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.

sendheaders.py 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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 behavior of headers messages to announce blocks.
  6. Setup:
  7. - Two nodes, two p2p connections to node0. One p2p connection should only ever
  8. receive inv's (omitted from testing description below, this is our control).
  9. Second node is used for creating reorgs.
  10. Part 1: No headers announcements before "sendheaders"
  11. a. node mines a block [expect: inv]
  12. send getdata for the block [expect: block]
  13. b. node mines another block [expect: inv]
  14. send getheaders and getdata [expect: headers, then block]
  15. c. node mines another block [expect: inv]
  16. peer mines a block, announces with header [expect: getdata]
  17. d. node mines another block [expect: inv]
  18. Part 2: After "sendheaders", headers announcements should generally work.
  19. a. peer sends sendheaders [expect: no response]
  20. peer sends getheaders with current tip [expect: no response]
  21. b. node mines a block [expect: tip header]
  22. c. for N in 1, ..., 10:
  23. * for announce-type in {inv, header}
  24. - peer mines N blocks, announces with announce-type
  25. [ expect: getheaders/getdata or getdata, deliver block(s) ]
  26. - node mines a block [ expect: 1 header ]
  27. Part 3: Headers announcements stop after large reorg and resume after getheaders or inv from peer.
  28. - For response-type in {inv, getheaders}
  29. * node mines a 7 block reorg [ expect: headers announcement of 8 blocks ]
  30. * node mines an 8-block reorg [ expect: inv at tip ]
  31. * peer responds with getblocks/getdata [expect: inv, blocks ]
  32. * node mines another block [ expect: inv at tip, peer sends getdata, expect: block ]
  33. * node mines another block at tip [ expect: inv ]
  34. * peer responds with getheaders with an old hashstop more than 8 blocks back [expect: headers]
  35. * peer requests block [ expect: block ]
  36. * node mines another block at tip [ expect: inv, peer sends getdata, expect: block ]
  37. * peer sends response-type [expect headers if getheaders, getheaders/getdata if mining new block]
  38. * node mines 1 block [expect: 1 header, peer responds with getdata]
  39. Part 4: Test direct fetch behavior
  40. a. Announce 2 old block headers.
  41. Expect: no getdata requests.
  42. b. Announce 3 new blocks via 1 headers message.
  43. Expect: one getdata request for all 3 blocks.
  44. (Send blocks.)
  45. c. Announce 1 header that forks off the last two blocks.
  46. Expect: no response.
  47. d. Announce 1 more header that builds on that fork.
  48. Expect: one getdata request for two blocks.
  49. e. Announce 16 more headers that build on that fork.
  50. Expect: getdata request for 14 more blocks.
  51. f. Announce 1 more header that builds on that fork.
  52. Expect: no response.
  53. Part 5: Test handling of headers that don't connect.
  54. a. Repeat 10 times:
  55. 1. Announce a header that doesn't connect.
  56. Expect: getheaders message
  57. 2. Send headers chain.
  58. Expect: getdata for the missing blocks, tip update.
  59. b. Then send 9 more headers that don't connect.
  60. Expect: getheaders message each time.
  61. c. Announce a header that does connect.
  62. Expect: no response.
  63. d. Announce 49 headers that don't connect.
  64. Expect: getheaders message each time.
  65. e. Announce one more that doesn't connect.
  66. Expect: disconnect.
  67. """
  68. from test_framework.mininode import *
  69. from test_framework.test_framework import BitcoinTestFramework
  70. from test_framework.util import *
  71. from test_framework.blocktools import create_block, create_coinbase
  72. direct_fetch_response_time = 0.05
  73. class TestNode(NodeConnCB):
  74. def __init__(self):
  75. super().__init__()
  76. self.block_announced = False
  77. self.last_blockhash_announced = None
  78. def clear_last_announcement(self):
  79. with mininode_lock:
  80. self.block_announced = False
  81. self.last_message.pop("inv", None)
  82. self.last_message.pop("headers", None)
  83. # Request data for a list of block hashes
  84. def get_data(self, block_hashes):
  85. msg = msg_getdata()
  86. for x in block_hashes:
  87. msg.inv.append(CInv(2, x))
  88. self.connection.send_message(msg)
  89. def get_headers(self, locator, hashstop):
  90. msg = msg_getheaders()
  91. msg.locator.vHave = locator
  92. msg.hashstop = hashstop
  93. self.connection.send_message(msg)
  94. def send_block_inv(self, blockhash):
  95. msg = msg_inv()
  96. msg.inv = [CInv(2, blockhash)]
  97. self.connection.send_message(msg)
  98. def on_inv(self, conn, message):
  99. self.block_announced = True
  100. self.last_blockhash_announced = message.inv[-1].hash
  101. def on_headers(self, conn, message):
  102. if len(message.headers):
  103. self.block_announced = True
  104. message.headers[-1].calc_sha256()
  105. self.last_blockhash_announced = message.headers[-1].sha256
  106. def on_block(self, conn, message):
  107. self.last_message["block"].calc_sha256()
  108. # Test whether the last announcement we received had the
  109. # right header or the right inv
  110. # inv and headers should be lists of block hashes
  111. def check_last_announcement(self, headers=None, inv=None):
  112. expect_headers = headers if headers != None else []
  113. expect_inv = inv if inv != None else []
  114. test_function = lambda: self.block_announced
  115. assert(wait_until(test_function, timeout=60))
  116. with mininode_lock:
  117. self.block_announced = False
  118. success = True
  119. compare_inv = []
  120. if "inv" in self.last_message:
  121. compare_inv = [x.hash for x in self.last_message["inv"].inv]
  122. if compare_inv != expect_inv:
  123. success = False
  124. hash_headers = []
  125. if "headers" in self.last_message:
  126. # treat headers as a list of block hashes
  127. hash_headers = [ x.sha256 for x in self.last_message["headers"].headers ]
  128. if hash_headers != expect_headers:
  129. success = False
  130. self.last_message.pop("inv", None)
  131. self.last_message.pop("headers", None)
  132. return success
  133. def wait_for_getdata(self, hash_list, timeout=60):
  134. if hash_list == []:
  135. return
  136. test_function = lambda: "getdata" in self.last_message and [x.hash for x in self.last_message["getdata"].inv] == hash_list
  137. assert(wait_until(test_function, timeout=timeout))
  138. return
  139. def wait_for_block_announcement(self, block_hash, timeout=60):
  140. test_function = lambda: self.last_blockhash_announced == block_hash
  141. assert(wait_until(test_function, timeout=timeout))
  142. return
  143. def send_header_for_blocks(self, new_blocks):
  144. headers_message = msg_headers()
  145. headers_message.headers = [ CBlockHeader(b) for b in new_blocks ]
  146. self.send_message(headers_message)
  147. def send_getblocks(self, locator):
  148. getblocks_message = msg_getblocks()
  149. getblocks_message.locator.vHave = locator
  150. self.send_message(getblocks_message)
  151. class SendHeadersTest(BitcoinTestFramework):
  152. def __init__(self):
  153. super().__init__()
  154. self.setup_clean_chain = True
  155. self.num_nodes = 2
  156. # mine count blocks and return the new tip
  157. def mine_blocks(self, count):
  158. # Clear out last block announcement from each p2p listener
  159. [ x.clear_last_announcement() for x in self.p2p_connections ]
  160. self.nodes[0].generate(count)
  161. return int(self.nodes[0].getbestblockhash(), 16)
  162. # mine a reorg that invalidates length blocks (replacing them with
  163. # length+1 blocks).
  164. # Note: we clear the state of our p2p connections after the
  165. # to-be-reorged-out blocks are mined, so that we don't break later tests.
  166. # return the list of block hashes newly mined
  167. def mine_reorg(self, length):
  168. self.nodes[0].generate(length) # make sure all invalidated blocks are node0's
  169. sync_blocks(self.nodes, wait=0.1)
  170. for x in self.p2p_connections:
  171. x.wait_for_block_announcement(int(self.nodes[0].getbestblockhash(), 16))
  172. x.clear_last_announcement()
  173. tip_height = self.nodes[1].getblockcount()
  174. hash_to_invalidate = self.nodes[1].getblockhash(tip_height-(length-1))
  175. self.nodes[1].invalidateblock(hash_to_invalidate)
  176. all_hashes = self.nodes[1].generate(length+1) # Must be longer than the orig chain
  177. sync_blocks(self.nodes, wait=0.1)
  178. return [int(x, 16) for x in all_hashes]
  179. def run_test(self):
  180. # Setup the p2p connections and start up the network thread.
  181. inv_node = TestNode()
  182. test_node = TestNode()
  183. self.p2p_connections = [inv_node, test_node]
  184. connections = []
  185. connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], inv_node))
  186. # Set nServices to 0 for test_node, so no block download will occur outside of
  187. # direct fetching
  188. connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node, services=0))
  189. inv_node.add_connection(connections[0])
  190. test_node.add_connection(connections[1])
  191. NetworkThread().start() # Start up network handling in another thread
  192. # Test logic begins here
  193. inv_node.wait_for_verack()
  194. test_node.wait_for_verack()
  195. tip = int(self.nodes[0].getbestblockhash(), 16)
  196. # PART 1
  197. # 1. Mine a block; expect inv announcements each time
  198. self.log.info("Part 1: headers don't start before sendheaders message...")
  199. for i in range(4):
  200. old_tip = tip
  201. tip = self.mine_blocks(1)
  202. assert_equal(inv_node.check_last_announcement(inv=[tip]), True)
  203. assert_equal(test_node.check_last_announcement(inv=[tip]), True)
  204. # Try a few different responses; none should affect next announcement
  205. if i == 0:
  206. # first request the block
  207. test_node.get_data([tip])
  208. test_node.wait_for_block(tip)
  209. elif i == 1:
  210. # next try requesting header and block
  211. test_node.get_headers(locator=[old_tip], hashstop=tip)
  212. test_node.get_data([tip])
  213. test_node.wait_for_block(tip)
  214. test_node.clear_last_announcement() # since we requested headers...
  215. elif i == 2:
  216. # this time announce own block via headers
  217. height = self.nodes[0].getblockcount()
  218. last_time = self.nodes[0].getblock(self.nodes[0].getbestblockhash())['time']
  219. block_time = last_time + 1
  220. new_block = create_block(tip, create_coinbase(height+1), block_time)
  221. new_block.solve()
  222. test_node.send_header_for_blocks([new_block])
  223. test_node.wait_for_getdata([new_block.sha256])
  224. test_node.send_message(msg_block(new_block))
  225. test_node.sync_with_ping() # make sure this block is processed
  226. inv_node.clear_last_announcement()
  227. test_node.clear_last_announcement()
  228. self.log.info("Part 1: success!")
  229. self.log.info("Part 2: announce blocks with headers after sendheaders message...")
  230. # PART 2
  231. # 2. Send a sendheaders message and test that headers announcements
  232. # commence and keep working.
  233. test_node.send_message(msg_sendheaders())
  234. prev_tip = int(self.nodes[0].getbestblockhash(), 16)
  235. test_node.get_headers(locator=[prev_tip], hashstop=0)
  236. test_node.sync_with_ping()
  237. # Now that we've synced headers, headers announcements should work
  238. tip = self.mine_blocks(1)
  239. assert_equal(inv_node.check_last_announcement(inv=[tip]), True)
  240. assert_equal(test_node.check_last_announcement(headers=[tip]), True)
  241. height = self.nodes[0].getblockcount()+1
  242. block_time += 10 # Advance far enough ahead
  243. for i in range(10):
  244. # Mine i blocks, and alternate announcing either via
  245. # inv (of tip) or via headers. After each, new blocks
  246. # mined by the node should successfully be announced
  247. # with block header, even though the blocks are never requested
  248. for j in range(2):
  249. blocks = []
  250. for b in range(i+1):
  251. blocks.append(create_block(tip, create_coinbase(height), block_time))
  252. blocks[-1].solve()
  253. tip = blocks[-1].sha256
  254. block_time += 1
  255. height += 1
  256. if j == 0:
  257. # Announce via inv
  258. test_node.send_block_inv(tip)
  259. test_node.wait_for_getheaders()
  260. # Should have received a getheaders now
  261. test_node.send_header_for_blocks(blocks)
  262. # Test that duplicate inv's won't result in duplicate
  263. # getdata requests, or duplicate headers announcements
  264. [ inv_node.send_block_inv(x.sha256) for x in blocks ]
  265. test_node.wait_for_getdata([x.sha256 for x in blocks])
  266. inv_node.sync_with_ping()
  267. else:
  268. # Announce via headers
  269. test_node.send_header_for_blocks(blocks)
  270. test_node.wait_for_getdata([x.sha256 for x in blocks])
  271. # Test that duplicate headers won't result in duplicate
  272. # getdata requests (the check is further down)
  273. inv_node.send_header_for_blocks(blocks)
  274. inv_node.sync_with_ping()
  275. [ test_node.send_message(msg_block(x)) for x in blocks ]
  276. test_node.sync_with_ping()
  277. inv_node.sync_with_ping()
  278. # This block should not be announced to the inv node (since it also
  279. # broadcast it)
  280. assert "inv" not in inv_node.last_message
  281. assert "headers" not in inv_node.last_message
  282. tip = self.mine_blocks(1)
  283. assert_equal(inv_node.check_last_announcement(inv=[tip]), True)
  284. assert_equal(test_node.check_last_announcement(headers=[tip]), True)
  285. height += 1
  286. block_time += 1
  287. self.log.info("Part 2: success!")
  288. self.log.info("Part 3: headers announcements can stop after large reorg, and resume after headers/inv from peer...")
  289. # PART 3. Headers announcements can stop after large reorg, and resume after
  290. # getheaders or inv from peer.
  291. for j in range(2):
  292. # First try mining a reorg that can propagate with header announcement
  293. new_block_hashes = self.mine_reorg(length=7)
  294. tip = new_block_hashes[-1]
  295. assert_equal(inv_node.check_last_announcement(inv=[tip]), True)
  296. assert_equal(test_node.check_last_announcement(headers=new_block_hashes), True)
  297. block_time += 8
  298. # Mine a too-large reorg, which should be announced with a single inv
  299. new_block_hashes = self.mine_reorg(length=8)
  300. tip = new_block_hashes[-1]
  301. assert_equal(inv_node.check_last_announcement(inv=[tip]), True)
  302. assert_equal(test_node.check_last_announcement(inv=[tip]), True)
  303. block_time += 9
  304. fork_point = self.nodes[0].getblock("%02x" % new_block_hashes[0])["previousblockhash"]
  305. fork_point = int(fork_point, 16)
  306. # Use getblocks/getdata
  307. test_node.send_getblocks(locator = [fork_point])
  308. assert_equal(test_node.check_last_announcement(inv=new_block_hashes), True)
  309. test_node.get_data(new_block_hashes)
  310. test_node.wait_for_block(new_block_hashes[-1])
  311. for i in range(3):
  312. # Mine another block, still should get only an inv
  313. tip = self.mine_blocks(1)
  314. assert_equal(inv_node.check_last_announcement(inv=[tip]), True)
  315. assert_equal(test_node.check_last_announcement(inv=[tip]), True)
  316. if i == 0:
  317. # Just get the data -- shouldn't cause headers announcements to resume
  318. test_node.get_data([tip])
  319. test_node.wait_for_block(tip)
  320. elif i == 1:
  321. # Send a getheaders message that shouldn't trigger headers announcements
  322. # to resume (best header sent will be too old)
  323. test_node.get_headers(locator=[fork_point], hashstop=new_block_hashes[1])
  324. test_node.get_data([tip])
  325. test_node.wait_for_block(tip)
  326. elif i == 2:
  327. test_node.get_data([tip])
  328. test_node.wait_for_block(tip)
  329. # This time, try sending either a getheaders to trigger resumption
  330. # of headers announcements, or mine a new block and inv it, also
  331. # triggering resumption of headers announcements.
  332. if j == 0:
  333. test_node.get_headers(locator=[tip], hashstop=0)
  334. test_node.sync_with_ping()
  335. else:
  336. test_node.send_block_inv(tip)
  337. test_node.sync_with_ping()
  338. # New blocks should now be announced with header
  339. tip = self.mine_blocks(1)
  340. assert_equal(inv_node.check_last_announcement(inv=[tip]), True)
  341. assert_equal(test_node.check_last_announcement(headers=[tip]), True)
  342. self.log.info("Part 3: success!")
  343. self.log.info("Part 4: Testing direct fetch behavior...")
  344. tip = self.mine_blocks(1)
  345. height = self.nodes[0].getblockcount() + 1
  346. last_time = self.nodes[0].getblock(self.nodes[0].getbestblockhash())['time']
  347. block_time = last_time + 1
  348. # Create 2 blocks. Send the blocks, then send the headers.
  349. blocks = []
  350. for b in range(2):
  351. blocks.append(create_block(tip, create_coinbase(height), block_time))
  352. blocks[-1].solve()
  353. tip = blocks[-1].sha256
  354. block_time += 1
  355. height += 1
  356. inv_node.send_message(msg_block(blocks[-1]))
  357. inv_node.sync_with_ping() # Make sure blocks are processed
  358. test_node.last_message.pop("getdata", None)
  359. test_node.send_header_for_blocks(blocks)
  360. test_node.sync_with_ping()
  361. # should not have received any getdata messages
  362. with mininode_lock:
  363. assert "getdata" not in test_node.last_message
  364. # This time, direct fetch should work
  365. blocks = []
  366. for b in range(3):
  367. blocks.append(create_block(tip, create_coinbase(height), block_time))
  368. blocks[-1].solve()
  369. tip = blocks[-1].sha256
  370. block_time += 1
  371. height += 1
  372. test_node.send_header_for_blocks(blocks)
  373. test_node.sync_with_ping()
  374. test_node.wait_for_getdata([x.sha256 for x in blocks], timeout=direct_fetch_response_time)
  375. [ test_node.send_message(msg_block(x)) for x in blocks ]
  376. test_node.sync_with_ping()
  377. # Now announce a header that forks the last two blocks
  378. tip = blocks[0].sha256
  379. height -= 1
  380. blocks = []
  381. # Create extra blocks for later
  382. for b in range(20):
  383. blocks.append(create_block(tip, create_coinbase(height), block_time))
  384. blocks[-1].solve()
  385. tip = blocks[-1].sha256
  386. block_time += 1
  387. height += 1
  388. # Announcing one block on fork should not trigger direct fetch
  389. # (less work than tip)
  390. test_node.last_message.pop("getdata", None)
  391. test_node.send_header_for_blocks(blocks[0:1])
  392. test_node.sync_with_ping()
  393. with mininode_lock:
  394. assert "getdata" not in test_node.last_message
  395. # Announcing one more block on fork should trigger direct fetch for
  396. # both blocks (same work as tip)
  397. test_node.send_header_for_blocks(blocks[1:2])
  398. test_node.sync_with_ping()
  399. test_node.wait_for_getdata([x.sha256 for x in blocks[0:2]], timeout=direct_fetch_response_time)
  400. # Announcing 16 more headers should trigger direct fetch for 14 more
  401. # blocks
  402. test_node.send_header_for_blocks(blocks[2:18])
  403. test_node.sync_with_ping()
  404. test_node.wait_for_getdata([x.sha256 for x in blocks[2:16]], timeout=direct_fetch_response_time)
  405. # Announcing 1 more header should not trigger any response
  406. test_node.last_message.pop("getdata", None)
  407. test_node.send_header_for_blocks(blocks[18:19])
  408. test_node.sync_with_ping()
  409. with mininode_lock:
  410. assert "getdata" not in test_node.last_message
  411. self.log.info("Part 4: success!")
  412. # Now deliver all those blocks we announced.
  413. [ test_node.send_message(msg_block(x)) for x in blocks ]
  414. self.log.info("Part 5: Testing handling of unconnecting headers")
  415. # First we test that receipt of an unconnecting header doesn't prevent
  416. # chain sync.
  417. for i in range(10):
  418. test_node.last_message.pop("getdata", None)
  419. blocks = []
  420. # Create two more blocks.
  421. for j in range(2):
  422. blocks.append(create_block(tip, create_coinbase(height), block_time))
  423. blocks[-1].solve()
  424. tip = blocks[-1].sha256
  425. block_time += 1
  426. height += 1
  427. # Send the header of the second block -> this won't connect.
  428. with mininode_lock:
  429. test_node.last_message.pop("getheaders", None)
  430. test_node.send_header_for_blocks([blocks[1]])
  431. test_node.wait_for_getheaders()
  432. test_node.send_header_for_blocks(blocks)
  433. test_node.wait_for_getdata([x.sha256 for x in blocks])
  434. [ test_node.send_message(msg_block(x)) for x in blocks ]
  435. test_node.sync_with_ping()
  436. assert_equal(int(self.nodes[0].getbestblockhash(), 16), blocks[1].sha256)
  437. blocks = []
  438. # Now we test that if we repeatedly don't send connecting headers, we
  439. # don't go into an infinite loop trying to get them to connect.
  440. MAX_UNCONNECTING_HEADERS = 10
  441. for j in range(MAX_UNCONNECTING_HEADERS+1):
  442. blocks.append(create_block(tip, create_coinbase(height), block_time))
  443. blocks[-1].solve()
  444. tip = blocks[-1].sha256
  445. block_time += 1
  446. height += 1
  447. for i in range(1, MAX_UNCONNECTING_HEADERS):
  448. # Send a header that doesn't connect, check that we get a getheaders.
  449. with mininode_lock:
  450. test_node.last_message.pop("getheaders", None)
  451. test_node.send_header_for_blocks([blocks[i]])
  452. test_node.wait_for_getheaders()
  453. # Next header will connect, should re-set our count:
  454. test_node.send_header_for_blocks([blocks[0]])
  455. # Remove the first two entries (blocks[1] would connect):
  456. blocks = blocks[2:]
  457. # Now try to see how many unconnecting headers we can send
  458. # before we get disconnected. Should be 5*MAX_UNCONNECTING_HEADERS
  459. for i in range(5*MAX_UNCONNECTING_HEADERS - 1):
  460. # Send a header that doesn't connect, check that we get a getheaders.
  461. with mininode_lock:
  462. test_node.last_message.pop("getheaders", None)
  463. test_node.send_header_for_blocks([blocks[i%len(blocks)]])
  464. test_node.wait_for_getheaders()
  465. # Eventually this stops working.
  466. test_node.send_header_for_blocks([blocks[-1]])
  467. # Should get disconnected
  468. test_node.wait_for_disconnect()
  469. self.log.info("Part 5: success!")
  470. # Finally, check that the inv node never received a getdata request,
  471. # throughout the test
  472. assert "getdata" not in inv_node.last_message
  473. if __name__ == '__main__':
  474. SendHeadersTest().main()