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

libbitcoin / libbitcoin-system / 14161486650

31 Mar 2025 12:25AM UTC coverage: 82.917%. Remained the same
14161486650

push

github

evoskuil
Comments.

10159 of 12252 relevant lines covered (82.92%)

3834696.19 hits per line

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

43.7
/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 <type_traits>
27
#include <utility>
28
#include <bitcoin/system/chain/context.hpp>
29
#include <bitcoin/system/chain/enums/flags.hpp>
30
#include <bitcoin/system/chain/enums/magic_numbers.hpp>
31
#include <bitcoin/system/chain/enums/opcode.hpp>
32
#include <bitcoin/system/chain/point.hpp>
33
#include <bitcoin/system/chain/script.hpp>
34
#include <bitcoin/system/data/data.hpp>
35
#include <bitcoin/system/define.hpp>
36
#include <bitcoin/system/error/error.hpp>
37
#include <bitcoin/system/hash/hash.hpp>
38
#include <bitcoin/system/math/math.hpp>
39
#include <bitcoin/system/stream/stream.hpp>
40

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

45
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
46
BC_PUSH_WARNING(NO_UNGUARDED_POINTERS)
47

48
// Constructors.
49
// ----------------------------------------------------------------------------
50

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

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

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

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

75
block::block(const data_slice& data, bool witness) NOEXCEPT
98✔
76
  : block(stream::in::copy(data), witness)
98✔
77
{
78
}
98✔
79

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

85
block::block(stream::in::fast& stream, bool witness) NOEXCEPT
×
86
  : block(read::bytes::fast(stream), witness)
×
87
{
88
}
×
89

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

95
block::block(std::istream& stream, bool witness) NOEXCEPT
3✔
96
  : block(read::bytes::istream(stream), witness)
3✔
97
{
98
}
3✔
99

100
block::block(reader&& source, bool witness) NOEXCEPT
101✔
101
  : block(source, witness)
101✔
102
{
103
}
×
104

105
block::block(reader& source, bool witness) NOEXCEPT
107✔
106
  : header_(CREATE(chain::header, source.get_allocator(), source)),
107✔
107
    txs_(CREATE(transaction_cptrs, source.get_allocator()))
214✔
108
{
109
    assign_data(source, witness);
107✔
110
}
107✔
111

112
// protected
113
block::block(const chain::header::cptr& header,
131✔
114
    const transactions_cptr& txs, bool valid) NOEXCEPT
131✔
115
  : header_(header),
116
    txs_(txs),
117
    valid_(valid),
131✔
118
    size_(serialized_size(*txs))
262✔
119
{
120
}
131✔
121

122
// Operators.
123
// ----------------------------------------------------------------------------
124

125
bool block::operator==(const block& other) const NOEXCEPT
29✔
126
{
127
    return (header_ == other.header_ || *header_ == *other.header_)
29✔
128
        && deep_equal(*txs_, *other.txs_);
47✔
129
}
130

131
bool block::operator!=(const block& other) const NOEXCEPT
5✔
132
{
133
    return !(*this == other);
5✔
134
}
135

136
// Deserialization.
137
// ----------------------------------------------------------------------------
138

139
// private
140
void block::assign_data(reader& source, bool witness) NOEXCEPT
107✔
141
{
142
    auto& allocator = source.get_allocator();
107✔
143
    const auto count = source.read_size(max_block_size);
107✔
144
    auto txs = to_non_const_raw_ptr(txs_);
107✔
145
    txs->reserve(count);
107✔
146

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

150
    size_ = serialized_size(*txs_);
107✔
151
    valid_ = source;
107✔
152
}
107✔
153

154
void block::set_allocation(size_t allocation) const NOEXCEPT
×
155
{
156
    allocation_ = allocation;
×
157
}
×
158

159
size_t block::get_allocation() const NOEXCEPT
×
160
{
161
    return allocation_;
×
162
}
163

164
// Serialization.
165
// ----------------------------------------------------------------------------
166

167
data_chunk block::to_data(bool witness) const NOEXCEPT
20✔
168
{
169
    data_chunk data(serialized_size(witness));
40✔
170
    stream::out::copy ostream(data);
20✔
171
    to_data(ostream, witness);
20✔
172
    return data;
20✔
173
}
20✔
174

175
void block::to_data(std::ostream& stream, bool witness) const NOEXCEPT
21✔
176
{
177
    write::bytes::ostream out(stream);
21✔
178
    to_data(out, witness);
21✔
179
}
21✔
180

181
void block::to_data(writer& sink, bool witness) const NOEXCEPT
22✔
182
{
183
    header_->to_data(sink);
22✔
184
    sink.write_variable(txs_->size());
22✔
185

186
    for (const auto& tx: *txs_)
49✔
187
        tx->to_data(sink, witness);
27✔
188
}
22✔
189

190
// Properties.
191
// ----------------------------------------------------------------------------
192

193
bool block::is_valid() const NOEXCEPT
59✔
194
{
195
    return valid_;
59✔
196
}
197

198
size_t block::transactions() const NOEXCEPT
×
199
{
200
    return txs_->size();
×
201
}
202

203
const chain::header& block::header() const NOEXCEPT
12✔
204
{
205
    return *header_;
2✔
206
}
207

208
const chain::header::cptr block::header_ptr() const NOEXCEPT
×
209
{
210
    return header_;
×
211
}
212

213
// Roll up inputs for concurrent prevout processing.
214
const inputs_cptr block::inputs_ptr() const NOEXCEPT
×
215
{
216
    const auto inputs = std::make_shared<input_cptrs>();
×
217
    const auto append_ins = [&inputs](const auto& tx) NOEXCEPT
×
218
    {
219
        const auto& tx_ins = tx->inputs_ptr();
×
220
        inputs->insert(inputs->end(), tx_ins->begin(), tx_ins->end());
×
221
    };
×
222

223
    std::for_each(txs_->begin(), txs_->end(), append_ins);
×
224
    return inputs;
×
225
}
226

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

234
hashes block::transaction_hashes(bool witness) const NOEXCEPT
14✔
235
{
236
    const auto count = txs_->size();
14✔
237
    const auto size = is_odd(count) && count > one ? add1(count) : count;
14✔
238
    hashes out{ size };
14✔
239

240
    // Extra allocation for odd count optimizes for merkle root.
241
    // Vector capacity is never reduced when resizing to smaller size.
242
    out.resize(count);
14✔
243

244
    const auto hash = [witness](const auto& tx) NOEXCEPT
19✔
245
    {
246
        return tx->hash(witness);
19✔
247
    };
14✔
248

249
    std::transform(txs_->begin(), txs_->end(), out.begin(), hash);
14✔
250
    return out;
14✔
251
}
252

253
// computed
254
size_t block::outputs() const NOEXCEPT
×
255
{
256
    if (txs_->empty())
×
257
        return zero;
258

259
    // Overflow returns max_size_t.
260
    const auto outs = [](size_t total, const auto& tx) NOEXCEPT
×
261
    {
262
         return ceilinged_add(total, tx->outputs());
×
263
    };
264

265
    return std::accumulate(std::next(txs_->begin()), txs_->end(), zero, outs);
×
266
}
267

268
// computed
269
size_t block::spends() const NOEXCEPT
7✔
270
{
271
    if (txs_->empty())
7✔
272
        return zero;
273

274
    // Overflow returns max_size_t.
275
    const auto ins = [](size_t total, const auto& tx) NOEXCEPT
11✔
276
    {
277
         return ceilinged_add(total, tx->inputs());
11✔
278
    };
279

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

284
// computed
285
hash_digest block::hash() const NOEXCEPT
38✔
286
{
287
    return header_->hash();
38✔
288
}
289

290
// computed
291
const hash_digest& block::get_hash() const NOEXCEPT
×
292
{
293
    return header_->get_hash();
×
294
}
295

296
void block::set_hashes(const data_chunk& data) NOEXCEPT
×
297
{
298
    constexpr auto header_size = chain::header::serialized_size();
×
299

300
    // Cache header hash.
301
    header_->set_hash(bitcoin_hash(header_size, data.data()));
×
302

303
    // Skip transaction count, guarded by preceding successful block construct.
304
    auto start = std::next(data.data(), header_size);
×
305
    std::advance(start, size_variable(*start));
×
306

307
    // Cache transaction hashes.
308
    auto coinbase = true;
×
309
    for (const auto& tx: *txs_)
×
310
    {
311
        const auto witness_size = tx->serialized_size(true);
×
312

313
        // If !witness then wire txs cannot have been segregated.
314
        if (tx->is_segregated())
×
315
        {
316
            const auto nominal_size = tx->serialized_size(false);
×
317

318
            tx->set_nominal_hash(transaction::desegregated_hash(
×
319
                witness_size, nominal_size, start));
320

321
            if (!coinbase)
×
322
                tx->set_witness_hash(bitcoin_hash(witness_size, start));
×
323
        }
324
        else
325
        {
326
            tx->set_nominal_hash(bitcoin_hash(witness_size, start));
×
327
        }
328

329
        coinbase = false;
×
330
        std::advance(start, witness_size);
×
331
    }
332
}
×
333

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

344
    const auto base_size = ceilinged_add(header::serialized_size(),
238✔
345
        variable_size(txs.size()));
346

347
    const auto nominal_size = ceilinged_add(base_size, size.nominal);
238✔
348
    const auto witnessed_size = ceilinged_add(base_size, size.witnessed);
238✔
349

350
    return { nominal_size, witnessed_size };
238✔
351
}
352

353
size_t block::serialized_size(bool witness) const NOEXCEPT
24✔
354
{
355
    return witness ? size_.witnessed : size_.nominal;
21✔
356
}
357

358
// Check (context free).
359
// ----------------------------------------------------------------------------
360

361
bool block::is_empty() const NOEXCEPT
2✔
362
{
363
    return txs_->empty();
2✔
364
}
365

366
bool block::is_oversized() const NOEXCEPT
3✔
367
{
368
    return serialized_size(false) > max_block_size;
3✔
369
}
370

371
bool block::is_first_non_coinbase() const NOEXCEPT
3✔
372
{
373
    return !txs_->empty() && !txs_->front()->is_coinbase();
3✔
374
}
375

376
// True if there is another coinbase other than the first tx.
377
// No txs or coinbases returns false.
378
bool block::is_extra_coinbases() const NOEXCEPT
3✔
379
{
380
    if (txs_->empty())
3✔
381
        return false;
382

383
    const auto value = [](const auto& tx) NOEXCEPT
2✔
384
    {
385
        return tx->is_coinbase();
2✔
386
    };
387

388
    return std::any_of(std::next(txs_->begin()), txs_->end(), value);
3✔
389
}
390

391
//*****************************************************************************
392
// CONSENSUS: This is only necessary because satoshi stores and queries as it
393
// validates, imposing an otherwise unnecessary partial transaction ordering.
394
//*****************************************************************************
395
bool block::is_forward_reference() const NOEXCEPT
8✔
396
{
397
    if (txs_->empty())
8✔
398
        return false;
399

400
    unordered_set_of_hash_cref hashes{ sub1(txs_->size()) };
7✔
401
    for (auto tx = txs_->rbegin(); tx != std::prev(txs_->rend()); ++tx)
13✔
402
    {
403
        for (const auto& in: *(*tx)->inputs_ptr())
10✔
404
            if (hashes.contains(in->point().hash()))
4✔
405
                return true;
406

407
        hashes.emplace((*tx)->get_hash(false));
6✔
408
    }
409

410
    return false;
411
}
412

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

421
    unordered_set_of_point_cref points{ spends() };
5✔
422
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
13✔
423
        for (const auto& in: *(*tx)->inputs_ptr())
17✔
424
            if (!points.emplace(in->point()).second)
18✔
425
                return true;
426

427
    return false;
428
}
429

430
// private
431
hash_digest block::generate_merkle_root(bool witness) const NOEXCEPT
14✔
432
{
433
    return sha256::merkle_root(transaction_hashes(witness));
28✔
434
}
435

436
bool block::is_invalid_merkle_root() const NOEXCEPT
14✔
437
{
438
    return generate_merkle_root(false) != header_->merkle_root();
14✔
439
}
440

441
// Accept (contextual).
442
// ----------------------------------------------------------------------------
443

444
size_t block::weight() const NOEXCEPT
×
445
{
446
    // Block weight is 3 * nominal size * + 1 * witness size (bip141).
447
    return ceilinged_add(
×
448
        ceilinged_multiply(base_size_contribution, serialized_size(false)),
449
        ceilinged_multiply(total_size_contribution, serialized_size(true)));
×
450
}
451

452
bool block::is_overweight() const NOEXCEPT
×
453
{
454
    return weight() > max_block_weight;
×
455
}
456

457
bool block::is_invalid_coinbase_script(size_t height) const NOEXCEPT
×
458
{
459
    if (txs_->empty() || txs_->front()->inputs_ptr()->empty())
×
460
        return false;
×
461

462
    const auto& script = txs_->front()->inputs_ptr()->front()->script();
×
463
    return !script::is_coinbase_pattern(script.ops(), height);
×
464
}
465

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

475
    // A set is used to collapse duplicates.
476
    unordered_set_of_hash_cref hashes{ txs_->size() };
×
477

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

481
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
482
    {
483
        // Insert the transaction hash.
484
        hashes.emplace((*tx)->get_hash(false));
×
485
        const auto& inputs = (*tx)->inputs_ptr();
×
486

487
        // Insert all input point hashes.
488
        for (const auto& input: *inputs)
×
489
            hashes.emplace(input->point().hash());
×
490
    }
491

492
    return hashes.size() > hash_limit;
×
493
}
494

495
// Malleability does not imply malleated.
496
bool block::is_malleable() const NOEXCEPT
3✔
497
{
498
    return is_malleable64() || is_malleable32();
3✔
499
}
500

501
bool block::is_malleated() const NOEXCEPT
×
502
{
503
    return is_malleated64() || is_malleated32();
×
504
}
505

506
// Malleability does not imply malleated.
507
bool block::is_malleable32() const NOEXCEPT
12✔
508
{
509
    const auto unmalleated = txs_->size();
12✔
510
    for (auto mally = one; mally <= unmalleated; mally *= two)
23✔
511
        if (is_malleable32(unmalleated, mally))
17✔
512
            return true;
513

514
    return false;
515
}
516

517
// Malleated32 implies malleable and invalid due to internal tx hash pairing.
518
bool block::is_malleated32() const NOEXCEPT
11✔
519
{
520
    return !is_zero(malleated32_size());
11✔
521
}
522

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

532
    return zero;
533
}
534

535
// protected
536
// True if the last width set of tx hashes repeats.
537
bool block::is_malleated32(size_t width) const NOEXCEPT
7✔
538
{
539
    const auto malleated = txs_->size();
7✔
540
    if (is_zero(width) || width > to_half(malleated))
7✔
541
        return false;
542

543
    auto mally = txs_->rbegin();
6✔
544
    auto legit = std::next(mally, width);
6✔
545
    while (!is_zero(width--))
9✔
546
        if ((*mally++)->get_hash(false) != (*legit++)->get_hash(false))
7✔
547
            return false;
548

549
    return true;
550
}
551

552
// Malleability does not imply malleated.
553
bool block::is_malleable64() const NOEXCEPT
12✔
554
{
555
    return is_malleable64(*txs_);
12✔
556
}
557

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

567
    return !txs.empty() && std::all_of(txs.begin(), txs.end(), two_leaves);
12✔
568
}
569

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

579
bool block::is_segregated() const NOEXCEPT
2✔
580
{
581
    const auto segregated = [](const auto& tx) NOEXCEPT
4✔
582
    {
583
        return tx->is_segregated();
4✔
584
    };
585

586
    return std::any_of(txs_->begin(), txs_->end(), segregated);
2✔
587
}
588

589
size_t block::segregated() const NOEXCEPT
×
590
{
591
    const auto count_segregated = [](const auto& tx) NOEXCEPT
×
592
    {
593
        return tx->is_segregated();
×
594
    };
595

596
    return std::count_if(txs_->begin(), txs_->end(), count_segregated);
×
597
}
598

599
// The witness merkle root is obtained from wtxids, subject to malleation just
600
// as the txs commitment. However, since tx duplicates are precluded by the
601
// malleable32 (or complete) block check, there is no opportunity for this.
602
// Similarly the witness commitment cannot be malleable64.
603
bool block::is_invalid_witness_commitment() const NOEXCEPT
×
604
{
605
    if (txs_->empty())
×
606
        return false;
607

608
    const auto& coinbase = txs_->front();
×
609
    if (coinbase->inputs_ptr()->empty())
×
610
        return false;
611

612
    // If no block tx has witness data the commitment is optional (bip141).
613
    if (!is_segregated())
×
614
        return false;
615

616
    // If there is a valid commitment, return false (valid).
617
    // Coinbase input witness must be 32 byte witness reserved value (bip141).
618
    // Last output of commitment pattern holds the committed value (bip141).
619
    hash_digest reserved{}, committed{};
×
620
    if (coinbase->inputs_ptr()->front()->reserved_hash(reserved))
×
621
        for (const auto& output: std::views::reverse(*coinbase->outputs_ptr()))
×
622
            if (output->committed_hash(committed))
×
623
                if (committed == sha256::double_hash(
×
624
                    generate_merkle_root(true), reserved))
×
625
                    return false;
626

627
    return true;
628
}
629

630
//*****************************************************************************
631
// CONSENSUS:
632
// bip42 compensates for C++ undefined behavior of a right shift of a number of
633
// bits greater or equal to the shifted integer width. Yet being undefined, the
634
// result of this operation may vary by compiler. The shift_right call below
635
// explicitly implements presumed pre-bip42 behavior (shift overflow modulo) by
636
// default, and specified bip42 behavior (shift overflow to zero) with bip42.
637
//*****************************************************************************
638
static uint64_t block_subsidy(size_t height, uint64_t subsidy_interval,
×
639
    uint64_t initial_block_subsidy_satoshi, bool bip42) NOEXCEPT
640
{
641
    // Guard: quotient domain cannot increase with positive integer divisor.
642
    const auto halves = possible_narrow_cast<size_t>(height / subsidy_interval);
×
643
    return shift_right(initial_block_subsidy_satoshi, halves, bip42);
×
644
}
645

646
// Prevouts required.
647

648
uint64_t block::fees() const NOEXCEPT
×
649
{
650
    // Overflow returns max_uint64.
651
    const auto value = [](uint64_t total, const auto& tx) NOEXCEPT
×
652
    {
653
        return ceilinged_add(total, tx->fee());
×
654
    };
655

656
    return std::accumulate(txs_->begin(), txs_->end(), uint64_t{}, value);
×
657
}
658

659
uint64_t block::claim() const NOEXCEPT
×
660
{
661
    return txs_->empty() ? zero : txs_->front()->value();
×
662
}
663

664
uint64_t block::reward(size_t height, uint64_t subsidy_interval,
×
665
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
666
{
667
    // Overflow returns max_uint64.
668
    return ceilinged_add(fees(), block_subsidy(height, subsidy_interval,
×
669
        initial_block_subsidy_satoshi, bip42));
×
670
}
671

672
bool block::is_overspent(size_t height, uint64_t subsidy_interval,
×
673
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
674
{
675
    return claim() > reward(height, subsidy_interval,
×
676
        initial_block_subsidy_satoshi, bip42);
×
677
}
678

679
size_t block::signature_operations(bool bip16, bool bip141) const NOEXCEPT
×
680
{
681
    // Overflow returns max_size_t.
682
    const auto value = [=](size_t total, const auto& tx) NOEXCEPT
×
683
    {
684
        return ceilinged_add(total, tx->signature_operations(bip16, bip141));
×
685
    };
×
686

687
    return std::accumulate(txs_->begin(), txs_->end(), zero, value);
×
688
}
689

690
bool block::is_signature_operations_limited(bool bip16,
×
691
    bool bip141) const NOEXCEPT
692
{
693
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
694
    return signature_operations(bip16, bip141) > limit;
×
695
}
696

697
//*****************************************************************************
698
// CONSENSUS:
699
// This check is excluded under two bip30 exception blocks and bip30_deactivate
700
// until bip30_reactivate. These conditions are rolled up into the bip30 flag.
701
//*****************************************************************************
702
bool block::is_unspent_coinbase_collision() const NOEXCEPT
×
703
{
704
    if (txs_->empty() || txs_->front()->inputs_ptr()->empty())
×
705
        return false;
×
706

707
    // May only commit duplicate coinbase that is already confirmed spent.
708
    // Metadata population defaults coinbase to spent (not a collision).
709
    return !txs_->front()->inputs_ptr()->front()->metadata.spent;
×
710
}
711

712
// Search is unordered, forward refs (and duplicates) caught by block.check.
713
void block::populate() const NOEXCEPT
×
714
{
715
    if (txs_->empty())
×
716
        return;
×
717

718
    unordered_map_of_cref_point_to_output_cptr_cref points{ outputs() };
×
719
    uint32_t index{};
×
720

721
    // Populate outputs hash table (coinbase included).
722
    for (auto tx = txs_->begin(); tx != txs_->end(); ++tx, index = 0)
×
723
        for (const auto& out: *(*tx)->outputs_ptr())
×
724
            points.emplace(cref_point{ (*tx)->get_hash(false), index++ }, out);
×
725

726
    // Populate input prevouts from hash table.
727
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
728
    {
729
        for (const auto& in: *(*tx)->inputs_ptr())
×
730
        {
731
            // Map chain::point to cref_point for search, should optimize away.
732
            const auto point = points.find({ in->point().hash(),
×
733
                in->point().index() });
×
734

735
            if (point != points.end())
×
736
                in->prevout = point->second;
×
737
        }
738
    }
739
}
740

741
code block::populate_with_metadata(const chain::context& ctx) const NOEXCEPT
×
742
{
743
    if (txs_->empty())
×
744
        return error::block_success;
×
745

746
    const auto bip68 = ctx.is_enabled(chain::flags::bip68_rule);
×
747
    unordered_map_of_cref_point_to_output_cptr_cref points{ outputs() };
×
748
    uint32_t index{};
×
749

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

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

764
            if (point != points.end())
×
765
            {
766
                // Zero maturity coinbase spend is immature.
767
                const auto lock = (bip68 && (*tx)->is_internally_locked(*in));
×
768
                const auto immature = !is_zero(coinbase_maturity) &&
×
769
                    (in->point().hash() == txs_->front()->get_hash(false));
×
770

771
                in->prevout = point->second;
×
772
                if ((in->metadata.locked = (immature || lock)))
×
773
                {
774
                    // Shortcircuit population and return above error.
775
                    return immature ? error::coinbase_maturity : 
×
776
                        error::relative_time_locked;
×
777
                }
778
            }
779
        }
780
    }
781

782
    return error::block_success;
×
783
}
784

785
// Delegated.
786
// ----------------------------------------------------------------------------
787

788
// DO invoke on coinbase.
789
code block::check_transactions() const NOEXCEPT
3✔
790
{
791
    for (const auto& tx: *txs_)
8✔
792
        if (const auto ec = tx->check())
5✔
793
            return ec;
×
794

795
    return error::block_success;
3✔
796
}
797

798
// DO invoke on coinbase.
799
code block::check_transactions(const context& ctx) const NOEXCEPT
×
800
{
801
    for (const auto& tx: *txs_)
×
802
        if (const auto ec = tx->check(ctx))
×
803
            return ec;
×
804

805
    return error::block_success;
×
806
}
807

808
// Do NOT invoke on coinbase.
809
code block::accept_transactions(const context& ctx) const NOEXCEPT
×
810
{
811
    if (!is_empty())
×
812
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
813
            if (const auto ec = (*tx)->accept(ctx))
×
814
                return ec;
×
815

816
    return error::block_success;
×
817
}
818

819
// Do NOT invoke on coinbase.
820
code block::connect_transactions(const context& ctx) const NOEXCEPT
×
821
{
822
    if (!is_empty())
×
823
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
824
            if (const auto ec = (*tx)->connect(ctx))
×
825
                return ec;
×
826

827
    return error::block_success;
×
828
}
829

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

838
    return error::block_success;
×
839
}
840

841
// Identity.
842
// ----------------------------------------------------------------------------
843
// invalid_transaction_commitment, invalid_witness_commitment, block_malleated
844
// codes specifically indicate lack of block hash tx identification (identity).
845

846
code block::identify() const NOEXCEPT
×
847
{
848
    // type64 malleated is a subset of first_not_coinbase.
849
    // type32 malleated is a subset of is_internal_double_spend.
850
    if (is_malleated())
×
851
        return error::block_malleated;
×
852
    if (is_invalid_merkle_root())
×
853
        return error::invalid_transaction_commitment;
×
854

855
    return error::block_success;
×
856
}
857

858
code block::identify(const context& ctx) const NOEXCEPT
×
859
{
860
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
861

862
    if (bip141 && is_invalid_witness_commitment())
×
863
        return error::invalid_witness_commitment;
×
864

865
    return error::block_success;
×
866
}
867

868
// Validation.
869
// ----------------------------------------------------------------------------
870
// In the case of validation failure
871
// The block header is checked/accepted independently.
872

873
// TODO: use of get_hash() in is_forward_reference makes this thread unsafe.
874
code block::check() const NOEXCEPT
3✔
875
{
876
    // empty_block is subset of first_not_coinbase.
877
    //if (is_empty())
878
    //    return error::empty_block;
879
    if (is_oversized())
3✔
880
        return error::block_size_limit;
×
881
    if (is_first_non_coinbase())
3✔
882
        return error::first_not_coinbase;
×
883
    if (is_extra_coinbases())
3✔
884
        return error::extra_coinbases;
×
885
    if (is_forward_reference())
3✔
886
        return error::forward_reference;
×
887
    if (is_internal_double_spend())
3✔
888
        return error::block_internal_double_spend;
×
889
    if (is_invalid_merkle_root())
3✔
890
        return error::invalid_transaction_commitment;
×
891

892
    return check_transactions();
3✔
893
}
894

895
// forks
896
// height
897
// timestamp
898
// median_time_past
899

900
// TODO: use of get_hash() in is_hash_limit_exceeded makes this thread unsafe.
901
code block::check(const context& ctx) const NOEXCEPT
×
902
{
903
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
904
    const auto bip34 = ctx.is_enabled(bip34_rule);
×
905
    const auto bip50 = ctx.is_enabled(bip50_rule);
×
906

907
    if (bip141 && is_overweight())
×
908
        return error::block_weight_limit;
×
909
    if (bip34 && is_invalid_coinbase_script(ctx.height))
×
910
        return error::coinbase_height_mismatch;
×
911
    if (bip50 && is_hash_limit_exceeded())
×
912
        return error::temporary_hash_limit;
×
913
    if (bip141 && is_invalid_witness_commitment())
×
914
        return error::invalid_witness_commitment;
×
915

916
    return check_transactions(ctx);
×
917
}
918

919
// forks
920
// height
921

922
// This assumes that prevout caching is completed on all inputs.
923
code block::accept(const context& ctx, size_t subsidy_interval,
×
924
    uint64_t initial_subsidy) const NOEXCEPT
925
{
926
    const auto bip16 = ctx.is_enabled(bip16_rule);
×
927
    const auto bip42 = ctx.is_enabled(bip42_rule);
×
928
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
929

930
    // prevouts required.
931
    if (is_overspent(ctx.height, subsidy_interval, initial_subsidy, bip42))
×
932
        return error::coinbase_value_limit;
×
933
    if (is_signature_operations_limited(bip16, bip141))
×
934
        return error::block_sigop_limit;
×
935

936
    return accept_transactions(ctx);
×
937
}
938

939
// forks
940

941
// Node performs these checks through database query.
942
// This assumes that prevout and metadata caching are completed on all inputs.
943
code block::confirm(const context& ctx) const NOEXCEPT
×
944
{
945
    const auto bip30 = ctx.is_enabled(bip30_rule);
×
946

947
    if (bip30 && is_unspent_coinbase_collision())
×
948
        return error::unspent_coinbase_collision;
×
949

950
    return confirm_transactions(ctx);
×
951
}
952

953
// forks
954

955
// This assumes that prevout caching is completed on all inputs.
956
code block::connect(const context& ctx) const NOEXCEPT
×
957
{
958
    return connect_transactions(ctx);
×
959
}
960

961
BC_POP_WARNING()
962
BC_POP_WARNING()
963

964
// JSON value convertors.
965
// ----------------------------------------------------------------------------
966

967
namespace json = boost::json;
968

969
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
970
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
971

972
block tag_invoke(json::value_to_tag<block>,
1✔
973
    const json::value& value) NOEXCEPT
974
{
975
    return
1✔
976
    {
977
        json::value_to<header>(value.at("header")),
1✔
978
        json::value_to<chain::transactions>(value.at("transactions"))
2✔
979
    };
2✔
980
}
981

982
void tag_invoke(json::value_from_tag, json::value& value,
2✔
983
    const block& block) NOEXCEPT
984
{
985
    value =
2✔
986
    {
987
        { "header", block.header() },
988
        { "transactions", *block.transactions_ptr() },
989
    };
2✔
990
}
2✔
991

992
BC_POP_WARNING()
993

994
block::cptr tag_invoke(json::value_to_tag<block::cptr>,
×
995
    const json::value& value) NOEXCEPT
996
{
997
    return to_shared(tag_invoke(json::value_to_tag<block>{}, value));
×
998
}
999

1000
// Shared pointer overload is required for navigation.
1001
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
1002
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
1003

1004
void tag_invoke(json::value_from_tag tag, json::value& value,
×
1005
    const block::cptr& block) NOEXCEPT
1006
{
1007
    tag_invoke(tag, value, *block);
×
1008
}
×
1009

1010
BC_POP_WARNING()
1011
BC_POP_WARNING()
1012

1013
} // namespace chain
1014
} // namespace system
1015
} // 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