mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:47:36 +00:00
txorphanage: bound orphan memory by storing transactions serialized #36015
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!36015
Loading…
Reference in a new issue
No description provided.
Delete branch "2026-08-orphanage-mem-bug"
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?
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.
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.
Concept ACK.
🚧 At least one of the CI tasks failed.
Task
Windows native, fuzz, VS: https://github.com/bitcoin/bitcoin/actions/runs/32186423022/job/95870987922LLM 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.
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.
My bad on that, forgot to push since my latest local change. Just did it.
Ready for review.
tACK d48b8afcaee6d08cc5e0c00262d0b7defdc6009f
Reverted
txorphanageback 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_USAGEcomment and got 1.24x and 1.47x, matching.Left a comment on
send_orphan()in the new test, nothing blocking.This
wait_untilmatches the getdata from the previous call, sincelast_messageisn't cleared. From the secondsend_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 whatp2p_orphan_handling.pydoes. Swapped it here and it still passes.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.
@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.
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.
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.
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.
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.
@brunoerg I'm a little busy, please take it on
Force-pushed addressing @instagibbs' approach.
title and OP will need updating 👍
Done.
Built the merge with master and tested again.
Every matching child is rebuilt before
Find1P1CPackagelooks at the first one. With 94 orphans of 199,000 1-byte items, one per peer, all announced by a single peer, that's 1,047.6 MB live against the 37.4 MB accounted for it, where one at a time would be 11.1 MB.The trigger costs no fee,
min relay fee not metalready returnsTX_RECONSIDERABLE.This test passes without the change. Reverting just
src/node/txorphanage.cppto before 493561a34285, the whole suite still passes, since the only difference the API exposes is the identity of the returned object.Fails without the change and passes with it.
Concept ACK
When finding potential 1P1C packages, we're now deserializing potentially many orphans, which on my machine can cause ~1s of cpu time at ~1GB of memory usage on top of normal. astra slop for your consideration:
github.com/instagibbs/bitcoin@847d2dc2a0Interesting, I benchmarked it (with and without your suggestion) and got +700 MB of peak (I think around 40MB of stored orphans) without and basically zero with. Will review the code and address it here.
Good point, I could add a
BOOST_CHECK(ptx_out != ptx)right after it.Force-pushed:
Addressed suggestion from @instagibbs - fixing
Find1P1CPackage. I got instagibbs@847d2dc but changed some things; most nits that I found and test improvements. I also changedFind1P1CPackageto store theGetTxresult and skips the candidate underAssumeif it is null.Addressed https://github.com/bitcoin/bitcoin/pull/36015#discussion_r3862075438
Missing rebase, doing it now.
CI failure is unrelated
Concept ACK
f4d43b530a: txorphanage: add GetOrphanUsage() and cache it per announcementnit.
f4d43b530a: txorphanage: add GetOrphanUsage() and cache it per announcementnit.
933a9f95af: txorphanage: store orphans serialized, making weight bound their memorynit.
f4d43b530a: txorphanage: add GetOrphanUsage() and cache it per announcementnit.
f4d43b530a: txorphanage: add GetOrphanUsage() and cache it per announcementnit. Match the usage API this comment documents.
0557bc81d5: txorphanage: return orphan ids from GetChildrenFromSamePeernit. Mirror GetPackageHash above
f4d43b530a: txorphanage: add GetOrphanUsage() and cache it per announcementCan add the usage metric
f4d43b530a: txorphanage: add GetOrphanUsage() and cache it per announcementCan use usage instead of weight.
f4d43b530a: txorphanage: add GetOrphanUsage() and cache it per announcementnit.
e9381aac15: test: cover storing a witness-heavy orphan at its serialized costnit.
e9381aac15: test: cover storing a witness-heavy orphan at its serialized costnit.
e9381aac15: test: cover storing a witness-heavy orphan at its serialized costnit.
Nits for the commit message themselves
87a2791f54: txorphanage: add GetParentTxids() and use it for orphan resolution candidatesSays "The following commit"
Should read "In a later commit"
9d6e93f5c7: iwyu: fix includes in node/txorphanage.hSays "the following commits modify this header"
Should read "later commits modify this header"
e9381aac15: test: cover storing a witness-heavy orphan at its serialized costSays "stored (accounted its weight, which now bounds its memory)"
Should read "stored (its usage is accounted for, which now bounds its memory)"
tACK
e9381aac15left a slew of non blocking nits, mostly about wording
the logic is sound based on my review and testing
3 additional verified findings in the full report.
🟠 Minor · Missing-input children can be repeatedly deserialized before cheap rejection
Distinct low-fee parent witness variants can repeatedly rebuild a retained witness-heavy child under cs_main and m_tx_download_mutex without requiring valid signatures.
Location:
src/node/txdownloadman_impl.cpp:328(head).🟠 Minor · getorphantxs decodes every orphan under the download mutex
An authorized getorphantxs call reconstructs every unique orphan while holding m_tx_download_mutex, even when the default response only needs cached txids.
Location:
src/node/txorphanage.cpp:783(head).🟠 Minor · Candidate cleanup can invalidate the later Assume(child_tx)
Cleaning up an in-mempool child can evict a later candidate from the ID snapshot, causing Assume-enforcing builds to abort; ordinary release builds skip it.
Location:
src/node/txdownloadman_impl.cpp:329(head).🔵 Suggestion · The witness-heavy test misses retention of the incoming transaction
Pointer inequality proves that GetTx returns a fresh object, but would not detect the orphanage retaining the original deserialized transaction as well.
Location:
src/test/orphanage_tests.cpp:759(head).🔵 Suggestion · EraseTx fuzz accounting still depends directly on weight
The txorphan accounting assertion bypasses GetOrphanUsage, leaving one usage expectation coupled to weight after the other targets adopt the new helper.
Location:
src/test/fuzz/txorphan.cpp:183(head).🔵 Suggestion · The usage comment incorrectly suggests platform-dependent accounting
GetOrphanUsage currently returns platform-independent transaction weight, contrary to the test comment's rationale for computing TX_USAGE.
Location:
src/test/orphanage_tests.cpp:113(head).Review coverage was incomplete.
Reviewed:
771bc5311c7b· Full review report · Previous reportspermalink
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.
Don't close until we get consensus on it 👍
🐙 This pull request conflicts with the target branch and needs rebase.
@brunoerg
#36895 (successor to #36521) has been merged. Can this be closed?
this should be closed 👍