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.

p2p-acceptblock.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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 processing of unrequested blocks.
  6. Since behavior differs when receiving unrequested blocks from whitelisted peers
  7. versus non-whitelisted peers, this tests the behavior of both (effectively two
  8. separate tests running in parallel).
  9. Setup: two nodes, node0 and node1, not connected to each other. Node0 does not
  10. whitelist localhost, but node1 does. They will each be on their own chain for
  11. this test.
  12. We have one NodeConn connection to each, test_node and white_node respectively.
  13. The test:
  14. 1. Generate one block on each node, to leave IBD.
  15. 2. Mine a new block on each tip, and deliver to each node from node's peer.
  16. The tip should advance.
  17. 3. Mine a block that forks the previous block, and deliver to each node from
  18. corresponding peer.
  19. Node0 should not process this block (just accept the header), because it is
  20. unrequested and doesn't have more work than the tip.
  21. Node1 should process because this is coming from a whitelisted peer.
  22. 4. Send another block that builds on the forking block.
  23. Node0 should process this block but be stuck on the shorter chain, because
  24. it's missing an intermediate block.
  25. Node1 should reorg to this longer chain.
  26. 4b.Send 288 more blocks on the longer chain.
  27. Node0 should process all but the last block (too far ahead in height).
  28. Send all headers to Node1, and then send the last block in that chain.
  29. Node1 should accept the block because it's coming from a whitelisted peer.
  30. 5. Send a duplicate of the block in #3 to Node0.
  31. Node0 should not process the block because it is unrequested, and stay on
  32. the shorter chain.
  33. 6. Send Node0 an inv for the height 3 block produced in #4 above.
  34. Node0 should figure out that Node0 has the missing height 2 block and send a
  35. getdata.
  36. 7. Send Node0 the missing block again.
  37. Node0 should process and the tip should advance.
  38. """
  39. from test_framework.mininode import *
  40. from test_framework.test_framework import BitcoinTestFramework
  41. from test_framework.util import *
  42. import time
  43. from test_framework.blocktools import create_block, create_coinbase
  44. # TestNode: bare-bones "peer". Used mostly as a conduit for a test to sending
  45. # p2p messages to a node, generating the messages in the main testing logic.
  46. class TestNode(NodeConnCB):
  47. def __init__(self):
  48. NodeConnCB.__init__(self)
  49. self.connection = None
  50. self.ping_counter = 1
  51. self.last_pong = msg_pong()
  52. def add_connection(self, conn):
  53. self.connection = conn
  54. # Track the last getdata message we receive (used in the test)
  55. def on_getdata(self, conn, message):
  56. self.last_getdata = message
  57. # Spin until verack message is received from the node.
  58. # We use this to signal that our test can begin. This
  59. # is called from the testing thread, so it needs to acquire
  60. # the global lock.
  61. def wait_for_verack(self):
  62. while True:
  63. with mininode_lock:
  64. if self.verack_received:
  65. return
  66. time.sleep(0.05)
  67. # Wrapper for the NodeConn's send_message function
  68. def send_message(self, message):
  69. self.connection.send_message(message)
  70. def on_pong(self, conn, message):
  71. self.last_pong = message
  72. # Sync up with the node after delivery of a block
  73. def sync_with_ping(self, timeout=30):
  74. self.connection.send_message(msg_ping(nonce=self.ping_counter))
  75. received_pong = False
  76. sleep_time = 0.05
  77. while not received_pong and timeout > 0:
  78. time.sleep(sleep_time)
  79. timeout -= sleep_time
  80. with mininode_lock:
  81. if self.last_pong.nonce == self.ping_counter:
  82. received_pong = True
  83. self.ping_counter += 1
  84. return received_pong
  85. class AcceptBlockTest(BitcoinTestFramework):
  86. def add_options(self, parser):
  87. parser.add_option("--testbinary", dest="testbinary",
  88. default=os.getenv("BITCOIND", "bitcoind"),
  89. help="bitcoind binary to test")
  90. def __init__(self):
  91. super().__init__()
  92. self.setup_clean_chain = True
  93. self.num_nodes = 2
  94. def setup_network(self):
  95. # Node0 will be used to test behavior of processing unrequested blocks
  96. # from peers which are not whitelisted, while Node1 will be used for
  97. # the whitelisted case.
  98. self.nodes = []
  99. self.nodes.append(start_node(0, self.options.tmpdir,
  100. binary=self.options.testbinary))
  101. self.nodes.append(start_node(1, self.options.tmpdir,
  102. ["-whitelist=127.0.0.1"],
  103. binary=self.options.testbinary))
  104. def run_test(self):
  105. # Setup the p2p connections and start up the network thread.
  106. test_node = TestNode() # connects to node0 (not whitelisted)
  107. white_node = TestNode() # connects to node1 (whitelisted)
  108. connections = []
  109. connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node))
  110. connections.append(NodeConn('127.0.0.1', p2p_port(1), self.nodes[1], white_node))
  111. test_node.add_connection(connections[0])
  112. white_node.add_connection(connections[1])
  113. NetworkThread().start() # Start up network handling in another thread
  114. # Test logic begins here
  115. test_node.wait_for_verack()
  116. white_node.wait_for_verack()
  117. # 1. Have both nodes mine a block (leave IBD)
  118. [ n.generate(1) for n in self.nodes ]
  119. tips = [ int("0x" + n.getbestblockhash(), 0) for n in self.nodes ]
  120. # 2. Send one block that builds on each tip.
  121. # This should be accepted.
  122. blocks_h2 = [] # the height 2 blocks on each node's chain
  123. block_time = int(time.time()) + 1
  124. for i in range(2):
  125. blocks_h2.append(create_block(tips[i], create_coinbase(2), block_time))
  126. blocks_h2[i].solve()
  127. block_time += 1
  128. test_node.send_message(msg_block(blocks_h2[0]))
  129. white_node.send_message(msg_block(blocks_h2[1]))
  130. [ x.sync_with_ping() for x in [test_node, white_node] ]
  131. assert_equal(self.nodes[0].getblockcount(), 2)
  132. assert_equal(self.nodes[1].getblockcount(), 2)
  133. self.log.info("First height 2 block accepted by both nodes")
  134. # 3. Send another block that builds on the original tip.
  135. blocks_h2f = [] # Blocks at height 2 that fork off the main chain
  136. for i in range(2):
  137. blocks_h2f.append(create_block(tips[i], create_coinbase(2), blocks_h2[i].nTime+1))
  138. blocks_h2f[i].solve()
  139. test_node.send_message(msg_block(blocks_h2f[0]))
  140. white_node.send_message(msg_block(blocks_h2f[1]))
  141. [ x.sync_with_ping() for x in [test_node, white_node] ]
  142. for x in self.nodes[0].getchaintips():
  143. if x['hash'] == blocks_h2f[0].hash:
  144. assert_equal(x['status'], "headers-only")
  145. for x in self.nodes[1].getchaintips():
  146. if x['hash'] == blocks_h2f[1].hash:
  147. assert_equal(x['status'], "valid-headers")
  148. self.log.info("Second height 2 block accepted only from whitelisted peer")
  149. # 4. Now send another block that builds on the forking chain.
  150. blocks_h3 = []
  151. for i in range(2):
  152. blocks_h3.append(create_block(blocks_h2f[i].sha256, create_coinbase(3), blocks_h2f[i].nTime+1))
  153. blocks_h3[i].solve()
  154. test_node.send_message(msg_block(blocks_h3[0]))
  155. white_node.send_message(msg_block(blocks_h3[1]))
  156. [ x.sync_with_ping() for x in [test_node, white_node] ]
  157. # Since the earlier block was not processed by node0, the new block
  158. # can't be fully validated.
  159. for x in self.nodes[0].getchaintips():
  160. if x['hash'] == blocks_h3[0].hash:
  161. assert_equal(x['status'], "headers-only")
  162. # But this block should be accepted by node0 since it has more work.
  163. self.nodes[0].getblock(blocks_h3[0].hash)
  164. self.log.info("Unrequested more-work block accepted from non-whitelisted peer")
  165. # Node1 should have accepted and reorged.
  166. assert_equal(self.nodes[1].getblockcount(), 3)
  167. self.log.info("Successfully reorged to length 3 chain from whitelisted peer")
  168. # 4b. Now mine 288 more blocks and deliver; all should be processed but
  169. # the last (height-too-high) on node0. Node1 should process the tip if
  170. # we give it the headers chain leading to the tip.
  171. tips = blocks_h3
  172. headers_message = msg_headers()
  173. all_blocks = [] # node0's blocks
  174. for j in range(2):
  175. for i in range(288):
  176. next_block = create_block(tips[j].sha256, create_coinbase(i + 4), tips[j].nTime+1)
  177. next_block.solve()
  178. if j==0:
  179. test_node.send_message(msg_block(next_block))
  180. all_blocks.append(next_block)
  181. else:
  182. headers_message.headers.append(CBlockHeader(next_block))
  183. tips[j] = next_block
  184. time.sleep(2)
  185. # Blocks 1-287 should be accepted, block 288 should be ignored because it's too far ahead
  186. for x in all_blocks[:-1]:
  187. self.nodes[0].getblock(x.hash)
  188. assert_raises_jsonrpc(-1, "Block not found on disk", self.nodes[0].getblock, all_blocks[-1].hash)
  189. headers_message.headers.pop() # Ensure the last block is unrequested
  190. white_node.send_message(headers_message) # Send headers leading to tip
  191. white_node.send_message(msg_block(tips[1])) # Now deliver the tip
  192. white_node.sync_with_ping()
  193. self.nodes[1].getblock(tips[1].hash)
  194. self.log.info("Unrequested block far ahead of tip accepted from whitelisted peer")
  195. # 5. Test handling of unrequested block on the node that didn't process
  196. # Should still not be processed (even though it has a child that has more
  197. # work).
  198. test_node.send_message(msg_block(blocks_h2f[0]))
  199. # Here, if the sleep is too short, the test could falsely succeed (if the
  200. # node hasn't processed the block by the time the sleep returns, and then
  201. # the node processes it and incorrectly advances the tip).
  202. # But this would be caught later on, when we verify that an inv triggers
  203. # a getdata request for this block.
  204. test_node.sync_with_ping()
  205. assert_equal(self.nodes[0].getblockcount(), 2)
  206. self.log.info("Unrequested block that would complete more-work chain was ignored")
  207. # 6. Try to get node to request the missing block.
  208. # Poke the node with an inv for block at height 3 and see if that
  209. # triggers a getdata on block 2 (it should if block 2 is missing).
  210. with mininode_lock:
  211. # Clear state so we can check the getdata request
  212. test_node.last_getdata = None
  213. test_node.send_message(msg_inv([CInv(2, blocks_h3[0].sha256)]))
  214. test_node.sync_with_ping()
  215. with mininode_lock:
  216. getdata = test_node.last_getdata
  217. # Check that the getdata includes the right block
  218. assert_equal(getdata.inv[0].hash, blocks_h2f[0].sha256)
  219. self.log.info("Inv at tip triggered getdata for unprocessed block")
  220. # 7. Send the missing block for the third time (now it is requested)
  221. test_node.send_message(msg_block(blocks_h2f[0]))
  222. test_node.sync_with_ping()
  223. assert_equal(self.nodes[0].getblockcount(), 290)
  224. self.log.info("Successfully reorged to longer chain from non-whitelisted peer")
  225. [ c.disconnect_node() for c in connections ]
  226. if __name__ == '__main__':
  227. AcceptBlockTest().main()