mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:47:36 +00:00
Detect transaction problems early during deserialization #36906
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!36906
Loading…
Reference in a new issue
No description provided.
Delete branch "202611_txdeser_failfast"
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?
This is split off from #36521 (and not included in #36895), as it's effectively an independent improvement.
This introduces a number of additional checks that are applied during transaction deserialization, which reduce various worst case deserialization time scenarios:
fundrawtransactionthat explicitly support transactions with 0 inputs)This is a mild behavior change, as detecting these problems early causes them to be treated as deserialization errors, which in P2P logic cause messages to be ignored instead of peer disconnection.
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.
@ajtowns I considered your suggestion in https://github.com/bitcoin/bitcoin/pull/36521#discussion_r4531930759, but don't like that it's not explicit what the lifetime of the budget counting is. I use a more strongly typed approach here to add mutable state to streams, but still keep the budget object scoped in P2P code. LMK what you think.
🔵 Suggestion · Zero-output tests miss the rejection-before-witness ordering
The zero-output P2P test uses legacy serialization, so it cannot detect moving rejection below witness parsing; the current parser already rejects before reading witnesses.
Location:
src/test/transaction_tests.cpp:1494(head).🔵 Suggestion · Transaction fuzzing does not compare the new P2P parsing mode
The transaction fuzz target never checks that P2P decoding accepts exactly the ordinary decoder's non-empty transactions and produces the same wtxids, although that relationship holds at head.
Location:
src/primitives/transaction.h:237(head).🔵 Suggestion · Release note omits block, tooling, kernel and P2P changes
The RPC-only note misses block-decoding errors,
bitcoin-txand kernel constructor failures, and changed P2P handling; these are observable compatibility changes confined to objects that could never be valid.Location:
doc/release-notes-36906.md:4(head).Review coverage was incomplete.
Reviewed:
1681dec88de0· Review report · Previous reportspermalink
Hmm, the lifetime of the budget there is just the wrapper, which seems fairly explicit to me?
So:
starts the budget at "(" and ends it at ")", so it would be the same as:
To get the same as:
you'd need to write:
at which point the budget is scoped to the params stream.
partial review
lgtm aaea7040575171c1d12887fa15e64bc201a3f67c~2 📚
Show signature
Signature:
nit in
9de186b527: Avoid the copy and makedatamutable or use aSpanReader?Also, I think the deser type can be inferred in C++20, to avoid having to type it again:
nit in the first commit: It took me two passes to parse the sentence. Maybe split it in two and repeat the verb?
nit in the first commit: I mostly only wrote this test for fun in
b55555da3e. There is no need to retain the code exactly. It would also be fine to just use:to keep it brief and in symmetry with the below check.
Done.
Done.
Done.
My concern is/was mostly with something like a change
READWRITE(block.vtx);intoREADWRITE(TX_WITH_WITNESS(block.vtx));, which would introduce a new scope without limiting, or a scope with limiting but a different variable (this exact example might not work, but you see what I mean).I've switched to your approach, but added a feature for parameters to declare they cannot be overridden, which would satisfy that concern and doesn't cause any compilation problems.
Can this stall block download when a requested block fails deserialization?
If an oversized block throws
std::ios_base::failureinvRecv >> TX_WITH_WITNESS_P2P, the exception unwinds out ofProcessMessagebeforeRemoveBlockRequest(hash, pfrom.GetId())runs. Since the peer isn't disconnected, the hash stays inmapBlocksInFlightuntil the 10-minute download timeout expires.That's a fair concern. It's no different from how we treat a peer that never responds to a
getdatarequests at all, but extending the definition of serialization-invalid means that there are potentially broken (but not malicious) peers out there that aren't disconnected quickly anymore.I'll investigate (separate from this PR) whether we can just blanket disconnect any peers that gives us undeserializable messages.
The first two commits look like nice cleanups, but I still wonder about the last few commits: Are they really worth the complexity (and minimal cpu cost) when there are other places in Bitcoin Core that can eat memory (including in p2p). Are we going to address all of them?
lgtm
57a26d1a63🍄Show signature
Signature:
nit in the first commit: I think it is faster both in the happy case and the worst case to use
reserve+emplacehere, because the cpu can re-use the hot cache lines and the compiler can optimize the default ctor+deser a bit better?Later edit:
Just for my own reference, I only tested this in a micro benchmark for truncated inputs (which then only use a faster reserve instead of a resize), as well as "happy-case" lot's of inputs (which likely can then re-use the cache lines). It was faster on my machine (with -O3) in that micro-benchmark, but obviously an end-to-end benchmark with real chain data won't show any difference here.
style nit in
c0fa7a7fd7: I'd find it easier to read if this was a C++11 init and not one that is done by each ctor:nit in the last commit: Can use the type of
objto avoid having to pass deser and just create a new deser object with the type ofobj?nit in the first commit
093c7d7c4f: I think theforcan be dropped for better english?@maflcko Yeah, that's fair. FWIW, the point is reducing the time to deserialize a pathological non-segwit 4 MB transactions (which would be 16 MWU). At some point while writing #36521, after representation changes and other optimizations, those formed the new worst case. I'll redo the benchmarks to justify it.
tACK
57a26d1a63Got a question here though
When a solicited block fails early deserialization, unwinding before
RemoveBlockRequest()leaves its hash inmapBlocksInFlightuntil the normal download timeout.Since malformed stream errors already followed this path, and withholding a requested block can stall download anyway, relying on the standard timeout seems fine.
Was leaving it to the timeout the intended behavior here?
@Husteem Sharing LLM output may get you blocked according to https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md. If you have something to say, that is great, but please put it in your own words. Re-hashing a prior review with an LLM is the opposite of useful.
hi maflcko, acknowledged.
I was/been testing and looking at the RemoveBlockrequest path in net_processing,
but yes, I used an LLM to clean up the phrasing of the question.
I'll just stick to my natural rough tone next time/onwards.
I'd also pay closer attention to earlier discussions before asking my questions.
Thank you.
I have dropped all but the first two commits; I think it's fair that the performance gains don't justify the complexity being added here.
FWIW, here are the benchmarks (Zen5, gcc 15.3 x86_64, median of 11 runs each) I'm basing that on, in milliseconds, with this PR's (former version) on top of #36918. The "+counts" and "+empty" commits remain; the "+weight" one is dropped now.
I have dropped the weight accounting, see benchmarks above.
Benchmarks don't show a measurable difference, but it's more obviously not wasting efficiency, so I've taken it.
Gone.
Gone.
Done.
ACK
82cd7e7427Makes sense to keep just these two commits and leave peer disconnect handling for undeserializable messages to a follow-up. Checked the
num_inputs == 0cases inUnserializeTransactionand the P2P call sites, and ran the updated unit and functional tests locally.ACK
82cd7e7427I’m glad you dropped the weight accounting and stream state - I was uneasy about touching that much serialization code for this, and the two remaining checks are much easier to review. I also prefer
reservewithemplace_backhere, filling each entry just after construction seems cache-friendlier - and it was slightly faster when I timed block decoding locally.I’d give the decoder some room above the block-derived counts so a transaction with one extra input still gets the usual validation error - to be on the safe side, since we only want to reject very obviously wrong entries.
I’d also find the minimum input weight easier to check if it used the field widths directly in place of
36 + 1 + 4. The output bound could also be shared withAccessByTxid. If we keep the tight caps, I’d lean toward a release note for RPC and kernel callers. With limits that only catch obviously excessive counts, I’d skip it.UnserializeTransactionis the part I’d be most careful about changing again: I need the same parsing order in #36548 and would like to share it if there’s a small extraction we’re comfortable with.I’d also find
end of dataclearer thanSuperfluous witness recordwhen the outputs are cut off.This also changes what RPC and kernel callers can inspect. A short release note with the two counts would help explain why a transaction that used to decode now fails.
Document transaction decoding changes for callers
I’d find these minimum weights easier to check if the expressions named the fields.
Txid::size() + sizeof(COutPoint::n)shows where the 36 comes from, andGetSizeOfCompactSize(0)gives the empty script’s length prefix in both cases.Use the serialized field widths for the minimum transaction weights
AccessByTxidalready calculates the same output limit. If we move the bounds here, it can reuseMAX_OUTPUTS_PER_BLOCK.Share the block input and output count bounds
Following up on my review of #36521 now that the count checks are here. I need the same parsing order in #36548 to strip witnesses without building transactions. Would it make sense to extract the common part here so we only have one place to update these rules? I tried that with lambdas for the input, output and witness reads - but maybe that's too much and there's a safer or simpler way.
I also did a reindex-chainstate which showed no speed difference whatsoever.
Getting
Superfluous witness recordwhen the output data is incomplete could be confusing for the user, we could also checkflagshere...Preserve output-count parsing for zero-input transactions
A funding template can have outputs before the wallet picks any inputs. I’d check that those outputs survive a
TX_NO_WITNESSround trip here.Cover zero-input funding templates in the ordinary decoder
These blocks used to exercise
bad-txns-vin-emptyandbad-txns-vout-empty. Now that P2P deserialization stops earlier, sending the same blocks throughsubmitblockwould keep both checks covered.Keep the block validation reasons covered through submitblock
I’d leave some room above the consensus limits - given this is meant to avoid extremes.
For the one extra input in this test I’d still expect
bad-txns-oversizefrom validation.A separate case farther over the limit could check for
TX decode failed.I've added a short release note about the RPCs. I don't think the rest is visible enough to mention for users.
I don't like using
sizeofhere. I know we're relying on a guarantee that in-memory representation of integer types matches the on-the-wire size, but it still feels like mixing an implementation issue (sizes of integer types) with a protocol/consensus issue.Done.
I haven't thought too much about that. I think accommodating that in this PR is out of scope, but I could imagine an approach where the deserializer (perhaps post #36918) is restructured in the form where a lambda
[&](std::span<const std::byte> bytes, bool discounted)is provided, with bytes that are part of the serialization, classifying them. That could be useful for your use case (where discounted bytes would be dropped), and possibly for a replacement for the older witness-counting-during-deser approach here.Done.
Done.
Done.
I didn't take that, as it seems more fragile. The cost of enforcing a consensus check at P2P time is that that check needs to be correct. If it's wrong, it should be as observable as possible to give tests the ability to catch it. So I'd rather have the check be as tight as possible.
Regarding the debugability, we could report the exact deserialization error string in a more complete/structured way too, I think, so nothing is lost there, without actually impacting the deserialization code.
I removed the lambda in my latest push, let's see what the reviewers will think - can be resolved
Isn't the tight version more fragile, since we have to make absolutely sure that we don't accidentally reject consensus valid values - instead of making it so wide that only obviously wrong values are rejected early?
Approach ACK, untested.
s >> LIMITED_VECTOR(tx.vin, MAX_INPUTS_PER_BLOCK);?The exception message perhaps isn't as nice, I guess, but perhaps could tweak the #define to improve that?
Only change since my last review ( https://github.com/bitcoin/bitcoin/pull/36906#pullrequestreview-5977344049 ) is dropping the running weight accounting, per the benchmarks in https://github.com/bitcoin/bitcoin/pull/36906#pullrequestreview-6006636619. Also:
MAX*PER_BLOCK, usereserve+emplace_back).TX_WITH_WITNESS-deser to decode vout again to return a possible "end of data" over "Superfluous witness record". Either seems fine here.review ACK
1681dec88d🌻Show signature
Signature:
re-ACK
1681dec88dChecked the
flags == 0change and re-ran the tests locally.tested ACK
1681dec88dSince my last ACK, the output bound was shared with
AccessByTxid, the ordinary decoder’s truncation error was restored, and the new limits were documented for RPC users. A test was also added for unfunded transactions, and both empty-list validation errors remained covered throughsubmitblock.I went back over the early count checks in this revision because I was worried they might affect valid blocks. I couldn’t find any corner case where the caps would reject one.
I’d be happy to re-review the parser if AJ’s
LIMITED_VECTORsuggestion is taken.With the output bound shared in this commit,
bitcoin-txcould drop its duplicate calculation and useMAX_OUTPUTS_PER_BLOCKtoo.Reuse the shared output bound in bitcoin-tx