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