diff --git a/docs/developers/evm-tracing/built-in-tracers.md b/docs/developers/evm-tracing/built-in-tracers.md index 95ab1415ac..9fdea51f41 100644 --- a/docs/developers/evm-tracing/built-in-tracers.md +++ b/docs/developers/evm-tracing/built-in-tracers.md @@ -182,7 +182,14 @@ Things to note about the call tracer: - In case a frame reverts, the field `output` will contain the raw return data - In case the top level frame reverts, its `revertReason` field will contain the parsed reason of revert as returned by the Solidity contract -`callTracer` has an option to only trace the main (top-level) call and none of the sub-calls. This avoids extra processing for each call frame if only the top-level call info are required. Here's how it can be configured: +#### Config + +`callTracer` accepts two options: + +- `onlyTopCall: true` instructs the tracer to only process the main (top-level) call and none of the sub-calls. This avoids extra processing for each call frame if only the top-level call info are required. +- `withLog: true` instructs the tracer to also collect the logs emitted during each call. + +Example invokation with the `onlyTopCall` flag: ```terminal > debug.traceTransaction('0xc73e70f6d60e63a71dabf90b9983f2cdd56b0cb7bcf1a205f638d630a95bba73', { tracer: 'callTracer', tracerConfig: { onlyTopCall: true } }) @@ -452,4 +459,4 @@ debug.traceCall({from: , to: , input: }, 'latest', {stateOverrides: {'0x...': {c ## Summary {#summary} -This page showed how to use the tracers that come bundled with Geth. There are a set written in Go and a set written in Javascript. They are invoked by passing their names when calling an API method. State overrides can be used in combination with tracers to examine precisely what the EVM will do in some hypothetical scenario. \ No newline at end of file +This page showed how to use the tracers that come bundled with Geth. There are a set written in Go and a set written in Javascript. They are invoked by passing their names when calling an API method. State overrides can be used in combination with tracers to examine precisely what the EVM will do in some hypothetical scenarios. \ No newline at end of file diff --git a/docs/developers/evm-tracing/custom-tracer.md b/docs/developers/evm-tracing/custom-tracer.md index 7c9e07dabf..df47276b9e 100644 --- a/docs/developers/evm-tracing/custom-tracer.md +++ b/docs/developers/evm-tracing/custom-tracer.md @@ -5,312 +5,9 @@ description: Introduction to writing custom tracers for Geth In addition to the default opcode tracer and the built-in tracers, Geth 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 Geth source code. -## Custom Javascript tracing {#custom-js-tracing} +## Custom Go 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. Detailed information about `debug_traceTransaction` and its component parts is available in the [reference documentation](/docs/rpc/ns-debug#debug_tracetransaction). - -### A simple filter {#simple-filter} - -Filters are Javascript functions that select information from the trace to persist and discard based on some conditions. The following Javascript function returns only the sequence of opcodes executed by the transaction as a comma-separated list. The function could be written directly in the Javascript console, but it is cleaner to write it in a separate re-usable file and load it into the console. - -1. Create a file, `filterTrace_1.js`, with this content: - - ```javascript - tracer = function (tx) { - return debug.traceTransaction(tx, { - tracer: - '{' + - 'retVal: [],' + - 'step: function(log,db) {this.retVal.push(log.getPC() + ":" + log.op.toString())},' + - 'fault: function(log,db) {this.retVal.push("FAULT: " + JSON.stringify(log))},' + - 'result: function(ctx,db) {return this.retVal}' + - '}' - }); // return debug.traceTransaction ... - }; // tracer = function ... - ``` - -2. Run the [JavaScript console](https://geth.ethereum.org/docs/interface/javascript-console). -3. Get the hash of a recent transaction from a node or block explorer. - -4. Run this command to run the script: - - ```javascript - loadScript('filterTrace_1.js'); - ``` - -5. Run the tracer from the script. Be patient, it could take a long time. - - ```javascript - tracer(''); - ``` - - The bottom of the output looks similar to: - - ```sh - "3366:POP", "3367:JUMP", "1355:JUMPDEST", "1356:PUSH1", "1358:MLOAD", "1359:DUP1", "1360:DUP3", "1361:ISZERO", "1362:ISZERO", - "1363:ISZERO", "1364:ISZERO", "1365:DUP2", "1366:MSTORE", "1367:PUSH1", "1369:ADD", "1370:SWAP2", "1371:POP", "1372:POP", "1373:PUSH1", - "1375:MLOAD", "1376:DUP1", "1377:SWAP2", "1378:SUB", "1379:SWAP1", "1380:RETURN" - ``` - -6. Run this line to get a more readable output with each string in its own line. - - ```javascript - console.log(JSON.stringify(tracer(''), null, 2)); - ``` - -More information about the `JSON.stringify` function is available [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). - -The commands above worked by calling the same `debug.traceTransaction` function that was previously explained in [basic traces](https://geth.ethereum.org/docs/dapp/tracing), but with a new parameter, `tracer`. This parameter takes the JavaScript object formated as a string. In the case of the trace above, it is: - -```javascript -{ - retVal: [], - step: function(log,db) {this.retVal.push(log.getPC() + ":" + log.op.toString())}, - fault: function(log,db) {this.retVal.push("FAULT: " + JSON.stringify(log))}, - result: function(ctx,db) {return this.retVal} -} -``` - -This object has three member functions: - -- `step`, called for each opcode. -- `fault`, called if there is a problem in the execution. -- `result`, called to produce the results that are returned by `debug.traceTransaction` -- after the execution is done. - -In this case, `retVal` is used to store the list of strings to return in `result`. - -The `step` function adds to `retVal` the program counter and the name of the opcode there. Then, in `result`, this list is returned to be sent to the caller. - -### Filtering with conditions {#filtering-with-conditions} - -For actual filtered tracing we need an `if` statement to only log relevant information. For example, to isolate the transaction's interaction with storage, the following tracer could be used: - -```javascript -tracer = function (tx) { - return debug.traceTransaction(tx, { - tracer: - '{' + - 'retVal: [],' + - 'step: function(log,db) {' + - ' if(log.op.toNumber() == 0x54) ' + - ' this.retVal.push(log.getPC() + ": SLOAD");' + - ' if(log.op.toNumber() == 0x55) ' + - ' this.retVal.push(log.getPC() + ": SSTORE");' + - '},' + - 'fault: function(log,db) {this.retVal.push("FAULT: " + JSON.stringify(log))},' + - 'result: function(ctx,db) {return this.retVal}' + - '}' - }); // return debug.traceTransaction ... -}; // tracer = function ... -``` - -The `step` function here looks at the opcode number of the op, and only pushes an entry if the opcode is `SLOAD` or `SSTORE` ([here is a list of EVM opcodes and their numbers](https://github.com/wolflo/evm-opcodes)). We could have used `log.op.toString()` instead, but it is faster to compare numbers rather than strings. - -The output looks similar to this: - -```javascript -[ - "5921: SLOAD", - . - . - . - "2413: SSTORE", - "2420: SLOAD", - "2475: SSTORE", - "6094: SSTORE" -] -``` - -### Stack Information {#stack-information} - -The trace above reports the program counter (PC) and whether the program read from storage or wrote to it. That alone isn't particularly useful. To know more, the `log.stack.peek` function can be used to peek into the stack. `log.stack.peek(0)` is the stack top, `log.stack.peek(1)` the entry below it, etc. - -The values returned by `log.stack.peek` are Go `big.Int` objects. By default they are converted to JavaScript floating point numbers, so you need `toString(16)` to get them as hexadecimals, which is how 256-bit values such as storage cells and their content are normally represented. - -#### Storage Information {#storage-information} - -The function below provides a trace of all the storage operations and their parameters. This gives a more complete picture of the program's interaction with storage. - -```javascript -tracer = function (tx) { - return debug.traceTransaction(tx, { - tracer: - '{' + - 'retVal: [],' + - 'step: function(log,db) {' + - ' if(log.op.toNumber() == 0x54) ' + - ' this.retVal.push(log.getPC() + ": SLOAD " + ' + - ' log.stack.peek(0).toString(16));' + - ' if(log.op.toNumber() == 0x55) ' + - ' this.retVal.push(log.getPC() + ": SSTORE " +' + - ' log.stack.peek(0).toString(16) + " <- " +' + - ' log.stack.peek(1).toString(16));' + - '},' + - 'fault: function(log,db) {this.retVal.push("FAULT: " + JSON.stringify(log))},' + - 'result: function(ctx,db) {return this.retVal}' + - '}' - }); // return debug.traceTransaction ... -}; // tracer = function ... -``` - -The output is similar to: - -```javascript -[ - "5921: SLOAD 0", - . - . - . - "2413: SSTORE 3f0af0a7a3ed17f5ba6a93e0a2a05e766ed67bf82195d2dd15feead3749a575d <- fb8629ad13d9a12456", - "2420: SLOAD cc39b177dd3a7f50d4c09527584048378a692aed24d31d2eabeddb7f3c041870", - "2475: SSTORE cc39b177dd3a7f50d4c09527584048378a692aed24d31d2eabeddb7f3c041870 <- 358c3de691bd19", - "6094: SSTORE 0 <- 1" -] -``` - -#### Operation Results {#operation-results} - -One piece of information missing from the function above is the result on an `SLOAD` operation. The state we get inside `log` is the state prior to the execution of the opcode, so that value is not known yet. For more operations we can figure it out for ourselves, but we don't have access to the -storage, so here we can't. - -The solution is to have a flag, `afterSload`, which is only true in the opcode right after an `SLOAD`, when we can see the result at the top of the stack. - -```javascript -tracer = function (tx) { - return debug.traceTransaction(tx, { - tracer: - '{' + - 'retVal: [],' + - 'afterSload: false,' + - 'step: function(log,db) {' + - ' if(this.afterSload) {' + - ' this.retVal.push(" Result: " + ' + - ' log.stack.peek(0).toString(16)); ' + - ' this.afterSload = false; ' + - ' } ' + - ' if(log.op.toNumber() == 0x54) {' + - ' this.retVal.push(log.getPC() + ": SLOAD " + ' + - ' log.stack.peek(0).toString(16));' + - ' this.afterSload = true; ' + - ' } ' + - ' if(log.op.toNumber() == 0x55) ' + - ' this.retVal.push(log.getPC() + ": SSTORE " +' + - ' log.stack.peek(0).toString(16) + " <- " +' + - ' log.stack.peek(1).toString(16));' + - '},' + - 'fault: function(log,db) {this.retVal.push("FAULT: " + JSON.stringify(log))},' + - 'result: function(ctx,db) {return this.retVal}' + - '}' - }); // return debug.traceTransaction ... -}; // tracer = function ... -``` - -The output now contains the result in the line that follows the `SLOAD`. - -```javascript -[ - "5921: SLOAD 0", - " Result: 1", - . - . - . - "2413: SSTORE 3f0af0a7a3ed17f5ba6a93e0a2a05e766ed67bf82195d2dd15feead3749a575d <- fb8629ad13d9a12456", - "2420: SLOAD cc39b177dd3a7f50d4c09527584048378a692aed24d31d2eabeddb7f3c041870", - " Result: 0", - "2475: SSTORE cc39b177dd3a7f50d4c09527584048378a692aed24d31d2eabeddb7f3c041870 <- 358c3de691bd19", - "6094: SSTORE 0 <- 1" -] -``` - -### Dealing With Calls Between Contracts {#calls-between-contracts} - -So the storage has been treated as if there are only 2256 cells. However, that is not true. Contracts can call other contracts, and then the storage involved is the storage of the other contract. We can see the address of the current contract in `log.contract.getAddress()`. This value is the execution context - the contract whose storage we are using - even when code from another contract is executed (by using -[`CALLCODE` or `DELEGATECALL`](https://docs.soliditylang.org/en/v0.8.14/introduction-to-smart-contracts.html#delegatecall-callcode-and-libraries)). - -However, `log.contract.getAddress()` returns an array of bytes. To convert this to the familiar hexadecimal representation of Ethereum addresses, `this.byteHex()` and `array2Hex()` can be used. - -```javascript -tracer = function (tx) { - return debug.traceTransaction(tx, { - tracer: - '{' + - 'retVal: [],' + - 'afterSload: false,' + - 'callStack: [],' + - 'byte2Hex: function(byte) {' + - ' if (byte < 0x10) ' + - ' return "0" + byte.toString(16); ' + - ' return byte.toString(16); ' + - '},' + - 'array2Hex: function(arr) {' + - ' var retVal = ""; ' + - ' for (var i=0; i debug.traceTransaction('0x7ae446a7897c056023a8104d254237a8d97783a92900a7b0f7db668a9432f384', { tracer: 'opcounter' }) { ADD: 4, @@ -412,6 +109,167 @@ To test out this tracer the source is first compiled with `make geth`. Then in t } ``` -## Summary {#summary} +## 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](/docs/rpc/ns-debug)) 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 Geth 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`: + +```js +debug.traceTransaction(', { tracer: 'callTracer', tracerConfig: { onlyTopCall: true } }) +``` + +The config in the following example is the `diffMode` option available in the `prestateTracer`: + +```js +debug.traceTransaction(', { tracer: 'prestateTracer': tracerConfig: { diffMode: true } }) +``` + +### 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 opcode +- `stack`: Object, a structure representing the EVM execution stack +- `memory`: Object, a structure representing the contract's memory space +- `contract`: Object, an object representing the account executing the current operation + +and the following methods: + +- `getPC()` - returns a Number with the current program counter +- `getGas()` - returns a Number with the amount of gas remaining +- `getCost()` - returns the cost of the opcode as a Number +- `getDepth()` - returns the execution depth as a Number +- `getRefund()` - returns the amount to be refunded as a Number +- `getError()` - returns information about the error if one occured, 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: + +```js +function(log) { + this.logs.append(log); +} +``` + +But this step function will: + +```js +function(log) { + this.logs.append({gas: log.getGas(), pc: log.getPC(), ...}); +} +``` + +`log.op` has the following methods: + +- `isPush()` - returns true if the opcode is a PUSHn +- `toString()` - returns the string representation of the opcode +- `toNumber()` - returns the opcode's number + +`log.memory` has the following methods: + +- `slice(start, stop)` - returns the specified segment of memory as a byte slice +- `getUint(offset)` - returns the 32 bytes at the given offset +- `length()` - 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.Int +- `length()` - returns the number of elements in the stack + +`log.contract` has the following methods: + +- `getCaller()` - returns the address of the caller +- `getAddress()` - returns the address of the current contract +- `getValue()` - returns the amount of value sent from caller to contract as a big.Int +- `getInput()` - returns the input data passed to the contract + +`db` has the following methods: + +- `getBalance(address)` - returns a `big.Int` with the specified account's balance +- `getNonce(address)` - returns a Number with the specified account's nonce +- `getCode(address)` - returns a byte slice with the code for the specified account +- `getState(address, hash)` - returns the state value for the specified account and the specified hash +- `exists(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 values `CALL` and `CREATE` +- `from` - Address, sender of the transaction +- `to` - Address, target of the transaction +- `input` - Buffer, input transaction data +- `gas` - Number, gas budget of the transaction +- `gasUsed` - Number, amount of gas used in executing the transaction (excludes txdata costs) +- `gasPrice` - Number, gas price configured in the transaction being executed +- `intrinsicGas` - Number, intrinsic gas for the transaction being executed +- `value` - big.Int, amount to be transferred in wei +- `block` - Number, block number +- `output` - Buffer, value returned from EVM +- `time` - 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 executed +- `txIndex` - Number, index of the transaction being executed in the block +- `txHash` - 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 frame +- `getFrom()` - returns the address of the call frame sender +- `getTo()` - returns the address of the call frame target +- `getInput()` - returns the input as a buffer +- `getGas()` - returns a Number which has the amount of gas provided for the frame +- `getValue()` - returns a `big.Int` with the amount to be transferred only if available, otherwise `undefined` + +`exit` takes in a `frameResult` object which has the following methods: + +- `getGasUsed()` - returns amount of gas used throughout the frame as a Number +- `getOutput()` - returns the output as a buffer +` -getError()` - returns an error if one occured 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: + +```js +debug.traceTransaction(txhash, {tracer: '{data: [], fault: function(log) {}, step: function(log) { if(log.op.toString() == "CALL") this.data.push(log.stack.peek(0)); }, result: function() { return this.data; }}'}); +``` + +## 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_call`s or rejected blocks. The full list of trace functions can +be explored in the [reference documentation](/content/docs/interacting_with_geth/RPC/ns-debug.md). + + +## Summary This page described how to write custom tracers for Geth. Custom tracers can be written in Javascript or Go. \ No newline at end of file diff --git a/docs/developers/evm-tracing/javascript-tutorial.md b/docs/developers/evm-tracing/javascript-tutorial.md new file mode 100644 index 0000000000..b777b91bc9 --- /dev/null +++ b/docs/developers/evm-tracing/javascript-tutorial.md @@ -0,0 +1,300 @@ +--- +title: Tutorial for Javascript tracing +description: Javascript tracing tutorial +--- + +Geth supports tracing via [custom Javascript tracers](/docs/evm-tracing/custom-tracer#custom-javascript-tracing). This document provides a tutorial with examples on how to achieve this. + +### A simple filter + +Filters are Javascript functions that select information from the trace to persist and discard based on some conditions. The following Javascript function returns only the sequence of opcodes executed by the transaction as a comma-separated list. The function could be written directly in the Javascript console, but it is cleaner to write it in a separate re-usable file and load it into the console. + +1. Create a file, `filterTrace_1.js`, with this content: + +```js +tracer = function (tx) { + return debug.traceTransaction(tx, { + tracer: + '{' + + 'retVal: [],' + + 'step: function(log,db) {this.retVal.push(log.getPC() + ":" + log.op.toString())},' + + 'fault: function(log,db) {this.retVal.push("FAULT: " + JSON.stringify(log))},' + + 'result: function(ctx,db) {return this.retVal}' + + '}' + }); // return debug.traceTransaction ... +}; // tracer = function ... +``` + +2. Run the [JavaScript console](https://geth.ethereum.org/docs/interface/javascript-console). +3. Get the hash of a recent transaction from a node or block explorer. + +4. Run this command to run the script: + + ```js + loadScript('filterTrace_1.js'); + ``` + +5. Run the tracer from the script. Be patient, it could take a long time. + + ```js + tracer(''); + ``` + + The bottom of the output looks similar to: + + ```sh + "3366:POP", "3367:JUMP", "1355:JUMPDEST", "1356:PUSH1", "1358:MLOAD", "1359:DUP1", "1360:DUP3", "1361:ISZERO", "1362:ISZERO", + "1363:ISZERO", "1364:ISZERO", "1365:DUP2", "1366:MSTORE", "1367:PUSH1", "1369:ADD", "1370:SWAP2", "1371:POP", "1372:POP", "1373:PUSH1", + "1375:MLOAD", "1376:DUP1", "1377:SWAP2", "1378:SUB", "1379:SWAP1", "1380:RETURN" + ``` + +6. Run this line to get a more readable output with each string in its own line. + + ```js + console.log(JSON.stringify(tracer(''), null, 2)); + ``` + +More information about the `JSON.stringify` function is available [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). + +The commands above worked by calling the same `debug.traceTransaction` function that was previously explained in [basic traces](https://geth.ethereum.org/docs/dapp/tracing), but with a new parameter, `tracer`. This parameter takes the JavaScript object formated as a string. In the case of the trace above, it is: + +```js +{ + retVal: [], + step: function(log,db) {this.retVal.push(log.getPC() + ":" + log.op.toString())}, + fault: function(log,db) {this.retVal.push("FAULT: " + JSON.stringify(log))}, + result: function(ctx,db) {return this.retVal} +} +``` + +This object has three member functions: + +- `step`, called for each opcode. +- `fault`, called if there is a problem in the execution. +- `result`, called to produce the results that are returned by `debug.traceTransaction` +- after the execution is done. + +In this case, `retVal` is used to store the list of strings to return in `result`. + +The `step` function adds to `retVal` the program counter and the name of the opcode there. Then, in `result`, this list is returned to be sent to the caller. + +### Filtering with conditions + +For actual filtered tracing we need an `if` statement to only log relevant information. For example, to isolate the transaction's interaction with storage, the following tracer could be used: + +```js +tracer = function (tx) { + return debug.traceTransaction(tx, { + tracer: + '{' + + 'retVal: [],' + + 'step: function(log,db) {' + + ' if(log.op.toNumber() == 0x54) ' + + ' this.retVal.push(log.getPC() + ": SLOAD");' + + ' if(log.op.toNumber() == 0x55) ' + + ' this.retVal.push(log.getPC() + ": SSTORE");' + + '},' + + 'fault: function(log,db) {this.retVal.push("FAULT: " + JSON.stringify(log))},' + + 'result: function(ctx,db) {return this.retVal}' + + '}' + }); // return debug.traceTransaction ... +}; // tracer = function ... +``` + +The `step` function here looks at the opcode number of the op, and only pushes an entry if the opcode is `SLOAD` or `SSTORE` ([here is a list of EVM opcodes and their numbers](https://github.com/wolflo/evm-opcodes)). We could have used `log.op.toString()` instead, but it is faster to compare numbers rather than strings. + +The output looks similar to this: + +```js +[ + "5921: SLOAD", + . + . + . + "2413: SSTORE", + "2420: SLOAD", + "2475: SSTORE", + "6094: SSTORE" +] +``` + +### Stack Information + +The trace above reports the program counter (PC) and whether the program read from storage or wrote to it. That alone isn't particularly useful. To know more, the `log.stack.peek` function can be used to peek into the stack. `log.stack.peek(0)` is the stack top, `log.stack.peek(1)` the entry below it, etc. + +The values returned by `log.stack.peek` are Go `big.Int` objects. By default they are converted to JavaScript floating point numbers, so you need `toString(16)` to get them as hexadecimals, which is how 256-bit values such as storage cells and their content are normally represented. + +#### Storage Information + +The function below provides a trace of all the storage operations and their parameters. This gives a more complete picture of the program's interaction with storage. + +```js +tracer = function (tx) { + return debug.traceTransaction(tx, { + tracer: + '{' + + 'retVal: [],' + + 'step: function(log,db) {' + + ' if(log.op.toNumber() == 0x54) ' + + ' this.retVal.push(log.getPC() + ": SLOAD " + ' + + ' log.stack.peek(0).toString(16));' + + ' if(log.op.toNumber() == 0x55) ' + + ' this.retVal.push(log.getPC() + ": SSTORE " +' + + ' log.stack.peek(0).toString(16) + " <- " +' + + ' log.stack.peek(1).toString(16));' + + '},' + + 'fault: function(log,db) {this.retVal.push("FAULT: " + JSON.stringify(log))},' + + 'result: function(ctx,db) {return this.retVal}' + + '}' + }); // return debug.traceTransaction ... +}; // tracer = function ... +``` + +The output is similar to: + +```js +[ + "5921: SLOAD 0", + . + . + . + "2413: SSTORE 3f0af0a7a3ed17f5ba6a93e0a2a05e766ed67bf82195d2dd15feead3749a575d <- fb8629ad13d9a12456", + "2420: SLOAD cc39b177dd3a7f50d4c09527584048378a692aed24d31d2eabeddb7f3c041870", + "2475: SSTORE cc39b177dd3a7f50d4c09527584048378a692aed24d31d2eabeddb7f3c041870 <- 358c3de691bd19", + "6094: SSTORE 0 <- 1" +] +``` + +#### Operation Results + +One piece of information missing from the function above is the result on an `SLOAD` operation. The state we get inside `log` is the state prior to the execution of the opcode, so that value is not known yet. For more operations we can figure it out for ourselves, but we don't have access to the +storage, so here we can't. + +The solution is to have a flag, `afterSload`, which is only true in the opcode right after an `SLOAD`, when we can see the result at the top of the stack. + +```javascript +tracer = function (tx) { + return debug.traceTransaction(tx, { + tracer: + '{' + + 'retVal: [],' + + 'afterSload: false,' + + 'step: function(log,db) {' + + ' if(this.afterSload) {' + + ' this.retVal.push(" Result: " + ' + + ' log.stack.peek(0).toString(16)); ' + + ' this.afterSload = false; ' + + ' } ' + + ' if(log.op.toNumber() == 0x54) {' + + ' this.retVal.push(log.getPC() + ": SLOAD " + ' + + ' log.stack.peek(0).toString(16));' + + ' this.afterSload = true; ' + + ' } ' + + ' if(log.op.toNumber() == 0x55) ' + + ' this.retVal.push(log.getPC() + ": SSTORE " +' + + ' log.stack.peek(0).toString(16) + " <- " +' + + ' log.stack.peek(1).toString(16));' + + '},' + + 'fault: function(log,db) {this.retVal.push("FAULT: " + JSON.stringify(log))},' + + 'result: function(ctx,db) {return this.retVal}' + + '}' + }); // return debug.traceTransaction ... +}; // tracer = function ... +``` + +The output now contains the result in the line that follows the `SLOAD`. + +```javascript +[ + "5921: SLOAD 0", + " Result: 1", + . + . + . + "2413: SSTORE 3f0af0a7a3ed17f5ba6a93e0a2a05e766ed67bf82195d2dd15feead3749a575d <- fb8629ad13d9a12456", + "2420: SLOAD cc39b177dd3a7f50d4c09527584048378a692aed24d31d2eabeddb7f3c041870", + " Result: 0", + "2475: SSTORE cc39b177dd3a7f50d4c09527584048378a692aed24d31d2eabeddb7f3c041870 <- 358c3de691bd19", + "6094: SSTORE 0 <- 1" +] +``` + +### Dealing With Calls Between Contracts + +So the storage has been treated as if there are only 2256 cells. However, that is not true. Contracts can call other contracts, and then the storage involved is the storage of the other contract. We can see the address of the current contract in `log.contract.getAddress()`. This value is the execution context - the contract whose storage we are using - even when code from another contract is executed (by using +[`CALLCODE` or `DELEGATECALL`](https://docs.soliditylang.org/en/v0.8.14/introduction-to-smart-contracts.html#delegatecall-callcode-and-libraries)). + +However, `log.contract.getAddress()` returns an array of bytes. To convert this to the familiar hexadecimal representation of Ethereum addresses, `this.byteHex()` and `array2Hex()` can be used. + +```js +tracer = function (tx) { + return debug.traceTransaction(tx, { + tracer: + '{' + + 'retVal: [],' + + 'afterSload: false,' + + 'callStack: [],' + + 'byte2Hex: function(byte) {' + + ' if (byte < 0x10) ' + + ' return "0" + byte.toString(16); ' + + ' return byte.toString(16); ' + + '},' + + 'array2Hex: function(arr) {' + + ' var retVal = ""; ' + + ' for (var i=0; i:`. @@ -37,13 +33,9 @@ Example: > debug.backtraceAt("server.go:443") ``` -### debug_blockProfile {#debug-blockprofile} +### debug_blockProfile -Turns on block profiling for the given duration and writes -profile data to disk. It uses a profile rate of 1 for most -accurate information. If a different rate is desired, set -the rate and write the profile manually using -`debug_writeBlockProfile`. +Turns on block profiling for the given duration and writes profile data to disk. It uses a profile rate of 1 for most accurate information. If a different rate is desired, set the rate and write the profile manually using `debug_writeBlockProfile`. | Client | Method invocation | | :------ | -------------------------------------------------------------- | @@ -51,7 +43,7 @@ the rate and write the profile manually using | RPC | `{"method": "debug_blockProfile", "params": [string, number]}` | -### debug_chaindbCompact {#debug-chaindbcompact} +### debug_chaindbCompact Flattens the entire key-value database into a single level, removing all unused slots and merging all keys. @@ -61,7 +53,7 @@ Flattens the entire key-value database into a single level, removing all unused | RPC | `{"method": "debug_chaindbCompact", "params": []}` | -### debug_chaindbProperty {#debug-chaindbproperty} +### debug_chaindbProperty Returns leveldb properties of the key-value database. @@ -71,10 +63,9 @@ Returns leveldb properties of the key-value database. | RPC | `{"method": "debug_chaindbProperty", "params": [property]}` | -### debug_cpuProfile {#debug-cpuprofile} +### debug_cpuProfile -Turns on CPU profiling for the given duration and writes -profile data to disk. +Turns on CPU profiling for the given duration and writes profile data to disk. | Client | Method invocation | | :------ | ------------------------------------------------------------ | @@ -82,10 +73,9 @@ profile data to disk. | RPC | `{"method": "debug_cpuProfile", "params": [string, number]}` | -### debug_dbAncient {#debug-dbancient} +### debug_dbAncient -Retrieves an ancient binary blob from the freezer. The freezer is a collection of append-only immutable files. -The first argument `kind` specifies which table to look up data from. The list of all table kinds are as follows: +Retrieves an ancient binary blob from the freezer. The freezer is a collection of append-only immutable files. The first argument `kind` specifies which table to look up data from. The list of all table kinds are as follows: - `headers`: block headers - `hashes`: canonical hash table (block number -> block hash) @@ -98,7 +88,7 @@ The first argument `kind` specifies which table to look up data from. The list o | Console | `debug.dbAncient(kind string, number uint64)` | | RPC | `{"method": "debug_dbAncient", "params": [string, number]}` | -### debug_dbAncients {#debug-dbancients} +### debug_dbAncients Returns the number of ancient items in the ancient store. @@ -107,7 +97,7 @@ Returns the number of ancient items in the ancient store. | Console | `debug.dbAncients()` | | RPC | `{"method": "debug_dbAncients"}` | -### debug_dbGet {#debug-dbget} +### debug_dbGet Returns the raw value of a key stored in the database. @@ -118,10 +108,9 @@ Returns the raw value of a key stored in the database. -### debug_dumpBlock {#debug-dumpblock} +### debug_dumpBlock -Retrieves the state that corresponds to the block number and returns a list of accounts (including -storage and code). +Retrieves the state that corresponds to the block number and returns a list of accounts (including storage and code). | Client | Method invocation | | :------ | ----------------------------------------------------- | @@ -155,7 +144,7 @@ storage and code). } ``` -### debug_freeOSMemory {#denug-free-os-memory} +### debug_freeOSMemory Forces garbage collection @@ -167,10 +156,9 @@ Forces garbage collection -### debug_freezeClient {#debug-freezeclient} +### debug_freezeClient -Forces a temporary client freeze, normally when the server is overloaded. -Available as part of LES light server. +Forces a temporary client freeze, normally when the server is overloaded. Available as part of LES light server. | Client | Method invocation | | :------ | ---------------------------------------------------- | @@ -179,12 +167,11 @@ Available as part of LES light server. -### debug_gcStats {#debug-gcstats} +### debug_gcStats Returns garbage collection statistics. -See https://golang.org/pkg/runtime/debug/#GCStats for information about -the fields of the returned object. +See https://golang.org/pkg/runtime/debug/#GCStats for information about the fields of the returned object. | Client | Method invocation | | :------ | ------------------------------------------- | @@ -192,12 +179,10 @@ the fields of the returned object. | RPC | `{"method": "debug_gcStats", "params": []}` | -### debug_getAccessibleState {#debug-getaccessiblestate} +### debug_getAccessibleState -Returns the first number where the node has accessible state on disk. -This is the post-state of that block and the pre-state of the next -block. The (from, to) parameters are the sequence of blocks -to search, which can go either forwards or backwards. +Returns the first number where the node has accessible state on disk. This is the post-state of that block and the pre-state of the next +block. The (from, to) parameters are the sequence of blocks to search, which can go either forwards or backwards. Note: to get the last state pass in the range of blocks in reverse, i.e. (last, first). @@ -207,10 +192,9 @@ Note: to get the last state pass in the range of blocks in reverse, i.e. (last, | RPC | `{"method": "debug_getAccessibleState", "params": [from, to]}` | -### debug_getBadBlocks {#debug-getbadblocks} +### debug_getBadBlocks -Returns a list of the last 'bad blocks' that the client has seen on -the network and returns them as a JSON list of block-hashes. +Returns a list of the last 'bad blocks' that the client has seen on the network and returns them as a JSON list of block-hashes. | Client | Method invocation | | :------ | ------------------------------------------------ | @@ -218,7 +202,7 @@ the network and returns them as a JSON list of block-hashes. | RPC | `{"method": "debug_getBadBlocks", "params": []}` | -### debug_getBlockRlp {#debug-getblockrlp} +### debug_getBlockRlp Retrieves and returns the RLP encoded block by number. @@ -230,7 +214,7 @@ Retrieves and returns the RLP encoded block by number. References: [RLP](https://github.com/ethereum/wiki/wiki/RLP) -### debug_getHeaderRlp {#debug-getheaderrlp} +### debug_getHeaderRlp Returns an RLP-encoded header. @@ -239,7 +223,7 @@ Returns an RLP-encoded header. | Console | `debug.getHeaderRlp(blockNum)` | | RPC | `{"method": "debug_getHeaderRlp", "params": [num]}` | -### debug_getModifiedAccountsByHash {#debug-getmodifiedaccoutnsbyhash} +### debug_getModifiedAccountsByHash Returns all accounts that have changed between the two blocks specified. A change is defined as a difference in nonce, balance, code hash, or storage hash. With one parameter, returns the list of accounts modified in the specified block. @@ -248,10 +232,9 @@ Returns all accounts that have changed between the two blocks specified. A chang | Console | `debug.getModifiedAccountsByHash(startHash, endHash)` | | RPC | `{"method": "debug_getModifiedAccountsByHash", "params": [startHash, endHash]}` | -### debug_getModifiedAccountsByNumber {#denug-getmodifiedaccountsbynumber} +### debug_getModifiedAccountsByNumber -Returns all accounts that have changed between the two blocks specified. -A change is defined as a difference in nonce, balance, code hash or +Returns all accounts that have changed between the two blocks specified. A change is defined as a difference in nonce, balance, code hash or storage hash. | Client | Method invocation | @@ -259,7 +242,7 @@ storage hash. | Console | `debug.getModifiedAccountsByNumber(startNum uint64, endNum uint64)` | | RPC | `{"method": "debug_getModifiedAccountsByNumber", "params": [startNum, endNum]}` | -### debug_getRawReceipts {#debug-getrawreceipts} +### debug_getRawReceipts Returns the consensus-encoding of all receipts in a single block. @@ -268,17 +251,16 @@ Returns the consensus-encoding of all receipts in a single block. | Console | `debug.getRawReceipts(blockNrOrHash)` | | RPC | `{"method": "debug_getRawReceipts", "params": [blockNrOrHash]}` | -### debug_goTrace {#debug-gotrace} +### debug_goTrace -Turns on Go runtime tracing for the given duration and writes -trace data to disk. +Turns on Go runtime tracing for the given duration and writes trace data to disk. | Client | Method invocation | | :------ | --------------------------------------------------------- | | Console | `debug.goTrace(file, seconds)` | | RPC | `{"method": "debug_goTrace", "params": [string, number]}` | -### debug_intermediateRoots {#debug-intermediateroots} +### debug_intermediateRoots Executes a block (bad- or canon- or side-), and returns a list of intermediate roots: the stateroot after each transaction. @@ -287,19 +269,18 @@ Executes a block (bad- or canon- or side-), and returns a list of intermediate r | Console | `debug.intermediateRoots(blockHash, [options])` | | RPC | `{"method": "debug_intermediateRoots", "params": [blockHash, {}]}` | -### debug_memStats {#debug-memstats} +### debug_memStats Returns detailed runtime memory statistics. -See https://golang.org/pkg/runtime/#MemStats for information about -the fields of the returned object. +See https://golang.org/pkg/runtime/#MemStats for information about the fields of the returned object. | Client | Method invocation | | :------ | -------------------------------------------- | | Console | `debug.memStats()` | | RPC | `{"method": "debug_memStats", "params": []}` | -### debug_mutexProfile {#debug-mutexprofile} +### debug_mutexProfile Turns on mutex profiling for nsec seconds and writes profile data to file. It uses a profile rate of 1 for most accurate information. If a different rate is desired, set the rate and write the profile manually. @@ -308,7 +289,7 @@ Turns on mutex profiling for nsec seconds and writes profile data to file. It us | Console | `debug.mutexProfile(file, nsec)` | | RPC | `{"method": "debug_mutexProfile", "params": [file, nsec]}` | -### debug_preimage {#debug-preimage} +### debug_preimage Returns the preimage for a sha3 hash, if known. @@ -318,7 +299,7 @@ Returns the preimage for a sha3 hash, if known. | RPC | `{"method": "debug_preimage", "params": [hash]}` | -### debug_printBlock {#debug-printblock} +### debug_printBlock Retrieves a block and returns its pretty printed form. @@ -328,7 +309,7 @@ Retrieves a block and returns its pretty printed form. | RPC | `{"method": "debug_printBlock", "params": [number]}` | -### debug_seedHash {#debug-seedhash} +### debug_seedHash Fetches and retrieves the seed hash of the block by number @@ -338,22 +319,18 @@ Fetches and retrieves the seed hash of the block by number | Console | `debug.seedHash(number, [options])` | | RPC | `{"method": "debug_seedHash", "params": [number]}` | -### debug_setBlockProfileRate {#debug-setblockprofilerate} +### debug_setBlockProfileRate -Sets the rate (in samples/sec) of goroutine block profile -data collection. A non-zero rate enables block profiling, -setting it to zero stops the profile. Collected profile data -can be written using `debug_writeBlockProfile`. +Sets the rate (in samples/sec) of goroutine block profile data collection. A non-zero rate enables block profiling, setting it to zero stops the profile. Collected profile data can be written using `debug_writeBlockProfile`. | Client | Method invocation | | :------ | ------------------------------------------------------------- | | Console | `debug.setBlockProfileRate(rate)` | | RPC | `{"method": "debug_setBlockProfileRate", "params": [number]}` | -### debug_setGCPercent {#debug-setgcpercent} +### debug_setGCPercent -Sets the garbage collection target percentage. A negative value disables garbage -collection. +Sets the garbage collection target percentage. A negative value disables garbage collection. | Client | Method invocation | | :------ | ------------------------------------------------- | @@ -362,10 +339,9 @@ collection. | RPC | `{"method": "debug_setGCPercent", "params": [v]}` | -### debug_setHead {#debug-sethead} +### debug_setHead -Sets the current head of the local chain by block number. **Note**, this is a -destructive action and may severely damage your chain. Use with *extreme* caution. +Sets the current head of the local chain by block number. **Note**, this is a destructive action and may severely damage your chain. Use with *extreme* caution. | Client | Method invocation | | :------ | ------------------------------------------------- | @@ -376,7 +352,7 @@ destructive action and may severely damage your chain. Use with *extreme* cautio References: [Ethash](https://eth.wiki/en/concepts/ethash/ethash) -### debug_setMutexProfileFraction {#debug-setmutexprofilefraction} +### debug_setMutexProfileFraction Sets the rate of mutex profiling. @@ -385,11 +361,9 @@ Sets the rate of mutex profiling. | Console | `debug.setMutexProfileFraction(rate int)` | | RPC | `{"method": "debug_setMutexProfileFraction", "params": [rate]}` | -### debug_stacks {#debug-stacks} +### debug_stacks -Returns a printed representation of the stacks of all goroutines. -Note that the web3 wrapper for this method takes care of the printing -and does not return the string. +Returns a printed representation of the stacks of all goroutines. Note that the web3 wrapper for this method takes care of the printing and does not return the string. | Client | Method invocation | | :------ | ------------------------------------------ | @@ -397,10 +371,9 @@ and does not return the string. | RPC | `{"method": "debug_stacks", "params": []}` | -### debug_standardTraceBlockToFile {#debug-standardtraceblocktofile} +### debug_standardTraceBlockToFile -When JS-based tracing (see below) was first implemented, the intended usecase was to enable long-running tracers that could stream results back via a subscription channel. -This method works a bit differently. (For full details, see [PR](https://github.com/ethereum/go-ethereum/pull/17914)) +When JS-based tracing (see below) was first implemented, the intended usecase was to enable long-running tracers that could stream results back via a subscription channel. This method works a bit differently. (For full details, see [PR](https://github.com/ethereum/go-ethereum/pull/17914)) - It streams output to disk during the execution, to not blow up the memory usage on the node - It uses `jsonl` as output format (to allow streaming) @@ -444,12 +417,12 @@ type StdTraceConfig struct { } ``` -### debug_standardTraceBadBlockToFile {#debug-standardtracebadblocktofile} +### debug_standardTraceBadBlockToFile This method is similar to `debug_standardTraceBlockToFile`, but can be used to obtain info about a block which has been _rejected_ as invalid (for some reason). -### debug_startCPUProfile {#debug-startcpuprofile} +### debug_startCPUProfile Turns on CPU profiling indefinitely, writing to the given file. @@ -458,7 +431,7 @@ Turns on CPU profiling indefinitely, writing to the given file. | Console | `debug.startCPUProfile(file)` | | RPC | `{"method": "debug_startCPUProfile", "params": [string]}` | -### debug_startGoTrace {#debug-startgotrace} +### debug_startGoTrace Starts writing a Go runtime trace to the given file. @@ -467,7 +440,7 @@ Starts writing a Go runtime trace to the given file. | Console | `debug.startGoTrace(file)` | | RPC | `{"method": "debug_startGoTrace", "params": [string]}` | -### debug_stopCPUProfile {#debug-stopcpuprofile} +### debug_stopCPUProfile Stops an ongoing CPU profile. @@ -476,7 +449,7 @@ Stops an ongoing CPU profile. | Console | `debug.stopCPUProfile()` | | RPC | `{"method": "debug_stopCPUProfile", "params": []}` | -### debug_stopGoTrace {#debug-stopgo-trace} +### debug_stopGoTrace Stops writing the Go runtime trace. @@ -485,7 +458,7 @@ Stops writing the Go runtime trace. | Console | `debug.startGoTrace(file)` | | RPC | `{"method": "debug_stopGoTrace", "params": []}` | -### debug_storageRangeAt {#debug-storagerangeat} +### debug_storageRangeAt Returns the storage at the given block height and transaction index. The result can be paged by providing a `maxResult` to cap the number of storage slots returned as well as specifying the offset via `keyStart` (hash of storage key). @@ -494,26 +467,25 @@ Returns the storage at the given block height and transaction index. The result | Console | `debug.storageRangeAt(blockHash, txIdx, contractAddress, keyStart, maxResult)` | | RPC | `{"method": "debug_storageRangeAt", "params": [blockHash, txIdx, contractAddress, keyStart, maxResult]}` | -### debug_traceBadBlock {#debug-tracebadblock} +### debug_traceBadBlock Returns the structured logs created during the execution of EVM against a block pulled from the pool of bad ones and returns them as a JSON object. +For the second parameter see [TraceConfig](#traceconfig) reference. | Client | Method invocation | | :------ | -------------------------------------------------------------- | | Console | `debug.traceBadBlock(blockHash, [options])` | | RPC | `{"method": "debug_traceBadBlock", "params": [blockHash, {}]}` | -### debug_traceBlock {#debug-traceblock} +### debug_traceBlock -The `traceBlock` method will return a full stack trace of all invoked opcodes of all transaction -that were included in this block. **Note**, the parent of this block must be present or it will -fail. +The `traceBlock` method will return a full stack trace of all invoked opcodes of all transaction that were included in this block. **Note**, the parent of this block must be present or it will fail. For the second parameter see [TraceConfig](#traceconfig) reference. -| Client | Method invocation | -| :------ | ------------------------------------------------------------------------ | -| Go | `debug.TraceBlock(blockRlp []byte, config. *vm.Config) BlockTraceResult` | -| Console | `debug.traceBlock(tblockRlp, [options])` | -| RPC | `{"method": "debug_traceBlock", "params": [blockRlp, {}]}` | +| Client | Method invocation | +| :------ | ------------------------------------------------------------------------- | +| Go | `debug.TraceBlock(blockRlp []byte, config *TraceConfig) BlockTraceResult` | +| Console | `debug.traceBlock(tblockRlp, [options])` | +| RPC | `{"method": "debug_traceBlock", "params": [blockRlp, {}]}` | References: [RLP](https://github.com/ethereum/wiki/wiki/RLP) @@ -554,51 +526,49 @@ References: }] ``` -### debug_traceBlockByNumber {#debug-traceblockbynumber} +### debug_traceBlockByNumber -Similar to [debug_traceBlock](#debug_traceblock), `traceBlockByNumber` accepts a block number and will replay the -block that is already present in the database. - -| Client | Method invocation | -| :------ | ------------------------------------------------------------------------------ | -| Go | `debug.TraceBlockByNumber(number uint64, config. *vm.Config) BlockTraceResult` | -| Console | `debug.traceBlockByNumber(number, [options])` | -| RPC | `{"method": "debug_traceBlockByNumber", "params": [number, {}]}` | - -References: -[RLP](https://github.com/ethereum/wiki/wiki/RLP) - -### debug_traceBlockByHash {#debug-traceblockbyhash} - -Similar to [debug_traceBlock](#debug_traceblock), `traceBlockByHash` accepts a block hash and will replay the -block that is already present in the database. +Similar to [debug_traceBlock](#debug_traceblock), `traceBlockByNumber` accepts a block number and will replay the block that is already present in the database. For the second parameter see [TraceConfig](#traceconfig) reference. | Client | Method invocation | | :------ | ------------------------------------------------------------------------------- | -| Go | `debug.TraceBlockByHash(hash common.Hash, config. *vm.Config) BlockTraceResult` | -| Console | `debug.traceBlockByHash(hash, [options])` | -| RPC | `{"method": "debug_traceBlockByHash", "params": [hash {}]}` | +| Go | `debug.TraceBlockByNumber(number uint64, config *TraceConfig) BlockTraceResult` | +| Console | `debug.traceBlockByNumber(number, [options])` | +| RPC | `{"method": "debug_traceBlockByNumber", "params": [number, {}]}` | References: [RLP](https://github.com/ethereum/wiki/wiki/RLP) +### debug_traceBlockByHash -### debug_traceBlockFromFile {#debug-traceblockfromfile} - -Similar to [debug_traceBlock](#debug_traceblock), `traceBlockFromFile` accepts a file containing the RLP of the block. +Similar to [debug_traceBlock](#debug_traceblock), `traceBlockByHash` accepts a block hash and will replay the block that is already present in the database. For the second parameter see [TraceConfig](#traceconfig) reference. | Client | Method invocation | | :------ | -------------------------------------------------------------------------------- | -| Go | `debug.TraceBlockFromFile(fileName string, config. *vm.Config) BlockTraceResult` | -| Console | `debug.traceBlockFromFile(fileName, [options])` | -| RPC | `{"method": "debug_traceBlockFromFile", "params": [fileName, {}]}` | +| Go | `debug.TraceBlockByHash(hash common.Hash, config *TraceConfig) BlockTraceResult` | +| Console | `debug.traceBlockByHash(hash, [options])` | +| RPC | `{"method": "debug_traceBlockByHash", "params": [hash {}]}` | References: [RLP](https://github.com/ethereum/wiki/wiki/RLP) -### debug_traceCall {#debug-tracecall} -The `debug_traceCall` method lets you run an `eth_call` within the context of the given block execution using the final state of parent block as the base. The first argument (just as in `eth_call`) is a [transaction object](/docs/rpc/objects#transaction-call-object). The block can be specified either by hash or by number as the second argument. A tracer can be specified as a third argument, similar to `debug_traceTransaction`. It returns the same output as `debug_traceTransaction`. +### debug_traceBlockFromFile + +Similar to [debug_traceBlock](#debug_traceblock), `traceBlockFromFile` accepts a file containing the RLP of the block. For the second parameter see [TraceConfig](#traceconfig) reference. + +| Client | Method invocation | +| :------ | --------------------------------------------------------------------------------- | +| Go | `debug.TraceBlockFromFile(fileName string, config *TraceConfig) BlockTraceResult` | +| Console | `debug.traceBlockFromFile(fileName, [options])` | +| RPC | `{"method": "debug_traceBlockFromFile", "params": [fileName, {}]}` | + +References: +[RLP](https://github.com/ethereum/wiki/wiki/RLP) + +### debug_traceCall + +The `debug_traceCall` method lets you run an `eth_call` within the context of the given block execution using the final state of parent block as the base. The first argument (just as in `eth_call`) is a [transaction object](/docs/rpc/objects#transaction-call-object). The block can be specified either by hash or by number as the second argument. The trace can be configured similar to `debug_traceTransaction`, see [TraceConfig](#traceconfig). The method returns the same output as `debug_traceTransaction`. | Client | Method invocation | | :-----: | --------------------------------------------------------------------------------------------------------------------------- | @@ -609,7 +579,8 @@ The `debug_traceCall` method lets you run an `eth_call` within the context of th #### Example No specific call options: -``` + +```sh > debug.traceCall(null, "0x0") { failed: false, @@ -619,7 +590,8 @@ No specific call options: } ``` Tracing a call with a destination and specific sender, disabling the storage and memory output (less data returned over RPC) -``` + +```sh debug.traceCall({ "from": "0xdeadbeef29292929192939494959594933929292", "to": "0xde929f939d939d393f939393f93939f393929023", @@ -629,9 +601,9 @@ debug.traceCall({ "latest", {"disableStorage": true, "disableMemory": true}) ``` -It is possible to supply 'overrides' for both state-data (accounts/storage) and block data (number, timestamp etc). In the example below, -a call which executes `NUMBER` is performed, and the overridden number is placed on the stack: -``` +It is possible to supply 'overrides' for both state-data (accounts/storage) and block data (number, timestamp etc). In the example below, a call which executes `NUMBER` is performed, and the overridden number is placed on the stack: + +```sh > debug.traceCall({ from: eth.accounts[0], value:"0x1", @@ -665,51 +637,58 @@ a call which executes `NUMBER` is performed, and the overridden number is placed ``` Curl example: -``` + +```sh > curl -H "Content-Type: application/json" -X POST localhost:8545 --data '{"jsonrpc":"2.0","method":"debug_traceCall","params":[null, "pending"],"id":1}' {"jsonrpc":"2.0","id":1,"result":{"gas":53000,"failed":false,"returnValue":"","structLogs":[]}} ``` -### debug_traceChain {#debug-tracechain} +### debug_traceChain -Returns the structured logs created during the execution of EVM between two blocks (excluding start) as a JSON object. -This endpoint must be invoked via `debug_subscribe` as follows: +Returns the structured logs created during the execution of EVM between two blocks (excluding start) as a JSON object. This endpoint must be invoked via `debug_subscribe` as follows: -`const res = provider.send('debug_subscribe', ['traceChain', '0x3f3a2a', '0x3f3a2b'])` +```js +const res = provider.send('debug_subscribe', ['traceChain', '0x3f3a2a', '0x3f3a2b'])` +``` please refer to the [subscription page](https://geth.ethereum.org/docs/rpc/pubsub) for more details. -### debug_traceTransaction {#debug-tracetransaction} +### debug_traceTransaction **OBS** In most scenarios, `debug.standardTraceBlockToFile` is better suited for tracing! -The `traceTransaction` debugging method will attempt to run the transaction in the exact same manner -as it was executed on the network. It will replay any transaction that may have been executed prior -to this one before it will finally attempt to execute the transaction that corresponds to the given +The `traceTransaction` debugging method will attempt to run the transaction in the exact same manner as it was executed on the network. It will replay any transaction that may have been executed prior to this one before it will finally attempt to execute the transaction that corresponds to the given hash. -In addition to the hash of the transaction you may give it a secondary *optional* argument, which -specifies the options for this specific call. The possible options are: +| Client | Method invocation | +| :------ | ------------------------------------------------------------------------------------------- | +| Go | `debug.TraceTransaction(txHash common.Hash, config *TraceConfig) (*ExecutionResult, error)` | +| Console | `debug.traceTransaction(txHash, [options])` | +| RPC | `{"method": "debug_traceTransaction", "params": [txHash, {}]}` | + + +#### TraceConfig + +In addition to the hash of the transaction you may give it a secondary *optional* argument, which specifies the options for this specific call. The possible options are: * `disableStorage`: `BOOL`. Setting this to true will disable storage capture (default = false). * `disableStack`: `BOOL`. Setting this to true will disable stack capture (default = false). * `enableMemory`: `BOOL`. Setting this to true will enable memory capture (default = false). * `enableReturnData`: `BOOL`. Setting this to true will enable return data capture (default = false). -* `tracer`: `STRING`. Setting this will enable JavaScript-based transaction tracing, described below. - If set, the previous four arguments will be ignored. +* `tracer`: `STRING`. Name for built-in tracer or Javascript expression. See below for more details. + +If set, the previous four arguments will be ignored. + * `timeout`: `STRING`. Overrides the default timeout of 5 seconds for JavaScript-based tracing calls. Valid values are described [here](https://golang.org/pkg/time/#ParseDuration). +* `tracerConfig`: Config for the specified `tracer`. For example see callTracer's [config](/docs/evm-tracing/builtin-tracers#config). -| Client | Method invocation | -| :------ | -------------------------------------------------------------------------------------------- | -| Go | `debug.TraceTransaction(txHash common.Hash, logger *vm.LogConfig) (*ExecutionResult, error)` | -| Console | `debug.traceTransaction(txHash, [options])` | -| RPC | `{"method": "debug_traceTransaction", "params": [txHash, {}]}` | +Geth comes with a bundle of [built-in tracers](/docs/evm-tracing/builtin-tracers), each providing various data about a transaction. This method defaults to the [struct logger](/docs/evm-tracing/builtin-tracers#structopcode-logger). The `tracer` field of the second parameter can be set to use any of the other tracers. Alternatively a [custom tracer](/docs/evm-tracing/custom-tracer) can be implemented in either Go or Javascript. #### Example -```javascript +```js > debug.traceTransaction("0x2059dd53ecac9827faad14d364f9e04b1d5fe5b506e3acc886eff7a6f88a696a") { gas: 85301, @@ -743,176 +722,18 @@ specifies the options for this specific call. The possible options are: }] ``` +### debug_verbosity -#### JavaScript-based tracing {#javascript-tracing} +Sets the logging verbosity ceiling. Log messages with level up to and including the given level will be printed. -Specifying the `tracer` option in the second argument 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} - -`setup` is invoked once, in the beginning when the tracer is being constructed by Geth -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`: - -```js -debug.traceTransaction(', { tracer: 'callTracer', tracerConfig: { onlyTopCall: true } }) -``` - -The config in the following example is the `diffMode` option available -in the `prestateTracer`: - -```js -debug.traceTransaction(', { tracer: 'prestateTracer': tracerConfig: { diffMode: true } }) -``` - -##### Step {#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 opcode - - `stack`: Object, a structure representing the EVM execution stack - - `memory`: Object, a structure representing the contract's memory space - - `contract`: Object, an object representing the account executing the current operation - -and the following methods: - - - `getPC()` - returns a Number with the current program counter - - `getGas()` - returns a Number with the amount of gas remaining - - `getCost()` - returns the cost of the opcode as a Number - - `getDepth()` - returns the execution depth as a Number - - `getRefund()` - returns the amount to be refunded as a Number - - `getError()` - returns information about the error if one occured, 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: - - function(log) { - this.logs.append(log); - } - -But this step function will: - - function(log) { - this.logs.append({gas: log.getGas(), pc: log.getPC(), ...}); - } - -`log.op` has the following methods: - - - `isPush()` - returns true if the opcode is a PUSHn - - `toString()` - returns the string representation of the opcode - - `toNumber()` - returns the opcode's number - -`log.memory` has the following methods: - - - `slice(start, stop)` - returns the specified segment of memory as a byte slice - - `getUint(offset)` - returns the 32 bytes at the given offset - - `length()` - 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.Int - - `length()` - returns the number of elements in the stack - -`log.contract` has the following methods: - -- `getCaller()` - returns the address of the caller -- `getAddress()` - returns the address of the current contract -- `getValue()` - returns the amount of value sent from caller to contract as a big.Int -- `getInput()` - returns the input data passed to the contract - -`db` has the following methods: - - - `getBalance(address)` - returns a `big.Int` with the specified account's balance - - `getNonce(address)` - returns a Number with the specified account's nonce - - `getCode(address)` - returns a byte slice with the code for the specified account - - `getState(address, hash)` - returns the state value for the specified account and the specified hash - - `exists(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} - -`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 values `CALL` and `CREATE` -- `from` - Address, sender of the transaction -- `to` - Address, target of the transaction -- `input` - Buffer, input transaction data -- `gas` - Number, gas budget of the transaction -- `gasUsed` - Number, amount of gas used in executing the transaction (excludes txdata costs) -- `gasPrice` - Number, gas price configured in the transaction being executed -- `intrinsicGas` - Number, intrinsic gas for the transaction being executed -- `value` - big.Int, amount to be transferred in wei -- `block` - Number, block number -- `output` - Buffer, value returned from EVM -- `time` - 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 executed -- `txIndex` - Number, index of the transaction being executed in the block -- `txHash` - Buffer, hash of the transaction being executed - -##### Fault {#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} - -`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 frame -- `getFrom()` - returns the address of the call frame sender -- `getTo()` - returns the address of the call frame target -- `getInput()` - returns the input as a buffer -- `getGas()` - returns a Number which has the amount of gas provided for the frame -- `getValue()` - returns a `big.Int` with the amount to be transferred only if available, otherwise `undefined` - -`exit` takes in a `frameResult` object which has the following methods: - -- `getGasUsed()` - returns amount of gas used throughout the frame as a Number -- `getOutput()` - returns the output as a buffer -` -getError()` - returns an error if one occured during execution and `undefined` otherwise - -##### Usage {#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: - - debug.traceTransaction(txhash, {tracer: '{data: [], fault: function(log) {}, step: function(log) { if(log.op.toString() == "CALL") this.data.push(log.stack.peek(0)); }, result: function() { return this.data; }}'}); - - -### debug_verbosity {#debug-verbosity} - -Sets the logging verbosity ceiling. Log messages with level -up to and including the given level will be printed. - -The verbosity of individual packages and source files -can be raised using `debug_vmodule`. +The verbosity of individual packages and source files can be raised using `debug_vmodule`. | Client | Method invocation | | :------ | ------------------------------------------------- | | Console | `debug.verbosity(level)` | | RPC | `{"method": "debug_vmodule", "params": [number]}` | -### debug_vmodule {#debug-vmodule} +### debug_vmodule Sets the logging verbosity pattern. @@ -924,15 +745,13 @@ Sets the logging verbosity pattern. #### Examples -If you want to see messages from a particular Go package (directory) -and all subdirectories, use: +If you want to see messages from a particular Go package (directory) and all subdirectories, use: ``` javascript > debug.vmodule("eth/*=6") ``` -If you want to restrict messages to a particular package (e.g. p2p) -but exclude subdirectories, use: +If you want to restrict messages to a particular package (e.g. p2p) but exclude subdirectories, use: ``` javascript > debug.vmodule("p2p=6") @@ -944,16 +763,13 @@ If you want to see log messages from a particular source file, use > debug.vmodule("server.go=6") ``` -You can compose these basic patterns. If you want to see all -output from peer.go in a package below eth (eth/peer.go, -eth/downloader/peer.go) as well as output from package p2p -at level <= 5, use: +You can compose these basic patterns. If you want to see all output from peer.go in a package below eth (eth/peer.go, eth/downloader/peer.go) as well as output from package p2p at level <= 5, use: ``` javascript debug.vmodule("eth/*/peer.go=6,p2p=5") ``` -### debug_writeBlockProfile {#debug-writeblockprofile} +### debug_writeBlockProfile Writes a goroutine blocking profile to the given file. @@ -962,19 +778,16 @@ Writes a goroutine blocking profile to the given file. | Console | `debug.writeBlockProfile(file)` | | RPC | `{"method": "debug_writeBlockProfile", "params": [string]}` | -### debug_writeMemProfile {#debug-writememprofile} +### debug_writeMemProfile -Writes an allocation profile to the given file. -Note that the profiling rate cannot be set through the API, -it must be set on the command line using the `--pprof.memprofilerate` -flag. +Writes an allocation profile to the given file. Note that the profiling rate cannot be set through the API, it must be set on the command line using the `--pprof.memprofilerate` flag. | Client | Method invocation | | :------ | ----------------------------------------------------------- | | Console | `debug.writeMemProfile(file string)` | | RPC | `{"method": "debug_writeBlockProfile", "params": [string]}` | -### debug_writeMutexProfile {#debug-writemutexprofile} +### debug_writeMutexProfile Writes a goroutine blocking profile to the given file. diff --git a/docs/interacting-with-geth/rpc/ns_personal_deprecation.md b/docs/interacting-with-geth/rpc/ns_personal_deprecation.md index bc1438138b..5691dbf133 100644 --- a/docs/interacting-with-geth/rpc/ns_personal_deprecation.md +++ b/docs/interacting-with-geth/rpc/ns_personal_deprecation.md @@ -211,7 +211,7 @@ Example call (use the following as a template for `` in `curl --data