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

libbitcoin / libbitcoin-system / 15237052663

25 May 2025 10:45AM UTC coverage: 81.177% (-0.08%) from 81.258%
15237052663

push

github

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

Enable taproot/tapscript (bip341/bip342) activation.

21 of 29 new or added lines in 6 files covered. (72.41%)

3 existing lines in 1 file now uncovered.

10402 of 12814 relevant lines covered (81.18%)

3699589.15 hits per line

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

11.04
/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
    // Initialize activation results with genesis values.
110
    activations result{ flags::no_rules, settings.first_version };
×
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
    else
235
    {
236
        result.minimum_block_version = settings.first_version;
237
    }
238

239
    // TODO: bip9 historical activation.
240

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

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

257
    // bip9_bit2 forks are enforced above the bip9_bit2 checkpoint.
NEW
258
    if (values.bip9_bit2_hash == settings.bip9_bit2_active_checkpoint.hash())
×
259
    {
NEW
260
        result.flags |= flags::bip341_rule;
×
NEW
261
        result.flags |= flags::bip342_rule;
×
262
    }
263

264
    // bip30_deactivate fork enforced above bip30_deactivate (bip34) checkpoint.
265
    const auto bip30_deactivate = forks.bip30 && forks.bip30_deactivate &&
×
266
        (values.bip30_deactivate_hash == settings.bip30_deactivate_checkpoint.hash());
×
267

268
    // bip30_reactivate fork is enforced above the bip30_reactivate height.
269
    const auto bip30_reactivate = bip30_deactivate && forks.bip30_reactivate &&
×
270
        (height >= settings.bip30_reactivate_height);
×
271

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

280
    return result;
×
281
}
282

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

290
    // Regtest bypasses all retargeting.
291
    if (!forks.retarget)
×
292
        return one;
293

294
    // Testnet uses mainnet retargeting on interval.
295
    if (is_retarget_height(height, retargeting_interval))
×
296
        return one;
297

298
    // Testnet requires all bits for inter-interval retargeting.
299
    return std::min(height, retargeting_interval);
×
300
}
301

302
size_t chain_state::version_count(size_t height, const forks& forks,
×
303
    size_t bip34_activation_sample) NOEXCEPT
304
{
305
    if (forks.bip90 || (!forks.bip34 && !forks.bip65 && !forks.bip66))
×
306
        return zero;
307

308
    return std::min(height, bip34_activation_sample);
×
309
}
310

311
size_t chain_state::timestamp_count(size_t height, const forks&) NOEXCEPT
×
312
{
313
    return std::min(height, median_time_past_interval);
×
314
}
315

316
size_t chain_state::retarget_height(size_t height, const forks& forks,
×
317
    size_t retargeting_interval) NOEXCEPT
318
{
319
    if (!forks.retarget)
×
320
        return map::unrequested;
321

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

328
// median_time_past
329
// ----------------------------------------------------------------------------
330

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

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

351
// work_required
352
// ----------------------------------------------------------------------------
353

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

361
    // Previous block has an invalid bits value.
362
    if (is_zero(compact::expand(bits_high(values))))
2✔
363
        return 0;
364

365
    // Regtest bypasses all retargeting.
366
    if (!forks.retarget)
2✔
367
        return bits_high(values);
×
368

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

377
    // Testnet retargets easy on inter-interval.
378
    if (!forks.difficult)
×
379
        return easy_work_required(values,
×
380
            settings.retargeting_interval(),
×
381
            settings.proof_of_work_limit,
×
382
            settings.block_spacing_seconds);
×
383

384
    // Mainnet not retargeting, must exact match the previous block bits value.
385
    return bits_high(values);
×
386
}
387

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

400
    //*************************************************************************
401
    // CONSENSUS: Constrain the timespan to the configured consensus limits.
402
    //*************************************************************************
403
    return limit(timespan, minimum_timespan, maximum_timespan);
2✔
404
}
405

406
constexpr bool patch_timewarp(const forks& forks, const uint256_t& limit,
2✔
407
    const uint256_t& target) NOEXCEPT
408
{
409
    return forks.retarget_overflow_patch &&
3✔
410
        floored_log2(target) >= floored_log2(limit);
1✔
411
}
412

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

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

424
    target >>= timewarp;
2✔
425
    target *= retarget_timespan(values, minimum_timespan, maximum_timespan);
2✔
426
    target /= retargeting_interval_seconds;
2✔
427
    target <<= timewarp;
2✔
428

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

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

444
uint32_t chain_state::easy_work_required(const data& values,
×
445
    size_t retargeting_interval, uint32_t proof_of_work_limit,
446
    uint32_t block_spacing_seconds) NOEXCEPT
447
{
448
    BC_ASSERT(!is_zero(values.height));
×
449

450
    // Overflow allowed here since supported coins would not do so.
451
    const auto easy_spacing_seconds = shift_left(block_spacing_seconds);
×
452

453
    // If the time limit has passed allow a minimum difficulty block.
454
    if (values.timestamp.self > ceilinged_add(timestamp_high(values),
×
455
        easy_spacing_seconds))
456
        return proof_of_work_limit;
457

458
    auto height = values.height;
×
459
    const auto& bits = values.bits.ordered;
×
460

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

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

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

489
    // Require bip30_deactivate hash at heights at/above bip30_deactivate active.
490
    return height < activation_height ? map::unrequested : activation_height;
×
491
}
492

493
// ****************************************************************************
494
// CONSENSUS: Hardcoded with bip90 activated.
495
// ****************************************************************************
UNCOV
496
size_t chain_state::bip9_bit0_height(size_t height,
×
497
    const checkpoint& bip9_bit0_active_checkpoint) NOEXCEPT
498
{
499
    const auto activation_height = bip9_bit0_active_checkpoint.height();
×
500

501
    // Require bip9_bit0 hash at heights at/above bip9_bit0 active.
502
    return height < activation_height ? map::unrequested : activation_height;
×
503
}
504

505
// ****************************************************************************
506
// CONSENSUS: Hardcoded in satoshi client (pull request #????).
507
// ****************************************************************************
UNCOV
508
size_t chain_state::bip9_bit1_height(size_t height,
×
509
    const checkpoint& bip9_bit1_active_checkpoint) NOEXCEPT
510
{
511
    const auto activation_height = bip9_bit1_active_checkpoint.height();
×
512

513
    // Require bip9_bit1 hash at heights at/above bip9_bit1 active.
514
    return height < activation_height ? map::unrequested : activation_height;
×
515
}
516

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

525
    // Require bip9_bit2 hash at heights at/above bip9_bit2 active.
NEW
526
    return height < activation_height ? map::unrequested : activation_height;
×
527
}
528

529
// Public static
530
// ----------------------------------------------------------------------------
531

532
chain_state::map chain_state::get_map(size_t height,
×
533
    const system::settings& settings) NOEXCEPT
534
{
535
    if (is_zero(height))
×
536
        return {};
×
537

538
    const auto& forks = settings.forks;
×
539
    const auto interval = settings.retargeting_interval();
×
540
    map map{};
×
541

542
    // The height bound of the reverse (high to low) retarget search.
543
    map.bits.high = sub1(height);
×
544
    map.bits.count = bits_count(height, forks, interval);
×
545

546
    // The height bound of the median time past function.
547
    map.timestamp.high = sub1(height);
×
548
    map.timestamp.count = timestamp_count(height, forks);
×
549

550
    // The height bound of the version sample for activations.
551
    map.version.high = sub1(height);
×
552
    map.version.count = version_count(height, forks,
×
553
        settings.bip34_activation_sample);
×
554

555
    // The most recent past retarget height.
556
    map.timestamp_retarget = retarget_height(height, forks, interval);
×
557

558
    // The checkpoint at/above which bip30_deactivate rule is enforced.
559
    if (forks.bip30 && forks.bip30_deactivate)
×
560
        map.bip30_deactivate_height = bip30_deactivate_height(height,
×
561
            settings.bip30_deactivate_checkpoint);
×
562

563
    // The checkpoint at/above which bip9_bit0 rules are enforced.
564
    if (forks.bip68 || forks.bip112 || forks.bip113)
×
565
        map.bip9_bit0_height = bip9_bit0_height(height,
×
566
            settings.bip9_bit0_active_checkpoint);
×
567

568
    // The checkpoint at/above which bip9_bit1 rules are enforced.
569
    if (forks.bip141 || forks.bip143 || forks.bip147)
×
570
        map.bip9_bit1_height = bip9_bit1_height(height,
×
571
            settings.bip9_bit1_active_checkpoint);
×
572

573
    return map;
×
574
}
575

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

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

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

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

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

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

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

604
    return settings.first_version;
×
605
}
606

607
// Constructors.
608
// ----------------------------------------------------------------------------
609

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

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

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

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

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

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

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

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

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

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

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

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

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

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

706
    return data;
×
707
}
708

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

721
chain_state::data chain_state::to_header(const chain_state& parent,
×
722
    const header& header, const system::settings& settings) NOEXCEPT
723
{
724
    BC_ASSERT(header.previous_block_hash() == parent.hash());
×
725

726
    // Copy and promote data from presumed parent-height header/block state.
727
    auto data = to_pool(parent, settings);
×
728

729
    // Replace the parent (pool or previous) block state with given state.
730
    // Preserve data.timestamp.retarget promotion.
731
    data.hash = header.hash();
×
732
    data.bits.self = header.bits();
×
733
    data.version.self = header.version();
×
734
    data.timestamp.self = header.timestamp();
×
735
    data.cumulative_work += header.proof();
×
736

737
    // Cache hash of bip30_deactivate block, otherwise use preceding state.
738
    if (data.height == settings.bip30_deactivate_checkpoint.height())
×
739
        data.bip30_deactivate_hash = data.hash;
×
740

741
    // Cache hash of bip9 bit0 height block, otherwise use preceding state.
742
    if (data.height == settings.bip9_bit0_active_checkpoint.height())
×
743
        data.bip9_bit0_hash = data.hash;
×
744

745
    // Cache hash of bip9 bit1 height block, otherwise use preceding state.
746
    if (data.height == settings.bip9_bit1_active_checkpoint.height())
×
747
        data.bip9_bit1_hash = data.hash;
×
748

749
    return data;
×
750
}
751

752
// Parent to header.
753
// This assumes that parent is the state of the header's previous block.
754
chain_state::chain_state(const chain_state& parent, const header& header,
×
755
    const system::settings& settings) NOEXCEPT
×
756
  : data_(to_header(parent, header, settings)),
×
757
    forks_(parent.forks_),
×
758
    activations_(activation(data_, forks_, settings)),
×
759
    work_required_(work_required(data_, forks_, settings)),
×
760
    median_time_past_(median_time_past(data_, forks_))
×
761
{
762
}
×
763

764
// From scratch (e.g. raw data obtained from store).
765
chain_state::chain_state(data&& values,
×
766
    const system::settings& settings) NOEXCEPT
×
767
  : data_(std::move(values)),
×
768
    forks_(settings.forks),
×
769
    activations_(activation(data_, forks_, settings)),
×
770
    work_required_(work_required(data_, forks_, settings)),
×
771
    median_time_past_(median_time_past(data_, forks_))
×
772
{
773
}
×
774

775
// Properties.
776
// ----------------------------------------------------------------------------
777

778
chain::context chain_state::context() const NOEXCEPT
×
779
{
780
    return
×
781
    {
782
        flags(),
783
        timestamp(),
784
        median_time_past(),
785
        possible_narrow_cast<uint32_t>(height()),
786
        minimum_block_version(),
787
        work_required()
788
    };
×
789
}
790

791
const hash_digest& chain_state::hash() const NOEXCEPT
×
792
{
793
    return data_.hash;
×
794
}
795

796
const uint256_t& chain_state::cumulative_work() const NOEXCEPT
×
797
{
798
    return data_.cumulative_work;
×
799
}
800

801
uint32_t chain_state::minimum_block_version() const NOEXCEPT
×
802
{
803
    return activations_.minimum_block_version;
×
804
}
805

806
uint32_t chain_state::work_required() const NOEXCEPT
×
807
{
808
    return work_required_;
×
809
}
810

811
// context
812

813
uint32_t chain_state::timestamp() const NOEXCEPT
×
814
{
815
    return data_.timestamp.self;
×
816
}
817

818
uint32_t chain_state::median_time_past() const NOEXCEPT
×
819
{
820
    return median_time_past_;
×
821
}
822

823
uint32_t chain_state::flags() const NOEXCEPT
×
824
{
825
    return activations_.flags;
×
826
}
827

828
size_t chain_state::height() const NOEXCEPT
×
829
{
830
    return data_.height;
×
831
}
832

833
} // namespace chain
834
} // namespace system
835
} // 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