github.com/ethereum/go-ethereum@v1.16.1/eth/tracers/js/tracer_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 js
    18  
    19  import (
    20  	"encoding/json"
    21  	"errors"
    22  	"math/big"
    23  	"strings"
    24  	"testing"
    25  	"time"
    26  
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/core/state"
    29  	"github.com/ethereum/go-ethereum/core/types"
    30  	"github.com/ethereum/go-ethereum/core/vm"
    31  	"github.com/ethereum/go-ethereum/eth/tracers"
    32  	"github.com/ethereum/go-ethereum/params"
    33  	"github.com/holiman/uint256"
    34  )
    35  
    36  type dummyStatedb struct {
    37  	state.StateDB
    38  }
    39  
    40  func (*dummyStatedb) GetRefund() uint64                           { return 1337 }
    41  func (*dummyStatedb) GetBalance(addr common.Address) *uint256.Int { return new(uint256.Int) }
    42  
    43  type vmContext struct {
    44  	blockCtx vm.BlockContext
    45  	txCtx    vm.TxContext
    46  }
    47  
    48  func testCtx() *vmContext {
    49  	return &vmContext{blockCtx: vm.BlockContext{BlockNumber: big.NewInt(1), BaseFee: big.NewInt(0)}, txCtx: vm.TxContext{GasPrice: big.NewInt(100000)}}
    50  }
    51  
    52  func runTrace(tracer *tracers.Tracer, vmctx *vmContext, chaincfg *params.ChainConfig, contractCode []byte) (json.RawMessage, error) {
    53  	var (
    54  		evm             = vm.NewEVM(vmctx.blockCtx, &dummyStatedb{}, chaincfg, vm.Config{Tracer: tracer.Hooks})
    55  		gasLimit uint64 = 31000
    56  		startGas uint64 = 10000
    57  		value           = uint256.NewInt(0)
    58  		contract        = vm.NewContract(common.Address{}, common.Address{}, value, startGas, nil)
    59  	)
    60  	evm.SetTxContext(vmctx.txCtx)
    61  	contract.Code = []byte{byte(vm.PUSH1), 0x1, byte(vm.PUSH1), 0x1, 0x0}
    62  	if contractCode != nil {
    63  		contract.Code = contractCode
    64  	}
    65  
    66  	tracer.OnTxStart(evm.GetVMContext(), types.NewTx(&types.LegacyTx{Gas: gasLimit, GasPrice: vmctx.txCtx.GasPrice}), contract.Caller())
    67  	tracer.OnEnter(0, byte(vm.CALL), contract.Caller(), contract.Address(), []byte{}, startGas, value.ToBig())
    68  	ret, err := evm.Interpreter().Run(contract, []byte{}, false)
    69  	tracer.OnExit(0, ret, startGas-contract.Gas, err, true)
    70  	// Rest gas assumes no refund
    71  	tracer.OnTxEnd(&types.Receipt{GasUsed: gasLimit - contract.Gas}, nil)
    72  	if err != nil {
    73  		return nil, err
    74  	}
    75  	return tracer.GetResult()
    76  }
    77  
    78  func TestTracer(t *testing.T) {
    79  	execTracer := func(code string, contract []byte) ([]byte, string) {
    80  		t.Helper()
    81  		chainConfig := params.TestChainConfig
    82  		tracer, err := newJsTracer(code, nil, nil, chainConfig)
    83  		if err != nil {
    84  			t.Fatal(err)
    85  		}
    86  		ret, err := runTrace(tracer, testCtx(), chainConfig, contract)
    87  		if err != nil {
    88  			return nil, err.Error() // Stringify to allow comparison without nil checks
    89  		}
    90  		return ret, ""
    91  	}
    92  	for i, tt := range []struct {
    93  		code     string
    94  		want     string
    95  		fail     string
    96  		contract []byte
    97  	}{
    98  		{ // tests that we don't panic on bad arguments to memory access
    99  			code: "{depths: [], step: function(log) { this.depths.push(log.memory.slice(-1,-2)); }, fault: function() {}, result: function() { return this.depths; }}",
   100  			want: ``,
   101  			fail: "tracer accessed out of bound memory: offset -1, end -2 at step (<eval>:1:53(13))    in server-side tracer function 'step'",
   102  		}, { // tests that we don't panic on bad arguments to stack peeks
   103  			code: "{depths: [], step: function(log) { this.depths.push(log.stack.peek(-1)); }, fault: function() {}, result: function() { return this.depths; }}",
   104  			want: ``,
   105  			fail: "tracer accessed out of bound stack: size 0, index -1 at step (<eval>:1:53(11))    in server-side tracer function 'step'",
   106  		}, { //  tests that we don't panic on bad arguments to memory getUint
   107  			code: "{ depths: [], step: function(log, db) { this.depths.push(log.memory.getUint(-64));}, fault: function() {}, result: function() { return this.depths; }}",
   108  			want: ``,
   109  			fail: "tracer accessed out of bound memory: available 0, offset -64, size 32 at step (<eval>:1:58(11))    in server-side tracer function 'step'",
   110  		}, { // tests some general counting
   111  			code: "{count: 0, step: function() { this.count += 1; }, fault: function() {}, result: function() { return this.count; }}",
   112  			want: `3`,
   113  		}, { // tests that depth is reported correctly
   114  			code: "{depths: [], step: function(log) { this.depths.push(log.stack.length()); }, fault: function() {}, result: function() { return this.depths; }}",
   115  			want: `[0,1,2]`,
   116  		}, { // tests memory length
   117  			code: "{lengths: [], step: function(log) { this.lengths.push(log.memory.length()); }, fault: function() {}, result: function() { return this.lengths; }}",
   118  			want: `[0,0,0]`,
   119  		}, { // tests to-string of opcodes
   120  			code: "{opcodes: [], step: function(log) { this.opcodes.push(log.op.toString()); }, fault: function() {}, result: function() { return this.opcodes; }}",
   121  			want: `["PUSH1","PUSH1","STOP"]`,
   122  		}, { // tests gasUsed
   123  			code: "{depths: [], step: function() {}, fault: function() {}, result: function(ctx) { return ctx.gasPrice+'.'+ctx.gasUsed; }}",
   124  			want: `"100000.21006"`,
   125  		}, { // tests toWord with byte array length < 32
   126  			code: "{res: null, step: function(log) {}, fault: function() {}, result: function() { return toWord('0xffaa') }}",
   127  			want: `{"0":0,"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":255,"31":170}`,
   128  		}, { // tests toWord with byte array length = 32
   129  			code: "{step: function() {}, fault: function() {}, result: function() { return toWord('0x1234567890123456789012345678901234567890123456789012345678901234'); }}",
   130  			want: `{"0":18,"1":52,"2":86,"3":120,"4":144,"5":18,"6":52,"7":86,"8":120,"9":144,"10":18,"11":52,"12":86,"13":120,"14":144,"15":18,"16":52,"17":86,"18":120,"19":144,"20":18,"21":52,"22":86,"23":120,"24":144,"25":18,"26":52,"27":86,"28":120,"29":144,"30":18,"31":52}`,
   131  		}, { // tests toWord with byte array length > 32
   132  			code: "{step: function() {}, fault: function() {}, result: function() { return toWord('0x1234567890123456789012345678901234567890123456789012345678901234567890'); }}",
   133  			want: `{"0":120,"1":144,"2":18,"3":52,"4":86,"5":120,"6":144,"7":18,"8":52,"9":86,"10":120,"11":144,"12":18,"13":52,"14":86,"15":120,"16":144,"17":18,"18":52,"19":86,"20":120,"21":144,"22":18,"23":52,"24":86,"25":120,"26":144,"27":18,"28":52,"29":86,"30":120,"31":144}`,
   134  		}, { // test feeding a buffer back into go
   135  			code: "{res: null, step: function(log) { var address = log.contract.getAddress(); this.res = toAddress(address); }, fault: function() {}, result: function() { return this.res }}",
   136  			want: `{"0":0,"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0}`,
   137  		}, {
   138  			code: "{res: null, step: function(log) { var address = '0x0000000000000000000000000000000000000000'; this.res = toAddress(address); }, fault: function() {}, result: function() { return this.res }}",
   139  			want: `{"0":0,"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0}`,
   140  		}, {
   141  			code: "{res: null, step: function(log) { var address = Array.prototype.slice.call(log.contract.getAddress()); this.res = toAddress(address); }, fault: function() {}, result: function() { return this.res }}",
   142  			want: `{"0":0,"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0}`,
   143  		}, {
   144  			code:     "{res: [], step: function(log) { var op = log.op.toString(); if (op === 'MSTORE8' || op === 'STOP') { this.res.push(log.memory.slice(0, 2)) } }, fault: function() {}, result: function() { return this.res }}",
   145  			want:     `[{"0":0,"1":0},{"0":255,"1":0}]`,
   146  			contract: []byte{byte(vm.PUSH1), byte(0xff), byte(vm.PUSH1), byte(0x00), byte(vm.MSTORE8), byte(vm.STOP)},
   147  		}, {
   148  			code:     "{res: [], step: function(log) { if (log.op.toString() === 'STOP') { this.res.push(log.memory.slice(5, 1025 * 1024)) } }, fault: function() {}, result: function() { return this.res }}",
   149  			want:     "",
   150  			fail:     "reached limit for padding memory slice: 1049568 at step (<eval>:1:83(20))    in server-side tracer function 'step'",
   151  			contract: []byte{byte(vm.PUSH1), byte(0xff), byte(vm.PUSH1), byte(0x00), byte(vm.MSTORE8), byte(vm.STOP)},
   152  		}, { // tests ctx.coinbase
   153  			code: "{lengths: [], step: function(log) { }, fault: function() {}, result: function(ctx) { var coinbase = ctx.coinbase; return toAddress(coinbase); }}",
   154  			want: `{"0":0,"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0}`,
   155  		},
   156  	} {
   157  		if have, err := execTracer(tt.code, tt.contract); tt.want != string(have) || tt.fail != err {
   158  			t.Errorf("testcase %d: expected return value to be \n'%s'\n\tgot\n'%s'\nerror to be\n'%s'\n\tgot\n'%s'\n\tcode: %v", i, tt.want, string(have), tt.fail, err, tt.code)
   159  		}
   160  	}
   161  }
   162  
   163  func TestHalt(t *testing.T) {
   164  	timeout := errors.New("stahp")
   165  	chainConfig := params.TestChainConfig
   166  	tracer, err := newJsTracer("{step: function() { while(1); }, result: function() { return null; }, fault: function(){}}", nil, nil, chainConfig)
   167  	if err != nil {
   168  		t.Fatal(err)
   169  	}
   170  	go func() {
   171  		time.Sleep(1 * time.Second)
   172  		tracer.Stop(timeout)
   173  	}()
   174  	if _, err = runTrace(tracer, testCtx(), chainConfig, nil); !strings.Contains(err.Error(), "stahp") {
   175  		t.Errorf("Expected timeout error, got %v", err)
   176  	}
   177  }
   178  
   179  func TestHaltBetweenSteps(t *testing.T) {
   180  	chainConfig := params.TestChainConfig
   181  	tracer, err := newJsTracer("{step: function() {}, fault: function() {}, result: function() { return null; }}", nil, nil, chainConfig)
   182  	if err != nil {
   183  		t.Fatal(err)
   184  	}
   185  	scope := &vm.ScopeContext{
   186  		Contract: vm.NewContract(common.Address{}, common.Address{}, uint256.NewInt(0), 0, nil),
   187  	}
   188  	evm := vm.NewEVM(vm.BlockContext{BlockNumber: big.NewInt(1)}, &dummyStatedb{}, chainConfig, vm.Config{Tracer: tracer.Hooks})
   189  	evm.SetTxContext(vm.TxContext{GasPrice: big.NewInt(1)})
   190  	tracer.OnTxStart(evm.GetVMContext(), types.NewTx(&types.LegacyTx{}), common.Address{})
   191  	tracer.OnEnter(0, byte(vm.CALL), common.Address{}, common.Address{}, []byte{}, 0, big.NewInt(0))
   192  	tracer.OnOpcode(0, 0, 0, 0, scope, nil, 0, nil)
   193  	timeout := errors.New("stahp")
   194  	tracer.Stop(timeout)
   195  	tracer.OnOpcode(0, 0, 0, 0, scope, nil, 0, nil)
   196  
   197  	if _, err := tracer.GetResult(); !strings.Contains(err.Error(), timeout.Error()) {
   198  		t.Errorf("Expected timeout error, got %v", err)
   199  	}
   200  }
   201  
   202  // TestNoStepExec tests a regular value transfer (no exec), and accessing the statedb
   203  // in 'result'
   204  func TestNoStepExec(t *testing.T) {
   205  	execTracer := func(code string) []byte {
   206  		t.Helper()
   207  		chainConfig := params.TestChainConfig
   208  		tracer, err := newJsTracer(code, nil, nil, chainConfig)
   209  		if err != nil {
   210  			t.Fatal(err)
   211  		}
   212  		evm := vm.NewEVM(vm.BlockContext{BlockNumber: big.NewInt(1)}, &dummyStatedb{}, chainConfig, vm.Config{Tracer: tracer.Hooks})
   213  		evm.SetTxContext(vm.TxContext{GasPrice: big.NewInt(100)})
   214  		tracer.OnTxStart(evm.GetVMContext(), types.NewTx(&types.LegacyTx{}), common.Address{})
   215  		tracer.OnEnter(0, byte(vm.CALL), common.Address{}, common.Address{}, []byte{}, 1000, big.NewInt(0))
   216  		tracer.OnExit(0, nil, 0, nil, false)
   217  		ret, err := tracer.GetResult()
   218  		if err != nil {
   219  			t.Fatal(err)
   220  		}
   221  		return ret
   222  	}
   223  	for i, tt := range []struct {
   224  		code string
   225  		want string
   226  	}{
   227  		{ // tests that we don't panic on accessing the db methods
   228  			code: "{depths: [], step: function() {}, fault: function() {},  result: function(ctx, db){ return db.getBalance(ctx.to)} }",
   229  			want: `"0"`,
   230  		},
   231  	} {
   232  		if have := execTracer(tt.code); tt.want != string(have) {
   233  			t.Errorf("testcase %d: expected return value to be %s got %s\n\tcode: %v", i, tt.want, string(have), tt.code)
   234  		}
   235  	}
   236  }
   237  
   238  func TestIsPrecompile(t *testing.T) {
   239  	chaincfg := &params.ChainConfig{ChainID: big.NewInt(1), HomesteadBlock: big.NewInt(0), DAOForkBlock: nil, DAOForkSupport: false, EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(0), EIP158Block: big.NewInt(0), ByzantiumBlock: big.NewInt(100), ConstantinopleBlock: big.NewInt(0), PetersburgBlock: big.NewInt(0), IstanbulBlock: big.NewInt(200), MuirGlacierBlock: big.NewInt(0), BerlinBlock: big.NewInt(300), LondonBlock: big.NewInt(0), TerminalTotalDifficulty: nil, Ethash: new(params.EthashConfig), Clique: nil}
   240  	chaincfg.ByzantiumBlock = big.NewInt(100)
   241  	chaincfg.IstanbulBlock = big.NewInt(200)
   242  	chaincfg.BerlinBlock = big.NewInt(300)
   243  	txCtx := vm.TxContext{GasPrice: big.NewInt(100000)}
   244  	tracer, err := newJsTracer("{addr: toAddress('0000000000000000000000000000000000000009'), res: null, step: function() { this.res = isPrecompiled(this.addr); }, fault: function() {}, result: function() { return this.res; }}", nil, nil, chaincfg)
   245  	if err != nil {
   246  		t.Fatal(err)
   247  	}
   248  
   249  	blockCtx := vm.BlockContext{BlockNumber: big.NewInt(150)}
   250  	res, err := runTrace(tracer, &vmContext{blockCtx, txCtx}, chaincfg, nil)
   251  	if err != nil {
   252  		t.Error(err)
   253  	}
   254  	if string(res) != "false" {
   255  		t.Errorf("tracer should not consider blake2f as precompile in byzantium")
   256  	}
   257  
   258  	tracer, _ = newJsTracer("{addr: toAddress('0000000000000000000000000000000000000009'), res: null, step: function() { this.res = isPrecompiled(this.addr); }, fault: function() {}, result: function() { return this.res; }}", nil, nil, chaincfg)
   259  	blockCtx = vm.BlockContext{BlockNumber: big.NewInt(250)}
   260  	res, err = runTrace(tracer, &vmContext{blockCtx, txCtx}, chaincfg, nil)
   261  	if err != nil {
   262  		t.Error(err)
   263  	}
   264  	if string(res) != "true" {
   265  		t.Errorf("tracer should consider blake2f as precompile in istanbul")
   266  	}
   267  }
   268  
   269  func TestEnterExit(t *testing.T) {
   270  	chainConfig := params.TestChainConfig
   271  	// test that either both or none of enter() and exit() are defined
   272  	if _, err := newJsTracer("{step: function() {}, fault: function() {}, result: function() { return null; }, enter: function() {}}", new(tracers.Context), nil, chainConfig); err == nil {
   273  		t.Fatal("tracer creation should've failed without exit() definition")
   274  	}
   275  	if _, err := newJsTracer("{step: function() {}, fault: function() {}, result: function() { return null; }, enter: function() {}, exit: function() {}}", new(tracers.Context), nil, chainConfig); err != nil {
   276  		t.Fatal(err)
   277  	}
   278  	// test that the enter and exit method are correctly invoked and the values passed
   279  	tracer, err := newJsTracer("{enters: 0, exits: 0, enterGas: 0, gasUsed: 0, step: function() {}, fault: function() {}, result: function() { return {enters: this.enters, exits: this.exits, enterGas: this.enterGas, gasUsed: this.gasUsed} }, enter: function(frame) { this.enters++; this.enterGas = frame.getGas(); }, exit: function(res) { this.exits++; this.gasUsed = res.getGasUsed(); }}", new(tracers.Context), nil, chainConfig)
   280  	if err != nil {
   281  		t.Fatal(err)
   282  	}
   283  	scope := &vm.ScopeContext{
   284  		Contract: vm.NewContract(common.Address{}, common.Address{}, uint256.NewInt(0), 0, nil),
   285  	}
   286  	tracer.OnEnter(1, byte(vm.CALL), scope.Contract.Caller(), scope.Contract.Address(), []byte{}, 1000, new(big.Int))
   287  	tracer.OnExit(1, []byte{}, 400, nil, false)
   288  
   289  	have, err := tracer.GetResult()
   290  	if err != nil {
   291  		t.Fatal(err)
   292  	}
   293  	want := `{"enters":1,"exits":1,"enterGas":1000,"gasUsed":400}`
   294  	if string(have) != want {
   295  		t.Errorf("Number of invocations of enter() and exit() is wrong. Have %s, want %s\n", have, want)
   296  	}
   297  }
   298  
   299  func TestSetup(t *testing.T) {
   300  	// Test empty config
   301  	chainConfig := params.TestChainConfig
   302  	_, err := newJsTracer(`{setup: function(cfg) { if (cfg !== "{}") { throw("invalid empty config") } }, fault: function() {}, result: function() {}}`, new(tracers.Context), nil, chainConfig)
   303  	if err != nil {
   304  		t.Error(err)
   305  	}
   306  
   307  	cfg, err := json.Marshal(map[string]string{"foo": "bar"})
   308  	if err != nil {
   309  		t.Fatal(err)
   310  	}
   311  	// Test no setup func
   312  	_, err = newJsTracer(`{fault: function() {}, result: function() {}}`, new(tracers.Context), cfg, chainConfig)
   313  	if err != nil {
   314  		t.Fatal(err)
   315  	}
   316  	// Test config value
   317  	tracer, err := newJsTracer("{config: null, setup: function(cfg) { this.config = JSON.parse(cfg) }, step: function() {}, fault: function() {}, result: function() { return this.config.foo }}", new(tracers.Context), cfg, chainConfig)
   318  	if err != nil {
   319  		t.Fatal(err)
   320  	}
   321  	have, err := tracer.GetResult()
   322  	if err != nil {
   323  		t.Fatal(err)
   324  	}
   325  	if string(have) != `"bar"` {
   326  		t.Errorf("tracer returned wrong result. have: %s, want: \"bar\"\n", string(have))
   327  	}
   328  }