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

libbitcoin / libbitcoin-system / 13069453084

31 Jan 2025 08:55AM UTC coverage: 82.728% (-0.007%) from 82.735%
13069453084

push

github

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

Set _CRTDBG_MAP_ALLOC for vc++ debug mode leak tracking.

2 of 2 new or added lines in 1 file covered. (100.0%)

15 existing lines in 11 files now uncovered.

10039 of 12135 relevant lines covered (82.73%)

3871639.49 hits per line

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

77.96
/src/chain/transaction.cpp
1
/**
2
 * Copyright (c) 2011-2025 libbitcoin developers (see AUTHORS)
3
 *
4
 * This file is part of libbitcoin.
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU Affero General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU Affero General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Affero General Public License
17
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19
#include <bitcoin/system/chain/transaction.hpp>
20

21
#include <algorithm>
22
#include <iterator>
23
#include <numeric>
24
#include <type_traits>
25
#include <utility>
26
#include <vector>
27
#include <bitcoin/system/chain/context.hpp>
28
#include <bitcoin/system/chain/enums/magic_numbers.hpp>
29
#include <bitcoin/system/chain/header.hpp>
30
#include <bitcoin/system/chain/input.hpp>
31
#include <bitcoin/system/chain/output.hpp>
32
#include <bitcoin/system/chain/script.hpp>
33
#include <bitcoin/system/data/data.hpp>
34
#include <bitcoin/system/define.hpp>
35
#include <bitcoin/system/error/error.hpp>
36
#include <bitcoin/system/hash/hash.hpp>
37
#include <bitcoin/system/machine/machine.hpp>
38
#include <bitcoin/system/math/math.hpp>
39
#include <bitcoin/system/stream/stream.hpp>
40

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

45
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
46

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

50
constexpr auto prefixed = true;
51

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

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

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

70
// Constructors.
71
// ----------------------------------------------------------------------------
72

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

81
transaction::transaction(uint32_t version, chain::inputs&& inputs,
905✔
82
    chain::outputs&& outputs, uint32_t locktime) NOEXCEPT
905✔
83
  : transaction(version, to_shareds(std::move(inputs)),
905✔
84
      to_shareds(std::move(outputs)), locktime)
2,715✔
85
{
86
}
905✔
87

88
transaction::transaction(uint32_t version, const chain::inputs& inputs,
1✔
89
    const chain::outputs& outputs, uint32_t locktime) NOEXCEPT
1✔
90
  : transaction(version, to_shareds(inputs), to_shareds(outputs), locktime,
1✔
91
      segregated(inputs), true)
3✔
92
{
93
}
1✔
94

95
transaction::transaction(uint32_t version, const chain::inputs_cptr& inputs,
905✔
96
    const chain::outputs_cptr& outputs, uint32_t locktime) NOEXCEPT
905✔
97
  : transaction(version, inputs, outputs, locktime, segregated(*inputs), true)
905✔
98
{
99
}
905✔
100

101
transaction::transaction(const data_slice& data, bool witness) NOEXCEPT
41✔
102
  : transaction(stream::in::copy(data), witness)
41✔
103
{
104
}
41✔
105

106
////transaction::transaction(stream::in::fast&& stream, bool witness) NOEXCEPT
107
////  : transaction(read::bytes::fast(stream), witness)
108
////{
109
////}
110

111
transaction::transaction(stream::in::fast& stream, bool witness) NOEXCEPT
2✔
112
  : transaction(read::bytes::fast(stream), witness)
2✔
113
{
114
}
2✔
115

116
transaction::transaction(std::istream&& stream, bool witness) NOEXCEPT
41✔
117
  : transaction(read::bytes::istream(stream), witness)
41✔
118
{
119
}
41✔
120

121
transaction::transaction(std::istream& stream, bool witness) NOEXCEPT
4✔
122
  : transaction(read::bytes::istream(stream), witness)
4✔
123
{
124
}
4✔
125

126
transaction::transaction(reader&& source, bool witness) NOEXCEPT
47✔
127
  : transaction(source, witness)
47✔
128
{
129
}
×
130

131
transaction::transaction(reader& source, bool witness) NOEXCEPT
180✔
132
  : version_(source.read_4_bytes_little_endian()),
360✔
133
    inputs_(CREATE(input_cptrs, source.get_allocator())),
180✔
134
    outputs_(CREATE(output_cptrs, source.get_allocator()))
540✔
135
{
136
    assign_data(source, witness);
180✔
137
}
180✔
138

139
// protected
140
transaction::transaction(uint32_t version,
927✔
141
    const chain::inputs_cptr& inputs, const chain::outputs_cptr& outputs,
142
    uint32_t locktime, bool segregated, bool valid) NOEXCEPT
927✔
143
  : version_(version),
927✔
144
    inputs_(inputs ? inputs : to_shared<input_cptrs>()),
1,854✔
145
    outputs_(outputs ? outputs : to_shared<output_cptrs>()),
927✔
146
    locktime_(locktime),
927✔
147
    segregated_(segregated),
927✔
148
    valid_(valid),
927✔
149
    size_(serialized_size(*inputs, *outputs, segregated))
1,854✔
150
{
151
}
927✔
152

153
// Operators.
154
// ----------------------------------------------------------------------------
155

156
bool transaction::operator==(const transaction& other) const NOEXCEPT
60✔
157
{
158
    // Compares input/output elements, not pointers, cache not compared.
159
    return (version_ == other.version_)
60✔
160
        && (locktime_ == other.locktime_)
58✔
161
        && ((inputs_ == other.inputs_) || 
74✔
162
            deep_equal(*inputs_, *other.inputs_))
16✔
163
        && ((outputs_ == other.outputs_) ||
134✔
164
            deep_equal(*outputs_, *other.outputs_));
16✔
165
}
166

167
bool transaction::operator!=(const transaction& other) const NOEXCEPT
2✔
168
{
169
    return !(*this == other);
2✔
170
}
171

172
// Deserialization.
173
// ----------------------------------------------------------------------------
174

175
// private
176
BC_PUSH_WARNING(NO_UNGUARDED_POINTERS)
177
void transaction::assign_data(reader& source, bool witness) NOEXCEPT
180✔
178
{
179
    auto& allocator = source.get_allocator();
180✔
180
    auto ins = to_non_const_raw_ptr(inputs_);
180✔
181
    auto count = source.read_size(max_block_size);
180✔
182
    ins->reserve(count);
180✔
183
    for (size_t in = 0; in < count; ++in)
405✔
184
        ins->emplace_back(CREATE(input, allocator, source));
225✔
185

186
    // Expensive repeated recomputation, so cache segregated state.
187
    // Detect witness as no inputs (marker) and expected flag (bip144).
188
    segregated_ = 
180✔
189
        inputs_->size() == witness_marker &&
196✔
190
        source.peek_byte() == witness_enabled;
16✔
191

192
    if (segregated_)
180✔
193
    {
194
        // Skip over the peeked witness flag.
195
        source.skip_byte();
16✔
196

197
        count = source.read_size(max_block_size);
16✔
198
        ins->reserve(count);
16✔
199
        for (size_t in = 0; in < count; ++in)
37✔
200
            ins->emplace_back(CREATE(input, allocator, source));
21✔
201

202
        auto outs = to_non_const_raw_ptr(outputs_);
16✔
203
        count = source.read_size(max_block_size);
16✔
204
        outs->reserve(count);
16✔
205
        for (size_t out = 0; out < count; ++out)
41✔
206
            outs->emplace_back(CREATE(output, allocator, source));
25✔
207

208
        // Read or skip witnesses as specified.
209
        if (witness)
16✔
210
        {
211
            for (auto& input: *inputs_)
35✔
212
                to_non_const_raw_ptr(input)->set_witness(source);
20✔
213
        }
214
        else
215
        {
216
            // Default witness is populated on input construct.
217
            for (size_t in = 0; in < inputs_->size(); ++in)
2✔
218
                witness::skip(source, true);
1✔
219
        }
220
    }
221
    else
222
    {
223
        auto outs = to_non_const_raw_ptr(outputs_);
164✔
224
        count = source.read_size(max_block_size);
164✔
225
        outs->reserve(count);
164✔
226
        for (size_t out = 0; out < count; ++out)
389✔
227
            outs->emplace_back(CREATE(output, allocator, source));
225✔
228
    }
229

230
    locktime_ = source.read_4_bytes_little_endian();
180✔
231
    size_ = serialized_size(*inputs_, *outputs_, segregated_);
180✔
232
    valid_ = source;
180✔
233
}
180✔
234
BC_POP_WARNING()
235

236
// Serialization.
237
// ----------------------------------------------------------------------------
238

239
// Transactions with empty witnesses always use old serialization (bip144).
240
// If no inputs are witness programs then witness hash is tx hash (bip141).
241
data_chunk transaction::to_data(bool witness) const NOEXCEPT
10✔
242
{
243
    witness &= segregated_;
10✔
244

245
    data_chunk data(serialized_size(witness));
10✔
246
    stream::out::copy ostream(data);
10✔
247
    to_data(ostream, witness);
10✔
248
    return data;
10✔
249
}
10✔
250

251
void transaction::to_data(std::ostream& stream, bool witness) const NOEXCEPT
11✔
252
{
253
    witness &= segregated_;
11✔
254

255
    write::bytes::ostream out(stream);
11✔
256
    to_data(out, witness);
11✔
257
}
11✔
258

259
void transaction::to_data(writer& sink, bool witness) const NOEXCEPT
966✔
260
{
261
    witness &= segregated_;
966✔
262

263
    sink.write_4_bytes_little_endian(version_);
966✔
264

265
    if (witness)
966✔
266
    {
267
        sink.write_byte(witness_marker);
2✔
268
        sink.write_byte(witness_enabled);
2✔
269
    }
270

271
    sink.write_variable(inputs_->size());
966✔
272
    for (const auto& input: *inputs_)
2,352✔
273
        input->to_data(sink);
1,386✔
274

275
    sink.write_variable(outputs_->size());
966✔
276
    for (const auto& output: *outputs_)
2,634✔
277
        output->to_data(sink);
1,668✔
278

279
    if (witness)
966✔
280
        for (auto& input: *inputs_)
5✔
281
            input->witness().to_data(sink, true);
3✔
282

283
    sink.write_4_bytes_little_endian(locktime_);
966✔
284
}
966✔
285

286
// static/private
287
transaction::sizes transaction::serialized_size(
1,107✔
288
    const chain::input_cptrs& inputs,
289
    const chain::output_cptrs& outputs, bool segregated) NOEXCEPT
290
{
291
    sizes size{ zero, zero };
1,107✔
292

293
    // Keep the condition outside of the loop.
294
    if (segregated)
1,107✔
295
    {
296
        std::for_each(inputs.begin(), inputs.end(), [&](const auto& in) NOEXCEPT
54✔
297
        {
298
            size.nominal = ceilinged_add(size.nominal, in->nominal_size());
64✔
299
            size.witnessed = ceilinged_add(size.witnessed, in->witnessed_size());
32✔
300
        });
32✔
301
    }
302
    else
303
    {
304
        // Witness must be zeroed because witnesses have nonzero size when they
305
        // are zero-valued, so they can be archived easily. Also it would be
306
        // wasteful to to count mutiple zero sizes, so exclude them here.
307
        std::for_each(inputs.begin(), inputs.end(), [&](const auto& in) NOEXCEPT
2,212✔
308
        {
309
            size.nominal = ceilinged_add(size.nominal, in->nominal_size());
1,127✔
310
        });
1,127✔
311
    }
312

313
    const auto outs = [](size_t total, const auto& output) NOEXCEPT
370✔
314
    {
315
        return ceilinged_add(total, output->serialized_size());
370✔
316
    };
317

318
    constexpr auto base_const_size = ceilinged_add(sizeof(version_),
1,107✔
319
        sizeof(locktime_));
320

321
    constexpr auto witness_const_size = ceilinged_add(sizeof(witness_marker),
1,107✔
322
        sizeof(witness_enabled));
323

324
    const auto base_size = ceilinged_add(ceilinged_add(ceilinged_add(
1,107✔
325
        base_const_size, variable_size(inputs.size())),
326
        variable_size(outputs.size())),
327
        std::accumulate(outputs.begin(), outputs.end(), zero, outs));
328

329
    const auto nominal_size = ceilinged_add(base_size, size.nominal);
1,107✔
330
    const auto witnessed_size = ceilinged_add(ceilinged_add(base_size,
1,107✔
331
        witness_const_size),
332
        size.witnessed);
333

334
    return { nominal_size, witnessed_size };
1,107✔
335
}
336

337
size_t transaction::serialized_size(bool witness) const NOEXCEPT
565✔
338
{
339
    witness &= segregated_;
565✔
340

341
    return witness ? size_.witnessed : size_.nominal;
565✔
342
}
343

344
// Properties.
345
// ----------------------------------------------------------------------------
346

347
bool transaction::is_valid() const NOEXCEPT
777✔
348
{
349
    return valid_;
777✔
350
}
351

352
size_t transaction::inputs() const NOEXCEPT
1,569✔
353
{
354
    return inputs_->size();
1,569✔
355
}
356

357
size_t transaction::outputs() const NOEXCEPT
1✔
358
{
359
    return outputs_->size();
1✔
360
}
361

362
uint32_t transaction::version() const NOEXCEPT
6✔
363
{
364
    return version_;
4✔
365
}
366

367
uint32_t transaction::locktime() const NOEXCEPT
13✔
368
{
369
    return locktime_;
4✔
370
}
371

372
const inputs_cptr& transaction::inputs_ptr() const NOEXCEPT
2,446✔
373
{
374
    return inputs_;
2,446✔
375
}
376

377
const outputs_cptr& transaction::outputs_ptr() const NOEXCEPT
62✔
378
{
379
    return outputs_;
62✔
380
}
381

382
uint64_t transaction::fee() const NOEXCEPT
4✔
383
{
384
    // Underflow returns zero (and is_overspent() will be true).
385
    // This is value of prevouts spent by inputs minus that claimed by outputs.
386
    return floored_subtract(value(), claim());
4✔
387
}
388

389
void transaction::set_nominal_hash(const hash_digest& hash) const NOEXCEPT
20✔
390
{
391
    nominal_hash_ = hash;
20✔
392
}
1✔
393

394
void transaction::set_witness_hash(const hash_digest& hash) const NOEXCEPT
2✔
395
{
396
    witness_hash_ = hash;
2✔
397
}
1✔
398

399
const hash_digest& transaction::get_hash(bool witness) const NOEXCEPT
26✔
400
{
401
    if (witness)
26✔
402
    {
403
        if (!witness_hash_) set_witness_hash(hash(witness));
4✔
404
        return *witness_hash_;
3✔
405
    }
406
    else
407
    {
408
        if (!nominal_hash_) set_nominal_hash(hash(witness));
42✔
409
        return *nominal_hash_;
23✔
410
    }
411
}
412

413
hash_digest transaction::hash(bool witness) const NOEXCEPT
934✔
414
{
415
    if (segregated_)
934✔
416
    {
417
        if (witness)
23✔
418
        {
419
            // Witness coinbase tx hash is assumed to be null_hash (bip141).
420
            if (witness_hash_) return *witness_hash_;
×
421
            if (is_coinbase()) return null_hash;
×
422
        }
423
        else
424
        {
425
            if (nominal_hash_) return *nominal_hash_;
23✔
426
        }
427
    }
428
    else
429
    {
430
        if (nominal_hash_) return *nominal_hash_;
911✔
431
    }
432

433
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
434
    hash_digest digest;
927✔
435
    BC_POP_WARNING()
436

437
    stream::out::fast stream{ digest };
927✔
438
    hash::sha256x2::fast sink{ stream };
927✔
439
    to_data(sink, witness);
927✔
440
    sink.flush();
927✔
441
    return digest;
927✔
442
}
927✔
443

444
// static
445
hash_digest transaction::desegregated_hash(size_t witnessed,
×
446
    size_t unwitnessed, const uint8_t* data) NOEXCEPT
447
{
448
    if (is_null(data))
×
449
        return null_hash;
×
450

451
    constexpr auto preamble = sizeof(uint32_t) + two * sizeof(uint8_t);
×
452
    const auto puts = floored_subtract(unwitnessed, two * sizeof(uint32_t));
×
453
    const auto locktime = floored_subtract(witnessed, sizeof(uint32_t));
×
454

455
    hash_digest digest{};
×
456
    stream::out::fast stream{ digest };
×
457
    hash::sha256x2::fast sink{ stream };
×
458
    sink.write_bytes(data, sizeof(uint32_t));
×
459
    sink.write_bytes(std::next(data, preamble), puts);
×
460
    sink.write_bytes(std::next(data, locktime), sizeof(uint32_t));
×
461
    sink.flush();
×
462
    return digest;
×
463
}
×
464

465
// Methods.
466
// ----------------------------------------------------------------------------
467

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

475
    return std::any_of(outputs_->begin(), outputs_->end(), dusty);
6✔
476
}
477

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

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

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

497
chain::points transaction::points() const NOEXCEPT
4✔
498
{
499
    chain::points out(inputs_->size());
4✔
500

501
    const auto point = [](const auto& input) NOEXCEPT
8✔
502
    {
503
        return input->point();
8✔
504
    };
505

506
    std::transform(inputs_->begin(), inputs_->end(), out.begin(), point);
4✔
507
    return out;
4✔
UNCOV
508
}
×
509

510
hash_digest transaction::outputs_hash() const NOEXCEPT
8✔
511
{
512
    if (sighash_cache_)
8✔
513
        return sighash_cache_->outputs;
×
514

515
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
516
    hash_digest digest;
8✔
517
    BC_POP_WARNING()
518
        
519
    stream::out::fast stream{ digest };
8✔
520
    hash::sha256x2::fast sink{ stream };
8✔
521

522
    for (const auto& output: *outputs_)
22✔
523
        output->to_data(sink);
14✔
524

525
    sink.flush();
8✔
526
    return digest;
8✔
527
}
8✔
528

529
hash_digest transaction::points_hash() const NOEXCEPT
11✔
530
{
531
    if (sighash_cache_)
11✔
532
        return sighash_cache_->points;
×
533

534
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
535
    hash_digest digest;
11✔
536
    BC_POP_WARNING()
537

538
    stream::out::fast stream{ digest };
11✔
539
    hash::sha256x2::fast sink{ stream };
11✔
540

541
    for (const auto& input: *inputs_)
27✔
542
        input->point().to_data(sink);
16✔
543

544
    sink.flush();
11✔
545
    return digest;
11✔
546
}
11✔
547

548
hash_digest transaction::sequences_hash() const NOEXCEPT
7✔
549
{
550
    if (sighash_cache_)
7✔
551
        return sighash_cache_->sequences;
×
552

553
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
554
    hash_digest digest;
7✔
555
    BC_POP_WARNING()
556

557
    stream::out::fast stream{ digest };
7✔
558
    hash::sha256x2::fast sink{ stream };
7✔
559

560
    for (const auto& input: *inputs_)
17✔
561
        sink.write_4_bytes_little_endian(input->sequence());
10✔
562

563
    sink.flush();
7✔
564
    return digest;
7✔
565
}
7✔
566

567
// Signing (unversioned).
568
// ----------------------------------------------------------------------------
569

570
// private
571
transaction::input_iterator transaction::input_at(
4✔
572
    uint32_t index) const NOEXCEPT
573
{
574
    // Guarded by check_signature and create_endorsement.
575
    BC_ASSERT_MSG(index < inputs_->size(), "invalid input index");
4✔
576

577
    return std::next(inputs_->begin(), index);
4✔
578
}
579

580
// private
581
uint32_t transaction::input_index(const input_iterator& input) const NOEXCEPT
25✔
582
{
583
    // Guarded by unversioned_signature_hash and output_hash.
584
    BC_ASSERT_MSG(inputs_->begin() != inputs_->end(), "invalid input iterator");
25✔
585

586
    return possible_narrow_and_sign_cast<uint32_t>(
25✔
587
        std::distance(inputs_->begin(), input));
×
588
}
589

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

608
void transaction::signature_hash_single(writer& sink,
4✔
609
    const input_iterator& input, const script& sub,
610
    uint8_t sighash_flags) const NOEXCEPT
611
{
612
    const auto write_inputs = [this, &input, &sub, sighash_flags](
8✔
613
        writer& sink) NOEXCEPT
614
    {
615
        const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
4✔
616
        input_cptrs::const_iterator in;
4✔
617

618
        sink.write_variable(anyone ? one : inputs_->size());
4✔
619

620
        for (in = inputs_->begin(); !anyone && in != input; ++in)
4✔
621
        {
622
            (*in)->point().to_data(sink);
×
623
            sink.write_bytes(empty_script());
×
624
            sink.write_bytes(zero_sequence());
×
625
        }
626

627
        (*input)->point().to_data(sink);
4✔
628
        sub.to_data(sink, prefixed);
4✔
629
        sink.write_4_bytes_little_endian((*input)->sequence());
4✔
630

631
        for (++in; !anyone && in != inputs_->end(); ++in)
5✔
632
        {
633
            (*in)->point().to_data(sink);
1✔
634
            sink.write_bytes(empty_script());
1✔
635
            sink.write_bytes(zero_sequence());
1✔
636
        }
637
    };
4✔
638

639
    const auto write_outputs = [this, &input](writer& sink) NOEXCEPT
8✔
640
    {
641
        const auto index = input_index(input);
4✔
642

643
        sink.write_variable(add1(index));
4✔
644

645
        for (size_t output = 0; output < index; ++output)
5✔
646
            sink.write_bytes(null_output());
1✔
647

648
        // Guarded by unversioned_signature_hash.
649
        outputs_->at(index)->to_data(sink);
4✔
650
    };
8✔
651

652
    sink.write_4_bytes_little_endian(version_);
4✔
653
    write_inputs(sink);
4✔
654
    write_outputs(sink);
4✔
655
    sink.write_4_bytes_little_endian(locktime_);
4✔
656
    sink.write_4_bytes_little_endian(sighash_flags);
4✔
657
}
4✔
658

659
void transaction::signature_hash_none(writer& sink,
×
660
    const input_iterator& input, const script& sub,
661
    uint8_t sighash_flags) const NOEXCEPT
662
{
663
    const auto write_inputs = [this, &input, &sub, sighash_flags](
×
664
        writer& sink) NOEXCEPT
665
    {
666
        const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
×
667
        input_cptrs::const_iterator in;
×
668

669
        sink.write_variable(anyone ? one : inputs_->size());
×
670

671
        for (in = inputs_->begin(); !anyone && in != input; ++in)
×
672
        {
673
            (*in)->point().to_data(sink);
×
674
            sink.write_bytes(empty_script());
×
675
            sink.write_bytes(zero_sequence());
×
676
        }
677

678
        (*input)->point().to_data(sink);
×
679
        sub.to_data(sink, prefixed);
×
680
        sink.write_4_bytes_little_endian((*input)->sequence());
×
681

682
        for (++in; !anyone && in != inputs_->end(); ++in)
×
683
        {
684
            (*in)->point().to_data(sink);
×
685
            sink.write_bytes(empty_script());
×
686
            sink.write_bytes(zero_sequence());
×
687
        }
688
    };
×
689

690
    sink.write_4_bytes_little_endian(version_);
×
691
    write_inputs(sink);
×
692
    sink.write_variable(zero);
×
693
    sink.write_4_bytes_little_endian(locktime_);
×
694
    sink.write_4_bytes_little_endian(sighash_flags);
×
695
}
×
696

697
void transaction::signature_hash_all(writer& sink,
12✔
698
    const input_iterator& input, const script& sub,
699
    uint8_t flags) const NOEXCEPT
700
{
701
    const auto write_inputs = [this, &input, &sub, flags](
24✔
702
        writer& sink) NOEXCEPT
703
    {
704
        const auto anyone = to_bool(flags & coverage::anyone_can_pay);
12✔
705
        input_cptrs::const_iterator in;
12✔
706

707
        sink.write_variable(anyone ? one : inputs_->size());
12✔
708

709
        for (in = inputs_->begin(); !anyone && in != input; ++in)
15✔
710
        {
711
            (*in)->point().to_data(sink);
3✔
712
            sink.write_bytes(empty_script());
3✔
713
            sink.write_4_bytes_little_endian((*in)->sequence());
3✔
714
        }
715

716
        (*input)->point().to_data(sink);
12✔
717
        sub.to_data(sink, prefixed);
12✔
718
        sink.write_4_bytes_little_endian((*input)->sequence());
12✔
719

720
        for (++in; !anyone && in != inputs_->end(); ++in)
16✔
721
        {
722
            (*in)->point().to_data(sink);
4✔
723
            sink.write_bytes(empty_script());
4✔
724
            sink.write_4_bytes_little_endian((*in)->sequence());
4✔
725
        }
726
    };
12✔
727

728
    const auto write_outputs = [this](writer& sink) NOEXCEPT
24✔
729
    {
730
        sink.write_variable(outputs_->size());
12✔
731
        for (const auto& output: *outputs_)
27✔
732
            output->to_data(sink);
15✔
733
    };
24✔
734

735
    sink.write_4_bytes_little_endian(version_);
12✔
736
    write_inputs(sink);
12✔
737
    write_outputs(sink);
12✔
738
    sink.write_4_bytes_little_endian(locktime_);
12✔
739
    sink.write_4_bytes_little_endian(flags);
12✔
740
}
12✔
741

742
// private
743
hash_digest transaction::unversioned_signature_hash(
19✔
744
    const input_iterator& input, const script& sub,
745
    uint8_t sighash_flags) const NOEXCEPT
746
{
747
    // Set options.
748
    const auto flag = mask_sighash(sighash_flags);
19✔
749

750
    // Create hash writer.
751
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
752
    hash_digest digest;
19✔
753
    BC_POP_WARNING()
754

755
    stream::out::fast stream{ digest };
19✔
756
    hash::sha256x2::fast sink{ stream };
19✔
757

758
    switch (flag)
19✔
759
    {
760
        case coverage::hash_single:
7✔
761
        {
7✔
762
            //*****************************************************************
763
            // CONSENSUS: return one_hash if index exceeds outputs in sighash.
764
            // Related Bug: bitcointalk.org/index.php?topic=260595
765
            // Exploit: joncave.co.uk/2014/08/bitcoin-sighash-single/
766
            //*****************************************************************
767
            if (input_index(input) >= outputs_->size())
7✔
768
                return one_hash;
3✔
769

770
            signature_hash_single(sink, input, sub, sighash_flags);
4✔
771
            break;
772
        }
773
        case coverage::hash_none:
×
774
        {
×
775
            signature_hash_none(sink, input, sub, sighash_flags);
×
776
            break;
777
        }
778
        default:
12✔
779
        case coverage::hash_all:
12✔
780
        {
12✔
781
            signature_hash_all(sink, input, sub, sighash_flags);
12✔
782
        }
783
    }
784

785
    sink.flush();
16✔
786
    return digest;
16✔
787
}
19✔
788

789
// Signing (version 0).
790
// ----------------------------------------------------------------------------
791

792
// private
793
// TODO: taproot requires both single and double hash of each.
794
void transaction::initialize_sighash_cache() const NOEXCEPT
2✔
795
{
796
    // C++23: std::optional<T>::or_else.
797
    if (!segregated_)
2✔
798
        return;
799

800
    // This overconstructs the cache (anyone or !all), however it is simple.
801
    sighash_cache_ =
2✔
802
    {
803
        outputs_hash(),
2✔
804
        points_hash(),
2✔
805
        sequences_hash()
2✔
806
    };
2✔
807
}
808

809
// private
810
hash_digest transaction::output_hash(const input_iterator& input) const NOEXCEPT
14✔
811
{
812
    const auto index = input_index(input);
14✔
813

814
    //*************************************************************************
815
    // CONSENSUS: if index exceeds outputs in signature hash, return null_hash.
816
    //*************************************************************************
817
    if (index >= outputs_->size())
14✔
818
        return null_hash;
2✔
819

820
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
821
    hash_digest digest;
12✔
822
    BC_POP_WARNING()
823

824
    stream::out::fast stream{ digest };
12✔
825
    hash::sha256x2::fast sink{ stream };
12✔
826
    outputs_->at(index)->to_data(sink);
12✔
827
    sink.flush();
12✔
828
    return digest;
12✔
829
}
12✔
830

831
// private
832
hash_digest transaction::version_0_signature_hash(const input_iterator& input,
29✔
833
    const script& sub, uint64_t value, uint8_t sighash_flags,
834
    bool bip143) const NOEXCEPT
835
{
836
    // bip143/v0: the way of serialization is changed.
837
    if (!bip143)
29✔
838
        return unversioned_signature_hash(input, sub, sighash_flags);
7✔
839

840
    // Set options.
841
    const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
22✔
842
    const auto flag = mask_sighash(sighash_flags);
22✔
843
    const auto all = (flag == coverage::hash_all);
22✔
844
    const auto single = (flag == coverage::hash_single);
22✔
845

846
    // Create hash writer.
847
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
848
    hash_digest digest;
22✔
849
    BC_POP_WARNING()
850

851
    stream::out::fast stream{ digest };
22✔
852
    hash::sha256x2::fast sink{ stream };
22✔
853

854
    // Create signature hash.
855
    sink.write_little_endian(version_);
22✔
856

857
    // Conditioning points, sequences, and outputs writes on cache_ instead of
858
    // conditionally passing them from methods avoids copying the cached hash.
859

860
    // points
861
    sink.write_bytes(!anyone ? points_hash() : null_hash);
22✔
862

863
    // sequences
864
    sink.write_bytes(!anyone && all ? sequences_hash() : null_hash);
22✔
865

866
    (*input)->point().to_data(sink);
22✔
867
    sub.to_data(sink, prefixed);
22✔
868
    sink.write_little_endian(value);
22✔
869
    sink.write_little_endian((*input)->sequence());
22✔
870

871
    // outputs
872
    if (single)
22✔
873
        sink.write_bytes(output_hash(input));
14✔
874
    else
875
        sink.write_bytes(all ? outputs_hash() : null_hash);
8✔
876

877
    sink.write_little_endian(locktime_);
22✔
878
    sink.write_4_bytes_little_endian(sighash_flags);
22✔
879

880
    sink.flush();
22✔
881
    return digest;
22✔
882
}
22✔
883

884
// Signing (unversioned and version 0).
885
// ----------------------------------------------------------------------------
886

887
// ****************************************************************************
888
// CONSENSUS: sighash flags are carried in a single byte but are encoded as 4
889
// bytes in the signature hash preimage serialization.
890
// ****************************************************************************
891

892
hash_digest transaction::signature_hash(const input_iterator& input,
41✔
893
    const script& sub, uint64_t value, uint8_t sighash_flags,
894
    script_version version, bool bip143) const NOEXCEPT
895
{
896
    // There is no rational interpretation of a signature hash for a coinbase.
897
    BC_ASSERT(!is_coinbase());
41✔
898

899
    switch (version)
41✔
900
    {
901
        case script_version::unversioned:
12✔
902
            return unversioned_signature_hash(input, sub, sighash_flags);
12✔
903
        case script_version::zero:
29✔
904
            return version_0_signature_hash(input, sub, value, sighash_flags,
29✔
905
                bip143);
29✔
906
        case script_version::reserved:
×
907
        default:
×
908
            return {};
×
909
    }
910
}
911

912
// This is not used internal to the library.
913
bool transaction::check_signature(const ec_signature& signature,
2✔
914
    const data_slice& public_key, const script& sub, uint32_t index,
915
    uint64_t value, uint8_t sighash_flags, script_version version,
916
    bool bip143) const NOEXCEPT
917
{
918
    if ((index >= inputs_->size()) || signature.empty() || public_key.empty())
2✔
919
        return false;
920

921
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
922
        sighash_flags, version, bip143);
923

924
    // Validate the EC signature.
925
    return verify_signature(public_key, sighash, signature);
2✔
926
}
927

928
// This is not used internal to the library.
929
bool transaction::create_endorsement(endorsement& out, const ec_secret& secret,
2✔
930
    const script& sub, uint32_t index, uint64_t value, uint8_t sighash_flags,
931
    script_version version, bool bip143) const NOEXCEPT
932
{
933
    if (index >= inputs_->size())
2✔
934
        return false;
935

936
    out.reserve(max_endorsement_size);
2✔
937
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
938
        sighash_flags, version, bip143);
939

940
    // Create the EC signature and encode as DER.
941
    ec_signature signature;
2✔
942
    if (!sign(signature, secret, sighash) || !encode_signature(out, signature))
2✔
943
        return false;
×
944

945
    // Add the sighash type to the end of the DER signature -> endorsement.
946
    out.push_back(sighash_flags);
2✔
947
    ////out.shrink_to_fit();
948
    return true;
949
}
950

951
// Guard (context free).
952
// ----------------------------------------------------------------------------
953

954
bool transaction::is_coinbase() const NOEXCEPT
80✔
955
{
956
    return is_one(inputs_->size()) && inputs_->front()->point().is_null();
80✔
957
}
958

959
bool transaction::is_internal_double_spend() const NOEXCEPT
4✔
960
{
961
    // TODO: optimize (see block.is_internal_double_spend).
962
    return !is_distinct(points());
4✔
963
}
964

965
// TODO: a pool (non-coinbase) tx must fit into a block (with a coinbase).
966
bool transaction::is_oversized() const NOEXCEPT
×
967
{
968
    return serialized_size(false) > max_block_size;
×
969
}
970

971
// Guard (contextual).
972
// ----------------------------------------------------------------------------
973

974
// static/private
975
bool transaction::segregated(const chain::inputs& inputs) NOEXCEPT
1✔
976
{
977
    const auto witnessed = [](const auto& input) NOEXCEPT
2✔
978
    {
979
        return !input.witness().stack().empty();
1✔
980
    };
981

982
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
1✔
983
}
984

985
// static/private
986
bool transaction::segregated(const chain::input_cptrs& inputs) NOEXCEPT
905✔
987
{
988
    const auto witnessed = [](const auto& input) NOEXCEPT
908✔
989
    {
990
        return !input->witness().stack().empty();
908✔
991
    };
992

993
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
905✔
994
}
995

996
bool transaction::is_segregated() const NOEXCEPT
4✔
997
{
998
    return segregated_;
4✔
999
}
1000

1001
size_t transaction::weight() const NOEXCEPT
×
1002
{
1003
    // Block weight is 3 * base size * + 1 * total size (bip141).
1004
    return ceilinged_add(
×
1005
        ceilinged_multiply(base_size_contribution, serialized_size(false)),
1006
        ceilinged_multiply(total_size_contribution, serialized_size(true)));
×
1007
}
1008

1009
bool transaction::is_overweight() const NOEXCEPT
×
1010
{
1011
    return weight() > max_block_weight;
×
1012
}
1013

1014
//*****************************************************************************
1015
// CONSENSUS: Legacy sigops are counted in coinbase scripts despite the fact
1016
// that coinbase input scripts are never executed. There is no need to exclude
1017
// p2sh coinbase sigops since there is never a script to count.
1018
//*****************************************************************************
1019
bool transaction::is_signature_operations_limit(bool bip16,
×
1020
    bool bip141) const NOEXCEPT
1021
{
1022
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
1023
    return signature_operations(bip16, bip141) > limit;
×
1024
}
1025

1026
// Check (context free).
1027
// ----------------------------------------------------------------------------
1028

1029
bool transaction::is_empty() const NOEXCEPT
9✔
1030
{
1031
    return inputs_->empty() || outputs_->empty();
9✔
1032
}
1033

1034
bool transaction::is_null_non_coinbase() const NOEXCEPT
7✔
1035
{
1036
    BC_ASSERT(!is_coinbase());
7✔
1037

1038
    const auto invalid = [](const auto& input) NOEXCEPT
9✔
1039
    {
1040
        return input->point().is_null();
9✔
1041
    };
1042

1043
    // True if not coinbase but has null previous_output(s).
1044
    return std::any_of(inputs_->begin(), inputs_->end(), invalid);
7✔
1045
}
1046

1047
bool transaction::is_invalid_coinbase_size() const NOEXCEPT
9✔
1048
{
1049
    BC_ASSERT(is_coinbase());
9✔
1050

1051
    // True if coinbase and has invalid input[0] script size.
1052
    const auto script_size = inputs_->front()->script().serialized_size(false);
9✔
1053
    return script_size < min_coinbase_size || script_size > max_coinbase_size;
9✔
1054
}
1055

1056
// Accept (contextual).
1057
// ----------------------------------------------------------------------------
1058

1059
bool transaction::is_non_final(size_t height, uint32_t timestamp,
5✔
1060
    uint32_t median_time_past, bool bip113) const NOEXCEPT
1061
{
1062
    // BIP113: comparing the locktime against the median of the past 11 block
1063
    // timestamps, rather than the timestamp of the block including the tx.
1064
    const auto time = bip113 ? median_time_past : timestamp;
5✔
1065

1066
    const auto finalized = [](const auto& input) NOEXCEPT
2✔
1067
    {
1068
        return input->is_final();
2✔
1069
    };
1070

1071
    const auto height_time = locktime_ < locktime_threshold ? height : time;
5✔
1072

1073
    return !(is_zero(locktime_) || locktime_ < height_time ||
8✔
1074
        std::all_of(inputs_->begin(), inputs_->end(), finalized));
3✔
1075
}
1076

1077
bool transaction::is_missing_prevouts() const NOEXCEPT
3✔
1078
{
1079
    BC_ASSERT(!is_coinbase());
3✔
1080

1081
    // Null or invalid prevout indicates not found.
1082
    const auto missing = [](const auto& input) NOEXCEPT
2✔
1083
    {
1084
        return !input->prevout;
1085
    };
1086

1087
    return std::any_of(inputs_->begin(), inputs_->end(), missing);
3✔
1088
}
1089

1090
uint64_t transaction::claim() const NOEXCEPT
8✔
1091
{
1092
    // Overflow returns max_uint64.
1093
    const auto sum = [](uint64_t total, const auto& output) NOEXCEPT
8✔
1094
    {
1095
        return ceilinged_add(total, output->value());
8✔
1096
    };
1097

1098
    // The amount claimed by outputs.
1099
    return std::accumulate(outputs_->begin(), outputs_->end(), 0_u64, sum);
8✔
1100
}
1101

1102
uint64_t transaction::value() const NOEXCEPT
9✔
1103
{
1104
    // Overflow, not populated, and coinbase (default) return max_uint64.
1105
    const auto sum = [](uint64_t total, const auto& input) NOEXCEPT
7✔
1106
    {
1107
        const auto value = input->prevout ? input->prevout->value() : max_uint64;
7✔
1108
        return ceilinged_add(total, value);
7✔
1109
    };
1110

1111
    // The amount of prevouts (referenced by inputs).
1112
    return std::accumulate(inputs_->begin(), inputs_->end(), 0_u64, sum);
9✔
1113
}
1114

1115
bool transaction::is_overspent() const NOEXCEPT
2✔
1116
{
1117
    BC_ASSERT(!is_coinbase());
2✔
1118

1119
    return claim() > value();
2✔
1120
}
1121

1122
constexpr bool is_non_coinbase_mature(size_t tx_height, size_t height) NOEXCEPT
2✔
1123
{
1124
    return tx_height <= height;
2✔
1125
}
1126

1127
//*****************************************************************************
1128
// CONSENSUS: Coinbase output matures at 100 blocks depth.
1129
// CONSENSUS: Genesis coinbase is forever immature (exception).
1130
//*****************************************************************************
1131
bool transaction::is_coinbase_mature(size_t coinbase_height,
3✔
1132
    size_t height) NOEXCEPT
1133
{
1134
    return !is_zero(coinbase_height) &&
5✔
1135
        ceilinged_add(coinbase_height, coinbase_maturity) <= height;
3✔
1136
}
1137

1138
bool transaction::is_immature(size_t height) const NOEXCEPT
6✔
1139
{
1140
    BC_ASSERT(!is_coinbase());
6✔
1141

1142
    // Spends internal to a block are handled by block validation.
1143
    const auto mature = [=](const auto& input) NOEXCEPT
5✔
1144
    {
1145
        return input->metadata.coinbase ?
5✔
1146
            is_coinbase_mature(input->metadata.height, height) :
3✔
1147
            is_non_coinbase_mature(input->metadata.height, height);
2✔
1148
    };
6✔
1149

1150
    return !std::all_of(inputs_->begin(), inputs_->end(), mature);
6✔
1151
}
1152

1153
bool transaction::is_internal_lock(const input& in) const NOEXCEPT
×
1154
{
1155
    // BIP68: not applied to the sequence of the input of a coinbase.
1156
    BC_ASSERT(!is_coinbase());
×
1157

1158
    // BIP68: applied to txs with a version greater than or equal to two.
1159
    if (version_ < relative_locktime_min_version)
×
1160
        return false;
1161

1162
    return in.is_internal_lock();
×
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
3✔
1209
    {
1210
        return input->metadata.spent && height > input->metadata.height;
3✔
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
5✔
1266
{
1267
    const auto coinbase = is_coinbase();
5✔
1268

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

1276
    return error::transaction_success;
5✔
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
    };
6✔
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

© 2025 Coveralls, Inc