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