validation: throw when a compressed script can't be decompressed #36280

Open
furszy wants to merge 2 commits from 2026_compression_throw into master AGit
furszy commented 2026-09-16 20:49:24 +00:00 (Migrated from github.com)

ScriptCompression::Unser ignores the DecompressScript return value and
leaves the script empty on failure, without notifying upper layers about the error.
In the worst-case scenario, which is currently only reachable through corruption,
an unspendable off-curve P2PK turns into an anyone-can-spend empty script.
Given that, properly throwing the error to prevent any future mistakes from
happening seems the sanest path to follow.

Aside from that, added coverage for a P2PK script with an uncompressed pubkey
that has a valid X but a wrong Y, which makes it unspendable. Checking we store
such scripts raw and never encode them as 0x04/0x05, as those encodings
serialize X with only Y's parity (not the full Y), which would make decompression
recompute Y from X and turn the unspendable script into a spendable one, which
would not be good.

`ScriptCompression::Unser` ignores the `DecompressScript` return value and leaves the script empty on failure, without notifying upper layers about the error. In the worst-case scenario, which is currently only reachable through corruption, an unspendable off-curve P2PK turns into an anyone-can-spend empty script. Given that, properly throwing the error to prevent any future mistakes from happening seems the sanest path to follow. Aside from that, added coverage for a P2PK script with an uncompressed pubkey that has a valid X but a wrong Y, which makes it unspendable. Checking we store such scripts raw and never encode them as 0x04/0x05, as those encodings serialize X with only Y's parity (not the full Y), which would make decompression recompute Y from X and turn the unspendable script into a spendable one, which would not be good.
DrahtBot commented 2026-09-16 20:49:32 +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 fametrano
Concept ACK fjahr, purpleKarrot, l0rinc
Approach ACK sedited

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)
  • #36386 (compressor: reject oversized scripts during deserialization by l0rinc)

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/36280 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36280.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36280#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 | [fametrano](https://github.com/bitcoin/bitcoin/pull/36280#issuecomment-6394507698) | | Concept ACK | [fjahr](https://github.com/bitcoin/bitcoin/pull/36280#pullrequestreview-5327457839), [purpleKarrot](https://github.com/bitcoin/bitcoin/pull/36280#issuecomment-5868071002), [l0rinc](https://github.com/bitcoin/bitcoin/pull/36280#pullrequestreview-5347579796) | | Approach ACK | [sedited](https://github.com/bitcoin/bitcoin/pull/36280#issuecomment-5705072137) | 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: * [#36946](https://github.com/bitcoin/bitcoin/pull/36946) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36946.svg"></sub> (scripted-diff: [test] Add util/check.h includes for assertions by maflcko) * [#36386](https://github.com/bitcoin/bitcoin/pull/36386) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36386.svg"></sub> (compressor: reject oversized scripts during deserialization by l0rinc) 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-->
sedited commented 2026-09-16 21:49:40 +00:00 (Migrated from github.com)

Approach ACK

Approach ACK
fjahr (Migrated from github.com) reviewed 2026-09-26 21:29:33 +00:00
fjahr (Migrated from github.com) left a comment

Concept ACK

Looks already pretty solid but I left a few, mostly minor comments.

Concept ACK Looks already pretty solid but I left a few, mostly minor comments.
fjahr (Migrated from github.com) commented 2026-09-26 21:14:41 +00:00

nit: sorting

nit: sorting
fjahr (Migrated from github.com) commented 2026-09-26 21:28:15 +00:00

Do we really need to check this 1000 times? If we do, then maybe this should rather be a fuzz test? For a unit test doing this once should suffice I think.

Do we really need to check this 1000 times? If we do, then maybe this should rather be a fuzz test? For a unit test doing this once should suffice I think.
fjahr (Migrated from github.com) commented 2026-09-26 21:23:05 +00:00

nit: maybe use BOOST_REQUIRE instead of assert?

nit: maybe use `BOOST_REQUIRE` instead of `assert`?
fjahr (Migrated from github.com) commented 2026-09-26 21:13:55 +00:00

I guess this coverage wasn't that interesting but this is dropping the call of DecompressScript with different nSize.

I guess this coverage wasn't that interesting but this is dropping the call of `DecompressScript` with different `nSize`.
fjahr (Migrated from github.com) commented 2026-09-26 21:11:04 +00:00

Would you mind covering each type here already? It doesn't seem to be that complex and otherwise the test is weaker than it needs to be.

Would you mind covering each type here already? It doesn't seem to be that complex and otherwise the test is weaker than it needs to be.
furszy (Migrated from github.com) reviewed 2026-09-27 23:50:15 +00:00
furszy (Migrated from github.com) commented 2026-09-27 23:50:15 +00:00

nSize is type (the compression format) and is still provided by the fuzzer and tested against the code. Diff is that we are providing it inside the data stream we feed to ScriptCompression instead of a direct func arg.

Happy to know if you are seeing something else.

`nSize` is `type` (the compression format) and is still provided by the fuzzer and tested against the code. Diff is that we are providing it inside the data stream we feed to `ScriptCompression` instead of a direct func arg. Happy to know if you are seeing something else.
fjahr (Migrated from github.com) reviewed 2026-09-28 07:51:39 +00:00
fjahr (Migrated from github.com) commented 2026-09-28 07:51:39 +00:00

Sorry, my comment wasn't that clear, what has changed is that the fuzzer doesn't cover DecompressScript with nSize >5 anymore, but as I said, not that important coverage I guess.

Sorry, my comment wasn't that clear, what has changed is that the fuzzer doesn't cover `DecompressScript` with `nSize` >5 anymore, but as I said, not that important coverage I guess.
First-time contributor

Base: a773e1e33b349dc819b5a0edc1c7a4839dc73b48
Head: 5500521f8bd93a42388bf8ef3c48d7c4c0ab75c6

Findings

Minor

Abort rollback snapshot copying when a coin read fails (src/compressor.h:85, head)

During rollback snapshot creation, an undecodable compressed script makes GetValue return false. The copy loop skips that coin and continues, then computes statistics and writes a snapshot from the incomplete temporary database without reporting the failed read. Abort the copy and report the read failure. No current production source of an undecodable compressed coin record was identified, so production impact remains unconfirmed and is limited to the corruption case described in the PR.

Review coverage was incomplete.

Review limitations
  • design: The full kernel/coinstats.cpp caller around its GetValue check (reported at line 129) was not inspected. It could contain later error handling that determines whether a failed row causes partial statistics to be returned.

Full review report

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:1e40d4c29146a38cb238a037edaa35c22b13996a5383ed7a85e089a15d569009:c9412d948811529792d161d97aa6951829440e3d548b7c576bb8d4df4183e0d0 --> Base: `a773e1e33b349dc819b5a0edc1c7a4839dc73b48` Head: `5500521f8bd93a42388bf8ef3c48d7c4c0ab75c6` ##### Findings **Minor** **Abort rollback snapshot copying when a coin read fails** (src/compressor.h:85, head) During rollback snapshot creation, an undecodable compressed script makes `GetValue` return false. The copy loop skips that coin and continues, then computes statistics and writes a snapshot from the incomplete temporary database without reporting the failed read. Abort the copy and report the read failure. No current production source of an undecodable compressed coin record was identified, so production impact remains unconfirmed and is limited to the corruption case described in the PR. Review coverage was incomplete. <details> <summary>Review limitations</summary> - design: The full kernel/coinstats.cpp caller around its GetValue check (reported at line 129) was not inspected. It could contain later error handling that determines whether a failed row causes partial statistics to be returned. </details> [Full review report](<https://review.fish.foo/traces/36280-5500521f8bd93a42388bf8ef3c48d7c4c0ab75c6-1316-3.html>)
purpleKarrot commented 2026-09-28 10:24:38 +00:00 (Migrated from github.com)

In the worst-case scenario, which is currently only reachable through corruption,

This does not sound like a valid use case for recoverable error handling to me. If this is a clear indication of corruption, it should be treated as such.

Edit: I see that all decoding errors are reported through exceptions, which is not great. But it means that the error handling in this PR is aligned. Hence, ACK.

> In the worst-case scenario, which is currently only reachable through corruption, This does not sound like a valid use case for recoverable error handling to me. If this is a clear indication of corruption, it should be treated as such. *Edit*: I see that all decoding errors are reported through exceptions, which is not great. But it means that the error handling in this PR is aligned. Hence, ACK.
furszy (Migrated from github.com) reviewed 2026-09-28 15:29:38 +00:00
furszy (Migrated from github.com) commented 2026-09-28 15:29:38 +00:00

ah, last one checked against is 6 (nSpecialScripts), which check the raw script storage path (any number over 5 takes the same path). This was on purpose because once we go over the last encoding format, we start consuming bytes from the script, which could make nSize to underflow and end up with a huge allocation. <-- not true, I need caffeine.

ah, last one checked against is 6 (`nSpecialScripts`), which check the raw script storage path (any number over 5 takes the same path). ~~This was on purpose because once we go over the last encoding format, we start consuming bytes from the script, which could make `nSize` to underflow and end up with a huge allocation.~~ <-- not true, I need caffeine.
l0rinc (Migrated from github.com) requested changes 2026-09-29 22:02:52 +00:00
l0rinc (Migrated from github.com) left a comment

Concept ACK, we have lots of similar findings that we should slowly plug, this seems like a good next step.

Could we also check how callers handle the new exception, especially where an unreadable coin could be silently skipped? Left a few suggestions for diagnostics and coverage too.

I’ll follow up separately on the OP_RETURN fallback potentially leaving a spendable script.

Concept ACK, we have lots of similar findings that we should slowly plug, this seems like a good next step. Could we also check how callers handle the new exception, especially where an unreadable coin could be silently skipped? Left a few suggestions for diagnostics and coverage too. I’ll follow up separately on the `OP_RETURN` fallback potentially leaving a spendable script.
l0rinc (Migrated from github.com) commented 2026-09-29 04:45:03 +00:00

For diagnostics we could include the compression class and a hex dump of the payload as well.

Include the compression class and payload in decode errors
diff --git a/src/compressor.h b/src/compressor.h
index d252c0b712..acd25aa2e8 100644
--- a/src/compressor.h
+++ b/src/compressor.h
@@ -6,11 +6,13 @@
 #ifndef BITCOIN_COMPRESSOR_H
 #define BITCOIN_COMPRESSOR_H
 
+#include <crypto/hex_base.h>
 #include <prevector.h>
 #include <primitives/transaction.h>
 #include <script/script.h>
 #include <serialize.h>
 #include <span.h>
+#include <tinyformat.h>
 
 #include <ios>
 
@@ -83,7 +85,7 @@ struct ScriptCompression
             CompressedScript vch(GetSpecialScriptSize(nSize), 0x00);
             s >> std::span{vch};
             if (!DecompressScript(script, nSize, vch)) {
-                throw std::ios_base::failure("Non-decodable compressed script");
+                throw std::ios_base::failure(strprintf("Non-decodable compressed script (type %u, data %s)", nSize, HexStr(vch)));
             }
             return;
         }

For diagnostics we could include the compression class and a hex dump of the payload as well. <details> <summary>Include the compression class and payload in decode errors</summary> ```diff diff --git a/src/compressor.h b/src/compressor.h index d252c0b712..acd25aa2e8 100644 --- a/src/compressor.h +++ b/src/compressor.h @@ -6,11 +6,13 @@ #ifndef BITCOIN_COMPRESSOR_H #define BITCOIN_COMPRESSOR_H +#include <crypto/hex_base.h> #include <prevector.h> #include <primitives/transaction.h> #include <script/script.h> #include <serialize.h> #include <span.h> +#include <tinyformat.h> #include <ios> @@ -83,7 +85,7 @@ struct ScriptCompression CompressedScript vch(GetSpecialScriptSize(nSize), 0x00); s >> std::span{vch}; if (!DecompressScript(script, nSize, vch)) { - throw std::ios_base::failure("Non-decodable compressed script"); + throw std::ios_base::failure(strprintf("Non-decodable compressed script (type %u, data %s)", nSize, HexStr(vch))); } return; } ``` </details>
l0rinc (Migrated from github.com) commented 2026-09-29 21:21:08 +00:00

When dumptxoutset creates a rollback snapshot, the copy loop skips coins on read failure. The cursor catches the new decompression exception and returns false, so this PR
adds another trigger for that issue. Could we abort the copy on a failed read, either here or in a separate follow-up? Otherwise, dumptxoutset can succeed with a coin missing.

scantxoutset uses the same cursor reader, but a failed read currently looks like cancellation (success: false with partial results). Could we return the UTXO read error there as well?
The existing corruption test can cover both RPCs before triggering the validation abort.

Report unreadable coins in rollback exports and UTXO scans
diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp
index ae75072462..27223dda57 100644
--- a/src/rpc/blockchain.cpp
+++ b/src/rpc/blockchain.cpp
@@ -2258,7 +2258,7 @@ bool FindScriptPubKey(std::atomic<int>& scan_progress, const std::atomic<bool>&
     while (cursor->Valid()) {
         COutPoint key;
         Coin coin;
-        if (!cursor->GetKey(key) || !cursor->GetValue(coin)) return false;
+        if (!cursor->GetKey(key) || !cursor->GetValue(coin)) throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
         if (++count % 8192 == 0) {
             interruption_point();
             if (should_abort) {
@@ -3304,6 +3304,8 @@ UniValue CreateRolledBackUTXOSnapshot(
                 if (coins_count % 100'000 == 0) {
                     temp_cache.Flush();
                 }
+            } else {
+                throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
             }
             cursor->Next();
         }
diff --git a/test/functional/feature_utxo_abort_on_error.py b/test/functional/feature_utxo_abort_on_error.py
index 5e69333c13..dbfcd0e262 100755
--- a/test/functional/feature_utxo_abort_on_error.py
+++ b/test/functional/feature_utxo_abort_on_error.py
@@ -22,7 +22,7 @@ except ImportError:
 
 from test_framework.blocktools import COINBASE_MATURITY
 from test_framework.test_framework import BitcoinTestFramework, SkipTest
-from test_framework.util import assert_equal
+from test_framework.util import assert_equal, assert_raises_rpc_error
 from test_framework.wallet import MiniWallet
 
 
@@ -87,6 +87,12 @@ class UTXOAbortOnErrorTest(BitcoinTestFramework):
         # touches them. The node starts cleanly regardless of the tampered entry.
         assert_equal(node0.getblockcount(), COINBASE_MATURITY + 1)
 
+        self.log.info("Rollback export must fail when it cannot read a coin")
+        assert_raises_rpc_error(-32603, "Unable to read UTXO set", node0.dumptxoutset, "rollback.dat", rollback=COINBASE_MATURITY)
+
+        self.log.info("UTXO set scan must fail when it cannot read a coin")
+        assert_raises_rpc_error(-32603, "Unable to read UTXO set", node0.scantxoutset, "start", ["raw(51)"])
+
         # Now spend the corrupted UTXO
         self.log.info("node1 broadcasts the spend and mines a block")
         node1.sendrawtransaction(spend_tx_hex)

When `dumptxoutset` creates a rollback snapshot, the copy loop skips coins on read failure. The cursor catches the new decompression exception and returns false, so this PR adds another trigger for that issue. Could we abort the copy on a failed read, either here or in a separate follow-up? Otherwise, `dumptxoutset` can succeed with a coin missing. `scantxoutset` uses the same cursor reader, but a failed read currently looks like cancellation (`success: false` with partial results). Could we return the UTXO read error there as well? The existing corruption test can cover both RPCs before triggering the validation abort. <details> <summary>Report unreadable coins in rollback exports and UTXO scans</summary> ```diff diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index ae75072462..27223dda57 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -2258,7 +2258,7 @@ bool FindScriptPubKey(std::atomic<int>& scan_progress, const std::atomic<bool>& while (cursor->Valid()) { COutPoint key; Coin coin; - if (!cursor->GetKey(key) || !cursor->GetValue(coin)) return false; + if (!cursor->GetKey(key) || !cursor->GetValue(coin)) throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set"); if (++count % 8192 == 0) { interruption_point(); if (should_abort) { @@ -3304,6 +3304,8 @@ UniValue CreateRolledBackUTXOSnapshot( if (coins_count % 100'000 == 0) { temp_cache.Flush(); } + } else { + throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set"); } cursor->Next(); } diff --git a/test/functional/feature_utxo_abort_on_error.py b/test/functional/feature_utxo_abort_on_error.py index 5e69333c13..dbfcd0e262 100755 --- a/test/functional/feature_utxo_abort_on_error.py +++ b/test/functional/feature_utxo_abort_on_error.py @@ -22,7 +22,7 @@ except ImportError: from test_framework.blocktools import COINBASE_MATURITY from test_framework.test_framework import BitcoinTestFramework, SkipTest -from test_framework.util import assert_equal +from test_framework.util import assert_equal, assert_raises_rpc_error from test_framework.wallet import MiniWallet @@ -87,6 +87,12 @@ class UTXOAbortOnErrorTest(BitcoinTestFramework): # touches them. The node starts cleanly regardless of the tampered entry. assert_equal(node0.getblockcount(), COINBASE_MATURITY + 1) + self.log.info("Rollback export must fail when it cannot read a coin") + assert_raises_rpc_error(-32603, "Unable to read UTXO set", node0.dumptxoutset, "rollback.dat", rollback=COINBASE_MATURITY) + + self.log.info("UTXO set scan must fail when it cannot read a coin") + assert_raises_rpc_error(-32603, "Unable to read UTXO set", node0.scantxoutset, "start", ["raw(51)"]) + # Now spend the corrupted UTXO self.log.info("node1 broadcasts the spend and mines a block") node1.sendrawtransaction(spend_tx_hex) ``` </details>
l0rinc (Migrated from github.com) commented 2026-09-29 21:02:01 +00:00

Given the concern about exceptions being caught along the way (hinted at in the PR description and discussed in several related PRs and issues recently), could we add simple higher-level checks that Coin and CTxUndo deserialization propagate this new failure?

Check failure propagation through Coin and undo deserialization
diff --git a/src/test/coins_tests.cpp b/src/test/coins_tests.cpp
index d2bd053d55..064e0bddc9 100644
--- a/src/test/coins_tests.cpp
+++ b/src/test/coins_tests.cpp
@@ -543,6 +543,10 @@ BOOST_AUTO_TEST_CASE(ccoins_serialization)
     // scriptPubKey that ends beyond the end of the stream
     BOOST_CHECK_EXCEPTION(SpanReader{"000007"_hex} >> Coin{}, std::ios_base::failure, HasReason{"end of data"});

+    // Coin and undo deserialization must propagate the script decompression failure
+    BOOST_CHECK_EXCEPTION(SpanReader{"000004ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"_hex} >> Coin{}, std::ios_base::failure, HasReason{"Non-decodable compressed script"});
+    BOOST_CHECK_EXCEPTION(SpanReader{"01000004ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"_hex} >> CTxUndo{}, std::ios_base::failure, HasReason{"Non-decodable compressed script"});
+
     // Very large scriptPubKey (3*10^9 bytes) past the end of the stream
     DataStream tmp{};
     uint64_t x = 3000000000ULL;
Given the concern about exceptions being caught along the way (hinted at in the PR description and discussed in several related PRs and issues recently), could we add simple higher-level checks that `Coin` and `CTxUndo` deserialization propagate this new failure? <details> <summary>Check failure propagation through Coin and undo deserialization</summary> ```diff diff --git a/src/test/coins_tests.cpp b/src/test/coins_tests.cpp index d2bd053d55..064e0bddc9 100644 --- a/src/test/coins_tests.cpp +++ b/src/test/coins_tests.cpp @@ -543,6 +543,10 @@ BOOST_AUTO_TEST_CASE(ccoins_serialization) // scriptPubKey that ends beyond the end of the stream BOOST_CHECK_EXCEPTION(SpanReader{"000007"_hex} >> Coin{}, std::ios_base::failure, HasReason{"end of data"}); + // Coin and undo deserialization must propagate the script decompression failure + BOOST_CHECK_EXCEPTION(SpanReader{"000004ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"_hex} >> Coin{}, std::ios_base::failure, HasReason{"Non-decodable compressed script"}); + BOOST_CHECK_EXCEPTION(SpanReader{"01000004ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"_hex} >> CTxUndo{}, std::ios_base::failure, HasReason{"Non-decodable compressed script"}); + // Very large scriptPubKey (3*10^9 bytes) past the end of the stream DataStream tmp{}; uint64_t x = 3000000000ULL; ``` </details>
l0rinc (Migrated from github.com) commented 2026-09-29 04:07:13 +00:00

For completeness we could round-trip 2/3 as well

Cover off-curve keys in compression classes 2 and 3
diff --git a/src/test/compress_tests.cpp b/src/test/compress_tests.cpp
index 533a2a49de..35594d2480 100644
--- a/src/test/compress_tests.cpp
+++ b/src/test/compress_tests.cpp
@@ -186,6 +186,11 @@ BOOST_AUTO_TEST_CASE(compress_p2pk_scripts_not_on_curve)
 
     // Check off-curve script serialization round-trips properly
     CheckScriptCompressionRoundTrip(script, 68);
+
+    // Classes 2/3 preserve off-curve keys verbatim and remain valid stored records
+    for (const CPubKey& compressed_pubkey : x_not_on_curve.GetCPubKeys()) {
+        CheckScriptCompressionRoundTrip(CScript() << compressed_pubkey << OP_CHECKSIG, 33);
+    }
 }
 
 BOOST_AUTO_TEST_CASE(compress_p2pk_wrong_y)

For completeness we could round-trip 2/3 as well <details> <summary>Cover off-curve keys in compression classes 2 and 3</summary> ```diff diff --git a/src/test/compress_tests.cpp b/src/test/compress_tests.cpp index 533a2a49de..35594d2480 100644 --- a/src/test/compress_tests.cpp +++ b/src/test/compress_tests.cpp @@ -186,6 +186,11 @@ BOOST_AUTO_TEST_CASE(compress_p2pk_scripts_not_on_curve) // Check off-curve script serialization round-trips properly CheckScriptCompressionRoundTrip(script, 68); + + // Classes 2/3 preserve off-curve keys verbatim and remain valid stored records + for (const CPubKey& compressed_pubkey : x_not_on_curve.GetCPubKeys()) { + CheckScriptCompressionRoundTrip(CScript() << compressed_pubkey << OP_CHECKSIG, 33); + } } BOOST_AUTO_TEST_CASE(compress_p2pk_wrong_y) ``` </details>
l0rinc (Migrated from github.com) commented 2026-09-29 04:05:29 +00:00

Seems to me the off-curve and wrong-Y raw-storage assertions are the same, so could we extract them into a helper?

Share P2PK raw-storage checks
diff --git a/src/test/compress_tests.cpp b/src/test/compress_tests.cpp
index eba72eb3be..533a2a49de 100644
--- a/src/test/compress_tests.cpp
+++ b/src/test/compress_tests.cpp
@@ -136,6 +136,16 @@ BOOST_AUTO_TEST_CASE(compress_script_to_uncompressed_pubkey_id)
     BOOST_CHECK_EQUAL(out[0], 0x04 | (script[65] & 0x01)); // least significant bit (lsb) of last char of pubkey is mapped into out[0]
 }
 
+// ScriptCompression must encode the script in serialized_size bytes and decode it back unchanged
+static void CheckScriptCompressionRoundTrip(const CScript& script, size_t serialized_size)
+{
+    DataStream s = DataStream{} << Using<ScriptCompression>(script);
+    BOOST_CHECK_EQUAL(s.size(), serialized_size);
+    CScript restored;
+    s >> Using<ScriptCompression>(restored);
+    BOOST_CHECK(restored == script);
+}
+
 BOOST_AUTO_TEST_CASE(compress_p2pk_scripts_not_on_curve)
 {
     XOnlyPubKey x_not_on_curve;
@@ -175,10 +185,7 @@ BOOST_AUTO_TEST_CASE(compress_p2pk_scripts_not_on_curve)
     }
 
     // Check off-curve script serialization round-trips properly
-    DataStream s = DataStream{} << Using<ScriptCompression>(script);
-    CScript restored;
-    s >> Using<ScriptCompression>(restored);
-    BOOST_CHECK(restored == script);
+    CheckScriptCompressionRoundTrip(script, 68);
 }
 
 BOOST_AUTO_TEST_CASE(compress_p2pk_wrong_y)
@@ -202,11 +209,7 @@ BOOST_AUTO_TEST_CASE(compress_p2pk_wrong_y)
 
         // Ensure serialize stores it raw (1-byte size prefix + 67, not 33 compressed)
         // and unserialize gives it back unchanged
-        DataStream s = DataStream{} << Using<ScriptCompression>(script);
-        BOOST_CHECK_EQUAL(s.size(), 68U);
-        CScript restored;
-        s >> Using<ScriptCompression>(restored);
-        BOOST_CHECK(restored == script);
+        CheckScriptCompressionRoundTrip(script, 68);
     }
 }
 

Seems to me the off-curve and wrong-Y raw-storage assertions are the same, so could we extract them into a helper? <details> <summary>Share P2PK raw-storage checks</summary> ```diff diff --git a/src/test/compress_tests.cpp b/src/test/compress_tests.cpp index eba72eb3be..533a2a49de 100644 --- a/src/test/compress_tests.cpp +++ b/src/test/compress_tests.cpp @@ -136,6 +136,16 @@ BOOST_AUTO_TEST_CASE(compress_script_to_uncompressed_pubkey_id) BOOST_CHECK_EQUAL(out[0], 0x04 | (script[65] & 0x01)); // least significant bit (lsb) of last char of pubkey is mapped into out[0] } +// ScriptCompression must encode the script in serialized_size bytes and decode it back unchanged +static void CheckScriptCompressionRoundTrip(const CScript& script, size_t serialized_size) +{ + DataStream s = DataStream{} << Using<ScriptCompression>(script); + BOOST_CHECK_EQUAL(s.size(), serialized_size); + CScript restored; + s >> Using<ScriptCompression>(restored); + BOOST_CHECK(restored == script); +} + BOOST_AUTO_TEST_CASE(compress_p2pk_scripts_not_on_curve) { XOnlyPubKey x_not_on_curve; @@ -175,10 +185,7 @@ BOOST_AUTO_TEST_CASE(compress_p2pk_scripts_not_on_curve) } // Check off-curve script serialization round-trips properly - DataStream s = DataStream{} << Using<ScriptCompression>(script); - CScript restored; - s >> Using<ScriptCompression>(restored); - BOOST_CHECK(restored == script); + CheckScriptCompressionRoundTrip(script, 68); } BOOST_AUTO_TEST_CASE(compress_p2pk_wrong_y) @@ -202,11 +209,7 @@ BOOST_AUTO_TEST_CASE(compress_p2pk_wrong_y) // Ensure serialize stores it raw (1-byte size prefix + 67, not 33 compressed) // and unserialize gives it back unchanged - DataStream s = DataStream{} << Using<ScriptCompression>(script); - BOOST_CHECK_EQUAL(s.size(), 68U); - CScript restored; - s >> Using<ScriptCompression>(restored); - BOOST_CHECK(restored == script); + CheckScriptCompressionRoundTrip(script, 68); } } ``` </details>
l0rinc (Migrated from github.com) commented 2026-09-29 20:57:20 +00:00

nit: the script is the last field of a Coin, so nothing follows it in a chainstate value.
Undo records and snapshot files are where more data follows.

Correct where trailing data follows the script
diff --git a/src/test/fuzz/script.cpp b/src/test/fuzz/script.cpp
index 2db84f6ef3..a6929d3a8f 100644
--- a/src/test/fuzz/script.cpp
+++ b/src/test/fuzz/script.cpp
@@ -95,8 +95,7 @@ FUZZ_TARGET(script, .init = initialize_script)
 
     {
         // Exercises ScriptCompression::Unser path.
-        // First, this always runs inside a Coin record, so more data follows the script
-        // in the stream and it must not be consumed.
+        // Undo records and snapshot files store more data after the script, which must not be consumed.
         //
         // A compressed script starts with its type: one of six special encodings (0 to 5) with
         // a fixed-size payload, or a raw script length plus nSpecialScripts. A special script

nit: the script is the last field of a `Coin`, so nothing follows it in a chainstate value. Undo records and snapshot files are where more data follows. <details> <summary>Correct where trailing data follows the script</summary> ```diff diff --git a/src/test/fuzz/script.cpp b/src/test/fuzz/script.cpp index 2db84f6ef3..a6929d3a8f 100644 --- a/src/test/fuzz/script.cpp +++ b/src/test/fuzz/script.cpp @@ -95,8 +95,7 @@ FUZZ_TARGET(script, .init = initialize_script) { // Exercises ScriptCompression::Unser path. - // First, this always runs inside a Coin record, so more data follows the script - // in the stream and it must not be consumed. + // Undo records and snapshot files store more data after the script, which must not be consumed. // // A compressed script starts with its type: one of six special encodings (0 to 5) with // a fixed-size payload, or a raw script length plus nSpecialScripts. A special script ``` </details>
l0rinc (Migrated from github.com) commented 2026-09-29 21:04:00 +00:00

nit: could we cap raw-payload consumption to leave more fuzz input for later checks? The fuzzer might already handle this, but I would expect it to have an easier time this
way...

Limit payload consumption while keeping varied bytes
diff --git a/src/test/fuzz/script.cpp b/src/test/fuzz/script.cpp
index 40a74cb008..3adf140b78 100644
--- a/src/test/fuzz/script.cpp
+++ b/src/test/fuzz/script.cpp
@@ -113,7 +113,9 @@ FUZZ_TARGET(script, .init = initialize_script)
             type = payload_size + ScriptCompression::nSpecialScripts;
         }
 
-        const std::vector<uint8_t> payload = ConsumeFixedLengthByteVector(fuzzed_data_provider, payload_size);
+        // Keep varied payload bytes without letting long raw records drain the input
+        std::vector<uint8_t> payload = ConsumeFixedLengthByteVector(fuzzed_data_provider, std::min(payload_size, 32U));
+        payload.resize(payload_size);
         const std::vector<std::byte> trailing = ConsumeRandomLengthByteVector<std::byte>(fuzzed_data_provider);
         // Decodable unless it is a pubkey record (type 4 or 5) whose X coordinate is not a valid compressed pubkey.
         bool decodable{true};

nit: could we cap raw-payload consumption to leave more fuzz input for later checks? The fuzzer might already handle this, but I would expect it to have an easier time this way... <details> <summary>Limit payload consumption while keeping varied bytes</summary> ```diff diff --git a/src/test/fuzz/script.cpp b/src/test/fuzz/script.cpp index 40a74cb008..3adf140b78 100644 --- a/src/test/fuzz/script.cpp +++ b/src/test/fuzz/script.cpp @@ -113,7 +113,9 @@ FUZZ_TARGET(script, .init = initialize_script) type = payload_size + ScriptCompression::nSpecialScripts; } - const std::vector<uint8_t> payload = ConsumeFixedLengthByteVector(fuzzed_data_provider, payload_size); + // Keep varied payload bytes without letting long raw records drain the input + std::vector<uint8_t> payload = ConsumeFixedLengthByteVector(fuzzed_data_provider, std::min(payload_size, 32U)); + payload.resize(payload_size); const std::vector<std::byte> trailing = ConsumeRandomLengthByteVector<std::byte>(fuzzed_data_provider); // Decodable unless it is a pubkey record (type 4 or 5) whose X coordinate is not a valid compressed pubkey. bool decodable{true}; ``` </details>
l0rinc (Migrated from github.com) commented 2026-09-29 20:54:14 +00:00

nit: I think we can simplify this a bit

Use XOnlyPubKey as the decodability oracle
diff --git a/src/test/fuzz/script.cpp b/src/test/fuzz/script.cpp
index 3adf140b78..6cc391c9d6 100644
--- a/src/test/fuzz/script.cpp
+++ b/src/test/fuzz/script.cpp
@@ -117,13 +117,8 @@ FUZZ_TARGET(script, .init = initialize_script)
         std::vector<uint8_t> payload = ConsumeFixedLengthByteVector(fuzzed_data_provider, std::min(payload_size, 32U));
         payload.resize(payload_size);
         const std::vector<std::byte> trailing = ConsumeRandomLengthByteVector<std::byte>(fuzzed_data_provider);
-        // Decodable unless it is a pubkey record (type 4 or 5) whose X coordinate is not a valid compressed pubkey.
-        bool decodable{true};
-        if (type == 4 || type == 5) {
-            std::vector<unsigned char> pubkey{static_cast<unsigned char>(type - 2)};
-            pubkey.insert(pubkey.end(), payload.begin(), payload.end());
-            decodable = CPubKey{pubkey}.IsFullyValid();
-        }
+        // Decodable unless it is a pubkey record (type 4 or 5) whose X coordinate is not on the curve.
+        const bool decodable{(type != 4 && type != 5) || XOnlyPubKey{payload}.IsFullyValid()};
 
         DataStream stream = DataStream{} << VARINT(type) << std::span{payload} << std::span{trailing};
         try {

nit: I think we can simplify this a bit <details> <summary>Use XOnlyPubKey as the decodability oracle</summary> ```diff diff --git a/src/test/fuzz/script.cpp b/src/test/fuzz/script.cpp index 3adf140b78..6cc391c9d6 100644 --- a/src/test/fuzz/script.cpp +++ b/src/test/fuzz/script.cpp @@ -117,13 +117,8 @@ FUZZ_TARGET(script, .init = initialize_script) std::vector<uint8_t> payload = ConsumeFixedLengthByteVector(fuzzed_data_provider, std::min(payload_size, 32U)); payload.resize(payload_size); const std::vector<std::byte> trailing = ConsumeRandomLengthByteVector<std::byte>(fuzzed_data_provider); - // Decodable unless it is a pubkey record (type 4 or 5) whose X coordinate is not a valid compressed pubkey. - bool decodable{true}; - if (type == 4 || type == 5) { - std::vector<unsigned char> pubkey{static_cast<unsigned char>(type - 2)}; - pubkey.insert(pubkey.end(), payload.begin(), payload.end()); - decodable = CPubKey{pubkey}.IsFullyValid(); - } + // Decodable unless it is a pubkey record (type 4 or 5) whose X coordinate is not on the curve. + const bool decodable{(type != 4 && type != 5) || XOnlyPubKey{payload}.IsFullyValid()}; DataStream stream = DataStream{} << VARINT(type) << std::span{payload} << std::span{trailing}; try { ``` </details>
l0rinc (Migrated from github.com) commented 2026-09-29 21:29:38 +00:00

Indeed, special-scripts were already checked to be decodable and should re-serialize to the same bytes, so a round-trip comparison would check that the script hasn't changed.

Require special records to re-encode unchanged
diff --git a/src/test/fuzz/script.cpp b/src/test/fuzz/script.cpp
index 14ec0a10a3..40a74cb008 100644
--- a/src/test/fuzz/script.cpp
+++ b/src/test/fuzz/script.cpp
@@ -129,7 +129,7 @@ FUZZ_TARGET(script, .init = initialize_script)
             stream >> Using<ScriptCompression>(decompressed_script);
             assert(decodable);
             if (type < ScriptCompression::nSpecialScripts) {
-                assert(!decompressed_script.empty()); // future: check each type individually
+                assert(std::ranges::equal(DataStream{} << Using<ScriptCompression>(decompressed_script), DataStream{} << VARINT(type) << std::span{payload}));
             } else if (payload_size > MAX_SCRIPT_SIZE) {
                 assert(decompressed_script == CScript() << OP_RETURN);
             } else {

Indeed, special-scripts were already checked to be decodable and should re-serialize to the same bytes, so a round-trip comparison would check that the script hasn't changed. <details> <summary>Require special records to re-encode unchanged</summary> ```diff diff --git a/src/test/fuzz/script.cpp b/src/test/fuzz/script.cpp index 14ec0a10a3..40a74cb008 100644 --- a/src/test/fuzz/script.cpp +++ b/src/test/fuzz/script.cpp @@ -129,7 +129,7 @@ FUZZ_TARGET(script, .init = initialize_script) stream >> Using<ScriptCompression>(decompressed_script); assert(decodable); if (type < ScriptCompression::nSpecialScripts) { - assert(!decompressed_script.empty()); // future: check each type individually + assert(std::ranges::equal(DataStream{} << Using<ScriptCompression>(decompressed_script), DataStream{} << VARINT(type) << std::span{payload})); } else if (payload_size > MAX_SCRIPT_SIZE) { assert(decompressed_script == CScript() << OP_RETURN); } else { ``` </details>
fametrano commented 2026-10-25 06:43:27 +00:00 (Migrated from github.com)

tACK 5500521f8b

DecompressScript can only fail for types 4 and 5, when libsecp256k1 rejects 02/03 || x: x is not below p, or x³+7 is not a square. Inside Unser the type is always below 6, so the final return false is unreachable and the new throw fires on exactly those inputs. I checked this against 4636 vectors from a library I maintain, cross-checked there with Euler's criterion: 2398 throw and 2238 decode to the expected script, as a bare script, inside a Coin and inside a CTxUndo, with the trailing byte left in the stream each time. The vectors include 200 x+p values, 101 of them reducing to a valid x; all throw, since libsecp256k1 requires x < p.

On regtest, a snapshot whose first coin is rewritten as type 4 with x=5 (off the curve) or x=1+p fails loadtxoutset with "Bad snapshot format or truncated snapshot after deserializing 0 coins", while x=1 still reaches the content hash check. compress_tests, coins_tests and the script fuzz target (3000 random inputs, non-libFuzzer build) pass. I measured on macOS at the PR head with a unit test reading the vectors and a functional test, which I can share as a gist.

The throw also reaches the coins cursor, where a rollback dumptxoutset skips the unreadable coin and scantxoutset returns partial results as if cancelled. I did not test those paths, but l0rinc's diff for them would fit in this PR.

tACK 5500521f8bd93a42388bf8ef3c48d7c4c0ab75c6 `DecompressScript` can only fail for types 4 and 5, when libsecp256k1 rejects `02/03 || x`: x is not below p, or x³+7 is not a square. Inside `Unser` the type is always below 6, so the final `return false` is unreachable and the new throw fires on exactly those inputs. I checked this against 4636 vectors from a library I maintain, cross-checked there with Euler's criterion: 2398 throw and 2238 decode to the expected script, as a bare script, inside a `Coin` and inside a `CTxUndo`, with the trailing byte left in the stream each time. The vectors include 200 x+p values, 101 of them reducing to a valid x; all throw, since libsecp256k1 requires x < p. On regtest, a snapshot whose first coin is rewritten as type 4 with x=5 (off the curve) or x=1+p fails `loadtxoutset` with "Bad snapshot format or truncated snapshot after deserializing 0 coins", while x=1 still reaches the content hash check. `compress_tests`, `coins_tests` and the `script` fuzz target (3000 random inputs, non-libFuzzer build) pass. I measured on macOS at the PR head with a unit test reading the vectors and a functional test, which I can share as a gist. The throw also reaches the coins cursor, where a rollback `dumptxoutset` skips the unreadable coin and `scantxoutset` returns partial results as if cancelled. I did not test those paths, but l0rinc's diff for them would fit in this PR.
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!36280
No description provided.