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

libbitcoin / libbitcoin-system / 10517615264

23 Aug 2024 12:19AM UTC coverage: 83.01% (-0.2%) from 83.249%
10517615264

push

github

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

Do not allow nullptr witness stack elements.

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

234 existing lines in 3 files now uncovered.

10065 of 12125 relevant lines covered (83.01%)

4762707.28 hits per line

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

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

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

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

46
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
47

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

51
constexpr auto prefixed = true;
52

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

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

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

71
// Constructors.
72
// ----------------------------------------------------------------------------
73

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

82
transaction::transaction(uint32_t version, chain::inputs&& inputs,
905✔
83
    chain::outputs&& outputs, uint32_t locktime) NOEXCEPT
905✔
84
  : transaction(version, to_shareds(std::move(inputs)),
1,810✔
85
      to_shareds(std::move(outputs)), locktime)
3,620✔
86
{
87
}
905✔
88

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

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

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

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

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

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

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

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

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

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

154
// Operators.
155
// ----------------------------------------------------------------------------
156

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

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

173
// Deserialization.
174
// ----------------------------------------------------------------------------
175

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

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

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

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

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

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

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

237
// Serialization.
238
// ----------------------------------------------------------------------------
239

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

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

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

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

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

264
    sink.write_4_bytes_little_endian(version_);
969✔
265

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

272
    sink.write_variable(inputs_->size());
969✔
273
    for (const auto& input: *inputs_)
2,358✔
274
        input->to_data(sink);
1,389✔
275

276
    sink.write_variable(outputs_->size());
969✔
277
    for (const auto& output: *outputs_)
2,639✔
278
        output->to_data(sink);
1,670✔
279

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

284
    sink.write_4_bytes_little_endian(locktime_);
969✔
285
}
969✔
286

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

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

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

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

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

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

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

335
    return { nominal_size, witnessed_size };
1,106✔
336
}
337

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

342
    return witness ? size_.witnessed : size_.nominal;
563✔
343
}
344

345
// Properties.
346
// ----------------------------------------------------------------------------
347

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

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

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

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

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

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

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

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

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

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

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

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

434
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
435
    hash_digest digest;
930✔
436
    BC_POP_WARNING()
437

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

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

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

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

466
// Methods.
467
// ----------------------------------------------------------------------------
468

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

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

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

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

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

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

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

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

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

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

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

527
    sink.flush();
8✔
528
    return digest;
8✔
529
}
8✔
530

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

536
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
537
    hash_digest digest;
11✔
538
    BC_POP_WARNING()
539

540
    stream::out::fast stream{ digest };
11✔
541
    hash::sha256x2::fast sink{ stream };
11✔
542

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

547
    sink.flush();
11✔
548
    return digest;
11✔
549
}
11✔
550

551
hash_digest transaction::sequences_hash() const NOEXCEPT
7✔
552
{
553
    if (sighash_cache_)
7✔
UNCOV
554
        return sighash_cache_->sequences;
×
555

556
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
557
    hash_digest digest;
7✔
558
    BC_POP_WARNING()
559

560
    stream::out::fast stream{ digest };
7✔
561
    hash::sha256x2::fast sink{ stream };
7✔
562

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

567
    sink.flush();
7✔
568
    return digest;
7✔
569
}
7✔
570

571
// Signing (unversioned).
572
// ----------------------------------------------------------------------------
573

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

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

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

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

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

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

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

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

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

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

644
    const auto write_outputs = [this, &input](writer& sink) NOEXCEPT
12✔
645
    {
646
        const auto index = input_index(input);
4✔
647

648
        sink.write_variable(add1(index));
4✔
649

650
        for (size_t output = 0; output < index; ++output)
5✔
651
            sink.write_bytes(null_output());
1✔
652

653
        // Guarded by unversioned_signature_hash.
654
        outputs_->at(index)->to_data(sink);
4✔
655
    };
8✔
656

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

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

675
        sink.write_variable(anyone ? one : inputs_->size());
×
676

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

UNCOV
684
        self.point().to_data(sink);
×
UNCOV
685
        sub.to_data(sink, prefixed);
×
UNCOV
686
        sink.write_4_bytes_little_endian(self.sequence());
×
687

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

UNCOV
696
    sink.write_4_bytes_little_endian(version_);
×
UNCOV
697
    write_inputs(sink);
×
UNCOV
698
    sink.write_variable(zero);
×
UNCOV
699
    sink.write_4_bytes_little_endian(locktime_);
×
UNCOV
700
    sink.write_4_bytes_little_endian(sighash_flags);
×
UNCOV
701
}
×
702

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

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

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

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

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

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

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

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

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

762
    stream::out::fast stream{ digest };
19✔
763
    hash::sha256x2::fast sink{ stream };
19✔
764

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

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

792
    sink.flush();
16✔
793
    return digest;
16✔
794
}
19✔
795

796
// Signing (version 0).
797
// ----------------------------------------------------------------------------
798

799
// private
800
// TODO: taproot requires both single and double hash of each.
801
void transaction::initialize_sighash_cache() const NOEXCEPT
2✔
802
{
803
    // C++23: std::optional<T>::or_else.
804
    if (!segregated_)
2✔
805
        return;
806

807
    // This overconstructs the cache (anyone or !all), however it is simple.
808
    sighash_cache_ =
2✔
809
    {
810
        outputs_hash(),
2✔
811
        points_hash(),
2✔
812
        sequences_hash()
2✔
813
    };
2✔
814
}
815

816
// private
817
hash_digest transaction::output_hash(const input_iterator& input) const NOEXCEPT
14✔
818
{
819
    const auto index = input_index(input);
14✔
820

821
    //*************************************************************************
822
    // CONSENSUS: if index exceeds outputs in signature hash, return null_hash.
823
    //*************************************************************************
824
    if (index >= outputs_->size())
14✔
825
        return null_hash;
2✔
826

827
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
828
    hash_digest digest;
12✔
829
    BC_POP_WARNING()
830

831
    stream::out::fast stream{ digest };
12✔
832
    hash::sha256x2::fast sink{ stream };
12✔
833
    outputs_->at(index)->to_data(sink);
12✔
834
    sink.flush();
12✔
835
    return digest;
12✔
836
}
12✔
837

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

847
    // Set options.
848
    const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
22✔
849
    const auto flag = mask_sighash(sighash_flags);
22✔
850
    const auto all = (flag == coverage::hash_all);
22✔
851
    const auto single = (flag == coverage::hash_single);
22✔
852
    const auto& self = **input;
22✔
853

854
    // Create hash writer.
855
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
856
    hash_digest digest;
22✔
857
    BC_POP_WARNING()
858

859
    stream::out::fast stream{ digest };
22✔
860
    hash::sha256x2::fast sink{ stream };
22✔
861

862
    // Create signature hash.
863
    sink.write_little_endian(version_);
22✔
864

865
    // Conditioning points, sequences, and outputs writes on cache_ instead of
866
    // conditionally passing them from methods avoids copying the cached hash.
867

868
    // points
869
    sink.write_bytes(!anyone ? points_hash() : null_hash);
22✔
870

871
    // sequences
872
    sink.write_bytes(!anyone && all ? sequences_hash() : null_hash);
22✔
873

874
    self.point().to_data(sink);
22✔
875
    sub.to_data(sink, prefixed);
22✔
876
    sink.write_little_endian(value);
22✔
877
    sink.write_little_endian(self.sequence());
22✔
878

879
    // outputs
880
    if (single)
22✔
881
        sink.write_bytes(output_hash(input));
14✔
882
    else
883
        sink.write_bytes(all ? outputs_hash() : null_hash);
8✔
884

885
    sink.write_little_endian(locktime_);
22✔
886
    sink.write_4_bytes_little_endian(sighash_flags);
22✔
887

888
    sink.flush();
22✔
889
    return digest;
22✔
890
}
22✔
891

892
// Signing (unversioned and version 0).
893
// ----------------------------------------------------------------------------
894

895
// ****************************************************************************
896
// CONSENSUS: sighash flags are carried in a single byte but are encoded as 4
897
// bytes in the signature hash preimage serialization.
898
// ****************************************************************************
899

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

907
    switch (version)
41✔
908
    {
909
        case script_version::unversioned:
12✔
910
            return unversioned_signature_hash(input, sub, sighash_flags);
12✔
911
        case script_version::zero:
29✔
912
            return version_0_signature_hash(input, sub, value, sighash_flags,
29✔
913
                bip143);
29✔
UNCOV
914
        case script_version::reserved:
×
UNCOV
915
        default:
×
UNCOV
916
            return {};
×
917
    }
918
}
919

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

929
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
930
        sighash_flags, version, bip143);
931

932
    // Validate the EC signature.
933
    return verify_signature(public_key, sighash, signature);
2✔
934
}
935

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

944
    out.reserve(max_endorsement_size);
2✔
945
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
946
        sighash_flags, version, bip143);
947

948
    // Create the EC signature and encode as DER.
949
    ec_signature signature;
2✔
950
    if (!sign(signature, secret, sighash) || !encode_signature(out, signature))
2✔
UNCOV
951
        return false;
×
952

953
    // Add the sighash type to the end of the DER signature -> endorsement.
954
    out.push_back(sighash_flags);
2✔
955
    ////out.shrink_to_fit();
956
    return true;
2✔
957
}
958

959
// Guard (context free).
960
// ----------------------------------------------------------------------------
961

962
bool transaction::is_coinbase() const NOEXCEPT
80✔
963
{
964
    return is_one(inputs_->size()) && inputs_->front()->point().is_null();
80✔
965
}
966

967
bool transaction::is_internal_double_spend() const NOEXCEPT
4✔
968
{
969
    // TODO: optimize (see block.is_internal_double_spend).
970
    return !is_distinct(points());
4✔
971
}
972

973
// TODO: a pool (non-coinbase) tx must fit into a block (with a coinbase).
UNCOV
974
bool transaction::is_oversized() const NOEXCEPT
×
975
{
UNCOV
976
    return serialized_size(false) > max_block_size;
×
977
}
978

979
// Guard (contextual).
980
// ----------------------------------------------------------------------------
981

982
// static/private
983
bool transaction::segregated(const chain::inputs& inputs) NOEXCEPT
1✔
984
{
985
    const auto witnessed = [](const auto& input) NOEXCEPT
2✔
986
    {
987
        return !input.witness().stack().empty();
1✔
988
    };
989

990
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
1✔
991
}
992

993
// static/private
994
bool transaction::segregated(const chain::input_cptrs& inputs) NOEXCEPT
905✔
995
{
996
    const auto witnessed = [](const auto& input) NOEXCEPT
908✔
997
    {
998
        return !input->witness().stack().empty();
908✔
999
    };
1000

1001
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
905✔
1002
}
1003

1004
bool transaction::is_segregated() const NOEXCEPT
4✔
1005
{
1006
    return segregated_;
4✔
1007
}
1008

1009
size_t transaction::weight() const NOEXCEPT
×
1010
{
1011
    // Block weight is 3 * base size * + 1 * total size (bip141).
UNCOV
1012
    return ceilinged_add(
×
1013
        ceilinged_multiply(base_size_contribution, serialized_size(false)),
UNCOV
1014
        ceilinged_multiply(total_size_contribution, serialized_size(true)));
×
1015
}
1016

UNCOV
1017
bool transaction::is_overweight() const NOEXCEPT
×
1018
{
UNCOV
1019
    return weight() > max_block_weight;
×
1020
}
1021

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

1034
// Check (context free).
1035
// ----------------------------------------------------------------------------
1036

1037
bool transaction::is_empty() const NOEXCEPT
9✔
1038
{
1039
    return inputs_->empty() || outputs_->empty();
9✔
1040
}
1041

1042
bool transaction::is_null_non_coinbase() const NOEXCEPT
7✔
1043
{
1044
    BC_ASSERT(!is_coinbase());
7✔
1045

1046
    const auto invalid = [](const auto& input) NOEXCEPT
9✔
1047
    {
1048
        return input->point().is_null();
9✔
1049
    };
1050

1051
    // True if not coinbase but has null previous_output(s).
1052
    return std::any_of(inputs_->begin(), inputs_->end(), invalid);
7✔
1053
}
1054

1055
bool transaction::is_invalid_coinbase_size() const NOEXCEPT
9✔
1056
{
1057
    BC_ASSERT(is_coinbase());
9✔
1058

1059
    // True if coinbase and has invalid input[0] script size.
1060
    const auto script_size = inputs_->front()->script().serialized_size(false);
9✔
1061
    return script_size < min_coinbase_size || script_size > max_coinbase_size;
9✔
1062
}
1063

1064
// Accept (contextual).
1065
// ----------------------------------------------------------------------------
1066

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

1074
    const auto finalized = [](const auto& input) NOEXCEPT
2✔
1075
    {
1076
        return input->is_final();
2✔
1077
    };
1078

1079
    const auto height_time = locktime_ < locktime_threshold ? height : time;
5✔
1080

1081
    return !(is_zero(locktime_) || locktime_ < height_time ||
8✔
1082
        std::all_of(inputs_->begin(), inputs_->end(), finalized));
3✔
1083
}
1084

1085
bool transaction::is_missing_prevouts() const NOEXCEPT
3✔
1086
{
1087
    BC_ASSERT(!is_coinbase());
3✔
1088

1089
    // Null or invalid prevout indicates not found.
1090
    const auto missing = [](const auto& input) NOEXCEPT
2✔
1091
    {
1092
        return !input->prevout;
1093
    };
1094

1095
    return std::any_of(inputs_->begin(), inputs_->end(), missing);
3✔
1096
}
1097

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

1106
    // The amount claimed by outputs.
1107
    return std::accumulate(outputs_->begin(), outputs_->end(), 0_u64, sum);
8✔
1108
}
1109

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

1119
    // The amount of prevouts (referenced by inputs).
1120
    return std::accumulate(inputs_->begin(), inputs_->end(), 0_u64, sum);
9✔
1121
}
1122

1123
bool transaction::is_overspent() const NOEXCEPT
2✔
1124
{
1125
    BC_ASSERT(!is_coinbase());
2✔
1126

1127
    return claim() > value();
2✔
1128
}
1129

1130
constexpr bool is_non_coinbase_mature(size_t tx_height, size_t height) NOEXCEPT
2✔
1131
{
1132
    return tx_height <= height;
2✔
1133
}
1134

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

1146
bool transaction::is_immature(size_t height) const NOEXCEPT
6✔
1147
{
1148
    BC_ASSERT(!is_coinbase());
6✔
1149

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

1158
    return !std::all_of(inputs_->begin(), inputs_->end(), mature);
6✔
1159
}
1160

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

1167
    // BIP68: applied to txs with a version greater than or equal to two.
1168
    if (version_ < relative_locktime_min_version)
4✔
1169
        return false;
1170

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

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

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

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

UNCOV
1196
    return std::any_of(inputs_->begin(), inputs_->end(), unconfirmed);
×
1197
}
1198

1199
bool transaction::is_confirmed_double_spend(size_t height) const NOEXCEPT
4✔
1200
{
1201
    BC_ASSERT(!is_coinbase());
4✔
1202

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

1209
    return std::any_of(inputs_->begin(), inputs_->end(), spent);
4✔
1210
}
1211

1212
// Guards (for tx pool without compact blocks).
1213
// ----------------------------------------------------------------------------
1214

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

UNCOV
1227
    return error::transaction_success;
×
1228
}
1229

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

UNCOV
1235
     if (!bip141 && is_segregated())
×
UNCOV
1236
        return error::unexpected_witness_transaction;
×
UNCOV
1237
    if (bip141 && is_overweight())
×
UNCOV
1238
        return error::transaction_weight_limit;
×
1239

UNCOV
1240
    return error::transaction_success;
×
1241
}
1242

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

1249
    if (is_missing_prevouts())
×
UNCOV
1250
        return error::missing_previous_output;
×
UNCOV
1251
    if (is_signature_operations_limit(bip16, bip141))
×
UNCOV
1252
        return error::transaction_sigop_limit;
×
1253

UNCOV
1254
    return error::transaction_success;
×
1255
}
1256

1257
// Validation.
1258
// ----------------------------------------------------------------------------
1259

1260
// DO invoke on coinbase.
1261
code transaction::check() const NOEXCEPT
5✔
1262
{
1263
    const auto coinbase = is_coinbase();
5✔
1264

1265
    if (is_empty())
5✔
UNCOV
1266
        return error::empty_transaction;
×
1267
    if (coinbase && is_invalid_coinbase_size())
5✔
UNCOV
1268
        return error::invalid_coinbase_script_size;
×
1269
    if (!coinbase && is_null_non_coinbase())
5✔
UNCOV
1270
        return error::previous_output_null;
×
1271

1272
    return error::transaction_success;
5✔
1273
}
1274

1275
// forks
1276
// height
1277
// timestamp
1278
// median_time_past
1279

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

UNCOV
1285
    if (is_non_final(ctx.height, ctx.timestamp, ctx.median_time_past, bip113))
×
UNCOV
1286
        return error::transaction_non_final;
×
1287

UNCOV
1288
    return error::transaction_success;
×
1289
}
1290

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

UNCOV
1297
    if (is_coinbase())
×
1298
        return error::transaction_success;
×
1299
    if (is_missing_prevouts())
×
1300
        return error::missing_previous_output;
×
1301
    if (is_overspent())
×
1302
        return error::spend_exceeds_value;
×
1303

1304
    return error::transaction_success;
×
1305
}
1306

1307
// forks
1308
// height
1309
// median_time_past
1310

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

UNCOV
1319
    if (is_coinbase())
×
UNCOV
1320
        return error::transaction_success;
×
UNCOV
1321
    if (bip68 && is_locked(ctx.height, ctx.median_time_past))
×
UNCOV
1322
        return error::relative_time_locked;
×
1323
    if (is_immature(ctx.height))
×
UNCOV
1324
        return error::coinbase_maturity;
×
UNCOV
1325
    if (is_unconfirmed_spend(ctx.height))
×
UNCOV
1326
        return error::unconfirmed_spend;
×
UNCOV
1327
    if (is_confirmed_double_spend(ctx.height))
×
UNCOV
1328
        return error::confirmed_double_spend;
×
1329

UNCOV
1330
    return error::transaction_success;
×
1331
}
1332

1333
// Connect (contextual).
1334
// ----------------------------------------------------------------------------
1335

1336
// forks
1337

1338
// Do not need to invoke on coinbase.
1339
code transaction::connect(const context& ctx) const NOEXCEPT
2✔
1340
{
1341
    ////BC_ASSERT(!is_coinbase());
1342

1343
    if (is_coinbase())
2✔
UNCOV
1344
        return error::transaction_success;
×
1345

1346
    code ec{};
2✔
1347
    using namespace machine;
2✔
1348
    initialize_sighash_cache();
2✔
1349

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

1361
    // TODO: accumulate sigops from each connect result and add coinbase.
1362
    // TODO: return in override with out parameter. more impactful with segwit.
1363
    return error::transaction_success;
2✔
1364
}
1365

1366
BC_POP_WARNING()
1367

1368
// JSON value convertors.
1369
// ----------------------------------------------------------------------------
1370

1371
namespace json = boost::json;
1372

1373
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
1374
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
1375

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

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

1400
BC_POP_WARNING()
1401

UNCOV
1402
transaction::cptr tag_invoke(json::value_to_tag<transaction::cptr>,
×
1403
    const json::value& value) NOEXCEPT
1404
{
UNCOV
1405
    return to_shared(tag_invoke(json::value_to_tag<transaction>{}, value));
×
1406
}
1407

1408
// Shared pointer overload is required for navigation.
1409
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
1410
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
1411

1412
void tag_invoke(json::value_from_tag tag, json::value& value,
2✔
1413
    const transaction::cptr& tx) NOEXCEPT
1414
{
1415
    tag_invoke(tag, value, *tx);
2✔
1416
}
2✔
1417

1418
BC_POP_WARNING()
1419
BC_POP_WARNING()
1420

1421
} // namespace chain
1422
} // namespace system
1423
} // namespace libbitcoin
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc