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

libbitcoin / libbitcoin-system / 10166595277

30 Jul 2024 05:00PM UTC coverage: 83.166% (-0.02%) from 83.181%
10166595277

push

github

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

Change block's memory retainer cache to shared_ptr.

1 of 1 new or added line in 1 file covered. (100.0%)

1 existing line in 1 file now uncovered.

10093 of 12136 relevant lines covered (83.17%)

4758177.36 hits per line

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

52.43
/src/chain/block.cpp
1
/**
2
 * Copyright (c) 2011-2023 libbitcoin developers (see AUTHORS)
3
 *
4
 * This file is part of libbitcoin.
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Affero General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU Affero General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Affero General Public License
17
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19
#include <bitcoin/system/chain/block.hpp>
20

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

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

46
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
47
BC_PUSH_WARNING(NO_UNGUARDED_POINTERS)
48

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

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

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

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

69
block::block(const chain::header::cptr& header,
×
70
    const 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
73✔
77
  : block(stream::in::copy(data), witness)
73✔
78
{
79
}
73✔
80

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

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

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

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

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

106
block::block(reader& source, bool witness) NOEXCEPT
82✔
107
  : header_(
82✔
108
        source.get_allocator().new_object<chain::header>(source),
82✔
109
        source.get_allocator().deleter<chain::header>(source.get_arena())),
82✔
110
    txs_(
164✔
111
        source.get_allocator().new_object<transaction_cptrs>(),
82✔
112
        source.get_allocator().deleter<transaction_cptrs>(source.get_arena()))
164✔
113
{
114
    assign_data(source, witness);
82✔
115
}
82✔
116

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

127
// Operators.
128
// ----------------------------------------------------------------------------
129

130
bool block::operator==(const block& other) const NOEXCEPT
29✔
131
{
132
    return (header_ == other.header_ || *header_ == *other.header_)
29✔
133
        && deep_equal(*txs_, *other.txs_);
37✔
134
}
135

136
bool block::operator!=(const block& other) const NOEXCEPT
5✔
137
{
138
    return !(*this == other);
5✔
139
}
140

141
// Deserialization.
142
// ----------------------------------------------------------------------------
143

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

152
    for (size_t tx = 0; tx < count; ++tx)
212✔
153
        txs->emplace_back(
260✔
154
            allocator.new_object<transaction>(source, witness),
130✔
155
            allocator.deleter<transaction>(source.get_arena()));
260✔
156

157
    size_ = serialized_size(*txs_);
82✔
158
    valid_ = source;
82✔
159
}
82✔
160

161
// Retainer will be an empty pointer when default allocator is used.
162
// Retainer release informs allocator that associated memory may be freed.
163
// Retainer is copied on block copy/assign, since allocations are thus shared.
164
// WARNING: retainer does not track objects shared from the block (e.g. tx).
UNCOV
165
void block::set_retainer(retainer::ptr&& retainer) const NOEXCEPT
×
166
{
167
    retainer_ = std::move(retainer);
×
168
}
×
169

170
// Serialization.
171
// ----------------------------------------------------------------------------
172

173
data_chunk block::to_data(bool witness) const NOEXCEPT
20✔
174
{
175
    data_chunk data(serialized_size(witness));
40✔
176
    stream::out::copy ostream(data);
20✔
177
    to_data(ostream, witness);
20✔
178
    return data;
40✔
179
}
20✔
180

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

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

192
    for (const auto& tx: *txs_)
49✔
193
        tx->to_data(sink, witness);
27✔
194
}
22✔
195

196
// Properties.
197
// ----------------------------------------------------------------------------
198

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

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

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

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

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

229
    std::for_each(txs_->begin(), txs_->end(), append_ins);
×
230
    return inputs;
×
231
}
232

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

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

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

250
    const auto hash = [witness](const auto& tx) NOEXCEPT
19✔
251
    {
252
        return tx->hash(witness);
19✔
253
    };
14✔
254

255
    std::transform(txs_->begin(), txs_->end(), out.begin(), hash);
14✔
256
    return out;
14✔
257
}
258

259
// computed
260
hash_digest block::hash() const NOEXCEPT
38✔
261
{
262
    return header_->hash();
38✔
263
}
264

265
// computed
266
const hash_digest& block::get_hash() const NOEXCEPT
×
267
{
268
    return header_->get_hash();
×
269
}
270

271
// static/private
272
block::sizes block::serialized_size(
188✔
273
    const chain::transaction_cptrs& txs) NOEXCEPT
274
{
275
    sizes size{};
188✔
276
    std::for_each(txs.begin(), txs.end(), [&](const auto& tx) NOEXCEPT
449✔
277
    {
278
        size.nominal = ceilinged_add(size.nominal, tx->serialized_size(false));
522✔
279
        size.witnessed = ceilinged_add(size.witnessed, tx->serialized_size(true));
261✔
280
    });
261✔
281

282
    const auto common_size = ceilinged_add(
188✔
283
        header::serialized_size(),
284
        variable_size(txs.size()));
285

286
    const auto nominal_size = ceilinged_add(
188✔
287
        common_size,
288
        size.nominal);
289

290
    const auto witnessed_size = ceilinged_add(
188✔
291
        common_size,
292
        size.witnessed);
293

294
    return { nominal_size, witnessed_size };
188✔
295
}
296

297
size_t block::serialized_size(bool witness) const NOEXCEPT
24✔
298
{
299
    return witness ? size_.witnessed : size_.nominal;
21✔
300
}
301

302
// Connect.
303
// ----------------------------------------------------------------------------
304

305
bool block::is_empty() const NOEXCEPT
2✔
306
{
307
    return txs_->empty();
2✔
308
}
309

310
bool block::is_oversized() const NOEXCEPT
3✔
311
{
312
    return serialized_size(false) > max_block_size;
3✔
313
}
314

315
bool block::is_first_non_coinbase() const NOEXCEPT
3✔
316
{
317
    return !txs_->empty() && !txs_->front()->is_coinbase();
3✔
318
}
319

320
// True if there is another coinbase other than the first tx.
321
// No txs or coinbases returns false.
322
bool block::is_extra_coinbases() const NOEXCEPT
3✔
323
{
324
    if (txs_->empty())
3✔
325
        return false;
326

327
    const auto value = [](const auto& tx) NOEXCEPT
2✔
328
    {
329
        return tx->is_coinbase();
2✔
330
    };
331

332
    return std::any_of(std::next(txs_->begin()), txs_->end(), value);
3✔
333
}
334

335
//*****************************************************************************
336
// CONSENSUS: This is only necessary because satoshi stores and queries as it
337
// validates, imposing an otherwise unnecessary partial transaction ordering.
338
//*****************************************************************************
339
bool block::is_forward_reference() const NOEXCEPT
8✔
340
{
341
    if (txs_->empty())
8✔
342
        return false;
343

344
    const auto sum_txs = sub1(txs_->size());
7✔
345
    unordered_set_of_constant_referenced_hashes hashes{ sum_txs };
7✔
346
    const auto spent = [&hashes](const input::cptr& input) NOEXCEPT
11✔
347
    {
348
        return hashes.find(std::ref(input->point().hash())) != hashes.end();
4✔
349
    };
7✔
350

351
    const auto spend = [&spent, &hashes](const auto& tx) NOEXCEPT
7✔
352
    {
353
        const auto& ins = *tx->inputs_ptr();
7✔
354
        const auto forward = std::any_of(ins.begin(), ins.end(), spent);
7✔
355
        hashes.emplace(tx->get_hash(false));
7✔
356
        return forward;
7✔
357
    };
7✔
358

359
    return std::any_of(txs_->rbegin(), std::prev(txs_->rend()), spend);
7✔
360
}
361

362
// This also precludes the block merkle calculation DoS exploit by preventing
363
// duplicate txs, as a duplicate non-empty tx implies a duplicate point.
364
// bitcointalk.org/?topic=102395
365
bool block::is_internal_double_spend() const NOEXCEPT
6✔
366
{
367
    if (txs_->empty())
6✔
368
        return false;
369

370
    // Overflow returns max_size_t.
371
    const auto sum_ins = [](size_t total, const auto& tx) NOEXCEPT
11✔
372
    {
373
        return ceilinged_add(total, tx->inputs());
11✔
374
    };
375

376
    const auto tx1 = std::next(txs_->begin());
5✔
377
    const auto spends_count = std::accumulate(tx1, txs_->end(), zero, sum_ins);
5✔
378
    unordered_set_of_constant_referenced_points points{ spends_count };
5✔
379
    const auto spent = [&points](const input::cptr& in) NOEXCEPT
14✔
380
    {
381
        return !points.emplace(in->point()).second;
9✔
382
    };
5✔
383

384
    const auto double_spent = [&spent](const auto& tx) NOEXCEPT
9✔
385
    {
386
        const auto& ins = *tx->inputs_ptr();
9✔
387
        return std::any_of(ins.begin(), ins.end(), spent);
9✔
388
    };
5✔
389

390
    return std::any_of(tx1, txs_->end(), double_spent);
5✔
391
}
392

393
// private
394
hash_digest block::generate_merkle_root(bool witness) const NOEXCEPT
14✔
395
{
396
    return sha256::merkle_root(transaction_hashes(witness));
14✔
397
}
398

399
bool block::is_invalid_merkle_root() const NOEXCEPT
14✔
400
{
401
    return generate_merkle_root(false) != header_->merkle_root();
14✔
402
}
403

404
// Accept (contextual).
405
// ----------------------------------------------------------------------------
406

407
size_t block::weight() const NOEXCEPT
×
408
{
409
    // Block weight is 3 * nominal size * + 1 * witness size (bip141).
410
    return ceilinged_add(
×
411
        ceilinged_multiply(base_size_contribution, serialized_size(false)),
412
        ceilinged_multiply(total_size_contribution, serialized_size(true)));
×
413
}
414

415
bool block::is_overweight() const NOEXCEPT
×
416
{
417
    return weight() > max_block_weight;
×
418
}
419

420
bool block::is_invalid_coinbase_script(size_t height) const NOEXCEPT
×
421
{
422
    if (txs_->empty() || txs_->front()->inputs_ptr()->empty())
×
423
        return false;
×
424

425
    const auto& script = txs_->front()->inputs_ptr()->front()->script();
×
426
    return !script::is_coinbase_pattern(script.ops(), height);
×
427
}
428

429
// TODO: add bip50 to chain_state with timestamp range activation.
430
// "Special short-term limits to avoid 10,000 BDB lock limit.
431
// Count of unique txids <= 4500 to prevent 10000 BDB lock exhaustion.
432
// header.timestamp > 1363039171 && header.timestamp < 1368576000."
433
bool block::is_hash_limit_exceeded() const NOEXCEPT
×
434
{
435
    if (txs_->empty())
×
436
        return false;
437

438
    // A set is used to collapse duplicates.
439
    unordered_set_of_constant_referenced_hashes hashes{};
×
440

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

444
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
445
    {
446
        // Insert the transaction hash.
447
        hashes.emplace((*tx)->get_hash(false));
×
448
        const auto& inputs = *(*tx)->inputs_ptr();
×
449

450
        // Insert all input point hashes.
451
        for (const auto& input: inputs)
×
452
            hashes.emplace(input->point().hash());
×
453
    }
454

455
    return hashes.size() > hash_limit;
×
456
}
457

458
// Malleability does not imply malleated.
459
bool block::is_malleable() const NOEXCEPT
3✔
460
{
461
    return is_malleable64() || is_malleable32();
3✔
462
}
463

464
bool block::is_malleated() const NOEXCEPT
×
465
{
466
    return is_malleated64() || is_malleated32();
×
467
}
468

469
// Malleability does not imply malleated.
470
bool block::is_malleable32() const NOEXCEPT
12✔
471
{
472
    const auto unmalleated = txs_->size();
12✔
473
    for (auto mally = one; mally <= unmalleated; mally *= two)
23✔
474
        if (is_malleable32(unmalleated, mally))
17✔
475
            return true;
476

477
    return false;
478
}
479

480
// Malleated32 implies malleable and invalid due to internal tx hash pairing.
481
bool block::is_malleated32() const NOEXCEPT
11✔
482
{
483
    return !is_zero(malleated32_size());
11✔
484
}
485

486
// protected
487
// The size of an actual malleation of this block, or zero.
488
size_t block::malleated32_size() const NOEXCEPT
11✔
489
{
490
    const auto malleated = txs_->size();
11✔
491
    for (auto mally = one; mally <= to_half(malleated); mally *= two)
23✔
492
        if (is_malleable32(malleated - mally, mally) && is_malleated32(mally))
14✔
493
            return mally;
2✔
494

495
    return zero;
496
}
497

498
// protected
499
// True if the last width set of tx hashes repeats.
500
bool block::is_malleated32(size_t width) const NOEXCEPT
7✔
501
{
502
    const auto malleated = txs_->size();
7✔
503
    if (is_zero(width) || width > to_half(malleated))
7✔
504
        return false;
505

506
    auto mally = txs_->rbegin();
6✔
507
    auto legit = std::next(mally, width);
6✔
508
    while (!is_zero(width--))
9✔
509
        if ((*mally++)->hash(false) != (*legit++)->hash(false))
7✔
510
            return false;
511

512
    return true;
513
}
514

515
// Malleability does not imply malleated.
516
bool block::is_malleable64() const NOEXCEPT
12✔
517
{
518
    return is_malleable64(*txs_);
12✔
519
}
520

521
// static
522
// If all non-witness tx serializations are 64 bytes the id is malleable.
523
bool block::is_malleable64(const transaction_cptrs& txs) NOEXCEPT
12✔
524
{
525
    const auto two_leaves = [](const auto& tx) NOEXCEPT
15✔
526
    {
527
        return tx->serialized_size(false) == two * hash_size;
15✔
528
    };
529

530
    return !txs.empty() && std::all_of(txs.begin(), txs.end(), two_leaves);
12✔
531
}
532

533
// Malleated64 implies malleable64 and invalid due to non-null coinbase point.
534
// It is considered computationally infeasible to produce malleable64 with a
535
// valid (null) coinbase input point.
536
bool block::is_malleated64() const NOEXCEPT
×
537
{
538
    return !txs_->empty() && !txs_->front()->is_coinbase() &&
×
539
        is_malleable64(*txs_);
×
540
}
541

542
bool block::is_segregated() const NOEXCEPT
2✔
543
{
544
    const auto segregated = [](const auto& tx) NOEXCEPT
4✔
545
    {
546
        return tx->is_segregated();
4✔
547
    };
548

549
    return std::any_of(txs_->begin(), txs_->end(), segregated);
2✔
550
}
551

552
// The witness merkle root is obtained from wtxids, subject to malleation just
553
// as the txs commitment. However, since tx duplicates are precluded by the
554
// malleable32 (or complete) block check, there is no opportunity for this.
555
// Similarly the witness commitment cannot be malleable64.
556
bool block::is_invalid_witness_commitment() const NOEXCEPT
×
557
{
558
    if (txs_->empty())
×
559
        return false;
560

561
    const auto& coinbase = *txs_->front();
×
562
    if (coinbase.inputs_ptr()->empty())
×
563
        return false;
564

565
    // If there is a valid commitment, return false (valid).
566
    // Coinbase input witness must be 32 byte witness reserved value (bip141).
567
    // Last output of commitment pattern holds the committed value (bip141).
568
    hash_digest reserved{}, committed{};
×
569
    if (coinbase.inputs_ptr()->front()->reserved_hash(reserved))
×
570
        for (const auto& output: views_reverse(*coinbase.outputs_ptr()))
×
571
            if (output->committed_hash(committed))
×
572
                if (committed == sha256::double_hash(
×
573
                    generate_merkle_root(true), reserved))
×
574
                    return false;
575
    
576
    // If no valid commitment, return true (invalid) if segregated.
577
    // If no block tx has witness data the commitment is optional (bip141).
578
    return is_segregated();
×
579
}
580

581
//*****************************************************************************
582
// CONSENSUS:
583
// bip42 compensates for C++ undefined behavior of a right shift of a number of
584
// bits greater or equal to the shifted integer width. Yet being undefined, the
585
// result of this operation may vary by compiler. The shift_right call below
586
// explicitly implements presumed pre-bip42 behavior (shift overflow modulo) by
587
// default, and specified bip42 behavior (shift overflow to zero) with bip42.
588
//*****************************************************************************
589
static uint64_t block_subsidy(size_t height, uint64_t subsidy_interval,
×
590
    uint64_t initial_block_subsidy_satoshi, bool bip42) NOEXCEPT
591
{
592
    // Guard: quotient domain cannot increase with positive integer divisor.
593
    const auto halves = possible_narrow_cast<size_t>(height / subsidy_interval);
×
594
    return shift_right(initial_block_subsidy_satoshi, halves, bip42);
×
595
}
596

597
// Prevouts required.
598

599
uint64_t block::fees() const NOEXCEPT
×
600
{
601
    // Overflow returns max_uint64.
602
    const auto value = [](uint64_t total, const auto& tx) NOEXCEPT
×
603
    {
604
        return ceilinged_add(total, tx->fee());
×
605
    };
606

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

610
uint64_t block::claim() const NOEXCEPT
×
611
{
612
    return txs_->empty() ? zero : txs_->front()->value();
×
613
}
614

615
uint64_t block::reward(size_t height, uint64_t subsidy_interval,
×
616
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
617
{
618
    // Overflow returns max_uint64.
619
    return ceilinged_add(fees(), block_subsidy(height, subsidy_interval,
×
620
        initial_block_subsidy_satoshi, bip42));
×
621
}
622

623
bool block::is_overspent(size_t height, uint64_t subsidy_interval,
×
624
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
625
{
626
    return claim() > reward(height, subsidy_interval,
×
627
        initial_block_subsidy_satoshi, bip42);
×
628
}
629

630
size_t block::signature_operations(bool bip16, bool bip141) const NOEXCEPT
×
631
{
632
    // Overflow returns max_size_t.
633
    const auto value = [=](size_t total, const auto& tx) NOEXCEPT
×
634
    {
635
        return ceilinged_add(total, tx->signature_operations(bip16, bip141));
×
636
    };
×
637

638
    return std::accumulate(txs_->begin(), txs_->end(), zero, value);
×
639
}
640

641
bool block::is_signature_operations_limited(bool bip16,
×
642
    bool bip141) const NOEXCEPT
643
{
644
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
645
    return signature_operations(bip16, bip141) > limit;
×
646
}
647

648
//*****************************************************************************
649
// CONSENSUS:
650
// This check is excluded under two bip30 exception blocks and bip30_deactivate
651
// until bip30_reactivate. These conditions are rolled up into the bip30 flag.
652
//*****************************************************************************
653
bool block::is_unspent_coinbase_collision() const NOEXCEPT
×
654
{
655
    if (txs_->empty() || txs_->front()->inputs_ptr()->empty())
×
656
        return false;
×
657

658
    // May only commit duplicate coinbase that is already confirmed spent.
659
    // Metadata population defaults coinbase to spent (not a collision).
660
    return !txs_->front()->inputs_ptr()->front()->metadata.spent;
×
661
}
662

663
// Search is not ordered, forward references are caught by block.check.
664
void block::populate() const NOEXCEPT
×
665
{
666
    std::unordered_map<point, output::cptr> points{};
×
667
    uint32_t index{};
×
668

669
    // Populate outputs hash table.
670
    for (auto tx = txs_->begin(); tx != txs_->end(); ++tx, index = 0)
×
671
        for (const auto& out: *(*tx)->outputs_ptr())
×
672
            points.emplace(std::pair{ point{ (*tx)->hash(false), index++ },
×
673
                out });
674

675
    // Populate input prevouts from hash table.
676
    for (auto tx = txs_->begin(); tx != txs_->end(); ++tx)
×
677
    {
678
        for (const auto& in: *(*tx)->inputs_ptr())
×
679
        {
680
            const auto point = points.find(in->point());
×
681
            if (point != points.end())
×
682
                in->prevout = point->second;
×
683
        }
684
    }
685
}
×
686

687
// Delegated.
688
// ----------------------------------------------------------------------------
689

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

697
    return error::block_success;
3✔
698
}
699

700
// DO invoke on coinbase.
701
code block::check_transactions(const context& ctx) const NOEXCEPT
×
702
{
703
    for (const auto& tx: *txs_)
×
704
        if (const auto ec = tx->check(ctx))
×
705
            return ec;
×
706

707
    return error::block_success;
×
708
}
709

710
// Do NOT invoke on coinbase.
711
code block::accept_transactions(const context& ctx) const NOEXCEPT
×
712
{
713
    if (!is_empty())
×
714
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
715
            if (const auto ec = (*tx)->accept(ctx))
×
716
                return ec;
×
717

718
    return error::block_success;
×
719
}
720

721
// Do NOT invoke on coinbase.
722
code block::connect_transactions(const context& ctx) const NOEXCEPT
×
723
{
724
    if (!is_empty())
×
725
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
726
            if (const auto ec = (*tx)->connect(ctx))
×
727
                return ec;
×
728

729
    return error::block_success;
×
730
}
731

732
// Do NOT invoke on coinbase.
733
code block::confirm_transactions(const context& ctx) const NOEXCEPT
×
734
{
735
    if (!is_empty())
×
736
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
737
            if (const auto ec = (*tx)->confirm(ctx))
×
738
                return ec;
×
739

740
    return error::block_success;
×
741
}
742

743
// Identity.
744
// ----------------------------------------------------------------------------
745
// invalid_transaction_commitment, invalid_witness_commitment, block_malleated
746
// codes specifically indicate lack of block hash tx identification (identity).
747

748
code block::identify() const NOEXCEPT
×
749
{
750
    // type64 malleated is a subset of first_not_coinbase.
751
    // type32 malleated is a subset of is_internal_double_spend.
752
    if (is_malleated())
×
753
        return error::block_malleated;
×
754
    if (is_invalid_merkle_root())
×
755
        return error::invalid_transaction_commitment;
×
756

757
    return error::block_success;
×
758
}
759

760
code block::identify(const context& ctx) const NOEXCEPT
×
761
{
762
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
763

764
    if (bip141 && is_invalid_witness_commitment())
×
765
        return error::invalid_witness_commitment;
×
766

767
    return error::block_success;
×
768
}
769

770
// Validation.
771
// ----------------------------------------------------------------------------
772
// In the case of validation failure
773
// The block header is checked/accepted independently.
774

775
// TODO: use of get_hash() in is_forward_reference makes this thread unsafe.
776
code block::check() const NOEXCEPT
3✔
777
{
778
    // empty_block is subset of first_not_coinbase.
779
    //if (is_empty())
780
    //    return error::empty_block;
781
    if (is_oversized())
3✔
782
        return error::block_size_limit;
×
783
    if (is_first_non_coinbase())
3✔
784
        return error::first_not_coinbase;
×
785
    if (is_extra_coinbases())
3✔
786
        return error::extra_coinbases;
×
787
    if (is_forward_reference())
3✔
788
        return error::forward_reference;
×
789
    if (is_internal_double_spend())
3✔
790
        return error::block_internal_double_spend;
×
791
    if (is_invalid_merkle_root())
3✔
792
        return error::invalid_transaction_commitment;
×
793

794
    return check_transactions();
3✔
795
}
796

797
// forks
798
// height
799
// timestamp
800
// median_time_past
801

802
// TODO: use of get_hash() in is_hash_limit_exceeded makes this thread unsafe.
803
code block::check(const context& ctx) const NOEXCEPT
×
804
{
805
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
806
    const auto bip34 = ctx.is_enabled(bip34_rule);
×
807
    const auto bip50 = ctx.is_enabled(bip50_rule);
×
808

809
    if (bip141 && is_overweight())
×
810
        return error::block_weight_limit;
×
811
    if (bip34 && is_invalid_coinbase_script(ctx.height))
×
812
        return error::coinbase_height_mismatch;
×
813
    if (bip50 && is_hash_limit_exceeded())
×
814
        return error::temporary_hash_limit;
×
815
    if (bip141 && is_invalid_witness_commitment())
×
816
        return error::invalid_witness_commitment;
×
817

818
    return check_transactions(ctx);
×
819
}
820

821
// forks
822
// height
823

824
// This assumes that prevout caching is completed on all inputs.
825
code block::accept(const context& ctx, size_t subsidy_interval,
×
826
    uint64_t initial_subsidy) const NOEXCEPT
827
{
828
    const auto bip16 = ctx.is_enabled(bip16_rule);
×
829
    const auto bip42 = ctx.is_enabled(bip42_rule);
×
830
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
831

832
    // prevouts required.
833
    if (is_overspent(ctx.height, subsidy_interval, initial_subsidy, bip42))
×
834
        return error::coinbase_value_limit;
×
835
    if (is_signature_operations_limited(bip16, bip141))
×
836
        return error::block_sigop_limit;
×
837

838
    return accept_transactions(ctx);
×
839
}
840

841
// forks
842

843
// Node performs these checks through database query.
844
// This assumes that prevout and metadata caching are completed on all inputs.
845
code block::confirm(const context& ctx) const NOEXCEPT
×
846
{
847
    const auto bip30 = ctx.is_enabled(bip30_rule);
×
848

849
    if (bip30 && is_unspent_coinbase_collision())
×
850
        return error::unspent_coinbase_collision;
×
851

852
    return confirm_transactions(ctx);
×
853
}
854

855
// forks
856

857
code block::connect(const context& ctx) const NOEXCEPT
×
858
{
859
    return connect_transactions(ctx);
×
860
}
861

862
BC_POP_WARNING()
863
BC_POP_WARNING()
864

865
// JSON value convertors.
866
// ----------------------------------------------------------------------------
867

868
namespace json = boost::json;
869

870
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
871
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
872

873
block tag_invoke(json::value_to_tag<block>,
1✔
874
    const json::value& value) NOEXCEPT
875
{
876
    return
1✔
877
    {
878
        json::value_to<header>(value.at("header")),
1✔
879
        json::value_to<chain::transactions>(value.at("transactions"))
2✔
880
    };
1✔
881
}
882

883
void tag_invoke(json::value_from_tag, json::value& value,
2✔
884
    const block& block) NOEXCEPT
885
{
886
    value =
2✔
887
    {
888
        { "header", block.header() },
889
        { "transactions", *block.transactions_ptr() },
890
    };
2✔
891
}
2✔
892

893
BC_POP_WARNING()
894

895
block::cptr tag_invoke(json::value_to_tag<block::cptr>,
×
896
    const json::value& value) NOEXCEPT
897
{
898
    return to_shared(tag_invoke(json::value_to_tag<block>{}, value));
×
899
}
900

901
// Shared pointer overload is required for navigation.
902
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
903
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
904

905
void tag_invoke(json::value_from_tag tag, json::value& value,
×
906
    const block::cptr& block) NOEXCEPT
907
{
908
    tag_invoke(tag, value, *block);
×
909
}
×
910

911
BC_POP_WARNING()
912
BC_POP_WARNING()
913

914
} // namespace chain
915
} // namespace system
916
} // 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