github.com/authcall/reference-optimistic-geth@v0.0.0-20220816224302-06313bfeb8d2/eth/tracers/api_test.go (about)

     1  // Copyright 2021 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 tracers
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"crypto/ecdsa"
    23  	"encoding/json"
    24  	"errors"
    25  	"fmt"
    26  	"math/big"
    27  	"reflect"
    28  	"sort"
    29  	"testing"
    30  	"time"
    31  
    32  	"github.com/ethereum/go-ethereum/common"
    33  	"github.com/ethereum/go-ethereum/common/hexutil"
    34  	"github.com/ethereum/go-ethereum/consensus"
    35  	"github.com/ethereum/go-ethereum/consensus/ethash"
    36  	"github.com/ethereum/go-ethereum/core"
    37  	"github.com/ethereum/go-ethereum/core/rawdb"
    38  	"github.com/ethereum/go-ethereum/core/state"
    39  	"github.com/ethereum/go-ethereum/core/types"
    40  	"github.com/ethereum/go-ethereum/core/vm"
    41  	"github.com/ethereum/go-ethereum/crypto"
    42  	"github.com/ethereum/go-ethereum/eth/tracers/logger"
    43  	"github.com/ethereum/go-ethereum/ethdb"
    44  	"github.com/ethereum/go-ethereum/internal/ethapi"
    45  	"github.com/ethereum/go-ethereum/params"
    46  	"github.com/ethereum/go-ethereum/rpc"
    47  )
    48  
    49  var (
    50  	errStateNotFound       = errors.New("state not found")
    51  	errBlockNotFound       = errors.New("block not found")
    52  	errTransactionNotFound = errors.New("transaction not found")
    53  )
    54  
    55  type testBackend struct {
    56  	chainConfig *params.ChainConfig
    57  	engine      consensus.Engine
    58  	chaindb     ethdb.Database
    59  	chain       *core.BlockChain
    60  }
    61  
    62  func newTestBackend(t *testing.T, n int, gspec *core.Genesis, generator func(i int, b *core.BlockGen)) *testBackend {
    63  	backend := &testBackend{
    64  		chainConfig: params.TestChainConfig,
    65  		engine:      ethash.NewFaker(),
    66  		chaindb:     rawdb.NewMemoryDatabase(),
    67  	}
    68  	// Generate blocks for testing
    69  	gspec.Config = backend.chainConfig
    70  	var (
    71  		gendb   = rawdb.NewMemoryDatabase()
    72  		genesis = gspec.MustCommit(gendb)
    73  	)
    74  	blocks, _ := core.GenerateChain(backend.chainConfig, genesis, backend.engine, gendb, n, generator)
    75  
    76  	// Import the canonical chain
    77  	gspec.MustCommit(backend.chaindb)
    78  	cacheConfig := &core.CacheConfig{
    79  		TrieCleanLimit:    256,
    80  		TrieDirtyLimit:    256,
    81  		TrieTimeLimit:     5 * time.Minute,
    82  		SnapshotLimit:     0,
    83  		TrieDirtyDisabled: true, // Archive mode
    84  	}
    85  	chain, err := core.NewBlockChain(backend.chaindb, cacheConfig, backend.chainConfig, backend.engine, vm.Config{}, nil, nil)
    86  	if err != nil {
    87  		t.Fatalf("failed to create tester chain: %v", err)
    88  	}
    89  	if n, err := chain.InsertChain(blocks); err != nil {
    90  		t.Fatalf("block %d: failed to insert into chain: %v", n, err)
    91  	}
    92  	backend.chain = chain
    93  	return backend
    94  }
    95  
    96  func (b *testBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
    97  	return b.chain.GetHeaderByHash(hash), nil
    98  }
    99  
   100  func (b *testBackend) HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error) {
   101  	if number == rpc.PendingBlockNumber || number == rpc.LatestBlockNumber {
   102  		return b.chain.CurrentHeader(), nil
   103  	}
   104  	return b.chain.GetHeaderByNumber(uint64(number)), nil
   105  }
   106  
   107  func (b *testBackend) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
   108  	return b.chain.GetBlockByHash(hash), nil
   109  }
   110  
   111  func (b *testBackend) BlockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error) {
   112  	if number == rpc.PendingBlockNumber || number == rpc.LatestBlockNumber {
   113  		return b.chain.CurrentBlock(), nil
   114  	}
   115  	return b.chain.GetBlockByNumber(uint64(number)), nil
   116  }
   117  
   118  func (b *testBackend) GetTransaction(ctx context.Context, txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, error) {
   119  	tx, hash, blockNumber, index := rawdb.ReadTransaction(b.chaindb, txHash)
   120  	if tx == nil {
   121  		return nil, common.Hash{}, 0, 0, errTransactionNotFound
   122  	}
   123  	return tx, hash, blockNumber, index, nil
   124  }
   125  
   126  func (b *testBackend) RPCGasCap() uint64 {
   127  	return 25000000
   128  }
   129  
   130  func (b *testBackend) ChainConfig() *params.ChainConfig {
   131  	return b.chainConfig
   132  }
   133  
   134  func (b *testBackend) Engine() consensus.Engine {
   135  	return b.engine
   136  }
   137  
   138  func (b *testBackend) ChainDb() ethdb.Database {
   139  	return b.chaindb
   140  }
   141  
   142  func (b *testBackend) StateAtBlock(ctx context.Context, block *types.Block, reexec uint64, base *state.StateDB, checkLive bool, preferDisk bool) (*state.StateDB, error) {
   143  	statedb, err := b.chain.StateAt(block.Root())
   144  	if err != nil {
   145  		return nil, errStateNotFound
   146  	}
   147  	return statedb, nil
   148  }
   149  
   150  func (b *testBackend) StateAtTransaction(ctx context.Context, block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, error) {
   151  	parent := b.chain.GetBlock(block.ParentHash(), block.NumberU64()-1)
   152  	if parent == nil {
   153  		return nil, vm.BlockContext{}, nil, errBlockNotFound
   154  	}
   155  	statedb, err := b.chain.StateAt(parent.Root())
   156  	if err != nil {
   157  		return nil, vm.BlockContext{}, nil, errStateNotFound
   158  	}
   159  	if txIndex == 0 && len(block.Transactions()) == 0 {
   160  		return nil, vm.BlockContext{}, statedb, nil
   161  	}
   162  	// Recompute transactions up to the target index.
   163  	signer := types.MakeSigner(b.chainConfig, block.Number())
   164  	for idx, tx := range block.Transactions() {
   165  		msg, _ := tx.AsMessage(signer, block.BaseFee())
   166  		txContext := core.NewEVMTxContext(msg)
   167  		context := core.NewEVMBlockContext(block.Header(), b.chain, nil)
   168  		if idx == txIndex {
   169  			return msg, context, statedb, nil
   170  		}
   171  		context.L1CostFunc = core.NewL1CostFunc(b.chainConfig, statedb)
   172  		vmenv := vm.NewEVM(context, txContext, statedb, b.chainConfig, vm.Config{})
   173  		if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
   174  			return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
   175  		}
   176  		statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
   177  	}
   178  	return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, block.Hash())
   179  }
   180  
   181  func TestTraceCall(t *testing.T) {
   182  	t.Parallel()
   183  
   184  	// Initialize test accounts
   185  	accounts := newAccounts(3)
   186  	genesis := &core.Genesis{Alloc: core.GenesisAlloc{
   187  		accounts[0].addr: {Balance: big.NewInt(params.Ether)},
   188  		accounts[1].addr: {Balance: big.NewInt(params.Ether)},
   189  		accounts[2].addr: {Balance: big.NewInt(params.Ether)},
   190  	}}
   191  	genBlocks := 10
   192  	signer := types.HomesteadSigner{}
   193  	api := NewAPI(newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) {
   194  		// Transfer from account[0] to account[1]
   195  		//    value: 1000 wei
   196  		//    fee:   0 wei
   197  		tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, b.BaseFee(), nil), signer, accounts[0].key)
   198  		b.AddTx(tx)
   199  	}))
   200  	var testSuite = []struct {
   201  		blockNumber rpc.BlockNumber
   202  		call        ethapi.TransactionArgs
   203  		config      *TraceCallConfig
   204  		expectErr   error
   205  		expect      string
   206  	}{
   207  		// Standard JSON trace upon the genesis, plain transfer.
   208  		{
   209  			blockNumber: rpc.BlockNumber(0),
   210  			call: ethapi.TransactionArgs{
   211  				From:  &accounts[0].addr,
   212  				To:    &accounts[1].addr,
   213  				Value: (*hexutil.Big)(big.NewInt(1000)),
   214  			},
   215  			config:    nil,
   216  			expectErr: nil,
   217  			expect:    `{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}`,
   218  		},
   219  		// Standard JSON trace upon the head, plain transfer.
   220  		{
   221  			blockNumber: rpc.BlockNumber(genBlocks),
   222  			call: ethapi.TransactionArgs{
   223  				From:  &accounts[0].addr,
   224  				To:    &accounts[1].addr,
   225  				Value: (*hexutil.Big)(big.NewInt(1000)),
   226  			},
   227  			config:    nil,
   228  			expectErr: nil,
   229  			expect:    `{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}`,
   230  		},
   231  		// Standard JSON trace upon the non-existent block, error expects
   232  		{
   233  			blockNumber: rpc.BlockNumber(genBlocks + 1),
   234  			call: ethapi.TransactionArgs{
   235  				From:  &accounts[0].addr,
   236  				To:    &accounts[1].addr,
   237  				Value: (*hexutil.Big)(big.NewInt(1000)),
   238  			},
   239  			config:    nil,
   240  			expectErr: fmt.Errorf("block #%d not found", genBlocks+1),
   241  			//expect:    nil,
   242  		},
   243  		// Standard JSON trace upon the latest block
   244  		{
   245  			blockNumber: rpc.LatestBlockNumber,
   246  			call: ethapi.TransactionArgs{
   247  				From:  &accounts[0].addr,
   248  				To:    &accounts[1].addr,
   249  				Value: (*hexutil.Big)(big.NewInt(1000)),
   250  			},
   251  			config:    nil,
   252  			expectErr: nil,
   253  			expect:    `{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}`,
   254  		},
   255  		// Tracing on 'pending' should fail:
   256  		{
   257  			blockNumber: rpc.PendingBlockNumber,
   258  			call: ethapi.TransactionArgs{
   259  				From:  &accounts[0].addr,
   260  				To:    &accounts[1].addr,
   261  				Value: (*hexutil.Big)(big.NewInt(1000)),
   262  			},
   263  			config:    nil,
   264  			expectErr: errors.New("tracing on top of pending is not supported"),
   265  		},
   266  		{
   267  			blockNumber: rpc.LatestBlockNumber,
   268  			call: ethapi.TransactionArgs{
   269  				From:  &accounts[0].addr,
   270  				Input: &hexutil.Bytes{0x43}, // blocknumber
   271  			},
   272  			config: &TraceCallConfig{
   273  				BlockOverrides: &ethapi.BlockOverrides{Number: (*hexutil.Big)(big.NewInt(0x1337))},
   274  			},
   275  			expectErr: nil,
   276  			expect: ` {"gas":53018,"failed":false,"returnValue":"","structLogs":[
   277  		{"pc":0,"op":"NUMBER","gas":24946984,"gasCost":2,"depth":1,"stack":[]},
   278  		{"pc":1,"op":"STOP","gas":24946982,"gasCost":0,"depth":1,"stack":["0x1337"]}]}`,
   279  		},
   280  	}
   281  	for i, testspec := range testSuite {
   282  		result, err := api.TraceCall(context.Background(), testspec.call, rpc.BlockNumberOrHash{BlockNumber: &testspec.blockNumber}, testspec.config)
   283  		if testspec.expectErr != nil {
   284  			if err == nil {
   285  				t.Errorf("test %d: expect error %v, got nothing", i, testspec.expectErr)
   286  				continue
   287  			}
   288  			if !reflect.DeepEqual(err, testspec.expectErr) {
   289  				t.Errorf("test %d: error mismatch, want %v, git %v", i, testspec.expectErr, err)
   290  			}
   291  		} else {
   292  			if err != nil {
   293  				t.Errorf("test %d: expect no error, got %v", i, err)
   294  				continue
   295  			}
   296  			var have *logger.ExecutionResult
   297  			if err := json.Unmarshal(result.(json.RawMessage), &have); err != nil {
   298  				t.Errorf("test %d: failed to unmarshal result %v", i, err)
   299  			}
   300  			var want *logger.ExecutionResult
   301  			if err := json.Unmarshal([]byte(testspec.expect), &want); err != nil {
   302  				t.Errorf("test %d: failed to unmarshal result %v", i, err)
   303  			}
   304  			if !reflect.DeepEqual(have, want) {
   305  				t.Errorf("test %d: result mismatch, want %v, got %v", i, testspec.expect, string(result.(json.RawMessage)))
   306  			}
   307  		}
   308  	}
   309  }
   310  
   311  func TestTraceTransaction(t *testing.T) {
   312  	t.Parallel()
   313  
   314  	// Initialize test accounts
   315  	accounts := newAccounts(2)
   316  	genesis := &core.Genesis{Alloc: core.GenesisAlloc{
   317  		accounts[0].addr: {Balance: big.NewInt(params.Ether)},
   318  		accounts[1].addr: {Balance: big.NewInt(params.Ether)},
   319  	}}
   320  	target := common.Hash{}
   321  	signer := types.HomesteadSigner{}
   322  	api := NewAPI(newTestBackend(t, 1, genesis, func(i int, b *core.BlockGen) {
   323  		// Transfer from account[0] to account[1]
   324  		//    value: 1000 wei
   325  		//    fee:   0 wei
   326  		tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, b.BaseFee(), nil), signer, accounts[0].key)
   327  		b.AddTx(tx)
   328  		target = tx.Hash()
   329  	}))
   330  	result, err := api.TraceTransaction(context.Background(), target, nil)
   331  	if err != nil {
   332  		t.Errorf("Failed to trace transaction %v", err)
   333  	}
   334  	var have *logger.ExecutionResult
   335  	if err := json.Unmarshal(result.(json.RawMessage), &have); err != nil {
   336  		t.Errorf("failed to unmarshal result %v", err)
   337  	}
   338  	if !reflect.DeepEqual(have, &logger.ExecutionResult{
   339  		Gas:         params.TxGas,
   340  		Failed:      false,
   341  		ReturnValue: "",
   342  		StructLogs:  []logger.StructLogRes{},
   343  	}) {
   344  		t.Error("Transaction tracing result is different")
   345  	}
   346  }
   347  
   348  func TestTraceBlock(t *testing.T) {
   349  	t.Parallel()
   350  
   351  	// Initialize test accounts
   352  	accounts := newAccounts(3)
   353  	genesis := &core.Genesis{Alloc: core.GenesisAlloc{
   354  		accounts[0].addr: {Balance: big.NewInt(params.Ether)},
   355  		accounts[1].addr: {Balance: big.NewInt(params.Ether)},
   356  		accounts[2].addr: {Balance: big.NewInt(params.Ether)},
   357  	}}
   358  	genBlocks := 10
   359  	signer := types.HomesteadSigner{}
   360  	api := NewAPI(newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) {
   361  		// Transfer from account[0] to account[1]
   362  		//    value: 1000 wei
   363  		//    fee:   0 wei
   364  		tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, b.BaseFee(), nil), signer, accounts[0].key)
   365  		b.AddTx(tx)
   366  	}))
   367  
   368  	var testSuite = []struct {
   369  		blockNumber rpc.BlockNumber
   370  		config      *TraceConfig
   371  		want        string
   372  		expectErr   error
   373  	}{
   374  		// Trace genesis block, expect error
   375  		{
   376  			blockNumber: rpc.BlockNumber(0),
   377  			expectErr:   errors.New("genesis is not traceable"),
   378  		},
   379  		// Trace head block
   380  		{
   381  			blockNumber: rpc.BlockNumber(genBlocks),
   382  			want:        `[{"result":{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}}]`,
   383  		},
   384  		// Trace non-existent block
   385  		{
   386  			blockNumber: rpc.BlockNumber(genBlocks + 1),
   387  			expectErr:   fmt.Errorf("block #%d not found", genBlocks+1),
   388  		},
   389  		// Trace latest block
   390  		{
   391  			blockNumber: rpc.LatestBlockNumber,
   392  			want:        `[{"result":{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}}]`,
   393  		},
   394  		// Trace pending block
   395  		{
   396  			blockNumber: rpc.PendingBlockNumber,
   397  			want:        `[{"result":{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}}]`,
   398  		},
   399  	}
   400  	for i, tc := range testSuite {
   401  		result, err := api.TraceBlockByNumber(context.Background(), tc.blockNumber, tc.config)
   402  		if tc.expectErr != nil {
   403  			if err == nil {
   404  				t.Errorf("test %d, want error %v", i, tc.expectErr)
   405  				continue
   406  			}
   407  			if !reflect.DeepEqual(err, tc.expectErr) {
   408  				t.Errorf("test %d: error mismatch, want %v, get %v", i, tc.expectErr, err)
   409  			}
   410  			continue
   411  		}
   412  		if err != nil {
   413  			t.Errorf("test %d, want no error, have %v", i, err)
   414  			continue
   415  		}
   416  		have, _ := json.Marshal(result)
   417  		want := tc.want
   418  		if string(have) != want {
   419  			t.Errorf("test %d, result mismatch, have\n%v\n, want\n%v\n", i, string(have), want)
   420  		}
   421  	}
   422  }
   423  
   424  func TestTracingWithOverrides(t *testing.T) {
   425  	t.Parallel()
   426  	// Initialize test accounts
   427  	accounts := newAccounts(3)
   428  	genesis := &core.Genesis{Alloc: core.GenesisAlloc{
   429  		accounts[0].addr: {Balance: big.NewInt(params.Ether)},
   430  		accounts[1].addr: {Balance: big.NewInt(params.Ether)},
   431  		accounts[2].addr: {Balance: big.NewInt(params.Ether)},
   432  	}}
   433  	genBlocks := 10
   434  	signer := types.HomesteadSigner{}
   435  	api := NewAPI(newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) {
   436  		// Transfer from account[0] to account[1]
   437  		//    value: 1000 wei
   438  		//    fee:   0 wei
   439  		tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, b.BaseFee(), nil), signer, accounts[0].key)
   440  		b.AddTx(tx)
   441  	}))
   442  	randomAccounts := newAccounts(3)
   443  	type res struct {
   444  		Gas         int
   445  		Failed      bool
   446  		ReturnValue string
   447  	}
   448  	var testSuite = []struct {
   449  		blockNumber rpc.BlockNumber
   450  		call        ethapi.TransactionArgs
   451  		config      *TraceCallConfig
   452  		expectErr   error
   453  		want        string
   454  	}{
   455  		// Call which can only succeed if state is state overridden
   456  		{
   457  			blockNumber: rpc.LatestBlockNumber,
   458  			call: ethapi.TransactionArgs{
   459  				From:  &randomAccounts[0].addr,
   460  				To:    &randomAccounts[1].addr,
   461  				Value: (*hexutil.Big)(big.NewInt(1000)),
   462  			},
   463  			config: &TraceCallConfig{
   464  				StateOverrides: &ethapi.StateOverride{
   465  					randomAccounts[0].addr: ethapi.OverrideAccount{Balance: newRPCBalance(new(big.Int).Mul(big.NewInt(1), big.NewInt(params.Ether)))},
   466  				},
   467  			},
   468  			want: `{"gas":21000,"failed":false,"returnValue":""}`,
   469  		},
   470  		// Invalid call without state overriding
   471  		{
   472  			blockNumber: rpc.LatestBlockNumber,
   473  			call: ethapi.TransactionArgs{
   474  				From:  &randomAccounts[0].addr,
   475  				To:    &randomAccounts[1].addr,
   476  				Value: (*hexutil.Big)(big.NewInt(1000)),
   477  			},
   478  			config:    &TraceCallConfig{},
   479  			expectErr: core.ErrInsufficientFunds,
   480  		},
   481  		// Successful simple contract call
   482  		//
   483  		// // SPDX-License-Identifier: GPL-3.0
   484  		//
   485  		//  pragma solidity >=0.7.0 <0.8.0;
   486  		//
   487  		//  /**
   488  		//   * @title Storage
   489  		//   * @dev Store & retrieve value in a variable
   490  		//   */
   491  		//  contract Storage {
   492  		//      uint256 public number;
   493  		//      constructor() {
   494  		//          number = block.number;
   495  		//      }
   496  		//  }
   497  		{
   498  			blockNumber: rpc.LatestBlockNumber,
   499  			call: ethapi.TransactionArgs{
   500  				From: &randomAccounts[0].addr,
   501  				To:   &randomAccounts[2].addr,
   502  				Data: newRPCBytes(common.Hex2Bytes("8381f58a")), // call number()
   503  			},
   504  			config: &TraceCallConfig{
   505  				//Tracer: &tracer,
   506  				StateOverrides: &ethapi.StateOverride{
   507  					randomAccounts[2].addr: ethapi.OverrideAccount{
   508  						Code:      newRPCBytes(common.Hex2Bytes("6080604052348015600f57600080fd5b506004361060285760003560e01c80638381f58a14602d575b600080fd5b60336049565b6040518082815260200191505060405180910390f35b6000548156fea2646970667358221220eab35ffa6ab2adfe380772a48b8ba78e82a1b820a18fcb6f59aa4efb20a5f60064736f6c63430007040033")),
   509  						StateDiff: newStates([]common.Hash{{}}, []common.Hash{common.BigToHash(big.NewInt(123))}),
   510  					},
   511  				},
   512  			},
   513  			want: `{"gas":23347,"failed":false,"returnValue":"000000000000000000000000000000000000000000000000000000000000007b"}`,
   514  		},
   515  		{ // Override blocknumber
   516  			blockNumber: rpc.LatestBlockNumber,
   517  			call: ethapi.TransactionArgs{
   518  				From: &accounts[0].addr,
   519  				// BLOCKNUMBER PUSH1 MSTORE
   520  				Input: newRPCBytes(common.Hex2Bytes("4360005260206000f3")),
   521  				//&hexutil.Bytes{0x43}, // blocknumber
   522  			},
   523  			config: &TraceCallConfig{
   524  				BlockOverrides: &ethapi.BlockOverrides{Number: (*hexutil.Big)(big.NewInt(0x1337))},
   525  			},
   526  			want: `{"gas":59537,"failed":false,"returnValue":"0000000000000000000000000000000000000000000000000000000000001337"}`,
   527  		},
   528  		{ // Override blocknumber, and query a blockhash
   529  			blockNumber: rpc.LatestBlockNumber,
   530  			call: ethapi.TransactionArgs{
   531  				From: &accounts[0].addr,
   532  				Input: &hexutil.Bytes{
   533  					0x60, 0x00, 0x40, // BLOCKHASH(0)
   534  					0x60, 0x00, 0x52, // STORE memory offset 0
   535  					0x61, 0x13, 0x36, 0x40, // BLOCKHASH(0x1336)
   536  					0x60, 0x20, 0x52, // STORE memory offset 32
   537  					0x61, 0x13, 0x37, 0x40, // BLOCKHASH(0x1337)
   538  					0x60, 0x40, 0x52, // STORE memory offset 64
   539  					0x60, 0x60, 0x60, 0x00, 0xf3, // RETURN (0-96)
   540  
   541  				}, // blocknumber
   542  			},
   543  			config: &TraceCallConfig{
   544  				BlockOverrides: &ethapi.BlockOverrides{Number: (*hexutil.Big)(big.NewInt(0x1337))},
   545  			},
   546  			want: `{"gas":72666,"failed":false,"returnValue":"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"}`,
   547  		},
   548  	}
   549  	for i, tc := range testSuite {
   550  		result, err := api.TraceCall(context.Background(), tc.call, rpc.BlockNumberOrHash{BlockNumber: &tc.blockNumber}, tc.config)
   551  		if tc.expectErr != nil {
   552  			if err == nil {
   553  				t.Errorf("test %d: want error %v, have nothing", i, tc.expectErr)
   554  				continue
   555  			}
   556  			if !errors.Is(err, tc.expectErr) {
   557  				t.Errorf("test %d: error mismatch, want %v, have %v", i, tc.expectErr, err)
   558  			}
   559  			continue
   560  		}
   561  		if err != nil {
   562  			t.Errorf("test %d: want no error, have %v", i, err)
   563  			continue
   564  		}
   565  		// Turn result into res-struct
   566  		var (
   567  			have res
   568  			want res
   569  		)
   570  		resBytes, _ := json.Marshal(result)
   571  		json.Unmarshal(resBytes, &have)
   572  		json.Unmarshal([]byte(tc.want), &want)
   573  		if !reflect.DeepEqual(have, want) {
   574  			t.Errorf("test %d, result mismatch, have\n%v\n, want\n%v\n", i, string(resBytes), want)
   575  		}
   576  	}
   577  }
   578  
   579  type Account struct {
   580  	key  *ecdsa.PrivateKey
   581  	addr common.Address
   582  }
   583  
   584  type Accounts []Account
   585  
   586  func (a Accounts) Len() int           { return len(a) }
   587  func (a Accounts) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
   588  func (a Accounts) Less(i, j int) bool { return bytes.Compare(a[i].addr.Bytes(), a[j].addr.Bytes()) < 0 }
   589  
   590  func newAccounts(n int) (accounts Accounts) {
   591  	for i := 0; i < n; i++ {
   592  		key, _ := crypto.GenerateKey()
   593  		addr := crypto.PubkeyToAddress(key.PublicKey)
   594  		accounts = append(accounts, Account{key: key, addr: addr})
   595  	}
   596  	sort.Sort(accounts)
   597  	return accounts
   598  }
   599  
   600  func newRPCBalance(balance *big.Int) **hexutil.Big {
   601  	rpcBalance := (*hexutil.Big)(balance)
   602  	return &rpcBalance
   603  }
   604  
   605  func newRPCBytes(bytes []byte) *hexutil.Bytes {
   606  	rpcBytes := hexutil.Bytes(bytes)
   607  	return &rpcBytes
   608  }
   609  
   610  func newStates(keys []common.Hash, vals []common.Hash) *map[common.Hash]common.Hash {
   611  	if len(keys) != len(vals) {
   612  		panic("invalid input")
   613  	}
   614  	m := make(map[common.Hash]common.Hash)
   615  	for i := 0; i < len(keys); i++ {
   616  		m[keys[i]] = vals[i]
   617  	}
   618  	return &m
   619  }