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.

assumevalid.py 8.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2014-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 logic for skipping signature validation on old blocks.
  6. Test logic for skipping signature validation on blocks which we've assumed
  7. valid (https://github.com/bitcoin/bitcoin/pull/9484)
  8. We build a chain that includes and invalid signature for one of the
  9. transactions:
  10. 0: genesis block
  11. 1: block 1 with coinbase transaction output.
  12. 2-101: bury that block with 100 blocks so the coinbase transaction
  13. output can be spent
  14. 102: a block containing a transaction spending the coinbase
  15. transaction output. The transaction has an invalid signature.
  16. 103-2202: bury the bad block with just over two weeks' worth of blocks
  17. (2100 blocks)
  18. Start three nodes:
  19. - node0 has no -assumevalid parameter. Try to sync to block 2202. It will
  20. reject block 102 and only sync as far as block 101
  21. - node1 has -assumevalid set to the hash of block 102. Try to sync to
  22. block 2202. node1 will sync all the way to block 2202.
  23. - node2 has -assumevalid set to the hash of block 102. Try to sync to
  24. block 200. node2 will reject block 102 since it's assumed valid, but it
  25. isn't buried by at least two weeks' work.
  26. """
  27. import time
  28. from test_framework.blocktools import (create_block, create_coinbase)
  29. from test_framework.key import CECKey
  30. from test_framework.mininode import (CBlockHeader,
  31. COutPoint,
  32. CTransaction,
  33. CTxIn,
  34. CTxOut,
  35. NetworkThread,
  36. NodeConn,
  37. NodeConnCB,
  38. msg_block,
  39. msg_headers)
  40. from test_framework.script import (CScript, OP_TRUE)
  41. from test_framework.test_framework import BitcoinTestFramework
  42. from test_framework.util import (p2p_port, assert_equal)
  43. class BaseNode(NodeConnCB):
  44. def send_header_for_blocks(self, new_blocks):
  45. headers_message = msg_headers()
  46. headers_message.headers = [CBlockHeader(b) for b in new_blocks]
  47. self.send_message(headers_message)
  48. class AssumeValidTest(BitcoinTestFramework):
  49. def set_test_params(self):
  50. self.setup_clean_chain = True
  51. self.num_nodes = 3
  52. def setup_network(self):
  53. self.add_nodes(3)
  54. # Start node0. We don't start the other nodes yet since
  55. # we need to pre-mine a block with an invalid transaction
  56. # signature so we can pass in the block hash as assumevalid.
  57. self.start_node(0)
  58. def send_blocks_until_disconnected(self, node):
  59. """Keep sending blocks to the node until we're disconnected."""
  60. for i in range(len(self.blocks)):
  61. if not node.connection:
  62. break
  63. try:
  64. node.send_message(msg_block(self.blocks[i]))
  65. except IOError as e:
  66. assert str(e) == 'Not connected, no pushbuf'
  67. break
  68. def assert_blockchain_height(self, node, height):
  69. """Wait until the blockchain is no longer advancing and verify it's reached the expected height."""
  70. last_height = node.getblock(node.getbestblockhash())['height']
  71. timeout = 10
  72. while True:
  73. time.sleep(0.25)
  74. current_height = node.getblock(node.getbestblockhash())['height']
  75. if current_height != last_height:
  76. last_height = current_height
  77. if timeout < 0:
  78. assert False, "blockchain too short after timeout: %d" % current_height
  79. timeout - 0.25
  80. continue
  81. elif current_height > height:
  82. assert False, "blockchain too long: %d" % current_height
  83. elif current_height == height:
  84. break
  85. def run_test(self):
  86. # Connect to node0
  87. node0 = BaseNode()
  88. connections = []
  89. connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], node0))
  90. node0.add_connection(connections[0])
  91. NetworkThread().start() # Start up network handling in another thread
  92. node0.wait_for_verack()
  93. # Build the blockchain
  94. self.tip = int(self.nodes[0].getbestblockhash(), 16)
  95. self.block_time = self.nodes[0].getblock(self.nodes[0].getbestblockhash())['time'] + 1
  96. self.blocks = []
  97. # Get a pubkey for the coinbase TXO
  98. coinbase_key = CECKey()
  99. coinbase_key.set_secretbytes(b"horsebattery")
  100. coinbase_pubkey = coinbase_key.get_pubkey()
  101. # Create the first block with a coinbase output to our key
  102. height = 1
  103. block = create_block(self.tip, create_coinbase(height, coinbase_pubkey), self.block_time)
  104. self.blocks.append(block)
  105. self.block_time += 1
  106. block.solve()
  107. # Save the coinbase for later
  108. self.block1 = block
  109. self.tip = block.sha256
  110. height += 1
  111. # Bury the block 100 deep so the coinbase output is spendable
  112. for i in range(100):
  113. block = create_block(self.tip, create_coinbase(height), self.block_time)
  114. block.solve()
  115. self.blocks.append(block)
  116. self.tip = block.sha256
  117. self.block_time += 1
  118. height += 1
  119. # Create a transaction spending the coinbase output with an invalid (null) signature
  120. tx = CTransaction()
  121. tx.vin.append(CTxIn(COutPoint(self.block1.vtx[0].sha256, 0), scriptSig=b""))
  122. tx.vout.append(CTxOut(49 * 100000000, CScript([OP_TRUE])))
  123. tx.calc_sha256()
  124. block102 = create_block(self.tip, create_coinbase(height), self.block_time)
  125. self.block_time += 1
  126. block102.vtx.extend([tx])
  127. block102.hashMerkleRoot = block102.calc_merkle_root()
  128. block102.rehash()
  129. block102.solve()
  130. self.blocks.append(block102)
  131. self.tip = block102.sha256
  132. self.block_time += 1
  133. height += 1
  134. # Bury the assumed valid block 2100 deep
  135. for i in range(2100):
  136. block = create_block(self.tip, create_coinbase(height), self.block_time)
  137. block.nVersion = 4
  138. block.solve()
  139. self.blocks.append(block)
  140. self.tip = block.sha256
  141. self.block_time += 1
  142. height += 1
  143. # Start node1 and node2 with assumevalid so they accept a block with a bad signature.
  144. self.start_node(1, extra_args=["-assumevalid=" + hex(block102.sha256)])
  145. node1 = BaseNode() # connects to node1
  146. connections.append(NodeConn('127.0.0.1', p2p_port(1), self.nodes[1], node1))
  147. node1.add_connection(connections[1])
  148. node1.wait_for_verack()
  149. self.start_node(2, extra_args=["-assumevalid=" + hex(block102.sha256)])
  150. node2 = BaseNode() # connects to node2
  151. connections.append(NodeConn('127.0.0.1', p2p_port(2), self.nodes[2], node2))
  152. node2.add_connection(connections[2])
  153. node2.wait_for_verack()
  154. # send header lists to all three nodes
  155. node0.send_header_for_blocks(self.blocks[0:2000])
  156. node0.send_header_for_blocks(self.blocks[2000:])
  157. node1.send_header_for_blocks(self.blocks[0:2000])
  158. node1.send_header_for_blocks(self.blocks[2000:])
  159. node2.send_header_for_blocks(self.blocks[0:200])
  160. # Send blocks to node0. Block 102 will be rejected.
  161. self.send_blocks_until_disconnected(node0)
  162. self.assert_blockchain_height(self.nodes[0], 101)
  163. # Send all blocks to node1. All blocks will be accepted.
  164. for i in range(2202):
  165. node1.send_message(msg_block(self.blocks[i]))
  166. # Syncing 2200 blocks can take a while on slow systems. Give it plenty of time to sync.
  167. node1.sync_with_ping(120)
  168. assert_equal(self.nodes[1].getblock(self.nodes[1].getbestblockhash())['height'], 2202)
  169. # Send blocks to node2. Block 102 will be rejected.
  170. self.send_blocks_until_disconnected(node2)
  171. self.assert_blockchain_height(self.nodes[2], 101)
  172. if __name__ == '__main__':
  173. AssumeValidTest().main()