Skip to content

Commit

Permalink
Use pool for keccak (#1407)
Browse files Browse the repository at this point in the history
  • Loading branch information
cffls authored Jan 21, 2025
1 parent 0d1b857 commit a153663
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions crypto/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"io"
"math/big"
"os"
"sync"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/math"
Expand Down Expand Up @@ -68,44 +69,58 @@ type KeccakState interface {
Read([]byte) (int, error)
}

// hasherPool holds LegacyKeccak256 hashers for reuse.
var hasherPool = sync.Pool{
New: func() interface{} { return sha3.NewLegacyKeccak256() },
}

// NewKeccakState creates a new KeccakState
func NewKeccakState() KeccakState {
return sha3.NewLegacyKeccak256().(KeccakState)
return hasherPool.Get().(KeccakState)
}

// PutKeccakState puts the KeccakState back into the pool.
// The state must not be used after calling this function.
func PutKeccakState(kh KeccakState) {
kh.Reset()
hasherPool.Put(kh)
}

// HashData hashes the provided data using the KeccakState and returns a 32 byte hash
func HashData(kh KeccakState, data []byte) (h common.Hash) {
kh.Reset()
kh.Write(data)
kh.Read(h[:])

return h
}

// Keccak256 calculates and returns the Keccak256 hash of the input data.
func Keccak256(data ...[]byte) []byte {
b := make([]byte, 32)
d := NewKeccakState()
defer PutKeccakState(d)
d.Reset()

for _, b := range data {
d.Write(b)
}

d.Read(b)

return b
}

// Keccak256Hash calculates and returns the Keccak256 hash of the input data,
// converting it to an internal Hash data structure.
func Keccak256Hash(data ...[]byte) (h common.Hash) {
d := NewKeccakState()
defer PutKeccakState(d)
d.Reset()

for _, b := range data {
d.Write(b)
}

d.Read(h[:])

return h
}

Expand Down

0 comments on commit a153663

Please sign in to comment.