Skip to content

Commit ba3bcd1

Browse files
authored
Merge pull request #14350 from fjl/trie-iterator-skip-2
eth: add debug_storageRangeAt
2 parents 7cc6abe + 207bd7d commit ba3bcd1

20 files changed

Lines changed: 477 additions & 303 deletions

‎core/state/dump.go‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222

2323
"github.com/ethereum/go-ethereum/common"
2424
"github.com/ethereum/go-ethereum/rlp"
25+
"github.com/ethereum/go-ethereum/trie"
2526
)
2627

2728
type DumpAccount struct {
@@ -44,7 +45,7 @@ func (self *StateDB) RawDump() Dump {
4445
Accounts: make(map[string]DumpAccount),
4546
}
4647

47-
it := self.trie.Iterator()
48+
it := trie.NewIterator(self.trie.NodeIterator(nil))
4849
for it.Next() {
4950
addr := self.trie.GetKey(it.Key)
5051
var data Account
@@ -61,7 +62,7 @@ func (self *StateDB) RawDump() Dump {
6162
Code: common.Bytes2Hex(obj.Code(self.db)),
6263
Storage: make(map[string]string),
6364
}
64-
storageIt := obj.getTrie(self.db).Iterator()
65+
storageIt := trie.NewIterator(obj.getTrie(self.db).NodeIterator(nil))
6566
for storageIt.Next() {
6667
account.Storage[common.Bytes2Hex(self.trie.GetKey(storageIt.Key))] = common.Bytes2Hex(storageIt.Value)
6768
}

‎core/state/iterator.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ func (it *NodeIterator) step() error {
7575
}
7676
// Initialize the iterator if we've just started
7777
if it.stateIt == nil {
78-
it.stateIt = it.state.trie.NodeIterator()
78+
it.stateIt = it.state.trie.NodeIterator(nil)
7979
}
8080
// If we had data nodes previously, we surely have at least state nodes
8181
if it.dataIt != nil {
@@ -118,7 +118,7 @@ func (it *NodeIterator) step() error {
118118
if err != nil {
119119
return err
120120
}
121-
it.dataIt = trie.NewNodeIterator(dataTrie)
121+
it.dataIt = dataTrie.NodeIterator(nil)
122122
if !it.dataIt.Next(true) {
123123
it.dataIt = nil
124124
}

‎core/state/state_object.go‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ func (self *stateObject) setState(key, value common.Hash) {
201201
}
202202

203203
// updateTrie writes cached storage modifications into the object's storage trie.
204-
func (self *stateObject) updateTrie(db trie.Database) {
204+
func (self *stateObject) updateTrie(db trie.Database) *trie.SecureTrie {
205205
tr := self.getTrie(db)
206206
for key, value := range self.dirtyStorage {
207207
delete(self.dirtyStorage, key)
@@ -213,6 +213,7 @@ func (self *stateObject) updateTrie(db trie.Database) {
213213
v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
214214
tr.Update(key[:], v)
215215
}
216+
return tr
216217
}
217218

218219
// UpdateRoot sets the trie root to the current root hash of
@@ -280,7 +281,11 @@ func (c *stateObject) ReturnGas(gas *big.Int) {}
280281

281282
func (self *stateObject) deepCopy(db *StateDB, onDirty func(addr common.Address)) *stateObject {
282283
stateObject := newObject(db, self.address, self.data, onDirty)
283-
stateObject.trie = self.trie
284+
if self.trie != nil {
285+
// A shallow copy makes the two tries independent.
286+
cpy := *self.trie
287+
stateObject.trie = &cpy
288+
}
284289
stateObject.code = self.code
285290
stateObject.dirtyStorage = self.dirtyStorage.Copy()
286291
stateObject.cachedStorage = self.dirtyStorage.Copy()

‎core/state/statedb.go‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,17 @@ func (self *StateDB) GetState(a common.Address, b common.Hash) common.Hash {
296296
return common.Hash{}
297297
}
298298

299+
// StorageTrie returns the storage trie of an account.
300+
// The return value is a copy and is nil for non-existent accounts.
301+
func (self *StateDB) StorageTrie(a common.Address) *trie.SecureTrie {
302+
stateObject := self.getStateObject(a)
303+
if stateObject == nil {
304+
return nil
305+
}
306+
cpy := stateObject.deepCopy(self, nil)
307+
return cpy.updateTrie(self.db)
308+
}
309+
299310
func (self *StateDB) HasSuicided(addr common.Address) bool {
300311
stateObject := self.getStateObject(addr)
301312
if stateObject != nil {
@@ -481,7 +492,7 @@ func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common
481492
cb(h, value)
482493
}
483494

484-
it := so.getTrie(db.db).Iterator()
495+
it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil))
485496
for it.Next() {
486497
// ignore cached values
487498
key := common.BytesToHash(db.trie.GetKey(it.Key))

‎eth/api.go‎

Lines changed: 90 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ import (
2020
"bytes"
2121
"compress/gzip"
2222
"context"
23-
"errors"
2423
"fmt"
2524
"io"
2625
"io/ioutil"
@@ -41,6 +40,7 @@ import (
4140
"github.com/ethereum/go-ethereum/params"
4241
"github.com/ethereum/go-ethereum/rlp"
4342
"github.com/ethereum/go-ethereum/rpc"
43+
"github.com/ethereum/go-ethereum/trie"
4444
)
4545

4646
const defaultTraceTimeout = 5 * time.Second
@@ -526,59 +526,67 @@ func (api *PrivateDebugAPI) TraceTransaction(ctx context.Context, txHash common.
526526
if tx == nil {
527527
return nil, fmt.Errorf("transaction %x not found", txHash)
528528
}
529+
msg, context, statedb, err := api.computeTxEnv(blockHash, int(txIndex))
530+
if err != nil {
531+
return nil, err
532+
}
533+
534+
// Run the transaction with tracing enabled.
535+
vmenv := vm.NewEVM(context, statedb, api.config, vm.Config{Debug: true, Tracer: tracer})
536+
ret, gas, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas()))
537+
if err != nil {
538+
return nil, fmt.Errorf("tracing failed: %v", err)
539+
}
540+
switch tracer := tracer.(type) {
541+
case *vm.StructLogger:
542+
return &ethapi.ExecutionResult{
543+
Gas: gas,
544+
ReturnValue: fmt.Sprintf("%x", ret),
545+
StructLogs: ethapi.FormatLogs(tracer.StructLogs()),
546+
}, nil
547+
case *ethapi.JavascriptTracer:
548+
return tracer.GetResult()
549+
default:
550+
panic(fmt.Sprintf("bad tracer type %T", tracer))
551+
}
552+
}
553+
554+
// computeTxEnv returns the execution environment of a certain transaction.
555+
func (api *PrivateDebugAPI) computeTxEnv(blockHash common.Hash, txIndex int) (core.Message, vm.Context, *state.StateDB, error) {
556+
// Create the parent state.
529557
block := api.eth.BlockChain().GetBlockByHash(blockHash)
530558
if block == nil {
531-
return nil, fmt.Errorf("block %x not found", blockHash)
559+
return nil, vm.Context{}, nil, fmt.Errorf("block %x not found", blockHash)
532560
}
533-
// Create the state database to mutate and eventually trace
534561
parent := api.eth.BlockChain().GetBlock(block.ParentHash(), block.NumberU64()-1)
535562
if parent == nil {
536-
return nil, fmt.Errorf("block parent %x not found", block.ParentHash())
563+
return nil, vm.Context{}, nil, fmt.Errorf("block parent %x not found", block.ParentHash())
537564
}
538-
stateDb, err := api.eth.BlockChain().StateAt(parent.Root())
565+
statedb, err := api.eth.BlockChain().StateAt(parent.Root())
539566
if err != nil {
540-
return nil, err
567+
return nil, vm.Context{}, nil, err
541568
}
569+
txs := block.Transactions()
542570

571+
// Recompute transactions up to the target index.
543572
signer := types.MakeSigner(api.config, block.Number())
544-
// Mutate the state and trace the selected transaction
545-
for idx, tx := range block.Transactions() {
573+
for idx, tx := range txs {
546574
// Assemble the transaction call message
547-
msg, err := tx.AsMessage(signer)
548-
if err != nil {
549-
return nil, fmt.Errorf("sender retrieval failed: %v", err)
550-
}
575+
msg, _ := tx.AsMessage(signer)
551576
context := core.NewEVMContext(msg, block.Header(), api.eth.BlockChain(), nil)
552-
553-
// Mutate the state if we haven't reached the tracing transaction yet
554-
if uint64(idx) < txIndex {
555-
vmenv := vm.NewEVM(context, stateDb, api.config, vm.Config{})
556-
_, _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas()))
557-
if err != nil {
558-
return nil, fmt.Errorf("mutation failed: %v", err)
559-
}
560-
stateDb.DeleteSuicides()
561-
continue
577+
if idx == txIndex {
578+
return msg, context, statedb, nil
562579
}
563580

564-
vmenv := vm.NewEVM(context, stateDb, api.config, vm.Config{Debug: true, Tracer: tracer})
565-
ret, gas, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas()))
581+
vmenv := vm.NewEVM(context, statedb, api.config, vm.Config{})
582+
gp := new(core.GasPool).AddGas(tx.Gas())
583+
_, _, err := core.ApplyMessage(vmenv, msg, gp)
566584
if err != nil {
567-
return nil, fmt.Errorf("tracing failed: %v", err)
568-
}
569-
570-
switch tracer := tracer.(type) {
571-
case *vm.StructLogger:
572-
return &ethapi.ExecutionResult{
573-
Gas: gas,
574-
ReturnValue: fmt.Sprintf("%x", ret),
575-
StructLogs: ethapi.FormatLogs(tracer.StructLogs()),
576-
}, nil
577-
case *ethapi.JavascriptTracer:
578-
return tracer.GetResult()
585+
return nil, vm.Context{}, nil, fmt.Errorf("tx %x failed: %v", tx.Hash(), err)
579586
}
587+
statedb.DeleteSuicides()
580588
}
581-
return nil, errors.New("database inconsistency")
589+
return nil, vm.Context{}, nil, fmt.Errorf("tx index %d out of range for block %x", txIndex, blockHash)
582590
}
583591

584592
// Preimage is a debug API function that returns the preimage for a sha3 hash, if known.
@@ -592,3 +600,48 @@ func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hex
592600
func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]core.BadBlockArgs, error) {
593601
return api.eth.BlockChain().BadBlocks()
594602
}
603+
604+
// StorageRangeResult is the result of a debug_storageRangeAt API call.
605+
type StorageRangeResult struct {
606+
Storage storageMap `json:"storage"`
607+
NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie.
608+
}
609+
610+
type storageMap map[common.Hash]storageEntry
611+
612+
type storageEntry struct {
613+
Key *common.Hash `json:"key"`
614+
Value common.Hash `json:"value"`
615+
}
616+
617+
// StorageRangeAt returns the storage at the given block height and transaction index.
618+
func (api *PrivateDebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) {
619+
_, _, statedb, err := api.computeTxEnv(blockHash, txIndex)
620+
if err != nil {
621+
return StorageRangeResult{}, err
622+
}
623+
st := statedb.StorageTrie(contractAddress)
624+
if st == nil {
625+
return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress)
626+
}
627+
return storageRangeAt(st, keyStart, maxResult), nil
628+
}
629+
630+
func storageRangeAt(st *trie.SecureTrie, start []byte, maxResult int) StorageRangeResult {
631+
it := trie.NewIterator(st.NodeIterator(start))
632+
result := StorageRangeResult{Storage: storageMap{}}
633+
for i := 0; i < maxResult && it.Next(); i++ {
634+
e := storageEntry{Value: common.BytesToHash(it.Value)}
635+
if preimage := st.GetKey(it.Key); preimage != nil {
636+
preimage := common.BytesToHash(preimage)
637+
e.Key = &preimage
638+
}
639+
result.Storage[common.BytesToHash(it.Key)] = e
640+
}
641+
// Add the 'next key' so clients can continue downloading.
642+
if it.Next() {
643+
next := common.BytesToHash(it.Key)
644+
result.NextKey = &next
645+
}
646+
return result
647+
}

‎eth/api_test.go‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
// Copyright 2016 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// The go-ethereum library is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
package eth
18+
19+
import (
20+
"reflect"
21+
"testing"
22+
23+
"github.com/davecgh/go-spew/spew"
24+
"github.com/ethereum/go-ethereum/common"
25+
"github.com/ethereum/go-ethereum/core/state"
26+
"github.com/ethereum/go-ethereum/ethdb"
27+
)
28+
29+
var dumper = spew.ConfigState{Indent: " "}
30+
31+
func TestStorageRangeAt(t *testing.T) {
32+
// Create a state where account 0x010000... has a few storage entries.
33+
var (
34+
db, _ = ethdb.NewMemDatabase()
35+
state, _ = state.New(common.Hash{}, db)
36+
addr = common.Address{0x01}
37+
keys = []common.Hash{ // hashes of Keys of storage
38+
common.HexToHash("340dd630ad21bf010b4e676dbfa9ba9a02175262d1fa356232cfde6cb5b47ef2"),
39+
common.HexToHash("426fcb404ab2d5d8e61a3d918108006bbb0a9be65e92235bb10eefbdb6dcd053"),
40+
common.HexToHash("48078cfed56339ea54962e72c37c7f588fc4f8e5bc173827ba75cb10a63a96a5"),
41+
common.HexToHash("5723d2c3a83af9b735e3b7f21531e5623d183a9095a56604ead41f3582fdfb75"),
42+
}
43+
storage = storageMap{
44+
keys[0]: {Key: &common.Hash{0x02}, Value: common.Hash{0x01}},
45+
keys[1]: {Key: &common.Hash{0x04}, Value: common.Hash{0x02}},
46+
keys[2]: {Key: &common.Hash{0x01}, Value: common.Hash{0x03}},
47+
keys[3]: {Key: &common.Hash{0x03}, Value: common.Hash{0x04}},
48+
}
49+
)
50+
for _, entry := range storage {
51+
state.SetState(addr, *entry.Key, entry.Value)
52+
}
53+
54+
// Check a few combinations of limit and start/end.
55+
tests := []struct {
56+
start []byte
57+
limit int
58+
want StorageRangeResult
59+
}{
60+
{
61+
start: []byte{}, limit: 0,
62+
want: StorageRangeResult{storageMap{}, &keys[0]},
63+
},
64+
{
65+
start: []byte{}, limit: 100,
66+
want: StorageRangeResult{storage, nil},
67+
},
68+
{
69+
start: []byte{}, limit: 2,
70+
want: StorageRangeResult{storageMap{keys[0]: storage[keys[0]], keys[1]: storage[keys[1]]}, &keys[2]},
71+
},
72+
{
73+
start: []byte{0x00}, limit: 4,
74+
want: StorageRangeResult{storage, nil},
75+
},
76+
{
77+
start: []byte{0x40}, limit: 2,
78+
want: StorageRangeResult{storageMap{keys[1]: storage[keys[1]], keys[2]: storage[keys[2]]}, &keys[3]},
79+
},
80+
}
81+
for _, test := range tests {
82+
result := storageRangeAt(state.StorageTrie(addr), test.start, test.limit)
83+
if !reflect.DeepEqual(result, test.want) {
84+
t.Fatalf("wrong result for range 0x%x.., limit %d:\ngot %s\nwant %s",
85+
test.start, test.limit, dumper.Sdump(result), dumper.Sdump(&test.want))
86+
}
87+
}
88+
}

‎internal/web3ext/web3ext.go‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,11 @@ web3._extend({
345345
call: 'debug_getBadBlocks',
346346
params: 0,
347347
}),
348+
new web3._extend.Method({
349+
name: 'storageRangeAt',
350+
call: 'debug_storageRangeAt',
351+
params: 5,
352+
}),
348353
],
349354
properties: []
350355
});

0 commit comments

Comments
 (0)