Skip to content

policy: use 64-bit accumulator for package total weight - #35473

Closed
digin1 wants to merge 1 commit into
bitcoin:masterfrom
digin1:policy-package-weight-64bit
Closed

digin1 wants to merge 1 commit into
bitcoin:masterfrom
digin1:policy-package-weight-64bit

Conversation

@digin1

@digin1 digin1 commented Jun 6, 2026

Copy link
Copy Markdown

IsWellFormedPackage() enforces MAX_PACKAGE_WEIGHT by summing each transaction's weight:

const int64_t total_weight = std::accumulate(txns.cbegin(), txns.cend(), 0,
                           [](int64_t sum, const auto& tx) { return sum + GetTransactionWeight(*tx); });
if (package_count > 1 && total_weight > MAX_PACKAGE_WEIGHT) { ... "package-too-large" }

std::accumulate's accumulator type is the type of the init value. The init here is the literal 0, so the accumulator is an int: the 64-bit lambda result is narrowed back to 32 bits on every iteration. A package whose true combined weight exceeds INT_MAX therefore wraps to a small or negative value, and the total_weight > MAX_PACKAGE_WEIGHT check is silently bypassed.

This is the only place MAX_PACKAGE_WEIGHT is enforced. The two sibling weight/fee accumulations in the package-acceptance path already use a 64-bit init (int64_t{0} / CAmount{0}); this call site is the inconsistent one.

Impact

Limited and policy-only — not a consensus issue:

  • Oversized transactions are still rejected individually by the per-transaction weight/standardness checks that run after IsWellFormedPackage(), so this does not let over-weight transactions into the mempool.
  • The effect is that the package-level early rejection (package-too-large) fails to fire for a package whose combined weight crosses INT_MAX, so the node does more work before rejecting. Such a package is reachable e.g. via the submitpackage RPC with sufficiently large transactions.

Still, the guard should do what it says, and relying on 32-bit truncation of a weight sum is fragile.

Fix

One line — initialise the accumulator with int64_t{0}.

Test

Adds package_weight_overflow_tests to txpackage_tests.cpp. Because triggering the wrap requires a combined weight above INT_MAX and MAX_PACKAGE_COUNT is 25, each transaction must be large. To avoid allocating 25 separate large transactions, the test reuses one ~27 MB transaction 25 times — the weight check runs before the duplicate-txid check, so the accumulator still sees 25 × weight. The test asserts the rejection reason is package-too-large; on the unfixed code the wrapped total bypasses the weight check and the reason is instead package-contains-duplicates. Happy to drop or slim the test if the maintainers prefer.

How to reproduce the mechanism

The truncation can be observed in isolation with a minimal program that mirrors the exact std::accumulate expression: 25 weights of ~90,000,000 sum to 2,250,000,000 (> INT_MAX); the int-accumulator version returns -2,044,967,296 (guard bypassed) while an int64_t accumulator returns the correct 2,250,000,000 (guard fires).

IsWellFormedPackage() sums each transaction's weight to enforce
MAX_PACKAGE_WEIGHT, but the std::accumulate() initial value is a plain
`0`, which makes the accumulator an `int`. The 64-bit lambda result is
therefore narrowed back to 32 bits on every iteration, so a package
whose combined weight exceeds INT_MAX wraps to a small or negative
value and slips past the "package-too-large" check.

Initialise the accumulator with int64_t{0} so the running total is kept
in 64 bits, consistent with the other weight/fee accumulations in the
package validation path.

Add a regression test that reuses a single large transaction
MAX_PACKAGE_COUNT times so the summed weight crosses INT_MAX while
keeping the test's footprint to one transaction. With the bug present
the wrapped total bypasses the weight check and the package is instead
rejected as "package-contains-duplicates"; with the fix it is correctly
rejected as "package-too-large".
Copilot AI review requested due to automatic review settings June 6, 2026 15:33
@DrahtBot

DrahtBot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

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

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/35473.

Reviews

See the guideline for information on the review process.
A summary of reviews will appear here.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Fixes an integer-truncation issue in IsWellFormedPackage’s package-weight calculation and adds a regression test to ensure oversized packages are rejected for the correct reason.

Changes:

  • Use a 64-bit initial value in std::accumulate to prevent narrowing the running sum to int.
  • Add a regression test that exercises the overflow/truncation scenario and asserts the correct reject reason.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
src/policy/packages.cpp Prevents truncation by making the std::accumulate initial value int64_t{0}.
src/test/txpackage_tests.cpp Adds a regression test for the weight-accumulator truncation case and includes <limits> for bounds checks.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +226 to +231
// Preconditions for this regression to be meaningful: a single tx is under
// INT_MAX, but MAX_PACKAGE_COUNT copies exceed it (and stay below 2^32, so a
// 32-bit accumulator wraps to a value <= MAX_PACKAGE_WEIGHT).
BOOST_REQUIRE(tx_weight <= std::numeric_limits<int32_t>::max());
BOOST_REQUIRE(total_true_weight > std::numeric_limits<int32_t>::max());
BOOST_REQUIRE(total_true_weight < (int64_t{1} << 32));
Comment on lines +219 to +223
// ~27 MB tx => weight ~109M; 25 copies => true total ~2.73e9, which exceeds
// INT_MAX (~2.147e9) and so overflows a 32-bit accumulator, yet stays a single
// ~27 MB allocation rather than 25 separate large transactions.
CTransactionRef big_ptx = create_placeholder_tx(/*num_inputs=*/150'000, /*num_outputs=*/150'000);
const int64_t tx_weight = GetTransactionWeight(*big_ptx);
@l0rinc

l0rinc commented Jun 6, 2026

Copy link
Copy Markdown
Contributor

Since when do we have copilot auto-review?

image

@pinheadmz

Copy link
Copy Markdown
Member

@digin1 are you able to explain this code change in your own words? How you reviewed the LLM output? How you discovered the issue in the first place? How this would affect normal users?

We require PR authors to provide the first "human pass" before consuming our very limited resources. Otherwise we'll have to close this PR

@digin1

digin1 commented Jun 6, 2026

Copy link
Copy Markdown
Author

Full transparency, since you asked directly:

This came out of an unattended, automated investigation of the repo — an LLM-driven audit pass I was running to look for a specific class of mistake (integer-width / accumulator bugs). It flagged this line and I'm passing it along rather than sitting on it. I want to be upfront that it was machine-found, not a human-first review, so please weigh it accordingly.

The finding itself is straightforward and checks out:

  • IsWellFormedPackage() sums each tx's weight with std::accumulate(txns.cbegin(), txns.cend(), 0, ...). accumulate's accumulator takes the type of the seed, and 0 is an int — so the running total is narrowed back to 32 bits every iteration even though the lambda returns int64_t. A package whose combined weight crosses INT_MAX wraps small/negative and slips past the > MAX_PACKAGE_WEIGHT check. Seeding with int64_t{0} keeps it 64-bit.
  • Impact looks low: not consensus, and over-weight txs are still rejected individually afterward, so nothing improper reaches the mempool — the only effect is the package-level early rejection failing to fire (reachable via submitpackage). Robustness, not security.
  • As far as I can tell it has never been reported: the int seed has been on master since Fix virtual size limit enforcement in transaction package context #28471 (Sept 2023, when this check moved from vsize to weight) and survived the later refactors of this function — probably why it went unnoticed, since the lambda's int64_t sum makes the accumulator look 64-bit at a glance.

No attachment to the PR — flagging it in case it's useful, and I'm completely fine closing it given it's machine-found and low-impact. If it's worth fixing, the one-liner stands on its own and you can take it from there however you prefer.

@sedited

sedited commented Jun 6, 2026

Copy link
Copy Markdown
Contributor

Closing this. I don't think the regression test makes sense at all the way it is right now, and I don't think it will be fun to prompt the author's llm to get it into better shape. If somebody wants to pick up this one line improvement, that seems fine as a tiny defense in depth change.

@sedited sedited closed this Jun 6, 2026
@digin1
digin1 deleted the policy-package-weight-64bit branch June 6, 2026 16:44
@maflcko

maflcko commented Jun 9, 2026

Copy link
Copy Markdown
Member

Yeah, seems fine to fix. For reference, this C++ bug/pitfall was fixed in C++23 with fold_left:

https://godbolt.org/z/9q7YvjPv9

l0rinc added a commit to l0rinc/bitcoin that referenced this pull request Aug 2, 2026
std::accumulate takes its accumulator type from the initial value, so the literal 0 narrows each intermediate sum to int even though the lambda returns int64_t.

A package heavy enough to wrap can therefore skip the package-too-large rejection and reach later package checks.

bitcoin#35473 proposed the same one-line fix and was closed over its regression test, so keep this change paired with a focused sanitization case.
l0rinc added a commit to l0rinc/bitcoin that referenced this pull request Aug 6, 2026
std::accumulate takes its accumulator type from the initial value, so the literal 0 narrows each intermediate sum to int even though the lambda returns int64_t.

A package heavy enough to wrap can therefore skip the package-too-large rejection and reach later package checks.

bitcoin#35473 proposed the same one-line fix and was closed over its regression test, so keep this change paired with a focused sanitization case.
fanquake added a commit that referenced this pull request Oct 16, 2026
faaabe4 policy: sum package weight in int64_t (Ferdinando Ametrano)

Pull request description:

  `IsWellFormedPackage` sums the package weight with `std::accumulate` starting from a plain `0`, so the running total is an `int`. A package heavier than `INT_MAX` would wrap and could pass the `MAX_PACKAGE_WEIGHT` check. No package that large reaches this check today, since RPC request bodies are capped at 32 MiB and P2P messages at 4 MB, so this is defense in depth. It picks up the one-line fix from #35473, which was closed with an invitation to do so.

  I start the sum from `int64_t{0}`, as the vsize sum in `validation.cpp` already does. I did not add a test, since the one on #35473 was turned down. I checked the fix locally with a throwaway test that puts one transaction of 88M weight into a package 25 times: before the fix the package is rejected as `package-contains-duplicates`, after it as `package-too-large`.

ACKs for top commit:
  maflcko:
    lgtm ACK faaabe4
  instagibbs:
    ACK faaabe4

Tree-SHA512: 0a975de2dab72917276eb90633f938847c49c9946212c68b4e513b671d5bdbb2fba1a0358633ee309b1830dae6da353a53df1f6019d6ccc9a371d4997d840ec4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants