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