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

libbitcoin / libbitcoin-system / 9324917697

31 May 2024 10:10PM UTC coverage: 82.819% (+0.09%) from 82.732%
9324917697

Pull #1469

github

web-flow
Merge 0155ccfba into 434772ab9
Pull Request #1469: Optimize size computations, use ceilinged_add, style.

71 of 85 new or added lines in 7 files covered. (83.53%)

7 existing lines in 2 files now uncovered.

9848 of 11891 relevant lines covered (82.82%)

4796079.56 hits per line

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

75.81
/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,191✔
83
{
84
}
2,191✔
85

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

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

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

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

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

118
transaction::transaction(uint32_t version, chain::inputs&& inputs,
814✔
119
    chain::outputs&& outputs, uint32_t locktime) NOEXCEPT
814✔
120
  : transaction(version, to_shareds(std::move(inputs)),
1,628✔
121
      to_shareds(std::move(outputs)), locktime)
3,256✔
122
{
123
}
814✔
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,
814✔
133
    const chain::outputs_cptr& outputs, uint32_t locktime) NOEXCEPT
814✔
134
  : transaction(version, inputs, outputs, locktime, segregated(*inputs), true)
814✔
135
{
136
}
814✔
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
119✔
169
  : transaction(from_data(source, witness))
119✔
170
{
171
}
119✔
172

173
// protected
174
transaction::transaction(uint32_t version,
2,074✔
175
    const chain::inputs_cptr& inputs, const chain::outputs_cptr& outputs,
176
    uint32_t locktime, bool segregated, bool valid) NOEXCEPT
2,074✔
177
  : version_(version),
2,074✔
178
    inputs_(inputs ? inputs : to_shared<input_cptrs>()),
4,148✔
179
    outputs_(outputs ? outputs : to_shared<output_cptrs>()),
2,074✔
180
    locktime_(locktime),
2,074✔
181
    segregated_(segregated),
2,074✔
182
    valid_(valid),
2,074✔
183
    size_(serialized_size(*inputs, *outputs, segregated))
4,148✔
184
{
185
}
2,074✔
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_;
×
NEW
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
NEW
211
        nominal_hash_.reset();
×
212

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

218
    if (other.sighash_cache_)
×
219
        sighash_cache_ = to_unique(*other.sighash_cache_);
×
220
    else
NEW
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
344✔
248
{
249
    auto puts = to_shared<std::vector<std::shared_ptr<const Put>>>();
250
    const auto capacity = source.read_size(max_block_size);
344✔
251

252
    puts->reserve(capacity);
344✔
253
    for (auto put = zero; put < capacity; ++put)
810✔
254
    {
255
        BC_PUSH_WARNING(NO_NEW_OR_DELETE)
256
        puts->emplace_back(new Put{ source });
466✔
257
        BC_POP_WARNING()
258
    }
259

260
    // This is a pointer copy (non-const to const).
261
    return puts;
344✔
262
}
263

264
// static/private
265
transaction transaction::from_data(reader& source, bool witness) NOEXCEPT
166✔
266
{
267
    const auto version = source.read_4_bytes_little_endian();
166✔
268

269
    // Inputs must be non-const so that they may assign the witness.
270
    auto inputs = read_puts<input>(source);
166✔
271
    chain::outputs_cptr outputs;
166✔
272

273
    // Expensive repeated recomputation, so cache segregated state.
274
    const auto segregated = inputs->size() == witness_marker &&
178✔
275
        source.peek_byte() == witness_enabled;
12✔
276

277
    // Detect witness as no inputs (marker) and expected flag (bip144).
278
    if (segregated)
166✔
279
    {
280
        // Skip over the peeked witness flag.
281
        source.skip_byte();
12✔
282

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

287
        // Read or skip witnesses as specified.
288
        for (auto& input: *inputs)
28✔
289
        {
290
            if (witness)
16✔
291
            {
292
                // Safe to cast as this method exclusively owns the input.
293
                const_cast<chain::input*>(input.get())->set_witness(source);
16✔
294
            }
295
            else
296
            {
297
                witness::skip(source, true);
×
298
            }
299
        }
300
    }
301
    else
302
    {
303
        // Default witness is populated on input construct.
304
        outputs = read_puts<const output>(source);
308✔
305
    }
306

307
    const auto locktime = source.read_4_bytes_little_endian();
166✔
308
    return { version, inputs, outputs, locktime, segregated, source };
166✔
309
}
310

311
// Serialization.
312
// ----------------------------------------------------------------------------
313

314
// Transactions with empty witnesses always use old serialization (bip144).
315
// If no inputs are witness programs then witness hash is tx hash (bip141).
316
data_chunk transaction::to_data(bool witness) const NOEXCEPT
10✔
317
{
318
    witness &= segregated_;
10✔
319

320
    data_chunk data(serialized_size(witness));
10✔
321
    stream::out::copy ostream(data);
10✔
322
    to_data(ostream, witness);
10✔
323
    return data;
20✔
324
}
10✔
325

326
void transaction::to_data(std::ostream& stream, bool witness) const NOEXCEPT
11✔
327
{
328
    witness &= segregated_;
11✔
329

330
    write::bytes::ostream out(stream);
11✔
331
    to_data(out, witness);
11✔
332
}
11✔
333

334
void transaction::to_data(writer& sink, bool witness) const NOEXCEPT
963✔
335
{
336
    witness &= segregated_;
963✔
337

338
    sink.write_4_bytes_little_endian(version_);
963✔
339

340
    if (witness)
963✔
341
    {
342
        sink.write_byte(witness_marker);
×
343
        sink.write_byte(witness_enabled);
×
344
    }
345

346
    sink.write_variable(inputs_->size());
963✔
347
    for (const auto& input: *inputs_)
2,344✔
348
        input->to_data(sink);
1,381✔
349

350
    sink.write_variable(outputs_->size());
963✔
351
    for (const auto& output: *outputs_)
2,625✔
352
        output->to_data(sink);
1,662✔
353

354
    if (witness)
963✔
355
        for (auto& input: *inputs_)
×
356
            input->witness().to_data(sink, true);
×
357

358
    sink.write_4_bytes_little_endian(locktime_);
963✔
359
}
963✔
360

361
// static/private
362
transaction::sizes transaction::serialized_size(
2,074✔
363
    const chain::input_cptrs& inputs,
364
    const chain::output_cptrs& outputs, bool segregated) NOEXCEPT
365
{
366
    sizes size{ zero, zero };
2,074✔
367

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

388
    const auto outs = [](size_t total, const auto& output) NOEXCEPT
566✔
389
    {
390
        return ceilinged_add(total, output->serialized_size());
566✔
391
    };
392

393
    constexpr auto base_const_size = ceilinged_add(
2,074✔
394
        sizeof(version_),
395
        sizeof(locktime_));
396

397
    constexpr auto witness_const_size = ceilinged_add(
2,074✔
398
        sizeof(witness_marker),
399
        sizeof(witness_enabled));
400

401
    const auto base_size = ceilinged_add(ceilinged_add(ceilinged_add(
2,074✔
402
        base_const_size,
403
        variable_size(inputs.size())),
404
        variable_size(outputs.size())),
405
        std::accumulate(outputs.begin(), outputs.end(), zero, outs));
406

407
    const auto nominal_size = ceilinged_add(
2,074✔
408
        base_size,
409
        size.nominal);
410

411
    const auto witnessed_size = ceilinged_add(ceilinged_add(
2,074✔
412
        base_size,
413
        witness_const_size),
414
        size.witnessed);
415

416
    return { nominal_size, witnessed_size };
2,074✔
417
}
418

419
size_t transaction::serialized_size(bool witness) const NOEXCEPT
531✔
420
{
421
    witness &= segregated_;
531✔
422

423
    return witness ? size_.witnessed : size_.nominal;
531✔
424
}
425

426
// Properties.
427
// ----------------------------------------------------------------------------
428

429
bool transaction::is_valid() const NOEXCEPT
775✔
430
{
431
    return valid_;
775✔
432
}
433

434
size_t transaction::inputs() const NOEXCEPT
1,563✔
435
{
436
    return inputs_->size();
1,563✔
437
}
438

439
size_t transaction::outputs() const NOEXCEPT
1✔
440
{
441
    return outputs_->size();
1✔
442
}
443

444
uint32_t transaction::version() const NOEXCEPT
6✔
445
{
446
    return version_;
4✔
447
}
448

449
uint32_t transaction::locktime() const NOEXCEPT
15✔
450
{
451
    return locktime_;
4✔
452
}
453

454
const inputs_cptr& transaction::inputs_ptr() const NOEXCEPT
2,436✔
455
{
456
    return inputs_;
2,436✔
457
}
458

459
const outputs_cptr& transaction::outputs_ptr() const NOEXCEPT
62✔
460
{
461
    return outputs_;
62✔
462
}
463

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

471
void transaction::set_nominal_hash(hash_digest&& hash) const NOEXCEPT
7✔
472
{
473
    nominal_hash_ = to_unique(std::move(hash));
14✔
474
}
7✔
475

476
void transaction::set_witness_hash(hash_digest&& hash) const NOEXCEPT
2✔
477
{
478
    witness_hash_ = to_unique(std::move(hash));
4✔
479
}
2✔
480

481
const hash_digest& transaction::get_hash(bool witness) const NOEXCEPT
11✔
482
{
483
    if (witness)
11✔
484
    {
485
        if (!witness_hash_) set_witness_hash(hash(witness));
3✔
486
        return *witness_hash_;
3✔
487
    }
488
    else
489
    {
490
        if (!nominal_hash_) set_nominal_hash(hash(witness));
8✔
491
        return *nominal_hash_;
8✔
492
    }
493
}
494

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

515
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
516
    hash_digest digest;
925✔
517
    BC_POP_WARNING()
518

519
    stream::out::fast stream{ digest };
925✔
520
    hash::sha256x2::fast sink{ stream };
925✔
521
    to_data(sink, witness);
925✔
522
    sink.flush();
925✔
523
    return digest;
925✔
524
}
925✔
525

526
// Methods.
527
// ----------------------------------------------------------------------------
528

529
bool transaction::is_dusty(uint64_t minimum_output_value) const NOEXCEPT
6✔
530
{
531
    const auto dusty = [=](const auto& output) NOEXCEPT
9✔
532
    {
533
        return output->is_dust(minimum_output_value);
9✔
534
    };
6✔
535

536
    return std::any_of(outputs_->begin(), outputs_->end(), dusty);
6✔
537
}
538

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

547
    const auto out = [=](size_t total, const auto& output) NOEXCEPT
×
548
    {
549
        return ceilinged_add(total, output->signature_operations(bip141));
×
550
    };
1✔
551

552
    // Overflow returns max_size_t.
553
    return ceilinged_add(
1✔
554
        std::accumulate(inputs_->begin(), inputs_->end(), zero, in),
555
        std::accumulate(outputs_->begin(), outputs_->end(), zero, out));
1✔
556
}
557

558
chain::points transaction::points() const NOEXCEPT
4✔
559
{
560
    chain::points out(inputs_->size());
4✔
561

562
    const auto point = [](const auto& input) NOEXCEPT
8✔
563
    {
564
        return input->point();
8✔
565
    };
566

567
    std::transform(inputs_->begin(), inputs_->end(), out.begin(), point);
4✔
568
    return out;
4✔
569
}
570

571
hash_digest transaction::outputs_hash() const NOEXCEPT
8✔
572
{
573
    if (sighash_cache_)
8✔
574
        return sighash_cache_->outputs;
×
575

576
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
577
    hash_digest digest;
8✔
578
    BC_POP_WARNING()
579
        
580
    stream::out::fast stream{ digest };
8✔
581
    hash::sha256x2::fast sink{ stream };
8✔
582

583
    const auto& outs = *outputs_;
8✔
584
    for (const auto& output: outs)
22✔
585
        output->to_data(sink);
14✔
586

587
    sink.flush();
8✔
588
    return digest;
8✔
589
}
8✔
590

591
hash_digest transaction::points_hash() const NOEXCEPT
11✔
592
{
593
    if (sighash_cache_)
11✔
594
        return sighash_cache_->points;
×
595

596
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
597
    hash_digest digest;
11✔
598
    BC_POP_WARNING()
599

600
    stream::out::fast stream{ digest };
11✔
601
    hash::sha256x2::fast sink{ stream };
11✔
602

603
    const auto& ins = *inputs_;
11✔
604
    for (const auto& input: ins)
27✔
605
        input->point().to_data(sink);
16✔
606

607
    sink.flush();
11✔
608
    return digest;
11✔
609
}
11✔
610

611
hash_digest transaction::sequences_hash() const NOEXCEPT
7✔
612
{
613
    if (sighash_cache_)
7✔
614
        return sighash_cache_->sequences;
×
615

616
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
617
    hash_digest digest;
7✔
618
    BC_POP_WARNING()
619

620
    stream::out::fast stream{ digest };
7✔
621
    hash::sha256x2::fast sink{ stream };
7✔
622

623
    const auto& ins = *inputs_;
7✔
624
    for (const auto& input: ins)
17✔
625
        sink.write_4_bytes_little_endian(input->sequence());
10✔
626

627
    sink.flush();
7✔
628
    return digest;
7✔
629
}
7✔
630

631
// Signing (unversioned).
632
// ----------------------------------------------------------------------------
633

634
// private
635
transaction::input_iterator transaction::input_at(
4✔
636
    uint32_t index) const NOEXCEPT
637
{
638
    // Guarded by check_signature and create_endorsement.
639
    BC_ASSERT_MSG(index < inputs_->size(), "invalid input index");
4✔
640

641
    return std::next(inputs_->begin(), index);
4✔
642
}
643

644
// private
645
uint32_t transaction::input_index(const input_iterator& input) const NOEXCEPT
25✔
646
{
647
    // Guarded by unversioned_signature_hash and output_hash.
648
    BC_ASSERT_MSG(inputs_->begin() != inputs_->end(), "invalid input iterator");
25✔
649

650
    return possible_narrow_and_sign_cast<uint32_t>(
25✔
651
        std::distance(inputs_->begin(), input));
×
652
}
653

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

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

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

685
        for (in = inputs_->begin(); !anyone && in != input; ++in)
4✔
686
        {
687
            (*in)->point().to_data(sink);
×
688
            sink.write_bytes(empty_script());
×
689
            sink.write_bytes(zero_sequence());
×
690
        }
691

692
        self.point().to_data(sink);
4✔
693
        sub.to_data(sink, prefixed);
4✔
694
        sink.write_4_bytes_little_endian(self.sequence());
4✔
695

696
        for (++in; !anyone && in != inputs_->end(); ++in)
5✔
697
        {
698
            (*in)->point().to_data(sink);
1✔
699
            sink.write_bytes(empty_script());
1✔
700
            sink.write_bytes(zero_sequence());
1✔
701
        }
702
    };
4✔
703

704
    const auto write_outputs = [this, &input](writer& sink) NOEXCEPT
12✔
705
    {
706
        // Guarded by unversioned_signature_hash.
707
        const auto index = input_index(input);
4✔
708

709
        sink.write_variable(add1(index));
4✔
710

711
        for (size_t output = 0; output < index; ++output)
5✔
712
            sink.write_bytes(null_output());
1✔
713

714
        outputs_->at(index)->to_data(sink);
4✔
715
    };
8✔
716

717
    sink.write_4_bytes_little_endian(version_);
4✔
718
    write_inputs(sink);
4✔
719
    write_outputs(sink);
4✔
720
    sink.write_4_bytes_little_endian(locktime_);
4✔
721
    sink.write_4_bytes_little_endian(sighash_flags);
4✔
722
}
4✔
723

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

735
        sink.write_variable(anyone ? one : inputs_->size());
×
736

737
        for (in = inputs_->begin(); !anyone && in != input; ++in)
×
738
        {
739
            (*in)->point().to_data(sink);
×
740
            sink.write_bytes(empty_script());
×
741
            sink.write_bytes(zero_sequence());
×
742
        }
743

744
        self.point().to_data(sink);
×
745
        sub.to_data(sink, prefixed);
×
746
        sink.write_4_bytes_little_endian(self.sequence());
×
747

748
        for (++in; !anyone && in != inputs_->end(); ++in)
×
749
        {
750
            (*in)->point().to_data(sink);
×
751
            sink.write_bytes(empty_script());
×
752
            sink.write_bytes(zero_sequence());
×
753
        }
754
    };
×
755

756
    sink.write_4_bytes_little_endian(version_);
×
757
    write_inputs(sink);
×
758
    sink.write_variable(zero);
×
759
    sink.write_4_bytes_little_endian(locktime_);
×
760
    sink.write_4_bytes_little_endian(sighash_flags);
×
761
}
×
762

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

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

776
        for (in = inputs_->begin(); !anyone && in != input; ++in)
15✔
777
        {
778
            (*in)->point().to_data(sink);
3✔
779
            sink.write_bytes(empty_script());
3✔
780
            sink.write_4_bytes_little_endian((*in)->sequence());
3✔
781
        }
782

783
        self.point().to_data(sink);
12✔
784
        sub.to_data(sink, prefixed);
12✔
785
        sink.write_4_bytes_little_endian(self.sequence());
12✔
786

787
        for (++in; !anyone && in != inputs_->end(); ++in)
16✔
788
        {
789
            (*in)->point().to_data(sink);
4✔
790
            sink.write_bytes(empty_script());
4✔
791
            sink.write_4_bytes_little_endian((*in)->sequence());
4✔
792
        }
793
    };
12✔
794

795
    const auto write_outputs = [this](writer& sink) NOEXCEPT
36✔
796
    {
797
        sink.write_variable(outputs_->size());
12✔
798
        for (const auto& output: *outputs_)
27✔
799
            output->to_data(sink);
15✔
800
    };
24✔
801

802
    sink.write_4_bytes_little_endian(version_);
12✔
803
    write_inputs(sink);
12✔
804
    write_outputs(sink);
12✔
805
    sink.write_4_bytes_little_endian(locktime_);
12✔
806
    sink.write_4_bytes_little_endian(flags);
12✔
807
}
12✔
808

809
// private
810
hash_digest transaction::unversioned_signature_hash(
19✔
811
    const input_iterator& input, const script& sub,
812
    uint8_t sighash_flags) const NOEXCEPT
813
{
814
    // Set options.
815
    const auto flag = mask_sighash(sighash_flags);
19✔
816

817
    // Create hash writer.
818
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
819
    hash_digest digest;
19✔
820
    BC_POP_WARNING()
821

822
    stream::out::fast stream{ digest };
19✔
823
    hash::sha256x2::fast sink{ stream };
19✔
824

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

837
            signature_hash_single(sink, input, sub, sighash_flags);
4✔
838
            break;
4✔
839
        }
840
        case coverage::hash_none:
×
841
        {
×
842
            signature_hash_none(sink, input, sub, sighash_flags);
×
843
            break;
×
844
        }
845
        default:
12✔
846
        case coverage::hash_all:
12✔
847
        {
12✔
848
            signature_hash_all(sink, input, sub, sighash_flags);
12✔
849
        }
850
    }
851

852
    sink.flush();
16✔
853
    return digest;
16✔
854
}
19✔
855

856
// Signing (version 0).
857
// ----------------------------------------------------------------------------
858

859
// private
860
// TODO: taproot requires both single and double hash of each.
861
void transaction::initialize_sighash_cache() const NOEXCEPT
2✔
862
{
863
    // This overconstructs the cache (anyone or !all), however it is simple and
864
    // the same criteria applied by satoshi.
865
    if (segregated_)
2✔
866
    {
867
        BC_PUSH_WARNING(NO_NEW_OR_DELETE)
868
        sighash_cache_.reset(new sighash_cache
2✔
869
        {
870
            outputs_hash(),
2✔
871
            points_hash(),
2✔
872
            sequences_hash()
2✔
873
        });
2✔
874
        BC_POP_WARNING()
875
    }
876
}
2✔
877

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

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

889
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
890
    hash_digest digest;
12✔
891
    BC_POP_WARNING()
892

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

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

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

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

921
    stream::out::fast stream{ digest };
22✔
922
    hash::sha256x2::fast sink{ stream };
22✔
923

924
    // Create signature hash.
925
    sink.write_little_endian(version_);
22✔
926

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

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

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

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

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

947
    sink.write_little_endian(locktime_);
22✔
948
    sink.write_4_bytes_little_endian(sighash_flags);
22✔
949

950
    sink.flush();
22✔
951
    return digest;
22✔
952
}
22✔
953

954
// Signing (unversioned and version 0).
955
// ----------------------------------------------------------------------------
956

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

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

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

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

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

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

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

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

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

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

1021
// Guard (context free).
1022
// ----------------------------------------------------------------------------
1023

1024
bool transaction::is_coinbase() const NOEXCEPT
70✔
1025
{
1026
    return inputs_->size() == one && inputs_->front()->point().is_null();
70✔
1027
}
1028

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

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

1041
// Guard (contextual).
1042
// ----------------------------------------------------------------------------
1043

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

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

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

1063
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
814✔
1064
}
1065

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

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

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

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

1096
// Check (context free).
1097
// ----------------------------------------------------------------------------
1098

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

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

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

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

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

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

1126
// Accept (contextual).
1127
// ----------------------------------------------------------------------------
1128

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

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

1141
    const auto height_time = locktime_ < locktime_threshold ? height : time;
5✔
1142

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

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

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

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

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

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

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

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

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

1189
    return claim() > value();
2✔
1190
}
1191

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1274
// Guards (for tx pool without compact blocks).
1275
// ----------------------------------------------------------------------------
1276

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

1289
    return error::transaction_success;
×
1290
}
1291

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

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

1302
    return error::transaction_success;
×
1303
}
1304

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

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

1316
    return error::transaction_success;
×
1317
}
1318

1319
// Validation.
1320
// ----------------------------------------------------------------------------
1321

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

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

1334
    return error::transaction_success;
×
1335
}
1336

1337
// forks
1338
// height
1339
// timestamp
1340
// median_time_past
1341

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

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

1350
    return error::transaction_success;
×
1351
}
1352

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

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

1366
    return error::transaction_success;
×
1367
}
1368

1369
// forks
1370
// height
1371
// median_time_past
1372

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

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

1392
    return error::transaction_success;
×
1393
}
1394

1395
// Connect (contextual).
1396
// ----------------------------------------------------------------------------
1397

1398
// forks
1399

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

1405
    if (is_coinbase())
2✔
1406
        return error::transaction_success;
×
1407

1408
    code ec{};
2✔
1409
    using namespace machine;
2✔
1410
    initialize_sighash_cache();
2✔
1411

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

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

1428
BC_POP_WARNING()
1429

1430
// JSON value convertors.
1431
// ----------------------------------------------------------------------------
1432

1433
namespace json = boost::json;
1434

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

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

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

1462
BC_POP_WARNING()
1463

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

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

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

1480
BC_POP_WARNING()
1481
BC_POP_WARNING()
1482

1483
} // namespace chain
1484
} // namespace system
1485
} // 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

© 2026 Coveralls, Inc