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
17package js
18
19import (
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
33type account struct{}
34
35func (account) SubBalance(amount *big.Int)                          {}
36func (account) AddBalance(amount *big.Int)                          {}
37func (account) SetAddress(common.Address)                           {}
38func (account) Value() *big.Int                                     { return nil }
39func (account) SetBalance(*big.Int)                                 {}
40func (account) SetNonce(uint64)                                     {}
41func (account) Balance() *big.Int                                   { return nil }
42func (account) Address() common.Address                             { return common.Address{} }
43func (account) SetCode(common.Hash, []byte)                         {}
44func (account) ForEachStorage(cb func(key, value common.Hash) bool) {}
45
46type dummyStatedb struct {
47	state.StateDB
48}
49
50func (*dummyStatedb) GetRefund() uint64                       { return 1337 }
51func (*dummyStatedb) GetBalance(addr common.Address) *big.Int { return new(big.Int) }
52
53type vmContext struct {
54	blockCtx vm.BlockContext
55	txCtx    vm.TxContext
56}
57
58func testCtx() *vmContext {
59	return &vmContext{blockCtx: vm.BlockContext{BlockNumber: big.NewInt(1)}, txCtx: vm.TxContext{GasPrice: big.NewInt(100000)}}
60}
61
62func 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
80func 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
130func 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
146func 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'
168func 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
199func 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	txCtx := vm.TxContext{GasPrice: big.NewInt(100000)}
205	tracer, err := newJsTracer("{addr: toAddress('0000000000000000000000000000000000000009'), res: null, step: function() { this.res = isPrecompiled(this.addr); }, fault: function() {}, result: function() { return this.res; }}", nil)
206	if err != nil {
207		t.Fatal(err)
208	}
209
210	blockCtx := vm.BlockContext{BlockNumber: big.NewInt(150)}
211	res, err := runTrace(tracer, &vmContext{blockCtx, txCtx}, chaincfg)
212	if err != nil {
213		t.Error(err)
214	}
215	if string(res) != "false" {
216		t.Errorf("Tracer should not consider blake2f as precompile in byzantium")
217	}
218
219	tracer, _ = newJsTracer("{addr: toAddress('0000000000000000000000000000000000000009'), res: null, step: function() { this.res = isPrecompiled(this.addr); }, fault: function() {}, result: function() { return this.res; }}", nil)
220	blockCtx = vm.BlockContext{BlockNumber: big.NewInt(250)}
221	res, err = runTrace(tracer, &vmContext{blockCtx, txCtx}, chaincfg)
222	if err != nil {
223		t.Error(err)
224	}
225	if string(res) != "true" {
226		t.Errorf("Tracer should consider blake2f as precompile in istanbul")
227	}
228}
229
230func TestEnterExit(t *testing.T) {
231	// test that either both or none of enter() and exit() are defined
232	if _, err := newJsTracer("{step: function() {}, fault: function() {}, result: function() { return null; }, enter: function() {}}", new(tracers.Context)); err == nil {
233		t.Fatal("tracer creation should've failed without exit() definition")
234	}
235	if _, err := newJsTracer("{step: function() {}, fault: function() {}, result: function() { return null; }, enter: function() {}, exit: function() {}}", new(tracers.Context)); err != nil {
236		t.Fatal(err)
237	}
238	// test that the enter and exit method are correctly invoked and the values passed
239	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))
240	if err != nil {
241		t.Fatal(err)
242	}
243	scope := &vm.ScopeContext{
244		Contract: vm.NewContract(&account{}, &account{}, big.NewInt(0), 0),
245	}
246	tracer.CaptureEnter(vm.CALL, scope.Contract.Caller(), scope.Contract.Address(), []byte{}, 1000, new(big.Int))
247	tracer.CaptureExit([]byte{}, 400, nil)
248
249	have, err := tracer.GetResult()
250	if err != nil {
251		t.Fatal(err)
252	}
253	want := `{"enters":1,"exits":1,"enterGas":1000,"gasUsed":400}`
254	if string(have) != want {
255		t.Errorf("Number of invocations of enter() and exit() is wrong. Have %s, want %s\n", have, want)
256	}
257}
258