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

libbitcoin / libbitcoin-system / 19980509087

06 Dec 2025 01:09AM UTC coverage: 81.145% (+0.01%) from 81.133%
19980509087

push

github

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

Fix block.fees() (use cb.spend, not cb.value).

11 of 13 new or added lines in 2 files covered. (84.62%)

4 existing lines in 1 file now uncovered.

10716 of 13206 relevant lines covered (81.14%)

3585940.21 hits per line

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

42.62
/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
90✔
51
  : block(to_shared<chain::header>(), to_shared<transaction_cptrs>(), false)
180✔
52
{
53
}
90✔
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
100✔
74
  : block(stream::in::fast(data), witness)
100✔
75
{
76
}
100✔
77

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

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

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

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

145
    size_ = serialized_size(*txs_);
112✔
146
    valid_ = source;
112✔
147
}
112✔
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
28✔
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
    const auto count = txs_->size();
14✔
233
    const auto size = is_odd(count) && count > one ? add1(count) : count;
14✔
234
    hashes out{ size };
14✔
235

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

357
    return { nominal_size, witnessed_size };
245✔
358
}
359

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

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

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

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

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

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

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

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

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

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

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

417
    return false;
418
}
419

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

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

434
    return false;
435
}
436

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

521
    return false;
522
}
523

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

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

539
    return zero;
540
}
541

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

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

556
    return true;
557
}
558

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

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

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

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

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

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

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

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

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

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

617
    return false;
618
}
619

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

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

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

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

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

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

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

670
// Prevouts required.
671

672
// The fees() is the sum of all transaction fees (coinbase is zero).
UNCOV
673
uint64_t block::fees() const NOEXCEPT
×
674
{
675
    // Overflow returns max_uint64.
UNCOV
676
    const auto value = [](uint64_t total, const auto& tx) NOEXCEPT
×
677
    {
678
        return ceilinged_add(total, tx->fee());
×
679
    };
680

NEW
681
    return std::accumulate(txs_->begin(), txs_->end(), 0_u64, value);
×
682
}
683

684
// The claim() is the spend of the coinbase transaction.
UNCOV
685
uint64_t block::claim() const NOEXCEPT
×
686
{
NEW
687
    return txs_->empty() ? zero : txs_->front()->spend();
×
688
}
689

690
// The reward() is the sum of all transaction.fee() and the block subsidy.
UNCOV
691
uint64_t block::reward(size_t height, uint64_t subsidy_interval,
×
692
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
693
{
694
    // Overflow returns max_uint64.
695
    return ceilinged_add(fees(), block_subsidy(height, subsidy_interval,
×
696
        initial_block_subsidy_satoshi, bip42));
×
697
}
698

699
bool block::is_overspent(size_t height, uint64_t subsidy_interval,
×
700
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
701
{
702
    return claim() > reward(height, subsidy_interval,
×
703
        initial_block_subsidy_satoshi, bip42);
×
704
}
705

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

715
    return std::accumulate(txs_->begin(), txs_->end(), zero, value);
×
716
}
717

718
bool block::is_signature_operations_limited(bool bip16,
×
719
    bool bip141) const NOEXCEPT
720
{
721
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
722
    return signature_operations(bip16, bip141) > limit;
×
723
}
724

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

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

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

745
    unordered_map_of_cref_point_to_output_cptr_cref points{ outputs() };
×
746
    uint32_t index{};
×
747

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

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

762
            if (point != points.end())
×
763
                in->prevout = point->second;
×
764
        }
765
    }
766
}
767

768
code block::populate_with_metadata(const chain::context& ctx) const NOEXCEPT
×
769
{
770
    if (txs_->empty())
×
771
        return error::block_success;
×
772

773
    const auto bip68 = ctx.is_enabled(chain::flags::bip68_rule);
×
774
    unordered_map_of_cref_point_to_output_cptr_cref points{ outputs() };
×
775
    uint32_t index{};
×
776

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

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

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

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

809
    return error::block_success;
×
810
}
811

812
// Delegated.
813
// ----------------------------------------------------------------------------
814

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

822
    return error::block_success;
3✔
823
}
824

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

832
    return error::block_success;
×
833
}
834

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

843
    return error::block_success;
×
844
}
845

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

854
    return error::block_success;
×
855
}
856

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

865
    return error::block_success;
×
866
}
867

868
// Identity.
869
// ----------------------------------------------------------------------------
870

871
code block::identify() const NOEXCEPT
×
872
{
873
    if (is_malleated() || is_invalid_merkle_root())
×
874
        return error::invalid_transaction_commitment;
×
875

876
    return error::block_success;
×
877
}
878

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

884
    if (bip141 && is_invalid_witness_commitment())
×
885
        return error::invalid_witness_commitment;
×
886

887
    return error::block_success;
×
888
}
889

890
// Validation.
891
// ----------------------------------------------------------------------------
892
// In the case of validation failure
893
// The block header is checked/accepted independently.
894

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

917
    return check_transactions();
3✔
918
}
919

920
// forks
921
// height
922
// timestamp
923
// median_time_past
924

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

933
    if (bip141 && is_overweight())
×
934
        return error::block_weight_limit;
×
935
    if (bip34 && is_invalid_coinbase_script(ctx.height))
×
936
        return error::coinbase_height_mismatch;
×
937
    if (bip50 && is_hash_limit_exceeded())
×
938
        return error::temporary_hash_limit;
×
939
    if (bip141 && is_invalid_witness_commitment())
×
940
        return error::invalid_witness_commitment;
×
941

942
    return check_transactions(ctx);
×
943
}
944

945
// forks
946
// height
947

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

956
    // prevouts required.
957
    if (is_overspent(ctx.height, subsidy_interval, initial_subsidy, bip42))
×
958
        return error::coinbase_value_limit;
×
959
    if (is_signature_operations_limited(bip16, bip141))
×
960
        return error::block_sigop_limit;
×
961

962
    return accept_transactions(ctx);
×
963
}
964

965
// forks
966

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

973
    if (bip30 && is_unspent_coinbase_collision())
×
974
        return error::unspent_coinbase_collision;
×
975

976
    return confirm_transactions(ctx);
×
977
}
978

979
// forks
980

981
// This assumes that prevout caching is completed on all inputs.
982
code block::connect(const context& ctx) const NOEXCEPT
×
983
{
984
    return connect_transactions(ctx);
×
985
}
986

987
BC_POP_WARNING()
988
BC_POP_WARNING()
989

990
// JSON value convertors.
991
// ----------------------------------------------------------------------------
992

993
DEFINE_JSON_TO_TAG(block)
1✔
994
{
995
    return
1✔
996
    {
997
        value_to<header>(value.at("header")),
1✔
998
        value_to<transactions>(value.at("transactions"))
2✔
999
    };
2✔
1000
}
1001

1002
DEFINE_JSON_FROM_TAG(block)
2✔
1003
{
1004
    value =
4✔
1005
    {
1006
        { "header", value_from(instance.header()) },
2✔
1007
        { "transactions", value_from(*instance.transactions_ptr()) },
4✔
1008
    };
2✔
1009
}
2✔
1010

1011
DEFINE_JSON_TO_TAG(block::cptr)
×
1012
{
1013
    return to_shared(tag_invoke(to_tag<block>{}, value));
×
1014
}
1015

1016
DEFINE_JSON_FROM_TAG(block::cptr)
×
1017
{
1018
    tag_invoke(from_tag{}, value, *instance);
×
1019
}
×
1020

1021
} // namespace chain
1022
} // namespace system
1023
} // 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