Repository: bitcoin/bitcoin
File: test/functional/p2p_initial_headers_sync.py (Python)

Code before:
    p2p_lock,
    P2PInterface,
)
from test_framework.util import (
    assert_equal,
)
import random

class HeadersSyncTest(BitcoinTestFramework):
    def set_test_params(self):
        self.setup_clean_chain = True
        self.num_nodes = 1

    def announce_random_block(self, peers):
        new_block_announcement = msg_inv(inv=[CInv(MSG_BLOCK, random.randrange(1<<256))])
        for p in peers:
            p.send_and_ping(new_block_announcement)

    def run_test(self):
        self.log.info("Adding a peer to node0")
        peer1 = self.nodes[0].add_p2p_connection(P2PInterface())
        best_block_hash = int(self.nodes[0].getbestblockhash(), 16)

        # Wait for peer1 to receive a getheaders
        peer1.wait_for_getheaders(block_hash=best_block_hash)
        # An empty reply will clear the outstanding getheaders request,
        # allowing additional getheaders requests to be sent to this peer in
        # the future.
        peer1.send_without_ping(msg_headers())

        self.log.info("Connecting two more peers to node0")
        # Connect 2 more peers; they should not receive a getheaders yet
        peer2 = self.nodes[0].add_p2p_connection(P2PInterface())
        peer3 = self.nodes[0].add_p2p_connection(P2PInterface())

        all_peers = [peer1, peer2, peer3]

        self.log.info("Verify that peer2 and peer3 don't receive a getheaders after connecting")
        for p in all_peers:
            p.sync_with_ping()
        with p2p_lock:
            assert "getheaders" not in peer2.last_message
            assert "getheaders" not in peer3.last_message

        self.log.info("Have all peers announce a new block")
        self.announce_random_block(all_peers)

        self.log.info("Check that peer1 receives a getheaders in response")
        peer1.wait_for_getheaders(block_hash=best_block_hash)
        peer1.send_without_ping(msg_headers()) # Send empty response, see above


Review comment (suggestion):
```suggestion
    variable_timeout_sec = math.ceil(HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER_MS /1_000 *
                           seconds_since_best_header / POW_TARGET_SPACING_SEC)   # ceil, to make this function usable with mocktime, which only has second precision.

    return (current_time + HEADERS_DOWNLOAD_TIMEOUT_BASE_SEC + variable_timeout_sec)
```

seems a bit odd to be rounding down in this function and then apply a random +1 offset below. So it is actually rounding up. It would be better to just round up directly. Also, documenting why rounding is needed at all can't hurt. Finally, 1000/1000000 can be written as 1/1000.

Code after:
    msg_inv,
)
from test_framework.p2p import (
    p2p_lock,
    P2PInterface,
)
from test_framework.util import (
    assert_equal,
)
import math
import random
import time

# Constants from net_processing
HEADERS_DOWNLOAD_TIMEOUT_BASE_SEC = 15 * 60
HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER_MS = 1
POW_TARGET_SPACING_SEC = 10 * 60


def calculate_headers_timeout(best_header_time, current_time):
    seconds_since_best_header = current_time - best_header_time
    # Using ceil ensures the calculated timeout is >= actual timeout and not lower
    # because of precision loss from conversion to seconds
    variable_timeout_sec = math.ceil(HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER_MS / 1_000 *
                                     seconds_since_best_header / POW_TARGET_SPACING_SEC)
    return int(current_time + HEADERS_DOWNLOAD_TIMEOUT_BASE_SEC + variable_timeout_sec)


class HeadersSyncTest(BitcoinTestFramework):
    def set_test_params(self):
        self.setup_clean_chain = True
        self.num_nodes = 1

    def announce_random_block(self, peers):
        new_block_announcement = msg_inv(inv=[CInv(MSG_BLOCK, random.randrange(1<<256))])
        for p in peers:
            p.send_and_ping(new_block_announcement)

    def assert_single_getheaders_recipient(self, peers):
        count = 0
        receiving_peer = None
        for p in peers:
            with p2p_lock:
                if "getheaders" in p.last_message:
                    count += 1
                    receiving_peer = p
        assert_equal(count, 1)
        return receiving_peer

    def test_initial_headers_sync(self):
        self.log.info("Test initial headers sync")