From df2cccec04caf0b0807ee9718cbac21d9b41ea6d Mon Sep 17 00:00:00 2001 From: Richard Ramos Date: Thu, 2 Mar 2023 09:53:06 -0400 Subject: [PATCH] fix: use sync.Pool for msgId hasher --- waku/v2/protocol/relay/waku_relay.go | 18 ++++++++++++++++-- waku/v2/protocol/relay/waku_relay_test.go | 15 +++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/waku/v2/protocol/relay/waku_relay.go b/waku/v2/protocol/relay/waku_relay.go index d773edc1..c3154e7d 100644 --- a/waku/v2/protocol/relay/waku_relay.go +++ b/waku/v2/protocol/relay/waku_relay.go @@ -6,6 +6,7 @@ import ( "encoding/hex" "errors" "fmt" + "hash" "sync" "github.com/libp2p/go-libp2p/core/host" @@ -51,9 +52,22 @@ type WakuRelay struct { subscriptionsMutex sync.Mutex } +var sha256Pool = sync.Pool{New: func() interface{} { + return sha256.New() +}} + func msgIdFn(pmsg *pubsub_pb.Message) string { - hash := sha256.Sum256(pmsg.Data) - return string(hash[:]) + h, ok := sha256Pool.Get().(hash.Hash) + if !ok { + h = sha256.New() + } + defer sha256Pool.Put(h) + h.Reset() + + var result [32]byte + h.Write(pmsg.Data) + h.Sum(result[:0]) + return string(result[:]) } // NewWakuRelay returns a new instance of a WakuRelay struct diff --git a/waku/v2/protocol/relay/waku_relay_test.go b/waku/v2/protocol/relay/waku_relay_test.go index cbfce0bd..08eac0fd 100644 --- a/waku/v2/protocol/relay/waku_relay_test.go +++ b/waku/v2/protocol/relay/waku_relay_test.go @@ -5,6 +5,7 @@ import ( "crypto/rand" "testing" + pubsub_pb "github.com/libp2p/go-libp2p-pubsub/pb" "github.com/stretchr/testify/require" "github.com/waku-org/go-waku/tests" "github.com/waku-org/go-waku/waku/v2/protocol/pb" @@ -53,3 +54,17 @@ func TestWakuRelay(t *testing.T) { <-ctx.Done() } + +func TestMsgID(t *testing.T) { + expectedMsgIdBytes := []byte{208, 214, 63, 55, 144, 6, 206, 39, 40, 251, 138, 74, 66, 168, 43, 32, 91, 94, 149, 122, 237, 198, 149, 87, 232, 156, 197, 34, 53, 131, 78, 112} + + topic := "abcde" + msg := &pubsub_pb.Message{ + Data: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, + Topic: &topic, + } + + msgId := msgIdFn(msg) + + require.Equal(t, expectedMsgIdBytes, []byte(msgId)) +}