fix: use pool for all sha256 hash operations

This commit is contained in:
Richard Ramos 2023-03-02 11:53:10 -04:00 committed by RichΛrd
parent df2cccec04
commit b20bf3dccd
4 changed files with 32 additions and 22 deletions

View File

@ -1,9 +1,10 @@
package persistence
import (
"crypto/sha256"
"encoding/binary"
"errors"
"github.com/waku-org/go-waku/waku/v2/utils"
)
const (
@ -34,7 +35,7 @@ func (k *DBKey) Bytes() []byte {
// NewDBKey creates a new DBKey with the given values.
func NewDBKey(senderTimestamp uint64, receiverTimestamp uint64, pubsubTopic string, digest []byte) *DBKey {
pubSubHash := sha256.Sum256([]byte(pubsubTopic))
pubSubHash := utils.SHA256([]byte(pubsubTopic))
var k DBKey
k.raw = make([]byte, DBKeyLength)

View File

@ -1,10 +1,9 @@
package protocol
import (
"crypto/sha256"
wpb "github.com/waku-org/go-waku/waku/v2/protocol/pb"
"github.com/waku-org/go-waku/waku/v2/protocol/store/pb"
"github.com/waku-org/go-waku/waku/v2/utils"
)
// Envelope contains information about the pubsub topic of a WakuMessage
@ -22,7 +21,7 @@ type Envelope struct {
// as well as generating a hash based on the bytes that compose the message
func NewEnvelope(msg *wpb.WakuMessage, receiverTime int64, pubSubTopic string) *Envelope {
messageHash, dataLen, _ := msg.Hash()
hash := sha256.Sum256(append([]byte(msg.ContentTopic), msg.Payload...))
hash := utils.SHA256(append([]byte(msg.ContentTopic), msg.Payload...))
return &Envelope{
msg: msg,
size: dataLen,

View File

@ -2,11 +2,9 @@ package relay
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"hash"
"sync"
"github.com/libp2p/go-libp2p/core/host"
@ -24,6 +22,7 @@ import (
waku_proto "github.com/waku-org/go-waku/waku/v2/protocol"
"github.com/waku-org/go-waku/waku/v2/protocol/pb"
"github.com/waku-org/go-waku/waku/v2/timesource"
"github.com/waku-org/go-waku/waku/v2/utils"
)
const WakuRelayID_v200 = protocol.ID("/vac/waku/relay/2.0.0")
@ -52,22 +51,8 @@ type WakuRelay struct {
subscriptionsMutex sync.Mutex
}
var sha256Pool = sync.Pool{New: func() interface{} {
return sha256.New()
}}
func msgIdFn(pmsg *pubsub_pb.Message) string {
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[:])
return string(utils.SHA256(pmsg.Data))
}
// NewWakuRelay returns a new instance of a WakuRelay struct

25
waku/v2/utils/hash.go Normal file
View File

@ -0,0 +1,25 @@
package utils
import (
"crypto/sha256"
"hash"
"sync"
)
var sha256Pool = sync.Pool{New: func() interface{} {
return sha256.New()
}}
func SHA256(data []byte) []byte {
h, ok := sha256Pool.Get().(hash.Hash)
if !ok {
h = sha256.New()
}
defer sha256Pool.Put(h)
h.Reset()
var result [32]byte
h.Write(data)
h.Sum(result[:0])
return result[:]
}