tracer_test.go 11 KB

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