github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/eth/tracers/js/tracer_test.go (about)

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