Detect transaction problems early during deserialization #36906

Open
sipa wants to merge 3 commits from 202611_txdeser_failfast into master AGit
sipa commented 2026-11-17 22:08:57 +00:00 (Migrated from github.com)

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:

  • Reject transactions with more txins or more txouts than can possibly fit in a block (applied always)
  • Reject transactions with 0 txins or 0 txouts (applied in P2P code only; there are RPCs like fundrawtransaction that 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.

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: * Reject transactions with more txins or more txouts than can possibly fit in a block (applied always) * Reject transactions with 0 txins or 0 txouts (applied in P2P code only; there are RPCs like `fundrawtransaction` that 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.
DrahtBot commented 2026-11-17 22:09:07 +00:00 (Migrated from github.com)

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
ACK maflcko, Yudis-bit, l0rinc
Approach ACK ajtowns

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:

  • #35502 (refactor: extract per-message helpers from ProcessMessage (move-only) by w0xlt)

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.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/36906 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36906.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36906#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | ACK | [maflcko](https://github.com/bitcoin/bitcoin/pull/36906#issuecomment-7275538786), [Yudis-bit](https://github.com/bitcoin/bitcoin/pull/36906#issuecomment-7316585689), [l0rinc](https://github.com/bitcoin/bitcoin/pull/36906#pullrequestreview-6132464844) | | Approach ACK | [ajtowns](https://github.com/bitcoin/bitcoin/pull/36906#pullrequestreview-6097138074) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#35502](https://github.com/bitcoin/bitcoin/pull/35502) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35502.svg"></sub> (refactor: extract per-message helpers from ProcessMessage (move-only) by w0xlt) 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. <!--5faf32d7da4f0f540f40219e4f7537a3-->
sipa commented 2026-11-17 22:11:44 +00:00 (Migrated from github.com)

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

@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.
First-time contributor

🔵 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-tx and 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 reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:312ddb2095238aa2ca395a9cc39b05ab5a38a7177afbdb0d69098df9c3e0bef9:9a7f127b15c6116c267953d38288a9f17ec7c7bcd3a975fb71a2db8bfd974dbf --> <!-- ralph-base:58e9d98f3110c6e759f3148d974305b843fed33c --> <!-- ralph-head:1681dec88de01ae0f167ae7176889a76378b92bc --> <!-- ralph-case:9ca4799a50f3850817a3dd4e07062e6e551619f6078f069f84053e5a5609cd95 --> **🔵 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`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/1681dec88de01ae0f167ae7176889a76378b92bc/src/test/transaction_tests.cpp#L1494>) (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`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/1681dec88de01ae0f167ae7176889a76378b92bc/src/primitives/transaction.h#L237>) (head). **🔵 Suggestion · Release note omits block, tooling, kernel and P2P changes** The RPC-only note misses block-decoding errors, `bitcoin-tx` and 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`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/1681dec88de01ae0f167ae7176889a76378b92bc/doc/release-notes-36906.md#L4>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`1681dec88de0`](<https://git.fish.foo/bitcoin/bitcoin/commit/1681dec88de01ae0f167ae7176889a76378b92bc>) · [Review report](<https://review.fish.foo/report/36906-1681dec88de01ae0f167ae7176889a76378b92bc-3263-4.html>) · [Previous reports](<https://review.fish.foo/traces/36906/>) [permalink](<https://review.fish.foo/report/36906-1681dec88de01ae0f167ae7176889a76378b92bc-3263-4.html>)
ajtowns (Migrated from github.com) reviewed 2026-11-17 23:51:21 +00:00
ajtowns (Migrated from github.com) commented 2026-11-17 23:51:20 +00:00

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

Hmm, the lifetime of the budget there is just the wrapper, which seems fairly explicit to me?

So:

vRecv >> TX_WITH_WITNESS_BLOCK_LIMIT(block_a) >> TX_WITH_WITNESS_BLOCK_LIMT(tx_b);

starts the budget at "(" and ends it at ")", so it would be the same as:

TxWeightBudget budget{MAX_BLOCK_TXS_WEIGHT};
vRecv >> WithState{budget}(TX_WITH_WITNESS_P2P(block_a));
budget = MAX_BLOCK_TXS_WEIGHT;
vRecv >> WithState{budget}(TX_WITH_WITNESS_P2P(tx_b));

To get the same as:

vRecv >> WithState{budget}(TX_WITH_WITNESS_P2P(block_a)) >> WithState{budget}(TX_WITH_WITNESS_P2P(tx_b));

you'd need to write:

const TransactionSerParams TxWitLimit{.allow_witness = true, .reject_empty = false, .max_weight = MAX_BLOCK_TXS_WEIGHT};
ParamsStream{vrecv, TxWitLimit} << block_a << tx_b;

at which point the budget is scoped to the params stream.

> @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. Hmm, the lifetime of the budget there is just the wrapper, which seems fairly explicit to me? So: ```c++ vRecv >> TX_WITH_WITNESS_BLOCK_LIMIT(block_a) >> TX_WITH_WITNESS_BLOCK_LIMT(tx_b); ``` starts the budget at "(" and ends it at ")", so it would be the same as: ```c++ TxWeightBudget budget{MAX_BLOCK_TXS_WEIGHT}; vRecv >> WithState{budget}(TX_WITH_WITNESS_P2P(block_a)); budget = MAX_BLOCK_TXS_WEIGHT; vRecv >> WithState{budget}(TX_WITH_WITNESS_P2P(tx_b)); ``` To get the same as: ```c++ vRecv >> WithState{budget}(TX_WITH_WITNESS_P2P(block_a)) >> WithState{budget}(TX_WITH_WITNESS_P2P(tx_b)); ``` you'd need to write: ```c++ const TransactionSerParams TxWitLimit{.allow_witness = true, .reject_empty = false, .max_weight = MAX_BLOCK_TXS_WEIGHT}; ParamsStream{vrecv, TxWitLimit} << block_a << tx_b; ``` at which point the budget is scoped to the params stream.
maflcko (Migrated from github.com) reviewed 2026-11-18 11:40:40 +00:00
maflcko (Migrated from github.com) left a comment

partial review

lgtm aaea7040575171c1d12887fa15e64bc201a3f67c~2 📚

Show signature

Signature:

untrusted comment: signature from minisign secret key on empty file; verify via: minisign -Vm "${path_to_any_empty_file}" -P RWTRmVTMeKV5noAMqVlsMugDDCyyTSbA3Re5AkUrhvLVln0tSaFWglOw -x "${path_to_this_whole_four_line_signature_blob}"
RUTRmVTMeKV5npGrKx1nqXCw5zeVHdtdYURB/KlyA/LMFgpNCs+SkW9a8N95d+U4AP1RJMi+krxU1A3Yux4bpwZNLvVBKy0wLgM=
trusted comment: lgtm aaea7040575171c1d12887fa15e64bc201a3f67c~2 📚
nLvjeeAlv+OVV17u/LiU6qKTHXSKQVslEz44pNdPili+F59XLnmtzwm412Oqz9INKt3W2RLaQ3ySHRG1hsCCAA==
partial review lgtm aaea7040575171c1d12887fa15e64bc201a3f67c~2 📚 <details><summary>Show signature</summary> Signature: ``` untrusted comment: signature from minisign secret key on empty file; verify via: minisign -Vm "${path_to_any_empty_file}" -P RWTRmVTMeKV5noAMqVlsMugDDCyyTSbA3Re5AkUrhvLVln0tSaFWglOw -x "${path_to_this_whole_four_line_signature_blob}" RUTRmVTMeKV5npGrKx1nqXCw5zeVHdtdYURB/KlyA/LMFgpNCs+SkW9a8N95d+U4AP1RJMi+krxU1A3Yux4bpwZNLvVBKy0wLgM= trusted comment: lgtm aaea7040575171c1d12887fa15e64bc201a3f67c~2 📚 nLvjeeAlv+OVV17u/LiU6qKTHXSKQVslEz44pNdPili+F59XLnmtzwm412Oqz9INKt3W2RLaQ3ySHRG1hsCCAA== ``` </details>
maflcko (Migrated from github.com) commented 2026-11-18 10:53:27 +00:00

nit in 9de186b527: Avoid the copy and make data mutable or use a SpanReader?

Also, I think the deser type can be inferred in C++20, to avoid having to type it again:

  const auto check{[&]<typename T>(const T& obj) {
      const auto data{DataStream{} << obj};
      const auto reason = with_input ? "Transaction without outputs" : "Transaction without inputs";
      BOOST_CHECK_EXCEPTION(SpanReader{data} >> T{}, std::ios_base::failure, HasReason{reason});
  }};
nit in 9de186b5271fe3f7a9edad1740d86ea4a5db7998: Avoid the copy and make `data` mutable or use a `SpanReader`? Also, I think the deser type can be inferred in C++20, to avoid having to type it again: ```cpp const auto check{[&]<typename T>(const T& obj) { const auto data{DataStream{} << obj}; const auto reason = with_input ? "Transaction without outputs" : "Transaction without inputs"; BOOST_CHECK_EXCEPTION(SpanReader{data} >> T{}, std::ios_base::failure, HasReason{reason}); }};
maflcko (Migrated from github.com) commented 2026-11-18 10:04:08 +00:00

nit in the first commit: It took me two passes to parse the sentence. Maybe split it in two and repeat the verb?

    // reading them. So it fails here, rather than for running out of data, in either format.
nit in the first commit: It took me two passes to parse the sentence. Maybe split it in two and repeat the verb? ```cpp // reading them. So it fails here, rather than for running out of data, in either format.
maflcko (Migrated from github.com) commented 2026-11-18 10:25:44 +00:00

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:

        self.log.info('A really large transaction')
        tx = tx_from_hex(raw_tx_reference)
        assert_equal(len(tx.vin[0].serialize()), 41)
        tx.vin = [tx.vin[0]] * (MAX_BLOCK_WEIGHT // (WITNESS_SCALE_FACTOR * 41))
        self.check_mempool_result(
            result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'bad-txns-oversize'}],
            rawtxs=[tx.serialize().hex()],
        )

to keep it brief and in symmetry with the below check.

nit in the first commit: I mostly only wrote this test for fun in b55555da3e25a47f1e7fced7f09d4f0bf8198624. There is no need to retain the code exactly. It would also be fine to just use: ```py self.log.info('A really large transaction') tx = tx_from_hex(raw_tx_reference) assert_equal(len(tx.vin[0].serialize()), 41) tx.vin = [tx.vin[0]] * (MAX_BLOCK_WEIGHT // (WITNESS_SCALE_FACTOR * 41)) self.check_mempool_result( result_expected=[{'txid': tx.txid_hex, 'allowed': False, 'reject-reason': 'bad-txns-oversize'}], rawtxs=[tx.serialize().hex()], ) ``` to keep it brief and in symmetry with the below check.
sipa (Migrated from github.com) reviewed 2026-11-18 21:29:05 +00:00
sipa (Migrated from github.com) commented 2026-11-18 21:29:05 +00:00

Done.

Done.
sipa (Migrated from github.com) reviewed 2026-11-18 21:29:47 +00:00
sipa (Migrated from github.com) commented 2026-11-18 21:29:47 +00:00

Done.

Done.
sipa (Migrated from github.com) reviewed 2026-11-18 21:30:01 +00:00
sipa (Migrated from github.com) commented 2026-11-18 21:30:01 +00:00

Done.

Done.
sipa (Migrated from github.com) reviewed 2026-11-18 21:34:57 +00:00
sipa (Migrated from github.com) commented 2026-11-18 21:34:57 +00:00

My concern is/was mostly with something like a change READWRITE(block.vtx); into READWRITE(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.

My concern is/was mostly with something like a change `READWRITE(block.vtx);` into `READWRITE(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.
Yudis-bit (Migrated from github.com) reviewed 2026-11-19 13:10:05 +00:00
Yudis-bit (Migrated from github.com) commented 2026-11-19 13:10:05 +00:00

Can this stall block download when a requested block fails deserialization?

If an oversized block throws std::ios_base::failure in vRecv >> TX_WITH_WITNESS_P2P, the exception unwinds out of ProcessMessage before RemoveBlockRequest(hash, pfrom.GetId()) runs. Since the peer isn't disconnected, the hash stays in mapBlocksInFlight until the 10-minute download timeout expires.

Can this stall block download when a requested block fails deserialization? If an oversized block throws `std::ios_base::failure` in `vRecv >> TX_WITH_WITNESS_P2P`, the exception unwinds out of `ProcessMessage` before `RemoveBlockRequest(hash, pfrom.GetId())` runs. Since the peer isn't disconnected, the hash stays in `mapBlocksInFlight` until the 10-minute download timeout expires.
sipa (Migrated from github.com) reviewed 2026-11-19 13:50:51 +00:00
sipa (Migrated from github.com) commented 2026-11-19 13:50:51 +00:00

That's a fair concern. It's no different from how we treat a peer that never responds to a getdata requests 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.

That's a fair concern. It's no different from how we treat a peer that never responds to a `getdata` requests 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.
maflcko (Migrated from github.com) reviewed 2026-11-19 19:26:48 +00:00
maflcko (Migrated from github.com) left a comment

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:

untrusted comment: signature from minisign secret key on empty file; verify via: minisign -Vm "${path_to_any_empty_file}" -P RWTRmVTMeKV5noAMqVlsMugDDCyyTSbA3Re5AkUrhvLVln0tSaFWglOw -x "${path_to_this_whole_four_line_signature_blob}"
RUTRmVTMeKV5npGrKx1nqXCw5zeVHdtdYURB/KlyA/LMFgpNCs+SkW9a8N95d+U4AP1RJMi+krxU1A3Yux4bpwZNLvVBKy0wLgM=
trusted comment: lgtm 57a26d1a63091964dc7010f45b7d836e11561bda 🍄
nlrPhry58U80wfI0YzYKuIHtuKYnQAmpM8mw4Cru9svpDYi/bDGLLmopM4gcKB/ElH4HQ5aPgHJQIN0u+EWYBA==
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 57a26d1a63091964dc7010f45b7d836e11561bda 🍄 <details><summary>Show signature</summary> Signature: ``` untrusted comment: signature from minisign secret key on empty file; verify via: minisign -Vm "${path_to_any_empty_file}" -P RWTRmVTMeKV5noAMqVlsMugDDCyyTSbA3Re5AkUrhvLVln0tSaFWglOw -x "${path_to_this_whole_four_line_signature_blob}" RUTRmVTMeKV5npGrKx1nqXCw5zeVHdtdYURB/KlyA/LMFgpNCs+SkW9a8N95d+U4AP1RJMi+krxU1A3Yux4bpwZNLvVBKy0wLgM= trusted comment: lgtm 57a26d1a63091964dc7010f45b7d836e11561bda 🍄 nlrPhry58U80wfI0YzYKuIHtuKYnQAmpM8mw4Cru9svpDYi/bDGLLmopM4gcKB/ElH4HQ5aPgHJQIN0u+EWYBA== ``` </details>
maflcko (Migrated from github.com) commented 2026-11-19 15:23:57 +00:00

nit in the first commit: I think it is faster both in the happy case and the worst case to use reserve+emplace here, because the cpu can re-use the hot cache lines and the compiler can optimize the default ctor+deser a bit better?

  // Read the transaction inputs.
  tx.vin.reserve(num_inputs);
  while (tx.vin.size() < num_inputs) {
      tx.vin.emplace_back();
      s >> tx.vin.back();
  }

...

  // Read the transaction outputs.
  tx.vout.reserve(num_outputs);
  while (tx.vout.size() < num_outputs) {
      tx.vout.emplace_back();
      s >> tx.vout.back();
  }

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.

nit in the first commit: I think it is faster both in the happy case and the worst case to use `reserve`+`emplace` here, because the cpu can re-use the hot cache lines and the compiler can optimize the default ctor+deser a bit better? ```cpp // Read the transaction inputs. tx.vin.reserve(num_inputs); while (tx.vin.size() < num_inputs) { tx.vin.emplace_back(); s >> tx.vin.back(); } ... // Read the transaction outputs. tx.vout.reserve(num_outputs); while (tx.vout.size() < num_outputs) { tx.vout.emplace_back(); s >> tx.vout.back(); } ``` 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.
maflcko (Migrated from github.com) commented 2026-11-19 17:22:25 +00:00

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:

diff --git a/src/serialize.h b/src/serialize.h
index bc559d4bc7..27bc22a28f 100644
--- a/src/serialize.h
+++ b/src/serialize.h
@@ -1206,3 +1206,3 @@ class ParamsStream
     //! The state for m_params, which starts as m_params.InitState() (empty if they have none).
-    State m_state;
+    State m_state{InitState(m_params)};
 
@@ -1227,3 +1227,3 @@ class ParamsStream
 public:
-    ParamsStream(SubStream&& substream, const Params& params LIFETIMEBOUND) : m_params{params}, m_state{InitState(m_params)}, m_substream{std::forward<SubStream>(substream)} {}
+    ParamsStream(SubStream&& substream, const Params& params LIFETIMEBOUND) : m_params{params}, m_substream{std::forward<SubStream>(substream)} {}
 
style nit in c0fa7a7fd715589c838794bfb5ffd0827a2a38d7: I'd find it easier to read if this was a C++11 init and not one that is done by each ctor: ```diff diff --git a/src/serialize.h b/src/serialize.h index bc559d4bc7..27bc22a28f 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -1206,3 +1206,3 @@ class ParamsStream //! The state for m_params, which starts as m_params.InitState() (empty if they have none). - State m_state; + State m_state{InitState(m_params)}; @@ -1227,3 +1227,3 @@ class ParamsStream public: - ParamsStream(SubStream&& substream, const Params& params LIFETIMEBOUND) : m_params{params}, m_state{InitState(m_params)}, m_substream{std::forward<SubStream>(substream)} {} + ParamsStream(SubStream&& substream, const Params& params LIFETIMEBOUND) : m_params{params}, m_substream{std::forward<SubStream>(substream)} {}
maflcko (Migrated from github.com) commented 2026-11-19 19:21:44 +00:00

nit in the last commit: Can use the type of obj to avoid having to pass deser and just create a new deser object with the type of obj?

nit in the last commit: Can use the type of `obj` to avoid having to pass deser and just create a new deser object with the type of `obj`?
maflcko (Migrated from github.com) commented 2026-11-19 14:54:57 +00:00

nit in the first commit 093c7d7c4f: I think the for can be dropped for better english?

nit in the first commit 093c7d7c4f73137bbd934ed09b1f0492d2bd97dd: I think the `for` can be dropped for better english?
sipa commented 2026-11-19 20:43:18 +00:00 (Migrated from github.com)

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

@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.
Husteem commented 2026-11-20 11:29:05 +00:00 (Migrated from github.com)

tACK 57a26d1a63

Got a question here though
When a solicited block fails early deserialization, unwinding before RemoveBlockRequest() leaves its hash in mapBlocksInFlight until 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?

tACK 57a26d1a63091964dc7010f45b7d836e11561bda Got a question here though When a solicited block fails early deserialization, unwinding before `RemoveBlockRequest()` leaves its hash in `mapBlocksInFlight` until 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?
maflcko commented 2026-11-20 11:33:08 +00:00 (Migrated from github.com)

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

@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.
Husteem commented 2026-11-20 11:57:38 +00:00 (Migrated from github.com)

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.

if you have something to say, that is great, but please put it in your own words.

I'll just stick to my natural rough tone next time/onwards.

Re-hashing a prior review with an LLM is the opposite of useful.

I'd also pay closer attention to earlier discussions before asking my questions.

Thank you.

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. >if you have something to say, that is great, but please put it in your own words. I'll just stick to my natural rough tone next time/onwards. >Re-hashing a prior review with an LLM is the opposite of useful. I'd also pay closer attention to earlier discussions before asking my questions. Thank you.
sipa (Migrated from github.com) reviewed 2026-11-21 16:50:13 +00:00
sipa (Migrated from github.com) left a comment

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.

block master #36918 +counts +empty +weight
❌ 399,700 txs, 0 txins/txouts 108 108 109 0.001 0.001
❌ no outputs, witness 2.0M × 1 B 126 15 15 0.001 0.001
❌ 1 tx with 97,487 inputs 8.0 3.7 0.001 0.001 0.001
❌ 1 tx with 444,111 outputs 22 22 0.001 0.001 0.001
❌ 66,616 txs of 60 B 28 27 27 27 4.1
❌ 4 txs with 24,300 inputs each 5.1 4.8 5.4 5.3 1.0
❌ 1.05 MB scriptSig, witness 1.45M × 1 B 57 12 12 12 0.02
❌ 1,055 WU, witness 2.0M × 1 B 138 15 15 15 13
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. | block | master | #36918 | +counts | +empty | +weight | |---|--:|--:|--:|--:|--:| | ❌ 399,700 txs, 0 txins/txouts | 108 | 108 | 109 | 0.001 | 0.001 | | ❌ no outputs, witness 2.0M × 1 B | 126 | 15 | 15 | 0.001 | 0.001 | | ❌ 1 tx with 97,487 inputs | 8.0 | 3.7 | 0.001 | 0.001 | 0.001 | | ❌ 1 tx with 444,111 outputs | 22 | 22 | 0.001 | 0.001 | 0.001 | | ❌ 66,616 txs of 60 B | 28 | 27 | 27 | 27 | 4.1 | | ❌ 4 txs with 24,300 inputs each | 5.1 | 4.8 | 5.4 | 5.3 | 1.0 | | ❌ 1.05 MB scriptSig, witness 1.45M × 1 B | 57 | 12 | 12 | 12 | 0.02 | | ❌ 1,055 WU, witness 2.0M × 1 B | 138 | 15 | 15 | 15 | 13 |
sipa (Migrated from github.com) commented 2026-11-21 16:44:48 +00:00

I have dropped the weight accounting, see benchmarks above.

I have dropped the weight accounting, see benchmarks above.
sipa (Migrated from github.com) commented 2026-11-21 16:46:13 +00:00

Benchmarks don't show a measurable difference, but it's more obviously not wasting efficiency, so I've taken it.

Benchmarks don't show a measurable difference, but it's more obviously not wasting efficiency, so I've taken it.
sipa (Migrated from github.com) commented 2026-11-21 16:43:33 +00:00

Gone.

Gone.
sipa (Migrated from github.com) commented 2026-11-21 16:43:42 +00:00

Gone.

Gone.
sipa (Migrated from github.com) commented 2026-11-21 16:46:19 +00:00

Done.

Done.
Yudis-bit commented 2026-11-22 02:49:30 +00:00 (Migrated from github.com)

ACK 82cd7e7427

Makes sense to keep just these two commits and leave peer disconnect handling for undeserializable messages to a follow-up. Checked the num_inputs == 0 cases in UnserializeTransaction and the P2P call sites, and ran the updated unit and functional tests locally.

ACK 82cd7e742729bdfd5ea3be9c029c63ee9ad1f59d Makes sense to keep just these two commits and leave peer disconnect handling for undeserializable messages to a follow-up. Checked the `num_inputs == 0` cases in `UnserializeTransaction` and the P2P call sites, and ran the updated unit and functional tests locally.
l0rinc (Migrated from github.com) reviewed 2026-11-25 18:56:11 +00:00
l0rinc (Migrated from github.com) left a comment

ACK 82cd7e7427

I’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 reserve with emplace_back here, 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 with AccessByTxid. 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.

UnserializeTransaction is 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 data clearer than Superfluous witness record when the outputs are cut off.

ACK 82cd7e742729bdfd5ea3be9c029c63ee9ad1f59d I’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 `reserve` with `emplace_back` here, 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 with `AccessByTxid`. 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. `UnserializeTransaction` is 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 data` clearer than `Superfluous witness record` when [the outputs are cut off](https://github.com/bitcoin/bitcoin/pull/36906#discussion_r4697816420).
l0rinc (Migrated from github.com) commented 2026-11-25 16:36:05 +00:00

82cd7e7 p2p: reject transactions without inputs or outputs when deserializing:

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
diff --git a/doc/release-notes-36906.md b/doc/release-notes-36906.md
new file mode 100644
index 0000000000..3fd3e5c8bd
--- /dev/null
+++ b/doc/release-notes-36906.md
@@ -0,0 +1,20 @@
+P2P and network changes
+-----------------------
+
+- The node ignores `tx`, `block`, `cmpctblock` and `blocktxn` messages that
+  contain a transaction with no inputs or no outputs, or with more inputs
+  or outputs than can fit in a block.
+
+Updated RPCs
+------------
+
+- RPC decoding now rejects a transaction declaring more than 24,390 inputs
+  or 111,111 outputs. Either count alone exceeds the block weight limit.
+  With `iswitness` omitted, `decoderawtransaction` can still return a
+  different transaction if the same bytes decode in legacy format.
+
+Low-level changes
+=================
+
+- The same count limits apply to `btck_transaction_create` and
+  `btck_block_create`, which return null on decode failure.
> [82cd7e7](https://github.com/bitcoin/bitcoin/pull/36906/changes/82cd7e742729bdfd5ea3be9c029c63ee9ad1f59d) _p2p: reject transactions without inputs or outputs when deserializing_: 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. <details> <summary>Document transaction decoding changes for callers</summary> ```patch diff --git a/doc/release-notes-36906.md b/doc/release-notes-36906.md new file mode 100644 index 0000000000..3fd3e5c8bd --- /dev/null +++ b/doc/release-notes-36906.md @@ -0,0 +1,20 @@ +P2P and network changes +----------------------- + +- The node ignores `tx`, `block`, `cmpctblock` and `blocktxn` messages that + contain a transaction with no inputs or no outputs, or with more inputs + or outputs than can fit in a block. + +Updated RPCs +------------ + +- RPC decoding now rejects a transaction declaring more than 24,390 inputs + or 111,111 outputs. Either count alone exceeds the block weight limit. + With `iswitness` omitted, `decoderawtransaction` can still return a + different transaction if the same bytes decode in legacy format. + +Low-level changes +================= + +- The same count limits apply to `btck_transaction_create` and + `btck_block_create`, which return null on decode failure. ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-25 17:53:04 +00:00

ec2cabb primitives: reject txs with more inputs or outputs than fit in a block:

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, and GetSizeOfCompactSize(0) gives the empty script’s length prefix in both cases.

Use the serialized field widths for the minimum transaction weights
diff --git a/src/primitives/transaction.h b/src/primitives/transaction.h
index a7136281a9..ade6989299 100644
--- a/src/primitives/transaction.h
+++ b/src/primitives/transaction.h
@@ -184,6 +184,6 @@ inline constexpr TransactionSerParams TX_NO_WITNESS{.allow_witness = false};
 
-/** The minimum weight of a transaction input: its prevout (36 bytes), an empty scriptSig (1), and its nSequence (4). */
-inline constexpr uint64_t MIN_WEIGHT_PER_TXIN{WITNESS_SCALE_FACTOR * (36 + 1 + 4)};
-/** The minimum weight of a transaction output: its nValue (8 bytes) and an empty scriptPubKey (1). */
-inline constexpr uint64_t MIN_WEIGHT_PER_TXOUT{WITNESS_SCALE_FACTOR * (8 + 1)};
+/** Minimum input weight with an empty scriptSig. */
+inline constexpr uint64_t MIN_WEIGHT_PER_TXIN{WITNESS_SCALE_FACTOR * (Txid::size() + sizeof(COutPoint::n) + GetSizeOfCompactSize(0) + sizeof(CTxIn::nSequence))};
+/** Minimum output weight with an empty scriptPubKey. */
+inline constexpr uint64_t MIN_WEIGHT_PER_TXOUT{WITNESS_SCALE_FACTOR * (sizeof(CTxOut::nValue) + GetSizeOfCompactSize(0))};
 
> [ec2cabb](https://github.com/bitcoin/bitcoin/pull/36906/changes/ec2cabb795b616ac39b9e62df60bd9ed3ffa5af2) _primitives: reject txs with more inputs or outputs than fit in a block_: 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, and `GetSizeOfCompactSize(0)` gives the empty script’s length prefix in both cases. <details> <summary>Use the serialized field widths for the minimum transaction weights</summary> ```patch diff --git a/src/primitives/transaction.h b/src/primitives/transaction.h index a7136281a9..ade6989299 100644 --- a/src/primitives/transaction.h +++ b/src/primitives/transaction.h @@ -184,6 +184,6 @@ inline constexpr TransactionSerParams TX_NO_WITNESS{.allow_witness = false}; -/** The minimum weight of a transaction input: its prevout (36 bytes), an empty scriptSig (1), and its nSequence (4). */ -inline constexpr uint64_t MIN_WEIGHT_PER_TXIN{WITNESS_SCALE_FACTOR * (36 + 1 + 4)}; -/** The minimum weight of a transaction output: its nValue (8 bytes) and an empty scriptPubKey (1). */ -inline constexpr uint64_t MIN_WEIGHT_PER_TXOUT{WITNESS_SCALE_FACTOR * (8 + 1)}; +/** Minimum input weight with an empty scriptSig. */ +inline constexpr uint64_t MIN_WEIGHT_PER_TXIN{WITNESS_SCALE_FACTOR * (Txid::size() + sizeof(COutPoint::n) + GetSizeOfCompactSize(0) + sizeof(CTxIn::nSequence))}; +/** Minimum output weight with an empty scriptPubKey. */ +inline constexpr uint64_t MIN_WEIGHT_PER_TXOUT{WITNESS_SCALE_FACTOR * (sizeof(CTxOut::nValue) + GetSizeOfCompactSize(0))}; ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-25 16:37:00 +00:00

82cd7e7 p2p: reject transactions without inputs or outputs when deserializing:

AccessByTxid already calculates the same output limit. If we move the bounds here, it can reuse MAX_OUTPUTS_PER_BLOCK.

Share the block input and output count bounds
diff --git a/src/coins.cpp b/src/coins.cpp
index 0a40564d76..6f8b2d6467 100644
--- a/src/coins.cpp
+++ b/src/coins.cpp
@@ -6,4 +6,4 @@
 
-#include <consensus/consensus.h>
 #include <primitives/block.h>
+#include <primitives/transaction.h>
 #include <random.h>
@@ -414,5 +414,2 @@ CCoinsViewCache::ResetGuard CoinsViewOverlay::StartFetching(const CBlock& block
 
-static const uint64_t MIN_TRANSACTION_OUTPUT_WEIGHT{WITNESS_SCALE_FACTOR * ::GetSerializeSize(CTxOut())};
-static const uint64_t MAX_OUTPUTS_PER_BLOCK{MAX_BLOCK_WEIGHT / MIN_TRANSACTION_OUTPUT_WEIGHT};
-
 const Coin& AccessByTxid(const CCoinsViewCache& view, const Txid& txid)
diff --git a/src/primitives/transaction.h b/src/primitives/transaction.h
index a4be11ca43..8d10298b61 100644
--- a/src/primitives/transaction.h
+++ b/src/primitives/transaction.h
@@ -195,2 +195,5 @@ inline constexpr uint64_t MIN_WEIGHT_PER_TXIN{WITNESS_SCALE_FACTOR * (36 + 1 + 4
 inline constexpr uint64_t MIN_WEIGHT_PER_TXOUT{WITNESS_SCALE_FACTOR * (8 + 1)};
+/** Upper bounds on the number of inputs or outputs in a block, ignoring other fields. */
+inline constexpr uint64_t MAX_INPUTS_PER_BLOCK{MAX_BLOCK_WEIGHT / MIN_WEIGHT_PER_TXIN};
+inline constexpr uint64_t MAX_OUTPUTS_PER_BLOCK{MAX_BLOCK_WEIGHT / MIN_WEIGHT_PER_TXOUT};
 
@@ -232,3 +235,3 @@ void UnserializeTransaction(TxType& tx, Stream& s, const TransactionSerParams& p
     // memory allocated for them.
-    if (num_inputs > MAX_BLOCK_WEIGHT / MIN_WEIGHT_PER_TXIN) throw std::ios_base::failure("Too many transaction inputs");
+    if (num_inputs > MAX_INPUTS_PER_BLOCK) throw std::ios_base::failure("Too many transaction inputs");
     if (num_inputs == 0 && params.reject_empty) throw std::ios_base::failure("Transaction without inputs");
@@ -244,3 +247,3 @@ void UnserializeTransaction(TxType& tx, Stream& s, const TransactionSerParams& p
     auto num_outputs = (num_inputs == 0 && fAllowWitness) ? uint64_t{0} : ReadCompactSize(s);
-    if (num_outputs > MAX_BLOCK_WEIGHT / MIN_WEIGHT_PER_TXOUT) throw std::ios_base::failure("Too many transaction outputs");
+    if (num_outputs > MAX_OUTPUTS_PER_BLOCK) throw std::ios_base::failure("Too many transaction outputs");
     if (num_outputs == 0 && params.reject_empty) throw std::ios_base::failure("Transaction without outputs");
> [82cd7e7](https://github.com/bitcoin/bitcoin/pull/36906/changes/82cd7e742729bdfd5ea3be9c029c63ee9ad1f59d) _p2p: reject transactions without inputs or outputs when deserializing_: `AccessByTxid` already calculates the same output limit. If we move the bounds here, it can reuse `MAX_OUTPUTS_PER_BLOCK`. <details> <summary>Share the block input and output count bounds</summary> ```patch diff --git a/src/coins.cpp b/src/coins.cpp index 0a40564d76..6f8b2d6467 100644 --- a/src/coins.cpp +++ b/src/coins.cpp @@ -6,4 +6,4 @@ -#include <consensus/consensus.h> #include <primitives/block.h> +#include <primitives/transaction.h> #include <random.h> @@ -414,5 +414,2 @@ CCoinsViewCache::ResetGuard CoinsViewOverlay::StartFetching(const CBlock& block -static const uint64_t MIN_TRANSACTION_OUTPUT_WEIGHT{WITNESS_SCALE_FACTOR * ::GetSerializeSize(CTxOut())}; -static const uint64_t MAX_OUTPUTS_PER_BLOCK{MAX_BLOCK_WEIGHT / MIN_TRANSACTION_OUTPUT_WEIGHT}; - const Coin& AccessByTxid(const CCoinsViewCache& view, const Txid& txid) diff --git a/src/primitives/transaction.h b/src/primitives/transaction.h index a4be11ca43..8d10298b61 100644 --- a/src/primitives/transaction.h +++ b/src/primitives/transaction.h @@ -195,2 +195,5 @@ inline constexpr uint64_t MIN_WEIGHT_PER_TXIN{WITNESS_SCALE_FACTOR * (36 + 1 + 4 inline constexpr uint64_t MIN_WEIGHT_PER_TXOUT{WITNESS_SCALE_FACTOR * (8 + 1)}; +/** Upper bounds on the number of inputs or outputs in a block, ignoring other fields. */ +inline constexpr uint64_t MAX_INPUTS_PER_BLOCK{MAX_BLOCK_WEIGHT / MIN_WEIGHT_PER_TXIN}; +inline constexpr uint64_t MAX_OUTPUTS_PER_BLOCK{MAX_BLOCK_WEIGHT / MIN_WEIGHT_PER_TXOUT}; @@ -232,3 +235,3 @@ void UnserializeTransaction(TxType& tx, Stream& s, const TransactionSerParams& p // memory allocated for them. - if (num_inputs > MAX_BLOCK_WEIGHT / MIN_WEIGHT_PER_TXIN) throw std::ios_base::failure("Too many transaction inputs"); + if (num_inputs > MAX_INPUTS_PER_BLOCK) throw std::ios_base::failure("Too many transaction inputs"); if (num_inputs == 0 && params.reject_empty) throw std::ios_base::failure("Transaction without inputs"); @@ -244,3 +247,3 @@ void UnserializeTransaction(TxType& tx, Stream& s, const TransactionSerParams& p auto num_outputs = (num_inputs == 0 && fAllowWitness) ? uint64_t{0} : ReadCompactSize(s); - if (num_outputs > MAX_BLOCK_WEIGHT / MIN_WEIGHT_PER_TXOUT) throw std::ios_base::failure("Too many transaction outputs"); + if (num_outputs > MAX_OUTPUTS_PER_BLOCK) throw std::ios_base::failure("Too many transaction outputs"); if (num_outputs == 0 && params.reject_empty) throw std::ios_base::failure("Transaction without outputs"); ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-25 17:20:14 +00:00

ec2cabb primitives: reject txs with more inputs or outputs than fit in a block:

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.

> [ec2cabb](https://github.com/bitcoin/bitcoin/pull/36906/changes/ec2cabb795b616ac39b9e62df60bd9ed3ffa5af2) _primitives: reject txs with more inputs or outputs than fit in a block_: Following up on [my review of #36521](https://github.com/bitcoin/bitcoin/pull/36521#pullrequestreview-5871920324) 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](https://github.com/bitcoin/bitcoin/pull/36548/changes/e7976647484f3a3a5e5c964c30265a6e402eab81#diff-32f83e93b123235079fbadc3f68f8158c56c67d031a579475e16c6857edbecbfR189-R219) - but maybe that's too much and there's a safer or simpler way.
l0rinc (Migrated from github.com) commented 2026-11-25 17:39:12 +00:00

I also did a reindex-chainstate which showed no speed difference whatsoever.

I also did a reindex-chainstate which showed no speed difference whatsoever.
l0rinc (Migrated from github.com) commented 2026-11-25 16:36:24 +00:00

82cd7e7 p2p: reject transactions without inputs or outputs when deserializing:

Getting Superfluous witness record when the output data is incomplete could be confusing for the user, we could also check flags here...

Preserve output-count parsing for zero-input transactions
diff --git a/src/primitives/transaction.h b/src/primitives/transaction.h
index a4be11ca43..88a3161099 100644
--- a/src/primitives/transaction.h
+++ b/src/primitives/transaction.h
@@ -241,5 +241,4 @@ void UnserializeTransaction(TxType& tx, Stream& s, const TransactionSerParams& p
 
-    // Read the number of outputs. In case of an empty vin, the byte read as the flags is the number of outputs (if the
-    // flags are not zero, there is witness data without inputs, which fails below).
-    auto num_outputs = (num_inputs == 0 && fAllowWitness) ? uint64_t{0} : ReadCompactSize(s);
+    // Read the number of outputs unless we already read the zero output count as the flags byte.
+    auto num_outputs = (num_inputs == 0 && fAllowWitness && flags == 0) ? uint64_t{0} : ReadCompactSize(s);
     if (num_outputs > MAX_BLOCK_WEIGHT / MIN_WEIGHT_PER_TXOUT) throw std::ios_base::failure("Too many transaction outputs");
diff --git a/src/test/transaction_tests.cpp b/src/test/transaction_tests.cpp
index a4ef16bd9e..63932b3e08 100644
--- a/src/test/transaction_tests.cpp
+++ b/src/test/transaction_tests.cpp
@@ -1501,4 +1501,7 @@ BOOST_AUTO_TEST_CASE(reject_empty)
     BOOST_CHECK_EXCEPTION(deser_tx(ext_no_inputs, TX_WITH_WITNESS_P2P), std::ios_base::failure, HasReason("Transaction without inputs"));
-    // ... even when the outputs that would follow are missing.
+    // Ordinary decoding reports the truncated output or its missing count.
+    ext_no_inputs.resize(9);
+    BOOST_CHECK_EXCEPTION(deser_tx(ext_no_inputs, TX_WITH_WITNESS), std::ios_base::failure, HasReason("end of data"));
     ext_no_inputs.resize(7);
+    BOOST_CHECK_EXCEPTION(deser_tx(ext_no_inputs, TX_WITH_WITNESS), std::ios_base::failure, HasReason("end of data"));
     BOOST_CHECK_EXCEPTION(deser_tx(ext_no_inputs, TX_WITH_WITNESS_P2P), std::ios_base::failure, HasReason("Transaction without inputs"));
> [82cd7e7](https://github.com/bitcoin/bitcoin/pull/36906/changes/82cd7e742729bdfd5ea3be9c029c63ee9ad1f59d) _p2p: reject transactions without inputs or outputs when deserializing_: Getting `Superfluous witness record` when the output data is incomplete could be confusing for the user, we could also check `flags` here... <details> <summary>Preserve output-count parsing for zero-input transactions</summary> ```patch diff --git a/src/primitives/transaction.h b/src/primitives/transaction.h index a4be11ca43..88a3161099 100644 --- a/src/primitives/transaction.h +++ b/src/primitives/transaction.h @@ -241,5 +241,4 @@ void UnserializeTransaction(TxType& tx, Stream& s, const TransactionSerParams& p - // Read the number of outputs. In case of an empty vin, the byte read as the flags is the number of outputs (if the - // flags are not zero, there is witness data without inputs, which fails below). - auto num_outputs = (num_inputs == 0 && fAllowWitness) ? uint64_t{0} : ReadCompactSize(s); + // Read the number of outputs unless we already read the zero output count as the flags byte. + auto num_outputs = (num_inputs == 0 && fAllowWitness && flags == 0) ? uint64_t{0} : ReadCompactSize(s); if (num_outputs > MAX_BLOCK_WEIGHT / MIN_WEIGHT_PER_TXOUT) throw std::ios_base::failure("Too many transaction outputs"); diff --git a/src/test/transaction_tests.cpp b/src/test/transaction_tests.cpp index a4ef16bd9e..63932b3e08 100644 --- a/src/test/transaction_tests.cpp +++ b/src/test/transaction_tests.cpp @@ -1501,4 +1501,7 @@ BOOST_AUTO_TEST_CASE(reject_empty) BOOST_CHECK_EXCEPTION(deser_tx(ext_no_inputs, TX_WITH_WITNESS_P2P), std::ios_base::failure, HasReason("Transaction without inputs")); - // ... even when the outputs that would follow are missing. + // Ordinary decoding reports the truncated output or its missing count. + ext_no_inputs.resize(9); + BOOST_CHECK_EXCEPTION(deser_tx(ext_no_inputs, TX_WITH_WITNESS), std::ios_base::failure, HasReason("end of data")); ext_no_inputs.resize(7); + BOOST_CHECK_EXCEPTION(deser_tx(ext_no_inputs, TX_WITH_WITNESS), std::ios_base::failure, HasReason("end of data")); BOOST_CHECK_EXCEPTION(deser_tx(ext_no_inputs, TX_WITH_WITNESS_P2P), std::ios_base::failure, HasReason("Transaction without inputs")); ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-25 16:35:02 +00:00

82cd7e7 p2p: reject transactions without inputs or outputs when deserializing:

A funding template can have outputs before the wallet picks any inputs. I’d check that those outputs survive a TX_NO_WITNESS round trip here.

Cover zero-input funding templates in the ordinary decoder
diff --git a/src/test/transaction_tests.cpp b/src/test/transaction_tests.cpp
index 3ae1f00267..a4ef16bd9e 100644
--- a/src/test/transaction_tests.cpp
+++ b/src/test/transaction_tests.cpp
@@ -1482,2 +1482,10 @@ BOOST_AUTO_TEST_CASE(reject_empty)
 
+    // A legacy transaction with outputs but no inputs can be read for funding.
+    CMutableTransaction no_inputs;
+    no_inputs.vout.emplace_back(1, CScript{} << OP_TRUE);
+    const auto no_inputs_ser{DataStream{} << TX_NO_WITNESS(no_inputs)};
+    const auto unfunded{deser_tx(no_inputs_ser, TX_NO_WITNESS)};
+    BOOST_CHECK(unfunded.vin.empty());
+    BOOST_CHECK(unfunded.vout == no_inputs.vout);
+
     // A transaction without outputs.
> [82cd7e7](https://github.com/bitcoin/bitcoin/pull/36906/changes/82cd7e742729bdfd5ea3be9c029c63ee9ad1f59d) _p2p: reject transactions without inputs or outputs when deserializing_: A funding template can have outputs before the wallet picks any inputs. I’d check that those outputs survive a `TX_NO_WITNESS` round trip here. <details> <summary>Cover zero-input funding templates in the ordinary decoder</summary> ```patch diff --git a/src/test/transaction_tests.cpp b/src/test/transaction_tests.cpp index 3ae1f00267..a4ef16bd9e 100644 --- a/src/test/transaction_tests.cpp +++ b/src/test/transaction_tests.cpp @@ -1482,2 +1482,10 @@ BOOST_AUTO_TEST_CASE(reject_empty) + // A legacy transaction with outputs but no inputs can be read for funding. + CMutableTransaction no_inputs; + no_inputs.vout.emplace_back(1, CScript{} << OP_TRUE); + const auto no_inputs_ser{DataStream{} << TX_NO_WITNESS(no_inputs)}; + const auto unfunded{deser_tx(no_inputs_ser, TX_NO_WITNESS)}; + BOOST_CHECK(unfunded.vin.empty()); + BOOST_CHECK(unfunded.vout == no_inputs.vout); + // A transaction without outputs. ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-25 16:34:38 +00:00

82cd7e7 p2p: reject transactions without inputs or outputs when deserializing:

These blocks used to exercise bad-txns-vin-empty and bad-txns-vout-empty. Now that P2P deserialization stops earlier, sending the same blocks through submitblock would keep both checks covered.

Keep the block validation reasons covered through submitblock
diff --git a/test/functional/feature_block.py b/test/functional/feature_block.py
index 66d0b59512..00d61f76a8 100755
--- a/test/functional/feature_block.py
+++ b/test/functional/feature_block.py
@@ -198,3 +198,3 @@ class FullBlockTest(BitcoinTestFramework):
             badblock = self.update_block(blockname, [badtx])
-            reject_reason = (template.p2p_deserialization_error or template.block_reject_reason or template.reject_reason)
+            reject_reason = (template.block_reject_reason or template.reject_reason)
             if reject_reason.startswith("mempool-script-verify-flag-failed"):
@@ -204,4 +204,6 @@ class FullBlockTest(BitcoinTestFramework):
                 [badblock], success=False,
-                reject_reason=reject_reason,
+                reject_reason=template.p2p_deserialization_error or reject_reason,
                 reconnect=template.p2p_deserialization_error is None, timeout=2)
+            if template.p2p_deserialization_error:
+                assert_equal(self.nodes[0].submitblock(badblock.serialize().hex()), reject_reason)
 
> [82cd7e7](https://github.com/bitcoin/bitcoin/pull/36906/changes/82cd7e742729bdfd5ea3be9c029c63ee9ad1f59d) _p2p: reject transactions without inputs or outputs when deserializing_: These blocks used to exercise `bad-txns-vin-empty` and `bad-txns-vout-empty`. Now that P2P deserialization stops earlier, sending the same blocks through `submitblock` would keep both checks covered. <details> <summary>Keep the block validation reasons covered through submitblock</summary> ```patch diff --git a/test/functional/feature_block.py b/test/functional/feature_block.py index 66d0b59512..00d61f76a8 100755 --- a/test/functional/feature_block.py +++ b/test/functional/feature_block.py @@ -198,3 +198,3 @@ class FullBlockTest(BitcoinTestFramework): badblock = self.update_block(blockname, [badtx]) - reject_reason = (template.p2p_deserialization_error or template.block_reject_reason or template.reject_reason) + reject_reason = (template.block_reject_reason or template.reject_reason) if reject_reason.startswith("mempool-script-verify-flag-failed"): @@ -204,4 +204,6 @@ class FullBlockTest(BitcoinTestFramework): [badblock], success=False, - reject_reason=reject_reason, + reject_reason=template.p2p_deserialization_error or reject_reason, reconnect=template.p2p_deserialization_error is None, timeout=2) + if template.p2p_deserialization_error: + assert_equal(self.nodes[0].submitblock(badblock.serialize().hex()), reject_reason) ``` </details>
l0rinc (Migrated from github.com) commented 2026-11-25 17:19:57 +00:00

ec2cabb primitives: reject txs with more inputs or outputs than fit in a block:

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-oversize from validation.
A separate case farther over the limit could check for TX decode failed.

> [ec2cabb](https://github.com/bitcoin/bitcoin/pull/36906/changes/ec2cabb795b616ac39b9e62df60bd9ed3ffa5af2) _primitives: reject txs with more inputs or outputs than fit in a block_: 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-oversize` from validation. A separate case farther over the limit could check for `TX decode failed`.
sipa (Migrated from github.com) reviewed 2026-11-27 15:18:07 +00:00
sipa (Migrated from github.com) commented 2026-11-27 15:20:24 +00:00

I've added a short release note about the RPCs. I don't think the rest is visible enough to mention for users.

I've added a short release note about the RPCs. I don't think the rest is visible enough to mention for users.
sipa (Migrated from github.com) commented 2026-11-27 15:43:57 +00:00

I don't like using sizeof here. 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.

I don't like using `sizeof` here. 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.
sipa (Migrated from github.com) commented 2026-11-27 15:23:08 +00:00

Done.

Done.
sipa (Migrated from github.com) commented 2026-11-27 15:42:23 +00:00

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.

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.
sipa (Migrated from github.com) commented 2026-11-27 15:22:57 +00:00

Done.

Done.
sipa (Migrated from github.com) commented 2026-11-27 15:18:48 +00:00

Done.

Done.
sipa (Migrated from github.com) commented 2026-11-27 15:18:07 +00:00

Done.

Done.
sipa (Migrated from github.com) commented 2026-11-27 15:28:51 +00:00

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.

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.
sipa (Migrated from github.com) reviewed 2026-11-27 15:53:11 +00:00
sipa (Migrated from github.com) commented 2026-11-27 15:53:11 +00:00

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.

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.
l0rinc (Migrated from github.com) reviewed 2026-11-27 20:10:41 +00:00
l0rinc (Migrated from github.com) commented 2026-11-27 20:10:41 +00:00

I removed the lambda in my latest push, let's see what the reviewers will think - can be resolved

I removed the lambda in my latest push, let's see what the reviewers will think - can be resolved
l0rinc (Migrated from github.com) reviewed 2026-11-27 20:13:32 +00:00
l0rinc (Migrated from github.com) commented 2026-11-27 20:13:32 +00:00

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?

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?
ajtowns (Migrated from github.com) reviewed 2026-11-28 10:03:52 +00:00
ajtowns (Migrated from github.com) left a comment

Approach ACK, untested.

Approach ACK, untested.
ajtowns (Migrated from github.com) commented 2026-11-28 09:54:28 +00:00

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?

`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?
maflcko commented 2026-11-30 10:24:05 +00:00 (Migrated from github.com)

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:

  • Minor style cleanups (Extract MAX*PER_BLOCK, use reserve+emplace_back).
  • Do a bit more work for TX_WITH_WITNESS-deser to decode vout again to return a possible "end of data" over "Superfluous witness record". Either seems fine here.
  • Add release note for rpc.

review ACK 1681dec88d 🌻

Show signature

Signature:

untrusted comment: signature from minisign secret key on empty file; verify via: minisign -Vm "${path_to_any_empty_file}" -P RWTRmVTMeKV5noAMqVlsMugDDCyyTSbA3Re5AkUrhvLVln0tSaFWglOw -x "${path_to_this_whole_four_line_signature_blob}"
RUTRmVTMeKV5npGrKx1nqXCw5zeVHdtdYURB/KlyA/LMFgpNCs+SkW9a8N95d+U4AP1RJMi+krxU1A3Yux4bpwZNLvVBKy0wLgM=
trusted comment: review ACK 1681dec88de01ae0f167ae7176889a76378b92bc 🌻
Q8bUMLi0pASKqV9/tjbKwXHKbVoy79DlPTtefJIGsefSTKIx9g/qElcs8kqt+BEemantYfszzEDVpbPgZDACCA==
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: * Minor style cleanups (Extract `MAX*PER_BLOCK`, use `reserve+emplace_back`). * Do a bit more work for `TX_WITH_WITNESS`-deser to decode vout again to return a possible "end of data" over "Superfluous witness record". Either seems fine here. * Add release note for rpc. review ACK 1681dec88de01ae0f167ae7176889a76378b92bc 🌻 <details><summary>Show signature</summary> Signature: ``` untrusted comment: signature from minisign secret key on empty file; verify via: minisign -Vm "${path_to_any_empty_file}" -P RWTRmVTMeKV5noAMqVlsMugDDCyyTSbA3Re5AkUrhvLVln0tSaFWglOw -x "${path_to_this_whole_four_line_signature_blob}" RUTRmVTMeKV5npGrKx1nqXCw5zeVHdtdYURB/KlyA/LMFgpNCs+SkW9a8N95d+U4AP1RJMi+krxU1A3Yux4bpwZNLvVBKy0wLgM= trusted comment: review ACK 1681dec88de01ae0f167ae7176889a76378b92bc 🌻 Q8bUMLi0pASKqV9/tjbKwXHKbVoy79DlPTtefJIGsefSTKIx9g/qElcs8kqt+BEemantYfszzEDVpbPgZDACCA== ``` </details>
Yudis-bit commented 2026-12-01 15:50:04 +00:00 (Migrated from github.com)

re-ACK 1681dec88d

Checked the flags == 0 change and re-ran the tests locally.

re-ACK 1681dec88de01ae0f167ae7176889a76378b92bc Checked the `flags == 0` change and re-ran the tests locally.
l0rinc (Migrated from github.com) approved these changes 2026-12-01 18:59:54 +00:00
l0rinc (Migrated from github.com) left a comment

tested ACK 1681dec88d

Since 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 through submitblock.

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_VECTOR suggestion is taken.

tested ACK 1681dec88de01ae0f167ae7176889a76378b92bc Since 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 through `submitblock`. 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_VECTOR` suggestion](https://github.com/bitcoin/bitcoin/pull/36906#discussion_r4726480196) is taken.
l0rinc (Migrated from github.com) commented 2026-12-01 13:44:40 +00:00

329a79c primitives: reject txs with more inputs or outputs than fit in a block:

With the output bound shared in this commit, bitcoin-tx could drop its duplicate calculation and use MAX_OUTPUTS_PER_BLOCK too.

Reuse the shared output bound in bitcoin-tx
diff --git a/src/bitcoin-tx.cpp b/src/bitcoin-tx.cpp
index 1e15b5028d..fbedc6b061 100644
--- a/src/bitcoin-tx.cpp
+++ b/src/bitcoin-tx.cpp
@@ -12,7 +12,6 @@
 #include <common/system.h>
 #include <compat/compat.h>
 #include <consensus/amount.h>
-#include <consensus/consensus.h>
 #include <core_io.h>
 #include <crypto/sha256.h>
 #include <key_io.h>
@@ -272,13 +271,10 @@ static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInpu
         throw std::runtime_error("invalid TX input txid");
     }
 
-    static const unsigned int minTxOutSz = 9;
-    static const unsigned int maxVout = MAX_BLOCK_WEIGHT / (WITNESS_SCALE_FACTOR * minTxOutSz);
-
     // extract and validate vout
     const std::string& strVout = vStrInputParts[1];
     const auto vout{ToIntegral<uint32_t>(strVout)};
-    if (!vout || *vout > maxVout) {
+    if (!vout || *vout > MAX_OUTPUTS_PER_BLOCK) {
         throw std::runtime_error("invalid TX input vout '" + strVout + "'");
     }
 
> [329a79c](https://github.com/bitcoin/bitcoin/pull/36906/changes/329a79c064fe6e0d5605f3ed2789736bfbf5354c) _primitives: reject txs with more inputs or outputs than fit in a block_: With the output bound shared in this commit, `bitcoin-tx` could drop its duplicate calculation and use `MAX_OUTPUTS_PER_BLOCK` too. <details><summary>Reuse the shared output bound in bitcoin-tx</summary> ```diff diff --git a/src/bitcoin-tx.cpp b/src/bitcoin-tx.cpp index 1e15b5028d..fbedc6b061 100644 --- a/src/bitcoin-tx.cpp +++ b/src/bitcoin-tx.cpp @@ -12,7 +12,6 @@ #include <common/system.h> #include <compat/compat.h> #include <consensus/amount.h> -#include <consensus/consensus.h> #include <core_io.h> #include <crypto/sha256.h> #include <key_io.h> @@ -272,13 +271,10 @@ static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInpu throw std::runtime_error("invalid TX input txid"); } - static const unsigned int minTxOutSz = 9; - static const unsigned int maxVout = MAX_BLOCK_WEIGHT / (WITNESS_SCALE_FACTOR * minTxOutSz); - // extract and validate vout const std::string& strVout = vStrInputParts[1]; const auto vout{ToIntegral<uint32_t>(strVout)}; - if (!vout || *vout > maxVout) { + if (!vout || *vout > MAX_OUTPUTS_PER_BLOCK) { throw std::runtime_error("invalid TX input vout '" + strVout + "'"); } ``` </details>
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!36906
No description provided.