Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 99f81d2

Browse files
authored
all: refactor trie API (ethereum#26995)
In this PR, all TryXXX(e.g. TryGet) APIs of trie are renamed to XXX(e.g. Get) with an error returned. The original XXX(e.g. Get) APIs are renamed to MustXXX(e.g. MustGet) and does not return any error -- they print a log output. A future PR will change the behaviour to panic on errorrs.
1 parent ae93e0b commit 99f81d2

28 files changed

+256
-229
lines changed

core/rawdb/accessors_indexes_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,10 @@ func (h *testHasher) Reset() {
4545
h.hasher.Reset()
4646
}
4747

48-
func (h *testHasher) Update(key, val []byte) {
48+
func (h *testHasher) Update(key, val []byte) error {
4949
h.hasher.Write(key)
5050
h.hasher.Write(val)
51+
return nil
5152
}
5253

5354
func (h *testHasher) Hash() common.Hash {

core/state/snapshot/conversion.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -371,7 +371,7 @@ func stackTrieGenerate(db ethdb.KeyValueWriter, scheme string, owner common.Hash
371371
}
372372
t := trie.NewStackTrieWithOwner(nodeWriter, owner)
373373
for leaf := range in {
374-
t.TryUpdate(leaf.key[:], leaf.value)
374+
t.Update(leaf.key[:], leaf.value)
375375
}
376376
var root common.Hash
377377
if db == nil {

core/state/snapshot/generate.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ func (dl *diskLayer) proveRange(ctx *generatorContext, trieId *trie.ID, prefix [
230230
if origin == nil && !diskMore {
231231
stackTr := trie.NewStackTrie(nil)
232232
for i, key := range keys {
233-
stackTr.TryUpdate(key, vals[i])
233+
stackTr.Update(key, vals[i])
234234
}
235235
if gotRoot := stackTr.Hash(); gotRoot != root {
236236
return &proofResult{

core/state/snapshot/generate_test.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ func newHelper() *testHelper {
161161

162162
func (t *testHelper) addTrieAccount(acckey string, acc *Account) {
163163
val, _ := rlp.EncodeToBytes(acc)
164-
t.accTrie.Update([]byte(acckey), val)
164+
t.accTrie.MustUpdate([]byte(acckey), val)
165165
}
166166

167167
func (t *testHelper) addSnapAccount(acckey string, acc *Account) {
@@ -186,7 +186,7 @@ func (t *testHelper) makeStorageTrie(stateRoot, owner common.Hash, keys []string
186186
id := trie.StorageTrieID(stateRoot, owner, common.Hash{})
187187
stTrie, _ := trie.NewStateTrie(id, t.triedb)
188188
for i, k := range keys {
189-
stTrie.Update([]byte(k), []byte(vals[i]))
189+
stTrie.MustUpdate([]byte(k), []byte(vals[i]))
190190
}
191191
if !commit {
192192
return stTrie.Hash().Bytes()
@@ -491,7 +491,7 @@ func TestGenerateWithExtraAccounts(t *testing.T) {
491491
)
492492
acc := &Account{Balance: big.NewInt(1), Root: stRoot, CodeHash: types.EmptyCodeHash.Bytes()}
493493
val, _ := rlp.EncodeToBytes(acc)
494-
helper.accTrie.Update([]byte("acc-1"), val) // 0x9250573b9c18c664139f3b6a7a8081b7d8f8916a8fcc5d94feec6c29f5fd4e9e
494+
helper.accTrie.MustUpdate([]byte("acc-1"), val) // 0x9250573b9c18c664139f3b6a7a8081b7d8f8916a8fcc5d94feec6c29f5fd4e9e
495495

496496
// Identical in the snap
497497
key := hashData([]byte("acc-1"))
@@ -562,7 +562,7 @@ func TestGenerateWithManyExtraAccounts(t *testing.T) {
562562
)
563563
acc := &Account{Balance: big.NewInt(1), Root: stRoot, CodeHash: types.EmptyCodeHash.Bytes()}
564564
val, _ := rlp.EncodeToBytes(acc)
565-
helper.accTrie.Update([]byte("acc-1"), val) // 0x9250573b9c18c664139f3b6a7a8081b7d8f8916a8fcc5d94feec6c29f5fd4e9e
565+
helper.accTrie.MustUpdate([]byte("acc-1"), val) // 0x9250573b9c18c664139f3b6a7a8081b7d8f8916a8fcc5d94feec6c29f5fd4e9e
566566

567567
// Identical in the snap
568568
key := hashData([]byte("acc-1"))
@@ -613,8 +613,8 @@ func TestGenerateWithExtraBeforeAndAfter(t *testing.T) {
613613
{
614614
acc := &Account{Balance: big.NewInt(1), Root: types.EmptyRootHash.Bytes(), CodeHash: types.EmptyCodeHash.Bytes()}
615615
val, _ := rlp.EncodeToBytes(acc)
616-
helper.accTrie.Update(common.HexToHash("0x03").Bytes(), val)
617-
helper.accTrie.Update(common.HexToHash("0x07").Bytes(), val)
616+
helper.accTrie.MustUpdate(common.HexToHash("0x03").Bytes(), val)
617+
helper.accTrie.MustUpdate(common.HexToHash("0x07").Bytes(), val)
618618

619619
rawdb.WriteAccountSnapshot(helper.diskdb, common.HexToHash("0x01"), val)
620620
rawdb.WriteAccountSnapshot(helper.diskdb, common.HexToHash("0x02"), val)
@@ -650,7 +650,7 @@ func TestGenerateWithMalformedSnapdata(t *testing.T) {
650650
{
651651
acc := &Account{Balance: big.NewInt(1), Root: types.EmptyRootHash.Bytes(), CodeHash: types.EmptyCodeHash.Bytes()}
652652
val, _ := rlp.EncodeToBytes(acc)
653-
helper.accTrie.Update(common.HexToHash("0x03").Bytes(), val)
653+
helper.accTrie.MustUpdate(common.HexToHash("0x03").Bytes(), val)
654654

655655
junk := make([]byte, 100)
656656
copy(junk, []byte{0xde, 0xad})

core/state/sync_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -213,22 +213,22 @@ func testIterativeStateSync(t *testing.T, count int, commit bool, bypath bool) {
213213
for i, node := range nodeElements {
214214
if bypath {
215215
if len(node.syncPath) == 1 {
216-
data, _, err := srcTrie.TryGetNode(node.syncPath[0])
216+
data, _, err := srcTrie.GetNode(node.syncPath[0])
217217
if err != nil {
218218
t.Fatalf("failed to retrieve node data for path %x: %v", node.syncPath[0], err)
219219
}
220220
nodeResults[i] = trie.NodeSyncResult{Path: node.path, Data: data}
221221
} else {
222222
var acc types.StateAccount
223-
if err := rlp.DecodeBytes(srcTrie.Get(node.syncPath[0]), &acc); err != nil {
223+
if err := rlp.DecodeBytes(srcTrie.MustGet(node.syncPath[0]), &acc); err != nil {
224224
t.Fatalf("failed to decode account on path %x: %v", node.syncPath[0], err)
225225
}
226226
id := trie.StorageTrieID(srcRoot, common.BytesToHash(node.syncPath[0]), acc.Root)
227227
stTrie, err := trie.New(id, srcDb.TrieDB())
228228
if err != nil {
229229
t.Fatalf("failed to retriev storage trie for path %x: %v", node.syncPath[1], err)
230230
}
231-
data, _, err := stTrie.TryGetNode(node.syncPath[1])
231+
data, _, err := stTrie.GetNode(node.syncPath[1])
232232
if err != nil {
233233
t.Fatalf("failed to retrieve node data for path %x: %v", node.syncPath[1], err)
234234
}

core/types/block_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,9 +232,10 @@ func (h *testHasher) Reset() {
232232
h.hasher.Reset()
233233
}
234234

235-
func (h *testHasher) Update(key, val []byte) {
235+
func (h *testHasher) Update(key, val []byte) error {
236236
h.hasher.Write(key)
237237
h.hasher.Write(val)
238+
return nil
238239
}
239240

240241
func (h *testHasher) Hash() common.Hash {

core/types/hashing.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ func prefixedRlpHash(prefix byte, x interface{}) (h common.Hash) {
6262
// This is internal, do not use.
6363
type TrieHasher interface {
6464
Reset()
65-
Update([]byte, []byte)
65+
Update([]byte, []byte) error
6666
Hash() common.Hash
6767
}
6868

@@ -93,6 +93,9 @@ func DeriveSha(list DerivableList, hasher TrieHasher) common.Hash {
9393
// StackTrie requires values to be inserted in increasing hash order, which is not the
9494
// order that `list` provides hashes in. This insertion sequence ensures that the
9595
// order is correct.
96+
//
97+
// The error returned by hasher is omitted because hasher will produce an incorrect
98+
// hash in case any error occurs.
9699
var indexBuf []byte
97100
for i := 1; i < list.Len() && i <= 0x7f; i++ {
98101
indexBuf = rlp.AppendUint64(indexBuf[:0], uint64(i))

core/types/hashing_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,9 +219,10 @@ func (d *hashToHumanReadable) Reset() {
219219
d.data = make([]byte, 0)
220220
}
221221

222-
func (d *hashToHumanReadable) Update(i []byte, i2 []byte) {
222+
func (d *hashToHumanReadable) Update(i []byte, i2 []byte) error {
223223
l := fmt.Sprintf("%x %x\n", i, i2)
224224
d.data = append(d.data, []byte(l)...)
225+
return nil
225226
}
226227

227228
func (d *hashToHumanReadable) Hash() common.Hash {

eth/protocols/snap/sync_test.go

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,7 @@ func defaultTrieRequestHandler(t *testPeer, requestId uint64, root common.Hash,
216216
for _, pathset := range paths {
217217
switch len(pathset) {
218218
case 1:
219-
blob, _, err := t.accountTrie.TryGetNode(pathset[0])
219+
blob, _, err := t.accountTrie.GetNode(pathset[0])
220220
if err != nil {
221221
t.logger.Info("Error handling req", "error", err)
222222
break
@@ -225,7 +225,7 @@ func defaultTrieRequestHandler(t *testPeer, requestId uint64, root common.Hash,
225225
default:
226226
account := t.storageTries[(common.BytesToHash(pathset[0]))]
227227
for _, path := range pathset[1:] {
228-
blob, _, err := account.TryGetNode(path)
228+
blob, _, err := account.GetNode(path)
229229
if err != nil {
230230
t.logger.Info("Error handling req", "error", err)
231231
break
@@ -1381,7 +1381,7 @@ func makeAccountTrieNoStorage(n int) (string, *trie.Trie, entrySlice) {
13811381
})
13821382
key := key32(i)
13831383
elem := &kv{key, value}
1384-
accTrie.Update(elem.k, elem.v)
1384+
accTrie.MustUpdate(elem.k, elem.v)
13851385
entries = append(entries, elem)
13861386
}
13871387
sort.Sort(entries)
@@ -1431,7 +1431,7 @@ func makeBoundaryAccountTrie(n int) (string, *trie.Trie, entrySlice) {
14311431
CodeHash: getCodeHash(uint64(i)),
14321432
})
14331433
elem := &kv{boundaries[i].Bytes(), value}
1434-
accTrie.Update(elem.k, elem.v)
1434+
accTrie.MustUpdate(elem.k, elem.v)
14351435
entries = append(entries, elem)
14361436
}
14371437
// Fill other accounts if required
@@ -1443,7 +1443,7 @@ func makeBoundaryAccountTrie(n int) (string, *trie.Trie, entrySlice) {
14431443
CodeHash: getCodeHash(i),
14441444
})
14451445
elem := &kv{key32(i), value}
1446-
accTrie.Update(elem.k, elem.v)
1446+
accTrie.MustUpdate(elem.k, elem.v)
14471447
entries = append(entries, elem)
14481448
}
14491449
sort.Sort(entries)
@@ -1487,7 +1487,7 @@ func makeAccountTrieWithStorageWithUniqueStorage(accounts, slots int, code bool)
14871487
CodeHash: codehash,
14881488
})
14891489
elem := &kv{key, value}
1490-
accTrie.Update(elem.k, elem.v)
1490+
accTrie.MustUpdate(elem.k, elem.v)
14911491
entries = append(entries, elem)
14921492

14931493
storageRoots[common.BytesToHash(key)] = stRoot
@@ -1551,7 +1551,7 @@ func makeAccountTrieWithStorage(accounts, slots int, code, boundary bool) (strin
15511551
CodeHash: codehash,
15521552
})
15531553
elem := &kv{key, value}
1554-
accTrie.Update(elem.k, elem.v)
1554+
accTrie.MustUpdate(elem.k, elem.v)
15551555
entries = append(entries, elem)
15561556

15571557
// we reuse the same one for all accounts
@@ -1599,7 +1599,7 @@ func makeStorageTrieWithSeed(owner common.Hash, n, seed uint64, db *trie.Databas
15991599
key := crypto.Keccak256Hash(slotKey[:])
16001600

16011601
elem := &kv{key[:], rlpSlotValue}
1602-
trie.Update(elem.k, elem.v)
1602+
trie.MustUpdate(elem.k, elem.v)
16031603
entries = append(entries, elem)
16041604
}
16051605
sort.Sort(entries)
@@ -1638,7 +1638,7 @@ func makeBoundaryStorageTrie(owner common.Hash, n int, db *trie.Database) (commo
16381638
val := []byte{0xde, 0xad, 0xbe, 0xef}
16391639

16401640
elem := &kv{key[:], val}
1641-
trie.Update(elem.k, elem.v)
1641+
trie.MustUpdate(elem.k, elem.v)
16421642
entries = append(entries, elem)
16431643
}
16441644
// Fill other slots if required
@@ -1650,7 +1650,7 @@ func makeBoundaryStorageTrie(owner common.Hash, n int, db *trie.Database) (commo
16501650
rlpSlotValue, _ := rlp.EncodeToBytes(common.TrimLeftZeroes(slotValue[:]))
16511651

16521652
elem := &kv{key[:], rlpSlotValue}
1653-
trie.Update(elem.k, elem.v)
1653+
trie.MustUpdate(elem.k, elem.v)
16541654
entries = append(entries, elem)
16551655
}
16561656
sort.Sort(entries)

les/server_handler.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,7 @@ func getAccount(triedb *trie.Database, root, hash common.Hash) (types.StateAccou
364364
if err != nil {
365365
return types.StateAccount{}, err
366366
}
367-
blob, err := trie.TryGet(hash[:])
367+
blob, err := trie.Get(hash[:])
368368
if err != nil {
369369
return types.StateAccount{}, err
370370
}

light/postprocess.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -206,8 +206,7 @@ func (c *ChtIndexerBackend) Process(ctx context.Context, header *types.Header) e
206206
var encNumber [8]byte
207207
binary.BigEndian.PutUint64(encNumber[:], num)
208208
data, _ := rlp.EncodeToBytes(ChtNode{hash, td})
209-
c.trie.Update(encNumber[:], data)
210-
return nil
209+
return c.trie.Update(encNumber[:], data)
211210
}
212211

213212
// Commit implements core.ChainIndexerBackend
@@ -450,10 +449,15 @@ func (b *BloomTrieIndexerBackend) Commit() error {
450449

451450
decompSize += uint64(len(decomp))
452451
compSize += uint64(len(comp))
452+
453+
var terr error
453454
if len(comp) > 0 {
454-
b.trie.Update(encKey[:], comp)
455+
terr = b.trie.Update(encKey[:], comp)
455456
} else {
456-
b.trie.Delete(encKey[:])
457+
terr = b.trie.Delete(encKey[:])
458+
}
459+
if terr != nil {
460+
return terr
457461
}
458462
}
459463
root, nodes := b.trie.Commit(false)

light/trie.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ func (t *odrTrie) GetStorage(_ common.Address, key []byte) ([]byte, error) {
109109
key = crypto.Keccak256(key)
110110
var res []byte
111111
err := t.do(key, func() (err error) {
112-
res, err = t.trie.TryGet(key)
112+
res, err = t.trie.Get(key)
113113
return err
114114
})
115115
return res, err
@@ -119,7 +119,7 @@ func (t *odrTrie) GetAccount(address common.Address) (*types.StateAccount, error
119119
var res types.StateAccount
120120
key := crypto.Keccak256(address.Bytes())
121121
err := t.do(key, func() (err error) {
122-
value, err := t.trie.TryGet(key)
122+
value, err := t.trie.Get(key)
123123
if err != nil {
124124
return err
125125
}
@@ -138,29 +138,29 @@ func (t *odrTrie) UpdateAccount(address common.Address, acc *types.StateAccount)
138138
return fmt.Errorf("decoding error in account update: %w", err)
139139
}
140140
return t.do(key, func() error {
141-
return t.trie.TryUpdate(key, value)
141+
return t.trie.Update(key, value)
142142
})
143143
}
144144

145145
func (t *odrTrie) UpdateStorage(_ common.Address, key, value []byte) error {
146146
key = crypto.Keccak256(key)
147147
return t.do(key, func() error {
148-
return t.trie.TryUpdate(key, value)
148+
return t.trie.Update(key, value)
149149
})
150150
}
151151

152152
func (t *odrTrie) DeleteStorage(_ common.Address, key []byte) error {
153153
key = crypto.Keccak256(key)
154154
return t.do(key, func() error {
155-
return t.trie.TryDelete(key)
155+
return t.trie.Delete(key)
156156
})
157157
}
158158

159159
// TryDeleteAccount abstracts an account deletion from the trie.
160160
func (t *odrTrie) DeleteAccount(address common.Address) error {
161161
key := crypto.Keccak256(address.Bytes())
162162
return t.do(key, func() error {
163-
return t.trie.TryDelete(key)
163+
return t.trie.Delete(key)
164164
})
165165
}
166166

tests/fuzzers/les/les-fuzzer.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,13 +93,13 @@ func makeTries() (chtTrie *trie.Trie, bloomTrie *trie.Trie, chtKeys, bloomKeys [
9393
// The element in CHT is <big-endian block number> -> <block hash>
9494
key := make([]byte, 8)
9595
binary.BigEndian.PutUint64(key, uint64(i+1))
96-
chtTrie.Update(key, []byte{0x1, 0xf})
96+
chtTrie.MustUpdate(key, []byte{0x1, 0xf})
9797
chtKeys = append(chtKeys, key)
9898

9999
// The element in Bloom trie is <2 byte bit index> + <big-endian block number> -> bloom
100100
key2 := make([]byte, 10)
101101
binary.BigEndian.PutUint64(key2[2:], uint64(i+1))
102-
bloomTrie.Update(key2, []byte{0x2, 0xe})
102+
bloomTrie.MustUpdate(key2, []byte{0x2, 0xe})
103103
bloomKeys = append(bloomKeys, key2)
104104
}
105105
return

tests/fuzzers/rangeproof/rangeproof-fuzzer.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,8 @@ func (f *fuzzer) randomTrie(n int) (*trie.Trie, map[string]*kv) {
6969
for i := byte(0); i < byte(size); i++ {
7070
value := &kv{common.LeftPadBytes([]byte{i}, 32), []byte{i}, false}
7171
value2 := &kv{common.LeftPadBytes([]byte{i + 10}, 32), []byte{i}, false}
72-
trie.Update(value.k, value.v)
73-
trie.Update(value2.k, value2.v)
72+
trie.MustUpdate(value.k, value.v)
73+
trie.MustUpdate(value2.k, value2.v)
7474
vals[string(value.k)] = value
7575
vals[string(value2.k)] = value2
7676
}
@@ -82,7 +82,7 @@ func (f *fuzzer) randomTrie(n int) (*trie.Trie, map[string]*kv) {
8282
k := f.randBytes(32)
8383
v := f.randBytes(20)
8484
value := &kv{k, v, false}
85-
trie.Update(k, v)
85+
trie.MustUpdate(k, v)
8686
vals[string(k)] = value
8787
if f.exhausted {
8888
return nil, nil

tests/fuzzers/stacktrie/trie_fuzzer.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ func (f *fuzzer) fuzz() int {
175175
}
176176
keys[string(k)] = struct{}{}
177177
vals = append(vals, kv{k: k, v: v})
178-
trieA.Update(k, v)
178+
trieA.MustUpdate(k, v)
179179
useful = true
180180
}
181181
if !useful {
@@ -195,7 +195,7 @@ func (f *fuzzer) fuzz() int {
195195
if f.debugging {
196196
fmt.Printf("{\"%#x\" , \"%#x\"} // stacktrie.Update\n", kv.k, kv.v)
197197
}
198-
trieB.Update(kv.k, kv.v)
198+
trieB.MustUpdate(kv.k, kv.v)
199199
}
200200
rootB := trieB.Hash()
201201
trieB.Commit()
@@ -223,7 +223,7 @@ func (f *fuzzer) fuzz() int {
223223
checked int
224224
)
225225
for _, kv := range vals {
226-
trieC.Update(kv.k, kv.v)
226+
trieC.MustUpdate(kv.k, kv.v)
227227
}
228228
rootC, _ := trieC.Commit()
229229
if rootA != rootC {

0 commit comments

Comments
 (0)