mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 16:02:38 +00:00
interfaces: Avoid node crashes from invalid Chain IPC calls #36520
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!36520
Loading…
Reference in a new issue
No description provided.
Delete branch "pr/chainsafe"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Problem: A program using the
ChainIPC interface from #29409 can crashbitcoin-nodewith a single bad call: asking for a block hash above the tip, passing a negative height tohasBlocks, leaving the transaction argument ofbroadcastTransactionorcheckChainLimitsunset, or returning an error from a notification handler. Separately,findAncestorByHashreports success when the descendant block is unknown (#36472). TheChainmethods were written for in-process C++ callers like the wallet, which follow documented preconditions, so they assert or dereference null instead of returning errors.Solution: Make these
Chainmethods insrc/node/interfaces.cppreturn errors for invalid arguments, catch and log IPC errors from notification handlers, and fix thefindAncestorByHashcheck. Three small commits, each with unit tests insrc/test/interfaces_tests.cpp. Valid calls behave the same as before. Details are in the commit messages.This PR does not depend on #29409, but the fixes matter if it is merged and
interfaces::Chainis exposed over IPC. The problems were reported by zaidmstrr, willcl-ark and xyzconstant while reviewing #29409, by enirox001 in #36472, and by cyb3ralbert and xyzconstant here (hasBlocks). ThefindAncestorByHashfix is the same one previously proposed by Romansage6 and Yudis-bit in #36473, #36484 and #36490.Fixes #36472.
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.
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:
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++, andfunc(x, named_arg=0)in Python):src/test/interfaces_tests.cpp:chain->hasBlocks(tip->GetBlockHash(), 0, -1)Possible places where comparison-specific test macros should replace generic comparisons:
src/test/interfaces_tests.cpp:BOOST_CHECK_THROW(chain->getBlockHash(tip->nHeight + 1), std::runtime_error)→ PreferBOOST_CHECK_EXCEPTIONwith a predicate checking the expected error message.src/test/interfaces_tests.cpp:BOOST_CHECK_THROW(chain->getBlockHash(-1), std::runtime_error)→ PreferBOOST_CHECK_EXCEPTIONwith a predicate checking the expected error message.2026-11-05 17:52:29
🟠 Minor · The new height exception leaves failed wallet loads subscribed
A height decrease during wallet attachment can return a load error while retaining the wallet's database lock until restart, and callbacks can advance its rescan checkpoint past unscanned blocks.
Location:
src/node/interfaces.cpp:601(head).🔵 Suggestion · Notification tests do not enforce the selective exception policy
All throwing callbacks use
ipc::Exception, so broadeningNotifyto catchstd::runtime_errororstd::exceptionwould leave these assertions passing.Location:
src/test/interfaces_tests.cpp:207(head).Review coverage was incomplete.
Reviewed:
e929e16f9843· Full review report · Previous reportspermalink
Concept ACK
I like this approach, which includes the specific fixes while also making the chain interface more defensive.
These methods were originally being called in process where the callers are expected to follow the preconditions, but once they are exposed over IPC, it makes sense to be more defensive around invalid inputs. Ideally an unexpected/bad IPC call should result in an error rather than crashing the nod
Could
hasBlocks()be covered here, or should it be a follow-up? It has the same kind of crash as the ones fixed here. With a negativemax_height,block->GetAncestor(*max_height)returns null (chain.cpp:84), and the loop then dereferences it (node/interfaces.cpp:691-692@b67d871f95, reading the code). Over IPC,hasBlocks(tip, 0, -1)kills the node (exit -11) with and without this PR; an in-process scratch unit test hits a memory access violation.Is
out_of_rangeintended over aruntime_error-derived type?getBlockHashnow throwsstd::out_of_range(astd::logic_error), whilewallet/load.cpp:161andwallet/wallet.cpp:313catch onlystd::runtime_error. Reading the code, a throw duringloadwalletwould skip theFAILED_LOADhandling and reach the genericstd::exceptioncatch inrpc/server.cpp:891, and one during startup wallet loading would skipinitError. I did not exercise this path.Tested on Linux aarch64 (Debian 13), GCC 14.2.0, with
b67d871f95merged with #29409 (0928430e16, merges cleanly). The PR alone also merges cleanly onto masterde96f3ae6d.interfaces_tests: 8/8 pass. Full unit suite: 879 cases pass. Functional (tool_bitcoin,feature_init,wallet_*,mempool_*,interface_ipc*): 95 passed, 4 skipped (previous releases not available).srcchanges of one commit at a time, while keeping the PR's tests:03e46542e6makesfindAncestorByHashfail atinterfaces_tests.cpp:108;42fcc504e2makesinvalidArgumentsabort ingetBlockHash;b67d871f95makesthrowingNotificationsterminate on the uncaughtipc::Exception. The other two tests pass in each case.srcchanges reverted against the merged tree:getBlockHash(tip+1)andgetBlockHash(-1): node exits with -6 (assertion), vs errorBlock height N is not in the active chainwith the node alive.broadcastTransactionandcheckChainLimitswithtxunset: node exits with -11, vsTransaction is null.broadcastTransactionwith method 255:(true, ""), vsInvalid broadcast method 255.findAncestorByHash(unknown block, known ancestor):true, vsfalse.blockConnected: node exits with -6, vs node alive, oneChain notification blockConnected failedwarning, and the handler still receivesblockConnectedandupdatedBlockTip3/3 for three mined blocks.blockConnectedcall is in flight: terminate onipc::Exception: IPC client method call interrupted by disconnect.(exit -6), vs node alive withChain notification blockConnected failed: IPC client method call interrupted by disconnect.and the next block mined normally. Client killed while its handler is registered but no call is in flight: node alive in both.blockConnectedandupdatedBlockTipthrow. A scratch case throwingipc::Exceptionfrom all sixNotificationsmethods passes on the head. Removing theNotifywrapper fromtransactionAddedToMempool,transactionRemovedFromMempool,blockDisconnectedorchainStateFlushedone at a time leaves the PR's three tests passing, while the scratch case fails for each.Not tested: a reorg between
getHeight()andgetBlockHash()at the wallet call sites.LGTM ACK
b67d871f95. Left some nits on the NotificationsProxy changes.This PR fixes a set of issues reported by IPC consumers testing the Chain interface exposed in #29409.
For anyone wondering, here is a short summary of the flawed Chain interface methods and their fixes:
findAncestorByHash- Returned an incorrect value (true) if an unknown block was passed, fixed by explicitly checking if the value returned byBlockManager::LookupBlockIndexon the block_hash arg was null.getBlockHash- The assertion failed if the providedheightwas out of the active chain bounds, crashing the process. Fixed by throwingstd::out_of_rangeinstead.broadcastTransaction,checkChainLimits- Passing a null tx crashes the process since it is internally dereferenced. Fixed by adding an early check ontxensuring it's not null.broadcastTransaction- Thebroadcast_methodcan be anything other than the values inTxBroadcastwhen received over IPC. Fixed by adding a helper that checks this arg is valid rather than relying on the type system.In addition to these Chain interface methods, the process can also perform IPC calls back to subscribers provided by clients. Such IPC calls may fail, and before this PR, we didn't handle these failures because in-process call failures are bugs; now, this PR catches only IPC exceptions (
ipc::Exception) and logs a warning.Checked whether these issues exist across other Chain methods not modified by this PR, but only
hasBlocks()(as @cyb3ralbert reported in https://github.com/bitcoin/bitcoin/pull/36520#issuecomment-6337747539) fails if a negativemax_heightis passed. Here's a diff to test it:I think this issue should also be covered in this PR. Nonetheless, the current fixes here are clean and can be merged as is.
Style nit, feel free to ignore:
I would like to see something shorter and more concise, like:
nit: This msg could be more explicit with something like
"Failed to deliver %s notification to IPC subscriber: %s"ralph referenced this pull request2026-10-24 21:06:38 +00:00
tACK
b67d871f95The fixes in these commits do resolve the problems reported in #36472 and during review of #29409. I applied the changes and confirmed the problem in #36472 is resolved in a functional test.
I think the negative max_height case in
hasBlocksand thefindAncestorByHashissue look related, since both rely on assumptions about lookup results.hasBlockscan dereference nullptr afterGetAncestorreceives a negative height, whilefindAncestorByHashcould return true when the starting block was unknown.I wonder if there is a shared way to handle invalid inputs and failed lookups across the exposed Chain interface in Core, so other methods don't repeat the same mistakes? Probably something for a followup.
In commit : interfaces: Catch IPC exceptions thrown by Chain notification handlers
We can remove the redundant queue synchronization in throwingNotifications as
CreateAndProcessBlockalready synchronizes notifications by defaultThanks for the reviews!
Rebased
b67d871f95->e929e16f98(pr/chainsafe.1->pr/chainsafe.2, compare) to fix thehasBlockscrash with a negativemax_height(https://github.com/bitcoin/bitcoin/pull/36520#issuecomment-6337747539, https://github.com/bitcoin/bitcoin/pull/36520#pullrequestreview-5621447619), throwstd::runtime_errorfromgetBlockHashso the wallet's existing error handling applies, make the notification test throw from all sixNotificationsmethods, and take the comment and test suggestions from xyzconstant and enirox001re: https://github.com/bitcoin/bitcoin/pull/36520#discussion_r4354127118
Thanks, took this in the latest push: the doc comment is now close to your version, and the sentence about why in-process exceptions are not caught moved next to the
catch.re: https://github.com/bitcoin/bitcoin/pull/36520#discussion_r4354026937
Thanks, agree it should say an IPC client was involved. Changed to
"IPC client failed to handle %s notification: %s"in the latest push, since the exception also covers a client that received the call and returned an error.re: cyb3ralbert https://github.com/bitcoin/bitcoin/pull/36520#issuecomment-6337747539
In commit "interfaces: Return errors instead of crashing on invalid Chain arguments" (
42fcc504e2)Good point,
out_of_rangewasn't chosen for any reason that outweighs this. The latest push throwsstd::runtime_errorinstead, so the wallet's existingloadwalletand startup error handling applies if a reorg makes the height invalid betweengetHeight()andgetBlockHash(). IPC clients see the same error message either way.re: cyb3ralbert https://github.com/bitcoin/bitcoin/pull/36520#issuecomment-6337747539
In commit "interfaces: Return errors instead of crashing on invalid Chain arguments" (
42fcc504e2)Thanks for finding this, and @xyzconstant for checking the other
Chainmethods and confirming it is the only remaining one. Since it is the same kind of bug as the others here, the latest push fixes it in this PR:hasBlocksnow returns false whenmax_heightis negative instead of dereferencing null, andinvalidArgumentshas xyzconstant's test case.re: enirox001 https://github.com/bitcoin/bitcoin/pull/36520#pullrequestreview-5712899549
In commit "interfaces: Return errors instead of crashing on invalid Chain arguments" (
42fcc504e2)Thanks for testing. Agree a shared approach would be better than fixing methods one at a time as reports come in, and that it fits a follow-up. A fuzz target that calls
Chainmethods over IPC with arbitrary arguments might be the most direct way to find the remaining cases.re: https://github.com/bitcoin/bitcoin/pull/36520#discussion_r4424094065
Thanks, removed in the latest push.
re: cyb3ralbert https://github.com/bitcoin/bitcoin/pull/36520#issuecomment-6337747539
In commit "interfaces: Catch IPC exceptions thrown by Chain notification handlers" (
b67d871f95)Thanks for the very thorough testing, especially the per-commit reverts and the client-killed-during-a-call case. Agree on the coverage gap: the latest push makes all six
Notificationsmethods throw in this test, so removing any of theNotifywrappers makes it fail.