tracer.go 10 KB

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