Skip to content

Commit 21d9215

Browse files
authored
Do not use go-ethereum for hasher. (#159)
1 parent cd0c2a3 commit 21d9215

File tree

3 files changed

+50
-6
lines changed

3 files changed

+50
-6
lines changed

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ require (
6262
github.com/lib/pq v1.10.9
6363
github.com/redis/go-redis/v9 v9.0.4
6464
github.com/testcontainers/testcontainers-go/modules/postgres v0.39.0
65+
golang.org/x/crypto v0.41.0
6566
)
6667

6768
require (
@@ -308,7 +309,6 @@ require (
308309
go.uber.org/multierr v1.11.0 // indirect
309310
go.uber.org/ratelimit v0.3.1 // indirect
310311
golang.org/x/arch v0.8.0 // indirect
311-
golang.org/x/crypto v0.41.0 // indirect
312312
golang.org/x/net v0.43.0 // indirect
313313
golang.org/x/sys v0.36.0 // indirect
314314
golang.org/x/term v0.34.0 // indirect

protocol/hashing.go

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,30 @@
11
package protocol
22

3-
import "github.com/ethereum/go-ethereum/crypto"
3+
import (
4+
"hash"
5+
"sync"
6+
7+
"golang.org/x/crypto/sha3"
8+
)
9+
10+
var hasherPool = sync.Pool{
11+
New: func() any {
12+
return sha3.NewLegacyKeccak256()
13+
},
14+
}
415

516
// Keccak256 computes the Keccak256 hash of the input.
617
func Keccak256(data []byte) [32]byte {
7-
hash := crypto.Keccak256(data)
8-
var result [32]byte
9-
copy(result[:], hash)
10-
return result
18+
h, ok := hasherPool.Get().(hash.Hash)
19+
if !ok {
20+
// This should never happen, but just in case.
21+
h = sha3.NewLegacyKeccak256()
22+
}
23+
24+
h.Reset()
25+
h.Write(data) //nolint // keccak256 never returns an error
26+
var out [32]byte
27+
copy(out[:], h.Sum(nil))
28+
hasherPool.Put(h)
29+
return out
1130
}

protocol/hashing_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package protocol
2+
3+
import (
4+
"testing"
5+
6+
"golang.org/x/crypto/sha3"
7+
)
8+
9+
var data = []byte("The quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dog")
10+
11+
func BenchmarkHashing(b *testing.B) {
12+
for i := 0; i < b.N; i++ {
13+
Keccak256(data)
14+
}
15+
}
16+
17+
func BenchmarkHashinbBaseline(b *testing.B) {
18+
for i := 0; i < b.N; i++ {
19+
h := sha3.NewLegacyKeccak256()
20+
h.Write(data)
21+
var out [32]byte
22+
copy(out[:], h.Sum(nil))
23+
hasherPool.Put(h)
24+
}
25+
}

0 commit comments

Comments
 (0)