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

libbitcoin / libbitcoin-system / 9717609804

28 Jun 2024 07:41PM UTC coverage: 82.716%. Remained the same
9717609804

Pull #1484

github

web-flow
Merge 47940a823 into 0ac7d4f9d
Pull Request #1484: Change malleation check ordering.

0 of 4 new or added lines in 1 file covered. (0.0%)

1 existing line in 1 file now uncovered.

9854 of 11913 relevant lines covered (82.72%)

4787248.89 hits per line

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

46.54
/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
63✔
53
  : block(to_shared<chain::header>(), to_shared<chain::transaction_cptrs>(),
63✔
54
      false)
189✔
55
{
56
}
63✔
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
71✔
77
  : block(stream::in::copy(data), witness)
71✔
78
{
79
}
71✔
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
71✔
92
  : block(read::bytes::istream(stream), witness)
71✔
93
{
94
}
71✔
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
75✔
102
  : block(from_data(source, witness))
75✔
103
{
104
}
75✔
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,
180✔
113
    const chain::transactions_cptr& txs, bool valid) NOEXCEPT
180✔
114
  : header_(header),
115
    txs_(txs),
116
    valid_(valid),
180✔
117
    size_(serialized_size(*txs))
360✔
118
{
119
}
180✔
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
76✔
140
{
141
    const auto read_transactions = [witness](reader& source) NOEXCEPT
152✔
142
    {
143
        auto txs = to_shared<transaction_cptrs>();
76✔
144
        const auto capacity = source.read_size(max_block_size);
76✔
145
        txs->reserve(capacity);
76✔
146

147
        for (size_t tx = 0; tx < capacity; ++tx)
197✔
148
            txs->push_back(to_shared<transaction>(source, witness));
242✔
149

150
        // This is a pointer copy (non-const to const).
151
        return txs;
76✔
152
    };
76✔
153

154
    return
76✔
155
    {
156
        to_shared<chain::header>(source),
76✔
157
        read_transactions(source),
152✔
158
        source
159
    };
152✔
160
}
161

162
// Serialization.
163
// ----------------------------------------------------------------------------
164

165
data_chunk block::to_data(bool witness) const NOEXCEPT
18✔
166
{
167
    data_chunk data(serialized_size(witness));
36✔
168
    stream::out::copy ostream(data);
18✔
169
    to_data(ostream, witness);
18✔
170
    return data;
36✔
171
}
18✔
172

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

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

184
    for (const auto& tx: *txs_)
46✔
185
        tx->to_data(sink, witness);
26✔
186
}
20✔
187

188
// Properties.
189
// ----------------------------------------------------------------------------
190

191
bool block::is_valid() const NOEXCEPT
32✔
192
{
193
    return valid_;
32✔
194
}
195

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

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

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

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

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

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

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

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

242
    const auto hash = [witness](const auto& tx) NOEXCEPT
14✔
243
    {
244
        return tx->hash(witness);
14✔
245
    };
11✔
246

247
    std::transform(txs_->begin(), txs_->end(), out.begin(), hash);
11✔
248
    return out;
11✔
249
}
250

251
// computed
252
hash_digest block::hash() const NOEXCEPT
36✔
253
{
254
    return header_->hash();
36✔
255
}
256

257
// computed
258
const hash_digest& block::get_hash() const NOEXCEPT
×
259
{
260
    return header_->get_hash();
×
261
}
262

263
// static/private
264
block::sizes block::serialized_size(
180✔
265
    const chain::transaction_cptrs& txs) NOEXCEPT
266
{
267
    sizes size{};
180✔
268
    std::for_each(txs.begin(), txs.end(), [&](const auto& tx) NOEXCEPT
429✔
269
    {
270
        size.nominal = ceilinged_add(size.nominal, tx->serialized_size(false));
498✔
271
        size.witnessed = ceilinged_add(size.witnessed, tx->serialized_size(true));
249✔
272
    });
249✔
273

274
    const auto common_size = ceilinged_add(
180✔
275
        header::serialized_size(),
276
        variable_size(txs.size()));
277

278
    const auto nominal_size = ceilinged_add(
180✔
279
        common_size,
280
        size.nominal);
281

282
    const auto witnessed_size = ceilinged_add(
180✔
283
        common_size,
284
        size.witnessed);
285

286
    return { nominal_size, witnessed_size };
180✔
287
}
288

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

294
// Connect.
295
// ----------------------------------------------------------------------------
296

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

396
// Accept (contextual).
397
// ----------------------------------------------------------------------------
398

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

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

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

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

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

430
    // A set is used to collapse duplicates.
431
    unordered_set_of_constant_referenced_hashes hashes{};
×
432

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

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

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

447
    return hashes.size() > hash_limit;
×
448
}
449

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

455
bool block::is_malleated() const NOEXCEPT
×
456
{
NEW
457
    return is_malleated64() || is_malleated32();
×
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) && is_malleated32(mally))
14✔
482
            return mally;
2✔
483

484
    return zero;
485
}
486

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

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

501
    return true;
502
}
503

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

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

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

522
// A mallaeable64 block is considered malleated if the first tx is not a valid
523
// coinbase and all txs are 64 bytes. It is possible but computationally
524
// infeasible to grind a valid coinbase and therefore treated similarly to
525
// sha256 hash collision.
UNCOV
526
bool block::is_malleated64() const NOEXCEPT
×
527
{
NEW
528
    return !txs_->front()->is_coinbase() && is_malleable64(*txs_);
×
529
}
530

531
bool block::is_segregated() const NOEXCEPT
×
532
{
533
    const auto segregated = [](const auto& tx) NOEXCEPT
×
534
    {
535
        return tx->is_segregated();
×
536
    };
537

538
    return std::any_of(txs_->begin(), txs_->end(), segregated);
×
539
}
540

541
// The witness merkle root is obtained from wtxids, subject to malleation just
542
// as the txs commitment. However, since tx duplicates are precluded by the
543
// malleable32 (or complete) block check, there is no opportunity for this.
544
// Similarly the witness commitment cannot be malleable64.
545
bool block::is_invalid_witness_commitment() const NOEXCEPT
×
546
{
547
    if (txs_->empty())
×
548
        return false;
549

550
    const auto& coinbase = *txs_->front();
×
551
    if (coinbase.inputs_ptr()->empty())
×
552
        return false;
553

554
    // If there is a valid commitment, return false (valid).
555
    // Coinbase input witness must be 32 byte witness reserved value (bip141).
556
    // Last output of commitment pattern holds the committed value (bip141).
557
    hash_digest reserved{}, committed{};
×
558
    if (coinbase.inputs_ptr()->front()->reserved_hash(reserved))
×
559
        for (const auto& output: views_reverse(*coinbase.outputs_ptr()))
×
560
            if (output->committed_hash(committed))
×
561
                if (committed == sha256::double_hash(
×
562
                    generate_merkle_root(true), reserved))
×
563
                    return false;
564
    
565
    // If no valid commitment, return true (invalid) if segregated.
566
    // If no block tx has witness data the commitment is optional (bip141).
567
    return is_segregated();
×
568
}
569

570
//*****************************************************************************
571
// CONSENSUS:
572
// bip42 compensates for C++ undefined behavior of a right shift of a number of
573
// bits greater or equal to the shifted integer width. Yet being undefined, the
574
// result of this operation may vary by compiler. The shift_right call below
575
// explicitly implements presumed pre-bip42 behavior (shift overflow modulo) by
576
// default, and specified bip42 behavior (shift overflow to zero) with bip42.
577
//*****************************************************************************
578
static uint64_t block_subsidy(size_t height, uint64_t subsidy_interval,
×
579
    uint64_t initial_block_subsidy_satoshi, bool bip42) NOEXCEPT
580
{
581
    // Guard: quotient domain cannot increase with positive integer divisor.
582
    const auto halves = possible_narrow_cast<size_t>(height / subsidy_interval);
×
583
    return shift_right(initial_block_subsidy_satoshi, halves, bip42);
×
584
}
585

586
// Prevouts required.
587

588
uint64_t block::fees() const NOEXCEPT
×
589
{
590
    // Overflow returns max_uint64.
591
    const auto value = [](uint64_t total, const auto& tx) NOEXCEPT
×
592
    {
593
        return ceilinged_add(total, tx->fee());
×
594
    };
595

596
    return std::accumulate(txs_->begin(), txs_->end(), uint64_t{0}, value);
×
597
}
598

599
uint64_t block::claim() const NOEXCEPT
×
600
{
601
    return txs_->empty() ? zero : txs_->front()->value();
×
602
}
603

604
uint64_t block::reward(size_t height, uint64_t subsidy_interval,
×
605
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
606
{
607
    // Overflow returns max_uint64.
608
    return ceilinged_add(fees(), block_subsidy(height, subsidy_interval,
×
609
        initial_block_subsidy_satoshi, bip42));
×
610
}
611

612
bool block::is_overspent(size_t height, uint64_t subsidy_interval,
×
613
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
614
{
615
    return claim() > reward(height, subsidy_interval,
×
616
        initial_block_subsidy_satoshi, bip42);
×
617
}
618

619
size_t block::signature_operations(bool bip16, bool bip141) const NOEXCEPT
×
620
{
621
    // Overflow returns max_size_t.
622
    const auto value = [=](size_t total, const auto& tx) NOEXCEPT
×
623
    {
624
        return ceilinged_add(total, tx->signature_operations(bip16, bip141));
×
625
    };
×
626

627
    return std::accumulate(txs_->begin(), txs_->end(), zero, value);
×
628
}
629

630
bool block::is_signature_operations_limited(bool bip16,
×
631
    bool bip141) const NOEXCEPT
632
{
633
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
634
    return signature_operations(bip16, bip141) > limit;
×
635
}
636

637
//*****************************************************************************
638
// CONSENSUS:
639
// This check is excluded under two bip30 exception blocks and bip30_deactivate
640
// until bip30_reactivate. These conditions are rolled up into the bip30 flag.
641
//*****************************************************************************
642
bool block::is_unspent_coinbase_collision() const NOEXCEPT
×
643
{
644
    if (txs_->empty() || txs_->front()->inputs_ptr()->empty())
×
645
        return false;
×
646

647
    // May only commit duplicate coinbase that is already confirmed spent.
648
    // Metadata population defaults coinbase to spent (not a collision).
649
    return !txs_->front()->inputs_ptr()->front()->metadata.spent;
×
650
}
651

652
// Search is not ordered, forward references are caught by block.check.
653
void block::populate() const NOEXCEPT
×
654
{
655
    std::unordered_map<point, output::cptr> points{};
×
656
    uint32_t index{};
×
657

658
    // Populate outputs hash table.
659
    for (auto tx = txs_->begin(); tx != txs_->end(); ++tx, index = 0)
×
660
        for (const auto& out: *(*tx)->outputs_ptr())
×
661
            points.emplace(std::pair{ point{ (*tx)->hash(false), index++ },
×
662
                out });
663

664
    // Populate input prevouts from hash table.
665
    for (auto tx = txs_->begin(); tx != txs_->end(); ++tx)
×
666
    {
667
        for (const auto& in: *(*tx)->inputs_ptr())
×
668
        {
669
            const auto point = points.find(in->point());
×
670
            if (point != points.end())
×
671
                in->prevout = point->second;
×
672
        }
673
    }
674
}
×
675

676
// Delegated.
677
// ----------------------------------------------------------------------------
678

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

688
    return error::block_success;
×
689
}
690

691
// DO invoke on coinbase.
692
code block::check_transactions(const context& ctx) const NOEXCEPT
×
693
{
694
    code ec;
×
695
    
696
    for (const auto& tx: *txs_)
×
697
        if ((ec = tx->check(ctx)))
×
698
            return ec;
×
699

700
    return error::block_success;
×
701
}
702

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

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

713
    return error::block_success;
×
714
}
715

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

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

726
    return error::block_success;
×
727
}
728

729
// Do NOT invoke on coinbase.
730
code block::confirm_transactions(const context& ctx) const NOEXCEPT
×
731
{
732
    code ec;
×
733

734
    if (!is_empty())
×
735
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
736
            if ((ec = (*tx)->confirm(ctx)))
×
737
                return ec;
×
738

739
    return error::block_success;
×
740
}
741

742
// Validation.
743
// ----------------------------------------------------------------------------
744
// The block header is checked/accepted independently.
745

746
// context free.
747
// TODO: use of get_hash() in is_forward_reference makes this thread unsafe.
748
code block::check(bool bypass) const NOEXCEPT
×
749
{
750
    // Node relies on error::block_malleated.
751
    // Node relies on error::invalid_transaction_commitment.
752

753
    // type32 malleated is a subset of is_internal_double_spend.
754
    // type64 malleated is a subset of first_not_coinbase.
755
    if (bypass && is_malleated())
×
756
        return error::block_malleated;
×
NEW
757
    if (is_invalid_merkle_root())
×
NEW
758
        return error::invalid_transaction_commitment;
×
759
    if (bypass)
×
760
        return error::block_success;
×
761

762
    // empty_block is subset of first_not_coinbase.
763
    //if (is_empty())
764
    //    return error::empty_block;
765
    if (is_oversized())
×
766
        return error::block_size_limit;
×
767
    if (is_first_non_coinbase())
×
768
        return error::first_not_coinbase;
×
769
    if (is_extra_coinbases())
×
770
        return error::extra_coinbases;
×
771
    if (is_forward_reference())
×
772
        return error::forward_reference;
×
773
    if (is_internal_double_spend())
×
774
        return error::block_internal_double_spend;
×
775

776
    return check_transactions();
×
777
}
778

779
// forks
780
// height
781
// timestamp
782
// median_time_past
783

784
// context required.
785
// TODO: use of get_hash() in is_hash_limit_exceeded makes this thread unsafe.
786
code block::check(const context& ctx, bool bypass) const NOEXCEPT
×
787
{
788
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
789

790
    // Node relies on error::invalid_witness_commitment.
791
    if (bip141 && is_invalid_witness_commitment())
×
792
        return error::invalid_witness_commitment;
×
793

794
    if (bypass)        
×
795
        return error::block_success;
×
796

797
    const auto bip34 = ctx.is_enabled(bip34_rule);
×
798
    const auto bip50 = ctx.is_enabled(bip50_rule);
×
799

800
    if (bip141 && is_overweight())
×
801
        return error::block_weight_limit;
×
802
    if (bip34 && is_invalid_coinbase_script(ctx.height))
×
803
        return error::coinbase_height_mismatch;
×
804
    if (bip50 && is_hash_limit_exceeded())
×
805
        return error::temporary_hash_limit;
×
806

807
    return check_transactions(ctx);
×
808
}
809

810
// forks
811
// height
812

813
// This assumes that prevout caching is completed on all inputs.
814
code block::accept(const context& ctx, size_t subsidy_interval,
×
815
    uint64_t initial_subsidy) const NOEXCEPT
816
{
817
    const auto bip16 = ctx.is_enabled(bip16_rule);
×
818
    const auto bip42 = ctx.is_enabled(bip42_rule);
×
819
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
820

821
    // prevouts required.
822
    if (is_overspent(ctx.height, subsidy_interval, initial_subsidy, bip42))
×
823
        return error::coinbase_value_limit;
×
824
    if (is_signature_operations_limited(bip16, bip141))
×
825
        return error::block_sigop_limit;
×
826

827
    return accept_transactions(ctx);
×
828
}
829

830
// forks
831

832
// Node performs these checks through database query.
833
// This assumes that prevout and metadata caching are completed on all inputs.
834
code block::confirm(const context& ctx) const NOEXCEPT
×
835
{
836
    const auto bip30 = ctx.is_enabled(bip30_rule);
×
837

838
    if (bip30 && is_unspent_coinbase_collision())
×
839
        return error::unspent_coinbase_collision;
×
840

841
    return confirm_transactions(ctx);
×
842
}
843

844
// forks
845

846
code block::connect(const context& ctx) const NOEXCEPT
×
847
{
848
    return connect_transactions(ctx);
×
849
}
850

851
BC_POP_WARNING()
852

853
// JSON value convertors.
854
// ----------------------------------------------------------------------------
855

856
namespace json = boost::json;
857

858
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
859
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
860

861
block tag_invoke(json::value_to_tag<block>,
1✔
862
    const json::value& value) NOEXCEPT
863
{
864
    return
1✔
865
    {
866
        json::value_to<header>(value.at("header")),
1✔
867
        json::value_to<chain::transactions>(value.at("transactions"))
2✔
868
    };
1✔
869
}
870

871
void tag_invoke(json::value_from_tag, json::value& value,
2✔
872
    const block& block) NOEXCEPT
873
{
874
    value =
2✔
875
    {
876
        { "header", block.header() },
877
        { "transactions", *block.transactions_ptr() },
878
    };
2✔
879
}
2✔
880

881
BC_POP_WARNING()
882

883
block::cptr tag_invoke(json::value_to_tag<block::cptr>,
×
884
    const json::value& value) NOEXCEPT
885
{
886
    return to_shared(tag_invoke(json::value_to_tag<block>{}, value));
×
887
}
888

889
// Shared pointer overload is required for navigation.
890
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
891
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
892

893
void tag_invoke(json::value_from_tag tag, json::value& value,
×
894
    const block::cptr& block) NOEXCEPT
895
{
896
    tag_invoke(tag, value, *block);
×
897
}
×
898

899
BC_POP_WARNING()
900
BC_POP_WARNING()
901

902
} // namespace chain
903
} // namespace system
904
} // 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