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