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

libbitcoin / libbitcoin-system / 22113584445

17 Feb 2026 07:59PM UTC coverage: 81.187% (-0.04%) from 81.224%
22113584445

push

github

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

Add block/tx virtual_size as (ceiling_divide(weight(),4)).

0 of 6 new or added lines in 2 files covered. (0.0%)

2 existing lines in 2 files now uncovered.

10858 of 13374 relevant lines covered (81.19%)

3540905.83 hits per line

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

44.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
91✔
51
  : block(to_shared<chain::header>(), to_shared<transaction_cptrs>(), false)
182✔
52
{
53
}
91✔
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
101✔
74
  : block(stream::in::fast(data), witness)
101✔
75
{
76
}
101✔
77

78
// protected
79
block::block(stream::in::fast&& stream, bool witness) NOEXCEPT
101✔
80
  : block(read::bytes::fast(stream), witness)
101✔
81
{
82
}
101✔
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
104✔
96
  : block(source, witness)
104✔
97
{
98
}
×
99

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

107
// protected
108
block::block(const chain::header::cptr& header,
134✔
109
    const transactions_cptr& txs, bool valid) NOEXCEPT
134✔
110
  : header_(header),
111
    txs_(txs),
112
    valid_(valid),
134✔
113
    size_(serialized_size(*txs))
268✔
114
{
115
}
134✔
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
113✔
136
{
137
    auto& allocator = source.get_allocator();
113✔
138
    const auto count = source.read_size(max_block_size);
113✔
139
    auto txs = to_non_const_raw_ptr(txs_);
113✔
140
    txs->reserve(count);
113✔
141

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

145
    size_ = serialized_size(*txs_);
113✔
146
    valid_ = source;
113✔
147
}
113✔
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
×
195
{
196
    return txs_->size();
×
197
}
198

199
const chain::header& block::header() const NOEXCEPT
29✔
200
{
201
    return *header_;
2✔
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
85✔
226
{
227
    return txs_;
85✔
228
}
229

230
hashes block::transaction_hashes(bool witness) const NOEXCEPT
14✔
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();
14✔
235
    const auto size = is_odd(count) && count > one ? add1(count) : count;
14✔
236
    hashes out(size);
14✔
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
247✔
341
{
342
    sizes size{};
247✔
343
    std::for_each(txs.begin(), txs.end(), [&](const auto& tx) NOEXCEPT
539✔
344
    {
345
        size.nominal = ceilinged_add(size.nominal, tx->serialized_size(false));
584✔
346
        size.witnessed = ceilinged_add(size.witnessed,
292✔
347
            tx->serialized_size(true));
348
    });
292✔
349

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

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

356
    return { nominal_size, witnessed_size };
247✔
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());
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
// public/static (utility)
448
block::positions block::merkle_branch(size_t leaf, size_t leaves) NOEXCEPT
10✔
449
{
450
    BC_ASSERT(leaves <= power2(sub1(bits<size_t>)));
10✔
451

452
    positions branch{};
10✔
453
    if (is_zero(leaves) || leaf >= leaves)
10✔
454
        return branch;
455

456
    // Upper bound, actual count may be less due to duplication.
457
    branch.reserve(ceilinged_log2(leaves));
9✔
458

459
    for (auto width = one, current = leaves; current > one;)
109✔
460
    {
461
        const auto sibling = bit_xor(leaf, one);
100✔
462
        if (sibling < current++)
100✔
463
            branch.emplace_back(sibling, width);
97✔
464

465
        shift_left_into(width);
100✔
466
        shift_right_into(leaf);
100✔
467
        shift_right_into(current);
100✔
468
    }
469

470
    return branch;
9✔
471
}
472

473
// Accept (contextual).
474
// ----------------------------------------------------------------------------
475

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

NEW
484
size_t block::virtual_size() const NOEXCEPT
×
485
{
NEW
486
    constexpr auto scale = base_size_contribution + total_size_contribution;
×
NEW
487
    return ceilinged_divide(weight(), scale);
×
488
}
489

UNCOV
490
bool block::is_overweight() const NOEXCEPT
×
491
{
492
    return weight() > max_block_weight;
×
493
}
494

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

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

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

513
    // A set is used to collapse duplicates.
514
    unordered_set_of_hash_cref hashes(txs_->size());
×
515

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

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

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

530
    return hashes.size() > hash_limit;
×
531
}
532

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

539
bool block::is_malleated() const NOEXCEPT
×
540
{
541
    return is_malleated64() || is_malleated32();
×
542
}
543

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

552
    return false;
553
}
554

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

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

570
    return zero;
571
}
572

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

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

587
    return true;
588
}
589

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

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

605
    return !txs.empty() && std::all_of(txs.begin(), txs.end(), two_leaves);
12✔
606
}
607

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

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

624
    return std::any_of(txs_->begin(), txs_->end(), segregated);
2✔
625
}
626

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

634
    return std::count_if(txs_->begin(), txs_->end(), count_segregated);
×
635
}
636

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

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

648
    return false;
649
}
650

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

657
    const auto& inputs = *txs_->front()->inputs_ptr();
×
658
    return !inputs.empty() && inputs.front()->reserved_hash(reservation);
×
659
}
660

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

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

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

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

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

701
// Prevouts required.
702

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

712
    return std::accumulate(txs_->begin(), txs_->end(), 0_u64, value);
×
713
}
714

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

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

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

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

746
    return std::accumulate(txs_->begin(), txs_->end(), zero, value);
×
747
}
748

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

756
//*****************************************************************************
757
// CONSENSUS: check excluded under bip30 exception blocks and bip30_deactivate
758
// until bip30_reactivate. Those conditions are rolled up into the bip30 flag.
759
//*****************************************************************************
760
bool block::is_unspent_coinbase_collision() const NOEXCEPT
×
761
{
762
    if (txs_->empty() || txs_->front()->inputs_ptr()->empty())
×
763
        return false;
×
764

765
    // May only commit duplicate coinbase that is already confirmed spent.
766
    // Metadata population defaults coinbase to spent (not a collision).
767
    return !txs_->front()->inputs_ptr()->front()->metadata.spent;
×
768
}
769

770
// Search is unordered, forward refs (and duplicates) caught by block.check.
771
void block::populate() const NOEXCEPT
×
772
{
773
    if (txs_->empty())
×
774
        return;
×
775

776
    unordered_map_of_cref_point_to_output_cptr_cref points(outputs());
×
777
    uint32_t index{};
×
778

779
    // Populate outputs hash table (coinbase included).
780
    for (auto tx = txs_->begin(); tx != txs_->end(); ++tx, index = 0)
×
781
        for (const auto& out: *(*tx)->outputs_ptr())
×
782
            points.emplace(cref_point{ (*tx)->get_hash(false), index++ }, out);
×
783

784
    // Populate input prevouts from hash table.
785
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
786
    {
787
        for (const auto& in: *(*tx)->inputs_ptr())
×
788
        {
789
            // Map chain::point to cref_point for search, should optimize away.
790
            const auto point = points.find({ in->point().hash(),
×
791
                in->point().index() });
×
792

793
            if (point != points.end())
×
794
                in->prevout = point->second;
×
795
        }
796
    }
797
}
798

799
code block::populate_with_metadata(const chain::context& ctx) const NOEXCEPT
×
800
{
801
    if (txs_->empty())
×
802
        return error::block_success;
×
803

804
    const auto bip68 = ctx.is_enabled(chain::flags::bip68_rule);
×
805
    unordered_map_of_cref_point_to_output_cptr_cref points(outputs());
×
806
    uint32_t index{};
×
807

808
    // Populate outputs hash table (coinbase included).
809
    for (auto tx = txs_->begin(); tx != txs_->end(); ++tx, index = 0)
×
810
        for (const auto& out: *(*tx)->outputs_ptr())
×
811
            points.emplace(cref_point{ (*tx)->get_hash(false), index++ }, out);
×
812

813
    // Populate input prevouts from hash table and obtain maturity.
814
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
815
    {
816
        for (const auto& in: *(*tx)->inputs_ptr())
×
817
        {
818
            // Map chain::point to cref_point for search, should optimize away.
819
            const auto point = points.find({ in->point().hash(),
×
820
                in->point().index() });
×
821

822
            if (point != points.end())
×
823
            {
824
                // Zero maturity coinbase spend is immature.
825
                const auto lock = (bip68 && (*tx)->is_internally_locked(*in));
×
826
                const auto immature = !is_zero(coinbase_maturity) &&
×
827
                    (in->point().hash() == txs_->front()->get_hash(false));
×
828

829
                in->prevout = point->second;
×
830
                if ((in->metadata.locked = (immature || lock)))
×
831
                {
832
                    // Shortcircuit population and return above error.
833
                    return immature ? error::coinbase_maturity : 
×
834
                        error::relative_time_locked;
×
835
                }
836
            }
837
        }
838
    }
839

840
    return error::block_success;
×
841
}
842

843
// Delegated.
844
// ----------------------------------------------------------------------------
845

846
// DO invoke on coinbase.
847
code block::check_transactions() const NOEXCEPT
3✔
848
{
849
    for (const auto& tx: *txs_)
8✔
850
        if (const auto ec = tx->check())
5✔
851
            return ec;
×
852

853
    return error::block_success;
3✔
854
}
855

856
// DO invoke on coinbase.
857
code block::check_transactions(const context& ctx) const NOEXCEPT
×
858
{
859
    for (const auto& tx: *txs_)
×
860
        if (const auto ec = tx->check(ctx))
×
861
            return ec;
×
862

863
    return error::block_success;
×
864
}
865

866
// Do NOT invoke on coinbase.
867
code block::accept_transactions(const context& ctx) const NOEXCEPT
×
868
{
869
    if (!is_empty())
×
870
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
871
            if (const auto ec = (*tx)->accept(ctx))
×
872
                return ec;
×
873

874
    return error::block_success;
×
875
}
876

877
// Do NOT invoke on coinbase.
878
code block::connect_transactions(const context& ctx) const NOEXCEPT
×
879
{
880
    if (!is_empty())
×
881
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
882
            if (const auto ec = (*tx)->connect(ctx))
×
883
                return ec;
×
884

885
    return error::block_success;
×
886
}
887

888
// Do NOT invoke on coinbase.
889
code block::confirm_transactions(const context& ctx) const NOEXCEPT
×
890
{
891
    if (!is_empty())
×
892
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
893
            if (const auto ec = (*tx)->confirm(ctx))
×
894
                return ec;
×
895

896
    return error::block_success;
×
897
}
898

899
// Identity.
900
// ----------------------------------------------------------------------------
901

902
code block::identify() const NOEXCEPT
×
903
{
904
    if (is_malleated() || is_invalid_merkle_root())
×
905
        return error::invalid_transaction_commitment;
×
906

907
    return error::block_success;
×
908
}
909

910
// bip141 should be disabled when the node is not accepting witness data.
911
code block::identify(const context& ctx) const NOEXCEPT
×
912
{
913
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
914

915
    if (bip141 && is_invalid_witness_commitment())
×
916
        return error::invalid_witness_commitment;
×
917

918
    return error::block_success;
×
919
}
920

921
// Validation.
922
// ----------------------------------------------------------------------------
923
// In the case of validation failure
924
// The block header is checked/accepted independently.
925

926
// Use of get_hash() in is_forward_reference makes this thread-unsafe.
927
code block::check() const NOEXCEPT
3✔
928
{
929
    // empty_block is subset of first_not_coinbase.
930
    // type64 malleated is a subset of first_not_coinbase.
931
    // type32 malleated is a subset of is_internal_double_spend.
932
    if (is_oversized())
3✔
933
        return error::block_size_limit;
×
934
    if (is_first_non_coinbase())
3✔
935
        return (is_empty() ? error::empty_block :
×
936
            (is_malleated() ? error::invalid_transaction_commitment :
×
937
                error::first_not_coinbase));
×
938
    if (is_extra_coinbases())
3✔
939
        return error::extra_coinbases;
×
940
    if (is_forward_reference())
3✔
941
        return error::forward_reference;
×
942
    if (is_internal_double_spend())
3✔
943
        return is_malleated() ? error::invalid_transaction_commitment : 
×
944
            error::block_internal_double_spend;
×
945
    if (is_invalid_merkle_root())
3✔
946
        return error::invalid_transaction_commitment;
×
947

948
    return check_transactions();
3✔
949
}
950

951
// forks
952
// height
953
// timestamp
954
// median_time_past
955

956
// Use of get_hash() in is_hash_limit_exceeded makes this thread-unsafe.
957
// bip141 should be disabled when the node is not accepting witness data.
958
code block::check(const context& ctx) const NOEXCEPT
×
959
{
960
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
961
    const auto bip34 = ctx.is_enabled(bip34_rule);
×
962
    const auto bip50 = ctx.is_enabled(bip50_rule);
×
963

964
    if (bip141 && is_overweight())
×
965
        return error::block_weight_limit;
×
966
    if (bip34 && is_invalid_coinbase_script(ctx.height))
×
967
        return error::coinbase_height_mismatch;
×
968
    if (bip50 && is_hash_limit_exceeded())
×
969
        return error::temporary_hash_limit;
×
970
    if (bip141 && is_invalid_witness_commitment())
×
971
        return error::invalid_witness_commitment;
×
972

973
    return check_transactions(ctx);
×
974
}
975

976
// forks
977
// height
978

979
// This assumes that prevout caching is completed on all inputs.
980
code block::accept(const context& ctx, size_t subsidy_interval,
×
981
    uint64_t initial_subsidy) const NOEXCEPT
982
{
983
    const auto bip16 = ctx.is_enabled(bip16_rule);
×
984
    const auto bip42 = ctx.is_enabled(bip42_rule);
×
985
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
986

987
    // prevouts required.
988
    if (is_overspent(ctx.height, subsidy_interval, initial_subsidy, bip42))
×
989
        return error::coinbase_value_limit;
×
990
    if (is_signature_operations_limited(bip16, bip141))
×
991
        return error::block_sigop_limit;
×
992

993
    return accept_transactions(ctx);
×
994
}
995

996
// forks
997

998
// Node performs these checks through database query.
999
// This assumes that prevout and metadata caching are completed on all inputs.
1000
code block::confirm(const context& ctx) const NOEXCEPT
×
1001
{
1002
    const auto bip30 = ctx.is_enabled(bip30_rule);
×
1003

1004
    if (bip30 && is_unspent_coinbase_collision())
×
1005
        return error::unspent_coinbase_collision;
×
1006

1007
    return confirm_transactions(ctx);
×
1008
}
1009

1010
// forks
1011

1012
// This assumes that prevout caching is completed on all inputs.
1013
code block::connect(const context& ctx) const NOEXCEPT
×
1014
{
1015
    return connect_transactions(ctx);
×
1016
}
1017

1018
BC_POP_WARNING()
1019
BC_POP_WARNING()
1020

1021
// JSON value convertors.
1022
// ----------------------------------------------------------------------------
1023

1024
DEFINE_JSON_TO_TAG(block)
1✔
1025
{
1026
    return
1✔
1027
    {
1028
        value_to<header>(value.at("header")),
1✔
1029
        value_to<transactions>(value.at("transactions"))
2✔
1030
    };
2✔
1031
}
1032

1033
DEFINE_JSON_FROM_TAG(block)
2✔
1034
{
1035
    value =
4✔
1036
    {
1037
        { "header", value_from(instance.header()) },
2✔
1038
        { "transactions", value_from(*instance.transactions_ptr()) },
4✔
1039
    };
2✔
1040
}
2✔
1041

1042
DEFINE_JSON_TO_TAG(block::cptr)
×
1043
{
1044
    return to_shared(tag_invoke(to_tag<block>{}, value));
×
1045
}
1046

1047
DEFINE_JSON_FROM_TAG(block::cptr)
×
1048
{
1049
    tag_invoke(from_tag{}, value, *instance);
×
1050
}
×
1051

1052
} // namespace chain
1053
} // namespace system
1054
} // 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