2023-04-05 21:03:29 +00:00
package relay
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"encoding/hex"
2023-05-03 15:59:47 +00:00
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/crypto/secp256k1"
2023-04-05 21:03:29 +00:00
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/waku-org/go-waku/waku/v2/hash"
"github.com/waku-org/go-waku/waku/v2/protocol/pb"
"go.uber.org/zap"
proto "google.golang.org/protobuf/proto"
)
// Application level message hash
func MsgHash ( pubSubTopic string , msg * pb . WakuMessage ) [ ] byte {
// TODO: Other fields?
return hash . SHA256 ( [ ] byte ( pubSubTopic ) , msg . Payload , [ ] byte ( msg . ContentTopic ) )
}
2023-05-02 15:10:45 +00:00
type validatorFn = func ( ctx context . Context , peerID peer . ID , message * pubsub . Message ) bool
func validatorFnBuilder ( topic string , publicKey * ecdsa . PublicKey ) validatorFn {
2023-05-03 15:59:47 +00:00
pubkBytes := crypto . FromECDSAPub ( publicKey )
2023-05-02 15:10:45 +00:00
return func ( ctx context . Context , peerID peer . ID , message * pubsub . Message ) bool {
2023-04-05 21:03:29 +00:00
msg := new ( pb . WakuMessage )
err := proto . Unmarshal ( message . Data , msg )
if err != nil {
return false
}
msgHash := MsgHash ( topic , msg )
signature := msg . Meta
2023-05-03 15:59:47 +00:00
return secp256k1 . VerifySignature ( pubkBytes , msgHash , signature )
2023-05-02 15:10:45 +00:00
}
}
func ( w * WakuRelay ) AddSignedTopicValidator ( topic string , publicKey * ecdsa . PublicKey ) error {
w . log . Info ( "adding validator to signed topic" , zap . String ( "topic" , topic ) , zap . String ( "publicKey" , hex . EncodeToString ( elliptic . Marshal ( publicKey . Curve , publicKey . X , publicKey . Y ) ) ) )
err := w . pubsub . RegisterTopicValidator ( topic , validatorFnBuilder ( topic , publicKey ) )
2023-05-04 14:04:54 +00:00
if err != nil {
return err
}
if ! w . IsSubscribed ( topic ) {
w . log . Warn ( "relay is not subscribed to signed topic" , zap . String ( "topic" , topic ) )
}
return nil
2023-04-05 21:03:29 +00:00
}
2023-05-02 15:10:45 +00:00
func SignMessage ( privKey * ecdsa . PrivateKey , topic string , msg * pb . WakuMessage ) error {
2023-04-05 21:03:29 +00:00
msgHash := MsgHash ( topic , msg )
2023-05-03 15:59:47 +00:00
sign , err := secp256k1 . Sign ( msgHash , crypto . FromECDSA ( privKey ) )
2023-04-05 21:03:29 +00:00
if err != nil {
return err
}
2023-05-03 15:59:47 +00:00
msg . Meta = sign [ 0 : 64 ] // Drop the V in R||S||V
2023-04-05 21:03:29 +00:00
return nil
}