github.com/jimmyx0x/go-ethereum@v1.10.28/eth/api_test.go (about)

     1  // Copyright 2017 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 eth
    18  
    19  import (
    20  	"bytes"
    21  	"fmt"
    22  	"math/big"
    23  	"reflect"
    24  	"sort"
    25  	"testing"
    26  
    27  	"github.com/davecgh/go-spew/spew"
    28  	"github.com/ethereum/go-ethereum/common"
    29  	"github.com/ethereum/go-ethereum/core/rawdb"
    30  	"github.com/ethereum/go-ethereum/core/state"
    31  	"github.com/ethereum/go-ethereum/crypto"
    32  	"github.com/ethereum/go-ethereum/trie"
    33  )
    34  
    35  var dumper = spew.ConfigState{Indent: "    "}
    36  
    37  func accountRangeTest(t *testing.T, trie *state.Trie, statedb *state.StateDB, start common.Hash, requestedNum int, expectedNum int) state.IteratorDump {
    38  	result := statedb.IteratorDump(&state.DumpConfig{
    39  		SkipCode:          true,
    40  		SkipStorage:       true,
    41  		OnlyWithAddresses: false,
    42  		Start:             start.Bytes(),
    43  		Max:               uint64(requestedNum),
    44  	})
    45  
    46  	if len(result.Accounts) != expectedNum {
    47  		t.Fatalf("expected %d results, got %d", expectedNum, len(result.Accounts))
    48  	}
    49  	for address := range result.Accounts {
    50  		if address == (common.Address{}) {
    51  			t.Fatalf("empty address returned")
    52  		}
    53  		if !statedb.Exist(address) {
    54  			t.Fatalf("account not found in state %s", address.Hex())
    55  		}
    56  	}
    57  	return result
    58  }
    59  
    60  type resultHash []common.Hash
    61  
    62  func (h resultHash) Len() int           { return len(h) }
    63  func (h resultHash) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
    64  func (h resultHash) Less(i, j int) bool { return bytes.Compare(h[i].Bytes(), h[j].Bytes()) < 0 }
    65  
    66  func TestAccountRange(t *testing.T) {
    67  	t.Parallel()
    68  
    69  	var (
    70  		statedb  = state.NewDatabaseWithConfig(rawdb.NewMemoryDatabase(), &trie.Config{Preimages: true})
    71  		state, _ = state.New(common.Hash{}, statedb, nil)
    72  		addrs    = [AccountRangeMaxResults * 2]common.Address{}
    73  		m        = map[common.Address]bool{}
    74  	)
    75  
    76  	for i := range addrs {
    77  		hash := common.HexToHash(fmt.Sprintf("%x", i))
    78  		addr := common.BytesToAddress(crypto.Keccak256Hash(hash.Bytes()).Bytes())
    79  		addrs[i] = addr
    80  		state.SetBalance(addrs[i], big.NewInt(1))
    81  		if _, ok := m[addr]; ok {
    82  			t.Fatalf("bad")
    83  		} else {
    84  			m[addr] = true
    85  		}
    86  	}
    87  	state.Commit(true)
    88  	root := state.IntermediateRoot(true)
    89  
    90  	trie, err := statedb.OpenTrie(root)
    91  	if err != nil {
    92  		t.Fatal(err)
    93  	}
    94  	accountRangeTest(t, &trie, state, common.Hash{}, AccountRangeMaxResults/2, AccountRangeMaxResults/2)
    95  	// test pagination
    96  	firstResult := accountRangeTest(t, &trie, state, common.Hash{}, AccountRangeMaxResults, AccountRangeMaxResults)
    97  	secondResult := accountRangeTest(t, &trie, state, common.BytesToHash(firstResult.Next), AccountRangeMaxResults, AccountRangeMaxResults)
    98  
    99  	hList := make(resultHash, 0)
   100  	for addr1 := range firstResult.Accounts {
   101  		// If address is empty, then it makes no sense to compare
   102  		// them as they might be two different accounts.
   103  		if addr1 == (common.Address{}) {
   104  			continue
   105  		}
   106  		if _, duplicate := secondResult.Accounts[addr1]; duplicate {
   107  			t.Fatalf("pagination test failed:  results should not overlap")
   108  		}
   109  		hList = append(hList, crypto.Keccak256Hash(addr1.Bytes()))
   110  	}
   111  	// Test to see if it's possible to recover from the middle of the previous
   112  	// set and get an even split between the first and second sets.
   113  	sort.Sort(hList)
   114  	middleH := hList[AccountRangeMaxResults/2]
   115  	middleResult := accountRangeTest(t, &trie, state, middleH, AccountRangeMaxResults, AccountRangeMaxResults)
   116  	missing, infirst, insecond := 0, 0, 0
   117  	for h := range middleResult.Accounts {
   118  		if _, ok := firstResult.Accounts[h]; ok {
   119  			infirst++
   120  		} else if _, ok := secondResult.Accounts[h]; ok {
   121  			insecond++
   122  		} else {
   123  			missing++
   124  		}
   125  	}
   126  	if missing != 0 {
   127  		t.Fatalf("%d hashes in the 'middle' set were neither in the first not the second set", missing)
   128  	}
   129  	if infirst != AccountRangeMaxResults/2 {
   130  		t.Fatalf("Imbalance in the number of first-test results: %d != %d", infirst, AccountRangeMaxResults/2)
   131  	}
   132  	if insecond != AccountRangeMaxResults/2 {
   133  		t.Fatalf("Imbalance in the number of second-test results: %d != %d", insecond, AccountRangeMaxResults/2)
   134  	}
   135  }
   136  
   137  func TestEmptyAccountRange(t *testing.T) {
   138  	t.Parallel()
   139  
   140  	var (
   141  		statedb = state.NewDatabase(rawdb.NewMemoryDatabase())
   142  		st, _   = state.New(common.Hash{}, statedb, nil)
   143  	)
   144  	st.Commit(true)
   145  	st.IntermediateRoot(true)
   146  	results := st.IteratorDump(&state.DumpConfig{
   147  		SkipCode:          true,
   148  		SkipStorage:       true,
   149  		OnlyWithAddresses: true,
   150  		Max:               uint64(AccountRangeMaxResults),
   151  	})
   152  	if bytes.Equal(results.Next, (common.Hash{}).Bytes()) {
   153  		t.Fatalf("Empty results should not return a second page")
   154  	}
   155  	if len(results.Accounts) != 0 {
   156  		t.Fatalf("Empty state should not return addresses: %v", results.Accounts)
   157  	}
   158  }
   159  
   160  func TestStorageRangeAt(t *testing.T) {
   161  	t.Parallel()
   162  
   163  	// Create a state where account 0x010000... has a few storage entries.
   164  	var (
   165  		state, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
   166  		addr     = common.Address{0x01}
   167  		keys     = []common.Hash{ // hashes of Keys of storage
   168  			common.HexToHash("340dd630ad21bf010b4e676dbfa9ba9a02175262d1fa356232cfde6cb5b47ef2"),
   169  			common.HexToHash("426fcb404ab2d5d8e61a3d918108006bbb0a9be65e92235bb10eefbdb6dcd053"),
   170  			common.HexToHash("48078cfed56339ea54962e72c37c7f588fc4f8e5bc173827ba75cb10a63a96a5"),
   171  			common.HexToHash("5723d2c3a83af9b735e3b7f21531e5623d183a9095a56604ead41f3582fdfb75"),
   172  		}
   173  		storage = storageMap{
   174  			keys[0]: {Key: &common.Hash{0x02}, Value: common.Hash{0x01}},
   175  			keys[1]: {Key: &common.Hash{0x04}, Value: common.Hash{0x02}},
   176  			keys[2]: {Key: &common.Hash{0x01}, Value: common.Hash{0x03}},
   177  			keys[3]: {Key: &common.Hash{0x03}, Value: common.Hash{0x04}},
   178  		}
   179  	)
   180  	for _, entry := range storage {
   181  		state.SetState(addr, *entry.Key, entry.Value)
   182  	}
   183  
   184  	// Check a few combinations of limit and start/end.
   185  	tests := []struct {
   186  		start []byte
   187  		limit int
   188  		want  StorageRangeResult
   189  	}{
   190  		{
   191  			start: []byte{}, limit: 0,
   192  			want: StorageRangeResult{storageMap{}, &keys[0]},
   193  		},
   194  		{
   195  			start: []byte{}, limit: 100,
   196  			want: StorageRangeResult{storage, nil},
   197  		},
   198  		{
   199  			start: []byte{}, limit: 2,
   200  			want: StorageRangeResult{storageMap{keys[0]: storage[keys[0]], keys[1]: storage[keys[1]]}, &keys[2]},
   201  		},
   202  		{
   203  			start: []byte{0x00}, limit: 4,
   204  			want: StorageRangeResult{storage, nil},
   205  		},
   206  		{
   207  			start: []byte{0x40}, limit: 2,
   208  			want: StorageRangeResult{storageMap{keys[1]: storage[keys[1]], keys[2]: storage[keys[2]]}, &keys[3]},
   209  		},
   210  	}
   211  	for _, test := range tests {
   212  		tr, err := state.StorageTrie(addr)
   213  		if err != nil {
   214  			t.Error(err)
   215  		}
   216  		result, err := storageRangeAt(tr, test.start, test.limit)
   217  		if err != nil {
   218  			t.Error(err)
   219  		}
   220  		if !reflect.DeepEqual(result, test.want) {
   221  			t.Fatalf("wrong result for range %#x.., limit %d:\ngot %s\nwant %s",
   222  				test.start, test.limit, dumper.Sdump(result), dumper.Sdump(&test.want))
   223  		}
   224  	}
   225  }