Skip to content
Developer Handbook

Wallet sync

On this page

Your wallet knows the locking scripts for its receiving and change addresses. To show its balance, it finds payments to those scripts and checks whether those payments were spent later. An outpoint identifies a specific UTXO by its transaction ID and zero-based output index. In this walkthrough, you’re looking for the 100,000-sat UTXO.

Choose a wallet sync method

Ask three questions when syncing a wallet. Which transactions paid it? Which of those transactions made it into a block? Which UTXOs are still spendable? The methods below trade off what you have to download, who sees your queries, and what you verify yourself.

Find activity on both address branches

On restore, derive addresses along the wallet’s original receiving and change paths. Scan each branch until you reach the configured number of unused addresses beyond the last address used or handed out. An address with past transactions counts as used even when its balance is zero. Save the last used and issued address indices so the wallet can extend that search window as activity arrives.

Fulcrum Protocol

Subscribe to a script’s status

Fulcrum is a wallet server backed by a full node. Wallets use the Fulcrum protocol, also known as Electrum Cash, to query its index and subscribe to updates. Fulcrum indexes transactions by the script hash, the reversed SHA-256 of the locking bytecode. Decode the CashAddr to get that bytecode before hashing it. The status hash summarizes the history the server currently reports for that script.

import { binToHex, cashAddressToLockingBytecode, sha256 } from '@bitauth/libauth';

const decoded = cashAddressToLockingBytecode(
  'bitcoincash:qze9274lawhjvwpyka0vgula0v7mwj2hageduvrmrl'
);
if (typeof decoded === 'string') throw new Error(decoded);
const scriptHash = binToHex(sha256.hash(decoded.bytecode).reverse());
// 0233a5fffd274216a24c79d70299ef982a444b237865143ac09a876b969e7b13
  1. Negotiate the protocol with server.version. Confirm the endpoint is on mainnet by comparing a known block hash with your node or a trusted checkpoint.
  2. Use blockchain.headers.subscribe to follow the chain tip, the latest block the server reports. It returns the block header, which identifies the block and commits to its transactions. Save the tip’s height and hash with your wallet state. Subscribe to blockchain.scripthash.subscribe for each watched script. The response supplies its current status, or null for an unused script.
  3. Compare the current status with the one saved for that script. Fetch the history for a new or changed status. Reconcile the chain tip separately, since the tip can advance while a script's history stays the same.
  4. Subscribe to more scripts as either branch approaches the end of its look-ahead window. Keep signing keys local.

Script status specification · Protocol methods

Reconcile history and UTXOs

  1. Check the history against the announced status. Request blockchain.scripthash.get_history. Join the history entries as txid:height: with lowercase display-order IDs, decimal heights, and no separators beyond the colons. Hash the UTF-8 bytes with SHA-256 and encode the digest as hex. Empty history has status null.
    • Sort confirmed entries by block height and by position within each block.
    • Unconfirmed entries follow the protocol’s canonical order. Their height is 0 when all inputs are confirmed and −1 when any input is unconfirmed.
    • Protocol 1.6 specifies sorted history responses. On older servers, verify the returned order reproduces the status or reconstruct the required order before accepting the result.
  2. Track the UTXOs created and spent. Download each missing raw transaction with blockchain.transaction.get. Recompute its transaction ID and decode the bytes. Record outputs whose locking scripts belong to the wallet and mark any outpoints spent by the reported inputs. Deduplicate transactions shared by multiple wallet scripts. Record confirmed and pending activity separately.
  3. Check the current view. Request blockchain.scripthash.listunspent. For token-aware BCH sync, negotiate 1.5 or later and request include_tokens. Match each returned tx_hash and tx_pos to its decoded output. Convert validated integer satoshi amounts to bigint. Keep decoded CashTokens category, fungible amount, and any NFT capability and commitment with the outpoint.
  4. Save a consistent snapshot. If a status or tip changes during the refresh, repeat the affected queries. Save the history, UTXOs, status, and tip together after reconciliation. Before spending, check whether a time restriction or an immature miner reward makes the UTXO unavailable. Preserve any tokens assigned to that UTXO.

Handle mempool changes, reorgs, and reconnects

A node keeps accepted but unconfirmed transactions in its mempool. A status change tells you to check whether the wallet’s transactions confirmed, were evicted, or now conflict with a different spend.

When a competing branch replaces part of the active chain, find the last block they share. Undo confirmations and spends from the removed blocks before applying the new branch and current mempool. After reconnecting, restore your subscriptions and compare the latest tip and statuses with the ones you saved.

Know what each check establishes

Discovery
History shows the transactions the server reports for your script. The status hash checks that the history matches its announcement.
Inclusion
For an independent inclusion check, request blockchain.transaction.get_merkle. The proof gives the hashes you combine with the transaction ID to reproduce the Merkle root, the hash that commits to the transactions in a validated block header.
Current spendable view
Inclusion proves the transaction appeared in a block. To learn whether an output remains unspent, track subsequent spends and mempool changes or query a node or index you trust.

Test the protocol on Chipnet

Download sync.mjs and package.json into one directory. With Node.js 22 or newer, install the dependencies and run the example with a Chipnet address. You can use your own address from the Chipnet lab.

npm install
node sync.mjs bchtest:qqptjuvw2sc3qeaynjgsg0cf6c0zsfx96gvce7z29g
node sync.mjs CHIPNET_CASHADDR PREVIOUS_STATUS

The public example address has a small transaction history on Chipnet. The program queries it over secure WebSockets. It compares the subscribed status with the returned history, reconstructs unspent outpoints from decoded transactions, and checks that the status and tip stayed consistent. It prints a snapshot for one script. To keep a wallet in sync, extend it with HD discovery, persistent subscriptions, and validated headers and Merkle proofs.

Direct peer-to-peer sync with SPV

Start with the network’s first block, called genesis, or a trusted checkpoint. Use getheaders to extend the header chain. Check each header’s link, difficulty, and proof of work, then compare accumulated work across valid branches. Download blocks with getdata and look for the wallet’s scripts and spent outpoints. For simple payment verification (SPV), recompute the block’s Merkle root from its transactions or verify an inclusion proof against the validated header. Older BIP37 peers can return a partial Merkle tree from merkleblock after receiving a Bloom filter, which discloses the matching interest to the peer. SPV reference · Bloom-filter reference

Try the shared P2P and Neutrino example against an isolated peer.

Neutrino compact-filter sync

A compact filter summarizes the data in a block. A Neutrino client checks its wallet scripts against each filter locally. A match can be a false positive, so the client downloads that block to check for actual payments and spends. BCH’s Neutrino implementation is used by BCH Wallet. It needs a BCH peer on the selected network that serves committed filters. The wire messages include getcfheaders and getcfilters with the regular filter type. Verify filter-header continuity and consult multiple peers or trusted checkpoints for filter history. Use the validated block chain for inclusion. Track later spends and handle mempool visibility separately.

Try both P2P methods on an isolated peer

Use BCHD v0.22.4 and Go 1.26 or newer. In an empty directory, download main.go, go.mod, and go.sum. Start a private regression-test node bound to loopback. The mining address uses this node’s address prefix with the same locking script you derived in the guide. BCHD release

mkdir -p peer/data peer/log
touch peer/bchd.conf
bchd --configfile="$PWD/peer/bchd.conf" --regtest --regtestnoreset \
  --datadir="$PWD/peer/data" --logdir="$PWD/peer/log" --nodnsseed \
  --listen=127.0.0.1:18449 --rpclisten=127.0.0.1:18448 --notls \
  --rpcuser=demo --rpcpass=laboratory-only \
  --miningaddr=bchreg:qze9274lawhjvwpyka0vgula0v7mwj2hag8rw2zl89

From a second shell in the same directory, mine one block and connect to the peer in each mode.

bchctl --configfile="$PWD/peer/bchd.conf" --notls -u demo -P laboratory-only \
  -s 127.0.0.1:18448 generate 1
go run . -mode=p2p
go run . -mode=neutrino

Both modes were verified against an isolated BCHD v0.22.4 node. The example checks the first header against regression-test genesis and verifies the single transaction’s Merkle commitment. The Neutrino mode also checks the announced filter hash and matches the script locally before downloading the block. This is a one-block wire demonstration. A full client would track header and filter history across peers, maintain reorg state, and apply all relevant spendability checks.

Full-node RPC

A full node verifies blocks and transactions under the consensus rules. Its remote procedure call (RPC) interface lets your wallet read those blocks and scan for scripts and spent outpoints. You can also use a wallet or index connected to the node. Once you know an outpoint, you can query the node’s current UTXO set directly.

Check a known outpoint

Use the transaction ID printed by the P2P or Neutrino example. Ask the node whether output 0 remains unspent, taking its mempool into account.

bchctl --configfile="$PWD/peer/bchd.conf" --notls -u demo -P laboratory-only \
  -s 127.0.0.1:18448 gettxout TRANSACTION_ID 0 true

This query was verified against the same block. It returned the output’s value, locking script, confirmation count, and coinbase flag. The output is unspent and immature after one block. Run Fulcrum · Full-node JSON-RPC reference

Chain indexer queries with Chaingraph

Look up a transaction by ID

A chain indexer serves queries over data it has collected from one or more nodes. This example reads one transaction by ID using Chaingraph’s GraphQL API. The example looks up the first block’s miner reward transaction, called the coinbase.

from hashlib import sha256
from json import dumps, load
from urllib.request import Request, urlopen

txid = '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b'
query = """query ReadTransaction($hash: bytea!) {
  transaction(limit: 1, where: {hash: {_eq: $hash}}) { encoded_hex }
}"""
body = dumps({'query': query, 'variables': {'hash': '\\x' + txid}}).encode()
request = Request('https://gql.chaingraph.pat.mn/v1/graphql', data=body,
                  headers={'Content-Type': 'application/json'})
with urlopen(request, timeout=10) as reply:
    rows = load(reply)['data']['transaction']
raw = bytes.fromhex(rows[0]['encoded_hex'])
assert sha256(sha256(raw).digest()).digest()[::-1].hex() == txid
print(raw.hex())

This query was verified against the public index. It checks raw bytes against a known transaction ID. To use an index for wallet sync, select the intended network and node observations, then track payments, spends, and reorganizations. A transaction lookup alone gives no current UTXO status. Chaingraph API and schema

Find the example UTXO

In the payment walkthrough, derive the address and select Find UTXO. Check the outpoint, value, and locking script against the funding transaction. You should see 100,000 sats at output 0 of the funding transaction.