github.com/ccm-chain/ccmchain@v1.0.0/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/ccm-chain/ccmchain/common"
    25  	"github.com/ccm-chain/ccmchain/core/rawdb"
    26  	"github.com/ccm-chain/ccmchain/crypto"
    27  	"github.com/ccm-chain/ccmchain/database"
    28  	"github.com/ccm-chain/ccmchain/database/memorydb"
    29  	"github.com/ccm-chain/ccmchain/trie"
    30  )
    31  
    32  // testAccount is the data associated with an account used by the state tests.
    33  type testAccount struct {
    34  	address common.Address
    35  	balance *big.Int
    36  	nonce   uint64
    37  	code    []byte
    38  }
    39  
    40  // makeTestState create a sample test state to test node-wise reconstruction.
    41  func makeTestState() (Database, common.Hash, []*testAccount) {
    42  	// Create an empty state
    43  	db := NewDatabase(rawdb.NewMemoryDatabase())
    44  	state, _ := New(common.Hash{}, db, nil)
    45  
    46  	// Fill it with some arbitrary data
    47  	accounts := []*testAccount{}
    48  	for i := byte(0); i < 96; i++ {
    49  		obj := state.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
    50  		acc := &testAccount{address: common.BytesToAddress([]byte{i})}
    51  
    52  		obj.AddBalance(big.NewInt(int64(11 * i)))
    53  		acc.balance = big.NewInt(int64(11 * i))
    54  
    55  		obj.SetNonce(uint64(42 * i))
    56  		acc.nonce = uint64(42 * i)
    57  
    58  		if i%3 == 0 {
    59  			obj.SetCode(crypto.Keccak256Hash([]byte{i, i, i, i, i}), []byte{i, i, i, i, i})
    60  			acc.code = []byte{i, i, i, i, i}
    61  		}
    62  		state.updateStateObject(obj)
    63  		accounts = append(accounts, acc)
    64  	}
    65  	root, _ := state.Commit(false)
    66  
    67  	// Return the generated state
    68  	return db, root, accounts
    69  }
    70  
    71  // checkStateAccounts cross references a reconstructed state with an expected
    72  // account array.
    73  func checkStateAccounts(t *testing.T, db database.Database, root common.Hash, accounts []*testAccount) {
    74  	// Check root availability and state contents
    75  	state, err := New(root, NewDatabase(db), nil)
    76  	if err != nil {
    77  		t.Fatalf("failed to create state trie at %x: %v", root, err)
    78  	}
    79  	if err := checkStateConsistency(db, root); err != nil {
    80  		t.Fatalf("inconsistent state trie at %x: %v", root, err)
    81  	}
    82  	for i, acc := range accounts {
    83  		if balance := state.GetBalance(acc.address); balance.Cmp(acc.balance) != 0 {
    84  			t.Errorf("account %d: balance mismatch: have %v, want %v", i, balance, acc.balance)
    85  		}
    86  		if nonce := state.GetNonce(acc.address); nonce != acc.nonce {
    87  			t.Errorf("account %d: nonce mismatch: have %v, want %v", i, nonce, acc.nonce)
    88  		}
    89  		if code := state.GetCode(acc.address); !bytes.Equal(code, acc.code) {
    90  			t.Errorf("account %d: code mismatch: have %x, want %x", i, code, acc.code)
    91  		}
    92  	}
    93  }
    94  
    95  // checkTrieConsistency checks that all nodes in a (sub-)trie are indeed present.
    96  func checkTrieConsistency(db database.Database, root common.Hash) error {
    97  	if v, _ := db.Get(root[:]); v == nil {
    98  		return nil // Consider a non existent state consistent.
    99  	}
   100  	trie, err := trie.New(root, trie.NewDatabase(db))
   101  	if err != nil {
   102  		return err
   103  	}
   104  	it := trie.NodeIterator(nil)
   105  	for it.Next(true) {
   106  	}
   107  	return it.Error()
   108  }
   109  
   110  // checkStateConsistency checks that all data of a state root is present.
   111  func checkStateConsistency(db database.Database, root common.Hash) error {
   112  	// Create and iterate a state trie rooted in a sub-node
   113  	if _, err := db.Get(root.Bytes()); err != nil {
   114  		return nil // Consider a non existent state consistent.
   115  	}
   116  	state, err := New(root, NewDatabase(db), nil)
   117  	if err != nil {
   118  		return err
   119  	}
   120  	it := NewNodeIterator(state)
   121  	for it.Next() {
   122  	}
   123  	return it.Error
   124  }
   125  
   126  // Tests that an empty state is not scheduled for syncing.
   127  func TestEmptyStateSync(t *testing.T) {
   128  	empty := common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
   129  	if req := NewStateSync(empty, rawdb.NewMemoryDatabase(), trie.NewSyncBloom(1, memorydb.New())).Missing(1); len(req) != 0 {
   130  		t.Errorf("content requested for empty state: %v", req)
   131  	}
   132  }
   133  
   134  // Tests that given a root hash, a state can sync iteratively on a single thread,
   135  // requesting retrieval tasks and returning all of them in one go.
   136  func TestIterativeStateSyncIndividual(t *testing.T)         { testIterativeStateSync(t, 1, false) }
   137  func TestIterativeStateSyncBatched(t *testing.T)            { testIterativeStateSync(t, 100, false) }
   138  func TestIterativeStateSyncIndividualFromDisk(t *testing.T) { testIterativeStateSync(t, 1, true) }
   139  func TestIterativeStateSyncBatchedFromDisk(t *testing.T)    { testIterativeStateSync(t, 100, true) }
   140  
   141  func testIterativeStateSync(t *testing.T, count int, commit bool) {
   142  	// Create a random state to copy
   143  	srcDb, srcRoot, srcAccounts := makeTestState()
   144  	if commit {
   145  		srcDb.TrieDB().Commit(srcRoot, false, nil)
   146  	}
   147  	// Create a destination state and sync with the scheduler
   148  	dstDb := rawdb.NewMemoryDatabase()
   149  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
   150  
   151  	queue := append([]common.Hash{}, sched.Missing(count)...)
   152  	for len(queue) > 0 {
   153  		results := make([]trie.SyncResult, len(queue))
   154  		for i, hash := range queue {
   155  			data, err := srcDb.TrieDB().Node(hash)
   156  			if err != nil {
   157  				data, err = srcDb.ContractCode(common.Hash{}, hash)
   158  			}
   159  			if err != nil {
   160  				t.Fatalf("failed to retrieve node data for %x", hash)
   161  			}
   162  			results[i] = trie.SyncResult{Hash: hash, Data: data}
   163  		}
   164  		for _, result := range results {
   165  			if err := sched.Process(result); err != nil {
   166  				t.Fatalf("failed to process result %v", err)
   167  			}
   168  		}
   169  		batch := dstDb.NewBatch()
   170  		if err := sched.Commit(batch); err != nil {
   171  			t.Fatalf("failed to commit data: %v", err)
   172  		}
   173  		batch.Write()
   174  		queue = append(queue[:0], sched.Missing(count)...)
   175  	}
   176  	// Cross check that the two states are in sync
   177  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   178  }
   179  
   180  // Tests that the trie scheduler can correctly reconstruct the state even if only
   181  // partial results are returned, and the others sent only later.
   182  func TestIterativeDelayedStateSync(t *testing.T) {
   183  	// Create a random state to copy
   184  	srcDb, srcRoot, srcAccounts := makeTestState()
   185  
   186  	// Create a destination state and sync with the scheduler
   187  	dstDb := rawdb.NewMemoryDatabase()
   188  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
   189  
   190  	queue := append([]common.Hash{}, sched.Missing(0)...)
   191  	for len(queue) > 0 {
   192  		// Sync only half of the scheduled nodes
   193  		results := make([]trie.SyncResult, len(queue)/2+1)
   194  		for i, hash := range queue[:len(results)] {
   195  			data, err := srcDb.TrieDB().Node(hash)
   196  			if err != nil {
   197  				data, err = srcDb.ContractCode(common.Hash{}, hash)
   198  			}
   199  			if err != nil {
   200  				t.Fatalf("failed to retrieve node data for %x", hash)
   201  			}
   202  			results[i] = trie.SyncResult{Hash: hash, Data: data}
   203  		}
   204  		for _, result := range results {
   205  			if err := sched.Process(result); err != nil {
   206  				t.Fatalf("failed to process result %v", err)
   207  			}
   208  		}
   209  		batch := dstDb.NewBatch()
   210  		if err := sched.Commit(batch); err != nil {
   211  			t.Fatalf("failed to commit data: %v", err)
   212  		}
   213  		batch.Write()
   214  		queue = append(queue[len(results):], sched.Missing(0)...)
   215  	}
   216  	// Cross check that the two states are in sync
   217  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   218  }
   219  
   220  // Tests that given a root hash, a trie can sync iteratively on a single thread,
   221  // requesting retrieval tasks and returning all of them in one go, however in a
   222  // random order.
   223  func TestIterativeRandomStateSyncIndividual(t *testing.T) { testIterativeRandomStateSync(t, 1) }
   224  func TestIterativeRandomStateSyncBatched(t *testing.T)    { testIterativeRandomStateSync(t, 100) }
   225  
   226  func testIterativeRandomStateSync(t *testing.T, count int) {
   227  	// Create a random state to copy
   228  	srcDb, srcRoot, srcAccounts := makeTestState()
   229  
   230  	// Create a destination state and sync with the scheduler
   231  	dstDb := rawdb.NewMemoryDatabase()
   232  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
   233  
   234  	queue := make(map[common.Hash]struct{})
   235  	for _, hash := range sched.Missing(count) {
   236  		queue[hash] = struct{}{}
   237  	}
   238  	for len(queue) > 0 {
   239  		// Fetch all the queued nodes in a random order
   240  		results := make([]trie.SyncResult, 0, len(queue))
   241  		for hash := range queue {
   242  			data, err := srcDb.TrieDB().Node(hash)
   243  			if err != nil {
   244  				data, err = srcDb.ContractCode(common.Hash{}, hash)
   245  			}
   246  			if err != nil {
   247  				t.Fatalf("failed to retrieve node data for %x", hash)
   248  			}
   249  			results = append(results, trie.SyncResult{Hash: hash, Data: data})
   250  		}
   251  		// Feed the retrieved results back and queue new tasks
   252  		for _, result := range results {
   253  			if err := sched.Process(result); err != nil {
   254  				t.Fatalf("failed to process result %v", err)
   255  			}
   256  		}
   257  		batch := dstDb.NewBatch()
   258  		if err := sched.Commit(batch); err != nil {
   259  			t.Fatalf("failed to commit data: %v", err)
   260  		}
   261  		batch.Write()
   262  		queue = make(map[common.Hash]struct{})
   263  		for _, hash := range sched.Missing(count) {
   264  			queue[hash] = struct{}{}
   265  		}
   266  	}
   267  	// Cross check that the two states are in sync
   268  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   269  }
   270  
   271  // Tests that the trie scheduler can correctly reconstruct the state even if only
   272  // partial results are returned (Even those randomly), others sent only later.
   273  func TestIterativeRandomDelayedStateSync(t *testing.T) {
   274  	// Create a random state to copy
   275  	srcDb, srcRoot, srcAccounts := makeTestState()
   276  
   277  	// Create a destination state and sync with the scheduler
   278  	dstDb := rawdb.NewMemoryDatabase()
   279  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
   280  
   281  	queue := make(map[common.Hash]struct{})
   282  	for _, hash := range sched.Missing(0) {
   283  		queue[hash] = struct{}{}
   284  	}
   285  	for len(queue) > 0 {
   286  		// Sync only half of the scheduled nodes, even those in random order
   287  		results := make([]trie.SyncResult, 0, len(queue)/2+1)
   288  		for hash := range queue {
   289  			delete(queue, hash)
   290  
   291  			data, err := srcDb.TrieDB().Node(hash)
   292  			if err != nil {
   293  				data, err = srcDb.ContractCode(common.Hash{}, hash)
   294  			}
   295  			if err != nil {
   296  				t.Fatalf("failed to retrieve node data for %x", hash)
   297  			}
   298  			results = append(results, trie.SyncResult{Hash: hash, Data: data})
   299  
   300  			if len(results) >= cap(results) {
   301  				break
   302  			}
   303  		}
   304  		// Feed the retrieved results back and queue new tasks
   305  		for _, result := range results {
   306  			if err := sched.Process(result); err != nil {
   307  				t.Fatalf("failed to process result %v", err)
   308  			}
   309  		}
   310  		batch := dstDb.NewBatch()
   311  		if err := sched.Commit(batch); err != nil {
   312  			t.Fatalf("failed to commit data: %v", err)
   313  		}
   314  		batch.Write()
   315  		for _, hash := range sched.Missing(0) {
   316  			queue[hash] = struct{}{}
   317  		}
   318  	}
   319  	// Cross check that the two states are in sync
   320  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   321  }
   322  
   323  // Tests that at any point in time during a sync, only complete sub-tries are in
   324  // the database.
   325  func TestIncompleteStateSync(t *testing.T) {
   326  	// Create a random state to copy
   327  	srcDb, srcRoot, srcAccounts := makeTestState()
   328  
   329  	// isCode reports whether the hash is contract code hash.
   330  	isCode := func(hash common.Hash) bool {
   331  		for _, acc := range srcAccounts {
   332  			if hash == crypto.Keccak256Hash(acc.code) {
   333  				return true
   334  			}
   335  		}
   336  		return false
   337  	}
   338  	checkTrieConsistency(srcDb.TrieDB().DiskDB().(database.Database), srcRoot)
   339  
   340  	// Create a destination state and sync with the scheduler
   341  	dstDb := rawdb.NewMemoryDatabase()
   342  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
   343  
   344  	added := []common.Hash{}
   345  	queue := append([]common.Hash{}, sched.Missing(1)...)
   346  	for len(queue) > 0 {
   347  		// Fetch a batch of state nodes
   348  		results := make([]trie.SyncResult, len(queue))
   349  		for i, hash := range queue {
   350  			data, err := srcDb.TrieDB().Node(hash)
   351  			if err != nil {
   352  				data, err = srcDb.ContractCode(common.Hash{}, hash)
   353  			}
   354  			if err != nil {
   355  				t.Fatalf("failed to retrieve node data for %x", hash)
   356  			}
   357  			results[i] = trie.SyncResult{Hash: hash, Data: data}
   358  		}
   359  		// Process each of the state nodes
   360  		for _, result := range results {
   361  			if err := sched.Process(result); err != nil {
   362  				t.Fatalf("failed to process result %v", err)
   363  			}
   364  		}
   365  		batch := dstDb.NewBatch()
   366  		if err := sched.Commit(batch); err != nil {
   367  			t.Fatalf("failed to commit data: %v", err)
   368  		}
   369  		batch.Write()
   370  		for _, result := range results {
   371  			added = append(added, result.Hash)
   372  		}
   373  		// Check that all known sub-tries added so far are complete or missing entirely.
   374  		for _, hash := range added {
   375  			if isCode(hash) {
   376  				continue
   377  			}
   378  			// Can't use checkStateConsistency here because subtrie keys may have odd
   379  			// length and crash in LeafKey.
   380  			if err := checkTrieConsistency(dstDb, hash); err != nil {
   381  				t.Fatalf("state inconsistent: %v", err)
   382  			}
   383  		}
   384  		// Fetch the next batch to retrieve
   385  		queue = append(queue[:0], sched.Missing(1)...)
   386  	}
   387  	// Sanity check that removing any node from the database is detected
   388  	for _, node := range added[1:] {
   389  		var (
   390  			key  = node.Bytes()
   391  			code = isCode(node)
   392  			val  []byte
   393  		)
   394  		if code {
   395  			val = rawdb.ReadCode(dstDb, node)
   396  			rawdb.DeleteCode(dstDb, node)
   397  		} else {
   398  			val = rawdb.ReadTrieNode(dstDb, node)
   399  			rawdb.DeleteTrieNode(dstDb, node)
   400  		}
   401  		if err := checkStateConsistency(dstDb, added[0]); err == nil {
   402  			t.Fatalf("trie inconsistency not caught, missing: %x", key)
   403  		}
   404  		if code {
   405  			rawdb.WriteCode(dstDb, node, val)
   406  		} else {
   407  			rawdb.WriteTrieNode(dstDb, node, val)
   408  		}
   409  	}
   410  }