bip352: match P2SH-P2WPKH instead of evaluating it #36776

Open
Eunovo wants to merge 3 commits from bip352-skip-empty-witness-stack-psh-pwpkh into master AGit
Eunovo commented 2026-11-05 13:58:09 +00:00 (Migrated from github.com)

For P2SH inputs, GetPubKeyFromInput evaluated the full scriptSig with EvalScript and then ran Solver on the redeem script, even though only P2SH-P2WPKH is eligible for BIP-352. That costs time on every non-segwit P2SH spend (e.g. multisig), whose scriptSigs can be up to MAX_SCRIPT_SIZE.

BIP-141 requires the scriptSig of a P2SH-wrapped witness program to be exactly a single push of the redeem script (SCRIPT_ERR_WITNESS_MALLEATED_P2SH). So any valid P2SH-P2WPKH scriptSig is exactly 0x16 OP_0 0x14 <20-byte keyhash>, and matching that template gives the same result without evaluating anything.

Benchmarks

bench_bitcoin -filter='BIP352_GetPubKey_P2SH_.*' -min-time=2000, Release build.

Before:

ns/input input/s err% total benchmark
688.30 1,452,858.07 0.1% 2.20 BIP352_GetPubKey_P2SH_Multisig
7,158.19 139,700.11 0.1% 2.20 BIP352_GetPubKey_P2SH_P2WPKH

After:

ns/input input/s err% total benchmark
56.87 17,584,611.40 0.0% 2.20 BIP352_GetPubKey_P2SH_Multisig
6,949.45 143,896.18 0.0% 2.20 BIP352_GetPubKey_P2SH_P2WPKH

P2SH multisig is about 12x faster to rule out. P2SH-P2WPKH saves about 200 ns per input; its time is still dominated by CPubKey::IsFullyValid().

For P2SH inputs, `GetPubKeyFromInput` evaluated the full scriptSig with `EvalScript` and then ran `Solver` on the redeem script, even though only P2SH-P2WPKH is eligible for BIP-352. That costs time on every non-segwit P2SH spend (e.g. multisig), whose scriptSigs can be up to `MAX_SCRIPT_SIZE`. BIP-141 requires the scriptSig of a P2SH-wrapped witness program to be exactly a single push of the redeem script (`SCRIPT_ERR_WITNESS_MALLEATED_P2SH`). So any valid P2SH-P2WPKH scriptSig is exactly `0x16 OP_0 0x14 <20-byte keyhash>`, and matching that template gives the same result without evaluating anything. ### Benchmarks `bench_bitcoin -filter='BIP352_GetPubKey_P2SH_.*' -min-time=2000`, Release build. Before: | ns/input | input/s | err% | total | benchmark |--------------------:|--------------------:|--------:|----------:|:---------- | 688.30 | 1,452,858.07 | 0.1% | 2.20 | `BIP352_GetPubKey_P2SH_Multisig` | 7,158.19 | 139,700.11 | 0.1% | 2.20 | `BIP352_GetPubKey_P2SH_P2WPKH` After: | ns/input | input/s | err% | total | benchmark |--------------------:|--------------------:|--------:|----------:|:---------- | 56.87 | 17,584,611.40 | 0.0% | 2.20 | `BIP352_GetPubKey_P2SH_Multisig` | 6,949.45 | 143,896.18 | 0.0% | 2.20 | `BIP352_GetPubKey_P2SH_P2WPKH` P2SH multisig is about 12x faster to rule out. P2SH-P2WPKH saves about 200 ns per input; its time is still dominated by `CPubKey::IsFullyValid()`.
DrahtBot commented 2026-11-05 13:58:16 +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
Stale ACK Yudis-bit, theStack

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:

  • #36360 (test: add tests in script test suites covering script.cpp live mutants by Yudis-bit)

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/36776 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36776.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36776#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 | | ---- | --------- | | Stale ACK | [Yudis-bit](https://github.com/bitcoin/bitcoin/pull/36776#pullrequestreview-5827072444), [theStack](https://github.com/bitcoin/bitcoin/pull/36776#pullrequestreview-5827141466) | 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: * [#36360](https://github.com/bitcoin/bitcoin/pull/36360) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36360.svg"></sub> (test: add tests in script test suites covering script.cpp live mutants by Yudis-bit) 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-->
First-time contributor

🔵 Suggestion · The P2SH template check loses its consensus rationale

The replacement comment describes the byte layout but omits the consensus requirement that makes exact matching safe here, unlike the adjacent malleable P2PKH case.

Location: src/common/bip352.cpp:211 (head).

🔵 Suggestion · P2SH extraction tests miss the newly rejected scriptSig forms

The tests do not cover the newly rejected non-canonical P2SH-P2WPKH scriptSig forms or verify that consensus rejects them, leaving the exact-match optimization's safety boundary untested.

Location: src/common/bip352.cpp:212 (head).

Review coverage was incomplete.


Reviewed: 1f4c03f444e2 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:806938d40e279b6d701b2e78128bb1a09b55193a0b697245a1dce6241d3081c1:3607c760b63c01fb7f1f349adfc3fd0614b148a7df02e42f2f0edc2d448925a1 --> <!-- ralph-base:095860411807e29282e61122b3b0247c08f3c7a5 --> <!-- ralph-head:1f4c03f444e20ce4328c3916447d86917728492e --> <!-- ralph-case:3d92c68b7e58af170885b2535c51281c95d5a1ac7f1dca8496bfa45055cd6ad4 --> **🔵 Suggestion · The P2SH template check loses its consensus rationale** The replacement comment describes the byte layout but omits the consensus requirement that makes exact matching safe here, unlike the adjacent malleable P2PKH case. Location: [`src/common/bip352.cpp:211`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/1f4c03f444e20ce4328c3916447d86917728492e/src/common/bip352.cpp#L211>) (head). **🔵 Suggestion · P2SH extraction tests miss the newly rejected `scriptSig` forms** The tests do not cover the newly rejected non-canonical P2SH-P2WPKH `scriptSig` forms or verify that consensus rejects them, leaving the exact-match optimization's safety boundary untested. Location: [`src/common/bip352.cpp:212`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/1f4c03f444e20ce4328c3916447d86917728492e/src/common/bip352.cpp#L212>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`1f4c03f444e2`](<https://git.fish.foo/bitcoin/bitcoin/commit/1f4c03f444e20ce4328c3916447d86917728492e>) · [Review report](<https://review.fish.foo/report/36776-1f4c03f444e20ce4328c3916447d86917728492e-3240-3.html>) · [Previous reports](<https://review.fish.foo/traces/36776/>) [permalink](<https://review.fish.foo/report/36776-1f4c03f444e20ce4328c3916447d86917728492e-3240-3.html>)
Yudis-bit (Migrated from github.com) reviewed 2026-11-06 14:17:08 +00:00
Yudis-bit (Migrated from github.com) left a comment

Tested ACK 959081325d

Benchmarked GetPubKeyFromInput on 2-of-3 multisig P2SH: drops from 1191 to 94 cycles on Zen 2 (-O2). All bip352_tests pass.

Since interpreter.cpp:2092 requires scriptSig == CScript() << redeem, any valid P2SH-P2WPKH scriptSig is always a single push of the 22-byte program ([22, OP_0, 20, <hash>], 23 bytes total). Could skip EvalScript and Solver entirely:

-        std::vector<std::vector<unsigned char>> stack;
-        if (!EvalScript(stack, txin.scriptSig, SCRIPT_VERIFY_NONE, DUMMY_CHECKER, SigVersion::BASE)) {
-            return std::nullopt;
-        }
-        if (stack.empty()) return std::nullopt;
-        CScript redeem{stack.back().begin(), stack.back().end()};
-        if (Solver(redeem, solutions) != TxoutType::WITNESS_V0_KEYHASH) return std::nullopt;
+        if (txin.scriptSig.size() != 23 ||
+            txin.scriptSig[0] != 22 ||
+            txin.scriptSig[1] != OP_0 ||
+            txin.scriptSig[2] != WITNESS_V0_KEYHASH_SIZE) {
+            return std::nullopt;
+        }

That also avoids EvalScript when the witness is non-empty (P2SH-P2WSH drops from 357 to 131 cycles), and removes the interpreter dependency on CScriptWitness ahead of #36521. Fine either way.

Tested ACK 959081325d Benchmarked GetPubKeyFromInput on 2-of-3 multisig P2SH: drops from 1191 to 94 cycles on Zen 2 (-O2). All bip352_tests pass. Since `interpreter.cpp:2092` requires `scriptSig == CScript() << redeem`, any valid P2SH-P2WPKH scriptSig is always a single push of the 22-byte program (`[22, OP_0, 20, <hash>]`, 23 bytes total). Could skip `EvalScript` and `Solver` entirely: ```diff - std::vector<std::vector<unsigned char>> stack; - if (!EvalScript(stack, txin.scriptSig, SCRIPT_VERIFY_NONE, DUMMY_CHECKER, SigVersion::BASE)) { - return std::nullopt; - } - if (stack.empty()) return std::nullopt; - CScript redeem{stack.back().begin(), stack.back().end()}; - if (Solver(redeem, solutions) != TxoutType::WITNESS_V0_KEYHASH) return std::nullopt; + if (txin.scriptSig.size() != 23 || + txin.scriptSig[0] != 22 || + txin.scriptSig[1] != OP_0 || + txin.scriptSig[2] != WITNESS_V0_KEYHASH_SIZE) { + return std::nullopt; + } ``` That also avoids `EvalScript` when the witness is non-empty (P2SH-P2WSH drops from 357 to 131 cycles), and removes the interpreter dependency on `CScriptWitness` ahead of #36521. Fine either way.
Eunovo commented 2026-11-09 13:23:48 +00:00 (Migrated from github.com)

Benchmarked GetPubKeyFromInput on 2-of-3 multisig P2SH: drops from 1191 to 94 cycles on Zen 2 (-O2). All bip352_tests pass.

Since interpreter.cpp:2092 requires scriptSig == CScript() << redeem, any valid P2SH-P2WPKH scriptSig is always a single push of the 22-byte program ([22, OP_0, 20, <hash>], 23 bytes total). Could skip EvalScript and Solver entirely:

Updated the PR to skip EvalScript entirely. I also added a benchmark for P2SH-MULTISIG, see results in https://github.com/bitcoin/bitcoin/pull/36776#issue-6224626766

> Benchmarked GetPubKeyFromInput on 2-of-3 multisig P2SH: drops from 1191 to 94 cycles on Zen 2 (-O2). All bip352_tests pass. > > Since `interpreter.cpp:2092` requires `scriptSig == CScript() << redeem`, any valid P2SH-P2WPKH scriptSig is always a single push of the 22-byte program (`[22, OP_0, 20, <hash>]`, 23 bytes total). Could skip `EvalScript` and `Solver` entirely: Updated the PR to skip `EvalScript` entirely. I also added a benchmark for `P2SH-MULTISIG`, see results in https://github.com/bitcoin/bitcoin/pull/36776#issue-6224626766
Yudis-bit (Migrated from github.com) reviewed 2026-11-09 14:13:11 +00:00
Yudis-bit (Migrated from github.com) left a comment

Tested ACK f9390ac89a

Ran bip352_tests and script_segwit_tests cleanly on Linux x86_64. BIP352_GetPubKey_P2SH_Multisig drops to 127 cycles with the single-push check avoiding EvalScript.

Tested ACK f9390ac89a Ran `bip352_tests` and `script_segwit_tests` cleanly on Linux x86_64. `BIP352_GetPubKey_P2SH_Multisig` drops to 127 cycles with the single-push check avoiding `EvalScript`.
theStack (Migrated from github.com) approved these changes 2026-11-09 14:42:41 +00:00
theStack (Migrated from github.com) left a comment

ACK f9390ac89a
(modulo a comment suggestion nit)

Seems reasonable to not involve the script interpreter for pubkey extraction at all.

ACK f9390ac89a9c2241636a082322c3c9c0ec202531 (modulo a comment suggestion nit) Seems reasonable to not involve the script interpreter for pubkey extraction at all.
theStack (Migrated from github.com) commented 2026-11-09 14:36:29 +00:00

note for other reviewers: I assumed the script/interpreter.h include could be removed now that we don't call EvalScript anymore, but it's still needed for the taproot control block size constants in the NUMS_H skipping logic

note for other reviewers: I assumed the `script/interpreter.h` include could be removed now that we don't call `EvalScript` anymore, but it's still needed for the taproot control block size constants in the NUMS_H skipping logic
Lines 212-214
theStack (Migrated from github.com) commented 2026-11-09 14:18:21 +00:00

nit: I'd keep the consensus rule for P2SH-P2WPKH (BIP 141) mentioned in the comments for clarity that only one (minimal push) encoding is possible, e.g. something like what you have in the PR description:

BIP-141 requires the scriptSig of a P2SH-wrapped witness program to be exactly a single push of the redeem script (SCRIPT_ERR_WITNESS_MALLEATED_P2SH). So any valid P2SH-P2WPKH scriptSig is exactly 0x16 OP_0 0x14 <20-byte keyhash>

nit: I'd keep the consensus rule for P2SH-P2WPKH (BIP 141) mentioned in the comments for clarity that only one (minimal push) encoding is possible, e.g. something like what you have in the PR description: > BIP-141 requires the scriptSig of a P2SH-wrapped witness program to be exactly a single push of the redeem script (`SCRIPT_ERR_WITNESS_MALLEATED_P2SH`). So any valid P2SH-P2WPKH scriptSig is exactly 0x16 OP_0 0x14 <20-byte keyhash>
Eunovo (Migrated from github.com) reviewed 2026-11-10 10:20:45 +00:00
Lines 212-214
Eunovo (Migrated from github.com) commented 2026-11-10 10:20:45 +00:00

Will do if I retouch.

Will do if I retouch.
DrahtBot commented 2026-11-26 17:39:24 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
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!36776
No description provided.