github.com/fff-chain/go-fff@v0.0.0-20220726032732-1c84420b8a99/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/fff-chain/go-fff/common"
    25  	"github.com/fff-chain/go-fff/core/rawdb"
    26  	"github.com/fff-chain/go-fff/crypto"
    27  	"github.com/fff-chain/go-fff/ethdb"
    28  	"github.com/fff-chain/go-fff/ethdb/memorydb"
    29  	"github.com/fff-chain/go-fff/rlp"
    30  	"github.com/fff-chain/go-fff/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  	state.Finalise(false)
    73  	state.AccountsIntermediateRoot()
    74  	root, _, _ := state.Commit(nil)
    75  
    76  	// Return the generated state
    77  	return db, root, accounts
    78  }
    79  
    80  // checkStateAccounts cross references a reconstructed state with an expected
    81  // account array.
    82  func checkStateAccounts(t *testing.T, db ethdb.Database, root common.Hash, accounts []*testAccount) {
    83  	// Check root availability and state contents
    84  	state, err := New(root, NewDatabase(db), nil)
    85  	if err != nil {
    86  		t.Fatalf("failed to create state trie at %x: %v", root, err)
    87  	}
    88  	if err := checkStateConsistency(db, root); err != nil {
    89  		t.Fatalf("inconsistent state trie at %x: %v", root, err)
    90  	}
    91  	for i, acc := range accounts {
    92  		if balance := state.GetBalance(acc.address); balance.Cmp(acc.balance) != 0 {
    93  			t.Errorf("account %d: balance mismatch: have %v, want %v", i, balance, acc.balance)
    94  		}
    95  		if nonce := state.GetNonce(acc.address); nonce != acc.nonce {
    96  			t.Errorf("account %d: nonce mismatch: have %v, want %v", i, nonce, acc.nonce)
    97  		}
    98  		if code := state.GetCode(acc.address); !bytes.Equal(code, acc.code) {
    99  			t.Errorf("account %d: code mismatch: have %x, want %x", i, code, acc.code)
   100  		}
   101  	}
   102  }
   103  
   104  // checkTrieConsistency checks that all nodes in a (sub-)trie are indeed present.
   105  func checkTrieConsistency(db ethdb.Database, root common.Hash) error {
   106  	if v, _ := db.Get(root[:]); v == nil {
   107  		return nil // Consider a non existent state consistent.
   108  	}
   109  	trie, err := trie.New(root, trie.NewDatabase(db))
   110  	if err != nil {
   111  		return err
   112  	}
   113  	it := trie.NodeIterator(nil)
   114  	for it.Next(true) {
   115  	}
   116  	return it.Error()
   117  }
   118  
   119  // checkStateConsistency checks that all data of a state root is present.
   120  func checkStateConsistency(db ethdb.Database, root common.Hash) error {
   121  	// Create and iterate a state trie rooted in a sub-node
   122  	if _, err := db.Get(root.Bytes()); err != nil {
   123  		return nil // Consider a non existent state consistent.
   124  	}
   125  	state, err := New(root, NewDatabase(db), nil)
   126  	if err != nil {
   127  		return err
   128  	}
   129  	it := NewNodeIterator(state)
   130  	for it.Next() {
   131  	}
   132  	return it.Error
   133  }
   134  
   135  // Tests that an empty state is not scheduled for syncing.
   136  func TestEmptyStateSync(t *testing.T) {
   137  	empty := common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
   138  	sync := NewStateSync(empty, rawdb.NewMemoryDatabase(), trie.NewSyncBloom(1, memorydb.New()), nil)
   139  	if nodes, paths, codes := sync.Missing(1); len(nodes) != 0 || len(paths) != 0 || len(codes) != 0 {
   140  		t.Errorf(" content requested for empty state: %v, %v, %v", nodes, paths, codes)
   141  	}
   142  }
   143  
   144  // Tests that given a root hash, a state can sync iteratively on a single thread,
   145  // requesting retrieval tasks and returning all of them in one go.
   146  func TestIterativeStateSyncIndividual(t *testing.T) {
   147  	testIterativeStateSync(t, 1, false, false)
   148  }
   149  func TestIterativeStateSyncBatched(t *testing.T) {
   150  	testIterativeStateSync(t, 100, false, false)
   151  }
   152  func TestIterativeStateSyncIndividualFromDisk(t *testing.T) {
   153  	testIterativeStateSync(t, 1, true, false)
   154  }
   155  func TestIterativeStateSyncBatchedFromDisk(t *testing.T) {
   156  	testIterativeStateSync(t, 100, true, false)
   157  }
   158  func TestIterativeStateSyncIndividualByPath(t *testing.T) {
   159  	testIterativeStateSync(t, 1, false, true)
   160  }
   161  func TestIterativeStateSyncBatchedByPath(t *testing.T) {
   162  	testIterativeStateSync(t, 100, false, true)
   163  }
   164  
   165  func testIterativeStateSync(t *testing.T, count int, commit bool, bypath bool) {
   166  	// Create a random state to copy
   167  	srcDb, srcRoot, srcAccounts := makeTestState()
   168  	if commit {
   169  		srcDb.TrieDB().Commit(srcRoot, false, nil)
   170  	}
   171  	srcTrie, _ := trie.New(srcRoot, srcDb.TrieDB())
   172  
   173  	// Create a destination state and sync with the scheduler
   174  	dstDb := rawdb.NewMemoryDatabase()
   175  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb), nil)
   176  
   177  	nodes, paths, codes := sched.Missing(count)
   178  	var (
   179  		hashQueue []common.Hash
   180  		pathQueue []trie.SyncPath
   181  	)
   182  	if !bypath {
   183  		hashQueue = append(append(hashQueue[:0], nodes...), codes...)
   184  	} else {
   185  		hashQueue = append(hashQueue[:0], codes...)
   186  		pathQueue = append(pathQueue[:0], paths...)
   187  	}
   188  	for len(hashQueue)+len(pathQueue) > 0 {
   189  		results := make([]trie.SyncResult, len(hashQueue)+len(pathQueue))
   190  		for i, hash := range hashQueue {
   191  			data, err := srcDb.TrieDB().Node(hash)
   192  			if err != nil {
   193  				data, err = srcDb.ContractCode(common.Hash{}, hash)
   194  			}
   195  			if err != nil {
   196  				t.Fatalf("failed to retrieve node data for hash %x", hash)
   197  			}
   198  			results[i] = trie.SyncResult{Hash: hash, Data: data}
   199  		}
   200  		for i, path := range pathQueue {
   201  			if len(path) == 1 {
   202  				data, _, err := srcTrie.TryGetNode(path[0])
   203  				if err != nil {
   204  					t.Fatalf("failed to retrieve node data for path %x: %v", path, err)
   205  				}
   206  				results[len(hashQueue)+i] = trie.SyncResult{Hash: crypto.Keccak256Hash(data), Data: data}
   207  			} else {
   208  				var acc Account
   209  				if err := rlp.DecodeBytes(srcTrie.Get(path[0]), &acc); err != nil {
   210  					t.Fatalf("failed to decode account on path %x: %v", path, err)
   211  				}
   212  				stTrie, err := trie.New(acc.Root, srcDb.TrieDB())
   213  				if err != nil {
   214  					t.Fatalf("failed to retriev storage trie for path %x: %v", path, err)
   215  				}
   216  				data, _, err := stTrie.TryGetNode(path[1])
   217  				if err != nil {
   218  					t.Fatalf("failed to retrieve node data for path %x: %v", path, err)
   219  				}
   220  				results[len(hashQueue)+i] = trie.SyncResult{Hash: crypto.Keccak256Hash(data), Data: data}
   221  			}
   222  		}
   223  		for _, result := range results {
   224  			if err := sched.Process(result); err != nil {
   225  				t.Errorf("failed to process result %v", err)
   226  			}
   227  		}
   228  		batch := dstDb.NewBatch()
   229  		if err := sched.Commit(batch); err != nil {
   230  			t.Fatalf("failed to commit data: %v", err)
   231  		}
   232  		batch.Write()
   233  
   234  		nodes, paths, codes = sched.Missing(count)
   235  		if !bypath {
   236  			hashQueue = append(append(hashQueue[:0], nodes...), codes...)
   237  		} else {
   238  			hashQueue = append(hashQueue[:0], codes...)
   239  			pathQueue = append(pathQueue[:0], paths...)
   240  		}
   241  	}
   242  	// Cross check that the two states are in sync
   243  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   244  }
   245  
   246  // Tests that the trie scheduler can correctly reconstruct the state even if only
   247  // partial results are returned, and the others sent only later.
   248  func TestIterativeDelayedStateSync(t *testing.T) {
   249  	// Create a random state to copy
   250  	srcDb, srcRoot, srcAccounts := makeTestState()
   251  
   252  	// Create a destination state and sync with the scheduler
   253  	dstDb := rawdb.NewMemoryDatabase()
   254  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb), nil)
   255  
   256  	nodes, _, codes := sched.Missing(0)
   257  	queue := append(append([]common.Hash{}, nodes...), codes...)
   258  
   259  	for len(queue) > 0 {
   260  		// Sync only half of the scheduled nodes
   261  		results := make([]trie.SyncResult, len(queue)/2+1)
   262  		for i, hash := range queue[:len(results)] {
   263  			data, err := srcDb.TrieDB().Node(hash)
   264  			if err != nil {
   265  				data, err = srcDb.ContractCode(common.Hash{}, hash)
   266  			}
   267  			if err != nil {
   268  				t.Fatalf("failed to retrieve node data for %x", hash)
   269  			}
   270  			results[i] = trie.SyncResult{Hash: hash, Data: data}
   271  		}
   272  		for _, result := range results {
   273  			if err := sched.Process(result); err != nil {
   274  				t.Fatalf("failed to process result %v", err)
   275  			}
   276  		}
   277  		batch := dstDb.NewBatch()
   278  		if err := sched.Commit(batch); err != nil {
   279  			t.Fatalf("failed to commit data: %v", err)
   280  		}
   281  		batch.Write()
   282  
   283  		nodes, _, codes = sched.Missing(0)
   284  		queue = append(append(queue[len(results):], nodes...), codes...)
   285  	}
   286  	// Cross check that the two states are in sync
   287  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   288  }
   289  
   290  // Tests that given a root hash, a trie can sync iteratively on a single thread,
   291  // requesting retrieval tasks and returning all of them in one go, however in a
   292  // random order.
   293  func TestIterativeRandomStateSyncIndividual(t *testing.T) { testIterativeRandomStateSync(t, 1) }
   294  func TestIterativeRandomStateSyncBatched(t *testing.T)    { testIterativeRandomStateSync(t, 100) }
   295  
   296  func testIterativeRandomStateSync(t *testing.T, count int) {
   297  	// Create a random state to copy
   298  	srcDb, srcRoot, srcAccounts := makeTestState()
   299  
   300  	// Create a destination state and sync with the scheduler
   301  	dstDb := rawdb.NewMemoryDatabase()
   302  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb), nil)
   303  
   304  	queue := make(map[common.Hash]struct{})
   305  	nodes, _, codes := sched.Missing(count)
   306  	for _, hash := range append(nodes, codes...) {
   307  		queue[hash] = struct{}{}
   308  	}
   309  	for len(queue) > 0 {
   310  		// Fetch all the queued nodes in a random order
   311  		results := make([]trie.SyncResult, 0, len(queue))
   312  		for hash := range queue {
   313  			data, err := srcDb.TrieDB().Node(hash)
   314  			if err != nil {
   315  				data, err = srcDb.ContractCode(common.Hash{}, hash)
   316  			}
   317  			if err != nil {
   318  				t.Fatalf("failed to retrieve node data for %x", hash)
   319  			}
   320  			results = append(results, trie.SyncResult{Hash: hash, Data: data})
   321  		}
   322  		// Feed the retrieved results back and queue new tasks
   323  		for _, result := range results {
   324  			if err := sched.Process(result); err != nil {
   325  				t.Fatalf("failed to process result %v", err)
   326  			}
   327  		}
   328  		batch := dstDb.NewBatch()
   329  		if err := sched.Commit(batch); err != nil {
   330  			t.Fatalf("failed to commit data: %v", err)
   331  		}
   332  		batch.Write()
   333  
   334  		queue = make(map[common.Hash]struct{})
   335  		nodes, _, codes = sched.Missing(count)
   336  		for _, hash := range append(nodes, codes...) {
   337  			queue[hash] = struct{}{}
   338  		}
   339  	}
   340  	// Cross check that the two states are in sync
   341  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   342  }
   343  
   344  // Tests that the trie scheduler can correctly reconstruct the state even if only
   345  // partial results are returned (Even those randomly), others sent only later.
   346  func TestIterativeRandomDelayedStateSync(t *testing.T) {
   347  	// Create a random state to copy
   348  	srcDb, srcRoot, srcAccounts := makeTestState()
   349  
   350  	// Create a destination state and sync with the scheduler
   351  	dstDb := rawdb.NewMemoryDatabase()
   352  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb), nil)
   353  
   354  	queue := make(map[common.Hash]struct{})
   355  	nodes, _, codes := sched.Missing(0)
   356  	for _, hash := range append(nodes, codes...) {
   357  		queue[hash] = struct{}{}
   358  	}
   359  	for len(queue) > 0 {
   360  		// Sync only half of the scheduled nodes, even those in random order
   361  		results := make([]trie.SyncResult, 0, len(queue)/2+1)
   362  		for hash := range queue {
   363  			delete(queue, hash)
   364  
   365  			data, err := srcDb.TrieDB().Node(hash)
   366  			if err != nil {
   367  				data, err = srcDb.ContractCode(common.Hash{}, hash)
   368  			}
   369  			if err != nil {
   370  				t.Fatalf("failed to retrieve node data for %x", hash)
   371  			}
   372  			results = append(results, trie.SyncResult{Hash: hash, Data: data})
   373  
   374  			if len(results) >= cap(results) {
   375  				break
   376  			}
   377  		}
   378  		// Feed the retrieved results back and queue new tasks
   379  		for _, result := range results {
   380  			if err := sched.Process(result); err != nil {
   381  				t.Fatalf("failed to process result %v", err)
   382  			}
   383  		}
   384  		batch := dstDb.NewBatch()
   385  		if err := sched.Commit(batch); err != nil {
   386  			t.Fatalf("failed to commit data: %v", err)
   387  		}
   388  		batch.Write()
   389  		for _, result := range results {
   390  			delete(queue, result.Hash)
   391  		}
   392  		nodes, _, codes = sched.Missing(0)
   393  		for _, hash := range append(nodes, codes...) {
   394  			queue[hash] = struct{}{}
   395  		}
   396  	}
   397  	// Cross check that the two states are in sync
   398  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   399  }
   400  
   401  // Tests that at any point in time during a sync, only complete sub-tries are in
   402  // the database.
   403  func TestIncompleteStateSync(t *testing.T) {
   404  	// Create a random state to copy
   405  	srcDb, srcRoot, srcAccounts := makeTestState()
   406  
   407  	// isCodeLookup to save some hashing
   408  	var isCode = make(map[common.Hash]struct{})
   409  	for _, acc := range srcAccounts {
   410  		if len(acc.code) > 0 {
   411  			isCode[crypto.Keccak256Hash(acc.code)] = struct{}{}
   412  		}
   413  	}
   414  	isCode[common.BytesToHash(emptyCodeHash)] = struct{}{}
   415  	checkTrieConsistency(srcDb.TrieDB().DiskDB().(ethdb.Database), srcRoot)
   416  
   417  	// Create a destination state and sync with the scheduler
   418  	dstDb := rawdb.NewMemoryDatabase()
   419  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb), nil)
   420  
   421  	var added []common.Hash
   422  
   423  	nodes, _, codes := sched.Missing(1)
   424  	queue := append(append([]common.Hash{}, nodes...), codes...)
   425  
   426  	for len(queue) > 0 {
   427  		// Fetch a batch of state nodes
   428  		results := make([]trie.SyncResult, len(queue))
   429  		for i, hash := range queue {
   430  			data, err := srcDb.TrieDB().Node(hash)
   431  			if err != nil {
   432  				data, err = srcDb.ContractCode(common.Hash{}, hash)
   433  			}
   434  			if err != nil {
   435  				t.Fatalf("failed to retrieve node data for %x", hash)
   436  			}
   437  			results[i] = trie.SyncResult{Hash: hash, Data: data}
   438  		}
   439  		// Process each of the state nodes
   440  		for _, result := range results {
   441  			if err := sched.Process(result); err != nil {
   442  				t.Fatalf("failed to process result %v", err)
   443  			}
   444  		}
   445  		batch := dstDb.NewBatch()
   446  		if err := sched.Commit(batch); err != nil {
   447  			t.Fatalf("failed to commit data: %v", err)
   448  		}
   449  		batch.Write()
   450  		for _, result := range results {
   451  			added = append(added, result.Hash)
   452  			// Check that all known sub-tries added so far are complete or missing entirely.
   453  			if _, ok := isCode[result.Hash]; ok {
   454  				continue
   455  			}
   456  			// Can't use checkStateConsistency here because subtrie keys may have odd
   457  			// length and crash in LeafKey.
   458  			if err := checkTrieConsistency(dstDb, result.Hash); err != nil {
   459  				t.Fatalf("state inconsistent: %v", err)
   460  			}
   461  		}
   462  		// Fetch the next batch to retrieve
   463  		nodes, _, codes = sched.Missing(1)
   464  		queue = append(append(queue[:0], nodes...), codes...)
   465  	}
   466  	// Sanity check that removing any node from the database is detected
   467  	for _, node := range added[1:] {
   468  		var (
   469  			key     = node.Bytes()
   470  			_, code = isCode[node]
   471  			val     []byte
   472  		)
   473  		if code {
   474  			val = rawdb.ReadCode(dstDb, node)
   475  			rawdb.DeleteCode(dstDb, node)
   476  		} else {
   477  			val = rawdb.ReadTrieNode(dstDb, node)
   478  			rawdb.DeleteTrieNode(dstDb, node)
   479  		}
   480  		if err := checkStateConsistency(dstDb, added[0]); err == nil {
   481  			t.Fatalf("trie inconsistency not caught, missing: %x", key)
   482  		}
   483  		if code {
   484  			rawdb.WriteCode(dstDb, node, val)
   485  		} else {
   486  			rawdb.WriteTrieNode(dstDb, node, val)
   487  		}
   488  	}
   489  }