Skip to content

Commit 778b920

Browse files
author
MarcoFalke
committed
Merge bitcoin/bitcoin#21945: test: add P2PK support to MiniWallet
4bea301 test: use P2PK-MiniWallet for feature_csv_activation.py (Sebastian Falbesoner) dc7eb64 test: MiniWallet: add P2PK support (Sebastian Falbesoner) Pull request description: This PR adds support for creating and spending transactions with raw pubkey (P2PK) outputs to MiniWallet, [as suggested by MarcoFalke](bitcoin/bitcoin#21900 (comment)). Using that mode in the test `feature_csv_activation.py`, all txs submitted to the mempool follow the standard policy, i.e. `-acceptnonstdtxn=1` can be removed. Possible follow-ups: * Improve MiniWallet constructor Interface; an enum-like parameter instead of two booleans would probably be better * Look at other tests that could benefit from P2PK (e.g. feature_cltv.py?) * Check vsize also for P2PK txs (vsize varies due to signature, i.e. a range has to be asserted) ACKs for top commit: laanwj: Code review ACK 4bea301 Tree-SHA512: 9b428e6b7cfde59a8c7955d5096cea88af1384a5f49723f00052e9884d819d952d20a5ab39bb02f9d8b6073769c44462aa265d84a33e33da33c2d21670c488a6
2 parents 3f3c4d2 + 4bea301 commit 778b920

File tree

2 files changed

+43
-8
lines changed

2 files changed

+43
-8
lines changed

test/functional/feature_csv_activation.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,6 @@ def set_test_params(self):
9090
self.setup_clean_chain = True
9191
self.extra_args = [[
9292
93-
'-acceptnonstdtxn=1',
9493
'-par=1', # Use only one script thread to get the exact reject reason for testing
9594
]]
9695
self.supports_cli = False
@@ -103,12 +102,14 @@ def create_self_transfer_from_utxo(self, input_tx):
103102
def create_bip112special(self, input, txversion):
104103
tx = self.create_self_transfer_from_utxo(input)
105104
tx.nVersion = txversion
105+
self.miniwallet.sign_tx(tx)
106106
tx.vin[0].scriptSig = CScript([-1, OP_CHECKSEQUENCEVERIFY, OP_DROP] + list(CScript(tx.vin[0].scriptSig)))
107107
return tx
108108

109109
def create_bip112emptystack(self, input, txversion):
110110
tx = self.create_self_transfer_from_utxo(input)
111111
tx.nVersion = txversion
112+
self.miniwallet.sign_tx(tx)
112113
tx.vin[0].scriptSig = CScript([OP_CHECKSEQUENCEVERIFY] + list(CScript(tx.vin[0].scriptSig)))
113114
return tx
114115

@@ -126,6 +127,7 @@ def create_bip68txs(self, bip68inputs, txversion, locktime_delta=0):
126127
tx = self.create_self_transfer_from_utxo(bip68inputs[i])
127128
tx.nVersion = txversion
128129
tx.vin[0].nSequence = locktime + locktime_delta
130+
self.miniwallet.sign_tx(tx)
129131
tx.rehash()
130132
txs.append({'tx': tx, 'sdf': sdf, 'stf': stf})
131133

@@ -143,6 +145,7 @@ def create_bip112txs(self, bip112inputs, varyOP_CSV, txversion, locktime_delta=0
143145
else: # vary nSequence instead, OP_CSV is fixed
144146
tx.vin[0].nSequence = locktime + locktime_delta
145147
tx.nVersion = txversion
148+
self.miniwallet.sign_tx(tx)
146149
if (varyOP_CSV):
147150
tx.vin[0].scriptSig = CScript([locktime, OP_CHECKSEQUENCEVERIFY, OP_DROP] + list(CScript(tx.vin[0].scriptSig)))
148151
else:
@@ -178,7 +181,7 @@ def send_blocks(self, blocks, success=True, reject_reason=None):
178181

179182
def run_test(self):
180183
self.helper_peer = self.nodes[0].add_p2p_connection(P2PDataStore())
181-
self.miniwallet = MiniWallet(self.nodes[0], raw_script=True)
184+
self.miniwallet = MiniWallet(self.nodes[0], use_p2pk=True)
182185

183186
self.log.info("Generate blocks in the past for coinbase outputs.")
184187
long_past_time = int(time.time()) - 600 * 1000 # enough to build up to 1000 blocks 10 minutes apart without worrying about getting into the future
@@ -285,7 +288,7 @@ def run_test(self):
285288
success_txs = []
286289
# BIP113 tx, -1 CSV tx and empty stack CSV tx should succeed
287290
bip113tx_v1.nLockTime = self.last_block_time - 600 * 5 # = MTP of prior block (not <) but < time put on current block
288-
bip113tx_v1.rehash()
291+
self.miniwallet.sign_tx(bip113tx_v1)
289292
success_txs.append(bip113tx_v1)
290293
success_txs.append(bip112tx_special_v1)
291294
success_txs.append(bip112tx_emptystack_v1)
@@ -305,7 +308,7 @@ def run_test(self):
305308
success_txs = []
306309
# BIP113 tx, -1 CSV tx and empty stack CSV tx should succeed
307310
bip113tx_v2.nLockTime = self.last_block_time - 600 * 5 # = MTP of prior block (not <) but < time put on current block
308-
bip113tx_v2.rehash()
311+
self.miniwallet.sign_tx(bip113tx_v2)
309312
success_txs.append(bip113tx_v2)
310313
success_txs.append(bip112tx_special_v2)
311314
success_txs.append(bip112tx_emptystack_v2)
@@ -331,16 +334,20 @@ def run_test(self):
331334
self.log.info("BIP 113 tests")
332335
# BIP 113 tests should now fail regardless of version number if nLockTime isn't satisfied by new rules
333336
bip113tx_v1.nLockTime = self.last_block_time - 600 * 5 # = MTP of prior block (not <) but < time put on current block
337+
self.miniwallet.sign_tx(bip113tx_v1)
334338
bip113tx_v1.rehash()
335339
bip113tx_v2.nLockTime = self.last_block_time - 600 * 5 # = MTP of prior block (not <) but < time put on current block
340+
self.miniwallet.sign_tx(bip113tx_v2)
336341
bip113tx_v2.rehash()
337342
for bip113tx in [bip113tx_v1, bip113tx_v2]:
338343
self.send_blocks([self.create_test_block([bip113tx])], success=False, reject_reason='bad-txns-nonfinal')
339344

340345
# BIP 113 tests should now pass if the locktime is < MTP
341346
bip113tx_v1.nLockTime = self.last_block_time - 600 * 5 - 1 # < MTP of prior block
347+
self.miniwallet.sign_tx(bip113tx_v1)
342348
bip113tx_v1.rehash()
343349
bip113tx_v2.nLockTime = self.last_block_time - 600 * 5 - 1 # < MTP of prior block
350+
self.miniwallet.sign_tx(bip113tx_v2)
344351
bip113tx_v2.rehash()
345352
for bip113tx in [bip113tx_v1, bip113tx_v2]:
346353
self.send_blocks([self.create_test_block([bip113tx])])
@@ -465,6 +472,7 @@ def run_test(self):
465472
time_txs = []
466473
for tx in [tx['tx'] for tx in bip112txs_vary_OP_CSV_v2 if not tx['sdf'] and tx['stf']]:
467474
tx.vin[0].nSequence = BASE_RELATIVE_LOCKTIME | SEQ_TYPE_FLAG
475+
self.miniwallet.sign_tx(tx)
468476
tx.rehash()
469477
time_txs.append(tx)
470478

test/functional/test_framework/wallet.py

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
from decimal import Decimal
88
from test_framework.address import ADDRESS_BCRT1_P2WSH_OP_TRUE
9+
from test_framework.key import ECKey
910
from test_framework.messages import (
1011
COIN,
1112
COutPoint,
@@ -16,8 +17,11 @@
1617
)
1718
from test_framework.script import (
1819
CScript,
20+
LegacySignatureHash,
21+
OP_CHECKSIG,
1922
OP_TRUE,
2023
OP_NOP,
24+
SIGHASH_ALL,
2125
)
2226
from test_framework.util import (
2327
assert_equal,
@@ -27,12 +31,20 @@
2731

2832

2933
class MiniWallet:
30-
def __init__(self, test_node, *, raw_script=False):
34+
def __init__(self, test_node, *, raw_script=False, use_p2pk=False):
3135
self._test_node = test_node
3236
self._utxos = []
37+
self._priv_key = None
38+
self._address = None
39+
3340
if raw_script:
34-
self._address = None
3541
self._scriptPubKey = bytes(CScript([OP_TRUE]))
42+
elif use_p2pk:
43+
# use simple deterministic private key (k=1)
44+
self._priv_key = ECKey()
45+
self._priv_key.set((1).to_bytes(32, 'big'), True)
46+
pub_key = self._priv_key.get_pubkey()
47+
self._scriptPubKey = bytes(CScript([pub_key.get_bytes(), OP_CHECKSIG]))
3648
else:
3749
self._address = ADDRESS_BCRT1_P2WSH_OP_TRUE
3850
self._scriptPubKey = hex_str_to_bytes(self._test_node.validateaddress(self._address)['scriptPubKey'])
@@ -50,6 +62,13 @@ def scan_tx(self, tx):
5062
if out['scriptPubKey']['hex'] == self._scriptPubKey.hex():
5163
self._utxos.append({'txid': tx['txid'], 'vout': out['n'], 'value': out['value']})
5264

65+
def sign_tx(self, tx):
66+
"""Sign tx that has been created by MiniWallet in P2PK mode"""
67+
assert self._priv_key is not None
68+
(sighash, err) = LegacySignatureHash(CScript(self._scriptPubKey), tx, 0, SIGHASH_ALL)
69+
assert err is None
70+
tx.vin[0].scriptSig = CScript([self._priv_key.sign_ecdsa(sighash) + bytes(bytearray([SIGHASH_ALL]))])
71+
5372
def generate(self, num_blocks):
5473
"""Generate blocks with coinbase outputs to the internal address, and append the outputs to the internal list"""
5574
blocks = self._test_node.generatetodescriptor(num_blocks, f'raw({self._scriptPubKey.hex()})')
@@ -99,7 +118,12 @@ def create_self_transfer(self, *, fee_rate=Decimal("0.003"), from_node, utxo_to_
99118
tx.vout = [CTxOut(int(send_value * COIN), self._scriptPubKey)]
100119
if not self._address:
101120
# raw script
102-
tx.vin[0].scriptSig = CScript([OP_NOP] * 35) # pad to identical size
121+
if self._priv_key is not None:
122+
# P2PK, need to sign
123+
self.sign_tx(tx)
124+
else:
125+
# anyone-can-spend
126+
tx.vin[0].scriptSig = CScript([OP_NOP] * 35) # pad to identical size
103127
else:
104128
tx.wit.vtxinwit = [CTxInWitness()]
105129
tx.wit.vtxinwit[0].scriptWitness.stack = [CScript([OP_TRUE])]
@@ -108,7 +132,10 @@ def create_self_transfer(self, *, fee_rate=Decimal("0.003"), from_node, utxo_to_
108132
tx_info = from_node.testmempoolaccept([tx_hex])[0]
109133
assert_equal(mempool_valid, tx_info['allowed'])
110134
if mempool_valid:
111-
assert_equal(tx_info['vsize'], vsize)
135+
# TODO: for P2PK, vsize is not constant due to varying scriptSig length,
136+
# so only check this for anyone-can-spend outputs right now
137+
if self._priv_key is None:
138+
assert_equal(tx_info['vsize'], vsize)
112139
assert_equal(tx_info['fees']['base'], fee)
113140
return {'txid': tx_info['txid'], 'wtxid': tx_info['wtxid'], 'hex': tx_hex, 'tx': tx}
114141

0 commit comments

Comments
 (0)