9090MAX_SIGOP_COST = 80000
9191
9292
93- # Calculate the virtual size of a witness block:
94- # (base + witness/4)
9593def get_virtual_size (witness_block ):
94+ """Calculate the virtual size of a witness block.
95+
96+ Virtual size is base + witness/4."""
9697 base_size = len (witness_block .serialize (with_witness = False ))
9798 total_size = len (witness_block .serialize (with_witness = True ))
9899 # the "+3" is so we round up
@@ -171,25 +172,24 @@ def request_block(self, blockhash, inv_type, timeout=60):
171172 self .wait_for_block (blockhash , timeout )
172173 return self .last_message ["block" ].block
173174
174- # Used to keep track of anyone-can-spend outputs that we can use in the tests
175175class UTXO ():
176+ """Used to keep track of anyone-can-spend outputs that we can use in the tests."""
176177 def __init__ (self , sha256 , n , value ):
177178 self .sha256 = sha256
178179 self .n = n
179180 self .nValue = value
180181
181- # Helper for getting the script associated with a P2PKH
182182def get_p2pkh_script (pubkeyhash ):
183+ """Get the script associated with a P2PKH."""
183184 return CScript ([CScriptOp (OP_DUP ), CScriptOp (OP_HASH160 ), pubkeyhash , CScriptOp (OP_EQUALVERIFY ), CScriptOp (OP_CHECKSIG )])
184185
185- # Add signature for a P2PK witness program.
186186def sign_p2pk_witness_input (script , tx_to , in_idx , hashtype , value , key ):
187+ """Add signature for a P2PK witness program."""
187188 tx_hash = SegwitVersion1SignatureHash (script , tx_to , in_idx , hashtype , value )
188189 signature = key .sign (tx_hash ) + chr (hashtype ).encode ('latin-1' )
189190 tx_to .wit .vtxinwit [in_idx ].scriptWitness .stack = [signature , script ]
190191 tx_to .rehash ()
191192
192-
193193class SegWitTest (BitcoinTestFramework ):
194194 def set_test_params (self ):
195195 self .setup_clean_chain = True
@@ -203,9 +203,10 @@ def setup_network(self):
203203 connect_nodes (self .nodes [0 ], 2 )
204204 self .sync_all ()
205205
206- ''' Helpers '''
207- # Build a block on top of node0's tip.
206+ # Helper functions
207+
208208 def build_next_block (self , version = 4 ):
209+ """Build a block on top of node0's tip."""
209210 tip = self .nodes [0 ].getbestblockhash ()
210211 height = self .nodes [0 ].getblockcount () + 1
211212 block_time = self .nodes [0 ].getblockheader (tip )["mediantime" ] + 1
@@ -214,21 +215,21 @@ def build_next_block(self, version=4):
214215 block .rehash ()
215216 return block
216217
217- # Adds list of transactions to block, adds witness commitment, then solves.
218218 def update_witness_block_with_transactions (self , block , tx_list , nonce = 0 ):
219+ """Add list of transactions to block, adds witness commitment, then solves."""
219220 block .vtx .extend (tx_list )
220221 add_witness_commitment (block , nonce )
221222 block .solve ()
222223 return
223224
224- ''' Individual tests '''
225+ # Individual tests
226+
225227 def test_witness_services (self ):
226228 self .log .info ("Verifying NODE_WITNESS service bit" )
227229 assert ((self .test_node .nServices & NODE_WITNESS ) != 0 )
228230
229- # See if sending a regular transaction works, and create a utxo
230- # to use in later tests.
231231 def test_non_witness_transaction (self ):
232+ """See if sending a regular transaction works, and create a utxo to use in later tests."""
232233 # Mine a block with an anyone-can-spend coinbase,
233234 # let it mature, then try to spend it.
234235 self .log .info ("Testing non-witness transaction" )
@@ -257,8 +258,8 @@ def test_non_witness_transaction(self):
257258 self .utxo .append (UTXO (tx .sha256 , 0 , 49 * 100000000 ))
258259 self .nodes [0 ].generate (1 )
259260
260- # Verify that blocks with witnesses are rejected before activation.
261261 def test_unnecessary_witness_before_segwit_activation (self ):
262+ """Verify that blocks with witnesses are rejected before activation."""
262263 self .log .info ("Testing behavior of unnecessary witnesses" )
263264 # For now, rely on earlier tests to have created at least one utxo for
264265 # us to use
@@ -299,14 +300,17 @@ def test_unnecessary_witness_before_segwit_activation(self):
299300 self .utxo .pop (0 )
300301 self .utxo .append (UTXO (tx .sha256 , 0 , tx .vout [0 ].nValue ))
301302
302- # ~6 months after segwit activation, the SCRIPT_VERIFY_WITNESS flag was
303- # backdated so that it applies to all blocks, going back to the genesis
304- # block.
305- #
306- # Consequently, version 0 witness outputs are never spendable without
307- # witness, and so can't be spent before segwit activation (the point at which
308- # blocks are permitted to contain witnesses).
309303 def test_v0_outputs_arent_spendable (self ):
304+ """Test that v0 outputs aren't spendable before segwit activation.
305+
306+ ~6 months after segwit activation, the SCRIPT_VERIFY_WITNESS flag was
307+ backdated so that it applies to all blocks, going back to the genesis
308+ block.
309+
310+ Consequently, version 0 witness outputs are never spendable without
311+ witness, and so can't be spent before segwit activation (the point at which
312+ blocks are permitted to contain witnesses)."""
313+
310314 self .log .info ("Testing that v0 witness program outputs aren't spendable before activation" )
311315
312316 assert len (self .utxo ), "self.utxo is empty"
@@ -374,8 +378,8 @@ def test_v0_outputs_arent_spendable(self):
374378 self .utxo .pop (0 )
375379 self .utxo .append (UTXO (txid , 2 , value ))
376380
377- # Mine enough blocks for segwit's vb state to be 'started'.
378381 def advance_to_segwit_started (self ):
382+ """Mine enough blocks for segwit's vb state to be 'started'."""
379383 height = self .nodes [0 ].getblockcount ()
380384 # Will need to rewrite the tests here if we are past the first period
381385 assert (height < VB_PERIOD - 1 )
@@ -385,10 +389,11 @@ def advance_to_segwit_started(self):
385389 self .nodes [0 ].generate (VB_PERIOD - height - 1 )
386390 assert_equal (get_bip9_status (self .nodes [0 ], 'segwit' )['status' ], 'started' )
387391
388- # Mine enough blocks to lock in segwit, but don't activate.
389- # TODO: we could verify that lockin only happens at the right threshold of
390- # signalling blocks, rather than just at the right period boundary.
391392 def advance_to_segwit_lockin (self ):
393+ """Mine enough blocks to lock in segwit, but don't activate."""
394+ # TODO: we could verify that lockin only happens at the right threshold of
395+ # signalling blocks, rather than just at the right period boundary.
396+
392397 height = self .nodes [0 ].getblockcount ()
393398 assert_equal (get_bip9_status (self .nodes [0 ], 'segwit' )['status' ], 'started' )
394399 # Advance to end of period, and verify lock-in happens at the end
@@ -399,19 +404,23 @@ def advance_to_segwit_lockin(self):
399404 self .nodes [0 ].generate (1 )
400405 assert_equal (get_bip9_status (self .nodes [0 ], 'segwit' )['status' ], 'locked_in' )
401406
402- # Mine enough blocks to activate segwit.
403- # TODO: we could verify that activation only happens at the right threshold
404- # of signalling blocks, rather than just at the right period boundary.
405407 def advance_to_segwit_active (self ):
408+ """Mine enough blocks to activate segwit."""
409+ # TODO: we could verify that activation only happens at the right threshold
410+ # of signalling blocks, rather than just at the right period boundary.
411+
406412 assert_equal (get_bip9_status (self .nodes [0 ], 'segwit' )['status' ], 'locked_in' )
407413 height = self .nodes [0 ].getblockcount ()
408414 self .nodes [0 ].generate (VB_PERIOD - (height % VB_PERIOD ) - 2 )
409415 assert_equal (get_bip9_status (self .nodes [0 ], 'segwit' )['status' ], 'locked_in' )
410416 self .nodes [0 ].generate (1 )
411417 assert_equal (get_bip9_status (self .nodes [0 ], 'segwit' )['status' ], 'active' )
412418
413- # This test can only be run after segwit has activated
414419 def test_witness_commitments (self ):
420+ """Test witness commitments.
421+
422+ This test can only be run after segwit has activated."""
423+
415424 self .log .info ("Testing witness commitments" )
416425
417426 # First try a correct witness commitment.
@@ -617,9 +626,8 @@ def test_witness_block_size(self):
617626 self .utxo .pop (0 )
618627 self .utxo .append (UTXO (block .vtx [- 1 ].sha256 , 0 , block .vtx [- 1 ].vout [0 ].nValue ))
619628
620- # submitblock will try to add the nonce automatically, so that mining
621- # software doesn't need to worry about doing so itself.
622629 def test_submit_block (self ):
630+ """Test that submitblock adds the nonce automatically when possible."""
623631 block = self .build_next_block ()
624632
625633 # Try using a custom nonce and then don't supply it.
@@ -653,8 +661,8 @@ def test_submit_block(self):
653661 # Tip should not advance!
654662 assert (self .nodes [0 ].getbestblockhash () != block_2 .hash )
655663
656- # Consensus tests of extra witness data in a transaction.
657664 def test_extra_witness_data (self ):
665+ """Test extra witness data in a transaction."""
658666 self .log .info ("Testing extra witness data in tx" )
659667
660668 assert (len (self .utxo ) > 0 )
@@ -729,7 +737,7 @@ def test_extra_witness_data(self):
729737 self .utxo .append (UTXO (tx2 .sha256 , 0 , tx2 .vout [0 ].nValue ))
730738
731739 def test_max_witness_push_length (self ):
732- ''' Should only allow up to 520 byte pushes in witness stack '''
740+ """Test that witness stack can only allow up to 520 byte pushes."""
733741 self .log .info ("Testing maximum witness push size" )
734742 MAX_SCRIPT_ELEMENT_SIZE = 520
735743 assert (len (self .utxo ))
@@ -768,8 +776,7 @@ def test_max_witness_push_length(self):
768776 self .utxo .append (UTXO (tx2 .sha256 , 0 , tx2 .vout [0 ].nValue ))
769777
770778 def test_max_witness_program_length (self ):
771- # Can create witness outputs that are long, but can't be greater than
772- # 10k bytes to successfully spend
779+ """Test that witness outputs greater than 10kB can't be spent."""
773780 self .log .info ("Testing maximum witness program length" )
774781 assert (len (self .utxo ))
775782 MAX_PROGRAM_LENGTH = 10000
@@ -817,7 +824,7 @@ def test_max_witness_program_length(self):
817824 self .utxo .append (UTXO (tx2 .sha256 , 0 , tx2 .vout [0 ].nValue ))
818825
819826 def test_witness_input_length (self ):
820- ''' Ensure that vin length must match vtxinwit length '''
827+ """Test that vin length must match vtxinwit length."""
821828 self .log .info ("Testing witness input length" )
822829 assert (len (self .utxo ))
823830
@@ -941,11 +948,14 @@ def test_witness_tx_relay_before_segwit_activation(self):
941948 self .utxo .pop (0 )
942949 self .utxo .append (UTXO (tx_hash , 0 , tx_value ))
943950
944- # After segwit activates, verify that mempool:
945- # - rejects transactions with unnecessary/extra witnesses
946- # - accepts transactions with valid witnesses
947- # and that witness transactions are relayed to non-upgraded peers.
948951 def test_tx_relay_after_segwit_activation (self ):
952+ """Test transaction relay after segwit activation.
953+
954+ After segwit activates, verify that mempool:
955+ - rejects transactions with unnecessary/extra witnesses
956+ - accepts transactions with valid witnesses
957+ and that witness transactions are relayed to non-upgraded peers."""
958+
949959 self .log .info ("Testing relay of witness transactions" )
950960 # Generate a transaction that doesn't require a witness, but send it
951961 # with a witness. Should be rejected because we can't use a witness
@@ -1032,10 +1042,11 @@ def test_tx_relay_after_segwit_activation(self):
10321042 self .utxo .pop (0 )
10331043 self .utxo .append (UTXO (tx3 .sha256 , 0 , tx3 .vout [0 ].nValue ))
10341044
1035- # Test that block requests to NODE_WITNESS peer are with MSG_WITNESS_FLAG
1036- # This is true regardless of segwit activation.
1037- # Also test that we don't ask for blocks from unupgraded peers
10381045 def test_block_relay (self , segwit_activated ):
1046+ """Test that block requests to NODE_WITNESS peer are with MSG_WITNESS_FLAG.
1047+
1048+ This is true regardless of segwit activation.
1049+ Also test that we don't ask for blocks from unupgraded peers."""
10391050 self .log .info ("Testing block relay" )
10401051
10411052 blocktype = 2 | MSG_WITNESS_FLAG
@@ -1127,8 +1138,12 @@ def test_block_relay(self, segwit_activated):
11271138 self .old_node .announce_tx_and_wait_for_getdata (block4 .vtx [0 ])
11281139 assert (block4 .sha256 not in self .old_node .getdataset )
11291140
1130- # V0 segwit outputs and inputs are always standard. V0 segwit inputs may only be mined after activation, but not before.
11311141 def test_standardness_v0 (self , segwit_activated ):
1142+ """Test V0 txout standardness.
1143+
1144+ V0 segwit outputs and inputs are always standard.
1145+ V0 segwit inputs may only be mined after activation, but not before."""
1146+
11321147 self .log .info ("Testing standardness of v0 outputs (%s activation)" % ("after" if segwit_activated else "before" ))
11331148 assert (len (self .utxo ))
11341149
@@ -1203,9 +1218,12 @@ def test_standardness_v0(self, segwit_activated):
12031218 self .utxo .append (UTXO (tx3 .sha256 , 0 , tx3 .vout [0 ].nValue ))
12041219 assert_equal (len (self .nodes [1 ].getrawmempool ()), 0 )
12051220
1206- # Verify that future segwit upgraded transactions are non-standard,
1207- # but valid in blocks. Can run this before and after segwit activation.
12081221 def test_segwit_versions (self ):
1222+ """Test validity of future segwit version transactions.
1223+
1224+ Future segwit version transactions are non-standard, but valid in blocks.
1225+ Can run this before and after segwit activation."""
1226+
12091227 self .log .info ("Testing standardness/consensus for segwit versions (0-16)" )
12101228 assert (len (self .utxo ))
12111229 num_tests = 17 # will test OP_0, OP1, ..., OP_16
@@ -1504,8 +1522,8 @@ def test_signature_version_1(self):
15041522 for i in range (len (tx .vout )):
15051523 self .utxo .append (UTXO (tx .sha256 , i , tx .vout [i ].nValue ))
15061524
1507- # Test P2SH wrapped witness programs.
15081525 def test_p2sh_witness (self , segwit_activated ):
1526+ """Test P2SH wrapped witness programs."""
15091527 self .log .info ("Testing P2SH witness transactions" )
15101528
15111529 assert (len (self .utxo ))
@@ -1574,12 +1592,8 @@ def test_p2sh_witness(self, segwit_activated):
15741592 self .utxo .pop (0 )
15751593 self .utxo .append (UTXO (spend_tx .sha256 , 0 , spend_tx .vout [0 ].nValue ))
15761594
1577- # Test the behavior of starting up a segwit-aware node after the softfork
1578- # has activated. As segwit requires different block data than pre-segwit
1579- # nodes would have stored, this requires special handling.
1580- # To enable this test, pass --oldbinary=<path-to-pre-segwit-bitcoind> to
1581- # the test.
15821595 def test_upgrade_after_activation (self , node_id ):
1596+ """Test the behavior of starting up a segwit-aware node after the softfork has activated."""
15831597 self .log .info ("Testing software upgrade after softfork activation" )
15841598
15851599 assert (node_id != 0 ) # node0 is assumed to be a segwit-active bitcoind
@@ -1606,7 +1620,7 @@ def test_upgrade_after_activation(self, node_id):
16061620 height -= 1
16071621
16081622 def test_witness_sigops (self ):
1609- '''Ensure sigop counting is correct inside witnesses.'''
1623+ """Test sigop counting is correct inside witnesses."""
16101624 self .log .info ("Testing sigops limit" )
16111625
16121626 assert (len (self .utxo ))
@@ -1755,9 +1769,12 @@ def test_getblocktemplate_before_lockin(self):
17551769 self .nodes [0 ].setmocktime (0 )
17561770 self .nodes [2 ].setmocktime (0 )
17571771
1758- # Uncompressed pubkeys are no longer supported in default relay policy,
1759- # but (for now) are still valid in blocks.
17601772 def test_uncompressed_pubkey (self ):
1773+ """Test uncompressed pubkey validity in segwit transactions.
1774+
1775+ Uncompressed pubkeys are no longer supported in default relay policy,
1776+ but (for now) are still valid in blocks."""
1777+
17611778 self .log .info ("Testing uncompressed pubkeys" )
17621779 # Segwit transactions using uncompressed pubkeys are not accepted
17631780 # under default policy, but should still pass consensus.
0 commit comments