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

libbitcoin / libbitcoin-system / 13376224156

17 Feb 2025 06:03PM UTC coverage: 83.008% (-0.02%) from 83.025%
13376224156

push

github

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

Add relative locktime helpers.

3 of 6 new or added lines in 2 files covered. (50.0%)

1 existing line in 1 file now uncovered.

10156 of 12235 relevant lines covered (83.01%)

3840024.25 hits per line

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

77.23
/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(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
204✔
132
  : version_(source.read_4_bytes_little_endian()),
408✔
133
    inputs_(CREATE(input_cptrs, source.get_allocator())),
204✔
134
    outputs_(CREATE(output_cptrs, source.get_allocator()))
612✔
135
{
136
    assign_data(source, witness);
204✔
137
}
204✔
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_) || 
84✔
162
            deep_equal(*inputs_, *other.inputs_))
26✔
163
        && ((outputs_ == other.outputs_) ||
144✔
164
            deep_equal(*outputs_, *other.outputs_));
26✔
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
204✔
178
{
179
    auto& allocator = source.get_allocator();
204✔
180
    auto ins = to_non_const_raw_ptr(inputs_);
204✔
181
    auto count = source.read_size(max_block_size);
204✔
182
    ins->reserve(count);
204✔
183
    for (size_t in = 0; in < count; ++in)
453✔
184
        ins->emplace_back(CREATE(input, allocator, source));
249✔
185

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

192
    if (segregated_)
204✔
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_);
188✔
224
        count = source.read_size(max_block_size);
188✔
225
        outs->reserve(count);
188✔
226
        for (size_t out = 0; out < count; ++out)
437✔
227
            outs->emplace_back(CREATE(output, allocator, source));
249✔
228
    }
229

230
    locktime_ = source.read_4_bytes_little_endian();
204✔
231
    size_ = serialized_size(*inputs_, *outputs_, segregated_);
204✔
232
    valid_ = source;
204✔
233
}
204✔
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(const input_cptrs& inputs,
1,131✔
288
    const output_cptrs& outputs, bool segregated) NOEXCEPT
289
{
290
    sizes size{ zero, zero };
1,131✔
291

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

299
    const auto outs = [](size_t total, const auto& output) NOEXCEPT
394✔
300
    {
301
        return ceilinged_add(total, output->serialized_size());
394✔
302
    };
303

304
    constexpr auto base_const_size = ceilinged_add(sizeof(version_),
1,131✔
305
        sizeof(locktime_));
306
    constexpr auto witness_const_size = ceilinged_add(sizeof(witness_marker),
1,131✔
307
        sizeof(witness_enabled));
308

309
    const auto base_size = ceilinged_add(ceilinged_add(ceilinged_add(
1,131✔
310
        base_const_size, variable_size(inputs.size())),
311
        variable_size(outputs.size())),
312
        std::accumulate(outputs.begin(), outputs.end(), zero, outs));
313
    const auto nominal_size = ceilinged_add(base_size, size.nominal);
1,131✔
314

315
    // witnessed_size is nominal_size for non-segregated transactions.
316
    const auto witnessed_size = segregated ? ceilinged_add(ceilinged_add(
1,131✔
317
        base_size, witness_const_size), size.witnessed) : nominal_size;
318

319
    // Values are the same for non-segregated transactions.
320
    return { nominal_size, witnessed_size };
1,131✔
321
}
322

323
size_t transaction::serialized_size(bool witness) const NOEXCEPT
613✔
324
{
325
    witness &= segregated_;
613✔
326

327
    return witness ? size_.witnessed : size_.nominal;
613✔
328
}
329

330
// Properties.
331
// ----------------------------------------------------------------------------
332

333
bool transaction::is_valid() const NOEXCEPT
777✔
334
{
335
    return valid_;
777✔
336
}
337

338
size_t transaction::spends() const NOEXCEPT
×
339
{
340
    return is_coinbase() ? zero : inputs_->size();
×
341
}
342

343
size_t transaction::inputs() const NOEXCEPT
1,569✔
344
{
345
    return inputs_->size();
1,569✔
346
}
347

348
size_t transaction::outputs() const NOEXCEPT
1✔
349
{
350
    return outputs_->size();
1✔
351
}
352

353
uint32_t transaction::version() const NOEXCEPT
6✔
354
{
355
    return version_;
4✔
356
}
357

358
uint32_t transaction::locktime() const NOEXCEPT
13✔
359
{
360
    return locktime_;
4✔
361
}
362

363
const inputs_cptr& transaction::inputs_ptr() const NOEXCEPT
2,446✔
364
{
365
    return inputs_;
2,446✔
366
}
367

368
const outputs_cptr& transaction::outputs_ptr() const NOEXCEPT
62✔
369
{
370
    return outputs_;
62✔
371
}
372

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

380
void transaction::set_nominal_hash(const hash_digest& hash) const NOEXCEPT
20✔
381
{
382
    nominal_hash_ = hash;
20✔
383
}
1✔
384

385
void transaction::set_witness_hash(const hash_digest& hash) const NOEXCEPT
2✔
386
{
387
    witness_hash_ = hash;
2✔
388
}
1✔
389

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

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

424
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
425
    hash_digest digest;
927✔
426
    BC_POP_WARNING()
427

428
    stream::out::fast stream{ digest };
927✔
429
    hash::sha256x2::fast sink{ stream };
927✔
430
    to_data(sink, witness);
927✔
431
    sink.flush();
927✔
432
    return digest;
927✔
433
}
927✔
434

435
// static
436
hash_digest transaction::desegregated_hash(size_t witnessed,
×
437
    size_t unwitnessed, const uint8_t* data) NOEXCEPT
438
{
439
    if (is_null(data))
×
440
        return null_hash;
×
441

442
    constexpr auto preamble = sizeof(uint32_t) + two * sizeof(uint8_t);
×
443
    const auto puts = floored_subtract(unwitnessed, two * sizeof(uint32_t));
×
444
    const auto locktime = floored_subtract(witnessed, sizeof(uint32_t));
×
445

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

456
// Methods.
457
// ----------------------------------------------------------------------------
458

459
bool transaction::is_dusty(uint64_t minimum_output_value) const NOEXCEPT
6✔
460
{
461
    const auto dusty = [=](const auto& output) NOEXCEPT
9✔
462
    {
463
        return output->is_dust(minimum_output_value);
9✔
464
    };
6✔
465

466
    return std::any_of(outputs_->begin(), outputs_->end(), dusty);
6✔
467
}
468

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

477
    const auto out = [=](size_t total, const auto& output) NOEXCEPT
×
478
    {
479
        return ceilinged_add(total, output->signature_operations(bip141));
×
480
    };
1✔
481

482
    // Overflow returns max_size_t.
483
    return ceilinged_add(
1✔
484
        std::accumulate(inputs_->begin(), inputs_->end(), zero, in),
485
        std::accumulate(outputs_->begin(), outputs_->end(), zero, out));
1✔
486
}
487

488
chain::points transaction::points() const NOEXCEPT
4✔
489
{
490
    chain::points out(inputs_->size());
4✔
491

492
    const auto point = [](const auto& input) NOEXCEPT
8✔
493
    {
494
        return input->point();
8✔
495
    };
496

497
    std::transform(inputs_->begin(), inputs_->end(), out.begin(), point);
4✔
498
    return out;
4✔
499
}
×
500

501
hash_digest transaction::outputs_hash() const NOEXCEPT
8✔
502
{
503
    if (sighash_cache_)
8✔
504
        return sighash_cache_->outputs;
×
505

506
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
507
    hash_digest digest;
8✔
508
    BC_POP_WARNING()
509
        
510
    stream::out::fast stream{ digest };
8✔
511
    hash::sha256x2::fast sink{ stream };
8✔
512

513
    for (const auto& output: *outputs_)
22✔
514
        output->to_data(sink);
14✔
515

516
    sink.flush();
8✔
517
    return digest;
8✔
518
}
8✔
519

520
hash_digest transaction::points_hash() const NOEXCEPT
11✔
521
{
522
    if (sighash_cache_)
11✔
523
        return sighash_cache_->points;
×
524

525
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
526
    hash_digest digest;
11✔
527
    BC_POP_WARNING()
528

529
    stream::out::fast stream{ digest };
11✔
530
    hash::sha256x2::fast sink{ stream };
11✔
531

532
    for (const auto& input: *inputs_)
27✔
533
        input->point().to_data(sink);
16✔
534

535
    sink.flush();
11✔
536
    return digest;
11✔
537
}
11✔
538

539
hash_digest transaction::sequences_hash() const NOEXCEPT
7✔
540
{
541
    if (sighash_cache_)
7✔
542
        return sighash_cache_->sequences;
×
543

544
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
545
    hash_digest digest;
7✔
546
    BC_POP_WARNING()
547

548
    stream::out::fast stream{ digest };
7✔
549
    hash::sha256x2::fast sink{ stream };
7✔
550

551
    for (const auto& input: *inputs_)
17✔
552
        sink.write_4_bytes_little_endian(input->sequence());
10✔
553

554
    sink.flush();
7✔
555
    return digest;
7✔
556
}
7✔
557

558
// Signing (unversioned).
559
// ----------------------------------------------------------------------------
560

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

568
    return std::next(inputs_->begin(), index);
4✔
569
}
570

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

577
    return possible_narrow_and_sign_cast<uint32_t>(
25✔
578
        std::distance(inputs_->begin(), input));
×
579
}
580

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

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

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

611
        for (in = inputs_->begin(); !anyone && in != input; ++in)
4✔
612
        {
613
            (*in)->point().to_data(sink);
×
614
            sink.write_bytes(empty_script());
×
615
            sink.write_bytes(zero_sequence());
×
616
        }
617

618
        (*input)->point().to_data(sink);
4✔
619
        sub.to_data(sink, prefixed);
4✔
620
        sink.write_4_bytes_little_endian((*input)->sequence());
4✔
621

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

630
    const auto write_outputs = [this, &input](writer& sink) NOEXCEPT
8✔
631
    {
632
        const auto index = input_index(input);
4✔
633

634
        sink.write_variable(add1(index));
4✔
635

636
        for (size_t output = 0; output < index; ++output)
5✔
637
            sink.write_bytes(null_output());
1✔
638

639
        // Guarded by unversioned_signature_hash.
640
        outputs_->at(index)->to_data(sink);
4✔
641
    };
8✔
642

643
    sink.write_4_bytes_little_endian(version_);
4✔
644
    write_inputs(sink);
4✔
645
    write_outputs(sink);
4✔
646
    sink.write_4_bytes_little_endian(locktime_);
4✔
647
    sink.write_4_bytes_little_endian(sighash_flags);
4✔
648
}
4✔
649

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

660
        sink.write_variable(anyone ? one : inputs_->size());
×
661

662
        for (in = inputs_->begin(); !anyone && in != input; ++in)
×
663
        {
664
            (*in)->point().to_data(sink);
×
665
            sink.write_bytes(empty_script());
×
666
            sink.write_bytes(zero_sequence());
×
667
        }
668

669
        (*input)->point().to_data(sink);
×
670
        sub.to_data(sink, prefixed);
×
671
        sink.write_4_bytes_little_endian((*input)->sequence());
×
672

673
        for (++in; !anyone && in != inputs_->end(); ++in)
×
674
        {
675
            (*in)->point().to_data(sink);
×
676
            sink.write_bytes(empty_script());
×
677
            sink.write_bytes(zero_sequence());
×
678
        }
679
    };
×
680

681
    sink.write_4_bytes_little_endian(version_);
×
682
    write_inputs(sink);
×
683
    sink.write_variable(zero);
×
684
    sink.write_4_bytes_little_endian(locktime_);
×
685
    sink.write_4_bytes_little_endian(sighash_flags);
×
686
}
×
687

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

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

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

707
        (*input)->point().to_data(sink);
12✔
708
        sub.to_data(sink, prefixed);
12✔
709
        sink.write_4_bytes_little_endian((*input)->sequence());
12✔
710

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

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

726
    sink.write_4_bytes_little_endian(version_);
12✔
727
    write_inputs(sink);
12✔
728
    write_outputs(sink);
12✔
729
    sink.write_4_bytes_little_endian(locktime_);
12✔
730
    sink.write_4_bytes_little_endian(flags);
12✔
731
}
12✔
732

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

741
    // Create hash writer.
742
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
743
    hash_digest digest;
19✔
744
    BC_POP_WARNING()
745

746
    stream::out::fast stream{ digest };
19✔
747
    hash::sha256x2::fast sink{ stream };
19✔
748

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

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

776
    sink.flush();
16✔
777
    return digest;
16✔
778
}
19✔
779

780
// Signing (version 0).
781
// ----------------------------------------------------------------------------
782

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

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

800
// private
801
hash_digest transaction::output_hash(const input_iterator& input) const NOEXCEPT
14✔
802
{
803
    const auto index = input_index(input);
14✔
804

805
    //*************************************************************************
806
    // CONSENSUS: if index exceeds outputs in signature hash, return null_hash.
807
    //*************************************************************************
808
    if (index >= outputs_->size())
14✔
809
        return null_hash;
2✔
810

811
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
812
    hash_digest digest;
12✔
813
    BC_POP_WARNING()
814

815
    stream::out::fast stream{ digest };
12✔
816
    hash::sha256x2::fast sink{ stream };
12✔
817
    outputs_->at(index)->to_data(sink);
12✔
818
    sink.flush();
12✔
819
    return digest;
12✔
820
}
12✔
821

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

831
    // Set options.
832
    const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
22✔
833
    const auto flag = mask_sighash(sighash_flags);
22✔
834
    const auto all = (flag == coverage::hash_all);
22✔
835
    const auto single = (flag == coverage::hash_single);
22✔
836

837
    // Create hash writer.
838
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
839
    hash_digest digest;
22✔
840
    BC_POP_WARNING()
841

842
    stream::out::fast stream{ digest };
22✔
843
    hash::sha256x2::fast sink{ stream };
22✔
844

845
    // Create signature hash.
846
    sink.write_little_endian(version_);
22✔
847

848
    // Conditioning points, sequences, and outputs writes on cache_ instead of
849
    // conditionally passing them from methods avoids copying the cached hash.
850

851
    // points
852
    sink.write_bytes(!anyone ? points_hash() : null_hash);
22✔
853

854
    // sequences
855
    sink.write_bytes(!anyone && all ? sequences_hash() : null_hash);
22✔
856

857
    (*input)->point().to_data(sink);
22✔
858
    sub.to_data(sink, prefixed);
22✔
859
    sink.write_little_endian(value);
22✔
860
    sink.write_little_endian((*input)->sequence());
22✔
861

862
    // outputs
863
    if (single)
22✔
864
        sink.write_bytes(output_hash(input));
14✔
865
    else
866
        sink.write_bytes(all ? outputs_hash() : null_hash);
8✔
867

868
    sink.write_little_endian(locktime_);
22✔
869
    sink.write_4_bytes_little_endian(sighash_flags);
22✔
870

871
    sink.flush();
22✔
872
    return digest;
22✔
873
}
22✔
874

875
// Signing (unversioned and version 0).
876
// ----------------------------------------------------------------------------
877

878
// ****************************************************************************
879
// CONSENSUS: sighash flags are carried in a single byte but are encoded as 4
880
// bytes in the signature hash preimage serialization.
881
// ****************************************************************************
882

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

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

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

912
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
913
        sighash_flags, version, bip143);
914

915
    // Validate the EC signature.
916
    return verify_signature(public_key, sighash, signature);
2✔
917
}
918

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

927
    out.reserve(max_endorsement_size);
2✔
928
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
929
        sighash_flags, version, bip143);
930

931
    // Create the EC signature and encode as DER.
932
    ec_signature signature;
2✔
933
    if (!sign(signature, secret, sighash) || !encode_signature(out, signature))
2✔
934
        return false;
×
935

936
    // Add the sighash type to the end of the DER signature -> endorsement.
937
    out.push_back(sighash_flags);
2✔
938
    ////out.shrink_to_fit();
939
    return true;
940
}
941

942
// Guard (context free).
943
// ----------------------------------------------------------------------------
944

945
bool transaction::is_coinbase() const NOEXCEPT
80✔
946
{
947
    return is_one(inputs_->size()) && inputs_->front()->point().is_null();
80✔
948
}
949

950
bool transaction::is_internal_double_spend() const NOEXCEPT
4✔
951
{
952
    // TODO: optimize (see block.is_internal_double_spend).
953
    return !is_distinct(points());
4✔
954
}
955

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

962
// Guard (contextual).
963
// ----------------------------------------------------------------------------
964

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

973
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
1✔
974
}
975

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

984
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
905✔
985
}
986

987
bool transaction::is_segregated() const NOEXCEPT
4✔
988
{
989
    return segregated_;
4✔
990
}
991

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

1000
bool transaction::is_overweight() const NOEXCEPT
×
1001
{
1002
    return weight() > max_block_weight;
×
1003
}
1004

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

1017
// Check (context free).
1018
// ----------------------------------------------------------------------------
1019

1020
bool transaction::is_empty() const NOEXCEPT
9✔
1021
{
1022
    return inputs_->empty() || outputs_->empty();
9✔
1023
}
1024

1025
bool transaction::is_null_non_coinbase() const NOEXCEPT
7✔
1026
{
1027
    BC_ASSERT(!is_coinbase());
7✔
1028

1029
    const auto invalid = [](const auto& input) NOEXCEPT
9✔
1030
    {
1031
        return input->point().is_null();
9✔
1032
    };
1033

1034
    // True if not coinbase but has null previous_output(s).
1035
    return std::any_of(inputs_->begin(), inputs_->end(), invalid);
7✔
1036
}
1037

1038
bool transaction::is_invalid_coinbase_size() const NOEXCEPT
9✔
1039
{
1040
    BC_ASSERT(is_coinbase());
9✔
1041

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

1047
// Accept (contextual).
1048
// ----------------------------------------------------------------------------
1049

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

1057
    const auto finalized = [](const auto& input) NOEXCEPT
2✔
1058
    {
1059
        return input->is_final();
2✔
1060
    };
1061

1062
    const auto height_time = locktime_ < locktime_threshold ? height : time;
5✔
1063

1064
    return !(is_zero(locktime_) || locktime_ < height_time ||
8✔
1065
        std::all_of(inputs_->begin(), inputs_->end(), finalized));
3✔
1066
}
1067

1068
bool transaction::is_missing_prevouts() const NOEXCEPT
3✔
1069
{
1070
    BC_ASSERT(!is_coinbase());
3✔
1071

1072
    // Null or invalid prevout indicates not found.
1073
    const auto missing = [](const auto& input) NOEXCEPT
2✔
1074
    {
1075
        return !input->prevout;
1076
    };
1077

1078
    return std::any_of(inputs_->begin(), inputs_->end(), missing);
3✔
1079
}
1080

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

1089
    // The amount claimed by outputs.
1090
    return std::accumulate(outputs_->begin(), outputs_->end(), 0_u64, sum);
8✔
1091
}
1092

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

1102
    // The amount of prevouts (referenced by inputs).
1103
    return std::accumulate(inputs_->begin(), inputs_->end(), 0_u64, sum);
9✔
1104
}
1105

1106
bool transaction::is_overspent() const NOEXCEPT
2✔
1107
{
1108
    BC_ASSERT(!is_coinbase());
2✔
1109

1110
    return claim() > value();
2✔
1111
}
1112

1113
constexpr bool is_non_coinbase_mature(size_t tx_height, size_t height) NOEXCEPT
2✔
1114
{
1115
    return tx_height <= height;
2✔
1116
}
1117

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

1130
bool transaction::is_immature(size_t height) const NOEXCEPT
6✔
1131
{
1132
    BC_ASSERT(!is_coinbase());
6✔
1133

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

1142
    return !std::all_of(inputs_->begin(), inputs_->end(), mature);
6✔
1143
}
1144

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

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

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

1165
    return in.is_internal_lock();
×
1166
}
1167

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

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

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

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

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

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

1203
    return std::any_of(inputs_->begin(), inputs_->end(), unconfirmed);
×
1204
}
1205

1206
bool transaction::is_confirmed_double_spend(size_t height) const NOEXCEPT
4✔
1207
{
1208
    BC_ASSERT(!is_coinbase());
4✔
1209

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

1216
    return std::any_of(inputs_->begin(), inputs_->end(), spent);
4✔
1217
}
1218

1219
// Guards (for tx pool without compact blocks).
1220
// ----------------------------------------------------------------------------
1221

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

1234
    return error::transaction_success;
×
1235
}
1236

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

1242
     if (!bip141 && is_segregated())
×
1243
        return error::unexpected_witness_transaction;
×
1244
    if (bip141 && is_overweight())
×
1245
        return error::transaction_weight_limit;
×
1246

1247
    return error::transaction_success;
×
1248
}
1249

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

1256
    if (is_missing_prevouts())
×
1257
        return error::missing_previous_output;
×
1258
    if (is_signature_operations_limit(bip16, bip141))
×
1259
        return error::transaction_sigop_limit;
×
1260

1261
    return error::transaction_success;
×
1262
}
1263

1264
// Validation.
1265
// ----------------------------------------------------------------------------
1266

1267
// DO invoke on coinbase.
1268
code transaction::check() const NOEXCEPT
5✔
1269
{
1270
    const auto coinbase = is_coinbase();
5✔
1271

1272
    if (is_empty())
5✔
1273
        return error::empty_transaction;
×
1274
    if (coinbase && is_invalid_coinbase_size())
5✔
1275
        return error::invalid_coinbase_script_size;
×
1276
    if (!coinbase && is_null_non_coinbase())
5✔
1277
        return error::previous_output_null;
×
1278

1279
    return error::transaction_success;
5✔
1280
}
1281

1282
// forks
1283
// height
1284
// timestamp
1285
// median_time_past
1286

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

1292
    if (is_non_final(ctx.height, ctx.timestamp, ctx.median_time_past, bip113))
×
1293
        return error::transaction_non_final;
×
1294

1295
    return error::transaction_success;
×
1296
}
1297

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

1304
    if (is_coinbase())
×
1305
        return error::transaction_success;
×
1306
    if (is_missing_prevouts())
×
1307
        return error::missing_previous_output;
×
1308
    if (is_overspent())
×
1309
        return error::spend_exceeds_value;
×
1310

1311
    return error::transaction_success;
×
1312
}
1313

1314
// forks
1315
// height
1316
// median_time_past
1317

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

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

1337
    return error::transaction_success;
×
1338
}
1339

1340
// Connect (contextual).
1341
// ----------------------------------------------------------------------------
1342

1343
// forks
1344

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

1350
    if (is_coinbase())
2✔
1351
        return error::transaction_success;
×
1352

1353
    code ec{};
2✔
1354
    using namespace machine;
2✔
1355
    initialize_sighash_cache();
2✔
1356

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

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

1373
BC_POP_WARNING()
1374

1375
// JSON value convertors.
1376
// ----------------------------------------------------------------------------
1377

1378
namespace json = boost::json;
1379

1380
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
1381
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
1382

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

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

1407
BC_POP_WARNING()
1408

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

1415
// Shared pointer overload is required for navigation.
1416
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
1417
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
1418

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

1425
BC_POP_WARNING()
1426
BC_POP_WARNING()
1427

1428
} // namespace chain
1429
} // namespace system
1430
} // 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