Merge feature/merge-v1.10.18-attempt-two

This commit is contained in:
philip-morlier
2022-05-25 13:07:38 -07:00
438 changed files with 129587 additions and 152641 deletions
+36 -69
View File
@@ -22,7 +22,6 @@ import (
"context"
"errors"
"fmt"
"io/ioutil"
"os"
"runtime"
"sync"
@@ -41,7 +40,6 @@ import (
"github.com/ethereum/go-ethereum/internal/ethapi"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/plugins/interfaces"
"github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/rpc"
)
@@ -464,7 +462,7 @@ func (api *API) TraceBlock(ctx context.Context, blob hexutil.Bytes, config *Trac
// TraceBlockFromFile returns the structured logs created during the execution of
// EVM and returns them as a JSON object.
func (api *API) TraceBlockFromFile(ctx context.Context, file string, config *TraceConfig) ([]*txTraceResult, error) {
blob, err := ioutil.ReadFile(file)
blob, err := os.ReadFile(file)
if err != nil {
return nil, fmt.Errorf("could not read file: %v", err)
}
@@ -723,7 +721,7 @@ func (api *API) standardTraceBlockToFile(ctx context.Context, block *types.Block
if !canon {
prefix = fmt.Sprintf("%valt-", prefix)
}
dump, err = ioutil.TempFile(os.TempDir(), prefix)
dump, err = os.CreateTemp(os.TempDir(), prefix)
if err != nil {
return nil, err
}
@@ -863,82 +861,51 @@ func (api *API) TraceCall(ctx context.Context, args ethapi.TransactionArgs, bloc
// executes the given message in the provided environment. The return value will
// be tracer dependent.
func (api *API) traceTx(ctx context.Context, message core.Message, txctx *Context, vmctx vm.BlockContext, statedb *state.StateDB, config *TraceConfig) (interface{}, error) {
// Assemble the structured logger or the JavaScript tracer
var (
tracer vm.EVMLogger
tracer Tracer
err error
timeout = defaultTraceTimeout
txContext = core.NewEVMTxContext(message)
)
switch {
case config == nil:
tracer = logger.NewStructLogger(nil)
case config.Tracer != nil:
// Define a meaningful timeout of a single transaction trace
timeout := defaultTraceTimeout
if config.Timeout != nil {
if timeout, err = time.ParseDuration(*config.Timeout); err != nil {
return nil, err
}
}
// Get the tracer from the plugin loader
//begin PluGeth code injection
if tr, ok := getPluginTracer(*config.Tracer); ok {
//end PluGeth code injection
tracer = tr(statedb, vmctx)
} else {
// Constuct the JavaScript tracer to execute with
if t, err := New(*config.Tracer, txctx); err != nil {
return nil, err
} else {
deadlineCtx, cancel := context.WithTimeout(ctx, timeout)
go func() {
<-deadlineCtx.Done()
if errors.Is(deadlineCtx.Err(), context.DeadlineExceeded) {
t.Stop(errors.New("execution timeout"))
}
}()
defer cancel()
tracer = t
}
}
default:
tracer = logger.NewStructLogger(config.Config)
if config == nil {
config = &TraceConfig{}
}
// Default tracer is the struct logger
tracer = logger.NewStructLogger(config.Config)
// Get the tracer from the plugin loader
//begin PluGeth code injection
if tr, ok := getPluginTracer(*config.Tracer); ok {
//end PluGeth code injection
tracer = tr(statedb, vmctx)
} else if config.Tracer != nil {
tracer, err = New(*config.Tracer, txctx)
if err != nil {
return nil, err
}
}
// Define a meaningful timeout of a single transaction trace
if config.Timeout != nil {
if timeout, err = time.ParseDuration(*config.Timeout); err != nil {
return nil, err
}
}
deadlineCtx, cancel := context.WithTimeout(ctx, timeout)
go func() {
<-deadlineCtx.Done()
if errors.Is(deadlineCtx.Err(), context.DeadlineExceeded) {
tracer.Stop(errors.New("execution timeout"))
}
}()
defer cancel()
// Run the transaction with tracing enabled.
vmenv := vm.NewEVM(vmctx, txContext, statedb, api.backend.ChainConfig(), vm.Config{Debug: true, Tracer: tracer, NoBaseFee: true})
// Call Prepare to clear out the statedb access list
statedb.Prepare(txctx.TxHash, txctx.TxIndex)
result, err := core.ApplyMessage(vmenv, message, new(core.GasPool).AddGas(message.Gas()))
if err != nil {
if _, err = core.ApplyMessage(vmenv, message, new(core.GasPool).AddGas(message.Gas())); err != nil {
return nil, fmt.Errorf("tracing failed: %w", err)
}
// Depending on the tracer type, format and return the output.
switch tracer := tracer.(type) {
case *logger.StructLogger:
// If the result contains a revert reason, return it.
returnVal := fmt.Sprintf("%x", result.Return())
if len(result.Revert()) > 0 {
returnVal = fmt.Sprintf("%x", result.Revert())
}
return &ethapi.ExecutionResult{
Gas: result.UsedGas,
Failed: result.Failed(),
ReturnValue: returnVal,
StructLogs: ethapi.FormatLogs(tracer.StructLogs()),
}, nil
case interfaces.TracerResult:
return tracer.GetResult()
case Tracer:
return tracer.GetResult()
default:
panic(fmt.Sprintf("bad tracer type %T", tracer))
}
return tracer.GetResult()
}
// APIs return the collection of RPC services the tracer package offers.
+21 -12
View File
@@ -39,6 +39,7 @@ import (
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth/tracers/logger"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/internal/ethapi"
"github.com/ethereum/go-ethereum/params"
@@ -213,11 +214,11 @@ func TestTraceCall(t *testing.T) {
},
config: nil,
expectErr: nil,
expect: &ethapi.ExecutionResult{
expect: &logger.ExecutionResult{
Gas: params.TxGas,
Failed: false,
ReturnValue: "",
StructLogs: []ethapi.StructLogRes{},
StructLogs: []logger.StructLogRes{},
},
},
// Standard JSON trace upon the head, plain transfer.
@@ -230,11 +231,11 @@ func TestTraceCall(t *testing.T) {
},
config: nil,
expectErr: nil,
expect: &ethapi.ExecutionResult{
expect: &logger.ExecutionResult{
Gas: params.TxGas,
Failed: false,
ReturnValue: "",
StructLogs: []ethapi.StructLogRes{},
StructLogs: []logger.StructLogRes{},
},
},
// Standard JSON trace upon the non-existent block, error expects
@@ -259,11 +260,11 @@ func TestTraceCall(t *testing.T) {
},
config: nil,
expectErr: nil,
expect: &ethapi.ExecutionResult{
expect: &logger.ExecutionResult{
Gas: params.TxGas,
Failed: false,
ReturnValue: "",
StructLogs: []ethapi.StructLogRes{},
StructLogs: []logger.StructLogRes{},
},
},
// Standard JSON trace upon the pending block
@@ -276,11 +277,11 @@ func TestTraceCall(t *testing.T) {
},
config: nil,
expectErr: nil,
expect: &ethapi.ExecutionResult{
expect: &logger.ExecutionResult{
Gas: params.TxGas,
Failed: false,
ReturnValue: "",
StructLogs: []ethapi.StructLogRes{},
StructLogs: []logger.StructLogRes{},
},
},
}
@@ -299,8 +300,12 @@ func TestTraceCall(t *testing.T) {
t.Errorf("Expect no error, get %v", err)
continue
}
if !reflect.DeepEqual(result, testspec.expect) {
t.Errorf("Result mismatch, want %v, get %v", testspec.expect, result)
var have *logger.ExecutionResult
if err := json.Unmarshal(result.(json.RawMessage), &have); err != nil {
t.Errorf("failed to unmarshal result %v", err)
}
if !reflect.DeepEqual(have, testspec.expect) {
t.Errorf("Result mismatch, want %v, get %v", testspec.expect, have)
}
}
}
@@ -329,11 +334,15 @@ func TestTraceTransaction(t *testing.T) {
if err != nil {
t.Errorf("Failed to trace transaction %v", err)
}
if !reflect.DeepEqual(result, &ethapi.ExecutionResult{
var have *logger.ExecutionResult
if err := json.Unmarshal(result.(json.RawMessage), &have); err != nil {
t.Errorf("failed to unmarshal result %v", err)
}
if !reflect.DeepEqual(have, &logger.ExecutionResult{
Gas: params.TxGas,
Failed: false,
ReturnValue: "",
StructLogs: []ethapi.StructLogRes{},
StructLogs: []logger.StructLogRes{},
}) {
t.Error("Transaction tracing result is different")
}
@@ -18,8 +18,8 @@ package tracetest
import (
"encoding/json"
"io/ioutil"
"math/big"
"os"
"path/filepath"
"reflect"
"strings"
@@ -135,7 +135,7 @@ func TestCallTracerNative(t *testing.T) {
}
func testCallTracer(tracerName string, dirPath string, t *testing.T) {
files, err := ioutil.ReadDir(filepath.Join("testdata", dirPath))
files, err := os.ReadDir(filepath.Join("testdata", dirPath))
if err != nil {
t.Fatalf("failed to retrieve tracer test suite: %v", err)
}
@@ -152,7 +152,7 @@ func testCallTracer(tracerName string, dirPath string, t *testing.T) {
tx = new(types.Transaction)
)
// Call tracer test found, read if from disk
if blob, err := ioutil.ReadFile(filepath.Join("testdata", dirPath, file.Name())); err != nil {
if blob, err := os.ReadFile(filepath.Join("testdata", dirPath, file.Name())); err != nil {
t.Fatalf("failed to read testcase: %v", err)
} else if err := json.Unmarshal(blob, test); err != nil {
t.Fatalf("failed to parse testcase: %v", err)
@@ -240,7 +240,7 @@ func camel(str string) string {
return strings.Join(pieces, "")
}
func BenchmarkTracers(b *testing.B) {
files, err := ioutil.ReadDir(filepath.Join("testdata", "call_tracer"))
files, err := os.ReadDir(filepath.Join("testdata", "call_tracer"))
if err != nil {
b.Fatalf("failed to retrieve tracer test suite: %v", err)
}
@@ -250,7 +250,7 @@ func BenchmarkTracers(b *testing.B) {
}
file := file // capture range variable
b.Run(camel(strings.TrimSuffix(file.Name(), ".json")), func(b *testing.B) {
blob, err := ioutil.ReadFile(filepath.Join("testdata", "call_tracer", file.Name()))
blob, err := os.ReadFile(filepath.Join("testdata", "call_tracer", file.Name()))
if err != nil {
b.Fatalf("failed to read testcase: %v", err)
}
@@ -258,7 +258,7 @@ func BenchmarkTracers(b *testing.B) {
if err := json.Unmarshal(blob, test); err != nil {
b.Fatalf("failed to parse testcase: %v", err)
}
benchTracer("callTracerNative", test, b)
benchTracer("callTracer", test, b)
})
}
}
+956
View File
@@ -0,0 +1,956 @@
// Copyright 2022 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package js
import (
"encoding/json"
"errors"
"fmt"
"math/big"
"time"
"github.com/dop251/goja"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth/tracers"
jsassets "github.com/ethereum/go-ethereum/eth/tracers/js/internal/tracers"
)
var assetTracers = make(map[string]string)
// init retrieves the JavaScript transaction tracers included in go-ethereum.
func init() {
var err error
assetTracers, err = jsassets.Load()
if err != nil {
panic(err)
}
tracers.RegisterLookup(true, newJsTracer)
}
// bigIntProgram is compiled once and the exported function mostly invoked to convert
// hex strings into big ints.
var bigIntProgram = goja.MustCompile("bigInt", bigIntegerJS, false)
type toBigFn = func(vm *goja.Runtime, val string) (goja.Value, error)
type toBufFn = func(vm *goja.Runtime, val []byte) (goja.Value, error)
type fromBufFn = func(vm *goja.Runtime, buf goja.Value, allowString bool) ([]byte, error)
func toBuf(vm *goja.Runtime, bufType goja.Value, val []byte) (goja.Value, error) {
// bufType is usually Uint8Array. This is equivalent to `new Uint8Array(val)` in JS.
res, err := vm.New(bufType, vm.ToValue(val))
if err != nil {
return nil, err
}
return vm.ToValue(res), nil
}
func fromBuf(vm *goja.Runtime, bufType goja.Value, buf goja.Value, allowString bool) ([]byte, error) {
obj := buf.ToObject(vm)
switch obj.ClassName() {
case "String":
if !allowString {
break
}
return common.FromHex(obj.String()), nil
case "Array":
var b []byte
if err := vm.ExportTo(buf, &b); err != nil {
return nil, err
}
return b, nil
case "Object":
if !obj.Get("constructor").SameAs(bufType) {
break
}
var b []byte
if err := vm.ExportTo(buf, &b); err != nil {
return nil, err
}
return b, nil
}
return nil, fmt.Errorf("invalid buffer type")
}
// jsTracer is an implementation of the Tracer interface which evaluates
// JS functions on the relevant EVM hooks. It uses Goja as its JS engine.
type jsTracer struct {
vm *goja.Runtime
env *vm.EVM
toBig toBigFn // Converts a hex string into a JS bigint
toBuf toBufFn // Converts a []byte into a JS buffer
fromBuf fromBufFn // Converts an array, hex string or Uint8Array to a []byte
ctx map[string]goja.Value // KV-bag passed to JS in `result`
activePrecompiles []common.Address // List of active precompiles at current block
traceStep bool // True if tracer object exposes a `step()` method
traceFrame bool // True if tracer object exposes the `enter()` and `exit()` methods
gasLimit uint64 // Amount of gas bought for the whole tx
err error // Any error that should stop tracing
obj *goja.Object // Trace object
// Methods exposed by tracer
result goja.Callable
fault goja.Callable
step goja.Callable
enter goja.Callable
exit goja.Callable
// Underlying structs being passed into JS
log *steplog
frame *callframe
frameResult *callframeResult
// Goja-wrapping of types prepared for JS consumption
logValue goja.Value
dbValue goja.Value
frameValue goja.Value
frameResultValue goja.Value
}
// newJsTracer instantiates a new JS tracer instance. code is either
// the name of a built-in JS tracer or a Javascript snippet which
// evaluates to an expression returning an object with certain methods.
// The methods `result` and `fault` are required to be present.
// The methods `step`, `enter`, and `exit` are optional, but note that
// `enter` and `exit` always go together.
func newJsTracer(code string, ctx *tracers.Context) (tracers.Tracer, error) {
if c, ok := assetTracers[code]; ok {
code = c
}
vm := goja.New()
// By default field names are exported to JS as is, i.e. capitalized.
vm.SetFieldNameMapper(goja.UncapFieldNameMapper())
t := &jsTracer{
vm: vm,
ctx: make(map[string]goja.Value),
}
if ctx == nil {
ctx = new(tracers.Context)
}
if ctx.BlockHash != (common.Hash{}) {
t.ctx["blockHash"] = vm.ToValue(ctx.BlockHash.Bytes())
if ctx.TxHash != (common.Hash{}) {
t.ctx["txIndex"] = vm.ToValue(ctx.TxIndex)
t.ctx["txHash"] = vm.ToValue(ctx.TxHash.Bytes())
}
}
t.setTypeConverters()
t.setBuiltinFunctions()
ret, err := vm.RunString("(" + code + ")")
if err != nil {
return nil, err
}
// Check tracer's interface for required and optional methods.
obj := ret.ToObject(vm)
result, ok := goja.AssertFunction(obj.Get("result"))
if !ok {
return nil, errors.New("trace object must expose a function result()")
}
fault, ok := goja.AssertFunction(obj.Get("fault"))
if !ok {
return nil, errors.New("trace object must expose a function fault()")
}
step, ok := goja.AssertFunction(obj.Get("step"))
t.traceStep = ok
enter, hasEnter := goja.AssertFunction(obj.Get("enter"))
exit, hasExit := goja.AssertFunction(obj.Get("exit"))
if hasEnter != hasExit {
return nil, errors.New("trace object must expose either both or none of enter() and exit()")
}
t.traceFrame = hasEnter
t.obj = obj
t.step = step
t.enter = enter
t.exit = exit
t.result = result
t.fault = fault
// Setup objects carrying data to JS. These are created once and re-used.
t.log = &steplog{
vm: vm,
op: &opObj{vm: vm},
memory: &memoryObj{vm: vm, toBig: t.toBig, toBuf: t.toBuf},
stack: &stackObj{vm: vm, toBig: t.toBig},
contract: &contractObj{vm: vm, toBig: t.toBig, toBuf: t.toBuf},
}
t.frame = &callframe{vm: vm, toBig: t.toBig, toBuf: t.toBuf}
t.frameResult = &callframeResult{vm: vm, toBuf: t.toBuf}
t.frameValue = t.frame.setupObject()
t.frameResultValue = t.frameResult.setupObject()
t.logValue = t.log.setupObject()
return t, nil
}
// CaptureTxStart implements the Tracer interface and is invoked at the beginning of
// transaction processing.
func (t *jsTracer) CaptureTxStart(gasLimit uint64) {
t.gasLimit = gasLimit
}
// CaptureTxStart implements the Tracer interface and is invoked at the end of
// transaction processing.
func (t *jsTracer) CaptureTxEnd(restGas uint64) {}
// CaptureStart implements the Tracer interface to initialize the tracing operation.
func (t *jsTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
t.env = env
db := &dbObj{db: env.StateDB, vm: t.vm, toBig: t.toBig, toBuf: t.toBuf, fromBuf: t.fromBuf}
t.dbValue = db.setupObject()
if create {
t.ctx["type"] = t.vm.ToValue("CREATE")
} else {
t.ctx["type"] = t.vm.ToValue("CALL")
}
t.ctx["from"] = t.vm.ToValue(from.Bytes())
t.ctx["to"] = t.vm.ToValue(to.Bytes())
t.ctx["input"] = t.vm.ToValue(input)
t.ctx["gas"] = t.vm.ToValue(gas)
t.ctx["gasPrice"] = t.vm.ToValue(env.TxContext.GasPrice)
valueBig, err := t.toBig(t.vm, value.String())
if err != nil {
t.err = err
return
}
t.ctx["value"] = valueBig
t.ctx["block"] = t.vm.ToValue(env.Context.BlockNumber.Uint64())
// Update list of precompiles based on current block
rules := env.ChainConfig().Rules(env.Context.BlockNumber, env.Context.Random != nil)
t.activePrecompiles = vm.ActivePrecompiles(rules)
t.ctx["intrinsicGas"] = t.vm.ToValue(t.gasLimit - gas)
}
// CaptureState implements the Tracer interface to trace a single step of VM execution.
func (t *jsTracer) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) {
if !t.traceStep {
return
}
if t.err != nil {
return
}
log := t.log
log.op.op = op
log.memory.memory = scope.Memory
log.stack.stack = scope.Stack
log.contract.contract = scope.Contract
log.pc = uint(pc)
log.gas = uint(gas)
log.cost = uint(cost)
log.depth = uint(depth)
log.err = err
if _, err := t.step(t.obj, t.logValue, t.dbValue); err != nil {
t.onError("step", err)
}
}
// CaptureFault implements the Tracer interface to trace an execution fault
func (t *jsTracer) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, depth int, err error) {
if t.err != nil {
return
}
// Other log fields have been already set as part of the last CaptureState.
t.log.err = err
if _, err := t.fault(t.obj, t.logValue, t.dbValue); err != nil {
t.onError("fault", err)
}
}
// CaptureEnd is called after the call finishes to finalize the tracing.
func (t *jsTracer) CaptureEnd(output []byte, gasUsed uint64, duration time.Duration, err error) {
t.ctx["output"] = t.vm.ToValue(output)
t.ctx["time"] = t.vm.ToValue(duration.String())
t.ctx["gasUsed"] = t.vm.ToValue(gasUsed)
if err != nil {
t.ctx["error"] = t.vm.ToValue(err.Error())
}
}
// CaptureEnter is called when EVM enters a new scope (via call, create or selfdestruct).
func (t *jsTracer) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) {
if !t.traceFrame {
return
}
if t.err != nil {
return
}
t.frame.typ = typ.String()
t.frame.from = from
t.frame.to = to
t.frame.input = common.CopyBytes(input)
t.frame.gas = uint(gas)
t.frame.value = nil
if value != nil {
t.frame.value = new(big.Int).SetBytes(value.Bytes())
}
if _, err := t.enter(t.obj, t.frameValue); err != nil {
t.onError("enter", err)
}
}
// CaptureExit is called when EVM exits a scope, even if the scope didn't
// execute any code.
func (t *jsTracer) CaptureExit(output []byte, gasUsed uint64, err error) {
if !t.traceFrame {
return
}
t.frameResult.gasUsed = uint(gasUsed)
t.frameResult.output = common.CopyBytes(output)
t.frameResult.err = err
if _, err := t.exit(t.obj, t.frameResultValue); err != nil {
t.onError("exit", err)
}
}
// GetResult calls the Javascript 'result' function and returns its value, or any accumulated error
func (t *jsTracer) GetResult() (json.RawMessage, error) {
ctx := t.vm.ToValue(t.ctx)
res, err := t.result(t.obj, ctx, t.dbValue)
if err != nil {
return nil, wrapError("result", err)
}
encoded, err := json.Marshal(res)
if err != nil {
return nil, err
}
return json.RawMessage(encoded), t.err
}
// Stop terminates execution of the tracer at the first opportune moment.
func (t *jsTracer) Stop(err error) {
t.vm.Interrupt(err)
}
// onError is called anytime the running JS code is interrupted
// and returns an error. It in turn pings the EVM to cancel its
// execution.
func (t *jsTracer) onError(context string, err error) {
t.err = wrapError(context, err)
// `env` is set on CaptureStart which comes before any JS execution.
// So it should be non-nil.
t.env.Cancel()
}
func wrapError(context string, err error) error {
return fmt.Errorf("%v in server-side tracer function '%v'", err, context)
}
// setBuiltinFunctions injects Go functions which are available to tracers into the environment.
// It depends on type converters having been set up.
func (t *jsTracer) setBuiltinFunctions() {
vm := t.vm
// TODO: load console from goja-nodejs
vm.Set("toHex", func(v goja.Value) string {
b, err := t.fromBuf(vm, v, false)
if err != nil {
vm.Interrupt(err)
return ""
}
return hexutil.Encode(b)
})
vm.Set("toWord", func(v goja.Value) goja.Value {
// TODO: add test with []byte len < 32 or > 32
b, err := t.fromBuf(vm, v, true)
if err != nil {
vm.Interrupt(err)
return nil
}
b = common.BytesToHash(b).Bytes()
res, err := t.toBuf(vm, b)
if err != nil {
vm.Interrupt(err)
return nil
}
return res
})
vm.Set("toAddress", func(v goja.Value) goja.Value {
a, err := t.fromBuf(vm, v, true)
if err != nil {
vm.Interrupt(err)
return nil
}
a = common.BytesToAddress(a).Bytes()
res, err := t.toBuf(vm, a)
if err != nil {
vm.Interrupt(err)
return nil
}
return res
})
vm.Set("toContract", func(from goja.Value, nonce uint) goja.Value {
a, err := t.fromBuf(vm, from, true)
if err != nil {
vm.Interrupt(err)
return nil
}
addr := common.BytesToAddress(a)
b := crypto.CreateAddress(addr, uint64(nonce)).Bytes()
res, err := t.toBuf(vm, b)
if err != nil {
vm.Interrupt(err)
return nil
}
return res
})
vm.Set("toContract2", func(from goja.Value, salt string, initcode goja.Value) goja.Value {
a, err := t.fromBuf(vm, from, true)
if err != nil {
vm.Interrupt(err)
return nil
}
addr := common.BytesToAddress(a)
code, err := t.fromBuf(vm, initcode, true)
if err != nil {
vm.Interrupt(err)
return nil
}
code = common.CopyBytes(code)
codeHash := crypto.Keccak256(code)
b := crypto.CreateAddress2(addr, common.HexToHash(salt), codeHash).Bytes()
res, err := t.toBuf(vm, b)
if err != nil {
vm.Interrupt(err)
return nil
}
return res
})
vm.Set("isPrecompiled", func(v goja.Value) bool {
a, err := t.fromBuf(vm, v, true)
if err != nil {
vm.Interrupt(err)
return false
}
addr := common.BytesToAddress(a)
for _, p := range t.activePrecompiles {
if p == addr {
return true
}
}
return false
})
vm.Set("slice", func(slice goja.Value, start, end int) goja.Value {
b, err := t.fromBuf(vm, slice, false)
if err != nil {
vm.Interrupt(err)
return nil
}
if start < 0 || start > end || end > len(b) {
vm.Interrupt(fmt.Sprintf("Tracer accessed out of bound memory: available %d, offset %d, size %d", len(b), start, end-start))
return nil
}
res, err := t.toBuf(vm, b[start:end])
if err != nil {
vm.Interrupt(err)
return nil
}
return res
})
}
// setTypeConverters sets up utilities for converting Go types into those
// suitable for JS consumption.
func (t *jsTracer) setTypeConverters() error {
// Inject bigint logic.
// TODO: To be replaced after goja adds support for native JS bigint.
toBigCode, err := t.vm.RunProgram(bigIntProgram)
if err != nil {
return err
}
// Used to create JS bigint objects from go.
toBigFn, ok := goja.AssertFunction(toBigCode)
if !ok {
return errors.New("failed to bind bigInt func")
}
toBigWrapper := func(vm *goja.Runtime, val string) (goja.Value, error) {
return toBigFn(goja.Undefined(), vm.ToValue(val))
}
t.toBig = toBigWrapper
// NOTE: We need this workaround to create JS buffers because
// goja doesn't at the moment expose constructors for typed arrays.
//
// Cache uint8ArrayType once to be used every time for less overhead.
uint8ArrayType := t.vm.Get("Uint8Array")
toBufWrapper := func(vm *goja.Runtime, val []byte) (goja.Value, error) {
return toBuf(vm, uint8ArrayType, val)
}
t.toBuf = toBufWrapper
fromBufWrapper := func(vm *goja.Runtime, buf goja.Value, allowString bool) ([]byte, error) {
return fromBuf(vm, uint8ArrayType, buf, allowString)
}
t.fromBuf = fromBufWrapper
return nil
}
type opObj struct {
vm *goja.Runtime
op vm.OpCode
}
func (o *opObj) ToNumber() int {
return int(o.op)
}
func (o *opObj) ToString() string {
return o.op.String()
}
func (o *opObj) IsPush() bool {
return o.op.IsPush()
}
func (o *opObj) setupObject() *goja.Object {
obj := o.vm.NewObject()
obj.Set("toNumber", o.vm.ToValue(o.ToNumber))
obj.Set("toString", o.vm.ToValue(o.ToString))
obj.Set("isPush", o.vm.ToValue(o.IsPush))
return obj
}
type memoryObj struct {
memory *vm.Memory
vm *goja.Runtime
toBig toBigFn
toBuf toBufFn
}
func (mo *memoryObj) Slice(begin, end int64) goja.Value {
b, err := mo.slice(begin, end)
if err != nil {
mo.vm.Interrupt(err)
return nil
}
res, err := mo.toBuf(mo.vm, b)
if err != nil {
mo.vm.Interrupt(err)
return nil
}
return res
}
// slice returns the requested range of memory as a byte slice.
func (mo *memoryObj) slice(begin, end int64) ([]byte, error) {
if end == begin {
return []byte{}, nil
}
if end < begin || begin < 0 {
return nil, fmt.Errorf("Tracer accessed out of bound memory: offset %d, end %d", begin, end)
}
if mo.memory.Len() < int(end) {
return nil, fmt.Errorf("Tracer accessed out of bound memory: available %d, offset %d, size %d", mo.memory.Len(), begin, end-begin)
}
return mo.memory.GetCopy(begin, end-begin), nil
}
func (mo *memoryObj) GetUint(addr int64) goja.Value {
value, err := mo.getUint(addr)
if err != nil {
mo.vm.Interrupt(err)
return nil
}
res, err := mo.toBig(mo.vm, value.String())
if err != nil {
mo.vm.Interrupt(err)
return nil
}
return res
}
// getUint returns the 32 bytes at the specified address interpreted as a uint.
func (mo *memoryObj) getUint(addr int64) (*big.Int, error) {
if mo.memory.Len() < int(addr)+32 || addr < 0 {
return nil, fmt.Errorf("Tracer accessed out of bound memory: available %d, offset %d, size %d", mo.memory.Len(), addr, 32)
}
return new(big.Int).SetBytes(mo.memory.GetPtr(addr, 32)), nil
}
func (mo *memoryObj) Length() int {
return mo.memory.Len()
}
func (m *memoryObj) setupObject() *goja.Object {
o := m.vm.NewObject()
o.Set("slice", m.vm.ToValue(m.Slice))
o.Set("getUint", m.vm.ToValue(m.GetUint))
o.Set("length", m.vm.ToValue(m.Length))
return o
}
type stackObj struct {
stack *vm.Stack
vm *goja.Runtime
toBig toBigFn
}
func (s *stackObj) Peek(idx int) goja.Value {
value, err := s.peek(idx)
if err != nil {
s.vm.Interrupt(err)
return nil
}
res, err := s.toBig(s.vm, value.String())
if err != nil {
s.vm.Interrupt(err)
return nil
}
return res
}
// peek returns the nth-from-the-top element of the stack.
func (s *stackObj) peek(idx int) (*big.Int, error) {
if len(s.stack.Data()) <= idx || idx < 0 {
return nil, fmt.Errorf("Tracer accessed out of bound stack: size %d, index %d", len(s.stack.Data()), idx)
}
return s.stack.Back(idx).ToBig(), nil
}
func (s *stackObj) Length() int {
return len(s.stack.Data())
}
func (s *stackObj) setupObject() *goja.Object {
o := s.vm.NewObject()
o.Set("peek", s.vm.ToValue(s.Peek))
o.Set("length", s.vm.ToValue(s.Length))
return o
}
type dbObj struct {
db vm.StateDB
vm *goja.Runtime
toBig toBigFn
toBuf toBufFn
fromBuf fromBufFn
}
func (do *dbObj) GetBalance(addrSlice goja.Value) goja.Value {
a, err := do.fromBuf(do.vm, addrSlice, false)
if err != nil {
do.vm.Interrupt(err)
return nil
}
addr := common.BytesToAddress(a)
value := do.db.GetBalance(addr)
res, err := do.toBig(do.vm, value.String())
if err != nil {
do.vm.Interrupt(err)
return nil
}
return res
}
func (do *dbObj) GetNonce(addrSlice goja.Value) uint64 {
a, err := do.fromBuf(do.vm, addrSlice, false)
if err != nil {
do.vm.Interrupt(err)
return 0
}
addr := common.BytesToAddress(a)
return do.db.GetNonce(addr)
}
func (do *dbObj) GetCode(addrSlice goja.Value) goja.Value {
a, err := do.fromBuf(do.vm, addrSlice, false)
if err != nil {
do.vm.Interrupt(err)
return nil
}
addr := common.BytesToAddress(a)
code := do.db.GetCode(addr)
res, err := do.toBuf(do.vm, code)
if err != nil {
do.vm.Interrupt(err)
return nil
}
return res
}
func (do *dbObj) GetState(addrSlice goja.Value, hashSlice goja.Value) goja.Value {
a, err := do.fromBuf(do.vm, addrSlice, false)
if err != nil {
do.vm.Interrupt(err)
return nil
}
addr := common.BytesToAddress(a)
h, err := do.fromBuf(do.vm, hashSlice, false)
if err != nil {
do.vm.Interrupt(err)
return nil
}
hash := common.BytesToHash(h)
state := do.db.GetState(addr, hash).Bytes()
res, err := do.toBuf(do.vm, state)
if err != nil {
do.vm.Interrupt(err)
return nil
}
return res
}
func (do *dbObj) Exists(addrSlice goja.Value) bool {
a, err := do.fromBuf(do.vm, addrSlice, false)
if err != nil {
do.vm.Interrupt(err)
return false
}
addr := common.BytesToAddress(a)
return do.db.Exist(addr)
}
func (do *dbObj) setupObject() *goja.Object {
o := do.vm.NewObject()
o.Set("getBalance", do.vm.ToValue(do.GetBalance))
o.Set("getNonce", do.vm.ToValue(do.GetNonce))
o.Set("getCode", do.vm.ToValue(do.GetCode))
o.Set("getState", do.vm.ToValue(do.GetState))
o.Set("exists", do.vm.ToValue(do.Exists))
return o
}
type contractObj struct {
contract *vm.Contract
vm *goja.Runtime
toBig toBigFn
toBuf toBufFn
}
func (co *contractObj) GetCaller() goja.Value {
caller := co.contract.Caller().Bytes()
res, err := co.toBuf(co.vm, caller)
if err != nil {
co.vm.Interrupt(err)
return nil
}
return res
}
func (co *contractObj) GetAddress() goja.Value {
addr := co.contract.Address().Bytes()
res, err := co.toBuf(co.vm, addr)
if err != nil {
co.vm.Interrupt(err)
return nil
}
return res
}
func (co *contractObj) GetValue() goja.Value {
value := co.contract.Value()
res, err := co.toBig(co.vm, value.String())
if err != nil {
co.vm.Interrupt(err)
return nil
}
return res
}
func (co *contractObj) GetInput() goja.Value {
input := co.contract.Input
res, err := co.toBuf(co.vm, input)
if err != nil {
co.vm.Interrupt(err)
return nil
}
return res
}
func (c *contractObj) setupObject() *goja.Object {
o := c.vm.NewObject()
o.Set("getCaller", c.vm.ToValue(c.GetCaller))
o.Set("getAddress", c.vm.ToValue(c.GetAddress))
o.Set("getValue", c.vm.ToValue(c.GetValue))
o.Set("getInput", c.vm.ToValue(c.GetInput))
return o
}
type callframe struct {
vm *goja.Runtime
toBig toBigFn
toBuf toBufFn
typ string
from common.Address
to common.Address
input []byte
gas uint
value *big.Int
}
func (f *callframe) GetType() string {
return f.typ
}
func (f *callframe) GetFrom() goja.Value {
from := f.from.Bytes()
res, err := f.toBuf(f.vm, from)
if err != nil {
f.vm.Interrupt(err)
return nil
}
return res
}
func (f *callframe) GetTo() goja.Value {
to := f.to.Bytes()
res, err := f.toBuf(f.vm, to)
if err != nil {
f.vm.Interrupt(err)
return nil
}
return res
}
func (f *callframe) GetInput() goja.Value {
input := f.input
res, err := f.toBuf(f.vm, input)
if err != nil {
f.vm.Interrupt(err)
return nil
}
return res
}
func (f *callframe) GetGas() uint {
return f.gas
}
func (f *callframe) GetValue() goja.Value {
if f.value == nil {
return goja.Undefined()
}
res, err := f.toBig(f.vm, f.value.String())
if err != nil {
f.vm.Interrupt(err)
return nil
}
return res
}
func (f *callframe) setupObject() *goja.Object {
o := f.vm.NewObject()
o.Set("getType", f.vm.ToValue(f.GetType))
o.Set("getFrom", f.vm.ToValue(f.GetFrom))
o.Set("getTo", f.vm.ToValue(f.GetTo))
o.Set("getInput", f.vm.ToValue(f.GetInput))
o.Set("getGas", f.vm.ToValue(f.GetGas))
o.Set("getValue", f.vm.ToValue(f.GetValue))
return o
}
type callframeResult struct {
vm *goja.Runtime
toBuf toBufFn
gasUsed uint
output []byte
err error
}
func (r *callframeResult) GetGasUsed() uint {
return r.gasUsed
}
func (r *callframeResult) GetOutput() goja.Value {
res, err := r.toBuf(r.vm, r.output)
if err != nil {
r.vm.Interrupt(err)
return nil
}
return res
}
func (r *callframeResult) GetError() goja.Value {
if r.err != nil {
return r.vm.ToValue(r.err.Error())
}
return goja.Undefined()
}
func (r *callframeResult) setupObject() *goja.Object {
o := r.vm.NewObject()
o.Set("getGasUsed", r.vm.ToValue(r.GetGasUsed))
o.Set("getOutput", r.vm.ToValue(r.GetOutput))
o.Set("getError", r.vm.ToValue(r.GetError))
return o
}
type steplog struct {
vm *goja.Runtime
op *opObj
memory *memoryObj
stack *stackObj
contract *contractObj
pc uint
gas uint
cost uint
depth uint
refund uint
err error
}
func (l *steplog) GetPC() uint {
return l.pc
}
func (l *steplog) GetGas() uint {
return l.gas
}
func (l *steplog) GetCost() uint {
return l.cost
}
func (l *steplog) GetDepth() uint {
return l.depth
}
func (l *steplog) GetRefund() uint {
return l.refund
}
func (l *steplog) GetError() goja.Value {
if l.err != nil {
return l.vm.ToValue(l.err.Error())
}
return goja.Undefined()
}
func (l *steplog) setupObject() *goja.Object {
o := l.vm.NewObject()
// Setup basic fields.
o.Set("getPC", l.vm.ToValue(l.GetPC))
o.Set("getGas", l.vm.ToValue(l.GetGas))
o.Set("getCost", l.vm.ToValue(l.GetCost))
o.Set("getDepth", l.vm.ToValue(l.GetDepth))
o.Set("getRefund", l.vm.ToValue(l.GetRefund))
o.Set("getError", l.vm.ToValue(l.GetError))
// Setup nested objects.
o.Set("op", l.op.setupObject())
o.Set("stack", l.stack.setupObject())
o.Set("memory", l.memory.setupObject())
o.Set("contract", l.contract.setupObject())
return o
}
File diff suppressed because one or more lines are too long
+41 -3
View File
@@ -14,8 +14,46 @@
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
//go:generate go-bindata -nometadata -o assets.go -pkg tracers -ignore tracers.go -ignore assets.go ./...
//go:generate gofmt -s -w assets.go
// Package tracers contains the actual JavaScript tracer assets.
package tracers
import (
"embed"
"io/fs"
"strings"
"unicode"
)
//go:embed *.js
var files embed.FS
// Load reads the built-in JS tracer files embedded in the binary and
// returns a mapping of tracer name to source.
func Load() (map[string]string, error) {
var assetTracers = make(map[string]string)
err := fs.WalkDir(files, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
b, err := fs.ReadFile(files, path)
if err != nil {
return err
}
name := camel(strings.TrimSuffix(path, ".js"))
assetTracers[name] = string(b)
return nil
})
return assetTracers, err
}
// camel converts a snake cased input string into a camel cased output.
func camel(str string) string {
pieces := strings.Split(str, "_")
for i := 1; i < len(pieces); i++ {
pieces[i] = string(unicode.ToUpper(rune(pieces[i][0]))) + pieces[i][1:]
}
return strings.Join(pieces, "")
}
-880
View File
@@ -1,880 +0,0 @@
// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// package js is a collection of tracers written in javascript.
package js
import (
"encoding/json"
"errors"
"fmt"
"math/big"
"strings"
"sync/atomic"
"time"
"unicode"
"unsafe"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
tracers2 "github.com/ethereum/go-ethereum/eth/tracers"
"github.com/ethereum/go-ethereum/eth/tracers/js/internal/tracers"
"github.com/ethereum/go-ethereum/log"
"gopkg.in/olebedev/go-duktape.v3"
)
// camel converts a snake cased input string into a camel cased output.
func camel(str string) string {
pieces := strings.Split(str, "_")
for i := 1; i < len(pieces); i++ {
pieces[i] = string(unicode.ToUpper(rune(pieces[i][0]))) + pieces[i][1:]
}
return strings.Join(pieces, "")
}
var assetTracers = make(map[string]string)
// init retrieves the JavaScript transaction tracers included in go-ethereum.
func init() {
for _, file := range tracers.AssetNames() {
name := camel(strings.TrimSuffix(file, ".js"))
assetTracers[name] = string(tracers.MustAsset(file))
}
tracers2.RegisterLookup(true, newJsTracer)
}
// makeSlice convert an unsafe memory pointer with the given type into a Go byte
// slice.
//
// Note, the returned slice uses the same memory area as the input arguments.
// If those are duktape stack items, popping them off **will** make the slice
// contents change.
func makeSlice(ptr unsafe.Pointer, size uint) []byte {
var sl = struct {
addr uintptr
len int
cap int
}{uintptr(ptr), int(size), int(size)}
return *(*[]byte)(unsafe.Pointer(&sl))
}
// popSlice pops a buffer off the JavaScript stack and returns it as a slice.
func popSlice(ctx *duktape.Context) []byte {
blob := common.CopyBytes(makeSlice(ctx.GetBuffer(-1)))
ctx.Pop()
return blob
}
// pushBigInt create a JavaScript BigInteger in the VM.
func pushBigInt(n *big.Int, ctx *duktape.Context) {
ctx.GetGlobalString("bigInt")
ctx.PushString(n.String())
ctx.Call(1)
}
// opWrapper provides a JavaScript wrapper around OpCode.
type opWrapper struct {
op vm.OpCode
}
// pushObject assembles a JSVM object wrapping a swappable opcode and pushes it
// onto the VM stack.
func (ow *opWrapper) pushObject(vm *duktape.Context) {
obj := vm.PushObject()
vm.PushGoFunction(func(ctx *duktape.Context) int { ctx.PushInt(int(ow.op)); return 1 })
vm.PutPropString(obj, "toNumber")
vm.PushGoFunction(func(ctx *duktape.Context) int { ctx.PushString(ow.op.String()); return 1 })
vm.PutPropString(obj, "toString")
vm.PushGoFunction(func(ctx *duktape.Context) int { ctx.PushBoolean(ow.op.IsPush()); return 1 })
vm.PutPropString(obj, "isPush")
}
// memoryWrapper provides a JavaScript wrapper around vm.Memory.
type memoryWrapper struct {
memory *vm.Memory
}
// slice returns the requested range of memory as a byte slice.
func (mw *memoryWrapper) slice(begin, end int64) []byte {
if end == begin {
return []byte{}
}
if end < begin || begin < 0 {
// TODO(karalabe): We can't js-throw from Go inside duktape inside Go. The Go
// runtime goes belly up https://github.com/golang/go/issues/15639.
log.Warn("Tracer accessed out of bound memory", "offset", begin, "end", end)
return nil
}
if mw.memory.Len() < int(end) {
// TODO(karalabe): We can't js-throw from Go inside duktape inside Go. The Go
// runtime goes belly up https://github.com/golang/go/issues/15639.
log.Warn("Tracer accessed out of bound memory", "available", mw.memory.Len(), "offset", begin, "size", end-begin)
return nil
}
return mw.memory.GetCopy(begin, end-begin)
}
// getUint returns the 32 bytes at the specified address interpreted as a uint.
func (mw *memoryWrapper) getUint(addr int64) *big.Int {
if mw.memory.Len() < int(addr)+32 || addr < 0 {
// TODO(karalabe): We can't js-throw from Go inside duktape inside Go. The Go
// runtime goes belly up https://github.com/golang/go/issues/15639.
log.Warn("Tracer accessed out of bound memory", "available", mw.memory.Len(), "offset", addr, "size", 32)
return new(big.Int)
}
return new(big.Int).SetBytes(mw.memory.GetPtr(addr, 32))
}
// pushObject assembles a JSVM object wrapping a swappable memory and pushes it
// onto the VM stack.
func (mw *memoryWrapper) pushObject(vm *duktape.Context) {
obj := vm.PushObject()
// Generate the `slice` method which takes two ints and returns a buffer
vm.PushGoFunction(func(ctx *duktape.Context) int {
blob := mw.slice(int64(ctx.GetInt(-2)), int64(ctx.GetInt(-1)))
ctx.Pop2()
ptr := ctx.PushFixedBuffer(len(blob))
copy(makeSlice(ptr, uint(len(blob))), blob)
return 1
})
vm.PutPropString(obj, "slice")
// Generate the `getUint` method which takes an int and returns a bigint
vm.PushGoFunction(func(ctx *duktape.Context) int {
offset := int64(ctx.GetInt(-1))
ctx.Pop()
pushBigInt(mw.getUint(offset), ctx)
return 1
})
vm.PutPropString(obj, "getUint")
}
// stackWrapper provides a JavaScript wrapper around vm.Stack.
type stackWrapper struct {
stack *vm.Stack
}
// peek returns the nth-from-the-top element of the stack.
func (sw *stackWrapper) peek(idx int) *big.Int {
if len(sw.stack.Data()) <= idx || idx < 0 {
// TODO(karalabe): We can't js-throw from Go inside duktape inside Go. The Go
// runtime goes belly up https://github.com/golang/go/issues/15639.
log.Warn("Tracer accessed out of bound stack", "size", len(sw.stack.Data()), "index", idx)
return new(big.Int)
}
return sw.stack.Back(idx).ToBig()
}
// pushObject assembles a JSVM object wrapping a swappable stack and pushes it
// onto the VM stack.
func (sw *stackWrapper) pushObject(vm *duktape.Context) {
obj := vm.PushObject()
vm.PushGoFunction(func(ctx *duktape.Context) int { ctx.PushInt(len(sw.stack.Data())); return 1 })
vm.PutPropString(obj, "length")
// Generate the `peek` method which takes an int and returns a bigint
vm.PushGoFunction(func(ctx *duktape.Context) int {
offset := ctx.GetInt(-1)
ctx.Pop()
pushBigInt(sw.peek(offset), ctx)
return 1
})
vm.PutPropString(obj, "peek")
}
// dbWrapper provides a JavaScript wrapper around vm.Database.
type dbWrapper struct {
db vm.StateDB
}
// pushObject assembles a JSVM object wrapping a swappable database and pushes it
// onto the VM stack.
func (dw *dbWrapper) pushObject(vm *duktape.Context) {
obj := vm.PushObject()
// Push the wrapper for statedb.GetBalance
vm.PushGoFunction(func(ctx *duktape.Context) int {
pushBigInt(dw.db.GetBalance(common.BytesToAddress(popSlice(ctx))), ctx)
return 1
})
vm.PutPropString(obj, "getBalance")
// Push the wrapper for statedb.GetNonce
vm.PushGoFunction(func(ctx *duktape.Context) int {
ctx.PushInt(int(dw.db.GetNonce(common.BytesToAddress(popSlice(ctx)))))
return 1
})
vm.PutPropString(obj, "getNonce")
// Push the wrapper for statedb.GetCode
vm.PushGoFunction(func(ctx *duktape.Context) int {
code := dw.db.GetCode(common.BytesToAddress(popSlice(ctx)))
ptr := ctx.PushFixedBuffer(len(code))
copy(makeSlice(ptr, uint(len(code))), code)
return 1
})
vm.PutPropString(obj, "getCode")
// Push the wrapper for statedb.GetState
vm.PushGoFunction(func(ctx *duktape.Context) int {
hash := popSlice(ctx)
addr := popSlice(ctx)
state := dw.db.GetState(common.BytesToAddress(addr), common.BytesToHash(hash))
ptr := ctx.PushFixedBuffer(len(state))
copy(makeSlice(ptr, uint(len(state))), state[:])
return 1
})
vm.PutPropString(obj, "getState")
// Push the wrapper for statedb.Exists
vm.PushGoFunction(func(ctx *duktape.Context) int {
ctx.PushBoolean(dw.db.Exist(common.BytesToAddress(popSlice(ctx))))
return 1
})
vm.PutPropString(obj, "exists")
}
// contractWrapper provides a JavaScript wrapper around vm.Contract
type contractWrapper struct {
contract *vm.Contract
}
// pushObject assembles a JSVM object wrapping a swappable contract and pushes it
// onto the VM stack.
func (cw *contractWrapper) pushObject(vm *duktape.Context) {
obj := vm.PushObject()
// Push the wrapper for contract.Caller
vm.PushGoFunction(func(ctx *duktape.Context) int {
ptr := ctx.PushFixedBuffer(20)
copy(makeSlice(ptr, 20), cw.contract.Caller().Bytes())
return 1
})
vm.PutPropString(obj, "getCaller")
// Push the wrapper for contract.Address
vm.PushGoFunction(func(ctx *duktape.Context) int {
ptr := ctx.PushFixedBuffer(20)
copy(makeSlice(ptr, 20), cw.contract.Address().Bytes())
return 1
})
vm.PutPropString(obj, "getAddress")
// Push the wrapper for contract.Value
vm.PushGoFunction(func(ctx *duktape.Context) int {
pushBigInt(cw.contract.Value(), ctx)
return 1
})
vm.PutPropString(obj, "getValue")
// Push the wrapper for contract.Input
vm.PushGoFunction(func(ctx *duktape.Context) int {
blob := cw.contract.Input
ptr := ctx.PushFixedBuffer(len(blob))
copy(makeSlice(ptr, uint(len(blob))), blob)
return 1
})
vm.PutPropString(obj, "getInput")
}
type frame struct {
typ *string
from *common.Address
to *common.Address
input []byte
gas *uint
value *big.Int
}
func newFrame() *frame {
return &frame{
typ: new(string),
from: new(common.Address),
to: new(common.Address),
gas: new(uint),
}
}
func (f *frame) pushObject(vm *duktape.Context) {
obj := vm.PushObject()
vm.PushGoFunction(func(ctx *duktape.Context) int { pushValue(ctx, *f.typ); return 1 })
vm.PutPropString(obj, "getType")
vm.PushGoFunction(func(ctx *duktape.Context) int { pushValue(ctx, *f.from); return 1 })
vm.PutPropString(obj, "getFrom")
vm.PushGoFunction(func(ctx *duktape.Context) int { pushValue(ctx, *f.to); return 1 })
vm.PutPropString(obj, "getTo")
vm.PushGoFunction(func(ctx *duktape.Context) int { pushValue(ctx, f.input); return 1 })
vm.PutPropString(obj, "getInput")
vm.PushGoFunction(func(ctx *duktape.Context) int { pushValue(ctx, *f.gas); return 1 })
vm.PutPropString(obj, "getGas")
vm.PushGoFunction(func(ctx *duktape.Context) int {
if f.value != nil {
pushValue(ctx, f.value)
} else {
ctx.PushUndefined()
}
return 1
})
vm.PutPropString(obj, "getValue")
}
type frameResult struct {
gasUsed *uint
output []byte
errorValue *string
}
func newFrameResult() *frameResult {
return &frameResult{
gasUsed: new(uint),
}
}
func (r *frameResult) pushObject(vm *duktape.Context) {
obj := vm.PushObject()
vm.PushGoFunction(func(ctx *duktape.Context) int { pushValue(ctx, *r.gasUsed); return 1 })
vm.PutPropString(obj, "getGasUsed")
vm.PushGoFunction(func(ctx *duktape.Context) int { pushValue(ctx, r.output); return 1 })
vm.PutPropString(obj, "getOutput")
vm.PushGoFunction(func(ctx *duktape.Context) int {
if r.errorValue != nil {
pushValue(ctx, *r.errorValue)
} else {
ctx.PushUndefined()
}
return 1
})
vm.PutPropString(obj, "getError")
}
// jsTracer provides an implementation of Tracer that evaluates a Javascript
// function for each VM execution step.
type jsTracer struct {
vm *duktape.Context // Javascript VM instance
env *vm.EVM // EVM instance executing the code being traced
tracerObject int // Stack index of the tracer JavaScript object
stateObject int // Stack index of the global state to pull arguments from
opWrapper *opWrapper // Wrapper around the VM opcode
stackWrapper *stackWrapper // Wrapper around the VM stack
memoryWrapper *memoryWrapper // Wrapper around the VM memory
contractWrapper *contractWrapper // Wrapper around the contract object
dbWrapper *dbWrapper // Wrapper around the VM environment
pcValue *uint // Swappable pc value wrapped by a log accessor
gasValue *uint // Swappable gas value wrapped by a log accessor
costValue *uint // Swappable cost value wrapped by a log accessor
depthValue *uint // Swappable depth value wrapped by a log accessor
errorValue *string // Swappable error value wrapped by a log accessor
refundValue *uint // Swappable refund value wrapped by a log accessor
frame *frame // Represents entry into call frame. Fields are swappable
frameResult *frameResult // Represents exit from a call frame. Fields are swappable
ctx map[string]interface{} // Transaction context gathered throughout execution
err error // Error, if one has occurred
interrupt uint32 // Atomic flag to signal execution interruption
reason error // Textual reason for the interruption
activePrecompiles []common.Address // Updated on CaptureStart based on given rules
traceSteps bool // When true, will invoke step() on each opcode
traceCallFrames bool // When true, will invoke enter() and exit() js funcs
}
// New instantiates a new tracer instance. code specifies a Javascript snippet,
// which must evaluate to an expression returning an object with 'step', 'fault'
// and 'result' functions.
func newJsTracer(code string, ctx *tracers2.Context) (tracers2.Tracer, error) {
if c, ok := assetTracers[code]; ok {
code = c
}
if ctx == nil {
ctx = new(tracers2.Context)
}
tracer := &jsTracer{
vm: duktape.New(),
ctx: make(map[string]interface{}),
opWrapper: new(opWrapper),
stackWrapper: new(stackWrapper),
memoryWrapper: new(memoryWrapper),
contractWrapper: new(contractWrapper),
dbWrapper: new(dbWrapper),
pcValue: new(uint),
gasValue: new(uint),
costValue: new(uint),
depthValue: new(uint),
refundValue: new(uint),
frame: newFrame(),
frameResult: newFrameResult(),
}
if ctx.BlockHash != (common.Hash{}) {
tracer.ctx["blockHash"] = ctx.BlockHash
if ctx.TxHash != (common.Hash{}) {
tracer.ctx["txIndex"] = ctx.TxIndex
tracer.ctx["txHash"] = ctx.TxHash
}
}
// Set up builtins for this environment
tracer.vm.PushGlobalGoFunction("toHex", func(ctx *duktape.Context) int {
ctx.PushString(hexutil.Encode(popSlice(ctx)))
return 1
})
tracer.vm.PushGlobalGoFunction("toWord", func(ctx *duktape.Context) int {
var word common.Hash
if ptr, size := ctx.GetBuffer(-1); ptr != nil {
word = common.BytesToHash(makeSlice(ptr, size))
} else {
word = common.HexToHash(ctx.GetString(-1))
}
ctx.Pop()
copy(makeSlice(ctx.PushFixedBuffer(32), 32), word[:])
return 1
})
tracer.vm.PushGlobalGoFunction("toAddress", func(ctx *duktape.Context) int {
var addr common.Address
if ptr, size := ctx.GetBuffer(-1); ptr != nil {
addr = common.BytesToAddress(makeSlice(ptr, size))
} else {
addr = common.HexToAddress(ctx.GetString(-1))
}
ctx.Pop()
copy(makeSlice(ctx.PushFixedBuffer(20), 20), addr[:])
return 1
})
tracer.vm.PushGlobalGoFunction("toContract", func(ctx *duktape.Context) int {
var from common.Address
if ptr, size := ctx.GetBuffer(-2); ptr != nil {
from = common.BytesToAddress(makeSlice(ptr, size))
} else {
from = common.HexToAddress(ctx.GetString(-2))
}
nonce := uint64(ctx.GetInt(-1))
ctx.Pop2()
contract := crypto.CreateAddress(from, nonce)
copy(makeSlice(ctx.PushFixedBuffer(20), 20), contract[:])
return 1
})
tracer.vm.PushGlobalGoFunction("toContract2", func(ctx *duktape.Context) int {
var from common.Address
if ptr, size := ctx.GetBuffer(-3); ptr != nil {
from = common.BytesToAddress(makeSlice(ptr, size))
} else {
from = common.HexToAddress(ctx.GetString(-3))
}
// Retrieve salt hex string from js stack
salt := common.HexToHash(ctx.GetString(-2))
// Retrieve code slice from js stack
var code []byte
if ptr, size := ctx.GetBuffer(-1); ptr != nil {
code = common.CopyBytes(makeSlice(ptr, size))
} else {
code = common.FromHex(ctx.GetString(-1))
}
codeHash := crypto.Keccak256(code)
ctx.Pop3()
contract := crypto.CreateAddress2(from, salt, codeHash)
copy(makeSlice(ctx.PushFixedBuffer(20), 20), contract[:])
return 1
})
tracer.vm.PushGlobalGoFunction("isPrecompiled", func(ctx *duktape.Context) int {
addr := common.BytesToAddress(popSlice(ctx))
for _, p := range tracer.activePrecompiles {
if p == addr {
ctx.PushBoolean(true)
return 1
}
}
ctx.PushBoolean(false)
return 1
})
tracer.vm.PushGlobalGoFunction("slice", func(ctx *duktape.Context) int {
start, end := ctx.GetInt(-2), ctx.GetInt(-1)
ctx.Pop2()
blob := popSlice(ctx)
size := end - start
if start < 0 || start > end || end > len(blob) {
// TODO(karalabe): We can't js-throw from Go inside duktape inside Go. The Go
// runtime goes belly up https://github.com/golang/go/issues/15639.
log.Warn("Tracer accessed out of bound memory", "available", len(blob), "offset", start, "size", size)
ctx.PushFixedBuffer(0)
return 1
}
copy(makeSlice(ctx.PushFixedBuffer(size), uint(size)), blob[start:end])
return 1
})
// Push the JavaScript tracer as object #0 onto the JSVM stack and validate it
if err := tracer.vm.PevalString("(" + code + ")"); err != nil {
log.Warn("Failed to compile tracer", "err", err)
return nil, err
}
tracer.tracerObject = 0 // yeah, nice, eval can't return the index itself
hasStep := tracer.vm.GetPropString(tracer.tracerObject, "step")
tracer.vm.Pop()
if !tracer.vm.GetPropString(tracer.tracerObject, "fault") {
return nil, fmt.Errorf("trace object must expose a function fault()")
}
tracer.vm.Pop()
if !tracer.vm.GetPropString(tracer.tracerObject, "result") {
return nil, fmt.Errorf("trace object must expose a function result()")
}
tracer.vm.Pop()
hasEnter := tracer.vm.GetPropString(tracer.tracerObject, "enter")
tracer.vm.Pop()
hasExit := tracer.vm.GetPropString(tracer.tracerObject, "exit")
tracer.vm.Pop()
if hasEnter != hasExit {
return nil, fmt.Errorf("trace object must expose either both or none of enter() and exit()")
}
tracer.traceCallFrames = hasEnter && hasExit
tracer.traceSteps = hasStep
// Tracer is valid, inject the big int library to access large numbers
tracer.vm.EvalString(bigIntegerJS)
tracer.vm.PutGlobalString("bigInt")
// Push the global environment state as object #1 into the JSVM stack
tracer.stateObject = tracer.vm.PushObject()
logObject := tracer.vm.PushObject()
tracer.opWrapper.pushObject(tracer.vm)
tracer.vm.PutPropString(logObject, "op")
tracer.stackWrapper.pushObject(tracer.vm)
tracer.vm.PutPropString(logObject, "stack")
tracer.memoryWrapper.pushObject(tracer.vm)
tracer.vm.PutPropString(logObject, "memory")
tracer.contractWrapper.pushObject(tracer.vm)
tracer.vm.PutPropString(logObject, "contract")
tracer.vm.PushGoFunction(func(ctx *duktape.Context) int { ctx.PushUint(*tracer.pcValue); return 1 })
tracer.vm.PutPropString(logObject, "getPC")
tracer.vm.PushGoFunction(func(ctx *duktape.Context) int { ctx.PushUint(*tracer.gasValue); return 1 })
tracer.vm.PutPropString(logObject, "getGas")
tracer.vm.PushGoFunction(func(ctx *duktape.Context) int { ctx.PushUint(*tracer.costValue); return 1 })
tracer.vm.PutPropString(logObject, "getCost")
tracer.vm.PushGoFunction(func(ctx *duktape.Context) int { ctx.PushUint(*tracer.depthValue); return 1 })
tracer.vm.PutPropString(logObject, "getDepth")
tracer.vm.PushGoFunction(func(ctx *duktape.Context) int { ctx.PushUint(*tracer.refundValue); return 1 })
tracer.vm.PutPropString(logObject, "getRefund")
tracer.vm.PushGoFunction(func(ctx *duktape.Context) int {
if tracer.errorValue != nil {
ctx.PushString(*tracer.errorValue)
} else {
ctx.PushUndefined()
}
return 1
})
tracer.vm.PutPropString(logObject, "getError")
tracer.vm.PutPropString(tracer.stateObject, "log")
tracer.frame.pushObject(tracer.vm)
tracer.vm.PutPropString(tracer.stateObject, "frame")
tracer.frameResult.pushObject(tracer.vm)
tracer.vm.PutPropString(tracer.stateObject, "frameResult")
tracer.dbWrapper.pushObject(tracer.vm)
tracer.vm.PutPropString(tracer.stateObject, "db")
return tracer, nil
}
// Stop terminates execution of the tracer at the first opportune moment.
func (jst *jsTracer) Stop(err error) {
jst.reason = err
atomic.StoreUint32(&jst.interrupt, 1)
}
// call executes a method on a JS object, catching any errors, formatting and
// returning them as error objects.
func (jst *jsTracer) call(noret bool, method string, args ...string) (json.RawMessage, error) {
// Execute the JavaScript call and return any error
jst.vm.PushString(method)
for _, arg := range args {
jst.vm.GetPropString(jst.stateObject, arg)
}
code := jst.vm.PcallProp(jst.tracerObject, len(args))
defer jst.vm.Pop()
if code != 0 {
err := jst.vm.SafeToString(-1)
return nil, errors.New(err)
}
// No error occurred, extract return value and return
if noret {
return nil, nil
}
// Push a JSON marshaller onto the stack. We can't marshal from the out-
// side because duktape can crash on large nestings and we can't catch
// C++ exceptions ourselves from Go. TODO(karalabe): Yuck, why wrap?!
jst.vm.PushString("(JSON.stringify)")
jst.vm.Eval()
jst.vm.Swap(-1, -2)
if code = jst.vm.Pcall(1); code != 0 {
err := jst.vm.SafeToString(-1)
return nil, errors.New(err)
}
return json.RawMessage(jst.vm.SafeToString(-1)), nil
}
func wrapError(context string, err error) error {
return fmt.Errorf("%v in server-side tracer function '%v'", err, context)
}
// CaptureStart implements the Tracer interface to initialize the tracing operation.
func (jst *jsTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) {
jst.env = env
jst.ctx["type"] = "CALL"
if create {
jst.ctx["type"] = "CREATE"
}
jst.ctx["from"] = from
jst.ctx["to"] = to
jst.ctx["input"] = input
jst.ctx["gas"] = gas
jst.ctx["gasPrice"] = env.TxContext.GasPrice
jst.ctx["value"] = value
// Initialize the context
jst.ctx["block"] = env.Context.BlockNumber.Uint64()
jst.dbWrapper.db = env.StateDB
// Update list of precompiles based on current block
rules := env.ChainConfig().Rules(env.Context.BlockNumber, env.Context.Random != nil)
jst.activePrecompiles = vm.ActivePrecompiles(rules)
// Compute intrinsic gas
isHomestead := env.ChainConfig().IsHomestead(env.Context.BlockNumber)
isIstanbul := env.ChainConfig().IsIstanbul(env.Context.BlockNumber)
intrinsicGas, err := core.IntrinsicGas(input, nil, jst.ctx["type"] == "CREATE", isHomestead, isIstanbul)
if err != nil {
return
}
jst.ctx["intrinsicGas"] = intrinsicGas
}
// CaptureState implements the Tracer interface to trace a single step of VM execution.
func (jst *jsTracer) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) {
if !jst.traceSteps {
return
}
if jst.err != nil {
return
}
// If tracing was interrupted, set the error and stop
if atomic.LoadUint32(&jst.interrupt) > 0 {
jst.err = jst.reason
jst.env.Cancel()
return
}
jst.opWrapper.op = op
jst.stackWrapper.stack = scope.Stack
jst.memoryWrapper.memory = scope.Memory
jst.contractWrapper.contract = scope.Contract
*jst.pcValue = uint(pc)
*jst.gasValue = uint(gas)
*jst.costValue = uint(cost)
*jst.depthValue = uint(depth)
*jst.refundValue = uint(jst.env.StateDB.GetRefund())
jst.errorValue = nil
if err != nil {
jst.errorValue = new(string)
*jst.errorValue = err.Error()
}
if _, err := jst.call(true, "step", "log", "db"); err != nil {
jst.err = wrapError("step", err)
}
}
// CaptureFault implements the Tracer interface to trace an execution fault
func (jst *jsTracer) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, depth int, err error) {
if jst.err != nil {
return
}
// Apart from the error, everything matches the previous invocation
jst.errorValue = new(string)
*jst.errorValue = err.Error()
if _, err := jst.call(true, "fault", "log", "db"); err != nil {
jst.err = wrapError("fault", err)
}
}
// CaptureEnd is called after the call finishes to finalize the tracing.
func (jst *jsTracer) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) {
jst.ctx["output"] = output
jst.ctx["time"] = t.String()
jst.ctx["gasUsed"] = gasUsed
if err != nil {
jst.ctx["error"] = err.Error()
}
}
// CaptureEnter is called when EVM enters a new scope (via call, create or selfdestruct).
func (jst *jsTracer) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) {
if !jst.traceCallFrames {
return
}
if jst.err != nil {
return
}
// If tracing was interrupted, set the error and stop
if atomic.LoadUint32(&jst.interrupt) > 0 {
jst.err = jst.reason
return
}
*jst.frame.typ = typ.String()
*jst.frame.from = from
*jst.frame.to = to
jst.frame.input = common.CopyBytes(input)
*jst.frame.gas = uint(gas)
jst.frame.value = nil
if value != nil {
jst.frame.value = new(big.Int).SetBytes(value.Bytes())
}
if _, err := jst.call(true, "enter", "frame"); err != nil {
jst.err = wrapError("enter", err)
}
}
// CaptureExit is called when EVM exits a scope, even if the scope didn't
// execute any code.
func (jst *jsTracer) CaptureExit(output []byte, gasUsed uint64, err error) {
if !jst.traceCallFrames {
return
}
// If tracing was interrupted, set the error and stop
if atomic.LoadUint32(&jst.interrupt) > 0 {
jst.err = jst.reason
return
}
jst.frameResult.output = common.CopyBytes(output)
*jst.frameResult.gasUsed = uint(gasUsed)
jst.frameResult.errorValue = nil
if err != nil {
jst.frameResult.errorValue = new(string)
*jst.frameResult.errorValue = err.Error()
}
if _, err := jst.call(true, "exit", "frameResult"); err != nil {
jst.err = wrapError("exit", err)
}
}
// GetResult calls the Javascript 'result' function and returns its value, or any accumulated error
func (jst *jsTracer) GetResult() (json.RawMessage, error) {
// Transform the context into a JavaScript object and inject into the state
obj := jst.vm.PushObject()
for key, val := range jst.ctx {
jst.addToObj(obj, key, val)
}
jst.vm.PutPropString(jst.stateObject, "ctx")
// Finalize the trace and return the results
result, err := jst.call(false, "result", "ctx", "db")
if err != nil {
jst.err = wrapError("result", err)
}
// Clean up the JavaScript environment
jst.vm.DestroyHeap()
jst.vm.Destroy()
return result, jst.err
}
// addToObj pushes a field to a JS object.
func (jst *jsTracer) addToObj(obj int, key string, val interface{}) {
pushValue(jst.vm, val)
jst.vm.PutPropString(obj, key)
}
func pushValue(ctx *duktape.Context, val interface{}) {
switch val := val.(type) {
case uint64:
ctx.PushUint(uint(val))
case string:
ctx.PushString(val)
case []byte:
ptr := ctx.PushFixedBuffer(len(val))
copy(makeSlice(ptr, uint(len(val))), val)
case common.Address:
ptr := ctx.PushFixedBuffer(20)
copy(makeSlice(ptr, 20), val[:])
case *big.Int:
pushBigInt(val, ctx)
case int:
ctx.PushInt(val)
case uint:
ctx.PushUint(val)
case common.Hash:
ptr := ctx.PushFixedBuffer(32)
copy(makeSlice(ptr, 32), val[:])
default:
panic(fmt.Sprintf("unsupported type: %T", val))
}
}
+30 -11
View File
@@ -1,4 +1,4 @@
// Copyright 2017 The go-ethereum Authors
// Copyright 2021 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
@@ -20,6 +20,7 @@ import (
"encoding/json"
"errors"
"math/big"
"strings"
"testing"
"time"
@@ -62,15 +63,19 @@ func testCtx() *vmContext {
func runTrace(tracer tracers.Tracer, vmctx *vmContext, chaincfg *params.ChainConfig) (json.RawMessage, error) {
var (
env = vm.NewEVM(vmctx.blockCtx, vmctx.txCtx, &dummyStatedb{}, chaincfg, vm.Config{Debug: true, Tracer: tracer})
gasLimit uint64 = 31000
startGas uint64 = 10000
value = big.NewInt(0)
contract = vm.NewContract(account{}, account{}, value, startGas)
)
contract.Code = []byte{byte(vm.PUSH1), 0x1, byte(vm.PUSH1), 0x1, 0x0}
tracer.CaptureTxStart(gasLimit)
tracer.CaptureStart(env, contract.Caller(), contract.Address(), false, []byte{}, startGas, value)
ret, err := env.Interpreter().Run(contract, []byte{}, false)
tracer.CaptureEnd(ret, startGas-contract.Gas, 1, err)
// Rest gas assumes no refund
tracer.CaptureTxEnd(startGas - contract.Gas)
if err != nil {
return nil, err
}
@@ -97,28 +102,43 @@ func TestTracer(t *testing.T) {
}{
{ // tests that we don't panic on bad arguments to memory access
code: "{depths: [], step: function(log) { this.depths.push(log.memory.slice(-1,-2)); }, fault: function() {}, result: function() { return this.depths; }}",
want: `[{},{},{}]`,
want: ``,
fail: "Tracer accessed out of bound memory: offset -1, end -2 at step (<eval>:1:53(15)) in server-side tracer function 'step'",
}, { // tests that we don't panic on bad arguments to stack peeks
code: "{depths: [], step: function(log) { this.depths.push(log.stack.peek(-1)); }, fault: function() {}, result: function() { return this.depths; }}",
want: `["0","0","0"]`,
want: ``,
fail: "Tracer accessed out of bound stack: size 0, index -1 at step (<eval>:1:53(13)) in server-side tracer function 'step'",
}, { // tests that we don't panic on bad arguments to memory getUint
code: "{ depths: [], step: function(log, db) { this.depths.push(log.memory.getUint(-64));}, fault: function() {}, result: function() { return this.depths; }}",
want: `["0","0","0"]`,
want: ``,
fail: "Tracer accessed out of bound memory: available 0, offset -64, size 32 at step (<eval>:1:58(13)) in server-side tracer function 'step'",
}, { // tests some general counting
code: "{count: 0, step: function() { this.count += 1; }, fault: function() {}, result: function() { return this.count; }}",
want: `3`,
}, { // tests that depth is reported correctly
code: "{depths: [], step: function(log) { this.depths.push(log.stack.length()); }, fault: function() {}, result: function() { return this.depths; }}",
want: `[0,1,2]`,
}, { // tests memory length
code: "{lengths: [], step: function(log) { this.lengths.push(log.memory.length()); }, fault: function() {}, result: function() { return this.lengths; }}",
want: `[0,0,0]`,
}, { // tests to-string of opcodes
code: "{opcodes: [], step: function(log) { this.opcodes.push(log.op.toString()); }, fault: function() {}, result: function() { return this.opcodes; }}",
want: `["PUSH1","PUSH1","STOP"]`,
}, { // tests intrinsic gas
code: "{depths: [], step: function() {}, fault: function() {}, result: function(ctx) { return ctx.gasPrice+'.'+ctx.gasUsed+'.'+ctx.intrinsicGas; }}",
want: `"100000.6.21000"`,
}, { // tests too deep object / serialization crash
code: "{step: function() {}, fault: function() {}, result: function() { var o={}; var x=o; for (var i=0; i<1000; i++){ o.foo={}; o=o.foo; } return x; }}",
fail: "RangeError: json encode recursion limit in server-side tracer function 'result'",
}, {
code: "{res: null, step: function(log) {}, fault: function() {}, result: function() { return toWord('0xffaa') }}",
want: `{"0":0,"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":255,"31":170}`,
}, { // test feeding a buffer back into go
code: "{res: null, step: function(log) { var address = log.contract.getAddress(); this.res = toAddress(address); }, fault: function() {}, result: function() { return this.res }}",
want: `{"0":0,"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0}`,
}, {
code: "{res: null, step: function(log) { var address = '0x0000000000000000000000000000000000000000'; this.res = toAddress(address); }, fault: function() {}, result: function() { return this.res }}",
want: `{"0":0,"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0}`,
}, {
code: "{res: null, step: function(log) { var address = Array.prototype.slice.call(log.contract.getAddress()); this.res = toAddress(address); }, fault: function() {}, result: function() { return this.res }}",
want: `{"0":0,"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0}`,
},
} {
if have, err := execTracer(tt.code); tt.want != string(have) || tt.fail != err {
@@ -128,7 +148,6 @@ func TestTracer(t *testing.T) {
}
func TestHalt(t *testing.T) {
t.Skip("duktape doesn't support abortion")
timeout := errors.New("stahp")
tracer, err := newJsTracer("{step: function() { while(1); }, result: function() { return null; }, fault: function(){}}", nil)
if err != nil {
@@ -138,7 +157,7 @@ func TestHalt(t *testing.T) {
time.Sleep(1 * time.Second)
tracer.Stop(timeout)
}()
if _, err = runTrace(tracer, testCtx(), params.TestChainConfig); err.Error() != "stahp in server-side tracer function 'step'" {
if _, err = runTrace(tracer, testCtx(), params.TestChainConfig); !strings.Contains(err.Error(), "stahp") {
t.Errorf("Expected timeout error, got %v", err)
}
}
@@ -158,12 +177,12 @@ func TestHaltBetweenSteps(t *testing.T) {
tracer.Stop(timeout)
tracer.CaptureState(0, 0, 0, 0, scope, nil, 0, nil)
if _, err := tracer.GetResult(); err.Error() != timeout.Error() {
if _, err := tracer.GetResult(); !strings.Contains(err.Error(), timeout.Error()) {
t.Errorf("Expected timeout error, got %v", err)
}
}
// TestNoStepExec tests a regular value transfer (no exec), and accessing the statedb
// testNoStepExec tests a regular value transfer (no exec), and accessing the statedb
// in 'result'
func TestNoStepExec(t *testing.T) {
execTracer := func(code string) []byte {
+9 -10
View File
@@ -62,16 +62,14 @@ func (al accessList) equal(other accessList) bool {
if len(al) != len(other) {
return false
}
// Given that len(al) == len(other), we only need to check that
// all the items from al are in other.
for addr := range al {
if _, ok := other[addr]; !ok {
return false
}
}
for addr := range other {
if _, ok := al[addr]; !ok {
return false
}
}
// Accounts match, cross reference the storage slots too
for addr, slots := range al {
otherslots := other[addr]
@@ -79,16 +77,13 @@ func (al accessList) equal(other accessList) bool {
if len(slots) != len(otherslots) {
return false
}
// Given that len(slots) == len(otherslots), we only need to check that
// all the items from slots are in otherslots.
for hash := range slots {
if _, ok := otherslots[hash]; !ok {
return false
}
}
for hash := range otherslots {
if _, ok := slots[hash]; !ok {
return false
}
}
}
return true
}
@@ -174,6 +169,10 @@ func (*AccessListTracer) CaptureEnter(typ vm.OpCode, from common.Address, to com
func (*AccessListTracer) CaptureExit(output []byte, gasUsed uint64, err error) {}
func (*AccessListTracer) CaptureTxStart(gasLimit uint64) {}
func (*AccessListTracer) CaptureTxEnd(restGas uint64) {}
// AccessList returns the current accesslist maintained by the tracer.
func (a *AccessListTracer) AccessList() types.AccessList {
return a.list.accessList()
+5 -5
View File
@@ -21,16 +21,16 @@ func (s StructLog) MarshalJSON() ([]byte, error) {
Op vm.OpCode `json:"op"`
Gas math.HexOrDecimal64 `json:"gas"`
GasCost math.HexOrDecimal64 `json:"gasCost"`
Memory hexutil.Bytes `json:"memory"`
Memory hexutil.Bytes `json:"memory,omitempty"`
MemorySize int `json:"memSize"`
Stack []uint256.Int `json:"stack"`
ReturnData hexutil.Bytes `json:"returnData"`
ReturnData hexutil.Bytes `json:"returnData,omitempty"`
Storage map[common.Hash]common.Hash `json:"-"`
Depth int `json:"depth"`
RefundCounter uint64 `json:"refund"`
Err error `json:"-"`
OpName string `json:"opName"`
ErrorString string `json:"error"`
ErrorString string `json:"error,omitempty"`
}
var enc StructLog
enc.Pc = s.Pc
@@ -57,10 +57,10 @@ func (s *StructLog) UnmarshalJSON(input []byte) error {
Op *vm.OpCode `json:"op"`
Gas *math.HexOrDecimal64 `json:"gas"`
GasCost *math.HexOrDecimal64 `json:"gasCost"`
Memory *hexutil.Bytes `json:"memory"`
Memory *hexutil.Bytes `json:"memory,omitempty"`
MemorySize *int `json:"memSize"`
Stack []uint256.Int `json:"stack"`
ReturnData *hexutil.Bytes `json:"returnData"`
ReturnData *hexutil.Bytes `json:"returnData,omitempty"`
Storage map[common.Hash]common.Hash `json:"-"`
Depth *int `json:"depth"`
RefundCounter *uint64 `json:"refund"`
+129 -14
View File
@@ -1,4 +1,4 @@
// Copyright 2015 The go-ethereum Authors
// Copyright 2021 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
@@ -18,10 +18,12 @@ package logger
import (
"encoding/hex"
"encoding/json"
"fmt"
"io"
"math/big"
"strings"
"sync/atomic"
"time"
"github.com/ethereum/go-ethereum/common"
@@ -57,7 +59,7 @@ type Config struct {
Overrides *params.ChainConfig `json:"overrides,omitempty"`
}
//go:generate gencodec -type StructLog -field-override structLogMarshaling -out gen_structlog.go
//go:generate go run github.com/fjl/gencodec -type StructLog -field-override structLogMarshaling -out gen_structlog.go
// StructLog is emitted to the EVM each cycle and lists information about the current internal state
// prior to the execution of the statement.
@@ -66,10 +68,10 @@ type StructLog struct {
Op vm.OpCode `json:"op"`
Gas uint64 `json:"gas"`
GasCost uint64 `json:"gasCost"`
Memory []byte `json:"memory"`
Memory []byte `json:"memory,omitempty"`
MemorySize int `json:"memSize"`
Stack []uint256.Int `json:"stack"`
ReturnData []byte `json:"returnData"`
ReturnData []byte `json:"returnData,omitempty"`
Storage map[common.Hash]common.Hash `json:"-"`
Depth int `json:"depth"`
RefundCounter uint64 `json:"refund"`
@@ -82,8 +84,8 @@ type structLogMarshaling struct {
GasCost math.HexOrDecimal64
Memory hexutil.Bytes
ReturnData hexutil.Bytes
OpName string `json:"opName"` // adds call to OpName() in MarshalJSON
ErrorString string `json:"error"` // adds call to ErrorString() in MarshalJSON
OpName string `json:"opName"` // adds call to OpName() in MarshalJSON
ErrorString string `json:"error,omitempty"` // adds call to ErrorString() in MarshalJSON
}
// OpName formats the operand name in a human-readable format.
@@ -108,10 +110,15 @@ type StructLogger struct {
cfg Config
env *vm.EVM
storage map[common.Address]Storage
logs []StructLog
output []byte
err error
storage map[common.Address]Storage
logs []StructLog
output []byte
err error
gasLimit uint64
usedGas uint64
interrupt uint32 // Atomic flag to signal execution interruption
reason error // Textual reason for the interruption
}
// NewStructLogger returns a new logger
@@ -142,13 +149,19 @@ func (l *StructLogger) CaptureStart(env *vm.EVM, from common.Address, to common.
//
// CaptureState also tracks SLOAD/SSTORE ops to track storage change.
func (l *StructLogger) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) {
memory := scope.Memory
stack := scope.Stack
contract := scope.Contract
// If tracing was interrupted, set the error and stop
if atomic.LoadUint32(&l.interrupt) > 0 {
l.env.Cancel()
return
}
// check if already accumulated the specified number of logs
if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) {
return
}
memory := scope.Memory
stack := scope.Stack
contract := scope.Contract
// Copy a snapshot of the current memory state to a new buffer
var mem []byte
if l.cfg.EnableMemory {
@@ -221,7 +234,42 @@ func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration
func (l *StructLogger) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) {
}
func (l *StructLogger) CaptureExit(output []byte, gasUsed uint64, err error) {}
func (l *StructLogger) CaptureExit(output []byte, gasUsed uint64, err error) {
}
func (l *StructLogger) GetResult() (json.RawMessage, error) {
// Tracing aborted
if l.reason != nil {
return nil, l.reason
}
failed := l.err != nil
returnData := common.CopyBytes(l.output)
// Return data when successful and revert reason when reverted, otherwise empty.
returnVal := fmt.Sprintf("%x", returnData)
if failed && l.err != vm.ErrExecutionReverted {
returnVal = ""
}
return json.Marshal(&ExecutionResult{
Gas: l.usedGas,
Failed: failed,
ReturnValue: returnVal,
StructLogs: formatLogs(l.StructLogs()),
})
}
// Stop terminates execution of the tracer at the first opportune moment.
func (l *StructLogger) Stop(err error) {
l.reason = err
atomic.StoreUint32(&l.interrupt, 1)
}
func (l *StructLogger) CaptureTxStart(gasLimit uint64) {
l.gasLimit = gasLimit
}
func (l *StructLogger) CaptureTxEnd(restGas uint64) {
l.usedGas = l.gasLimit - restGas
}
// StructLogs returns the captured log entries.
func (l *StructLogger) StructLogs() []StructLog { return l.logs }
@@ -347,3 +395,70 @@ func (t *mdLogger) CaptureEnter(typ vm.OpCode, from common.Address, to common.Ad
}
func (t *mdLogger) CaptureExit(output []byte, gasUsed uint64, err error) {}
func (*mdLogger) CaptureTxStart(gasLimit uint64) {}
func (*mdLogger) CaptureTxEnd(restGas uint64) {}
// ExecutionResult groups all structured logs emitted by the EVM
// while replaying a transaction in debug mode as well as transaction
// execution status, the amount of gas used and the return value
type ExecutionResult struct {
Gas uint64 `json:"gas"`
Failed bool `json:"failed"`
ReturnValue string `json:"returnValue"`
StructLogs []StructLogRes `json:"structLogs"`
}
// StructLogRes stores a structured log emitted by the EVM while replaying a
// transaction in debug mode
type StructLogRes struct {
Pc uint64 `json:"pc"`
Op string `json:"op"`
Gas uint64 `json:"gas"`
GasCost uint64 `json:"gasCost"`
Depth int `json:"depth"`
Error string `json:"error,omitempty"`
Stack *[]string `json:"stack,omitempty"`
Memory *[]string `json:"memory,omitempty"`
Storage *map[string]string `json:"storage,omitempty"`
RefundCounter uint64 `json:"refund,omitempty"`
}
// formatLogs formats EVM returned structured logs for json output
func formatLogs(logs []StructLog) []StructLogRes {
formatted := make([]StructLogRes, len(logs))
for index, trace := range logs {
formatted[index] = StructLogRes{
Pc: trace.Pc,
Op: trace.Op.String(),
Gas: trace.Gas,
GasCost: trace.GasCost,
Depth: trace.Depth,
Error: trace.ErrorString(),
RefundCounter: trace.RefundCounter,
}
if trace.Stack != nil {
stack := make([]string, len(trace.Stack))
for i, stackValue := range trace.Stack {
stack[i] = stackValue.Hex()
}
formatted[index].Stack = &stack
}
if trace.Memory != nil {
memory := make([]string, 0, (len(trace.Memory)+31)/32)
for i := 0; i+32 <= len(trace.Memory); i += 32 {
memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
}
formatted[index].Memory = &memory
}
if trace.Storage != nil {
storage := make(map[string]string)
for i, storageValue := range trace.Storage {
storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
}
formatted[index].Storage = &storage
}
}
return formatted
}
+5 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017 The go-ethereum Authors
// Copyright 2021 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
@@ -98,3 +98,7 @@ func (l *JSONLogger) CaptureEnter(typ vm.OpCode, from common.Address, to common.
}
func (l *JSONLogger) CaptureExit(output []byte, gasUsed uint64, err error) {}
func (l *JSONLogger) CaptureTxStart(gasLimit uint64) {}
func (l *JSONLogger) CaptureTxEnd(restGas uint64) {}
+34 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2016 The go-ethereum Authors
// Copyright 2021 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
@@ -17,6 +17,8 @@
package logger
import (
"encoding/json"
"fmt"
"math/big"
"testing"
@@ -72,3 +74,34 @@ func TestStoreCapture(t *testing.T) {
t.Errorf("expected %x, got %x", exp, logger.storage[contract.Address()][index])
}
}
// Tests that blank fields don't appear in logs when JSON marshalled, to reduce
// logs bloat and confusion. See https://github.com/ethereum/go-ethereum/issues/24487
func TestStructLogMarshalingOmitEmpty(t *testing.T) {
tests := []struct {
name string
log *StructLog
want string
}{
{"empty err and no fields", &StructLog{},
`{"pc":0,"op":0,"gas":"0x0","gasCost":"0x0","memSize":0,"stack":null,"depth":0,"refund":0,"opName":"STOP"}`},
{"with err", &StructLog{Err: fmt.Errorf("this failed")},
`{"pc":0,"op":0,"gas":"0x0","gasCost":"0x0","memSize":0,"stack":null,"depth":0,"refund":0,"opName":"STOP","error":"this failed"}`},
{"with mem", &StructLog{Memory: make([]byte, 2), MemorySize: 2},
`{"pc":0,"op":0,"gas":"0x0","gasCost":"0x0","memory":"0x0000","memSize":2,"stack":null,"depth":0,"refund":0,"opName":"STOP"}`},
{"with 0-size mem", &StructLog{Memory: make([]byte, 0)},
`{"pc":0,"op":0,"gas":"0x0","gasCost":"0x0","memSize":0,"stack":null,"depth":0,"refund":0,"opName":"STOP"}`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
blob, err := json.Marshal(tt.log)
if err != nil {
t.Fatal(err)
}
if have, want := string(blob), tt.want; have != want {
t.Fatalf("mismatched results\n\thave: %v\n\twant: %v", have, want)
}
})
}
}
+5 -1
View File
@@ -55,7 +55,7 @@ type fourByteTracer struct {
// newFourByteTracer returns a native go tracer which collects
// 4 byte-identifiers of a tx, and implements vm.EVMLogger.
func newFourByteTracer() tracers.Tracer {
func newFourByteTracer(ctx *tracers.Context) tracers.Tracer {
t := &fourByteTracer{
ids: make(map[string]int),
}
@@ -131,6 +131,10 @@ func (t *fourByteTracer) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64,
func (t *fourByteTracer) CaptureEnd(output []byte, gasUsed uint64, _ time.Duration, err error) {
}
func (*fourByteTracer) CaptureTxStart(gasLimit uint64) {}
func (*fourByteTracer) CaptureTxEnd(restGas uint64) {}
// GetResult returns the json-encoded nested list of call traces, and any
// error arising from the encoding or forceful termination (via `Stop`).
func (t *fourByteTracer) GetResult() (json.RawMessage, error) {
+5 -1
View File
@@ -56,7 +56,7 @@ type callTracer struct {
// newCallTracer returns a native go tracer which tracks
// call frames of a tx, and implements vm.EVMLogger.
func newCallTracer() tracers.Tracer {
func newCallTracer(ctx *tracers.Context) tracers.Tracer {
// First callframe contains tx context info
// and is populated on start and end.
return &callTracer{callstack: make([]callFrame, 1)}
@@ -142,6 +142,10 @@ func (t *callTracer) CaptureExit(output []byte, gasUsed uint64, err error) {
t.callstack[size-1].Calls = append(t.callstack[size-1].Calls, call)
}
func (*callTracer) CaptureTxStart(gasLimit uint64) {}
func (*callTracer) CaptureTxEnd(restGas uint64) {}
// GetResult returns the json-encoded nested list of call traces, and any
// error arising from the encoding or forceful termination (via `Stop`).
func (t *callTracer) GetResult() (json.RawMessage, error) {
+5 -1
View File
@@ -35,7 +35,7 @@ func init() {
type noopTracer struct{}
// newNoopTracer returns a new noop tracer.
func newNoopTracer() tracers.Tracer {
func newNoopTracer(ctx *tracers.Context) tracers.Tracer {
return &noopTracer{}
}
@@ -64,6 +64,10 @@ func (t *noopTracer) CaptureEnter(typ vm.OpCode, from common.Address, to common.
func (t *noopTracer) CaptureExit(output []byte, gasUsed uint64, err error) {
}
func (*noopTracer) CaptureTxStart(gasLimit uint64) {}
func (*noopTracer) CaptureTxEnd(restGas uint64) {}
// GetResult returns an empty json object.
func (t *noopTracer) GetResult() (json.RawMessage, error) {
return json.RawMessage(`{}`), nil
+10 -18
View File
@@ -24,7 +24,6 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth/tracers"
@@ -47,11 +46,12 @@ type prestateTracer struct {
prestate prestate
create bool
to common.Address
gasLimit uint64 // Amount of gas bought for the whole tx
interrupt uint32 // Atomic flag to signal execution interruption
reason error // Textual reason for the interruption
}
func newPrestateTracer() tracers.Tracer {
func newPrestateTracer(ctx *tracers.Context) tracers.Tracer {
// First callframe contains tx context info
// and is populated on start and end.
return &prestateTracer{prestate: prestate{}}
@@ -63,14 +63,6 @@ func (t *prestateTracer) CaptureStart(env *vm.EVM, from common.Address, to commo
t.create = create
t.to = to
// Compute intrinsic gas
isHomestead := env.ChainConfig().IsHomestead(env.Context.BlockNumber)
isIstanbul := env.ChainConfig().IsIstanbul(env.Context.BlockNumber)
intrinsicGas, err := core.IntrinsicGas(input, nil, create, isHomestead, isIstanbul)
if err != nil {
return
}
t.lookupAccount(from)
t.lookupAccount(to)
@@ -79,17 +71,11 @@ func (t *prestateTracer) CaptureStart(env *vm.EVM, from common.Address, to commo
toBal = new(big.Int).Sub(toBal, value)
t.prestate[to].Balance = hexutil.EncodeBig(toBal)
// The sender balance is after reducing: value, gasLimit, intrinsicGas.
// The sender balance is after reducing: value and gasLimit.
// We need to re-add them to get the pre-tx balance.
fromBal := hexutil.MustDecodeBig(t.prestate[from].Balance)
gasPrice := env.TxContext.GasPrice
consumedGas := new(big.Int).Mul(
gasPrice,
new(big.Int).Add(
new(big.Int).SetUint64(intrinsicGas),
new(big.Int).SetUint64(gas),
),
)
consumedGas := new(big.Int).Mul(gasPrice, new(big.Int).SetUint64(t.gasLimit))
fromBal.Add(fromBal, new(big.Int).Add(value, consumedGas))
t.prestate[from].Balance = hexutil.EncodeBig(fromBal)
t.prestate[from].Nonce--
@@ -145,6 +131,12 @@ func (t *prestateTracer) CaptureEnter(typ vm.OpCode, from common.Address, to com
func (t *prestateTracer) CaptureExit(output []byte, gasUsed uint64, err error) {
}
func (t *prestateTracer) CaptureTxStart(gasLimit uint64) {
t.gasLimit = gasLimit
}
func (t *prestateTracer) CaptureTxEnd(restGas uint64) {}
// GetResult returns the json-encoded nested list of call traces, and any
// error arising from the encoding or forceful termination (via `Stop`).
func (t *prestateTracer) GetResult() (json.RawMessage, error) {
+8 -5
View File
@@ -45,6 +45,9 @@ func init() {
tracers.RegisterLookup(false, lookup)
}
// ctorFn is the constructor signature of a native tracer.
type ctorFn = func(*tracers.Context) tracers.Tracer
/*
ctors is a map of package-local tracer constructors.
@@ -57,12 +60,12 @@ The go spec (https://golang.org/ref/spec#Package_initialization) says
Hence, we cannot make the map in init, but must make it upon first use.
*/
var ctors map[string]func() tracers.Tracer
var ctors map[string]ctorFn
// register is used by native tracers to register their presence.
func register(name string, ctor func() tracers.Tracer) {
func register(name string, ctor ctorFn) {
if ctors == nil {
ctors = make(map[string]func() tracers.Tracer)
ctors = make(map[string]ctorFn)
}
ctors[name] = ctor
}
@@ -70,10 +73,10 @@ func register(name string, ctor func() tracers.Tracer) {
// lookup returns a tracer, if one can be matched to the given name.
func lookup(name string, ctx *tracers.Context) (tracers.Tracer, error) {
if ctors == nil {
ctors = make(map[string]func() tracers.Tracer)
ctors = make(map[string]ctorFn)
}
if ctor, ok := ctors[name]; ok {
return ctor(), nil
return ctor(ctx), nil
}
return nil, errors.New("no tracer found")
}