Merge #11121: TestNode tidyups
[bitcoinplatinum.git] / test / functional / segwit.py
blob609c592ed3f4c4a9531afba9b0963711053a3f2d
1 #!/usr/bin/env python3
2 # Copyright (c) 2016 The Bitcoin Core developers
3 # Distributed under the MIT software license, see the accompanying
4 # file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 """Test the SegWit changeover logic."""
7 from test_framework.test_framework import BitcoinTestFramework
8 from test_framework.util import *
9 from test_framework.mininode import sha256, CTransaction, CTxIn, COutPoint, CTxOut, COIN, ToHex, FromHex
10 from test_framework.address import script_to_p2sh, key_to_p2pkh
11 from test_framework.script import CScript, OP_HASH160, OP_CHECKSIG, OP_0, hash160, OP_EQUAL, OP_DUP, OP_EQUALVERIFY, OP_1, OP_2, OP_CHECKMULTISIG, OP_TRUE
12 from io import BytesIO
14 NODE_0 = 0
15 NODE_2 = 2
16 WIT_V0 = 0
17 WIT_V1 = 1
19 # Create a scriptPubKey corresponding to either a P2WPKH output for the
20 # given pubkey, or a P2WSH output of a 1-of-1 multisig for the given
21 # pubkey. Returns the hex encoding of the scriptPubKey.
22 def witness_script(use_p2wsh, pubkey):
23 if (use_p2wsh == False):
24 # P2WPKH instead
25 pubkeyhash = hash160(hex_str_to_bytes(pubkey))
26 pkscript = CScript([OP_0, pubkeyhash])
27 else:
28 # 1-of-1 multisig
29 witness_program = CScript([OP_1, hex_str_to_bytes(pubkey), OP_1, OP_CHECKMULTISIG])
30 scripthash = sha256(witness_program)
31 pkscript = CScript([OP_0, scripthash])
32 return bytes_to_hex_str(pkscript)
34 # Return a transaction (in hex) that spends the given utxo to a segwit output,
35 # optionally wrapping the segwit output using P2SH.
36 def create_witnessprogram(use_p2wsh, utxo, pubkey, encode_p2sh, amount):
37 pkscript = hex_str_to_bytes(witness_script(use_p2wsh, pubkey))
38 if (encode_p2sh):
39 p2sh_hash = hash160(pkscript)
40 pkscript = CScript([OP_HASH160, p2sh_hash, OP_EQUAL])
41 tx = CTransaction()
42 tx.vin.append(CTxIn(COutPoint(int(utxo["txid"], 16), utxo["vout"]), b""))
43 tx.vout.append(CTxOut(int(amount*COIN), pkscript))
44 return ToHex(tx)
46 # Create a transaction spending a given utxo to a segwit output corresponding
47 # to the given pubkey: use_p2wsh determines whether to use P2WPKH or P2WSH;
48 # encode_p2sh determines whether to wrap in P2SH.
49 # sign=True will have the given node sign the transaction.
50 # insert_redeem_script will be added to the scriptSig, if given.
51 def send_to_witness(use_p2wsh, node, utxo, pubkey, encode_p2sh, amount, sign=True, insert_redeem_script=""):
52 tx_to_witness = create_witnessprogram(use_p2wsh, utxo, pubkey, encode_p2sh, amount)
53 if (sign):
54 signed = node.signrawtransaction(tx_to_witness)
55 assert("errors" not in signed or len(["errors"]) == 0)
56 return node.sendrawtransaction(signed["hex"])
57 else:
58 if (insert_redeem_script):
59 tx = FromHex(CTransaction(), tx_to_witness)
60 tx.vin[0].scriptSig += CScript([hex_str_to_bytes(insert_redeem_script)])
61 tx_to_witness = ToHex(tx)
63 return node.sendrawtransaction(tx_to_witness)
65 def getutxo(txid):
66 utxo = {}
67 utxo["vout"] = 0
68 utxo["txid"] = txid
69 return utxo
71 def find_unspent(node, min_value):
72 for utxo in node.listunspent():
73 if utxo['amount'] >= min_value:
74 return utxo
76 class SegWitTest(BitcoinTestFramework):
77 def set_test_params(self):
78 self.setup_clean_chain = True
79 self.num_nodes = 3
80 self.extra_args = [["-walletprematurewitness", "-rpcserialversion=0"],
81 ["-blockversion=4", "-promiscuousmempoolflags=517", "-prematurewitness", "-walletprematurewitness", "-rpcserialversion=1"],
82 ["-blockversion=536870915", "-promiscuousmempoolflags=517", "-prematurewitness", "-walletprematurewitness"]]
84 def setup_network(self):
85 super().setup_network()
86 connect_nodes(self.nodes[0], 2)
87 self.sync_all()
89 def success_mine(self, node, txid, sign, redeem_script=""):
90 send_to_witness(1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
91 block = node.generate(1)
92 assert_equal(len(node.getblock(block[0])["tx"]), 2)
93 sync_blocks(self.nodes)
95 def skip_mine(self, node, txid, sign, redeem_script=""):
96 send_to_witness(1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
97 block = node.generate(1)
98 assert_equal(len(node.getblock(block[0])["tx"]), 1)
99 sync_blocks(self.nodes)
101 def fail_accept(self, node, error_msg, txid, sign, redeem_script=""):
102 assert_raises_jsonrpc(-26, error_msg, send_to_witness, 1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
104 def fail_mine(self, node, txid, sign, redeem_script=""):
105 send_to_witness(1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
106 assert_raises_jsonrpc(-1, "CreateNewBlock: TestBlockValidity failed", node.generate, 1)
107 sync_blocks(self.nodes)
109 def run_test(self):
110 self.nodes[0].generate(161) #block 161
112 self.log.info("Verify sigops are counted in GBT with pre-BIP141 rules before the fork")
113 txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1)
114 tmpl = self.nodes[0].getblocktemplate({})
115 assert(tmpl['sizelimit'] == 1000000)
116 assert('weightlimit' not in tmpl)
117 assert(tmpl['sigoplimit'] == 20000)
118 assert(tmpl['transactions'][0]['hash'] == txid)
119 assert(tmpl['transactions'][0]['sigops'] == 2)
120 tmpl = self.nodes[0].getblocktemplate({'rules':['segwit']})
121 assert(tmpl['sizelimit'] == 1000000)
122 assert('weightlimit' not in tmpl)
123 assert(tmpl['sigoplimit'] == 20000)
124 assert(tmpl['transactions'][0]['hash'] == txid)
125 assert(tmpl['transactions'][0]['sigops'] == 2)
126 self.nodes[0].generate(1) #block 162
128 balance_presetup = self.nodes[0].getbalance()
129 self.pubkey = []
130 p2sh_ids = [] # p2sh_ids[NODE][VER] is an array of txids that spend to a witness version VER pkscript to an address for NODE embedded in p2sh
131 wit_ids = [] # wit_ids[NODE][VER] is an array of txids that spend to a witness version VER pkscript to an address for NODE via bare witness
132 for i in range(3):
133 newaddress = self.nodes[i].getnewaddress()
134 self.pubkey.append(self.nodes[i].validateaddress(newaddress)["pubkey"])
135 multiaddress = self.nodes[i].addmultisigaddress(1, [self.pubkey[-1]])
136 self.nodes[i].addwitnessaddress(newaddress)
137 self.nodes[i].addwitnessaddress(multiaddress)
138 p2sh_ids.append([])
139 wit_ids.append([])
140 for v in range(2):
141 p2sh_ids[i].append([])
142 wit_ids[i].append([])
144 for i in range(5):
145 for n in range(3):
146 for v in range(2):
147 wit_ids[n][v].append(send_to_witness(v, self.nodes[0], find_unspent(self.nodes[0], 50), self.pubkey[n], False, Decimal("49.999")))
148 p2sh_ids[n][v].append(send_to_witness(v, self.nodes[0], find_unspent(self.nodes[0], 50), self.pubkey[n], True, Decimal("49.999")))
150 self.nodes[0].generate(1) #block 163
151 sync_blocks(self.nodes)
153 # Make sure all nodes recognize the transactions as theirs
154 assert_equal(self.nodes[0].getbalance(), balance_presetup - 60*50 + 20*Decimal("49.999") + 50)
155 assert_equal(self.nodes[1].getbalance(), 20*Decimal("49.999"))
156 assert_equal(self.nodes[2].getbalance(), 20*Decimal("49.999"))
158 self.nodes[0].generate(260) #block 423
159 sync_blocks(self.nodes)
161 self.log.info("Verify default node can't accept any witness format txs before fork")
162 # unsigned, no scriptsig
163 self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", wit_ids[NODE_0][WIT_V0][0], False)
164 self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", wit_ids[NODE_0][WIT_V1][0], False)
165 self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", p2sh_ids[NODE_0][WIT_V0][0], False)
166 self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", p2sh_ids[NODE_0][WIT_V1][0], False)
167 # unsigned with redeem script
168 self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", p2sh_ids[NODE_0][WIT_V0][0], False, witness_script(False, self.pubkey[0]))
169 self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", p2sh_ids[NODE_0][WIT_V1][0], False, witness_script(True, self.pubkey[0]))
170 # signed
171 self.fail_accept(self.nodes[0], "no-witness-yet", wit_ids[NODE_0][WIT_V0][0], True)
172 self.fail_accept(self.nodes[0], "no-witness-yet", wit_ids[NODE_0][WIT_V1][0], True)
173 self.fail_accept(self.nodes[0], "no-witness-yet", p2sh_ids[NODE_0][WIT_V0][0], True)
174 self.fail_accept(self.nodes[0], "no-witness-yet", p2sh_ids[NODE_0][WIT_V1][0], True)
176 self.log.info("Verify witness txs are skipped for mining before the fork")
177 self.skip_mine(self.nodes[2], wit_ids[NODE_2][WIT_V0][0], True) #block 424
178 self.skip_mine(self.nodes[2], wit_ids[NODE_2][WIT_V1][0], True) #block 425
179 self.skip_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V0][0], True) #block 426
180 self.skip_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V1][0], True) #block 427
182 # TODO: An old node would see these txs without witnesses and be able to mine them
184 self.log.info("Verify unsigned bare witness txs in versionbits-setting blocks are valid before the fork")
185 self.success_mine(self.nodes[2], wit_ids[NODE_2][WIT_V0][1], False) #block 428
186 self.success_mine(self.nodes[2], wit_ids[NODE_2][WIT_V1][1], False) #block 429
188 self.log.info("Verify unsigned p2sh witness txs without a redeem script are invalid")
189 self.fail_accept(self.nodes[2], "mandatory-script-verify-flag", p2sh_ids[NODE_2][WIT_V0][1], False)
190 self.fail_accept(self.nodes[2], "mandatory-script-verify-flag", p2sh_ids[NODE_2][WIT_V1][1], False)
192 self.log.info("Verify unsigned p2sh witness txs with a redeem script in versionbits-settings blocks are valid before the fork")
193 self.success_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V0][1], False, witness_script(False, self.pubkey[2])) #block 430
194 self.success_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V1][1], False, witness_script(True, self.pubkey[2])) #block 431
196 self.log.info("Verify previous witness txs skipped for mining can now be mined")
197 assert_equal(len(self.nodes[2].getrawmempool()), 4)
198 block = self.nodes[2].generate(1) #block 432 (first block with new rules; 432 = 144 * 3)
199 sync_blocks(self.nodes)
200 assert_equal(len(self.nodes[2].getrawmempool()), 0)
201 segwit_tx_list = self.nodes[2].getblock(block[0])["tx"]
202 assert_equal(len(segwit_tx_list), 5)
204 self.log.info("Verify block and transaction serialization rpcs return differing serializations depending on rpc serialization flag")
205 assert(self.nodes[2].getblock(block[0], False) != self.nodes[0].getblock(block[0], False))
206 assert(self.nodes[1].getblock(block[0], False) == self.nodes[2].getblock(block[0], False))
207 for i in range(len(segwit_tx_list)):
208 tx = FromHex(CTransaction(), self.nodes[2].gettransaction(segwit_tx_list[i])["hex"])
209 assert(self.nodes[2].getrawtransaction(segwit_tx_list[i]) != self.nodes[0].getrawtransaction(segwit_tx_list[i]))
210 assert(self.nodes[1].getrawtransaction(segwit_tx_list[i], 0) == self.nodes[2].getrawtransaction(segwit_tx_list[i]))
211 assert(self.nodes[0].getrawtransaction(segwit_tx_list[i]) != self.nodes[2].gettransaction(segwit_tx_list[i])["hex"])
212 assert(self.nodes[1].getrawtransaction(segwit_tx_list[i]) == self.nodes[2].gettransaction(segwit_tx_list[i])["hex"])
213 assert(self.nodes[0].getrawtransaction(segwit_tx_list[i]) == bytes_to_hex_str(tx.serialize_without_witness()))
215 self.log.info("Verify witness txs without witness data are invalid after the fork")
216 self.fail_mine(self.nodes[2], wit_ids[NODE_2][WIT_V0][2], False)
217 self.fail_mine(self.nodes[2], wit_ids[NODE_2][WIT_V1][2], False)
218 self.fail_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V0][2], False, witness_script(False, self.pubkey[2]))
219 self.fail_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V1][2], False, witness_script(True, self.pubkey[2]))
221 self.log.info("Verify default node can now use witness txs")
222 self.success_mine(self.nodes[0], wit_ids[NODE_0][WIT_V0][0], True) #block 432
223 self.success_mine(self.nodes[0], wit_ids[NODE_0][WIT_V1][0], True) #block 433
224 self.success_mine(self.nodes[0], p2sh_ids[NODE_0][WIT_V0][0], True) #block 434
225 self.success_mine(self.nodes[0], p2sh_ids[NODE_0][WIT_V1][0], True) #block 435
227 self.log.info("Verify sigops are counted in GBT with BIP141 rules after the fork")
228 txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1)
229 tmpl = self.nodes[0].getblocktemplate({'rules':['segwit']})
230 assert(tmpl['sizelimit'] >= 3999577) # actual maximum size is lower due to minimum mandatory non-witness data
231 assert(tmpl['weightlimit'] == 4000000)
232 assert(tmpl['sigoplimit'] == 80000)
233 assert(tmpl['transactions'][0]['txid'] == txid)
234 assert(tmpl['transactions'][0]['sigops'] == 8)
236 self.nodes[0].generate(1) # Mine a block to clear the gbt cache
238 self.log.info("Non-segwit miners are able to use GBT response after activation.")
239 # Create a 3-tx chain: tx1 (non-segwit input, paying to a segwit output) ->
240 # tx2 (segwit input, paying to a non-segwit output) ->
241 # tx3 (non-segwit input, paying to a non-segwit output).
242 # tx1 is allowed to appear in the block, but no others.
243 txid1 = send_to_witness(1, self.nodes[0], find_unspent(self.nodes[0], 50), self.pubkey[0], False, Decimal("49.996"))
244 hex_tx = self.nodes[0].gettransaction(txid)['hex']
245 tx = FromHex(CTransaction(), hex_tx)
246 assert(tx.wit.is_null()) # This should not be a segwit input
247 assert(txid1 in self.nodes[0].getrawmempool())
249 # Now create tx2, which will spend from txid1.
250 tx = CTransaction()
251 tx.vin.append(CTxIn(COutPoint(int(txid1, 16), 0), b''))
252 tx.vout.append(CTxOut(int(49.99*COIN), CScript([OP_TRUE])))
253 tx2_hex = self.nodes[0].signrawtransaction(ToHex(tx))['hex']
254 txid2 = self.nodes[0].sendrawtransaction(tx2_hex)
255 tx = FromHex(CTransaction(), tx2_hex)
256 assert(not tx.wit.is_null())
258 # Now create tx3, which will spend from txid2
259 tx = CTransaction()
260 tx.vin.append(CTxIn(COutPoint(int(txid2, 16), 0), b""))
261 tx.vout.append(CTxOut(int(49.95*COIN), CScript([OP_TRUE]))) # Huge fee
262 tx.calc_sha256()
263 txid3 = self.nodes[0].sendrawtransaction(ToHex(tx))
264 assert(tx.wit.is_null())
265 assert(txid3 in self.nodes[0].getrawmempool())
267 # Now try calling getblocktemplate() without segwit support.
268 template = self.nodes[0].getblocktemplate()
270 # Check that tx1 is the only transaction of the 3 in the template.
271 template_txids = [ t['txid'] for t in template['transactions'] ]
272 assert(txid2 not in template_txids and txid3 not in template_txids)
273 assert(txid1 in template_txids)
275 # Check that running with segwit support results in all 3 being included.
276 template = self.nodes[0].getblocktemplate({"rules": ["segwit"]})
277 template_txids = [ t['txid'] for t in template['transactions'] ]
278 assert(txid1 in template_txids)
279 assert(txid2 in template_txids)
280 assert(txid3 in template_txids)
282 # Mine a block to clear the gbt cache again.
283 self.nodes[0].generate(1)
285 self.log.info("Verify behaviour of importaddress, addwitnessaddress and listunspent")
287 # Some public keys to be used later
288 pubkeys = [
289 "0363D44AABD0F1699138239DF2F042C3282C0671CC7A76826A55C8203D90E39242", # cPiM8Ub4heR9NBYmgVzJQiUH1if44GSBGiqaeJySuL2BKxubvgwb
290 "02D3E626B3E616FC8662B489C123349FECBFC611E778E5BE739B257EAE4721E5BF", # cPpAdHaD6VoYbW78kveN2bsvb45Q7G5PhaPApVUGwvF8VQ9brD97
291 "04A47F2CBCEFFA7B9BCDA184E7D5668D3DA6F9079AD41E422FA5FD7B2D458F2538A62F5BD8EC85C2477F39650BD391EA6250207065B2A81DA8B009FC891E898F0E", # 91zqCU5B9sdWxzMt1ca3VzbtVm2YM6Hi5Rxn4UDtxEaN9C9nzXV
292 "02A47F2CBCEFFA7B9BCDA184E7D5668D3DA6F9079AD41E422FA5FD7B2D458F2538", # cPQFjcVRpAUBG8BA9hzr2yEzHwKoMgLkJZBBtK9vJnvGJgMjzTbd
293 "036722F784214129FEB9E8129D626324F3F6716555B603FFE8300BBCB882151228", # cQGtcm34xiLjB1v7bkRa4V3aAc9tS2UTuBZ1UnZGeSeNy627fN66
294 "0266A8396EE936BF6D99D17920DB21C6C7B1AB14C639D5CD72B300297E416FD2EC", # cTW5mR5M45vHxXkeChZdtSPozrFwFgmEvTNnanCW6wrqwaCZ1X7K
295 "0450A38BD7F0AC212FEBA77354A9B036A32E0F7C81FC4E0C5ADCA7C549C4505D2522458C2D9AE3CEFD684E039194B72C8A10F9CB9D4764AB26FCC2718D421D3B84", # 92h2XPssjBpsJN5CqSP7v9a7cf2kgDunBC6PDFwJHMACM1rrVBJ
298 # Import a compressed key and an uncompressed key, generate some multisig addresses
299 self.nodes[0].importprivkey("92e6XLo5jVAVwrQKPNTs93oQco8f8sDNBcpv73Dsrs397fQtFQn")
300 uncompressed_spendable_address = ["mvozP4UwyGD2mGZU4D2eMvMLPB9WkMmMQu"]
301 self.nodes[0].importprivkey("cNC8eQ5dg3mFAVePDX4ddmPYpPbw41r9bm2jd1nLJT77e6RrzTRR")
302 compressed_spendable_address = ["mmWQubrDomqpgSYekvsU7HWEVjLFHAakLe"]
303 assert ((self.nodes[0].validateaddress(uncompressed_spendable_address[0])['iscompressed'] == False))
304 assert ((self.nodes[0].validateaddress(compressed_spendable_address[0])['iscompressed'] == True))
306 self.nodes[0].importpubkey(pubkeys[0])
307 compressed_solvable_address = [key_to_p2pkh(pubkeys[0])]
308 self.nodes[0].importpubkey(pubkeys[1])
309 compressed_solvable_address.append(key_to_p2pkh(pubkeys[1]))
310 self.nodes[0].importpubkey(pubkeys[2])
311 uncompressed_solvable_address = [key_to_p2pkh(pubkeys[2])]
313 spendable_anytime = [] # These outputs should be seen anytime after importprivkey and addmultisigaddress
314 spendable_after_importaddress = [] # These outputs should be seen after importaddress
315 solvable_after_importaddress = [] # These outputs should be seen after importaddress but not spendable
316 unsolvable_after_importaddress = [] # These outputs should be unsolvable after importaddress
317 solvable_anytime = [] # These outputs should be solvable after importpubkey
318 unseen_anytime = [] # These outputs should never be seen
320 uncompressed_spendable_address.append(self.nodes[0].addmultisigaddress(2, [uncompressed_spendable_address[0], compressed_spendable_address[0]]))
321 uncompressed_spendable_address.append(self.nodes[0].addmultisigaddress(2, [uncompressed_spendable_address[0], uncompressed_spendable_address[0]]))
322 compressed_spendable_address.append(self.nodes[0].addmultisigaddress(2, [compressed_spendable_address[0], compressed_spendable_address[0]]))
323 uncompressed_solvable_address.append(self.nodes[0].addmultisigaddress(2, [compressed_spendable_address[0], uncompressed_solvable_address[0]]))
324 compressed_solvable_address.append(self.nodes[0].addmultisigaddress(2, [compressed_spendable_address[0], compressed_solvable_address[0]]))
325 compressed_solvable_address.append(self.nodes[0].addmultisigaddress(2, [compressed_solvable_address[0], compressed_solvable_address[1]]))
326 unknown_address = ["mtKKyoHabkk6e4ppT7NaM7THqPUt7AzPrT", "2NDP3jLWAFT8NDAiUa9qiE6oBt2awmMq7Dx"]
328 # Test multisig_without_privkey
329 # We have 2 public keys without private keys, use addmultisigaddress to add to wallet.
330 # Money sent to P2SH of multisig of this should only be seen after importaddress with the BASE58 P2SH address.
332 multisig_without_privkey_address = self.nodes[0].addmultisigaddress(2, [pubkeys[3], pubkeys[4]])
333 script = CScript([OP_2, hex_str_to_bytes(pubkeys[3]), hex_str_to_bytes(pubkeys[4]), OP_2, OP_CHECKMULTISIG])
334 solvable_after_importaddress.append(CScript([OP_HASH160, hash160(script), OP_EQUAL]))
336 for i in compressed_spendable_address:
337 v = self.nodes[0].validateaddress(i)
338 if (v['isscript']):
339 [bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
340 # bare and p2sh multisig with compressed keys should always be spendable
341 spendable_anytime.extend([bare, p2sh])
342 # P2WSH and P2SH(P2WSH) multisig with compressed keys are spendable after direct importaddress
343 spendable_after_importaddress.extend([p2wsh, p2sh_p2wsh])
344 else:
345 [p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh] = self.p2pkh_address_to_script(v)
346 # normal P2PKH and P2PK with compressed keys should always be spendable
347 spendable_anytime.extend([p2pkh, p2pk])
348 # P2SH_P2PK, P2SH_P2PKH, and witness with compressed keys are spendable after direct importaddress
349 spendable_after_importaddress.extend([p2wpkh, p2sh_p2wpkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh])
351 for i in uncompressed_spendable_address:
352 v = self.nodes[0].validateaddress(i)
353 if (v['isscript']):
354 [bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
355 # bare and p2sh multisig with uncompressed keys should always be spendable
356 spendable_anytime.extend([bare, p2sh])
357 # P2WSH and P2SH(P2WSH) multisig with uncompressed keys are never seen
358 unseen_anytime.extend([p2wsh, p2sh_p2wsh])
359 else:
360 [p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh] = self.p2pkh_address_to_script(v)
361 # normal P2PKH and P2PK with uncompressed keys should always be spendable
362 spendable_anytime.extend([p2pkh, p2pk])
363 # P2SH_P2PK and P2SH_P2PKH are spendable after direct importaddress
364 spendable_after_importaddress.extend([p2sh_p2pk, p2sh_p2pkh])
365 # witness with uncompressed keys are never seen
366 unseen_anytime.extend([p2wpkh, p2sh_p2wpkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh])
368 for i in compressed_solvable_address:
369 v = self.nodes[0].validateaddress(i)
370 if (v['isscript']):
371 # Multisig without private is not seen after addmultisigaddress, but seen after importaddress
372 [bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
373 solvable_after_importaddress.extend([bare, p2sh, p2wsh, p2sh_p2wsh])
374 else:
375 [p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh] = self.p2pkh_address_to_script(v)
376 # normal P2PKH and P2PK with compressed keys should always be seen
377 solvable_anytime.extend([p2pkh, p2pk])
378 # P2SH_P2PK, P2SH_P2PKH, and witness with compressed keys are seen after direct importaddress
379 solvable_after_importaddress.extend([p2wpkh, p2sh_p2wpkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh])
381 for i in uncompressed_solvable_address:
382 v = self.nodes[0].validateaddress(i)
383 if (v['isscript']):
384 [bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
385 # Base uncompressed multisig without private is not seen after addmultisigaddress, but seen after importaddress
386 solvable_after_importaddress.extend([bare, p2sh])
387 # P2WSH and P2SH(P2WSH) multisig with uncompressed keys are never seen
388 unseen_anytime.extend([p2wsh, p2sh_p2wsh])
389 else:
390 [p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh] = self.p2pkh_address_to_script(v)
391 # normal P2PKH and P2PK with uncompressed keys should always be seen
392 solvable_anytime.extend([p2pkh, p2pk])
393 # P2SH_P2PK, P2SH_P2PKH with uncompressed keys are seen after direct importaddress
394 solvable_after_importaddress.extend([p2sh_p2pk, p2sh_p2pkh])
395 # witness with uncompressed keys are never seen
396 unseen_anytime.extend([p2wpkh, p2sh_p2wpkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh])
398 op1 = CScript([OP_1])
399 op0 = CScript([OP_0])
400 # 2N7MGY19ti4KDMSzRfPAssP6Pxyuxoi6jLe is the P2SH(P2PKH) version of mjoE3sSrb8ByYEvgnC3Aox86u1CHnfJA4V
401 unsolvable_address = ["mjoE3sSrb8ByYEvgnC3Aox86u1CHnfJA4V", "2N7MGY19ti4KDMSzRfPAssP6Pxyuxoi6jLe", script_to_p2sh(op1), script_to_p2sh(op0)]
402 unsolvable_address_key = hex_str_to_bytes("02341AEC7587A51CDE5279E0630A531AEA2615A9F80B17E8D9376327BAEAA59E3D")
403 unsolvablep2pkh = CScript([OP_DUP, OP_HASH160, hash160(unsolvable_address_key), OP_EQUALVERIFY, OP_CHECKSIG])
404 unsolvablep2wshp2pkh = CScript([OP_0, sha256(unsolvablep2pkh)])
405 p2shop0 = CScript([OP_HASH160, hash160(op0), OP_EQUAL])
406 p2wshop1 = CScript([OP_0, sha256(op1)])
407 unsolvable_after_importaddress.append(unsolvablep2pkh)
408 unsolvable_after_importaddress.append(unsolvablep2wshp2pkh)
409 unsolvable_after_importaddress.append(op1) # OP_1 will be imported as script
410 unsolvable_after_importaddress.append(p2wshop1)
411 unseen_anytime.append(op0) # OP_0 will be imported as P2SH address with no script provided
412 unsolvable_after_importaddress.append(p2shop0)
414 spendable_txid = []
415 solvable_txid = []
416 spendable_txid.append(self.mine_and_test_listunspent(spendable_anytime, 2))
417 solvable_txid.append(self.mine_and_test_listunspent(solvable_anytime, 1))
418 self.mine_and_test_listunspent(spendable_after_importaddress + solvable_after_importaddress + unseen_anytime + unsolvable_after_importaddress, 0)
420 importlist = []
421 for i in compressed_spendable_address + uncompressed_spendable_address + compressed_solvable_address + uncompressed_solvable_address:
422 v = self.nodes[0].validateaddress(i)
423 if (v['isscript']):
424 bare = hex_str_to_bytes(v['hex'])
425 importlist.append(bytes_to_hex_str(bare))
426 importlist.append(bytes_to_hex_str(CScript([OP_0, sha256(bare)])))
427 else:
428 pubkey = hex_str_to_bytes(v['pubkey'])
429 p2pk = CScript([pubkey, OP_CHECKSIG])
430 p2pkh = CScript([OP_DUP, OP_HASH160, hash160(pubkey), OP_EQUALVERIFY, OP_CHECKSIG])
431 importlist.append(bytes_to_hex_str(p2pk))
432 importlist.append(bytes_to_hex_str(p2pkh))
433 importlist.append(bytes_to_hex_str(CScript([OP_0, hash160(pubkey)])))
434 importlist.append(bytes_to_hex_str(CScript([OP_0, sha256(p2pk)])))
435 importlist.append(bytes_to_hex_str(CScript([OP_0, sha256(p2pkh)])))
437 importlist.append(bytes_to_hex_str(unsolvablep2pkh))
438 importlist.append(bytes_to_hex_str(unsolvablep2wshp2pkh))
439 importlist.append(bytes_to_hex_str(op1))
440 importlist.append(bytes_to_hex_str(p2wshop1))
442 for i in importlist:
443 # import all generated addresses. The wallet already has the private keys for some of these, so catch JSON RPC
444 # exceptions and continue.
445 try:
446 self.nodes[0].importaddress(i,"",False,True)
447 except JSONRPCException as exp:
448 assert_equal(exp.error["message"], "The wallet already contains the private key for this address or script")
449 assert_equal(exp.error["code"], -4)
451 self.nodes[0].importaddress(script_to_p2sh(op0)) # import OP_0 as address only
452 self.nodes[0].importaddress(multisig_without_privkey_address) # Test multisig_without_privkey
454 spendable_txid.append(self.mine_and_test_listunspent(spendable_anytime + spendable_after_importaddress, 2))
455 solvable_txid.append(self.mine_and_test_listunspent(solvable_anytime + solvable_after_importaddress, 1))
456 self.mine_and_test_listunspent(unsolvable_after_importaddress, 1)
457 self.mine_and_test_listunspent(unseen_anytime, 0)
459 # addwitnessaddress should refuse to return a witness address if an uncompressed key is used
460 # note that no witness address should be returned by unsolvable addresses
461 for i in uncompressed_spendable_address + uncompressed_solvable_address + unknown_address + unsolvable_address:
462 assert_raises_jsonrpc(-4, "Public key or redeemscript not known to wallet, or the key is uncompressed", self.nodes[0].addwitnessaddress, i)
464 # addwitnessaddress should return a witness addresses even if keys are not in the wallet
465 self.nodes[0].addwitnessaddress(multisig_without_privkey_address)
467 for i in compressed_spendable_address + compressed_solvable_address:
468 witaddress = self.nodes[0].addwitnessaddress(i)
469 # addwitnessaddress should return the same address if it is a known P2SH-witness address
470 assert_equal(witaddress, self.nodes[0].addwitnessaddress(witaddress))
472 spendable_txid.append(self.mine_and_test_listunspent(spendable_anytime + spendable_after_importaddress, 2))
473 solvable_txid.append(self.mine_and_test_listunspent(solvable_anytime + solvable_after_importaddress, 1))
474 self.mine_and_test_listunspent(unsolvable_after_importaddress, 1)
475 self.mine_and_test_listunspent(unseen_anytime, 0)
477 # Repeat some tests. This time we don't add witness scripts with importaddress
478 # Import a compressed key and an uncompressed key, generate some multisig addresses
479 self.nodes[0].importprivkey("927pw6RW8ZekycnXqBQ2JS5nPyo1yRfGNN8oq74HeddWSpafDJH")
480 uncompressed_spendable_address = ["mguN2vNSCEUh6rJaXoAVwY3YZwZvEmf5xi"]
481 self.nodes[0].importprivkey("cMcrXaaUC48ZKpcyydfFo8PxHAjpsYLhdsp6nmtB3E2ER9UUHWnw")
482 compressed_spendable_address = ["n1UNmpmbVUJ9ytXYXiurmGPQ3TRrXqPWKL"]
484 self.nodes[0].importpubkey(pubkeys[5])
485 compressed_solvable_address = [key_to_p2pkh(pubkeys[5])]
486 self.nodes[0].importpubkey(pubkeys[6])
487 uncompressed_solvable_address = [key_to_p2pkh(pubkeys[6])]
489 spendable_after_addwitnessaddress = [] # These outputs should be seen after importaddress
490 solvable_after_addwitnessaddress=[] # These outputs should be seen after importaddress but not spendable
491 unseen_anytime = [] # These outputs should never be seen
493 uncompressed_spendable_address.append(self.nodes[0].addmultisigaddress(2, [uncompressed_spendable_address[0], compressed_spendable_address[0]]))
494 uncompressed_spendable_address.append(self.nodes[0].addmultisigaddress(2, [uncompressed_spendable_address[0], uncompressed_spendable_address[0]]))
495 compressed_spendable_address.append(self.nodes[0].addmultisigaddress(2, [compressed_spendable_address[0], compressed_spendable_address[0]]))
496 uncompressed_solvable_address.append(self.nodes[0].addmultisigaddress(2, [compressed_solvable_address[0], uncompressed_solvable_address[0]]))
497 compressed_solvable_address.append(self.nodes[0].addmultisigaddress(2, [compressed_spendable_address[0], compressed_solvable_address[0]]))
499 premature_witaddress = []
501 for i in compressed_spendable_address:
502 v = self.nodes[0].validateaddress(i)
503 if (v['isscript']):
504 [bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
505 # P2WSH and P2SH(P2WSH) multisig with compressed keys are spendable after addwitnessaddress
506 spendable_after_addwitnessaddress.extend([p2wsh, p2sh_p2wsh])
507 premature_witaddress.append(script_to_p2sh(p2wsh))
508 else:
509 [p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh] = self.p2pkh_address_to_script(v)
510 # P2WPKH, P2SH_P2WPKH are spendable after addwitnessaddress
511 spendable_after_addwitnessaddress.extend([p2wpkh, p2sh_p2wpkh])
512 premature_witaddress.append(script_to_p2sh(p2wpkh))
514 for i in uncompressed_spendable_address + uncompressed_solvable_address:
515 v = self.nodes[0].validateaddress(i)
516 if (v['isscript']):
517 [bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
518 # P2WSH and P2SH(P2WSH) multisig with uncompressed keys are never seen
519 unseen_anytime.extend([p2wsh, p2sh_p2wsh])
520 else:
521 [p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh] = self.p2pkh_address_to_script(v)
522 # P2WPKH, P2SH_P2WPKH with uncompressed keys are never seen
523 unseen_anytime.extend([p2wpkh, p2sh_p2wpkh])
525 for i in compressed_solvable_address:
526 v = self.nodes[0].validateaddress(i)
527 if (v['isscript']):
528 # P2WSH multisig without private key are seen after addwitnessaddress
529 [bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
530 solvable_after_addwitnessaddress.extend([p2wsh, p2sh_p2wsh])
531 premature_witaddress.append(script_to_p2sh(p2wsh))
532 else:
533 [p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh] = self.p2pkh_address_to_script(v)
534 # P2SH_P2PK, P2SH_P2PKH with compressed keys are seen after addwitnessaddress
535 solvable_after_addwitnessaddress.extend([p2wpkh, p2sh_p2wpkh])
536 premature_witaddress.append(script_to_p2sh(p2wpkh))
538 self.mine_and_test_listunspent(spendable_after_addwitnessaddress + solvable_after_addwitnessaddress + unseen_anytime, 0)
540 # addwitnessaddress should refuse to return a witness address if an uncompressed key is used
541 # note that a multisig address returned by addmultisigaddress is not solvable until it is added with importaddress
542 # premature_witaddress are not accepted until the script is added with addwitnessaddress first
543 for i in uncompressed_spendable_address + uncompressed_solvable_address + premature_witaddress:
544 # This will raise an exception
545 assert_raises_jsonrpc(-4, "Public key or redeemscript not known to wallet, or the key is uncompressed", self.nodes[0].addwitnessaddress, i)
547 # after importaddress it should pass addwitnessaddress
548 v = self.nodes[0].validateaddress(compressed_solvable_address[1])
549 self.nodes[0].importaddress(v['hex'],"",False,True)
550 for i in compressed_spendable_address + compressed_solvable_address + premature_witaddress:
551 witaddress = self.nodes[0].addwitnessaddress(i)
552 assert_equal(witaddress, self.nodes[0].addwitnessaddress(witaddress))
554 spendable_txid.append(self.mine_and_test_listunspent(spendable_after_addwitnessaddress, 2))
555 solvable_txid.append(self.mine_and_test_listunspent(solvable_after_addwitnessaddress, 1))
556 self.mine_and_test_listunspent(unseen_anytime, 0)
558 # Check that spendable outputs are really spendable
559 self.create_and_mine_tx_from_txids(spendable_txid)
561 # import all the private keys so solvable addresses become spendable
562 self.nodes[0].importprivkey("cPiM8Ub4heR9NBYmgVzJQiUH1if44GSBGiqaeJySuL2BKxubvgwb")
563 self.nodes[0].importprivkey("cPpAdHaD6VoYbW78kveN2bsvb45Q7G5PhaPApVUGwvF8VQ9brD97")
564 self.nodes[0].importprivkey("91zqCU5B9sdWxzMt1ca3VzbtVm2YM6Hi5Rxn4UDtxEaN9C9nzXV")
565 self.nodes[0].importprivkey("cPQFjcVRpAUBG8BA9hzr2yEzHwKoMgLkJZBBtK9vJnvGJgMjzTbd")
566 self.nodes[0].importprivkey("cQGtcm34xiLjB1v7bkRa4V3aAc9tS2UTuBZ1UnZGeSeNy627fN66")
567 self.nodes[0].importprivkey("cTW5mR5M45vHxXkeChZdtSPozrFwFgmEvTNnanCW6wrqwaCZ1X7K")
568 self.create_and_mine_tx_from_txids(solvable_txid)
570 def mine_and_test_listunspent(self, script_list, ismine):
571 utxo = find_unspent(self.nodes[0], 50)
572 tx = CTransaction()
573 tx.vin.append(CTxIn(COutPoint(int('0x'+utxo['txid'],0), utxo['vout'])))
574 for i in script_list:
575 tx.vout.append(CTxOut(10000000, i))
576 tx.rehash()
577 signresults = self.nodes[0].signrawtransaction(bytes_to_hex_str(tx.serialize_without_witness()))['hex']
578 txid = self.nodes[0].sendrawtransaction(signresults, True)
579 self.nodes[0].generate(1)
580 sync_blocks(self.nodes)
581 watchcount = 0
582 spendcount = 0
583 for i in self.nodes[0].listunspent():
584 if (i['txid'] == txid):
585 watchcount += 1
586 if (i['spendable'] == True):
587 spendcount += 1
588 if (ismine == 2):
589 assert_equal(spendcount, len(script_list))
590 elif (ismine == 1):
591 assert_equal(watchcount, len(script_list))
592 assert_equal(spendcount, 0)
593 else:
594 assert_equal(watchcount, 0)
595 return txid
597 def p2sh_address_to_script(self,v):
598 bare = CScript(hex_str_to_bytes(v['hex']))
599 p2sh = CScript(hex_str_to_bytes(v['scriptPubKey']))
600 p2wsh = CScript([OP_0, sha256(bare)])
601 p2sh_p2wsh = CScript([OP_HASH160, hash160(p2wsh), OP_EQUAL])
602 return([bare, p2sh, p2wsh, p2sh_p2wsh])
604 def p2pkh_address_to_script(self,v):
605 pubkey = hex_str_to_bytes(v['pubkey'])
606 p2wpkh = CScript([OP_0, hash160(pubkey)])
607 p2sh_p2wpkh = CScript([OP_HASH160, hash160(p2wpkh), OP_EQUAL])
608 p2pk = CScript([pubkey, OP_CHECKSIG])
609 p2pkh = CScript(hex_str_to_bytes(v['scriptPubKey']))
610 p2sh_p2pk = CScript([OP_HASH160, hash160(p2pk), OP_EQUAL])
611 p2sh_p2pkh = CScript([OP_HASH160, hash160(p2pkh), OP_EQUAL])
612 p2wsh_p2pk = CScript([OP_0, sha256(p2pk)])
613 p2wsh_p2pkh = CScript([OP_0, sha256(p2pkh)])
614 p2sh_p2wsh_p2pk = CScript([OP_HASH160, hash160(p2wsh_p2pk), OP_EQUAL])
615 p2sh_p2wsh_p2pkh = CScript([OP_HASH160, hash160(p2wsh_p2pkh), OP_EQUAL])
616 return [p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh]
618 def create_and_mine_tx_from_txids(self, txids, success = True):
619 tx = CTransaction()
620 for i in txids:
621 txtmp = CTransaction()
622 txraw = self.nodes[0].getrawtransaction(i)
623 f = BytesIO(hex_str_to_bytes(txraw))
624 txtmp.deserialize(f)
625 for j in range(len(txtmp.vout)):
626 tx.vin.append(CTxIn(COutPoint(int('0x'+i,0), j)))
627 tx.vout.append(CTxOut(0, CScript()))
628 tx.rehash()
629 signresults = self.nodes[0].signrawtransaction(bytes_to_hex_str(tx.serialize_without_witness()))['hex']
630 self.nodes[0].sendrawtransaction(signresults, True)
631 self.nodes[0].generate(1)
632 sync_blocks(self.nodes)
635 if __name__ == '__main__':
636 SegWitTest().main()