sync_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. // Copyright 2015 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. package state
  17. import (
  18. "bytes"
  19. "math/big"
  20. "testing"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/core/rawdb"
  23. "github.com/ethereum/go-ethereum/core/types"
  24. "github.com/ethereum/go-ethereum/crypto"
  25. "github.com/ethereum/go-ethereum/ethdb"
  26. "github.com/ethereum/go-ethereum/rlp"
  27. "github.com/ethereum/go-ethereum/trie"
  28. )
  29. // testAccount is the data associated with an account used by the state tests.
  30. type testAccount struct {
  31. address common.Address
  32. balance *big.Int
  33. nonce uint64
  34. code []byte
  35. }
  36. // makeTestState create a sample test state to test node-wise reconstruction.
  37. func makeTestState() (Database, common.Hash, []*testAccount) {
  38. // Create an empty state
  39. db := NewDatabase(rawdb.NewMemoryDatabase())
  40. state, _ := New(common.Hash{}, db, nil)
  41. // Fill it with some arbitrary data
  42. var accounts []*testAccount
  43. for i := byte(0); i < 96; i++ {
  44. obj := state.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
  45. acc := &testAccount{address: common.BytesToAddress([]byte{i})}
  46. obj.AddBalance(big.NewInt(int64(11 * i)))
  47. acc.balance = big.NewInt(int64(11 * i))
  48. obj.SetNonce(uint64(42 * i))
  49. acc.nonce = uint64(42 * i)
  50. if i%3 == 0 {
  51. obj.SetCode(crypto.Keccak256Hash([]byte{i, i, i, i, i}), []byte{i, i, i, i, i})
  52. acc.code = []byte{i, i, i, i, i}
  53. }
  54. if i%5 == 0 {
  55. for j := byte(0); j < 5; j++ {
  56. hash := crypto.Keccak256Hash([]byte{i, i, i, i, i, j, j})
  57. obj.SetState(db, hash, hash)
  58. }
  59. }
  60. state.updateStateObject(obj)
  61. accounts = append(accounts, acc)
  62. }
  63. root, _ := state.Commit(false)
  64. // Return the generated state
  65. return db, root, accounts
  66. }
  67. // checkStateAccounts cross references a reconstructed state with an expected
  68. // account array.
  69. func checkStateAccounts(t *testing.T, db ethdb.Database, root common.Hash, accounts []*testAccount) {
  70. // Check root availability and state contents
  71. state, err := New(root, NewDatabase(db), nil)
  72. if err != nil {
  73. t.Fatalf("failed to create state trie at %x: %v", root, err)
  74. }
  75. if err := checkStateConsistency(db, root); err != nil {
  76. t.Fatalf("inconsistent state trie at %x: %v", root, err)
  77. }
  78. for i, acc := range accounts {
  79. if balance := state.GetBalance(acc.address); balance.Cmp(acc.balance) != 0 {
  80. t.Errorf("account %d: balance mismatch: have %v, want %v", i, balance, acc.balance)
  81. }
  82. if nonce := state.GetNonce(acc.address); nonce != acc.nonce {
  83. t.Errorf("account %d: nonce mismatch: have %v, want %v", i, nonce, acc.nonce)
  84. }
  85. if code := state.GetCode(acc.address); !bytes.Equal(code, acc.code) {
  86. t.Errorf("account %d: code mismatch: have %x, want %x", i, code, acc.code)
  87. }
  88. }
  89. }
  90. // checkTrieConsistency checks that all nodes in a (sub-)trie are indeed present.
  91. func checkTrieConsistency(db ethdb.Database, root common.Hash) error {
  92. if v, _ := db.Get(root[:]); v == nil {
  93. return nil // Consider a non existent state consistent.
  94. }
  95. trie, err := trie.New(common.Hash{}, root, trie.NewDatabase(db))
  96. if err != nil {
  97. return err
  98. }
  99. it := trie.NodeIterator(nil)
  100. for it.Next(true) {
  101. }
  102. return it.Error()
  103. }
  104. // checkStateConsistency checks that all data of a state root is present.
  105. func checkStateConsistency(db ethdb.Database, root common.Hash) error {
  106. // Create and iterate a state trie rooted in a sub-node
  107. if _, err := db.Get(root.Bytes()); err != nil {
  108. return nil // Consider a non existent state consistent.
  109. }
  110. state, err := New(root, NewDatabase(db), nil)
  111. if err != nil {
  112. return err
  113. }
  114. it := NewNodeIterator(state)
  115. for it.Next() {
  116. }
  117. return it.Error
  118. }
  119. // Tests that an empty state is not scheduled for syncing.
  120. func TestEmptyStateSync(t *testing.T) {
  121. empty := common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  122. sync := NewStateSync(empty, rawdb.NewMemoryDatabase(), nil)
  123. if paths, nodes, codes := sync.Missing(1); len(paths) != 0 || len(nodes) != 0 || len(codes) != 0 {
  124. t.Errorf("content requested for empty state: %v, %v, %v", nodes, paths, codes)
  125. }
  126. }
  127. // Tests that given a root hash, a state can sync iteratively on a single thread,
  128. // requesting retrieval tasks and returning all of them in one go.
  129. func TestIterativeStateSyncIndividual(t *testing.T) {
  130. testIterativeStateSync(t, 1, false, false)
  131. }
  132. func TestIterativeStateSyncBatched(t *testing.T) {
  133. testIterativeStateSync(t, 100, false, false)
  134. }
  135. func TestIterativeStateSyncIndividualFromDisk(t *testing.T) {
  136. testIterativeStateSync(t, 1, true, false)
  137. }
  138. func TestIterativeStateSyncBatchedFromDisk(t *testing.T) {
  139. testIterativeStateSync(t, 100, true, false)
  140. }
  141. func TestIterativeStateSyncIndividualByPath(t *testing.T) {
  142. testIterativeStateSync(t, 1, false, true)
  143. }
  144. func TestIterativeStateSyncBatchedByPath(t *testing.T) {
  145. testIterativeStateSync(t, 100, false, true)
  146. }
  147. // stateElement represents the element in the state trie(bytecode or trie node).
  148. type stateElement struct {
  149. path string
  150. hash common.Hash
  151. code common.Hash
  152. syncPath trie.SyncPath
  153. }
  154. func testIterativeStateSync(t *testing.T, count int, commit bool, bypath bool) {
  155. // Create a random state to copy
  156. srcDb, srcRoot, srcAccounts := makeTestState()
  157. if commit {
  158. srcDb.TrieDB().Commit(srcRoot, false, nil)
  159. }
  160. srcTrie, _ := trie.New(common.Hash{}, srcRoot, srcDb.TrieDB())
  161. // Create a destination state and sync with the scheduler
  162. dstDb := rawdb.NewMemoryDatabase()
  163. sched := NewStateSync(srcRoot, dstDb, nil)
  164. var (
  165. nodeElements []stateElement
  166. codeElements []stateElement
  167. )
  168. paths, nodes, codes := sched.Missing(count)
  169. for i := 0; i < len(paths); i++ {
  170. nodeElements = append(nodeElements, stateElement{
  171. path: paths[i],
  172. hash: nodes[i],
  173. syncPath: trie.NewSyncPath([]byte(paths[i])),
  174. })
  175. }
  176. for i := 0; i < len(codes); i++ {
  177. codeElements = append(codeElements, stateElement{
  178. code: codes[i],
  179. })
  180. }
  181. for len(nodeElements)+len(codeElements) > 0 {
  182. var (
  183. nodeResults = make([]trie.NodeSyncResult, len(nodeElements))
  184. codeResults = make([]trie.CodeSyncResult, len(codeElements))
  185. )
  186. for i, element := range codeElements {
  187. data, err := srcDb.ContractCode(common.Hash{}, element.code)
  188. if err != nil {
  189. t.Fatalf("failed to retrieve contract bytecode for hash %x", element.code)
  190. }
  191. codeResults[i] = trie.CodeSyncResult{Hash: element.code, Data: data}
  192. }
  193. for i, node := range nodeElements {
  194. if bypath {
  195. if len(node.syncPath) == 1 {
  196. data, _, err := srcTrie.TryGetNode(node.syncPath[0])
  197. if err != nil {
  198. t.Fatalf("failed to retrieve node data for path %x: %v", node.syncPath[0], err)
  199. }
  200. nodeResults[i] = trie.NodeSyncResult{Path: node.path, Data: data}
  201. } else {
  202. var acc types.StateAccount
  203. if err := rlp.DecodeBytes(srcTrie.Get(node.syncPath[0]), &acc); err != nil {
  204. t.Fatalf("failed to decode account on path %x: %v", node.syncPath[0], err)
  205. }
  206. stTrie, err := trie.New(common.BytesToHash(node.syncPath[0]), acc.Root, srcDb.TrieDB())
  207. if err != nil {
  208. t.Fatalf("failed to retriev storage trie for path %x: %v", node.syncPath[1], err)
  209. }
  210. data, _, err := stTrie.TryGetNode(node.syncPath[1])
  211. if err != nil {
  212. t.Fatalf("failed to retrieve node data for path %x: %v", node.syncPath[1], err)
  213. }
  214. nodeResults[i] = trie.NodeSyncResult{Path: node.path, Data: data}
  215. }
  216. } else {
  217. data, err := srcDb.TrieDB().Node(node.hash)
  218. if err != nil {
  219. t.Fatalf("failed to retrieve node data for key %v", []byte(node.path))
  220. }
  221. nodeResults[i] = trie.NodeSyncResult{Path: node.path, Data: data}
  222. }
  223. }
  224. for _, result := range codeResults {
  225. if err := sched.ProcessCode(result); err != nil {
  226. t.Errorf("failed to process result %v", err)
  227. }
  228. }
  229. for _, result := range nodeResults {
  230. if err := sched.ProcessNode(result); err != nil {
  231. t.Errorf("failed to process result %v", err)
  232. }
  233. }
  234. batch := dstDb.NewBatch()
  235. if err := sched.Commit(batch); err != nil {
  236. t.Fatalf("failed to commit data: %v", err)
  237. }
  238. batch.Write()
  239. paths, nodes, codes = sched.Missing(count)
  240. nodeElements = nodeElements[:0]
  241. for i := 0; i < len(paths); i++ {
  242. nodeElements = append(nodeElements, stateElement{
  243. path: paths[i],
  244. hash: nodes[i],
  245. syncPath: trie.NewSyncPath([]byte(paths[i])),
  246. })
  247. }
  248. codeElements = codeElements[:0]
  249. for i := 0; i < len(codes); i++ {
  250. codeElements = append(codeElements, stateElement{
  251. code: codes[i],
  252. })
  253. }
  254. }
  255. // Cross check that the two states are in sync
  256. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  257. }
  258. // Tests that the trie scheduler can correctly reconstruct the state even if only
  259. // partial results are returned, and the others sent only later.
  260. func TestIterativeDelayedStateSync(t *testing.T) {
  261. // Create a random state to copy
  262. srcDb, srcRoot, srcAccounts := makeTestState()
  263. // Create a destination state and sync with the scheduler
  264. dstDb := rawdb.NewMemoryDatabase()
  265. sched := NewStateSync(srcRoot, dstDb, nil)
  266. var (
  267. nodeElements []stateElement
  268. codeElements []stateElement
  269. )
  270. paths, nodes, codes := sched.Missing(0)
  271. for i := 0; i < len(paths); i++ {
  272. nodeElements = append(nodeElements, stateElement{
  273. path: paths[i],
  274. hash: nodes[i],
  275. syncPath: trie.NewSyncPath([]byte(paths[i])),
  276. })
  277. }
  278. for i := 0; i < len(codes); i++ {
  279. codeElements = append(codeElements, stateElement{
  280. code: codes[i],
  281. })
  282. }
  283. for len(nodeElements)+len(codeElements) > 0 {
  284. // Sync only half of the scheduled nodes
  285. var nodeProcessed int
  286. var codeProcessed int
  287. if len(codeElements) > 0 {
  288. codeResults := make([]trie.CodeSyncResult, len(codeElements)/2+1)
  289. for i, element := range codeElements[:len(codeResults)] {
  290. data, err := srcDb.ContractCode(common.Hash{}, element.code)
  291. if err != nil {
  292. t.Fatalf("failed to retrieve contract bytecode for %x", element.code)
  293. }
  294. codeResults[i] = trie.CodeSyncResult{Hash: element.code, Data: data}
  295. }
  296. for _, result := range codeResults {
  297. if err := sched.ProcessCode(result); err != nil {
  298. t.Fatalf("failed to process result %v", err)
  299. }
  300. }
  301. codeProcessed = len(codeResults)
  302. }
  303. if len(nodeElements) > 0 {
  304. nodeResults := make([]trie.NodeSyncResult, len(nodeElements)/2+1)
  305. for i, element := range nodeElements[:len(nodeResults)] {
  306. data, err := srcDb.TrieDB().Node(element.hash)
  307. if err != nil {
  308. t.Fatalf("failed to retrieve contract bytecode for %x", element.code)
  309. }
  310. nodeResults[i] = trie.NodeSyncResult{Path: element.path, Data: data}
  311. }
  312. for _, result := range nodeResults {
  313. if err := sched.ProcessNode(result); err != nil {
  314. t.Fatalf("failed to process result %v", err)
  315. }
  316. }
  317. nodeProcessed = len(nodeResults)
  318. }
  319. batch := dstDb.NewBatch()
  320. if err := sched.Commit(batch); err != nil {
  321. t.Fatalf("failed to commit data: %v", err)
  322. }
  323. batch.Write()
  324. paths, nodes, codes = sched.Missing(0)
  325. nodeElements = nodeElements[nodeProcessed:]
  326. for i := 0; i < len(paths); i++ {
  327. nodeElements = append(nodeElements, stateElement{
  328. path: paths[i],
  329. hash: nodes[i],
  330. syncPath: trie.NewSyncPath([]byte(paths[i])),
  331. })
  332. }
  333. codeElements = codeElements[codeProcessed:]
  334. for i := 0; i < len(codes); i++ {
  335. codeElements = append(codeElements, stateElement{
  336. code: codes[i],
  337. })
  338. }
  339. }
  340. // Cross check that the two states are in sync
  341. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  342. }
  343. // Tests that given a root hash, a trie can sync iteratively on a single thread,
  344. // requesting retrieval tasks and returning all of them in one go, however in a
  345. // random order.
  346. func TestIterativeRandomStateSyncIndividual(t *testing.T) { testIterativeRandomStateSync(t, 1) }
  347. func TestIterativeRandomStateSyncBatched(t *testing.T) { testIterativeRandomStateSync(t, 100) }
  348. func testIterativeRandomStateSync(t *testing.T, count int) {
  349. // Create a random state to copy
  350. srcDb, srcRoot, srcAccounts := makeTestState()
  351. // Create a destination state and sync with the scheduler
  352. dstDb := rawdb.NewMemoryDatabase()
  353. sched := NewStateSync(srcRoot, dstDb, nil)
  354. nodeQueue := make(map[string]stateElement)
  355. codeQueue := make(map[common.Hash]struct{})
  356. paths, nodes, codes := sched.Missing(count)
  357. for i, path := range paths {
  358. nodeQueue[path] = stateElement{
  359. path: path,
  360. hash: nodes[i],
  361. syncPath: trie.NewSyncPath([]byte(path)),
  362. }
  363. }
  364. for _, hash := range codes {
  365. codeQueue[hash] = struct{}{}
  366. }
  367. for len(nodeQueue)+len(codeQueue) > 0 {
  368. // Fetch all the queued nodes in a random order
  369. if len(codeQueue) > 0 {
  370. results := make([]trie.CodeSyncResult, 0, len(codeQueue))
  371. for hash := range codeQueue {
  372. data, err := srcDb.ContractCode(common.Hash{}, hash)
  373. if err != nil {
  374. t.Fatalf("failed to retrieve node data for %x", hash)
  375. }
  376. results = append(results, trie.CodeSyncResult{Hash: hash, Data: data})
  377. }
  378. for _, result := range results {
  379. if err := sched.ProcessCode(result); err != nil {
  380. t.Fatalf("failed to process result %v", err)
  381. }
  382. }
  383. }
  384. if len(nodeQueue) > 0 {
  385. results := make([]trie.NodeSyncResult, 0, len(nodeQueue))
  386. for path, element := range nodeQueue {
  387. data, err := srcDb.TrieDB().Node(element.hash)
  388. if err != nil {
  389. t.Fatalf("failed to retrieve node data for %x %v %v", element.hash, []byte(element.path), element.path)
  390. }
  391. results = append(results, trie.NodeSyncResult{Path: path, Data: data})
  392. }
  393. for _, result := range results {
  394. if err := sched.ProcessNode(result); err != nil {
  395. t.Fatalf("failed to process result %v", err)
  396. }
  397. }
  398. }
  399. // Feed the retrieved results back and queue new tasks
  400. batch := dstDb.NewBatch()
  401. if err := sched.Commit(batch); err != nil {
  402. t.Fatalf("failed to commit data: %v", err)
  403. }
  404. batch.Write()
  405. nodeQueue = make(map[string]stateElement)
  406. codeQueue = make(map[common.Hash]struct{})
  407. paths, nodes, codes := sched.Missing(count)
  408. for i, path := range paths {
  409. nodeQueue[path] = stateElement{
  410. path: path,
  411. hash: nodes[i],
  412. syncPath: trie.NewSyncPath([]byte(path)),
  413. }
  414. }
  415. for _, hash := range codes {
  416. codeQueue[hash] = struct{}{}
  417. }
  418. }
  419. // Cross check that the two states are in sync
  420. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  421. }
  422. // Tests that the trie scheduler can correctly reconstruct the state even if only
  423. // partial results are returned (Even those randomly), others sent only later.
  424. func TestIterativeRandomDelayedStateSync(t *testing.T) {
  425. // Create a random state to copy
  426. srcDb, srcRoot, srcAccounts := makeTestState()
  427. // Create a destination state and sync with the scheduler
  428. dstDb := rawdb.NewMemoryDatabase()
  429. sched := NewStateSync(srcRoot, dstDb, nil)
  430. nodeQueue := make(map[string]stateElement)
  431. codeQueue := make(map[common.Hash]struct{})
  432. paths, nodes, codes := sched.Missing(0)
  433. for i, path := range paths {
  434. nodeQueue[path] = stateElement{
  435. path: path,
  436. hash: nodes[i],
  437. syncPath: trie.NewSyncPath([]byte(path)),
  438. }
  439. }
  440. for _, hash := range codes {
  441. codeQueue[hash] = struct{}{}
  442. }
  443. for len(nodeQueue)+len(codeQueue) > 0 {
  444. // Sync only half of the scheduled nodes, even those in random order
  445. if len(codeQueue) > 0 {
  446. results := make([]trie.CodeSyncResult, 0, len(codeQueue)/2+1)
  447. for hash := range codeQueue {
  448. delete(codeQueue, hash)
  449. data, err := srcDb.ContractCode(common.Hash{}, hash)
  450. if err != nil {
  451. t.Fatalf("failed to retrieve node data for %x", hash)
  452. }
  453. results = append(results, trie.CodeSyncResult{Hash: hash, Data: data})
  454. if len(results) >= cap(results) {
  455. break
  456. }
  457. }
  458. for _, result := range results {
  459. if err := sched.ProcessCode(result); err != nil {
  460. t.Fatalf("failed to process result %v", err)
  461. }
  462. }
  463. }
  464. if len(nodeQueue) > 0 {
  465. results := make([]trie.NodeSyncResult, 0, len(nodeQueue)/2+1)
  466. for path, element := range nodeQueue {
  467. delete(nodeQueue, path)
  468. data, err := srcDb.TrieDB().Node(element.hash)
  469. if err != nil {
  470. t.Fatalf("failed to retrieve node data for %x", element.hash)
  471. }
  472. results = append(results, trie.NodeSyncResult{Path: path, Data: data})
  473. if len(results) >= cap(results) {
  474. break
  475. }
  476. }
  477. // Feed the retrieved results back and queue new tasks
  478. for _, result := range results {
  479. if err := sched.ProcessNode(result); err != nil {
  480. t.Fatalf("failed to process result %v", err)
  481. }
  482. }
  483. }
  484. batch := dstDb.NewBatch()
  485. if err := sched.Commit(batch); err != nil {
  486. t.Fatalf("failed to commit data: %v", err)
  487. }
  488. batch.Write()
  489. paths, nodes, codes := sched.Missing(0)
  490. for i, path := range paths {
  491. nodeQueue[path] = stateElement{
  492. path: path,
  493. hash: nodes[i],
  494. syncPath: trie.NewSyncPath([]byte(path)),
  495. }
  496. }
  497. for _, hash := range codes {
  498. codeQueue[hash] = struct{}{}
  499. }
  500. }
  501. // Cross check that the two states are in sync
  502. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  503. }
  504. // Tests that at any point in time during a sync, only complete sub-tries are in
  505. // the database.
  506. func TestIncompleteStateSync(t *testing.T) {
  507. // Create a random state to copy
  508. srcDb, srcRoot, srcAccounts := makeTestState()
  509. // isCodeLookup to save some hashing
  510. var isCode = make(map[common.Hash]struct{})
  511. for _, acc := range srcAccounts {
  512. if len(acc.code) > 0 {
  513. isCode[crypto.Keccak256Hash(acc.code)] = struct{}{}
  514. }
  515. }
  516. isCode[common.BytesToHash(emptyCodeHash)] = struct{}{}
  517. checkTrieConsistency(srcDb.TrieDB().DiskDB().(ethdb.Database), srcRoot)
  518. // Create a destination state and sync with the scheduler
  519. dstDb := rawdb.NewMemoryDatabase()
  520. sched := NewStateSync(srcRoot, dstDb, nil)
  521. var (
  522. addedCodes []common.Hash
  523. addedNodes []common.Hash
  524. )
  525. nodeQueue := make(map[string]stateElement)
  526. codeQueue := make(map[common.Hash]struct{})
  527. paths, nodes, codes := sched.Missing(1)
  528. for i, path := range paths {
  529. nodeQueue[path] = stateElement{
  530. path: path,
  531. hash: nodes[i],
  532. syncPath: trie.NewSyncPath([]byte(path)),
  533. }
  534. }
  535. for _, hash := range codes {
  536. codeQueue[hash] = struct{}{}
  537. }
  538. for len(nodeQueue)+len(codeQueue) > 0 {
  539. // Fetch a batch of state nodes
  540. if len(codeQueue) > 0 {
  541. results := make([]trie.CodeSyncResult, 0, len(codeQueue))
  542. for hash := range codeQueue {
  543. data, err := srcDb.ContractCode(common.Hash{}, hash)
  544. if err != nil {
  545. t.Fatalf("failed to retrieve node data for %x", hash)
  546. }
  547. results = append(results, trie.CodeSyncResult{Hash: hash, Data: data})
  548. addedCodes = append(addedCodes, hash)
  549. }
  550. // Process each of the state nodes
  551. for _, result := range results {
  552. if err := sched.ProcessCode(result); err != nil {
  553. t.Fatalf("failed to process result %v", err)
  554. }
  555. }
  556. }
  557. var nodehashes []common.Hash
  558. if len(nodeQueue) > 0 {
  559. results := make([]trie.NodeSyncResult, 0, len(nodeQueue))
  560. for key, element := range nodeQueue {
  561. data, err := srcDb.TrieDB().Node(element.hash)
  562. if err != nil {
  563. t.Fatalf("failed to retrieve node data for %x", element.hash)
  564. }
  565. results = append(results, trie.NodeSyncResult{Path: key, Data: data})
  566. if element.hash != srcRoot {
  567. addedNodes = append(addedNodes, element.hash)
  568. }
  569. nodehashes = append(nodehashes, element.hash)
  570. }
  571. // Process each of the state nodes
  572. for _, result := range results {
  573. if err := sched.ProcessNode(result); err != nil {
  574. t.Fatalf("failed to process result %v", err)
  575. }
  576. }
  577. }
  578. batch := dstDb.NewBatch()
  579. if err := sched.Commit(batch); err != nil {
  580. t.Fatalf("failed to commit data: %v", err)
  581. }
  582. batch.Write()
  583. for _, root := range nodehashes {
  584. // Can't use checkStateConsistency here because subtrie keys may have odd
  585. // length and crash in LeafKey.
  586. if err := checkTrieConsistency(dstDb, root); err != nil {
  587. t.Fatalf("state inconsistent: %v", err)
  588. }
  589. }
  590. // Fetch the next batch to retrieve
  591. nodeQueue = make(map[string]stateElement)
  592. codeQueue = make(map[common.Hash]struct{})
  593. paths, nodes, codes := sched.Missing(1)
  594. for i, path := range paths {
  595. nodeQueue[path] = stateElement{
  596. path: path,
  597. hash: nodes[i],
  598. syncPath: trie.NewSyncPath([]byte(path)),
  599. }
  600. }
  601. for _, hash := range codes {
  602. codeQueue[hash] = struct{}{}
  603. }
  604. }
  605. // Sanity check that removing any node from the database is detected
  606. for _, node := range addedCodes {
  607. val := rawdb.ReadCode(dstDb, node)
  608. rawdb.DeleteCode(dstDb, node)
  609. if err := checkStateConsistency(dstDb, srcRoot); err == nil {
  610. t.Errorf("trie inconsistency not caught, missing: %x", node)
  611. }
  612. rawdb.WriteCode(dstDb, node, val)
  613. }
  614. for _, node := range addedNodes {
  615. val := rawdb.ReadTrieNode(dstDb, node)
  616. rawdb.DeleteTrieNode(dstDb, node)
  617. if err := checkStateConsistency(dstDb, srcRoot); err == nil {
  618. t.Errorf("trie inconsistency not caught, missing: %v", node.Hex())
  619. }
  620. rawdb.WriteTrieNode(dstDb, node, val)
  621. }
  622. }