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

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