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

libbitcoin / libbitcoin-system / 23967426501

04 Apr 2026 12:36AM UTC coverage: 81.59% (+0.05%) from 81.542%
23967426501

push

github

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

Fix/update tx confirm & metadata for use in network.

8 of 17 new or added lines in 5 files covered. (47.06%)

4 existing lines in 2 files now uncovered.

11155 of 13672 relevant lines covered (81.59%)

3345189.9 hits per line

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

44.9
/src/chain/block.cpp
1
/**
2
 * Copyright (c) 2011-2026 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
93✔
51
  : block(to_shared<chain::header>(), to_shared<transaction_cptrs>(), false)
186✔
52
{
53
}
93✔
54

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

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

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

73
block::block(const data_slice& data, bool witness) NOEXCEPT
103✔
74
  : block(stream::in::fast(data), witness)
103✔
75
{
76
}
103✔
77

78
// protected
79
block::block(stream::in::fast&& stream, bool witness) NOEXCEPT
103✔
80
  : block(read::bytes::fast(stream), witness)
103✔
81
{
82
}
103✔
83

84
block::block(stream::in::fast& stream, bool witness) NOEXCEPT
×
85
  : block(read::bytes::fast(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
// protected
95
block::block(reader&& source, bool witness) NOEXCEPT
106✔
96
  : block(source, witness)
106✔
97
{
98
}
×
99

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

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

117
// Operators.
118
// ----------------------------------------------------------------------------
119

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

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

131
// Deserialization.
132
// ----------------------------------------------------------------------------
133

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

142
    for (size_t tx{}; tx < count; ++tx)
278✔
143
        txs->emplace_back(CREATE(transaction, allocator, source, witness));
163✔
144

145
    size_ = serialized_size(*txs_);
115✔
146
    valid_ = source;
115✔
147
}
115✔
148

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

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

159
// Serialization.
160
// ----------------------------------------------------------------------------
161

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

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

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

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

186
// Properties.
187
// ----------------------------------------------------------------------------
188

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

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

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

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

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

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

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

230
hashes block::transaction_hashes(bool witness) const NOEXCEPT
28✔
231
{
232
    // Extra allocation for odd count optimizes for merkle root.
233
    // Vector capacity is never reduced when resizing to smaller size.
234
    const auto count = txs_->size();
28✔
235
    const auto size = !is_one(count) && is_odd(count) ? add1(count) : count;
28✔
236
    hashes out(size);
28✔
237
    out.resize(count);
28✔
238

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

244
    std::transform(txs_->begin(), txs_->end(), out.begin(), hash);
28✔
245
    return out;
28✔
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
44✔
281
{
282
    return header_->hash();
44✔
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
251✔
341
{
342
    sizes size{};
251✔
343
    std::for_each(txs.begin(), txs.end(), [&](const auto& tx) NOEXCEPT
545✔
344
    {
345
        size.nominal = ceilinged_add(size.nominal, tx->serialized_size(false));
588✔
346
        size.witnessed = ceilinged_add(size.witnessed,
294✔
347
            tx->serialized_size(true));
348
    });
294✔
349

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

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

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

359
size_t block::serialized_size(bool witness) const NOEXCEPT
35✔
360
{
361
    return witness ? size_.witnessed : size_.nominal;
28✔
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());
10✔
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
// static
448
hashes block::merkle_branch(size_t position, hashes&& leaves) NOEXCEPT
14✔
449
{
450
    if (position >= leaves.size())
14✔
451
        return {};
2✔
452

453
    hashes branch{};
12✔
454
    branch.reserve(ceilinged_log2(leaves.size()));
12✔
455
    for (auto at = position; leaves.size() > one; at = to_half(at))
34✔
456
    {
457
        if (is_odd(leaves.size())) leaves.push_back(leaves.back());
22✔
458
        branch.push_back(leaves.at(is_even(at) ? add1(at) : sub1(at)));
44✔
459
        sha256::merkle_hash(leaves);
22✔
460
    }
461

462
    return branch;
12✔
463
}
464

465
hashes block::merkle_branch(size_t position, bool witness) const NOEXCEPT
14✔
466
{
467
    return merkle_branch(position, transaction_hashes(witness));
14✔
468
}
469

470
// Accept (contextual).
471
// ----------------------------------------------------------------------------
472

473
size_t block::weight() const NOEXCEPT
4✔
474
{
475
    // Block weight is 3 * nominal size * + 1 * witness size [bip141].
476
    return ceilinged_add(
4✔
477
        ceilinged_multiply(base_size_contribution, serialized_size(false)),
478
        ceilinged_multiply(total_size_contribution, serialized_size(true)));
4✔
479
}
480

481
size_t block::virtual_size() const NOEXCEPT
×
482
{
483
    constexpr auto scale = base_size_contribution + total_size_contribution;
×
484
    return ceilinged_divide(weight(), scale);
×
485
}
486

487
bool block::is_overweight() const NOEXCEPT
×
488
{
489
    return weight() > max_block_weight;
×
490
}
491

492
bool block::is_invalid_coinbase_script(size_t height) const NOEXCEPT
×
493
{
494
    if (txs_->empty() || txs_->front()->inputs_ptr()->empty())
×
495
        return false;
×
496

497
    const auto& script = txs_->front()->inputs_ptr()->front()->script();
×
498
    return !script::is_coinbase_pattern(script.ops(), height);
×
499
}
500

501
// TODO: add bip50 to chain_state with timestamp range activation.
502
// "Special short-term limits to avoid 10,000 BDB lock limit.
503
// Count of unique txids <= 4500 to prevent 10000 BDB lock exhaustion.
504
// header.timestamp > 1363039171 && header.timestamp < 1368576000."
505
bool block::is_hash_limit_exceeded() const NOEXCEPT
×
506
{
507
    if (txs_->empty())
×
508
        return false;
509

510
    // A set is used to collapse duplicates.
511
    unordered_set_of_hash_cref hashes(txs_->size());
×
512

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

516
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
517
    {
518
        // Insert the transaction hash.
519
        hashes.emplace((*tx)->get_hash(false));
×
520
        const auto& inputs = (*tx)->inputs_ptr();
×
521

522
        // Insert all input point hashes.
523
        for (const auto& input: *inputs)
×
524
            hashes.emplace(input->point().hash());
×
525
    }
526

527
    return hashes.size() > hash_limit;
×
528
}
529

530
// Malleability does not imply malleated.
531
bool block::is_malleable() const NOEXCEPT
3✔
532
{
533
    return is_malleable64() || is_malleable32();
3✔
534
}
535

536
bool block::is_malleated() const NOEXCEPT
×
537
{
538
    return is_malleated64() || is_malleated32();
×
539
}
540

541
// Malleability does not imply malleated.
542
bool block::is_malleable32() const NOEXCEPT
12✔
543
{
544
    const auto unmalleated = txs_->size();
12✔
545
    for (auto mally = one; mally <= unmalleated; mally *= two)
23✔
546
        if (is_malleable32(unmalleated, mally))
17✔
547
            return true;
548

549
    return false;
550
}
551

552
// Malleated32 implies malleable and invalid due to internal tx hash pairing.
553
bool block::is_malleated32() const NOEXCEPT
11✔
554
{
555
    return !is_zero(malleated32_size());
11✔
556
}
557

558
// protected
559
// The size of an actual malleation of this block, or zero.
560
size_t block::malleated32_size() const NOEXCEPT
11✔
561
{
562
    const auto malleated = txs_->size();
11✔
563
    for (auto mally = one; mally <= to_half(malleated); mally *= two)
23✔
564
        if (is_malleable32(malleated - mally, mally) && is_malleated32(mally))
14✔
565
            return mally;
2✔
566

567
    return zero;
568
}
569

570
// protected
571
// True if the last width set of tx hashes repeats.
572
bool block::is_malleated32(size_t width) const NOEXCEPT
7✔
573
{
574
    const auto malleated = txs_->size();
7✔
575
    if (is_zero(width) || width > to_half(malleated))
7✔
576
        return false;
577

578
    auto mally = txs_->rbegin();
6✔
579
    auto legit = std::next(mally, width);
6✔
580
    while (!is_zero(width--))
9✔
581
        if ((*mally++)->get_hash(false) != (*legit++)->get_hash(false))
7✔
582
            return false;
583

584
    return true;
585
}
586

587
// Malleability does not imply malleated.
588
bool block::is_malleable64() const NOEXCEPT
12✔
589
{
590
    return is_malleable64(*txs_);
12✔
591
}
592

593
// static
594
// If all non-witness tx serializations are 64 bytes the id is malleable.
595
bool block::is_malleable64(const transaction_cptrs& txs) NOEXCEPT
12✔
596
{
597
    const auto two_leaves = [](const auto& tx) NOEXCEPT
15✔
598
    {
599
        return tx->serialized_size(false) == two * hash_size;
15✔
600
    };
601

602
    return !txs.empty() && std::all_of(txs.begin(), txs.end(), two_leaves);
12✔
603
}
604

605
// Malleated64 implies malleable64 and invalid due to non-null coinbase point.
606
// It is considered computationally infeasible to produce malleable64 with a
607
// valid (null) coinbase input point.
608
bool block::is_malleated64() const NOEXCEPT
×
609
{
610
    return !txs_->empty() && !txs_->front()->is_coinbase() &&
×
611
        is_malleable64(*txs_);
×
612
}
613

614
bool block::is_segregated() const NOEXCEPT
2✔
615
{
616
    const auto segregated = [](const auto& tx) NOEXCEPT
4✔
617
    {
618
        return tx->is_segregated();
4✔
619
    };
620

621
    return std::any_of(txs_->begin(), txs_->end(), segregated);
2✔
622
}
623

624
size_t block::segregated() const NOEXCEPT
×
625
{
626
    const auto count_segregated = [](const auto& tx) NOEXCEPT
×
627
    {
628
        return tx->is_segregated();
×
629
    };
630

631
    return std::count_if(txs_->begin(), txs_->end(), count_segregated);
×
632
}
633

634
// Last output of commitment pattern holds the committed value [bip141].
635
bool block::get_witness_commitment(hash_cref& commitment) const NOEXCEPT
×
636
{
637
    if (txs_->empty())
×
638
        return false;
639

640
    const auto& outputs = *txs_->front()->outputs_ptr();
×
641
    for (const auto& output: std::views::reverse(outputs))
×
642
        if (output->committed_hash(commitment))
×
643
            return true;
644

645
    return false;
646
}
647

648
// Coinbase input witness must be 32 byte witness reserved value [bip141].
649
bool block::get_witness_reservation(hash_cref& reservation) const NOEXCEPT
×
650
{
651
    if (txs_->empty())
×
652
        return false;
653

654
    const auto& inputs = *txs_->front()->inputs_ptr();
×
655
    return !inputs.empty() && inputs.front()->reserved_hash(reservation);
×
656
}
657

658
// The witness merkle root is obtained from wtxids, subject to malleation just
659
// as the txs commitment. However, since tx duplicates are precluded by the
660
// malleable32 (or complete) block check, there is no opportunity for this.
661
// Similarly the witness commitment cannot be malleable64.
662
bool block::is_invalid_witness_commitment() const NOEXCEPT
×
663
{
664
    if (txs_->empty())
×
665
        return false;
666

667
    // Witness data (segregated) disallowed if no commitment [bip141].
668
    // If no block tx has witness data the commitment is optional [bip141].
669
    hash_cref commit{ null_hash };
×
670
    if (!get_witness_commitment(commit))
×
671
        return is_segregated();
×
672

673
    // If there is a witness reservation there must be a commitment [bip141].
674
    hash_cref reserve{ null_hash };
×
675
    if (!get_witness_reservation(reserve))
×
676
        return true;
677

678
    // If there is a valid commitment, return false (valid).
679
    return commit != sha256::double_hash(generate_merkle_root(true), reserve);
×
680
}
681

682
//*****************************************************************************
683
// CONSENSUS:
684
// bip42 compensates for C++ undefined behavior of a right shift of a number of
685
// bits greater or equal to the shifted integer width. Yet being undefined, the
686
// result of this operation may vary by compiler. The shift_right call below
687
// explicitly implements presumed pre-bip42 behavior (shift overflow modulo) by
688
// default, and specified bip42 behavior (shift overflow to zero) with bip42.
689
//*****************************************************************************
690
uint64_t block::subsidy(size_t height, uint64_t subsidy_interval,
×
691
    uint64_t initial_block_subsidy_satoshi, bool bip42) NOEXCEPT
692
{
693
    // Guard: quotient domain cannot increase with positive integer divisor.
694
    const auto halves = possible_narrow_cast<size_t>(height / subsidy_interval);
×
695
    return shift_right(initial_block_subsidy_satoshi, halves, bip42);
×
696
}
697

698
// Prevouts required.
699

700
// The fees() is the sum of all transaction fees (coinbase is zero).
701
uint64_t block::fees() const NOEXCEPT
×
702
{
703
    // Overflow returns max_uint64.
704
    const auto value = [](uint64_t total, const auto& tx) NOEXCEPT
×
705
    {
706
        return ceilinged_add(total, tx->fee());
×
707
    };
708

709
    return std::accumulate(txs_->begin(), txs_->end(), 0_u64, value);
×
710
}
711

712
// The claim() is the spend of the coinbase transaction.
713
uint64_t block::claim() const NOEXCEPT
×
714
{
715
    return txs_->empty() ? zero : txs_->front()->spend();
×
716
}
717

718
// The reward() is the sum of all transaction.fee() and the block subsidy.
719
uint64_t block::reward(size_t height, uint64_t subsidy_interval,
×
720
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
721
{
722
    // Overflow returns max_uint64.
723
    return ceilinged_add(fees(), subsidy(height, subsidy_interval,
×
724
        initial_block_subsidy_satoshi, bip42));
×
725
}
726

727
bool block::is_overspent(size_t height, uint64_t subsidy_interval,
×
728
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
729
{
730
    return claim() > reward(height, subsidy_interval,
×
731
        initial_block_subsidy_satoshi, bip42);
×
732
}
733

734
size_t block::signature_operations(bool bip16, bool bip141) const NOEXCEPT
×
735
{
736
    // Overflow returns max_size_t.
737
    const auto value = [=](size_t total, const auto& tx) NOEXCEPT
×
738
    {
739
        const auto add = tx->signature_operations(bip16, bip141);
×
740
        return ceilinged_add(total, add);
×
741
    };
×
742

743
    return std::accumulate(txs_->begin(), txs_->end(), zero, value);
×
744
}
745

746
bool block::is_signature_operations_limited(bool bip16,
×
747
    bool bip141) const NOEXCEPT
748
{
749
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
750
    return signature_operations(bip16, bip141) > limit;
×
751
}
752

753
// Search is unordered, forward refs (and duplicates) caught by block.check.
UNCOV
754
void block::populate() const NOEXCEPT
×
755
{
756
    if (txs_->empty())
×
757
        return;
×
758

759
    unordered_map_of_cref_point_to_output_cptr_cref points(outputs());
×
760
    uint32_t index{};
×
761

762
    // Populate outputs hash table (coinbase included).
763
    for (auto tx = txs_->begin(); tx != txs_->end(); ++tx, index = 0)
×
764
        for (const auto& out: *(*tx)->outputs_ptr())
×
765
            points.emplace(cref_point{ (*tx)->get_hash(false), index++ }, out);
×
766

767
    // Populate input prevouts from hash table.
768
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
769
    {
770
        for (const auto& in: *(*tx)->inputs_ptr())
×
771
        {
772
            // Map chain::point to cref_point for search, should optimize away.
773
            const auto point = points.find({ in->point().hash(),
×
774
                in->point().index() });
×
775

776
            if (point != points.end())
×
777
                in->prevout = point->second;
×
778
        }
779
    }
780
}
781

782
code block::populate_with_metadata(const chain::context& ctx) const NOEXCEPT
×
783
{
784
    if (txs_->empty())
×
785
        return error::block_success;
×
786

NEW
787
    const auto& self = txs_->front()->get_hash(false);
×
NEW
788
    constexpr auto matures = !is_zero(coinbase_maturity);
×
789
    const auto bip68 = ctx.is_enabled(chain::flags::bip68_rule);
×
790
    unordered_map_of_cref_point_to_output_cptr_cref points(outputs());
×
791
    uint32_t index{};
×
792

793
    // Populate outputs hash table (coinbase included).
794
    for (auto tx = txs_->begin(); tx != txs_->end(); ++tx, index = 0)
×
795
        for (const auto& out: *(*tx)->outputs_ptr())
×
796
            points.emplace(cref_point{ (*tx)->get_hash(false), index++ }, out);
×
797

798
    // Populate prevouts from hash table, determine get locked and maturity.
799
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
800
    {
801
        for (const auto& in: *(*tx)->inputs_ptr())
×
802
        {
803
            // Map chain::point to cref_point for search, should optimize away.
NEW
804
            const cref_point key{ in->point().hash(), in->point().index() };
×
805

NEW
806
            if (const auto it = points.find(key); it != points.end())
×
807
            {
NEW
808
                const auto immature = (matures && in->point().hash() == self);
×
809
                const auto lock = (bip68 && (*tx)->is_internally_locked(*in));
×
NEW
810
                in->prevout = it->second;
×
811

812
                // If invalid shortcircuit population and return above error.
813
                if ((in->metadata.locked = (immature || lock)))
×
814
                {
NEW
815
                    return immature ? error::coinbase_maturity :
×
816
                        error::relative_time_locked;
×
817
                }
818
            }
819
        }
820
    }
821

822
    return error::block_success;
×
823
}
824

825
// Delegated.
826
// ----------------------------------------------------------------------------
827

828
// DO invoke on coinbase.
829
code block::check_transactions() const NOEXCEPT
3✔
830
{
831
    for (const auto& tx: *txs_)
8✔
832
        if (const auto ec = tx->check())
5✔
833
            return ec;
×
834

835
    return error::block_success;
3✔
836
}
837

838
// DO invoke on coinbase.
839
code block::check_transactions(const context& ctx) const NOEXCEPT
×
840
{
841
    for (const auto& tx: *txs_)
×
842
        if (const auto ec = tx->check(ctx))
×
843
            return ec;
×
844

845
    return error::block_success;
×
846
}
847

848
// Do NOT invoke on coinbase.
849
code block::accept_transactions(const context& ctx) const NOEXCEPT
×
850
{
851
    if (!is_empty())
×
852
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
853
            if (const auto ec = (*tx)->accept(ctx))
×
854
                return ec;
×
855

856
    return error::block_success;
×
857
}
858

859
// Do NOT invoke on coinbase.
860
code block::connect_transactions(const context& ctx) const NOEXCEPT
×
861
{
862
    if (!is_empty())
×
863
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
864
            if (const auto ec = (*tx)->connect(ctx))
×
865
                return ec;
×
866

867
    return error::block_success;
×
868
}
869

870
// Do NOT invoke on coinbase.
871
code block::confirm_transactions(const context& ctx) const NOEXCEPT
×
872
{
873
    if (!is_empty())
×
874
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
875
            if (const auto ec = (*tx)->confirm(ctx))
×
876
                return ec;
×
877

878
    return error::block_success;
×
879
}
880

881
// Identity.
882
// ----------------------------------------------------------------------------
883

884
code block::identify() const NOEXCEPT
×
885
{
886
    if (is_malleated() || is_invalid_merkle_root())
×
887
        return error::invalid_transaction_commitment;
×
888

889
    return error::block_success;
×
890
}
891

892
// bip141 should be disabled when the node is not accepting witness data.
893
code block::identify(const context& ctx) const NOEXCEPT
×
894
{
895
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
896

897
    if (bip141 && is_invalid_witness_commitment())
×
898
        return error::invalid_witness_commitment;
×
899

900
    return error::block_success;
×
901
}
902

903
// Validation.
904
// ----------------------------------------------------------------------------
905
// In the case of validation failure
906
// The block header is checked/accepted independently.
907

908
// Use of get_hash() in is_forward_reference makes this thread-unsafe.
909
code block::check() const NOEXCEPT
3✔
910
{
911
    // empty_block is subset of first_not_coinbase.
912
    // type64 malleated is a subset of first_not_coinbase.
913
    // type32 malleated is a subset of is_internal_double_spend.
914
    if (is_oversized())
3✔
915
        return error::block_size_limit;
×
916
    if (is_first_non_coinbase())
3✔
917
        return (is_empty() ? error::empty_block :
×
918
            (is_malleated() ? error::invalid_transaction_commitment :
×
919
                error::first_not_coinbase));
×
920
    if (is_extra_coinbases())
3✔
921
        return error::extra_coinbases;
×
922
    if (is_forward_reference())
3✔
923
        return error::forward_reference;
×
924
    if (is_internal_double_spend())
3✔
925
        return is_malleated() ? error::invalid_transaction_commitment : 
×
926
            error::block_internal_double_spend;
×
927
    if (is_invalid_merkle_root())
3✔
928
        return error::invalid_transaction_commitment;
×
929

930
    return check_transactions();
3✔
931
}
932

933
// forks
934
// height
935
// timestamp
936
// median_time_past
937

938
// Use of get_hash() in is_hash_limit_exceeded makes this thread-unsafe.
939
// bip141 should be disabled when the node is not accepting witness data.
940
code block::check(const context& ctx) const NOEXCEPT
×
941
{
942
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
943
    const auto bip34 = ctx.is_enabled(bip34_rule);
×
944
    const auto bip50 = ctx.is_enabled(bip50_rule);
×
945

946
    if (bip141 && is_overweight())
×
947
        return error::block_weight_limit;
×
948
    if (bip34 && is_invalid_coinbase_script(ctx.height))
×
949
        return error::coinbase_height_mismatch;
×
950
    if (bip50 && is_hash_limit_exceeded())
×
951
        return error::temporary_hash_limit;
×
952
    if (bip141 && is_invalid_witness_commitment())
×
953
        return error::invalid_witness_commitment;
×
954

955
    return check_transactions(ctx);
×
956
}
957

958
// forks
959
// height
960

961
// This assumes that prevout caching is completed on all inputs.
962
code block::accept(const context& ctx, size_t subsidy_interval,
×
963
    uint64_t initial_subsidy) const NOEXCEPT
964
{
965
    const auto bip16 = ctx.is_enabled(bip16_rule);
×
966
    const auto bip42 = ctx.is_enabled(bip42_rule);
×
967
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
968

969
    // prevouts required.
970
    if (is_overspent(ctx.height, subsidy_interval, initial_subsidy, bip42))
×
971
        return error::coinbase_value_limit;
×
972
    if (is_signature_operations_limited(bip16, bip141))
×
973
        return error::block_sigop_limit;
×
974

975
    return accept_transactions(ctx);
×
976
}
977

978
// forks
979

980
// Node performs these checks through database query.
981
// This assumes that prevout and metadata caching are completed on all inputs.
982
code block::confirm(const context& ctx) const NOEXCEPT
×
983
{
984
    return confirm_transactions(ctx);
×
985
}
986

987
// forks
988

989
// This assumes that prevout caching is completed on all inputs.
990
code block::connect(const context& ctx) const NOEXCEPT
×
991
{
992
    return connect_transactions(ctx);
×
993
}
994

995
BC_POP_WARNING()
996
BC_POP_WARNING()
997

998
} // namespace chain
999
} // namespace system
1000
} // 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