Skip to content

Commit 058a4ac

Browse files
holimankaralabe
andauthored
core/evm: less iteration in blockhash (#20589)
* core/vm/runtime: add test for blockhash * core/evm: less iteration in blockhash * core/vm/runtime: nitpickfix Co-authored-by: Péter Szilágyi <peterke@gmail.com>
1 parent 33791db commit 058a4ac

3 files changed

Lines changed: 135 additions & 16 deletions

File tree

‎core/evm.go‎

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -60,24 +60,32 @@ func NewEVMContext(msg Message, header *types.Header, chain ChainContext, author
6060

6161
// GetHashFn returns a GetHashFunc which retrieves header hashes by number
6262
func GetHashFn(ref *types.Header, chain ChainContext) func(n uint64) common.Hash {
63-
var cache map[uint64]common.Hash
63+
// Cache will initially contain [refHash.parent],
64+
// Then fill up with [refHash.p, refHash.pp, refHash.ppp, ...]
65+
var cache []common.Hash
6466

6567
return func(n uint64) common.Hash {
6668
// If there's no hash cache yet, make one
67-
if cache == nil {
68-
cache = map[uint64]common.Hash{
69-
ref.Number.Uint64() - 1: ref.ParentHash,
70-
}
69+
if len(cache) == 0 {
70+
cache = append(cache, ref.ParentHash)
7171
}
72-
// Try to fulfill the request from the cache
73-
if hash, ok := cache[n]; ok {
74-
return hash
72+
if idx := ref.Number.Uint64() - n - 1; idx < uint64(len(cache)) {
73+
return cache[idx]
7574
}
76-
// Not cached, iterate the blocks and cache the hashes
77-
for header := chain.GetHeader(ref.ParentHash, ref.Number.Uint64()-1); header != nil; header = chain.GetHeader(header.ParentHash, header.Number.Uint64()-1) {
78-
cache[header.Number.Uint64()-1] = header.ParentHash
79-
if n == header.Number.Uint64()-1 {
80-
return header.ParentHash
75+
// No luck in the cache, but we can start iterating from the last element we already know
76+
lastKnownHash := cache[len(cache)-1]
77+
lastKnownNumber := ref.Number.Uint64() - uint64(len(cache))
78+
79+
for {
80+
header := chain.GetHeader(lastKnownHash, lastKnownNumber)
81+
if header == nil {
82+
break
83+
}
84+
cache = append(cache, header.ParentHash)
85+
lastKnownHash = header.ParentHash
86+
lastKnownNumber = header.Number.Uint64() - 1
87+
if n == lastKnownNumber {
88+
return lastKnownHash
8189
}
8290
}
8391
return common.Hash{}

‎core/vm/runtime/env.go‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
package runtime
1818

1919
import (
20-
"github.com/ethereum/go-ethereum/common"
2120
"github.com/ethereum/go-ethereum/core"
2221
"github.com/ethereum/go-ethereum/core/vm"
2322
)
@@ -26,8 +25,7 @@ func NewEnv(cfg *Config) *vm.EVM {
2625
context := vm.Context{
2726
CanTransfer: core.CanTransfer,
2827
Transfer: core.Transfer,
29-
GetHash: func(uint64) common.Hash { return common.Hash{} },
30-
28+
GetHash: cfg.GetHashFn,
3129
Origin: cfg.Origin,
3230
Coinbase: cfg.Coinbase,
3331
BlockNumber: cfg.BlockNumber,

‎core/vm/runtime/runtime_test.go‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,11 @@ import (
2323

2424
"github.com/ethereum/go-ethereum/accounts/abi"
2525
"github.com/ethereum/go-ethereum/common"
26+
"github.com/ethereum/go-ethereum/consensus"
27+
"github.com/ethereum/go-ethereum/core"
2628
"github.com/ethereum/go-ethereum/core/rawdb"
2729
"github.com/ethereum/go-ethereum/core/state"
30+
"github.com/ethereum/go-ethereum/core/types"
2831
"github.com/ethereum/go-ethereum/core/vm"
2932
"github.com/ethereum/go-ethereum/params"
3033
)
@@ -203,3 +206,113 @@ func BenchmarkEVM_CREATE2_1200(bench *testing.B) {
203206
// initcode size 1200K, repeatedly calls CREATE2 and then modifies the mem contents
204207
benchmarkEVM_Create(bench, "5b5862124f80600080f5600152600056")
205208
}
209+
210+
func fakeHeader(n uint64, parentHash common.Hash) *types.Header {
211+
header := types.Header{
212+
Coinbase: common.HexToAddress("0x00000000000000000000000000000000deadbeef"),
213+
Number: big.NewInt(int64(n)),
214+
ParentHash: parentHash,
215+
Time: 1000,
216+
Nonce: types.BlockNonce{0x1},
217+
Extra: []byte{},
218+
Difficulty: big.NewInt(0),
219+
GasLimit: 100000,
220+
}
221+
return &header
222+
}
223+
224+
type dummyChain struct {
225+
counter int
226+
}
227+
228+
// Engine retrieves the chain's consensus engine.
229+
func (d *dummyChain) Engine() consensus.Engine {
230+
return nil
231+
}
232+
233+
// GetHeader returns the hash corresponding to their hash.
234+
func (d *dummyChain) GetHeader(h common.Hash, n uint64) *types.Header {
235+
d.counter++
236+
parentHash := common.Hash{}
237+
s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32)
238+
copy(parentHash[:], s)
239+
240+
//parentHash := common.Hash{byte(n - 1)}
241+
//fmt.Printf("GetHeader(%x, %d) => header with parent %x\n", h, n, parentHash)
242+
return fakeHeader(n, parentHash)
243+
}
244+
245+
// TestBlockhash tests the blockhash operation. It's a bit special, since it internally
246+
// requires access to a chain reader.
247+
func TestBlockhash(t *testing.T) {
248+
// Current head
249+
n := uint64(1000)
250+
parentHash := common.Hash{}
251+
s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32)
252+
copy(parentHash[:], s)
253+
header := fakeHeader(n, parentHash)
254+
255+
// This is the contract we're using. It requests the blockhash for current num (should be all zeroes),
256+
// then iteratively fetches all blockhashes back to n-260.
257+
// It returns
258+
// 1. the first (should be zero)
259+
// 2. the second (should be the parent hash)
260+
// 3. the last non-zero hash
261+
// By making the chain reader return hashes which correlate to the number, we can
262+
// verify that it obtained the right hashes where it should
263+
264+
/*
265+
266+
pragma solidity ^0.5.3;
267+
contract Hasher{
268+
269+
function test() public view returns (bytes32, bytes32, bytes32){
270+
uint256 x = block.number;
271+
bytes32 first;
272+
bytes32 last;
273+
bytes32 zero;
274+
zero = blockhash(x); // Should be zeroes
275+
first = blockhash(x-1);
276+
for(uint256 i = 2 ; i < 260; i++){
277+
bytes32 hash = blockhash(x - i);
278+
if (uint256(hash) != 0){
279+
last = hash;
280+
}
281+
}
282+
return (zero, first, last);
283+
}
284+
}
285+
286+
*/
287+
// The contract above
288+
data := common.Hex2Bytes("6080604052348015600f57600080fd5b50600436106045576000357c010000000000000000000000000000000000000000000000000000000090048063f8a8fd6d14604a575b600080fd5b60506074565b60405180848152602001838152602001828152602001935050505060405180910390f35b600080600080439050600080600083409050600184034092506000600290505b61010481101560c35760008186034090506000816001900414151560b6578093505b5080806001019150506094565b508083839650965096505050505090919256fea165627a7a72305820462d71b510c1725ff35946c20b415b0d50b468ea157c8c77dff9466c9cb85f560029")
289+
// The method call to 'test()'
290+
input := common.Hex2Bytes("f8a8fd6d")
291+
chain := &dummyChain{}
292+
ret, _, err := Execute(data, input, &Config{
293+
GetHashFn: core.GetHashFn(header, chain),
294+
BlockNumber: new(big.Int).Set(header.Number),
295+
})
296+
if err != nil {
297+
t.Fatalf("expected no error, got %v", err)
298+
}
299+
if len(ret) != 96 {
300+
t.Fatalf("expected returndata to be 96 bytes, got %d", len(ret))
301+
}
302+
303+
zero := new(big.Int).SetBytes(ret[0:32])
304+
first := new(big.Int).SetBytes(ret[32:64])
305+
last := new(big.Int).SetBytes(ret[64:96])
306+
if zero.BitLen() != 0 {
307+
t.Fatalf("expected zeroes, got %x", ret[0:32])
308+
}
309+
if first.Uint64() != 999 {
310+
t.Fatalf("second block should be 999, got %d (%x)", first, ret[32:64])
311+
}
312+
if last.Uint64() != 744 {
313+
t.Fatalf("last block should be 744, got %d (%x)", last, ret[64:96])
314+
}
315+
if exp, got := 255, chain.counter; exp != got {
316+
t.Errorf("suboptimal; too much chain iteration, expected %d, got %d", exp, got)
317+
}
318+
}

0 commit comments

Comments
 (0)