• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

libbitcoin / libbitcoin-system / 44679030460

20 Nov 2026 05:08AM UTC coverage: 96.454% (+0.001%) from 96.453%
44679030460

push

github

web-flow
Merge pull request #2188 from evoskuil/master

Hold chain state histories in vectors and count versions as they promote.

40 of 41 new or added lines in 1 file covered. (97.56%)

28781 of 29839 relevant lines covered (96.45%)

3695023.1 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.66
/src/chain/chain_state.cpp
1
/**
2
 * Copyright (c) 2011-2026 libbitcoin developers
3
 *
4
 * This file is part of libbitcoin.
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Affero General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU Affero General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Affero General Public License
17
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19
#include <bitcoin/system/chain/chain_state.hpp>
20

21
#include <chrono>
22
#include <optional>
23
#include <ranges>
24
#include <bitcoin/system/chain/block.hpp>
25
#include <bitcoin/system/chain/chain_state.hpp>
26
#include <bitcoin/system/chain/checkpoint.hpp>
27
#include <bitcoin/system/chain/compact.hpp>
28
#include <bitcoin/system/chain/context.hpp>
29
#include <bitcoin/system/chain/enums/flags.hpp>
30
#include <bitcoin/system/chain/enums/policy.hpp>
31
#include <bitcoin/system/chain/script.hpp>
32
#include <bitcoin/system/data/data.hpp>
33
#include <bitcoin/system/forks.hpp>
34
#include <bitcoin/system/hash/hash.hpp>
35
#include <bitcoin/system/math/math.hpp>
36
#include <bitcoin/system/settings.hpp>
37

38
namespace libbitcoin {
39
namespace system {
40
namespace chain {
41

42
// github.com/bitcoin/bips/blob/master/bip-0030.mediawiki#specification
43
// As bip30 exceptions apply only to bitcoin mainnet these can be embedded.
44
static const checkpoint mainnet_bip30_exception_checkpoint1
45
{
46
    "00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec", 91842
47
};
48
static const checkpoint mainnet_bip30_exception_checkpoint2
49
{
50
    "00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721", 91880
51
};
52

53
// Inlines.
54
// ----------------------------------------------------------------------------
55

56
constexpr bool is_active(size_t count, size_t bip34_activation_threshold) NOEXCEPT
12,299 ✔
57
{
58
    return count >= bip34_activation_threshold;
12,299 ✔
59
}
60

61
constexpr bool is_enforced(size_t count, size_t bip34_enforcement_threshold) NOEXCEPT
12,076 ✔
62
{
63
    return count >= bip34_enforcement_threshold;
12,076 ✔
64
}
65

66
//*****************************************************************************
67
// CONSENSUS: Though unspecified in bip34, the satoshi implementation
68
// performed this comparison using the signed integer version value.
69
//*****************************************************************************
70
constexpr bool is_version(uint32_t value, uint32_t version) NOEXCEPT
56,595 ✔
71
{
72
    return sign_cast<int32_t>(value) >= sign_cast<int32_t>(version);
56,595 ✔
73
}
74

75
// Count (or uncount) a version against each bip34-based version.
76
static void tally(chain_state::data& values, uint32_t value, bool add,
17,949 ✔
77
    const system::settings& settings) NOEXCEPT
78
{
79
    const auto adjust = [add](size_t& count, bool counted) NOEXCEPT
53,847 ✔
80
    {
81
        if (counted)
53,847 ✔
82
            count = add ? add1(count) : sub1(count);
26,334 ✔
83
    };
71,796 ✔
84

85
    adjust(values.version.bip34, is_version(value, settings.bip34_version));
17,949 ✔
86
    adjust(values.version.bip66, is_version(value, settings.bip66_version));
17,949 ✔
87
    adjust(values.version.bip65, is_version(value, settings.bip65_version));
17,949 ✔
88
}
17,949 ✔
89

90
// Append the value, dropping the oldest when the window would exceed count.
91
static std::optional<uint32_t> enqueue(std::vector<uint32_t>& ordered,
6,087 ✔
92
    uint32_t value, size_t count) NOEXCEPT
93
{
94
    std::optional<uint32_t> oldest{};
6,087 ✔
95
    if (ordered.size() >= count)
6,087 ✔
96
    {
97
        if (ordered.empty())
6,006 ✔
NEW
98
            return value;
×
99

100
        oldest = ordered.front();
6,006 ✔
101
        ordered.erase(ordered.begin());
6,006 ✔
102
    }
103

104
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
105
    ordered.push_back(value);
6,087 ✔
106
    BC_POP_WARNING()
107
    return oldest;
6,087 ✔
108
}
109

110
// Determine the number of blocks back to the closest retarget height.
111
constexpr size_t retarget_distance(size_t height,
4,098 ✔
112
    size_t retargeting_interval) NOEXCEPT
113
{
114
    return height % retargeting_interval;
4,098 ✔
115
}
116

117
// Determine if height is a multiple of retargeting_interval.
118
constexpr bool is_retarget_height(size_t height,
4,089 ✔
119
    size_t retargeting_interval) NOEXCEPT
120
{
121
    return is_zero(retarget_distance(height, retargeting_interval));
4,089 ✔
122
}
123

124
// bip30 is active for all but two mainnet blocks that violate the rule.
125
// These two blocks each have a coinbase transaction that exactly duplicates
126
// another that is not spent by the arrival of the corresponding duplicate.
127
// Exceptions: block 91842 (duplicates 91812), 91880 (duplicates 91722).
128
inline bool is_bip30_exception(const hash_digest& hash,
4,101 ✔
129
    size_t height) NOEXCEPT
130
{
131
    return (hash   == mainnet_bip30_exception_checkpoint1.hash() &&
4,102 ✔
132
            height == mainnet_bip30_exception_checkpoint1.height()) ||
4,101 ✔
133
           (hash   == mainnet_bip30_exception_checkpoint2.hash() &&
4,100 ✔
134
            height == mainnet_bip30_exception_checkpoint2.height());
×
135
}
136

137
// The top three version bits are reserved for the bip9 version base.
138
constexpr uint32_t bip9_version_mask = 0xe0000000;
139

140
// The period boundary at or below the height.
141
inline size_t period_floor(size_t height, size_t period) NOEXCEPT
38 ✔
142
{
143
    return floored_divide(height, period) * period;
38 ✔
144
}
145

146
typedef std::array<chain_state::deployment,
147
    chain_state::deployment_count> deployments_t;
148

149
inline deployments_t deployments(const system::settings& settings) NOEXCEPT
6,184 ✔
150
{
151
    return
152
    {
153
        settings.bip9_bit0_deployment,
154
        settings.bip9_bit1_deployment,
155
        settings.bip9_bit2_deployment,
156
        settings.bip54_timewarp_deployment,
157
        settings.bip54_timespan_deployment,
158
        settings.bip54_sigops_deployment,
159
        settings.bip54_txsize_deployment,
160
        settings.bip54_coinbase_deployment
161
    };
6,184 ✔
162
}
163

164
inline bool is_configured(const chain_state::deployment& deployment,
82,279 ✔
165
    uint32_t configured) NOEXCEPT
166
{
167
    return !is_zero(bit_and(deployment.flags, configured));
82,279 ✔
168
}
169

170
inline bool is_signaled(const chain_state::deployment& deployment,
49,471 ✔
171
    const system::settings& settings, uint32_t configured) NOEXCEPT
172
{
173
    const auto always = chain_state::deployment::always_active;
174

175
    return is_configured(deployment, configured)
49,471 ✔
176
        && deployment.start != always
49,467 ✔
177
        && !is_zero(deployment.threshold)
49,388 ✔
178
        && !is_zero(settings.bip9_activation_period);
67,985 ✔
179
}
180

181
inline uint32_t timestamp_high(const chain_state::data& values) NOEXCEPT
28 ✔
182
{
183
    return values.timestamp.ordered.back();
28 ✔
184
}
185

186
inline uint32_t bits_high(const chain_state::data& values) NOEXCEPT
8,160 ✔
187
{
188
    return values.bits.ordered.back();
8,160 ✔
189
}
190

191
// activation
192
// ----------------------------------------------------------------------------
193

194
uint32_t chain_state::configured_flags(const forks& forks) NOEXCEPT
6,193 ✔
195
{
196
    uint32_t result{ flags::no_rules };
197
    if (forks.retarget)
6,193 ✔
198
        result |= flags::retarget;
199
    if (forks.difficult)
6,193 ✔
200
        result |= flags::difficult;
6,187 ✔
201
    if (forks.ltc_time_warp_patch)
6,193 ✔
202
        result |= flags::ltc_time_warp_patch;
12 ✔
203
    if (forks.ltc_retarget_overflow_patch)
6,193 ✔
204
        result |= flags::ltc_retarget_overflow_patch;
2 ✔
205
    if (forks.ltc_scrypt_proof_of_work)
6,193 ✔
206
        result |= flags::ltc_scrypt_proof_of_work;
2 ✔
207
    if (forks.time_warp_patch)
6,193 ✔
208
        result |= flags::time_warp_patch;
3 ✔
209
    if (forks.block_storm_patch)
6,193 ✔
210
        result |= flags::block_storm_patch;
3 ✔
211
    if (forks.signet)
6,193 ✔
212
        result |= flags::signet_rule;
3 ✔
213
    if (forks.bip16)
6,193 ✔
214
        result |= flags::bip16_rule;
6,192 ✔
215
    if (forks.bip30)
6,193 ✔
216
        result |= flags::bip30_rule;
6,191 ✔
217
    if (forks.bip34)
6,193 ✔
218
        result |= flags::bip34_rule;
6,191 ✔
219
    if (forks.bip42)
6,193 ✔
220
        result |= flags::bip42_rule;
6,191 ✔
221
    if (forks.bip65)
6,193 ✔
222
        result |= flags::bip65_rule;
6,191 ✔
223
    if (forks.bip66)
6,193 ✔
224
        result |= flags::bip66_rule;
6,191 ✔
225
    if (forks.bip68)
6,193 ✔
226
        result |= flags::bip68_rule;
6,188 ✔
227
    if (forks.bip90)
6,193 ✔
228
        result |= flags::bip90_rule;
4 ✔
229
    if (forks.bip112)
6,193 ✔
230
        result |= flags::bip112_rule;
6,188 ✔
231
    if (forks.bip113)
6,193 ✔
232
        result |= flags::bip113_rule;
6,188 ✔
233
    if (forks.bip141)
6,193 ✔
234
        result |= flags::bip141_rule;
6,191 ✔
235
    if (forks.bip143)
6,193 ✔
236
        result |= flags::bip143_rule;
6,191 ✔
237
    if (forks.bip147)
6,193 ✔
238
        result |= flags::bip147_rule;
6,191 ✔
239
    if (forks.bip341)
6,193 ✔
240
        result |= flags::bip341_rule;
6,190 ✔
241
    if (forks.bip342)
6,193 ✔
242
        result |= flags::bip342_rule;
6,190 ✔
243
    if (forks.bip54_timewarp)
6,193 ✔
244
        result |= flags::bip54_timewarp_rule;
6,191 ✔
245
    if (forks.bip54_timespan)
6,193 ✔
246
        result |= flags::bip54_timespan_rule;
6,190 ✔
247
    if (forks.bip54_sigops)
6,193 ✔
248
        result |= flags::bip54_sigops_rule;
6,191 ✔
249
    if (forks.bip54_txsize)
6,193 ✔
250
        result |= flags::bip54_txsize_rule;
6,191 ✔
251
    if (forks.bip54_coinbase)
6,193 ✔
252
        result |= flags::bip54_coinbase_rule;
6,191 ✔
253

254
    return result;
6,193 ✔
255
}
256

257
chain_state::activations chain_state::activation(const data& values,
4,101 ✔
258
    const forks& forks, const system::settings& settings) NOEXCEPT
259
{
260
    // There are no constraints on block version before bip34.
261
    activations result{ flags::no_rules, 0 };
4,101 ✔
262

263
    // regtest is only activated via configuration.
264
    if (forks.retarget)
4,101 ✔
265
    {
266
        result.flags |= flags::retarget;
45 ✔
267
    }
268

269
    // testnet is activated based on configuration alone.
270
    if (forks.difficult)
4,101 ✔
271
    {
272
        result.flags |= flags::difficult;
4,101 ✔
273
    }
274

275
    // time_warp_patch is activated based on configuration alone.
276
    if (forks.ltc_time_warp_patch)
4,101 ✔
277
    {
278
        result.flags |= flags::ltc_time_warp_patch;
6 ✔
279
    }
280

281
    // retarget_overflow_patch is activated based on configuration alone.
282
    if (forks.ltc_retarget_overflow_patch)
4,101 ✔
283
    {
284
        result.flags |= flags::ltc_retarget_overflow_patch;
1 ✔
285
    }
286

287
    // scrypt_proof_of_work is activated based on configuration alone.
288
    if (forks.ltc_scrypt_proof_of_work)
4,101 ✔
289
    {
290
        result.flags |= flags::ltc_scrypt_proof_of_work;
1 ✔
291
    }
292

293
    // bip42 is activated based on configuration alone (soft fork).
294
    if (forks.bip42)
4,101 ✔
295
    {
296
        result.flags |= flags::bip42_rule;
4,101 ✔
297
    }
298

299
    // bip90 is activated based on configuration alone (hard fork).
300
    if (forks.bip90)
4,101 ✔
301
    {
302
        result.flags |= flags::bip90_rule;
3 ✔
303
    }
304

305
    // time_warp_patch (testnet4) is activated based on configuration
306
    // alone (hard fork).
307
    if (forks.time_warp_patch)
4,101 ✔
308
    {
309
        result.flags |= flags::time_warp_patch;
1 ✔
310
    }
311

312
    // block_storm_patch (testnet4) is activated based on configuration
313
    // alone (hard fork).
314
    if (forks.block_storm_patch)
4,101 ✔
315
    {
316
        result.flags |= flags::block_storm_patch;
1 ✔
317
    }
318

319
    // signet is activated based on configuration above genesis (soft fork).
320
    if (forks.signet && !is_zero(values.height))
4,101 ✔
321
    {
322
        result.flags |= flags::signet_rule;
1 ✔
323
    }
324

325
    // bip16 was activated by manual inspection of signal history (soft fork).
326
    if (forks.bip16 &&
4,101 ✔
327
        (values.timestamp.self >= settings.bip16_activation_time))
4,101 ✔
328
    {
329
        result.flags |= flags::bip16_rule;
1 ✔
330
    }
331

332
    const auto height = values.height;
4,101 ✔
333
    const auto version = values.version.self;
4,101 ✔
334

335
    // bip34-based activation version summaries (zero if disabled).
336
    const auto count_2 = values.version.bip34;
4,101 ✔
337
    const auto count_3 = values.version.bip66;
4,101 ✔
338
    const auto count_4 = values.version.bip65;
4,101 ✔
339

340
    // Frozen activations (require version and enforce above freeze height).
341
    const auto bip90_bip34 = forks.bip90 && height >= settings.bip90_bip34_height;
4,101 ✔
342
    const auto bip90_bip65 = forks.bip90 && height >= settings.bip90_bip65_height;
4,101 ✔
343
    const auto bip90_bip66 = forks.bip90 && height >= settings.bip90_bip66_height;
4,101 ✔
344

345
    // bip34 activations oscillate until enforced by minimum_block_version.
346
    // bip90 does not require that the corresponding rules be defined.
347
    // bip34 is active based on 75% of preceding 1000 mainnet blocks.
348
    if (bip90_bip34 ||
4,101 ✔
349
        (is_active(count_2, settings.bip34_activation_threshold) &&
4,099 ✔
350
        is_version(version, settings.bip34_version)))
921 ✔
351
    {
352
        result.flags |= flags::bip34_rule;
664 ✔
353
    }
354

355
    // bip66 is active based on 75% of preceding 1000 mainnet blocks.
356
    if (bip90_bip66 ||
4,101 ✔
357
        (is_active(count_3, settings.bip34_activation_threshold) &&
4,100 ✔
358
        is_version(version, settings.bip66_version)))
915 ✔
359
    {
360
        result.flags |= flags::bip66_rule;
659 ✔
361
    }
362

363
    // bip65 is active based on 75% of preceding 1000 mainnet blocks.
364
    if (bip90_bip65 ||
4,101 ✔
365
        (is_active(count_4, settings.bip34_activation_threshold) &&
4,100 ✔
366
        is_version(version, settings.bip65_version)))
912 ✔
367
    {
368
        result.flags |= flags::bip65_rule;
657 ✔
369
    }
370

371
    // version 4/3/2 enforced based on 95% of preceding 1000 mainnet blocks.
372
    if (bip90_bip65 ||
4,101 ✔
373
        is_enforced(count_4, settings.bip34_enforcement_threshold))
4,100 ✔
374
    {
375
        result.minimum_block_version = settings.bip65_version;
112 ✔
376
    }
377
    else if (bip90_bip66 ||
3,989 ✔
378
        is_enforced(count_3, settings.bip34_enforcement_threshold))
3,989 ✔
379
    {
380
        result.minimum_block_version = settings.bip66_version;
1 ✔
381
    }
382
    else if (bip90_bip34 ||
3,988 ✔
383
        is_enforced(count_2, settings.bip34_enforcement_threshold))
3,987 ✔
384
    {
385
        result.minimum_block_version = settings.bip34_version;
1 ✔
386
    }
387

388
    const auto configured = configured_flags(forks);
4,101 ✔
389

390
    // Signaled deployments are enforced once active, always above genesis.
391
    const auto list = deployments(settings);
4,101 ✔
392
    for (size_t index{}; index < list.size(); ++index)
36,909 ✔
393
    {
394
        const auto& deployment = list.at(index);
32,808 ✔
395
        if (!is_configured(deployment, configured))
32,808 ✔
396
            continue;
1 ✔
397

398
        const auto always = deployment.start == deployment::always_active;
32,807 ✔
399
        if (is_signaled(deployment, settings, configured) ?
32,807 ✔
400
            values.signals.at(index).state == deployment_state::active :
12,288 ✔
401
            always && !is_zero(height))
20,519 ✔
402
            result.flags |= deployment.flags;
20 ✔
403
    }
404

405
    // If not exception, existing duplicate coinbase must be spent.
406
    if (forks.bip30 && !is_bip30_exception(values.hash, height))
4,101 ✔
407
    {
408
        result.flags |= flags::bip30_rule;
4,100 ✔
409
    }
410

411
    return result;
4,101 ✔
412
}
413

414
// github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#state-transitions
415
// github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#deployment
416
chain_state::deployment_state chain_state::next_state(
48 ✔
417
    const deployment& deployment, deployment_state state,
418
    uint32_t median_time_past, size_t count, size_t boundary) NOEXCEPT
419
{
420
    const auto started = median_time_past >= deployment.start;
48 ✔
421
    const auto timed_out = median_time_past >= deployment.timeout;
48 ✔
422
    const auto locked_in = count >= deployment.threshold;
48 ✔
423

424
    switch (state)
48 ✔
425
    {
426
        // bip9 fails a deployment that times out before it starts.
427
        case deployment_state::defined:
26 ✔
428
        {
429
            if (!deployment.speedy && timed_out)
26 ✔
430
                return deployment_state::failed;
431

432
            return started ? deployment_state::started : state;
25 ✔
433
        }
434

435
        // bip9 checks timeout before threshold, speedy trial after.
436
        case deployment_state::started:
13 ✔
437
        {
438
            if (!deployment.speedy && timed_out)
13 ✔
439
                return deployment_state::failed;
440

441
            if (locked_in)
12 ✔
442
                return deployment_state::locked_in;
443

444
            return timed_out ? deployment_state::failed : state;
6 ✔
445
        }
446

447
        case deployment_state::locked_in:
7 ✔
448
        {
449
            return boundary >= deployment.activation_height ?
7 ✔
450
                deployment_state::active : state;
451
        }
452

453
        case deployment_state::active:
454
        case deployment_state::failed:
455
        default:
456
        {
457
            return state;
458
        }
459
    }
460
}
461

462
size_t chain_state::bits_count(size_t height, const forks& forks,
2,042 ✔
463
    size_t retargeting_interval) NOEXCEPT
464
{
465
    // Mainnet doesn't use bits in retargeting.
466
    if (forks.difficult)
2,042 ✔
467
        return one;
468

469
    // Regtest bypasses all retargeting.
470
    if (!forks.retarget)
4 ✔
471
        return one;
472

473
    // Testnet uses mainnet retargeting on interval, unless storm patched.
474
    if (!forks.block_storm_patch &&
2 ✔
475
        is_retarget_height(height, retargeting_interval))
1 ✔
476
        return one;
477

478
    // Testnet requires all bits for inter-interval retargeting.
479
    // Block storm patch requires all bits for interval retargeting [bip94].
480
    return std::min(height, retargeting_interval);
1 ✔
481
}
482

483
size_t chain_state::version_count(size_t height, const forks& forks,
2,042 ✔
484
    size_t bip34_activation_sample) NOEXCEPT
485
{
486
    if (forks.bip90 || (!forks.bip34 && !forks.bip65 && !forks.bip66))
2,042 ✔
487
        return zero;
488

489
    return std::min(height, bip34_activation_sample);
2,041 ✔
490
}
491

492
size_t chain_state::timestamp_count(size_t height, const forks&) NOEXCEPT
2,042 ✔
493
{
494
    return std::min(height, median_time_past_interval);
2,042 ✔
495
}
496

497
size_t chain_state::retarget_height(size_t height, const forks& forks,
13 ✔
498
    size_t retargeting_interval) NOEXCEPT
499
{
500
    if (!forks.retarget && !forks.bip54_timespan)
13 ✔
501
        return map::unrequested;
502

503
    // Height must be a positive multiple of interval, so underflow safe.
504
    // If not retarget height get most recent so that it may be promoted.
505
    return height - (is_retarget_height(height, retargeting_interval) ?
12 ✔
506
        retargeting_interval : retarget_distance(height, retargeting_interval));
12 ✔
507
}
508

509
// median_time_past
510
// ----------------------------------------------------------------------------
511

512
//*****************************************************************************
513
// CONSENSUS: satoshi associates the median time past for block N with block
514
// N-1, as opposed to block N. This is unnecessarily confusing. We associate
515
// the median time past for block N with block N. This is intuitive but
516
// requires care when comparing code.
517
//*****************************************************************************
518
uint32_t chain_state::median_time_past(const data& values,
6,106 ✔
519
    const forks&) NOEXCEPT
520
{
521
    return median(values.timestamp.ordered);
6,106 ✔
522
}
523

524
// work_required
525
// ----------------------------------------------------------------------------
526

527
uint32_t chain_state::work_required(const data& values, const forks& forks,
4,093 ✔
528
    const system::settings& settings) NOEXCEPT
529
{
530
    // Genesis has no preceding block data.
531
    if (is_zero(values.height))
4,093 ✔
532
        return 0;
533

534
    // Previous block has an invalid bits value.
535
    if (is_zero(compact::expand(bits_high(values))))
4,083 ✔
536
        return 0;
537

538
    // Regtest bypasses all retargeting.
539
    if (!forks.retarget)
4,082 ✔
540
        return bits_high(values);
4,052 ✔
541

542
    // Mainnet and testnet retarget on interval.
543
    if (is_retarget_height(values.height, settings.retargeting_interval()))
30 ✔
544
        return work_required_retarget(values, forks,
64 ✔
545
            settings.proof_of_work_limit,
16 ✔
546
            settings.minimum_timespan(),
16 ✔
547
            settings.maximum_timespan(),
16 ✔
548
            settings.retargeting_interval(),
16 ✔
549
            settings.retargeting_interval_seconds);
32 ✔
550

551
    // Testnet retargets easy on inter-interval.
552
    if (!forks.difficult)
14 ✔
553
        return easy_work_required(values,
4 ✔
554
            settings.retargeting_interval(),
4 ✔
555
            settings.proof_of_work_limit,
4 ✔
556
            settings.block_spacing_seconds);
8 ✔
557

558
    // Mainnet not retargeting, must exact match the previous block bits value.
559
    return bits_high(values);
10 ✔
560
}
561

562
// Get the bounded total time spanning the highest 2016 blocks.
563
uint32_t chain_state::retarget_timespan(const data& values,
16 ✔
564
    uint32_t minimum_timespan, uint32_t maximum_timespan) NOEXCEPT
565
{
566
    //*************************************************************************
567
    // CONSENSUS: "Subtract unsigned 32 bit numbers in signed 64 bit space".
568
    // This is done order to prevent underflow before applying the range
569
    // constraint. This is properly just a floored subtraction in 32 bit space.
570
    //*************************************************************************
571
    const auto timespan = floored_subtract(timestamp_high(values),
32 ✔
572
        values.timestamp.retarget);
16 ✔
573

574
    //*************************************************************************
575
    // CONSENSUS: Constrain the timespan to the configured consensus limits.
576
    //*************************************************************************
577
    return limit(timespan, minimum_timespan, maximum_timespan);
16 ✔
578
}
579

580
constexpr bool patch_timewarp(const forks& forks, const uint256_t& limit,
16 ✔
581
    const uint256_t& target) NOEXCEPT
582
{
583
    return forks.ltc_retarget_overflow_patch &&
17 ✔
584
        floored_log2(target) >= floored_log2(limit);
1 ✔
585
}
586

587
// A retarget height, or a block that does not have proof_of_work_limit bits.
588
constexpr bool is_retarget_or_non_limit(size_t height, uint32_t bits,
2,020 ✔
589
    uint32_t retargeting_interval,
590
    uint32_t proof_of_work_limit) NOEXCEPT
591
{
592
    // Zero is a retarget height, termination required before height underflow.
593
    // This is guaranteed, just a comment here because it may not be obvious.
594
    return bits != proof_of_work_limit ||
2,020 ✔
595
        is_retarget_height(height, retargeting_interval);
2,017 ✔
596
}
597

598
uint32_t chain_state::work_required_retarget_bits(const data& values,
16 ✔
599
    const forks& forks, uint32_t proof_of_work_limit,
600
    uint32_t retargeting_interval) NOEXCEPT
601
{
602
    if (forks.block_storm_patch)
16 ✔
603
    {
604
        auto height = values.height;
1 ✔
605

606
        // Reverse iterate the ordered-by-height list of header bits.
607
        const auto& bits = values.bits.ordered;
1 ✔
608
        for (auto bit: std::views::reverse(bits))
2,016 ✔
609
        {
610
            if (is_retarget_or_non_limit(--height, bit, retargeting_interval,
2,016 ✔
611
                proof_of_work_limit))
612
                return bit;
1 ✔
613
        }
614
    }
615

616
    return bits_high(values);
15 ✔
617
}
618

619
uint32_t chain_state::work_required_retarget(const data& values,
16 ✔
620
    const forks& forks,
621
    uint32_t proof_of_work_limit,
622
    uint32_t minimum_timespan,
623
    uint32_t maximum_timespan,
624
    uint32_t retargeting_interval,
625
    uint32_t retargeting_interval_seconds) NOEXCEPT
626
{
627
    const auto limit = compact::expand(proof_of_work_limit);
16 ✔
628
    auto target = compact::expand(work_required_retarget_bits(values,
16 ✔
629
        forks, proof_of_work_limit, retargeting_interval));
630

631
    // Conditionally implement retarget overflow patch (e.g. Litecoin).
632
    const auto timewarp = to_int(patch_timewarp(forks, limit, target));
16 ✔
633

634
    target >>= timewarp;
16 ✔
635
    target *= retarget_timespan(values, minimum_timespan, maximum_timespan);
16 ✔
636
    target /= retargeting_interval_seconds;
16 ✔
637
    target <<= timewarp;
16 ✔
638

639
    // Disallow target from falling below minimum configured.
640
    // All targets are a bits value normalized by compress here.
641
    return target > limit ? proof_of_work_limit : compact::compress(target);
16 ✔
642
}
643

644
uint32_t chain_state::easy_work_required(const data& values,
4 ✔
645
    uint32_t retargeting_interval,
646
    uint32_t proof_of_work_limit,
647
    uint32_t block_spacing_seconds) NOEXCEPT
648
{
649
    BC_ASSERT(!is_zero(values.height));
4 ✔
650

651
    // Overflow allowed here since supported coins would not do so.
652
    const auto easy_spacing_seconds = shift_left(block_spacing_seconds);
4 ✔
653

654
    // If the time limit has passed allow a minimum difficulty block.
655
    if (values.timestamp.self > ceilinged_add(timestamp_high(values),
4 ✔
656
        easy_spacing_seconds))
657
        return proof_of_work_limit;
658

659
    auto height = values.height;
2 ✔
660
    const auto& bits = values.bits.ordered;
2 ✔
661

662
    // Reverse iterate the ordered-by-height list of header bits.
663
    for (auto bit: std::views::reverse(bits))
4 ✔
664
    {
665
        if (is_retarget_or_non_limit(--height, bit, retargeting_interval,
4 ✔
666
            proof_of_work_limit))
667
            return bit;
2 ✔
668
    }
669

670
    // Since the set of heights is either a full retarget range or ends at
671
    // zero this is not reachable unless the data set is invalid.
672
    BC_ASSERT(false);
×
673
    return proof_of_work_limit;
674
}
675

676
chain_state::map::signal chain_state::bip9_signal(size_t height,
34 ✔
677
    const deployment& deployment, const system::settings& settings) NOEXCEPT
678
{
679
    const auto period = settings.bip9_activation_period;
34 ✔
680

681
    // Sample periods down from the boundary at/below height.
682
    return
683
    {
684
        period_floor(height, period),
34 ✔
685
        period,
686
        settings.bip9_version_base,
34 ✔
687
        deployment.bit,
34 ✔
688
        deployment.start,
34 ✔
689
        deployment.timeout
34 ✔
690
    };
34 ✔
691
}
692

693
// Public static
694
// ----------------------------------------------------------------------------
695

696
chain_state::map chain_state::get_map(size_t height,
14 ✔
697
    const system::settings& settings) NOEXCEPT
698
{
699
    const auto& forks = settings.forks;
14 ✔
700
    map map{};
112 ✔
701

702
    // The signal periods of each signaled deployment.
703
    const auto configured = configured_flags(forks);
14 ✔
704
    const auto list = deployments(settings);
14 ✔
705
    for (size_t index{}; index < list.size(); ++index)
126 ✔
706
        if (is_signaled(list.at(index), settings, configured))
112 ✔
707
            map.signals.at(index) = bip9_signal(height, list.at(index),
34 ✔
708
                settings);
709

710
    // Genesis has no preceding block data.
711
    if (is_zero(height))
14 ✔
712
        return map;
713

714
    const auto interval = settings.retargeting_interval();
13 ✔
715

716
    // The height bound of the reverse (high to low) retarget search.
717
    map.bits.high = sub1(height);
13 ✔
718
    map.bits.count = bits_count(height, forks, interval);
13 ✔
719

720
    // The height bound of the median time past function.
721
    map.timestamp.high = sub1(height);
13 ✔
722
    map.timestamp.count = timestamp_count(height, forks);
13 ✔
723

724
    // The height bound of the version sample for activations.
725
    map.version.high = sub1(height);
13 ✔
726
    map.version.count = version_count(height, forks,
13 ✔
727
        settings.bip34_activation_sample);
13 ✔
728

729
    // The most recent past retarget height.
730
    map.timestamp_retarget = retarget_height(height, forks, interval);
13 ✔
731

732
    return map;
13 ✔
733
}
734

735
// Consensus defines median time using modulo 2 element selection.
736
// This differs from arithmetic median which averages two middle values.
737
uint32_t chain_state::median(const timestamps& times) NOEXCEPT
6,109 ✔
738
{
739
    const auto sorted = sort_copy(times);
6,109 ✔
740
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
741
    return sorted.empty() ? 0 : sorted.at(to_half(sorted.size()));
12,218 ✔
742
    BC_POP_WARNING()
743
}
6,109 ✔
744

745
bool chain_state::is_signal(uint32_t version, uint32_t base,
6,091 ✔
746
    uint32_t bit) NOEXCEPT
747
{
748
    return bit_and(version, bip9_version_mask) == base
6,091 ✔
749
        && get_right(version, bit);
6,091 ✔
750
}
751

752
// Only a miner signals, in the version of a block templated on the pool
753
// state. Configured bip9 groups are signaled unconditionally, where bip9
754
// defines signaling only while a deployment is started or locked in.
755
uint32_t chain_state::signal_version(const system::settings& settings) NOEXCEPT
2,036 ✔
756
{
757
    const auto& forks = settings.forks;
758

759
    // TODO: these can be retired.
760
    // Signal bip9 bit2 if any of the group is configured.
761
    if (forks.bip341 || forks.bip342)
2,036 ✔
762
        return settings.bip9_version_base | settings.bip9_version_bit2;
2,030 ✔
763

764
    // TODO: these can be retired.
765
    // Signal bip9 bit1 if any of the group is configured.
766
    if (forks.bip141 || forks.bip143 || forks.bip147)
6 ✔
767
        return settings.bip9_version_base | settings.bip9_version_bit1;
1 ✔
768

769
    // TODO: these can be retired.
770
    // Signal bip9 bit0 if any of the group is configured.
771
    if (forks.bip68 || forks.bip112 || forks.bip113)
5 ✔
772
        return settings.bip9_version_base | settings.bip9_version_bit0;
1 ✔
773

774
    if (forks.bip65)
4 ✔
775
        return settings.bip65_version;
1 ✔
776

777
    if (forks.bip66)
3 ✔
778
        return settings.bip66_version;
1 ✔
779

780
    if (forks.bip34)
2 ✔
781
        return settings.bip34_version;
1 ✔
782

783
    return settings.first_version;
1 ✔
784
}
785

786
// Signals.
787
// ----------------------------------------------------------------------------
788

789
// Count the previous block signal, and change state at a period boundary.
790
void chain_state::promote(data::signal& signal, const deployment& deployment,
6,087 ✔
791
    uint32_t version, uint32_t median_time_past, size_t height,
792
    const system::settings& settings) NOEXCEPT
793
{
794
    const auto period = settings.bip9_activation_period;
6,087 ✔
795
    if (is_signal(version, settings.bip9_version_base, deployment.bit))
6,087 ✔
796
        ++signal.count;
1 ✔
797

798
    if (is_zero(height % period))
6,087 ✔
799
    {
800
        signal.state = next_state(deployment, signal.state, median_time_past,
21 ✔
801
            signal.count, height);
802
        signal.count = zero;
21 ✔
803
    }
804
}
6,087 ✔
805

806
// Change state at each sampled boundary, from defined below the first.
807
void chain_state::reduce(data::signal& signal, const deployment& deployment,
105 ✔
808
    size_t height, size_t period) NOEXCEPT
809
{
810
    if (signal.ordered.empty())
105 ✔
811
        return;
812

813
    const auto high = period_floor(height, period);
4 ✔
814
    auto boundary = high - sub1(signal.ordered.size()) * period;
4 ✔
815
    for (const auto& value: std::views::reverse(signal.ordered))
16 ✔
816
    {
817
        signal.state = next_state(deployment, signal.state,
12 ✔
818
            value.median_time_past, value.count, boundary);
12 ✔
819
        boundary += period;
12 ✔
820
    }
821

822
    signal.ordered.clear();
4 ✔
823
}
824

825
// Versions.
826
// ----------------------------------------------------------------------------
827

828
void chain_state::count_versions(data& values,
67 ✔
829
    const system::settings& settings) NOEXCEPT
830
{
831
    values.version.bip34 = zero;
67 ✔
832
    values.version.bip66 = zero;
67 ✔
833
    values.version.bip65 = zero;
67 ✔
834
    for (const auto value: values.version.ordered)
13,984 ✔
835
        tally(values, value, true, settings);
13,917 ✔
836
}
67 ✔
837

838
// Constructors.
839
// ----------------------------------------------------------------------------
840

841
// This is promotion from a preceding height to the next.
842
chain_state::data chain_state::to_pool(const chain_state& top,
2,029 ✔
843
    const system::settings& settings) NOEXCEPT
844
{
845
    // Alias configured forks.
846
    const auto& forks = top.forks_;
2,029 ✔
847

848
    // Copy data from presumed previous-height block state.
849
    chain_state::data data{ top.data_ };
2,029 ✔
850

851
    // If this overflows height is zero and result is handled as invalid.
852
    const auto height = add1(data.height);
2,029 ✔
853

854
    // Enqueue previous block values to collections, dequeuing the oldest
855
    // member of a collection that overflows.
856
    enqueue(data.bits.ordered, data.bits.self,
2,029 ✔
857
        bits_count(height, forks, settings.retargeting_interval()));
2,029 ✔
858
    enqueue(data.timestamp.ordered, data.timestamp.self,
2,029 ✔
859
        timestamp_count(height, forks));
860

861
    // Version counts follow the versions entering and leaving the collection.
862
    tally(data, data.version.self, true, settings);
2,029 ✔
863
    if (const auto oldest = enqueue(data.version.ordered, data.version.self,
4,058 ✔
864
        version_count(height, forks, settings.bip34_activation_sample)))
2,029 ✔
865
        tally(data, oldest.value(), false, settings);
2,003 ✔
866

867
    // Regtest does not retarget, but may require the timestamp for bip54.
868
    // If promoting from retarget height, move that timestamp into retarget.
869
    if ((forks.retarget || forks.bip54_timespan) &&
2,029 ✔
870
        is_retarget_height(sub1(height), settings.retargeting_interval()))
2,029 ✔
871
    {
872
        // Conditionally patch time warp bug (e.g. Litecoin).
873
        data.timestamp.retarget = (forks.ltc_time_warp_patch && !is_one(height)) ?
8 ✔
874
            *std::next(data.timestamp.ordered.crbegin()) : data.timestamp.self;
9 ✔
875
    }
876

877
    // Promote bip9 signaling from the previous block to this height.
878
    const auto mtp = median_time_past(data, forks);
2,029 ✔
879
    const auto configured = configured_flags(forks);
2,029 ✔
880
    const auto list = deployments(settings);
2,029 ✔
881
    for (size_t index{}; index < list.size(); ++index)
18,261 ✔
882
        if (is_signaled(list.at(index), settings, configured))
16,232 ✔
883
            promote(data.signals.at(index), list.at(index),
6,087 ✔
884
                data.version.self, mtp, height, settings);
885

886
    // Replace previous block state with tx pool chain state for next height
887
    // Preserve top block timestamp for use in computation of staleness.
888
    // bits.self is unused.
889
    data.height = height;
2,029 ✔
890
    data.hash = {};
2,029 ✔
891
    data.bits.self = 0;
2,029 ✔
892
    data.version.self = signal_version(settings);
2,029 ✔
893
    return data;
2,029 ✔
894
}
×
895

896
// Top to pool.
897
// This generates a state for the pool above the presumed top block state.
898
chain_state::chain_state(const chain_state& top,
2,011 ✔
899
    const system::settings& settings) NOEXCEPT
2,011 ✔
900
  : data_(to_pool(top, settings)),
2,011 ✔
901
    forks_(top.forks_),
2,011 ✔
902
    activations_(activation(data_, forks_, settings)),
2,011 ✔
903
    work_required_(work_required(data_, forks_, settings)),
2,011 ✔
904
    median_time_past_(median_time_past(data_, forks_))
4,022 ✔
905
{
906
}
2,011 ✔
907

908
chain_state::data chain_state::to_block(const chain_state& pool,
2,005 ✔
909
    const block& block) NOEXCEPT
910
{
911
    // Copy data from presumed same-height pool state.
912
    chain_state::data data{ pool.data_ };
2,005 ✔
913

914
    // Replace pool chain state with block state at same (next) height.
915
    // Preserve data.timestamp.retarget promotion.
916
    const auto& header = block.header();
2,005 ✔
917
    data.hash = {};
2,005 ✔
918
    data.bits.self = header.bits();
2,005 ✔
919
    data.version.self = header.version();
2,005 ✔
920
    data.timestamp.self = header.timestamp();
2,005 ✔
921
    data.cumulative_work += header.proof();
2,005 ✔
922

923
    return data;
2,005 ✔
924
}
×
925

926
// Pool to block.
927
// This assumes that the pool state is the same height as the block.
928
chain_state::chain_state(const chain_state& pool, const block& block,
2,005 ✔
929
    const system::settings& settings) NOEXCEPT
2,005 ✔
930
  : data_(to_block(pool, block)),
2,005 ✔
931
    forks_(pool.forks_),
2,005 ✔
932
    activations_(activation(data_, forks_, settings)),
2,005 ✔
933
    work_required_(work_required(data_, forks_, settings)),
2,005 ✔
934
    median_time_past_(median_time_past(data_, forks_))
4,010 ✔
935
{
936
}
2,005 ✔
937

938
chain_state::data chain_state::to_header(const chain_state& parent,
18 ✔
939
    const header& header, const system::settings& settings) NOEXCEPT
940
{
941
    BC_ASSERT(header.previous_block_hash() == parent.hash());
18 ✔
942

943
    // Copy and promote data from presumed parent-height header/block state.
944
    auto data = to_pool(parent, settings);
18 ✔
945

946
    // Replace the parent (pool or previous) block state with given state.
947
    // Preserve data.timestamp.retarget promotion.
948
    data.hash = header.hash();
18 ✔
949
    data.bits.self = header.bits();
18 ✔
950
    data.version.self = header.version();
18 ✔
951
    data.timestamp.self = header.timestamp();
18 ✔
952
    data.cumulative_work += header.proof();
18 ✔
953

954
    return data;
18 ✔
955
}
×
956

957
// Parent to header.
958
// This assumes that parent is the state of the header's previous block.
959
chain_state::chain_state(const chain_state& parent, const header& header,
18 ✔
960
    const system::settings& settings) NOEXCEPT
18 ✔
961
  : data_(to_header(parent, header, settings)),
18 ✔
962
    forks_(parent.forks_),
18 ✔
963
    activations_(activation(data_, forks_, settings)),
18 ✔
964
    work_required_(work_required(data_, forks_, settings)),
18 ✔
965
    median_time_past_(median_time_past(data_, forks_))
36 ✔
966
{
967
}
18 ✔
968

969
chain_state::data chain_state::to_values(data values,
40 ✔
970
    const system::settings& settings) NOEXCEPT
971
{
972
    count_versions(values, settings);
40 ✔
973

974
    const auto period = settings.bip9_activation_period;
40 ✔
975
    const auto configured = configured_flags(settings.forks);
40 ✔
976
    const auto list = deployments(settings);
40 ✔
977

978
    // Compute bip9 states from sampled boundaries.
979
    for (size_t index{}; index < list.size(); ++index)
360 ✔
980
        if (is_signaled(list.at(index), settings, configured))
320 ✔
981
            reduce(values.signals.at(index), list.at(index), values.height,
105 ✔
982
                period);
983

984
    return values;
40 ✔
985
}
986

987
// From scratch (e.g. raw data obtained from store).
988
chain_state::chain_state(data&& values,
40 ✔
989
    const system::settings& settings) NOEXCEPT
40 ✔
990
  : data_(to_values(std::move(values), settings)),
40 ✔
991
    forks_(settings.forks),
40 ✔
992
    activations_(activation(data_, forks_, settings)),
40 ✔
993
    work_required_(work_required(data_, forks_, settings)),
40 ✔
994
    median_time_past_(median_time_past(data_, forks_))
80 ✔
995
{
996
}
40 ✔
997

998
// Properties.
999
// ----------------------------------------------------------------------------
1000

1001
chain::context chain_state::context() const NOEXCEPT
3 ✔
1002
{
1003
    return
1004
    {
1005
        flags(),
3 ✔
1006
        timestamp(),
3 ✔
1007
        median_time_past(),
3 ✔
1008
        possible_narrow_cast<uint32_t>(height()),
3 ✔
1009
        minimum_block_version(),
3 ✔
1010
        work_required(),
3 ✔
1011
        previous_timestamp(),
3 ✔
1012
        retarget_timestamp()
3 ✔
1013
    };
3 ✔
1014
}
1015

1016
const hash_digest& chain_state::hash() const NOEXCEPT
29 ✔
1017
{
1018
    return data_.hash;
29 ✔
1019
}
1020

1021
const uint256_t& chain_state::cumulative_work() const NOEXCEPT
6 ✔
1022
{
1023
    return data_.cumulative_work;
6 ✔
1024
}
1025

1026
uint32_t chain_state::minimum_block_version() const NOEXCEPT
11 ✔
1027
{
1028
    return activations_.minimum_block_version;
11 ✔
1029
}
1030

1031
uint32_t chain_state::work_required() const NOEXCEPT
7 ✔
1032
{
1033
    return work_required_;
7 ✔
1034
}
1035

1036
// context
1037

1038
uint32_t chain_state::timestamp() const NOEXCEPT
10 ✔
1039
{
1040
    return data_.timestamp.self;
10 ✔
1041
}
1042

1043
uint32_t chain_state::previous_timestamp() const NOEXCEPT
9 ✔
1044
{
1045
    return data_.timestamp.ordered.empty() ? 0 : timestamp_high(data_);
9 ✔
1046
}
1047

1048
uint32_t chain_state::retarget_timestamp() const NOEXCEPT
6 ✔
1049
{
1050
    return data_.timestamp.retarget;
6 ✔
1051
}
1052

1053
uint32_t chain_state::median_time_past() const NOEXCEPT
7 ✔
1054
{
1055
    return median_time_past_;
7 ✔
1056
}
1057

1058
uint32_t chain_state::flags() const NOEXCEPT
40 ✔
1059
{
1060
    return activations_.flags;
40 ✔
1061
}
1062

1063
size_t chain_state::height() const NOEXCEPT
18 ✔
1064
{
1065
    return data_.height;
18 ✔
1066
}
1067

1068
} // namespace chain
1069
} // namespace system
1070
} // namespace libbitcoin
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc