github.com/Cleverse/go-ethereum@v0.0.0-20220927095127-45113064e7f2/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  	"encoding/binary"
    23  	mrand "math/rand"
    24  	"sort"
    25  	"testing"
    26  	"time"
    27  
    28  	"github.com/ethereum/go-ethereum/common"
    29  	"github.com/ethereum/go-ethereum/core/rawdb"
    30  	"github.com/ethereum/go-ethereum/crypto"
    31  	"github.com/ethereum/go-ethereum/ethdb/memorydb"
    32  )
    33  
    34  func init() {
    35  	mrand.Seed(time.Now().Unix())
    36  }
    37  
    38  // makeProvers creates Merkle trie provers based on different implementations to
    39  // test all variations.
    40  func makeProvers(trie *Trie) []func(key []byte) *memorydb.Database {
    41  	var provers []func(key []byte) *memorydb.Database
    42  
    43  	// Create a direct trie based Merkle prover
    44  	provers = append(provers, func(key []byte) *memorydb.Database {
    45  		proof := memorydb.New()
    46  		trie.Prove(key, 0, proof)
    47  		return proof
    48  	})
    49  	// Create a leaf iterator based Merkle prover
    50  	provers = append(provers, func(key []byte) *memorydb.Database {
    51  		proof := memorydb.New()
    52  		if it := NewIterator(trie.NodeIterator(key)); it.Next() && bytes.Equal(key, it.Key) {
    53  			for _, p := range it.Prove() {
    54  				proof.Put(crypto.Keccak256(p), p)
    55  			}
    56  		}
    57  		return proof
    58  	})
    59  	return provers
    60  }
    61  
    62  func TestProof(t *testing.T) {
    63  	trie, vals := randomTrie(500)
    64  	root := trie.Hash()
    65  	for i, prover := range makeProvers(trie) {
    66  		for _, kv := range vals {
    67  			proof := prover(kv.k)
    68  			if proof == nil {
    69  				t.Fatalf("prover %d: missing key %x while constructing proof", i, kv.k)
    70  			}
    71  			val, err := VerifyProof(root, kv.k, proof)
    72  			if err != nil {
    73  				t.Fatalf("prover %d: failed to verify proof for key %x: %v\nraw proof: %x", i, kv.k, err, proof)
    74  			}
    75  			if !bytes.Equal(val, kv.v) {
    76  				t.Fatalf("prover %d: verified value mismatch for key %x: have %x, want %x", i, kv.k, val, kv.v)
    77  			}
    78  		}
    79  	}
    80  }
    81  
    82  func TestOneElementProof(t *testing.T) {
    83  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
    84  	updateString(trie, "k", "v")
    85  	for i, prover := range makeProvers(trie) {
    86  		proof := prover([]byte("k"))
    87  		if proof == nil {
    88  			t.Fatalf("prover %d: nil proof", i)
    89  		}
    90  		if proof.Len() != 1 {
    91  			t.Errorf("prover %d: proof should have one element", i)
    92  		}
    93  		val, err := VerifyProof(trie.Hash(), []byte("k"), proof)
    94  		if err != nil {
    95  			t.Fatalf("prover %d: failed to verify proof: %v\nraw proof: %x", i, err, proof)
    96  		}
    97  		if !bytes.Equal(val, []byte("v")) {
    98  			t.Fatalf("prover %d: verified value mismatch: have %x, want 'k'", i, val)
    99  		}
   100  	}
   101  }
   102  
   103  func TestBadProof(t *testing.T) {
   104  	trie, vals := randomTrie(800)
   105  	root := trie.Hash()
   106  	for i, prover := range makeProvers(trie) {
   107  		for _, kv := range vals {
   108  			proof := prover(kv.k)
   109  			if proof == nil {
   110  				t.Fatalf("prover %d: nil proof", i)
   111  			}
   112  			it := proof.NewIterator(nil, nil)
   113  			for i, d := 0, mrand.Intn(proof.Len()); i <= d; i++ {
   114  				it.Next()
   115  			}
   116  			key := it.Key()
   117  			val, _ := proof.Get(key)
   118  			proof.Delete(key)
   119  			it.Release()
   120  
   121  			mutateByte(val)
   122  			proof.Put(crypto.Keccak256(val), val)
   123  
   124  			if _, err := VerifyProof(root, kv.k, proof); err == nil {
   125  				t.Fatalf("prover %d: expected proof to fail for key %x", i, kv.k)
   126  			}
   127  		}
   128  	}
   129  }
   130  
   131  // Tests that missing keys can also be proven. The test explicitly uses a single
   132  // entry trie and checks for missing keys both before and after the single entry.
   133  func TestMissingKeyProof(t *testing.T) {
   134  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   135  	updateString(trie, "k", "v")
   136  
   137  	for i, key := range []string{"a", "j", "l", "z"} {
   138  		proof := memorydb.New()
   139  		trie.Prove([]byte(key), 0, proof)
   140  
   141  		if proof.Len() != 1 {
   142  			t.Errorf("test %d: proof should have one element", i)
   143  		}
   144  		val, err := VerifyProof(trie.Hash(), []byte(key), proof)
   145  		if err != nil {
   146  			t.Fatalf("test %d: failed to verify proof: %v\nraw proof: %x", i, err, proof)
   147  		}
   148  		if val != nil {
   149  			t.Fatalf("test %d: verified value mismatch: have %x, want nil", i, val)
   150  		}
   151  	}
   152  }
   153  
   154  type entrySlice []*kv
   155  
   156  func (p entrySlice) Len() int           { return len(p) }
   157  func (p entrySlice) Less(i, j int) bool { return bytes.Compare(p[i].k, p[j].k) < 0 }
   158  func (p entrySlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
   159  
   160  // TestRangeProof tests normal range proof with both edge proofs
   161  // as the existent proof. The test cases are generated randomly.
   162  func TestRangeProof(t *testing.T) {
   163  	trie, vals := randomTrie(4096)
   164  	var entries entrySlice
   165  	for _, kv := range vals {
   166  		entries = append(entries, kv)
   167  	}
   168  	sort.Sort(entries)
   169  	for i := 0; i < 500; i++ {
   170  		start := mrand.Intn(len(entries))
   171  		end := mrand.Intn(len(entries)-start) + start + 1
   172  
   173  		proof := memorydb.New()
   174  		if err := trie.Prove(entries[start].k, 0, proof); err != nil {
   175  			t.Fatalf("Failed to prove the first node %v", err)
   176  		}
   177  		if err := trie.Prove(entries[end-1].k, 0, proof); 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[len(keys)-1], keys, vals, proof)
   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 two non-existent proofs.
   194  // 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 + 1
   205  		proof := memorydb.New()
   206  
   207  		// Short circuit if the decreased key is same with the previous key
   208  		first := decreseKey(common.CopyBytes(entries[start].k))
   209  		if start != 0 && bytes.Equal(first, entries[start-1].k) {
   210  			continue
   211  		}
   212  		// Short circuit if the decreased key is underflow
   213  		if bytes.Compare(first, entries[start].k) > 0 {
   214  			continue
   215  		}
   216  		// Short circuit if the increased key is same with the next key
   217  		last := increseKey(common.CopyBytes(entries[end-1].k))
   218  		if end != len(entries) && bytes.Equal(last, entries[end].k) {
   219  			continue
   220  		}
   221  		// Short circuit if the increased key is overflow
   222  		if bytes.Compare(last, entries[end-1].k) < 0 {
   223  			continue
   224  		}
   225  		if err := trie.Prove(first, 0, proof); err != nil {
   226  			t.Fatalf("Failed to prove the first node %v", err)
   227  		}
   228  		if err := trie.Prove(last, 0, proof); err != nil {
   229  			t.Fatalf("Failed to prove the last node %v", err)
   230  		}
   231  		var keys [][]byte
   232  		var vals [][]byte
   233  		for i := start; i < end; i++ {
   234  			keys = append(keys, entries[i].k)
   235  			vals = append(vals, entries[i].v)
   236  		}
   237  		_, err := VerifyRangeProof(trie.Hash(), first, last, keys, vals, proof)
   238  		if err != nil {
   239  			t.Fatalf("Case %d(%d->%d) expect no error, got %v", i, start, end-1, err)
   240  		}
   241  	}
   242  	// Special case, two edge proofs for two edge key.
   243  	proof := memorydb.New()
   244  	first := common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000").Bytes()
   245  	last := common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").Bytes()
   246  	if err := trie.Prove(first, 0, proof); err != nil {
   247  		t.Fatalf("Failed to prove the first node %v", err)
   248  	}
   249  	if err := trie.Prove(last, 0, proof); err != nil {
   250  		t.Fatalf("Failed to prove the last node %v", err)
   251  	}
   252  	var k [][]byte
   253  	var v [][]byte
   254  	for i := 0; i < len(entries); i++ {
   255  		k = append(k, entries[i].k)
   256  		v = append(v, entries[i].v)
   257  	}
   258  	_, err := VerifyRangeProof(trie.Hash(), first, last, k, v, proof)
   259  	if err != nil {
   260  		t.Fatal("Failed to verify whole rang with non-existent edges")
   261  	}
   262  }
   263  
   264  // TestRangeProofWithInvalidNonExistentProof tests such scenarios:
   265  // - There exists a gap between the first element and the left edge proof
   266  // - There exists a gap between the last element and the right edge proof
   267  func TestRangeProofWithInvalidNonExistentProof(t *testing.T) {
   268  	trie, vals := randomTrie(4096)
   269  	var entries entrySlice
   270  	for _, kv := range vals {
   271  		entries = append(entries, kv)
   272  	}
   273  	sort.Sort(entries)
   274  
   275  	// Case 1
   276  	start, end := 100, 200
   277  	first := decreseKey(common.CopyBytes(entries[start].k))
   278  
   279  	proof := memorydb.New()
   280  	if err := trie.Prove(first, 0, proof); err != nil {
   281  		t.Fatalf("Failed to prove the first node %v", err)
   282  	}
   283  	if err := trie.Prove(entries[end-1].k, 0, proof); err != nil {
   284  		t.Fatalf("Failed to prove the last node %v", err)
   285  	}
   286  	start = 105 // Gap created
   287  	k := make([][]byte, 0)
   288  	v := make([][]byte, 0)
   289  	for i := start; i < end; i++ {
   290  		k = append(k, entries[i].k)
   291  		v = append(v, entries[i].v)
   292  	}
   293  	_, err := VerifyRangeProof(trie.Hash(), first, k[len(k)-1], k, v, proof)
   294  	if err == nil {
   295  		t.Fatalf("Expected to detect the error, got nil")
   296  	}
   297  
   298  	// Case 2
   299  	start, end = 100, 200
   300  	last := increseKey(common.CopyBytes(entries[end-1].k))
   301  	proof = memorydb.New()
   302  	if err := trie.Prove(entries[start].k, 0, proof); err != nil {
   303  		t.Fatalf("Failed to prove the first node %v", err)
   304  	}
   305  	if err := trie.Prove(last, 0, proof); err != nil {
   306  		t.Fatalf("Failed to prove the last node %v", err)
   307  	}
   308  	end = 195 // Capped slice
   309  	k = make([][]byte, 0)
   310  	v = make([][]byte, 0)
   311  	for i := start; i < end; i++ {
   312  		k = append(k, entries[i].k)
   313  		v = append(v, entries[i].v)
   314  	}
   315  	_, err = VerifyRangeProof(trie.Hash(), k[0], last, k, v, proof)
   316  	if err == nil {
   317  		t.Fatalf("Expected to detect the error, got nil")
   318  	}
   319  }
   320  
   321  // TestOneElementRangeProof tests the proof with only one
   322  // element. The first edge proof can be existent one or
   323  // non-existent one.
   324  func TestOneElementRangeProof(t *testing.T) {
   325  	trie, vals := randomTrie(4096)
   326  	var entries entrySlice
   327  	for _, kv := range vals {
   328  		entries = append(entries, kv)
   329  	}
   330  	sort.Sort(entries)
   331  
   332  	// One element with existent edge proof, both edge proofs
   333  	// point to the SAME key.
   334  	start := 1000
   335  	proof := memorydb.New()
   336  	if err := trie.Prove(entries[start].k, 0, proof); err != nil {
   337  		t.Fatalf("Failed to prove the first node %v", err)
   338  	}
   339  	_, err := VerifyRangeProof(trie.Hash(), entries[start].k, entries[start].k, [][]byte{entries[start].k}, [][]byte{entries[start].v}, proof)
   340  	if err != nil {
   341  		t.Fatalf("Expected no error, got %v", err)
   342  	}
   343  
   344  	// One element with left non-existent edge proof
   345  	start = 1000
   346  	first := decreseKey(common.CopyBytes(entries[start].k))
   347  	proof = memorydb.New()
   348  	if err := trie.Prove(first, 0, proof); err != nil {
   349  		t.Fatalf("Failed to prove the first node %v", err)
   350  	}
   351  	if err := trie.Prove(entries[start].k, 0, proof); err != nil {
   352  		t.Fatalf("Failed to prove the last node %v", err)
   353  	}
   354  	_, err = VerifyRangeProof(trie.Hash(), first, entries[start].k, [][]byte{entries[start].k}, [][]byte{entries[start].v}, proof)
   355  	if err != nil {
   356  		t.Fatalf("Expected no error, got %v", err)
   357  	}
   358  
   359  	// One element with right non-existent edge proof
   360  	start = 1000
   361  	last := increseKey(common.CopyBytes(entries[start].k))
   362  	proof = memorydb.New()
   363  	if err := trie.Prove(entries[start].k, 0, proof); err != nil {
   364  		t.Fatalf("Failed to prove the first node %v", err)
   365  	}
   366  	if err := trie.Prove(last, 0, proof); err != nil {
   367  		t.Fatalf("Failed to prove the last node %v", err)
   368  	}
   369  	_, err = VerifyRangeProof(trie.Hash(), entries[start].k, last, [][]byte{entries[start].k}, [][]byte{entries[start].v}, proof)
   370  	if err != nil {
   371  		t.Fatalf("Expected no error, got %v", err)
   372  	}
   373  
   374  	// One element with two non-existent edge proofs
   375  	start = 1000
   376  	first, last = decreseKey(common.CopyBytes(entries[start].k)), increseKey(common.CopyBytes(entries[start].k))
   377  	proof = memorydb.New()
   378  	if err := trie.Prove(first, 0, proof); err != nil {
   379  		t.Fatalf("Failed to prove the first node %v", err)
   380  	}
   381  	if err := trie.Prove(last, 0, proof); err != nil {
   382  		t.Fatalf("Failed to prove the last node %v", err)
   383  	}
   384  	_, err = VerifyRangeProof(trie.Hash(), first, last, [][]byte{entries[start].k}, [][]byte{entries[start].v}, proof)
   385  	if err != nil {
   386  		t.Fatalf("Expected no error, got %v", err)
   387  	}
   388  
   389  	// Test the mini trie with only a single element.
   390  	tinyTrie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   391  	entry := &kv{randBytes(32), randBytes(20), false}
   392  	tinyTrie.Update(entry.k, entry.v)
   393  
   394  	first = common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000").Bytes()
   395  	last = entry.k
   396  	proof = memorydb.New()
   397  	if err := tinyTrie.Prove(first, 0, proof); err != nil {
   398  		t.Fatalf("Failed to prove the first node %v", err)
   399  	}
   400  	if err := tinyTrie.Prove(last, 0, proof); err != nil {
   401  		t.Fatalf("Failed to prove the last node %v", err)
   402  	}
   403  	_, err = VerifyRangeProof(tinyTrie.Hash(), first, last, [][]byte{entry.k}, [][]byte{entry.v}, proof)
   404  	if err != nil {
   405  		t.Fatalf("Expected no error, got %v", err)
   406  	}
   407  }
   408  
   409  // TestAllElementsProof tests the range proof with all elements.
   410  // The edge proofs can be nil.
   411  func TestAllElementsProof(t *testing.T) {
   412  	trie, vals := randomTrie(4096)
   413  	var entries entrySlice
   414  	for _, kv := range vals {
   415  		entries = append(entries, kv)
   416  	}
   417  	sort.Sort(entries)
   418  
   419  	var k [][]byte
   420  	var v [][]byte
   421  	for i := 0; i < len(entries); i++ {
   422  		k = append(k, entries[i].k)
   423  		v = append(v, entries[i].v)
   424  	}
   425  	_, err := VerifyRangeProof(trie.Hash(), nil, nil, k, v, nil)
   426  	if err != nil {
   427  		t.Fatalf("Expected no error, got %v", err)
   428  	}
   429  
   430  	// With edge proofs, it should still work.
   431  	proof := memorydb.New()
   432  	if err := trie.Prove(entries[0].k, 0, proof); err != nil {
   433  		t.Fatalf("Failed to prove the first node %v", err)
   434  	}
   435  	if err := trie.Prove(entries[len(entries)-1].k, 0, proof); err != nil {
   436  		t.Fatalf("Failed to prove the last node %v", err)
   437  	}
   438  	_, err = VerifyRangeProof(trie.Hash(), k[0], k[len(k)-1], k, v, proof)
   439  	if err != nil {
   440  		t.Fatalf("Expected no error, got %v", err)
   441  	}
   442  
   443  	// Even with non-existent edge proofs, it should still work.
   444  	proof = memorydb.New()
   445  	first := common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000000").Bytes()
   446  	last := common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").Bytes()
   447  	if err := trie.Prove(first, 0, proof); err != nil {
   448  		t.Fatalf("Failed to prove the first node %v", err)
   449  	}
   450  	if err := trie.Prove(last, 0, proof); err != nil {
   451  		t.Fatalf("Failed to prove the last node %v", err)
   452  	}
   453  	_, err = VerifyRangeProof(trie.Hash(), first, last, k, v, proof)
   454  	if err != nil {
   455  		t.Fatalf("Expected no error, got %v", err)
   456  	}
   457  }
   458  
   459  // TestSingleSideRangeProof tests the range starts from zero.
   460  func TestSingleSideRangeProof(t *testing.T) {
   461  	for i := 0; i < 64; i++ {
   462  		trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   463  		var entries entrySlice
   464  		for i := 0; i < 4096; i++ {
   465  			value := &kv{randBytes(32), randBytes(20), false}
   466  			trie.Update(value.k, value.v)
   467  			entries = append(entries, value)
   468  		}
   469  		sort.Sort(entries)
   470  
   471  		var cases = []int{0, 1, 50, 100, 1000, 2000, len(entries) - 1}
   472  		for _, pos := range cases {
   473  			proof := memorydb.New()
   474  			if err := trie.Prove(common.Hash{}.Bytes(), 0, proof); err != nil {
   475  				t.Fatalf("Failed to prove the first node %v", err)
   476  			}
   477  			if err := trie.Prove(entries[pos].k, 0, proof); err != nil {
   478  				t.Fatalf("Failed to prove the first node %v", err)
   479  			}
   480  			k := make([][]byte, 0)
   481  			v := make([][]byte, 0)
   482  			for i := 0; i <= pos; i++ {
   483  				k = append(k, entries[i].k)
   484  				v = append(v, entries[i].v)
   485  			}
   486  			_, err := VerifyRangeProof(trie.Hash(), common.Hash{}.Bytes(), k[len(k)-1], k, v, proof)
   487  			if err != nil {
   488  				t.Fatalf("Expected no error, got %v", err)
   489  			}
   490  		}
   491  	}
   492  }
   493  
   494  // TestReverseSingleSideRangeProof tests the range ends with 0xffff...fff.
   495  func TestReverseSingleSideRangeProof(t *testing.T) {
   496  	for i := 0; i < 64; i++ {
   497  		trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   498  		var entries entrySlice
   499  		for i := 0; i < 4096; i++ {
   500  			value := &kv{randBytes(32), randBytes(20), false}
   501  			trie.Update(value.k, value.v)
   502  			entries = append(entries, value)
   503  		}
   504  		sort.Sort(entries)
   505  
   506  		var cases = []int{0, 1, 50, 100, 1000, 2000, len(entries) - 1}
   507  		for _, pos := range cases {
   508  			proof := memorydb.New()
   509  			if err := trie.Prove(entries[pos].k, 0, proof); err != nil {
   510  				t.Fatalf("Failed to prove the first node %v", err)
   511  			}
   512  			last := common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
   513  			if err := trie.Prove(last.Bytes(), 0, proof); err != nil {
   514  				t.Fatalf("Failed to prove the last node %v", err)
   515  			}
   516  			k := make([][]byte, 0)
   517  			v := make([][]byte, 0)
   518  			for i := pos; i < len(entries); i++ {
   519  				k = append(k, entries[i].k)
   520  				v = append(v, entries[i].v)
   521  			}
   522  			_, err := VerifyRangeProof(trie.Hash(), k[0], last.Bytes(), k, v, proof)
   523  			if err != nil {
   524  				t.Fatalf("Expected no error, got %v", err)
   525  			}
   526  		}
   527  	}
   528  }
   529  
   530  // TestBadRangeProof tests a few cases which the proof is wrong.
   531  // The prover is expected to detect the error.
   532  func TestBadRangeProof(t *testing.T) {
   533  	trie, vals := randomTrie(4096)
   534  	var entries entrySlice
   535  	for _, kv := range vals {
   536  		entries = append(entries, kv)
   537  	}
   538  	sort.Sort(entries)
   539  
   540  	for i := 0; i < 500; i++ {
   541  		start := mrand.Intn(len(entries))
   542  		end := mrand.Intn(len(entries)-start) + start + 1
   543  		proof := memorydb.New()
   544  		if err := trie.Prove(entries[start].k, 0, proof); err != nil {
   545  			t.Fatalf("Failed to prove the first node %v", err)
   546  		}
   547  		if err := trie.Prove(entries[end-1].k, 0, proof); err != nil {
   548  			t.Fatalf("Failed to prove the last node %v", err)
   549  		}
   550  		var keys [][]byte
   551  		var vals [][]byte
   552  		for i := start; i < end; i++ {
   553  			keys = append(keys, entries[i].k)
   554  			vals = append(vals, entries[i].v)
   555  		}
   556  		var first, last = keys[0], keys[len(keys)-1]
   557  		testcase := mrand.Intn(6)
   558  		var index int
   559  		switch testcase {
   560  		case 0:
   561  			// Modified key
   562  			index = mrand.Intn(end - start)
   563  			keys[index] = randBytes(32) // In theory it can't be same
   564  		case 1:
   565  			// Modified val
   566  			index = mrand.Intn(end - start)
   567  			vals[index] = randBytes(20) // In theory it can't be same
   568  		case 2:
   569  			// Gapped entry slice
   570  			index = mrand.Intn(end - start)
   571  			if (index == 0 && start < 100) || (index == end-start-1 && end <= 100) {
   572  				continue
   573  			}
   574  			keys = append(keys[:index], keys[index+1:]...)
   575  			vals = append(vals[:index], vals[index+1:]...)
   576  		case 3:
   577  			// Out of order
   578  			index1 := mrand.Intn(end - start)
   579  			index2 := mrand.Intn(end - start)
   580  			if index1 == index2 {
   581  				continue
   582  			}
   583  			keys[index1], keys[index2] = keys[index2], keys[index1]
   584  			vals[index1], vals[index2] = vals[index2], vals[index1]
   585  		case 4:
   586  			// Set random key to nil, do nothing
   587  			index = mrand.Intn(end - start)
   588  			keys[index] = nil
   589  		case 5:
   590  			// Set random value to nil, deletion
   591  			index = mrand.Intn(end - start)
   592  			vals[index] = nil
   593  		}
   594  		_, err := VerifyRangeProof(trie.Hash(), first, last, keys, vals, proof)
   595  		if err == nil {
   596  			t.Fatalf("%d Case %d index %d range: (%d->%d) expect error, got nil", i, testcase, index, start, end-1)
   597  		}
   598  	}
   599  }
   600  
   601  // TestGappedRangeProof focuses on the small trie with embedded nodes.
   602  // If the gapped node is embedded in the trie, it should be detected too.
   603  func TestGappedRangeProof(t *testing.T) {
   604  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   605  	var entries []*kv // Sorted entries
   606  	for i := byte(0); i < 10; i++ {
   607  		value := &kv{common.LeftPadBytes([]byte{i}, 32), []byte{i}, false}
   608  		trie.Update(value.k, value.v)
   609  		entries = append(entries, value)
   610  	}
   611  	first, last := 2, 8
   612  	proof := memorydb.New()
   613  	if err := trie.Prove(entries[first].k, 0, proof); err != nil {
   614  		t.Fatalf("Failed to prove the first node %v", err)
   615  	}
   616  	if err := trie.Prove(entries[last-1].k, 0, proof); err != nil {
   617  		t.Fatalf("Failed to prove the last node %v", err)
   618  	}
   619  	var keys [][]byte
   620  	var vals [][]byte
   621  	for i := first; i < last; i++ {
   622  		if i == (first+last)/2 {
   623  			continue
   624  		}
   625  		keys = append(keys, entries[i].k)
   626  		vals = append(vals, entries[i].v)
   627  	}
   628  	_, err := VerifyRangeProof(trie.Hash(), keys[0], keys[len(keys)-1], keys, vals, proof)
   629  	if err == nil {
   630  		t.Fatal("expect error, got nil")
   631  	}
   632  }
   633  
   634  // TestSameSideProofs tests the element is not in the range covered by proofs
   635  func TestSameSideProofs(t *testing.T) {
   636  	trie, vals := randomTrie(4096)
   637  	var entries entrySlice
   638  	for _, kv := range vals {
   639  		entries = append(entries, kv)
   640  	}
   641  	sort.Sort(entries)
   642  
   643  	pos := 1000
   644  	first := decreseKey(common.CopyBytes(entries[pos].k))
   645  	first = decreseKey(first)
   646  	last := decreseKey(common.CopyBytes(entries[pos].k))
   647  
   648  	proof := memorydb.New()
   649  	if err := trie.Prove(first, 0, proof); err != nil {
   650  		t.Fatalf("Failed to prove the first node %v", err)
   651  	}
   652  	if err := trie.Prove(last, 0, proof); err != nil {
   653  		t.Fatalf("Failed to prove the last node %v", err)
   654  	}
   655  	_, err := VerifyRangeProof(trie.Hash(), first, last, [][]byte{entries[pos].k}, [][]byte{entries[pos].v}, proof)
   656  	if err == nil {
   657  		t.Fatalf("Expected error, got nil")
   658  	}
   659  
   660  	first = increseKey(common.CopyBytes(entries[pos].k))
   661  	last = increseKey(common.CopyBytes(entries[pos].k))
   662  	last = increseKey(last)
   663  
   664  	proof = memorydb.New()
   665  	if err := trie.Prove(first, 0, proof); err != nil {
   666  		t.Fatalf("Failed to prove the first node %v", err)
   667  	}
   668  	if err := trie.Prove(last, 0, proof); err != nil {
   669  		t.Fatalf("Failed to prove the last node %v", err)
   670  	}
   671  	_, err = VerifyRangeProof(trie.Hash(), first, last, [][]byte{entries[pos].k}, [][]byte{entries[pos].v}, proof)
   672  	if err == nil {
   673  		t.Fatalf("Expected error, got nil")
   674  	}
   675  }
   676  
   677  func TestHasRightElement(t *testing.T) {
   678  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
   679  	var entries entrySlice
   680  	for i := 0; i < 4096; i++ {
   681  		value := &kv{randBytes(32), randBytes(20), false}
   682  		trie.Update(value.k, value.v)
   683  		entries = append(entries, value)
   684  	}
   685  	sort.Sort(entries)
   686  
   687  	var cases = []struct {
   688  		start   int
   689  		end     int
   690  		hasMore bool
   691  	}{
   692  		{-1, 1, true}, // single element with non-existent left proof
   693  		{0, 1, true},  // single element with existent left proof
   694  		{0, 10, true},
   695  		{50, 100, true},
   696  		{50, len(entries), false},               // No more element expected
   697  		{len(entries) - 1, len(entries), false}, // Single last element with two existent proofs(point to same key)
   698  		{len(entries) - 1, -1, false},           // Single last element with non-existent right proof
   699  		{0, len(entries), false},                // The whole set with existent left proof
   700  		{-1, len(entries), false},               // The whole set with non-existent left proof
   701  		{-1, -1, false},                         // The whole set with non-existent left/right proof
   702  	}
   703  	for _, c := range cases {
   704  		var (
   705  			firstKey []byte
   706  			lastKey  []byte
   707  			start    = c.start
   708  			end      = c.end
   709  			proof    = memorydb.New()
   710  		)
   711  		if c.start == -1 {
   712  			firstKey, start = common.Hash{}.Bytes(), 0
   713  			if err := trie.Prove(firstKey, 0, proof); err != nil {
   714  				t.Fatalf("Failed to prove the first node %v", err)
   715  			}
   716  		} else {
   717  			firstKey = entries[c.start].k
   718  			if err := trie.Prove(entries[c.start].k, 0, proof); err != nil {
   719  				t.Fatalf("Failed to prove the first node %v", err)
   720  			}
   721  		}
   722  		if c.end == -1 {
   723  			lastKey, end = common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").Bytes(), len(entries)
   724  			if err := trie.Prove(lastKey, 0, proof); err != nil {
   725  				t.Fatalf("Failed to prove the first node %v", err)
   726  			}
   727  		} else {
   728  			lastKey = entries[c.end-1].k
   729  			if err := trie.Prove(entries[c.end-1].k, 0, proof); err != nil {
   730  				t.Fatalf("Failed to prove the first node %v", err)
   731  			}
   732  		}
   733  		k := make([][]byte, 0)
   734  		v := make([][]byte, 0)
   735  		for i := start; i < end; i++ {
   736  			k = append(k, entries[i].k)
   737  			v = append(v, entries[i].v)
   738  		}
   739  		hasMore, err := VerifyRangeProof(trie.Hash(), firstKey, lastKey, k, v, proof)
   740  		if err != nil {
   741  			t.Fatalf("Expected no error, got %v", err)
   742  		}
   743  		if hasMore != c.hasMore {
   744  			t.Fatalf("Wrong hasMore indicator, want %t, got %t", c.hasMore, hasMore)
   745  		}
   746  	}
   747  }
   748  
   749  // TestEmptyRangeProof tests the range proof with "no" element.
   750  // The first edge proof must be a non-existent proof.
   751  func TestEmptyRangeProof(t *testing.T) {
   752  	trie, vals := randomTrie(4096)
   753  	var entries entrySlice
   754  	for _, kv := range vals {
   755  		entries = append(entries, kv)
   756  	}
   757  	sort.Sort(entries)
   758  
   759  	var cases = []struct {
   760  		pos int
   761  		err bool
   762  	}{
   763  		{len(entries) - 1, false},
   764  		{500, true},
   765  	}
   766  	for _, c := range cases {
   767  		proof := memorydb.New()
   768  		first := increseKey(common.CopyBytes(entries[c.pos].k))
   769  		if err := trie.Prove(first, 0, proof); err != nil {
   770  			t.Fatalf("Failed to prove the first node %v", err)
   771  		}
   772  		_, err := VerifyRangeProof(trie.Hash(), first, nil, nil, nil, proof)
   773  		if c.err && err == nil {
   774  			t.Fatalf("Expected error, got nil")
   775  		}
   776  		if !c.err && err != nil {
   777  			t.Fatalf("Expected no error, got %v", err)
   778  		}
   779  	}
   780  }
   781  
   782  // TestBloatedProof tests a malicious proof, where the proof is more or less the
   783  // whole trie. Previously we didn't accept such packets, but the new APIs do, so
   784  // lets leave this test as a bit weird, but present.
   785  func TestBloatedProof(t *testing.T) {
   786  	// Use a small trie
   787  	trie, kvs := nonRandomTrie(100)
   788  	var entries entrySlice
   789  	for _, kv := range kvs {
   790  		entries = append(entries, kv)
   791  	}
   792  	sort.Sort(entries)
   793  	var keys [][]byte
   794  	var vals [][]byte
   795  
   796  	proof := memorydb.New()
   797  	// In the 'malicious' case, we add proofs for every single item
   798  	// (but only one key/value pair used as leaf)
   799  	for i, entry := range entries {
   800  		trie.Prove(entry.k, 0, proof)
   801  		if i == 50 {
   802  			keys = append(keys, entry.k)
   803  			vals = append(vals, entry.v)
   804  		}
   805  	}
   806  	// For reference, we use the same function, but _only_ prove the first
   807  	// and last element
   808  	want := memorydb.New()
   809  	trie.Prove(keys[0], 0, want)
   810  	trie.Prove(keys[len(keys)-1], 0, want)
   811  
   812  	if _, err := VerifyRangeProof(trie.Hash(), keys[0], keys[len(keys)-1], keys, vals, proof); err != nil {
   813  		t.Fatalf("expected bloated proof to succeed, got %v", err)
   814  	}
   815  }
   816  
   817  // TestEmptyValueRangeProof tests normal range proof with both edge proofs
   818  // as the existent proof, but with an extra empty value included, which is a
   819  // noop technically, but practically should be rejected.
   820  func TestEmptyValueRangeProof(t *testing.T) {
   821  	trie, values := randomTrie(512)
   822  	var entries entrySlice
   823  	for _, kv := range values {
   824  		entries = append(entries, kv)
   825  	}
   826  	sort.Sort(entries)
   827  
   828  	// Create a new entry with a slightly modified key
   829  	mid := len(entries) / 2
   830  	key := common.CopyBytes(entries[mid-1].k)
   831  	for n := len(key) - 1; n >= 0; n-- {
   832  		if key[n] < 0xff {
   833  			key[n]++
   834  			break
   835  		}
   836  	}
   837  	noop := &kv{key, []byte{}, false}
   838  	entries = append(append(append([]*kv{}, entries[:mid]...), noop), entries[mid:]...)
   839  
   840  	start, end := 1, len(entries)-1
   841  
   842  	proof := memorydb.New()
   843  	if err := trie.Prove(entries[start].k, 0, proof); err != nil {
   844  		t.Fatalf("Failed to prove the first node %v", err)
   845  	}
   846  	if err := trie.Prove(entries[end-1].k, 0, proof); err != nil {
   847  		t.Fatalf("Failed to prove the last node %v", err)
   848  	}
   849  	var keys [][]byte
   850  	var vals [][]byte
   851  	for i := start; i < end; i++ {
   852  		keys = append(keys, entries[i].k)
   853  		vals = append(vals, entries[i].v)
   854  	}
   855  	_, err := VerifyRangeProof(trie.Hash(), keys[0], keys[len(keys)-1], keys, vals, proof)
   856  	if err == nil {
   857  		t.Fatalf("Expected failure on noop entry")
   858  	}
   859  }
   860  
   861  // TestAllElementsEmptyValueRangeProof tests the range proof with all elements,
   862  // but with an extra empty value included, which is a noop technically, but
   863  // practically should be rejected.
   864  func TestAllElementsEmptyValueRangeProof(t *testing.T) {
   865  	trie, values := randomTrie(512)
   866  	var entries entrySlice
   867  	for _, kv := range values {
   868  		entries = append(entries, kv)
   869  	}
   870  	sort.Sort(entries)
   871  
   872  	// Create a new entry with a slightly modified key
   873  	mid := len(entries) / 2
   874  	key := common.CopyBytes(entries[mid-1].k)
   875  	for n := len(key) - 1; n >= 0; n-- {
   876  		if key[n] < 0xff {
   877  			key[n]++
   878  			break
   879  		}
   880  	}
   881  	noop := &kv{key, []byte{}, false}
   882  	entries = append(append(append([]*kv{}, entries[:mid]...), noop), entries[mid:]...)
   883  
   884  	var keys [][]byte
   885  	var vals [][]byte
   886  	for i := 0; i < len(entries); i++ {
   887  		keys = append(keys, entries[i].k)
   888  		vals = append(vals, entries[i].v)
   889  	}
   890  	_, err := VerifyRangeProof(trie.Hash(), nil, nil, keys, vals, nil)
   891  	if err == nil {
   892  		t.Fatalf("Expected failure on noop entry")
   893  	}
   894  }
   895  
   896  // mutateByte changes one byte in b.
   897  func mutateByte(b []byte) {
   898  	for r := mrand.Intn(len(b)); ; {
   899  		new := byte(mrand.Intn(255))
   900  		if new != b[r] {
   901  			b[r] = new
   902  			break
   903  		}
   904  	}
   905  }
   906  
   907  func increseKey(key []byte) []byte {
   908  	for i := len(key) - 1; i >= 0; i-- {
   909  		key[i]++
   910  		if key[i] != 0x0 {
   911  			break
   912  		}
   913  	}
   914  	return key
   915  }
   916  
   917  func decreseKey(key []byte) []byte {
   918  	for i := len(key) - 1; i >= 0; i-- {
   919  		key[i]--
   920  		if key[i] != 0xff {
   921  			break
   922  		}
   923  	}
   924  	return key
   925  }
   926  
   927  func BenchmarkProve(b *testing.B) {
   928  	trie, vals := randomTrie(100)
   929  	var keys []string
   930  	for k := range vals {
   931  		keys = append(keys, k)
   932  	}
   933  
   934  	b.ResetTimer()
   935  	for i := 0; i < b.N; i++ {
   936  		kv := vals[keys[i%len(keys)]]
   937  		proofs := memorydb.New()
   938  		if trie.Prove(kv.k, 0, proofs); proofs.Len() == 0 {
   939  			b.Fatalf("zero length proof for %x", kv.k)
   940  		}
   941  	}
   942  }
   943  
   944  func BenchmarkVerifyProof(b *testing.B) {
   945  	trie, vals := randomTrie(100)
   946  	root := trie.Hash()
   947  	var keys []string
   948  	var proofs []*memorydb.Database
   949  	for k := range vals {
   950  		keys = append(keys, k)
   951  		proof := memorydb.New()
   952  		trie.Prove([]byte(k), 0, proof)
   953  		proofs = append(proofs, proof)
   954  	}
   955  
   956  	b.ResetTimer()
   957  	for i := 0; i < b.N; i++ {
   958  		im := i % len(keys)
   959  		if _, err := VerifyProof(root, []byte(keys[im]), proofs[im]); err != nil {
   960  			b.Fatalf("key %x: %v", keys[im], err)
   961  		}
   962  	}
   963  }
   964  
   965  func BenchmarkVerifyRangeProof10(b *testing.B)   { benchmarkVerifyRangeProof(b, 10) }
   966  func BenchmarkVerifyRangeProof100(b *testing.B)  { benchmarkVerifyRangeProof(b, 100) }
   967  func BenchmarkVerifyRangeProof1000(b *testing.B) { benchmarkVerifyRangeProof(b, 1000) }
   968  func BenchmarkVerifyRangeProof5000(b *testing.B) { benchmarkVerifyRangeProof(b, 5000) }
   969  
   970  func benchmarkVerifyRangeProof(b *testing.B, size int) {
   971  	trie, vals := randomTrie(8192)
   972  	var entries entrySlice
   973  	for _, kv := range vals {
   974  		entries = append(entries, kv)
   975  	}
   976  	sort.Sort(entries)
   977  
   978  	start := 2
   979  	end := start + size
   980  	proof := memorydb.New()
   981  	if err := trie.Prove(entries[start].k, 0, proof); err != nil {
   982  		b.Fatalf("Failed to prove the first node %v", err)
   983  	}
   984  	if err := trie.Prove(entries[end-1].k, 0, proof); err != nil {
   985  		b.Fatalf("Failed to prove the last node %v", err)
   986  	}
   987  	var keys [][]byte
   988  	var values [][]byte
   989  	for i := start; i < end; i++ {
   990  		keys = append(keys, entries[i].k)
   991  		values = append(values, entries[i].v)
   992  	}
   993  
   994  	b.ResetTimer()
   995  	for i := 0; i < b.N; i++ {
   996  		_, err := VerifyRangeProof(trie.Hash(), keys[0], keys[len(keys)-1], keys, values, proof)
   997  		if err != nil {
   998  			b.Fatalf("Case %d(%d->%d) expect no error, got %v", i, start, end-1, err)
   999  		}
  1000  	}
  1001  }
  1002  
  1003  func BenchmarkVerifyRangeNoProof10(b *testing.B)   { benchmarkVerifyRangeNoProof(b, 100) }
  1004  func BenchmarkVerifyRangeNoProof500(b *testing.B)  { benchmarkVerifyRangeNoProof(b, 500) }
  1005  func BenchmarkVerifyRangeNoProof1000(b *testing.B) { benchmarkVerifyRangeNoProof(b, 1000) }
  1006  
  1007  func benchmarkVerifyRangeNoProof(b *testing.B, size int) {
  1008  	trie, vals := randomTrie(size)
  1009  	var entries entrySlice
  1010  	for _, kv := range vals {
  1011  		entries = append(entries, kv)
  1012  	}
  1013  	sort.Sort(entries)
  1014  
  1015  	var keys [][]byte
  1016  	var values [][]byte
  1017  	for _, entry := range entries {
  1018  		keys = append(keys, entry.k)
  1019  		values = append(values, entry.v)
  1020  	}
  1021  	b.ResetTimer()
  1022  	for i := 0; i < b.N; i++ {
  1023  		_, err := VerifyRangeProof(trie.Hash(), keys[0], keys[len(keys)-1], keys, values, nil)
  1024  		if err != nil {
  1025  			b.Fatalf("Expected no error, got %v", err)
  1026  		}
  1027  	}
  1028  }
  1029  
  1030  func randomTrie(n int) (*Trie, map[string]*kv) {
  1031  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
  1032  	vals := make(map[string]*kv)
  1033  	for i := byte(0); i < 100; i++ {
  1034  		value := &kv{common.LeftPadBytes([]byte{i}, 32), []byte{i}, false}
  1035  		value2 := &kv{common.LeftPadBytes([]byte{i + 10}, 32), []byte{i}, false}
  1036  		trie.Update(value.k, value.v)
  1037  		trie.Update(value2.k, value2.v)
  1038  		vals[string(value.k)] = value
  1039  		vals[string(value2.k)] = value2
  1040  	}
  1041  	for i := 0; i < n; i++ {
  1042  		value := &kv{randBytes(32), randBytes(20), false}
  1043  		trie.Update(value.k, value.v)
  1044  		vals[string(value.k)] = value
  1045  	}
  1046  	return trie, vals
  1047  }
  1048  
  1049  func randBytes(n int) []byte {
  1050  	r := make([]byte, n)
  1051  	crand.Read(r)
  1052  	return r
  1053  }
  1054  
  1055  func nonRandomTrie(n int) (*Trie, map[string]*kv) {
  1056  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
  1057  	vals := make(map[string]*kv)
  1058  	max := uint64(0xffffffffffffffff)
  1059  	for i := uint64(0); i < uint64(n); i++ {
  1060  		value := make([]byte, 32)
  1061  		key := make([]byte, 32)
  1062  		binary.LittleEndian.PutUint64(key, i)
  1063  		binary.LittleEndian.PutUint64(value, i-max)
  1064  		//value := &kv{common.LeftPadBytes([]byte{i}, 32), []byte{i}, false}
  1065  		elem := &kv{key, value, false}
  1066  		trie.Update(elem.k, elem.v)
  1067  		vals[string(elem.k)] = elem
  1068  	}
  1069  	return trie, vals
  1070  }
  1071  
  1072  func TestRangeProofKeysWithSharedPrefix(t *testing.T) {
  1073  	keys := [][]byte{
  1074  		common.Hex2Bytes("aa10000000000000000000000000000000000000000000000000000000000000"),
  1075  		common.Hex2Bytes("aa20000000000000000000000000000000000000000000000000000000000000"),
  1076  	}
  1077  	vals := [][]byte{
  1078  		common.Hex2Bytes("02"),
  1079  		common.Hex2Bytes("03"),
  1080  	}
  1081  	trie := NewEmpty(NewDatabase(rawdb.NewMemoryDatabase()))
  1082  	for i, key := range keys {
  1083  		trie.Update(key, vals[i])
  1084  	}
  1085  	root := trie.Hash()
  1086  	proof := memorydb.New()
  1087  	start := common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000000")
  1088  	end := common.Hex2Bytes("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
  1089  	if err := trie.Prove(start, 0, proof); err != nil {
  1090  		t.Fatalf("failed to prove start: %v", err)
  1091  	}
  1092  	if err := trie.Prove(end, 0, proof); err != nil {
  1093  		t.Fatalf("failed to prove end: %v", err)
  1094  	}
  1095  
  1096  	more, err := VerifyRangeProof(root, start, end, keys, vals, proof)
  1097  	if err != nil {
  1098  		t.Fatalf("failed to verify range proof: %v", err)
  1099  	}
  1100  	if more != false {
  1101  		t.Error("expected more to be false")
  1102  	}
  1103  }