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