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

libbitcoin / libbitcoin-system / 9325105456

31 May 2024 10:31PM UTC coverage: 82.819% (+0.09%) from 82.732%
9325105456

push

github

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

Optimize size computations, use ceilinged_add, style.

71 of 85 new or added lines in 7 files covered. (83.53%)

7 existing lines in 2 files now uncovered.

9848 of 11891 relevant lines covered (82.82%)

4796079.56 hits per line

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

48.29
/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 <functional>
23
#include <iterator>
24
#include <memory>
25
#include <numeric>
26
#include <set>
27
#include <type_traits>
28
#include <unordered_map>
29
#include <utility>
30
#include <bitcoin/system/chain/context.hpp>
31
#include <bitcoin/system/chain/enums/flags.hpp>
32
#include <bitcoin/system/chain/enums/magic_numbers.hpp>
33
#include <bitcoin/system/chain/enums/opcode.hpp>
34
#include <bitcoin/system/chain/point.hpp>
35
#include <bitcoin/system/chain/script.hpp>
36
#include <bitcoin/system/data/data.hpp>
37
#include <bitcoin/system/define.hpp>
38
#include <bitcoin/system/error/error.hpp>
39
#include <bitcoin/system/hash/hash.hpp>
40
#include <bitcoin/system/math/math.hpp>
41
#include <bitcoin/system/stream/stream.hpp>
42

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

47
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
48

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

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

58
block::block(chain::header&& header, chain::transactions&& txs) NOEXCEPT
11✔
59
  : block(to_shared(std::move(header)), to_shareds(std::move(txs)), true)
33✔
60
{
61
}
11✔
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 chain::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
67✔
77
  : block(stream::in::copy(data), witness)
67✔
78
{
79
}
67✔
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
1✔
87
  : block(read::bytes::fast(stream), witness)
1✔
88
{
89
}
1✔
90

91
block::block(std::istream&& stream, bool witness) NOEXCEPT
67✔
92
  : block(read::bytes::istream(stream), witness)
67✔
93
{
94
}
67✔
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
71✔
102
  : block(from_data(source, witness))
71✔
103
{
104
}
71✔
105

106
block::block(reader& source, bool witness) NOEXCEPT
1✔
107
  : block(from_data(source, witness))
1✔
108
{
109
}
1✔
110

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

121
// Operators.
122
// ----------------------------------------------------------------------------
123

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

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

135
// Deserialization.
136
// ----------------------------------------------------------------------------
137

138
// static/private
139
block block::from_data(reader& source, bool witness) NOEXCEPT
72✔
140
{
141
    const auto read_transactions = [witness](reader& source) NOEXCEPT
261✔
142
    {
143
        auto txs = to_shared<transaction_cptrs>();
72✔
144
        const auto capacity = source.read_size(max_block_size);
72✔
145
        txs->reserve(capacity);
72✔
146

147
        for (size_t tx = 0; tx < capacity; ++tx)
189✔
148
        {
149
            BC_PUSH_WARNING(NO_NEW_OR_DELETE)
150
            txs->emplace_back(new transaction{ source, witness });
117✔
151
            BC_POP_WARNING()
152
        }
153

154
        // This is a pointer copy (non-const to const).
155
        return txs;
72✔
156
    };
72✔
157

158
    return
72✔
159
    {
160
        to_shared<chain::header>(source),
72✔
161
        read_transactions(source),
144✔
162
        source
163
    };
144✔
164
}
165

166
// Serialization.
167
// ----------------------------------------------------------------------------
168

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

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

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

188
    for (const auto& tx: *txs_)
46✔
189
        tx->to_data(sink, witness);
26✔
190
}
20✔
191

192
// Properties.
193
// ----------------------------------------------------------------------------
194

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

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

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

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

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

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

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

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

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

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

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

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

261
// static/private
262
block::sizes block::serialized_size(
172✔
263
    const chain::transaction_cptrs& txs) NOEXCEPT
264
{
265
    sizes size{};
172✔
266
    std::for_each(txs.begin(), txs.end(), [&](const auto& tx) NOEXCEPT
417✔
267
    {
268
        size.nominal = ceilinged_add(size.nominal, tx->serialized_size(false));
490✔
269
        size.witnessed = ceilinged_add(size.witnessed, tx->serialized_size(true));
245✔
270
    });
245✔
271

272
    const auto common_size = ceilinged_add(
172✔
273
        header::serialized_size(),
274
        variable_size(txs.size()));
275

276
    const auto nominal_size = ceilinged_add(
172✔
277
        common_size,
278
        size.nominal);
279

280
    const auto witnessed_size = ceilinged_add(
172✔
281
        common_size,
282
        size.witnessed);
283

284
    return { nominal_size, witnessed_size };
172✔
285
}
286

287
size_t block::serialized_size(bool witness) const NOEXCEPT
19✔
288
{
289
    return witness ? size_.witnessed : size_.nominal;
19✔
290
}
291

292
// Connect.
293
// ----------------------------------------------------------------------------
294

295
bool block::is_empty() const NOEXCEPT
2✔
296
{
297
    return txs_->empty();
2✔
298
}
299

300
bool block::is_oversized() const NOEXCEPT
×
301
{
302
    return serialized_size(false) > max_block_size;
×
303
}
304

305
bool block::is_first_non_coinbase() const NOEXCEPT
×
306
{
307
    return !txs_->empty() && !txs_->front()->is_coinbase();
×
308
}
309

310
// True if there is another coinbase other than the first tx.
311
// No txs or coinbases returns false.
312
bool block::is_extra_coinbases() const NOEXCEPT
×
313
{
314
    if (txs_->empty())
×
315
        return false;
316

NEW
317
    const auto value = [](const auto& tx) NOEXCEPT
×
318
    {
319
        return tx->is_coinbase();
×
320
    };
321

322
    return std::any_of(std::next(txs_->begin()), txs_->end(), value);
×
323
}
324

325
//*****************************************************************************
326
// CONSENSUS: This is only necessary because satoshi stores and queries as it
327
// validates, imposing an otherwise unnecessary partial transaction ordering.
328
//*****************************************************************************
329
bool block::is_forward_reference() const NOEXCEPT
5✔
330
{
331
    if (txs_->empty())
5✔
332
        return false;
333

334
    const auto sum_txs = sub1(txs_->size());
4✔
335
    unordered_set_of_constant_referenced_hashes hashes{ sum_txs };
4✔
336
    const auto spent = [&hashes](const input::cptr& input) NOEXCEPT
6✔
337
    {
338
        return hashes.find(std::ref(input->point().hash())) != hashes.end();
2✔
339
    };
4✔
340

341
    const auto spend = [&spent, &hashes](const auto& tx) NOEXCEPT
5✔
342
    {
343
        const auto& ins = *tx->inputs_ptr();
5✔
344
        const auto forward = std::any_of(ins.begin(), ins.end(), spent);
5✔
345
        hashes.emplace(tx->get_hash(false));
5✔
346
        return forward;
5✔
347
    };
4✔
348

349
    return std::any_of(txs_->rbegin(), std::prev(txs_->rend()), spend);
4✔
350
}
351

352
// This also precludes the block merkle calculation DoS exploit by preventing
353
// duplicate txs, as a duplicate non-empty tx implies a duplicate point.
354
// bitcointalk.org/?topic=102395
355
bool block::is_internal_double_spend() const NOEXCEPT
3✔
356
{
357
    if (txs_->empty())
3✔
358
        return false;
359

360
    // Overflow returns max_size_t.
361
    const auto sum_ins = [](size_t total, const auto& tx) NOEXCEPT
9✔
362
    {
363
        return ceilinged_add(total, tx->inputs());
9✔
364
    };
365

366
    const auto tx1 = std::next(txs_->begin());
2✔
367
    const auto spends_count = std::accumulate(tx1, txs_->end(), zero, sum_ins);
2✔
368
    unordered_set_of_constant_referenced_points points{ spends_count };
2✔
369
    const auto spent = [&points](const input::cptr& in) NOEXCEPT
9✔
370
    {
371
        return !points.emplace(in->point()).second;
7✔
372
    };
2✔
373

374
    const auto double_spent = [&spent](const auto& tx) NOEXCEPT
7✔
375
    {
376
        const auto& ins = *tx->inputs_ptr();
7✔
377
        return std::any_of(ins.begin(), ins.end(), spent);
7✔
378
    };
2✔
379

380
    return std::any_of(tx1, txs_->end(), double_spent);
2✔
381
}
382

383
// private
384
hash_digest block::generate_merkle_root(bool witness) const NOEXCEPT
11✔
385
{
386
    return sha256::merkle_root(transaction_hashes(witness));
11✔
387
}
388

389
bool block::is_invalid_merkle_root() const NOEXCEPT
11✔
390
{
391
    return generate_merkle_root(false) != header_->merkle_root();
11✔
392
}
393

394
// Accept (contextual).
395
// ----------------------------------------------------------------------------
396

397
size_t block::weight() const NOEXCEPT
×
398
{
399
    // Block weight is 3 * nominal size * + 1 * witness size (bip141).
NEW
400
    return ceilinged_add(
×
401
        ceilinged_multiply(base_size_contribution, serialized_size(false)),
NEW
402
        ceilinged_multiply(total_size_contribution, serialized_size(true)));
×
403
}
404

405
bool block::is_overweight() const NOEXCEPT
×
406
{
407
    return weight() > max_block_weight;
×
408
}
409

410
bool block::is_invalid_coinbase_script(size_t height) const NOEXCEPT
×
411
{
412
    if (txs_->empty() || txs_->front()->inputs_ptr()->empty())
×
413
        return false;
×
414

415
    const auto& script = txs_->front()->inputs_ptr()->front()->script();
×
416
    return !script::is_coinbase_pattern(script.ops(), height);
×
417
}
418

419
// TODO: add bip50 to chain_state with timestamp range activation.
420
// "Special short-term limits to avoid 10,000 BDB lock limit.
421
// Count of unique txids <= 4500 to prevent 10000 BDB lock exhaustion.
422
// header.timestamp > 1363039171 && header.timestamp < 1368576000."
423
bool block::is_hash_limit_exceeded() const NOEXCEPT
×
424
{
425
    if (txs_->empty())
×
426
        return false;
427

428
    // A set is used to collapse duplicates.
429
    unordered_set_of_constant_referenced_hashes hashes;
×
430

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

434
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
435
    {
436
        // Insert the transaction hash.
437
        hashes.emplace((*tx)->get_hash(false));
×
438
        const auto& inputs = *(*tx)->inputs_ptr();
×
439

440
        // Insert all input point hashes.
441
        for (const auto& input: inputs)
×
442
            hashes.emplace(input->point().hash());
×
443
    }
444

445
    return hashes.size() > hash_limit;
×
446
}
447

448
bool block::is_malleable() const NOEXCEPT
3✔
449
{
450
    return is_malleable64() || is_malleable32();
3✔
451
}
452

453
bool block::is_malleable32() const NOEXCEPT
12✔
454
{
455
    const auto unmalleated = txs_->size();
12✔
456
    for (auto mally = one; mally <= unmalleated; mally *= two)
23✔
457
        if (is_malleable32(unmalleated, mally))
17✔
458
            return true;
459

460
    return false;
461
}
462

463
bool block::is_malleated32() const NOEXCEPT
11✔
464
{
465
    return !is_zero(malleated32_size());
11✔
466
}
467

468
// protected
469
// The size of an actual malleation of this block, or zero.
470
size_t block::malleated32_size() const NOEXCEPT
11✔
471
{
472
    const auto malleated = txs_->size();
11✔
473
    for (auto mally = one; mally <= to_half(malleated); mally *= two)
23✔
474
        if (is_malleable32(malleated - mally, mally) &&
20✔
475
            is_malleated32(mally))
6✔
476
            return mally;
2✔
477

478
    return zero;
479
}
480

481
// protected
482
// True if the last width set of tx hashes repeats.
483
bool block::is_malleated32(size_t width) const NOEXCEPT
7✔
484
{
485
    const auto malleated = txs_->size();
7✔
486
    if (is_zero(width) || width > to_half(malleated))
7✔
487
        return false;
488

489
    auto mally = txs_->rbegin();
6✔
490
    auto legit = std::next(mally, width);
6✔
491
    while (!is_zero(width--))
9✔
492
        if ((*mally++)->hash(false) != (*legit++)->hash(false))
7✔
493
            return false;
494

495
    return true;
496
}
497

498
bool block::is_malleable64() const NOEXCEPT
12✔
499
{
500
    return is_malleable64(*txs_);
12✔
501
}
502

503
// static
504
// If all non-witness tx serializations are 64 bytes the id is malleable.
505
// This form of malleability does not imply current block instance is invalid.
506
bool block::is_malleable64(const transaction_cptrs& txs) NOEXCEPT
12✔
507
{
508
    const auto two_leaves = [](const auto& tx) NOEXCEPT
15✔
509
    {
510
        return tx->serialized_size(false) == two * hash_size;
15✔
511
    };
512

513
    return !txs.empty() && std::all_of(txs.begin(), txs.end(), two_leaves);
12✔
514
}
515

516
bool block::is_segregated() const NOEXCEPT
×
517
{
NEW
518
    const auto segregated = [](const auto& tx) NOEXCEPT
×
519
    {
520
        return tx->is_segregated();
×
521
    };
522

523
    return std::any_of(txs_->begin(), txs_->end(), segregated);
×
524
}
525

526
bool block::is_invalid_witness_commitment() const NOEXCEPT
×
527
{
528
    if (txs_->empty())
×
529
        return false;
530

531
    const auto& coinbase = *txs_->front();
×
532
    if (coinbase.inputs_ptr()->empty())
×
533
        return false;
534

535
    // If there is a valid commitment, return false (valid).
536
    // Last output of commitment pattern holds committed value (bip141).
537
    hash_digest reserved{}, committed{};
×
538
    if (coinbase.inputs_ptr()->front()->reserved_hash(reserved))
×
539
        for (const auto& output: views_reverse(*coinbase.outputs_ptr()))
×
540
            if (output->committed_hash(committed))
×
541
                if (committed == sha256::double_hash(
×
542
                    generate_merkle_root(true), reserved))
×
543
                    return false;
544
    
545
    // If no valid commitment, return true (invalid) if segregated.
546
    // If no block tx has witness data the commitment is optional (bip141).
547
    return is_segregated();
×
548
}
549

550
//*****************************************************************************
551
// CONSENSUS:
552
// bip42 compensates for C++ undefined behavior of a right shift of a number of
553
// bits greater or equal to the shifted integer width. Yet being undefined, the
554
// result of this operation may vary by compiler. The shift_right call below
555
// explicitly implements presumed pre-bip42 behavior (shift overflow modulo) by
556
// default, and specified bip42 behavior (shift overflow to zero) with bip42.
557
//*****************************************************************************
558
static uint64_t block_subsidy(size_t height, uint64_t subsidy_interval,
×
559
    uint64_t initial_block_subsidy_satoshi, bool bip42) NOEXCEPT
560
{
561
    // Guard: quotient domain cannot increase with positive integer divisor.
562
    const auto halves = possible_narrow_cast<size_t>(height / subsidy_interval);
×
563
    return shift_right(initial_block_subsidy_satoshi, halves, bip42);
×
564
}
565

566
// Prevouts required.
567

568
uint64_t block::fees() const NOEXCEPT
×
569
{
570
    // Overflow returns max_uint64.
NEW
571
    const auto value = [](uint64_t total, const auto& tx) NOEXCEPT
×
572
    {
573
        return ceilinged_add(total, tx->fee());
×
574
    };
575

576
    return std::accumulate(txs_->begin(), txs_->end(), uint64_t{0}, value);
×
577
}
578

579
uint64_t block::claim() const NOEXCEPT
×
580
{
581
    return txs_->empty() ? zero : txs_->front()->value();
×
582
}
583

584
uint64_t block::reward(size_t height, uint64_t subsidy_interval,
×
585
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
586
{
587
    // Overflow returns max_uint64.
588
    return ceilinged_add(fees(), block_subsidy(height, subsidy_interval,
×
589
        initial_block_subsidy_satoshi, bip42));
×
590
}
591

592
bool block::is_overspent(size_t height, uint64_t subsidy_interval,
×
593
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
594
{
595
    return claim() > reward(height, subsidy_interval,
×
596
        initial_block_subsidy_satoshi, bip42);
×
597
}
598

599
size_t block::signature_operations(bool bip16, bool bip141) const NOEXCEPT
×
600
{
601
    // Overflow returns max_size_t.
NEW
602
    const auto value = [=](size_t total, const auto& tx) NOEXCEPT
×
603
    {
604
        return ceilinged_add(total, tx->signature_operations(bip16, bip141));
×
605
    };
×
606

607
    return std::accumulate(txs_->begin(), txs_->end(), zero, value);
×
608
}
609

610
bool block::is_signature_operations_limited(bool bip16,
×
611
    bool bip141) const NOEXCEPT
612
{
613
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
614
    return signature_operations(bip16, bip141) > limit;
×
615
}
616

617
//*****************************************************************************
618
// CONSENSUS:
619
// This check is excluded under two bip30 exception blocks and bip30_deactivate
620
// until bip30_reactivate. These conditions are rolled up into the bip30 flag.
621
//*****************************************************************************
622
bool block::is_unspent_coinbase_collision() const NOEXCEPT
×
623
{
624
    if (txs_->empty() || txs_->front()->inputs_ptr()->empty())
×
625
        return false;
×
626

627
    // May only commit duplicate coinbase that is already confirmed spent.
628
    // Metadata population defaults coinbase to spent (not a collision).
629
    return !txs_->front()->inputs_ptr()->front()->metadata.spent;
×
630
}
631

632
// Search is not ordered, forward references are caught by block.check.
633
void block::populate() const NOEXCEPT
×
634
{
635
    unordered_map_of_constant_referenced_points points{};
×
636
    uint32_t index{};
×
637

638
    // Populate outputs hash table.
639
    for (auto tx = txs_->begin(); tx != txs_->end(); ++tx, index = 0)
×
640
        for (const auto& out: *(*tx)->outputs_ptr())
×
641
            points.emplace(std::pair{ point{ (*tx)->get_hash(false),
×
642
                index++ }, out });
643

644
    // Populate input prevouts from hash table.
645
    for (auto tx = txs_->begin(); tx != txs_->end(); ++tx)
×
646
    {
647
        for (const auto& in: *(*tx)->inputs_ptr())
×
648
        {
649
            const auto point = points.find(std::cref(in->point()));
×
650
            if (point != points.end())
×
651
                in->prevout = point->second;
×
652
        }
653
    }
654
}
×
655

656
// Delegated.
657
// ----------------------------------------------------------------------------
658

659
// DO invoke on coinbase.
660
code block::check_transactions() const NOEXCEPT
×
661
{
662
    code ec;
×
663
    
664
    for (const auto& tx: *txs_)
×
665
        if ((ec = tx->check()))
×
666
            return ec;
×
667

668
    return error::block_success;
×
669
}
670

671
// DO invoke on coinbase.
672
code block::check_transactions(const context& ctx) const NOEXCEPT
×
673
{
674
    code ec;
×
675
    
676
    for (const auto& tx: *txs_)
×
677
        if ((ec = tx->check(ctx)))
×
678
            return ec;
×
679

680
    return error::block_success;
×
681
}
682

683
// Do NOT invoke on coinbase.
684
code block::accept_transactions(const context& ctx) const NOEXCEPT
×
685
{
686
    code ec;
×
687

688
    if (!is_empty())
×
689
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
690
            if ((ec = (*tx)->accept(ctx)))
×
691
                return ec;
×
692

693
    return error::block_success;
×
694
}
695

696
// Do NOT invoke on coinbase.
697
code block::connect_transactions(const context& ctx) const NOEXCEPT
×
698
{
699
    code ec;
×
700

701
    if (!is_empty())
×
702
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
703
            if ((ec = (*tx)->connect(ctx)))
×
704
                return ec;
×
705

706
    return error::block_success;
×
707
}
708

709
// Do NOT invoke on coinbase.
710
code block::confirm_transactions(const context& ctx) const NOEXCEPT
×
711
{
712
    code ec;
×
713

714
    if (!is_empty())
×
715
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
716
            if ((ec = (*tx)->confirm(ctx)))
×
717
                return ec;
×
718

719
    return error::block_success;
×
720
}
721

722
// Validation.
723
// ----------------------------------------------------------------------------
724
// The block header is checked/accepted independently.
725

726
code block::check() const NOEXCEPT
×
727
{
728
    // context free.
729
    // empty_block is redundant with first_not_coinbase.
730
    //if (is_empty())
731
    //    return error::empty_block;
732
    if (is_oversized())
×
733
        return error::block_size_limit;
×
734
    if (is_first_non_coinbase())
×
735
        return error::first_not_coinbase;
×
736
    if (is_extra_coinbases())
×
737
        return error::extra_coinbases;
×
738
    if (is_forward_reference())
×
739
        return error::forward_reference;
×
740
    if (is_internal_double_spend())
×
741
        return error::block_internal_double_spend;
×
742
    if (is_invalid_merkle_root())
×
743
        return error::merkle_mismatch;
×
744

745
    return check_transactions();
×
746
}
747

748
// forks
749
// height
750
// timestamp
751
// median_time_past
752

753
code block::check(const context& ctx) const NOEXCEPT
×
754
{
755
    const auto bip34 = ctx.is_enabled(bip34_rule);
×
756
    const auto bip50 = ctx.is_enabled(bip50_rule);
×
757
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
758

759
    // context required.
760
    if (bip141 && is_overweight())
×
761
        return error::block_weight_limit;
×
762
    if (bip34 && is_invalid_coinbase_script(ctx.height))
×
763
        return error::coinbase_height_mismatch;
×
764
    if (bip50 && is_hash_limit_exceeded())
×
765
        return error::temporary_hash_limit;
×
766
    if (bip141 && is_invalid_witness_commitment())
×
767
        return error::invalid_witness_commitment;
×
768

769
    return check_transactions(ctx);
×
770
}
771

772
// forks
773
// height
774

775
// This assumes that prevout caching is completed on all inputs.
776
code block::accept(const context& ctx, size_t subsidy_interval,
×
777
    uint64_t initial_subsidy) const NOEXCEPT
778
{
779
    const auto bip16 = ctx.is_enabled(bip16_rule);
×
780
    const auto bip42 = ctx.is_enabled(bip42_rule);
×
781
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
782

783
    // prevouts required.
784
    if (is_overspent(ctx.height, subsidy_interval, initial_subsidy, bip42))
×
785
        return error::coinbase_value_limit;
×
786
    if (is_signature_operations_limited(bip16, bip141))
×
787
        return error::block_sigop_limit;
×
788

789
    return accept_transactions(ctx);
×
790
}
791

792
// forks
793

794
// Node performs these checks through database query.
795
// This assumes that prevout and metadata caching are completed on all inputs.
796
code block::confirm(const context& ctx) const NOEXCEPT
×
797
{
798
    const auto bip30 = ctx.is_enabled(bip30_rule);
×
799

800
    if (bip30 && is_unspent_coinbase_collision())
×
801
        return error::unspent_coinbase_collision;
×
802

803
    return confirm_transactions(ctx);
×
804
}
805

806
// forks
807

808
code block::connect(const context& ctx) const NOEXCEPT
×
809
{
810
    return connect_transactions(ctx);
×
811
}
812

813
BC_POP_WARNING()
814

815
// JSON value convertors.
816
// ----------------------------------------------------------------------------
817

818
namespace json = boost::json;
819

820
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
821
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
822

823
block tag_invoke(json::value_to_tag<block>,
1✔
824
    const json::value& value) NOEXCEPT
825
{
826
    return
1✔
827
    {
828
        json::value_to<header>(value.at("header")),
1✔
829
        json::value_to<chain::transactions>(value.at("transactions"))
2✔
830
    };
1✔
831
}
832

833
void tag_invoke(json::value_from_tag, json::value& value,
2✔
834
    const block& block) NOEXCEPT
835
{
836
    value =
2✔
837
    {
838
        { "header", block.header() },
839
        { "transactions", *block.transactions_ptr() },
840
    };
2✔
841
}
2✔
842

843
BC_POP_WARNING()
844

845
block::cptr tag_invoke(json::value_to_tag<block::cptr>,
×
846
    const json::value& value) NOEXCEPT
847
{
848
    return to_shared(tag_invoke(json::value_to_tag<block>{}, value));
×
849
}
850

851
// Shared pointer overload is required for navigation.
852
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
853
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
854

855
void tag_invoke(json::value_from_tag tag, json::value& value,
×
856
    const block::cptr& block) NOEXCEPT
857
{
858
    tag_invoke(tag, value, *block);
×
859
}
×
860

861
BC_POP_WARNING()
862
BC_POP_WARNING()
863

864
} // namespace chain
865
} // namespace system
866
} // 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