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