Skip to content

Commit e9edd43

Browse files
committed
Merge bitcoin/bitcoin#32521: policy: make pathological transactions packed with legacy sigops non-standard
96da68a qa: functional test a transaction running into the legacy sigop limit (Antoine Poinsot) 3671479 qa: unit test standardness of inputs packed with legacy sigops (Antoine Poinsot) 5863315 policy: make pathological transactions packed with legacy sigops non-standard. (Antoine Poinsot) Pull request description: The Consensus Cleanup soft fork proposal includes a limit on the number of legacy signature operations potentially executed when validating a transaction. If this change is to be implemented here and activated by Bitcoin users in the future, we should make transactions that are not valid according to the new rules non-standard first because it would otherwise be a trivial DoS to potentially unupgraded miners after the soft fork activates. ML post: https://gnusha.org/pi/bitcoindev/49dyqqkf5NqGlGdinp6SELIoxzE_ONh3UIj6-EB8S804Id5yROq-b1uGK8DUru66eIlWuhb5R3nhRRutwuYjemiuOOBS2FQ4KWDnEh0wLuA=@protonmail.com/T/#u ACKs for top commit: instagibbs: reACK bitcoin/bitcoin@96da68a maflcko: review ACK 96da68a 🚋 achow101: ACK 96da68a glozow: light code review ACK 96da68a, looks correct to me Tree-SHA512: 106ffe62e48952affa31c5894a404a17a3b4ea8971815828166fba89069f757366129f7807205e8c6558beb75c6f67d8f9a41000be2f8cf95be3b1a02d87bfe9
2 parents 80067ac + 96da68a commit e9edd43

File tree

5 files changed

+184
-0
lines changed

5 files changed

+184
-0
lines changed

src/policy/policy.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,35 @@ bool IsStandardTx(const CTransaction& tx, const std::optional<unsigned>& max_dat
163163
return true;
164164
}
165165

166+
/**
167+
* Check the total number of non-witness sigops across the whole transaction, as per BIP54.
168+
*/
169+
static bool CheckSigopsBIP54(const CTransaction& tx, const CCoinsViewCache& inputs)
170+
{
171+
Assert(!tx.IsCoinBase());
172+
173+
unsigned int sigops{0};
174+
for (const auto& txin: tx.vin) {
175+
const auto& prev_txo{inputs.AccessCoin(txin.prevout).out};
176+
177+
// Unlike the existing block wide sigop limit which counts sigops present in the block
178+
// itself (including the scriptPubKey which is not executed until spending later), BIP54
179+
// counts sigops in the block where they are potentially executed (only).
180+
// This means sigops in the spent scriptPubKey count toward the limit.
181+
// `fAccurate` means correctly accounting sigops for CHECKMULTISIGs(VERIFY) with 16 pubkeys
182+
// or fewer. This method of accounting was introduced by BIP16, and BIP54 reuses it.
183+
// The GetSigOpCount call on the previous scriptPubKey counts both bare and P2SH sigops.
184+
sigops += txin.scriptSig.GetSigOpCount(/*fAccurate=*/true);
185+
sigops += prev_txo.scriptPubKey.GetSigOpCount(txin.scriptSig);
186+
187+
if (sigops > MAX_TX_LEGACY_SIGOPS) {
188+
return false;
189+
}
190+
}
191+
192+
return true;
193+
}
194+
166195
/**
167196
* Check transaction inputs.
168197
*
@@ -178,13 +207,19 @@ bool IsStandardTx(const CTransaction& tx, const std::optional<unsigned>& max_dat
178207
* as potential new upgrade hooks.
179208
*
180209
* Note that only the non-witness portion of the transaction is checked here.
210+
*
211+
* We also check the total number of non-witness sigops across the whole transaction, as per BIP54.
181212
*/
182213
bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
183214
{
184215
if (tx.IsCoinBase()) {
185216
return true; // Coinbases don't use vin normally
186217
}
187218

219+
if (!CheckSigopsBIP54(tx, mapInputs)) {
220+
return false;
221+
}
222+
188223
for (unsigned int i = 0; i < tx.vin.size(); i++) {
189224
const CTxOut& prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;
190225

src/policy/policy.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ static constexpr unsigned int MIN_STANDARD_TX_NONWITNESS_SIZE{65};
3838
static constexpr unsigned int MAX_P2SH_SIGOPS{15};
3939
/** The maximum number of sigops we're willing to relay/mine in a single tx */
4040
static constexpr unsigned int MAX_STANDARD_TX_SIGOPS_COST{MAX_BLOCK_SIGOPS_COST/5};
41+
/** The maximum number of potentially executed legacy signature operations in a single standard tx */
42+
static constexpr unsigned int MAX_TX_LEGACY_SIGOPS{2'500};
4143
/** Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or replacement **/
4244
static constexpr unsigned int DEFAULT_INCREMENTAL_RELAY_FEE{1000};
4345
/** Default for -bytespersigop */

src/test/transaction_tests.cpp

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
#include <clientversion.h>
1111
#include <consensus/amount.h>
1212
#include <consensus/tx_check.h>
13+
#include <consensus/tx_verify.h>
1314
#include <consensus/validation.h>
1415
#include <core_io.h>
1516
#include <key.h>
@@ -1053,4 +1054,99 @@ BOOST_AUTO_TEST_CASE(test_IsStandard)
10531054
CheckIsNotStandard(t, "dust");
10541055
}
10551056

1057+
BOOST_AUTO_TEST_CASE(max_standard_legacy_sigops)
1058+
{
1059+
CCoinsView coins_dummy;
1060+
CCoinsViewCache coins(&coins_dummy);
1061+
CKey key;
1062+
key.MakeNewKey(true);
1063+
1064+
// Create a pathological P2SH script padded with as many sigops as is standard.
1065+
CScript max_sigops_redeem_script{CScript() << std::vector<unsigned char>{} << key.GetPubKey()};
1066+
for (unsigned i{0}; i < MAX_P2SH_SIGOPS - 1; ++i) max_sigops_redeem_script << OP_2DUP << OP_CHECKSIG << OP_DROP;
1067+
max_sigops_redeem_script << OP_CHECKSIG << OP_NOT;
1068+
const CScript max_sigops_p2sh{GetScriptForDestination(ScriptHash(max_sigops_redeem_script))};
1069+
1070+
// Create a transaction fanning out as many such P2SH outputs as is standard to spend in a
1071+
// single transaction, and a transaction spending them.
1072+
CMutableTransaction tx_create, tx_max_sigops;
1073+
const unsigned p2sh_inputs_count{MAX_TX_LEGACY_SIGOPS / MAX_P2SH_SIGOPS};
1074+
tx_create.vout.reserve(p2sh_inputs_count);
1075+
for (unsigned i{0}; i < p2sh_inputs_count; ++i) {
1076+
tx_create.vout.emplace_back(424242 + i, max_sigops_p2sh);
1077+
}
1078+
auto prev_txid{tx_create.GetHash()};
1079+
tx_max_sigops.vin.reserve(p2sh_inputs_count);
1080+
for (unsigned i{0}; i < p2sh_inputs_count; ++i) {
1081+
tx_max_sigops.vin.emplace_back(prev_txid, i, CScript() << ToByteVector(max_sigops_redeem_script));
1082+
}
1083+
1084+
// p2sh_inputs_count is truncated to 166 (from 166.6666..)
1085+
BOOST_CHECK_LT(p2sh_inputs_count * MAX_P2SH_SIGOPS, MAX_TX_LEGACY_SIGOPS);
1086+
AddCoins(coins, CTransaction(tx_create), 0, false);
1087+
1088+
// 2490 sigops is below the limit.
1089+
BOOST_CHECK_EQUAL(GetP2SHSigOpCount(CTransaction(tx_max_sigops), coins), 2490);
1090+
BOOST_CHECK(::AreInputsStandard(CTransaction(tx_max_sigops), coins));
1091+
1092+
// Adding one more input will bump this to 2505, hitting the limit.
1093+
tx_create.vout.emplace_back(424242, max_sigops_p2sh);
1094+
prev_txid = tx_create.GetHash();
1095+
for (unsigned i{0}; i < p2sh_inputs_count; ++i) {
1096+
tx_max_sigops.vin[i] = CTxIn(COutPoint(prev_txid, i), CScript() << ToByteVector(max_sigops_redeem_script));
1097+
}
1098+
tx_max_sigops.vin.emplace_back(prev_txid, p2sh_inputs_count, CScript() << ToByteVector(max_sigops_redeem_script));
1099+
AddCoins(coins, CTransaction(tx_create), 0, false);
1100+
BOOST_CHECK_GT((p2sh_inputs_count + 1) * MAX_P2SH_SIGOPS, MAX_TX_LEGACY_SIGOPS);
1101+
BOOST_CHECK_EQUAL(GetP2SHSigOpCount(CTransaction(tx_max_sigops), coins), 2505);
1102+
BOOST_CHECK(!::AreInputsStandard(CTransaction(tx_max_sigops), coins));
1103+
1104+
// Now, check the limit can be reached with regular P2PK outputs too. Use a separate
1105+
// preparation transaction, to demonstrate spending coins from a single tx is irrelevant.
1106+
CMutableTransaction tx_create_p2pk;
1107+
const auto p2pk_script{CScript() << key.GetPubKey() << OP_CHECKSIG};
1108+
unsigned p2pk_inputs_count{10}; // From 2490 to 2500.
1109+
for (unsigned i{0}; i < p2pk_inputs_count; ++i) {
1110+
tx_create_p2pk.vout.emplace_back(212121 + i, p2pk_script);
1111+
}
1112+
prev_txid = tx_create_p2pk.GetHash();
1113+
tx_max_sigops.vin.resize(p2sh_inputs_count); // Drop the extra input.
1114+
for (unsigned i{0}; i < p2pk_inputs_count; ++i) {
1115+
tx_max_sigops.vin.emplace_back(prev_txid, i);
1116+
}
1117+
AddCoins(coins, CTransaction(tx_create_p2pk), 0, false);
1118+
1119+
// The transaction now contains exactly 2500 sigops, the check should pass.
1120+
BOOST_CHECK_EQUAL(p2sh_inputs_count * MAX_P2SH_SIGOPS + p2pk_inputs_count * 1, MAX_TX_LEGACY_SIGOPS);
1121+
BOOST_CHECK(::AreInputsStandard(CTransaction(tx_max_sigops), coins));
1122+
1123+
// Now, add some Segwit inputs. We add one for each defined Segwit output type. The limit
1124+
// is exclusively on non-witness sigops and therefore those should not be counted.
1125+
CMutableTransaction tx_create_segwit;
1126+
const auto witness_script{CScript() << key.GetPubKey() << OP_CHECKSIG};
1127+
tx_create_segwit.vout.emplace_back(121212, GetScriptForDestination(WitnessV0KeyHash(key.GetPubKey())));
1128+
tx_create_segwit.vout.emplace_back(131313, GetScriptForDestination(WitnessV0ScriptHash(witness_script)));
1129+
tx_create_segwit.vout.emplace_back(141414, GetScriptForDestination(WitnessV1Taproot{XOnlyPubKey(key.GetPubKey())}));
1130+
prev_txid = tx_create_segwit.GetHash();
1131+
for (unsigned i{0}; i < tx_create_segwit.vout.size(); ++i) {
1132+
tx_max_sigops.vin.emplace_back(prev_txid, i);
1133+
}
1134+
1135+
// The transaction now still contains exactly 2500 sigops, the check should pass.
1136+
AddCoins(coins, CTransaction(tx_create_segwit), 0, false);
1137+
BOOST_REQUIRE(::AreInputsStandard(CTransaction(tx_max_sigops), coins));
1138+
1139+
// Add one more P2PK input. We'll reach the limit.
1140+
tx_create_p2pk.vout.emplace_back(212121, p2pk_script);
1141+
prev_txid = tx_create_p2pk.GetHash();
1142+
tx_max_sigops.vin.resize(p2sh_inputs_count);
1143+
++p2pk_inputs_count;
1144+
for (unsigned i{0}; i < p2pk_inputs_count; ++i) {
1145+
tx_max_sigops.vin.emplace_back(prev_txid, i);
1146+
}
1147+
AddCoins(coins, CTransaction(tx_create_p2pk), 0, false);
1148+
BOOST_CHECK_GT(p2sh_inputs_count * MAX_P2SH_SIGOPS + p2pk_inputs_count * 1, MAX_TX_LEGACY_SIGOPS);
1149+
BOOST_CHECK(!::AreInputsStandard(CTransaction(tx_max_sigops), coins));
1150+
}
1151+
10561152
BOOST_AUTO_TEST_SUITE_END()

test/functional/mempool_sigoplimit.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
# Distributed under the MIT software license, see the accompanying
44
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
55
"""Test sigop limit mempool policy (`-bytespersigop` parameter)"""
6+
from copy import deepcopy
67
from decimal import Decimal
78
from math import ceil
89

@@ -17,23 +18,30 @@
1718
)
1819
from test_framework.script import (
1920
CScript,
21+
OP_2DUP,
2022
OP_CHECKMULTISIG,
2123
OP_CHECKSIG,
24+
OP_DROP,
2225
OP_ENDIF,
2326
OP_FALSE,
2427
OP_IF,
28+
OP_NOT,
2529
OP_RETURN,
2630
OP_TRUE,
2731
)
2832
from test_framework.script_util import (
2933
keys_to_multisig_script,
3034
script_to_p2wsh_script,
35+
script_to_p2sh_script,
36+
MAX_STD_LEGACY_SIGOPS,
37+
MAX_STD_P2SH_SIGOPS,
3138
)
3239
from test_framework.test_framework import BitcoinTestFramework
3340
from test_framework.util import (
3441
assert_equal,
3542
assert_greater_than,
3643
assert_greater_than_or_equal,
44+
assert_raises_rpc_error,
3745
)
3846
from test_framework.wallet import MiniWallet
3947
from test_framework.wallet_util import generate_keypair
@@ -174,6 +182,42 @@ def create_bare_multisig_tx(utxo_to_spend=None):
174182
# Transactions are tiny in weight
175183
assert_greater_than(2000, tx_parent.get_weight() + tx_child.get_weight())
176184

185+
def test_legacy_sigops_stdness(self):
186+
self.log.info("Test a transaction with too many legacy sigops in its inputs is non-standard.")
187+
188+
# Restart with the default settings
189+
self.restart_node(0)
190+
191+
# Create a P2SH script with 15 sigops.
192+
_, dummy_pubkey = generate_keypair()
193+
packed_redeem_script = [dummy_pubkey]
194+
for _ in range(MAX_STD_P2SH_SIGOPS - 1):
195+
packed_redeem_script += [OP_2DUP, OP_CHECKSIG, OP_DROP]
196+
packed_redeem_script = CScript(packed_redeem_script + [OP_CHECKSIG, OP_NOT])
197+
packed_p2sh_script = script_to_p2sh_script(packed_redeem_script)
198+
199+
# Create enough outputs to reach the sigops limit when spending them all at once.
200+
outpoints = []
201+
for _ in range(int(MAX_STD_LEGACY_SIGOPS / MAX_STD_P2SH_SIGOPS) + 1):
202+
res = self.wallet.send_to(from_node=self.nodes[0], scriptPubKey=packed_p2sh_script, amount=1_000)
203+
txid = int.from_bytes(bytes.fromhex(res["txid"]), byteorder="big")
204+
outpoints.append(COutPoint(txid, res["sent_vout"]))
205+
self.generate(self.nodes[0], 1)
206+
207+
# Spending all these outputs at once accounts for 2505 legacy sigops and is non-standard.
208+
nonstd_tx = CTransaction()
209+
nonstd_tx.vin = [CTxIn(op, CScript([b"", packed_redeem_script])) for op in outpoints]
210+
nonstd_tx.vout = [CTxOut(0, CScript([OP_RETURN, b""]))]
211+
assert_raises_rpc_error(-26, "bad-txns-nonstandard-inputs", self.nodes[0].sendrawtransaction, nonstd_tx.serialize().hex())
212+
213+
# Spending one less accounts for 2490 legacy sigops and is standard.
214+
std_tx = deepcopy(nonstd_tx)
215+
std_tx.vin.pop()
216+
self.nodes[0].sendrawtransaction(std_tx.serialize().hex())
217+
218+
# Make sure the original, non-standard, transaction can be mined.
219+
self.generateblock(self.nodes[0], output="raw(42)", transactions=[nonstd_tx.serialize().hex()])
220+
177221
def run_test(self):
178222
self.wallet = MiniWallet(self.nodes[0])
179223

@@ -191,6 +235,7 @@ def run_test(self):
191235
self.generate(self.wallet, 1)
192236

193237
self.test_sigops_package()
238+
self.test_legacy_sigops_stdness()
194239

195240

196241
if __name__ == '__main__':

test/functional/test_framework/script_util.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,12 @@
3535
hash160,
3636
)
3737

38+
# Maximum number of potentially executed legacy signature operations in validating a transaction.
39+
MAX_STD_LEGACY_SIGOPS = 2_500
40+
41+
# Maximum number of sigops per standard P2SH redeemScript.
42+
MAX_STD_P2SH_SIGOPS = 15
43+
3844
# To prevent a "tx-size-small" policy rule error, a transaction has to have a
3945
# non-witness size of at least 65 bytes (MIN_STANDARD_TX_NONWITNESS_SIZE in
4046
# src/policy/policy.h). Considering a Tx with the smallest possible single

0 commit comments

Comments
 (0)