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