LCOV - code coverage report
Current view: top level - src/test - headers_sync_chainwork_tests.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 98.3 % 59 58
Test Date: 2025-10-25 05:06:34 Functions: 100.0 % 12 12
Branches: 50.9 % 540 275

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2022-present The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #include <chain.h>
       6                 :             : #include <chainparams.h>
       7                 :             : #include <consensus/params.h>
       8                 :             : #include <headerssync.h>
       9                 :             : #include <net_processing.h>
      10                 :             : #include <pow.h>
      11                 :             : #include <test/util/setup_common.h>
      12                 :             : #include <validation.h>
      13                 :             : 
      14                 :             : #include <cstddef>
      15                 :             : #include <vector>
      16                 :             : 
      17                 :             : #include <boost/test/unit_test.hpp>
      18                 :             : 
      19                 :             : using State = HeadersSyncState::State;
      20                 :             : 
      21                 :             : // Standard set of checks common to all scenarios. Macro keeps failure lines at the call-site.
      22                 :             : #define CHECK_RESULT(result_expression, hss, exp_state, exp_success, exp_request_more,                   \
      23                 :             :                      exp_headers_size, exp_pow_validated_prev, exp_locator_hash)                         \
      24                 :             :     do {                                                                                                 \
      25                 :             :         const auto result{result_expression};                                                            \
      26                 :             :         BOOST_REQUIRE_EQUAL(hss.GetState(), exp_state);                                                  \
      27                 :             :         BOOST_CHECK_EQUAL(result.success, exp_success);                                                  \
      28                 :             :         BOOST_CHECK_EQUAL(result.request_more, exp_request_more);                                        \
      29                 :             :         BOOST_CHECK_EQUAL(result.pow_validated_headers.size(), exp_headers_size);                        \
      30                 :             :         const std::optional<uint256> pow_validated_prev_opt{exp_pow_validated_prev};                     \
      31                 :             :         if (pow_validated_prev_opt) {                                                                    \
      32                 :             :             BOOST_CHECK_EQUAL(result.pow_validated_headers.at(0).hashPrevBlock, pow_validated_prev_opt); \
      33                 :             :         } else {                                                                                         \
      34                 :             :             BOOST_CHECK_EQUAL(exp_headers_size, 0);                                                      \
      35                 :             :         }                                                                                                \
      36                 :             :         const std::optional<uint256> locator_hash_opt{exp_locator_hash};                                 \
      37                 :             :         if (locator_hash_opt) {                                                                          \
      38                 :             :             BOOST_CHECK_EQUAL(hss.NextHeadersRequestLocator().vHave.at(0), locator_hash_opt);            \
      39                 :             :         } else {                                                                                         \
      40                 :             :             BOOST_CHECK_EQUAL(exp_state, State::FINAL);                                                  \
      41                 :             :         }                                                                                                \
      42                 :             :     } while (false)
      43                 :             : 
      44                 :             : constexpr size_t TARGET_BLOCKS{15'000};
      45                 :             : constexpr arith_uint256 CHAIN_WORK{TARGET_BLOCKS * 2};
      46                 :             : 
      47                 :             : // Subtract MAX_HEADERS_RESULTS (2000 headers/message) + an arbitrary smaller
      48                 :             : // value (123) so our redownload buffer is well below the number of blocks
      49                 :             : // required to reach the CHAIN_WORK threshold, to behave similarly to mainnet.
      50                 :             : constexpr size_t REDOWNLOAD_BUFFER_SIZE{TARGET_BLOCKS - (MAX_HEADERS_RESULTS + 123)};
      51                 :             : constexpr size_t COMMITMENT_PERIOD{600}; // Somewhat close to mainnet.
      52                 :             : 
      53                 :           6 : struct HeadersGeneratorSetup : public RegTestingSetup {
      54                 :             :     const CBlock& genesis{Params().GenesisBlock()};
      55   [ +  -  +  -  :           6 :     const CBlockIndex* chain_start{WITH_LOCK(::cs_main, return m_node.chainman->m_blockman.LookupBlockIndex(genesis.GetHash()))};
                   +  - ]
      56                 :             : 
      57                 :             :     // Generate headers for two different chains (using differing merkle roots
      58                 :             :     // to ensure the headers are different).
      59                 :           2 :     const std::vector<CBlockHeader>& FirstChain()
      60                 :             :     {
      61                 :             :         // Block header hash target is half of max uint256 (2**256 / 2), expressible
      62                 :             :         // roughly as the coefficient 0x7fffff with the exponent 0x20 (32 bytes).
      63                 :             :         // This implies around every 2nd hash attempt should succeed, which
      64                 :             :         // is why CHAIN_WORK == TARGET_BLOCKS * 2.
      65         [ -  + ]:           2 :         assert(genesis.nBits == 0x207fffff);
      66                 :             : 
      67                 :             :         // Subtract 1 since the genesis block also contributes work so we reach
      68                 :             :         // the CHAIN_WORK target.
      69                 :           2 :         static const auto first_chain{GenerateHeaders(/*count=*/TARGET_BLOCKS - 1, genesis.GetHash(),
      70   [ +  +  +  -  :           3 :                 genesis.nVersion, genesis.nTime, /*merkle_root=*/uint256::ZERO, genesis.nBits)};
             +  -  +  - ]
      71                 :           2 :         return first_chain;
      72                 :             :     }
      73                 :           2 :     const std::vector<CBlockHeader>& SecondChain()
      74                 :             :     {
      75                 :             :         // Subtract 2 to keep total work below the target.
      76                 :           2 :         static const auto second_chain{GenerateHeaders(/*count=*/TARGET_BLOCKS - 2, genesis.GetHash(),
      77   [ +  +  +  -  :           3 :                 genesis.nVersion, genesis.nTime, /*merkle_root=*/uint256::ONE, genesis.nBits)};
             +  -  +  - ]
      78                 :           2 :         return second_chain;
      79                 :             :     }
      80                 :             : 
      81                 :           4 :     HeadersSyncState CreateState()
      82                 :             :     {
      83                 :           4 :         return {/*id=*/0,
      84                 :           4 :                 Params().GetConsensus(),
      85                 :           4 :                 HeadersSyncParams{
      86                 :             :                     .commitment_period = COMMITMENT_PERIOD,
      87                 :             :                     .redownload_buffer_size = REDOWNLOAD_BUFFER_SIZE,
      88                 :             :                 },
      89                 :             :                 chain_start,
      90                 :           4 :                 /*minimum_required_work=*/CHAIN_WORK};
      91                 :             :     }
      92                 :             : 
      93                 :             : private:
      94                 :             :     /** Search for a nonce to meet (regtest) proof of work */
      95                 :             :     void FindProofOfWork(CBlockHeader& starting_header);
      96                 :             :     /**
      97                 :             :      * Generate headers in a chain that build off a given starting hash, using
      98                 :             :      * the given nVersion, advancing time by 1 second from the starting
      99                 :             :      * prev_time, and with a fixed merkle root hash.
     100                 :             :      */
     101                 :             :     std::vector<CBlockHeader> GenerateHeaders(size_t count,
     102                 :             :             uint256 prev_hash, int32_t nVersion, uint32_t prev_time,
     103                 :             :             const uint256& merkle_root, uint32_t nBits);
     104                 :             : };
     105                 :             : 
     106                 :       29997 : void HeadersGeneratorSetup::FindProofOfWork(CBlockHeader& starting_header)
     107                 :             : {
     108         [ +  + ]:       59957 :     while (!CheckProofOfWork(starting_header.GetHash(), starting_header.nBits, Params().GetConsensus())) {
     109                 :       29960 :         ++starting_header.nNonce;
     110                 :             :     }
     111                 :       29997 : }
     112                 :             : 
     113                 :           2 : std::vector<CBlockHeader> HeadersGeneratorSetup::GenerateHeaders(
     114                 :             :         const size_t count, uint256 prev_hash, const int32_t nVersion,
     115                 :             :         uint32_t prev_time, const uint256& merkle_root, const uint32_t nBits)
     116                 :             : {
     117                 :           2 :     std::vector<CBlockHeader> headers(count);
     118         [ +  + ]:       29999 :     for (auto& next_header : headers) {
     119                 :       29997 :         next_header.nVersion = nVersion;
     120                 :       29997 :         next_header.hashPrevBlock = prev_hash;
     121                 :       29997 :         next_header.hashMerkleRoot = merkle_root;
     122                 :       29997 :         next_header.nTime = ++prev_time;
     123                 :       29997 :         next_header.nBits = nBits;
     124                 :             : 
     125         [ +  - ]:       29997 :         FindProofOfWork(next_header);
     126         [ +  - ]:       29997 :         prev_hash = next_header.GetHash();
     127                 :             :     }
     128                 :           2 :     return headers;
     129                 :           0 : }
     130                 :             : 
     131                 :             : // In this test, we construct two sets of headers from genesis, one with
     132                 :             : // sufficient proof of work and one without.
     133                 :             : // 1. We deliver the first set of headers and verify that the headers sync state
     134                 :             : //    updates to the REDOWNLOAD phase successfully.
     135                 :             : //    Then we deliver the second set of headers and verify that they fail
     136                 :             : //    processing (presumably due to commitments not matching).
     137                 :             : // 2. Verify that repeating with the first set of headers in both phases is
     138                 :             : //    successful.
     139                 :             : // 3. Repeat the second set of headers in both phases to demonstrate behavior
     140                 :             : //    when the chain a peer provides has too little work.
     141                 :             : BOOST_FIXTURE_TEST_SUITE(headers_sync_chainwork_tests, HeadersGeneratorSetup)
     142                 :             : 
     143   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(sneaky_redownload)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     144                 :             : {
     145                 :           1 :     const auto& first_chain{FirstChain()};
     146                 :           1 :     const auto& second_chain{SecondChain()};
     147                 :             : 
     148                 :             :     // Feed the first chain to HeadersSyncState, by delivering 1 header
     149                 :             :     // initially and then the rest.
     150                 :           1 :     HeadersSyncState hss{CreateState()};
     151                 :             : 
     152                 :             :     // Just feed one header and check state.
     153                 :             :     // Pretend the message is still "full", so we don't abort.
     154   [ +  -  +  -  :           2 :     CHECK_RESULT(hss.ProcessNextHeaders({{first_chain.front()}}, /*full_headers_message=*/true),
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
                -  +  - ]
     155                 :             :         hss, /*exp_state=*/State::PRESYNC,
     156                 :             :         /*exp_success*/true, /*exp_request_more=*/true,
     157                 :             :         /*exp_headers_size=*/0, /*exp_pow_validated_prev=*/std::nullopt,
     158                 :             :         /*exp_locator_hash=*/first_chain.front().GetHash());
     159                 :             : 
     160                 :             :     // This chain should look valid, and we should have met the proof-of-work
     161                 :             :     // requirement during PRESYNC and transitioned to REDOWNLOAD.
     162   [ -  +  +  -  :           2 :     CHECK_RESULT(hss.ProcessNextHeaders(std::span{first_chain}.subspan(1), true),
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
             -  +  -  +  
                      - ]
     163                 :             :         hss, /*exp_state=*/State::REDOWNLOAD,
     164                 :             :         /*exp_success*/true, /*exp_request_more=*/true,
     165                 :             :         /*exp_headers_size=*/0, /*exp_pow_validated_prev=*/std::nullopt,
     166                 :             :         /*exp_locator_hash=*/genesis.GetHash());
     167                 :             : 
     168                 :             :     // Below is the number of commitment bits that must randomly match between
     169                 :             :     // the two chains for this test to spuriously fail. 1 / 2^25 =
     170                 :             :     // 1 in 33'554'432 (somewhat less due to HeadersSyncState::m_commit_offset).
     171                 :           1 :     static_assert(TARGET_BLOCKS / COMMITMENT_PERIOD == 25);
     172                 :             : 
     173                 :             :     // Try to sneakily feed back the second chain during REDOWNLOAD.
     174   [ -  +  +  -  :           1 :     CHECK_RESULT(hss.ProcessNextHeaders(second_chain, true),
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
                      - ]
     175                 :             :         hss, /*exp_state=*/State::FINAL,
     176                 :             :         /*exp_success*/false, // Foiled! We detected mismatching headers.
     177                 :             :         /*exp_request_more=*/false,
     178                 :             :         /*exp_headers_size=*/0, /*exp_pow_validated_prev=*/std::nullopt,
     179                 :             :         /*exp_locator_hash=*/std::nullopt);
     180                 :           1 : }
     181                 :             : 
     182   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(happy_path)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     183                 :             : {
     184                 :           1 :     const auto& first_chain{FirstChain()};
     185                 :             : 
     186                 :             :     // Headers message that moves us to the next state doesn't need to be full.
     187         [ +  + ]:           3 :     for (const bool full_headers_message : {false, true}) {
     188                 :             :         // This time we feed the first chain twice.
     189                 :           2 :         HeadersSyncState hss{CreateState()};
     190                 :             : 
     191                 :             :         // Sufficient work transitions us from PRESYNC to REDOWNLOAD:
     192         [ +  - ]:           2 :         const auto genesis_hash{genesis.GetHash()};
     193   [ -  +  +  -  :           4 :         CHECK_RESULT(hss.ProcessNextHeaders(first_chain, full_headers_message),
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
                -  +  - ]
     194                 :             :             hss, /*exp_state=*/State::REDOWNLOAD,
     195                 :             :             /*exp_success*/true, /*exp_request_more=*/true,
     196                 :             :             /*exp_headers_size=*/0, /*exp_pow_validated_prev=*/std::nullopt,
     197                 :             :             /*exp_locator_hash=*/genesis_hash);
     198                 :             : 
     199                 :             :         // Process only so that the internal threshold isn't exceeded, meaning
     200                 :             :         // validated headers shouldn't be returned yet:
     201   [ +  -  +  -  :           4 :         CHECK_RESULT(hss.ProcessNextHeaders({first_chain.begin(), REDOWNLOAD_BUFFER_SIZE}, true),
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
                -  +  - ]
     202                 :             :             hss, /*exp_state=*/State::REDOWNLOAD,
     203                 :             :             /*exp_success*/true, /*exp_request_more=*/true,
     204                 :             :             /*exp_headers_size=*/0, /*exp_pow_validated_prev=*/std::nullopt,
     205                 :             :             /*exp_locator_hash=*/first_chain[REDOWNLOAD_BUFFER_SIZE - 1].GetHash());
     206                 :             : 
     207                 :             :         // We start receiving headers for permanent storage before completing:
     208   [ +  -  +  -  :           4 :         CHECK_RESULT(hss.ProcessNextHeaders({{first_chain[REDOWNLOAD_BUFFER_SIZE]}}, true),
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
             -  +  -  +  
                      - ]
     209                 :             :             hss, /*exp_state=*/State::REDOWNLOAD,
     210                 :             :             /*exp_success*/true, /*exp_request_more=*/true,
     211                 :             :             /*exp_headers_size=*/1, /*exp_pow_validated_prev=*/genesis_hash,
     212                 :             :             /*exp_locator_hash=*/first_chain[REDOWNLOAD_BUFFER_SIZE].GetHash());
     213                 :             : 
     214                 :             :         // Feed in remaining headers, meeting the work threshold again and
     215                 :             :         // completing the REDOWNLOAD phase:
     216   [ +  -  +  -  :           2 :         CHECK_RESULT(hss.ProcessNextHeaders({first_chain.begin() + REDOWNLOAD_BUFFER_SIZE + 1, first_chain.end()}, full_headers_message),
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  -  
          +  +  -  +  -  
          +  -  +  -  +  
             -  +  -  +  
                      - ]
     217                 :             :             hss, /*exp_state=*/State::FINAL,
     218                 :             :             /*exp_success*/true, /*exp_request_more=*/false,
     219                 :             :             // All headers except the one already returned above:
     220                 :             :             /*exp_headers_size=*/first_chain.size() - 1, /*exp_pow_validated_prev=*/first_chain.front().GetHash(),
     221                 :             :             /*exp_locator_hash=*/std::nullopt);
     222                 :           2 :     }
     223                 :           1 : }
     224                 :             : 
     225   [ +  -  +  -  :           7 : BOOST_AUTO_TEST_CASE(too_little_work)
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  +  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
                      - ]
     226                 :             : {
     227                 :           1 :     const auto& second_chain{SecondChain()};
     228                 :             : 
     229                 :             :     // Verify that just trying to process the second chain would not succeed
     230                 :             :     // (too little work).
     231                 :           1 :     HeadersSyncState hss{CreateState()};
     232   [ +  -  +  - ]:           1 :     BOOST_REQUIRE_EQUAL(hss.GetState(), State::PRESYNC);
     233                 :             : 
     234                 :             :     // Pretend just the first message is "full", so we don't abort.
     235   [ +  -  +  -  :           2 :     CHECK_RESULT(hss.ProcessNextHeaders({{second_chain.front()}}, true),
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  +  -  +  
                -  +  - ]
     236                 :             :         hss, /*exp_state=*/State::PRESYNC,
     237                 :             :         /*exp_success*/true, /*exp_request_more=*/true,
     238                 :             :         /*exp_headers_size=*/0, /*exp_pow_validated_prev=*/std::nullopt,
     239                 :             :         /*exp_locator_hash=*/second_chain.front().GetHash());
     240                 :             : 
     241                 :             :     // Tell the sync logic that the headers message was not full, implying no
     242                 :             :     // more headers can be requested. For a low-work-chain, this should cause
     243                 :             :     // the sync to end with no headers for acceptance.
     244   [ -  +  +  -  :           1 :     CHECK_RESULT(hss.ProcessNextHeaders(std::span{second_chain}.subspan(1), false),
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  -  
          +  +  -  +  -  
          +  -  +  -  +  
                      - ]
     245                 :             :         hss, /*exp_state=*/State::FINAL,
     246                 :             :         // Nevertheless, no validation errors should have been detected with the
     247                 :             :         // chain:
     248                 :             :         /*exp_success*/true,
     249                 :             :         /*exp_request_more=*/false,
     250                 :             :         /*exp_headers_size=*/0, /*exp_pow_validated_prev=*/std::nullopt,
     251                 :             :         /*exp_locator_hash=*/std::nullopt);
     252                 :           1 : }
     253                 :             : 
     254                 :             : BOOST_AUTO_TEST_SUITE_END()
        

Generated by: LCOV version 2.0-1