Skip to content

interfaces: Avoid node crashes from invalid Chain IPC calls - #36520

Open
ryanofsky wants to merge 3 commits into
bitcoin:masterfrom
ryanofsky:pr/chainsafe
Open

ryanofsky wants to merge 3 commits into
bitcoin:masterfrom
ryanofsky:pr/chainsafe

Conversation

@ryanofsky

@ryanofsky ryanofsky commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Problem: A program using the Chain IPC interface from #29409 can crash bitcoin-node with a single bad call: asking for a block hash above the tip, passing a negative height to hasBlocks, leaving the transaction argument of broadcastTransaction or checkChainLimits unset, or returning an error from a notification handler. Separately, findAncestorByHash reports success when the descendant block is unknown (#36472). The Chain methods 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 Chain methods in src/node/interfaces.cpp return errors for invalid arguments, catch and log IPC errors from notification handlers, and fix the findAncestorByHash check. Three small commits, each with unit tests in src/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::Chain is 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). The findAncestorByHash fix is the same one previously proposed by Romansage6 and Yudis-bit in #36473, #36484 and #36490.

Fixes #36472.

@DrahtBot DrahtBot added the IPC label Oct 14, 2026
@DrahtBot

DrahtBot commented Oct 14, 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
Stale ACK xyzconstant, enirox001

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:

  • #37094 (validation: validate assumeutxo snapshots with a single chainstate by fjahr)
  • #36946 (scripted-diff: [test] Add util/check.h includes for assertions by maflcko)

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):

  • 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) → Prefer BOOST_CHECK_EXCEPTION with a predicate checking the expected error message.
  • src/test/interfaces_tests.cpp: BOOST_CHECK_THROW(chain->getBlockHash(-1), std::runtime_error) → Prefer BOOST_CHECK_EXCEPTION with a predicate checking the expected error message.

2026-11-05 17:52:29

@enochaz enochaz 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

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

@cyb3ralbert

Copy link
Copy Markdown
Contributor

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 negative max_height, block->GetAncestor(*max_height) returns null (chain.cpp:84), and the loop then dereferences it (node/interfaces.cpp:691-692 @ b67d871, 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_range intended over a runtime_error-derived type? getBlockHash now throws std::out_of_range (a std::logic_error), while wallet/load.cpp:161 and wallet/wallet.cpp:313 catch only std::runtime_error. Reading the code, a throw during loadwallet would skip the FAILED_LOAD handling and reach the generic std::exception catch in rpc/server.cpp:891, and one during startup wallet loading would skip initError. I did not exercise this path.

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.

  • 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).
  • Reverting the src changes of one commit at a time, while keeping the PR's tests: 03e4654 makes findAncestorByHash fail at interfaces_tests.cpp:108; 42fcc50 makes invalidArguments abort in getBlockHash; b67d871 makes throwingNotifications terminate on the uncaught ipc::Exception. The other two tests pass in each case.
  • Over IPC with a Python capnp client, comparing the same tree with the PR's src changes reverted against the merged tree:
    • getBlockHash(tip+1) and getBlockHash(-1): node exits with -6 (assertion), vs error Block height N is not in the active chain with the node alive.
    • broadcastTransaction and checkChainLimits with tx unset: node exits with -11, vs Transaction is null.
    • broadcastTransaction with method 255: (true, ""), vs Invalid broadcast method 255.
    • findAncestorByHash(unknown block, known ancestor): true, vs false.
    • A handler that raises in its first blockConnected: node exits with -6, vs node alive, one Chain notification blockConnected failed warning, and the handler still receives blockConnected and updatedBlockTip 3/3 for three mined blocks.
    • Client process killed while a blockConnected call is in flight: terminate on ipc::Exception: IPC client method call interrupted by disconnect. (exit -6), vs node alive with Chain 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.
  • Coverage nit: the PR's tests make only blockConnected and updatedBlockTip throw. A scratch case throwing ipc::Exception from all six Notifications methods passes on the head. Removing the Notify wrapper from transactionAddedToMempool, transactionRemovedFromMempool, blockDisconnected or chainStateFlushed one at a time leaves the PR's three tests passing, while the scratch case fails for each.

Not tested: a reorg between getHeight() and getBlockHash() at the wallet call sites.

@nullfail nullfail 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.

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 by BlockManager::LookupBlockIndex on the block_hash arg was null.
  • getBlockHash - The assertion failed if the provided height was out of the active chain bounds, crashing the process. Fixed by throwing std::out_of_range instead.
  • broadcastTransaction, checkChainLimits - Passing a null tx crashes the process since it is internally dereferenced. Fixed by adding an early check on tx ensuring it's not null.
  • broadcastTransaction - The broadcast_method can be anything other than the values in TxBroadcast when 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.

Comment thread src/node/interfaces.cpp Outdated
try {
fn();
} catch (const ipc::Exception& e) {
LogWarning("Chain notification %s failed: %s", name, e.what());

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.

nit: This msg could be more explicit with something like "Failed to deliver %s notification to IPC subscriber: %s"

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: #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.

Comment thread src/node/interfaces.cpp Outdated
Comment on lines +508 to +514
//! 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.

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.

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.

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: #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.

@enochaz enochaz 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.

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.

Comment thread src/test/interfaces_tests.cpp Outdated
auto handler{m_node.chain->handleNotifications(notifications)};
for (int i = 0; i < 2; ++i) {
CreateAndProcessBlock({}, CScript() << OP_TRUE);
m_node.validation_signals->SyncWithValidationInterfaceQueue();

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.

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

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: #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).

@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 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

Comment thread src/node/interfaces.cpp
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();
}

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: 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.

Comment thread src/test/interfaces_tests.cpp Outdated
Comment on lines +211 to +223
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)};

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: 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.

Comment thread src/node/interfaces.cpp Outdated
try {
fn();
} catch (const ipc::Exception& e) {
LogWarning("Chain notification %s failed: %s", name, e.what());

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: #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.

Comment thread src/node/interfaces.cpp Outdated
Comment on lines +508 to +514
//! 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.

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: #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.

Comment thread src/test/interfaces_tests.cpp Outdated
auto handler{m_node.chain->handleNotifications(notifications)};
for (int i = 0; i < 2; ++i) {
CreateAndProcessBlock({}, CScript() << OP_TRUE);
m_node.validation_signals->SyncWithValidationInterfaceQueue();

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: #36520 (comment)

Thanks, removed in the latest push.

Comment on lines +182 to +184
// preconditions, so they should return errors instead of crashing when
// passed invalid arguments.
auto& chain = m_node.chain;

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: 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.

Comment thread src/node/interfaces.cpp
Comment on lines 694 to 695
if (block->nHeight <= min_height || !block->pprev) return true;
}

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: 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.

ryanofsky added a commit that referenced this pull request Dec 2, 2026
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
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.

interfaces: findAncestorByHash returns true for an unknown descendant

5 participants