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

libbitcoin / libbitcoin-system / 9322277612

31 May 2024 05:52PM UTC coverage: 82.792% (+0.06%) from 82.732%
9322277612

push

github

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

Optimize size computations, use ceilinged_add, style.

58 of 69 new or added lines in 7 files covered. (84.06%)

7 existing lines in 2 files now uncovered.

9834 of 11878 relevant lines covered (82.79%)

4801329.06 hits per line

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

75.31
/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
    if (other.nominal_hash_)
1,072✔
101
        nominal_hash_ = to_unique(*other.nominal_hash_);
×
102
    if (other.witness_hash_)
1,072✔
103
        witness_hash_ = to_unique(*other.witness_hash_);
×
104
    if (other.sighash_cache_)
1,072✔
105
        sighash_cache_ = to_unique(*other.sighash_cache_);
×
106
}
1,072✔
107

108
transaction::transaction(uint32_t version, chain::inputs&& inputs,
814✔
109
    chain::outputs&& outputs, uint32_t locktime) NOEXCEPT
814✔
110
  : transaction(version, to_shareds(std::move(inputs)),
1,628✔
111
      to_shareds(std::move(outputs)), locktime, false, true)
3,256✔
112
{
113
    // Defer execution for constructor move.
114
    segregated_ = segregated(*inputs_);
814✔
115
}
814✔
116

117
transaction::transaction(uint32_t version, const chain::inputs& inputs,
1✔
118
    const chain::outputs& outputs, uint32_t locktime) NOEXCEPT
1✔
119
  : transaction(version, to_shareds(inputs), to_shareds(outputs), locktime,
2✔
120
      segregated(inputs), true)
4✔
121
{
122
}
1✔
123

124
transaction::transaction(uint32_t version, const chain::inputs_cptr& inputs,
×
125
    const chain::outputs_cptr& outputs, uint32_t locktime) NOEXCEPT
×
126
  : transaction(version, inputs, outputs, locktime, segregated(*inputs), true)
×
127
{
128
}
×
129

130
transaction::transaction(const data_slice& data, bool witness) NOEXCEPT
41✔
131
  : transaction(stream::in::copy(data), witness)
41✔
132
{
133
}
41✔
134

135
////transaction::transaction(stream::in::fast&& stream, bool witness) NOEXCEPT
136
////  : transaction(read::bytes::fast(stream), witness)
137
////{
138
////}
139

140
transaction::transaction(stream::in::fast& stream, bool witness) NOEXCEPT
2✔
141
  : transaction(read::bytes::fast(stream), witness)
2✔
142
{
143
}
2✔
144

145
transaction::transaction(std::istream&& stream, bool witness) NOEXCEPT
41✔
146
  : transaction(read::bytes::istream(stream), witness)
41✔
147
{
148
}
41✔
149

150
transaction::transaction(std::istream& stream, bool witness) NOEXCEPT
4✔
151
  : transaction(read::bytes::istream(stream), witness)
4✔
152
{
153
}
4✔
154

155
transaction::transaction(reader&& source, bool witness) NOEXCEPT
47✔
156
  : transaction(from_data(source, witness))
47✔
157
{
158
}
47✔
159

160
transaction::transaction(reader& source, bool witness) NOEXCEPT
119✔
161
  : transaction(from_data(source, witness))
119✔
162
{
163
}
119✔
164

165
// protected
166
transaction::transaction(uint32_t version,
2,074✔
167
    const chain::inputs_cptr& inputs, const chain::outputs_cptr& outputs,
168
    uint32_t locktime, bool segregated, bool valid) NOEXCEPT
2,074✔
169
  : version_(version),
2,074✔
170
    inputs_(inputs ? inputs : to_shared<input_cptrs>()),
4,148✔
171
    outputs_(outputs ? outputs : to_shared<output_cptrs>()),
2,074✔
172
    locktime_(locktime),
2,074✔
173
    segregated_(segregated),
2,074✔
174
    valid_(valid),
2,074✔
175
    size_(serialized_size(*inputs, *outputs))
4,148✔
176
{
177
}
2,074✔
178

179
// Operators.
180
// ----------------------------------------------------------------------------
181

182
transaction& transaction::operator=(transaction&& other) NOEXCEPT
×
183
{
184
    *this = other;
×
185
    return *this;
×
186
}
187

188
transaction& transaction::operator=(const transaction& other) NOEXCEPT
×
189
{
190
    version_ = other.version_;
×
191
    inputs_ = other.inputs_;
×
192
    outputs_ = other.outputs_;
×
193
    locktime_ = other.locktime_;
×
194
    segregated_ = other.segregated_;
×
195
    valid_ = other.valid_;
×
NEW
196
    size_ = other.size_;
×
197

198
    if (other.nominal_hash_)
×
199
        nominal_hash_ = to_unique(*other.nominal_hash_);
×
200
    if (other.witness_hash_)
×
201
        witness_hash_ = to_unique(*other.witness_hash_);
×
202
    if (other.sighash_cache_)
×
203
        sighash_cache_ = to_unique(*other.sighash_cache_);
×
204

205
    return *this;
×
206
}
207

208
bool transaction::operator==(const transaction& other) const NOEXCEPT
58✔
209
{
210
    // Compares input/output elements, not pointers, cache not compared.
211
    return (version_ == other.version_)
58✔
212
        && (locktime_ == other.locktime_)
56✔
213
        && ((inputs_ == other.inputs_) || 
70✔
214
            deep_equal(*inputs_, *other.inputs_))
14✔
215
        && ((outputs_ == other.outputs_) ||
128✔
216
            deep_equal(*outputs_, *other.outputs_));
14✔
217
}
218

219
bool transaction::operator!=(const transaction& other) const NOEXCEPT
2✔
220
{
221
    return !(*this == other);
2✔
222
}
223

224
// Deserialization.
225
// ----------------------------------------------------------------------------
226

227
template<class Put, class Source>
228
std::shared_ptr<const std::vector<std::shared_ptr<const Put>>>
229
read_puts(Source& source) NOEXCEPT
344✔
230
{
231
    auto puts = to_shared<std::vector<std::shared_ptr<const Put>>>();
232
    const auto capacity = source.read_size(max_block_size);
344✔
233

234
    puts->reserve(capacity);
344✔
235
    for (auto put = zero; put < capacity; ++put)
810✔
236
    {
237
        BC_PUSH_WARNING(NO_NEW_OR_DELETE)
238
        puts->emplace_back(new Put{ source });
466✔
239
        BC_POP_WARNING()
240
    }
241

242
    // This is a pointer copy (non-const to const).
243
    return puts;
344✔
244
}
245

246
// static/private
247
transaction transaction::from_data(reader& source, bool witness) NOEXCEPT
166✔
248
{
249
    const auto version = source.read_4_bytes_little_endian();
166✔
250

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

255
    // Expensive repeated recomputation, so cache segregated state.
256
    const auto segregated = inputs->size() == witness_marker &&
178✔
257
        source.peek_byte() == witness_enabled;
12✔
258

259
    // Detect witness as no inputs (marker) and expected flag (bip144).
260
    if (segregated)
166✔
261
    {
262
        // Skip over the peeked witness flag.
263
        source.skip_byte();
12✔
264

265
        // Inputs and outputs are constructed on a vector of const pointers.
266
        inputs = read_puts<input>(source);
12✔
267
        outputs = read_puts<output>(source);
12✔
268

269
        // Read or skip witnesses as specified.
270
        for (auto& input: *inputs)
28✔
271
        {
272
            if (witness)
16✔
273
            {
274
                // Safe to cast as this method exclusively owns the input and
275
                // input::witness_ a mutable public property of the instance.
276
                const auto setter = const_cast<chain::input*>(input.get());
16✔
277
                setter->witness_ = to_shared<chain::witness>(source, true);
32✔
278
            }
279
            else
280
            {
281
                witness::skip(source, true);
×
282
            }
283
        }
284
    }
285
    else
286
    {
287
        // Default witness is populated on input construct.
288
        outputs = read_puts<const output>(source);
308✔
289
    }
290

291
    const auto locktime = source.read_4_bytes_little_endian();
166✔
292
    return { version, inputs, outputs, locktime, segregated, source };
166✔
293
}
294

295
// Serialization.
296
// ----------------------------------------------------------------------------
297

298
// Transactions with empty witnesses always use old serialization (bip144).
299
// If no inputs are witness programs then witness hash is tx hash (bip141).
300
data_chunk transaction::to_data(bool witness) const NOEXCEPT
10✔
301
{
302
    witness &= segregated_;
10✔
303

304
    data_chunk data(serialized_size(witness));
10✔
305
    stream::out::copy ostream(data);
10✔
306
    to_data(ostream, witness);
10✔
307
    return data;
20✔
308
}
10✔
309

310
void transaction::to_data(std::ostream& stream, bool witness) const NOEXCEPT
11✔
311
{
312
    witness &= segregated_;
11✔
313

314
    write::bytes::ostream out(stream);
11✔
315
    to_data(out, witness);
11✔
316
}
11✔
317

318
void transaction::to_data(writer& sink, bool witness) const NOEXCEPT
963✔
319
{
320
    witness &= segregated_;
963✔
321

322
    sink.write_4_bytes_little_endian(version_);
963✔
323

324
    if (witness)
963✔
325
    {
326
        sink.write_byte(witness_marker);
×
327
        sink.write_byte(witness_enabled);
×
328
    }
329

330
    sink.write_variable(inputs_->size());
963✔
331
    for (const auto& input: *inputs_)
2,344✔
332
        input->to_data(sink);
1,381✔
333

334
    sink.write_variable(outputs_->size());
963✔
335
    for (const auto& output: *outputs_)
2,625✔
336
        output->to_data(sink);
1,662✔
337

338
    if (witness)
963✔
339
        for (auto& input: *inputs_)
×
340
            input->witness().to_data(sink, true);
×
341

342
    sink.write_4_bytes_little_endian(locktime_);
963✔
343
}
963✔
344

345
// static/private
346
transaction::sizes transaction::serialized_size(
2,074✔
347
    const chain::input_cptrs& inputs,
348
    const chain::output_cptrs& outputs) NOEXCEPT
349
{
350
    sizes size{};
2,074✔
351
    std::for_each(inputs.begin(), inputs.end(), [&](const auto& input) NOEXCEPT
4,181✔
352
    {
353
        size.nominal = ceilinged_add(size.nominal, input->nominal_size());
4,214✔
354
        size.witness = ceilinged_add(size.witness, input->witness_size());
2,107✔
355
    });
2,107✔
356

357
    const auto outs = [](size_t total, const auto& output) NOEXCEPT
566✔
358
    {
359
        return ceilinged_add(total, output->serialized_size());
566✔
360
    };
361

362
    constexpr auto const_size = ceilinged_add(
2,074✔
363
        sizeof(version_),
364
        sizeof(locktime_));
365

366
    const auto nominal_size =
2,074✔
367
        ceilinged_add(ceilinged_add(ceilinged_add(ceilinged_add(
2,074✔
368
            const_size,
369
            variable_size(inputs.size())),
370
            size.nominal),
371
            variable_size(outputs.size())),
372
            std::accumulate(outputs.begin(), outputs.end(), zero, outs));
373

374
    const auto witness_size = ceilinged_add(
2,074✔
375
        nominal_size,
376
        size.witness);
377

378
    return { nominal_size, witness_size };
2,074✔
379
}
380

381
size_t transaction::serialized_size(bool witness) const NOEXCEPT
531✔
382
{
383
    witness &= segregated_;
531✔
384

385
    return witness ? size_.witness : size_.nominal;
531✔
386
}
387

388
// Properties.
389
// ----------------------------------------------------------------------------
390

391
bool transaction::is_valid() const NOEXCEPT
775✔
392
{
393
    return valid_;
775✔
394
}
395

396
size_t transaction::inputs() const NOEXCEPT
1,563✔
397
{
398
    return inputs_->size();
1,563✔
399
}
400

401
size_t transaction::outputs() const NOEXCEPT
1✔
402
{
403
    return outputs_->size();
1✔
404
}
405

406
uint32_t transaction::version() const NOEXCEPT
6✔
407
{
408
    return version_;
4✔
409
}
410

411
uint32_t transaction::locktime() const NOEXCEPT
15✔
412
{
413
    return locktime_;
4✔
414
}
415

416
const inputs_cptr& transaction::inputs_ptr() const NOEXCEPT
2,436✔
417
{
418
    return inputs_;
2,436✔
419
}
420

421
const outputs_cptr& transaction::outputs_ptr() const NOEXCEPT
62✔
422
{
423
    return outputs_;
62✔
424
}
425

426
uint64_t transaction::fee() const NOEXCEPT
4✔
427
{
428
    // Underflow returns zero (and is_overspent() will be true).
429
    // This is value of prevouts spent by inputs minus that claimed by outputs.
430
    return floored_subtract(value(), claim());
4✔
431
}
432

433
void transaction::set_nominal_hash(hash_digest&& hash) const NOEXCEPT
7✔
434
{
435
    nominal_hash_ = to_unique(std::move(hash));
14✔
436
}
7✔
437

438
void transaction::set_witness_hash(hash_digest&& hash) const NOEXCEPT
2✔
439
{
440
    witness_hash_ = to_unique(std::move(hash));
4✔
441
}
2✔
442

443
const hash_digest& transaction::get_hash(bool witness) const NOEXCEPT
11✔
444
{
445
    if (witness)
11✔
446
    {
447
        if (!witness_hash_) set_witness_hash(hash(witness));
3✔
448
        return *witness_hash_;
3✔
449
    }
450
    else
451
    {
452
        if (!nominal_hash_) set_nominal_hash(hash(witness));
8✔
453
        return *nominal_hash_;
8✔
454
    }
455
}
456

457
hash_digest transaction::hash(bool witness) const NOEXCEPT
930✔
458
{
459
    if (segregated_)
930✔
460
    {
461
        if (witness)
18✔
462
        {
463
            // Witness coinbase tx hash is assumed to be null_hash (bip141).
464
            if (witness_hash_) return *witness_hash_;
×
465
            if (is_coinbase()) return null_hash;
×
466
        }
467
        else
468
        {
469
            if (nominal_hash_) return *nominal_hash_;
18✔
470
        }
471
    }
472
    else
473
    {
474
        if (nominal_hash_) return *nominal_hash_;
912✔
475
    }
476

477
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
478
    hash_digest digest;
925✔
479
    BC_POP_WARNING()
480

481
    stream::out::fast stream{ digest };
925✔
482
    hash::sha256x2::fast sink{ stream };
925✔
483
    to_data(sink, witness);
925✔
484
    sink.flush();
925✔
485
    return digest;
925✔
486
}
925✔
487

488
// Methods.
489
// ----------------------------------------------------------------------------
490

491
bool transaction::is_dusty(uint64_t minimum_output_value) const NOEXCEPT
6✔
492
{
493
    const auto dusty = [=](const auto& output) NOEXCEPT
9✔
494
    {
495
        return output->is_dust(minimum_output_value);
9✔
496
    };
6✔
497

498
    return std::any_of(outputs_->begin(), outputs_->end(), dusty);
6✔
499
}
500

501
size_t transaction::signature_operations(bool bip16, bool bip141) const NOEXCEPT
1✔
502
{
503
    // Includes BIP16 p2sh additional sigops, max_size_t if prevout invalid.
504
    const auto in = [=](size_t total, const auto& input) NOEXCEPT
×
505
    {
506
        return ceilinged_add(total, input->signature_operations(bip16, bip141));
×
507
    };
1✔
508

509
    const auto out = [=](size_t total, const auto& output) NOEXCEPT
×
510
    {
511
        return ceilinged_add(total, output->signature_operations(bip141));
×
512
    };
1✔
513

514
    // Overflow returns max_size_t.
515
    return ceilinged_add(
1✔
516
        std::accumulate(inputs_->begin(), inputs_->end(), zero, in),
517
        std::accumulate(outputs_->begin(), outputs_->end(), zero, out));
1✔
518
}
519

520
chain::points transaction::points() const NOEXCEPT
4✔
521
{
522
    chain::points out(inputs_->size());
4✔
523

524
    const auto point = [](const auto& input) NOEXCEPT
8✔
525
    {
526
        return input->point();
8✔
527
    };
528

529
    std::transform(inputs_->begin(), inputs_->end(), out.begin(), point);
4✔
530
    return out;
4✔
531
}
532

533
hash_digest transaction::outputs_hash() const NOEXCEPT
8✔
534
{
535
    if (sighash_cache_)
8✔
536
        return sighash_cache_->outputs;
×
537

538
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
539
    hash_digest digest;
8✔
540
    BC_POP_WARNING()
541
        
542
    stream::out::fast stream{ digest };
8✔
543
    hash::sha256x2::fast sink{ stream };
8✔
544

545
    const auto& outs = *outputs_;
8✔
546
    for (const auto& output: outs)
22✔
547
        output->to_data(sink);
14✔
548

549
    sink.flush();
8✔
550
    return digest;
8✔
551
}
8✔
552

553
hash_digest transaction::points_hash() const NOEXCEPT
11✔
554
{
555
    if (sighash_cache_)
11✔
556
        return sighash_cache_->points;
×
557

558
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
559
    hash_digest digest;
11✔
560
    BC_POP_WARNING()
561

562
    stream::out::fast stream{ digest };
11✔
563
    hash::sha256x2::fast sink{ stream };
11✔
564

565
    const auto& ins = *inputs_;
11✔
566
    for (const auto& input: ins)
27✔
567
        input->point().to_data(sink);
16✔
568

569
    sink.flush();
11✔
570
    return digest;
11✔
571
}
11✔
572

573
hash_digest transaction::sequences_hash() const NOEXCEPT
7✔
574
{
575
    if (sighash_cache_)
7✔
576
        return sighash_cache_->sequences;
×
577

578
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
579
    hash_digest digest;
7✔
580
    BC_POP_WARNING()
581

582
    stream::out::fast stream{ digest };
7✔
583
    hash::sha256x2::fast sink{ stream };
7✔
584

585
    const auto& ins = *inputs_;
7✔
586
    for (const auto& input: ins)
17✔
587
        sink.write_4_bytes_little_endian(input->sequence());
10✔
588

589
    sink.flush();
7✔
590
    return digest;
7✔
591
}
7✔
592

593
// Signing (unversioned).
594
// ----------------------------------------------------------------------------
595

596
// private
597
transaction::input_iterator transaction::input_at(
4✔
598
    uint32_t index) const NOEXCEPT
599
{
600
    // Guarded by check_signature and create_endorsement.
601
    BC_ASSERT_MSG(index < inputs_->size(), "invalid input index");
4✔
602

603
    return std::next(inputs_->begin(), index);
4✔
604
}
605

606
// private
607
uint32_t transaction::input_index(const input_iterator& input) const NOEXCEPT
25✔
608
{
609
    // Guarded by unversioned_signature_hash and output_hash.
610
    BC_ASSERT_MSG(inputs_->begin() != inputs_->end(), "invalid input iterator");
25✔
611

612
    return possible_narrow_and_sign_cast<uint32_t>(
25✔
613
        std::distance(inputs_->begin(), input));
×
614
}
615

616
//*****************************************************************************
617
// CONSENSUS: Due to masking of bits 6/7 (8 is the anyone_can_pay flag),
618
// there are 4 possible 7 bit values that can set "single" and 4 others that
619
// can set none, and yet all other values set "all".
620
//*****************************************************************************
621
inline coverage mask_sighash(uint8_t sighash_flags) NOEXCEPT
41✔
622
{
623
    switch (sighash_flags & coverage::mask)
41✔
624
    {
625
        case coverage::hash_single:
626
            return coverage::hash_single;
627
        case coverage::hash_none:
2✔
628
            return coverage::hash_none;
2✔
629
        default:
18✔
630
            return coverage::hash_all;
18✔
631
    }
632
}
633

634
void transaction::signature_hash_single(writer& sink,
4✔
635
    const input_iterator& input, const script& sub,
636
    uint8_t sighash_flags) const NOEXCEPT
637
{
638
    const auto write_inputs = [this, &input, &sub, sighash_flags](
8✔
639
        writer& sink) NOEXCEPT
4✔
640
    {
641
        const auto& self = **input;
4✔
642
        const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
4✔
643
        input_cptrs::const_iterator in;
4✔
644

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

647
        for (in = inputs_->begin(); !anyone && in != input; ++in)
4✔
648
        {
649
            (*in)->point().to_data(sink);
×
650
            sink.write_bytes(empty_script());
×
651
            sink.write_bytes(zero_sequence());
×
652
        }
653

654
        self.point().to_data(sink);
4✔
655
        sub.to_data(sink, prefixed);
4✔
656
        sink.write_4_bytes_little_endian(self.sequence());
4✔
657

658
        for (++in; !anyone && in != inputs_->end(); ++in)
5✔
659
        {
660
            (*in)->point().to_data(sink);
1✔
661
            sink.write_bytes(empty_script());
1✔
662
            sink.write_bytes(zero_sequence());
1✔
663
        }
664
    };
4✔
665

666
    const auto write_outputs = [this, &input](writer& sink) NOEXCEPT
12✔
667
    {
668
        // Guarded by unversioned_signature_hash.
669
        const auto index = input_index(input);
4✔
670

671
        sink.write_variable(add1(index));
4✔
672

673
        for (size_t output = 0; output < index; ++output)
5✔
674
            sink.write_bytes(null_output());
1✔
675

676
        outputs_->at(index)->to_data(sink);
4✔
677
    };
8✔
678

679
    sink.write_4_bytes_little_endian(version_);
4✔
680
    write_inputs(sink);
4✔
681
    write_outputs(sink);
4✔
682
    sink.write_4_bytes_little_endian(locktime_);
4✔
683
    sink.write_4_bytes_little_endian(sighash_flags);
4✔
684
}
4✔
685

686
void transaction::signature_hash_none(writer& sink,
×
687
    const input_iterator& input, const script& sub,
688
    uint8_t sighash_flags) const NOEXCEPT
689
{
690
    const auto write_inputs = [this, &input, &sub, sighash_flags](
×
691
        writer& sink) NOEXCEPT
×
692
    {
693
        const auto& self = **input;
×
694
        const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
×
695
        input_cptrs::const_iterator in;
×
696

697
        sink.write_variable(anyone ? one : inputs_->size());
×
698

699
        for (in = inputs_->begin(); !anyone && in != input; ++in)
×
700
        {
701
            (*in)->point().to_data(sink);
×
702
            sink.write_bytes(empty_script());
×
703
            sink.write_bytes(zero_sequence());
×
704
        }
705

706
        self.point().to_data(sink);
×
707
        sub.to_data(sink, prefixed);
×
708
        sink.write_4_bytes_little_endian(self.sequence());
×
709

710
        for (++in; !anyone && in != inputs_->end(); ++in)
×
711
        {
712
            (*in)->point().to_data(sink);
×
713
            sink.write_bytes(empty_script());
×
714
            sink.write_bytes(zero_sequence());
×
715
        }
716
    };
×
717

718
    sink.write_4_bytes_little_endian(version_);
×
719
    write_inputs(sink);
×
720
    sink.write_variable(zero);
×
721
    sink.write_4_bytes_little_endian(locktime_);
×
722
    sink.write_4_bytes_little_endian(sighash_flags);
×
723
}
×
724

725
void transaction::signature_hash_all(writer& sink,
12✔
726
    const input_iterator& input, const script& sub,
727
    uint8_t flags) const NOEXCEPT
728
{
729
    const auto write_inputs = [this, &input, &sub, flags](
24✔
730
        writer& sink) NOEXCEPT
43✔
731
    {
732
        const auto& self = **input;
12✔
733
        const auto anyone = to_bool(flags & coverage::anyone_can_pay);
12✔
734
        input_cptrs::const_iterator in;
12✔
735

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

738
        for (in = inputs_->begin(); !anyone && in != input; ++in)
15✔
739
        {
740
            (*in)->point().to_data(sink);
3✔
741
            sink.write_bytes(empty_script());
3✔
742
            sink.write_4_bytes_little_endian((*in)->sequence());
3✔
743
        }
744

745
        self.point().to_data(sink);
12✔
746
        sub.to_data(sink, prefixed);
12✔
747
        sink.write_4_bytes_little_endian(self.sequence());
12✔
748

749
        for (++in; !anyone && in != inputs_->end(); ++in)
16✔
750
        {
751
            (*in)->point().to_data(sink);
4✔
752
            sink.write_bytes(empty_script());
4✔
753
            sink.write_4_bytes_little_endian((*in)->sequence());
4✔
754
        }
755
    };
12✔
756

757
    const auto write_outputs = [this](writer& sink) NOEXCEPT
36✔
758
    {
759
        sink.write_variable(outputs_->size());
12✔
760
        for (const auto& output: *outputs_)
27✔
761
            output->to_data(sink);
15✔
762
    };
24✔
763

764
    sink.write_4_bytes_little_endian(version_);
12✔
765
    write_inputs(sink);
12✔
766
    write_outputs(sink);
12✔
767
    sink.write_4_bytes_little_endian(locktime_);
12✔
768
    sink.write_4_bytes_little_endian(flags);
12✔
769
}
12✔
770

771
// private
772
hash_digest transaction::unversioned_signature_hash(
19✔
773
    const input_iterator& input, const script& sub,
774
    uint8_t sighash_flags) const NOEXCEPT
775
{
776
    // Set options.
777
    const auto flag = mask_sighash(sighash_flags);
19✔
778

779
    // Create hash writer.
780
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
781
    hash_digest digest;
19✔
782
    BC_POP_WARNING()
783

784
    stream::out::fast stream{ digest };
19✔
785
    hash::sha256x2::fast sink{ stream };
19✔
786

787
    switch (flag)
19✔
788
    {
789
        case coverage::hash_single:
7✔
790
        {
7✔
791
            //*****************************************************************
792
            // CONSENSUS: return one_hash if index exceeds outputs in sighash.
793
            // Related Bug: bitcointalk.org/index.php?topic=260595
794
            // Exploit: joncave.co.uk/2014/08/bitcoin-sighash-single/
795
            //*****************************************************************
796
            if (input_index(input) >= outputs_->size())
7✔
797
                return one_hash;
3✔
798

799
            signature_hash_single(sink, input, sub, sighash_flags);
4✔
800
            break;
4✔
801
        }
802
        case coverage::hash_none:
×
803
        {
×
804
            signature_hash_none(sink, input, sub, sighash_flags);
×
805
            break;
×
806
        }
807
        default:
12✔
808
        case coverage::hash_all:
12✔
809
        {
12✔
810
            signature_hash_all(sink, input, sub, sighash_flags);
12✔
811
        }
812
    }
813

814
    sink.flush();
16✔
815
    return digest;
16✔
816
}
19✔
817

818
// Signing (version 0).
819
// ----------------------------------------------------------------------------
820

821
// private
822
// TODO: taproot requires both single and double hash of each.
823
void transaction::initialize_sighash_cache() const NOEXCEPT
2✔
824
{
825
    // This overconstructs the cache (anyone or !all), however it is simple and
826
    // the same criteria applied by satoshi.
827
    if (segregated_)
2✔
828
    {
829
        BC_PUSH_WARNING(NO_NEW_OR_DELETE)
830
        sighash_cache_.reset(new sighash_cache
2✔
831
        {
832
            outputs_hash(),
2✔
833
            points_hash(),
2✔
834
            sequences_hash()
2✔
835
        });
2✔
836
        BC_POP_WARNING()
837
    }
838
}
2✔
839

840
// private
841
hash_digest transaction::output_hash(const input_iterator& input) const NOEXCEPT
14✔
842
{
843
    const auto index = input_index(input);
14✔
844

845
    //*************************************************************************
846
    // CONSENSUS: if index exceeds outputs in signature hash, return null_hash.
847
    //*************************************************************************
848
    if (index >= outputs_->size())
14✔
849
        return null_hash;
2✔
850

851
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
852
    hash_digest digest;
12✔
853
    BC_POP_WARNING()
854

855
    stream::out::fast stream{ digest };
12✔
856
    hash::sha256x2::fast sink{ stream };
12✔
857
    outputs_->at(index)->to_data(sink);
12✔
858
    sink.flush();
12✔
859
    return digest;
12✔
860
}
12✔
861

862
// private
863
hash_digest transaction::version_0_signature_hash(const input_iterator& input,
29✔
864
    const script& sub, uint64_t value, uint8_t sighash_flags,
865
    bool bip143) const NOEXCEPT
866
{
867
    // bip143/v0: the way of serialization is changed.
868
    if (!bip143)
29✔
869
        return unversioned_signature_hash(input, sub, sighash_flags);
7✔
870

871
    // Set options.
872
    const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
22✔
873
    const auto flag = mask_sighash(sighash_flags);
22✔
874
    const auto all = (flag == coverage::hash_all);
22✔
875
    const auto single = (flag == coverage::hash_single);
22✔
876
    const auto& self = **input;
22✔
877

878
    // Create hash writer.
879
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
880
    hash_digest digest;
22✔
881
    BC_POP_WARNING()
882

883
    stream::out::fast stream{ digest };
22✔
884
    hash::sha256x2::fast sink{ stream };
22✔
885

886
    // Create signature hash.
887
    sink.write_little_endian(version_);
22✔
888

889
    // Conditioning points, sequences, and outputs writes on cache_ instead of
890
    // conditionally passing them from methods avoids copying the cached hash.
891

892
    // points
893
    sink.write_bytes(!anyone ? points_hash() : null_hash);
22✔
894

895
    // sequences
896
    sink.write_bytes(!anyone && all ? sequences_hash() : null_hash);
22✔
897

898
    self.point().to_data(sink);
22✔
899
    sub.to_data(sink, prefixed);
22✔
900
    sink.write_little_endian(value);
22✔
901
    sink.write_little_endian(self.sequence());
22✔
902

903
    // outputs
904
    if (single)
22✔
905
        sink.write_bytes(output_hash(input));
14✔
906
    else
907
        sink.write_bytes(all ? outputs_hash() : null_hash);
8✔
908

909
    sink.write_little_endian(locktime_);
22✔
910
    sink.write_4_bytes_little_endian(sighash_flags);
22✔
911

912
    sink.flush();
22✔
913
    return digest;
22✔
914
}
22✔
915

916
// Signing (unversioned and version 0).
917
// ----------------------------------------------------------------------------
918

919
// ****************************************************************************
920
// CONSENSUS: sighash flags are carried in a single byte but are encoded as 4
921
// bytes in the signature hash preimage serialization.
922
// ****************************************************************************
923

924
hash_digest transaction::signature_hash(const input_iterator& input,
41✔
925
    const script& sub, uint64_t value, uint8_t sighash_flags,
926
    script_version version, bool bip143) const NOEXCEPT
927
{
928
    // There is no rational interpretation of a signature hash for a coinbase.
929
    BC_ASSERT(!is_coinbase());
41✔
930

931
    switch (version)
41✔
932
    {
933
        case script_version::unversioned:
12✔
934
            return unversioned_signature_hash(input, sub, sighash_flags);
12✔
935
        case script_version::zero:
29✔
936
            return version_0_signature_hash(input, sub, value, sighash_flags,
29✔
937
                bip143);
29✔
938
        case script_version::reserved:
×
939
        default:
×
940
            return {};
×
941
    }
942
}
943

944
// This is not used internal to the library.
945
bool transaction::check_signature(const ec_signature& signature,
2✔
946
    const data_slice& public_key, const script& sub, uint32_t index,
947
    uint64_t value, uint8_t sighash_flags, script_version version,
948
    bool bip143) const NOEXCEPT
949
{
950
    if ((index >= inputs_->size()) || signature.empty() || public_key.empty())
2✔
951
        return false;
952

953
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
954
        sighash_flags, version, bip143);
955

956
    // Validate the EC signature.
957
    return verify_signature(public_key, sighash, signature);
2✔
958
}
959

960
// This is not used internal to the library.
961
bool transaction::create_endorsement(endorsement& out, const ec_secret& secret,
2✔
962
    const script& sub, uint32_t index, uint64_t value, uint8_t sighash_flags,
963
    script_version version, bool bip143) const NOEXCEPT
964
{
965
    if (index >= inputs_->size())
2✔
966
        return false;
967

968
    out.reserve(max_endorsement_size);
2✔
969
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
970
        sighash_flags, version, bip143);
971

972
    // Create the EC signature and encode as DER.
973
    ec_signature signature;
2✔
974
    if (!sign(signature, secret, sighash) || !encode_signature(out, signature))
2✔
975
        return false;
×
976

977
    // Add the sighash type to the end of the DER signature -> endorsement.
978
    out.push_back(sighash_flags);
2✔
979
    out.shrink_to_fit();
2✔
980
    return true;
2✔
981
}
982

983
// Guard (context free).
984
// ----------------------------------------------------------------------------
985

986
bool transaction::is_coinbase() const NOEXCEPT
70✔
987
{
988
    return inputs_->size() == one && inputs_->front()->point().is_null();
70✔
989
}
990

991
bool transaction::is_internal_double_spend() const NOEXCEPT
4✔
992
{
993
    // TODO: optimize (see block.is_internal_double_spend).
994
    return !is_distinct(points());
4✔
995
}
996

997
// TODO: a pool (non-coinbase) tx must fit into a block (with a coinbase).
998
bool transaction::is_oversized() const NOEXCEPT
×
999
{
1000
    return serialized_size(false) > max_block_size;
×
1001
}
1002

1003
// Guard (contextual).
1004
// ----------------------------------------------------------------------------
1005

1006
// static/private
1007
bool transaction::segregated(const chain::inputs& inputs) NOEXCEPT
1✔
1008
{
1009
    const auto witnessed = [](const auto& input) NOEXCEPT
2✔
1010
    {
1011
        return !input.witness().stack().empty();
1✔
1012
    };
1013

1014
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
1✔
1015
}
1016

1017
// static/private
1018
bool transaction::segregated(const chain::input_cptrs& inputs) NOEXCEPT
814✔
1019
{
1020
    const auto witnessed = [](const auto& input) NOEXCEPT
816✔
1021
    {
1022
        return !input->witness().stack().empty();
816✔
1023
    };
1024

1025
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
814✔
1026
}
1027

1028
bool transaction::is_segregated() const NOEXCEPT
×
1029
{
1030
    return segregated_;
×
1031
}
1032

1033
size_t transaction::weight() const NOEXCEPT
×
1034
{
1035
    // Block weight is 3 * base size * + 1 * total size (bip141).
NEW
1036
    return ceilinged_add(
×
1037
        ceilinged_multiply(base_size_contribution, serialized_size(false)),
NEW
1038
        ceilinged_multiply(total_size_contribution, serialized_size(true)));
×
1039
}
1040

1041
bool transaction::is_overweight() const NOEXCEPT
×
1042
{
1043
    return weight() > max_block_weight;
×
1044
}
1045

1046
//*****************************************************************************
1047
// CONSENSUS: Legacy sigops are counted in coinbase scripts despite the fact
1048
// that coinbase input scripts are never executed. There is no need to exclude
1049
// p2sh coinbase sigops since there is never a script to count.
1050
//*****************************************************************************
1051
bool transaction::is_signature_operations_limit(bool bip16,
×
1052
    bool bip141) const NOEXCEPT
1053
{
1054
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
1055
    return signature_operations(bip16, bip141) > limit;
×
1056
}
1057

1058
// Check (context free).
1059
// ----------------------------------------------------------------------------
1060

1061
bool transaction::is_empty() const NOEXCEPT
4✔
1062
{
1063
    return inputs_->empty() || outputs_->empty();
4✔
1064
}
1065

1066
bool transaction::is_null_non_coinbase() const NOEXCEPT
5✔
1067
{
1068
    BC_ASSERT(!is_coinbase());
5✔
1069

1070
    const auto invalid = [](const auto& input) NOEXCEPT
7✔
1071
    {
1072
        return input->point().is_null();
7✔
1073
    };
1074

1075
    // True if not coinbase but has null previous_output(s).
1076
    return std::any_of(inputs_->begin(), inputs_->end(), invalid);
5✔
1077
}
1078

1079
bool transaction::is_invalid_coinbase_size() const NOEXCEPT
6✔
1080
{
1081
    BC_ASSERT(is_coinbase());
6✔
1082

1083
    // True if coinbase and has invalid input[0] script size.
1084
    const auto script_size = inputs_->front()->script().serialized_size(false);
6✔
1085
    return script_size < min_coinbase_size || script_size > max_coinbase_size;
6✔
1086
}
1087

1088
// Accept (contextual).
1089
// ----------------------------------------------------------------------------
1090

1091
bool transaction::is_non_final(size_t height, uint32_t timestamp,
5✔
1092
    uint32_t median_time_past, bool bip113) const NOEXCEPT
1093
{
1094
    // BIP113: comparing the locktime against the median of the past 11 block
1095
    // timestamps, rather than the timestamp of the block including the tx.
1096
    const auto time = bip113 ? median_time_past : timestamp;
5✔
1097

1098
    const auto finalized = [](const auto& input) NOEXCEPT
2✔
1099
    {
1100
        return input->is_final();
2✔
1101
    };
1102

1103
    const auto height_time = locktime_ < locktime_threshold ? height : time;
5✔
1104

1105
    return !(is_zero(locktime_) || locktime_ < height_time ||
8✔
1106
        std::all_of(inputs_->begin(), inputs_->end(), finalized));
3✔
1107
}
1108

1109
bool transaction::is_missing_prevouts() const NOEXCEPT
3✔
1110
{
1111
    BC_ASSERT(!is_coinbase());
3✔
1112

1113
    // Null or invalid prevout indicates not found.
1114
    const auto missing = [](const auto& input) NOEXCEPT
2✔
1115
    {
1116
        return !input->prevout;
1117
    };
1118

1119
    return std::any_of(inputs_->begin(), inputs_->end(), missing);
3✔
1120
}
1121

1122
uint64_t transaction::claim() const NOEXCEPT
8✔
1123
{
1124
    // Overflow returns max_uint64.
1125
    const auto sum = [](uint64_t total, const auto& output) NOEXCEPT
8✔
1126
    {
1127
        return ceilinged_add(total, output->value());
8✔
1128
    };
1129

1130
    // The amount claimed by outputs.
1131
    return std::accumulate(outputs_->begin(), outputs_->end(), 0_u64, sum);
8✔
1132
}
1133

1134
uint64_t transaction::value() const NOEXCEPT
9✔
1135
{
1136
    // Overflow, not populated, and coinbase (default) return max_uint64.
1137
    const auto sum = [](uint64_t total, const auto& input) NOEXCEPT
7✔
1138
    {
1139
        const auto value = input->prevout ? input->prevout->value() : max_uint64;
7✔
1140
        return ceilinged_add(total, value);
7✔
1141
    };
1142

1143
    // The amount of prevouts (referenced by inputs).
1144
    return std::accumulate(inputs_->begin(), inputs_->end(), 0_u64, sum);
9✔
1145
}
1146

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

1151
    return claim() > value();
2✔
1152
}
1153

1154
constexpr bool is_non_coinbase_mature(size_t tx_height, size_t height) NOEXCEPT
2✔
1155
{
1156
    return tx_height <= height;
2✔
1157
}
1158

1159
//*****************************************************************************
1160
// CONSENSUS: Coinbase output matures at 100 blocks depth.
1161
// CONSENSUS: Genesis coinbase is forever immature (exception).
1162
//*****************************************************************************
1163
bool transaction::is_coinbase_mature(size_t coinbase_height,
3✔
1164
    size_t height) NOEXCEPT
1165
{
1166
    return !is_zero(coinbase_height) &&
5✔
1167
        ceilinged_add(coinbase_height, coinbase_maturity) <= height;
3✔
1168
}
1169

1170
bool transaction::is_immature(size_t height) const NOEXCEPT
6✔
1171
{
1172
    BC_ASSERT(!is_coinbase());
6✔
1173

1174
    // Spends internal to a block are handled by block validation.
1175
    const auto mature = [=](const auto& input) NOEXCEPT
5✔
1176
    {
1177
        return input->metadata.coinbase ?
5✔
1178
            is_coinbase_mature(input->metadata.height, height) :
3✔
1179
            is_non_coinbase_mature(input->metadata.height, height);
2✔
1180
    };
6✔
1181

1182
    return !std::all_of(inputs_->begin(), inputs_->end(), mature);
6✔
1183
}
1184

1185
bool transaction::is_locked(size_t height,
4✔
1186
    uint32_t median_time_past) const NOEXCEPT
1187
{
1188
    // BIP68: not applied to the sequence of the input of a coinbase.
1189
    BC_ASSERT(!is_coinbase());
4✔
1190

1191
    // BIP68: applied to txs with a version greater than or equal to two.
1192
    if (version_ < relative_locktime_min_version)
4✔
1193
        return false;
1194

1195
    // BIP68: references to median time past are as defined by bip113.
1196
    const auto locked = [=](const auto& input) NOEXCEPT
2✔
1197
    {
1198
        return input->is_locked(height, median_time_past);
2✔
1199
    };
2✔
1200

1201
    // BIP68: when the relative lock time is block based, it is interpreted as
1202
    // a minimum block height constraint over the age of the input.
1203
    return std::any_of(inputs_->begin(), inputs_->end(), locked);
2✔
1204
}
1205

1206
// Spends internal to a block are handled by block validation.
1207
bool transaction::is_unconfirmed_spend(size_t height) const NOEXCEPT
×
1208
{
1209
    BC_ASSERT(!is_coinbase());
×
1210

1211
    // Zero is either genesis or not found.
1212
    // Test maturity first to obtain proper error code.
1213
    // Spends internal to a block are handled by block validation.
1214
    const auto unconfirmed = [=](const auto& input) NOEXCEPT
×
1215
    {
1216
        const auto prevout_height = input->metadata.height;
×
1217
        return is_zero(prevout_height) && !(height > prevout_height);
×
1218
    };
×
1219

1220
    return std::any_of(inputs_->begin(), inputs_->end(), unconfirmed);
×
1221
}
1222

1223
bool transaction::is_confirmed_double_spend(size_t height) const NOEXCEPT
4✔
1224
{
1225
    BC_ASSERT(!is_coinbase());
4✔
1226

1227
    // Spends internal to a block are handled by block validation.
1228
    const auto spent = [=](const auto& input) NOEXCEPT
4✔
1229
    {
1230
        return input->metadata.spent && height > input->metadata.height;
4✔
1231
    };
4✔
1232

1233
    return std::any_of(inputs_->begin(), inputs_->end(), spent);
4✔
1234
}
1235

1236
// Guards (for tx pool without compact blocks).
1237
// ----------------------------------------------------------------------------
1238

1239
// Pools do not have coinbases.
1240
// Redundant with block is_internal_double_spend check.
1241
// Redundant with block max_block_size check.
1242
code transaction::guard_check() const NOEXCEPT
×
1243
{
1244
    if (is_coinbase())
×
1245
        return error::coinbase_transaction;
×
1246
    if (is_internal_double_spend())
×
1247
        return error::transaction_internal_double_spend;
×
1248
    if (is_oversized())
×
1249
        return error::transaction_size_limit;
×
1250

1251
    return error::transaction_success;
×
1252
}
1253

1254
// Redundant with block max_block_weight accept.
1255
code transaction::guard_check(const context& ctx) const NOEXCEPT
×
1256
{
1257
    const auto bip141 = ctx.is_enabled(flags::bip141_rule);
×
1258

1259
     if (!bip141 && is_segregated())
×
1260
        return error::unexpected_witness_transaction;
×
1261
    if (bip141 && is_overweight())
×
1262
        return error::transaction_weight_limit;
×
1263

1264
    return error::transaction_success;
×
1265
}
1266

1267
// Redundant with block max_block_sigops accept.
1268
code transaction::guard_accept(const context& ctx) const NOEXCEPT
×
1269
{
1270
    const auto bip16 = ctx.is_enabled(flags::bip16_rule);
×
1271
    const auto bip141 = ctx.is_enabled(flags::bip141_rule);
×
1272

1273
    if (is_missing_prevouts())
×
1274
        return error::missing_previous_output;
×
1275
    if (is_signature_operations_limit(bip16, bip141))
×
1276
        return error::transaction_sigop_limit;
×
1277

1278
    return error::transaction_success;
×
1279
}
1280

1281
// Validation.
1282
// ----------------------------------------------------------------------------
1283

1284
// DO invoke on coinbase.
1285
code transaction::check() const NOEXCEPT
×
1286
{
1287
    const auto coinbase = is_coinbase();
×
1288

1289
    if (is_empty())
×
1290
        return error::empty_transaction;
×
1291
    if (coinbase && is_invalid_coinbase_size())
×
1292
        return error::invalid_coinbase_script_size;
×
1293
    if (!coinbase && is_null_non_coinbase())
×
1294
        return error::previous_output_null;
×
1295

1296
    return error::transaction_success;
×
1297
}
1298

1299
// forks
1300
// height
1301
// timestamp
1302
// median_time_past
1303

1304
// DO invoke on coinbase.
1305
code transaction::check(const context& ctx) const NOEXCEPT
×
1306
{
1307
    const auto bip113 = ctx.is_enabled(bip113_rule);
×
1308

1309
    if (is_non_final(ctx.height, ctx.timestamp, ctx.median_time_past, bip113))
×
1310
        return error::transaction_non_final;
×
1311

1312
    return error::transaction_success;
×
1313
}
1314

1315
// Do not need to invoke on coinbase.
1316
// This assumes that prevout caching is completed on all inputs.
1317
code transaction::accept(const context&) const NOEXCEPT
×
1318
{
1319
    ////BC_ASSERT(!is_coinbase());
1320

1321
    if (is_coinbase())
×
1322
        return error::transaction_success;
×
1323
    if (is_missing_prevouts())
×
1324
        return error::missing_previous_output;
×
1325
    if (is_overspent())
×
1326
        return error::spend_exceeds_value;
×
1327

1328
    return error::transaction_success;
×
1329
}
1330

1331
// forks
1332
// height
1333
// median_time_past
1334

1335
// Do not need to invoke on coinbase.
1336
// Node performs these checks through database query.
1337
// This assumes that prevout and metadata caching are completed on all inputs.
1338
code transaction::confirm(const context& ctx) const NOEXCEPT
×
1339
{
1340
    ////BC_ASSERT(!is_coinbase());
1341
    const auto bip68 = ctx.is_enabled(bip68_rule);
×
1342

1343
    if (is_coinbase())
×
1344
        return error::transaction_success;
×
1345
    if (bip68 && is_locked(ctx.height, ctx.median_time_past))
×
1346
        return error::relative_time_locked;
×
1347
    if (is_immature(ctx.height))
×
1348
        return error::coinbase_maturity;
×
1349
    if (is_unconfirmed_spend(ctx.height))
×
1350
        return error::unconfirmed_spend;
×
1351
    if (is_confirmed_double_spend(ctx.height))
×
1352
        return error::confirmed_double_spend;
×
1353

1354
    return error::transaction_success;
×
1355
}
1356

1357
// Connect (contextual).
1358
// ----------------------------------------------------------------------------
1359

1360
// forks
1361

1362
// Do not need to invoke on coinbase.
1363
code transaction::connect(const context& ctx) const NOEXCEPT
2✔
1364
{
1365
    ////BC_ASSERT(!is_coinbase());
1366

1367
    if (is_coinbase())
2✔
1368
        return error::transaction_success;
×
1369

1370
    code ec{};
2✔
1371
    using namespace machine;
2✔
1372
    initialize_sighash_cache();
2✔
1373

1374
    // Validate scripts.
1375
    for (auto input = inputs_->begin(); input != inputs_->end(); ++input)
6✔
1376
    {
1377
        // Evaluate rolling scripts with linear search but constant erase.
1378
        // Evaluate non-rolling scripts with constant search but linear erase.
1379
        if ((ec = (*input)->is_roller() ?
8✔
1380
            interpreter<linked_stack>::connect(ctx, *this, input) :
×
1381
            interpreter<contiguous_stack>::connect(ctx, *this, input)))
4✔
1382
            return ec;
×
1383
    }
1384

1385
    // TODO: accumulate sigops from each connect result and add coinbase.
1386
    // TODO: return in override with out parameter. more impactful with segwit.
1387
    return error::transaction_success;
2✔
1388
}
1389

1390
BC_POP_WARNING()
1391

1392
// JSON value convertors.
1393
// ----------------------------------------------------------------------------
1394

1395
namespace json = boost::json;
1396

1397
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
1398
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
1399

1400
transaction tag_invoke(json::value_to_tag<transaction>,
2✔
1401
    const json::value& value) NOEXCEPT
1402
{
1403
    return
2✔
1404
    {
1405
        value.at("version").to_number<uint32_t>(),
2✔
1406
        json::value_to<chain::inputs>(value.at("inputs")),
2✔
1407
        json::value_to<chain::outputs>(value.at("outputs")),
4✔
1408
        value.at("locktime").to_number<uint32_t>()
4✔
1409
    };
4✔
1410
}
1411

1412
void tag_invoke(json::value_from_tag, json::value& value,
4✔
1413
    const transaction& tx) NOEXCEPT
1414
{
1415
    value =
4✔
1416
    {
1417
        { "version", tx.version() },
1418
        { "inputs", *tx.inputs_ptr() },
1419
        { "outputs", *tx.outputs_ptr() },
1420
        { "locktime", tx.locktime() }
1421
    };
4✔
1422
}
4✔
1423

1424
BC_POP_WARNING()
1425

1426
transaction::cptr tag_invoke(json::value_to_tag<transaction::cptr>,
×
1427
    const json::value& value) NOEXCEPT
1428
{
1429
    return to_shared(tag_invoke(json::value_to_tag<transaction>{}, value));
×
1430
}
1431

1432
// Shared pointer overload is required for navigation.
1433
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
1434
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
1435

1436
void tag_invoke(json::value_from_tag tag, json::value& value,
2✔
1437
    const transaction::cptr& tx) NOEXCEPT
1438
{
1439
    tag_invoke(tag, value, *tx);
2✔
1440
}
2✔
1441

1442
BC_POP_WARNING()
1443
BC_POP_WARNING()
1444

1445
} // namespace chain
1446
} // namespace system
1447
} // 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