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