LCOV - code coverage report
Current view: top level - src/test/fuzz - versionbits.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 98.9 % 174 172
Test Date: 2026-12-01 05:40:45 Functions: 100.0 % 8 8
Branches: 64.5 % 262 169

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2020-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 <versionbits.h>
       6                 :             : 
       7                 :             : #include <chain.h>
       8                 :             : #include <chainparams.h>
       9                 :             : #include <common/args.h>
      10                 :             : #include <consensus/params.h>
      11                 :             : #include <primitives/block.h>
      12                 :             : #include <test/fuzz/FuzzedDataProvider.h>
      13                 :             : #include <test/fuzz/fuzz.h>
      14                 :             : #include <test/fuzz/util.h>
      15                 :             : #include <test/util/versionbits.h>
      16                 :             : #include <util/chaintype.h>
      17                 :             : #include <util/check.h>
      18                 :             : #include <versionbits_impl.h>
      19                 :             : 
      20                 :             : #include <cstdint>
      21                 :             : #include <limits>
      22                 :             : #include <memory>
      23                 :             : #include <vector>
      24                 :             : 
      25                 :             : namespace {
      26                 :         217 : class TestConditionChecker : public VersionBitsConditionChecker
      27                 :             : {
      28                 :             : private:
      29                 :             :     mutable ThresholdConditionCache m_cache;
      30                 :             : 
      31                 :             : public:
      32         [ -  + ]:         217 :     TestConditionChecker(const Consensus::BIP9Deployment& dep) : VersionBitsConditionChecker{dep}
      33                 :             :     {
      34         [ -  + ]:         217 :         assert(dep.period > 0);
      35         [ -  + ]:         217 :         assert(dep.threshold <= dep.period);
      36         [ -  + ]:         217 :         assert(0 <= dep.bit && dep.bit < 32 && dep.bit < VERSIONBITS_MAX_NUM_BITS);
      37         [ -  + ]:         217 :         assert(0 <= dep.min_activation_height);
      38                 :         217 :     }
      39                 :             : 
      40                 :        6633 :     ThresholdState GetStateFor(const CBlockIndex* pindexPrev) const { return AbstractThresholdConditionChecker::GetStateFor(pindexPrev, m_cache); }
      41                 :        6633 :     int GetStateSinceHeightFor(const CBlockIndex* pindexPrev) const { return AbstractThresholdConditionChecker::GetStateSinceHeightFor(pindexPrev, m_cache); }
      42                 :             : };
      43                 :             : 
      44                 :             : /** Track blocks mined for test */
      45                 :           0 : class Blocks
      46                 :             : {
      47                 :             : private:
      48                 :             :     std::vector<std::unique_ptr<CBlockIndex>> m_blocks;
      49                 :             :     const uint32_t m_start_time;
      50                 :             :     const uint32_t m_interval;
      51                 :             :     const int32_t m_signal;
      52                 :             :     const int32_t m_no_signal;
      53                 :             : 
      54                 :             : public:
      55                 :         217 :     Blocks(uint32_t start_time, uint32_t interval, int32_t signal, int32_t no_signal)
      56                 :         217 :         : m_start_time{start_time}, m_interval{interval}, m_signal{signal}, m_no_signal{no_signal} {}
      57                 :             : 
      58                 :        4830 :     size_t size() const { return m_blocks.size(); }
      59                 :             : 
      60                 :       77481 :     CBlockIndex* tip() const
      61                 :             :     {
      62         [ +  + ]:       77481 :         return m_blocks.empty() ? nullptr : m_blocks.back().get();
      63                 :             :     }
      64                 :             : 
      65                 :       77280 :     CBlockIndex* mine_block(bool signal)
      66                 :             :     {
      67                 :       77280 :         CBlockHeader header;
      68         [ +  + ]:       77280 :         header.nVersion = signal ? m_signal : m_no_signal;
      69         [ -  + ]:       77280 :         header.nTime = m_start_time + m_blocks.size() * m_interval;
      70                 :       77280 :         header.nBits = 0x1d00ffff;
      71                 :             : 
      72                 :       77280 :         auto current_block = std::make_unique<CBlockIndex>(header);
      73         [ -  + ]:       77280 :         current_block->pprev = tip();
      74   [ -  +  +  - ]:       77280 :         current_block->nHeight = m_blocks.size();
      75         [ +  - ]:       77280 :         current_block->BuildSkip();
      76                 :             : 
      77         [ +  - ]:       77280 :         return m_blocks.emplace_back(std::move(current_block)).get();
      78                 :       77280 :     }
      79                 :             : };
      80                 :             : 
      81                 :             : std::unique_ptr<const CChainParams> g_params;
      82                 :             : 
      83                 :           1 : void initialize()
      84                 :             : {
      85                 :             :     // this is actually comparatively slow, so only do it once
      86         [ +  - ]:           2 :     g_params = CreateChainParams(ArgsManager{}, ChainType::MAIN);
      87         [ -  + ]:           1 :     assert(g_params != nullptr);
      88                 :           1 : }
      89                 :             : 
      90                 :             : constexpr uint32_t MAX_START_TIME = 4102444800; // 2100-01-01
      91                 :             : 
      92         [ +  - ]:         714 : FUZZ_TARGET(versionbits, .init = initialize)
      93                 :             : {
      94         [ -  + ]:         236 :     const CChainParams& params = *g_params;
      95                 :         236 :     const int64_t interval = params.GetConsensus().nPowTargetSpacing;
      96         [ -  + ]:         236 :     assert(interval > 1); // need to be able to halve it
      97         [ -  + ]:         236 :     assert(interval < std::numeric_limits<int32_t>::max());
      98                 :             : 
      99         [ -  + ]:         236 :     FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
     100                 :             : 
     101                 :             :     // making period/max_periods larger slows these tests down significantly
     102                 :         236 :     const uint32_t period = 32;
     103                 :         236 :     const size_t max_periods = 16;
     104                 :         236 :     const size_t max_blocks = 2 * period * max_periods;
     105                 :             : 
     106                 :             :     // too many blocks at 10min each might cause uint32_t time to overflow if
     107                 :             :     // block_start_time is at the end of the range above
     108         [ -  + ]:         236 :     assert(std::numeric_limits<uint32_t>::max() - MAX_START_TIME > interval * max_blocks);
     109                 :             : 
     110                 :         236 :     const int64_t block_start_time = fuzzed_data_provider.ConsumeIntegralInRange<uint32_t>(params.GenesisBlock().nTime, MAX_START_TIME);
     111                 :             : 
     112                 :             :     // what values for version will we use to signal / not signal?
     113                 :         236 :     const int32_t ver_signal = fuzzed_data_provider.ConsumeIntegral<int32_t>();
     114                 :         236 :     const int32_t ver_nosignal = fuzzed_data_provider.ConsumeIntegral<int32_t>();
     115         [ +  + ]:         236 :     if (ver_nosignal < 0) return; // negative values are uninteresting
     116                 :             : 
     117                 :             :     // Now that we have chosen time and versions, setup to mine blocks
     118                 :         217 :     Blocks blocks(block_start_time, interval, ver_signal, ver_nosignal);
     119                 :             : 
     120                 :         217 :     const bool always_active_test = fuzzed_data_provider.ConsumeBool();
     121   [ +  +  +  + ]:         399 :     const bool never_active_test = !always_active_test && fuzzed_data_provider.ConsumeBool();
     122                 :             : 
     123                 :         434 :     const Consensus::BIP9Deployment dep{[&]() {
     124                 :         217 :         Consensus::BIP9Deployment dep;
     125                 :         217 :         dep.period = period;
     126                 :             : 
     127                 :         217 :         dep.threshold = fuzzed_data_provider.ConsumeIntegralInRange<uint32_t>(1, period);
     128   [ +  -  -  + ]:         217 :         assert(0 < dep.threshold && dep.threshold <= dep.period); // must be able to both pass and fail threshold!
     129                 :             : 
     130                 :             :         // select deployment parameters: bit, start time, timeout
     131                 :         217 :         dep.bit = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, VERSIONBITS_MAX_NUM_BITS - 1);
     132                 :             : 
     133         [ +  + ]:         217 :         if (always_active_test) {
     134                 :          35 :             dep.nStartTime = Consensus::BIP9Deployment::ALWAYS_ACTIVE;
     135         [ +  + ]:          35 :             dep.nTimeout = fuzzed_data_provider.ConsumeBool() ? Consensus::BIP9Deployment::NO_TIMEOUT : fuzzed_data_provider.ConsumeIntegral<int64_t>();
     136         [ +  + ]:         182 :         } else if (never_active_test) {
     137                 :          10 :             dep.nStartTime = Consensus::BIP9Deployment::NEVER_ACTIVE;
     138         [ +  + ]:          10 :             dep.nTimeout = fuzzed_data_provider.ConsumeBool() ? Consensus::BIP9Deployment::NO_TIMEOUT : fuzzed_data_provider.ConsumeIntegral<int64_t>();
     139                 :             :         } else {
     140                 :             :             // pick the timestamp to switch based on a block
     141                 :             :             // note states will change *after* these blocks because mediantime lags
     142                 :         172 :             int start_block = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, period * (max_periods - 3));
     143                 :         172 :             int end_block = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, period * (max_periods - 3));
     144                 :             : 
     145                 :         172 :             dep.nStartTime = block_start_time + start_block * interval;
     146                 :         172 :             dep.nTimeout = block_start_time + end_block * interval;
     147                 :             : 
     148                 :             :             // allow for times to not exactly match a block
     149         [ +  + ]:         172 :             if (fuzzed_data_provider.ConsumeBool()) dep.nStartTime += interval / 2;
     150         [ +  + ]:         172 :             if (fuzzed_data_provider.ConsumeBool()) dep.nTimeout += interval / 2;
     151                 :             :         }
     152                 :         217 :         dep.min_activation_height = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, period * max_periods);
     153                 :         217 :         return dep;
     154                 :         217 :     }()};
     155                 :         217 :     TestConditionChecker checker(dep);
     156                 :             : 
     157                 :             :     // Early exit if the versions don't signal sensibly for the deployment
     158         [ +  + ]:         217 :     if (!checker.Condition(ver_signal)) return;
     159         [ +  + ]:         220 :     if (checker.Condition(ver_nosignal)) return;
     160                 :             : 
     161                 :             :     // TOP_BITS should ensure version will be positive and meet min
     162                 :             :     // version requirement
     163         [ -  + ]:         201 :     assert(ver_signal > 0);
     164         [ -  + ]:         201 :     assert(ver_signal >= VERSIONBITS_LAST_OLD_BLOCK_VERSION);
     165                 :             : 
     166                 :             :     /* Strategy:
     167                 :             :      *  * we will mine a final period worth of blocks, with
     168                 :             :      *    randomised signalling according to a mask
     169                 :             :      *  * but before we mine those blocks, we will mine some
     170                 :             :      *    randomised number of prior periods; with either all
     171                 :             :      *    or no blocks in the period signalling
     172                 :             :      *
     173                 :             :      * We establish the mask first, then consume "bools" until
     174                 :             :      * we run out of fuzz data to work out how many prior periods
     175                 :             :      * there are and which ones will signal.
     176                 :             :      */
     177                 :             : 
     178                 :             :     // establish the mask
     179                 :         201 :     const uint32_t signalling_mask = fuzzed_data_provider.ConsumeIntegral<uint32_t>();
     180                 :             : 
     181                 :             :     // mine prior periods
     182         [ +  + ]:        2592 :     while (fuzzed_data_provider.remaining_bytes() > 0) { // early exit; no need for LIMITED_WHILE
     183                 :             :         // all blocks in these periods either do or don't signal
     184                 :        2214 :         bool signal = fuzzed_data_provider.ConsumeBool();
     185         [ +  + ]:       73062 :         for (uint32_t b = 0; b < period; ++b) {
     186         [ +  - ]:       70848 :             blocks.mine_block(signal);
     187                 :             :         }
     188                 :             : 
     189                 :             :         // don't risk exceeding max_blocks or times may wrap around
     190   [ -  +  +  + ]:        2214 :         if (blocks.size() + 2 * period > max_blocks) break;
     191                 :             :     }
     192                 :             :     // NOTE: fuzzed_data_provider may be fully consumed at this point and should not be used further
     193                 :             : 
     194                 :             :     // now we mine the final period and check that everything looks sane
     195                 :             : 
     196                 :             :     // count the number of signalling blocks
     197                 :         201 :     uint32_t blocks_sig = 0;
     198                 :             : 
     199                 :             :     // get the info for the first block of the period
     200                 :         201 :     CBlockIndex* prev = blocks.tip();
     201         [ +  - ]:         201 :     const int exp_since = checker.GetStateSinceHeightFor(prev);
     202         [ +  - ]:         201 :     const ThresholdState exp_state = checker.GetStateFor(prev);
     203                 :             : 
     204                 :             :     // get statistics from end of previous period, then reset
     205                 :         201 :     BIP9Stats last_stats;
     206                 :         201 :     last_stats.period = period;
     207                 :         201 :     last_stats.threshold = dep.threshold;
     208                 :         201 :     last_stats.count = last_stats.elapsed = 0;
     209                 :         201 :     last_stats.possible = (period >= dep.threshold);
     210                 :         201 :     std::vector<bool> last_signals{};
     211                 :             : 
     212         [ +  + ]:         201 :     int prev_next_height = (prev == nullptr ? 0 : prev->nHeight + 1);
     213         [ -  + ]:         201 :     assert(exp_since <= prev_next_height);
     214                 :             : 
     215                 :             :     // mine (period-1) blocks and check state
     216         [ +  + ]:        6432 :     for (uint32_t b = 1; b < period; ++b) {
     217                 :        6231 :         const bool signal = (signalling_mask >> (b % 32)) & 1;
     218         [ +  + ]:        6231 :         if (signal) ++blocks_sig;
     219                 :             : 
     220         [ +  - ]:        6231 :         CBlockIndex* current_block = blocks.mine_block(signal);
     221                 :             : 
     222                 :             :         // verify that signalling attempt was interpreted correctly
     223   [ +  +  -  + ]:        9213 :         assert(checker.Condition(current_block->nVersion) == signal);
     224                 :             : 
     225                 :             :         // state and since don't change within the period
     226         [ +  - ]:        6231 :         const ThresholdState state = checker.GetStateFor(current_block);
     227         [ +  - ]:        6231 :         const int since = checker.GetStateSinceHeightFor(current_block);
     228         [ -  + ]:        6231 :         assert(state == exp_state);
     229         [ -  + ]:        6231 :         assert(since == exp_since);
     230                 :             : 
     231                 :             :         // check that after mining this block stats change as expected
     232                 :        6231 :         std::vector<bool> signals;
     233         [ +  - ]:        6231 :         const BIP9Stats stats = checker.GetStateStatisticsFor(current_block, &signals);
     234         [ +  - ]:        6231 :         const BIP9Stats stats_no_signals = checker.GetStateStatisticsFor(current_block);
     235   [ +  -  +  -  :        6231 :         assert(stats.period == stats_no_signals.period && stats.threshold == stats_no_signals.threshold
          +  -  +  -  -  
                      + ]
     236                 :             :                && stats.elapsed == stats_no_signals.elapsed && stats.count == stats_no_signals.count
     237                 :             :                && stats.possible == stats_no_signals.possible);
     238                 :             : 
     239         [ -  + ]:        6231 :         assert(stats.period == period);
     240         [ -  + ]:        6231 :         assert(stats.threshold == dep.threshold);
     241         [ -  + ]:        6231 :         assert(stats.elapsed == b);
     242   [ +  +  -  + ]:        9946 :         assert(stats.count == last_stats.count + (signal ? 1 : 0));
     243         [ -  + ]:        6231 :         assert(stats.possible == (stats.count + period >= stats.elapsed + dep.threshold));
     244                 :        6231 :         last_stats = stats;
     245                 :             : 
     246         [ -  + ]:        6231 :         assert(signals.size() == last_signals.size() + 1);
     247         [ -  + ]:        6231 :         assert(signals.back() == signal);
     248         [ +  - ]:        6231 :         last_signals.push_back(signal);
     249         [ -  + ]:        6231 :         assert(signals == last_signals);
     250                 :        6231 :     }
     251                 :             : 
     252         [ +  + ]:         201 :     if (exp_state == ThresholdState::STARTED) {
     253                 :             :         // double check that stats.possible is sane
     254   [ +  +  -  + ]:          43 :         if (blocks_sig >= dep.threshold - 1) assert(last_stats.possible);
     255                 :             :     }
     256                 :             : 
     257                 :             :     // mine the final block
     258                 :         201 :     bool signal = (signalling_mask >> (period % 32)) & 1;
     259         [ +  + ]:         201 :     if (signal) ++blocks_sig;
     260         [ +  - ]:         201 :     CBlockIndex* current_block = blocks.mine_block(signal);
     261   [ +  +  -  + ]:         309 :     assert(checker.Condition(current_block->nVersion) == signal);
     262                 :             : 
     263         [ +  - ]:         201 :     const BIP9Stats stats = checker.GetStateStatisticsFor(current_block);
     264         [ -  + ]:         201 :     assert(stats.period == period);
     265         [ -  + ]:         201 :     assert(stats.threshold == dep.threshold);
     266         [ -  + ]:         201 :     assert(stats.elapsed == period);
     267         [ -  + ]:         201 :     assert(stats.count == blocks_sig);
     268         [ -  + ]:         201 :     assert(stats.possible == (stats.count + period >= stats.elapsed + dep.threshold));
     269                 :             : 
     270                 :             :     // More interesting is whether the state changed.
     271         [ +  - ]:         201 :     const ThresholdState state = checker.GetStateFor(current_block);
     272         [ +  - ]:         201 :     const int since = checker.GetStateSinceHeightFor(current_block);
     273                 :             : 
     274                 :             :     // since is straightforward:
     275         [ -  + ]:         201 :     assert(since % period == 0);
     276   [ +  -  -  + ]:         201 :     assert(0 <= since && since <= current_block->nHeight + 1);
     277         [ +  + ]:         201 :     if (state == exp_state) {
     278         [ -  + ]:         149 :         assert(since == exp_since);
     279                 :             :     } else {
     280         [ -  + ]:          52 :         assert(since == current_block->nHeight + 1);
     281                 :             :     }
     282                 :             : 
     283                 :             :     // state is where everything interesting is
     284                 :         402 :     [&]() {
     285   [ +  +  +  +  :         201 :         switch (state) {
                   +  - ]
     286                 :          16 :         case ThresholdState::DEFINED:
     287         [ -  + ]:          16 :             assert(since == 0);
     288         [ -  + ]:          16 :             assert(exp_state == ThresholdState::DEFINED);
     289         [ -  + ]:          16 :             assert(current_block->GetMedianTimePast() < dep.nStartTime);
     290                 :             :             return;
     291                 :          27 :         case ThresholdState::STARTED:
     292         [ -  + ]:          27 :             assert(current_block->GetMedianTimePast() >= dep.nStartTime);
     293         [ +  + ]:          27 :             if (exp_state == ThresholdState::STARTED) {
     294         [ -  + ]:          14 :                 assert(blocks_sig < dep.threshold);
     295         [ -  + ]:          14 :                 assert(current_block->GetMedianTimePast() < dep.nTimeout);
     296                 :             :             } else {
     297         [ -  + ]:          13 :                 assert(exp_state == ThresholdState::DEFINED);
     298                 :             :             }
     299                 :             :             return;
     300                 :          26 :         case ThresholdState::LOCKED_IN:
     301         [ +  + ]:          26 :             if (exp_state == ThresholdState::LOCKED_IN) {
     302         [ -  + ]:           8 :                 assert(current_block->nHeight + 1 < dep.min_activation_height);
     303                 :             :             } else {
     304         [ -  + ]:          18 :                 assert(exp_state == ThresholdState::STARTED);
     305         [ -  + ]:          18 :                 assert(blocks_sig >= dep.threshold);
     306                 :             :             }
     307                 :             :             return;
     308                 :          86 :         case ThresholdState::ACTIVE:
     309   [ +  +  -  + ]:          86 :             assert(always_active_test || dep.min_activation_height <= current_block->nHeight + 1);
     310         [ -  + ]:          86 :             assert(exp_state == ThresholdState::ACTIVE || exp_state == ThresholdState::LOCKED_IN);
     311                 :             :             return;
     312                 :          46 :         case ThresholdState::FAILED:
     313   [ +  +  -  + ]:          46 :             assert(never_active_test || current_block->GetMedianTimePast() >= dep.nTimeout);
     314         [ +  + ]:          46 :             if (exp_state == ThresholdState::STARTED) {
     315         [ -  + ]:          11 :                 assert(blocks_sig < dep.threshold);
     316                 :             :             } else {
     317         [ -  + ]:          35 :                 assert(exp_state == ThresholdState::FAILED);
     318                 :             :             }
     319                 :             :             return;
     320                 :             :         } // no default case, so the compiler can warn about missing cases
     321                 :           0 :         AssertUnreachable();
     322         [ +  - ]:         201 :     }();
     323                 :             : 
     324   [ -  +  +  + ]:         201 :     if (blocks.size() >= period * max_periods) {
     325                 :             :         // we chose the timeout (and block times) so that by the time we have this many blocks it's all over
     326         [ -  + ]:          68 :         assert(state == ThresholdState::ACTIVE || state == ThresholdState::FAILED);
     327                 :             :     }
     328                 :             : 
     329         [ +  + ]:         201 :     if (always_active_test) {
     330                 :             :         // "always active" has additional restrictions
     331         [ -  + ]:          24 :         assert(state == ThresholdState::ACTIVE);
     332         [ -  + ]:          24 :         assert(exp_state == ThresholdState::ACTIVE);
     333         [ -  + ]:          24 :         assert(since == 0);
     334         [ +  + ]:         177 :     } else if (never_active_test) {
     335                 :             :         // "never active" does too
     336         [ -  + ]:           6 :         assert(state == ThresholdState::FAILED);
     337         [ -  + ]:           6 :         assert(exp_state == ThresholdState::FAILED);
     338         [ -  + ]:           6 :         assert(since == 0);
     339                 :             :     } else {
     340                 :             :         // for signalled deployments, the initial state is always DEFINED
     341   [ +  +  -  + ]:         171 :         assert(since > 0 || state == ThresholdState::DEFINED);
     342   [ +  +  -  + ]:         171 :         assert(exp_since > 0 || exp_state == ThresholdState::DEFINED);
     343                 :             :     }
     344                 :         217 : }
     345                 :             : } // namespace
        

Generated by: LCOV version 2.5.0-full