github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/parallel_trie/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 trie
    18  
    19  import (
    20  	"bytes"
    21  	"testing"
    22  
    23  	"github.com/bigzoro/my_simplechain/ethdb/memorydb"
    24  
    25  	"github.com/bigzoro/my_simplechain/common"
    26  )
    27  
    28  // makeTestTrie create a sample test trie to test node-wise reconstruction.
    29  func makeTestTrie() (*Database, *Trie, map[string][]byte) {
    30  	// Create an empty trie
    31  	triedb := NewDatabase(memorydb.New())
    32  	trie, _ := New(common.Hash{}, triedb)
    33  
    34  	// Fill it with some arbitrary data
    35  	content := make(map[string][]byte)
    36  	for i := byte(0); i < 255; i++ {
    37  		// Map the same data under multiple keys
    38  		key, val := common.LeftPadBytes([]byte{1, i}, 32), []byte{i}
    39  		content[string(key)] = val
    40  		trie.Update(key, val)
    41  
    42  		key, val = common.LeftPadBytes([]byte{2, i}, 32), []byte{i}
    43  		content[string(key)] = val
    44  		trie.Update(key, val)
    45  
    46  		// Add some other data to inflate the trie
    47  		for j := byte(3); j < 13; j++ {
    48  			key, val = common.LeftPadBytes([]byte{j, i}, 32), []byte{j, i}
    49  			content[string(key)] = val
    50  			trie.Update(key, val)
    51  		}
    52  	}
    53  	trie.Commit(nil)
    54  
    55  	// Return the generated trie
    56  	return triedb, trie, content
    57  }
    58  
    59  // checkTrieContents cross references a reconstructed trie with an expected data
    60  // content map.
    61  func checkTrieContents(t *testing.T, db *Database, root []byte, content map[string][]byte) {
    62  	// Check root availability and trie contents
    63  	trie, err := New(common.BytesToHash(root), db)
    64  	if err != nil {
    65  		t.Fatalf("failed to create trie at %x: %v", root, err)
    66  	}
    67  	if err := checkTrieConsistency(db, common.BytesToHash(root)); err != nil {
    68  		t.Fatalf("inconsistent trie at %x: %v", root, err)
    69  	}
    70  	for key, val := range content {
    71  		if have := trie.Get([]byte(key)); !bytes.Equal(have, val) {
    72  			t.Errorf("entry %x: content mismatch: have %x, want %x", key, have, val)
    73  		}
    74  	}
    75  }
    76  
    77  // checkTrieConsistency checks that all nodes in a trie are indeed present.
    78  func checkTrieConsistency(db *Database, root common.Hash) error {
    79  	// Create and iterate a trie rooted in a subnode
    80  	trie, err := New(root, db)
    81  	if err != nil {
    82  		return nil // Consider a non existent state consistent
    83  	}
    84  	it := trie.NodeIterator(nil)
    85  	for it.Next(true) {
    86  	}
    87  	return it.Error()
    88  }
    89  
    90  // Tests that an empty trie is not scheduled for syncing.
    91  func TestEmptySync(t *testing.T) {
    92  	dbA := NewDatabase(memorydb.New())
    93  	dbB := NewDatabase(memorydb.New())
    94  	emptyA, _ := New(common.Hash{}, dbA)
    95  	emptyB, _ := New(emptyRoot, dbB)
    96  
    97  	for i, trie := range []*Trie{emptyA, emptyB} {
    98  		if req := NewSync(trie.Hash(), memorydb.New(), nil).Missing(1); len(req) != 0 {
    99  			t.Errorf("test %d: content requested for empty trie: %v", i, req)
   100  		}
   101  	}
   102  }
   103  
   104  // Tests that given a root hash, a trie can sync iteratively on a single thread,
   105  // requesting retrieval tasks and returning all of them in one go.
   106  func TestIterativeSyncIndividual(t *testing.T) { testIterativeSync(t, 1) }
   107  func TestIterativeSyncBatched(t *testing.T)    { testIterativeSync(t, 100) }
   108  
   109  func testIterativeSync(t *testing.T, batch int) {
   110  	// Create a random trie to copy
   111  	srcDb, srcTrie, srcData := makeTestTrie()
   112  
   113  	// Create a destination trie and sync with the scheduler
   114  	diskdb := memorydb.New()
   115  	triedb := NewDatabase(diskdb)
   116  	sched := NewSync(srcTrie.Hash(), diskdb, nil)
   117  
   118  	queue := append([]common.Hash{}, sched.Missing(batch)...)
   119  	for len(queue) > 0 {
   120  		results := make([]SyncResult, len(queue))
   121  		for i, hash := range queue {
   122  			data, err := srcDb.Node(hash)
   123  			if err != nil {
   124  				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
   125  			}
   126  			results[i] = SyncResult{hash, data}
   127  		}
   128  		if _, index, err := sched.Process(results); err != nil {
   129  			t.Fatalf("failed to process result #%d: %v", index, err)
   130  		}
   131  		if index, err := sched.Commit(diskdb); err != nil {
   132  			t.Fatalf("failed to commit data #%d: %v", index, err)
   133  		}
   134  		queue = append(queue[:0], sched.Missing(batch)...)
   135  	}
   136  	// Cross check that the two tries are in sync
   137  	checkTrieContents(t, triedb, srcTrie.Root(), srcData)
   138  }
   139  
   140  // Tests that the trie scheduler can correctly reconstruct the state even if only
   141  // partial results are returned, and the others sent only later.
   142  func TestIterativeDelayedSync(t *testing.T) {
   143  	// Create a random trie to copy
   144  	srcDb, srcTrie, srcData := makeTestTrie()
   145  
   146  	// Create a destination trie and sync with the scheduler
   147  	diskdb := memorydb.New()
   148  	triedb := NewDatabase(diskdb)
   149  	sched := NewSync(srcTrie.Hash(), diskdb, nil)
   150  
   151  	queue := append([]common.Hash{}, sched.Missing(10000)...)
   152  	for len(queue) > 0 {
   153  		// Sync only half of the scheduled nodes
   154  		results := make([]SyncResult, len(queue)/2+1)
   155  		for i, hash := range queue[:len(results)] {
   156  			data, err := srcDb.Node(hash)
   157  			if err != nil {
   158  				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
   159  			}
   160  			results[i] = SyncResult{hash, data}
   161  		}
   162  		if _, index, err := sched.Process(results); err != nil {
   163  			t.Fatalf("failed to process result #%d: %v", index, err)
   164  		}
   165  		if index, err := sched.Commit(diskdb); err != nil {
   166  			t.Fatalf("failed to commit data #%d: %v", index, err)
   167  		}
   168  		queue = append(queue[len(results):], sched.Missing(10000)...)
   169  	}
   170  	// Cross check that the two tries are in sync
   171  	checkTrieContents(t, triedb, srcTrie.Root(), srcData)
   172  }
   173  
   174  // Tests that given a root hash, a trie can sync iteratively on a single thread,
   175  // requesting retrieval tasks and returning all of them in one go, however in a
   176  // random order.
   177  func TestIterativeRandomSyncIndividual(t *testing.T) { testIterativeRandomSync(t, 1) }
   178  func TestIterativeRandomSyncBatched(t *testing.T)    { testIterativeRandomSync(t, 100) }
   179  
   180  func testIterativeRandomSync(t *testing.T, batch int) {
   181  	// Create a random trie to copy
   182  	srcDb, srcTrie, srcData := makeTestTrie()
   183  
   184  	// Create a destination trie and sync with the scheduler
   185  	diskdb := memorydb.New()
   186  	triedb := NewDatabase(diskdb)
   187  	sched := NewSync(srcTrie.Hash(), diskdb, nil)
   188  
   189  	queue := make(map[common.Hash]struct{})
   190  	for _, hash := range sched.Missing(batch) {
   191  		queue[hash] = struct{}{}
   192  	}
   193  	for len(queue) > 0 {
   194  		// Fetch all the queued nodes in a random order
   195  		results := make([]SyncResult, 0, len(queue))
   196  		for hash := range queue {
   197  			data, err := srcDb.Node(hash)
   198  			if err != nil {
   199  				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
   200  			}
   201  			results = append(results, SyncResult{hash, data})
   202  		}
   203  		// Feed the retrieved results back and queue new tasks
   204  		if _, index, err := sched.Process(results); err != nil {
   205  			t.Fatalf("failed to process result #%d: %v", index, err)
   206  		}
   207  		if index, err := sched.Commit(diskdb); err != nil {
   208  			t.Fatalf("failed to commit data #%d: %v", index, err)
   209  		}
   210  		queue = make(map[common.Hash]struct{})
   211  		for _, hash := range sched.Missing(batch) {
   212  			queue[hash] = struct{}{}
   213  		}
   214  	}
   215  	// Cross check that the two tries are in sync
   216  	checkTrieContents(t, triedb, srcTrie.Root(), srcData)
   217  }
   218  
   219  // Tests that the trie scheduler can correctly reconstruct the state even if only
   220  // partial results are returned (Even those randomly), others sent only later.
   221  func TestIterativeRandomDelayedSync(t *testing.T) {
   222  	// Create a random trie to copy
   223  	srcDb, srcTrie, srcData := makeTestTrie()
   224  
   225  	// Create a destination trie and sync with the scheduler
   226  	diskdb := memorydb.New()
   227  	triedb := NewDatabase(diskdb)
   228  	sched := NewSync(srcTrie.Hash(), diskdb, nil)
   229  
   230  	queue := make(map[common.Hash]struct{})
   231  	for _, hash := range sched.Missing(10000) {
   232  		queue[hash] = struct{}{}
   233  	}
   234  	for len(queue) > 0 {
   235  		// Sync only half of the scheduled nodes, even those in random order
   236  		results := make([]SyncResult, 0, len(queue)/2+1)
   237  		for hash := range queue {
   238  			data, err := srcDb.Node(hash)
   239  			if err != nil {
   240  				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
   241  			}
   242  			results = append(results, SyncResult{hash, data})
   243  
   244  			if len(results) >= cap(results) {
   245  				break
   246  			}
   247  		}
   248  		// Feed the retrieved results back and queue new tasks
   249  		if _, index, err := sched.Process(results); err != nil {
   250  			t.Fatalf("failed to process result #%d: %v", index, err)
   251  		}
   252  		if index, err := sched.Commit(diskdb); err != nil {
   253  			t.Fatalf("failed to commit data #%d: %v", index, err)
   254  		}
   255  		for _, result := range results {
   256  			delete(queue, result.Hash)
   257  		}
   258  		for _, hash := range sched.Missing(10000) {
   259  			queue[hash] = struct{}{}
   260  		}
   261  	}
   262  	// Cross check that the two tries are in sync
   263  	checkTrieContents(t, triedb, srcTrie.Root(), srcData)
   264  }
   265  
   266  // Tests that a trie sync will not request nodes multiple times, even if they
   267  // have such references.
   268  func TestDuplicateAvoidanceSync(t *testing.T) {
   269  	// Create a random trie to copy
   270  	srcDb, srcTrie, srcData := makeTestTrie()
   271  
   272  	// Create a destination trie and sync with the scheduler
   273  	diskdb := memorydb.New()
   274  	triedb := NewDatabase(diskdb)
   275  	sched := NewSync(srcTrie.Hash(), diskdb, nil)
   276  
   277  	queue := append([]common.Hash{}, sched.Missing(0)...)
   278  	requested := make(map[common.Hash]struct{})
   279  
   280  	for len(queue) > 0 {
   281  		results := make([]SyncResult, len(queue))
   282  		for i, hash := range queue {
   283  			data, err := srcDb.Node(hash)
   284  			if err != nil {
   285  				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
   286  			}
   287  			if _, ok := requested[hash]; ok {
   288  				t.Errorf("hash %x already requested once", hash)
   289  			}
   290  			requested[hash] = struct{}{}
   291  
   292  			results[i] = SyncResult{hash, data}
   293  		}
   294  		if _, index, err := sched.Process(results); err != nil {
   295  			t.Fatalf("failed to process result #%d: %v", index, err)
   296  		}
   297  		if index, err := sched.Commit(diskdb); err != nil {
   298  			t.Fatalf("failed to commit data #%d: %v", index, err)
   299  		}
   300  		queue = append(queue[:0], sched.Missing(0)...)
   301  	}
   302  	// Cross check that the two tries are in sync
   303  	checkTrieContents(t, triedb, srcTrie.Root(), srcData)
   304  }
   305  
   306  // Tests that at any point in time during a sync, only complete sub-tries are in
   307  // the database.
   308  func TestIncompleteSync(t *testing.T) {
   309  	// Create a random trie to copy
   310  	srcDb, srcTrie, _ := makeTestTrie()
   311  
   312  	// Create a destination trie and sync with the scheduler
   313  	diskdb := memorydb.New()
   314  	triedb := NewDatabase(diskdb)
   315  	sched := NewSync(srcTrie.Hash(), diskdb, nil)
   316  
   317  	var added []common.Hash
   318  	queue := append([]common.Hash{}, sched.Missing(1)...)
   319  	for len(queue) > 0 {
   320  		// Fetch a batch of trie nodes
   321  		results := make([]SyncResult, len(queue))
   322  		for i, hash := range queue {
   323  			data, err := srcDb.Node(hash)
   324  			if err != nil {
   325  				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
   326  			}
   327  			results[i] = SyncResult{hash, data}
   328  		}
   329  		// Process each of the trie nodes
   330  		if _, index, err := sched.Process(results); err != nil {
   331  			t.Fatalf("failed to process result #%d: %v", index, err)
   332  		}
   333  		if index, err := sched.Commit(diskdb); err != nil {
   334  			t.Fatalf("failed to commit data #%d: %v", index, err)
   335  		}
   336  		for _, result := range results {
   337  			added = append(added, result.Hash)
   338  		}
   339  		// Check that all known sub-tries in the synced trie are complete
   340  		for _, root := range added {
   341  			if err := checkTrieConsistency(triedb, root); err != nil {
   342  				t.Fatalf("trie inconsistent: %v", err)
   343  			}
   344  		}
   345  		// Fetch the next batch to retrieve
   346  		queue = append(queue[:0], sched.Missing(1)...)
   347  	}
   348  	// Sanity check that removing any node from the database is detected
   349  	for _, node := range added[1:] {
   350  		key := node.Bytes()
   351  		value, _ := diskdb.Get(key)
   352  
   353  		diskdb.Delete(key)
   354  		if err := checkTrieConsistency(triedb, added[0]); err == nil {
   355  			t.Fatalf("trie inconsistency not caught, missing: %x", key)
   356  		}
   357  		diskdb.Put(key, value)
   358  	}
   359  }