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

libbitcoin / libbitcoin-system / 18457551774

13 Oct 2025 06:50AM UTC coverage: 80.903%. Remained the same
18457551774

push

github

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

Revert "Rename to_shared() to make_shared(), add make_shared(vargs...)."

14 of 23 new or added lines in 7 files covered. (60.87%)

1 existing line in 1 file now uncovered.

10591 of 13091 relevant lines covered (80.9%)

3617136.95 hits per line

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

42.04
/src/chain/block.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/block.hpp>
20

21
#include <algorithm>
22
#include <iterator>
23
#include <numeric>
24
#include <ranges>
25
#include <set>
26
#include <utility>
27
#include <bitcoin/system/chain/context.hpp>
28
#include <bitcoin/system/chain/enums/flags.hpp>
29
#include <bitcoin/system/chain/enums/magic_numbers.hpp>
30
#include <bitcoin/system/chain/enums/opcode.hpp>
31
#include <bitcoin/system/chain/point.hpp>
32
#include <bitcoin/system/chain/script.hpp>
33
#include <bitcoin/system/data/data.hpp>
34
#include <bitcoin/system/define.hpp>
35
#include <bitcoin/system/error/error.hpp>
36
#include <bitcoin/system/hash/hash.hpp>
37
#include <bitcoin/system/math/math.hpp>
38
#include <bitcoin/system/stream/stream.hpp>
39

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

44
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
45
BC_PUSH_WARNING(NO_UNGUARDED_POINTERS)
46

47
// Constructors.
48
// ----------------------------------------------------------------------------
49

50
block::block() NOEXCEPT
88✔
51
  : block(to_shared<chain::header>(), to_shared<transaction_cptrs>(),
176✔
52
      false)
176✔
53
{
54
}
88✔
55

56
block::block(chain::header&& header, chain::transactions&& txs) NOEXCEPT
13✔
57
  : block(to_shared(std::move(header)), to_shareds(std::move(txs)), true)
39✔
58
{
59
}
13✔
60

61
block::block(const chain::header& header,
30✔
62
    const chain::transactions& txs) NOEXCEPT
30✔
63
  : block(to_shared<chain::header>(header), to_shareds(txs), true)
90✔
64
{
65
}
30✔
66

67
block::block(const chain::header::cptr& header,
×
68
    const transactions_cptr& txs) NOEXCEPT
×
NEW
69
  : block(header ? header : to_shared<chain::header>(),
×
NEW
70
      txs ? txs : to_shared<transaction_cptrs>(), true)
×
71
{
72
}
×
73

74
block::block(stream::in::fast&& stream, bool witness) NOEXCEPT
98✔
75
  : block(read::bytes::fast(stream), witness)
98✔
76
{
77
}
98✔
78

79
block::block(stream::in::fast& stream, bool witness) NOEXCEPT
×
80
  : block(read::bytes::fast(stream), witness)
×
81
{
82
}
×
83

84
block::block(std::istream&& stream, bool witness) NOEXCEPT
×
85
  : block(read::bytes::istream(stream), witness)
×
86
{
87
}
×
88

89
block::block(std::istream& stream, bool witness) NOEXCEPT
3✔
90
  : block(read::bytes::istream(stream), witness)
3✔
91
{
92
}
3✔
93

94
block::block(reader&& source, bool witness) NOEXCEPT
101✔
95
  : block(source, witness)
101✔
96
{
97
}
×
98

99
block::block(reader& source, bool witness) NOEXCEPT
107✔
100
  : header_(CREATE(chain::header, source.get_allocator(), source)),
107✔
101
    txs_(CREATE(transaction_cptrs, source.get_allocator()))
214✔
102
{
103
    assign_data(source, witness);
107✔
104
}
107✔
105

106
// protected
107
block::block(const chain::header::cptr& header,
131✔
108
    const transactions_cptr& txs, bool valid) NOEXCEPT
131✔
109
  : header_(header),
110
    txs_(txs),
111
    valid_(valid),
131✔
112
    size_(serialized_size(*txs))
262✔
113
{
114
}
131✔
115

116
// Operators.
117
// ----------------------------------------------------------------------------
118

119
bool block::operator==(const block& other) const NOEXCEPT
29✔
120
{
121
    return (header_ == other.header_ || *header_ == *other.header_)
29✔
122
        && deep_equal(*txs_, *other.txs_);
47✔
123
}
124

125
bool block::operator!=(const block& other) const NOEXCEPT
5✔
126
{
127
    return !(*this == other);
5✔
128
}
129

130
// Deserialization.
131
// ----------------------------------------------------------------------------
132

133
// private
134
void block::assign_data(reader& source, bool witness) NOEXCEPT
107✔
135
{
136
    auto& allocator = source.get_allocator();
107✔
137
    const auto count = source.read_size(max_block_size);
107✔
138
    auto txs = to_non_const_raw_ptr(txs_);
107✔
139
    txs->reserve(count);
107✔
140

141
    for (size_t tx = 0; tx < count; ++tx)
262✔
142
        txs->emplace_back(CREATE(transaction, allocator, source, witness));
155✔
143

144
    size_ = serialized_size(*txs_);
107✔
145
    valid_ = source;
107✔
146
}
107✔
147

148
void block::set_allocation(size_t allocation) const NOEXCEPT
×
149
{
150
    allocation_ = allocation;
×
151
}
×
152

153
size_t block::get_allocation() const NOEXCEPT
×
154
{
155
    return allocation_;
×
156
}
157

158
// Serialization.
159
// ----------------------------------------------------------------------------
160

161
data_chunk block::to_data(bool witness) const NOEXCEPT
19✔
162
{
163
    data_chunk data(serialized_size(witness));
38✔
164
    stream::out::fast ostream(data);
19✔
165
    write::bytes::fast out(ostream);
19✔
166
    to_data(out, witness);
19✔
167
    return data;
38✔
168
}
19✔
169

170
void block::to_data(std::ostream& stream, bool witness) const NOEXCEPT
1✔
171
{
172
    write::bytes::ostream out(stream);
1✔
173
    to_data(out, witness);
1✔
174
}
1✔
175

176
void block::to_data(writer& sink, bool witness) const NOEXCEPT
21✔
177
{
178
    header_->to_data(sink);
21✔
179
    sink.write_variable(txs_->size());
21✔
180

181
    for (const auto& tx: *txs_)
47✔
182
        tx->to_data(sink, witness);
26✔
183
}
21✔
184

185
// Properties.
186
// ----------------------------------------------------------------------------
187

188
bool block::is_valid() const NOEXCEPT
58✔
189
{
190
    return valid_;
58✔
191
}
192

193
size_t block::transactions() const NOEXCEPT
×
194
{
195
    return txs_->size();
×
196
}
197

198
const chain::header& block::header() const NOEXCEPT
18✔
199
{
200
    return *header_;
2✔
201
}
202

203
const chain::header::cptr block::header_ptr() const NOEXCEPT
×
204
{
205
    return header_;
×
206
}
207

208
// Roll up inputs for concurrent prevout processing.
209
const inputs_cptr block::inputs_ptr() const NOEXCEPT
×
210
{
NEW
211
    const auto inputs = to_shared<input_cptrs>();
×
212
    const auto append_ins = [&inputs](const auto& tx) NOEXCEPT
×
213
    {
214
        const auto& tx_ins = tx->inputs_ptr();
×
215
        inputs->insert(inputs->end(), tx_ins->begin(), tx_ins->end());
×
216
    };
×
217

218
    std::for_each(txs_->begin(), txs_->end(), append_ins);
×
219
    return inputs;
×
220
}
221

222
// vector<transaction> is not exposed (because we don't have it).
223
// This would require a from_shared(txs_) conversion (expensive).
224
const transactions_cptr& block::transactions_ptr() const NOEXCEPT
85✔
225
{
226
    return txs_;
85✔
227
}
228

229
hashes block::transaction_hashes(bool witness) const NOEXCEPT
14✔
230
{
231
    const auto count = txs_->size();
14✔
232
    const auto size = is_odd(count) && count > one ? add1(count) : count;
14✔
233
    hashes out{ size };
14✔
234

235
    // Extra allocation for odd count optimizes for merkle root.
236
    // Vector capacity is never reduced when resizing to smaller size.
237
    out.resize(count);
14✔
238

239
    const auto hash = [witness](const auto& tx) NOEXCEPT
19✔
240
    {
241
        return tx->hash(witness);
19✔
242
    };
14✔
243

244
    std::transform(txs_->begin(), txs_->end(), out.begin(), hash);
14✔
245
    return out;
14✔
246
}
247

248
// computed
249
size_t block::outputs() const NOEXCEPT
×
250
{
251
    if (txs_->empty())
×
252
        return zero;
253

254
    // Overflow returns max_size_t.
255
    const auto outs = [](size_t total, const auto& tx) NOEXCEPT
×
256
    {
257
         return ceilinged_add(total, tx->outputs());
×
258
    };
259

260
    return std::accumulate(std::next(txs_->begin()), txs_->end(), zero, outs);
×
261
}
262

263
// computed
264
size_t block::spends() const NOEXCEPT
7✔
265
{
266
    if (txs_->empty())
7✔
267
        return zero;
268

269
    // Overflow returns max_size_t.
270
    const auto ins = [](size_t total, const auto& tx) NOEXCEPT
11✔
271
    {
272
         return ceilinged_add(total, tx->inputs());
11✔
273
    };
274

275
    // inputs() is add1(spends()) if the block is valid (one coinbase input).
276
    return std::accumulate(std::next(txs_->begin()), txs_->end(), zero, ins);
7✔
277
}
278

279
// computed
280
hash_digest block::hash() const NOEXCEPT
40✔
281
{
282
    return header_->hash();
40✔
283
}
284

285
// computed
286
const hash_digest& block::get_hash() const NOEXCEPT
×
287
{
288
    return header_->get_hash();
×
289
}
290

291
void block::set_hashes(const data_chunk& data) NOEXCEPT
×
292
{
293
    constexpr auto header_size = chain::header::serialized_size();
×
294

295
    // Cache header hash.
296
    header_->set_hash(bitcoin_hash(header_size, data.data()));
×
297

298
    // Skip transaction count, guarded by preceding successful block construct.
299
    auto start = std::next(data.data(), header_size);
×
300
    std::advance(start, size_variable(*start));
×
301

302
    // Cache transaction hashes.
303
    auto coinbase = true;
×
304
    for (const auto& tx: *txs_)
×
305
    {
306
        const auto witness_size = tx->serialized_size(true);
×
307

308
        // If !witness then wire txs cannot have been segregated.
309
        if (tx->is_segregated())
×
310
        {
311
            const auto nominal_size = tx->serialized_size(false);
×
312

313
            tx->set_nominal_hash(transaction::desegregated_hash(
×
314
                witness_size, nominal_size, start));
315

316
            if (!coinbase)
×
317
                tx->set_witness_hash(bitcoin_hash(witness_size, start));
×
318
        }
319
        else
320
        {
321
            tx->set_nominal_hash(bitcoin_hash(witness_size, start));
×
322
        }
323

324
        coinbase = false;
×
325
        std::advance(start, witness_size);
×
326
    }
327
}
×
328

329
const chain_state::cptr& block::get_state() const NOEXCEPT
×
330
{
331
    return header_->get_state();
×
332
}
333

334
void block::set_state(const chain_state::cptr& state) const NOEXCEPT
×
335
{
336
    header_->set_state(state);
×
337
}
×
338

339
// static/private
340
block::sizes block::serialized_size(const transaction_cptrs& txs) NOEXCEPT
238✔
341
{
342
    sizes size{};
238✔
343
    std::for_each(txs.begin(), txs.end(), [&](const auto& tx) NOEXCEPT
524✔
344
    {
345
        size.nominal = ceilinged_add(size.nominal, tx->serialized_size(false));
572✔
346
        size.witnessed = ceilinged_add(size.witnessed,
286✔
347
            tx->serialized_size(true));
348
    });
286✔
349

350
    const auto base_size = ceilinged_add(header::serialized_size(),
238✔
351
        variable_size(txs.size()));
352

353
    const auto nominal_size = ceilinged_add(base_size, size.nominal);
238✔
354
    const auto witnessed_size = ceilinged_add(base_size, size.witnessed);
238✔
355

356
    return { nominal_size, witnessed_size };
238✔
357
}
358

359
size_t block::serialized_size(bool witness) const NOEXCEPT
23✔
360
{
361
    return witness ? size_.witnessed : size_.nominal;
20✔
362
}
363

364
// Check (context free).
365
// ----------------------------------------------------------------------------
366

367
bool block::is_empty() const NOEXCEPT
2✔
368
{
369
    return txs_->empty();
2✔
370
}
371

372
bool block::is_oversized() const NOEXCEPT
3✔
373
{
374
    return serialized_size(false) > max_block_size;
3✔
375
}
376

377
bool block::is_first_non_coinbase() const NOEXCEPT
3✔
378
{
379
    return !txs_->empty() && !txs_->front()->is_coinbase();
3✔
380
}
381

382
// True if there is another coinbase other than the first tx.
383
// No txs or coinbases returns false.
384
bool block::is_extra_coinbases() const NOEXCEPT
3✔
385
{
386
    if (txs_->empty())
3✔
387
        return false;
388

389
    const auto value = [](const auto& tx) NOEXCEPT
2✔
390
    {
391
        return tx->is_coinbase();
2✔
392
    };
393

394
    return std::any_of(std::next(txs_->begin()), txs_->end(), value);
3✔
395
}
396

397
//*****************************************************************************
398
// CONSENSUS: This is only necessary because satoshi stores and queries as it
399
// validates, imposing an otherwise unnecessary partial transaction ordering.
400
//*****************************************************************************
401
bool block::is_forward_reference() const NOEXCEPT
8✔
402
{
403
    if (txs_->empty())
8✔
404
        return false;
405

406
    unordered_set_of_hash_cref hashes{ sub1(txs_->size()) };
7✔
407
    for (auto tx = txs_->rbegin(); tx != std::prev(txs_->rend()); ++tx)
13✔
408
    {
409
        for (const auto& in: *(*tx)->inputs_ptr())
10✔
410
            if (hashes.contains(in->point().hash()))
4✔
411
                return true;
412

413
        hashes.emplace((*tx)->get_hash(false));
6✔
414
    }
415

416
    return false;
417
}
418

419
// This also precludes the block merkle calculation DoS exploit by preventing
420
// duplicate txs, as a duplicate non-empty tx implies a duplicate point.
421
// bitcointalk.org/?topic=102395
422
bool block::is_internal_double_spend() const NOEXCEPT
6✔
423
{
424
    if (txs_->empty())
6✔
425
        return false;
426

427
    unordered_set_of_point_cref points{ spends() };
5✔
428
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
13✔
429
        for (const auto& in: *(*tx)->inputs_ptr())
17✔
430
            if (!points.emplace(in->point()).second)
18✔
431
                return true;
432

433
    return false;
434
}
435

436
// private
437
hash_digest block::generate_merkle_root(bool witness) const NOEXCEPT
14✔
438
{
439
    return sha256::merkle_root(transaction_hashes(witness));
14✔
440
}
441

442
bool block::is_invalid_merkle_root() const NOEXCEPT
14✔
443
{
444
    return generate_merkle_root(false) != header_->merkle_root();
14✔
445
}
446

447
// Accept (contextual).
448
// ----------------------------------------------------------------------------
449

450
size_t block::weight() const NOEXCEPT
×
451
{
452
    // Block weight is 3 * nominal size * + 1 * witness size [bip141].
453
    return ceilinged_add(
×
454
        ceilinged_multiply(base_size_contribution, serialized_size(false)),
455
        ceilinged_multiply(total_size_contribution, serialized_size(true)));
×
456
}
457

458
bool block::is_overweight() const NOEXCEPT
×
459
{
460
    return weight() > max_block_weight;
×
461
}
462

463
bool block::is_invalid_coinbase_script(size_t height) const NOEXCEPT
×
464
{
465
    if (txs_->empty() || txs_->front()->inputs_ptr()->empty())
×
466
        return false;
×
467

468
    const auto& script = txs_->front()->inputs_ptr()->front()->script();
×
469
    return !script::is_coinbase_pattern(script.ops(), height);
×
470
}
471

472
// TODO: add bip50 to chain_state with timestamp range activation.
473
// "Special short-term limits to avoid 10,000 BDB lock limit.
474
// Count of unique txids <= 4500 to prevent 10000 BDB lock exhaustion.
475
// header.timestamp > 1363039171 && header.timestamp < 1368576000."
476
bool block::is_hash_limit_exceeded() const NOEXCEPT
×
477
{
478
    if (txs_->empty())
×
479
        return false;
480

481
    // A set is used to collapse duplicates.
482
    unordered_set_of_hash_cref hashes{ txs_->size() };
×
483

484
    // Just the coinbase tx hash, skip its null input hashes.
485
    hashes.emplace(txs_->front()->get_hash(false));
×
486

487
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
488
    {
489
        // Insert the transaction hash.
490
        hashes.emplace((*tx)->get_hash(false));
×
491
        const auto& inputs = (*tx)->inputs_ptr();
×
492

493
        // Insert all input point hashes.
494
        for (const auto& input: *inputs)
×
495
            hashes.emplace(input->point().hash());
×
496
    }
497

498
    return hashes.size() > hash_limit;
×
499
}
500

501
// Malleability does not imply malleated.
502
bool block::is_malleable() const NOEXCEPT
3✔
503
{
504
    return is_malleable64() || is_malleable32();
3✔
505
}
506

507
bool block::is_malleated() const NOEXCEPT
×
508
{
509
    return is_malleated64() || is_malleated32();
×
510
}
511

512
// Malleability does not imply malleated.
513
bool block::is_malleable32() const NOEXCEPT
12✔
514
{
515
    const auto unmalleated = txs_->size();
12✔
516
    for (auto mally = one; mally <= unmalleated; mally *= two)
23✔
517
        if (is_malleable32(unmalleated, mally))
17✔
518
            return true;
519

520
    return false;
521
}
522

523
// Malleated32 implies malleable and invalid due to internal tx hash pairing.
524
bool block::is_malleated32() const NOEXCEPT
11✔
525
{
526
    return !is_zero(malleated32_size());
11✔
527
}
528

529
// protected
530
// The size of an actual malleation of this block, or zero.
531
size_t block::malleated32_size() const NOEXCEPT
11✔
532
{
533
    const auto malleated = txs_->size();
11✔
534
    for (auto mally = one; mally <= to_half(malleated); mally *= two)
23✔
535
        if (is_malleable32(malleated - mally, mally) && is_malleated32(mally))
14✔
536
            return mally;
2✔
537

538
    return zero;
539
}
540

541
// protected
542
// True if the last width set of tx hashes repeats.
543
bool block::is_malleated32(size_t width) const NOEXCEPT
7✔
544
{
545
    const auto malleated = txs_->size();
7✔
546
    if (is_zero(width) || width > to_half(malleated))
7✔
547
        return false;
548

549
    auto mally = txs_->rbegin();
6✔
550
    auto legit = std::next(mally, width);
6✔
551
    while (!is_zero(width--))
9✔
552
        if ((*mally++)->get_hash(false) != (*legit++)->get_hash(false))
7✔
553
            return false;
554

555
    return true;
556
}
557

558
// Malleability does not imply malleated.
559
bool block::is_malleable64() const NOEXCEPT
12✔
560
{
561
    return is_malleable64(*txs_);
12✔
562
}
563

564
// static
565
// If all non-witness tx serializations are 64 bytes the id is malleable.
566
bool block::is_malleable64(const transaction_cptrs& txs) NOEXCEPT
12✔
567
{
568
    const auto two_leaves = [](const auto& tx) NOEXCEPT
15✔
569
    {
570
        return tx->serialized_size(false) == two * hash_size;
15✔
571
    };
572

573
    return !txs.empty() && std::all_of(txs.begin(), txs.end(), two_leaves);
12✔
574
}
575

576
// Malleated64 implies malleable64 and invalid due to non-null coinbase point.
577
// It is considered computationally infeasible to produce malleable64 with a
578
// valid (null) coinbase input point.
579
bool block::is_malleated64() const NOEXCEPT
×
580
{
581
    return !txs_->empty() && !txs_->front()->is_coinbase() &&
×
582
        is_malleable64(*txs_);
×
583
}
584

585
bool block::is_segregated() const NOEXCEPT
2✔
586
{
587
    const auto segregated = [](const auto& tx) NOEXCEPT
4✔
588
    {
589
        return tx->is_segregated();
4✔
590
    };
591

592
    return std::any_of(txs_->begin(), txs_->end(), segregated);
2✔
593
}
594

595
size_t block::segregated() const NOEXCEPT
×
596
{
597
    const auto count_segregated = [](const auto& tx) NOEXCEPT
×
598
    {
599
        return tx->is_segregated();
×
600
    };
601

602
    return std::count_if(txs_->begin(), txs_->end(), count_segregated);
×
603
}
604

605
// Last output of commitment pattern holds the committed value [bip141].
606
bool block::get_witness_commitment(hash_cref& commitment) const NOEXCEPT
×
607
{
608
    if (txs_->empty())
×
609
        return false;
610

611
    const auto& outputs = *txs_->front()->outputs_ptr();
×
612
    for (const auto& output: std::views::reverse(outputs))
×
613
        if (output->committed_hash(commitment))
×
614
            return true;
615

616
    return false;
617
}
618

619
// Coinbase input witness must be 32 byte witness reserved value [bip141].
620
bool block::get_witness_reservation(hash_cref& reservation) const NOEXCEPT
×
621
{
622
    if (txs_->empty())
×
623
        return false;
624

625
    const auto& inputs = *txs_->front()->inputs_ptr();
×
626
    return !inputs.empty() && inputs.front()->reserved_hash(reservation);
×
627
}
628

629
// The witness merkle root is obtained from wtxids, subject to malleation just
630
// as the txs commitment. However, since tx duplicates are precluded by the
631
// malleable32 (or complete) block check, there is no opportunity for this.
632
// Similarly the witness commitment cannot be malleable64.
633
bool block::is_invalid_witness_commitment() const NOEXCEPT
×
634
{
635
    if (txs_->empty())
×
636
        return false;
637

638
    // Witness data (segregated) disallowed if no commitment [bip141].
639
    // If no block tx has witness data the commitment is optional [bip141].
640
    hash_cref commit{ null_hash };
×
641
    if (!get_witness_commitment(commit))
×
642
        return is_segregated();
×
643

644
    // If there is a witness reservation there must be a commitment [bip141].
645
    hash_cref reserve{ null_hash };
×
646
    if (!get_witness_reservation(reserve))
×
647
        return true;
648

649
    // If there is a valid commitment, return false (valid).
650
    return commit != sha256::double_hash(generate_merkle_root(true), reserve);
×
651
}
652

653
//*****************************************************************************
654
// CONSENSUS:
655
// bip42 compensates for C++ undefined behavior of a right shift of a number of
656
// bits greater or equal to the shifted integer width. Yet being undefined, the
657
// result of this operation may vary by compiler. The shift_right call below
658
// explicitly implements presumed pre-bip42 behavior (shift overflow modulo) by
659
// default, and specified bip42 behavior (shift overflow to zero) with bip42.
660
//*****************************************************************************
661
static uint64_t block_subsidy(size_t height, uint64_t subsidy_interval,
×
662
    uint64_t initial_block_subsidy_satoshi, bool bip42) NOEXCEPT
663
{
664
    // Guard: quotient domain cannot increase with positive integer divisor.
665
    const auto halves = possible_narrow_cast<size_t>(height / subsidy_interval);
×
666
    return shift_right(initial_block_subsidy_satoshi, halves, bip42);
×
667
}
668

669
// Prevouts required.
670

671
uint64_t block::fees() const NOEXCEPT
×
672
{
673
    // Overflow returns max_uint64.
674
    const auto value = [](uint64_t total, const auto& tx) NOEXCEPT
×
675
    {
676
        return ceilinged_add(total, tx->fee());
×
677
    };
678

679
    return std::accumulate(txs_->begin(), txs_->end(), uint64_t{}, value);
×
680
}
681

682
uint64_t block::claim() const NOEXCEPT
×
683
{
684
    return txs_->empty() ? zero : txs_->front()->value();
×
685
}
686

687
uint64_t block::reward(size_t height, uint64_t subsidy_interval,
×
688
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
689
{
690
    // Overflow returns max_uint64.
691
    return ceilinged_add(fees(), block_subsidy(height, subsidy_interval,
×
692
        initial_block_subsidy_satoshi, bip42));
×
693
}
694

695
bool block::is_overspent(size_t height, uint64_t subsidy_interval,
×
696
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
697
{
698
    return claim() > reward(height, subsidy_interval,
×
699
        initial_block_subsidy_satoshi, bip42);
×
700
}
701

702
size_t block::signature_operations(bool bip16, bool bip141) const NOEXCEPT
×
703
{
704
    // Overflow returns max_size_t.
705
    const auto value = [=](size_t total, const auto& tx) NOEXCEPT
×
706
    {
707
        const auto add = tx->signature_operations(bip16, bip141);
×
708
        return ceilinged_add(total, add);
×
709
    };
×
710

711
    return std::accumulate(txs_->begin(), txs_->end(), zero, value);
×
712
}
713

714
bool block::is_signature_operations_limited(bool bip16,
×
715
    bool bip141) const NOEXCEPT
716
{
717
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
718
    return signature_operations(bip16, bip141) > limit;
×
719
}
720

721
//*****************************************************************************
722
// CONSENSUS: check excluded under bip30 exception blocks and bip30_deactivate
723
// until bip30_reactivate. Those conditions are rolled up into the bip30 flag.
724
//*****************************************************************************
725
bool block::is_unspent_coinbase_collision() const NOEXCEPT
×
726
{
727
    if (txs_->empty() || txs_->front()->inputs_ptr()->empty())
×
728
        return false;
×
729

730
    // May only commit duplicate coinbase that is already confirmed spent.
731
    // Metadata population defaults coinbase to spent (not a collision).
732
    return !txs_->front()->inputs_ptr()->front()->metadata.spent;
×
733
}
734

735
// Search is unordered, forward refs (and duplicates) caught by block.check.
736
void block::populate() const NOEXCEPT
×
737
{
738
    if (txs_->empty())
×
739
        return;
×
740

741
    unordered_map_of_cref_point_to_output_cptr_cref points{ outputs() };
×
742
    uint32_t index{};
×
743

744
    // Populate outputs hash table (coinbase included).
745
    for (auto tx = txs_->begin(); tx != txs_->end(); ++tx, index = 0)
×
746
        for (const auto& out: *(*tx)->outputs_ptr())
×
747
            points.emplace(cref_point{ (*tx)->get_hash(false), index++ }, out);
×
748

749
    // Populate input prevouts from hash table.
750
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
751
    {
752
        for (const auto& in: *(*tx)->inputs_ptr())
×
753
        {
754
            // Map chain::point to cref_point for search, should optimize away.
755
            const auto point = points.find({ in->point().hash(),
×
756
                in->point().index() });
×
757

758
            if (point != points.end())
×
759
                in->prevout = point->second;
×
760
        }
761
    }
762
}
763

764
code block::populate_with_metadata(const chain::context& ctx) const NOEXCEPT
×
765
{
766
    if (txs_->empty())
×
767
        return error::block_success;
×
768

769
    const auto bip68 = ctx.is_enabled(chain::flags::bip68_rule);
×
770
    unordered_map_of_cref_point_to_output_cptr_cref points{ outputs() };
×
771
    uint32_t index{};
×
772

773
    // Populate outputs hash table (coinbase included).
774
    for (auto tx = txs_->begin(); tx != txs_->end(); ++tx, index = 0)
×
775
        for (const auto& out: *(*tx)->outputs_ptr())
×
776
            points.emplace(cref_point{ (*tx)->get_hash(false), index++ }, out);
×
777

778
    // Populate input prevouts from hash table and obtain maturity.
779
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
780
    {
781
        for (const auto& in: *(*tx)->inputs_ptr())
×
782
        {
783
            // Map chain::point to cref_point for search, should optimize away.
784
            const auto point = points.find({ in->point().hash(),
×
785
                in->point().index() });
×
786

787
            if (point != points.end())
×
788
            {
789
                // Zero maturity coinbase spend is immature.
790
                const auto lock = (bip68 && (*tx)->is_internally_locked(*in));
×
791
                const auto immature = !is_zero(coinbase_maturity) &&
×
792
                    (in->point().hash() == txs_->front()->get_hash(false));
×
793

794
                in->prevout = point->second;
×
795
                if ((in->metadata.locked = (immature || lock)))
×
796
                {
797
                    // Shortcircuit population and return above error.
798
                    return immature ? error::coinbase_maturity : 
×
799
                        error::relative_time_locked;
×
800
                }
801
            }
802
        }
803
    }
804

805
    return error::block_success;
×
806
}
807

808
// Delegated.
809
// ----------------------------------------------------------------------------
810

811
// DO invoke on coinbase.
812
code block::check_transactions() const NOEXCEPT
3✔
813
{
814
    for (const auto& tx: *txs_)
8✔
815
        if (const auto ec = tx->check())
5✔
816
            return ec;
×
817

818
    return error::block_success;
3✔
819
}
820

821
// DO invoke on coinbase.
822
code block::check_transactions(const context& ctx) const NOEXCEPT
×
823
{
824
    for (const auto& tx: *txs_)
×
825
        if (const auto ec = tx->check(ctx))
×
826
            return ec;
×
827

828
    return error::block_success;
×
829
}
830

831
// Do NOT invoke on coinbase.
832
code block::accept_transactions(const context& ctx) const NOEXCEPT
×
833
{
834
    if (!is_empty())
×
835
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
836
            if (const auto ec = (*tx)->accept(ctx))
×
837
                return ec;
×
838

839
    return error::block_success;
×
840
}
841

842
// Do NOT invoke on coinbase.
843
code block::connect_transactions(const context& ctx) const NOEXCEPT
×
844
{
845
    if (!is_empty())
×
846
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
847
            if (const auto ec = (*tx)->connect(ctx))
×
848
                return ec;
×
849

850
    return error::block_success;
×
851
}
852

853
// Do NOT invoke on coinbase.
854
code block::confirm_transactions(const context& ctx) const NOEXCEPT
×
855
{
856
    if (!is_empty())
×
857
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
858
            if (const auto ec = (*tx)->confirm(ctx))
×
859
                return ec;
×
860

861
    return error::block_success;
×
862
}
863

864
// Identity.
865
// ----------------------------------------------------------------------------
866

867
code block::identify() const NOEXCEPT
×
868
{
869
    if (is_malleated() || is_invalid_merkle_root())
×
870
        return error::invalid_transaction_commitment;
×
871

872
    return error::block_success;
×
873
}
874

875
// bip141 should be disabled when the node is not accepting witness data.
876
code block::identify(const context& ctx) const NOEXCEPT
×
877
{
878
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
879

880
    if (bip141 && is_invalid_witness_commitment())
×
881
        return error::invalid_witness_commitment;
×
882

883
    return error::block_success;
×
884
}
885

886
// Validation.
887
// ----------------------------------------------------------------------------
888
// In the case of validation failure
889
// The block header is checked/accepted independently.
890

891
// Use of get_hash() in is_forward_reference makes this thread-unsafe.
892
code block::check() const NOEXCEPT
3✔
893
{
894
    // empty_block is subset of first_not_coinbase.
895
    // type64 malleated is a subset of first_not_coinbase.
896
    // type32 malleated is a subset of is_internal_double_spend.
897
    if (is_oversized())
3✔
898
        return error::block_size_limit;
×
899
    if (is_first_non_coinbase())
3✔
900
        return (is_empty() ? error::empty_block :
×
901
            (is_malleated() ? error::invalid_transaction_commitment :
×
902
                error::first_not_coinbase));
×
903
    if (is_extra_coinbases())
3✔
904
        return error::extra_coinbases;
×
905
    if (is_forward_reference())
3✔
906
        return error::forward_reference;
×
907
    if (is_internal_double_spend())
3✔
908
        return is_malleated() ? error::invalid_transaction_commitment : 
×
909
            error::block_internal_double_spend;
×
910
    if (is_invalid_merkle_root())
3✔
911
        return error::invalid_transaction_commitment;
×
912

913
    return check_transactions();
3✔
914
}
915

916
// forks
917
// height
918
// timestamp
919
// median_time_past
920

921
// Use of get_hash() in is_hash_limit_exceeded makes this thread-unsafe.
922
// bip141 should be disabled when the node is not accepting witness data.
923
code block::check(const context& ctx) const NOEXCEPT
×
924
{
925
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
926
    const auto bip34 = ctx.is_enabled(bip34_rule);
×
927
    const auto bip50 = ctx.is_enabled(bip50_rule);
×
928

929
    if (bip141 && is_overweight())
×
930
        return error::block_weight_limit;
×
931
    if (bip34 && is_invalid_coinbase_script(ctx.height))
×
932
        return error::coinbase_height_mismatch;
×
933
    if (bip50 && is_hash_limit_exceeded())
×
934
        return error::temporary_hash_limit;
×
935
    if (bip141 && is_invalid_witness_commitment())
×
936
        return error::invalid_witness_commitment;
×
937

938
    return check_transactions(ctx);
×
939
}
940

941
// forks
942
// height
943

944
// This assumes that prevout caching is completed on all inputs.
945
code block::accept(const context& ctx, size_t subsidy_interval,
×
946
    uint64_t initial_subsidy) const NOEXCEPT
947
{
948
    const auto bip16 = ctx.is_enabled(bip16_rule);
×
949
    const auto bip42 = ctx.is_enabled(bip42_rule);
×
950
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
951

952
    // prevouts required.
953
    if (is_overspent(ctx.height, subsidy_interval, initial_subsidy, bip42))
×
954
        return error::coinbase_value_limit;
×
955
    if (is_signature_operations_limited(bip16, bip141))
×
956
        return error::block_sigop_limit;
×
957

958
    return accept_transactions(ctx);
×
959
}
960

961
// forks
962

963
// Node performs these checks through database query.
964
// This assumes that prevout and metadata caching are completed on all inputs.
965
code block::confirm(const context& ctx) const NOEXCEPT
×
966
{
967
    const auto bip30 = ctx.is_enabled(bip30_rule);
×
968

969
    if (bip30 && is_unspent_coinbase_collision())
×
970
        return error::unspent_coinbase_collision;
×
971

972
    return confirm_transactions(ctx);
×
973
}
974

975
// forks
976

977
// This assumes that prevout caching is completed on all inputs.
978
code block::connect(const context& ctx) const NOEXCEPT
×
979
{
980
    return connect_transactions(ctx);
×
981
}
982

983
BC_POP_WARNING()
984
BC_POP_WARNING()
985

986
// JSON value convertors.
987
// ----------------------------------------------------------------------------
988

989
namespace json = boost::json;
990

991
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
992
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
993

994
block tag_invoke(json::value_to_tag<block>,
1✔
995
    const json::value& value) NOEXCEPT
996
{
997
    return
1✔
998
    {
999
        json::value_to<header>(value.at("header")),
1✔
1000
        json::value_to<chain::transactions>(value.at("transactions"))
2✔
1001
    };
1✔
1002
}
1003

1004
void tag_invoke(json::value_from_tag, json::value& value,
2✔
1005
    const block& block) NOEXCEPT
1006
{
1007
    value =
4✔
1008
    {
1009
        { "header", json::value_from(block.header()) },
2✔
1010
        { "transactions", json::value_from(*block.transactions_ptr()) },
6✔
1011
    };
2✔
1012
}
2✔
1013

1014
BC_POP_WARNING()
1015

1016
block::cptr tag_invoke(json::value_to_tag<block::cptr>,
×
1017
    const json::value& value) NOEXCEPT
1018
{
1019
    return to_shared(tag_invoke(json::value_to_tag<block>{}, value));
×
1020
}
1021

1022
// Shared pointer overload is required for navigation.
1023
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
1024
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
1025

1026
void tag_invoke(json::value_from_tag tag, json::value& value,
×
1027
    const block::cptr& block) NOEXCEPT
1028
{
1029
    tag_invoke(tag, value, *block);
×
1030
}
×
1031

1032
BC_POP_WARNING()
1033
BC_POP_WARNING()
1034

1035
} // namespace chain
1036
} // namespace system
1037
} // 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