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