Custom EVM tracer
In addition to the default opcode tracer and the built-in tracers, Etn-sc offers the possibility to write custom code that hook to events in the EVM to process and return the data in a consumable format. Custom tracers can be written either in Javascript or Go. JS tracers are good for quick prototyping and experimentation as well as for less intensive applications. Go tracers are performant but require the tracer to be compiled together with the Etn-sc source code.
Custom Go tracing
Custom tracers can also be made more performant by writing them in Go. The gain in performance mostly comes from the fact that Etn-sc doesn't need to interpret JS code and can execute native functions. Etn-sc comes with several built-in native tracers which can serve as examples. Please note that unlike JS tracers, Go tracing scripts cannot be simply passed as an argument to the API. They will need to be added to and compiled with the rest of the Etn-sc source code.
In this section a simple native tracer that counts the number of opcodes will be covered. First follow the instructions to clone and build Etn-sc from source code. Next save the following snippet as a .go
file and add it to eth/tracers/native
:
Every method of the EVMLogger interface needs to be implemented (even if empty). Key parts to notice are the init()
function which registers the tracer in Etn-sc, the CaptureState
hook where the opcode counts are incremented and GetResult
where the result is serialized and delivered. Note that the constructor takes in a cfg json.RawMessage
. This will be filled with a JSON object that user provides to the tracer to pass in optional config fields.
To test out this tracer the source is first compiled with make etn-sc
. Then in the console it can be invoked through the usual API methods by passing in the name it was registered under:
Custom Javascript tracing
Transaction traces include the complete status of the EVM at every point during the transaction execution, which can be a very large amount of data. Often, users are only interested in a small subset of that data. Javascript trace filters are available to isolate the useful information.
Specifying the tracer
option in one of the tracing methods (see list in reference) enables JavaScript-based tracing. In this mode, tracer
is interpreted as a JavaScript expression that is expected to evaluate to an object which must expose the result
and fault
methods. There exist 4 additional methods, namely: setup
, step
, enter
, and exit
. enter
and exit
must be present or omitted together.
Setup
setup
is invoked once, in the beginning when the tracer is being constructed by Etn-sc for a given transaction. It takes in one argument config
. config
is tracer-specific and allows users to pass in options to the tracer. config
is to be JSON-decoded for usage and its default value is "{}"
.
The config
in the following example is the onlyTopCall
option available in the callTracer
:
The config in the following example is the diffMode
option available in the prestateTracer
:
Step
step
is a function that takes two arguments, log
and db
, and is called for each step of the EVM, or when an error occurs, as the specified transaction is traced.
log
has the following fields:
op
: Object, an OpCode object representing the current opcodestack
: Object, a structure representing the EVM execution stackmemory
: Object, a structure representing the contract's memory spacecontract
: Object, an object representing the account executing the current operation
and the following methods:
getPC()
- returns a Number with the current program countergetGas()
- returns a Number with the amount of gas remaininggetCost()
- returns the cost of the opcode as a NumbergetDepth()
- returns the execution depth as a NumbergetRefund()
- returns the amount to be refunded as a NumbergetError()
- returns information about the error if one occurred, otherwise returns undefined
If error is non-empty, all other fields should be ignored.
For efficiency, the same log
object is reused on each execution step, updated with current values; make sure to copy values you want to preserve beyond the current call. For instance, this step function will not work:
But this step function will:
log.op
has the following methods:
isPush()
- returns true if the opcode is aPUSHn
toString()
- returns the string representation of the opcodetoNumber()
- returns the opcode's number
log.memory
has the following methods:
slice(start, stop)
- returns the specified segment of memory as a byte slicegetUint(offset)
- returns the 32 bytes at the given offsetlength()
- returns the memory size
log.stack
has the following methods:
peek(idx)
- returns the idx-th element from the top of the stack (0 is the topmost element) as a big.Intlength()
- returns the number of elements in the stack
log.contract
has the following methods:
getCaller()
- returns the address of the callergetAddress()
- returns the address of the current contractgetValue()
- returns the amount of value sent from caller to contract as a big.IntgetInput()
- returns the input data passed to the contract
db
has the following methods:
getBalance(address)
- returns abig.Int
with the specified account's balancegetNonce(address)
- returns a Number with the specified account's noncegetCode(address)
- returns a byte slice with the code for the specified accountgetState(address, hash)
- returns the state value for the specified account and the specified hashexists(address)
- returns true if the specified address exists
If the step function throws an exception or executes an illegal operation at any point, it will not be called on any further VM steps, and the error will be returned to the caller.
Result
result
is a function that takes two arguments ctx
and db
, and is expected to return a JSON-serializable value to return to the RPC caller.
ctx
is the context in which the transaction is executing and has the following fields:
type
- String, one of the two valuesCALL
andCREATE
from
- Address, sender of the transactionto
- Address, target of the transactioninput
- Buffer, input transaction datagas
- Number, gas budget of the transactiongasUsed
- Number, amount of gas used in executing the transaction (excludes txdata costs)gasPrice
- Number, gas price configured in the transaction being executedintrinsicGas
- Number, intrinsic gas for the transaction being executedvalue
- big.Int, amount to be transferred in weiblock
- Number, block numberoutput
- Buffer, value returned from EVMtime
- String, execution runtime
And these fields are only available for tracing mined transactions (i.e. not available when doing debug_traceCall
):
blockHash
- Buffer, hash of the block that holds the transaction being executedtxIndex
- Number, index of the transaction being executed in the blocktxHash
- Buffer, hash of the transaction being executed
Fault
fault
is a function that takes two arguments, log
and db
, just like step
and is invoked when an error happens during the execution of an opcode which wasn't reported in step. The method log.getError()
has information about the error.
Enter & Exit
enter
and exit
are respectively invoked on stepping in and out of an internal call. More specifically they are invoked on the CALL
variants, CREATE
variants and also for the transfer implied by a SELFDESTRUCT
.
enter
takes a callFrame
object as argument which has the following methods:
getType()
- returns a string which has the type of the call framegetFrom()
- returns the address of the call frame sendergetTo()
- returns the address of the call frame targetgetInput()
- returns the input as a buffergetGas()
- returns a Number which has the amount of gas provided for the framegetValue()
- returns abig.Int
with the amount to be transferred only if available, otherwiseundefined
exit
takes in a frameResult
object which has the following methods:
getGasUsed()
- returns amount of gas used throughout the frame as a NumbergetOutput()
- returns the output as a buffergetError()
- returns an error if one occurred during execution and undefined otherwise
Usage
Note that several values are Golang big.Int objects, not JavaScript numbers or JS bigints. As such, they have the same interface as described in the godocs. Their default serialization to JSON is as a Javascript number; to serialize large numbers accurately call .String()
on them. For convenience, big.NewInt(x)
is provided, and will convert a uint to a Go BigInt.
Usage example, returns the top element of the stack at each CALL opcode only:
Other traces
This tutorial has focused on debug_traceTransaction()
which reports information about individual transactions. There are also RPC endpoints that provide different information, including tracing the EVM execution within a block, between two blocks, for specific eth_calls
or rejected blocks. The full list of trace functions can be explored in the reference documentation.
Summary
This page described how to write custom tracers for Etn-sc. Custom tracers can be written in Javascript or Go.
Last updated