[tests] don't override __init__() in individual tests
[bitcoinplatinum.git] / test / functional / sendheaders.py
blobfe577dc20a2dbd662f22c95acc188334dbfda5fc
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 # Test whether the last announcement we received had the
125 # right header or the right inv
126 # inv and headers should be lists of block hashes
127 def check_last_announcement(self, headers=None, inv=None):
128 expect_headers = headers if headers != None else []
129 expect_inv = inv if inv != None else []
130 test_function = lambda: self.block_announced
131 wait_until(test_function, timeout=60, lock=mininode_lock)
132 with mininode_lock:
133 self.block_announced = False
135 success = True
136 compare_inv = []
137 if "inv" in self.last_message:
138 compare_inv = [x.hash for x in self.last_message["inv"].inv]
139 if compare_inv != expect_inv:
140 success = False
142 hash_headers = []
143 if "headers" in self.last_message:
144 # treat headers as a list of block hashes
145 hash_headers = [ x.sha256 for x in self.last_message["headers"].headers ]
146 if hash_headers != expect_headers:
147 success = False
149 self.last_message.pop("inv", None)
150 self.last_message.pop("headers", None)
151 return success
153 def wait_for_getdata(self, hash_list, timeout=60):
154 if hash_list == []:
155 return
157 test_function = lambda: "getdata" in self.last_message and [x.hash for x in self.last_message["getdata"].inv] == hash_list
158 wait_until(test_function, timeout=timeout, lock=mininode_lock)
159 return
161 def wait_for_block_announcement(self, block_hash, timeout=60):
162 test_function = lambda: self.last_blockhash_announced == block_hash
163 wait_until(test_function, timeout=timeout, lock=mininode_lock)
164 return
166 def send_header_for_blocks(self, new_blocks):
167 headers_message = msg_headers()
168 headers_message.headers = [ CBlockHeader(b) for b in new_blocks ]
169 self.send_message(headers_message)
171 def send_getblocks(self, locator):
172 getblocks_message = msg_getblocks()
173 getblocks_message.locator.vHave = locator
174 self.send_message(getblocks_message)
176 class SendHeadersTest(BitcoinTestFramework):
177 def set_test_params(self):
178 self.setup_clean_chain = True
179 self.num_nodes = 2
181 # mine count blocks and return the new tip
182 def mine_blocks(self, count):
183 # Clear out last block announcement from each p2p listener
184 [ x.clear_last_announcement() for x in self.p2p_connections ]
185 self.nodes[0].generate(count)
186 return int(self.nodes[0].getbestblockhash(), 16)
188 # mine a reorg that invalidates length blocks (replacing them with
189 # length+1 blocks).
190 # Note: we clear the state of our p2p connections after the
191 # to-be-reorged-out blocks are mined, so that we don't break later tests.
192 # return the list of block hashes newly mined
193 def mine_reorg(self, length):
194 self.nodes[0].generate(length) # make sure all invalidated blocks are node0's
195 sync_blocks(self.nodes, wait=0.1)
196 for x in self.p2p_connections:
197 x.wait_for_block_announcement(int(self.nodes[0].getbestblockhash(), 16))
198 x.clear_last_announcement()
200 tip_height = self.nodes[1].getblockcount()
201 hash_to_invalidate = self.nodes[1].getblockhash(tip_height-(length-1))
202 self.nodes[1].invalidateblock(hash_to_invalidate)
203 all_hashes = self.nodes[1].generate(length+1) # Must be longer than the orig chain
204 sync_blocks(self.nodes, wait=0.1)
205 return [int(x, 16) for x in all_hashes]
207 def run_test(self):
208 # Setup the p2p connections and start up the network thread.
209 inv_node = TestNode()
210 test_node = TestNode()
212 self.p2p_connections = [inv_node, test_node]
214 connections = []
215 connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], inv_node))
216 # Set nServices to 0 for test_node, so no block download will occur outside of
217 # direct fetching
218 connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node, services=0))
219 inv_node.add_connection(connections[0])
220 test_node.add_connection(connections[1])
222 NetworkThread().start() # Start up network handling in another thread
224 # Test logic begins here
225 inv_node.wait_for_verack()
226 test_node.wait_for_verack()
228 tip = int(self.nodes[0].getbestblockhash(), 16)
230 # PART 1
231 # 1. Mine a block; expect inv announcements each time
232 self.log.info("Part 1: headers don't start before sendheaders message...")
233 for i in range(4):
234 old_tip = tip
235 tip = self.mine_blocks(1)
236 assert_equal(inv_node.check_last_announcement(inv=[tip]), True)
237 assert_equal(test_node.check_last_announcement(inv=[tip]), True)
238 # Try a few different responses; none should affect next announcement
239 if i == 0:
240 # first request the block
241 test_node.get_data([tip])
242 test_node.wait_for_block(tip)
243 elif i == 1:
244 # next try requesting header and block
245 test_node.get_headers(locator=[old_tip], hashstop=tip)
246 test_node.get_data([tip])
247 test_node.wait_for_block(tip)
248 test_node.clear_last_announcement() # since we requested headers...
249 elif i == 2:
250 # this time announce own block via headers
251 height = self.nodes[0].getblockcount()
252 last_time = self.nodes[0].getblock(self.nodes[0].getbestblockhash())['time']
253 block_time = last_time + 1
254 new_block = create_block(tip, create_coinbase(height+1), block_time)
255 new_block.solve()
256 test_node.send_header_for_blocks([new_block])
257 test_node.wait_for_getdata([new_block.sha256])
258 test_node.send_message(msg_block(new_block))
259 test_node.sync_with_ping() # make sure this block is processed
260 inv_node.clear_last_announcement()
261 test_node.clear_last_announcement()
263 self.log.info("Part 1: success!")
264 self.log.info("Part 2: announce blocks with headers after sendheaders message...")
265 # PART 2
266 # 2. Send a sendheaders message and test that headers announcements
267 # commence and keep working.
268 test_node.send_message(msg_sendheaders())
269 prev_tip = int(self.nodes[0].getbestblockhash(), 16)
270 test_node.get_headers(locator=[prev_tip], hashstop=0)
271 test_node.sync_with_ping()
273 # Now that we've synced headers, headers announcements should work
274 tip = self.mine_blocks(1)
275 assert_equal(inv_node.check_last_announcement(inv=[tip]), True)
276 assert_equal(test_node.check_last_announcement(headers=[tip]), True)
278 height = self.nodes[0].getblockcount()+1
279 block_time += 10 # Advance far enough ahead
280 for i in range(10):
281 # Mine i blocks, and alternate announcing either via
282 # inv (of tip) or via headers. After each, new blocks
283 # mined by the node should successfully be announced
284 # with block header, even though the blocks are never requested
285 for j in range(2):
286 blocks = []
287 for b in range(i+1):
288 blocks.append(create_block(tip, create_coinbase(height), block_time))
289 blocks[-1].solve()
290 tip = blocks[-1].sha256
291 block_time += 1
292 height += 1
293 if j == 0:
294 # Announce via inv
295 test_node.send_block_inv(tip)
296 test_node.wait_for_getheaders()
297 # Should have received a getheaders now
298 test_node.send_header_for_blocks(blocks)
299 # Test that duplicate inv's won't result in duplicate
300 # getdata requests, or duplicate headers announcements
301 [ inv_node.send_block_inv(x.sha256) for x in blocks ]
302 test_node.wait_for_getdata([x.sha256 for x in blocks])
303 inv_node.sync_with_ping()
304 else:
305 # Announce via headers
306 test_node.send_header_for_blocks(blocks)
307 test_node.wait_for_getdata([x.sha256 for x in blocks])
308 # Test that duplicate headers won't result in duplicate
309 # getdata requests (the check is further down)
310 inv_node.send_header_for_blocks(blocks)
311 inv_node.sync_with_ping()
312 [ test_node.send_message(msg_block(x)) for x in blocks ]
313 test_node.sync_with_ping()
314 inv_node.sync_with_ping()
315 # This block should not be announced to the inv node (since it also
316 # broadcast it)
317 assert "inv" not in inv_node.last_message
318 assert "headers" not in inv_node.last_message
319 tip = self.mine_blocks(1)
320 assert_equal(inv_node.check_last_announcement(inv=[tip]), True)
321 assert_equal(test_node.check_last_announcement(headers=[tip]), True)
322 height += 1
323 block_time += 1
325 self.log.info("Part 2: success!")
327 self.log.info("Part 3: headers announcements can stop after large reorg, and resume after headers/inv from peer...")
329 # PART 3. Headers announcements can stop after large reorg, and resume after
330 # getheaders or inv from peer.
331 for j in range(2):
332 # First try mining a reorg that can propagate with header announcement
333 new_block_hashes = self.mine_reorg(length=7)
334 tip = new_block_hashes[-1]
335 assert_equal(inv_node.check_last_announcement(inv=[tip]), True)
336 assert_equal(test_node.check_last_announcement(headers=new_block_hashes), True)
338 block_time += 8
340 # Mine a too-large reorg, which should be announced with a single inv
341 new_block_hashes = self.mine_reorg(length=8)
342 tip = new_block_hashes[-1]
343 assert_equal(inv_node.check_last_announcement(inv=[tip]), True)
344 assert_equal(test_node.check_last_announcement(inv=[tip]), True)
346 block_time += 9
348 fork_point = self.nodes[0].getblock("%02x" % new_block_hashes[0])["previousblockhash"]
349 fork_point = int(fork_point, 16)
351 # Use getblocks/getdata
352 test_node.send_getblocks(locator = [fork_point])
353 assert_equal(test_node.check_last_announcement(inv=new_block_hashes), True)
354 test_node.get_data(new_block_hashes)
355 test_node.wait_for_block(new_block_hashes[-1])
357 for i in range(3):
358 # Mine another block, still should get only an inv
359 tip = self.mine_blocks(1)
360 assert_equal(inv_node.check_last_announcement(inv=[tip]), True)
361 assert_equal(test_node.check_last_announcement(inv=[tip]), True)
362 if i == 0:
363 # Just get the data -- shouldn't cause headers announcements to resume
364 test_node.get_data([tip])
365 test_node.wait_for_block(tip)
366 elif i == 1:
367 # Send a getheaders message that shouldn't trigger headers announcements
368 # to resume (best header sent will be too old)
369 test_node.get_headers(locator=[fork_point], hashstop=new_block_hashes[1])
370 test_node.get_data([tip])
371 test_node.wait_for_block(tip)
372 elif i == 2:
373 test_node.get_data([tip])
374 test_node.wait_for_block(tip)
375 # This time, try sending either a getheaders to trigger resumption
376 # of headers announcements, or mine a new block and inv it, also
377 # triggering resumption of headers announcements.
378 if j == 0:
379 test_node.get_headers(locator=[tip], hashstop=0)
380 test_node.sync_with_ping()
381 else:
382 test_node.send_block_inv(tip)
383 test_node.sync_with_ping()
384 # New blocks should now be announced with header
385 tip = self.mine_blocks(1)
386 assert_equal(inv_node.check_last_announcement(inv=[tip]), True)
387 assert_equal(test_node.check_last_announcement(headers=[tip]), True)
389 self.log.info("Part 3: success!")
391 self.log.info("Part 4: Testing direct fetch behavior...")
392 tip = self.mine_blocks(1)
393 height = self.nodes[0].getblockcount() + 1
394 last_time = self.nodes[0].getblock(self.nodes[0].getbestblockhash())['time']
395 block_time = last_time + 1
397 # Create 2 blocks. Send the blocks, then send the headers.
398 blocks = []
399 for b in range(2):
400 blocks.append(create_block(tip, create_coinbase(height), block_time))
401 blocks[-1].solve()
402 tip = blocks[-1].sha256
403 block_time += 1
404 height += 1
405 inv_node.send_message(msg_block(blocks[-1]))
407 inv_node.sync_with_ping() # Make sure blocks are processed
408 test_node.last_message.pop("getdata", None)
409 test_node.send_header_for_blocks(blocks)
410 test_node.sync_with_ping()
411 # should not have received any getdata messages
412 with mininode_lock:
413 assert "getdata" not in test_node.last_message
415 # This time, direct fetch should work
416 blocks = []
417 for b in range(3):
418 blocks.append(create_block(tip, create_coinbase(height), block_time))
419 blocks[-1].solve()
420 tip = blocks[-1].sha256
421 block_time += 1
422 height += 1
424 test_node.send_header_for_blocks(blocks)
425 test_node.sync_with_ping()
426 test_node.wait_for_getdata([x.sha256 for x in blocks], timeout=direct_fetch_response_time)
428 [ test_node.send_message(msg_block(x)) for x in blocks ]
430 test_node.sync_with_ping()
432 # Now announce a header that forks the last two blocks
433 tip = blocks[0].sha256
434 height -= 1
435 blocks = []
437 # Create extra blocks for later
438 for b in range(20):
439 blocks.append(create_block(tip, create_coinbase(height), block_time))
440 blocks[-1].solve()
441 tip = blocks[-1].sha256
442 block_time += 1
443 height += 1
445 # Announcing one block on fork should not trigger direct fetch
446 # (less work than tip)
447 test_node.last_message.pop("getdata", None)
448 test_node.send_header_for_blocks(blocks[0:1])
449 test_node.sync_with_ping()
450 with mininode_lock:
451 assert "getdata" not in test_node.last_message
453 # Announcing one more block on fork should trigger direct fetch for
454 # both blocks (same work as tip)
455 test_node.send_header_for_blocks(blocks[1:2])
456 test_node.sync_with_ping()
457 test_node.wait_for_getdata([x.sha256 for x in blocks[0:2]], timeout=direct_fetch_response_time)
459 # Announcing 16 more headers should trigger direct fetch for 14 more
460 # blocks
461 test_node.send_header_for_blocks(blocks[2:18])
462 test_node.sync_with_ping()
463 test_node.wait_for_getdata([x.sha256 for x in blocks[2:16]], timeout=direct_fetch_response_time)
465 # Announcing 1 more header should not trigger any response
466 test_node.last_message.pop("getdata", None)
467 test_node.send_header_for_blocks(blocks[18:19])
468 test_node.sync_with_ping()
469 with mininode_lock:
470 assert "getdata" not in test_node.last_message
472 self.log.info("Part 4: success!")
474 # Now deliver all those blocks we announced.
475 [ test_node.send_message(msg_block(x)) for x in blocks ]
477 self.log.info("Part 5: Testing handling of unconnecting headers")
478 # First we test that receipt of an unconnecting header doesn't prevent
479 # chain sync.
480 for i in range(10):
481 test_node.last_message.pop("getdata", None)
482 blocks = []
483 # Create two more blocks.
484 for j in range(2):
485 blocks.append(create_block(tip, create_coinbase(height), block_time))
486 blocks[-1].solve()
487 tip = blocks[-1].sha256
488 block_time += 1
489 height += 1
490 # Send the header of the second block -> this won't connect.
491 with mininode_lock:
492 test_node.last_message.pop("getheaders", None)
493 test_node.send_header_for_blocks([blocks[1]])
494 test_node.wait_for_getheaders()
495 test_node.send_header_for_blocks(blocks)
496 test_node.wait_for_getdata([x.sha256 for x in blocks])
497 [ test_node.send_message(msg_block(x)) for x in blocks ]
498 test_node.sync_with_ping()
499 assert_equal(int(self.nodes[0].getbestblockhash(), 16), blocks[1].sha256)
501 blocks = []
502 # Now we test that if we repeatedly don't send connecting headers, we
503 # don't go into an infinite loop trying to get them to connect.
504 MAX_UNCONNECTING_HEADERS = 10
505 for j in range(MAX_UNCONNECTING_HEADERS+1):
506 blocks.append(create_block(tip, create_coinbase(height), block_time))
507 blocks[-1].solve()
508 tip = blocks[-1].sha256
509 block_time += 1
510 height += 1
512 for i in range(1, MAX_UNCONNECTING_HEADERS):
513 # Send a header that doesn't connect, check that we get a getheaders.
514 with mininode_lock:
515 test_node.last_message.pop("getheaders", None)
516 test_node.send_header_for_blocks([blocks[i]])
517 test_node.wait_for_getheaders()
519 # Next header will connect, should re-set our count:
520 test_node.send_header_for_blocks([blocks[0]])
522 # Remove the first two entries (blocks[1] would connect):
523 blocks = blocks[2:]
525 # Now try to see how many unconnecting headers we can send
526 # before we get disconnected. Should be 5*MAX_UNCONNECTING_HEADERS
527 for i in range(5*MAX_UNCONNECTING_HEADERS - 1):
528 # Send a header that doesn't connect, check that we get a getheaders.
529 with mininode_lock:
530 test_node.last_message.pop("getheaders", None)
531 test_node.send_header_for_blocks([blocks[i%len(blocks)]])
532 test_node.wait_for_getheaders()
534 # Eventually this stops working.
535 test_node.send_header_for_blocks([blocks[-1]])
537 # Should get disconnected
538 test_node.wait_for_disconnect()
540 self.log.info("Part 5: success!")
542 # Finally, check that the inv node never received a getdata request,
543 # throughout the test
544 assert "getdata" not in inv_node.last_message
546 if __name__ == '__main__':
547 SendHeadersTest().main()