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

libbitcoin / libbitcoin-system / 9310800761

31 May 2024 12:08AM UTC coverage: 82.732% (-0.01%) from 82.746%
9310800761

push

github

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

Performance optimizations, style, comments.

233 of 289 new or added lines in 11 files covered. (80.62%)

8 existing lines in 4 files now uncovered.

9812 of 11860 relevant lines covered (82.73%)

4808594.09 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✔
NEW
101
        nominal_hash_ = to_unique(*other.nominal_hash_);
×
102
    if (other.witness_hash_)
1,072✔
NEW
103
        witness_hash_ = to_unique(*other.witness_hash_);
×
104
    if (other.sighash_cache_)
1,072✔
NEW
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
{
176
}
2,074✔
177

178
// Operators.
179
// ----------------------------------------------------------------------------
180

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

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

NEW
196
    if (other.nominal_hash_)
×
NEW
197
        nominal_hash_ = to_unique(*other.nominal_hash_);
×
NEW
198
    if (other.witness_hash_)
×
NEW
199
        witness_hash_ = to_unique(*other.witness_hash_);
×
NEW
200
    if (other.sighash_cache_)
×
NEW
201
        sighash_cache_ = to_unique(*other.sighash_cache_);
×
202

UNCOV
203
    return *this;
×
204
}
205

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

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

222
// Deserialization.
223
// ----------------------------------------------------------------------------
224

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

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

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

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

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

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

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

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

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

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

293
// Serialization.
294
// ----------------------------------------------------------------------------
295

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

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

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

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

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

320
    sink.write_4_bytes_little_endian(version_);
963✔
321

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

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

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

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

340
    sink.write_4_bytes_little_endian(locktime_);
963✔
341
}
963✔
342

343
// TODO: this is expensive.
344
size_t transaction::serialized_size(bool witness) const NOEXCEPT
64✔
345
{
346
    witness &= segregated_;
64✔
347

348
    const auto ins = [=](size_t total, const auto& input) NOEXCEPT
80✔
349
    {
350
        // Inputs account for witness bytes. 
351
        return total + input->serialized_size(witness);
80✔
352
    };
64✔
353

354
    const auto outs = [](size_t total, const auto& output) NOEXCEPT
82✔
355
    {
356
        return total + output->serialized_size();
82✔
357
    };
358

359
    return sizeof(version_)
64✔
360
        + (witness ? sizeof(witness_marker) + sizeof(witness_enabled) : zero)
64✔
361
        + variable_size(inputs_->size())
64✔
362
        + std::accumulate(inputs_->begin(), inputs_->end(), zero, ins)
64✔
363
        + variable_size(outputs_->size())
64✔
364
        + std::accumulate(outputs_->begin(), outputs_->end(), zero, outs)
64✔
365
        + sizeof(locktime_);
64✔
366
}
367

368
// Properties.
369
// ----------------------------------------------------------------------------
370

371
bool transaction::is_valid() const NOEXCEPT
775✔
372
{
373
    return valid_;
775✔
374
}
375

376
size_t transaction::inputs() const NOEXCEPT
1,563✔
377
{
378
    return inputs_->size();
1,563✔
379
}
380

381
size_t transaction::outputs() const NOEXCEPT
1✔
382
{
383
    return outputs_->size();
1✔
384
}
385

386
uint32_t transaction::version() const NOEXCEPT
6✔
387
{
388
    return version_;
4✔
389
}
390

391
uint32_t transaction::locktime() const NOEXCEPT
15✔
392
{
393
    return locktime_;
4✔
394
}
395

396
const inputs_cptr& transaction::inputs_ptr() const NOEXCEPT
2,436✔
397
{
398
    return inputs_;
2,436✔
399
}
400

401
const outputs_cptr& transaction::outputs_ptr() const NOEXCEPT
62✔
402
{
403
    return outputs_;
62✔
404
}
405

406
uint64_t transaction::fee() const NOEXCEPT
4✔
407
{
408
    // Underflow returns zero (and is_overspent() will be true).
409
    // This is value of prevouts spent by inputs minus that claimed by outputs.
410
    return floored_subtract(value(), claim());
4✔
411
}
412

413
void transaction::set_nominal_hash(hash_digest&& hash) const NOEXCEPT
7✔
414
{
415
    nominal_hash_ = to_unique(std::move(hash));
14✔
416
}
7✔
417

418
void transaction::set_witness_hash(hash_digest&& hash) const NOEXCEPT
2✔
419
{
420
    witness_hash_ = to_unique(std::move(hash));
4✔
421
}
2✔
422

423
const hash_digest& transaction::get_hash(bool witness) const NOEXCEPT
11✔
424
{
425
    if (witness)
11✔
426
    {
427
        if (!witness_hash_) set_witness_hash(hash(witness));
3✔
428
        return *witness_hash_;
3✔
429
    }
430
    else
431
    {
432
        if (!nominal_hash_) set_nominal_hash(hash(witness));
8✔
433
        return *nominal_hash_;
8✔
434
    }
435
}
436

437
hash_digest transaction::hash(bool witness) const NOEXCEPT
930✔
438
{
439
    if (segregated_)
930✔
440
    {
441
        if (witness)
18✔
442
        {
443
            // Witness coinbase tx hash is assumed to be null_hash (bip141).
NEW
444
            if (witness_hash_) return *witness_hash_;
×
UNCOV
445
            if (is_coinbase()) return null_hash;
×
446
        }
447
        else
448
        {
449
            if (nominal_hash_) return *nominal_hash_;
18✔
450
        }
451
    }
452
    else
453
    {
454
        if (nominal_hash_) return *nominal_hash_;
912✔
455
    }
456

457
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
458
    hash_digest digest;
925✔
459
    BC_POP_WARNING()
460

461
    stream::out::fast stream{ digest };
925✔
462
    hash::sha256x2::fast sink{ stream };
925✔
463
    to_data(sink, witness);
925✔
464
    sink.flush();
925✔
465
    return digest;
925✔
466
}
925✔
467

468
// Methods.
469
// ----------------------------------------------------------------------------
470

471
bool transaction::is_dusty(uint64_t minimum_output_value) const NOEXCEPT
6✔
472
{
473
    const auto dusty = [=](const auto& output) NOEXCEPT
9✔
474
    {
475
        return output->is_dust(minimum_output_value);
9✔
476
    };
6✔
477

478
    return std::any_of(outputs_->begin(), outputs_->end(), dusty);
6✔
479
}
480

481
size_t transaction::signature_operations(bool bip16, bool bip141) const NOEXCEPT
1✔
482
{
483
    // Includes BIP16 p2sh additional sigops, max_size_t if prevout invalid.
484
    const auto in = [=](size_t total, const auto& input) NOEXCEPT
×
485
    {
486
        return ceilinged_add(total, input->signature_operations(bip16, bip141));
×
487
    };
1✔
488

489
    const auto out = [=](size_t total, const auto& output) NOEXCEPT
×
490
    {
491
        return ceilinged_add(total, output->signature_operations(bip141));
×
492
    };
1✔
493

494
    // Overflow returns max_size_t.
495
    return ceilinged_add(
1✔
496
        std::accumulate(inputs_->begin(), inputs_->end(), zero, in),
497
        std::accumulate(outputs_->begin(), outputs_->end(), zero, out));
1✔
498
}
499

500
chain::points transaction::points() const NOEXCEPT
4✔
501
{
502
    chain::points out(inputs_->size());
4✔
503

504
    const auto point = [](const auto& input) NOEXCEPT
8✔
505
    {
506
        return input->point();
8✔
507
    };
508

509
    std::transform(inputs_->begin(), inputs_->end(), out.begin(), point);
4✔
510
    return out;
4✔
511
}
512

513
hash_digest transaction::outputs_hash() const NOEXCEPT
8✔
514
{
515
    if (sighash_cache_)
8✔
NEW
516
        return sighash_cache_->outputs;
×
517

518
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
519
    hash_digest digest;
8✔
520
    BC_POP_WARNING()
521
        
522
    stream::out::fast stream{ digest };
8✔
523
    hash::sha256x2::fast sink{ stream };
8✔
524

525
    const auto& outs = *outputs_;
8✔
526
    for (const auto& output: outs)
22✔
527
        output->to_data(sink);
14✔
528

529
    sink.flush();
8✔
530
    return digest;
8✔
531
}
8✔
532

533
hash_digest transaction::points_hash() const NOEXCEPT
11✔
534
{
535
    if (sighash_cache_)
11✔
NEW
536
        return sighash_cache_->points;
×
537

538
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
539
    hash_digest digest;
11✔
540
    BC_POP_WARNING()
541

542
    stream::out::fast stream{ digest };
11✔
543
    hash::sha256x2::fast sink{ stream };
11✔
544

545
    const auto& ins = *inputs_;
11✔
546
    for (const auto& input: ins)
27✔
547
        input->point().to_data(sink);
16✔
548

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

553
hash_digest transaction::sequences_hash() const NOEXCEPT
7✔
554
{
555
    if (sighash_cache_)
7✔
NEW
556
        return sighash_cache_->sequences;
×
557

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

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

565
    const auto& ins = *inputs_;
7✔
566
    for (const auto& input: ins)
17✔
567
        sink.write_4_bytes_little_endian(input->sequence());
10✔
568

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

573
// Signing (unversioned).
574
// ----------------------------------------------------------------------------
575

576
// private
577
transaction::input_iterator transaction::input_at(
4✔
578
    uint32_t index) const NOEXCEPT
579
{
580
    // Guarded by check_signature and create_endorsement.
581
    BC_ASSERT_MSG(index < inputs_->size(), "invalid input index");
4✔
582

583
    return std::next(inputs_->begin(), index);
4✔
584
}
585

586
// private
587
uint32_t transaction::input_index(const input_iterator& input) const NOEXCEPT
25✔
588
{
589
    // Guarded by unversioned_signature_hash and output_hash.
590
    BC_ASSERT_MSG(inputs_->begin() != inputs_->end(), "invalid input iterator");
25✔
591

592
    return possible_narrow_and_sign_cast<uint32_t>(
25✔
593
        std::distance(inputs_->begin(), input));
×
594
}
595

596
//*****************************************************************************
597
// CONSENSUS: Due to masking of bits 6/7 (8 is the anyone_can_pay flag),
598
// there are 4 possible 7 bit values that can set "single" and 4 others that
599
// can set none, and yet all other values set "all".
600
//*****************************************************************************
601
inline coverage mask_sighash(uint8_t sighash_flags) NOEXCEPT
41✔
602
{
603
    switch (sighash_flags & coverage::mask)
41✔
604
    {
605
        case coverage::hash_single:
606
            return coverage::hash_single;
607
        case coverage::hash_none:
2✔
608
            return coverage::hash_none;
2✔
609
        default:
18✔
610
            return coverage::hash_all;
18✔
611
    }
612
}
613

614
void transaction::signature_hash_single(writer& sink,
4✔
615
    const input_iterator& input, const script& sub,
616
    uint8_t sighash_flags) const NOEXCEPT
617
{
618
    const auto write_inputs = [this, &input, &sub, sighash_flags](
8✔
619
        writer& sink) NOEXCEPT
4✔
620
    {
621
        const auto& self = **input;
4✔
622
        const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
4✔
623
        input_cptrs::const_iterator in;
4✔
624

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

627
        for (in = inputs_->begin(); !anyone && in != input; ++in)
4✔
628
        {
629
            (*in)->point().to_data(sink);
×
630
            sink.write_bytes(empty_script());
×
631
            sink.write_bytes(zero_sequence());
×
632
        }
633

634
        self.point().to_data(sink);
4✔
635
        sub.to_data(sink, prefixed);
4✔
636
        sink.write_4_bytes_little_endian(self.sequence());
4✔
637

638
        for (++in; !anyone && in != inputs_->end(); ++in)
5✔
639
        {
640
            (*in)->point().to_data(sink);
1✔
641
            sink.write_bytes(empty_script());
1✔
642
            sink.write_bytes(zero_sequence());
1✔
643
        }
644
    };
4✔
645

646
    const auto write_outputs = [this, &input](writer& sink) NOEXCEPT
12✔
647
    {
648
        // Guarded by unversioned_signature_hash.
649
        const auto index = input_index(input);
4✔
650

651
        sink.write_variable(add1(index));
4✔
652

653
        for (size_t output = 0; output < index; ++output)
5✔
654
            sink.write_bytes(null_output());
1✔
655

656
        outputs_->at(index)->to_data(sink);
4✔
657
    };
8✔
658

659
    sink.write_4_bytes_little_endian(version_);
4✔
660
    write_inputs(sink);
4✔
661
    write_outputs(sink);
4✔
662
    sink.write_4_bytes_little_endian(locktime_);
4✔
663
    sink.write_4_bytes_little_endian(sighash_flags);
4✔
664
}
4✔
665

666
void transaction::signature_hash_none(writer& sink,
×
667
    const input_iterator& input, const script& sub,
668
    uint8_t sighash_flags) const NOEXCEPT
669
{
670
    const auto write_inputs = [this, &input, &sub, sighash_flags](
×
671
        writer& sink) NOEXCEPT
×
672
    {
673
        const auto& self = **input;
×
674
        const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
×
675
        input_cptrs::const_iterator in;
×
676

677
        sink.write_variable(anyone ? one : inputs_->size());
×
678

679
        for (in = inputs_->begin(); !anyone && in != input; ++in)
×
680
        {
681
            (*in)->point().to_data(sink);
×
682
            sink.write_bytes(empty_script());
×
683
            sink.write_bytes(zero_sequence());
×
684
        }
685

686
        self.point().to_data(sink);
×
687
        sub.to_data(sink, prefixed);
×
688
        sink.write_4_bytes_little_endian(self.sequence());
×
689

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

698
    sink.write_4_bytes_little_endian(version_);
×
699
    write_inputs(sink);
×
700
    sink.write_variable(zero);
×
701
    sink.write_4_bytes_little_endian(locktime_);
×
702
    sink.write_4_bytes_little_endian(sighash_flags);
×
703
}
×
704

705
void transaction::signature_hash_all(writer& sink,
12✔
706
    const input_iterator& input, const script& sub,
707
    uint8_t flags) const NOEXCEPT
708
{
709
    const auto write_inputs = [this, &input, &sub, flags](
24✔
710
        writer& sink) NOEXCEPT
43✔
711
    {
712
        const auto& self = **input;
12✔
713
        const auto anyone = to_bool(flags & coverage::anyone_can_pay);
12✔
714
        input_cptrs::const_iterator in;
12✔
715

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

718
        for (in = inputs_->begin(); !anyone && in != input; ++in)
15✔
719
        {
720
            (*in)->point().to_data(sink);
3✔
721
            sink.write_bytes(empty_script());
3✔
722
            sink.write_4_bytes_little_endian((*in)->sequence());
3✔
723
        }
724

725
        self.point().to_data(sink);
12✔
726
        sub.to_data(sink, prefixed);
12✔
727
        sink.write_4_bytes_little_endian(self.sequence());
12✔
728

729
        for (++in; !anyone && in != inputs_->end(); ++in)
16✔
730
        {
731
            (*in)->point().to_data(sink);
4✔
732
            sink.write_bytes(empty_script());
4✔
733
            sink.write_4_bytes_little_endian((*in)->sequence());
4✔
734
        }
735
    };
12✔
736

737
    const auto write_outputs = [this](writer& sink) NOEXCEPT
36✔
738
    {
739
        sink.write_variable(outputs_->size());
12✔
740
        for (const auto& output: *outputs_)
27✔
741
            output->to_data(sink);
15✔
742
    };
24✔
743

744
    sink.write_4_bytes_little_endian(version_);
12✔
745
    write_inputs(sink);
12✔
746
    write_outputs(sink);
12✔
747
    sink.write_4_bytes_little_endian(locktime_);
12✔
748
    sink.write_4_bytes_little_endian(flags);
12✔
749
}
12✔
750

751
// private
752
hash_digest transaction::unversioned_signature_hash(
19✔
753
    const input_iterator& input, const script& sub,
754
    uint8_t sighash_flags) const NOEXCEPT
755
{
756
    // Set options.
757
    const auto flag = mask_sighash(sighash_flags);
19✔
758

759
    // Create hash writer.
760
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
761
    hash_digest digest;
19✔
762
    BC_POP_WARNING()
763

764
    stream::out::fast stream{ digest };
19✔
765
    hash::sha256x2::fast sink{ stream };
19✔
766

767
    switch (flag)
19✔
768
    {
769
        case coverage::hash_single:
7✔
770
        {
7✔
771
            //*****************************************************************
772
            // CONSENSUS: return one_hash if index exceeds outputs in sighash.
773
            // Related Bug: bitcointalk.org/index.php?topic=260595
774
            // Exploit: joncave.co.uk/2014/08/bitcoin-sighash-single/
775
            //*****************************************************************
776
            if (input_index(input) >= outputs_->size())
7✔
777
                return one_hash;
3✔
778

779
            signature_hash_single(sink, input, sub, sighash_flags);
4✔
780
            break;
4✔
781
        }
782
        case coverage::hash_none:
×
NEW
783
        {
×
784
            signature_hash_none(sink, input, sub, sighash_flags);
×
785
            break;
×
786
        }
787
        default:
12✔
788
        case coverage::hash_all:
12✔
789
        {
12✔
790
            signature_hash_all(sink, input, sub, sighash_flags);
12✔
791
        }
792
    }
793

794
    sink.flush();
16✔
795
    return digest;
16✔
796
}
19✔
797

798
// Signing (version 0).
799
// ----------------------------------------------------------------------------
800

801
// private
802
// TODO: taproot requires both single and double hash of each.
803
void transaction::initialize_sighash_cache() const NOEXCEPT
2✔
804
{
805
    // This overconstructs the cache (anyone or !all), however it is simple and
806
    // the same criteria applied by satoshi.
807
    if (segregated_)
2✔
808
    {
809
        BC_PUSH_WARNING(NO_NEW_OR_DELETE)
810
        sighash_cache_.reset(new sighash_cache
2✔
811
        {
812
            outputs_hash(),
2✔
813
            points_hash(),
2✔
814
            sequences_hash()
2✔
815
        });
2✔
816
        BC_POP_WARNING()
817
    }
818
}
2✔
819

820
// private
821
hash_digest transaction::output_hash(const input_iterator& input) const NOEXCEPT
14✔
822
{
823
    const auto index = input_index(input);
14✔
824

825
    //*************************************************************************
826
    // CONSENSUS: if index exceeds outputs in signature hash, return null_hash.
827
    //*************************************************************************
828
    if (index >= outputs_->size())
14✔
829
        return null_hash;
2✔
830

831
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
832
    hash_digest digest;
12✔
833
    BC_POP_WARNING()
834

835
    stream::out::fast stream{ digest };
12✔
836
    hash::sha256x2::fast sink{ stream };
12✔
837
    outputs_->at(index)->to_data(sink);
12✔
838
    sink.flush();
12✔
839
    return digest;
12✔
840
}
12✔
841

842
// private
843
hash_digest transaction::version_0_signature_hash(const input_iterator& input,
29✔
844
    const script& sub, uint64_t value, uint8_t sighash_flags,
845
    bool bip143) const NOEXCEPT
846
{
847
    // bip143/v0: the way of serialization is changed.
848
    if (!bip143)
29✔
849
        return unversioned_signature_hash(input, sub, sighash_flags);
7✔
850

851
    // Set options.
852
    // C++14: switch in constexpr.
853
    const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
22✔
854
    const auto flag = mask_sighash(sighash_flags);
22✔
855
    const auto all = (flag == coverage::hash_all);
22✔
856
    const auto single = (flag == coverage::hash_single);
22✔
857
    const auto& self = **input;
22✔
858

859
    // Create hash writer.
860
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
861
    hash_digest digest;
22✔
862
    BC_POP_WARNING()
863

864
    stream::out::fast stream{ digest };
22✔
865
    hash::sha256x2::fast sink{ stream };
22✔
866

867
    // Create signature hash.
868
    sink.write_little_endian(version_);
22✔
869

870
    // Conditioning points, sequences, and outputs writes on cache_ instead of
871
    // conditionally passing them from methods avoids copying the cached hash.
872

873
    // points
874
    sink.write_bytes(!anyone ? points_hash() : null_hash);
22✔
875

876
    // sequences
877
    sink.write_bytes(!anyone && all ? sequences_hash() : null_hash);
22✔
878

879
    self.point().to_data(sink);
22✔
880
    sub.to_data(sink, prefixed);
22✔
881
    sink.write_little_endian(value);
22✔
882
    sink.write_little_endian(self.sequence());
22✔
883

884
    // outputs
885
    if (single)
22✔
886
        sink.write_bytes(output_hash(input));
14✔
887
    else
888
        sink.write_bytes(all ? outputs_hash() : null_hash);
8✔
889

890
    sink.write_little_endian(locktime_);
22✔
891
    sink.write_4_bytes_little_endian(sighash_flags);
22✔
892

893
    sink.flush();
22✔
894
    return digest;
22✔
895
}
22✔
896

897
// Signing (unversioned and version 0).
898
// ----------------------------------------------------------------------------
899

900
// ****************************************************************************
901
// CONSENSUS: sighash flags are carried in a single byte but are encoded as 4
902
// bytes in the signature hash preimage serialization.
903
// ****************************************************************************
904

905
hash_digest transaction::signature_hash(const input_iterator& input,
41✔
906
    const script& sub, uint64_t value, uint8_t sighash_flags,
907
    script_version version, bool bip143) const NOEXCEPT
908
{
909
    // There is no rational interpretation of a signature hash for a coinbase.
910
    BC_ASSERT(!is_coinbase());
41✔
911

912
    switch (version)
41✔
913
    {
914
        case script_version::unversioned:
12✔
915
            return unversioned_signature_hash(input, sub, sighash_flags);
12✔
916
        case script_version::zero:
29✔
917
            return version_0_signature_hash(input, sub, value, sighash_flags,
29✔
918
                bip143);
29✔
919
        case script_version::reserved:
×
920
        default:
×
921
            return {};
×
922
    }
923
}
924

925
// This is not used internal to the library.
926
bool transaction::check_signature(const ec_signature& signature,
2✔
927
    const data_slice& public_key, const script& sub, uint32_t index,
928
    uint64_t value, uint8_t sighash_flags, script_version version,
929
    bool bip143) const NOEXCEPT
930
{
931
    if ((index >= inputs_->size()) || signature.empty() || public_key.empty())
2✔
932
        return false;
933

934
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
935
        sighash_flags, version, bip143);
936

937
    // Validate the EC signature.
938
    return verify_signature(public_key, sighash, signature);
2✔
939
}
940

941
// This is not used internal to the library.
942
bool transaction::create_endorsement(endorsement& out, const ec_secret& secret,
2✔
943
    const script& sub, uint32_t index, uint64_t value, uint8_t sighash_flags,
944
    script_version version, bool bip143) const NOEXCEPT
945
{
946
    if (index >= inputs_->size())
2✔
947
        return false;
948

949
    out.reserve(max_endorsement_size);
2✔
950
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
951
        sighash_flags, version, bip143);
952

953
    // Create the EC signature and encode as DER.
954
    ec_signature signature;
2✔
955
    if (!sign(signature, secret, sighash) || !encode_signature(out, signature))
2✔
956
        return false;
×
957

958
    // Add the sighash type to the end of the DER signature -> endorsement.
959
    out.push_back(sighash_flags);
2✔
960
    out.shrink_to_fit();
2✔
961
    return true;
2✔
962
}
963

964
// Guard (context free).
965
// ----------------------------------------------------------------------------
966

967
bool transaction::is_coinbase() const NOEXCEPT
70✔
968
{
969
    return inputs_->size() == one && inputs_->front()->point().is_null();
70✔
970
}
971

972
bool transaction::is_internal_double_spend() const NOEXCEPT
4✔
973
{
974
    // TODO: optimize (see block.is_internal_double_spend).
975
    return !is_distinct(points());
4✔
976
}
977

978
// TODO: a pool (non-coinbase) tx must fit into a block (with a coinbase).
979
bool transaction::is_oversized() const NOEXCEPT
×
980
{
981
    return serialized_size(false) > max_block_size;
×
982
}
983

984
// Guard (contextual).
985
// ----------------------------------------------------------------------------
986

987
// static/private
988
bool transaction::segregated(const chain::inputs& inputs) NOEXCEPT
1✔
989
{
990
    const auto witnessed = [](const auto& input) NOEXCEPT
2✔
991
    {
992
        return !input.witness().stack().empty();
1✔
993
    };
994

995
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
1✔
996
}
997

998
// static/private
999
bool transaction::segregated(const chain::input_cptrs& inputs) NOEXCEPT
814✔
1000
{
1001
    const auto witnessed = [](const auto& input) NOEXCEPT
816✔
1002
    {
1003
        return !input->witness().stack().empty();
816✔
1004
    };
1005

1006
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
814✔
1007
}
1008

1009
bool transaction::is_segregated() const NOEXCEPT
×
1010
{
1011
    return segregated_;
×
1012
}
1013

1014
size_t transaction::weight() const NOEXCEPT
×
1015
{
1016
    // Block weight is 3 * base size * + 1 * total size (bip141).
1017
    return base_size_contribution * serialized_size(false) +
×
1018
        total_size_contribution * serialized_size(true);
×
1019
}
1020

1021
bool transaction::is_overweight() const NOEXCEPT
×
1022
{
1023
    return weight() > max_block_weight;
×
1024
}
1025

1026
//*****************************************************************************
1027
// CONSENSUS: Legacy sigops are counted in coinbase scripts despite the fact
1028
// that coinbase input scripts are never executed. There is no need to exclude
1029
// p2sh coinbase sigops since there is never a script to count.
1030
//*****************************************************************************
1031
bool transaction::is_signature_operations_limit(bool bip16,
×
1032
    bool bip141) const NOEXCEPT
1033
{
1034
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
1035
    return signature_operations(bip16, bip141) > limit;
×
1036
}
1037

1038
// Check (context free).
1039
// ----------------------------------------------------------------------------
1040

1041
bool transaction::is_empty() const NOEXCEPT
4✔
1042
{
1043
    return inputs_->empty() || outputs_->empty();
4✔
1044
}
1045

1046
bool transaction::is_null_non_coinbase() const NOEXCEPT
5✔
1047
{
1048
    BC_ASSERT(!is_coinbase());
5✔
1049

1050
    const auto invalid = [](const auto& input) NOEXCEPT
7✔
1051
    {
1052
        return input->point().is_null();
7✔
1053
    };
1054

1055
    // True if not coinbase but has null previous_output(s).
1056
    return std::any_of(inputs_->begin(), inputs_->end(), invalid);
5✔
1057
}
1058

1059
bool transaction::is_invalid_coinbase_size() const NOEXCEPT
6✔
1060
{
1061
    BC_ASSERT(is_coinbase());
6✔
1062

1063
    // True if coinbase and has invalid input[0] script size.
1064
    const auto script_size = inputs_->front()->script().serialized_size(false);
6✔
1065
    return script_size < min_coinbase_size || script_size > max_coinbase_size;
6✔
1066
}
1067

1068
// Accept (contextual).
1069
// ----------------------------------------------------------------------------
1070

1071
bool transaction::is_non_final(size_t height, uint32_t timestamp,
5✔
1072
    uint32_t median_time_past, bool bip113) const NOEXCEPT
1073
{
1074
    // BIP113: comparing the locktime against the median of the past 11 block
1075
    // timestamps, rather than the timestamp of the block including the tx.
1076
    const auto time = bip113 ? median_time_past : timestamp;
5✔
1077

1078
    const auto finalized = [](const auto& input) NOEXCEPT
2✔
1079
    {
1080
        return input->is_final();
2✔
1081
    };
1082

1083
    const auto height_time = locktime_ < locktime_threshold ? height : time;
5✔
1084

1085
    return !(is_zero(locktime_) || locktime_ < height_time ||
8✔
1086
        std::all_of(inputs_->begin(), inputs_->end(), finalized));
3✔
1087
}
1088

1089
bool transaction::is_missing_prevouts() const NOEXCEPT
3✔
1090
{
1091
    BC_ASSERT(!is_coinbase());
3✔
1092

1093
    // Null or invalid prevout indicates not found.
1094
    const auto missing = [](const auto& input) NOEXCEPT
2✔
1095
    {
1096
        return !input->prevout;
1097
    };
1098

1099
    return std::any_of(inputs_->begin(), inputs_->end(), missing);
3✔
1100
}
1101

1102
uint64_t transaction::claim() const NOEXCEPT
8✔
1103
{
1104
    // Overflow returns max_uint64.
1105
    const auto sum = [](uint64_t total, const auto& output) NOEXCEPT
8✔
1106
    {
1107
        return ceilinged_add(total, output->value());
8✔
1108
    };
1109

1110
    // The amount claimed by outputs.
1111
    return std::accumulate(outputs_->begin(), outputs_->end(), 0_u64, sum);
8✔
1112
}
1113

1114
uint64_t transaction::value() const NOEXCEPT
9✔
1115
{
1116
    // Overflow, not populated, and coinbase (default) return max_uint64.
1117
    const auto sum = [](uint64_t total, const auto& input) NOEXCEPT
7✔
1118
    {
1119
        const auto value = input->prevout ? input->prevout->value() : max_uint64;
7✔
1120
        return ceilinged_add(total, value);
7✔
1121
    };
1122

1123
    // The amount of prevouts (referenced by inputs).
1124
    return std::accumulate(inputs_->begin(), inputs_->end(), 0_u64, sum);
9✔
1125
}
1126

1127
bool transaction::is_overspent() const NOEXCEPT
2✔
1128
{
1129
    BC_ASSERT(!is_coinbase());
2✔
1130

1131
    return claim() > value();
2✔
1132
}
1133

1134
constexpr bool is_non_coinbase_mature(size_t tx_height, size_t height) NOEXCEPT
2✔
1135
{
1136
    return tx_height <= height;
2✔
1137
}
1138

1139
//*****************************************************************************
1140
// CONSENSUS: Coinbase output matures at 100 blocks depth.
1141
// CONSENSUS: Genesis coinbase is forever immature (exception).
1142
//*****************************************************************************
1143
bool transaction::is_coinbase_mature(size_t coinbase_height,
3✔
1144
    size_t height) NOEXCEPT
1145
{
1146
    return !is_zero(coinbase_height) &&
5✔
1147
        ceilinged_add(coinbase_height, coinbase_maturity) <= height;
3✔
1148
}
1149

1150
bool transaction::is_immature(size_t height) const NOEXCEPT
6✔
1151
{
1152
    BC_ASSERT(!is_coinbase());
6✔
1153

1154
    // Spends internal to a block are handled by block validation.
1155
    const auto mature = [=](const auto& input) NOEXCEPT
5✔
1156
    {
1157
        return input->metadata.coinbase ?
5✔
1158
            is_coinbase_mature(input->metadata.height, height) :
3✔
1159
            is_non_coinbase_mature(input->metadata.height, height);
2✔
1160
    };
6✔
1161

1162
    return !std::all_of(inputs_->begin(), inputs_->end(), mature);
6✔
1163
}
1164

1165
bool transaction::is_locked(size_t height,
4✔
1166
    uint32_t median_time_past) const NOEXCEPT
1167
{
1168
    // BIP68: not applied to the sequence of the input of a coinbase.
1169
    BC_ASSERT(!is_coinbase());
4✔
1170

1171
    // BIP68: applied to txs with a version greater than or equal to two.
1172
    if (version_ < relative_locktime_min_version)
4✔
1173
        return false;
1174

1175
    // BIP68: references to median time past are as defined by bip113.
1176
    const auto locked = [=](const auto& input) NOEXCEPT
2✔
1177
    {
1178
        return input->is_locked(height, median_time_past);
2✔
1179
    };
2✔
1180

1181
    // BIP68: when the relative lock time is block based, it is interpreted as
1182
    // a minimum block height constraint over the age of the input.
1183
    return std::any_of(inputs_->begin(), inputs_->end(), locked);
2✔
1184
}
1185

1186
// Spends internal to a block are handled by block validation.
1187
bool transaction::is_unconfirmed_spend(size_t height) const NOEXCEPT
×
1188
{
1189
    BC_ASSERT(!is_coinbase());
×
1190

1191
    // Zero is either genesis or not found.
1192
    // Test maturity first to obtain proper error code.
1193
    // Spends internal to a block are handled by block validation.
1194
    const auto unconfirmed = [=](const auto& input) NOEXCEPT
×
1195
    {
1196
        const auto prevout_height = input->metadata.height;
×
1197
        return is_zero(prevout_height) && !(height > prevout_height);
×
1198
    };
×
1199

1200
    return std::any_of(inputs_->begin(), inputs_->end(), unconfirmed);
×
1201
}
1202

1203
bool transaction::is_confirmed_double_spend(size_t height) const NOEXCEPT
4✔
1204
{
1205
    BC_ASSERT(!is_coinbase());
4✔
1206

1207
    // Spends internal to a block are handled by block validation.
1208
    const auto spent = [=](const auto& input) NOEXCEPT
4✔
1209
    {
1210
        return input->metadata.spent && height > input->metadata.height;
4✔
1211
    };
4✔
1212

1213
    return std::any_of(inputs_->begin(), inputs_->end(), spent);
4✔
1214
}
1215

1216
// Guards (for tx pool without compact blocks).
1217
// ----------------------------------------------------------------------------
1218

1219
// Pools do not have coinbases.
1220
// Redundant with block is_internal_double_spend check.
1221
// Redundant with block max_block_size check.
1222
code transaction::guard_check() const NOEXCEPT
×
1223
{
1224
    if (is_coinbase())
×
1225
        return error::coinbase_transaction;
×
1226
    if (is_internal_double_spend())
×
1227
        return error::transaction_internal_double_spend;
×
1228
    if (is_oversized())
×
1229
        return error::transaction_size_limit;
×
1230

1231
    return error::transaction_success;
×
1232
}
1233

1234
// Redundant with block max_block_weight accept.
1235
code transaction::guard_check(const context& ctx) const NOEXCEPT
×
1236
{
1237
    const auto bip141 = ctx.is_enabled(flags::bip141_rule);
×
1238

1239
     if (!bip141 && is_segregated())
×
1240
        return error::unexpected_witness_transaction;
×
1241
    if (bip141 && is_overweight())
×
1242
        return error::transaction_weight_limit;
×
1243

1244
    return error::transaction_success;
×
1245
}
1246

1247
// Redundant with block max_block_sigops accept.
1248
code transaction::guard_accept(const context& ctx) const NOEXCEPT
×
1249
{
1250
    const auto bip16 = ctx.is_enabled(flags::bip16_rule);
×
1251
    const auto bip141 = ctx.is_enabled(flags::bip141_rule);
×
1252

1253
    if (is_missing_prevouts())
×
1254
        return error::missing_previous_output;
×
1255
    if (is_signature_operations_limit(bip16, bip141))
×
1256
        return error::transaction_sigop_limit;
×
1257

1258
    return error::transaction_success;
×
1259
}
1260

1261
// Validation.
1262
// ----------------------------------------------------------------------------
1263

1264
// DO invoke on coinbase.
1265
code transaction::check() const NOEXCEPT
×
1266
{
1267
    const auto coinbase = is_coinbase();
×
1268

1269
    if (is_empty())
×
1270
        return error::empty_transaction;
×
1271
    if (coinbase && is_invalid_coinbase_size())
×
1272
        return error::invalid_coinbase_script_size;
×
1273
    if (!coinbase && is_null_non_coinbase())
×
1274
        return error::previous_output_null;
×
1275

1276
    return error::transaction_success;
×
1277
}
1278

1279
// forks
1280
// height
1281
// timestamp
1282
// median_time_past
1283

1284
// DO invoke on coinbase.
1285
code transaction::check(const context& ctx) const NOEXCEPT
×
1286
{
1287
    const auto bip113 = ctx.is_enabled(bip113_rule);
×
1288

1289
    if (is_non_final(ctx.height, ctx.timestamp, ctx.median_time_past, bip113))
×
1290
        return error::transaction_non_final;
×
1291

1292
    return error::transaction_success;
×
1293
}
1294

1295
// Do not need to invoke on coinbase.
1296
// This assumes that prevout caching is completed on all inputs.
1297
code transaction::accept(const context&) const NOEXCEPT
×
1298
{
1299
    ////BC_ASSERT(!is_coinbase());
1300

1301
    if (is_coinbase())
×
1302
        return error::transaction_success;
×
1303
    if (is_missing_prevouts())
×
1304
        return error::missing_previous_output;
×
1305
    if (is_overspent())
×
1306
        return error::spend_exceeds_value;
×
1307

1308
    return error::transaction_success;
×
1309
}
1310

1311
// forks
1312
// height
1313
// median_time_past
1314

1315
// Do not need to invoke on coinbase.
1316
// Node performs these checks through database query.
1317
// This assumes that prevout and metadata caching are completed on all inputs.
1318
code transaction::confirm(const context& ctx) const NOEXCEPT
×
1319
{
1320
    ////BC_ASSERT(!is_coinbase());
1321
    const auto bip68 = ctx.is_enabled(bip68_rule);
×
1322

1323
    if (is_coinbase())
×
1324
        return error::transaction_success;
×
1325
    if (bip68 && is_locked(ctx.height, ctx.median_time_past))
×
1326
        return error::relative_time_locked;
×
1327
    if (is_immature(ctx.height))
×
1328
        return error::coinbase_maturity;
×
1329
    if (is_unconfirmed_spend(ctx.height))
×
1330
        return error::unconfirmed_spend;
×
1331
    if (is_confirmed_double_spend(ctx.height))
×
1332
        return error::confirmed_double_spend;
×
1333

1334
    return error::transaction_success;
×
1335
}
1336

1337
// Connect (contextual).
1338
// ----------------------------------------------------------------------------
1339

1340
// forks
1341

1342
// Do not need to invoke on coinbase.
1343
code transaction::connect(const context& ctx) const NOEXCEPT
2✔
1344
{
1345
    ////BC_ASSERT(!is_coinbase());
1346

1347
    if (is_coinbase())
2✔
1348
        return error::transaction_success;
×
1349

1350
    code ec{};
2✔
1351
    using namespace machine;
2✔
1352
    initialize_sighash_cache();
2✔
1353

1354
    // Validate scripts.
1355
    for (auto input = inputs_->begin(); input != inputs_->end(); ++input)
6✔
1356
    {
1357
        // Evaluate rolling scripts with linear search but constant erase.
1358
        // Evaluate non-rolling scripts with constant search but linear erase.
1359
        if ((ec = (*input)->is_roller() ?
8✔
1360
            interpreter<linked_stack>::connect(ctx, *this, input) :
×
1361
            interpreter<contiguous_stack>::connect(ctx, *this, input)))
4✔
1362
            return ec;
×
1363
    }
1364

1365
    // TODO: accumulate sigops from each connect result and add coinbase.
1366
    // TODO: return in override with out parameter. more impactful with segwit.
1367
    return error::transaction_success;
2✔
1368
}
1369

1370
BC_POP_WARNING()
1371

1372
// JSON value convertors.
1373
// ----------------------------------------------------------------------------
1374

1375
namespace json = boost::json;
1376

1377
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
1378
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
1379

1380
transaction tag_invoke(json::value_to_tag<transaction>,
2✔
1381
    const json::value& value) NOEXCEPT
1382
{
1383
    return
2✔
1384
    {
1385
        value.at("version").to_number<uint32_t>(),
2✔
1386
        json::value_to<chain::inputs>(value.at("inputs")),
2✔
1387
        json::value_to<chain::outputs>(value.at("outputs")),
4✔
1388
        value.at("locktime").to_number<uint32_t>()
4✔
1389
    };
4✔
1390
}
1391

1392
void tag_invoke(json::value_from_tag, json::value& value,
4✔
1393
    const transaction& tx) NOEXCEPT
1394
{
1395
    value =
4✔
1396
    {
1397
        { "version", tx.version() },
1398
        { "inputs", *tx.inputs_ptr() },
1399
        { "outputs", *tx.outputs_ptr() },
1400
        { "locktime", tx.locktime() }
1401
    };
4✔
1402
}
4✔
1403

1404
BC_POP_WARNING()
1405

1406
transaction::cptr tag_invoke(json::value_to_tag<transaction::cptr>,
×
1407
    const json::value& value) NOEXCEPT
1408
{
1409
    return to_shared(tag_invoke(json::value_to_tag<transaction>{}, value));
×
1410
}
1411

1412
// Shared pointer overload is required for navigation.
1413
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
1414
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
1415

1416
void tag_invoke(json::value_from_tag tag, json::value& value,
2✔
1417
    const transaction::cptr& tx) NOEXCEPT
1418
{
1419
    tag_invoke(tag, value, *tx);
2✔
1420
}
2✔
1421

1422
BC_POP_WARNING()
1423
BC_POP_WARNING()
1424

1425
} // namespace chain
1426
} // namespace system
1427
} // 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