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