Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, 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.
Possible places where comparison-specific test macros should replace generic comparisons:
2026-11-05 17:52:29 |
enochaz
left a comment
There was a problem hiding this comment.
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 Is Tested on Linux aarch64 (Debian 13), GCC 14.2.0, with b67d871 merged with #29409 (0928430, merges cleanly). The PR alone also merges cleanly onto master de96f3a.
Not tested: a reorg between |
nullfail
left a comment
There was a problem hiding this comment.
LGTM ACK b67d871. 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 #36520 (comment)) fails if a negative max_height is passed. Here's a diff to test it:
diff --git a/src/test/interfaces_tests.cpp b/src/test/interfaces_tests.cpp
index 031415bff1..98eb28a8e3 100644
--- a/src/test/interfaces_tests.cpp
+++ b/src/test/interfaces_tests.cpp
@@ -187,6 +187,8 @@ BOOST_FIXTURE_TEST_CASE(invalidArguments, TestChain100Setup)
BOOST_CHECK_THROW(chain->getBlockHash(tip->nHeight + 1), std::out_of_range);
BOOST_CHECK_THROW(chain->getBlockHash(-1), std::out_of_range);
+ BOOST_CHECK(!chain->hasBlocks(tip->GetBlockHash(), /*min_height=*/0, /*max_height=*/-1));
+
BOOST_CHECK(!chain->checkChainLimits(nullptr));
std::string err;I think this issue should also be covered in this PR. Nonetheless, the current fixes here are clean and can be merged as is.
| try { | ||
| fn(); | ||
| } catch (const ipc::Exception& e) { | ||
| LogWarning("Chain notification %s failed: %s", name, e.what()); |
There was a problem hiding this comment.
nit: This msg could be more explicit with something like "Failed to deliver %s notification to IPC subscriber: %s"
There was a problem hiding this comment.
re: #36520 (comment)
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.
| //! Call a notification method, logging and discarding IPC errors. A | ||
| //! notification handler in an IPC client throws ipc::Exception if it | ||
| //! returns an error or disconnects, and should not be able to crash the | ||
| //! node, which happens if an exception escapes the validation interface | ||
| //! scheduler thread. Other exceptions are not caught: an in-process handler | ||
| //! like the wallet throwing indicates a bug, and continuing could leave it | ||
| //! with missing or inconsistent state. |
There was a problem hiding this comment.
Style nit, feel free to ignore:
I would like to see something shorter and more concise, like:
//! Call a chain notification method on the subscriber.
//!
//! For IPC subscribers: If the call fails because the subscriber returned an
//! error or disconnected, just log a warning. In-process subscribers are not
//! expected to fail.There was a problem hiding this comment.
re: #36520 (comment)
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.
There was a problem hiding this comment.
tACK b67d871
The 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 hasBlocks and the findAncestorByHash issue look related, since both rely on assumptions about lookup results. hasBlocks can dereference nullptr after GetAncestor receives a negative height, while findAncestorByHash could 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.
| auto handler{m_node.chain->handleNotifications(notifications)}; | ||
| for (int i = 0; i < 2; ++i) { | ||
| CreateAndProcessBlock({}, CScript() << OP_TRUE); | ||
| m_node.validation_signals->SyncWithValidationInterfaceQueue(); |
There was a problem hiding this comment.
In commit : interfaces: Catch IPC exceptions thrown by Chain notification handlers
We can remove the redundant queue synchronization in throwingNotifications as CreateAndProcessBlock already synchronizes notifications by default
There was a problem hiding this comment.
re: #36520 (comment)
Thanks, removed in the latest push.
Chain::findAncestorByHash returned true when block_hash was unknown and ancestor_hash was known, because the check clearing the ancestor pointer only ran when both hashes were found. Clear the ancestor whenever the block is not found. Fixes bitcoin#36472, reported by enirox001 while testing the IPC Chain interface from bitcoin#29409. The same fix was previously proposed in bitcoin#36473, bitcoin#36484 and bitcoin#36490 by Romansage6 and Yudis-bit. This change was written with Claude Opus 5.5 (1M context).
Chain methods were written for in-process C++ callers, which are expected to follow documented preconditions. Over IPC, non-C++ clients can pass any value, including null pointers for omitted Cap'n Proto fields, and an invalid argument should not be able to crash the node. - getBlockHash throws std::runtime_error instead of asserting when the height is not in the active chain. libmultiprocess sends the exception to the IPC client as an error. In-process, the wallet's loadwallet and startup error handling catch std::runtime_error, so they also handle a reorg that makes the height invalid between getHeight() and getBlockHash(). - hasBlocks returns false for a negative max_height instead of dereferencing the null block that GetAncestor() returns for it. - broadcastTransaction returns an error for a null transaction or an out of range broadcast method, instead of dereferencing null or silently doing nothing. - checkChainLimits returns an error for a null transaction instead of dereferencing it. These were reported by zaidmstrr and willcl-ark while reviewing bitcoin#29409, and the hasBlocks case by cyb3ralbert and xyzconstant. This change was written with Claude Opus 5.5 (1M context).
Chain::Notifications methods are called from the validation interface scheduler thread, where an uncaught exception terminates the node. A handler implemented by an IPC client throws ipc::Exception on the node side if the client returns an error or disconnects. Catch and log these exceptions so a misbehaving client cannot crash the node. Exceptions from in-process handlers are still not caught, since they indicate bugs. Reported by xyzconstant while reviewing bitcoin#29409. This change was written with Claude Opus 5.5 (1M context).
b67d871 to
e929e16
Compare
ryanofsky
left a comment
There was a problem hiding this comment.
Thanks for the reviews!
Rebased b67d871 -> e929e16 (pr/chainsafe.1 -> pr/chainsafe.2, compare) to fix the hasBlocks crash with a negative max_height (#36520 (comment), #36520 (review)), throw std::runtime_error from getBlockHash so the wallet's existing error handling applies, make the notification test throw from all six Notifications methods, and take the comment and test suggestions from xyzconstant and enirox001
| const CBlockIndex* block{chainman().ActiveChain()[height]}; | ||
| if (!block) throw std::out_of_range(strprintf("Block height %d is not in the active chain", height)); | ||
| return block->GetBlockHash(); | ||
| } |
There was a problem hiding this comment.
re: cyb3ralbert #36520 (comment)
In commit "interfaces: Return errors instead of crashing on invalid Chain arguments" (42fcc50)
Good point, out_of_range wasn't chosen for any reason that outweighs this. The latest push throws std::runtime_error instead, so the wallet's existing loadwallet and startup error handling applies if a reorg makes the height invalid between getHeight() and getBlockHash(). IPC clients see the same error message either way.
| void blockConnected(const kernel::ChainstateRole&, const interfaces::BlockInfo&) override | ||
| { | ||
| ++m_blocks; | ||
| throw ipc::Exception("blockConnected error"); | ||
| } | ||
| void updatedBlockTip() override | ||
| { | ||
| ++m_tips; | ||
| throw ipc::Exception("updatedBlockTip error"); | ||
| } | ||
| }; | ||
| auto notifications{std::make_shared<ThrowingNotifications>()}; | ||
| auto handler{m_node.chain->handleNotifications(notifications)}; |
There was a problem hiding this comment.
re: cyb3ralbert #36520 (comment)
In commit "interfaces: Catch IPC exceptions thrown by Chain notification handlers" (b67d871)
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 Notifications methods throw in this test, so removing any of the Notify wrappers makes it fail.
| try { | ||
| fn(); | ||
| } catch (const ipc::Exception& e) { | ||
| LogWarning("Chain notification %s failed: %s", name, e.what()); |
There was a problem hiding this comment.
re: #36520 (comment)
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.
| //! Call a notification method, logging and discarding IPC errors. A | ||
| //! notification handler in an IPC client throws ipc::Exception if it | ||
| //! returns an error or disconnects, and should not be able to crash the | ||
| //! node, which happens if an exception escapes the validation interface | ||
| //! scheduler thread. Other exceptions are not caught: an in-process handler | ||
| //! like the wallet throwing indicates a bug, and continuing could leave it | ||
| //! with missing or inconsistent state. |
There was a problem hiding this comment.
re: #36520 (comment)
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.
| auto handler{m_node.chain->handleNotifications(notifications)}; | ||
| for (int i = 0; i < 2; ++i) { | ||
| CreateAndProcessBlock({}, CScript() << OP_TRUE); | ||
| m_node.validation_signals->SyncWithValidationInterfaceQueue(); |
There was a problem hiding this comment.
re: #36520 (comment)
Thanks, removed in the latest push.
| // preconditions, so they should return errors instead of crashing when | ||
| // passed invalid arguments. | ||
| auto& chain = m_node.chain; |
There was a problem hiding this comment.
re: enirox001 #36520 (review)
In commit "interfaces: Return errors instead of crashing on invalid Chain arguments" (42fcc50)
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 Chain methods over IPC with arbitrary arguments might be the most direct way to find the remaining cases.
| if (block->nHeight <= min_height || !block->pprev) return true; | ||
| } |
There was a problem hiding this comment.
re: cyb3ralbert #36520 (comment)
In commit "interfaces: Return errors instead of crashing on invalid Chain arguments" (42fcc50)
Thanks for finding this, and @xyzconstant for checking the other Chain methods 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: hasBlocks now returns false when max_height is negative instead of dereferencing null, and invalidArguments has xyzconstant's test case.
d293ef6 doc: add release note for rejected IPC wait timeouts (Enoch Azariah) 525d69e mining: reject negative and NaN wait timeouts from IPC clients (Enoch Azariah) 44dbc7c test: add check_order option to wait_and_do (Enoch Azariah) Pull request description: An ipc client can pass any timeout to `waitTipChanged`, but the code assumes it is never negative: ``` Assume(timeout >= 0ms); // No internal callers should use a negative timeout ``` On debug builds, a negative or NaN timeout fails this check and aborts the node. I reproduced this with a timeout of -1.0. On release builds the check is skipped. Negative values are clamped to zero, but NaN is not, because every comparison with NaN is false. It ends up as the deadline passed to `wait_until`. `waitNext` has no Assume, but it also doesn't check its timeout. A NaN timeout waits one extra fee tick (about one second) before returning. `waitTipChanged` and `waitNext` now throw an error for negative or NaN timeouts. The internal `Assume` in `WaitTipChanged` still checks internal callers. The interface documents the errors, and the functional test covers rejection of negative and NaN timeouts and acceptance of positive infinity in both methods. I'm not aware of any client that sends these values (sv2-tp, for example, requires an interval of at least one second), so this is hardening against bad input from ipc clients. _This is similar to #36520, which handles invalid arguments to the Chain interface for the same reason._ Links - https://ipcbugs.ofsky.org/bugs/bitcoin-2026-wait-timeout-assume/ ACKs for top commit: Sjors: ACK d293ef6 nervana21: tACK d293ef6 ryanofsky: Code review ACK d293ef6. This stops IPC clients from crashing debug builds of the node with negative or NaN wait timeouts, and from turning a NaN timeout into a `wait_until` deadline in release builds. Tree-SHA512: d60297b47444261ce0eee01a04711e37fc12ebdbd0da01753168e2eec285740a6f89c34244b51aa2c570d67a4bf752c649e5f653b62df4574e368eceecd17b1e

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.