Skip to content

Commit 6bd896a

Browse files
jwasingerfjl
authored andcommitted
eth: add debug_accountRange (#17438)
This adds the debug_accountRange method which returns all accounts in the state for a given block and transaction index.
1 parent 49a7ee4 commit 6bd896a

3 files changed

Lines changed: 225 additions & 2 deletions

File tree

‎cmd/geth/retesteth.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ type RetestethEthAPI interface {
8686
}
8787

8888
type RetestethDebugAPI interface {
89-
AccountRangeAt(ctx context.Context,
89+
AccountRange(ctx context.Context,
9090
blockHashOrNumber *math.HexOrDecimal256, txIndex uint64,
9191
addressHash *math.HexOrDecimal256, maxResults uint64,
9292
) (AccountRangeResult, error)
@@ -604,7 +604,7 @@ func (api *RetestethAPI) GetBlockByNumber(ctx context.Context, blockNr math.HexO
604604
return nil, fmt.Errorf("block %d not found", blockNr)
605605
}
606606

607-
func (api *RetestethAPI) AccountRangeAt(ctx context.Context,
607+
func (api *RetestethAPI) AccountRange(ctx context.Context,
608608
blockHashOrNumber *math.HexOrDecimal256, txIndex uint64,
609609
addressHash *math.HexOrDecimal256, maxResults uint64,
610610
) (AccountRangeResult, error) {

‎eth/api.go‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,72 @@ func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs,
334334
return results, nil
335335
}
336336

337+
// AccountRangeResult returns a mapping from the hash of an account addresses
338+
// to its preimage. It will return the JSON null if no preimage is found.
339+
// Since a query can return a limited amount of results, a "next" field is
340+
// also present for paging.
341+
type AccountRangeResult struct {
342+
Accounts map[common.Hash]*common.Address `json:"accounts"`
343+
Next common.Hash `json:"next"`
344+
}
345+
346+
func accountRange(st state.Trie, start *common.Hash, maxResults int) (AccountRangeResult, error) {
347+
if start == nil {
348+
start = &common.Hash{0}
349+
}
350+
it := trie.NewIterator(st.NodeIterator(start.Bytes()))
351+
result := AccountRangeResult{Accounts: make(map[common.Hash]*common.Address), Next: common.Hash{}}
352+
353+
if maxResults > AccountRangeMaxResults {
354+
maxResults = AccountRangeMaxResults
355+
}
356+
357+
for i := 0; i < maxResults && it.Next(); i++ {
358+
if preimage := st.GetKey(it.Key); preimage != nil {
359+
addr := &common.Address{}
360+
addr.SetBytes(preimage)
361+
result.Accounts[common.BytesToHash(it.Key)] = addr
362+
} else {
363+
result.Accounts[common.BytesToHash(it.Key)] = nil
364+
}
365+
}
366+
367+
if it.Next() {
368+
result.Next = common.BytesToHash(it.Key)
369+
}
370+
371+
return result, nil
372+
}
373+
374+
// AccountRangeMaxResults is the maximum number of results to be returned per call
375+
const AccountRangeMaxResults = 256
376+
377+
// AccountRange enumerates all accounts in the latest state
378+
func (api *PrivateDebugAPI) AccountRange(ctx context.Context, start *common.Hash, maxResults int) (AccountRangeResult, error) {
379+
var statedb *state.StateDB
380+
var err error
381+
block := api.eth.blockchain.CurrentBlock()
382+
383+
if len(block.Transactions()) == 0 {
384+
statedb, err = api.computeStateDB(block, defaultTraceReexec)
385+
if err != nil {
386+
return AccountRangeResult{}, err
387+
}
388+
} else {
389+
_, _, statedb, err = api.computeTxEnv(block.Hash(), len(block.Transactions())-1, 0)
390+
if err != nil {
391+
return AccountRangeResult{}, err
392+
}
393+
}
394+
395+
trie, err := statedb.Database().OpenTrie(block.Header().Root)
396+
if err != nil {
397+
return AccountRangeResult{}, err
398+
}
399+
400+
return accountRange(trie, start, maxResults)
401+
}
402+
337403
// StorageRangeResult is the result of a debug_storageRangeAt API call.
338404
type StorageRangeResult struct {
339405
Storage storageMap `json:"storage"`

‎eth/api_test.go‎

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,17 +17,174 @@
1717
package eth
1818

1919
import (
20+
"bytes"
21+
"fmt"
22+
"math/big"
2023
"reflect"
24+
"sort"
2125
"testing"
2226

2327
"github.com/davecgh/go-spew/spew"
2428
"github.com/ethereum/go-ethereum/common"
2529
"github.com/ethereum/go-ethereum/core/rawdb"
2630
"github.com/ethereum/go-ethereum/core/state"
31+
"github.com/ethereum/go-ethereum/crypto"
2732
)
2833

2934
var dumper = spew.ConfigState{Indent: " "}
3035

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+
}
41+
42+
if len(result.Accounts) != expectedNum {
43+
t.Fatalf("expected %d results. Got %d", expectedNum, len(result.Accounts))
44+
}
45+
46+
for _, address := range result.Accounts {
47+
if address == nil {
48+
t.Fatalf("null address returned")
49+
}
50+
if !statedb.Exist(*address) {
51+
t.Fatalf("account not found in state %s", address.Hex())
52+
}
53+
}
54+
55+
return result
56+
}
57+
58+
type resultHash []*common.Hash
59+
60+
func (h resultHash) Len() int { return len(h) }
61+
func (h resultHash) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
62+
func (h resultHash) Less(i, j int) bool { return bytes.Compare(h[i].Bytes(), h[j].Bytes()) < 0 }
63+
64+
func TestAccountRange(t *testing.T) {
65+
var (
66+
statedb = state.NewDatabase(rawdb.NewMemoryDatabase())
67+
state, _ = state.New(common.Hash{}, statedb)
68+
addrs = [AccountRangeMaxResults * 2]common.Address{}
69+
m = map[common.Address]bool{}
70+
)
71+
72+
for i := range addrs {
73+
hash := common.HexToHash(fmt.Sprintf("%x", i))
74+
addr := common.BytesToAddress(crypto.Keccak256Hash(hash.Bytes()).Bytes())
75+
addrs[i] = addr
76+
state.SetBalance(addrs[i], big.NewInt(1))
77+
if _, ok := m[addr]; ok {
78+
t.Fatalf("bad")
79+
} else {
80+
m[addr] = true
81+
}
82+
}
83+
84+
state.Commit(true)
85+
root := state.IntermediateRoot(true)
86+
87+
trie, err := statedb.OpenTrie(root)
88+
if err != nil {
89+
t.Fatal(err)
90+
}
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+
103+
// 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)
108+
109+
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+
}
132+
}
133+
}
134+
135+
// Test to see if it's possible to recover from the middle of the previous
136+
// set and get an even split between the first and second sets.
137+
t.Logf("test random access pagination")
138+
sort.Sort(hList)
139+
middleH := hList[AccountRangeMaxResults/2]
140+
middleResult := accountRangeTest(t, &trie, state, middleH, AccountRangeMaxResults, AccountRangeMaxResults)
141+
innone, infirst, insecond := 0, 0, 0
142+
for h := range middleResult.Accounts {
143+
if _, ok := firstResult.Accounts[h]; ok {
144+
infirst++
145+
} else if _, ok := secondResult.Accounts[h]; ok {
146+
insecond++
147+
} else {
148+
innone++
149+
}
150+
}
151+
if innone != 0 {
152+
t.Fatalf("%d hashes in the 'middle' set were neither in the first not the second set", innone)
153+
}
154+
if infirst != AccountRangeMaxResults/2 {
155+
t.Fatalf("Imbalance in the number of first-test results: %d != %d", infirst, AccountRangeMaxResults/2)
156+
}
157+
if insecond != AccountRangeMaxResults/2 {
158+
t.Fatalf("Imbalance in the number of second-test results: %d != %d", insecond, AccountRangeMaxResults/2)
159+
}
160+
}
161+
162+
func TestEmptyAccountRange(t *testing.T) {
163+
var (
164+
statedb = state.NewDatabase(rawdb.NewMemoryDatabase())
165+
state, _ = state.New(common.Hash{}, statedb)
166+
)
167+
168+
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") {
181+
t.Fatalf("Empty results should not return a second page")
182+
}
183+
if len(results.Accounts) != 0 {
184+
t.Fatalf("Empty state should not return addresses: %v", results.Accounts)
185+
}
186+
}
187+
31188
func TestStorageRangeAt(t *testing.T) {
32189
// Create a state where account 0x010000... has a few storage entries.
33190
var (

0 commit comments

Comments
 (0)