You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

bip9-softforks.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2015-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 BIP 9 soft forks.
  6. Connect to a single node.
  7. regtest lock-in with 108/144 block signalling
  8. activation after a further 144 blocks
  9. mine 2 block and save coinbases for later use
  10. mine 141 blocks to transition from DEFINED to STARTED
  11. mine 100 blocks signalling readiness and 44 not in order to fail to change state this period
  12. mine 108 blocks signalling readiness and 36 blocks not signalling readiness (STARTED->LOCKED_IN)
  13. mine a further 143 blocks (LOCKED_IN)
  14. test that enforcement has not triggered (which triggers ACTIVE)
  15. test that enforcement has triggered
  16. """
  17. from test_framework.test_framework import ComparisonTestFramework
  18. from test_framework.util import *
  19. from test_framework.mininode import CTransaction, NetworkThread
  20. from test_framework.blocktools import create_coinbase, create_block
  21. from test_framework.comptool import TestInstance, TestManager
  22. from test_framework.script import CScript, OP_1NEGATE, OP_CHECKSEQUENCEVERIFY, OP_DROP
  23. from io import BytesIO
  24. import time
  25. import itertools
  26. class BIP9SoftForksTest(ComparisonTestFramework):
  27. def __init__(self):
  28. super().__init__()
  29. self.num_nodes = 1
  30. def setup_network(self):
  31. self.nodes = start_nodes(self.num_nodes, self.options.tmpdir,
  32. extra_args=[['-whitelist=127.0.0.1']],
  33. binary=[self.options.testbinary])
  34. def run_test(self):
  35. self.test = TestManager(self, self.options.tmpdir)
  36. self.test.add_all_connections(self.nodes)
  37. NetworkThread().start() # Start up network handling in another thread
  38. self.test.run()
  39. def create_transaction(self, node, coinbase, to_address, amount):
  40. from_txid = node.getblock(coinbase)['tx'][0]
  41. inputs = [{ "txid" : from_txid, "vout" : 0}]
  42. outputs = { to_address : amount }
  43. rawtx = node.createrawtransaction(inputs, outputs)
  44. tx = CTransaction()
  45. f = BytesIO(hex_str_to_bytes(rawtx))
  46. tx.deserialize(f)
  47. tx.nVersion = 2
  48. return tx
  49. def sign_transaction(self, node, tx):
  50. signresult = node.signrawtransaction(bytes_to_hex_str(tx.serialize()))
  51. tx = CTransaction()
  52. f = BytesIO(hex_str_to_bytes(signresult['hex']))
  53. tx.deserialize(f)
  54. return tx
  55. def generate_blocks(self, number, version, test_blocks = []):
  56. for i in range(number):
  57. block = create_block(self.tip, create_coinbase(self.height), self.last_block_time + 1)
  58. block.nVersion = version
  59. block.rehash()
  60. block.solve()
  61. test_blocks.append([block, True])
  62. self.last_block_time += 1
  63. self.tip = block.sha256
  64. self.height += 1
  65. return test_blocks
  66. def get_bip9_status(self, key):
  67. info = self.nodes[0].getblockchaininfo()
  68. return info['bip9_softforks'][key]
  69. def test_BIP(self, bipName, activated_version, invalidate, invalidatePostSignature, bitno):
  70. assert_equal(self.get_bip9_status(bipName)['status'], 'defined')
  71. assert_equal(self.get_bip9_status(bipName)['since'], 0)
  72. # generate some coins for later
  73. self.coinbase_blocks = self.nodes[0].generate(2)
  74. self.height = 3 # height of the next block to build
  75. self.tip = int("0x" + self.nodes[0].getbestblockhash(), 0)
  76. self.nodeaddress = self.nodes[0].getnewaddress()
  77. self.last_block_time = int(time.time())
  78. assert_equal(self.get_bip9_status(bipName)['status'], 'defined')
  79. assert_equal(self.get_bip9_status(bipName)['since'], 0)
  80. tmpl = self.nodes[0].getblocktemplate({})
  81. assert(bipName not in tmpl['rules'])
  82. assert(bipName not in tmpl['vbavailable'])
  83. assert_equal(tmpl['vbrequired'], 0)
  84. assert_equal(tmpl['version'], 0x20000000)
  85. # Test 1
  86. # Advance from DEFINED to STARTED
  87. test_blocks = self.generate_blocks(141, 4)
  88. yield TestInstance(test_blocks, sync_every_block=False)
  89. assert_equal(self.get_bip9_status(bipName)['status'], 'started')
  90. assert_equal(self.get_bip9_status(bipName)['since'], 144)
  91. tmpl = self.nodes[0].getblocktemplate({})
  92. assert(bipName not in tmpl['rules'])
  93. assert_equal(tmpl['vbavailable'][bipName], bitno)
  94. assert_equal(tmpl['vbrequired'], 0)
  95. assert(tmpl['version'] & activated_version)
  96. # Test 2
  97. # Fail to achieve LOCKED_IN 100 out of 144 signal bit 1
  98. # using a variety of bits to simulate multiple parallel softforks
  99. test_blocks = self.generate_blocks(50, activated_version) # 0x20000001 (signalling ready)
  100. test_blocks = self.generate_blocks(20, 4, test_blocks) # 0x00000004 (signalling not)
  101. test_blocks = self.generate_blocks(50, activated_version, test_blocks) # 0x20000101 (signalling ready)
  102. test_blocks = self.generate_blocks(24, 4, test_blocks) # 0x20010000 (signalling not)
  103. yield TestInstance(test_blocks, sync_every_block=False)
  104. assert_equal(self.get_bip9_status(bipName)['status'], 'started')
  105. assert_equal(self.get_bip9_status(bipName)['since'], 144)
  106. tmpl = self.nodes[0].getblocktemplate({})
  107. assert(bipName not in tmpl['rules'])
  108. assert_equal(tmpl['vbavailable'][bipName], bitno)
  109. assert_equal(tmpl['vbrequired'], 0)
  110. assert(tmpl['version'] & activated_version)
  111. # Test 3
  112. # 108 out of 144 signal bit 1 to achieve LOCKED_IN
  113. # using a variety of bits to simulate multiple parallel softforks
  114. test_blocks = self.generate_blocks(58, activated_version) # 0x20000001 (signalling ready)
  115. test_blocks = self.generate_blocks(26, 4, test_blocks) # 0x00000004 (signalling not)
  116. test_blocks = self.generate_blocks(50, activated_version, test_blocks) # 0x20000101 (signalling ready)
  117. test_blocks = self.generate_blocks(10, 4, test_blocks) # 0x20010000 (signalling not)
  118. yield TestInstance(test_blocks, sync_every_block=False)
  119. assert_equal(self.get_bip9_status(bipName)['status'], 'locked_in')
  120. assert_equal(self.get_bip9_status(bipName)['since'], 432)
  121. tmpl = self.nodes[0].getblocktemplate({})
  122. assert(bipName not in tmpl['rules'])
  123. # Test 4
  124. # 143 more version 536870913 blocks (waiting period-1)
  125. test_blocks = self.generate_blocks(143, 4)
  126. yield TestInstance(test_blocks, sync_every_block=False)
  127. assert_equal(self.get_bip9_status(bipName)['status'], 'locked_in')
  128. assert_equal(self.get_bip9_status(bipName)['since'], 432)
  129. tmpl = self.nodes[0].getblocktemplate({})
  130. assert(bipName not in tmpl['rules'])
  131. # Test 5
  132. # Check that the new rule is enforced
  133. spendtx = self.create_transaction(self.nodes[0],
  134. self.coinbase_blocks[0], self.nodeaddress, 1.0)
  135. invalidate(spendtx)
  136. spendtx = self.sign_transaction(self.nodes[0], spendtx)
  137. spendtx.rehash()
  138. invalidatePostSignature(spendtx)
  139. spendtx.rehash()
  140. block = create_block(self.tip, create_coinbase(self.height), self.last_block_time + 1)
  141. block.nVersion = activated_version
  142. block.vtx.append(spendtx)
  143. block.hashMerkleRoot = block.calc_merkle_root()
  144. block.rehash()
  145. block.solve()
  146. self.last_block_time += 1
  147. self.tip = block.sha256
  148. self.height += 1
  149. yield TestInstance([[block, True]])
  150. assert_equal(self.get_bip9_status(bipName)['status'], 'active')
  151. assert_equal(self.get_bip9_status(bipName)['since'], 576)
  152. tmpl = self.nodes[0].getblocktemplate({})
  153. assert(bipName in tmpl['rules'])
  154. assert(bipName not in tmpl['vbavailable'])
  155. assert_equal(tmpl['vbrequired'], 0)
  156. assert(not (tmpl['version'] & (1 << bitno)))
  157. # Test 6
  158. # Check that the new sequence lock rules are enforced
  159. spendtx = self.create_transaction(self.nodes[0],
  160. self.coinbase_blocks[1], self.nodeaddress, 1.0)
  161. invalidate(spendtx)
  162. spendtx = self.sign_transaction(self.nodes[0], spendtx)
  163. spendtx.rehash()
  164. invalidatePostSignature(spendtx)
  165. spendtx.rehash()
  166. block = create_block(self.tip, create_coinbase(self.height), self.last_block_time + 1)
  167. block.nVersion = 5
  168. block.vtx.append(spendtx)
  169. block.hashMerkleRoot = block.calc_merkle_root()
  170. block.rehash()
  171. block.solve()
  172. self.last_block_time += 1
  173. yield TestInstance([[block, False]])
  174. # Restart all
  175. self.test.clear_all_connections()
  176. stop_nodes(self.nodes)
  177. shutil.rmtree(self.options.tmpdir + "/node0")
  178. self.setup_chain()
  179. self.setup_network()
  180. self.test.add_all_connections(self.nodes)
  181. NetworkThread().start()
  182. self.test.test_nodes[0].wait_for_verack()
  183. def get_tests(self):
  184. for test in itertools.chain(
  185. self.test_BIP('csv', 0x20000001, self.sequence_lock_invalidate, self.donothing, 0),
  186. self.test_BIP('csv', 0x20000001, self.mtp_invalidate, self.donothing, 0),
  187. self.test_BIP('csv', 0x20000001, self.donothing, self.csv_invalidate, 0)
  188. ):
  189. yield test
  190. def donothing(self, tx):
  191. return
  192. def csv_invalidate(self, tx):
  193. """Modify the signature in vin 0 of the tx to fail CSV
  194. Prepends -1 CSV DROP in the scriptSig itself.
  195. """
  196. tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_CHECKSEQUENCEVERIFY, OP_DROP] +
  197. list(CScript(tx.vin[0].scriptSig)))
  198. def sequence_lock_invalidate(self, tx):
  199. """Modify the nSequence to make it fails once sequence lock rule is
  200. activated (high timespan).
  201. """
  202. tx.vin[0].nSequence = 0x00FFFFFF
  203. tx.nLockTime = 0
  204. def mtp_invalidate(self, tx):
  205. """Modify the nLockTime to make it fails once MTP rule is activated."""
  206. # Disable Sequence lock, Activate nLockTime
  207. tx.vin[0].nSequence = 0x90FFFFFF
  208. tx.nLockTime = self.last_block_time
  209. if __name__ == '__main__':
  210. BIP9SoftForksTest().main()