Skip to content

rpc: Report -rpcwhitelist denials as JSON-RPC errors - #36753

Open
ryanofsky wants to merge 8 commits into
bitcoin:masterfrom
ryanofsky:pr/rpcdeny
Open

ryanofsky wants to merge 8 commits into
bitcoin:masterfrom
ryanofsky:pr/rpcdeny

Conversation

@ryanofsky

@ryanofsky ryanofsky commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

This PR adds two JSON-RPC error codes for requests refused by -rpcwhitelist, which until now got an HTTP 403 status with an empty body:

  • RPC_METHOD_NOT_PERMITTED (-38) is returned for a refused request, with HTTP 200 for JSON-RPC 2.0 requests and 403 for legacy 1.x requests.
  • RPC_REQUEST_NOT_EXECUTED (-39) is returned for the other requests in a refused batch. A refused batch now gets HTTP 200 and an array with an error for each request, and still runs none of them.

Problem: -rpcwhitelist errors are currently handled differently from other JSON-RPC errors, so clients report them with vague or misleading messages, and for JSON-RPC 2.0 requests the handling does not follow documented behavior. Specifically, requests refused by -rpcwhitelist get HTTP 403 with an empty body, so the refusal shows up as a generic transport error rather than a specific JSON-RPC error. This is especially a problem for JSON-RPC 2.0 requests, which are supposed to report failed method calls only as JSON-RPC errors, not HTTP errors. The empty reply causes a concrete problem when JSON-RPC requests are sent over IPC instead of HTTP: bitcoin-cli -ipcconnect receives only the response body, so a refused call prints a JSON type error instead of a permission error, as described in a private security review. Over HTTP, bitcoin-cli currently stops at the 403 status and prints only "server returned HTTP error 403" instead of the actual error.

Solution: Report whitelist denials like any other failed call: a JSON-RPC error in the body, with the HTTP status the request's version calls for. This brings the behavior in line with the documentation. bitcoin-cli then prints the permission error over both HTTP and IPC, with no change to the IPC interface. The first commit documents how batch requests work, since the documentation didn't mention them. The second adds tests for the current replies, so the later commits' test changes show how each reply changes. Two refactoring commits follow: one suggested in #36642 moves connection fields out of JSONRPCRequest into a new JSONRPCClient struct, and one moves the batch handling out of ExecuteHTTPRPC() into an ExecuteBatch() function. Between them, a small commit makes JSONRPCRequest::parse() reset the fields it sets, so a reused request object can't answer with an earlier request's id. A small bitcoin-cli fix makes -generate report errors from generatetoaddress, which it ignored. The last two commits make the change, in src/httprpc.cpp and src/rpc/protocol.h. Details in the commit messages.

Compatibility: HTTP clients that send "jsonrpc": "2.0" or batches and check for a 403 status need to read the error code instead. Single 1.x requests keep the 403 status, now with an error body.

Open question for review: RPC_METHOD_NOT_PERMITTED could be named RPC_ACCESS_DENIED, and RPC_REQUEST_NOT_EXECUTED is documented as batch-specific but would fit any request refused before it runs.

@DrahtBot

DrahtBot commented Nov 4, 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.

Type Reviewers
ACK pinheadmz
Concept ACK janb84, winterrdog
Stale ACK Zippo76, hodlinator

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36826 (rpc: Return the right RPCErrorCode more consistently by maflcko)
  • #36200 (rpc: invalid credentials can occupy every HTTP worker by hodlinator)

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.

@DrahtBot

DrahtBot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task tidy: https://github.com/bitcoin/bitcoin/actions/runs/41833576128/job/126586635980
LLM reason (✨ experimental): CI failed because clang-tidy flagged std::move(*denial) in httprpc.cpp:193 as ineffective on a const reference, and warnings are treated as errors.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

@ryanofsky

Copy link
Copy Markdown
Contributor Author

Updated 8cfdc34 -> 21526b1 (pr/rpcdeny.1 -> pr/rpcdeny.2, compare) to fix CI: drop a no-op std::move flagged by clang-tidy https://github.com/bitcoin/bitcoin/actions/runs/41833576128/job/126586635980; and pass the IPC socket path explicitly in the new interface_ipc_cli.py whitelist test, since -ipcconnect=auto can't find it when the datadir path is too long https://github.com/bitcoin/bitcoin/actions/runs/41833576128/job/126586636207

@pinheadmz

Copy link
Copy Markdown
Member

concept ACK
Narrowly avoiding a merge conflict with #36758 but I think 36758 should be merged first, since this PR (36753) exposes that bug to a slightly wider use case.

@ryanofsky

Copy link
Copy Markdown
Contributor Author

Updated 21526b1 -> 3667e19 (pr/rpcdeny.2 -> pr/rpcdeny.3, compare) to address findings from the Ralph LLM review (https://review.fish.foo/traces/36753-8cfdc340b779dc9c31f360900d98b8d807192e9b-2121-1.html): name the denied methods in RPC_REQUEST_NOT_EXECUTED errors so bitcoin-cli -getinfo shows them, report parse errors for malformed requests in refused batches, test that a refused batch has no effect, and add a release note

@fametrano

Copy link
Copy Markdown

My #36642 gives a non-object batch element a null id, so if it lands, the batch loop here can stay as it is.

janb84 asked on #36642 for the same batch replies with or without -rpcwhitelist, and pinheadmz pointed him here. On master, a user without a whitelist gets the previous element's id on that element's error, and this PR extends that reply to whitelisted users. I ran janb84's batches against each PR and their merge (https://gist.github.com/fametrano/2fc9fb4e35b060c3870aaf198668c271/dd9a540a099199d4293f6854f543915a838b0fbb): with both, each user gets the null id. The two merge cleanly (tree 1042df97fa), and either can land first.

@janb84 janb84 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concept ACK 3667e19

Comment thread src/httprpc.cpp Outdated
Comment on lines +137 to +146
// Name the denied methods in the errors for the held-back requests too,
// because clients like bitcoin-cli -getinfo show only the first error in
// a batch.
std::vector<std::string> denied_methods;
for (size_t i{0}; i < valRequest.size(); ++i) {
if (denied[i].empty()) continue;
const std::string& method{valRequest[i].find_value("method").get_str()};
if (std::ranges::find(denied_methods, method) == denied_methods.end()) denied_methods.push_back(method);
}
const std::string not_executed{strprintf("Not executed because the batch includes methods the user is not permitted to call: %s", util::Join(denied_methods, ", "))};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Think this code still has the DOS vector as highlighted by Ralph

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

re: #36753 (comment)

In commit "rpc: Add RPC_REQUEST_NOT_EXECUTED error for refused -rpcwhitelist batches" (711222b)

Think this code still has the DOS vector as highlighted by Ralph

Thanks, you're right. The -39 message listed every denied method and was repeated in each held-back request's error, so the reply could grow with the product of the two. It now names at most three short methods and says how many more there are, so the reply grows linearly with the batch. There's a new test for it.

@Zippo76 Zippo76 left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concept ACK

Tested 3667e19fe9 on macOS 27.2 arm64 against master 117c54d4c5.

rpc_whitelist.py fails on master and passes with this PR. Manual checks with curl confirmed errors -38 and -39, HTTP 403 for JSON-RPC 1.0 requests, and HTTP 200 for JSON-RPC 2.0 requests and batches. bitcoin-cli reports the RPC errors. A user denied access to all methods receives -38 (“User is not permitted to call any methods”), including for each element of a batch.

I also measured the response-size and memory amplification noted in the Ralph review. For batches containing N allowed calls and N distinct forbidden method names:

N Request size Response size Peak observed RSS
800 92 KB 8.5 MB 69 MB
1600 184 KB 33.7 MB 200 MB
3200 370 KB 134 MB 706 MB

RSS was sampled every 20 ms. On the PR, RSS was approximately 22 MB before the full series, which started at N=100; it was not measured immediately before the N=3200 batch. On master, these requests returned HTTP 403 with an empty body, and RSS remained roughly stable, increasing from 62 MB to 67 MB over the full series.

Across the run, the PR produced 6,300 “not allowed to call” warnings in debug.log, versus 6 on master. A separate batch containing 1,000 allowed calls and one forbidden method with a 10,000-character name produced a 10 MB response from a 68 KB request.

For bitcoin-cli -generate, I observed:

Case Master PR
User allowed only getnewaddress HTTP error 403, exit 1 "blocks": null, exit 0
Unrestricted user, out-of-range block count "blocks": null, exit 0 "blocks": null, exit 0

The second case confirms that the bitcoin-cli -generate handler already masks errors from generatetoaddress on master. This PR also exposes that existing behavior for whitelist rejections.

I did not test the IPC path or the reported abort in Debug builds.

@ryanofsky ryanofsky left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the reviews!

Rebased 3667e19 -> 711222b (pr/rpcdeny.3 -> pr/rpcdeny.4, compare) after #36642 was merged:

  • Added a first commit with characterization tests of the current replies, so the later commits' test changes only update expected values.
  • Added two refactoring commits suggested in #36642: a JSONRPCClient struct, so each batch element gets a fresh request without copying anything, and a ProcessBatch() helper shared by executed and refused batches.
  • Bounded the -39 error to at most three short denied method names. Listing all of them in every held-back request's error made the reply size quadratic (reported by janb84 and Ralph).
  • Added a commit fixing bitcoin-cli -generate, which ignored errors from generatetoaddress and reported success when it was denied (Ralph).

The other two findings in that Ralph review are fixed elsewhere: non-object batch elements reusing the previous id by #36642, and malformed 2.0 requests reaching the Assume() in JSONErrorReply() by #36758.

Comment thread src/httprpc.cpp Outdated
Comment on lines +137 to +146
// Name the denied methods in the errors for the held-back requests too,
// because clients like bitcoin-cli -getinfo show only the first error in
// a batch.
std::vector<std::string> denied_methods;
for (size_t i{0}; i < valRequest.size(); ++i) {
if (denied[i].empty()) continue;
const std::string& method{valRequest[i].find_value("method").get_str()};
if (std::ranges::find(denied_methods, method) == denied_methods.end()) denied_methods.push_back(method);
}
const std::string not_executed{strprintf("Not executed because the batch includes methods the user is not permitted to call: %s", util::Join(denied_methods, ", "))};

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

re: #36753 (comment)

In commit "rpc: Add RPC_REQUEST_NOT_EXECUTED error for refused -rpcwhitelist batches" (711222b)

Think this code still has the DOS vector as highlighted by Ralph

Thanks, you're right. The -39 message listed every denied method and was repeated in each held-back request's error, so the reply could grow with the product of the two. It now names at most three short methods and says how many more there are, so the reply grows linearly with the batch. There's a new test for it.

Comment thread src/httprpc.cpp Outdated
Comment on lines +143 to +145
// Each element gets its own request, so that nothing parsed from one
// element ends up in the reply to the next
JSONRPCRequest req{client};

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

re: #36753 (comment)

In commit "refactor: rpc: move batch loop into ProcessBatch()" (8036a77)

I ran janb84's batches against each PR and their merge ... with both, each user gets the null id.

Thanks for checking. This PR is now based on #36642, and the reply to a refused batch goes through the same ProcessBatch() loop, so both paths give a non-object element a null id.

@Zippo76 Zippo76 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tACK 711222b

Tested on macOS 27.2.1 arm64 against master 9183edd25e. Both rpc_whitelist.py and interface_ipc_cli.py from this PR fail on master and pass with this PR.

Retested the cases from my November 10 review:

Case Previous results (3667e19fe9) Current results (711222b96f)
Response size, N = 800 / 1600 / 3200 8.5 / 33.7 / 134 MB 243 / 488 / 978 KB
Peak observed RSS at N = 3200 706 MB 36 MB; 23 MB before the full series
1,000 allowed calls plus one forbidden method with a 10,000-character name 10 MB response 179 KB response
-generate, user allowed only getnewaddress "blocks": null, exit 0 Error -38 for generatetoaddress, exit 38
-generate, unrestricted user with an out-of-range block count "blocks": null, exit 0 Error -1, "JSON integer out of range", exit 1

Response size now scales linearly across the tested batch sizes.

For batches containing a non-object element, master returns HTTP 400 for the entire batch for the restricted user, while the unrestricted user receives per-element responses. With this PR, both users receive the same per-element responses with HTTP 200. The basic whitelist checks from my previous review still behave as expected.

@hodlinator hodlinator left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK 711222b

This change primarily fixes the error handling bug for RPC over IPC where we get an unexpected JSON value when a user is blocked from executing an RPC due to the whitelist. It also implements much finer grained error reporting when it comes to batched requests and corrects HTTP status codes returned upon permission failure to match the JSON-RPC-interface.md docs. (interface_rpc.py is unchanged by this PR and already demonstrates fine-grained batch errors with expected HTTP status codes).

Happy you implemented a variant of my suggestion to split the client's fields from the requests (with more correct handling of context)!

Comment thread test/functional/interface_ipc_cli.py Resolved
Comment thread test/functional/interface_ipc_cli.py Resolved
Comment thread src/httprpc.h Resolved
Comment thread src/rpc/request.h Resolved
Comment thread src/httprpc.cpp Resolved
Comment thread src/httprpc.cpp Resolved

@pinheadmz pinheadmz left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

code review at 711222b

Still waiting for #36758 merge and rebase on top of that but I wanted to get this PR into my brain today. I left several questions and a few nits. I also agree with @Zippo76 about perhaps logging too much.

Built and tested on macos/arm64, manually tested the behavior change with eccentric RPC requests and batches. I still need to test the IPC behavior locally and try some mutations against the tests.

Comment thread test/functional/rpc_whitelist.py Resolved
Comment thread test/functional/rpc_whitelist.py Resolved
Comment thread src/httprpc.cpp Resolved
Comment thread src/httprpc.cpp Resolved
Comment thread src/bitcoin-cli.cpp

UniValue ProcessReply(const UniValue &reply) override
{
if (!reply["error"].isNull()) return reply;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0afef9d

Remark: this logic already exists for the other "macros" -getinfo -netinfo -getaddrinfo

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

re: #36753 (comment)

Right, this just makes -generate check for an error reply the way the other handlers already do. It was the odd one out, so it turned errors from its second call into "blocks": null and exit code 0.

Comment thread src/httprpc.cpp Resolved
Comment thread src/rpc/request.h Outdated
* every request in an HTTP body or IPC call, including every element of a
* batch.
*/
struct JSONRPCClient

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

e49c9ac

bikeshedding nit: These data describe an HTTP request I think, not to be confused with a jsonrpc request which there might be more than one of in a batch contained in the total payload from the client. Just something about URI, authUser, and context fields which don't really describe a client.

However we are already using HTTPClient and HTTPRequest in the codebase and the rest of this PR uses client so I dunno. Even calling it HTTPContext with field nodeContext might be more clear.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

re: #36753 (comment)

These data describe an HTTP request I think

They describe the HTTP request for HTTP callers, but not every caller is HTTP: bitcoin-cli -ipcconnect requests come in through RpcImpl::executeRpc over IPC, and ChainImpl::executeRpc fills it in for internal calls, so I'd avoid an HTTP name. The idea of "client" is the thing that sent the request, which every element of a batch shares. I don't feel strongly about the name, though, so happy to change it if you have a better one.

@DrahtBot
DrahtBot requested a review from pinheadmz December 2, 2026 21:12

@ryanofsky ryanofsky left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the reviews!

Rebased 711222b -> dfcdc8b (pr/rpcdeny.4 -> pr/rpcdeny.5, compare) after #36758 was merged, with changes from review:

  • Restructured ExecuteHTTPRPC() as pinheadmz suggested. The third commit now moves the whole batch branch, including the -rpcwhitelist check, into an ExecuteBatch() function that calls JSONRPCExec() directly, replacing ProcessBatch() and its callback. A refused single request now throws its error for both JSON-RPC versions and lets JSONErrorReply() answer it, which works now that #36758 made JSONErrorReply() handle 2.0 requests.
  • Added a commit resetting the parsed fields at the start of JSONRPCRequest::parse(), suggested by janb84 on #36758.
  • A refused batch now logs only its first denial, as on master, instead of a warning per denied request (Zippo76, pinheadmz).
  • Quoted the method names in the -38 and -39 messages, so an empty name is visible (pinheadmz).
  • The -38 commit now keeps the empty 403 reply for refused batches, so the new batch reply only appears in the last commit (Ralph). Added tests for notifications in refused batches (Ralph) and a test for a batch whose denied request is also malformed. The release note now covers more of the changes, and each commit that changes behavior adds its own items to it (Ralph, Ralph).
  • Documented batch requests in doc/JSON-RPC-interface.md, which didn't mention them: requests in a batch are handled independently, except that a batch with a refused method is refused as a whole. The -rpcwhitelist text there now names the -38 error.
  • Took hodlinator's six suggestions and renamed the reply() test helper to parse_response().

Updated dfcdc8b -> 7c1c232 (pr/rpcdeny.5 -> pr/rpcdeny.6, compare) to fix CI: a clang-tidy use-after-move false positive in ExecuteBatch(), by building the refused batch's errors directly instead of throwing them https://github.com/bitcoin/bitcoin/actions/runs/47139517821/job/144370827671. Also dropped an outdated comment in the batch loop about each element getting its own request, which no longer explained anything after the client/request split. And simplified the error handling around batches: ExecuteHTTPRPC() now hands a batch to ExecuteBatch() before its try block, since ExecuteBatch() no longer throws, and the batch loop, from the ExecuteBatch() refactoring commit on, only puts parse() in a try, since JSONRPCExec() with catch_errors=true already returns errors in the reply. Also reworded a comment in the RPC_METHOD_NOT_PERMITTED commit that only made sense next to the old code. Moved the general description of batch requests in doc/JSON-RPC-interface.md into a new first commit, since it describes the intended behavior, including the exception for refused batches, with a note on how the current behavior differs. The last commit removes the note when it fixes those differences, and names the -38 and -39 error codes. Renamed WhitelistDenial() to CheckWhitelist(), since it checks the whitelist rather than just building an error.

Comment thread src/httprpc.cpp Resolved
Comment thread test/functional/rpc_whitelist.py Resolved
Comment thread test/functional/rpc_whitelist.py Resolved
Comment thread src/httprpc.cpp Resolved
Comment thread src/httprpc.cpp Resolved
Comment thread src/bitcoin-cli.cpp

UniValue ProcessReply(const UniValue &reply) override
{
if (!reply["error"].isNull()) return reply;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

re: #36753 (comment)

Right, this just makes -generate check for an error reply the way the other handlers already do. It was the odd one out, so it turned errors from its second call into "blocks": null and exit code 0.

Comment thread src/httprpc.cpp Resolved
Comment thread src/rpc/request.h Outdated
* every request in an HTTP body or IPC call, including every element of a
* batch.
*/
struct JSONRPCClient

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

re: #36753 (comment)

These data describe an HTTP request I think

They describe the HTTP request for HTTP callers, but not every caller is HTTP: bitcoin-cli -ipcconnect requests come in through RpcImpl::executeRpc over IPC, and ChainImpl::executeRpc fills it in for internal calls, so I'd avoid an HTTP name. The idea of "client" is the thing that sent the request, which every element of a batch shares. I don't feel strongly about the name, though, so happy to change it if you have a better one.

Comment thread src/httprpc.cpp Outdated
for (size_t i{0}; i < valRequest.size(); ++i) {
if (denied[i].empty()) continue;
const std::string& method{valRequest[i].find_value("method").get_str()};
if (!seen.insert(method).second) continue;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In commit "rpc: Add RPC_REQUEST_NOT_EXECUTED error for refused -rpcwhitelist batches" (dfcdc8b)

re: #36753 (review)

I also agree with @Zippo76 about perhaps logging too much.

Agreed, and thanks @Zippo76 for measuring it. The latest push logs only the first denial in a batch, as master did when it stopped at the first one, so a refused batch writes one warning however many denied requests it has. The test checks that the second denial isn't logged.

Describe batch requests in doc/JSON-RPC-interface.md, which did not
mention them: each request in a batch is handled independently, with one
response per request in an HTTP 200 reply, and a batch of only
notifications gets HTTP 204. The exception is a batch containing a method
refused by -rpcwhitelist, which is refused as a whole, with an error for
each request.

This documents the intended behavior. A note says how the current behavior
differs: a refused batch gets an empty HTTP 403 reply, and for users listed
in -rpcwhitelist, a malformed request fails the whole batch. A later commit
in this PR fixes both and removes the note.

This change was written with Claude Opus 5.5.
Add tests for what clients currently get when -rpcwhitelist refuses a
request, so that the following commits, which change these replies, only
need to update the expected values:

- A denied request, JSON-RPC 2.0 request or notification gets HTTP 403
  with an empty body, and bitcoin-cli prints "server returned HTTP error
  403", including for -getinfo and -generate.
- A batch including a denied request gets HTTP 403 with an empty body,
  and none of its requests run.
- With a whitelist, a batch request missing its method fails the whole
  batch with HTTP 500, and a request that is not an object fails it with
  HTTP 400.
- Over IPC, where bitcoin-cli gets the reply body without the HTTP
  status, the empty body is reported as a JSON type error.

This change was written with Claude Opus 5.5.
Move the fields that describe the connection a request came in on (URI,
authUser, peerAddr and the default context) into a new JSONRPCClient
struct, and have JSONRPCRequest refer to it instead of holding copies.
ExecuteHTTPRPC() now takes the client and creates a new request for each
batch element instead of copying a template request, so nothing parsed
from one element can end up in the reply to the next.

JSONRPCRequest keeps its own context, which starts as the client's,
because the wallet's RPC dispatcher replaces it with the wallet context
before calling wallet handlers.

This was suggested as a follow-up in bitcoin#36642, and lets the next commit
share the batch loop.

This change was written with Claude Opus 5.5.
Reset id, m_json_version and m_notification before parsing, so that a
JSONRPCRequest that is parsed more than once never answers a request that
fails to parse with the id or JSON-RPC version of an earlier one, or treats
it as a notification. parse() set m_notification only after a successful
parse and set id and m_json_version only after checking that the request
is an object.

This does not change behavior: every caller parses a newly constructed
request, and JSONRPCRequest objects now start out empty and share only the
client. It makes parse() safe to call on a reused object instead of relying
on callers not to.

Suggested by janb84 in
bitcoin#36758 (comment)

This change was written with Claude Opus 5.5.
Move the code that handles a JSON-RPC batch out of ExecuteHTTPRPC() into an
ExecuteBatch() function: the -rpcwhitelist check of every method in the
batch and the loop that parses and executes each element. ExecuteHTTPRPC()
calls it as soon as it sees an array, and then handles a single request
without the if/else-if chain over the request type. In the loop, only
parse() is in the try block now, because JSONRPCExec() with
catch_errors=true already returns a method's errors in the reply. Behavior
does not change.

The next commits change how -rpcwhitelist refusals are reported, and this
keeps the batch and single-request changes separate.

This change was written with Claude Opus 5.5.
bitcoin-cli -generate calls getnewaddress, then generatetoaddress, and
builds its output from the second reply's result without checking its
error. When generatetoaddress returns a JSON-RPC error, -generate prints
the address with "blocks": null and exits successfully. Return the reply
as it is when it has an error, so bitcoin-cli prints the error and exits
with its code, as the other request handlers do.

The next commit makes this reachable for users refused by -rpcwhitelist:
a denied generatetoaddress call now gets a JSON-RPC error instead of an
HTTP 403 status. This was found by the Ralph LLM review.

This change was written with Claude Opus 5.5.
Reply to a single request refused by -rpcwhitelist with a JSON-RPC error
that has a new RPC_METHOD_NOT_PERMITTED (-38) code, instead of an empty body
with HTTP status 403. The error names the method ("User is not permitted to
call method 'getblockchaininfo'"), and the code lets clients tell a refusal
apart from a method that ran and failed. The empty reply gave no reason,
and over IPC, which carries no HTTP status, no sign of a refusal at all:
bitcoin-cli -ipcconnect printed a JSON type error, and bitcoin-cli over
HTTP printed only "server returned HTTP error 403". Both now print the
permission error.

As with other failed calls, a legacy 1.x request keeps HTTP 403, a JSON-RPC
2.0 request gets HTTP 200 as doc/JSON-RPC-interface.md specifies, and a
refused 2.0 notification gets HTTP 204 and no body. The empty reply to a
2.0 request also broke the JSON-RPC 2.0 specification, which requires a
Response object with a result or an error for every request that is not a
notification. A refused batch still gets the empty 403 reply; the next
commit changes it.

The denial is thrown like any other error, and JSONErrorReply() answers it
in the request's version, with a new case for 2.0 notifications. Because
the request has to be parsed first, a user refused outright by
-rpcwhitelistdefault now gets the usual errors for malformed requests, and
an empty reply for an empty batch, instead of the early 403.

For review:

- HTTP clients that send "jsonrpc": "2.0" and check for a 403 status need to
  read the error code instead.
- Code name: RPC_METHOD_NOT_PERMITTED could instead be a more general
  RPC_ACCESS_DENIED. Reusing RPC_INVALID_REQUEST or RPC_METHOD_NOT_FOUND would
  conflict with JSONErrorReply(), which maps them to 400 and 404 for 1.x
  requests.

The wrong error bitcoin-cli -ipcconnect printed for a refused method was
reported privately as part of a security audit. Only the message was wrong:
the refused method never ran.

This change was written with Claude Opus 5.
…ches

Reply to a batch refused by -rpcwhitelist with an error for each request,
instead of an empty HTTP 403 reply for the whole batch. The batch is still
refused as a whole before any request runs, so a refused batch has no partial
effect.

The reply is HTTP 200 with an array holding one error per request:
RPC_METHOD_NOT_PERMITTED (-38) for each denied method, and a new
RPC_REQUEST_NOT_EXECUTED (-39) code for the other requests, which did not run.
The -39 message names up to three of the denied methods too, because batch
clients like bitcoin-cli -getinfo show only the first error. It names no more,
and skips long names, because it is repeated in every held-back request's error
and would otherwise let one batch ask for a reply quadratic in its size.

Batches report every other error per request in an HTTP 200 response, whatever
the JSON-RPC version, and batch clients cannot read a single error object.
bitcoin-cli -getinfo sends a batch, so a refused one reported "Batch must be an
array" from JSONRPCProcessBatchReply over -ipcconnect, and "server returned
HTTP error 403" over HTTP. It now prints the permission error. Every denial in
the batch is reported, not only the first, so one reply names every method the
caller needs to drop. Only the first denial is logged, as before, so a batch
can't write a warning per request.

The authorization pass also no longer fails the whole batch on a malformed
request. It threw for a request that was not an object, and let an absent or
non-string method field throw out of get_str(), which failed the whole batch
with HTTP 400 or 500. Without a whitelist those requests are reported
individually and the rest of the batch still runs. The pass now leaves them to
the loop that executes the batch, and a refused batch reports their parse
errors the same way, so both paths agree. Nothing slips past the check: parsing
such a request fails there before its method would run.

Requests without an id are left out of the reply, because JSON-RPC 2.0 gives
notifications no response, so a refused batch of only notifications gets HTTP
204 and no body, like an executed one.

For review:

- The status of a refused 1.x batch changes from 403 to 200 too, matching how
  1.x batches report every other error.
- RPC_REQUEST_NOT_EXECUTED is documented as batch-specific, but the name would
  also fit any request refused before it runs.

This extends the fix for the privately reported bitcoin-cli -ipcconnect
error to batches, which bitcoin-cli -getinfo sends.

This change was written with Claude Opus 5.
@DrahtBot

DrahtBot commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task tidy: https://github.com/bitcoin/bitcoin/actions/runs/47139517821/job/144370827671
LLM reason (✨ experimental): tidy_fail: clang-tidy reports bugprone-use-after-move in httprpc.cpp (treated as an error).

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • Intermittent network issues can occur; re-run CI for now, and report the issue if they keep happening.

  • A functional or integration test failure may be intermittent or unrelated to this pull request.
    If no dedicated issue thread exists, create a new one to track it.

Leave a comment here, if you need help tracking down a confusing failure.

@pinheadmz pinheadmz left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK 7c1c232

Built and tested on macos/arm64. Played with the new errors via http and bitcoin-cli -ipcconnect, comparing to master. It's a big improvement in the UX for RPC over IPC.

I noticed a few things that are redundant with the rebase on master (I think...?)

Also noticed some slight differences in UX between HTTP and IPC simply because rpcpassword is ignored over IPC, so for example over IPC an unauthorized request gets

User is not permitted to call any methods

but over HTTP that same request gets

Incorrect rpcuser or rpcpassword were specified.

... I don't see this as a blocker at all.

Show Signature
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

ACK 7c1c2320ecc5eb3ef09ad530c5daedc03ae4556f
-----BEGIN PGP SIGNATURE-----

iQJPBAEBCAA5FiEE5hdzzW4BBA4vG9eM5+KYS2KJyToFAmsRz5gbFIAAAAAABAAO
bWFudTIsMi41KzEuMTIsMCwzAAoJEOfimEtiick6HXAQAMqEk7uTHW2ca78/v74g
D9leU5ELOsxuVzM1FPYgFEXw1UDOgby9wFDrX/USzUyQgc5E/cGc3LqFqn5WCfsS
Rn3VRdR3uUKlnA/46IqnNcuShWwH1qxrgXAaSz2uC36x1UjdgPeQhJLgDRG+G8In
d8h4Jg4bKlB9MTn7vOMlnosT2HqGIEgODOutvJPFccy9S6mZrWPfONn19VVEJ//3
vUNL7LE5NlP2T2hgxgxoTEjYqRnvYbZjDfLs3J+rbshnh0YaILG8sAPCodhCR6Sz
DLR65slZVXkNQJo6bSiUUMqK4L4+VKqi+P+CFVHJWrfUPyRMwm27XAVio/ofjFyW
qmJ68CorpLTJzahav4AY4rSizsuUeXAZRs7b3xqAZxXlX2WDOmR0Wg42/JTcvimf
e2VXM/+HfOgyBgJS3+ZPZ5DGl0/UACzCvPwNssEGr88Fp9vojKI+PlzDehvGMyEF
1e7ToHybebIDTwBPgtooYjjnmE3wvpKxiu3IgET0xaBeyGDorSZCHc/c5Ifl/be5
qC+xlpijbZFVsFuBxU35Kq5iSGYbWyXpws2uEvXYQhlwYbyEBPfPkz4B/GfbsFmZ
vNwQlgzFjzEVsVublWr0hrlv+qb63gx4okt5+4K5qAd1Tj2HE0GVjukAge+RelRi
Q2nIJluLJuYzFfngipb0yHd4
=JUpf
-----END PGP SIGNATURE-----

pinheadmz's public key is on openpgp.org

Comment thread src/rpc/request.cpp
Comment on lines +220 to +223
id = UniValue::VNULL;
m_json_version = JSONRPCVersion::V1_LEGACY;
m_notification = false;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ed0bcf6

Hm, the changes in this commit were proposed almost exactly the same in #36642 but that PR discussion it was decided to make the caller responsible. I think this commit is a no-op since that was merged.

#36642 (comment)

Comment thread src/httprpc.cpp Outdated
*/
static UniValue ExecuteBatch(const UniValue& batch, const JSONRPCClient& client, HTTPStatusCode& status)
{
// Check authorization for each request's method

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ec6a991

nit Might be worth mentioning that at this point if the user is not in the whitelist, it means they can execute anything, checked by the caller ExecuteHTTPRPC()

Comment thread src/httprpc.cpp
Comment on lines +47 to +50
if (jreq.IsNotification()) {
nStatus = HTTP_NO_CONTENT;
return {};
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

82dff38

Didn't we already determine this was dead code?

#36758 (comment)

@winterrdog winterrdog left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

concept ACK

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants