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

libbitcoin / libbitcoin-system / 13069453084

31 Jan 2025 08:55AM UTC coverage: 82.728% (-0.007%) from 82.735%
13069453084

push

github

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

Set _CRTDBG_MAP_ALLOC for vc++ debug mode leak tracking.

2 of 2 new or added lines in 1 file covered. (100.0%)

15 existing lines in 11 files now uncovered.

10039 of 12135 relevant lines covered (82.73%)

3871639.49 hits per line

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

11.22
/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
    // bip30_deactivate fork enforced above bip30_deactivate (bip34) checkpoint.
258
    const auto bip30_deactivate = forks.bip30 && forks.bip30_deactivate &&
×
259
        (values.bip30_deactivate_hash == settings.bip30_deactivate_checkpoint.hash());
×
260

261
    // bip30_reactivate fork is enforced above the bip30_reactivate height.
262
    const auto bip30_reactivate = bip30_deactivate && forks.bip30_reactivate &&
×
263
        (height >= settings.bip30_reactivate_height);
×
264

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

273
    return result;
×
274
}
275

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

283
    // Regtest bypasses all retargeting.
284
    if (!forks.retarget)
×
285
        return one;
286

287
    // Testnet uses mainnet retargeting on interval.
288
    if (is_retarget_height(height, retargeting_interval))
×
289
        return one;
290

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

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

301
    return std::min(height, bip34_activation_sample);
×
302
}
303

304
size_t chain_state::timestamp_count(size_t height, const forks&) NOEXCEPT
×
305
{
306
    return std::min(height, median_time_past_interval);
×
307
}
308

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

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

321
// median_time_past
322
// ----------------------------------------------------------------------------
323

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

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

344
// work_required
345
// ----------------------------------------------------------------------------
346

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

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

358
    // Regtest bypasses all retargeting.
359
    if (!forks.retarget)
2✔
360
        return bits_high(values);
×
361

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

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

377
    // Mainnet not retargeting, must exact match the previous block bits value.
378
    return bits_high(values);
×
379
}
380

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

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

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

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

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

417
    target >>= timewarp;
2✔
418
    target *= retarget_timespan(values, minimum_timespan, maximum_timespan);
2✔
419
    target /= retargeting_interval_seconds;
2✔
420
    target <<= timewarp;
2✔
421

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

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

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

443
    // Overflow allowed here since supported coins would not do so.
444
    const auto easy_spacing_seconds = shift_left(block_spacing_seconds);
×
445

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

451
    auto height = values.height;
×
452
    const auto& bits = values.bits.ordered;
×
453

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

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

468
size_t chain_state::bip30_deactivate_height(size_t height,
×
469
    const checkpoint& bip30_deactivate_checkpoint) NOEXCEPT
470
{
471
    const auto activation_height = bip30_deactivate_checkpoint.height();
×
472

473
    // Require bip30_deactivate hash at heights at/above bip30_deactivate active.
474
    return height < activation_height ? map::unrequested : activation_height;
×
475
}
476

477
size_t chain_state::bip9_bit0_height(size_t height,
×
478
    const checkpoint& bip9_bit0_active_checkpoint) NOEXCEPT
479
{
480
    const auto activation_height = bip9_bit0_active_checkpoint.height();
×
481

482
    // Require bip9_bit0 hash at heights at/above bip9_bit0 active.
483
    return height < activation_height ? map::unrequested : activation_height;
×
484
}
485

486
size_t chain_state::bip9_bit1_height(size_t height,
×
487
    const checkpoint& bip9_bit1_active_checkpoint) NOEXCEPT
488
{
489
    const auto activation_height = bip9_bit1_active_checkpoint.height();
×
490

491
    // Require bip9_bit1 hash at heights at/above bip9_bit1 active.
492
    return height < activation_height ? map::unrequested : activation_height;
×
493
}
494

495
// Public static
496
// ----------------------------------------------------------------------------
497

498
chain_state::map chain_state::get_map(size_t height,
×
499
    const system::settings& settings) NOEXCEPT
500
{
501
    if (is_zero(height))
×
502
        return {};
×
503

504
    const auto& forks = settings.forks;
×
505
    const auto interval = settings.retargeting_interval();
×
506
    map map{};
×
507

508
    // The height bound of the reverse (high to low) retarget search.
509
    map.bits.high = sub1(height);
×
510
    map.bits.count = bits_count(height, forks, interval);
×
511

512
    // The height bound of the median time past function.
513
    map.timestamp.high = sub1(height);
×
514
    map.timestamp.count = timestamp_count(height, forks);
×
515

516
    // The height bound of the version sample for activations.
517
    map.version.high = sub1(height);
×
518
    map.version.count = version_count(height, forks,
×
519
        settings.bip34_activation_sample);
×
520

521
    // The most recent past retarget height.
522
    map.timestamp_retarget = retarget_height(height, forks, interval);
×
523

524
    // The checkpoint at/above which bip30_deactivate rule is enforced.
525
    if (forks.bip30 && forks.bip30_deactivate)
×
526
        map.bip30_deactivate_height = bip30_deactivate_height(height,
×
527
            settings.bip30_deactivate_checkpoint);
×
528

529
    // The checkpoint at/above which bip9_bit0 rules are enforced.
530
    if (forks.bip68 || forks.bip112 || forks.bip113)
×
531
        map.bip9_bit0_height = bip9_bit0_height(height,
×
532
            settings.bip9_bit0_active_checkpoint);
×
533

534
    // The checkpoint at/above which bip9_bit1 rules are enforced.
535
    if (forks.bip141 || forks.bip143 || forks.bip147)
×
536
        map.bip9_bit1_height = bip9_bit1_height(height,
×
537
            settings.bip9_bit1_active_checkpoint);
×
538

539
    return map;
×
540
}
541

542
uint32_t chain_state::signal_version(const system::settings& settings) NOEXCEPT
×
543
{
544
    const auto& forks = settings.forks;
×
545

546
    // TODO: these can be retired.
547
    // Signal bip9 bit1 if any of the group is configured.
548
    if (forks.bip141 || forks.bip143 || forks.bip147)
×
549
        return settings.bip9_version_base | settings.bip9_version_bit1;
×
550

551
    // TODO: these can be retired.
552
    // Signal bip9 bit0 if any of the group is configured.
553
    if (forks.bip68 || forks.bip112 || forks.bip113)
×
554
        return settings.bip9_version_base | settings.bip9_version_bit0;
×
555

556
    if (forks.bip65)
×
557
        return settings.bip65_version;
×
558

559
    if (forks.bip66)
×
560
        return settings.bip66_version;
×
561

562
    if (forks.bip34)
×
563
        return settings.bip34_version;
×
564

565
    return settings.first_version;
×
566
}
567

568
// Constructors.
569
// ----------------------------------------------------------------------------
570

571
// This is promotion from a preceding height to the next.
572
chain_state::data chain_state::to_pool(const chain_state& top,
×
573
    const system::settings& settings) NOEXCEPT
574
{
575
    // Alias configured forks.
576
    const auto& forks = top.forks_;
×
577

578
    // Copy data from presumed previous-height block state.
579
    chain_state::data data{ top.data_ };
×
580

581
    // If this overflows height is zero and result is handled as invalid.
582
    const auto height = add1(data.height);
×
583
    
584
    // Enqueue previous block values to collections.
585
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
586
    data.bits.ordered.push_back(data.bits.self);
×
587
    data.version.ordered.push_back(data.version.self);
×
588
    data.timestamp.ordered.push_back(data.timestamp.self);
×
589
    BC_POP_WARNING()
590

591
    // If bits collection overflows, dequeue oldest member.
592
    if (data.bits.ordered.size() >
×
593
        bits_count(height, forks, settings.retargeting_interval()))
×
594
        data.bits.ordered.pop_front();
×
595

596
    // If version collection overflows, dequeue oldest member.
597
    if (data.version.ordered.size() > version_count(height, forks,
×
598
        settings.bip34_activation_sample))
×
599
        data.version.ordered.pop_front();
×
600

601
    // If timestamp collection overflows, dequeue oldest member.
602
    if (data.timestamp.ordered.size() > timestamp_count(height, forks))
×
603
        data.timestamp.ordered.pop_front();
×
604

605
    // Regtest does not perform retargeting.
606
    // If promoting from retarget height, move that timestamp into retarget.
607
    if (forks.retarget && is_retarget_height(sub1(height),
×
608
        settings.retargeting_interval()))
×
609
    {
610
        // Conditionally patch time warp bug (e.g. Litecoin).
611
        data.timestamp.retarget = (forks.time_warp_patch && height != one) ?
×
612
            *std::next(data.timestamp.ordered.crbegin()) : data.timestamp.self;
×
613
    }
614

615
    // Replace previous block state with tx pool chain state for next height
616
    // Preserve top block timestamp for use in computation of staleness.
617
    // Preserve data.bip30_deactivate_hash promotion.
618
    // Preserve data.bip9_bit0_hash promotion.
619
    // Preserve data.bip9_bit1_hash promotion.
620
    // bits.self is unused.
621
    data.height = height;
×
622
    data.hash = {};
×
623
    data.bits.self = 0;
×
624
    data.version.self = signal_version(settings);
×
625
    return data;
×
UNCOV
626
}
×
627

628
// Top to pool.
629
// This generates a state for the pool above the presumed top block state.
630
chain_state::chain_state(const chain_state& top,
×
631
    const system::settings& settings) NOEXCEPT
×
632
  : data_(to_pool(top, settings)),
×
633
    forks_(top.forks_),
×
634
    activations_(activation(data_, forks_, settings)),
×
635
    work_required_(work_required(data_, forks_, settings)),
×
636
    median_time_past_(median_time_past(data_, forks_))
×
637
{
638
}
×
639

640
chain_state::data chain_state::to_block(const chain_state& pool,
×
641
    const block& block, const system::settings& settings) NOEXCEPT
642
{
643
    // Copy data from presumed same-height pool state.
644
    chain_state::data data{ pool.data_ };
×
645

646
    // Replace pool chain state with block state at same (next) height.
647
    // Preserve data.timestamp.retarget promotion.
648
    const auto& header = block.header();
×
649
    data.hash = {};
×
650
    data.bits.self = header.bits();
×
651
    data.version.self = header.version();
×
652
    data.timestamp.self = header.timestamp();
×
653
    data.cumulative_work += header.proof();
×
654

655
    // Cache hash of bip30_deactivate block, otherwise use preceding state.
656
    if (data.height == settings.bip30_deactivate_checkpoint.height())
×
657
        data.bip30_deactivate_hash = data.hash;
×
658

659
    // Cache hash of bip9 bit0 height block, otherwise use preceding state.
660
    if (data.height == settings.bip9_bit0_active_checkpoint.height())
×
661
        data.bip9_bit0_hash = data.hash;
×
662

663
    // Cache hash of bip9 bit1 height block, otherwise use preceding state.
664
    if (data.height == settings.bip9_bit1_active_checkpoint.height())
×
665
        data.bip9_bit1_hash = data.hash;
×
666

667
    return data;
×
UNCOV
668
}
×
669

670
// Pool to block.
671
// This assumes that the pool state is the same height as the block.
672
chain_state::chain_state(const chain_state& pool, const block& block,
×
673
    const system::settings& settings) NOEXCEPT
×
674
  : data_(to_block(pool, block, settings)),
×
675
    forks_(pool.forks_),
×
676
    activations_(activation(data_, forks_, settings)),
×
677
    work_required_(work_required(data_, forks_, settings)),
×
678
    median_time_past_(median_time_past(data_, forks_))
×
679
{
680
}
×
681

682
chain_state::data chain_state::to_header(const chain_state& parent,
×
683
    const header& header, const system::settings& settings) NOEXCEPT
684
{
685
    BC_ASSERT(header.previous_block_hash() == parent.hash());
×
686

687
    // Copy and promote data from presumed parent-height header/block state.
688
    auto data = to_pool(parent, settings);
×
689

690
    // Replace the parent (pool or previous) block state with given state.
691
    // Preserve data.timestamp.retarget promotion.
692
    data.hash = header.hash();
×
693
    data.bits.self = header.bits();
×
694
    data.version.self = header.version();
×
695
    data.timestamp.self = header.timestamp();
×
696
    data.cumulative_work += header.proof();
×
697

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

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

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

710
    return data;
×
UNCOV
711
}
×
712

713
// Parent to header.
714
// This assumes that parent is the state of the header's previous block.
715
chain_state::chain_state(const chain_state& parent, const header& header,
×
716
    const system::settings& settings) NOEXCEPT
×
717
  : data_(to_header(parent, header, settings)),
×
718
    forks_(parent.forks_),
×
719
    activations_(activation(data_, forks_, settings)),
×
720
    work_required_(work_required(data_, forks_, settings)),
×
721
    median_time_past_(median_time_past(data_, forks_))
×
722
{
723
}
×
724

725
// From scratch (e.g. raw data obtained from store).
726
chain_state::chain_state(data&& values,
×
727
    const system::settings& settings) NOEXCEPT
×
728
  : data_(std::move(values)),
×
729
    forks_(settings.forks),
×
730
    activations_(activation(data_, forks_, settings)),
×
731
    work_required_(work_required(data_, forks_, settings)),
×
732
    median_time_past_(median_time_past(data_, forks_))
×
733
{
734
}
×
735

736
// Properties.
737
// ----------------------------------------------------------------------------
738

739
chain::context chain_state::context() const NOEXCEPT
×
740
{
741
    return
×
742
    {
743
        flags(),
744
        timestamp(),
745
        median_time_past(),
746
        possible_narrow_cast<uint32_t>(height()),
747
        minimum_block_version(),
748
        work_required()
749
    };
×
750
}
751

752
const hash_digest& chain_state::hash() const NOEXCEPT
×
753
{
754
    return data_.hash;
×
755
}
756

757
const uint256_t& chain_state::cumulative_work() const NOEXCEPT
×
758
{
759
    return data_.cumulative_work;
×
760
}
761

762
uint32_t chain_state::minimum_block_version() const NOEXCEPT
×
763
{
764
    return activations_.minimum_block_version;
×
765
}
766

767
uint32_t chain_state::work_required() const NOEXCEPT
×
768
{
769
    return work_required_;
×
770
}
771

772
// context
773

774
uint32_t chain_state::timestamp() const NOEXCEPT
×
775
{
776
    return data_.timestamp.self;
×
777
}
778

779
uint32_t chain_state::median_time_past() const NOEXCEPT
×
780
{
781
    return median_time_past_;
×
782
}
783

784
uint32_t chain_state::flags() const NOEXCEPT
×
785
{
786
    return activations_.flags;
×
787
}
788

789
size_t chain_state::height() const NOEXCEPT
×
790
{
791
    return data_.height;
×
792
}
793

794
} // namespace chain
795
} // namespace system
796
} // 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