tracer.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. // Copyright 2016 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 ethapi
  17. import (
  18. "encoding/json"
  19. "errors"
  20. "fmt"
  21. "math/big"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/core/vm"
  24. "github.com/robertkrimen/otto"
  25. )
  26. // fakeBig is used to provide an interface to Javascript for 'big.NewInt'
  27. type fakeBig struct{}
  28. // NewInt creates a new big.Int with the specified int64 value.
  29. func (fb *fakeBig) NewInt(x int64) *big.Int {
  30. return big.NewInt(x)
  31. }
  32. // OpCodeWrapper provides a JavaScript-friendly wrapper around OpCode, to convince Otto to treat it
  33. // as an object, instead of a number.
  34. type opCodeWrapper struct {
  35. op vm.OpCode
  36. }
  37. // toNumber returns the ID of this opcode as an integer
  38. func (ocw *opCodeWrapper) toNumber() int {
  39. return int(ocw.op)
  40. }
  41. // toString returns the string representation of the opcode
  42. func (ocw *opCodeWrapper) toString() string {
  43. return ocw.op.String()
  44. }
  45. // isPush returns true if the op is a Push
  46. func (ocw *opCodeWrapper) isPush() bool {
  47. return ocw.op.IsPush()
  48. }
  49. // MarshalJSON serializes the opcode as JSON
  50. func (ocw *opCodeWrapper) MarshalJSON() ([]byte, error) {
  51. return json.Marshal(ocw.op.String())
  52. }
  53. // toValue returns an otto.Value for the opCodeWrapper
  54. func (ocw *opCodeWrapper) toValue(vm *otto.Otto) otto.Value {
  55. value, _ := vm.ToValue(ocw)
  56. obj := value.Object()
  57. obj.Set("toNumber", ocw.toNumber)
  58. obj.Set("toString", ocw.toString)
  59. obj.Set("isPush", ocw.isPush)
  60. return value
  61. }
  62. // memoryWrapper provides a JS wrapper around vm.Memory
  63. type memoryWrapper struct {
  64. memory *vm.Memory
  65. }
  66. // slice returns the requested range of memory as a byte slice
  67. func (mw *memoryWrapper) slice(begin, end int64) []byte {
  68. return mw.memory.Get(begin, end-begin)
  69. }
  70. // getUint returns the 32 bytes at the specified address interpreted
  71. // as an unsigned integer
  72. func (mw *memoryWrapper) getUint(addr int64) *big.Int {
  73. ret := big.NewInt(0)
  74. ret.SetBytes(mw.memory.GetPtr(addr, 32))
  75. return ret
  76. }
  77. // toValue returns an otto.Value for the memoryWrapper
  78. func (mw *memoryWrapper) toValue(vm *otto.Otto) otto.Value {
  79. value, _ := vm.ToValue(mw)
  80. obj := value.Object()
  81. obj.Set("slice", mw.slice)
  82. obj.Set("getUint", mw.getUint)
  83. return value
  84. }
  85. // stackWrapper provides a JS wrapper around vm.Stack
  86. type stackWrapper struct {
  87. stack *vm.Stack
  88. }
  89. // peek returns the nth-from-the-top element of the stack.
  90. func (sw *stackWrapper) peek(idx int) *big.Int {
  91. return sw.stack.Data()[len(sw.stack.Data())-idx-1]
  92. }
  93. // length returns the length of the stack
  94. func (sw *stackWrapper) length() int {
  95. return len(sw.stack.Data())
  96. }
  97. // toValue returns an otto.Value for the stackWrapper
  98. func (sw *stackWrapper) toValue(vm *otto.Otto) otto.Value {
  99. value, _ := vm.ToValue(sw)
  100. obj := value.Object()
  101. obj.Set("peek", sw.peek)
  102. obj.Set("length", sw.length)
  103. return value
  104. }
  105. // dbWrapper provides a JS wrapper around vm.Database
  106. type dbWrapper struct {
  107. db vm.StateDB
  108. }
  109. // getBalance retrieves an account's balance
  110. func (dw *dbWrapper) getBalance(addr common.Address) *big.Int {
  111. return dw.db.GetBalance(addr)
  112. }
  113. // getNonce retrieves an account's nonce
  114. func (dw *dbWrapper) getNonce(addr common.Address) uint64 {
  115. return dw.db.GetNonce(addr)
  116. }
  117. // getCode retrieves an account's code
  118. func (dw *dbWrapper) getCode(addr common.Address) []byte {
  119. return dw.db.GetCode(addr)
  120. }
  121. // getState retrieves an account's state data for the given hash
  122. func (dw *dbWrapper) getState(addr common.Address, hash common.Hash) common.Hash {
  123. return dw.db.GetState(addr, hash)
  124. }
  125. // exists returns true iff the account exists
  126. func (dw *dbWrapper) exists(addr common.Address) bool {
  127. return dw.db.Exist(addr)
  128. }
  129. // toValue returns an otto.Value for the dbWrapper
  130. func (dw *dbWrapper) toValue(vm *otto.Otto) otto.Value {
  131. value, _ := vm.ToValue(dw)
  132. obj := value.Object()
  133. obj.Set("getBalance", dw.getBalance)
  134. obj.Set("getNonce", dw.getNonce)
  135. obj.Set("getCode", dw.getCode)
  136. obj.Set("getState", dw.getState)
  137. obj.Set("exists", dw.exists)
  138. return value
  139. }
  140. // JavascriptTracer provides an implementation of Tracer that evaluates a
  141. // Javascript function for each VM execution step.
  142. type JavascriptTracer struct {
  143. vm *otto.Otto // Javascript VM instance
  144. traceobj *otto.Object // User-supplied object to call
  145. log map[string]interface{} // (Reusable) map for the `log` arg to `step`
  146. logvalue otto.Value // JS view of `log`
  147. memory *memoryWrapper // Wrapper around the VM memory
  148. memvalue otto.Value // JS view of `memory`
  149. stack *stackWrapper // Wrapper around the VM stack
  150. stackvalue otto.Value // JS view of `stack`
  151. db *dbWrapper // Wrapper around the VM environment
  152. dbvalue otto.Value // JS view of `db`
  153. err error // Error, if one has occurred
  154. }
  155. // NewJavascriptTracer instantiates a new JavascriptTracer instance.
  156. // code specifies a Javascript snippet, which must evaluate to an expression
  157. // returning an object with 'step' and 'result' functions.
  158. func NewJavascriptTracer(code string) (*JavascriptTracer, error) {
  159. vm := otto.New()
  160. vm.Interrupt = make(chan func(), 1)
  161. // Set up builtins for this environment
  162. vm.Set("big", &fakeBig{})
  163. jstracer, err := vm.Object("(" + code + ")")
  164. if err != nil {
  165. return nil, err
  166. }
  167. // Check the required functions exist
  168. step, err := jstracer.Get("step")
  169. if err != nil {
  170. return nil, err
  171. }
  172. if !step.IsFunction() {
  173. return nil, fmt.Errorf("Trace object must expose a function step()")
  174. }
  175. result, err := jstracer.Get("result")
  176. if err != nil {
  177. return nil, err
  178. }
  179. if !result.IsFunction() {
  180. return nil, fmt.Errorf("Trace object must expose a function result()")
  181. }
  182. // Create the persistent log object
  183. log := make(map[string]interface{})
  184. logvalue, _ := vm.ToValue(log)
  185. // Create persistent wrappers for memory and stack
  186. mem := &memoryWrapper{}
  187. stack := &stackWrapper{}
  188. db := &dbWrapper{}
  189. return &JavascriptTracer{
  190. vm: vm,
  191. traceobj: jstracer,
  192. log: log,
  193. logvalue: logvalue,
  194. memory: mem,
  195. memvalue: mem.toValue(vm),
  196. stack: stack,
  197. stackvalue: stack.toValue(vm),
  198. db: db,
  199. dbvalue: db.toValue(vm),
  200. err: nil,
  201. }, nil
  202. }
  203. // Stop terminates execution of any JavaScript
  204. func (jst *JavascriptTracer) Stop(err error) {
  205. jst.vm.Interrupt <- func() {
  206. panic(err)
  207. }
  208. }
  209. // callSafely executes a method on a JS object, catching any panics and
  210. // returning them as error objects.
  211. func (jst *JavascriptTracer) callSafely(method string, argumentList ...interface{}) (ret interface{}, err error) {
  212. defer func() {
  213. if caught := recover(); caught != nil {
  214. switch caught := caught.(type) {
  215. case error:
  216. err = caught
  217. case string:
  218. err = errors.New(caught)
  219. case fmt.Stringer:
  220. err = errors.New(caught.String())
  221. default:
  222. panic(caught)
  223. }
  224. }
  225. }()
  226. value, err := jst.traceobj.Call(method, argumentList...)
  227. ret, _ = value.Export()
  228. return ret, err
  229. }
  230. func wrapError(context string, err error) error {
  231. var message string
  232. switch err := err.(type) {
  233. case *otto.Error:
  234. message = err.String()
  235. default:
  236. message = err.Error()
  237. }
  238. return fmt.Errorf("%v in server-side tracer function '%v'", message, context)
  239. }
  240. // CaptureState implements the Tracer interface to trace a single step of VM execution
  241. func (jst *JavascriptTracer) CaptureState(env *vm.Environment, pc uint64, op vm.OpCode, gas, cost *big.Int, memory *vm.Memory, stack *vm.Stack, contract *vm.Contract, depth int, err error) error {
  242. if jst.err == nil {
  243. jst.memory.memory = memory
  244. jst.stack.stack = stack
  245. jst.db.db = env.StateDB
  246. ocw := &opCodeWrapper{op}
  247. jst.log["pc"] = pc
  248. jst.log["op"] = ocw.toValue(jst.vm)
  249. jst.log["gas"] = gas.Int64()
  250. jst.log["gasPrice"] = cost.Int64()
  251. jst.log["memory"] = jst.memvalue
  252. jst.log["stack"] = jst.stackvalue
  253. jst.log["depth"] = depth
  254. jst.log["account"] = contract.Address()
  255. jst.log["err"] = err
  256. _, err := jst.callSafely("step", jst.logvalue, jst.dbvalue)
  257. if err != nil {
  258. jst.err = wrapError("step", err)
  259. }
  260. }
  261. return nil
  262. }
  263. // GetResult calls the Javascript 'result' function and returns its value, or any accumulated error
  264. func (jst *JavascriptTracer) GetResult() (result interface{}, err error) {
  265. if jst.err != nil {
  266. return nil, jst.err
  267. }
  268. result, err = jst.callSafely("result")
  269. if err != nil {
  270. err = wrapError("result", err)
  271. }
  272. return
  273. }