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

libbitcoin / libbitcoin-system / 8240232113

11 Mar 2024 09:57PM UTC coverage: 82.677%. Remained the same
8240232113

push

github

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

Comments.

9641 of 11661 relevant lines covered (82.68%)

4891762.23 hits per line

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

12.59
/src/chain/chain_state.cpp
1
/**
2
 * Copyright (c) 2011-2023 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 <bitcoin/system/chain/block.hpp>
25
#include <bitcoin/system/chain/chain_state.hpp>
26
#include <bitcoin/system/chain/checkpoint.hpp>
27
#include <bitcoin/system/chain/compact.hpp>
28
#include <bitcoin/system/chain/context.hpp>
29
#include <bitcoin/system/chain/enums/forks.hpp>
30
#include <bitcoin/system/chain/enums/policy.hpp>
31
#include <bitcoin/system/chain/script.hpp>
32
#include <bitcoin/system/data/data.hpp>
33
#include <bitcoin/system/hash/hash.hpp>
34
#include <bitcoin/system/math/math.hpp>
35
#include <bitcoin/system/settings.hpp>
36

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

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

52
// Inlines.
53
// ----------------------------------------------------------------------------
54

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

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

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

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

79
// bip30 is active for all but two mainnet blocks that violate the rule.
80
// These two blocks each have a coinbase transaction that exactly duplicates
81
// another that is not spent by the arrival of the corresponding duplicate.
82
// No need to check the configuration for mainnet (hashes presumed unique).
83
inline bool is_bip30_exception(const checkpoint& check) NOEXCEPT
×
84
{
85
    return (check == mainnet_bip30_exception_checkpoint1) ||
×
86
         (check == mainnet_bip30_exception_checkpoint2);
×
87
}
88

89
inline uint32_t timestamp_high(const chain_state::data& values) NOEXCEPT
2✔
90
{
91
    return values.timestamp.ordered.back();
2✔
92
}
93

94
inline uint32_t bits_high(const chain_state::data& values) NOEXCEPT
4✔
95
{
96
    return values.bits.ordered.back();
4✔
97
}
98

99
// activation
100
// ----------------------------------------------------------------------------
101

102
chain_state::activations chain_state::activation(const data& values,
×
103
    uint32_t forks, const system::settings& settings) NOEXCEPT
104
{
105
    const auto height = values.height;
×
106
    const auto version = values.version.self;
×
107
    const auto& history = values.version.ordered;
×
108
    const auto bip90 = script::is_enabled(forks, forks::bip90_rule);
×
109

110
    //*************************************************************************
111
    // CONSENSUS: Though unspecified in bip34, the satoshi implementation
112
    // performed this comparison using the signed integer version value.
113
    //*************************************************************************
114
    constexpr auto ge = [](uint32_t value, uint32_t version) NOEXCEPT
×
115
    {
116
        return sign_cast<int32_t>(value) >= sign_cast<int32_t>(version);
×
117
    };
118

119
    // Declare bip34-based version predicates.
120
    const auto ge_2 = [&](uint32_t value) NOEXCEPT { return ge(value,
×
121
        settings.bip34_version); };
×
122
    const auto ge_3 = [&](uint32_t value) NOEXCEPT { return ge(value,
×
123
        settings.bip66_version); };
×
124
    const auto ge_4 = [&](uint32_t value) NOEXCEPT { return ge(value,
×
125
        settings.bip65_version); };
×
126

127
    // Compute bip34-based activation version summaries (empty if disabled).
128
    const auto count_2 = std::count_if(history.begin(), history.end(), ge_2);
×
129
    const auto count_3 = std::count_if(history.begin(), history.end(), ge_3);
×
130
    const auto count_4 = std::count_if(history.begin(), history.end(), ge_4);
×
131

132
    // Frozen activations (require version and enforce above freeze height).
133
    const auto bip90_34 = bip90 && height >= settings.bip34_freeze;
×
134
    const auto bip90_66 = bip90 && height >= settings.bip66_freeze;
×
135
    const auto bip90_65 = bip90 && height >= settings.bip65_freeze;
×
136

137
    // Initialize activation results with genesis values.
138
    activations result{ forks::no_rules, settings.first_version };
×
139

140
    // regtest is only activated via configuration (hard fork).
141
    result.forks |= (forks::retarget & forks);
×
142

143
    // testnet is activated based on configuration alone (hard fork).
144
    result.forks |= (forks::difficult & forks);
×
145

146
    // bip42 is activated based on configuration alone (soft fork).
147
    result.forks |= (forks::bip42_rule & forks);
×
148

149
    // bip90 is activated based on configuration alone (hard fork).
150
    result.forks |= (forks::bip90_rule & forks);
×
151

152
    // time_warp_patch is activated based on configuration alone (hard fork).
153
    result.forks |= (forks::time_warp_patch & forks);
×
154

155
    // retarget_overflow_patch is activated based on configuration alone (hard fork).
156
    result.forks |= (forks::retarget_overflow_patch & forks);
×
157

158
    // scrypt_proof_of_work is activated based on configuration alone (hard fork).
159
    result.forks |= (forks::scrypt_proof_of_work & forks);
×
160

161
    // bip16 was activated based on manual inspection of signal history (soft fork).
162
    if (values.timestamp.self >= settings.bip16_activation_time)
×
163
    {
164
        result.forks |= (forks::bip16_rule & forks);
×
165
    }
166

167
    // bip34 activations oscillate until enforced by minimum_block_version.
168
    // bip90 does not require that the corresponding rules be defined.
169

170
    // bip34 is active based on 75% of preceding 1000 mainnet blocks.
171
    if (bip90_34 || (is_active(count_2, settings.bip34_activation_threshold) &&
×
172
        version >= settings.bip34_version))
×
173
    {
174
        result.forks |= (forks::bip34_rule & forks);
×
175
    }
176
    // bip30 is disabled by bip34 or unconditional activation of it by bip90.
177
    // Otherwise if not exception, existing duplicate coinbase must be spent.
178
    else if (!is_bip30_exception({ values.hash, height }))
×
179
    {
180
        result.forks |= (forks::bip30_rule & forks);
×
181
    }
182

183
    // bip66 is active based on 75% of preceding 1000 mainnet blocks.
184
    if (bip90_66 || (is_active(count_3, settings.bip34_activation_threshold) &&
×
185
        version >= settings.bip66_version))
×
186
    {
187
        result.forks |= (forks::bip66_rule & forks);
×
188
    }
189

190
    // bip65 is active based on 75% of preceding 1000 mainnet blocks.
191
    if (bip90_65 || (is_active(count_4, settings.bip34_activation_threshold) &&
×
192
        version >= settings.bip65_version))
×
193
    {
194
        result.forks |= (forks::bip65_rule & forks);
×
195
    }
196

197
    // version 4/3/2 enforced based on 95% of preceding 1000 mainnet blocks.
198
    if (bip90_65 || is_enforced(count_4, settings.bip34_enforcement_threshold))
×
199
    {
200
        result.minimum_block_version = settings.bip65_version;
×
201
    }
202
    else if (bip90_66 || is_enforced(count_3, settings.bip34_enforcement_threshold))
×
203
    {
204
        result.minimum_block_version = settings.bip66_version;
×
205
    }
206
    else if (bip90_34 || is_enforced(count_2, settings.bip34_enforcement_threshold))
×
207
    {
208
        result.minimum_block_version = settings.bip34_version;
×
209
    }
210
    else
211
    {
212
        result.minimum_block_version = settings.first_version;
×
213
    }
214

215
    // TODO: bip9 historical activation.
216

217
    // bip9_bit0 forks are enforced above the bip9_bit0 checkpoint.
218
    if (values.bip9_bit0_hash == settings.bip9_bit0_active_checkpoint.hash())
×
219
    {
220
        result.forks |= (forks::bip9_bit0_group & forks);
×
221
    }
222

223
    // bip9_bit1 forks are enforced above the bip9_bit1 checkpoint.
224
    if (values.bip9_bit1_hash == settings.bip9_bit1_active_checkpoint.hash())
×
225
    {
226
        result.forks |= (forks::bip9_bit1_group & forks);
×
227
    }
228

229
    return result;
×
230
}
231

232
size_t chain_state::bits_count(size_t height, uint32_t forks,
×
233
    size_t retargeting_interval) NOEXCEPT
234
{
235
    // Mainnet doesn't use bits in retargeting.
236
    if (script::is_enabled(forks, forks::difficult))
×
237
        return one;
238

239
    // Regtest bypasses all retargeting.
240
    if (!script::is_enabled(forks, forks::retarget))
×
241
        return one;
242

243
    // Testnet uses mainnet retargeting on interval.
244
    if (is_retarget_height(height, retargeting_interval))
×
245
        return one;
246

247
    // Testnet requires all bits for inter-interval retargeting.
248
    return std::min(height, retargeting_interval);
×
249
}
250

251
size_t chain_state::version_count(size_t height, uint32_t forks,
×
252
    size_t bip34_activation_sample) NOEXCEPT
253
{
254
    if (script::is_enabled(forks, forks::bip90_rule) ||
×
255
        !script::is_enabled(forks, forks::bip34_activations))
256
    {
257
        return zero;
258
    }
259

260
    return std::min(height, bip34_activation_sample);
×
261
}
262

263
size_t chain_state::timestamp_count(size_t height, uint32_t) NOEXCEPT
×
264
{
265
    return std::min(height, median_time_past_interval);
×
266
}
267

268
size_t chain_state::retarget_height(size_t height, uint32_t forks,
×
269
    size_t retargeting_interval) NOEXCEPT
270
{
271
    if (!script::is_enabled(forks, forks::retarget))
×
272
        return map::unrequested;
273

274
    // Height must be a positive multiple of interval, so underflow safe.
275
    // If not retarget height get most recent so that it may be promoted.
276
    return height - (is_retarget_height(height, retargeting_interval) ?
×
277
        retargeting_interval : retarget_distance(height, retargeting_interval));
×
278
}
279

280
// median_time_past
281
// ----------------------------------------------------------------------------
282

283
//*****************************************************************************
284
// CONSENSUS: satoshi associates the median time past for block N with block
285
// N-1, as opposed to block N. Given that the value is actually obtained from
286
// yet another preceding block in all cases except block 1 and 2, this is a
287
// curious and confusing convention. We associate the median time past for
288
// block N with block N. This is simple but requires care when comparing code.
289
//*****************************************************************************
290
uint32_t chain_state::median_time_past(const data& values, uint32_t) NOEXCEPT
×
291
{
292
    // Sort the times by value to obtain the median.
293
    auto times = sort_copy(values.timestamp.ordered);
×
294

295
    // Consensus defines median time using modulo 2 element selection.
296
    // This differs from arithmetic median which averages two middle values.
297
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
298
    return times.empty() ? 0 : times.at(to_half(times.size()));
×
299
    BC_POP_WARNING()
300
}
×
301

302
// work_required
303
// ----------------------------------------------------------------------------
304

305
uint32_t chain_state::work_required(const data& values, uint32_t forks,
2✔
306
    const system::settings& settings) NOEXCEPT
307
{
308
    // Genesis has no preceding block data.
309
    if (is_zero(values.height))
2✔
310
        return 0;
311

312
    // Previous block has an invalid bits value.
313
    if (is_zero(compact::expand(bits_high(values))))
2✔
314
        return 0;
315

316
    // Regtest bypasses all retargeting.
317
    if (!script::is_enabled(forks, forks::retarget))
2✔
318
        return bits_high(values);
×
319

320
    // Mainnet and testnet retarget on interval.
321
    if (is_retarget_height(values.height, settings.retargeting_interval()))
2✔
322
        return work_required_retarget(values, forks,
6✔
323
            settings.proof_of_work_limit,
2✔
324
            settings.minimum_timespan(),
2✔
325
            settings.maximum_timespan(),
2✔
326
            settings.retargeting_interval_seconds);
4✔
327

328
    // Testnet retargets easy on inter-interval.
329
    if (!script::is_enabled(forks, forks::difficult))
×
330
        return easy_work_required(values,
×
331
            settings.retargeting_interval(),
×
332
            settings.proof_of_work_limit,
×
333
            settings.block_spacing_seconds);
×
334

335
    // Mainnet not retargeting, must exact match the previous block bits value.
336
    return bits_high(values);
×
337
}
338

339
// Get the bounded total time spanning the highest 2016 blocks.
340
uint32_t chain_state::retarget_timespan(const data& values,
2✔
341
    uint32_t minimum_timespan, uint32_t maximum_timespan) NOEXCEPT
342
{
343
    //*************************************************************************
344
    // CONSENSUS: "Subtract unsigned 32 bit numbers in signed 64 bit space".
345
    // This is done order to prevent underflow before applying the range
346
    // constraint. This is properly just a floored subtraction in 32 bit space.
347
    //*************************************************************************
348
    const auto timespan = floored_subtract(timestamp_high(values),
2✔
349
        values.timestamp.retarget);
2✔
350

351
    //*************************************************************************
352
    // CONSENSUS: Constrain the timespan to the configured consensus limits.
353
    //*************************************************************************
354
    return limit(timespan, minimum_timespan, maximum_timespan);
2✔
355
}
356

357
constexpr bool patch_timewarp(uint32_t forks, const uint256_t& limit,
2✔
358
    const uint256_t& target) NOEXCEPT
359
{
360
    return script::is_enabled(forks, forks::retarget_overflow_patch) &&
3✔
361
        floored_log2(target) >= floored_log2(limit);
1✔
362
}
363

364
uint32_t chain_state::work_required_retarget(const data& values, uint32_t forks,
2✔
365
    uint32_t proof_of_work_limit, uint32_t minimum_timespan,
366
    uint32_t maximum_timespan, uint32_t retargeting_interval_seconds) NOEXCEPT
367
{
368
    static const auto limit = compact::expand(proof_of_work_limit);
2✔
369
    auto target = compact::expand(bits_high(values));
2✔
370

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

374
    target >>= timewarp;
2✔
375
    target *= retarget_timespan(values, minimum_timespan, maximum_timespan);
2✔
376
    target /= retargeting_interval_seconds;
2✔
377
    target <<= timewarp;
2✔
378

379
    // Disallow target from falling below minimum configured.
380
    // All targets are a bits value normalized by compress here.
381
    return target > limit ? proof_of_work_limit : compact::compress(target);
2✔
382
}
383

384
// A retarget height, or a block that does not have proof_of_work_limit bits.
385
constexpr bool is_retarget_or_non_limit(size_t height, uint32_t bits,
×
386
    size_t retargeting_interval, uint32_t proof_of_work_limit) NOEXCEPT
387
{
388
    // Zero is a retarget height, termination required before height underflow.
389
    // This is guaranteed, just a comment here because it may not be obvious.
390
    return bits != proof_of_work_limit ||
×
391
        is_retarget_height(height, retargeting_interval);
392
}
393

394
uint32_t chain_state::easy_work_required(const data& values,
×
395
    size_t retargeting_interval, uint32_t proof_of_work_limit,
396
    uint32_t block_spacing_seconds) NOEXCEPT
397
{
398
    BC_ASSERT(!is_zero(values.height));
×
399

400
    // Overflow allowed here since supported coins would not do so.
401
    const auto easy_spacing_seconds = shift_left(block_spacing_seconds);
×
402

403
    // If the time limit has passed allow a minimum difficulty block.
404
    if (values.timestamp.self > ceilinged_add(timestamp_high(values),
×
405
        easy_spacing_seconds))
406
        return proof_of_work_limit;
407

408
    auto height = values.height;
×
409
    const auto& bits = values.bits.ordered;
×
410

411
    // Reverse iterate the ordered-by-height list of header bits.
412
    for (auto bit: views_reverse(bits))
×
413
    {
414
        if (is_retarget_or_non_limit(--height, bit, retargeting_interval,
×
415
            proof_of_work_limit))
416
            return bit;
×
417
    }
418

419
    // Since the set of heights is either a full retarget range or ends at
420
    // zero this is not reachable unless the data set is invalid.
421
    BC_ASSERT(false);
×
422
    return proof_of_work_limit;
×
423
}
424

425
size_t chain_state::bip9_bit0_height(size_t height,
×
426
    const checkpoint& bip9_bit0_active_checkpoint) NOEXCEPT
427
{
428
    const auto activation_height = bip9_bit0_active_checkpoint.height();
×
429

430
    // Require bip9_bit0 hash at heights above historical bip9_bit0 activation.
431
    return height > activation_height ? activation_height : map::unrequested;
×
432
}
433

434
size_t chain_state::bip9_bit1_height(size_t height,
×
435
    const checkpoint& bip9_bit1_active_checkpoint) NOEXCEPT
436
{
437
    const auto activation_height = bip9_bit1_active_checkpoint.height();
×
438

439
    // Require bip9_bit1 hash at heights above historical bip9_bit1 activation.
440
    return height > activation_height ? activation_height : map::unrequested;
×
441
}
442

443
// Public static
444
// ----------------------------------------------------------------------------
445

446
chain_state::map chain_state::get_map(size_t height,
×
447
    const system::settings& settings) NOEXCEPT
448
{
449
    if (is_zero(height))
×
450
        return {};
×
451

452
    const auto forks = settings.enabled_forks();
×
453
    const auto interval = settings.retargeting_interval();
×
454
    map map{};
×
455

456
    // The height bound of the reverse (high to low) retarget search.
457
    map.bits_self = height;
×
458
    map.bits.high = sub1(height);
×
459
    map.bits.count = bits_count(height, forks, interval);
×
460

461
    // The height bound of the median time past function.
462
    map.timestamp_self = height;
×
463
    map.timestamp.high = sub1(height);
×
464
    map.timestamp.count = timestamp_count(height, forks);
×
465

466
    // The height bound of the version sample for activations.
467
    map.version_self = height;
×
468
    map.version.high = sub1(height);
×
469
    map.version.count = version_count(height, forks,
×
470
        settings.bip34_activation_sample);
×
471

472
    // The most recent past retarget height.
473
    map.timestamp_retarget = retarget_height(height, forks, interval);
×
474

475
    // The checkpoint above which bip9_bit0 rules are enforced.
476
    map.bip9_bit0_height = bip9_bit0_height(height,
×
477
        settings.bip9_bit0_active_checkpoint);
×
478

479
    // The checkpoint above which bip9_bit1 rules are enforced.
480
    map.bip9_bit1_height = bip9_bit1_height(height,
×
481
        settings.bip9_bit1_active_checkpoint);
×
482

483
    return map;
×
484
}
485

486
uint32_t chain_state::signal_version(uint32_t forks,
×
487
    const system::settings& settings) NOEXCEPT
488
{
489
    if (script::is_enabled(forks, forks::bip65_rule))
×
490
        return settings.bip65_version;
×
491

492
    if (script::is_enabled(forks, forks::bip66_rule))
×
493
        return settings.bip66_version;
×
494

495
    if (script::is_enabled(forks, forks::bip34_rule))
×
496
        return settings.bip34_version;
×
497

498
    // TODO: these can be retired.
499
    // Signal bip9 bit0 if any of the group is configured.
500
    if (script::is_enabled(forks, forks::bip9_bit0_group))
×
501
        return settings.bip9_version_base | settings.bip9_version_bit0;
×
502

503
    // TODO: these can be retired.
504
    // Signal bip9 bit1 if any of the group is configured.
505
    if (script::is_enabled(forks, forks::bip9_bit1_group))
×
506
        return settings.bip9_version_base | settings.bip9_version_bit1;
×
507

508
    return settings.first_version;
×
509
}
510

511
// Constructors.
512
// ----------------------------------------------------------------------------
513

514
// This is promotion from a preceding height to the next.
515
chain_state::data chain_state::to_pool(const chain_state& top,
×
516
    const system::settings& settings) NOEXCEPT
517
{
518
    // Alias configured forks.
519
    const auto forks = top.forks_;
×
520

521
    // Retargeting is only activated via configuration.
522
    const auto retarget = script::is_enabled(forks, forks::retarget);
×
523

524
    // Copy data from presumed previous-height block state.
525
    chain_state::data data{ top.data_ };
×
526

527
    // If this overflows height is zero and result is handled as invalid.
528
    const auto height = add1(data.height);
×
529
    
530
    // Enqueue previous block values to collections.
531
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
532
    data.bits.ordered.push_back(data.bits.self);
×
533
    data.version.ordered.push_back(data.version.self);
×
534
    data.timestamp.ordered.push_back(data.timestamp.self);
×
535
    BC_POP_WARNING()
536

537
    // If bits collection overflows, dequeue oldest member.
538
    if (data.bits.ordered.size() >
×
539
        bits_count(height, forks, settings.retargeting_interval()))
×
540
        data.bits.ordered.pop_front();
×
541

542
    // If version collection overflows, dequeue oldest member.
543
    if (data.version.ordered.size() > version_count(height, forks,
×
544
        settings.bip34_activation_sample))
×
545
        data.version.ordered.pop_front();
×
546

547
    // If timestamp collection overflows, dequeue oldest member.
548
    if (data.timestamp.ordered.size() > timestamp_count(height, forks))
×
549
        data.timestamp.ordered.pop_front();
×
550

551

552
    // Regtest does not perform retargeting.
553
    // If promoting from retarget height, move that timestamp into retarget.
554
    if (retarget && is_retarget_height(sub1(height),
×
555
        settings.retargeting_interval()))
×
556
    {
557
        // Conditionally patch time warp bug (e.g. Litecoin).
558
        const auto patch = script::is_enabled(forks, forks::time_warp_patch);
×
559

560
        data.timestamp.retarget = (patch && height != one) ?
×
561
            *std::next(data.timestamp.ordered.crbegin()) : data.timestamp.self;
×
562
    }
563

564
    // Replace previous block state with tx pool chain state for next height
565
    // Preserve top block timestamp for use in computation of staleness.
566
    // Preserve data.bip9_bit0_hash promotion.
567
    // Preserve data.bip9_bit1_hash promotion.
568
    // bits.self is unused.
569
    data.height = height;
×
570
    data.hash = {};
×
571
    data.bits.self = 0;
×
572
    data.version.self = signal_version(forks, settings);
×
573
    return data;
×
574
}
575

576
// Top to pool.
577
// This generates a state for the pool above the presumed top block state.
578
chain_state::chain_state(const chain_state& top,
×
579
    const system::settings& settings) NOEXCEPT
×
580
  : data_(to_pool(top, settings)),
×
581
    forks_(top.forks_),
×
582
    active_(activation(data_, forks_, settings)),
×
583
    work_required_(work_required(data_, forks_, settings)),
×
584
    median_time_past_(median_time_past(data_, forks_))
×
585
{
586
}
×
587

588
chain_state::data chain_state::to_block(const chain_state& pool,
×
589
    const block& block, const system::settings& settings) NOEXCEPT
590
{
591
    // Copy data from presumed same-height pool state.
592
    chain_state::data data{ pool.data_ };
×
593

594
    // Replace pool chain state with block state at same (next) height.
595
    // Preserve data.timestamp.retarget promotion.
596
    const auto& header = block.header();
×
597
    data.hash = {};
×
598
    data.bits.self = header.bits();
×
599
    data.version.self = header.version();
×
600
    data.timestamp.self = header.timestamp();
×
601
    data.cumulative_work += header.proof();
×
602

603
    // Cache hash of bip9 bit0 height block, otherwise use preceding state.
604
    if (data.height == settings.bip9_bit0_active_checkpoint.height())
×
605
        data.bip9_bit0_hash = data.hash;
×
606

607
    // Cache hash of bip9 bit1 height block, otherwise use preceding state.
608
    if (data.height == settings.bip9_bit1_active_checkpoint.height())
×
609
        data.bip9_bit1_hash = data.hash;
×
610

611
    return data;
×
612
}
613

614
// Pool to block.
615
// This assumes that the pool state is the same height as the block.
616
chain_state::chain_state(const chain_state& pool, const block& block,
×
617
    const system::settings& settings) NOEXCEPT
×
618
  : data_(to_block(pool, block, settings)),
×
619
    forks_(pool.forks_),
×
620
    active_(activation(data_, forks_, settings)),
×
621
    work_required_(work_required(data_, forks_, settings)),
×
622
    median_time_past_(median_time_past(data_, forks_))
×
623
{
624
}
×
625

626
chain_state::data chain_state::to_header(const chain_state& parent,
×
627
    const header& header, const system::settings& settings) NOEXCEPT
628
{
629
    BC_ASSERT(header.previous_block_hash() == parent.hash());
×
630

631
    // Copy and promote data from presumed parent-height header/block state.
632
    auto data = to_pool(parent, settings);
×
633

634
    // Replace the parent (pool or previous) block state with given state.
635
    // Preserve data.timestamp.retarget promotion.
636
    data.hash = header.hash();
×
637
    data.bits.self = header.bits();
×
638
    data.version.self = header.version();
×
639
    data.timestamp.self = header.timestamp();
×
640
    data.cumulative_work += header.proof();
×
641

642
    // Cache hash of bip9 bit0 height block, otherwise use preceding state.
643
    if (data.height == settings.bip9_bit0_active_checkpoint.height())
×
644
        data.bip9_bit0_hash = data.hash;
×
645

646
    // Cache hash of bip9 bit1 height block, otherwise use preceding state.
647
    if (data.height == settings.bip9_bit1_active_checkpoint.height())
×
648
        data.bip9_bit1_hash = data.hash;
×
649

650
    return data;
×
651
}
652

653
// Parent to header.
654
// This assumes that parent is the state of the header's previous block.
655
chain_state::chain_state(const chain_state& parent, const header& header,
×
656
    const system::settings& settings) NOEXCEPT
×
657
  : data_(to_header(parent, header, settings)),
×
658
    forks_(parent.forks_),
×
659
    active_(activation(data_, forks_, settings)),
×
660
    work_required_(work_required(data_, forks_, settings)),
×
661
    median_time_past_(median_time_past(data_, forks_))
×
662
{
663
}
×
664

665
// From scratch (e.g. raw data obtained from store).
666
chain_state::chain_state(data&& values,
×
667
    const system::settings& settings) NOEXCEPT
×
668
  : data_(std::move(values)),
×
669
    forks_(settings.enabled_forks()),
×
670
    active_(activation(data_, forks_, settings)),
×
671
    work_required_(work_required(data_, forks_, settings)),
×
672
    median_time_past_(median_time_past(data_, forks_))
×
673
{
674
}
×
675

676
// Properties.
677
// ----------------------------------------------------------------------------
678

679
chain::context chain_state::context() const NOEXCEPT
×
680
{
681
    return
×
682
    {
683
        forks(),
684
        timestamp(),
685
        median_time_past(),
686
        possible_narrow_cast<uint32_t>(height()),
687
        minimum_block_version(),
688
        work_required()
689
    };
×
690
}
691

692
const hash_digest& chain_state::hash() const NOEXCEPT
×
693
{
694
    return data_.hash;
×
695
}
696

697
const uint256_t& chain_state::cumulative_work() const NOEXCEPT
×
698
{
699
    return data_.cumulative_work;
×
700
}
701

702
uint32_t chain_state::minimum_block_version() const NOEXCEPT
×
703
{
704
    return active_.minimum_block_version;
×
705
}
706

707
uint32_t chain_state::work_required() const NOEXCEPT
×
708
{
709
    return work_required_;
×
710
}
711

712
// context
713

714
uint32_t chain_state::timestamp() const NOEXCEPT
×
715
{
716
    return data_.timestamp.self;
×
717
}
718

719
uint32_t chain_state::median_time_past() const NOEXCEPT
×
720
{
721
    return median_time_past_;
×
722
}
723

724
uint32_t chain_state::forks() const NOEXCEPT
×
725
{
726
    return active_.forks;
×
727
}
728

729
size_t chain_state::height() const NOEXCEPT
×
730
{
731
    return data_.height;
×
732
}
733

734
} // namespace chain
735
} // namespace system
736
} // 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