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

libbitcoin / libbitcoin-system / 12739695152

13 Jan 2025 02:44AM UTC coverage: 82.969% (-0.1%) from 83.098%
12739695152

push

github

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

Optimize populate by avoiding hash copies, normalize ref optimizations.

14 of 40 new or added lines in 6 files covered. (35.0%)

2 existing lines in 1 file now uncovered.

10065 of 12131 relevant lines covered (82.97%)

4721517.14 hits per line

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

48.48
/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 <memory>
24
#include <numeric>
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
64✔
52
  : block(to_shared<chain::header>(), to_shared<transaction_cptrs>(),
64✔
53
      false)
192✔
54
{
55
}
64✔
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
74✔
76
  : block(stream::in::copy(data), witness)
74✔
77
{
78
}
74✔
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
74✔
91
  : block(read::bytes::istream(stream), witness)
74✔
92
{
93
}
74✔
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
77✔
101
  : block(source, witness)
77✔
102
{
103
}
×
104

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

112
// protected
113
block::block(const chain::header::cptr& header,
107✔
114
    const transactions_cptr& txs, bool valid) NOEXCEPT
107✔
115
  : header_(header),
116
    txs_(txs),
117
    valid_(valid),
107✔
118
    size_(serialized_size(*txs))
214✔
119
{
120
}
107✔
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_);
37✔
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
83✔
141
{
142
    auto& allocator = source.get_allocator();
83✔
143
    const auto count = source.read_size(max_block_size);
83✔
144
    auto txs = to_non_const_raw_ptr(txs_);
83✔
145
    txs->reserve(count);
83✔
146

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

150
    size_ = serialized_size(*txs_);
83✔
151
    valid_ = source;
83✔
152
}
83✔
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;
40✔
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
35✔
194
{
195
    return valid_;
35✔
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::spends() const NOEXCEPT
2✔
255
{
256
    if (txs_->empty())
2✔
257
        return zero;
258

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

265
    return std::accumulate(std::next(txs_->begin()), txs_->end(), zero, ins);
2✔
266
}
267

268
// computed
269
hash_digest block::hash() const NOEXCEPT
38✔
270
{
271
    return header_->hash();
38✔
272
}
273

274
// computed
275
const hash_digest& block::get_hash() const NOEXCEPT
×
276
{
277
    return header_->get_hash();
×
278
}
279

280
void block::set_hashes(const data_chunk& data) NOEXCEPT
×
281
{
282
    constexpr auto header_size = chain::header::serialized_size();
×
283

284
    // Cache header hash.
285
    header_->set_hash(bitcoin_hash(header_size, data.data()));
×
286

287
    // Skip transaction count, guarded by preceding successful block construct.
288
    auto start = std::next(data.data(), header_size);
×
289
    std::advance(start, size_variable(*start));
×
290

291
    // Cache transaction hashes.
292
    auto coinbase = true;
×
293
    for (const auto& tx: *txs_)
×
294
    {
295
        const auto witness_size = tx->serialized_size(true);
×
296

297
        // If !witness then wire txs cannot have been segregated.
298
        if (tx->is_segregated())
×
299
        {
300
            const auto nominal_size = tx->serialized_size(false);
×
301

302
            tx->set_nominal_hash(transaction::desegregated_hash(
×
303
                witness_size, nominal_size, start));
304

305
            if (!coinbase)
×
306
                tx->set_witness_hash(bitcoin_hash(witness_size, start));
×
307
        }
308
        else
309
        {
310
            tx->set_nominal_hash(bitcoin_hash(witness_size, start));
×
311
        }
312

313
        coinbase = false;
×
314
        std::advance(start, witness_size);
×
315
    }
316
}
×
317

318
// static/private
319
block::sizes block::serialized_size(
190✔
320
    const chain::transaction_cptrs& txs) NOEXCEPT
321
{
322
    sizes size{};
190✔
323
    std::for_each(txs.begin(), txs.end(), [&](const auto& tx) NOEXCEPT
452✔
324
    {
325
        size.nominal = ceilinged_add(size.nominal, tx->serialized_size(false));
524✔
326
        size.witnessed = ceilinged_add(size.witnessed, tx->serialized_size(true));
262✔
327
    });
262✔
328

329
    const auto common_size = ceilinged_add(header::serialized_size(),
190✔
330
        variable_size(txs.size()));
331

332
    const auto nominal_size = ceilinged_add(common_size, size.nominal);
190✔
333
    const auto witnessed_size = ceilinged_add(common_size, size.witnessed);
190✔
334

335
    return { nominal_size, witnessed_size };
190✔
336
}
337

338
size_t block::serialized_size(bool witness) const NOEXCEPT
24✔
339
{
340
    return witness ? size_.witnessed : size_.nominal;
21✔
341
}
342

343
// Connect.
344
// ----------------------------------------------------------------------------
345

346
bool block::is_empty() const NOEXCEPT
2✔
347
{
348
    return txs_->empty();
2✔
349
}
350

351
bool block::is_oversized() const NOEXCEPT
3✔
352
{
353
    return serialized_size(false) > max_block_size;
3✔
354
}
355

356
bool block::is_first_non_coinbase() const NOEXCEPT
3✔
357
{
358
    return !txs_->empty() && !txs_->front()->is_coinbase();
3✔
359
}
360

361
// True if there is another coinbase other than the first tx.
362
// No txs or coinbases returns false.
363
bool block::is_extra_coinbases() const NOEXCEPT
3✔
364
{
365
    if (txs_->empty())
3✔
366
        return false;
367

368
    const auto value = [](const auto& tx) NOEXCEPT
2✔
369
    {
370
        return tx->is_coinbase();
2✔
371
    };
372

373
    return std::any_of(std::next(txs_->begin()), txs_->end(), value);
3✔
374
}
375

376
//*****************************************************************************
377
// CONSENSUS: This is only necessary because satoshi stores and queries as it
378
// validates, imposing an otherwise unnecessary partial transaction ordering.
379
//*****************************************************************************
380
bool block::is_forward_reference() const NOEXCEPT
8✔
381
{
382
    if (txs_->empty())
8✔
383
        return false;
384

385
    const auto sum_txs = sub1(txs_->size());
7✔
386
    unordered_set_of_hash_cref hashes{ sum_txs };
7✔
387
    const auto spent = [&hashes](const input::cptr& input) NOEXCEPT
11✔
388
    {
389
        return hashes.find(std::ref(input->point().hash())) != hashes.end();
4✔
390
    };
7✔
391

392
    const auto spend = [&spent, &hashes](const auto& tx) NOEXCEPT
7✔
393
    {
394
        const auto& ins = tx->inputs_ptr();
7✔
395
        const auto forward = std::any_of(ins->begin(), ins->end(), spent);
7✔
396
        hashes.emplace(tx->get_hash(false));
7✔
397
        return forward;
7✔
398
    };
7✔
399

400
    return std::any_of(txs_->rbegin(), std::prev(txs_->rend()), spend);
7✔
401
}
402

403
// This also precludes the block merkle calculation DoS exploit by preventing
404
// duplicate txs, as a duplicate non-empty tx implies a duplicate point.
405
// bitcointalk.org/?topic=102395
406
bool block::is_internal_double_spend() const NOEXCEPT
6✔
407
{
408
    if (txs_->empty())
6✔
409
        return false;
410

411
    // Overflow returns max_size_t.
412
    const auto sum_ins = [](size_t total, const auto& tx) NOEXCEPT
11✔
413
    {
414
        return ceilinged_add(total, tx->inputs());
11✔
415
    };
416

417
    const auto tx1 = std::next(txs_->begin());
5✔
418
    const auto spends_count = std::accumulate(tx1, txs_->end(), zero, sum_ins);
5✔
419
    unordered_set_of_point_cref points{ spends_count };
5✔
420
    const auto spent = [&points](const input::cptr& in) NOEXCEPT
14✔
421
    {
422
        return !points.emplace(in->point()).second;
9✔
423
    };
5✔
424

425
    const auto double_spent = [&spent](const auto& tx) NOEXCEPT
9✔
426
    {
427
        const auto& ins = tx->inputs_ptr();
9✔
428
        return std::any_of(ins->begin(), ins->end(), spent);
9✔
429
    };
5✔
430

431
    return std::any_of(tx1, txs_->end(), double_spent);
5✔
432
}
433

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

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

445
// Accept (contextual).
446
// ----------------------------------------------------------------------------
447

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

456
bool block::is_overweight() const NOEXCEPT
×
457
{
458
    return weight() > max_block_weight;
×
459
}
460

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

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

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

479
    // A set is used to collapse duplicates.
NEW
480
    unordered_set_of_hash_cref hashes{};
×
481

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

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

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

496
    return hashes.size() > hash_limit;
×
497
}
498

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

505
bool block::is_malleated() const NOEXCEPT
×
506
{
507
    return is_malleated64() || is_malleated32();
×
508
}
509

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

518
    return false;
519
}
520

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

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

536
    return zero;
537
}
538

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

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

553
    return true;
554
}
555

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

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

571
    return !txs.empty() && std::all_of(txs.begin(), txs.end(), two_leaves);
12✔
572
}
573

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

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

590
    return std::any_of(txs_->begin(), txs_->end(), segregated);
2✔
591
}
592

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

602
    const auto& coinbase = txs_->front();
×
603
    if (coinbase->inputs_ptr()->empty())
×
604
        return false;
605

606
    // If there is a valid commitment, return false (valid).
607
    // Coinbase input witness must be 32 byte witness reserved value (bip141).
608
    // Last output of commitment pattern holds the committed value (bip141).
609
    hash_digest reserved{}, committed{};
×
610
    if (coinbase->inputs_ptr()->front()->reserved_hash(reserved))
×
611
        for (const auto& output: views_reverse(*coinbase->outputs_ptr()))
×
612
            if (output->committed_hash(committed))
×
613
                if (committed == sha256::double_hash(
×
614
                    generate_merkle_root(true), reserved))
×
615
                    return false;
616
    
617
    // If no valid commitment, return true (invalid) if segregated.
618
    // If no block tx has witness data the commitment is optional (bip141).
619
    return is_segregated();
×
620
}
621

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

638
// Prevouts required.
639

640
uint64_t block::fees() const NOEXCEPT
×
641
{
642
    // Overflow returns max_uint64.
643
    const auto value = [](uint64_t total, const auto& tx) NOEXCEPT
×
644
    {
645
        return ceilinged_add(total, tx->fee());
×
646
    };
647

648
    return std::accumulate(txs_->begin(), txs_->end(), uint64_t{0}, value);
×
649
}
650

651
uint64_t block::claim() const NOEXCEPT
×
652
{
653
    return txs_->empty() ? zero : txs_->front()->value();
×
654
}
655

656
uint64_t block::reward(size_t height, uint64_t subsidy_interval,
×
657
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
658
{
659
    // Overflow returns max_uint64.
660
    return ceilinged_add(fees(), block_subsidy(height, subsidy_interval,
×
661
        initial_block_subsidy_satoshi, bip42));
×
662
}
663

664
bool block::is_overspent(size_t height, uint64_t subsidy_interval,
×
665
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
666
{
667
    return claim() > reward(height, subsidy_interval,
×
668
        initial_block_subsidy_satoshi, bip42);
×
669
}
670

671
size_t block::signature_operations(bool bip16, bool bip141) const NOEXCEPT
×
672
{
673
    // Overflow returns max_size_t.
674
    const auto value = [=](size_t total, const auto& tx) NOEXCEPT
×
675
    {
676
        return ceilinged_add(total, tx->signature_operations(bip16, bip141));
×
677
    };
×
678

679
    return std::accumulate(txs_->begin(), txs_->end(), zero, value);
×
680
}
681

682
bool block::is_signature_operations_limited(bool bip16,
×
683
    bool bip141) const NOEXCEPT
684
{
685
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
686
    return signature_operations(bip16, bip141) > limit;
×
687
}
688

689
//*****************************************************************************
690
// CONSENSUS:
691
// This check is excluded under two bip30 exception blocks and bip30_deactivate
692
// until bip30_reactivate. These conditions are rolled up into the bip30 flag.
693
//*****************************************************************************
694
bool block::is_unspent_coinbase_collision() const NOEXCEPT
×
695
{
696
    if (txs_->empty() || txs_->front()->inputs_ptr()->empty())
×
697
        return false;
×
698

699
    // May only commit duplicate coinbase that is already confirmed spent.
700
    // Metadata population defaults coinbase to spent (not a collision).
701
    return !txs_->front()->inputs_ptr()->front()->metadata.spent;
×
702
}
703

704
// Search is not ordered, forward references are caught by block.check.
705
bool block::populate() const NOEXCEPT
×
706
{
NEW
707
    if (txs_->empty())
×
708
        return true;
709

NEW
710
    unordered_map_of_cref_point_to_output_cptr_cref points{};
×
NEW
711
    const auto second = std::next(txs_->begin());
×
NEW
712
    const auto last = txs_->end();
×
UNCOV
713
    uint32_t index{};
×
714

715
    // Populate outputs hash table.
NEW
716
    for (auto tx = second; tx != last; ++tx, index = 0)
×
717
        for (const auto& out: *(*tx)->outputs_ptr())
×
NEW
718
            points.emplace(cref_point{ (*tx)->get_hash(false), index++ }, out);
×
719

720
    // Populate input prevouts from hash table and obtain locked state.
721
    auto locked = false;
NEW
722
    for (auto tx = second; tx != last; ++tx)
×
723
    {
724
        for (const auto& in: *(*tx)->inputs_ptr())
×
725
        {
726
            // Map chain::point to cref_point for search, should optimize away.
NEW
727
            const auto point = points.find({ in->point().hash(),
×
NEW
728
                in->point().index() });
×
729

UNCOV
730
            if (point != points.end())
×
731
            {
732
                in->prevout = point->second;
×
733
                in->metadata.locked = in->is_internally_locked();
×
734
                locked |= in->metadata.locked;
×
735
            }
736
        }
737
    }
738

739
    return !locked;
×
740
}
741

742
// Delegated.
743
// ----------------------------------------------------------------------------
744

745
// DO invoke on coinbase.
746
code block::check_transactions() const NOEXCEPT
3✔
747
{
748
    for (const auto& tx: *txs_)
8✔
749
        if (const auto ec = tx->check())
5✔
750
            return ec;
×
751

752
    return error::block_success;
3✔
753
}
754

755
// DO invoke on coinbase.
756
code block::check_transactions(const context& ctx) const NOEXCEPT
×
757
{
758
    for (const auto& tx: *txs_)
×
759
        if (const auto ec = tx->check(ctx))
×
760
            return ec;
×
761

762
    return error::block_success;
×
763
}
764

765
// Do NOT invoke on coinbase.
766
code block::accept_transactions(const context& ctx) const NOEXCEPT
×
767
{
768
    if (!is_empty())
×
769
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
770
            if (const auto ec = (*tx)->accept(ctx))
×
771
                return ec;
×
772

773
    return error::block_success;
×
774
}
775

776
// Do NOT invoke on coinbase.
777
code block::connect_transactions(const context& ctx) const NOEXCEPT
×
778
{
779
    if (!is_empty())
×
780
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
781
            if (const auto ec = (*tx)->connect(ctx))
×
782
                return ec;
×
783

784
    return error::block_success;
×
785
}
786

787
// Do NOT invoke on coinbase.
788
code block::confirm_transactions(const context& ctx) const NOEXCEPT
×
789
{
790
    if (!is_empty())
×
791
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
792
            if (const auto ec = (*tx)->confirm(ctx))
×
793
                return ec;
×
794

795
    return error::block_success;
×
796
}
797

798
// Identity.
799
// ----------------------------------------------------------------------------
800
// invalid_transaction_commitment, invalid_witness_commitment, block_malleated
801
// codes specifically indicate lack of block hash tx identification (identity).
802

803
code block::identify() const NOEXCEPT
×
804
{
805
    // type64 malleated is a subset of first_not_coinbase.
806
    // type32 malleated is a subset of is_internal_double_spend.
807
    if (is_malleated())
×
808
        return error::block_malleated;
×
809
    if (is_invalid_merkle_root())
×
810
        return error::invalid_transaction_commitment;
×
811

812
    return error::block_success;
×
813
}
814

815
code block::identify(const context& ctx) const NOEXCEPT
×
816
{
817
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
818

819
    if (bip141 && is_invalid_witness_commitment())
×
820
        return error::invalid_witness_commitment;
×
821

822
    return error::block_success;
×
823
}
824

825
// Validation.
826
// ----------------------------------------------------------------------------
827
// In the case of validation failure
828
// The block header is checked/accepted independently.
829

830
// TODO: use of get_hash() in is_forward_reference makes this thread unsafe.
831
code block::check() const NOEXCEPT
3✔
832
{
833
    // empty_block is subset of first_not_coinbase.
834
    //if (is_empty())
835
    //    return error::empty_block;
836
    if (is_oversized())
3✔
837
        return error::block_size_limit;
×
838
    if (is_first_non_coinbase())
3✔
839
        return error::first_not_coinbase;
×
840
    if (is_extra_coinbases())
3✔
841
        return error::extra_coinbases;
×
842
    if (is_forward_reference())
3✔
843
        return error::forward_reference;
×
844
    if (is_internal_double_spend())
3✔
845
        return error::block_internal_double_spend;
×
846
    if (is_invalid_merkle_root())
3✔
847
        return error::invalid_transaction_commitment;
×
848

849
    return check_transactions();
3✔
850
}
851

852
// forks
853
// height
854
// timestamp
855
// median_time_past
856

857
// TODO: use of get_hash() in is_hash_limit_exceeded makes this thread unsafe.
858
code block::check(const context& ctx) const NOEXCEPT
×
859
{
860
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
861
    const auto bip34 = ctx.is_enabled(bip34_rule);
×
862
    const auto bip50 = ctx.is_enabled(bip50_rule);
×
863

864
    if (bip141 && is_overweight())
×
865
        return error::block_weight_limit;
×
866
    if (bip34 && is_invalid_coinbase_script(ctx.height))
×
867
        return error::coinbase_height_mismatch;
×
868
    if (bip50 && is_hash_limit_exceeded())
×
869
        return error::temporary_hash_limit;
×
870
    if (bip141 && is_invalid_witness_commitment())
×
871
        return error::invalid_witness_commitment;
×
872

873
    return check_transactions(ctx);
×
874
}
875

876
// forks
877
// height
878

879
// This assumes that prevout caching is completed on all inputs.
880
code block::accept(const context& ctx, size_t subsidy_interval,
×
881
    uint64_t initial_subsidy) const NOEXCEPT
882
{
883
    const auto bip16 = ctx.is_enabled(bip16_rule);
×
884
    const auto bip42 = ctx.is_enabled(bip42_rule);
×
885
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
886

887
    // prevouts required.
888
    if (is_overspent(ctx.height, subsidy_interval, initial_subsidy, bip42))
×
889
        return error::coinbase_value_limit;
×
890
    if (is_signature_operations_limited(bip16, bip141))
×
891
        return error::block_sigop_limit;
×
892

893
    return accept_transactions(ctx);
×
894
}
895

896
// forks
897

898
// Node performs these checks through database query.
899
// This assumes that prevout and metadata caching are completed on all inputs.
900
code block::confirm(const context& ctx) const NOEXCEPT
×
901
{
902
    const auto bip30 = ctx.is_enabled(bip30_rule);
×
903

904
    if (bip30 && is_unspent_coinbase_collision())
×
905
        return error::unspent_coinbase_collision;
×
906

907
    return confirm_transactions(ctx);
×
908
}
909

910
// forks
911

912
code block::connect(const context& ctx) const NOEXCEPT
×
913
{
914
    return connect_transactions(ctx);
×
915
}
916

917
BC_POP_WARNING()
918
BC_POP_WARNING()
919

920
// JSON value convertors.
921
// ----------------------------------------------------------------------------
922

923
namespace json = boost::json;
924

925
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
926
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
927

928
block tag_invoke(json::value_to_tag<block>,
1✔
929
    const json::value& value) NOEXCEPT
930
{
931
    return
1✔
932
    {
933
        json::value_to<header>(value.at("header")),
1✔
934
        json::value_to<chain::transactions>(value.at("transactions"))
2✔
935
    };
1✔
936
}
937

938
void tag_invoke(json::value_from_tag, json::value& value,
2✔
939
    const block& block) NOEXCEPT
940
{
941
    value =
2✔
942
    {
943
        { "header", block.header() },
944
        { "transactions", *block.transactions_ptr() },
945
    };
2✔
946
}
2✔
947

948
BC_POP_WARNING()
949

950
block::cptr tag_invoke(json::value_to_tag<block::cptr>,
×
951
    const json::value& value) NOEXCEPT
952
{
953
    return to_shared(tag_invoke(json::value_to_tag<block>{}, value));
×
954
}
955

956
// Shared pointer overload is required for navigation.
957
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
958
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
959

960
void tag_invoke(json::value_from_tag tag, json::value& value,
×
961
    const block::cptr& block) NOEXCEPT
962
{
963
    tag_invoke(tag, value, *block);
×
964
}
×
965

966
BC_POP_WARNING()
967
BC_POP_WARNING()
968

969
} // namespace chain
970
} // namespace system
971
} // 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