github.com/codysnider/go-ethereum@v1.10.18-0.20220420071915-14f4ae99222a/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/ethereum/go-ethereum/common" 27 "github.com/ethereum/go-ethereum/core/state" 28 "github.com/ethereum/go-ethereum/core/vm" 29 "github.com/ethereum/go-ethereum/eth/tracers" 30 "github.com/ethereum/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 gasLimit uint64 = 31000 66 startGas uint64 = 10000 67 value = big.NewInt(0) 68 contract = vm.NewContract(account{}, account{}, value, startGas) 69 ) 70 contract.Code = []byte{byte(vm.PUSH1), 0x1, byte(vm.PUSH1), 0x1, 0x0} 71 72 tracer.CaptureTxStart(gasLimit) 73 tracer.CaptureStart(env, contract.Caller(), contract.Address(), false, []byte{}, startGas, value) 74 ret, err := env.Interpreter().Run(contract, []byte{}, false) 75 tracer.CaptureEnd(ret, startGas-contract.Gas, 1, err) 76 // Rest gas assumes no refund 77 tracer.CaptureTxEnd(startGas - contract.Gas) 78 if err != nil { 79 return nil, err 80 } 81 return tracer.GetResult() 82 } 83 84 func TestTracer(t *testing.T) { 85 execTracer := func(code string) ([]byte, string) { 86 t.Helper() 87 tracer, err := newJsTracer(code, nil) 88 if err != nil { 89 t.Fatal(err) 90 } 91 ret, err := runTrace(tracer, testCtx(), params.TestChainConfig) 92 if err != nil { 93 return nil, err.Error() // Stringify to allow comparison without nil checks 94 } 95 return ret, "" 96 } 97 for i, tt := range []struct { 98 code string 99 want string 100 fail string 101 }{ 102 { // tests that we don't panic on bad arguments to memory access 103 code: "{depths: [], step: function(log) { this.depths.push(log.memory.slice(-1,-2)); }, fault: function() {}, result: function() { return this.depths; }}", 104 want: `[{},{},{}]`, 105 }, { // tests that we don't panic on bad arguments to stack peeks 106 code: "{depths: [], step: function(log) { this.depths.push(log.stack.peek(-1)); }, fault: function() {}, result: function() { return this.depths; }}", 107 want: `["0","0","0"]`, 108 }, { // tests that we don't panic on bad arguments to memory getUint 109 code: "{ depths: [], step: function(log, db) { this.depths.push(log.memory.getUint(-64));}, fault: function() {}, result: function() { return this.depths; }}", 110 want: `["0","0","0"]`, 111 }, { // tests some general counting 112 code: "{count: 0, step: function() { this.count += 1; }, fault: function() {}, result: function() { return this.count; }}", 113 want: `3`, 114 }, { // tests that depth is reported correctly 115 code: "{depths: [], step: function(log) { this.depths.push(log.stack.length()); }, fault: function() {}, result: function() { return this.depths; }}", 116 want: `[0,1,2]`, 117 }, { // tests to-string of opcodes 118 code: "{opcodes: [], step: function(log) { this.opcodes.push(log.op.toString()); }, fault: function() {}, result: function() { return this.opcodes; }}", 119 want: `["PUSH1","PUSH1","STOP"]`, 120 }, { // tests intrinsic gas 121 code: "{depths: [], step: function() {}, fault: function() {}, result: function(ctx) { return ctx.gasPrice+'.'+ctx.gasUsed+'.'+ctx.intrinsicGas; }}", 122 want: `"100000.6.21000"`, 123 }, { // tests too deep object / serialization crash 124 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; }}", 125 fail: "RangeError: json encode recursion limit in server-side tracer function 'result'", 126 }, 127 } { 128 if have, err := execTracer(tt.code); tt.want != string(have) || tt.fail != err { 129 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) 130 } 131 } 132 } 133 134 func TestHalt(t *testing.T) { 135 t.Skip("duktape doesn't support abortion") 136 timeout := errors.New("stahp") 137 tracer, err := newJsTracer("{step: function() { while(1); }, result: function() { return null; }, fault: function(){}}", nil) 138 if err != nil { 139 t.Fatal(err) 140 } 141 go func() { 142 time.Sleep(1 * time.Second) 143 tracer.Stop(timeout) 144 }() 145 if _, err = runTrace(tracer, testCtx(), params.TestChainConfig); err.Error() != "stahp in server-side tracer function 'step'" { 146 t.Errorf("Expected timeout error, got %v", err) 147 } 148 } 149 150 func TestHaltBetweenSteps(t *testing.T) { 151 tracer, err := newJsTracer("{step: function() {}, fault: function() {}, result: function() { return null; }}", nil) 152 if err != nil { 153 t.Fatal(err) 154 } 155 env := vm.NewEVM(vm.BlockContext{BlockNumber: big.NewInt(1)}, vm.TxContext{GasPrice: big.NewInt(1)}, &dummyStatedb{}, params.TestChainConfig, vm.Config{Debug: true, Tracer: tracer}) 156 scope := &vm.ScopeContext{ 157 Contract: vm.NewContract(&account{}, &account{}, big.NewInt(0), 0), 158 } 159 tracer.CaptureStart(env, common.Address{}, common.Address{}, false, []byte{}, 0, big.NewInt(0)) 160 tracer.CaptureState(0, 0, 0, 0, scope, nil, 0, nil) 161 timeout := errors.New("stahp") 162 tracer.Stop(timeout) 163 tracer.CaptureState(0, 0, 0, 0, scope, nil, 0, nil) 164 165 if _, err := tracer.GetResult(); err.Error() != timeout.Error() { 166 t.Errorf("Expected timeout error, got %v", err) 167 } 168 } 169 170 // TestNoStepExec tests a regular value transfer (no exec), and accessing the statedb 171 // in 'result' 172 func TestNoStepExec(t *testing.T) { 173 execTracer := func(code string) []byte { 174 t.Helper() 175 tracer, err := newJsTracer(code, nil) 176 if err != nil { 177 t.Fatal(err) 178 } 179 env := vm.NewEVM(vm.BlockContext{BlockNumber: big.NewInt(1)}, vm.TxContext{GasPrice: big.NewInt(100)}, &dummyStatedb{}, params.TestChainConfig, vm.Config{Debug: true, Tracer: tracer}) 180 tracer.CaptureStart(env, common.Address{}, common.Address{}, false, []byte{}, 1000, big.NewInt(0)) 181 tracer.CaptureEnd(nil, 0, 1, nil) 182 ret, err := tracer.GetResult() 183 if err != nil { 184 t.Fatal(err) 185 } 186 return ret 187 } 188 for i, tt := range []struct { 189 code string 190 want string 191 }{ 192 { // tests that we don't panic on accessing the db methods 193 code: "{depths: [], step: function() {}, fault: function() {}, result: function(ctx, db){ return db.getBalance(ctx.to)} }", 194 want: `"0"`, 195 }, 196 } { 197 if have := execTracer(tt.code); tt.want != string(have) { 198 t.Errorf("testcase %d: expected return value to be %s got %s\n\tcode: %v", i, tt.want, string(have), tt.code) 199 } 200 } 201 } 202 203 func TestIsPrecompile(t *testing.T) { 204 chaincfg := ¶ms.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} 205 chaincfg.ByzantiumBlock = big.NewInt(100) 206 chaincfg.IstanbulBlock = big.NewInt(200) 207 chaincfg.BerlinBlock = big.NewInt(300) 208 txCtx := vm.TxContext{GasPrice: big.NewInt(100000)} 209 tracer, err := newJsTracer("{addr: toAddress('0000000000000000000000000000000000000009'), res: null, step: function() { this.res = isPrecompiled(this.addr); }, fault: function() {}, result: function() { return this.res; }}", nil) 210 if err != nil { 211 t.Fatal(err) 212 } 213 214 blockCtx := vm.BlockContext{BlockNumber: big.NewInt(150)} 215 res, err := runTrace(tracer, &vmContext{blockCtx, txCtx}, chaincfg) 216 if err != nil { 217 t.Error(err) 218 } 219 if string(res) != "false" { 220 t.Errorf("Tracer should not consider blake2f as precompile in byzantium") 221 } 222 223 tracer, _ = newJsTracer("{addr: toAddress('0000000000000000000000000000000000000009'), res: null, step: function() { this.res = isPrecompiled(this.addr); }, fault: function() {}, result: function() { return this.res; }}", nil) 224 blockCtx = vm.BlockContext{BlockNumber: big.NewInt(250)} 225 res, err = runTrace(tracer, &vmContext{blockCtx, txCtx}, chaincfg) 226 if err != nil { 227 t.Error(err) 228 } 229 if string(res) != "true" { 230 t.Errorf("Tracer should consider blake2f as precompile in istanbul") 231 } 232 } 233 234 func TestEnterExit(t *testing.T) { 235 // test that either both or none of enter() and exit() are defined 236 if _, err := newJsTracer("{step: function() {}, fault: function() {}, result: function() { return null; }, enter: function() {}}", new(tracers.Context)); err == nil { 237 t.Fatal("tracer creation should've failed without exit() definition") 238 } 239 if _, err := newJsTracer("{step: function() {}, fault: function() {}, result: function() { return null; }, enter: function() {}, exit: function() {}}", new(tracers.Context)); err != nil { 240 t.Fatal(err) 241 } 242 // test that the enter and exit method are correctly invoked and the values passed 243 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)) 244 if err != nil { 245 t.Fatal(err) 246 } 247 scope := &vm.ScopeContext{ 248 Contract: vm.NewContract(&account{}, &account{}, big.NewInt(0), 0), 249 } 250 tracer.CaptureEnter(vm.CALL, scope.Contract.Caller(), scope.Contract.Address(), []byte{}, 1000, new(big.Int)) 251 tracer.CaptureExit([]byte{}, 400, nil) 252 253 have, err := tracer.GetResult() 254 if err != nil { 255 t.Fatal(err) 256 } 257 want := `{"enters":1,"exits":1,"enterGas":1000,"gasUsed":400}` 258 if string(have) != want { 259 t.Errorf("Number of invocations of enter() and exit() is wrong. Have %s, want %s\n", have, want) 260 } 261 }