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

libbitcoin / libbitcoin-system / 9280677383

29 May 2024 05:19AM UTC coverage: 82.746% (-0.05%) from 82.795%
9280677383

push

github

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

Disable use of count_op/op_count to preallocate script ops.

16 of 19 new or added lines in 4 files covered. (84.21%)

3 existing lines in 2 files now uncovered.

9774 of 11812 relevant lines covered (82.75%)

4827757.11 hits per line

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

47.08
/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 <unordered_set>
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
// Constructors.
48
// ----------------------------------------------------------------------------
49

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

56
block::block(chain::header&& header, chain::transactions&& txs) NOEXCEPT
11✔
57
  : block(to_shared(std::move(header)), to_shareds(std::move(txs)), true)
33✔
58
{
59
}
11✔
60

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

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

74
block::block(const data_slice& data, bool witness) NOEXCEPT
67✔
75
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
76
  : block(stream::in::copy(data), witness)
67✔
77
    BC_POP_WARNING()
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), txs_(txs), valid_(valid)
172✔
115
{
116
}
172✔
117

118
// Operators.
119
// ----------------------------------------------------------------------------
120

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

127
bool block::operator!=(const block& other) const NOEXCEPT
5✔
128
{
129
    return !(*this == other);
5✔
130
}
131

132
// Deserialization.
133
// ----------------------------------------------------------------------------
134

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

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

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

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

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

168
data_chunk block::to_data(bool witness) const NOEXCEPT
18✔
169
{
170
    data_chunk data(serialized_size(witness));
18✔
171

172
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
173
    stream::out::copy ostream(data);
18✔
174
    BC_POP_WARNING()
175

176
    to_data(ostream, witness);
18✔
177
    return data;
36✔
178
}
18✔
179

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

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

191
    for (const auto& tx: *txs_)
46✔
192
        tx->to_data(sink, witness);
26✔
193
}
20✔
194

195
// Properties.
196
// ----------------------------------------------------------------------------
197

198
bool block::is_valid() const NOEXCEPT
32✔
199
{
200
    return valid_;
32✔
201
}
202

203
size_t block::transactions() const NOEXCEPT
×
204
{
205
    return txs_->size();
×
206
}
207

208
const chain::header& block::header() const NOEXCEPT
12✔
209
{
210
    return *header_;
2✔
211
}
212

213
const chain::header::cptr block::header_ptr() const NOEXCEPT
×
214
{
215
    return header_;
×
216
}
217

218
// Roll up inputs for concurrent prevout processing.
219
const inputs_cptr block::inputs_ptr() const NOEXCEPT
×
220
{
221
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
222
    const auto inputs = std::make_shared<input_cptrs>();
×
223
    BC_POP_WARNING()
224

225
    const auto append_inputs = [&inputs](const transaction::cptr& tx)
×
226
    {
227
        const auto& tx_ins = *tx->inputs_ptr();
×
228
        inputs->insert(inputs->end(), tx_ins.begin(), tx_ins.end());
×
229
    };
×
230

231
    std::for_each(txs_->begin(), txs_->end(), append_inputs);
×
232
    return inputs;
×
233
}
234

235
// vector<transaction> is not exposed (because we don't have it).
236
// This would require a from_shared(txs_) conversion (expensive).
237
const transactions_cptr& block::transactions_ptr() const NOEXCEPT
85✔
238
{
239
    return txs_;
85✔
240
}
241

242
hashes block::transaction_hashes(bool witness) const NOEXCEPT
11✔
243
{
244
    const auto count = txs_->size();
11✔
245
    const auto size = is_odd(count) && count > one ? add1(count) : count;
11✔
246
    hashes out(size);
11✔
247

248
    // Extra allocation for odd count optimizes for merkle root.
249
    // Vector capacity is never reduced when resizing to smaller size.
250
    out.resize(count);
11✔
251

252
    const auto hash = [witness](const transaction::cptr& tx) NOEXCEPT
25✔
253
    {
254
        return tx->hash(witness);
14✔
255
    };
11✔
256

257
    std::transform(txs_->begin(), txs_->end(), out.begin(), hash);
11✔
258
    return out;
11✔
259
}
260

261
// computed
262
hash_digest block::hash() const NOEXCEPT
34✔
263
{
264
    return header_->hash();
34✔
265
}
266

267
// TODO: this is expensive.
268
size_t block::serialized_size(bool witness) const NOEXCEPT
19✔
269
{
270
    // Overflow returns max_size_t.
271
    const auto sum = [witness](size_t total, const transaction::cptr& tx) NOEXCEPT
42✔
272
    {
273
        return ceilinged_add(total, tx->serialized_size(witness));
23✔
274
    };
19✔
275

276
    return header::serialized_size()
19✔
277
        + variable_size(txs_->size())
19✔
278
        + std::accumulate(txs_->begin(), txs_->end(), zero, sum);
19✔
279
}
280

281
// Connect.
282
// ----------------------------------------------------------------------------
283

284
bool block::is_empty() const NOEXCEPT
2✔
285
{
286
    return txs_->empty();
2✔
287
}
288

289
bool block::is_oversized() const NOEXCEPT
×
290
{
291
    return serialized_size(false) > max_block_size;
×
292
}
293

294
bool block::is_first_non_coinbase() const NOEXCEPT
×
295
{
296
    return !txs_->empty() && !txs_->front()->is_coinbase();
×
297
}
298

299
// True if there is another coinbase other than the first tx.
300
// No txs or coinbases returns false.
301
bool block::is_extra_coinbases() const NOEXCEPT
×
302
{
303
    if (txs_->empty())
×
304
        return false;
305

306
    const auto value = [](const transaction::cptr& tx) NOEXCEPT
×
307
    {
308
        return tx->is_coinbase();
×
309
    };
310

311
    return std::any_of(std::next(txs_->begin()), txs_->end(), value);
×
312
}
313

314
//*****************************************************************************
315
// CONSENSUS: This is only necessary because satoshi stores and queries as it
316
// validates, imposing an otherwise unnecessary partial transaction ordering.
317
//*****************************************************************************
318
bool block::is_forward_reference() const NOEXCEPT
5✔
319
{
320
    // unordered_set manages the maximum load factor (number of elements per
321
    // bucket). The container automatically increases the number of buckets
322
    // if the load factor exceeds this threshold. This defaults to 1.0.
323
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
324
    std::unordered_set<hash_digest, unique_hash_t<>> hashes(txs_->size());
5✔
325
    BC_POP_WARNING()
326

327
    const auto is_forward = [&hashes](const input::cptr& input) NOEXCEPT
7✔
328
    {
329
        BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
330
        return hashes.find(input->point().hash()) != hashes.end();
2✔
331
        BC_POP_WARNING()
332
    };
5✔
333

334
    for (const auto& tx: views_reverse(*txs_))
12✔
335
    {
336
        BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
337
        hashes.emplace(tx->hash(false));
8✔
338
        BC_POP_WARNING()
339

340
        const auto& inputs = *tx->inputs_ptr();
8✔
341
        if (std::any_of(inputs.begin(), inputs.end(), is_forward))
8✔
342
            return true;
1✔
343
    }
344

345
    return false;
4✔
346
}
347

348
// private
349
size_t block::non_coinbase_inputs() const NOEXCEPT
2✔
350
{
351
    // Overflow returns max_size_t.
352
    const auto inputs = [](size_t total, const transaction::cptr& tx) NOEXCEPT
11✔
353
    {
354
        return ceilinged_add(total, tx->inputs());
9✔
355
    };
356

357
    return std::accumulate(std::next(txs_->begin()), txs_->end(), zero, inputs);
2✔
358
}
359

360
// This also precludes the block merkle calculation DoS exploit.
361
// bitcointalk.org/?topic=102395
362
bool block::is_internal_double_spend() const NOEXCEPT
3✔
363
{
364
    if (txs_->empty())
3✔
365
        return false;
366

367
    const auto inputs = non_coinbase_inputs();
2✔
368
    std::vector<point> outs{};
2✔
369
    outs.reserve(inputs);
2✔
370

371
    // Copy all block.txs.points into the vector.
372
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
11✔
373
    {
374
        auto out = (*tx)->points();
9✔
375
        std::move(out.begin(), out.end(), std::inserter(outs, outs.end()));
9✔
376
    }
9✔
377

378
    distinct(outs);
2✔
379
    return outs.size() != inputs;
2✔
380
}
2✔
381

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

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

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

396
size_t block::weight() const NOEXCEPT
×
397
{
398
    // Block weight is 3 * Base size * + 1 * Total size (bip141).
399
    return base_size_contribution * serialized_size(false) +
×
400
        total_size_contribution * serialized_size(true);
×
401
}
402

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

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

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

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

426
    // A set is used to collapse duplicates.
NEW
427
    std::unordered_set<hash_digest, unique_hash_t<>> hashes;
×
428

429
    // Just the coinbase tx hash, skip its null input hashes.
430
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
431
    hashes.insert(txs_->front()->hash(false));
×
432
    BC_POP_WARNING()
433

434
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
435
    {
436
        // Insert the transaction hash.
437
        BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
438
        hashes.insert((*tx)->hash(false));
×
439
        BC_POP_WARNING()
440

441
        const auto& inputs = *(*tx)->inputs_ptr();
×
442

443
        // Insert all input point hashes.
444
        for (const auto& input: inputs)
×
445
        {
446
            BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
447
            hashes.insert(input->point().hash());
×
448
            BC_POP_WARNING()
449
        }
450
    }
451

452
    return hashes.size() > hash_limit;
×
453
}
454

455
bool block::is_malleable() const NOEXCEPT
3✔
456
{
457
    return is_malleable64() || is_malleable32();
3✔
458
}
459

460
bool block::is_malleable32() const NOEXCEPT
12✔
461
{
462
    const auto unmalleated = txs_->size();
12✔
463
    for (auto mally = one; mally <= unmalleated; mally *= two)
23✔
464
        if (is_malleable32(unmalleated, mally))
17✔
465
            return true;
466

467
    return false;
468
}
469

470
bool block::is_malleated32() const NOEXCEPT
11✔
471
{
472
    return !is_zero(malleated32_size());
11✔
473
}
474

475
// protected
476
// The size of an actual malleation of this block, or zero.
477
size_t block::malleated32_size() const NOEXCEPT
11✔
478
{
479
    const auto malleated = txs_->size();
11✔
480
    for (auto mally = one; mally <= to_half(malleated); mally *= two)
23✔
481
        if (is_malleable32(malleated - mally, mally) &&
20✔
482
            is_malleated32(mally))
6✔
483
            return mally;
2✔
484

485
    return zero;
486
}
487

488
// protected
489
// True if the last width set of tx hashes repeats.
490
bool block::is_malleated32(size_t width) const NOEXCEPT
7✔
491
{
492
    const auto malleated = txs_->size();
7✔
493
    if (is_zero(width) || width > to_half(malleated))
7✔
494
        return false;
495

496
    auto mally = txs_->rbegin();
6✔
497
    auto legit = std::next(mally, width);
6✔
498
    while (!is_zero(width--))
9✔
499
        if ((*mally++)->hash(false) != (*legit++)->hash(false))
7✔
500
            return false;
501

502
    return true;
503
}
504

505
bool block::is_malleable64() const NOEXCEPT
12✔
506
{
507
    return is_malleable64(*txs_);
12✔
508
}
509

510
// static
511
// If all non-witness tx serializations are 64 bytes the id is malleable.
512
// This form of malleability does not imply current block instance is invalid.
513
bool block::is_malleable64(const transaction_cptrs& txs) NOEXCEPT
12✔
514
{
515
    const auto two_leaves = [](const transaction::cptr& tx) NOEXCEPT
27✔
516
    {
517
        return tx->serialized_size(false) == two * hash_size;
15✔
518
    };
519

520
    return !txs.empty() && std::all_of(txs.begin(), txs.end(), two_leaves);
12✔
521
}
522

523
bool block::is_segregated() const NOEXCEPT
×
524
{
525
    const auto segregated = [](const transaction::cptr& tx) NOEXCEPT
×
526
    {
527
        return tx->is_segregated();
×
528
    };
529

530
    return std::any_of(txs_->begin(), txs_->end(), segregated);
×
531
}
532

533
bool block::is_invalid_witness_commitment() const NOEXCEPT
×
534
{
535
    if (txs_->empty())
×
536
        return false;
537

538
    const auto& coinbase = *txs_->front();
×
539
    if (coinbase.inputs_ptr()->empty())
×
540
        return false;
541

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

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

573
// Prevouts required.
574

575
uint64_t block::fees() const NOEXCEPT
×
576
{
577
    // Overflow returns max_uint64.
578
    const auto value = [](uint64_t total, const transaction::cptr& tx) NOEXCEPT
×
579
    {
580
        return ceilinged_add(total, tx->fee());
×
581
    };
582

583
    return std::accumulate(txs_->begin(), txs_->end(), uint64_t{0}, value);
×
584
}
585

586
uint64_t block::claim() const NOEXCEPT
×
587
{
588
    return txs_->empty() ? zero : txs_->front()->value();
×
589
}
590

591
uint64_t block::reward(size_t height, uint64_t subsidy_interval,
×
592
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
593
{
594
    // Overflow returns max_uint64.
595
    return ceilinged_add(fees(), block_subsidy(height, subsidy_interval,
×
596
        initial_block_subsidy_satoshi, bip42));
×
597
}
598

599
bool block::is_overspent(size_t height, uint64_t subsidy_interval,
×
600
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
601
{
602
    return claim() > reward(height, subsidy_interval,
×
603
        initial_block_subsidy_satoshi, bip42);
×
604
}
605

606
size_t block::signature_operations(bool bip16, bool bip141) const NOEXCEPT
×
607
{
608
    // Overflow returns max_size_t.
609
    const auto value = [=](size_t total, const transaction::cptr& tx) NOEXCEPT
×
610
    {
611
        return ceilinged_add(total, tx->signature_operations(bip16, bip141));
×
612
    };
×
613

614
    return std::accumulate(txs_->begin(), txs_->end(), zero, value);
×
615
}
616

617
bool block::is_signature_operations_limited(bool bip16,
×
618
    bool bip141) const NOEXCEPT
619
{
620
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
621
    return signature_operations(bip16, bip141) > limit;
×
622
}
623

624
//*****************************************************************************
625
// CONSENSUS:
626
// This check is excluded under two bip30 exception blocks and bip30_deactivate
627
// until bip30_reactivate. These conditions are rolled up into the bip30 flag.
628
//*****************************************************************************
629
bool block::is_unspent_coinbase_collision() const NOEXCEPT
×
630
{
631
    if (txs_->empty() || txs_->front()->inputs_ptr()->empty())
×
632
        return false;
×
633

634
    // May only commit duplicate coinbase that is already confirmed spent.
635
    // Metadata population defaults coinbase to spent (not a collision).
636
    return !txs_->front()->inputs_ptr()->front()->metadata.spent;
×
637
}
638

639
// Search is not ordered, forward references are caught by block.check.
640
void block::populate() const NOEXCEPT
×
641
{
642
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
643
    std::unordered_map<point, output::cptr> points{};
×
644
    uint32_t index{};
×
645

646
    // Populate outputs hash table.
647
    for (auto tx = txs_->begin(); tx != txs_->end(); ++tx, index = 0)
×
648
        for (const auto& out: *(*tx)->outputs_ptr())
×
649
            points.emplace(point{ (*tx)->hash(false), index++ }, out);
×
650

651
    // Populate input prevouts from hash table.
652
    for (auto tx = txs_->begin(); tx != txs_->end(); ++tx)
×
653
    {
654
        for (const auto& in: *(*tx)->inputs_ptr())
×
655
        {
656
            const auto point = points.find(in->point());
×
657
            if (point != points.end())
×
658
                in->prevout = point->second;
×
659
        }
660
    }
661

662
    BC_POP_WARNING()
663
}
×
664

665
// Delegated.
666
// ----------------------------------------------------------------------------
667

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

677
    return error::block_success;
×
678
}
679

680
// DO invoke on coinbase.
681
code block::check_transactions(const context& ctx) const NOEXCEPT
×
682
{
683
    code ec;
×
684
    
685
    for (const auto& tx: *txs_)
×
686
        if ((ec = tx->check(ctx)))
×
687
            return ec;
×
688

689
    return error::block_success;
×
690
}
691

692
// Do NOT invoke on coinbase.
693
code block::accept_transactions(const context& ctx) const NOEXCEPT
×
694
{
695
    code ec;
×
696

697
    if (!is_empty())
×
698
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
699
            if ((ec = (*tx)->accept(ctx)))
×
700
                return ec;
×
701

702
    return error::block_success;
×
703
}
704

705
// Do NOT invoke on coinbase.
706
code block::connect_transactions(const context& ctx) const NOEXCEPT
×
707
{
708
    code ec;
×
709

710
    if (!is_empty())
×
711
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
712
            if ((ec = (*tx)->connect(ctx)))
×
713
                return ec;
×
714

715
    return error::block_success;
×
716
}
717

718
// Do NOT invoke on coinbase.
719
code block::confirm_transactions(const context& ctx) const NOEXCEPT
×
720
{
721
    code ec;
×
722

723
    if (!is_empty())
×
724
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
725
            if ((ec = (*tx)->confirm(ctx)))
×
726
                return ec;
×
727

728
    return error::block_success;
×
729
}
730

731
// Validation.
732
// ----------------------------------------------------------------------------
733
// The block header is checked/accepted independently.
734

735
code block::check() const NOEXCEPT
×
736
{
737
    // context free.
738
    // empty_block is redundant with first_not_coinbase.
739
    //if (is_empty())
740
    //    return error::empty_block;
741
    if (is_oversized())
×
742
        return error::block_size_limit;
×
743
    if (is_first_non_coinbase())
×
744
        return error::first_not_coinbase;
×
745
    if (is_extra_coinbases())
×
746
        return error::extra_coinbases;
×
747
    if (is_forward_reference())
×
748
        return error::forward_reference;
×
749
    if (is_internal_double_spend())
×
750
        return error::block_internal_double_spend;
×
751
    if (is_invalid_merkle_root())
×
752
        return error::merkle_mismatch;
×
753

754
    return check_transactions();
×
755
}
756

757
// forks
758
// height
759
// timestamp
760
// median_time_past
761

762
code block::check(const context& ctx) const NOEXCEPT
×
763
{
764
    const auto bip34 = ctx.is_enabled(bip34_rule);
×
765
    const auto bip50 = ctx.is_enabled(bip50_rule);
×
766
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
767

768
    // context required.
769
    if (bip141 && is_overweight())
×
770
        return error::block_weight_limit;
×
771
    if (bip34 && is_invalid_coinbase_script(ctx.height))
×
772
        return error::coinbase_height_mismatch;
×
773
    if (bip50 && is_hash_limit_exceeded())
×
774
        return error::temporary_hash_limit;
×
775
    if (bip141 && is_invalid_witness_commitment())
×
776
        return error::invalid_witness_commitment;
×
777

778
    return check_transactions(ctx);
×
779
}
780

781
// forks
782
// height
783

784
// This assumes that prevout caching is completed on all inputs.
785
code block::accept(const context& ctx, size_t subsidy_interval,
×
786
    uint64_t initial_subsidy) const NOEXCEPT
787
{
788
    const auto bip16 = ctx.is_enabled(bip16_rule);
×
789
    const auto bip42 = ctx.is_enabled(bip42_rule);
×
790
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
791

792
    // prevouts required.
793
    if (is_overspent(ctx.height, subsidy_interval, initial_subsidy, bip42))
×
794
        return error::coinbase_value_limit;
×
795
    if (is_signature_operations_limited(bip16, bip141))
×
796
        return error::block_sigop_limit;
×
797

798
    return accept_transactions(ctx);
×
799
}
800

801
// forks
802

803
// Node performs these checks through database query.
804
// This assumes that prevout and metadata caching are completed on all inputs.
805
code block::confirm(const context& ctx) const NOEXCEPT
×
806
{
807
    const auto bip30 = ctx.is_enabled(bip30_rule);
×
808

809
    if (bip30 && is_unspent_coinbase_collision())
×
810
        return error::unspent_coinbase_collision;
×
811

812
    return confirm_transactions(ctx);
×
813
}
814

815
// forks
816

817
code block::connect(const context& ctx) const NOEXCEPT
×
818
{
819
    return connect_transactions(ctx);
×
820
}
821

822
// JSON value convertors.
823
// ----------------------------------------------------------------------------
824

825
namespace json = boost::json;
826

827
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
828
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
829

830
block tag_invoke(json::value_to_tag<block>,
1✔
831
    const json::value& value) NOEXCEPT
832
{
833
    return
1✔
834
    {
835
        json::value_to<header>(value.at("header")),
1✔
836
        json::value_to<chain::transactions>(value.at("transactions"))
2✔
837
    };
1✔
838
}
839

840
void tag_invoke(json::value_from_tag, json::value& value,
2✔
841
    const block& block) NOEXCEPT
842
{
843
    value =
2✔
844
    {
845
        { "header", block.header() },
846
        { "transactions", *block.transactions_ptr() },
847
    };
2✔
848
}
2✔
849

850
BC_POP_WARNING()
851

852
block::cptr tag_invoke(json::value_to_tag<block::cptr>,
×
853
    const json::value& value) NOEXCEPT
854
{
855
    return to_shared(tag_invoke(json::value_to_tag<block>{}, value));
×
856
}
857

858
// Shared pointer overload is required for navigation.
859
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
860
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
861

862
void tag_invoke(json::value_from_tag tag, json::value& value,
×
863
    const block::cptr& block) NOEXCEPT
864
{
865
    tag_invoke(tag, value, *block);
×
866
}
×
867

868
BC_POP_WARNING()
869
BC_POP_WARNING()
870

871
} // namespace chain
872
} // namespace system
873
} // 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