# Code review guidelines Source: https://docs.parallaxprotocol.org/client/developers/client/code-review-guidelines The only way to get code into the Parallax client is to submit a pull request (PR). Those pull requests need to be reviewed by someone. This document is a guide that explains our expectations around PRs for both authors and reviewers. ## Terminology * The **author** of a pull request is the entity who wrote the diff and submitted it to GitHub. * The **team** consists of people with commit rights on the Parallax repository. * The **reviewer** is the person assigned to review the diff. The reviewer must be a team member. * The **code owner** is the person responsible for the subsystem being modified by the PR. ## The Process The first decision to make for any PR is whether it's worth including at all. This decision lies primarily with the code owner, but may be negotiated with team members. To make the decision we must understand what the PR is about. If there isn't enough description content or the diff is too large, request an explanation. Anyone can do this part. We expect that reviewers check the style and functionality of the PR, providing comments to the author using the GitHub review system. Reviewers should follow up with the PR until it is in good shape, then **approve** the PR. Approved PRs can be merged by any code owner. When communicating with authors, be polite and respectful. ### Code Style We expect `gofmt`ed code. For contributions of significant size, we expect authors to understand and use the guidelines in [Effective Go](https://golang.org/doc/effective_go.html). Authors should avoid common mistakes explained in the [Go Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments) page. ### Functional Checks For PRs that fix an issue, reviewers should try reproduce the issue and verify that the pull request actually fixes it. Authors can help with this by including a unit test that fails without (and passes with) the change. For PRs adding new features, reviewers should attempt to use the feature and comment on how it feels to use it. Example: if a PR adds a new command line flag, use the program with the flag and comment on whether the flag feels useful. We expect appropriate unit test coverage. Reviewers should verify that new code is covered by unit tests. ### CI Code submitted must pass all unit tests and static analysis ("lint") checks. We use Travis CI to test code on Linux, macOS and AppVeyor to test code on Microsoft Windows. For failing CI builds, the issue may not be related to the PR itself. Such failures are usually related to flakey tests. These failures can be ignored (authors don't need to fix unrelated issues), but please file a GH issue so the test gets fixed eventually. ### Commit Messages Commit messages on the master branch should follow the rule below. PR authors are not required to use any particular style because the message can be modified at merge time. Enforcing commit message style is the responsibility of the person merging the PR. The commit message style we use is similar to the style used by the Go project: The first line of the change description is conventionally a one-line summary of the change, prefixed by the primary affected Go package. It should complete the sentence "This change modifies Parallax to **\_**." The rest of the description elaborates and should provide context for the change and explain what it does. Template: ``` package/path: change XYZ Longer explanation of the change in the commit. You can use multiple sentences here. It's usually best to include content from the PR description in the final commit message. issue notices, e.g. "Fixes #42353". ``` ### Special Situations And How To Deal With Them Reviewers may find themselves in one of the situations below. Here's how to deal with them: * The author doesn't follow up: ping them after a while (i.e. after a few days). If there is no further response, close the PR or complete the work yourself. * Author insists on including refactoring changes alongside bug fix: We can tolerate small refactorings alongside any change. If you feel lost in the diff, ask the author to submit the refactoring as an independent PR, or at least as an independent commit in the same PR. * Author keeps rejecting feedback: reviewers have authority to reject any change for technical reasons. If you're unsure, ask the team for a second opinion. The PR can be closed if no consensus can be reached. *** *Adapted from [Code Review Guidelines](https://geth.ethereum.org/docs/developers/geth-developer/code-review-guidelines) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Disclosures Source: https://docs.parallaxprotocol.org/client/developers/client/disclosures In the software world, it is expected for security vulnerabilities to be immediately announced, thus giving operators an opportunity to take protective measure against attackers. Vulnerabilities typically take two forms: 1. Vulnerabilities that, if exploited, would harm the software operator. In the case of Parallax examples would be: * A bug that would allow remote reading or writing of OS files, or * Remote command execution, or * Bugs that would leak cryptographic keys 2. Vulnerabilities that, if exploited, would harm the Parallax mainnet. In the case of the Parallax client, examples would be: * Consensus vulnerabilities, which would cause a chain split, * Denial-of-service during block processing, whereby a malicious transaction could cause the network to crash. * Denial-of-service via p2p networking, whereby portions of the network could be made inaccessible due to crashes or resource consumption. In most cases so far, vulnerabilities in the Parallax client have been of the second type, where the health of the network is a concern, rather than individual node operators. For such issues, the Parallax reserves the right to silently patch and ship fixes in new releases. ### Why silent patches In the case of Parallax, it takes a lot of time (weeks, months) to get node operators to update even to a scheduled hard fork. If we were to highlight that a release contains important consensus or DoS fixes, there is always a risk of someone trying to beat node operators to the punch, and exploit the vulnerability. Delaying a potential attack sufficiently to make the majority of node operators immune may be worth the temporary loss of transparency. The primary goal for the Parallax team is the health of the Parallax network as a whole, and the decision whether or not to publish details about a serious vulnerability boils down to minimising the risk and/or impact of discovery and exploitation. At certain times, it's better to remain silent. This practice is also followed by other projects such as [Bitcoin](https://www.coindesk.com/the-latest-bitcoin-bug-was-so-bad-developers-kept-its-full-details-a-secret). ### Public transparency Our policy on public transparency is: * If we silently fix a vulnerability and include the fix in release `X`, then, * After 4-8 weeks, we will disclose that `X` contained a security-fix. * After an additional 4-8 weeks, we will publish the details about the vulnerability. We hope that this provides sufficient balance between transparency versus the need for secrecy, and aids node operators and downstream projects in keeping up to date with what versions to run on their infrastructure. In keeping with this policy, we have taken inspiration from [Solidity bug disclosure](https://solidity.readthedocs.io/en/develop/bugs.html) - see below. ### Disclosed vulnerabilities The Parallax client has a built-in command to check whether it is affected by any publically disclosed vulnerability, using the command `parallaxd version-check`. This command will fetch the latest json file (and the accompanying [signature-file](https://geth.ethereum.org/docs/vulnerabilities/vulnerabilities.json.minisig), and cross-check the data against its own version number. The JSON file of known vulnerabilities below is a list of objects, one for each vulnerability, with the following keys: * `name` * Unique name given to the vulnerability. * `uid` * Unique identifier of the vulnerability. Format `Parallax--` * `summary` * Short description of the vulnerability. * `description` * Detailed description of the vulnerability. * `links` * List of relevant URLs with more detailed information (optional). * `introduced` * The first published Parallax client version that contained the vulnerability (optional). * `fixed` * The first published Parallax client version that did not contain the vulnerability anymore. * `published` * The date at which the vulnerability became known publicly (optional). * `severity` * Severity of the vulnerability: `low`, `medium`, `high`, `critical`. * Takes into account the severity of impact and likelihood of exploitation. * `check` * This field contains a regular expression, which can be used against the reported `web3_clientVersion` of a node. If the check matches, the node is with a high likelihood affected by the vulnerability. * `CVE` * The assigned `CVE` identifier, if available (optional) ### What about GitHub security advisories We prefer to not rely on GitHub as the only/primary publishing protocol for security advisories, but we plan to use the GitHub-advisory process as a second channel for disseminating vulnerability-information. Advisories published via GitHub can be accessed [here](https://github.com/ParallaxProtocol/parallax/security/advisories?state=published). *** *Adapted from [Vulnerability disclosure](https://geth.ethereum.org/docs/developers/geth-developer/disclosures) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # DNS discovery setup guide Source: https://docs.parallaxprotocol.org/client/developers/client/dns-disc-guide This document explains how to set up an [EIP 1459](https://eips.ethereum.org/EIPS/eip-1459) node list using the devp2p developer tool. The focus of this guide is creating a public list for the Parallax mainnet and public testnets, but it may also be helpful for setting up DNS-based discovery for a private network. DNS-based node lists can serve as a fallback option when connectivity to the discovery DHT is unavailable. In this guide, node lists will be created by crawling the discovery DHT, then publishing the resulting node sets under chosen DNS names. ## Installing the devp2p command `cmd/devp2p` is a developer utility and is not included in the Parallax client distribution. You can install this command using go get: ```sh theme={null} go get github.com/ParallaxProtocol/parallax/v2/cmd/devp2p ``` To create a signing key, the `parallax-wallet` utility is needed. It ships with the release package and replaces the older standalone `parallaxkey` tool. ```sh theme={null} go get github.com/ParallaxProtocol/parallax/v2/cmd/parallax-wallet ``` ## Crawling the v4 DHT Our first step is to compile a list of all reachable nodes. The DHT crawler in cmd/devp2p is a batch process which runs for a set amount of time. You should schedule this command to run at a regular interval. To create a node list, run ```sh theme={null} devp2p discv4 crawl -timeout 30m all-nodes.json ``` This walks the DHT and stores the set of all found nodes in the `all-nodes.json` file. Subsequent runs of the same command will revalidate previously discovered node records, add newly-found nodes to the set, and remove nodes which are no longer alive. The quality of the node set improves with each run because the number of revalidations is tracked alongside each node in the set. ## Creating sub-lists through filtering Once `all-nodes.json` has been created and the set contains a sizeable number of nodes, useful sub-sets of nodes can be extracted using the `devp2p nodeset filter` command. This command takes a node set file as argument and applies filters given as command-line flags. To create a filtered node set, first create a new directory to hold the output set. You can use any directory name, though it's good practice to use the DNS domain name as the name of this directory. ```sh theme={null} mkdir mainnet.nodes.example.org ``` Then, to create the output set containing Parallax mainnet nodes only, run ```sh theme={null} devp2p nodeset filter all-nodes.json -eth-network mainnet > mainnet.nodes.example.org/nodes.json ``` The following filter flags are available: * `-eth-network` ( `mainnet` | `testnet` ) selects a Parallax network. * `-ip ` restricts nodes to the given IP range. * `-min-age ` restricts the result to nodes which have been live for the given duration. ## Creating DNS trees To turn a node list into a DNS node tree, the list needs to be signed. To do this, a key pair is required. To create the key file in the correct format, the `cmd/parallax-wallet` utility should be used. Choose a strong password to encrypt the key on disk! ```sh theme={null} parallax-wallet generate dnskey.json ``` Now use `devp2p dns sign` to update the signature of the node list. If the list's directory name differs from the name it will be published at, specify the DNS name using the `-domain` flag. This command will prompt for the key file password and update the tree signature. ```sh theme={null} devp2p dns sign mainnet.nodes.example.org dnskey.json ``` The resulting DNS tree metadata is stored in the `mainnet.nodes.example.org/enrtree-info.json` file. ## Publishing DNS trees Now that the tree is signed, it can be published to a DNS provider. `cmd/devp2p` currently supports publishing to CloudFlare DNS and Amazon Route53.TXT records can also be exported as a JSON file and published independently. To publish to CloudFlare, first create an API token in the management console. `cmd/devp2p` expects the API token in the `CLOUDFLARE_API_TOKEN` environment variable. Now use the following command to upload DNS TXT records via the CloudFlare API: ```sh theme={null} devp2p dns to-cloudflare mainnet.nodes.example.org ``` Note that this command uses the domain name specified during signing. Any existing records below this name will be erased by `cmd/devp2p`. ## Using DNS trees with the Parallax client Once a tree is available through a DNS name, the Parallax client can use it with the `--discovery.dns` command line flag. Node trees are referenced using the `enrtree://` URL scheme. The URL of the tree can be found in the `enrtree-info.json` file created by `devp2p dns sign`. Pass the URL as an argument to the flag in order to make use of the published tree. ```sh theme={null} parallaxd --discovery.dns "enrtree://AMBMWDM3J6UY3M32TMMROUNLX6Y3YTLVC3DC6HN2AVG5NHNSAXDW6@mainnet.nodes.example.org" ``` *** *Adapted from [DNS Discovery Setup Guide](https://geth.ethereum.org/docs/developers/geth-developer/dns-discovery-setup) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Developer guide Source: https://docs.parallaxprotocol.org/client/developers/client/guide This document is the entry point for developers who wish to work on the Parallax client. Developers are people who are interested to build, develop, debug, submit a bug report or pull request or otherwise contribute to the Parallax client source code. Please see [Contributing](/client/developers/contributing) for the Parallax client contribution guidelines. ## Building and Testing Developers should use a recent version of Go for building and testing. We use the go toolchain for development, which you can get from the [Go downloads page](https://golang.org/doc/install). The Parallax client is a Go module, and uses the [Go modules system](https://github.com/golang/go/wiki/Modules) to manage dependencies. Using `GOPATH` is not required to build the Parallax client. ### Building Executables Switch to the `parallax` repository root directory. All code can be built using the go tool, placing the resulting binary in `$GOPATH/bin`. ```sh theme={null} go install -v ./... ``` The Parallax executables can be built individually. To build just the Parallax client, use: ```sh theme={null} go install -v ./cmd/parallax ``` Cross compilation is not recommended, please build the Parallax client for the host architecture. ### Testing Testing a package: ```sh theme={null} go test -v ./node/fullnode ``` Running an individual test: ```sh theme={null} go test -v ./node/fullnode -run TestMethod ``` > [!NOTE] > > **Note**: here all tests with prefix *TestMethod* will be run, so if TestMethod and TestMethod1 both exist then both tests will run. Running benchmarks, eg.: ```sh theme={null} go test -v -bench . -run BenchmarkJoin ``` For more information, see the [go test flags](https://golang.org/cmd/go/#hdr-Testing_flags) documentation. ### Getting Stack Traces A stack trace provides a very detailed look into the current state of the Parallax node. It helps us to debug issues easier as it contains information about what is currently done by the node. Stack traces can be created by running `debug.stacks()` in the Parallax client console. If the node was started without the `console` command or with a script in the background, the following command can be used to dump the stack trace into a file. ```sh theme={null} parallaxd attach --exec "debug.stacks()" > stacktrace.txt ``` The Parallax client logs the location of the IPC endpoint on startup. It is typically under `/home/user/.parallax/parallax.ipc` or `/tmp/parallax.ipc`. `debug.stacks()` also takes an optional `filter` argument. Passing a package name or filepath to `filter` restricts the output to stack traces involving only that package/file. For example: ```sh theme={null} debug.stacks("enode") ``` returns data that looks like: ``` INFO [11-04|16:15:54.486] Expanded filter expression filter=enode expanded="`enode` in Value" goroutine 121 [chan receive, 3 minutes]: github.com/ParallaxProtocol/parallax/v2/p2p/enode.(*FairMix).nextFromAny(...) github.com/ParallaxProtocol/parallax/v2/p2p/enode/iter.go:241 github.com/ParallaxProtocol/parallax/v2/p2p/enode.(*FairMix).Next(0xc0008c6060) github.com/ParallaxProtocol/parallax/v2/p2p/enode/iter.go:215 +0x2c5 github.com/ParallaxProtocol/parallax/v2/p2p.(*dialScheduler).readNodes(0xc00021c2c0, {0x18149b0, 0xc0008c6060}) github.com/ParallaxProtocol/parallax/v2/p2p/dial.go:321 +0x9f created by github.com/ParallaxProtocol/parallax/v2/p2p.newDialScheduler github.com/ParallaxProtocol/parallax/v2/p2p/dial.go:179 +0x425 ``` and ```sh theme={null} debug.stacks("consolecmd.go") ``` returns data that looks like: ``` INFO [11-04|16:16:47.141] Expanded filter expression filter=consolecmd.go expanded="`consolecmd.go` in Value" goroutine 1 [chan receive]: github.com/ParallaxProtocol/parallax/v2/internal/jsre.(*JSRE).Do(0xc0004223c0, 0xc0003c00f0) github.com/ParallaxProtocol/parallax/v2/internal/jsre/jsre.go:230 +0xf4 github.com/ParallaxProtocol/parallax/v2/internal/jsre.(*JSRE).Evaluate(0xc00033eb60?, {0xc0013c00a0, 0x1e}, {0x180d720?, 0xc000010018}) github.com/ParallaxProtocol/parallax/v2/internal/jsre/jsre.go:289 +0xb3 github.com/ParallaxProtocol/parallax/v2/node/console.(*Console).Evaluate(0xc0005366e0, {0xc0013c00a0?, 0x0?}) github.com/ParallaxProtocol/parallax/v2/node/console/console.go:353 +0x6d github.com/ParallaxProtocol/parallax/v2/node/console.(*Console).Interactive(0xc0005366e0) github.com/ParallaxProtocol/parallax/v2/node/console/console.go:481 +0x691 main.localConsole(0xc00026d580?) github.com/ParallaxProtocol/parallax/v2/cmd/parallax/consolecmd.go:109 +0x348 github.com/ParallaxProtocol/parallax/v2/internal/flags.MigrateGlobalFlags.func2.1(0x20b52c0?) github.com/ParallaxProtocol/parallax/v2/internal/flags/helpers.go:91 +0x36 github.com/urfave/cli/v2.(*Command).Run(0x20b52c0, 0xc000313540) github.com/urfave/cli/v2@v2.17.2-0.20221006022127-8f469abc00aa/command.go:177 +0x719 github.com/urfave/cli/v2.(*App).RunContext(0xc0005501c0, {0x1816128?, 0xc000040110}, {0xc00003c180, 0x3, 0x3}) github.com/urfave/cli/v2@v2.17.2-0.20221006022127-8f469abc00aa/app.go:387 +0x1035 github.com/urfave/cli/v2.(*App).Run(...) github.com/urfave/cli/v2@v2.17.2-0.20221006022127-8f469abc00aa/app.go:252 main.main() github.com/ParallaxProtocol/parallax/v2/cmd/parallax/main.go:266 +0x47 goroutine 159 [chan receive, 4 minutes]: github.com/ParallaxProtocol/parallax/v2/node.(*Node).Wait(...) github.com/ParallaxProtocol/parallax/v2/node/node.go:529 main.localConsole.func1() github.com/ParallaxProtocol/parallax/v2/cmd/parallax/consolecmd.go:103 +0x2d created by main.localConsole github.com/ParallaxProtocol/parallax/v2/cmd/parallax/consolecmd.go:102 +0x32e ``` If the Parallax client is started with the `--pprof` option, a debugging HTTP server is made available on port 6060. Navigating to [http://localhost:6060/debug/pprof](http://localhost:6060/debug/pprof) displays the heap, running routines etc. By clicking "full goroutine stack dump" a trace can be generated that is useful for debugging. Note that if multiple instances of the Parallax client exist, port 6060 will only work for the first instance that was launched. To generate stacktraces for other instances, they should be started up with alternative pprof ports. Ensure `stderr` is being redirected to a logfile. ```sh theme={null} parallaxd -port=30300 -verbosity 5 --pprof --pprof.port 6060 2>> /tmp/00.glog parallaxd -port=30301 -verbosity 5 --pprof --pprof.port 6061 2>> /tmp/01.glog parallaxd -port=30302 -verbosity 5 --pprof --pprof.port 6062 2>> /tmp/02.glog ``` Alternatively to kill the clients (in case they hang or stalled syncing, etc) and have the stacktrace too, use the `-QUIT` signal with `kill`: ```sh theme={null} killall -QUIT parallaxd ``` This will dump stack traces for each instance to their respective log file. ## Where to go next Read the remaining pages in the Parallax client developer section, and get building! *** *Adapted from [Getting Started](https://geth.ethereum.org/docs/developers/geth-developer/dev-guide) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Contributing Source: https://docs.parallaxprotocol.org/client/developers/contributing # Developer mode Source: https://docs.parallaxprotocol.org/client/developers/dapp/developer-mode It is often convenient for developers to work in an environment where changes to client or application software can be deployed and tested rapidly and without putting real-world users or assets at risk. For this purpose, the Parallax client has a `--dev` flag that spins up the Parallax client in "developer mode". This creates a single-node Parallax test network with no connections to any external peers. It exists solely on the local machine. Starting the Parallax client in developer mode does the following: * Initialises the data directory with a testing genesis block * Sets max peers to 0 (meaning the Parallax client does not search for peers) * Turns off discovery by other nodes (meaning the node is invisible to other nodes) * Sets the gas price to 0 (no cost to send transactions) * Uses the Clique proof-of-authority consensus engine which allows blocks to be mined as-needed without excessive CPU and memory consumption * Uses on-demand block generation, producing blocks when transactions are waiting to be mined This configuration enables developers to experiment with the Parallax client's source code or develop new applications without having to sync to a pre-existing public network. Blocks are only mined when there are pending transactions. Developers can break things on this network without affecting other users. This page will demonstrate how to spin up a local Parallax testnet and a simple smart contract will be deployed to it using the Remix online integrated development environment (IDE). ## Prerequisites It is assumed that the user has a working the Parallax client installation (see [installation guide](/client/getting-started/installing-client)). It would also be helpful to have basic knowledge of the Parallax client and the Javascript console. See [Getting Started](/client/getting-started/introduction). Some basic knowledge of [Solidity](https://docs.soliditylang.org/) and [smart contract deployment](https://ethereum.org/en/developers/tutorials/deploying-your-first-smart-contract/) would be useful. ## Start the Parallax client in Dev Mode Starting the Parallax client in developer mode is as simple as providing the `--dev` flag. It is also possible to create a realistic block creation frequency by setting `--dev.period 5` instead of creating blocks only when transactions are pending. There are also additional configuration options required to follow this tutorial. Remix will be used to deploy a smart contract to the node which requires information to be exchanged externally to the Parallax client's own domain. To permit this, enable `http` and the `net` namespace must be enabled and the Remix URL must be provided to `--http.corsdomain`. For this tutorial some other namespaces will also be enabled. The full command is as follows: ```sh theme={null} parallaxd --dev --http --http.api eth,web3,net --http.corsdomain "http://remix.ethereum.org" ``` The terminal will display the following logs, confirming the Parallax client has started successfully in developer mode: ``` INFO [07-27|17:33:30.439] Starting Parallax in ephemeral dev mode... WARN [07-27|17:33:30.439] You are running Parallax in --dev mode. Please note the following: 1. This mode is only intended for fast, iterative development without assumptions on security or persistence. 2. The database is created in memory unless specified otherwise. Therefore, shutting down your computer or losing power will wipe your entire block data and chain state for your dev environment. 3. A random, pre-allocated developer account will be available and unlocked as eth.coinbase, which can be used for testing. The random dev account is temporary, stored on a ramdisk, and will be lost if your machine is restarted. 4. Mining is enabled by default. However, the client will only seal blocks if transactions are pending in the mempool. The miner's minimum accepted gas price is 1. 5. Networking is disabled; there is no listen-address, the maximum number of peers is set to 0, and discovery is disabled. INFO [07-27|17:33:30.439] Maximum peer count total=50 INFO [07-27|17:33:30.439] Set global gas cap cap=50,000,000 INFO [07-27|17:33:30.553] Using developer account address=0xa7F18aD76a5F7e1F0d5BfB2E36CeDd7eC5324b29 INFO [07-27|17:33:30.553] Allocated trie memory caches clean=154.00MiB dirty=256.00MiB INFO [07-27|17:33:30.553] Writing custom genesis block INFO [07-27|17:33:30.553] Persisted trie from memory database nodes=12 size=1.82KiB time="15.958µs" gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B INFO [07-27|17:33:30.553] Initialised chain configuration config="{ChainID: 1337 Homestead: 0 DAO: DAOSupport: false EIP150: 0 EIP155: 0 EIP158: 0 Byzantium: 0 Constantinople: 0 Petersburg: 0 Istanbul: 0, Muir Glacier: 0, Berlin: 0, London: 0, Arrow Glacier: , MergeFork: , Terminal TD: , Engine: clique}" INFO [07-27|17:33:30.553] Initialising Parallax Protocol name= versions=[] network=1337 dbversion= INFO [07-27|17:33:30.553] Loaded most recent local header number=0 hash=efac4a..3904e4 td=1 age=54y4mo5d INFO [07-27|17:33:30.553] Loaded most recent local full block number=0 hash=efac4a..3904e4 td=1 age=54y4mo5d INFO [07-27|17:33:30.553] Loaded most recent local fast block number=0 hash=efac4a..3904e4 td=1 age=54y4mo5d WARN [07-27|17:33:30.554] Failed to load snapshot, regenerating err="missing or corrupted snapshot" INFO [07-27|17:33:30.554] Rebuilding state snapshot INFO [07-27|17:33:30.554] Resuming state snapshot generation root=2a9a45..bb4bda accounts=0 slots=0 storage=0.00B dangling=0 elapsed="132.083µs" INFO [07-27|17:33:30.554] Gasprice oracle is ignoring threshold set threshold=2 WARN [07-27|17:33:30.554] Error reading unclean shutdown markers error="not found" ERROR[07-27|17:33:30.554] Failed to check db for legacy receipts err="this operation is not supported" INFO [07-27|17:33:30.554] Starting peer-to-peer node instance=Parallax/v1.0.0-stable-95cf8a9f/darwin-arm64/go1.20.6 WARN [07-27|17:33:30.554] P2P server will be useless, neither dialing nor listening INFO [07-27|17:33:30.554] Generated state snapshot accounts=10 slots=0 storage=412.00B dangling=0 elapsed="287.166µs" INFO [07-27|17:33:30.554] Stored checkpoint snapshot to disk number=0 hash=efac4a..3904e4 INFO [07-27|17:33:30.556] IPC endpoint opened url=/var/folders/j2/t2yw6xxs20sfnb1qlr4hc9br0000gn/T/parallax.ipc INFO [07-27|17:33:30.556] New local node record seq=1,690,490,010,555 id=7d74b1101188406b ip=127.0.0.1 udp=0 tcp=0 INFO [07-27|17:33:30.556] Started P2P networking self=enode://7f6c9244dc6ffeb0824085cf67a75bc0a6fafc8fc5490690c474ea3fefb8c97478fedd9aeb7163e3dbed865d0586f7e811af596660c0d9be6a5cb6956993233e@127.0.0.1:0 INFO [07-27|17:33:30.556] HTTP server started endpoint=127.0.0.1:8545 auth=false prefix= cors=http://remix.ethereum.org vhosts=localhost INFO [07-27|17:33:30.556] Transaction pool price threshold updated price=0 INFO [07-27|17:33:30.556] Updated mining threads threads=0 INFO [07-27|17:33:30.556] Transaction pool price threshold updated price=1 INFO [07-27|17:33:30.556] Coinbase automatically configured address=0xa7F18aD76a5F7e1F0d5BfB2E36CeDd7eC5324b29 WARN [07-27|17:33:30.556] Failed to get free disk space path= err="failed to call Statfs: no such file or directory" INFO [07-27|17:33:30.556] Commit new sealing work number=1 sealhash=48e711..4b52d3 uncles=0 txs=0 gas=0 fees=0 elapsed="31.916µs" WARN [07-27|17:33:30.556] Block sealing failed err="sealing paused while waiting for transactions" INFO [07-27|17:33:30.556] Commit new sealing work number=1 sealhash=48e711..4b52d3 uncles=0 txs=0 gas=0 fees=0 elapsed="91.75µs" ``` This terminal must be left running throughout the entire tutorial. In a second terminal, attach a Javascript console. By default the ipc file is saved in the datadir: ```sh theme={null} parallaxd attach /parallax.ipc ``` The Javascript terminal will open with the following welcome message: ``` Welcome to the Parallax JavaScript console! instance: Parallax/v1.0.0-stable-95cf8a9f/darwin-arm64/go1.20.6 coinbase: 0xa7f18ad76a5f7e1f0d5bfb2e36cedd7ec5324b29 at block: 0 (Wed Dec 31 1969 21:00:00 GMT-0300 (-03)) datadir: modules: admin:1.0 clique:1.0 debug:1.0 eth:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0 To exit, press ctrl-d or type exit > ``` For simplicity this tutorial uses the Parallax client's built-in account management. First, the existing accounts can be displayed using `eth.accounts`: ```sh theme={null} eth.accounts ``` An array containing a single address will be displayed in the terminal, despite no accounts having yet been explicitly created. This is the "coinbase" account. The coinbase address is the recipient of the total amount of Laxes created at the local network genesis. Querying the balance of the coinbase account will return a very large number. The coinbase account can be invoked as `eth.accounts[0]` or as `eth.coinbase`: ```javascript theme={null} eth.coinbase==eth.accounts[0] true ``` The following command can be used to query the balance. The return value is in units of Wei, which is divided by 1e18 to give units of Lax. This can be done explicitly or by calling the `web3.FromWei()` function: ```sh theme={null} eth.getBalance(eth.coinbase)/1e18 // or web3.fromWei(eth.getBalance(eth.coinbase)) ``` Using `web3.fromWei()` is less error prone because the correct multiplier is built in. These commands both return the following: ``` 1.157920892373162e+59 ``` A new account can be created using Clef. Some of the Laxes from the coinbase can then be transferred across to it. A new account is generated using the newaccount function on the command line: ```sh theme={null} clef newaccount --keystore ``` The terminal will display a request for a password, twice. Once provided, a new account will be created and its address printed to the terminal. The account creation is also logged in the Parallax client's terminal, including the location of the keyfile in the keystore. It is a good idea to back up the password somewhere at this point. If this were an account on a live network, intended to own assets of real-world value, it would be critical to back up the account password and the keystore in a secure manner. To reconfirm the account creation, running `eth.accounts` in the Javascript console should display an array containing two account addresses, one being the coinbase and the other being the newly generated address. The following command transfers 50 Laxes from the coinbase to the new account: ```sh theme={null} eth.sendTransaction({from: eth.coinbase, to: eth.accounts[1], value: web3.toWei(50, "ether")}) ``` A transaction hash will be returned to the console. This transaction hash will also be displayed in the logs in the Parallax client console, followed by logs confirming that a new block was mined (remember in the local development network blocks are mined when transactions are pending). The transaction details can be displayed in the Javascript console by passing the transaction hash to `eth.getTransaction()`: ```sh theme={null} eth.getTransaction("0x62044d2cab405388891ee6d53747817f34c0f00341cde548c0ce9834e9718f27") ``` The transaction details are displayed as follows: ```json theme={null} { accessList: [], blockHash: "0xdef68762539ebfb247e31d749acc26ab5df3163aabf9d450b6001c200d17da8a", blockNumber: 1, chainId: "0x539", from: "0x540dbaeb2390f2eb005f7a6dbf3436a0959197a9", gas: 21000, gasPrice: 875000001, hash: "0x2326887390dc04483d435a6303dc05bd2648086eab15f24d7dcdf8c26e8af4b8", input: "0x", maxFeePerGas: 2000000001, maxPriorityFeePerGas: 1, nonce: 0, r: "0x3f7b54f095b837ec13480eab5ac7de082465fc79f43b813cca051394dd028d5d", s: "0x167ef271ae8175239dccdd970db85e06a044d5039252d6232d0954d803bb4e3e", to: "0x43e3a14fb8c68caa7eea95a02693759de4513950", transactionIndex: 0, type: "0x2", v: "0x0", value: 50000000000000000000 } ``` Now that the user account is funded with some Laxes, a contract can be created ready to deploy to the Parallax client. ## A simple smart contract This tutorial will make use of a classic example smart contract, `Storage.sol`. This contract exposes two public functions, one to add a value to the contract storage and one to view the stored value. The contract, written in Solidity, is provided below: ```solidity theme={null} pragma solidity >=0.7.0; contract Storage{ uint256 number; function store(uint256 num) public{ number = num; } function retrieve() public view returns (uint256){ return number; } } ``` Solidity is a high-level language that makes code executable by the Parallax Virtual Machine (PVM) readable to humans. This means that there is an intermediate step between writing code in Solidity and deploying it to Parallax. This step is called "compilation" and it converts human-readable code into PVM-executable byte-code. This byte-code is then included in a transaction sent from the Parallax client during contract deployment. This can all be done directly from the Parallax client Javascript console; however this tutorial uses an online IDE called Remix to handle the compilation and deployment of the contract to the local Parallax client. ## Compile and deploy using Remix In a web browser, open [https://remix.ethereum.org](https://remix.ethereum.org/). This opens an online smart contract development environment. On the left-hand side of the screen there is a side-bar menu that toggles between several toolboxes that are displayed in a vertical panel. On the right hand side of the screen there is an editor and a terminal. This layout is similar to the default layout of many other IDEs such as [VSCode](https://code.visualstudio.com/). The contract defined in the previous section, `Storage.sol` is already available in the `Contracts` directory in Remix. It can be opened and reviewed in the editor. ![](https://geth.ethereum.org/images/docs/remix.png) The Solidity logo is present as an icon in the Remix side-bar. Clicking this icon opens the Solidity compiler wizard. This can be used to compile `Storage.sol` ready. With `Solidity.sol` open in the editor window, simply click the `Compile 1_Storage.sol` button. A green tick will appear next to the Solidity icon to confirm that the contract has compiled successfully. This means the contract bytecode is available. ![](https://geth.ethereum.org/images/docs/remix-compiler.png) Below the Solidity icon is a fourth icon that includes the Ethereum logo. Clicking this opens the Deploy menu. In this menu, Remix can be configured to connect to the local Parallax client. In the drop-down menu labelled `ENVIRONMENT`, select `Injected Web3`. This will open an information pop-up with instructions for configuring the Parallax client - these can be ignored as they were completed earlier in this tutorial. However, at the bottom of this pop-up is a box labelled `Web3 Provider Endpoint`. This should be set to Parallax client's 8545 port on `localhost (127.0.0.1:8545)`. Click OK. The `ACCOUNT` field should automatically populate with the address of the account created earlier using the Parallax client Javascript console. ![](https://geth.ethereum.org/images/docs/remix-deploy.png) To deploy `Storage.sol`, click DEPLOY. The following logs in the Parallax client terminal confirm that the contract was successfully deployed. ``` INFO [05-09|12:27:09.680] Setting new local account address=0x7Aa16266Ba3d309e3cb278B452b1A6307E52Fb62 INFO [05-09|12:27:09.680] Submitted contract creation hash=0xbf2d2d1c393a882ffb6c90e6d1713906fd799651ae683237223b897d4781c4f2 from=0x7Aa16266Ba3d309e3cb278B452b1A6307E52Fb62 nonce=1 contract=0x4aA11DdfD817dD70e9FF2A2bf9c0306e8EC450d3 value=0 INFO [05-09|12:27:09.681] Commit new sealing work number=2 sealhash=845a53..f22818 uncles=0 txs=1 gas=125,677 fees=0.0003141925 elapsed="335.991µs" INFO [05-09|12:27:09.681] Successfully sealed new block number=2 sealhash=845a53..f22818 hash=e927bc..f2c8ed elapsed="703.415µs" INFO [05-09|12:27:09.681] 🔨 mined potential block number=2 hash=e927bc..f2c8ed ``` ## Interact with contract using Remix The contract is now deployed on a local testnet version of the Parallax blockchain. This means there is a contract address that contains executable bytecode that can be invoked by sending transactions with instructions, also in bytecode, to that address. Again, this can all be achieved by constructing transactions directly in the Parallax client console or even by making external http requests using tools such as Curl. Here, Remix is used to retrieve the value, then the same action is taken using the Javascript console. After deploying the contract in Remix, the `Deployed Contracts` tab in the sidebar automatically populates with the public functions exposed by `Storage.sol`. To send a value to the contract storage, type a number in the field adjacent to the `store` button, then click the button. ![](https://geth.ethereum.org/images/docs/remix-func.png) In the Parallax client terminal, the following logs confirm that the transaction was successful (the actual values will vary from the example below): ``` INFO [05-09|13:41:58.644] Submitted transaction hash=0xfa3cd8df6841c5d3706d3bacfb881d2b985d0b55bdba440f1fdafa4ed5b5cc31 from=0x7Aa16266Ba3d309e3cb278B452b1A6307E52Fb62 nonce=2 recipient=0x4aA11DdfD817dD70e9FF2A2bf9c0306e8EC450d3 value=0 INFO [05-09|13:41:58.644] Commit new sealing work number=3 sealhash=5442e3..f49739 uncles=0 txs=1 gas=43724 fees=0.00010931 elapsed="334.446µs" INFO [05-09|13:41:58.645] Successfully sealed new block number=3 sealhash=5442e3..f49739 hash=c076c8..eeee77 elapsed="581.374µs" INFO [05-09|13:41:58.645] 🔨 mined potential block number=3 hash=c076c8..eeee77 ``` The transaction hash can be used to retrieve the transaction details using the Parallax client Javascript console, which will return the following information: ```json theme={null} { accessList: [], blockHash: "0xc076c88200618f4cbbfb4fe7c3eb8d93566724755acc6c4e9a355cc090eeee77", blockNumber: 3, chainId: "0x539", from: "0x7aa16266ba3d309e3cb278b452b1a6307e52fb62", gas: 43724, gasPrice: 3172359839, hash: "0xfa3cd8df6841c5d3706d3bacfb881d2b985d0b55bdba440f1fdafa4ed5b5cc31", input: "0x6057361d0000000000000000000000000000000000000000000000000000000000000038", maxFeePerGas: 4032048134, maxPriorityFeePerGas: 2500000000, nonce: 2, r: "0x859b88062715c5d66b9a188886ad51b68a1e4938d5932ce2dac874c104d2b26", s: "0x61ef6bc454d5e6a76c414f133aeb6321197a61e263a3e270a16bd4a65d94da55", to: "0x4aa11ddfd817dd70e9ff2a2bf9c0306e8ec450d3", transactionIndex: 0, type: "0x2", v: "0x1", value: 0 } ``` The from address is the account that sent the transaction, the `to` address is the deployment address of the contract. The value entered into Remix is now in storage at that contract address. This can be retrieved using Remix by calling the `retrieve` function - to do this simply click the retrieve button. Alternatively, it can be retrieved using `web3.getStorageAt` using the Parallax client Javascript console. The following command returns the value in the contract storage (replace the given address with the correct one displayed in the Parallax client logs). ```sh theme={null} web3.eth.getStorageAt("0x407d73d8a49eeb85d32cf465507dd71d507100c1", 0) ``` This returns a value that looks like the following: ``` "0x000000000000000000000000000000000000000000000000000000000000000038" ``` The returned value is a left-padded hexadecimal value. For example, the return value `0x000000000000000000000000000000000000000000000000000000000000000038` corresponds to a value of `56` entered as a uint256 to Remix. After converting from hexadecimal string to decimal number the returned value should be equal to that provided to Remix in the previous step. ## Reusing --datadir This tutorial used an ephemeral blockchain that is completely destroyed and started afresh during each dev-mode session. However, it is also possible to create persistent blockchain and account data that can be reused across multiple sessions. This is done by providing the `--datadir` flag and a directory name when starting the Parallax client in dev-mode. ```sh theme={null} parallaxd --datadir dev-chain --dev --http --http.api web3,eth,net --http.corsdomain "remix.ethereum.org" ``` ## Re-using accounts The Parallax client will fail to start in dev-mode if keys have been manually created or imported into the keystore in the `--datadir` directory. This is because the account cannot be automatically unlocked. To resolve this issue, the password defined when the account was created can be saved to a text file and its path passed to the `--password` flag on starting the client, for example if `password.txt` is saved in the top-level `parallax` directory: ```sh theme={null} parallaxd --datadir dev-chain --dev --http --http.api web3,eth,net --http.corsdomain "remix.ethereum.org" --password password.txt ``` **Note** that this is an edge-case that applies when both the `--datadir` and `--dev` flags are used and a key has been manually created or imported into the keystore. ## Summary This tutorial has demonstrated how to spin up a local developer network using the Parallax client. Having started this development network, a simple contract was deployed to the developer network. Then, Remix was connected to the local Parallax client and used to deploy and interact with a contract. Remix was used to add a value to the contract storage and then the value was retrieved using Remix and also using the lower level commands in the Javascript console. *** *Adapted from [Developer mode](https://geth.ethereum.org/docs/developers/dapp-developer/dev-mode) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Go account management Source: https://docs.parallaxprotocol.org/client/developers/dapp/go-account-management The Parallax client provides a simple, yet thorough accounts package that includes all the tools developers need to leverage all the security of the Parallax client's crypto implementation in a Go native application. The account management is done client side with all sensitive data held inside the application. This gives the user control over access permissions without relying on any third party. **Note: the Parallax client's built-in account management is convenient and straightforward to use, but best practice is to use the external tool *****Clef***** for key management.** ## Encrypted keystores Access keys to Parallax accounts should never be stored in plain-text. Instead, they should be stored encrypted so that even if the mobile device is accessed by a malicious third party the keys are still hidden under an additional layer of security. The Parallax client provides a keystore that enables developers to store keys securely. The Parallax client keystore uses [Scrypt](https://pkg.go.dev/golang.org/x/crypto/scrypt) to store keys that are encoded using the [secp256k1](https://www.secg.org/sec2-v2.pdf) elliptic curve. Accounts are stored on disk in the [Web3 Secret Storage](https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition) format. Developers should be aware of these implementation details but are not required to deeply understand the cryptographic primitives in order to use the keystore. One thing that should be understood, though, is that the cryptographic primitives underpinning the keystore can operate in light or standard mode. Light mode is computationally cheaper, while standard mode has extra security. Light mode is appropriate for mobile devices, but developers should be aware that there is a security trade-off. * standard needs 256MB memory and 1 second processing on a modern CPU to access a key * light needs 4MB memory and 100 millisecond processing on a modern CPU to access a key The encrypted keystore is implemented by the [wallet.Manager](https://godoc.org/github.com/ParallaxProtocol/parallax/v2/wallet#Manager) struct from the [wallet](https://godoc.org/github.com/ParallaxProtocol/parallax/v2/wallet) package, which also contains the configuration constants for the *standard* or *light* security modes described above. Hence client side account management simply requires importing the wallet package into the application code. ```go theme={null} import "github.com/ParallaxProtocol/parallax/v2/wallet" import "github.com/ParallaxProtocol/parallax/v2/wallet/keystore" import "github.com/ParallaxProtocol/parallax/v2/util" ``` Afterwards a new encrypted account manager can be created via: ```go theme={null} ks := keystore.NewKeyStore("/path/to/keystore", keystore.StandardScryptN, keystore.StandardScryptP) am := wallet.NewManager(&wallet.Config{InsecureUnlockAllowed: false}, ks) ``` The path to the keystore folder needs to be a location that is writable by the local user but non-readable for other system users, such as inside the user's home directory. The last two arguments of [keystore.NewKeyStore](https://godoc.org/github.com/ParallaxProtocol/parallax/v2/wallet/keystore#NewKeyStore) are the crypto parameters defining how resource-intensive the keystore encryption should be. The options are [wallet.StandardScryptN, wallet.StandardScryptP, wallet.LightScryptN, wallet.LightScryptP](https://godoc.org/github.com/ParallaxProtocol/parallax/v2/wallet#pkg-constants) or custom values (requiring understanding of the underlying cryptography). The *standard* version is recommended. ## Account lifecycle Once an encrypted keystore for Parallax accounts exists it, it can be used to manage accounts for the entire account lifecycle requirements of a Go native application. This includes the basic functionality of creating new accounts and deleting existing ones as well as updating access credentials, exporting existing accounts, and importing them on other devices. Although the keystore defines the encryption strength it uses to store accounts, there is no global master password that can grant access to all of them. Rather each account is maintained individually, and stored on disk in its [encrypted format](https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition) individually, ensuring a much cleaner and stricter separation of credentials. This individuality means that any operation requiring access to an account will need to provide the necessary authentication credentials for that particular account in the form of a passphrase: * When creating a new account, the caller must supply a passphrase to encrypt the account with. This passphrase will be required for any subsequent access, the lack of which will forever forfeit using the newly created account. * When deleting an existing account, the caller must supply a passphrase to verify ownership of the account. This isn't cryptographically necessary, rather a protective measure against accidental loss of accounts. * When updating an existing account, the caller must supply both current and new passphrases. After completing the operation, the account will not be accessible via the old passphrase anymore. * When exporting an existing account, the caller must supply both the current passphrase to decrypt the account, as well as an export passphrase to re-encrypt it with before returning the key-file to the user. This is required to allow moving accounts between machines and applications without sharing original credentials. * When importing a new account, the caller must supply both the encryption passphrase of the key-file being imported, as well as a new passphrase with which to store the account. This is required to allow storing account with different credentials than used for moving them around. ***Please note, there are no recovery mechanisms for lost passphrases. The cryptographic properties of the encrypted keystore (using the provided parameters) guarantee that account credentials cannot be brute forced in any meaningful time.*** A Parallax account is implemented by the [wallet.Account](https://godoc.org/github.com/ParallaxProtocol/parallax/v2/wallet#Account) struct from the Parallax client [wallet](https://pkg.go.dev/github.com/ParallaxProtocol/parallax/v2/wallet) package. Assuming an instance of an [wallet.Manager](https://godoc.org/github.com/ParallaxProtocol/parallax/v2/wallet#Manager) called am exists, all of the described lifecycle operations can be executed with a handful of function calls (error handling omitted). ```go theme={null} // Create a new account with the specified encryption passphrase. newAcc, _ := ks.NewAccount("Creation password") fmt.Println(newAcc) // Export the newly created account with a different passphrase. The returned // data from this method invocation is a JSON encoded, encrypted key-file. jsonAcc, _ := ks.Export(newAcc, "Creation password", "Export password") // Update the passphrase on the account created above inside the local keystore. _ = ks.Update(newAcc, "Creation password", "Update password") // Delete the account updated above from the local keystore. _ = ks.Delete(newAcc, "Update password") // Import back the account we've exported (and then deleted) above with yet // again a fresh passphrase. impAcc, _ := ks.Import(jsonAcc, "Export password", "Import password") ``` *Although instances of* [*wallet.Account*](https://godoc.org/github.com/ParallaxProtocol/parallax/v2/wallet#Account) *can be used to access various information about specific Parallax accounts, they do not contain any sensitive data (such as passphrases or private keys), rather they act solely as identifiers for client code and the keystore.* ## Signing authorization Account objects do not hold the sensitive private keys of the associated Parallax accounts. Account objects are placeholders that identify the cryptographic keys. All operations that require authorization (e.g. transaction signing) are performed by the account manager after granting it access to the private keys. There are a few different ways to authorize the account manager to execute signing operations, each having its advantages and drawbacks. Since the different methods have wildly different security guarantees, it is essential to be clear on how each works: * **Single authorization**: The simplest way to sign a transaction via the account manager is to provide the passphrase of the account every time something needs to be signed, which will ephemerally decrypt the private key, execute the signing operation and immediately throw away the decrypted key. The drawbacks are that the passphrase needs to be queried from the user every time, which can become annoying if done frequently or the application needs to keep the passphrase in memory, which can have security consequences if not done properly. Depending on the keystore's configured strength, constantly decrypting keys can result in non-negligible resource requirements. * **Multiple authorizations**: A more complex way of signing transactions via the account manager is to unlock the account via its passphrase once, and allow the account manager to cache the decrypted private key, enabling all subsequent signing requests to complete without the passphrase. The lifetime of the cached private key may be managed manually (by explicitly locking the account back up) or automatically (by providing a timeout during unlock). This mechanism is useful for scenarios where the user may need to sign many transactions or the application would need to do so without requiring user input. The crucial aspect to remember is that **anyone with access to the account manager can sign transactions while a particular account is unlocked** (e.g. application running untrusted code). Assuming an instance of an [wallet.Manager](https://godoc.org/github.com/ParallaxProtocol/parallax/v2/wallet#Manager) called am exists, a new account can be created to sign transactions using [NewAccount](https://godoc.org/github.com/ParallaxProtocol/parallax/v2/wallet#Manager.NewAccount). Creating transactions is out of scope for this page so instead a random [util.Hash](https://godoc.org/github.com/ParallaxProtocol/parallax/v2/util#Hash) will be signed instead. For information on creating transactions in Go native applications see the [Go API page](/client/developers/dapp/go-api). ```go theme={null} // Create a new account to sign transactions with signer, _ := ks.NewAccount("Signer password") txHash := util.HexToHash("0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef") ``` With the boilerplate out of the way, the transaction can be signed using the authorization mechanisms described above: ```go theme={null} // Sign a transaction with a single authorization signature, _ := ks.SignHashWithPassphrase(signer, "Signer password", txHash.Bytes()) // Sign a transaction with multiple manually cancelled authorizations _ = ks.Unlock(signer, "Signer password") signature, _ = ks.SignHash(signer, txHash.Bytes()) _ = ks.Lock(signer.Address) // Sign a transaction with multiple automatically cancelled authorizations _ = ks.TimedUnlock(signer, "Signer password", time.Second) signature, _ = ks.SignHash(signer, txHash.Bytes()) ``` Note that [SignWithPassphrase](https://godoc.org/github.com/ParallaxProtocol/parallax/v2/wallet#Manager.SignWithPassphrase) takes an [wallet.Account](https://godoc.org/github.com/ParallaxProtocol/parallax/v2/wallet#Account) as the signer, whereas [Sign](https://godoc.org/github.com/ParallaxProtocol/parallax/v2/wallet#Manager.Sign) takes only a [util.Address](https://godoc.org/github.com/ParallaxProtocol/parallax/v2/util#Address). The reason for this is that an [wallet.Account](https://godoc.org/github.com/ParallaxProtocol/parallax/v2/wallet#Account) object may also contain a custom key-path, allowing [SignWithPassphrase](https://godoc.org/github.com/ParallaxProtocol/parallax/v2/wallet#Manager.SignWithPassphrase) to sign using accounts outside of the keystore; however [Sign](https://godoc.org/github.com/ParallaxProtocol/parallax/v2/wallet#Manager.Sign) relies on accounts already unlocked within the keystore, so it cannot specify custom paths. ## Summary Account management is a fundamental pillar of Parallax development. The Parallax client's Go API provides the tools required to integrate best-practice account security into Go native applications using a simple set of Go functions. *** *Adapted from [Go Account Management](https://geth.ethereum.org/docs/developers/dapp-developer/native-accounts) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Go API Source: https://docs.parallaxprotocol.org/client/developers/dapp/go-api ## Overview The Parallax client reusable Go libraries focus on three main usage areas: * Simplified client side account management * Remote node interfacing via different transports * Contract interactions through auto-generated bindings The libraries are updated synchronously with the Parallax client GitHub repository. The Go libraries can be viewed in full at [Go Packages](https://pkg.go.dev/github.com/ParallaxProtocol/parallax/v2#section-directories). ## Go packages The `parallax` library is distributed as a collection of standard Go packages straight from Parallax's GitHub repository. The packages can be used directly via the official Go toolkit, without needing any third party tools. The canonical import path for the Parallax client is `github.com/ParallaxProtocol/parallax/v2`, with all packages residing underneath. Although there are [lots of them](https://pkg.go.dev/github.com/ParallaxProtocol/parallax/v2/#section-directories) most developers will only care about a limited subset. The `/v2` suffix was added in v2.1.0; v2.0.x releases use the path `github.com/ParallaxProtocol/parallax`. The suffix is the module's major version: it changes only when the exported Go API breaks, and a `/v3` module would be able to coexist with this one in the same build. See [Versioning](/client/fundamentals/versioning) for what each digit of a release means. All the Parallax client packages can be downloaded using: ```sh theme={null} go get -d github.com/ParallaxProtocol/parallax/v2/... ``` More Go API support for dapp developers can be found on the [Go Contract Bindings](/client/developers/dapp/go-contract-bindings) and [Go Account Management](/client/developers/dapp/go-account-management) pages. ## Tutorial This section includes some basic usage examples for the `prlclient` and `prlxclient` packages available as part of the Go API. The `prlclient` package provides a client that implements the full Parallax JSON-RPC API, whereas `prlxclient` offers the Parallax client specific API. ### Instantiating a client The client is an instance of the Client struct which has associated functions that wrap requests to the Parallax client RPC API endpoints. A client is instantiated by passing a raw url or path to an ipc file to the client's Dial function. In the following code snippet the path to the ipc file for a local Parallax client is provided to client.Dial(). ```go theme={null} // create instance of prlclient and assign to cl cl, err := client.Dial("/tmp/parallax.ipc") if err != nil { panic(err) } _ = cl ``` ### Interacting with the client The client can now be used to handle requests to the Parallax client using the full JSON-RPC API. For example, the function `BlockNumber()` wraps a call to the `eth_blockNumber` endpoint. The function `SendTransaction` wraps a call to `eth_sendTransaction`. The full list of client methods can be found [here](https://pkg.go.dev/github.com/ParallaxProtocol/parallax/v2/rpc/client#Client). Frequently, the functions take an instance of the Context type as their leading argument. This defines context about requests sent from the application such as deadlines, cancellation signals etc. More information on this can be found in the [Go documentation](https://pkg.go.dev/golang.org/x/net/context). An empty context instance can be created using `Context.Background()`. ### Querying client for data A simple starting point is to fetch the chain ID from the client. This e.g. is needed when signing a transaction as is to be seen in the next section. ```go theme={null} chainid, err := cl.ChainID(context.Background()) if err != nil { return err } ``` Unlike `ChainID`, many functions require arguments other than context. The Go API takes in and returns high-level types which are used in the Parallax client internals as well to simplify programming and remove the need for knowing how data needs to be formatted exactly as per the JSON-RPC API spec. For example to find out the nonce for an account at a given block the address needs to be provided as a `util.Address` type and the block number as a `*big.Int`: ```go theme={null} addr := util.HexToAddress("0xb02A2EdA1b317FBd16760128836B0Ac59B560e9D") nonce, err := cl.NonceAt(context.Background(), addr, big.NewInt(14000000)) ``` ### Querying past events Contracts emit events during execution which can be queried from the client. The parameters for the event one is interested in have to be filled out in the `parallax.FilterQuery` object. This includes which event topics are of interest, from which contracts and during which range of blocks. The example below queries Transfer events of all ERC-20 tokens for the last 10 blocks: ```go theme={null} blockNumber, err := cl.BlockNumber(context.Background()) if err != nil { fmt.Println("Failed to retrieve block number:", err) return } blockNumberBig := big.NewInt(int64(blockNumber)) eventSignatureBytes := []byte("Transfer(address,address,uint256)") eventSignaturehash := crypto.Keccak256Hash(eventSignatureBytes) q := parallax.FilterQuery{ FromBlock: new(big.Int).Sub(blockNumberBig, big.NewInt(10)), ToBlock: blockNumberBig, Topics: [][]util.Hash{ {eventSignaturehash}, }, } logs, err := cl.FilterLogs(context.Background(), q) if err != nil { return err } ``` ### Sending a transaction Sending a transaction is achieved using the `SendTransaction()` function. `SendTransaction` takes an instance of `context.Context` as its leading argument and a signed transaction as its second argument. The signed transaction must be generated in advance. Building the signed transaction is a multi-stage process that requires first generating a key pair if none exists already, retrieving some chain data and defining sender and recipient addresses. Then these data can be collected into a transaction object and signed. The resulting signed transaction can then be passed to `SendTransaction`. The example below assumes the following key pair has already been generated: ```go theme={null} // SK and ADDR are the secret key and sender address SK = "0xaf5ead4413ff4b78bc94191a2926ae9ccbec86ce099d65aaf469e9eb1a0fa87f" ADDR = "0x6177843db3138ae69679A54b95cf345ED759450d" ``` The secret key and address can be used to send a transaction. In the example below `1 Lax` is sent from the address `ADDR` to an arbitrary recipient. ```go theme={null} import ( "context" "math/big" "github.com/ParallaxProtocol/parallax/v2/util" "github.com/ParallaxProtocol/parallax/v2/primitives/types" "github.com/ParallaxProtocol/parallax/v2/crypto" "github.com/ParallaxProtocol/parallax/v2/rpc/client" "github.com/ParallaxProtocol/parallax/v2/kernel/chainparams" ) // sendTransaction sends a transaction with 1 Lax to a specified address. func sendTransaction(cl *client.Client) error { var ( sk = crypto.ToECDSAUnsafe(util.FromHex(SK)) to = util.HexToAddress("0xb02A2EdA1b317FBd16760128836B0Ac59B560e9D") value = new(big.Int).Mul(big.NewInt(1), big.NewInt(chainparams.Ether)) sender = util.HexToAddress(ADDR) gasLimit = uint64(21000) ) // Retrieve the chainid (needed for signer) chainid, err := cl.ChainID(context.Background()) if err != nil { return err } // Retrieve the pending nonce nonce, err := cl.PendingNonceAt(context.Background(), sender) if err != nil { return err } // Get suggested gas price tipCap, _ := cl.SuggestGasTipCap(context.Background()) feeCap, _ := cl.SuggestGasPrice(context.Background()) // Create a new transaction tx := types.NewTx( &types.DynamicFeeTx{ ChainID: chainid, Nonce: nonce, GasTipCap: tipCap, GasFeeCap: feeCap, Gas: gasLimit, To: &to, Value: value, Data: nil, }) // Sign the transaction using our keys signedTx, _ := types.SignTx(tx, types.NewLondonSigner(chainid), sk) // Send the transaction to our node return cl.SendTransaction(context.Background(), signedTx) } ``` ### prlxclient An instance of `prlxclient` can be used in exactly the same way as `prlclient`. However, `prlxclient` includes the Parallax client specific API methods. These additional methods are: ```sh theme={null} CallContract() CreateAccessList() GCStats() GetNodeInfo() GetProof() MemStats() SetHead() SubscribePendingTransactions() ``` *Note that both `prlclient` and `prlxclient` have a `CallContract()` function - the difference is that the `prlxclient` version includes an overrides argument.* Details relating to these endpoints can be found at [pkg.go.dev](https://pkg.go.dev/github.com/ParallaxProtocol/parallax/v2/rpc/client) or the Parallax client [GitHub](https://github.com/ParallaxProtocol/parallax/tree/main/rpc/client). ## Summary There are a wide variety of Go APIs available for dapp developers that abstract away the complexity of interacting with Parallax using a set of composable, reusable functions provided by the Parallax client. *** *Adapted from [Go API](https://geth.ethereum.org/docs/developers/dapp-developer/native) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Go contract bindings Source: https://docs.parallaxprotocol.org/client/developers/dapp/go-contract-bindings This page introduces the concept of server-side native dapps. The Parallax client provides the tools required to generate [Go](https://github.com/golang/go/wiki#getting-started-with-go) language bindings to any Parallax contract that is compile-time type safe, highly performant and can be generated completely automatically from a compiled contract. Interacting with a contract on the Parallax blockchain from Go is already possible via the RPC interfaces exposed by Parallax clients. However, writing the boilerplate code that translates Go language constructs into RPC calls and back is time consuming and brittle - implementation bugs can only be detected during runtime and it's almost impossible to evolve a contract as even a tiny change in Solidity is awkward to port over to Go. Therefore, the Parallax client provides tools for easily converting contract code into Go code that can be used directly in Go applications. This page provides an introduction to generating Go contract bindings and using them in a simple Go application. ## Prerequisites This page is fairly beginner-friendly and designed for people starting out with writing Go native dapps. The core concepts will be introduced gradually as a developer would encounter them. However, some basic familiarity with [Ethereum](https://ethereum.org), [Solidity](https://docs.soliditylang.org/en/v0.8.15/) and [Go](https://go.dev/) is assumed. ## What is an ABI? Parallax smart contracts have a schema that defines its functions and return types in the form of a JSON file. This JSON file is known as an *Application Binary Interface*, or ABI. The ABI acts as a specification for precisely how to encode data sent to a contract and how to decode the data the contract sends back. The ABI is the only essential piece of information required to generate Go bindings. Go developers can then use the bindings to interact with the contract from their Go application without having to deal directly with data encoding and decoding. An ABI is generated when a contract is compiled. ## Abigen: Go binding generator The Parallax client includes a source code generator called `abigen` that can convert Parallax ABI definitions into easy to use, type-safe Go packages. With a valid Go development environment set up and the Parallax repository checked out correctly, abigen can be built as follows: ```sh theme={null} cd $GOPATH/src/github.com/ParallaxProtocol/parallax go build ./cmd/abigen ``` ### Generating the bindings To demonstrate the binding generator a contract is required. The contract `Storage.sol` implements two very simple functions: `store` updates a user-defined `uint256` to the contract's storage, and `retrieve` displays the value stored in the contract to the user. The Solidity code is as follows: ```solidity theme={null} // SPDX-License-Identifier: GPL-3.0 pragma solidity >0.7.0 < 0.9.0; /** * @title Storage * @dev store or retrieve variable value */ contract Storage { uint256 value; function store(uint256 number) public{ value = number; } function retrieve() public view returns (uint256){ return value; } } ``` This contract can be pasted into a text file and saved as `Storage.sol`. The following code snippet shows how an ABI can be generated for `Storage.sol` using the Solidity compiler solc. ```sh theme={null} solc --abi Storage.sol -o build ``` The ABI can also be generated in other ways such as using the compile commands in development frameworks such as [Truffle](https://trufflesuite.com/docs/truffle/), [Hardhat](https://hardhat.org/) and [Brownie](https://eth-brownie.readthedocs.io/en/stable/) or in the online IDE [Remix](https://remix.ethereum.org/). The ABI for `Storage.sol` (`Storage.abi`) looks as follows: ```json theme={null} [ { "inputs": [], "name": "retrieve", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "uint256", "name": "number", "type": "uint256" }], "name": "store", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ] ``` The contract binding can then be generated by passing the ABI to abigen as follows: ```sh theme={null} abigen --abi Storage.abi --pkg main --type Storage --out Storage.go ``` Where the flags are: * `--abi`: Mandatory path to the contract ABI to bind to * `--pkg`: Mandatory Go package name to place the Go code into * `--type`: Optional Go type name to assign to the binding struct * `--out`: Optional output path for the generated Go source file (not set = stdout) This will generate a type-safe Go binding for the Storage contract. The generated code will look something like the snippet below, the full version of which can be viewed [here](https://gist.github.com/jmcook1186/a78e59d203bb54b06e1b81f2cda79d93). ```go theme={null} // Code generated - DO NOT EDIT. // This file is a generated binding and any manual changes will be lost. package main import ( "errors" "math/big" "strings" parallax "github.com/ParallaxProtocol/parallax/v2" "github.com/ParallaxProtocol/parallax/v2/script/abi" "github.com/ParallaxProtocol/parallax/v2/script/abi/bind" "github.com/ParallaxProtocol/parallax/v2/util" "github.com/ParallaxProtocol/parallax/v2/primitives/types" "github.com/ParallaxProtocol/parallax/v2/support/event" ) // Reference imports to suppress errors if they are not otherwise used. var ( _ = errors.New _ = big.NewInt _ = strings.NewReader _ = parallax.ErrNotFound _ = bind.Bind _ = util.Big1 _ = types.BloomLookup _ = event.NewSubscription ) // StorageMetaData contains all metadata concerning the Storage contract. var StorageMetaData = &bind.MetaData{ ABI: "[{\"inputs\":[],\"name\":\"retrieve\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"number\",\"type\":\"uint256\"}],\"name\":\"store\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", } // StorageABI is the input ABI used to generate the binding from. // Deprecated: Use StorageMetaData.ABI instead. var StorageABI = StorageMetaData.ABI // Storage is an auto generated Go binding around a Parallax contract. type Storage struct { StorageCaller // Read-only binding to the contract StorageTransactor // Write-only binding to the contract StorageFilterer // Log filterer for contract events } ... ``` `Storage.go` contains all the bindings required to interact with `Storage.sol` from a Go application. However, this isn't very useful unless the contract is actually deployed on Parallax mainnet or one of Parallax's testnets. The following sections will demonstrate how to deploy the contract to the Parallax testnet and interact with it using the Go bindings. ### Deploying contracts to Parallax In the previous section, the contract ABI was sufficient for generating the contract bindings from its ABI. However, deploying the contract requires some additional information in the form of the compiled bytecode. The bytecode is obtained by running the compiler again but this passing the `--bin` flag, e.g. ```sh theme={null} solc --bin Storage.sol -o Storage.bin ``` Then `abigen` can be run again, this time passing `Storage.bin`: ```sh theme={null} abigen --abi Storage.abi --pkg main --type Storage --out Storage.go --bin Storage.bin ``` This will generate something similar to the bindings generated in the previous section. However, an additional `DeployStorage` function has been injected: ```go theme={null} // DeployStorage deploys a new Parallax contract, binding an instance of Storage to it. func DeployStorage(auth *bind.TransactOpts, backend bind.ContractBackend) (util.Address, *types.Transaction, *Storage, error) { parsed, err := StorageMetaData.GetAbi() if err != nil { return util.Address{}, nil, nil, err } if parsed == nil { return util.Address{}, nil, nil, errors.New("GetABI returned nil") } address, tx, contract, err := bind.DeployContract(auth, *parsed, util.FromHex(StorageBin), backend) if err != nil { return util.Address{}, nil, nil, err } return address, tx, &Storage{StorageCaller: StorageCaller{contract: contract}, StorageTransactor: StorageTransactor{contract: contract}, StorageFilterer: StorageFilterer{contract: contract}}, nil } ``` View the full file [here](https://gist.github.com/jmcook1186/91124cfcbc7f22dcd3bb4f148d2868a8). The new `DeployStorage()` function can be used to deploy the contract to the Parallax testnet from a Go application. To do this requires incorporating the bindings into a Go application that also handles account management, authorization and Parallax backend to deploy the contract through. Specifically, this requires: 1. A running Parallax client connected to the Parallax testnet 2. An account in the keystore prefunded with enough Laxes to cover gas costs for deploying and interacting with the contract Assuming these prerequisites exist, a new `prlclient` can be instantiated with the local Parallax node's ipc file, providing access to the testnet from the Go application. The key can be instantiated as a variable in the application by copying the JSON object from the keyfile in the keystore. Putting it all together would result in: ```go theme={null} package main import ( "fmt" "log" "math/big" "strings" "time" "github.com/ParallaxProtocol/parallax/v2/script/abi/bind" "github.com/ParallaxProtocol/parallax/v2/rpc/client" ) const key = `<>` func main() { // Create an IPC based RPC connection to a remote node and an authorized transactor conn, err := client.Dial("/home/parallax/testnet/parallax.ipc") if err != nil { log.Fatalf("Failed to connect to the Parallax client: %v", err) } auth, err := bind.NewTransactor(strings.NewReader(key), "<>") if err != nil { log.Fatalf("Failed to create authorized transactor: %v", err) } // Deploy the contract passing the newly created `auth` and `conn` vars address, tx, instance, err := DeployStorage(auth, conn), new(big.Int), "Storage contract in Go!", 0, "Go!") if err != nil { log.Fatalf("Failed to deploy new storage contract: %v", err) } fmt.Printf("Contract pending deploy: 0x%x\n", address) fmt.Printf("Transaction waiting to be mined: 0x%x\n\n", tx.Hash()) time.Sleep(250 * time.Millisecond) // Allow it to be processed by the local node :P // function call on `instance`. Retrieves pending name name, err := instance.Name(&bind.CallOpts{Pending: true}) if err != nil { log.Fatalf("Failed to retrieve pending name: %v", err) } fmt.Println("Pending name:", name) } ``` Running this code requests the creation of a brand new `Storage` contract on the Testnet blockchain. The contract functions can be called while the contract is waiting to be included in a block. ```sh theme={null} Contract pending deploy: 0x46506d900559ad005feb4645dcbb2dbbf65e19cc Transaction waiting to be mined: 0x6a81231874edd2461879b7280ddde1a857162a744e3658ca7ec276984802183b Pending name: Storage contract in Go! ``` Once the contract deployment has been included in a validated block, the contract exists permanently at its deployment address and can now be interacted with from other applications without ever needing to be redeployed. Note that `DeployStorage` returns four variables: * `address`: the deployment address of the contract * `tx`: the transaction hash that can be queried using the Parallax client * `instance`: an instance of the deployed contract whose functions can be called in the Go application * `err`: a variable that handles errors in case of a deployment failure ### Accessing a Parallax contract To interact with a contract already deployed on the blockchain, the deployment address is required and a backend through which to access Parallax must be defined. The binding generator provides an RPC backend out-of-the-box that can be used to attach to an existing Parallax node via IPC, HTTP or WebSockets. As in the previous section, a Parallax node running on the Parallax testnet and an account with some test Laxes to cover gas is required. The `Storage.sol` deployment address is also needed. Again, an instance of `prlclient` can be created, passing the path to the Parallax client's ipc file. In the example below this backend is assigned to the variable conn. ```go theme={null} // Create an IPC based RPC connection to a remote node // NOTE update the path to the ipc file! conn, err := client.Dial("/home/parallax/testnet/parallax.ipc") if err != nil { log.Fatalf("Failed to connect to the Parallax client: %v", err) } ``` The functions available for interacting with the `Storage` contract are defined in `Storage.go`. To create a new instance of the contract in a Go application, the `NewStorage()` function can be used. The function is defined in `Storage.go` as follows: ```go theme={null} // NewStorage creates a new instance of Storage, bound to a specific deployed contract. func NewStorage(address util.Address, backend bind.ContractBackend) (*Storage, error) { contract, err := bindStorage(address, backend, backend, backend) if err != nil { return nil, err } return &Storage{StorageCaller: StorageCaller{contract: contract}, StorageTransactor: StorageTransactor{contract: contract}, StorageFilterer: StorageFilterer{contract: contract}}, nil } ``` `NewStorage()` takes two arguments: the deployment address and a backend (`conn`) and returns an instance of the deployed contract. In the example below, the instance is assigned to store. ```go theme={null} package main import ( "fmt" "log" "github.com/ParallaxProtocol/parallax/v2/util" "github.com/ParallaxProtocol/parallax/v2/rpc/client" ) func main() { // Create an IPC based RPC connection to a remote node // NOTE update the path to the ipc file! conn, err := client.Dial("/home/parallax/testnet/parallax.ipc") if err != nil { log.Fatalf("Failed to connect to the Parallax client: %v", err) } // Instantiate the contract and display its name // NOTE update the deployment address! store, err := NewStorage(util.HexToAddress("0x21e6fc92f93c8a1bb41e2be64b4e1f88a54d3576"), conn) if err != nil { log.Fatalf("Failed to instantiate Storage contract: %v", err) } ``` The contract instance is then available to interact with in the Go application. To read a value from the blockchain, for example the `value` stored in the contract, the contract's `Retrieve()` function can be called. Again, the function is defined in `Storage.go` as follows: ```go theme={null} // Retrieve is a free data retrieval call binding the contract method 0x2e64cec1. // // Solidity: function retrieve() view returns(uint256) func (_Storage *StorageCaller) Retrieve(opts *bind.CallOpts) (*big.Int, error) { var out []interface{} err := _Storage.contract.Call(opts, &out, "retrieve") if err != nil { return *new(*big.Int), err } out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) return out0, err } ``` Note that the `Retrieve()` function requires a parameter to be passed, even though the original Solidity contract didn't require any at all none. The parameter required is a `*bind.CallOpts` type, which can be used to fine tune the call. If no adjustments to the call are required, pass `nil`. Adjustments to the call include: * `Pending`: Whether to access pending contract state or the current stable one * `GasLimit`: Place a limit on the computing resources the call might consume So to call the `Retrieve()` function in the Go application: ```go theme={null} value, err := store.Retrieve(nil) if err != nil { log.Fatalf("Failed to retrieve value: %v", err) } fmt.Println("Value: ", value) } ``` The output will be something like: `Value: 56` ### Transacting with an Parallax contract Invoking a method that changes contract state (i.e. transacting) is a bit more involved, as a live transaction needs to be authorized and broadcast into the network. **Go bindings require local signing of transactions and do not delegate this to a remote node.** This is to keep accounts private within dapps, and not shared (by default) between them. Thus to allow transacting with a contract, your code needs to implement a method that given an input transaction, signs it and returns an authorized output transaction. Since most users have their keys in the [Web3 Secret Storage](https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition) format, the bind package contains a small utility method (`bind.NewTransactor(keyjson, passphrase)`) that can create an authorized transactor from a key file and associated password, without the user needing to implement key signing themselves. Changing the previous code snippet to update the value stored in the contract: ```go theme={null} package main import ( "fmt" "log" "math/big" "strings" "github.com/ParallaxProtocol/parallax/v2/script/abi/bind" "github.com/ParallaxProtocol/parallax/v2/util" "github.com/ParallaxProtocol/parallax/v2/rpc/client" ) const key = `json object from keystore` func main() { // Create an IPC based RPC connection to a remote node and instantiate a contract binding conn, err := client.Dial("/home/parallax/testnet/parallax.ipc") if err != nil { log.Fatalf("Failed to connect to the Parallax client: %v", err) } store, err := NewStorage(util.HexToAddress("0x21e6fc92f93c8a1bb41e2be64b4e1f88a54d3576"), conn) if err != nil { log.Fatalf("Failed to instantiate a Storage contract: %v", err) } // Create an authorized transactor and call the store function auth, err := bind.NewStorageTransactor(strings.NewReader(key), "strong_password") if err != nil { log.Fatalf("Failed to create authorized transactor: %v", err) } // Call the store() function tx, err := store.Store(auth, big.NewInt(420)) if err != nil { log.Fatalf("Failed to update value: %v", err) } fmt.Printf("Update pending: 0x%x\n", tx.Hash()) } ``` And the output: ``` Update pending: 0x4f4aaeb29ed48e88dd653a81f0b05d4df64a86c99d4e83b5bfeb0f0006b0e55b ``` Similar to the method invocations in the previous section which only read contract state, transacting methods also require a mandatory first parameter, a `*bind.TransactOpts` type, which authorizes the transaction and potentially fine tunes it: * `From`: Address of the account to invoke the method with (mandatory) * `Signer`: Method to sign a transaction locally before broadcasting it (mandatory) * `Nonce`: Account nonce to use for the transaction ordering (optional) * `GasLimit`: Place a limit on the computing resources the call might consume (optional) * `GasPrice`: Explicitly set the gas price to run the transaction with (optional) * `Value`: Any funds to transfer along with the method call (optional) The two mandatory fields are automatically set by the `bind` package if the auth options are constructed using `bind.NewTransactor`. The nonce and gas related fields are automatically derived by the binding if they are not set. Unset values are assumed to be zero. ### Pre-configured contract sessions Reading and state modifying contract-calls require a mandatory first parameter which can authorize and fine tune some of the internal parameters. However, most of the time the same accounts and parameters will be used to issue many transactions, so constructing the call/transact options individually quickly becomes unwieldy. To avoid this, the generator also creates specialized wrappers that can be pre-configured with tuning and authorization parameters, allowing all the Solidity defined methods to be invoked without needing an extra parameter. These are named similarly to the original contract type name but suffixed with `Sessions`: ```go theme={null} // Wrap the Storage contract instance into a session session := &StorageSession{ Contract: store, CallOpts: bind.CallOpts{ Pending: true, }, TransactOpts: bind.TransactOpts{ From: auth.From, Signer: auth.Signer, GasLimit: big.NewInt(3141592), }, } // Call the previous methods without the option parameters session.Store(big.NewInt(69)) ``` ## Bind Solidity directly The compilation and binding steps can be joined together into a pipeline, for example: ```sh theme={null} solc Storage.sol --combined-json abi,bin | abigen --pkg main --type storage --out Storage.go --combined-json - ``` ### Project integration (`go generate`) The `abigen` command was made in such a way as to integrate easily into existing Go toolchains: instead of having to remember the exact command needed to bind a Parallax contract into a Go project, `go generate` can handle all the fine details. Place the binding generation command into a Go source file before the package definition: ```go theme={null} //go:generate abigen --sol Storage.sol --pkg main --out Storage.go ``` After which whenever the Solidity contract is modified, instead of needing to remember and run the above command, we can simply call `go generate` on the package (or even the entire source tree via `go generate ./...`), and it will correctly generate the new bindings for us. ## Blockchain simulator Being able to deploy and access deployed Parallax contracts from native Go code is a powerful feature. However, using public testnets as a backend does not lend itself well to *automated unit testing*. Therefore, the Parallax client also implements a *simulated blockchain* that can be set as a backend to native contracts the same way as a live RPC backend, using the command `backends.NewSimulatedBackend(genesisAccounts)`. The code snippet below shows how this can be used as a backend in a Go application. ```go theme={null} package main import ( "fmt" "log" "math/big" "github.com/ParallaxProtocol/parallax/v2/script/abi/bind" "github.com/ParallaxProtocol/parallax/v2/script/abi/bind/backends" "github.com/ParallaxProtocol/parallax/v2/validation" "github.com/ParallaxProtocol/parallax/v2/crypto" ) func main() { // Generate a new random account and a funded simulator key, _ := crypto.GenerateKey() auth := bind.NewKeyedTransactor(key) sim := backends.NewSimulatedBackend(validation.GenesisAccount{Address: auth.From, Balance: big.NewInt(10000000000)}) // instantiate contract store, err := NewStorage(util.HexToAddress("0x21e6fc92f93c8a1bb41e2be64b4e1f88a54d3576"), sim) if err != nil { log.Fatalf("Failed to instantiate a Storage contract: %v", err) } // Create an authorized transactor and call the store function auth, err := bind.NewStorageTransactor(strings.NewReader(key), "strong_password") if err != nil { log.Fatalf("Failed to create authorized transactor: %v", err) } // Call the store() function tx, err := store.Store(auth, big.NewInt(420)) if err != nil { log.Fatalf("Failed to update value: %v", err) } fmt.Printf("Update pending: 0x%x\n", tx.Hash()) } ``` ## Summary To make interacting with Parallax contracts easier for Go developers, the Parallax client provides tools that generate contract bindings automatically. This makes contract functions available in Go native applications. *** *Adapted from [Go Contract Bindings](https://geth.ethereum.org/docs/developers/dapp-developer/native-bindings) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Introduction Source: https://docs.parallaxprotocol.org/client/developers/introduction Welcome to the Parallax client Developer docs! This section includes information for builders. If you are building decentralized apps on top of Parallax, head to the dapp-developer docs. If you are developing the Parallax client itself, explore the client developer docs. ## Dapp developers The Parallax client has many features that support dapp developers. There are many built-in tracers implemented in Go or Javascript that allow developers to monitor what is happening in the Parallax client from inside an app, and users can build their own custom tracers too. The Parallax client also includes a suite of tools for interacting with Parallax smart contracts using the Parallax client functions using Go functions inside Go native applications. * [Developer mode](/client/developers/dapp/developer-mode) * [Parallax in Go apps](/client/developers/dapp/go-api) * [Go contract bindings](/client/developers/dapp/go-contract-bindings) * [Account management in Go apps](/client/developers/dapp/go-account-management) ## Parallax client developers The Parallax client developers add/remove features and fix bugs in the client. The Parallax client developer section includes contribution guidelines and documentation relating to testing and disclosing vulnerabilities that will help you get started with working on the Parallax client. * [Code review guidelines](/client/developers/client/code-review-guidelines) * [Contributing to the Parallax client](/client/developers/contributing) * [Developer guide](/client/developers/client/guide) * [Disclosures](/client/developers/client/disclosures) * [DNS discovery setup guide](/client/developers/client/dns-disc-guide) ## EVM tracing Tracing allows developers to analyze precisely what the EVM has done or will do given a certain set of commands. This section outlines the various ways tracing can be implemented in the Parallax client. * [Introduction](/client/developers/pvm-tracing/introduction) * [Basic tracers](/client/developers/pvm-tracing/basic) * [Built-in tracers](/client/developers/pvm-tracing/built-in) * [Custom tracers](/client/developers/pvm-tracing/custom-pvm) * [Javascript tracing tutorial](/client/developers/pvm-tracing/tutorial) *** *Partly adapted from [Developer docs](https://geth.ethereum.org/docs/developers) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Basic tracers Source: https://docs.parallaxprotocol.org/client/developers/pvm-tracing/basic The simplest type of transaction trace that the Parallax client can generate are raw EVM opcode traces. For every VM instruction the transaction executes, a structured log entry is emitted, containing all contextual metadata deemed useful. This includes the *program counter*, *opcode name*, *opcode cost*, *remaining gas*, *execution depth* and any *occurred error*. The structured logs can optionally also contain the content of the *execution stack*, *execution memory* and *contract storage*. The entire output of a raw EVM opcode trace is a JSON object having a few metadata fields: *consumed gas*, *failure status*, *return value*; and a list of *opcode entries*: ```json theme={null} { "gas": 25523, "failed": false, "returnValue": "", "structLogs": [] } ``` An example log for a single opcode entry has the following format: ```json theme={null} { "pc": 48, "op": "DIV", "gasCost": 5, "gas": 64532, "depth": 1, "error": null, "stack": [ "00000000000000000000000000000000000000000000000000000000ffffffff", "0000000100000000000000000000000000000000000000000000000000000000", "2df07fbaabbe40e3244445af30759352e348ec8bebd4dd75467a9f29ec55d98d" ], "memory": [ "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000060" ], "storage": {} } ``` ### Generating basic traces To generate a raw EVM opcode trace, the Parallax client provides a few [RPC API endpoints](/client/interacting-with-parallax/json-rpc-namespaces/debug). The most commonly used is [debug\_traceTransaction](/client/interacting-with-parallax/json-rpc-namespaces/debug#debug_tracetransaction). In its simplest form, `traceTransaction` accepts a transaction hash as its only argument. It then traces the transaction, aggregates all the generated data and returns it as a **large** JSON object. A sample invocation from the Parallax client console would be: ```javascript theme={null} debug.traceTransaction('0xfc9359e49278b7ba99f59edac0e3de49956e46e530a53c15aa71226b7aa92c6f'); ``` The same call can also be invoked from outside the node too via HTTP RPC (e.g. using Curl). In this case, the HTTP endpoint must be enabled in the Parallax client using the `--http` command and the `debug` API namespace must be exposed using `--http.api=debug`. ```sh theme={null} curl -H "Content-Type: application/json" -d '{"id": 1, "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0xfc9359e49278b7ba99f59edac0e3de49956e46e530a53c15aa71226b7aa92c6f"]}' localhost:8545 ``` To follow along with this tutorial, transaction hashes can be found from a local Parallax node (e.g. by attaching a [Javascript console](/client/interacting-with-parallax/js-console) and running `eth.getBlock('latest')` then passing a transaction hash from the returned block to `debug.traceTransaction()`) or from a block explorer. It is also possible to configure the trace by passing Boolean (true/false) values for four parameters that tweak the verbosity of the trace. By default, the *EVM memory* and *Return data* are not reported but the *EVM stack* and *EVM storage* are. To report the maximum amount of data: ```sh theme={null} enableMemory: true disableStack: false disableStorage: false enableReturnData: true ``` An example call, made in the Parallax client Javascript console, configured to report the maximum amount of data looks as follows: ```javascript theme={null} debug.traceTransaction('0xfc9359e49278b7ba99f59edac0e3de49956e46e530a53c15aa71226b7aa92c6f', { enableMemory: true, disableStack: false, disableStorage: false, enableReturnData: true }); ``` Alternatively, disabling *EVM Stack*, *EVM Memory*, *Storage* and *Return data* (as demonstrated in the Curl request below) results in the following, much shorter, [trace dump](https://gist.github.com/karalabe/d74a7cb33a70f2af75e7824fc772c5b4). ```sh theme={null} curl -H "Content-Type: application/json" -d '{"id": 1, "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0xfc9359e49278b7ba99f59edac0e3de49956e46e530a53c15aa71226b7aa92c6f", {"disableStack": true, "disableStorage": true}]}' localhost:8545 ``` ### Limits of basic traces Although the raw opcode traces generated above are useful, having an individual log entry for every single opcode is too low level for most use cases, and will require developers to create additional tools to post-process the traces. Additionally, a full opcode trace can easily go into the hundreds of megabytes, making them very resource intensive to get out of the node and process externally. To avoid those issues, the Parallax client supports running custom JavaScript tracers *within* the Parallax node, which have full access to the EVM stack, memory and contract storage. This means developers only have to gather the data they actually need, and do any processing at the source. ### Summary This page described how to do basic traces in the Parallax client Basic traces are very low level and can generate lots of data that might not all be useful. Therefore, it is also possible to use a set of built-in tracers or write custom ones in Javascript or Go. Read more about [built-in](/client/developers/pvm-tracing/built-in) and [custom](/client/developers/pvm-tracing/custom-pvm) tracers. *** *Adapted from [Basic traces](https://geth.ethereum.org/docs/developers/evm-tracing/basic-traces) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Built-in tracers Source: https://docs.parallaxprotocol.org/client/developers/pvm-tracing/built-in The Parallax client comes bundled with a choice of tracers that can be invoked via the [tracing API](/client/interacting-with-parallax/json-rpc-namespaces/debug). Some of these built-in tracers are implemented natively in Go, and others in Javascript. The default tracer is the opcode logger (otherwise known as struct logger) which is the default tracer for all the methods. Other tracers have to be specified by passing their name to the tracer parameter in the API call. ## Struct/opcode logger The struct logger (aka opcode logger) is a native Go tracer which executes a transaction and emits the opcode and execution context at every step. This is the tracer that will be used when no name is passed to the API, e.g. `debug.traceTransaction()`. The following information is emitted at each step: | FIELD | TYPE | DESCRIPTION | | - | - | - | | pc | uint64 | program counter | | op | byte | opcode to be executed | | gas | uint64 | remaining gas | | gasCost | uint64 | cost for executing op | | memory | \[]byte | EVM memory. Enabled via enableMemory | | memSize | int | Size of memory | | stack | \[]uint256 | EVM stack. Disabled via disableStack | | returnData | \[]byte | Last call's return data. Enabled via enableReturnData | | storage | map\[hash]hash | Storage slots of current contract read from and written to. Only emitted for SLOAD and SSTORE. Disabled via disableStorage | | depth | int | Current call depth | | refund | uint64 | Refund counter | | error | string | Error message if any | Note that the fields `memory`, `stack`, `returnData`, and `storage` have dynamic size and depending on the exact transaction they could grow large in size. This is specially true for memory which could blow up the trace size. It is recommended to keep them disabled unless they are explicitly required for a given use case. It is also possible to configure the trace by passing Boolean (true/false) values for four parameters that tweak the verbosity of the trace. By default, the *EVM memory* and *Return data* are not reported but the *EVM stack* and *EVM storage* are to report the maximum amount of data: ```sh theme={null} enableMemory: true disableStack: false disableStorage: false enableReturnData: true ``` An example call: ```javascript theme={null} debug.traceTransaction('0xfc9359e49278b7ba99f59edac0e3de49956e46e530a53c15aa71226b7aa92c6f', { enableMemory: true, disableStack: false, disableStorage: false, enableReturnData: true }); ``` Return: ```json theme={null} { "gas":25523, "failed":false, "returnValue":"", "structLogs":[ { "pc":0, "op":"PUSH1", "gas":64580, "gasCost":3, "depth":1, "error":null, "stack":[ ], "memory":null, "storage":{ } }, { "pc":2, "op":"PUSH1", "gas":64577, "gasCost":3, "depth":1, "error":null, "stack":[ "0000000000000000000000000000000000000000000000000000000000000060" ], "memory":null, "storage":{ } }, ... ``` ## Native tracers The following tracers are implement in Go. This means they are much more performant than other tracers that are written in Javascript. The tracers are selected by passing their name to the tracer parameter when invoking a tracing API method, e.g. `debug.traceTransaction(, { tracer: 'callTracer' })`. ### 4byteTracer Solidity contract functions are [addressed](https://docs.soliditylang.org/en/develop/abi-spec.html#function-selector) using the first four byte of the Keccak-256 hash of their signature. Therefore when calling the function of a contract, the caller must send this function selector as well as the ABI-encoded arguments as call data. The `4byteTracer` collects the function selectors of every function executed in the lifetime of a transaction, along with the size of the supplied call data. The result is a `map[string]int` where the keys are `SELECTOR-CALLDATASIZE` and the values are number of occurrences of this key. For example: Example call: ```sh theme={null} debug.traceTransaction( "0x214e597e35da083692f5386141e69f47e973b2c56e7a8073b1ea08fd7571e9de", {tracer: "4byteTracer"}) ``` Return: ```json theme={null} { "0x27dc297e-128": 1, "0x38cc4831-0": 2, "0x524f3889-96": 1, "0xadf59f99-288": 1, "0xc281d19e-0": 1 } ``` ### callTracer The `callTracer` tracks all the call frames executed during a transaction, including depth 0. The result will be a nested list of call frames, resembling how EVM works. They form a tree with the top-level call at root and sub-calls as children of the higher levels. Each call frame has the following fields: | FIELD | TYPE | DESCRIPTION | | - | - | - | | type | string | CALL or CREATE | | from | string | address | | to | string | address | | value | string | hex-encoded amount of value transfer | | gas | string | hex-encoded gas provided for call | | gasUsed | string | hex-encoded gas used during call | | input | string | call data | | output | string | return data | | error | string | error, if any | | revertReason | string | Solidity revert reason, if any | | calls | \[]callframe | list of sub-calls | Example Call: ```sh theme={null} > debug.traceTransaction("0x44bed3dc0f584b2a2ab32f5e2948abaaca13917eeae7ae3b959de3371a6e9a95", {tracer: 'callTracer'}) ``` Return: ```json theme={null} { calls: [{ from: "0xc8ba32cab1757528daf49033e3673fae77dcf05d", gas: "0x18461", gasUsed: "0x60", input: "0x000000204895cd480cc8412691a880028a25aec86786f1ed2aa5562bc400000000000000c6403c14f35be1da6f433eadbb6e9178a47fbc7c6c1d568d2f2b876e929089c8d8db646304fd001a187dc8a6", output: "0x557904b74478f8810cc02198544a030d1829bb491e14fe1dd0354e933c5e87bd", to: "0x0000000000000000000000000000000000000002", type: "STATICCALL" }, { from: "0xc8ba32cab1757528daf49033e3673fae77dcf05d", gas: "0x181db", gasUsed: "0x48", input: "0x557904b74478f8810cc02198544a030d1829bb491e14fe1dd0354e933c5e87bd", output: "0x5fb393023b12544491a5b8fb057943b4ebf5b1401e88e44a7800000000000000", to: "0x0000000000000000000000000000000000000002", type: "STATICCALL" }], from: "0x35a9f94af726f07b5162df7e828cc9dc8439e7d0", gas: "0x1a310", gasUsed: "0xfcb6", input: "0xd1a2eab2000000000000000000000000000000000000000000000000000000000024aea100000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000050000000204895cd480cc8412691a880028a25aec86786f1ed2aa5562bc400000000000000c6403c14f35be1da6f433eadbb6e9178a47fbc7c6c1d568d2f2b876e929089c8d8db646304fd001a187dc8a600000000000000000000000000000000", to: "0xc8ba32cab1757528daf49033e3673fae77dcf05d", type: "CALL", value: "0x0" } ``` Things to note about the call tracer: * Calls to precompiles are also included in the result * 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 #### **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: ```javascript theme={null} > debug.traceTransaction('0xc73e70f6d60e63a71dabf90b9983f2cdd56b0cb7bcf1a205f638d630a95bba73', { tracer: 'callTracer', tracerConfig: { onlyTopCall: true } }) ``` ### prestateTracer The prestate tracer has two modes: `prestate` and `diff`. The `prestate` mode returns the accounts necessary to execute a given transaction. `diff` mode returns the differences between the transaction's pre and post-state (i.e. what changed because the transaction happened). The `prestateTracer` defaults to `prestate` mode. It reexecutes the given transaction and tracks every part of state that is touched. This is similar to the concept of a [stateless witness](https://ethresear.ch/t/the-stateless-client-concept/172), the difference being this tracer doesn't return any cryptographic proof, rather only the trie leaves. The result is an object. The keys are addresses of accounts. The value is an object with the following fields: | FIELD | TYPE | DESCRIPTION | | - | - | - | | balance | string | balance in Wei | | nonce | uint64 | nonce | | code | string | hex-encoded bytecode | | storage | map\[string]string | storage slots of the contract | In `diff` mode the result object will contain a `pre` and a `post` object: 1. Any read-only access is omitted completely from the result. This mode is only concerned with state modifications. 2. In `pre` you will find the state of an account before the tx started, and in post its state after tx execution finished. 3. `post` will contain only the modified fields. e.g. if `nonce` of an account hasn't changed it will be omitted from post. 4. Deletion (i.e. account selfdestruct, or storage clearing) will be signified by inclusion in `pre` and omission in `post`. 5. Insertion (i.e. account creation or new slots) will be signified by omission in `pre` and inclusion in `post`. To run this tracer in `diff` mode, pass `tracerConfig: {diffMode: true}` in the API call. Example of `prestate` mode: ```javascript theme={null} debug.traceCall( { from: '0x35a9f94af726f07b5162df7e828cc9dc8439e7d0', to: '0xc8ba32cab1757528daf49033e3673fae77dcf05d', data: '0xd1a2eab2000000000000000000000000000000000000000000000000000000000024aea100000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000050000000204895cd480cc8412691a880028a25aec86786f1ed2aa5562bc400000000000000c6403c14f35be1da6f433eadbb6e9178a47fbc7c6c1d568d2f2b876e929089c8d8db646304fd001a187dc8a600000000000000000000000000000000' }, 'latest', { tracer: 'prestateTracer' } ); ``` Return: ```json theme={null} { 0x0000000000000000000000000000000000000002: { balance: "0x0" }, 0x008b3b2f992c0e14edaa6e2c662bec549caa8df1: { balance: "0x2638035a26d133809" }, 0x35a9f94af726f07b5162df7e828cc9dc8439e7d0: { balance: "0x7a48734599f7284", nonce: 1133 }, 0xc8ba32cab1757528daf49033e3673fae77dcf05d: { balance: "0x0", code: "0x608060405234801561001057600080fd5b50600436106100885760003560e01c8063a9c2d... nonce: 1, storage: { 0x0000000000000000000000000000000000000000000000000000000000000000: "0x000000000000000000000000000000000000000000000000000000000024aea6", 0x59fb7853eb21f604d010b94c123acbeae621f09ce15ee5d7616485b1e78a72e9: "0x00000000000000c42b56a52aedf18667c8ae258a0280a8912641c80c48cd9548", 0x8d8ebb65ec00cb973d4fe086a607728fd1b9de14aa48208381eed9592f0dee9a: "0x00000000000000784ae4881e40b1f5ebb4437905fbb8a5914454123b0293b35f", 0xff896b09014882056009dedb136458f017fcef9a4729467d0d00b4fd413fb1f1: "0x000000000000000e78ac39cb1c20e9edc753623b153705d0ccc487e31f9d6749" } } } ``` Return (same call with `{diffMode: True}`): ```json theme={null} { post: { 0x35a9f94af726f07b5162df7e828cc9dc8439e7d0: { nonce: 1135 } }, pre: { 0x35a9f94af726f07b5162df7e828cc9dc8439e7d0: { balance: "0x7a48429e177130a", nonce: 1134 } } } ``` ### noopTracer This tracer is noop. It returns an empty object and is only meant for testing the setup. ## Javascript tracers There are also a set of tracers written in Javascript. These are less performant than the Go native tracers because of overheads associated with interpreting the Javascript in Parallax client's Go environment. ### bigram `bigramTracer` counts the opcode bigrams, i.e. how many times 2 opcodes were executed one after the other. Example: ```javascript theme={null} debug.traceCall( { from: '0x35a9f94af726f07b5162df7e828cc9dc8439e7d0', to: '0xc8ba32cab1757528daf49033e3673fae77dcf05d', data: '0xd1a2eab2000000000000000000000000000000000000000000000000000000000024aea100000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000050000000204895cd480cc8412691a880028a25aec86786f1ed2aa5562bc400000000000000c6403c14f35be1da6f433eadbb6e9178a47fbc7c6c1d568d2f2b876e929089c8d8db646304fd001a187dc8a600000000000000000000000000000000' }, 'latest', { tracer: 'bigramTracer' } ); ``` Returns: ```json theme={null} { ADD-ADD: 1, ADD-AND: 2, ADD-CALLDATALOAD: 1, ADD-DUP1: 2, ADD-DUP2: 2, ADD-GT: 1, ADD-MLOAD: 1, ADD-MSTORE: 4, ADD-PUSH1: 1, ADD-PUSH2: 4, ADD-SLT: 1, ADD-SWAP1: 10, ADD-SWAP2: 1, ADD-SWAP3: 1, ADD-SWAP4: 3, ADD-SWAP5: 1, AND-DUP3: 2, AND-ISZERO: 4, ... } ``` ### evmdis evmdisTracer returns sufficient information from a trace to perform [evmdis](https://github.com/Arachnid/evmdis)-style disassembly Example: ```javascript theme={null} > debug.traceCall({from: "0x35a9f94af726f07b5162df7e828cc9dc8439e7d0", to: "0xc8ba32cab1757528daf49033e3673fae77dcf05d", data: "0xd1a2eab2000000000000000000000000000000000000000000000000000000000024aea100000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000050000000204895cd480cc8412691a880028a25aec86786f1ed2aa5562bc400000000000000c6403c14f35be1da6f433eadbb6e9178a47fbc7c6c1d568d2f2b876e929089c8d8db646304fd001a187dc8a600000000000000000000000000000000"}, 'latest', {tracer: 'evmdisTracer'}) ``` Returns: ```json theme={null} [{ depth: 1, len: 2, op: 96, result: ["80"] }, { depth: 1, len: 2, op: 96, result: ["40"] }, { depth: 1, op: 82, result: [] }, { depth: 1, op: 52, result: ["0"] }, { depth: 1, op: 128, result: ["0", "0"] }, { depth: 1, op: 21, result: ["1"] }, { depth: 1, len: 3, op: 97, result: ["10"] }, { depth: 1, op: 87, result: [] }, { depth: 1, op: 91, pc: 16, result: [] }, ... ``` ### opcount `opcountTracer` counts the total number of opcodes executed and simply returns the number. Example: ```javascript theme={null} debug.traceCall( { from: '0x35a9f94af726f07b5162df7e828cc9dc8439e7d0', to: '0xc8ba32cab1757528daf49033e3673fae77dcf05d', data: '0xd1a2eab2000000000000000000000000000000000000000000000000000000000024aea100000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000050000000204895cd480cc8412691a880028a25aec86786f1ed2aa5562bc400000000000000c6403c14f35be1da6f433eadbb6e9178a47fbc7c6c1d568d2f2b876e929089c8d8db646304fd001a187dc8a600000000000000000000000000000000' }, 'latest', { tracer: 'opcountTracer' } ); ``` Returns: ``` 1384 ``` ### trigram `trigramTracer` counts the opcode trigrams. Trigrams are the possible combinations of three opcodes this tracer reports how many times each combination is seen during execution. Example: ```javascript theme={null} debug.traceCall( { from: '0x35a9f94af726f07b5162df7e828cc9dc8439e7d0', to: '0xc8ba32cab1757528daf49033e3673fae77dcf05d', data: '0xd1a2eab2000000000000000000000000000000000000000000000000000000000024aea100000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000050000000204895cd480cc8412691a880028a25aec86786f1ed2aa5562bc400000000000000c6403c14f35be1da6f433eadbb6e9178a47fbc7c6c1d568d2f2b876e929089c8d8db646304fd001a187dc8a600000000000000000000000000000000' }, 'latest', { tracer: 'trigramTracer' } ); ``` Returns: ```json theme={null} { --PUSH1: 1, -PUSH1-MSTORE: 1, ADD-ADD-GT: 1, ADD-AND-DUP3: 2, ADD-CALLDATALOAD-PUSH8: 1, ADD-DUP1-PUSH1: 2, ADD-DUP2-ADD: 1, ADD-DUP2-MSTORE: 1, ADD-GT-ISZERO: 1, ADD-MLOAD-DUP6: 1, ADD-MSTORE-ADD: 1, ADD-MSTORE-PUSH1: 2, ADD-MSTORE-PUSH32: 1, ADD-PUSH1-KECCAK256: 1, ADD-PUSH2-JUMP: 2, ADD-PUSH2-JUMPI: 1, ADD-PUSH2-SWAP2: 1, ADD-SLT-PUSH2: 1, ... } ``` ### unigram `unigramTracer` counts the frequency of occurrence of each opcode. Example: ```javascript theme={null} > debug.traceCall({from: "0x35a9f94af726f07b5162df7e828cc9dc8439e7d0", to: "0xc8ba32cab1757528daf49033e3673fae77dcf05d", data: "0xd1a2eab2000000000000000000000000000000000000000000000000000000000024aea100000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000050000000204895cd480cc8412691a880028a25aec86786f1ed2aa5562bc400000000000000c6403c14f35be1da6f433eadbb6e9178a47fbc7c6c1d568d2f2b876e929089c8d8db646304fd001a187dc8a600000000000000000000000000000000"}, 'latest', {tracer: 'unigramTracer'}) ``` Returns: ```json theme={null} { ADD: 36, AND: 23, BYTE: 4, CALLDATACOPY: 1, CALLDATALOAD: 6, CALLDATASIZE: 2, CALLVALUE: 1, DIV: 9, DUP1: 29, DUP10: 2, DUP11: 1, DUP12: 3, DUP13: 2, ... } ``` ## State overrides It is possible to give temporary state modifications to the Parallax client in order to simulate the effects of `eth_call`. For example, some new bytecode could be deployed to some address *temporarily just for the duration of the execution* and then a transaction interacting with that address can be traced. This can be used for scenario testing or determining the outcome of some hypothetical transaction before executing for real. To do this, the tracer is written as normal, but the parameter `stateOverrides` is passed an address and some bytecode. ```javascript theme={null} var code = //contract bytecode var tracer = //tracer name debug.traceCall({from: , to: , input: }, 'latest', {stateOverrides: {'0x...': {code: code}}, tracer: tracer}) ``` ## Summary This page showed how to use the tracers that come bundled with the Parallax client. 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. *** *Adapted from [Built-in tracers](https://geth.ethereum.org/docs/developers/evm-tracing/built-in-tracers) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Custom PVM tracer Source: https://docs.parallaxprotocol.org/client/developers/pvm-tracing/custom-pvm In addition to the default opcode tracer and the built-in tracers, the Parallax client 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 Parallax client source code. ## Custom Go tracing Custom tracers can also be made more performant by writing them in Go. The gain in performance mostly comes from the fact that the Parallax client doesn't need to interpret JS code and can execute native functions. The Parallax client comes with several built-in [native tracers](https://github.com/ParallaxProtocol/parallax/tree/main/node/fullnode/tracers/native) which can serve as examples. Please note that unlike JS tracers, Go tracing scripts cannot be simply passed as an argument to the API. They will need to be added to and compiled with the rest of the Parallax client source code. In this section a simple native tracer that counts the number of opcodes will be covered. First follow the instructions to [clone and build](/client/getting-started/installing-client) Parallax client from source code. Next save the following snippet as a `.go` file and add it to `node/fullnode/tracers/native`: ```go theme={null} package native import ( "encoding/json" "math/big" "sync/atomic" "time" "github.com/ParallaxProtocol/parallax/v2/util" "github.com/ParallaxProtocol/parallax/v2/script" "github.com/ParallaxProtocol/parallax/v2/node/fullnode/tracers" ) func init() { // This is how Parallax client will become aware of the tracer and register it under a given name register("opcounter", newOpcounter) } type opcounter struct { env *script.EVM counts map[string]int // Store opcode counts interrupt uint32 // Atomic flag to signal execution interruption reason error // Textual reason for the interruption } func newOpcounter(ctx *tracers.Context, cfg json.RawMessage) tracers.Tracer { return &opcounter{counts: make(map[string]int)} } // CaptureStart implements the EVMLogger interface to initialize the tracing operation. func (t *opcounter) CaptureStart(env *script.EVM, from util.Address, to util.Address, create bool, input []byte, gas uint64, value *big.Int) { t.env = env } // CaptureState implements the EVMLogger interface to trace a single step of VM execution. func (t *opcounter) CaptureState(pc uint64, op script.OpCode, gas, cost uint64, scope *script.ScopeContext, rData []byte, depth int, err error) { // Skip if tracing was interrupted if atomic.LoadUint32(&t.interrupt) > 0 { t.env.Cancel() return } name := op.String() if _, ok := t.counts[name]; !ok { t.counts[name] = 0 } t.counts[name]++ } // CaptureEnter is called when EVM enters a new scope (via call, create or selfdestruct). func (t *opcounter) CaptureEnter(op script.OpCode, from util.Address, to util.Address, input []byte, gas uint64, value *big.Int) {} // CaptureExit is called when EVM exits a scope, even if the scope didn't // execute any code. func (t *opcounter) CaptureExit(output []byte, gasUsed uint64, err error) {} // CaptureFault implements the EVMLogger interface to trace an execution fault. func (t *opcounter) CaptureFault(pc uint64, op script.OpCode, gas, cost uint64, scope *script.ScopeContext, depth int, err error) {} // CaptureEnd is called after the call finishes to finalize the tracing. func (t *opcounter) CaptureEnd(output []byte, gasUsed uint64, _ time.Duration, err error) {} func (*opcounter) CaptureTxStart(gasLimit uint64) {} func (*opcounter) CaptureTxEnd(restGas uint64) {} // GetResult returns the json-encoded nested list of call traces, and any // error arising from the encoding or forceful termination (via `Stop`). func (t *opcounter) GetResult() (json.RawMessage, error) { res, err := json.Marshal(t.counts) if err != nil { return nil, err } return res, t.reason } // Stop terminates execution of the tracer at the first opportune moment. func (t *opcounter) Stop(err error) { t.reason = err atomic.StoreUint32(&t.interrupt, 1) } ``` Every method of the [EVMLogger interface](https://pkg.go.dev/github.com/ParallaxProtocol/parallax/v2/script#EVMLogger) needs to be implemented (even if empty). Key parts to notice are the `init()` function which registers the tracer in the Parallax client, the `CaptureState` hook where the opcode counts are incremented and `GetResult` where the result is serialized and delivered. Note that the constructor takes in a `cfg json.RawMessage`. This will be filled with a JSON object that user provides to the tracer to pass in optional config fields. To test out this tracer the source is first compiled with `make parallax`. Then in the console it can be invoked through the usual API methods by passing in the name it was registered under: ```javascript theme={null} > debug.traceTransaction('0x7ae446a7897c056023a8104d254237a8d97783a92900a7b0f7db668a9432f384', { tracer: 'opcounter' }) { ADD: 4, AND: 3, CALLDATALOAD: 2, ... } ``` ## 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](/client/interacting-with-parallax/json-rpc-namespaces/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 the Parallax client 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`: ```javascript theme={null} debug.traceTransaction(', { tracer: 'callTracer', tracerConfig: { onlyTopCall: true } }) ``` The config in the following example is the `diffMode` option available in the `prestateTracer`: ```javascript theme={null} 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 occurred, otherwise returns undefined If error is non-empty, all other fields should be ignored. For efficiency, the same `log` object is reused on each execution step, updated with current values; make sure to copy values you want to preserve beyond the current call. For instance, this step function will not work: ```javascript theme={null} function(log) { this.logs.append(log); } ``` But this step function will: ```javascript theme={null} 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 occurred during execution and undefined otherwise ### Usage Note that several values are Golang big.Int objects, not JavaScript numbers or JS bigints. As such, they have the same interface as described in the godocs. Their default serialization to JSON is as a Javascript number; to serialize large numbers accurately call `.String()` on them. For convenience, `big.NewInt(x)` is provided, and will convert a uint to a Go BigInt. Usage example, returns the top element of the stack at each CALL opcode only: ```javascript theme={null} 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_calls` or rejected blocks. The full list of trace functions can be explored in the [reference documentation](/client/interacting-with-parallax/json-rpc-namespaces/debug). ## Summary This page described how to write custom tracers for the Parallax client. Custom tracers can be written in Javascript or Go. *** *Adapted from [Custom EVM tracer](https://geth.ethereum.org/docs/developers/evm-tracing/custom-tracer) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Introduction Source: https://docs.parallaxprotocol.org/client/developers/pvm-tracing/introduction Tracing allows users to examine precisely what was executed by the EVM during some specific transaction or set of transactions. There are two different types of [transactions](/protocol/foundational-topics/transactions) in Parallax: value transfers and contract executions. A value transfer just moves Laxes from one account to another. A contract interaction executes some code stored at a contract address which can include altering stored data and transacting multiple times with other contracts and externally-owned accounts. A contract execution transaction can therefore be a complicated web of interactions that can be difficult to unpick. The transaction receipt contains a status code that shows whether the transaction succeeded or failed, but more detailed information is not readily available, meaning it is very difficult to know what a contract execution actually did, what data was modified and which addresses were touched. This is the problem that EVM tracing solves. The Parallax client traces transactions by re-running them locally and collecting data about precisely what was executed by the EVM. ## State availability In its simplest form, tracing a transaction entails requesting the Parallax node to reexecute the desired transaction with varying degrees of data collection and have it return an aggregated summary. In order for a Parallax node to reexecute a transaction, all historical state accessed by the transaction must be available. This includes: * Balance, nonce, bytecode and storage of both the recipient as well as all internally invoked contracts. * Block metadata referenced during execution of both the outer as well as all internally created transactions. * Intermediate state generated by all preceding transactions contained in the same block as the one being traced. This means there are limits on the transactions that can be traced imposed by the synchronization and pruning configuration of a node: * An **archive** node retains **all historical data** back to genesis. It can therefore trace arbitrary transactions at any point in the history of the chain. Tracing a single transaction requires reexecuting all preceding transactions in the same block. * A **node synced from genesis** node only retains the most recent 128 block states in memory. Older states are represented by a sequence of occasional checkpoints that intermediate states can be regenerated from. This means that states within the most recent 128 blocks are immediately available, older states have to be regenerated from snapshots "on-the-fly". If the distance between the requested transaction and the most recent checkpoint is large, rebuilding the state can take a long time. Tracing a single transaction requires reexecuting all preceding transactions in the same block **and** all preceding blocks until the previous stored snapshot. * A **snap synced** node holds the most recent 128 blocks in memory, so transactions in that range are always accessible. However, snap-sync only starts processing from a relatively recent block (as opposed to genesis for a full node). Between the initial sync block and the 128 most recent blocks, the node stores occasional checkpoints that can be used to rebuild the state on-the-fly. This means transactions can be traced back as far as the block that was used for the initial sync. Tracing a single transaction requires reexecuting all preceding transactions in the same block, **and** all preceding blocks until the previous stored snapshot. ![](https://geth.ethereum.org/images/docs/state-pruning.png) > [!NOTE] > > More detailed information about syncing is available on the [sync modes page](/client/fundamentals/sync-modes). When a trace of a specific transaction is executed, the state is prepared by fetching the state of the parent block from the database. If it is not available, the Parallax client will crawl backwards in time to find the next available state but only up to a limit defined in the `reexec` parameter which defaults to 128 blocks. If no state is available within the `reexec` window then the trace fails with `Error: required historical state unavailable` and the `reexec` parameter must be increased. If a valid state *is* found in the `reexec` window, then the Parallax client sequentially re-executes the transactions in each block between the last available state and the target block. The greater the value of `reexec` the longer the tracing will take because more blocks have to be re-executed to regenerate the target state. The `debug_getAccessibleStates` endpoint is a useful tool for estimating a suitable value for `reexec`. Passing the number of the block that contains the target transaction and a search distance to this endpoint will return the number of blocks behind the current head where the most recent available state exists. This value can be passed to the tracer as `re-exec`. It is also possible to force the Parallax client to store the state for specific sequences of block by stopping the client, running again with `--gcmode archive` for some period - this prevents state pruning for blocks that arrive while the Parallax client is running with `--gcmode archive`. > [!NOTE] > > *There are exceptions to the above rules when running batch traces of entire blocks or chain segments. Those will be detailed later.* ## Types of trace ### Basic traces The simplest type of transaction trace that the Parallax client can generate are raw EVM opcode traces. For every EVM instruction the transaction executes, a structured log entry is emitted, containing all contextual metadata deemed useful. This includes the *program counter*, *opcode name*, *opcode cost*, *remaining gas*, *execution depth* and any *occurred error*. The structured logs can optionally also contain the content of the *execution stack*, *execution memory* and *contract storage*. > [!NOTE] > > Read more about the Parallax client's basic traces on the [basic traces page](/client/developers/pvm-tracing/basic). ### Built-in tracers The tracing API accepts an optional `tracer` parameter that defines how the data returned to the API call should be processed. If this parameter is omitted the default tracer is used. The default is the struct (or 'opcode') logger. These raw opcode traces are sometimes useful, but the returned data is very low level and can be too extensive and awkward to read for many use cases. A full opcode trace can easily go into the hundreds of megabytes, making them very resource intensive to get out of the node and process externally. For these reasons, there are a set of non-default built-in tracers that can be named in the API call to return different data from the method. Under the hood, these tracers are Go or Javascript functions that do some specific preprocessing on the trace data before it is returned. > [!NOTE] > > More information about Parallax client's built-in tracers is available on the [built-in tracers](/client/developers/pvm-tracing/built-in) page. ### Custom tracers In addition to built-in tracers, it is possible to provide custom code that hooks to events in the EVM to process and return 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 Parallax client source code. This means developers only have to gather the data they actually need, and do any processing at the source. > [!NOTE] > > More information about custom tracers is available on the [custom tracers](/client/developers/pvm-tracing/custom-pvm) page. ## Summary This page gave an introduction to the concept of tracing and explained issues around state availability. More detailed information on Parallax client's built-in and custom tracers can be found on their dedicated pages. *** *Adapted from [EVM Tracing](https://geth.ethereum.org/docs/developers/evm-tracing) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Tutorial for JavaScript tracing Source: https://docs.parallaxprotocol.org/client/developers/pvm-tracing/tutorial The Parallax client supports tracing via [custom Javascript tracers](/client/developers/pvm-tracing/custom-pvm#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: ```javascript theme={null} 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 ... ``` 1. Run the [JavaScript console](/client/interacting-with-parallax/js-console). 2. Get the hash of a recent transaction from a node or block explorer. 3. Run this command to run the script: ```javascript theme={null} loadScript('filterTrace_1.js'); ``` 4. Run the tracer from the script. Be patient, it could take a long time. ```javascript theme={null} tracer(''); ``` The bottom of the output looks similar to: ```sh theme={null} "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" ``` 5. Run this line to get a more readable output with each string in its own line. ```javascript theme={null} 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](/client/developers/pvm-tracing/basic), but with a new parameter, `tracer`. This parameter takes the JavaScript object formatted as a string. In the case of the trace above, it is: ```javascript theme={null} { 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: ```javascript theme={null} 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](/protocol/foundational-topics/pvm/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 theme={null} [ "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. ```javascript theme={null} 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 theme={null} [ "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 of 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 theme={null} 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`. ```json theme={null} [ "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 2^256 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 Parallax addresses, `this.byteHex()` and `array2Hex()` can be used. ```javascript theme={null} 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 ``` The Parallax client can be started in a separate terminal. To connect to Clef, ensure the data directory is consistent with the path provided to Clef and pass the location of the the Clef IPC file - which Clef saves to the path provided to its `--configdir` flag - in this case we set it to `~/parallax/testnet/clef`: ```sh theme={null} parallaxd --testnet --datadir testnet --signer=testnet/clef/clef.ipc ``` ## Interacting with Clef There are two modes of interaction with Clef. One is direct interaction, which is achieved by passing requests by HTTP or IPC with JSON-RPC data as defined in Clef's external API. This is the way to do things in Clef that don't require the Parallax client, such as creating and listing accounts, or signing data offline. The other way is via Parallax client. With the Parallax client started with Clef as an external signer, requests made to the Parallax client that touch account data will route via Clef for approval. By default, the user approves or denies interactions manually by typing `y` or `n` into the Clef console when prompted, but custom rules can also be created to automate common tasks. ### Creating accounts New accounts can be created using Clef's `account new` method. This generates a new key pair and adds them to the given `keystore` directory: ```sh theme={null} clef newaccount --keystore testnet/keystore ``` Clef will request the new password in the terminal. The same can be achieved using raw JSON requests (this example send the request to Clef's exposed HTTP port using curl): ```sh theme={null} curl -X POST --data '{"id": 0, "jsonrpc": "2.0", "method": "account_new", "params": []}' http://localhost:8550 -H "Content-Type: application/json" ``` The console will hang because Clef is waiting for manual approval. Switch to the Clef terminal and approve the action. Clef will prompt for an account password and then confirm the account creation in the terminal logs. A new keyfile has been added to the keystore in `parallax/testnet`. A JSON response is returned to the terminal the request originated from, containing the new account address in the result field. ```json theme={null} {"jsonrpc": "2.0", "id": 0, "result": "0x168bc315a2ee09042d83d7c5811b533620531f67"} ``` It is critical to backup the account password safely and securely as it cannot be retrieved or reset. If the password provided on account creation is lost or forgotten, there is no way to retrive it and the account will simply stay locked forever. The password MUST be backed up safely and securely! **IT IS CRITICAL TO BACKUP THE KEYSTORE AND REMEMBER PASSWORDS!** The newly generated key files can be viewed in `/keystore/`. The file naming format is `UTC----
` where `date` is the date and time of key creation formatted according to [UTC 8601](https://www.iso.org/iso-8601-date-and-time-format.html) with zero time offset and seconds precise to eight decimal places; `address` is the 40 hexadecimal characters that make up the account address without a leading `0x`, for example: `UTC--2022-05-19T12-34-36.47413510Z--0b85e5a13e118466159b1e1b6a4234e5f9f784bb` An account can also be created by importing a raw private key (hex string) using clef importraw as follows: ```sh theme={null} clef importraw ``` The terminal will respond with the following message, indicating the account has been created successfully: ``` ## Info Key imported: Address 0x9160DC9105f7De5dC5E7f3d97ef11DA47269BdA6 Keystore file: /home/user/.parallax/keystore/UTC--2022-10-28T12-03-13.976383602Z--9160dc9105f7de5dc5e7f3d97ef11da47269bda6 The key is now encrypted; losing the password will result in permanently losing access to the key and all associated funds! Make sure to backup keystore and passwords in a safe location. ``` ### Listing accounts The accounts in the keystore can be listed to the terminal using a simple CLI command as follows: ```sh theme={null} clef list-accounts --keystore ``` or using `account_list` in a POST request as follows: ```sh theme={null} curl -X POST --data '{"id": 0, "jsonrpc": "2.0", "method": "account_list", "params": []}' http://localhost:8550 -H "Content-Type: application/json" ``` This returns a JSON object with the account addresses in an array in the `result` field. ```json theme={null} {"jsonrpc": "2.0", "id": 0, "result": ["0x168bc315a2ee09042d83d7c5811b533620531f67", "0x0b85e5a13e118466159b1e1b6a4234e5f9f784bb"]} ``` The ordering of accounts when they are listed is lexicographic, but is effectively chronological based on time of creation due to the timestamp in the file name. It is safe to transfer the entire `keystore` directory or individual key files between Parallax nodes. This is important because when accounts are added from other nodes the order of accounts in the keystore may change. It is therefore important not to rely on account indexes in scripts or code snippets. Accounts can also be listed in the Javascript console using `eth.accounts`, which will defer to Clef for approval. As well as individual accounts, any wallets managed by Clef can be listed (which will also print the wallet status and the address and URl of any accounts they contain. This uses the `list-wallets` CLI command. ```sh theme={null} clef list-wallets --keystore ``` which returns: ``` - Wallet 0 at keystore:///home/user/Code/Parallax/testnet/keystore/UTC--2022-11-01T17-05-01.517877299Z--4f4094babd1a8c433e0f52a6ee3b6ff32dee6a9c (Locked ) - Account 0: 0x4f4094BaBd1A8c433e0f52A6ee3B6ff32dEe6a9c (keystore:///home/user/parallax/testnet/keystore/UTC--2022-11-01T17-05-01.517877299Z--4f4094babd1a8c433e0f52a6ee3b6ff32dee6a9c) - Wallet 1 at keystore:///home/user/parallax/testnet/keystore/UTC--2022-11-01T17-05-11.100536003Z--8ef15919f852a8034688a71d8b57ab0187364009 (Locked ) - Account 0: 0x8Ef15919F852A8034688a71d8b57Ab0187364009 (keystore:///home/user/parallax/testnet/keystore/UTC--2022-11-01T17-05-11.100536003Z--8ef15919f852a8034688a71d8b57ab0187364009) ``` ### Import a keyfile It is also possible to create an account by importing an existing private key. For example, a user might already have some Laxes at an address they created using a browser wallet and now wish to use a new Parallax node to interact with their funds. In this case, the private key can be exported from the browser wallet and imported into the Parallax client. It is possible to do this using Clef, but currently the method is not externally exposed and requires implementing a UI. There is a Python UI on the Parallax GitHub that could be used as an example or it can be done using the default console UI. However, for now, the most straightforward way to import an account from a private key is to use `parallax-wallet import`. `parallax-wallet` requires the private key to be stored as a file which contains the private key as unencrypted canonical elliptic curve bytes encoded into hex (i.e. plain text key without leading 0x). The new account is then saved in encrypted format, protected by a passphrase the user provides on request. As always, this passphrase must be securely and safely backed up - there is no way to retrieve or reset it if it is forgotten! ```sh theme={null} parallax-wallet import --datadir /some-dir ./keyfile ``` The following information will be displayed in the terminal, indicating a successful import: ``` Please enter a passphrase now. Passphrase: Repeat Passphrase: Address: {7f444580bfef4b9bc7e14eb7fb2a029336b07c9d} ``` This import/export process is **not necessary** for users transferring accounts between the Parallax client instances because the key files can simply be copied directly from one keystore to another. It is also possible to import an account in non-interactive mode by saving the account password as plaintext in a `.txt` file and passing its path with the `--password` flag on startup. ```sh theme={null} parallax-wallet import --password path/password.txt path/keyfile ``` In this case, it is important to ensure the password file is not readable by anyone but the intended user. This can be achieved by changing the file permissions. On Linux, the following commands update the file permissions so only the current user has access: ```sh theme={null} chmod 700 /path/to/password cat > /path/to/password ``` ## Updating accounts Clef can be used to set and remove passwords for an existing keystore file. To set a new password, pass the account address to setpw: ```sh theme={null} clef setpw a94f5374fce5edbc8e2a8697c15331677e6ebf0b ``` This will cause Clef to prompt for a new password, twice, and then the Clef master password to decrypt the keyfile. The `parallax-wallet update` subcommand can also be used to update the account password: ```sh theme={null} parallax-wallet update a94f5374fce5edbc8e2a8697c15331677e6ebf0b ``` Alternatively, in non-interactive mode the path to a password file containing the account password in unencrypted plaintext can be passed with the `--password` flag: ```sh theme={null} parallax-wallet update a94f5374fce5edbc8e2a8697c15331677e6ebf0b --password path/password.txt ``` Updating the account using `parallax-wallet update` replaces the original file with a new one - this means the original file is no longer available after it has been updated. This can be used to update a key file to the latest format. ## Unlocking accounts With Clef, indiscriminate account unlocking is no longer a feature. Instead, Clef unlocks are locked until actions are explicitly approved manually by a user, unless they conform to some specific scenario that has been encoded in a ruleset. Please refer to our Clef docs for instructions for how to create rulesets. ### Transactions Transactions can be sent using raw JSON requests to the Parallax client or using web3js in the Javascript console. Either way, with Clef acting as the signer the transactions will not get sent until approval is given in Clef. The following code snippet shows how a transaction could be sent between two accounts in the keystore using the Javascript console. ```sh theme={null} var tx = {from: eth.accounts[1], to: eth.accounts[2], value: web3.toWei(5, "ether")} # this will hang until approval is given in the Clef console eth.sendTransaction(tx) ``` ## Summary This page has demonstrated how to manage accounts using Clef and Parallax client's account management tools. Accounts are stored encrypted by a password. It is critical that the account passwords and the keystore directory are safely and securely backed up. *** *Adapted from [Account Management with Clef](https://geth.ethereum.org/docs/fundamentals/account-management) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Backup and restore Source: https://docs.parallaxprotocol.org/client/fundamentals/backup-and-restore **Keep secure backups of your keystore and password!** ## Data Directory All data relating to a specific Parallax client instance gets written inside a data directory. The default data directory locations are platform specific: * Mac: \~/Library/Parallax * Linux: \~/.parallax * Windows: %LOCALAPPDATA%\Parallax Accounts are stored in the keystore subdirectory. The contents of this directories should be transportable between nodes, platforms, and client implementations. To configure the location of the data directory, the `--datadir` parameter can be specified. See [CLI Options](/client/fundamentals/cli) for more details. There may exist multiple data directories for multiple networks (e.g. a separate directory for Parallax Mainnet and testnet). Each would have subdirectories for their blockchain data and keystore. It is important to backup the files in the keystore securely. These files are encrypted using an account password. This needs to be securely backed up too. There is no way to decrypt the keys without the password! ## Cleanup The Parallax's blockchain and state databases can be removed with: ```sh theme={null} parallaxd removedb ``` This is useful for deleting an old chain and sync'ing to a new one. It only affects data directories that can be re-created on synchronisation and does not touch the keystore. Specifically, passing the `removedb` command with no arguments removes the full node state database, ancient database. ## Blockchain Import/Export Export the blockchain in binary format with: ```sh theme={null} parallaxd export ``` Or if you want to back up portions of the chain over time, a first and last block can be specified. For example, to back up the first epoch: ```sh theme={null} parallaxd export 0 29999 ``` Note that when backing up a partial chain, the file will be appended rather than truncated. Import binary-format blockchain exports with: ```sh theme={null} parallaxd import ``` And finally: **REMEMBER YOUR PASSWORD** and **BACKUP YOUR KEYSTORE**! *** *Adapted from [Backup & Restore](https://geth.ethereum.org/docs/fundamentals/backup-restore) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Command-line options Source: https://docs.parallaxprotocol.org/client/fundamentals/cli Parallax ships four binaries, mirroring Bitcoin Core's `bitcoind` / `bitcoin-cli` / `bitcoin-wallet` / `bitcoin` layout: * **`parallaxd`** — the full-node daemon. Runs the node, serves JSON-RPC over HTTP/WS/IPC, and hosts the account/chain/db/console subcommands used to bootstrap and maintain the node. * **`parallax-cli`** — the JSON-RPC client. Talks to a running `parallaxd` over its IPC socket (or `--rpc http://…`) and exposes a small set of ergonomic sugar commands (`info`, `peers`, `balance`, `sendraw`, …). * **`parallax-wallet`** — the offline wallet tool. Operates directly on keystore files on disk, never talks to a running node, and is covered in full on the [parallax-wallet](/client/tools/parallax-wallet) page. * **`parallax`** — a thin multi-call wrapper. `parallax node ` dispatches to `parallaxd`; `parallax rpc ` dispatches to `parallax-cli`; `parallax wallet ` dispatches to `parallax-wallet`. The full, authoritative command list for each binary is emitted by the binary itself: ```sh theme={null} parallaxd --help parallax-cli --help parallax-wallet --help parallax help ``` The rest of this page is a quick reference to help you decide which binary a given task belongs to. ## `parallaxd` — daemon subcommands Run under `parallaxd ` (or `parallax node `). These commands operate on local on-disk state (the datadir, keystore, chaindata) and generally do not require a running daemon. | Category | Commands | | - | - | | Blockchain | `init`, `import`, `export`, `import-preimages`, `export-preimages`, `dump`, `dumpgenesis` | | Accounts | `account` (list/new/update/import subcommands) | | Database | `db`, `removedb`, `snapshot` | | Console | `attach`, `console`, `js` | | XHash | `makecache`, `makedag` | | Misc | `dumpconfig`, `license`, `version`, `version-check` | Invoking `parallaxd` with no subcommand runs the node itself (the default action). ## `parallax-cli` — RPC sugar subcommands Run under `parallax-cli ` (or `parallax rpc `). Each of these issues a JSON-RPC call against a running `parallaxd`, auto-discovering the IPC socket at `/parallax.ipc` unless `--rpc` is given. | Category | Commands | | - | - | | Lifecycle | `start`, `stop`, `info`, `uptime`, `loglevel`, `trace` | | Chain | `chaininfo`, `blockcount`, `syncing`, `tip`, `getblock`, `getblockhash`, `getheader`, `gettx`, `getreceipt` | | Network | `netinfo`, `peers`, `addpeer`, `removepeer`, `addtrusted`, `removetrusted`, `addnode`, `removenode`, `addrbook-status`, `addrbook-resetkey`, `dialv2`, `setban`, `listbanned`, `clearbanned` | | Mempool | `mempool`, `mempool-content`, `sendraw` | | Accounts | `listaccounts`, `newaccount`, `balance`, `nonce`, `code`, `storage`, `unlock`, `lock`, `sign`, `sendtx` | | Gas | `gasprice`, `estimategas` | | Mining | `mining`, `startmining`, `stopmining`, `setcoinbase`, `setextra` | | Utilities | `decoderaw`, `toaddr`, `dbstats` | Output conventions match `bitcoin-cli`: object responses are pretty-printed JSON (2-space indent, HTML escaping disabled), scalar responses are bare values followed by a newline (so `$(parallax-cli blockcount)` is directly pipeable in shell scripts), and mutating commands print nothing on success. The global flag set for `parallax-cli` is intentionally tiny: | Flag | Purpose | | - | - | | `--datadir ` | Where to look for the IPC socket when `--rpc` is unset. Defaults to the platform's standard Parallax datadir. | | `--testnet` | Resolve paths relative to `/testnet/` instead of `/`. | | `--rpc ` | Override the endpoint. Accepts an IPC path or `http://`, `ws://` URL. | ## `parallax-wallet` — offline wallet subcommands Run under `parallax-wallet ` (or `parallax wallet `). Every command operates directly on files on disk — no running daemon is required or contacted — which makes the binary suitable for air-gapped, cold-signing workflows. | Category | Commands | | - | - | | Keystore directory | `list`, `new`, `update`, `import`, `info`, `dump`, `createfromdump` | | Single keyfile | `generate`, `inspect`, `changepassword`, `signmessage`, `verifymessage`, `signtx` | See the [parallax-wallet](/client/tools/parallax-wallet) page for flags, password handling and worked examples. ## `parallax` — wrapper ``` parallax node [args...] run the parallaxd full-node daemon parallax rpc [args...] send an RPC via parallax-cli parallax wallet [args...] run an offline wallet command via parallax-wallet parallax help show wrapper help parallax version print version information ``` The wrapper forwards every argument after `node`, `rpc` or `wallet` verbatim to the companion binary. On Unix it replaces itself with the target via `syscall.Exec`, so the companion's process signals, exit codes, and terminal attachment behave exactly as if it had been invoked directly. # Config files Source: https://docs.parallaxprotocol.org/client/fundamentals/config-files There are many flags and commands that can be provided to the Parallax client on startup to influence how your node will behave. It is often convenient to configure these options in a file rather than typing them out on the command line every time you start your node. This can be done using a simple shell script to start the Parallax client. There are also other configuration options that are not accessible from the command line but can be adjusted by providing the Parallax client with a config file. This gives access to lower level configuration that influences how some of client's internal components behave. ## Shell scripts The benefit of writing a shell script for starting a Parallax node is that it is more easily repeatable and you don't have to remember lots of syntax for making a node behave in a certain way. This is especially useful for running multiple nodes with their own specific configurations. To create a shell script, save the Parallax client startup commands in a shell file, prepended with `#!/bin/bash`. The contents of the file might look like this: ```sh theme={null} #! /bin/bash ./parallaxd --testnet --datadir testnet --http --http.api eth,net --metrics.expensive --metric.addr 127.0.0.1 --metrics.port 6060 ``` Save the file as (e.g.) start-parallax.sh. Then make the file executable using ```sh theme={null} chmod +x start-parallax.sh ``` Now you can start the Parallax client using this shell script instead of having to create the startup configuration from scratch each time: ```sh theme={null} ./start-parallax.sh ``` ## Config files It is also possible to tweak the deeper configuration via a config file. The config file is more complex than a shell script but it can touch parts of the internal configuration structure of the Parallax client that are not accessible through the command line interface. The config file should be a `.toml` file. A convenient way to create a config file is to get the Parallax client to create one for you and use it as a template. To do this, use the `dumpconfig` command, saving the result to a `.toml` file. Note that you also need to explicitly provide the `network_id` on the command line for the public testnet: ```sh theme={null} ./parallaxd --testnet dumpconfig > parallax-config.toml ``` You can change the values in this file and then pass it to the Parallax client on startup so that the node is configured exactly as you want it. To override an option specified in the configuration file, specify the same option on the command line. To run the Parallax client with the configuration defined in `parallax-config.toml`, pass the config file path to `--config`. The `network_id` is not persisted from the config file; it has to be explicitly defined on the command line on startup, for example: ``` ./parallaxd --testnet --config parallax-config.toml ``` ### Config file example The config file created using `dumpconfig` contains the following information (this example is for the testnet - Mainnet and other network configurations will be slightly different): ```toml theme={null} [Eth] NetworkId = 2110 SyncMode = "snap" EthDiscoveryURLs = [] SnapDiscoveryURLs = [] NoPruning = false NoPrefetch = false TxLookupLimit = 6307200 LightPeers = 100 UltraLightFraction = 75 DatabaseCache = 512 DatabaseFreezer = "" TrieCleanCache = 154 TrieCleanCacheJournal = "triecache" TrieCleanCacheRejournal = 3600000000000 TrieDirtyCache = 256 TrieTimeout = 3600000000000 SnapshotCache = 102 Preimages = false EnablePreimageRecording = false RPCGasCap = 50000000 RPCEVMTimeout = 5000000000 RPCTxFeeCap = 1e+05 [Eth.Miner] GasFloor = 0 GasCeil = 30000000 GasPrice = 1000000000 Recommit = 3000000000 Noverify = false [Eth.XHash] CacheDir = "xhash" CachesInMem = 2 CachesOnDisk = 3 CachesLockMmap = false DatasetDir = "/Users/andrepatta/Library/XHash" DatasetsInMem = 1 DatasetsOnDisk = 2 DatasetsLockMmap = false PowMode = 0 NotifyFull = false [Eth.TxPool] Locals = [] NoLocals = false Journal = "transactions.rlp" Rejournal = 3600000000000 PriceLimit = 1 PriceBump = 10 AccountSlots = 16 GlobalSlots = 5120 AccountQueue = 64 GlobalQueue = 1024 Lifetime = 10800000000000 [Eth.GPO] Blocks = 20 Percentile = 60 MaxHeaderHistory = 1024 MaxBlockHistory = 1024 MaxPrice = 500000000000 IgnorePrice = 2 [Eth.Istanbul] RequestTimeout = 10000 BlockPeriod = 5 ProposerPolicy = "id = 0\n" Epoch = 30000 AllowedFutureBlockTime = 5 [Node] DataDir = "/Users/andrepatta/Library/Parallax/testnet" IPCPath = "parallax.ipc" HTTPHost = "" HTTPPort = 8545 HTTPVirtualHosts = ["localhost"] HTTPModules = ["net", "web3", "eth"] AuthAddr = "localhost" AuthPort = 8551 AuthVirtualHosts = ["localhost"] WSHost = "" WSPort = 8546 WSModules = ["net", "web3", "eth"] GraphQLVirtualHosts = ["localhost"] [Node.P2P] MaxPeers = 50 NoDiscovery = false BootstrapNodes = ["enode://973089afc9ae8141a47b211cb48979bb1fd2cbf5f24c498b4aab93a7cee5fcb996c7badac0d3b8414608b113bb12b9b997ac5bea35dd7842149a3182e42dfe18@46.137.237.72:32110"] StaticNodes = [] TrustedNodes = [] ListenAddr = ":32110" EnableMsgEvents = false [Node.HTTPTimeouts] ReadTimeout = 30000000000 WriteTimeout = 30000000000 IdleTimeout = 120000000000 [Metrics] HTTP = "127.0.0.1" Port = 6060 InfluxDBEndpoint = "http://localhost:8086" InfluxDBDatabase = "parallax" InfluxDBUsername = "test" InfluxDBPassword = "test" InfluxDBTags = "host=localhost" InfluxDBToken = "test" InfluxDBBucket = "parallax" InfluxDBOrganization = "parallax" ``` *** *Adapted from [Config files](https://geth.ethereum.org/docs/fundamentals/config-files) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Connecting to peers Source: https://docs.parallaxprotocol.org/client/fundamentals/connecting-to-peers The default behaviour for the Parallax client is to connect to Parallax mainnet. However, the Parallax client can also connect to public testnets, [private networks](/client/fundamentals/private-networks) and [local testnets](/client/developers/dapp/developer-mode). For convenience, the the public testnet with long term support have their own command line flag. The Parallax client can connect to the testnet simply by passing: * `--testnet` **Note:** Network selection is not persisted from a config file. To connect to a pre-defined network you must always enable it explicitly, even when using the `--config` flag to load other configuration values. For example: ```sh theme={null} # Generate desired config file. You must specify testnet here. parallaxd --testnet --syncmode "full" ... dumpconfig > testnet.toml # Start Parallax client with given config file. Here too the testnet must be specified. parallaxd --testnet --config testnet.toml ``` ## Finding peers The Parallax client continuously attempts to connect to other nodes on the network until it has enough peers. If UPnP (Universal Plug and Play) is enabled at the router or Parallax is run on an Internet-facing server, it will also accept connections from other nodes. The Parallax client finds peers using the [discovery protocol](/protocol/advanced/networking/overview). In the discovery protocol, nodes exchange connectivity details and then establish sessions ([RLPx](https://github.com/ethereum/devp2p/blob/master/rlpx.md)). If the nodes support compatible sub-protocols they can start exchanging Parallax data [on the wire](/protocol/advanced/networking/overview). A new node entering the network for the first time gets introduced to a set of peers by a bootstrap node ("bootnode") whose sole purpose is to connect new nodes to peers. The endpoints for these bootnodes are hardcoded into the Parallax client but they can also be specified by providing the `--bootnode` flag along with comma-separated bootnode addresses in the form of [enodes](/protocol/advanced/networking/addresses) on startup. For example: ```sh theme={null} parallaxd --bootnodes enode://pubkey1@ip1:port1,enode://pubkey2@ip2:port2,enode://pubkey3@ip3:port3 ``` There are scenarios where disabling the discovery process is useful, for example for running a local test node or an experimental test network with known, fixed nodes. This can be achieved by passing the `--nodiscover` flag to the Parallax client at startup. Since v2.1.0, v2-native bootnode entries (both the hardcoded list and `--bootnodes` values) may also be plain `ip:port` pairs or Tor v3 onion addresses in the form `.onion:port` — no public key required, since the v2 handshake authenticates against whoever answers at the address. Onion entries are used only when the node has a Tor route configured. ## Connecting over Tor > [!NOTE] > > Tor support was added in v2.1.0. The client can route its connections through Tor, host an onion service so peers can reach it without any port forwarding, and run entirely inside Tor with `--onlynet=onion`. With a local Tor daemon exposing its control port, all of this is enabled by default — see [Running over Tor](/client/fundamentals/tor) for setup, flags, and verification. ## Connectivity problems There are occasions when the Parallax client simply fails to connect to peers. The common reasons for this are: * Local time might be incorrect. An accurate clock is required to participate in the Parallax network. The local clock can be resynchronized using commands such as `sudo ntpdate -s time.nist.gov` (this will vary depending on operating system). * Some firewall configurations can prohibit UDP traffic. The static nodes feature or `admin.addPeer()` on the console can be used to configure connections manually. * The public test network the Parallax client is connecting to might be deprecated or have a low number of active nodes that are hard to find. In this case, the best action is to switch to an alternative test network. ## Checking Connectivity The `net` module has two attributes that enable checking node connectivity from the [interactive Javascript console](/client/interacting-with-parallax/js-console). These are `net.listening` which reports whether the Parallax client node is listening for inbound requests, and `peerCount` which returns the number of active peers the node is connected to. ```javascript theme={null} > net.listening true > net.peerCount 4 ``` Functions in the `admin` module provide more information about the connected peers, including their IP address, port number, supported protocols etc. Calling `admin.peers` returns this information for all connected peers. ```javascript theme={null} > admin.peers [{ caps: ["parallax/66", "snap/1"], enode: "enode://c8d58742fef51a70267a916949cefd0d7ba5bdb75393bbfcbcbc959b3eebf16353ac15d1f7493d749f7f452ff2bec894b8a8c469306e247d265f4f305c5740f7@69.62.94.166:32110", id: "2048d5ae22f7206bc8ad6476a2918bd7558776b0438e0cde4eb579d5d85d8886", name: "Parallax/v0.1.1-stable-78d2f22b/linux-amd64/go1.25.1", network: { inbound: false, localAddress: "192.168.3.2:37772", remoteAddress: "69.62.94.166:32110", static: false, trusted: false }, protocols: { parallax: { difficulty: 286554849280, head: "0x39a519def2f7eb13b4bc6affa22d34acb6a70c4b52782b8173f9119d9a5e20a8", version: 66 }, snap: { version: 1 } } }, { caps: ["parallax/66", "snap/1"], enode: "enode://d3440cdb8f942e1f01dac2292b7a8f886831800e301c41cf943a4ba4c68e37513920cd94c421fa5e073ed7329d9c3194e3911c857b9ded1677a5234441d9950d@54.94.191.104:32110", id: "4dd1f03a46b51083b7fa10bda14a92ddd0c1e80ec1ef3320c229a098e5f81865", name: "Parallax/v0.1.1-stable-78d2f22b/linux-arm64/go1.25.1", network: { inbound: false, localAddress: "192.168.3.2:55992", remoteAddress: "54.94.191.104:32110", static: false, trusted: false }, protocols: { parallax: { difficulty: 286554849280, head: "0x39a519def2f7eb13b4bc6affa22d34acb6a70c4b52782b8173f9119d9a5e20a8", version: 66 }, snap: { version: 1 } } }] ``` The `admin` module also includes functions for gathering information about the local node rather than its peers. For example, `admin.nodeInfo` returns the name and connectivity details for the local node. ```javascript theme={null} > admin.nodeInfo { enode: "enode://df18e0e4fea492eef74787a67368ada6200f6ed8ab01a9b105904fac442d720591aa9ab87d33c42ad1abcf24cc3eed373c3eb8dbc0df29b206615cc80a949c94@127.0.0.1:32110", enr: "enr:-KO4QL1FbkA2y9yCx_bXLIXApQKUgPLiCrhszQfXQH6IoCqaJYKHXCBJHm6A0G7NpvJF-MLyr1cS8imBYdgcEigzUm6GAZmWB3qcg2V0aMfGhN4LIImAgmlkgnY0gmlwhH8AAAGJc2VjcDI1NmsxoQLfGODk_qSS7vdHh6ZzaK2mIA9u2KsBqbEFkE-sRC1yBYRzbmFwwIN0Y3CCfW6DdWRwgn1u", id: "6c0a4611b88067d29f43e764475ec3ce70de6139c7316b960deadd29203fa358", ip: "127.0.0.1", listenAddr: "[::]:32110", name: "Parallax/v0.1.1-stable-d9425677/linux-amd64/go1.25.1 X:nodwarf5", ports: { discovery: 32110, listener: 32110 }, protocols: { parallax: { config: { berlinBlock: 0, byzantiumBlock: 0, chainId: 2111, constantinopleBlock: 0, eip150Block: 0, eip150Hash: "0x0000000000000000000000000000000000000000000000000000000000000000", eip155Block: 0, eip158Block: 0, xhash: {...}, homesteadBlock: 0, istanbulBlock: 0, minDifficulty: 33554432, petersburgBlock: 0 }, difficulty: 286554849280, genesis: "0x2b0467e57fabfc5d8082765e7bbc1f6aad8f13ddd937142f51c85e3f7051be5f", head: "0x39a519def2f7eb13b4bc6affa22d34acb6a70c4b52782b8173f9119d9a5e20a8", network: 2111 }, snap: {} } } ``` ## Custom Networks It is often useful for developers to connect to private test networks rather than public testnets or Parallax mainnet. These sandbox environments allow block creation without competing against other miners, easy minting of test ether and give freedom to break things without real-world consequences. A private network is started by providing a value to `--networkid` that is not used by any other existing public network ([Chainlist](https://chainlist.org/)) and creating a custom `genesis.json` file. Detailed instructions for this are available on the [Private Networks page](/client/fundamentals/private-networks). ## Static nodes The Parallax client also supports static nodes. Static nodes are specific peers that are always connected to. The Parallax client reconnects to these peers automatically when it is restarted. Specific nodes are defined to be static nodes by adding their enode addresses to a config file. The easiest way to create this config file is to run: ```sh theme={null} parallaxd --datadir dumpconfig > config.toml ``` This will create `config.toml` in the current directory. The enode addresses for static nodes can then be added as a list to the `StaticNodes` field of the `Node.P2P` section in `config.toml`. When the Parallax client is started, pass `--config config.toml`. The relevant line in `config.toml` looks as follows: ```toml theme={null} StaticNodes = ["enode://f4642fa65af50cfdea8fa7414a5def7bb7991478b768e296f5e4a54e8b995de102e0ceae2e826f293c481b5325f89be6d207b003382e18a8ecba66fbaf6416c0@33.4.2.1:32110"] ``` Ensure the other lines in `config.toml` are also set correctly before starting the Parallax client, as passing `--config` instructs the client to get its configuration values from this file. An example of a complete `config.toml` file can be found [here](https://gist.github.com/jmcook1186/16db2f0feddb4bd0581ebb9ba867a47a). Static nodes can also be added at runtime in the Javascript console by passing an enode address to `admin.addPeer()`: ```javascript theme={null} admin.addPeer( 'enode://f4642fa65af50cfdea8fa7414a5def7bb7991478b768e296f5e4a54e8b995de102e0ceae2e826f293c481b5325f89be6d207b003382e18a8ecba66fbaf6416c0@33.4.2.1:32110' ); ``` ## Peer limit It is sometimes desirable to cap the number of peers the Parallax client will connect to in order to limit on the computational and bandwidth cost associated with running a node. By default, the limit is 50 peers, however, this can be updated by passing a value to `--maxpeers`: ```sh theme={null} parallaxd --maxpeers 15 ``` ## Trusted nodes Trusted nodes can be added to `config.toml` in the same way as for static nodes. Add the trusted node's enode address to the `TrustedNodes` field in `config.toml` before starting the Parallax client with `--config config.toml`. Nodes can be added using the `admin.addTrustedPeer()` call in the Javascript console and removed using `admin.removeTrustedPeer()` call. ```javascript theme={null} admin.addTrustedPeer( 'enode://f4642fa65af50cfdea8fa7414a5def7bb7991478b768e296f5e4a54e8b995de102e0ceae2e826f293c481b5325f89be6d207b003382e18a8ecba66fbaf6416c0@33.4.2.1:32110' ); ``` ## Summary The Parallax client connects to Parallax mainnet by default. However, this behaviour can be changed using combinations of command line flags and files. This page has described the various options available for connecting a Parallax node to the Parallax blockchain, public testnet and private networks. *** *Adapted from [Connecting To The Network](https://geth.ethereum.org/docs/fundamentals/peer-to-peer) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Daemon mode Source: https://docs.parallaxprotocol.org/client/fundamentals/daemon-mode The Parallax node can run in the foreground as an interactive process or detach into the background as a long-running daemon, in the same spirit as Bitcoin Core's `bitcoind -daemon` flag. The daemon lives in the `parallaxd` binary; `parallax-cli` is the companion client that talks to it over JSON-RPC. ## Foreground mode (default) Running `parallaxd` with no special flags starts the node attached to the terminal. Logs stream to stderr, `Ctrl-C` (SIGINT) or SIGTERM triggers a graceful shutdown. This is the mode you want during development or when running under a supervisor like systemd that expects the process to stay in the foreground. ```sh theme={null} parallaxd --datadir ~/.parallax ``` ## Background mode (`--daemon`) Passing `--daemon` detaches the process from the controlling terminal, redirects stdout and stderr to a log file inside the data directory, writes a PID file, and exits the parent process with status 0. The node continues running in its own session. ```sh theme={null} parallaxd --datadir ~/.parallax --daemon ``` Or use `parallax-cli start` as syntactic sugar — it execs the sibling `parallaxd` with `--daemon` appended and the same global flags forwarded: ```sh theme={null} parallax-cli --datadir ~/.parallax start # same as parallaxd --daemon parallax-cli --datadir ~/.parallax start /etc/parallax.toml # + --config ``` `parallax-cli start` looks for `parallaxd` next to the `parallax-cli` binary first, then falls back to `$PATH`. If you install the binaries under `/usr/local/bin/` (the default for the Dockerfile and release tarballs) both locations resolve correctly. On success the parent prints a single line before exiting: ``` parallax daemon started (pid 12345, logs: /home/user/.parallax/parallax.log) ``` ### What `--daemon` does under the hood * Re-executes the `parallaxd` binary with the same arguments and a sentinel environment variable (`PARALLAX_DAEMONIZED=1`) so the child knows not to daemonize again. * On Unix, places the child in its own session via `setsid(2)`, decoupling it from the controlling terminal's signal delivery. On Windows, the child is spawned with `DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP`. * Redirects the child's stdout and stderr to `/parallax.log` (append mode). * Closes stdin by binding it to `/dev/null`. * The child writes its own PID to the PID file after the node has finished starting up, and removes it on clean shutdown. ### Log file Stdout and stderr are redirected to: ``` /parallax.log ``` The file is opened in append mode, so successive daemon runs accumulate history. Rotate it externally (e.g. with `logrotate`) for long-running installations. ### PID file By default the PID file is: ``` /parallax.pid ``` You can override the location with `--pid`: ```sh theme={null} parallaxd --daemon --pid /var/run/parallax.pid ``` The PID file is removed automatically when the node shuts down cleanly. If the node crashes the file may be left behind; on the next `--daemon` start parallaxd checks whether the recorded PID is still alive (via `signal 0` on Unix) and either refuses to start if a live daemon is present or silently overwrites the stale file. ### Refusing to start when a daemon is already running ```sh theme={null} $ parallaxd --datadir ~/.parallax --daemon parallax daemon already running (pid 12345, pidfile /home/user/.parallax/parallax.pid) ``` This check only protects against accidental double-start within the same data directory. For multi-tenant setups pin distinct data directories or PID file paths per instance. ## Managing a running daemon `parallax-cli` talks to a running daemon over the IPC socket at `/parallax.ipc` — see [Command-line RPC](/client/interacting-with-parallax/command-line-rpc) for the full sugar-command list. The most relevant for daemon lifecycle management is `stop`: ```sh theme={null} parallax-cli --datadir ~/.parallax stop # → Parallax server stopping ``` Under the hood `parallax-cli stop` invokes the [`admin_stop`](/client/interacting-with-parallax/json-rpc-namespaces/admin#admin_stop) RPC method. You can also signal the process directly: ```sh theme={null} kill -TERM "$(cat ~/.parallax/parallax.pid)" ``` Both paths trigger the same graceful shutdown sequence: stop protocols, flush the transaction pool, persist the trie cache, close databases, remove the IPC socket and PID file. ## systemd example Daemon mode composes with systemd if you use `Type=forking` so the unit treats the parent exit as readiness: ```ini theme={null} [Unit] Description=Parallax node After=network-online.target Wants=network-online.target [Service] Type=forking PIDFile=/var/run/parallax.pid ExecStart=/usr/local/bin/parallaxd --datadir /var/lib/parallax --daemon --pid /var/run/parallax.pid ExecStop=/usr/local/bin/parallax-cli --datadir /var/lib/parallax stop Restart=on-failure User=parallax [Install] WantedBy=multi-user.target ``` For most modern setups, prefer `Type=simple` without `--daemon` — systemd already handles log capture (via the journal), PID tracking, and graceful shutdown. Use `--daemon` when integrating with init systems that expect a forking service, or for manual long-running setups without a supervisor. ## Flag reference | Flag | Description | | - | - | | `--daemon` | Detach and run the node as a background daemon. Logs redirect to `/parallax.log`. | | `--pid` | PID file path when running with `--daemon`. Defaults to `/parallax.pid`. | # Databases Source: https://docs.parallaxprotocol.org/client/fundamentals/databases The Parallax client divides its database into two parts. Recent blocks and state data are kept in quick-access storage, but older blocks and receipts ("ancients") are stored in a "freezer" database. The point of this separation is to minimise the dependency on expensive, sensitive SSDs, and instead push the less frequently-accessed data into a database that can be supported by cheaper and more durable drives. Storing less data in the faster LevelDB database also enables faster compactions and improves the database performance by allowing more state trie nodes to be held in active memory for a given cache-size. ## Recent blocks The Parallax client stores recent blocks in a LevelDB database. This is a persistent key-value store that can be queried very quickly. The LevelDB database is supposed to be run on top of a fast SSD hard disk so that the disk IO is not bottlenecked by the underlying hardware. In addition to basic storage, the LevelDB database supports batch writes and iterations over the keyspace in binary-alphabetical order. The database is periodically compacted to reduce the operational cost of accessing individual items. This is achieved by flattening the underlying data store for a given range of keys. Any deleted or overwritten items in that key range are removed and the surviving data is reorganised for efficiency. The Parallax client also tracks several performance metrics for the LevelDB database that can be monitored via the metrics subsystem. These are: | METER | FUNCTION | | - | - | | `compTimeMeter` | Meter for measuring the total time spent in database compaction | | `compReadMeter` | Meter for measuring the data read during compaction | | `compWriteMeter` | Meter for measuring the data written during compaction | | `writeDelayNMeter` | Meter for measuring the write delay number due to database compaction | | `writeDelayMeter` | Meter for measuring the write delay duration due to database compaction | | `diskSizeGauge` | Gauge for tracking the size of all the levels in the database | | `diskReadMeter` | Meter for measuring the effective amount of data read | | `diskWriteMeter` | Meter for measuring the effective amount of data written | | `memCompGauge` | Gauge for tracking the number of memory compaction | | `level0CompGauge` | Gauge for tracking the number of table compaction in level0 | | `nonlevel0CompGauge` | Gauge for tracking the number of table compaction in non0 level | | `seekCompGauge` | Gauge for tracking the number of table compaction caused by read opt | ## Freezer/ancients Older segments of the chain are moved out of the LevelDB database and into a freezer database. Nodes rarely need to access these files so IO speed is less important and the bulk of the chain data can be stored on a cheaper HDD. Once blocks pass some threshold age (90,000 blocks behind the head by default) the block and receipt data is flattened and saved as a raw binary blob of data along with an index entry file used for identification. The Parallax client also tracks some basic metrics relating to the ancients database that can be monitored: | METRIC | FUNCTION | | - | - | | `readMeter` | Meter for measuring the effective amount of data read | | `writeMeter` | Meter for measuring the effective amount of data written | | `sizeGauge` | Gauge for tracking the combined size of all freezer tables | The ancients data is saved entirely separately from the fast-access recent data, meaning it can be stored in a different location. The default location for the ancient chain segments is inside the `chaindata` directory, which is inside `datadir`, but it can be defined by passing `--datadir.ancient ` to the Parallax client on startup. The freezer is designed to have a read operation complexity of O(1), involving only a read for index items (6 bytes) and a read for the data. This design makes the freezer performant enough to run on a slow HDD disk, permitting people to run Parallax nodes without requiring a huge SSD. The ancient data can also be moved later by manually copying the directory to a new location and then starting the Parallax client passing the new path to `--datadir.ancient`. ## Using the freezer If the Parallax client cannot find the freezer, either because the database was deleted or because the Parallax client received an incorrect path, then the node becomes unstable. It is explicitly forbidden to start the Parallax client with an invalid path to the freezer. However, if the state database goes missing the Parallax client can rebuild all its indices based upon data from the freezer and then do a snap-sync on top of it to fill in the missing state data. This can be used to deliberately clean up a node. Passing `--datadir --removedb` starts the process. The Parallax client will ask whether it should delete the state database, the ancient database. Choosing to delete the state database only leaves the block bodies, receipts, headers etc intact in the freezer, meaning rebuilding the state will not include re-downloading data from the network. The Parallax client will then rebuild the state from the freezer reusing that existing block and receipt data. In doing so, unused data and accumulated junk data will be pruned from the state database. This process can take an hour or more. ## Unclean shutdowns If the Parallax client stops unexpectedly the database can be corrupted. This is known as an "unclean shutdown" and it can lead to a variety of problems for the node when it is restarted. It is always best to shut down the Parallax client gracefully, i.e. using a shutdown command such as `ctrl-c`, `docker stop -t 300 ` or `systemctl stop` (although please note that `systemctl stop` has a default timeout of 90s - if the Parallax client takes longer than this to gracefully shut down it will quit forcefully. Update the `TimeoutSecs` variable in `systemd.service` to override this value to something larger, at least 300s). This way, the Parallax client knows to write all relevant information into the database to allow the node to restart properly later. This can involve >1GB of information being written to the LevelDB database which can take several minutes. If an unexpected shutdown does occur, the `removedb` subcommand can be used to delete the state database and resync it from the ancient database. This should get the database back up and running. *** *Adapted from [Databases](https://geth.ethereum.org/docs/fundamentals/databases) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Logs Source: https://docs.parallaxprotocol.org/client/fundamentals/logs A Parallax node continually reports messages to the console allowing users to monitor Parallax's current status in real-time. The logs indicate when the Parallax client is running normally and indicates when some attention is required. However, reading these logs can be difficult for new users. This page will help to interpret the log messages to better understand what the Parallax is doing. Note that there are a large number of log messages covering a wide range of possible scenarios for a Parallax node. This page will only address a subset of commonly seen messages. For more, see the [Parallax GitHub](https://github.com/ParallaxProtocol/parallax/). Log messages are usually sufficiently self-describing that they do not require additional explanation. ## Configuring log messages Log messages are displayed to the console by default. The messages can be tuned to be more or less detailed by passing `--verbosity` and a value between `0` and `5` to the Parallax client at startup: ``` 0 = silent (no log messages) 1 = error (error messages only) 2 = warn (error messages and warnings only) 3 = info (error messages, warnings and normal activity logs) 4 = debug (all info plus additional messages for debugging) 5 = detail (all info plus detailed debugging messages) ``` The default is `--verbosity 3`. Log messages can also be redirected so they are saved to a text file instead of being displayed in the console. In Linux the syntax `>> 2>&1` redirects both `stdout` and `stderr` messages to ``. For example: ```sh theme={null} # saves detailed logs to path/parallax.log parallaxd --verbosity 5 >> /path/parallax.log 2>&1 ``` ### Startup When the Parallax client starts up it immediately reports a fairly long page of configuration details and status reports that allow the user to confirm the Parallax client is on the right network and operating in its intended modes. The basic structure of a log message is as follows: ```sh theme={null} MESSAGE_TYPE [MONTH-DAY][TIME] MESSAGE VALUE ``` Where `MESSAGE_TYPE` can be `INFO`, `WARN`, `ERROR` or `DEBUG`. These tags categorize log messages according to their purpose. `INFO` messages inform the user about the Parallax client's current configuration and status. `WARN` messages are for alerting the user to details that affect the way the Parallax client is running. `ERROR` messages are for alerting the user to problems. `DEBUG` is for messages that are relevant to troubleshooting or for developers working on the Parallax client. The messages displayed on startup break down as follows: ``` INFO [07-25|15:50:01.128] Starting Parallax testnet... INFO [07-25|15:50:01.129] Maximum peer count total=50 INFO [07-25|15:50:01.131] Set global gas cap cap=50,000,000 INFO [07-25|15:50:01.131] Allocated trie memory caches clean=154.00MiB dirty=256.00MiB INFO [07-25|15:50:01.131] Allocated cache and file handles database=/Users/andrepatta/Library/Parallax/testnet/parallax/chaindata cache=512.00MiB handles=5120 INFO [07-25|15:50:01.309] Opened ancient database database=/Users/andrepatta/Library/Parallax/testnet/parallax/chaindata/ancient readonly=false INFO [07-25|15:50:01.313] Persisted trie from memory database nodes=3 size=415.00B time="17.084µs" gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B INFO [07-25|15:50:01.314] Initialised chain configuration config="{ChainID: 2111 Homestead: 0 DAO: DAOSupport: true EIP150: 0 EIP155: 0 EIP158: 0 Byzantium: 0 Constantinople: 0 Petersburg: 0 Istanbul: 0, Muir Glacier: , Berlin: 0, London: 0, Arrow Glacier: , MergeFork: , Terminal TD: , Engine: XHash}" INFO [07-25|15:50:01.319] Initialising Parallax Protocol name=prl versions=[100] network=2110 dbversion=8 INFO [07-25|15:50:01.613] Loaded most recent local header number=2,669,522 hash=6b1a52..7fadf7 td=2,669,523 age=5d3h58m INFO [07-25|15:50:01.613] Loaded most recent local full block number=2,669,522 hash=6b1a52..7fadf7 td=2,669,523 age=5d3h58m INFO [07-25|15:50:01.613] Loaded most recent local fast block number=2,669,522 hash=6b1a52..7fadf7 td=2,669,523 age=5d3h58m INFO [07-25|15:50:01.613] Loaded last fast-sync pivot marker number=2,645,471 INFO [07-25|15:50:01.643] Loaded local transaction journal transactions=0 dropped=0 INFO [07-25|15:50:01.646] Regenerated local transaction journal transactions=0 accounts=0 ``` The logs above show the user that the node is connecting to Parallax testnet and some low level configuration details. The cache size is bumped to the Testnet default (4096). The maximum peer count is the highest number of peers this node is allowed to connect to and can be used to control the bandwidth requirements of the node. ``` INFO [07-25|15:50:01.650] Starting peer-to-peer node instance=eParallax/v1.0.0-stable-5be45479/darwin-arm64/go1.20.6 INFO [07-25|15:50:01.701] New local node record seq=1,689,703,084,530 id=695cfb779e4be582 ip=127.0.0.1 udp=41300 tcp=41300 INFO [07-25|15:50:01.701] Started P2P networking self=enode://666e25ebd14912ab79dd9bdf547bdb17981ab328f79517b0f8191109daaeef7c54f4dead8fb7777726dd7a599cedc16cf006961716be181ee37efddb47ef0383@127.0.0.1:41300 INFO [07-25|15:50:01.701] IPC endpoint opened url=/Users/andrepatta/Library/Parallax/testnet/parallax.ipc INFO [07-25|15:50:01.702] HTTP server started endpoint=127.0.0.1:8545 auth=false prefix= cors= vhosts=localhost INFO [07-25|15:50:01.702] WebSocket enabled url=ws://127.0.0.1:8546 ``` ### Syncing The default for the Parallax client is to sync in snap mode. The client requests block headers from its peers that are parents of the target until there is a continuous chain of sequential headers of sufficient length. Then, the Parallax client requests block bodies and receipts for each header and simultaneously starts downloading state data. This state data is stored in the form of a [Patricia Merkle Trie](/protocol/advanced/data-structures/patricia-trie). Only the leaves of the trie are downloaded, the full trie structure is then locally regenerated from the leaves up. Meanwhile, the blockchain continues to progress and the target header is updated. This means some of the regenerated state data need to be updated. This is known as *healing*. Assuming the Parallax client has some peers it will start importing headers, block bodies and receipts. The log messages for data downloading look as follows: ``` INFO [07-28|10:29:49.681] Block synchronisation started INFO [07-28|10:29:50.427] Imported new block headers count=1 elapsed=253.434ms number=12,914,945 hash=ee1a08..9ce38a INFO [07-28|10:30:00.224] Imported new block receipts count=64 elapsed=13.703s number=12,914,881 hash=fef964..d789fc age=18m5s size=7.69MiB INFO [07-28|10:30:18.658] Imported new block headers count=1 elapsed=46.715ms number=12,914,946 hash=7b24c8..2d8006 INFO [07-28|10:30:21.665] Imported new state entries ``` For state sync, the Parallax client reports when the state heal is in progress. This can take a long time. The log message includes values for the number of `accounts`, `slots`, `codes` and `nodes` that were downloaded in the current healing phase, and the pending field is the number of state entires waiting to be downloaded. The `pending` value is not necessarily the number of state entries remaining until the healing is finished. As the blockchain progresses the state trie is updated and therefore the data that need to be downloaded to heal the trie can increase as well as decrease over time. Ultimately, the state should heal faster than the blockchain progresses so the node can get in sync. When the state healing is finished there is a post-sync snapshot generation phase. The node is not in sync until the state healing phase is over. If the node is still regularly reporting `State heal in progress` it is not yet in sync - the state healing is still ongoing. ``` INFO [07-28|10:30:21.965] State heal in progress accounts=169,633@7.48MiB slots=57314@4.17MiB codes=4895@38.14MiB nodes=43,293,196@11.70GiB pending=112,626 INFO [09-06|01:31:59.885] Rebuilding state snapshot INFO [09-06|01:31:59.910] Resuming state snapshot generation root=bc64d4..fc1edd accounts=0 slots=0 storage=0.00B dangling=0 elapsed=18.838ms ``` The sync can be confirmed using [eth.syncing](/protocol/parallax-stack/apis/json-rpc) - it will return `false` if the node is in sync. If `eth.syncing` returns anything other than `false` it has not finished syncing. Generally, if syncing is still ongoing, `eth.syncing` will return block info that looks as follows: ```json theme={null} > eth.syncing { currentBlock: 15285946, healedBytecodeBytes: 991164713, healedBytecodes: 130880, healedTrienodeBytes: 489298493475, healedTrienodes: 1752917331, healingBytecode: 0, healingTrienodes: 1745, highestBlock: 16345003, startingBlock: 12218525, syncedAccountBytes: 391561544809, syncedAccounts: 136498212, syncedBytecodeBytes: 2414143936, syncedBytecodes: 420599, syncedStorage: 496503178, syncedStorageBytes: 103368240246 } ``` There are other log messages that are commonly seen during syncing. For example: ```sh theme={null} WARN [09-28|11:06:01.363] Snapshot extension registration failed ``` This warning is nothing to worry about - it is reporting a configuration mismatch between the node and a peer. It does not mean syncing is stalling or failing, it simply results in the peer being dropped and replaced. ## Transaction logs Transactions submitted over local IPC, Websockets or HTTP connections are reported in the console logs. For example, a simple transaction appears in the console logs as follows: ```sh theme={null} INFO [09-06|01:31:59.910] Submitted transaction hash=0x2893b70483bf1791b550e5a93763058b0abf7c6d9e6201e07212dbc64d4764532 from: 0xFB48587362536C606d6e89f717Fsd229673246e6 nonce: 43 recipient: 0x7C60662d63536e89f717F9673sd22246F6eB4858 value: 100,000,000,000,000,000 ``` Other user actions have similar log messages that are displayed to the console. ## Common warnings There are many warnings that can be emitted by the Parallax client as part of its normal operation. ```sh theme={null} WARN [10-03|18:00:40.413] Unexpected trienode heal packet peer=9f0e8fbf reqid=6,915,308,639,612,522,441 ``` The above is often seen and misinterpreted as a problem with snap sync. In reality, it indicates a request timeout that may be because I/O speed is low. It is usually not an issue, but if this message is seen very often over prolonged periods of time it might be rooted in a local connectivity or hardware issue. ```sh theme={null} WARN [10-03 | 13:15:56.543] Dropping unsynced node during sync id = e2fdc0d92d70953 conn = ... ``` This message indicates that a peer is being dropped because it is not fully synced. This is normal - the necessary data will be requested from an alternative peer instead. ## Summary There are a wide range of log messages that are emitted while the Parallax client is running. The level of detail in the logs can be configured using the `verbosity` flag at startup. This page has outlined some of the common messages users can expect to see when the Parallax client is run with default verbosity, without attempting to be comprehensive. *** *Adapted from [Geth logs](https://geth.ethereum.org/docs/fundamentals/logs) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Private networks Source: https://docs.parallaxprotocol.org/client/fundamentals/private-networks This guide explains how to set up a private network of multiple Parallax client nodes. A Parallax network is private if the nodes are not connected to the main network. In this context private only means reserved or isolated, rather than protected or secure. A fully controlled, private Parallax network is useful as a backend for core developers working on issues relating to networking/blockchain syncing etc. Private networks are also useful for Dapp developers testing multi-block and multi-user scenarios. ## Prerequisites To follow the tutorial on this page it is necessary to have a working Parallax client installation (instructions [here](/client/getting-started/installing-client)). It is also helpful to understand the Parallax client fundamentals (see [Getting Started](/client/getting-started/introduction)). ## Private Networks A private network is composed of multiple Parallax nodes that can only connect to each other. In order to run multiple nodes locally, each one requires a separate data directory (`--datadir`). The nodes must also know about each other and be able to exchange information, share an initial state and a common consensus algorithm. The remainder of this page will explain how to configure the Parallax client so that these basic requirements are met, enabling a private network to be started. ### Choosing A Network ID The Parallax mainnet has Network ID = 2110. There are also many other networks that the Parallax client can connect to by providing alternative Chain IDs, some are testnets and others are alternative networks built from forks of the Parallax client source code. Providing a network ID that is not already being used by an existing network or testnet means the nodes using that network ID can only connect to each other, creating a private network. A list of current network IDs is available at [Chainlist.org](https://chainlist.org/). The network ID is controlled using the `networkid` flag, e.g. ```sh theme={null} parallaxd --networkid 12345 ``` ### Choosing A Consensus Algorithm #### **XHash** Parallax's PoW algorithm, XHash, is a system that allows open participation by anyone willing to dedicate resources to mining. While this is a critical property for a public network, the overall security of the blockchain strictly depends on the total amount of resources used to secure it. As such, PoW is a poor choice for private networks with few miners. The XHash mining 'difficulty' is adjusted automatically so that new blocks are created approximately 10 minutes apart. As more mining resources are deployed on the network, creating a new block becomes harder so that the average block time matches the target block time. #### **Clique** Clique consensus is a PoA system where new blocks can be created by authorized 'signers' only. The clique consensus protocol is specified in [EIP-225](https://eips.ethereum.org/EIPS/eip-225). The initial set of authorized signers is configured in the genesis block. Signers can be authorized and de-authorized using a voting mechanism, thus allowing the set of signers to change while the blockchain operates. Clique can be configured to target any block time (within reasonable limits) since it isn't tied to the difficulty adjustment. ### Creating The Genesis Block Every blockchain starts with a genesis block. When the Parallax client is run with default settings for the first time, it commits the Mainnet genesis to the database. For a private network, it is generally preferable to use a different genesis block. The genesis block is configured using a *`genesis.json`* file whose path must be provided to the Parallax client on start-up. When creating a genesis block, a few initial parameters for the private blockchain must be defined: * Parallax platform features enabled at launch (config). Enabling and disabling features once the blockchain is running requires scheduling a [hard fork](https://ethereum.org/en/glossary/#hard-fork). * Initial block gas limit (gasLimit). This impacts how much EVM computation can happen within a single block. Mirroring the main Parallax network is generally a good choice. The block gas limit can be adjusted after launch using the `--miner.gaslimit` command-line flag. * Initial allocation of LAX (alloc). This determines how much Laxes is available to the addresses listed in the genesis block. Additional Laxes can be created through mining as the chain progresses. #### **Clique Example** Below is an example of a `genesis.json` file for a PoA network. The config section ensures that all known protocol changes are available and configures the 'clique' engine to be used for consensus. Note that the initial signer set must be configured through the `extradata` field. This field is required for Clique to work. The signer account keys can be generated using the [Parallax account](/client/fundamentals/account-management) command (this command can be run multiple times to create more than one signer key). ```sh theme={null} parallax-wallet new --datadir data ``` The Parallax address printed by this command should be recorded. To encode the signer addresses in `extradata`, concatenate 32 zero bytes, all signer addresses and 65 further zero bytes. The result of this concatenation is then used as the value accompanying the `extradata` key in `genesis.json`. In the example below, `extradata` contains a single initial signer address, `0x7df9a875a174b3bc565e6424a0050ebc1b2d1d82`. The `period` configuration option sets the target block time of the chain. ```json theme={null} { "config": { "chainId": 12345, "homesteadBlock": 0, "eip150Block": 0, "eip155Block": 0, "eip158Block": 0, "byzantiumBlock": 0, "constantinopleBlock": 0, "petersburgBlock": 0, "istanbulBlock": 0, "berlinBlock": 0, "clique": { "period": 5, "epoch": 30000 } }, "difficulty": "1", "gasLimit": "8000000", "extradata": "0x00000000000000000000000000000000000000000000000000000000000000007df9a875a174b3bc565e6424a0050ebc1b2d1d820000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "alloc": { "7df9a875a174b3bc565e6424a0050ebc1b2d1d82": { "balance": "300000" }, "f41c74c9ae680c1aa78f42e5647a62f353b7bdde": { "balance": "400000" } } } ``` #### **XHash Example** Since XHash is the default consensus algorithm, no additional parameters need to be configured in order to use it. The initial mining difficulty is influenced using the difficulty parameter, but note that the difficulty adjustment algorithm will quickly adapt to the amount of mining resources deployed on the chain. ```json theme={null} { "config": { "chainId": 12345, "homesteadBlock": 0, "eip150Block": 0, "eip155Block": 0, "eip158Block": 0, "byzantiumBlock": 0, "constantinopleBlock": 0, "petersburgBlock": 0, "istanbulBlock": 0, "berlinBlock": 0, "xhash": {} }, "difficulty": "1", "gasLimit": "8000000", "alloc": { "7df9a875a174b3bc565e6424a0050ebc1b2d1d82": { "balance": "300000" }, "f41c74c9ae680c1aa78f42e5647a62f353b7bdde": { "balance": "400000" } } } ``` ### Initialising the Parallax Client Database To create a blockchain node that uses this genesis block, first use `parallaxd init` to import and sets the canonical genesis block for the new chain. This requires the path to `genesis.json` to be passed as an argument. ```sh theme={null} parallaxd init --datadir data genesis.json ``` When the Parallax client is started using `--datadir` data the genesis block defined in `genesis.json` will be used. For example: ```sh theme={null} parallaxd --datadir data --networkid 12345 ``` ### Scheduling Hard Forks As the Parallax protocol development progresses, new features become available. To enable these features on an existing private network, a hard fork must be scheduled. To do this, a future block number must be chosen which determines precisely when the hard fork will activate. Continuing the `genesis.json` example above and assuming the current block number is 35421, a hard fork might be scheduled for block 40000. This hard fork might upgrade the network to conform to the 'London' specs. First, all the Parallax client instances on the private network must be recent enough to support the specific hard fork. If so, `genesis.json` can be updated so that the `londonBlock` key gets the value 40000. The Parallax client instances are then shut down and `parallaxd init` is run to update their configuration. When the nodes are restarted they will pick up where they left off and run normally until block 40000, at which point they will automatically upgrade. The modification to `genesis.json` is as follows: ```json theme={null} { "config": { "londonBlock": 40000 } } ``` The upgrade command is: ```sh theme={null} parallaxd init --datadir data genesis.json ``` ### Setting Up Networking With the node configured and initialised, the next step is to set up a peer-to-peer network. This requires a bootstrap node. The bootstrap node is a normal node that is designated to be the entry point that other nodes use to join the network. Any node can be chosen to be the bootstrap node. To configure a bootstrap node, the IP address of the machine the bootstrap node will run on must be known. The bootstrap node needs to know its own IP address so that it can broadcast it to other nodes. On a local machine this can be found using tools such as `ifconfig` and on cloud instances such as Amazon EC2 the IP address of the virtual machine can be found in the management console. Any firewalls must allow UDP and TCP traffic on port `32110`. The bootstrap node IP is set using the `--nat` flag (the command below contains an example address - replace it with the correct one). ```sh theme={null} parallaxd --datadir data --networkid 15 --nat extip:172.16.254.4 ``` The 'node record' of the bootnode can be extracted using the JS console: ```sh theme={null} parallaxd attach --exec admin.nodeInfo.enr data/parallax.ipc ``` This command should print a base64 string such as the following example. Other nodes will use the information contained in the bootstrap node record to connect to the peer-to-peer network. ``` "enr:-Je4QEiMeOxy_h0aweL2DtZmxnUMy-XPQcZllrMt_2V1lzynOwSx7GnjCf1k8BAsZD5dvHOBLuldzLYxpoD5UcqISiwDg2V0aMfGhGlQhqmAgmlkgnY0gmlwhKwQ_gSJc2VjcDI1NmsxoQKX_WLWgDKONsGvxtp9OeSIv2fRoGwu5vMtxfNGdut4cIN0Y3CCdl-DdWRwgnZf" ``` If the nodes are intended to connect across the Internet, the bootnode and all other nodes must have public IP addresses assigned, and both TCP and UDP traffic can pass their firewalls. If Internet connectivity is not required or all member nodes connect using well-known IPs, the Parallax client should be set up to restrict peer-to-peer connectivity to an IP subnet. Doing so will further isolate the network and prevents cross-connecting with other blockchain networks in case the nodes are reachable from the Internet. Use the `--netrestrict` flag to configure a whitelist of IP networks: ```sh theme={null} parallaxd --netrestrict 172.16.254.0/24 ``` With the above setting, the Parallax client will only allow connections from the 172.16.254.0/24 subnet, and will not attempt to connect to other nodes outside of the set IP range. ### Running Member Nodes Before running a member node, it must be initialized with the same genesis file as used for the bootstrap node. With the bootnode operational and externally reachable (`telnet ` will confirm that it is indeed reachable), more Parallax nodes can be started and connected to them via the bootstrap node using the `--bootnodes` flag. The process is to start the Parallax client on the same machine as the bootnode, with a separate data directory and listening port and the bootnode node record provided as an argument: For example, using data directory (example: data2) and listening port (example: 30305): ```sh theme={null} parallaxd --datadir data2 --networkid 12345 --port 30305 --bootnodes ``` With the member node running, it is possible to check that it is connected to the bootstrap node or any other node in the network by attaching a console and running `admin.peers`. It may take up to a few seconds for the nodes to get connected. ```sh theme={null} parallaxd attach data2/parallax.ipc --exec admin.peers ``` ### Running A Signer (Clique) To set up the Parallax client for signing blocks in Clique, a signer account must be available. The account must already be available as a keyfile in the keystore. To use it for signing blocks, it must be unlocked. The following command, for address `0x7df9a875a174b3bc565e6424a0050ebc1b2d1d82` will prompt for the account password, then start signing blocks: ```sh theme={null} parallaxd --unlock 0x7df9a875a174b3bc565e6424a0050ebc1b2d1d82 --mine ``` Mining can be further configured by changing the default gas limit blocks converge to (with `--miner.gaslimit`) and the price transactions are accepted at (with `--miner.gasprice`). ### Running A Miner (XHash) For PoW in a simple private network, a single CPU miner instance is enough to create a stable stream of blocks at regular intervals. To start a Parallax client instance for mining, it can be run with all the usual flags plus the following to configure mining: ```sh theme={null} parallaxd --mine --miner.threads=1 --miner.coinbase=0xf41c74c9ae680c1aa78f42e5647a62f353b7bdde ``` This will start mining bocks and transactions on a single CPU thread, crediting all block rewards to the account specified by `--miner.coinbase`. ## End-to-end example This section will run through the commands for setting up a simple private network of two nodes. Both nodes will run on the local machine using the same genesis block and network ID. The data directories for each node will be named node1 and node2. ```sh theme={null} `mkdir node1 node2` ``` Each node will have an associated account that will receive some ether at launch. The following command creates an account for Node 1: ```sh theme={null} parallax-wallet --datadir node1 new ``` This command returns a request for a password. Once a password has been provided the following information is returned to the terminal: ``` Your new account is locked with a password. Please give a password. Do not forget this password. Password: Repeat password: Your new key was generated Public address of the key: 0xC1B2c0dFD381e6aC08f34816172d6343Decbb12b Path of the secret key file: node1/keystore/UTC--2022-05-13T14-25-49.229126160Z--c1b2c0dfd381e6ac08f34816172d6343decbb12b - You can share your public address with anyone. Others need it to interact with you. - You must NEVER share the secret key with anyone! The key controls access to your funds! - You must BACKUP your key file! Without the key, it's impossible to access account funds! - You must remember your password! Without the password, it's impossible to decrypt the key! ``` The keyfile and account password should be backed up securely. These steps can then be repeated for Node 2. These commands create keyfiles that are stored in the `keystore` directory in `node1` and `node2` data directories. In order to unlock the accounts later the passwords for each account should be saved to a text file in each node's data directory. In each data directory save a copy of the following `genesis.json` to the top level project directory. The account addresses in the `alloc` field should be replaced with those created for each node in the previous step (without the leading 0x). ```json theme={null} { "config": { "chainId": 12345, "homesteadBlock": 0, "eip150Block": 0, "eip155Block": 0, "eip158Block": 0, "byzantiumBlock": 0, "constantinopleBlock": 0, "petersburgBlock": 0, "istanbulBlock": 0, "muirGlacierBlock": 0, "berlinBlock": 0, "londonBlock": 0, "arrowGlacierBlock": 0, "grayGlacierBlock": 0, "clique": { "period": 5, "epoch": 30000 } }, "difficulty": "1", "gasLimit": "800000000", "extradata": "0x00000000000000000000000000000000000000000000000000000000000000007df9a875a174b3bc565e6424a0050ebc1b2d1d820000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "alloc": { "C1B2c0dFD381e6aC08f34816172d6343Decbb12b": { "balance": "500000" }, "c94d95a5106270775351eecfe43f97e8e75e59e8": { "balance": "500000" } } } ``` The nodes can now be set up using `parallaxd init` as follows: ```sh theme={null} parallaxd init --datadir node1 genesis.json ``` This should be repeated for both nodes. The following will be returned to the terminal: ``` INFO [05-13|15:41:47.520] Maximum peer count total=50 INFO [05-13|15:41:47.520] Smartcard socket not found, disabling err="stat /run/pcscd/pcscd.comm: no such file or directory" INFO [05-13|15:41:47.520] Set global gas cap cap=50,000,000 INFO [05-13|15:41:47.520] Allocated cache and file handles database=/home/parallax/node2/parallax/chaindata cache=16.00MiB handles=16 INFO [05-13|15:41:47.542] Writing custom genesis block INFO [05-13|15:41:47.542] Persisted trie from memory database nodes=3 size=397.00B time="41.246µs" gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B INFO [05-13|15:41:47.543] Successfully wrote genesis state database=chaindata hash=c9a158..d415a0 INFO [05-13|15:41:47.543] Allocated cache and file handles database=/home/parallax/node2/parallax/chaindata cache=16.00MiB handles=16 INFO [05-13|15:41:47.556] Writing custom genesis block INFO [05-13|15:41:47.557] Persisted trie from memory database nodes=3 size=397.00B time="81.801µs" gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B INFO [05-13|15:41:47.558] Successfully wrote genesis state database=chaindata hash=c9a158..d415a0 ``` The next step is to configure a bootnode. This can be any node, but for this tutorial the developer tool `bootnode` will be used to quickly and easily configure a dedicated bootnode. First the bootnode requires a key, which can be created with the following command, which will save a key to boot.key: ```sh theme={null} bootnode -genkey boot.key ``` This key can then be used to generate a bootnode as follows: ```sh theme={null} bootnode -nodekey boot.key -addr :30305 ``` The choice of port passed to `-addr` is arbitrary, but public Parallax networks use 32110, so this is best avoided. The bootnode command returns the following logs to the terminal, confirming that it is running: ``` enode://f7aba85ba369923bffd3438b4c8fde6b1f02b1c23ea0aac825ed7eac38e6230e5cadcf868e73b0e28710f4c9f685ca71a86a4911461637ae9ab2bd852939b77f@127.0.0.1:0?discport=30305 Note: you're using cmd/bootnode, a developer tool. We recommend using a regular node as bootstrap node for production deployments. INFO [05-13|15:50:03.645] New local node record seq=1,652,453,403,645 id=a2d37f4a7d515b3a ip=nil udp=0 tcp=0 ``` The two nodes can now be started. Open separate terminals for each node, leaving the bootnode running in the original terminal. In each terminal, run the following command (replacing `node1` with `node2` where appropriate, and giving each node different `--port` and `authrpc.port` IDs). The account address and password file for `node` 1 must also be provided: ```sh theme={null} ./parallaxd --datadir node1 --port 30306 --bootnodes enode://f7aba85ba369923bffd3438b4c8fde6b1f02b1c23ea0aac825ed7eac38e6230e5cadcf868e73b0e28710f4c9f685ca71a86a4911461637ae9ab2bd852939b77f@127.0.0.1:0?discport=30305 --networkid 123454321 --unlock 0xC1B2c0dFD381e6aC08f34816172d6343Decbb12b --password node1/password.txt --authrpc.port 8551 ``` This will start the node using the bootnode as an entry point. Repeat the same command with the information appropriate to node 2. In each terminal, the following logs indicate success: ``` INFO [05-13|16:17:40.061] Maximum peer count total=50 INFO [05-13|16:17:40.061] Smartcard socket not found, disabling err="stat /run/pcscd/pcscd.comm: no such file or directory" INFO [05-13|16:17:40.061] Set global gas cap cap=50,000,000 INFO [05-13|16:17:40.061] Allocated trie memory caches clean=154.00MiB dirty=256.00MiB INFO [05-13|16:17:40.061] Allocated cache and file handles database=/home/parallax/node1/parallax/chaindata cache=512.00MiB handles=524,288 INFO [05-13|16:17:40.094] Opened ancient database database=/home/parallax/node1/parallax/chaindata/ancient readonly=false INFO [05-13|16:17:40.095] Initialised chain configuration config="{ChainID: 123454321 Homestead: 0 DAO: nil DAOSupport: false EIP150: 0 EIP155: 0 EIP158: 0 Byzantium: 0 Constantinople: 0 Petersburg: 0 Istanbul: nil, Muir Glacier: nil, Berlin: nil, London: nil, Arrow Glacier: nil, MergeFork: nil, Terminal TD: nil, Engine: clique}" INFO [05-13|16:17:40.096] Initialising Parallax protocol network=123,454,321 dbversion=8 INFO [05-13|16:17:40.098] Loaded most recent local header number=0 hash=c9a158..d415a0 td=1 age=53y1mo2w INFO [05-13|16:17:40.098] Loaded most recent local full block number=0 hash=c9a158..d415a0 td=1 age=53y1mo2w INFO [05-13|16:17:40.098] Loaded most recent local fast block number=0 hash=c9a158..d415a0 td=1 age=53y1mo2w INFO [05-13|16:17:40.099] Loaded local transaction journal transactions=0 dropped=0 INFO [05-13|16:17:40.100] Regenerated local transaction journal transactions=0 accounts=0 INFO [05-13|16:17:40.100] Gasprice oracle is ignoring threshold set threshold=2 WARN [05-13|16:17:40.100] Unclean shutdown detected booted=2022-05-13T16:16:46+0100 age=54s INFO [05-13|16:17:40.100] Starting peer-to-peer node instance=Parallax/v1.0.0-unstable-8d84a701-20220503/linux-amd64/go1.18.1 INFO [05-13|16:17:40.130] New local node record seq=1,652,454,949,228 id=f1364e6d060c4625 ip=127.0.0.1 udp=30306 tcp=30306 INFO [05-13|16:17:40.130] Started P2P networking self=enode://87606cd0b27c9c47ca33541d4b68cf553ae6765e22800f0df340e9788912b1e3d2759b3d1933b6f739c720701a56ce26f672823084420746d04c25fc7b8c6824@127.0.0.1:30306 INFO [05-13|16:17:40.133] IPC endpoint opened url=/home/parallax/node1/parallax.ipc INFO [05-13|16:17:40.785] Unlocked account address=0xC1B2c0dFD381e6aC08f34816172d6343Decbb12b INFO [05-13|16:17:42.636] New local node record seq=1,652,454,949,229 id=f1364e6d060c4625 ip=82.11.59.221 udp=30306 tcp=30306 INFO [05-13|16:17:43.309] Mapped network port proto=tcp extport=30306 intport=30306 interface="UPNP IGDv1-IP1" INFO [05-13|16:17:43.822] Mapped network port proto=udp extport=30306 intport=30306 interface="UPNP IGDv1-IP1" [05-13|16:17:50.150] Looking for peers peercount=0 tried=0 static=0 INFO [05-13|16:18:00.164] Looking for peers peercount=0 tried=0 static=0 ``` In the first terminal that is currently running the logs resembling the following will be displayed, showing the discovery process in action: ``` INFO [05-13|15:50:03.645] New local node record seq=1,652,453,403,645 id=a2d37f4a7d515b3a ip=nil udp=0 tcp=0 TRACE[05-13|16:15:49.228] PING/v4 id=f1364e6d060c4625 addr=127.0.0.1:30306 err=nil TRACE[05-13|16:15:49.229] PONG/v4 id=f1364e6d060c4625 addr=127.0.0.1:30306 err=nil TRACE[05-13|16:15:49.229] PING/v4 id=f1364e6d060c4625 addr=127.0.0.1:30306 err=nil TRACE[05-13|16:15:49.230] PONG/v4 id=f1364e6d060c4625 addr=127.0.0.1:30306 err=nil TRACE[05-13|16:15:49.730] FINDNODE/v4 id=f1364e6d060c4625 addr=127.0.0.1:30306 err=nil TRACE[05-13|16:15:49.731] NEIGHBORS/v4 id=f1364e6d060c4625 addr=127.0.0.1:30306 err=nil TRACE[05-13|16:15:50.231] FINDNODE/v4 id=f1364e6d060c4625 addr=127.0.0.1:30306 err=nil TRACE[05-13|16:15:50.231] NEIGHBORS/v4 id=f1364e6d060c4625 addr=127.0.0.1:30306 err=nil TRACE[05-13|16:15:50.561] FINDNODE/v4 id=f1364e6d060c4625 addr=127.0.0.1:30306 err=nil TRACE[05-13|16:15:50.561] NEIGHBORS/v4 id=f1364e6d060c4625 addr=127.0.0.1:30306 err=nil TRACE[05-13|16:15:50.731] FINDNODE/v4 id=f1364e6d060c4625 addr=127.0.0.1:30306 err=nil TRACE[05-13|16:15:50.731] NEIGHBORS/v4 id=f1364e6d060c4625 addr=127.0.0.1:30306 err=nil TRACE[05-13|16:15:51.231] FINDNODE/v4 id=f1364e6d060c4625 addr=127.0.0.1:30306 err=nil TRACE[05-13|16:15:51.232] NEIGHBORS/v4 id=f1364e6d060c4625 addr=127.0.0.1:30306 err=nil TRACE[05-13|16:15:52.591] FINDNODE/v4 id=f1364e6d060c4625 addr=127.0.0.1:30306 err=nil TRACE[05-13|16:15:52.591] NEIGHBORS/v4 id=f1364e6d060c4625 addr=127.0.0.1:30306 err=nil TRACE[05-13|16:15:57.767] PING/v4 id=f1364e6d060c4625 addr=127.0.0.1:30306 err=nil ``` It is now possible to attach a Javascript console to either node to query the network properties: ```sh theme={null} parallaxd attach node1/parallax.ipc ``` Once the Javascript console is running, check that the node is connected to one other peer (node 2): ```sh theme={null} net.peerCount ``` The details of this peer can also be queried and used to check that the peer really is Node 2: ```sh theme={null} admin.peers ``` This should return the following: ```javascript theme={null} [{ caps: ["prl/66", "snap/1"], enode: "enode://6a4576fb12004aa13949dbf25de978102483a6521e6d5d87c5b7ccb1944bbf8995dc730303ae891732410b1dd2e684277e9292fc0a17372a789bb4e87bdf366b@127.0.0.1:32110", id: "d300c59ba301abcb5f4a3866aab6f833857c3ddf2f0febb583410b1dc466f175", name: "Parallax/v1.0.0-unstable-8d84a701-20220503/linux-amd64/go1.18.1", network: { inbound: false, localAddress: "127.0.0.1:56620", remoteAddress: "127.0.0.1:32110", static: false, trusted: false }, protocols: { eth: { difficulty: 1, head: "0xc9a158a687eff8a46128bd5b9aaf6b2f04f10f0683acbd7f031514db9ad415a0", version: 66 }, snap: { version: 1 } } }] ``` The account associated with Node 1 was supposed to be funded with some Laxes at the chain genesis. This can be checked easily using `eth.getBalance()`: ```sh theme={null} eth.getBalance(eth.accounts[0]) ``` This account can then be unlocked and some Laxes sent to Node 2, using the following commands: ```javascript theme={null} // send some Wei eth.sendTransaction({ to: '0xc94d95a5106270775351eecfe43f97e8e75e59e8', from: eth.accounts[0], value: 25000 }); //check the transaction was successful by querying Node 2's account balance eth.getBalance('0xc94d95a5106270775351eecfe43f97e8e75e59e8'); ``` The same steps can then be repeated to attach a console to Node 2. ## Summary This page explored the various options for configuring a local private network. A step by step guide showed how to set up and launch a private network, unlock the associated accounts, attach a console to check the network status and make some basic interactions. *** *Adapted from [Private Networks](https://geth.ethereum.org/docs/fundamentals/private-network) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Pruning Source: https://docs.parallaxprotocol.org/client/fundamentals/pruning To prune a Parallax client at least 40 GB of free disk space is recommended. This means pruning cannot be used to save a hard drive that has been completely filled. A good rule of thumb is to prune before the node fills \~80% of the available disk space. ## Pruning rules 1. Do not try to prune an archive node. Archive nodes need to maintain ALL historic data by definition. 2. Ensure there is at least 40 GB of storage space still available on the disk that will be pruned. Failures have been reported with \~25GB of free space. 3. Parallax client is fully sync'd 4. Parallax client has finished creating a snapshot that is at least 128 blocks old. This is true when "state snapshot generation" is no longer reported in the logs. With these rules satisfied, the Parallax client's database can be pruned. ## How pruning works Pruning uses snapshots of the state database as an indicator to determine which nodes in the state trie can be kept and which ones are stale and can be discarded. The Parallax client identifies the target state trie based on a stored snapshot layer which has at least 128 block confirmations on top (for surviving reorgs) data that isn't part of the target state trie or genesis state. The Parallax client prunes the database in three stages: 1. Iterating state snapshot: the Parallax client iterates the bottom-most snapshot layer and constructs a bloom filter set for identifying the target trie nodes. 2. Pruning state data: the Parallax client deletes stale trie nodes from the database which are not in the bloom filter set. 3. Compacting database: the Parallax client tidies up the new database to reclaim free space. There may be a period of >1 hour during the Compacting Database stage with no log messages at all. This is normal, and the pruning should be left to run until finally a log message containing the phrase `State pruning successful` appears (i.e. do not restart the Parallax client yet!). That message indicates that the pruning is complete and the client can be started. ## Pruning command For a normal Parallax node, the client should be stopped and the following command executed to start a offline state prune: ```sh theme={null} parallaxd snapshot prune-state ``` For a Parallax client run using systemd: ```sh theme={null} sudo systemctl stop parallaxd # stop the daemon, wait >3mins to ensure clean shutdown tmux # tmux enables pruning to keep running even if you disconnect sudo -u parallaxd --datadir snapshot prune-state # wait for pruning to finish sudo systemctl start parallaxd # restart the daemon ``` The pruning could take 4-5 hours to complete. Once finished, restart the Parallax client. ## Troubleshooting Messages about "state snapshot generation" indicate that a snapshot is not fully generated. This suggests either the `--datadir` is not correct or the Parallax client ran out of time to complete the snapshot generation and the pruning began before the snapshot was completed. In either case, the best course of action is to stop the client, run it normally again (no pruning) until the snapshot is definitely complete and at least 128 blocks exist on top of it, then try pruning again. *** *Adapted from [Database Pruning](https://geth.ethereum.org/docs/fundamentals/dbpruning) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Security Source: https://docs.parallaxprotocol.org/client/fundamentals/security ## Downloading the Parallax client Download the Parallax client using the links on the [Downloads](https://github.com/ParallaxProtocol/parallax/releases) page. The SHA256 hashes of the downloaded files can be used to confirm precise consistency with our releases. This protects against malicious code being inadvertently downloaded from an adversarial source. The same measures should also be taken to download trusted consensus client software. ## Networking security The local machine's firewall settings should: * Block all traffic to 8545, or whatever custom port has been defined for JSON-RPC requests to the node, except for traffic from explicitly defined trusted machines. * Allow traffic on TCP 32110 or whichever custom port has been defined for peer-to-peer communications. This allows the node to connect to peers. * Allow traffic on UDP 32110 or whichever custom port has been defined for peer-to-peer communications. This allows node discovery. ## Account security Account security comes down to keeping private keys and account passwords backed up and inaccessible to adversaries. This is something that users take responsibility for. The Parallax client provides an encrypted store for keys that are unlocked using an account password. If the key files or the passwords are lost, the account is impossible to access and the funds are effectively lost forever. If access to the unencrypted keys is obtained by an adversary they gain control of any funds associated with the account. The Parallax client has built-in account management tools. However, Clef is recommended as an external account management and signing tool. It can be run decoupled from the Parallax client and can even be run on dedicated secure external hardware such as a VM or a secure USB drive. This is considered best practice because the user is required to manually review all actions that touch sensitive data, except where specific predefined rules are implemented. Signing is done locally to Clef rather than giving key access to a node. **Back up your keystore and passwords safely and securely!** ## Other security considerations Even with a perfectly secure node, users can still be manipulated by attackers into exposing security weaknesses or inadvertently interact with insecure smart contracts. For an overview, please see the Ethereum's [security best practice webpage](https://ethereum.org/en/security) and this introduction to [smart contract security](https://ethereum.org/en/developers/docs/smart-contracts/security/). *** *Adapted from [Security](https://geth.ethereum.org/docs/fundamentals/security) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Sync modes Source: https://docs.parallaxprotocol.org/client/fundamentals/sync-modes Syncing is the process by which Parallax client catches up to the latest Parallax block and current global state. There are several ways to sync a Parallax client that differ in their speed, storage requirements and trust assumptions. ## Full nodes There are two types of full node that use different mechanisms to sync up to the head of the chain: ### Snap (default) Snap sync starts from a relatively recent block and syncs from there to the head of the chain, keeping only the most recent 128 block states in memory. Between the initial sync block and the 128 most recent blocks, the node stores occasional snapshots that can be used to rebuild any intermediate state "on-the-fly". The difference between the snap-synced node and a full block-by-block synced node is that a snap synced node started from an initial checkpoint that was more recent than the genesis block. Snap sync is much faster than a full block-by-block sync from genesis. To start a node with snap sync pass `--syncmode snap` at startup. ![](https://geth.ethereum.org/images/docs/state-pruning.png) Snap sync works by first downloading the headers for a chunk of blocks. Once the headers have been verified, the block bodies and receipts for those blocks are downloaded. In parallel, the Parallax client also begins state-sync. In state-sync, the Parallax client first downloads the leaves of the state trie for each block without the intermediate nodes along with a range proof. The state trie is then regenerated locally. The state download is the part of the snap-sync that takes the most time to complete and the progress can be monitored using the ETA values in the log messages. However, the blockchain is also progressing at the same time and invalidating some of the regenerated state data. This means it is also necessary to have a 'healing' phase where errors in the state are fixed. It is not possible to monitor the progress of the state heal because the extent of the errors cannot be known until the current state has already been regenerated. The Parallax client regularly reports Syncing, state heal in progress during state healing - this informs the user that state heal has not finished. It is also possible to confirm this using `eth.syncing` - if this command returns `false` then the node is in sync. If it returns anything other than false then syncing is still in progress. The healing has to outpace the growth of the blockchain, otherwise the node will never catch up to the current state. There are some hardware factors that determine the speed of the state healing (speed of disk read/write and internet connection) and also the total gas used in each block (more gas means more changes to the state that have to be handled). To summarize, snap sync progresses in the following sequence: * download and verify headers * download block bodies and receipts. In parallel, download raw state data and build state trie * heal state trie to account for newly arriving data Snap sync is the default behaviour, so if the `--syncmode` value is not passed to the Parallax client at startup, it will use snap sync. A node that is started using snap will switch to block-by-block sync once it has caught up to the head of the chain. ### Full A full block-by-block sync generates the current state by executing every block starting from the genesis block. A full sync independently verifies block provenance as well as all state transitions by re-executing the transactions in the entire historical sequence of blocks. Only the most recent 128 block states are stored in a full node - older block states are pruned periodically and represented as a series of checkpoints from which any previous state can be regenerated on request. 128 blocks is about 21 hours of history with a block time of 10 minutes. To create a full node pass `--syncmode full` at startup. ## Archive nodes An archive node is a node that retains all historical data right back to genesis. There is no need to regenerate any data from checkpoints because all data is directly available in the node's own storage. Archive nodes are therefore ideal for making fast queries about historical states. Archive nodes are created by configuring the Parallax client's garbage collection so that old data is never deleted: `parallaxd --syncmode full --gcmode archive`. It is also possible to create a partial/recent archive node where the node was synced using snap but the state is never pruned. This creates an archive node that saves all state data from the point that the node first syncs. This is configured by starting the Parallax client with `--syncmode snap --gcmode archive`. ## Summary There are several ways to sync a Parallax node. The default is to use snap sync to create a full node. Full nodes can be created by syncing block-by-block from genesis (full-sync) or by starting at an intermediate checkpoint block (snap-sync). By default, these modes prune state data older than 128 blocks, keeping only checkpoints that enable on-request regeneration of historical states. For rapid queries of historical data an archive node is required. Archive nodes keep local copies of all historical data right back to genesis. Partial archive nodes can be created by snap-syncing a node and turning off state-pruning to create a node that keeps all states since the initial sync block. *** *Adapted from [Sync modes](https://geth.ethereum.org/docs/fundamentals/sync-modes) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Running over Tor Source: https://docs.parallaxprotocol.org/client/fundamentals/tor Connect through the Tor network, host an onion service, and run a fully dark node > [!NOTE] > > Tor support was added in v2.1.0. The Parallax client has first-class [Tor](https://www.torproject.org/) support, modeled closely on Bitcoin Core's: outbound connections can be routed through a SOCKS5 proxy, the node can host a Tor v3 onion service for inbound connections with no port forwarding, onion addresses are gossiped and stored like any other peer address, and a node can run entirely inside Tor with `--onlynet=onion`. See [Tor Integration](/protocol/advanced/networking/tor) for the protocol-level design. ## Quick start Install Tor and enable its control port in `/etc/tor/torrc`: ``` ControlPort 9051 CookieAuthentication 1 CookieAuthFileGroupReadable 1 ``` restart Tor (`sudo systemctl restart tor`), add the user running `parallaxd` to the Tor group (`debian-tor` on Debian/Ubuntu, `tor` on Arch — on Arch also add `DataDirectoryGroupReadable 1` to torrc, since the auth cookie lives inside `/var/lib/tor` there), then simply start the node: ```sh theme={null} parallaxd ``` No Tor-specific flags are needed for the default experience. On startup the node connects to the control port, creates a v3 onion service pointing at its P2P listener, and — because `--onion` wasn't set — asks the Tor daemon for its SOCKS listener and configures it as the onion proxy automatically. Watch for: ``` torcontrol: onion proxy auto-configured proxy=127.0.0.1:9050 reachable=true torcontrol: onion service established service=xxxx….onion virtualPort=32110 ``` From that point the node is reachable at its onion address, advertises it to the network, and can dial other nodes' onion addresses. The `network reachability` line logged at startup summarizes what the resolved configuration allows. ## Flags | Flag | Default | Effect | | - | - | - | | `--listenonion` | on | Create a v3 onion service for the P2P listener via the Tor control port. A no-op (with quiet periodic retries) until a control port answers. | | `--torcontrol` | `127.0.0.1:9051` | Tor control port address. | | `--torpassword` | unset | Control-port password (`HashedControlPassword` auth). Cookie auth is used automatically when unset. | | `--proxy` | unset | SOCKS5 proxy for **all** outbound connections, including clearnet ones. Also suppresses everything that would expose the node's real IP regardless of the proxy: DNS-seed bootstrapping moves off the system resolver, the discv4 UDP socket is not opened, enrtree resolution is skipped, and UPnP/NAT-PMP is disabled. | | `--onion` | auto-discovered | SOCKS5 proxy used only for `.onion` targets, overriding both `--proxy` and the auto-discovery. `--onion=0` disables onion outbound entirely. | | `--onlynet` | unset | Restrict **automatic** outbound connections to the named networks (`ipv4`, `ipv6`, `onion`, comma-separated). Manual dials (`addnode`, `addPeer`, `dialV2`) and static nodes are exempt, as in Core. | | `--proxyrandomize` | on | Fresh SOCKS5 credentials per connection, so Tor puts every peer on its own circuit (stream isolation). | ## The onion service identity The service key persists in `/onion_v3_private_key`, so the node keeps the same `.onion` address across restarts. Treat the file like the node key: back it up to keep the address, protect it because whoever holds it can impersonate the service. Deleting it yields a fresh address on next startup. The onion service always advertises the network default port (32110) regardless of the local `--port`, so nodes on non-standard ports are not decloaked by their port number. ## Verifying On the console: ```javascript theme={null} > admin.nodeInfo.onion "xxxx….onion:32110" > admin.nodeInfo.networks [{name: "ipv4", reachable: true, ...}, {name: "ipv6", reachable: true, ...}, {name: "onion", reachable: true, proxy: "127.0.0.1:9050", proxy_randomize_credentials: true}] ``` `admin.peers` shows each peer's transport and logical address. A proxied peer's `remoteAddress` is always the SOCKS5 proxy — the socket-level truth — while `network.address` names the actual target: ```javascript theme={null} network: { address: "yyyy….onion:32110", network: "onion", remoteAddress: "127.0.0.1:9050", inbound: false, ... } ``` An **inbound** onion peer shows an empty `address`: it reached us through a Tor rendezvous and is anonymous by design. To test reachability from another machine with Tor, dial the address directly: ```sh theme={null} parallax-cli dialv2 xxxx….onion:32110 # one-shot parallax-cli addnode xxxx….onion:32110 # persistent, survives restarts ``` `setban`/`listbanned` accept onion addresses the same way, and `removenode` accepts them too — outbound peers are matched by the address they were dialed at, so a peer reached through a proxy is addressed by its real address rather than the proxy's. ## Fully dark: `--onlynet=onion` ```sh theme={null} parallaxd --onlynet=onion ``` restricts outbound to onion peers. No discv4 UDP socket is opened, NAT traversal and DNS seeding are disabled, and the node bootstraps from the onion addresses in the hardcoded bootnode list, then from gossip. It is legal to start this way before the Tor daemon is up: the node begins with no reachable network and flips onion reachable the moment the control port answers. An onion-only node never reveals its IP address to any peer — the client refuses to advertise an IP over a Tor circuit even when it knows one. A dual-stack node (clearnet listener + onion service) advertises both addresses, which allows observers to link them. Operators who need unlinkability must run onion-only. ## Clearnet through Tor: expectations `--proxy=127.0.0.1:9050` routes clearnet connections through Tor exit relays. This works, but most exit policies do not carry non-standard ports, so only a fraction of circuits complete a connection to clearnet peers on 32110 — measured at roughly 1 in 6 on the live network (Bitcoin has the same property on 8333). Onion-to-onion connections use rendezvous circuits, never exits, and connect reliably in seconds. Treat exit-based clearnet dialing as a bootstrap fallback; onion peering is the real transport. ## Troubleshooting * **No `torcontrol:` lines at all** — the control port isn't answering, or the auth cookie is unreadable. The controller retries with backoff and logs failures only at debug level; run `debug.verbosity(4)` on the console to see the exact error (`connection refused` → torrc lacks `ControlPort`; `permission denied` → group membership or, on Arch, the missing `DataDirectoryGroupReadable 1`). * **Onion dial says `no route to network`** — the node has no onion proxy: no `--proxy`/`--onion`, and no control port for the auto-discovery. Onion entries are then neither stored nor dialed. * **First dial to a fresh onion address fails with `onion service descriptor can not be found`** — the descriptor hasn't propagated yet; retry after 30-60 seconds. # Versioning Source: https://docs.parallaxprotocol.org/client/fundamentals/versioning What a major, minor, or patch release means, and which version to run Parallax releases follow [Semantic Versioning](https://semver.org): `MAJOR.MINOR.PATCH`, tagged as `vX.Y.Z`. | Component | Bumped for | Example | | - | - | - | | **PATCH** (`Z`) | Bug fixes, security patches, performance work. No new features and no interface changes — a drop-in upgrade. | `2.0.0` → `2.0.1` | | **MINOR** (`Y`) | Features added, changed, or removed: new RPC methods, new CLI flags, new subsystems. Node operators upgrade without changes; removals and behaviour changes are listed in the release notes. | `2.0.1` → `2.1.0` | | **MAJOR** (`X`) | Breaking changes to the exported Go API — moved packages, renamed or removed types and functions. Code that imports Parallax as a library needs edits. `1.x` → `2.0` was the move to the layered architecture. | `2.1.0` → `3.0.0` | The major digit tracks the **library** surface, so it matters most to developers embedding the Go packages. For someone who only runs `parallaxd`, a major release mostly means "read the release notes carefully." ## Which release to run Run the latest patch release of the current stable series. Every release carries a metadata tag alongside the version numbers: | Metadata | Meaning | | - | - | | `stable` | A released build. The only kind recommended for mainnet. | | `rcN` | Release candidate, e.g. `2.1.0-rc1`. Published for testing; any tag containing a hyphen is marked as a prerelease on GitHub and never moves the `latest` Docker tag. | | `unstable` | A development build from the `main` branch, e.g. `2.1.0-unstable`. Not a release — the version names the *next* release, not the last one. | Check what a node is running with: ```sh theme={null} parallaxd version ``` Development and release-candidate builds also print the git commit and its date, so any binary can be traced back to the exact source it was built from. Binary downloads and Docker tags are described in [Installing the client](/client/getting-started/installing-client). ## Release branches Each minor series gets a long-lived branch, `X.Y.x` (for example `2.0.x`). The series is cut when `X.Y.0` ships; patch releases are tagged from that branch, while `main` moves on to the next minor's development cycle. Documentation is versioned by major release instead; see [Versions of this documentation](#versions-of-this-documentation). ## Importing Parallax as a Go library The major version is part of the Go module path: ```go theme={null} import "github.com/ParallaxProtocol/parallax/v2/kernel/chainparams" ``` ```sh theme={null} go get github.com/ParallaxProtocol/parallax/v2@latest ``` The `/vN` suffix is what lets a `3.x` release land without breaking code still on `2.x` — Go treats the two as distinct modules that can coexist in one build. The suffix was introduced in `v2.1.0`; earlier `2.0.x` tags are not resolvable under the `/v2` path. See the [Go API](/client/developers/dapp/go-api) page for the packages most applications need. ## Consensus is not versioned by releases The version number describes the *software*, never the *rules*. Parallax treats consensus the way Bitcoin does: the rules are meant to stay fixed. There is no scheduled fork cadence, and a new release is not an occasion to change how blocks are validated. Client releases ship bug fixes, features, and refactors on top of rules that are expected to outlive every version number in this scheme. Consequently: * A major version bump means the Go API moved, not that the chain changed. Upgrading from `2.x` to `3.x` does not imply a fork. * On the rare occasion a consensus change is warranted, it activates at a **block height** rather than at a release boundary, and the release carrying it is mandatory for every node regardless of which digit moved. * The wire protocols carry their own version numbers — `prl/66` for chain sync and `parallax-disc/1` for peer discovery — and bump independently of the release version. Release notes state explicitly when an upgrade is mandatory rather than optional. ## Versions of this documentation The client documentation has one version per major release: `v2.x` covers every 2.x release and is updated as new ones ship. A feature added after `2.0.0` names the release that added it, for example "added in v2.1.0", so check that note against the version you run. The `v1.x` documentation is archived and no longer updated. # Binaries Source: https://docs.parallaxprotocol.org/client/getting-started/binaries Parallax ships as four cooperating binaries, mirroring the layout used by Bitcoin Core. Building from source (`make parallax`) produces all four under `./build/bin/`; distribution packages install them onto `$PATH`. ## The four binaries | Binary | Role | | - | - | | `parallaxd` | Full-node daemon. Owns chain data, the JSON-RPC server, mining, peer networking and all on-disk state operations (init, import/export, account keystore, database maintenance, attach/console, snapshot, dumpgenesis, etc.). All node flags such as `--http`, `--ws`, `--mine`, `--dev`, `--datadir`, `--syncmode` and `--daemon` are passed to `parallaxd`. | | `parallax-cli` | JSON-RPC client. A small sugar binary that speaks to a running `parallaxd` over IPC/HTTP and exposes ergonomic subcommands (`info`, `chaininfo`, `peers`, `balance`, `gettx`, `sendraw`, `startmining`, `newaccount`, `unlock`, `sign`, `loglevel`, …) instead of raw JSON-RPC payloads. | | `parallax-wallet` | Offline wallet tool. Operates directly on keystore files on disk and never talks to a running node, making it safe for air-gapped, cold-signing workflows (`list`, `new`, `import`, `dump`, `signtx`, `signmessage`, …). See [parallax-wallet](/client/tools/parallax-wallet) for the full command reference. | | `parallax` | Multi-call wrapper. Dispatches `parallax node ` to `parallaxd`, `parallax rpc ` to `parallax-cli` and `parallax wallet ` to `parallax-wallet`. It has no other functionality — it exists so a single command name covers all roles for users who want it. | ## Dispatch model The wrapper is a thin shim: ```sh theme={null} parallax node --http --datadir ./data # equivalent to: parallaxd --http --datadir ./data parallax rpc info # equivalent to: parallax-cli info parallax wallet list # equivalent to: parallax-wallet list ``` Any argument after `node`, `rpc` or `wallet` is forwarded verbatim. You can always invoke `parallaxd`, `parallax-cli` or `parallax-wallet` directly; the wrapper is only a convenience. ## One-line examples Start the full node in daemon mode with HTTP-RPC enabled: ```sh theme={null} parallaxd --http --datadir ~/.parallax --daemon ``` Query the running node over JSON-RPC: ```sh theme={null} parallax-cli info ``` List the accounts in the keystore, entirely offline: ```sh theme={null} parallax-wallet list ``` Use the multi-call wrapper to do the same: ```sh theme={null} parallax node --http --datadir ~/.parallax --daemon parallax rpc info parallax wallet list ``` Throughout the rest of this documentation, shell snippets use `parallaxd` for node operations and `parallax-cli` for RPC queries. Substitute `parallax node` or `parallax rpc` if you prefer the wrapper. # Hardware requirements Source: https://docs.parallaxprotocol.org/client/getting-started/hardware-requirements The hardware requirements for running a Parallax node depend upon the node configuration and can change over time as the network grows. Parallax nodes can be run on low power, resource-constrained devices such as Raspberry Pi's. However, many users will choose to run nodes on laptop or desktop computers. Parallax uses 10-minute block times and the chain is currently small, so requirements are modest. ## CPU A single-core CPU is sufficient to run a node. A dual-core or better is recommended, especially for mining. ## Memory It is recommended to use at least 2 GB RAM. 4 GB or more is recommended for mining or running additional services. ## Disk space At the time of writing, the Parallax chain is in its early stages with minimal state. A 50 GB SSD is sufficient for a full node. We recommend 100 GB SSD to allow room for growth and DAG file storage used by the XHash mining algorithm. Archive nodes that retain all historical state back to genesis require additional space. A fast SSD is recommended over HDD for read/write performance during sync. ## Bandwidth A stable internet connection with at least 1 Mbps is sufficient to run a node. 10 Mbps or more is recommended for faster initial sync and reliable peer connectivity. It is better to use an ISP that does not have a capped data allowance. *** *Partly adapted from [Hardware requirements](https://geth.ethereum.org/docs/getting-started/hardware-requirements) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Installing the Parallax Client Source: https://docs.parallaxprotocol.org/client/getting-started/installing-client There are several ways to install the Parallax client, including via a package manager, downloading a pre-built bundle, running as a docker container or building from downloaded source code. > [!NOTE] > > Not comfortable with the terminal? **[Parallax Wallet](/parallax-wallet/introduction)** is a native GUI application that bundles a full Parallax node in a single installer for Windows, macOS, and Linux — no command line required. The rest of this page covers the CLI client. On this page the various installation options are explained for several major operating systems. Users prioritizing ease of installation should choose to use a package manager or prebuilt bundle. Users prioritizing customization should build from source. It is important to run the latest version of the Parallax client because each release includes bug fixes and improvements over the previous versions. The stable releases are recommended for most users because they have been fully tested. A list of stable releases can be found [here](https://github.com/ParallaxProtocol/parallax/releases). Instructions for updating existing Parallax installations are also provided in each section. ## Package managers Not yet available in package managers. ## Standalone bundle Stable releases and development builds are provided as standalone bundles. These are useful for users who: a) wish to install a specific version of the Parallax client (e.g., for reproducible environments); b) wish to install on machines without internet access (e.g. air-gapped computers); or c) wish to avoid automatic updates and instead prefer to manually install software. The following standalone bundles are available: * 32bit, 64bit, ARMv5, ARMv6, ARMv7 and ARM64 archives (.tar.gz) on Linux * 64bit archives (.tar.gz) on macOS * 32bit and 64bit archives (.zip) and installers (.exe) on Windows Some archives contain only the Parallax suite — `parallaxd` (full-node daemon), `parallax-cli` (JSON-RPC client) and `parallax` (multi-call wrapper) — while other archives bundle the suite together with the developer tools (clef, devp2p, abigen, bootnode, evm, rlpdump). The standalone bundles can be downloaded from the [Parallax client Releases](https://github.com/ParallaxProtocol/parallax/releases) page. To update an existing installation, download and manually install the latest version. ## Docker container Official images are published to [Docker Hub](https://hub.docker.com/r/parallaxprotocol/parallax) for `linux/amd64` and `linux/arm64` on every release, with SBOM and provenance attestations. Each image bundles the full client suite — `parallaxd` (full-node daemon), `parallax-cli` (JSON-RPC client), `parallax-wallet` (offline wallet tool) and the `parallax` multi-call wrapper, which is the image entrypoint — so the familiar subcommands work directly. The container runs as an unprivileged user (uid/gid 1000) and keeps all state under `/home/parallax/.parallax`. Three kinds of tags are available: `latest` always points at the most recent stable release, version lines such as `2.0` track the newest patch release of that line, and exact versions such as `2.0.0` never move. Prerelease tags (e.g. `2.0.0-rc4`) are published but never move `latest`. To run a full node with persistent chain data, mount a volume at the datadir and publish the P2P port: ```sh theme={null} docker run -d --name parallax \ -v parallax-data:/home/parallax/.parallax \ -p 32110:32110 -p 32110:32110/udp \ parallaxprotocol/parallax node ``` The running node can be queried through the bundled RPC client, which connects over the IPC socket inside the container — no HTTP configuration is required: ```sh theme={null} docker exec parallax parallax rpc info docker exec parallax parallax rpc blockcount ``` To serve JSON-RPC over HTTP, the server must be bound to the container's external interface, and the published port should stay on loopback (or inside a private Docker network) — an unauthenticated RPC port must never be exposed to the public internet: ```sh theme={null} docker run -d --name parallax \ -v parallax-data:/home/parallax/.parallax \ -p 32110:32110 -p 32110:32110/udp \ -p 127.0.0.1:8545:8545 \ parallaxprotocol/parallax node --http --http.addr 0.0.0.0 ``` When stopping the node, give the database time to close cleanly rather than accepting Docker's 10-second default kill: ```sh theme={null} docker stop -t 60 parallax ``` To update an existing installation, pull the newer image and recreate the container; chain data survives in the named volume: ```sh theme={null} docker pull parallaxprotocol/parallax docker stop -t 60 parallax && docker rm parallax docker run -d --name parallax \ -v parallax-data:/home/parallax/.parallax \ -p 32110:32110 -p 32110:32110/udp \ parallaxprotocol/parallax node ``` When mining, the XHash DAGs under `/home/parallax/.xhash` are worth mounting as a second volume so they are not regenerated on every container recreation. The image can also be built locally from the repository root with `docker build -t parallax .`; a `Dockerfile.alltools` variant additionally bundles the developer tools (abigen, clef, devp2p, pvm, rlpdump and friends). ## Build from source code ### Linux and Mac The [Parallax client repository](https://github.com/ParallaxProtocol/parallax) should be cloned locally. Then, the command `make parallax` configures everything for a temporary build and cleans up afterwards. This method of building only works on UNIX-like operating systems, and a Go installation is still required. ```sh theme={null} git clone https://github.com/ParallaxProtocol/parallax.git cd parallax make parallax ``` These commands create four executable files under `parallax/build/bin/`: `parallaxd` (the full-node daemon), `parallax-cli` (the JSON-RPC client), `parallax-wallet` (the offline wallet tool) and `parallax` (a thin wrapper that dispatches `parallax node …` → `parallaxd`, `parallax rpc …` → `parallax-cli` and `parallax wallet …` → `parallax-wallet`). All four are statically linked and can be moved or copied independently; the wrapper resolves its companions as siblings in its own install directory or via `$PATH`. To update an existing Parallax client installation simply stop the node, navigate to the project root directory and pull the latest version from the Parallax GitHub repository. Then rebuild and restart the node. ```sh theme={null} cd parallax git pull make parallax ``` ### Windows The Chocolatey package manager provides an easy way to install the required build tools. Chocolatey can be installed by following these [instructions](https://chocolatey.org/). Then, to install the build tool the following commands can be run in an Administrator command prompt: ```sh theme={null} C:\Windows\system32> choco install git C:\Windows\system32> choco install golang C:\Windows\system32> choco install mingw ``` Installing these packages sets up the path environment variables. To get the new path a new command prompt must be opened. To install the Parallax client, a Go workspace directory must first be created, then the Parallax source code can be created and built. ```sh theme={null} C:\Users\xxx> mkdir src\github.com\ParallaxProtocol C:\Users\xxx> git clone https://github.com/ParallaxProtocol/parallax src\github.com\ParallaxProtocol\parallax C:\Users\xxx> cd src\github.com\ParallaxProtocol\parallax C:\Users\xxx\src\github.com\ParallaxProtocol\parallax> go get -u -v golang.org/x/net/context C:\Users\xxx\src\github.com\ParallaxProtocol\parallax> go install -v ./cmd/... ``` ### FreeBSD To build the Parallax client from source code on FreeBSD, the Parallax GitHub repository can be cloned into a local directory. ```sh theme={null} git clone https://github.com/ParallaxProtocol/parallax ``` Then, the Go compiler can be used to build the Parallax client: ```sh theme={null} pkg install go ``` If the Go version currently installed is >= 1.5, the Parallax client can be built using the following command: ```sh theme={null} cd parallax make parallax ``` If the installed Go version is \< 1.5 (quarterly packages, for example), the following command can be used instead: ```sh theme={null} cd parallax CC=clang make parallax ``` To start the node, the following command can be run: ```sh theme={null} build/bin/parallaxd ``` Additionally all the developer tools provided with Parallax (clef, devp2p, abigen, bootnode, evm and rlpdump) can be compiled by running `make all`. To build a stable release, e.g. v1.0.0, the command `git checkout v1.0.0` retrieves that specific version. Executing that command before running `make parallax` switches the Parallax client to a stable branch. *** *Partly adapted from [Installing Geth](https://geth.ethereum.org/docs/getting-started/installing-geth) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Introduction Source: https://docs.parallaxprotocol.org/client/getting-started/introduction This page explains how to set up the Parallax Client and execute some basic tasks using the command line tools. In order to use the Parallax Client, the software must first be installed. There are several ways the Parallax client can be installed depending on the operating system and the user's choice of installation method, for example using a package manager, container or building from source. Instructions for installing the Parallax client can be found on the ["Install and Build"](/client/getting-started/installing-client) pages. The tutorial on this page assumes the Parallax client have been installed successfully and that a firewall has been configured to block external traffic to the JSON-RPC port 8545, see [Security](/client/fundamentals/sync-modes). This page provides step-by-step instructions covering the fundamentals of using the Parallax client. This includes generating accounts, joining the Parallax network, syncing the blockchain and sending laxes between accounts. This tutorial uses [Clef](/client/tools/clef/introduction). Clef is an account management tool external to the Parallax client itself that allows users to sign transactions. It is developed by the Geth team and maintained by the Parallax team. ## Prerequisites In order to get the most value from the tutorials on this page, the following skills are necessary: * Experience using the command line * Basic knowledge about Ethereum, Parallax and testnets * Basic knowledge about HTTP and JavaScript * Basic knowledge of node architecture Users that need to revisit these fundamentals can find helpful resources relating to the command line [here](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line), http [here](https://developer.mozilla.org/en-US/docs/Web/HTTP) and Javascript [here](https://www.javascript.com/learn). If the Parallax client was installed from source on Linux, `make parallax` drops the four suite binaries — `parallaxd` (the full-node daemon), `parallax-cli` (the JSON-RPC client), `parallax-wallet` (the offline wallet tool) and `parallax` (a multi-call wrapper that dispatches `parallax node …` → `parallaxd`, `parallax rpc …` → `parallax-cli` and `parallax wallet …` → `parallax-wallet`) — into `./build/bin/`. Either move them to somewhere on `$PATH`, add `./build/bin` to `$PATH`, or prefix each invocation with `./build/bin/` in the snippets below. ## Background Running the Parallax client turns a computer into an Parallax node. Parallax is a peer-to-peer network where information is shared directly between nodes rather than being managed by a central server. Every 5 seconds one validator node is selected to generate a new block containing a list of transactions that nodes receiving the block should execute. This "block proposer" node sends the new block to its peers. On receiving a new block, each node checks that it is valid and adds it to their database. The sequence of discrete blocks is called a "blockchain". The information provided in each block is used by the Parallax client to update its "state" - the LAX balance of each account on Parallax and the data stored by each smart contract. There are two types of account: externally-owned accounts (EOAs) and contract accounts. Contract accounts execute contract code when they receive transactions. EOAs are accounts that users manage locally in order to sign and submit transactions. Each EOA is a public-private key pair, where the public key is used to derive a unique address for the user and the private key is used to protect the account and securely sign messages. Therefore, in order to use Parallax, it is first necessary to generate an EOA (hereafter, "account"). This tutorial will guide the user through creating an account, funding it with Laxes and sending some to another address. Read more about Parallax accounts [here](/protocol/foundational-topics/accounts). ### Step 1: Generating accounts There are several methods for generating accounts in the Parallax client. This tutorial demonstrates how to generate accounts using Clef, as this is considered best practice, largely because it decouples the users' key management from the Parallax client, making it more modular and flexible. It can also be run from secure USB sticks or virtual machines, offering security benefits. For convenience, this tutorial will execute Clef on the same computer that will also run the Parallax client, although more secure options are available (see [here](/client/tools/clef/setup)). An account is a pair of keys (public and private). Clef needs to know where to save these keys to so that they can be retrieved later. This information is passed to Clef as an argument. This is achieved using the following command: ```sh theme={null} clef newaccount --keystore parallax-tutorial/keystore ``` The specific function from Clef that generates new accounts is newaccount and it accepts a parameter, --keystore, that tells it where to store the newly generated keys. In this example the keystore location is a new directory that will be created automatically: parallax-tutorial/keystore. Clef will return the following result in the terminal: ``` WARNING! Clef is an account management tool. It may, like any software, contain bugs. Please take care to - backup your keystore files, - verify that the keystore(s) can be opened with your password. Clef is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Enter 'ok' to proceed: > ``` This is important information. The parallax-tutorial/keystore directory will soon contain a secret key that can be used to access any funds held in the new account. If it is compromised, the funds can be stolen. If it is lost, there is no way to retrieve the funds. This tutorial will only use dummy funds with no real world value, but when these steps are repeated on Parallax mainnet is critical that the keystore is kept secure and backed up. Typing ok into the terminal and pressing enter causes Clef to prompt for a password. Clef requires a password that is at least 10 characters long, and best practice would be to use a combination of numbers, characters and special characters. Entering a suitable password and pressing enter returns the following result to the terminal: ``` ----------------------- DEBUG[02-10|13:46:46.436] FS scan times list="92.081µs" set="12.629µs" diff="2.129µs" INFO [02-10|13:46:46.592] Your new key was generated address=0xCe8dBA5e4157c2B284d8853afEEea259344C1653 WARN [02-10|13:46:46.595] Please backup your key file! path=keystore:///.../parallax-tutorial/keystore/UTC--2022-02-07T17-19-56.517538000Z--ca57f3b40b42fcce3c37b8d18adbca5260ca72ec WARN [02-10|13:46:46.595] Please remember your password! Generated account 0xCe8dBA5e4157c2B284d8853afEEea259344C1653 ``` It is important to save the account address and the password somewhere secure. They will be used again later in this tutorial. Please note that the account address shown in the code snippets above and later in this tutorials are examples - those generated by followers of this tutorial will be different. The account generated above can be used as the main account throughout the remainder of this tutorial. However in order to demonstrate transactions between accounts it is also necessary to have a second account. A second account can be added to the same keystore by precisely repeating the previous steps, providing the same password. ### Step 2: Start Clef The previous commands used Clef's newaccount function to add new key pairs to the keystore. Clef uses the private key(s) saved in the keystore to sign transactions. In order to do this, Clef needs to be started and left running while the Parallax client is running simultaneously, so that the two programs can communicate between one another. To start Clef, run the Clef executable passing as arguments the keystore file location, config directory location and a chain ID. The config directory was automatically created inside the parallax-tutorial directory during the previous step. The [chain ID](https://chainlist.org/) is an integer that defines which EVM compatible network to connect to. Parallax mainnet has **chain ID 2110**. In this tutorial Chain ID **2111** is used which is that of the Parallax testnet. It is very important that this chain ID parameter is set to 2111 - Clef uses the chain ID to sign messages so it must be correct. The following command starts Clef on Parallax testnet: ```sh theme={null} clef --keystore parallax-tutorial/keystore --configdir parallax-tutorial/clef --chainid 2111 ``` After running the command above, Clef requests the user to type “ok” to proceed. On typing "ok" and pressing enter, Clef returns the following to the terminal: ``` INFO [02-10|13:55:30.812] Using CLI as UI-channel INFO [02-10|13:55:30.946] Loaded 4byte database embeds=146,841 locals=0 local=./4byte-custom.json WARN [02-10|13:55:30.947] Failed to open master, rules disabled err="failed stat on parallax-tutorial/clef/masterseed.json: stat parallax-tutorial/clef/masterseed.json: no such file or directory" INFO [02-10|13:55:30.947] Starting signer chainid=2111 keystore=parallax-tutorial/keystore light-kdf=false advanced=false DEBUG[02-10|13:55:30.948] FS scan times list="133.35µs" set="5.692µs" diff="3.262µs" DEBUG[02-10|13:55:30.970] Ledger support enabled DEBUG[02-10|13:55:30.973] Trezor support enabled via HID DEBUG[02-10|13:55:30.976] Trezor support enabled via WebUSB INFO [02-10|13:55:30.978] Audit logs configured file=audit.log DEBUG[02-10|13:55:30.981] IPCs registered namespaces=account INFO [02-10|13:55:30.984] IPC endpoint opened url=parallax-tutorial/clef/clef.ipc ------- Signer info ------- * intapi_version : 7.0.1 * extapi_version : 6.1.0 * extapi_http : n/a * extapi_ipc : parallax-tutorial/clef/clef.ipc ``` This result indicates that Clef is running. This terminal should be left running for the duration of this tutorial. If the tutorial is stopped and restarted later Clef must also be restarted by running the previous command. ### Step 3: Start the Parallax client The Parallax client will connect the computer to the Parallax network. In this tutorial the network is the Parallax testnet. Testnets are used to test Parallax client software and smart contracts in an environment where no real-world value is at risk. To start the Parallax client, run the the Parallax client executable file passing argument that define the data directory (where the Parallax client should save blockchain data), signer (points the Parallax client to Clef), the network ID and the sync mode. For this tutorial, snap sync is recommended. The final argument passed to the Parallax client is the --http flag. This enables the http-rpc server that allows external programs to interact with the Parallax client by sending it http requests. By default the http server is only exposed locally using port 8545: localhost:8545. The following command should be run in a new terminal, separate to the one running Clef: ```sh theme={null} parallaxd --testnet --datadir parallax-tutorial --http --http.api eth,net --signer=parallax-tutorial/clef/clef.ipc --http ``` Running the above command starts the Parallax client. By default, the Parallax client uses snap-sync which download blocks sequentially from a relatively recent block, not the genesis block. It saves the data in files in /parallax/parallax-tutorial/parallax/chaindata/. Once the sequence of headers has been verified, the Parallax client downloads the block bodies and state data before starting the "state healing" phase to update the state for newly arriving data. This is confirmed by the logs printed to the terminal. There should be a rapidly-growing sequence of logs in the terminal with the following syntax: ``` INFO [04-29][15:54:09.238] Looking for peers peercount=2 tried=0 static=0 INFO [04-29][15:54:19.393] Imported new block headers count=2 elapsed=1.127ms number=996288 hash=09f1e3..718c47 age=13h9m5s INFO [04-29][15:54:19:656] Imported new block receipts count=698 elapsed=4.464ms number=994566 hash=56dc44..007c93 age=13h9m9s ``` This message will be displayed periodically until state healing has finished: ``` INFO [10-20|20:20:09.510] State heal in progress accounts=313,309@17.95MiB slots=363,525@28.77MiB codes=7222@50.73MiB nodes=49,616,912@12.67GiB pending=29805 ``` When state healing is finished, the node is in sync and ready to use. Sending an empty Curl request to the http server provides a quick way to confirm that this too has been started without any issues. In a third terminal, the following command can be run: ```sh theme={null} curl http://localhost:8545 ``` If there is no error message reported to the terminal, everything is OK. The Parallax client must be running and synced in order for a user to interact with the Parallax network. If the terminal running the Parallax client is closed down then the Parallax client must be restarted again in a new terminal. The Parallax client can be started and stopped easily, but it must be running for any interaction with Parallax to take place. To shut down the Parallax client, simply press CTRL+C in the Parallax client terminal. To start it again, run the previous command `parallaxd --datadir `. ### Step 4: Get Testnet LAX In order to make some transactions, the user must fund their account with Laxes. On the Parallax mainnet, Laxes can only be obtained in three ways: 1. by receiving it as a reward for mining blocks; 2. receiving it in a transfer from another Parallax user or contract; 3. receiving it from an exchange On Parallax testnets, the Laxes has no real world value so it can be made freely available via faucets. Faucets allow users to request a transfer of testnet Laxes to their account. ### Step 5: Interact with the Parallax client For interacting with the blockchain, the Parallax client provides JSON-RPC APIs. [JSON-RPC](/protocol/parallax-stack/apis/json-rpc) is a way to execute specific tasks by sending instructions to the Parallax client in the form of [JSON](https://www.json.org/json-en.html) objects. RPC stands for "Remote Procedure Call" and it refers to the ability to send these JSON-encoded instructions from locations outside of those managed by the Parallax client. It is possible to interact with the Parallax client by sending these JSON encoded instructions directly over the Parallax client's exposed http port using tools like Curl. However, this is somewhat user-unfriendly and error-prone, especially for more complex instructions. For this reason, there are a set of libraries built on top of JSON-RPC that provide a more user-friendly interface for interacting with the Parallax client. One of the most widely used is Web3.js. The Parallax client provides a Javascript console that exposes the Web3.js API. This means that with the Parallax client running in one terminal, a Javascript environment can be opened in another allowing the user to interact with the Parallax client using Web3.js. There are three transport protocols that can be used to connect the Javascript environment to the Parallax client: * IPC (Inter-Process Communication): Provides unrestricted access to all APIs, but only works when the console is run on the same host as the Parallax node. * HTTP: By default provides access to the eth, web3 and net method namespaces. * Websocket: By default provides access to the eth, web3 and net method namespaces. This tutorial will use the HTTP option. Note that the terminals running the Parallax client and Clef should both still be active. In a new (third) terminal, the following command can be run to start the console and connect it to the Parallax client using the exposed http port: ```sh theme={null} parallaxd attach http://127.0.0.1:8545 ``` This command causes the terminal to hang because it is waiting for approval from Clef. Approving the request in the terminal running Clef will lead to the following welcome message being displayed in the Javascript console: ``` Welcome to the Parallax JavaScript console! instance: Parallax/v1.0.0-stable/darwin-amd64/go1.24.0 at block: 6354736 (Thu Feb 10 2025 14:01:46 GMT+0100 (WAT)) modules: eth:1.0 net:1.0 rpc:1.0 web3:1.0 To exit, press ctrl-d or type exit ``` The console is now active and connected to the Parallax client. It can now be used to interact with the Parallax (testnet) network. **List of accounts** In this tutorial, the accounts are managed using Clef. This means that requesting information about the accounts requires explicit approval in Clef, which should still be running in its own terminal. Earlier in this tutorial, two accounts were created using Clef. The following command will display the addresses of those two accounts and any others that might have been added to the keystore before or since. ```javascript theme={null} eth.accounts; ``` The console will hang, because Clef is waiting for approval. The following message will be displayed in the Clef terminal: ``` -------- List Account request-------------- A request has been made to list all accounts. You can select which accounts the caller can see [x] 0xca57F3b40B42FCce3c37B8D18aDBca5260ca72EC URL: keystore:///.../parallax-tutorial/keystore/UTC--2022-02-07T17-19-56.517538000Z--ca57f3b40b42fcce3c37b8d18adbca5260ca72ec [x] 0xCe8dBA5e4157c2B284d8853afEEea259344C1653 URL: keystore:///.../parallax-tutorial/keystore/UTC--2022-02-10T12-46-45.265592000Z--ce8dba5e4157c2b284d8853afeeea259344c1653 ------------------------------------------- Request context: NA - ipc - NA Additional HTTP header data, provided by the external caller: User-Agent: "" Origin: "" Approve? [y/N]: ``` Entering "y" approves the request from the console. In the terminal running the Javascript console, the account addresses are now displayed: ``` ["0xca57f3b40b42fcce3c37b8d18adbca5260ca72ec", "0xce8dba5e4157c2b284d8853afeeea259344c1653"] ``` It is also possible for this request to time out if the Clef approval took too long - in this case simply repeat the request and approval. Accounts can also be listed directly from Clef by opening a new terminal and running clef list-accounts --keystore \. **Checking account balance.** Having confirmed that the two addresses created earlier are indeed in the keystore and accessible through the Javascript console, it is possible to retrieve information about how much LAX they own. The testnet faucet should have sent 10 Laxes to the address provided, meaning that the balance of one of the accounts should be at least 10 Laxes and the other should be 0. There are other faucets available that may dispense more Laxes per request, and multiple requests can be made to accumulate more Laxes. The following command displays the account balance in the console: ```javascript theme={null} web3.fromWei(eth.getBalance('0xca57F3b40B42FCce3c37B8D18aDBca5260ca72EC'), 'ether'); ``` There are actually two instructions sent in the above command. The inner one is the getBalance function from the eth namespace. This takes the account address as its only argument. By default, this returns the account balance in units of Wei. There are 1e-18 Wei to one LAX. To present the result in units of Laxes, getBalance is wrapped in the fromWei function from the web3 namespace. Running this command should provide the following result, assuming the account balance is 1 Lax: ``` 1 ``` Repeating the command for the other (empty) account should yield: ``` 0 ``` **Send LAX to another account** The command eth.sendTransaction can be used to send some Laxes from one address to another. This command takes three arguments: from, to and value. These define the sender and recipient addresses (as strings) and the amount of Wei to transfer. It is far less error prone to enter the transaction value in units of Lax rather than Wei, so the value field can take the return value from the toWei function. The following command, run in the Javascript console, sends 0.1 Lax from one of the accounts in the Clef keystore to the other. Note that the addresses here are examples - the user must replace the address in the from field with the address currently owning 1 Lax, and the address in the to field with the address currently holding 0 Lax. ```javascript theme={null} eth.sendTransaction({ from: '0xca57f3b40b42fcce3c37b8d18adbca5260ca72ec', to: '0xce8dba5e4157c2b284d8853afeeea259344c1653', value: web3.toWei(0.1, 'ether') }); ``` Note that submitting this transaction requires approval in Clef. In the Clef terminal, Clef will prompt for approval and request the account password. If the password is correctly entered, the Parallax client proceeds with the transaction. The transaction request summary is presented by Clef in the Clef terminal. This is an opportunity for the sender to review the details and ensure they are correct. ``` --------- Transaction request------------- to: 0xCe8dBA5e4157c2B284d8853afEEea259344C1653 from: 0xca57F3b40B42FCce3c37B8D18aDBca5260ca72EC [chksum ok] value: 10000000000000000 wei gas: 0x5208 (21000) maxFeePerGas: 2425000057 wei maxPriorityFeePerGas: 2424999967 wei nonce: 0x3 (3) chainid: 0x4f5e0c Accesslist Request context: NA - ipc - NA Additional HTTP header data, provided by the external caller: User-Agent: "" Origin: "" ------------------------------------------- Approve? [y/N]: Please enter the password for account 0xca57F3b40B42FCce3c37B8D18aDBca5260ca72EC ``` After approving the transaction, the following confirmation screen in displayed in the Clef terminal: ``` ----------------------- Transaction signed: { "type": "0x2", "nonce": "0x3", "gasPrice": null, "maxPriorityFeePerGas": "0x908a901f", "maxFeePerGas": "0x908a9079", "gas": "0x5208", "value": "0x2386f26fc10000", "input": "0x", "v": "0x0", "r": "0x66e5d23ad156e04363e68b986d3a09e879f7fe6c84993cef800bc3b7ba8af072", "s": "0x647ff82be943ea4738600c831c4a19879f212eb77e32896c05055174045da1bc", "to": "0xce8dba5e4157c2b284d8853afeeea259344c1653", "chainId": "0x4f5e0c", "accessList": [], "hash": "0x99d489d0bd984915fd370b307c2d39320860950666aac3f261921113ae4f95bb" } ``` In the Javascript console, the transaction hash is displayed. This will be used in the next section to retrieve the transaction details. ``` "0x99d489d0bd984915fd370b307c2d39320860950666aac3f261921113ae4f95bb" ``` It is also advised to check the account balances using the Parallax client by repeating the instructions from earlier. At this point in the tutorial, the balances of the two accounts in the Clef keystore should have changed by \~0.1 Lax (the sender's balance will have decremented by a little over 0.1 Lax because some small was amount paid in transaction gas). **Checking the transaction hash** The transaction hash is a unique identifier for this specific transaction that can be used later to retrieve the transaction details. The same information can also be retrieved directly from the Parallax client. The hash returned in the previous step can be provided as an argument to eth.getTransaction to return the transaction information: ```javascript theme={null} eth.getTransaction('0x99d489d0bd984915fd370b307c2d39320860950666aac3f261921113ae4f95bb'); ``` This returns the following response (although the actual values for each field will vary because they are specific to each transaction): ```json theme={null} { accessList: [], blockHash: "0x1c5d3f8dd997b302935391b57dc3e4fffd1fa2088ef2836d51f844f993eb39c4", blockNumber: 6355150, chainId: "0x4f5e0c", from: "0xca57f3b40b42fcce3c37b8d18adbca5260ca72ec", gas: 21000, gasPrice: 2425000023, hash: "0x99d489d0bd984915fd370b307c2d39320860950666aac3f261921113ae4f95bb", input: "0x", maxFeePerGas: 2425000057, maxPriorityFeePerGas: 2424999967, nonce: 3, r: "0x66e5d23ad156e04363e68b986d3a09e879f7fe6c84993cef800bc3b7ba8af072", s: "0x647ff82be943ea4738600c831c4a19879f212eb77e32896c05055174045da1bc", to: "0xce8dba5e4157c2b284d8853afeeea259344c1653", transactionIndex: 630, type: "0x2", v: "0x0", value: 10000000000000000 } ``` ### Using Curl Up to this point this tutorial has interacted with the Parallax client using the convenience library Web3.js. This library enables the user to send instructions to the Parallax client using a more user-friendly interface compared to sending raw JSON objects. However, it is also possible for the user to send these JSON objects directly to the Parallax client's exposed HTTP port. Curl is a command line tool that sends HTTP requests. This part of the tutorial demonstrates how to check account balances and send a transaction using Curl. **Checking account balance** The command below returns the balance of the given account. This is a HTTP POST request to the local port 8545. The `-H` flag is for header information. It is used here to define the format of the incoming payload, which is JSON. The `--data` flag defines the content of the payload, which is a JSON object. That JSON object contains four fields: `jsonrpc` defines the spec version for the JSON-RPC API, `method` is the specific function being invoked, `params` are the function arguments, and `id` is used for ordering transactions. The two arguments passed to `eth_getBalance` are the account address whose balance to check and the block to query (here latest is used to check the balance in the most recently mined block). ```sh theme={null} curl -X POST http://127.0.0.1:8545 \ -H "Content-Type: application/json" \ --data '{"jsonrpc":"2.0", "method":"eth_getBalance", "params":["0xca57f3b40b42fcce3c37b8d18adbca5260ca72ec","latest"], "id":1}' ``` A successful call will return a response like the one below: ```json theme={null} {"jsonrpc":"2.0","id":1,"result":"0xc7d54951f87f7c0"} ``` The balance is in the result field in the returned JSON object. However, it is denominated in Wei and presented as a hexadecimal string. There are many options for converting this value to a decimal in units of Lax, for example by opening a Python console and running: ```python theme={null} 0xc7d54951f87f7c0 / 1e18 ``` This returns the balance in Lax: ``` 0.8999684999998321 ``` **Checking the account list** The curl command below returns the list of all accounts. ```sh theme={null} curl -X POST http://127.0.0.1:8545 \ -H "Content-Type: application/json" \ --data '{"jsonrpc":"2.0", "method":"eth_accounts","params":[], "id":1}' ``` This requires approval in Clef. Once approved, the following information is returned to the terminal: ```json theme={null} {"jsonrpc":"2.0","id":1,"result":["0xca57f3b40b42fcce3c37b8d18adbca5260ca72ec"]} ``` **Sending Transactions** Sending a transaction between accounts can also be achieved using Curl. Notice that the value of the transaction is a hexadecimal string in units of Wei. To transfer 0.1 LAX, it is first necessary to convert this to Wei by multiplying by 10^18 then converting to hex. 0.1 LAX is "0x16345785d8a0000" in hex. As before, update the to and from fields with the addresses in the Clef keystore. ```sh theme={null} curl -X POST http://127.0.0.1:8545 \ -H "Content-Type: application/json" \ --data '{"jsonrpc":"2.0", "method":"eth_sendTransaction", "params":[{"from": "0xca57f3b40b42fcce3c37b8d18adbca5260ca72ec","to": "0xce8dba5e4157c2b284d8853afeeea259344c1653","value": "0x16345785d8a0000"}], "id":1}' ``` This requires approval in Clef. Once the password for the sender account has been provided, Clef will return a summary of the transaction details and the terminal that made the Curl request will display a response containing the transaction hash. ```json theme={null} {"jsonrpc":"2.0","id":5,"result":"0xac8b347d70a82805edb85fc136fc2c4e77d31677c2f9e4e7950e0342f0dc7e7c"} ``` ### Summary This tutorial has demonstrated how to generate accounts using Clef, fund them with testnet Laxes and use those accounts to interact with Parallax (testnet) through the Parallax client. Checking account balances, sending transactions and retrieving transaction details were explained using the web3.js library via the Parallax client console and using the JSON-RPC directly using Curl. For more detailed information about Clef, please see [the Clef docs](/client/tools/clef/introduction). *** *Adapted from [Getting started with Geth](https://geth.ethereum.org/docs/getting-started) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Command-line RPC Source: https://docs.parallaxprotocol.org/client/interacting-with-parallax/command-line-rpc The `parallax-cli` binary is Parallax's JSON-RPC client for talking to a running node, in the same spirit as Bitcoin Core's `bitcoin-cli`. Rather than curling the RPC endpoint directly or entering the [JavaScript console](/client/interacting-with-parallax/js-console) for a quick status check, you invoke short subcommands: ```sh theme={null} parallax-cli info # → JSON node overview parallax-cli blockcount # → 12345 parallax-cli stop # → graceful shutdown ``` Each subcommand opens an RPC connection, issues a single request, prints the result, and exits. ## Endpoint resolution By default every command connects to `/parallax.ipc`, picking the data directory from `--datadir` (honoring `--testnet` as `/testnet/parallax.ipc`). You can override the endpoint with `--rpc`, which accepts a filesystem path (IPC) or a `http://`, `https://`, or `ws://` URL: ```sh theme={null} parallax-cli --datadir ~/.parallax info parallax-cli --rpc http://127.0.0.1:8545 info parallax-cli --rpc /tmp/parallax.ipc info ``` If the node cannot be reached the command exits non-zero with a short hint. ## Output conventions The command output mirrors `bitcoin-cli`: * **Object or array responses** are pretty-printed JSON (2-space indent), safe to pipe into `jq`. * **Scalar responses** (numbers, hashes, decimal amounts) are printed as a bare value plus a newline, so `$(parallax-cli blockcount)` works in shell scripts. * **Mutating commands** (`stop`, `addpeer`, `removepeer`) print nothing on success and return exit code 0. Errors are written to stderr and produce exit code 1. ## Command reference All commands below accept `--datadir`, `--testnet`, and `--rpc`. ### `start [config]` Convenience wrapper for `parallaxd --daemon`. Starts the node in the background, detached from the controlling terminal, with logs redirected to `/parallax.log`. An optional positional argument points at a TOML configuration file to pass through as `--config`. Every global flag placed before `start` on the command line is preserved, so: ```sh theme={null} parallax-cli --datadir /var/lib/parallax start /etc/parallax.toml ``` is exactly equivalent to: ```sh theme={null} parallaxd --datadir /var/lib/parallax --daemon --config /etc/parallax.toml ``` See [Daemon mode](/client/fundamentals/daemon-mode) for the detachment mechanics, log rotation, and PID-file conventions. ### `stop` Gracefully shuts down the running daemon. Equivalent to `bitcoin-cli stop`. Prints `Parallax server stopping` on success. Uses the [`admin_stop`](/client/interacting-with-parallax/json-rpc-namespaces/admin#admin_stop) RPC. ```sh theme={null} parallax-cli --datadir ~/.parallax stop ``` ### `info` Combined overview of chain, network, and mempool state. Merges the fields you would get from `getblockchaininfo`, `getnetworkinfo`, and `getmempoolinfo` in Bitcoin Core into a single JSON object. ```sh theme={null} $ parallax-cli info { "blocks": 1234567, "chainid": 2110, "connections": 8, "enode": "enode://...", "gasprice": "1000000000", "id": "3a...e4", "listenaddr": ":32110", "mempool": { "pending": 3, "queued": 1 }, "mining": false, "networkid": "2110", "protocolversion": 66, "syncing": false, "version": "Parallax/v2.0.0-.../linux-amd64/go1.22.0" } ``` ### `chaininfo` Chain state only (no network or mempool). Equivalent to `bitcoin-cli getblockchaininfo`. ```sh theme={null} $ parallax-cli chaininfo { "bestblockhash": "0x2e9f...0150", "blocks": 1234567, "chainid": 2110, "difficulty": "0x1", "gaslimit": 11500000, "gasused": 0, "networkid": "2110", "syncing": false, "timestamp": 1700000000, "totaldifficulty": "0x1" } ``` ### `netinfo` Network state only. Equivalent to `bitcoin-cli getnetworkinfo`. Uses `admin_nodeInfo` + `net_peerCount` + `net_listening`. ```sh theme={null} $ parallax-cli netinfo { "connections": 8, "enode": "enode://...", "id": "3ab8...cecf", "ip": "127.0.0.1", "listenaddr": ":32110", "listening": true, "ports": { "discovery": 32110, "listener": 32110 }, "protocolversion": 66, "version": "Parallax/v2.0.0/.../go1.22.0" } ``` ### `uptime` Seconds since the running node started. Equivalent to `bitcoin-cli uptime`. Backed by a new `admin_uptime` RPC. ```sh theme={null} $ parallax-cli uptime 86400 ``` ### `blockcount` Prints the latest block number as a bare integer. Equivalent to `bitcoin-cli getblockcount`. Uses `eth_blockNumber`. ```sh theme={null} $ parallax-cli blockcount 1234567 ``` ### `syncing` Prints `false` if the node is caught up, otherwise a JSON object with sync progress. Uses `eth_syncing`. ```sh theme={null} $ parallax-cli syncing false ``` ### `mempool` Summary of the node's transaction pool. Uses `txpool_status`. ```sh theme={null} $ parallax-cli mempool { "pending": 42, "queued": 5 } ``` ### `mempool-content` Dump the full transaction pool as JSON, or narrow it with `--address ` (useful when you're debugging a specific account). Pass `--inspect` for one-line summaries instead of full transaction objects — handy when the pool is large. Uses `txpool_content`, `txpool_contentFrom`, or `txpool_inspect` depending on the flags. ```sh theme={null} parallax-cli mempool-content parallax-cli mempool-content --address 0xabc...123 parallax-cli mempool-content --inspect ``` Output shape (both variants): ```json theme={null} { "pending": { "0xabc…": { "42": { "from": "…", "to": "…", ... } } }, "queued": {} } ``` ### `estimategas` Estimates the gas required to execute a transaction. Prints a bare integer, matching the scalar-output convention used by `gasprice`. Errors from the RPC (e.g. insufficient funds, revert) are surfaced to stderr with exit 1. ```sh theme={null} # Simple transfer (always 21000 on basic accounts) parallax-cli estimategas 0x1111...2222 # With value and calldata parallax-cli estimategas 0xcontract... --from 0xsender... --value 1000000000000000000 --data 0xa9059cbb... ``` `--value` accepts decimal wei or 0x-prefixed hex. Uses `eth_estimateGas`. ### `peers` JSON array of connected peers. Equivalent to `bitcoin-cli getpeerinfo`. Uses `admin_peers`. ```sh theme={null} $ parallax-cli peers [ { "enode": "enode://...", "id": "...", "name": "Parallax/v2.0.0/...", "caps": ["eth/66", "snap/1"], "network": { "localAddress": "10.0.0.2:32110", "remoteAddress": "203.0.113.1:32110", "inbound": false, "trusted": false, "static": false }, "protocols": { "eth": { "version": 66, "difficulty": 123, "head": "0x..." } } } ] ``` ### `balance
` Prints the balance of an account. Equivalent to `bitcoin-cli getbalance` (applied to a specific address, since the daemon has no wallet of its own). By default prints a decimal LAX value; pass `--wei` for the exact integer. Supports `--block` for historical queries. ```sh theme={null} $ parallax-cli balance 0xabc...123 1.234567890123456789 $ parallax-cli balance 0xabc...123 --wei 1234567890123456789 $ parallax-cli balance 0xabc...123 --block 1000000 0.5 ``` Uses `eth_getBalance`. ### `nonce
` Prints the transaction count (nonce) of an account as a bare integer. Essential when crafting raw transactions. Supports `--block` for historical queries. Uses `eth_getTransactionCount`. ```sh theme={null} $ parallax-cli nonce 0xabc...123 42 $ parallax-cli nonce 0xabc...123 --block 1000000 37 ``` ### `code
` Prints the deployed bytecode at an address as a 0x-prefixed hex string, or `0x` if the address is an externally owned account. Uses `eth_getCode`. ```sh theme={null} $ parallax-cli code 0xcontract... 0x608060405234801561001057600080fd5b50... $ parallax-cli code 0xeoa... 0x ``` Combine with `[ "$(parallax-cli code $addr)" = "0x" ]` to branch on contract vs EOA in shell scripts. ### `storage
` Reads a 32-byte storage slot from a contract and prints it as a 0x-prefixed hex string. `` accepts a decimal index or a 0x-prefixed hex key. Uses `eth_getStorageAt`. ```sh theme={null} $ parallax-cli storage 0xcontract... 0 0x000000000000000000000000000000000000000000000000000000000000002a $ parallax-cli storage 0xcontract... 0x1 0x0000000000000000000000000000000000000000000000000000000000000000 ``` Supports `--block` for historical reads. ### `gettx ` Fetches a transaction by hash and prints it as JSON. Equivalent to `bitcoin-cli getrawtransaction 1`. Uses `eth_getTransactionByHash`. ```sh theme={null} parallax-cli gettx 0xabc... ``` Exits non-zero with `transaction ... not found` if the node does not know the hash. ### `getreceipt ` Fetches the receipt of a mined transaction as JSON. Uses `eth_getTransactionReceipt`. Exits non-zero if the transaction is not mined yet or unknown. ```sh theme={null} parallax-cli getreceipt 0xabc... ``` ### `getblock [--full]` Fetches a block as JSON. Accepts a decimal block number, a hex block hash, or one of the tags `latest`, `earliest`, `pending`, `safe`, `finalized`. Pass `--full` to include full transaction objects instead of only hashes. ```sh theme={null} parallax-cli getblock 1234567 parallax-cli getblock latest --full parallax-cli getblock 0xabc...def ``` Uses `eth_getBlockByNumber` or `eth_getBlockByHash` depending on the argument shape. ### `getblockhash ` Prints the canonical hash of the block at a given height. Equivalent to `bitcoin-cli getblockhash`. Refuses hash input (use `getheader` for the hash → header direction). ```sh theme={null} $ parallax-cli getblockhash 0 0xb3a45e5033f0a0a4ccfa8a82cbe2fbf93bbc26c50fc3340fa749e5a5678d4391 ``` Backed by `eth_getBlockByNumber(n, false)` since there is no dedicated `eth_getBlockHash` RPC. ### `getheader ` Fetches a block header as JSON — same shape as `getblock` but without the `transactions` list, so it's smaller and faster when you only need metadata. Equivalent to `bitcoin-cli getblockheader`. ```sh theme={null} parallax-cli getheader 1234567 parallax-cli getheader 0xabc...def parallax-cli getheader latest ``` Uses `eth_getHeaderByNumber` or `eth_getHeaderByHash` depending on the argument shape. ### `tip` Condensed JSON view of the chain tip: number, hash, parent, timestamp, miner, gas used and limit, transaction count, size, difficulty. Useful at the top of operational scripts or in health checks. ```sh theme={null} $ parallax-cli tip { "difficulty": "0x2", "gaslimit": 11556255, "gasused": 0, "hash": "0xc8a6...15a8", "miner": "0x0000000000000000000000000000000000000000", "number": 5, "parent": "0xa5a9...a284", "size": 578, "timestamp": 1776147050, "txs": 0 } ``` Derived from a single `eth_getBlockByNumber("latest", false)` call. ### `gasprice` Prints the current suggested gas price as a bare wei integer. Uses `eth_gasPrice`. ```sh theme={null} $ parallax-cli gasprice 1000000000 ``` ### `sendraw ` Submits a signed, hex-encoded transaction and prints the resulting hash on a single line. Equivalent to `bitcoin-cli sendrawtransaction`. The `0x` prefix is optional. Uses `eth_sendRawTransaction`. ```sh theme={null} $ parallax-cli sendraw 0xf86c... 0xabc...def ``` ### Peer identifiers The four peer-admin commands (`addpeer`, `removepeer`, `addtrusted`, `removetrusted`) accept either form: * **Full enode URL** — `enode://<64-hex-id>@host:port[?discport=…]`, or an `enr:` record. Always works. * **`host:port`** — resolved against the running node's current peer list by matching IP and advertised listen port. * **`host`** — as above, but without the port constraint; must uniquely identify a connected peer. If multiple peers share the same host, the error message lists them so you can disambiguate. The host-based forms only work when the target peer is **currently connected** (so its cryptographic node ID is known to us). If the lookup fails the command exits non-zero with a pointer to use the full enode form. The shortcut deliberately never dials an unknown address to discover its node ID, because adopting an arbitrary pubkey picked up that way would let any process at that address get itself trusted. ### `addpeer ` Adds a static peer. Equivalent to `bitcoin-cli addnode add`. Silent on success, non-zero exit on failure. Uses `admin_addPeer`. ```sh theme={null} parallax-cli addpeer enode://a979...@1.2.3.4:32110 parallax-cli addpeer 1.2.3.4:32110 # resolves via connected peers ``` ### `removepeer ` Removes a static peer. Silent on success. Uses `admin_removePeer`. ```sh theme={null} parallax-cli removepeer enode://a979...@1.2.3.4:32110 parallax-cli removepeer 1.2.3.4:32110 ``` ### `addtrusted ` Marks a peer as trusted, so it is always allowed to connect even when the node has hit its `--maxpeers` limit. Silent on success. Uses `admin_addTrustedPeer`. ```sh theme={null} parallax-cli addtrusted enode://a979...@1.2.3.4:32110 parallax-cli addtrusted 1.2.3.4:32110 ``` ### `removetrusted ` Removes a peer from the trusted list. The peer is not disconnected automatically — run `removepeer` afterwards if you also want to drop the connection. Uses `admin_removeTrustedPeer`. ```sh theme={null} parallax-cli removetrusted enode://a979...@1.2.3.4:32110 parallax-cli removetrusted 1.2.3.4:32110 ``` ### `mining` Shows the miner's current state as JSON: whether mining is enabled, current hashrate, configured coinbase, and a snippet of chain-tip context. Equivalent to `bitcoin-cli getmininginfo`. ```sh theme={null} $ parallax-cli mining { "bestblockhash": "0xc73d...5f8f", "bestblocktime": 1700000000, "blocks": 1234567, "coinbase": "0x9af3f6517b7a2152ccaf0126d39b6464f73e8918", "hashrate": "0", "mining": true } ``` `coinbase` is `null` when no coinbase is configured (e.g. fresh dev node without `--miner.coinbase`). Hashrate is printed as a bare decimal string so it composes cleanly with other scalar-output commands. ### `startmining [threads]` Starts the built-in miner, optionally pinned to the given number of CPU threads. Silent on success. Uses `miner_start`. ```sh theme={null} parallax-cli startmining # one worker per logical CPU parallax-cli startmining 2 # two workers ``` ### `stopmining` Stops the miner. Silent on success. Uses `miner_stop`. ```sh theme={null} parallax-cli stopmining ``` ### `setcoinbase
` Updates the coinbase — the address credited with block rewards — without restarting the node. Silent on success. Uses `miner_setCoinbase`. ```sh theme={null} parallax-cli setcoinbase 0xabc...123 ``` ### `setextra ` Updates the extra-data bytes embedded in blocks this node mines. Accepts a plain string or a 0x-prefixed hex blob (auto-detected). Must fit the 32-byte extradata limit; longer values are rejected by the miner with a clear error. Uses `miner_setExtra`. ```sh theme={null} parallax-cli setextra "my-pool-v1" parallax-cli setextra 0xdeadbeef ``` ### `loglevel ` Adjusts log verbosity at runtime, without restarting the node. Equivalent to `bitcoin-cli logging`. * Integer `0..5` (silent, error, warn, info, debug, detail) → `debug_verbosity`. * Anything else is treated as a vmodule pattern like `eth/*=5,p2p=4` → `debug_vmodule`. ```sh theme={null} parallax-cli loglevel 4 # bump everything to debug parallax-cli loglevel 3 # back to info parallax-cli loglevel "eth/*=5,p2p=4" # per-package overrides ``` Silent on success; bad patterns exit non-zero with the server's validation message. ### `trace ` Traces the execution of a mined transaction. Equivalent to geth's `debug.traceTransaction` from the JS console. Two modes: * Without `--tracer`: returns the full opcode-by-opcode execution log. Output can be very large; consider redirecting to a file. * With `--tracer `: runs a named tracer and returns its condensed output. Common values: `callTracer` (call tree), `prestateTracer` (pre-execution state), `4byteTracer` (function-selector histogram). ```sh theme={null} parallax-cli trace 0xabc... parallax-cli trace 0xabc... --tracer callTracer parallax-cli trace 0xabc... --tracer callTracer --timeout 2m ``` `--timeout` accepts any Go duration (`30s`, `2m`, `10m`). Default is 5 minutes because non-tracer runs can take a while on large transactions. Uses `debug_traceTransaction`. ### `dbstats` Summary of on-disk database state: per-category ancient-freezer sizes in bytes plus the raw LevelDB compaction stats. Uses a new `debug_dbStats` RPC. ```sh theme={null} $ parallax-cli dbstats { "ancients": { "bodies": 123456789, "diffs": 12345, "hashes": 23456, "headers": 3456789, "receipts": 234567890 }, "leveldb": "Compactions\n Level | Tables | Size(MB) ..." } ``` Intended for quick "am I running out of disk?" checks. For a full per-prefix chaindata walk, use `parallaxd db inspect` (offline, reads the database directly). ## Wallet / accounts All commands below hit the running node's `personal_*` namespace. By default `personal_*` is refused over HTTP-RPC (it can expose key material); the sugar commands reach it via the IPC socket, which is the intended transport. If you must expose it over HTTP, enable it explicitly with `--http.api personal` and combine with `--allow-insecure-unlock`. **Never pass a passphrase as a CLI argument** — it would land in process listings and shell history. Pass it through `--password ` (first non-empty line) or let the command prompt on stdin. ### `listaccounts` JSON array of addresses the running node can see. Equivalent to the offline `parallax-wallet list`, but works without stopping the daemon. Uses `personal_listAccounts`. ```sh theme={null} $ parallax-cli listaccounts [ "0xa202...5108", "0x96a5...6b4d" ] ``` ### `newaccount` Creates a new keystore entry on the running node. Prompts for a passphrase with confirmation, or reads it from `--password `. Prints the bare address. Uses `personal_newAccount`. ```sh theme={null} parallax-cli newaccount parallax-cli newaccount --password /etc/parallax/newkey.pass ``` ### `unlock
` Unlocks an account so the node can sign transactions on its behalf. Equivalent to `bitcoin-cli walletpassphrase`. Silent on success. Uses `personal_unlockAccount`. ```sh theme={null} parallax-cli unlock 0xabc...123 parallax-cli unlock 0xabc...123 --password /run/secrets/acct.pass --duration 1h parallax-cli unlock 0xabc...123 --duration 0 # keep unlocked until the node stops ``` Default duration is 5 minutes (matching geth's built-in default). `--duration 0` passes a null duration to the RPC, which geth interprets as "until node stops". ### `lock
` Clears the in-memory decrypted key for an account. Silent on success. Uses `personal_lockAccount`. ```sh theme={null} parallax-cli lock 0xabc...123 ``` ### `sign
` Signs `` with the account's key (prefixed with the standard Ethereum signed-message preamble). Prints the 65-byte signature as a 0x-prefixed hex string. `` accepts a plain UTF-8 string or a 0x-prefixed hex blob (auto-detected). Prompts for the passphrase unless `--password` is set. ```sh theme={null} parallax-cli sign 0xabc...123 "approve this request" parallax-cli sign 0xabc...123 0xdeadbeef --password /run/secrets/acct.pass ``` Uses `personal_sign`. ### `sendtx --from ...` Builds a transaction from flags and submits it via `personal_sendTransaction` (signs client-side at the node using the sender's unlocked key). Prints the transaction hash on success. Required: `--from`. Optional: `--to` (omit for contract deploy), `--value` (wei, decimal or 0x-hex), `--data` (hex), `--gas`, `--gasprice`, `--nonce` (all decimal or 0x-hex). ```sh theme={null} parallax-cli sendtx --from 0xabc... --to 0xdef... --value 1000000000000000000 --password /run/secrets/from.pass parallax-cli sendtx --from 0xabc... --data 0x608060... # contract deploy ``` Prompts for the passphrase unless `--password` is set. ## Offline utilities Two commands run entirely client-side and do not require a running daemon — useful for air-gapped key handling and tx inspection. ### `decoderaw ` Decodes a 0x-prefixed RLP-encoded signed transaction and prints its fields as JSON, including the recovered sender. Equivalent to `bitcoin-cli decoderawtransaction`. Works for legacy, EIP-2930, and EIP-1559 transactions; dynamic-fee fields (`maxfeepergas`, `maxpriorityfeepergas`) only appear on EIP-1559 txs so legacy output stays clean. ```sh theme={null} $ parallax-cli decoderaw 0xf86580843b9aca00825208941111111111111111111111111111111111111111010180820a96a0... { "chainid": "1337", "data": "0x", "from": "0x43Ec477b3dd00BF4434Fc457425b0425AB39F00f", "gas": 21000, "gasprice": "1000000000", "hash": "0xabc...", "nonce": 0, "r": "...", "s": "...", "to": "0x1111111111111111111111111111111111111111", "type": 0, "v": "2710", "value": "1" } ``` No RPC call is made. Parsing and sender recovery happen in the binary itself. ### `toaddr ` Derives and prints the 0x-address for a hex-encoded secp256k1 private key. Runs entirely client-side — the key is never sent to any node or written to disk. Useful when verifying a backup or wiring up a key before funding it. ```sh theme={null} $ parallax-cli toaddr 0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318 0x2c7536E3605D9C16a7a3D7b1898e529396a65c23 $ parallax-cli toaddr 4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318 # 0x prefix optional 0x2c7536E3605D9C16a7a3D7b1898e529396a65c23 ``` ## When to use the JS console instead For one-off scripted calls and shell pipelines these subcommands are the quickest path. For interactive exploration of the full RPC surface, or any call that doesn't have a sugar wrapper, prefer the [JavaScript console](/client/interacting-with-parallax/js-console) via `parallaxd attach`. # GraphQL Server Source: https://docs.parallaxprotocol.org/client/interacting-with-parallax/graph-ql-server In addition to the [JSON-RPC APIs](/client/interacting-with-parallax/json-rpc-server/overview), the Parallax client 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 the Parallax client: ```sh theme={null} parallaxd --http --graphql ``` Now queries can be raised against `http://localhost:8545/graphql`. To change the port, provide a custom port number to `--http.port`, e.g.: ```sh theme={null} parallaxd --http --http.port 9545 --graphql ``` ## GraphiQL An easy way to try out queries is the GraphiQL interface shipped with the Parallax client. To open it visit `http://localhost:8545/graphql/ui`. To see how this works let's read the sender, recipient and value of all transactions in block number 6000000. In GraphiQL: ```graphql theme={null} query txInfo { block(number: 6000000) { transactions { hash from { address } to { address } value } } } ``` GraphiQL also provides a way to explore the schema the Parallax client provides to help you formulate your queries, which you can see on the right sidebar. Under the title `Root Types` click on `Query` to see the high-level types and their fields. ## Query Reading out data from the Parallax client 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: ```sh theme={null} ❯ curl -X POST http://localhost:8545/graphql -H "Content-Type: application/json" --data '{ "query": "query { block { number } }" }' {"data":{"block":{"number":"0x5b9d65"}}} ``` Alternatively store the JSON-ified query in a file (let's call it block-num.query) and do: ```sh theme={null} ❯ curl -X POST http://localhost:8545/graphql -H "Content-Type: application/json" --data '@block-num.query' ``` Executing a simple query in JS looks as follows. Here the lightweight library `graphql-request` is used to perform the request. Note the use of variables instead of hardcoding the block number in the query: ```javascript theme={null} const { request, gql } = require('graphql-request'); const query = gql` query blockInfo($number: Long) { block(number: $number) { hash stateRoot } } `; request('http://localhost:8545/graphql', query, { number: '6004067' }) .then(res => { console.log(res); }) .catch(err => { console.log(err); }); ``` ## Accessing state The schema allows for querying parts of state, i.e. accounts and their storage slots. E.g. it is possible to get the balance of the sender of a tx via: ```graphql theme={null} transaction(hash: "0xdad") { from { balance } } ``` It is important to note however that the balance returned here is **not** the balance at the given transaction, rather it is the latest balance of the sender account, i.e. at the head of the chain. It is possible to query the state of this account at a particular block N via: ```graphql theme={null} transaction(hash: "0xdad") { from(block: 6004067) { balance } } ``` As you can see this effect takes in a block number parameter which instructs the Parallax client to return the state of this account from an older block. The node needs to have the state for that block persisted, otherwise this query will result in an error. To see how the Parallax client persists state please see this [page](/client/developers/pvm-tracing/introduction). *** *Adapted from [GraphQL Server](https://geth.ethereum.org/docs/interacting-with-geth/rpc/graphql) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # JS Console Source: https://docs.parallaxprotocol.org/client/interacting-with-parallax/js-console The Parallax client responds to instructions encoded as JSON objects as defined in the [JSON-RPC-API](/client/interacting-with-parallax/json-rpc-server/overview). A Parallax 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 Parallax node with the HTTP port `8545` exposed. ```sh theme={null} curl --data '{"jsonrpc":"2.0","method":"eth_getBalance", "params": ["0x9b1d35635cc34752ca54713bb99d38614f63c955", "latest"], "id":2}' -H "Content-Type: application/json" localhost:8545 ``` This returns a result which is also a JSON object, with values expressed as hexadecimal strings, for example: ```json theme={null} {"id":2,"jsonrpc":"2.0","result":"0x1639e49bba16280000"} ``` This is a low level and rather error-prone way to interact with the Parallax client. Most developers prefer to use convenience libraries that abstract away some of the more tedious and awkward tasks such as converting values from hexadecimal strings into numbers, or converting between denominations of LAX (Wei, Gwei, etc). One such library is [Web3.js](https://web3js.readthedocs.io/en/v1.7.3/). The purpose of the Parallax client's Javascript console is to provide a built-in environment to use a subset of the Web3.js libraries to interact with a Parallax node. The web3.js version that comes bundled with the Parallax client is not up to date with the official Web3.js documentation. There are several Web3.js libraries that are not available in the Parallax Javascript Console. There are also administrative APIs included in the Parallax console that are not documented in the Web3.js documentation. The full list of libraries available in the Parallax console is available on the [JSON-RPC API page](/client/interacting-with-parallax/json-rpc-server/overview). ## Starting the console There are two ways to start an interactive session using the Parallax client `console`. The first is to provide the console command when the Parallax client is started up. This starts the node and runs the console in the same terminal. It is therefore convenient to suppress the logs from the node to prevent them from obscuring the console. If the logs are not needed, they can be redirected to the `dev/null` path, effectively muting them. Alternatively, if the logs are required they can be redirected to a text file. The level of detail provided in the logs can be adjusted by providing a value between 1-6 to the `--verbosity` flag as in the example below: ```sh theme={null} # to mute logs parallaxd console 2> /dev/null # to save logs to file parallaxd console --verbosity 3 2> parallax-logs.log ``` Alternatively, a Javascript console can be attached to an existing Parallax client instance (i.e. one that is running in another terminal or remotely). In this case, `parallaxd attach` can be used to open a Javascript console connected to the Parallax node. It is also necessary to define the method used to connect the console to the node. The Parallax client supports websockets, HTTP or local IPC. To use HTTP or Websockets, these must be enabled at the node by providing the following flags at startup: ```sh theme={null} # enable websockets parallaxd --ws # enable http parallaxd --http ``` The commands above use default HTTP/WS endpoints and only enables the default JSON-RPC libraries. To update the Websockets or HTTP endpoints used, or to add support for additional libraries, the `.addr` `.port` and `.api` flags can be used as follows: ```sh theme={null} # define a custom http adress, custom http port and enable libraries parallaxd --http --http.addr 192.60.52.21 --http.port 8552 --http.api eth,web3,admin # define a custom Websockets address and enable libraries parallaxd --ws --ws.addr 192.60.52.21 --ws.port 8552 --ws.api eth,web3,admin ``` It is important to note that by default **some functionality, including account unlocking is forbidden when HTTP or Websockets access is enabled**. This is because an attacker that manages to access the node via the externally-exposed HTTP/WS port then control the unlocked account. This is not a hypothetical risk: **there are bots that continually scan for http-enabled Parallax nodes to attack**" The Javascript console can also be connected to a Parallax node using IPC. When the Parallax client is started, a parallax.ipc file is automatically generated and saved to the data directory. This file, or a custom path to a specific ipc file can be passed to `parallaxd attach` as follows: ```sh theme={null} parallaxd attach datadir/parallax.ipc ``` Once started, the console looks like this: ``` Welcome to the Parallax JavaScript console! instance: Parallax/v1.0.0-stable-95cf8a9f/darwin-arm64/go1.20.6 coinbase: 0xa71299ee4c91bf07d84a51620f54379de83a5ba5 at block: 2754218 (Wed Jul 26 2023 15:07:49 GMT-0300 (-03)) datadir: /home/parallax/data modules: admin:1.0 debug:1.0 eth:1.0 istanbul:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0 To exit, press ctrl-d or type exit ``` ## Interactive use Once the console has been started, it can be used to interact with the Parallax client. The console supports Javascript and the full Parallax client [JSON-RPC API](/client/interacting-with-parallax/json-rpc-server/overview). For example, to check the balance of the first account already existing in the keystore: ```javascript theme={null} eth.getBalance(eth.accounts[0]); ``` To send a transaction (without global account unlocking): ```javascript theme={null} eth.sendTransaction({ to: eth.accounts[0], to: eth.accounts[1], value: web3.toWei(0.5, 'ether') }); ``` It is also possible to load pre-written Javascript files into the console by passing the `--preload` flag when starting the console. This is useful for setting up complex contract objects or loading frequently-used functions. ```sh theme={null} parallaxd console --preload "/my/scripts/folder/utils.js" ``` Once the interactive session is over, the console can be closed down by typing `exit` or `CTRL-D`. Remember that interactions that touch accounts need approval in Clef - either manually or by writing a custom ruleset. ## Non-interactive Use: Script Mode It is also possible to execute JavaScript code non-interactively by passing the `--exec` and a JSON-RPC-API endpoint to `parallaxd attach` or `parallaxd console`. The result is displayed directly in the terminal rather than in an interactive Javascript console. For example, to display the accounts in the keystore: ```sh theme={null} parallaxd attach --exec eth.accounts ``` ```sh theme={null} parallaxd attach --exec eth.blockNumber ``` The same syntax can be used to execute a local script file with more complex statements on a remote node over http, for example: ```sh theme={null} parallaxd attach http://parallax.example.org:8545 --exec 'loadScript("/tmp/checkbalances.js")' parallaxd attach http://parallax.example.org:8545 --jspath "/tmp" --exec 'loadScript("checkbalances.js")' ``` The `--jspath` flag is used to set a library directory for the Javascript scripts. Any parameters passed to `loadScript()` that do not explicitly define an absolute path will be interpreted relative to the `jspath` directory. ## Timers In addition to the full functionality of JS (as per ECMA5), the Parallax Javascript Runtime Environment (JSRE) is augmented with various timers. It implements `setInterval`, `clearInterval`, `setTimeout`, `clearTimeout` which some users will be familiar with from browser windows. It also provides implementation for `admin.sleep(seconds)` and a block based timer, `admin.sleepBlocks(n)` which sleeps till the number of new blocks added is equal to or greater than `n`. ## Caveats The Parallax client's console is built using the [GoJa JS Virtual Machine](https://github.com/dop251/goja) which is compatible with ECMAScript 5.1. This does not support promises or async functions. Web3js depends upon the bignumber.js library. This is auto-loaded into the console. *** *Adapted from [JavaScript Console](https://geth.ethereum.org/docs/interacting-with-geth/javascript-console) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # JS Console 2: Contracts Source: https://docs.parallaxprotocol.org/client/interacting-with-parallax/js-console-contracts The [Introduction to the Javascript console](/client/interacting-with-parallax/js-console) page outlined how a Javascript console can be attached to the Parallax client to provide a more user-friendly interface to Parallax than interacting directly with the JSON-RPC API. This page will describe how to deploy contracts and interact with contracts using the attached console. This page will assume the Javascript console is attached to a running the Parallax client instance using IPC. Clef should be used to manage accounts. ## Deploying a contract First we need a contract to deploy. We can use the well-known `Storage.sol` contract written in Solidity. The following Solidity code can be copied and pasted into a text editor and saved as `parallax/storage-contract/Storage.sol`. ```solidity theme={null} // SPDX License-Identifier: GPL 3.0 pragma solidity ^0.8.0; contract Storage{ uint256 value = 5; function set(uint256 number) public{ value = number; } function retrieve() public view returns (uint256){ return value; } } ``` The contract needs to be compiled before the Parallax client can understand it. Compiling the contract creates an [Application Binary Interface](/client/tools/abi-gen) and the contract bytecode. This requires a Solidity compiler (e.g. `solc`) to be installed on the local machine. Then, compile and save the ABI and bytecode to a new `build` subdirectory using the following terminal commands: ```sh theme={null} cd ~/parallax/storage-contract solc --bin Storage.sol -o build solc --abi Storage.sol -o build ``` The outputs look as follows: ```sh theme={null} # build/Storage.bin 608060405234801561001057600080fd5b50610150806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c80632e64cec11461003b5780636057361d14610059575b600080fd5b610043610075565b60405161005091906100a1565b60405180910390f35b610073600480360381019061006e91906100ed565b61007e565b005b60008054905090565b8060008190555050565b6000819050919050565b61009b81610088565b82525050565b60006020820190506100b66000830184610092565b92915050565b600080fd5b6100ca81610088565b81146100d557600080fd5b50565b6000813590506100e7816100c1565b92915050565b600060208284031215610103576101026100bc565b5b6000610111848285016100d8565b9150509291505056fea264697066735822122031443f2fb748bdb27e539fdbeb0c6f575aec50508baaa7e4dbeb08577ef19b3764736f6c63430008110033 ``` ```json theme={null} # Storage.abi [{"inputs":[],"name":"retrieve","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"number","type":"uint256"}],"name":"store","outputs":[],"stateMutability":"nonpayable","type":"function"}] ``` These are all the data required to deploy the contract using the Parallax client Javascript console. Open the Javascript console using `./parallaxd attach parallax.ipc`. Now, for convenice we can store the abi and bytecode in variables in the console: ```javascript theme={null} var abi = [ { inputs: [], name: 'retrieve', outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }], stateMutability: 'view', type: 'function' }, { inputs: [{ internalType: 'uint256', name: 'number', type: 'uint256' }], name: 'store', outputs: [], stateMutability: 'nonpayable', type: 'function' } ]; var bytecode = '608060405234801561001057600080fd5b50610150806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c80632e64cec11461003b5780636057361d14610059575b600080fd5b610043610075565b60405161005091906100a1565b60405180910390f35b610073600480360381019061006e91906100ed565b61007e565b005b60008054905090565b8060008190555050565b6000819050919050565b61009b81610088565b82525050565b60006020820190506100b66000830184610092565b92915050565b600080fd5b6100ca81610088565b81146100d557600080fd5b50565b6000813590506100e7816100c1565b92915050565b600060208284031215610103576101026100bc565b5b6000610111848285016100d8565b9150509291505056fea264697066735822122031443f2fb748bdb27e539fdbeb0c6f575aec50508baaa7e4dbeb08577ef19b3764736f6c63430008110033'; ``` The ABI can be used to create an instance of the contract: ```javascript theme={null} var contract = eth.contract(abi); ``` This contract instance can then be deployed to the blockchain. This is done using `eth.sendTransaction`, passing the contract bytecode in the `data` field. For convenience we can create a transaction JSON object first, then pass it to `eth.sendTransaction` later. Let's use the first account in `eth.accounts` as the sender. The amount of gas to include can be determined using `eth.estimateGas`: ```javascript theme={null} var gas = eth.estimateGas({ data: bytecode }); ``` Note that each command that touches accounts will require **approval in Clef** unless a custom rule has been implemented. The bytecode, gas and address of the sender can be bundled together into an object that will be passed to the contract's `new()` method which deploys the contract. ```javascript theme={null} var tx = { from: eth.accounts[0], data: bytecode, gas: gas }; var deployed_contract = contract.new(tx); ``` The transaction hash and deployment address can now been viewed in the console by entering the variable name (in this case `deployed_contract`): ```javascript theme={null} { abi:[{ inputs: [], name: "retrieve", outputs: [{...}], stateMutability: "view", type: "function" },{ inputs: [], name: "store", outputs: [{...}], stateMutability: "nonpayable", type: "function" }], address: "0x2d6505f8b1130a22a5998cd31788bf6c751247f", transactionHash: "0x5040a8916b23b76696ea9eba5b072546e1112cc481995219081fc86f5b911bf3", allEvents: function bound(), retrieve: function bound(), store: function bound() } ``` Passing the transaction hash to `eth.getTransaction()` returns the deployment transaction details including the contract bytecode in the `input` field. To interact with the contract, create an instance by passing the deployment address to `contract.at` then call the methods. ```javascript theme={null} var instance = contract.at('0x2d6505f8b1130a22a5998cd31788bf6c751247f'); // store() alters the state and therefore requires sendTransaction() contract.set.sendTransaction(42, { from: eth.accounts[0], gas: 1000000 }); // retrieve does not alter state so it can be executed using call() contract.retrieve().call() >> 2; ``` ## Summary This page demonstrated how to create, compile, deploy and interact with a Parallax smart contract using the Parallax client's Javascript console. *** *Adapted from [JavaScript Console 2: Contracts](https://geth.ethereum.org/docs/interacting-with-geth/javascript-console-contracts) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # admin Source: https://docs.parallaxprotocol.org/client/interacting-with-parallax/json-rpc-namespaces/admin The `admin` API gives access to several non-standard RPC methods, which allows fine grained control over an Parallax client instance, including but not limited to network peer and RPC endpoint management. ### admin\_addnode Ingests an address into the addrbook with `source=manual`. Manual entries persist across restarts, are exempt from source-aware bucket eviction, and are heavily weighted in dial selection (a 4x chance multiplier over other sources, not a strict front-of-queue guarantee). Accepts either plain `ip:port` (v2.0-native peers, `KeyType=0x00`) or the legacy `enode://@ip:port` form (v1.x peers, `KeyType=0x01`). Returns `true` if the entry was inserted or updated, `false` otherwise. | CLIENT | METHOD INVOCATION | | - | - | | Console | admin.addnode(address) | | RPC | \{method": "admin\_addnode", "params": \[string]} | #### Example ```javascript theme={null} > admin.addnode("69.62.94.166:32110") true ``` ### 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 method accepts a single argument, the [enode](/protocol/advanced/networking/addresses) URL of the remote peer to start tracking and returns a BOOL indicating whether the peer was accepted for tracking or some error occurred. | CLIENT | METHOD INVOCATION | | - | - | | Go | admin.AddPeer(url string) (bool, error) | | Console | admin.addPeer(url) | | RPC | \{method": "admin\_addPeer", "params": \[url]} | #### Example ```javascript theme={null} > admin.addPeer("enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@52.16.188.185:32110") true ``` ### admin\_addrbookResetKey Regenerates the addrbook's per-node secret `nKey` and clears the tried table atomically. Use after a credible `nKey` leak — without a fresh key, an attacker who learned the old one can predict which buckets future peers will land in and skew the address selection. Destructive: every entry currently in the tried table is moved back to the new table or evicted. Returns `true` on success. | CLIENT | METHOD INVOCATION | | - | - | | Console | admin.addrbookResetKey() | | RPC | \{method": "admin\_addrbookResetKey"} | ### admin\_addrbookStatus Returns a read-only snapshot of the addrbook: total entry count, the new/tried split, and per-source counts (`manual`, `dns_seed`, `tcp_gossip`, `legacy_udp`, plus `self_advertised` when present). | CLIENT | METHOD INVOCATION | | - | - | | Console | admin.addrbookStatus() | | RPC | \{method": "admin\_addrbookStatus"} | #### Example ```javascript theme={null} > admin.addrbookStatus() { total: 1247, new: 1118, tried: 129, perSource: { dns_seed: 64, legacy_udp: 0, manual: 2, tcp_gossip: 1181 } } ``` ### admin\_addTrustedPeer 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. | CLIENT | METHOD INVOCATION | | - | - | | Console | admin.addTrustedPeer(url) | | RPC | \{method": "admin\_addTrustedPeer", "params": \[url]} | ### admin\_clearbanned Removes every entry from the persistent ban list (`/banlist.json`). Does **not** touch the in-memory discourage filter, which is restart-cleared by design. Returns `true` on success. | CLIENT | METHOD INVOCATION | | - | - | | Console | admin.clearbanned() | | RPC | \{method": "admin\_clearbanned"} | ### admin\_datadir The datadir administrative property can be queried for the absolute path the running the Parallax node currently uses to store all its databases. | CLIENT | METHOD INVOCATION | | - | - | | Go | admin.Datadir() (string, error) | | Console | admin.datadir | | RPC | \{method": "admin\_datadir"} | #### Example ```javascript theme={null} > admin.datadir "/home/john/.parallax" ``` ### admin\_dialV2 Directly opens a BIP324-style v2 RLPx connection to the given `ip:port`. Bypasses the addrman routability filter, so it can target loopback / RFC1918 addresses for testing. Operator-testing entry point — peers established via `admin_dialV2` are still subject to all the normal post-handshake checks (peer cap, ban list, self-endpoint guard). Returns `true` if the dial was launched, `false` otherwise. | CLIENT | METHOD INVOCATION | | - | - | | Console | admin.dialV2(address) | | RPC | \{method": "admin\_dialV2", "params": \[string]} | #### Example ```javascript theme={null} > admin.dialV2("127.0.0.1:32110") true ``` ### 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. | CLIENT | METHOD INVOCATION | | - | - | | Console | admin.exportChain(file, first, last) | | RPC | \{method": "admin\_exportChain", "params": \[string, uint64, uint64]} | ### 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. | CLIENT | METHOD INVOCATION | | - | - | | Console | admin.importChain(file) | | RPC | \{method": "admin\_importChain", "params": \[string]} | ### admin\_listbanned Returns the active (non-expired) entries from the persistent ban list as a JSON array, matching Bitcoin Core's `listbanned` output shape. Each entry has the CIDR-formatted subnet, the Unix-second timestamps for `ban_created` and `banned_until`, plus the derived `ban_duration` and `time_remaining` in seconds. Expired entries are pruned lazily on each call. | CLIENT | METHOD INVOCATION | | - | - | | Console | admin.listbanned() | | RPC | \{method": "admin\_listbanned"} | #### Example ```javascript theme={null} > admin.listbanned() [ { address: "10.0.0.0/24", ban_created: 1730000000, banned_until: 1730086400, ban_duration: 86400, time_remaining: 82500 } ] ``` ### admin\_nodeInfo The nodeInfo administrative property can be queried for all the information known about the running the Parallax 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). | CLIENT | METHOD INVOCATION | | - | - | | Go | admin.NodeInfo() (\*p2p.NodeInfo, error) | | Console | admin.nodeInfo | | RPC | \{method": "admin\_nodeInfo"} | #### Example ```javascript theme={null} > admin.nodeInfo { enode: "enode://df18e0e4fea492eef74787a67368ada6200f6ed8ab01a9b105904fac442d720591aa9ab87d33c42ad1abcf24cc3eed373c3eb8dbc0df29b206615cc80a949c94@127.0.0.1:32110", enr: "enr:-KO4QL1FbkA2y9yCx_bXLIXApQKUgPLiCrhszQfXQH6IoCqaJYKHXCBJHm6A0G7NpvJF-MLyr1cS8imBYdgcEigzUm6GAZmWB3qcg2V0aMfGhN4LIImAgmlkgnY0gmlwhH8AAAGJc2VjcDI1NmsxoQLfGODk_qSS7vdHh6ZzaK2mIA9u2KsBqbEFkE-sRC1yBYRzbmFwwIN0Y3CCfW6DdWRwgn1u", id: "6c0a4611b88067d29f43e764475ec3ce70de6139c7316b960deadd29203fa358", ip: "127.0.0.1", listenAddr: "[::]:32110", name: "Parallax/v0.1.1-stable-d9425677/linux-amd64/go1.25.1 X:nodwarf5", ports: { discovery: 32110, listener: 32110 }, protocols: { parallax: { config: { berlinBlock: 0, byzantiumBlock: 0, chainId: 2111, constantinopleBlock: 0, eip150Block: 0, eip150Hash: "0x0000000000000000000000000000000000000000000000000000000000000000", eip155Block: 0, eip158Block: 0, xhash: {...}, homesteadBlock: 0, istanbulBlock: 0, minDifficulty: 33554432, petersburgBlock: 0 }, difficulty: 286554849280, genesis: "0x2b0467e57fabfc5d8082765e7bbc1f6aad8f13ddd937142f51c85e3f7051be5f", head: "0x39a519def2f7eb13b4bc6affa22d34acb6a70c4b52782b8173f9119d9a5e20a8", network: 2111 }, snap: {} } } ``` ### admin\_peerEvents PeerEvents creates an [RPC subscription](/client/interacting-with-parallax/json-rpc-server/realtime-events) 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 * msgsend: emitted when a message is successfully sent to a peer * msgrecv: emitted when a message is received from a peer ### 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). | CLIENT | METHOD INVOCATION | | - | - | | Go | admin.Peers() (\[]\*p2p.PeerInfo, error) | | Console | admin.peers | | RPC | \{method": "admin\_peers"} | `minPing` is the smallest ping/pong round-trip time observed with the peer during the current session, in seconds. It is omitted until the peer has answered its first ping. It was added in v2.1.2. #### Example ```javascript theme={null} > admin.peers [{ caps: ["parallax/66", "snap/1"], enode: "enode://c8d58742fef51a70267a916949cefd0d7ba5bdb75393bbfcbcbc959b3eebf16353ac15d1f7493d749f7f452ff2bec894b8a8c469306e247d265f4f305c5740f7@69.62.94.166:32110", id: "2048d5ae22f7206bc8ad6476a2918bd7558776b0438e0cde4eb579d5d85d8886", minPing: 0.142318, name: "Parallax/v0.1.1-stable-78d2f22b/linux-amd64/go1.25.1", network: { inbound: false, localAddress: "192.168.3.2:37772", remoteAddress: "69.62.94.166:32110", static: false, trusted: false }, protocols: { parallax: { difficulty: 286554849280, head: "0x39a519def2f7eb13b4bc6affa22d34acb6a70c4b52782b8173f9119d9a5e20a8", version: 66 }, snap: { version: 1 } } }, { caps: ["parallax/66", "snap/1"], enode: "enode://d3440cdb8f942e1f01dac2292b7a8f886831800e301c41cf943a4ba4c68e37513920cd94c421fa5e073ed7329d9c3194e3911c857b9ded1677a5234441d9950d@54.94.191.104:32110", id: "4dd1f03a46b51083b7fa10bda14a92ddd0c1e80ec1ef3320c229a098e5f81865", minPing: 0.198731, name: "Parallax/v0.1.1-stable-78d2f22b/linux-arm64/go1.25.1", network: { inbound: false, localAddress: "192.168.3.2:55992", remoteAddress: "54.94.191.104:32110", static: false, trusted: false }, protocols: { parallax: { difficulty: 286689067008, head: "0x46c56ac46f354b18650c623c0605e214f9fb1942e9a77f19489e581d9f39b891", version: 66 }, snap: { version: 1 } } }] ``` ### admin\_removePeer 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. | CLIENT | METHOD INVOCATION | | - | - | | Console | admin.removePeer(url) | | RPC | \{method": "admin\_removePeer", "params": \[string]} | ### admin\_removenode Drops an address from the addrbook regardless of which table holds it. Inverse of `admin_addnode`. Returns `true` if the entry was removed, `false` if it was not present. | CLIENT | METHOD INVOCATION | | - | - | | Console | admin.removenode(address) | | RPC | \{method": "admin\_removenode", "params": \[string]} | ### admin\_removeTrustedPeer Removes a remote node from the trusted peer set, but it does not disconnect it automatically. It returns a boolean indicating validations succeeded. | CLIENT | METHOD INVOCATION | | - | - | | Console | admin.removeTrustedPeer(url) | | RPC | \{method": "admin\_removeTrustedPeer", "params": \[string]} | ### admin\_setban Adds or removes an entry in the persistent ban list. Banned IPs are hard-rejected at the listener for every inbound, with no trusted-peer exemption — the rejection happens before the handshake, so the node cannot yet know whether the remote is trusted. If a banned range must reach a trusted peer, unban it rather than working around the check. Arguments: * `subnet` — IP or CIDR string. `"1.2.3.4"` is treated as `/32`; `"10.0.0.0/24"` as a CIDR. IPv6 supported similarly. * `command` — `"add"` or `"remove"`. * `bantime` — seconds. Honored only on `"add"`. Omitted, `0`, or negative falls back to the daemon's `DefaultBanDuration` (24 h) — relative form only. * `absolute` — when `true`, `bantime` is interpreted as a Unix timestamp instead of an offset from now and must lie in the future (`0` is an error in this form). Defaults to `false`. On `"add"` any currently-connected peer whose remote address matches the subnet is also disconnected, and re-adding a currently-active ban is an error (`IP/subnet already banned`) unless the new expiry extends the old one. On `"remove"` the call returns an error if the subnet was not previously banned. Note for the interactive console: `admin.setban` requires all four positional arguments there — pass `null` for the optional ones, e.g. `admin.setban("1.2.3.4", "add", null, null)`. The JSON-RPC and `parallax-cli` surfaces accept omitted optionals. Returns `true` on success. | CLIENT | METHOD INVOCATION | | - | - | | Console | admin.setban(subnet, command, bantime, absolute) | | RPC | \{method": "admin\_setban", "params": \[string, string, int64, bool]} | #### Example ```javascript theme={null} > admin.setban("10.0.0.0/24", "add", 86400, false) true > admin.setban("10.0.0.0/24", "remove") true ``` ### admin\_startHTTP The startHTTP administrative method starts an HTTP based JSON-RPC [API](/client/interacting-with-parallax/json-rpc-server/overview) 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) * cors: [cross-origin resource sharing](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) header to use (defaults to "") * apis: API modules to offer over this interface (defaults to "eth,net,web3") The method returns a boolean flag specifying whether the HTTP RPC listener was opened or not. Please note, only one HTTP endpoint is allowed to be active at any time. | CLIENT | METHOD INVOCATION | | - | - | | Go | admin.StartHTTP(host \*string, port \*rpc.HexNumber, cors \*string, apis \*string) (bool, error) | | Console | admin.startHTTP(host, port, cors, apis) | | RPC | \{method": "admin\_startHTTP", "params": \[host, port, cors, apis]} | #### Example ```javascript theme={null} > admin.startHTTP("127.0.0.1", 8545) true ``` ### admin\_startWS The startWS administrative method starts an WebSocket based [JSON RPC](/client/interacting-with-parallax/json-rpc-server/overview) 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) * cors: [cross-origin resource sharing](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) header to use (defaults to "") * apis: API modules to offer over this interface (defaults to "eth,net,web3") The method returns a boolean flag specifying whether the WebSocket RPC listener was opened or not. Please note, only one WebSocket endpoint is allowed to be active at any time. | CLIENT | METHOD INVOCATION | | - | - | | Go | admin.StartWS(host \*string, port \*rpc.HexNumber, cors \*string, apis \*string) (bool, error) | | Console | admin.startWS(host, port, cors, apis) | | RPC | \{method": "admin\_startWS", "params": \[host, port, cors, apis]} | #### Example ```javascript theme={null} > admin.startWS("127.0.0.1", 8546) true ``` ### admin\_uptime Returns the number of seconds the node has been running since its most recent `Start`. Returns 0 if the node is not yet fully started. Mirrors Bitcoin Core's `uptime` command and backs the `parallax-cli uptime` command-line helper. | CLIENT | METHOD INVOCATION | | - | - | | Go | admin.Uptime() (uint64, error) | | Console | admin.uptime() | | RPC | \{method": "admin\_uptime"} | #### Example ```javascript theme={null} > admin.uptime() 86400 ``` ### admin\_stop Gracefully shuts down the running node. The method schedules the shutdown on a short delay (about 100 ms) and returns immediately so the RPC response can be delivered before the RPC server itself tears down. Client callers should therefore tolerate the RPC connection being closed without a final response — that outcome still indicates a successful shutdown. This is the underlying method used by the `parallax-cli stop` command-line helper, analogous to `bitcoin-cli stop` in Bitcoin Core. | CLIENT | METHOD INVOCATION | | - | - | | Go | admin.Stop() (bool, error) | | Console | admin.stop() | | RPC | \{method": "admin\_stop"} | #### Example ```javascript theme={null} > admin.stop() true ``` ### admin\_stopHTTP The stopHTTP administrative method closes the currently open HTTP RPC endpoint. As the node can only have a single HTTP endpoint running, this method takes no parameters, returning a boolean whether the endpoint was closed or not. | CLIENT | METHOD INVOCATION | | - | - | | Go | admin.StopHTTP() (bool, error) | | Console | admin.stopHTTP() | | RPC | \{method": "admin\_stopHTTP"} | #### Example ```javascript theme={null} > admin.stopHTTP() true ``` ### admin\_stopWS The stopWS administrative method closes the currently open WebSocket RPC endpoint. As the node can only have a single WebSocket endpoint running, this method takes no parameters, returning a boolean whether the endpoint was closed or not. | CLIENT | METHOD INVOCATION | | - | - | | Go | admin.StopWS() (bool, error) | | Console | admin.stopWS() | | RPC | \{method": "admin\_stopWS"} | #### Example ```javascript theme={null} > admin.stopWS() true ``` *** *Partly adapted from [admin Namespace](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-admin) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # clique Source: https://docs.parallaxprotocol.org/client/interacting-with-parallax/json-rpc-namespaces/clique The `clique` API provides access to the state of the clique consensus engine. This API can be used to manage signer votes and to check the health of a private network. ### clique\_getSnapshot Retrieves a snapshot of all clique state at a given block. | CLIENT | METHOD INVOCATION | | - | - | | Console | clique.getSnapshot(blockNumber) | | RPC | \{method": "clique\_getSnapshot", "params": \[blockNumber]} | Example: ```javascript theme={null} > clique.getSnapshot(5463755) { hash: "0x018194fc50ca62d973e2f85cffef1e6811278ffd2040a4460537f8dbec3d5efc", number: 5463755, recents: { 5463752: "0x42eb768f2244c8811c63729a21a3569731535f06", 5463753: "0x6635f83421bf059cd8111f180f0727128685bae4", 5463754: "0x7ffc57839b00206d1ad20c69a1981b489f772031", 5463755: "0xb279182d99e65703f0076e4812653aab85fca0f0" }, signers: { 0x42eb768f2244c8811c63729a21a3569731535f06: {}, 0x6635f83421bf059cd8111f180f0727128685bae4: {}, 0x7ffc57839b00206d1ad20c69a1981b489f772031: {}, 0xb279182d99e65703f0076e4812653aab85fca0f0: {}, 0xd6ae8250b8348c94847280928c79fb3b63ca453e: {}, 0xda35dee8eddeaa556e4c26268463e26fb91ff74f: {}, 0xfc18cbc391de84dbd87db83b20935d3e89f5dd91: {} }, tally: {}, votes: [] } ``` ### clique\_getSnapshotAtHash Retrieves the state snapshot at a given block. | CLIENT | METHOD INVOCATION | | - | - | | Console | clique.getSnapshotAtHash(blockHash) | | RPC | \{method": "clique\_getSnapshotAtHash", "params": \[blockHash]} | ### 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. | CLIENT | METHOD INVOCATION | | - | - | | Console | clique.getSigner(blockNrOrHashOrRlp) | | RPC | \{method": "clique\_getSigner", "params": \[string]} | ### clique\_getSigners Retrieves the list of authorized signers at the specified block number. | CLIENT | METHOD INVOCATION | | - | - | | Console | clique.getSigners(blockNumber) | | RPC | \{method": "clique\_getSigners", "params": \[blockNumber]} | ### clique\_getSignersAtHash Retrieves the list of authorized signers at the specified block hash. | CLIENT | METHOD INVOCATION | | - | - | | Console | clique.getSignersAtHash(blockHash) | | RPC | \{method": "clique\_getSignersAtHash", "params": \[string]} | ### clique\_proposals Returns the current proposals the node is voting on. | CLIENT | METHOD INVOCATION | | - | - | | Console | clique.proposals() | | RPC | \{method": "clique\_proposals", "params": \[]} | ### 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. | CLIENT | METHOD INVOCATION | | - | - | | Console | clique.propose(address, auth) | | RPC | \{method": "clique\_propose", "params": \[address, auth]} | ### clique\_discard This method drops a currently running proposal. The signer will not cast further votes (either for or against) the address. | CLIENT | METHOD INVOCATION | | - | - | | Console | clique.discard(address) | | RPC | \{method": "clique\_discard", "params": \[address]} | ### clique\_status This is a debugging method which returns statistics about signer activity for the last 64 blocks. The returned object contains the following fields: * inturnPercent: percentage of blocks signed in-turn * sealerActivity: object containing signer addresses and the number of blocks signed by them * numBlocks: number of blocks analyzed | CLIENT | METHOD INVOCATION | | - | - | | Console | clique.status() | | RPC | \{method": "clique\_status", "params": \[]} | Example: ```javascript theme={null} > clique.status() { inturnPercent: 100, numBlocks: 64, sealerActivity: { 0x42eb768f2244c8811c63729a21a3569731535f06: 9, 0x6635f83421bf059cd8111f180f0727128685bae4: 9, 0x7ffc57839b00206d1ad20c69a1981b489f772031: 9, 0xb279182d99e65703f0076e4812653aab85fca0f0: 10, 0xd6ae8250b8348c94847280928c79fb3b63ca453e: 9, 0xda35dee8eddeaa556e4c26268463e26fb91ff74f: 9, 0xfc18cbc391de84dbd87db83b20935d3e89f5dd91: 9 } } ``` *** *Adapted from [clique Namespace](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-clique) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # debug Source: https://docs.parallaxprotocol.org/client/interacting-with-parallax/json-rpc-namespaces/debug The `debug` API gives you access to several non-standard RPC methods, which will allow you to inspect, debug and set certain debugging flags during runtime. ### debug\_accountRange Enumerates all accounts at a given block with paging capability. `maxResults` are returned in the page and the items have keys that come after the `start` key (hashed address). If `incompletes` is false, then accounts for which the key preimage (i.e: the `address`) doesn't exist in db are skipped. NB: the Parallax client by default does not store preimages. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.accountRange(blockNrOrHash, start, maxResults, nocode, nostorage, incompletes) | | RPC | \{method": "debug\_accountRange", "params": \[blockNrOrHash, start, maxResults, nocode, nostorage, incompletes]} | ### 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. The location is specified as `:`. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.backtraceAt(string) | | RPC | \{method": "debug\_backtraceAt", "params": \[string]} | Example: ```javascript theme={null} > debug.backtraceAt("server.go:443") ``` ### 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`. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.blockProfile(file, seconds) | | RPC | \{method": "debug\_blockProfile", "params": \[string, number]} | ### debug\_chaindbCompact Flattens the entire key-value database into a single level, removing all unused slots and merging all keys. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.chaindbCompact() | | RPC | \{method": "debug\_chaindbCompact", "params": \[]} | ### debug\_chaindbProperty Returns leveldb properties of the key-value database. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.chaindbProperty(property string) | | RPC | \{method": "debug\_chaindbProperty", "params": \[property]} | ### debug\_dbStats Returns a summary of on-disk database sizes. The `ancients` object lists per-category frozen-chain sizes in bytes; `leveldb` carries the same human-readable compaction-stats table that `debug_chaindbProperty("leveldb.stats")` returns. Intended for quick storage-use checks and backs the `parallax-cli dbstats` command-line helper. | CLIENT | METHOD INVOCATION | | - | - | | Go | debug.DbStats() (map\[string]interface, error) | | Console | debug.dbStats() | | RPC | \{method": "debug\_dbStats"} | #### Example ```javascript theme={null} > debug.dbStats() { ancients: { bodies: 123456789, diffs: 12345, hashes: 23456, headers: 3456789, receipts: 234567890 }, leveldb: "Compactions\n Level | Tables | Size(MB) ..." } ``` ### debug\_cpuProfile Turns on CPU profiling for the given duration and writes profile data to disk. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.cpuProfile(file, seconds) | | RPC | \{method": "debug\_cpuProfile", "params": \[string, number]} | ### 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: * `headers`: block headers * `hashes`: canonical hash table (block number -> block hash) * `bodies`: block bodies * `receipts`: block receipts * `diffs`: total difficulty table (block number -> td) | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.dbAncient(kind string, number uint64) | | RPC | \{method": "debug\_dbAncient", "params": \[string, number]} | ### debug\_dbAncients Returns the number of ancient items in the ancient store. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.dbAncients() | | RPC | \{method": "debug\_dbAncients"} | ### debug\_dbGet Returns the raw value of a key stored in the database. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.dbGet(key string) | | RPC | \{method": "debug\_dbGet", "params": \[key]} | ### debug\_dumpBlock Retrieves the state that corresponds to the block number and returns a list of accounts (including storage and code). | CLIENT | METHOD INVOCATION | | - | - | | Go | debug.DumpBlock(number uint64) (state.Dump, error) | | Console | debug.traceBlockByHash(number, \[options]) | | RPC | \{method": "debug\_dumpBlock", "params": \[number]} | **Example** ```javascript theme={null} > debug.dumpBlock(10) { fff7ac99c8e4feb60c9750054bdc14ce1857f181: { balance: "49358640978154672", code: "", codeHash: "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", nonce: 2, root: "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", storage: {} }, fffbca3a38c3c5fcb3adbb8e63c04c3e629aafce: { balance: "3460945928", code: "", codeHash: "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", nonce: 657, root: "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", storage: {} } }, root: "19f4ed94e188dd9c7eb04226bd240fa6b449401a6c656d6d2816a87ccaf206f1" } ``` ### debug\_freeOSMemory Forces garbage collection | CLIENT | METHOD INVOCATION | | - | - | | Go | debug.FreeOSMemory() | | Console | debug.freeOSMemory() | | RPC | \{method": "debug\_freeOSMemory", "params": \[]} | ### debug\_freezeClient Forces a temporary client freeze, normally when the server is overloaded. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.freezeClient(node string) | | RPC | \{method": "debug\_freezeClient", "params": \[node]} | ### debug\_gcStats Returns garbage collection statistics. See [this](https://golang.org/pkg/runtime/debug/#GCStats) for information about the fields of the returned object. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.gcStats() | | RPC | \{method": "debug\_gcStats", "params": \[]} | ### 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. Note: to get the last state pass in the range of blocks in reverse, i.e. (last, first). | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.getAccessibleState(from, to rpc.BlockNumber) | | RPC | \{method": "debug\_getAccessibleState", "params": \[from, to]} | ### 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. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.getBadBlocks() | | RPC | \{method": "debug\_getBadBlocks", "params": \[]} | ### debug\_getRawBlock Retrieves and returns the RLP encoded block by number. | CLIENT | METHOD INVOCATION | | - | - | | Go | debug.getRawBlock(blockNrOrHash) (string, error) | | Console | debug.getBlockRlp(blockNrOrHash) | | RPC | \{method": "debug\_getRawBlock", "params": \[blockNrOrHash]} | References: [RLP](/protocol/advanced/data-structures/rlp) ### debug\_getRawHeader Returns an RLP-encoded header. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.getRawHeader(blockNrOrHash) | | RPC | \{method": "debug\_getRawHeader", "params": \[blockNrOrHash]} | ### debug\_getRawTransaction Returns the bytes of the transaction. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.getRawTransaction(blockNrOrHash) | | RPC | \{method": "debug\_getRawTransaction", "params": \[transactionHash]} | ### 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. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.getModifiedAccountsByHash(startHash, endHash) | | RPC | \{method": "debug\_getModifiedAccountsByHash", "params": \[startHash, endHash]} | ### 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. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.getModifiedAccountsByNumber(startNum uint64, endNum uint64) | | RPC | \{method": "debug\_getModifiedAccountsByNumber", "params": \[startNum, endNum]} | > [!NOTE] > > The Parallax client only keeps recent trie nodes and preimages of keys in memory - for older blocks this information is deleted by client's garbage collection. This means that calls to `debug_GetModifiedAccountsByNumber` on blocks that are old enough to be eligible for garbage collection will return an error due to the trie nodes and preimages being unavailable. To fix this, run the Parallax client with `--cache.preimages=true` to prevent the relevant data being lost to the garbage collector ### debug\_getRawReceipts Returns the consensus-encoding of all receipts in a single block. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.getRawReceipts(blockNrOrHash) | | RPC | \{method": "debug\_getRawReceipts", "params": \[blockNrOrHash]} | ### debug\_goTrace 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 Executes a block (bad- or canon- or side-), and returns a list of intermediate roots: the stateroot after each transaction. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.intermediateRoots(blockHash, \[options]) | | RPC | \{method": "debug\_intermediateRoots", "params": \[blockHash, ]} | ### debug\_memStats Returns detailed runtime memory statistics. See [this](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 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. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.mutexProfile(file, nsec) | | RPC | \{method": "debug\_mutexProfile", "params": \[file, nsec]} | ### debug\_preimage Returns the preimage for a sha3 hash, if known. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.preimage(hash) | | RPC | \{method": "debug\_preimage", "params": \[hash]} | ### debug\_printBlock Retrieves a block and returns its pretty printed form. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.printBlock(number uint64) | | RPC | \{method": "debug\_printBlock", "params": \[number]} | ### debug\_seedHash Fetches and retrieves the seed hash of the block by number | CLIENT | METHOD INVOCATION | | - | - | | Go | debug.SeedHash(number uint64) (string, error) | | Console | debug.seedHash(number, \[options]) | | RPC | \{method": "debug\_seedHash", "params": \[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. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.setBlockProfileRate(rate) | | RPC | \{method": "debug\_setBlockProfileRate", "params": \[number]} | ### debug\_setGCPercent Sets the garbage collection target percentage. A negative value disables garbage collection. | CLIENT | METHOD INVOCATION | | - | - | | Go | debug.SetGCPercent(v int) | | Console | debug.setGCPercent(v) | | RPC | \{method": "debug\_setGCPercent", "params": \[v]} | ### 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. | CLIENT | METHOD INVOCATION | | - | - | | Go | debug.SetHead(number uint64) | | Console | debug.setHead(number) | | RPC | \{method": "debug\_setHead", "params": \[number]} | ### debug\_setMutexProfileFraction Sets the rate of mutex profiling. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.setMutexProfileFraction(rate int) | | RPC | \{method": "debug\_setMutexProfileFraction", "params": \[rate]} | ### debug\_setTrieFlushInterval Configures how often in-memory state tries are persisted to disk. The interval needs to be in a format parsable by a [time.Duration](https://pkg.go.dev/time#ParseDuration). Note that the interval is not wall-clock time. Rather it is accumulated block processing time after which the state should be flushed. For example the value 0s will essentially turn on archive mode. If set to 1h, it means that after one hour of effective block processing time, the trie would be flushed. If one block takes 200ms, a flush would occur every 5\*3600=18000 blocks. The default interval for mainnet is 1h. > [!NOTE] > > This configuration will not be presisted through restarts. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.setTrieFlushInterval(interval string) | | RPC | \{method": "debug\_setTrieFlushInterval", "params": \[interval]} | ### 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. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.stacks() | | RPC | \{method": "debug\_stacks", "params": \[]} | ### 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)) * 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) * Uses a cross-client standardized output, so called 'standard json' * Uses op for string-representation of opcode, instead of op/opName for numeric/string, and other simlar small differences. * has refund * Represents memory as a contiguous chunk of data, as opposed to a list of 32-byte segments like debug\_traceTransaction 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: ```javascript theme={null} > debug.standardTraceBlockToFile("0x0bbe9f1484668a2bf159c63f0cf556ed8c8282f99e3ffdb03ad2175a863bca63", {txHash:"0x4049f61ffbb0747bb88dc1c85dd6686ebf225a3c10c282c45a8e0c644739f7e9", disableMemory:true}) ["/tmp/block_0x0bbe9f14-14-0x4049f61f-099048234"] ``` Or all txs from a block: ```javascript theme={null} > debug.standardTraceBlockToFile("0x0bbe9f1484668a2bf159c63f0cf556ed8c8282f99e3ffdb03ad2175a863bca63", {disableMemory:true}) ["/tmp/block_0x0bbe9f14-0-0xb4502ea7-409046657", "/tmp/block_0x0bbe9f14-1-0xe839be8f-954614764", "/tmp/block_0x0bbe9f14-2-0xc6e2052f-542255195", "/tmp/block_0x0bbe9f14-3-0x01b7f3fe-209673214", "/tmp/block_0x0bbe9f14-4-0x0f290422-320999749", "/tmp/block_0x0bbe9f14-5-0x2dc0fb80-844117472", "/tmp/block_0x0bbe9f14-6-0x35542da1-256306111", "/tmp/block_0x0bbe9f14-7-0x3e199a08-086370834", "/tmp/block_0x0bbe9f14-8-0x87778b88-194603593", "/tmp/block_0x0bbe9f14-9-0xbcb081ba-629580052", "/tmp/block_0x0bbe9f14-10-0xc254381a-578605923", "/tmp/block_0x0bbe9f14-11-0xcc434d58-405931366", "/tmp/block_0x0bbe9f14-12-0xce61967d-874423181", "/tmp/block_0x0bbe9f14-13-0x05a20b35-267153288", "/tmp/block_0x0bbe9f14-14-0x4049f61f-606653767", "/tmp/block_0x0bbe9f14-15-0x46d473d2-614457338", "/tmp/block_0x0bbe9f14-16-0x35cf5500-411906321", "/tmp/block_0x0bbe9f14-17-0x79222961-278569788", "/tmp/block_0x0bbe9f14-18-0xad84e7b1-095032683", "/tmp/block_0x0bbe9f14-19-0x4bd48260-019097038", "/tmp/block_0x0bbe9f14-20-0x1517411d-292624085", "/tmp/block_0x0bbe9f14-21-0x6857e350-971385904", "/tmp/block_0x0bbe9f14-22-0xbe3ae2ca-236639695"] ``` Files are created in a temp-location, with the naming standard `block_---`. Each opcode immediately streams to file, with no in-client buffering aside from whatever buffering the os normally does. On the server side, it also adds some more info when regenerating historical state, namely, the reexec-number if required historical state is not avaiable is encountered, so a user can experiment with increasing that setting. It also prints out the remaining block until it reaches target: ``` INFO [10-15|13:48:25.263] Regenerating historical state block=2385959 target=2386012 remaining=53 elapsed=3m30.990537767s INFO [10-15|13:48:33.342] Regenerating historical state block=2386012 target=2386012 remaining=0 elapsed=3m39.070073163s INFO [10-15|13:48:33.343] Historical state regenerated block=2386012 elapsed=3m39.070454362s nodes=10.03mB preimages=652.08kB INFO [10-15|13:48:33.352] Wrote trace file=/tmp/block_0x14490c57-0-0xfbbd6d91-715824834 INFO [10-15|13:48:33.352] Wrote trace file=/tmp/block_0x14490c57-1-0x71076194-187462969 INFO [10-15|13:48:34.421] Wrote trace file=/tmp/block_0x14490c57-2-0x3f4263fe-056924484 ``` The options is as follows: ```javascript theme={null} type StdTraceConfig struct { *vm.LogConfig Reexec *uint64 TxHash *util.Hash } ``` ### debug\_standardTraceBadBlockToFile This method is similar to [`debug_standardTraceBlockToFile`](#debug_standardtraceblocktofile), but can be used to obtain info about a block which has been *rejected* as invalid (for some reason). ### debug\_startCPUProfile Turns on CPU profiling indefinitely, writing to the given file. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.startCPUProfile(file) | | RPC | \{method": "debug\_startCPUProfile", "params": \[string]} | ### debug\_startGoTrace Starts writing a Go runtime trace to the given file. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.startGoTrace(file) | | RPC | \{method": "debug\_startGoTrace", "params": \[string]} | ### debug\_stopCPUProfile Stops an ongoing CPU profile. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.stopCPUProfile() | | RPC | \{method": "debug\_stopCPUProfile", "params": \[]} | ### debug\_stopGoTrace Stops writing the Go runtime trace. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.startGoTrace(file) | | RPC | \{method": "debug\_stopGoTrace", "params": \[]} | ### 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). | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.storageRangeAt(blockHash, txIdx, contractAddress, keyStart, maxResult) | | RPC | \{method": "debug\_storageRangeAt", "params": \[blockHash, txIdx, contractAddress, keyStart, maxResult]} | ### 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 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 \*TraceConfig) BlockTraceResult | | Console | debug.traceBlock(tblockRlp, \[options]) | | RPC | \{method": "debug\_traceBlock", "params": \[blockRlp, ]} | References: [RLP](/protocol/advanced/data-structures/rlp) **Example** ```javascript theme={null} > debug.traceBlock("0xblock_rlp") { gas: 85301, returnValue: "", structLogs: [{ depth: 1, error: "", gas: 162106, gasCost: 3, memory: null, op: "PUSH1", pc: 0, stack: [], storage: {} }, /* snip */ { depth: 1, error: "", gas: 100000, gasCost: 0, memory: ["0000000000000000000000000000000000000000000000000000000000000006", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000060"], op: "STOP", pc: 120, stack: ["00000000000000000000000000000000000000000000000000000000d67cbec9"], storage: { 0000000000000000000000000000000000000000000000000000000000000004: "8241fa522772837f0d05511f20caa6da1d5a3209000000000000000400000001", 0000000000000000000000000000000000000000000000000000000000000006: "0000000000000000000000000000000000000000000000000000000000000001", f652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f: "00000000000000000000000002e816afc1b5c0f39852131959d946eb3b07b5ad" } }] ``` ### 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. For the second parameter see [TraceConfig](#traceconfig) reference. | CLIENT | METHOD INVOCATION | | - | - | | Go | debug.TraceBlockByNumber(number uint64, config \*TraceConfig) BlockTraceResult | | Console | debug.traceBlockByNumber(number, \[options]) | | RPC | \{method": "debug\_traceBlockByNumber", "params": \[number, ]} | References: [RLP](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/) ### 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. For the second parameter see [TraceConfig](#traceconfig) reference. | CLIENT | METHOD INVOCATION | | - | - | | Go | debug.TraceBlockByHash(hash util.Hash, config \*TraceConfig) BlockTraceResult | | Console | debug.traceBlockByHash(hash, \[options]) | | RPC | \{method": "debug\_traceBlockByHash", "params": \[hash ]} | References: [RLP](/protocol/advanced/data-structures/rlp) ### 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](/protocol/advanced/data-structures/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. The block can be specified either by hash or by number as the second argument. The trace can be configured similar to [debug\_traceTransaction](#debug_tracetransaction), see [TraceConfig](#traceconfig). The method returns the same output as [debug\_traceTransaction](#debug_tracetransaction). | CLIENT | METHOD INVOCATION | | - | - | | Go | debug.TraceCall(args ethapi.CallArgs, blockNrOrHash rpc.BlockNumberOrHash, config \*TraceConfig) (\*ExecutionResult, error) | | Console | debug.traceCall(object, blockNrOrHash, \[options]) | | RPC | \{method": "debug\_traceCall", "params": \[object, blockNrOrHash, ]} | **Example** No specific call options: ```javascript theme={null} > debug.traceCall(null, "0x0") { failed: false, gas: 53000, returnValue: "", structLogs: [] } ``` Tracing a call with a destination and specific sender, disabling the storage and memory output (less data returned over RPC) ```javascript theme={null} debug.traceCall( { from: '0xdeadbeef29292929192939494959594933929292', to: '0xde929f939d939d393f939393f93939f393929023', gas: '0x7a120', data: '0xf00d4b5d00000000000000000000000001291230982139282304923482304912923823920000000000000000000000001293123098123928310239129839291010293810' }, '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: ```javascript theme={null} > debug.traceCall({ from: eth.accounts[0], value:"0x1", gasPrice: "0xffffffff", gas: "0xffff", input: "0x43"}, "latest", \{blockoverrides": \{number": "0x50"} }) { failed: false, gas: 53018, returnValue: "", structLogs: [{ depth: 1, gas: 12519, gasCost: 2, op: "NUMBER", pc: 0, stack: [] }, { depth: 1, gas: 12517, gasCost: 0, op: "STOP", pc: 1, stack: ["0x50"] }] } ``` Curl example: ```sh theme={null} > 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 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: ```javascript theme={null} const res = provider.send('debug_subscribe', ['traceChain', '0x3f3a2a', '0x3f3a2b'])` ``` please refer to the [subscription page](/client/interacting-with-parallax/json-rpc-server/realtime-events) for more details. ### debug\_traceTransaction **OBS** In most scenarios, [debug.standardTraceBlockToFile](#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 hash. | CLIENT | METHOD INVOCATION | | - | - | | Go | debug.TraceTransaction(txHash util.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. 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](/client/developers/pvm-tracing/built-in). The Parallax client comes with a bundle of [built-in tracers](/client/developers/pvm-tracing/built-in), each providing various data about a transaction. This method defaults to the [struct logger](/client/developers/pvm-tracing/built-in). The tracer field of the second parameter can be set to use any of the other tracers. Alternatively a [custom tracer](/client/developers/pvm-tracing/custom-pvm) can be implemented in either Go or Javascript. **Example** ```javascript theme={null} > debug.traceTransaction("0x2059dd53ecac9827faad14d364f9e04b1d5fe5b506e3acc886eff7a6f88a696a") { gas: 85301, returnValue: "", structLogs: [{ depth: 1, error: "", gas: 162106, gasCost: 3, memory: null, op: "PUSH1", pc: 0, stack: [], storage: {} }, /* snip */ { depth: 1, error: "", gas: 100000, gasCost: 0, memory: ["0000000000000000000000000000000000000000000000000000000000000006", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000060"], op: "STOP", pc: 120, stack: ["00000000000000000000000000000000000000000000000000000000d67cbec9"], storage: { 0000000000000000000000000000000000000000000000000000000000000004: "8241fa522772837f0d05511f20caa6da1d5a3209000000000000000400000001", 0000000000000000000000000000000000000000000000000000000000000006: "0000000000000000000000000000000000000000000000000000000000000001", f652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f: "00000000000000000000000002e816afc1b5c0f39852131959d946eb3b07b5ad" } }] ``` ### 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. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.verbosity(level) | | RPC | \{method": "debug\_vmodule", "params": \[number]} | ### debug\_vmodule Sets the logging verbosity pattern. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.vmodule(string) | | RPC | \{method": "debug\_vmodule", "params": \[string]} | **Examples** If you want to see messages from a particular Go package (directory) and all subdirectories, use: ```javascript theme={null} > debug.vmodule("node/*=6") ``` If you want to restrict messages to a particular package (e.g. p2p) but exclude subdirectories, use: ```javascript theme={null} > debug.vmodule("p2p=6") ``` If you want to see log messages from a particular source file, use ```javascript theme={null} > 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 node (node/peer.go, node/fullnode/peer.go) as well as output from package p2p at level \<= 5, use: ```javascript theme={null} debug.vmodule('node/*/peer.go=6,p2p=5'); ``` ### debug\_writeBlockProfile Writes a goroutine blocking profile to the given file. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.writeBlockProfile(file) | | RPC | \{method": "debug\_writeBlockProfile", "params": \[string]} | ### 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. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.writeMemProfile(file string) | | RPC | \{method": "debug\_writeBlockProfile", "params": \[string]} | ### debug\_writeMutexProfile Writes a goroutine blocking profile to the given file. | CLIENT | METHOD INVOCATION | | - | - | | Console | debug.writeMutexProfile(file) | | RPC | \{method": "debug\_writeMutexProfile", "params": \[file]} | *** *Adapted from [debug Namespace](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-debug) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # eth Source: https://docs.parallaxprotocol.org/client/interacting-with-parallax/json-rpc-namespaces/eth Documentation for the API methods in the eth namespace can be found on [here](/protocol/parallax-stack/apis/json-rpc). The Parallax client provides several extensions to the standard "eth" JSON-RPC namespace that are defined below. ## eth\_subscribe, eth\_unsubscribe These methods are used for real-time events through subscriptions. See the [subscription documentation](/client/interacting-with-parallax/json-rpc-server/realtime-events) for more information. ## eth\_call Executes a new message call immediately, without creating a transaction on the block chain. The [eth\_call](#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. ### **1. Object - Transaction call object** The *transaction call object* is mandatory. ### **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). ### **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: | FIELD | TYPE | BYTES | OPTIONAL | DESCRIPTION | | - | - | - | - | - | | balance | Quantity | \<32 | Yes | Fake balance to set for the account before executing the call. | | nonce | Quantity | \<8 | Yes | Fake nonce to set for the account before executing the call. | | code | Binary | any | Yes | Fake EVM bytecode to inject into the account before executing the call. | | state | Object | any | Yes | Fake key-value mapping to override **all** slots in the account storage before executing the call. | | stateDiff | Object | any | Yes | Fake key-value mapping to override **individual** slots in the account storage before executing the call. | 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. Example: ```json theme={null} { "0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3": { "balance": "0xde0b6b3a7640000" }, "0xebe8efa441b9302a0d7eaecc277c09d20d684540": { "code": "0x...", "state": { "" } } } ``` **Return Values** The method returns a single Binary consisting the return value of the executed contract call. ## 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 and blockNumberOrTag object as [eth\_call](#eth_call). An accessList can be used to unstuck contracts that became inaccessible due to gas cost increases. **Parameters** | FIELD | TYPE | DESCRIPTION | | - | - | - | | transaction | Object | TransactionCall object | | blockNumberOrTag | Object | Optional, blocknumber or latest or pending | **Usage** ``` curl --data '{"method":"eth_createAccessList","params":[{"from": "0x8cd02c6cbd8375b39b06577f8d50c51d86e8d5cd", "data": "0x608060806080608155"}, "pending"],"id":1,"jsonrpc":"2.0"}' -H "Content-Type: application/json" -X POST localhost:8545 ``` **Response** The method [eth\_createAccessList](#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. Example: ```json theme={null} { "accessList": [ { "address": "0xa02457e5dfd32bda5fc7e1f1b008aa5979568150", "storageKeys": [ "0x0000000000000000000000000000000000000000000000000000000000000081", ] } ] "gasUsed": "0x125f8" } ``` ## eth\_getHeaderByNumber Returns a block header. **Parameters** | FIELD | TYPE | DESCRIPTION | | - | - | - | | blockNumber | Quantity | Block number | **Usage** `curl localhost:8545 -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_getHeaderByNumber","params":["0xe934"],"id":0}'` **Response** ```json theme={null} { "difficulty": "0x44eccd7eda7", "epochStartTime": "0x6ac4e0d9", "extraData": "0xd8830102008470726c7888676f312e32352e31856c696e7578", "gasLimit": "0x23c34600", "gasUsed": "0x0", "hash": "0xe7afc97ee43bc6024f6bf57d9912678709c31b089ffb972cb265e72f4629a25f", "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "miner": "0x38432a328b3c6f15582292f7235f17b08a98c6ab", "mixHash": "0x658efc6d3c3cc52e6996a5d0803f258a8568cc34f0789da67101245c10dfd625", "nonce": "0x85943e36390c08d3", "number": "0xe934", "parentHash": "0x3eff702e910b1562ae6e40ce29c1f53449daf63808a49460cc3f7b6a11618fde", "receiptsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", "size": "0x230", "stateRoot": "0xdbd2f3ccaacca4fbe8fd6006b2b2fd98204d674d15acae6b13a115039c37274b", "timestamp": "0x6ace88cf", "totalDifficulty": "0x1c357248a071b48d", "transactionsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421" } ``` ## eth\_getHeaderByHash Returns a block header. **Parameters** | FIELD | TYPE | DESCRIPTION | | - | - | - | | blockHash | string | Block hash | **Usage** ``` curl localhost:8545 -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_getHeaderByHash","params":["0xe7afc97ee43bc6024f6bf57d9912678709c31b089ffb972cb265e72f4629a25f"],"id":0}' ``` **Response** ```json theme={null} { "difficulty": "0x44eccd7eda7", "epochStartTime": "0x6ac4e0d9", "extraData": "0xd8830102008470726c7888676f312e32352e31856c696e7578", "gasLimit": "0x23c34600", "gasUsed": "0x0", "hash": "0xe7afc97ee43bc6024f6bf57d9912678709c31b089ffb972cb265e72f4629a25f", "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "miner": "0x38432a328b3c6f15582292f7235f17b08a98c6ab", "mixHash": "0x658efc6d3c3cc52e6996a5d0803f258a8568cc34f0789da67101245c10dfd625", "nonce": "0x85943e36390c08d3", "number": "0xe934", "parentHash": "0x3eff702e910b1562ae6e40ce29c1f53449daf63808a49460cc3f7b6a11618fde", "receiptsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", "size": "0x230", "stateRoot": "0xdbd2f3ccaacca4fbe8fd6006b2b2fd98204d674d15acae6b13a115039c37274b", "timestamp": "0x6ace88cf", "totalDifficulty": "0x1c357248a071b48d", "transactionsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421" } ``` *** *Partly adapted from [eth Namespace](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-eth) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # miner Source: https://docs.parallaxprotocol.org/client/interacting-with-parallax/json-rpc-namespaces/miner The miner API is responsible to provide remote control the node's mining operation and set various mining specific settings. ### miner\_getHashrate Get hashrate in H/s (Hash operations per second). | CLIENT | METHOD INVOCATION | | - | - | | Console | miner.getHashrate() | | RPC | \{"method": "miner\_getHashrate", "params": \[]} | ### miner\_setExtra Sets the extra data a miner can include when miner blocks. This is capped at 32 bytes. | CLIENT | METHOD INVOCATION | | - | - | | Go | miner.setExtra(extra string) (bool, error) | | Console | miner.setExtra(string) | | RPC | \{"method": "miner\_setExtra", "params": \[string]} | ### miner\_setGasPrice Sets the minimal accepted gas price when mining transactions. Any transactions that are below this limit are excluded from the mining process. | CLIENT | METHOD INVOCATION | | - | - | | Go | miner.setGasPrice(number \*rpc.HexNumber) bool | | Console | miner.setGasPrice(number) | | RPC | \{"method": "miner\_setGasPrice", "params": \[number]} | ### miner\_setRecommitInterval Updates the interval for recomitting the miner sealing work. | CLIENT | METHOD INVOCATION | | - | - | | Console | miner.setRecommitInterval(interval int) | | RPC | \{"method": "miner\_setRecommitInterval", "params": \[number]} | ### miner\_start Start the CPU mining process. | CLIENT | METHOD INVOCATION | | - | - | | Go | miner.Start() error | | Console | miner.start() | | RPC | \{"method": "miner\_start", "params": \[]} | ### miner\_stop Stop the CPU mining operation. | CLIENT | METHOD INVOCATION | | - | - | | Go | miner.Stop() bool | | Console | miner.stop() | | RPC | \{"method": "miner\_stop", "params": \[]} | ### miner\_setCoinbase Sets the coinbase, where mining rewards will go. | CLIENT | METHOD INVOCATION | | - | - | | Go | miner.SetCoinbase(util.Address) bool | | Console | miner.setCoinbase(address) | | RPC | \{"method": "miner\_setCoinbase", "params": \[address]} | ### miner\_setGasLimit Sets the gas limit the miner will target when mining. Note: on networks where EIP-1559 is activated, this should be set to twice the gas target (i.e. the effective gas used on average per block) to be. | CLIENT | METHOD INVOCATION | | - | - | | Go | miner.SetGasLimit(number \*rpc.HexNumber) bool | | Console | miner.SetGasLimit(number) | | RPC | \{"method": "miner\_setGasLimit", "params": \[number]} | *** *Adapted from [miner Namespace](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-miner) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # net Source: https://docs.parallaxprotocol.org/client/interacting-with-parallax/json-rpc-namespaces/net The net API provides insight about the networking aspect of the client. ### net\_listening Returns an indication if the node is listening for network connections. | CLIENT | METHOD INVOCATION | | - | - | | Console | net.listening | | RPC | \{"method": "net\_listening"} | ### net\_peerCount Returns the number of connected peers. | CLIENT | METHOD INVOCATION | | - | - | | Console | net.peerCount | | RPC | \{"method": "net\_peerCount"} | ### net\_version Returns the devp2p network ID (e.g. 2110 for mainnet, 2111 for testnet). | CLIENT | METHOD INVOCATION | | - | - | | Console | net.version | | RPC | \{"method": "net\_version"} | *** *Partly adapted from [net Namespace](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-net) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # personal Source: https://docs.parallaxprotocol.org/client/interacting-with-parallax/json-rpc-namespaces/personal The JSON-RPC API's personal namespace has historically been used to manage accounts and sign transactions and data over RPC. However, it has **now been deprecated** in favour of using [Clef](/client/tools/clef/introduction) as an external signer and account manager. One of the major changes is moving away from indiscriminate locking and unlocking of accounts and instead using Clef to explicitly approve or deny specific actions. The first section on this page shows the suggested replacement for each method in personal. The second section shows the deprecated methods for archival purposes. ## Method replacements The following list shows each method from the personal namespace and the intended method in Clef that supercedes it. ### personal\_listAccounts personal\_listAccounts displays the addresses of all accounts in the keystore. It is identical to eth.accounts. Calling eth.accounts requires manual approval in Clef (unless a rule for it has been attested). There is also Clef's list-accounts command that can be called from the terminal. Examples: ```sh theme={null} # eth_accounts using curl curl -X POST --data '{"jsonrpc":"2.0","method":"eth_accounts","params":[],"id":1}' ``` ```javascript theme={null} // eth_accounts in Parallax client's JS console eth.accounts; ``` ```sh theme={null} # clef list-accounts in the terminal clef list-accounts ``` ### personal\_deriveAccount personal\_deriveAccount requests a hardware wallet to derive a new account, optionally pinning it for later use. This method is identical to clef\_deriveAccount. The Clef method is not externally exposed so it must be called via a UI. ### personal.ecRecover personal\_ecRecover returns the address for the account that was used to create a signature. An equivalent method, account\_ecRecover is available on the Clef external API. Example call: ```sh theme={null} curl --data '{"id": 4, "jsonrpc": "2.0", "method": "account_ecRecover","params": ["0xaabbccdd", "0x5b6693f153b48ec1c706ba4169960386dbaa6903e249cc79a8e6ddc434451d417e1e57327872c7f538beeb323c300afa9999a3d4a5de6caf3be0d5ef832b67ef1c"]}' -X POST localhost:8550 ``` ### personal\_importRawKey personal.importRawKey was used to create a new account in the keystore from a raw private key. Clef has an equivalent method that can be invoked in the terminal using: ```sh theme={null} clef importraw ``` ### personal\_listWallets As opposed to listAccounts, this method lists full details, including usb path or keystore-file paths. The equivalent method is clef\_listWallets. This method can be called from the terminal using: ```sh theme={null} clef list-wallets ``` ### personal\_newAccount personal\_newAccount was used to create a new accoutn and save it in the keystore. Clef has an equivalent method, account\_new. It can be accessed on the terminal using an http request or using a Clef command: Example call (curl): ```sh theme={null} curl --data '{"id": 1, "jsonrpc": "2.0", "method": "account_new", "params": []}' -X POST localhost:8550 ``` Example call (Clef command): ```sh theme={null} clef newaccount ``` Both require manual approval in Clef unless a custom ruleset is in place. ### personal\_openWallet personal\_OpenWallet initiates a hardware wallet opening procedure by establishing a USB connection and then attempting to authenticate via the provided passphrase. Note, the method may return an extra challenge requiring a second open (e.g. the Trezor PIN matrix challenge). personal\_openWallet is identical to clef\_openWallet. The Clef method is not externally eposed, meaning it must be called via a UI. ### personal\_sendTransaction personal\_sendTransaction ws used to sign and submit a transaction. This can be done using eth\_sendTransaction, requiring manual approval in Clef. Example call (Javascript console): ```javascript theme={null} // this command requires 2x approval in Clef because it loads account data via eth.accounts[0] // and eth.accounts[1] var tx = { from: eth.accounts[0], to: eth.accounts[1], value: web3.toWei(0.1, 'ether') }; // then send the transaction eth.sendTransaction(tx); ``` Example call (terminal) ```sh theme={null} curl --data '{"id":1, "jsonrpc":"2.0", "method":"eth_sendTransaction", "params":[{"from": "0xE70CAD05D0D54Ae3C9Fe5442f901E0433f9bd14B", "to":"0x4FDc03d09Ffca5Bba3138149E29D85C8A9E2Ac42", "gas":"21000","gasPrice":"20000000000", "nonce":"94"}]}' -H "Content-Type: application/json" -X POST localhost:8545 ``` ### personal\_sign The sign method calculates an Ethereum specific signature with sign(keccak256("\x19Ethereum Signed Message:\n" + len(message) + message)). Adding a prefix to the message makes the calculated signature recognisable as an Ethereum specific signature. This prevents misuse where a malicious DApp can sign arbitrary data (e.g. transaction) and use the signature to impersonate the victim. personal.sign is equivalent to Clef's account\_signData. It returns the calculated signature. Example call: ```sh theme={null} curl --data {"id": 3, "jsonrpc": "2.0", "method": "account_signData", "params": ["data/plain", "0x1923f626bb8dc025849e00f99c25fe2b2f7fb0db","0xaabbccdd"]} -X POST localhost:8550 ``` Clef also has account\_signTypedData that signs data structured according to [EIP-712](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md) and returns the signature. Example call (use the following as a template for \ in curl --data \ -X POST localhost:8550 -H "Content-Type: application/json") ```json theme={null} { "id": 68, "jsonrpc": "2.0", "method": "account_signTypedData", "params": [ "0xcd2a3d9f938e13cd947ec05abc7fe734df8dd826", { "types": { "EIP712Domain": [ { "name": "name", "type": "string" }, { "name": "version", "type": "string" }, { "name": "chainId", "type": "uint256" }, { "name": "verifyingContract", "type": "address" } ], "Person": [ { "name": "name", "type": "string" }, { "name": "wallet", "type": "address" } ], "Mail": [ { "name": "from", "type": "Person" }, { "name": "to", "type": "Person" }, { "name": "contents", "type": "string" } ] }, "primaryType": "Mail", "domain": { "name": "Ether Mail", "version": "1", "chainId": 1, "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC" }, "message": { "from": { "name": "Cow", "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" }, "to": { "name": "Bob", "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" }, "contents": "Hello, Bob!" } } ] } ``` ### personal\_signTransaction personal\_signTransaction was used to create and sign a transaction from the given arguments. The transaction was returned in RLP-form, not broadcast to other nodes. The equivalent method is Clef's account\_signTransaction from the external API. The arguments are a transaction object (\{"from": , "to": , "gas": , "maxPriorityFeePerGas": , "MaxFeePerGas": , "value": , "data": , "nonce": })) and an optional method signature that enables Clef to decode the calldata and show the user the methods, arguments and values being sent. Example call (terminal): ```sh theme={null} curl --data '{"id": 2, "jsonrpc": "2.0", "method": "account_signTransaction", "params": [{"from": "0x1923f626bb8dc025849e00f99c25fe2b2f7fb0db", "gas": "0x55555","gasPrice": "0x1234", "input": "0xabcd", "nonce": "0x0", "to": "0x07a565b7ed7d7a678680a4c162885bedbb695fe0", "value": "0x1234"}]}' -X POST -H "Content-Type: application/json" localhost:8550 ``` ## Methods without replacements Thjere are a few methods that were available in the personal namepsace that have been deprecated without replacements. These are: ### personal\_unlockAccount There is no need for a direct replacement for personal\_unlockAccount. Using Clef to manually approve actions or to attest custom rulesets is a much more secure way to interact with accounts without needing to indiscriminately unlock accounts. ### personal\_lockAccount There is no need for a direct replacement for personal\_lockAccount because account locking/unlocking is replaced by Clef's approve/deny logic. This is a more secure way to interact with accounts. ### personal.unpair Unpair deletes a pairing between some specific types of smartcard wallet and the Parallax client. There is not yet an equivalent method in Clef. ### personal\_initializeWallet InitializeWallet is for initializing some specific types of smartcard wallet at a provided URL. There is not yet a corresponding method in Clef. ## Deprecated method documentation The personal API managed private keys in the key store. It is now deprecated in favour of using [Clef](/client/tools/clef/introduction) for interacting with accounts. The following documentation should be treated as archive information and users should migrate to using Clef for account interactions. ### personal\_deriveAccount Requests a HD wallet to derive a new account, optionally pinning it for later reuse. | CLIENT | METHOD INVOCATION | | - | - | | Console | personal.deriveAccount(url, path, pin) | | RPC | \{"method": "personal\_deriveAccount", "params": \[string, string, bool]} | ### personal\_importRawKey Imports the given unencrypted private key (hex string) into the key store, encrypting it with the passphrase. Returns the address of the new account. | CLIENT | METHOD INVOCATION | | - | - | | Console | personal.importRawKey(keydata, passphrase) | | RPC | \{"method": "personal\_importRawKey", "params": \[string, string]} | ### personal\_initializeWallets Initializes a new wallet at the provided URL by generating and returning a new private key. | CLIENT | METHOD INVOCATION | | - | - | | Console | personal.initializeWallet(url) | | RPC | \{"method": "personal\_initializeWallet", "params": \[string]} | ### personal\_listAccounts Returns all the Ethereum account addresses of all keys in the key store. | CLIENT | METHOD INVOCATION | | - | - | | Console | personal.listAccounts | | RPC | \{"method": "personal\_listAccounts", "params": \[]} | **Example** ```javascript theme={null} > personal.listAccounts ["0x5e97870f263700f46aa00d967821199b9bc5a120", "0x3d80b31a78c30fc628f20b2c89d7ddbf6e53cedc"] ``` ### personal\_listWallets Returns a list of wallets this node manages. | CLIENT | METHOD INVOCATION | | - | - | | Console | personal.listWallets | | RPC | \{"method": "personal\_listWallets", "params": \[]} | **Example** ```javascript theme={null} > personal.listWallets [{ accounts: [{ address: "0x51594065a986c58d4698c23e3d932b68a22c4d21", url: "keystore:///var/folders/cp/k3x0xm3959qf9l0pcbbdxdt80000gn/T/parallax-keystore65174700/UTC--2022-06-28T10-31-09.477982000Z--51594065a986c58d4698c23e3d932b68a22c4d21" }], status: "Unlocked", url: "keystore:///var/folders/cp/k3x0xm3959qf9l0pcbbdxdt80000gn/T/parallax-keystore65174700/UTC--2022-06-28T10-31-09.477982000Z--51594065a986c58d4698c23e3d932b68a22c4d21" }] ``` ### personal\_lockAccount Removes the private key with given address from memory. The account can no longer be used to send transactions. | CLIENT | METHOD INVOCATION | | - | - | | Console | personal.lockAccount(address) | | RPC | \{"method": "personal\_lockAccount", "params": \[string]} | ### personal\_newAccount Generates a new private key and stores it in the key store directory. The key file is encrypted with the given passphrase. Returns the address of the new account. At the Parallax client console, newAccount will prompt for a passphrase when it is not supplied as the argument. | CLIENT | METHOD INVOCATION | | - | - | | Console | personal.newAccount() | | RPC | \{"method": "personal\_newAccount", "params": \[string]} | **Example** ```javascript theme={null} > personal.newAccount() Passphrase: Repeat passphrase: "0x5e97870f263700f46aa00d967821199b9bc5a120" ``` The passphrase can also be supplied as a string. ```javascript theme={null} > personal.newAccount("h4ck3r") "0x3d80b31a78c30fc628f20b2c89d7ddbf6e53cedc" ``` ### personal\_openWallet Initiates a hardware wallet opening procedure by establishing a USB connection and then attempting to authenticate via the provided passphrase. Note, the method may return an extra challenge requiring a second open (e.g. the Trezor PIN matrix challenge). | CLIENT | METHOD INVOCATION | | - | - | | Console | personal.openWallet(url, passphrase) | | RPC | \{"method": "personal\_openWallet", "params": \[string, string]} | ### personal\_unlockAccount 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 the Parallax client exits. The account can be used with eth\_sign and eth\_sendTransaction while it is unlocked. | CLIENT | METHOD INVOCATION | | - | - | | Console | personal.unlockAccount(address, passphrase, duration) | | RPC | \{"method": "personal\_unlockAccount", "params": \[string, string, number]} | **Examples** ```javascript theme={null} > personal.unlockAccount("0x5e97870f263700f46aa00d967821199b9bc5a120") Unlock account 0x5e97870f263700f46aa00d967821199b9bc5a120 Passphrase: true ``` Supplying the passphrase and unlock duration as arguments: ```javascript theme={null} > personal.unlockAccount("0x5e97870f263700f46aa00d967821199b9bc5a120", "foo", 30) true ``` To type in the passphrase and still override the default unlock duration, pass null as the passphrase. ```javascript theme={null} > personal.unlockAccount("0x5e97870f263700f46aa00d967821199b9bc5a120", null, 30) Unlock account 0x5e97870f263700f46aa00d967821199b9bc5a120 Passphrase: true ``` ### personal\_unpair Deletes a pairing between wallet and the Parallax client. | CLIENT | METHOD INVOCATION | | - | - | | Console | personal.unpair(url, pin) | | RPC | \{"method": "personal\_unpair", "params": \[string, string]} | ### personal\_sendTransaction Validate the given passphrase and submit transaction. The transaction is the same argument as for eth\_sendTransaction (i.e. [transaction object](https://geth.ethereum.org/docs/interacting-with-geth/rpc/objects#transaction-call-object)) and contains the from address. If the passphrase can be used to decrypt the private key belogging to tx.from the transaction is verified, signed and send onto the network. The account is not unlocked globally in the node and cannot be used in other RPC calls. | CLIENT | METHOD INVOCATION | | - | - | | Console | personal.sendTransaction(tx, passphrase) | | RPC | \{"method": "personal\_sendTransaction", "params": \[tx, string]} | **Examples** ```javascript theme={null} > var tx = {from: "0x391694e7e0b0cce554cb130d723a9d27458f9298", to: "0xafa3f8684e54059998bc3a7b0d2b0da075154d66", value: web3.toWei(1.23, "ether")} undefined > personal.sendTransaction(tx, "passphrase") 0x8474441674cdd47b35b875fd1a530b800b51a5264b9975fb21129eeb8c18582f ``` ### personal\_sign The sign method calculates an Ethereum specific signature with: sign(keccak256("\x19Ethereum Signed Message:\n" + len(message) + message)). By adding a prefix to the message makes the calculated signature recognisable as an Ethereum specific signature. This prevents misuse where a malicious DApp can sign arbitrary data (e.g. transaction) and use the signature to impersonate the victim. See ecRecover to verify the signature. | CLIENT | METHOD INVOCATION | | - | - | | Console | personal.sign(message, account, \[password]) | | RPC | \{"method": "personal\_sign", "params": \[message, account, password]} | **Examples** ```javascript theme={null} > personal.sign("0xdeadbeaf", "0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", "") "0xa3f20717a250c2b0b729b7e5becbff67fdaef7e0699da4de7ca5895b02a170a12d887fd3b17bfdce3481f10bea41f45ba9f709d39ce8325427b57afcfc994cee1b" ``` ### 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](https://geth.ethereum.org/docs/interacting-with-geth/rpc/objects) and the second argument is the password, similar to personal\_sendTransaction. | CLIENT | METHOD INVOCATION | | - | - | | Console | personal.signTransaction(tx, passphrase) | | RPC | \{"method": "personal\_signTransaction", "params": \[tx, string]} | ### personal\_ecRecover ecRecover returns the address associated with the private key that was used to calculate the signature in personal\_sign. | CLIENT | METHOD INVOCATION | | - | - | | Console | personal.ecRecover(message, signature) | | RPC | \{"method": "personal\_ecRecover", "params": \[message, signature]} | **Examples** ```javascript theme={null} > personal.sign("0xdeadbeaf", "0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", "") "0xa3f20717a250c2b0b729b7e5becbff67fdaef7e0699da4de7ca5895b02a170a12d887fd3b17bfdce3481f10bea41f45ba9f709d39ce8325427b57afcfc994cee1b" > personal.ecRecover("0xdeadbeaf", "0xa3f20717a250c2b0b729b7e5becbff67fdaef7e0699da4de7ca5895b02a170a12d887fd3b17bfdce3481f10bea41f45ba9f709d39ce8325427b57afcfc994cee1b") "0x9b2055d370f73ec7d8a03e965129118dc8f5bf83" ``` *** *Adapted from [personal Namespace](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-personal) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # txpool Source: https://docs.parallaxprotocol.org/client/interacting-with-parallax/json-rpc-namespaces/txpool 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 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). | CLIENT | METHOD INVOCATION | | - | - | | Go | txpool.Content() (map\[string]map\[string]map\[string]\*RPCTransaction) | | Console | txpool.content | | RPC | \{"method": "txpool\_content"} | #### Example ```javascript theme={null} > txpool.content { pending: { 0x0216d5032f356960cd3749c31ab34eeff21b3395: { 806: { blockHash: "0x0000000000000000000000000000000000000000000000000000000000000000", blockNumber: null, from: "0x0216d5032f356960cd3749c31ab34eeff21b3395", gas: "0x5208", gasPrice: "0xba43b7400", hash: "0xaf953a2d01f55cfe080c0c94150a60105e8ac3d51153058a1f03dd239dd08586", input: "0x", nonce: "0x326", to: "0x7f69a91a3cf4be60020fb58b893b7cbb65376db8", transactionIndex: null, value: "0x19a99f0cf456000" } }, 0x24d407e5a0b506e1cb2fae163100b5de01f5193c: { 34: { blockHash: "0x0000000000000000000000000000000000000000000000000000000000000000", blockNumber: null, from: "0x24d407e5a0b506e1cb2fae163100b5de01f5193c", gas: "0x44c72", gasPrice: "0x4a817c800", hash: "0xb5b8b853af32226755a65ba0602f7ed0e8be2211516153b75e9ed640a7d359fe", input: "0xb61d27f600000000000000000000000024d407e5a0b506e1cb2fae163100b5de01f5193c00000000000000000000000000000000000000000000000053444835ec580000000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", nonce: "0x22", to: "0x7320785200f74861b69c49e4ab32399a71b34f1a", transactionIndex: null, value: "0x0" } } }, queued: { 0x976a3fc5d6f7d259ebfb4cc2ae75115475e9867c: { 3: { blockHash: "0x0000000000000000000000000000000000000000000000000000000000000000", blockNumber: null, from: "0x976a3fc5d6f7d259ebfb4cc2ae75115475e9867c", gas: "0x15f90", gasPrice: "0x4a817c800", hash: "0x57b30c59fc39a50e1cba90e3099286dfa5aaf60294a629240b5bbec6e2e66576", input: "0x", nonce: "0x3", to: "0x346fb27de7e7370008f5da379f74dd49f5f2f80f", transactionIndex: null, value: "0x1f161421c8e0000" } }, 0x9b11bf0459b0c4b2f87f8cebca4cfc26f294b63a: { 2: { blockHash: "0x0000000000000000000000000000000000000000000000000000000000000000", blockNumber: null, from: "0x9b11bf0459b0c4b2f87f8cebca4cfc26f294b63a", gas: "0x15f90", gasPrice: "0xba43b7400", hash: "0x3a3c0698552eec2455ed3190eac3996feccc806970a4a056106deaf6ceb1e5e3", input: "0x", nonce: "0x2", to: "0x24a461f25ee6a318bdef7f33de634a67bb67ac9d", transactionIndex: null, value: "0xebec21ee1da40000" }, 6: { blockHash: "0x0000000000000000000000000000000000000000000000000000000000000000", blockNumber: null, from: "0x9b11bf0459b0c4b2f87f8cebca4cfc26f294b63a", gas: "0x15f90", gasPrice: "0x4a817c800", hash: "0xbbcd1e45eae3b859203a04be7d6e1d7b03b222ec1d66dfcc8011dd39794b147e", input: "0x", nonce: "0x6", to: "0x6368f3f8c2b42435d6c136757382e4a59436a681", transactionIndex: null, value: "0xf9a951af55470000" } } } } ``` ### txpool\_contentFrom Retrieves the transactions contained within the txpool, returning pending as well as queued transactions of this address, grouped by nonce. | CLIENT | METHOD INVOCATION | | - | - | | Console | txpool.contentFrom(address) | | RPC | \{"method": "txpool\_contentFrom, "params": \[string]"} | ### 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 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). | CLIENT | METHOD INVOCATION | | - | - | | Go | txpool.Inspect() (map\[string]map\[string]map\[string]string) | | Console | txpool.inspect | | RPC | \{"method": "txpool\_inspect"} | #### Example ```javascript theme={null} > txpool.inspect { pending: { 0x26588a9301b0428d95e6fc3a5024fce8bec12d51: { 31813: "0x3375ee30428b2a71c428afa5e89e427905f95f7e: 0 wei + 500000 × 20000000000 wei" }, 0x2a65aca4d5fc5b5c859090a6c34d164135398226: { 563662: "0x958c1fa64b34db746925c6f8a3dd81128e40355e: 1051546810000000000 wei + 90000 gas × 20000000000 wei", 563663: "0x77517b1491a0299a44d668473411676f94e97e34: 1051190740000000000 wei + 90000 gas × 20000000000 wei", 563664: "0x3e2a7fe169c8f8eee251bb00d9fb6d304ce07d3a: 1050828950000000000 wei + 90000 gas × 20000000000 wei", 563665: "0xaf6c4695da477f8c663ea2d8b768ad82cb6a8522: 1050544770000000000 wei + 90000 gas × 20000000000 wei", 563666: "0x139b148094c50f4d20b01caf21b85edb711574db: 1048598530000000000 wei + 90000 gas × 20000000000 wei", 563667: "0x48b3bd66770b0d1eecefce090dafee36257538ae: 1048367260000000000 wei + 90000 gas × 20000000000 wei", 563668: "0x468569500925d53e06dd0993014ad166fd7dd381: 1048126690000000000 wei + 90000 gas × 20000000000 wei", 563669: "0x3dcb4c90477a4b8ff7190b79b524773cbe3be661: 1047965690000000000 wei + 90000 gas × 20000000000 wei", 563670: "0x6dfef5bc94b031407ffe71ae8076ca0fbf190963: 1047859050000000000 wei + 90000 gas × 20000000000 wei" }, 0x9174e688d7de157c5c0583df424eaab2676ac162: { 3: "0xbb9bc244d798123fde783fcc1c72d3bb8c189413: 30000000000000000000 wei + 85000 gas × 21000000000 wei" }, 0xb18f9d01323e150096650ab989cfecd39d757aec: { 777: "0xcd79c72690750f079ae6ab6ccd7e7aedc03c7720: 0 wei + 1000000 gas × 20000000000 wei" }, 0xb2916c870cf66967b6510b76c07e9d13a5d23514: { 2: "0x576f25199d60982a8f31a8dff4da8acb982e6aba: 26000000000000000000 wei + 90000 gas × 20000000000 wei" }, 0xbc0ca4f217e052753614d6b019948824d0d8688b: { 0: "0x2910543af39aba0cd09dbb2d50200b3e800a63d2: 1000000000000000000 wei + 50000 gas × 1171602790622 wei" }, 0xea674fdde714fd979de3edf0f56aa9716b898ec8: { 70148: "0xe39c55ead9f997f7fa20ebe40fb4649943d7db66: 1000767667434026200 wei + 90000 gas × 20000000000 wei" } }, queued: { 0x0f6000de1578619320aba5e392706b131fb1de6f: { 6: "0x8383534d0bcd0186d326c993031311c0ac0d9b2d: 9000000000000000000 wei + 21000 gas × 20000000000 wei" }, 0x5b30608c678e1ac464a8994c3b33e5cdf3497112: { 6: "0x9773547e27f8303c87089dc42d9288aa2b9d8f06: 50000000000000000000 wei + 90000 gas × 50000000000 wei" }, 0x976a3fc5d6f7d259ebfb4cc2ae75115475e9867c: { 3: "0x346fb27de7e7370008f5da379f74dd49f5f2f80f: 140000000000000000 wei + 90000 gas × 20000000000 wei" }, 0x9b11bf0459b0c4b2f87f8cebca4cfc26f294b63a: { 2: "0x24a461f25ee6a318bdef7f33de634a67bb67ac9d: 17000000000000000000 wei + 90000 gas × 50000000000 wei", 6: "0x6368f3f8c2b42435d6c136757382e4a59436a681: 17990000000000000000 wei + 90000 gas × 20000000000 wei", 7: "0x6368f3f8c2b42435d6c136757382e4a59436a681: 17900000000000000000 wei + 90000 gas × 20000000000 wei" } } } ``` ### txpool\_status 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. | CLIENT | METHOD INVOCATION | | - | - | | Go | txpool.Status() (map\[string]\*rpc.HexNumber) | | Console | txpool.status | | RPC | \{"method": "txpool\_status"} | #### Example ```javascript theme={null} > txpool.status { pending: 10, queued: 7 } ``` *** *Adapted from [txpool Namespace](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-txpool) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Batch requests Source: https://docs.parallaxprotocol.org/client/interacting-with-parallax/json-rpc-server/batch-requests 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 the Parallax client'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: ```javascript theme={null} import fetch from 'node-fetch'; async function main() { const endpoint = 'http://127.0.0.1:8545'; const from = parseInt(process.argv[2]); const to = parseInt(process.argv[3]); const reqs = []; for (let i = from; i < to; i++) { reqs.push({ method: 'eth_getBlockByNumber', params: [`0x${i.toString(16)}`, false], id: i - from, jsonrpc: '2.0' }); } const res = await fetch(endpoint, { method: 'POST', body: JSON.stringify(reqs), headers: { 'Content-Type': 'application/json' } }); const data = await res.json(); } main() .then() .catch(err => console.log(err)); ``` In this case there's no dependency between the requests. Often the retrieved data from one request is needed to issue a second one. Let's take the example of fetching all the receipts for a range of blocks. The JSON-RPC API provides `eth_getTransactionReceipt` which takes in a transaction hash and returns the corresponding receipt object, but no method to fetch receipt objects for a whole block. We need to get the list of transactions in a block and then call `eth_getTransactionReceipt` for each of them. We can break this into 2 batch requests: * First to download the list of transaction hashes for all of the blocks in our desired range * And then to download the list of receipts objects for all of the transaction hashes For use-cases which depend on several JSON-RPC endpoints the batching approach can get easily complicated. In that case the Parallax client offers a [GraphQL API](/client/interacting-with-parallax/graph-ql-server) which is more suitable. *** *Adapted from [Batch requests](https://geth.ethereum.org/docs/interacting-with-geth/rpc/batch) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # JSON-RPC Server Source: https://docs.parallaxprotocol.org/client/interacting-with-parallax/json-rpc-server/overview Interacting with the Parallax client requires sending requests to specific JSON-RPC API methods. The Parallax client supports all standard [JSON-RPC API](/protocol/parallax-stack/apis/json-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 the Parallax client, providing the information users require to choose a transport protocol for a specific user scenario. ## Introduction JSON-RPC is provided on multiple transports. The Parallax client supports JSON-RPC over HTTP, WebSocket and Unix Domain Sockets. Transports must be enabled through command-line flags. The Parallax 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. ## Transports There are three transport protocols available in the Parallax client: 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 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 the Parallax client. To start a HTTP server in Parallax client, include the `--http` flag: ```sh theme={null} ./parallaxd --http ``` If no other commands are provided, the Parallax client 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 theme={null} ./parallaxd --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 the Parallax client 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 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 theme={null} ./parallaxd --http --http.api 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. ```sh theme={null} ./parallaxd --http --http.corsdomain https://remix.ethereum.org ``` The `--http.corsdomain` command also accepts wildcards that enable access to the RPC from any origin: ```sh theme={null} --http.corsdomain '*' ``` ### 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. Because Websocket is bidirectional, servers can push events to clients. That makes Websocket a good choice for use-cases involving [event subscription](/client/interacting-with-parallax/json-rpc-server/realtime-events). 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 the Parallax client follows the same pattern as the HTTP transport. WebSocket access can be enabled using the `--ws` flag. If no additional information is provided, the Parallax client 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 the Parallax client with a Websocket connection for RPC using the custom port `3334` and whitelisting the `eth`, `net` and `web3` namespaces: ```sh theme={null} ./parallaxd --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: ```sh theme={null} ./parallaxd --ws --ws.origins http://myapp.example.com ``` As with `--http.corsdomain`, using the wildcard `--ws.origins '*'` allows access from any origin. 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 Parallax 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. The Parallax client creates a pipe in the computers local file system (at ipcpath) that configures a connection between node and console. The `parallax.ipc` file can also be used by other processes on the same machine to interact with the Parallax client. 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 Parallax client socket is ```sh theme={null} ~/.parallax/parallax.ipc ``` On Windows, IPC is provided via named pipes. The default location of the Parallax client pipe is: ```sh theme={null} \\.\pipe\parallax.ipc ``` The location of the socket can be customized using the `--ipcpath` flag. IPC can be disabled 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. | | HTTP | WS | IPC | | - | - | - | - | | Event subscription | N | **Y** | **Y** | | Remote connection | **Y** | **Y** | N | | Per-message metadata overhead | high | low | low | 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 Parallax 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. *** *Adapted from [JSON-RPC Server](https://geth.ethereum.org/docs/interacting-with-geth/rpc) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Real-time events Source: https://docs.parallaxprotocol.org/client/interacting-with-parallax/json-rpc-server/realtime-events The Parallax client supports publish / subscribe using JSON-RPC notifications. This allows clients to wait for events instead of polling for them. It works by subscribing to particular events. The node will return a subscription id. For each event that matches the subscription a notification with relevant data is send together with the subscription id. Example: ```json theme={null} // create subscription {"id": 1, "jsonrpc": "2.0", "method": "eth_subscribe", "params": ["newHeads"]} ``` returns ```json theme={null} {"jsonrpc":"2.0","id":1,"result":"0xcd0c3e8af590364c09d0fa6a1210faf5"} // incoming notifications {"jsonrpc":"2.0","method":"eth_subscription","params":{"subscription":"0xcd0c3e8af590364c09d0fa6a1210faf5","result":{"parentHash":"0x3eff702e910b1562ae6e40ce29c1f53449daf63808a49460cc3f7b6a11618fde",<...>,"number":"0xe934",<...>}}} {"jsonrpc":"2.0","method":"eth_subscription","params":{"subscription":"0xcd0c3e8af590364c09d0fa6a1210faf5","result":{"parentHash":"0xe7afc97ee43bc6024f6bf57d9912678709c31b089ffb972cb265e72f4629a25f",<...>,"number":"0xe935",<...>}}} ``` to cancel the subscription: ```json theme={null} // cancel subscription {"id": 1, "jsonrpc": "2.0", "method": "eth_unsubscribe", "params": ["0xcd0c3e8af590364c09d0fa6a1210faf5"]} {"jsonrpc":"2.0","id":1,"result":true} ``` ## Considerations 1. Notifications are sent for current events and not for past events. For use cases that cannot afford to miss any notifications, subscriptions are probably not the best option. 2. Subscriptions require a full duplex connection. The Parallax client offers such connections in the form of WebSocket and IPC (enabled by default). 3. Subscriptions are coupled to a connection. If the connection is closed all subscriptions that are created over this connection are removed. 4. Notifications are stored in an internal buffer and sent from this buffer to the client. If the client is unable to keep up and the number of buffered notifications reaches a limit (currently 10k) the connection is closed. Keep in mind that subscribing to some events can cause a flood of notifications, e.g. listening for all logs/blocks when the node starts to synchronize. ## Create subscription Subscriptions are created with a regular RPC call with `eth_subscribe` as method and the subscription name as first parameter. If successful it returns the subscription id. #### Parameters 1. Subscription name 2. Optional arguments #### Example ```json theme={null} {"id": 1, "jsonrpc": "2.0", "method": "eth_subscribe", "params": ["newHeads"]} {"id": 1, "jsonrpc": "2.0", "result": "0x9cef478923ff08bf67fde6c64013158d"} ``` ## 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. #### Parameters 1. subscription id #### Example ```json theme={null} {"id": 1, "jsonrpc": "2.0", "method": "eth_unsubscribe", "params": ["0x9cef478923ff08bf67fde6c64013158d"]} {"jsonrpc":"2.0","id":1,"result":true} ``` ## Supported Subscriptions ### newHeads 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 the Parallax client 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. **Example** ```json theme={null} {"id": 1, "jsonrpc": "2.0", "method": "eth_subscribe", "params": ["newHeads"]} ``` returns ```json theme={null} {"jsonrpc":"2.0","id":2,"result":"0x9ce59a13059e417087c02d3236a0b1cc"} { "jsonrpc": "2.0", "method": "eth_subscription", "params": { "result": { "parentHash": "0x3eff702e910b1562ae6e40ce29c1f53449daf63808a49460cc3f7b6a11618fde", "miner": "0x38432a328b3c6f15582292f7235f17b08a98c6ab", "stateRoot": "0xdbd2f3ccaacca4fbe8fd6006b2b2fd98204d674d15acae6b13a115039c37274b", "transactionsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", "receiptsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "difficulty": "0x44eccd7eda7", "number": "0xe934", "gasLimit": "0x23c34600", "gasUsed": "0x0", "timestamp": "0x6ace88cf", "epochStartTime": "0x6ac4e0d9", "extraData": "0xd8830102008470726c7888676f312e32352e31856c696e7578", "mixHash": "0x658efc6d3c3cc52e6996a5d0803f258a8568cc34f0789da67101245c10dfd625", "nonce": "0x85943e36390c08d3", "baseFeePerGas": null, "hash": "0xe7afc97ee43bc6024f6bf57d9912678709c31b089ffb972cb265e72f4629a25f" }, "subscription": "0x9ce59a13059e417087c02d3236a0b1cc" } } ``` ### logs Returns logs that are included in new imported blocks and match the given filter criteria. In case of a chain reorganization previous sent logs that are on the old chain will be resent with the removed property set to true. Logs from transactions that ended up in the new chain are emitted. Therefore a subscription can emit logs for the same transaction multiple times. **Parameters** 1. object with the following (optional) fields * **address**, either an address or an array of addresses. Only logs that are created from these addresses are returned (optional) * **topics**, only logs which match the specified topics (optional) **Example** ```json theme={null} { "id": 1, "jsonrpc": "2.0", "method": "eth_subscribe", "params": [ "logs", { "address": "0x8320fe7702b96808f7bbc0d4a888ed1468216cfd", "topics": ["0xd78a0cb8bb633d06981248b816e7bd33c2a35a6089241d099fa519e361cab902"] } ] } ``` returns ```json theme={null} {"jsonrpc":"2.0","id":2,"result":"0x4a8a4c0517381924f9838102c5a4dcb7"} {"jsonrpc":"2.0","method":"eth_subscription","params": {"subscription":"0x4a8a4c0517381924f9838102c5a4dcb7","result":{"address":"0x8320fe7702b96808f7bbc0d4a888ed1468216cfd","blockHash":"0x61cdb2a09ab99abf791d474f20c2ea89bf8de2923a2d42bb49944c8c993cbf04","blockNumber":"0x29e87","data":"0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000003","logIndex":"0x0","topics":["0xd78a0cb8bb633d06981248b816e7bd33c2a35a6089241d099fa519e361cab902"],"transactionHash":"0xe044554a0a55067caafd07f8020ab9f2af60bdfe337e395ecd84b4877a3d1ab4","transactionIndex":"0x0"}}} ``` ### newPendingTransactions Returns the hash for all transactions that are added to the pending state and are signed with a key that is available in the node. When a transaction that was previously part of the canonical chain isn't part of the new canonical chain after a reorganization its again emitted. **Parameters** none **Example** ```json theme={null} {"id": 1, "jsonrpc": "2.0", "method": "eth_subscribe", "params": ["newPendingTransactions"]} ``` returns ```json theme={null} {"jsonrpc":"2.0","id":2,"result":"0xc3b33aa549fb9a60e95d21862596617c"} { "jsonrpc":"2.0", "method":"eth_subscription", "params":{ "subscription":"0xc3b33aa549fb9a60e95d21862596617c", "result":"0xd6fdc5cc41a9959e922f30cb772a9aef46f4daea279307bc5f7024edc4ccd7fa" } } ``` ### 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. **Parameters** none **Example** ```json theme={null} {"id": 1, "jsonrpc": "2.0", "method": "eth_subscribe", "params": ["syncing"]} {"jsonrpc":"2.0","id":2,"result":"0xe2ffeb2703bcf602d42922385829ce96"} {"subscription":"0xe2ffeb2703bcf602d42922385829ce96","result":{"syncing":true,"status":{"startingBlock":674427,"currentBlock":67400,"highestBlock":674432,"pulledStates":0,"knownStates":0}}}} ``` *** *Adapted from [Real-time Events](https://geth.ethereum.org/docs/interacting-with-geth/rpc/pubsub) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Creating dashboards Source: https://docs.parallaxprotocol.org/client/monitoring/creating-dashboards There are several ways to monitor the performance of a Parallax node. Insights into a node's performance are useful for debugging, tuning and understanding what is really happening when the Parallax client is running. ## Prerequisites To follow along with the instructions on this page it will be useful to have: * a running Parallax client instance. * basic working knowlegde of bash/terminal. [This video](https://www.youtube.com/watch?v=cOBab8IJMYI) provides an excellent introduction to Geth monitoring. ## Monitoring stack The Parallax client collects lots of data which can be read in the form of a chronological database. To make monitoring easier, this data can be fed into data visualisation software. On this page, the Parallax client will be configured to push data into a InfluxDB database and Grafana will be used to visualise the data. ## Setting up InfluxDB InfluxDB can be downloaded from the [Influxdata release page](https://portal.influxdata.com/downloads/). It can also be installed from a [repository](https://repos.influxdata.com/). For example the following commands will download and install InfluxDB on a Debian based Linux operating system - you can check for up-to-date instructions for your operating system on the InfluxDB [downloads page](https://portal.influxdata.com/downloads/): ```sh theme={null} curl -tlsv1.3 --proto =https -sL https://repos.influxdata.com/influxdb.key | sudo apt-key add source /etc/lsb-release echo "deb https://repos.influxdata.com/${DISTRIB_ID,,} ${DISTRIB_CODENAME} stable" | sudo tee /etc/apt/sources.list.d/influxdb.list sudo apt update sudo apt install influxdb -y sudo systemctl enable influxdb sudo systemctl start influxdb sudo apt install influxdb-client ``` By default, InfluxDB it is reachable at `localhost:8086`. Before using the influx client, a new user with admin privileges needs to be created. This user will serve for high level management, creating databases and users. ```sh theme={null} curl -XPOST "http://localhost:8086/query" --data-urlencode "q=CREATE USER username WITH PASSWORD 'password' WITH ALL PRIVILEGES" ``` Now the influx client can be used to enter [InfluxDB shell](https://docs.influxdata.com/influxdb/v1.8/tools/shell/) with the new user. ```sh theme={null} influx -username 'username' -password 'password' ``` A database and user for Parallax client metrics can be created by communicating with it directly via its shell. ```sh theme={null} create database parallax create user parallax with password choosepassword ``` Verify created entries with: ```sh theme={null} show databases show users ``` Leave InfluxDB shell. ```sh theme={null} exit ``` InfluxDB is running and configured to store metrics from the Parallax client ## Setting up Prometheus Prometheus can be downloaded from the [Prometheus](https://prometheus.io/download/). There is also a Docker image at [prom/prometheus](https://hub.docker.com/r/prom/prometheus), you can run in containerized environments. eg: ```sh theme={null} docker run \ -p 9090:9090 \ -v /path/to/prometheus:/etc/prometheus \ prom/prometheus:latest ``` Here a example directoy of /path/to/promethus: ```sh theme={null} prometheus/ ├── prometheus.yml └── record.parallax.rules.yml ``` And an example of prometheus.yml is: ```yaml theme={null} global: scrape_interval: 15s evaluation_interval: 15s # Load and evaluate rules in this file every 'evaluation_interval' seconds. rule_files: - 'record.parallax.rules.yml' # A scrape configuration containing exactly one endpoint to scrape. scrape_configs: - job_name: 'parallax-client' scrape_interval: 10s metrics_path: /debug/metrics/prometheus static_configs: - targets: - '127.0.0.1:6060' labels: chain: parallax ``` Meanwhile, [Recording rules](https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/) are a powerful feature that allow you to precompute frequently needed or computationally expensive expressions and save their results as new sets of time series. Read more about setting up recording rules at the [official prometheus docs](https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/). ## Preparing the Parallax client After setting up database, metrics need to be enabled in the Parallax client. Various options are available, as documented in the `METRICS AND STATS OPTIONS` in `parallaxd --help` and in our [metrics page](/client/monitoring/metrics). In this case the Parallax client will be configured to push data into InfluxDB. Basic setup specifies the endpoint where InfluxDB is reachable and authenticates the database. ```sh theme={null} parallaxd --metrics --metrics.influxdb --metrics.influxdb.endpoint "http://0.0.0.0:8086" --metrics.influxdb.username "parallax" --metrics.influxdb.password "chosenpassword" ``` These flags can be provided when the Parallax client is started or saved to the configuration file. Listing the metrics in the database verifies that the Parallax client is pushing data correctly. In InfluxDB shell: ```sh theme={null} use parallax show measurements ``` ## Setting up Grafana With the InfluxDB database setup and successfully receiving data from the Parallax client the next step is to install Grafana so that the data can be visualized. The following code snippet shows how to download, install and run Grafana on a Debian based Linux system. Up to date instructions for your operating system can be found on the Grafana [downloads page](https://grafana.com/grafana/download). ```sh theme={null} curl -tlsv1.3 --proto =https -sL https://packages.grafana.com/gpg.key | sudo apt-key add - echo "deb https://packages.grafana.com/oss/deb stable main" | sudo tee -a /etc/apt/sources.list.d/grafana.list sudo apt update sudo apt install grafana sudo systemctl enable grafana-server sudo systemctl start grafana-server ``` When Grafana is up and running, it should be reachable at `localhost:3000`. A browser can be pointed to that URL to access a visualization dashboard. The browser will prompt for login credentials (user: `admin` and password: `admin`). When prompted, the default password should be changed and saved. The browser first redirects to the Grafana home page to set up the source data. Click on the "Data sources" icon and then click on "InfluxDB". The following configuration options are recommended: ```sh theme={null} Name: InfluxDB Query Language: InfluxQL HTTP URL: http://localhost:8086 Access: Server (default) Whitelisted cookies: None (leave blank) Auth All options left as their default (switches off) Custom HTTP Headers None InfluxDB Details Database: parallax User: Password: HTTP Method: GET ``` Click on "Save and test" and wait for the confirmation to pop up. Grafana is now set up to read data from InfluxDB. Now a dashboard can be created to interpret and display it. Dashboards properties are encoded in JSON files which can be created by anybody and easily imported. On the left bar, click on the "Dashboards" icon, then "Import". For a Parallax client InfluxDB monitoring dashboard, copy the URL of [this dashboard](https://grafana.com/grafana/dashboards/13877/) and paste it in the "Import page" in Grafana. After saving the dashboard, it should look like this: ![](https://geth.ethereum.org/images/docs/grafana.png) For a Parallax client Prometheus monitoring dashboard, copy the URL of [this dashboard](https://grafana.com/grafana/dashboards/18463/) and paste it in the "Import page" in Grafana. After saving the dashboard, it should look like this: ![](https://geth.ethereum.org/images/docs/grafana2.png) ## Customization The dashboards can be customized further. Each panel can be edited, moved, removed or added. To learn more about how dashboards work, refer to [Grafana's documentation](https://grafana.com/docs/grafana/latest/dashboards/). Some users might also be interested in automatic [alerting](https://grafana.com/docs/grafana/latest/alerting/), which sets up alert notifications that are sent automatically when metrics reach certain values. Various communication channels are supported. ## Summary This page has outlined how to set up a simple node monitoring dashboard using Grafana. ***NB: this page was adapted from a tutorial on ethereum.org written by Mario Havel*** *** *Adapted from [Monitoring Geth with InfluxDB and Grafana](https://geth.ethereum.org/docs/monitoring/dashboards) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Metrics Source: https://docs.parallaxprotocol.org/client/monitoring/metrics The Parallax client includes a variety of optional metrics that can be reported to the user. However, metrics are disabled by default to save on the computational overhead for the average user. Users that choose to see more detailed metrics can enable them using the `--metrics` flag when starting the Parallax client. Some metrics are classed as especially expensive and are only enabled when the `--metrics.expensive` flag is supplied. For example, per-packet network traffic data is considered expensive. The goal of the Parallax client metrics system is that - similar to logs - arbitrary metric collections can be added to any part of the code without requiring fancy constructs to analyze them (counter variables, public interfaces, crossing over the APIs, console hooks, etc). Instead, metrics should be "updated" whenever and wherever needed and be automatically collected, surfaced through the APIs, queryable and visualizable for analysis. ## Metric types The Parallax client's metrics can be classified into four types: meters, timers, counters and guages. ### Meters Analogous to physical meters (electricity, water, etc), the Parallax client's meters are capable of measuring the *amount* of "things" that pass through and at the *rate* at which they do. A meter doesn't have a specific unit of measure (byte, block, malloc, etc), it just counts arbitrary *events*. At any point in time a meter can report: * *Total number of events* that passed through the meter * *Mean throughput rate* of the meter since startup (events / second) * *Weighted throughput rate* in the last *1*, *5* and *15* minutes (events / second) ("weighted" means that recent seconds count more that in older ones\*) ### Timers Timers are extensions of *meters*, the *duration* of an event is collected alongside a log of its occurrence. Similarly to meters, a timer can also measure arbitrary events but each requires a duration to be assigned individually. In addition generating all of the meter report types, a timer also reports: * *Percentiles (5, 20, 50, 80, 95)*, reporting that some percentage of the events took less than the reported time to execute (*e.g. Percentile 20 = 1.5s would mean that 20% of the measured events took less time than 1.5 seconds to execute; inherently 80%(=100%-20%) took more that 1.5s*) * Percentile 5: minimum durations (this is as fast as it gets) * Percentile 50: well behaved samples (boring, just to give an idea) * Percentile 80: general performance (these should be optimised) * Percentile 95: worst case outliers (rare, just handle gracefully) ### Counters A counter is a single int64 value that can be incremented and decremented. The current value of the counter can be queried. ### Gauges A gauge is a single int64 value. Its value can increment and decrement - as with a counter - but can also be set arbitrarily. ## Querying metrics The Parallax client collects metrics if the `--metrics` flag is provided at startup. Those metrics are available via an HTTP server if the `--metrics.addr` flag is also provided. By default the metrics are served at `127.0.0.1:6060/debug/metrics` but a custom IP address can be provided. A custom port can also be provided to the `--metrics.port` flag. More computationally expensive metrics are toggled on or off by providing or omitting the `--metrics.expensive` flag. For example, to serve all metrics at the default address and port: ```sh theme={null} parallaxd --metrics --metrics.addr 127.0.0.1 --metrics.expensive ``` Navigating the browser to the given metrics address displays all the available metrics in the form of JSON data that looks similar to: ```sh theme={null} chain/account/commits.50-percentile: 374072 chain/account/commits.75-percentile: 830356 chain/account/commits.95-percentile: 1783005.3999976 chain/account/commits.99-percentile: 3991806 chain/account/commits.99.999-percentile: 3991806 chain/account/commits.count: 43 chain/account/commits.fifteen-minute: 0.029134344092314267 chain/account/commits.five-minute: 0.029134344092314267 ... ``` Any developer is free to add, remove or modify the available metrics as they see fit. The precise list of available metrics is always available by opening the metrics server in the browser. The Parallax client also supports dumping metrics directly into an influx database. In order to activate this, the `--metrics.influxdb` flag must be provided at startup. The API endpoint, username, password and other influxdb tags can also be provided. The available tags are: ```sh theme={null} --metrics.influxdb.endpoint value InfluxDB API endpoint to report metrics to (default: "http://localhost:8086") --metrics.influxdb.database value InfluxDB database name to push reported metrics to (default: "parallax") --metrics.influxdb.username value Username to authorize access to the database (default: "test") --metrics.influxdb.password value Password to authorize access to the database (default: "test") --metrics.influxdb.tags value Comma-separated InfluxDB tags (key/values) attached to all measurements (default: "host=localhost") --metrics.influxdbv2 Enable metrics export/push to an external InfluxDB v2 database --metrics.influxdb.token value Token to authorize access to the database (v2 only) (default: "test") --metrics.influxdb.bucket value InfluxDB bucket name to push reported metrics to (v2 only) (default: "parallax") --metrics.influxdb.organization value InfluxDB organization name (v2 only) (default: "parallax") ``` We also provide Prometheus-formatted metrics data, which can be obtained through the `http://127.0.0.1:6060/debug/metrics/prometheus` URL, eg: ```sh theme={null} # TYPE chain_account_commits_count counter chain_account_commits_count 6506 # TYPE chain_account_commits summary chain_account_commits {quantile="0.5"} 8.194577e+06 chain_account_commits {quantile="0.75"} 1.016841725e+07 chain_account_commits {quantile="0.95"} 1.4334824899999999e+07 chain_account_commits {quantile="0.99"} 1.923948246000001e+07 chain_account_commits {quantile="0.999"} 5.038267952400009e+07 chain_account_commits {quantile="0.9999"} 5.108694e+07 # TYPE chain_account_hashes_count counter chain_account_hashes_count 6506 # TYPE chain_account_hashes summary chain_account_hashes {quantile="0.5"} 1.565746e+06 chain_account_hashes {quantile="0.75"} 1.87953975e+06 chain_account_hashes {quantile="0.95"} 4.6262716e+06 chain_account_hashes {quantile="0.99"} 8.655076970000029e+06 chain_account_hashes {quantile="0.999"} 4.823811956800011e+07 chain_account_hashes {quantile="0.9999"} 4.9055682e+07 ... ``` ## Creating and updating metrics Metrics can be added easily in the Parallax client source code: ```go theme={null} meter := metrics.NewMeter("system/memory/allocs") timer := metrics.NewTimer("chain/inserts") ``` In order to use the same meter from two different packages without creating dependency cycles, the metrics can be created using `NewOrRegisteredX()` functions. This creates a new meter if no meter with this name is available or returns the existing meter. ```go theme={null} meter := metrics.NewOrRegisteredMeter("system/memory/allocs") timer := metrics.NewOrRegisteredTimer("chain/inserts") ``` The name given to the metric can be any arbitrary string. However, since the Parallax client assumes it to be some meaningful sub-system hierarchy, it should be named accordingly. Metrics can then be updated: ```go theme={null} meter.Mark(n) // Record the occurrence of `n` events timer.Update(duration) // Record an event that took `duration` timer.UpdateSince(time) // Record an event that started at `time` timer.Time(function) // Measure and record the execution of `function` ``` ## Summary The Parallax client can be configured to report metrics to an HTTP server or database. These functions are disabled by default but can be configured by passing the appropriate commands on startup. Users can easily create custom metrics by adding them to the Parallax client source code, following the instructions on this page. *** *Adapted from [Metrics](https://geth.ethereum.org/docs/monitoring/metrics) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Understanding dashboards Source: https://docs.parallaxprotocol.org/client/monitoring/understanding-dashboards Our [dashboards page](/client/monitoring/creating-dashboards) explains how to set up a Grafana dashboard for monitoring your Parallax node. This page explores the dashboard itself, explaining what the various metrics are and what they mean for the health of a node. Note that the raw data informing the dashboard can be viewed in JSON format in the browser by navigating to the ip address and port passed to `--metrics.addr` and `--metrics.port` (`127.0.0.1:6060` by default). ## What does the dashboard look like? The default Grafana dashboard looks as follows (note that there are many more panels on the actual page than in the snapshot below): ![](https://geth.ethereum.org/images/docs/grafana/dashboard.png) Each panel in the dashboard tracks a different metric that can be used to understand some aspect of how a Parallax node is behaving. There are three main categories of panel in the default dashboard: System, Network and Blockchain. The individual panels are explained in the following sections. ## What do the panels show? ### System Panels in the System category track the impact of the Parallax client on the local machine, including memory and CPU usage. #### **CPU** ![](https://geth.ethereum.org/images/docs/grafana/cpu.png) The CPU panel shows how much CPU is being used as a percentage of one processing core (i.e. 100% means complete usage of one processing core, 200% means complete usage of two processing cores). There are three processes plotted on the figure. The total CPU usage by the entire system is plotted as system; the percentage of time that the CPUs are idle waiting for disk i/o operations is plotted as iowait; the CPU usage by the Parallax client process is plotted as parallax. #### **Memory** ![](https://geth.ethereum.org/images/docs/grafana/memory.png) Memory tracks the amount of RAM being used by the Parallax client. Three metrics are plotted: the cache size, i.e. the total RAM reserved for the Parallax client (default 1024 MB) is plotted as held; the amount of the cache actually being used by the Parallax client is plotted as used; the number of bytes being allocated by the system per second is plotted as alloc. #### **Disk** Disk tracks the rate that data is written to (plotted as write) or read from (plotted as read) the hard disk in units of MB/s. ![](https://geth.ethereum.org/images/docs/grafana/disk.png) #### **Goroutines** Tracks the total number of active goroutines being used by the Parallax client. Goroutines are lighweight threads managed by the Go runtime, they allow processes to execute concurrently. ![](https://geth.ethereum.org/images/docs/grafana/goroutines.png) ### Network Panels in the Network category track the data flow in and out of the local node. #### **Traffic** The Traffic panel shows the rate of data ingress and egress for all subprotocols, measured in units of kB/s. ![](https://geth.ethereum.org/images/docs/grafana/traffic.png) #### **Peers** The Peers panel shows the number of individual peers the local node is connected to. The number of dials issued by the Parallax client per second and the number of external connections received per second are also tracked in this panel. ![](https://geth.ethereum.org/images/docs/grafana/peers.png) #### **Laxes ingress data rate** Ingress is the process of data arriving at the local node from its peers. This panel shows the rate that data specifically using the eth subprotocol is arriving at the local node in units of kB/s (kilobytes per second). The data is subdivided into specific versions of the ETH subprotocol. Make sure your dashboard includes the latest version of the eth subprotocol! ![](https://geth.ethereum.org/images/docs/grafana/eth-ingress-rate.png) #### **Laxes egress data rate** Egress is the process of data leaving the local node and being transferred to its peers. This panel shows the rate that data specifically using the eth subprotocol is leaving the local node in units of kB/s (kilobytes per second). Make sure your dashboard includes the latest version of the eth subprotocol! ![](https://geth.ethereum.org/images/docs/grafana/eth-egress-rate.png) #### **ETH ingress traffic** Ingress is the process of data arriving at the local node from its peers. This panel shows a moment-by-moment snapshot of the amount of data that is arriving at the local node, specifically using the eth subprotocol, in units of GB (gigabytes). Make sure your dashboard includes the latest version of the eth subprotocol! ![](https://geth.ethereum.org/images/docs/grafana/eth-ingress-traffic.png) **ETH egress traffic** Egress is the process of data leaving the local node and being transferred to its peers. This panel shows a moment-by-moment snapshot of the amount of data that has left the local node, specifically using the eth subprotocol, in units of GB (gigabytes). Make sure your dashboard includes the latest version of the eth subprotocol! ![](https://geth.ethereum.org/images/docs/grafana/eth-egress-traffic.png) ### Blockchain Panels in the Blockchain category track the local node's view of the blockchain. #### **Chain head** The chain head simply tracks the latest block number that the local node is aware of. ![](https://geth.ethereum.org/images/docs/grafana/chain-head.png) #### **Transaction pool** The Parallax client has a capacity for pending transactions defined by `--txpool.globalslots` (default is `5160`). The number of slots filled with transactions is tracked as slots. The transactions in the pool are divided into pending transactions and queued transactions. Pending transactions are ready to be processed and included in a block, whereas queued transactions are those whose transaction nonces are out of sequence. Queued transactions can become pending transactions if transactions with the missing nonces become available. In the dashboard pending transactions are labelled as executable and queued transactions are labelled gapped. The subset of those global transactions that originated from the local node are tracked as local. ![](https://geth.ethereum.org/images/docs/grafana/tx-pool.png) #### **Block processing** The block processing panel tracks the time taken to complete the various tasks involved in processing each block, measured in microseconds or nanoseconds. Specifically, this includes: * **execution**: time taken to execute the transactions in the block * **validation**: time taken to validate that the information in a received block body matches what is described in the block header. * **commit**: time taken to write the new block to the chain data * **account read**: time taken to access account information from the state trie * **account update**: time taken to incorporate dirty account objects into the state trie (account trie) * **account hash**: time taken to re-compute the new root hash of the state trie (account trie) * **account commit**: time taken to commit the changes of state trie (account trie) into database * **storage read**: time taken to access smart contract storage data from the storage trie * **storage update**: time taken to incorporate dirty storage slots into the storage tries * **storage hash**: time take to re-compute the new root hash of storage tries * **storage commit**: time take to commit the changes of storage tries into database * **snapshot account read**: time taken to read account data from a snapshot * **snapshot storage read**: time taken to read storage data from a snapshot * **snapshot commit**: time take to flush the dirty state data as a new snapshot ![](https://geth.ethereum.org/images/docs/grafana/block-processing.png) #### **Transaction processing** The transaction processing panel tracks the time taken to complete the various tasks involved in validating the transactions received from the network, measured as a mean rate of events per second: * **known**: rate of new transactions arriving at the node that are ignored because the local node already knows about them. * **valid**: rate that node marks received transactions as valid * **invalid**: rate that node marks received transactions as invalid * **underpriced**: rate that node marks transactions paying too low gas price as rejected * **executable discard**: rate that valid transactions are dropped from the transaction pool, e.g. because it is already known. * **executable replace**: rate that valid transactions are replaced with a new one from same sender with same nonce but higher gas * **executable ratelimit**: rate that valid transactions are dropped due to rate-limiting * **executable nofunds**: rate that valid transations are dropped due to running out of Laxes to pay gas * **gapped discard**: rate that queued transactions are discarded from the transaction pool * **gapped replace**: rate that queued transactions are replaced with a new one from same sender with same nonce but higher gas * **gapped ratelimit**: rate that queued transactions are dropped due to rate limiting * **gapped nofunds**: rate that queued transactions are dropped due to running out of Laxes to pay gas ![](https://geth.ethereum.org/images/docs/grafana/tx-processing.png) #### **Block propagation** Block propagation metrics track the rate that the local node hears about, receives and broadcasts blocks. This includes: * **ingress announcements**: the number of inbound announcements per second. Announcements are messages from peers that signal that they have a block to share * **known announcements**: the number of announcements per second the local node is already aware of them * **malicious announcements**: the number of announcements per second that are determined to be malicious, e.g. because they are trying to mount a denial-of-service attack on the local node * **ingress broadcasts**: the number of blocks directly propagated to local node per second * **known broadcasts**: counts all blocks that have been broadcast by peers including those that are too far behind the head to be downloaded * **malicious broadcasts**: the number of blocks which are determined to be malicious per second #### **Transaction propagation** Transaction propagation tracks the sending and receiving of transactions on the peer-to-peer network. This includes: * **ingress announcements**: inbound announcements (notifications of a transaction's availability) per second * **known announcements**: announcements that are ignored because the local node is already aware of them, per second * **underpriced announcements**: announcements per second that do not get fetched because they pay too little gas * **malicious announcements**: announcements per second that are dropped because they appear malicious * **ingress broadcasts**: number of transactions propagated from peers per second * **known broadcasts**: transactions per second that are ignored because they duplicate transactions that the local node already knows about * **underpriced broadcasts**: all fetched transactions that are dropped due to paying insufficient gas, per second * **otherreject broadcasts**: transactions that are rejected for reasons other than paying too little gas, per second * **finished requests**: successful deliveries of transactions per second, meaning they have been added to the local transaction pool * **failed requests**: number of failed transaction deliveries per second, e.g. failed because a peer disconnected unexpectedly * **timed out requests**: counts the number of transaction requests that time out per second * **ingress replies**: total number of inbound replies to requests for transactions per second * **known replies**: number of replies that are dropped because they are already known to the local node, per second * **underpriced replies**: number of replies per second that get dropped due to paying too little gas * **otherreject replies**: number of replies to transaction requests that get dropped for reasons other than paying too little gas, per second ![](https://geth.ethereum.org/images/docs/grafana/tx-propagation.png) #### **Block forwarding** The block forwarding panel counts the announcements and the blocks that the local node receives that it should pass on to its peers. #### **Transaction fetcher peers** The transaction fetcher peers panel shows how many peers the local node is connected to that can serve requests for transactions. The adjacent transaction fetcher hashes panel shows how many transaction hashes are available for fetching. Three statuses are reported in each panel: Waiting, queuing and fetching. #### **Reorg** The reorg meter panel simply counts the blocks added and the blocks removed during chain reorgs. The adjacent Reorg total panel shows the total number of reorg executions including both additions and removals. #### **Eth fetcher filter bodies/headers** Tracks the rate that headers/block bodies arrive from remote peers. ### Database The database section tracks various metrics related to data storage and i/o in the LevelDB and ancients databases. #### **Data rate** Measures the rate that data is written to, or read from, the LevelDB and ancients databases. Includes: * **leveldb read**: Rate that data is read from the fast-access LevelDB database that stores recent data. * **leveldb write**: Rate that data is written to the fast-access LevelDB database that stores recent data. * **ancient read**: Rate that data is read from the freezer (the database storing older data). * **ancient write**: Rate that data is written to the freezer (the database storing older data) * **compaction read**: Rate that data is read from the LevelDB database while it is being compacted (i.e. free space is reclaimed by deleting uneccessary data) * **compaction write**: Rate that data is written to the LevelDB database while it is being compacted (i.e. free space is reclaimed by deleting uneccessary data) #### **Session totals** Instead of the *rate* that data is read from, and written to, the LevelDB and ancients databases (as per Data rate), this panel tracks the total amount of data read and written across the entire time the Parallax client is running. #### **Persistent size** This panel shows the amount of data, in GB, in the LevelDB and ancients databases. #### **Compaction time, delay and count** These panels show the amount of time spent compacting the LevelDB database, duration write operations to the database are delayed due to compaction and the count of various types of compaction executions. ## Creating new dashboards If the default dashboard isn't right for you, you can update it in the browser. Remove panels by clicking on their titles and selectign remove. Add a new panel by clicking the "plus" icon in the upper right of the browser window. There, you will have to define an InfluxDB query for the metric you want to display. The endpoints for the various metrics that the Parallax client reports are listed by the Parallax client at the address/port combination passed to `--metrics.addr` and `--metrics.port` on startup - by default `127.0.0.1:6060/debug/metrics`. It is also possible to configure a panel by providing a JSON configuration model. Individial components are defined using the following syntax (the example below is for the CPU panel): ```json theme={null} { "id": 106, "gridPos": { "h": 6, "w": 8, "x": 0, "y": 1 }, "type": "graph", "title": "CPU", "datasource": { "uid": "s1zWCjvVk", "type": "influxdb" }, "thresholds": [], "pluginVersion": "9.3.6", "links": [], "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "rightSide": false, "show": true, "total": false, "values": false }, "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "fieldConfig": { "defaults": { "links": [] }, "overrides": [] }, "fill": 1, "fillGradient": 0, "hiddenSeries": false, "lines": true, "linewidth": 1, "nullPointMode": "connected", "options": { "alertThreshold": true }, "percentage": false, "pointradius": 5, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "stack": false, "steppedLine": false, "targets": [ { "alias": "system", "expr": "system_cpu_sysload", "format": "time_series", "groupBy": [ { "params": ["$interval"], "type": "time" } ], "intervalFactor": 1, "legendFormat": "system", "measurement": "parallax.system/cpu/sysload.gauge", "orderByTime": "ASC", "policy": "default", "refId": "A", "resultFormat": "time_series", "select": [ [ { "params": ["value"], "type": "field" }, { "params": [], "type": "mean" } ] ], "tags": [ { "key": "host", "operator": "=~", "value": "/^$host$/" } ], "datasource": { "uid": "s1zWCjvVk", "type": "influxdb" } }, { "alias": "iowait", "expr": "system_cpu_syswait", "format": "time_series", "groupBy": [ { "params": ["$interval"], "type": "time" } ], "intervalFactor": 1, "legendFormat": "iowait", "measurement": "parallax.system/cpu/syswait.gauge", "orderByTime": "ASC", "policy": "default", "refId": "B", "resultFormat": "time_series", "select": [ [ { "params": ["value"], "type": "field" }, { "params": [], "type": "mean" } ] ], "tags": [ { "key": "host", "operator": "=~", "value": "/^$host$/" } ], "datasource": { "uid": "s1zWCjvVk", "type": "influxdb" } }, { "alias": "parallax", "expr": "system_cpu_procload", "format": "time_series", "groupBy": [ { "params": ["$interval"], "type": "time" } ], "intervalFactor": 1, "legendFormat": "parallax", "measurement": "parallax.system/cpu/procload.gauge", "orderByTime": "ASC", "policy": "default", "refId": "C", "resultFormat": "time_series", "select": [ [ { "params": ["value"], "type": "field" }, { "params": [], "type": "mean" } ] ], "tags": [ { "key": "host", "operator": "=~", "value": "/^$host$/" } ], "datasource": { "uid": "s1zWCjvVk", "type": "influxdb" } } ], "timeFrom": null, "timeRegions": [], "timeShift": null, "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "percent", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ], "yaxis": { "align": false, "alignLevel": null } } ``` *** *Adapted from [Understanding Geth's dashboard](https://geth.ethereum.org/docs/monitoring/understanding-dashboards) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # abigen Source: https://docs.parallaxprotocol.org/client/tools/abi-gen Abigen is a binding-generator for easily interacting with Parallax using Go. Abigen creates easy-to-use, type-safe Go packages from Parallax smart contract definitions known as ABIs. This abstracts away a lot of the complexity of handling smart contract deployment and interaction in Go native applications such as encoding and decoding smart contracts into EVM bytecode. Abigen comes bundled with the Parallax client. A full Parallax client installation includes the abigen binary. Abigen can also be built independently by navigating to `parallax/cmd/abigen` and running `go build`, or equivalently: ```sh theme={null} cd $GOPATH/src/github.com/ParallaxProtocol/parallax go build ./cmd/abigen ``` ## What is an ABI? Parallax smart contracts have a schema that defines its functions and return types in the form of a JSON file. This JSON file is known as an *Application Binary Interface*, or ABI. The ABI acts as a specification for precisely how to encode data sent to a contract and how to decode the data the contract sends back. The ABI is the only essential piece of information required to generate Go bindings. Go developers can then use the bindings to interact with the contract from their Go application without having to deal directly with data encoding and decoding. An ABI is generated when a contract is compiled. ### Generating the bindings To demonstrate the binding generator a contract is required. The contract `Storage.sol` implements two very simple functions: `store` updates a user-defined `uint256` to the contract's storage, and `retrieve` displays the value stored in the contract to the user. The Solidity code is as follows: ```solidity theme={null} // SPDX-License-Identifier: GPL-3.0 pragma solidity >0.7.0 < 0.9.0; /** * @title Storage * @dev store or retrieve variable value */ contract Storage { uint256 value; function store(uint256 number) public{ value = number; } function retrieve() public view returns (uint256){ return value; } } ``` This contract can be pasted into a text file and saved as `Storage.sol`. The following code snippet shows how an ABI can be generated for `Storage.sol` using the Solidity compiler solc. ```sh theme={null} solc --abi Storage.sol -o build ``` The ABI can also be generated in other ways such as using the compile commands in development frameworks such as [Truffle](https://trufflesuite.com/), [Hardhat](https://hardhat.org/) and [Brownie](https://eth-brownie.readthedocs.io/en/stable/) or in the online IDE [Remix](https://remix.ethereum.org/). The ABI for `Storage.sol` (`Storage.abi`) looks as follows: ```json theme={null} [ { "inputs": [], "name": "retrieve", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "uint256", "name": "number", "type": "uint256" }], "name": "store", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ] ``` The contract binding can then be generated by passing the ABI to abigen as follows: ```sh theme={null} abigen --abi Storage.abi --pkg main --type Storage --out Storage.go ``` Where the flags are: * `--abi`: Mandatory path to the contract ABI to bind to * `--pkg`: Mandatory Go package name to place the Go code into * `--type`: Optional Go type name to assign to the binding struct * `--out`: Optional output path for the generated Go source file (not set = stdout) This will generate a type-safe Go binding for the Storage contract. The generated code will look something like the snippet below, the full version of which can be viewed [here](https://gist.github.com/jmcook1186/a78e59d203bb54b06e1b81f2cda79d93). ```go theme={null} // Code generated - DO NOT EDIT. // This file is a generated binding and any manual changes will be lost. package main import ( "errors" "math/big" "strings" "github.com/ParallaxProtocol/parallax/v2" "github.com/ParallaxProtocol/parallax/v2/script/abi" "github.com/ParallaxProtocol/parallax/v2/script/abi/bind" "github.com/ParallaxProtocol/parallax/v2/util" "github.com/ParallaxProtocol/parallax/v2/primitives/types" "github.com/ParallaxProtocol/parallax/v2/support/event" ) // Reference imports to suppress errors if they are not otherwise used. var ( _ = errors.New _ = big.NewInt _ = strings.NewReader _ = parallax.ErrNotFound _ = bind.Bind _ = util.Big1 _ = types.BloomLookup _ = event.NewSubscription ) // StorageMetaData contains all meta data concerning the Storage contract. var StorageMetaData = &bind.MetaData{ ABI: "[{\"inputs\":[],\"name\":\"retrieve\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"number\",\"type\":\"uint256\"}],\"name\":\"store\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]", } // StorageABI is the input ABI used to generate the binding from. // Deprecated: Use StorageMetaData.ABI instead. var StorageABI = StorageMetaData.ABI // Storage is an auto generated Go binding around an Parallax contract. type Storage struct { StorageCaller // Read-only binding to the contract StorageTransactor // Write-only binding to the contract StorageFilterer // Log filterer for contract events } ... ``` `Storage.go` contains all the bindings required to interact with `Storage.sol` from a Go application. For instructions on how to deploy this contract to Parallax from a Go native application read our [Go bindings page](/client/developers/dapp/go-contract-bindings). To browse the Abigen source code visit the Parallax client [GitHub repository](https://github.com/ParallaxProtocol/parallax). *** *Adapted from [Abigen](https://geth.ethereum.org/docs/tools/abigen) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # APIs Source: https://docs.parallaxprotocol.org/client/tools/clef/apis Clef uses two separate APIs. The **external API** is an untrusted set of JSON-RPC methods that can be called by a user. The **internal API** is a set of JSON-RPC methods that can be called by a UI. The UI could be Clef's native command line interface or a custom UI. ## External API Clef listens to HTTP requests on http.addr:http.port (or to IPC on ipcpath), with the same JSON-RPC standard as the Parallax client. The messages are expected to be [JSON-RPC 2.0 standard](https://www.jsonrpc.org/specification). Some of these JSON-RPC calls require user interaction in the Clef terminal. Responses may be delayed significantly or may never be received if a user fails to respond to a confirmation request. The External API is **untrusted**: it does not accept credentials, nor does it expect that requests have any authority. See the [external API changelog](https://github.com/ParallaxProtocol/parallax/blob/main/cmd/clef/extapi_changelog.md) for up to date information about changes to this API. The External API encoding is as follows: * number: positive integers that are hex encoded * data: hex encoded data * string: ASCII string All hex encoded values must be prefixed with 0x. ## Methods ### **account\_new** **Create new password protected account** The signer will generate a new private key, encrypt it according to [web3 keystore spec](https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition) and store it in the keystore directory. The client is responsible for creating a backup of the keystore. If the keystore is lost there is no method of retrieving lost accounts. **Arguments** None **Result** * address \[string]: account address that is derived from the generated key **Sample call** ```json theme={null} { "id": 0, "jsonrpc": "2.0", "method": "account_new", "params": [] } ``` Response ```json theme={null} { "id": 0, "jsonrpc": "2.0", "result": "0xbea9183f8f4f03d427f6bcea17388bdff1cab133" } ``` ### **account\_list** **List available accounts** List all accounts that this signer currently manages **Arguments** None **Result** * array with account records: * account.address \[string]: account address that is derived from the generated key **Sample call** ```json theme={null} { "id": 1, "jsonrpc": "2.0", "method": "account_list" } ``` Response ```json theme={null} { "id": 1, "jsonrpc": "2.0", "result": [ "0xafb2f771f58513609765698f65d3f2f0224a956f", "0xbea9183f8f4f03d427f6bcea17388bdff1cab133" ] } ``` ### **account\_signTransaction** **Sign transactions** Signs a transaction and responds with the signed transaction in RLP-encoded and JSON forms. Supports both legacy and EIP-1559-style transactions. **Arguments** 1. transaction object (legacy): * from \[address]: account to send the transaction from * to \[address]: receiver account. If omitted or 0x, will cause contract creation. * gas \[number]: maximum amount of gas to burn * gasPrice \[number]: gas price * value \[number:optional]: amount of Wei to send with the transaction * data \[data:optional]: input data * nonce \[number]: account nonce 2. transaction object (1559): * from \[address]: account to send the transaction from * to \[address]: receiver account. If omitted or 0x, will cause contract creation. * gas \[number]: maximum amount of gas to burn * maxPriorityFeePerGas \[number]: maximum priority fee per unit of gas for the transaction * maxFeePerGas \[number]: maximum fee per unit of gas for the transaction * value \[number:optional]: amount of Wei to send with the transaction * data \[data:optional]: input data * nonce \[number]: account nonce 3. method signature \[string:optional] * The method signature, if present, is to aid decoding the calldata. Should consist of methodname(paramtype,...), e.g. transfer(uint256,address). The signer may use this data to parse the supplied calldata, and show the user. The data, however, is considered totally untrusted, and reliability is not expected. **Result** * raw \[data]: signed transaction in RLP encoded form * tx \[json]: signed transaction in JSON form **Sample call (legacy)** ```json theme={null} { "id": 2, "jsonrpc": "2.0", "method": "account_signTransaction", "params": [ { "from": "0x1923f626bb8dc025849e00f99c25fe2b2f7fb0db", "gas": "0x55555", "gasPrice": "0x1234", "input": "0xabcd", "nonce": "0x0", "to": "0x07a565b7ed7d7a678680a4c162885bedbb695fe0", "value": "0x1234" } ] } ``` Response ```json theme={null} { "jsonrpc": "2.0", "id": 2, "result": { "raw": "0xf88380018203339407a565b7ed7d7a678680a4c162885bedbb695fe080a44401a6e4000000000000000000000000000000000000000000000000000000000000001226a0223a7c9bcf5531c99be5ea7082183816eb20cfe0bbc322e97cc5c7f71ab8b20ea02aadee6b34b45bb15bc42d9c09de4a6754e7000908da72d48cc7704971491663", "tx": { "nonce": "0x0", "gasPrice": "0x1234", "gas": "0x55555", "to": "0x07a565b7ed7d7a678680a4c162885bedbb695fe0", "value": "0x1234", "input": "0xabcd", "v": "0x26", "r": "0x223a7c9bcf5531c99be5ea7082183816eb20cfe0bbc322e97cc5c7f71ab8b20e", "s": "0x2aadee6b34b45bb15bc42d9c09de4a6754e7000908da72d48cc7704971491663", "hash": "0xeba2df809e7a612a0a0d444ccfa5c839624bdc00dd29e3340d46df3870f8a30e" } } } ``` **Sample call (1559)** ```json theme={null} { "id": 2, "jsonrpc": "2.0", "method": "account_signTransaction", "params": [ { "from": "0xd1a9C60791e8440AEd92019a2C3f6c336ffefA27", "to": "0x8A8eAFb1cf62BfBeb1741769DAE1a9dd47996192", "gas": "0x33333", "maxPriorityFeePerGas": "0x174876E800", "maxFeePerGas": "0x174876E800", "nonce": "0x0", "value": "0x10", "data": "0x4401a6e40000000000000000000000000000000000000000000000000000000000000012" } ] } ``` Response ```json theme={null} { "jsonrpc": "2.0", "id": 2, "result": { "raw": "0x02f891018085174876e80085174876e80083033333948a8eafb1cf62bfbeb1741769dae1a9dd4799619210a44401a6e40000000000000000000000000000000000000000000000000000000000000012c080a0c8b59180c6e0c154284402b52d772f1afcf8ec2d245cf75bfb3212ebe676135ba02c660aaebf92d5e314fc2ba4c70f018915d174c3c1fc6e4e38d00ebf1a5bb69f", "tx": { "type": "0x2", "nonce": "0x0", "gasPrice": null, "maxPriorityFeePerGas": "0x174876e800", "maxFeePerGas": "0x174876e800", "gas": "0x33333", "value": "0x10", "input": "0x4401a6e40000000000000000000000000000000000000000000000000000000000000012", "v": "0x0", "r": "0xc8b59180c6e0c154284402b52d772f1afcf8ec2d245cf75bfb3212ebe676135b", "s": "0x2c660aaebf92d5e314fc2ba4c70f018915d174c3c1fc6e4e38d00ebf1a5bb69f", "to": "0x8a8eafb1cf62bfbeb1741769dae1a9dd47996192", "chainId": "0x1", "accessList": [], "hash": "0x8e096eb11ea89aa83900e6816fb182ff0adb2c85d270998ca2dd2394ec6c5a73" } } } ``` **Sample call with ABI-data** ```json theme={null} { "id": 67, "jsonrpc": "2.0", "method": "account_signTransaction", "params": [ { "from": "0x694267f14675d7e1b9494fd8d72fefe1755710fa", "gas": "0x333", "gasPrice": "0x1", "nonce": "0x0", "to": "0x07a565b7ed7d7a678680a4c162885bedbb695fe0", "value": "0x0", "data": "0x4401a6e40000000000000000000000000000000000000000000000000000000000000012" }, "safeSend(address)" ] } ``` Response ```json theme={null} { "jsonrpc": "2.0", "id": 67, "result": { "raw": "0xf88380018203339407a565b7ed7d7a678680a4c162885bedbb695fe080a44401a6e4000000000000000000000000000000000000000000000000000000000000001226a0223a7c9bcf5531c99be5ea7082183816eb20cfe0bbc322e97cc5c7f71ab8b20ea02aadee6b34b45bb15bc42d9c09de4a6754e7000908da72d48cc7704971491663", "tx": { "nonce": "0x0", "gasPrice": "0x1", "gas": "0x333", "to": "0x07a565b7ed7d7a678680a4c162885bedbb695fe0", "value": "0x0", "input": "0x4401a6e40000000000000000000000000000000000000000000000000000000000000012", "v": "0x26", "r": "0x223a7c9bcf5531c99be5ea7082183816eb20cfe0bbc322e97cc5c7f71ab8b20e", "s": "0x2aadee6b34b45bb15bc42d9c09de4a6754e7000908da72d48cc7704971491663", "hash": "0xeba2df809e7a612a0a0d444ccfa5c839624bdc00dd29e3340d46df3870f8a30e" } } } ``` Bash example: ```sh theme={null} > curl -H "Content-Type: application/json" -X POST --data '{"jsonrpc":"2.0","method":"account_signTransaction","params":[{"from":"0x694267f14675d7e1b9494fd8d72fefe1755710fa","gas":"0x333","gasPrice":"0x1","nonce":"0x0","to":"0x07a565b7ed7d7a678680a4c162885bedbb695fe0", "value":"0x0", "data":"0x4401a6e40000000000000000000000000000000000000000000000000000000000000012"},"safeSend(address)"],"id":67}' http://localhost:8550/ {"jsonrpc":"2.0","id":67,"result":{"raw":"0xf88380018203339407a565b7ed7d7a678680a4c162885bedbb695fe080a44401a6e4000000000000000000000000000000000000000000000000000000000000001226a0223a7c9bcf5531c99be5ea7082183816eb20cfe0bbc322e97cc5c7f71ab8b20ea02aadee6b34b45bb15bc42d9c09de4a6754e7000908da72d48cc7704971491663","tx":{"nonce":"0x0","gasPrice":"0x1","gas":"0x333","to":"0x07a565b7ed7d7a678680a4c162885bedbb695fe0","value":"0x0","input":"0x4401a6e40000000000000000000000000000000000000000000000000000000000000012","v":"0x26","r":"0x223a7c9bcf5531c99be5ea7082183816eb20cfe0bbc322e97cc5c7f71ab8b20e","s":"0x2aadee6b34b45bb15bc42d9c09de4a6754e7000908da72d48cc7704971491663","hash":"0xeba2df809e7a612a0a0d444ccfa5c839624bdc00dd29e3340d46df3870f8a30e"}}} ``` ### **account\_signData** **Sign data** Signs a chunk of data and returns the calculated signature. **Arguments** * content type \[string]: type of signed data * text/validator: hex data with custom validator defined in a contract * application/clique: [clique](https://github.com/ethereum/EIPs/issues/225) headers * text/plain: simple hex data validated by account\_ecRecover * account \[address]: account to sign with * data \[object]: data to sign **Result** * calculated signature \[data] **Sample call** ```json theme={null} { "id": 3, "jsonrpc": "2.0", "method": "account_signData", "params": ["data/plain", "0x1923f626bb8dc025849e00f99c25fe2b2f7fb0db", "0xaabbccdd"] } ``` Response ```json theme={null} { "id": 3, "jsonrpc": "2.0", "result": "0x5b6693f153b48ec1c706ba4169960386dbaa6903e249cc79a8e6ddc434451d417e1e57327872c7f538beeb323c300afa9999a3d4a5de6caf3be0d5ef832b67ef1c" } ``` ### **account\_signTypedData** **Sign data** Signs a chunk of structured data conformant to [EIP-712](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md) and returns the calculated signature. **Arguments** * account \[address]: account to sign with * data \[object]: data to sign **Result** * calculated signature \[data] **Sample call** ```json theme={null} { "id": 68, "jsonrpc": "2.0", "method": "account_signTypedData", "params": [ "0xcd2a3d9f938e13cd947ec05abc7fe734df8dd826", { "types": { "EIP712Domain": [ { "name": "name", "type": "string" }, { "name": "version", "type": "string" }, { "name": "chainId", "type": "uint256" }, { "name": "verifyingContract", "type": "address" } ], "Person": [ { "name": "name", "type": "string" }, { "name": "wallet", "type": "address" } ], "Mail": [ { "name": "from", "type": "Person" }, { "name": "to", "type": "Person" }, { "name": "contents", "type": "string" } ] }, "primaryType": "Mail", "domain": { "name": "Ether Mail", "version": "1", "chainId": 1, "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC" }, "message": { "from": { "name": "Cow", "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" }, "to": { "name": "Bob", "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" }, "contents": "Hello, Bob!" } } ] } ``` Response ```json theme={null} { "id": 1, "jsonrpc": "2.0", "result": "0x4355c47d63924e8a72e509b65029052eb6c299d53a04e167c5775fd466751c9d07299936d304c153f6443dfa05f40ff007d72911b6f72307f996231605b915621c" } ``` ### **account\_ecRecover** **Recover the signing address** Derive the address from the account that was used to sign data with content type text/plain and the signature. **Arguments** * data \[data]: data that was signed * signature \[data]: the signature to verify **Result** * derived account \[address] **Sample call** ```json theme={null} { "id": 4, "jsonrpc": "2.0", "method": "account_ecRecover", "params": [ "0xaabbccdd", "0x5b6693f153b48ec1c706ba4169960386dbaa6903e249cc79a8e6ddc434451d417e1e57327872c7f538beeb323c300afa9999a3d4a5de6caf3be0d5ef832b67ef1c" ] } ``` Response ```json theme={null} { "id": 4, "jsonrpc": "2.0", "result": "0x1923f626bb8dc025849e00f99c25fe2b2f7fb0db" } ``` ### **account\_version** **Get external API version** Get the version of the external API used by Clef. **Arguments** None **Result** * external API version \[string] **Sample call** ```json theme={null} { "id": 0, "jsonrpc": "2.0", "method": "account_version", "params": [] } ``` Response ```json theme={null} { "id": 0, "jsonrpc": "2.0", "result": "6.0.0" } ``` ## Internal (UI) API Clef has one native console-based UI, for operation without any standalone tools. However, there is also an API to communicate with an external UI. To enable that UI, the signer needs to be started with the `--stdio-ui` option, which allocates stdin / stdout for the UI API. The internal API methods need to be implemented by a UI listener. By starting the signer with the switch `--stdio-ui-test`, the signer will invoke all known methods, and expect the UI to respond with denials. This can be used during development to ensure that the API is (at least somewhat) correctly implemented. All methods in this API use object-based parameters, so that there can be no mixup of parameters: each piece of data is accessed by key. An example (insecure) proof-of-concept external UI has been implemented in [pythonsigner.py](https://github.com/ethereum/go-ethereum/blob/master/cmd/clef/pythonsigner.py). The model is as follows: * The user starts the UI app (pythonsigner.py). * The UI app starts clef with `--stdio-ui`, and listens to the process output for confirmation-requests. * clef opens the external HTTP API. * When the signer receives requests, it sends a JSON-RPC request via stdout. * The UI app prompts the user accordingly, and responds to clef. * clef signs (or not), and responds to the original request. **NOTE** A slight deviation from json standard is in place: every request and response should be confined to a single line. Whereas the json specification allows for linebreaks, linebreaks **should not** be used in this communication channel, to make things simpler for both parties. ## Methods ### **ApproveTx / ui\_approveTx** Invoked when there's a transaction for approval. **Sample call** Here's a method invocation: ```sh theme={null} curl -i -H "Content-Type: application/json" -X POST --data '{"jsonrpc":"2.0","method":"account_signTransaction","params":[{"from":"0x694267f14675d7e1b9494fd8d72fefe1755710fa","gas":"0x333","gasPrice":"0x1","nonce":"0x0","to":"0x07a565b7ed7d7a678680a4c162885bedbb695fe0", "value":"0x0", "data":"0x4401a6e40000000000000000000000000000000000000000000000000000000000000012"},"safeSend(address)"],"id":67}' http://localhost:8550/ ``` Results in the following invocation on the UI: ```json theme={null} { "jsonrpc": "2.0", "id": 1, "method": "ui_approveTx", "params": [ { "transaction": { "from": "0x0x694267f14675d7e1b9494fd8d72fefe1755710fa", "to": "0x0x07a565b7ed7d7a678680a4c162885bedbb695fe0", "gas": "0x333", "gasPrice": "0x1", "value": "0x0", "nonce": "0x0", "data": "0x4401a6e40000000000000000000000000000000000000000000000000000000000000012", "input": null }, "call_info": [ { "type": "WARNING", "message": "Invalid checksum on to-address" }, { "type": "Info", "message": "safeSend(address: 0x0000000000000000000000000000000000000012)" } ], "meta": { "remote": "127.0.0.1:48486", "local": "localhost:8550", "scheme": "HTTP/1.1" } } ] } ``` The same method invocation, but with invalid data: ```sh theme={null} curl -i -H "Content-Type: application/json" -X POST --data '{"jsonrpc":"2.0","method":"account_signTransaction","params":[{"from":"0x694267f14675d7e1b9494fd8d72fefe1755710fa","gas":"0x333","gasPrice":"0x1","nonce":"0x0","to":"0x07a565b7ed7d7a678680a4c162885bedbb695fe0", "value":"0x0", "data":"0x4401a6e40000000000000002000000000000000000000000000000000000000000000012"},"safeSend(address)"],"id":67}' http://localhost:8550/ ``` ```json theme={null} { "jsonrpc": "2.0", "id": 1, "method": "ui_approveTx", "params": [ { "transaction": { "from": "0x0x694267f14675d7e1b9494fd8d72fefe1755710fa", "to": "0x0x07a565b7ed7d7a678680a4c162885bedbb695fe0", "gas": "0x333", "gasPrice": "0x1", "value": "0x0", "nonce": "0x0", "data": "0x4401a6e40000000000000002000000000000000000000000000000000000000000000012", "input": null }, "call_info": [ { "type": "WARNING", "message": "Invalid checksum on to-address" }, { "type": "WARNING", "message": "Transaction data did not match ABI-interface: WARNING: Supplied data is stuffed with extra data. \nWant 0000000000000002000000000000000000000000000000000000000000000012\nHave 0000000000000000000000000000000000000000000000000000000000000012\nfor method safeSend(address)" } ], "meta": { "remote": "127.0.0.1:48492", "local": "localhost:8550", "scheme": "HTTP/1.1" } } ] } ``` One which has missing to, but with no data: ```json theme={null} { "jsonrpc": "2.0", "id": 3, "method": "ui_approveTx", "params": [ { "transaction": { "from": "", "to": null, "gas": "0x0", "gasPrice": "0x0", "value": "0x0", "nonce": "0x0", "data": null, "input": null }, "call_info": [ { "type": "CRITICAL", "message": "Tx will create contract with empty code!" } ], "meta": { "remote": "signer binary", "local": "main", "scheme": "in-proc" } } ] } ``` ### **ApproveListing / ui\_approveListing** Invoked when a request for account listing has been made. **Sample call** ```json theme={null} { "jsonrpc": "2.0", "id": 5, "method": "ui_approveListing", "params": [ { "accounts": [ { "url": "keystore:///home/bazonk/.ethereum/keystore/UTC--2017-11-20T14-44-54.089682944Z--123409812340981234098123409812deadbeef42", "address": "0x123409812340981234098123409812deadbeef42" }, { "url": "keystore:///home/bazonk/.ethereum/keystore/UTC--2017-11-23T21-59-03.199240693Z--cafebabedeadbeef34098123409812deadbeef42", "address": "0xcafebabedeadbeef34098123409812deadbeef42" } ], "meta": { "remote": "signer binary", "local": "main", "scheme": "in-proc" } } ] } ``` ### **ApproveSignData / ui\_approveSignData** **Sample call** ```json theme={null} { "jsonrpc": "2.0", "id": 4, "method": "ui_approveSignData", "params": [ { "address": "0x123409812340981234098123409812deadbeef42", "raw_data": "0x01020304", "messages": [ { "name": "message", "value": "\u0019Ethereum Signed Message:\n4\u0001\u0002\u0003\u0004", "type": "text/plain" } ], "hash": "0x7e3a4e7a9d1744bc5c675c25e1234ca8ed9162bd17f78b9085e48047c15ac310", "meta": { "remote": "signer binary", "local": "main", "scheme": "in-proc" } } ] } ``` ### **ApproveNewAccount / ui\_approveNewAccount** Invoked when a request for creating a new account has been made. **Sample call** ```json theme={null} { "jsonrpc": "2.0", "id": 4, "method": "ui_approveNewAccount", "params": [ { "meta": { "remote": "signer binary", "local": "main", "scheme": "in-proc" } } ] } ``` ### **ShowInfo / ui\_showInfo** The UI should show the info (a single message) to the user. Does not expect response. **Sample call** ```json theme={null} { "jsonrpc": "2.0", "id": 9, "method": "ui_showInfo", "params": ["Tests completed"] } ``` ### **ShowError / ui\_showError** The UI should show the error (a single message) to the user. Does not expect response. ```json theme={null} { "jsonrpc": "2.0", "id": 2, "method": "ui_showError", "params": ["Something bad happened!"] } ``` ### **OnApprovedTx / ui\_onApprovedTx** OnApprovedTx is called when a transaction has been approved and signed. The call contains the return value that will be sent to the external caller. The return value from this method is ignored - the reason for having this callback is to allow the ruleset to keep track of approved transactions. When implementing rate-limited rules, this callback should be used. TLDR; Use this method to keep track of signed transactions, instead of using the data in ApproveTx. Example call: ```json theme={null} { "jsonrpc": "2.0", "id": 1, "method": "ui_onApprovedTx", "params": [ { "raw": "0xf88380018203339407a565b7ed7d7a678680a4c162885bedbb695fe080a44401a6e4000000000000000000000000000000000000000000000000000000000000001226a0223a7c9bcf5531c99be5ea7082183816eb20cfe0bbc322e97cc5c7f71ab8b20ea02aadee6b34b45bb15bc42d9c09de4a6754e7000908da72d48cc7704971491663", "tx": { "nonce": "0x0", "gasPrice": "0x1", "gas": "0x333", "to": "0x07a565b7ed7d7a678680a4c162885bedbb695fe0", "value": "0x0", "input": "0x4401a6e40000000000000000000000000000000000000000000000000000000000000012", "v": "0x26", "r": "0x223a7c9bcf5531c99be5ea7082183816eb20cfe0bbc322e97cc5c7f71ab8b20e", "s": "0x2aadee6b34b45bb15bc42d9c09de4a6754e7000908da72d48cc7704971491663", "hash": "0xeba2df809e7a612a0a0d444ccfa5c839624bdc00dd29e3340d46df3870f8a30e" } } ] } ``` ### **OnSignerStartup / ui\_onSignerStartup** This method provides the UI with information about what API version the signer uses (both internal and external) as well as build-info and external API, in k/v-form. Example call: ```json theme={null} { "jsonrpc": "2.0", "id": 1, "method": "ui_onSignerStartup", "params": [ { "info": { "extapi_http": "http://localhost:8550", "extapi_ipc": null, "extapi_version": "2.0.0", "intapi_version": "1.2.0" } } ] } ``` ### **OnInputRequired / ui\_onInputRequired** Invoked when Clef requires user input (e.g. a password). Example call: ```json theme={null} { "jsonrpc": "2.0", "id": 1, "method": "ui_onInputRequired", "params": [ { "title": "Account password", "prompt": "Please enter the password for account 0x694267f14675d7e1b9494fd8d72fefe1755710fa", "isPassword": true } ] } ``` *** *Adapted from [Clef APIs](https://geth.ethereum.org/docs/tools/clef/apis) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Clique signing Source: https://docs.parallaxprotocol.org/client/tools/clef/clique-signing Clique is a proof-of-authority system where new blocks can be created by authorized ‘signers’ only. The initial set of authorized signers is configured in the genesis block. Signers can be authorized and de-authorized using a voting mechanism, thus allowing the set of signers to change while the blockchain operates. Signing blocks in Clique networks classically uses the "unlock" feature of the Parallax client so that each node is always ready to sign without requiring a user to manually provide authorization. However, using the `--unlock` flag is generally a highly dangerous thing to do because it is indiscriminate, i.e. if an account is unlocked and an attacker obtains access to the RPC api, the attacker can sign anything without supplying a password. Clef provides a way to safely circumvent `--unlock` while maintaining a enough automation for the network to be useable. ## Prerequisites It is useful to have basic knowledge of private networks and Clef. These topics are covered on our [private networks](/client/fundamentals/private-networks) and [Introduction to Clef](/client/tools/clef/introduction) pages. ## Prepping a Clique network First of all, set up a rudimentary testnet to have something to sign. Create a new keystore (password `testtesttest`) ``` $ parallax-wallet new --datadir ./ddir INFO [06-16|11:10:39.600] Maximum peer count total=50 Your new account is locked with a password. Please give a password. Do not forget this password. Password: Repeat password: Your new key was generated Public address of the key: 0x9CD932F670F7eDe5dE86F756A6D02548e5899f47 Path of the secret key file: ddir/keystore/UTC--2022-06-16T09-10-48.578523828Z--9cd932f670f7ede5de86f756a6d02548e5899f47 - You can share your public address with anyone. Others need it to interact with you. - You must NEVER share the secret key with anyone! The key controls access to your funds! - You must BACKUP your key file! Without the key, it's impossible to access account funds! - You must REMEMBER your password! Without the password, it's impossible to decrypt the key! ``` Create a genesis with that account as a sealer: ```json theme={null} { "config": { "chainId": 15, "homesteadBlock": 0, "eip150Block": 0, "eip155Block": 0, "eip158Block": 0, "byzantiumBlock": 0, "constantinopleBlock": 0, "petersburgBlock": 0, "clique": { "period": 30, "epoch": 30000 } }, "difficulty": "1", "gasLimit": "8000000", "extradata": "0x00000000000000000000000000000000000000000000000000000000000000009CD932F670F7eDe5dE86F756A6D02548e5899f470000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "alloc": { "0x9CD932F670F7eDe5dE86F756A6D02548e5899f47": { "balance": "300000000000000000000000000000000" } } } ``` Initiate the Parallax client: ```sh theme={null} parallaxd --datadir ./ddir init genesis.json ``` ``` ... INFO [06-16|11:14:54.123] Writing custom genesis block INFO [06-16|11:14:54.125] Persisted trie from memory database nodes=1 size=153.00B time="64.715µs" gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B INFO [06-16|11:14:54.125] Successfully wrote genesis state database=lightchaindata hash=187412..4deb98 ``` At this point the Parallax client has been initiated with a genesis configuration. ## Prepping Clef In order to make use of `clef` for signing: 1. Ensure `clef` knows the password for the keystore. 2. Ensure `clef` auto-approves clique signing requests. These two things are independent of each other. First of all, however, `clef` must be initiated (for this example the password is clefclefclef) ```sh theme={null} clef --keystore ./ddir/keystore --configdir ./clef --chainid 15 --suppress-bootwarn init ``` ``` The master seed of clef will be locked with a password. Please specify a password. Do not forget this password! Password: Repeat password: A master seed has been generated into clef/masterseed.json This is required to be able to store credentials, such as: * Passwords for keystores (used by rule engine) * Storage for JavaScript auto-signing rules * Hash of JavaScript rule-file You should treat 'masterseed.json' with utmost secrecy and make a backup of it! * The password is necessary but not enough, you need to back up the master seed too! * The master seed does not contain your accounts, those need to be backed up separately! ``` After this operation, `clef` has it's own vault where it can store secrets and attestations. ## Storing passwords in clef With that done, `clef` can be made aware of the password. To do this `setpw
` is invoked to store a password for a given address. `clef` asks for the password, and it also asks for the master-password, in order to update and store the new secrets inside the vault. ```sh theme={null} clef --keystore ./ddir/keystore --configdir ./clef --chainid 15 --suppress-bootwarn setpw 0x9CD932F670F7eDe5dE86F756A6D02548e5899f47 ``` ``` Please enter a password to store for this address: Password: Repeat password: Decrypt master seed of clef Password: INFO [06-16|11:27:09.153] Credential store updated set=0x9CD932F670F7eDe5dE86F756A6D02548e5899f47 ``` At this point, if Clef is used as a sealer, each block would require manual approval, but without needing to provide the password. ### Testing stored password To test that the stored password is correct and being properly handled by Clef, first start clef: ```sh theme={null} clef --keystore ./ddir/keystore --configdir ./clef --chainid 15 --suppress-bootwarn ``` then start the Parallax client: ```sh theme={null} parallaxd --datadir ./ddir --signer ./clef/clef.ipc --mine ``` The Parallax client will ask what accounts are present - enter `y` to approve: ``` -------- List Account request-------------- A request has been made to list all accounts. You can select which accounts the caller can see [x] 0x9CD932F670F7eDe5dE86F756A6D02548e5899f47 URL: keystore:///home/user/tmp/clique_clef/ddir/keystore/UTC--2022-06-16T09-10-48.578523828Z--9cd932f670f7ede5de86f756a6d02548e5899f47 ------------------------------------------- Request context: NA - ipc - NA Additional HTTP header data, provided by the external caller: User-Agent: "" Origin: "" Approve? [y/N]: > y DEBUG[06-16|11:36:42.499] Served account_list reqid=2 duration=3.213768195s ``` After this, the Parallax client will start asking clef to sign things: ``` -------- Sign data request-------------- Account: 0x9CD932F670F7eDe5dE86F756A6D02548e5899f47 [chksum ok] messages: Clique header [clique]: "clique header 1 [0x9b08fa3705e8b6e1b327d84f7936c21a3cb11810d9344dc4473f78f8da71e571]" raw data: "\xf9\x02\x14\xa0\x18t\x12:\x91f\xa2\x90U\b\xf9\xac\xc02i\xffs\x9f\xf4\xc9⮷!\x0f\x16\xaa?#M똠\x1d\xccM\xe8\xde\xc7]z\xab\x85\xb5g\xb6\xcc\xd4\x1a\xd3\x12E\x1b\x94\x8at\x13\xf0\xa1B\xfd@ԓG\x94\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa0]1%\n\xfc\xee'\xd0e\xce\xc7t\xcc\\?\t4v\x8f\x06\xcb\xf8\xa0P5\xfeN\xea\x0ff\xfe\x9c\xa0V\xe8\x1f\x17\x1b\xccU\xa6\xff\x83E\xe6\x92\xc0\xf8n[H\xe0\x1b\x99l\xad\xc0\x01b/\xb5\xe3c\xb4!\xa0V\xe8\x1f\x17\x1b\xccU\xa6\xff\x83E\xe6\x92\xc0\xf8n[H\xe0\x1b\x99l\xad\xc0\x01b/\xb5\xe3c\xb4!\xb9\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x01\x83z0\x83\x80\x84b\xaa\xf9\xaa\xa0\u0603\x01\n\x14\x84geth\x88go1.18.1\x85linux\x00\x00\x00\x00\x00\x00\x00\xa0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x88\x00\x00\x00\x00\x00\x00\x00\x00" data hash: 0x9589ed81e959db6330b3d70e5f8e426fb683d03512f203009f7e41fc70662d03 ------------------------------------------- Request context: NA -> ipc -> NA Additional HTTP header data, provided by the external caller: User-Agent: "" Origin: "" Approve? [y/N]: > y ``` And indeed, after approving with `y`, the password is not required - the signed block is returned to the Parallax client: ``` INFO [06-16|11:36:46.714] Successfully sealed new block number=1 sealhash=9589ed..662d03 hash=bd20b9..af8b87 elapsed=4.214s ``` This mode of operation offers quite a poor UX because each block to be sealed requires manual approval. That is fixed in the following section. ## Using rules to approve blocks Clef rules allow a piece of Javascript take over the Approve/Deny decision. The Javascript snippet has access to the same information as the manual operator. The first approach, which approves listing, and returns the request data for ApproveListing, is demonstrated below: ```javascript theme={null} function ApproveListing() { return 'Approve'; } function ApproveSignData(r) { console.log('In Approve Sign data'); console.log(JSON.stringify(r)); } ``` In order to use a certain ruleset, it must first be 'attested'. This is to prevent someone from modifying a ruleset-file on disk after creation. ```sh theme={null} clef --keystore ./ddir/keystore --configdir ./clef --chainid 15 --suppress-bootwarn attest `sha256sum rules.js | cut -f1` ``` which returns: ``` Decrypt master seed of clef Password: INFO [06-16|13:49:00.298] Ruleset attestation updated sha256=54aae496c3f0eda063a62c73ee284ca9fae3f43b401da847ef30ea30e85e35d1 ``` And `clef` can be started, pointing out the `rules.js` file. ```sh theme={null} clef --keystore ./ddir/keystore --configdir ./clef --chainid 15 --suppress-bootwarn --rules ./rules.js ``` Once the Parallax client starts asking clef to seal blocks, the data will be displayed. From that data, rules can be defined that allow signing clique headers but nothing else. The actual data that gets passed to the js environment (and which the ruleset display in the terminal) looks as follows: ```json theme={null} { "content_type": "application/x-clique-header", "address": "0x9CD932F670F7eDe5dE86F756A6D02548e5899f47", "raw_data": "+QIUoL0guY+66jZpzZh1wDX4Si/ycX4zD8FQqF/1Apy/r4uHoB3MTejex116q4W1Z7bM1BrTEkUblIp0E/ChQv1A1JNHlAAAAAAAAAAAAAAAAAAAAAAAAAAAoF0xJQr87ifQZc7HdMxcPwk0do8Gy/igUDX+TuoPZv6coFboHxcbzFWm/4NF5pLA+G5bSOAbmWytwAFiL7XjY7QhoFboHxcbzFWm/4NF5pLA+G5bSOAbmWytwAFiL7XjY7QhuQEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICg3pPDoCEYqsY1qDYgwEKFIRnZXRoiGdvMS4xOC4xhWxpbnV4AAAAAAAAAKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIgAAAAAAAAAAA==", "messages": [ { "name": "Clique header", "value": "clique header 2 [0xae525b65bc7f711bc136f502650039cd6959c3abc28fdf0ebfe2a5f85c92f3b6]", "type": "clique" } ], "call_info": null, "hash": "0x8ca6c78af7d5ae67ceb4a1e465a8b639b9fbdec4b78e4d19cd9b1232046fbbf4", "meta": { "remote": "NA", "local": "NA", "scheme": "ipc", "User-Agent": "", "Origin": "" } } ``` To create an extremely trustless ruleset, the `raw_data` could be verified to ensure it has the right rlp structure for a Clique header: ```sh theme={null} echo "+QIUoL0guY+66jZpzZh1wDX4Si/ycX4zD8FQqF/1Apy/r4uHoB3MTejex116q4W1Z7bM1BrTEkUblIp0E/ChQv1A1JNHlAAAAAAAAAAAAAAAAAAAAAAAAAAAoF0xJQr87ifQZc7HdMxcPwk0do8Gy/igUDX+TuoPZv6coFboHxcbzFWm/4NF5pLA+G5bSOAbmWytwAFiL7XjY7QhoFboHxcbzFWm/4NF5pLA+G5bSOAbmWytwAFiL7XjY7QhuQEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICg3pPDoCEYqsY1qDYgwEKFIRnZXRoiGdvMS4xOC4xhWxpbnV4AAAAAAAAAKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIgAAAAAAAAAAA==" | base64 -d | rlpdump [ bd20b98fbaea3669cd9875c035f84a2ff2717e330fc150a85ff5029cbfaf8b87, 1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347, 0000000000000000000000000000000000000000, 5d31250afcee27d065cec774cc5c3f0934768f06cbf8a05035fe4eea0f66fe9c, 56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421, 56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421, 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, 02, 02, 7a4f0e, "", 62ab18d6, d883010a14846765746888676f312e31382e31856c696e757800000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000, ] ``` However, `messages` could also be used. They do not come from the external caller, but are generated inernally: `clef` parsed the incoming request and verified the Clique wellformedness of the content. The following simply checks for such a message: ```javascript theme={null} function OnSignerStartup(info) {} function ApproveListing() { return 'Approve'; } function ApproveSignData(r) { if (r.content_type == 'application/x-clique-header') { for (var i = 0; i < r.messages.length; i++) { var msg = r.messages[i]; if (msg.name == 'Clique header' && msg.type == 'clique') { return 'Approve'; } } } return 'Reject'; } ``` Attest the ruleset: ```sh theme={null} clef --keystore ./ddir/keystore --configdir ./clef --chainid 15 --suppress-bootwarn attest `sha256sum rules.js | cut -f1` ``` returning ``` Decrypt master seed of clef Password: INFO [06-16|14:18:53.476] Ruleset attestation updated sha256=7d5036d22d1cc66599e7050fb1877f4e48b89453678c38eea06e3525996c2379 ``` Run `clef`: ```sh theme={null} clef --keystore ./ddir/keystore --configdir ./clef --chainid 15 --suppress-bootwarn --rules ./rules.js ``` Run the Parallax client: ```sh theme={null} parallaxd --datadir ./ddir --signer ./clef/clef.ipc --mine ``` And `clef` should now happily sign blocks: ``` DEBUG[06-16|14:20:02.136] Served account_version reqid=1 duration="131.38µs" INFO [06-16|14:20:02.289] Op approved DEBUG[06-16|14:20:02.289] Served account_list reqid=2 duration=4.672441ms INFO [06-16|14:20:02.303] Op approved DEBUG[06-16|14:20:03.450] Served account_signData reqid=3 duration=1.152074109s INFO [06-16|14:20:03.456] Op approved DEBUG[06-16|14:20:04.267] Served account_signData reqid=4 duration=815.874746ms INFO [06-16|14:20:32.823] Op approved DEBUG[06-16|14:20:33.584] Served account_signData reqid=5 duration=766.840681ms ``` ## Refinements If an attacker find the Clef "external" interface (which would only happen if you start it with http enabled), they * cannot make it sign arbitrary transactions, * cannot sign arbitrary data message, However, they could still make it sign e.g. 1000 versions of a certain block height, making the chain very unstable. It is possible for rule execution to be stateful (i.e. storing data). In this case, one could, for example, store what block heights have been sealed and reject sealing a particular block height twice. In other words, these rules could be used to build a miniature version of an execution layer slashing-db. The `clique header 2` `[0xae525b65bc7f711bc136f502650039cd6959c3abc28fdf0ebfe2a5f85c92f3b6]` line is split, and the number stored using `storage.get` and `storage.put`: ```javascript theme={null} function OnSignerStartup(info) {} function ApproveListing() { return 'Approve'; } function ApproveSignData(r) { if (r.content_type != 'application/x-clique-header') { return 'Reject'; } for (var i = 0; i < r.messages.length; i++) { var msg = r.messages[i]; if (msg.name == 'Clique header' && msg.type == 'clique') { var number = parseInt(msg.value.split(' ')[2]); var latest = storage.get('lastblock') || 0; console.log('number', number, 'latest', latest); if (number > latest) { storage.put('lastblock', number); return 'Approve'; } } } return 'Reject'; } ``` Running with this ruleset: ``` JS:> number 45 latest 44 INFO [06-16|22:26:43.023] Op approved DEBUG[06-16|22:26:44.305] Served account_signData reqid=3 duration=1.287465394s JS:> number 46 latest 45 INFO [06-16|22:26:44.313] Op approved DEBUG[06-16|22:26:45.317] Served account_signData reqid=4 duration=1.010612774s ``` This might be a bit over-the-top, security-wise, and may cause problems if, for some reason, a clique-deadlock needs to be resolved by rolling back and continuing on a side-chain. It is mainly meant as a demonstration that rules can use Javascript and statefulness to construct very intricate signing logic. ## TLDR quick-version Creation and attestation is a one-off event: ```sh theme={null} ## Create the rules-file cat << END > rules.js function OnSignerStartup(info){} function ApproveListing(){ return "Approve" } function ApproveSignData(r){ if (r.content_type == "application/x-clique-header"){ for(var i = 0; i < r.messages.length; i++){ var msg = r.messages[i] if (msg.name=="Clique header" && msg.type == "clique"){ return "Approve" } } } return "Reject" } END ## Attest it, assumes clef master password is in `./clefpw` clef --keystore ./ddir/keystore \ --configdir ./clef --chainid 15 \ --suppress-bootwarn --signersecret ./clefpw \ attest `sha256sum rules.js | cut -f1` ``` The normal startup command for clef: ```sh theme={null} clef --keystore ./ddir/keystore \ --configdir ./clef --chainid 15 \ --suppress-bootwarn --signersecret ./clefpw --rules ./rules.js ``` For the Parallax client, the only change is to provide `--signer `. ## Summary Clef can be used as a signer that automatically seals Clique blocks. This is a much more secure option than unlocking accounts using the Parallax client's built-in account manager. *** *Adapted from [Clique signing](https://geth.ethereum.org/docs/tools/clef/clique-signing) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Datatypes Source: https://docs.parallaxprotocol.org/client/tools/clef/datatypes ## UI Client interface These data types are defined in the channel between Clef and the UI ### SignDataRequest SignDataRequest contains information about a pending request to sign some data. The data to be signed can be of various types, defined by content-type. Clef has done most of the work in canonicalizing and making sense of the data, and it's up to the UI to present the user with the contents of the `message` Example: ```json theme={null} { "content_type": "text/plain", "address": "0xDEADbEeF000000000000000000000000DeaDbeEf", "raw_data": "GUV0aGVyZXVtIFNpZ25lZCBNZXNzYWdlOgoxMWhlbGxvIHdvcmxk", "messages": [ { "name": "message", "value": "\u0019Ethereum Signed Message:\n11hello world", "type": "text/plain" } ], "hash": "0xd9eba16ed0ecae432b71fe008c98cc872bb4cc214d3220a36f365326cf807d68", "meta": { "remote": "localhost:9999", "local": "localhost:8545", "scheme": "http", "User-Agent": "Firefox 3.2", "Origin": "www.malicious.ru" } } ``` ### SignDataResponse - approve Response to SignDataRequest Example: ```json theme={null} { "approved": true } ``` ### SignDataResponse - deny Response to SignDataRequest Example: ```json theme={null} { "approved": false } ``` ### SignTxRequest SignTxRequest contains information about a pending request to sign a transaction. Aside from the transaction itself, there is also a `call_info`-struct. That struct contains messages of various types, that the user should be informed of. As in any request, it's important to consider that the `meta` info also contains untrusted data. The `transaction` (on input into clef) can have either `data` or `input` -- if both are set, they must be identical, otherwise an error is generated. However, Clef will always use data when passing this struct on (if Clef does otherwise, please file a ticket) Example: ```json theme={null} { "transaction": { "from": "0xDEADbEeF000000000000000000000000DeaDbeEf", "to": null, "gas": "0x3e8", "gasPrice": "0x5", "value": "0x6", "nonce": "0x1", "data": "0x01020304" }, "call_info": [ { "type": "Warning", "message": "Something looks odd, show this message as a warning" }, { "type": "Info", "message": "User should see this aswell" } ], "meta": { "remote": "localhost:9999", "local": "localhost:8545", "scheme": "http", "User-Agent": "Firefox 3.2", "Origin": "www.malicious.ru" } } ``` ### SignTxResponse - approve Response to request to sign a transaction. This response needs to contain the `transaction`, because the UI is free to make modifications to the transaction. Example: ```json theme={null} { "transaction": { "from": "0xDEADbEeF000000000000000000000000DeaDbeEf", "to": null, "gas": "0x3e8", "gasPrice": "0x5", "value": "0x6", "nonce": "0x4", "data": "0x04030201" }, "approved": true } ``` ### SignTxResponse - deny Response to SignTxRequest. When denying a request, there's no need to provide the transaction in return Example: ```json theme={null} { "transaction": { "from": "0x", "to": null, "gas": "0x0", "gasPrice": "0x0", "value": "0x0", "nonce": "0x0", "data": null }, "approved": false } ``` ### OnApproved - SignTransactionResult SignTransactionResult is used in the call `clef` -> `OnApprovedTx(result)` This occurs *after* successful completion of the entire signing procedure, but right before the signed transaction is passed to the external caller. This method (and data) can be used by the UI to signal to the user that the transaction was signed, but it is primarily useful for ruleset implementations. A ruleset that implements a rate limitation needs to know what transactions are sent out to the external interface. By hooking into this methods, the ruleset can maintain track of that count. **OBS:** Note that if an attacker can restore your clef data to a previous point in time (e.g through a backup), the attacker can reset such windows, even if he/she is unable to decrypt the content. The OnApproved method cannot be responded to, it's purely informative Example: ```json theme={null} { "raw": "0xf85d640101948a8eafb1cf62bfbeb1741769dae1a9dd47996192018026a0716bd90515acb1e68e5ac5867aa11a1e65399c3349d479f5fb698554ebc6f293a04e8a4ebfff434e971e0ef12c5bf3a881b06fd04fc3f8b8a7291fb67a26a1d4ed", "tx": { "nonce": "0x64", "gasPrice": "0x1", "gas": "0x1", "to": "0x8a8eafb1cf62bfbeb1741769dae1a9dd47996192", "value": "0x1", "input": "0x", "v": "0x26", "r": "0x716bd90515acb1e68e5ac5867aa11a1e65399c3349d479f5fb698554ebc6f293", "s": "0x4e8a4ebfff434e971e0ef12c5bf3a881b06fd04fc3f8b8a7291fb67a26a1d4ed", "hash": "0x662f6d772692dd692f1b5e8baa77a9ff95bbd909362df3fc3d301aafebde5441" } } ``` ### UserInputRequest Sent when clef needs the user to provide data. If 'password' is true, the input field should be treated accordingly (echo-free) Example: ```json theme={null} { "prompt": "The question to ask the user", "title": "The title here", "isPassword": true } ``` ### UserInputResponse Response to UserInputRequest Example: ```json theme={null} { "text": "The textual response from user" } ``` ### ListRequest Sent when a request has been made to list addresses. The UI is provided with the full accounts, including local directory names. Note: this information is not passed back to the external caller, who only sees the addresses. Example: ```json theme={null} { "accounts": [ { "address": "0xdeadbeef000000000000000000000000deadbeef", "url": "keystore:///path/to/keyfile/a" }, { "address": "0x1111111122222222222233333333334444444444", "url": "keystore:///path/to/keyfile/b" } ], "meta": { "remote": "localhost:9999", "local": "localhost:8545", "scheme": "http", "User-Agent": "Firefox 3.2", "Origin": "www.malicious.ru" } } ``` ### ListResponse Response to list request. The response contains a list of all addresses to show to the caller. Note: the UI is free to respond with any address the caller, regardless of whether it exists or not Example: ```json theme={null} { "accounts": [ { "address": "0x0000000000000000000000000000000000000000", "url": ".. ignored .." }, { "address": "0xffffffffffffffffffffffffffffffffffffffff", "url": "" } ] } ``` *** *Adapted from [Communication data types](https://geth.ethereum.org/docs/tools/clef/datatypes) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Introduction Source: https://docs.parallaxprotocol.org/client/tools/clef/introduction ### What is Clef? Clef is a tool for **signing transactions and data** in a secure local environment. It is intended to become a more composable and secure replacement for Parallax client's built-in account management. Clef decouples key management from the Parallax client itself, meaning it can be used as an independent, standalone key management and signing application, or it can be integrated into the Parallax client. This provides a more flexible modular tool compared to the Parallax client's account manager. Clef can be used safely in situations where access to Parallax is via a remote and/or untrusted node because signing happens locally, either manually or automatically using custom rulesets. The separation of Clef from the node itself enables it to run as a daemon on the same machine as the client software, on a secure usb-stick like [USB armory](https://inversepath.com/usbarmory), or even a separate VM in a [QubesOS](https://www.qubes-os.org/) type setup. ### Installing and starting Clef Clef comes bundled with the Parallax client and can be built along with the client and the other bundled tools using: ``` make all ``` However, Clef is not bound to the Parallax client and can be built on its own using: ``` make clef ``` Once built, Clef must be initialized. This includes storing some data, some of which is sensitive (such as passwords, account data, signing rules etc). Initializing Clef takes that data and encrypts it using a user-defined password. ``` clef init ``` ``` WARNING! Clef is an account management tool. It may, like any software, contain bugs. Please take care to - backup your keystore files, - verify that the keystore(s) can be opened with your password. Clef is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Enter 'ok' to proceed: > ok The master seed of clef will be locked with a password. Please specify a password. Do not forget this password! Password: Repeat password: A master seed has been generated into /home/martin/.clef/masterseed.json This is required to be able to store credentials, such as: * Passwords for keystores (used by rule engine) * Storage for JavaScript auto-signing rules * Hash of JavaScript rule-file You should treat 'masterseed.json' with utmost secrecy and make a backup of it! * The password is necessary but not enough, you need to back up the master seed too! * The master seed does not contain your accounts, those need to be backed up separately! ``` ### Security model One of the major benefits of Clef is that it is decoupled from the client software, meaning it can be used by users and dapps to sign data and transactions in a secure, local environment and send the signed packet to an arbitrary Parallax entry-point, which might include, for example, an untrusted remote node. Alternatively, Clef can simply be used as a standalone, composable signer that can be a backend component for decentralized applications. This requires a secure architecture that separates cryptographic operations from user interactions and internal/external communication. The security model of Clef is as follows: * A self-contained binary controls all cryptographic operations including encryption, decryption and storage of keystore files, and signing data and transactions. * A well defined, deliberately minimal "external" API is used to communicate with the Clef binary - Clef considers this external traffic to be UNTRUSTED. This means Clef does not accept any credentials and does not recognize authority of requests received over this channel. Clef listens on `http.addr:http.port` or `ipcpath` - the same as the Parallax client - and expects messages to be formatted using the [JSON-RPC 2.0 standard](https://www.jsonrpc.org/specification). Some of the external API calls require some user interaction (manual approve/deny)- if it is not received responses can be delayed indefinitely. * Clef communicates with the process that invoked the binary using stin/stout. The process invoking the binary is usually the native console-based user interface (UI) but there is also an API that enables communication with an external UI. This has to be enabled using `--stdio-ui` at startup. This channel is considered TRUSTED and is used to pass approvals and passwords between the user and Clef. * Clef does not store keys - the user is responsible for securely storing and backing up keyfiles. Clef does store account passwords in its encrypted vault if they are explicitly provided to Clef by the user to enable automatic account unlocking. The external API never handles any sensitive data directly, but it can be used to request Clef to sign some data or a transaction. It is the internal API that controls signing and triggers requests for manual approval (automatic approves actions that conform to attested rulesets) and passwords. The general flow for a basic transaction-signing operation using Clef and the Parallax client is as follows: ![](https://geth.ethereum.org/images/docs/clef_sign_flow.png) In the case illustrated in the schematic above, the Parallax client would be started with `--signer :` and would relay requests to `eth.sendTransaction`. Text in mono font positioned along arrows shows the objects passed between each component. Most users use Clef by manually approving transactions through the UI as in the schematic above, but it is also possible to configure Clef to sign transactions without always prompting the user. This requires defining the precise conditions under which a transaction will be signed. These conditions are known as Rules and they are small Javascript snippets that are *attested* by the user by injecting the snippet's hash into Clef's secure whitelist. Clef is then started with the rule file, so that requests that satisfy the conditions in the whitelisted rule files are automatically signed. This is covered in detail on the [Rules page](/client/tools/clef/rules). ### Basic usage Clef is started on the command line using the clef command. Clef can be configured by providing flags and commands to clef on startup. The full list of command line options is available [below](#command-line-options). Frequently used options include `--keystore` and `--chainid` which configure the path to an existing keystore and a network to connect to. These options default to `$HOME/.parallax/keystore` and 52014 (corresponding to Parallax mainnet) respectively. The following code snippet starts Clef, providing a custom path to an existing keystore and connecting to the Parallax testnet: ```sh theme={null} clef --keystore /my/keystore --chainid 5201420 ``` On starting Clef, the following welcome message is displayed in the terminal: ``` WARNING! Clef is an account management tool. It may, like any software, contain bugs. Please take care to - backup your keystore files, - verify that the keystore(s) can be opened with your password. Clef is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Enter 'ok' to proceed: > ``` Requests requiring account access or signing now require explicit consent in this terminal. Activities such as sending transactions via a local Parallax node's attached Javascript console or RPC will now hang indefinitely, awaiting approval in this terminal. A much more detailed Clef tutorial is available on the [Tutorial page](/client/tools/clef/tutorial). ### Command line options ```sh theme={null} COMMANDS: init Initialize the signer, generate secret storage attest Attest that a js-file is to be used setpw Store a credential for a keystore file delpw Remove a credential for a keystore file newaccount Create a new account gendoc Generate documentation about json-rpc format help, h Shows a list of commands or help for one command GLOBAL OPTIONS: --loglevel value log level to emit to the screen (default: 4) --keystore value Directory for the keystore (default: "$HOME/.ethereum/keystore") --configdir value Directory for Clef configuration (default: "$HOME/.clef") --chainid value Chain id to use for signing (1=mainnet, 3=Ropsten, 4=Rinkeby, 5=Goerli) (default: 1) --lightkdf Reduce key-derivation RAM & CPU usage at some expense of KDF strength --pcscdpath value Path to the smartcard daemon (pcscd) socket file (default: "/run/pcscd/pcscd.comm") --http.addr value HTTP-RPC server listening interface (default: "localhost") --http.vhosts value Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (default: "localhost") --ipcdisable Disable the IPC-RPC server --ipcpath value Filename for IPC socket/pipe within the datadir (explicit paths escape it) --http Enable the HTTP-RPC server --http.port value HTTP-RPC server listening port (default: 8550) --signersecret value A file containing the (encrypted) master seed to encrypt Clef data, e.g. keystore credentials and ruleset hash --4bytedb-custom value File used for writing new 4byte-identifiers submitted via API (default: "./4byte-custom.json") --auditlog value File used to emit audit logs. Set to "" to disable (default: "audit.log") --rules value Path to the rule file to auto-authorize requests with --stdio-ui Use STDIN/STDOUT as a channel for an external UI. This means that an STDIN/STDOUT is used for RPC-communication with a e.g. a graphical user interface, and can be used when Clef is started by an external process. --stdio-ui-test Mechanism to test interface between Clef and UI. Requires 'stdio-ui'. --advanced If enabled, issues warnings instead of rejections for suspicious requests. Default off --suppress-bootwarn If set, does not show the warning during boot ``` ### Summary Clef is an external key management and signer tool that comes bundled with the Parallax client but can either be used as a backend account manager and signer for the Parallax client or as a completely separate standalone application. Being modular and composable it can be used as a component in decentralized applications or to sign data and transactions in untrusted environments. Clef is intended to eventually replace the Parallax client's built-in account management tools. *** *Adapted from [Introduction to Clef](https://geth.ethereum.org/docs/tools/clef/introduction) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Rules Source: https://docs.parallaxprotocol.org/client/tools/clef/rules Rules in Clef are sets of conditions that determine whether a given action can be approved automatically without requiring manual intervention from the user. This can be useful for automatically approving transactions between a user's own accounts, or approving patterns that are commonly used by applications. Automatic signing also requires Clef to have access to account passwords which is configured independently of the ruleset. Rules can define arbitrary conditions such as: * Auto-approve 10 transactions with contract `CasinoDapp`, with value between `0.05 Lax` and `1 Lax` per 24h period. * Auto-approve transactions to contract `Uniswapv2` with value up to `1 Lax`, if `gas < 44k` and `gasPrice < 40Gwei`. * Auto-approve signing if the data to be signed contains the string `"approve_me"`. * Auto-approve any requests to list accounts in keystore if the request arrives over IPC Because the rules are Javascript files they can be customized to implement any arbitrary logic on the available request data. This page will explain how rules are implemented in Clef and how best to manage credentials when automatic rulesets are enabled. ## Rule Implementation The ruleset engine acts as a gatekeeper to the command line interface - it auto-approves any requests that meet the conditions defined in a set of authenticated rule files. This prevents the user from having to manually approve or reject every request - instead they can define common patterns in a rule file and abstract that task away to the ruleset engine. The general architecture is as follows: ![](https://geth.ethereum.org/images/docs/clef_ruleset.png) When Clef receives a request, the ruleset engine evaluates a Javascript file for each method defined in the internal [UI API docs](/client/tools/clef/apis#internal-ui-api). For example the code snippet below is an example ruleset that calls the function `ApproveTx`. The call to `ApproveTx` is invoking the `ui_approveTx` [JSON\_RPC API endpoint](/client/tools/clef/apis#approvetx-/-ui_approvetx). Every time an RPC method is invoked the Javascript code is executed in a freshly instantiated virtual machine. ```javascript theme={null} function asBig(str) { if (str.slice(0, 2) == "0x") { return new BigNumber(str.slice(2), 16) } return new BigNumber(str) } // Approve transactions to a certain contract if value is below a certain limit function ApproveTx(req) { var limit = big.Newint("0xb1a2bc2ec50000") var value = asBig(req.transaction.value); if (req.transaction.to.toLowerCase() == "0xae967917c465db8578ca9024c205720b1a3651a9") && value.lt(limit)) { return "Approve" } // If we return "Reject", it will be rejected. // By not returning anything, the decision to approve/reject // will be passed to the next UI, for manual processing } // Approve listings if request made from IPC function ApproveListing(req){ if (req.metadata.scheme == "ipc"){ return "Approve"} } ``` When a request is made via the external API, the logic flow is as follows: * Request is made to the signer binary using external API * signer calls the UI - in this case the ruleset engine * UI evaluates whether the call conforms to rules in an attested rulefile * Assuming the call returns "Approve", request is signed. There are three possible outcomes from the ruleset engine that are handled in different ways: | RETURN VALUE | ACTION | | - | - | | "Approve" | Auto-approve request | | "Reject" | Auto-reject request | | Anything else | Pass decision to UI for manual approval | There are some additional noteworthy implementation details that are important for defining rules correctly in ruleset.js: * The code in ruleset.js **cannot** load external Javascript files. * The Javascript engine can access storage and console * The only preloaded library in the Javascript environment is bignumber.js version 2.0.3. * Each invocation is made in a fresh virtual machine meaning data cannot be stored in global variables between invocations. * Since no global variable storage is available, disk backed storage must be used - rules should not rely on ephemeral data. * Javascript API parameters are always objects. This ensures parameters are accessed by *key* to avoid misordering errors. * Otto VM uses ES5. ES6-specific features (such as Typed Arrays) are not supported. * The regular expression engine (re2/regexp) in Otto VM is not fully compatible with the [ECMA5 specification](https://tc39.es/ecma262/#sec-intro). * [Strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) is not supported. "use strict" will parse but it does nothing. ## Credential management The ability to auto-approve transaction requires that the signer has the necessary credentials, i.e. account passwords, to decrypt keyfiles. These are stored encrypted as follows: When the signer is started it generates a seed that is locked with a user specified password. The seed is saved to a location that defaults to `$HOME/.clef/masterseed.json`. The seed itself is a blob of bytes. The signer uses the seed to: * Generate the path where the configuration and credentials data are stored. * `$HOME/.clef/790046d38025/config.json` * `$HOME/.clef/790046d38025/credentials.json` * Generate the encryption password for the config and credentials files. `config.json` stores the hashes of any attested rulesets. `credentials.json` stores encrypted account passwords. The masterseed is required to decrypt these files. The decrypted account passwords can then be used to decrypt keyfiles. ## Security ### The Javascript VM The downside of the very flexible rule implementation included in Clef is that the signer binary needs to contain a Javascript engine. This is an additional attack surface. The only viable attack is for an adversary to somehow extract cryptographic keys from memory during the Javascript VM execution. The hash-based rule attestation condition means the actual Javascript code executed by the Javascript engine is not a viable attack surface -- since if the attacker can control the ruleset, a much simpler attack would be to surreptitiously insert an attested "always-approve" rule instead of attempting to exploit the Javascript virtual machine. The Javascript engine is quite simple to implement and there are currently no known security vulnerabilities, not have there been any security problems identified for the similar Javascript VM implemented in the Parallax client. ### Writing rules Since the user has complete freedom to write custom rules, it is plausible that those rules could create unintended security vulnerabilities. This can only really be protected by coding very carefully and trying to test rulesets (e.g. on a private testnet) before implementing them on a public network. Javascript is very flexible but also easy to write incorrectly. For example, users might assume that javascript can handle large integers natively rather than explicitly using bigInt. This is an error commonly encountered in the Parallax context when users attempt to multiply gas by gasCost. It’s unclear whether any other language would be more secure - there is alwas the possibility of implementing an insecure rule. ### Credential security Clef implements a secure, encrypted vault for storing sensitive data. This vault is encrypted using a masterseed which the user is responsible for storing and backing up safely and securely. Since this masterseed is used to decrypt the secure vault, and its security is not handled by Clef, it could represent a security vulnerability if the user does not implement best practise in keeping it safe. The same is also true for keys. Keys are not stored by Clef, they are only accessed using account passwords that Clef does store in its vault. The keys themselves are stored in an external keystore whose security is the responsibility of the user. If the keys are compromised, the account is not safe irrespective of the security benefits derived from Clef. ### Ruleset examples Below are some examples of ruleset.js files. #### Example 1: Allow destination ```javascript theme={null} function ApproveTx(r) { if (r.transaction.to.toLowerCase() == '0x0000000000000000000000000000000000001337') { return 'Approve'; } if (r.transaction.to.toLowerCase() == '0x000000000000000000000000000000000000dead') { return 'Reject'; } // Otherwise goes to manual processing } ``` #### Example 2: Allow listing ```javascript theme={null} function ApproveListing() { return 'Approve'; } ``` #### Example 3: Approve signing data ```javascript theme={null} function ApproveSignData(req) { if (req.address.toLowerCase() == '0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3') { if (req.messages[0].value.indexOf('bazonk') >= 0) { return 'Approve'; } return 'Reject'; } // Otherwise goes to manual processing } ``` #### Example 4: Rate-limited window ```javascript theme={null} function big(str) { if (str.slice(0, 2) == '0x') { return new BigNumber(str.slice(2), 16); } return new BigNumber(str); } // Time window: 1 week var window = 1000 * 3600 * 24 * 7; // Limit : 1 lax var limit = new BigNumber('1e18'); function isLimitOk(transaction) { var value = big(transaction.value); // Start of our window function var windowstart = new Date().getTime() - window; var txs = []; var stored = storage.get('txs'); if (stored != '') { txs = JSON.parse(stored); } // First, remove all that have passed out of the time-window var newtxs = txs.filter(function (tx) { return tx.tstamp > windowstart; }); console.log(txs, newtxs.length); // Secondly, aggregate the current sum sum = new BigNumber(0); sum = newtxs.reduce(function (agg, tx) { return big(tx.value).plus(agg); }, sum); console.log('ApproveTx > Sum so far', sum); console.log('ApproveTx > Requested', value.toNumber()); // Would we exceed weekly limit ? return sum.plus(value).lt(limit); } function ApproveTx(r) { if (isLimitOk(r.transaction)) { return 'Approve'; } return 'Nope'; } /** * OnApprovedTx(str) is called when a transaction has been approved and signed. The parameter * 'response_str' contains the return value that will be sent to the external caller. * The return value from this method is ignore - the reason for having this callback is to allow the * ruleset to keep track of approved transactions. * * When implementing rate-limited rules, this callback should be used. * If a rule responds with neither 'Approve' nor 'Reject' - the tx goes to manual processing. If the user * then accepts the transaction, this method will be called. * * TLDR; Use this method to keep track of signed transactions, instead of using the data in ApproveTx. */ function OnApprovedTx(resp) { var value = big(resp.tx.value); var txs = []; // Load stored transactions var stored = storage.get('txs'); if (stored != '') { txs = JSON.parse(stored); } // Add this to the storage txs.push({ tstamp: new Date().getTime(), value: value }); storage.put('txs', JSON.stringify(txs)); } ``` ### Summary Rules are sets of conditions encoded in Javascript files that enable certain actions to be auto-approved by Clef. This page outlined the implementation details and security considerations that will help to build suitrable ruleset files. *** *Adapted from [Rules](https://geth.ethereum.org/docs/tools/clef/rules) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Setup Source: https://docs.parallaxprotocol.org/client/tools/clef/setup Clef is a signer and account management tool that is external to the Parallax client. This means it can be run as a separate process or even on a separate machine to the one running Parallax client, for example on secure hardware that is not connected to any external network, or on secure virtual machines. This page describes how Clef can be used with Qubes OS to provide a more secure setup than a normal laptop. Using Clef with USBArmory hardware is also briefly described. ## Qubes OS ### Background The Qubes operating system configures a set of virtual machines for different purposes such as: * personal * Your personal email, browsing etc * work * Work email etc * vault * a VM without network access, where gpg-keys and/or keepass credentials are stored. A couple of dedicated virtual machines handle externalities: * sys-net provides networking to all other (network-enabled) machines * sys-firewall handles firewall rules * sys-usb handles USB devices, and can map usb-devices to certain qubes. The goal of this document is to describe how we can set up Clef to provide secure transaction signing from a vault vm, to another networked qube which runs Dapps. ### Setup There are two ways that this can be achieved: integrated via Qubes or integrated via networking. **1. Qubes Integrated** Qubes provides a facility for inter-qubes communication via qrexec. A qube can request to make a cross-qube RPC request to another qube. The OS then asks the user if the call is permitted. ![](https://geth.ethereum.org/images/docs/qrexec-example.png) A policy-file can be created to allow such interaction. On the target domain, a service is invoked which can read the stdin from the client qube. This is how [Split GPG](https://www.qubes-os.org/doc/split-gpg/) is implemented. Clef can be set up in the same way: #### **Server** ![](https://geth.ethereum.org/images/docs/clef_qubes_qrexec.png) On the `target` qubes, we need to define the RPC service. ```sh theme={null} #!/bin/bash SIGNER_BIN="/home/user/tools/clef/clef" SIGNER_CMD="/home/user/tools/gtksigner/gtkui.py -s $SIGNER_BIN" # Start clef if not already started if [ ! -S /home/user/.clef/clef.ipc ]; then $SIGNER_CMD & sleep 1 fi # Should be started by now if [ -S /home/user/.clef/clef.ipc ]; then # Post incoming request to HTTP channel curl -H "Content-Type: application/json" -X POST -d @- http://localhost:8550 2>/dev/null fi ``` This RPC service is not complete (see notes about HTTP headers below), but works as a proof-of-concept. It will forward the data received on stdin (forwarded by the OS) to Clef's HTTP channel. It would have been possible to send data directly to the `/home/user/.clef/.clef.ipc` socket via e.g `nc -U /home/user/.clef/clef.ipc`, but the reason for sending the request data over HTTP instead of IPC is for the ability to forward HTTP headers. To enable the service: ```sh theme={null} sudo cp qubes.Clefsign /etc/qubes-rpc/ sudo chmod +x /etc/qubes-rpc/ qubes.Clefsign ``` This setup uses [gtksigner](https://github.com/holiman/gtksigner), which is a very minimal GTK-based UI that works well with minimal requirements. #### **Client** On the client qube, a listener is required to receive the request from the Dapp, and proxy it. ```python theme={null} """ This implements a dispatcher which listens to localhost:8550, and proxies requests via qrexec to the service qubes.EthSign on a target domain """ import http.server import socketserver,subprocess PORT=8550 TARGET_DOMAIN= 'debian-work' class Dispatcher(http.server.BaseHTTPRequestHandler): def do_POST(self): post_data = self.rfile.read(int(self.headers['Content-Length'])) p = subprocess.Popen(['/usr/bin/qrexec-client-vm',TARGET_DOMAIN,'qubes.Clefsign'],stdin=subprocess.PIPE, stdout=subprocess.PIPE) output = p.communicate(post_data)[0] self.wfile.write(output) with socketserver.TCPServer(("",PORT), Dispatcher) as httpd: print("Serving at port", PORT) httpd.serve_forever() ``` #### **Testing** To test the flow, with debian-work as the target: ```sh theme={null} $ cat newaccnt.json { "id": 0, "jsonrpc": "2.0","method": "account_new","params": []} $ cat newaccnt.json| qrexec-client-vm debian-work qubes.Clefsign ``` A dialog should pop up first to allow the IPC call: ![](https://geth.ethereum.org/images/docs/qubes_newaccount-1.png) Followed by a GTK-dialog to approve the operation: ![](https://geth.ethereum.org/images/docs/qubes_newaccount-2.png) To test the full flow, start the client wrapper on the client qube: ```sh theme={null} [user@work qubes]$ python3 qubes-client.py ``` Make the request over http (client qube): ```sh theme={null} [user@work clef]$ cat newaccnt.json | curl -X POST -d @- http://localhost:8550 ``` And it should show the same popups again. #### **Pros and cons** The benefits of this setup are: * This is the qubes-os intended model for inter-qube communication, * and thus benefits from qubes-os dialogs and policies for user approval However, it comes with a couple of drawbacks: * The qubes-gpg-client must forward the http request via RPC to the target qube. When doing so, the proxy will either drop important headers, or replace them. * The Host header is most likely localhost * The Origin header must be forwarded * Information about the remote ip must be added as a X-Forwarded-For. However, Clef cannot always trust an XFF header, since malicious clients may lie about XFF in order to fool the http server into believing it comes from another address. * Even with a policy in place to allow RPC calls between caller and target, there will be several popups: * One qubes-specific where the user specifies the target vm * One clef-specific to approve the transaction **2. Network integrated** The second way to set up Clef on a qubes system is to allow networking, and have Clef listen to a port which is accessible from other qubes. ![](https://geth.ethereum.org/images/docs/clef_qubes_http.png) ## USBArmory The [USB armory](https://inversepath.com/usbarmory) is an open source hardware design with an 800 MHz ARM processor. It is a pocket-sized computer. When inserted into a laptop, it identifies itself as a USB network interface, basically adding another network to your computer that can be used to SSH into the device. Running Clef off a USB armory means that the armory can be used as a very versatile offline computer, which only ever connects to a local network between the local computer and the device itself. Needless to say, while this model should be fairly secure against remote attacks, an attacker with physical access to the USB Armory would trivially be able to extract the contents of the device filesystem. ## Summary This page introduced two ways to setup Clef that give additional security compared to running on a normal laptop. *** *Adapted from [Advanced setup](https://geth.ethereum.org/docs/tools/clef/setup) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # Tutorial Source: https://docs.parallaxprotocol.org/client/tools/clef/tutorial This page provides a step-by-step walkthrough tutorial demonstrating some common uses of Clef. This includes manual approvals and automated rules. Clef is presented both as a standalone general signer with requests made via RPC and also as a backend signer for the Parallax client. ## Initialising Clef First things first, Clef needs to store some data itself. Since that data might be sensitive (passwords, signing rules, accounts), Clef's entire storage is encrypted. To support encrypting data, the first step is to initialize Clef with a random master seed, itself too encrypted with a password: ```sh theme={null} clef init ``` ``` WARNING! Clef is an account management tool. It may, like any software, contain bugs. Please take care to - backup your keystore files, - verify that the keystore(s) can be opened with your password. Clef is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Enter 'ok' to proceed: > ok The master seed of clef will be locked with a password. Please specify a password. Do not forget this password! Password: Repeat password: A master seed has been generated into /home/martin/.clef/masterseed.json This is required to be able to store credentials, such as: * Passwords for keystores (used by rule engine) * Storage for JavaScript auto-signing rules * Hash of JavaScript rule-file You should treat 'masterseed.json' with utmost secrecy and make a backup of it! * The password is necessary but not enough, you need to back up the master seed too! * The master seed does not contain your accounts, those need to be backed up separately! ``` *For readability purposes, we'll remove the WARNING printout, user confirmation and the unlocking of the master seed in the rest of this document.* ## Remote interactions This tutorial will use Clef with the Parallax client on testnet. The accounts used will be in the testnet keystore with the path `~/parallax/testnet/keystore`. The tutorial assumes there are two accounts in this keystore. Instructions for creating accounts can be found on the [Account managament page](/client/fundamentals/account-management). Note that Clef can also interact with hardware wallets, although that is not demonstrated here. Clef should be started before the Parallax client, otherwise the client will complain that it cannot find a Clef instance to connect to. Clef should be started with the correct chainid for testnet. Clef itself does not connect to a blockchain, but the chainID parameter is included in the data that is aggregated to form a signature. Clef also needs a path to the correct keystore passed to the `--keystore` command. A custom path to the config directory can also be provided. This is where the ipc file will be saved which is needed to connect Clef to the Parallax client: ```sh theme={null} clef --keystore ~/parallax/testnet/keystore --configdir ~/parallax/testnet/clef --chainid=2111 ``` The following logs will be displayed in the console: ``` INFO [07-01|11:00:46.385] Starting signer chainid=5201420 keystore= parallax/testnet/keystore light-kdf=false advanced=false DEBUG[07-01|11:00:46.389] FS scan times list=3.521941ms set=9.017µs diff=4.112µs DEBUG[07-01|11:00:46.391] Ledger support enabled DEBUG[07-01|11:00:46.391] Trezor support enabled via HID DEBUG[07-01|11:00:46.391] Trezor support enabled via WebUSB INFO [07-01|11:00:46.391] Audit logs configured file=audit.log DEBUG[07-01|11:00:46.392] IPC registered namespace=account INFO [07-01|11:00:46.392] IPC endpoint opened url=parallax/testnet/clef/clef.ipc ------- Signer info ------- * intapi_version : 7.0.1 * extapi_version : 6.1.0 * extapi_http : n/a * extapi_ipc : parallax/testnet/clef/clef.ipc ``` Clef starts up in CLI (Command Line Interface) mode by default. Arbitrary remote processes may *request* account interactions (e.g. sign a transaction), which the user can individually *confirm* or *deny*. The code snippet below shows a request made to Clef via its *External API endpoint* using [NetCat](http://netcat.sourceforge.net/). The request invokes the ["account\_list"](/client/tools/clef/apis#account_list) endpoint which lists the accounts in the keystore. This command should be run in a new terminal. ```sh theme={null} echo '{"id": 1, "jsonrpc": "2.0", "method": "account_list"}' | nc -U ~/.clef/clef.ipc ``` The terminal used to send the command will now hang. This is because the process is awaiting confirmation from Clef. Switching to the Clef console reveals Clef's prompt to the user to confirm or deny the request: ``` -------- List Account request-------------- A request has been made to list all accounts. You can select which accounts the caller can see [x] 0xD9C9Cd5f6779558b6e0eD4e6Acf6b1947E7fA1F3 URL: keystore://parallax/testnet/keystore/UTC--2017-04-14T15-15-00.327614556Z--d9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3 [x] 0x086278A6C067775F71d6B2BB1856Db6E28c30418 URL: keystore://parallax/testnet/keystore/UTC--2018-02-06T22-53-11.211657239Z--086278a6c067775f71d6b2bb1856db6e28c30418 ------------------------------------------- Request context: NA - ipc - NA Additional HTTP header data, provided by the external caller: User-Agent: Origin: Approve? [y/N]: ``` Depending on whether the request is approved or denied, the NetCat process in the other terminal will receive one of the following responses: ``` {"jsonrpc":"2.0","id":1,"result":["0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3","0x086278a6c067775f71d6b2bb1856db6e28c30418"]} ``` or ``` {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"Request denied"}} ``` Apart from listing accounts, a *request* can be submitted to create a new account, signing transactions and data or recovering signatures. The available methods are documented in the Clef [External API Spec](https://github.com/ParallaxProtocol/parallax/tree/main/cmd/clef#external-api-1) and the [External API Changelog](https://github.com/ParallaxProtocol/parallax/blob/main/cmd/clef/extapi_changelog.md). > [!NOTE] > > *Note, the number of things that can be done from the External API is deliberately small to limit the power of remote calls as much as possible! Clef has an* [*Internal API*](https://github.com/ParallaxProtocol/parallax/tree/main/cmd/clef#ui-api-1) *too for the UI (User Interface) which is much richer and can support custom interfaces on top. But that's out of scope here.* The example above used Clef completely independently of the Parallax client. However, by defining Clef as the signer when the Parallax client is started imposes Clef's `request` - `confirm` - `result` pattern to any interaction with the local Parallax node that touches accounts, including requests made using RPC or an attached Javascript console. To demonstrate this, the Parallax client can be started, with Clef as the signer: ```sh theme={null} parallaxd --testnet --datadir testnet --signer=testnet/clef/clef.ipc ``` With the Parallax client running, open a new terminal and attach a Javascript console: ```sh theme={null} parallaxd attach testnet/parallax.ipc ``` A simple request to list the accounts in the keystore will cause the Javascript console to hang. ```javascript theme={null} eth.accounts; ``` Switching to the Clef terminal reveals that this is because the request is awaiting explicit confirmation from the user. The log is identical to the one shown above, when the same request for account information was made to Clef via Netcat: ``` -------- List Account request-------------- A request has been made to list all accounts. You can select which accounts the caller can see [x] 0xD9C9Cd5f6779558b6e0eD4e6Acf6b1947E7fA1F3 URL: keystore://parallax/testnet/keystore/UTC--2017-04-14T15-15-00.327614556Z--d9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3 [x] 0x086278A6C067775F71d6B2BB1856Db6E28c30418 URL: keystore://parallax/testnet/keystore/UTC--2018-02-06T22-53-11.211657239Z--086278a6c067775f71d6b2bb1856db6e28c30418 ------------------------------------------- Request context: NA - ipc - NA Additional HTTP header data, provided by the external caller: User-Agent: Origin: Approve? [y/N]: ``` In this mode, the user is required to manually confirm every action that touches account data, including querying accounts, signing and sending transactions. The example below shows an ether transaction between the two accounts in the keystore using eth.sendTransaction in the attached Javascript console. ```javascript theme={null} // this command requires 2x approval in Clef because it loads account data via eth.accounts[0] // and eth.accounts[1] var tx = { from: eth.accounts[0], to: eth.accounts[1], value: web3.toWei(0.1, 'ether') }; // then send the transaction eth.sendTransaction(tx); ``` This example demonstrates the power of Clef much more clearly than the account-listing example. In the Clef terminal, all the details of the transaction are presented to the user so that they can be reviewed before being confirmed. This gives the user an opportunity to review the fine details and make absolutely sure they really want to sign the transaction. eth.sendTransaction returns the following confirmation prompt in the Clef terminal: ``` -------- Transaction request---------------- to: 0x086278A6C067775F71d6B2BB1856Db6E28c30418 from: 0xD9C9Cd5f6779558b6e0eD4e6Acf6b1947E7fA1F3 [chksum ok] value: 100000000000000000 wei gas: 0x5208 (21000) maxFeePerGas: 1500000016 wei maxPriorityFeePerGas: 1500000000 wei nonce: 0x0 (0) chainid: 0x5 Accesslist Request context: NA - ipc - NA Additional HTTP header data, provided by the external caller: User-Agent: "" Origin: "" --------------------------------------------- Approve? [y/N] ``` Approving this transaction causes Clef to prompt the user to provide the password for the sender account. Providing the password enables the transaction to be signed and sent to the Parallax client for broadcasting to the network. The details of the signed transaction are displayed in the console. Account passwords can also be stored in Clef's encrypted vault so that they do not have to be manually entered - [more on this below](#account-passwords). ## Automatic rules For most users, manually confirming every transaction is the right way to use Clef because a human-in-the-loop can review every action. However, there are cases when it makes sense to set up some rules which permit Clef to sign a transaction without prompting the user. For example, well defined rules such as: * Auto-approve transactions with `Uniswap v2`, with value between `0.1` and `0.5 Lax` per 24h period * Auto-approve transactions to address `0xD9C9Cd5f6779558b6e0eD4e6Acf6b1947E7fA1F3` as long as `gas < 44k` and `gasPrice < 80Gwei` can be encoded and interpreted by Clef's built-in ruleset engine. ### Rule files Rules are implemented as Javascript code in js files. The ruleset engine includes the same methods as the JSON\_RPC defined in the [UI Protocol](/client/tools/clef/datatypes). The following code snippet demonstrates a rule file that approves a transaction if it satisfies the following conditions: * the recipient is `0xae967917c465db8578ca9024c205720b1a3651a9` * the value is less than 50000000000000000 wei (0.05 Lax) and approves account listing if: * the request has arrived via ipc ```javascript theme={null} //ancillary function for formatting numbers function asBig(str) { if (str.slice(0, 2) == "0x") { return new BigNumber(str.slice(2), 16) } return new BigNumber(str) } // Approve transactions to a certain contract if value is below a certain limit function ApproveTx(req) { var limit = big.Newint("0xb1a2bc2ec50000") var value = asBig(req.transaction.value); if (req.transaction.to.toLowerCase() == "0xae967917c465db8578ca9024c205720b1a3651a9") && value.lt(limit)) { return "Approve" } else{ return "Reject" } } // Approve listings if request made from IPC function ApproveListing(req){ if (req.metadata.scheme == "ipc"){ return "Approve"} } // returning nothing passes the decision to the next UI for manual assessment ``` There are three possible outcomes to this ruleset that are handled in different ways: | RETURN VALUE | ACTION | | - | - | | "Approve" | Auto-approve request | | "Reject" | Auto-approve request | | Error | Pass decision to UI for manual approval | | Unexpected value | Pass decision to UI for manual approval | | Nothing | Pass decision to UI for manual approval | ### Attestations Clef will not just accept and run arbitrary scripts - that would create an attack vector because a malicious party could change the rule file. Instead, the user explicitly *attests* to a rule file, which involves injecting the file's SHA256 hash into Clef's secure store. The following code snippet shows how to calculate a SHA256 hash for a file named `rules.js` and pass it to Clef. Note that Clef will prompt the user to provide the master password because the Clef store has to be decrypted in order to add the attestation to it. ```sh theme={null} # calculate hash sha256sum rules.js # attest to rules.js in Clef clef attest 645b58e4f945e24d0221714ff29f6aa8e860382ced43490529db1695f5fcc71c ``` Once this attestation has been added to the Clef store, it can be used to automatically approve interactions that satisfy the conditions encoded in rules.js in Clef. ### Account passwords The rules described in `rules.js` above require access to the accounts in the Clef keystore which are protected by user-defined passwords. The signer therefore requires access to these passwords in order to automatically unlock the keystore and sign data and transactions using the accounts. This is done using clef setpw, passing the account address as the sole argument: ```sh theme={null} clef setpw 0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3 ``` which displays the following in the terminal: ``` Please enter a password to store for this address: Password: Repeat password: Decrypt master seed of clef Password: INFO [07-01|14:05:56.031] Credential store updated key=0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3 ``` Note that Clef does not really 'unlock' an account, it just abstracts the process of providing the password away from the end-user in specific, predefined scenarios. If an account password exists in the Clef vault and the rule evaluates to "Approve" then Clef decrypts the password, uses it to decrypt the key, does the requested signing and then re-locks the account. ### Implementing rules Clef can be instructed to run an attested rule file simply by passing the path to rules.js to the --rules flag: ```sh theme={null} clef --keystore parallax/testnet/ --configdir parallax/testnet/clef --chainid 5201420 --rules rules.js ``` The following logs will be displayed in the terminal: ``` INFO [07-01|13:39:49.726] Rule engine configured file=rules.js INFO [07-01|13:39:49.726] Starting signer chainid=5201420 keystore=$parallax/testnet/ light-kdf=false advanced=false DEBUG[07-01|13:39:49.726] FS scan times list=35.15µs set=4.251µs diff=2.766µs DEBUG[07-01|13:39:49.727] Ledger support enabled DEBUG[07-01|13:39:49.727] Trezor support enabled via HID DEBUG[07-01|13:39:49.727] Trezor support enabled via WebUSB INFO [07-01|13:39:49.728] Audit logs configured file=audit.log DEBUG[07-01|13:39:49.728] IPC registered namespace=account INFO [07-01|13:39:49.728] IPC endpoint opened url=parallax/testnet/clef/clef.ipc ------- Signer info ------- * intapi_version : 7.0.0 * extapi_version : 6.0.0 * extapi_http : n/a * extapi_ipc : parallax/testnet/clef/clef.ipc ``` Any request that satisfies the ruleset will now be auto-approved by the rule file, for example the following request to sign a transaction made using the Parallax client Javascript console (note that the password for account `0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3` has already been provided to setpw and the recipient and value comply with the rules in `rules.js`): ```javascript theme={null} var tx = { to: '0xae967917c465db8578ca9024c205720b1a3651a9', from: '0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3', value: web3.toWei(0.01, 'ether') }; eth.sendTransaction(tx); ``` By contrast, the following transactions *do not* satisfy the rules in rules.js: ```javascript theme={null} // violate maximum transaction value condition var tx = { to: '0xae967917c465db8578ca9024c205720b1a3651a9', from: '0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3', value: web3.toWei(1, 'ether') }; eth.sendTransaction(tx); ``` ```javascript theme={null} // violate recipient condition var tx = { to: '0xae967917c465db8578ca9024c205720b1a3651a9', from: '0xd4c4bb7d6889453c6c6ea3e9eab3c4177b4fbcc3', value: web3.toWei(0.01, 'ether') }; eth.sendTransaction(tx); ``` These latter two transactions, that do not satisfy the encoded rules in `rules.js`, are not automatically approved, but instead pass the decision back to the UI for manual approval by the user. ### Summary of basic usage To summarize, the steps required to run Clef with an automated ruleset that requires account access is as follows: **1)** Define rules as Javascript and save as a `.js` file, e.g. `rules.js` **2)** Calculate hash of rule file using `sha256sum rules.js` **3)** Attest the rules in Clef using `clef attest ` **4)** Set account passwords in Clef using `clef --setpw
` **5)** Start Clef with rule file enabled using `clef --keystore --chainid --rules rules.js` **6)** Make requests directly to Clef using the external API or connect to the Parallax client by passing `--signer=` at client startup ## More rules Since rules are defined as Javascript code, rulesets of arbitrary complexity can be created and they can impose conditions on any part of a transaction, not only the recipient and value. A simple example is implementing a "whitelist" of recipients where transactions that have those accounts in the to field are automatically signed (for example perhaps transactions between a user's own accounts might be whitelisted): ```javascript theme={null} function ApproveTx(r) { if (r.transaction.to.toLowerCase() == '0xd4c4bb7d6889453c6c6ea3e9eab3c4177b4fbcc3') { return 'Approve'; } if (r.transaction.to.toLowerCase() == '0xae967917c465db8578ca9024c205720b1a3651a9') { return 'Reject'; } // Otherwise goes to manual processing } ``` In addition to addresses and values, other properties of a request can also be incorporated into a ruleset. The example below demonstrates a ruleset for `approve_signData` imposing the following conditions on a transaction's sender and message data. 1. The sender must be `0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3` 2. The transaction message must include the text wen-merge, which is `77656E2D6D65726765` in hex. If these conditions are satisfied then the transaction is auto-approved (assuming the password for `0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3` has been provided to setpw). ```javascript theme={null} function ApproveListing() { return 'Approve'; } function ApproveSignData(req) { if (req.address.toLowerCase() == '0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3') { if (req.messages[0].value.indexOf('wen-merge') >= 0) { return 'Approve'; } return 'Reject'; } // Otherwise goes to manual processing } ``` This file should be saved as a .js file, hashed and attested in Clef: ```sh theme={null} sha256sum rules.js ``` which returns: ``` 84d9e70aa30d0e5ffb3c4b376c9490f428390a196bfdc1d36770ffd2bbe66845 rules.js ``` then: ```sh theme={null} clef attest 84d9e70aa30d0e5ffb3c4b376c9490f428390a196bfdc1d36770ffd2bbe66845 ``` which returns: ``` Decrypt master seed of clef Password: INFO [07-01|14:11:28.509] Ruleset attestation updated sha256=84d9e70aa30d0e5ffb3c4b376c9490f428390a196bfdc1d36770ffd2bbe66845 ``` Then, Clef can be restarted with the new rules in place: ```sh theme={null} clef --keystore parallax/testnet/clef --configdir parallax/testnet/clef --chainid 5201420 --rules rules.js ``` ``` INFO [07-01|14:12:41.636] Rule engine configured file=rules.js INFO [07-01|14:12:41.636] Starting signer chainid=5201420 keystore=parallax/testnet/clef/keystore light-kdf=false advanced=false DEBUG[07-01|14:12:41.636] FS scan times list=46.722µs set=4.47µs diff=2.157µs DEBUG[07-01|14:12:41.637] Ledger support enabled DEBUG[07-01|14:12:41.637] Trezor support enabled via HID DEBUG[07-01|14:12:41.638] Trezor support enabled via WebUSB INFO [07-01|14:12:41.638] Audit logs configured file=audit.log DEBUG[07-01|14:12:41.638] IPC registered namespace=account INFO [07-01|14:12:41.638] IPC endpoint opened url=parallax/testnet/clef/clef.ipc ------- Signer info ------- * intapi_version : 7.0.0 * extapi_version : 6.0.0 * extapi_http : n/a * extapi_ipc : parallax/testnet/clef/clef.ipc ``` Finally, a request can be submitted to test that the rules are being applied as expected. Here, Clef is used independently of the Parallax client by making a request via RPC, but the same logic would be imposed if the request was made via a connected Parallax node. Some arbitrary text will be included in the message data that includes the term `wen-merge`. The plaintext `clefdemotextthatincludeswen-merge` is `636c656664656d6f7465787474686174696e636c7564657377656e2d6d65726765` when represented as a hexadecimal string. This can be passed as data to an `account_signData` request as follows: ```sh theme={null} echo '{"id": 1, "jsonrpc":"2.0", "method":"account_signData", "params":["data/plain", "0x636c656664656d6f7465787474686174696e636c7564657377656e2d6d65726765"]}' | nc -U ~/parallax/testnet/clef/clef.ipc ``` This will be automatically signed, returning a result that looks like the following: ```json theme={null} {"jsonrpc":"2.0","id":1,"result":"0x4f93e3457027f6be99b06b3392d0ebc60615ba448bb7544687ef1248dea4f5317f789002df783979c417d969836b6fda3710f5bffb296b4d51c8aaae6e2ac4831c"} ``` Alternatively, a request that does not include the phrase `wen-merge` will not automatically approve. For example, the following request passes the hexadecimal string representing the plaintext clefdemotextwithoutspecialtext: ```sh theme={null} echo '{"id": 1, "jsonrpc":"2.0", "method":"account_signData", "params":["data/plain", "0x636c656664656d6f74657874776974686f75747370656369616c74657874"]}' | nc -U ~/parallax/testnet/clef/clef.ipc ``` This returns a Request denied message as follows: ``` {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"Request denied"}} ``` Meanwhile, in the output logs in the Clef terminal: ``` INFO [02-21|14:42:41] Op approved INFO [02-21|14:42:56] Op rejected ``` The signer also stores all traffic over the external API in a log file. The last 4 lines shows the two requests and their responses: ``` $ tail -n 4 audit.log t=2022-07-01T15:52:14+0300 lvl=info msg=SignData api=signer type=request metadata="{\"remote\":\"NA\",\"local\":\"NA\",\"scheme\":\"NA\",\"User-Agent\":\"\",\"Origin\":\"\"}" addr="0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3 [chksum INVALID]" data=0x202062617a6f6e6b2062617a2067617a0a content-type=data/plain t=2022-07-01T15:52:14+0300 lvl=info msg=SignData api=signer type=response data=0x636c656664656d6f7465787474686174696e636c7564657377656e2d6d65726765 error=nil t=2022-07-01T15:52:23+0300 lvl=info msg=SignData api=signer type=request metadata="{\"remote\":\"NA\",\"local\":\"NA\",\"scheme\":\"NA\",\"User-Agent\":\"\",\"Origin\":\"\"}" addr="0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3 [chksum INVALID]" data=0x636c656664656d6f74657874776974686f75747370656369616c74657874 content-type=data/plain t=2022-07-01T15:52:23+0300 lvl=info msg=SignData api=signer type=response data= error="Request denied" ``` More examples, including a ruleset for a rate-limited window, are available on the [Clef GitHub](https://github.com/ParallaxProtocol/parallax/blob/main/cmd/clef/rules.md#example-1-ruleset-for-a-rate-limited-window) and on the [Rules page](/client/tools/clef/rules). ## Under the hood The examples on this page have provided step-by-step instructions for various operations using Clef. However, they have not provided much detail as to what is happening under the hood. This section will provide some more details about how Clef organizes itself locally. Initializing Clef with a master password and providing an account password to `clef setpw` and attesting a ruleset creates the following files in the directory `~/.clef/` (this path is independent of the paths provided to `--keystore` and `--configdir` on startup): ``` # displayed using $ ls -laR ~/.clef/ /home/user/.clef/: total 24 drwxr-x--x 3 user user 4096 Jul 1 13:45 . drwxr-xr-x 102 user user 12288 Jul 1 13:39 .. drwx------ 2 user user 4096 Jul 1 13:25 02f90c0603f4f2f60188 -r-------- 1 user user 868 Jun 28 13:55 masterseed.json /home/user/.clef/02f90c0603f4f2f60188: total 12 drwx------ 2 user user 4096 Jul 1 13:25 . drwxr-x--x 3 user user 4096 Jul 1 13:45 .. -rw------- 1 user user 159 Jul 1 13:25 config.json -rw------- 1 user user 115 Jul 1 13:35 credentials.json ``` The file `masterseed.json` includes a json object containing the masterseed which was used to derive the vault directory (in this case `02f90c0603f4f2f60188`). The vault is encrypted using a password which is also derived from the masterseed. Inside the vault are two subdirectories: `credentials.json` `config.json` Inside `credentials.json` are the confidential `ksp` data (standing for "keystore pass" - these are the account passwords used to unlock the keystore). The `config.json file` contains encrypted key/value pairs for configuration data. Usually this is only the `sha256` hashes of any attested rulesets. Vault locations map uniquely to masterseeds so that multiple instances of Clef can co-exist each with their own attested rules and their own set of keystore passwords. This is useful for, for example, maintaining separate setups for Mainnet and testnets. The contents of each of these json files can be viewed using cat and should look something like the following: For config.json: ```sh theme={null} cat ~/.clef/02f90c0603f4f2f60188/config.json ``` ```json theme={null} {"ruleset_sha256":{"iv":"SWWEtnl+R+I+wfG7","c":"I3fjmwmamxVcfGax7D0MdUOL29/rBWcs73WBILmYK0o1CrX7wSMc3y37KsmtlZUAjp0oItYq01Ow8VGUOzilG91tDHInB5YHNtm/YkufEbo="}} ``` and for credentials.json: ```sh theme={null} cat ~/.clef/02f90c0603f4f2f60188/config.json ``` ```json theme={null} {"0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3": {"iv": "6SC062CfaUW8uSqH","c":"C+S5kaJyrarrxrAESs4EmPjL5zmg5tRh0Q=="}} ``` ## Parallax client integration This tutorial has bounced back and forth between demonstrating Clef as a standalone tool by making 'manual\` JSON RPC requests from the terminal and integrating it as a backend singer for the Parallax client. Using Clef for account management is considered best practise for the Parallax client users because of the additional security benefits it offers over and above what it offered by the Parallax client's built-in accounts module. Clef is far more flexible and composable than the Parallax client's built-in account management tool and can interface directly with hardware wallets, while Apps and wallets can request signatures directly from Clef. Ultimately, the goal is to deprecate the Parallax client's account management tools completely and replace them with Clef. Until then, users are simply encouraged to choose to use Clef as an optional backend signer for the Parallax client. In addition to the examples on this page, the [Getting started tutorial](/client/getting-started/introduction) also demonstrates Clef/Parallax client integration. ## Summary This page includes step-by-step instructions for basic and intermediate uses of Clef, including using it as a standalone app and a backend signer for the Parallax client. Further information is available on our other Clef pages, including [Introduction](/client/tools/clef/introduction), [Setup](/client/tools/clef/setup), [Rules](/client/tools/clef/rules), [Communication Datatypes](/client/tools/clef/datatypes) and [Communication APIs](/client/tools/clef/apis). *** *Adapted from [Tutorial](https://geth.ethereum.org/docs/tools/clef/tutorial) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # devp2p Source: https://docs.parallaxprotocol.org/client/tools/devp2p [DevP2P](https://github.com/ethereum/devp2p) is a set of network protocols that form the Parallax peer-to-peer network. The DevP2P specifications define precisely how nodes should find each other and communicate. The Parallax client implements the DevP2P specifications in Go. The DevP2P stack includes the low-level peer-to-peer protocols that define discovery and secure sessions between nodes such as: * [Ethereum Node Records](https://github.com/ethereum/devp2p/blob/master/enr.md): A standard format for connectivity information for a node * [Discovery protocol](https://github.com/ethereum/devp2p/blob/master/discv4.md): Defines how nodes find each other. * [RLPx protocol](https://github.com/ethereum/devp2p/blob/master/rlpx.md): Defines a TCP based transport system for communication between nodes. DevP2P also includes the RLPx-based application level protocols including: * [Ethereum Wire Protocol](https://github.com/ethereum/devp2p/blob/master/caps/eth.md): facilitates exchange of blockchain data between peers * [Ethereum Snapshot Protocol](https://github.com/ethereum/devp2p/blob/master/caps/snap.md): enables exchange of snapshots between peers To debug and develop these networking components, the Parallax client includes a command line tool called `devp2p`. This page will outline some of `devp2p`s built-in tools. ## PNR Decoding Parallax Node Records can be decoded, verified and displayed to the terminal using `enrdump`. It takes the ENR in its encoded form, which is the base64 encoding of its RLP representation. A decoded human-readable text representation is displayed. Use `devp2p enrdump ` to verify and display a Parallax Node Record. The following is an example of the data returned by enrdump: ``` ./devp2p enrdump "enr:-J24QG3pjTFObcDvTOTJr2qPOTDH3-YxDqS47Ylm-kgM5BUwb1oD5Id6fSRTfUzTahTa7y4TWx_HSV7wri7T6iYtyAQHg2V0aMfGhLjGKZ2AgmlkgnY0gmlwhJ1a19CJc2VjcDI1NmsxoQPlCNb7N__vcnsNC8YYkFkmNj8mibnR5NuvSowcRZsLU4RzbmFwwIN0Y3CCdl-DdWRwgnZf" Node ID: 001816492db22f7572e9eea1c871a2ffe75c28162a9fbc5a9d240e480a7c176f URLv4: ./devp2p enrdump "enr:-J24QG3pjTFObcDvTOTJr2qPOTDH3-YxDqS47Ylm-kgM5BUwb1oD5Id6fSRTfUzTahTa7y4TWx_HSV7wri7T6iYtyAQHg2V0aMfGhLjGKZ2AgmlkgnY0gmlwhJ1a19CJc2VjcDI1NmsxoQPlCNb7N__vcnsNC8YYkFkmNj8mibnR5NuvSowcRZsLU4RzbmFwwIN0Y3CCdl-DdWRwgnZf" Node ID: 001816492db22f7572e9eea1c871a2ffe75c28162a9fbc5a9d240e480a7c176f URLv4: enode://e508d6fb37ffef727b0d0bc618905926363f2689b9d1e4dbaf4a8c1c459b0b534dcdf84342b78250a6dc013c9ee9f89d095d7a6d1ef0c5f4c57a083b22c557ef@157.90.215.208:30303 Record has sequence number 7 and 7 key/value pairs. "eth" c7c684b8c6299d80 "id" "v4" "ip" 157.90.215.208 "secp256k1" a103e508d6fb37ffef727b0d0bc618905926363f2689b9d1e4dbaf4a8c1c459b0b53 "snap" c0 "tcp" 30303 "udp" 30303 ``` Read more on [Parallax Node Records](/protocol/advanced/networking/addresses#parallax-node-records-pnrs) or browse the [specs](https://github.com/ethereum/devp2p/blob/591edbd36eb57280384d07373a818c00bddf3b31/enr.md). ## Node Key Management The `devp2p key ...` command family deals with node key files. Run `devp2p key generate mynode.key` to create a new node key in the `mynode.key` file. Run `devp2p key to-enode mynode.key -ip 127.0.0.1 -tcp 30303` to create an `enode://` URL corresponding to the given node key and address information. ## Maintaining DNS Discovery Node Lists The devp2p command can create and publish DNS discovery node lists. Run `devp2p dns sign ` to update the signature of a DNS discovery tree. Run `devp2p dns sync ` to download a complete DNS discovery tree. Run `devp2p dns to-cloudflare ` to publish a tree to CloudFlare DNS. Run `devp2p dns to-route53 ` to publish a tree to Amazon Route53. More information about these commands can be found in the [DNS Discovery Setup Guide](/client/developers/client/dns-disc-guide). ## Node Set Utilities There are several commands for working with JSON node set files. These files are generated by the discovery crawlers and DNS client commands. Node sets also used as the input of the DNS deployer commands. Run `devp2p nodeset info ` to display statistics of a node set. Run `devp2p nodeset filter ` to write a new, filtered node set to standard output. The following filters are supported: * `-limit ` limits the output set to N entries, taking the top N nodes by score * `-ip ` filters nodes by IP subnet * `-min-age ` filters nodes by 'first seen' time * `-eth-network ` filters nodes by "prl" ENR entry * `-snap` filters nodes by snap protocol support For example, given a node set in `nodes.json`, you could create a filtered set containing up to 20 Parallax mainnet nodes which also support snap sync using this command: ```sh theme={null} devp2p nodeset filter nodes.json -eth-network mainnet -snap -limit 20 ``` ## Discovery v4 Utilities The `devp2p discv4 ...` command family deals with the [Node Discovery v4](https://github.com/ethereum/devp2p/tree/master/discv4.md) protocol. Run `devp2p discv4 ping ` to ping a node. Run `devp2p discv4 resolve ` to find the most recent node record of a node in the DHT. Run `devp2p discv4 crawl ` to create or update a JSON node set. ## Discovery v5 Utilities The `devp2p discv5 ...` command family deals with the [Node Discovery v5](https://github.com/ethereum/devp2p/tree/master/discv5/discv5.md) protocol. This protocol is currently under active development. Run `devp2p discv5 ping ` to ping a node. Run `devp2p discv5 resolve ` to find the most recent node record of a node in the discv5 DHT. Run `devp2p discv5 listen` to run a Discovery v5 node. Run `devp2p discv5 crawl ` to create or update a JSON node set containing discv5 nodes. ## Discovery Test Suites The devp2p command also contains interactive test suites for Discovery v4 and Discovery v5. To run these tests a networking environment must be set up with two separate UDP listening addresses are available on the same machine. The two listening addresses must also be routed such that they are able to reach the node you want to test. For example, to run the test on the local host when the node under test is also on the local host, assign two IP addresses (or a larger range) to the loopback interface. On macOS, this can be done by executing the following command: ```sh theme={null} sudo ifconfig lo0 add 127.0.0.2 ``` Either test suite can then be run as follows: 1. Start the node under test first, ensuring that it won't talk to the Internet (i.e. disable bootstrapping). An easy way to prevent unintended connections to the global DHT is listening on `127.0.0.1`. 2. Get the ENR of the node and store it in the `NODE` environment variable. 3. Start the test by running `devp2p discv5 test -listen1 127.0.0.1 -listen2 127.0.0.2 $NODE`. ## Eth Protocol Test Suite The Eth Protocol test suite is a conformance test suite for the [eth protocol](https://github.com/ethereum/devp2p/blob/master/caps/eth.md). To run the eth protocol test suite, the node needs to be initialized as follows: 1. initialize the Parallax node with the `genesis.json` file contained in the testdata directory 2. import the `halfchain.rlp` file in the testdata directory 3. run the Parallax client with the following flags: ```sh theme={null} parallaxd --datadir --nodiscover --nat=none --networkid 51420 --verbosity 5 ``` Then, run the following command, replacing `` with the enode of the Parallax node: ```sh theme={null} devp2p rlpx eth-test cmd/devp2p/internal/ethtest/testdata/chain.rlp cmd/devp2p/internal/ethtest/testdata/genesis.json ``` Repeat the above process (re-initialising the node) in order to run the Eth Protocol test suite again. ### Eth66 Test Suite The Eth66 test suite is also a conformance test suite for the eth 66 protocol version specifically. To run the eth66 protocol test suite, initialize a Parallax node as described above and run the following command, replacing `` with the enode of the Parallax node: ```sh theme={null} devp2p rlpx eth66-test cmd/devp2p/internal/ethtest/testdata/chain.rlp cmd/devp2p/internal/ethtest/testdata/genesis.json ``` ## Summary This page introduced the DevP2P stack that defines Parallax's peer-to-peer network and the `devp2p` command line tool that comes bundled with the Parallax client. The devp2p tools enables the Parallax client developers to work on the peer-to-peer network. *** *Adapted from [devp2p](https://geth.ethereum.org/docs/tools/devp2p) in the go-ethereum documentation, © The go-ethereum Authors. See the [third-party notices](https://github.com/ParallaxProtocol/parallax-docs/blob/main/THIRD_PARTY_NOTICES.md).* # parallax-wallet Source: https://docs.parallaxprotocol.org/client/tools/parallax-wallet `parallax-wallet` is the offline wallet management tool for the Parallax client suite. It consolidates the keystore-directory operations previously offered by `parallaxd account …` and the single-keyfile tool previously shipped as `parallaxkey` into a single binary, modeled after Bitcoin Core's `bitcoin-wallet`. `parallax-wallet` **never talks to a running node**. Every command operates directly on files on disk, which makes it safe to run on air-gapped machines for cold-signing workflows. For commands that require a running daemon (`newaccount`, `unlock`, `sign`, `sendtx` against a live IPC socket), use `parallax-cli` instead. ## Installation `parallax-wallet` ships alongside `parallaxd` and `parallax-cli` in every release bundle. Building from source: ```sh theme={null} make parallax-wallet ``` or, for the whole suite: ```sh theme={null} make parallax ``` ## Subcommands ### Keystore-directory operations These commands operate on the keystore directory at `/keystore` (override with `--keystore`). | Command | Purpose | | - | - | | `list` | Enumerate accounts in the keystore. | | `new` | Create a new, encrypted account. | | `update
` | Change an account's password or migrate to the latest keyfile format. | | `import ` | Import a raw, hex-encoded private key and store it encrypted. | | `info` | Print keystore metadata (path, account count, KDF parameters). | | `dump` | Serialise the keystore into a single JSON backup (keys stay encrypted). | | `createfromdump` | Restore a keystore directory from a `dump` file. | ### Single-keyfile operations These commands operate on a single keyfile path — useful when you want a portable, self-contained key outside the keystore. | Command | Purpose | | - | - | | `generate [keyfile]` | Create a new, encrypted standalone keyfile. | | `inspect ` | Print a keyfile's public metadata (add `--private` to reveal the private key). | | `changepassword ` | Re-encrypt a keyfile with a new password. | | `signmessage ` | Sign an EIP-191 personal message. | | `verifymessage
` | Verify a signature against an address (hex, with or without `0x`; `v` may be 0/1 or 27/28). | | `signtx ` | Build, sign and print a raw transaction offline (submit via `parallax-cli sendraw`). | | `signrequest ` | Sign a Parallax Wallet offline signing request (a transfer or a message) and emit the signed document. | ### Passwords For every command that decrypts a keyfile, `parallax-wallet` either prompts interactively or reads the password from the file passed with `--passwordfile` (for keyfile commands) or `--password` (for keystore-directory commands). The first non-empty line of the file is used as the password. ### JSON output Where applicable, the `--json` flag switches output to structured JSON. ## Examples ### Create a new account ```sh theme={null} parallax-wallet new ``` ### Cold-sign a transaction on an air-gapped machine Given the account's current nonce (looked up on a live node: `parallax-cli nonce 0x…`), the current gas price, and the target chain ID (2110 for mainnet): ```sh theme={null} parallax-wallet signtx \ --chainid 2110 --nonce 42 \ --gas 21000 --gasprice 1000000000 \ --to 0xabc… --value 0x1 \ ~/keystore/UTC--...keyfile ``` Copy the resulting `0x…` raw transaction to an internet-connected host and broadcast it with `parallax-cli sendraw`. ### Sign a Parallax Wallet offline signing request `signrequest` is the command-line counterpart of Parallax Wallet's offline signer. The desktop app (on the online, watch-only machine) exports a signing request; `signrequest` validates and signs it on the air-gapped machine and writes a signed-transaction document for the desktop app to broadcast. A request looks like this (all integers are decimal strings; `id` is the EIP-155 signing hash of the unsigned transaction and binds every signed field; `createdAt` and `memo` are informational and not signed): ```json theme={null} { "type": "parallax-sign-request", "version": 1, "id": "0x…", "chainId": "2110", "from": "0x…", "to": "0x…", "nonce": "7", "valueWei": "1000000000000000000", "gasLimit": "21000", "gasPriceWei": "1000000000", "createdAt": 1791965000, "memo": "rent" } ``` Before the key is used, the request must pass every check: plain LAX transfers only (no `data`), chain 2110 unless `--chainid` names another, `21000 ≤ gasLimit ≤ 30000000`, a non-zero gas price, a maximum fee (`gasLimit × gasPriceWei`) no higher than `--feecap`, checksummed addresses, an `id` that matches the recomputed signing hash, and a `from` that matches the keyfile. A summary with a fingerprint (the first eight hex digits of `id`, e.g. `3FA2-91C0`) is printed to stderr; compare it with the fingerprint shown in Parallax Wallet before answering the `Sign this transaction? [y/N]` prompt. ```sh theme={null} parallax-wallet signrequest --out signed.json \ ~/keystore/UTC--...keyfile request.json ``` | Flag | Purpose | | - | - | | `--passwordfile ` | Read the keyfile password from a file instead of prompting. | | `--chainid ` | Allow chain `` instead of mainnet; the request's `chainId` must equal it (transfers only). | | `--feecap ` | Maximum fee to sign, in LAX (default `1`; transfers only). | | `--yes` | Sign without the confirmation prompt (required when the request is read from stdin with `-`, together with `--passwordfile`). | | `--out ` | Write the signed document to a file (mode 0600) instead of stdout. | The output is the document Parallax Wallet imports: ```json theme={null} { "type": "parallax-signed-tx", "version": 1, "id": "0x", "hash": "0x", "raw": "0x", "from": "0x…", "nonce": "7", "chainId": "2110" } ``` `raw` is an ordinary signed transaction, so it can also be broadcast with `parallax-cli sendraw`. #### Message requests `signrequest` also signs a message request, as an EIP-191 personal message (the same hash `signmessage` signs). `id` is the message's EIP-191 hash, `0x` + keccak256(`"\x19Ethereum Signed Message:\n"` + byte length + message); there is no chain ID, so `--chainid` and `--feecap` are ignored. ```json theme={null} { "type": "parallax-sign-message-request", "version": 1, "id": "0x…", "from": "0x…", "message": "I control this address. 2026-10-14", "createdAt": 1791965000 } ``` The message must be valid UTF-8, 1 to 1024 bytes, with no control characters other than line feed and tab (no `\r`, NUL or escape sequences), so what is shown is everything that is signed. `from` must be a checksummed, non-zero address matching the keyfile, and `id` must match the message. The whole message is printed to stderr, one line per message line, with tabs, backslashes and invisible characters escaped, followed by its byte length and fingerprint; confirm with `Sign this message? [y/N]` (or `--yes`). The output: ```json theme={null} { "type": "parallax-signed-message", "version": 1, "id": "0x", "address": "0x…", "message": "I control this address. 2026-10-14", "signature": "0x<65 bytes r‖s‖v, v = 27 or 28>" } ``` The signature can be checked anywhere with `parallax-wallet verifymessage
`, which accepts it as is as well as the `signmessage` form (no `0x`, `v` 0/1). ### Back up and restore a keystore ```sh theme={null} parallax-wallet dump --outfile backup.json parallax-wallet createfromdump --keystore /new/location --infile backup.json ``` The dump contains every keyfile in its encrypted JSON form — the dump itself is safe to move between machines so long as the account passwords are handled independently. ## Related tools * `parallax-cli` — talks to a running daemon over IPC (JSON-RPC). Hosts the live `newaccount`, `unlock`, `sign` and `sendtx` sugar commands, all of which require a node. * `clef` — long-running external signer daemon with a rule engine and interactive approval UI. Different problem domain from `parallax-wallet`: it's a service called by other processes, not a one-shot CLI. # Ask Parallax with AI Source: https://docs.parallaxprotocol.org/guides/ai/parallax-mcp Connect Claude and other AI assistants to the Parallax network with the Parallax MCP server, and ask about blocks, transactions, mining and network health in plain language. The **Parallax MCP server** lets AI assistants such as Claude read the Parallax network directly. Instead of looking things up in the explorer yourself, you ask a question in plain language, and the assistant answers from live chain data: blocks and transactions, balances and tokens, mining and supply, and the health of the network. It uses the [Model Context Protocol](https://modelcontextprotocol.io) (MCP), the open standard assistants use to connect to outside tools. The project lives at [github.com/ParallaxProtocol/parallax-mcp](https://github.com/ParallaxProtocol/parallax-mcp). *** ## What you can ask * *"What's the state of the Parallax network right now?"* * *"Explain transaction 0x3afc1e38…24f0 to me."* * *"Audit address 0x45a1…0248: what is it and is anything risky about it?"* * *"Which token approvals has my address granted, and should I revoke any?"* * *"How many confirmations should I wait for before accepting a payment?"* * *"When is the next halving, and how much LAX has been issued so far?"* * *"Chart daily transactions over the last month."* * *"Wait for the next block and tell me who mined it."* * *"Summarize PIP-0004 and how the fee estimator works."* The assistant decides which tools to call and puts the answer together. Every figure comes from the network, the [block explorer](https://explorer.parallaxprotocol.org) or the [network status page](https://status.parallaxprotocol.org) at the moment you ask. *** ## Connect your assistant A public server runs at `https://mcp.parallaxprotocol.org/mcp`. Nothing to install: add it to your assistant and start asking. ### Claude Desktop and claude.ai Custom connectors are available on Claude plans that support them. **1. Open the connector settings** In Claude, go to **Settings → Connectors** and choose **Add custom connector**. **2. Add the Parallax server** Name it `Parallax` and enter the URL `https://mcp.parallaxprotocol.org/mcp`. **3. Ask a question** Start a new chat and ask, for example, *"What's the state of the Parallax network?"* ### Claude Code ```bash theme={null} claude mcp add --transport http parallax https://mcp.parallaxprotocol.org/mcp ``` Run `/mcp` inside Claude Code to check that `parallax` is connected. ### Other assistants Any MCP client that supports Streamable HTTP can use the same URL. The server is also listed in the [MCP Registry](https://registry.modelcontextprotocol.io) as `io.github.ParallaxProtocol/parallax-mcp`, which some clients can install from directly. > [!NOTE] > > The public server is read-only. It cannot send transactions, sign > anything or access any wallet, and it never asks for a private key. If an > assistant or anyone else asks for your private key or seed phrase, do not > give it. *** ## What it can do The public server offers over thirty tools in five groups. You don't call them yourself: the assistant picks them. | Group | What it covers | | - | - | | **Chain** | Blocks, transactions, receipts and their events, balances, contract code and storage, read-only contract calls, gas and fee estimates, event logs, and an audit of the token approvals an address has granted | | **Mining** | Hashrate, difficulty, block times, which miners found recent blocks, block rewards, issued supply against the 21,000,000 LAX cap, and the next halving | | **Explorer** | Address summaries, token balances and holders, transaction history, verified contract source code, internal transactions, search and charts | | **Network** | Network health and alerts, reporting nodes, incidents, block propagation and 7-day trends, from the status page | | **Mempool** | Transactions waiting to be mined | Amounts are given both in **LAX** and in **wei** (1 LAX = 1018 wei), so the assistant can do exact arithmetic. The server also shares reference material the assistant can read: the chain parameters, a glossary, these docs and the PIPs. It can notify assistants that support it whenever a new block is mined. *** ## Safety AI assistants can be misled by text that looks like instructions. On a public blockchain anyone can write such text into places a tool reads: a token's name, a contract's source code, an event. The Parallax MCP server treats all of it as untrusted. It strips hidden characters from that text and marks it clearly as data, and it tells the assistant never to follow instructions found there. The server is also built so that it cannot be turned into a way of moving funds: * **Read-only by design.** The public server has no tool that sends transactions. Self-hosted servers can enable transaction building for an external wallet to sign, and broadcasting only with an explicit flag. * **No keys.** The server never holds, accepts or asks for private keys. * **Bounded.** Every query is limited in size and time, and each user has a rate limit. > [!TIP] > > Treat answers as you would any research: the assistant is reading real > data, but it can still misread it. Before acting on anything that moves > funds, check the details in your wallet and in the > [block explorer](https://explorer.parallaxprotocol.org). *** ## Run your own server You can run the server yourself, for example to keep your questions off a shared server, to point it at your own node, or to enable the transaction tools. > [!TIP] > > Running [Parallax Wallet](/parallax-wallet/introduction)? It has the server built in, > answering from its own node, and can also let assistants see your wallet > and ask the app to act, as far as you allow. See > [AI assistants in Parallax Wallet](/parallax-wallet/ai-assistants). ### Locally with Docker ```bash theme={null} claude mcp add parallax -- docker run -i --rm ghcr.io/parallaxprotocol/parallax-mcp --transport stdio ``` For Claude Desktop, add this to `claude_desktop_config.json` (**Settings → Developer → Edit Config**): ```json theme={null} { "mcpServers": { "parallax": { "command": "docker", "args": ["run", "-i", "--rm", "ghcr.io/parallaxprotocol/parallax-mcp", "--transport", "stdio"] } } } ``` ### With your own node By default the server reads the public RPC endpoint, which offers the `eth`, `net` and `web3` namespaces. Pointed at your own node, it also offers transaction tracing, your node's peers and the mempool's transactions. Start the node with the extra namespaces on a local address only: ```bash theme={null} parallaxd --http --http.addr 127.0.0.1 \ --http.api eth,net,web3,txpool,debug,admin,xhash \ --gcmode archive --txlookuplimit 0 ``` Then pass `--rpc-url http://127.0.0.1:8545` to the server. Reading balances and tracing transactions at old blocks needs an archive node (`--gcmode archive`). > [!NOTE] > > The MCP server only calls read-only RPC methods, so exposing these > namespaces to it is safe. Never expose them to the internet or to other > programs. All options, the HTTP deployment and the security model are documented in the [project README](https://github.com/ParallaxProtocol/parallax-mcp#readme). # Introduction to the Parallax Client Source: https://docs.parallaxprotocol.org/guides/client/introduction Overview of the Parallax client, the official software for running a Parallax node. # Parallax Client The **Parallax client** is the official software that allows you to run a full node on the Parallax network.\ It connects to other peers, validates transactions and blocks, and enables you to interact directly with the Parallax blockchain. Running the client gives you the ability to: * **Verify the network independently** — don’t rely on third parties. * **Send and receive laxes** securely from your own machine. * **Mine blocks** using CPU or GPU mining. * **Expose APIs** for wallets, dapps, or custom applications. * **Help decentralize the network** by contributing to peer-to-peer connectivity. *** ## What’s inside this section? > [!TIP] > > Just want to hold, send and receive LAX with your own node? **[Parallax Wallet](/parallax-wallet/introduction)** is a desktop wallet with a full node built in, no command line needed, and it has a section of its own. **Recommended for most users.** This section of the documentation contains **practical guides** to help you get started with the Parallax client: * [Installing the Parallax client (CLI)](/guides/client/setup) → Step-by-step instructions to download and run the command-line client. * [Setting up MetaMask](/guides/wallets/metamask) → How to connect MetaMask to your local node and manage addresses. *** ## Who is this for? This section is designed for: * **Beginners** who just want to double-click and start running a node. * **Intermediate users** who want to connect wallets and mine. *** ## Next Steps 👉 Start here: [Parallax Wallet](/parallax-wallet/introduction) (desktop app) — or use the [CLI client](/guides/client/setup) if you prefer the terminal. Once installed, you’ll be ready to explore mining, wallets, and more! # Running the Parallax client Source: https://docs.parallaxprotocol.org/guides/client/setup Step-by-step guide for installing and running the Parallax client on your machine. Running your own **Parallax node** is the best way to fully participate in the network—whether you're a miner, or just a curious user who wants to verify everything independently.\ This guide walks you through downloading, installing, and running the Parallax client with the simplest possible steps. For more technical details about the Parallax client, please read the [Parallax client technical documentation](/client/getting-started/introduction). *** ## Prerequisites Before you begin, make sure you have: * A computer running **Windows, macOS, or Linux** * At least **2 GB of RAM** (4 GB recommended for mining) * At least 50 GB of space (SSD recommended, 100 GB for mining with DAG storage) * A stable internet connection * Port `32110` TCP & UDP allowed through your firewall (recommended — see [Accepting incoming connections](#accepting-incoming-connections)) *** ## Step-by-step Guide **1. Download the Parallax client** Go to our [GitHub Releases page](https://github.com/ParallaxProtocol/parallax/releases/latest) and download the correct file for your operating system: * **Windows 64-bit**: `parallax-windows-amd64.zip` * **Windows 32-bit**: `parallax-windows-386.zip` * **macOS (Intel)**: `parallax-darwin-amd64.tar.gz` * **macOS (Apple Silicon)**: `parallax-darwin-arm64.tar.gz` * **Linux (x86)**: `parallax-linux-amd64.tar.gz` * **Linux (ARM)**: `parallax-linux-arm64.tar.gz` * **Linux (ARMv7)**: `parallax-linux-armv7.tar.gz` **2. Unzip the package** Extract the downloaded file to a folder of your choice. Inside, you’ll see these programs: * **parallaxd** → the Parallax full-node daemon (this is the one you’ll run) * **parallax-cli** → JSON-RPC client for talking to a running node * **parallax-wallet** → offline wallet management tool (create/list/import accounts, sign messages and transactions) * **parallax** → a thin multi-call wrapper (`parallax node ...` → `parallaxd`, `parallax rpc ...` → `parallax-cli`, `parallax wallet ...` → `parallax-wallet`) * **clef** → long-running external signer daemon with a rule engine (advanced users only) **3. Start the client** * **Windows / macOS**: Simply double-click `parallaxd` to start your Parallax node. * **Linux**: You may need to right-click → “Allow executing file as program” before double-clicking. A window or terminal will open showing logs as the node connects to the network.\ That’s it — you’re running a Parallax node! > [!NOTE] > > By default, the Parallax client will store the block chain data in this folder depending on your Operating System: > > * Windows: `%APPDATA%\Parallax` or `%LOCALAPPDATA%\Parallax` > * macOS: `~/Library/Parallax` > * Linux: `~/.parallax` ✨ You’re now connected to the Parallax network! *** ## Accepting incoming connections Your node works without this, but it can only connect *out* to other nodes. Letting other nodes connect *in* gives you more peers and helps strengthen the network. Two things have to let the connection through: your **router** and your computer's **firewall**. ### Router Most home routers need no setup. The client asks the router to forward port `32110` automatically (UPnP or NAT-PMP), and keeps the mapping alive while it runs. If that fails, the node log shows `Couldn't add port mapping`; in that case, enable UPnP in your router's settings, or forward `32110` TCP & UDP to your computer by hand. > [!NOTE] > > Some internet providers share one public address between many customers (carrier-grade NAT). Incoming connections can't reach you then, whatever you configure. To check, compare the WAN address shown in your router with the address [ifconfig.me](https://ifconfig.me) shows — if they differ, you're behind carrier-grade NAT. ### Firewall The router forwarding the port is not enough: your computer's own firewall must allow it too. * **Windows**: the first time `parallaxd` runs, Windows asks whether to allow it on the network. Tick **both** "Private networks" **and** "Public networks", then click **Allow access**. Windows treats most networks as *Public* by default, so allowing Private alone usually still blocks incoming connections. If you already answered the prompt, open **Windows Security → Firewall & network protection → Allow an app through firewall**, click **Change settings**, and tick both columns for `parallaxd`. Or run this in a terminal opened as administrator: ```powershell theme={null} netsh advfirewall firewall add rule name="Parallax P2P TCP" dir=in action=allow protocol=TCP localport=32110 netsh advfirewall firewall add rule name="Parallax P2P UDP" dir=in action=allow protocol=UDP localport=32110 ``` If you clicked **Cancel** on the prompt, Windows created a rule that *blocks* `parallaxd`, and block rules win over allow rules. Remove it in the "Allow an app through firewall" list, or under **Advanced settings → Inbound Rules**, before adding the rules above. * **macOS**: if the firewall is on, allow `parallaxd` when macOS asks whether it may accept incoming connections. To change it later: **System Settings → Network → Firewall → Options**. * **Linux**: most desktop distributions ship with the firewall off. If you use `ufw` or `firewalld`: ```bash theme={null} sudo ufw allow 32110 # or sudo firewall-cmd --permanent --add-port=32110/tcp --add-port=32110/udp && sudo firewall-cmd --reload ``` > [!TIP] > > To confirm it works, check port `32110` with an online open-port checker while the node runs, or run `admin.peers` in the console: peers with `"inbound": true` connected to you. *** ## For Advanced Users If you’re comfortable with the terminal, here are a few helpful commands: * **Check version**: ```bash theme={null} ./parallaxd version ``` * **Change data directory**: ```bash theme={null} ./parallaxd --datadir /custom/path ``` * **Enable API**: ```bash theme={null} ./parallaxd --http --http.api "eth,net,web3" ``` * **Increase log detail**: ```bash theme={null} ./parallaxd --verbosity 4 ``` * **Show your node on [status.parallaxprotocol.org](https://status.parallaxprotocol.org)**: ```bash theme={null} ./parallaxd --prlstats ``` Your node reports under a random name, generated once and kept in the data directory, and is shown under a pseudonym. To report to another stats service, give its address: `--prlstats name@stats.example.org`. Only mainnet nodes can report to status.parallaxprotocol.org. * **Sync from Parallax testnet**: ```bash theme={null} ./parallaxd --testnet ``` *** ## Security Notice ⚠️ **Never expose RPC or WebSocket ports `8545`/`8546` directly to the internet** without proper protection. This can put your node and assets at risk. For most users, simply double-clicking the client and letting it run is the safest approach. # Mining with your CPU Source: https://docs.parallaxprotocol.org/guides/mining/cpu Beginner-friendly guide on how to start mining using the built-in CPU miner. Mining is how new coins are created and how transactions are secured on the Parallax network. The Parallax client comes with a **built-in CPU miner**, which makes it easy to start mining without installing extra software. *** ## Prerequisites * You have already installed and started the [Parallax client](/guides/client/setup). * Your client is synced or actively syncing with the Parallax network. *** ## Step-by-step Guide **1. Create or unlock an account** Before you can mine, you need a Parallax account (address) to receive rewards. * If you already use [MetaMask with Parallax](/guides/wallets/metamask), you can use one of those addresses. * To quickly generate a new account with the client, run: ```bash theme={null} ./parallax-wallet new ``` You’ll be asked to create a password. **Keep this safe!** Copy the address that is generated — you’ll need it in the next step. **2. Start mining** Run the Parallax client with the `--mine` flag and point it to your account: ```bash theme={null} ./parallaxd --mine --miner.coinbase ``` Replace `` with the account you created in the previous step. Example: ```bash theme={null} ./parallaxd --mine --miner.coinbase 0x1234abcd... ``` > [!NOTE] > > `--miner.coinbase` tells the node where to send mining rewards. > [!TIP] > > If you are using MetaMask, don't forget to include `--http` when starting the Parallax client. You can find more details on the [Setting up MetaMask](/guides/wallets/metamask) guide. > [!TIP] > > You can specify how many CPU threads to use when mining with `--miner.threads N`, where `N` is the number of threads. Set to `0` to use all available threads. **3. Check mining status** Once running, the client will show logs about new work being generated and accepted. To confirm mining is active, look for messages like: ``` ⛏️ Working on new block template 🔷 Block found ``` *** ## Where do rewards go? * Mining rewards are automatically sent to the **coinbase account** you specified. * These rewards will be credited to your account once the block you mined reach enough maturity (100 blocks on top of the one you mined). * You can view your balance in MetaMask (if using the same account) or with: ```bash theme={null} ./parallaxd attach --exec "eth.getBalance('')" ``` *** ## Tips & Troubleshooting * If your node isn’t syncing, mining will not produce valid blocks. Wait until sync is caught up. * CPU mining is slow — don’t expect big rewards. For better performance, look into GPU mining. * Make sure your node stays online; if you close the client, mining stops. *** ✨ You’re now mining on the Parallax network with your CPU! # Introduction to Mining Source: https://docs.parallaxprotocol.org/guides/mining/introduction Overview of how mining works on the Parallax network and guides to help you get started. # Mining on Parallax Mining is the process that secures the **Parallax network** and creates new coins. By contributing your computing power, you help validate transactions, maintain the blockchain, and are rewarded with laxes for your efforts. Parallax uses the [XHash](/protocol/foundational-topics/consensus/algorithms/xhash) proof-of-work algorithm, making it accessible to both **CPU** and **GPU miners**. While CPU mining is a great way to get started, GPU and pool mining provide significantly higher performance and more consistent rewards. *** ## Why mine? * **Earn rewards:** Receive coins for helping secure the network. * **Support decentralization:** Every miner strengthens the Parallax network. * **Learn by doing:** Mining is a hands-on way to understand how blockchain works. *** ## What’s inside this section? This section contains step-by-step guides for all major mining methods: * [CPU Mining](/guides/mining/cpu) → Use the built-in CPU miner included in the Parallax client. * [GPU Mining with Hashwarp](/hashwarp/getting-started) → Harness your GPU for much faster mining. Hashwarp has its own section in these docs. * [Pool Mining](/hashwarp/pool-mining) → Join a mining pool for more predictable rewards. *** ## Which method should I choose? * **Just starting out?** → Try the built-in CPU miner. * **Want real performance?** → Use your GPU with Hashwarp. * **Prefer steady payouts?** → Connect to a mining pool. *** ## Next Steps 👉 Begin with [Mining with the CPU Miner](/guides/mining/cpu) to quickly try mining on your own machine. From there, you can explore GPU and pool mining for better results. # Understanding Accounts & Addresses Source: https://docs.parallaxprotocol.org/guides/wallets/accounts Beginner-friendly guide to Parallax accounts, addresses, and keys. To use the Parallax network, you need an **account**. Accounts are how you **hold Parallax coins**, **send and receive transactions**, and **interact with the blockchain**. This guide explains what accounts are, how they work, and how to create one safely. *** ## What is an Account? A Parallax account has two important parts: * **Public Address** → This is your “bank account number.” * Example: `0x1234...abcd` * Safe to share with others so they can send you Laxes. * **Private Key** → This is your secret password. * Example: `0xabcdef1234567890...` * Must **never** be shared with anyone. Whoever has it controls your funds. Together, the address and private key let you prove ownership of your coins. *** ## How to Create an Account There are several ways to create a Parallax account: **1. Using MetaMask (recommended)** The easiest way is through [MetaMask](/guides/wallets/metamask). * When you install MetaMask, it generates a **wallet** with one or more addresses. * MetaMask secures your keys behind a **seed phrase** (12 words). * Write down your seed phrase and keep it offline in a safe place. **2. Using the Parallax client** You can also create an account directly with the Parallax client: ```bash theme={null} ./parallax-wallet new ``` You’ll be asked to set a password.\ The account file (keystore) will be saved in your data directory: * Windows: `%LOCALAPPDATA%\Parallax\keystore` * macOS: `~/Library/Parallax/keystore` * Linux: `~/.parallax/keystore` ⚠️ **Important:** Always back up your keystore file and password securely. **3. Standalone keyfiles (advanced)** Advanced users can produce a single, portable keyfile (outside the keystore) with: ```bash theme={null} ./parallax-wallet generate my-key.json ``` Use this for air-gapped cold-signing workflows. Regular users should prefer `parallax-wallet new`. *** ## Sending & Receiving Laxes * To **receive LAX**, share your **public address** with the sender. * To **send LAX**, use MetaMask or the client to sign a transaction with your **private key**. All transactions are recorded permanently on the blockchain and can be viewed in the [Parallax Explorer](https://explorer.parallaxprotocol.org). *** ## Security Best Practices * **Never share your private key or seed phrase** with anyone. * **Back up your keys** in multiple safe places (preferably offline). * Use a **strong password** when creating accounts with the client. * Consider a **hardware wallet** for added security: [Parallax Wallet works with Ledger and Trezor](/parallax-wallet/hardware-wallets). *** ✨ You now know the basics of accounts and addresses in Parallax! Next, try [Sending and Receiving LAX](/guides/wallets/send-and-reveive) to make your first transaction. # Verifying transactions in the Block Explorer Source: https://docs.parallaxprotocol.org/guides/wallets/explorer Beginner-friendly guide to using the Parallax Block Explorer to track accounts, transactions, and blocks. The **Parallax Block Explorer** is like a search engine for the blockchain. It lets you see **transactions, blocks, accounts, and balances** directly on the Parallax network. With the explorer, you don’t need to trust anyone — you can **verify everything yourself**. *** ## Why use the Explorer? * **Check your balance** without relying only on your wallet. * **Track transactions** to see when they are confirmed. * **View blocks** and see which miner produced them. * **Explore the network** and understand how Parallax works behind the scenes. *** ## Getting Started Open the official Parallax Explorer in your browser: 👉 [https://explorer.parallaxprotocol.org](https://explorer.parallaxprotocol.org) *** ## Searching for Your Account 1. Copy your Parallax address (from MetaMask or the client). 2. Paste it into the **search bar** of the explorer. 3. Press Enter. You’ll see: * Your **current balance**. * A list of **incoming and outgoing transactions**. * Your account’s **transaction count (nonce)**. *** ## Tracking a Transaction When you send Laxes, MetaMask gives you a **transaction hash** (a long string starting with `0x`). 1. Copy the transaction hash. 2. Paste it into the explorer’s search bar. 3. The explorer will show: * **Status**: Pending or Confirmed * **Block number**: Which block included your transaction * **From/To**: Sender and recipient addresses * **Amount**: Laxes transferred * **Gas used** *** ## Viewing Blocks Click on a **block number** in the explorer to see: * **Block height** (its position in the chain) * **Timestamp** (when it was mined) * **Miner** (address that mined it) * **Transactions included** * **Difficulty and hash** *** ## Tips * Bookmark the explorer to quickly check balances. * Use the transaction hash from MetaMask to confirm transfers. * Remember: if it’s not on the explorer, it didn’t happen on-chain. *** ✨ Now you know how to use the Parallax Block Explorer to independently verify accounts, transactions, and blocks! # Keeping Your Wallet Safe Source: https://docs.parallaxprotocol.org/guides/wallets/keep-safe Beginner-friendly guide to securing your Parallax accounts and protecting your LAX coins. Your Parallax **account** holds your **coins**. Protecting it is the most important thing you can do. Unlike a bank, there is **no password reset** — if you lose access to your wallet or share your private key, your funds are gone forever. This guide explains the best practices for keeping your wallet safe. *** ## The Golden Rules * **Never share your private key or seed phrase** with anyone. * **Back up your wallet** in a safe place (offline is best). * **Beware of scams and fake websites** pretending to be Parallax. * **If it sounds too good to be true, it is.** *** ## Understanding Keys & Phrases * **Public Address** → Safe to share, others use it to send you LAX. * **Private Key** → Controls your funds, must remain secret. * **Seed Phrase (12/24 words)** → A human-readable backup of your wallet. Anyone with it can restore your wallet and steal your coins. *** ## How to Back Up Safely **1. Write it down** When you first create a wallet (for example in MetaMask), you’ll be shown a **seed phrase**.\ Write it down on paper and store it in a secure location. **2. Make multiple backups** Keep at least 2–3 backups in **different safe places** (e.g., safe at home, safe deposit box).\ Avoid digital-only backups like screenshots or cloud storage — these can be hacked. **3. Protect your password** If you created an account in the Parallax client, you set a password for the keystore file.\ Back up this password alongside your seed phrase in a secure place. *** ## Common Security Mistakes to Avoid * ❌ Saving seed phrases in Google Drive, Dropbox, or email. * ❌ Taking screenshots of your wallet keys. * ❌ Sharing private keys in support chats or forums. * ❌ Downloading wallets from unofficial websites. *** ## Advanced Protection If you plan to hold significant amounts of Laxes: * Consider using a **hardware wallet**: [Parallax Wallet works with Ledger and Trezor](/parallax-wallet/hardware-wallets). * Run your own Parallax node instead of relying only on third parties. * Use a password manager for encrypting and storing backups digitally. *** ✨ By following these steps, you’ll keep your wallet — and your LAX coins — safe. # Setting up MetaMask Source: https://docs.parallaxprotocol.org/guides/wallets/metamask [MetaMask](https://metamask.io/) is one of the most popular crypto wallets for interacting with blockchains. By adding Parallax as a **custom network**, you can use MetaMask to create addresses, manage balances, and transfer Parallax coins (laxes). This guide will show you how to connect MetaMask to the Parallax network in a single click. *** ## Prerequisites * You have already installed and started the [Parallax client](/guides/client/setup). * MetaMask is installed in your browser (Chrome, Firefox, Brave, or Edge). * If not, download it from [metamask.io](https://metamask.io/download). *** ## Step-by-step Guide **1. Open the Parallax wallets page** Go to [parallaxprotocol.org/en/wallets](https://parallaxprotocol.org/en/wallets). This page works with MetaMask and any other EVM-compatible wallet. **2. Add Parallax to your wallet** Click the **Add to MetaMask** button. Your wallet will open a prompt with the Parallax network details pre-filled — review them and approve to add the network. **3. Switch to the Parallax network** Once approved, MetaMask will add **Parallax** to your list of networks. Select it from the network dropdown to start using Parallax. > [!TIP] > > Prefer to add the network by hand? Open MetaMask → **Settings** → **Networks** → **Add a network manually** and fill in: > > * **Network Name:** `Parallax` > * **New RPC URL:** `https://rpc.parallaxprotocol.org` > * **Chain ID:** `2110` > * **Currency Symbol:** `LAX` > * **Block Explorer URL:** `https://explorer.parallaxprotocol.org` *** ## Using MetaMask with Parallax Once connected, you can: * **Create new addresses**: MetaMask will generate them automatically. * **View balances**: See how much laxes each address holds. * **Send transactions**: Transfer laxes to other addresses on the Parallax network. *** ✨ That’s it! You’re now using MetaMask with Parallax to manage addresses and send Laxes. # Sending and Receiving Laxes Source: https://docs.parallaxprotocol.org/guides/wallets/send-and-reveive Beginner-friendly guide to transferring LAX coins using MetaMask and the Parallax network. Once you have a [Parallax account](/guides/wallets/accounts) set up, you can start moving coins. This guide will show you how to **send** and **receive** Laxes using MetaMask. *** ## What You Need * [MetaMask installed and configured for Parallax](/guides/wallets/metamask). * An account with some Laxes (either mined or received). * The recipient’s Parallax **address** (looks like `0x1234...abcd`). *** ## Receiving Laxes To receive LAX, simply share your **public address** with the sender: 1. Open MetaMask. 2. Copy your address from the top of the wallet screen (starts with `0x...`). 3. Send this address to the person transferring LAX to you. > [!NOTE] > > It’s safe to share your public address. Only your **private key/seed phrase** must be kept secret. Once the transaction is confirmed on the blockchain, the balance will appear in your wallet. *** ## Sending Laxes **1. Open MetaMask** Select your account in MetaMask and make sure you’re on the **Parallax network**. **2. Click Send** Press the **Send** button in MetaMask. **3. Enter the recipient address** Paste the address you want to send LAX to (starts with `0x...`). **4. Enter the amount** Choose how many **Laxes** you want to send. **5. Set the transaction fee (gas)** MetaMask will automatically suggest a transaction fee. Higher fees → faster confirmation. Lower fees → slower confirmation. **6. Confirm the transaction** Review the details and click **Confirm**.\ MetaMask will sign and broadcast the transaction. *** ## Tracking Your Transaction After sending: * MetaMask will show a **pending transaction** until it’s confirmed. * You can also paste your transaction hash into the [Parallax Explorer](https://explorer.parallaxprotocol.org) to see: * Status (pending/confirmed) * Block number * Gas used * Sender & recipient *** ## Tips & Safety * Always **double-check the recipient’s address** — blockchain transactions are irreversible. * Start with a **small test transfer** if you’re sending a large amount. * Keep an eye on your node’s sync status — if your client isn’t synced, balances may appear outdated. *** ✨ You now know how to send and receive LAX with MetaMask! Next, try exploring the [Parallax Block Explorer](/guides/wallets/explorer) to see your transactions directly on the chain. # API Source: https://docs.parallaxprotocol.org/hashwarp/api Hashwarp's JSON API, Prometheus metrics and JSON-RPC interface. Hashwarp serves the [dashboard](/hashwarp/dashboard), a JSON API, Prometheus metrics and a JSON-RPC interface on one TCP port, when started with `--api-bind`: | Option | Meaning | | - | - | | `--api-bind address:port` | Listen on this address and port, such as `127.0.0.1:21550` (this computer only) or `0.0.0.0:21550` (every network interface) | | `--api-token secret` | Require this secret: `Authorization: Bearer secret` on HTTP, `api_authorize` on JSON-RPC | | `--api-allow-control` | Allow clients to pause, resume and restart the GPUs and to change pools | Without `--api-allow-control` the API is read only. Control on an address other than `127.0.0.1` requires `--api-token`: anyone able to change pools could send your hashrate elsewhere. The API has no TLS: the token travels in clear text, so use a VPN or an SSH tunnel rather than exposing the port to the internet. Requests from web pages of other sites are refused. The `--api-port N` option of Hashwarp 1.x and ethminer still works, and listens on `127.0.0.1:N`, read only. *** ## HTTP API ### GET /api/v1/summary The rig's current state: ```bash theme={null} curl -s http://127.0.0.1:21550/api/v1/summary curl -s -H "Authorization: Bearer secret" http://127.0.0.1:21550/api/v1/summary ``` ```json theme={null} { "control": false, "miner": { "name": "hashwarp", "version": "2.0.0", "algorithm": "xhash", "uptime": 3600 }, "pool": { "connected": true, "host": "pool.example.com:3333", "url": "stratum+tcp://0xYourParallaxAddress.rig1:***@pool.example.com:3333", "difficulty": 4294967296.0, "epoch": 83, "block": -1, "switches": 1, "warning": "" }, "hashrate": { "now": 115480000.0, "60s": 115400000.0, "15m": 115210000.0, "effective": 112300000.0 }, "shares": { "accepted": 42, "rejected": 1, "failed": 0 }, "gpus": [ { "index": 0, "name": "NVIDIA GeForce RTX 4090", "pci": "01:00.0", "backend": "cu", "hashrate": { "now": 115480000.0, "60s": 115400000.0, "15m": 115210000.0 }, "shares": { "accepted": 42, "rejected": 1, "failed": 0 }, "paused": false, "pause_reason": "", "temperature": { "core": 65, "hotspot": 0, "memory": 0 }, "fan": 70, "power": 280.5, "power_limit": 450.0, "clocks": { "core": 2790, "memory": 10501 } } ] } ``` * Hashrates are in hashes per second. `effective` is what the accepted shares of the last 15 minutes are worth, 0 during the first 2 minutes. * `difficulty` is the expected number of hashes per share. * `block` is the height being mined, -1 when the pool doesn't send it. * `warning` is set when the pool finds most of the network's blocks (see [Pool Mining](/hashwarp/pool-mining#pools-with-the-majority)), empty otherwise. * `failed` counts solutions the CPU check found wrong, which weren't submitted. * Sensors are 0 when the GPU doesn't report them. `pause_reason` is empty while a GPU mines. * The pool password is never shown. ### GET /api/v1/rigs This rig (unless it runs with `--monitor`) and the [`--rig` rigs](/hashwarp/dashboard#all-your-rigs-in-one-dashboard), as the dashboard shows them: ```json theme={null} { "mining": true, "rigs": [ {"name": "rig1", "host": "", "local": true, "online": true, "error": "", "age": 0, "summary": {...}}, {"name": "rig2", "host": "10.0.0.12:21550", "online": true, "error": "", "age": 3, "summary": {...}}, {"name": "rig3", "host": "10.0.0.13:21550", "online": false, "error": "Connection refused", "age": 120, "summary": {...}} ] } ``` `summary` is the rig's last `/api/v1/summary`: kept while the rig is unreachable, absent if it never answered. `age` is the seconds since then (-1: never), and `error` why the last attempt failed. ### POST /api/v1/control Needs `--api-allow-control` (403 otherwise): ```bash theme={null} curl -s -X POST -H "Content-Type: application/json" -d '{"action":"pause","gpu":1}' http://127.0.0.1:21550/api/v1/control curl -s -X POST -H "Content-Type: application/json" -d '{"action":"resume"}' http://127.0.0.1:21550/api/v1/control curl -s -X POST -H "Content-Type: application/json" -d '{"action":"restart"}' http://127.0.0.1:21550/api/v1/control ``` `action` is `pause` or `resume` (one GPU with `gpu`, every GPU without), or `restart` (every GPU: the DAGs are rebuilt, the pool connection stays). The answer is `{"result":true}`, or 400 with the reason. ### Errors | Status | Meaning | | - | - | | 400 | Malformed request or JSON body | | 401 | Missing or wrong token | | 403 | Control not allowed, or a request from another site's web page | | 404 | Unknown path, or a path a `--monitor` instance doesn't serve | | 405 | Wrong method (GET or POST) | `GET /getstat1` serves the HTML statistics page of Hashwarp 1.x. *** ## Prometheus `GET /metrics` serves the metrics in Prometheus' text format: ```yaml theme={null} scrape_configs: - job_name: hashwarp static_configs: - targets: ["rig1:21550", "rig2:21550"] # with --api-token: # authorization: # credentials: secret ``` | Metric | Labels | Meaning | | - | - | - | | `hashwarp_hashrate` | `window` (`now`, `60s`, `15m`), `gpu`, `name` | Hashes per second, total (no `gpu` label) and per GPU | | `hashwarp_effective_hashrate` | | What the accepted shares are worth | | `hashwarp_shares_total` | `result` (`accepted`, `rejected`, `failed`), `gpu`, `name` | Shares | | `hashwarp_gpu_paused` | `gpu`, `name` | 1 when paused | | `hashwarp_gpu_temperature_celsius` | `gpu`, `name`, `sensor` (`core`, `hotspot`, `memory`) | Temperatures reported by the GPU | | `hashwarp_gpu_fan_percent`, `hashwarp_gpu_power_watts`, `hashwarp_gpu_power_limit_watts` | `gpu`, `name` | Fan, power draw and power limit | | `hashwarp_gpu_clock_mhz` | `gpu`, `name`, `clock` (`core`, `memory`) | Clocks | | `hashwarp_pool_connected` | `host` | 1 when connected | | `hashwarp_pool_difficulty_hashes` | | Expected hashes per share | | `hashwarp_pool_switches_total` | | Pool switches | | `hashwarp_epoch`, `hashwarp_block_height` | | XHash epoch and height being mined | | `hashwarp_uptime_seconds`, `hashwarp_info` | `version` | Uptime, and the version as a label | | `hashwarp_rig_up` | `rig` | With `--rig`: 1 when the rig's API answers | | `hashwarp_rig_hashrate`, `hashwarp_rig_power_watts` | `rig` | A rig's hashrate and GPU power draw | | `hashwarp_rig_shares_total` | `rig`, `result` | A rig's shares | *** ## JSON-RPC The JSON-RPC interface of ethminer and Hashwarp 1.x, which some monitoring tools use, is on the same port. Send JSON-RPC 2.0 requests, one per line: ```bash theme={null} echo '{"id":1,"jsonrpc":"2.0","method":"miner_ping"}' | nc 127.0.0.1 21550 ``` With `--api-token`, send `api_authorize` first on each connection: ```json theme={null} {"id":0,"jsonrpc":"2.0","method":"api_authorize","params":{"psw":"secret"}} ``` | Method | Params | Control | Result | | - | - | - | - | | `miner_ping` | | | `"pong"` | | `miner_getstat1` | | | Claymore-compatible array: version, uptime (minutes), "total kh/s;accepted;rejected", kh/s per GPU, unused, unused, "temperature;fan" pairs, pool, "failed;switches;0;0" | | `miner_getstatdetail` | | | Host, connection, mining and per GPU details | | `miner_getconnections` | | | Pools (`index`, `active`, `uri` with the password masked) | | `miner_getscramblerinfo` | | | Start nonce and segment width of each GPU | | `miner_setactiveconnection` | `{"index": n}` or `{"URI": "regex"}` | yes | Switch to that pool | | `miner_addconnection` | `{"uri": "stratum+tcp://..."}` | yes | Add a pool | | `miner_removeconnection` | `{"index": n}` | yes | Remove a pool (not the active one) | | `miner_pausegpu` | `{"index": n, "pause": true}` | yes | Pause or resume a GPU | | `miner_restart` | | yes | Restart the GPUs (the DAGs are rebuilt, the pool connection stays) | | `miner_reboot` | | yes | Run `reboot.sh` (`reboot.bat` on Windows) next to the executable, with `api_miner_reboot` as its argument | | `miner_shuffle` | | yes | Pick a new random start nonce | | `miner_setscramblerinfo` | `{"noncescrambler": n, "segmentwidth": w}` | yes | Set the start nonce and narrow the segments (10 to 63 bits) | | `miner_setverbosity` | `{"verbosity": n}` | yes | Debug categories (sum of 1 json, 2 per GPU, 32 connect, 64 switch, 128 submit, 256 flow) | Methods marked "yes" need `--api-allow-control`. Errors follow JSON-RPC 2.0: `{"error": {"code": ..., "message": ...}}`. A `--monitor` instance has no miner, and closes JSON-RPC connections. # Configuration Source: https://docs.parallaxprotocol.org/hashwarp/configuration Configure Hashwarp with the first-run wizard, a JSON configuration file or command line options. Hashwarp takes its settings from the command line, from a JSON configuration file, or both. Every option has the same name in both places. The [option reference](/hashwarp/options) lists them all. *** ## The first-run wizard Run `hashwarp` without options and without a configuration file, in a terminal. It asks: 1. Whether you mine on a pool or solo, on your own node. 2. On a pool: which one, from a list of known Parallax pools, or another pool's address and whether it uses TLS. Then your Parallax address and a name for the rig (the computer's name by default). 3. Solo: your node's URL (`http://127.0.0.1:8545` by default). 4. Whether to save the answers to `hashwarp.json`, and whether to start mining now. When the [Parallax status page](https://status.parallaxprotocol.org) can be reached, the pool list shows each pool's share of the network's blocks, and a pool with the majority comes last. On Windows, double-clicking `hashwarp.exe` starts the wizard too, and the window stays open when Hashwarp exits so you can read why. *** ## The configuration file Run without options, Hashwarp reads `hashwarp.json` from the folder of the executable, or else from the current folder. Run with options, it reads a configuration file only when given one with `--config`: ```bash theme={null} hashwarp --config /path/to/hashwarp.json ``` The keys are the option names without the leading dashes. The download has a commented example, `hashwarp.json.example`: ```json theme={null} // Hashwarp configuration. Comments are allowed. { // Pools in failover order: host:port, or URLs "pool": ["pool.example.com:3333"], // Your Parallax address and a name for this rig "wallet": "0x0000000000000000000000000000000000000000", "worker": "rig1", // Pause a GPU at 85°C and resume it at 70°C (lists hold one value per GPU) "temp-stop": [85], "temp-resume": [70], // Log to a file as well (rotated at 20 MB) "log-file": "hashwarp.log", // Dashboard and JSON API on http://127.0.0.1:21550 "api-bind": "127.0.0.1:21550" } ``` * An option that takes a value is a string or a number: `"worker": "rig1"`, `"retry-delay": 10`. * An option that takes a list is an array: `"pool": ["a.example.com:3333", "b.example.com:3333"]`. * A flag (an option without a value) is `true`: `"tls": true`. * A key Hashwarp doesn't know stops it with an error, so a typo doesn't go unnoticed. Options given on the command line override the file's: `hashwarp --config hashwarp.json --worker rig2` mines with the file's settings as `rig2`. ### Writing a configuration file `--save-config` writes the options you give to a file, then exits: ```bash theme={null} hashwarp --pool pool.example.com:3333 --wallet --worker rig1 --temp-stop 85 --save-config hashwarp.json ``` *** ## Lists per GPU Tuning, temperature and overclocking options take one value per GPU, separated by commas, in the order of `--gpu-id` (or of `hashwarp --list-devices` when all GPUs mine). A single value applies to every GPU: ```bash theme={null} hashwarp ... --temp-stop 85 # every GPU at 85°C hashwarp ... --temp-stop 85,80,80 # GPU 0 at 85°C, GPUs 1 and 2 at 80°C ``` In the configuration file these are arrays: `"temp-stop": [85, 80, 80]`. Overclocking options also accept `x` for a GPU to leave alone: `--oc-mem-offset 2000,x,1500`. *** ## Start scripts The download has start scripts to edit and double-click (`start.bat`, `start-solo.bat` on Windows) or run (`start.sh`, `start-solo.sh` on Linux). Each sets the pool or node and your address at its top, and passes on any extra options. *** ## Running as a service (Linux) To start Hashwarp with the computer and restart it after a [watchdog](/hashwarp/safety#the-watchdog) exit, run it as a systemd service. Save as `/etc/systemd/system/hashwarp.service`, with your paths: ```ini theme={null} [Unit] Description=Hashwarp Wants=network-online.target After=network-online.target [Service] ExecStart=/opt/hashwarp/hashwarp --config /opt/hashwarp/hashwarp.json --no-hotkeys --syslog Restart=on-failure RestartSec=10 [Install] WantedBy=multi-user.target ``` Then: ```bash theme={null} sudo systemctl daemon-reload sudo systemctl enable --now hashwarp journalctl -u hashwarp -f ``` `--syslog` leaves out the time, which journald adds, and marks each line's level so `journalctl -p warning` shows only the warnings and errors. The service runs as root, which [overclocking](/hashwarp/overclocking) needs; without overclocking, add `User=` with an ordinary user. *** ## Environment variables | Variable | Meaning | | - | - | | `HASHWARP_WALLET` | Your Parallax address, when `--wallet` isn't given | | `NO_COLOR` | Log without colors, like `--no-color` | | `SSL_CERT_FILE` | The CA certificates file for TLS pools, when Hashwarp can't find the system's | | `SSL_NOVERIFY` | Don't check TLS pools' certificates. Anyone between you and the pool could then steal your shares | # Dashboard Source: https://docs.parallaxprotocol.org/hashwarp/dashboard Watch one rig or all of them in Hashwarp's web dashboard. Hashwarp has a web dashboard: the hashrate, its averages and the effective hashrate, shares, and each GPU's temperatures, fan, power and efficiency, refreshed every 5 seconds. It can show your other rigs too. *** ## Turning it on ```bash theme={null} hashwarp ... --api-bind 127.0.0.1:21550 ``` Then open `http://127.0.0.1:21550` in a browser on the same computer. The dashboard follows your system's light or dark theme. | Option | Meaning | | - | - | | `--api-bind address:port` | Listen on this address and port. `127.0.0.1:21550` is this computer only; `0.0.0.0:21550` is every network interface, to open the dashboard from another computer | | `--api-token secret` | Require this secret. The dashboard asks for it once per browser session | | `--api-allow-control` | Add pause, resume and restart buttons (and allow the same through the [API](/hashwarp/api)) | > [!WARNING] > > The dashboard is plain HTTP: on `0.0.0.0` anyone on your network can open it, and a token travels unencrypted. Set `--api-token` there, and reach a rig over the internet through a VPN or an SSH tunnel rather than by opening the port. Control on an address other than `127.0.0.1` requires a token. *** ## All your rigs in one dashboard Give the rig whose dashboard you open the other rigs' addresses with `--rig`: ```bash theme={null} hashwarp ... --api-bind 0.0.0.0:21550 --rig rig2=10.0.0.12 --rig rig3=s3cret@10.0.0.13:21550 ``` Each other rig needs `--api-bind` on an address this rig can reach (`0.0.0.0:21550`, or its own network address), and Hashwarp 2.0 or later. This rig reads their status every 5 seconds, so your browser only talks to one rig and the other rigs' tokens stay on it. A rig is written `[name=][token@]host[:port]`: * `name`: shown on the dashboard. The host by default. * `token`: the rig's `--api-token`, if it has one. * `host:port`: its `--api-bind` address. Port 21550 by default. Repeat `--rig`, or separate rigs with commas. In the configuration file: `"rig": ["rig2=10.0.0.12", "rig3=s3cret@10.0.0.13"]`. The dashboard then starts with a table of the rigs, this one first under its worker name: status, hashrate and 15 minute average, shares, GPUs, the hottest GPU, power, efficiency, pool and uptime, with the totals. Click a rig to see its GPUs. A rig's status shows what needs a look: * **unreachable**, with the reason and when it was last seen; * **not connected** to its pool; * **paused** GPUs; * **hot**: a GPU at 85°C or more; * **rejected shares**: more than 5% of its shares; * **majority pool**: its pool finds most of the network's blocks. Hashwarp also logs when a rig goes offline and comes back: ``` 09:48:18 WARN rigs rig3 (10.0.0.13:21550) unreachable: no answer in 4.0 s ``` *** ## A dashboard without mining: --monitor `--monitor` runs Hashwarp only for this view, on a computer that doesn't mine, such as a home server or a laptop: ```bash theme={null} hashwarp --monitor --api-bind 0.0.0.0:21550 --rig rig1=10.0.0.11,rig2=10.0.0.12,rig3=10.0.0.13 ``` It needs no GPU and no GPU driver. *** ## Prometheus and Grafana For history and alerts, Prometheus can scrape every rig's metrics; see [API](/hashwarp/api#prometheus). With `--rig`, one rig's metrics also cover the others' status, hashrate, shares and power. # Mining with your GPU Source: https://docs.parallaxprotocol.org/hashwarp/getting-started How to mine Parallax with your GPU using Hashwarp, the official XHash miner. [Hashwarp](https://github.com/ParallaxProtocol/hashwarp) is the official GPU miner for Parallax's [XHash](/protocol/foundational-topics/consensus/algorithms/xhash) Proof-of-Work. It mines on **NVIDIA** GPUs (CUDA) and **AMD** and other GPUs (OpenCL), on a mining pool or solo on your own node. It has no dev fee. Besides mining, Hashwarp: * Sets itself up: run it without options and a short wizard asks how you want to mine. * Protects your hardware: temperature limits per GPU, a shutdown temperature, and a watchdog that restarts a GPU when it fails. Every solution is checked before it is submitted. * Tunes your GPUs: memory and core clocks, power limits and fans per GPU, and `--oc-tune`, which finds the best settings for each one. * Shows what it does: a web dashboard of one rig or all of them, a JSON API and Prometheus metrics. * Warns you when your pool finds most of the network's blocks, which puts the network at risk. * Runs on HiveOS and mmpOS with ready-made packages. *** ## Prerequisites * An **NVIDIA** GPU (driver 525 or newer) or an **AMD** GPU (AMD driver with OpenCL: Adrenalin on Windows, ROCm on Linux), with enough memory for the XHash DAG: about 1.7 GB in late 2026, growing slowly with each epoch. * **Windows** 10 or newer, or **Linux** with glibc 2.28 or newer (Ubuntu 20.04, Debian 10, RHEL 8 and later). Everything else Hashwarp needs comes in the download. * A Parallax address to receive rewards, or your own [Parallax client](/guides/client/setup) to mine solo. *** ## Step-by-step Guide **1. Download Hashwarp** Download the archive for your operating system from the [Hashwarp releases](https://github.com/ParallaxProtocol/hashwarp/releases) and extract it. It holds the `hashwarp` executable, a sample configuration (`hashwarp.json.example`) and start scripts. On HiveOS or mmpOS, use the ready-made package instead: see [HiveOS & mmpOS](/hashwarp/rig-os). **2. Start it** Run `hashwarp` without options. The first time, it asks whether you want to mine on a pool or solo, which pool, your address and a name for the rig, saves the answers in `hashwarp.json` and starts mining. Next time it starts with that configuration. Or give the options on the command line. On a pool: ```bash theme={null} hashwarp --pool : --wallet --worker rig1 ``` Replace `:` with the pool's address and `` with your Parallax address. The worker name tells your rigs apart on the pool's dashboard. See [Mining on a Pool](/hashwarp/pool-mining) to choose a pool, or [Solo Mining](/hashwarp/solo-mining) to mine on your own node. **3. Check that it mines** Hashwarp prints the hashrate every 10 seconds and a line for each share the pool accepts: ``` 05:57:14 INFO share ✔ accepted gpu0 · diff 8.59 GH · 364 ms · A20 R1 05:57:20 INFO miner 115.42 MH/s · 60s 115.43 · 15m 116.18 · eff 133.62 · A20 R1 · 71°C · fan 53% · 377 W · 306 kH/J ``` The line shows the current hashrate and its 1 and 15 minute averages, the effective hashrate (what the pool credits you), the accepted (`A`) and rejected (`R`) shares, then the temperature, fan, power and efficiency. Press `s` for a table per GPU, or `h` for the other keys. [Output & Logs](/hashwarp/output-and-logs) explains every part. > [!TIP] > > Run `hashwarp --selftest` once after installing, and after changing drivers or overclocking: it mines offline for up to 30 seconds, checks every GPU's results on the CPU and says PASS or FAIL for each GPU. *** ## Next steps > **[Configuration](/hashwarp/configuration)** > > The configuration file, the wizard and how options combine. > **[Overclocking](/hashwarp/overclocking)** > > Clocks, power and fans per GPU, and `--oc-tune` to find the best settings. > **[Dashboard](/hashwarp/dashboard)** > > A web dashboard of this rig, or of all your rigs. > **[Safety](/hashwarp/safety)** > > Temperature limits, the watchdog and exit codes. # GPUs & Tuning Source: https://docs.parallaxprotocol.org/hashwarp/gpus-and-tuning Choose the GPUs Hashwarp mines on, check them, benchmark them and tune their kernels. Hashwarp finds your GPUs at start and mines on all of them, NVIDIA GPUs with CUDA and the others with OpenCL. Its defaults suit most GPUs: start with [overclocking](/hashwarp/overclocking), which matters much more for XHash than the kernel settings below. *** ## Listing the GPUs ```bash theme={null} hashwarp --list-devices ``` ``` Id Pci Id Backend Name Memory Details -- ------ ------- ---- ------ ------- 0 01:00.0 cu,cl NVIDIA GeForce RTX 4090 23.59 GB SM 8.9, NVIDIA CUDA OpenCL 3.0 CUDA ``` `Id` is the number the other options use for a GPU, and `Backend` what Hashwarp can mine on it with: `cu` (CUDA) and `cl` (OpenCL). The log names each GPU by that number: `gpu0`, `gpu1` ... *** ## Choosing GPUs | Option | Meaning | | - | - | | `--gpu-id 0,2` | Mine on these GPUs only | | `--backend` | `auto` (CUDA on NVIDIA GPUs, OpenCL on the others), `cuda` or `opencl`. `-U` and `-G` are shortcuts for `cuda` and `opencl` | | `--disable-gpu-nvidia`, `--disable-gpu-amd`, `--disable-gpu-intel` | Skip the GPUs of a vendor | While mining, press a GPU's number (`0` to `9`) to pause or resume it, or `p` and `r` for all of them. *** ## GPU memory Each GPU holds the XHash DAG, which grows by 8 MB every epoch (720 blocks, about 5 days): around 1.7 GB in late 2026, 2 GB around mid 2027. Hashwarp builds it on the GPU when mining starts and at each new epoch, which takes under a second on recent GPUs: ``` 06:20:34 INFO gpu0 DAG epoch 84 (1.66 GB) built in 403 ms · 19.54 GB free ``` A GPU without enough free memory is paused until the next epoch with a warning (`Epoch N needs ...`). On rigs whose CPU or power supply struggles when every GPU builds its DAG at once, `--dag-load-mode 1` builds them one after the other. *** ## Checking the GPUs: --selftest ```bash theme={null} hashwarp --selftest ``` The self-test mines offline for up to 30 seconds (`--selftest 60` for longer), checks every result on the CPU and ends with a verdict per GPU: ``` 06:48:44 INFO gpu0 ✔ PASS NVIDIA GeForce RTX 4090 · 35 solutions verified · 82.14 MH/s ``` It exits with code 0 when every GPU passes and 1 otherwise, so scripts can use it. Run it after installing Hashwarp, updating drivers or changing an overclock. Its hashrate includes the start, so it reads lower than while mining. While mining, Hashwarp checks every solution on the CPU before sending it too. A wrong one isn't submitted: it counts as `F` (failed) in the share counts and is logged as `Wrong result, lower the overclock if it happens often`. `--noeval` turns the check off, which isn't recommended. *** ## Benchmarking ```bash theme={null} hashwarp --benchmark 60500 ``` mines offline on the DAG of block 60500 and prints the hashrate as when mining, without a pool. Stop it with `q` or Ctrl+C; it prints the highest and mean hashrate. Use a current block number, so the DAG has its current size. *** ## Kernel tuning These take [one value per GPU](/hashwarp/configuration#lists-per-gpu), or one for all. The defaults are right for most GPUs; change one at a time, and compare with `--benchmark`. | Option | Default | Meaning | | - | - | - | | `--cuda-kernel` | `auto` | CUDA search kernel. `0` is best when memory bandwidth limits the hashrate (nearly every GPU), `1` when compute does. `auto` times both on each GPU at start and keeps the faster | | `--cuda-grid-size` | 8192 | CUDA blocks per kernel launch | | `--cuda-block-size` | 128 | CUDA threads per block: 32, 64, 128 or 256 | | `--cuda-streams` | 2 | CUDA kernels in flight | | `--cuda-schedule` | `sync` | How the CPU waits for CUDA (all GPUs): `spin` lowers the latency a little at the cost of a CPU core per GPU | | `--cl-global-work` | 65536 | OpenCL global work size multiplier | | `--cl-local-work` | 128 | OpenCL work group size: 64, 128 or 256 | | `--cl-noexit` | off | OpenCL: don't use the fast exit kernel (all GPUs) | At start Hashwarp logs which CUDA kernel it chose, with both kernels' hashrates: ``` 06:20:36 INFO gpu0 Kernel standard (standard 115.05 MH/s, dedup 112.26 MH/s) ``` On an RTX 4090 at stock clocks Hashwarp mines at 115.5 MH/s, about 94% of the GPU's memory bandwidth: XHash reads 8 KB of the DAG per hash, so memory bandwidth limits it on nearly every GPU. That is why the memory clock matters most: see [Overclocking](/hashwarp/overclocking). # Option Reference Source: https://docs.parallaxprotocol.org/hashwarp/options Every Hashwarp command line option and configuration key, with its values and default. Every option of Hashwarp 2.0, as `hashwarp --help-all` lists them. In the [configuration file](/hashwarp/configuration#the-configuration-file) the key is the long name without the dashes: `--temp-stop 85` is `"temp-stop": [85]`. * **Value**: what the option takes. A **comma separated list** takes several values: `--pool a.example.com:3333,b.example.com:3333`. Tuning, temperature and overclocking lists hold [one value per GPU](/hashwarp/configuration#lists-per-gpu), or one for all. * Options without a value are flags: give them to turn the feature on. * Several names on one row are the same option. The second ones are the names of Hashwarp 1.x and ethminer, kept so that older command lines keep working. ## Pool | Option | Value | Default | Description | | - | - | - | - | | `-o` `-P` `--pool` | text, comma separated list | | Pool as host:port or URL (stratum+tcp\://, stratum+ssl://, http\:// for getwork). Repeat or comma separate for failover pools | | `-u` `--wallet` | text (or `HASHWARP_WALLET`) | | Your Parallax address (0x...) | | `-w` `--worker` | text | | Worker (rig) name shown by the pool | | `-p` `--password` | text | `x` | Pool password | | `--tls` | | | Use TLS for pools given as host:port | | `--esm` | `auto`, `0`, `1`, `2`, `3` | `auto` | Stratum flavour: auto, 0 = EthProxy, 1/2 = EthereumStratum/1.0.0 (NiceHash), 3 = EthereumStratum/2.0.0 | | `--solo` | text | | Solo mine on a Parallax node (default [http://127.0.0.1:8545](http://127.0.0.1:8545); ws\://host:8546 to have the node push new work). Rewards go to the node's --miner.coinbase | | `-R` `--report-hashrate` `--report-hr` | | | Report the hashrate to the pool or node | | `--pool-retries` `--farm-retries` | number, 0 to 99999 | `3` | Connection attempts before switching to the next pool (a single pool is retried forever) | | `--retry-delay` | number, 1 to 999 | `5` | Seconds before reconnecting, doubles on each failed attempt (up to 120) | | `--no-pool-check` | | | Don't warn when the pool finds most of the network's blocks (hashwarp reads the pools' shares from status.parallaxprotocol.org every 10 minutes) | | `--failover-timeout` | number, 0 to 999 | `0` | Minutes on a failover pool before trying the first one again (0 = never) | | `--work-timeout` | number, 600 to 99999 | `7200` | Reconnect if no new work arrives for this many seconds | | `--response-timeout` | number, 2 to 999 | `2` | Reconnect if the pool doesn't answer within this many seconds | | `--getwork-interval` `--farm-recheck` | number, 100 to 99999 | `1000` | Milliseconds between getwork polls (solo / http pools) | ## Devices | Option | Value | Default | Description | | - | - | - | - | | `--list-devices` | | | List the GPUs and exit | | `--backend` | `auto`, `cuda`, `opencl` | `auto` | auto (CUDA on NVIDIA, OpenCL on the others), cuda or opencl | | `-U` `--cuda` | | | Same as --backend cuda | | `-G` `--opencl` | | | Same as --backend opencl | | `--gpu-id` `--devices` | numbers, comma separated | | GPUs to mine on, as listed by --list-devices (default: all) | | `--disable-gpu-nvidia` | | | Don't mine on NVIDIA GPUs | | `--disable-gpu-amd` | | | Don't mine on AMD GPUs | | `--disable-gpu-intel` | | | Don't mine on Intel GPUs | ## Tuning Per GPU lists: one value per GPU, or one for all. | Option | Value | Default | Description | | - | - | - | - | | `--cuda-grid-size` `--cu-grid-size` | numbers, comma separated | | CUDA grid size \[1 .. 131072] (default 8192) | | `--cuda-block-size` `--cu-block-size` | numbers, comma separated | | CUDA block size: 32, 64, 128 or 256 (default 128) | | `--cuda-streams` `--cu-streams` | numbers, comma separated | | CUDA streams \[1 .. 99] (default 2) | | `--cuda-schedule` `--cu-schedule` | `auto`, `spin`, `yield`, `sync` | `sync` | How the CPU waits for CUDA kernels: auto, spin, yield or sync (all GPUs) | | `--cuda-kernel` | `auto`, `0`, `1` | `auto` | CUDA search kernel: auto (time both on each GPU at start), 0 (best when memory bandwidth limits the hashrate) or 1 (best when compute does) | | `--cl-global-work` | numbers, comma separated | | OpenCL global work size multiplier (default 65536) | | `--cl-local-work` | numbers, comma separated | | OpenCL work group size: 64, 128 or 256 (default 128) | | `--cl-noexit` | | | OpenCL: don't use the fast exit kernel (all GPUs) | | `-L` `--dag-load-mode` | number, 0 to 1 | `0` | 0 = build DAGs on all GPUs at once, 1 = one GPU after the other | | `--noeval` | | | Submit solutions without checking them on the CPU first (not recommended) | | `--ergodicity` | number, 0 to 2 | `0` | Pick a new random nonce range 0 = once, 1 = per connection, 2 = per job | ## Hardware | Option | Value | Default | Description | | - | - | - | - | | `--no-hwmon` | | | Don't read temperatures, fans and power | | `--temp-stop` `--tstop` | numbers, comma separated | | Pause a GPU at this core temperature in C \[30 .. 100] (default off) | | `--temp-resume` `--tstart` | numbers, comma separated | | Resume a GPU paused by --temp-stop at this temperature (default stop - 15) | | `--mem-temp-stop` | numbers, comma separated | | Pause a GPU at this memory temperature in C (hotspot on GPUs without memory sensor) \[40 .. 120] (default off) | | `--mem-temp-resume` | numbers, comma separated | | Resume a GPU paused by --mem-temp-stop at this temperature (default stop - 10) | | `--shutdown-temp` | number, 0 to 125 | `0` | Stop hashwarp (exit code 6) if any GPU temperature reaches this in C (default off) | | `--watchdog-timeout` | number, 0 to 3600 | `120` | Seconds a GPU may give no sign of life before hashwarp exits (code 5) so it can be restarted (0 = no watchdog) | | `--watchdog-restarts` | number, 0 to 100 | `3` | Times per hour a failed GPU is restarted before hashwarp exits (code 5) | | `--watchdog-script` | text | | Run this program (with the GPU index and the reason) when the watchdog gives up, e.g. to reboot the rig | ## Overclocking Per GPU lists, x leaves a GPU alone; needs root or administrator rights. | Option | Value | Default | Description | | - | - | - | - | | `--oc-profile` | text, comma separated list | | Overclocking profile: stock, efficient (the tuned core clock, or 80% power), tuned (the --oc-tune results) or one of oc-profiles in the configuration file | | `--oc-core-clock` | text, comma separated list | | Core clock in MHz: locked on NVIDIA, highest state on AMD (0 = default) | | `--oc-core-offset` | text, comma separated list | | Core clock offset in MHz (NVIDIA) | | `--oc-mem-offset` | text, comma separated list | | Memory clock offset in MHz (NVIDIA), in the units of nvidia-settings and HiveOS: twice MSI Afterburner's | | `--oc-mem-clock` | text, comma separated list | | Memory clock in MHz of the highest state (AMD, 0 = default) | | `--oc-power` | text, comma separated list | | Power limit in W, or in percent of the default (75%) | | `--oc-fan` | text, comma separated list | | Fan speed in percent, or auto | | `--oc-profiles` | text | | Named overclocking profiles, a JSON object (the oc-profiles object of the configuration file) | | `--oc-tune` `--oc-tune=core` | | `all` | Find the best memory clock and the most efficient core clock of each GPU, save them for --oc-profile tuned and exit. --oc-tune=core only tunes the core clock, which is safe | | `--oc-reset` | | | Set the stock clocks, power limits and fan control of the GPUs and exit, e.g. after hashwarp was killed while overclocking | | `--oc-tune-file` | text | | Tuning results (default hashwarp-oc.json next to the configuration file) | ## Logging and display | Option | Value | Default | Description | | - | - | - | - | | `--log-file` | text | | Also write the log to this file | | `--log-max-size` | number | `20` | Rotate the log file when it reaches this many MB (0 = never) | | `--log-keep` | number, 0 to 99 | `3` | Rotated log files to keep | | `--log-level` | `error`, `warn`, `info`, `debug`, `trace` | `info` | error, warn, info, debug or trace | | `--log-format` | `text`, `json` | `text` | text, or json: one JSON object per line, on the console and in the log file | | `--log-debug` | `json`, `per-gpu`, `connect`, `switch`, `submit`, `flow`, comma separated list | | Extra debug output (implies --log-level debug): json, per-gpu, connect, switch, submit, flow | | `--no-color` `--nocolor` | | | Don't use colors | | `--syslog` | | | Log without timestamps and colors (for syslog) | | `--stdout` | | | Log to stdout instead of stderr | | `--display-interval` | number, 1 to 1800 | `10` | Seconds between hashrate lines | | `--no-hotkeys` | | | Don't read keys from the terminal (h for help) | | `--stats-interval` | number, 0 to 86400 | `60` | Seconds between per GPU statistics tables (0 = never) | ## API | Option | Value | Default | Description | | - | - | - | - | | `--api-bind` | text | | Serve the API on address:port, e.g. 127.0.0.1:21550 (default off) | | `--api-token` `--api-password` | text | | Secret required by the API (required to allow control on non loopback addresses) | | `--api-allow-control` | | | Allow API clients to pause, restart and change pools | | `--rig` | text, comma separated list | | Show another rig on the dashboard: \[name=]\[token@]host\[:port] (port 21550 by default). Repeat it, or separate rigs with commas | | `--monitor` | | | Don't mine: only serve the dashboard of the --rig rigs (needs --api-bind) | ## Other | Option | Value | Default | Description | | - | - | - | - | | `-c` `--config` | | | Read options from a JSON file (keys are option names) | | `--save-config` | text | | Write the options given to this JSON file and exit | | `-M` `-Z` `--benchmark` `--simulation` | number | | Benchmark offline on the DAG of this block number | | `--selftest` | number | `30` | Check every GPU's results on the CPU offline for up to this many seconds (default 30) and exit with 0 if all are correct | | `--exit` | | | Exit when a GPU fails instead of carrying on | # Output & Logs Source: https://docs.parallaxprotocol.org/hashwarp/output-and-logs Read Hashwarp's output, use its keys, and log to a file, to journald or as JSON lines. ## Reading the output Each line has the time, the level, the source and the message: ``` 05:35:49 INFO pool Connected to prlx.coolpool.top [185.246.66.177:3003] 05:35:49 INFO pool Protocol EthereumStratum/1.0.0 05:35:49 INFO pool Authorized as 0xYourParallaxAddress.rig1 05:35:49 INFO gpu0 NVIDIA GeForce RTX 4090 · PCI 01:00.0 · compute 8.9 · 23.59 GB 05:35:50 INFO gpu0 DAG epoch 83 (1.65 GB) built in 356 ms · 19.87 GB free 05:35:52 INFO gpu0 Kernel standard (standard 115.32 MH/s, dedup 112.62 MH/s) 05:38:10 INFO share ✔ accepted gpu0 · diff 8.59 GH · 357 ms · A1 05:52:00 INFO miner 116.24 MH/s · 60s 116.25 · 15m 115.44 · eff 153.96 · A13 R1 · 71°C · fan 53% · 378 W · 308 kH/J ``` The level is `INFO`, `WARN` or `ERROR` (and `DEBUG` with [`--log-level debug`](#options)). The source says what the line is about: | Source | About | | - | - | | `gpu0`, `gpu1` ... | A GPU, numbered as in `--list-devices`; each in its own color | | `pool` | The pool connection (`node` when solo mining) | | `share`, `block` | Accepted and rejected shares, blocks found when solo mining | | `miner` | Hashwarp itself: hashrate, start and stop | | `api`, `rigs` | The [dashboard and API](/hashwarp/dashboard), and the other rigs it shows | | `hwmon`, `oc`, `tune` | Sensors, [overclocking](/hashwarp/overclocking) and `--oc-tune` | ### The hashrate line Every 10 seconds (`--display-interval`) Hashwarp prints: * the current hashrate, then its 1 minute (`60s`) and 15 minute (`15m`) averages; * `eff`: the effective hashrate, what the accepted shares of the last 15 minutes are worth, from 2 minutes after the start. It follows the pool's view of your hashrate, luck included, so it swings above and below the real one; * the shares: accepted (`A`), rejected by the pool (`R`) and failed (`F`), which are wrong results Hashwarp caught before sending them; * the temperature, fan, power draw and efficiency in kH/J (thousands of hashes per joule). With several GPUs, the totals come on the `miner` line, followed by a line per GPU: ``` 12:00:10 INFO miner 230.96 MH/s · 60s 230.80 · 15m 230.42 · eff 224.60 · A84 R1 12:00:10 INFO gpu0 115.48 MH/s · 65°C · fan 70% · 280 W · 412 kH/J 12:00:10 INFO gpu1 115.48 MH/s · 66°C · fan 72% · 281 W · 411 kH/J ``` ### The statistics table Every 60 seconds (`--stats-interval`, `0` to turn it off), and when you press `s`, Hashwarp prints a table per GPU with the clocks as well, then the pool, its difficulty and the blocks left before the next epoch: ``` 05:55:50 INFO miner GPU Name MH/s 60s 15m Shares Temp Fan Power kH/J Clocks 05:55:50 INFO miner gpu0 NVIDIA GeForce RTX 4090 116.26 116.26 116.15 A17 R1 71°C 53% 378W 307 2775/10251 05:55:50 INFO miner Pool prlx.coolpool.top:3003 diff 8.59 GH, effective 152.71 MH/s, up 0:16, epoch 83 ``` ### Keys While Hashwarp runs in a terminal, these keys work (`--no-hotkeys` turns them off): | Key | Action | | - | - | | `h` | Help: list the keys | | `s` | The statistics table | | `p` / `r` | Pause / resume every GPU | | `0` to `9` | Pause or resume that GPU | | `c` | The connection: pool, user, difficulty, epoch and pool switches | | `l` | Debug output on or off | | `q` | Quit | ### Without UTF-8 On a console without UTF-8 (on Linux, `LANG` not set to a UTF-8 locale, as in some services and containers), the symbols are replaced by ASCII: `|` for `·`, `+` for `✔`, `x` for `✘`, and `C` for `°C`. *** ## Logging to a file ```bash theme={null} hashwarp ... --log-file hashwarp.log ``` writes every line to the file as well, without colors and with the full date and time (ISO 8601, with the time zone). The file is rotated when it reaches 20 MB, keeping 3 old ones (`hashwarp.log.1` ...). ## Options | Option | Meaning | | - | - | | `--log-file` | Also write the log to this file | | `--log-max-size 20`, `--log-keep 3` | Rotate the file at 20 MB, keep 3 old ones (`--log-max-size 0`: never) | | `--log-level` | `error`, `warn`, `info` (default), `debug` or `trace`. Debug lines also name the thread | | `--log-format json` | One JSON object per line, on the console and in the log file (see below) | | `--log-debug` | Extra debug output: `json` (the pool's messages), `per-gpu` (solutions per GPU) | | `--no-color` | No colors | | `--syslog` | For syslog and journald: no time, and each line's level as a syslog priority (`<4>` for warnings ...) | | `--stdout` | Log to stdout instead of stderr | | `--display-interval`, `--stats-interval` | Seconds between hashrate lines (10) and statistics tables (60) | *** ## JSON lines `--log-format json` writes each line as a JSON object with `time`, `level`, `source` and `msg` (the text of the line, without colors), for log collectors and scripts: ```json theme={null} {"time":"2026-10-19T05:38:10.512-03:00","level":"info","source":"share","msg":"✔ accepted gpu0 · diff 8.59 GH · 357 ms · A1","event":"share","result":"accepted","gpu":0,"difficulty":8589934592,"ms":357} ``` The lines worth reading by a program also have an `event` and its values: | `event` | Values | | - | - | | `connected`, `disconnected` | `host` | | `difficulty` | `epoch`, `difficulty` (hashes per share) | | `job` (debug level) | `block` | | `share` | `result` (`accepted`, `stale` or `rejected`), `gpu`, `difficulty`, `ms`, `reason` | | `block` | `gpu`, `height`, `ms` | | `hashrate` | `hashrate`, `hashrate60`, `hashrate900` (H/s), `accepted`, `rejected`, `failed`, `effective` | | `gpu` | `gpu`, `hashrate`, `paused`, `temp` (°C), `fan` (%), `power` (W) | | `pool_majority` | `pool`, `share` (0 to 1): your pool has the majority of the blocks | | `tune_step`, `tuned` | `--oc-tune`'s measurements and results | With `--log-level debug` each line also has the `thread`. For the current state rather than a stream of events, the [JSON API](/hashwarp/api) is easier to read. # Overclocking Source: https://docs.parallaxprotocol.org/hashwarp/overclocking Set the clocks, power limits and fans of your GPUs with Hashwarp, and let --oc-tune find the best settings. XHash is limited by the GPU's memory: a higher memory clock raises the hashrate, while the core clock can usually go well below its default without costing any hashrate, which saves power. Hashwarp sets both itself, on **NVIDIA** GPUs (Linux and Windows) and **AMD** GPUs (Linux), and puts each GPU back to its previous settings when it exits. > [!NOTE] > > Changing clocks needs root on Linux (`sudo hashwarp ...`) or administrator rights on Windows. Rig operating systems that overclock themselves, such as HiveOS and mmpOS, don't need these options: set the overclock there. *** ## Finding the settings: --oc-tune ```bash theme={null} sudo hashwarp --oc-tune # memory and core clocks, 10 to 20 minutes sudo hashwarp --oc-tune=core # only the core clock, which is safe, about 5 minutes ``` The tuner mines offline at an easy difficulty and checks every result on the CPU: 1. It raises the memory clock step by step, as long as the results stay correct and the hashrate grows. GDDR6X memory corrects its own errors, which shows as a hashrate that falls again rather than as wrong results; the tuner watches for both. It keeps the best memory clock, or the one below it when that costs almost nothing. 2. It lowers the core clock as far as the hashrate stays within 1%. 3. It mines a while longer with both to confirm them, and backs off a step if they fail. It logs each step and the result per GPU, then saves the results to `hashwarp-oc.json` next to the configuration file (`--oc-tune-file` to change it). Mine with them using the `tuned` profile: ```bash theme={null} sudo hashwarp --oc-profile tuned --pool ... --wallet ... ``` > [!WARNING] > > Tune with the GPUs otherwise idle. A desktop, a video or a game on the same GPU makes the hashrate unsteady: the tuner notices and measures longer, but its results are less precise. * `--oc-tune=core` keeps a memory clock tuned before, and only tunes the core clock. * A memory clock that is too high can hang a GPU. The [watchdog](/hashwarp/safety#the-watchdog) then exits Hashwarp, which restores the settings. * Run `--oc-tune` again after changing drivers or cooling, or swapping GPUs: results are kept per GPU. *** ## Profiles `--oc-profile` takes one profile per GPU, or one for all: | Profile | Settings | | - | - | | `tuned` | The GPU's `--oc-tune` results | | `efficient` | The tuned core clock, never the memory. On GPUs that weren't tuned, 80% of the default power limit | | `stock` | Default clocks, power limit and fan control | Your own profiles go into the [configuration file](/hashwarp/configuration#the-configuration-file), and can be chosen per GPU: ```json theme={null} { "oc-profile": ["fast", "fast", "quiet"], "oc-profiles": { "fast": {"core-clock": 1650, "mem-offset": 2500, "power": 320}, "quiet": {"core-clock": 1400, "power": "70%", "fan": 60} } } ``` A profile's keys are the settings below without the `oc-` prefix. *** ## Settings These take [one value per GPU](/hashwarp/configuration#lists-per-gpu), or one for all; `x` leaves a GPU alone, for example `--oc-mem-offset 2000,x,1500`. They override a profile's values. | Option | Meaning | | - | - | | `--oc-core-clock` | Core clock in MHz: locked on NVIDIA, highest state on AMD. `0`: default | | `--oc-core-offset` | Core clock offset in MHz (NVIDIA) | | `--oc-mem-offset` | Memory clock offset in MHz (NVIDIA), in the units of nvidia-settings and HiveOS, which are twice MSI Afterburner's: Afterburner's +1000 is +2000 | | `--oc-mem-clock` | Memory clock of the highest state in MHz (AMD). `0`: default | | `--oc-power` | Power limit in W, or in percent of the default (`75%`) | | `--oc-fan` | Fan speed in percent, or `auto` | Each GPU's settings are logged when mining starts: ``` 06:12:01 INFO gpu0 Overclock core 1650 MHz, mem +2500 MHz, power 320 W ``` ### AMD GPUs On Linux, AMD GPUs only accept clock changes with overdrive enabled: add `amdgpu.ppfeaturemask=0xffffffff` to the kernel command line and reboot. AMD GPUs take a memory clock (`--oc-mem-clock`) rather than an offset. Overclocking AMD GPUs on Windows isn't supported: use AMD Adrenalin. *** ## Restoring the stock settings Hashwarp restores each GPU's previous settings when it exits, also after a watchdog exit. If it is killed (`kill -9`, a power loss), it can't: reboot, or set the stock settings with ```bash theme={null} sudo hashwarp --oc-reset ``` # Mining on a Pool Source: https://docs.parallaxprotocol.org/hashwarp/pool-mining How to mine Parallax on a pool with Hashwarp: choosing a pool, connecting, TLS and failover pools. Mining on a pool combines your hashrate with other miners'. Instead of waiting to find a block on your own, the pool finds blocks together and shares the rewards among its miners, which makes earnings **regular and predictable**. To keep the whole block reward for yourself instead, see [Solo Mining](/hashwarp/solo-mining). *** ## Step-by-step Guide **1. Choose a pool** Parallax pools are listed on [miningpoolstats](https://miningpoolstats.stream/parallax). These take your Parallax address as the user name (checked in October 2026): | Pool | Scheme, fee | Address | TLS address | | - | - | - | - | | [coolpool.top](https://coolpool.top/pool/prlx) | PPLNS 1% | `prlx.coolpool.top:3003` | | | [coolpool.top](https://coolpool.top/pool/prlxsolo) | SOLO 1.5% | `prlx.coolpool.top:3002` | | | [cedric-crispin.com](https://parallax.cedric-crispin.com) | PPLNS 0.1% | `parallax.cedric-crispin.com:4554` | | | [pool.ion.cool](https://pool.ion.cool/parallax) | PPLNS 1% | `pool.ion.cool:33350` | | | [rplant.xyz](https://pool.rplant.xyz) | PROP 1% (solo 2%) | `stratum-.rplant.xyz:7159` | `stratum-.rplant.xyz:17159` | rplant's regions are `eu`, `na`, `asia` and `ru`; coolpool also has `eu.`, `us.` and `asia.` hosts. [gtpool.io](https://gtpool.io) takes its own account ID instead of an address. Hashwarp's first-run wizard offers these pools too. > [!WARNING] > > Prefer a pool that finds less than half of the network's blocks. A pool with the majority can reverse payments and block transactions, which puts the coin you mine at risk. The [Parallax status page](https://status.parallaxprotocol.org) shows each pool's share, and Hashwarp [warns you](#pools-with-the-majority) when your pool has the majority. **2. Start Hashwarp** ```bash theme={null} hashwarp --pool : --wallet --worker rig1 ``` Replace `:` with the pool's address and `` with your Parallax address. * Add `--tls` for a TLS port. * The worker name (`rig1`) tells your rigs apart on the pool's dashboard. * No password is required for most pools. Or run `hashwarp` without options and answer the wizard's questions: see [Configuration](/hashwarp/configuration). **3. Check that shares are accepted** Each share the pool accepts is logged: ``` 16:12:42 INFO share ✔ accepted gpu0 · diff 8.59 GH · 364 ms · A42 ``` The line shows the GPU that found it, the share's difficulty, the time the pool took to answer and the shares so far. A rejected share is a warning with the pool's reason. **4. Check the pool's dashboard** Most pools have a web dashboard where you enter your address to see your hashrate as the pool sees it, accepted shares, pending rewards and payouts. It can take a few minutes to show a new rig. *** ## Options | Option | Meaning | | - | - | | `--pool` | `host:port`, or a URL (see below). Repeat it or separate pools with commas: the next pool is used when one fails | | `--wallet` | Your Parallax address. Also read from the `HASHWARP_WALLET` environment variable | | `--worker` | The rig's name on the pool's dashboard | | `--password` | Pool password, `x` by default | | `--tls` | Connect to `host:port` pools with TLS | | `--esm` | Stratum flavour, when a pool needs one (see below) | | `--pool-retries` | Connection attempts before moving to the next pool (3) | | `--retry-delay` | Seconds before reconnecting (5), doubled after each failed attempt up to 120. A single pool is retried forever | | `--failover-timeout` | Minutes on a failover pool before trying the first one again (0: stay) | | `--report-hashrate` | Send the hashrate to the pool, for pools that show it | See [all options](/hashwarp/options#pool) for the timeouts. ### Failover pools ```bash theme={null} hashwarp --pool a.example.com:3333,b.example.com:3333 --wallet --worker rig1 ``` Hashwarp mines on the first pool and moves to the next when the first fails `--pool-retries` times in a row. With `--failover-timeout 30` it tries the first pool again after 30 minutes on another. ### Pool URLs Pools can also be given as URLs, which is how ethminer and Hashwarp 1.x took them (`-P` still works): ```bash theme={null} hashwarp --pool stratum+ssl://pool.example.com:4443 --wallet hashwarp -P stratum2+tcp://.rig1@pool.example.com:3333 ``` The scheme is `stratum`, `stratum1` (EthProxy), `stratum2` (EthereumStratum/1.0.0) or `stratum3` (EthereumStratum/2.0.0), followed by `+tcp`, or `+ssl` / `+tls` for TLS. If the URL has no wallet, `--wallet` and `--worker` are added. ### Stratum flavours Pools speak one of several Stratum dialects. By default Hashwarp tries EthereumStratum/1.0.0, then EthProxy, then plain Stratum, and logs the one the pool accepted: ``` 12:00:00 INFO pool Protocol EthereumStratum/1.0.0 ``` If a pool needs a particular one, `--esm` sets it: `0` EthProxy, `1` or `2` EthereumStratum/1.0.0 (NiceHash), `3` EthereumStratum/2.0.0. EthereumStratum/2.0.0 is only used with `--esm 3`. ### Difficulty Pool difficulty is counted in units of 232 hashes, like the pools count it: difficulty 1 is a share every 4.29 billion hashes on average. Hashwarp writes difficulties in hashes, so a pool difficulty of 2 is `diff 8.59 GH`. *** ## Pools with the majority A pool that finds more than half of the blocks can reverse payments and block transactions. Hashwarp reads the pools' shares of the last 7 days' blocks from [status.parallaxprotocol.org](https://status.parallaxprotocol.org) every 10 minutes. When your pool has the majority it says so at startup and then every hour, with the smaller pools to move to: ``` 05:26:47 WARN pool rplant.xyz found 86% of the network's blocks in the last 7 days. A pool with the majority can reverse payments and block transactions, which puts the coin you mine at risk 05:26:47 WARN pool Please mine on a smaller pool (coolpool.top 13% · gtpool.io 1%) or solo (--solo). https://status.parallaxprotocol.org has the figures; --no-pool-check hides this ``` The [dashboard](/hashwarp/dashboard) shows it too, and the first-run wizard lists such a pool last. * Hashwarp never changes pools by itself: moving is your choice. * The request sends nothing about you or your rig, only Hashwarp's version as the User-Agent. If it fails, Hashwarp carries on mining without a word. * It doesn't run when solo mining, in simulation, `--selftest` or `--oc-tune`. * `--no-pool-check` turns it off. *** ## Tips & Troubleshooting * **Rejected shares** with a reason like `low difficulty`: the pool may need another Stratum flavour; try `--esm`. **Wrong results** (the `F` count): lower the GPU's overclock. * Choose a pool with servers close to you: the share latency in the log should stay well under a second. * Make sure your address is right: rewards sent to a wrong address can't be recovered. * More in [Troubleshooting](/hashwarp/troubleshooting). # HiveOS & mmpOS Source: https://docs.parallaxprotocol.org/hashwarp/rig-os Mine with Hashwarp on HiveOS and mmpOS, with the ready-made packages. Each Hashwarp release has a package for HiveOS and one for mmpOS, on the [releases page](https://github.com/ParallaxProtocol/hashwarp/releases): | Rig OS | Package | | - | - | | HiveOS | `hashwarp-.tar.gz`, labeled "HiveOS package" | | mmpOS | `hashwarp--mmpos.tgz`, labeled "mmpOS package" | Both report the hashrate, shares, temperatures and fans to the rig OS through Hashwarp's API, which they keep on `127.0.0.1`. Both restart Hashwarp when it exits, which the [watchdog](/hashwarp/safety#the-watchdog) relies on. > [!NOTE] > > Set the overclock in the rig OS, as for any miner. Hashwarp's own [overclocking](/hashwarp/overclocking) options aren't needed there. *** ## HiveOS **1. Copy the package's link** On the [releases page](https://github.com/ParallaxProtocol/hashwarp/releases), copy the link of `hashwarp-.tar.gz`, for example: ``` https://github.com/ParallaxProtocol/hashwarp/releases/download/v2.0.0/hashwarp-2.0.0.tar.gz ``` HiveOS reads the miner's name and version from this file name, so use it as it is. **2. Create a flight sheet** In HiveOS, create a flight sheet with your Parallax wallet, choose **Custom** as the miner, and open its **Setup Miner Config**: | Field | Value | | - | - | | Miner name | `hashwarp` (filled in from the link) | | Installation URL | The link from the previous step | | Hash algorithm | `xhash` | | Wallet and worker template | `%WAL%.%WORKER_NAME%` | | Pool URL | The pool's `host:port`, for example `pool.example.com:3333`. Several pools separated by spaces are failover pools | | Pass | The pool password, if it needs one | | Extra config arguments | Any Hashwarp options, for example `--tls --temp-stop 85` | **3. Apply it to your rigs** Apply the flight sheet. HiveOS downloads Hashwarp, starts it, and shows its hashrate and statistics on the rig's page. The miner log shows Hashwarp's output. To update Hashwarp, change the Installation URL to the new release's package. *** ## mmpOS **1. Copy the package's link** On the [releases page](https://github.com/ParallaxProtocol/hashwarp/releases), copy the link of `hashwarp--mmpos.tgz`. **2. Create a miner profile** Create a miner profile of the **Custom miner** type with the package's link, your Parallax wallet and the pool. The package maps the profile's pool, wallet, worker, password and TLS setting to Hashwarp's options. Extra Hashwarp options can be added after the profile's arguments, for example `--temp-stop 85`. **3. Apply it to your rigs** mmpOS downloads Hashwarp, starts it and shows its statistics. *** ## Other rig operating systems Any Linux with glibc 2.28 or newer runs the Linux archive as it is: see [Configuration](/hashwarp/configuration) to run it as a service. A RaveOS package isn't available yet. # Safety Source: https://docs.parallaxprotocol.org/hashwarp/safety Temperature limits, the watchdog, checked results and exit codes: how Hashwarp protects your rig. Hashwarp watches each GPU's temperatures and health while it mines, and checks every result before sending it. *** ## Temperatures Hardware monitoring is on by default (`--no-hwmon` turns it off). Hashwarp reads NVIDIA GPUs through the NVIDIA driver, and AMD GPUs on Linux through the kernel driver: core, junction and memory temperatures, fan, power and clocks. On Windows, AMD GPUs older than Vega report their temperature, fan and power; newer AMD GPUs report nothing on Windows. | Option | Meaning | | - | - | | `--temp-stop 85` | Pause a GPU when its core reaches 85°C | | `--temp-resume 70` | Resume it at 70°C (default: 15° below `--temp-stop`) | | `--mem-temp-stop 100` | Pause a GPU at this memory temperature, or hotspot temperature on GPUs without a memory sensor | | `--mem-temp-resume 90` | Resume it at this temperature (default: 10° below `--mem-temp-stop`) | | `--shutdown-temp 95` | Stop Hashwarp (exit code 6) when any GPU temperature reaches 95°C | The temperature limits take [one value per GPU](/hashwarp/configuration#lists-per-gpu), or one for all. A paused GPU is logged with a warning, and resumes by itself once it has cooled down: ``` 14:02:11 WARN gpu1 Reached 85°C, pausing until 70°C 14:03:40 INFO gpu1 Cooled down to 70°C, resuming ``` > [!NOTE] > > `--mem-temp-stop` needs a GPU that reports its memory or hotspot temperature. Most AMD GPUs on Linux report both, but NVIDIA's driver doesn't report them for many GeForce cards. When a GPU reports neither, Hashwarp warns that `--mem-temp-stop` has no effect on it. The statistics table (`s`) shows which temperatures each GPU reports. *** ## The watchdog The watchdog restarts a GPU whose mining failed, and stops Hashwarp when a GPU hangs, so that a supervisor can start it again: | Option | Meaning | | - | - | | `--watchdog-restarts 3` | Restart a GPU whose mining failed up to 3 times per hour. After that it is left stopped while the other GPUs mine on; when no GPU is left mining, Hashwarp exits (code 5) | | `--watchdog-timeout 120` | Exit (code 5) when a GPU gives no sign of life for 120 seconds, which is usually a GPU or driver hang (`0`: off) | | `--watchdog-script` | A program to run before exiting, with the GPU index and the reason as arguments; for example to reboot the rig | | `--exit` | Exit when a GPU fails, instead of restarting it | A hung GPU can't be recovered by Hashwarp: the watchdog exits so that Hashwarp, or the whole rig, can be restarted. Run Hashwarp under a supervisor that starts it again: HiveOS or mmpOS, a [systemd service](/hashwarp/configuration#running-as-a-service-linux), or a loop in a script. Overclocks are restored on a watchdog exit. *** ## Checked results Every solution a GPU finds is checked on the CPU before it is sent. A wrong one, usually from too high a memory overclock, isn't submitted: it counts as `F` (failed) in the share counts and is logged: ``` 10:14:02 WARN gpu0 Wrong result, lower the overclock if it happens often ``` `hashwarp --selftest` runs the same check offline and says PASS or FAIL per GPU: see [GPUs & Tuning](/hashwarp/gpus-and-tuning). *** ## Exit codes | Code | Meaning | | - | - | | 0 | Normal exit, or `--selftest` passed | | 1 | Invalid options, or `--selftest` failed | | 2 | Runtime error, such as no usable GPU | | 5 | Watchdog: a GPU kept failing or stopped responding | | 6 | A GPU reached `--shutdown-temp` | # Solo Mining Source: https://docs.parallaxprotocol.org/hashwarp/solo-mining How to mine Parallax on your own node with Hashwarp: the whole block reward, no pool. Solo mining sends your hashrate to your own Parallax node instead of a pool. Each block you find pays the whole block reward to you, but blocks come irregularly: a small rig can go a long time without one. On a pool, rewards come in small, regular amounts instead; see [Pool Mining](/hashwarp/pool-mining). *** ## Step-by-step Guide **1. Start your node with mining enabled** Run the [Parallax client](/guides/client/setup) with the mining API and the address that receives the rewards: ```bash theme={null} ./parallaxd --http --http.api "eth,net,web3,miner" --mine --miner.coinbase ``` The node must be synced: until then it has no work to give. **2. Point Hashwarp to it** ```bash theme={null} hashwarp --solo # node on this computer, http://127.0.0.1:8545 hashwarp --solo http://192.168.1.10:8545 # node on another computer ``` The block reward goes to the node's `--miner.coinbase` address: Hashwarp doesn't need `--wallet` for solo mining. **3. Wait for a block** Each block found is logged with its height: ``` 06:20:45 INFO block ★ BLOCK FOUND by gpu0 at height 60500 · 5 ms ``` The reward can be spent once the block has 100 blocks on top of it. Check your balance with: ```bash theme={null} ./parallaxd attach --exec "eth.getBalance('')" ``` > [!WARNING] > > Keep the node's HTTP and WebSocket ports on your local network: the mining API has no authentication, so anyone who can reach it can submit work to your node. *** ## New work without polling: WebSocket Over HTTP, Hashwarp asks the node for new work every second (`--getwork-interval`, in milliseconds). Over the node's WebSocket, the node can instead push each new block's work to Hashwarp the moment it has it, and blocks go back on the same connection: ```bash theme={null} ./parallaxd --ws --ws.api "eth,net,web3,miner" --mine --miner.coinbase hashwarp --solo ws://127.0.0.1:8546 ``` When the node pushes work, Hashwarp says so when it connects: ``` 06:20:33 INFO node The node pushes new work ``` > [!NOTE] > > Pushing new work needs a Parallax client that supports the `newWork` subscription. With an older client, Hashwarp asks for work on the same WebSocket every `--getwork-interval` milliseconds instead, and says so when it connects: mining works the same. `wss://` works with a node behind a TLS proxy. *** ## Solo with a failover pool Solo mining combines with failover pools: Hashwarp mines on the pool while the node is unreachable, and moves back to the node with `--failover-timeout`: ```bash theme={null} hashwarp --solo --pool pool.example.com:3333 --wallet --failover-timeout 10 ``` *** ## Options | Option | Meaning | | - | - | | `--solo [URL]` | The node's URL: `http://host:8545` (default `http://127.0.0.1:8545`), or `ws://host:8546` / `wss://` | | `--getwork-interval` | Milliseconds between requests for new work, when the node doesn't push it (1000) | | `--work-timeout` | Reconnect when no new work arrives for this many seconds (7200) | | `--report-hashrate` | Report the hashrate to the node, which adds it to the hashrate it shows | # Troubleshooting Source: https://docs.parallaxprotocol.org/hashwarp/troubleshooting Common Hashwarp problems and what to do about them, and what to do when Hashwarp finds no GPU on Windows. ## Common problems | Problem | What to do | | - | - | | `No usable mining devices found` | Hashwarp found no GPU it can mine with: see [No GPU found on Windows](#no-gpu-found-on-windows) below. On Linux, install the NVIDIA driver (525 or newer) or AMD's driver with OpenCL (ROCm) | | `Wrong result, lower the overclock if it happens often` | Lower the memory overclock of that GPU, then check it with `hashwarp --selftest` | | Rejected shares with a `low difficulty` reason | The pool may need another Stratum flavour: try `--esm` (see [Pool Mining](/hashwarp/pool-mining#stratum-flavours)) | | The pool keeps disconnecting | Check the pool's address and port, and `--tls` for a TLS port. `--log-debug json` shows the messages exchanged with the pool | | `Epoch N needs ...` and the GPU paused | The GPU doesn't have enough free memory for the DAG. Close other programs using the GPU | | The hashrate drops to 0 and the GPU shows `paused` | A temperature limit was reached: see the warning above it, and [Safety](/hashwarp/safety#temperatures) | | The hashrate swings a lot | Something else uses the GPU: a desktop, a browser, a video. Mine on GPUs without a display where you can | | `--mem-temp-stop has no effect` | The GPU reports no memory or hotspot temperature: see [Safety](/hashwarp/safety#temperatures) | | Overclocking says `needs root` | Run Hashwarp with `sudo` on Linux, or as administrator on Windows | | `Rusticl warning` or `pci id for fd` lines at start (Linux) | Printed by Mesa's OpenCL driver, harmless. On NVIDIA-only rigs mine with `--cuda`, or set `OCL_ICD_VENDORS` to the vendor's `.icd` file (e.g. `nvidia.icd`) | | TLS pools fail with a certificate error | Install your distribution's CA certificates (`ca-certificates`), or set `SSL_CERT_FILE` to a CA bundle | When asking for help, run `hashwarp --list-devices` and include its output, your command line or configuration (without your address if you prefer), and the lines around the problem from the log (`--log-file hashwarp.log`). *** ## No GPU found on Windows If Hashwarp stops at start with: ``` Error: No usable mining devices found ``` it found no GPU it can mine with. Run `hashwarp --list-devices` to see which GPUs it detects, then follow the section for your GPU. *** ### NVIDIA GPUs Hashwarp mines on NVIDIA GPUs with **CUDA**, which needs only the NVIDIA driver: 1. Install or update the driver from [NVIDIA Driver Downloads](https://www.nvidia.com/Download/index.aspx): version **525 or newer**. 2. Reboot, then run `hashwarp --list-devices` again. If the driver is too old, Hashwarp says so when it starts: `The NVIDIA driver supports CUDA ... only: update it to version 525 or newer`. > [!NOTE] > > Older Hashwarp versions mined on NVIDIA GPUs with OpenCL, and needed the OpenCL runtime to be registered in Windows. Hashwarp 2.0 doesn't: on NVIDIA you don't need the steps below. *** ### AMD GPUs Hashwarp mines on AMD GPUs with **OpenCL**. The AMD driver (Adrenalin) installs the OpenCL runtime (`amdocl64.dll`) and registers it so programs can find it. When Hashwarp doesn't find an AMD GPU, the driver install is usually damaged: 1. Download the current driver from [AMD Drivers and Support](https://www.amd.com/en/support/download/drivers.html). 2. Install it with **Factory Reset** selected, which removes the previous installation first. 3. Reboot, then run `hashwarp --list-devices` again. If the GPU is still missing, the OpenCL runtime may not be registered. You can register it by hand, as below. *** ### Registering the OpenCL runtime by hand (advanced) #### Step 1 — Locate the OpenCL DLL Run **PowerShell as Administrator**, then execute: ```powershell theme={null} theme={null} Get-ChildItem -Path "C:\Windows\System32\DriverStore\FileRepository" -Filter "amdocl64.dll" -Recurse -ErrorAction SilentlyContinue ``` Expected output (example): ``` C:\Windows\System32\DriverStore\FileRepository\u0123456.inf_amd64_xxxxx\B012345\amdocl64.dll ``` Note the full path: you'll need it in Step 3. If the file isn't there, the driver isn't installed correctly: reinstall it as above. *** #### Step 2 — Check if the registry key is missing Still in PowerShell, run: ```powershell theme={null} theme={null} Get-ItemProperty -Path 'HKLM:\SOFTWARE\Khronos\OpenCL\Vendors' ``` If the output doesn't list the path from Step 1, or you see **"Cannot find path"**, register it in Step 3. *** #### Step 3 — Register the OpenCL runtime Run the following in **Administrator PowerShell**, with the path from Step 1: ```powershell theme={null} theme={null} $icd = 'C:\Windows\System32\DriverStore\FileRepository\u0123456.inf_amd64_xxxxx\B012345\amdocl64.dll' New-Item -Path 'HKLM:\SOFTWARE\Khronos\OpenCL' -Name 'Vendors' -Force | Out-Null New-ItemProperty -Path 'HKLM:\SOFTWARE\Khronos\OpenCL\Vendors' ` -Name $icd -PropertyType DWord -Value 0 -Force | Out-Null ``` Then **reboot your PC**. > [!WARNING] > > Driver updates can move the DLL to a new folder. If the GPU disappears after an update, repeat these steps with the new path, or reinstall the driver with Factory Reset. *** #### Step 4 — Verify after reboot ```powershell theme={null} theme={null} reg query "HKLM\SOFTWARE\Khronos\OpenCL\Vendors" ``` The output should list the path of `amdocl64.dll` with the value `0x0`. *** ### Final check Now you can run Hashwarp again: ```bash theme={null} theme={null} hashwarp --list-devices ``` If everything was successful, your GPU is listed. Start mining as usual, and Hashwarp prints its hashrate every 10 seconds: ``` 15:42:12 INFO miner 115.42 MH/s · 60s 115.43 · 15m 116.18 · A20 · 71°C · fan 53% · 377 W · 306 kH/J ``` Your GPU is now recognized and mining on Parallax. # Upgrading from 1.x Source: https://docs.parallaxprotocol.org/hashwarp/upgrading What changes when you move from Hashwarp 1.x to Hashwarp 2.0. Hashwarp 2.0 runs your 1.x command lines and configuration as they are. A few things work differently; this page lists them. *** ## One download for every GPU Hashwarp 1.x had separate CUDA and OpenCL builds. Hashwarp 2.0 has one build per system, which mines on NVIDIA GPUs with CUDA and on AMD and other GPUs with OpenCL, and needs no CUDA toolkit: only the GPU driver (NVIDIA 525 or newer). On Windows, NVIDIA GPUs no longer need the OpenCL runtime to be registered, and the archive no longer has `fix-opencl-icd.vbs`. If an AMD GPU isn't found, see [Troubleshooting](/hashwarp/troubleshooting#no-gpu-found-on-windows). *** ## Options Every 1.x option still works. Most have a new, clearer name, which `hashwarp --help` shows; the old names are listed by `hashwarp --help-all`: | 1.x | 2.0 | | - | - | | `-P stratum+tcp://0xAddress.rig1@pool:3333` | `--pool pool:3333 --wallet 0xAddress --worker rig1` | | `-P http://127.0.0.1:8545` | `--solo` | | `-U`, `-G` | `--backend cuda`, `--backend opencl` | | `--cu-devices`, `--cl-devices`, `--opencl-devices` | `--gpu-id` | | `--tstop`, `--tstart` | `--temp-stop`, `--temp-resume` | | `--farm-recheck` | `--getwork-interval` | | `--farm-retries` | `--pool-retries` | | `--cu-grid-size`, `--cu-block-size`, `--cu-streams` | `--cuda-grid-size`, `--cuda-block-size`, `--cuda-streams` | | `--api-port 3333` | `--api-bind 127.0.0.1:3333` | | `--api-password` | `--api-token` | | `-v 1` | `--log-debug json` | | `--cl-nobin` | Not needed: accepted and ignored | A configuration file can replace the long command lines: `--save-config hashwarp.json` writes one from your options. See [Configuration](/hashwarp/configuration). *** ## The output The output is new: each line has its time, level and source, hashrates are written `MH/s` and difficulties `GH`, and a line is printed per share. See [Output & Logs](/hashwarp/output-and-logs). Scripts that read 1.x's output should read `--log-format json` or the [API](/hashwarp/api) instead. *** ## The API * The API listens only where `--api-bind` says, and on `127.0.0.1` with the 1.x option `--api-port`. * It is read only unless `--api-allow-control` is given; with 1.x's `--api-port`, it is read only. Control on an address other than `127.0.0.1` requires `--api-token`. * The JSON-RPC methods of 1.x (`miner_getstat1` ...) still work, on the same port as the new [JSON API, dashboard and Prometheus metrics](/hashwarp/api). *** ## New in 2.0 * A [first-run wizard](/hashwarp/configuration#the-first-run-wizard) and [configuration file](/hashwarp/configuration#the-configuration-file). * [Overclocking](/hashwarp/overclocking) with `--oc-tune`. * A [dashboard](/hashwarp/dashboard) for one rig or all of them. * [Temperature limits, a watchdog](/hashwarp/safety), and `--selftest`. * A warning when your pool finds [most of the network's blocks](/hashwarp/pool-mining#pools-with-the-majority). * [HiveOS and mmpOS](/hashwarp/rig-os) packages. The full list is in the [release notes](https://github.com/ParallaxProtocol/hashwarp/releases/tag/v2.0.0). # Welcome to Parallax Source: https://docs.parallaxprotocol.org/index The official Parallax documentation: learn how Parallax works, how to take part in the network, and how to build on top of it. Parallax is a decentralized, EVM-compatible blockchain protocol inspired by Bitcoin’s time-tested economic model and secured by XHash Proof of Work. This documentation is your primary resource to understand how Parallax works, how to connect to the network, and how to contribute to its ecosystem. *** ## Where to start > **[Beginner Guides](/guides/client/introduction)** > > New to Parallax? Step-by-step guides to wallets, running a node, CPU mining and AI assistants. > **[Parallax Wallet](/parallax-wallet/introduction)** > > The desktop wallet with a full node built in: hold, send and receive LAX on Windows, macOS or Linux. > **[Hashwarp](/hashwarp/getting-started)** > > The official GPU miner for XHash: a first run, pools, solo mining, tuning and monitoring. > **[Parallax Client](/client/getting-started/introduction)** > > Install, configure and run a node from the command line, use its JSON-RPC, and build on it. > **[Protocol Specification](/protocol/foundational-topics/introduction-to-parallax)** > > How Parallax works: accounts, transactions, blocks, the PVM, consensus, XHash and networking. > **[Exchange Integration Guide](/exchange-integration/overview)** > > What an exchange needs to list LAX: nodes, deposits, withdrawals, confirmations and the status API. Only the client documentation is versioned, one version per major release: the current one is `v2.x`, and `v1.x` is archived. Everything else always describes the current network and software. *** ## Network at a glance | | | | - | - | | **Coin** | LAX, 18 decimals | | **Chain ID** | `2110` | | **Consensus** | Proof of work, [XHash](/protocol/foundational-topics/consensus/algorithms/xhash) | | **Block time** | 10 minutes, with difficulty adjusted every block (ASERT) | | **Block reward** | 50 LAX, halving every 210,000 blocks (about 4 years) | | **Supply cap** | 21,000,000 LAX. No premine | | **EVM** | Berlin. Legacy and access-list transactions, no EIP-1559 | | **Public RPC** | `https://rpc.parallaxprotocol.org`, for testing. Run your own node for anything serious | | **Block explorer** | [explorer.parallaxprotocol.org](https://explorer.parallaxprotocol.org) | | **Network status** | [status.parallaxprotocol.org](https://status.parallaxprotocol.org) | The full list, with address and transaction formats, is in the [Network reference](/exchange-integration/network-reference). To add Parallax to MetaMask, see [Setting up MetaMask](/guides/wallets/metamask). *** ## Get help * **Ask an AI assistant**: the [Parallax MCP server](/guides/ai/parallax-mcp) lets Claude and other assistants search these docs and read the chain. * **Check the network**: [status.parallaxprotocol.org](https://status.parallaxprotocol.org) shows whether blocks, nodes and mining are healthy. * **Report a problem**: open an issue in the right repository of the [ParallaxProtocol GitHub organization](https://github.com/ParallaxProtocol). * **Follow the project**: [@prlxchain on X](https://x.com/prlxchain). *** ## Contributing Parallax is open source. Code, documentation and research are all welcome: see the [ParallaxProtocol GitHub organization](https://github.com/ParallaxProtocol). These docs live in [parallax-docs](https://github.com/ParallaxProtocol/parallax-docs). # Accounts in Parallax Wallet Source: https://docs.parallaxprotocol.org/parallax-wallet/accounts The kinds of accounts Parallax Wallet holds, and how to create, import, back up and remove them. An account is an address that holds LAX, and the key that can spend it. Parallax Wallet keeps every key encrypted with your wallet password, and groups your accounts by kind, in the account switcher at the top of the sidebar and in **Settings → Accounts**: | Kind | What it is | | - | - | | **Recovery phrases** | Accounts from a 12 or 24-word phrase. One phrase backs up every account made from it, now or later. | | **Single keys** | One account with a key of its own, from a private key or a keystore file. Its backup is the keystore file. | | **Hardware wallets** | Accounts whose keys stay on a Ledger or Trezor, which confirms every send. See [Hardware wallets](/parallax-wallet/hardware-wallets). | | **Watch-only** | An address you follow without its key, such as one kept on an [offline signer](/parallax-wallet/offline-signing). | For how accounts and addresses work in general, see [Accounts & addresses](/guides/wallets/accounts). *** ## Create an account In **Settings → Accounts**, choose **Create accounts**: * **New recovery phrase** (recommended) — 24 words, or 12 with **Use 12 words instead**. Write them down on paper; the app asks you to type a few back to make sure. The words work in MetaMask and most other wallets. * **New single key** — one account with a key of its own, backed up as an encrypted keystore file. * **New account from this phrase** — the next account from a recovery phrase you already have, backed up by the same words. *** ## Import an account In **Settings → Accounts**, choose **Import accounts**: * **Import a recovery phrase** — 12 to 24 words from MetaMask or another wallet. The app looks for the accounts you've used and ticks them for you to confirm. * **Import a key** — a keystore file with its file password, or a private key typed in. * **Connect a hardware wallet** — a Ledger or a Trezor; see [Hardware wallets](/parallax-wallet/hardware-wallets). * **Watch an address** — only the address comes in, by scanning its QR code or typing it; see [Offline signing](/parallax-wallet/offline-signing). ### Finding the right accounts Wallets keep a phrase's accounts along different paths. If the accounts you expect don't appear, look along the path the other wallet used: | Path | Used by | | - | - | | **Standard** | MetaMask, Trezor Suite and most wallets | | **Ledger Live** | Ledger Live | | **Legacy** | Older wallets, such as MyEtherWallet | *** ## Managing your accounts From **Settings → Accounts** you can: * **Rename** an account. * **Show** a recovery phrase, after typing your wallet password. * **Save backup** of a single key: its encrypted keystore file, written where you choose. It opens with the wallet password you had when you saved it. * **Remove** an account, or a recovery phrase with all its accounts. The app warns you and asks you to confirm first: without a backup, removed keys can't be brought back. An account that hasn't been backed up yet is marked **No backup**. > [!WARNING] > > Anyone with your recovery phrase or a single key's backup and its password > can take your LAX. Keep them offline and private; see > [Keeping your wallet safe](/guides/wallets/keep-safe). # AI assistants in Parallax Wallet Source: https://docs.parallaxprotocol.org/parallax-wallet/ai-assistants Let Claude and other AI assistants read the chain through your own node, and, as far as you allow, see your wallet and ask the app to act, each request approved by you. [Parallax Wallet](/parallax-wallet/introduction), the desktop app, has an MCP server built in. An AI assistant such as Claude connects to it on your computer and answers from **your own node**: blocks, transactions, balances, contracts, the mempool and mining, with none of it looked up on a public server. As far as you allow it, the assistant can also see your node's status and logs, your wallet's accounts and your address book, start the node, and ask the app to do things for you: send LAX, stop the node, change settings, create an account, follow an address or add a contact. Each request waits for you to approve it in the app. It uses the same tools as the [public Parallax MCP server](/guides/ai/parallax-mcp), so everything that guide says about asking questions applies here too. *** ## Public server or Parallax Wallet? | | Public server | Parallax Wallet | | - | - | - | | Chain data from | The public RPC | Your own node | | What you look up | Goes to a shared server | Stays on your computer, unless you allow the public explorer or status page | | Explorer and network health | Always | When you allow them | | Your wallet and address book | No | When you allow them | | Asks the app to act | No | When you allow it, each request approved by you | | Needs | Nothing | Parallax Wallet running, with its node | *** ## Turn it on **1. Open the assistant settings** In Parallax Wallet, open **Settings → AI assistants → Overview** and turn on **Assistant access**. Save. **2. Copy the connection** Under **Connect an assistant**, choose your assistant from the list (Claude Code, Claude Desktop, Codex, Gemini CLI, Cursor, VS Code, Windsurf, Zed, Cline, opencode, LM Studio, or **JSON config** for any other) and copy what it shows: a command to run or a config to add, with the server's address and its access token in it. **3. Choose what assistants may do** Open **Settings → AI assistants → Permissions**. To begin with, the node's status is allowed and everything else asks you first. You can leave it that way and decide as assistants ask. The server listens on `127.0.0.1:8549` by default; you can change the port in Overview. > [!NOTE] > > The assistant server doesn't need HTTP-RPC (**Settings → RPC**): it > reaches the node inside the app, as the wallet does. It does need the node > running: while the node is stopped, a tool that needs it has it started > first, as **Start the node** allows (see [Permissions](#permissions)), and > carries on. ### Claude Code Run the command you copied in a terminal. It looks like this, with your own token: ```bash theme={null} claude mcp add --transport http parallax-wallet-app http://127.0.0.1:8549/mcp \ --header "Authorization: Bearer " ``` Add `-s user` after `claude mcp add` to have it in every project. Then run `/mcp` in Claude Code to check that `parallax-wallet-app` is connected. ### Other assistants For the other assistants in the list, the app says where its config goes (for example `~/.cursor/mcp.json` for Cursor, or `~/.codex/config.toml` for Codex): add it there, alongside any servers already in it. Claude Desktop reaches the server through `mcp-remote`, which needs Node.js. The JSON config works for MCP clients that read an `mcpServers` config, such as a project's `.mcp.json`: ```json theme={null} { "mcpServers": { "parallax-wallet-app": { "type": "http", "url": "http://127.0.0.1:8549/mcp", "headers": { "Authorization": "Bearer " } } } } ``` The client must run on the same computer as Parallax Wallet, and support Streamable HTTP with a custom header. *** ## The assistant bar While an assistant is connected, a small round bar sits at the bottom right of the window, beside the node bar, with a dot for its state. Point at it to see who is connected, such as *"Claude Code connected"*. * **At work.** While an assistant uses a tool, the robot gives way to a spinner, and pointing at the bar says what it's doing: *"Claude Code is checking a balance…"*, or *"…is waiting for block 10…"* while it waits on the chain. A **✕** beside it stops that: the tool's work ends, and the assistant is told you cancelled it. * **On a request.** When an assistant asks for something, the bar opens into the request, lit blue, pushing the node bar aside, and closes again once you've decided (see [Approving requests](#approving-requests)). With no assistant connected, the bar isn't shown. *** ## Permissions You choose, feature by feature, what assistants may see, do and ask for. Each permission is set to one of: * **Allow:** assistants use it without asking. * **Ask:** the app asks you the first time an assistant uses it (see below). * **Block:** refused, without asking you. Changes apply as soon as you save, even for an assistant already connected. ### When an assistant asks for permission Like Claude asks before it uses a tool, Parallax Wallet asks you before an assistant uses a feature set to **Ask**. The prompt names the tool and what it gives the assistant, and offers: * **Allow once:** this assistant may use it until it disconnects (or goes half an hour without it). Other assistants are asked again. * **Always allow:** the permission becomes **Allow**, for every assistant. * **Don't allow:** refused this time. The assistant waits up to 2 minutes for your answer, then is told you didn't answer. ### What assistants can see | Permission | What it shows | | - | - | | **Chain data** (always) | Blocks, transactions, balances, contracts, the mempool, mining and the docs, from your node | | **Node status** (allowed by default) | Whether the node runs and syncs, peers, uptime and version | | **Logs** | The node's and the app's log, which can name peers' addresses | | **Wallet** | Your accounts, their names, balances and activity, your recovery phrases by name (never their words), and your hardware wallets by name, with which accounts sign on a Ledger or Trezor | | **Address book** | Your contacts' names, addresses and notes | Everything an assistant reads goes to its provider along with your conversation. Turning on **Wallet**, for example, lets the provider see which addresses are yours. ### Public services | Permission | What it adds | | - | - | | **Block explorer** | Address histories, token balances and transfers, verified contract sources and search, from [explorer.parallaxprotocol.org](https://explorer.parallaxprotocol.org). Transactions and events are decoded with verified sources too. | | **Status page** | Network health and alerts, recommended confirmations, incidents and network-wide mining figures, from [status.parallaxprotocol.org](https://status.parallaxprotocol.org) | Both are off by default: everything comes from your node. With them on, what the assistant looks up there leaves your computer. Changing them restarts the assistant server, so connected assistants reconnect (in Claude Code, from `/mcp` if it doesn't on its own). The development chain never uses them, as they describe mainnet. ### What assistants can do | Permission | What it does | | - | - | | **Start the node** | Starts the node when it's stopped: when an assistant asks to, and when a tool it uses needs the node. Set to **Ask**, the prompt says the node is stopped; allowed, the node starts and the assistant's request carries on. | ### What assistants can ask for These don't act on their own. The assistant asks, and the app shows you the request to approve or turn down, every time, so these are set to **Ask** or **Block**: Block stops assistants from asking at all. | Permission | The request | | - | - | | **Stop the node** | Stop the node | | **Settings** | Change settings: appearance, logging, sync, peers, caches, the transaction pool, fee estimates and RPC limits | | **Create accounts** | Create a wallet account, with a new key or the next one from a recovery phrase | | **Watch-only accounts** | Follow an address whose key is kept elsewhere | | **Edit the address book** | Add a contact, or change one | | **Send transactions** | Send LAX from one of your accounts, approved with the wallet password, or on the device for a hardware wallet account | *** ## Approving requests When an assistant asks for something, the assistant bar opens on the request wherever you are in the app, with a desktop notification if the window is in the background and notifications are on. It shows exactly what would happen: * **Settings:** each setting before and after, when it takes effect, and a warning on sensitive ones (those that open the node to other programs or share something about it). * **Contacts:** the address in full, and the old values when a contact changes. Check the address: a contact is where you'll send funds. * **Sends:** the amount, the account it comes from, the recipient in full and who it is (one of your accounts, a contact, or an address you have never sent to, with a warning), the network fee, the total and your balance after. Amounts are exact, never rounded. You approve with the wallet password, which goes to the wallet, never to the assistant. The app refuses beforehand what your balance doesn't cover, or a fee over your fee cap (1 LAX unless you changed it). From a watch-only account, approving makes a signing request to sign on your offline signer. From a hardware wallet account, there's no password: approving sends it to your Ledger or Trezor, where you check it against the request and confirm or reject it. If the device isn't connected and ready (unlocked, with the Ethereum app open on a Ledger), the request stays for you to try again. Sends are plain LAX transfers: assistants can't ask to call contracts. * **Accounts:** the new account's name and where its key comes from. You type the wallet password in the app; it goes to the wallet, never to the assistant. The assistant's reason is shown in quotes, as its words. The approving button names what it does (**Sign and send**, **Change settings**, **Create account**, **Add contact** and so on) and carries out exactly what was shown; **Don't allow** refuses it. Requests come one at a time, the next taking the bar's place once you've decided. A request not decided within 10 minutes expires, and no more than five wait at once. The assistant is told the outcome. Once a send is made, the bar confirms it: the amount, where it went, and the transaction's hash to copy. It stays while you point at it, and closes two seconds after you move away. Some settings can never be requested: RPC addresses, APIs and CORS, proxies and Tor, peers and bootnodes, network restrictions, the fee and disk guards, data directories, update checks, offline signing and the assistant settings. *** ## What assistants can never do Whatever you allow, no assistant can: * See recovery phrases, or export, import or back up keys. * See or change the wallet password. * Sign or send a transaction without your approval and the wallet password, or, from a hardware wallet account, your confirmation on the device. * Remove accounts, recovery phrases or contacts. * Open the node to the network. * Turn offline signing on or off, or change what assistants may do. It can build an unsigned transaction for you to check and sign yourself. *** ## Safety * **Local only.** The server listens on `127.0.0.1`, so only programs on your computer reach it. * **Access token.** Every request needs the token. **New token** in Overview replaces it and disconnects every assistant set up with the old one; set them up again with the new command. * **Not from web pages.** Requests from web pages are refused, and so are those using another host name, a trick web pages use to reach local servers. * **Read-only to the node.** Every request to the node passes the same read-only allowlist as the public server. * **Untrusted text.** Token names, contract strings, log messages and imported contacts are marked as data the assistant must not follow. > [!WARNING] > > Assistants can be misled by what they read: a web page, a token's name or > a contract can carry instructions meant to steer them. Approve only > requests you meant to make, and check addresses yourself. *** ## Troubleshooting | Problem | What to do | | - | - | | The assistant bar isn't showing | It shows only while an assistant is connected. Check the assistant's connection (in Claude Code, `/mcp`). | | Overview says the server could not start | Its port is taken, often by another copy of Parallax Wallet. Choose another port. | | The assistant says the node is stopped | **Start the node** is set to **Block**, or you turned the prompt down. Start it in the app, or set it to **Ask** or **Allow**. | | The assistant says you don't let it | That permission is set to **Block**: change it in **Settings → AI assistants → Permissions**. | | The assistant says you didn't answer | A prompt waited 2 minutes. Ask again and answer it in the app, or set the permission to **Allow**. | | The assistant can't connect after a change | Changing the port or the public services restarts the server: reconnect, in Claude Code from `/mcp`. A new token needs the server added again. | | A send from a hardware wallet account waits | Connect and unlock the device (on a Ledger, open the Ethereum app), then approve the request again: it stays until you do. | | No explorer data or network health | Turn on **Block explorer** or **Status page** under Permissions. | # Contacts in Parallax Wallet Source: https://docs.parallaxprotocol.org/parallax-wallet/contacts Keep the addresses you send to under a name, pick them when sending, and import or export your contacts as JSON or CSV. **Contacts** is your address book: the people and services you send to, saved under a name. You can pick them by name on **Send**, and the app recognises them in your activity, on the review before you send, and when you verify a signed message. Your contacts are encrypted with your wallet password, like your keys: who you pay says a lot about you. They can only be read or changed while the wallet is unlocked. *** ## Add a contact Choose **Add contact** and fill in: * **Name**: who or what the address belongs to, up to 64 characters. * **Address**: paste the full address. A mixed-case address is checked against its checksum, so a mistyped character is caught. * **Note** (optional): what you pay them for, an invoice reference, up to 500 characters. Each name and each address can be saved only once: a name always means one address, so a look-alike entry can't hide behind a familiar one. The app also tells you when the address is one of your own accounts. *** ## Your contacts * **Favorites** sit at the top of the page as tiles: click one to send to it. Star or unstar a contact from its row. * **All contacts** lists the rest, favorites first, then by name, with when you last sent to each. Search by name, address or note. * **Open a contact** to see its address in full, grouped to check against what the other party gave you, when it was added and last sent to, and its note. From there you can send to it, star it, edit it, **Show history** (your transactions with it) or remove it. Removing a contact doesn't affect any transactions. *** ## Sending to a contact On **Send**, type a contact's name, or choose from your contacts, instead of an address. The review shows who you're sending to. Contacts you've sent to recently are offered first. > [!WARNING] > > A contact is where you'll send funds. Check a new contact's address against > where it came from before you save it, and again when someone asks you to > change it. *** ## Import and export **Export** saves your contacts as JSON or CSV, for a backup or another wallet. **Import** takes: * A JSON export from Parallax Wallet, or a plain JSON list of `{ "name", "address", "note" }` entries. * A CSV file with a `name` and an `address` column. `note` and `favorite` columns are read when they're there. For example: ```csv theme={null} name,address,note,favorite Alice,0x1111111111111111111111111111111111111111,Rent,yes Exchange deposit,0x2222222222222222222222222222222222222222,, ``` Every entry is checked as if typed. An import never overwrites: entries whose name or address is already in your contacts are skipped. When it's done, the app says how many were added, how many were already there, and how many weren't valid, with why for the first few. Files are limited to 2 MB. > [!NOTE] > > An exported file isn't encrypted. Keep it as private as you'd keep the list > of people you pay. *** ## AI assistants and contacts An [AI assistant](/parallax-wallet/ai-assistants) can read your contacts and ask to add or change one, only as far as you allow in **Settings → AI assistants → Permissions**. Each change waits for you to approve it, and no assistant can remove a contact. # Hardware wallets in Parallax Wallet Source: https://docs.parallaxprotocol.org/parallax-wallet/hardware-wallets Use a Ledger or a Trezor with Parallax Wallet: its keys stay on the device, which confirms every send on its own screen. [Parallax Wallet](/parallax-wallet/introduction), the desktop app, works with **Ledger** and **Trezor** hardware wallets. The device keeps the keys: the app only knows the accounts' addresses, and every transaction or message from them is checked and confirmed on the device's own screen before it's signed. Even a compromised computer can't send from them without you. *** ## What you need * **A Ledger** (Nano S Plus, Nano X, Stax, Flex or Nano Gen5) with the **Ethereum** app installed from Ledger Live, or **a Trezor** (Model One, Model T, Safe 3 or Safe 5), set up and with its firmware up to date. * **Parallax Wallet** with its node, connected to the computer by USB. * Close **Ledger Live** or **Trezor Suite** while you use the device with Parallax Wallet: only one app can talk to it at a time. > [!NOTE] > > There's no Parallax app to install on the device. Parallax accounts use the > same paths as Ethereum's (coin type 60) and are signed by the device's > Ethereum app for Parallax's own chain ID, 2110, so a signature for one > network can never be replayed on the other. The device may not know > Parallax by name: it can show the amount as ETH and the network as chain > 2110\. It's LAX on Parallax, as the app shows. ### On Linux: USB access Linux gives a USB device to the user at the computer only once a rule allows it, which Ledger's and Trezor's own apps install and an AppImage can't. If the app says it **can't open your device**, choose **Set up USB access** where it says so: it installs the rules for Ledger and Trezor devices, asking for an administrator's password. Then unplug the device and plug it in again. macOS and Windows need nothing. *** ## Add your accounts **1. Connect the device** Plug in your Ledger or Trezor and unlock it. On a Ledger, open the **Ethereum** app. **2. Start the import** Open **Settings → Accounts → Import accounts → Connect a hardware wallet**. The app shows how the device stands until it's ready: * **Ledger:** unlock it, then open the Ethereum app, as it asks. * **Trezor Model T, Safe 3, Safe 5:** enter the PIN, and your passphrase if you use one, on the device's screen. * **Trezor Model One:** the device shows its digits shuffled on a grid; press the same places on the blank grid in the app. If it asks for a passphrase, type it in the app (leave it empty for the wallet without one). Once it's ready, choose **Continue**. **3. Pick the accounts** The app reads the device's accounts, with what each holds on Parallax, and selects those that have been used. Choose the ones to add, then **Add accounts**. More load on demand, and you can look along other paths (see below). The accounts are added to the wallet, each named **Account N** as other accounts are, and you can rename them. Nothing secret is kept: the app stores each account's address and where it is on the device. ### Derivation paths Wallets put a device's accounts along different paths. The app can look along the three in use: | Path | Where | Used by | | - | - | - | | **Ledger Live** | `m/44'/60'/n'/0/0` | Ledger Live, and MetaMask with a Ledger. The app looks here first on a Ledger. | | **Standard** | `m/44'/60'/0'/0/n` | Trezor Suite, MetaMask and most wallets. The app looks here first on a Trezor. | | **Legacy** | `m/44'/60'/0'/n` | Ledger's old Chrome app, and MyEtherWallet's older versions | Account 0 is the same address on Ledger Live's path and the standard one, so it's offered once. If you've used your device's accounts on Ethereum with Ledger Live or MetaMask, the same addresses are yours on Parallax. *** ## Hardware wallets in Settings **Settings → Accounts** gathers your accounts under **Hardware wallets**, one group per wallet your devices hold: * **Named as you like.** Each starts as **Hardware Wallet 1**, **Hardware Wallet 2** and so on, with a **Ledger** or **Trezor** badge. Point at its heading and choose the pencil to rename it. * **Told apart by the wallet, not the device.** A wallet is its recovery phrase: two devices restored from the same phrase hold the same wallet, and either signs for its accounts. On a Trezor, each passphrase opens a wallet of its own, so each has its own group. * **Find accounts** adds more of a wallet's accounts. It reads them from a connected device that holds that wallet, and says so if the one plugged in holds another. * **By path.** Where a wallet's accounts are on more than one path, they're listed under **Ledger Live**, **Standard** and **Legacy**, numbered along each. The account switcher lists them under its **Hardware** tab. > [!NOTE] > > Accounts added with an earlier version of the app are first listed under > the kind of device alone ("Ledger"). The next time you connect and unlock > that device, the app sorts them into their wallet's group. *** ## Send and sign Sending from a hardware wallet account is the same as from any other, with no password: the device confirms instead. 1. Fill in **Send** and review it, as usual. While the device isn't ready, the review says what it needs (connect it, unlock it, open the Ethereum app). 2. Choose **Sign on Ledger** (or **Trezor**). The device shows the transaction. 3. **Check it on the device**: the recipient's address, the amount and the fee must match the review. Then approve it there. To cancel, reject it on the device. The same goes for **speeding up or cancelling** a waiting transaction, and for [**signing a message**](/parallax-wallet/messages): the device shows the message to check before you approve it. ### Check your address on the device On **Receive**, a hardware wallet account has **Verify on Ledger** (or **Trezor**). The device shows the account's address: compare it with the one in the app before you share it. What a computer shows can be tampered with; what the device shows can't. ### AI assistants An [AI assistant](/parallax-wallet/ai-assistants) can ask to send from a hardware wallet account. You review the request in the app, then confirm it on the device: no password is involved. If the device isn't ready, the request waits for you to connect it and approve it again. *** ## Remove an account Removing a hardware wallet account from the app needs no password: its key stays on the device, and you can add it again any time with **Find accounts**. A wallet's group goes with its last account. *** ## Keep it safe * **Your device's recovery phrase is the backup.** The app keeps no copy of any hardware wallet key. Lose the device and you restore its accounts from its recovery phrase, on a new device or any wallet. * **Confirm only what you meant.** Check every transaction on the device's screen, not only on the computer's. * **Keep the firmware and the Ethereum app up to date**, from Ledger Live or Trezor Suite. *** ## Troubleshooting | Problem | What to do | | - | - | | The app doesn't see the device | Use a data cable (not a charge-only one), unlock the device, and close Ledger Live or Trezor Suite. On Linux, set up USB access (above). | | "Open the Ethereum app" | On the Ledger, open the Ethereum app. If it isn't there, install it from Ledger Live's My Ledger. | | "Can't open your device" | Another app has it: close Ledger Live, Trezor Suite or a browser wallet using it, then unplug it and plug it in again. On Linux, choose **Set up USB access**. | | "The device connected doesn't hold this account" | It's another wallet: another device, or on a Trezor, another passphrase. Connect the one that holds it. | | "It was turned down on the device" | You rejected it on the device. Start again to send it. | | "Wrong PIN" on a Trezor One | Enter it again on the grid: the device shuffles its digits after each try. | | The device is busy | It's waiting for you to confirm or reject something on its screen. Answer it there first. | | "Allow blind signing" | Only for contract data, which the app doesn't send. Update the Ethereum app on the Ledger. | # Installing Parallax Wallet Source: https://docs.parallaxprotocol.org/parallax-wallet/installing Download Parallax Wallet, open it on Windows, macOS or Linux, and set up your node and your wallet on first launch. ## Installing **1. Download the latest release** Visit the [Parallax Wallet releases page](https://github.com/ParallaxProtocol/parallax-wallet/releases/latest) and download the file for your computer: * **Windows (64-bit)**: `Parallax-Wallet--windows-x86_64-setup.exe` (installer) or `Parallax-Wallet--windows-x86_64.exe` (portable, runs without installing) * **macOS (Apple Silicon)**: `Parallax-Wallet--macos-arm64.dmg` * **macOS (Intel)**: `Parallax-Wallet--macos-x86_64.dmg` * **Linux (x86\_64)**: `Parallax-Wallet--linux-x86_64.AppImage` * **Linux (ARM64)**: `Parallax-Wallet--linux-arm64.AppImage` Each release includes a `SHA256SUMS.txt` file you can use to verify the download. **2. Install and open it** * **Windows**: run the installer, or open the portable `.exe` directly. The app isn't signed with a Windows certificate yet, so SmartScreen may say *Windows protected your PC*: choose **More info → Run anyway**. * **macOS**: open the `.dmg` and drag *Parallax Wallet* to *Applications*. The app isn't notarized by Apple yet, so the first time you open it macOS may refuse. Open **System Settings → Privacy & Security**, scroll down, and choose **Open Anyway** next to Parallax Wallet. * **Linux**: make the AppImage executable (`chmod +x Parallax-Wallet-*.AppImage`) and run it. Some distributions need `libfuse2` installed to run AppImages. Only one copy of Parallax Wallet runs at a time: opening it again brings the open window forward. *** ## First launch The first time you open Parallax Wallet, it greets you and sets up your node and your wallet, one question at a time. **1. Language and how you'll use this computer** Pick your language (the app starts in your system's language when it has it), then choose **Wallet with my own node**. Choose **Offline signer** only for a computer that will never go online; see [Offline signing](/parallax-wallet/offline-signing). **2. Where to keep your data** The blockchain needs room on disk. The suggested folder is fine for most people; see [Files on your computer](/parallax-wallet/settings#files-on-your-computer). **3. Help the network** **Allow inbound connections** lets other nodes connect to yours, which strengthens the network. It's recommended, and you can turn it off later. Press **Start node**. **4. Let it sync** Your node downloads the blockchain and checks it. You can wait until it's in sync, or press **Continue while it syncs** and carry on. **5. Create your wallet password** At least 8 characters. It protects every key and recovery phrase in the wallet, and it **can't be recovered**: if you lose it, only your recovery phrases and backups can bring your accounts back. **6. Set up your recovery phrase** Choose one: * **Create recovery phrase** — the app shows you 24 words. Write them down on paper, then type three of them back to confirm. You can add an optional passphrase. * **Import recovery phrase** — type the 12 to 24 words of a phrase you already have. The app finds the accounts you've used and ticks them. * **Connect a hardware wallet** — use a Ledger or Trezor; see [Hardware wallets](/parallax-wallet/hardware-wallets). ✨ Your wallet is ready. To import a private key or keystore file, or to watch an address, use **Settings → Accounts** afterwards. > [!WARNING] > > Your recovery phrase is your money. Anyone who has it can take your LAX, > and no one, including Parallax, can recover it for you. Read > [Keeping your wallet safe](/guides/wallets/keep-safe). *** ## Next steps * [Around the app](/parallax-wallet/introduction#around-the-app) — what's where. * [Accounts](/parallax-wallet/accounts) — add a private key, a keystore file or a watch-only address. * [Keeping your wallet safe](/guides/wallets/keep-safe) — what to protect, and how. # Parallax Wallet Source: https://docs.parallaxprotocol.org/parallax-wallet/introduction The desktop wallet for Parallax, with its own full node built in: hold, send and receive LAX on Windows, macOS or Linux, no terminal needed. **Parallax Wallet** is the desktop app for holding, sending and receiving LAX. It runs its own full Parallax node inside the app, so your balance and your transactions are checked by your computer rather than by someone else's server. There's no terminal and nothing else to install: download it, open it, and it walks you through the rest. The project lives at [github.com/ParallaxProtocol/parallax-wallet](https://github.com/ParallaxProtocol/parallax-wallet). *** ## Is this the right option for me? Use **Parallax Wallet** if you want to: * Keep your LAX in a wallet on your own computer, protected by a password only you know. * Create or import a recovery phrase, import a private key or keystore file, or use a [Ledger or Trezor](/parallax-wallet/hardware-wallets). * Send and receive LAX, keep an address book, and see your full history. * Run a full node that helps the network, without touching a command line. * Keep your keys on a computer that never goes online, with the [offline signer](/parallax-wallet/offline-signing). * Let an [AI assistant](/parallax-wallet/ai-assistants) read the chain through your node, with every action approved by you. Use the [**Parallax client CLI**](/guides/client/setup) if you want to run a node on a headless server, mine, or control every flag from a terminal. Parallax Wallet doesn't mine. *** ## Around the app * **The sidebar** — your current account at the top (click it to switch accounts), then **Overview**, **Send**, **Receive** and **History**; **Contacts**; and **Sign message** and **Verify message**. **Settings** sits at the bottom. * **Overview** — your balance, what's waiting to be confirmed, and your recent activity. * **The node bar** — the capsule at the bottom of the window shows whether your node is *Syncing*, *Synced* or *Offline*, its latest block, its peers and how long it has been up. Its button connects or disconnects the node. Click the bar to open the **Network** panel: the block clock, the latest blocks, your peers (where you can add, trust or block one), the mempool, and more details about your node. See [Your node](/parallax-wallet/your-node). * **The top bar** — notifications, **Lock wallet**, and an update button when a new version is ready. *** ## In this section **Get started** * [Installing](/parallax-wallet/installing) — download the app, open it, and set up your node and your wallet. * [Accounts](/parallax-wallet/accounts) — recovery phrases, single keys, hardware wallets and watch-only addresses. **Using the wallet** * [Your node](/parallax-wallet/your-node) — the Network panel: the block clock, peers, the mempool and your node's details. * [Sending and receiving](/parallax-wallet/send-and-receive) — sending, receiving, speeding up or cancelling a send, and your history. * [Contacts](/parallax-wallet/contacts) — your address book, and importing or exporting it. * [Signing messages](/parallax-wallet/messages) — prove you own an address, and check someone else's signature. * [Hardware wallets](/parallax-wallet/hardware-wallets) — use a Ledger or a Trezor. * [Offline signing](/parallax-wallet/offline-signing) — keep your keys on a computer that never goes online. **Settings and safety** * [Settings](/parallax-wallet/settings) — every section of Settings, and where the app keeps its files. * [Security](/parallax-wallet/security) — your password, locking, and what to back up. * [AI assistants](/parallax-wallet/ai-assistants) — let Claude and other assistants use your node, with every action approved by you. **Reference** * [Troubleshooting](/parallax-wallet/troubleshooting) — common problems and what to do about them. * [Updating](/parallax-wallet/updating) — how the app updates itself, and installing a new version by hand. ## Getting help In **Settings → About**, **Report a problem** and **Request a feature** open a short form on GitHub, with the app's version filled in. Never share your recovery phrase, password or a private key there, or anywhere else. # Signing messages in Parallax Wallet Source: https://docs.parallaxprotocol.org/parallax-wallet/messages Prove you control an address by signing a message with it, and check a message someone else signed. Signing a message proves you control an address without sending anything: you sign a short text with the account's key, and anyone can check the signature against the address. Exchanges, pools and other services sometimes ask for one, as does anyone who wants to know an address is yours. Parallax Wallet signs with the standard personal-message signature (EIP-191, as `personal_sign`), so signatures made here can be checked in other wallets, and the other way round. Signing a message never moves funds. *** ## Sign a message **1. Open Sign message** Choose **Sign message** in the sidebar. It signs as the account selected in the account switcher, shown under **Signing as**. **2. Write the message** Type the text to sign, for example `I control this address. 2026-10-19`. A message is 1 to 1024 bytes of text. Line breaks and tabs are fine; other control characters aren't, so what you see is everything that's signed. **3. Sign it** Choose **Sign message**. From a hardware wallet account, the device shows the message: check it there, then approve it. **4. Share it** The app shows the address, the message and the signature, each with a copy button. **Copy** copies all three together, which is what the other party needs to check it. > [!WARNING] > > Only sign text you wrote or fully understand. Anyone you give the signature > to can show it as proof that your address signed it. ### From a watch-only account A watch-only account's key is on your [offline signer](/parallax-wallet/offline-signing), so the message is signed there: 1. Write the message, then **Create signing request**. The app shows it as a QR code, and can save it as a file. 2. On the offline signer, choose **Sign** and scan the code, or open the file. Read the whole message, check that the fingerprint matches the one your everyday computer shows, then sign it. 3. Back on your everyday computer, **Scan signed message**: hold up the QR code the signer shows, or open the file it saved. The app checks that it's the message you asked for, and that the signature is from the account. *** ## Verify a message **Verify message** checks anyone's signed message. It needs no account. 1. Fill in the **message**, the **address** that's meant to have signed it, and the **signature**. Or choose **Scan or open** to fill them in from a signed message's QR code or file. 2. Choose **Verify**. The answer is one of: * **Valid signature**: the address signed exactly this message. If the address is one of your accounts or a contact, the app names it. * **Not signed by this address**: the signature is valid but made by another address, which the app shows. Either the address or the message isn't what was signed. The message must match character for character: an added space or line break changes it. > [!NOTE] > > The app takes signatures in the common `0x…` form, and also as the > `parallax-wallet signmessage` command-line tool prints them. It writes them > in the common form. # Offline signing in Parallax Wallet Source: https://docs.parallaxprotocol.org/parallax-wallet/offline-signing Keep your keys on a computer that never goes online, and send from another one with a watch-only account. For the most careful setups, Parallax Wallet can keep your keys on a computer that never connects to the network. That computer, the **offline signer**, only signs. Your everyday computer runs the wallet with its node, follows the same accounts as **watch-only**, prepares each transfer, and broadcasts it once it's signed. They pass transfers back and forth as QR codes, held up to each computer's camera, or as files, so the signer never needs a network. *** ## What you need * A computer that will stay offline, with Parallax Wallet installed as an **Offline signer**. Install the app on it before taking it offline; it never checks for updates, so install new versions by hand. * Your everyday computer with Parallax Wallet and its node. * A camera on each, or a way to carry files between them, such as a USB stick. *** ## Set up **1. Make the offline computer a signer** At first launch choose **Offline signer**, or turn on **Settings → General → Offline signer**. It never starts a node, and it hides everything that needs the network. **2. Add your accounts on the signer** Create or import them there, as on any wallet; see [Accounts](/parallax-wallet/accounts). **3. Follow them from your everyday computer** On the signer, choose **Show for watch-only** next to an account to show its address as a QR code. On your everyday computer, add it with **Settings → Accounts → Import accounts → Watch an address**, and scan it. *** ## Send **1. Create a signing request** On your everyday computer, choose the watch-only account and **Send** as usual, then **Create signing request**. The app shows it as a QR code, and **Save file…** saves it. You can leave the page: the request waits on the **Overview** until it's signed. **2. Sign it offline** On the signer, choose **Scan a signing request**, then scan the QR code or open the file. Check that the fingerprint matches the one your everyday computer shows, and that the amount and the recipient are what you meant to send. Then **Sign**. **3. Broadcast it** The signer shows the signed transaction as a QR code, or saves it as a file. On your everyday computer, **Scan signed transaction** (or **Broadcast** in the sidebar) and send it to the network. **Broadcast** also takes a raw signed transaction from the `parallax-wallet` command-line tool. *** ## Good to know * Only plain LAX transfers can be signed offline. * **Fee cap** in **Settings → General** on the signer is the most fee a signed transfer may pay; a request above it is refused. * If the signer has already signed a different transfer from the same account with the same nonce, it warns you: only one of them can go through. * To call off a request that's waiting, choose **Cancel with a replacement** on the **Overview**: it makes a new request that sends 0 LAX back to the account, which you sign and broadcast like any other. **Discard** only stops the wallet following it. * [**Sign message**](/parallax-wallet/messages#from-a-watch-only-account) works the same way for watch-only accounts: the request goes to the signer as a QR code. # Security in Parallax Wallet Source: https://docs.parallaxprotocol.org/parallax-wallet/security Your wallet password, automatic locking, and what to back up. * The wallet unlocks with your password once per session, and **locks itself** after 15 minutes of inactivity. Change that in **Settings → Security → Lock automatically**, or lock it at any time from the top bar. On macOS and Windows it also locks when your computer sleeps or its screen locks. * Showing a recovery phrase, saving a backup, removing an account and changing your password always ask for your password again. * **Settings → Security → Change password** re-encrypts every key and phrase. Backups saved before the change still open only with the old password. * Everything the wallet keeps beside your keys, such as account names, contacts and the app's logs, is encrypted too. *** ## Backing up Your wallet password protects the wallet on this computer, but it isn't a backup. If this computer is lost or broken, what brings your accounts back is: * **Your recovery phrases**, written on paper. * **Your single keys' backup files**, saved with **Save backup** in **Settings → Accounts**. * **Hardware wallet accounts** are backed up by the device's own recovery phrase. Read [Keeping your wallet safe](/guides/wallets/keep-safe) for how to store them. # Sending and receiving in Parallax Wallet Source: https://docs.parallaxprotocol.org/parallax-wallet/send-and-receive Send and receive LAX, speed up or cancel a send that's waiting, and follow your history in Parallax Wallet. Sending, and seeing your balance and activity, go through your own node: it needs to be running and in sync. Your addresses and keys work without it, so **Receive** always shows your address. For how sending works on Parallax in general, see [Sending and receiving LAX](/guides/wallets/send-and-reveive). *** ## Receive **Receive** shows your address, a **Copy** button and a QR code. You can use the same address as many times as you like. Only send LAX on the Parallax network (chain ID 2110) to it. For a hardware wallet account, choose **Verify on Ledger** (or **Trezor**) to check the address on the device before you share it; see [Hardware wallets](/parallax-wallet/hardware-wallets#check-your-address-on-the-device). *** ## Send **1. Fill in the recipient and the amount** **Send** takes an address, or a contact's name from your [Contacts](/parallax-wallet/contacts). It says when the address is one of your own accounts or a contact. **Max** sends your whole balance less the fee. **2. Choose the fee** The network fee is **Suggested** by your node, from recent blocks and its pool, or **Custom** if you'd rather pay more to get into a block sooner. A custom fee can't go below the suggested one: a transaction that waits holds back every later one from the same account. **3. Review and send** **Review and sign** shows the recipient in full (check every character against the address you were given), the amount, the network fee and the total. It warns you when something looks off: sending to the same account, sending to a contract, or a fee more than three times what your node suggests. Then **Sign and send**: a hardware wallet account confirms on the device, and a watch-only account makes a signing request for your [offline signer](/parallax-wallet/offline-signing). While the node is offline or still syncing, **Send** says so and waits: connect, or let it finish syncing, first. *** ## A send that's waiting A send stays **Pending** until a miner puts it in a block. From its row in your activity you can: * **Speed up**: send the same transaction again with a higher fee, so miners take it sooner. It replaces the original. * **Cancel**: send 0 LAX to your own account in its place, with a higher fee, so miners take it instead. Only the fee is spent. Either way, if the original makes it into a block first, the replacement has no effect and costs nothing. The wallet keeps each of its sends until it's in a block, and sends it to the network again whenever the node starts or the wallet unlocks. A send the node lost by restarting still reaches its peers. *** ## History **History** lists everything an account has sent, received and mined: * **Filters** for **Received**, **Sent**, **Mined** and **Failed**. * **Search** by contact, address, transaction hash or block number, and **Go to a date**. Search by hash reaches back as far as the node's transaction index, about a year of blocks: go to an older transaction's date instead. * **Export** saves what's shown as a CSV file. On a new install, the history is indexed in the background: the latest activity shows at once, and older activity appears as indexing goes on (**Indexing history**, with its progress). Export is available once it's done. *** ## See also * [Contacts](/parallax-wallet/contacts): send to people by name. * [Signing messages](/parallax-wallet/messages): prove you own an address without sending anything. # Settings in Parallax Wallet Source: https://docs.parallaxprotocol.org/parallax-wallet/settings What each section of Settings holds, and where Parallax Wallet keeps its files. ## Settings | Section | What's there | | - | - | | **General** | Language, open at login, starting the node automatically, keeping the computer awake while syncing, notifications, automatic update checks, and offline signing | | **Appearance** | Theme (System, Light or Dark), account avatars, and turning off animations | | **Privacy** | **Use Tor**: send everything the app sends through Tor (the node's peers, the update check, and what assistants look up), with the app's own Tor or one already running on this computer, and whether the node reaches all peers or only onion ones | | **Storage** | Where the wallet and the node's data live, moving them, the node's minimum free disk space, deleting the chain data, and deleting the wallet | | **Accounts** | Creating, importing, backing up and removing accounts | | **Security** | Your wallet password and automatic locking | | **Node** | Sync mode (*Snap*, recommended, or *Full*), caches, fee estimation and the transaction pool | | **Network** | Inbound connections, the listening port, peers, port mapping, and a SOCKS5 proxy for the node's peer connections | | **RPC** | The node's HTTP-RPC (on by default, at `127.0.0.1:8545`), WebSocket and other interfaces | | **AI assistants** | Letting AI assistants use your node and wallet, and what they may do; see [AI assistants](/parallax-wallet/ai-assistants) | | **Diagnostics** | Log level, clearing the logs on startup, and the node's and the app's live logs | | **About** | The app's version, checking for updates, release notes, and ways to report a problem or request a feature; see [Updating](/parallax-wallet/updating) | Changes take effect when you **Save**; the few that need the node or the app to restart say so. Advanced options show the command-line flag they match, if you also use the [CLI client](/guides/client/setup). > [!NOTE] > > Your node's HTTP-RPC is what other wallets connect to. To use MetaMask > with your own node, point it at `http://127.0.0.1:8545`; see > [Setting up MetaMask](/guides/wallets/metamask). It only listens on your own > computer unless you change its listen address. *** ## Files on your computer The node's data (the blockchain) goes in the same places as the CLI client's, unless you chose another folder: * **Windows**: `%LOCALAPPDATA%\Parallax` (or `%APPDATA%\Parallax` if an older install already uses it) * **macOS**: `~/Library/Parallax` * **Linux**: `~/.parallax` The app's settings (`gui.json`) and your wallet (its encrypted keys, phrases, contacts and logs) live in a `Parallax` folder in your system's app-config folder: * **Windows**: `%APPDATA%\Parallax` * **macOS**: `~/Library/Application Support/Parallax` * **Linux**: `~/.config/Parallax` **Settings → Storage** shows both, and can move them. Because the node uses the same data directory as the CLI client, you can switch between them without downloading the chain again. > [!WARNING] > > These folders are not a backup. If this computer is lost or broken, what > brings your accounts back is your recovery phrases, written on paper, and > your single keys' backup files, saved with **Save backup**. # Troubleshooting Parallax Wallet Source: https://docs.parallaxprotocol.org/parallax-wallet/troubleshooting Common Parallax Wallet problems and what to do about them: installing, the node, sending, a forgotten password, and where to find the logs. ## Installing and opening | Problem | What to do | | - | - | | Windows says *Windows protected your PC* | The app isn't signed with a Windows certificate yet. Choose **More info → Run anyway**. | | macOS won't open the app | It isn't notarized by Apple yet. Open **System Settings → Privacy & Security**, scroll down and choose **Open Anyway** next to Parallax Wallet. | | The AppImage doesn't start on Linux | Make it executable (`chmod +x Parallax-Wallet-*.AppImage`). Some distributions need `libfuse2` installed to run AppImages. | | Opening the app only brings a window forward | Parallax Wallet is already running: only one copy runs at a time. | *** ## The node | Problem | What to do | | - | - | | The node bar says **Couldn't start** | Point at it to read why, in full. The cases below are the common ones. | | `datadir already used by another process` | Another node is using the same data directory, usually the [CLI client](/guides/client/setup) (`parallaxd`), which shares it by default. Stop it, then **Connect**. | | `address already in use` | Another program, often another node, holds a port the node needs: the peer port (32110), HTTP-RPC (8545) or WebSocket. Stop it, or choose other ports in **Settings → Network** and **Settings → RPC**. | | Stuck on **Looking for peers** | The node can't reach the network. Check your internet connection and that your firewall lets Parallax Wallet out. With **Use Tor** on, check that Tor is connected. You can also add a peer by hand; see [Peers](/parallax-wallet/your-node#peers). | | **Waiting for Tor** | With **Use Tor** on, the node starts only once Tor is connected, so nothing goes out directly. If Tor can't connect, turn it off in **Settings → Privacy**, or use the Tor already running on this computer. | | The node stopped, and a notification says the disk is nearly full | The node stops itself before its database runs out of space, which could corrupt it. Free up space, then **Connect**. The level is **Settings → Storage → Minimum free disk space**. | | Syncing is slow | The first sync takes hours, and more on a slow disk or connection. Keep the app open, turn on **Keep the computer awake** in **Settings → General**, and keep the node's data on an SSD. | | **Restart to apply your changes** | A setting you saved needs the node to restart. Use the button on the node bar. | If the chain data is damaged beyond what the node can recover from, **Settings → Storage → Delete chain data** removes the downloaded blockchain for the node to download it again. Your wallet and its accounts aren't touched, but syncing again takes hours. *** ## Balance and sending | Problem | What to do | | - | - | | No balance, or **Connect to see your balance** | Balances and activity come from your node: connect it, and wait for it to finish syncing. | | **Wait for the node to finish syncing before sending** | Sending needs the node in sync. Wait for **Synced** on the node bar. | | A send stays **Pending** | Miners haven't taken it yet, often because its fee is low. **Speed up** or **Cancel** it from its row; see [A send that's waiting](/parallax-wallet/send-and-receive#a-send-thats-waiting). | | A later send waits behind an earlier one | Sends from an account go into blocks in order. Speed up or cancel the earliest one that's waiting. | | Older activity is missing | On a new install the history is indexed in the background: older activity appears as it goes on. | | A transaction can't be found by its hash | Search by hash reaches about a year back. Go to the transaction's date instead. | *** ## The wallet | Problem | What to do | | - | - | | **Some of the wallet's files were damaged** | The app set them aside and opened with the last copy it could read, or without them. It lists what was affected (account names, contacts, signing requests and so on). Your keys and recovery phrases aren't in these files. | | The wallet locks itself | It locks after 15 minutes of inactivity. Change that in **Settings → Security → Lock automatically**. | | Accounts from a recovery phrase aren't the ones you expect | The other wallet may use another derivation path; see [Finding the right accounts](/parallax-wallet/accounts#finding-the-right-accounts). | | A Ledger or Trezor isn't seen, or won't sign | See [Hardware wallets → Troubleshooting](/parallax-wallet/hardware-wallets#troubleshooting). | | An AI assistant can't connect or is refused | See [AI assistants → Troubleshooting](/parallax-wallet/ai-assistants#troubleshooting). | ### Forgotten wallet password Your wallet password can't be recovered or reset: nobody, including Parallax, can open the wallet without it. What brings your accounts back is your recovery phrases and your single keys' backup files. To start over with a new password: **1. Make sure you have your backups** Your recovery phrases, written down, and the backup file of each single key, with the password it was saved with. Hardware wallet accounts are backed up by the device. Without these, the accounts can't come back. **2. Set the old wallet aside** Quit Parallax Wallet. In the app's config folder (see [Files on your computer](/parallax-wallet/settings#files-on-your-computer)), rename the `Parallax` folder, for example to `Parallax-old`. Keep it: if you remember the password later, renaming it back brings the wallet back. **3. Set up again** Open Parallax Wallet. It starts as on a first launch: if you had moved the node's data, choose the same folder, so it doesn't download the chain again. Then set a new password, and import your recovery phrases and backups; see [Accounts](/parallax-wallet/accounts). If you had moved the wallet's folder in **Settings → Storage**, it isn't in the config folder: rename that folder too. On Windows, an older install may keep the node's data in `%APPDATA%\Parallax` as well: it's set aside with the rest, and the node downloads the chain again. *** ## Logs and crash reports * **Settings → Diagnostics** shows the node's and the app's logs live, with a filter and a pause. Turn up **Log level** there to see more. * The logs are kept across restarts, encrypted so that only your unlocked wallet can read them. **Clear logs on startup** starts each launch with an empty log instead. * If the app crashes, it writes a report named `crash-