github.com/unicornultrafoundation/go-u2u@v1.0.0-rc1.0.20240205080301-e74a83d3fadc/eth/protocols/snap/sync_test.go (about) 1 // Copyright 2020 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 snap 18 19 import ( 20 "bytes" 21 "crypto/rand" 22 "encoding/binary" 23 "fmt" 24 "math/big" 25 "sort" 26 "sync" 27 "testing" 28 "time" 29 30 "github.com/unicornultrafoundation/go-u2u/common" 31 "github.com/unicornultrafoundation/go-u2u/core/rawdb" 32 "github.com/unicornultrafoundation/go-u2u/core/state" 33 "github.com/unicornultrafoundation/go-u2u/crypto" 34 "github.com/unicornultrafoundation/go-u2u/ethdb" 35 "github.com/unicornultrafoundation/go-u2u/light" 36 "github.com/unicornultrafoundation/go-u2u/log" 37 "github.com/unicornultrafoundation/go-u2u/rlp" 38 "github.com/unicornultrafoundation/go-u2u/trie" 39 "golang.org/x/crypto/sha3" 40 ) 41 42 func TestHashing(t *testing.T) { 43 t.Parallel() 44 45 var bytecodes = make([][]byte, 10) 46 for i := 0; i < len(bytecodes); i++ { 47 buf := make([]byte, 100) 48 rand.Read(buf) 49 bytecodes[i] = buf 50 } 51 var want, got string 52 var old = func() { 53 hasher := sha3.NewLegacyKeccak256() 54 for i := 0; i < len(bytecodes); i++ { 55 hasher.Reset() 56 hasher.Write(bytecodes[i]) 57 hash := hasher.Sum(nil) 58 got = fmt.Sprintf("%v\n%v", got, hash) 59 } 60 } 61 var new = func() { 62 hasher := sha3.NewLegacyKeccak256().(crypto.KeccakState) 63 var hash = make([]byte, 32) 64 for i := 0; i < len(bytecodes); i++ { 65 hasher.Reset() 66 hasher.Write(bytecodes[i]) 67 hasher.Read(hash) 68 want = fmt.Sprintf("%v\n%v", want, hash) 69 } 70 } 71 old() 72 new() 73 if want != got { 74 t.Errorf("want\n%v\ngot\n%v\n", want, got) 75 } 76 } 77 78 func BenchmarkHashing(b *testing.B) { 79 var bytecodes = make([][]byte, 10000) 80 for i := 0; i < len(bytecodes); i++ { 81 buf := make([]byte, 100) 82 rand.Read(buf) 83 bytecodes[i] = buf 84 } 85 var old = func() { 86 hasher := sha3.NewLegacyKeccak256() 87 for i := 0; i < len(bytecodes); i++ { 88 hasher.Reset() 89 hasher.Write(bytecodes[i]) 90 hasher.Sum(nil) 91 } 92 } 93 var new = func() { 94 hasher := sha3.NewLegacyKeccak256().(crypto.KeccakState) 95 var hash = make([]byte, 32) 96 for i := 0; i < len(bytecodes); i++ { 97 hasher.Reset() 98 hasher.Write(bytecodes[i]) 99 hasher.Read(hash) 100 } 101 } 102 b.Run("old", func(b *testing.B) { 103 b.ReportAllocs() 104 for i := 0; i < b.N; i++ { 105 old() 106 } 107 }) 108 b.Run("new", func(b *testing.B) { 109 b.ReportAllocs() 110 for i := 0; i < b.N; i++ { 111 new() 112 } 113 }) 114 } 115 116 type ( 117 accountHandlerFunc func(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, limit common.Hash, cap uint64) error 118 storageHandlerFunc func(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error 119 trieHandlerFunc func(t *testPeer, requestId uint64, root common.Hash, paths []TrieNodePathSet, cap uint64) error 120 codeHandlerFunc func(t *testPeer, id uint64, hashes []common.Hash, max uint64) error 121 ) 122 123 type testPeer struct { 124 id string 125 test *testing.T 126 remote *Syncer 127 logger log.Logger 128 accountTrie *trie.Trie 129 accountValues entrySlice 130 storageTries map[common.Hash]*trie.Trie 131 storageValues map[common.Hash]entrySlice 132 133 accountRequestHandler accountHandlerFunc 134 storageRequestHandler storageHandlerFunc 135 trieRequestHandler trieHandlerFunc 136 codeRequestHandler codeHandlerFunc 137 term func() 138 139 // counters 140 nAccountRequests int 141 nStorageRequests int 142 nBytecodeRequests int 143 nTrienodeRequests int 144 } 145 146 func newTestPeer(id string, t *testing.T, term func()) *testPeer { 147 peer := &testPeer{ 148 id: id, 149 test: t, 150 logger: log.New("id", id), 151 accountRequestHandler: defaultAccountRequestHandler, 152 trieRequestHandler: defaultTrieRequestHandler, 153 storageRequestHandler: defaultStorageRequestHandler, 154 codeRequestHandler: defaultCodeRequestHandler, 155 term: term, 156 } 157 //stderrHandler := log.StreamHandler(os.Stderr, log.TerminalFormat(true)) 158 //peer.logger.SetHandler(stderrHandler) 159 return peer 160 } 161 162 func (t *testPeer) ID() string { return t.id } 163 func (t *testPeer) Log() log.Logger { return t.logger } 164 165 func (t *testPeer) Stats() string { 166 return fmt.Sprintf(`Account requests: %d 167 Storage requests: %d 168 Bytecode requests: %d 169 Trienode requests: %d 170 `, t.nAccountRequests, t.nStorageRequests, t.nBytecodeRequests, t.nTrienodeRequests) 171 } 172 173 func (t *testPeer) RequestAccountRange(id uint64, root, origin, limit common.Hash, bytes uint64) error { 174 t.logger.Trace("Fetching range of accounts", "reqid", id, "root", root, "origin", origin, "limit", limit, "bytes", common.StorageSize(bytes)) 175 t.nAccountRequests++ 176 go t.accountRequestHandler(t, id, root, origin, limit, bytes) 177 return nil 178 } 179 180 func (t *testPeer) RequestTrieNodes(id uint64, root common.Hash, paths []TrieNodePathSet, bytes uint64) error { 181 t.logger.Trace("Fetching set of trie nodes", "reqid", id, "root", root, "pathsets", len(paths), "bytes", common.StorageSize(bytes)) 182 t.nTrienodeRequests++ 183 go t.trieRequestHandler(t, id, root, paths, bytes) 184 return nil 185 } 186 187 func (t *testPeer) RequestStorageRanges(id uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, bytes uint64) error { 188 t.nStorageRequests++ 189 if len(accounts) == 1 && origin != nil { 190 t.logger.Trace("Fetching range of large storage slots", "reqid", id, "root", root, "account", accounts[0], "origin", common.BytesToHash(origin), "limit", common.BytesToHash(limit), "bytes", common.StorageSize(bytes)) 191 } else { 192 t.logger.Trace("Fetching ranges of small storage slots", "reqid", id, "root", root, "accounts", len(accounts), "first", accounts[0], "bytes", common.StorageSize(bytes)) 193 } 194 go t.storageRequestHandler(t, id, root, accounts, origin, limit, bytes) 195 return nil 196 } 197 198 func (t *testPeer) RequestByteCodes(id uint64, hashes []common.Hash, bytes uint64) error { 199 t.nBytecodeRequests++ 200 t.logger.Trace("Fetching set of byte codes", "reqid", id, "hashes", len(hashes), "bytes", common.StorageSize(bytes)) 201 go t.codeRequestHandler(t, id, hashes, bytes) 202 return nil 203 } 204 205 // defaultTrieRequestHandler is a well-behaving handler for trie healing requests 206 func defaultTrieRequestHandler(t *testPeer, requestId uint64, root common.Hash, paths []TrieNodePathSet, cap uint64) error { 207 // Pass the response 208 var nodes [][]byte 209 for _, pathset := range paths { 210 switch len(pathset) { 211 case 1: 212 blob, _, err := t.accountTrie.TryGetNode(pathset[0]) 213 if err != nil { 214 t.logger.Info("Error handling req", "error", err) 215 break 216 } 217 nodes = append(nodes, blob) 218 default: 219 account := t.storageTries[(common.BytesToHash(pathset[0]))] 220 for _, path := range pathset[1:] { 221 blob, _, err := account.TryGetNode(path) 222 if err != nil { 223 t.logger.Info("Error handling req", "error", err) 224 break 225 } 226 nodes = append(nodes, blob) 227 } 228 } 229 } 230 t.remote.OnTrieNodes(t, requestId, nodes) 231 return nil 232 } 233 234 // defaultAccountRequestHandler is a well-behaving handler for AccountRangeRequests 235 func defaultAccountRequestHandler(t *testPeer, id uint64, root common.Hash, origin common.Hash, limit common.Hash, cap uint64) error { 236 keys, vals, proofs := createAccountRequestResponse(t, root, origin, limit, cap) 237 if err := t.remote.OnAccounts(t, id, keys, vals, proofs); err != nil { 238 t.test.Errorf("Remote side rejected our delivery: %v", err) 239 t.term() 240 return err 241 } 242 return nil 243 } 244 245 func createAccountRequestResponse(t *testPeer, root common.Hash, origin common.Hash, limit common.Hash, cap uint64) (keys []common.Hash, vals [][]byte, proofs [][]byte) { 246 var size uint64 247 if limit == (common.Hash{}) { 248 limit = common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff") 249 } 250 for _, entry := range t.accountValues { 251 if size > cap { 252 break 253 } 254 if bytes.Compare(origin[:], entry.k) <= 0 { 255 keys = append(keys, common.BytesToHash(entry.k)) 256 vals = append(vals, entry.v) 257 size += uint64(32 + len(entry.v)) 258 } 259 // If we've exceeded the request threshold, abort 260 if bytes.Compare(entry.k, limit[:]) >= 0 { 261 break 262 } 263 } 264 // Unless we send the entire trie, we need to supply proofs 265 // Actually, we need to supply proofs either way! This seems to be an implementation 266 // quirk in go-ethereum 267 proof := light.NewNodeSet() 268 if err := t.accountTrie.Prove(origin[:], 0, proof); err != nil { 269 t.logger.Error("Could not prove inexistence of origin", "origin", origin, "error", err) 270 } 271 if len(keys) > 0 { 272 lastK := (keys[len(keys)-1])[:] 273 if err := t.accountTrie.Prove(lastK, 0, proof); err != nil { 274 t.logger.Error("Could not prove last item", "error", err) 275 } 276 } 277 for _, blob := range proof.NodeList() { 278 proofs = append(proofs, blob) 279 } 280 return keys, vals, proofs 281 } 282 283 // defaultStorageRequestHandler is a well-behaving storage request handler 284 func defaultStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, bOrigin, bLimit []byte, max uint64) error { 285 hashes, slots, proofs := createStorageRequestResponse(t, root, accounts, bOrigin, bLimit, max) 286 if err := t.remote.OnStorage(t, requestId, hashes, slots, proofs); err != nil { 287 t.test.Errorf("Remote side rejected our delivery: %v", err) 288 t.term() 289 } 290 return nil 291 } 292 293 func defaultCodeRequestHandler(t *testPeer, id uint64, hashes []common.Hash, max uint64) error { 294 var bytecodes [][]byte 295 for _, h := range hashes { 296 bytecodes = append(bytecodes, getCodeByHash(h)) 297 } 298 if err := t.remote.OnByteCodes(t, id, bytecodes); err != nil { 299 t.test.Errorf("Remote side rejected our delivery: %v", err) 300 t.term() 301 } 302 return nil 303 } 304 305 func createStorageRequestResponse(t *testPeer, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) (hashes [][]common.Hash, slots [][][]byte, proofs [][]byte) { 306 var size uint64 307 for _, account := range accounts { 308 // The first account might start from a different origin and end sooner 309 var originHash common.Hash 310 if len(origin) > 0 { 311 originHash = common.BytesToHash(origin) 312 } 313 var limitHash = common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff") 314 if len(limit) > 0 { 315 limitHash = common.BytesToHash(limit) 316 } 317 var ( 318 keys []common.Hash 319 vals [][]byte 320 abort bool 321 ) 322 for _, entry := range t.storageValues[account] { 323 if size >= max { 324 abort = true 325 break 326 } 327 if bytes.Compare(entry.k, originHash[:]) < 0 { 328 continue 329 } 330 keys = append(keys, common.BytesToHash(entry.k)) 331 vals = append(vals, entry.v) 332 size += uint64(32 + len(entry.v)) 333 if bytes.Compare(entry.k, limitHash[:]) >= 0 { 334 break 335 } 336 } 337 hashes = append(hashes, keys) 338 slots = append(slots, vals) 339 340 // Generate the Merkle proofs for the first and last storage slot, but 341 // only if the response was capped. If the entire storage trie included 342 // in the response, no need for any proofs. 343 if originHash != (common.Hash{}) || abort { 344 // If we're aborting, we need to prove the first and last item 345 // This terminates the response (and thus the loop) 346 proof := light.NewNodeSet() 347 stTrie := t.storageTries[account] 348 349 // Here's a potential gotcha: when constructing the proof, we cannot 350 // use the 'origin' slice directly, but must use the full 32-byte 351 // hash form. 352 if err := stTrie.Prove(originHash[:], 0, proof); err != nil { 353 t.logger.Error("Could not prove inexistence of origin", "origin", originHash, "error", err) 354 } 355 if len(keys) > 0 { 356 lastK := (keys[len(keys)-1])[:] 357 if err := stTrie.Prove(lastK, 0, proof); err != nil { 358 t.logger.Error("Could not prove last item", "error", err) 359 } 360 } 361 for _, blob := range proof.NodeList() { 362 proofs = append(proofs, blob) 363 } 364 break 365 } 366 } 367 return hashes, slots, proofs 368 } 369 370 // the createStorageRequestResponseAlwaysProve tests a cornercase, where it always 371 // 372 // supplies the proof for the last account, even if it is 'complete'.h 373 func createStorageRequestResponseAlwaysProve(t *testPeer, root common.Hash, accounts []common.Hash, bOrigin, bLimit []byte, max uint64) (hashes [][]common.Hash, slots [][][]byte, proofs [][]byte) { 374 var size uint64 375 max = max * 3 / 4 376 377 var origin common.Hash 378 if len(bOrigin) > 0 { 379 origin = common.BytesToHash(bOrigin) 380 } 381 var exit bool 382 for i, account := range accounts { 383 var keys []common.Hash 384 var vals [][]byte 385 for _, entry := range t.storageValues[account] { 386 if bytes.Compare(entry.k, origin[:]) < 0 { 387 exit = true 388 } 389 keys = append(keys, common.BytesToHash(entry.k)) 390 vals = append(vals, entry.v) 391 size += uint64(32 + len(entry.v)) 392 if size > max { 393 exit = true 394 } 395 } 396 if i == len(accounts)-1 { 397 exit = true 398 } 399 hashes = append(hashes, keys) 400 slots = append(slots, vals) 401 402 if exit { 403 // If we're aborting, we need to prove the first and last item 404 // This terminates the response (and thus the loop) 405 proof := light.NewNodeSet() 406 stTrie := t.storageTries[account] 407 408 // Here's a potential gotcha: when constructing the proof, we cannot 409 // use the 'origin' slice directly, but must use the full 32-byte 410 // hash form. 411 if err := stTrie.Prove(origin[:], 0, proof); err != nil { 412 t.logger.Error("Could not prove inexistence of origin", "origin", origin, 413 "error", err) 414 } 415 if len(keys) > 0 { 416 lastK := (keys[len(keys)-1])[:] 417 if err := stTrie.Prove(lastK, 0, proof); err != nil { 418 t.logger.Error("Could not prove last item", "error", err) 419 } 420 } 421 for _, blob := range proof.NodeList() { 422 proofs = append(proofs, blob) 423 } 424 break 425 } 426 } 427 return hashes, slots, proofs 428 } 429 430 // emptyRequestAccountRangeFn is a rejects AccountRangeRequests 431 func emptyRequestAccountRangeFn(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, limit common.Hash, cap uint64) error { 432 t.remote.OnAccounts(t, requestId, nil, nil, nil) 433 return nil 434 } 435 436 func nonResponsiveRequestAccountRangeFn(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, limit common.Hash, cap uint64) error { 437 return nil 438 } 439 440 func emptyTrieRequestHandler(t *testPeer, requestId uint64, root common.Hash, paths []TrieNodePathSet, cap uint64) error { 441 t.remote.OnTrieNodes(t, requestId, nil) 442 return nil 443 } 444 445 func nonResponsiveTrieRequestHandler(t *testPeer, requestId uint64, root common.Hash, paths []TrieNodePathSet, cap uint64) error { 446 return nil 447 } 448 449 func emptyStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error { 450 t.remote.OnStorage(t, requestId, nil, nil, nil) 451 return nil 452 } 453 454 func nonResponsiveStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error { 455 return nil 456 } 457 458 func proofHappyStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error { 459 hashes, slots, proofs := createStorageRequestResponseAlwaysProve(t, root, accounts, origin, limit, max) 460 if err := t.remote.OnStorage(t, requestId, hashes, slots, proofs); err != nil { 461 t.test.Errorf("Remote side rejected our delivery: %v", err) 462 t.term() 463 } 464 return nil 465 } 466 467 //func emptyCodeRequestHandler(t *testPeer, id uint64, hashes []common.Hash, max uint64) error { 468 // var bytecodes [][]byte 469 // t.remote.OnByteCodes(t, id, bytecodes) 470 // return nil 471 //} 472 473 func corruptCodeRequestHandler(t *testPeer, id uint64, hashes []common.Hash, max uint64) error { 474 var bytecodes [][]byte 475 for _, h := range hashes { 476 // Send back the hashes 477 bytecodes = append(bytecodes, h[:]) 478 } 479 if err := t.remote.OnByteCodes(t, id, bytecodes); err != nil { 480 t.logger.Info("remote error on delivery (as expected)", "error", err) 481 // Mimic the real-life handler, which drops a peer on errors 482 t.remote.Unregister(t.id) 483 } 484 return nil 485 } 486 487 func cappedCodeRequestHandler(t *testPeer, id uint64, hashes []common.Hash, max uint64) error { 488 var bytecodes [][]byte 489 for _, h := range hashes[:1] { 490 bytecodes = append(bytecodes, getCodeByHash(h)) 491 } 492 // Missing bytecode can be retrieved again, no error expected 493 if err := t.remote.OnByteCodes(t, id, bytecodes); err != nil { 494 t.test.Errorf("Remote side rejected our delivery: %v", err) 495 t.term() 496 } 497 return nil 498 } 499 500 // starvingStorageRequestHandler is somewhat well-behaving storage handler, but it caps the returned results to be very small 501 func starvingStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error { 502 return defaultStorageRequestHandler(t, requestId, root, accounts, origin, limit, 500) 503 } 504 505 func starvingAccountRequestHandler(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, limit common.Hash, cap uint64) error { 506 return defaultAccountRequestHandler(t, requestId, root, origin, limit, 500) 507 } 508 509 //func misdeliveringAccountRequestHandler(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, cap uint64) error { 510 // return defaultAccountRequestHandler(t, requestId-1, root, origin, 500) 511 //} 512 513 func corruptAccountRequestHandler(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, limit common.Hash, cap uint64) error { 514 hashes, accounts, proofs := createAccountRequestResponse(t, root, origin, limit, cap) 515 if len(proofs) > 0 { 516 proofs = proofs[1:] 517 } 518 if err := t.remote.OnAccounts(t, requestId, hashes, accounts, proofs); err != nil { 519 t.logger.Info("remote error on delivery (as expected)", "error", err) 520 // Mimic the real-life handler, which drops a peer on errors 521 t.remote.Unregister(t.id) 522 } 523 return nil 524 } 525 526 // corruptStorageRequestHandler doesn't provide good proofs 527 func corruptStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error { 528 hashes, slots, proofs := createStorageRequestResponse(t, root, accounts, origin, limit, max) 529 if len(proofs) > 0 { 530 proofs = proofs[1:] 531 } 532 if err := t.remote.OnStorage(t, requestId, hashes, slots, proofs); err != nil { 533 t.logger.Info("remote error on delivery (as expected)", "error", err) 534 // Mimic the real-life handler, which drops a peer on errors 535 t.remote.Unregister(t.id) 536 } 537 return nil 538 } 539 540 func noProofStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error { 541 hashes, slots, _ := createStorageRequestResponse(t, root, accounts, origin, limit, max) 542 if err := t.remote.OnStorage(t, requestId, hashes, slots, nil); err != nil { 543 t.logger.Info("remote error on delivery (as expected)", "error", err) 544 // Mimic the real-life handler, which drops a peer on errors 545 t.remote.Unregister(t.id) 546 } 547 return nil 548 } 549 550 // TestSyncBloatedProof tests a scenario where we provide only _one_ value, but 551 // also ship the entire trie inside the proof. If the attack is successful, 552 // the remote side does not do any follow-up requests 553 func TestSyncBloatedProof(t *testing.T) { 554 t.Parallel() 555 556 var ( 557 once sync.Once 558 cancel = make(chan struct{}) 559 term = func() { 560 once.Do(func() { 561 close(cancel) 562 }) 563 } 564 ) 565 sourceAccountTrie, elems := makeAccountTrieNoStorage(100) 566 source := newTestPeer("source", t, term) 567 source.accountTrie = sourceAccountTrie 568 source.accountValues = elems 569 570 source.accountRequestHandler = func(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, limit common.Hash, cap uint64) error { 571 var ( 572 proofs [][]byte 573 keys []common.Hash 574 vals [][]byte 575 ) 576 // The values 577 for _, entry := range t.accountValues { 578 if bytes.Compare(entry.k, origin[:]) < 0 { 579 continue 580 } 581 if bytes.Compare(entry.k, limit[:]) > 0 { 582 continue 583 } 584 keys = append(keys, common.BytesToHash(entry.k)) 585 vals = append(vals, entry.v) 586 } 587 // The proofs 588 proof := light.NewNodeSet() 589 if err := t.accountTrie.Prove(origin[:], 0, proof); err != nil { 590 t.logger.Error("Could not prove origin", "origin", origin, "error", err) 591 } 592 // The bloat: add proof of every single element 593 for _, entry := range t.accountValues { 594 if err := t.accountTrie.Prove(entry.k, 0, proof); err != nil { 595 t.logger.Error("Could not prove item", "error", err) 596 } 597 } 598 // And remove one item from the elements 599 if len(keys) > 2 { 600 keys = append(keys[:1], keys[2:]...) 601 vals = append(vals[:1], vals[2:]...) 602 } 603 for _, blob := range proof.NodeList() { 604 proofs = append(proofs, blob) 605 } 606 if err := t.remote.OnAccounts(t, requestId, keys, vals, proofs); err != nil { 607 t.logger.Info("remote error on delivery (as expected)", "error", err) 608 t.term() 609 // This is actually correct, signal to exit the test successfully 610 } 611 return nil 612 } 613 syncer := setupSyncer(source) 614 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err == nil { 615 t.Fatal("No error returned from incomplete/cancelled sync") 616 } 617 } 618 619 func setupSyncer(peers ...*testPeer) *Syncer { 620 stateDb := rawdb.NewMemoryDatabase() 621 syncer := NewSyncer(stateDb) 622 for _, peer := range peers { 623 syncer.Register(peer) 624 peer.remote = syncer 625 } 626 return syncer 627 } 628 629 // TestSync tests a basic sync with one peer 630 func TestSync(t *testing.T) { 631 t.Parallel() 632 633 var ( 634 once sync.Once 635 cancel = make(chan struct{}) 636 term = func() { 637 once.Do(func() { 638 close(cancel) 639 }) 640 } 641 ) 642 sourceAccountTrie, elems := makeAccountTrieNoStorage(100) 643 644 mkSource := func(name string) *testPeer { 645 source := newTestPeer(name, t, term) 646 source.accountTrie = sourceAccountTrie 647 source.accountValues = elems 648 return source 649 } 650 syncer := setupSyncer(mkSource("source")) 651 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil { 652 t.Fatalf("sync failed: %v", err) 653 } 654 verifyTrie(syncer.db, sourceAccountTrie.Hash(), t) 655 } 656 657 // TestSyncTinyTriePanic tests a basic sync with one peer, and a tiny trie. This caused a 658 // panic within the prover 659 func TestSyncTinyTriePanic(t *testing.T) { 660 t.Parallel() 661 662 var ( 663 once sync.Once 664 cancel = make(chan struct{}) 665 term = func() { 666 once.Do(func() { 667 close(cancel) 668 }) 669 } 670 ) 671 sourceAccountTrie, elems := makeAccountTrieNoStorage(1) 672 673 mkSource := func(name string) *testPeer { 674 source := newTestPeer(name, t, term) 675 source.accountTrie = sourceAccountTrie 676 source.accountValues = elems 677 return source 678 } 679 syncer := setupSyncer(mkSource("source")) 680 done := checkStall(t, term) 681 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil { 682 t.Fatalf("sync failed: %v", err) 683 } 684 close(done) 685 verifyTrie(syncer.db, sourceAccountTrie.Hash(), t) 686 } 687 688 // TestMultiSync tests a basic sync with multiple peers 689 func TestMultiSync(t *testing.T) { 690 t.Parallel() 691 692 var ( 693 once sync.Once 694 cancel = make(chan struct{}) 695 term = func() { 696 once.Do(func() { 697 close(cancel) 698 }) 699 } 700 ) 701 sourceAccountTrie, elems := makeAccountTrieNoStorage(100) 702 703 mkSource := func(name string) *testPeer { 704 source := newTestPeer(name, t, term) 705 source.accountTrie = sourceAccountTrie 706 source.accountValues = elems 707 return source 708 } 709 syncer := setupSyncer(mkSource("sourceA"), mkSource("sourceB")) 710 done := checkStall(t, term) 711 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil { 712 t.Fatalf("sync failed: %v", err) 713 } 714 close(done) 715 verifyTrie(syncer.db, sourceAccountTrie.Hash(), t) 716 } 717 718 // TestSyncWithStorage tests basic sync using accounts + storage + code 719 func TestSyncWithStorage(t *testing.T) { 720 t.Parallel() 721 722 var ( 723 once sync.Once 724 cancel = make(chan struct{}) 725 term = func() { 726 once.Do(func() { 727 close(cancel) 728 }) 729 } 730 ) 731 sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(3, 3000, true, false) 732 733 mkSource := func(name string) *testPeer { 734 source := newTestPeer(name, t, term) 735 source.accountTrie = sourceAccountTrie 736 source.accountValues = elems 737 source.storageTries = storageTries 738 source.storageValues = storageElems 739 return source 740 } 741 syncer := setupSyncer(mkSource("sourceA")) 742 done := checkStall(t, term) 743 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil { 744 t.Fatalf("sync failed: %v", err) 745 } 746 close(done) 747 verifyTrie(syncer.db, sourceAccountTrie.Hash(), t) 748 } 749 750 // TestMultiSyncManyUseless contains one good peer, and many which doesn't return anything valuable at all 751 func TestMultiSyncManyUseless(t *testing.T) { 752 t.Parallel() 753 754 var ( 755 once sync.Once 756 cancel = make(chan struct{}) 757 term = func() { 758 once.Do(func() { 759 close(cancel) 760 }) 761 } 762 ) 763 sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(100, 3000, true, false) 764 765 mkSource := func(name string, noAccount, noStorage, noTrieNode bool) *testPeer { 766 source := newTestPeer(name, t, term) 767 source.accountTrie = sourceAccountTrie 768 source.accountValues = elems 769 source.storageTries = storageTries 770 source.storageValues = storageElems 771 772 if !noAccount { 773 source.accountRequestHandler = emptyRequestAccountRangeFn 774 } 775 if !noStorage { 776 source.storageRequestHandler = emptyStorageRequestHandler 777 } 778 if !noTrieNode { 779 source.trieRequestHandler = emptyTrieRequestHandler 780 } 781 return source 782 } 783 784 syncer := setupSyncer( 785 mkSource("full", true, true, true), 786 mkSource("noAccounts", false, true, true), 787 mkSource("noStorage", true, false, true), 788 mkSource("noTrie", true, true, false), 789 ) 790 done := checkStall(t, term) 791 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil { 792 t.Fatalf("sync failed: %v", err) 793 } 794 close(done) 795 verifyTrie(syncer.db, sourceAccountTrie.Hash(), t) 796 } 797 798 // TestMultiSyncManyUseless contains one good peer, and many which doesn't return anything valuable at all 799 func TestMultiSyncManyUselessWithLowTimeout(t *testing.T) { 800 var ( 801 once sync.Once 802 cancel = make(chan struct{}) 803 term = func() { 804 once.Do(func() { 805 close(cancel) 806 }) 807 } 808 ) 809 sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(100, 3000, true, false) 810 811 mkSource := func(name string, noAccount, noStorage, noTrieNode bool) *testPeer { 812 source := newTestPeer(name, t, term) 813 source.accountTrie = sourceAccountTrie 814 source.accountValues = elems 815 source.storageTries = storageTries 816 source.storageValues = storageElems 817 818 if !noAccount { 819 source.accountRequestHandler = emptyRequestAccountRangeFn 820 } 821 if !noStorage { 822 source.storageRequestHandler = emptyStorageRequestHandler 823 } 824 if !noTrieNode { 825 source.trieRequestHandler = emptyTrieRequestHandler 826 } 827 return source 828 } 829 830 syncer := setupSyncer( 831 mkSource("full", true, true, true), 832 mkSource("noAccounts", false, true, true), 833 mkSource("noStorage", true, false, true), 834 mkSource("noTrie", true, true, false), 835 ) 836 // We're setting the timeout to very low, to increase the chance of the timeout 837 // being triggered. This was previously a cause of panic, when a response 838 // arrived simultaneously as a timeout was triggered. 839 syncer.rates.OverrideTTLLimit = time.Millisecond 840 841 done := checkStall(t, term) 842 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil { 843 t.Fatalf("sync failed: %v", err) 844 } 845 close(done) 846 verifyTrie(syncer.db, sourceAccountTrie.Hash(), t) 847 } 848 849 // TestMultiSyncManyUnresponsive contains one good peer, and many which doesn't respond at all 850 func TestMultiSyncManyUnresponsive(t *testing.T) { 851 var ( 852 once sync.Once 853 cancel = make(chan struct{}) 854 term = func() { 855 once.Do(func() { 856 close(cancel) 857 }) 858 } 859 ) 860 sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(100, 3000, true, false) 861 862 mkSource := func(name string, noAccount, noStorage, noTrieNode bool) *testPeer { 863 source := newTestPeer(name, t, term) 864 source.accountTrie = sourceAccountTrie 865 source.accountValues = elems 866 source.storageTries = storageTries 867 source.storageValues = storageElems 868 869 if !noAccount { 870 source.accountRequestHandler = nonResponsiveRequestAccountRangeFn 871 } 872 if !noStorage { 873 source.storageRequestHandler = nonResponsiveStorageRequestHandler 874 } 875 if !noTrieNode { 876 source.trieRequestHandler = nonResponsiveTrieRequestHandler 877 } 878 return source 879 } 880 881 syncer := setupSyncer( 882 mkSource("full", true, true, true), 883 mkSource("noAccounts", false, true, true), 884 mkSource("noStorage", true, false, true), 885 mkSource("noTrie", true, true, false), 886 ) 887 // We're setting the timeout to very low, to make the test run a bit faster 888 syncer.rates.OverrideTTLLimit = time.Millisecond 889 890 done := checkStall(t, term) 891 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil { 892 t.Fatalf("sync failed: %v", err) 893 } 894 close(done) 895 verifyTrie(syncer.db, sourceAccountTrie.Hash(), t) 896 } 897 898 func checkStall(t *testing.T, term func()) chan struct{} { 899 testDone := make(chan struct{}) 900 go func() { 901 select { 902 case <-time.After(time.Minute): // TODO(karalabe): Make tests smaller, this is too much 903 t.Log("Sync stalled") 904 term() 905 case <-testDone: 906 return 907 } 908 }() 909 return testDone 910 } 911 912 // TestSyncBoundaryAccountTrie tests sync against a few normal peers, but the 913 // account trie has a few boundary elements. 914 func TestSyncBoundaryAccountTrie(t *testing.T) { 915 t.Parallel() 916 917 var ( 918 once sync.Once 919 cancel = make(chan struct{}) 920 term = func() { 921 once.Do(func() { 922 close(cancel) 923 }) 924 } 925 ) 926 sourceAccountTrie, elems := makeBoundaryAccountTrie(3000) 927 928 mkSource := func(name string) *testPeer { 929 source := newTestPeer(name, t, term) 930 source.accountTrie = sourceAccountTrie 931 source.accountValues = elems 932 return source 933 } 934 syncer := setupSyncer( 935 mkSource("peer-a"), 936 mkSource("peer-b"), 937 ) 938 done := checkStall(t, term) 939 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil { 940 t.Fatalf("sync failed: %v", err) 941 } 942 close(done) 943 verifyTrie(syncer.db, sourceAccountTrie.Hash(), t) 944 } 945 946 // TestSyncNoStorageAndOneCappedPeer tests sync using accounts and no storage, where one peer is 947 // consistently returning very small results 948 func TestSyncNoStorageAndOneCappedPeer(t *testing.T) { 949 t.Parallel() 950 951 var ( 952 once sync.Once 953 cancel = make(chan struct{}) 954 term = func() { 955 once.Do(func() { 956 close(cancel) 957 }) 958 } 959 ) 960 sourceAccountTrie, elems := makeAccountTrieNoStorage(3000) 961 962 mkSource := func(name string, slow bool) *testPeer { 963 source := newTestPeer(name, t, term) 964 source.accountTrie = sourceAccountTrie 965 source.accountValues = elems 966 967 if slow { 968 source.accountRequestHandler = starvingAccountRequestHandler 969 } 970 return source 971 } 972 973 syncer := setupSyncer( 974 mkSource("nice-a", false), 975 mkSource("nice-b", false), 976 mkSource("nice-c", false), 977 mkSource("capped", true), 978 ) 979 done := checkStall(t, term) 980 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil { 981 t.Fatalf("sync failed: %v", err) 982 } 983 close(done) 984 verifyTrie(syncer.db, sourceAccountTrie.Hash(), t) 985 } 986 987 // TestSyncNoStorageAndOneCodeCorruptPeer has one peer which doesn't deliver 988 // code requests properly. 989 func TestSyncNoStorageAndOneCodeCorruptPeer(t *testing.T) { 990 t.Parallel() 991 992 var ( 993 once sync.Once 994 cancel = make(chan struct{}) 995 term = func() { 996 once.Do(func() { 997 close(cancel) 998 }) 999 } 1000 ) 1001 sourceAccountTrie, elems := makeAccountTrieNoStorage(3000) 1002 1003 mkSource := func(name string, codeFn codeHandlerFunc) *testPeer { 1004 source := newTestPeer(name, t, term) 1005 source.accountTrie = sourceAccountTrie 1006 source.accountValues = elems 1007 source.codeRequestHandler = codeFn 1008 return source 1009 } 1010 // One is capped, one is corrupt. If we don't use a capped one, there's a 50% 1011 // chance that the full set of codes requested are sent only to the 1012 // non-corrupt peer, which delivers everything in one go, and makes the 1013 // test moot 1014 syncer := setupSyncer( 1015 mkSource("capped", cappedCodeRequestHandler), 1016 mkSource("corrupt", corruptCodeRequestHandler), 1017 ) 1018 done := checkStall(t, term) 1019 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil { 1020 t.Fatalf("sync failed: %v", err) 1021 } 1022 close(done) 1023 verifyTrie(syncer.db, sourceAccountTrie.Hash(), t) 1024 } 1025 1026 func TestSyncNoStorageAndOneAccountCorruptPeer(t *testing.T) { 1027 t.Parallel() 1028 1029 var ( 1030 once sync.Once 1031 cancel = make(chan struct{}) 1032 term = func() { 1033 once.Do(func() { 1034 close(cancel) 1035 }) 1036 } 1037 ) 1038 sourceAccountTrie, elems := makeAccountTrieNoStorage(3000) 1039 1040 mkSource := func(name string, accFn accountHandlerFunc) *testPeer { 1041 source := newTestPeer(name, t, term) 1042 source.accountTrie = sourceAccountTrie 1043 source.accountValues = elems 1044 source.accountRequestHandler = accFn 1045 return source 1046 } 1047 // One is capped, one is corrupt. If we don't use a capped one, there's a 50% 1048 // chance that the full set of codes requested are sent only to the 1049 // non-corrupt peer, which delivers everything in one go, and makes the 1050 // test moot 1051 syncer := setupSyncer( 1052 mkSource("capped", defaultAccountRequestHandler), 1053 mkSource("corrupt", corruptAccountRequestHandler), 1054 ) 1055 done := checkStall(t, term) 1056 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil { 1057 t.Fatalf("sync failed: %v", err) 1058 } 1059 close(done) 1060 verifyTrie(syncer.db, sourceAccountTrie.Hash(), t) 1061 } 1062 1063 // TestSyncNoStorageAndOneCodeCappedPeer has one peer which delivers code hashes 1064 // one by one 1065 func TestSyncNoStorageAndOneCodeCappedPeer(t *testing.T) { 1066 t.Parallel() 1067 1068 var ( 1069 once sync.Once 1070 cancel = make(chan struct{}) 1071 term = func() { 1072 once.Do(func() { 1073 close(cancel) 1074 }) 1075 } 1076 ) 1077 sourceAccountTrie, elems := makeAccountTrieNoStorage(3000) 1078 1079 mkSource := func(name string, codeFn codeHandlerFunc) *testPeer { 1080 source := newTestPeer(name, t, term) 1081 source.accountTrie = sourceAccountTrie 1082 source.accountValues = elems 1083 source.codeRequestHandler = codeFn 1084 return source 1085 } 1086 // Count how many times it's invoked. Remember, there are only 8 unique hashes, 1087 // so it shouldn't be more than that 1088 var counter int 1089 syncer := setupSyncer( 1090 mkSource("capped", func(t *testPeer, id uint64, hashes []common.Hash, max uint64) error { 1091 counter++ 1092 return cappedCodeRequestHandler(t, id, hashes, max) 1093 }), 1094 ) 1095 done := checkStall(t, term) 1096 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil { 1097 t.Fatalf("sync failed: %v", err) 1098 } 1099 close(done) 1100 // There are only 8 unique hashes, and 3K accounts. However, the code 1101 // deduplication is per request batch. If it were a perfect global dedup, 1102 // we would expect only 8 requests. If there were no dedup, there would be 1103 // 3k requests. 1104 // We expect somewhere below 100 requests for these 8 unique hashes. 1105 if threshold := 100; counter > threshold { 1106 t.Fatalf("Error, expected < %d invocations, got %d", threshold, counter) 1107 } 1108 verifyTrie(syncer.db, sourceAccountTrie.Hash(), t) 1109 } 1110 1111 // TestSyncBoundaryStorageTrie tests sync against a few normal peers, but the 1112 // storage trie has a few boundary elements. 1113 func TestSyncBoundaryStorageTrie(t *testing.T) { 1114 t.Parallel() 1115 1116 var ( 1117 once sync.Once 1118 cancel = make(chan struct{}) 1119 term = func() { 1120 once.Do(func() { 1121 close(cancel) 1122 }) 1123 } 1124 ) 1125 sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(10, 1000, false, true) 1126 1127 mkSource := func(name string) *testPeer { 1128 source := newTestPeer(name, t, term) 1129 source.accountTrie = sourceAccountTrie 1130 source.accountValues = elems 1131 source.storageTries = storageTries 1132 source.storageValues = storageElems 1133 return source 1134 } 1135 syncer := setupSyncer( 1136 mkSource("peer-a"), 1137 mkSource("peer-b"), 1138 ) 1139 done := checkStall(t, term) 1140 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil { 1141 t.Fatalf("sync failed: %v", err) 1142 } 1143 close(done) 1144 verifyTrie(syncer.db, sourceAccountTrie.Hash(), t) 1145 } 1146 1147 // TestSyncWithStorageAndOneCappedPeer tests sync using accounts + storage, where one peer is 1148 // consistently returning very small results 1149 func TestSyncWithStorageAndOneCappedPeer(t *testing.T) { 1150 t.Parallel() 1151 1152 var ( 1153 once sync.Once 1154 cancel = make(chan struct{}) 1155 term = func() { 1156 once.Do(func() { 1157 close(cancel) 1158 }) 1159 } 1160 ) 1161 sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(300, 1000, false, false) 1162 1163 mkSource := func(name string, slow bool) *testPeer { 1164 source := newTestPeer(name, t, term) 1165 source.accountTrie = sourceAccountTrie 1166 source.accountValues = elems 1167 source.storageTries = storageTries 1168 source.storageValues = storageElems 1169 1170 if slow { 1171 source.storageRequestHandler = starvingStorageRequestHandler 1172 } 1173 return source 1174 } 1175 1176 syncer := setupSyncer( 1177 mkSource("nice-a", false), 1178 mkSource("slow", true), 1179 ) 1180 done := checkStall(t, term) 1181 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil { 1182 t.Fatalf("sync failed: %v", err) 1183 } 1184 close(done) 1185 verifyTrie(syncer.db, sourceAccountTrie.Hash(), t) 1186 } 1187 1188 // TestSyncWithStorageAndCorruptPeer tests sync using accounts + storage, where one peer is 1189 // sometimes sending bad proofs 1190 func TestSyncWithStorageAndCorruptPeer(t *testing.T) { 1191 t.Parallel() 1192 1193 var ( 1194 once sync.Once 1195 cancel = make(chan struct{}) 1196 term = func() { 1197 once.Do(func() { 1198 close(cancel) 1199 }) 1200 } 1201 ) 1202 sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(100, 3000, true, false) 1203 1204 mkSource := func(name string, handler storageHandlerFunc) *testPeer { 1205 source := newTestPeer(name, t, term) 1206 source.accountTrie = sourceAccountTrie 1207 source.accountValues = elems 1208 source.storageTries = storageTries 1209 source.storageValues = storageElems 1210 source.storageRequestHandler = handler 1211 return source 1212 } 1213 1214 syncer := setupSyncer( 1215 mkSource("nice-a", defaultStorageRequestHandler), 1216 mkSource("nice-b", defaultStorageRequestHandler), 1217 mkSource("nice-c", defaultStorageRequestHandler), 1218 mkSource("corrupt", corruptStorageRequestHandler), 1219 ) 1220 done := checkStall(t, term) 1221 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil { 1222 t.Fatalf("sync failed: %v", err) 1223 } 1224 close(done) 1225 verifyTrie(syncer.db, sourceAccountTrie.Hash(), t) 1226 } 1227 1228 func TestSyncWithStorageAndNonProvingPeer(t *testing.T) { 1229 t.Parallel() 1230 1231 var ( 1232 once sync.Once 1233 cancel = make(chan struct{}) 1234 term = func() { 1235 once.Do(func() { 1236 close(cancel) 1237 }) 1238 } 1239 ) 1240 sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(100, 3000, true, false) 1241 1242 mkSource := func(name string, handler storageHandlerFunc) *testPeer { 1243 source := newTestPeer(name, t, term) 1244 source.accountTrie = sourceAccountTrie 1245 source.accountValues = elems 1246 source.storageTries = storageTries 1247 source.storageValues = storageElems 1248 source.storageRequestHandler = handler 1249 return source 1250 } 1251 syncer := setupSyncer( 1252 mkSource("nice-a", defaultStorageRequestHandler), 1253 mkSource("nice-b", defaultStorageRequestHandler), 1254 mkSource("nice-c", defaultStorageRequestHandler), 1255 mkSource("corrupt", noProofStorageRequestHandler), 1256 ) 1257 done := checkStall(t, term) 1258 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil { 1259 t.Fatalf("sync failed: %v", err) 1260 } 1261 close(done) 1262 verifyTrie(syncer.db, sourceAccountTrie.Hash(), t) 1263 } 1264 1265 // TestSyncWithStorage tests basic sync using accounts + storage + code, against 1266 // a peer who insists on delivering full storage sets _and_ proofs. This triggered 1267 // an error, where the recipient erroneously clipped the boundary nodes, but 1268 // did not mark the account for healing. 1269 func TestSyncWithStorageMisbehavingProve(t *testing.T) { 1270 t.Parallel() 1271 var ( 1272 once sync.Once 1273 cancel = make(chan struct{}) 1274 term = func() { 1275 once.Do(func() { 1276 close(cancel) 1277 }) 1278 } 1279 ) 1280 sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorageWithUniqueStorage(10, 30, false) 1281 1282 mkSource := func(name string) *testPeer { 1283 source := newTestPeer(name, t, term) 1284 source.accountTrie = sourceAccountTrie 1285 source.accountValues = elems 1286 source.storageTries = storageTries 1287 source.storageValues = storageElems 1288 source.storageRequestHandler = proofHappyStorageRequestHandler 1289 return source 1290 } 1291 syncer := setupSyncer(mkSource("sourceA")) 1292 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil { 1293 t.Fatalf("sync failed: %v", err) 1294 } 1295 verifyTrie(syncer.db, sourceAccountTrie.Hash(), t) 1296 } 1297 1298 type kv struct { 1299 k, v []byte 1300 } 1301 1302 // Some helpers for sorting 1303 type entrySlice []*kv 1304 1305 func (p entrySlice) Len() int { return len(p) } 1306 func (p entrySlice) Less(i, j int) bool { return bytes.Compare(p[i].k, p[j].k) < 0 } 1307 func (p entrySlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } 1308 1309 func key32(i uint64) []byte { 1310 key := make([]byte, 32) 1311 binary.LittleEndian.PutUint64(key, i) 1312 return key 1313 } 1314 1315 var ( 1316 codehashes = []common.Hash{ 1317 crypto.Keccak256Hash([]byte{0}), 1318 crypto.Keccak256Hash([]byte{1}), 1319 crypto.Keccak256Hash([]byte{2}), 1320 crypto.Keccak256Hash([]byte{3}), 1321 crypto.Keccak256Hash([]byte{4}), 1322 crypto.Keccak256Hash([]byte{5}), 1323 crypto.Keccak256Hash([]byte{6}), 1324 crypto.Keccak256Hash([]byte{7}), 1325 } 1326 ) 1327 1328 // getCodeHash returns a pseudo-random code hash 1329 func getCodeHash(i uint64) []byte { 1330 h := codehashes[int(i)%len(codehashes)] 1331 return common.CopyBytes(h[:]) 1332 } 1333 1334 // getCodeByHash convenience function to lookup the code from the code hash 1335 func getCodeByHash(hash common.Hash) []byte { 1336 if hash == emptyCode { 1337 return nil 1338 } 1339 for i, h := range codehashes { 1340 if h == hash { 1341 return []byte{byte(i)} 1342 } 1343 } 1344 return nil 1345 } 1346 1347 // makeAccountTrieNoStorage spits out a trie, along with the leafs 1348 func makeAccountTrieNoStorage(n int) (*trie.Trie, entrySlice) { 1349 db := trie.NewDatabase(rawdb.NewMemoryDatabase()) 1350 accTrie, _ := trie.New(common.Hash{}, db) 1351 var entries entrySlice 1352 for i := uint64(1); i <= uint64(n); i++ { 1353 value, _ := rlp.EncodeToBytes(state.Account{ 1354 Nonce: i, 1355 Balance: big.NewInt(int64(i)), 1356 Root: emptyRoot, 1357 CodeHash: getCodeHash(i), 1358 }) 1359 key := key32(i) 1360 elem := &kv{key, value} 1361 accTrie.Update(elem.k, elem.v) 1362 entries = append(entries, elem) 1363 } 1364 sort.Sort(entries) 1365 accTrie.Commit(nil) 1366 return accTrie, entries 1367 } 1368 1369 // makeBoundaryAccountTrie constructs an account trie. Instead of filling 1370 // accounts normally, this function will fill a few accounts which have 1371 // boundary hash. 1372 func makeBoundaryAccountTrie(n int) (*trie.Trie, entrySlice) { 1373 var ( 1374 entries entrySlice 1375 boundaries []common.Hash 1376 1377 db = trie.NewDatabase(rawdb.NewMemoryDatabase()) 1378 trie, _ = trie.New(common.Hash{}, db) 1379 ) 1380 // Initialize boundaries 1381 var next common.Hash 1382 step := new(big.Int).Sub( 1383 new(big.Int).Div( 1384 new(big.Int).Exp(common.Big2, common.Big256, nil), 1385 big.NewInt(int64(accountConcurrency)), 1386 ), common.Big1, 1387 ) 1388 for i := 0; i < accountConcurrency; i++ { 1389 last := common.BigToHash(new(big.Int).Add(next.Big(), step)) 1390 if i == accountConcurrency-1 { 1391 last = common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff") 1392 } 1393 boundaries = append(boundaries, last) 1394 next = common.BigToHash(new(big.Int).Add(last.Big(), common.Big1)) 1395 } 1396 // Fill boundary accounts 1397 for i := 0; i < len(boundaries); i++ { 1398 value, _ := rlp.EncodeToBytes(state.Account{ 1399 Nonce: uint64(0), 1400 Balance: big.NewInt(int64(i)), 1401 Root: emptyRoot, 1402 CodeHash: getCodeHash(uint64(i)), 1403 }) 1404 elem := &kv{boundaries[i].Bytes(), value} 1405 trie.Update(elem.k, elem.v) 1406 entries = append(entries, elem) 1407 } 1408 // Fill other accounts if required 1409 for i := uint64(1); i <= uint64(n); i++ { 1410 value, _ := rlp.EncodeToBytes(state.Account{ 1411 Nonce: i, 1412 Balance: big.NewInt(int64(i)), 1413 Root: emptyRoot, 1414 CodeHash: getCodeHash(i), 1415 }) 1416 elem := &kv{key32(i), value} 1417 trie.Update(elem.k, elem.v) 1418 entries = append(entries, elem) 1419 } 1420 sort.Sort(entries) 1421 trie.Commit(nil) 1422 return trie, entries 1423 } 1424 1425 // makeAccountTrieWithStorageWithUniqueStorage creates an account trie where each accounts 1426 // has a unique storage set. 1427 func makeAccountTrieWithStorageWithUniqueStorage(accounts, slots int, code bool) (*trie.Trie, entrySlice, map[common.Hash]*trie.Trie, map[common.Hash]entrySlice) { 1428 var ( 1429 db = trie.NewDatabase(rawdb.NewMemoryDatabase()) 1430 accTrie, _ = trie.New(common.Hash{}, db) 1431 entries entrySlice 1432 storageTries = make(map[common.Hash]*trie.Trie) 1433 storageEntries = make(map[common.Hash]entrySlice) 1434 ) 1435 // Create n accounts in the trie 1436 for i := uint64(1); i <= uint64(accounts); i++ { 1437 key := key32(i) 1438 codehash := emptyCode[:] 1439 if code { 1440 codehash = getCodeHash(i) 1441 } 1442 // Create a storage trie 1443 stTrie, stEntries := makeStorageTrieWithSeed(uint64(slots), i, db) 1444 stRoot := stTrie.Hash() 1445 stTrie.Commit(nil) 1446 value, _ := rlp.EncodeToBytes(state.Account{ 1447 Nonce: i, 1448 Balance: big.NewInt(int64(i)), 1449 Root: stRoot, 1450 CodeHash: codehash, 1451 }) 1452 elem := &kv{key, value} 1453 accTrie.Update(elem.k, elem.v) 1454 entries = append(entries, elem) 1455 1456 storageTries[common.BytesToHash(key)] = stTrie 1457 storageEntries[common.BytesToHash(key)] = stEntries 1458 } 1459 sort.Sort(entries) 1460 1461 accTrie.Commit(nil) 1462 return accTrie, entries, storageTries, storageEntries 1463 } 1464 1465 // makeAccountTrieWithStorage spits out a trie, along with the leafs 1466 func makeAccountTrieWithStorage(accounts, slots int, code, boundary bool) (*trie.Trie, entrySlice, map[common.Hash]*trie.Trie, map[common.Hash]entrySlice) { 1467 var ( 1468 db = trie.NewDatabase(rawdb.NewMemoryDatabase()) 1469 accTrie, _ = trie.New(common.Hash{}, db) 1470 entries entrySlice 1471 storageTries = make(map[common.Hash]*trie.Trie) 1472 storageEntries = make(map[common.Hash]entrySlice) 1473 ) 1474 // Make a storage trie which we reuse for the whole lot 1475 var ( 1476 stTrie *trie.Trie 1477 stEntries entrySlice 1478 ) 1479 if boundary { 1480 stTrie, stEntries = makeBoundaryStorageTrie(slots, db) 1481 } else { 1482 stTrie, stEntries = makeStorageTrieWithSeed(uint64(slots), 0, db) 1483 } 1484 stRoot := stTrie.Hash() 1485 1486 // Create n accounts in the trie 1487 for i := uint64(1); i <= uint64(accounts); i++ { 1488 key := key32(i) 1489 codehash := emptyCode[:] 1490 if code { 1491 codehash = getCodeHash(i) 1492 } 1493 value, _ := rlp.EncodeToBytes(state.Account{ 1494 Nonce: i, 1495 Balance: big.NewInt(int64(i)), 1496 Root: stRoot, 1497 CodeHash: codehash, 1498 }) 1499 elem := &kv{key, value} 1500 accTrie.Update(elem.k, elem.v) 1501 entries = append(entries, elem) 1502 // we reuse the same one for all accounts 1503 storageTries[common.BytesToHash(key)] = stTrie 1504 storageEntries[common.BytesToHash(key)] = stEntries 1505 } 1506 sort.Sort(entries) 1507 stTrie.Commit(nil) 1508 accTrie.Commit(nil) 1509 return accTrie, entries, storageTries, storageEntries 1510 } 1511 1512 // makeStorageTrieWithSeed fills a storage trie with n items, returning the 1513 // not-yet-committed trie and the sorted entries. The seeds can be used to ensure 1514 // that tries are unique. 1515 func makeStorageTrieWithSeed(n, seed uint64, db *trie.Database) (*trie.Trie, entrySlice) { 1516 trie, _ := trie.New(common.Hash{}, db) 1517 var entries entrySlice 1518 for i := uint64(1); i <= n; i++ { 1519 // store 'x' at slot 'x' 1520 slotValue := key32(i + seed) 1521 rlpSlotValue, _ := rlp.EncodeToBytes(common.TrimLeftZeroes(slotValue[:])) 1522 1523 slotKey := key32(i) 1524 key := crypto.Keccak256Hash(slotKey[:]) 1525 1526 elem := &kv{key[:], rlpSlotValue} 1527 trie.Update(elem.k, elem.v) 1528 entries = append(entries, elem) 1529 } 1530 sort.Sort(entries) 1531 trie.Commit(nil) 1532 return trie, entries 1533 } 1534 1535 // makeBoundaryStorageTrie constructs a storage trie. Instead of filling 1536 // storage slots normally, this function will fill a few slots which have 1537 // boundary hash. 1538 func makeBoundaryStorageTrie(n int, db *trie.Database) (*trie.Trie, entrySlice) { 1539 var ( 1540 entries entrySlice 1541 boundaries []common.Hash 1542 trie, _ = trie.New(common.Hash{}, db) 1543 ) 1544 // Initialize boundaries 1545 var next common.Hash 1546 step := new(big.Int).Sub( 1547 new(big.Int).Div( 1548 new(big.Int).Exp(common.Big2, common.Big256, nil), 1549 big.NewInt(int64(accountConcurrency)), 1550 ), common.Big1, 1551 ) 1552 for i := 0; i < accountConcurrency; i++ { 1553 last := common.BigToHash(new(big.Int).Add(next.Big(), step)) 1554 if i == accountConcurrency-1 { 1555 last = common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff") 1556 } 1557 boundaries = append(boundaries, last) 1558 next = common.BigToHash(new(big.Int).Add(last.Big(), common.Big1)) 1559 } 1560 // Fill boundary slots 1561 for i := 0; i < len(boundaries); i++ { 1562 key := boundaries[i] 1563 val := []byte{0xde, 0xad, 0xbe, 0xef} 1564 1565 elem := &kv{key[:], val} 1566 trie.Update(elem.k, elem.v) 1567 entries = append(entries, elem) 1568 } 1569 // Fill other slots if required 1570 for i := uint64(1); i <= uint64(n); i++ { 1571 slotKey := key32(i) 1572 key := crypto.Keccak256Hash(slotKey[:]) 1573 1574 slotValue := key32(i) 1575 rlpSlotValue, _ := rlp.EncodeToBytes(common.TrimLeftZeroes(slotValue[:])) 1576 1577 elem := &kv{key[:], rlpSlotValue} 1578 trie.Update(elem.k, elem.v) 1579 entries = append(entries, elem) 1580 } 1581 sort.Sort(entries) 1582 trie.Commit(nil) 1583 return trie, entries 1584 } 1585 1586 func verifyTrie(db ethdb.KeyValueStore, root common.Hash, t *testing.T) { 1587 t.Helper() 1588 triedb := trie.NewDatabase(db) 1589 accTrie, err := trie.New(root, triedb) 1590 if err != nil { 1591 t.Fatal(err) 1592 } 1593 accounts, slots := 0, 0 1594 accIt := trie.NewIterator(accTrie.NodeIterator(nil)) 1595 for accIt.Next() { 1596 var acc struct { 1597 Nonce uint64 1598 Balance *big.Int 1599 Root common.Hash 1600 CodeHash []byte 1601 } 1602 if err := rlp.DecodeBytes(accIt.Value, &acc); err != nil { 1603 log.Crit("Invalid account encountered during snapshot creation", "err", err) 1604 } 1605 accounts++ 1606 if acc.Root != emptyRoot { 1607 storeTrie, err := trie.NewSecure(acc.Root, triedb) 1608 if err != nil { 1609 t.Fatal(err) 1610 } 1611 storeIt := trie.NewIterator(storeTrie.NodeIterator(nil)) 1612 for storeIt.Next() { 1613 slots++ 1614 } 1615 if err := storeIt.Err; err != nil { 1616 t.Fatal(err) 1617 } 1618 } 1619 } 1620 if err := accIt.Err; err != nil { 1621 t.Fatal(err) 1622 } 1623 t.Logf("accounts: %d, slots: %d", accounts, slots) 1624 } 1625 1626 // TestSyncAccountPerformance tests how efficient the snap algo is at minimizing 1627 // state healing 1628 func TestSyncAccountPerformance(t *testing.T) { 1629 // Set the account concurrency to 1. This _should_ result in the 1630 // range root to become correct, and there should be no healing needed 1631 defer func(old int) { accountConcurrency = old }(accountConcurrency) 1632 accountConcurrency = 1 1633 1634 var ( 1635 once sync.Once 1636 cancel = make(chan struct{}) 1637 term = func() { 1638 once.Do(func() { 1639 close(cancel) 1640 }) 1641 } 1642 ) 1643 sourceAccountTrie, elems := makeAccountTrieNoStorage(100) 1644 1645 mkSource := func(name string) *testPeer { 1646 source := newTestPeer(name, t, term) 1647 source.accountTrie = sourceAccountTrie 1648 source.accountValues = elems 1649 return source 1650 } 1651 src := mkSource("source") 1652 syncer := setupSyncer(src) 1653 if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil { 1654 t.Fatalf("sync failed: %v", err) 1655 } 1656 verifyTrie(syncer.db, sourceAccountTrie.Hash(), t) 1657 // The trie root will always be requested, since it is added when the snap 1658 // sync cycle starts. When popping the queue, we do not look it up again. 1659 // Doing so would bring this number down to zero in this artificial testcase, 1660 // but only add extra IO for no reason in practice. 1661 if have, want := src.nTrienodeRequests, 1; have != want { 1662 fmt.Printf(src.Stats()) 1663 t.Errorf("trie node heal requests wrong, want %d, have %d", want, have) 1664 } 1665 } 1666 1667 func TestSlotEstimation(t *testing.T) { 1668 for i, tc := range []struct { 1669 last common.Hash 1670 count int 1671 want uint64 1672 }{ 1673 { 1674 // Half the space 1675 common.HexToHash("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), 1676 100, 1677 100, 1678 }, 1679 { 1680 // 1 / 16th 1681 common.HexToHash("0x0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), 1682 100, 1683 1500, 1684 }, 1685 { 1686 // Bit more than 1 / 16th 1687 common.HexToHash("0x1000000000000000000000000000000000000000000000000000000000000000"), 1688 100, 1689 1499, 1690 }, 1691 { 1692 // Almost everything 1693 common.HexToHash("0xF000000000000000000000000000000000000000000000000000000000000000"), 1694 100, 1695 6, 1696 }, 1697 { 1698 // Almost nothing -- should lead to error 1699 common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000001"), 1700 1, 1701 0, 1702 }, 1703 { 1704 // Nothing -- should lead to error 1705 common.Hash{}, 1706 100, 1707 0, 1708 }, 1709 } { 1710 have, _ := estimateRemainingSlots(tc.count, tc.last) 1711 if want := tc.want; have != want { 1712 t.Errorf("test %d: have %d want %d", i, have, want) 1713 } 1714 } 1715 }