LCOV - code coverage report
Current view: top level - src/test/fuzz - p2p_headers_presync.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 98.3 % 118 116
Test Date: 2024-12-04 04:00:22 Functions: 100.0 % 16 16
Branches: 53.6 % 140 75

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2024-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 <arith_uint256.h>
       6                 :             : #include <blockencodings.h>
       7                 :             : #include <net.h>
       8                 :             : #include <net_processing.h>
       9                 :             : #include <netmessagemaker.h>
      10                 :             : #include <node/peerman_args.h>
      11                 :             : #include <pow.h>
      12                 :             : #include <test/fuzz/FuzzedDataProvider.h>
      13                 :             : #include <test/fuzz/fuzz.h>
      14                 :             : #include <test/fuzz/util.h>
      15                 :             : #include <test/util/net.h>
      16                 :             : #include <test/util/script.h>
      17                 :             : #include <test/util/setup_common.h>
      18                 :             : #include <uint256.h>
      19                 :             : #include <validation.h>
      20                 :             : 
      21                 :             : namespace {
      22                 :             : constexpr uint32_t FUZZ_MAX_HEADERS_RESULTS{16};
      23                 :             : 
      24                 :           1 : class HeadersSyncSetup : public TestingSetup
      25                 :             : {
      26                 :             :     std::vector<CNode*> m_connections;
      27                 :             : 
      28                 :             : public:
      29   [ +  -  +  - ]:           2 :     HeadersSyncSetup(const ChainType chain_type, TestOpts opts) : TestingSetup(chain_type, opts)
      30                 :             :     {
      31                 :           1 :         PeerManager::Options peerman_opts;
      32         [ +  - ]:           1 :         node::ApplyArgsManOptions(*m_node.args, peerman_opts);
      33                 :           1 :         peerman_opts.max_headers_result = FUZZ_MAX_HEADERS_RESULTS;
      34                 :           2 :         m_node.peerman = PeerManager::make(*m_node.connman, *m_node.addrman,
      35         [ +  - ]:           1 :                                            m_node.banman.get(), *m_node.chainman,
      36         [ +  - ]:           1 :                                            *m_node.mempool, *m_node.warnings, peerman_opts);
      37                 :             : 
      38                 :           1 :         CConnman::Options options;
      39         [ +  - ]:           1 :         options.m_msgproc = m_node.peerman.get();
      40         [ +  - ]:           1 :         m_node.connman->Init(options);
      41                 :           1 :     }
      42                 :             : 
      43                 :             :     void ResetAndInitialize() EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex);
      44                 :             :     void SendMessage(FuzzedDataProvider& fuzzed_data_provider, CSerializedNetMsg&& msg)
      45                 :             :         EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex);
      46                 :             : };
      47                 :             : 
      48                 :         414 : void HeadersSyncSetup::ResetAndInitialize()
      49                 :             : {
      50         [ +  + ]:         414 :     m_connections.clear();
      51                 :         414 :     auto& connman = static_cast<ConnmanTestMsg&>(*m_node.connman);
      52                 :         414 :     connman.StopNodes();
      53                 :             : 
      54                 :         414 :     NodeId id{0};
      55                 :         414 :     std::vector<ConnectionType> conn_types = {
      56                 :             :         ConnectionType::OUTBOUND_FULL_RELAY,
      57                 :             :         ConnectionType::BLOCK_RELAY,
      58                 :             :         ConnectionType::INBOUND
      59                 :         414 :     };
      60                 :             : 
      61         [ +  + ]:        1656 :     for (auto conn_type : conn_types) {
      62         [ +  - ]:        1242 :         CAddress addr{};
      63   [ +  -  +  -  :        2484 :         m_connections.push_back(new CNode(id++, nullptr, addr, 0, 0, addr, "", conn_type, false));
          +  -  -  +  -  
                      - ]
      64                 :        1242 :         CNode& p2p_node = *m_connections.back();
      65                 :             : 
      66         [ +  - ]:        1242 :         connman.Handshake(
      67                 :             :             /*node=*/p2p_node,
      68                 :             :             /*successfully_connected=*/true,
      69                 :             :             /*remote_services=*/ServiceFlags(NODE_NETWORK | NODE_WITNESS),
      70                 :             :             /*local_services=*/ServiceFlags(NODE_NETWORK | NODE_WITNESS),
      71                 :             :             /*version=*/PROTOCOL_VERSION,
      72                 :             :             /*relay_txs=*/true);
      73                 :             : 
      74         [ +  - ]:        1242 :         connman.AddTestNode(p2p_node);
      75                 :        1242 :     }
      76         [ +  - ]:        1656 : }
      77                 :             : 
      78                 :       12230 : void HeadersSyncSetup::SendMessage(FuzzedDataProvider& fuzzed_data_provider, CSerializedNetMsg&& msg)
      79                 :             : {
      80                 :       12230 :     auto& connman = static_cast<ConnmanTestMsg&>(*m_node.connman);
      81                 :       12230 :     CNode& connection = *PickValue(fuzzed_data_provider, m_connections);
      82                 :             : 
      83                 :       12230 :     connman.FlushSendBuffer(connection);
      84                 :       12230 :     (void)connman.ReceiveMsgFrom(connection, std::move(msg));
      85         [ +  - ]:       12230 :     connection.fPauseSend = false;
      86                 :       12230 :     try {
      87         [ +  - ]:       12230 :         connman.ProcessMessagesOnce(connection);
      88         [ -  - ]:           0 :     } catch (const std::ios_base::failure&) {
      89                 :           0 :     }
      90                 :       12230 :     m_node.peerman->SendMessages(&connection);
      91                 :       12230 : }
      92                 :             : 
      93                 :       68315 : CBlockHeader ConsumeHeader(FuzzedDataProvider& fuzzed_data_provider, const uint256& prev_hash, uint32_t prev_nbits)
      94                 :             : {
      95                 :       68315 :     CBlockHeader header;
      96                 :       68315 :     header.nNonce = 0;
      97                 :             :     // Either use the previous difficulty or let the fuzzer choose. The upper target in the
      98                 :             :     // range comes from the bits value of the genesis block, which is 0x1d00ffff. The lower
      99                 :             :     // target comes from the bits value of mainnet block 840000, which is 0x17034219.
     100                 :             :     // Calling lower_target.SetCompact(0x17034219) and upper_target.SetCompact(0x1d00ffff)
     101                 :             :     // should return the values below.
     102                 :             :     //
     103                 :             :     // RPC commands to verify:
     104                 :             :     // getblockheader 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
     105                 :             :     // getblockheader 0000000000000000000320283a032748cef8227873ff4872689bf23f1cda83a5
     106         [ +  + ]:       68315 :     if (fuzzed_data_provider.ConsumeBool()) {
     107                 :       64703 :         header.nBits = prev_nbits;
     108                 :             :     } else {
     109                 :        3612 :         arith_uint256 lower_target = UintToArith256(uint256{"0000000000000000000342190000000000000000000000000000000000000000"});
     110                 :        3612 :         arith_uint256 upper_target = UintToArith256(uint256{"00000000ffff0000000000000000000000000000000000000000000000000000"});
     111                 :        3612 :         arith_uint256 target = ConsumeArithUInt256InRange(fuzzed_data_provider, lower_target, upper_target);
     112                 :        3612 :         header.nBits = target.GetCompact();
     113                 :             :     }
     114                 :       68315 :     header.nTime = ConsumeTime(fuzzed_data_provider);
     115                 :       68315 :     header.hashPrevBlock = prev_hash;
     116                 :       68315 :     header.nVersion = fuzzed_data_provider.ConsumeIntegral<int32_t>();
     117                 :       68315 :     return header;
     118                 :             : }
     119                 :             : 
     120                 :        8491 : CBlock ConsumeBlock(FuzzedDataProvider& fuzzed_data_provider, const uint256& prev_hash, uint32_t prev_nbits)
     121                 :             : {
     122                 :        8491 :     auto header = ConsumeHeader(fuzzed_data_provider, prev_hash, prev_nbits);
     123                 :             :     // In order to reach the headers acceptance logic, the block is
     124                 :             :     // constructed in a way that will pass the mutation checks.
     125                 :        8491 :     CBlock block{header};
     126         [ +  - ]:        8491 :     CMutableTransaction tx;
     127         [ +  - ]:        8491 :     tx.vin.resize(1);
     128         [ +  - ]:        8491 :     tx.vout.resize(1);
     129                 :        8491 :     tx.vout[0].nValue = 0;
     130                 :        8491 :     tx.vin[0].scriptSig.resize(2);
     131   [ +  -  +  -  :       16982 :     block.vtx.push_back(MakeTransactionRef(tx));
                   -  + ]
     132                 :        8491 :     block.hashMerkleRoot = block.vtx[0]->GetHash();
     133                 :        8491 :     return block;
     134                 :        8491 : }
     135                 :             : 
     136                 :       68315 : void FinalizeHeader(CBlockHeader& header, const ChainstateManager& chainman)
     137                 :             : {
     138         [ +  + ]:      137110 :     while (!CheckProofOfWork(header.GetHash(), header.nBits, chainman.GetParams().GetConsensus())) {
     139                 :       68795 :         ++(header.nNonce);
     140                 :             :     }
     141                 :       68315 : }
     142                 :             : 
     143                 :             : // Global setup works for this test as state modification (specifically in the
     144                 :             : // block index) would indicate a bug.
     145                 :             : HeadersSyncSetup* g_testing_setup;
     146                 :             : 
     147                 :           1 : void initialize()
     148                 :             : {
     149   [ +  -  +  -  :           2 :     static auto setup = MakeNoLogFileContext<HeadersSyncSetup>(ChainType::MAIN, {.extra_args = {"-checkpoints=0"}});
                   +  - ]
     150                 :           1 :     g_testing_setup = setup.get();
     151         [ +  - ]:           2 : }
     152                 :             : } // namespace
     153                 :             : 
     154         [ +  - ]:         826 : FUZZ_TARGET(p2p_headers_presync, .init = initialize)
     155                 :             : {
     156                 :         414 :     ChainstateManager& chainman = *g_testing_setup->m_node.chainman;
     157                 :             : 
     158                 :         414 :     LOCK(NetEventsInterface::g_msgproc_mutex);
     159                 :             : 
     160         [ +  - ]:         414 :     g_testing_setup->ResetAndInitialize();
     161                 :             : 
     162         [ +  - ]:         414 :     FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
     163                 :             : 
     164         [ +  - ]:         414 :     CBlockHeader base{chainman.GetParams().GenesisBlock()};
     165         [ +  - ]:         414 :     SetMockTime(base.nTime);
     166                 :             : 
     167                 :             :     // The chain is just a single block, so this is equal to 1
     168         [ +  - ]:         828 :     size_t original_index_size{WITH_LOCK(cs_main, return chainman.m_blockman.m_block_index.size())};
     169         [ +  - ]:        1242 :     arith_uint256 total_work{WITH_LOCK(cs_main, return chainman.m_best_header->nChainWork)};
     170                 :             : 
     171                 :         414 :     std::vector<CBlockHeader> all_headers;
     172                 :             : 
     173   [ +  +  +  + ]:       12644 :     LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 100)
     174                 :             :     {
     175                 :       20721 :         auto finalized_block = [&]() {
     176                 :        8491 :             CBlock block = ConsumeBlock(fuzzed_data_provider, base.GetHash(), base.nBits);
     177         [ +  - ]:        8491 :             FinalizeHeader(block, chainman);
     178                 :        8491 :             return block;
     179                 :       12230 :         };
     180                 :             : 
     181                 :             :         // Send low-work headers, compact blocks, and blocks
     182         [ +  - ]:       12230 :         CallOneOf(
     183                 :             :             fuzzed_data_provider,
     184                 :        3739 :             [&]() NO_THREAD_SAFETY_ANALYSIS {
     185                 :             :                 // Send FUZZ_MAX_HEADERS_RESULTS headers
     186                 :        3739 :                 std::vector<CBlock> headers;
     187         [ +  - ]:        3739 :                 headers.resize(FUZZ_MAX_HEADERS_RESULTS);
     188         [ +  + ]:       63563 :                 for (CBlock& header : headers) {
     189   [ +  -  +  - ]:       59824 :                     header = ConsumeHeader(fuzzed_data_provider, base.GetHash(), base.nBits);
     190         [ +  - ]:       59824 :                     FinalizeHeader(header, chainman);
     191                 :       59824 :                     base = header;
     192                 :             :                 }
     193                 :             : 
     194         [ +  - ]:        3739 :                 all_headers.insert(all_headers.end(), headers.begin(), headers.end());
     195                 :             : 
     196   [ +  -  +  - ]:        3739 :                 auto headers_msg = NetMsg::Make(NetMsgType::HEADERS, TX_WITH_WITNESS(headers));
     197         [ +  - ]:        3739 :                 g_testing_setup->SendMessage(fuzzed_data_provider, std::move(headers_msg));
     198                 :        3739 :             },
     199                 :        3615 :             [&]() NO_THREAD_SAFETY_ANALYSIS {
     200                 :             :                 // Send a compact block
     201                 :        3615 :                 auto block = finalized_block();
     202         [ +  - ]:        3615 :                 CBlockHeaderAndShortTxIDs cmpct_block{block, fuzzed_data_provider.ConsumeIntegral<uint64_t>()};
     203                 :             : 
     204         [ +  - ]:        3615 :                 all_headers.push_back(block);
     205                 :             : 
     206   [ +  -  +  - ]:        3615 :                 auto headers_msg = NetMsg::Make(NetMsgType::CMPCTBLOCK, TX_WITH_WITNESS(cmpct_block));
     207         [ +  - ]:        3615 :                 g_testing_setup->SendMessage(fuzzed_data_provider, std::move(headers_msg));
     208                 :        7230 :             },
     209                 :        4876 :             [&]() NO_THREAD_SAFETY_ANALYSIS {
     210                 :             :                 // Send a block
     211                 :        4876 :                 auto block = finalized_block();
     212                 :             : 
     213         [ +  - ]:        4876 :                 all_headers.push_back(block);
     214                 :             : 
     215   [ +  -  +  - ]:        4876 :                 auto headers_msg = NetMsg::Make(NetMsgType::BLOCK, TX_WITH_WITNESS(block));
     216         [ +  - ]:        4876 :                 g_testing_setup->SendMessage(fuzzed_data_provider, std::move(headers_msg));
     217                 :        4876 :             });
     218                 :             :     }
     219                 :             : 
     220                 :             :     // This is a conservative overestimate, as base is only moved forward when sending headers. In theory,
     221                 :             :     // the longest chain generated by this test is 1600 (FUZZ_MAX_HEADERS_RESULTS * 100) headers. In that case,
     222                 :             :     // this variable will accurately reflect the chain's total work.
     223         [ +  - ]:         414 :     total_work += CalculateClaimedHeadersWork(all_headers);
     224                 :             : 
     225                 :             :     // This test should never create a chain with more work than MinimumChainWork.
     226   [ +  -  +  -  :         414 :     assert(total_work < chainman.MinimumChainWork());
                   -  + ]
     227                 :             : 
     228                 :             :     // The headers/blocks sent in this test should never be stored, as the chains don't have the work required
     229                 :             :     // to meet the anti-DoS work threshold. So, if at any point the block index grew in size, then there's a bug
     230                 :             :     // in the headers pre-sync logic.
     231   [ +  -  -  + ]:         828 :     assert(WITH_LOCK(cs_main, return chainman.m_blockman.m_block_index.size()) == original_index_size);
     232                 :             : 
     233         [ +  - ]:         414 :     g_testing_setup->m_node.validation_signals->SyncWithValidationInterfaceQueue();
     234         [ +  - ]:         828 : }
        

Generated by: LCOV version 2.0-1