Skip to content

test: replace hard-coded RPC error codes - #36990

Open
l0rinc wants to merge 3 commits into
bitcoin:masterfrom
l0rinc:l0rinc/test-rpc-error-codes
Open

l0rinc wants to merge 3 commits into
bitcoin:masterfrom
l0rinc:l0rinc/test-rpc-error-codes

Conversation

@l0rinc

@l0rinc l0rinc commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Problem: When a test expects an RPC error by number, readers have to look up the code to tell which failure it covers.

Fix: Use the RPCErrorCode names in the C++ RPC tests and mirror the enum in the Python test framework.
Give the test client’s errors their own constants so AuthServiceProxy and TestNodeCLI can share the HTTP error code.

I split this out while reviewing #36976.

Compare the original numeric error codes

Run this diff to inline the constants back to validate that the values haven't changed.

sed -Ei -f /dev/stdin $(git diff --name-only HEAD~3 HEAD) <<'SED'
/^enum RPCErrorCode$/,/^};$/b
s/\bRPC_INVALID_REQUEST\b/-32600/g
s/\bRPC_METHOD_NOT_FOUND\b/-32601/g
s/\bRPC_INVALID_PARAMS\b/-32602/g
s/\bRPC_INTERNAL_ERROR\b/-32603/g
s/\bRPC_PARSE_ERROR\b/-32700/g
s/\bRPC_MISC_ERROR\b/-1/g
s/\bRPC_TYPE_ERROR\b/-3/g
s/\bRPC_INVALID_ADDRESS_OR_KEY\b/-5/g
s/\bRPC_OUT_OF_MEMORY\b/-7/g
s/\bRPC_INVALID_PARAMETER\b/-8/g
s/\bRPC_DATABASE_ERROR\b/-20/g
s/\bRPC_DESERIALIZATION_ERROR\b/-22/g
s/\bRPC_VERIFY_ERROR\b/-25/g
s/\bRPC_VERIFY_REJECTED\b/-26/g
s/\bRPC_VERIFY_ALREADY_IN_UTXO_SET\b/-27/g
s/\bRPC_IN_WARMUP\b/-28/g
s/\bRPC_METHOD_DEPRECATED\b/-32/g
s/\bRPC_LIMIT_EXCEEDED\b/-37/g
s/\bRPC_TRANSACTION_ERROR\b/-25/g
s/\bRPC_TRANSACTION_REJECTED\b/-26/g
s/\bRPC_CLIENT_NOT_CONNECTED\b/-9/g
s/\bRPC_CLIENT_IN_INITIAL_DOWNLOAD\b/-10/g
s/\bRPC_CLIENT_NODE_ALREADY_ADDED\b/-23/g
s/\bRPC_CLIENT_NODE_NOT_ADDED\b/-24/g
s/\bRPC_CLIENT_NODE_NOT_CONNECTED\b/-29/g
s/\bRPC_CLIENT_INVALID_IP_OR_SUBNET\b/-30/g
s/\bRPC_CLIENT_P2P_DISABLED\b/-31/g
s/\bRPC_CLIENT_NODE_CAPACITY_REACHED\b/-34/g
s/\bRPC_CLIENT_MEMPOOL_DISABLED\b/-33/g
s/\bRPC_WALLET_ERROR\b/-4/g
s/\bRPC_WALLET_INSUFFICIENT_FUNDS\b/-6/g
s/\bRPC_WALLET_INVALID_LABEL_NAME\b/-11/g
s/\bRPC_WALLET_KEYPOOL_RAN_OUT\b/-12/g
s/\bRPC_WALLET_UNLOCK_NEEDED\b/-13/g
s/\bRPC_WALLET_PASSPHRASE_INCORRECT\b/-14/g
s/\bRPC_WALLET_WRONG_ENC_STATE\b/-15/g
s/\bRPC_WALLET_ENCRYPTION_FAILED\b/-16/g
s/\bRPC_WALLET_ALREADY_UNLOCKED\b/-17/g
s/\bRPC_WALLET_NOT_FOUND\b/-18/g
s/\bRPC_WALLET_NOT_SPECIFIED\b/-19/g
s/\bRPC_WALLET_ALREADY_LOADED\b/-35/g
s/\bRPC_WALLET_ALREADY_EXISTS\b/-36/g
s/\bRPC_WALLET_INVALID_ACCOUNT_NAME\b/-11/g
s/\bRPC_FORBIDDEN_BY_SAFE_MODE\b/-2/g
s/\bRPC_HTTP_ERROR\b/-342/g
s/\bRPC_MISSING_RESULT\b/-343/g
s/\bRPC_TIMEOUT\b/-344/g
s/strprintf\((R"\(\{"code":)%d(.*"), (-[0-9]+)\)/\1\3\2/
SED

git diff HEAD~3

@DrahtBot DrahtBot added the Tests label Nov 26, 2026
@DrahtBot

DrahtBot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.
A summary of reviews will appear here.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36979 (rpc: fix getorphantxs verbosity help and type checking by l0rinc)
  • #36976 (rpc: Use OBJ_NAMED_PARAMS in estimatesmartfee by maflcko)
  • #36877 (test: cover scantxoutset scan-object validation errors by Pranav-error)
  • #36826 (rpc: Return the right RPCErrorCode more consistently by maflcko)
  • #36778 (AssumeUTXO: replace loadtxoutset RPC with a startup arg by l0rinc)
  • #36767 (wallet: fix crash when external signer wallet creation fails by zerog975)
  • #36710 (test: Replace hardcoded extended keys with ExtendedKey helpers by nebula-21)
  • #36705 (test: Replace stale TODO with mempoolminfee test in wallet_send.py by Conradgabe)
  • #36648 (descriptor, rpc, wallet: do not echo key material in error messages by fametrano)
  • #36627 (tracing: run USDT tests without BPF privileges by willcl-ark)
  • #36603 (Improve loadtxoutset performance by ajtowns)
  • #36569 (psbt: analyzepsbt reports an error when outputs exceed inputs by Ravan002)
  • #36547 (test: return typed P2PInterface from add_p2p_connection helpers by ViniciusCestarii)
  • #36540 (mempool: remove time-based transaction expiry by ismaelsadeeq)
  • #36482 (wallet: Only broadcast resubmitted transactions that were added to the mempool by achow101)
  • #36455 (Test: Add legacy script edge case spender test by benthecarman)
  • #36402 (refactor: wallet_importdescriptors to separate run_test() contents into specific functions by nebula-21)
  • #36257 (qa: assert_equal -> assert_true/assert_false by hodlinator)
  • #36149 (validation: Leave some pruned blocks in m_blocks_unlinked, fix another nSequenceId issue by mzumsande)
  • #36114 (wallet: harden external signer psbt processing, revamp mock by Sjors)
  • #36070 (wallet: Add deriveHDKey interface by PraneethGunas)
  • #36014 (net: ignore repeated -addnode startup values by w0xlt)
  • #36002 (txindex: allow running in pruned mode by andrewtoth)
  • #35831 (argsman, cli: Allow options after non-option arguments (GNU-style) by pablomartin4btc)
  • #35793 (Implement BIP 54 (Consensus Cleanup) without mainnet activation by darosior)
  • #35433 (wallet: deprecate replaceable argument from transaction (and psbt) creation (and modification) RPCs by rkrux)
  • #35429 (wallet: avoid global access in external signer SPKM by w0xlt)
  • #35302 (Silent Payments: Sending (take 2) by Eunovo)
  • #35224 (wallet: importdescriptors should output the request on error by kevkevinpal)
  • #33959 (test: deduplicate reorg test code by yuvicc)
  • #33954 (test: add functional test for outbound connection management by mzumsande)
  • #33741 (rpc: Optionally print feerates in sat/vb by polespinasa)
  • #33112 (wallet: relax external_signer flag constraints by Sjors)
  • #32861 (Have createwalletdescriptor auto-detect an unused(KEY) by Sjors)
  • #32857 (wallet: allow skipping script paths by Sjors)
  • #32468 (rpc: generateblock to allow multiple outputs with custom payouts by polespinasa)
  • #31668 (Added rescan option for import descriptors by saikiran57)
  • #27260 (Enhanced error messages for invalid network prefix during address parsing. by portlandhodl)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

LLM Linter (✨ experimental)

Possible places where named args for integral literals may be used (e.g. func(x, /*named_arg=*/0) in C++, and func(x, named_arg=0) in Python):

  • test/functional/p2p_disconnect_ban.py: self.nodes[1].setban, "127.27.0.1", "add", 123, True
  • test/functional/mempool_ephemeral_dust.py: self.nodes[0].prioritisetransaction, dusty_tx["txid"], 0, 1
  • test/functional/mining_prioritisetransaction.py: self.nodes[0].prioritisetransaction, txid, 1, 0
  • test/functional/rpc_rawtransaction.py: self.nodes[0].createrawtransaction, [], {}, 0, False, TX_MIN_STANDARD_VERSION - 1
  • test/functional/wallet_send.py: w0.send, {w1.getnewaddress(): 1}, 6, "conservative", 1, {"feeRate": 0.01}

2026-12-03 14:20:16

@l0rinc
l0rinc force-pushed the l0rinc/test-rpc-error-codes branch from f8c5b6c to 7599576 Compare November 27, 2026 12:16
This was referenced Nov 27, 2026
Expose `RPCErrorCode` to the Python functional tests using the names, values, and aliases from `src/rpc/protocol.h`.
Add a note beside the C++ enum to keep the Python definitions in sync.

-BEGIN VERIFY SCRIPT-
rpc_codes_file=test/functional/test_framework/rpc_error_codes.py
sed -n '2,4p' test/functional/feature_io_errors.py > "$rpc_codes_file"
printf '\n# Values from RPCErrorCode in src/rpc/protocol.h.\n' >> "$rpc_codes_file"
sed -nE '/^enum RPCErrorCode$/,/^};$/s/^    (RPC_[A-Z0-9_]+) *= ([^,]+),.*/\1 = \2/p' src/rpc/protocol.h >> "$rpc_codes_file"
sed -i "/^enum RPCErrorCode$/i //! Keep $rpc_codes_file in sync with this enum." src/rpc/protocol.h
git add -N "$rpc_codes_file"
-END VERIFY SCRIPT-
Replace numeric first arguments to `assert_raises_rpc_error` with their primary `RPCErrorCode` names and import the constants each test uses.

-BEGIN VERIFY SCRIPT-
python3 - <<'PY'
import re
from pathlib import Path

definitions = Path("test/functional/test_framework/rpc_error_codes.py").read_text()
codes = {value: name for name, value in re.findall(r"^(RPC_\w+) = (-\d+)$", definitions, re.M)}
calls = re.compile(r"(^[ \t]*assert_raises_rpc_error\(\s*)(-\d+)\b", re.M)
for path in Path("test/functional").glob("*.py"):
    source = path.read_text()
    used = sorted({codes[value] for _, value in calls.findall(source)})
    if not used:
        continue
    imports = used[0] if len(used) == 1 else "(\n    " + ",\n    ".join(used) + ",\n)"
    source = calls.sub(lambda match: match[1] + codes[match[2]], source)
    source = re.sub(
        r"^from test_framework\.(?:script\w*|test_framework|util) import",
        lambda match: f"from test_framework.rpc_error_codes import {imports}\n{match[0]}",
        source, count=1, flags=re.M,
    )
    path.write_text(source)
PY
-END VERIFY SCRIPT-
Use the named codes in the C++ RPC unit tests and in Python checks outside the scripted conversion.
Give the errors generated by the test client their own constants so `AuthServiceProxy` and `TestNodeCLI` can share the HTTP error code.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants