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

libbitcoin / libbitcoin-system / 15428987191

03 Jun 2025 10:17PM UTC coverage: 81.096% (+0.006%) from 81.09%
15428987191

push

github

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

Update header.version processing, style, refactor.

1 of 17 new or added lines in 3 files covered. (5.88%)

1 existing line in 1 file now uncovered.

10433 of 12865 relevant lines covered (81.1%)

3684919.44 hits per line

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

10.79
/src/chain/chain_state.cpp
1
/**
2
 * Copyright (c) 2011-2025 libbitcoin developers (see AUTHORS)
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 <algorithm>
22
#include <chrono>
23
#include <iterator>
24
#include <ranges>
25
#include <bitcoin/system/chain/block.hpp>
26
#include <bitcoin/system/chain/chain_state.hpp>
27
#include <bitcoin/system/chain/checkpoint.hpp>
28
#include <bitcoin/system/chain/compact.hpp>
29
#include <bitcoin/system/chain/context.hpp>
30
#include <bitcoin/system/chain/enums/flags.hpp>
31
#include <bitcoin/system/chain/enums/policy.hpp>
32
#include <bitcoin/system/chain/script.hpp>
33
#include <bitcoin/system/data/data.hpp>
34
#include <bitcoin/system/forks.hpp>
35
#include <bitcoin/system/hash/hash.hpp>
36
#include <bitcoin/system/math/math.hpp>
37
#include <bitcoin/system/settings.hpp>
38

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

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

54
// Inlines.
55
// ----------------------------------------------------------------------------
56

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

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

67
// Determine the number of blocks back to the closest retarget height.
68
constexpr size_t retarget_distance(size_t height,
2✔
69
    size_t retargeting_interval) NOEXCEPT
70
{
71
    return height % retargeting_interval;
2✔
72
}
73

74
// Determine if height is a multiple of retargeting_interval.
75
constexpr bool is_retarget_height(size_t height,
2✔
76
    size_t retargeting_interval) NOEXCEPT
77
{
78
    return is_zero(retarget_distance(height, retargeting_interval));
2✔
79
}
80

81
// bip30 is active for all but two mainnet blocks that violate the rule.
82
// These two blocks each have a coinbase transaction that exactly duplicates
83
// another that is not spent by the arrival of the corresponding duplicate.
84
// Exceptions: block 91842 (duplicates 91812), 91880 (duplicates 91722).
85
inline bool is_bip30_exception(const hash_digest& hash, size_t height) NOEXCEPT
×
86
{
87
    return (hash   == mainnet_bip30_exception_checkpoint1.hash() &&
×
88
            height == mainnet_bip30_exception_checkpoint1.height()) ||
×
89
           (hash   == mainnet_bip30_exception_checkpoint2.hash() &&
×
90
            height == mainnet_bip30_exception_checkpoint2.height());
×
91
}
92

93
inline uint32_t timestamp_high(const chain_state::data& values) NOEXCEPT
2✔
94
{
95
    return values.timestamp.ordered.back();
2✔
96
}
97

98
inline uint32_t bits_high(const chain_state::data& values) NOEXCEPT
4✔
99
{
100
    return values.bits.ordered.back();
4✔
101
}
102

103
// activation
104
// ----------------------------------------------------------------------------
105

106
chain_state::activations chain_state::activation(const data& values,
×
107
    const forks& forks, const system::settings& settings) NOEXCEPT
108
{
109
    // There are no constraints on block version before bip34.
NEW
110
    activations result{ flags::no_rules, 0 };
×
111

112
    // regtest is only activated via configuration.
113
    if (forks.retarget)
×
114
    {
115
        result.flags |= flags::retarget;
×
116
    }
117

118
    // testnet is activated based on configuration alone.
119
    if (forks.difficult)
×
120
    {
121
        result.flags |= flags::difficult;
×
122
    }
123

124
    // time_warp_patch is activated based on configuration alone.
125
    if (forks.time_warp_patch)
×
126
    {
127
        result.flags |= flags::time_warp_patch;
×
128
    }
129

130
    // retarget_overflow_patch is activated based on configuration alone.
131
    if (forks.retarget_overflow_patch)
×
132
    {
133
        result.flags |= flags::retarget_overflow_patch;
×
134
    }
135

136
    // scrypt_proof_of_work is activated based on configuration alone.
137
    if (forks.scrypt_proof_of_work)
×
138
    {
139
        result.flags |= flags::scrypt_proof_of_work;
×
140
    }
141

142
    // bip42 is activated based on configuration alone (soft fork).
143
    if (forks.bip42)
×
144
    {
145
        result.flags |= flags::bip42_rule;
×
146
    }
147

148
    // bip90 is activated based on configuration alone (hard fork).
149
    if (forks.bip90)
×
150
    {
151
        result.flags |= flags::bip90_rule;
×
152
    }
153

154
    // bip16 was activated by manual inspection of signal history (soft fork).
155
    if (forks.bip16 &&
×
156
        (values.timestamp.self >= settings.bip16_activation_time))
×
157
    {
158
        result.flags |= flags::bip16_rule;
×
159
    }
160

161
    const auto height = values.height;
×
162
    const auto version = values.version.self;
×
163
    const auto& history = values.version.ordered;
×
164

165
    //*************************************************************************
166
    // CONSENSUS: Though unspecified in bip34, the satoshi implementation
167
    // performed this comparison using the signed integer version value.
168
    //*************************************************************************
169
    constexpr auto ge = [](uint32_t value, uint32_t version) NOEXCEPT
×
170
    {
171
        return sign_cast<int32_t>(value) >= sign_cast<int32_t>(version);
×
172
    };
173

174
    // Declare bip34-based version predicates.
175
    const auto ge_2 = [&](uint32_t value) NOEXCEPT
×
176
        { return ge(value, settings.bip34_version); };
×
177
    const auto ge_3 = [&](uint32_t value) NOEXCEPT
×
178
        { return ge(value, settings.bip66_version); };
×
179
    const auto ge_4 = [&](uint32_t value) NOEXCEPT
×
180
        { return ge(value, settings.bip65_version); };
×
181

182
    // Compute bip34-based activation version summaries (empty if disabled).
183
    const auto count_2 = std::count_if(history.begin(), history.end(), ge_2);
×
184
    const auto count_3 = std::count_if(history.begin(), history.end(), ge_3);
×
185
    const auto count_4 = std::count_if(history.begin(), history.end(), ge_4);
×
186

187
    // Frozen activations (require version and enforce above freeze height).
188
    const auto bip90_bip34 = forks.bip90 && height >= settings.bip90_bip34_height;
×
189
    const auto bip90_bip65 = forks.bip90 && height >= settings.bip90_bip65_height;
×
190
    const auto bip90_bip66 = forks.bip90 && height >= settings.bip90_bip66_height;
×
191

192
    // bip34 activations oscillate until enforced by minimum_block_version.
193
    // bip90 does not require that the corresponding rules be defined.
194
    // bip34 is active based on 75% of preceding 1000 mainnet blocks.
195
    if (bip90_bip34 ||
×
196
        (is_active(count_2, settings.bip34_activation_threshold) &&
×
197
        version >= settings.bip34_version))
×
198
    {
199
        result.flags |= flags::bip34_rule;
×
200
    }
201

202
    // bip66 is active based on 75% of preceding 1000 mainnet blocks.
203
    if (bip90_bip66 ||
×
204
        (is_active(count_3, settings.bip34_activation_threshold) &&
×
205
        version >= settings.bip66_version))
×
206
    {
207
        result.flags |= flags::bip66_rule;
×
208
    }
209

210
    // bip65 is active based on 75% of preceding 1000 mainnet blocks.
211
    if (bip90_bip65 ||
×
212
        (is_active(count_4, settings.bip34_activation_threshold) &&
×
213
        version >= settings.bip65_version))
×
214
    {
215
        result.flags |= flags::bip65_rule;
×
216
    }
217

218
    // version 4/3/2 enforced based on 95% of preceding 1000 mainnet blocks.
219
    if (bip90_bip65 ||
×
220
        is_enforced(count_4, settings.bip34_enforcement_threshold))
×
221
    {
222
        result.minimum_block_version = settings.bip65_version;
×
223
    }
224
    else if (bip90_bip66 ||
×
225
        is_enforced(count_3, settings.bip34_enforcement_threshold))
×
226
    {
227
        result.minimum_block_version = settings.bip66_version;
×
228
    }
229
    else if (bip90_bip34 ||
×
230
        is_enforced(count_2, settings.bip34_enforcement_threshold))
×
231
    {
232
        result.minimum_block_version = settings.bip34_version;
×
233
    }
234

235
    // TODO: bip9 historical activation.
236

237
    // bip9_bit0 forks are enforced above the bip9_bit0 checkpoint.
238
    if (values.bip9_bit0_hash == settings.bip9_bit0_active_checkpoint.hash())
×
239
    {
240
        result.flags |= flags::bip68_rule;
×
241
        result.flags |= flags::bip112_rule;
×
242
        result.flags |= flags::bip113_rule;
×
243
    }
244

245
    // bip9_bit1 forks are enforced above the bip9_bit1 checkpoint.
246
    if (values.bip9_bit1_hash == settings.bip9_bit1_active_checkpoint.hash())
×
247
    {
248
        result.flags |= flags::bip141_rule;
×
249
        result.flags |= flags::bip143_rule;
×
250
        result.flags |= flags::bip147_rule;
×
251
    }
252

253
    // bip9_bit2 forks are enforced above the bip9_bit2 checkpoint.
254
    if (values.bip9_bit2_hash == settings.bip9_bit2_active_checkpoint.hash())
×
255
    {
256
        result.flags |= flags::bip341_rule;
×
257
        result.flags |= flags::bip342_rule;
×
258
    }
259

260
    // bip30_deactivate fork enforced above bip30_deactivate (bip34) checkpoint.
261
    const auto bip30_deactivate = forks.bip30 && forks.bip30_deactivate &&
×
262
        (values.bip30_deactivate_hash == settings.bip30_deactivate_checkpoint.hash());
×
263

264
    // bip30_reactivate fork is enforced above the bip30_reactivate height.
265
    const auto bip30_reactivate = bip30_deactivate && forks.bip30_reactivate &&
×
266
        (height >= settings.bip30_reactivate_height);
×
267

268
    // bip30 is disabled by bip30_deactivate and reenabled by bip30_reactivate.
269
    // Otherwise if not exception, existing duplicate coinbase must be spent.
270
    if (forks.bip30 && (!bip30_deactivate || bip30_reactivate) &&
×
271
        !is_bip30_exception(values.hash, height))
×
272
    {
273
        result.flags |= flags::bip30_rule;
×
274
    }
275

276
    return result;
×
277
}
278

279
size_t chain_state::bits_count(size_t height, const forks& forks,
×
280
    size_t retargeting_interval) NOEXCEPT
281
{
282
    // Mainnet doesn't use bits in retargeting.
283
    if (forks.difficult)
×
284
        return one;
285

286
    // Regtest bypasses all retargeting.
287
    if (!forks.retarget)
×
288
        return one;
289

290
    // Testnet uses mainnet retargeting on interval.
291
    if (is_retarget_height(height, retargeting_interval))
×
292
        return one;
293

294
    // Testnet requires all bits for inter-interval retargeting.
295
    return std::min(height, retargeting_interval);
×
296
}
297

298
size_t chain_state::version_count(size_t height, const forks& forks,
×
299
    size_t bip34_activation_sample) NOEXCEPT
300
{
301
    if (forks.bip90 || (!forks.bip34 && !forks.bip65 && !forks.bip66))
×
302
        return zero;
303

304
    return std::min(height, bip34_activation_sample);
×
305
}
306

307
size_t chain_state::timestamp_count(size_t height, const forks&) NOEXCEPT
×
308
{
309
    return std::min(height, median_time_past_interval);
×
310
}
311

312
size_t chain_state::retarget_height(size_t height, const forks& forks,
×
313
    size_t retargeting_interval) NOEXCEPT
314
{
315
    if (!forks.retarget)
×
316
        return map::unrequested;
317

318
    // Height must be a positive multiple of interval, so underflow safe.
319
    // If not retarget height get most recent so that it may be promoted.
320
    return height - (is_retarget_height(height, retargeting_interval) ?
×
321
        retargeting_interval : retarget_distance(height, retargeting_interval));
×
322
}
323

324
// median_time_past
325
// ----------------------------------------------------------------------------
326

327
//*****************************************************************************
328
// CONSENSUS: satoshi associates the median time past for block N with block
329
// N-1, as opposed to block N. Given that the value is actually obtained from
330
// yet another preceding block in all cases except block 1 and 2, this is a
331
// curious and confusing convention. We associate the median time past for
332
// block N with block N. This is simple but requires care when comparing code.
333
//*****************************************************************************
334
uint32_t chain_state::median_time_past(const data& values,
×
335
    const forks&) NOEXCEPT
336
{
337
    // Sort the times by value to obtain the median.
338
    auto times = sort_copy(values.timestamp.ordered);
×
339

340
    // Consensus defines median time using modulo 2 element selection.
341
    // This differs from arithmetic median which averages two middle values.
342
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
343
    return times.empty() ? 0 : times.at(to_half(times.size()));
×
344
    BC_POP_WARNING()
345
}
346

347
// work_required
348
// ----------------------------------------------------------------------------
349

350
uint32_t chain_state::work_required(const data& values, const forks& forks,
2✔
351
    const system::settings& settings) NOEXCEPT
352
{
353
    // Genesis has no preceding block data.
354
    if (is_zero(values.height))
2✔
355
        return 0;
356

357
    // Previous block has an invalid bits value.
358
    if (is_zero(compact::expand(bits_high(values))))
2✔
359
        return 0;
360

361
    // Regtest bypasses all retargeting.
362
    if (!forks.retarget)
2✔
363
        return bits_high(values);
×
364

365
    // Mainnet and testnet retarget on interval.
366
    if (is_retarget_height(values.height, settings.retargeting_interval()))
2✔
367
        return work_required_retarget(values, forks,
6✔
368
            settings.proof_of_work_limit,
2✔
369
            settings.minimum_timespan(),
2✔
370
            settings.maximum_timespan(),
2✔
371
            settings.retargeting_interval_seconds);
4✔
372

373
    // Testnet retargets easy on inter-interval.
374
    if (!forks.difficult)
×
375
        return easy_work_required(values,
×
376
            settings.retargeting_interval(),
×
377
            settings.proof_of_work_limit,
×
378
            settings.block_spacing_seconds);
×
379

380
    // Mainnet not retargeting, must exact match the previous block bits value.
381
    return bits_high(values);
×
382
}
383

384
// Get the bounded total time spanning the highest 2016 blocks.
385
uint32_t chain_state::retarget_timespan(const data& values,
2✔
386
    uint32_t minimum_timespan, uint32_t maximum_timespan) NOEXCEPT
387
{
388
    //*************************************************************************
389
    // CONSENSUS: "Subtract unsigned 32 bit numbers in signed 64 bit space".
390
    // This is done order to prevent underflow before applying the range
391
    // constraint. This is properly just a floored subtraction in 32 bit space.
392
    //*************************************************************************
393
    const auto timespan = floored_subtract(timestamp_high(values),
2✔
394
        values.timestamp.retarget);
2✔
395

396
    //*************************************************************************
397
    // CONSENSUS: Constrain the timespan to the configured consensus limits.
398
    //*************************************************************************
399
    return limit(timespan, minimum_timespan, maximum_timespan);
2✔
400
}
401

402
constexpr bool patch_timewarp(const forks& forks, const uint256_t& limit,
2✔
403
    const uint256_t& target) NOEXCEPT
404
{
405
    return forks.retarget_overflow_patch &&
3✔
406
        floored_log2(target) >= floored_log2(limit);
1✔
407
}
408

409
uint32_t chain_state::work_required_retarget(const data& values,
2✔
410
    const forks& forks, uint32_t proof_of_work_limit,
411
    uint32_t minimum_timespan, uint32_t maximum_timespan,
412
    uint32_t retargeting_interval_seconds) NOEXCEPT
413
{
414
    static const auto limit = compact::expand(proof_of_work_limit);
2✔
415
    auto target = compact::expand(bits_high(values));
2✔
416

417
    // Conditionally implement retarget overflow patch (e.g. Litecoin).
418
    const auto timewarp = to_int(patch_timewarp(forks, limit, target));
2✔
419

420
    target >>= timewarp;
2✔
421
    target *= retarget_timespan(values, minimum_timespan, maximum_timespan);
2✔
422
    target /= retargeting_interval_seconds;
2✔
423
    target <<= timewarp;
2✔
424

425
    // Disallow target from falling below minimum configured.
426
    // All targets are a bits value normalized by compress here.
427
    return target > limit ? proof_of_work_limit : compact::compress(target);
2✔
428
}
429

430
// A retarget height, or a block that does not have proof_of_work_limit bits.
431
constexpr bool is_retarget_or_non_limit(size_t height, uint32_t bits,
×
432
    size_t retargeting_interval, uint32_t proof_of_work_limit) NOEXCEPT
433
{
434
    // Zero is a retarget height, termination required before height underflow.
435
    // This is guaranteed, just a comment here because it may not be obvious.
436
    return bits != proof_of_work_limit ||
×
437
        is_retarget_height(height, retargeting_interval);
438
}
439

440
uint32_t chain_state::easy_work_required(const data& values,
×
441
    size_t retargeting_interval, uint32_t proof_of_work_limit,
442
    uint32_t block_spacing_seconds) NOEXCEPT
443
{
444
    BC_ASSERT(!is_zero(values.height));
×
445

446
    // Overflow allowed here since supported coins would not do so.
447
    const auto easy_spacing_seconds = shift_left(block_spacing_seconds);
×
448

449
    // If the time limit has passed allow a minimum difficulty block.
450
    if (values.timestamp.self > ceilinged_add(timestamp_high(values),
×
451
        easy_spacing_seconds))
452
        return proof_of_work_limit;
453

454
    auto height = values.height;
×
455
    const auto& bits = values.bits.ordered;
×
456

457
    // Reverse iterate the ordered-by-height list of header bits.
458
    for (auto bit: std::views::reverse(bits))
×
459
    {
460
        if (is_retarget_or_non_limit(--height, bit, retargeting_interval,
×
461
            proof_of_work_limit))
462
            return bit;
×
463
    }
464

465
    // Since the set of heights is either a full retarget range or ends at
466
    // zero this is not reachable unless the data set is invalid.
467
    BC_ASSERT(false);
×
468
    return proof_of_work_limit;
×
469
}
470

471
// ****************************************************************************
472
// CONSENSUS: Hardcoded in satoshi client 0.10.0 (pull request #6931), based on
473
// the assumption that bip34 made bip30 redundant (at least if bip34 active).
474
// However it was later learned that bip34 does not make bip30 redundant. As a
475
// result satoshi client 0.17.0 (pull request #12204) restored the checks. This
476
// constitutes a hard fork and a subsequent soft fork in addition to bip30. We
477
// refer to these as bip30_deactivate and bip30_reactivate and roll them into
478
// the bip30 flag for validation purposes.
479
// ****************************************************************************
480
size_t chain_state::bip30_deactivate_height(size_t height,
×
481
    const checkpoint& bip30_deactivate_checkpoint) NOEXCEPT
482
{
483
    const auto activation_height = bip30_deactivate_checkpoint.height();
×
484

485
    // Require bip30_deactivate hash at heights at/above bip30_deactivate active.
486
    return height < activation_height ? map::unrequested : activation_height;
×
487
}
488

489
// ****************************************************************************
490
// CONSENSUS: Hardcoded with bip90 activated.
491
// ****************************************************************************
492
size_t chain_state::bip9_bit0_height(size_t height,
×
493
    const checkpoint& bip9_bit0_active_checkpoint) NOEXCEPT
494
{
495
    const auto activation_height = bip9_bit0_active_checkpoint.height();
×
496

497
    // Require bip9_bit0 hash at heights at/above bip9_bit0 active.
498
    return height < activation_height ? map::unrequested : activation_height;
×
499
}
500

501
// ****************************************************************************
502
// CONSENSUS: Hardcoded in satoshi client (pull request #????).
503
// ****************************************************************************
504
size_t chain_state::bip9_bit1_height(size_t height,
×
505
    const checkpoint& bip9_bit1_active_checkpoint) NOEXCEPT
506
{
507
    const auto activation_height = bip9_bit1_active_checkpoint.height();
×
508

509
    // Require bip9_bit1 hash at heights at/above bip9_bit1 active.
510
    return height < activation_height ? map::unrequested : activation_height;
×
511
}
512

513
// ****************************************************************************
514
// CONSENSUS: Not yet hardcoded in satoshi client (as of 0.29.0).
515
// ****************************************************************************
516
size_t chain_state::bip9_bit2_height(size_t height,
×
517
    const checkpoint& bip9_bit2_active_checkpoint) NOEXCEPT
518
{
519
    const auto activation_height = bip9_bit2_active_checkpoint.height();
×
520

521
    // Require bip9_bit2 hash at heights at/above bip9_bit2 active.
522
    return height < activation_height ? map::unrequested : activation_height;
×
523
}
524

525
// Public static
526
// ----------------------------------------------------------------------------
527

528
chain_state::map chain_state::get_map(size_t height,
×
529
    const system::settings& settings) NOEXCEPT
530
{
531
    if (is_zero(height))
×
532
        return {};
×
533

534
    const auto& forks = settings.forks;
×
535
    const auto interval = settings.retargeting_interval();
×
536
    map map{};
×
537

538
    // The height bound of the reverse (high to low) retarget search.
539
    map.bits.high = sub1(height);
×
540
    map.bits.count = bits_count(height, forks, interval);
×
541

542
    // The height bound of the median time past function.
543
    map.timestamp.high = sub1(height);
×
544
    map.timestamp.count = timestamp_count(height, forks);
×
545

546
    // The height bound of the version sample for activations.
547
    map.version.high = sub1(height);
×
548
    map.version.count = version_count(height, forks,
×
549
        settings.bip34_activation_sample);
×
550

551
    // The most recent past retarget height.
552
    map.timestamp_retarget = retarget_height(height, forks, interval);
×
553

554
    // The checkpoint at/above which bip30_deactivate rule is enforced.
555
    if (forks.bip30 && forks.bip30_deactivate)
×
556
        map.bip30_deactivate_height = bip30_deactivate_height(height,
×
557
            settings.bip30_deactivate_checkpoint);
×
558

559
    // The checkpoint at/above which bip9_bit0 rules are enforced.
560
    if (forks.bip68 || forks.bip112 || forks.bip113)
×
561
        map.bip9_bit0_height = bip9_bit0_height(height,
×
562
            settings.bip9_bit0_active_checkpoint);
×
563

564
    // The checkpoint at/above which bip9_bit1 rules are enforced.
565
    if (forks.bip141 || forks.bip143 || forks.bip147)
×
566
        map.bip9_bit1_height = bip9_bit1_height(height,
×
567
            settings.bip9_bit1_active_checkpoint);
×
568

569
    // The checkpoint at/above which bip9_bit2 rules are enforced.
570
    if (forks.bip341 || forks.bip342)
×
571
        map.bip9_bit2_height = bip9_bit2_height(height,
×
572
            settings.bip9_bit2_active_checkpoint);
×
573

574
    return map;
×
575
}
576

577
uint32_t chain_state::signal_version(const system::settings& settings) NOEXCEPT
×
578
{
579
    const auto& forks = settings.forks;
×
580

581
    // TODO: these can be retired.
582
    // Signal bip9 bit2 if any of the group is configured.
583
    if (forks.bip341 || forks.bip342)
×
584
        return settings.bip9_version_base | settings.bip9_version_bit2;
×
585

586
    // TODO: these can be retired.
587
    // Signal bip9 bit1 if any of the group is configured.
588
    if (forks.bip141 || forks.bip143 || forks.bip147)
×
589
        return settings.bip9_version_base | settings.bip9_version_bit1;
×
590

591
    // TODO: these can be retired.
592
    // Signal bip9 bit0 if any of the group is configured.
593
    if (forks.bip68 || forks.bip112 || forks.bip113)
×
594
        return settings.bip9_version_base | settings.bip9_version_bit0;
×
595

596
    if (forks.bip65)
×
597
        return settings.bip65_version;
×
598

599
    if (forks.bip66)
×
600
        return settings.bip66_version;
×
601

602
    if (forks.bip34)
×
603
        return settings.bip34_version;
×
604

605
    return settings.first_version;
×
606
}
607

608
// Constructors.
609
// ----------------------------------------------------------------------------
610

611
// This is promotion from a preceding height to the next.
612
chain_state::data chain_state::to_pool(const chain_state& top,
×
613
    const system::settings& settings) NOEXCEPT
614
{
615
    // Alias configured forks.
616
    const auto& forks = top.forks_;
×
617

618
    // Copy data from presumed previous-height block state.
619
    chain_state::data data{ top.data_ };
×
620

621
    // If this overflows height is zero and result is handled as invalid.
622
    const auto height = add1(data.height);
×
623
    
624
    // Enqueue previous block values to collections.
625
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
626
    data.bits.ordered.push_back(data.bits.self);
×
627
    data.version.ordered.push_back(data.version.self);
×
628
    data.timestamp.ordered.push_back(data.timestamp.self);
×
629
    BC_POP_WARNING()
630

631
    // If bits collection overflows, dequeue oldest member.
632
    if (data.bits.ordered.size() >
×
633
        bits_count(height, forks, settings.retargeting_interval()))
×
634
        data.bits.ordered.pop_front();
×
635

636
    // If version collection overflows, dequeue oldest member.
637
    if (data.version.ordered.size() > version_count(height, forks,
×
638
        settings.bip34_activation_sample))
×
639
        data.version.ordered.pop_front();
×
640

641
    // If timestamp collection overflows, dequeue oldest member.
642
    if (data.timestamp.ordered.size() > timestamp_count(height, forks))
×
643
        data.timestamp.ordered.pop_front();
×
644

645
    // Regtest does not perform retargeting.
646
    // If promoting from retarget height, move that timestamp into retarget.
647
    if (forks.retarget && is_retarget_height(sub1(height),
×
648
        settings.retargeting_interval()))
×
649
    {
650
        // Conditionally patch time warp bug (e.g. Litecoin).
651
        data.timestamp.retarget = (forks.time_warp_patch && !is_one(height)) ?
×
652
            *std::next(data.timestamp.ordered.crbegin()) : data.timestamp.self;
×
653
    }
654

655
    // Replace previous block state with tx pool chain state for next height
656
    // Preserve top block timestamp for use in computation of staleness.
657
    // Preserve data.bip30_deactivate_hash promotion.
658
    // Preserve data.bip9_bit0_hash promotion.
659
    // Preserve data.bip9_bit1_hash promotion.
660
    // bits.self is unused.
661
    data.height = height;
×
662
    data.hash = {};
×
663
    data.bits.self = 0;
×
664
    data.version.self = signal_version(settings);
×
665
    return data;
×
666
}
667

668
// Top to pool.
669
// This generates a state for the pool above the presumed top block state.
670
chain_state::chain_state(const chain_state& top,
×
671
    const system::settings& settings) NOEXCEPT
×
672
  : data_(to_pool(top, settings)),
×
673
    forks_(top.forks_),
×
674
    activations_(activation(data_, forks_, settings)),
×
675
    work_required_(work_required(data_, forks_, settings)),
×
676
    median_time_past_(median_time_past(data_, forks_))
×
677
{
678
}
×
679

680
chain_state::data chain_state::to_block(const chain_state& pool,
×
681
    const block& block, const system::settings& settings) NOEXCEPT
682
{
683
    // Copy data from presumed same-height pool state.
684
    chain_state::data data{ pool.data_ };
×
685

686
    // Replace pool chain state with block state at same (next) height.
687
    // Preserve data.timestamp.retarget promotion.
688
    const auto& header = block.header();
×
689
    data.hash = {};
×
690
    data.bits.self = header.bits();
×
691
    data.version.self = header.version();
×
692
    data.timestamp.self = header.timestamp();
×
693
    data.cumulative_work += header.proof();
×
694

695
    // Cache hash of bip30_deactivate block, otherwise use preceding state.
696
    if (data.height == settings.bip30_deactivate_checkpoint.height())
×
697
        data.bip30_deactivate_hash = data.hash;
×
698

699
    // Cache hash of bip9 bit0 height block, otherwise use preceding state.
700
    if (data.height == settings.bip9_bit0_active_checkpoint.height())
×
701
        data.bip9_bit0_hash = data.hash;
×
702

703
    // Cache hash of bip9 bit1 height block, otherwise use preceding state.
704
    if (data.height == settings.bip9_bit1_active_checkpoint.height())
×
705
        data.bip9_bit1_hash = data.hash;
×
706

707
    // Cache hash of bip9 bit2 height block, otherwise use preceding state.
708
    if (data.height == settings.bip9_bit2_active_checkpoint.height())
×
709
        data.bip9_bit2_hash = data.hash;
×
710

711
    return data;
×
712
}
713

714
// Pool to block.
715
// This assumes that the pool state is the same height as the block.
716
chain_state::chain_state(const chain_state& pool, const block& block,
×
717
    const system::settings& settings) NOEXCEPT
×
718
  : data_(to_block(pool, block, settings)),
×
719
    forks_(pool.forks_),
×
720
    activations_(activation(data_, forks_, settings)),
×
721
    work_required_(work_required(data_, forks_, settings)),
×
722
    median_time_past_(median_time_past(data_, forks_))
×
723
{
724
}
×
725

726
chain_state::data chain_state::to_header(const chain_state& parent,
×
727
    const header& header, const system::settings& settings) NOEXCEPT
728
{
729
    BC_ASSERT(header.previous_block_hash() == parent.hash());
×
730

731
    // Copy and promote data from presumed parent-height header/block state.
732
    auto data = to_pool(parent, settings);
×
733

734
    // Replace the parent (pool or previous) block state with given state.
735
    // Preserve data.timestamp.retarget promotion.
736
    data.hash = header.hash();
×
737
    data.bits.self = header.bits();
×
738
    data.version.self = header.version();
×
739
    data.timestamp.self = header.timestamp();
×
740
    data.cumulative_work += header.proof();
×
741

742
    // Cache hash of bip30_deactivate block, otherwise use preceding state.
743
    if (data.height == settings.bip30_deactivate_checkpoint.height())
×
744
        data.bip30_deactivate_hash = data.hash;
×
745

746
    // Cache hash of bip9 bit0 height block, otherwise use preceding state.
747
    if (data.height == settings.bip9_bit0_active_checkpoint.height())
×
748
        data.bip9_bit0_hash = data.hash;
×
749

750
    // Cache hash of bip9 bit1 height block, otherwise use preceding state.
751
    if (data.height == settings.bip9_bit1_active_checkpoint.height())
×
752
        data.bip9_bit1_hash = data.hash;
×
753

754
    // Cache hash of bip9 bit2 height block, otherwise use preceding state.
755
    if (data.height == settings.bip9_bit2_active_checkpoint.height())
×
756
        data.bip9_bit2_hash = data.hash;
×
757

758
    return data;
×
759
}
760

761
// Parent to header.
762
// This assumes that parent is the state of the header's previous block.
763
chain_state::chain_state(const chain_state& parent, const header& header,
×
764
    const system::settings& settings) NOEXCEPT
×
765
  : data_(to_header(parent, header, settings)),
×
766
    forks_(parent.forks_),
×
767
    activations_(activation(data_, forks_, settings)),
×
768
    work_required_(work_required(data_, forks_, settings)),
×
769
    median_time_past_(median_time_past(data_, forks_))
×
770
{
771
}
×
772

773
// From scratch (e.g. raw data obtained from store).
774
chain_state::chain_state(data&& values,
×
775
    const system::settings& settings) NOEXCEPT
×
776
  : data_(std::move(values)),
×
777
    forks_(settings.forks),
×
778
    activations_(activation(data_, forks_, settings)),
×
779
    work_required_(work_required(data_, forks_, settings)),
×
780
    median_time_past_(median_time_past(data_, forks_))
×
781
{
782
}
×
783

784
// Properties.
785
// ----------------------------------------------------------------------------
786

787
chain::context chain_state::context() const NOEXCEPT
×
788
{
789
    return
×
790
    {
791
        flags(),
792
        timestamp(),
793
        median_time_past(),
794
        possible_narrow_cast<uint32_t>(height()),
795
        minimum_block_version(),
796
        work_required()
797
    };
×
798
}
799

800
const hash_digest& chain_state::hash() const NOEXCEPT
×
801
{
802
    return data_.hash;
×
803
}
804

805
const uint256_t& chain_state::cumulative_work() const NOEXCEPT
×
806
{
807
    return data_.cumulative_work;
×
808
}
809

810
uint32_t chain_state::minimum_block_version() const NOEXCEPT
×
811
{
812
    return activations_.minimum_block_version;
×
813
}
814

815
uint32_t chain_state::work_required() const NOEXCEPT
×
816
{
817
    return work_required_;
×
818
}
819

820
// context
821

822
uint32_t chain_state::timestamp() const NOEXCEPT
×
823
{
824
    return data_.timestamp.self;
×
825
}
826

827
uint32_t chain_state::median_time_past() const NOEXCEPT
×
828
{
829
    return median_time_past_;
×
830
}
831

832
uint32_t chain_state::flags() const NOEXCEPT
×
833
{
834
    return activations_.flags;
×
835
}
836

837
size_t chain_state::height() const NOEXCEPT
×
838
{
839
    return data_.height;
×
840
}
841

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

© 2026 Coveralls, Inc