github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/eth/api_test.go (about)

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