github.com/calmw/ethereum@v0.1.1/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/calmw/ethereum/common"
    32  	"github.com/calmw/ethereum/core/rawdb"
    33  	"github.com/calmw/ethereum/core/types"
    34  	"github.com/calmw/ethereum/crypto"
    35  	"github.com/calmw/ethereum/ethdb"
    36  	"github.com/calmw/ethereum/rlp"
    37  	"github.com/calmw/ethereum/trie/trienode"
    38  	"github.com/davecgh/go-spew/spew"
    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 := types.EmptyRootHash
    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.MustUpdate(key, value)
    61  	if !bytes.Equal(trie.MustGet(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(rawdb.NewMemoryDatabase()))
    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 TestMissingNode(t *testing.T) {
    78  	testMissingNode(t, false, rawdb.HashScheme)
    79  	//testMissingNode(t, false, rawdb.PathScheme)
    80  	testMissingNode(t, true, rawdb.HashScheme)
    81  	//testMissingNode(t, true, rawdb.PathScheme)
    82  }
    83  
    84  func testMissingNode(t *testing.T, memonly bool, scheme string) {
    85  	diskdb := rawdb.NewMemoryDatabase()
    86  	triedb := newTestDatabase(diskdb, scheme)
    87  
    88  	trie := NewEmpty(triedb)
    89  	updateString(trie, "120000", "qwerqwerqwerqwerqwerqwerqwerqwer")
    90  	updateString(trie, "123456", "asdfasdfasdfasdfasdfasdfasdfasdf")
    91  	root, nodes := trie.Commit(false)
    92  	triedb.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
    93  
    94  	if !memonly {
    95  		triedb.Commit(root, false)
    96  	}
    97  
    98  	trie, _ = New(TrieID(root), triedb)
    99  	_, err := trie.Get([]byte("120000"))
   100  	if err != nil {
   101  		t.Errorf("Unexpected error: %v", err)
   102  	}
   103  	trie, _ = New(TrieID(root), triedb)
   104  	_, err = trie.Get([]byte("120099"))
   105  	if err != nil {
   106  		t.Errorf("Unexpected error: %v", err)
   107  	}
   108  	trie, _ = New(TrieID(root), triedb)
   109  	_, err = trie.Get([]byte("123456"))
   110  	if err != nil {
   111  		t.Errorf("Unexpected error: %v", err)
   112  	}
   113  	trie, _ = New(TrieID(root), triedb)
   114  	err = trie.Update([]byte("120099"), []byte("zxcvzxcvzxcvzxcvzxcvzxcvzxcvzxcv"))
   115  	if err != nil {
   116  		t.Errorf("Unexpected error: %v", err)
   117  	}
   118  	trie, _ = New(TrieID(root), triedb)
   119  	err = trie.Delete([]byte("123456"))
   120  	if err != nil {
   121  		t.Errorf("Unexpected error: %v", err)
   122  	}
   123  
   124  	var (
   125  		path []byte
   126  		hash = common.HexToHash("0xe1d943cc8f061a0c0b98162830b970395ac9315654824bf21b73b891365262f9")
   127  	)
   128  	for p, n := range nodes.Nodes {
   129  		if n.Hash == hash {
   130  			path = common.CopyBytes([]byte(p))
   131  			break
   132  		}
   133  	}
   134  	trie, _ = New(TrieID(root), triedb)
   135  	if memonly {
   136  		trie.reader.banned = map[string]struct{}{string(path): {}}
   137  	} else {
   138  		rawdb.DeleteTrieNode(diskdb, common.Hash{}, path, hash, scheme)
   139  	}
   140  
   141  	_, err = trie.Get([]byte("120000"))
   142  	if _, ok := err.(*MissingNodeError); !ok {
   143  		t.Errorf("Wrong error: %v", err)
   144  	}
   145  	_, err = trie.Get([]byte("120099"))
   146  	if _, ok := err.(*MissingNodeError); !ok {
   147  		t.Errorf("Wrong error: %v", err)
   148  	}
   149  	_, err = trie.Get([]byte("123456"))
   150  	if err != nil {
   151  		t.Errorf("Unexpected error: %v", err)
   152  	}
   153  	err = trie.Update([]byte("120099"), []byte("zxcv"))
   154  	if _, ok := err.(*MissingNodeError); !ok {
   155  		t.Errorf("Wrong error: %v", err)
   156  	}
   157  	err = trie.Delete([]byte("123456"))
   158  	if _, ok := err.(*MissingNodeError); !ok {
   159  		t.Errorf("Wrong error: %v", err)
   160  	}
   161  }
   162  
   163  func TestInsert(t *testing.T) {
   164  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   165  
   166  	updateString(trie, "doe", "reindeer")
   167  	updateString(trie, "dog", "puppy")
   168  	updateString(trie, "dogglesworth", "cat")
   169  
   170  	exp := common.HexToHash("8aad789dff2f538bca5d8ea56e8abe10f4c7ba3a5dea95fea4cd6e7c3a1168d3")
   171  	root := trie.Hash()
   172  	if root != exp {
   173  		t.Errorf("case 1: exp %x got %x", exp, root)
   174  	}
   175  
   176  	trie = NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   177  	updateString(trie, "A", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
   178  
   179  	exp = common.HexToHash("d23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab")
   180  	root, _ = trie.Commit(false)
   181  	if root != exp {
   182  		t.Errorf("case 2: exp %x got %x", exp, root)
   183  	}
   184  }
   185  
   186  func TestGet(t *testing.T) {
   187  	db := NewDatabase(rawdb.NewMemoryDatabase())
   188  	trie := NewEmpty(db)
   189  	updateString(trie, "doe", "reindeer")
   190  	updateString(trie, "dog", "puppy")
   191  	updateString(trie, "dogglesworth", "cat")
   192  
   193  	for i := 0; i < 2; i++ {
   194  		res := getString(trie, "dog")
   195  		if !bytes.Equal(res, []byte("puppy")) {
   196  			t.Errorf("expected puppy got %x", res)
   197  		}
   198  		unknown := getString(trie, "unknown")
   199  		if unknown != nil {
   200  			t.Errorf("expected nil got %x", unknown)
   201  		}
   202  		if i == 1 {
   203  			return
   204  		}
   205  		root, nodes := trie.Commit(false)
   206  		db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
   207  		trie, _ = New(TrieID(root), db)
   208  	}
   209  }
   210  
   211  func TestDelete(t *testing.T) {
   212  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   213  	vals := []struct{ k, v string }{
   214  		{"do", "verb"},
   215  		{"ether", "wookiedoo"},
   216  		{"horse", "stallion"},
   217  		{"shaman", "horse"},
   218  		{"doge", "coin"},
   219  		{"ether", ""},
   220  		{"dog", "puppy"},
   221  		{"shaman", ""},
   222  	}
   223  	for _, val := range vals {
   224  		if val.v != "" {
   225  			updateString(trie, val.k, val.v)
   226  		} else {
   227  			deleteString(trie, val.k)
   228  		}
   229  	}
   230  
   231  	hash := trie.Hash()
   232  	exp := common.HexToHash("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84")
   233  	if hash != exp {
   234  		t.Errorf("expected %x got %x", exp, hash)
   235  	}
   236  }
   237  
   238  func TestEmptyValues(t *testing.T) {
   239  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   240  
   241  	vals := []struct{ k, v string }{
   242  		{"do", "verb"},
   243  		{"ether", "wookiedoo"},
   244  		{"horse", "stallion"},
   245  		{"shaman", "horse"},
   246  		{"doge", "coin"},
   247  		{"ether", ""},
   248  		{"dog", "puppy"},
   249  		{"shaman", ""},
   250  	}
   251  	for _, val := range vals {
   252  		updateString(trie, val.k, val.v)
   253  	}
   254  
   255  	hash := trie.Hash()
   256  	exp := common.HexToHash("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84")
   257  	if hash != exp {
   258  		t.Errorf("expected %x got %x", exp, hash)
   259  	}
   260  }
   261  
   262  func TestReplication(t *testing.T) {
   263  	db := NewDatabase(rawdb.NewMemoryDatabase())
   264  	trie := NewEmpty(db)
   265  	vals := []struct{ k, v string }{
   266  		{"do", "verb"},
   267  		{"ether", "wookiedoo"},
   268  		{"horse", "stallion"},
   269  		{"shaman", "horse"},
   270  		{"doge", "coin"},
   271  		{"dog", "puppy"},
   272  		{"somethingveryoddindeedthis is", "myothernodedata"},
   273  	}
   274  	for _, val := range vals {
   275  		updateString(trie, val.k, val.v)
   276  	}
   277  	root, nodes := trie.Commit(false)
   278  	db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
   279  
   280  	// create a new trie on top of the database and check that lookups work.
   281  	trie2, err := New(TrieID(root), db)
   282  	if err != nil {
   283  		t.Fatalf("can't recreate trie at %x: %v", root, err)
   284  	}
   285  	for _, kv := range vals {
   286  		if string(getString(trie2, kv.k)) != kv.v {
   287  			t.Errorf("trie2 doesn't have %q => %q", kv.k, kv.v)
   288  		}
   289  	}
   290  	hash, nodes := trie2.Commit(false)
   291  	if hash != root {
   292  		t.Errorf("root failure. expected %x got %x", root, hash)
   293  	}
   294  
   295  	// recreate the trie after commit
   296  	if nodes != nil {
   297  		db.Update(hash, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
   298  	}
   299  	trie2, err = New(TrieID(hash), db)
   300  	if err != nil {
   301  		t.Fatalf("can't recreate trie at %x: %v", hash, err)
   302  	}
   303  	// perform some insertions on the new trie.
   304  	vals2 := []struct{ k, v string }{
   305  		{"do", "verb"},
   306  		{"ether", "wookiedoo"},
   307  		{"horse", "stallion"},
   308  		// {"shaman", "horse"},
   309  		// {"doge", "coin"},
   310  		// {"ether", ""},
   311  		// {"dog", "puppy"},
   312  		// {"somethingveryoddindeedthis is", "myothernodedata"},
   313  		// {"shaman", ""},
   314  	}
   315  	for _, val := range vals2 {
   316  		updateString(trie2, val.k, val.v)
   317  	}
   318  	if trie2.Hash() != hash {
   319  		t.Errorf("root failure. expected %x got %x", hash, hash)
   320  	}
   321  }
   322  
   323  func TestLargeValue(t *testing.T) {
   324  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   325  	trie.MustUpdate([]byte("key1"), []byte{99, 99, 99, 99})
   326  	trie.MustUpdate([]byte("key2"), bytes.Repeat([]byte{1}, 32))
   327  	trie.Hash()
   328  }
   329  
   330  // TestRandomCases tests som cases that were found via random fuzzing
   331  func TestRandomCases(t *testing.T) {
   332  	var rt = []randTestStep{
   333  		{op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 0
   334  		{op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 1
   335  		{op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000002")},           // step 2
   336  		{op: 2, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("")},                         // step 3
   337  		{op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 4
   338  		{op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 5
   339  		{op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 6
   340  		{op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 7
   341  		{op: 0, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("0000000000000008")},         // step 8
   342  		{op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000009")},           // step 9
   343  		{op: 2, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("")},                                                                                               // step 10
   344  		{op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 11
   345  		{op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 12
   346  		{op: 0, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("000000000000000d")},                                                                               // step 13
   347  		{op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 14
   348  		{op: 1, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("")},                         // step 15
   349  		{op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 16
   350  		{op: 0, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("0000000000000011")},         // step 17
   351  		{op: 5, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 18
   352  		{op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 19
   353  		{op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000014")},           // step 20
   354  		{op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000015")},           // step 21
   355  		{op: 0, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("0000000000000016")},         // step 22
   356  		{op: 5, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 23
   357  		{op: 1, key: common.Hex2Bytes("980c393656413a15c8da01978ed9f89feb80b502f58f2d640e3a2f5f7a99a7018f1b573befd92053ac6f78fca4a87268"), value: common.Hex2Bytes("")}, // step 24
   358  		{op: 1, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("")},                                                                                               // step 25
   359  	}
   360  	runRandTest(rt)
   361  }
   362  
   363  // randTest performs random trie operations.
   364  // Instances of this test are created by Generate.
   365  type randTest []randTestStep
   366  
   367  type randTestStep struct {
   368  	op    int
   369  	key   []byte // for opUpdate, opDelete, opGet
   370  	value []byte // for opUpdate
   371  	err   error  // for debugging
   372  }
   373  
   374  const (
   375  	opUpdate = iota
   376  	opDelete
   377  	opGet
   378  	opHash
   379  	opCommit
   380  	opItercheckhash
   381  	opNodeDiff
   382  	opProve
   383  	opMax // boundary value, not an actual op
   384  )
   385  
   386  func (randTest) Generate(r *rand.Rand, size int) reflect.Value {
   387  	var allKeys [][]byte
   388  	genKey := func() []byte {
   389  		if len(allKeys) < 2 || r.Intn(100) < 10 {
   390  			// new key
   391  			key := make([]byte, r.Intn(50))
   392  			r.Read(key)
   393  			allKeys = append(allKeys, key)
   394  			return key
   395  		}
   396  		// use existing key
   397  		return allKeys[r.Intn(len(allKeys))]
   398  	}
   399  
   400  	var steps randTest
   401  	for i := 0; i < size; i++ {
   402  		step := randTestStep{op: r.Intn(opMax)}
   403  		switch step.op {
   404  		case opUpdate:
   405  			step.key = genKey()
   406  			step.value = make([]byte, 8)
   407  			binary.BigEndian.PutUint64(step.value, uint64(i))
   408  		case opGet, opDelete, opProve:
   409  			step.key = genKey()
   410  		}
   411  		steps = append(steps, step)
   412  	}
   413  	return reflect.ValueOf(steps)
   414  }
   415  
   416  func verifyAccessList(old *Trie, new *Trie, set *trienode.NodeSet) error {
   417  	deletes, inserts, updates := diffTries(old, new)
   418  
   419  	// Check insertion set
   420  	for path := range inserts {
   421  		n, ok := set.Nodes[path]
   422  		if !ok || n.IsDeleted() {
   423  			return errors.New("expect new node")
   424  		}
   425  		if len(n.Prev) > 0 {
   426  			return errors.New("unexpected origin value")
   427  		}
   428  	}
   429  	// Check deletion set
   430  	for path, blob := range deletes {
   431  		n, ok := set.Nodes[path]
   432  		if !ok || !n.IsDeleted() {
   433  			return errors.New("expect deleted node")
   434  		}
   435  		if len(n.Prev) == 0 {
   436  			return errors.New("expect origin value")
   437  		}
   438  		if !bytes.Equal(n.Prev, blob) {
   439  			return errors.New("invalid origin value")
   440  		}
   441  	}
   442  	// Check update set
   443  	for path, blob := range updates {
   444  		n, ok := set.Nodes[path]
   445  		if !ok || n.IsDeleted() {
   446  			return errors.New("expect updated node")
   447  		}
   448  		if len(n.Prev) == 0 {
   449  			return errors.New("expect origin value")
   450  		}
   451  		if !bytes.Equal(n.Prev, blob) {
   452  			return errors.New("invalid origin value")
   453  		}
   454  	}
   455  	return nil
   456  }
   457  
   458  func runRandTest(rt randTest) bool {
   459  	var scheme = rawdb.HashScheme
   460  	//if rand.Intn(2) == 0 {
   461  	//	scheme = rawdb.PathScheme
   462  	//}
   463  	var (
   464  		origin   = types.EmptyRootHash
   465  		triedb   = newTestDatabase(rawdb.NewMemoryDatabase(), scheme)
   466  		tr       = NewEmpty(triedb)
   467  		values   = make(map[string]string) // tracks content of the trie
   468  		origTrie = NewEmpty(triedb)
   469  	)
   470  	for i, step := range rt {
   471  		// fmt.Printf("{op: %d, key: common.Hex2Bytes(\"%x\"), value: common.Hex2Bytes(\"%x\")}, // step %d\n",
   472  		// 	step.op, step.key, step.value, i)
   473  
   474  		switch step.op {
   475  		case opUpdate:
   476  			tr.MustUpdate(step.key, step.value)
   477  			values[string(step.key)] = string(step.value)
   478  		case opDelete:
   479  			tr.MustDelete(step.key)
   480  			delete(values, string(step.key))
   481  		case opGet:
   482  			v := tr.MustGet(step.key)
   483  			want := values[string(step.key)]
   484  			if string(v) != want {
   485  				rt[i].err = fmt.Errorf("mismatch for key %#x, got %#x want %#x", step.key, v, want)
   486  			}
   487  		case opProve:
   488  			hash := tr.Hash()
   489  			if hash == types.EmptyRootHash {
   490  				continue
   491  			}
   492  			proofDb := rawdb.NewMemoryDatabase()
   493  			err := tr.Prove(step.key, 0, proofDb)
   494  			if err != nil {
   495  				rt[i].err = fmt.Errorf("failed for proving key %#x, %v", step.key, err)
   496  			}
   497  			_, err = VerifyProof(hash, step.key, proofDb)
   498  			if err != nil {
   499  				rt[i].err = fmt.Errorf("failed for verifying key %#x, %v", step.key, err)
   500  			}
   501  		case opHash:
   502  			tr.Hash()
   503  		case opCommit:
   504  			root, nodes := tr.Commit(true)
   505  			if nodes != nil {
   506  				triedb.Update(root, origin, trienode.NewWithNodeSet(nodes))
   507  			}
   508  			newtr, err := New(TrieID(root), triedb)
   509  			if err != nil {
   510  				rt[i].err = err
   511  				return false
   512  			}
   513  			if nodes != nil {
   514  				if err := verifyAccessList(origTrie, newtr, nodes); err != nil {
   515  					rt[i].err = err
   516  					return false
   517  				}
   518  			}
   519  			tr = newtr
   520  			origTrie = tr.Copy()
   521  			origin = root
   522  		case opItercheckhash:
   523  			checktr := NewEmpty(triedb)
   524  			it := NewIterator(tr.NodeIterator(nil))
   525  			for it.Next() {
   526  				checktr.MustUpdate(it.Key, it.Value)
   527  			}
   528  			if tr.Hash() != checktr.Hash() {
   529  				rt[i].err = fmt.Errorf("hash mismatch in opItercheckhash")
   530  			}
   531  		case opNodeDiff:
   532  			var (
   533  				origIter = origTrie.NodeIterator(nil)
   534  				curIter  = tr.NodeIterator(nil)
   535  				origSeen = make(map[string]struct{})
   536  				curSeen  = make(map[string]struct{})
   537  			)
   538  			for origIter.Next(true) {
   539  				if origIter.Leaf() {
   540  					continue
   541  				}
   542  				origSeen[string(origIter.Path())] = struct{}{}
   543  			}
   544  			for curIter.Next(true) {
   545  				if curIter.Leaf() {
   546  					continue
   547  				}
   548  				curSeen[string(curIter.Path())] = struct{}{}
   549  			}
   550  			var (
   551  				insertExp = make(map[string]struct{})
   552  				deleteExp = make(map[string]struct{})
   553  			)
   554  			for path := range curSeen {
   555  				_, present := origSeen[path]
   556  				if !present {
   557  					insertExp[path] = struct{}{}
   558  				}
   559  			}
   560  			for path := range origSeen {
   561  				_, present := curSeen[path]
   562  				if !present {
   563  					deleteExp[path] = struct{}{}
   564  				}
   565  			}
   566  			if len(insertExp) != len(tr.tracer.inserts) {
   567  				rt[i].err = fmt.Errorf("insert set mismatch")
   568  			}
   569  			if len(deleteExp) != len(tr.tracer.deletes) {
   570  				rt[i].err = fmt.Errorf("delete set mismatch")
   571  			}
   572  			for insert := range tr.tracer.inserts {
   573  				if _, present := insertExp[insert]; !present {
   574  					rt[i].err = fmt.Errorf("missing inserted node")
   575  				}
   576  			}
   577  			for del := range tr.tracer.deletes {
   578  				if _, present := deleteExp[del]; !present {
   579  					rt[i].err = fmt.Errorf("missing deleted node")
   580  				}
   581  			}
   582  		}
   583  		// Abort the test on error.
   584  		if rt[i].err != nil {
   585  			return false
   586  		}
   587  	}
   588  	return true
   589  }
   590  
   591  func TestRandom(t *testing.T) {
   592  	if err := quick.Check(runRandTest, nil); err != nil {
   593  		if cerr, ok := err.(*quick.CheckError); ok {
   594  			t.Fatalf("random test iteration %d failed: %s", cerr.Count, spew.Sdump(cerr.In))
   595  		}
   596  		t.Fatal(err)
   597  	}
   598  }
   599  
   600  func BenchmarkGet(b *testing.B)      { benchGet(b) }
   601  func BenchmarkUpdateBE(b *testing.B) { benchUpdate(b, binary.BigEndian) }
   602  func BenchmarkUpdateLE(b *testing.B) { benchUpdate(b, binary.LittleEndian) }
   603  
   604  const benchElemCount = 20000
   605  
   606  func benchGet(b *testing.B) {
   607  	triedb := NewDatabase(rawdb.NewMemoryDatabase())
   608  	trie := NewEmpty(triedb)
   609  	k := make([]byte, 32)
   610  	for i := 0; i < benchElemCount; i++ {
   611  		binary.LittleEndian.PutUint64(k, uint64(i))
   612  		trie.MustUpdate(k, k)
   613  	}
   614  	binary.LittleEndian.PutUint64(k, benchElemCount/2)
   615  
   616  	b.ResetTimer()
   617  	for i := 0; i < b.N; i++ {
   618  		trie.MustGet(k)
   619  	}
   620  	b.StopTimer()
   621  }
   622  
   623  func benchUpdate(b *testing.B, e binary.ByteOrder) *Trie {
   624  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   625  	k := make([]byte, 32)
   626  	b.ReportAllocs()
   627  	for i := 0; i < b.N; i++ {
   628  		e.PutUint64(k, uint64(i))
   629  		trie.MustUpdate(k, k)
   630  	}
   631  	return trie
   632  }
   633  
   634  // Benchmarks the trie hashing. Since the trie caches the result of any operation,
   635  // we cannot use b.N as the number of hashing rounds, since all rounds apart from
   636  // the first one will be NOOP. As such, we'll use b.N as the number of account to
   637  // insert into the trie before measuring the hashing.
   638  // BenchmarkHash-6   	  288680	      4561 ns/op	     682 B/op	       9 allocs/op
   639  // BenchmarkHash-6   	  275095	      4800 ns/op	     685 B/op	       9 allocs/op
   640  // pure hasher:
   641  // BenchmarkHash-6   	  319362	      4230 ns/op	     675 B/op	       9 allocs/op
   642  // BenchmarkHash-6   	  257460	      4674 ns/op	     689 B/op	       9 allocs/op
   643  // With hashing in-between and pure hasher:
   644  // BenchmarkHash-6   	  225417	      7150 ns/op	     982 B/op	      12 allocs/op
   645  // BenchmarkHash-6   	  220378	      6197 ns/op	     983 B/op	      12 allocs/op
   646  // same with old hasher
   647  // BenchmarkHash-6   	  229758	      6437 ns/op	     981 B/op	      12 allocs/op
   648  // BenchmarkHash-6   	  212610	      7137 ns/op	     986 B/op	      12 allocs/op
   649  func BenchmarkHash(b *testing.B) {
   650  	// Create a realistic account trie to hash. We're first adding and hashing N
   651  	// entries, then adding N more.
   652  	addresses, accounts := makeAccounts(2 * b.N)
   653  	// Insert the accounts into the trie and hash it
   654  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   655  	i := 0
   656  	for ; i < len(addresses)/2; i++ {
   657  		trie.MustUpdate(crypto.Keccak256(addresses[i][:]), accounts[i])
   658  	}
   659  	trie.Hash()
   660  	for ; i < len(addresses); i++ {
   661  		trie.MustUpdate(crypto.Keccak256(addresses[i][:]), accounts[i])
   662  	}
   663  	b.ResetTimer()
   664  	b.ReportAllocs()
   665  	//trie.hashRoot(nil, nil)
   666  	trie.Hash()
   667  }
   668  
   669  // Benchmarks the trie Commit following a Hash. Since the trie caches the result of any operation,
   670  // we cannot use b.N as the number of hashing rounds, since all rounds apart from
   671  // the first one will be NOOP. As such, we'll use b.N as the number of account to
   672  // insert into the trie before measuring the hashing.
   673  func BenchmarkCommitAfterHash(b *testing.B) {
   674  	b.Run("no-onleaf", func(b *testing.B) {
   675  		benchmarkCommitAfterHash(b, false)
   676  	})
   677  	b.Run("with-onleaf", func(b *testing.B) {
   678  		benchmarkCommitAfterHash(b, true)
   679  	})
   680  }
   681  
   682  func benchmarkCommitAfterHash(b *testing.B, collectLeaf bool) {
   683  	// Make the random benchmark deterministic
   684  	addresses, accounts := makeAccounts(b.N)
   685  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   686  	for i := 0; i < len(addresses); i++ {
   687  		trie.MustUpdate(crypto.Keccak256(addresses[i][:]), accounts[i])
   688  	}
   689  	// Insert the accounts into the trie and hash it
   690  	trie.Hash()
   691  	b.ResetTimer()
   692  	b.ReportAllocs()
   693  	trie.Commit(collectLeaf)
   694  }
   695  
   696  func TestTinyTrie(t *testing.T) {
   697  	// Create a realistic account trie to hash
   698  	_, accounts := makeAccounts(5)
   699  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   700  	trie.MustUpdate(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001337"), accounts[3])
   701  	if exp, root := common.HexToHash("8c6a85a4d9fda98feff88450299e574e5378e32391f75a055d470ac0653f1005"), trie.Hash(); exp != root {
   702  		t.Errorf("1: got %x, exp %x", root, exp)
   703  	}
   704  	trie.MustUpdate(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001338"), accounts[4])
   705  	if exp, root := common.HexToHash("ec63b967e98a5720e7f720482151963982890d82c9093c0d486b7eb8883a66b1"), trie.Hash(); exp != root {
   706  		t.Errorf("2: got %x, exp %x", root, exp)
   707  	}
   708  	trie.MustUpdate(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001339"), accounts[4])
   709  	if exp, root := common.HexToHash("0608c1d1dc3905fa22204c7a0e43644831c3b6d3def0f274be623a948197e64a"), trie.Hash(); exp != root {
   710  		t.Errorf("3: got %x, exp %x", root, exp)
   711  	}
   712  	checktr := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   713  	it := NewIterator(trie.NodeIterator(nil))
   714  	for it.Next() {
   715  		checktr.MustUpdate(it.Key, it.Value)
   716  	}
   717  	if troot, itroot := trie.Hash(), checktr.Hash(); troot != itroot {
   718  		t.Fatalf("hash mismatch in opItercheckhash, trie: %x, check: %x", troot, itroot)
   719  	}
   720  }
   721  
   722  func TestCommitAfterHash(t *testing.T) {
   723  	// Create a realistic account trie to hash
   724  	addresses, accounts := makeAccounts(1000)
   725  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   726  	for i := 0; i < len(addresses); i++ {
   727  		trie.MustUpdate(crypto.Keccak256(addresses[i][:]), accounts[i])
   728  	}
   729  	// Insert the accounts into the trie and hash it
   730  	trie.Hash()
   731  	trie.Commit(false)
   732  	root := trie.Hash()
   733  	exp := common.HexToHash("72f9d3f3fe1e1dd7b8936442e7642aef76371472d94319900790053c493f3fe6")
   734  	if exp != root {
   735  		t.Errorf("got %x, exp %x", root, exp)
   736  	}
   737  	root, _ = trie.Commit(false)
   738  	if exp != root {
   739  		t.Errorf("got %x, exp %x", root, exp)
   740  	}
   741  }
   742  
   743  func makeAccounts(size int) (addresses [][20]byte, accounts [][]byte) {
   744  	// Make the random benchmark deterministic
   745  	random := rand.New(rand.NewSource(0))
   746  	// Create a realistic account trie to hash
   747  	addresses = make([][20]byte, size)
   748  	for i := 0; i < len(addresses); i++ {
   749  		data := make([]byte, 20)
   750  		random.Read(data)
   751  		copy(addresses[i][:], data)
   752  	}
   753  	accounts = make([][]byte, len(addresses))
   754  	for i := 0; i < len(accounts); i++ {
   755  		var (
   756  			nonce = uint64(random.Int63())
   757  			root  = types.EmptyRootHash
   758  			code  = crypto.Keccak256(nil)
   759  		)
   760  		// The big.Rand function is not deterministic with regards to 64 vs 32 bit systems,
   761  		// and will consume different amount of data from the rand source.
   762  		//balance = new(big.Int).Rand(random, new(big.Int).Exp(common.Big2, common.Big256, nil))
   763  		// Therefore, we instead just read via byte buffer
   764  		numBytes := random.Uint32() % 33 // [0, 32] bytes
   765  		balanceBytes := make([]byte, numBytes)
   766  		random.Read(balanceBytes)
   767  		balance := new(big.Int).SetBytes(balanceBytes)
   768  		data, _ := rlp.EncodeToBytes(&types.StateAccount{Nonce: nonce, Balance: balance, Root: root, CodeHash: code})
   769  		accounts[i] = data
   770  	}
   771  	return addresses, accounts
   772  }
   773  
   774  // spongeDb is a dummy db backend which accumulates writes in a sponge
   775  type spongeDb struct {
   776  	sponge  hash.Hash
   777  	id      string
   778  	journal []string
   779  }
   780  
   781  func (s *spongeDb) Has(key []byte) (bool, error)             { panic("implement me") }
   782  func (s *spongeDb) Get(key []byte) ([]byte, error)           { return nil, errors.New("no such elem") }
   783  func (s *spongeDb) Delete(key []byte) error                  { panic("implement me") }
   784  func (s *spongeDb) NewBatch() ethdb.Batch                    { return &spongeBatch{s} }
   785  func (s *spongeDb) NewBatchWithSize(size int) ethdb.Batch    { return &spongeBatch{s} }
   786  func (s *spongeDb) NewSnapshot() (ethdb.Snapshot, error)     { panic("implement me") }
   787  func (s *spongeDb) Stat(property string) (string, error)     { panic("implement me") }
   788  func (s *spongeDb) Compact(start []byte, limit []byte) error { panic("implement me") }
   789  func (s *spongeDb) Close() error                             { return nil }
   790  func (s *spongeDb) Put(key []byte, value []byte) error {
   791  	valbrief := value
   792  	if len(valbrief) > 8 {
   793  		valbrief = valbrief[:8]
   794  	}
   795  	s.journal = append(s.journal, fmt.Sprintf("%v: PUT([%x...], [%d bytes] %x...)\n", s.id, key[:8], len(value), valbrief))
   796  	s.sponge.Write(key)
   797  	s.sponge.Write(value)
   798  	return nil
   799  }
   800  func (s *spongeDb) NewIterator(prefix []byte, start []byte) ethdb.Iterator { panic("implement me") }
   801  
   802  // spongeBatch is a dummy batch which immediately writes to the underlying spongedb
   803  type spongeBatch struct {
   804  	db *spongeDb
   805  }
   806  
   807  func (b *spongeBatch) Put(key, value []byte) error {
   808  	b.db.Put(key, value)
   809  	return nil
   810  }
   811  func (b *spongeBatch) Delete(key []byte) error             { panic("implement me") }
   812  func (b *spongeBatch) ValueSize() int                      { return 100 }
   813  func (b *spongeBatch) Write() error                        { return nil }
   814  func (b *spongeBatch) Reset()                              {}
   815  func (b *spongeBatch) Replay(w ethdb.KeyValueWriter) error { return nil }
   816  
   817  // TestCommitSequence tests that the trie.Commit operation writes the elements of the trie
   818  // in the expected order.
   819  // The test data was based on the 'master' code, and is basically random. It can be used
   820  // to check whether changes to the trie modifies the write order or data in any way.
   821  func TestCommitSequence(t *testing.T) {
   822  	for i, tc := range []struct {
   823  		count           int
   824  		expWriteSeqHash []byte
   825  	}{
   826  		{20, common.FromHex("873c78df73d60e59d4a2bcf3716e8bfe14554549fea2fc147cb54129382a8066")},
   827  		{200, common.FromHex("ba03d891bb15408c940eea5ee3d54d419595102648d02774a0268d892add9c8e")},
   828  		{2000, common.FromHex("f7a184f20df01c94f09537401d11e68d97ad0c00115233107f51b9c287ce60c7")},
   829  	} {
   830  		addresses, accounts := makeAccounts(tc.count)
   831  		// This spongeDb is used to check the sequence of disk-db-writes
   832  		s := &spongeDb{sponge: sha3.NewLegacyKeccak256()}
   833  		db := NewDatabase(rawdb.NewDatabase(s))
   834  		trie := NewEmpty(db)
   835  		// Fill the trie with elements
   836  		for i := 0; i < tc.count; i++ {
   837  			trie.MustUpdate(crypto.Keccak256(addresses[i][:]), accounts[i])
   838  		}
   839  		// Flush trie -> database
   840  		root, nodes := trie.Commit(false)
   841  		db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
   842  		// Flush memdb -> disk (sponge)
   843  		db.Commit(root, false)
   844  		if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) {
   845  			t.Errorf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp)
   846  		}
   847  	}
   848  }
   849  
   850  // TestCommitSequenceRandomBlobs is identical to TestCommitSequence
   851  // but uses random blobs instead of 'accounts'
   852  func TestCommitSequenceRandomBlobs(t *testing.T) {
   853  	for i, tc := range []struct {
   854  		count           int
   855  		expWriteSeqHash []byte
   856  	}{
   857  		{20, common.FromHex("8e4a01548551d139fa9e833ebc4e66fc1ba40a4b9b7259d80db32cff7b64ebbc")},
   858  		{200, common.FromHex("6869b4e7b95f3097a19ddb30ff735f922b915314047e041614df06958fc50554")},
   859  		{2000, common.FromHex("444200e6f4e2df49f77752f629a96ccf7445d4698c164f962bbd85a0526ef424")},
   860  	} {
   861  		prng := rand.New(rand.NewSource(int64(i)))
   862  		// This spongeDb is used to check the sequence of disk-db-writes
   863  		s := &spongeDb{sponge: sha3.NewLegacyKeccak256()}
   864  		db := NewDatabase(rawdb.NewDatabase(s))
   865  		trie := NewEmpty(db)
   866  		// Fill the trie with elements
   867  		for i := 0; i < tc.count; i++ {
   868  			key := make([]byte, 32)
   869  			var val []byte
   870  			// 50% short elements, 50% large elements
   871  			if prng.Intn(2) == 0 {
   872  				val = make([]byte, 1+prng.Intn(32))
   873  			} else {
   874  				val = make([]byte, 1+prng.Intn(4096))
   875  			}
   876  			prng.Read(key)
   877  			prng.Read(val)
   878  			trie.MustUpdate(key, val)
   879  		}
   880  		// Flush trie -> database
   881  		root, nodes := trie.Commit(false)
   882  		db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
   883  		// Flush memdb -> disk (sponge)
   884  		db.Commit(root, false)
   885  		if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) {
   886  			t.Fatalf("test %d, disk write 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  			rawdb.WriteTrieNode(stackTrieSponge, owner, path, hash, blob, db.Scheme())
   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.Update(key, val)
   917  			stTrie.Update(key, val)
   918  		}
   919  		// Flush trie -> database
   920  		root, nodes := trie.Commit(false)
   921  		// Flush memdb -> disk (sponge)
   922  		db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
   923  		db.Commit(root, false)
   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  		rawdb.WriteTrieNode(stackTrieSponge, owner, path, hash, blob, db.Scheme())
   961  	})
   962  	// Add a single small-element to the trie(s)
   963  	key := make([]byte, 5)
   964  	key[0] = 1
   965  	trie.Update(key, []byte{0x1})
   966  	stTrie.Update(key, []byte{0x1})
   967  	// Flush trie -> database
   968  	root, nodes := trie.Commit(false)
   969  	// Flush memdb -> disk (sponge)
   970  	db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
   971  	db.Commit(root, false)
   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.MustUpdate(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.MustUpdate(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.MustUpdate(crypto.Keccak256(addresses[i][:]), accounts[i])
  1139  	}
  1140  	h := trie.Hash()
  1141  	root, nodes := trie.Commit(false)
  1142  	triedb.Update(root, types.EmptyRootHash, trienode.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.MustGet([]byte(k))
  1150  }
  1151  
  1152  func updateString(trie *Trie, k, v string) {
  1153  	trie.MustUpdate([]byte(k), []byte(v))
  1154  }
  1155  
  1156  func deleteString(trie *Trie, k string) {
  1157  	trie.MustDelete([]byte(k))
  1158  }
  1159  
  1160  func TestDecodeNode(t *testing.T) {
  1161  	t.Parallel()
  1162  
  1163  	var (
  1164  		hash  = make([]byte, 20)
  1165  		elems = make([]byte, 20)
  1166  	)
  1167  	for i := 0; i < 5000000; i++ {
  1168  		prng.Read(hash)
  1169  		prng.Read(elems)
  1170  		decodeNode(hash, elems)
  1171  	}
  1172  }