github.com/calmw/ethereum@v0.1.1/eth/tracers/js/goja.go (about)

     1  // Copyright 2022 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  
    17  package js
    18  
    19  import (
    20  	"encoding/json"
    21  	"errors"
    22  	"fmt"
    23  	"math/big"
    24  
    25  	"github.com/dop251/goja"
    26  
    27  	"github.com/calmw/ethereum/common"
    28  	"github.com/calmw/ethereum/common/hexutil"
    29  	"github.com/calmw/ethereum/core/vm"
    30  	"github.com/calmw/ethereum/crypto"
    31  	"github.com/calmw/ethereum/eth/tracers"
    32  	jsassets "github.com/calmw/ethereum/eth/tracers/js/internal/tracers"
    33  )
    34  
    35  var assetTracers = make(map[string]string)
    36  
    37  // init retrieves the JavaScript transaction tracers included in go-ethereum.
    38  func init() {
    39  	var err error
    40  	assetTracers, err = jsassets.Load()
    41  	if err != nil {
    42  		panic(err)
    43  	}
    44  	type ctorFn = func(*tracers.Context, json.RawMessage) (tracers.Tracer, error)
    45  	lookup := func(code string) ctorFn {
    46  		return func(ctx *tracers.Context, cfg json.RawMessage) (tracers.Tracer, error) {
    47  			return newJsTracer(code, ctx, cfg)
    48  		}
    49  	}
    50  	for name, code := range assetTracers {
    51  		tracers.DefaultDirectory.Register(name, lookup(code), true)
    52  	}
    53  	tracers.DefaultDirectory.RegisterJSEval(newJsTracer)
    54  }
    55  
    56  // bigIntProgram is compiled once and the exported function mostly invoked to convert
    57  // hex strings into big ints.
    58  var bigIntProgram = goja.MustCompile("bigInt", bigIntegerJS, false)
    59  
    60  type toBigFn = func(vm *goja.Runtime, val string) (goja.Value, error)
    61  type toBufFn = func(vm *goja.Runtime, val []byte) (goja.Value, error)
    62  type fromBufFn = func(vm *goja.Runtime, buf goja.Value, allowString bool) ([]byte, error)
    63  
    64  func toBuf(vm *goja.Runtime, bufType goja.Value, val []byte) (goja.Value, error) {
    65  	// bufType is usually Uint8Array. This is equivalent to `new Uint8Array(val)` in JS.
    66  	return vm.New(bufType, vm.ToValue(vm.NewArrayBuffer(val)))
    67  }
    68  
    69  func fromBuf(vm *goja.Runtime, bufType goja.Value, buf goja.Value, allowString bool) ([]byte, error) {
    70  	obj := buf.ToObject(vm)
    71  	switch obj.ClassName() {
    72  	case "String":
    73  		if !allowString {
    74  			break
    75  		}
    76  		return common.FromHex(obj.String()), nil
    77  
    78  	case "Array":
    79  		var b []byte
    80  		if err := vm.ExportTo(buf, &b); err != nil {
    81  			return nil, err
    82  		}
    83  		return b, nil
    84  
    85  	case "Object":
    86  		if !obj.Get("constructor").SameAs(bufType) {
    87  			break
    88  		}
    89  		b := obj.Get("buffer").Export().(goja.ArrayBuffer).Bytes()
    90  		return b, nil
    91  	}
    92  	return nil, fmt.Errorf("invalid buffer type")
    93  }
    94  
    95  // jsTracer is an implementation of the Tracer interface which evaluates
    96  // JS functions on the relevant EVM hooks. It uses Goja as its JS engine.
    97  type jsTracer struct {
    98  	vm                *goja.Runtime
    99  	env               *vm.EVM
   100  	toBig             toBigFn               // Converts a hex string into a JS bigint
   101  	toBuf             toBufFn               // Converts a []byte into a JS buffer
   102  	fromBuf           fromBufFn             // Converts an array, hex string or Uint8Array to a []byte
   103  	ctx               map[string]goja.Value // KV-bag passed to JS in `result`
   104  	activePrecompiles []common.Address      // List of active precompiles at current block
   105  	traceStep         bool                  // True if tracer object exposes a `step()` method
   106  	traceFrame        bool                  // True if tracer object exposes the `enter()` and `exit()` methods
   107  	gasLimit          uint64                // Amount of gas bought for the whole tx
   108  	err               error                 // Any error that should stop tracing
   109  	obj               *goja.Object          // Trace object
   110  
   111  	// Methods exposed by tracer
   112  	result goja.Callable
   113  	fault  goja.Callable
   114  	step   goja.Callable
   115  	enter  goja.Callable
   116  	exit   goja.Callable
   117  
   118  	// Underlying structs being passed into JS
   119  	log         *steplog
   120  	frame       *callframe
   121  	frameResult *callframeResult
   122  
   123  	// Goja-wrapping of types prepared for JS consumption
   124  	logValue         goja.Value
   125  	dbValue          goja.Value
   126  	frameValue       goja.Value
   127  	frameResultValue goja.Value
   128  }
   129  
   130  // newJsTracer instantiates a new JS tracer instance. code is a
   131  // Javascript snippet which evaluates to an expression returning
   132  // an object with certain methods:
   133  //
   134  // The methods `result` and `fault` are required to be present.
   135  // The methods `step`, `enter`, and `exit` are optional, but note that
   136  // `enter` and `exit` always go together.
   137  func newJsTracer(code string, ctx *tracers.Context, cfg json.RawMessage) (tracers.Tracer, error) {
   138  	vm := goja.New()
   139  	// By default field names are exported to JS as is, i.e. capitalized.
   140  	vm.SetFieldNameMapper(goja.UncapFieldNameMapper())
   141  	t := &jsTracer{
   142  		vm:  vm,
   143  		ctx: make(map[string]goja.Value),
   144  	}
   145  	if ctx == nil {
   146  		ctx = new(tracers.Context)
   147  	}
   148  	if ctx.BlockHash != (common.Hash{}) {
   149  		t.ctx["blockHash"] = vm.ToValue(ctx.BlockHash.Bytes())
   150  		if ctx.TxHash != (common.Hash{}) {
   151  			t.ctx["txIndex"] = vm.ToValue(ctx.TxIndex)
   152  			t.ctx["txHash"] = vm.ToValue(ctx.TxHash.Bytes())
   153  		}
   154  	}
   155  
   156  	t.setTypeConverters()
   157  	t.setBuiltinFunctions()
   158  	ret, err := vm.RunString("(" + code + ")")
   159  	if err != nil {
   160  		return nil, err
   161  	}
   162  	// Check tracer's interface for required and optional methods.
   163  	obj := ret.ToObject(vm)
   164  	result, ok := goja.AssertFunction(obj.Get("result"))
   165  	if !ok {
   166  		return nil, errors.New("trace object must expose a function result()")
   167  	}
   168  	fault, ok := goja.AssertFunction(obj.Get("fault"))
   169  	if !ok {
   170  		return nil, errors.New("trace object must expose a function fault()")
   171  	}
   172  	step, ok := goja.AssertFunction(obj.Get("step"))
   173  	t.traceStep = ok
   174  	enter, hasEnter := goja.AssertFunction(obj.Get("enter"))
   175  	exit, hasExit := goja.AssertFunction(obj.Get("exit"))
   176  	if hasEnter != hasExit {
   177  		return nil, errors.New("trace object must expose either both or none of enter() and exit()")
   178  	}
   179  	t.traceFrame = hasEnter
   180  	t.obj = obj
   181  	t.step = step
   182  	t.enter = enter
   183  	t.exit = exit
   184  	t.result = result
   185  	t.fault = fault
   186  
   187  	// Pass in config
   188  	if setup, ok := goja.AssertFunction(obj.Get("setup")); ok {
   189  		cfgStr := "{}"
   190  		if cfg != nil {
   191  			cfgStr = string(cfg)
   192  		}
   193  		if _, err := setup(obj, vm.ToValue(cfgStr)); err != nil {
   194  			return nil, err
   195  		}
   196  	}
   197  	// Setup objects carrying data to JS. These are created once and re-used.
   198  	t.log = &steplog{
   199  		vm:       vm,
   200  		op:       &opObj{vm: vm},
   201  		memory:   &memoryObj{vm: vm, toBig: t.toBig, toBuf: t.toBuf},
   202  		stack:    &stackObj{vm: vm, toBig: t.toBig},
   203  		contract: &contractObj{vm: vm, toBig: t.toBig, toBuf: t.toBuf},
   204  	}
   205  	t.frame = &callframe{vm: vm, toBig: t.toBig, toBuf: t.toBuf}
   206  	t.frameResult = &callframeResult{vm: vm, toBuf: t.toBuf}
   207  	t.frameValue = t.frame.setupObject()
   208  	t.frameResultValue = t.frameResult.setupObject()
   209  	t.logValue = t.log.setupObject()
   210  	return t, nil
   211  }
   212  
   213  // CaptureTxStart implements the Tracer interface and is invoked at the beginning of
   214  // transaction processing.
   215  func (t *jsTracer) CaptureTxStart(gasLimit uint64) {
   216  	t.gasLimit = gasLimit
   217  }
   218  
   219  // CaptureTxEnd implements the Tracer interface and is invoked at the end of
   220  // transaction processing.
   221  func (t *jsTracer) CaptureTxEnd(restGas uint64) {
   222  	t.ctx["gasUsed"] = t.vm.ToValue(t.gasLimit - restGas)
   223  }
   224  
   225  // CaptureStart implements the Tracer interface to initialize the tracing operation.
   226  func (t *jsTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
   227  	t.env = env
   228  	db := &dbObj{db: env.StateDB, vm: t.vm, toBig: t.toBig, toBuf: t.toBuf, fromBuf: t.fromBuf}
   229  	t.dbValue = db.setupObject()
   230  	if create {
   231  		t.ctx["type"] = t.vm.ToValue("CREATE")
   232  	} else {
   233  		t.ctx["type"] = t.vm.ToValue("CALL")
   234  	}
   235  	t.ctx["from"] = t.vm.ToValue(from.Bytes())
   236  	t.ctx["to"] = t.vm.ToValue(to.Bytes())
   237  	t.ctx["input"] = t.vm.ToValue(input)
   238  	t.ctx["gas"] = t.vm.ToValue(t.gasLimit)
   239  	t.ctx["gasPrice"] = t.vm.ToValue(env.TxContext.GasPrice)
   240  	valueBig, err := t.toBig(t.vm, value.String())
   241  	if err != nil {
   242  		t.err = err
   243  		return
   244  	}
   245  	t.ctx["value"] = valueBig
   246  	t.ctx["block"] = t.vm.ToValue(env.Context.BlockNumber.Uint64())
   247  	// Update list of precompiles based on current block
   248  	rules := env.ChainConfig().Rules(env.Context.BlockNumber, env.Context.Random != nil, env.Context.Time)
   249  	t.activePrecompiles = vm.ActivePrecompiles(rules)
   250  }
   251  
   252  // CaptureState implements the Tracer interface to trace a single step of VM execution.
   253  func (t *jsTracer) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) {
   254  	if !t.traceStep {
   255  		return
   256  	}
   257  	if t.err != nil {
   258  		return
   259  	}
   260  
   261  	log := t.log
   262  	log.op.op = op
   263  	log.memory.memory = scope.Memory
   264  	log.stack.stack = scope.Stack
   265  	log.contract.contract = scope.Contract
   266  	log.pc = pc
   267  	log.gas = gas
   268  	log.cost = cost
   269  	log.refund = t.env.StateDB.GetRefund()
   270  	log.depth = depth
   271  	log.err = err
   272  	if _, err := t.step(t.obj, t.logValue, t.dbValue); err != nil {
   273  		t.onError("step", err)
   274  	}
   275  }
   276  
   277  // CaptureFault implements the Tracer interface to trace an execution fault
   278  func (t *jsTracer) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, depth int, err error) {
   279  	if t.err != nil {
   280  		return
   281  	}
   282  	// Other log fields have been already set as part of the last CaptureState.
   283  	t.log.err = err
   284  	if _, err := t.fault(t.obj, t.logValue, t.dbValue); err != nil {
   285  		t.onError("fault", err)
   286  	}
   287  }
   288  
   289  // CaptureEnd is called after the call finishes to finalize the tracing.
   290  func (t *jsTracer) CaptureEnd(output []byte, gasUsed uint64, err error) {
   291  	t.ctx["output"] = t.vm.ToValue(output)
   292  	if err != nil {
   293  		t.ctx["error"] = t.vm.ToValue(err.Error())
   294  	}
   295  }
   296  
   297  // CaptureEnter is called when EVM enters a new scope (via call, create or selfdestruct).
   298  func (t *jsTracer) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) {
   299  	if !t.traceFrame {
   300  		return
   301  	}
   302  	if t.err != nil {
   303  		return
   304  	}
   305  
   306  	t.frame.typ = typ.String()
   307  	t.frame.from = from
   308  	t.frame.to = to
   309  	t.frame.input = common.CopyBytes(input)
   310  	t.frame.gas = uint(gas)
   311  	t.frame.value = nil
   312  	if value != nil {
   313  		t.frame.value = new(big.Int).SetBytes(value.Bytes())
   314  	}
   315  
   316  	if _, err := t.enter(t.obj, t.frameValue); err != nil {
   317  		t.onError("enter", err)
   318  	}
   319  }
   320  
   321  // CaptureExit is called when EVM exits a scope, even if the scope didn't
   322  // execute any code.
   323  func (t *jsTracer) CaptureExit(output []byte, gasUsed uint64, err error) {
   324  	if !t.traceFrame {
   325  		return
   326  	}
   327  
   328  	t.frameResult.gasUsed = uint(gasUsed)
   329  	t.frameResult.output = common.CopyBytes(output)
   330  	t.frameResult.err = err
   331  
   332  	if _, err := t.exit(t.obj, t.frameResultValue); err != nil {
   333  		t.onError("exit", err)
   334  	}
   335  }
   336  
   337  // GetResult calls the Javascript 'result' function and returns its value, or any accumulated error
   338  func (t *jsTracer) GetResult() (json.RawMessage, error) {
   339  	ctx := t.vm.ToValue(t.ctx)
   340  	res, err := t.result(t.obj, ctx, t.dbValue)
   341  	if err != nil {
   342  		return nil, wrapError("result", err)
   343  	}
   344  	encoded, err := json.Marshal(res)
   345  	if err != nil {
   346  		return nil, err
   347  	}
   348  	return json.RawMessage(encoded), t.err
   349  }
   350  
   351  // Stop terminates execution of the tracer at the first opportune moment.
   352  func (t *jsTracer) Stop(err error) {
   353  	t.vm.Interrupt(err)
   354  }
   355  
   356  // onError is called anytime the running JS code is interrupted
   357  // and returns an error. It in turn pings the EVM to cancel its
   358  // execution.
   359  func (t *jsTracer) onError(context string, err error) {
   360  	t.err = wrapError(context, err)
   361  	// `env` is set on CaptureStart which comes before any JS execution.
   362  	// So it should be non-nil.
   363  	t.env.Cancel()
   364  }
   365  
   366  func wrapError(context string, err error) error {
   367  	return fmt.Errorf("%v    in server-side tracer function '%v'", err, context)
   368  }
   369  
   370  // setBuiltinFunctions injects Go functions which are available to tracers into the environment.
   371  // It depends on type converters having been set up.
   372  func (t *jsTracer) setBuiltinFunctions() {
   373  	vm := t.vm
   374  	// TODO: load console from goja-nodejs
   375  	vm.Set("toHex", func(v goja.Value) string {
   376  		b, err := t.fromBuf(vm, v, false)
   377  		if err != nil {
   378  			vm.Interrupt(err)
   379  			return ""
   380  		}
   381  		return hexutil.Encode(b)
   382  	})
   383  	vm.Set("toWord", func(v goja.Value) goja.Value {
   384  		// TODO: add test with []byte len < 32 or > 32
   385  		b, err := t.fromBuf(vm, v, true)
   386  		if err != nil {
   387  			vm.Interrupt(err)
   388  			return nil
   389  		}
   390  		b = common.BytesToHash(b).Bytes()
   391  		res, err := t.toBuf(vm, b)
   392  		if err != nil {
   393  			vm.Interrupt(err)
   394  			return nil
   395  		}
   396  		return res
   397  	})
   398  	vm.Set("toAddress", func(v goja.Value) goja.Value {
   399  		a, err := t.fromBuf(vm, v, true)
   400  		if err != nil {
   401  			vm.Interrupt(err)
   402  			return nil
   403  		}
   404  		a = common.BytesToAddress(a).Bytes()
   405  		res, err := t.toBuf(vm, a)
   406  		if err != nil {
   407  			vm.Interrupt(err)
   408  			return nil
   409  		}
   410  		return res
   411  	})
   412  	vm.Set("toContract", func(from goja.Value, nonce uint) goja.Value {
   413  		a, err := t.fromBuf(vm, from, true)
   414  		if err != nil {
   415  			vm.Interrupt(err)
   416  			return nil
   417  		}
   418  		addr := common.BytesToAddress(a)
   419  		b := crypto.CreateAddress(addr, uint64(nonce)).Bytes()
   420  		res, err := t.toBuf(vm, b)
   421  		if err != nil {
   422  			vm.Interrupt(err)
   423  			return nil
   424  		}
   425  		return res
   426  	})
   427  	vm.Set("toContract2", func(from goja.Value, salt string, initcode goja.Value) goja.Value {
   428  		a, err := t.fromBuf(vm, from, true)
   429  		if err != nil {
   430  			vm.Interrupt(err)
   431  			return nil
   432  		}
   433  		addr := common.BytesToAddress(a)
   434  		code, err := t.fromBuf(vm, initcode, true)
   435  		if err != nil {
   436  			vm.Interrupt(err)
   437  			return nil
   438  		}
   439  		code = common.CopyBytes(code)
   440  		codeHash := crypto.Keccak256(code)
   441  		b := crypto.CreateAddress2(addr, common.HexToHash(salt), codeHash).Bytes()
   442  		res, err := t.toBuf(vm, b)
   443  		if err != nil {
   444  			vm.Interrupt(err)
   445  			return nil
   446  		}
   447  		return res
   448  	})
   449  	vm.Set("isPrecompiled", func(v goja.Value) bool {
   450  		a, err := t.fromBuf(vm, v, true)
   451  		if err != nil {
   452  			vm.Interrupt(err)
   453  			return false
   454  		}
   455  		addr := common.BytesToAddress(a)
   456  		for _, p := range t.activePrecompiles {
   457  			if p == addr {
   458  				return true
   459  			}
   460  		}
   461  		return false
   462  	})
   463  	vm.Set("slice", func(slice goja.Value, start, end int) goja.Value {
   464  		b, err := t.fromBuf(vm, slice, false)
   465  		if err != nil {
   466  			vm.Interrupt(err)
   467  			return nil
   468  		}
   469  		if start < 0 || start > end || end > len(b) {
   470  			vm.Interrupt(fmt.Sprintf("Tracer accessed out of bound memory: available %d, offset %d, size %d", len(b), start, end-start))
   471  			return nil
   472  		}
   473  		res, err := t.toBuf(vm, b[start:end])
   474  		if err != nil {
   475  			vm.Interrupt(err)
   476  			return nil
   477  		}
   478  		return res
   479  	})
   480  }
   481  
   482  // setTypeConverters sets up utilities for converting Go types into those
   483  // suitable for JS consumption.
   484  func (t *jsTracer) setTypeConverters() error {
   485  	// Inject bigint logic.
   486  	// TODO: To be replaced after goja adds support for native JS bigint.
   487  	toBigCode, err := t.vm.RunProgram(bigIntProgram)
   488  	if err != nil {
   489  		return err
   490  	}
   491  	// Used to create JS bigint objects from go.
   492  	toBigFn, ok := goja.AssertFunction(toBigCode)
   493  	if !ok {
   494  		return errors.New("failed to bind bigInt func")
   495  	}
   496  	toBigWrapper := func(vm *goja.Runtime, val string) (goja.Value, error) {
   497  		return toBigFn(goja.Undefined(), vm.ToValue(val))
   498  	}
   499  	t.toBig = toBigWrapper
   500  	// NOTE: We need this workaround to create JS buffers because
   501  	// goja doesn't at the moment expose constructors for typed arrays.
   502  	//
   503  	// Cache uint8ArrayType once to be used every time for less overhead.
   504  	uint8ArrayType := t.vm.Get("Uint8Array")
   505  	toBufWrapper := func(vm *goja.Runtime, val []byte) (goja.Value, error) {
   506  		return toBuf(vm, uint8ArrayType, val)
   507  	}
   508  	t.toBuf = toBufWrapper
   509  	fromBufWrapper := func(vm *goja.Runtime, buf goja.Value, allowString bool) ([]byte, error) {
   510  		return fromBuf(vm, uint8ArrayType, buf, allowString)
   511  	}
   512  	t.fromBuf = fromBufWrapper
   513  	return nil
   514  }
   515  
   516  type opObj struct {
   517  	vm *goja.Runtime
   518  	op vm.OpCode
   519  }
   520  
   521  func (o *opObj) ToNumber() int {
   522  	return int(o.op)
   523  }
   524  
   525  func (o *opObj) ToString() string {
   526  	return o.op.String()
   527  }
   528  
   529  func (o *opObj) IsPush() bool {
   530  	return o.op.IsPush()
   531  }
   532  
   533  func (o *opObj) setupObject() *goja.Object {
   534  	obj := o.vm.NewObject()
   535  	obj.Set("toNumber", o.vm.ToValue(o.ToNumber))
   536  	obj.Set("toString", o.vm.ToValue(o.ToString))
   537  	obj.Set("isPush", o.vm.ToValue(o.IsPush))
   538  	return obj
   539  }
   540  
   541  type memoryObj struct {
   542  	memory *vm.Memory
   543  	vm     *goja.Runtime
   544  	toBig  toBigFn
   545  	toBuf  toBufFn
   546  }
   547  
   548  func (mo *memoryObj) Slice(begin, end int64) goja.Value {
   549  	b, err := mo.slice(begin, end)
   550  	if err != nil {
   551  		mo.vm.Interrupt(err)
   552  		return nil
   553  	}
   554  	res, err := mo.toBuf(mo.vm, b)
   555  	if err != nil {
   556  		mo.vm.Interrupt(err)
   557  		return nil
   558  	}
   559  	return res
   560  }
   561  
   562  // slice returns the requested range of memory as a byte slice.
   563  func (mo *memoryObj) slice(begin, end int64) ([]byte, error) {
   564  	if end == begin {
   565  		return []byte{}, nil
   566  	}
   567  	if end < begin || begin < 0 {
   568  		return nil, fmt.Errorf("tracer accessed out of bound memory: offset %d, end %d", begin, end)
   569  	}
   570  	slice, err := tracers.GetMemoryCopyPadded(mo.memory, begin, end-begin)
   571  	if err != nil {
   572  		return nil, err
   573  	}
   574  	return slice, nil
   575  }
   576  
   577  func (mo *memoryObj) GetUint(addr int64) goja.Value {
   578  	value, err := mo.getUint(addr)
   579  	if err != nil {
   580  		mo.vm.Interrupt(err)
   581  		return nil
   582  	}
   583  	res, err := mo.toBig(mo.vm, value.String())
   584  	if err != nil {
   585  		mo.vm.Interrupt(err)
   586  		return nil
   587  	}
   588  	return res
   589  }
   590  
   591  // getUint returns the 32 bytes at the specified address interpreted as a uint.
   592  func (mo *memoryObj) getUint(addr int64) (*big.Int, error) {
   593  	if mo.memory.Len() < int(addr)+32 || addr < 0 {
   594  		return nil, fmt.Errorf("tracer accessed out of bound memory: available %d, offset %d, size %d", mo.memory.Len(), addr, 32)
   595  	}
   596  	return new(big.Int).SetBytes(mo.memory.GetPtr(addr, 32)), nil
   597  }
   598  
   599  func (mo *memoryObj) Length() int {
   600  	return mo.memory.Len()
   601  }
   602  
   603  func (m *memoryObj) setupObject() *goja.Object {
   604  	o := m.vm.NewObject()
   605  	o.Set("slice", m.vm.ToValue(m.Slice))
   606  	o.Set("getUint", m.vm.ToValue(m.GetUint))
   607  	o.Set("length", m.vm.ToValue(m.Length))
   608  	return o
   609  }
   610  
   611  type stackObj struct {
   612  	stack *vm.Stack
   613  	vm    *goja.Runtime
   614  	toBig toBigFn
   615  }
   616  
   617  func (s *stackObj) Peek(idx int) goja.Value {
   618  	value, err := s.peek(idx)
   619  	if err != nil {
   620  		s.vm.Interrupt(err)
   621  		return nil
   622  	}
   623  	res, err := s.toBig(s.vm, value.String())
   624  	if err != nil {
   625  		s.vm.Interrupt(err)
   626  		return nil
   627  	}
   628  	return res
   629  }
   630  
   631  // peek returns the nth-from-the-top element of the stack.
   632  func (s *stackObj) peek(idx int) (*big.Int, error) {
   633  	if len(s.stack.Data()) <= idx || idx < 0 {
   634  		return nil, fmt.Errorf("tracer accessed out of bound stack: size %d, index %d", len(s.stack.Data()), idx)
   635  	}
   636  	return s.stack.Back(idx).ToBig(), nil
   637  }
   638  
   639  func (s *stackObj) Length() int {
   640  	return len(s.stack.Data())
   641  }
   642  
   643  func (s *stackObj) setupObject() *goja.Object {
   644  	o := s.vm.NewObject()
   645  	o.Set("peek", s.vm.ToValue(s.Peek))
   646  	o.Set("length", s.vm.ToValue(s.Length))
   647  	return o
   648  }
   649  
   650  type dbObj struct {
   651  	db      vm.StateDB
   652  	vm      *goja.Runtime
   653  	toBig   toBigFn
   654  	toBuf   toBufFn
   655  	fromBuf fromBufFn
   656  }
   657  
   658  func (do *dbObj) GetBalance(addrSlice goja.Value) goja.Value {
   659  	a, err := do.fromBuf(do.vm, addrSlice, false)
   660  	if err != nil {
   661  		do.vm.Interrupt(err)
   662  		return nil
   663  	}
   664  	addr := common.BytesToAddress(a)
   665  	value := do.db.GetBalance(addr)
   666  	res, err := do.toBig(do.vm, value.String())
   667  	if err != nil {
   668  		do.vm.Interrupt(err)
   669  		return nil
   670  	}
   671  	return res
   672  }
   673  
   674  func (do *dbObj) GetNonce(addrSlice goja.Value) uint64 {
   675  	a, err := do.fromBuf(do.vm, addrSlice, false)
   676  	if err != nil {
   677  		do.vm.Interrupt(err)
   678  		return 0
   679  	}
   680  	addr := common.BytesToAddress(a)
   681  	return do.db.GetNonce(addr)
   682  }
   683  
   684  func (do *dbObj) GetCode(addrSlice goja.Value) goja.Value {
   685  	a, err := do.fromBuf(do.vm, addrSlice, false)
   686  	if err != nil {
   687  		do.vm.Interrupt(err)
   688  		return nil
   689  	}
   690  	addr := common.BytesToAddress(a)
   691  	code := do.db.GetCode(addr)
   692  	res, err := do.toBuf(do.vm, code)
   693  	if err != nil {
   694  		do.vm.Interrupt(err)
   695  		return nil
   696  	}
   697  	return res
   698  }
   699  
   700  func (do *dbObj) GetState(addrSlice goja.Value, hashSlice goja.Value) goja.Value {
   701  	a, err := do.fromBuf(do.vm, addrSlice, false)
   702  	if err != nil {
   703  		do.vm.Interrupt(err)
   704  		return nil
   705  	}
   706  	addr := common.BytesToAddress(a)
   707  	h, err := do.fromBuf(do.vm, hashSlice, false)
   708  	if err != nil {
   709  		do.vm.Interrupt(err)
   710  		return nil
   711  	}
   712  	hash := common.BytesToHash(h)
   713  	state := do.db.GetState(addr, hash).Bytes()
   714  	res, err := do.toBuf(do.vm, state)
   715  	if err != nil {
   716  		do.vm.Interrupt(err)
   717  		return nil
   718  	}
   719  	return res
   720  }
   721  
   722  func (do *dbObj) Exists(addrSlice goja.Value) bool {
   723  	a, err := do.fromBuf(do.vm, addrSlice, false)
   724  	if err != nil {
   725  		do.vm.Interrupt(err)
   726  		return false
   727  	}
   728  	addr := common.BytesToAddress(a)
   729  	return do.db.Exist(addr)
   730  }
   731  
   732  func (do *dbObj) setupObject() *goja.Object {
   733  	o := do.vm.NewObject()
   734  	o.Set("getBalance", do.vm.ToValue(do.GetBalance))
   735  	o.Set("getNonce", do.vm.ToValue(do.GetNonce))
   736  	o.Set("getCode", do.vm.ToValue(do.GetCode))
   737  	o.Set("getState", do.vm.ToValue(do.GetState))
   738  	o.Set("exists", do.vm.ToValue(do.Exists))
   739  	return o
   740  }
   741  
   742  type contractObj struct {
   743  	contract *vm.Contract
   744  	vm       *goja.Runtime
   745  	toBig    toBigFn
   746  	toBuf    toBufFn
   747  }
   748  
   749  func (co *contractObj) GetCaller() goja.Value {
   750  	caller := co.contract.Caller().Bytes()
   751  	res, err := co.toBuf(co.vm, caller)
   752  	if err != nil {
   753  		co.vm.Interrupt(err)
   754  		return nil
   755  	}
   756  	return res
   757  }
   758  
   759  func (co *contractObj) GetAddress() goja.Value {
   760  	addr := co.contract.Address().Bytes()
   761  	res, err := co.toBuf(co.vm, addr)
   762  	if err != nil {
   763  		co.vm.Interrupt(err)
   764  		return nil
   765  	}
   766  	return res
   767  }
   768  
   769  func (co *contractObj) GetValue() goja.Value {
   770  	value := co.contract.Value()
   771  	res, err := co.toBig(co.vm, value.String())
   772  	if err != nil {
   773  		co.vm.Interrupt(err)
   774  		return nil
   775  	}
   776  	return res
   777  }
   778  
   779  func (co *contractObj) GetInput() goja.Value {
   780  	input := common.CopyBytes(co.contract.Input)
   781  	res, err := co.toBuf(co.vm, input)
   782  	if err != nil {
   783  		co.vm.Interrupt(err)
   784  		return nil
   785  	}
   786  	return res
   787  }
   788  
   789  func (c *contractObj) setupObject() *goja.Object {
   790  	o := c.vm.NewObject()
   791  	o.Set("getCaller", c.vm.ToValue(c.GetCaller))
   792  	o.Set("getAddress", c.vm.ToValue(c.GetAddress))
   793  	o.Set("getValue", c.vm.ToValue(c.GetValue))
   794  	o.Set("getInput", c.vm.ToValue(c.GetInput))
   795  	return o
   796  }
   797  
   798  type callframe struct {
   799  	vm    *goja.Runtime
   800  	toBig toBigFn
   801  	toBuf toBufFn
   802  
   803  	typ   string
   804  	from  common.Address
   805  	to    common.Address
   806  	input []byte
   807  	gas   uint
   808  	value *big.Int
   809  }
   810  
   811  func (f *callframe) GetType() string {
   812  	return f.typ
   813  }
   814  
   815  func (f *callframe) GetFrom() goja.Value {
   816  	from := f.from.Bytes()
   817  	res, err := f.toBuf(f.vm, from)
   818  	if err != nil {
   819  		f.vm.Interrupt(err)
   820  		return nil
   821  	}
   822  	return res
   823  }
   824  
   825  func (f *callframe) GetTo() goja.Value {
   826  	to := f.to.Bytes()
   827  	res, err := f.toBuf(f.vm, to)
   828  	if err != nil {
   829  		f.vm.Interrupt(err)
   830  		return nil
   831  	}
   832  	return res
   833  }
   834  
   835  func (f *callframe) GetInput() goja.Value {
   836  	input := f.input
   837  	res, err := f.toBuf(f.vm, input)
   838  	if err != nil {
   839  		f.vm.Interrupt(err)
   840  		return nil
   841  	}
   842  	return res
   843  }
   844  
   845  func (f *callframe) GetGas() uint {
   846  	return f.gas
   847  }
   848  
   849  func (f *callframe) GetValue() goja.Value {
   850  	if f.value == nil {
   851  		return goja.Undefined()
   852  	}
   853  	res, err := f.toBig(f.vm, f.value.String())
   854  	if err != nil {
   855  		f.vm.Interrupt(err)
   856  		return nil
   857  	}
   858  	return res
   859  }
   860  
   861  func (f *callframe) setupObject() *goja.Object {
   862  	o := f.vm.NewObject()
   863  	o.Set("getType", f.vm.ToValue(f.GetType))
   864  	o.Set("getFrom", f.vm.ToValue(f.GetFrom))
   865  	o.Set("getTo", f.vm.ToValue(f.GetTo))
   866  	o.Set("getInput", f.vm.ToValue(f.GetInput))
   867  	o.Set("getGas", f.vm.ToValue(f.GetGas))
   868  	o.Set("getValue", f.vm.ToValue(f.GetValue))
   869  	return o
   870  }
   871  
   872  type callframeResult struct {
   873  	vm    *goja.Runtime
   874  	toBuf toBufFn
   875  
   876  	gasUsed uint
   877  	output  []byte
   878  	err     error
   879  }
   880  
   881  func (r *callframeResult) GetGasUsed() uint {
   882  	return r.gasUsed
   883  }
   884  
   885  func (r *callframeResult) GetOutput() goja.Value {
   886  	res, err := r.toBuf(r.vm, r.output)
   887  	if err != nil {
   888  		r.vm.Interrupt(err)
   889  		return nil
   890  	}
   891  	return res
   892  }
   893  
   894  func (r *callframeResult) GetError() goja.Value {
   895  	if r.err != nil {
   896  		return r.vm.ToValue(r.err.Error())
   897  	}
   898  	return goja.Undefined()
   899  }
   900  
   901  func (r *callframeResult) setupObject() *goja.Object {
   902  	o := r.vm.NewObject()
   903  	o.Set("getGasUsed", r.vm.ToValue(r.GetGasUsed))
   904  	o.Set("getOutput", r.vm.ToValue(r.GetOutput))
   905  	o.Set("getError", r.vm.ToValue(r.GetError))
   906  	return o
   907  }
   908  
   909  type steplog struct {
   910  	vm *goja.Runtime
   911  
   912  	op       *opObj
   913  	memory   *memoryObj
   914  	stack    *stackObj
   915  	contract *contractObj
   916  
   917  	pc     uint64
   918  	gas    uint64
   919  	cost   uint64
   920  	depth  int
   921  	refund uint64
   922  	err    error
   923  }
   924  
   925  func (l *steplog) GetPC() uint64     { return l.pc }
   926  func (l *steplog) GetGas() uint64    { return l.gas }
   927  func (l *steplog) GetCost() uint64   { return l.cost }
   928  func (l *steplog) GetDepth() int     { return l.depth }
   929  func (l *steplog) GetRefund() uint64 { return l.refund }
   930  
   931  func (l *steplog) GetError() goja.Value {
   932  	if l.err != nil {
   933  		return l.vm.ToValue(l.err.Error())
   934  	}
   935  	return goja.Undefined()
   936  }
   937  
   938  func (l *steplog) setupObject() *goja.Object {
   939  	o := l.vm.NewObject()
   940  	// Setup basic fields.
   941  	o.Set("getPC", l.vm.ToValue(l.GetPC))
   942  	o.Set("getGas", l.vm.ToValue(l.GetGas))
   943  	o.Set("getCost", l.vm.ToValue(l.GetCost))
   944  	o.Set("getDepth", l.vm.ToValue(l.GetDepth))
   945  	o.Set("getRefund", l.vm.ToValue(l.GetRefund))
   946  	o.Set("getError", l.vm.ToValue(l.GetError))
   947  	// Setup nested objects.
   948  	o.Set("op", l.op.setupObject())
   949  	o.Set("stack", l.stack.setupObject())
   950  	o.Set("memory", l.memory.setupObject())
   951  	o.Set("contract", l.contract.setupObject())
   952  	return o
   953  }