Skip to content

Commit 9032013

Browse files
authored
Merge pull request #580 from OffchainLabs/pmikolajczyk/nit-4123-keccaking
all: Unify keccaking
2 parents 52efdc6 + cbe5e2f commit 9032013

File tree

16 files changed

+43
-169
lines changed

16 files changed

+43
-169
lines changed

cmd/devp2p/internal/ethtest/snap.go

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -900,16 +900,12 @@ 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)
905903
codes = make([][]byte, len(req.Hashes))
906904
)
907905

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

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

960956
// Cross reference the requested trienodes with the response to find gaps
961957
// that the serving node is missing
962-
hasher := crypto.NewKeccakState()
963-
hash := make([]byte, 32)
964958
trienodes := res.Nodes
965959
if got, want := len(trienodes), len(tc.expHashes); got != want {
966960
return fmt.Errorf("wrong trienode count, got %d, want %d", got, want)
967961
}
968962
for i, trienode := range trienodes {
969-
hasher.Reset()
970-
hasher.Write(trienode)
971-
hasher.Read(hash)
963+
hash := crypto.Keccak256(trienode[:])
972964
if got, want := hash, tc.expHashes[i]; !bytes.Equal(got, want[:]) {
973965
t.Logf(" hash %d wrong, got %#x, want %#x\n", i, got, want)
974966
err = fmt.Errorf("hash %d wrong, got %#x, want %#x", i, got, want)

cmd/geth/dbcmd.go

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -354,8 +354,6 @@ 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)
359357
errs int
360358
count int
361359
startTime = time.Now()
@@ -365,9 +363,7 @@ func checkStateContent(ctx *cli.Context) error {
365363
count++
366364
k := it.Key()
367365
v := it.Value()
368-
hasher.Reset()
369-
hasher.Write(v)
370-
hasher.Read(got)
366+
got := crypto.Keccak256(v)
371367
if !bytes.Equal(k, got) {
372368
errs++
373369
fmt.Printf("Error at %#x\n", k)

cmd/geth/snapshot.go

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -434,8 +434,6 @@ 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)
439437
)
440438
accIter, err := t.NodeIterator(nil)
441439
if err != nil {
@@ -459,9 +457,7 @@ func traverseRawState(ctx *cli.Context) error {
459457
log.Error("Missing trie node(account)", "hash", node)
460458
return errors.New("missing account")
461459
}
462-
hasher.Reset()
463-
hasher.Write(blob)
464-
hasher.Read(got)
460+
got := crypto.Keccak256(blob)
465461
if !bytes.Equal(got, node.Bytes()) {
466462
log.Error("Invalid trie node(account)", "hash", node.Hex(), "value", blob)
467463
return errors.New("invalid account node")
@@ -500,9 +496,7 @@ func traverseRawState(ctx *cli.Context) error {
500496
log.Error("Missing trie node(storage)", "hash", node)
501497
return errors.New("missing storage")
502498
}
503-
hasher.Reset()
504-
hasher.Write(blob)
505-
hasher.Read(got)
499+
got := crypto.Keccak256(blob)
506500
if !bytes.Equal(got, node.Bytes()) {
507501
log.Error("Invalid trie node(storage)", "hash", node.Hex(), "value", blob)
508502
return errors.New("invalid storage node")

cmd/workload/historytestgen.go

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

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

140139
func writeJSON(fileName string, value any) {

core/stateless/database.go

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -34,33 +34,21 @@ import (
3434
//
3535
// Acceleration structures built would need to explicitly validate the witness.
3636
func (w *Witness) MakeHashDB() ethdb.Database {
37-
var (
38-
memdb = rawdb.NewMemoryDatabase()
39-
hasher = crypto.NewKeccakState()
40-
hash = make([]byte, 32)
41-
)
37+
var memdb = rawdb.NewMemoryDatabase()
4238
// Inject all the "block hashes" (i.e. headers) into the ephemeral database
4339
for _, header := range w.Headers {
4440
rawdb.WriteHeader(memdb, header)
4541
}
4642
// Inject all the bytecodes into the ephemeral database
4743
for code := range w.Codes {
4844
blob := []byte(code)
49-
50-
hasher.Reset()
51-
hasher.Write(blob)
52-
hasher.Read(hash)
53-
45+
hash := crypto.Keccak256(blob)
5446
rawdb.WriteCode(memdb, common.BytesToHash(hash), blob)
5547
}
5648
// Inject all the MPT trie nodes into the ephemeral database
5749
for node := range w.State {
5850
blob := []byte(node)
59-
60-
hasher.Reset()
61-
hasher.Write(blob)
62-
hasher.Read(hash)
63-
51+
hash := crypto.Keccak256(blob)
6452
rawdb.WriteLegacyTrieNode(memdb, common.BytesToHash(hash), blob)
6553
}
6654
return memdb

core/types/bloom9.go

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -141,11 +141,8 @@ 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-
sha := hasherPool.Get().(crypto.KeccakState)
145-
sha.Reset()
146-
sha.Write(data)
147-
sha.Read(hashbuf[:])
148-
hasherPool.Put(sha)
144+
hash := crypto.Keccak256(data)
145+
copy(hashbuf[:], hash[:6])
149146
// The actual bits to flip
150147
v1 := byte(1 << (hashbuf[1] & 0x7))
151148
v2 := byte(1 << (hashbuf[3] & 0x7))

core/types/hashing.go

Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,6 @@ 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-
3530
// encodeBufferPool holds temporary encoder buffers for DeriveSha and TX encoding.
3631
var encodeBufferPool = sync.Pool{
3732
New: func() interface{} { return new(bytes.Buffer) },
@@ -55,24 +50,15 @@ func getPooledBuffer(size uint64) ([]byte, *bytes.Buffer, error) {
5550

5651
// rlpHash encodes x and hashes the encoded bytes.
5752
func rlpHash(x interface{}) (h common.Hash) {
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
53+
encoded, _ := rlp.EncodeToBytes(x)
54+
return crypto.Keccak256Hash(encoded)
6455
}
6556

6657
// prefixedRlpHash writes the prefix into the hasher before rlp-encoding x.
6758
// It's used for typed transactions.
6859
func prefixedRlpHash(prefix byte, x interface{}) (h common.Hash) {
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
60+
encoded, _ := rlp.EncodeToBytes(x)
61+
return crypto.Keccak256Hash([]byte{prefix}, encoded)
7662
}
7763

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

core/vm/evm.go

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -133,9 +133,6 @@ 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-
139136
readOnly bool // Whether to throw on stateful modifications
140137
returnData []byte // Last CALL's return data for subsequent reuse
141138
}
@@ -152,7 +149,6 @@ func NewEVM(blockCtx BlockContext, statedb StateDB, chainConfig *params.ChainCon
152149
chainConfig: chainConfig,
153150
chainRules: chainConfig.Rules(blockCtx.BlockNumber, blockCtx.Random != nil, blockCtx.Time, blockCtx.ArbOSVersion),
154151
jumpDests: newMapJumpDests(),
155-
hasher: crypto.NewKeccakState(),
156152
}
157153
evm.ProcessingHook = DefaultTxProcessor{evm: evm}
158154
evm.precompiles = activePrecompiledContracts(evm.chainRules)
@@ -703,7 +699,7 @@ func (evm *EVM) Create(caller common.Address, code []byte, gas uint64, value *ui
703699
// The different between Create2 with Create is Create2 uses keccak256(0xff ++ msg.sender ++ salt ++ keccak256(init_code))[12:]
704700
// instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
705701
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) {
706-
inithash := crypto.HashData(evm.hasher, code)
702+
inithash := crypto.Keccak256Hash(code)
707703
contractAddr = crypto.CreateAddress2(caller, salt.Bytes32(), inithash[:])
708704
return evm.create(caller, code, gas, endowment, contractAddr, CREATE2)
709705
}

core/vm/instructions.go

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ 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"
2829
"github.com/ethereum/go-ethereum/params"
2930
"github.com/holiman/uint256"
3031
)
@@ -235,15 +236,12 @@ func opSAR(pc *uint64, evm *EVM, scope *ScopeContext) ([]byte, error) {
235236
func opKeccak256(pc *uint64, evm *EVM, scope *ScopeContext) ([]byte, error) {
236237
offset, size := scope.Stack.pop(), scope.Stack.peek()
237238
data := scope.Memory.GetPtr(offset.Uint64(), size.Uint64())
238-
239-
evm.hasher.Reset()
240-
evm.hasher.Write(data)
241-
evm.hasher.Read(evm.hasherBuf[:])
239+
hasherBuf := crypto.Keccak256Hash(data)
242240

243241
if evm.Config.EnablePreimageRecording {
244-
evm.StateDB.AddPreimage(evm.hasherBuf, data)
242+
evm.StateDB.AddPreimage(hasherBuf, data)
245243
}
246-
size.SetBytes(evm.hasherBuf[:])
244+
size.SetBytes(hasherBuf[:])
247245
return nil, nil
248246
}
249247

crypto/crypto.go

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -67,14 +67,6 @@ 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-
7870
// CreateAddress creates an ethereum address given the bytes and the nonce
7971
func CreateAddress(b common.Address, nonce uint64) common.Address {
8072
data, _ := rlp.EncodeToBytes([]interface{}{b, nonce})

0 commit comments

Comments
 (0)