@@ -3,7 +3,7 @@ import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
3
3
import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
4
4
import { sha256 } from 'multiformats/hashes/sha2'
5
5
import type { Message , PubSubRPCMessage } from '@libp2p/interface-pubsub'
6
- import { peerIdFromBytes } from '@libp2p/peer-id'
6
+ import { peerIdFromBytes , peerIdFromKeys } from '@libp2p/peer-id'
7
7
import { codes } from './errors.js'
8
8
import { CodeError } from '@libp2p/interfaces/errors'
9
9
@@ -66,12 +66,30 @@ export const ensureArray = function <T> (maybeArray: T | T[]) {
66
66
return maybeArray
67
67
}
68
68
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 > => {
70
88
if ( message . from == null ) {
71
89
throw new CodeError ( 'RPC message was missing from' , codes . ERR_MISSING_FROM )
72
90
}
73
91
74
- if ( message . sequenceNumber == null || message . from == null || message . signature == null || message . key == null ) {
92
+ if ( ! await isSigned ( message ) ) {
75
93
return {
76
94
type : 'unsigned' ,
77
95
topic : message . topic ?? '' ,
@@ -83,9 +101,10 @@ export const toMessage = (message: PubSubRPCMessage): Message => {
83
101
type : 'signed' ,
84
102
from : peerIdFromBytes ( message . from ) ,
85
103
topic : message . topic ?? '' ,
86
- sequenceNumber : bigIntFromBytes ( message . sequenceNumber ) ,
104
+ sequenceNumber : bigIntFromBytes ( message . sequenceNumber ?? new Uint8Array ( 0 ) ) ,
87
105
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
89
108
key : message . key
90
109
}
91
110
}
0 commit comments