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