github.com/zhiqiangxu/go-ethereum@v1.9.16-0.20210824055606-be91cfdebc48/trie/proof_test.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package trie
    18  
    19  import (
    20  	"bytes"
    21  	crand "crypto/rand"
    22  	mrand "math/rand"
    23  	"sort"
    24  	"testing"
    25  	"time"
    26  
    27  	"github.com/zhiqiangxu/go-ethereum/common"
    28  	"github.com/zhiqiangxu/go-ethereum/crypto"
    29  	"github.com/zhiqiangxu/go-ethereum/ethdb/memorydb"
    30  )
    31  
    32  func init() {
    33  	mrand.Seed(time.Now().Unix())
    34  }
    35  
    36  // makeProvers creates Merkle trie provers based on different implementations to
    37  // test all variations.
    38  func makeProvers(trie *Trie) []func(key []byte) *memorydb.Database {
    39  	var provers []func(key []byte) *memorydb.Database
    40  
    41  	// Create a direct trie based Merkle prover
    42  	provers = append(provers, func(key []byte) *memorydb.Database {
    43  		proof := memorydb.New()
    44  		trie.Prove(key, 0, proof)
    45  		return proof
    46  	})
    47  	// Create a leaf iterator based Merkle prover
    48  	provers = append(provers, func(key []byte) *memorydb.Database {
    49  		proof := memorydb.New()
    50  		if it := NewIterator(trie.NodeIterator(key)); it.Next() && bytes.Equal(key, it.Key) {
    51  			for _, p := range it.Prove() {
    52  				proof.Put(crypto.Keccak256(p), p)
    53  			}
    54  		}
    55  		return proof
    56  	})
    57  	return provers
    58  }
    59  
    60  func TestProof(t *testing.T) {
    61  	trie, vals := randomTrie(500)
    62  	root := trie.Hash()
    63  	for i, prover := range makeProvers(trie) {
    64  		for _, kv := range vals {
    65  			proof := prover(kv.k)
    66  			if proof == nil {
    67  				t.Fatalf("prover %d: missing key %x while constructing proof", i, kv.k)
    68  			}
    69  			val, err := VerifyProof(root, kv.k, proof)
    70  			if err != nil {
    71  				t.Fatalf("prover %d: failed to verify proof for key %x: %v\nraw proof: %x", i, kv.k, err, proof)
    72  			}
    73  			if !bytes.Equal(val, kv.v) {
    74  				t.Fatalf("prover %d: verified value mismatch for key %x: have %x, want %x", i, kv.k, val, kv.v)
    75  			}
    76  		}
    77  	}
    78  }
    79  
    80  func TestOneElementProof(t *testing.T) {
    81  	trie := new(Trie)
    82  	updateString(trie, "k", "v")
    83  	for i, prover := range makeProvers(trie) {
    84  		proof := prover([]byte("k"))
    85  		if proof == nil {
    86  			t.Fatalf("prover %d: nil proof", i)
    87  		}
    88  		if proof.Len() != 1 {
    89  			t.Errorf("prover %d: proof should have one element", i)
    90  		}
    91  		val, err := VerifyProof(trie.Hash(), []byte("k"), proof)
    92  		if err != nil {
    93  			t.Fatalf("prover %d: failed to verify proof: %v\nraw proof: %x", i, err, proof)
    94  		}
    95  		if !bytes.Equal(val, []byte("v")) {
    96  			t.Fatalf("prover %d: verified value mismatch: have %x, want 'k'", i, val)
    97  		}
    98  	}
    99  }
   100  
   101  func TestBadProof(t *testing.T) {
   102  	trie, vals := randomTrie(800)
   103  	root := trie.Hash()
   104  	for i, prover := range makeProvers(trie) {
   105  		for _, kv := range vals {
   106  			proof := prover(kv.k)
   107  			if proof == nil {
   108  				t.Fatalf("prover %d: nil proof", i)
   109  			}
   110  			it := proof.NewIterator(nil, nil)
   111  			for i, d := 0, mrand.Intn(proof.Len()); i <= d; i++ {
   112  				it.Next()
   113  			}
   114  			key := it.Key()
   115  			val, _ := proof.Get(key)
   116  			proof.Delete(key)
   117  			it.Release()
   118  
   119  			mutateByte(val)
   120  			proof.Put(crypto.Keccak256(val), val)
   121  
   122  			if _, err := VerifyProof(root, kv.k, proof); err == nil {
   123  				t.Fatalf("prover %d: expected proof to fail for key %x", i, kv.k)
   124  			}
   125  		}
   126  	}
   127  }
   128  
   129  // Tests that missing keys can also be proven. The test explicitly uses a single
   130  // entry trie and checks for missing keys both before and after the single entry.
   131  func TestMissingKeyProof(t *testing.T) {
   132  	trie := new(Trie)
   133  	updateString(trie, "k", "v")
   134  
   135  	for i, key := range []string{"a", "j", "l", "z"} {
   136  		proof := memorydb.New()
   137  		trie.Prove([]byte(key), 0, proof)
   138  
   139  		if proof.Len() != 1 {
   140  			t.Errorf("test %d: proof should have one element", i)
   141  		}
   142  		val, err := VerifyProof(trie.Hash(), []byte(key), proof)
   143  		if err != nil {
   144  			t.Fatalf("test %d: failed to verify proof: %v\nraw proof: %x", i, err, proof)
   145  		}
   146  		if val != nil {
   147  			t.Fatalf("test %d: verified value mismatch: have %x, want nil", i, val)
   148  		}
   149  	}
   150  }
   151  
   152  type entrySlice []*kv
   153  
   154  func (p entrySlice) Len() int           { return len(p) }
   155  func (p entrySlice) Less(i, j int) bool { return bytes.Compare(p[i].k, p[j].k) < 0 }
   156  func (p entrySlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
   157  
   158  // TestRangeProof tests normal range proof with both edge proofs
   159  // as the existent proof. The test cases are generated randomly.
   160  func TestRangeProof(t *testing.T) {
   161  	trie, vals := randomTrie(4096)
   162  	var entries entrySlice
   163  	for _, kv := range vals {
   164  		entries = append(entries, kv)
   165  	}
   166  	sort.Sort(entries)
   167  	for i := 0; i < 500; i++ {
   168  		start := mrand.Intn(len(entries))
   169  		end := mrand.Intn(len(entries)-start) + start
   170  		if start == end {
   171  			continue
   172  		}
   173  		firstProof, lastProof := memorydb.New(), memorydb.New()
   174  		if err := trie.Prove(entries[start].k, 0, firstProof); err != nil {
   175  			t.Fatalf("Failed to prove the first node %v", err)
   176  		}
   177  		if err := trie.Prove(entries[end-1].k, 0, lastProof); err != nil {
   178  			t.Fatalf("Failed to prove the last node %v", err)
   179  		}
   180  		var keys [][]byte
   181  		var vals [][]byte
   182  		for i := start; i < end; i++ {
   183  			keys = append(keys, entries[i].k)
   184  			vals = append(vals, entries[i].v)
   185  		}
   186  		err, _ := VerifyRangeProof(trie.Hash(), keys[0], keys, vals, firstProof, lastProof)
   187  		if err != nil {
   188  			t.Fatalf("Case %d(%d->%d) expect no error, got %v", i, start, end-1, err)
   189  		}
   190  	}
   191  }
   192  
   193  // TestRangeProof tests normal range proof with the first edge proof
   194  // as the non-existent proof. The test cases are generated randomly.
   195  func TestRangeProofWithNonExistentProof(t *testing.T) {
   196  	trie, vals := randomTrie(4096)
   197  	var entries entrySlice
   198  	for _, kv := range vals {
   199  		entries = append(entries, kv)
   200  	}
   201  	sort.Sort(entries)
   202  	for i := 0; i < 500; i++ {
   203  		start := mrand.Intn(len(entries))
   204  		end := mrand.Intn(len(entries)-start) + start
   205  		if start == end {
   206  			continue
   207  		}
   208  		firstProof, lastProof := memorydb.New(), memorydb.New()
   209  
   210  		first := decreseKey(common.CopyBytes(entries[start].k))
   211  		if start != 0 && bytes.Equal(first, entries[start-1].k) {
   212  			continue
   213  		}
   214  		if err := trie.Prove(first, 0, firstProof); err != nil {
   215  			t.Fatalf("Failed to prove the first node %v", err)
   216  		}
   217  		if err := trie.Prove(entries[end-1].k, 0, lastProof); err != nil {
   218  			t.Fatalf("Failed to prove the last node %v", err)
   219  		}
   220  		var keys [][]byte
   221  		var vals [][]byte
   222  		for i := start; i < end; i++ {
   223  			keys = append(keys, entries[i].k)
   224  			vals = append(vals, entries[i].v)
   225  		}
   226  		err, _ := VerifyRangeProof(trie.Hash(), first, keys, vals, firstProof, lastProof)
   227  		if err != nil {
   228  			t.Fatalf("Case %d(%d->%d) expect no error, got %v", i, start, end-1, err)
   229  		}
   230  	}
   231  }
   232  
   233  // TestRangeProofWithInvalidNonExistentProof tests such scenarios:
   234  // - The last edge proof is an non-existent proof
   235  // - There exists a gap between the first element and the left edge proof
   236  func TestRangeProofWithInvalidNonExistentProof(t *testing.T) {
   237  	trie, vals := randomTrie(4096)
   238  	var entries entrySlice
   239  	for _, kv := range vals {
   240  		entries = append(entries, kv)
   241  	}
   242  	sort.Sort(entries)
   243  
   244  	// Case 1
   245  	start, end := 100, 200
   246  	first, last := decreseKey(common.CopyBytes(entries[start].k)), increseKey(common.CopyBytes(entries[end].k))
   247  	firstProof, lastProof := memorydb.New(), memorydb.New()
   248  	if err := trie.Prove(first, 0, firstProof); err != nil {
   249  		t.Fatalf("Failed to prove the first node %v", err)
   250  	}
   251  	if err := trie.Prove(last, 0, lastProof); err != nil {
   252  		t.Fatalf("Failed to prove the last node %v", err)
   253  	}
   254  	var k [][]byte
   255  	var v [][]byte
   256  	for i := start; i < end; i++ {
   257  		k = append(k, entries[i].k)
   258  		v = append(v, entries[i].v)
   259  	}
   260  	err, _ := VerifyRangeProof(trie.Hash(), first, k, v, firstProof, lastProof)
   261  	if err == nil {
   262  		t.Fatalf("Expected to detect the error, got nil")
   263  	}
   264  
   265  	// Case 2
   266  	start, end = 100, 200
   267  	first = decreseKey(common.CopyBytes(entries[start].k))
   268  
   269  	firstProof, lastProof = memorydb.New(), memorydb.New()
   270  	if err := trie.Prove(first, 0, firstProof); err != nil {
   271  		t.Fatalf("Failed to prove the first node %v", err)
   272  	}
   273  	if err := trie.Prove(entries[end-1].k, 0, lastProof); err != nil {
   274  		t.Fatalf("Failed to prove the last node %v", err)
   275  	}
   276  	start = 105 // Gap created
   277  	k = make([][]byte, 0)
   278  	v = make([][]byte, 0)
   279  	for i := start; i < end; i++ {
   280  		k = append(k, entries[i].k)
   281  		v = append(v, entries[i].v)
   282  	}
   283  	err, _ = VerifyRangeProof(trie.Hash(), first, k, v, firstProof, lastProof)
   284  	if err == nil {
   285  		t.Fatalf("Expected to detect the error, got nil")
   286  	}
   287  }
   288  
   289  // TestOneElementRangeProof tests the proof with only one
   290  // element. The first edge proof can be existent one or
   291  // non-existent one.
   292  func TestOneElementRangeProof(t *testing.T) {
   293  	trie, vals := randomTrie(4096)
   294  	var entries entrySlice
   295  	for _, kv := range vals {
   296  		entries = append(entries, kv)
   297  	}
   298  	sort.Sort(entries)
   299  
   300  	// One element with existent edge proof
   301  	start := 1000
   302  	firstProof, lastProof := memorydb.New(), memorydb.New()
   303  	if err := trie.Prove(entries[start].k, 0, firstProof); err != nil {
   304  		t.Fatalf("Failed to prove the first node %v", err)
   305  	}
   306  	if err := trie.Prove(entries[start].k, 0, lastProof); err != nil {
   307  		t.Fatalf("Failed to prove the last node %v", err)
   308  	}
   309  	err, _ := VerifyRangeProof(trie.Hash(), entries[start].k, [][]byte{entries[start].k}, [][]byte{entries[start].v}, firstProof, lastProof)
   310  	if err != nil {
   311  		t.Fatalf("Expected no error, got %v", err)
   312  	}
   313  
   314  	// One element with non-existent edge proof
   315  	start = 1000
   316  	first := decreseKey(common.CopyBytes(entries[start].k))
   317  	firstProof, lastProof = memorydb.New(), memorydb.New()
   318  	if err := trie.Prove(first, 0, firstProof); err != nil {
   319  		t.Fatalf("Failed to prove the first node %v", err)
   320  	}
   321  	if err := trie.Prove(entries[start].k, 0, lastProof); err != nil {
   322  		t.Fatalf("Failed to prove the last node %v", err)
   323  	}
   324  	err, _ = VerifyRangeProof(trie.Hash(), first, [][]byte{entries[start].k}, [][]byte{entries[start].v}, firstProof, lastProof)
   325  	if err != nil {
   326  		t.Fatalf("Expected no error, got %v", err)
   327  	}
   328  }
   329  
   330  // TestAllElementsProof tests the range proof with all elements.
   331  // The edge proofs can be nil.
   332  func TestAllElementsProof(t *testing.T) {
   333  	trie, vals := randomTrie(4096)
   334  	var entries entrySlice
   335  	for _, kv := range vals {
   336  		entries = append(entries, kv)
   337  	}
   338  	sort.Sort(entries)
   339  
   340  	var k [][]byte
   341  	var v [][]byte
   342  	for i := 0; i < len(entries); i++ {
   343  		k = append(k, entries[i].k)
   344  		v = append(v, entries[i].v)
   345  	}
   346  	err, _ := VerifyRangeProof(trie.Hash(), k[0], k, v, nil, nil)
   347  	if err != nil {
   348  		t.Fatalf("Expected no error, got %v", err)
   349  	}
   350  
   351  	// Even with edge proofs, it should still work.
   352  	firstProof, lastProof := memorydb.New(), memorydb.New()
   353  	if err := trie.Prove(entries[0].k, 0, firstProof); err != nil {
   354  		t.Fatalf("Failed to prove the first node %v", err)
   355  	}
   356  	if err := trie.Prove(entries[len(entries)-1].k, 0, lastProof); err != nil {
   357  		t.Fatalf("Failed to prove the last node %v", err)
   358  	}
   359  	err, _ = VerifyRangeProof(trie.Hash(), k[0], k, v, firstProof, lastProof)
   360  	if err != nil {
   361  		t.Fatalf("Expected no error, got %v", err)
   362  	}
   363  }
   364  
   365  // TestSingleSideRangeProof tests the range starts from zero.
   366  func TestSingleSideRangeProof(t *testing.T) {
   367  	for i := 0; i < 64; i++ {
   368  		trie := new(Trie)
   369  		var entries entrySlice
   370  		for i := 0; i < 4096; i++ {
   371  			value := &kv{randBytes(32), randBytes(20), false}
   372  			trie.Update(value.k, value.v)
   373  			entries = append(entries, value)
   374  		}
   375  		sort.Sort(entries)
   376  
   377  		var cases = []int{0, 1, 50, 100, 1000, 2000, len(entries) - 1}
   378  		for _, pos := range cases {
   379  			firstProof, lastProof := memorydb.New(), memorydb.New()
   380  			if err := trie.Prove(common.Hash{}.Bytes(), 0, firstProof); err != nil {
   381  				t.Fatalf("Failed to prove the first node %v", err)
   382  			}
   383  			if err := trie.Prove(entries[pos].k, 0, lastProof); err != nil {
   384  				t.Fatalf("Failed to prove the first node %v", err)
   385  			}
   386  			k := make([][]byte, 0)
   387  			v := make([][]byte, 0)
   388  			for i := 0; i <= pos; i++ {
   389  				k = append(k, entries[i].k)
   390  				v = append(v, entries[i].v)
   391  			}
   392  			err, _ := VerifyRangeProof(trie.Hash(), common.Hash{}.Bytes(), k, v, firstProof, lastProof)
   393  			if err != nil {
   394  				t.Fatalf("Expected no error, got %v", err)
   395  			}
   396  		}
   397  	}
   398  }
   399  
   400  // TestBadRangeProof tests a few cases which the proof is wrong.
   401  // The prover is expected to detect the error.
   402  func TestBadRangeProof(t *testing.T) {
   403  	trie, vals := randomTrie(4096)
   404  	var entries entrySlice
   405  	for _, kv := range vals {
   406  		entries = append(entries, kv)
   407  	}
   408  	sort.Sort(entries)
   409  
   410  	for i := 0; i < 500; i++ {
   411  		start := mrand.Intn(len(entries))
   412  		end := mrand.Intn(len(entries)-start) + start
   413  		if start == end {
   414  			continue
   415  		}
   416  		firstProof, lastProof := memorydb.New(), memorydb.New()
   417  		if err := trie.Prove(entries[start].k, 0, firstProof); err != nil {
   418  			t.Fatalf("Failed to prove the first node %v", err)
   419  		}
   420  		if err := trie.Prove(entries[end-1].k, 0, lastProof); err != nil {
   421  			t.Fatalf("Failed to prove the last node %v", err)
   422  		}
   423  		var keys [][]byte
   424  		var vals [][]byte
   425  		for i := start; i < end; i++ {
   426  			keys = append(keys, entries[i].k)
   427  			vals = append(vals, entries[i].v)
   428  		}
   429  		testcase := mrand.Intn(6)
   430  		var index int
   431  		switch testcase {
   432  		case 0:
   433  			// Modified key
   434  			index = mrand.Intn(end - start)
   435  			keys[index] = randBytes(32) // In theory it can't be same
   436  		case 1:
   437  			// Modified val
   438  			index = mrand.Intn(end - start)
   439  			vals[index] = randBytes(20) // In theory it can't be same
   440  		case 2:
   441  			// Gapped entry slice
   442  
   443  			// There are only two elements, skip it. Dropped any element
   444  			// will lead to single edge proof which is always correct.
   445  			if end-start <= 2 {
   446  				continue
   447  			}
   448  			// If the dropped element is the first or last one and it's a
   449  			// batch of small size elements. In this special case, it can
   450  			// happen that the proof for the edge element is exactly same
   451  			// with the first/last second element(since small values are
   452  			// embedded in the parent). Avoid this case.
   453  			index = mrand.Intn(end - start)
   454  			if (index == end-start-1 || index == 0) && end <= 100 {
   455  				continue
   456  			}
   457  			keys = append(keys[:index], keys[index+1:]...)
   458  			vals = append(vals[:index], vals[index+1:]...)
   459  		case 3:
   460  			// Switched entry slice, same effect with gapped
   461  			index = mrand.Intn(end - start)
   462  			keys[index] = entries[len(entries)-1].k
   463  			vals[index] = entries[len(entries)-1].v
   464  		case 4:
   465  			// Set random key to nil
   466  			index = mrand.Intn(end - start)
   467  			keys[index] = nil
   468  		case 5:
   469  			// Set random value to nil
   470  			index = mrand.Intn(end - start)
   471  			vals[index] = nil
   472  		}
   473  		err, _ := VerifyRangeProof(trie.Hash(), keys[0], keys, vals, firstProof, lastProof)
   474  		if err == nil {
   475  			t.Fatalf("%d Case %d index %d range: (%d->%d) expect error, got nil", i, testcase, index, start, end-1)
   476  		}
   477  	}
   478  }
   479  
   480  // TestGappedRangeProof focuses on the small trie with embedded nodes.
   481  // If the gapped node is embedded in the trie, it should be detected too.
   482  func TestGappedRangeProof(t *testing.T) {
   483  	trie := new(Trie)
   484  	var entries []*kv // Sorted entries
   485  	for i := byte(0); i < 10; i++ {
   486  		value := &kv{common.LeftPadBytes([]byte{i}, 32), []byte{i}, false}
   487  		trie.Update(value.k, value.v)
   488  		entries = append(entries, value)
   489  	}
   490  	first, last := 2, 8
   491  	firstProof, lastProof := memorydb.New(), memorydb.New()
   492  	if err := trie.Prove(entries[first].k, 0, firstProof); err != nil {
   493  		t.Fatalf("Failed to prove the first node %v", err)
   494  	}
   495  	if err := trie.Prove(entries[last-1].k, 0, lastProof); err != nil {
   496  		t.Fatalf("Failed to prove the last node %v", err)
   497  	}
   498  	var keys [][]byte
   499  	var vals [][]byte
   500  	for i := first; i < last; i++ {
   501  		if i == (first+last)/2 {
   502  			continue
   503  		}
   504  		keys = append(keys, entries[i].k)
   505  		vals = append(vals, entries[i].v)
   506  	}
   507  	err, _ := VerifyRangeProof(trie.Hash(), keys[0], keys, vals, firstProof, lastProof)
   508  	if err == nil {
   509  		t.Fatal("expect error, got nil")
   510  	}
   511  }
   512  
   513  func TestHasRightElement(t *testing.T) {
   514  	trie := new(Trie)
   515  	var entries entrySlice
   516  	for i := 0; i < 4096; i++ {
   517  		value := &kv{randBytes(32), randBytes(20), false}
   518  		trie.Update(value.k, value.v)
   519  		entries = append(entries, value)
   520  	}
   521  	sort.Sort(entries)
   522  
   523  	var cases = []struct {
   524  		start   int
   525  		end     int
   526  		hasMore bool
   527  	}{
   528  		{-1, 1, true}, // single element with non-existent left proof
   529  		{0, 1, true},  // single element with existent left proof
   530  		{0, 10, true},
   531  		{50, 100, true},
   532  		{50, len(entries), false},               // No more element expected
   533  		{len(entries) - 1, len(entries), false}, // Single last element
   534  		{0, len(entries), false},                // The whole set with existent left proof
   535  		{-1, len(entries), false},               // The whole set with non-existent left proof
   536  	}
   537  	for _, c := range cases {
   538  		var (
   539  			firstKey   []byte
   540  			start      = c.start
   541  			firstProof = memorydb.New()
   542  			lastProof  = memorydb.New()
   543  		)
   544  		if c.start == -1 {
   545  			firstKey, start = common.Hash{}.Bytes(), 0
   546  			if err := trie.Prove(firstKey, 0, firstProof); err != nil {
   547  				t.Fatalf("Failed to prove the first node %v", err)
   548  			}
   549  		} else {
   550  			firstKey = entries[c.start].k
   551  			if err := trie.Prove(entries[c.start].k, 0, firstProof); err != nil {
   552  				t.Fatalf("Failed to prove the first node %v", err)
   553  			}
   554  		}
   555  		if err := trie.Prove(entries[c.end-1].k, 0, lastProof); err != nil {
   556  			t.Fatalf("Failed to prove the first node %v", err)
   557  		}
   558  		k := make([][]byte, 0)
   559  		v := make([][]byte, 0)
   560  		for i := start; i < c.end; i++ {
   561  			k = append(k, entries[i].k)
   562  			v = append(v, entries[i].v)
   563  		}
   564  		err, hasMore := VerifyRangeProof(trie.Hash(), firstKey, k, v, firstProof, lastProof)
   565  		if err != nil {
   566  			t.Fatalf("Expected no error, got %v", err)
   567  		}
   568  		if hasMore != c.hasMore {
   569  			t.Fatalf("Wrong hasMore indicator, want %t, got %t", c.hasMore, hasMore)
   570  		}
   571  	}
   572  }
   573  
   574  // mutateByte changes one byte in b.
   575  func mutateByte(b []byte) {
   576  	for r := mrand.Intn(len(b)); ; {
   577  		new := byte(mrand.Intn(255))
   578  		if new != b[r] {
   579  			b[r] = new
   580  			break
   581  		}
   582  	}
   583  }
   584  
   585  func increseKey(key []byte) []byte {
   586  	for i := len(key) - 1; i >= 0; i-- {
   587  		key[i]++
   588  		if key[i] != 0x0 {
   589  			break
   590  		}
   591  	}
   592  	return key
   593  }
   594  
   595  func decreseKey(key []byte) []byte {
   596  	for i := len(key) - 1; i >= 0; i-- {
   597  		key[i]--
   598  		if key[i] != 0xff {
   599  			break
   600  		}
   601  	}
   602  	return key
   603  }
   604  
   605  func BenchmarkProve(b *testing.B) {
   606  	trie, vals := randomTrie(100)
   607  	var keys []string
   608  	for k := range vals {
   609  		keys = append(keys, k)
   610  	}
   611  
   612  	b.ResetTimer()
   613  	for i := 0; i < b.N; i++ {
   614  		kv := vals[keys[i%len(keys)]]
   615  		proofs := memorydb.New()
   616  		if trie.Prove(kv.k, 0, proofs); proofs.Len() == 0 {
   617  			b.Fatalf("zero length proof for %x", kv.k)
   618  		}
   619  	}
   620  }
   621  
   622  func BenchmarkVerifyProof(b *testing.B) {
   623  	trie, vals := randomTrie(100)
   624  	root := trie.Hash()
   625  	var keys []string
   626  	var proofs []*memorydb.Database
   627  	for k := range vals {
   628  		keys = append(keys, k)
   629  		proof := memorydb.New()
   630  		trie.Prove([]byte(k), 0, proof)
   631  		proofs = append(proofs, proof)
   632  	}
   633  
   634  	b.ResetTimer()
   635  	for i := 0; i < b.N; i++ {
   636  		im := i % len(keys)
   637  		if _, err := VerifyProof(root, []byte(keys[im]), proofs[im]); err != nil {
   638  			b.Fatalf("key %x: %v", keys[im], err)
   639  		}
   640  	}
   641  }
   642  
   643  func BenchmarkVerifyRangeProof10(b *testing.B)   { benchmarkVerifyRangeProof(b, 10) }
   644  func BenchmarkVerifyRangeProof100(b *testing.B)  { benchmarkVerifyRangeProof(b, 100) }
   645  func BenchmarkVerifyRangeProof1000(b *testing.B) { benchmarkVerifyRangeProof(b, 1000) }
   646  func BenchmarkVerifyRangeProof5000(b *testing.B) { benchmarkVerifyRangeProof(b, 5000) }
   647  
   648  func benchmarkVerifyRangeProof(b *testing.B, size int) {
   649  	trie, vals := randomTrie(8192)
   650  	var entries entrySlice
   651  	for _, kv := range vals {
   652  		entries = append(entries, kv)
   653  	}
   654  	sort.Sort(entries)
   655  
   656  	start := 2
   657  	end := start + size
   658  	firstProof, lastProof := memorydb.New(), memorydb.New()
   659  	if err := trie.Prove(entries[start].k, 0, firstProof); err != nil {
   660  		b.Fatalf("Failed to prove the first node %v", err)
   661  	}
   662  	if err := trie.Prove(entries[end-1].k, 0, lastProof); err != nil {
   663  		b.Fatalf("Failed to prove the last node %v", err)
   664  	}
   665  	var keys [][]byte
   666  	var values [][]byte
   667  	for i := start; i < end; i++ {
   668  		keys = append(keys, entries[i].k)
   669  		values = append(values, entries[i].v)
   670  	}
   671  
   672  	b.ResetTimer()
   673  	for i := 0; i < b.N; i++ {
   674  		err, _ := VerifyRangeProof(trie.Hash(), keys[0], keys, values, firstProof, lastProof)
   675  		if err != nil {
   676  			b.Fatalf("Case %d(%d->%d) expect no error, got %v", i, start, end-1, err)
   677  		}
   678  	}
   679  }
   680  
   681  func randomTrie(n int) (*Trie, map[string]*kv) {
   682  	trie := new(Trie)
   683  	vals := make(map[string]*kv)
   684  	for i := byte(0); i < 100; i++ {
   685  		value := &kv{common.LeftPadBytes([]byte{i}, 32), []byte{i}, false}
   686  		value2 := &kv{common.LeftPadBytes([]byte{i + 10}, 32), []byte{i}, false}
   687  		trie.Update(value.k, value.v)
   688  		trie.Update(value2.k, value2.v)
   689  		vals[string(value.k)] = value
   690  		vals[string(value2.k)] = value2
   691  	}
   692  	for i := 0; i < n; i++ {
   693  		value := &kv{randBytes(32), randBytes(20), false}
   694  		trie.Update(value.k, value.v)
   695  		vals[string(value.k)] = value
   696  	}
   697  	return trie, vals
   698  }
   699  
   700  func randBytes(n int) []byte {
   701  	r := make([]byte, n)
   702  	crand.Read(r)
   703  	return r
   704  }