github.com/ylsGit/go-ethereum@v1.6.5/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/crypto"
    26  	"github.com/ethereum/go-ethereum/ethdb"
    27  	"github.com/ethereum/go-ethereum/trie"
    28  )
    29  
    30  // testAccount is the data associated with an account used by the state tests.
    31  type testAccount struct {
    32  	address common.Address
    33  	balance *big.Int
    34  	nonce   uint64
    35  	code    []byte
    36  }
    37  
    38  // makeTestState create a sample test state to test node-wise reconstruction.
    39  func makeTestState() (ethdb.Database, common.Hash, []*testAccount) {
    40  	// Create an empty state
    41  	db, _ := ethdb.NewMemDatabase()
    42  	state, _ := New(common.Hash{}, db)
    43  
    44  	// Fill it with some arbitrary data
    45  	accounts := []*testAccount{}
    46  	for i := byte(0); i < 96; i++ {
    47  		obj := state.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
    48  		acc := &testAccount{address: common.BytesToAddress([]byte{i})}
    49  
    50  		obj.AddBalance(big.NewInt(int64(11 * i)))
    51  		acc.balance = big.NewInt(int64(11 * i))
    52  
    53  		obj.SetNonce(uint64(42 * i))
    54  		acc.nonce = uint64(42 * i)
    55  
    56  		if i%3 == 0 {
    57  			obj.SetCode(crypto.Keccak256Hash([]byte{i, i, i, i, i}), []byte{i, i, i, i, i})
    58  			acc.code = []byte{i, i, i, i, i}
    59  		}
    60  		state.updateStateObject(obj)
    61  		accounts = append(accounts, acc)
    62  	}
    63  	root, _ := state.Commit(false)
    64  
    65  	// Return the generated state
    66  	return db, root, accounts
    67  }
    68  
    69  // checkStateAccounts cross references a reconstructed state with an expected
    70  // account array.
    71  func checkStateAccounts(t *testing.T, db ethdb.Database, root common.Hash, accounts []*testAccount) {
    72  	// Check root availability and state contents
    73  	state, err := New(root, db)
    74  	if err != nil {
    75  		t.Fatalf("failed to create state trie at %x: %v", root, err)
    76  	}
    77  	if err := checkStateConsistency(db, root); err != nil {
    78  		t.Fatalf("inconsistent state trie at %x: %v", root, err)
    79  	}
    80  	for i, acc := range accounts {
    81  		if balance := state.GetBalance(acc.address); balance.Cmp(acc.balance) != 0 {
    82  			t.Errorf("account %d: balance mismatch: have %v, want %v", i, balance, acc.balance)
    83  		}
    84  		if nonce := state.GetNonce(acc.address); nonce != acc.nonce {
    85  			t.Errorf("account %d: nonce mismatch: have %v, want %v", i, nonce, acc.nonce)
    86  		}
    87  		if code := state.GetCode(acc.address); !bytes.Equal(code, acc.code) {
    88  			t.Errorf("account %d: code mismatch: have %x, want %x", i, code, acc.code)
    89  		}
    90  	}
    91  }
    92  
    93  // checkStateConsistency checks that all nodes in a state trie are indeed present.
    94  func checkStateConsistency(db ethdb.Database, root common.Hash) error {
    95  	// Create and iterate a state trie rooted in a sub-node
    96  	if _, err := db.Get(root.Bytes()); err != nil {
    97  		return nil // Consider a non existent state consistent
    98  	}
    99  	state, err := New(root, db)
   100  	if err != nil {
   101  		return err
   102  	}
   103  	it := NewNodeIterator(state)
   104  	for it.Next() {
   105  	}
   106  	return it.Error
   107  }
   108  
   109  // Tests that an empty state is not scheduled for syncing.
   110  func TestEmptyStateSync(t *testing.T) {
   111  	empty := common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
   112  	db, _ := ethdb.NewMemDatabase()
   113  	if req := NewStateSync(empty, db).Missing(1); len(req) != 0 {
   114  		t.Errorf("content requested for empty state: %v", req)
   115  	}
   116  }
   117  
   118  // Tests that given a root hash, a state can sync iteratively on a single thread,
   119  // requesting retrieval tasks and returning all of them in one go.
   120  func TestIterativeStateSyncIndividual(t *testing.T) { testIterativeStateSync(t, 1) }
   121  func TestIterativeStateSyncBatched(t *testing.T)    { testIterativeStateSync(t, 100) }
   122  
   123  func testIterativeStateSync(t *testing.T, batch int) {
   124  	// Create a random state to copy
   125  	srcDb, srcRoot, srcAccounts := makeTestState()
   126  
   127  	// Create a destination state and sync with the scheduler
   128  	dstDb, _ := ethdb.NewMemDatabase()
   129  	sched := NewStateSync(srcRoot, dstDb)
   130  
   131  	queue := append([]common.Hash{}, sched.Missing(batch)...)
   132  	for len(queue) > 0 {
   133  		results := make([]trie.SyncResult, len(queue))
   134  		for i, hash := range queue {
   135  			data, err := srcDb.Get(hash.Bytes())
   136  			if err != nil {
   137  				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
   138  			}
   139  			results[i] = trie.SyncResult{Hash: hash, Data: data}
   140  		}
   141  		if _, index, err := sched.Process(results, dstDb); err != nil {
   142  			t.Fatalf("failed to process result #%d: %v", index, err)
   143  		}
   144  		queue = append(queue[:0], sched.Missing(batch)...)
   145  	}
   146  	// Cross check that the two states are in sync
   147  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   148  }
   149  
   150  // Tests that the trie scheduler can correctly reconstruct the state even if only
   151  // partial results are returned, and the others sent only later.
   152  func TestIterativeDelayedStateSync(t *testing.T) {
   153  	// Create a random state to copy
   154  	srcDb, srcRoot, srcAccounts := makeTestState()
   155  
   156  	// Create a destination state and sync with the scheduler
   157  	dstDb, _ := ethdb.NewMemDatabase()
   158  	sched := NewStateSync(srcRoot, dstDb)
   159  
   160  	queue := append([]common.Hash{}, sched.Missing(0)...)
   161  	for len(queue) > 0 {
   162  		// Sync only half of the scheduled nodes
   163  		results := make([]trie.SyncResult, len(queue)/2+1)
   164  		for i, hash := range queue[:len(results)] {
   165  			data, err := srcDb.Get(hash.Bytes())
   166  			if err != nil {
   167  				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
   168  			}
   169  			results[i] = trie.SyncResult{Hash: hash, Data: data}
   170  		}
   171  		if _, index, err := sched.Process(results, dstDb); err != nil {
   172  			t.Fatalf("failed to process result #%d: %v", index, err)
   173  		}
   174  		queue = append(queue[len(results):], sched.Missing(0)...)
   175  	}
   176  	// Cross check that the two states are in sync
   177  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   178  }
   179  
   180  // Tests that given a root hash, a trie can sync iteratively on a single thread,
   181  // requesting retrieval tasks and returning all of them in one go, however in a
   182  // random order.
   183  func TestIterativeRandomStateSyncIndividual(t *testing.T) { testIterativeRandomStateSync(t, 1) }
   184  func TestIterativeRandomStateSyncBatched(t *testing.T)    { testIterativeRandomStateSync(t, 100) }
   185  
   186  func testIterativeRandomStateSync(t *testing.T, batch int) {
   187  	// Create a random state to copy
   188  	srcDb, srcRoot, srcAccounts := makeTestState()
   189  
   190  	// Create a destination state and sync with the scheduler
   191  	dstDb, _ := ethdb.NewMemDatabase()
   192  	sched := NewStateSync(srcRoot, dstDb)
   193  
   194  	queue := make(map[common.Hash]struct{})
   195  	for _, hash := range sched.Missing(batch) {
   196  		queue[hash] = struct{}{}
   197  	}
   198  	for len(queue) > 0 {
   199  		// Fetch all the queued nodes in a random order
   200  		results := make([]trie.SyncResult, 0, len(queue))
   201  		for hash := range queue {
   202  			data, err := srcDb.Get(hash.Bytes())
   203  			if err != nil {
   204  				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
   205  			}
   206  			results = append(results, trie.SyncResult{Hash: hash, Data: data})
   207  		}
   208  		// Feed the retrieved results back and queue new tasks
   209  		if _, index, err := sched.Process(results, dstDb); err != nil {
   210  			t.Fatalf("failed to process result #%d: %v", index, err)
   211  		}
   212  		queue = make(map[common.Hash]struct{})
   213  		for _, hash := range sched.Missing(batch) {
   214  			queue[hash] = struct{}{}
   215  		}
   216  	}
   217  	// Cross check that the two states are in sync
   218  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   219  }
   220  
   221  // Tests that the trie scheduler can correctly reconstruct the state even if only
   222  // partial results are returned (Even those randomly), others sent only later.
   223  func TestIterativeRandomDelayedStateSync(t *testing.T) {
   224  	// Create a random state to copy
   225  	srcDb, srcRoot, srcAccounts := makeTestState()
   226  
   227  	// Create a destination state and sync with the scheduler
   228  	dstDb, _ := ethdb.NewMemDatabase()
   229  	sched := NewStateSync(srcRoot, dstDb)
   230  
   231  	queue := make(map[common.Hash]struct{})
   232  	for _, hash := range sched.Missing(0) {
   233  		queue[hash] = struct{}{}
   234  	}
   235  	for len(queue) > 0 {
   236  		// Sync only half of the scheduled nodes, even those in random order
   237  		results := make([]trie.SyncResult, 0, len(queue)/2+1)
   238  		for hash := range queue {
   239  			delete(queue, hash)
   240  
   241  			data, err := srcDb.Get(hash.Bytes())
   242  			if err != nil {
   243  				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
   244  			}
   245  			results = append(results, trie.SyncResult{Hash: hash, Data: data})
   246  
   247  			if len(results) >= cap(results) {
   248  				break
   249  			}
   250  		}
   251  		// Feed the retrieved results back and queue new tasks
   252  		if _, index, err := sched.Process(results, dstDb); err != nil {
   253  			t.Fatalf("failed to process result #%d: %v", index, err)
   254  		}
   255  		for _, hash := range sched.Missing(0) {
   256  			queue[hash] = struct{}{}
   257  		}
   258  	}
   259  	// Cross check that the two states are in sync
   260  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   261  }
   262  
   263  // Tests that at any point in time during a sync, only complete sub-tries are in
   264  // the database.
   265  func TestIncompleteStateSync(t *testing.T) {
   266  	// Create a random state to copy
   267  	srcDb, srcRoot, srcAccounts := makeTestState()
   268  
   269  	// Create a destination state and sync with the scheduler
   270  	dstDb, _ := ethdb.NewMemDatabase()
   271  	sched := NewStateSync(srcRoot, dstDb)
   272  
   273  	added := []common.Hash{}
   274  	queue := append([]common.Hash{}, sched.Missing(1)...)
   275  	for len(queue) > 0 {
   276  		// Fetch a batch of state nodes
   277  		results := make([]trie.SyncResult, len(queue))
   278  		for i, hash := range queue {
   279  			data, err := srcDb.Get(hash.Bytes())
   280  			if err != nil {
   281  				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
   282  			}
   283  			results[i] = trie.SyncResult{Hash: hash, Data: data}
   284  		}
   285  		// Process each of the state nodes
   286  		if _, index, err := sched.Process(results, dstDb); err != nil {
   287  			t.Fatalf("failed to process result #%d: %v", index, err)
   288  		}
   289  		for _, result := range results {
   290  			added = append(added, result.Hash)
   291  		}
   292  		// Check that all known sub-tries in the synced state is complete
   293  		for _, root := range added {
   294  			// Skim through the accounts and make sure the root hash is not a code node
   295  			codeHash := false
   296  			for _, acc := range srcAccounts {
   297  				if root == crypto.Keccak256Hash(acc.code) {
   298  					codeHash = true
   299  					break
   300  				}
   301  			}
   302  			// If the root is a real trie node, check consistency
   303  			if !codeHash {
   304  				if err := checkStateConsistency(dstDb, root); err != nil {
   305  					t.Fatalf("state inconsistent: %v", err)
   306  				}
   307  			}
   308  		}
   309  		// Fetch the next batch to retrieve
   310  		queue = append(queue[:0], sched.Missing(1)...)
   311  	}
   312  	// Sanity check that removing any node from the database is detected
   313  	for _, node := range added[1:] {
   314  		key := node.Bytes()
   315  		value, _ := dstDb.Get(key)
   316  
   317  		dstDb.Delete(key)
   318  		if err := checkStateConsistency(dstDb, added[0]); err == nil {
   319  			t.Fatalf("trie inconsistency not caught, missing: %x", key)
   320  		}
   321  		dstDb.Put(key, value)
   322  	}
   323  }