Skip to content

Commit 3199f20

Browse files
Merge branch 'master' into pmikolajczyk/nit-3121-uncompressed-batch-size-limit
2 parents 6b74e98 + 1e983cb commit 3199f20

File tree

16 files changed

+169
-43
lines changed

16 files changed

+169
-43
lines changed

cmd/devp2p/internal/ethtest/snap.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -900,12 +900,16 @@ func (s *Suite) snapGetByteCodes(t *utesting.T, tc *byteCodesTest) error {
900900
// that the serving node is missing
901901
var (
902902
bytecodes = res.Codes
903+
hasher = crypto.NewKeccakState()
904+
hash = make([]byte, 32)
903905
codes = make([][]byte, len(req.Hashes))
904906
)
905907

906908
for i, j := 0, 0; i < len(bytecodes); i++ {
907909
// Find the next hash that we've been served, leaving misses with nils
908-
hash := crypto.Keccak256(bytecodes[i])
910+
hasher.Reset()
911+
hasher.Write(bytecodes[i])
912+
hasher.Read(hash)
909913

910914
for j < len(req.Hashes) && !bytes.Equal(hash, req.Hashes[j][:]) {
911915
j++
@@ -955,12 +959,16 @@ func (s *Suite) snapGetTrieNodes(t *utesting.T, tc *trieNodesTest) error {
955959

956960
// Cross reference the requested trienodes with the response to find gaps
957961
// that the serving node is missing
962+
hasher := crypto.NewKeccakState()
963+
hash := make([]byte, 32)
958964
trienodes := res.Nodes
959965
if got, want := len(trienodes), len(tc.expHashes); got != want {
960966
return fmt.Errorf("wrong trienode count, got %d, want %d", got, want)
961967
}
962968
for i, trienode := range trienodes {
963-
hash := crypto.Keccak256(trienode[:])
969+
hasher.Reset()
970+
hasher.Write(trienode)
971+
hasher.Read(hash)
964972
if got, want := hash, tc.expHashes[i]; !bytes.Equal(got, want[:]) {
965973
t.Logf(" hash %d wrong, got %#x, want %#x\n", i, got, want)
966974
err = fmt.Errorf("hash %d wrong, got %#x, want %#x", i, got, want)

cmd/geth/dbcmd.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,8 @@ func checkStateContent(ctx *cli.Context) error {
354354
defer db.Close()
355355
var (
356356
it = rawdb.NewKeyLengthIterator(db.NewIterator(prefix, start), 32)
357+
hasher = crypto.NewKeccakState()
358+
got = make([]byte, 32)
357359
errs int
358360
count int
359361
startTime = time.Now()
@@ -363,7 +365,9 @@ func checkStateContent(ctx *cli.Context) error {
363365
count++
364366
k := it.Key()
365367
v := it.Value()
366-
got := crypto.Keccak256(v)
368+
hasher.Reset()
369+
hasher.Write(v)
370+
hasher.Read(got)
367371
if !bytes.Equal(k, got) {
368372
errs++
369373
fmt.Printf("Error at %#x\n", k)

cmd/geth/snapshot.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -434,6 +434,8 @@ func traverseRawState(ctx *cli.Context) error {
434434
codes int
435435
lastReport time.Time
436436
start = time.Now()
437+
hasher = crypto.NewKeccakState()
438+
got = make([]byte, 32)
437439
)
438440
accIter, err := t.NodeIterator(nil)
439441
if err != nil {
@@ -457,7 +459,9 @@ func traverseRawState(ctx *cli.Context) error {
457459
log.Error("Missing trie node(account)", "hash", node)
458460
return errors.New("missing account")
459461
}
460-
got := crypto.Keccak256(blob)
462+
hasher.Reset()
463+
hasher.Write(blob)
464+
hasher.Read(got)
461465
if !bytes.Equal(got, node.Bytes()) {
462466
log.Error("Invalid trie node(account)", "hash", node.Hex(), "value", blob)
463467
return errors.New("invalid account node")
@@ -496,7 +500,9 @@ func traverseRawState(ctx *cli.Context) error {
496500
log.Error("Missing trie node(storage)", "hash", node)
497501
return errors.New("missing storage")
498502
}
499-
got := crypto.Keccak256(blob)
503+
hasher.Reset()
504+
hasher.Write(blob)
505+
hasher.Read(got)
500506
if !bytes.Equal(got, node.Bytes()) {
501507
log.Error("Invalid trie node(storage)", "hash", node.Hex(), "value", blob)
502508
return errors.New("invalid storage node")

cmd/workload/historytestgen.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,8 +132,9 @@ func generateHistoryTests(clictx *cli.Context) error {
132132
}
133133

134134
func calcReceiptsHash(rcpt []*types.Receipt) common.Hash {
135-
encoded, _ := rlp.EncodeToBytes(rcpt)
136-
return crypto.Keccak256Hash(encoded)
135+
h := crypto.NewKeccakState()
136+
rlp.Encode(h, rcpt)
137+
return common.Hash(h.Sum(nil))
137138
}
138139

139140
func writeJSON(fileName string, value any) {

core/stateless/database.go

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,21 +34,33 @@ import (
3434
//
3535
// Acceleration structures built would need to explicitly validate the witness.
3636
func (w *Witness) MakeHashDB() ethdb.Database {
37-
var memdb = rawdb.NewMemoryDatabase()
37+
var (
38+
memdb = rawdb.NewMemoryDatabase()
39+
hasher = crypto.NewKeccakState()
40+
hash = make([]byte, 32)
41+
)
3842
// Inject all the "block hashes" (i.e. headers) into the ephemeral database
3943
for _, header := range w.Headers {
4044
rawdb.WriteHeader(memdb, header)
4145
}
4246
// Inject all the bytecodes into the ephemeral database
4347
for code := range w.Codes {
4448
blob := []byte(code)
45-
hash := crypto.Keccak256(blob)
49+
50+
hasher.Reset()
51+
hasher.Write(blob)
52+
hasher.Read(hash)
53+
4654
rawdb.WriteCode(memdb, common.BytesToHash(hash), blob)
4755
}
4856
// Inject all the MPT trie nodes into the ephemeral database
4957
for node := range w.State {
5058
blob := []byte(node)
51-
hash := crypto.Keccak256(blob)
59+
60+
hasher.Reset()
61+
hasher.Write(blob)
62+
hasher.Read(hash)
63+
5264
rawdb.WriteLegacyTrieNode(memdb, common.BytesToHash(hash), blob)
5365
}
5466
return memdb

core/types/bloom9.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,8 +141,11 @@ func Bloom9(data []byte) []byte {
141141

142142
// bloomValues returns the bytes (index-value pairs) to set for the given data
143143
func bloomValues(data []byte, hashbuf *[6]byte) (uint, byte, uint, byte, uint, byte) {
144-
hash := crypto.Keccak256(data)
145-
copy(hashbuf[:], hash[:6])
144+
sha := hasherPool.Get().(crypto.KeccakState)
145+
sha.Reset()
146+
sha.Write(data)
147+
sha.Read(hashbuf[:])
148+
hasherPool.Put(sha)
146149
// The actual bits to flip
147150
v1 := byte(1 << (hashbuf[1] & 0x7))
148151
v2 := byte(1 << (hashbuf[3] & 0x7))

core/types/hashing.go

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,11 @@ import (
2727
"github.com/ethereum/go-ethereum/rlp"
2828
)
2929

30+
// hasherPool holds LegacyKeccak256 buffer for rlpHash.
31+
var hasherPool = sync.Pool{
32+
New: func() interface{} { return crypto.NewKeccakState() },
33+
}
34+
3035
// encodeBufferPool holds temporary encoder buffers for DeriveSha and TX encoding.
3136
var encodeBufferPool = sync.Pool{
3237
New: func() interface{} { return new(bytes.Buffer) },
@@ -50,15 +55,24 @@ func getPooledBuffer(size uint64) ([]byte, *bytes.Buffer, error) {
5055

5156
// rlpHash encodes x and hashes the encoded bytes.
5257
func rlpHash(x interface{}) (h common.Hash) {
53-
encoded, _ := rlp.EncodeToBytes(x)
54-
return crypto.Keccak256Hash(encoded)
58+
sha := hasherPool.Get().(crypto.KeccakState)
59+
defer hasherPool.Put(sha)
60+
sha.Reset()
61+
rlp.Encode(sha, x)
62+
sha.Read(h[:])
63+
return h
5564
}
5665

5766
// prefixedRlpHash writes the prefix into the hasher before rlp-encoding x.
5867
// It's used for typed transactions.
5968
func prefixedRlpHash(prefix byte, x interface{}) (h common.Hash) {
60-
encoded, _ := rlp.EncodeToBytes(x)
61-
return crypto.Keccak256Hash([]byte{prefix}, encoded)
69+
sha := hasherPool.Get().(crypto.KeccakState)
70+
defer hasherPool.Put(sha)
71+
sha.Reset()
72+
sha.Write([]byte{prefix})
73+
rlp.Encode(sha, x)
74+
sha.Read(h[:])
75+
return h
6276
}
6377

6478
// ListHasher defines the interface for computing the hash of a derivable list.

core/vm/evm.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,9 @@ type EVM struct {
133133
// jumpDests stores results of JUMPDEST analysis.
134134
jumpDests JumpDestCache
135135

136+
hasher crypto.KeccakState // Keccak256 hasher instance shared across opcodes
137+
hasherBuf common.Hash // Keccak256 hasher result array shared across opcodes
138+
136139
readOnly bool // Whether to throw on stateful modifications
137140
returnData []byte // Last CALL's return data for subsequent reuse
138141
}
@@ -149,6 +152,7 @@ func NewEVM(blockCtx BlockContext, statedb StateDB, chainConfig *params.ChainCon
149152
chainConfig: chainConfig,
150153
chainRules: chainConfig.Rules(blockCtx.BlockNumber, blockCtx.Random != nil, blockCtx.Time, blockCtx.ArbOSVersion),
151154
jumpDests: newMapJumpDests(),
155+
hasher: crypto.NewKeccakState(),
152156
}
153157
evm.ProcessingHook = DefaultTxProcessor{evm: evm}
154158
evm.precompiles = activePrecompiledContracts(evm.chainRules)
@@ -699,7 +703,7 @@ func (evm *EVM) Create(caller common.Address, code []byte, gas uint64, value *ui
699703
// The different between Create2 with Create is Create2 uses keccak256(0xff ++ msg.sender ++ salt ++ keccak256(init_code))[12:]
700704
// instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
701705
func (evm *EVM) Create2(caller common.Address, code []byte, gas uint64, endowment *uint256.Int, salt *uint256.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, usedMultiGas multigas.MultiGas, err error) {
702-
inithash := crypto.Keccak256Hash(code)
706+
inithash := crypto.HashData(evm.hasher, code)
703707
contractAddr = crypto.CreateAddress2(caller, salt.Bytes32(), inithash[:])
704708
return evm.create(caller, code, gas, endowment, contractAddr, CREATE2)
705709
}

core/vm/instructions.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ import (
2525
"github.com/ethereum/go-ethereum/core/state"
2626
"github.com/ethereum/go-ethereum/core/tracing"
2727
"github.com/ethereum/go-ethereum/core/types"
28-
"github.com/ethereum/go-ethereum/crypto"
2928
"github.com/ethereum/go-ethereum/params"
3029
"github.com/holiman/uint256"
3130
)
@@ -236,12 +235,15 @@ func opSAR(pc *uint64, evm *EVM, scope *ScopeContext) ([]byte, error) {
236235
func opKeccak256(pc *uint64, evm *EVM, scope *ScopeContext) ([]byte, error) {
237236
offset, size := scope.Stack.pop(), scope.Stack.peek()
238237
data := scope.Memory.GetPtr(offset.Uint64(), size.Uint64())
239-
hasherBuf := crypto.Keccak256Hash(data)
238+
239+
evm.hasher.Reset()
240+
evm.hasher.Write(data)
241+
evm.hasher.Read(evm.hasherBuf[:])
240242

241243
if evm.Config.EnablePreimageRecording {
242-
evm.StateDB.AddPreimage(hasherBuf, data)
244+
evm.StateDB.AddPreimage(evm.hasherBuf, data)
243245
}
244-
size.SetBytes(hasherBuf[:])
246+
size.SetBytes(evm.hasherBuf[:])
245247
return nil, nil
246248
}
247249

crypto/crypto.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,14 @@ type KeccakState interface {
6767
Read([]byte) (int, error)
6868
}
6969

70+
// HashData hashes the provided data using the KeccakState and returns a 32 byte hash
71+
func HashData(kh KeccakState, data []byte) (h common.Hash) {
72+
kh.Reset()
73+
kh.Write(data)
74+
kh.Read(h[:])
75+
return h
76+
}
77+
7078
// CreateAddress creates an ethereum address given the bytes and the nonce
7179
func CreateAddress(b common.Address, nonce uint64) common.Address {
7280
data, _ := rlp.EncodeToBytes([]interface{}{b, nonce})

0 commit comments

Comments
 (0)