Skip to content

Detect transaction problems early during deserialization - #36906

Open
sipa wants to merge 3 commits into
bitcoin:masterfrom
sipa:202611_txdeser_failfast
Open

sipa wants to merge 3 commits into
bitcoin:masterfrom
sipa:202611_txdeser_failfast

Conversation

@sipa

@sipa sipa commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

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

DrahtBot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
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.

@sipa

sipa commented Nov 17, 2026

Copy link
Copy Markdown
Member Author

@ajtowns I considered your suggestion in #36521 (comment), 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.

Comment thread src/net_processing.cpp Outdated
// The transactions are part of the block, so stop deserializing as soon as they exceed the weight that the
// transactions of a valid block can have (not accounting for those of the block that are already known).
TxWeightBudget budget{MAX_BLOCK_TXS_WEIGHT};
vRecv >> WithState{budget}(TX_WITH_WITNESS_P2P(resp));

@ajtowns ajtowns Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ajtowns I considered your suggestion in #36521 (comment), 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have dropped the weight accounting, see benchmarks above.

@maflcko maflcko left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

partial review

lgtm aaea704~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==

Comment thread src/test/transaction_tests.cpp Resolved
Comment thread test/functional/mempool_accept.py Resolved
Comment thread src/test/blockencodings_tests.cpp Resolved
@sipa
sipa force-pushed the 202611_txdeser_failfast branch from aaea704 to 57a26d1 Compare November 18, 2026 21:24
Comment thread src/net_processing.cpp

std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
vRecv >> TX_WITH_WITNESS(*pblock);
vRecv >> TX_WITH_WITNESS_P2P(*pblock);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 maflcko left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 57a26d1 🍄

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

Comment thread src/test/transaction_tests.cpp Resolved
Comment thread src/primitives/transaction.h Resolved
Comment thread src/serialize.h Resolved
Comment thread src/test/blockencodings_tests.cpp Resolved
@sipa

sipa commented Nov 19, 2026

Copy link
Copy Markdown
Member Author

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

@sipa sipa left a comment •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/serialize.h Resolved
Comment thread src/test/blockencodings_tests.cpp Resolved
Comment thread src/net_processing.cpp Outdated
// The transactions are part of the block, so stop deserializing as soon as they exceed the weight that the
// transactions of a valid block can have (not accounting for those of the block that are already known).
TxWeightBudget budget{MAX_BLOCK_TXS_WEIGHT};
vRecv >> WithState{budget}(TX_WITH_WITNESS_P2P(resp));

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have dropped the weight accounting, see benchmarks above.

Comment thread src/primitives/transaction.h Resolved
Comment thread src/test/transaction_tests.cpp Resolved
@Yudis-bit

Copy link
Copy Markdown

ACK 82cd7e7

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 l0rinc left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK 82cd7e7

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.

Comment thread test/functional/feature_block.py Resolved
Comment thread src/test/transaction_tests.cpp Resolved
inline constexpr TransactionSerParams TX_NO_WITNESS{.allow_witness = false};
/** TX_WITH_WITNESS, but rejecting transactions without inputs or outputs. For data received from
* P2P peers. */
inline constexpr TransactionSerParams TX_WITH_WITNESS_P2P{.allow_witness = true, .reject_empty = true};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/primitives/transaction.h Resolved
Comment thread src/primitives/transaction.h Resolved
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) + 1)
assert_raises_rpc_error(-22, 'TX decode failed', lambda: node.testmempoolaccept(rawtxs=[tx.serialize().hex()]))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

} else {
/* We read a non-empty vin. Assume a normal vout follows. */
s >> tx.vout;
if (flags != 0) num_inputs = ReadCompactSize(s);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/primitives/transaction.h Resolved
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)};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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))};
 

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 added 3 commits November 27, 2026 03:03
When deserializing a transaction, read the input and output counts
first, and fail before reading the inputs or outputs if more of them
are claimed than can fit in a block, given their minimum size (41 bytes
for an input, 9 for an output). Such a transaction can never be valid.

This allows us to allocate the vin and vout vectors immediately, rather
than sequentially in batches of 5 MB as the std::vector deserializer
does, because that memory becomes bounded: to 2.7 MB for 24390 inputs,
and 5.3 MB for 111111 outputs. It is a preparation for further changes
that rely on this structuring of conditionals.

This affects all places where transactions are deserialized. Through
RPC, such transactions can no longer be decoded. From P2P, a transaction
or block containing one is ignored like other malformed messages, rather
than rejected by validation.

The bound on the number of outputs replaces an identical one that
AccessByTxid in coins.cpp computed separately.
Add a reject_empty flag to TransactionSerParams, which makes
deserialization fail as soon as a transaction is found to have no
inputs or no outputs. Such transactions are never valid, but are
currently fully deserialized (along with the rest of the message) before
validation rejects them.

This reduces the memory a peer can make us allocate by sending a block
full of such transactions. At 10 bytes each, about 400000 of them fit in
a block message, each of which gets its own CTransaction. With this
change, the smallest transaction that gets deserialized has one input
and one output, which takes 60 bytes.

The flag is enabled (as TX_WITH_WITNESS_P2P) only where transactions are
received from P2P peers: tx and block messages, and the transactions in
cmpctblock and blocktxn messages. Like other malformed messages, these
are now ignored, rather than, for a block, causing the peer to be
disconnected, or, for a transaction, being added to the reject filters.
The functional tests are updated accordingly.
@sipa
sipa force-pushed the 202611_txdeser_failfast branch from 82cd7e7 to 1681dec Compare November 27, 2026 15:15

@ajtowns ajtowns left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approach ACK, untested.

if (num_inputs > MAX_INPUTS_PER_BLOCK) throw std::ios_base::failure("Too many transaction inputs");
// Read the transaction inputs.
tx.vin.reserve(num_inputs);
while (tx.vin.size() < num_inputs) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

maflcko commented Nov 30, 2026

Copy link
Copy Markdown
Member

Only change since my last review ( #36906 (review) ) is dropping the running weight accounting, per the benchmarks in #36906 (review). 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 1681dec 🌻

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

@Yudis-bit

Copy link
Copy Markdown

re-ACK 1681dec

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

@l0rinc l0rinc left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tested ACK 1681dec

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.

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};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 + "'");
     }
 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants