github.com/Cleverse/go-ethereum@v0.0.0-20220927095127-45113064e7f2/trie/trie_test.go (about) 1 // Copyright 2014 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 trie 18 19 import ( 20 "bytes" 21 "encoding/binary" 22 "errors" 23 "fmt" 24 "hash" 25 "math/big" 26 "math/rand" 27 "os" 28 "reflect" 29 "testing" 30 "testing/quick" 31 32 "github.com/davecgh/go-spew/spew" 33 "github.com/ethereum/go-ethereum/common" 34 "github.com/ethereum/go-ethereum/core/rawdb" 35 "github.com/ethereum/go-ethereum/core/types" 36 "github.com/ethereum/go-ethereum/crypto" 37 "github.com/ethereum/go-ethereum/ethdb" 38 "github.com/ethereum/go-ethereum/ethdb/leveldb" 39 "github.com/ethereum/go-ethereum/ethdb/memorydb" 40 "github.com/ethereum/go-ethereum/rlp" 41 "golang.org/x/crypto/sha3" 42 ) 43 44 func init() { 45 spew.Config.Indent = " " 46 spew.Config.DisableMethods = false 47 } 48 49 // Used for testing 50 func newEmpty() *Trie { 51 trie := NewEmpty(NewDatabase(memorydb.New())) 52 return trie 53 } 54 55 func TestEmptyTrie(t *testing.T) { 56 trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase())) 57 res := trie.Hash() 58 exp := emptyRoot 59 if res != exp { 60 t.Errorf("expected %x got %x", exp, res) 61 } 62 } 63 64 func TestNull(t *testing.T) { 65 trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase())) 66 key := make([]byte, 32) 67 value := []byte("test") 68 trie.Update(key, value) 69 if !bytes.Equal(trie.Get(key), value) { 70 t.Fatal("wrong value") 71 } 72 } 73 74 func TestMissingRoot(t *testing.T) { 75 trie, err := New(common.Hash{}, common.HexToHash("0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"), NewDatabase(memorydb.New())) 76 if trie != nil { 77 t.Error("New returned non-nil trie for invalid root") 78 } 79 if _, ok := err.(*MissingNodeError); !ok { 80 t.Errorf("New returned wrong error: %v", err) 81 } 82 } 83 84 func TestMissingNodeDisk(t *testing.T) { testMissingNode(t, false) } 85 func TestMissingNodeMemonly(t *testing.T) { testMissingNode(t, true) } 86 87 func testMissingNode(t *testing.T, memonly bool) { 88 diskdb := memorydb.New() 89 triedb := NewDatabase(diskdb) 90 91 trie := NewEmpty(triedb) 92 updateString(trie, "120000", "qwerqwerqwerqwerqwerqwerqwerqwer") 93 updateString(trie, "123456", "asdfasdfasdfasdfasdfasdfasdfasdf") 94 root, _, _ := trie.Commit(nil) 95 if !memonly { 96 triedb.Commit(root, true, nil) 97 } 98 99 trie, _ = New(common.Hash{}, root, triedb) 100 _, err := trie.TryGet([]byte("120000")) 101 if err != nil { 102 t.Errorf("Unexpected error: %v", err) 103 } 104 trie, _ = New(common.Hash{}, root, triedb) 105 _, err = trie.TryGet([]byte("120099")) 106 if err != nil { 107 t.Errorf("Unexpected error: %v", err) 108 } 109 trie, _ = New(common.Hash{}, root, triedb) 110 _, err = trie.TryGet([]byte("123456")) 111 if err != nil { 112 t.Errorf("Unexpected error: %v", err) 113 } 114 trie, _ = New(common.Hash{}, root, triedb) 115 err = trie.TryUpdate([]byte("120099"), []byte("zxcvzxcvzxcvzxcvzxcvzxcvzxcvzxcv")) 116 if err != nil { 117 t.Errorf("Unexpected error: %v", err) 118 } 119 trie, _ = New(common.Hash{}, root, triedb) 120 err = trie.TryDelete([]byte("123456")) 121 if err != nil { 122 t.Errorf("Unexpected error: %v", err) 123 } 124 125 hash := common.HexToHash("0xe1d943cc8f061a0c0b98162830b970395ac9315654824bf21b73b891365262f9") 126 if memonly { 127 delete(triedb.dirties, hash) 128 } else { 129 diskdb.Delete(hash[:]) 130 } 131 132 trie, _ = New(common.Hash{}, root, triedb) 133 _, err = trie.TryGet([]byte("120000")) 134 if _, ok := err.(*MissingNodeError); !ok { 135 t.Errorf("Wrong error: %v", err) 136 } 137 trie, _ = New(common.Hash{}, root, triedb) 138 _, err = trie.TryGet([]byte("120099")) 139 if _, ok := err.(*MissingNodeError); !ok { 140 t.Errorf("Wrong error: %v", err) 141 } 142 trie, _ = New(common.Hash{}, root, triedb) 143 _, err = trie.TryGet([]byte("123456")) 144 if err != nil { 145 t.Errorf("Unexpected error: %v", err) 146 } 147 trie, _ = New(common.Hash{}, root, triedb) 148 err = trie.TryUpdate([]byte("120099"), []byte("zxcv")) 149 if _, ok := err.(*MissingNodeError); !ok { 150 t.Errorf("Wrong error: %v", err) 151 } 152 trie, _ = New(common.Hash{}, root, triedb) 153 err = trie.TryDelete([]byte("123456")) 154 if _, ok := err.(*MissingNodeError); !ok { 155 t.Errorf("Wrong error: %v", err) 156 } 157 } 158 159 func TestInsert(t *testing.T) { 160 trie := newEmpty() 161 162 updateString(trie, "doe", "reindeer") 163 updateString(trie, "dog", "puppy") 164 updateString(trie, "dogglesworth", "cat") 165 166 exp := common.HexToHash("8aad789dff2f538bca5d8ea56e8abe10f4c7ba3a5dea95fea4cd6e7c3a1168d3") 167 root := trie.Hash() 168 if root != exp { 169 t.Errorf("case 1: exp %x got %x", exp, root) 170 } 171 172 trie = newEmpty() 173 updateString(trie, "A", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") 174 175 exp = common.HexToHash("d23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab") 176 root, _, err := trie.Commit(nil) 177 if err != nil { 178 t.Fatalf("commit error: %v", err) 179 } 180 if root != exp { 181 t.Errorf("case 2: exp %x got %x", exp, root) 182 } 183 } 184 185 func TestGet(t *testing.T) { 186 trie := newEmpty() 187 updateString(trie, "doe", "reindeer") 188 updateString(trie, "dog", "puppy") 189 updateString(trie, "dogglesworth", "cat") 190 191 for i := 0; i < 2; i++ { 192 res := getString(trie, "dog") 193 if !bytes.Equal(res, []byte("puppy")) { 194 t.Errorf("expected puppy got %x", res) 195 } 196 197 unknown := getString(trie, "unknown") 198 if unknown != nil { 199 t.Errorf("expected nil got %x", unknown) 200 } 201 202 if i == 1 { 203 return 204 } 205 trie.Commit(nil) 206 } 207 } 208 209 func TestDelete(t *testing.T) { 210 trie := newEmpty() 211 vals := []struct{ k, v string }{ 212 {"do", "verb"}, 213 {"ether", "wookiedoo"}, 214 {"horse", "stallion"}, 215 {"shaman", "horse"}, 216 {"doge", "coin"}, 217 {"ether", ""}, 218 {"dog", "puppy"}, 219 {"shaman", ""}, 220 } 221 for _, val := range vals { 222 if val.v != "" { 223 updateString(trie, val.k, val.v) 224 } else { 225 deleteString(trie, val.k) 226 } 227 } 228 229 hash := trie.Hash() 230 exp := common.HexToHash("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84") 231 if hash != exp { 232 t.Errorf("expected %x got %x", exp, hash) 233 } 234 } 235 236 func TestEmptyValues(t *testing.T) { 237 trie := newEmpty() 238 239 vals := []struct{ k, v string }{ 240 {"do", "verb"}, 241 {"ether", "wookiedoo"}, 242 {"horse", "stallion"}, 243 {"shaman", "horse"}, 244 {"doge", "coin"}, 245 {"ether", ""}, 246 {"dog", "puppy"}, 247 {"shaman", ""}, 248 } 249 for _, val := range vals { 250 updateString(trie, val.k, val.v) 251 } 252 253 hash := trie.Hash() 254 exp := common.HexToHash("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84") 255 if hash != exp { 256 t.Errorf("expected %x got %x", exp, hash) 257 } 258 } 259 260 func TestReplication(t *testing.T) { 261 trie := newEmpty() 262 vals := []struct{ k, v string }{ 263 {"do", "verb"}, 264 {"ether", "wookiedoo"}, 265 {"horse", "stallion"}, 266 {"shaman", "horse"}, 267 {"doge", "coin"}, 268 {"dog", "puppy"}, 269 {"somethingveryoddindeedthis is", "myothernodedata"}, 270 } 271 for _, val := range vals { 272 updateString(trie, val.k, val.v) 273 } 274 exp, _, err := trie.Commit(nil) 275 if err != nil { 276 t.Fatalf("commit error: %v", err) 277 } 278 279 // create a new trie on top of the database and check that lookups work. 280 trie2, err := New(common.Hash{}, exp, trie.db) 281 if err != nil { 282 t.Fatalf("can't recreate trie at %x: %v", exp, err) 283 } 284 for _, kv := range vals { 285 if string(getString(trie2, kv.k)) != kv.v { 286 t.Errorf("trie2 doesn't have %q => %q", kv.k, kv.v) 287 } 288 } 289 hash, _, err := trie2.Commit(nil) 290 if err != nil { 291 t.Fatalf("commit error: %v", err) 292 } 293 if hash != exp { 294 t.Errorf("root failure. expected %x got %x", exp, hash) 295 } 296 297 // perform some insertions on the new trie. 298 vals2 := []struct{ k, v string }{ 299 {"do", "verb"}, 300 {"ether", "wookiedoo"}, 301 {"horse", "stallion"}, 302 // {"shaman", "horse"}, 303 // {"doge", "coin"}, 304 // {"ether", ""}, 305 // {"dog", "puppy"}, 306 // {"somethingveryoddindeedthis is", "myothernodedata"}, 307 // {"shaman", ""}, 308 } 309 for _, val := range vals2 { 310 updateString(trie2, val.k, val.v) 311 } 312 if hash := trie2.Hash(); hash != exp { 313 t.Errorf("root failure. expected %x got %x", exp, hash) 314 } 315 } 316 317 func TestLargeValue(t *testing.T) { 318 trie := newEmpty() 319 trie.Update([]byte("key1"), []byte{99, 99, 99, 99}) 320 trie.Update([]byte("key2"), bytes.Repeat([]byte{1}, 32)) 321 trie.Hash() 322 } 323 324 // TestRandomCases tests som cases that were found via random fuzzing 325 func TestRandomCases(t *testing.T) { 326 var rt = []randTestStep{ 327 {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 0 328 {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 1 329 {op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000002")}, // step 2 330 {op: 2, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("")}, // step 3 331 {op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 4 332 {op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 5 333 {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 6 334 {op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 7 335 {op: 0, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("0000000000000008")}, // step 8 336 {op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000009")}, // step 9 337 {op: 2, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("")}, // step 10 338 {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 11 339 {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 12 340 {op: 0, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("000000000000000d")}, // step 13 341 {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 14 342 {op: 1, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("")}, // step 15 343 {op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 16 344 {op: 0, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("0000000000000011")}, // step 17 345 {op: 5, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 18 346 {op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 19 347 {op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000014")}, // step 20 348 {op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000015")}, // step 21 349 {op: 0, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("0000000000000016")}, // step 22 350 {op: 5, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 23 351 {op: 1, key: common.Hex2Bytes("980c393656413a15c8da01978ed9f89feb80b502f58f2d640e3a2f5f7a99a7018f1b573befd92053ac6f78fca4a87268"), value: common.Hex2Bytes("")}, // step 24 352 {op: 1, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("")}, // step 25 353 } 354 runRandTest(rt) 355 } 356 357 // randTest performs random trie operations. 358 // Instances of this test are created by Generate. 359 type randTest []randTestStep 360 361 type randTestStep struct { 362 op int 363 key []byte // for opUpdate, opDelete, opGet 364 value []byte // for opUpdate 365 err error // for debugging 366 } 367 368 const ( 369 opUpdate = iota 370 opDelete 371 opGet 372 opCommit 373 opHash 374 opReset 375 opItercheckhash 376 opNodeDiff 377 opMax // boundary value, not an actual op 378 ) 379 380 func (randTest) Generate(r *rand.Rand, size int) reflect.Value { 381 var allKeys [][]byte 382 genKey := func() []byte { 383 if len(allKeys) < 2 || r.Intn(100) < 10 { 384 // new key 385 key := make([]byte, r.Intn(50)) 386 r.Read(key) 387 allKeys = append(allKeys, key) 388 return key 389 } 390 // use existing key 391 return allKeys[r.Intn(len(allKeys))] 392 } 393 394 var steps randTest 395 for i := 0; i < size; i++ { 396 step := randTestStep{op: r.Intn(opMax)} 397 switch step.op { 398 case opUpdate: 399 step.key = genKey() 400 step.value = make([]byte, 8) 401 binary.BigEndian.PutUint64(step.value, uint64(i)) 402 case opGet, opDelete: 403 step.key = genKey() 404 } 405 steps = append(steps, step) 406 } 407 return reflect.ValueOf(steps) 408 } 409 410 func runRandTest(rt randTest) bool { 411 var ( 412 triedb = NewDatabase(memorydb.New()) 413 tr = NewEmpty(triedb) 414 values = make(map[string]string) // tracks content of the trie 415 origTrie = NewEmpty(triedb) 416 ) 417 tr.tracer = newTracer() 418 419 for i, step := range rt { 420 // fmt.Printf("{op: %d, key: common.Hex2Bytes(\"%x\"), value: common.Hex2Bytes(\"%x\")}, // step %d\n", 421 // step.op, step.key, step.value, i) 422 423 switch step.op { 424 case opUpdate: 425 tr.Update(step.key, step.value) 426 values[string(step.key)] = string(step.value) 427 case opDelete: 428 tr.Delete(step.key) 429 delete(values, string(step.key)) 430 case opGet: 431 v := tr.Get(step.key) 432 want := values[string(step.key)] 433 if string(v) != want { 434 rt[i].err = fmt.Errorf("mismatch for key %#x, got %#x want %#x", step.key, v, want) 435 } 436 case opCommit: 437 _, _, rt[i].err = tr.Commit(nil) 438 origTrie = tr.Copy() 439 case opHash: 440 tr.Hash() 441 case opReset: 442 hash, _, err := tr.Commit(nil) 443 if err != nil { 444 rt[i].err = err 445 return false 446 } 447 newtr, err := New(common.Hash{}, hash, triedb) 448 if err != nil { 449 rt[i].err = err 450 return false 451 } 452 tr = newtr 453 tr.tracer = newTracer() 454 455 origTrie = tr.Copy() 456 case opItercheckhash: 457 checktr := NewEmpty(triedb) 458 it := NewIterator(tr.NodeIterator(nil)) 459 for it.Next() { 460 checktr.Update(it.Key, it.Value) 461 } 462 if tr.Hash() != checktr.Hash() { 463 rt[i].err = fmt.Errorf("hash mismatch in opItercheckhash") 464 } 465 case opNodeDiff: 466 var ( 467 inserted = tr.tracer.insertList() 468 deleted = tr.tracer.deleteList() 469 origIter = origTrie.NodeIterator(nil) 470 curIter = tr.NodeIterator(nil) 471 origSeen = make(map[string]struct{}) 472 curSeen = make(map[string]struct{}) 473 ) 474 for origIter.Next(true) { 475 if origIter.Leaf() { 476 continue 477 } 478 origSeen[string(origIter.Path())] = struct{}{} 479 } 480 for curIter.Next(true) { 481 if curIter.Leaf() { 482 continue 483 } 484 curSeen[string(curIter.Path())] = struct{}{} 485 } 486 var ( 487 insertExp = make(map[string]struct{}) 488 deleteExp = make(map[string]struct{}) 489 ) 490 for path := range curSeen { 491 _, present := origSeen[path] 492 if !present { 493 insertExp[path] = struct{}{} 494 } 495 } 496 for path := range origSeen { 497 _, present := curSeen[path] 498 if !present { 499 deleteExp[path] = struct{}{} 500 } 501 } 502 if len(insertExp) != len(inserted) { 503 rt[i].err = fmt.Errorf("insert set mismatch") 504 } 505 if len(deleteExp) != len(deleted) { 506 rt[i].err = fmt.Errorf("delete set mismatch") 507 } 508 for _, insert := range inserted { 509 if _, present := insertExp[string(insert)]; !present { 510 rt[i].err = fmt.Errorf("missing inserted node") 511 } 512 } 513 for _, del := range deleted { 514 if _, present := deleteExp[string(del)]; !present { 515 rt[i].err = fmt.Errorf("missing deleted node") 516 } 517 } 518 } 519 // Abort the test on error. 520 if rt[i].err != nil { 521 return false 522 } 523 } 524 return true 525 } 526 527 func TestRandom(t *testing.T) { 528 if err := quick.Check(runRandTest, nil); err != nil { 529 if cerr, ok := err.(*quick.CheckError); ok { 530 t.Fatalf("random test iteration %d failed: %s", cerr.Count, spew.Sdump(cerr.In)) 531 } 532 t.Fatal(err) 533 } 534 } 535 536 func BenchmarkGet(b *testing.B) { benchGet(b, false) } 537 func BenchmarkGetDB(b *testing.B) { benchGet(b, true) } 538 func BenchmarkUpdateBE(b *testing.B) { benchUpdate(b, binary.BigEndian) } 539 func BenchmarkUpdateLE(b *testing.B) { benchUpdate(b, binary.LittleEndian) } 540 541 const benchElemCount = 20000 542 543 func benchGet(b *testing.B, commit bool) { 544 trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase())) 545 if commit { 546 tmpdb := tempDB(b) 547 trie = NewEmpty(tmpdb) 548 } 549 k := make([]byte, 32) 550 for i := 0; i < benchElemCount; i++ { 551 binary.LittleEndian.PutUint64(k, uint64(i)) 552 trie.Update(k, k) 553 } 554 binary.LittleEndian.PutUint64(k, benchElemCount/2) 555 if commit { 556 trie.Commit(nil) 557 } 558 559 b.ResetTimer() 560 for i := 0; i < b.N; i++ { 561 trie.Get(k) 562 } 563 b.StopTimer() 564 565 if commit { 566 ldb := trie.db.diskdb.(*leveldb.Database) 567 ldb.Close() 568 os.RemoveAll(ldb.Path()) 569 } 570 } 571 572 func benchUpdate(b *testing.B, e binary.ByteOrder) *Trie { 573 trie := newEmpty() 574 k := make([]byte, 32) 575 b.ReportAllocs() 576 for i := 0; i < b.N; i++ { 577 e.PutUint64(k, uint64(i)) 578 trie.Update(k, k) 579 } 580 return trie 581 } 582 583 // Benchmarks the trie hashing. Since the trie caches the result of any operation, 584 // we cannot use b.N as the number of hashing rouns, since all rounds apart from 585 // the first one will be NOOP. As such, we'll use b.N as the number of account to 586 // insert into the trie before measuring the hashing. 587 // BenchmarkHash-6 288680 4561 ns/op 682 B/op 9 allocs/op 588 // BenchmarkHash-6 275095 4800 ns/op 685 B/op 9 allocs/op 589 // pure hasher: 590 // BenchmarkHash-6 319362 4230 ns/op 675 B/op 9 allocs/op 591 // BenchmarkHash-6 257460 4674 ns/op 689 B/op 9 allocs/op 592 // With hashing in-between and pure hasher: 593 // BenchmarkHash-6 225417 7150 ns/op 982 B/op 12 allocs/op 594 // BenchmarkHash-6 220378 6197 ns/op 983 B/op 12 allocs/op 595 // same with old hasher 596 // BenchmarkHash-6 229758 6437 ns/op 981 B/op 12 allocs/op 597 // BenchmarkHash-6 212610 7137 ns/op 986 B/op 12 allocs/op 598 func BenchmarkHash(b *testing.B) { 599 // Create a realistic account trie to hash. We're first adding and hashing N 600 // entries, then adding N more. 601 addresses, accounts := makeAccounts(2 * b.N) 602 // Insert the accounts into the trie and hash it 603 trie := newEmpty() 604 i := 0 605 for ; i < len(addresses)/2; i++ { 606 trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i]) 607 } 608 trie.Hash() 609 for ; i < len(addresses); i++ { 610 trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i]) 611 } 612 b.ResetTimer() 613 b.ReportAllocs() 614 //trie.hashRoot(nil, nil) 615 trie.Hash() 616 } 617 618 // Benchmarks the trie Commit following a Hash. Since the trie caches the result of any operation, 619 // we cannot use b.N as the number of hashing rouns, since all rounds apart from 620 // the first one will be NOOP. As such, we'll use b.N as the number of account to 621 // insert into the trie before measuring the hashing. 622 func BenchmarkCommitAfterHash(b *testing.B) { 623 b.Run("no-onleaf", func(b *testing.B) { 624 benchmarkCommitAfterHash(b, nil) 625 }) 626 var a types.StateAccount 627 onleaf := func(paths [][]byte, hexpath []byte, leaf []byte, parent common.Hash, parentPath []byte) error { 628 rlp.DecodeBytes(leaf, &a) 629 return nil 630 } 631 b.Run("with-onleaf", func(b *testing.B) { 632 benchmarkCommitAfterHash(b, onleaf) 633 }) 634 } 635 636 func benchmarkCommitAfterHash(b *testing.B, onleaf LeafCallback) { 637 // Make the random benchmark deterministic 638 addresses, accounts := makeAccounts(b.N) 639 trie := newEmpty() 640 for i := 0; i < len(addresses); i++ { 641 trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i]) 642 } 643 // Insert the accounts into the trie and hash it 644 trie.Hash() 645 b.ResetTimer() 646 b.ReportAllocs() 647 trie.Commit(onleaf) 648 } 649 650 func TestTinyTrie(t *testing.T) { 651 // Create a realistic account trie to hash 652 _, accounts := makeAccounts(5) 653 trie := newEmpty() 654 trie.Update(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001337"), accounts[3]) 655 if exp, root := common.HexToHash("8c6a85a4d9fda98feff88450299e574e5378e32391f75a055d470ac0653f1005"), trie.Hash(); exp != root { 656 t.Errorf("1: got %x, exp %x", root, exp) 657 } 658 trie.Update(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001338"), accounts[4]) 659 if exp, root := common.HexToHash("ec63b967e98a5720e7f720482151963982890d82c9093c0d486b7eb8883a66b1"), trie.Hash(); exp != root { 660 t.Errorf("2: got %x, exp %x", root, exp) 661 } 662 trie.Update(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001339"), accounts[4]) 663 if exp, root := common.HexToHash("0608c1d1dc3905fa22204c7a0e43644831c3b6d3def0f274be623a948197e64a"), trie.Hash(); exp != root { 664 t.Errorf("3: got %x, exp %x", root, exp) 665 } 666 checktr := NewEmpty(trie.db) 667 it := NewIterator(trie.NodeIterator(nil)) 668 for it.Next() { 669 checktr.Update(it.Key, it.Value) 670 } 671 if troot, itroot := trie.Hash(), checktr.Hash(); troot != itroot { 672 t.Fatalf("hash mismatch in opItercheckhash, trie: %x, check: %x", troot, itroot) 673 } 674 } 675 676 func TestCommitAfterHash(t *testing.T) { 677 // Create a realistic account trie to hash 678 addresses, accounts := makeAccounts(1000) 679 trie := newEmpty() 680 for i := 0; i < len(addresses); i++ { 681 trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i]) 682 } 683 // Insert the accounts into the trie and hash it 684 trie.Hash() 685 trie.Commit(nil) 686 root := trie.Hash() 687 exp := common.HexToHash("72f9d3f3fe1e1dd7b8936442e7642aef76371472d94319900790053c493f3fe6") 688 if exp != root { 689 t.Errorf("got %x, exp %x", root, exp) 690 } 691 root, _, _ = trie.Commit(nil) 692 if exp != root { 693 t.Errorf("got %x, exp %x", root, exp) 694 } 695 } 696 697 func makeAccounts(size int) (addresses [][20]byte, accounts [][]byte) { 698 // Make the random benchmark deterministic 699 random := rand.New(rand.NewSource(0)) 700 // Create a realistic account trie to hash 701 addresses = make([][20]byte, size) 702 for i := 0; i < len(addresses); i++ { 703 data := make([]byte, 20) 704 random.Read(data) 705 copy(addresses[i][:], data) 706 } 707 accounts = make([][]byte, len(addresses)) 708 for i := 0; i < len(accounts); i++ { 709 var ( 710 nonce = uint64(random.Int63()) 711 root = emptyRoot 712 code = crypto.Keccak256(nil) 713 ) 714 // The big.Rand function is not deterministic with regards to 64 vs 32 bit systems, 715 // and will consume different amount of data from the rand source. 716 //balance = new(big.Int).Rand(random, new(big.Int).Exp(common.Big2, common.Big256, nil)) 717 // Therefore, we instead just read via byte buffer 718 numBytes := random.Uint32() % 33 // [0, 32] bytes 719 balanceBytes := make([]byte, numBytes) 720 random.Read(balanceBytes) 721 balance := new(big.Int).SetBytes(balanceBytes) 722 data, _ := rlp.EncodeToBytes(&types.StateAccount{Nonce: nonce, Balance: balance, Root: root, CodeHash: code}) 723 accounts[i] = data 724 } 725 return addresses, accounts 726 } 727 728 // spongeDb is a dummy db backend which accumulates writes in a sponge 729 type spongeDb struct { 730 sponge hash.Hash 731 id string 732 journal []string 733 } 734 735 func (s *spongeDb) Has(key []byte) (bool, error) { panic("implement me") } 736 func (s *spongeDb) Get(key []byte) ([]byte, error) { return nil, errors.New("no such elem") } 737 func (s *spongeDb) Delete(key []byte) error { panic("implement me") } 738 func (s *spongeDb) NewBatch() ethdb.Batch { return &spongeBatch{s} } 739 func (s *spongeDb) NewBatchWithSize(size int) ethdb.Batch { return &spongeBatch{s} } 740 func (s *spongeDb) NewSnapshot() (ethdb.Snapshot, error) { panic("implement me") } 741 func (s *spongeDb) Stat(property string) (string, error) { panic("implement me") } 742 func (s *spongeDb) Compact(start []byte, limit []byte) error { panic("implement me") } 743 func (s *spongeDb) Close() error { return nil } 744 func (s *spongeDb) Put(key []byte, value []byte) error { 745 valbrief := value 746 if len(valbrief) > 8 { 747 valbrief = valbrief[:8] 748 } 749 s.journal = append(s.journal, fmt.Sprintf("%v: PUT([%x...], [%d bytes] %x...)\n", s.id, key[:8], len(value), valbrief)) 750 s.sponge.Write(key) 751 s.sponge.Write(value) 752 return nil 753 } 754 func (s *spongeDb) NewIterator(prefix []byte, start []byte) ethdb.Iterator { panic("implement me") } 755 756 // spongeBatch is a dummy batch which immediately writes to the underlying spongedb 757 type spongeBatch struct { 758 db *spongeDb 759 } 760 761 func (b *spongeBatch) Put(key, value []byte) error { 762 b.db.Put(key, value) 763 return nil 764 } 765 func (b *spongeBatch) Delete(key []byte) error { panic("implement me") } 766 func (b *spongeBatch) ValueSize() int { return 100 } 767 func (b *spongeBatch) Write() error { return nil } 768 func (b *spongeBatch) Reset() {} 769 func (b *spongeBatch) Replay(w ethdb.KeyValueWriter) error { return nil } 770 771 // TestCommitSequence tests that the trie.Commit operation writes the elements of the trie 772 // in the expected order, and calls the callbacks in the expected order. 773 // The test data was based on the 'master' code, and is basically random. It can be used 774 // to check whether changes to the trie modifies the write order or data in any way. 775 func TestCommitSequence(t *testing.T) { 776 for i, tc := range []struct { 777 count int 778 expWriteSeqHash []byte 779 expCallbackSeqHash []byte 780 }{ 781 {20, common.FromHex("873c78df73d60e59d4a2bcf3716e8bfe14554549fea2fc147cb54129382a8066"), 782 common.FromHex("ff00f91ac05df53b82d7f178d77ada54fd0dca64526f537034a5dbe41b17df2a")}, 783 {200, common.FromHex("ba03d891bb15408c940eea5ee3d54d419595102648d02774a0268d892add9c8e"), 784 common.FromHex("f3cd509064c8d319bbdd1c68f511850a902ad275e6ed5bea11547e23d492a926")}, 785 {2000, common.FromHex("f7a184f20df01c94f09537401d11e68d97ad0c00115233107f51b9c287ce60c7"), 786 common.FromHex("ff795ea898ba1e4cfed4a33b4cf5535a347a02cf931f88d88719faf810f9a1c9")}, 787 } { 788 addresses, accounts := makeAccounts(tc.count) 789 // This spongeDb is used to check the sequence of disk-db-writes 790 s := &spongeDb{sponge: sha3.NewLegacyKeccak256()} 791 db := NewDatabase(s) 792 trie := NewEmpty(db) 793 // Another sponge is used to check the callback-sequence 794 callbackSponge := sha3.NewLegacyKeccak256() 795 // Fill the trie with elements 796 for i := 0; i < tc.count; i++ { 797 trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i]) 798 } 799 // Flush trie -> database 800 root, _, _ := trie.Commit(nil) 801 // Flush memdb -> disk (sponge) 802 db.Commit(root, false, func(c common.Hash) { 803 // And spongify the callback-order 804 callbackSponge.Write(c[:]) 805 }) 806 if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) { 807 t.Errorf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp) 808 } 809 if got, exp := callbackSponge.Sum(nil), tc.expCallbackSeqHash; !bytes.Equal(got, exp) { 810 t.Errorf("test %d, call back sequence wrong:\ngot: %x exp %x\n", i, got, exp) 811 } 812 } 813 } 814 815 // TestCommitSequenceRandomBlobs is identical to TestCommitSequence 816 // but uses random blobs instead of 'accounts' 817 func TestCommitSequenceRandomBlobs(t *testing.T) { 818 for i, tc := range []struct { 819 count int 820 expWriteSeqHash []byte 821 expCallbackSeqHash []byte 822 }{ 823 {20, common.FromHex("8e4a01548551d139fa9e833ebc4e66fc1ba40a4b9b7259d80db32cff7b64ebbc"), 824 common.FromHex("450238d73bc36dc6cc6f926987e5428535e64be403877c4560e238a52749ba24")}, 825 {200, common.FromHex("6869b4e7b95f3097a19ddb30ff735f922b915314047e041614df06958fc50554"), 826 common.FromHex("0ace0b03d6cb8c0b82f6289ef5b1a1838306b455a62dafc63cada8e2924f2550")}, 827 {2000, common.FromHex("444200e6f4e2df49f77752f629a96ccf7445d4698c164f962bbd85a0526ef424"), 828 common.FromHex("117d30dafaa62a1eed498c3dfd70982b377ba2b46dd3e725ed6120c80829e518")}, 829 } { 830 prng := rand.New(rand.NewSource(int64(i))) 831 // This spongeDb is used to check the sequence of disk-db-writes 832 s := &spongeDb{sponge: sha3.NewLegacyKeccak256()} 833 db := NewDatabase(s) 834 trie := NewEmpty(db) 835 // Another sponge is used to check the callback-sequence 836 callbackSponge := sha3.NewLegacyKeccak256() 837 // Fill the trie with elements 838 for i := 0; i < tc.count; i++ { 839 key := make([]byte, 32) 840 var val []byte 841 // 50% short elements, 50% large elements 842 if prng.Intn(2) == 0 { 843 val = make([]byte, 1+prng.Intn(32)) 844 } else { 845 val = make([]byte, 1+prng.Intn(4096)) 846 } 847 prng.Read(key) 848 prng.Read(val) 849 trie.Update(key, val) 850 } 851 // Flush trie -> database 852 root, _, _ := trie.Commit(nil) 853 // Flush memdb -> disk (sponge) 854 db.Commit(root, false, func(c common.Hash) { 855 // And spongify the callback-order 856 callbackSponge.Write(c[:]) 857 }) 858 if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) { 859 t.Fatalf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp) 860 } 861 if got, exp := callbackSponge.Sum(nil), tc.expCallbackSeqHash; !bytes.Equal(got, exp) { 862 t.Fatalf("test %d, call back sequence wrong:\ngot: %x exp %x\n", i, got, exp) 863 } 864 } 865 } 866 867 func TestCommitSequenceStackTrie(t *testing.T) { 868 for count := 1; count < 200; count++ { 869 prng := rand.New(rand.NewSource(int64(count))) 870 // This spongeDb is used to check the sequence of disk-db-writes 871 s := &spongeDb{sponge: sha3.NewLegacyKeccak256(), id: "a"} 872 db := NewDatabase(s) 873 trie := NewEmpty(db) 874 // Another sponge is used for the stacktrie commits 875 stackTrieSponge := &spongeDb{sponge: sha3.NewLegacyKeccak256(), id: "b"} 876 stTrie := NewStackTrie(stackTrieSponge) 877 // Fill the trie with elements 878 for i := 1; i < count; i++ { 879 // For the stack trie, we need to do inserts in proper order 880 key := make([]byte, 32) 881 binary.BigEndian.PutUint64(key, uint64(i)) 882 var val []byte 883 // 50% short elements, 50% large elements 884 if prng.Intn(2) == 0 { 885 val = make([]byte, 1+prng.Intn(32)) 886 } else { 887 val = make([]byte, 1+prng.Intn(1024)) 888 } 889 prng.Read(val) 890 trie.TryUpdate(key, val) 891 stTrie.TryUpdate(key, val) 892 } 893 // Flush trie -> database 894 root, _, _ := trie.Commit(nil) 895 // Flush memdb -> disk (sponge) 896 db.Commit(root, false, nil) 897 // And flush stacktrie -> disk 898 stRoot, err := stTrie.Commit() 899 if err != nil { 900 t.Fatalf("Failed to commit stack trie %v", err) 901 } 902 if stRoot != root { 903 t.Fatalf("root wrong, got %x exp %x", stRoot, root) 904 } 905 if got, exp := stackTrieSponge.sponge.Sum(nil), s.sponge.Sum(nil); !bytes.Equal(got, exp) { 906 // Show the journal 907 t.Logf("Expected:") 908 for i, v := range s.journal { 909 t.Logf("op %d: %v", i, v) 910 } 911 t.Logf("Stacktrie:") 912 for i, v := range stackTrieSponge.journal { 913 t.Logf("op %d: %v", i, v) 914 } 915 t.Fatalf("test %d, disk write sequence wrong:\ngot %x exp %x\n", count, got, exp) 916 } 917 } 918 } 919 920 // TestCommitSequenceSmallRoot tests that a trie which is essentially only a 921 // small (<32 byte) shortnode with an included value is properly committed to a 922 // database. 923 // This case might not matter, since in practice, all keys are 32 bytes, which means 924 // that even a small trie which contains a leaf will have an extension making it 925 // not fit into 32 bytes, rlp-encoded. However, it's still the correct thing to do. 926 func TestCommitSequenceSmallRoot(t *testing.T) { 927 s := &spongeDb{sponge: sha3.NewLegacyKeccak256(), id: "a"} 928 db := NewDatabase(s) 929 trie := NewEmpty(db) 930 // Another sponge is used for the stacktrie commits 931 stackTrieSponge := &spongeDb{sponge: sha3.NewLegacyKeccak256(), id: "b"} 932 stTrie := NewStackTrie(stackTrieSponge) 933 // Add a single small-element to the trie(s) 934 key := make([]byte, 5) 935 key[0] = 1 936 trie.TryUpdate(key, []byte{0x1}) 937 stTrie.TryUpdate(key, []byte{0x1}) 938 // Flush trie -> database 939 root, _, _ := trie.Commit(nil) 940 // Flush memdb -> disk (sponge) 941 db.Commit(root, false, nil) 942 // And flush stacktrie -> disk 943 stRoot, err := stTrie.Commit() 944 if err != nil { 945 t.Fatalf("Failed to commit stack trie %v", err) 946 } 947 if stRoot != root { 948 t.Fatalf("root wrong, got %x exp %x", stRoot, root) 949 } 950 951 t.Logf("root: %x\n", stRoot) 952 if got, exp := stackTrieSponge.sponge.Sum(nil), s.sponge.Sum(nil); !bytes.Equal(got, exp) { 953 t.Fatalf("test, disk write sequence wrong:\ngot %x exp %x\n", got, exp) 954 } 955 } 956 957 // BenchmarkCommitAfterHashFixedSize benchmarks the Commit (after Hash) of a fixed number of updates to a trie. 958 // This benchmark is meant to capture the difference on efficiency of small versus large changes. Typically, 959 // storage tries are small (a couple of entries), whereas the full post-block account trie update is large (a couple 960 // of thousand entries) 961 func BenchmarkHashFixedSize(b *testing.B) { 962 b.Run("10", func(b *testing.B) { 963 b.StopTimer() 964 acc, add := makeAccounts(20) 965 for i := 0; i < b.N; i++ { 966 benchmarkHashFixedSize(b, acc, add) 967 } 968 }) 969 b.Run("100", func(b *testing.B) { 970 b.StopTimer() 971 acc, add := makeAccounts(100) 972 for i := 0; i < b.N; i++ { 973 benchmarkHashFixedSize(b, acc, add) 974 } 975 }) 976 977 b.Run("1K", func(b *testing.B) { 978 b.StopTimer() 979 acc, add := makeAccounts(1000) 980 for i := 0; i < b.N; i++ { 981 benchmarkHashFixedSize(b, acc, add) 982 } 983 }) 984 b.Run("10K", func(b *testing.B) { 985 b.StopTimer() 986 acc, add := makeAccounts(10000) 987 for i := 0; i < b.N; i++ { 988 benchmarkHashFixedSize(b, acc, add) 989 } 990 }) 991 b.Run("100K", func(b *testing.B) { 992 b.StopTimer() 993 acc, add := makeAccounts(100000) 994 for i := 0; i < b.N; i++ { 995 benchmarkHashFixedSize(b, acc, add) 996 } 997 }) 998 } 999 1000 func benchmarkHashFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) { 1001 b.ReportAllocs() 1002 trie := newEmpty() 1003 for i := 0; i < len(addresses); i++ { 1004 trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i]) 1005 } 1006 // Insert the accounts into the trie and hash it 1007 b.StartTimer() 1008 trie.Hash() 1009 b.StopTimer() 1010 } 1011 1012 func BenchmarkCommitAfterHashFixedSize(b *testing.B) { 1013 b.Run("10", func(b *testing.B) { 1014 b.StopTimer() 1015 acc, add := makeAccounts(20) 1016 for i := 0; i < b.N; i++ { 1017 benchmarkCommitAfterHashFixedSize(b, acc, add) 1018 } 1019 }) 1020 b.Run("100", func(b *testing.B) { 1021 b.StopTimer() 1022 acc, add := makeAccounts(100) 1023 for i := 0; i < b.N; i++ { 1024 benchmarkCommitAfterHashFixedSize(b, acc, add) 1025 } 1026 }) 1027 1028 b.Run("1K", func(b *testing.B) { 1029 b.StopTimer() 1030 acc, add := makeAccounts(1000) 1031 for i := 0; i < b.N; i++ { 1032 benchmarkCommitAfterHashFixedSize(b, acc, add) 1033 } 1034 }) 1035 b.Run("10K", func(b *testing.B) { 1036 b.StopTimer() 1037 acc, add := makeAccounts(10000) 1038 for i := 0; i < b.N; i++ { 1039 benchmarkCommitAfterHashFixedSize(b, acc, add) 1040 } 1041 }) 1042 b.Run("100K", func(b *testing.B) { 1043 b.StopTimer() 1044 acc, add := makeAccounts(100000) 1045 for i := 0; i < b.N; i++ { 1046 benchmarkCommitAfterHashFixedSize(b, acc, add) 1047 } 1048 }) 1049 } 1050 1051 func benchmarkCommitAfterHashFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) { 1052 b.ReportAllocs() 1053 trie := newEmpty() 1054 for i := 0; i < len(addresses); i++ { 1055 trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i]) 1056 } 1057 // Insert the accounts into the trie and hash it 1058 trie.Hash() 1059 b.StartTimer() 1060 trie.Commit(nil) 1061 b.StopTimer() 1062 } 1063 1064 func BenchmarkDerefRootFixedSize(b *testing.B) { 1065 b.Run("10", func(b *testing.B) { 1066 b.StopTimer() 1067 acc, add := makeAccounts(20) 1068 for i := 0; i < b.N; i++ { 1069 benchmarkDerefRootFixedSize(b, acc, add) 1070 } 1071 }) 1072 b.Run("100", func(b *testing.B) { 1073 b.StopTimer() 1074 acc, add := makeAccounts(100) 1075 for i := 0; i < b.N; i++ { 1076 benchmarkDerefRootFixedSize(b, acc, add) 1077 } 1078 }) 1079 1080 b.Run("1K", func(b *testing.B) { 1081 b.StopTimer() 1082 acc, add := makeAccounts(1000) 1083 for i := 0; i < b.N; i++ { 1084 benchmarkDerefRootFixedSize(b, acc, add) 1085 } 1086 }) 1087 b.Run("10K", func(b *testing.B) { 1088 b.StopTimer() 1089 acc, add := makeAccounts(10000) 1090 for i := 0; i < b.N; i++ { 1091 benchmarkDerefRootFixedSize(b, acc, add) 1092 } 1093 }) 1094 b.Run("100K", func(b *testing.B) { 1095 b.StopTimer() 1096 acc, add := makeAccounts(100000) 1097 for i := 0; i < b.N; i++ { 1098 benchmarkDerefRootFixedSize(b, acc, add) 1099 } 1100 }) 1101 } 1102 1103 func benchmarkDerefRootFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) { 1104 b.ReportAllocs() 1105 trie := newEmpty() 1106 for i := 0; i < len(addresses); i++ { 1107 trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i]) 1108 } 1109 h := trie.Hash() 1110 trie.Commit(nil) 1111 b.StartTimer() 1112 trie.db.Dereference(h) 1113 b.StopTimer() 1114 } 1115 1116 func tempDB(tb testing.TB) *Database { 1117 dir := tb.TempDir() 1118 diskdb, err := leveldb.New(dir, 256, 0, "", false) 1119 if err != nil { 1120 panic(fmt.Sprintf("can't create temporary database: %v", err)) 1121 } 1122 return NewDatabase(diskdb) 1123 } 1124 1125 func getString(trie *Trie, k string) []byte { 1126 return trie.Get([]byte(k)) 1127 } 1128 1129 func updateString(trie *Trie, k, v string) { 1130 trie.Update([]byte(k), []byte(v)) 1131 } 1132 1133 func deleteString(trie *Trie, k string) { 1134 trie.Delete([]byte(k)) 1135 } 1136 1137 func TestDecodeNode(t *testing.T) { 1138 t.Parallel() 1139 var ( 1140 hash = make([]byte, 20) 1141 elems = make([]byte, 20) 1142 ) 1143 for i := 0; i < 5000000; i++ { 1144 rand.Read(hash) 1145 rand.Read(elems) 1146 decodeNode(hash, elems) 1147 } 1148 }