github.com/fff-chain/go-fff@v0.0.0-20220726032732-1c84420b8a99/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/fff-chain/go-fff/common"
    33  	"github.com/fff-chain/go-fff/common/hexutil"
    34  	"github.com/fff-chain/go-fff/consensus"
    35  	"github.com/fff-chain/go-fff/consensus/ethash"
    36  	"github.com/fff-chain/go-fff/core"
    37  	"github.com/fff-chain/go-fff/core/rawdb"
    38  	"github.com/fff-chain/go-fff/core/state"
    39  	"github.com/fff-chain/go-fff/core/types"
    40  	"github.com/fff-chain/go-fff/core/vm"
    41  	"github.com/fff-chain/go-fff/crypto"
    42  	"github.com/fff-chain/go-fff/ethdb"
    43  	"github.com/fff-chain/go-fff/internal/ethapi"
    44  	"github.com/fff-chain/go-fff/params"
    45  	"github.com/fff-chain/go-fff/rpc"
    46  )
    47  
    48  var (
    49  	errStateNotFound       = errors.New("state not found")
    50  	errBlockNotFound       = errors.New("block not found")
    51  	errTransactionNotFound = errors.New("transaction not found")
    52  )
    53  
    54  type testBackend struct {
    55  	chainConfig *params.ChainConfig
    56  	engine      consensus.Engine
    57  	chaindb     ethdb.Database
    58  	chain       *core.BlockChain
    59  }
    60  
    61  func newTestBackend(t *testing.T, n int, gspec *core.Genesis, generator func(i int, b *core.BlockGen)) *testBackend {
    62  	backend := &testBackend{
    63  		chainConfig: params.TestChainConfig,
    64  		engine:      ethash.NewFaker(),
    65  		chaindb:     rawdb.NewMemoryDatabase(),
    66  	}
    67  	// Generate blocks for testing
    68  	gspec.Config = backend.chainConfig
    69  	var (
    70  		gendb   = rawdb.NewMemoryDatabase()
    71  		genesis = gspec.MustCommit(gendb)
    72  	)
    73  	blocks, _ := core.GenerateChain(backend.chainConfig, genesis, backend.engine, gendb, n, generator)
    74  
    75  	// Import the canonical chain
    76  	gspec.MustCommit(backend.chaindb)
    77  	cacheConfig := &core.CacheConfig{
    78  		TrieCleanLimit:    256,
    79  		TrieDirtyLimit:    256,
    80  		TrieTimeLimit:     5 * time.Minute,
    81  		SnapshotLimit:     0,
    82  		TriesInMemory:     128,
    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)
   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  		vmenv := vm.NewEVM(context, txContext, statedb, b.chainConfig, vm.Config{})
   172  		if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
   173  			return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
   174  		}
   175  		statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
   176  	}
   177  	return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, block.Hash())
   178  }
   179  
   180  func TestTraceCall(t *testing.T) {
   181  	t.Parallel()
   182  
   183  	// Initialize test accounts
   184  	accounts := newAccounts(3)
   185  	genesis := &core.Genesis{Alloc: core.GenesisAlloc{
   186  		accounts[0].addr: {Balance: big.NewInt(params.Ether)},
   187  		accounts[1].addr: {Balance: big.NewInt(params.Ether)},
   188  		accounts[2].addr: {Balance: big.NewInt(params.Ether)},
   189  	}}
   190  	genBlocks := 10
   191  	signer := types.HomesteadSigner{}
   192  	api := NewAPI(newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) {
   193  		// Transfer from account[0] to account[1]
   194  		//    value: 1000 wei
   195  		//    fee:   0 wei
   196  		tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, big.NewInt(0), nil), signer, accounts[0].key)
   197  		b.AddTx(tx)
   198  	}))
   199  
   200  	var testSuite = []struct {
   201  		blockNumber rpc.BlockNumber
   202  		call        ethapi.CallArgs
   203  		config      *TraceCallConfig
   204  		expectErr   error
   205  		expect      interface{}
   206  	}{
   207  		// Standard JSON trace upon the genesis, plain transfer.
   208  		{
   209  			blockNumber: rpc.BlockNumber(0),
   210  			call: ethapi.CallArgs{
   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: &ethapi.ExecutionResult{
   218  				Gas:         params.TxGas,
   219  				Failed:      false,
   220  				ReturnValue: "",
   221  				StructLogs:  []ethapi.StructLogRes{},
   222  			},
   223  		},
   224  		// Standard JSON trace upon the head, plain transfer.
   225  		{
   226  			blockNumber: rpc.BlockNumber(genBlocks),
   227  			call: ethapi.CallArgs{
   228  				From:  &accounts[0].addr,
   229  				To:    &accounts[1].addr,
   230  				Value: (*hexutil.Big)(big.NewInt(1000)),
   231  			},
   232  			config:    nil,
   233  			expectErr: nil,
   234  			expect: &ethapi.ExecutionResult{
   235  				Gas:         params.TxGas,
   236  				Failed:      false,
   237  				ReturnValue: "",
   238  				StructLogs:  []ethapi.StructLogRes{},
   239  			},
   240  		},
   241  		// Standard JSON trace upon the non-existent block, error expects
   242  		{
   243  			blockNumber: rpc.BlockNumber(genBlocks + 1),
   244  			call: ethapi.CallArgs{
   245  				From:  &accounts[0].addr,
   246  				To:    &accounts[1].addr,
   247  				Value: (*hexutil.Big)(big.NewInt(1000)),
   248  			},
   249  			config:    nil,
   250  			expectErr: fmt.Errorf("block #%d not found", genBlocks+1),
   251  			expect:    nil,
   252  		},
   253  		// Standard JSON trace upon the latest block
   254  		{
   255  			blockNumber: rpc.LatestBlockNumber,
   256  			call: ethapi.CallArgs{
   257  				From:  &accounts[0].addr,
   258  				To:    &accounts[1].addr,
   259  				Value: (*hexutil.Big)(big.NewInt(1000)),
   260  			},
   261  			config:    nil,
   262  			expectErr: nil,
   263  			expect: &ethapi.ExecutionResult{
   264  				Gas:         params.TxGas,
   265  				Failed:      false,
   266  				ReturnValue: "",
   267  				StructLogs:  []ethapi.StructLogRes{},
   268  			},
   269  		},
   270  		// Standard JSON trace upon the pending block
   271  		{
   272  			blockNumber: rpc.PendingBlockNumber,
   273  			call: ethapi.CallArgs{
   274  				From:  &accounts[0].addr,
   275  				To:    &accounts[1].addr,
   276  				Value: (*hexutil.Big)(big.NewInt(1000)),
   277  			},
   278  			config:    nil,
   279  			expectErr: nil,
   280  			expect: &ethapi.ExecutionResult{
   281  				Gas:         params.TxGas,
   282  				Failed:      false,
   283  				ReturnValue: "",
   284  				StructLogs:  []ethapi.StructLogRes{},
   285  			},
   286  		},
   287  	}
   288  	for _, testspec := range testSuite {
   289  		result, err := api.TraceCall(context.Background(), testspec.call, rpc.BlockNumberOrHash{BlockNumber: &testspec.blockNumber}, testspec.config)
   290  		if testspec.expectErr != nil {
   291  			if err == nil {
   292  				t.Errorf("Expect error %v, get nothing", testspec.expectErr)
   293  				continue
   294  			}
   295  			if !reflect.DeepEqual(err, testspec.expectErr) {
   296  				t.Errorf("Error mismatch, want %v, get %v", testspec.expectErr, err)
   297  			}
   298  		} else {
   299  			if err != nil {
   300  				t.Errorf("Expect no error, get %v", err)
   301  				continue
   302  			}
   303  			if !reflect.DeepEqual(result, testspec.expect) {
   304  				t.Errorf("Result mismatch, want %v, get %v", testspec.expect, result)
   305  			}
   306  		}
   307  	}
   308  }
   309  
   310  func TestTraceTransaction(t *testing.T) {
   311  	t.Parallel()
   312  
   313  	// Initialize test accounts
   314  	accounts := newAccounts(2)
   315  	genesis := &core.Genesis{Alloc: core.GenesisAlloc{
   316  		accounts[0].addr: {Balance: big.NewInt(params.Ether)},
   317  		accounts[1].addr: {Balance: big.NewInt(params.Ether)},
   318  	}}
   319  	target := common.Hash{}
   320  	signer := types.HomesteadSigner{}
   321  	api := NewAPI(newTestBackend(t, 1, genesis, func(i int, b *core.BlockGen) {
   322  		// Transfer from account[0] to account[1]
   323  		//    value: 1000 wei
   324  		//    fee:   0 wei
   325  		tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, big.NewInt(0), nil), signer, accounts[0].key)
   326  		b.AddTx(tx)
   327  		target = tx.Hash()
   328  	}))
   329  	result, err := api.TraceTransaction(context.Background(), target, nil)
   330  	if err != nil {
   331  		t.Errorf("Failed to trace transaction %v", err)
   332  	}
   333  	if !reflect.DeepEqual(result, &ethapi.ExecutionResult{
   334  		Gas:         params.TxGas,
   335  		Failed:      false,
   336  		ReturnValue: "",
   337  		StructLogs:  []ethapi.StructLogRes{},
   338  	}) {
   339  		t.Error("Transaction tracing result is different")
   340  	}
   341  }
   342  
   343  func TestTraceBlock(t *testing.T) {
   344  	t.Parallel()
   345  
   346  	// Initialize test accounts
   347  	accounts := newAccounts(3)
   348  	genesis := &core.Genesis{Alloc: core.GenesisAlloc{
   349  		accounts[0].addr: {Balance: big.NewInt(params.Ether)},
   350  		accounts[1].addr: {Balance: big.NewInt(params.Ether)},
   351  		accounts[2].addr: {Balance: big.NewInt(params.Ether)},
   352  	}}
   353  	genBlocks := 10
   354  	signer := types.HomesteadSigner{}
   355  	api := NewAPI(newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) {
   356  		// Transfer from account[0] to account[1]
   357  		//    value: 1000 wei
   358  		//    fee:   0 wei
   359  		tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, big.NewInt(0), nil), signer, accounts[0].key)
   360  		b.AddTx(tx)
   361  	}))
   362  
   363  	var testSuite = []struct {
   364  		blockNumber rpc.BlockNumber
   365  		config      *TraceConfig
   366  		want        string
   367  		expectErr   error
   368  	}{
   369  		// Trace genesis block, expect error
   370  		{
   371  			blockNumber: rpc.BlockNumber(0),
   372  			expectErr:   errors.New("genesis is not traceable"),
   373  		},
   374  		// Trace head block
   375  		{
   376  			blockNumber: rpc.BlockNumber(genBlocks),
   377  			want:        `[{"result":{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}}]`,
   378  		},
   379  		// Trace non-existent block
   380  		{
   381  			blockNumber: rpc.BlockNumber(genBlocks + 1),
   382  			expectErr:   fmt.Errorf("block #%d not found", genBlocks+1),
   383  		},
   384  		// Trace latest block
   385  		{
   386  			blockNumber: rpc.LatestBlockNumber,
   387  			want:        `[{"result":{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}}]`,
   388  		},
   389  		// Trace pending block
   390  		{
   391  			blockNumber: rpc.PendingBlockNumber,
   392  			want:        `[{"result":{"gas":21000,"failed":false,"returnValue":"","structLogs":[]}}]`,
   393  		},
   394  	}
   395  	for i, tc := range testSuite {
   396  		result, err := api.TraceBlockByNumber(context.Background(), tc.blockNumber, tc.config)
   397  		if tc.expectErr != nil {
   398  			if err == nil {
   399  				t.Errorf("test %d, want error %v", i, tc.expectErr)
   400  				continue
   401  			}
   402  			if !reflect.DeepEqual(err, tc.expectErr) {
   403  				t.Errorf("test %d: error mismatch, want %v, get %v", i, tc.expectErr, err)
   404  			}
   405  			continue
   406  		}
   407  		if err != nil {
   408  			t.Errorf("test %d, want no error, have %v", i, err)
   409  			continue
   410  		}
   411  		have, _ := json.Marshal(result)
   412  		want := tc.want
   413  		if string(have) != want {
   414  			t.Errorf("test %d, result mismatch, have\n%v\n, want\n%v\n", i, string(have), want)
   415  		}
   416  	}
   417  }
   418  
   419  func TestTracingWithOverrides(t *testing.T) {
   420  	t.Parallel()
   421  	// Initialize test accounts
   422  	accounts := newAccounts(3)
   423  	genesis := &core.Genesis{Alloc: core.GenesisAlloc{
   424  		accounts[0].addr: {Balance: big.NewInt(params.Ether)},
   425  		accounts[1].addr: {Balance: big.NewInt(params.Ether)},
   426  		accounts[2].addr: {Balance: big.NewInt(params.Ether)},
   427  	}}
   428  	genBlocks := 10
   429  	signer := types.HomesteadSigner{}
   430  	api := NewAPI(newTestBackend(t, genBlocks, genesis, func(i int, b *core.BlockGen) {
   431  		// Transfer from account[0] to account[1]
   432  		//    value: 1000 wei
   433  		//    fee:   0 wei
   434  		tx, _ := types.SignTx(types.NewTransaction(uint64(i), accounts[1].addr, big.NewInt(1000), params.TxGas, big.NewInt(0), nil), signer, accounts[0].key)
   435  		b.AddTx(tx)
   436  	}))
   437  	randomAccounts := newAccounts(3)
   438  	type res struct {
   439  		Gas         int
   440  		Failed      bool
   441  		returnValue string
   442  	}
   443  	var testSuite = []struct {
   444  		blockNumber rpc.BlockNumber
   445  		call        ethapi.CallArgs
   446  		config      *TraceCallConfig
   447  		expectErr   error
   448  		want        string
   449  	}{
   450  		// Call which can only succeed if state is state overridden
   451  		{
   452  			blockNumber: rpc.PendingBlockNumber,
   453  			call: ethapi.CallArgs{
   454  				From:  &randomAccounts[0].addr,
   455  				To:    &randomAccounts[1].addr,
   456  				Value: (*hexutil.Big)(big.NewInt(1000)),
   457  			},
   458  			config: &TraceCallConfig{
   459  				StateOverrides: &ethapi.StateOverride{
   460  					randomAccounts[0].addr: ethapi.OverrideAccount{Balance: newRPCBalance(new(big.Int).Mul(big.NewInt(1), big.NewInt(params.Ether)))},
   461  				},
   462  			},
   463  			want: `{"gas":21000,"failed":false,"returnValue":""}`,
   464  		},
   465  		// Invalid call without state overriding
   466  		{
   467  			blockNumber: rpc.PendingBlockNumber,
   468  			call: ethapi.CallArgs{
   469  				From:  &randomAccounts[0].addr,
   470  				To:    &randomAccounts[1].addr,
   471  				Value: (*hexutil.Big)(big.NewInt(1000)),
   472  			},
   473  			config:    &TraceCallConfig{},
   474  			expectErr: core.ErrInsufficientFundsForTransfer,
   475  		},
   476  		// Successful simple contract call
   477  		//
   478  		// // SPDX-License-Identifier: GPL-3.0
   479  		//
   480  		//  pragma solidity >=0.7.0 <0.8.0;
   481  		//
   482  		//  /**
   483  		//   * @title Storage
   484  		//   * @dev Store & retrieve value in a variable
   485  		//   */
   486  		//  contract Storage {
   487  		//      uint256 public number;
   488  		//      constructor() {
   489  		//          number = block.number;
   490  		//      }
   491  		//  }
   492  		{
   493  			blockNumber: rpc.PendingBlockNumber,
   494  			call: ethapi.CallArgs{
   495  				From: &randomAccounts[0].addr,
   496  				To:   &randomAccounts[2].addr,
   497  				Data: newRPCBytes(common.Hex2Bytes("8381f58a")), // call number()
   498  			},
   499  			config: &TraceCallConfig{
   500  				//Tracer: &tracer,
   501  				StateOverrides: &ethapi.StateOverride{
   502  					randomAccounts[2].addr: ethapi.OverrideAccount{
   503  						Code:      newRPCBytes(common.Hex2Bytes("6080604052348015600f57600080fd5b506004361060285760003560e01c80638381f58a14602d575b600080fd5b60336049565b6040518082815260200191505060405180910390f35b6000548156fea2646970667358221220eab35ffa6ab2adfe380772a48b8ba78e82a1b820a18fcb6f59aa4efb20a5f60064736f6c63430007040033")),
   504  						StateDiff: newStates([]common.Hash{{}}, []common.Hash{common.BigToHash(big.NewInt(123))}),
   505  					},
   506  				},
   507  			},
   508  			want: `{"gas":23347,"failed":false,"returnValue":"000000000000000000000000000000000000000000000000000000000000007b"}`,
   509  		},
   510  	}
   511  	for i, tc := range testSuite {
   512  		result, err := api.TraceCall(context.Background(), tc.call, rpc.BlockNumberOrHash{BlockNumber: &tc.blockNumber}, tc.config)
   513  		if tc.expectErr != nil {
   514  			if err == nil {
   515  				t.Errorf("test %d: want error %v, have nothing", i, tc.expectErr)
   516  				continue
   517  			}
   518  			if !errors.Is(err, tc.expectErr) {
   519  				t.Errorf("test %d: error mismatch, want %v, have %v", i, tc.expectErr, err)
   520  			}
   521  			continue
   522  		}
   523  		if err != nil {
   524  			t.Errorf("test %d: want no error, have %v", i, err)
   525  			continue
   526  		}
   527  		// Turn result into res-struct
   528  		var (
   529  			have res
   530  			want res
   531  		)
   532  		resBytes, _ := json.Marshal(result)
   533  		json.Unmarshal(resBytes, &have)
   534  		json.Unmarshal([]byte(tc.want), &want)
   535  		if !reflect.DeepEqual(have, want) {
   536  			t.Errorf("test %d, result mismatch, have\n%v\n, want\n%v\n", i, string(resBytes), want)
   537  		}
   538  	}
   539  }
   540  
   541  type Account struct {
   542  	key  *ecdsa.PrivateKey
   543  	addr common.Address
   544  }
   545  
   546  type Accounts []Account
   547  
   548  func (a Accounts) Len() int           { return len(a) }
   549  func (a Accounts) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
   550  func (a Accounts) Less(i, j int) bool { return bytes.Compare(a[i].addr.Bytes(), a[j].addr.Bytes()) < 0 }
   551  
   552  func newAccounts(n int) (accounts Accounts) {
   553  	for i := 0; i < n; i++ {
   554  		key, _ := crypto.GenerateKey()
   555  		addr := crypto.PubkeyToAddress(key.PublicKey)
   556  		accounts = append(accounts, Account{key: key, addr: addr})
   557  	}
   558  	sort.Sort(accounts)
   559  	return accounts
   560  }
   561  
   562  func newRPCBalance(balance *big.Int) **hexutil.Big {
   563  	rpcBalance := (*hexutil.Big)(balance)
   564  	return &rpcBalance
   565  }
   566  
   567  func newRPCBytes(bytes []byte) *hexutil.Bytes {
   568  	rpcBytes := hexutil.Bytes(bytes)
   569  	return &rpcBytes
   570  }
   571  
   572  func newStates(keys []common.Hash, vals []common.Hash) *map[common.Hash]common.Hash {
   573  	if len(keys) != len(vals) {
   574  		panic("invalid input")
   575  	}
   576  	m := make(map[common.Hash]common.Hash)
   577  	for i := 0; i < len(keys); i++ {
   578  		m[keys[i]] = vals[i]
   579  	}
   580  	return &m
   581  }