From f0c4ab9a7034aca6be83fcb6cd8479cd19a196a2 Mon Sep 17 00:00:00 2001
From: John Newbery <john@johnnewbery.com>
Date: Thu, 16 Nov 2017 11:52:59 -0500
Subject: [PATCH] [tests] fix flakiness in sendheaders.py

Fixes to sources of intermittent failure in sendheaders.py

- at the start of test_null_locators(), a new block is generated and
then a getheaders is sent. check_last_accouncement() is called to assert
that the headers message is received. However, the new block triggers an
inv to be sent over both P2P connections, so there's a race. If the inv
is received at the wrong time, the test fails.

- test_null_locators() ends by sending a block to the node under test.
At the start of test_nonnull_locators(), a block is mined and
check_last_announcement() is called to assert that the inv received is
for the same block. That means there's a race: if the inv from the block
sent in test_null_locators() is received at the wrong time, the test
fails.
---
 test/functional/sendheaders.py | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/test/functional/sendheaders.py b/test/functional/sendheaders.py
index 1a585dd11..056471370 100755
--- a/test/functional/sendheaders.py
+++ b/test/functional/sendheaders.py
@@ -243,13 +243,16 @@ class SendHeadersTest(BitcoinTestFramework):
         inv_node.sync_with_ping()
         test_node.sync_with_ping()
 
-        self.test_null_locators(test_node)
+        self.test_null_locators(test_node, inv_node)
         self.test_nonnull_locators(test_node, inv_node)
 
-    def test_null_locators(self, test_node):
+    def test_null_locators(self, test_node, inv_node):
         tip = self.nodes[0].getblockheader(self.nodes[0].generate(1)[0])
         tip_hash = int(tip["hash"], 16)
 
+        inv_node.check_last_announcement(inv=[tip_hash], headers=[])
+        test_node.check_last_announcement(inv=[tip_hash], headers=[])
+
         self.log.info("Verify getheaders with null locator and valid hashstop returns headers.")
         test_node.clear_last_announcement()
         test_node.send_get_headers(locator=[], hashstop=tip_hash)
@@ -263,7 +266,10 @@ class SendHeadersTest(BitcoinTestFramework):
         test_node.send_get_headers(locator=[], hashstop=int(block.hash, 16))
         test_node.sync_with_ping()
         assert_equal(test_node.block_announced, False)
+        inv_node.clear_last_announcement()
         test_node.send_message(msg_block(block))
+        inv_node.check_last_announcement(inv=[int(block.hash, 16)], headers=[])
+        inv_node.clear_last_announcement()
 
     def test_nonnull_locators(self, test_node, inv_node):
         tip = int(self.nodes[0].getbestblockhash(), 16)