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

libbitcoin / libbitcoin-system / 9556127807

17 Jun 2024 11:14PM UTC coverage: 82.716% (-0.03%) from 82.744%
9556127807

Pull #1481

github

web-flow
Merge c5e719e80 into b619ff2dd
Pull Request #1481: Add malleated64 check based on coinbase invalidity.

0 of 6 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

NEW
455
bool block::is_malleated() const NOEXCEPT
×
456
{
NEW
457
    return is_malleated32() || is_malleated64();
×
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. It is possible but computationally infeasible to grind a valid
524
// coinbase and therefore treated similarly to sha256 hash collision.
NEW
525
bool block::is_malleated64() const NOEXCEPT
×
526
{
NEW
527
    return is_malleable64(*txs_) && !txs_->front()->is_coinbase();
×
528
}
529

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

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

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

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

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

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

585
// Prevouts required.
586

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

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

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

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

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

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

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

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

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

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

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

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

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

675
// Delegated.
676
// ----------------------------------------------------------------------------
677

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

687
    return error::block_success;
×
688
}
689

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

699
    return error::block_success;
×
700
}
701

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

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

712
    return error::block_success;
×
713
}
714

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

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

725
    return error::block_success;
×
726
}
727

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

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

738
    return error::block_success;
×
739
}
740

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

745
// context free.
746
// TODO: use of get_hash() in is_forward_reference makes this thread unsafe.
747
code block::check(bool bypass) const NOEXCEPT
×
748
{
749
    if (is_invalid_merkle_root())
×
750
        return error::invalid_transaction_commitment;
×
751

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

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

773
    return check_transactions();
×
774
}
775

776
// forks
777
// height
778
// timestamp
779
// median_time_past
780

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

787
    if (bip141 && is_invalid_witness_commitment())
×
788
        return error::invalid_witness_commitment;
×
789

790
    if (bypass)        
×
791
        return error::block_success;
×
792

793
    const auto bip34 = ctx.is_enabled(bip34_rule);
×
794
    const auto bip50 = ctx.is_enabled(bip50_rule);
×
795

796
    if (bip141 && is_overweight())
×
797
        return error::block_weight_limit;
×
798
    if (bip34 && is_invalid_coinbase_script(ctx.height))
×
799
        return error::coinbase_height_mismatch;
×
800
    if (bip50 && is_hash_limit_exceeded())
×
801
        return error::temporary_hash_limit;
×
802

803
    return check_transactions(ctx);
×
804
}
805

806
// forks
807
// height
808

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

817
    // prevouts required.
818
    if (is_overspent(ctx.height, subsidy_interval, initial_subsidy, bip42))
×
819
        return error::coinbase_value_limit;
×
820
    if (is_signature_operations_limited(bip16, bip141))
×
821
        return error::block_sigop_limit;
×
822

823
    return accept_transactions(ctx);
×
824
}
825

826
// forks
827

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

834
    if (bip30 && is_unspent_coinbase_collision())
×
835
        return error::unspent_coinbase_collision;
×
836

837
    return confirm_transactions(ctx);
×
838
}
839

840
// forks
841

842
code block::connect(const context& ctx) const NOEXCEPT
×
843
{
844
    return connect_transactions(ctx);
×
845
}
846

847
BC_POP_WARNING()
848

849
// JSON value convertors.
850
// ----------------------------------------------------------------------------
851

852
namespace json = boost::json;
853

854
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
855
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
856

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

867
void tag_invoke(json::value_from_tag, json::value& value,
2✔
868
    const block& block) NOEXCEPT
869
{
870
    value =
2✔
871
    {
872
        { "header", block.header() },
873
        { "transactions", *block.transactions_ptr() },
874
    };
2✔
875
}
2✔
876

877
BC_POP_WARNING()
878

879
block::cptr tag_invoke(json::value_to_tag<block::cptr>,
×
880
    const json::value& value) NOEXCEPT
881
{
882
    return to_shared(tag_invoke(json::value_to_tag<block>{}, value));
×
883
}
884

885
// Shared pointer overload is required for navigation.
886
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
887
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
888

889
void tag_invoke(json::value_from_tag tag, json::value& value,
×
890
    const block::cptr& block) NOEXCEPT
891
{
892
    tag_invoke(tag, value, *block);
×
893
}
×
894

895
BC_POP_WARNING()
896
BC_POP_WARNING()
897

898
} // namespace chain
899
} // namespace system
900
} // 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