test: Add test for CompactSize larger than MAX_SIZE value #36853

Open
maflcko wants to merge 4 commits from 2611-test-CompactSize-MAX_SIZE into master AGit
maflcko commented 2026-11-13 11:11:20 +00:00 (Migrated from github.com)

Currently there is no test coverage for oversized CompactSize. This is fine, because a vector this large will already be rejected earlier by the P2P transport payload size check.

However, it would be good to still add test coverage:

Currently there is no test coverage for oversized CompactSize. This is fine, because a vector this large will already be rejected earlier by the P2P transport payload size check. However, it would be good to still add test coverage: * Removing the check would pass all tests. * There is some accidental non-deterministic coverage through tx-deser "fuzzing", which hurts coverage reports, see https://github.com/corecheck/corecheck/pull/219#discussion_r4554170963. * Having explicit end-to-end P2P coverage for such corrupt messages seems fine.
DrahtBot commented 2026-11-13 11:11:30 +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 seduless, m3dwards

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:

  • #36918 (Witness stacks in serialized form (optimization follow-ups) by sipa)

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/36853 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36853.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36853#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 | [seduless](https://github.com/bitcoin/bitcoin/pull/36853#pullrequestreview-6029742151), [m3dwards](https://github.com/bitcoin/bitcoin/pull/36853#issuecomment-7114961299) | 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: * [#36918](https://github.com/bitcoin/bitcoin/pull/36918) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36918.svg"></sub> (Witness stacks in serialized form (optimization follow-ups) by sipa) 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-->
maflcko commented 2026-11-13 11:13:25 +00:00 (Migrated from github.com)

Mutation:

diff --git a/src/serialize.h b/src/serialize.h
index 9a1ff56ec4..81d675c3c0 100644
--- a/src/serialize.h
+++ b/src/serialize.h
@@ -358,5 +358,2 @@ uint64_t ReadCompactSize(Stream& is, bool range_check = true)
     }
-    if (range_check && nSizeRet > MAX_SIZE) {
-        throw std::ios_base::failure("ReadCompactSize(): size too large");
-    }
     return nSizeRet;
Mutation: ```diff diff --git a/src/serialize.h b/src/serialize.h index 9a1ff56ec4..81d675c3c0 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -358,5 +358,2 @@ uint64_t ReadCompactSize(Stream& is, bool range_check = true) } - if (range_check && nSizeRet > MAX_SIZE) { - throw std::ios_base::failure("ReadCompactSize(): size too large"); - } return nSizeRet; ``` <!--- +BOOST_AUTO_TEST_CASE(compactsize_type_range) +{ + using Fmt = CompactSizeFormatter</*RangeCheck=*/false>; // Only type check + DataStream ss{}; + ss << Using<Fmt>(uint64_t{std::numeric_limits<uint32_t>::max()} + 1); + uint32_t value; + BOOST_CHECK_EXCEPTION(ss >> Using<Fmt>(value), std::ios_base::failure, HasReason{"CompactSize exceeds limit of type"}); +}
First-time contributor

No verified findings are available from this review.

Review coverage was incomplete.


Reviewed: fa5aabe5a076 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:0bd5eb03661671073172343f1dd2ec27836b36eacef46f7d8f97c54ae4477623:1ed10c4979af6fc548d6b8d4534d505e02e84ac4b0aa4f8633555b2ba75119e8 --> <!-- ralph-base:079437cca7a8e2997a6dcd83ad38350014352544 --> <!-- ralph-head:fa5aabe5a076765fc687080412a214f370d41911 --> <!-- ralph-case:f47df87a2ebc85c000f69fb21788bf5d5a163d0099566faae49e23fe92afb730 --> No verified findings are available from this review. Review coverage was incomplete. <!-- Review tier: routine --> --- Reviewed: [`fa5aabe5a076`](<https://git.fish.foo/bitcoin/bitcoin/commit/fa5aabe5a076765fc687080412a214f370d41911>) · [Review report](<https://review.fish.foo/report/36853-fa5aabe5a076765fc687080412a214f370d41911-2854-3.html>) · [Previous reports](<https://review.fish.foo/traces/36853/>) [permalink](<https://review.fish.foo/report/36853-fa5aabe5a076765fc687080412a214f370d41911-2854-3.html>)
m3dwards commented 2026-11-13 14:30:10 +00:00 (Migrated from github.com)

Quite nuanced to track down! Fixing this will help with coverage determinism.

Concept ACK

Quite nuanced to track down! Fixing this will help with coverage determinism. Concept ACK
m3dwards commented 2026-11-16 17:39:23 +00:00 (Migrated from github.com)

If this is useful to anyone, here a script that reproduces the non-determinism in coverage. With this PR applied it is fixed.

Script
#!/usr/bin/env bash
# Coverage check for the src/serialize.h "ReadCompactSize(): size too large" guard.
# Builds with LLVM coverage, then runs the unit suite's serialisation cases and one
# functional test per run, and reports the guard's execution count for each run.
# Run from the bitcoin checkout root. Needs clang, cmake, python3, llvm-profdata and
# llvm-cov on PATH. Usage: ./guard-flip.sh [runs]      (default 8)
set -eu
cd "$(dirname "$0")"
RUNS=${1:-8}

echo 'Building bitcoin with coverage'

cmake -B build -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ \
  -DAPPEND_CFLAGS="-fprofile-instr-generate -fcoverage-mapping" \
  -DAPPEND_CXXFLAGS="-fprofile-instr-generate -fcoverage-mapping" \
  -DAPPEND_LDFLAGS="-fprofile-instr-generate" \
  -DBUILD_GUI=OFF -DBUILD_BENCH=OFF -DBUILD_FUZZ_BINARY=OFF >/dev/null
cmake --build build -j"$(nproc)" --target bitcoind bitcoin-cli test_bitcoin >/dev/null

L=$(grep -n 'ReadCompactSize(): size too large' src/serialize.h | cut -d: -f1)
echo "guard line: src/serialize.h:$L"
counts=()
for i in $(seq "$RUNS"); do
  d=$(mktemp -d)
  LLVM_PROFILE_FILE=$d/u_%m_%p.profraw ./build/bin/test_bitcoin --run_test=serialize_tests >/dev/null 2>&1 || true
  LLVM_PROFILE_FILE=$d/f_%m_%p.profraw TMPDIR=/tmp \
    python3 build/test/functional/test_runner.py wallet_create_tx.py --randomseed=1234 >/dev/null 2>&1 || true
  llvm-profdata merge -o "$d/p.profdata" "$d"/*.profraw 2>/dev/null
  llvm-cov export --format=lcov --object=build/bin/bitcoind --object=build/bin/test_bitcoin \
    --instr-profile="$d/p.profdata" > "$d/info" 2>"$d/err" || true
  c=$(awk -F'[:,]' -v l="$L" '/^SF:.*serialize\.h$/ {s=1} s && $1=="DA" && $2==l {print $3; exit}' "$d/info")
  [ -n "$c" ] || { echo "run $i: no DA record for line $L, see $d/err" >&2; exit 2; }
  counts+=("$c")
  echo "run $i: $c"
  rm -rf "$d"
done
echo "counts: ${counts[*]}"
if printf '%s\n' "${counts[@]}" | grep -qx 0; then
  echo "FLIPS: the guard was left uncovered on at least one run"
else
  echo "NO FLIPS: the guard was covered on every run"
fi

If this is useful to anyone, here a script that reproduces the non-determinism in coverage. With this PR applied it is fixed. <details> <summary>Script</summary> ```shell #!/usr/bin/env bash # Coverage check for the src/serialize.h "ReadCompactSize(): size too large" guard. # Builds with LLVM coverage, then runs the unit suite's serialisation cases and one # functional test per run, and reports the guard's execution count for each run. # Run from the bitcoin checkout root. Needs clang, cmake, python3, llvm-profdata and # llvm-cov on PATH. Usage: ./guard-flip.sh [runs] (default 8) set -eu cd "$(dirname "$0")" RUNS=${1:-8} echo 'Building bitcoin with coverage' cmake -B build -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ \ -DAPPEND_CFLAGS="-fprofile-instr-generate -fcoverage-mapping" \ -DAPPEND_CXXFLAGS="-fprofile-instr-generate -fcoverage-mapping" \ -DAPPEND_LDFLAGS="-fprofile-instr-generate" \ -DBUILD_GUI=OFF -DBUILD_BENCH=OFF -DBUILD_FUZZ_BINARY=OFF >/dev/null cmake --build build -j"$(nproc)" --target bitcoind bitcoin-cli test_bitcoin >/dev/null L=$(grep -n 'ReadCompactSize(): size too large' src/serialize.h | cut -d: -f1) echo "guard line: src/serialize.h:$L" counts=() for i in $(seq "$RUNS"); do d=$(mktemp -d) LLVM_PROFILE_FILE=$d/u_%m_%p.profraw ./build/bin/test_bitcoin --run_test=serialize_tests >/dev/null 2>&1 || true LLVM_PROFILE_FILE=$d/f_%m_%p.profraw TMPDIR=/tmp \ python3 build/test/functional/test_runner.py wallet_create_tx.py --randomseed=1234 >/dev/null 2>&1 || true llvm-profdata merge -o "$d/p.profdata" "$d"/*.profraw 2>/dev/null llvm-cov export --format=lcov --object=build/bin/bitcoind --object=build/bin/test_bitcoin \ --instr-profile="$d/p.profdata" > "$d/info" 2>"$d/err" || true c=$(awk -F'[:,]' -v l="$L" '/^SF:.*serialize\.h$/ {s=1} s && $1=="DA" && $2==l {print $3; exit}' "$d/info") [ -n "$c" ] || { echo "run $i: no DA record for line $L, see $d/err" >&2; exit 2; } counts+=("$c") echo "run $i: $c" rm -rf "$d" done echo "counts: ${counts[*]}" if printf '%s\n' "${counts[@]}" | grep -qx 0; then echo "FLIPS: the guard was left uncovered on at least one run" else echo "NO FLIPS: the guard was covered on every run" fi ``` </details>
maflcko commented 2026-11-17 09:32:49 +00:00 (Migrated from github.com)

If this is useful to anyone, here a script that reproduces the non-determinism in coverage.

An alternative would be to just replace the code with assert(false) and then run the functional tests. Sometimes they pass, sometimes they fail.

> If this is useful to anyone, here a script that reproduces the non-determinism in coverage. An alternative would be to just replace the code with `assert(false)` and then run the functional tests. Sometimes they pass, sometimes they fail.
m3dwards (Migrated from github.com) reviewed 2026-11-18 17:42:57 +00:00
m3dwards (Migrated from github.com) commented 2026-11-18 17:07:49 +00:00

There's another one in the compactsize test. Should that be dropped too?

Perhaps:

BOOST_AUTO_TEST_CASE(compactsize)
{
    DataStream ss{};
    for (uint64_t i = 1; i <= MAX_SIZE; i *= 2) {
        WriteCompactSize(ss, i - 1);
        WriteCompactSize(ss, i);
    }
    for (uint64_t i = 1; i <= MAX_SIZE; i *= 2) {
        BOOST_CHECK_EQUAL(ReadCompactSize(ss), i - 1);
        BOOST_CHECK_EQUAL(ReadCompactSize(ss), i);
    }
}
There's another one in the compactsize test. Should that be dropped too? Perhaps: ```cpp BOOST_AUTO_TEST_CASE(compactsize) { DataStream ss{}; for (uint64_t i = 1; i <= MAX_SIZE; i *= 2) { WriteCompactSize(ss, i - 1); WriteCompactSize(ss, i); } for (uint64_t i = 1; i <= MAX_SIZE; i *= 2) { BOOST_CHECK_EQUAL(ReadCompactSize(ss), i - 1); BOOST_CHECK_EQUAL(ReadCompactSize(ss), i); } } ```
m3dwards (Migrated from github.com) commented 2026-11-17 15:43:39 +00:00

Is there a reason you opted for a generic lambda here and not a parameter called RangeCheck? More for my understanding than a nit.

Is there a reason you opted for a generic lambda here and not a parameter called RangeCheck? More for my understanding than a nit.
m3dwards (Migrated from github.com) commented 2026-11-18 16:58:12 +00:00

This just checks 5 byte values and I did consider if we should also check 9 byte values but I don't think it really adds anything.

This just checks 5 byte values and I did consider if we should also check 9 byte values but I don't think it really adds anything.
m3dwards (Migrated from github.com) commented 2026-11-18 17:42:33 +00:00

In this situation it looks like the node will log the error but won't do any Misbehaving behaviour or anything. Do we think this is correct? It's just a malformed message I guess and not necessarily a large message.

In this situation it looks like the node will log the error but won't do any `Misbehaving` behaviour or anything. Do we think this is correct? It's just a malformed message I guess and not necessarily a large message.
maflcko (Migrated from github.com) reviewed 2026-11-19 14:12:38 +00:00
maflcko (Migrated from github.com) commented 2026-11-19 14:12:38 +00:00

It is impossible to enumerate all cases of "misbehavior" and it can also be net-split risky to mark something as misbehavior when ancient (pre-bip) protocol may have allowed it.

The p2p protocol message size limit was added in ba04c4a780 without a bip, so making MAX_SIZE+1 compactsize a misbehavior may be controversial and difficult to review.

In any case, this is a test-only pull, so I am not allowed to change misbehavior here. Also, to give more examples, https://github.com/bitcoin/bitcoin/pull/36906 goes the opposite way and changes a bad-txns-oversize from misbehavior to an ignored deser error.

To also give an example where a new misbehavior is added based on a bip text: https://github.com/bitcoin/bitcoin/pull/35550

It is impossible to enumerate all cases of "misbehavior" and it can also be net-split risky to mark something as misbehavior when ancient (pre-bip) protocol may have allowed it. The p2p protocol message size limit was added in ba04c4a7801e7d68a5e84035b919e5c3626eb7a7 without a bip, so making MAX_SIZE+1 compactsize a misbehavior may be controversial and difficult to review. In any case, this is a test-only pull, so I am not allowed to change misbehavior here. Also, to give more examples, https://github.com/bitcoin/bitcoin/pull/36906 goes the opposite way and changes a bad-txns-oversize from misbehavior to an ignored deser error. To also give an example where a new misbehavior is added based on a bip text: https://github.com/bitcoin/bitcoin/pull/35550
maflcko (Migrated from github.com) reviewed 2026-11-19 14:12:45 +00:00
maflcko (Migrated from github.com) commented 2026-11-19 14:12:45 +00:00

Edit: Looks like https://github.com/bitcoin/bitcoin/pull/36906#discussion_r4629650852 may take care of it:

I'll investigate (separate from this PR) whether we can just blanket disconnect any peers that gives us undeserializable messages.

Edit: Looks like https://github.com/bitcoin/bitcoin/pull/36906#discussion_r4629650852 may take care of it: > 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 14:12:58 +00:00
maflcko (Migrated from github.com) commented 2026-11-19 14:12:58 +00:00

right, this should be sufficient

right, this should be sufficient
maflcko commented 2026-11-19 14:14:20 +00:00 (Migrated from github.com)

thx, took all nits

thx, took all nits
m3dwards (Migrated from github.com) reviewed 2026-11-19 17:05:04 +00:00
m3dwards (Migrated from github.com) commented 2026-11-19 17:05:04 +00:00

Only if there is a further change to this PR I wonder if there should be a comment to reference where this is from (src/serialize.h)?

Only if there is a further change to this PR I wonder if there should be a comment to reference where this is from (`src/serialize.h`)?
m3dwards commented 2026-11-19 17:11:47 +00:00 (Migrated from github.com)
ACK fa01715b969985feb0f9a0de495f5e73b93c0b34
seduless (Migrated from github.com) reviewed 2026-11-23 21:22:59 +00:00
seduless (Migrated from github.com) left a comment

Tested ACK fa5aabe5a0

  • Verified vs the PR's base no unit or functional test catches the mutation to delete the guard
  • Verified the new unit (compactsize_value_range) and functional (test_corrupt_compactsize) tests fail when applying the same mutation
Tested ACK fa5aabe5a076765fc687080412a214f370d41911 - Verified vs the PR's base no unit or functional test catches the [mutation](https://github.com/bitcoin/bitcoin/pull/36853#issuecomment-6851170313) to delete the guard - Verified the new unit (`compactsize_value_range`) and functional (`test_corrupt_compactsize`) tests fail when applying the same mutation
seduless (Migrated from github.com) reviewed 2026-11-23 21:25:35 +00:00
seduless (Migrated from github.com) commented 2026-11-23 21:25:35 +00:00

The latest force push (fa0899b364) includes the 9-byte check. Just to clarify since the 5-byte case was considered sufficient, did you add it because we don't have any tested 9-byte round-trip in the suite without this?

The latest force push (fa0899b36411f20c2c659a5066014cd5cb1f2d94) includes the 9-byte check. Just to clarify since the 5-byte case was considered sufficient, did you add it because we don't have any tested 9-byte round-trip in the suite without this?
m3dwards commented 2026-11-23 21:49:16 +00:00 (Migrated from github.com)

reACK fa5aabe5a0

reACK fa5aabe5a076765fc687080412a214f370d41911
maflcko (Migrated from github.com) reviewed 2026-11-24 06:56:25 +00:00
maflcko (Migrated from github.com) commented 2026-11-24 06:56:25 +00:00

Yes, I think there was no round-trip test: I added it for the /*range_check=*/false coverage. The size too large coverage was "free", so I guess it can't hurt 😅

Yes, I think there was no round-trip test: I added it for the `/*range_check=*/false` coverage. The `size too large` coverage was "free", so I guess it can't hurt :sweat_smile:
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!36853
No description provided.