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

libbitcoin / libbitcoin-system / 19162822888

07 Nov 2025 08:37AM UTC coverage: 81.135% (+0.1%) from 80.989%
19162822888

push

github

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

Refactor stream/reader/chain object construction.

68 of 90 new or added lines in 17 files covered. (75.56%)

1 existing line in 1 file now uncovered.

10709 of 13199 relevant lines covered (81.13%)

3587823.84 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

NEW
84
block::block(stream::in::fast& stream, bool witness) NOEXCEPT
×
NEW
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
uint64_t block::fees() const NOEXCEPT
×
673
{
674
    // Overflow returns max_uint64.
675
    const auto value = [](uint64_t total, const auto& tx) NOEXCEPT
×
676
    {
677
        return ceilinged_add(total, tx->fee());
×
678
    };
679

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

806
    return error::block_success;
×
807
}
808

809
// Delegated.
810
// ----------------------------------------------------------------------------
811

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

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

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

829
    return error::block_success;
×
830
}
831

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

840
    return error::block_success;
×
841
}
842

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

851
    return error::block_success;
×
852
}
853

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

862
    return error::block_success;
×
863
}
864

865
// Identity.
866
// ----------------------------------------------------------------------------
867

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

873
    return error::block_success;
×
874
}
875

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

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

884
    return error::block_success;
×
885
}
886

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

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

914
    return check_transactions();
3✔
915
}
916

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

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

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

939
    return check_transactions(ctx);
×
940
}
941

942
// forks
943
// height
944

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

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

959
    return accept_transactions(ctx);
×
960
}
961

962
// forks
963

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

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

973
    return confirm_transactions(ctx);
×
974
}
975

976
// forks
977

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

984
BC_POP_WARNING()
985
BC_POP_WARNING()
986

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

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

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

1008
DEFINE_JSON_TO_TAG(block::cptr)
×
1009
{
1010
    return to_shared(tag_invoke(to_tag<block>{}, value));
×
1011
}
1012

1013
DEFINE_JSON_FROM_TAG(block::cptr)
×
1014
{
1015
    tag_invoke(from_tag{}, value, *instance);
×
1016
}
×
1017

1018
} // namespace chain
1019
} // namespace system
1020
} // 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