go-waku/waku/v2/protocol/rln/waku_rln_relay.go

441 lines
13 KiB
Go
Raw Normal View History

2022-07-05 21:28:34 +00:00
package rln
import (
"bytes"
"context"
"errors"
"math"
2022-10-09 15:54:20 +00:00
"sync"
2022-07-05 21:28:34 +00:00
"time"
2022-09-11 21:08:58 +00:00
"github.com/ethereum/go-ethereum/core/types"
2023-04-03 21:45:19 +00:00
"github.com/ethereum/go-ethereum/log"
2022-07-05 21:28:34 +00:00
pubsub "github.com/libp2p/go-libp2p-pubsub"
2022-10-19 19:39:32 +00:00
"github.com/libp2p/go-libp2p/core/peer"
"github.com/waku-org/go-waku/waku/v2/protocol/pb"
"github.com/waku-org/go-waku/waku/v2/protocol/relay"
2022-12-09 03:08:04 +00:00
"github.com/waku-org/go-waku/waku/v2/timesource"
r "github.com/waku-org/go-zerokit-rln/rln"
2022-07-05 21:28:34 +00:00
"go.uber.org/zap"
proto "google.golang.org/protobuf/proto"
2022-07-05 21:28:34 +00:00
)
2022-07-06 16:59:38 +00:00
// the maximum clock difference between peers in seconds
const MAX_CLOCK_GAP_SECONDS = 20
// maximum allowed gap between the epochs of messages' RateLimitProofs
const MAX_EPOCH_GAP = int64(MAX_CLOCK_GAP_SECONDS / r.EPOCH_UNIT_SECONDS)
2023-04-03 21:45:19 +00:00
// Acceptable roots for merkle root validation of incoming messages
const AcceptableRootWindowSize = 5
type AppInfo struct {
Application string
AppIdentifier string
Version string
}
2022-09-11 21:08:58 +00:00
type RegistrationHandler = func(tx *types.Transaction)
2023-04-03 21:45:19 +00:00
type SpamHandler = func(message *pb.WakuMessage) error
var RLNAppInfo = AppInfo{
Application: "go-waku-rln-relay",
AppIdentifier: "01234567890abcdef",
Version: "0.1",
}
type GroupManager interface {
Start(ctx context.Context, rln *r.RLN) error
GenerateProof(input []byte, epoch r.Epoch) (*r.RateLimitProof, error)
VerifyProof(input []byte, msgProof *r.RateLimitProof, ValidMerkleRoots ...r.MerkleNode) (bool, error)
Stop()
}
2022-10-21 19:49:55 +00:00
2022-07-05 21:28:34 +00:00
type WakuRLNRelay struct {
2022-12-09 03:08:04 +00:00
timesource timesource.Timesource
2022-07-28 14:04:33 +00:00
2023-04-03 21:45:19 +00:00
groupManager GroupManager
2022-07-05 21:28:34 +00:00
2023-04-03 21:45:19 +00:00
// pubsubTopic is the topic for which rln relay is mounted
pubsubTopic string
contentTopic string
relay *relay.WakuRelay
spamHandler SpamHandler
2022-08-18 16:27:10 +00:00
RLN *r.RLN
2022-10-09 15:54:20 +00:00
2022-10-21 19:49:55 +00:00
validMerkleRoots []r.MerkleNode
2022-07-05 21:28:34 +00:00
// the log of nullifiers and Shamir shares of the past messages grouped per epoch
2022-10-09 15:54:20 +00:00
nullifierLogLock sync.RWMutex
2023-04-03 21:45:19 +00:00
nullifierLog map[r.Nullifier][]r.ProofMetadata
2022-07-05 21:28:34 +00:00
2023-04-03 21:45:19 +00:00
log *zap.Logger
2022-07-05 21:28:34 +00:00
}
2023-04-03 21:45:19 +00:00
func New(
relay *relay.WakuRelay,
groupManager GroupManager,
pubsubTopic string,
contentTopic string,
spamHandler SpamHandler,
timesource timesource.Timesource,
log *zap.Logger) (*WakuRLNRelay, error) {
rlnInstance, err := r.NewRLN()
if err != nil {
return nil, err
2022-08-18 16:27:10 +00:00
}
2023-04-03 21:45:19 +00:00
// create the WakuRLNRelay
rlnPeer := &WakuRLNRelay{
RLN: rlnInstance,
groupManager: groupManager,
pubsubTopic: pubsubTopic,
contentTopic: contentTopic,
relay: relay,
spamHandler: spamHandler,
log: log,
timesource: timesource,
nullifierLog: make(map[r.MerkleNode][]r.ProofMetadata),
}
2022-07-05 21:28:34 +00:00
2023-04-03 21:45:19 +00:00
// TODO: pass RLN to group manager
root, err := rlnPeer.RLN.GetMerkleRoot()
if err != nil {
return nil, err
2022-07-05 21:28:34 +00:00
}
2023-04-03 21:45:19 +00:00
rlnPeer.validMerkleRoots = append(rlnPeer.validMerkleRoots, root)
2022-07-05 21:28:34 +00:00
2023-04-03 21:45:19 +00:00
return rlnPeer, nil
}
func (rln *WakuRLNRelay) Start(ctx context.Context) error {
err := rln.groupManager.Start(ctx, rln.RLN)
2022-07-05 21:28:34 +00:00
if err != nil {
2023-04-03 21:45:19 +00:00
return err
}
root, err := rln.RLN.GetMerkleRoot()
if err != nil {
return err
2022-07-05 21:28:34 +00:00
}
2023-04-03 21:45:19 +00:00
rln.validMerkleRoots = append(rln.validMerkleRoots, root)
// adds a topic validator for the supplied pubsub topic at the relay protocol
// messages published on this pubsub topic will be relayed upon a successful validation, otherwise they will be dropped
// the topic validator checks for the correct non-spamming proof of the message
err = rln.addValidator(rln.relay, rln.pubsubTopic, rln.contentTopic, rln.spamHandler)
if err != nil {
return err
2022-07-05 21:28:34 +00:00
}
2023-04-03 21:45:19 +00:00
log.Info("rln relay topic validator mounted", zap.String("pubsubTopic", rln.pubsubTopic), zap.String("contentTopic", rln.contentTopic))
2022-07-05 21:28:34 +00:00
2023-04-03 21:45:19 +00:00
return nil
2022-07-05 21:28:34 +00:00
}
2023-04-03 21:45:19 +00:00
func (rln *WakuRLNRelay) Stop() {
rln.groupManager.Stop()
}
func (rln *WakuRLNRelay) HasDuplicate(proofMD r.ProofMetadata) (bool, error) {
2022-07-05 21:28:34 +00:00
// returns true if there is another message in the `nullifierLog` of the `rlnPeer` with the same
// epoch and nullifier as `msg`'s epoch and nullifier but different Shamir secret shares
// otherwise, returns false
2022-10-09 15:54:20 +00:00
rln.nullifierLogLock.RLock()
2023-04-03 21:45:19 +00:00
proofs, ok := rln.nullifierLog[proofMD.ExternalNullifier]
2022-10-09 15:54:20 +00:00
rln.nullifierLogLock.RUnlock()
2022-07-05 21:28:34 +00:00
// check if the epoch exists
if !ok {
return false, nil
}
for _, p := range proofs {
if p.Equals(proofMD) {
// there is an identical record, ignore rhe mag
return false, nil
}
}
// check for a message with the same nullifier but different secret shares
matched := false
for _, it := range proofs {
if bytes.Equal(it.Nullifier[:], proofMD.Nullifier[:]) && (!bytes.Equal(it.ShareX[:], proofMD.ShareX[:]) || !bytes.Equal(it.ShareY[:], proofMD.ShareY[:])) {
matched = true
break
}
}
return matched, nil
}
2023-04-03 21:45:19 +00:00
func (rln *WakuRLNRelay) updateLog(proofMD r.ProofMetadata) (bool, error) {
2022-10-09 15:54:20 +00:00
rln.nullifierLogLock.Lock()
defer rln.nullifierLogLock.Unlock()
2023-04-03 21:45:19 +00:00
proofs, ok := rln.nullifierLog[proofMD.ExternalNullifier]
2022-07-05 21:28:34 +00:00
// check if the epoch exists
if !ok {
2023-04-03 21:45:19 +00:00
rln.nullifierLog[proofMD.ExternalNullifier] = []r.ProofMetadata{proofMD}
2022-07-05 21:28:34 +00:00
return true, nil
}
// check if an identical record exists
for _, p := range proofs {
if p.Equals(proofMD) {
2023-04-03 21:45:19 +00:00
// TODO: slashing logic
2022-07-05 21:28:34 +00:00
return true, nil
}
}
// add proofMD to the log
proofs = append(proofs, proofMD)
2023-04-03 21:45:19 +00:00
rln.nullifierLog[proofMD.ExternalNullifier] = proofs
2022-07-05 21:28:34 +00:00
return true, nil
}
2022-07-06 16:59:38 +00:00
func (rln *WakuRLNRelay) ValidateMessage(msg *pb.WakuMessage, optionalTime *time.Time) (MessageValidationResult, error) {
2022-07-05 21:28:34 +00:00
// validate the supplied `msg` based on the waku-rln-relay routing protocol i.e.,
// the `msg`'s epoch is within MAX_EPOCH_GAP of the current epoch
// the `msg` has valid rate limit proof
// the `msg` does not violate the rate limit
// `timeOption` indicates Unix epoch time (fractional part holds sub-seconds)
// if `timeOption` is supplied, then the current epoch is calculated based on that
if msg == nil {
return MessageValidationResult_Unknown, errors.New("nil message")
}
// checks if the `msg`'s epoch is far from the current epoch
// it corresponds to the validation of rln external nullifier
var epoch r.Epoch
if optionalTime != nil {
epoch = r.CalcEpoch(*optionalTime)
} else {
// get current rln epoch
2022-12-09 03:08:04 +00:00
epoch = r.CalcEpoch(rln.timesource.Now())
2022-07-05 21:28:34 +00:00
}
msgProof := ToRateLimitProof(msg)
2022-07-06 16:59:38 +00:00
if msgProof == nil {
// message does not contain a proof
rln.log.Debug("invalid message: message does not contain a proof")
return MessageValidationResult_Invalid, nil
}
2022-07-05 21:28:34 +00:00
2023-04-03 21:45:19 +00:00
proofMD, err := r.ExtractMetadata(*msgProof)
if err != nil {
rln.log.Debug("could not extract metadata", zap.Error(err))
return MessageValidationResult_Invalid, nil
}
2022-07-06 16:59:38 +00:00
// calculate the gaps and validate the epoch
2022-07-05 21:28:34 +00:00
gap := r.Diff(epoch, msgProof.Epoch)
2022-10-10 22:08:35 +00:00
if int64(math.Abs(float64(gap))) > MAX_EPOCH_GAP {
2022-07-05 21:28:34 +00:00
// message's epoch is too old or too ahead
// accept messages whose epoch is within +-MAX_EPOCH_GAP from the current epoch
2022-07-06 16:59:38 +00:00
rln.log.Debug("invalid message: epoch gap exceeds a threshold", zap.Int64("gap", gap))
2022-07-05 21:28:34 +00:00
return MessageValidationResult_Invalid, nil
}
// verify the proof
contentTopicBytes := []byte(msg.ContentTopic)
input := append(msg.Payload, contentTopicBytes...)
2022-10-07 22:58:16 +00:00
2023-04-03 21:45:19 +00:00
valid, err := rln.groupManager.VerifyProof(input, msgProof, rln.validMerkleRoots...)
2022-10-07 22:58:16 +00:00
if err != nil {
rln.log.Debug("could not verify proof", zap.Error(err))
return MessageValidationResult_Invalid, nil
}
if !valid {
2022-07-05 21:28:34 +00:00
// invalid proof
2022-10-07 22:58:16 +00:00
rln.log.Debug("Invalid proof")
2022-07-05 21:28:34 +00:00
return MessageValidationResult_Invalid, nil
}
// check if double messaging has happened
2023-04-03 21:45:19 +00:00
hasDup, err := rln.HasDuplicate(proofMD)
2022-07-05 21:28:34 +00:00
if err != nil {
2022-07-06 16:59:38 +00:00
rln.log.Debug("validation error", zap.Error(err))
2022-07-05 21:28:34 +00:00
return MessageValidationResult_Unknown, err
}
if hasDup {
2022-07-06 16:59:38 +00:00
rln.log.Debug("spam received")
2022-07-05 21:28:34 +00:00
return MessageValidationResult_Spam, nil
}
// insert the message to the log
// the result of `updateLog` is discarded because message insertion is guaranteed by the implementation i.e.,
// it will never error out
2023-04-03 21:45:19 +00:00
_, err = rln.updateLog(proofMD)
2022-07-05 21:28:34 +00:00
if err != nil {
return MessageValidationResult_Unknown, err
}
2022-07-06 16:59:38 +00:00
rln.log.Debug("message is valid")
2022-07-05 21:28:34 +00:00
return MessageValidationResult_Valid, nil
}
2022-07-06 16:59:38 +00:00
func (rln *WakuRLNRelay) AppendRLNProof(msg *pb.WakuMessage, senderEpochTime time.Time) error {
2022-07-05 21:28:34 +00:00
// returns error if it could not create and append a `RateLimitProof` to the supplied `msg`
// `senderEpochTime` indicates the number of seconds passed since Unix epoch. The fractional part holds sub-seconds.
// The `epoch` field of `RateLimitProof` is derived from the provided `senderEpochTime` (using `calcEpoch()`)
if msg == nil {
return errors.New("nil message")
}
input := toRLNSignal(msg)
2023-04-03 21:45:19 +00:00
proof, err := rln.groupManager.GenerateProof(input, r.CalcEpoch(senderEpochTime))
2022-07-05 21:28:34 +00:00
if err != nil {
return err
}
msg.RateLimitProof = &pb.RateLimitProof{
2022-10-04 23:15:39 +00:00
Proof: proof.Proof[:],
MerkleRoot: proof.MerkleRoot[:],
Epoch: proof.Epoch[:],
ShareX: proof.ShareX[:],
ShareY: proof.ShareY[:],
Nullifier: proof.Nullifier[:],
RlnIdentifier: proof.RLNIdentifier[:],
2022-07-05 21:28:34 +00:00
}
return nil
}
2023-04-03 21:45:19 +00:00
func (r *WakuRLNRelay) insertMember(pubkey r.IDCommitment) error { // TODO: move to group manager? #########################################################
2022-10-21 19:49:55 +00:00
r.log.Debug("a new key is added", zap.Binary("pubkey", pubkey[:]))
// assuming all the members arrive in order
err := r.RLN.InsertMember(pubkey)
if err == nil {
newRoot, err := r.RLN.GetMerkleRoot()
if err != nil {
r.log.Error("inserting member into merkletree", zap.Error(err))
return err
}
r.validMerkleRoots = append(r.validMerkleRoots, newRoot)
if len(r.validMerkleRoots) > AcceptableRootWindowSize {
r.validMerkleRoots = r.validMerkleRoots[1:]
}
}
return err
}
2022-07-05 21:28:34 +00:00
// this function sets a validator for the waku messages published on the supplied pubsubTopic and contentTopic
// if contentTopic is empty, then validation takes place for All the messages published on the given pubsubTopic
// the message validation logic is according to https://rfc.vac.dev/spec/17/
func (r *WakuRLNRelay) addValidator(
relay *relay.WakuRelay,
pubsubTopic string,
contentTopic string,
2022-07-06 20:29:20 +00:00
spamHandler SpamHandler) error {
2022-07-05 21:28:34 +00:00
validator := func(ctx context.Context, peerID peer.ID, message *pubsub.Message) bool {
r.log.Debug("rln-relay topic validator called")
wakuMessage := &pb.WakuMessage{}
if err := proto.Unmarshal(message.Data, wakuMessage); err != nil {
r.log.Debug("could not unmarshal message")
return true
}
// check the contentTopic
if (wakuMessage.ContentTopic != "") && (contentTopic != "") && (wakuMessage.ContentTopic != contentTopic) {
r.log.Debug("content topic did not match", zap.String("contentTopic", contentTopic))
return true
}
// validate the message
validationRes, err := r.ValidateMessage(wakuMessage, nil)
if err != nil {
r.log.Debug("validating message", zap.Error(err))
return false
}
switch validationRes {
case MessageValidationResult_Valid:
r.log.Debug("message verified",
zap.String("contentTopic", wakuMessage.ContentTopic),
zap.Binary("epoch", wakuMessage.RateLimitProof.Epoch),
zap.Int("timestamp", int(wakuMessage.Timestamp)),
zap.Binary("payload", wakuMessage.Payload),
2022-08-04 21:39:12 +00:00
zap.Any("proof", wakuMessage.RateLimitProof),
2022-07-05 21:28:34 +00:00
)
relay.AddToCache(pubsubTopic, message.ID, wakuMessage)
2022-07-05 21:28:34 +00:00
return true
case MessageValidationResult_Invalid:
r.log.Debug("message could not be verified",
zap.String("contentTopic", wakuMessage.ContentTopic),
zap.Binary("epoch", wakuMessage.RateLimitProof.Epoch),
zap.Int("timestamp", int(wakuMessage.Timestamp)),
zap.Binary("payload", wakuMessage.Payload),
2022-08-04 21:39:12 +00:00
zap.Any("proof", wakuMessage.RateLimitProof),
2022-07-05 21:28:34 +00:00
)
2022-10-04 23:15:39 +00:00
return false
2022-07-05 21:28:34 +00:00
case MessageValidationResult_Spam:
r.log.Debug("spam message found",
zap.String("contentTopic", wakuMessage.ContentTopic),
zap.Binary("epoch", wakuMessage.RateLimitProof.Epoch),
zap.Int("timestamp", int(wakuMessage.Timestamp)),
zap.Binary("payload", wakuMessage.Payload),
2022-08-04 21:39:12 +00:00
zap.Any("proof", wakuMessage.RateLimitProof),
2022-07-05 21:28:34 +00:00
)
if spamHandler != nil {
if err := spamHandler(wakuMessage); err != nil {
r.log.Error("executing spam handler", zap.Error(err))
}
}
return false
default:
r.log.Debug("unhandled validation result", zap.Int("validationResult", int(validationRes)))
return false
}
}
// In case there's a topic validator registered
_ = relay.PubSub().UnregisterTopicValidator(pubsubTopic)
2022-07-06 20:29:20 +00:00
return relay.PubSub().RegisterTopicValidator(pubsubTopic, validator)
2022-07-05 21:28:34 +00:00
}
func toRLNSignal(wakuMessage *pb.WakuMessage) []byte {
if wakuMessage == nil {
return []byte{}
}
contentTopicBytes := []byte(wakuMessage.ContentTopic)
return append(wakuMessage.Payload, contentTopicBytes...)
}
func ToRateLimitProof(msg *pb.WakuMessage) *r.RateLimitProof {
2022-07-06 16:59:38 +00:00
if msg == nil || msg.RateLimitProof == nil {
2022-07-05 21:28:34 +00:00
return nil
}
result := &r.RateLimitProof{
2022-10-05 22:08:01 +00:00
Proof: r.ZKSNARK(r.Bytes128(msg.RateLimitProof.Proof)),
MerkleRoot: r.MerkleNode(r.Bytes32(msg.RateLimitProof.MerkleRoot)),
Epoch: r.Epoch(r.Bytes32(msg.RateLimitProof.Epoch)),
ShareX: r.MerkleNode(r.Bytes32(msg.RateLimitProof.ShareX)),
ShareY: r.MerkleNode(r.Bytes32(msg.RateLimitProof.ShareY)),
Nullifier: r.Nullifier(r.Bytes32(msg.RateLimitProof.Nullifier)),
RLNIdentifier: r.RLNIdentifier(r.Bytes32(msg.RateLimitProof.RlnIdentifier)),
2022-07-05 21:28:34 +00:00
}
return result
}