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

libbitcoin / libbitcoin-system / 9879696031

10 Jul 2024 06:40PM UTC coverage: 82.863% (-0.01%) from 82.874%
9879696031

Pull #1498

github

web-flow
Merge 8a7dacadf into 155e5fae6
Pull Request #1498: Optimizing deserializations (block, header, txs, point).

30 of 31 new or added lines in 4 files covered. (96.77%)

3 existing lines in 3 files now uncovered.

9980 of 12044 relevant lines covered (82.86%)

4793774.11 hits per line

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

75.65
/src/chain/transaction.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/transaction.hpp>
20

21
#include <algorithm>
22
#include <iterator>
23
#include <memory>
24
#include <numeric>
25
#include <type_traits>
26
#include <utility>
27
#include <vector>
28
#include <bitcoin/system/chain/context.hpp>
29
#include <bitcoin/system/chain/enums/magic_numbers.hpp>
30
#include <bitcoin/system/chain/header.hpp>
31
#include <bitcoin/system/chain/input.hpp>
32
#include <bitcoin/system/chain/output.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/machine/machine.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

48
// Precompute fixed elements of signature hashing.
49
// ----------------------------------------------------------------------------
50

51
constexpr auto prefixed = true;
52

53
static const auto& null_output() NOEXCEPT
1✔
54
{
55
    static const auto null = output{}.to_data();
1✔
56
    return null;
1✔
57
}
58

59
static const auto& empty_script() NOEXCEPT
8✔
60
{
61
    static const auto empty = script{}.to_data(prefixed);
8✔
62
    return empty;
8✔
63
}
64

65
static const auto& zero_sequence() NOEXCEPT
1✔
66
{
67
    static const auto sequence = to_little_endian<uint32_t>(0);
1✔
68
    return sequence;
1✔
69
}
70

71
// Constructors.
72
// ----------------------------------------------------------------------------
73

74
transaction::transaction() NOEXCEPT
21✔
75
  : transaction(0,
76
      to_shared<input_cptrs>(),
21✔
77
      to_shared<output_cptrs>(),
21✔
78
      0, false, false)
63✔
79
{
80
}
21✔
81

82
transaction::~transaction() NOEXCEPT
2,077✔
83
{
84
}
2,077✔
85

86
transaction::transaction(transaction&& other) NOEXCEPT
30✔
87
  : transaction(other)
30✔
88
{
89
}
30✔
90

91
transaction::transaction(const transaction& other) NOEXCEPT
983✔
92
  : transaction(
93
      other.version_,
983✔
94
      other.inputs_,
983✔
95
      other.outputs_,
983✔
96
      other.locktime_,
983✔
97
      other.segregated_,
983✔
98
      other.valid_)
983✔
99
{
100
    // Optimized for faster optional, not for copy.
101

102
    if (other.nominal_hash_)
983✔
103
        nominal_hash_ = to_unique(*other.nominal_hash_);
×
104
    else
105
        nominal_hash_.reset();
983✔
106

107
    if (other.witness_hash_)
983✔
108
        witness_hash_ = to_unique(*other.witness_hash_);
×
109
    else
110
        witness_hash_.reset();
983✔
111

112
    if (other.sighash_cache_)
983✔
113
        sighash_cache_ = to_unique(*other.sighash_cache_);
×
114
    else
115
        sighash_cache_.reset();
983✔
116
}
983✔
117

118
transaction::transaction(uint32_t version, chain::inputs&& inputs,
900✔
119
    chain::outputs&& outputs, uint32_t locktime) NOEXCEPT
900✔
120
  : transaction(version, to_shareds(std::move(inputs)),
1,800✔
121
      to_shareds(std::move(outputs)), locktime)
3,600✔
122
{
123
}
900✔
124

125
transaction::transaction(uint32_t version, const chain::inputs& inputs,
1✔
126
    const chain::outputs& outputs, uint32_t locktime) NOEXCEPT
1✔
127
  : transaction(version, to_shareds(inputs), to_shareds(outputs), locktime,
2✔
128
      segregated(inputs), true)
4✔
129
{
130
}
1✔
131

132
transaction::transaction(uint32_t version, const chain::inputs_cptr& inputs,
900✔
133
    const chain::outputs_cptr& outputs, uint32_t locktime) NOEXCEPT
900✔
134
  : transaction(version, inputs, outputs, locktime, segregated(*inputs), true)
900✔
135
{
136
}
900✔
137

138
transaction::transaction(const data_slice& data, bool witness) NOEXCEPT
41✔
139
  : transaction(stream::in::copy(data), witness)
41✔
140
{
141
}
41✔
142

143
////transaction::transaction(stream::in::fast&& stream, bool witness) NOEXCEPT
144
////  : transaction(read::bytes::fast(stream), witness)
145
////{
146
////}
147

148
transaction::transaction(stream::in::fast& stream, bool witness) NOEXCEPT
2✔
149
  : transaction(read::bytes::fast(stream), witness)
2✔
150
{
151
}
2✔
152

153
transaction::transaction(std::istream&& stream, bool witness) NOEXCEPT
41✔
154
  : transaction(read::bytes::istream(stream), witness)
41✔
155
{
156
}
41✔
157

158
transaction::transaction(std::istream& stream, bool witness) NOEXCEPT
4✔
159
  : transaction(read::bytes::istream(stream), witness)
4✔
160
{
161
}
4✔
162

163
transaction::transaction(reader&& source, bool witness) NOEXCEPT
47✔
164
  : transaction(from_data(source, witness))
47✔
165
{
166
}
47✔
167

168
transaction::transaction(reader& source, bool witness) NOEXCEPT
125✔
169
  : transaction(from_data(source, witness))
125✔
170
{
171
}
125✔
172

173
// protected
174
transaction::transaction(uint32_t version,
2,077✔
175
    const chain::inputs_cptr& inputs, const chain::outputs_cptr& outputs,
176
    uint32_t locktime, bool segregated, bool valid) NOEXCEPT
2,077✔
177
  : version_(version),
2,077✔
178
    inputs_(inputs ? inputs : to_shared<input_cptrs>()),
4,154✔
179
    outputs_(outputs ? outputs : to_shared<output_cptrs>()),
2,077✔
180
    locktime_(locktime),
2,077✔
181
    segregated_(segregated),
2,077✔
182
    valid_(valid),
2,077✔
183
    size_(serialized_size(*inputs, *outputs, segregated))
4,154✔
184
{
185
}
2,077✔
186

187
// Operators.
188
// ----------------------------------------------------------------------------
189

190
transaction& transaction::operator=(transaction&& other) NOEXCEPT
×
191
{
192
    *this = other;
×
193
    return *this;
×
194
}
195

196
transaction& transaction::operator=(const transaction& other) NOEXCEPT
×
197
{
198
    version_ = other.version_;
×
199
    inputs_ = other.inputs_;
×
200
    outputs_ = other.outputs_;
×
201
    locktime_ = other.locktime_;
×
202
    segregated_ = other.segregated_;
×
203
    valid_ = other.valid_;
×
204
    size_ = other.size_;
×
205

206
    // Optimized for faster optional, not for copy.
207

208
    if (other.nominal_hash_)
×
209
        nominal_hash_ = to_unique(*other.nominal_hash_);
×
210
    else
211
        nominal_hash_.reset();
×
212

213
    if (other.witness_hash_)
×
214
        witness_hash_ = to_unique(*other.witness_hash_);
×
215
    else
216
        witness_hash_.reset();
×
217

218
    if (other.sighash_cache_)
×
219
        sighash_cache_ = to_unique(*other.sighash_cache_);
×
220
    else
221
        sighash_cache_.reset();
×
222

223
    return *this;
×
224
}
225

226
bool transaction::operator==(const transaction& other) const NOEXCEPT
58✔
227
{
228
    // Compares input/output elements, not pointers, cache not compared.
229
    return (version_ == other.version_)
58✔
230
        && (locktime_ == other.locktime_)
56✔
231
        && ((inputs_ == other.inputs_) || 
70✔
232
            deep_equal(*inputs_, *other.inputs_))
14✔
233
        && ((outputs_ == other.outputs_) ||
128✔
234
            deep_equal(*outputs_, *other.outputs_));
14✔
235
}
236

237
bool transaction::operator!=(const transaction& other) const NOEXCEPT
2✔
238
{
239
    return !(*this == other);
2✔
240
}
241

242
// Deserialization.
243
// ----------------------------------------------------------------------------
244

245
template<class Put, class Source>
246
std::shared_ptr<const std_vector<std::shared_ptr<const Put>>>
247
read_puts(Source& source) NOEXCEPT
356✔
248
{
249
    // Allocate arena cputs shared_ptr and std_vector(captures arena).
250
    using puts_type = std_vector<std::shared_ptr<const Put>>;
251
    auto cputs = to_allocated<puts_type>(source.allocator());
356✔
252

253
    BC_PUSH_WARNING(NO_UNGUARDED_POINTERS)
254
    auto puts = to_non_const_raw_ptr(cputs);
255
    BC_POP_WARNING()
256

257
    // Allocate cputs capacity(uses arena).
258
    const auto capacity = source.read_size(max_block_size);
356✔
259
    puts->reserve(capacity);
356✔
260

261
    // Allocate each shared_ptr<put> and move ptr to reservation.
262
    // Each put is constructed in place as allocated by/with its pointer.
263
    for (size_t put = 0; put < capacity; ++put)
834✔
264
        puts->push_back(to_allocated<Put>(source.allocator(), source));
956✔
265

266
    return cputs;
356✔
267
}
268

269
// static/private
270
transaction transaction::from_data(reader& source, bool witness) NOEXCEPT
172✔
271
{
272
    const auto version = source.read_4_bytes_little_endian();
172✔
273
    auto inputs = read_puts<input>(source);
172✔
274
    chain::outputs_cptr outputs;
172✔
275

276
    // Expensive repeated recomputation, so cache segregated state.
277
    const auto segregated = inputs->size() == witness_marker &&
184✔
278
        source.peek_byte() == witness_enabled;
12✔
279

280
    // Detect witness as no inputs (marker) and expected flag (bip144).
281
    if (segregated)
172✔
282
    {
283
        // Skip over the peeked witness flag.
284
        source.skip_byte();
12✔
285

286
        // Inputs and outputs are constructed on a vector of const pointers.
287
        inputs = read_puts<input>(source);
12✔
288
        outputs = read_puts<output>(source);
12✔
289

290
        // Read or skip witnesses as specified.
291
        if (witness)
12✔
292
        {
293
            for (auto& input: *inputs)
28✔
294
            {
295
                BC_PUSH_WARNING(NO_UNGUARDED_POINTERS)
296
                to_non_const_raw_ptr(input)->set_witness(source);
16✔
297
                BC_POP_WARNING()
298
            }
299
        }
300
        else
301
        {
NEW
302
            for (size_t in = 0; in < inputs->size(); ++in)
×
UNCOV
303
                witness::skip(source, true);
×
304
        }
305
    }
306
    else
307
    {
308
        // Default witness is populated on input construct.
309
        outputs = read_puts<const output>(source);
320✔
310
    }
311

312
    const auto locktime = source.read_4_bytes_little_endian();
172✔
313
    return { version, inputs, outputs, locktime, segregated, source };
172✔
314
}
315

316
// Serialization.
317
// ----------------------------------------------------------------------------
318

319
// Transactions with empty witnesses always use old serialization (bip144).
320
// If no inputs are witness programs then witness hash is tx hash (bip141).
321
data_chunk transaction::to_data(bool witness) const NOEXCEPT
10✔
322
{
323
    witness &= segregated_;
10✔
324

325
    data_chunk data(serialized_size(witness));
10✔
326
    stream::out::copy ostream(data);
10✔
327
    to_data(ostream, witness);
10✔
328
    return data;
20✔
329
}
10✔
330

331
void transaction::to_data(std::ostream& stream, bool witness) const NOEXCEPT
11✔
332
{
333
    witness &= segregated_;
11✔
334

335
    write::bytes::ostream out(stream);
11✔
336
    to_data(out, witness);
11✔
337
}
11✔
338

339
void transaction::to_data(writer& sink, bool witness) const NOEXCEPT
961✔
340
{
341
    witness &= segregated_;
961✔
342

343
    sink.write_4_bytes_little_endian(version_);
961✔
344

345
    if (witness)
961✔
346
    {
347
        sink.write_byte(witness_marker);
×
348
        sink.write_byte(witness_enabled);
×
349
    }
350

351
    sink.write_variable(inputs_->size());
961✔
352
    for (const auto& input: *inputs_)
2,340✔
353
        input->to_data(sink);
1,379✔
354

355
    sink.write_variable(outputs_->size());
961✔
356
    for (const auto& output: *outputs_)
2,621✔
357
        output->to_data(sink);
1,660✔
358

359
    if (witness)
961✔
360
        for (auto& input: *inputs_)
×
361
            input->witness().to_data(sink, true);
×
362

363
    sink.write_4_bytes_little_endian(locktime_);
961✔
364
}
961✔
365

366
// static/private
367
transaction::sizes transaction::serialized_size(
2,077✔
368
    const chain::input_cptrs& inputs,
369
    const chain::output_cptrs& outputs, bool segregated) NOEXCEPT
370
{
371
    sizes size{ zero, zero };
2,077✔
372

373
    // Keep the condition outside of the loop.
374
    if (segregated)
2,077✔
375
    {
376
        std::for_each(inputs.begin(), inputs.end(), [&](const auto& in) NOEXCEPT
52✔
377
        {
378
            size.nominal = ceilinged_add(size.nominal, in->nominal_size());
64✔
379
            size.witnessed = ceilinged_add(size.witnessed, in->witnessed_size());
32✔
380
        });
32✔
381
    }
382
    else
383
    {
384
        // Witness must be zeroed because witnesses have nonzero size when they
385
        // are zero-valued, so they can be archived easily. Also it would be
386
        // wasteful to to count mutiple zero sizes, so exclude them here.
387
        std::for_each(inputs.begin(), inputs.end(), [&](const auto& in) NOEXCEPT
4,135✔
388
        {
389
            size.nominal = ceilinged_add(size.nominal, in->nominal_size());
2,078✔
390
        });
2,078✔
391
    }
392

393
    const auto outs = [](size_t total, const auto& output) NOEXCEPT
569✔
394
    {
395
        return ceilinged_add(total, output->serialized_size());
569✔
396
    };
397

398
    constexpr auto base_const_size = ceilinged_add(
2,077✔
399
        sizeof(version_),
400
        sizeof(locktime_));
401

402
    constexpr auto witness_const_size = ceilinged_add(
2,077✔
403
        sizeof(witness_marker),
404
        sizeof(witness_enabled));
405

406
    const auto base_size = ceilinged_add(ceilinged_add(ceilinged_add(
2,077✔
407
        base_const_size,
408
        variable_size(inputs.size())),
409
        variable_size(outputs.size())),
410
        std::accumulate(outputs.begin(), outputs.end(), zero, outs));
411

412
    const auto nominal_size = ceilinged_add(
2,077✔
413
        base_size,
414
        size.nominal);
415

416
    const auto witnessed_size = ceilinged_add(ceilinged_add(
2,077✔
417
        base_size,
418
        witness_const_size),
419
        size.witnessed);
420

421
    return { nominal_size, witnessed_size };
2,077✔
422
}
423

424
size_t transaction::serialized_size(bool witness) const NOEXCEPT
543✔
425
{
426
    witness &= segregated_;
543✔
427

428
    return witness ? size_.witnessed : size_.nominal;
543✔
429
}
430

431
// Properties.
432
// ----------------------------------------------------------------------------
433

434
bool transaction::is_valid() const NOEXCEPT
775✔
435
{
436
    return valid_;
775✔
437
}
438

439
size_t transaction::inputs() const NOEXCEPT
1,563✔
440
{
441
    return inputs_->size();
1,563✔
442
}
443

444
size_t transaction::outputs() const NOEXCEPT
1✔
445
{
446
    return outputs_->size();
1✔
447
}
448

449
uint32_t transaction::version() const NOEXCEPT
6✔
450
{
451
    return version_;
4✔
452
}
453

454
uint32_t transaction::locktime() const NOEXCEPT
15✔
455
{
456
    return locktime_;
4✔
457
}
458

459
const inputs_cptr& transaction::inputs_ptr() const NOEXCEPT
2,436✔
460
{
461
    return inputs_;
2,436✔
462
}
463

464
const outputs_cptr& transaction::outputs_ptr() const NOEXCEPT
62✔
465
{
466
    return outputs_;
62✔
467
}
468

469
uint64_t transaction::fee() const NOEXCEPT
4✔
470
{
471
    // Underflow returns zero (and is_overspent() will be true).
472
    // This is value of prevouts spent by inputs minus that claimed by outputs.
473
    return floored_subtract(value(), claim());
4✔
474
}
475

476
void transaction::set_nominal_hash(hash_digest&& hash) const NOEXCEPT
7✔
477
{
478
    nominal_hash_ = to_unique(std::move(hash));
14✔
479
}
7✔
480

481
void transaction::set_witness_hash(hash_digest&& hash) const NOEXCEPT
2✔
482
{
483
    witness_hash_ = to_unique(std::move(hash));
4✔
484
}
2✔
485

486
const hash_digest& transaction::get_hash(bool witness) const NOEXCEPT
11✔
487
{
488
    if (witness)
11✔
489
    {
490
        if (!witness_hash_) set_witness_hash(hash(witness));
3✔
491
        return *witness_hash_;
3✔
492
    }
493
    else
494
    {
495
        if (!nominal_hash_) set_nominal_hash(hash(witness));
8✔
496
        return *nominal_hash_;
8✔
497
    }
498
}
499

500
hash_digest transaction::hash(bool witness) const NOEXCEPT
930✔
501
{
502
    if (segregated_)
930✔
503
    {
504
        if (witness)
18✔
505
        {
506
            // Witness coinbase tx hash is assumed to be null_hash (bip141).
507
            if (witness_hash_) return *witness_hash_;
×
508
            if (is_coinbase()) return null_hash;
×
509
        }
510
        else
511
        {
512
            if (nominal_hash_) return *nominal_hash_;
18✔
513
        }
514
    }
515
    else
516
    {
517
        if (nominal_hash_) return *nominal_hash_;
912✔
518
    }
519

520
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
521
    hash_digest digest;
925✔
522
    BC_POP_WARNING()
523

524
    stream::out::fast stream{ digest };
925✔
525
    hash::sha256x2::fast sink{ stream };
925✔
526
    to_data(sink, witness);
925✔
527
    sink.flush();
925✔
528
    return digest;
925✔
529
}
925✔
530

531
// Methods.
532
// ----------------------------------------------------------------------------
533

534
bool transaction::is_dusty(uint64_t minimum_output_value) const NOEXCEPT
6✔
535
{
536
    const auto dusty = [=](const auto& output) NOEXCEPT
9✔
537
    {
538
        return output->is_dust(minimum_output_value);
9✔
539
    };
6✔
540

541
    return std::any_of(outputs_->begin(), outputs_->end(), dusty);
6✔
542
}
543

544
size_t transaction::signature_operations(bool bip16, bool bip141) const NOEXCEPT
1✔
545
{
546
    // Includes BIP16 p2sh additional sigops, max_size_t if prevout invalid.
547
    const auto in = [=](size_t total, const auto& input) NOEXCEPT
×
548
    {
549
        return ceilinged_add(total, input->signature_operations(bip16, bip141));
×
550
    };
1✔
551

552
    const auto out = [=](size_t total, const auto& output) NOEXCEPT
×
553
    {
554
        return ceilinged_add(total, output->signature_operations(bip141));
×
555
    };
1✔
556

557
    // Overflow returns max_size_t.
558
    return ceilinged_add(
1✔
559
        std::accumulate(inputs_->begin(), inputs_->end(), zero, in),
560
        std::accumulate(outputs_->begin(), outputs_->end(), zero, out));
1✔
561
}
562

563
chain::points transaction::points() const NOEXCEPT
4✔
564
{
565
    chain::points out(inputs_->size());
4✔
566

567
    const auto point = [](const auto& input) NOEXCEPT
8✔
568
    {
569
        return input->point();
8✔
570
    };
571

572
    std::transform(inputs_->begin(), inputs_->end(), out.begin(), point);
4✔
573
    return out;
4✔
574
}
575

576
hash_digest transaction::outputs_hash() const NOEXCEPT
8✔
577
{
578
    if (sighash_cache_)
8✔
579
        return sighash_cache_->outputs;
×
580

581
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
582
    hash_digest digest;
8✔
583
    BC_POP_WARNING()
584
        
585
    stream::out::fast stream{ digest };
8✔
586
    hash::sha256x2::fast sink{ stream };
8✔
587

588
    const auto& outs = *outputs_;
8✔
589
    for (const auto& output: outs)
22✔
590
        output->to_data(sink);
14✔
591

592
    sink.flush();
8✔
593
    return digest;
8✔
594
}
8✔
595

596
hash_digest transaction::points_hash() const NOEXCEPT
11✔
597
{
598
    if (sighash_cache_)
11✔
599
        return sighash_cache_->points;
×
600

601
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
602
    hash_digest digest;
11✔
603
    BC_POP_WARNING()
604

605
    stream::out::fast stream{ digest };
11✔
606
    hash::sha256x2::fast sink{ stream };
11✔
607

608
    const auto& ins = *inputs_;
11✔
609
    for (const auto& input: ins)
27✔
610
        input->point().to_data(sink);
16✔
611

612
    sink.flush();
11✔
613
    return digest;
11✔
614
}
11✔
615

616
hash_digest transaction::sequences_hash() const NOEXCEPT
7✔
617
{
618
    if (sighash_cache_)
7✔
619
        return sighash_cache_->sequences;
×
620

621
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
622
    hash_digest digest;
7✔
623
    BC_POP_WARNING()
624

625
    stream::out::fast stream{ digest };
7✔
626
    hash::sha256x2::fast sink{ stream };
7✔
627

628
    const auto& ins = *inputs_;
7✔
629
    for (const auto& input: ins)
17✔
630
        sink.write_4_bytes_little_endian(input->sequence());
10✔
631

632
    sink.flush();
7✔
633
    return digest;
7✔
634
}
7✔
635

636
// Signing (unversioned).
637
// ----------------------------------------------------------------------------
638

639
// private
640
transaction::input_iterator transaction::input_at(
4✔
641
    uint32_t index) const NOEXCEPT
642
{
643
    // Guarded by check_signature and create_endorsement.
644
    BC_ASSERT_MSG(index < inputs_->size(), "invalid input index");
4✔
645

646
    return std::next(inputs_->begin(), index);
4✔
647
}
648

649
// private
650
uint32_t transaction::input_index(const input_iterator& input) const NOEXCEPT
25✔
651
{
652
    // Guarded by unversioned_signature_hash and output_hash.
653
    BC_ASSERT_MSG(inputs_->begin() != inputs_->end(), "invalid input iterator");
25✔
654

655
    return possible_narrow_and_sign_cast<uint32_t>(
25✔
656
        std::distance(inputs_->begin(), input));
×
657
}
658

659
//*****************************************************************************
660
// CONSENSUS: Due to masking of bits 6/7 (8 is the anyone_can_pay flag),
661
// there are 4 possible 7 bit values that can set "single" and 4 others that
662
// can set none, and yet all other values set "all".
663
//*****************************************************************************
664
inline coverage mask_sighash(uint8_t sighash_flags) NOEXCEPT
41✔
665
{
666
    switch (sighash_flags & coverage::mask)
41✔
667
    {
668
        case coverage::hash_single:
669
            return coverage::hash_single;
670
        case coverage::hash_none:
2✔
671
            return coverage::hash_none;
2✔
672
        default:
18✔
673
            return coverage::hash_all;
18✔
674
    }
675
}
676

677
void transaction::signature_hash_single(writer& sink,
4✔
678
    const input_iterator& input, const script& sub,
679
    uint8_t sighash_flags) const NOEXCEPT
680
{
681
    const auto write_inputs = [this, &input, &sub, sighash_flags](
8✔
682
        writer& sink) NOEXCEPT
4✔
683
    {
684
        const auto& self = **input;
4✔
685
        const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
4✔
686
        input_cptrs::const_iterator in;
4✔
687

688
        sink.write_variable(anyone ? one : inputs_->size());
5✔
689

690
        for (in = inputs_->begin(); !anyone && in != input; ++in)
4✔
691
        {
692
            (*in)->point().to_data(sink);
×
693
            sink.write_bytes(empty_script());
×
694
            sink.write_bytes(zero_sequence());
×
695
        }
696

697
        self.point().to_data(sink);
4✔
698
        sub.to_data(sink, prefixed);
4✔
699
        sink.write_4_bytes_little_endian(self.sequence());
4✔
700

701
        for (++in; !anyone && in != inputs_->end(); ++in)
5✔
702
        {
703
            (*in)->point().to_data(sink);
1✔
704
            sink.write_bytes(empty_script());
1✔
705
            sink.write_bytes(zero_sequence());
1✔
706
        }
707
    };
4✔
708

709
    const auto write_outputs = [this, &input](writer& sink) NOEXCEPT
12✔
710
    {
711
        const auto index = input_index(input);
4✔
712

713
        sink.write_variable(add1(index));
4✔
714

715
        for (size_t output = 0; output < index; ++output)
5✔
716
            sink.write_bytes(null_output());
1✔
717

718
        // Guarded by unversioned_signature_hash.
719
        outputs_->at(index)->to_data(sink);
4✔
720
    };
8✔
721

722
    sink.write_4_bytes_little_endian(version_);
4✔
723
    write_inputs(sink);
4✔
724
    write_outputs(sink);
4✔
725
    sink.write_4_bytes_little_endian(locktime_);
4✔
726
    sink.write_4_bytes_little_endian(sighash_flags);
4✔
727
}
4✔
728

729
void transaction::signature_hash_none(writer& sink,
×
730
    const input_iterator& input, const script& sub,
731
    uint8_t sighash_flags) const NOEXCEPT
732
{
733
    const auto write_inputs = [this, &input, &sub, sighash_flags](
×
734
        writer& sink) NOEXCEPT
×
735
    {
736
        const auto& self = **input;
×
737
        const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
×
738
        input_cptrs::const_iterator in;
×
739

740
        sink.write_variable(anyone ? one : inputs_->size());
×
741

742
        for (in = inputs_->begin(); !anyone && in != input; ++in)
×
743
        {
744
            (*in)->point().to_data(sink);
×
745
            sink.write_bytes(empty_script());
×
746
            sink.write_bytes(zero_sequence());
×
747
        }
748

749
        self.point().to_data(sink);
×
750
        sub.to_data(sink, prefixed);
×
751
        sink.write_4_bytes_little_endian(self.sequence());
×
752

753
        for (++in; !anyone && in != inputs_->end(); ++in)
×
754
        {
755
            (*in)->point().to_data(sink);
×
756
            sink.write_bytes(empty_script());
×
757
            sink.write_bytes(zero_sequence());
×
758
        }
759
    };
×
760

761
    sink.write_4_bytes_little_endian(version_);
×
762
    write_inputs(sink);
×
763
    sink.write_variable(zero);
×
764
    sink.write_4_bytes_little_endian(locktime_);
×
765
    sink.write_4_bytes_little_endian(sighash_flags);
×
766
}
×
767

768
void transaction::signature_hash_all(writer& sink,
12✔
769
    const input_iterator& input, const script& sub,
770
    uint8_t flags) const NOEXCEPT
771
{
772
    const auto write_inputs = [this, &input, &sub, flags](
24✔
773
        writer& sink) NOEXCEPT
43✔
774
    {
775
        const auto& self = **input;
12✔
776
        const auto anyone = to_bool(flags & coverage::anyone_can_pay);
12✔
777
        input_cptrs::const_iterator in;
12✔
778

779
        sink.write_variable(anyone ? one : inputs_->size());
24✔
780

781
        for (in = inputs_->begin(); !anyone && in != input; ++in)
15✔
782
        {
783
            (*in)->point().to_data(sink);
3✔
784
            sink.write_bytes(empty_script());
3✔
785
            sink.write_4_bytes_little_endian((*in)->sequence());
3✔
786
        }
787

788
        self.point().to_data(sink);
12✔
789
        sub.to_data(sink, prefixed);
12✔
790
        sink.write_4_bytes_little_endian(self.sequence());
12✔
791

792
        for (++in; !anyone && in != inputs_->end(); ++in)
16✔
793
        {
794
            (*in)->point().to_data(sink);
4✔
795
            sink.write_bytes(empty_script());
4✔
796
            sink.write_4_bytes_little_endian((*in)->sequence());
4✔
797
        }
798
    };
12✔
799

800
    const auto write_outputs = [this](writer& sink) NOEXCEPT
36✔
801
    {
802
        sink.write_variable(outputs_->size());
12✔
803
        for (const auto& output: *outputs_)
27✔
804
            output->to_data(sink);
15✔
805
    };
24✔
806

807
    sink.write_4_bytes_little_endian(version_);
12✔
808
    write_inputs(sink);
12✔
809
    write_outputs(sink);
12✔
810
    sink.write_4_bytes_little_endian(locktime_);
12✔
811
    sink.write_4_bytes_little_endian(flags);
12✔
812
}
12✔
813

814
// private
815
hash_digest transaction::unversioned_signature_hash(
19✔
816
    const input_iterator& input, const script& sub,
817
    uint8_t sighash_flags) const NOEXCEPT
818
{
819
    // Set options.
820
    const auto flag = mask_sighash(sighash_flags);
19✔
821

822
    // Create hash writer.
823
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
824
    hash_digest digest;
19✔
825
    BC_POP_WARNING()
826

827
    stream::out::fast stream{ digest };
19✔
828
    hash::sha256x2::fast sink{ stream };
19✔
829

830
    switch (flag)
19✔
831
    {
832
        case coverage::hash_single:
7✔
833
        {
7✔
834
            //*****************************************************************
835
            // CONSENSUS: return one_hash if index exceeds outputs in sighash.
836
            // Related Bug: bitcointalk.org/index.php?topic=260595
837
            // Exploit: joncave.co.uk/2014/08/bitcoin-sighash-single/
838
            //*****************************************************************
839
            if (input_index(input) >= outputs_->size())
7✔
840
                return one_hash;
3✔
841

842
            signature_hash_single(sink, input, sub, sighash_flags);
4✔
843
            break;
4✔
844
        }
845
        case coverage::hash_none:
×
846
        {
×
847
            signature_hash_none(sink, input, sub, sighash_flags);
×
848
            break;
×
849
        }
850
        default:
12✔
851
        case coverage::hash_all:
12✔
852
        {
12✔
853
            signature_hash_all(sink, input, sub, sighash_flags);
12✔
854
        }
855
    }
856

857
    sink.flush();
16✔
858
    return digest;
16✔
859
}
19✔
860

861
// Signing (version 0).
862
// ----------------------------------------------------------------------------
863

864
// private
865
// TODO: taproot requires both single and double hash of each.
866
void transaction::initialize_sighash_cache() const NOEXCEPT
2✔
867
{
868
    // This overconstructs the cache (anyone or !all), however it is simple.
869
    if (!segregated_)
2✔
870
        return;
871

872
    sighash_cache_ = to_unique<sighash_cache>
2✔
873
    (
4✔
874
        outputs_hash(),
2✔
875
        points_hash(),
2✔
876
        sequences_hash()
4✔
877
    );
878
}
879

880
// private
881
hash_digest transaction::output_hash(const input_iterator& input) const NOEXCEPT
14✔
882
{
883
    const auto index = input_index(input);
14✔
884

885
    //*************************************************************************
886
    // CONSENSUS: if index exceeds outputs in signature hash, return null_hash.
887
    //*************************************************************************
888
    if (index >= outputs_->size())
14✔
889
        return null_hash;
2✔
890

891
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
892
    hash_digest digest;
12✔
893
    BC_POP_WARNING()
894

895
    stream::out::fast stream{ digest };
12✔
896
    hash::sha256x2::fast sink{ stream };
12✔
897
    outputs_->at(index)->to_data(sink);
12✔
898
    sink.flush();
12✔
899
    return digest;
12✔
900
}
12✔
901

902
// private
903
hash_digest transaction::version_0_signature_hash(const input_iterator& input,
29✔
904
    const script& sub, uint64_t value, uint8_t sighash_flags,
905
    bool bip143) const NOEXCEPT
906
{
907
    // bip143/v0: the way of serialization is changed.
908
    if (!bip143)
29✔
909
        return unversioned_signature_hash(input, sub, sighash_flags);
7✔
910

911
    // Set options.
912
    const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
22✔
913
    const auto flag = mask_sighash(sighash_flags);
22✔
914
    const auto all = (flag == coverage::hash_all);
22✔
915
    const auto single = (flag == coverage::hash_single);
22✔
916
    const auto& self = **input;
22✔
917

918
    // Create hash writer.
919
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
920
    hash_digest digest;
22✔
921
    BC_POP_WARNING()
922

923
    stream::out::fast stream{ digest };
22✔
924
    hash::sha256x2::fast sink{ stream };
22✔
925

926
    // Create signature hash.
927
    sink.write_little_endian(version_);
22✔
928

929
    // Conditioning points, sequences, and outputs writes on cache_ instead of
930
    // conditionally passing them from methods avoids copying the cached hash.
931

932
    // points
933
    sink.write_bytes(!anyone ? points_hash() : null_hash);
22✔
934

935
    // sequences
936
    sink.write_bytes(!anyone && all ? sequences_hash() : null_hash);
22✔
937

938
    self.point().to_data(sink);
22✔
939
    sub.to_data(sink, prefixed);
22✔
940
    sink.write_little_endian(value);
22✔
941
    sink.write_little_endian(self.sequence());
22✔
942

943
    // outputs
944
    if (single)
22✔
945
        sink.write_bytes(output_hash(input));
14✔
946
    else
947
        sink.write_bytes(all ? outputs_hash() : null_hash);
8✔
948

949
    sink.write_little_endian(locktime_);
22✔
950
    sink.write_4_bytes_little_endian(sighash_flags);
22✔
951

952
    sink.flush();
22✔
953
    return digest;
22✔
954
}
22✔
955

956
// Signing (unversioned and version 0).
957
// ----------------------------------------------------------------------------
958

959
// ****************************************************************************
960
// CONSENSUS: sighash flags are carried in a single byte but are encoded as 4
961
// bytes in the signature hash preimage serialization.
962
// ****************************************************************************
963

964
hash_digest transaction::signature_hash(const input_iterator& input,
41✔
965
    const script& sub, uint64_t value, uint8_t sighash_flags,
966
    script_version version, bool bip143) const NOEXCEPT
967
{
968
    // There is no rational interpretation of a signature hash for a coinbase.
969
    BC_ASSERT(!is_coinbase());
41✔
970

971
    switch (version)
41✔
972
    {
973
        case script_version::unversioned:
12✔
974
            return unversioned_signature_hash(input, sub, sighash_flags);
12✔
975
        case script_version::zero:
29✔
976
            return version_0_signature_hash(input, sub, value, sighash_flags,
29✔
977
                bip143);
29✔
978
        case script_version::reserved:
×
979
        default:
×
980
            return {};
×
981
    }
982
}
983

984
// This is not used internal to the library.
985
bool transaction::check_signature(const ec_signature& signature,
2✔
986
    const data_slice& public_key, const script& sub, uint32_t index,
987
    uint64_t value, uint8_t sighash_flags, script_version version,
988
    bool bip143) const NOEXCEPT
989
{
990
    if ((index >= inputs_->size()) || signature.empty() || public_key.empty())
2✔
991
        return false;
992

993
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
994
        sighash_flags, version, bip143);
995

996
    // Validate the EC signature.
997
    return verify_signature(public_key, sighash, signature);
2✔
998
}
999

1000
// This is not used internal to the library.
1001
bool transaction::create_endorsement(endorsement& out, const ec_secret& secret,
2✔
1002
    const script& sub, uint32_t index, uint64_t value, uint8_t sighash_flags,
1003
    script_version version, bool bip143) const NOEXCEPT
1004
{
1005
    if (index >= inputs_->size())
2✔
1006
        return false;
1007

1008
    out.reserve(max_endorsement_size);
2✔
1009
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
1010
        sighash_flags, version, bip143);
1011

1012
    // Create the EC signature and encode as DER.
1013
    ec_signature signature;
2✔
1014
    if (!sign(signature, secret, sighash) || !encode_signature(out, signature))
2✔
1015
        return false;
×
1016

1017
    // Add the sighash type to the end of the DER signature -> endorsement.
1018
    out.push_back(sighash_flags);
2✔
1019
    ////out.shrink_to_fit();
1020
    return true;
2✔
1021
}
1022

1023
// Guard (context free).
1024
// ----------------------------------------------------------------------------
1025

1026
bool transaction::is_coinbase() const NOEXCEPT
70✔
1027
{
1028
    return is_one(inputs_->size()) && inputs_->front()->point().is_null();
70✔
1029
}
1030

1031
bool transaction::is_internal_double_spend() const NOEXCEPT
4✔
1032
{
1033
    // TODO: optimize (see block.is_internal_double_spend).
1034
    return !is_distinct(points());
4✔
1035
}
1036

1037
// TODO: a pool (non-coinbase) tx must fit into a block (with a coinbase).
1038
bool transaction::is_oversized() const NOEXCEPT
×
1039
{
1040
    return serialized_size(false) > max_block_size;
×
1041
}
1042

1043
// Guard (contextual).
1044
// ----------------------------------------------------------------------------
1045

1046
// static/private
1047
bool transaction::segregated(const chain::inputs& inputs) NOEXCEPT
1✔
1048
{
1049
    const auto witnessed = [](const auto& input) NOEXCEPT
2✔
1050
    {
1051
        return !input.witness().stack().empty();
1✔
1052
    };
1053

1054
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
1✔
1055
}
1056

1057
// static/private
1058
bool transaction::segregated(const chain::input_cptrs& inputs) NOEXCEPT
900✔
1059
{
1060
    const auto witnessed = [](const auto& input) NOEXCEPT
902✔
1061
    {
1062
        return !input->witness().stack().empty();
902✔
1063
    };
1064

1065
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
900✔
1066
}
1067

1068
bool transaction::is_segregated() const NOEXCEPT
×
1069
{
1070
    return segregated_;
×
1071
}
1072

1073
size_t transaction::weight() const NOEXCEPT
×
1074
{
1075
    // Block weight is 3 * base size * + 1 * total size (bip141).
1076
    return ceilinged_add(
×
1077
        ceilinged_multiply(base_size_contribution, serialized_size(false)),
1078
        ceilinged_multiply(total_size_contribution, serialized_size(true)));
×
1079
}
1080

1081
bool transaction::is_overweight() const NOEXCEPT
×
1082
{
1083
    return weight() > max_block_weight;
×
1084
}
1085

1086
//*****************************************************************************
1087
// CONSENSUS: Legacy sigops are counted in coinbase scripts despite the fact
1088
// that coinbase input scripts are never executed. There is no need to exclude
1089
// p2sh coinbase sigops since there is never a script to count.
1090
//*****************************************************************************
1091
bool transaction::is_signature_operations_limit(bool bip16,
×
1092
    bool bip141) const NOEXCEPT
1093
{
1094
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
1095
    return signature_operations(bip16, bip141) > limit;
×
1096
}
1097

1098
// Check (context free).
1099
// ----------------------------------------------------------------------------
1100

1101
bool transaction::is_empty() const NOEXCEPT
4✔
1102
{
1103
    return inputs_->empty() || outputs_->empty();
4✔
1104
}
1105

1106
bool transaction::is_null_non_coinbase() const NOEXCEPT
5✔
1107
{
1108
    BC_ASSERT(!is_coinbase());
5✔
1109

1110
    const auto invalid = [](const auto& input) NOEXCEPT
7✔
1111
    {
1112
        return input->point().is_null();
7✔
1113
    };
1114

1115
    // True if not coinbase but has null previous_output(s).
1116
    return std::any_of(inputs_->begin(), inputs_->end(), invalid);
5✔
1117
}
1118

1119
bool transaction::is_invalid_coinbase_size() const NOEXCEPT
6✔
1120
{
1121
    BC_ASSERT(is_coinbase());
6✔
1122

1123
    // True if coinbase and has invalid input[0] script size.
1124
    const auto script_size = inputs_->front()->script().serialized_size(false);
6✔
1125
    return script_size < min_coinbase_size || script_size > max_coinbase_size;
6✔
1126
}
1127

1128
// Accept (contextual).
1129
// ----------------------------------------------------------------------------
1130

1131
bool transaction::is_non_final(size_t height, uint32_t timestamp,
5✔
1132
    uint32_t median_time_past, bool bip113) const NOEXCEPT
1133
{
1134
    // BIP113: comparing the locktime against the median of the past 11 block
1135
    // timestamps, rather than the timestamp of the block including the tx.
1136
    const auto time = bip113 ? median_time_past : timestamp;
5✔
1137

1138
    const auto finalized = [](const auto& input) NOEXCEPT
2✔
1139
    {
1140
        return input->is_final();
2✔
1141
    };
1142

1143
    const auto height_time = locktime_ < locktime_threshold ? height : time;
5✔
1144

1145
    return !(is_zero(locktime_) || locktime_ < height_time ||
8✔
1146
        std::all_of(inputs_->begin(), inputs_->end(), finalized));
3✔
1147
}
1148

1149
bool transaction::is_missing_prevouts() const NOEXCEPT
3✔
1150
{
1151
    BC_ASSERT(!is_coinbase());
3✔
1152

1153
    // Null or invalid prevout indicates not found.
1154
    const auto missing = [](const auto& input) NOEXCEPT
2✔
1155
    {
1156
        return !input->prevout;
1157
    };
1158

1159
    return std::any_of(inputs_->begin(), inputs_->end(), missing);
3✔
1160
}
1161

1162
uint64_t transaction::claim() const NOEXCEPT
8✔
1163
{
1164
    // Overflow returns max_uint64.
1165
    const auto sum = [](uint64_t total, const auto& output) NOEXCEPT
8✔
1166
    {
1167
        return ceilinged_add(total, output->value());
8✔
1168
    };
1169

1170
    // The amount claimed by outputs.
1171
    return std::accumulate(outputs_->begin(), outputs_->end(), 0_u64, sum);
8✔
1172
}
1173

1174
uint64_t transaction::value() const NOEXCEPT
9✔
1175
{
1176
    // Overflow, not populated, and coinbase (default) return max_uint64.
1177
    const auto sum = [](uint64_t total, const auto& input) NOEXCEPT
7✔
1178
    {
1179
        const auto value = input->prevout ? input->prevout->value() : max_uint64;
7✔
1180
        return ceilinged_add(total, value);
7✔
1181
    };
1182

1183
    // The amount of prevouts (referenced by inputs).
1184
    return std::accumulate(inputs_->begin(), inputs_->end(), 0_u64, sum);
9✔
1185
}
1186

1187
bool transaction::is_overspent() const NOEXCEPT
2✔
1188
{
1189
    BC_ASSERT(!is_coinbase());
2✔
1190

1191
    return claim() > value();
2✔
1192
}
1193

1194
constexpr bool is_non_coinbase_mature(size_t tx_height, size_t height) NOEXCEPT
2✔
1195
{
1196
    return tx_height <= height;
2✔
1197
}
1198

1199
//*****************************************************************************
1200
// CONSENSUS: Coinbase output matures at 100 blocks depth.
1201
// CONSENSUS: Genesis coinbase is forever immature (exception).
1202
//*****************************************************************************
1203
bool transaction::is_coinbase_mature(size_t coinbase_height,
3✔
1204
    size_t height) NOEXCEPT
1205
{
1206
    return !is_zero(coinbase_height) &&
5✔
1207
        ceilinged_add(coinbase_height, coinbase_maturity) <= height;
3✔
1208
}
1209

1210
bool transaction::is_immature(size_t height) const NOEXCEPT
6✔
1211
{
1212
    BC_ASSERT(!is_coinbase());
6✔
1213

1214
    // Spends internal to a block are handled by block validation.
1215
    const auto mature = [=](const auto& input) NOEXCEPT
5✔
1216
    {
1217
        return input->metadata.coinbase ?
5✔
1218
            is_coinbase_mature(input->metadata.height, height) :
3✔
1219
            is_non_coinbase_mature(input->metadata.height, height);
2✔
1220
    };
6✔
1221

1222
    return !std::all_of(inputs_->begin(), inputs_->end(), mature);
6✔
1223
}
1224

1225
bool transaction::is_locked(size_t height,
4✔
1226
    uint32_t median_time_past) const NOEXCEPT
1227
{
1228
    // BIP68: not applied to the sequence of the input of a coinbase.
1229
    BC_ASSERT(!is_coinbase());
4✔
1230

1231
    // BIP68: applied to txs with a version greater than or equal to two.
1232
    if (version_ < relative_locktime_min_version)
4✔
1233
        return false;
1234

1235
    // BIP68: references to median time past are as defined by bip113.
1236
    const auto locked = [=](const auto& input) NOEXCEPT
2✔
1237
    {
1238
        return input->is_locked(height, median_time_past);
2✔
1239
    };
2✔
1240

1241
    // BIP68: when the relative lock time is block based, it is interpreted as
1242
    // a minimum block height constraint over the age of the input.
1243
    return std::any_of(inputs_->begin(), inputs_->end(), locked);
2✔
1244
}
1245

1246
// Spends internal to a block are handled by block validation.
1247
bool transaction::is_unconfirmed_spend(size_t height) const NOEXCEPT
×
1248
{
1249
    BC_ASSERT(!is_coinbase());
×
1250

1251
    // Zero is either genesis or not found.
1252
    // Test maturity first to obtain proper error code.
1253
    // Spends internal to a block are handled by block validation.
1254
    const auto unconfirmed = [=](const auto& input) NOEXCEPT
×
1255
    {
1256
        const auto prevout_height = input->metadata.height;
×
1257
        return is_zero(prevout_height) && !(height > prevout_height);
×
1258
    };
×
1259

1260
    return std::any_of(inputs_->begin(), inputs_->end(), unconfirmed);
×
1261
}
1262

1263
bool transaction::is_confirmed_double_spend(size_t height) const NOEXCEPT
4✔
1264
{
1265
    BC_ASSERT(!is_coinbase());
4✔
1266

1267
    // Spends internal to a block are handled by block validation.
1268
    const auto spent = [=](const auto& input) NOEXCEPT
4✔
1269
    {
1270
        return input->metadata.spent && height > input->metadata.height;
4✔
1271
    };
4✔
1272

1273
    return std::any_of(inputs_->begin(), inputs_->end(), spent);
4✔
1274
}
1275

1276
// Guards (for tx pool without compact blocks).
1277
// ----------------------------------------------------------------------------
1278

1279
// Pools do not have coinbases.
1280
// Redundant with block is_internal_double_spend check.
1281
// Redundant with block max_block_size check.
1282
code transaction::guard_check() const NOEXCEPT
×
1283
{
1284
    if (is_coinbase())
×
1285
        return error::coinbase_transaction;
×
1286
    if (is_internal_double_spend())
×
1287
        return error::transaction_internal_double_spend;
×
1288
    if (is_oversized())
×
1289
        return error::transaction_size_limit;
×
1290

1291
    return error::transaction_success;
×
1292
}
1293

1294
// Redundant with block max_block_weight accept.
1295
code transaction::guard_check(const context& ctx) const NOEXCEPT
×
1296
{
1297
    const auto bip141 = ctx.is_enabled(flags::bip141_rule);
×
1298

1299
     if (!bip141 && is_segregated())
×
1300
        return error::unexpected_witness_transaction;
×
1301
    if (bip141 && is_overweight())
×
1302
        return error::transaction_weight_limit;
×
1303

1304
    return error::transaction_success;
×
1305
}
1306

1307
// Redundant with block max_block_sigops accept.
1308
code transaction::guard_accept(const context& ctx) const NOEXCEPT
×
1309
{
1310
    const auto bip16 = ctx.is_enabled(flags::bip16_rule);
×
1311
    const auto bip141 = ctx.is_enabled(flags::bip141_rule);
×
1312

1313
    if (is_missing_prevouts())
×
1314
        return error::missing_previous_output;
×
1315
    if (is_signature_operations_limit(bip16, bip141))
×
1316
        return error::transaction_sigop_limit;
×
1317

1318
    return error::transaction_success;
×
1319
}
1320

1321
// Validation.
1322
// ----------------------------------------------------------------------------
1323

1324
// DO invoke on coinbase.
1325
code transaction::check() const NOEXCEPT
×
1326
{
1327
    const auto coinbase = is_coinbase();
×
1328

1329
    if (is_empty())
×
1330
        return error::empty_transaction;
×
1331
    if (coinbase && is_invalid_coinbase_size())
×
1332
        return error::invalid_coinbase_script_size;
×
1333
    if (!coinbase && is_null_non_coinbase())
×
1334
        return error::previous_output_null;
×
1335

1336
    return error::transaction_success;
×
1337
}
1338

1339
// forks
1340
// height
1341
// timestamp
1342
// median_time_past
1343

1344
// DO invoke on coinbase.
1345
code transaction::check(const context& ctx) const NOEXCEPT
×
1346
{
1347
    const auto bip113 = ctx.is_enabled(bip113_rule);
×
1348

1349
    if (is_non_final(ctx.height, ctx.timestamp, ctx.median_time_past, bip113))
×
1350
        return error::transaction_non_final;
×
1351

1352
    return error::transaction_success;
×
1353
}
1354

1355
// Do not need to invoke on coinbase.
1356
// This assumes that prevout caching is completed on all inputs.
1357
code transaction::accept(const context&) const NOEXCEPT
×
1358
{
1359
    ////BC_ASSERT(!is_coinbase());
1360

1361
    if (is_coinbase())
×
1362
        return error::transaction_success;
×
1363
    if (is_missing_prevouts())
×
1364
        return error::missing_previous_output;
×
1365
    if (is_overspent())
×
1366
        return error::spend_exceeds_value;
×
1367

1368
    return error::transaction_success;
×
1369
}
1370

1371
// forks
1372
// height
1373
// median_time_past
1374

1375
// Do not need to invoke on coinbase.
1376
// Node performs these checks through database query.
1377
// This assumes that prevout and metadata caching are completed on all inputs.
1378
code transaction::confirm(const context& ctx) const NOEXCEPT
×
1379
{
1380
    ////BC_ASSERT(!is_coinbase());
1381
    const auto bip68 = ctx.is_enabled(bip68_rule);
×
1382

1383
    if (is_coinbase())
×
1384
        return error::transaction_success;
×
1385
    if (bip68 && is_locked(ctx.height, ctx.median_time_past))
×
1386
        return error::relative_time_locked;
×
1387
    if (is_immature(ctx.height))
×
1388
        return error::coinbase_maturity;
×
1389
    if (is_unconfirmed_spend(ctx.height))
×
1390
        return error::unconfirmed_spend;
×
1391
    if (is_confirmed_double_spend(ctx.height))
×
1392
        return error::confirmed_double_spend;
×
1393

1394
    return error::transaction_success;
×
1395
}
1396

1397
// Connect (contextual).
1398
// ----------------------------------------------------------------------------
1399

1400
// forks
1401

1402
// Do not need to invoke on coinbase.
1403
code transaction::connect(const context& ctx) const NOEXCEPT
2✔
1404
{
1405
    ////BC_ASSERT(!is_coinbase());
1406

1407
    if (is_coinbase())
2✔
1408
        return error::transaction_success;
×
1409

1410
    code ec{};
2✔
1411
    using namespace machine;
2✔
1412
    initialize_sighash_cache();
2✔
1413

1414
    // Validate scripts.
1415
    for (auto input = inputs_->begin(); input != inputs_->end(); ++input)
6✔
1416
    {
1417
        // Evaluate rolling scripts with linear search but constant erase.
1418
        // Evaluate non-rolling scripts with constant search but linear erase.
1419
        if ((ec = (*input)->is_roller() ?
8✔
1420
            interpreter<linked_stack>::connect(ctx, *this, input) :
×
1421
            interpreter<contiguous_stack>::connect(ctx, *this, input)))
4✔
1422
            return ec;
×
1423
    }
1424

1425
    // TODO: accumulate sigops from each connect result and add coinbase.
1426
    // TODO: return in override with out parameter. more impactful with segwit.
1427
    return error::transaction_success;
2✔
1428
}
1429

1430
BC_POP_WARNING()
1431

1432
// JSON value convertors.
1433
// ----------------------------------------------------------------------------
1434

1435
namespace json = boost::json;
1436

1437
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
1438
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
1439

1440
transaction tag_invoke(json::value_to_tag<transaction>,
2✔
1441
    const json::value& value) NOEXCEPT
1442
{
1443
    return
2✔
1444
    {
1445
        value.at("version").to_number<uint32_t>(),
2✔
1446
        json::value_to<chain::inputs>(value.at("inputs")),
2✔
1447
        json::value_to<chain::outputs>(value.at("outputs")),
4✔
1448
        value.at("locktime").to_number<uint32_t>()
4✔
1449
    };
4✔
1450
}
1451

1452
void tag_invoke(json::value_from_tag, json::value& value,
4✔
1453
    const transaction& tx) NOEXCEPT
1454
{
1455
    value =
4✔
1456
    {
1457
        { "version", tx.version() },
1458
        { "inputs", *tx.inputs_ptr() },
1459
        { "outputs", *tx.outputs_ptr() },
1460
        { "locktime", tx.locktime() }
1461
    };
4✔
1462
}
4✔
1463

1464
BC_POP_WARNING()
1465

1466
transaction::cptr tag_invoke(json::value_to_tag<transaction::cptr>,
×
1467
    const json::value& value) NOEXCEPT
1468
{
1469
    return to_shared(tag_invoke(json::value_to_tag<transaction>{}, value));
×
1470
}
1471

1472
// Shared pointer overload is required for navigation.
1473
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
1474
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
1475

1476
void tag_invoke(json::value_from_tag tag, json::value& value,
2✔
1477
    const transaction::cptr& tx) NOEXCEPT
1478
{
1479
    tag_invoke(tag, value, *tx);
2✔
1480
}
2✔
1481

1482
BC_POP_WARNING()
1483
BC_POP_WARNING()
1484

1485
} // namespace chain
1486
} // namespace system
1487
} // 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