tracer.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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 []byte) *big.Int {
  113. return dw.db.GetBalance(common.BytesToAddress(addr))
  114. }
  115. // getNonce retrieves an account's nonce
  116. func (dw *dbWrapper) getNonce(addr []byte) uint64 {
  117. return dw.db.GetNonce(common.BytesToAddress(addr))
  118. }
  119. // getCode retrieves an account's code
  120. func (dw *dbWrapper) getCode(addr []byte) []byte {
  121. return dw.db.GetCode(common.BytesToAddress(addr))
  122. }
  123. // getState retrieves an account's state data for the given hash
  124. func (dw *dbWrapper) getState(addr []byte, hash common.Hash) common.Hash {
  125. return dw.db.GetState(common.BytesToAddress(addr), hash)
  126. }
  127. // exists returns true iff the account exists
  128. func (dw *dbWrapper) exists(addr []byte) bool {
  129. return dw.db.Exist(common.BytesToAddress(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. op *opCodeWrapper // Wrapper around the VM opcode
  173. log map[string]interface{} // (Reusable) map for the `log` arg to `step`
  174. logvalue otto.Value // JS view of `log`
  175. memory *memoryWrapper // Wrapper around the VM memory
  176. stack *stackWrapper // Wrapper around the VM 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. err error // Error, if one has occurred
  181. result interface{} // Final result to return to the user
  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. var (
  213. op = new(opCodeWrapper)
  214. mem = new(memoryWrapper)
  215. stack = new(stackWrapper)
  216. db = new(dbWrapper)
  217. contract = new(contractWrapper)
  218. )
  219. log := map[string]interface{}{
  220. "op": op.toValue(vm),
  221. "memory": mem.toValue(vm),
  222. "stack": stack.toValue(vm),
  223. "contract": contract.toValue(vm),
  224. }
  225. logvalue, _ := vm.ToValue(log)
  226. return &JavascriptTracer{
  227. vm: vm,
  228. traceobj: jstracer,
  229. op: op,
  230. log: log,
  231. logvalue: logvalue,
  232. memory: mem,
  233. stack: stack,
  234. db: db,
  235. dbvalue: db.toValue(vm),
  236. contract: contract,
  237. err: nil,
  238. }, nil
  239. }
  240. // Stop terminates execution of any JavaScript
  241. func (jst *JavascriptTracer) Stop(err error) {
  242. jst.vm.Interrupt <- func() {
  243. panic(err)
  244. }
  245. }
  246. // callSafely executes a method on a JS object, catching any panics and
  247. // returning them as error objects.
  248. func (jst *JavascriptTracer) callSafely(method string, argumentList ...interface{}) (ret interface{}, err error) {
  249. defer func() {
  250. if caught := recover(); caught != nil {
  251. switch caught := caught.(type) {
  252. case error:
  253. err = caught
  254. case string:
  255. err = errors.New(caught)
  256. case fmt.Stringer:
  257. err = errors.New(caught.String())
  258. default:
  259. panic(caught)
  260. }
  261. }
  262. }()
  263. value, err := jst.traceobj.Call(method, argumentList...)
  264. ret, _ = value.Export()
  265. return ret, err
  266. }
  267. func wrapError(context string, err error) error {
  268. var message string
  269. switch err := err.(type) {
  270. case *otto.Error:
  271. message = err.String()
  272. default:
  273. message = err.Error()
  274. }
  275. return fmt.Errorf("%v in server-side tracer function '%v'", message, context)
  276. }
  277. // CaptureState implements the Tracer interface to trace a single step of VM execution
  278. 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 {
  279. if jst.err == nil {
  280. jst.op.op = op
  281. jst.memory.memory = memory
  282. jst.stack.stack = stack
  283. jst.db.db = env.StateDB
  284. jst.contract.contract = contract
  285. jst.log["pc"] = pc
  286. jst.log["gas"] = gas
  287. jst.log["cost"] = cost
  288. jst.log["depth"] = depth
  289. jst.log["account"] = contract.Address()
  290. delete(jst.log, "error")
  291. if err != nil {
  292. jst.log["error"] = err
  293. }
  294. _, err := jst.callSafely("step", jst.logvalue, jst.dbvalue)
  295. if err != nil {
  296. jst.err = wrapError("step", err)
  297. }
  298. }
  299. return nil
  300. }
  301. // CaptureEnd is called after the call finishes
  302. func (jst *JavascriptTracer) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error {
  303. //TODO! @Arachnid please figure out of there's anything we can use this method for
  304. return nil
  305. }
  306. // GetResult calls the Javascript 'result' function and returns its value, or any accumulated error
  307. func (jst *JavascriptTracer) GetResult() (result interface{}, err error) {
  308. if jst.err != nil {
  309. return nil, jst.err
  310. }
  311. result, err = jst.callSafely("result")
  312. if err != nil {
  313. err = wrapError("result", err)
  314. }
  315. return
  316. }