XChain Regtest Miner: Operations
Prerequisites
- Node.js 22 (22.x LTS), the platform’s canonical runtime, pinned in
.nvmrc - A running regtest coin node (bitcoind, litecoind, or dogecoind) with JSON-RPC enabled
- The coin node must be in regtest mode with wallet support enabled
Running the Miner
npm run api
On startup, the miner:
- Validates all 6 required environment variables (exits on failure)
- Connects to the coin node via JSON-RPC
- Creates or loads the
xchain_regtest_walletwallet - Mines 101 bootstrap blocks if the chain is fresh (coinbase maturity)
- Begins the 100 ms mempool polling loop
- Starts the Express JSON-RPC API server on
REGTEST_MINER_API_PORT
Docker
When managed by xchain-node, the regtest miner runs as a Docker container:
- Image: Alpine Node 22 with non-root user
- Healthcheck: JSON-RPC
healthcall, which answers 503 when the miner is stalled (pingalways answers 200) - Security headers: Helmet (CSP, X-Frame-Options, etc.)
- CORS: Enabled for cross-origin access
The container is only created for regtest networks; it is automatically excluded from mainnet and testnet installations.
Stopping
The miner handles SIGTERM gracefully; it allows the current mining loop iteration to complete before exiting. No data corruption occurs on shutdown.
JSON-RPC API
The miner exposes a JSON-RPC 2.0 API via Express for test orchestration. All methods are called via HTTP POST.
Authentication
By default the API is open (no auth), matching the encoder/hub opt-in pattern. Setting the MINER_API_KEY environment variable requires a matching X-API-Key header on every request; a missing or wrong key returns HTTP 401. The read-only health methods ping, status and health always bypass the key gate, so Docker healthchecks and uptime monitors keep working on keyed deployments. Only read-only methods belong in this exempt set.
Note that the miner refuses to start when NETWORK is mainnet (only regtest and testnet are accepted): send_funds would otherwise expose a default-unauthenticated way to spend the node wallet.
ping
Health check endpoint.
Request:
{
"jsonrpc": "2.0",
"method": "ping",
"id": 1
}
Response:
{
"jsonrpc": "2.0",
"result": { "status": "success", "ready": true },
"id": 1
}
The ready field reflects wallet preparation (mine-readiness), not just that the port is listening. Callers that depend on mining should gate on ready: true.
status
Return the current mining loop state for operator diagnostics and CI health checks.
Request:
{
"jsonrpc": "2.0",
"method": "status",
"id": 2
}
Response:
{
"jsonrpc": "2.0",
"result": {
"wallet_ready": true,
"wallet_balance": 50.0,
"wallet_funded": true,
"wallet_balance_at": 1718900003000,
"mempool_size": 0,
"mempool_size_at": 1718900004000,
"idle_mine_interval_ms": 0,
"blocks_mined": 42,
"last_mine_at": 1718900000000,
"consecutive_errors": 0,
"mine_failures": 0,
"mining_paused": false,
"mining_started": true
},
"id": 2
}
| Field | Type | Description |
|---|---|---|
wallet_ready |
boolean | true once prepareWallet has completed; gates on mine-readiness, not just server availability. It marks startup completion only and stays true across a reorg, even one that leaves the wallet unable to fund a send; read wallet_funded for that. |
wallet_balance |
number or null | The wallet’s spendable balance in coin units from the last getbalance read. null when no read has happened or the last read failed; neither null nor 0 counts as funded. |
wallet_funded |
boolean | true only when wallet_balance is a number above 0. Use this, not wallet_ready, to learn whether the wallet can still fund a send (for example after a deep invalidate_block). |
wallet_balance_at |
number or null | Unix timestamp in milliseconds of the last balance read attempt, successful or not; null before the first read |
mining_paused |
boolean | true while the auto-mine loop is paused (pause_mining, or a fill_mempool/invalidate_block that never resumed). If mining seems stalled, check this first. |
mining_started |
boolean | true once wallet preparation finished and the auto-mine loop started; a pause never resets it. A miner still starting reads mining_paused: true with mining_started: false. |
mempool_size |
number | Number of transactions in the mempool read started by this status request; use only when consecutive_errors is zero |
mempool_size_at |
number or null | Unix timestamp in milliseconds of the successful mempool read started by this status request; unchanged when that read fails |
idle_mine_interval_ms |
number | Current mine-empty heartbeat interval in milliseconds; 0 means mining is driven only by the mempool (see set_idle_mine_interval) |
blocks_mined |
number | Cumulative count of blocks mined by this miner instance since startup |
last_mine_at |
number or null | Unix timestamp in milliseconds (Date.now()) of the most recent successful block mine; null if no block has been mined yet in this session |
consecutive_errors |
number | Running count of consecutive RPC failures (either getrawmempool or generatetoaddress). Resets to 0 on the next successful RPC call. Useful for alerting: a non-zero value means the miner is retrying with exponential backoff. |
mine_failures |
number | Consecutive failed block mines, on a streak of its own: a successful mempool read zeroes consecutive_errors, so that counter cannot show a miner that answers RPC but cannot generate a block. Resets on the next mined block; health reports it as a stall reason. |
Balance freshness. The balance is read at startup, re-read before invalidate_block and reconsider_block return, and refreshed by the auto-mine loop at most every 5 seconds, including while mining is paused or fill_mempool is running. A single failed read, a node restart included, shows as wallet_balance: null and wallet_funded: false for one interval and then recovers, so re-poll once before concluding the wallet is drained. A wallet_balance_at well over 5 seconds old while mining_started is true means the refresh has stalled.
health
Readiness probe read by the container healthcheck. Unlike ping, it answers HTTP 503 when mining is stalled: past the cold-start grace window, a wallet that never became ready, a loop that never started, or a run of consecutive errors or failed mines at the stall threshold. A deliberate pause is never a stall.
Request:
{
"jsonrpc": "2.0",
"method": "health",
"id": 3
}
Response:
{
"jsonrpc": "2.0",
"result": {
"status": "success",
"reason": "ok",
"wallet_ready": true,
"consecutive_errors": 0,
"mine_failures": 0,
"mining_paused": false,
"mining_started": true
},
"id": 3
}
status is degraded when unhealthy, and reason is one of starting, ok, paused, wallet_not_ready, not_started, consecutive_errors or mine_failures.
send_funds
Send regtest coins to a specified address.
Request:
{
"jsonrpc": "2.0",
"method": "send_funds",
"params": {
"address": "bcrt1q...",
"amount": 1.0
},
"id": 3
}
| Parameter | Type | Required | Description |
|---|---|---|---|
address |
string | Yes | Recipient address |
amount |
number | Yes | Amount in coin units (must be > 0) |
fill_mempool
Broadcast multiple transactions to stress-test the mempool.
Request:
{
"jsonrpc": "2.0",
"method": "fill_mempool",
"params": {
"tx_quantity": 100
},
"id": 4
}
| Parameter | Type | Required | Description |
|---|---|---|---|
tx_quantity |
number | Yes | Number of transactions to create (1–50,000) |
This method pauses auto-mining during execution and restores it automatically when done. A mutex prevents concurrent calls.
pause_mining
Pause the auto-mine loop. Any block already in flight at the time of the call completes normally. Use continue_mining to resume.
Request:
{
"jsonrpc": "2.0",
"method": "pause_mining",
"id": 5
}
continue_mining
Resume auto-mining after a pause.
Request:
{
"jsonrpc": "2.0",
"method": "continue_mining",
"id": 6
}
set_mining_time
Override timer durations at runtime.
Request:
{
"jsonrpc": "2.0",
"method": "set_mining_time",
"params": {
"max_time": 60000,
"tx_added_time": 10000
},
"id": 7
}
| Parameter | Type | Required | Description |
|---|---|---|---|
max_time |
number | Yes | Max timer in milliseconds (1,000–3,600,000) |
tx_added_time |
number | Yes | Extension timer in milliseconds (1,000–3,600,000) |
set_default_mining_time
Reset timers to defaults (30,000 / 5,000 ms).
Request:
{
"jsonrpc": "2.0",
"method": "set_default_mining_time",
"id": 8
}
set_mock_time
Pin the coin node’s clock (setmocktime) so the next generate_blocks stamps its block at that time. Used to make time-based expiries fire at a deterministic block. Refused on mainnet.
Request:
{
"jsonrpc": "2.0",
"method": "set_mock_time",
"params": { "timestamp": 1718900000 },
"id": 8
}
| Parameter | Type | Required | Description |
|---|---|---|---|
timestamp |
number | Yes | Unix time in seconds, non-negative. 0 releases the mock clock. |
Returns "ok" once the node confirms the pin; any failure returns an error object.
set_idle_mine_interval
Turn the mine-empty heartbeat on or off at runtime. The mining loop is mempool-driven: with no transactions arriving it mines nothing, so an idle chain never gains height and anything gated on height (stake activation delays, confirmation depth, time-locked expiries) waits forever. With an interval set, the loop mines one empty block each time the mempool has been empty that long.
Use generate_blocks to JUMP a height window; use this to WAIT one out on a quiet chain.
Request:
{
"jsonrpc": "2.0",
"method": "set_idle_mine_interval",
"params": {
"interval_ms": 5000
},
"id": 9
}
| Parameter | Type | Required | Description |
|---|---|---|---|
interval_ms |
number | Yes | Milliseconds of empty mempool before mining one empty block. 0 disables. Otherwise 1,000 to 3,600,000. |
The boot-time equivalent is the IDLE_MINE_INTERVAL_MS environment variable. The current value is reported as idle_mine_interval_ms by status.
generate_blocks
Mine a specific number of blocks immediately, regardless of mempool state; the blocks are mined through the node’s generatetoaddress, so they pick up transactions waiting in the mempool and { "count": 1 } confirms a pending transaction. Used by e2e tests to advance block height past time-locked states (such as STAKE activation delays).
Request:
{
"jsonrpc": "2.0",
"method": "generate_blocks",
"params": {
"count": 10
},
"id": 9
}
| Parameter | Type | Required | Description |
|---|---|---|---|
count |
number | Yes | Number of blocks to mine (a positive integer, at most 10000; a larger value is rejected with an error) |
Response:
{
"jsonrpc": "2.0",
"result": { "count": 10, "hashes": ["..."] },
"id": 9
}
invalidate_block
Mark a block as invalid so the node rolls back to the fork point. Auto-mining is paused; call continue_mining when the reorg is complete. Together with reconsider_block, this enables deterministic reorg tests without dropping to raw node RPC.
Request:
{
"jsonrpc": "2.0",
"method": "invalidate_block",
"params": { "block_hash": "..." },
"id": 10
}
reconsider_block
Remove a block from the invalid set so the node can re-evaluate chain selection. Call after mining the competing branch, before continue_mining.
Request:
{
"jsonrpc": "2.0",
"method": "reconsider_block",
"params": { "block_hash": "..." },
"id": 11
}
Resilience
Exponential Backoff
When the coin node is unreachable (ECONNREFUSED, timeout, DNS failure), the miner retries with capped exponential backoff from 200 ms to 30 seconds. The attempt counter resets on the first successful call.
Pinned Wallet Fee Rate
On a matured regtest chain, the node’s estimatesmartfee can inflate to absurd rates, pushing funding-send fees above -maxtxfee and failing send_funds/fill_mempool with RPC error -6 (easily misread as UTXO exhaustion). prepareWallet therefore pins a fixed funding fee ceiling, by whichever mechanism the coin’s daemon implements. The ceiling is 0.001 coins/kB, which is the same rate as 100 sat/vB.
The coin is the part of NETWORK before the first - (bitcoin, litecoin, dogecoin); a bare regtest has no coin.
| Mechanism | Used by | What sendtoaddress sends |
|---|---|---|
fee_rate |
Bitcoin, always: Core 31 deleted settxfee, so the miner never calls it on BTC. Also Litecoin or a bare regtest whose settxfee answers method-not-found (-32601), and Litecoin whose settxfee stays unreachable through its retries. |
Named params { address, amount, fee_rate: 100 } on every call |
settxfee |
Litecoin, Dogecoin and a bare regtest whose daemon accepts settxfee 0.001 (the normal path for LTC v0.21 and DOGE v1.14) |
Positional [address, amount]; the wallet-wide pin caps the fee |
| none (fee estimate) | A daemon that refuses the rate (any other RPC error, or a reply that is not true); Dogecoin without settxfee, since DOGE v1.14 refuses fee_rate; Dogecoin or a bare regtest whose settxfee stays unreachable |
Positional [address, amount]; estimatesmartfee sets the fee |
Bitcoin has no fallback to the estimate: falling back would give the ceiling up on exactly the chain that needs it. A settxfee that times out, loses its transport or answers warmup (-28) is tried up to three times before it counts as unreachable.
settxfee is in-memory wallet state and is lost when the node restarts, so the miner pins again after it reloads a lost wallet, both on the send_funds retry and from the background balance read. A re-pin whose settxfee cannot be reached keeps a per-call fee_rate already in force.
Startup logs name the mechanism in force: via the per-call fee_rate argument, via settxfee, or funding sends use the fee estimate. On Bitcoin a funding -6 never comes with a settxfee call or log line, so look for the per-call fee_rate line instead.
Error Sanitization
RPC credentials (NODE_USER, NODE_PASSWORD) are never included in error messages or console output. Error responses include sanitized messages only.
Concurrent Call Protection
The fillMempool method uses a mutex to prevent overlapping stress test runs. If called while another fillMempool is in progress, the second call is rejected. The keepMining flag is automatically restored in a finally block even if an error occurs.
Troubleshooting
Miner exits on startup with “Missing environment variable”
All 6 environment variables are required. Check your .env file or Docker container environment. See Configuration for the full list.
Miner cannot connect to coin node
Error: connect ECONNREFUSED 127.0.0.1:18444
The coin node is not running or not listening on the expected port. Verify:
bitcoin-cli -regtest getblockchaininfo
No blocks being mined
If the miner is running but not mining, check:
- Is
keepMiningset tofalse? Callcontinue_miningto resume. - Is the mempool empty? The miner only mines when transactions are present.
- Are the timers set to very large values? Call
set_default_mining_timeto reset.
fillMempool fails or hangs
- Check that the wallet has sufficient balance for the requested transaction count
- Ensure
tx_quantityis between 1 and 50,000 - Check coin node logs for RPC errors
- If a previous
fillMempoolcrashed, the mutex may be locked, restart the miner
Port already in use
Error: listen EADDRINUSE :::3005
Another process is using REGTEST_MINER_API_PORT. Change the port in .env or stop the conflicting process.
Copyright © 2025–2026 Dankest, LLC
Based on XChain Platform by Dankest, LLC – https://dankest.llc
Licensed under the GNU Affero General Public License v3.0 (AGPL-3.0-or-later) with a commercial license available for proprietary use.
You may use, modify, and distribute this material under the terms of the License. See LICENSE and NOTICE for full terms. See the licensing overview.