github.com/carter-ya/go-ethereum@v0.0.0-20230628080049-d2309be3983b/trie/trie_test.go (about)

     1  // Copyright 2014 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  	"encoding/binary"
    22  	"errors"
    23  	"fmt"
    24  	"hash"
    25  	"math/big"
    26  	"math/rand"
    27  	"reflect"
    28  	"testing"
    29  	"testing/quick"
    30  
    31  	"github.com/davecgh/go-spew/spew"
    32  	"github.com/ethereum/go-ethereum/common"
    33  	"github.com/ethereum/go-ethereum/core/rawdb"
    34  	"github.com/ethereum/go-ethereum/core/types"
    35  	"github.com/ethereum/go-ethereum/crypto"
    36  	"github.com/ethereum/go-ethereum/ethdb"
    37  	"github.com/ethereum/go-ethereum/ethdb/memorydb"
    38  	"github.com/ethereum/go-ethereum/rlp"
    39  	"golang.org/x/crypto/sha3"
    40  )
    41  
    42  func init() {
    43  	spew.Config.Indent = "    "
    44  	spew.Config.DisableMethods = false
    45  }
    46  
    47  func TestEmptyTrie(t *testing.T) {
    48  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
    49  	res := trie.Hash()
    50  	exp := emptyRoot
    51  	if res != exp {
    52  		t.Errorf("expected %x got %x", exp, res)
    53  	}
    54  }
    55  
    56  func TestNull(t *testing.T) {
    57  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
    58  	key := make([]byte, 32)
    59  	value := []byte("test")
    60  	trie.Update(key, value)
    61  	if !bytes.Equal(trie.Get(key), value) {
    62  		t.Fatal("wrong value")
    63  	}
    64  }
    65  
    66  func TestMissingRoot(t *testing.T) {
    67  	root := common.HexToHash("0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33")
    68  	trie, err := New(TrieID(root), NewDatabase(memorydb.New()))
    69  	if trie != nil {
    70  		t.Error("New returned non-nil trie for invalid root")
    71  	}
    72  	if _, ok := err.(*MissingNodeError); !ok {
    73  		t.Errorf("New returned wrong error: %v", err)
    74  	}
    75  }
    76  
    77  func TestMissingNodeDisk(t *testing.T)    { testMissingNode(t, false) }
    78  func TestMissingNodeMemonly(t *testing.T) { testMissingNode(t, true) }
    79  
    80  func testMissingNode(t *testing.T, memonly bool) {
    81  	diskdb := memorydb.New()
    82  	triedb := NewDatabase(diskdb)
    83  
    84  	trie := NewEmpty(triedb)
    85  	updateString(trie, "120000", "qwerqwerqwerqwerqwerqwerqwerqwer")
    86  	updateString(trie, "123456", "asdfasdfasdfasdfasdfasdfasdfasdf")
    87  	root, nodes, _ := trie.Commit(false)
    88  	triedb.Update(NewWithNodeSet(nodes))
    89  	if !memonly {
    90  		triedb.Commit(root, true, nil)
    91  	}
    92  
    93  	trie, _ = New(TrieID(root), triedb)
    94  	_, err := trie.TryGet([]byte("120000"))
    95  	if err != nil {
    96  		t.Errorf("Unexpected error: %v", err)
    97  	}
    98  	trie, _ = New(TrieID(root), triedb)
    99  	_, err = trie.TryGet([]byte("120099"))
   100  	if err != nil {
   101  		t.Errorf("Unexpected error: %v", err)
   102  	}
   103  	trie, _ = New(TrieID(root), triedb)
   104  	_, err = trie.TryGet([]byte("123456"))
   105  	if err != nil {
   106  		t.Errorf("Unexpected error: %v", err)
   107  	}
   108  	trie, _ = New(TrieID(root), triedb)
   109  	err = trie.TryUpdate([]byte("120099"), []byte("zxcvzxcvzxcvzxcvzxcvzxcvzxcvzxcv"))
   110  	if err != nil {
   111  		t.Errorf("Unexpected error: %v", err)
   112  	}
   113  	trie, _ = New(TrieID(root), triedb)
   114  	err = trie.TryDelete([]byte("123456"))
   115  	if err != nil {
   116  		t.Errorf("Unexpected error: %v", err)
   117  	}
   118  
   119  	hash := common.HexToHash("0xe1d943cc8f061a0c0b98162830b970395ac9315654824bf21b73b891365262f9")
   120  	if memonly {
   121  		delete(triedb.dirties, hash)
   122  	} else {
   123  		diskdb.Delete(hash[:])
   124  	}
   125  
   126  	trie, _ = New(TrieID(root), triedb)
   127  	_, err = trie.TryGet([]byte("120000"))
   128  	if _, ok := err.(*MissingNodeError); !ok {
   129  		t.Errorf("Wrong error: %v", err)
   130  	}
   131  	trie, _ = New(TrieID(root), triedb)
   132  	_, err = trie.TryGet([]byte("120099"))
   133  	if _, ok := err.(*MissingNodeError); !ok {
   134  		t.Errorf("Wrong error: %v", err)
   135  	}
   136  	trie, _ = New(TrieID(root), triedb)
   137  	_, err = trie.TryGet([]byte("123456"))
   138  	if err != nil {
   139  		t.Errorf("Unexpected error: %v", err)
   140  	}
   141  	trie, _ = New(TrieID(root), triedb)
   142  	err = trie.TryUpdate([]byte("120099"), []byte("zxcv"))
   143  	if _, ok := err.(*MissingNodeError); !ok {
   144  		t.Errorf("Wrong error: %v", err)
   145  	}
   146  	trie, _ = New(TrieID(root), triedb)
   147  	err = trie.TryDelete([]byte("123456"))
   148  	if _, ok := err.(*MissingNodeError); !ok {
   149  		t.Errorf("Wrong error: %v", err)
   150  	}
   151  }
   152  
   153  func TestInsert(t *testing.T) {
   154  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   155  
   156  	updateString(trie, "doe", "reindeer")
   157  	updateString(trie, "dog", "puppy")
   158  	updateString(trie, "dogglesworth", "cat")
   159  
   160  	exp := common.HexToHash("8aad789dff2f538bca5d8ea56e8abe10f4c7ba3a5dea95fea4cd6e7c3a1168d3")
   161  	root := trie.Hash()
   162  	if root != exp {
   163  		t.Errorf("case 1: exp %x got %x", exp, root)
   164  	}
   165  
   166  	trie = NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   167  	updateString(trie, "A", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
   168  
   169  	exp = common.HexToHash("d23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab")
   170  	root, _, err := trie.Commit(false)
   171  	if err != nil {
   172  		t.Fatalf("commit error: %v", err)
   173  	}
   174  	if root != exp {
   175  		t.Errorf("case 2: exp %x got %x", exp, root)
   176  	}
   177  }
   178  
   179  func TestGet(t *testing.T) {
   180  	db := NewDatabase(rawdb.NewMemoryDatabase())
   181  	trie := NewEmpty(db)
   182  	updateString(trie, "doe", "reindeer")
   183  	updateString(trie, "dog", "puppy")
   184  	updateString(trie, "dogglesworth", "cat")
   185  
   186  	for i := 0; i < 2; i++ {
   187  		res := getString(trie, "dog")
   188  		if !bytes.Equal(res, []byte("puppy")) {
   189  			t.Errorf("expected puppy got %x", res)
   190  		}
   191  		unknown := getString(trie, "unknown")
   192  		if unknown != nil {
   193  			t.Errorf("expected nil got %x", unknown)
   194  		}
   195  		if i == 1 {
   196  			return
   197  		}
   198  		root, nodes, _ := trie.Commit(false)
   199  		db.Update(NewWithNodeSet(nodes))
   200  		trie, _ = New(TrieID(root), db)
   201  	}
   202  }
   203  
   204  func TestDelete(t *testing.T) {
   205  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   206  	vals := []struct{ k, v string }{
   207  		{"do", "verb"},
   208  		{"ether", "wookiedoo"},
   209  		{"horse", "stallion"},
   210  		{"shaman", "horse"},
   211  		{"doge", "coin"},
   212  		{"ether", ""},
   213  		{"dog", "puppy"},
   214  		{"shaman", ""},
   215  	}
   216  	for _, val := range vals {
   217  		if val.v != "" {
   218  			updateString(trie, val.k, val.v)
   219  		} else {
   220  			deleteString(trie, val.k)
   221  		}
   222  	}
   223  
   224  	hash := trie.Hash()
   225  	exp := common.HexToHash("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84")
   226  	if hash != exp {
   227  		t.Errorf("expected %x got %x", exp, hash)
   228  	}
   229  }
   230  
   231  func TestEmptyValues(t *testing.T) {
   232  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   233  
   234  	vals := []struct{ k, v string }{
   235  		{"do", "verb"},
   236  		{"ether", "wookiedoo"},
   237  		{"horse", "stallion"},
   238  		{"shaman", "horse"},
   239  		{"doge", "coin"},
   240  		{"ether", ""},
   241  		{"dog", "puppy"},
   242  		{"shaman", ""},
   243  	}
   244  	for _, val := range vals {
   245  		updateString(trie, val.k, val.v)
   246  	}
   247  
   248  	hash := trie.Hash()
   249  	exp := common.HexToHash("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84")
   250  	if hash != exp {
   251  		t.Errorf("expected %x got %x", exp, hash)
   252  	}
   253  }
   254  
   255  func TestReplication(t *testing.T) {
   256  	triedb := NewDatabase(rawdb.NewMemoryDatabase())
   257  	trie := NewEmpty(triedb)
   258  	vals := []struct{ k, v string }{
   259  		{"do", "verb"},
   260  		{"ether", "wookiedoo"},
   261  		{"horse", "stallion"},
   262  		{"shaman", "horse"},
   263  		{"doge", "coin"},
   264  		{"dog", "puppy"},
   265  		{"somethingveryoddindeedthis is", "myothernodedata"},
   266  	}
   267  	for _, val := range vals {
   268  		updateString(trie, val.k, val.v)
   269  	}
   270  	exp, nodes, err := trie.Commit(false)
   271  	if err != nil {
   272  		t.Fatalf("commit error: %v", err)
   273  	}
   274  	triedb.Update(NewWithNodeSet(nodes))
   275  
   276  	// create a new trie on top of the database and check that lookups work.
   277  	trie2, err := New(TrieID(exp), triedb)
   278  	if err != nil {
   279  		t.Fatalf("can't recreate trie at %x: %v", exp, err)
   280  	}
   281  	for _, kv := range vals {
   282  		if string(getString(trie2, kv.k)) != kv.v {
   283  			t.Errorf("trie2 doesn't have %q => %q", kv.k, kv.v)
   284  		}
   285  	}
   286  	hash, nodes, err := trie2.Commit(false)
   287  	if err != nil {
   288  		t.Fatalf("commit error: %v", err)
   289  	}
   290  	if hash != exp {
   291  		t.Errorf("root failure. expected %x got %x", exp, hash)
   292  	}
   293  
   294  	// recreate the trie after commit
   295  	if nodes != nil {
   296  		triedb.Update(NewWithNodeSet(nodes))
   297  	}
   298  	trie2, err = New(TrieID(hash), triedb)
   299  	if err != nil {
   300  		t.Fatalf("can't recreate trie at %x: %v", exp, err)
   301  	}
   302  	// perform some insertions on the new trie.
   303  	vals2 := []struct{ k, v string }{
   304  		{"do", "verb"},
   305  		{"ether", "wookiedoo"},
   306  		{"horse", "stallion"},
   307  		// {"shaman", "horse"},
   308  		// {"doge", "coin"},
   309  		// {"ether", ""},
   310  		// {"dog", "puppy"},
   311  		// {"somethingveryoddindeedthis is", "myothernodedata"},
   312  		// {"shaman", ""},
   313  	}
   314  	for _, val := range vals2 {
   315  		updateString(trie2, val.k, val.v)
   316  	}
   317  	if hash := trie2.Hash(); hash != exp {
   318  		t.Errorf("root failure. expected %x got %x", exp, hash)
   319  	}
   320  }
   321  
   322  func TestLargeValue(t *testing.T) {
   323  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   324  	trie.Update([]byte("key1"), []byte{99, 99, 99, 99})
   325  	trie.Update([]byte("key2"), bytes.Repeat([]byte{1}, 32))
   326  	trie.Hash()
   327  }
   328  
   329  // TestRandomCases tests som cases that were found via random fuzzing
   330  func TestRandomCases(t *testing.T) {
   331  	var rt = []randTestStep{
   332  		{op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 0
   333  		{op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 1
   334  		{op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000002")},           // step 2
   335  		{op: 2, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("")},                         // step 3
   336  		{op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 4
   337  		{op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 5
   338  		{op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 6
   339  		{op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 7
   340  		{op: 0, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("0000000000000008")},         // step 8
   341  		{op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000009")},           // step 9
   342  		{op: 2, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("")},                                                                                               // step 10
   343  		{op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 11
   344  		{op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 12
   345  		{op: 0, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("000000000000000d")},                                                                               // step 13
   346  		{op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 14
   347  		{op: 1, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("")},                         // step 15
   348  		{op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 16
   349  		{op: 0, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("0000000000000011")},         // step 17
   350  		{op: 5, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 18
   351  		{op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 19
   352  		{op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000014")},           // step 20
   353  		{op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000015")},           // step 21
   354  		{op: 0, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("0000000000000016")},         // step 22
   355  		{op: 5, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 23
   356  		{op: 1, key: common.Hex2Bytes("980c393656413a15c8da01978ed9f89feb80b502f58f2d640e3a2f5f7a99a7018f1b573befd92053ac6f78fca4a87268"), value: common.Hex2Bytes("")}, // step 24
   357  		{op: 1, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("")},                                                                                               // step 25
   358  	}
   359  	runRandTest(rt)
   360  }
   361  
   362  // randTest performs random trie operations.
   363  // Instances of this test are created by Generate.
   364  type randTest []randTestStep
   365  
   366  type randTestStep struct {
   367  	op    int
   368  	key   []byte // for opUpdate, opDelete, opGet
   369  	value []byte // for opUpdate
   370  	err   error  // for debugging
   371  }
   372  
   373  const (
   374  	opUpdate = iota
   375  	opDelete
   376  	opGet
   377  	opHash
   378  	opCommit
   379  	opItercheckhash
   380  	opNodeDiff
   381  	opProve
   382  	opMax // boundary value, not an actual op
   383  )
   384  
   385  func (randTest) Generate(r *rand.Rand, size int) reflect.Value {
   386  	var allKeys [][]byte
   387  	genKey := func() []byte {
   388  		if len(allKeys) < 2 || r.Intn(100) < 10 {
   389  			// new key
   390  			key := make([]byte, r.Intn(50))
   391  			r.Read(key)
   392  			allKeys = append(allKeys, key)
   393  			return key
   394  		}
   395  		// use existing key
   396  		return allKeys[r.Intn(len(allKeys))]
   397  	}
   398  
   399  	var steps randTest
   400  	for i := 0; i < size; i++ {
   401  		step := randTestStep{op: r.Intn(opMax)}
   402  		switch step.op {
   403  		case opUpdate:
   404  			step.key = genKey()
   405  			step.value = make([]byte, 8)
   406  			binary.BigEndian.PutUint64(step.value, uint64(i))
   407  		case opGet, opDelete, opProve:
   408  			step.key = genKey()
   409  		}
   410  		steps = append(steps, step)
   411  	}
   412  	return reflect.ValueOf(steps)
   413  }
   414  
   415  func runRandTest(rt randTest) bool {
   416  	var (
   417  		triedb   = NewDatabase(memorydb.New())
   418  		tr       = NewEmpty(triedb)
   419  		values   = make(map[string]string) // tracks content of the trie
   420  		origTrie = NewEmpty(triedb)
   421  	)
   422  	tr.tracer = newTracer()
   423  
   424  	for i, step := range rt {
   425  		// fmt.Printf("{op: %d, key: common.Hex2Bytes(\"%x\"), value: common.Hex2Bytes(\"%x\")}, // step %d\n",
   426  		// 	step.op, step.key, step.value, i)
   427  
   428  		switch step.op {
   429  		case opUpdate:
   430  			tr.Update(step.key, step.value)
   431  			values[string(step.key)] = string(step.value)
   432  		case opDelete:
   433  			tr.Delete(step.key)
   434  			delete(values, string(step.key))
   435  		case opGet:
   436  			v := tr.Get(step.key)
   437  			want := values[string(step.key)]
   438  			if string(v) != want {
   439  				rt[i].err = fmt.Errorf("mismatch for key %#x, got %#x want %#x", step.key, v, want)
   440  			}
   441  		case opProve:
   442  			hash := tr.Hash()
   443  			if hash == emptyRoot {
   444  				continue
   445  			}
   446  			proofDb := rawdb.NewMemoryDatabase()
   447  			err := tr.Prove(step.key, 0, proofDb)
   448  			if err != nil {
   449  				rt[i].err = fmt.Errorf("failed for proving key %#x, %v", step.key, err)
   450  			}
   451  			_, err = VerifyProof(hash, step.key, proofDb)
   452  			if err != nil {
   453  				rt[i].err = fmt.Errorf("failed for verifying key %#x, %v", step.key, err)
   454  			}
   455  		case opHash:
   456  			tr.Hash()
   457  		case opCommit:
   458  			root, nodes, err := tr.Commit(true)
   459  			if err != nil {
   460  				rt[i].err = err
   461  				return false
   462  			}
   463  			// Validity the returned nodeset
   464  			if nodes != nil {
   465  				for path, node := range nodes.updates.nodes {
   466  					blob, _, _ := origTrie.TryGetNode(hexToCompact([]byte(path)))
   467  					got := node.prev
   468  					if !bytes.Equal(blob, got) {
   469  						rt[i].err = fmt.Errorf("prevalue mismatch for 0x%x, got 0x%x want 0x%x", path, got, blob)
   470  						panic(rt[i].err)
   471  					}
   472  				}
   473  				for path, prev := range nodes.deletes {
   474  					blob, _, _ := origTrie.TryGetNode(hexToCompact([]byte(path)))
   475  					if !bytes.Equal(blob, prev) {
   476  						rt[i].err = fmt.Errorf("prevalue mismatch for 0x%x, got 0x%x want 0x%x", path, prev, blob)
   477  						return false
   478  					}
   479  				}
   480  			}
   481  			if nodes != nil {
   482  				triedb.Update(NewWithNodeSet(nodes))
   483  			}
   484  			newtr, err := New(TrieID(root), triedb)
   485  			if err != nil {
   486  				rt[i].err = err
   487  				return false
   488  			}
   489  			tr = newtr
   490  
   491  			// Enable node tracing. Resolve the root node again explicitly
   492  			// since it's not captured at the beginning.
   493  			tr.tracer = newTracer()
   494  			tr.resolveAndTrack(root.Bytes(), nil)
   495  
   496  			origTrie = tr.Copy()
   497  		case opItercheckhash:
   498  			checktr := NewEmpty(triedb)
   499  			it := NewIterator(tr.NodeIterator(nil))
   500  			for it.Next() {
   501  				checktr.Update(it.Key, it.Value)
   502  			}
   503  			if tr.Hash() != checktr.Hash() {
   504  				rt[i].err = fmt.Errorf("hash mismatch in opItercheckhash")
   505  			}
   506  		case opNodeDiff:
   507  			var (
   508  				inserted = tr.tracer.insertList()
   509  				deleted  = tr.tracer.deleteList()
   510  				origIter = origTrie.NodeIterator(nil)
   511  				curIter  = tr.NodeIterator(nil)
   512  				origSeen = make(map[string]struct{})
   513  				curSeen  = make(map[string]struct{})
   514  			)
   515  			for origIter.Next(true) {
   516  				if origIter.Leaf() {
   517  					continue
   518  				}
   519  				origSeen[string(origIter.Path())] = struct{}{}
   520  			}
   521  			for curIter.Next(true) {
   522  				if curIter.Leaf() {
   523  					continue
   524  				}
   525  				curSeen[string(curIter.Path())] = struct{}{}
   526  			}
   527  			var (
   528  				insertExp = make(map[string]struct{})
   529  				deleteExp = make(map[string]struct{})
   530  			)
   531  			for path := range curSeen {
   532  				_, present := origSeen[path]
   533  				if !present {
   534  					insertExp[path] = struct{}{}
   535  				}
   536  			}
   537  			for path := range origSeen {
   538  				_, present := curSeen[path]
   539  				if !present {
   540  					deleteExp[path] = struct{}{}
   541  				}
   542  			}
   543  			if len(insertExp) != len(inserted) {
   544  				rt[i].err = fmt.Errorf("insert set mismatch")
   545  			}
   546  			if len(deleteExp) != len(deleted) {
   547  				rt[i].err = fmt.Errorf("delete set mismatch")
   548  			}
   549  			for _, insert := range inserted {
   550  				if _, present := insertExp[string(insert)]; !present {
   551  					rt[i].err = fmt.Errorf("missing inserted node")
   552  				}
   553  			}
   554  			for _, del := range deleted {
   555  				if _, present := deleteExp[string(del)]; !present {
   556  					rt[i].err = fmt.Errorf("missing deleted node")
   557  				}
   558  			}
   559  		}
   560  		// Abort the test on error.
   561  		if rt[i].err != nil {
   562  			return false
   563  		}
   564  	}
   565  	return true
   566  }
   567  
   568  func TestRandom(t *testing.T) {
   569  	if err := quick.Check(runRandTest, nil); err != nil {
   570  		if cerr, ok := err.(*quick.CheckError); ok {
   571  			t.Fatalf("random test iteration %d failed: %s", cerr.Count, spew.Sdump(cerr.In))
   572  		}
   573  		t.Fatal(err)
   574  	}
   575  }
   576  
   577  func BenchmarkGet(b *testing.B)      { benchGet(b) }
   578  func BenchmarkUpdateBE(b *testing.B) { benchUpdate(b, binary.BigEndian) }
   579  func BenchmarkUpdateLE(b *testing.B) { benchUpdate(b, binary.LittleEndian) }
   580  
   581  const benchElemCount = 20000
   582  
   583  func benchGet(b *testing.B) {
   584  	triedb := NewDatabase(rawdb.NewMemoryDatabase())
   585  	trie := NewEmpty(triedb)
   586  	k := make([]byte, 32)
   587  	for i := 0; i < benchElemCount; i++ {
   588  		binary.LittleEndian.PutUint64(k, uint64(i))
   589  		trie.Update(k, k)
   590  	}
   591  	binary.LittleEndian.PutUint64(k, benchElemCount/2)
   592  
   593  	b.ResetTimer()
   594  	for i := 0; i < b.N; i++ {
   595  		trie.Get(k)
   596  	}
   597  	b.StopTimer()
   598  }
   599  
   600  func benchUpdate(b *testing.B, e binary.ByteOrder) *Trie {
   601  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   602  	k := make([]byte, 32)
   603  	b.ReportAllocs()
   604  	for i := 0; i < b.N; i++ {
   605  		e.PutUint64(k, uint64(i))
   606  		trie.Update(k, k)
   607  	}
   608  	return trie
   609  }
   610  
   611  // Benchmarks the trie hashing. Since the trie caches the result of any operation,
   612  // we cannot use b.N as the number of hashing rouns, since all rounds apart from
   613  // the first one will be NOOP. As such, we'll use b.N as the number of account to
   614  // insert into the trie before measuring the hashing.
   615  // BenchmarkHash-6   	  288680	      4561 ns/op	     682 B/op	       9 allocs/op
   616  // BenchmarkHash-6   	  275095	      4800 ns/op	     685 B/op	       9 allocs/op
   617  // pure hasher:
   618  // BenchmarkHash-6   	  319362	      4230 ns/op	     675 B/op	       9 allocs/op
   619  // BenchmarkHash-6   	  257460	      4674 ns/op	     689 B/op	       9 allocs/op
   620  // With hashing in-between and pure hasher:
   621  // BenchmarkHash-6   	  225417	      7150 ns/op	     982 B/op	      12 allocs/op
   622  // BenchmarkHash-6   	  220378	      6197 ns/op	     983 B/op	      12 allocs/op
   623  // same with old hasher
   624  // BenchmarkHash-6   	  229758	      6437 ns/op	     981 B/op	      12 allocs/op
   625  // BenchmarkHash-6   	  212610	      7137 ns/op	     986 B/op	      12 allocs/op
   626  func BenchmarkHash(b *testing.B) {
   627  	// Create a realistic account trie to hash. We're first adding and hashing N
   628  	// entries, then adding N more.
   629  	addresses, accounts := makeAccounts(2 * b.N)
   630  	// Insert the accounts into the trie and hash it
   631  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   632  	i := 0
   633  	for ; i < len(addresses)/2; i++ {
   634  		trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
   635  	}
   636  	trie.Hash()
   637  	for ; i < len(addresses); i++ {
   638  		trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
   639  	}
   640  	b.ResetTimer()
   641  	b.ReportAllocs()
   642  	//trie.hashRoot(nil, nil)
   643  	trie.Hash()
   644  }
   645  
   646  // Benchmarks the trie Commit following a Hash. Since the trie caches the result of any operation,
   647  // we cannot use b.N as the number of hashing rouns, since all rounds apart from
   648  // the first one will be NOOP. As such, we'll use b.N as the number of account to
   649  // insert into the trie before measuring the hashing.
   650  func BenchmarkCommitAfterHash(b *testing.B) {
   651  	b.Run("no-onleaf", func(b *testing.B) {
   652  		benchmarkCommitAfterHash(b, false)
   653  	})
   654  	b.Run("with-onleaf", func(b *testing.B) {
   655  		benchmarkCommitAfterHash(b, true)
   656  	})
   657  }
   658  
   659  func benchmarkCommitAfterHash(b *testing.B, collectLeaf bool) {
   660  	// Make the random benchmark deterministic
   661  	addresses, accounts := makeAccounts(b.N)
   662  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   663  	for i := 0; i < len(addresses); i++ {
   664  		trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
   665  	}
   666  	// Insert the accounts into the trie and hash it
   667  	trie.Hash()
   668  	b.ResetTimer()
   669  	b.ReportAllocs()
   670  	trie.Commit(collectLeaf)
   671  }
   672  
   673  func TestTinyTrie(t *testing.T) {
   674  	// Create a realistic account trie to hash
   675  	_, accounts := makeAccounts(5)
   676  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   677  	trie.Update(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001337"), accounts[3])
   678  	if exp, root := common.HexToHash("8c6a85a4d9fda98feff88450299e574e5378e32391f75a055d470ac0653f1005"), trie.Hash(); exp != root {
   679  		t.Errorf("1: got %x, exp %x", root, exp)
   680  	}
   681  	trie.Update(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001338"), accounts[4])
   682  	if exp, root := common.HexToHash("ec63b967e98a5720e7f720482151963982890d82c9093c0d486b7eb8883a66b1"), trie.Hash(); exp != root {
   683  		t.Errorf("2: got %x, exp %x", root, exp)
   684  	}
   685  	trie.Update(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001339"), accounts[4])
   686  	if exp, root := common.HexToHash("0608c1d1dc3905fa22204c7a0e43644831c3b6d3def0f274be623a948197e64a"), trie.Hash(); exp != root {
   687  		t.Errorf("3: got %x, exp %x", root, exp)
   688  	}
   689  	checktr := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   690  	it := NewIterator(trie.NodeIterator(nil))
   691  	for it.Next() {
   692  		checktr.Update(it.Key, it.Value)
   693  	}
   694  	if troot, itroot := trie.Hash(), checktr.Hash(); troot != itroot {
   695  		t.Fatalf("hash mismatch in opItercheckhash, trie: %x, check: %x", troot, itroot)
   696  	}
   697  }
   698  
   699  func TestCommitAfterHash(t *testing.T) {
   700  	// Create a realistic account trie to hash
   701  	addresses, accounts := makeAccounts(1000)
   702  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   703  	for i := 0; i < len(addresses); i++ {
   704  		trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
   705  	}
   706  	// Insert the accounts into the trie and hash it
   707  	trie.Hash()
   708  	trie.Commit(false)
   709  	root := trie.Hash()
   710  	exp := common.HexToHash("72f9d3f3fe1e1dd7b8936442e7642aef76371472d94319900790053c493f3fe6")
   711  	if exp != root {
   712  		t.Errorf("got %x, exp %x", root, exp)
   713  	}
   714  	root, _, _ = trie.Commit(false)
   715  	if exp != root {
   716  		t.Errorf("got %x, exp %x", root, exp)
   717  	}
   718  }
   719  
   720  func makeAccounts(size int) (addresses [][20]byte, accounts [][]byte) {
   721  	// Make the random benchmark deterministic
   722  	random := rand.New(rand.NewSource(0))
   723  	// Create a realistic account trie to hash
   724  	addresses = make([][20]byte, size)
   725  	for i := 0; i < len(addresses); i++ {
   726  		data := make([]byte, 20)
   727  		random.Read(data)
   728  		copy(addresses[i][:], data)
   729  	}
   730  	accounts = make([][]byte, len(addresses))
   731  	for i := 0; i < len(accounts); i++ {
   732  		var (
   733  			nonce = uint64(random.Int63())
   734  			root  = emptyRoot
   735  			code  = crypto.Keccak256(nil)
   736  		)
   737  		// The big.Rand function is not deterministic with regards to 64 vs 32 bit systems,
   738  		// and will consume different amount of data from the rand source.
   739  		//balance = new(big.Int).Rand(random, new(big.Int).Exp(common.Big2, common.Big256, nil))
   740  		// Therefore, we instead just read via byte buffer
   741  		numBytes := random.Uint32() % 33 // [0, 32] bytes
   742  		balanceBytes := make([]byte, numBytes)
   743  		random.Read(balanceBytes)
   744  		balance := new(big.Int).SetBytes(balanceBytes)
   745  		data, _ := rlp.EncodeToBytes(&types.StateAccount{Nonce: nonce, Balance: balance, Root: root, CodeHash: code})
   746  		accounts[i] = data
   747  	}
   748  	return addresses, accounts
   749  }
   750  
   751  // spongeDb is a dummy db backend which accumulates writes in a sponge
   752  type spongeDb struct {
   753  	sponge  hash.Hash
   754  	id      string
   755  	journal []string
   756  }
   757  
   758  func (s *spongeDb) Has(key []byte) (bool, error)             { panic("implement me") }
   759  func (s *spongeDb) Get(key []byte) ([]byte, error)           { return nil, errors.New("no such elem") }
   760  func (s *spongeDb) Delete(key []byte) error                  { panic("implement me") }
   761  func (s *spongeDb) NewBatch() ethdb.Batch                    { return &spongeBatch{s} }
   762  func (s *spongeDb) NewBatchWithSize(size int) ethdb.Batch    { return &spongeBatch{s} }
   763  func (s *spongeDb) NewSnapshot() (ethdb.Snapshot, error)     { panic("implement me") }
   764  func (s *spongeDb) Stat(property string) (string, error)     { panic("implement me") }
   765  func (s *spongeDb) Compact(start []byte, limit []byte) error { panic("implement me") }
   766  func (s *spongeDb) Close() error                             { return nil }
   767  func (s *spongeDb) Put(key []byte, value []byte) error {
   768  	valbrief := value
   769  	if len(valbrief) > 8 {
   770  		valbrief = valbrief[:8]
   771  	}
   772  	s.journal = append(s.journal, fmt.Sprintf("%v: PUT([%x...], [%d bytes] %x...)\n", s.id, key[:8], len(value), valbrief))
   773  	s.sponge.Write(key)
   774  	s.sponge.Write(value)
   775  	return nil
   776  }
   777  func (s *spongeDb) NewIterator(prefix []byte, start []byte) ethdb.Iterator { panic("implement me") }
   778  
   779  // spongeBatch is a dummy batch which immediately writes to the underlying spongedb
   780  type spongeBatch struct {
   781  	db *spongeDb
   782  }
   783  
   784  func (b *spongeBatch) Put(key, value []byte) error {
   785  	b.db.Put(key, value)
   786  	return nil
   787  }
   788  func (b *spongeBatch) Delete(key []byte) error             { panic("implement me") }
   789  func (b *spongeBatch) ValueSize() int                      { return 100 }
   790  func (b *spongeBatch) Write() error                        { return nil }
   791  func (b *spongeBatch) Reset()                              {}
   792  func (b *spongeBatch) Replay(w ethdb.KeyValueWriter) error { return nil }
   793  
   794  // TestCommitSequence tests that the trie.Commit operation writes the elements of the trie
   795  // in the expected order, and calls the callbacks in the expected order.
   796  // The test data was based on the 'master' code, and is basically random. It can be used
   797  // to check whether changes to the trie modifies the write order or data in any way.
   798  func TestCommitSequence(t *testing.T) {
   799  	for i, tc := range []struct {
   800  		count              int
   801  		expWriteSeqHash    []byte
   802  		expCallbackSeqHash []byte
   803  	}{
   804  		{20, common.FromHex("873c78df73d60e59d4a2bcf3716e8bfe14554549fea2fc147cb54129382a8066"),
   805  			common.FromHex("ff00f91ac05df53b82d7f178d77ada54fd0dca64526f537034a5dbe41b17df2a")},
   806  		{200, common.FromHex("ba03d891bb15408c940eea5ee3d54d419595102648d02774a0268d892add9c8e"),
   807  			common.FromHex("f3cd509064c8d319bbdd1c68f511850a902ad275e6ed5bea11547e23d492a926")},
   808  		{2000, common.FromHex("f7a184f20df01c94f09537401d11e68d97ad0c00115233107f51b9c287ce60c7"),
   809  			common.FromHex("ff795ea898ba1e4cfed4a33b4cf5535a347a02cf931f88d88719faf810f9a1c9")},
   810  	} {
   811  		addresses, accounts := makeAccounts(tc.count)
   812  		// This spongeDb is used to check the sequence of disk-db-writes
   813  		s := &spongeDb{sponge: sha3.NewLegacyKeccak256()}
   814  		db := NewDatabase(s)
   815  		trie := NewEmpty(db)
   816  		// Another sponge is used to check the callback-sequence
   817  		callbackSponge := sha3.NewLegacyKeccak256()
   818  		// Fill the trie with elements
   819  		for i := 0; i < tc.count; i++ {
   820  			trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
   821  		}
   822  		// Flush trie -> database
   823  		root, nodes, _ := trie.Commit(false)
   824  		db.Update(NewWithNodeSet(nodes))
   825  		// Flush memdb -> disk (sponge)
   826  		db.Commit(root, false, func(c common.Hash) {
   827  			// And spongify the callback-order
   828  			callbackSponge.Write(c[:])
   829  		})
   830  		if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) {
   831  			t.Errorf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp)
   832  		}
   833  		if got, exp := callbackSponge.Sum(nil), tc.expCallbackSeqHash; !bytes.Equal(got, exp) {
   834  			t.Errorf("test %d, call back sequence wrong:\ngot: %x exp %x\n", i, got, exp)
   835  		}
   836  	}
   837  }
   838  
   839  // TestCommitSequenceRandomBlobs is identical to TestCommitSequence
   840  // but uses random blobs instead of 'accounts'
   841  func TestCommitSequenceRandomBlobs(t *testing.T) {
   842  	for i, tc := range []struct {
   843  		count              int
   844  		expWriteSeqHash    []byte
   845  		expCallbackSeqHash []byte
   846  	}{
   847  		{20, common.FromHex("8e4a01548551d139fa9e833ebc4e66fc1ba40a4b9b7259d80db32cff7b64ebbc"),
   848  			common.FromHex("450238d73bc36dc6cc6f926987e5428535e64be403877c4560e238a52749ba24")},
   849  		{200, common.FromHex("6869b4e7b95f3097a19ddb30ff735f922b915314047e041614df06958fc50554"),
   850  			common.FromHex("0ace0b03d6cb8c0b82f6289ef5b1a1838306b455a62dafc63cada8e2924f2550")},
   851  		{2000, common.FromHex("444200e6f4e2df49f77752f629a96ccf7445d4698c164f962bbd85a0526ef424"),
   852  			common.FromHex("117d30dafaa62a1eed498c3dfd70982b377ba2b46dd3e725ed6120c80829e518")},
   853  	} {
   854  		prng := rand.New(rand.NewSource(int64(i)))
   855  		// This spongeDb is used to check the sequence of disk-db-writes
   856  		s := &spongeDb{sponge: sha3.NewLegacyKeccak256()}
   857  		db := NewDatabase(s)
   858  		trie := NewEmpty(db)
   859  		// Another sponge is used to check the callback-sequence
   860  		callbackSponge := sha3.NewLegacyKeccak256()
   861  		// Fill the trie with elements
   862  		for i := 0; i < tc.count; i++ {
   863  			key := make([]byte, 32)
   864  			var val []byte
   865  			// 50% short elements, 50% large elements
   866  			if prng.Intn(2) == 0 {
   867  				val = make([]byte, 1+prng.Intn(32))
   868  			} else {
   869  				val = make([]byte, 1+prng.Intn(4096))
   870  			}
   871  			prng.Read(key)
   872  			prng.Read(val)
   873  			trie.Update(key, val)
   874  		}
   875  		// Flush trie -> database
   876  		root, nodes, _ := trie.Commit(false)
   877  		db.Update(NewWithNodeSet(nodes))
   878  		// Flush memdb -> disk (sponge)
   879  		db.Commit(root, false, func(c common.Hash) {
   880  			// And spongify the callback-order
   881  			callbackSponge.Write(c[:])
   882  		})
   883  		if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) {
   884  			t.Fatalf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp)
   885  		}
   886  		if got, exp := callbackSponge.Sum(nil), tc.expCallbackSeqHash; !bytes.Equal(got, exp) {
   887  			t.Fatalf("test %d, call back sequence wrong:\ngot: %x exp %x\n", i, got, exp)
   888  		}
   889  	}
   890  }
   891  
   892  func TestCommitSequenceStackTrie(t *testing.T) {
   893  	for count := 1; count < 200; count++ {
   894  		prng := rand.New(rand.NewSource(int64(count)))
   895  		// This spongeDb is used to check the sequence of disk-db-writes
   896  		s := &spongeDb{sponge: sha3.NewLegacyKeccak256(), id: "a"}
   897  		db := NewDatabase(s)
   898  		trie := NewEmpty(db)
   899  		// Another sponge is used for the stacktrie commits
   900  		stackTrieSponge := &spongeDb{sponge: sha3.NewLegacyKeccak256(), id: "b"}
   901  		stTrie := NewStackTrie(stackTrieSponge)
   902  		// Fill the trie with elements
   903  		for i := 0; i < count; i++ {
   904  			// For the stack trie, we need to do inserts in proper order
   905  			key := make([]byte, 32)
   906  			binary.BigEndian.PutUint64(key, uint64(i))
   907  			var val []byte
   908  			// 50% short elements, 50% large elements
   909  			if prng.Intn(2) == 0 {
   910  				val = make([]byte, 1+prng.Intn(32))
   911  			} else {
   912  				val = make([]byte, 1+prng.Intn(1024))
   913  			}
   914  			prng.Read(val)
   915  			trie.TryUpdate(key, val)
   916  			stTrie.TryUpdate(key, val)
   917  		}
   918  		// Flush trie -> database
   919  		root, nodes, _ := trie.Commit(false)
   920  		// Flush memdb -> disk (sponge)
   921  		db.Update(NewWithNodeSet(nodes))
   922  		db.Commit(root, false, nil)
   923  		// And flush stacktrie -> disk
   924  		stRoot, err := stTrie.Commit()
   925  		if err != nil {
   926  			t.Fatalf("Failed to commit stack trie %v", err)
   927  		}
   928  		if stRoot != root {
   929  			t.Fatalf("root wrong, got %x exp %x", stRoot, root)
   930  		}
   931  		if got, exp := stackTrieSponge.sponge.Sum(nil), s.sponge.Sum(nil); !bytes.Equal(got, exp) {
   932  			// Show the journal
   933  			t.Logf("Expected:")
   934  			for i, v := range s.journal {
   935  				t.Logf("op %d: %v", i, v)
   936  			}
   937  			t.Logf("Stacktrie:")
   938  			for i, v := range stackTrieSponge.journal {
   939  				t.Logf("op %d: %v", i, v)
   940  			}
   941  			t.Fatalf("test %d, disk write sequence wrong:\ngot %x exp %x\n", count, got, exp)
   942  		}
   943  	}
   944  }
   945  
   946  // TestCommitSequenceSmallRoot tests that a trie which is essentially only a
   947  // small (<32 byte) shortnode with an included value is properly committed to a
   948  // database.
   949  // This case might not matter, since in practice, all keys are 32 bytes, which means
   950  // that even a small trie which contains a leaf will have an extension making it
   951  // not fit into 32 bytes, rlp-encoded. However, it's still the correct thing to do.
   952  func TestCommitSequenceSmallRoot(t *testing.T) {
   953  	s := &spongeDb{sponge: sha3.NewLegacyKeccak256(), id: "a"}
   954  	db := NewDatabase(s)
   955  	trie := NewEmpty(db)
   956  	// Another sponge is used for the stacktrie commits
   957  	stackTrieSponge := &spongeDb{sponge: sha3.NewLegacyKeccak256(), id: "b"}
   958  	stTrie := NewStackTrie(stackTrieSponge)
   959  	// Add a single small-element to the trie(s)
   960  	key := make([]byte, 5)
   961  	key[0] = 1
   962  	trie.TryUpdate(key, []byte{0x1})
   963  	stTrie.TryUpdate(key, []byte{0x1})
   964  	// Flush trie -> database
   965  	root, nodes, _ := trie.Commit(false)
   966  	// Flush memdb -> disk (sponge)
   967  	db.Update(NewWithNodeSet(nodes))
   968  	db.Commit(root, false, nil)
   969  	// And flush stacktrie -> disk
   970  	stRoot, err := stTrie.Commit()
   971  	if err != nil {
   972  		t.Fatalf("Failed to commit stack trie %v", err)
   973  	}
   974  	if stRoot != root {
   975  		t.Fatalf("root wrong, got %x exp %x", stRoot, root)
   976  	}
   977  
   978  	t.Logf("root: %x\n", stRoot)
   979  	if got, exp := stackTrieSponge.sponge.Sum(nil), s.sponge.Sum(nil); !bytes.Equal(got, exp) {
   980  		t.Fatalf("test, disk write sequence wrong:\ngot %x exp %x\n", got, exp)
   981  	}
   982  }
   983  
   984  // BenchmarkCommitAfterHashFixedSize benchmarks the Commit (after Hash) of a fixed number of updates to a trie.
   985  // This benchmark is meant to capture the difference on efficiency of small versus large changes. Typically,
   986  // storage tries are small (a couple of entries), whereas the full post-block account trie update is large (a couple
   987  // of thousand entries)
   988  func BenchmarkHashFixedSize(b *testing.B) {
   989  	b.Run("10", func(b *testing.B) {
   990  		b.StopTimer()
   991  		acc, add := makeAccounts(20)
   992  		for i := 0; i < b.N; i++ {
   993  			benchmarkHashFixedSize(b, acc, add)
   994  		}
   995  	})
   996  	b.Run("100", func(b *testing.B) {
   997  		b.StopTimer()
   998  		acc, add := makeAccounts(100)
   999  		for i := 0; i < b.N; i++ {
  1000  			benchmarkHashFixedSize(b, acc, add)
  1001  		}
  1002  	})
  1003  
  1004  	b.Run("1K", func(b *testing.B) {
  1005  		b.StopTimer()
  1006  		acc, add := makeAccounts(1000)
  1007  		for i := 0; i < b.N; i++ {
  1008  			benchmarkHashFixedSize(b, acc, add)
  1009  		}
  1010  	})
  1011  	b.Run("10K", func(b *testing.B) {
  1012  		b.StopTimer()
  1013  		acc, add := makeAccounts(10000)
  1014  		for i := 0; i < b.N; i++ {
  1015  			benchmarkHashFixedSize(b, acc, add)
  1016  		}
  1017  	})
  1018  	b.Run("100K", func(b *testing.B) {
  1019  		b.StopTimer()
  1020  		acc, add := makeAccounts(100000)
  1021  		for i := 0; i < b.N; i++ {
  1022  			benchmarkHashFixedSize(b, acc, add)
  1023  		}
  1024  	})
  1025  }
  1026  
  1027  func benchmarkHashFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  1028  	b.ReportAllocs()
  1029  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
  1030  	for i := 0; i < len(addresses); i++ {
  1031  		trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  1032  	}
  1033  	// Insert the accounts into the trie and hash it
  1034  	b.StartTimer()
  1035  	trie.Hash()
  1036  	b.StopTimer()
  1037  }
  1038  
  1039  func BenchmarkCommitAfterHashFixedSize(b *testing.B) {
  1040  	b.Run("10", func(b *testing.B) {
  1041  		b.StopTimer()
  1042  		acc, add := makeAccounts(20)
  1043  		for i := 0; i < b.N; i++ {
  1044  			benchmarkCommitAfterHashFixedSize(b, acc, add)
  1045  		}
  1046  	})
  1047  	b.Run("100", func(b *testing.B) {
  1048  		b.StopTimer()
  1049  		acc, add := makeAccounts(100)
  1050  		for i := 0; i < b.N; i++ {
  1051  			benchmarkCommitAfterHashFixedSize(b, acc, add)
  1052  		}
  1053  	})
  1054  
  1055  	b.Run("1K", func(b *testing.B) {
  1056  		b.StopTimer()
  1057  		acc, add := makeAccounts(1000)
  1058  		for i := 0; i < b.N; i++ {
  1059  			benchmarkCommitAfterHashFixedSize(b, acc, add)
  1060  		}
  1061  	})
  1062  	b.Run("10K", func(b *testing.B) {
  1063  		b.StopTimer()
  1064  		acc, add := makeAccounts(10000)
  1065  		for i := 0; i < b.N; i++ {
  1066  			benchmarkCommitAfterHashFixedSize(b, acc, add)
  1067  		}
  1068  	})
  1069  	b.Run("100K", func(b *testing.B) {
  1070  		b.StopTimer()
  1071  		acc, add := makeAccounts(100000)
  1072  		for i := 0; i < b.N; i++ {
  1073  			benchmarkCommitAfterHashFixedSize(b, acc, add)
  1074  		}
  1075  	})
  1076  }
  1077  
  1078  func benchmarkCommitAfterHashFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  1079  	b.ReportAllocs()
  1080  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
  1081  	for i := 0; i < len(addresses); i++ {
  1082  		trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  1083  	}
  1084  	// Insert the accounts into the trie and hash it
  1085  	trie.Hash()
  1086  	b.StartTimer()
  1087  	trie.Commit(false)
  1088  	b.StopTimer()
  1089  }
  1090  
  1091  func BenchmarkDerefRootFixedSize(b *testing.B) {
  1092  	b.Run("10", func(b *testing.B) {
  1093  		b.StopTimer()
  1094  		acc, add := makeAccounts(20)
  1095  		for i := 0; i < b.N; i++ {
  1096  			benchmarkDerefRootFixedSize(b, acc, add)
  1097  		}
  1098  	})
  1099  	b.Run("100", func(b *testing.B) {
  1100  		b.StopTimer()
  1101  		acc, add := makeAccounts(100)
  1102  		for i := 0; i < b.N; i++ {
  1103  			benchmarkDerefRootFixedSize(b, acc, add)
  1104  		}
  1105  	})
  1106  
  1107  	b.Run("1K", func(b *testing.B) {
  1108  		b.StopTimer()
  1109  		acc, add := makeAccounts(1000)
  1110  		for i := 0; i < b.N; i++ {
  1111  			benchmarkDerefRootFixedSize(b, acc, add)
  1112  		}
  1113  	})
  1114  	b.Run("10K", func(b *testing.B) {
  1115  		b.StopTimer()
  1116  		acc, add := makeAccounts(10000)
  1117  		for i := 0; i < b.N; i++ {
  1118  			benchmarkDerefRootFixedSize(b, acc, add)
  1119  		}
  1120  	})
  1121  	b.Run("100K", func(b *testing.B) {
  1122  		b.StopTimer()
  1123  		acc, add := makeAccounts(100000)
  1124  		for i := 0; i < b.N; i++ {
  1125  			benchmarkDerefRootFixedSize(b, acc, add)
  1126  		}
  1127  	})
  1128  }
  1129  
  1130  func benchmarkDerefRootFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  1131  	b.ReportAllocs()
  1132  	triedb := NewDatabase(rawdb.NewMemoryDatabase())
  1133  	trie := NewEmpty(triedb)
  1134  	for i := 0; i < len(addresses); i++ {
  1135  		trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  1136  	}
  1137  	h := trie.Hash()
  1138  	_, nodes, _ := trie.Commit(false)
  1139  	triedb.Update(NewWithNodeSet(nodes))
  1140  	b.StartTimer()
  1141  	triedb.Dereference(h)
  1142  	b.StopTimer()
  1143  }
  1144  
  1145  func getString(trie *Trie, k string) []byte {
  1146  	return trie.Get([]byte(k))
  1147  }
  1148  
  1149  func updateString(trie *Trie, k, v string) {
  1150  	trie.Update([]byte(k), []byte(v))
  1151  }
  1152  
  1153  func deleteString(trie *Trie, k string) {
  1154  	trie.Delete([]byte(k))
  1155  }
  1156  
  1157  func TestDecodeNode(t *testing.T) {
  1158  	t.Parallel()
  1159  	var (
  1160  		hash  = make([]byte, 20)
  1161  		elems = make([]byte, 20)
  1162  	)
  1163  	for i := 0; i < 5000000; i++ {
  1164  		rand.Read(hash)
  1165  		rand.Read(elems)
  1166  		decodeNode(hash, elems)
  1167  	}
  1168  }