github.com/authcall/reference-optimistic-geth@v0.0.0-20220816224302-06313bfeb8d2/core/state/sync_test.go (about)

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