fix: use sync.Pool for msgId hasher

This commit is contained in:
Richard Ramos 2023-03-02 09:53:06 -04:00 committed by RichΛrd
parent 93e8b34c1a
commit df2cccec04
2 changed files with 31 additions and 2 deletions

View File

@ -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

View File

@ -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))
}