github.com/ethereum/go-ethereum@v1.16.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  	"io"
    26  	"math/rand"
    27  	"reflect"
    28  	"sort"
    29  	"strings"
    30  	"testing"
    31  	"testing/quick"
    32  
    33  	"github.com/davecgh/go-spew/spew"
    34  	"github.com/ethereum/go-ethereum/common"
    35  	"github.com/ethereum/go-ethereum/core/rawdb"
    36  	"github.com/ethereum/go-ethereum/core/types"
    37  	"github.com/ethereum/go-ethereum/crypto"
    38  	"github.com/ethereum/go-ethereum/ethdb"
    39  	"github.com/ethereum/go-ethereum/internal/testrand"
    40  	"github.com/ethereum/go-ethereum/rlp"
    41  	"github.com/ethereum/go-ethereum/trie/trienode"
    42  	"github.com/holiman/uint256"
    43  	"golang.org/x/crypto/sha3"
    44  )
    45  
    46  func init() {
    47  	spew.Config.Indent = "    "
    48  	spew.Config.DisableMethods = false
    49  }
    50  
    51  func TestEmptyTrie(t *testing.T) {
    52  	trie := NewEmpty(newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme))
    53  	res := trie.Hash()
    54  	exp := types.EmptyRootHash
    55  	if res != exp {
    56  		t.Errorf("expected %x got %x", exp, res)
    57  	}
    58  }
    59  
    60  func TestNull(t *testing.T) {
    61  	trie := NewEmpty(newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme))
    62  	key := make([]byte, 32)
    63  	value := []byte("test")
    64  	trie.MustUpdate(key, value)
    65  	if !bytes.Equal(trie.MustGet(key), value) {
    66  		t.Fatal("wrong value")
    67  	}
    68  }
    69  
    70  func TestMissingRoot(t *testing.T) {
    71  	testMissingRoot(t, rawdb.HashScheme)
    72  	testMissingRoot(t, rawdb.PathScheme)
    73  }
    74  
    75  func testMissingRoot(t *testing.T, scheme string) {
    76  	root := common.HexToHash("0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33")
    77  	trie, err := New(TrieID(root), newTestDatabase(rawdb.NewMemoryDatabase(), scheme))
    78  	if trie != nil {
    79  		t.Error("New returned non-nil trie for invalid root")
    80  	}
    81  	if _, ok := err.(*MissingNodeError); !ok {
    82  		t.Errorf("New returned wrong error: %v", err)
    83  	}
    84  }
    85  
    86  func TestMissingNode(t *testing.T) {
    87  	testMissingNode(t, false, rawdb.HashScheme)
    88  	testMissingNode(t, false, rawdb.PathScheme)
    89  	testMissingNode(t, true, rawdb.HashScheme)
    90  	testMissingNode(t, true, rawdb.PathScheme)
    91  }
    92  
    93  func testMissingNode(t *testing.T, memonly bool, scheme string) {
    94  	diskdb := rawdb.NewMemoryDatabase()
    95  	triedb := newTestDatabase(diskdb, scheme)
    96  
    97  	trie := NewEmpty(triedb)
    98  	updateString(trie, "120000", "qwerqwerqwerqwerqwerqwerqwerqwer")
    99  	updateString(trie, "123456", "asdfasdfasdfasdfasdfasdfasdfasdf")
   100  	root, nodes := trie.Commit(false)
   101  	triedb.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
   102  
   103  	if !memonly {
   104  		triedb.Commit(root)
   105  	}
   106  
   107  	trie, _ = New(TrieID(root), triedb)
   108  	_, err := trie.Get([]byte("120000"))
   109  	if err != nil {
   110  		t.Errorf("Unexpected error: %v", err)
   111  	}
   112  	trie, _ = New(TrieID(root), triedb)
   113  	_, err = trie.Get([]byte("120099"))
   114  	if err != nil {
   115  		t.Errorf("Unexpected error: %v", err)
   116  	}
   117  	trie, _ = New(TrieID(root), triedb)
   118  	_, err = trie.Get([]byte("123456"))
   119  	if err != nil {
   120  		t.Errorf("Unexpected error: %v", err)
   121  	}
   122  	trie, _ = New(TrieID(root), triedb)
   123  	err = trie.Update([]byte("120099"), []byte("zxcvzxcvzxcvzxcvzxcvzxcvzxcvzxcv"))
   124  	if err != nil {
   125  		t.Errorf("Unexpected error: %v", err)
   126  	}
   127  	trie, _ = New(TrieID(root), triedb)
   128  	err = trie.Delete([]byte("123456"))
   129  	if err != nil {
   130  		t.Errorf("Unexpected error: %v", err)
   131  	}
   132  
   133  	var (
   134  		path []byte
   135  		hash = common.HexToHash("0xe1d943cc8f061a0c0b98162830b970395ac9315654824bf21b73b891365262f9")
   136  	)
   137  	for p, n := range nodes.Nodes {
   138  		if n.Hash == hash {
   139  			path = common.CopyBytes([]byte(p))
   140  			break
   141  		}
   142  	}
   143  	trie, _ = New(TrieID(root), triedb)
   144  	if memonly {
   145  		trie.reader.banned = map[string]struct{}{string(path): {}}
   146  	} else {
   147  		rawdb.DeleteTrieNode(diskdb, common.Hash{}, path, hash, scheme)
   148  	}
   149  
   150  	_, err = trie.Get([]byte("120000"))
   151  	if _, ok := err.(*MissingNodeError); !ok {
   152  		t.Errorf("Wrong error: %v", err)
   153  	}
   154  	_, err = trie.Get([]byte("120099"))
   155  	if _, ok := err.(*MissingNodeError); !ok {
   156  		t.Errorf("Wrong error: %v", err)
   157  	}
   158  	_, err = trie.Get([]byte("123456"))
   159  	if err != nil {
   160  		t.Errorf("Unexpected error: %v", err)
   161  	}
   162  	err = trie.Update([]byte("120099"), []byte("zxcv"))
   163  	if _, ok := err.(*MissingNodeError); !ok {
   164  		t.Errorf("Wrong error: %v", err)
   165  	}
   166  	err = trie.Delete([]byte("123456"))
   167  	if _, ok := err.(*MissingNodeError); !ok {
   168  		t.Errorf("Wrong error: %v", err)
   169  	}
   170  }
   171  
   172  func TestInsert(t *testing.T) {
   173  	trie := NewEmpty(newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme))
   174  
   175  	updateString(trie, "doe", "reindeer")
   176  	updateString(trie, "dog", "puppy")
   177  	updateString(trie, "dogglesworth", "cat")
   178  
   179  	exp := common.HexToHash("8aad789dff2f538bca5d8ea56e8abe10f4c7ba3a5dea95fea4cd6e7c3a1168d3")
   180  	root := trie.Hash()
   181  	if root != exp {
   182  		t.Errorf("case 1: exp %x got %x", exp, root)
   183  	}
   184  
   185  	trie = NewEmpty(newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme))
   186  	updateString(trie, "A", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
   187  
   188  	exp = common.HexToHash("d23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab")
   189  	root, _ = trie.Commit(false)
   190  	if root != exp {
   191  		t.Errorf("case 2: exp %x got %x", exp, root)
   192  	}
   193  }
   194  
   195  func TestGet(t *testing.T) {
   196  	db := newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme)
   197  	trie := NewEmpty(db)
   198  	updateString(trie, "doe", "reindeer")
   199  	updateString(trie, "dog", "puppy")
   200  	updateString(trie, "dogglesworth", "cat")
   201  
   202  	for i := 0; i < 2; i++ {
   203  		res := getString(trie, "dog")
   204  		if !bytes.Equal(res, []byte("puppy")) {
   205  			t.Errorf("expected puppy got %x", res)
   206  		}
   207  		unknown := getString(trie, "unknown")
   208  		if unknown != nil {
   209  			t.Errorf("expected nil got %x", unknown)
   210  		}
   211  		if i == 1 {
   212  			return
   213  		}
   214  		root, nodes := trie.Commit(false)
   215  		db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
   216  		trie, _ = New(TrieID(root), db)
   217  	}
   218  }
   219  
   220  func TestDelete(t *testing.T) {
   221  	db := newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme)
   222  	trie := NewEmpty(db)
   223  	vals := []struct{ k, v string }{
   224  		{"do", "verb"},
   225  		{"ether", "wookiedoo"},
   226  		{"horse", "stallion"},
   227  		{"shaman", "horse"},
   228  		{"doge", "coin"},
   229  		{"ether", ""},
   230  		{"dog", "puppy"},
   231  		{"shaman", ""},
   232  	}
   233  	for _, val := range vals {
   234  		if val.v != "" {
   235  			updateString(trie, val.k, val.v)
   236  		} else {
   237  			deleteString(trie, val.k)
   238  		}
   239  	}
   240  
   241  	hash := trie.Hash()
   242  	exp := common.HexToHash("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84")
   243  	if hash != exp {
   244  		t.Errorf("expected %x got %x", exp, hash)
   245  	}
   246  }
   247  
   248  func TestEmptyValues(t *testing.T) {
   249  	trie := NewEmpty(newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme))
   250  
   251  	vals := []struct{ k, v string }{
   252  		{"do", "verb"},
   253  		{"ether", "wookiedoo"},
   254  		{"horse", "stallion"},
   255  		{"shaman", "horse"},
   256  		{"doge", "coin"},
   257  		{"ether", ""},
   258  		{"dog", "puppy"},
   259  		{"shaman", ""},
   260  	}
   261  	for _, val := range vals {
   262  		updateString(trie, val.k, val.v)
   263  	}
   264  
   265  	hash := trie.Hash()
   266  	exp := common.HexToHash("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84")
   267  	if hash != exp {
   268  		t.Errorf("expected %x got %x", exp, hash)
   269  	}
   270  }
   271  
   272  func TestReplication(t *testing.T) {
   273  	db := newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme)
   274  	trie := NewEmpty(db)
   275  	vals := []struct{ k, v string }{
   276  		{"do", "verb"},
   277  		{"ether", "wookiedoo"},
   278  		{"horse", "stallion"},
   279  		{"shaman", "horse"},
   280  		{"doge", "coin"},
   281  		{"dog", "puppy"},
   282  		{"somethingveryoddindeedthis is", "myothernodedata"},
   283  	}
   284  	for _, val := range vals {
   285  		updateString(trie, val.k, val.v)
   286  	}
   287  	root, nodes := trie.Commit(false)
   288  	db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
   289  
   290  	// create a new trie on top of the database and check that lookups work.
   291  	trie2, err := New(TrieID(root), db)
   292  	if err != nil {
   293  		t.Fatalf("can't recreate trie at %x: %v", root, err)
   294  	}
   295  	for _, kv := range vals {
   296  		if string(getString(trie2, kv.k)) != kv.v {
   297  			t.Errorf("trie2 doesn't have %q => %q", kv.k, kv.v)
   298  		}
   299  	}
   300  	hash, nodes := trie2.Commit(false)
   301  	if hash != root {
   302  		t.Errorf("root failure. expected %x got %x", root, hash)
   303  	}
   304  
   305  	// recreate the trie after commit
   306  	if nodes != nil {
   307  		db.Update(hash, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
   308  	}
   309  	trie2, err = New(TrieID(hash), db)
   310  	if err != nil {
   311  		t.Fatalf("can't recreate trie at %x: %v", hash, err)
   312  	}
   313  	// perform some insertions on the new trie.
   314  	vals2 := []struct{ k, v string }{
   315  		{"do", "verb"},
   316  		{"ether", "wookiedoo"},
   317  		{"horse", "stallion"},
   318  		// {"shaman", "horse"},
   319  		// {"doge", "coin"},
   320  		// {"ether", ""},
   321  		// {"dog", "puppy"},
   322  		// {"somethingveryoddindeedthis is", "myothernodedata"},
   323  		// {"shaman", ""},
   324  	}
   325  	for _, val := range vals2 {
   326  		updateString(trie2, val.k, val.v)
   327  	}
   328  	if trie2.Hash() != hash {
   329  		t.Errorf("root failure. expected %x got %x", hash, hash)
   330  	}
   331  }
   332  
   333  func TestLargeValue(t *testing.T) {
   334  	trie := NewEmpty(newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme))
   335  	trie.MustUpdate([]byte("key1"), []byte{99, 99, 99, 99})
   336  	trie.MustUpdate([]byte("key2"), bytes.Repeat([]byte{1}, 32))
   337  	trie.Hash()
   338  }
   339  
   340  // TestRandomCases tests some cases that were found via random fuzzing
   341  func TestRandomCases(t *testing.T) {
   342  	var rt = []randTestStep{
   343  		{op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 0
   344  		{op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 1
   345  		{op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000002")},           // step 2
   346  		{op: 2, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("")},                         // step 3
   347  		{op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 4
   348  		{op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 5
   349  		{op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 6
   350  		{op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 7
   351  		{op: 0, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("0000000000000008")},         // step 8
   352  		{op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000009")},           // step 9
   353  		{op: 2, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("")},                                                                                               // step 10
   354  		{op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 11
   355  		{op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 12
   356  		{op: 0, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("000000000000000d")},                                                                               // step 13
   357  		{op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 14
   358  		{op: 1, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("")},                         // step 15
   359  		{op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 16
   360  		{op: 0, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("0000000000000011")},         // step 17
   361  		{op: 5, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 18
   362  		{op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 19
   363  		{op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000014")},           // step 20
   364  		{op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000015")},           // step 21
   365  		{op: 0, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("0000000000000016")},         // step 22
   366  		{op: 5, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")},                                                                                                 // step 23
   367  		{op: 1, key: common.Hex2Bytes("980c393656413a15c8da01978ed9f89feb80b502f58f2d640e3a2f5f7a99a7018f1b573befd92053ac6f78fca4a87268"), value: common.Hex2Bytes("")}, // step 24
   368  		{op: 1, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("")},                                                                                               // step 25
   369  	}
   370  	if err := runRandTest(rt); err != nil {
   371  		t.Fatal(err)
   372  	}
   373  }
   374  
   375  // randTest performs random trie operations.
   376  // Instances of this test are created by Generate.
   377  type randTest []randTestStep
   378  
   379  // compile-time interface check
   380  var _ quick.Generator = (randTest)(nil)
   381  
   382  type randTestStep struct {
   383  	op    int
   384  	key   []byte // for opUpdate, opDelete, opGet
   385  	value []byte // for opUpdate
   386  	err   error  // for debugging
   387  }
   388  
   389  const (
   390  	opUpdate = iota
   391  	opDelete
   392  	opGet
   393  	opHash
   394  	opCommit
   395  	opItercheckhash
   396  	opNodeDiff
   397  	opProve
   398  	opMax // boundary value, not an actual op
   399  )
   400  
   401  func (randTest) Generate(r *rand.Rand, size int) reflect.Value {
   402  	var finishedFn = func() bool {
   403  		size--
   404  		return size == 0
   405  	}
   406  	return reflect.ValueOf(generateSteps(finishedFn, r))
   407  }
   408  
   409  func generateSteps(finished func() bool, r io.Reader) randTest {
   410  	var allKeys [][]byte
   411  	var one = []byte{0}
   412  	genKey := func() []byte {
   413  		r.Read(one)
   414  		if len(allKeys) < 2 || one[0]%100 > 90 {
   415  			// new key
   416  			size := one[0] % 50
   417  			key := make([]byte, size)
   418  			r.Read(key)
   419  			allKeys = append(allKeys, key)
   420  			return key
   421  		}
   422  		// use existing key
   423  		idx := int(one[0]) % len(allKeys)
   424  		return allKeys[idx]
   425  	}
   426  	var steps randTest
   427  	for !finished() {
   428  		r.Read(one)
   429  		step := randTestStep{op: int(one[0]) % opMax}
   430  		switch step.op {
   431  		case opUpdate:
   432  			step.key = genKey()
   433  			step.value = make([]byte, 8)
   434  			binary.BigEndian.PutUint64(step.value, uint64(len(steps)))
   435  		case opGet, opDelete, opProve:
   436  			step.key = genKey()
   437  		}
   438  		steps = append(steps, step)
   439  	}
   440  	return steps
   441  }
   442  
   443  func verifyAccessList(old *Trie, new *Trie, set *trienode.NodeSet) error {
   444  	deletes, inserts, updates := diffTries(old, new)
   445  
   446  	// Check insertion set
   447  	for path := range inserts {
   448  		n, ok := set.Nodes[path]
   449  		if !ok || n.IsDeleted() {
   450  			return errors.New("expect new node")
   451  		}
   452  		//if len(n.Prev) > 0 {
   453  		//	return errors.New("unexpected origin value")
   454  		//}
   455  	}
   456  	// Check deletion set
   457  	for path := range deletes {
   458  		n, ok := set.Nodes[path]
   459  		if !ok || !n.IsDeleted() {
   460  			return errors.New("expect deleted node")
   461  		}
   462  		//if len(n.Prev) == 0 {
   463  		//	return errors.New("expect origin value")
   464  		//}
   465  		//if !bytes.Equal(n.Prev, blob) {
   466  		//	return errors.New("invalid origin value")
   467  		//}
   468  	}
   469  	// Check update set
   470  	for path := range updates {
   471  		n, ok := set.Nodes[path]
   472  		if !ok || n.IsDeleted() {
   473  			return errors.New("expect updated node")
   474  		}
   475  		//if len(n.Prev) == 0 {
   476  		//	return errors.New("expect origin value")
   477  		//}
   478  		//if !bytes.Equal(n.Prev, blob) {
   479  		//	return errors.New("invalid origin value")
   480  		//}
   481  	}
   482  	return nil
   483  }
   484  
   485  // runRandTestBool coerces error to boolean, for use in quick.Check
   486  func runRandTestBool(rt randTest) bool {
   487  	return runRandTest(rt) == nil
   488  }
   489  
   490  func runRandTest(rt randTest) error {
   491  	var scheme = rawdb.HashScheme
   492  	if rand.Intn(2) == 0 {
   493  		scheme = rawdb.PathScheme
   494  	}
   495  	var (
   496  		origin   = types.EmptyRootHash
   497  		triedb   = newTestDatabase(rawdb.NewMemoryDatabase(), scheme)
   498  		tr       = NewEmpty(triedb)
   499  		values   = make(map[string]string) // tracks content of the trie
   500  		origTrie = NewEmpty(triedb)
   501  	)
   502  	for i, step := range rt {
   503  		// fmt.Printf("{op: %d, key: common.Hex2Bytes(\"%x\"), value: common.Hex2Bytes(\"%x\")}, // step %d\n",
   504  		// 	step.op, step.key, step.value, i)
   505  
   506  		switch step.op {
   507  		case opUpdate:
   508  			tr.MustUpdate(step.key, step.value)
   509  			values[string(step.key)] = string(step.value)
   510  		case opDelete:
   511  			tr.MustDelete(step.key)
   512  			delete(values, string(step.key))
   513  		case opGet:
   514  			v := tr.MustGet(step.key)
   515  			want := values[string(step.key)]
   516  			if string(v) != want {
   517  				rt[i].err = fmt.Errorf("mismatch for key %#x, got %#x want %#x", step.key, v, want)
   518  			}
   519  		case opProve:
   520  			hash := tr.Hash()
   521  			if hash == types.EmptyRootHash {
   522  				continue
   523  			}
   524  			proofDb := rawdb.NewMemoryDatabase()
   525  			err := tr.Prove(step.key, proofDb)
   526  			if err != nil {
   527  				rt[i].err = fmt.Errorf("failed for proving key %#x, %v", step.key, err)
   528  			}
   529  			_, err = VerifyProof(hash, step.key, proofDb)
   530  			if err != nil {
   531  				rt[i].err = fmt.Errorf("failed for verifying key %#x, %v", step.key, err)
   532  			}
   533  		case opHash:
   534  			tr.Hash()
   535  		case opCommit:
   536  			root, nodes := tr.Commit(true)
   537  			if nodes != nil {
   538  				triedb.Update(root, origin, trienode.NewWithNodeSet(nodes))
   539  			}
   540  			newtr, err := New(TrieID(root), triedb)
   541  			if err != nil {
   542  				rt[i].err = err
   543  				return err
   544  			}
   545  			if nodes != nil {
   546  				if err := verifyAccessList(origTrie, newtr, nodes); err != nil {
   547  					rt[i].err = err
   548  					return err
   549  				}
   550  			}
   551  			tr = newtr
   552  			origTrie = tr.Copy()
   553  			origin = root
   554  		case opItercheckhash:
   555  			checktr := NewEmpty(triedb)
   556  			it := NewIterator(tr.MustNodeIterator(nil))
   557  			for it.Next() {
   558  				checktr.MustUpdate(it.Key, it.Value)
   559  			}
   560  			if tr.Hash() != checktr.Hash() {
   561  				rt[i].err = errors.New("hash mismatch in opItercheckhash")
   562  			}
   563  		case opNodeDiff:
   564  			var (
   565  				origIter = origTrie.MustNodeIterator(nil)
   566  				curIter  = tr.MustNodeIterator(nil)
   567  				origSeen = make(map[string]struct{})
   568  				curSeen  = make(map[string]struct{})
   569  			)
   570  			for origIter.Next(true) {
   571  				if origIter.Leaf() {
   572  					continue
   573  				}
   574  				origSeen[string(origIter.Path())] = struct{}{}
   575  			}
   576  			for curIter.Next(true) {
   577  				if curIter.Leaf() {
   578  					continue
   579  				}
   580  				curSeen[string(curIter.Path())] = struct{}{}
   581  			}
   582  			var (
   583  				insertExp = make(map[string]struct{})
   584  				deleteExp = make(map[string]struct{})
   585  			)
   586  			for path := range curSeen {
   587  				_, present := origSeen[path]
   588  				if !present {
   589  					insertExp[path] = struct{}{}
   590  				}
   591  			}
   592  			for path := range origSeen {
   593  				_, present := curSeen[path]
   594  				if !present {
   595  					deleteExp[path] = struct{}{}
   596  				}
   597  			}
   598  			if len(insertExp) != len(tr.tracer.inserts) {
   599  				rt[i].err = errors.New("insert set mismatch")
   600  			}
   601  			if len(deleteExp) != len(tr.tracer.deletes) {
   602  				rt[i].err = errors.New("delete set mismatch")
   603  			}
   604  			for insert := range tr.tracer.inserts {
   605  				if _, present := insertExp[insert]; !present {
   606  					rt[i].err = errors.New("missing inserted node")
   607  				}
   608  			}
   609  			for del := range tr.tracer.deletes {
   610  				if _, present := deleteExp[del]; !present {
   611  					rt[i].err = errors.New("missing deleted node")
   612  				}
   613  			}
   614  		}
   615  		// Abort the test on error.
   616  		if rt[i].err != nil {
   617  			return rt[i].err
   618  		}
   619  	}
   620  	return nil
   621  }
   622  
   623  func TestRandom(t *testing.T) {
   624  	if err := quick.Check(runRandTestBool, nil); err != nil {
   625  		if cerr, ok := err.(*quick.CheckError); ok {
   626  			t.Fatalf("random test iteration %d failed: %s", cerr.Count, spew.Sdump(cerr.In))
   627  		}
   628  		t.Fatal(err)
   629  	}
   630  }
   631  
   632  func BenchmarkGet(b *testing.B)      { benchGet(b) }
   633  func BenchmarkUpdateBE(b *testing.B) { benchUpdate(b, binary.BigEndian) }
   634  func BenchmarkUpdateLE(b *testing.B) { benchUpdate(b, binary.LittleEndian) }
   635  
   636  const benchElemCount = 20000
   637  
   638  func benchGet(b *testing.B) {
   639  	triedb := newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme)
   640  	trie := NewEmpty(triedb)
   641  	k := make([]byte, 32)
   642  	for i := 0; i < benchElemCount; i++ {
   643  		binary.LittleEndian.PutUint64(k, uint64(i))
   644  		v := make([]byte, 32)
   645  		binary.LittleEndian.PutUint64(v, uint64(i))
   646  		trie.MustUpdate(k, v)
   647  	}
   648  	binary.LittleEndian.PutUint64(k, benchElemCount/2)
   649  
   650  	b.ResetTimer()
   651  	for i := 0; i < b.N; i++ {
   652  		trie.MustGet(k)
   653  	}
   654  	b.StopTimer()
   655  }
   656  
   657  func benchUpdate(b *testing.B, e binary.ByteOrder) *Trie {
   658  	trie := NewEmpty(newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme))
   659  	k := make([]byte, 32)
   660  	b.ReportAllocs()
   661  	for i := 0; i < b.N; i++ {
   662  		v := make([]byte, 32)
   663  		e.PutUint64(k, uint64(i))
   664  		e.PutUint64(v, uint64(i))
   665  		trie.MustUpdate(k, v)
   666  	}
   667  	return trie
   668  }
   669  
   670  // Benchmarks the trie hashing. Since the trie caches the result of any operation,
   671  // we cannot use b.N as the number of hashing rounds, since all rounds apart from
   672  // the first one will be NOOP. As such, we'll use b.N as the number of account to
   673  // insert into the trie before measuring the hashing.
   674  // BenchmarkHash-6   	  288680	      4561 ns/op	     682 B/op	       9 allocs/op
   675  // BenchmarkHash-6   	  275095	      4800 ns/op	     685 B/op	       9 allocs/op
   676  // pure hasher:
   677  // BenchmarkHash-6   	  319362	      4230 ns/op	     675 B/op	       9 allocs/op
   678  // BenchmarkHash-6   	  257460	      4674 ns/op	     689 B/op	       9 allocs/op
   679  // With hashing in-between and pure hasher:
   680  // BenchmarkHash-6   	  225417	      7150 ns/op	     982 B/op	      12 allocs/op
   681  // BenchmarkHash-6   	  220378	      6197 ns/op	     983 B/op	      12 allocs/op
   682  // same with old hasher
   683  // BenchmarkHash-6   	  229758	      6437 ns/op	     981 B/op	      12 allocs/op
   684  // BenchmarkHash-6   	  212610	      7137 ns/op	     986 B/op	      12 allocs/op
   685  func BenchmarkHash(b *testing.B) {
   686  	// Create a realistic account trie to hash. We're first adding and hashing N
   687  	// entries, then adding N more.
   688  	addresses, accounts := makeAccounts(2 * b.N)
   689  	// Insert the accounts into the trie and hash it
   690  	trie := NewEmpty(newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme))
   691  	i := 0
   692  	for ; i < len(addresses)/2; i++ {
   693  		trie.MustUpdate(crypto.Keccak256(addresses[i][:]), accounts[i])
   694  	}
   695  	trie.Hash()
   696  	for ; i < len(addresses); i++ {
   697  		trie.MustUpdate(crypto.Keccak256(addresses[i][:]), accounts[i])
   698  	}
   699  	b.ResetTimer()
   700  	b.ReportAllocs()
   701  	//trie.hashRoot(nil, nil)
   702  	trie.Hash()
   703  }
   704  
   705  // Benchmarks the trie Commit following a Hash. Since the trie caches the result of any operation,
   706  // we cannot use b.N as the number of hashing rounds, since all rounds apart from
   707  // the first one will be NOOP. As such, we'll use b.N as the number of account to
   708  // insert into the trie before measuring the hashing.
   709  func BenchmarkCommitAfterHash(b *testing.B) {
   710  	b.Run("no-onleaf", func(b *testing.B) {
   711  		benchmarkCommitAfterHash(b, false)
   712  	})
   713  	b.Run("with-onleaf", func(b *testing.B) {
   714  		benchmarkCommitAfterHash(b, true)
   715  	})
   716  }
   717  
   718  func benchmarkCommitAfterHash(b *testing.B, collectLeaf bool) {
   719  	// Make the random benchmark deterministic
   720  	addresses, accounts := makeAccounts(b.N)
   721  	trie := NewEmpty(newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme))
   722  	for i := 0; i < len(addresses); i++ {
   723  		trie.MustUpdate(crypto.Keccak256(addresses[i][:]), accounts[i])
   724  	}
   725  	// Insert the accounts into the trie and hash it
   726  	trie.Hash()
   727  	b.ResetTimer()
   728  	b.ReportAllocs()
   729  	trie.Commit(collectLeaf)
   730  }
   731  
   732  func TestTinyTrie(t *testing.T) {
   733  	// Create a realistic account trie to hash
   734  	_, accounts := makeAccounts(5)
   735  	trie := NewEmpty(newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme))
   736  	trie.MustUpdate(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001337"), accounts[3])
   737  	if exp, root := common.HexToHash("8c6a85a4d9fda98feff88450299e574e5378e32391f75a055d470ac0653f1005"), trie.Hash(); exp != root {
   738  		t.Errorf("1: got %x, exp %x", root, exp)
   739  	}
   740  	trie.MustUpdate(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001338"), accounts[4])
   741  	if exp, root := common.HexToHash("ec63b967e98a5720e7f720482151963982890d82c9093c0d486b7eb8883a66b1"), trie.Hash(); exp != root {
   742  		t.Errorf("2: got %x, exp %x", root, exp)
   743  	}
   744  	trie.MustUpdate(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001339"), accounts[4])
   745  	if exp, root := common.HexToHash("0608c1d1dc3905fa22204c7a0e43644831c3b6d3def0f274be623a948197e64a"), trie.Hash(); exp != root {
   746  		t.Errorf("3: got %x, exp %x", root, exp)
   747  	}
   748  	checktr := NewEmpty(newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme))
   749  	it := NewIterator(trie.MustNodeIterator(nil))
   750  	for it.Next() {
   751  		checktr.MustUpdate(it.Key, it.Value)
   752  	}
   753  	if troot, itroot := trie.Hash(), checktr.Hash(); troot != itroot {
   754  		t.Fatalf("hash mismatch in opItercheckhash, trie: %x, check: %x", troot, itroot)
   755  	}
   756  }
   757  
   758  func TestCommitAfterHash(t *testing.T) {
   759  	// Create a realistic account trie to hash
   760  	addresses, accounts := makeAccounts(1000)
   761  	trie := NewEmpty(newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme))
   762  	for i := 0; i < len(addresses); i++ {
   763  		trie.MustUpdate(crypto.Keccak256(addresses[i][:]), accounts[i])
   764  	}
   765  	// Insert the accounts into the trie and hash it
   766  	trie.Hash()
   767  	trie.Commit(false)
   768  	root := trie.Hash()
   769  	exp := common.HexToHash("72f9d3f3fe1e1dd7b8936442e7642aef76371472d94319900790053c493f3fe6")
   770  	if exp != root {
   771  		t.Errorf("got %x, exp %x", root, exp)
   772  	}
   773  	root, _ = trie.Commit(false)
   774  	if exp != root {
   775  		t.Errorf("got %x, exp %x", root, exp)
   776  	}
   777  }
   778  
   779  func makeAccounts(size int) (addresses [][20]byte, accounts [][]byte) {
   780  	// Make the random benchmark deterministic
   781  	random := rand.New(rand.NewSource(0))
   782  
   783  	// Create a realistic account trie to hash
   784  	addresses = make([][20]byte, size)
   785  	for i := 0; i < len(addresses); i++ {
   786  		data := make([]byte, 20)
   787  		random.Read(data)
   788  		copy(addresses[i][:], data)
   789  	}
   790  	accounts = make([][]byte, len(addresses))
   791  	for i := 0; i < len(accounts); i++ {
   792  		var (
   793  			nonce = uint64(random.Int63())
   794  			root  = types.EmptyRootHash
   795  			code  = crypto.Keccak256(nil)
   796  		)
   797  		// The big.Rand function is not deterministic with regards to 64 vs 32 bit systems,
   798  		// and will consume different amount of data from the rand source.
   799  		// balance = new(big.Int).Rand(random, new(big.Int).Exp(common.Big2, common.Big256, nil))
   800  		// Therefore, we instead just read via byte buffer
   801  		numBytes := random.Uint32() % 33 // [0, 32] bytes
   802  		balanceBytes := make([]byte, numBytes)
   803  		random.Read(balanceBytes)
   804  		balance := new(uint256.Int).SetBytes(balanceBytes)
   805  		data, _ := rlp.EncodeToBytes(&types.StateAccount{
   806  			Nonce:    nonce,
   807  			Balance:  balance,
   808  			Root:     root,
   809  			CodeHash: code,
   810  		})
   811  		accounts[i] = data
   812  	}
   813  	return addresses, accounts
   814  }
   815  
   816  // spongeDb is a dummy db backend which accumulates writes in a sponge
   817  type spongeDb struct {
   818  	sponge  hash.Hash
   819  	id      string
   820  	journal []string
   821  	keys    []string
   822  	values  map[string]string
   823  }
   824  
   825  func (s *spongeDb) Has(key []byte) (bool, error)             { panic("implement me") }
   826  func (s *spongeDb) Get(key []byte) ([]byte, error)           { return nil, errors.New("no such elem") }
   827  func (s *spongeDb) Delete(key []byte) error                  { panic("implement me") }
   828  func (s *spongeDb) DeleteRange(start, end []byte) error      { panic("implement me") }
   829  func (s *spongeDb) NewBatch() ethdb.Batch                    { return &spongeBatch{s} }
   830  func (s *spongeDb) NewBatchWithSize(size int) ethdb.Batch    { return &spongeBatch{s} }
   831  func (s *spongeDb) Stat() (string, error)                    { panic("implement me") }
   832  func (s *spongeDb) Compact(start []byte, limit []byte) error { panic("implement me") }
   833  func (s *spongeDb) SyncKeyValue() error                      { return nil }
   834  func (s *spongeDb) Close() error                             { return nil }
   835  func (s *spongeDb) Put(key []byte, value []byte) error {
   836  	var (
   837  		keybrief = key
   838  		valbrief = value
   839  	)
   840  	if len(keybrief) > 8 {
   841  		keybrief = keybrief[:8]
   842  	}
   843  	if len(valbrief) > 8 {
   844  		valbrief = valbrief[:8]
   845  	}
   846  	s.journal = append(s.journal, fmt.Sprintf("%v: PUT([%x...], [%d bytes] %x...)\n", s.id, keybrief, len(value), valbrief))
   847  
   848  	if s.values == nil {
   849  		s.sponge.Write(key)
   850  		s.sponge.Write(value)
   851  	} else {
   852  		s.keys = append(s.keys, string(key))
   853  		s.values[string(key)] = string(value)
   854  	}
   855  	return nil
   856  }
   857  func (s *spongeDb) NewIterator(prefix []byte, start []byte) ethdb.Iterator { panic("implement me") }
   858  
   859  func (s *spongeDb) Flush() {
   860  	// Bottom-up, the longest path first
   861  	sort.Sort(sort.Reverse(sort.StringSlice(s.keys)))
   862  	for _, key := range s.keys {
   863  		s.sponge.Write([]byte(key))
   864  		s.sponge.Write([]byte(s.values[key]))
   865  	}
   866  	fmt.Println(len(s.keys))
   867  }
   868  
   869  // spongeBatch is a dummy batch which immediately writes to the underlying spongedb
   870  type spongeBatch struct {
   871  	db *spongeDb
   872  }
   873  
   874  func (b *spongeBatch) Put(key, value []byte) error {
   875  	b.db.Put(key, value)
   876  	return nil
   877  }
   878  func (b *spongeBatch) Delete(key []byte) error             { panic("implement me") }
   879  func (b *spongeBatch) DeleteRange(start, end []byte) error { panic("implement me") }
   880  func (b *spongeBatch) ValueSize() int                      { return 100 }
   881  func (b *spongeBatch) Write() error                        { return nil }
   882  func (b *spongeBatch) Reset()                              {}
   883  func (b *spongeBatch) Replay(w ethdb.KeyValueWriter) error { return nil }
   884  
   885  // TestCommitSequence tests that the trie.Commit operation writes the elements
   886  // of the trie in the expected order.
   887  //
   888  // The test data was based on the 'master' code, and is basically random.
   889  // It can be used to check whether changes to the trie modifies the write order
   890  // or data in any way.
   891  func TestCommitSequence(t *testing.T) {
   892  	for i, tc := range []struct {
   893  		count           int
   894  		expWriteSeqHash []byte
   895  	}{
   896  		{20, common.FromHex("330b0afae2853d96b9f015791fbe0fb7f239bf65f335f16dfc04b76c7536276d")},
   897  		{200, common.FromHex("5162b3735c06b5d606b043a3ee8adbdbbb408543f4966bca9dcc63da82684eeb")},
   898  		{2000, common.FromHex("4574cd8e6b17f3fe8ad89140d1d0bf4f1bd7a87a8ac3fb623b33550544c77635")},
   899  	} {
   900  		addresses, accounts := makeAccounts(tc.count)
   901  
   902  		// This spongeDb is used to check the sequence of disk-db-writes
   903  		s := &spongeDb{sponge: crypto.NewKeccakState()}
   904  		db := newTestDatabase(rawdb.NewDatabase(s), rawdb.HashScheme)
   905  
   906  		// Fill the trie with elements
   907  		trie := NewEmpty(db)
   908  		for i := 0; i < tc.count; i++ {
   909  			trie.MustUpdate(crypto.Keccak256(addresses[i][:]), accounts[i])
   910  		}
   911  		// Flush trie -> database
   912  		root, nodes := trie.Commit(false)
   913  		db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
   914  
   915  		// Flush memdb -> disk (sponge)
   916  		db.Commit(root)
   917  
   918  		if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) {
   919  			t.Errorf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp)
   920  		}
   921  	}
   922  }
   923  
   924  // TestCommitSequenceRandomBlobs is identical to TestCommitSequence
   925  // but uses random blobs instead of 'accounts'
   926  func TestCommitSequenceRandomBlobs(t *testing.T) {
   927  	for i, tc := range []struct {
   928  		count           int
   929  		expWriteSeqHash []byte
   930  	}{
   931  		{20, common.FromHex("8016650c7a50cf88485fd06cde52d634a89711051107f00d21fae98234f2f13d")},
   932  		{200, common.FromHex("dde92ca9812e068e6982d04b40846dc65a61a9fd4996fc0f55f2fde172a8e13c")},
   933  		{2000, common.FromHex("ab553a7f9aff82e3929c382908e30ef7dd17a332933e92ba3fe873fc661ef382")},
   934  	} {
   935  		// This spongeDb is used to check the sequence of disk-db-writes
   936  		prng := rand.New(rand.NewSource(int64(i)))
   937  		s := &spongeDb{sponge: crypto.NewKeccakState()}
   938  		db := newTestDatabase(rawdb.NewDatabase(s), rawdb.HashScheme)
   939  
   940  		// Fill the trie with elements
   941  		trie := NewEmpty(db)
   942  		for i := 0; i < tc.count; i++ {
   943  			key := make([]byte, 32)
   944  			var val []byte
   945  			// 50% short elements, 50% large elements
   946  			if prng.Intn(2) == 0 {
   947  				val = make([]byte, 1+prng.Intn(32))
   948  			} else {
   949  				val = make([]byte, 1+prng.Intn(4096))
   950  			}
   951  			prng.Read(key)
   952  			prng.Read(val)
   953  			trie.MustUpdate(key, val)
   954  		}
   955  		// Flush trie -> database
   956  		root, nodes := trie.Commit(false)
   957  		db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
   958  
   959  		// Flush memdb -> disk (sponge)
   960  		db.Commit(root)
   961  		if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) {
   962  			t.Fatalf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp)
   963  		}
   964  	}
   965  }
   966  
   967  func TestCommitSequenceStackTrie(t *testing.T) {
   968  	for count := 1; count < 200; count++ {
   969  		prng := rand.New(rand.NewSource(int64(count)))
   970  		// This spongeDb is used to check the sequence of disk-db-writes
   971  		s := &spongeDb{
   972  			sponge: sha3.NewLegacyKeccak256(),
   973  			id:     "a",
   974  			values: make(map[string]string),
   975  		}
   976  		db := newTestDatabase(rawdb.NewDatabase(s), rawdb.HashScheme)
   977  		trie := NewEmpty(db)
   978  
   979  		// Another sponge is used for the stacktrie commits
   980  		stackTrieSponge := &spongeDb{
   981  			sponge: sha3.NewLegacyKeccak256(),
   982  			id:     "b",
   983  			values: make(map[string]string),
   984  		}
   985  		stTrie := NewStackTrie(func(path []byte, hash common.Hash, blob []byte) {
   986  			rawdb.WriteTrieNode(stackTrieSponge, common.Hash{}, path, hash, blob, db.Scheme())
   987  		})
   988  
   989  		// Fill the trie with elements
   990  		for i := 0; i < count; i++ {
   991  			// For the stack trie, we need to do inserts in proper order
   992  			key := make([]byte, 32)
   993  			binary.BigEndian.PutUint64(key, uint64(i))
   994  
   995  			// 50% short elements, 50% large elements
   996  			var val []byte
   997  			if prng.Intn(2) == 0 {
   998  				val = make([]byte, 1+prng.Intn(32))
   999  			} else {
  1000  				val = make([]byte, 1+prng.Intn(1024))
  1001  			}
  1002  			prng.Read(val)
  1003  
  1004  			trie.Update(key, val)
  1005  			stTrie.Update(key, val)
  1006  		}
  1007  		// Flush trie -> database
  1008  		root, nodes := trie.Commit(false)
  1009  
  1010  		// Flush memdb -> disk (sponge)
  1011  		db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
  1012  		db.Commit(root)
  1013  		s.Flush()
  1014  
  1015  		// And flush stacktrie -> disk
  1016  		stRoot := stTrie.Hash()
  1017  		if stRoot != root {
  1018  			t.Fatalf("root wrong, got %x exp %x", stRoot, root)
  1019  		}
  1020  		stackTrieSponge.Flush()
  1021  		if got, exp := stackTrieSponge.sponge.Sum(nil), s.sponge.Sum(nil); !bytes.Equal(got, exp) {
  1022  			// Show the journal
  1023  			t.Logf("Expected:")
  1024  			for i, v := range s.journal {
  1025  				t.Logf("op %d: %v", i, v)
  1026  			}
  1027  			t.Logf("Stacktrie:")
  1028  			for i, v := range stackTrieSponge.journal {
  1029  				t.Logf("op %d: %v", i, v)
  1030  			}
  1031  			t.Fatalf("test %d, disk write sequence wrong:\ngot %x exp %x\n", count, got, exp)
  1032  		}
  1033  	}
  1034  }
  1035  
  1036  // TestCommitSequenceSmallRoot tests that a trie which is essentially only a
  1037  // small (<32 byte) shortnode with an included value is properly committed to a
  1038  // database.
  1039  // This case might not matter, since in practice, all keys are 32 bytes, which means
  1040  // that even a small trie which contains a leaf will have an extension making it
  1041  // not fit into 32 bytes, rlp-encoded. However, it's still the correct thing to do.
  1042  func TestCommitSequenceSmallRoot(t *testing.T) {
  1043  	s := &spongeDb{
  1044  		sponge: sha3.NewLegacyKeccak256(),
  1045  		id:     "a",
  1046  		values: make(map[string]string),
  1047  	}
  1048  	db := newTestDatabase(rawdb.NewDatabase(s), rawdb.HashScheme)
  1049  	trie := NewEmpty(db)
  1050  
  1051  	// Another sponge is used for the stacktrie commits
  1052  	stackTrieSponge := &spongeDb{
  1053  		sponge: sha3.NewLegacyKeccak256(),
  1054  		id:     "b",
  1055  		values: make(map[string]string),
  1056  	}
  1057  	stTrie := NewStackTrie(func(path []byte, hash common.Hash, blob []byte) {
  1058  		rawdb.WriteTrieNode(stackTrieSponge, common.Hash{}, path, hash, blob, db.Scheme())
  1059  	})
  1060  	// Add a single small-element to the trie(s)
  1061  	key := make([]byte, 5)
  1062  	key[0] = 1
  1063  	trie.Update(key, []byte{0x1})
  1064  	stTrie.Update(key, []byte{0x1})
  1065  
  1066  	// Flush trie -> database
  1067  	root, nodes := trie.Commit(false)
  1068  
  1069  	// Flush memdb -> disk (sponge)
  1070  	db.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
  1071  	db.Commit(root)
  1072  
  1073  	// And flush stacktrie -> disk
  1074  	stRoot := stTrie.Hash()
  1075  	if stRoot != root {
  1076  		t.Fatalf("root wrong, got %x exp %x", stRoot, root)
  1077  	}
  1078  	t.Logf("root: %x\n", stRoot)
  1079  
  1080  	s.Flush()
  1081  	stackTrieSponge.Flush()
  1082  	if got, exp := stackTrieSponge.sponge.Sum(nil), s.sponge.Sum(nil); !bytes.Equal(got, exp) {
  1083  		t.Fatalf("test, disk write sequence wrong:\ngot %x exp %x\n", got, exp)
  1084  	}
  1085  }
  1086  
  1087  // BenchmarkHashFixedSize benchmarks the hash of a fixed number of updates to a trie.
  1088  // This benchmark is meant to capture the difference on efficiency of small versus large changes. Typically,
  1089  // storage tries are small (a couple of entries), whereas the full post-block account trie update is large (a couple
  1090  // of thousand entries)
  1091  func BenchmarkHashFixedSize(b *testing.B) {
  1092  	b.Run("10", func(b *testing.B) {
  1093  		b.StopTimer()
  1094  		acc, add := makeAccounts(20)
  1095  		for i := 0; i < b.N; i++ {
  1096  			benchmarkHashFixedSize(b, acc, add)
  1097  		}
  1098  	})
  1099  	b.Run("100", func(b *testing.B) {
  1100  		b.StopTimer()
  1101  		acc, add := makeAccounts(100)
  1102  		for i := 0; i < b.N; i++ {
  1103  			benchmarkHashFixedSize(b, acc, add)
  1104  		}
  1105  	})
  1106  
  1107  	b.Run("1K", func(b *testing.B) {
  1108  		b.StopTimer()
  1109  		acc, add := makeAccounts(1000)
  1110  		for i := 0; i < b.N; i++ {
  1111  			benchmarkHashFixedSize(b, acc, add)
  1112  		}
  1113  	})
  1114  	b.Run("10K", func(b *testing.B) {
  1115  		b.StopTimer()
  1116  		acc, add := makeAccounts(10000)
  1117  		for i := 0; i < b.N; i++ {
  1118  			benchmarkHashFixedSize(b, acc, add)
  1119  		}
  1120  	})
  1121  	b.Run("100K", func(b *testing.B) {
  1122  		b.StopTimer()
  1123  		acc, add := makeAccounts(100000)
  1124  		for i := 0; i < b.N; i++ {
  1125  			benchmarkHashFixedSize(b, acc, add)
  1126  		}
  1127  	})
  1128  }
  1129  
  1130  func benchmarkHashFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  1131  	b.ReportAllocs()
  1132  	trie := NewEmpty(newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme))
  1133  	for i := 0; i < len(addresses); i++ {
  1134  		trie.MustUpdate(crypto.Keccak256(addresses[i][:]), accounts[i])
  1135  	}
  1136  	// Insert the accounts into the trie and hash it
  1137  	b.StartTimer()
  1138  	trie.Hash()
  1139  	b.StopTimer()
  1140  }
  1141  
  1142  func BenchmarkCommitAfterHashFixedSize(b *testing.B) {
  1143  	b.Run("10", func(b *testing.B) {
  1144  		b.StopTimer()
  1145  		acc, add := makeAccounts(20)
  1146  		for i := 0; i < b.N; i++ {
  1147  			benchmarkCommitAfterHashFixedSize(b, acc, add)
  1148  		}
  1149  	})
  1150  	b.Run("100", func(b *testing.B) {
  1151  		b.StopTimer()
  1152  		acc, add := makeAccounts(100)
  1153  		for i := 0; i < b.N; i++ {
  1154  			benchmarkCommitAfterHashFixedSize(b, acc, add)
  1155  		}
  1156  	})
  1157  
  1158  	b.Run("1K", func(b *testing.B) {
  1159  		b.StopTimer()
  1160  		acc, add := makeAccounts(1000)
  1161  		for i := 0; i < b.N; i++ {
  1162  			benchmarkCommitAfterHashFixedSize(b, acc, add)
  1163  		}
  1164  	})
  1165  	b.Run("10K", func(b *testing.B) {
  1166  		b.StopTimer()
  1167  		acc, add := makeAccounts(10000)
  1168  		for i := 0; i < b.N; i++ {
  1169  			benchmarkCommitAfterHashFixedSize(b, acc, add)
  1170  		}
  1171  	})
  1172  	b.Run("100K", func(b *testing.B) {
  1173  		b.StopTimer()
  1174  		acc, add := makeAccounts(100000)
  1175  		for i := 0; i < b.N; i++ {
  1176  			benchmarkCommitAfterHashFixedSize(b, acc, add)
  1177  		}
  1178  	})
  1179  }
  1180  
  1181  func benchmarkCommitAfterHashFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  1182  	b.ReportAllocs()
  1183  	trie := NewEmpty(newTestDatabase(rawdb.NewMemoryDatabase(), rawdb.HashScheme))
  1184  	for i := 0; i < len(addresses); i++ {
  1185  		trie.MustUpdate(crypto.Keccak256(addresses[i][:]), accounts[i])
  1186  	}
  1187  	// Insert the accounts into the trie and hash it
  1188  	trie.Hash()
  1189  	b.StartTimer()
  1190  	trie.Commit(false)
  1191  	b.StopTimer()
  1192  }
  1193  
  1194  func getString(trie *Trie, k string) []byte {
  1195  	return trie.MustGet([]byte(k))
  1196  }
  1197  
  1198  func updateString(trie *Trie, k, v string) {
  1199  	trie.MustUpdate([]byte(k), []byte(v))
  1200  }
  1201  
  1202  func deleteString(trie *Trie, k string) {
  1203  	trie.MustDelete([]byte(k))
  1204  }
  1205  
  1206  func TestDecodeNode(t *testing.T) {
  1207  	t.Parallel()
  1208  
  1209  	var (
  1210  		hash  = make([]byte, 20)
  1211  		elems = make([]byte, 20)
  1212  	)
  1213  	for i := 0; i < 5000000; i++ {
  1214  		prng.Read(hash)
  1215  		prng.Read(elems)
  1216  		decodeNode(hash, elems)
  1217  	}
  1218  }
  1219  
  1220  func FuzzTrie(f *testing.F) {
  1221  	f.Fuzz(func(t *testing.T, data []byte) {
  1222  		var steps = 500
  1223  		var input = bytes.NewReader(data)
  1224  		var finishedFn = func() bool {
  1225  			steps--
  1226  			return steps < 0 || input.Len() == 0
  1227  		}
  1228  		if err := runRandTest(generateSteps(finishedFn, input)); err != nil {
  1229  			t.Fatal(err)
  1230  		}
  1231  	})
  1232  }
  1233  
  1234  func BenchmarkCommit(b *testing.B) {
  1235  	benchmarkCommit(b, 100)
  1236  	benchmarkCommit(b, 500)
  1237  	benchmarkCommit(b, 2000)
  1238  	benchmarkCommit(b, 5000)
  1239  }
  1240  
  1241  func benchmarkCommit(b *testing.B, n int) {
  1242  	b.Run(fmt.Sprintf("commit-%vnodes-sequential", n), func(b *testing.B) {
  1243  		testCommit(b, n, false)
  1244  	})
  1245  	b.Run(fmt.Sprintf("commit-%vnodes-parallel", n), func(b *testing.B) {
  1246  		testCommit(b, n, true)
  1247  	})
  1248  }
  1249  
  1250  func testCommit(b *testing.B, n int, parallel bool) {
  1251  	tries := make([]*Trie, b.N)
  1252  	for i := 0; i < b.N; i++ {
  1253  		tries[i] = NewEmpty(nil)
  1254  		for j := 0; j < n; j++ {
  1255  			key := testrand.Bytes(32)
  1256  			val := testrand.Bytes(32)
  1257  			tries[i].Update(key, val)
  1258  		}
  1259  		tries[i].Hash()
  1260  		if !parallel {
  1261  			tries[i].uncommitted = 0
  1262  		}
  1263  	}
  1264  	b.ResetTimer()
  1265  	b.ReportAllocs()
  1266  	for i := 0; i < len(tries); i++ {
  1267  		tries[i].Commit(true)
  1268  	}
  1269  }
  1270  
  1271  func TestCommitCorrect(t *testing.T) {
  1272  	var paraTrie = NewEmpty(nil)
  1273  	var refTrie = NewEmpty(nil)
  1274  
  1275  	for j := 0; j < 5000; j++ {
  1276  		key := testrand.Bytes(32)
  1277  		val := testrand.Bytes(32)
  1278  		paraTrie.Update(key, val)
  1279  		refTrie.Update(common.CopyBytes(key), common.CopyBytes(val))
  1280  	}
  1281  	paraTrie.Hash()
  1282  	refTrie.Hash()
  1283  	refTrie.uncommitted = 0
  1284  
  1285  	haveRoot, haveNodes := paraTrie.Commit(true)
  1286  	wantRoot, wantNodes := refTrie.Commit(true)
  1287  
  1288  	if haveRoot != wantRoot {
  1289  		t.Fatalf("have %x want %x", haveRoot, wantRoot)
  1290  	}
  1291  	have := printSet(haveNodes)
  1292  	want := printSet(wantNodes)
  1293  	if have != want {
  1294  		i := 0
  1295  		for i = 0; i < len(have); i++ {
  1296  			if have[i] != want[i] {
  1297  				break
  1298  			}
  1299  		}
  1300  		if i > 100 {
  1301  			i -= 100
  1302  		}
  1303  		t.Fatalf("have != want\nhave %q\nwant %q", have[i:], want[i:])
  1304  	}
  1305  }
  1306  func printSet(set *trienode.NodeSet) string {
  1307  	var out = new(strings.Builder)
  1308  	fmt.Fprintf(out, "nodeset owner: %v\n", set.Owner)
  1309  	var paths []string
  1310  	for k := range set.Nodes {
  1311  		paths = append(paths, k)
  1312  	}
  1313  	sort.Strings(paths)
  1314  
  1315  	for _, path := range paths {
  1316  		n := set.Nodes[path]
  1317  		// Deletion
  1318  		if n.IsDeleted() {
  1319  			fmt.Fprintf(out, "  [-]: %x\n", path)
  1320  			continue
  1321  		}
  1322  		// Insertion or update
  1323  		fmt.Fprintf(out, "  [+/*]: %x -> %v \n", path, n.Hash)
  1324  	}
  1325  	sort.Slice(set.Leaves, func(i, j int) bool {
  1326  		a := set.Leaves[i]
  1327  		b := set.Leaves[j]
  1328  		return bytes.Compare(a.Parent[:], b.Parent[:]) < 0
  1329  	})
  1330  	for _, n := range set.Leaves {
  1331  		fmt.Fprintf(out, "[leaf]: %v\n", n)
  1332  	}
  1333  	return out.String()
  1334  }
  1335  
  1336  func TestTrieCopy(t *testing.T) {
  1337  	testTrieCopy(t, []kv{
  1338  		{k: []byte("do"), v: []byte("verb")},
  1339  		{k: []byte("ether"), v: []byte("wookiedoo")},
  1340  		{k: []byte("horse"), v: []byte("stallion")},
  1341  		{k: []byte("shaman"), v: []byte("horse")},
  1342  		{k: []byte("doge"), v: []byte("coin")},
  1343  		{k: []byte("dog"), v: []byte("puppy")},
  1344  	})
  1345  
  1346  	var entries []kv
  1347  	for i := 0; i < 256; i++ {
  1348  		entries = append(entries, kv{k: testrand.Bytes(32), v: testrand.Bytes(32)})
  1349  	}
  1350  	testTrieCopy(t, entries)
  1351  }
  1352  
  1353  func testTrieCopy(t *testing.T, entries []kv) {
  1354  	tr := NewEmpty(nil)
  1355  	for _, entry := range entries {
  1356  		tr.Update(entry.k, entry.v)
  1357  	}
  1358  	trCpy := tr.Copy()
  1359  
  1360  	if tr.Hash() != trCpy.Hash() {
  1361  		t.Errorf("Hash mismatch: old %v, copy %v", tr.Hash(), trCpy.Hash())
  1362  	}
  1363  
  1364  	// Check iterator
  1365  	it, _ := tr.NodeIterator(nil)
  1366  	itCpy, _ := trCpy.NodeIterator(nil)
  1367  
  1368  	for it.Next(false) {
  1369  		hasNext := itCpy.Next(false)
  1370  		if !hasNext {
  1371  			t.Fatal("Iterator is not matched")
  1372  		}
  1373  		if !bytes.Equal(it.Path(), itCpy.Path()) {
  1374  			t.Fatal("Iterator is not matched")
  1375  		}
  1376  		if it.Leaf() != itCpy.Leaf() {
  1377  			t.Fatal("Iterator is not matched")
  1378  		}
  1379  		if it.Leaf() && !bytes.Equal(it.LeafBlob(), itCpy.LeafBlob()) {
  1380  			t.Fatal("Iterator is not matched")
  1381  		}
  1382  	}
  1383  
  1384  	// Check commit
  1385  	root, nodes := tr.Commit(false)
  1386  	rootCpy, nodesCpy := trCpy.Commit(false)
  1387  	if root != rootCpy {
  1388  		t.Fatal("root mismatch")
  1389  	}
  1390  	if len(nodes.Nodes) != len(nodesCpy.Nodes) {
  1391  		t.Fatal("commit node mismatch")
  1392  	}
  1393  	for p, n := range nodes.Nodes {
  1394  		nn, exists := nodesCpy.Nodes[p]
  1395  		if !exists {
  1396  			t.Fatalf("node not exists: %v", p)
  1397  		}
  1398  		if !reflect.DeepEqual(n, nn) {
  1399  			t.Fatalf("node mismatch: %v", p)
  1400  		}
  1401  	}
  1402  }
  1403  
  1404  func TestTrieCopyOldTrie(t *testing.T) {
  1405  	testTrieCopyOldTrie(t, []kv{
  1406  		{k: []byte("do"), v: []byte("verb")},
  1407  		{k: []byte("ether"), v: []byte("wookiedoo")},
  1408  		{k: []byte("horse"), v: []byte("stallion")},
  1409  		{k: []byte("shaman"), v: []byte("horse")},
  1410  		{k: []byte("doge"), v: []byte("coin")},
  1411  		{k: []byte("dog"), v: []byte("puppy")},
  1412  	})
  1413  
  1414  	var entries []kv
  1415  	for i := 0; i < 256; i++ {
  1416  		entries = append(entries, kv{k: testrand.Bytes(32), v: testrand.Bytes(32)})
  1417  	}
  1418  	testTrieCopyOldTrie(t, entries)
  1419  }
  1420  
  1421  func testTrieCopyOldTrie(t *testing.T, entries []kv) {
  1422  	tr := NewEmpty(nil)
  1423  	for _, entry := range entries {
  1424  		tr.Update(entry.k, entry.v)
  1425  	}
  1426  	hash := tr.Hash()
  1427  
  1428  	trCpy := tr.Copy()
  1429  	for _, val := range entries {
  1430  		if rand.Intn(2) == 0 {
  1431  			trCpy.Delete(val.k)
  1432  		} else {
  1433  			trCpy.Update(val.k, testrand.Bytes(32))
  1434  		}
  1435  	}
  1436  	for i := 0; i < 10; i++ {
  1437  		trCpy.Update(testrand.Bytes(32), testrand.Bytes(32))
  1438  	}
  1439  	trCpy.Hash()
  1440  	trCpy.Commit(false)
  1441  
  1442  	// Traverse the original tree, the changes made on the copy one shouldn't
  1443  	// affect the old one
  1444  	for _, entry := range entries {
  1445  		d, _ := tr.Get(entry.k)
  1446  		if !bytes.Equal(d, entry.v) {
  1447  			t.Errorf("Unexpected data, key: %v, want: %v, got: %v", entry.k, entry.v, d)
  1448  		}
  1449  	}
  1450  	if tr.Hash() != hash {
  1451  		t.Errorf("Hash mismatch: old %v, new %v", hash, tr.Hash())
  1452  	}
  1453  }
  1454  
  1455  func TestTrieCopyNewTrie(t *testing.T) {
  1456  	testTrieCopyNewTrie(t, []kv{
  1457  		{k: []byte("do"), v: []byte("verb")},
  1458  		{k: []byte("ether"), v: []byte("wookiedoo")},
  1459  		{k: []byte("horse"), v: []byte("stallion")},
  1460  		{k: []byte("shaman"), v: []byte("horse")},
  1461  		{k: []byte("doge"), v: []byte("coin")},
  1462  		{k: []byte("dog"), v: []byte("puppy")},
  1463  	})
  1464  
  1465  	var entries []kv
  1466  	for i := 0; i < 256; i++ {
  1467  		entries = append(entries, kv{k: testrand.Bytes(32), v: testrand.Bytes(32)})
  1468  	}
  1469  	testTrieCopyNewTrie(t, entries)
  1470  }
  1471  
  1472  func testTrieCopyNewTrie(t *testing.T, entries []kv) {
  1473  	tr := NewEmpty(nil)
  1474  	for _, entry := range entries {
  1475  		tr.Update(entry.k, entry.v)
  1476  	}
  1477  	trCpy := tr.Copy()
  1478  	hash := trCpy.Hash()
  1479  
  1480  	for _, val := range entries {
  1481  		if rand.Intn(2) == 0 {
  1482  			tr.Delete(val.k)
  1483  		} else {
  1484  			tr.Update(val.k, testrand.Bytes(32))
  1485  		}
  1486  	}
  1487  	for i := 0; i < 10; i++ {
  1488  		tr.Update(testrand.Bytes(32), testrand.Bytes(32))
  1489  	}
  1490  
  1491  	// Traverse the original tree, the changes made on the copy one shouldn't
  1492  	// affect the old one
  1493  	for _, entry := range entries {
  1494  		d, _ := trCpy.Get(entry.k)
  1495  		if !bytes.Equal(d, entry.v) {
  1496  			t.Errorf("Unexpected data, key: %v, want: %v, got: %v", entry.k, entry.v, d)
  1497  		}
  1498  	}
  1499  	if trCpy.Hash() != hash {
  1500  		t.Errorf("Hash mismatch: old %v, new %v", hash, tr.Hash())
  1501  	}
  1502  }