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

libbitcoin / libbitcoin-system / 12918657337

22 Jan 2025 11:01PM UTC coverage: 82.883% (-0.02%) from 82.903%
12918657337

push

github

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

Treat internal cb spend (immature) as locked in block.prevout().

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

1 existing line in 1 file now uncovered.

10052 of 12128 relevant lines covered (82.88%)

4722683.61 hits per line

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

45.85
/src/chain/block.cpp
1
/**
2
 * Copyright (c) 2011-2025 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 <utility>
28
#include <bitcoin/system/chain/context.hpp>
29
#include <bitcoin/system/chain/enums/flags.hpp>
30
#include <bitcoin/system/chain/enums/magic_numbers.hpp>
31
#include <bitcoin/system/chain/enums/opcode.hpp>
32
#include <bitcoin/system/chain/point.hpp>
33
#include <bitcoin/system/chain/script.hpp>
34
#include <bitcoin/system/data/data.hpp>
35
#include <bitcoin/system/define.hpp>
36
#include <bitcoin/system/error/error.hpp>
37
#include <bitcoin/system/hash/hash.hpp>
38
#include <bitcoin/system/math/math.hpp>
39
#include <bitcoin/system/stream/stream.hpp>
40

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

45
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
46
BC_PUSH_WARNING(NO_UNGUARDED_POINTERS)
47

48
// Constructors.
49
// ----------------------------------------------------------------------------
50

51
block::block() NOEXCEPT
64✔
52
  : block(to_shared<chain::header>(), to_shared<transaction_cptrs>(),
64✔
53
      false)
192✔
54
{
55
}
64✔
56

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

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

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

75
block::block(const data_slice& data, bool witness) NOEXCEPT
74✔
76
  : block(stream::in::copy(data), witness)
74✔
77
{
78
}
74✔
79

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

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

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

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

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

105
block::block(reader& source, bool witness) NOEXCEPT
83✔
106
  : header_(CREATE(chain::header, source.get_allocator(), source)),
83✔
107
    txs_(CREATE(transaction_cptrs, source.get_allocator()))
166✔
108
{
109
    assign_data(source, witness);
83✔
110
}
83✔
111

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

122
// Operators.
123
// ----------------------------------------------------------------------------
124

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

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

136
// Deserialization.
137
// ----------------------------------------------------------------------------
138

139
// private
140
void block::assign_data(reader& source, bool witness) NOEXCEPT
83✔
141
{
142
    auto& allocator = source.get_allocator();
83✔
143
    const auto count = source.read_size(max_block_size);
83✔
144
    auto txs = to_non_const_raw_ptr(txs_);
83✔
145
    txs->reserve(count);
83✔
146

147
    for (size_t tx = 0; tx < count; ++tx)
214✔
148
        txs->emplace_back(CREATE(transaction, allocator, source, witness));
131✔
149

150
    size_ = serialized_size(*txs_);
83✔
151
    valid_ = source;
83✔
152
}
83✔
153

154
void block::set_allocation(size_t allocation) const NOEXCEPT
×
155
{
156
    allocation_ = allocation;
×
157
}
×
158

159
size_t block::get_allocation() const NOEXCEPT
×
160
{
161
    return allocation_;
×
162
}
163

164
// Serialization.
165
// ----------------------------------------------------------------------------
166

167
data_chunk block::to_data(bool witness) const NOEXCEPT
20✔
168
{
169
    data_chunk data(serialized_size(witness));
40✔
170
    stream::out::copy ostream(data);
20✔
171
    to_data(ostream, witness);
20✔
172
    return data;
40✔
173
}
20✔
174

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

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

186
    for (const auto& tx: *txs_)
49✔
187
        tx->to_data(sink, witness);
27✔
188
}
22✔
189

190
// Properties.
191
// ----------------------------------------------------------------------------
192

193
bool block::is_valid() const NOEXCEPT
35✔
194
{
195
    return valid_;
35✔
196
}
197

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

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

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

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

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

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

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

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

244
    const auto hash = [witness](const auto& tx) NOEXCEPT
19✔
245
    {
246
        return tx->hash(witness);
19✔
247
    };
14✔
248

249
    std::transform(txs_->begin(), txs_->end(), out.begin(), hash);
14✔
250
    return out;
14✔
251
}
252

253
// computed
254
size_t block::outputs() const NOEXCEPT
×
255
{
256
    if (txs_->empty())
×
257
        return zero;
258

259
    // Overflow returns max_size_t.
260
    const auto outs = [](size_t total, const auto& tx) NOEXCEPT
×
261
    {
262
         return ceilinged_add(total, tx->outputs());
×
263
    };
264

265
    return std::accumulate(std::next(txs_->begin()), txs_->end(), zero, outs);
×
266
}
267

268
// computed
269
size_t block::spends() const NOEXCEPT
7✔
270
{
271
    if (txs_->empty())
7✔
272
        return zero;
273

274
    // Overflow returns max_size_t.
275
    const auto ins = [](size_t total, const auto& tx) NOEXCEPT
11✔
276
    {
277
         return ceilinged_add(total, tx->inputs());
11✔
278
    };
279

280
    // inputs() is add1(spends()) if the block is valid (one coinbase input).
281
    return std::accumulate(std::next(txs_->begin()), txs_->end(), zero, ins);
7✔
282
}
283

284
// computed
285
hash_digest block::hash() const NOEXCEPT
38✔
286
{
287
    return header_->hash();
38✔
288
}
289

290
// computed
291
const hash_digest& block::get_hash() const NOEXCEPT
×
292
{
293
    return header_->get_hash();
×
294
}
295

296
void block::set_hashes(const data_chunk& data) NOEXCEPT
×
297
{
298
    constexpr auto header_size = chain::header::serialized_size();
×
299

300
    // Cache header hash.
301
    header_->set_hash(bitcoin_hash(header_size, data.data()));
×
302

303
    // Skip transaction count, guarded by preceding successful block construct.
304
    auto start = std::next(data.data(), header_size);
×
305
    std::advance(start, size_variable(*start));
×
306

307
    // Cache transaction hashes.
308
    auto coinbase = true;
×
309
    for (const auto& tx: *txs_)
×
310
    {
311
        const auto witness_size = tx->serialized_size(true);
×
312

313
        // If !witness then wire txs cannot have been segregated.
314
        if (tx->is_segregated())
×
315
        {
316
            const auto nominal_size = tx->serialized_size(false);
×
317

318
            tx->set_nominal_hash(transaction::desegregated_hash(
×
319
                witness_size, nominal_size, start));
320

321
            if (!coinbase)
×
322
                tx->set_witness_hash(bitcoin_hash(witness_size, start));
×
323
        }
324
        else
325
        {
326
            tx->set_nominal_hash(bitcoin_hash(witness_size, start));
×
327
        }
328

329
        coinbase = false;
×
330
        std::advance(start, witness_size);
×
331
    }
332
}
×
333

334
// static/private
335
block::sizes block::serialized_size(
190✔
336
    const chain::transaction_cptrs& txs) NOEXCEPT
337
{
338
    sizes size{};
190✔
339
    std::for_each(txs.begin(), txs.end(), [&](const auto& tx) NOEXCEPT
452✔
340
    {
341
        size.nominal = ceilinged_add(size.nominal, tx->serialized_size(false));
524✔
342
        size.witnessed = ceilinged_add(size.witnessed, tx->serialized_size(true));
262✔
343
    });
262✔
344

345
    const auto common_size = ceilinged_add(header::serialized_size(),
190✔
346
        variable_size(txs.size()));
347

348
    const auto nominal_size = ceilinged_add(common_size, size.nominal);
190✔
349
    const auto witnessed_size = ceilinged_add(common_size, size.witnessed);
190✔
350

351
    return { nominal_size, witnessed_size };
190✔
352
}
353

354
size_t block::serialized_size(bool witness) const NOEXCEPT
24✔
355
{
356
    return witness ? size_.witnessed : size_.nominal;
21✔
357
}
358

359
// Connect.
360
// ----------------------------------------------------------------------------
361

362
bool block::is_empty() const NOEXCEPT
2✔
363
{
364
    return txs_->empty();
2✔
365
}
366

367
bool block::is_oversized() const NOEXCEPT
3✔
368
{
369
    return serialized_size(false) > max_block_size;
3✔
370
}
371

372
bool block::is_first_non_coinbase() const NOEXCEPT
3✔
373
{
374
    return !txs_->empty() && !txs_->front()->is_coinbase();
3✔
375
}
376

377
// True if there is another coinbase other than the first tx.
378
// No txs or coinbases returns false.
379
bool block::is_extra_coinbases() const NOEXCEPT
3✔
380
{
381
    if (txs_->empty())
3✔
382
        return false;
383

384
    const auto value = [](const auto& tx) NOEXCEPT
2✔
385
    {
386
        return tx->is_coinbase();
2✔
387
    };
388

389
    return std::any_of(std::next(txs_->begin()), txs_->end(), value);
3✔
390
}
391

392
//*****************************************************************************
393
// CONSENSUS: This is only necessary because satoshi stores and queries as it
394
// validates, imposing an otherwise unnecessary partial transaction ordering.
395
//*****************************************************************************
396
bool block::is_forward_reference() const NOEXCEPT
8✔
397
{
398
    if (txs_->empty())
8✔
399
        return false;
400

401
    unordered_set_of_hash_cref hashes{ sub1(txs_->size()) };
7✔
402
    for (auto tx = txs_->rbegin(); tx != std::prev(txs_->rend()); ++tx)
13✔
403
    {
404
        for (const auto& in: *(*tx)->inputs_ptr())
10✔
405
            if (hashes.contains(in->point().hash()))
4✔
406
                return true;
407

408
        hashes.emplace((*tx)->get_hash(false));
6✔
409
    }
410

411
    return false;
412
}
413

414
// This also precludes the block merkle calculation DoS exploit by preventing
415
// duplicate txs, as a duplicate non-empty tx implies a duplicate point.
416
// bitcointalk.org/?topic=102395
417
bool block::is_internal_double_spend() const NOEXCEPT
6✔
418
{
419
    if (txs_->empty())
6✔
420
        return false;
421

422
    unordered_set_of_point_cref points{ spends() };
5✔
423
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
13✔
424
        for (const auto& in: *(*tx)->inputs_ptr())
17✔
425
            if (!points.emplace(in->point()).second)
18✔
426
                return true;
427

428
    return false;
429
}
430

431
// private
432
hash_digest block::generate_merkle_root(bool witness) const NOEXCEPT
14✔
433
{
434
    return sha256::merkle_root(transaction_hashes(witness));
14✔
435
}
436

437
bool block::is_invalid_merkle_root() const NOEXCEPT
14✔
438
{
439
    return generate_merkle_root(false) != header_->merkle_root();
14✔
440
}
441

442
// Accept (contextual).
443
// ----------------------------------------------------------------------------
444

445
size_t block::weight() const NOEXCEPT
×
446
{
447
    // Block weight is 3 * nominal size * + 1 * witness size (bip141).
448
    return ceilinged_add(
×
449
        ceilinged_multiply(base_size_contribution, serialized_size(false)),
450
        ceilinged_multiply(total_size_contribution, serialized_size(true)));
×
451
}
452

453
bool block::is_overweight() const NOEXCEPT
×
454
{
455
    return weight() > max_block_weight;
×
456
}
457

458
bool block::is_invalid_coinbase_script(size_t height) const NOEXCEPT
×
459
{
460
    if (txs_->empty() || txs_->front()->inputs_ptr()->empty())
×
461
        return false;
×
462

463
    const auto& script = txs_->front()->inputs_ptr()->front()->script();
×
464
    return !script::is_coinbase_pattern(script.ops(), height);
×
465
}
466

467
// TODO: add bip50 to chain_state with timestamp range activation.
468
// "Special short-term limits to avoid 10,000 BDB lock limit.
469
// Count of unique txids <= 4500 to prevent 10000 BDB lock exhaustion.
470
// header.timestamp > 1363039171 && header.timestamp < 1368576000."
471
bool block::is_hash_limit_exceeded() const NOEXCEPT
×
472
{
473
    if (txs_->empty())
×
474
        return false;
475

476
    // A set is used to collapse duplicates.
477
    unordered_set_of_hash_cref hashes{ txs_->size() };
×
478

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

482
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
483
    {
484
        // Insert the transaction hash.
485
        hashes.emplace((*tx)->get_hash(false));
×
486
        const auto& inputs = (*tx)->inputs_ptr();
×
487

488
        // Insert all input point hashes.
489
        for (const auto& input: *inputs)
×
490
            hashes.emplace(input->point().hash());
×
491
    }
492

493
    return hashes.size() > hash_limit;
×
494
}
495

496
// Malleability does not imply malleated.
497
bool block::is_malleable() const NOEXCEPT
3✔
498
{
499
    return is_malleable64() || is_malleable32();
3✔
500
}
501

502
bool block::is_malleated() const NOEXCEPT
×
503
{
504
    return is_malleated64() || is_malleated32();
×
505
}
506

507
// Malleability does not imply malleated.
508
bool block::is_malleable32() const NOEXCEPT
12✔
509
{
510
    const auto unmalleated = txs_->size();
12✔
511
    for (auto mally = one; mally <= unmalleated; mally *= two)
23✔
512
        if (is_malleable32(unmalleated, mally))
17✔
513
            return true;
514

515
    return false;
516
}
517

518
// Malleated32 implies malleable and invalid due to internal tx hash pairing.
519
bool block::is_malleated32() const NOEXCEPT
11✔
520
{
521
    return !is_zero(malleated32_size());
11✔
522
}
523

524
// protected
525
// The size of an actual malleation of this block, or zero.
526
size_t block::malleated32_size() const NOEXCEPT
11✔
527
{
528
    const auto malleated = txs_->size();
11✔
529
    for (auto mally = one; mally <= to_half(malleated); mally *= two)
23✔
530
        if (is_malleable32(malleated - mally, mally) && is_malleated32(mally))
14✔
531
            return mally;
2✔
532

533
    return zero;
534
}
535

536
// protected
537
// True if the last width set of tx hashes repeats.
538
bool block::is_malleated32(size_t width) const NOEXCEPT
7✔
539
{
540
    const auto malleated = txs_->size();
7✔
541
    if (is_zero(width) || width > to_half(malleated))
7✔
542
        return false;
543

544
    auto mally = txs_->rbegin();
6✔
545
    auto legit = std::next(mally, width);
6✔
546
    while (!is_zero(width--))
9✔
547
        if ((*mally++)->get_hash(false) != (*legit++)->get_hash(false))
7✔
548
            return false;
549

550
    return true;
551
}
552

553
// Malleability does not imply malleated.
554
bool block::is_malleable64() const NOEXCEPT
12✔
555
{
556
    return is_malleable64(*txs_);
12✔
557
}
558

559
// static
560
// If all non-witness tx serializations are 64 bytes the id is malleable.
561
bool block::is_malleable64(const transaction_cptrs& txs) NOEXCEPT
12✔
562
{
563
    const auto two_leaves = [](const auto& tx) NOEXCEPT
15✔
564
    {
565
        return tx->serialized_size(false) == two * hash_size;
15✔
566
    };
567

568
    return !txs.empty() && std::all_of(txs.begin(), txs.end(), two_leaves);
12✔
569
}
570

571
// Malleated64 implies malleable64 and invalid due to non-null coinbase point.
572
// It is considered computationally infeasible to produce malleable64 with a
573
// valid (null) coinbase input point.
574
bool block::is_malleated64() const NOEXCEPT
×
575
{
576
    return !txs_->empty() && !txs_->front()->is_coinbase() &&
×
577
        is_malleable64(*txs_);
×
578
}
579

580
bool block::is_segregated() const NOEXCEPT
2✔
581
{
582
    const auto segregated = [](const auto& tx) NOEXCEPT
4✔
583
    {
584
        return tx->is_segregated();
4✔
585
    };
586

587
    return std::any_of(txs_->begin(), txs_->end(), segregated);
2✔
588
}
589

590
// The witness merkle root is obtained from wtxids, subject to malleation just
591
// as the txs commitment. However, since tx duplicates are precluded by the
592
// malleable32 (or complete) block check, there is no opportunity for this.
593
// Similarly the witness commitment cannot be malleable64.
594
bool block::is_invalid_witness_commitment() const NOEXCEPT
×
595
{
596
    if (txs_->empty())
×
597
        return false;
598

599
    const auto& coinbase = txs_->front();
×
600
    if (coinbase->inputs_ptr()->empty())
×
601
        return false;
602

603
    // If there is a valid commitment, return false (valid).
604
    // Coinbase input witness must be 32 byte witness reserved value (bip141).
605
    // Last output of commitment pattern holds the committed value (bip141).
606
    hash_digest reserved{}, committed{};
×
607
    if (coinbase->inputs_ptr()->front()->reserved_hash(reserved))
×
608
        for (const auto& output: views_reverse(*coinbase->outputs_ptr()))
×
609
            if (output->committed_hash(committed))
×
610
                if (committed == sha256::double_hash(
×
611
                    generate_merkle_root(true), reserved))
×
612
                    return false;
613
    
614
    // If no valid commitment, return true (invalid) if segregated.
615
    // If no block tx has witness data the commitment is optional (bip141).
616
    return is_segregated();
×
617
}
618

619
//*****************************************************************************
620
// CONSENSUS:
621
// bip42 compensates for C++ undefined behavior of a right shift of a number of
622
// bits greater or equal to the shifted integer width. Yet being undefined, the
623
// result of this operation may vary by compiler. The shift_right call below
624
// explicitly implements presumed pre-bip42 behavior (shift overflow modulo) by
625
// default, and specified bip42 behavior (shift overflow to zero) with bip42.
626
//*****************************************************************************
627
static uint64_t block_subsidy(size_t height, uint64_t subsidy_interval,
×
628
    uint64_t initial_block_subsidy_satoshi, bool bip42) NOEXCEPT
629
{
630
    // Guard: quotient domain cannot increase with positive integer divisor.
631
    const auto halves = possible_narrow_cast<size_t>(height / subsidy_interval);
×
632
    return shift_right(initial_block_subsidy_satoshi, halves, bip42);
×
633
}
634

635
// Prevouts required.
636

637
uint64_t block::fees() const NOEXCEPT
×
638
{
639
    // Overflow returns max_uint64.
640
    const auto value = [](uint64_t total, const auto& tx) NOEXCEPT
×
641
    {
642
        return ceilinged_add(total, tx->fee());
×
643
    };
644

645
    return std::accumulate(txs_->begin(), txs_->end(), uint64_t{}, value);
×
646
}
647

648
uint64_t block::claim() const NOEXCEPT
×
649
{
650
    return txs_->empty() ? zero : txs_->front()->value();
×
651
}
652

653
uint64_t block::reward(size_t height, uint64_t subsidy_interval,
×
654
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
655
{
656
    // Overflow returns max_uint64.
657
    return ceilinged_add(fees(), block_subsidy(height, subsidy_interval,
×
658
        initial_block_subsidy_satoshi, bip42));
×
659
}
660

661
bool block::is_overspent(size_t height, uint64_t subsidy_interval,
×
662
    uint64_t initial_block_subsidy_satoshi, bool bip42) const NOEXCEPT
663
{
664
    return claim() > reward(height, subsidy_interval,
×
665
        initial_block_subsidy_satoshi, bip42);
×
666
}
667

668
size_t block::signature_operations(bool bip16, bool bip141) const NOEXCEPT
×
669
{
670
    // Overflow returns max_size_t.
671
    const auto value = [=](size_t total, const auto& tx) NOEXCEPT
×
672
    {
673
        return ceilinged_add(total, tx->signature_operations(bip16, bip141));
×
674
    };
×
675

676
    return std::accumulate(txs_->begin(), txs_->end(), zero, value);
×
677
}
678

679
bool block::is_signature_operations_limited(bool bip16,
×
680
    bool bip141) const NOEXCEPT
681
{
682
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
683
    return signature_operations(bip16, bip141) > limit;
×
684
}
685

686
//*****************************************************************************
687
// CONSENSUS:
688
// This check is excluded under two bip30 exception blocks and bip30_deactivate
689
// until bip30_reactivate. These conditions are rolled up into the bip30 flag.
690
//*****************************************************************************
691
bool block::is_unspent_coinbase_collision() const NOEXCEPT
×
692
{
693
    if (txs_->empty() || txs_->front()->inputs_ptr()->empty())
×
694
        return false;
×
695

696
    // May only commit duplicate coinbase that is already confirmed spent.
697
    // Metadata population defaults coinbase to spent (not a collision).
698
    return !txs_->front()->inputs_ptr()->front()->metadata.spent;
×
699
}
700

701
// Search is unordered, forward refs (and duplicates) caught by block.check.
702
bool block::populate(const chain::context& ctx) const NOEXCEPT
×
703
{
704
    if (txs_->empty())
×
705
        return true;
706

707
    const auto bip68 = ctx.is_enabled(chain::flags::bip68_rule);
×
708
    unordered_map_of_cref_point_to_output_cptr_cref points{ outputs() };
×
709
    uint32_t index{};
×
710

711
    // Populate outputs hash table (coinbase included).
NEW
712
    for (auto tx = txs_->begin(); tx != txs_->end(); ++tx, index = 0)
×
713
        for (const auto& out: *(*tx)->outputs_ptr())
×
714
            points.emplace(cref_point{ (*tx)->get_hash(false), index++ }, out);
×
715

716
    // Populate input prevouts from hash table and obtain locked state.
UNCOV
717
    auto locked = false;
×
NEW
718
    for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
719
    {
720
        for (const auto& in: *(*tx)->inputs_ptr())
×
721
        {
722
            // Map chain::point to cref_point for search, should optimize away.
723
            const auto point = points.find({ in->point().hash(),
×
724
                in->point().index() });
×
725

726
            if (point != points.end())
×
727
            {
728
                // Zero maturity coinbase spend is treated as locked.
NEW
729
                const auto lock = (bip68 && (*tx)->is_internal_lock(*in));
×
NEW
730
                const auto immature = !is_zero(coinbase_maturity) &&
×
NEW
731
                    (in->point().hash() == txs_->front()->get_hash(false));
×
732

733
                in->prevout = point->second;
×
NEW
734
                in->metadata.locked = immature || lock;
×
735
                locked |= in->metadata.locked;
×
736
            }
737
        }
738
    }
739

740
    return !locked;
×
741
}
742

743
// Delegated.
744
// ----------------------------------------------------------------------------
745

746
// DO invoke on coinbase.
747
code block::check_transactions() const NOEXCEPT
3✔
748
{
749
    for (const auto& tx: *txs_)
8✔
750
        if (const auto ec = tx->check())
5✔
751
            return ec;
×
752

753
    return error::block_success;
3✔
754
}
755

756
// DO invoke on coinbase.
757
code block::check_transactions(const context& ctx) const NOEXCEPT
×
758
{
759
    for (const auto& tx: *txs_)
×
760
        if (const auto ec = tx->check(ctx))
×
761
            return ec;
×
762

763
    return error::block_success;
×
764
}
765

766
// Do NOT invoke on coinbase.
767
code block::accept_transactions(const context& ctx) const NOEXCEPT
×
768
{
769
    if (!is_empty())
×
770
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
771
            if (const auto ec = (*tx)->accept(ctx))
×
772
                return ec;
×
773

774
    return error::block_success;
×
775
}
776

777
// Do NOT invoke on coinbase.
778
code block::connect_transactions(const context& ctx) const NOEXCEPT
×
779
{
780
    if (!is_empty())
×
781
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
782
            if (const auto ec = (*tx)->connect(ctx))
×
783
                return ec;
×
784

785
    return error::block_success;
×
786
}
787

788
// Do NOT invoke on coinbase.
789
code block::confirm_transactions(const context& ctx) const NOEXCEPT
×
790
{
791
    if (!is_empty())
×
792
        for (auto tx = std::next(txs_->begin()); tx != txs_->end(); ++tx)
×
793
            if (const auto ec = (*tx)->confirm(ctx))
×
794
                return ec;
×
795

796
    return error::block_success;
×
797
}
798

799
// Identity.
800
// ----------------------------------------------------------------------------
801
// invalid_transaction_commitment, invalid_witness_commitment, block_malleated
802
// codes specifically indicate lack of block hash tx identification (identity).
803

804
code block::identify() const NOEXCEPT
×
805
{
806
    // type64 malleated is a subset of first_not_coinbase.
807
    // type32 malleated is a subset of is_internal_double_spend.
808
    if (is_malleated())
×
809
        return error::block_malleated;
×
810
    if (is_invalid_merkle_root())
×
811
        return error::invalid_transaction_commitment;
×
812

813
    return error::block_success;
×
814
}
815

816
code block::identify(const context& ctx) const NOEXCEPT
×
817
{
818
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
819

820
    if (bip141 && is_invalid_witness_commitment())
×
821
        return error::invalid_witness_commitment;
×
822

823
    return error::block_success;
×
824
}
825

826
// Validation.
827
// ----------------------------------------------------------------------------
828
// In the case of validation failure
829
// The block header is checked/accepted independently.
830

831
// TODO: use of get_hash() in is_forward_reference makes this thread unsafe.
832
code block::check() const NOEXCEPT
3✔
833
{
834
    // empty_block is subset of first_not_coinbase.
835
    //if (is_empty())
836
    //    return error::empty_block;
837
    if (is_oversized())
3✔
838
        return error::block_size_limit;
×
839
    if (is_first_non_coinbase())
3✔
840
        return error::first_not_coinbase;
×
841
    if (is_extra_coinbases())
3✔
842
        return error::extra_coinbases;
×
843
    if (is_forward_reference())
3✔
844
        return error::forward_reference;
×
845
    if (is_internal_double_spend())
3✔
846
        return error::block_internal_double_spend;
×
847
    if (is_invalid_merkle_root())
3✔
848
        return error::invalid_transaction_commitment;
×
849

850
    return check_transactions();
3✔
851
}
852

853
// forks
854
// height
855
// timestamp
856
// median_time_past
857

858
// TODO: use of get_hash() in is_hash_limit_exceeded makes this thread unsafe.
859
code block::check(const context& ctx) const NOEXCEPT
×
860
{
861
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
862
    const auto bip34 = ctx.is_enabled(bip34_rule);
×
863
    const auto bip50 = ctx.is_enabled(bip50_rule);
×
864

865
    if (bip141 && is_overweight())
×
866
        return error::block_weight_limit;
×
867
    if (bip34 && is_invalid_coinbase_script(ctx.height))
×
868
        return error::coinbase_height_mismatch;
×
869
    if (bip50 && is_hash_limit_exceeded())
×
870
        return error::temporary_hash_limit;
×
871
    if (bip141 && is_invalid_witness_commitment())
×
872
        return error::invalid_witness_commitment;
×
873

874
    return check_transactions(ctx);
×
875
}
876

877
// forks
878
// height
879

880
// This assumes that prevout caching is completed on all inputs.
881
code block::accept(const context& ctx, size_t subsidy_interval,
×
882
    uint64_t initial_subsidy) const NOEXCEPT
883
{
884
    const auto bip16 = ctx.is_enabled(bip16_rule);
×
885
    const auto bip42 = ctx.is_enabled(bip42_rule);
×
886
    const auto bip141 = ctx.is_enabled(bip141_rule);
×
887

888
    // prevouts required.
889
    if (is_overspent(ctx.height, subsidy_interval, initial_subsidy, bip42))
×
890
        return error::coinbase_value_limit;
×
891
    if (is_signature_operations_limited(bip16, bip141))
×
892
        return error::block_sigop_limit;
×
893

894
    return accept_transactions(ctx);
×
895
}
896

897
// forks
898

899
// Node performs these checks through database query.
900
// This assumes that prevout and metadata caching are completed on all inputs.
901
code block::confirm(const context& ctx) const NOEXCEPT
×
902
{
903
    const auto bip30 = ctx.is_enabled(bip30_rule);
×
904

905
    if (bip30 && is_unspent_coinbase_collision())
×
906
        return error::unspent_coinbase_collision;
×
907

908
    return confirm_transactions(ctx);
×
909
}
910

911
// forks
912

913
code block::connect(const context& ctx) const NOEXCEPT
×
914
{
915
    return connect_transactions(ctx);
×
916
}
917

918
BC_POP_WARNING()
919
BC_POP_WARNING()
920

921
// JSON value convertors.
922
// ----------------------------------------------------------------------------
923

924
namespace json = boost::json;
925

926
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
927
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
928

929
block tag_invoke(json::value_to_tag<block>,
1✔
930
    const json::value& value) NOEXCEPT
931
{
932
    return
1✔
933
    {
934
        json::value_to<header>(value.at("header")),
1✔
935
        json::value_to<chain::transactions>(value.at("transactions"))
2✔
936
    };
1✔
937
}
938

939
void tag_invoke(json::value_from_tag, json::value& value,
2✔
940
    const block& block) NOEXCEPT
941
{
942
    value =
2✔
943
    {
944
        { "header", block.header() },
945
        { "transactions", *block.transactions_ptr() },
946
    };
2✔
947
}
2✔
948

949
BC_POP_WARNING()
950

951
block::cptr tag_invoke(json::value_to_tag<block::cptr>,
×
952
    const json::value& value) NOEXCEPT
953
{
954
    return to_shared(tag_invoke(json::value_to_tag<block>{}, value));
×
955
}
956

957
// Shared pointer overload is required for navigation.
958
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
959
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
960

961
void tag_invoke(json::value_from_tag tag, json::value& value,
×
962
    const block::cptr& block) NOEXCEPT
963
{
964
    tag_invoke(tag, value, *block);
×
965
}
×
966

967
BC_POP_WARNING()
968
BC_POP_WARNING()
969

970
} // namespace chain
971
} // namespace system
972
} // 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