Skip to content

compressor: reject oversized scripts during deserialization - #36386

Open
l0rinc wants to merge 2 commits into
bitcoin:masterfrom
l0rinc:l0rinc/script-compression-replace-oversized
Open

l0rinc wants to merge 2 commits into
bitcoin:masterfrom
l0rinc:l0rinc/script-compression-replace-oversized

Conversation

@l0rinc

@l0rinc l0rinc commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Problem: UTXO insertion excludes scripts larger than MAX_SCRIPT_SIZE as unspendable, so an oversized compressed script indicates corrupt data. Deserialization currently uses an OP_RETURN fallback and skips the oversized payload, hiding the corruption.

Fix: Throw std::ios_base::failure as soon as the decoded script length exceeds MAX_SCRIPT_SIZE.

Context: #7933 added the fallback to avoid an out-of-memory failure in the then-current per-transaction chainstate format, when coin database deserialization errors were indistinguishable from missing entries. #34931 now sends coin deserialization failures to the fatal database-error path, and #24236 removed upgrade support for that old format.

@DrahtBot

DrahtBot commented Sep 30, 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
Stale ACK jcastros, fametrano, hodlinator, maflcko, optout21

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:

  • #36946 (scripted-diff: [test] Add util/check.h includes for assertions by maflcko)
  • #36280 (validation: throw when a compressed script can't be decompressed by furszy)

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.

@maflcko

maflcko commented Sep 30, 2026

Copy link
Copy Markdown
Member

it could affect malformed stored records decoded into a reused destination.

Not sure, reusing a destination would be an unrelated bug? So I am half suggesting to drop the test in a third commit again, or at least clarify in the comment that this isn't supposed to test any real production behavior.

lgtm either way.

@l0rinc
l0rinc force-pushed the l0rinc/script-compression-replace-oversized branch from 6a30cea to f313faf Compare September 30, 2026 18:10
@l0rinc

l0rinc commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

Not sure, reusing a destination would be an unrelated bug?

We do have some existing reuses, e.g. in

bitcoin/src/rpc/blockchain.cpp

Lines 3435 to 3462 in e7aef7e

Coin coin;
unsigned int iter{0};
size_t written_coins_count{0};
std::vector<std::pair<uint32_t, Coin>> coins;
// To reduce space the serialization format of the snapshot avoids
// duplication of tx hashes. The code takes advantage of the guarantee by
// leveldb that keys are lexicographically sorted.
// In the coins vector we collect all coins that belong to a certain tx hash
// (key.hash) and when we have them all (key.hash != last_hash) we write
// them to file using the below lambda function.
// See also https://github.com/bitcoin/bitcoin/issues/25675
auto write_coins_to_file = [&](AutoFile& afile, const Txid& last_hash, const std::vector<std::pair<uint32_t, Coin>>& coins, size_t& written_coins_count) {
afile << last_hash;
WriteCompactSize(afile, coins.size());
for (const auto& [n, coin] : coins) {
WriteCompactSize(afile, n);
afile << coin;
++written_coins_count;
}
};
pcursor->GetKey(key);
last_hash = key.hash;
while (pcursor->Valid()) {
if (iter % 5000 == 0) interruption_point();
++iter;
if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
the snapshot export reuses the same Coin in the loop. Regardless, added a comment clarifying that this tests the fallback directly, since normal UTXO insertion excludes oversized scripts.

@jcastros

jcastros commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Tested ACK f313faf

I built test_bitcoin (GCC 13.3, RelWithDebInfo) and ran compress_tests on this and on 11494ef. Both are clean. Putting script << OP_RETURN back makes compress_oversized_script fail, so the new check covers the fix.

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

Concept ACK f313faf

Comment thread src/test/compress_tests.cpp Outdated
{
// Test the fallback directly, since normal UTXO insertion excludes oversized scripts
CScript restored{ParseScript("0x01")}; // Incomplete push: appending OP_RETURN would make it pushed data
(DataStream{} << Using<ScriptCompression>(CScript{CScript() << std::vector(MAX_SCRIPT_SIZE + 1, uint8_t{0})})) >> Using<ScriptCompression>(restored);

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.

This has a bit too much happening at once IMO (+ redundant CScript-ctor-call). Would rather have something closer to

Suggested change
(DataStream{} << Using<ScriptCompression>(CScript{CScript() << std::vector(MAX_SCRIPT_SIZE + 1, uint8_t{0})})) >> Using<ScriptCompression>(restored);
DataStream oversized_compressed{DataStream{} << Using<ScriptCompression>(CScript{} << std::vector(MAX_SCRIPT_SIZE + 1, uint8_t{0}))};
oversized_compressed >> Using<ScriptCompression>(restored);

Comment thread src/test/compress_tests.cpp Outdated
Comment on lines +175 to +176
CScript restored{ParseScript("0x01")}; // Incomplete push: appending OP_RETURN would make it pushed data
(DataStream{} << Using<ScriptCompression>(CScript{CScript() << std::vector(MAX_SCRIPT_SIZE + 1, uint8_t{0})})) >> Using<ScriptCompression>(restored);

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.

nit: Could verify that restored starts out spendable before the compression round-trip makes it unspendable?

Suggested change
CScript restored{ParseScript("0x01")}; // Incomplete push: appending OP_RETURN would make it pushed data
(DataStream{} << Using<ScriptCompression>(CScript{CScript() << std::vector(MAX_SCRIPT_SIZE + 1, uint8_t{0})})) >> Using<ScriptCompression>(restored);
CScript restored{ParseScript("0x01")}; // Incomplete push: appending OP_RETURN would make it pushed data
BOOST_CHECK(!restored.IsUnspendable());
(DataStream{} << Using<ScriptCompression>(CScript{CScript() << std::vector(MAX_SCRIPT_SIZE + 1, uint8_t{0})})) >> Using<ScriptCompression>(restored);

Comment thread src/test/compress_tests.cpp Outdated
// Test the fallback directly, since normal UTXO insertion excludes oversized scripts
CScript restored{ParseScript("0x01")}; // Incomplete push: appending OP_RETURN would make it pushed data
(DataStream{} << Using<ScriptCompression>(CScript{CScript() << std::vector(MAX_SCRIPT_SIZE + 1, uint8_t{0})})) >> Using<ScriptCompression>(restored);
BOOST_CHECK(restored.IsUnspendable());

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.

Ralph suggested also pinning down the resulting script (https://git.fish.foo/bitcoin/bitcoin/pulls/36386#issuecomment-608275), which seems fair enough.

Guess it could be done through:

Suggested change
BOOST_CHECK(restored.IsUnspendable());
BOOST_CHECK(restored.IsUnspendable());
const CScript expected{OP_RETURN};
BOOST_CHECK_EQUAL_COLLECTIONS(restored.begin(), restored.end(), expected.begin(), expected.end());

@l0rinc
l0rinc force-pushed the l0rinc/script-compression-replace-oversized branch from f313faf to 426f29c Compare October 15, 2026 13:57
@fametrano

Copy link
Copy Markdown

tACK 426f29c

I decoded 1307 compressed scripts (raw sizes 0 to 39 and from just under MAX_SCRIPT_SIZE to 200000, truncated streams, every special type) into a fresh target and five reused ones, a P2PKH among them, and compared each result with what a library I maintain decodes from the same bytes. On the base, every complete oversized script decoded into a reused target keeps the old bytes and appends OP_RETURN (35 decodes). On this head every raw and oversized case matches for every target.

One path still depends on the target: an uncompressed P2PK (type 4 or 5) whose x is not on the curve leaves a reused target untouched, so a P2PKH stays a P2PKH. #36280 makes that path throw. Its compressor.h change merges cleanly with this one; only compress_tests.cpp conflicts. With both applied, no decode in the set depends on what the target held before. I can share the vectors and the test.

@DrahtBot
DrahtBot requested a review from hodlinator October 25, 2026 11:19

@hodlinator hodlinator 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 426f29c

Comment thread src/test/compress_tests.cpp Outdated
BOOST_AUTO_TEST_CASE(compress_oversized_script)
{
// Test the fallback directly, since normal UTXO insertion excludes oversized scripts
CScript restored{ParseScript("0x01")}; // Incomplete push: appending OP_RETURN would make it pushed data

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.

nit: Could compute at compile time:

--- a/src/test/compress_tests.cpp
+++ b/src/test/compress_tests.cpp
@@ -28,6 +28,8 @@
 // amounts 50 .. 21000000
 #define NUM_MULTIPLES_50BTC 420000

+using namespace util::hex_literals;
+
 BOOST_FIXTURE_TEST_SUITE(compress_tests, BasicTestingSetup)

 bool static TestEncode(uint64_t in) {
@@ -172,7 +174,7 @@ BOOST_AUTO_TEST_CASE(compress_p2pk_scripts_not_on_curve)
 BOOST_AUTO_TEST_CASE(compress_oversized_script)
 {
     // Test the fallback directly, since normal UTXO insertion excludes oversized scripts
-    CScript restored{ParseScript("0x01")}; // Incomplete push: appending OP_RETURN would make it pushed data
+    auto restored{CScript{} << "01"_hex}; // Incomplete push: appending OP_RETURN would make it pushed data
     BOOST_CHECK(!restored.IsUnspendable());
     DataStream oversized_compressed{DataStream{} << Using<ScriptCompression>(CScript{} << std::vector(MAX_SCRIPT_SIZE + 1, uint8_t{0}))};
     oversized_compressed >> Using<ScriptCompression>(restored);

@maflcko

maflcko commented Oct 27, 2026

Copy link
Copy Markdown
Member

review ACK 426f29c 🏉

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 426f29c3f1639e4c97be63cdf4c2e76bb86b39dd 🏉
ZMFrq8y3VWJkvdmEHZqxUEXnr07PVirQi5JeVZZ0cI9PWixMNhtsYF/RYb7eALrDfdaoDa4OPwLQP3GmubegDg==

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

Reviewed, left some comments. Happy to re-check/ack once answered.
(426f29c)

Comment thread src/compressor.h Resolved
Comment thread src/compressor.h Outdated
if (nSize > MAX_SCRIPT_SIZE) {
// Overly long script, replace with a short invalid one
script << OP_RETURN;
script = CScript{OP_RETURN};

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.

426f29c compressor: replace oversized scripts instead of appending:

Would it be possible to clear the script output variable at the beginning of this method? That would ensure the claim (independence of previous value).

@optout21

Copy link
Copy Markdown
Contributor

ACK 426f29c
Upgraded my previous review result, upon reconsideration. This change is a net improvement, independent of #36280 . I'd appreciate answers to my comments, nonetheless.

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

Not sure why this should be changed from the motivation provided here. If I understand this correctly, the only way to encounter an oversized script outside of loadtxoutset is corruption. Why not just throw in that case? Deserializing potentially corrupt entries as unspendable seems confusing to me in the first place.

@maflcko

maflcko commented Nov 4, 2026

Copy link
Copy Markdown
Member

If I understand this correctly, the only way to encounter an oversized script outside of loadtxoutset is corruption.

Even if this happens inside loadtxoutset, such a utxo-file is still only possible after corruption. While reviewing this I thought that this was needed to gracefully upgrade ancient utxo dbs, and looking at the diff of #7933, it seems that was accurate?

However, according to git blame ./test/functional/feature_unsupported_utxo_db.py those dbs are now invalid anyway, so throwing seems more consistent with other deser errors.

Record that decompression accepts scripts larger than MAX_SCRIPT_SIZE. Valid UTXO records cannot contain these scripts.
Valid UTXO records exclude oversized scripts because they are unspendable. Reject the corrupt record with a deserialization error instead of replacing it with the `OP_RETURN` fallback.
@l0rinc
l0rinc force-pushed the l0rinc/script-compression-replace-oversized branch from 426f29c to 777ede5 Compare December 2, 2026 12:09
@l0rinc l0rinc changed the title compressor: oversized script decoding can leave a spendable script compressor: reject oversized scripts during deserialization Dec 2, 2026
@l0rinc

l0rinc commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

this was needed to gracefully upgrade ancient utxo dbs

I really hated that ugly, hacky OP_RETURN fallback too. It seems to have been introduced as an OOM mitigation because CDBWrapper::Read() couldn't distinguish a missing entry from a deserialization failure, so throwing would have made the whole transaction's UTXO record look missing. The same decoder also remained part of the old per-transaction chainstate upgrade path, but #24236 removed that path and requires reindexing instead. Now that #34931 fixed the error handling for coin reads, we can indeed throw here, which is so much better in every sense. I've updated the PR accordingly. Thanks for the pushback!

@DrahtBot

DrahtBot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task Windows, test cross-built: https://github.com/bitcoin/bitcoin/actions/runs/46878258029/job/143457183354
LLM reason (✨ experimental): functional_test_fail: feature_unsupported_utxo_db.py failed while starting the node because parsing its RPC auth cookie raised IndexError (split_userpass[1] was missing).

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • Intermittent network issues can occur; re-run CI for now, and report the issue if they keep happening.

  • A functional or integration test failure may be intermittent or unrelated to this pull request.
    If no dedicated issue thread exists, create a new one to track it.

Leave a comment here, if you need help tracking down a confusing failure.

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.

8 participants