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

libbitcoin / libbitcoin-system / 14434326165

13 Apr 2025 11:21PM UTC coverage: 82.798% (-0.1%) from 82.939%
14434326165

push

github

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

Move golomb_coding from /crypto to new /filter folder.

62 of 64 new or added lines in 13 files covered. (96.88%)

32 existing lines in 9 files now uncovered.

10190 of 12307 relevant lines covered (82.8%)

3818174.07 hits per line

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

76.67
/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 inputs_cptr& inputs,
905✔
96
    const 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(stream::in::fast&& stream, bool witness) NOEXCEPT
41✔
102
  : transaction(read::bytes::fast(stream), witness)
41✔
103
{
104
}
41✔
105

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

UNCOV
111
transaction::transaction(std::istream&& stream, bool witness) NOEXCEPT
×
UNCOV
112
  : transaction(read::bytes::istream(stream), witness)
×
113
{
UNCOV
114
}
×
115

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

121
transaction::transaction(reader&& source, bool witness) NOEXCEPT
47✔
122
  : transaction(source, witness)
47✔
123
{
124
}
×
125

126
transaction::transaction(reader& source, bool witness) NOEXCEPT
204✔
127
  : version_(source.read_4_bytes_little_endian()),
408✔
128
    inputs_(CREATE(input_cptrs, source.get_allocator())),
204✔
129
    outputs_(CREATE(output_cptrs, source.get_allocator()))
612✔
130
{
131
    assign_data(source, witness);
204✔
132
}
204✔
133

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

148
// Operators.
149
// ----------------------------------------------------------------------------
150

151
bool transaction::operator==(const transaction& other) const NOEXCEPT
60✔
152
{
153
    // Compares input/output elements, not pointers, cache not compared.
154
    return (version_ == other.version_)
60✔
155
        && (locktime_ == other.locktime_)
58✔
156
        && ((inputs_ == other.inputs_) || 
84✔
157
            deep_equal(*inputs_, *other.inputs_))
26✔
158
        && ((outputs_ == other.outputs_) ||
144✔
159
            deep_equal(*outputs_, *other.outputs_));
26✔
160
}
161

162
bool transaction::operator!=(const transaction& other) const NOEXCEPT
2✔
163
{
164
    return !(*this == other);
2✔
165
}
166

167
// Deserialization.
168
// ----------------------------------------------------------------------------
169

170
// private
171
BC_PUSH_WARNING(NO_UNGUARDED_POINTERS)
172
void transaction::assign_data(reader& source, bool witness) NOEXCEPT
204✔
173
{
174
    auto& allocator = source.get_allocator();
204✔
175
    auto ins = to_non_const_raw_ptr(inputs_);
204✔
176
    auto count = source.read_size(max_block_size);
204✔
177
    ins->reserve(count);
204✔
178
    for (size_t in = 0; in < count; ++in)
453✔
179
        ins->emplace_back(CREATE(input, allocator, source));
249✔
180

181
    // Expensive repeated recomputation, so cache segregated state.
182
    // Detect witness as no inputs (marker) and expected flag (bip144).
183
    segregated_ = 
204✔
184
        inputs_->size() == witness_marker &&
220✔
185
        source.peek_byte() == witness_enabled;
16✔
186

187
    if (segregated_)
204✔
188
    {
189
        // Skip over the peeked witness flag.
190
        source.skip_byte();
16✔
191

192
        count = source.read_size(max_block_size);
16✔
193
        ins->reserve(count);
16✔
194
        for (size_t in = 0; in < count; ++in)
37✔
195
            ins->emplace_back(CREATE(input, allocator, source));
21✔
196

197
        auto outs = to_non_const_raw_ptr(outputs_);
16✔
198
        count = source.read_size(max_block_size);
16✔
199
        outs->reserve(count);
16✔
200
        for (size_t out = 0; out < count; ++out)
41✔
201
            outs->emplace_back(CREATE(output, allocator, source));
25✔
202

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

225
    locktime_ = source.read_4_bytes_little_endian();
204✔
226
    size_ = serialized_size(*inputs_, *outputs_, segregated_);
204✔
227
    valid_ = source;
204✔
228
}
204✔
229
BC_POP_WARNING()
230

231
// Serialization.
232
// ----------------------------------------------------------------------------
233

234
// Transactions with empty witnesses always use old serialization (bip144).
235
// If no inputs are witness programs then witness hash is tx hash (bip141).
236
data_chunk transaction::to_data(bool witness) const NOEXCEPT
10✔
237
{
238
    witness &= segregated_;
10✔
239

240
    data_chunk data(serialized_size(witness));
10✔
241
    stream::out::fast ostream(data);
10✔
242
    write::bytes::fast out(ostream);
10✔
243
    to_data(out, witness);
10✔
244
    return data;
10✔
245
}
10✔
246

247
void transaction::to_data(std::ostream& stream, bool witness) const NOEXCEPT
1✔
248
{
249
    witness &= segregated_;
1✔
250

251
    write::bytes::ostream out(stream);
1✔
252
    to_data(out, witness);
1✔
253
}
1✔
254

255
void transaction::to_data(writer& sink, bool witness) const NOEXCEPT
966✔
256
{
257
    witness &= segregated_;
966✔
258

259
    sink.write_4_bytes_little_endian(version_);
966✔
260

261
    if (witness)
966✔
262
    {
263
        sink.write_byte(witness_marker);
2✔
264
        sink.write_byte(witness_enabled);
2✔
265
    }
266

267
    sink.write_variable(inputs_->size());
966✔
268
    for (const auto& input: *inputs_)
2,352✔
269
        input->to_data(sink);
1,386✔
270

271
    sink.write_variable(outputs_->size());
966✔
272
    for (const auto& output: *outputs_)
2,634✔
273
        output->to_data(sink);
1,668✔
274

275
    if (witness)
966✔
276
        for (auto& input: *inputs_)
5✔
277
            input->witness().to_data(sink, true);
3✔
278

279
    sink.write_4_bytes_little_endian(locktime_);
966✔
280
}
966✔
281

282
// static/private
283
transaction::sizes transaction::serialized_size(const input_cptrs& inputs,
1,131✔
284
    const output_cptrs& outputs, bool segregated) NOEXCEPT
285
{
286
    sizes size{ zero, zero };
1,131✔
287

288
    std::for_each(inputs.begin(), inputs.end(), [&](const auto& in) NOEXCEPT
2,314✔
289
    {
290
        size.nominal = ceilinged_add(size.nominal, in->nominal_size());
1,183✔
291
        if (segregated)
1,183✔
292
            size.witnessed = ceilinged_add(size.witnessed, in->witnessed_size());
64✔
293
    });
1,183✔
294

295
    const auto outs = [](size_t total, const auto& output) NOEXCEPT
394✔
296
    {
297
        return ceilinged_add(total, output->serialized_size());
394✔
298
    };
299

300
    constexpr auto base_const_size = ceilinged_add(sizeof(version_),
1,131✔
301
        sizeof(locktime_));
302
    constexpr auto witness_const_size = ceilinged_add(sizeof(witness_marker),
1,131✔
303
        sizeof(witness_enabled));
304

305
    const auto base_size = ceilinged_add(ceilinged_add(ceilinged_add(
1,131✔
306
        base_const_size, variable_size(inputs.size())),
307
        variable_size(outputs.size())),
308
        std::accumulate(outputs.begin(), outputs.end(), zero, outs));
309
    const auto nominal_size = ceilinged_add(base_size, size.nominal);
1,131✔
310

311
    // witnessed_size is nominal_size for non-segregated transactions.
312
    const auto witnessed_size = segregated ? ceilinged_add(ceilinged_add(
1,131✔
313
        base_size, witness_const_size), size.witnessed) : nominal_size;
314

315
    // Values are the same for non-segregated transactions.
316
    return { nominal_size, witnessed_size };
1,131✔
317
}
318

319
size_t transaction::serialized_size(bool witness) const NOEXCEPT
613✔
320
{
321
    witness &= segregated_;
613✔
322

323
    return witness ? size_.witnessed : size_.nominal;
613✔
324
}
325

326
// Properties.
327
// ----------------------------------------------------------------------------
328

329
bool transaction::is_valid() const NOEXCEPT
777✔
330
{
331
    return valid_;
777✔
332
}
333

334
size_t transaction::spends() const NOEXCEPT
×
335
{
336
    return is_coinbase() ? zero : inputs_->size();
×
337
}
338

339
size_t transaction::inputs() const NOEXCEPT
1,569✔
340
{
341
    return inputs_->size();
1,569✔
342
}
343

344
size_t transaction::outputs() const NOEXCEPT
1✔
345
{
346
    return outputs_->size();
1✔
347
}
348

349
uint32_t transaction::version() const NOEXCEPT
6✔
350
{
351
    return version_;
4✔
352
}
353

354
uint32_t transaction::locktime() const NOEXCEPT
13✔
355
{
356
    return locktime_;
4✔
357
}
358

359
const inputs_cptr& transaction::inputs_ptr() const NOEXCEPT
2,446✔
360
{
361
    return inputs_;
2,446✔
362
}
363

364
const outputs_cptr& transaction::outputs_ptr() const NOEXCEPT
62✔
365
{
366
    return outputs_;
62✔
367
}
368

369
uint64_t transaction::fee() const NOEXCEPT
4✔
370
{
371
    // Underflow returns zero (and is_overspent() will be true).
372
    // This is value of prevouts spent by inputs minus that claimed by outputs.
373
    return floored_subtract(value(), claim());
4✔
374
}
375

376
void transaction::set_nominal_hash(const hash_digest& hash) const NOEXCEPT
20✔
377
{
378
    nominal_hash_ = hash;
20✔
379
}
1✔
380

381
void transaction::set_witness_hash(const hash_digest& hash) const NOEXCEPT
2✔
382
{
383
    witness_hash_ = hash;
2✔
384
}
1✔
385

386
const hash_digest& transaction::get_hash(bool witness) const NOEXCEPT
26✔
387
{
388
    if (witness)
26✔
389
    {
390
        if (!witness_hash_) set_witness_hash(hash(witness));
4✔
391
        return *witness_hash_;
3✔
392
    }
393
    else
394
    {
395
        if (!nominal_hash_) set_nominal_hash(hash(witness));
42✔
396
        return *nominal_hash_;
23✔
397
    }
398
}
399

400
hash_digest transaction::hash(bool witness) const NOEXCEPT
934✔
401
{
402
    if (segregated_)
934✔
403
    {
404
        if (witness)
23✔
405
        {
406
            // Witness coinbase tx hash is assumed to be null_hash (bip141).
407
            if (witness_hash_) return *witness_hash_;
×
408
            if (is_coinbase()) return null_hash;
×
409
        }
410
        else
411
        {
412
            if (nominal_hash_) return *nominal_hash_;
23✔
413
        }
414
    }
415
    else
416
    {
417
        if (nominal_hash_) return *nominal_hash_;
911✔
418
    }
419

420
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
421
    hash_digest digest;
927✔
422
    BC_POP_WARNING()
423

424
    stream::out::fast stream{ digest };
927✔
425
    hash::sha256x2::fast sink{ stream };
927✔
426
    to_data(sink, witness);
927✔
427
    sink.flush();
927✔
428
    return digest;
927✔
429
}
927✔
430

431
// static
432
hash_digest transaction::desegregated_hash(size_t witnessed,
×
433
    size_t unwitnessed, const uint8_t* data) NOEXCEPT
434
{
435
    if (is_null(data))
×
436
        return null_hash;
×
437

438
    constexpr auto preamble = sizeof(uint32_t) + two * sizeof(uint8_t);
×
439
    const auto puts = floored_subtract(unwitnessed, two * sizeof(uint32_t));
×
440
    const auto locktime = floored_subtract(witnessed, sizeof(uint32_t));
×
441

442
    hash_digest digest{};
×
443
    stream::out::fast stream{ digest };
×
444
    hash::sha256x2::fast sink{ stream };
×
445
    sink.write_bytes(data, sizeof(uint32_t));
×
446
    sink.write_bytes(std::next(data, preamble), puts);
×
447
    sink.write_bytes(std::next(data, locktime), sizeof(uint32_t));
×
448
    sink.flush();
×
449
    return digest;
×
450
}
×
451

452
// Methods.
453
// ----------------------------------------------------------------------------
454

455
bool transaction::is_dusty(uint64_t minimum_output_value) const NOEXCEPT
6✔
456
{
457
    const auto dusty = [=](const auto& output) NOEXCEPT
9✔
458
    {
459
        return output->is_dust(minimum_output_value);
9✔
460
    };
6✔
461

462
    return std::any_of(outputs_->begin(), outputs_->end(), dusty);
6✔
463
}
464

465
size_t transaction::signature_operations(bool bip16, bool bip141) const NOEXCEPT
1✔
466
{
467
    // Includes BIP16 p2sh additional sigops, max_size_t if prevout invalid.
468
    const auto in = [=](size_t total, const auto& input) NOEXCEPT
×
469
    {
470
        return ceilinged_add(total, input->signature_operations(bip16, bip141));
×
471
    };
1✔
472

473
    const auto out = [=](size_t total, const auto& output) NOEXCEPT
×
474
    {
475
        return ceilinged_add(total, output->signature_operations(bip141));
×
476
    };
1✔
477

478
    // Overflow returns max_size_t.
479
    return ceilinged_add(
1✔
480
        std::accumulate(inputs_->begin(), inputs_->end(), zero, in),
481
        std::accumulate(outputs_->begin(), outputs_->end(), zero, out));
1✔
482
}
483

484
chain::points transaction::points() const NOEXCEPT
4✔
485
{
486
    chain::points out(inputs_->size());
4✔
487

488
    const auto point = [](const auto& input) NOEXCEPT
8✔
489
    {
490
        return input->point();
8✔
491
    };
492

493
    std::transform(inputs_->begin(), inputs_->end(), out.begin(), point);
4✔
494
    return out;
4✔
495
}
×
496

497
hash_digest transaction::outputs_hash() const NOEXCEPT
8✔
498
{
499
    if (sighash_cache_)
8✔
500
        return sighash_cache_->outputs;
×
501

502
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
503
    hash_digest digest;
8✔
504
    BC_POP_WARNING()
505
        
506
    stream::out::fast stream{ digest };
8✔
507
    hash::sha256x2::fast sink{ stream };
8✔
508

509
    for (const auto& output: *outputs_)
22✔
510
        output->to_data(sink);
14✔
511

512
    sink.flush();
8✔
513
    return digest;
8✔
514
}
8✔
515

516
hash_digest transaction::points_hash() const NOEXCEPT
11✔
517
{
518
    if (sighash_cache_)
11✔
519
        return sighash_cache_->points;
×
520

521
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
522
    hash_digest digest;
11✔
523
    BC_POP_WARNING()
524

525
    stream::out::fast stream{ digest };
11✔
526
    hash::sha256x2::fast sink{ stream };
11✔
527

528
    for (const auto& input: *inputs_)
27✔
529
        input->point().to_data(sink);
16✔
530

531
    sink.flush();
11✔
532
    return digest;
11✔
533
}
11✔
534

535
hash_digest transaction::sequences_hash() const NOEXCEPT
7✔
536
{
537
    if (sighash_cache_)
7✔
538
        return sighash_cache_->sequences;
×
539

540
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
541
    hash_digest digest;
7✔
542
    BC_POP_WARNING()
543

544
    stream::out::fast stream{ digest };
7✔
545
    hash::sha256x2::fast sink{ stream };
7✔
546

547
    for (const auto& input: *inputs_)
17✔
548
        sink.write_4_bytes_little_endian(input->sequence());
10✔
549

550
    sink.flush();
7✔
551
    return digest;
7✔
552
}
7✔
553

554
// Signing (unversioned).
555
// ----------------------------------------------------------------------------
556

557
// private
558
transaction::input_iterator transaction::input_at(
4✔
559
    uint32_t index) const NOEXCEPT
560
{
561
    // Guarded by check_signature and create_endorsement.
562
    BC_ASSERT_MSG(index < inputs_->size(), "invalid input index");
4✔
563

564
    return std::next(inputs_->begin(), index);
4✔
565
}
566

567
// private
568
uint32_t transaction::input_index(const input_iterator& input) const NOEXCEPT
25✔
569
{
570
    // Guarded by unversioned_signature_hash and output_hash.
571
    BC_ASSERT_MSG(inputs_->begin() != inputs_->end(), "invalid input iterator");
25✔
572

573
    return possible_narrow_and_sign_cast<uint32_t>(
25✔
574
        std::distance(inputs_->begin(), input));
×
575
}
576

577
//*****************************************************************************
578
// CONSENSUS: Due to masking of bits 6/7 (8 is the anyone_can_pay flag),
579
// there are 4 possible 7 bit values that can set "single" and 4 others that
580
// can set none, and yet all other values set "all".
581
//*****************************************************************************
582
inline coverage mask_sighash(uint8_t sighash_flags) NOEXCEPT
41✔
583
{
584
    switch (sighash_flags & coverage::mask)
41✔
585
    {
586
        case coverage::hash_single:
587
            return coverage::hash_single;
588
        case coverage::hash_none:
2✔
589
            return coverage::hash_none;
2✔
590
        default:
18✔
591
            return coverage::hash_all;
18✔
592
    }
593
}
594

595
void transaction::signature_hash_single(writer& sink,
4✔
596
    const input_iterator& input, const script& sub,
597
    uint8_t sighash_flags) const NOEXCEPT
598
{
599
    const auto write_inputs = [this, &input, &sub, sighash_flags](
8✔
600
        writer& sink) NOEXCEPT
601
    {
602
        const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
4✔
603
        input_cptrs::const_iterator in;
4✔
604

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

607
        for (in = inputs_->begin(); !anyone && in != input; ++in)
4✔
608
        {
609
            (*in)->point().to_data(sink);
×
610
            sink.write_bytes(empty_script());
×
611
            sink.write_bytes(zero_sequence());
×
612
        }
613

614
        (*input)->point().to_data(sink);
4✔
615
        sub.to_data(sink, prefixed);
4✔
616
        sink.write_4_bytes_little_endian((*input)->sequence());
4✔
617

618
        for (++in; !anyone && in != inputs_->end(); ++in)
5✔
619
        {
620
            (*in)->point().to_data(sink);
1✔
621
            sink.write_bytes(empty_script());
1✔
622
            sink.write_bytes(zero_sequence());
1✔
623
        }
624
    };
4✔
625

626
    const auto write_outputs = [this, &input](writer& sink) NOEXCEPT
8✔
627
    {
628
        const auto index = input_index(input);
4✔
629

630
        sink.write_variable(add1(index));
4✔
631

632
        for (size_t output = 0; output < index; ++output)
5✔
633
            sink.write_bytes(null_output());
1✔
634

635
        // Guarded by unversioned_signature_hash.
636
        outputs_->at(index)->to_data(sink);
4✔
637
    };
8✔
638

639
    sink.write_4_bytes_little_endian(version_);
4✔
640
    write_inputs(sink);
4✔
641
    write_outputs(sink);
4✔
642
    sink.write_4_bytes_little_endian(locktime_);
4✔
643
    sink.write_4_bytes_little_endian(sighash_flags);
4✔
644
}
4✔
645

646
void transaction::signature_hash_none(writer& sink,
×
647
    const input_iterator& input, const script& sub,
648
    uint8_t sighash_flags) const NOEXCEPT
649
{
650
    const auto write_inputs = [this, &input, &sub, sighash_flags](
×
651
        writer& sink) NOEXCEPT
652
    {
653
        const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
×
654
        input_cptrs::const_iterator in;
×
655

656
        sink.write_variable(anyone ? one : inputs_->size());
×
657

658
        for (in = inputs_->begin(); !anyone && in != input; ++in)
×
659
        {
660
            (*in)->point().to_data(sink);
×
661
            sink.write_bytes(empty_script());
×
662
            sink.write_bytes(zero_sequence());
×
663
        }
664

665
        (*input)->point().to_data(sink);
×
666
        sub.to_data(sink, prefixed);
×
667
        sink.write_4_bytes_little_endian((*input)->sequence());
×
668

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

677
    sink.write_4_bytes_little_endian(version_);
×
678
    write_inputs(sink);
×
679
    sink.write_variable(zero);
×
680
    sink.write_4_bytes_little_endian(locktime_);
×
681
    sink.write_4_bytes_little_endian(sighash_flags);
×
682
}
×
683

684
void transaction::signature_hash_all(writer& sink,
12✔
685
    const input_iterator& input, const script& sub,
686
    uint8_t flags) const NOEXCEPT
687
{
688
    const auto write_inputs = [this, &input, &sub, flags](
24✔
689
        writer& sink) NOEXCEPT
690
    {
691
        const auto anyone = to_bool(flags & coverage::anyone_can_pay);
12✔
692
        input_cptrs::const_iterator in;
12✔
693

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

696
        for (in = inputs_->begin(); !anyone && in != input; ++in)
15✔
697
        {
698
            (*in)->point().to_data(sink);
3✔
699
            sink.write_bytes(empty_script());
3✔
700
            sink.write_4_bytes_little_endian((*in)->sequence());
3✔
701
        }
702

703
        (*input)->point().to_data(sink);
12✔
704
        sub.to_data(sink, prefixed);
12✔
705
        sink.write_4_bytes_little_endian((*input)->sequence());
12✔
706

707
        for (++in; !anyone && in != inputs_->end(); ++in)
16✔
708
        {
709
            (*in)->point().to_data(sink);
4✔
710
            sink.write_bytes(empty_script());
4✔
711
            sink.write_4_bytes_little_endian((*in)->sequence());
4✔
712
        }
713
    };
12✔
714

715
    const auto write_outputs = [this](writer& sink) NOEXCEPT
24✔
716
    {
717
        sink.write_variable(outputs_->size());
12✔
718
        for (const auto& output: *outputs_)
27✔
719
            output->to_data(sink);
15✔
720
    };
24✔
721

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

729
// private
730
hash_digest transaction::unversioned_signature_hash(
19✔
731
    const input_iterator& input, const script& sub,
732
    uint8_t sighash_flags) const NOEXCEPT
733
{
734
    // Set options.
735
    const auto flag = mask_sighash(sighash_flags);
19✔
736

737
    // Create hash writer.
738
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
739
    hash_digest digest;
19✔
740
    BC_POP_WARNING()
741

742
    stream::out::fast stream{ digest };
19✔
743
    hash::sha256x2::fast sink{ stream };
19✔
744

745
    switch (flag)
19✔
746
    {
747
        case coverage::hash_single:
7✔
748
        {
7✔
749
            //*****************************************************************
750
            // CONSENSUS: return one_hash if index exceeds outputs in sighash.
751
            // Related Bug: bitcointalk.org/index.php?topic=260595
752
            // Exploit: joncave.co.uk/2014/08/bitcoin-sighash-single/
753
            //*****************************************************************
754
            if (input_index(input) >= outputs_->size())
7✔
755
                return one_hash;
3✔
756

757
            signature_hash_single(sink, input, sub, sighash_flags);
4✔
758
            break;
759
        }
760
        case coverage::hash_none:
×
761
        {
×
762
            signature_hash_none(sink, input, sub, sighash_flags);
×
763
            break;
764
        }
765
        default:
12✔
766
        case coverage::hash_all:
12✔
767
        {
12✔
768
            signature_hash_all(sink, input, sub, sighash_flags);
12✔
769
        }
770
    }
771

772
    sink.flush();
16✔
773
    return digest;
16✔
774
}
19✔
775

776
// Signing (version 0).
777
// ----------------------------------------------------------------------------
778

779
// private
780
// TODO: taproot requires both single and double hash of each.
781
void transaction::initialize_sighash_cache() const NOEXCEPT
2✔
782
{
783
    // C++23: std::optional<T>::or_else.
784
    if (!segregated_)
2✔
785
        return;
786

787
    // This overconstructs the cache (anyone or !all), however it is simple.
788
    sighash_cache_ =
2✔
789
    {
790
        outputs_hash(),
2✔
791
        points_hash(),
2✔
792
        sequences_hash()
2✔
793
    };
2✔
794
}
795

796
// private
797
hash_digest transaction::output_hash(const input_iterator& input) const NOEXCEPT
14✔
798
{
799
    const auto index = input_index(input);
14✔
800

801
    //*************************************************************************
802
    // CONSENSUS: if index exceeds outputs in signature hash, return null_hash.
803
    //*************************************************************************
804
    if (index >= outputs_->size())
14✔
805
        return null_hash;
2✔
806

807
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
808
    hash_digest digest;
12✔
809
    BC_POP_WARNING()
810

811
    stream::out::fast stream{ digest };
12✔
812
    hash::sha256x2::fast sink{ stream };
12✔
813
    outputs_->at(index)->to_data(sink);
12✔
814
    sink.flush();
12✔
815
    return digest;
12✔
816
}
12✔
817

818
// private
819
hash_digest transaction::version_0_signature_hash(const input_iterator& input,
29✔
820
    const script& sub, uint64_t value, uint8_t sighash_flags,
821
    bool bip143) const NOEXCEPT
822
{
823
    // bip143/v0: the way of serialization is changed.
824
    if (!bip143)
29✔
825
        return unversioned_signature_hash(input, sub, sighash_flags);
7✔
826

827
    // Set options.
828
    const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
22✔
829
    const auto flag = mask_sighash(sighash_flags);
22✔
830
    const auto all = (flag == coverage::hash_all);
22✔
831
    const auto single = (flag == coverage::hash_single);
22✔
832

833
    // Create hash writer.
834
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
835
    hash_digest digest;
22✔
836
    BC_POP_WARNING()
837

838
    stream::out::fast stream{ digest };
22✔
839
    hash::sha256x2::fast sink{ stream };
22✔
840

841
    // Create signature hash.
842
    sink.write_little_endian(version_);
22✔
843

844
    // Conditioning points, sequences, and outputs writes on cache_ instead of
845
    // conditionally passing them from methods avoids copying the cached hash.
846

847
    // points
848
    sink.write_bytes(!anyone ? points_hash() : null_hash);
22✔
849

850
    // sequences
851
    sink.write_bytes(!anyone && all ? sequences_hash() : null_hash);
22✔
852

853
    (*input)->point().to_data(sink);
22✔
854
    sub.to_data(sink, prefixed);
22✔
855
    sink.write_little_endian(value);
22✔
856
    sink.write_little_endian((*input)->sequence());
22✔
857

858
    // outputs
859
    if (single)
22✔
860
        sink.write_bytes(output_hash(input));
14✔
861
    else
862
        sink.write_bytes(all ? outputs_hash() : null_hash);
8✔
863

864
    sink.write_little_endian(locktime_);
22✔
865
    sink.write_4_bytes_little_endian(sighash_flags);
22✔
866

867
    sink.flush();
22✔
868
    return digest;
22✔
869
}
22✔
870

871
// Signing (unversioned and version 0).
872
// ----------------------------------------------------------------------------
873

874
// ****************************************************************************
875
// CONSENSUS: sighash flags are carried in a single byte but are encoded as 4
876
// bytes in the signature hash preimage serialization.
877
// ****************************************************************************
878

879
hash_digest transaction::signature_hash(const input_iterator& input,
41✔
880
    const script& sub, uint64_t value, uint8_t sighash_flags,
881
    script_version version, bool bip143) const NOEXCEPT
882
{
883
    // There is no rational interpretation of a signature hash for a coinbase.
884
    BC_ASSERT(!is_coinbase());
41✔
885

886
    switch (version)
41✔
887
    {
888
        case script_version::unversioned:
12✔
889
            return unversioned_signature_hash(input, sub, sighash_flags);
12✔
890
        case script_version::zero:
29✔
891
            return version_0_signature_hash(input, sub, value, sighash_flags,
29✔
892
                bip143);
29✔
893
        case script_version::reserved:
×
894
        default:
×
895
            return {};
×
896
    }
897
}
898

899
// This is not used internal to the library.
900
bool transaction::check_signature(const ec_signature& signature,
2✔
901
    const data_slice& public_key, const script& sub, uint32_t index,
902
    uint64_t value, uint8_t sighash_flags, script_version version,
903
    bool bip143) const NOEXCEPT
904
{
905
    if ((index >= inputs_->size()) || signature.empty() || public_key.empty())
2✔
906
        return false;
907

908
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
909
        sighash_flags, version, bip143);
910

911
    // Validate the EC signature.
912
    return verify_signature(public_key, sighash, signature);
2✔
913
}
914

915
// This is not used internal to the library.
916
bool transaction::create_endorsement(endorsement& out, const ec_secret& secret,
2✔
917
    const script& sub, uint32_t index, uint64_t value, uint8_t sighash_flags,
918
    script_version version, bool bip143) const NOEXCEPT
919
{
920
    if (index >= inputs_->size())
2✔
921
        return false;
922

923
    out.reserve(max_endorsement_size);
2✔
924
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
925
        sighash_flags, version, bip143);
926

927
    // Create the EC signature and encode as DER.
928
    ec_signature signature;
2✔
929
    if (!sign(signature, secret, sighash) || !encode_signature(out, signature))
2✔
930
        return false;
×
931

932
    // Add the sighash type to the end of the DER signature -> endorsement.
933
    out.push_back(sighash_flags);
2✔
934
    ////out.shrink_to_fit();
935
    return true;
936
}
937

938
// Guard (context free).
939
// ----------------------------------------------------------------------------
940

941
bool transaction::is_coinbase() const NOEXCEPT
80✔
942
{
943
    return is_one(inputs_->size()) && inputs_->front()->point().is_null();
80✔
944
}
945

946
bool transaction::is_internal_double_spend() const NOEXCEPT
4✔
947
{
948
    // TODO: optimize (see block.is_internal_double_spend).
949
    return !is_distinct(points());
4✔
950
}
951

952
// TODO: a pool (non-coinbase) tx must fit into a block (with a coinbase).
953
bool transaction::is_oversized() const NOEXCEPT
×
954
{
955
    return serialized_size(false) > max_block_size;
×
956
}
957

958
// Guard (contextual).
959
// ----------------------------------------------------------------------------
960

961
// static/private
962
bool transaction::segregated(const chain::inputs& inputs) NOEXCEPT
1✔
963
{
964
    const auto witnessed = [](const auto& input) NOEXCEPT
2✔
965
    {
966
        return !input.witness().stack().empty();
1✔
967
    };
968

969
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
1✔
970
}
971

972
// static/private
973
bool transaction::segregated(const input_cptrs& inputs) NOEXCEPT
905✔
974
{
975
    const auto witnessed = [](const auto& input) NOEXCEPT
908✔
976
    {
977
        return !input->witness().stack().empty();
908✔
978
    };
979

980
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
905✔
981
}
982

983
bool transaction::is_segregated() const NOEXCEPT
4✔
984
{
985
    return segregated_;
4✔
986
}
987

988
size_t transaction::weight() const NOEXCEPT
×
989
{
990
    // Block weight is 3 * base size * + 1 * total size (bip141).
991
    return ceilinged_add(
×
992
        ceilinged_multiply(base_size_contribution, serialized_size(false)),
993
        ceilinged_multiply(total_size_contribution, serialized_size(true)));
×
994
}
995

996
bool transaction::is_overweight() const NOEXCEPT
×
997
{
998
    return weight() > max_block_weight;
×
999
}
1000

1001
//*****************************************************************************
1002
// CONSENSUS: Legacy sigops are counted in coinbase scripts despite the fact
1003
// that coinbase input scripts are never executed. There is no need to exclude
1004
// p2sh coinbase sigops since there is never a script to count.
1005
//*****************************************************************************
1006
bool transaction::is_signature_operations_limit(bool bip16,
×
1007
    bool bip141) const NOEXCEPT
1008
{
1009
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
1010
    return signature_operations(bip16, bip141) > limit;
×
1011
}
1012

1013
// Check (context free).
1014
// ----------------------------------------------------------------------------
1015

1016
bool transaction::is_empty() const NOEXCEPT
9✔
1017
{
1018
    return inputs_->empty() || outputs_->empty();
9✔
1019
}
1020

1021
bool transaction::is_null_non_coinbase() const NOEXCEPT
7✔
1022
{
1023
    BC_ASSERT(!is_coinbase());
7✔
1024

1025
    const auto invalid = [](const auto& input) NOEXCEPT
9✔
1026
    {
1027
        return input->point().is_null();
9✔
1028
    };
1029

1030
    // True if not coinbase but has null previous_output(s).
1031
    return std::any_of(inputs_->begin(), inputs_->end(), invalid);
7✔
1032
}
1033

1034
bool transaction::is_invalid_coinbase_size() const NOEXCEPT
9✔
1035
{
1036
    BC_ASSERT(is_coinbase());
9✔
1037

1038
    // True if coinbase and has invalid input[0] script size.
1039
    const auto script_size = inputs_->front()->script().serialized_size(false);
9✔
1040
    return script_size < min_coinbase_size || script_size > max_coinbase_size;
9✔
1041
}
1042

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

1046
bool transaction::is_absolute_locked(size_t height, uint32_t timestamp,
5✔
1047
    uint32_t median_time_past, bool bip113) const NOEXCEPT
1048
{
1049
    // BIP113: comparing the locktime against the median of the past 11 block
1050
    // timestamps, rather than the timestamp of the block including the tx.
1051
    const auto time = bip113 ? median_time_past : timestamp;
5✔
1052

1053
    const auto finalized = [](const auto& input) NOEXCEPT
2✔
1054
    {
1055
        return input->is_final();
2✔
1056
    };
1057

1058
    const auto height_time = locktime_ < locktime_threshold ? height : time;
5✔
1059

1060
    return !(is_zero(locktime_) || locktime_ < height_time ||
8✔
1061
        std::all_of(inputs_->begin(), inputs_->end(), finalized));
3✔
1062
}
1063

1064
bool transaction::is_missing_prevouts() const NOEXCEPT
3✔
1065
{
1066
    BC_ASSERT(!is_coinbase());
3✔
1067

1068
    // Null or invalid prevout indicates not found.
1069
    const auto missing = [](const auto& input) NOEXCEPT
2✔
1070
    {
1071
        return !input->prevout;
1072
    };
1073

1074
    return std::any_of(inputs_->begin(), inputs_->end(), missing);
3✔
1075
}
1076

1077
uint64_t transaction::claim() const NOEXCEPT
8✔
1078
{
1079
    // Overflow returns max_uint64.
1080
    const auto sum = [](uint64_t total, const auto& output) NOEXCEPT
8✔
1081
    {
1082
        return ceilinged_add(total, output->value());
8✔
1083
    };
1084

1085
    // The amount claimed by outputs.
1086
    return std::accumulate(outputs_->begin(), outputs_->end(), 0_u64, sum);
8✔
1087
}
1088

1089
uint64_t transaction::value() const NOEXCEPT
9✔
1090
{
1091
    // Overflow, not populated, and coinbase (default) return max_uint64.
1092
    const auto sum = [](uint64_t total, const auto& input) NOEXCEPT
7✔
1093
    {
1094
        const auto value = input->prevout ? input->prevout->value() : max_uint64;
7✔
1095
        return ceilinged_add(total, value);
7✔
1096
    };
1097

1098
    // The amount of prevouts (referenced by inputs).
1099
    return std::accumulate(inputs_->begin(), inputs_->end(), 0_u64, sum);
9✔
1100
}
1101

1102
bool transaction::is_overspent() const NOEXCEPT
2✔
1103
{
1104
    BC_ASSERT(!is_coinbase());
2✔
1105

1106
    return claim() > value();
2✔
1107
}
1108

1109
constexpr bool is_non_coinbase_mature(size_t tx_height, size_t height) NOEXCEPT
2✔
1110
{
1111
    return tx_height <= height;
2✔
1112
}
1113

1114
// static
1115
//*****************************************************************************
1116
// CONSENSUS: Coinbase output matures at 100 blocks depth.
1117
// CONSENSUS: Genesis coinbase is forever immature (exception).
1118
//*****************************************************************************
1119
bool transaction::is_coinbase_mature(size_t coinbase_height,
3✔
1120
    size_t height) NOEXCEPT
1121
{
1122
    return !is_zero(coinbase_height) &&
5✔
1123
        ceilinged_add(coinbase_height, coinbase_maturity) <= height;
3✔
1124
}
1125

1126
bool transaction::is_immature(size_t height) const NOEXCEPT
6✔
1127
{
1128
    BC_ASSERT(!is_coinbase());
6✔
1129

1130
    // Spends internal to a block are handled by block validation.
1131
    const auto mature = [=](const auto& input) NOEXCEPT
5✔
1132
    {
1133
        return input->metadata.coinbase ?
5✔
1134
            is_coinbase_mature(input->metadata.height, height) :
3✔
1135
            is_non_coinbase_mature(input->metadata.height, height);
2✔
1136
    };
6✔
1137

1138
    return !std::all_of(inputs_->begin(), inputs_->end(), mature);
6✔
1139
}
1140

1141
// static
1142
bool transaction::is_relative_locktime_applied(bool coinbase, uint32_t version,
×
1143
    uint32_t sequence) NOEXCEPT
1144
{
1145
    // BIP68: not applied to the sequence of the input of a coinbase.
1146
    // BIP68: if bit 31 is set then no consensus meaning is applied.
1147
    // BIP68: applied to txs with a version greater than or equal to two.
1148
    return !coinbase && input::is_relative_locktime_applied(sequence) &&
×
1149
        (version >= relative_locktime_min_version);
×
1150
}
1151

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

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

1161
    // Internal spends have no relative height/mtp (own metadata vs. itself).
1162
    return in.is_relative_locked(in.metadata.height,
×
1163
        in.metadata.median_time_past);
×
1164
}
1165

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

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

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

1182
    return std::any_of(inputs_->begin(), inputs_->end(), locked);
2✔
1183
}
1184

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

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

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

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

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

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

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

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

1230
    return error::transaction_success;
×
1231
}
1232

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

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

1243
    return error::transaction_success;
×
1244
}
1245

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

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

1257
    return error::transaction_success;
×
1258
}
1259

1260
// Validation.
1261
// ----------------------------------------------------------------------------
1262

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

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

1275
    return error::transaction_success;
5✔
1276
}
1277

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

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

1288
    if (is_absolute_locked(ctx.height, ctx.timestamp, ctx.median_time_past, bip113))
×
1289
        return error::absolute_time_locked;
×
1290

1291
    return error::transaction_success;
×
1292
}
1293

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

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

1307
    return error::transaction_success;
×
1308
}
1309

1310
// forks
1311
// height
1312
// median_time_past
1313

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

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

1333
    return error::transaction_success;
×
1334
}
1335

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

1339
// forks
1340

1341
// Do not need to invoke on coinbase.
1342
// This assumes that prevout caching is completed on all inputs.
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

© 2026 Coveralls, Inc