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