Skip to content

Commit b5a3289

Browse files
furszytheStack
andcommitted
test: refactor, multiple cleanups in rpc_createmultisig.py
Cleaning up the test in the following ways: * Generate priv-pub key pairs used for testing only once (instead of doing it 4 times). * Simplifies 'wmulti' wallet creation, load and unload process. * Removes confusing class members initialized and updated inside a nested for-loop. * Simplifies do_multisig() outpoint detection: The outpoint index information is already contained in MiniWallet's `send_to` return value dictionary as "sent_vout". Co-authored-by: Sebastian Falbesoner <[email protected]>
1 parent 3635d43 commit b5a3289

File tree

1 file changed

+40
-50
lines changed

1 file changed

+40
-50
lines changed

test/functional/rpc_createmultisig.py

Lines changed: 40 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@
1010

1111
from test_framework.address import address_to_scriptpubkey
1212
from test_framework.blocktools import COINBASE_MATURITY
13-
from test_framework.authproxy import JSONRPCException
1413
from test_framework.descriptors import descsum_create, drop_origins
1514
from test_framework.key import ECPubKey
15+
from test_framework.messages import COIN
1616
from test_framework.test_framework import BitcoinTestFramework
1717
from test_framework.util import (
1818
assert_raises_rpc_error,
@@ -34,19 +34,22 @@ def set_test_params(self):
3434
self.supports_cli = False
3535
self.enable_wallet_if_possible()
3636

37-
def get_keys(self):
37+
def create_keys(self, num_keys):
3838
self.pub = []
3939
self.priv = []
40-
node0, node1, node2 = self.nodes
41-
for _ in range(self.nkeys):
40+
for _ in range(num_keys):
4241
privkey, pubkey = generate_keypair(wif=True)
4342
self.pub.append(pubkey.hex())
4443
self.priv.append(privkey)
4544
if self.is_bdb_compiled():
46-
self.final = node2.getnewaddress()
45+
self.final = self.nodes[2].getnewaddress()
4746
else:
4847
self.final = getnewdestination('bech32')[2]
4948

49+
def create_wallet(self, node, wallet_name):
50+
node.createwallet(wallet_name=wallet_name, disable_private_keys=True)
51+
return node.get_wallet_rpc(wallet_name)
52+
5053
def run_test(self):
5154
node0, node1, node2 = self.nodes
5255
self.wallet = MiniWallet(test_node=node0)
@@ -57,12 +60,15 @@ def run_test(self):
5760
self.log.info('Generating blocks ...')
5861
self.generate(self.wallet, 149)
5962

63+
wallet_multi = self.create_wallet(node1, 'wmulti') if self._requires_wallet else None
6064
self.moved = 0
61-
for self.nkeys in [3, 5]:
62-
for self.nsigs in [2, 3]:
63-
for self.output_type in ["bech32", "p2sh-segwit", "legacy"]:
64-
self.get_keys()
65-
self.do_multisig()
65+
self.create_keys(5)
66+
for nkeys in [3, 5]:
67+
for nsigs in [2, 3]:
68+
for output_type in ["bech32", "p2sh-segwit", "legacy"]:
69+
self.do_multisig(nkeys, nsigs, output_type, wallet_multi)
70+
if wallet_multi is not None:
71+
wallet_multi.unloadwallet()
6672
if self.is_bdb_compiled():
6773
self.checkbalances()
6874

@@ -149,101 +155,85 @@ def checkbalances(self):
149155
assert bal2 == self.moved
150156
assert_equal(bal0 + bal1 + bal2 + balw, total)
151157

152-
def do_multisig(self):
158+
def do_multisig(self, nkeys, nsigs, output_type, wallet_multi):
153159
node0, node1, node2 = self.nodes
154-
155-
if self.is_bdb_compiled():
156-
if 'wmulti' not in node1.listwallets():
157-
try:
158-
node1.loadwallet('wmulti')
159-
except JSONRPCException as e:
160-
path = self.nodes[1].wallets_path / "wmulti"
161-
if e.error['code'] == -18 and "Wallet file verification failed. Failed to load database path '{}'. Path does not exist.".format(path) in e.error['message']:
162-
node1.createwallet(wallet_name='wmulti', disable_private_keys=True)
163-
else:
164-
raise
165-
wmulti = node1.get_wallet_rpc('wmulti')
160+
pub_keys = self.pub[0: nkeys]
161+
priv_keys = self.priv[0: nkeys]
166162

167163
# Construct the expected descriptor
168-
desc = 'multi({},{})'.format(self.nsigs, ','.join(self.pub))
169-
if self.output_type == 'legacy':
164+
desc = 'multi({},{})'.format(nsigs, ','.join(pub_keys))
165+
if output_type == 'legacy':
170166
desc = 'sh({})'.format(desc)
171-
elif self.output_type == 'p2sh-segwit':
167+
elif output_type == 'p2sh-segwit':
172168
desc = 'sh(wsh({}))'.format(desc)
173-
elif self.output_type == 'bech32':
169+
elif output_type == 'bech32':
174170
desc = 'wsh({})'.format(desc)
175171
desc = descsum_create(desc)
176172

177-
msig = node2.createmultisig(self.nsigs, self.pub, self.output_type)
173+
msig = node2.createmultisig(nsigs, pub_keys, output_type)
178174
assert 'warnings' not in msig
179175
madd = msig["address"]
180176
mredeem = msig["redeemScript"]
181177
assert_equal(desc, msig['descriptor'])
182-
if self.output_type == 'bech32':
178+
if output_type == 'bech32':
183179
assert madd[0:4] == "bcrt" # actually a bech32 address
184180

185-
if self.is_bdb_compiled():
181+
if wallet_multi is not None:
186182
# compare against addmultisigaddress
187-
msigw = wmulti.addmultisigaddress(self.nsigs, self.pub, None, self.output_type)
183+
msigw = wallet_multi.addmultisigaddress(nsigs, pub_keys, None, output_type)
188184
maddw = msigw["address"]
189185
mredeemw = msigw["redeemScript"]
190186
assert_equal(desc, drop_origins(msigw['descriptor']))
191187
# addmultisigiaddress and createmultisig work the same
192188
assert maddw == madd
193189
assert mredeemw == mredeem
194-
wmulti.unloadwallet()
195190

196191
spk = address_to_scriptpubkey(madd)
197-
txid = self.wallet.send_to(from_node=self.nodes[0], scriptPubKey=spk, amount=1300)["txid"]
198-
tx = node0.getrawtransaction(txid, True)
199-
vout = [v["n"] for v in tx["vout"] if madd == v["scriptPubKey"]["address"]]
200-
assert len(vout) == 1
201-
vout = vout[0]
202-
scriptPubKey = tx["vout"][vout]["scriptPubKey"]["hex"]
203-
value = tx["vout"][vout]["value"]
204-
prevtxs = [{"txid": txid, "vout": vout, "scriptPubKey": scriptPubKey, "redeemScript": mredeem, "amount": value}]
192+
value = decimal.Decimal("0.00001300")
193+
tx = self.wallet.send_to(from_node=self.nodes[0], scriptPubKey=spk, amount=int(value * COIN))
194+
prevtxs = [{"txid": tx["txid"], "vout": tx["sent_vout"], "scriptPubKey": spk.hex(), "redeemScript": mredeem, "amount": value}]
205195

206196
self.generate(node0, 1)
207197

208198
outval = value - decimal.Decimal("0.00001000")
209-
rawtx = node2.createrawtransaction([{"txid": txid, "vout": vout}], [{self.final: outval}])
199+
rawtx = node2.createrawtransaction([{"txid": tx["txid"], "vout": tx["sent_vout"]}], [{self.final: outval}])
210200

211201
prevtx_err = dict(prevtxs[0])
212202
del prevtx_err["redeemScript"]
213203

214-
assert_raises_rpc_error(-8, "Missing redeemScript/witnessScript", node2.signrawtransactionwithkey, rawtx, self.priv[0:self.nsigs-1], [prevtx_err])
204+
assert_raises_rpc_error(-8, "Missing redeemScript/witnessScript", node2.signrawtransactionwithkey, rawtx, priv_keys[0:nsigs-1], [prevtx_err])
215205

216206
# if witnessScript specified, all ok
217207
prevtx_err["witnessScript"] = prevtxs[0]["redeemScript"]
218-
node2.signrawtransactionwithkey(rawtx, self.priv[0:self.nsigs-1], [prevtx_err])
208+
node2.signrawtransactionwithkey(rawtx, priv_keys[0:nsigs-1], [prevtx_err])
219209

220210
# both specified, also ok
221211
prevtx_err["redeemScript"] = prevtxs[0]["redeemScript"]
222-
node2.signrawtransactionwithkey(rawtx, self.priv[0:self.nsigs-1], [prevtx_err])
212+
node2.signrawtransactionwithkey(rawtx, priv_keys[0:nsigs-1], [prevtx_err])
223213

224214
# redeemScript mismatch to witnessScript
225215
prevtx_err["redeemScript"] = "6a" # OP_RETURN
226-
assert_raises_rpc_error(-8, "redeemScript does not correspond to witnessScript", node2.signrawtransactionwithkey, rawtx, self.priv[0:self.nsigs-1], [prevtx_err])
216+
assert_raises_rpc_error(-8, "redeemScript does not correspond to witnessScript", node2.signrawtransactionwithkey, rawtx, priv_keys[0:nsigs-1], [prevtx_err])
227217

228218
# redeemScript does not match scriptPubKey
229219
del prevtx_err["witnessScript"]
230-
assert_raises_rpc_error(-8, "redeemScript/witnessScript does not match scriptPubKey", node2.signrawtransactionwithkey, rawtx, self.priv[0:self.nsigs-1], [prevtx_err])
220+
assert_raises_rpc_error(-8, "redeemScript/witnessScript does not match scriptPubKey", node2.signrawtransactionwithkey, rawtx, priv_keys[0:nsigs-1], [prevtx_err])
231221

232222
# witnessScript does not match scriptPubKey
233223
prevtx_err["witnessScript"] = prevtx_err["redeemScript"]
234224
del prevtx_err["redeemScript"]
235-
assert_raises_rpc_error(-8, "redeemScript/witnessScript does not match scriptPubKey", node2.signrawtransactionwithkey, rawtx, self.priv[0:self.nsigs-1], [prevtx_err])
225+
assert_raises_rpc_error(-8, "redeemScript/witnessScript does not match scriptPubKey", node2.signrawtransactionwithkey, rawtx, priv_keys[0:nsigs-1], [prevtx_err])
236226

237-
rawtx2 = node2.signrawtransactionwithkey(rawtx, self.priv[0:self.nsigs - 1], prevtxs)
238-
rawtx3 = node2.signrawtransactionwithkey(rawtx2["hex"], [self.priv[-1]], prevtxs)
227+
rawtx2 = node2.signrawtransactionwithkey(rawtx, priv_keys[0:nsigs - 1], prevtxs)
228+
rawtx3 = node2.signrawtransactionwithkey(rawtx2["hex"], [priv_keys[-1]], prevtxs)
239229

240230
self.moved += outval
241231
tx = node0.sendrawtransaction(rawtx3["hex"], 0)
242232
blk = self.generate(node0, 1)[0]
243233
assert tx in node0.getblock(blk)["tx"]
244234

245235
txinfo = node0.getrawtransaction(tx, True, blk)
246-
self.log.info("n/m=%d/%d %s size=%d vsize=%d weight=%d" % (self.nsigs, self.nkeys, self.output_type, txinfo["size"], txinfo["vsize"], txinfo["weight"]))
236+
self.log.info("n/m=%d/%d %s size=%d vsize=%d weight=%d" % (nsigs, nkeys, output_type, txinfo["size"], txinfo["vsize"], txinfo["weight"]))
247237

248238

249239
if __name__ == '__main__':

0 commit comments

Comments
 (0)