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 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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.blockstore import BlockStore
  18. from test_framework.test_framework import ComparisonTestFramework
  19. from test_framework.util import *
  20. from test_framework.mininode import CTransaction, NetworkThread
  21. from test_framework.blocktools import create_coinbase, create_block
  22. from test_framework.comptool import TestInstance, TestManager
  23. from test_framework.script import CScript, OP_1NEGATE, OP_CHECKSEQUENCEVERIFY, OP_DROP
  24. from io import BytesIO
  25. import time
  26. import itertools
  27. class BIP9SoftForksTest(ComparisonTestFramework):
  28. def __init__(self):
  29. super().__init__()
  30. self.num_nodes = 1
  31. def setup_network(self):
  32. self.nodes = start_nodes(self.num_nodes, self.options.tmpdir,
  33. extra_args=[['-whitelist=127.0.0.1']],
  34. binary=[self.options.testbinary])
  35. def run_test(self):
  36. self.test = TestManager(self, self.options.tmpdir)
  37. self.test.add_all_connections(self.nodes)
  38. NetworkThread().start() # Start up network handling in another thread
  39. self.test.run()
  40. def create_transaction(self, node, coinbase, to_address, amount):
  41. from_txid = node.getblock(coinbase)['tx'][0]
  42. inputs = [{ "txid" : from_txid, "vout" : 0}]
  43. outputs = { to_address : amount }
  44. rawtx = node.createrawtransaction(inputs, outputs)
  45. tx = CTransaction()
  46. f = BytesIO(hex_str_to_bytes(rawtx))
  47. tx.deserialize(f)
  48. tx.nVersion = 2
  49. return tx
  50. def sign_transaction(self, node, tx):
  51. signresult = node.signrawtransaction(bytes_to_hex_str(tx.serialize()))
  52. tx = CTransaction()
  53. f = BytesIO(hex_str_to_bytes(signresult['hex']))
  54. tx.deserialize(f)
  55. return tx
  56. def generate_blocks(self, number, version, test_blocks = []):
  57. for i in range(number):
  58. block = create_block(self.tip, create_coinbase(self.height), self.last_block_time + 1)
  59. block.nVersion = version
  60. block.rehash()
  61. block.solve()
  62. test_blocks.append([block, True])
  63. self.last_block_time += 1
  64. self.tip = block.sha256
  65. self.height += 1
  66. return test_blocks
  67. def get_bip9_status(self, key):
  68. info = self.nodes[0].getblockchaininfo()
  69. return info['bip9_softforks'][key]
  70. def test_BIP(self, bipName, activated_version, invalidate, invalidatePostSignature, bitno):
  71. assert_equal(self.get_bip9_status(bipName)['status'], 'defined')
  72. assert_equal(self.get_bip9_status(bipName)['since'], 0)
  73. # generate some coins for later
  74. self.coinbase_blocks = self.nodes[0].generate(2)
  75. self.height = 3 # height of the next block to build
  76. self.tip = int("0x" + self.nodes[0].getbestblockhash(), 0)
  77. self.nodeaddress = self.nodes[0].getnewaddress()
  78. self.last_block_time = int(time.time())
  79. assert_equal(self.get_bip9_status(bipName)['status'], 'defined')
  80. assert_equal(self.get_bip9_status(bipName)['since'], 0)
  81. tmpl = self.nodes[0].getblocktemplate({})
  82. assert(bipName not in tmpl['rules'])
  83. assert(bipName not in tmpl['vbavailable'])
  84. assert_equal(tmpl['vbrequired'], 0)
  85. assert_equal(tmpl['version'], 0x20000000)
  86. # Test 1
  87. # Advance from DEFINED to STARTED
  88. test_blocks = self.generate_blocks(141, 4)
  89. yield TestInstance(test_blocks, sync_every_block=False)
  90. assert_equal(self.get_bip9_status(bipName)['status'], 'started')
  91. assert_equal(self.get_bip9_status(bipName)['since'], 144)
  92. assert_equal(self.get_bip9_status(bipName)['statistics']['elapsed'], 0)
  93. assert_equal(self.get_bip9_status(bipName)['statistics']['count'], 0)
  94. tmpl = self.nodes[0].getblocktemplate({})
  95. assert(bipName not in tmpl['rules'])
  96. assert_equal(tmpl['vbavailable'][bipName], bitno)
  97. assert_equal(tmpl['vbrequired'], 0)
  98. assert(tmpl['version'] & activated_version)
  99. # Test 1-A
  100. # check stats after max number of "signalling not" blocks such that LOCKED_IN still possible this period
  101. test_blocks = self.generate_blocks(36, 4, test_blocks) # 0x00000004 (signalling not)
  102. test_blocks = self.generate_blocks(10, activated_version) # 0x20000001 (signalling ready)
  103. yield TestInstance(test_blocks, sync_every_block=False)
  104. assert_equal(self.get_bip9_status(bipName)['statistics']['elapsed'], 46)
  105. assert_equal(self.get_bip9_status(bipName)['statistics']['count'], 10)
  106. assert_equal(self.get_bip9_status(bipName)['statistics']['possible'], True)
  107. # Test 1-B
  108. # check stats after one additional "signalling not" block -- LOCKED_IN no longer possible this period
  109. test_blocks = self.generate_blocks(1, 4, test_blocks) # 0x00000004 (signalling not)
  110. yield TestInstance(test_blocks, sync_every_block=False)
  111. assert_equal(self.get_bip9_status(bipName)['statistics']['elapsed'], 47)
  112. assert_equal(self.get_bip9_status(bipName)['statistics']['count'], 10)
  113. assert_equal(self.get_bip9_status(bipName)['statistics']['possible'], False)
  114. # Test 1-C
  115. # finish period with "ready" blocks, but soft fork will still fail to advance to LOCKED_IN
  116. test_blocks = self.generate_blocks(97, activated_version) # 0x20000001 (signalling ready)
  117. yield TestInstance(test_blocks, sync_every_block=False)
  118. assert_equal(self.get_bip9_status(bipName)['statistics']['elapsed'], 0)
  119. assert_equal(self.get_bip9_status(bipName)['statistics']['count'], 0)
  120. assert_equal(self.get_bip9_status(bipName)['statistics']['possible'], True)
  121. assert_equal(self.get_bip9_status(bipName)['status'], 'started')
  122. # Test 2
  123. # Fail to achieve LOCKED_IN 100 out of 144 signal bit 1
  124. # using a variety of bits to simulate multiple parallel softforks
  125. test_blocks = self.generate_blocks(50, activated_version) # 0x20000001 (signalling ready)
  126. test_blocks = self.generate_blocks(20, 4, test_blocks) # 0x00000004 (signalling not)
  127. test_blocks = self.generate_blocks(50, activated_version, test_blocks) # 0x20000101 (signalling ready)
  128. test_blocks = self.generate_blocks(24, 4, test_blocks) # 0x20010000 (signalling not)
  129. yield TestInstance(test_blocks, sync_every_block=False)
  130. assert_equal(self.get_bip9_status(bipName)['status'], 'started')
  131. assert_equal(self.get_bip9_status(bipName)['since'], 144)
  132. assert_equal(self.get_bip9_status(bipName)['statistics']['elapsed'], 0)
  133. assert_equal(self.get_bip9_status(bipName)['statistics']['count'], 0)
  134. tmpl = self.nodes[0].getblocktemplate({})
  135. assert(bipName not in tmpl['rules'])
  136. assert_equal(tmpl['vbavailable'][bipName], bitno)
  137. assert_equal(tmpl['vbrequired'], 0)
  138. assert(tmpl['version'] & activated_version)
  139. # Test 3
  140. # 108 out of 144 signal bit 1 to achieve LOCKED_IN
  141. # using a variety of bits to simulate multiple parallel softforks
  142. test_blocks = self.generate_blocks(57, activated_version) # 0x20000001 (signalling ready)
  143. test_blocks = self.generate_blocks(26, 4, test_blocks) # 0x00000004 (signalling not)
  144. test_blocks = self.generate_blocks(50, activated_version, test_blocks) # 0x20000101 (signalling ready)
  145. test_blocks = self.generate_blocks(10, 4, test_blocks) # 0x20010000 (signalling not)
  146. yield TestInstance(test_blocks, sync_every_block=False)
  147. # check counting stats and "possible" flag before last block of this period achieves LOCKED_IN...
  148. assert_equal(self.get_bip9_status(bipName)['statistics']['elapsed'], 143)
  149. assert_equal(self.get_bip9_status(bipName)['statistics']['count'], 107)
  150. assert_equal(self.get_bip9_status(bipName)['statistics']['possible'], True)
  151. assert_equal(self.get_bip9_status(bipName)['status'], 'started')
  152. # ...continue with Test 3
  153. test_blocks = self.generate_blocks(1, activated_version) # 0x20000001 (signalling ready)
  154. yield TestInstance(test_blocks, sync_every_block=False)
  155. assert_equal(self.get_bip9_status(bipName)['status'], 'locked_in')
  156. assert_equal(self.get_bip9_status(bipName)['since'], 576)
  157. tmpl = self.nodes[0].getblocktemplate({})
  158. assert(bipName not in tmpl['rules'])
  159. # Test 4
  160. # 143 more version 536870913 blocks (waiting period-1)
  161. test_blocks = self.generate_blocks(143, 4)
  162. yield TestInstance(test_blocks, sync_every_block=False)
  163. assert_equal(self.get_bip9_status(bipName)['status'], 'locked_in')
  164. assert_equal(self.get_bip9_status(bipName)['since'], 576)
  165. tmpl = self.nodes[0].getblocktemplate({})
  166. assert(bipName not in tmpl['rules'])
  167. # Test 5
  168. # Check that the new rule is enforced
  169. spendtx = self.create_transaction(self.nodes[0],
  170. self.coinbase_blocks[0], self.nodeaddress, 1.0)
  171. invalidate(spendtx)
  172. spendtx = self.sign_transaction(self.nodes[0], spendtx)
  173. spendtx.rehash()
  174. invalidatePostSignature(spendtx)
  175. spendtx.rehash()
  176. block = create_block(self.tip, create_coinbase(self.height), self.last_block_time + 1)
  177. block.nVersion = activated_version
  178. block.vtx.append(spendtx)
  179. block.hashMerkleRoot = block.calc_merkle_root()
  180. block.rehash()
  181. block.solve()
  182. self.last_block_time += 1
  183. self.tip = block.sha256
  184. self.height += 1
  185. yield TestInstance([[block, True]])
  186. assert_equal(self.get_bip9_status(bipName)['status'], 'active')
  187. assert_equal(self.get_bip9_status(bipName)['since'], 720)
  188. tmpl = self.nodes[0].getblocktemplate({})
  189. assert(bipName in tmpl['rules'])
  190. assert(bipName not in tmpl['vbavailable'])
  191. assert_equal(tmpl['vbrequired'], 0)
  192. assert(not (tmpl['version'] & (1 << bitno)))
  193. # Test 6
  194. # Check that the new sequence lock rules are enforced
  195. spendtx = self.create_transaction(self.nodes[0],
  196. self.coinbase_blocks[1], self.nodeaddress, 1.0)
  197. invalidate(spendtx)
  198. spendtx = self.sign_transaction(self.nodes[0], spendtx)
  199. spendtx.rehash()
  200. invalidatePostSignature(spendtx)
  201. spendtx.rehash()
  202. block = create_block(self.tip, create_coinbase(self.height), self.last_block_time + 1)
  203. block.nVersion = 5
  204. block.vtx.append(spendtx)
  205. block.hashMerkleRoot = block.calc_merkle_root()
  206. block.rehash()
  207. block.solve()
  208. self.last_block_time += 1
  209. yield TestInstance([[block, False]])
  210. # Restart all
  211. self.test.block_store.close()
  212. stop_nodes(self.nodes)
  213. shutil.rmtree(self.options.tmpdir)
  214. self.setup_chain()
  215. self.setup_network()
  216. self.test.block_store = BlockStore(self.options.tmpdir)
  217. self.test.clear_all_connections()
  218. self.test.add_all_connections(self.nodes)
  219. NetworkThread().start() # Start up network handling in another thread
  220. def get_tests(self):
  221. for test in itertools.chain(
  222. self.test_BIP('csv', 0x20000001, self.sequence_lock_invalidate, self.donothing, 0),
  223. self.test_BIP('csv', 0x20000001, self.mtp_invalidate, self.donothing, 0),
  224. self.test_BIP('csv', 0x20000001, self.donothing, self.csv_invalidate, 0)
  225. ):
  226. yield test
  227. def donothing(self, tx):
  228. return
  229. def csv_invalidate(self, tx):
  230. """Modify the signature in vin 0 of the tx to fail CSV
  231. Prepends -1 CSV DROP in the scriptSig itself.
  232. """
  233. tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_CHECKSEQUENCEVERIFY, OP_DROP] +
  234. list(CScript(tx.vin[0].scriptSig)))
  235. def sequence_lock_invalidate(self, tx):
  236. """Modify the nSequence to make it fails once sequence lock rule is
  237. activated (high timespan).
  238. """
  239. tx.vin[0].nSequence = 0x00FFFFFF
  240. tx.nLockTime = 0
  241. def mtp_invalidate(self, tx):
  242. """Modify the nLockTime to make it fails once MTP rule is activated."""
  243. # Disable Sequence lock, Activate nLockTime
  244. tx.vin[0].nSequence = 0x90FFFFFF
  245. tx.nLockTime = self.last_block_time
  246. if __name__ == '__main__':
  247. BIP9SoftForksTest().main()