tracer.go 10 KB

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