qa: Remove unused NodeConn members
[bitcoinplatinum.git] / test / functional / p2p-segwit.py
blobb940bc40966a8a54011db4204a08992b612ebb62
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 segwit transactions and blocks on P2P network."""
7 from test_framework.mininode import *
8 from test_framework.test_framework import BitcoinTestFramework
9 from test_framework.util import *
10 from test_framework.script import *
11 from test_framework.blocktools import create_block, create_coinbase, add_witness_commitment, get_witness_script, WITNESS_COMMITMENT_HEADER
12 from test_framework.key import CECKey, CPubKey
13 import time
14 import random
15 from binascii import hexlify
17 # The versionbit bit used to signal activation of SegWit
18 VB_WITNESS_BIT = 1
19 VB_PERIOD = 144
20 VB_TOP_BITS = 0x20000000
22 MAX_SIGOP_COST = 80000
25 # Calculate the virtual size of a witness block:
26 # (base + witness/4)
27 def get_virtual_size(witness_block):
28 base_size = len(witness_block.serialize())
29 total_size = len(witness_block.serialize(with_witness=True))
30 # the "+3" is so we round up
31 vsize = int((3*base_size + total_size + 3)/4)
32 return vsize
34 class TestNode(NodeConnCB):
35 def __init__(self, rpc):
36 super().__init__()
37 self.getdataset = set()
38 self.rpc = rpc
40 def on_getdata(self, conn, message):
41 for inv in message.inv:
42 self.getdataset.add(inv.hash)
44 def announce_tx_and_wait_for_getdata(self, tx, timeout=60):
45 with mininode_lock:
46 self.last_message.pop("getdata", None)
47 self.send_message(msg_inv(inv=[CInv(1, tx.sha256)]))
48 self.wait_for_getdata(timeout)
50 def announce_block_and_wait_for_getdata(self, block, use_header, timeout=60):
51 with mininode_lock:
52 self.last_message.pop("getdata", None)
53 self.last_message.pop("getheaders", None)
54 msg = msg_headers()
55 msg.headers = [ CBlockHeader(block) ]
56 if use_header:
57 self.send_message(msg)
58 else:
59 self.send_message(msg_inv(inv=[CInv(2, block.sha256)]))
60 self.wait_for_getheaders()
61 self.send_message(msg)
62 self.wait_for_getdata()
64 def request_block(self, blockhash, inv_type, timeout=60):
65 with mininode_lock:
66 self.last_message.pop("block", None)
67 self.send_message(msg_getdata(inv=[CInv(inv_type, blockhash)]))
68 self.wait_for_block(blockhash, timeout)
69 return self.last_message["block"].block
71 def test_transaction_acceptance(self, tx, with_witness, accepted, reason=None):
72 tx_message = msg_tx(tx)
73 if with_witness:
74 tx_message = msg_witness_tx(tx)
75 self.send_message(tx_message)
76 self.sync_with_ping()
77 assert_equal(tx.hash in self.rpc.getrawmempool(), accepted)
78 if (reason != None and not accepted):
79 # Check the rejection reason as well.
80 with mininode_lock:
81 assert_equal(self.last_message["reject"].reason, reason)
83 # Test whether a witness block had the correct effect on the tip
84 def test_witness_block(self, block, accepted, with_witness=True):
85 if with_witness:
86 self.send_message(msg_witness_block(block))
87 else:
88 self.send_message(msg_block(block))
89 self.sync_with_ping()
90 assert_equal(self.rpc.getbestblockhash() == block.hash, accepted)
92 # Used to keep track of anyone-can-spend outputs that we can use in the tests
93 class UTXO():
94 def __init__(self, sha256, n, nValue):
95 self.sha256 = sha256
96 self.n = n
97 self.nValue = nValue
99 # Helper for getting the script associated with a P2PKH
100 def GetP2PKHScript(pubkeyhash):
101 return CScript([CScriptOp(OP_DUP), CScriptOp(OP_HASH160), pubkeyhash, CScriptOp(OP_EQUALVERIFY), CScriptOp(OP_CHECKSIG)])
103 # Add signature for a P2PK witness program.
104 def sign_P2PK_witness_input(script, txTo, inIdx, hashtype, value, key):
105 tx_hash = SegwitVersion1SignatureHash(script, txTo, inIdx, hashtype, value)
106 signature = key.sign(tx_hash) + chr(hashtype).encode('latin-1')
107 txTo.wit.vtxinwit[inIdx].scriptWitness.stack = [signature, script]
108 txTo.rehash()
111 class SegWitTest(BitcoinTestFramework):
112 def set_test_params(self):
113 self.setup_clean_chain = True
114 self.num_nodes = 3
115 # This test tests SegWit both pre and post-activation, so use the normal BIP9 activation.
116 self.extra_args = [["-whitelist=127.0.0.1", "-vbparams=segwit:0:999999999999"], ["-whitelist=127.0.0.1", "-acceptnonstdtxn=0", "-vbparams=segwit:0:999999999999"], ["-whitelist=127.0.0.1", "-vbparams=segwit:0:0"]]
118 def setup_network(self):
119 self.setup_nodes()
120 connect_nodes(self.nodes[0], 1)
121 connect_nodes(self.nodes[0], 2)
122 self.sync_all()
124 ''' Helpers '''
125 # Build a block on top of node0's tip.
126 def build_next_block(self, nVersion=4):
127 tip = self.nodes[0].getbestblockhash()
128 height = self.nodes[0].getblockcount() + 1
129 block_time = self.nodes[0].getblockheader(tip)["mediantime"] + 1
130 block = create_block(int(tip, 16), create_coinbase(height), block_time)
131 block.nVersion = nVersion
132 block.rehash()
133 return block
135 # Adds list of transactions to block, adds witness commitment, then solves.
136 def update_witness_block_with_transactions(self, block, tx_list, nonce=0):
137 block.vtx.extend(tx_list)
138 add_witness_commitment(block, nonce)
139 block.solve()
140 return
142 ''' Individual tests '''
143 def test_witness_services(self):
144 self.log.info("Verifying NODE_WITNESS service bit")
145 assert((self.test_node.connection.nServices & NODE_WITNESS) != 0)
148 # See if sending a regular transaction works, and create a utxo
149 # to use in later tests.
150 def test_non_witness_transaction(self):
151 # Mine a block with an anyone-can-spend coinbase,
152 # let it mature, then try to spend it.
153 self.log.info("Testing non-witness transaction")
154 block = self.build_next_block(nVersion=1)
155 block.solve()
156 self.test_node.send_message(msg_block(block))
157 self.test_node.sync_with_ping() # make sure the block was processed
158 txid = block.vtx[0].sha256
160 self.nodes[0].generate(99) # let the block mature
162 # Create a transaction that spends the coinbase
163 tx = CTransaction()
164 tx.vin.append(CTxIn(COutPoint(txid, 0), b""))
165 tx.vout.append(CTxOut(49*100000000, CScript([OP_TRUE])))
166 tx.calc_sha256()
168 # Check that serializing it with or without witness is the same
169 # This is a sanity check of our testing framework.
170 assert_equal(msg_tx(tx).serialize(), msg_witness_tx(tx).serialize())
172 self.test_node.send_message(msg_witness_tx(tx))
173 self.test_node.sync_with_ping() # make sure the tx was processed
174 assert(tx.hash in self.nodes[0].getrawmempool())
175 # Save this transaction for later
176 self.utxo.append(UTXO(tx.sha256, 0, 49*100000000))
177 self.nodes[0].generate(1)
180 # Verify that blocks with witnesses are rejected before activation.
181 def test_unnecessary_witness_before_segwit_activation(self):
182 self.log.info("Testing behavior of unnecessary witnesses")
183 # For now, rely on earlier tests to have created at least one utxo for
184 # us to use
185 assert(len(self.utxo) > 0)
186 assert(get_bip9_status(self.nodes[0], 'segwit')['status'] != 'active')
188 tx = CTransaction()
189 tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b""))
190 tx.vout.append(CTxOut(self.utxo[0].nValue-1000, CScript([OP_TRUE])))
191 tx.wit.vtxinwit.append(CTxInWitness())
192 tx.wit.vtxinwit[0].scriptWitness.stack = [CScript([CScriptNum(1)])]
194 # Verify the hash with witness differs from the txid
195 # (otherwise our testing framework must be broken!)
196 tx.rehash()
197 assert(tx.sha256 != tx.calc_sha256(with_witness=True))
199 # Construct a segwit-signaling block that includes the transaction.
200 block = self.build_next_block(nVersion=(VB_TOP_BITS|(1 << VB_WITNESS_BIT)))
201 self.update_witness_block_with_transactions(block, [tx])
202 # Sending witness data before activation is not allowed (anti-spam
203 # rule).
204 self.test_node.test_witness_block(block, accepted=False)
205 # TODO: fix synchronization so we can test reject reason
206 # Right now, bitcoind delays sending reject messages for blocks
207 # until the future, making synchronization here difficult.
208 #assert_equal(self.test_node.last_message["reject"].reason, "unexpected-witness")
210 # But it should not be permanently marked bad...
211 # Resend without witness information.
212 self.test_node.send_message(msg_block(block))
213 self.test_node.sync_with_ping()
214 assert_equal(self.nodes[0].getbestblockhash(), block.hash)
216 sync_blocks(self.nodes)
218 # Create a p2sh output -- this is so we can pass the standardness
219 # rules (an anyone-can-spend OP_TRUE would be rejected, if not wrapped
220 # in P2SH).
221 p2sh_program = CScript([OP_TRUE])
222 p2sh_pubkey = hash160(p2sh_program)
223 scriptPubKey = CScript([OP_HASH160, p2sh_pubkey, OP_EQUAL])
225 # Now check that unnecessary witnesses can't be used to blind a node
226 # to a transaction, eg by violating standardness checks.
227 tx2 = CTransaction()
228 tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b""))
229 tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, scriptPubKey))
230 tx2.rehash()
231 self.test_node.test_transaction_acceptance(tx2, False, True)
232 self.nodes[0].generate(1)
233 sync_blocks(self.nodes)
235 # We'll add an unnecessary witness to this transaction that would cause
236 # it to be non-standard, to test that violating policy with a witness before
237 # segwit activation doesn't blind a node to a transaction. Transactions
238 # rejected for having a witness before segwit activation shouldn't be added
239 # to the rejection cache.
240 tx3 = CTransaction()
241 tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), CScript([p2sh_program])))
242 tx3.vout.append(CTxOut(tx2.vout[0].nValue-1000, scriptPubKey))
243 tx3.wit.vtxinwit.append(CTxInWitness())
244 tx3.wit.vtxinwit[0].scriptWitness.stack = [b'a'*400000]
245 tx3.rehash()
246 # Note that this should be rejected for the premature witness reason,
247 # rather than a policy check, since segwit hasn't activated yet.
248 self.std_node.test_transaction_acceptance(tx3, True, False, b'no-witness-yet')
250 # If we send without witness, it should be accepted.
251 self.std_node.test_transaction_acceptance(tx3, False, True)
253 # Now create a new anyone-can-spend utxo for the next test.
254 tx4 = CTransaction()
255 tx4.vin.append(CTxIn(COutPoint(tx3.sha256, 0), CScript([p2sh_program])))
256 tx4.vout.append(CTxOut(tx3.vout[0].nValue-1000, CScript([OP_TRUE])))
257 tx4.rehash()
258 self.test_node.test_transaction_acceptance(tx3, False, True)
259 self.test_node.test_transaction_acceptance(tx4, False, True)
261 self.nodes[0].generate(1)
262 sync_blocks(self.nodes)
264 # Update our utxo list; we spent the first entry.
265 self.utxo.pop(0)
266 self.utxo.append(UTXO(tx4.sha256, 0, tx4.vout[0].nValue))
269 # Mine enough blocks for segwit's vb state to be 'started'.
270 def advance_to_segwit_started(self):
271 height = self.nodes[0].getblockcount()
272 # Will need to rewrite the tests here if we are past the first period
273 assert(height < VB_PERIOD - 1)
274 # Genesis block is 'defined'.
275 assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'defined')
276 # Advance to end of period, status should now be 'started'
277 self.nodes[0].generate(VB_PERIOD-height-1)
278 assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'started')
280 # Mine enough blocks to lock in segwit, but don't activate.
281 # TODO: we could verify that lockin only happens at the right threshold of
282 # signalling blocks, rather than just at the right period boundary.
283 def advance_to_segwit_lockin(self):
284 height = self.nodes[0].getblockcount()
285 assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'started')
286 # Advance to end of period, and verify lock-in happens at the end
287 self.nodes[0].generate(VB_PERIOD-1)
288 height = self.nodes[0].getblockcount()
289 assert((height % VB_PERIOD) == VB_PERIOD - 2)
290 assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'started')
291 self.nodes[0].generate(1)
292 assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'locked_in')
295 # Mine enough blocks to activate segwit.
296 # TODO: we could verify that activation only happens at the right threshold
297 # of signalling blocks, rather than just at the right period boundary.
298 def advance_to_segwit_active(self):
299 assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'locked_in')
300 height = self.nodes[0].getblockcount()
301 self.nodes[0].generate(VB_PERIOD - (height%VB_PERIOD) - 2)
302 assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'locked_in')
303 self.nodes[0].generate(1)
304 assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'active')
307 # This test can only be run after segwit has activated
308 def test_witness_commitments(self):
309 self.log.info("Testing witness commitments")
311 # First try a correct witness commitment.
312 block = self.build_next_block()
313 add_witness_commitment(block)
314 block.solve()
316 # Test the test -- witness serialization should be different
317 assert(msg_witness_block(block).serialize() != msg_block(block).serialize())
319 # This empty block should be valid.
320 self.test_node.test_witness_block(block, accepted=True)
322 # Try to tweak the nonce
323 block_2 = self.build_next_block()
324 add_witness_commitment(block_2, nonce=28)
325 block_2.solve()
327 # The commitment should have changed!
328 assert(block_2.vtx[0].vout[-1] != block.vtx[0].vout[-1])
330 # This should also be valid.
331 self.test_node.test_witness_block(block_2, accepted=True)
333 # Now test commitments with actual transactions
334 assert (len(self.utxo) > 0)
335 tx = CTransaction()
336 tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b""))
338 # Let's construct a witness program
339 witness_program = CScript([OP_TRUE])
340 witness_hash = sha256(witness_program)
341 scriptPubKey = CScript([OP_0, witness_hash])
342 tx.vout.append(CTxOut(self.utxo[0].nValue-1000, scriptPubKey))
343 tx.rehash()
345 # tx2 will spend tx1, and send back to a regular anyone-can-spend address
346 tx2 = CTransaction()
347 tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b""))
348 tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, witness_program))
349 tx2.wit.vtxinwit.append(CTxInWitness())
350 tx2.wit.vtxinwit[0].scriptWitness.stack = [witness_program]
351 tx2.rehash()
353 block_3 = self.build_next_block()
354 self.update_witness_block_with_transactions(block_3, [tx, tx2], nonce=1)
355 # Add an extra OP_RETURN output that matches the witness commitment template,
356 # even though it has extra data after the incorrect commitment.
357 # This block should fail.
358 block_3.vtx[0].vout.append(CTxOut(0, CScript([OP_RETURN, WITNESS_COMMITMENT_HEADER + ser_uint256(2), 10])))
359 block_3.vtx[0].rehash()
360 block_3.hashMerkleRoot = block_3.calc_merkle_root()
361 block_3.rehash()
362 block_3.solve()
364 self.test_node.test_witness_block(block_3, accepted=False)
366 # Add a different commitment with different nonce, but in the
367 # right location, and with some funds burned(!).
368 # This should succeed (nValue shouldn't affect finding the
369 # witness commitment).
370 add_witness_commitment(block_3, nonce=0)
371 block_3.vtx[0].vout[0].nValue -= 1
372 block_3.vtx[0].vout[-1].nValue += 1
373 block_3.vtx[0].rehash()
374 block_3.hashMerkleRoot = block_3.calc_merkle_root()
375 block_3.rehash()
376 assert(len(block_3.vtx[0].vout) == 4) # 3 OP_returns
377 block_3.solve()
378 self.test_node.test_witness_block(block_3, accepted=True)
380 # Finally test that a block with no witness transactions can
381 # omit the commitment.
382 block_4 = self.build_next_block()
383 tx3 = CTransaction()
384 tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), b""))
385 tx3.vout.append(CTxOut(tx.vout[0].nValue-1000, witness_program))
386 tx3.rehash()
387 block_4.vtx.append(tx3)
388 block_4.hashMerkleRoot = block_4.calc_merkle_root()
389 block_4.solve()
390 self.test_node.test_witness_block(block_4, with_witness=False, accepted=True)
392 # Update available utxo's for use in later test.
393 self.utxo.pop(0)
394 self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue))
397 def test_block_malleability(self):
398 self.log.info("Testing witness block malleability")
400 # Make sure that a block that has too big a virtual size
401 # because of a too-large coinbase witness is not permanently
402 # marked bad.
403 block = self.build_next_block()
404 add_witness_commitment(block)
405 block.solve()
407 block.vtx[0].wit.vtxinwit[0].scriptWitness.stack.append(b'a'*5000000)
408 assert(get_virtual_size(block) > MAX_BLOCK_BASE_SIZE)
410 # We can't send over the p2p network, because this is too big to relay
411 # TODO: repeat this test with a block that can be relayed
412 self.nodes[0].submitblock(bytes_to_hex_str(block.serialize(True)))
414 assert(self.nodes[0].getbestblockhash() != block.hash)
416 block.vtx[0].wit.vtxinwit[0].scriptWitness.stack.pop()
417 assert(get_virtual_size(block) < MAX_BLOCK_BASE_SIZE)
418 self.nodes[0].submitblock(bytes_to_hex_str(block.serialize(True)))
420 assert(self.nodes[0].getbestblockhash() == block.hash)
422 # Now make sure that malleating the witness nonce doesn't
423 # result in a block permanently marked bad.
424 block = self.build_next_block()
425 add_witness_commitment(block)
426 block.solve()
428 # Change the nonce -- should not cause the block to be permanently
429 # failed
430 block.vtx[0].wit.vtxinwit[0].scriptWitness.stack = [ ser_uint256(1) ]
431 self.test_node.test_witness_block(block, accepted=False)
433 # Changing the witness nonce doesn't change the block hash
434 block.vtx[0].wit.vtxinwit[0].scriptWitness.stack = [ ser_uint256(0) ]
435 self.test_node.test_witness_block(block, accepted=True)
438 def test_witness_block_size(self):
439 self.log.info("Testing witness block size limit")
440 # TODO: Test that non-witness carrying blocks can't exceed 1MB
441 # Skipping this test for now; this is covered in p2p-fullblocktest.py
443 # Test that witness-bearing blocks are limited at ceil(base + wit/4) <= 1MB.
444 block = self.build_next_block()
446 assert(len(self.utxo) > 0)
448 # Create a P2WSH transaction.
449 # The witness program will be a bunch of OP_2DROP's, followed by OP_TRUE.
450 # This should give us plenty of room to tweak the spending tx's
451 # virtual size.
452 NUM_DROPS = 200 # 201 max ops per script!
453 NUM_OUTPUTS = 50
455 witness_program = CScript([OP_2DROP]*NUM_DROPS + [OP_TRUE])
456 witness_hash = uint256_from_str(sha256(witness_program))
457 scriptPubKey = CScript([OP_0, ser_uint256(witness_hash)])
459 prevout = COutPoint(self.utxo[0].sha256, self.utxo[0].n)
460 value = self.utxo[0].nValue
462 parent_tx = CTransaction()
463 parent_tx.vin.append(CTxIn(prevout, b""))
464 child_value = int(value/NUM_OUTPUTS)
465 for i in range(NUM_OUTPUTS):
466 parent_tx.vout.append(CTxOut(child_value, scriptPubKey))
467 parent_tx.vout[0].nValue -= 50000
468 assert(parent_tx.vout[0].nValue > 0)
469 parent_tx.rehash()
471 child_tx = CTransaction()
472 for i in range(NUM_OUTPUTS):
473 child_tx.vin.append(CTxIn(COutPoint(parent_tx.sha256, i), b""))
474 child_tx.vout = [CTxOut(value - 100000, CScript([OP_TRUE]))]
475 for i in range(NUM_OUTPUTS):
476 child_tx.wit.vtxinwit.append(CTxInWitness())
477 child_tx.wit.vtxinwit[-1].scriptWitness.stack = [b'a'*195]*(2*NUM_DROPS) + [witness_program]
478 child_tx.rehash()
479 self.update_witness_block_with_transactions(block, [parent_tx, child_tx])
481 vsize = get_virtual_size(block)
482 additional_bytes = (MAX_BLOCK_BASE_SIZE - vsize)*4
483 i = 0
484 while additional_bytes > 0:
485 # Add some more bytes to each input until we hit MAX_BLOCK_BASE_SIZE+1
486 extra_bytes = min(additional_bytes+1, 55)
487 block.vtx[-1].wit.vtxinwit[int(i/(2*NUM_DROPS))].scriptWitness.stack[i%(2*NUM_DROPS)] = b'a'*(195+extra_bytes)
488 additional_bytes -= extra_bytes
489 i += 1
491 block.vtx[0].vout.pop() # Remove old commitment
492 add_witness_commitment(block)
493 block.solve()
494 vsize = get_virtual_size(block)
495 assert_equal(vsize, MAX_BLOCK_BASE_SIZE + 1)
496 # Make sure that our test case would exceed the old max-network-message
497 # limit
498 assert(len(block.serialize(True)) > 2*1024*1024)
500 self.test_node.test_witness_block(block, accepted=False)
502 # Now resize the second transaction to make the block fit.
503 cur_length = len(block.vtx[-1].wit.vtxinwit[0].scriptWitness.stack[0])
504 block.vtx[-1].wit.vtxinwit[0].scriptWitness.stack[0] = b'a'*(cur_length-1)
505 block.vtx[0].vout.pop()
506 add_witness_commitment(block)
507 block.solve()
508 assert(get_virtual_size(block) == MAX_BLOCK_BASE_SIZE)
510 self.test_node.test_witness_block(block, accepted=True)
512 # Update available utxo's
513 self.utxo.pop(0)
514 self.utxo.append(UTXO(block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue))
517 # submitblock will try to add the nonce automatically, so that mining
518 # software doesn't need to worry about doing so itself.
519 def test_submit_block(self):
520 block = self.build_next_block()
522 # Try using a custom nonce and then don't supply it.
523 # This shouldn't possibly work.
524 add_witness_commitment(block, nonce=1)
525 block.vtx[0].wit = CTxWitness() # drop the nonce
526 block.solve()
527 self.nodes[0].submitblock(bytes_to_hex_str(block.serialize(True)))
528 assert(self.nodes[0].getbestblockhash() != block.hash)
530 # Now redo commitment with the standard nonce, but let bitcoind fill it in.
531 add_witness_commitment(block, nonce=0)
532 block.vtx[0].wit = CTxWitness()
533 block.solve()
534 self.nodes[0].submitblock(bytes_to_hex_str(block.serialize(True)))
535 assert_equal(self.nodes[0].getbestblockhash(), block.hash)
537 # This time, add a tx with non-empty witness, but don't supply
538 # the commitment.
539 block_2 = self.build_next_block()
541 add_witness_commitment(block_2)
543 block_2.solve()
545 # Drop commitment and nonce -- submitblock should not fill in.
546 block_2.vtx[0].vout.pop()
547 block_2.vtx[0].wit = CTxWitness()
549 self.nodes[0].submitblock(bytes_to_hex_str(block_2.serialize(True)))
550 # Tip should not advance!
551 assert(self.nodes[0].getbestblockhash() != block_2.hash)
554 # Consensus tests of extra witness data in a transaction.
555 def test_extra_witness_data(self):
556 self.log.info("Testing extra witness data in tx")
558 assert(len(self.utxo) > 0)
560 block = self.build_next_block()
562 witness_program = CScript([OP_DROP, OP_TRUE])
563 witness_hash = sha256(witness_program)
564 scriptPubKey = CScript([OP_0, witness_hash])
566 # First try extra witness data on a tx that doesn't require a witness
567 tx = CTransaction()
568 tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b""))
569 tx.vout.append(CTxOut(self.utxo[0].nValue-2000, scriptPubKey))
570 tx.vout.append(CTxOut(1000, CScript([OP_TRUE]))) # non-witness output
571 tx.wit.vtxinwit.append(CTxInWitness())
572 tx.wit.vtxinwit[0].scriptWitness.stack = [CScript([])]
573 tx.rehash()
574 self.update_witness_block_with_transactions(block, [tx])
576 # Extra witness data should not be allowed.
577 self.test_node.test_witness_block(block, accepted=False)
579 # Try extra signature data. Ok if we're not spending a witness output.
580 block.vtx[1].wit.vtxinwit = []
581 block.vtx[1].vin[0].scriptSig = CScript([OP_0])
582 block.vtx[1].rehash()
583 add_witness_commitment(block)
584 block.solve()
586 self.test_node.test_witness_block(block, accepted=True)
588 # Now try extra witness/signature data on an input that DOES require a
589 # witness
590 tx2 = CTransaction()
591 tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) # witness output
592 tx2.vin.append(CTxIn(COutPoint(tx.sha256, 1), b"")) # non-witness
593 tx2.vout.append(CTxOut(tx.vout[0].nValue, CScript([OP_TRUE])))
594 tx2.wit.vtxinwit.extend([CTxInWitness(), CTxInWitness()])
595 tx2.wit.vtxinwit[0].scriptWitness.stack = [ CScript([CScriptNum(1)]), CScript([CScriptNum(1)]), witness_program ]
596 tx2.wit.vtxinwit[1].scriptWitness.stack = [ CScript([OP_TRUE]) ]
598 block = self.build_next_block()
599 self.update_witness_block_with_transactions(block, [tx2])
601 # This has extra witness data, so it should fail.
602 self.test_node.test_witness_block(block, accepted=False)
604 # Now get rid of the extra witness, but add extra scriptSig data
605 tx2.vin[0].scriptSig = CScript([OP_TRUE])
606 tx2.vin[1].scriptSig = CScript([OP_TRUE])
607 tx2.wit.vtxinwit[0].scriptWitness.stack.pop(0)
608 tx2.wit.vtxinwit[1].scriptWitness.stack = []
609 tx2.rehash()
610 add_witness_commitment(block)
611 block.solve()
613 # This has extra signature data for a witness input, so it should fail.
614 self.test_node.test_witness_block(block, accepted=False)
616 # Now get rid of the extra scriptsig on the witness input, and verify
617 # success (even with extra scriptsig data in the non-witness input)
618 tx2.vin[0].scriptSig = b""
619 tx2.rehash()
620 add_witness_commitment(block)
621 block.solve()
623 self.test_node.test_witness_block(block, accepted=True)
625 # Update utxo for later tests
626 self.utxo.pop(0)
627 self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue))
630 def test_max_witness_push_length(self):
631 ''' Should only allow up to 520 byte pushes in witness stack '''
632 self.log.info("Testing maximum witness push size")
633 MAX_SCRIPT_ELEMENT_SIZE = 520
634 assert(len(self.utxo))
636 block = self.build_next_block()
638 witness_program = CScript([OP_DROP, OP_TRUE])
639 witness_hash = sha256(witness_program)
640 scriptPubKey = CScript([OP_0, witness_hash])
642 tx = CTransaction()
643 tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b""))
644 tx.vout.append(CTxOut(self.utxo[0].nValue-1000, scriptPubKey))
645 tx.rehash()
647 tx2 = CTransaction()
648 tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b""))
649 tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, CScript([OP_TRUE])))
650 tx2.wit.vtxinwit.append(CTxInWitness())
651 # First try a 521-byte stack element
652 tx2.wit.vtxinwit[0].scriptWitness.stack = [ b'a'*(MAX_SCRIPT_ELEMENT_SIZE+1), witness_program ]
653 tx2.rehash()
655 self.update_witness_block_with_transactions(block, [tx, tx2])
656 self.test_node.test_witness_block(block, accepted=False)
658 # Now reduce the length of the stack element
659 tx2.wit.vtxinwit[0].scriptWitness.stack[0] = b'a'*(MAX_SCRIPT_ELEMENT_SIZE)
661 add_witness_commitment(block)
662 block.solve()
663 self.test_node.test_witness_block(block, accepted=True)
665 # Update the utxo for later tests
666 self.utxo.pop()
667 self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue))
669 def test_max_witness_program_length(self):
670 # Can create witness outputs that are long, but can't be greater than
671 # 10k bytes to successfully spend
672 self.log.info("Testing maximum witness program length")
673 assert(len(self.utxo))
674 MAX_PROGRAM_LENGTH = 10000
676 # This program is 19 max pushes (9937 bytes), then 64 more opcode-bytes.
677 long_witness_program = CScript([b'a'*520]*19 + [OP_DROP]*63 + [OP_TRUE])
678 assert(len(long_witness_program) == MAX_PROGRAM_LENGTH+1)
679 long_witness_hash = sha256(long_witness_program)
680 long_scriptPubKey = CScript([OP_0, long_witness_hash])
682 block = self.build_next_block()
684 tx = CTransaction()
685 tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b""))
686 tx.vout.append(CTxOut(self.utxo[0].nValue-1000, long_scriptPubKey))
687 tx.rehash()
689 tx2 = CTransaction()
690 tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b""))
691 tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, CScript([OP_TRUE])))
692 tx2.wit.vtxinwit.append(CTxInWitness())
693 tx2.wit.vtxinwit[0].scriptWitness.stack = [b'a']*44 + [long_witness_program]
694 tx2.rehash()
696 self.update_witness_block_with_transactions(block, [tx, tx2])
698 self.test_node.test_witness_block(block, accepted=False)
700 # Try again with one less byte in the witness program
701 witness_program = CScript([b'a'*520]*19 + [OP_DROP]*62 + [OP_TRUE])
702 assert(len(witness_program) == MAX_PROGRAM_LENGTH)
703 witness_hash = sha256(witness_program)
704 scriptPubKey = CScript([OP_0, witness_hash])
706 tx.vout[0] = CTxOut(tx.vout[0].nValue, scriptPubKey)
707 tx.rehash()
708 tx2.vin[0].prevout.hash = tx.sha256
709 tx2.wit.vtxinwit[0].scriptWitness.stack = [b'a']*43 + [witness_program]
710 tx2.rehash()
711 block.vtx = [block.vtx[0]]
712 self.update_witness_block_with_transactions(block, [tx, tx2])
713 self.test_node.test_witness_block(block, accepted=True)
715 self.utxo.pop()
716 self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue))
719 def test_witness_input_length(self):
720 ''' Ensure that vin length must match vtxinwit length '''
721 self.log.info("Testing witness input length")
722 assert(len(self.utxo))
724 witness_program = CScript([OP_DROP, OP_TRUE])
725 witness_hash = sha256(witness_program)
726 scriptPubKey = CScript([OP_0, witness_hash])
728 # Create a transaction that splits our utxo into many outputs
729 tx = CTransaction()
730 tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b""))
731 nValue = self.utxo[0].nValue
732 for i in range(10):
733 tx.vout.append(CTxOut(int(nValue/10), scriptPubKey))
734 tx.vout[0].nValue -= 1000
735 assert(tx.vout[0].nValue >= 0)
737 block = self.build_next_block()
738 self.update_witness_block_with_transactions(block, [tx])
739 self.test_node.test_witness_block(block, accepted=True)
741 # Try various ways to spend tx that should all break.
742 # This "broken" transaction serializer will not normalize
743 # the length of vtxinwit.
744 class BrokenCTransaction(CTransaction):
745 def serialize_with_witness(self):
746 flags = 0
747 if not self.wit.is_null():
748 flags |= 1
749 r = b""
750 r += struct.pack("<i", self.nVersion)
751 if flags:
752 dummy = []
753 r += ser_vector(dummy)
754 r += struct.pack("<B", flags)
755 r += ser_vector(self.vin)
756 r += ser_vector(self.vout)
757 if flags & 1:
758 r += self.wit.serialize()
759 r += struct.pack("<I", self.nLockTime)
760 return r
762 tx2 = BrokenCTransaction()
763 for i in range(10):
764 tx2.vin.append(CTxIn(COutPoint(tx.sha256, i), b""))
765 tx2.vout.append(CTxOut(nValue-3000, CScript([OP_TRUE])))
767 # First try using a too long vtxinwit
768 for i in range(11):
769 tx2.wit.vtxinwit.append(CTxInWitness())
770 tx2.wit.vtxinwit[i].scriptWitness.stack = [b'a', witness_program]
772 block = self.build_next_block()
773 self.update_witness_block_with_transactions(block, [tx2])
774 self.test_node.test_witness_block(block, accepted=False)
776 # Now try using a too short vtxinwit
777 tx2.wit.vtxinwit.pop()
778 tx2.wit.vtxinwit.pop()
780 block.vtx = [block.vtx[0]]
781 self.update_witness_block_with_transactions(block, [tx2])
782 self.test_node.test_witness_block(block, accepted=False)
784 # Now make one of the intermediate witnesses be incorrect
785 tx2.wit.vtxinwit.append(CTxInWitness())
786 tx2.wit.vtxinwit[-1].scriptWitness.stack = [b'a', witness_program]
787 tx2.wit.vtxinwit[5].scriptWitness.stack = [ witness_program ]
789 block.vtx = [block.vtx[0]]
790 self.update_witness_block_with_transactions(block, [tx2])
791 self.test_node.test_witness_block(block, accepted=False)
793 # Fix the broken witness and the block should be accepted.
794 tx2.wit.vtxinwit[5].scriptWitness.stack = [b'a', witness_program]
795 block.vtx = [block.vtx[0]]
796 self.update_witness_block_with_transactions(block, [tx2])
797 self.test_node.test_witness_block(block, accepted=True)
799 self.utxo.pop()
800 self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue))
803 def test_witness_tx_relay_before_segwit_activation(self):
804 self.log.info("Testing relay of witness transactions")
805 # Generate a transaction that doesn't require a witness, but send it
806 # with a witness. Should be rejected for premature-witness, but should
807 # not be added to recently rejected list.
808 assert(len(self.utxo))
809 tx = CTransaction()
810 tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b""))
811 tx.vout.append(CTxOut(self.utxo[0].nValue-1000, CScript([OP_TRUE])))
812 tx.wit.vtxinwit.append(CTxInWitness())
813 tx.wit.vtxinwit[0].scriptWitness.stack = [ b'a' ]
814 tx.rehash()
816 tx_hash = tx.sha256
817 tx_value = tx.vout[0].nValue
819 # Verify that if a peer doesn't set nServices to include NODE_WITNESS,
820 # the getdata is just for the non-witness portion.
821 self.old_node.announce_tx_and_wait_for_getdata(tx)
822 assert(self.old_node.last_message["getdata"].inv[0].type == 1)
824 # Since we haven't delivered the tx yet, inv'ing the same tx from
825 # a witness transaction ought not result in a getdata.
826 try:
827 self.test_node.announce_tx_and_wait_for_getdata(tx, timeout=2)
828 self.log.error("Error: duplicate tx getdata!")
829 assert(False)
830 except AssertionError as e:
831 pass
833 # Delivering this transaction with witness should fail (no matter who
834 # its from)
835 assert_equal(len(self.nodes[0].getrawmempool()), 0)
836 assert_equal(len(self.nodes[1].getrawmempool()), 0)
837 self.old_node.test_transaction_acceptance(tx, with_witness=True, accepted=False)
838 self.test_node.test_transaction_acceptance(tx, with_witness=True, accepted=False)
840 # But eliminating the witness should fix it
841 self.test_node.test_transaction_acceptance(tx, with_witness=False, accepted=True)
843 # Cleanup: mine the first transaction and update utxo
844 self.nodes[0].generate(1)
845 assert_equal(len(self.nodes[0].getrawmempool()), 0)
847 self.utxo.pop(0)
848 self.utxo.append(UTXO(tx_hash, 0, tx_value))
851 # After segwit activates, verify that mempool:
852 # - rejects transactions with unnecessary/extra witnesses
853 # - accepts transactions with valid witnesses
854 # and that witness transactions are relayed to non-upgraded peers.
855 def test_tx_relay_after_segwit_activation(self):
856 self.log.info("Testing relay of witness transactions")
857 # Generate a transaction that doesn't require a witness, but send it
858 # with a witness. Should be rejected because we can't use a witness
859 # when spending a non-witness output.
860 assert(len(self.utxo))
861 tx = CTransaction()
862 tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b""))
863 tx.vout.append(CTxOut(self.utxo[0].nValue-1000, CScript([OP_TRUE])))
864 tx.wit.vtxinwit.append(CTxInWitness())
865 tx.wit.vtxinwit[0].scriptWitness.stack = [ b'a' ]
866 tx.rehash()
868 tx_hash = tx.sha256
870 # Verify that unnecessary witnesses are rejected.
871 self.test_node.announce_tx_and_wait_for_getdata(tx)
872 assert_equal(len(self.nodes[0].getrawmempool()), 0)
873 self.test_node.test_transaction_acceptance(tx, with_witness=True, accepted=False)
875 # Verify that removing the witness succeeds.
876 self.test_node.announce_tx_and_wait_for_getdata(tx)
877 self.test_node.test_transaction_acceptance(tx, with_witness=False, accepted=True)
879 # Now try to add extra witness data to a valid witness tx.
880 witness_program = CScript([OP_TRUE])
881 witness_hash = sha256(witness_program)
882 scriptPubKey = CScript([OP_0, witness_hash])
883 tx2 = CTransaction()
884 tx2.vin.append(CTxIn(COutPoint(tx_hash, 0), b""))
885 tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, scriptPubKey))
886 tx2.rehash()
888 tx3 = CTransaction()
889 tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), b""))
890 tx3.wit.vtxinwit.append(CTxInWitness())
892 # Add too-large for IsStandard witness and check that it does not enter reject filter
893 p2sh_program = CScript([OP_TRUE])
894 p2sh_pubkey = hash160(p2sh_program)
895 witness_program2 = CScript([b'a'*400000])
896 tx3.vout.append(CTxOut(tx2.vout[0].nValue-1000, CScript([OP_HASH160, p2sh_pubkey, OP_EQUAL])))
897 tx3.wit.vtxinwit[0].scriptWitness.stack = [witness_program2]
898 tx3.rehash()
900 # Node will not be blinded to the transaction
901 self.std_node.announce_tx_and_wait_for_getdata(tx3)
902 self.std_node.test_transaction_acceptance(tx3, True, False, b'tx-size')
903 self.std_node.announce_tx_and_wait_for_getdata(tx3)
904 self.std_node.test_transaction_acceptance(tx3, True, False, b'tx-size')
906 # Remove witness stuffing, instead add extra witness push on stack
907 tx3.vout[0] = CTxOut(tx2.vout[0].nValue-1000, CScript([OP_TRUE]))
908 tx3.wit.vtxinwit[0].scriptWitness.stack = [CScript([CScriptNum(1)]), witness_program ]
909 tx3.rehash()
911 self.test_node.test_transaction_acceptance(tx2, with_witness=True, accepted=True)
912 self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=False)
914 # Get rid of the extra witness, and verify acceptance.
915 tx3.wit.vtxinwit[0].scriptWitness.stack = [ witness_program ]
916 # Also check that old_node gets a tx announcement, even though this is
917 # a witness transaction.
918 self.old_node.wait_for_inv([CInv(1, tx2.sha256)]) # wait until tx2 was inv'ed
919 self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=True)
920 self.old_node.wait_for_inv([CInv(1, tx3.sha256)])
922 # Test that getrawtransaction returns correct witness information
923 # hash, size, vsize
924 raw_tx = self.nodes[0].getrawtransaction(tx3.hash, 1)
925 assert_equal(int(raw_tx["hash"], 16), tx3.calc_sha256(True))
926 assert_equal(raw_tx["size"], len(tx3.serialize_with_witness()))
927 vsize = (len(tx3.serialize_with_witness()) + 3*len(tx3.serialize_without_witness()) + 3) / 4
928 assert_equal(raw_tx["vsize"], vsize)
929 assert_equal(len(raw_tx["vin"][0]["txinwitness"]), 1)
930 assert_equal(raw_tx["vin"][0]["txinwitness"][0], hexlify(witness_program).decode('ascii'))
931 assert(vsize != raw_tx["size"])
933 # Cleanup: mine the transactions and update utxo for next test
934 self.nodes[0].generate(1)
935 assert_equal(len(self.nodes[0].getrawmempool()), 0)
937 self.utxo.pop(0)
938 self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue))
941 # Test that block requests to NODE_WITNESS peer are with MSG_WITNESS_FLAG
942 # This is true regardless of segwit activation.
943 # Also test that we don't ask for blocks from unupgraded peers
944 def test_block_relay(self, segwit_activated):
945 self.log.info("Testing block relay")
947 blocktype = 2|MSG_WITNESS_FLAG
949 # test_node has set NODE_WITNESS, so all getdata requests should be for
950 # witness blocks.
951 # Test announcing a block via inv results in a getdata, and that
952 # announcing a version 4 or random VB block with a header results in a getdata
953 block1 = self.build_next_block()
954 block1.solve()
956 self.test_node.announce_block_and_wait_for_getdata(block1, use_header=False)
957 assert(self.test_node.last_message["getdata"].inv[0].type == blocktype)
958 self.test_node.test_witness_block(block1, True)
960 block2 = self.build_next_block(nVersion=4)
961 block2.solve()
963 self.test_node.announce_block_and_wait_for_getdata(block2, use_header=True)
964 assert(self.test_node.last_message["getdata"].inv[0].type == blocktype)
965 self.test_node.test_witness_block(block2, True)
967 block3 = self.build_next_block(nVersion=(VB_TOP_BITS | (1<<15)))
968 block3.solve()
969 self.test_node.announce_block_and_wait_for_getdata(block3, use_header=True)
970 assert(self.test_node.last_message["getdata"].inv[0].type == blocktype)
971 self.test_node.test_witness_block(block3, True)
973 # Check that we can getdata for witness blocks or regular blocks,
974 # and the right thing happens.
975 if segwit_activated == False:
976 # Before activation, we should be able to request old blocks with
977 # or without witness, and they should be the same.
978 chain_height = self.nodes[0].getblockcount()
979 # Pick 10 random blocks on main chain, and verify that getdata's
980 # for MSG_BLOCK, MSG_WITNESS_BLOCK, and rpc getblock() are equal.
981 all_heights = list(range(chain_height+1))
982 random.shuffle(all_heights)
983 all_heights = all_heights[0:10]
984 for height in all_heights:
985 block_hash = self.nodes[0].getblockhash(height)
986 rpc_block = self.nodes[0].getblock(block_hash, False)
987 block_hash = int(block_hash, 16)
988 block = self.test_node.request_block(block_hash, 2)
989 wit_block = self.test_node.request_block(block_hash, 2|MSG_WITNESS_FLAG)
990 assert_equal(block.serialize(True), wit_block.serialize(True))
991 assert_equal(block.serialize(), hex_str_to_bytes(rpc_block))
992 else:
993 # After activation, witness blocks and non-witness blocks should
994 # be different. Verify rpc getblock() returns witness blocks, while
995 # getdata respects the requested type.
996 block = self.build_next_block()
997 self.update_witness_block_with_transactions(block, [])
998 # This gives us a witness commitment.
999 assert(len(block.vtx[0].wit.vtxinwit) == 1)
1000 assert(len(block.vtx[0].wit.vtxinwit[0].scriptWitness.stack) == 1)
1001 self.test_node.test_witness_block(block, accepted=True)
1002 # Now try to retrieve it...
1003 rpc_block = self.nodes[0].getblock(block.hash, False)
1004 non_wit_block = self.test_node.request_block(block.sha256, 2)
1005 wit_block = self.test_node.request_block(block.sha256, 2|MSG_WITNESS_FLAG)
1006 assert_equal(wit_block.serialize(True), hex_str_to_bytes(rpc_block))
1007 assert_equal(wit_block.serialize(False), non_wit_block.serialize())
1008 assert_equal(wit_block.serialize(True), block.serialize(True))
1010 # Test size, vsize, weight
1011 rpc_details = self.nodes[0].getblock(block.hash, True)
1012 assert_equal(rpc_details["size"], len(block.serialize(True)))
1013 assert_equal(rpc_details["strippedsize"], len(block.serialize(False)))
1014 weight = 3*len(block.serialize(False)) + len(block.serialize(True))
1015 assert_equal(rpc_details["weight"], weight)
1017 # Upgraded node should not ask for blocks from unupgraded
1018 block4 = self.build_next_block(nVersion=4)
1019 block4.solve()
1020 self.old_node.getdataset = set()
1022 # Blocks can be requested via direct-fetch (immediately upon processing the announcement)
1023 # or via parallel download (with an indeterminate delay from processing the announcement)
1024 # so to test that a block is NOT requested, we could guess a time period to sleep for,
1025 # and then check. We can avoid the sleep() by taking advantage of transaction getdata's
1026 # being processed after block getdata's, and announce a transaction as well,
1027 # and then check to see if that particular getdata has been received.
1028 # Since 0.14, inv's will only be responded to with a getheaders, so send a header
1029 # to announce this block.
1030 msg = msg_headers()
1031 msg.headers = [ CBlockHeader(block4) ]
1032 self.old_node.send_message(msg)
1033 self.old_node.announce_tx_and_wait_for_getdata(block4.vtx[0])
1034 assert(block4.sha256 not in self.old_node.getdataset)
1036 # V0 segwit outputs should be standard after activation, but not before.
1037 def test_standardness_v0(self, segwit_activated):
1038 self.log.info("Testing standardness of v0 outputs (%s activation)" % ("after" if segwit_activated else "before"))
1039 assert(len(self.utxo))
1041 witness_program = CScript([OP_TRUE])
1042 witness_hash = sha256(witness_program)
1043 scriptPubKey = CScript([OP_0, witness_hash])
1045 p2sh_pubkey = hash160(witness_program)
1046 p2sh_scriptPubKey = CScript([OP_HASH160, p2sh_pubkey, OP_EQUAL])
1048 # First prepare a p2sh output (so that spending it will pass standardness)
1049 p2sh_tx = CTransaction()
1050 p2sh_tx.vin = [CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")]
1051 p2sh_tx.vout = [CTxOut(self.utxo[0].nValue-1000, p2sh_scriptPubKey)]
1052 p2sh_tx.rehash()
1054 # Mine it on test_node to create the confirmed output.
1055 self.test_node.test_transaction_acceptance(p2sh_tx, with_witness=True, accepted=True)
1056 self.nodes[0].generate(1)
1057 sync_blocks(self.nodes)
1059 # Now test standardness of v0 P2WSH outputs.
1060 # Start by creating a transaction with two outputs.
1061 tx = CTransaction()
1062 tx.vin = [CTxIn(COutPoint(p2sh_tx.sha256, 0), CScript([witness_program]))]
1063 tx.vout = [CTxOut(p2sh_tx.vout[0].nValue-10000, scriptPubKey)]
1064 tx.vout.append(CTxOut(8000, scriptPubKey)) # Might burn this later
1065 tx.rehash()
1067 self.std_node.test_transaction_acceptance(tx, with_witness=True, accepted=segwit_activated)
1069 # Now create something that looks like a P2PKH output. This won't be spendable.
1070 scriptPubKey = CScript([OP_0, hash160(witness_hash)])
1071 tx2 = CTransaction()
1072 if segwit_activated:
1073 # if tx was accepted, then we spend the second output.
1074 tx2.vin = [CTxIn(COutPoint(tx.sha256, 1), b"")]
1075 tx2.vout = [CTxOut(7000, scriptPubKey)]
1076 tx2.wit.vtxinwit.append(CTxInWitness())
1077 tx2.wit.vtxinwit[0].scriptWitness.stack = [witness_program]
1078 else:
1079 # if tx wasn't accepted, we just re-spend the p2sh output we started with.
1080 tx2.vin = [CTxIn(COutPoint(p2sh_tx.sha256, 0), CScript([witness_program]))]
1081 tx2.vout = [CTxOut(p2sh_tx.vout[0].nValue-1000, scriptPubKey)]
1082 tx2.rehash()
1084 self.std_node.test_transaction_acceptance(tx2, with_witness=True, accepted=segwit_activated)
1086 # Now update self.utxo for later tests.
1087 tx3 = CTransaction()
1088 if segwit_activated:
1089 # tx and tx2 were both accepted. Don't bother trying to reclaim the
1090 # P2PKH output; just send tx's first output back to an anyone-can-spend.
1091 sync_mempools([self.nodes[0], self.nodes[1]])
1092 tx3.vin = [CTxIn(COutPoint(tx.sha256, 0), b"")]
1093 tx3.vout = [CTxOut(tx.vout[0].nValue-1000, CScript([OP_TRUE]))]
1094 tx3.wit.vtxinwit.append(CTxInWitness())
1095 tx3.wit.vtxinwit[0].scriptWitness.stack = [witness_program]
1096 tx3.rehash()
1097 self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=True)
1098 else:
1099 # tx and tx2 didn't go anywhere; just clean up the p2sh_tx output.
1100 tx3.vin = [CTxIn(COutPoint(p2sh_tx.sha256, 0), CScript([witness_program]))]
1101 tx3.vout = [CTxOut(p2sh_tx.vout[0].nValue-1000, witness_program)]
1102 tx3.rehash()
1103 self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=True)
1105 self.nodes[0].generate(1)
1106 sync_blocks(self.nodes)
1107 self.utxo.pop(0)
1108 self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue))
1109 assert_equal(len(self.nodes[1].getrawmempool()), 0)
1112 # Verify that future segwit upgraded transactions are non-standard,
1113 # but valid in blocks. Can run this before and after segwit activation.
1114 def test_segwit_versions(self):
1115 self.log.info("Testing standardness/consensus for segwit versions (0-16)")
1116 assert(len(self.utxo))
1117 NUM_TESTS = 17 # will test OP_0, OP1, ..., OP_16
1118 if (len(self.utxo) < NUM_TESTS):
1119 tx = CTransaction()
1120 tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b""))
1121 split_value = (self.utxo[0].nValue - 4000) // NUM_TESTS
1122 for i in range(NUM_TESTS):
1123 tx.vout.append(CTxOut(split_value, CScript([OP_TRUE])))
1124 tx.rehash()
1125 block = self.build_next_block()
1126 self.update_witness_block_with_transactions(block, [tx])
1127 self.test_node.test_witness_block(block, accepted=True)
1128 self.utxo.pop(0)
1129 for i in range(NUM_TESTS):
1130 self.utxo.append(UTXO(tx.sha256, i, split_value))
1132 sync_blocks(self.nodes)
1133 temp_utxo = []
1134 tx = CTransaction()
1135 count = 0
1136 witness_program = CScript([OP_TRUE])
1137 witness_hash = sha256(witness_program)
1138 assert_equal(len(self.nodes[1].getrawmempool()), 0)
1139 for version in list(range(OP_1, OP_16+1)) + [OP_0]:
1140 count += 1
1141 # First try to spend to a future version segwit scriptPubKey.
1142 scriptPubKey = CScript([CScriptOp(version), witness_hash])
1143 tx.vin = [CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")]
1144 tx.vout = [CTxOut(self.utxo[0].nValue-1000, scriptPubKey)]
1145 tx.rehash()
1146 self.std_node.test_transaction_acceptance(tx, with_witness=True, accepted=False)
1147 self.test_node.test_transaction_acceptance(tx, with_witness=True, accepted=True)
1148 self.utxo.pop(0)
1149 temp_utxo.append(UTXO(tx.sha256, 0, tx.vout[0].nValue))
1151 self.nodes[0].generate(1) # Mine all the transactions
1152 sync_blocks(self.nodes)
1153 assert(len(self.nodes[0].getrawmempool()) == 0)
1155 # Finally, verify that version 0 -> version 1 transactions
1156 # are non-standard
1157 scriptPubKey = CScript([CScriptOp(OP_1), witness_hash])
1158 tx2 = CTransaction()
1159 tx2.vin = [CTxIn(COutPoint(tx.sha256, 0), b"")]
1160 tx2.vout = [CTxOut(tx.vout[0].nValue-1000, scriptPubKey)]
1161 tx2.wit.vtxinwit.append(CTxInWitness())
1162 tx2.wit.vtxinwit[0].scriptWitness.stack = [ witness_program ]
1163 tx2.rehash()
1164 # Gets accepted to test_node, because standardness of outputs isn't
1165 # checked with fRequireStandard
1166 self.test_node.test_transaction_acceptance(tx2, with_witness=True, accepted=True)
1167 self.std_node.test_transaction_acceptance(tx2, with_witness=True, accepted=False)
1168 temp_utxo.pop() # last entry in temp_utxo was the output we just spent
1169 temp_utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue))
1171 # Spend everything in temp_utxo back to an OP_TRUE output.
1172 tx3 = CTransaction()
1173 total_value = 0
1174 for i in temp_utxo:
1175 tx3.vin.append(CTxIn(COutPoint(i.sha256, i.n), b""))
1176 tx3.wit.vtxinwit.append(CTxInWitness())
1177 total_value += i.nValue
1178 tx3.wit.vtxinwit[-1].scriptWitness.stack = [witness_program]
1179 tx3.vout.append(CTxOut(total_value - 1000, CScript([OP_TRUE])))
1180 tx3.rehash()
1181 # Spending a higher version witness output is not allowed by policy,
1182 # even with fRequireStandard=false.
1183 self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=False)
1184 self.test_node.sync_with_ping()
1185 with mininode_lock:
1186 assert(b"reserved for soft-fork upgrades" in self.test_node.last_message["reject"].reason)
1188 # Building a block with the transaction must be valid, however.
1189 block = self.build_next_block()
1190 self.update_witness_block_with_transactions(block, [tx2, tx3])
1191 self.test_node.test_witness_block(block, accepted=True)
1192 sync_blocks(self.nodes)
1194 # Add utxo to our list
1195 self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue))
1198 def test_premature_coinbase_witness_spend(self):
1199 self.log.info("Testing premature coinbase witness spend")
1200 block = self.build_next_block()
1201 # Change the output of the block to be a witness output.
1202 witness_program = CScript([OP_TRUE])
1203 witness_hash = sha256(witness_program)
1204 scriptPubKey = CScript([OP_0, witness_hash])
1205 block.vtx[0].vout[0].scriptPubKey = scriptPubKey
1206 # This next line will rehash the coinbase and update the merkle
1207 # root, and solve.
1208 self.update_witness_block_with_transactions(block, [])
1209 self.test_node.test_witness_block(block, accepted=True)
1211 spend_tx = CTransaction()
1212 spend_tx.vin = [CTxIn(COutPoint(block.vtx[0].sha256, 0), b"")]
1213 spend_tx.vout = [CTxOut(block.vtx[0].vout[0].nValue, witness_program)]
1214 spend_tx.wit.vtxinwit.append(CTxInWitness())
1215 spend_tx.wit.vtxinwit[0].scriptWitness.stack = [ witness_program ]
1216 spend_tx.rehash()
1218 # Now test a premature spend.
1219 self.nodes[0].generate(98)
1220 sync_blocks(self.nodes)
1221 block2 = self.build_next_block()
1222 self.update_witness_block_with_transactions(block2, [spend_tx])
1223 self.test_node.test_witness_block(block2, accepted=False)
1225 # Advancing one more block should allow the spend.
1226 self.nodes[0].generate(1)
1227 block2 = self.build_next_block()
1228 self.update_witness_block_with_transactions(block2, [spend_tx])
1229 self.test_node.test_witness_block(block2, accepted=True)
1230 sync_blocks(self.nodes)
1233 def test_signature_version_1(self):
1234 self.log.info("Testing segwit signature hash version 1")
1235 key = CECKey()
1236 key.set_secretbytes(b"9")
1237 pubkey = CPubKey(key.get_pubkey())
1239 witness_program = CScript([pubkey, CScriptOp(OP_CHECKSIG)])
1240 witness_hash = sha256(witness_program)
1241 scriptPubKey = CScript([OP_0, witness_hash])
1243 # First create a witness output for use in the tests.
1244 assert(len(self.utxo))
1245 tx = CTransaction()
1246 tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b""))
1247 tx.vout.append(CTxOut(self.utxo[0].nValue-1000, scriptPubKey))
1248 tx.rehash()
1250 self.test_node.test_transaction_acceptance(tx, with_witness=True, accepted=True)
1251 # Mine this transaction in preparation for following tests.
1252 block = self.build_next_block()
1253 self.update_witness_block_with_transactions(block, [tx])
1254 self.test_node.test_witness_block(block, accepted=True)
1255 sync_blocks(self.nodes)
1256 self.utxo.pop(0)
1258 # Test each hashtype
1259 prev_utxo = UTXO(tx.sha256, 0, tx.vout[0].nValue)
1260 for sigflag in [ 0, SIGHASH_ANYONECANPAY ]:
1261 for hashtype in [SIGHASH_ALL, SIGHASH_NONE, SIGHASH_SINGLE]:
1262 hashtype |= sigflag
1263 block = self.build_next_block()
1264 tx = CTransaction()
1265 tx.vin.append(CTxIn(COutPoint(prev_utxo.sha256, prev_utxo.n), b""))
1266 tx.vout.append(CTxOut(prev_utxo.nValue - 1000, scriptPubKey))
1267 tx.wit.vtxinwit.append(CTxInWitness())
1268 # Too-large input value
1269 sign_P2PK_witness_input(witness_program, tx, 0, hashtype, prev_utxo.nValue+1, key)
1270 self.update_witness_block_with_transactions(block, [tx])
1271 self.test_node.test_witness_block(block, accepted=False)
1273 # Too-small input value
1274 sign_P2PK_witness_input(witness_program, tx, 0, hashtype, prev_utxo.nValue-1, key)
1275 block.vtx.pop() # remove last tx
1276 self.update_witness_block_with_transactions(block, [tx])
1277 self.test_node.test_witness_block(block, accepted=False)
1279 # Now try correct value
1280 sign_P2PK_witness_input(witness_program, tx, 0, hashtype, prev_utxo.nValue, key)
1281 block.vtx.pop()
1282 self.update_witness_block_with_transactions(block, [tx])
1283 self.test_node.test_witness_block(block, accepted=True)
1285 prev_utxo = UTXO(tx.sha256, 0, tx.vout[0].nValue)
1287 # Test combinations of signature hashes.
1288 # Split the utxo into a lot of outputs.
1289 # Randomly choose up to 10 to spend, sign with different hashtypes, and
1290 # output to a random number of outputs. Repeat NUM_TESTS times.
1291 # Ensure that we've tested a situation where we use SIGHASH_SINGLE with
1292 # an input index > number of outputs.
1293 NUM_TESTS = 500
1294 temp_utxos = []
1295 tx = CTransaction()
1296 tx.vin.append(CTxIn(COutPoint(prev_utxo.sha256, prev_utxo.n), b""))
1297 split_value = prev_utxo.nValue // NUM_TESTS
1298 for i in range(NUM_TESTS):
1299 tx.vout.append(CTxOut(split_value, scriptPubKey))
1300 tx.wit.vtxinwit.append(CTxInWitness())
1301 sign_P2PK_witness_input(witness_program, tx, 0, SIGHASH_ALL, prev_utxo.nValue, key)
1302 for i in range(NUM_TESTS):
1303 temp_utxos.append(UTXO(tx.sha256, i, split_value))
1305 block = self.build_next_block()
1306 self.update_witness_block_with_transactions(block, [tx])
1307 self.test_node.test_witness_block(block, accepted=True)
1309 block = self.build_next_block()
1310 used_sighash_single_out_of_bounds = False
1311 for i in range(NUM_TESTS):
1312 # Ping regularly to keep the connection alive
1313 if (not i % 100):
1314 self.test_node.sync_with_ping()
1315 # Choose random number of inputs to use.
1316 num_inputs = random.randint(1, 10)
1317 # Create a slight bias for producing more utxos
1318 num_outputs = random.randint(1, 11)
1319 random.shuffle(temp_utxos)
1320 assert(len(temp_utxos) > num_inputs)
1321 tx = CTransaction()
1322 total_value = 0
1323 for i in range(num_inputs):
1324 tx.vin.append(CTxIn(COutPoint(temp_utxos[i].sha256, temp_utxos[i].n), b""))
1325 tx.wit.vtxinwit.append(CTxInWitness())
1326 total_value += temp_utxos[i].nValue
1327 split_value = total_value // num_outputs
1328 for i in range(num_outputs):
1329 tx.vout.append(CTxOut(split_value, scriptPubKey))
1330 for i in range(num_inputs):
1331 # Now try to sign each input, using a random hashtype.
1332 anyonecanpay = 0
1333 if random.randint(0, 1):
1334 anyonecanpay = SIGHASH_ANYONECANPAY
1335 hashtype = random.randint(1, 3) | anyonecanpay
1336 sign_P2PK_witness_input(witness_program, tx, i, hashtype, temp_utxos[i].nValue, key)
1337 if (hashtype == SIGHASH_SINGLE and i >= num_outputs):
1338 used_sighash_single_out_of_bounds = True
1339 tx.rehash()
1340 for i in range(num_outputs):
1341 temp_utxos.append(UTXO(tx.sha256, i, split_value))
1342 temp_utxos = temp_utxos[num_inputs:]
1344 block.vtx.append(tx)
1346 # Test the block periodically, if we're close to maxblocksize
1347 if (get_virtual_size(block) > MAX_BLOCK_BASE_SIZE - 1000):
1348 self.update_witness_block_with_transactions(block, [])
1349 self.test_node.test_witness_block(block, accepted=True)
1350 block = self.build_next_block()
1352 if (not used_sighash_single_out_of_bounds):
1353 self.log.info("WARNING: this test run didn't attempt SIGHASH_SINGLE with out-of-bounds index value")
1354 # Test the transactions we've added to the block
1355 if (len(block.vtx) > 1):
1356 self.update_witness_block_with_transactions(block, [])
1357 self.test_node.test_witness_block(block, accepted=True)
1359 # Now test witness version 0 P2PKH transactions
1360 pubkeyhash = hash160(pubkey)
1361 scriptPKH = CScript([OP_0, pubkeyhash])
1362 tx = CTransaction()
1363 tx.vin.append(CTxIn(COutPoint(temp_utxos[0].sha256, temp_utxos[0].n), b""))
1364 tx.vout.append(CTxOut(temp_utxos[0].nValue, scriptPKH))
1365 tx.wit.vtxinwit.append(CTxInWitness())
1366 sign_P2PK_witness_input(witness_program, tx, 0, SIGHASH_ALL, temp_utxos[0].nValue, key)
1367 tx2 = CTransaction()
1368 tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b""))
1369 tx2.vout.append(CTxOut(tx.vout[0].nValue, CScript([OP_TRUE])))
1371 script = GetP2PKHScript(pubkeyhash)
1372 sig_hash = SegwitVersion1SignatureHash(script, tx2, 0, SIGHASH_ALL, tx.vout[0].nValue)
1373 signature = key.sign(sig_hash) + b'\x01' # 0x1 is SIGHASH_ALL
1375 # Check that we can't have a scriptSig
1376 tx2.vin[0].scriptSig = CScript([signature, pubkey])
1377 block = self.build_next_block()
1378 self.update_witness_block_with_transactions(block, [tx, tx2])
1379 self.test_node.test_witness_block(block, accepted=False)
1381 # Move the signature to the witness.
1382 block.vtx.pop()
1383 tx2.wit.vtxinwit.append(CTxInWitness())
1384 tx2.wit.vtxinwit[0].scriptWitness.stack = [signature, pubkey]
1385 tx2.vin[0].scriptSig = b""
1386 tx2.rehash()
1388 self.update_witness_block_with_transactions(block, [tx2])
1389 self.test_node.test_witness_block(block, accepted=True)
1391 temp_utxos.pop(0)
1393 # Update self.utxos for later tests. Just spend everything in
1394 # temp_utxos to a corresponding entry in self.utxos
1395 tx = CTransaction()
1396 index = 0
1397 for i in temp_utxos:
1398 # Just spend to our usual anyone-can-spend output
1399 # Use SIGHASH_SINGLE|SIGHASH_ANYONECANPAY so we can build up
1400 # the signatures as we go.
1401 tx.vin.append(CTxIn(COutPoint(i.sha256, i.n), b""))
1402 tx.vout.append(CTxOut(i.nValue, CScript([OP_TRUE])))
1403 tx.wit.vtxinwit.append(CTxInWitness())
1404 sign_P2PK_witness_input(witness_program, tx, index, SIGHASH_SINGLE|SIGHASH_ANYONECANPAY, i.nValue, key)
1405 index += 1
1406 block = self.build_next_block()
1407 self.update_witness_block_with_transactions(block, [tx])
1408 self.test_node.test_witness_block(block, accepted=True)
1410 for i in range(len(tx.vout)):
1411 self.utxo.append(UTXO(tx.sha256, i, tx.vout[i].nValue))
1414 # Test P2SH wrapped witness programs.
1415 def test_p2sh_witness(self, segwit_activated):
1416 self.log.info("Testing P2SH witness transactions")
1418 assert(len(self.utxo))
1420 # Prepare the p2sh-wrapped witness output
1421 witness_program = CScript([OP_DROP, OP_TRUE])
1422 witness_hash = sha256(witness_program)
1423 p2wsh_pubkey = CScript([OP_0, witness_hash])
1424 p2sh_witness_hash = hash160(p2wsh_pubkey)
1425 scriptPubKey = CScript([OP_HASH160, p2sh_witness_hash, OP_EQUAL])
1426 scriptSig = CScript([p2wsh_pubkey]) # a push of the redeem script
1428 # Fund the P2SH output
1429 tx = CTransaction()
1430 tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b""))
1431 tx.vout.append(CTxOut(self.utxo[0].nValue-1000, scriptPubKey))
1432 tx.rehash()
1434 # Verify mempool acceptance and block validity
1435 self.test_node.test_transaction_acceptance(tx, with_witness=False, accepted=True)
1436 block = self.build_next_block()
1437 self.update_witness_block_with_transactions(block, [tx])
1438 self.test_node.test_witness_block(block, accepted=True, with_witness=segwit_activated)
1439 sync_blocks(self.nodes)
1441 # Now test attempts to spend the output.
1442 spend_tx = CTransaction()
1443 spend_tx.vin.append(CTxIn(COutPoint(tx.sha256, 0), scriptSig))
1444 spend_tx.vout.append(CTxOut(tx.vout[0].nValue-1000, CScript([OP_TRUE])))
1445 spend_tx.rehash()
1447 # This transaction should not be accepted into the mempool pre- or
1448 # post-segwit. Mempool acceptance will use SCRIPT_VERIFY_WITNESS which
1449 # will require a witness to spend a witness program regardless of
1450 # segwit activation. Note that older bitcoind's that are not
1451 # segwit-aware would also reject this for failing CLEANSTACK.
1452 self.test_node.test_transaction_acceptance(spend_tx, with_witness=False, accepted=False)
1454 # Try to put the witness script in the scriptSig, should also fail.
1455 spend_tx.vin[0].scriptSig = CScript([p2wsh_pubkey, b'a'])
1456 spend_tx.rehash()
1457 self.test_node.test_transaction_acceptance(spend_tx, with_witness=False, accepted=False)
1459 # Now put the witness script in the witness, should succeed after
1460 # segwit activates.
1461 spend_tx.vin[0].scriptSig = scriptSig
1462 spend_tx.rehash()
1463 spend_tx.wit.vtxinwit.append(CTxInWitness())
1464 spend_tx.wit.vtxinwit[0].scriptWitness.stack = [ b'a', witness_program ]
1466 # Verify mempool acceptance
1467 self.test_node.test_transaction_acceptance(spend_tx, with_witness=True, accepted=segwit_activated)
1468 block = self.build_next_block()
1469 self.update_witness_block_with_transactions(block, [spend_tx])
1471 # If we're before activation, then sending this without witnesses
1472 # should be valid. If we're after activation, then sending this with
1473 # witnesses should be valid.
1474 if segwit_activated:
1475 self.test_node.test_witness_block(block, accepted=True)
1476 else:
1477 self.test_node.test_witness_block(block, accepted=True, with_witness=False)
1479 # Update self.utxo
1480 self.utxo.pop(0)
1481 self.utxo.append(UTXO(spend_tx.sha256, 0, spend_tx.vout[0].nValue))
1483 # Test the behavior of starting up a segwit-aware node after the softfork
1484 # has activated. As segwit requires different block data than pre-segwit
1485 # nodes would have stored, this requires special handling.
1486 # To enable this test, pass --oldbinary=<path-to-pre-segwit-bitcoind> to
1487 # the test.
1488 def test_upgrade_after_activation(self, node_id):
1489 self.log.info("Testing software upgrade after softfork activation")
1491 assert(node_id != 0) # node0 is assumed to be a segwit-active bitcoind
1493 # Make sure the nodes are all up
1494 sync_blocks(self.nodes)
1496 # Restart with the new binary
1497 self.stop_node(node_id)
1498 self.start_node(node_id, extra_args=["-vbparams=segwit:0:999999999999"])
1499 connect_nodes(self.nodes[0], node_id)
1501 sync_blocks(self.nodes)
1503 # Make sure that this peer thinks segwit has activated.
1504 assert(get_bip9_status(self.nodes[node_id], 'segwit')['status'] == "active")
1506 # Make sure this peers blocks match those of node0.
1507 height = self.nodes[node_id].getblockcount()
1508 while height >= 0:
1509 block_hash = self.nodes[node_id].getblockhash(height)
1510 assert_equal(block_hash, self.nodes[0].getblockhash(height))
1511 assert_equal(self.nodes[0].getblock(block_hash), self.nodes[node_id].getblock(block_hash))
1512 height -= 1
1515 def test_witness_sigops(self):
1516 '''Ensure sigop counting is correct inside witnesses.'''
1517 self.log.info("Testing sigops limit")
1519 assert(len(self.utxo))
1521 # Keep this under MAX_OPS_PER_SCRIPT (201)
1522 witness_program = CScript([OP_TRUE, OP_IF, OP_TRUE, OP_ELSE] + [OP_CHECKMULTISIG]*5 + [OP_CHECKSIG]*193 + [OP_ENDIF])
1523 witness_hash = sha256(witness_program)
1524 scriptPubKey = CScript([OP_0, witness_hash])
1526 sigops_per_script = 20*5 + 193*1
1527 # We'll produce 2 extra outputs, one with a program that would take us
1528 # over max sig ops, and one with a program that would exactly reach max
1529 # sig ops
1530 outputs = (MAX_SIGOP_COST // sigops_per_script) + 2
1531 extra_sigops_available = MAX_SIGOP_COST % sigops_per_script
1533 # We chose the number of checkmultisigs/checksigs to make this work:
1534 assert(extra_sigops_available < 100) # steer clear of MAX_OPS_PER_SCRIPT
1536 # This script, when spent with the first
1537 # N(=MAX_SIGOP_COST//sigops_per_script) outputs of our transaction,
1538 # would push us just over the block sigop limit.
1539 witness_program_toomany = CScript([OP_TRUE, OP_IF, OP_TRUE, OP_ELSE] + [OP_CHECKSIG]*(extra_sigops_available + 1) + [OP_ENDIF])
1540 witness_hash_toomany = sha256(witness_program_toomany)
1541 scriptPubKey_toomany = CScript([OP_0, witness_hash_toomany])
1543 # If we spend this script instead, we would exactly reach our sigop
1544 # limit (for witness sigops).
1545 witness_program_justright = CScript([OP_TRUE, OP_IF, OP_TRUE, OP_ELSE] + [OP_CHECKSIG]*(extra_sigops_available) + [OP_ENDIF])
1546 witness_hash_justright = sha256(witness_program_justright)
1547 scriptPubKey_justright = CScript([OP_0, witness_hash_justright])
1549 # First split our available utxo into a bunch of outputs
1550 split_value = self.utxo[0].nValue // outputs
1551 tx = CTransaction()
1552 tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b""))
1553 for i in range(outputs):
1554 tx.vout.append(CTxOut(split_value, scriptPubKey))
1555 tx.vout[-2].scriptPubKey = scriptPubKey_toomany
1556 tx.vout[-1].scriptPubKey = scriptPubKey_justright
1557 tx.rehash()
1559 block_1 = self.build_next_block()
1560 self.update_witness_block_with_transactions(block_1, [tx])
1561 self.test_node.test_witness_block(block_1, accepted=True)
1563 tx2 = CTransaction()
1564 # If we try to spend the first n-1 outputs from tx, that should be
1565 # too many sigops.
1566 total_value = 0
1567 for i in range(outputs-1):
1568 tx2.vin.append(CTxIn(COutPoint(tx.sha256, i), b""))
1569 tx2.wit.vtxinwit.append(CTxInWitness())
1570 tx2.wit.vtxinwit[-1].scriptWitness.stack = [ witness_program ]
1571 total_value += tx.vout[i].nValue
1572 tx2.wit.vtxinwit[-1].scriptWitness.stack = [ witness_program_toomany ]
1573 tx2.vout.append(CTxOut(total_value, CScript([OP_TRUE])))
1574 tx2.rehash()
1576 block_2 = self.build_next_block()
1577 self.update_witness_block_with_transactions(block_2, [tx2])
1578 self.test_node.test_witness_block(block_2, accepted=False)
1580 # Try dropping the last input in tx2, and add an output that has
1581 # too many sigops (contributing to legacy sigop count).
1582 checksig_count = (extra_sigops_available // 4) + 1
1583 scriptPubKey_checksigs = CScript([OP_CHECKSIG]*checksig_count)
1584 tx2.vout.append(CTxOut(0, scriptPubKey_checksigs))
1585 tx2.vin.pop()
1586 tx2.wit.vtxinwit.pop()
1587 tx2.vout[0].nValue -= tx.vout[-2].nValue
1588 tx2.rehash()
1589 block_3 = self.build_next_block()
1590 self.update_witness_block_with_transactions(block_3, [tx2])
1591 self.test_node.test_witness_block(block_3, accepted=False)
1593 # If we drop the last checksig in this output, the tx should succeed.
1594 block_4 = self.build_next_block()
1595 tx2.vout[-1].scriptPubKey = CScript([OP_CHECKSIG]*(checksig_count-1))
1596 tx2.rehash()
1597 self.update_witness_block_with_transactions(block_4, [tx2])
1598 self.test_node.test_witness_block(block_4, accepted=True)
1600 # Reset the tip back down for the next test
1601 sync_blocks(self.nodes)
1602 for x in self.nodes:
1603 x.invalidateblock(block_4.hash)
1605 # Try replacing the last input of tx2 to be spending the last
1606 # output of tx
1607 block_5 = self.build_next_block()
1608 tx2.vout.pop()
1609 tx2.vin.append(CTxIn(COutPoint(tx.sha256, outputs-1), b""))
1610 tx2.wit.vtxinwit.append(CTxInWitness())
1611 tx2.wit.vtxinwit[-1].scriptWitness.stack = [ witness_program_justright ]
1612 tx2.rehash()
1613 self.update_witness_block_with_transactions(block_5, [tx2])
1614 self.test_node.test_witness_block(block_5, accepted=True)
1616 # TODO: test p2sh sigop counting
1618 def test_getblocktemplate_before_lockin(self):
1619 self.log.info("Testing getblocktemplate setting of segwit versionbit (before lockin)")
1620 # Node0 is segwit aware, node2 is not.
1621 for node in [self.nodes[0], self.nodes[2]]:
1622 gbt_results = node.getblocktemplate()
1623 block_version = gbt_results['version']
1624 # If we're not indicating segwit support, we will still be
1625 # signalling for segwit activation.
1626 assert_equal((block_version & (1 << VB_WITNESS_BIT) != 0), node == self.nodes[0])
1627 # If we don't specify the segwit rule, then we won't get a default
1628 # commitment.
1629 assert('default_witness_commitment' not in gbt_results)
1631 # Workaround:
1632 # Can either change the tip, or change the mempool and wait 5 seconds
1633 # to trigger a recomputation of getblocktemplate.
1634 txid = int(self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1), 16)
1635 # Using mocktime lets us avoid sleep()
1636 sync_mempools(self.nodes)
1637 self.nodes[0].setmocktime(int(time.time())+10)
1638 self.nodes[2].setmocktime(int(time.time())+10)
1640 for node in [self.nodes[0], self.nodes[2]]:
1641 gbt_results = node.getblocktemplate({"rules" : ["segwit"]})
1642 block_version = gbt_results['version']
1643 if node == self.nodes[2]:
1644 # If this is a non-segwit node, we should still not get a witness
1645 # commitment, nor a version bit signalling segwit.
1646 assert_equal(block_version & (1 << VB_WITNESS_BIT), 0)
1647 assert('default_witness_commitment' not in gbt_results)
1648 else:
1649 # For segwit-aware nodes, check the version bit and the witness
1650 # commitment are correct.
1651 assert(block_version & (1 << VB_WITNESS_BIT) != 0)
1652 assert('default_witness_commitment' in gbt_results)
1653 witness_commitment = gbt_results['default_witness_commitment']
1655 # Check that default_witness_commitment is present.
1656 witness_root = CBlock.get_merkle_root([ser_uint256(0),
1657 ser_uint256(txid)])
1658 script = get_witness_script(witness_root, 0)
1659 assert_equal(witness_commitment, bytes_to_hex_str(script))
1661 # undo mocktime
1662 self.nodes[0].setmocktime(0)
1663 self.nodes[2].setmocktime(0)
1665 # Uncompressed pubkeys are no longer supported in default relay policy,
1666 # but (for now) are still valid in blocks.
1667 def test_uncompressed_pubkey(self):
1668 self.log.info("Testing uncompressed pubkeys")
1669 # Segwit transactions using uncompressed pubkeys are not accepted
1670 # under default policy, but should still pass consensus.
1671 key = CECKey()
1672 key.set_secretbytes(b"9")
1673 key.set_compressed(False)
1674 pubkey = CPubKey(key.get_pubkey())
1675 assert_equal(len(pubkey), 65) # This should be an uncompressed pubkey
1677 assert(len(self.utxo) > 0)
1678 utxo = self.utxo.pop(0)
1680 # Test 1: P2WPKH
1681 # First create a P2WPKH output that uses an uncompressed pubkey
1682 pubkeyhash = hash160(pubkey)
1683 scriptPKH = CScript([OP_0, pubkeyhash])
1684 tx = CTransaction()
1685 tx.vin.append(CTxIn(COutPoint(utxo.sha256, utxo.n), b""))
1686 tx.vout.append(CTxOut(utxo.nValue-1000, scriptPKH))
1687 tx.rehash()
1689 # Confirm it in a block.
1690 block = self.build_next_block()
1691 self.update_witness_block_with_transactions(block, [tx])
1692 self.test_node.test_witness_block(block, accepted=True)
1694 # Now try to spend it. Send it to a P2WSH output, which we'll
1695 # use in the next test.
1696 witness_program = CScript([pubkey, CScriptOp(OP_CHECKSIG)])
1697 witness_hash = sha256(witness_program)
1698 scriptWSH = CScript([OP_0, witness_hash])
1700 tx2 = CTransaction()
1701 tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b""))
1702 tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, scriptWSH))
1703 script = GetP2PKHScript(pubkeyhash)
1704 sig_hash = SegwitVersion1SignatureHash(script, tx2, 0, SIGHASH_ALL, tx.vout[0].nValue)
1705 signature = key.sign(sig_hash) + b'\x01' # 0x1 is SIGHASH_ALL
1706 tx2.wit.vtxinwit.append(CTxInWitness())
1707 tx2.wit.vtxinwit[0].scriptWitness.stack = [ signature, pubkey ]
1708 tx2.rehash()
1710 # Should fail policy test.
1711 self.test_node.test_transaction_acceptance(tx2, True, False, b'non-mandatory-script-verify-flag (Using non-compressed keys in segwit)')
1712 # But passes consensus.
1713 block = self.build_next_block()
1714 self.update_witness_block_with_transactions(block, [tx2])
1715 self.test_node.test_witness_block(block, accepted=True)
1717 # Test 2: P2WSH
1718 # Try to spend the P2WSH output created in last test.
1719 # Send it to a P2SH(P2WSH) output, which we'll use in the next test.
1720 p2sh_witness_hash = hash160(scriptWSH)
1721 scriptP2SH = CScript([OP_HASH160, p2sh_witness_hash, OP_EQUAL])
1722 scriptSig = CScript([scriptWSH])
1724 tx3 = CTransaction()
1725 tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), b""))
1726 tx3.vout.append(CTxOut(tx2.vout[0].nValue-1000, scriptP2SH))
1727 tx3.wit.vtxinwit.append(CTxInWitness())
1728 sign_P2PK_witness_input(witness_program, tx3, 0, SIGHASH_ALL, tx2.vout[0].nValue, key)
1730 # Should fail policy test.
1731 self.test_node.test_transaction_acceptance(tx3, True, False, b'non-mandatory-script-verify-flag (Using non-compressed keys in segwit)')
1732 # But passes consensus.
1733 block = self.build_next_block()
1734 self.update_witness_block_with_transactions(block, [tx3])
1735 self.test_node.test_witness_block(block, accepted=True)
1737 # Test 3: P2SH(P2WSH)
1738 # Try to spend the P2SH output created in the last test.
1739 # Send it to a P2PKH output, which we'll use in the next test.
1740 scriptPubKey = GetP2PKHScript(pubkeyhash)
1741 tx4 = CTransaction()
1742 tx4.vin.append(CTxIn(COutPoint(tx3.sha256, 0), scriptSig))
1743 tx4.vout.append(CTxOut(tx3.vout[0].nValue-1000, scriptPubKey))
1744 tx4.wit.vtxinwit.append(CTxInWitness())
1745 sign_P2PK_witness_input(witness_program, tx4, 0, SIGHASH_ALL, tx3.vout[0].nValue, key)
1747 # Should fail policy test.
1748 self.test_node.test_transaction_acceptance(tx4, True, False, b'non-mandatory-script-verify-flag (Using non-compressed keys in segwit)')
1749 block = self.build_next_block()
1750 self.update_witness_block_with_transactions(block, [tx4])
1751 self.test_node.test_witness_block(block, accepted=True)
1753 # Test 4: Uncompressed pubkeys should still be valid in non-segwit
1754 # transactions.
1755 tx5 = CTransaction()
1756 tx5.vin.append(CTxIn(COutPoint(tx4.sha256, 0), b""))
1757 tx5.vout.append(CTxOut(tx4.vout[0].nValue-1000, CScript([OP_TRUE])))
1758 (sig_hash, err) = SignatureHash(scriptPubKey, tx5, 0, SIGHASH_ALL)
1759 signature = key.sign(sig_hash) + b'\x01' # 0x1 is SIGHASH_ALL
1760 tx5.vin[0].scriptSig = CScript([signature, pubkey])
1761 tx5.rehash()
1762 # Should pass policy and consensus.
1763 self.test_node.test_transaction_acceptance(tx5, True, True)
1764 block = self.build_next_block()
1765 self.update_witness_block_with_transactions(block, [tx5])
1766 self.test_node.test_witness_block(block, accepted=True)
1767 self.utxo.append(UTXO(tx5.sha256, 0, tx5.vout[0].nValue))
1769 def test_non_standard_witness(self):
1770 self.log.info("Testing detection of non-standard P2WSH witness")
1771 pad = chr(1).encode('latin-1')
1773 # Create scripts for tests
1774 scripts = []
1775 scripts.append(CScript([OP_DROP] * 100))
1776 scripts.append(CScript([OP_DROP] * 99))
1777 scripts.append(CScript([pad * 59] * 59 + [OP_DROP] * 60))
1778 scripts.append(CScript([pad * 59] * 59 + [OP_DROP] * 61))
1780 p2wsh_scripts = []
1782 assert(len(self.utxo))
1783 tx = CTransaction()
1784 tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b""))
1786 # For each script, generate a pair of P2WSH and P2SH-P2WSH output.
1787 outputvalue = (self.utxo[0].nValue - 1000) // (len(scripts) * 2)
1788 for i in scripts:
1789 p2wsh = CScript([OP_0, sha256(i)])
1790 p2sh = hash160(p2wsh)
1791 p2wsh_scripts.append(p2wsh)
1792 tx.vout.append(CTxOut(outputvalue, p2wsh))
1793 tx.vout.append(CTxOut(outputvalue, CScript([OP_HASH160, p2sh, OP_EQUAL])))
1794 tx.rehash()
1795 txid = tx.sha256
1796 self.test_node.test_transaction_acceptance(tx, with_witness=False, accepted=True)
1798 self.nodes[0].generate(1)
1799 sync_blocks(self.nodes)
1801 # Creating transactions for tests
1802 p2wsh_txs = []
1803 p2sh_txs = []
1804 for i in range(len(scripts)):
1805 p2wsh_tx = CTransaction()
1806 p2wsh_tx.vin.append(CTxIn(COutPoint(txid,i*2)))
1807 p2wsh_tx.vout.append(CTxOut(outputvalue - 5000, CScript([OP_0, hash160(hex_str_to_bytes(""))])))
1808 p2wsh_tx.wit.vtxinwit.append(CTxInWitness())
1809 p2wsh_tx.rehash()
1810 p2wsh_txs.append(p2wsh_tx)
1811 p2sh_tx = CTransaction()
1812 p2sh_tx.vin.append(CTxIn(COutPoint(txid,i*2+1), CScript([p2wsh_scripts[i]])))
1813 p2sh_tx.vout.append(CTxOut(outputvalue - 5000, CScript([OP_0, hash160(hex_str_to_bytes(""))])))
1814 p2sh_tx.wit.vtxinwit.append(CTxInWitness())
1815 p2sh_tx.rehash()
1816 p2sh_txs.append(p2sh_tx)
1818 # Testing native P2WSH
1819 # Witness stack size, excluding witnessScript, over 100 is non-standard
1820 p2wsh_txs[0].wit.vtxinwit[0].scriptWitness.stack = [pad] * 101 + [scripts[0]]
1821 self.std_node.test_transaction_acceptance(p2wsh_txs[0], True, False, b'bad-witness-nonstandard')
1822 # Non-standard nodes should accept
1823 self.test_node.test_transaction_acceptance(p2wsh_txs[0], True, True)
1825 # Stack element size over 80 bytes is non-standard
1826 p2wsh_txs[1].wit.vtxinwit[0].scriptWitness.stack = [pad * 81] * 100 + [scripts[1]]
1827 self.std_node.test_transaction_acceptance(p2wsh_txs[1], True, False, b'bad-witness-nonstandard')
1828 # Non-standard nodes should accept
1829 self.test_node.test_transaction_acceptance(p2wsh_txs[1], True, True)
1830 # Standard nodes should accept if element size is not over 80 bytes
1831 p2wsh_txs[1].wit.vtxinwit[0].scriptWitness.stack = [pad * 80] * 100 + [scripts[1]]
1832 self.std_node.test_transaction_acceptance(p2wsh_txs[1], True, True)
1834 # witnessScript size at 3600 bytes is standard
1835 p2wsh_txs[2].wit.vtxinwit[0].scriptWitness.stack = [pad, pad, scripts[2]]
1836 self.test_node.test_transaction_acceptance(p2wsh_txs[2], True, True)
1837 self.std_node.test_transaction_acceptance(p2wsh_txs[2], True, True)
1839 # witnessScript size at 3601 bytes is non-standard
1840 p2wsh_txs[3].wit.vtxinwit[0].scriptWitness.stack = [pad, pad, pad, scripts[3]]
1841 self.std_node.test_transaction_acceptance(p2wsh_txs[3], True, False, b'bad-witness-nonstandard')
1842 # Non-standard nodes should accept
1843 self.test_node.test_transaction_acceptance(p2wsh_txs[3], True, True)
1845 # Repeating the same tests with P2SH-P2WSH
1846 p2sh_txs[0].wit.vtxinwit[0].scriptWitness.stack = [pad] * 101 + [scripts[0]]
1847 self.std_node.test_transaction_acceptance(p2sh_txs[0], True, False, b'bad-witness-nonstandard')
1848 self.test_node.test_transaction_acceptance(p2sh_txs[0], True, True)
1849 p2sh_txs[1].wit.vtxinwit[0].scriptWitness.stack = [pad * 81] * 100 + [scripts[1]]
1850 self.std_node.test_transaction_acceptance(p2sh_txs[1], True, False, b'bad-witness-nonstandard')
1851 self.test_node.test_transaction_acceptance(p2sh_txs[1], True, True)
1852 p2sh_txs[1].wit.vtxinwit[0].scriptWitness.stack = [pad * 80] * 100 + [scripts[1]]
1853 self.std_node.test_transaction_acceptance(p2sh_txs[1], True, True)
1854 p2sh_txs[2].wit.vtxinwit[0].scriptWitness.stack = [pad, pad, scripts[2]]
1855 self.test_node.test_transaction_acceptance(p2sh_txs[2], True, True)
1856 self.std_node.test_transaction_acceptance(p2sh_txs[2], True, True)
1857 p2sh_txs[3].wit.vtxinwit[0].scriptWitness.stack = [pad, pad, pad, scripts[3]]
1858 self.std_node.test_transaction_acceptance(p2sh_txs[3], True, False, b'bad-witness-nonstandard')
1859 self.test_node.test_transaction_acceptance(p2sh_txs[3], True, True)
1861 self.nodes[0].generate(1) # Mine and clean up the mempool of non-standard node
1862 # Valid but non-standard transactions in a block should be accepted by standard node
1863 sync_blocks(self.nodes)
1864 assert_equal(len(self.nodes[0].getrawmempool()), 0)
1865 assert_equal(len(self.nodes[1].getrawmempool()), 0)
1867 self.utxo.pop(0)
1870 def run_test(self):
1871 # Setup the p2p connections and start up the network thread.
1872 # self.test_node sets NODE_WITNESS|NODE_NETWORK
1873 self.test_node = self.nodes[0].add_p2p_connection(TestNode(self.nodes[0].rpc), services=NODE_NETWORK|NODE_WITNESS)
1874 # self.old_node sets only NODE_NETWORK
1875 self.old_node = self.nodes[0].add_p2p_connection(TestNode(self.nodes[0].rpc), services=NODE_NETWORK)
1876 # self.std_node is for testing node1 (fRequireStandard=true)
1877 self.std_node = self.nodes[1].add_p2p_connection(TestNode(self.nodes[1].rpc), services=NODE_NETWORK|NODE_WITNESS)
1879 NetworkThread().start() # Start up network handling in another thread
1881 # Keep a place to store utxo's that can be used in later tests
1882 self.utxo = []
1884 # Test logic begins here
1885 self.test_node.wait_for_verack()
1887 self.log.info("Starting tests before segwit lock in:")
1889 self.test_witness_services() # Verifies NODE_WITNESS
1890 self.test_non_witness_transaction() # non-witness tx's are accepted
1891 self.test_unnecessary_witness_before_segwit_activation()
1892 self.test_block_relay(segwit_activated=False)
1894 # Advance to segwit being 'started'
1895 self.advance_to_segwit_started()
1896 sync_blocks(self.nodes)
1897 self.test_getblocktemplate_before_lockin()
1899 sync_blocks(self.nodes)
1901 # At lockin, nothing should change.
1902 self.log.info("Testing behavior post lockin, pre-activation")
1903 self.advance_to_segwit_lockin()
1905 # Retest unnecessary witnesses
1906 self.test_unnecessary_witness_before_segwit_activation()
1907 self.test_witness_tx_relay_before_segwit_activation()
1908 self.test_block_relay(segwit_activated=False)
1909 self.test_p2sh_witness(segwit_activated=False)
1910 self.test_standardness_v0(segwit_activated=False)
1912 sync_blocks(self.nodes)
1914 # Now activate segwit
1915 self.log.info("Testing behavior after segwit activation")
1916 self.advance_to_segwit_active()
1918 sync_blocks(self.nodes)
1920 # Test P2SH witness handling again
1921 self.test_p2sh_witness(segwit_activated=True)
1922 self.test_witness_commitments()
1923 self.test_block_malleability()
1924 self.test_witness_block_size()
1925 self.test_submit_block()
1926 self.test_extra_witness_data()
1927 self.test_max_witness_push_length()
1928 self.test_max_witness_program_length()
1929 self.test_witness_input_length()
1930 self.test_block_relay(segwit_activated=True)
1931 self.test_tx_relay_after_segwit_activation()
1932 self.test_standardness_v0(segwit_activated=True)
1933 self.test_segwit_versions()
1934 self.test_premature_coinbase_witness_spend()
1935 self.test_uncompressed_pubkey()
1936 self.test_signature_version_1()
1937 self.test_non_standard_witness()
1938 sync_blocks(self.nodes)
1939 self.test_upgrade_after_activation(node_id=2)
1940 self.test_witness_sigops()
1943 if __name__ == '__main__':
1944 SegWitTest().main()