description: How to interact with Geth using Javascript
---
Geth responds to instructions encoded as JSON objects as defined in the [JSON-RPC-API](/docs/rpc/server). A Geth user can send these instructions directly, for example over HTTP using tools like [Curl](https://github.com/curl/curl). The code snippet below shows a request for an account balance sent to a local Geth node with the HTTP port `8545` exposed.
description: How to make batch requests using JSON-RPC API
---
The JSON-RPC [specification](https://www.jsonrpc.org/specification#batch) outlines how clients can send multiple requests at the same time by filling the request objects in an array. This feature is implemented by Geth's API and can be used to cut network delays. Batching offers visible speed-ups specially when used for fetching larger amounts of mostly independent data objects. Below is an example for fetching a list of blocks in JS:
In addition to the [JSON-RPC APIs](../rpc/server), Geth supports the GraphQL API as specified by [EIP-1767](eip-1767). GraphQL lets you specify which fields of an objects you need as part of the query, eliminating the extra load on the client for filling in fields which are not needed. It also allows for combining several traditional JSON-RPC requests into one query which translates into less overhead and more performance.
In addition to the [JSON-RPC APIs](/content/docs/interacting_with_geth/RPC/server.md), Geth supports the GraphQL API as specified by [EIP-1767](https://eips.ethereum.org/EIPS/eip-1767). GraphQL lets you specify which fields of an objects you need as part of the query, eliminating the extra load on the client for filling in fields which are not needed. It also allows for combining several traditional JSON-RPC requests into one query which translates into less overhead and more performance.
The GraphQL endpoint piggybacks on the HTTP transport used by JSON-RPC. Hence the relevant `--http` flags and the `--graphql` flag should be passed to Geth:
@ -31,7 +31,7 @@ GraphiQL also provides a way to explore the schema Geth provides to help you for
### Query
Reading out data from Geth is the biggest use-case for GraphQL. In addition to using the UI queries can also be sent programmatically. The official GraphQL[docs](graphql-code) explain how to find bindings for many languages, or send http requests from the terminal using tools such as Curl.
Reading out data from Geth is the biggest use-case for GraphQL. In addition to using the UI queries can also be sent programmatically. The official GraphQL[docs](https://graphql.org/code/) explain how to find bindings for many languages, or send http requests from the terminal using tools such as Curl.
For example, the code snippet below shows how to obtain the latest block number using Curl. Note the use of a JSON object for the data section:
description: Documentation for the JSON-RPC API "admin" namespace
---
The `admin` API gives access to several non-standard RPC methods, which allows fine grained control over a Geth instance, including but not limited to network peer and RPC endpoint management.
@ -8,13 +8,9 @@ The `admin` API gives access to several non-standard RPC methods, which allows f
### admin_addPeer
The `addPeer` administrative method requests adding a new remote node to the list of tracked static
nodes. The node will try to maintain connectivity to these nodes at all times, reconnecting every
once in a while if the remote connection goes down.
The `addPeer` administrative method requests adding a new remote node to the list of tracked static nodes. The node will try to maintain connectivity to these nodes at all times, reconnecting every once in a while if the remote connection goes down.
The method accepts a single argument, the [`enode`](https://ethereum.org/en/developers/docs/networking-layer/network-addresses/#enode)
URL of the remote peer to start tracking and returns a `BOOL` indicating whether the peer was accepted
for tracking or some error occurred.
The method accepts a single argument, the [`enode`](https://ethereum.org/en/developers/docs/networking-layer/network-addresses/#enode) URL of the remote peer to start tracking and returns a `BOOL` indicating whether the peer was accepted for tracking or some error occurred.
Adds the given node to a reserved trusted list which allows the
node to always connect, even if the slots are full.
It returns a `BOOL` to indicate whether the peer was successfully added to the list.
Adds the given node to a reserved trusted list which allows the node to always connect, even if the slots are full. It returns a `BOOL` to indicate whether the peer was successfully added to the list.
@ -43,8 +36,7 @@ It returns a `BOOL` to indicate whether the peer was successfully added to the l
### admin_datadir
The `datadir` administrative property can be queried for the absolute path the running Geth node
currently uses to store all its databases.
The `datadir` administrative property can be queried for the absolute path the running Geth node currently uses to store all its databases.
| Client | Method invocation |
|:--------|-----------------------------------|
@ -61,10 +53,7 @@ currently uses to store all its databases.
### admin_exportChain
Exports the current blockchain into a local file.
It optionally takes a first and last block number, in which case it exports only that range of blocks.
It returns a boolean indicating whether the operation succeeded.
Exports the current blockchain into a local file. It optionally takes a first and last block number, in which case it exports only that range of blocks. It returns a boolean indicating whether the operation succeeded.
@ -73,10 +62,7 @@ It returns a boolean indicating whether the operation succeeded.
### admin_importChain
Imports an exported list of blocks from a local file. Importing involves processing the blocks and inserting them
into the canonical chain. The state from the parent block of this range is required.
It returns a boolean indicating whether the operation succeeded.
Imports an exported list of blocks from a local file. Importing involves processing the blocks and inserting them into the canonical chain. The state from the parent block of this range is required. It returns a boolean indicating whether the operation succeeded.
@ -85,11 +71,7 @@ It returns a boolean indicating whether the operation succeeded.
### admin_nodeInfo
The `nodeInfo` administrative property can be queried for all the information known about the running
Geth node at the networking granularity. These include general information about the node itself as a
participant of the [ÐΞVp2p](https://github.com/ethereum/devp2p/blob/master/caps/eth.md) P2P
overlay protocol, as well as specialized information added by each of the running application protocols
(e.g. `eth`, `les`, `shh`, `bzz`).
The `nodeInfo` administrative property can be queried for all the information known about the running Geth node at the networking granularity. These include general information about the node itself as a participant of the [ÐΞVp2p](https://github.com/ethereum/devp2p/blob/master/caps/eth.md) P2P overlay protocol, as well as specialized information added by each of the running application protocols (e.g. `eth`, `les`, `shh`, `bzz`).
@ -124,9 +106,7 @@ overlay protocol, as well as specialized information added by each of the runnin
### admin_peerEvents
PeerEvents creates an [RPC subscription](/docs/rpc/pubsub) which receives peer events from the node's p2p server.
The type of events emitted by the server are as follows:
PeerEvents creates an [RPC subscription](/docs/rpc/pubsub) which receives peer events from the node's p2p server. The type of events emitted by the server are as follows:
- `add`: emitted when a peer is added
- `drop`: emitted when a peer is dropped
@ -135,11 +115,7 @@ The type of events emitted by the server are as follows:
### admin_peers
The `peers` administrative property can be queried for all the information known about the connected
remote nodes at the networking granularity. These include general information about the nodes themselves
as participants of the [ÐΞVp2p](https://github.com/ethereum/devp2p/blob/master/caps/eth.md)
P2P overlay protocol, as well as specialized information added by each of the running application
protocols (e.g. `eth`, `les`, `shh`, `bzz`).
The `peers` administrative property can be queried for all the information known about the connected remote nodes at the networking granularity. These include general information about the nodes themselves as participants of the [ÐΞVp2p](https://github.com/ethereum/devp2p/blob/master/caps/eth.md) P2P overlay protocol, as well as specialized information added by each of the running application protocols (e.g. `eth`, `les`, `shh`, `bzz`).
Disconnects from a remote node if the connection exists.
It returns a boolean indicating validations succeeded. Note a `true` value doesn't necessarily mean
that there was a connection which was disconnected.
Disconnects from a remote node if the connection exists. It returns a boolean indicating validations succeeded. Note a `true` value doesn't necessarily mean that there was a connection which was disconnected.
@ -209,8 +180,7 @@ It returns a boolean indicating validations succeeded.
### admin_startHTTP
The `startHTTP` administrative method starts an HTTP based JSON-RPC [API](/docs/rpc/server)
webserver to handle client requests. All the parameters are optional:
The `startHTTP` administrative method starts an HTTP based JSON-RPC [API](/docs/rpc/server) webserver to handle client requests. All the parameters are optional:
* `host`: network interface to open the listener socket on (defaults to `"localhost"`)
* `port`: network port to open the listener socket on (defaults to `8545`)
@ -234,8 +204,7 @@ true
### admin_startWS
The `startWS` administrative method starts an WebSocket based [JSON RPC](https://www.jsonrpc.org/specification)
API webserver to handle client requests. All the parameters are optional:
The `startWS` administrative method starts an WebSocket based [JSON RPC](https://www.jsonrpc.org/specification) API webserver to handle client requests. All the parameters are optional:
* `host`: network interface to open the listener socket on (defaults to `"localhost"`)
* `port`: network port to open the listener socket on (defaults to `8546`)
description: Documentation for the JSON-RPC API "clique" namespace
---
The `clique` API provides access to the state of the clique consensus engine. This API cna be used to manage signer votes and to check the health of a private network.
@ -52,8 +52,7 @@ Retrieves the state snapshot at a given block.
### clique_getSigner
Returns the signer for a specific clique block. Can be called with either a blocknumber, blockhash or an rlp encoded blob.
The RLP encoded blob can either be a block or a header.
Returns the signer for a specific clique block. Can be called with either a blocknumber, blockhash or an rlp encoded blob. The RLP encoded blob can either be a block or a header.
@ -89,10 +88,7 @@ Returns the current proposals the node is voting on.
### clique_propose
Adds a new authorization proposal that the signer will attempt to push through. If the
`auth` parameter is true, the local signer votes for the given address to be included in
the set of authorized signers. With `auth` set to `false`, the vote is against the
address.
Adds a new authorization proposal that the signer will attempt to push through. If the `auth` parameter is true, the local signer votes for the given address to be included in the set of authorized signers. With `auth` set to `false`, the vote is against the address.
description: Documentation for the JSON-RPC API "clique" namespace
---
The `debug` API gives access to several non-standard RPC methods, which allow inspection, debugging and setting certain debugging flags during runtime.
@ -19,9 +19,7 @@ If `incompletes` is false, then accounts for which the key preimage (i.e: the `a
### debug_backtraceAt
Sets the logging backtrace location. When a backtrace location
is set and a log message is emitted at that location, the stack
of the goroutine executing the log statement will be printed to stderr.
Sets the logging backtrace location. When a backtrace location is set and a log message is emitted at that location, the stack of the goroutine executing the log statement will be printed to stderr.
The location is specified as `<filename>:<line>`.
@ -38,11 +36,7 @@ Example:
### 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`.
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)
@ -119,8 +111,7 @@ Returns the raw value of a key stored in the database.
### 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).
@ -193,10 +182,7 @@ the fields of the returned object.
### 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.
@ -247,9 +232,7 @@ Returns all accounts that have changed between the two blocks specified. A chang
### 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
storage hash.
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.
@ -337,10 +318,7 @@ Fetches and retrieves the seed hash of the block by number
### 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`.
Sets the current head of the local chain by block number. **Note**, this is a
destructive action and may severely damage the 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 the chain. Use with *extreme* caution.
@ -384,9 +360,7 @@ Sets the rate of mutex profiling.
### 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.
@ -396,8 +370,7 @@ and does not return the string.
### 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)
@ -409,12 +382,13 @@ This method works a bit differently. (For full details, see [PR](https://github.
This means that this method is only 'useful' for callers who control the node -- at least sufficiently to be able to read the artefacts from the filesystem after the fact.
The method can be used to dump a certain transaction out of a given block:
@ -433,7 +407,8 @@ INFO [10-15|13:48:34.421] Wrote trace file=/tmp/block_0x14490c57-2-0x3f4263fe-05
```
The `options` is as follows:
```
```sh
type StdTraceConfig struct {
*vm.LogConfig
Reexec *uint64
@ -502,9 +477,7 @@ Returns the structured logs created during the execution of EVM against a block
### 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.
Similar to [debug_traceBlock](#debug_traceblock), `traceBlockByNumber` accepts a block number 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.
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), `traceBlockByHash` accepts a block hash and will replay the block that is already present in the database.
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",
@ -662,15 +635,14 @@ a call which executes `NUMBER` is performed, and the overridden number is placed
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'])`
@ -681,13 +653,10 @@ please refer to the [subscription page](https://geth.ethereum.org/docs/rpc/pubsu
**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 it can take a secondary *optional* argument, which
specifies the options for this specific call. The possible options are:
In addition to the hash of the transaction it can take 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).
@ -856,16 +825,15 @@ Note that several values are Golang big.Int objects, not JavaScript numbers or J
Usage example, returns the top element of the stack at each CALL opcode only:
@ -884,8 +852,7 @@ Sets the logging verbosity pattern.
#### Examples
To see messages from a particular Go package (directory)
and all subdirectories, use:
To see messages from a particular Go package (directory) and all subdirectories, use:
``` javascript
> debug.vmodule("eth/*=6")
@ -921,10 +888,7 @@ Writes a goroutine blocking profile to the given file.
### 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.
sort_key: Documentation for the JSON-RPC API "eth" namespace
---
Geth provides several extensions to the standard "eth" JSON-RPC namespace.
### eth_subscribe, eth_unsubscribe
These methods are used for real-time events through subscriptions. See the [subscription
documentation](./pubsub) for more information.
These methods are used for real-time events through subscriptions. See the [subscription documentation](/content/docs/interacting_with_geth/RPC/pubsub.md) for more information.
### eth_call
Executes a new message call immediately, without creating a transaction on the block
chain. The `eth_call` method can be used to query internal contract state, to execute
validations coded into a contract or even to test what the effect of a transaction would
be without running it live.
Executes a new message call immediately, without creating a transaction on the block chain. The `eth_call` method can be used to query internal contract state, to execute validations coded into a contract or even to test what the effect of a transaction would be without running it live.
#### Parameters
The method takes 3 parameters: an unsigned transaction object to execute in read-only
mode; the block number to execute the call against; and an optional state override-set to
allow executing the call against a modified chain state.
The method takes 3 parameters: an unsigned transaction object to execute in read-only mode; the block number to execute the call against; and an optional state override-set to allow executing the call against a modified chain state.
##### 1. `Object` - Transaction call object
The *transaction call object* is mandatory. Please see [here](/docs/rpc/objects#transaction-call-object) for details.
The *transaction call object* is mandatory. Please see [here](/content/docs/interacting_with_geth/RPC/objects.md) for details.
##### 2. `Quantity | Tag` - Block number or the string `latest` or `pending`
The *block number* is mandatory and defines the context (state) against which the
specified transaction should be executed. It is not possible to execute calls against
reorged blocks; or blocks older than 128 (unless the node is an archive node).
The *block number* is mandatory and defines the context (state) against which the specified transaction should be executed. It is not possible to execute calls against reorged blocks; or blocks older than 128 (unless the node is an archive node).
##### 3. `Object` - State override set
The *state override set* is an optional address-to-state mapping, where each entry
specifies some state to be ephemerally overridden prior to executing the call. Each
address maps to an object containing:
The *state override set* is an optional address-to-state mapping, where each entry specifies some state to be ephemerally overridden prior to executing the call. Each address maps to an object containing:
@ -49,15 +39,9 @@ address maps to an object containing:
The goal of the *state override set* is manyfold:
* It can be used by DApps to reduce the amount of contract code needed to be deployed on
chain. Code that simply returns internal state or does pre-defined validations can be
kept off chain and fed to the node on-demand.
* It can be used for smart contract analysis by extending the code deployed on chain with
custom methods and invoking them. This avoids having to download and reconstruct the
entire state in a sandbox to run custom code against.
* It can be used to debug smart contracts in an already deployed large suite of contracts
by selectively overriding some code or state and seeing how execution changes.
Specialized tooling will probably be necessary.
* It can be used by DApps to reduce the amount of contract code needed to be deployed on chain. Code that simply returns internal state or does pre-defined validations can be kept off chain and fed to the node on-demand.
* It can be used for smart contract analysis by extending the code deployed on chain with custom methods and invoking them. This avoids having to download and reconstruct the entire state in a sandbox to run custom code against.
* It can be used to debug smart contracts in an already deployed large suite of contracts by selectively overriding some code or state and seeing how execution changes. Specialized tooling will probably be necessary.
Example:
@ -77,15 +61,11 @@ Example:
#### Return Values
The method returns a single `Binary` consisting the return value of the executed contract
call.
The method returns a single `Binary` consisting the return value of the executed contract call.
#### Simple example
With a synced Rinkeby node with RPC exposed on localhost (`geth --rinkeby --http`) we can
With a synced Rinkeby node with RPC exposed on localhost (`geth --rinkeby --http`) we can make a call against the [CheckpointOracle](https://rinkeby.etherscan.io/address/0xebe8efa441b9302a0d7eaecc277c09d20d684540) to retrieve the list of administrators:
```
$ curl --data '{"method":"eth_call","params":[{"to":"0xebe8efa441b9302a0d7eaecc277c09d20d684540","data":"0x45848dfc"},"latest"],"id":1,"jsonrpc":"2.0"}' -H "Content-Type: application/json" -X POST localhost:8545
@ -112,13 +92,9 @@ Just for the sake of completeness, decoded the response is:
#### Override example
The above *simple example* showed how to call a method already exposed by an on-chain
smart contract. What if we want to access some data not exposed by it?
The above *simple example* showed how to call a method already exposed by an on-chain smart contract. What if we want to access some data not exposed by it?
checkpoint oracle contract with one that retains the same fields (to retain the same
storage layout), but one that includes a different method set:
We can gut out the [original](https://github.com/ethereum/go-ethereum/blob/master/contracts/checkpointoracle/contract/oracle.sol) checkpoint oracle contract with one that retains the same fields (to retain the same storage layout), but one that includes a different method set:
```
pragma solidity ^0.5.10;
@ -139,10 +115,7 @@ contract CheckpointOracle {
}
```
With a synced Rinkeby node with RPC exposed on localhost (`geth --rinkeby --http`) we can
but override its byte code with our own version that has an accessor for the voting
With a synced Rinkeby node with RPC exposed on localhost (`geth --rinkeby --http`) we can make a call against the live [Checkpoint Oracle](https://rinkeby.etherscan.io/address/0xebe8efa441b9302a0d7eaecc277c09d20d684540), but override its byte code with our own version that has an accessor for the voting
threshold field:
```
@ -163,10 +136,7 @@ Just for the sake of completeness, decoded the response is: `2`.
### eth_createAccessList
This method creates an [EIP2930](https://eips.ethereum.org/EIPS/eip-2930) type `accessList` based on a given `Transaction`.
The `accessList` contains all storage slots and addresses read and written by the transaction, except for the sender account and the precompiles.
This method uses the same `transaction` call [object](/docs/rpc/objects#transaction-call-object) and `blockNumberOrTag` object as `eth_call`.
An `accessList` can be used to unstuck contracts that became inaccessible due to gas cost increases.
This method creates an [EIP2930](https://eips.ethereum.org/EIPS/eip-2930) type `accessList` based on a given `Transaction`. The `accessList` contains all storage slots and addresses read and written by the transaction, except for the sender account and the precompiles. This method uses the same `transaction` call [object](/docs/rpc/objects#transaction-call-object) and `blockNumberOrTag` object as `eth_call`. An `accessList` can be used to unstuck contracts that became inaccessible due to gas cost increases.
The method `eth_createAccessList` returns list of addresses and storage keys used by the transaction, plus the gas consumed when the access list is added.
That is, it gives the list of addresses and storage keys that will be used by that transaction, plus the gas consumed if the access list is included. Like `eth_estimateGas`, this is an estimation; the list could change when the transaction is actually mined.
Adding an `accessList` to a transaction does not necessary result in lower gas usage compared to a transaction without an access list.
That is, it gives the list of addresses and storage keys that will be used by that transaction, plus the gas consumed if the access list is included. Like `eth_estimateGas`, this is an estimation; the list could change when the transaction is actually mined. Adding an `accessList` to a transaction does not necessary result in lower gas usage compared to a transaction without an access list.
description: Documentation for the JSON-RPC API "les" namespace
---
The `les` API is for managing LES server settings, including client parameters and payment settings for prioritized clients. It also provides functions to query checkpoint information in both server and client mode.
description: Documentation for the JSON-RPC API "miner" namespace
---
The `miner` API is **now deprecated** because mining was switched off at the transition to proof-of-stake. It existed to provide remote control the node's mining operation and set various mining specific settings. It is provided here for historical interest!
@ -16,8 +16,7 @@ Get hashrate in H/s (Hash operations per second).
### miner_setExtra
Sets the extra data a miner can include when miner blocks. This is capped at
32 bytes.
Sets the extra data a miner can include when miner blocks. This is capped at 32 bytes.
Decrypts the key with the given address from the key store.
Both passphrase and unlock duration are optional when using the JavaScript console.
If the passphrase is not supplied as an argument, the console will prompt for
the passphrase interactively.
The unencrypted key will be held in memory until the unlock duration expires.
If the unlock duration defaults to 300 seconds. An explicit duration
of zero seconds unlocks the key until geth exits.
Both passphrase and unlock duration are optional when using the JavaScript console. If the passphrase is not supplied as an argument, the console will prompt for
the passphrase interactively. The unencrypted key will be held in memory until the unlock duration expires. If the unlock duration defaults to 300 seconds. An explicit duration of zero seconds unlocks the key until geth exits.
The account can be used with `eth_sign` and `eth_sendTransaction` while it is unlocked.
@ -162,8 +148,7 @@ Supplying the passphrase and unlock duration as arguments:
true
```
To type in the passphrase and still override the default unlock duration,
pass `null` as the passphrase.
To type in the passphrase and still override the default unlock duration, pass `null` as the passphrase.
@ -225,7 +210,7 @@ See ecRecover to verify the signature.
### personal_signTransaction
SignTransaction will create a transaction from the given arguments and tries to sign it with the key associated with `tx.from`. If the given passwd isn't able to decrypt the key it fails. The transaction is returned in RLP-form, not broadcast to other nodes. The first argument is a [transaction object](/docs/rpc/objects#transaction-call-object) and the second argument is the password, similar to `personal_sendTransaction`.
SignTransaction will create a transaction from the given arguments and tries to sign it with the key associated with `tx.from`. If the given passwd isn't able to decrypt the key it fails. The transaction is returned in RLP-form, not broadcast to other nodes. The first argument is a [transaction object](/content/docs/interacting_with_geth/RPC/objects.md) and the second argument is the password, similar to `personal_sendTransaction`.
description: Documentation for the JSON-RPC API "txpool" namespace
---
The `txpool` API gives access to several non-standard RPC methods to inspect the contents of the
transaction pool containing all the currently pending transactions as well as the ones queued for
future processing.
The `txpool` API gives access to several non-standard RPC methods to inspect the contents of the transaction pool containing all the currently pending transactions as well as the ones queued for future processing.
### txpool_content
The `content` inspection property can be queried to list the exact details of all the transactions
currently pending for inclusion in the next block(s), as well as the ones that are being scheduled
for future execution only.
The `content` inspection property can be queried to list the exact details of all the transactions currently pending for inclusion in the next block(s), as well as the ones that are being scheduled for future execution only.
The result is an object with two fields `pending` and `queued`. Each of these fields are associative
arrays, in which each entry maps an origin-address to a batch of scheduled transactions. These batches
themselves are maps associating nonces with actual transactions.
The result is an object with two fields `pending` and `queued`. Each of these fields are associative arrays, in which each entry maps an origin-address to a batch of scheduled transactions. These batches themselves are maps associating nonces with actual transactions.
Please note, there may be multiple transactions associated with the same account and nonce. This can
happen if the user broadcast mutliple ones with varying gas allowances (or even completely different
transactions).
Please note, there may be multiple transactions associated with the same account and nonce. This can happen if the user broadcast mutliple ones with varying gas allowances (or even completely different transactions).
@ -124,18 +115,11 @@ returning pending as well as queued transactions of this address, grouped by non
### txpool_inspect
The `inspect` inspection property can be queried to list a textual summary of all the transactions
currently pending for inclusion in the next block(s), as well as the ones that are being scheduled
for future execution only. This is a method specifically tailored to developers to quickly see the
transactions in the pool and find any potential issues.
The `inspect` inspection property can be queried to list a textual summary of all the transactions currently pending for inclusion in the next block(s), as well as the ones that are being scheduled for future execution only. This is a method specifically tailored to developers to quickly see the transactions in the pool and find any potential issues.
The result is an object with two fields `pending` and `queued`. Each of these fields are associative
arrays, in which each entry maps an origin-address to a batch of scheduled transactions. These batches
themselves are maps associating nonces with transactions summary strings.
The result is an object with two fields `pending` and `queued`. Each of these fields are associative arrays, in which each entry maps an origin-address to a batch of scheduled transactions. These batches themselves are maps associating nonces with transactions summary strings.
Please note, there may be multiple transactions associated with the same account and nonce. This can
happen if the user broadcast mutliple ones with varying gas allowances (or even completely different
transactions).
Please note, there may be multiple transactions associated with the same account and nonce. This can happen if the user broadcast mutliple ones with varying gas allowances (or even completely different transactions).
The `status` inspection property can be queried for the number of transactions currently pending for
inclusion in the next block(s), as well as the ones that are being scheduled for future execution only.
The `status` inspection property can be queried for the number of transactions currently pending for inclusion in the next block(s), as well as the ones that are being scheduled for future execution only.
The result is an object with two fields `pending` and `queued`, each of which is a counter representing
the number of transactions in that particular state.
The result is an object with two fields `pending` and `queued`, each of which is a counter representing the number of transactions in that particular state.
description: How to subscribe to events using JSON-RPC notifications.
---
Geth v1.4 and later support publish / subscribe using JSON-RPC notifications. This allows clients to wait for events instead of polling for them.
@ -54,9 +54,7 @@ Subscriptions are created with a regular RPC call with `eth_subscribe` as method
## Cancel subscription
Subscriptions are cancelled with a regular RPC call with `eth_unsubscribe` as method and
the subscription id as first parameter. It returns a bool indicating if the subscription
was cancelled successful.
Subscriptions are cancelled with a regular RPC call with `eth_unsubscribe` as method and the subscription id as first parameter. It returns a bool indicating if the subscription was cancelled successful.
### Parameters
1. subscription id
@ -74,8 +72,7 @@ was cancelled successful.
Fires a notification each time a new header is appended to the chain, including chain reorganizations. Users can use the bloom filter to determine if the block contains logs that are interested to them. Note that if geth receives multiple blocks simultaneously, e.g. catching up after being out of sync, only the last block is emitted.
In case of a chain reorganization the subscription will emit the last header in the new
chain. Therefore the subscription can emit multiple headers on the same height.
In case of a chain reorganization the subscription will emit the last header in the new chain. Therefore the subscription can emit multiple headers on the same height.
#### Example
@ -169,9 +166,7 @@ returns
### syncing
Indicates when the node starts or stops synchronizing. The result can either be a boolean
indicating that the synchronization has started (true), finished (false) or an object with
various progress indicators.
Indicates when the node starts or stops synchronizing. The result can either be a boolean indicating that the synchronization has started (true), finished (false) or an object with various progress indicators.
Interacting with Geth requires sending requests to specific JSON-RPC API
methods. Geth supports all standard [JSON-RPC API][web3-rpc] endpoints.
The RPC requests must be sent to the node and the response returned to the client
using some transport protocol. This page outlines the available transport protocols
in Geth, providing the information users require to choose a transport protocol for
a specific user scenario.
Interacting with Geth requires sending requests to specific JSON-RPC API methods. Geth supports all standard [JSON-RPC API](https://github.com/ethereum/execution-apis) endpoints.
The RPC requests must be sent to the node and the response returned to the client using some transport protocol. This page outlines the available transport protocols in Geth, providing the information users require to choose a transport protocol for a specific user scenario.
{:toc}
- this will be removed by the toc
## Introduction
JSON-RPC is provided on multiple transports. Geth supports JSON-RPC over HTTP,
WebSocket and Unix Domain Sockets. Transports must be enabled through
command-line flags.
JSON-RPC is provided on multiple transports. Geth supports JSON-RPC over HTTP, WebSocket and Unix Domain Sockets. Transports must be enabled through
command-line flags.
Ethereum JSON-RPC APIs use a name-space system. RPC methods are grouped into
several categories depending on their purpose. All method names are composed of
the namespace, an underscore, and the actual method name within the namespace.
For example, the `eth_call` method resides in the `eth` namespace.
Ethereum JSON-RPC APIs use a name-space system. RPC methods are grouped into several categories depending on their purpose. All method names are composed of
the namespace, an underscore, and the actual method name within the namespace. For example, the `eth_call` method resides in the `eth` namespace.
Access to RPC methods can be enabled on a per-namespace basis. Find
documentation for individual namespaces in the sidebar.
Access to RPC methods can be enabled on a per-namespace basis. Find documentation for individual namespaces in the sidebar.
## Transports
@ -33,50 +23,35 @@ There are three transport protocols available in Geth: IPC, HTTP and Websockets.
### HTTP Server
[HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP) is a unidirectional transport protocol
that connects a client and server. The client sends a request to the server, and the server
returns a response back to the client. An HTTP connection is closed after the response for a given
request is sent.
[HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP) is a unidirectional transport protocol that connects a client and server. The client sends a request to the server, and the server returns a response back to the client. An HTTP connection is closed after the response for a given request is sent.
HTTP is supported in every browser as well as almost all programming toolchains. Due to its ubiquity
it has become the most widely used transport for interacting with Geth. To start a HTTP server in Geth, include the `--http` flag:
HTTP is supported in every browser as well as almost all programming toolchains. Due to its ubiquity it has become the most widely used transport for interacting with Geth. To start a HTTP server in Geth, include the `--http` flag:
```sh
geth --http
```
If no other commands are provided, Geth falls back to its default behaviour of accepting connections
from the local loopback interface (127.0.0.1). The default listening port is 8545. The ip address and
listening port can be customized using the `--http.addr` and `--http.port` flags:
If no other commands are provided, Geth falls back to its default behaviour of accepting connections from the local loopback interface (127.0.0.1). The default listening port is 8545. The ip address and listening port can be customized using the `--http.addr` and `--http.port` flags:
```sh
geth --http --http.port 3334
```
Not all of the JSON-RPC method namespaces are enabled for HTTP requests by default.
Instead, they have to be whitelisted explicitly when Geth is started. Calling non-whitelisted
RPC namespaces returns an RPC error with code `-32602`.
Not all of the JSON-RPC method namespaces are enabled for HTTP requests by default. Instead, they have to be whitelisted explicitly when Geth is started. Calling non-whitelisted RPC namespaces returns an RPC error with code `-32602`.
The default whitelist allows access to the `eth`, `net` and `web3` namespaces. To enable access
to other APIs like account management (`personal`) and debugging (`debug`), they must be configured
using the `--http.api` flag. Enabling these APIs over HTTP is **not recommended** because access
to these methods increases the attack surface.
The default whitelist allows access to the `eth`, `net` and `web3` namespaces. To enable access to other APIs like account management (`personal`) and debugging (`debug`), they must be configured using the `--http.api` flag. Enabling these APIs over HTTP is **not recommended** because access to these methods increases the attack surface.
```sh
geth --http --http.api personal,eth,net,web3
```
Since the HTTP server is reachable from any local application, additional protection is built into
the server to prevent misuse of the API from web pages. To enable access to the API from a web page
(for example to use the online IDE, [Remix](https://remix.ethereum.org)), the server needs to be
configured to accept Cross-Origin requests. This is achieved using the `--http.corsdomain` flag.
Since the HTTP server is reachable from any local application, additional protection is built into the server to prevent misuse of the API from web pages. To enable access to the API from a web page (for example to use the online IDE, [Remix](https://remix.ethereum.org)), the server needs to be configured to accept Cross-Origin requests. This is achieved using the `--http.corsdomain` flag.
The `--http.corsdomain` command also acceptsd wildcards that enable access to the RPC from any
origin:
The `--http.corsdomain` command also acceptsd wildcards that enable access to the RPC from any origin:
```sh
--http.corsdomain '*'
@ -84,28 +59,19 @@ origin:
### WebSocket Server
Websocket is a bidirectional transport protocol. A Websocket connection is maintained by client and server
until it is explicitly terminated by one. Most modern browsers support Websocket which means
it has good tooling.
Websocket is a bidirectional transport protocol. A Websocket connection is maintained by client and server until it is explicitly terminated by one. Most modern browsers support Websocket which means it has good tooling.
Because Websocket is bidirectional, servers can push events to clients. That makes Websocket a good
choice for use-cases involving [event subscription](https://geth.ethereum.org/docs/rpc/pubsub). Another
benefit of Websocket is that after the handshake procedure, the overhead of individual messages is low,
Because Websocket is bidirectional, servers can push events to clients. That makes Websocket a good choice for use-cases involving [event subscription](https://geth.ethereum.org/docs/rpc/pubsub). Another benefit of Websocket is that after the handshake procedure, the overhead of individual messages is low,
making it good for sending high number of requests.
Configuration of the WebSocket endpoint in Geth follows the same pattern as the HTTP transport.
WebSocket access can be enabled using the `--ws` flag. If no additional information is provided,
Geth falls back to its default behaviour which is to establish the Websocket on port 8546.
The `--ws.addr`, `--ws.port` and `--ws.api` flags can be used to customize settings
for the WebSocket server. For example, to start Geth with a Websocket connection for RPC using
Configuration of the WebSocket endpoint in Geth follows the same pattern as the HTTP transport. WebSocket access can be enabled using the `--ws` flag. If no additional information is provided, Geth falls back to its default behaviour which is to establish the Websocket on port 8546. The `--ws.addr`, `--ws.port` and `--ws.api` flags can be used to customize settings for the WebSocket server. For example, to start Geth with a Websocket connection for RPC using
the custom port 3334 and whitelisting the `eth`, `net` and `web3` namespaces:
```sh
geth --ws --ws.port 3334 --ws.api eth,net,web3
```
Cross-Origin request protection also applies to the WebSocket server. The
`--ws.origins` flag can be used to allow access to the server from web pages:
Cross-Origin request protection also applies to the WebSocket server. The `--ws.origins` flag can be used to allow access to the server from web pages:
As with `--http.corsdomain`, using the wildcard `--ws.origins '*'` allows access from any origin.
{% include note.html content=" By default, **account unlocking is forbidden when HTTP or
Websocket access is enabled** (i.e. by passing `--http` or `ws` flag). This is because an
attacker that manages to access the node via the externally-exposed HTTP/WS port can then
control the unlocked account. It is possible to force account unlock by including the
`--allow-insecure-unlock` flag but this is unsafe and **not recommended** except for expert
users that completely understand how it can be used safely.
This is not a hypothetical risk: **there are bots that continually scan for http-enabled
Ethereum nodes to attack**" %}
{% include note.html content=" By default, **account unlocking is forbidden when HTTP or Websocket access is enabled** (i.e. by passing `--http` or `ws` flag). This is because an attacker that manages to access the node via the externally-exposed HTTP/WS port can then control the unlocked account. It is possible to force account unlock by including the `--allow-insecure-unlock` flag but this is unsafe and **not recommended** except for expert users that completely understand how it can be used safely. This is not a hypothetical risk: **there are bots that continually scan for http-enabled Ethereum nodes to attack**" %}
### IPC Server
IPC is normally available for use in local environments where the node and the console
exist on the same machine. Geth creates a pipe in the computers local file system
(at `ipcpath`) that configures a connection between node and console. The `geth.ipc` file can
also be used by other processes on the same machine to interact with Geth.
IPC is normally available for use in local environments where the node and the console exist on the same machine. Geth creates a pipe in the computers local file system (at `ipcpath`) that configures a connection between node and console. The `geth.ipc` file can also be used by other processes on the same machine to interact with Geth.
On UNIX-based systems (Linux, OSX) the IPC is a UNIX domain socket. On Windows IPC is
provided using named pipes. The IPC server is enabled by default and has access to all
JSON-RPC namespaces.
On UNIX-based systems (Linux, OSX) the IPC is a UNIX domain socket. On Windows IPC is provided using named pipes. The IPC server is enabled by default and has access to all JSON-RPC namespaces.
The listening socket is placed into the data directory by default. On Linux and macOS,
the default location of the geth socket is
The listening socket is placed into the data directory by default. On Linux and macOS, the default location of the geth socket is
```sh
~/.ethereum/geth.ipc
@ -152,8 +105,7 @@ using the `--ipcdisable` flag.
## Choosing a transport protocol
The following table summarizes the relative strengths and weaknesses of each transport
protocol so that users can make informed decisions about which to use.
The following table summarizes the relative strengths and weaknesses of each transport protocol so that users can make informed decisions about which to use.
As a general rule IPC is most secure because it is limited to interactions on the
local machine and cannot be exposed to external traffic. It can also be used
to subscribe to events. HTTP is a familiar and idempotent transport that closes
connections between requests and can therefore have lower overall overheads if the number
of requests is fairly low. Websockets provides a continuous open channel that can enable
event subscriptions and streaming and handle large volumes of requests with smaller per-message
overheads.
As a general rule IPC is most secure because it is limited to interactions on the local machine and cannot be exposed to external traffic. It can also be used
to subscribe to events. HTTP is a familiar and idempotent transport that closes connections between requests and can therefore have lower overall overheads if the number of requests is fairly low. Websockets provides a continuous open channel that can enable event subscriptions and streaming and handle large volumes of requests with smaller per-message overheads.
## Summary
RPC requests to a Geth node can be made using three different transport protocols. The
protocols are enabled at startup using their respective flags. The right choice of transport
RPC requests to a Geth node can be made using three different transport protocols. The protocols are enabled at startup using their respective flags. The right choice of transport protocol depends on the specific use case.