Skip to content

Commit 03fe9de

Browse files
jsvisaholimanfjl
authored
eth: add debug_accountRange API (#19645)
This new API allows reading accounts and their content by address range. Co-authored-by: Martin Holst Swende <martin@swende.se> Co-authored-by: Felix Lange <fjl@twurst.com>
1 parent c56f4fa commit 03fe9de

3 files changed

Lines changed: 102 additions & 132 deletions

File tree

‎core/state/dump.go‎

Lines changed: 41 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ import (
2727
"github.com/ethereum/go-ethereum/trie"
2828
)
2929

30-
// DumpAccount represents an account in the state
30+
// DumpAccount represents an account in the state.
3131
type DumpAccount struct {
3232
Balance string `json:"balance"`
3333
Nonce uint64 `json:"nonce"`
@@ -40,17 +40,24 @@ type DumpAccount struct {
4040

4141
}
4242

43-
// Dump represents the full dump in a collected format, as one large map
43+
// Dump represents the full dump in a collected format, as one large map.
4444
type Dump struct {
4545
Root string `json:"root"`
4646
Accounts map[common.Address]DumpAccount `json:"accounts"`
4747
}
4848

49-
// iterativeDump is a 'collector'-implementation which dump output line-by-line iteratively
49+
// iterativeDump is a 'collector'-implementation which dump output line-by-line iteratively.
5050
type iterativeDump struct {
5151
*json.Encoder
5252
}
5353

54+
// IteratorDump is an implementation for iterating over data.
55+
type IteratorDump struct {
56+
Root string `json:"root"`
57+
Accounts map[common.Address]DumpAccount `json:"accounts"`
58+
Next []byte `json:"next,omitempty"` // nil if no more accounts
59+
}
60+
5461
// Collector interface which the state trie calls during iteration
5562
type collector interface {
5663
onRoot(common.Hash)
@@ -64,6 +71,13 @@ func (d *Dump) onRoot(root common.Hash) {
6471
func (d *Dump) onAccount(addr common.Address, account DumpAccount) {
6572
d.Accounts[addr] = account
6673
}
74+
func (d *IteratorDump) onRoot(root common.Hash) {
75+
d.Root = fmt.Sprintf("%x", root)
76+
}
77+
78+
func (d *IteratorDump) onAccount(addr common.Address, account DumpAccount) {
79+
d.Accounts[addr] = account
80+
}
6781

6882
func (d iterativeDump) onAccount(addr common.Address, account DumpAccount) {
6983
dumpAccount := &DumpAccount{
@@ -88,11 +102,13 @@ func (d iterativeDump) onRoot(root common.Hash) {
88102
}{root})
89103
}
90104

91-
func (s *StateDB) dump(c collector, excludeCode, excludeStorage, excludeMissingPreimages bool) {
105+
func (s *StateDB) dump(c collector, excludeCode, excludeStorage, excludeMissingPreimages bool, start []byte, maxResults int) (nextKey []byte) {
92106
emptyAddress := (common.Address{})
93107
missingPreimages := 0
94108
c.onRoot(s.trie.Hash())
95-
it := trie.NewIterator(s.trie.NodeIterator(nil))
109+
110+
var count int
111+
it := trie.NewIterator(s.trie.NodeIterator(start))
96112
for it.Next() {
97113
var data Account
98114
if err := rlp.DecodeBytes(it.Value, &data); err != nil {
@@ -130,18 +146,27 @@ func (s *StateDB) dump(c collector, excludeCode, excludeStorage, excludeMissingP
130146
}
131147
}
132148
c.onAccount(addr, account)
149+
count++
150+
if maxResults > 0 && count >= maxResults {
151+
if it.Next() {
152+
nextKey = it.Key
153+
}
154+
break
155+
}
133156
}
134157
if missingPreimages > 0 {
135158
log.Warn("Dump incomplete due to missing preimages", "missing", missingPreimages)
136159
}
160+
161+
return nextKey
137162
}
138163

139164
// RawDump returns the entire state an a single large object
140165
func (s *StateDB) RawDump(excludeCode, excludeStorage, excludeMissingPreimages bool) Dump {
141166
dump := &Dump{
142167
Accounts: make(map[common.Address]DumpAccount),
143168
}
144-
s.dump(dump, excludeCode, excludeStorage, excludeMissingPreimages)
169+
s.dump(dump, excludeCode, excludeStorage, excludeMissingPreimages, nil, 0)
145170
return *dump
146171
}
147172

@@ -157,5 +182,14 @@ func (s *StateDB) Dump(excludeCode, excludeStorage, excludeMissingPreimages bool
157182

158183
// IterativeDump dumps out accounts as json-objects, delimited by linebreaks on stdout
159184
func (s *StateDB) IterativeDump(excludeCode, excludeStorage, excludeMissingPreimages bool, output *json.Encoder) {
160-
s.dump(iterativeDump{output}, excludeCode, excludeStorage, excludeMissingPreimages)
185+
s.dump(iterativeDump{output}, excludeCode, excludeStorage, excludeMissingPreimages, nil, 0)
186+
}
187+
188+
// IteratorDump dumps out a batch of accounts starts with the given start key
189+
func (s *StateDB) IteratorDump(excludeCode, excludeStorage, excludeMissingPreimages bool, start []byte, maxResults int) IteratorDump {
190+
iterator := &IteratorDump{
191+
Accounts: make(map[common.Address]DumpAccount),
192+
}
193+
iterator.Next = s.dump(iterator, excludeCode, excludeStorage, excludeMissingPreimages, start, maxResults)
194+
return *iterator
161195
}

‎eth/api.go‎

Lines changed: 34 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -351,70 +351,50 @@ func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs,
351351
return results, nil
352352
}
353353

354-
// AccountRangeResult returns a mapping from the hash of an account addresses
355-
// to its preimage. It will return the JSON null if no preimage is found.
356-
// Since a query can return a limited amount of results, a "next" field is
357-
// also present for paging.
358-
type AccountRangeResult struct {
359-
Accounts map[common.Hash]*common.Address `json:"accounts"`
360-
Next common.Hash `json:"next"`
361-
}
362-
363-
func accountRange(st state.Trie, start *common.Hash, maxResults int) (AccountRangeResult, error) {
364-
if start == nil {
365-
start = &common.Hash{0}
366-
}
367-
it := trie.NewIterator(st.NodeIterator(start.Bytes()))
368-
result := AccountRangeResult{Accounts: make(map[common.Hash]*common.Address), Next: common.Hash{}}
369-
370-
if maxResults > AccountRangeMaxResults {
371-
maxResults = AccountRangeMaxResults
372-
}
373-
374-
for i := 0; i < maxResults && it.Next(); i++ {
375-
if preimage := st.GetKey(it.Key); preimage != nil {
376-
addr := &common.Address{}
377-
addr.SetBytes(preimage)
378-
result.Accounts[common.BytesToHash(it.Key)] = addr
379-
} else {
380-
result.Accounts[common.BytesToHash(it.Key)] = nil
381-
}
382-
}
383-
384-
if it.Next() {
385-
result.Next = common.BytesToHash(it.Key)
386-
}
387-
388-
return result, nil
389-
}
390-
391354
// AccountRangeMaxResults is the maximum number of results to be returned per call
392355
const AccountRangeMaxResults = 256
393356

394-
// AccountRange enumerates all accounts in the latest state
395-
func (api *PrivateDebugAPI) AccountRange(ctx context.Context, start *common.Hash, maxResults int) (AccountRangeResult, error) {
396-
var statedb *state.StateDB
357+
// AccountRangeAt enumerates all accounts in the given block and start point in paging request
358+
func (api *PublicDebugAPI) AccountRange(blockNrOrHash rpc.BlockNumberOrHash, start []byte, maxResults int, nocode, nostorage, incompletes bool) (state.IteratorDump, error) {
359+
var stateDb *state.StateDB
397360
var err error
398-
block := api.eth.blockchain.CurrentBlock()
399361

400-
if len(block.Transactions()) == 0 {
401-
statedb, err = api.computeStateDB(block, defaultTraceReexec)
402-
if err != nil {
403-
return AccountRangeResult{}, err
362+
if number, ok := blockNrOrHash.Number(); ok {
363+
if number == rpc.PendingBlockNumber {
364+
// If we're dumping the pending state, we need to request
365+
// both the pending block as well as the pending state from
366+
// the miner and operate on those
367+
_, stateDb = api.eth.miner.Pending()
368+
} else {
369+
var block *types.Block
370+
if number == rpc.LatestBlockNumber {
371+
block = api.eth.blockchain.CurrentBlock()
372+
} else {
373+
block = api.eth.blockchain.GetBlockByNumber(uint64(number))
374+
}
375+
if block == nil {
376+
return state.IteratorDump{}, fmt.Errorf("block #%d not found", number)
377+
}
378+
stateDb, err = api.eth.BlockChain().StateAt(block.Root())
379+
if err != nil {
380+
return state.IteratorDump{}, err
381+
}
404382
}
405-
} else {
406-
_, _, statedb, err = api.computeTxEnv(block.Hash(), len(block.Transactions())-1, 0)
383+
} else if hash, ok := blockNrOrHash.Hash(); ok {
384+
block := api.eth.blockchain.GetBlockByHash(hash)
385+
if block == nil {
386+
return state.IteratorDump{}, fmt.Errorf("block %s not found", hash.Hex())
387+
}
388+
stateDb, err = api.eth.BlockChain().StateAt(block.Root())
407389
if err != nil {
408-
return AccountRangeResult{}, err
390+
return state.IteratorDump{}, err
409391
}
410392
}
411393

412-
trie, err := statedb.Database().OpenTrie(block.Header().Root)
413-
if err != nil {
414-
return AccountRangeResult{}, err
394+
if maxResults > AccountRangeMaxResults || maxResults <= 0 {
395+
maxResults = AccountRangeMaxResults
415396
}
416-
417-
return accountRange(trie, start, maxResults)
397+
return stateDb.IteratorDump(nocode, nostorage, incompletes, start, maxResults), nil
418398
}
419399

420400
// StorageRangeResult is the result of a debug_storageRangeAt API call.
@@ -431,7 +411,7 @@ type storageEntry struct {
431411
}
432412

433413
// StorageRangeAt returns the storage at the given block height and transaction index.
434-
func (api *PrivateDebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) {
414+
func (api *PrivateDebugAPI) StorageRangeAt(blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) {
435415
_, _, statedb, err := api.computeTxEnv(blockHash, txIndex, 0)
436416
if err != nil {
437417
return StorageRangeResult{}, err

‎eth/api_test.go‎

Lines changed: 27 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -33,29 +33,24 @@ import (
3333

3434
var dumper = spew.ConfigState{Indent: " "}
3535

36-
func accountRangeTest(t *testing.T, trie *state.Trie, statedb *state.StateDB, start *common.Hash, requestedNum int, expectedNum int) AccountRangeResult {
37-
result, err := accountRange(*trie, start, requestedNum)
38-
if err != nil {
39-
t.Fatal(err)
40-
}
36+
func accountRangeTest(t *testing.T, trie *state.Trie, statedb *state.StateDB, start common.Hash, requestedNum int, expectedNum int) state.IteratorDump {
37+
result := statedb.IteratorDump(true, true, false, start.Bytes(), requestedNum)
4138

4239
if len(result.Accounts) != expectedNum {
43-
t.Fatalf("expected %d results. Got %d", expectedNum, len(result.Accounts))
40+
t.Fatalf("expected %d results, got %d", expectedNum, len(result.Accounts))
4441
}
45-
46-
for _, address := range result.Accounts {
47-
if address == nil {
48-
t.Fatalf("null address returned")
42+
for address := range result.Accounts {
43+
if address == (common.Address{}) {
44+
t.Fatalf("empty address returned")
4945
}
50-
if !statedb.Exist(*address) {
46+
if !statedb.Exist(address) {
5147
t.Fatalf("account not found in state %s", address.Hex())
5248
}
5349
}
54-
5550
return result
5651
}
5752

58-
type resultHash []*common.Hash
53+
type resultHash []common.Hash
5954

6055
func (h resultHash) Len() int { return len(h) }
6156
func (h resultHash) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
@@ -80,76 +75,47 @@ func TestAccountRange(t *testing.T) {
8075
m[addr] = true
8176
}
8277
}
83-
8478
state.Commit(true)
8579
root := state.IntermediateRoot(true)
8680

8781
trie, err := statedb.OpenTrie(root)
8882
if err != nil {
8983
t.Fatal(err)
9084
}
91-
92-
t.Logf("test getting number of results less than max")
93-
accountRangeTest(t, &trie, state, &common.Hash{0x0}, AccountRangeMaxResults/2, AccountRangeMaxResults/2)
94-
95-
t.Logf("test getting number of results greater than max %d", AccountRangeMaxResults)
96-
accountRangeTest(t, &trie, state, &common.Hash{0x0}, AccountRangeMaxResults*2, AccountRangeMaxResults)
97-
98-
t.Logf("test with empty 'start' hash")
99-
accountRangeTest(t, &trie, state, nil, AccountRangeMaxResults, AccountRangeMaxResults)
100-
101-
t.Logf("test pagination")
102-
85+
accountRangeTest(t, &trie, state, common.Hash{}, AccountRangeMaxResults/2, AccountRangeMaxResults/2)
10386
// test pagination
104-
firstResult := accountRangeTest(t, &trie, state, &common.Hash{0x0}, AccountRangeMaxResults, AccountRangeMaxResults)
105-
106-
t.Logf("test pagination 2")
107-
secondResult := accountRangeTest(t, &trie, state, &firstResult.Next, AccountRangeMaxResults, AccountRangeMaxResults)
87+
firstResult := accountRangeTest(t, &trie, state, common.Hash{}, AccountRangeMaxResults, AccountRangeMaxResults)
88+
secondResult := accountRangeTest(t, &trie, state, common.BytesToHash(firstResult.Next), AccountRangeMaxResults, AccountRangeMaxResults)
10889

10990
hList := make(resultHash, 0)
110-
for h1, addr1 := range firstResult.Accounts {
111-
h := &common.Hash{}
112-
h.SetBytes(h1.Bytes())
113-
hList = append(hList, h)
114-
for h2, addr2 := range secondResult.Accounts {
115-
// Make sure that the hashes aren't the same
116-
if bytes.Equal(h1.Bytes(), h2.Bytes()) {
117-
t.Fatalf("pagination test failed: results should not overlap")
118-
}
119-
120-
// If either address is nil, then it makes no sense to compare
121-
// them as they might be two different accounts.
122-
if addr1 == nil || addr2 == nil {
123-
continue
124-
}
125-
126-
// Since the two hashes are different, they should not have
127-
// the same preimage, but let's check anyway in case there
128-
// is a bug in the (hash, addr) map generation code.
129-
if bytes.Equal(addr1.Bytes(), addr2.Bytes()) {
130-
t.Fatalf("pagination test failed: addresses should not repeat")
131-
}
91+
for addr1 := range firstResult.Accounts {
92+
// If address is empty, then it makes no sense to compare
93+
// them as they might be two different accounts.
94+
if addr1 == (common.Address{}) {
95+
continue
96+
}
97+
if _, duplicate := secondResult.Accounts[addr1]; duplicate {
98+
t.Fatalf("pagination test failed: results should not overlap")
13299
}
100+
hList = append(hList, crypto.Keccak256Hash(addr1.Bytes()))
133101
}
134-
135102
// Test to see if it's possible to recover from the middle of the previous
136103
// set and get an even split between the first and second sets.
137-
t.Logf("test random access pagination")
138104
sort.Sort(hList)
139105
middleH := hList[AccountRangeMaxResults/2]
140106
middleResult := accountRangeTest(t, &trie, state, middleH, AccountRangeMaxResults, AccountRangeMaxResults)
141-
innone, infirst, insecond := 0, 0, 0
107+
missing, infirst, insecond := 0, 0, 0
142108
for h := range middleResult.Accounts {
143109
if _, ok := firstResult.Accounts[h]; ok {
144110
infirst++
145111
} else if _, ok := secondResult.Accounts[h]; ok {
146112
insecond++
147113
} else {
148-
innone++
114+
missing++
149115
}
150116
}
151-
if innone != 0 {
152-
t.Fatalf("%d hashes in the 'middle' set were neither in the first not the second set", innone)
117+
if missing != 0 {
118+
t.Fatalf("%d hashes in the 'middle' set were neither in the first not the second set", missing)
153119
}
154120
if infirst != AccountRangeMaxResults/2 {
155121
t.Fatalf("Imbalance in the number of first-test results: %d != %d", infirst, AccountRangeMaxResults/2)
@@ -164,20 +130,10 @@ func TestEmptyAccountRange(t *testing.T) {
164130
statedb = state.NewDatabase(rawdb.NewMemoryDatabase())
165131
state, _ = state.New(common.Hash{}, statedb, nil)
166132
)
167-
168133
state.Commit(true)
169-
root := state.IntermediateRoot(true)
170-
171-
trie, err := statedb.OpenTrie(root)
172-
if err != nil {
173-
t.Fatal(err)
174-
}
175-
176-
results, err := accountRange(trie, &common.Hash{0x0}, AccountRangeMaxResults)
177-
if err != nil {
178-
t.Fatalf("Empty results should not trigger an error: %v", err)
179-
}
180-
if results.Next != common.HexToHash("0") {
134+
state.IntermediateRoot(true)
135+
results := state.IteratorDump(true, true, true, (common.Hash{}).Bytes(), AccountRangeMaxResults)
136+
if bytes.Equal(results.Next, (common.Hash{}).Bytes()) {
181137
t.Fatalf("Empty results should not return a second page")
182138
}
183139
if len(results.Accounts) != 0 {

0 commit comments

Comments
 (0)