Skip to content

txorphanage: bound orphan memory by storing transactions serialized - #36015

Closed
brunoerg wants to merge 7 commits into
bitcoin:masterfrom
brunoerg:2026-08-orphanage-mem-bug
Closed

brunoerg wants to merge 7 commits into
bitcoin:masterfrom
brunoerg:2026-08-orphanage-mem-bug

Conversation

@brunoerg

@brunoerg brunoerg commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

The orphanage limits the "usage" of the orphans it stores, per peer and globally, to bound the amount of memory an attacker can make us hold on to. It uses weight as a proxy for that memory, on the assumption that weight is "often higher than the actual memory usage of the transaction".

That assumption does not hold for a deserialized transaction. Every witness stack element is an individually heap-allocated vector, costing its 24-byte slot in the stack vector plus a 32-byte minimum allocation, while only weighing 2WU. A transaction of 199,000 1-byte witness elements weighs 398,247WU (i.e. it is of standard weight, and witness standardness cannot be checked while the inputs are missing), but uses 11.1MB of memory: 28 times what is accounted for it, and one such orphan can be retained per peer.

Rather than change the accounting metric, keep orphans in serialized form, deserializing them again on the paths that hand them back out. Serialized, a transaction's memory usage is bounded by its weight, so the existing weight-based accounting becomes a true upper bound on memory and the worst case is the peers' combined allowances.

Admission, eviction and accounting behavior are unchanged: no transaction that was previously accepted is refused, so orphan resolution (and thus 1p1c package relay) keeps working for standard-weight transactions whose witnesses consist of many small elements, such as BitVM-style transactions.

@DrahtBot

DrahtBot commented Aug 18, 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
Concept ACK w0xlt, l0rinc, Crypt-iQ
Stale ACK jeanpablojp, nervana21

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:

  • #36904 (log: Remove trailing and embedded newlines from log messages by maflcko)
  • #36884 (p2p: skip parent lookups for orphan announcements that cannot add a candidate by kah-ja)
  • #36506 (p2p: plug "tier 1" 1p1c liveness holes by instagibbs)

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.

@w0xlt

w0xlt commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Concept ACK.

@brunoerg
brunoerg marked this pull request as draft August 18, 2026 21:32
@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task Windows native, fuzz, VS: https://github.com/bitcoin/bitcoin/actions/runs/32186423022/job/95870987922
LLM reason (✨ experimental): CI failed due to an assertion failure in the fuzz test txorphan (txorphan.cpp:182), causing the fuzzer to exit with code 1.

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.

@l0rinc

l0rinc commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Concept ACK
The failing orphanage tests seem related (the musl one is the new test, the fuzz ones need a rebase, iwyu is the bench) and the change mixes refactors and hardening - can you check if it's possible to simplify and do refactors that aren't strictly related in follow-ups instead?
Especially since #35923 is related and complements this change, and #35919 is also touching the same area.

@brunoerg
brunoerg force-pushed the 2026-08-orphanage-mem-bug branch from 821f740 to eca91cf Compare August 18, 2026 23:19
@brunoerg

Copy link
Copy Markdown
Contributor Author

The failing orphanage tests seem related (the musl one is the new test, the fuzz ones need a rebase, iwyu is the bench) and the change mixes refactors and hardening - can you check if it's possible to simplify and do refactors that aren't strictly related in follow-ups instead?

My bad on that, forgot to push since my latest local change. Just did it.

@brunoerg
brunoerg force-pushed the 2026-08-orphanage-mem-bug branch from eca91cf to d48b8af Compare August 19, 2026 00:08
@brunoerg
brunoerg marked this pull request as ready for review August 19, 2026 11:33
@brunoerg

Copy link
Copy Markdown
Contributor Author

Ready for review.

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

Reverted txorphanage back to master and the new functional test fails like it should, "no orphan was evicted". With 10 peers sending one memory-heavy orphan each, master keeps all 10 and the head none.

I also checked the two numbers in the MAX_ORPHAN_TX_USAGE comment and got 1.24x and 1.47x, matching.

Left a comment on send_orphan() in the new test, nothing blocking.

node = self.nodes[0]
peer.send_and_ping(msg_inv([CInv(t=MSG_WTX, h=int(tx.wtxid_hex, 16))]))
node.bumpmocktime(TXREQUEST_TIME_SKIP)
peer.wait_until(lambda: peer.last_message.get("getdata"))

@jeanpablojp jeanpablojp Aug 21, 2026 •

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.

This wait_until matches the getdata from the previous call, since last_message isn't cleared. From the second send_orphan() on, the getdata doesn't hold the current tx's wtxid, so the tx goes out unrequested and the inv/getdata path is only exercised on the first call.

wait_for_getdata([int(tx.wtxid_hex, 16)]) fixes it, which is what p2p_orphan_handling.py does. Swapped it here and it still passes.

@DrahtBot
DrahtBot requested a review from l0rinc August 21, 2026 15:03
@instagibbs

instagibbs commented Aug 24, 2026 •

Copy link
Copy Markdown
Member

I'm pretty worried that the new behavior would cause subtle user breakage, epsecially considering something BitVM-like (with lots of 20b and 1b elements in witness data i.e. winternitz sigs).

Rather than change the metrics entirely, could you consider an alternative where the stored transactions are in serialized form, and deserialized only when required? https://github.com/instagibbs/bitcoin/tree/2026-08-orphanage-serialized-weight

It's significantly less code, doesn't require the weight metric to be swapped out (it would truly be an overestimation now modulo small constant), limiting the scope of the change. The one cost is the serialize<->deserialize that would be added on round-tripping. From my benchmarks it looks like a non-adversarial large tx would take ~1.5ms on ReconsiderTx, and a BitVM-like one ~3ms. The other costs look negligible.

Let me know what you think. I'm happy for you to take the code, or to open my own PR.

@jeanpablojp

jeanpablojp commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

@instagibbs I was curious so I built your branch, and I'm sharing some numbers I got in my tests.

The timing below is for rebuilding the transaction, one input with N items of k bytes.

witness stack         weight    deserialize   with teardown
100 x 80B              8,343        0.07 ms         0.08 ms
1 x 380,000B         380,248         2.4 ms          2.4 ms
8,000 x 20B          168,245         2.2 ms          2.8 ms
199,000 x 1B         398,247          28 ms           42 ms

Your ~3ms checks out. It's the item count driving this and not the bytes, and it's paid once, both of the paths a peer can trigger consume the orphan.

The limit here is 600,000 bytes of memory, not weight. Varying the item size, this is the weight at which it's reached.

item size    stored up to    % of the range to 400,000 WU lost
  1 byte       21,661 WU                  94.6%
 20 bytes     175,133 WU                  56.2%
 64 bytes     375,035 WU                   6.2%
 65 bytes     330,047 WU                  17.5%

64 to 65 is a MallocUsage step, so the threshold tracks the allocator's buckets and not the transaction.

I tested on x86-64, best case of several runs.

@instagibbs

Copy link
Copy Markdown
Member

Note that it's a pretty expensive "attack" in that to cause deserialization in the orphanage you'd have to enter in a valid parent tx into the mempool.

@brunoerg

Copy link
Copy Markdown
Contributor Author

I'm pretty worried that the new behavior would cause subtle user breakage, epsecially considering something BitVM-like (with lots of 20b and 1b elements in witness data i.e. winternitz sigs).

Rather than change the metrics entirely, could you consider an alternative where the stored transactions are in serialized form, and deserialized only when required? https://github.com/instagibbs/bitcoin/tree/2026-08-orphanage-serialized-weight

It's significantly less code, doesn't require the weight metric to be swapped out (it would truly be an overestimation now modulo small constant), limiting the scope of the change. The one cost is the serialize<->deserialize that would be added on round-tripping. From my benchmarks it looks like a non-adversarial large tx would take ~1.5ms on ReconsiderTx, and a BitVM-like one ~3ms. The other costs look negligible.

Let me know what you think. I'm happy for you to take the code, or to open my own PR.

Good point. I haven't tried that approach, but it seems simpler and achieves the same. I'll take a look at your branch, but you can open the PR and move on, no problem. Happy to review.

@instagibbs

Copy link
Copy Markdown
Member

@brunoerg I'm a little busy, please take it on

@brunoerg
brunoerg force-pushed the 2026-08-orphanage-mem-bug branch from d48b8af to c377e4a Compare August 25, 2026 17:20
@brunoerg

Copy link
Copy Markdown
Contributor Author

Force-pushed addressing @instagibbs' approach.

@instagibbs

Copy link
Copy Markdown
Member

title and OP will need updating 👍

@brunoerg brunoerg changed the title txorphanage: account memory usage instead of weight txorphanage: bound orphan memory by storing transactions serialized Aug 25, 2026
@brunoerg

Copy link
Copy Markdown
Contributor Author

title and OP will need updating 👍

Done.

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

Built the merge with master and tested again.

Comment thread src/node/txorphanage.cpp Resolved
Comment thread src/test/orphanage_tests.cpp Resolved
@Crypt-iQ

Copy link
Copy Markdown
Contributor

Concept ACK

@nervana21

Copy link
Copy Markdown
Contributor

Nits for the commit message themselves

87a2791: txorphanage: add GetParentTxids() and use it for orphan resolution candidates
Says "The following commit"
Should read "In a later commit"

9d6e93f: iwyu: fix includes in node/txorphanage.h
Says "the following commits modify this header"
Should read "later commits modify this header"

e9381aa: test: cover storing a witness-heavy orphan at its serialized cost
Says "stored (accounted its weight, which now bounds its memory)"
Should read "stored (its usage is accounted for, which now bounds its memory)"

@nervana21

Copy link
Copy Markdown
Contributor

tACK e9381aa

left a slew of non blocking nits, mostly about wording
the logic is sound based on my review and testing

@instagibbs

Copy link
Copy Markdown
Member

I think I approach nack this overall, if #36521 is viable

@brunoerg

Copy link
Copy Markdown
Contributor Author

I think I approach nack this overall, if #36521 is viable

I did really a quick look at #36521, looks to solve the issue. If that is viable, happy to close this.

@instagibbs

Copy link
Copy Markdown
Member

Don't close until we get consensus on it 👍

brunoerg and others added 7 commits November 4, 2026 13:30
Drop includes the header does not use, add the ones it does, and forward
declare FastRandomContext. The IWYU job checks the files a change touches,
and the following commits modify this header.
This constant is the default for TxOrphanage::m_reserved_usage_per_peer,
returned by ReservedPeerUsage() and compared against UsageByPeer(), all
of which are named after the "usage" they bound (of type
TxOrphanage::Usage). Name the constant after that same quantity rather
than after weight, the metric that happens to measure it, so that it
matches the field it initializes and the rest of the usage-based API.

The orphanage keeps accounting usage by weight, so this is a pure
naming change with no change in behavior.

-BEGIN VERIFY SCRIPT-
sed -i 's/DEFAULT_RESERVED_ORPHAN_WEIGHT_PER_PEER/DEFAULT_RESERVED_ORPHAN_USAGE_PER_PEER/g' $(git grep -l DEFAULT_RESERVED_ORPHAN_WEIGHT_PER_PEER)
-END VERIFY SCRIPT-
The orphanage's notion of an orphan's "usage" is currently duplicated in
the unit tests, the benchmarks and the fuzz targets, all of which call
GetTransactionWeight() to predict what the orphanage will account. Move
that knowledge into a single function so that a change of metric only
has to happen in one place, and so that all users agree on it.

Also cache the value in the Announcement instead of recomputing it on
every operation. Announcements hold an immutable CTransactionRef, so the
value never changes; caching it guarantees that PeerDoSInfo::Add() and
::Subtract() always use the same number, and makes Erase() (and therefore
LimitOrphans()) independent of the transaction's size.

No behavior change.
…ndidates

AddTxAnnouncement() only needs the deduplicated prevout txids of an
announced orphan to consider a peer as an orphan resolution candidate,
but obtains them by retrieving the full transaction with GetTx(). Serve
them from the orphanage directly, so that handling an announcement of a
known orphan does not depend on how the orphanage stores the
transaction. The following commit stores orphans in serialized form,
which would otherwise make every such announcement deserialize the
orphan.
Find1P1CPackage only needs each candidate child's txid and wtxid to
check the reject filters, and materializes at most one of them. Have
GetChildrenFromSamePeer() return those ids instead of a CTransactionRef
per child, add GetPackageHashFromWtxids() so the package-reject check
can be done from ids, and look up the selected child with GetTx().

This prepares for storing orphans serialized: with this change, finding
a 1P1C package deserializes only the child that is actually selected.
Otherwise a peer holding ~40MB of witness-heavy orphans (many tiny
witness elements, each a separate heap allocation once deserialized)
could make a single call cost ~0.9s of CPU and ~700MB of memory.

Co-authored-by: Greg Sanders <[email protected]>
The orphanage limits the "usage" of the orphans it stores, per peer and
globally, to bound the amount of memory an attacker can make us hold on
to, using weight as a proxy for that memory on the assumption that it
is "often higher than the actual memory usage of the transaction".

That assumption does not hold for a deserialized transaction: every
witness stack element is an individually heap-allocated vector, costing
its 24-byte slot in the stack vector plus a 32-byte minimum allocation,
while only weighing 2WU. A transaction of 199,000 1-byte witness
elements weighs 398,247WU (i.e. it is of standard weight, and witness
standardness cannot be checked while the inputs are missing), but uses
11.1MB of memory: 28 times what is accounted for it, and one such
orphan can be retained per peer.

Keep orphans in serialized form instead, deserializing them again on
the paths that hand them back out, all of which feed into full
(re)validation or RPC whose cost dwarfs a deserialization. Serialized,
a transaction's memory usage is bounded by its weight, so the existing
weight-based accounting becomes a true upper bound on memory and the
worst case is the peers' combined allowances. Admission, eviction and
accounting behavior are unchanged: no transaction that was previously
accepted is refused, so orphan resolution (and thus 1p1c package relay)
keeps working for standard-weight transactions whose witnesses consist
of many small elements, such as BitVM-style transactions.

The remaining per-orphan overhead not covered by weight (the entry in
m_orphans, the entries in m_outpoint_to_orphan_wtxids, and the cached
prevouts and hashes) is bounded by the latency score limits.
A standard-weight transaction of 199,000 1-byte witness elements, which
would use over 10 times its weight in memory if stored deserialized, is
stored (accounted its weight, which now bounds its memory), fits within
the announcer's reservation alongside normal orphans, and round-trips
through the orphanage intact.
@nervana21

Copy link
Copy Markdown
Contributor

@brunoerg
#36895 (successor to #36521) has been merged. Can this be closed?

@instagibbs

Copy link
Copy Markdown
Member

this should be closed 👍

@fanquake fanquake closed this Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants