@@ -3,7 +3,7 @@ import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
33import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
44import { sha256 } from 'multiformats/hashes/sha2'
55import type { Message , PubSubRPCMessage } from '@libp2p/interface-pubsub'
6- import { peerIdFromBytes } from '@libp2p/peer-id'
6+ import { peerIdFromBytes , peerIdFromKeys } from '@libp2p/peer-id'
77import { codes } from './errors.js'
88import { CodeError } from '@libp2p/interfaces/errors'
99
@@ -66,12 +66,30 @@ export const ensureArray = function <T> (maybeArray: T | T[]) {
6666 return maybeArray
6767}
6868
69- export const toMessage = ( message : PubSubRPCMessage ) : Message => {
69+ const isSigned = async ( message : PubSubRPCMessage ) : Promise < boolean > => {
70+ if ( ( message . sequenceNumber == null ) || ( message . from == null ) || ( message . signature == null ) ) {
71+ return false
72+ }
73+ // if a public key is present in the `from` field, the message should be signed
74+ const fromID = peerIdFromBytes ( message . from )
75+ if ( fromID . publicKey != null ) {
76+ return true
77+ }
78+
79+ if ( message . key != null ) {
80+ const signingID = await peerIdFromKeys ( message . key )
81+ return signingID . equals ( fromID )
82+ }
83+
84+ return false
85+ }
86+
87+ export const toMessage = async ( message : PubSubRPCMessage ) : Promise < Message > => {
7088 if ( message . from == null ) {
7189 throw new CodeError ( 'RPC message was missing from' , codes . ERR_MISSING_FROM )
7290 }
7391
74- if ( message . sequenceNumber == null || message . from == null || message . signature == null || message . key == null ) {
92+ if ( ! await isSigned ( message ) ) {
7593 return {
7694 type : 'unsigned' ,
7795 topic : message . topic ?? '' ,
@@ -83,9 +101,10 @@ export const toMessage = (message: PubSubRPCMessage): Message => {
83101 type : 'signed' ,
84102 from : peerIdFromBytes ( message . from ) ,
85103 topic : message . topic ?? '' ,
86- sequenceNumber : bigIntFromBytes ( message . sequenceNumber ) ,
104+ sequenceNumber : bigIntFromBytes ( message . sequenceNumber ?? new Uint8Array ( 0 ) ) ,
87105 data : message . data ?? new Uint8Array ( 0 ) ,
88- signature : message . signature ,
106+ signature : message . signature ?? new Uint8Array ( 0 ) ,
107+ // @ts -expect-error key need not be defined
89108 key : message . key
90109 }
91110}
0 commit comments