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

libbitcoin / libbitcoin-system / 11616218925

31 Oct 2024 04:47PM UTC coverage: 83.009% (-0.001%) from 83.01%
11616218925

push

github

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

Avoid assigning shared ptr dereference to reference.

13 of 23 new or added lines in 2 files covered. (56.52%)

1 existing line in 1 file now uncovered.

10059 of 12118 relevant lines covered (83.01%)

4765458.48 hits per line

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

49.09
/src/chain/block.cpp
1
/**
2
 * Copyright (c) 2011-2023 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 <unordered_map>
28
#include <utility>
29
#include <bitcoin/system/chain/context.hpp>
30
#include <bitcoin/system/chain/enums/flags.hpp>
31
#include <bitcoin/system/chain/enums/magic_numbers.hpp>
32
#include <bitcoin/system/chain/enums/opcode.hpp>
33
#include <bitcoin/system/chain/point.hpp>
34
#include <bitcoin/system/chain/script.hpp>
35
#include <bitcoin/system/data/data.hpp>
36
#include <bitcoin/system/define.hpp>
37
#include <bitcoin/system/error/error.hpp>
38
#include <bitcoin/system/hash/hash.hpp>
39
#include <bitcoin/system/math/math.hpp>
40
#include <bitcoin/system/stream/stream.hpp>
41

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

46
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
47
BC_PUSH_WARNING(NO_UNGUARDED_POINTERS)
48

49
// Constructors.
50
// ----------------------------------------------------------------------------
51

52
block::block() NOEXCEPT
63✔
53
  : block(to_shared<chain::header>(), to_shared<transaction_cptrs>(),
63✔
54
      false)
189✔
55
{
56
}
63✔
57

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

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

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

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

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

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

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

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

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

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

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

123
// Operators.
124
// ----------------------------------------------------------------------------
125

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

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

137
// Deserialization.
138
// ----------------------------------------------------------------------------
139

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

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

151
    size_ = serialized_size(*txs_);
82✔
152
    valid_ = source;
82✔
153
}
82✔
154

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

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

165
// Serialization.
166
// ----------------------------------------------------------------------------
167

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

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

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

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

191
// Properties.
192
// ----------------------------------------------------------------------------
193

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

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

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

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

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

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

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

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

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

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

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

254
// computed
255
hash_digest block::hash() const NOEXCEPT
38✔
256
{
257
    return header_->hash();
38✔
258
}
259

260
// computed
261
const hash_digest& block::get_hash() const NOEXCEPT
×
262
{
263
    return header_->get_hash();
×
264
}
265

266
void block::set_hashes(const data_chunk& data) NOEXCEPT
×
267
{
268
    constexpr auto header_size = chain::header::serialized_size();
×
269

270
    // Cache header hash.
271
    header_->set_hash(bitcoin_hash(header_size, data.data()));
×
272

273
    // Skip transaction count, guarded by preceding successful block construct.
274
    auto start = std::next(data.data(), header_size);
×
275
    std::advance(start, size_variable(*start));
×
276

277
    // Cache transaction hashes.
278
    auto coinbase = true;
×
279
    for (const auto& tx: *txs_)
×
280
    {
281
        const auto witness_size = tx->serialized_size(true);
×
282

283
        // If !witness then wire txs cannot have been segregated.
284
        if (tx->is_segregated())
×
285
        {
286
            const auto nominal_size = tx->serialized_size(false);
×
287

288
            tx->set_nominal_hash(transaction::desegregated_hash(
×
289
                witness_size, nominal_size, start));
290

291
            if (!coinbase)
×
292
                tx->set_witness_hash(bitcoin_hash(witness_size, start));
×
293
        }
294
        else
295
        {
296
            tx->set_nominal_hash(bitcoin_hash(witness_size, start));
×
297
        }
298

299
        coinbase = false;
×
300
        std::advance(start, witness_size);
×
301
    }
302
}
×
303

304
// static/private
305
block::sizes block::serialized_size(
188✔
306
    const chain::transaction_cptrs& txs) NOEXCEPT
307
{
308
    sizes size{};
188✔
309
    std::for_each(txs.begin(), txs.end(), [&](const auto& tx) NOEXCEPT
449✔
310
    {
311
        size.nominal = ceilinged_add(size.nominal, tx->serialized_size(false));
522✔
312
        size.witnessed = ceilinged_add(size.witnessed, tx->serialized_size(true));
261✔
313
    });
261✔
314

315
    const auto common_size = ceilinged_add(header::serialized_size(),
188✔
316
        variable_size(txs.size()));
317

318
    const auto nominal_size = ceilinged_add(common_size, size.nominal);
188✔
319
    const auto witnessed_size = ceilinged_add(common_size, size.witnessed);
188✔
320

321
    return { nominal_size, witnessed_size };
188✔
322
}
323

324
size_t block::serialized_size(bool witness) const NOEXCEPT
24✔
325
{
326
    return witness ? size_.witnessed : size_.nominal;
21✔
327
}
328

329
// Connect.
330
// ----------------------------------------------------------------------------
331

332
bool block::is_empty() const NOEXCEPT
2✔
333
{
334
    return txs_->empty();
2✔
335
}
336

337
bool block::is_oversized() const NOEXCEPT
3✔
338
{
339
    return serialized_size(false) > max_block_size;
3✔
340
}
341

342
bool block::is_first_non_coinbase() const NOEXCEPT
3✔
343
{
344
    return !txs_->empty() && !txs_->front()->is_coinbase();
3✔
345
}
346

347
// True if there is another coinbase other than the first tx.
348
// No txs or coinbases returns false.
349
bool block::is_extra_coinbases() const NOEXCEPT
3✔
350
{
351
    if (txs_->empty())
3✔
352
        return false;
353

354
    const auto value = [](const auto& tx) NOEXCEPT
2✔
355
    {
356
        return tx->is_coinbase();
2✔
357
    };
358

359
    return std::any_of(std::next(txs_->begin()), txs_->end(), value);
3✔
360
}
361

362
//*****************************************************************************
363
// CONSENSUS: This is only necessary because satoshi stores and queries as it
364
// validates, imposing an otherwise unnecessary partial transaction ordering.
365
//*****************************************************************************
366
bool block::is_forward_reference() const NOEXCEPT
8✔
367
{
368
    if (txs_->empty())
8✔
369
        return false;
370

371
    const auto sum_txs = sub1(txs_->size());
7✔
372
    unordered_set_of_constant_referenced_hashes hashes{ sum_txs };
7✔
373
    const auto spent = [&hashes](const input::cptr& input) NOEXCEPT
11✔
374
    {
375
        return hashes.find(std::ref(input->point().hash())) != hashes.end();
4✔
376
    };
7✔
377

378
    const auto spend = [&spent, &hashes](const auto& tx) NOEXCEPT
7✔
379
    {
380
        const auto& ins = tx->inputs_ptr();
7✔
381
        const auto forward = std::any_of(ins->begin(), ins->end(), spent);
7✔
382
        hashes.emplace(tx->get_hash(false));
7✔
383
        return forward;
7✔
384
    };
7✔
385

386
    return std::any_of(txs_->rbegin(), std::prev(txs_->rend()), spend);
7✔
387
}
388

389
// This also precludes the block merkle calculation DoS exploit by preventing
390
// duplicate txs, as a duplicate non-empty tx implies a duplicate point.
391
// bitcointalk.org/?topic=102395
392
bool block::is_internal_double_spend() const NOEXCEPT
6✔
393
{
394
    if (txs_->empty())
6✔
395
        return false;
396

397
    // Overflow returns max_size_t.
398
    const auto sum_ins = [](size_t total, const auto& tx) NOEXCEPT
11✔
399
    {
400
        return ceilinged_add(total, tx->inputs());
11✔
401
    };
402

403
    const auto tx1 = std::next(txs_->begin());
5✔
404
    const auto spends_count = std::accumulate(tx1, txs_->end(), zero, sum_ins);
5✔
405
    unordered_set_of_constant_referenced_points points{ spends_count };
5✔
406
    const auto spent = [&points](const input::cptr& in) NOEXCEPT
14✔
407
    {
408
        return !points.emplace(in->point()).second;
9✔
409
    };
5✔
410

411
    const auto double_spent = [&spent](const auto& tx) NOEXCEPT
9✔
412
    {
413
        const auto& ins = tx->inputs_ptr();
9✔
414
        return std::any_of(ins->begin(), ins->end(), spent);
9✔
415
    };
5✔
416

417
    return std::any_of(tx1, txs_->end(), double_spent);
5✔
418
}
419

420
// private
421
hash_digest block::generate_merkle_root(bool witness) const NOEXCEPT
14✔
422
{
423
    return sha256::merkle_root(transaction_hashes(witness));
14✔
424
}
425

426
bool block::is_invalid_merkle_root() const NOEXCEPT
14✔
427
{
428
    return generate_merkle_root(false) != header_->merkle_root();
14✔
429
}
430

431
// Accept (contextual).
432
// ----------------------------------------------------------------------------
433

434
size_t block::weight() const NOEXCEPT
×
435
{
436
    // Block weight is 3 * nominal size * + 1 * witness size (bip141).
437
    return ceilinged_add(
×
438
        ceilinged_multiply(base_size_contribution, serialized_size(false)),
439
        ceilinged_multiply(total_size_contribution, serialized_size(true)));
×
440
}
441

442
bool block::is_overweight() const NOEXCEPT
×
443
{
444
    return weight() > max_block_weight;
×
445
}
446

447
bool block::is_invalid_coinbase_script(size_t height) const NOEXCEPT
×
448
{
449
    if (txs_->empty() || txs_->front()->inputs_ptr()->empty())
×
450
        return false;
×
451

452
    const auto& script = txs_->front()->inputs_ptr()->front()->script();
×
453
    return !script::is_coinbase_pattern(script.ops(), height);
×
454
}
455

456
// TODO: add bip50 to chain_state with timestamp range activation.
457
// "Special short-term limits to avoid 10,000 BDB lock limit.
458
// Count of unique txids <= 4500 to prevent 10000 BDB lock exhaustion.
459
// header.timestamp > 1363039171 && header.timestamp < 1368576000."
460
bool block::is_hash_limit_exceeded() const NOEXCEPT
×
461
{
462
    if (txs_->empty())
×
463
        return false;
464

465
    // A set is used to collapse duplicates.
466
    unordered_set_of_constant_referenced_hashes hashes{};
×
467

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

471
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
472
    {
473
        // Insert the transaction hash.
474
        hashes.emplace((*tx)->get_hash(false));
×
NEW
475
        const auto& inputs = (*tx)->inputs_ptr();
×
476

477
        // Insert all input point hashes.
NEW
478
        for (const auto& input: *inputs)
×
479
            hashes.emplace(input->point().hash());
×
480
    }
481

482
    return hashes.size() > hash_limit;
×
483
}
484

485
// Malleability does not imply malleated.
486
bool block::is_malleable() const NOEXCEPT
3✔
487
{
488
    return is_malleable64() || is_malleable32();
3✔
489
}
490

491
bool block::is_malleated() const NOEXCEPT
×
492
{
493
    return is_malleated64() || is_malleated32();
×
494
}
495

496
// Malleability does not imply malleated.
497
bool block::is_malleable32() const NOEXCEPT
12✔
498
{
499
    const auto unmalleated = txs_->size();
12✔
500
    for (auto mally = one; mally <= unmalleated; mally *= two)
23✔
501
        if (is_malleable32(unmalleated, mally))
17✔
502
            return true;
503

504
    return false;
505
}
506

507
// Malleated32 implies malleable and invalid due to internal tx hash pairing.
508
bool block::is_malleated32() const NOEXCEPT
11✔
509
{
510
    return !is_zero(malleated32_size());
11✔
511
}
512

513
// protected
514
// The size of an actual malleation of this block, or zero.
515
size_t block::malleated32_size() const NOEXCEPT
11✔
516
{
517
    const auto malleated = txs_->size();
11✔
518
    for (auto mally = one; mally <= to_half(malleated); mally *= two)
23✔
519
        if (is_malleable32(malleated - mally, mally) && is_malleated32(mally))
14✔
520
            return mally;
2✔
521

522
    return zero;
523
}
524

525
// protected
526
// True if the last width set of tx hashes repeats.
527
bool block::is_malleated32(size_t width) const NOEXCEPT
7✔
528
{
529
    const auto malleated = txs_->size();
7✔
530
    if (is_zero(width) || width > to_half(malleated))
7✔
531
        return false;
532

533
    auto mally = txs_->rbegin();
6✔
534
    auto legit = std::next(mally, width);
6✔
535
    while (!is_zero(width--))
9✔
536
        if ((*mally++)->hash(false) != (*legit++)->hash(false))
7✔
537
            return false;
538

539
    return true;
540
}
541

542
// Malleability does not imply malleated.
543
bool block::is_malleable64() const NOEXCEPT
12✔
544
{
545
    return is_malleable64(*txs_);
12✔
546
}
547

548
// static
549
// If all non-witness tx serializations are 64 bytes the id is malleable.
550
bool block::is_malleable64(const transaction_cptrs& txs) NOEXCEPT
12✔
551
{
552
    const auto two_leaves = [](const auto& tx) NOEXCEPT
15✔
553
    {
554
        return tx->serialized_size(false) == two * hash_size;
15✔
555
    };
556

557
    return !txs.empty() && std::all_of(txs.begin(), txs.end(), two_leaves);
12✔
558
}
559

560
// Malleated64 implies malleable64 and invalid due to non-null coinbase point.
561
// It is considered computationally infeasible to produce malleable64 with a
562
// valid (null) coinbase input point.
563
bool block::is_malleated64() const NOEXCEPT
×
564
{
565
    return !txs_->empty() && !txs_->front()->is_coinbase() &&
×
566
        is_malleable64(*txs_);
×
567
}
568

569
bool block::is_segregated() const NOEXCEPT
2✔
570
{
571
    const auto segregated = [](const auto& tx) NOEXCEPT
4✔
572
    {
573
        return tx->is_segregated();
4✔
574
    };
575

576
    return std::any_of(txs_->begin(), txs_->end(), segregated);
2✔
577
}
578

579
// The witness merkle root is obtained from wtxids, subject to malleation just
580
// as the txs commitment. However, since tx duplicates are precluded by the
581
// malleable32 (or complete) block check, there is no opportunity for this.
582
// Similarly the witness commitment cannot be malleable64.
583
bool block::is_invalid_witness_commitment() const NOEXCEPT
×
584
{
585
    if (txs_->empty())
×
586
        return false;
587

NEW
588
    const auto& coinbase = txs_->front();
×
NEW
589
    if (coinbase->inputs_ptr()->empty())
×
590
        return false;
591

592
    // If there is a valid commitment, return false (valid).
593
    // Coinbase input witness must be 32 byte witness reserved value (bip141).
594
    // Last output of commitment pattern holds the committed value (bip141).
595
    hash_digest reserved{}, committed{};
×
NEW
596
    if (coinbase->inputs_ptr()->front()->reserved_hash(reserved))
×
NEW
597
        for (const auto& output: views_reverse(*coinbase->outputs_ptr()))
×
598
            if (output->committed_hash(committed))
×
599
                if (committed == sha256::double_hash(
×
600
                    generate_merkle_root(true), reserved))
×
601
                    return false;
602
    
603
    // If no valid commitment, return true (invalid) if segregated.
604
    // If no block tx has witness data the commitment is optional (bip141).
605
    return is_segregated();
×
606
}
607

608
//*****************************************************************************
609
// CONSENSUS:
610
// bip42 compensates for C++ undefined behavior of a right shift of a number of
611
// bits greater or equal to the shifted integer width. Yet being undefined, the
612
// result of this operation may vary by compiler. The shift_right call below
613
// explicitly implements presumed pre-bip42 behavior (shift overflow modulo) by
614
// default, and specified bip42 behavior (shift overflow to zero) with bip42.
615
//*****************************************************************************
616
static uint64_t block_subsidy(size_t height, uint64_t subsidy_interval,
×
617
    uint64_t initial_block_subsidy_satoshi, bool bip42) NOEXCEPT
618
{
619
    // Guard: quotient domain cannot increase with positive integer divisor.
620
    const auto halves = possible_narrow_cast<size_t>(height / subsidy_interval);
×
621
    return shift_right(initial_block_subsidy_satoshi, halves, bip42);
×
622
}
623

624
// Prevouts required.
625

626
uint64_t block::fees() const NOEXCEPT
×
627
{
628
    // Overflow returns max_uint64.
629
    const auto value = [](uint64_t total, const auto& tx) NOEXCEPT
×
630
    {
631
        return ceilinged_add(total, tx->fee());
×
632
    };
633

634
    return std::accumulate(txs_->begin(), txs_->end(), uint64_t{0}, value);
×
635
}
636

637
uint64_t block::claim() const NOEXCEPT
×
638
{
639
    return txs_->empty() ? zero : txs_->front()->value();
×
640
}
641

642
uint64_t block::reward(size_t height, uint64_t subsidy_interval,
×
643
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
644
{
645
    // Overflow returns max_uint64.
646
    return ceilinged_add(fees(), block_subsidy(height, subsidy_interval,
×
647
        initial_block_subsidy_satoshi, bip42));
×
648
}
649

650
bool block::is_overspent(size_t height, uint64_t subsidy_interval,
×
651
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
652
{
653
    return claim() > reward(height, subsidy_interval,
×
654
        initial_block_subsidy_satoshi, bip42);
×
655
}
656

657
size_t block::signature_operations(bool bip16, bool bip141) const NOEXCEPT
×
658
{
659
    // Overflow returns max_size_t.
660
    const auto value = [=](size_t total, const auto& tx) NOEXCEPT
×
661
    {
662
        return ceilinged_add(total, tx->signature_operations(bip16, bip141));
×
663
    };
×
664

665
    return std::accumulate(txs_->begin(), txs_->end(), zero, value);
×
666
}
667

668
bool block::is_signature_operations_limited(bool bip16,
×
669
    bool bip141) const NOEXCEPT
670
{
671
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
672
    return signature_operations(bip16, bip141) > limit;
×
673
}
674

675
//*****************************************************************************
676
// CONSENSUS:
677
// This check is excluded under two bip30 exception blocks and bip30_deactivate
678
// until bip30_reactivate. These conditions are rolled up into the bip30 flag.
679
//*****************************************************************************
680
bool block::is_unspent_coinbase_collision() const NOEXCEPT
×
681
{
682
    if (txs_->empty() || txs_->front()->inputs_ptr()->empty())
×
683
        return false;
×
684

685
    // May only commit duplicate coinbase that is already confirmed spent.
686
    // Metadata population defaults coinbase to spent (not a collision).
687
    return !txs_->front()->inputs_ptr()->front()->metadata.spent;
×
688
}
689

690
// Search is not ordered, forward references are caught by block.check.
691
void block::populate() const NOEXCEPT
×
692
{
693
    std::unordered_map<point, output::cptr> points{};
×
694
    uint32_t index{};
×
695

696
    // Populate outputs hash table.
697
    for (auto tx = txs_->begin(); tx != txs_->end(); ++tx, index = 0)
×
698
        for (const auto& out: *(*tx)->outputs_ptr())
×
699
            points.emplace(std::pair{ point{ (*tx)->hash(false), index++ },
×
700
                out });
701

702
    // Populate input prevouts from hash table.
703
    for (auto tx = txs_->begin(); tx != txs_->end(); ++tx)
×
704
    {
705
        for (const auto& in: *(*tx)->inputs_ptr())
×
706
        {
707
            const auto point = points.find(in->point());
×
708
            if (point != points.end())
×
709
                in->prevout = point->second;
×
710
        }
711
    }
712
}
×
713

714
// Delegated.
715
// ----------------------------------------------------------------------------
716

717
// DO invoke on coinbase.
718
code block::check_transactions() const NOEXCEPT
3✔
719
{
720
    for (const auto& tx: *txs_)
8✔
721
        if (const auto ec = tx->check())
5✔
722
            return ec;
×
723

724
    return error::block_success;
3✔
725
}
726

727
// DO invoke on coinbase.
728
code block::check_transactions(const context& ctx) const NOEXCEPT
×
729
{
730
    for (const auto& tx: *txs_)
×
731
        if (const auto ec = tx->check(ctx))
×
732
            return ec;
×
733

734
    return error::block_success;
×
735
}
736

737
// Do NOT invoke on coinbase.
738
code block::accept_transactions(const context& ctx) const NOEXCEPT
×
739
{
740
    if (!is_empty())
×
741
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
742
            if (const auto ec = (*tx)->accept(ctx))
×
743
                return ec;
×
744

745
    return error::block_success;
×
746
}
747

748
// Do NOT invoke on coinbase.
749
code block::connect_transactions(const context& ctx) const NOEXCEPT
×
750
{
751
    if (!is_empty())
×
752
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
753
            if (const auto ec = (*tx)->connect(ctx))
×
754
                return ec;
×
755

756
    return error::block_success;
×
757
}
758

759
// Do NOT invoke on coinbase.
760
code block::confirm_transactions(const context& ctx) const NOEXCEPT
×
761
{
762
    if (!is_empty())
×
763
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
764
            if (const auto ec = (*tx)->confirm(ctx))
×
765
                return ec;
×
766

767
    return error::block_success;
×
768
}
769

770
// Identity.
771
// ----------------------------------------------------------------------------
772
// invalid_transaction_commitment, invalid_witness_commitment, block_malleated
773
// codes specifically indicate lack of block hash tx identification (identity).
774

775
code block::identify() const NOEXCEPT
×
776
{
777
    // type64 malleated is a subset of first_not_coinbase.
778
    // type32 malleated is a subset of is_internal_double_spend.
779
    if (is_malleated())
×
780
        return error::block_malleated;
×
781
    if (is_invalid_merkle_root())
×
782
        return error::invalid_transaction_commitment;
×
783

784
    return error::block_success;
×
785
}
786

787
code block::identify(const context& ctx) const NOEXCEPT
×
788
{
789
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
790

791
    if (bip141 && is_invalid_witness_commitment())
×
792
        return error::invalid_witness_commitment;
×
793

794
    return error::block_success;
×
795
}
796

797
// Validation.
798
// ----------------------------------------------------------------------------
799
// In the case of validation failure
800
// The block header is checked/accepted independently.
801

802
// TODO: use of get_hash() in is_forward_reference makes this thread unsafe.
803
code block::check() const NOEXCEPT
3✔
804
{
805
    // empty_block is subset of first_not_coinbase.
806
    //if (is_empty())
807
    //    return error::empty_block;
808
    if (is_oversized())
3✔
809
        return error::block_size_limit;
×
810
    if (is_first_non_coinbase())
3✔
811
        return error::first_not_coinbase;
×
812
    if (is_extra_coinbases())
3✔
813
        return error::extra_coinbases;
×
814
    if (is_forward_reference())
3✔
815
        return error::forward_reference;
×
816
    if (is_internal_double_spend())
3✔
817
        return error::block_internal_double_spend;
×
818
    if (is_invalid_merkle_root())
3✔
819
        return error::invalid_transaction_commitment;
×
820

821
    return check_transactions();
3✔
822
}
823

824
// forks
825
// height
826
// timestamp
827
// median_time_past
828

829
// TODO: use of get_hash() in is_hash_limit_exceeded makes this thread unsafe.
830
code block::check(const context& ctx) const NOEXCEPT
×
831
{
832
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
833
    const auto bip34 = ctx.is_enabled(bip34_rule);
×
834
    const auto bip50 = ctx.is_enabled(bip50_rule);
×
835

836
    if (bip141 && is_overweight())
×
837
        return error::block_weight_limit;
×
838
    if (bip34 && is_invalid_coinbase_script(ctx.height))
×
839
        return error::coinbase_height_mismatch;
×
840
    if (bip50 && is_hash_limit_exceeded())
×
841
        return error::temporary_hash_limit;
×
842
    if (bip141 && is_invalid_witness_commitment())
×
843
        return error::invalid_witness_commitment;
×
844

845
    return check_transactions(ctx);
×
846
}
847

848
// forks
849
// height
850

851
// This assumes that prevout caching is completed on all inputs.
852
code block::accept(const context& ctx, size_t subsidy_interval,
×
853
    uint64_t initial_subsidy) const NOEXCEPT
854
{
855
    const auto bip16 = ctx.is_enabled(bip16_rule);
×
856
    const auto bip42 = ctx.is_enabled(bip42_rule);
×
857
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
858

859
    // prevouts required.
860
    if (is_overspent(ctx.height, subsidy_interval, initial_subsidy, bip42))
×
861
        return error::coinbase_value_limit;
×
862
    if (is_signature_operations_limited(bip16, bip141))
×
863
        return error::block_sigop_limit;
×
864

865
    return accept_transactions(ctx);
×
866
}
867

868
// forks
869

870
// Node performs these checks through database query.
871
// This assumes that prevout and metadata caching are completed on all inputs.
872
code block::confirm(const context& ctx) const NOEXCEPT
×
873
{
874
    const auto bip30 = ctx.is_enabled(bip30_rule);
×
875

876
    if (bip30 && is_unspent_coinbase_collision())
×
877
        return error::unspent_coinbase_collision;
×
878

879
    return confirm_transactions(ctx);
×
880
}
881

882
// forks
883

884
code block::connect(const context& ctx) const NOEXCEPT
×
885
{
886
    return connect_transactions(ctx);
×
887
}
888

889
BC_POP_WARNING()
890
BC_POP_WARNING()
891

892
// JSON value convertors.
893
// ----------------------------------------------------------------------------
894

895
namespace json = boost::json;
896

897
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
898
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
899

900
block tag_invoke(json::value_to_tag<block>,
1✔
901
    const json::value& value) NOEXCEPT
902
{
903
    return
1✔
904
    {
905
        json::value_to<header>(value.at("header")),
1✔
906
        json::value_to<chain::transactions>(value.at("transactions"))
2✔
907
    };
1✔
908
}
909

910
void tag_invoke(json::value_from_tag, json::value& value,
2✔
911
    const block& block) NOEXCEPT
912
{
913
    value =
2✔
914
    {
915
        { "header", block.header() },
916
        { "transactions", *block.transactions_ptr() },
917
    };
2✔
918
}
2✔
919

920
BC_POP_WARNING()
921

922
block::cptr tag_invoke(json::value_to_tag<block::cptr>,
×
923
    const json::value& value) NOEXCEPT
924
{
925
    return to_shared(tag_invoke(json::value_to_tag<block>{}, value));
×
926
}
927

928
// Shared pointer overload is required for navigation.
929
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
930
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
931

932
void tag_invoke(json::value_from_tag tag, json::value& value,
×
933
    const block::cptr& block) NOEXCEPT
934
{
935
    tag_invoke(tag, value, *block);
×
936
}
×
937

938
BC_POP_WARNING()
939
BC_POP_WARNING()
940

941
} // namespace chain
942
} // namespace system
943
} // 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

© 2025 Coveralls, Inc