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

libbitcoin / libbitcoin-system / 9950156475

16 Jul 2024 03:16AM UTC coverage: 83.203% (+0.3%) from 82.874%
9950156475

push

github

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

Optimizing deserializations.

205 of 222 new or added lines in 12 files covered. (92.34%)

14 existing lines in 8 files now uncovered.

10090 of 12127 relevant lines covered (83.2%)

4761709.16 hits per line

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

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

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

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

46
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
47

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

51
constexpr auto prefixed = true;
52

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

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

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

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

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

82
transaction::~transaction() NOEXCEPT
2,093✔
83
{
84
}
2,093✔
85

86
transaction::transaction(transaction&& other) NOEXCEPT
33✔
87
  : transaction(other)
33✔
88
{
89
}
33✔
90

91
transaction::transaction(const transaction& other) NOEXCEPT
989✔
92
  : transaction(
93
      other.version_,
989✔
94
      other.inputs_,
989✔
95
      other.outputs_,
989✔
96
      other.locktime_,
989✔
97
      other.segregated_,
989✔
98
      other.valid_)
989✔
99
{
100
    // Optimized for faster optional, not for copy.
101

102
    if (other.nominal_hash_)
989✔
103
        nominal_hash_ = to_unique(*other.nominal_hash_);
×
104
    else
105
        nominal_hash_.reset();
989✔
106

107
    if (other.witness_hash_)
989✔
108
        witness_hash_ = to_unique(*other.witness_hash_);
×
109
    else
110
        witness_hash_.reset();
989✔
111

112
    if (other.sighash_cache_)
989✔
113
        sighash_cache_ = to_unique(*other.sighash_cache_);
×
114
    else
115
        sighash_cache_.reset();
989✔
116
}
989✔
117

118
transaction::transaction(uint32_t version, chain::inputs&& inputs,
903✔
119
    chain::outputs&& outputs, uint32_t locktime) NOEXCEPT
903✔
120
  : transaction(version, to_shareds(std::move(inputs)),
1,806✔
121
      to_shareds(std::move(outputs)), locktime)
3,612✔
122
{
123
}
903✔
124

125
transaction::transaction(uint32_t version, const chain::inputs& inputs,
1✔
126
    const chain::outputs& outputs, uint32_t locktime) NOEXCEPT
1✔
127
  : transaction(version, to_shareds(inputs), to_shareds(outputs), locktime,
2✔
128
      segregated(inputs), true)
4✔
129
{
130
}
1✔
131

132
transaction::transaction(uint32_t version, const chain::inputs_cptr& inputs,
903✔
133
    const chain::outputs_cptr& outputs, uint32_t locktime) NOEXCEPT
903✔
134
  : transaction(version, inputs, outputs, locktime, segregated(*inputs), true)
903✔
135
{
136
}
903✔
137

138
transaction::transaction(const data_slice& data, bool witness) NOEXCEPT
41✔
139
  : transaction(stream::in::copy(data), witness)
41✔
140
{
141
}
41✔
142

143
////transaction::transaction(stream::in::fast&& stream, bool witness) NOEXCEPT
144
////  : transaction(read::bytes::fast(stream), witness)
145
////{
146
////}
147

148
transaction::transaction(stream::in::fast& stream, bool witness) NOEXCEPT
2✔
149
  : transaction(read::bytes::fast(stream), witness)
2✔
150
{
151
}
2✔
152

153
transaction::transaction(std::istream&& stream, bool witness) NOEXCEPT
41✔
154
  : transaction(read::bytes::istream(stream), witness)
41✔
155
{
156
}
41✔
157

158
transaction::transaction(std::istream& stream, bool witness) NOEXCEPT
4✔
159
  : transaction(read::bytes::istream(stream), witness)
4✔
160
{
161
}
4✔
162

163
transaction::transaction(reader&& source, bool witness) NOEXCEPT
47✔
164
  : transaction(source, witness/*from_data(source, witness)*/)
47✔
165
{
UNCOV
166
}
×
167

168
transaction::transaction(reader& source, bool witness) NOEXCEPT
179✔
169
////: transaction(from_data(source, witness))
170
  : version_(source.read_4_bytes_little_endian()),
358✔
171
    inputs_(
179✔
172
        source.get_allocator().new_object<input_cptrs>(),
179✔
173
        source.get_allocator().deleter<input_cptrs>(source.get_arena())),
179✔
174
    outputs_(
358✔
175
        source.get_allocator().new_object<output_cptrs>(),
179✔
176
        source.get_allocator().deleter<output_cptrs>(source.get_arena()))
358✔
177
{
178
    assign_data(source, witness);
179✔
179
}
179✔
180

181
// protected
182
transaction::transaction(uint32_t version,
1,914✔
183
    const chain::inputs_cptr& inputs, const chain::outputs_cptr& outputs,
184
    uint32_t locktime, bool segregated, bool valid) NOEXCEPT
1,914✔
185
  : version_(version),
1,914✔
186
    inputs_(inputs ? inputs : to_shared<input_cptrs>()),
3,828✔
187
    outputs_(outputs ? outputs : to_shared<output_cptrs>()),
1,914✔
188
    locktime_(locktime),
1,914✔
189
    segregated_(segregated),
1,914✔
190
    valid_(valid),
1,914✔
191
    size_(serialized_size(*inputs, *outputs, segregated))
3,828✔
192
{
193
}
1,914✔
194

195
// Operators.
196
// ----------------------------------------------------------------------------
197

198
transaction& transaction::operator=(transaction&& other) NOEXCEPT
×
199
{
200
    *this = other;
×
201
    return *this;
×
202
}
203

204
transaction& transaction::operator=(const transaction& other) NOEXCEPT
×
205
{
206
    version_ = other.version_;
×
207
    inputs_ = other.inputs_;
×
208
    outputs_ = other.outputs_;
×
209
    locktime_ = other.locktime_;
×
210
    segregated_ = other.segregated_;
×
211
    valid_ = other.valid_;
×
212
    size_ = other.size_;
×
213

214
    // Optimized for faster optional, not for copy.
215

216
    if (other.nominal_hash_)
×
217
        nominal_hash_ = to_unique(*other.nominal_hash_);
×
218
    else
219
        nominal_hash_.reset();
×
220

221
    if (other.witness_hash_)
×
222
        witness_hash_ = to_unique(*other.witness_hash_);
×
223
    else
224
        witness_hash_.reset();
×
225

226
    if (other.sighash_cache_)
×
227
        sighash_cache_ = to_unique(*other.sighash_cache_);
×
228
    else
229
        sighash_cache_.reset();
×
230

231
    return *this;
×
232
}
233

234
bool transaction::operator==(const transaction& other) const NOEXCEPT
60✔
235
{
236
    // Compares input/output elements, not pointers, cache not compared.
237
    return (version_ == other.version_)
60✔
238
        && (locktime_ == other.locktime_)
58✔
239
        && ((inputs_ == other.inputs_) || 
74✔
240
            deep_equal(*inputs_, *other.inputs_))
16✔
241
        && ((outputs_ == other.outputs_) ||
134✔
242
            deep_equal(*outputs_, *other.outputs_));
16✔
243
}
244

245
bool transaction::operator!=(const transaction& other) const NOEXCEPT
2✔
246
{
247
    return !(*this == other);
2✔
248
}
249

250
// Deserialization.
251
// ----------------------------------------------------------------------------
252

253
////template<class Put, class Source>
254
////std::shared_ptr<const std_vector<std::shared_ptr<const Put>>>
255
////read_puts(Source& source) NOEXCEPT
256
////{
257
////    // Allocate arena cputs shared_ptr and std_vector(captures arena).
258
////    using puts_type = std_vector<std::shared_ptr<const Put>>;
259
////    auto cputs = to_allocated<puts_type>(source.get_arena());
260
////
261
////    BC_PUSH_WARNING(NO_UNGUARDED_POINTERS)
262
////    auto puts = to_non_const_raw_ptr(cputs);
263
////    BC_POP_WARNING()
264
////
265
////    // Allocate cputs capacity(uses arena).
266
////    const auto capacity = source.read_size(max_block_size);
267
////    puts->reserve(capacity);
268
////
269
////    // Allocate each shared_ptr<put> and move ptr to reservation.
270
////    // Each put is constructed in place as allocated by/with its pointer.
271
////    for (size_t put = 0; put < capacity; ++put)
272
////        puts->push_back(to_allocated<Put>(source.get_arena(), source));
273
////
274
////    return cputs;
275
////}
276
////
277
////// static/private
278
////transaction transaction::from_data(reader& source, bool witness) NOEXCEPT
279
////{
280
////    const auto version = source.read_4_bytes_little_endian();
281
////    auto inputs = read_puts<input>(source);
282
////    chain::outputs_cptr outputs;
283
////
284
////    // Expensive repeated recomputation, so cache segregated state.
285
////    const auto segregated = inputs->size() == witness_marker &&
286
////        source.peek_byte() == witness_enabled;
287
////
288
////    // Detect witness as no inputs (marker) and expected flag (bip144).
289
////    if (segregated)
290
////    {
291
////        // Skip over the peeked witness flag.
292
////        source.skip_byte();
293
////
294
////        // Inputs and outputs are constructed on a vector of const pointers.
295
////        inputs = read_puts<input>(source);
296
////        outputs = read_puts<output>(source);
297
////
298
////        // Read or skip witnesses as specified.
299
////        if (witness)
300
////        {
301
////            for (auto& input: *inputs)
302
////            {
303
////                BC_PUSH_WARNING(NO_UNGUARDED_POINTERS)
304
////                to_non_const_raw_ptr(input)->set_witness(source);
305
////                BC_POP_WARNING()
306
////            }
307
////        }
308
////        else
309
////        {
310
////            for (size_t in = 0; in < inputs->size(); ++in)
311
////                witness::skip(source, true);
312
////        }
313
////    }
314
////    else
315
////    {
316
////        // Default witness is populated on input construct.
317
////        outputs = read_puts<const output>(source);
318
////    }
319
////
320
////    const auto locktime = source.read_4_bytes_little_endian();
321
////    return { version, inputs, outputs, locktime, segregated, source };
322
////}
323

324
// private
325
BC_PUSH_WARNING(NO_UNGUARDED_POINTERS)
326
void transaction::assign_data(reader& source, bool witness) NOEXCEPT
179✔
327
{
328
    auto& allocator = source.get_allocator();
179✔
329

330
    ////allocator.construct<inputs_cptr>(&inputs_,
331
    ////    allocator.new_object<input_cptrs>(),
332
    ////    allocator.deleter<input_cptrs>(source.get_arena()));
333
    ////
334
    ////allocator.construct<outputs_cptr>(&outputs_,
335
    ////    allocator.new_object<output_cptrs>(),
336
    ////    allocator.deleter<output_cptrs>(source.get_arena()));
337
    ////
338
    ////version_ = source.read_4_bytes_little_endian();
339

340
    auto ins = to_non_const_raw_ptr(inputs_);
179✔
341
    auto count = source.read_size(max_block_size);
179✔
342
    ins->reserve(count);
179✔
343
    for (size_t in = 0; in < count; ++in)
403✔
344
        ins->emplace_back(
448✔
345
            allocator.new_object<input>(source),
224✔
346
            allocator.deleter<input>(source.get_arena()));
448✔
347

348
    // Expensive repeated recomputation, so cache segregated state.
349
    // Detect witness as no inputs (marker) and expected flag (bip144).
350
    segregated_ = 
179✔
351
        inputs_->size() == witness_marker &&
195✔
352
        source.peek_byte() == witness_enabled;
16✔
353

354
    if (segregated_)
179✔
355
    {
356
        // Skip over the peeked witness flag.
357
        source.skip_byte();
16✔
358

359
        count = source.read_size(max_block_size);
16✔
360
        ins->reserve(count);
16✔
361
        for (size_t in = 0; in < count; ++in)
37✔
362
            ins->emplace_back(
42✔
363
                allocator.new_object<input>(source),
21✔
364
                allocator.deleter<input>(source.get_arena()));
42✔
365

366
        auto outs = to_non_const_raw_ptr(outputs_);
16✔
367
        count = source.read_size(max_block_size);
16✔
368
        outs->reserve(count);
16✔
369
        for (size_t out = 0; out < count; ++out)
41✔
370
            outs->emplace_back(
50✔
371
                allocator.new_object<output>(source),
25✔
372
                allocator.deleter<output>(source.get_arena()));
50✔
373

374
        // Read or skip witnesses as specified.
375
        if (witness)
16✔
376
        {
377
            for (auto& input: *inputs_)
35✔
378
                to_non_const_raw_ptr(input)->set_witness(source);
20✔
379
        }
380
        else
381
        {
382
            // Default witness is populated on input construct.
383
            for (size_t in = 0; in < inputs_->size(); ++in)
2✔
384
                witness::skip(source, true);
1✔
385
        }
386
    }
387
    else
388
    {
389
        auto outs = to_non_const_raw_ptr(outputs_);
163✔
390
        count = source.read_size(max_block_size);
163✔
391
        outs->reserve(count);
163✔
392
        for (size_t out = 0; out < count; ++out)
387✔
393
            outs->emplace_back(
448✔
394
                allocator.new_object<output>(source),
224✔
395
                allocator.deleter<output>(source.get_arena()));
448✔
396
    }
397

398
    locktime_ = source.read_4_bytes_little_endian();
179✔
399
    size_ = serialized_size(*inputs_, *outputs_, segregated_);
179✔
400
    valid_ = source;
179✔
401
}
179✔
402
BC_POP_WARNING()
403

404
// Serialization.
405
// ----------------------------------------------------------------------------
406

407
// Transactions with empty witnesses always use old serialization (bip144).
408
// If no inputs are witness programs then witness hash is tx hash (bip141).
409
data_chunk transaction::to_data(bool witness) const NOEXCEPT
10✔
410
{
411
    witness &= segregated_;
10✔
412

413
    data_chunk data(serialized_size(witness));
10✔
414
    stream::out::copy ostream(data);
10✔
415
    to_data(ostream, witness);
10✔
416
    return data;
20✔
417
}
10✔
418

419
void transaction::to_data(std::ostream& stream, bool witness) const NOEXCEPT
11✔
420
{
421
    witness &= segregated_;
11✔
422

423
    write::bytes::ostream out(stream);
11✔
424
    to_data(out, witness);
11✔
425
}
11✔
426

427
void transaction::to_data(writer& sink, bool witness) const NOEXCEPT
969✔
428
{
429
    witness &= segregated_;
969✔
430

431
    sink.write_4_bytes_little_endian(version_);
969✔
432

433
    if (witness)
969✔
434
    {
435
        sink.write_byte(witness_marker);
2✔
436
        sink.write_byte(witness_enabled);
2✔
437
    }
438

439
    sink.write_variable(inputs_->size());
969✔
440
    for (const auto& input: *inputs_)
2,358✔
441
        input->to_data(sink);
1,389✔
442

443
    sink.write_variable(outputs_->size());
969✔
444
    for (const auto& output: *outputs_)
2,639✔
445
        output->to_data(sink);
1,670✔
446

447
    if (witness)
969✔
448
        for (auto& input: *inputs_)
5✔
449
            input->witness().to_data(sink, true);
3✔
450

451
    sink.write_4_bytes_little_endian(locktime_);
969✔
452
}
969✔
453

454
// static/private
455
transaction::sizes transaction::serialized_size(
2,093✔
456
    const chain::input_cptrs& inputs,
457
    const chain::output_cptrs& outputs, bool segregated) NOEXCEPT
458
{
459
    sizes size{ zero, zero };
2,093✔
460

461
    // Keep the condition outside of the loop.
462
    if (segregated)
2,093✔
463
    {
464
        std::for_each(inputs.begin(), inputs.end(), [&](const auto& in) NOEXCEPT
76✔
465
        {
466
            size.nominal = ceilinged_add(size.nominal, in->nominal_size());
92✔
467
            size.witnessed = ceilinged_add(size.witnessed, in->witnessed_size());
46✔
468
        });
46✔
469
    }
470
    else
471
    {
472
        // Witness must be zeroed because witnesses have nonzero size when they
473
        // are zero-valued, so they can be archived easily. Also it would be
474
        // wasteful to to count mutiple zero sizes, so exclude them here.
475
        std::for_each(inputs.begin(), inputs.end(), [&](const auto& in) NOEXCEPT
4,147✔
476
        {
477
            size.nominal = ceilinged_add(size.nominal, in->nominal_size());
2,084✔
478
        });
2,084✔
479
    }
480

481
    const auto outs = [](size_t total, const auto& output) NOEXCEPT
589✔
482
    {
483
        return ceilinged_add(total, output->serialized_size());
589✔
484
    };
485

486
    constexpr auto base_const_size = ceilinged_add(
2,093✔
487
        sizeof(version_),
488
        sizeof(locktime_));
489

490
    constexpr auto witness_const_size = ceilinged_add(
2,093✔
491
        sizeof(witness_marker),
492
        sizeof(witness_enabled));
493

494
    const auto base_size = ceilinged_add(ceilinged_add(ceilinged_add(
2,093✔
495
        base_const_size,
496
        variable_size(inputs.size())),
497
        variable_size(outputs.size())),
498
        std::accumulate(outputs.begin(), outputs.end(), zero, outs));
499

500
    const auto nominal_size = ceilinged_add(
2,093✔
501
        base_size,
502
        size.nominal);
503

504
    const auto witnessed_size = ceilinged_add(ceilinged_add(
2,093✔
505
        base_size,
506
        witness_const_size),
507
        size.witnessed);
508

509
    return { nominal_size, witnessed_size };
2,093✔
510
}
511

512
size_t transaction::serialized_size(bool witness) const NOEXCEPT
563✔
513
{
514
    witness &= segregated_;
563✔
515

516
    return witness ? size_.witnessed : size_.nominal;
563✔
517
}
518

519
// Properties.
520
// ----------------------------------------------------------------------------
521

522
bool transaction::is_valid() const NOEXCEPT
775✔
523
{
524
    return valid_;
775✔
525
}
526

527
size_t transaction::inputs() const NOEXCEPT
1,565✔
528
{
529
    return inputs_->size();
1,565✔
530
}
531

532
size_t transaction::outputs() const NOEXCEPT
1✔
533
{
534
    return outputs_->size();
1✔
535
}
536

537
uint32_t transaction::version() const NOEXCEPT
6✔
538
{
539
    return version_;
4✔
540
}
541

542
uint32_t transaction::locktime() const NOEXCEPT
15✔
543
{
544
    return locktime_;
4✔
545
}
546

547
const inputs_cptr& transaction::inputs_ptr() const NOEXCEPT
2,440✔
548
{
549
    return inputs_;
2,440✔
550
}
551

552
const outputs_cptr& transaction::outputs_ptr() const NOEXCEPT
62✔
553
{
554
    return outputs_;
62✔
555
}
556

557
uint64_t transaction::fee() const NOEXCEPT
4✔
558
{
559
    // Underflow returns zero (and is_overspent() will be true).
560
    // This is value of prevouts spent by inputs minus that claimed by outputs.
561
    return floored_subtract(value(), claim());
4✔
562
}
563

564
void transaction::set_nominal_hash(hash_digest&& hash) const NOEXCEPT
9✔
565
{
566
    nominal_hash_ = to_unique(std::move(hash));
18✔
567
}
9✔
568

569
void transaction::set_witness_hash(hash_digest&& hash) const NOEXCEPT
2✔
570
{
571
    witness_hash_ = to_unique(std::move(hash));
4✔
572
}
2✔
573

574
const hash_digest& transaction::get_hash(bool witness) const NOEXCEPT
13✔
575
{
576
    if (witness)
13✔
577
    {
578
        if (!witness_hash_) set_witness_hash(hash(witness));
3✔
579
        return *witness_hash_;
3✔
580
    }
581
    else
582
    {
583
        if (!nominal_hash_) set_nominal_hash(hash(witness));
10✔
584
        return *nominal_hash_;
10✔
585
    }
586
}
587

588
hash_digest transaction::hash(bool witness) const NOEXCEPT
937✔
589
{
590
    if (segregated_)
937✔
591
    {
592
        if (witness)
23✔
593
        {
594
            // Witness coinbase tx hash is assumed to be null_hash (bip141).
595
            if (witness_hash_) return *witness_hash_;
×
596
            if (is_coinbase()) return null_hash;
×
597
        }
598
        else
599
        {
600
            if (nominal_hash_) return *nominal_hash_;
23✔
601
        }
602
    }
603
    else
604
    {
605
        if (nominal_hash_) return *nominal_hash_;
914✔
606
    }
607

608
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
609
    hash_digest digest;
930✔
610
    BC_POP_WARNING()
611

612
    stream::out::fast stream{ digest };
930✔
613
    hash::sha256x2::fast sink{ stream };
930✔
614
    to_data(sink, witness);
930✔
615
    sink.flush();
930✔
616
    return digest;
930✔
617
}
930✔
618

619
// Methods.
620
// ----------------------------------------------------------------------------
621

622
bool transaction::is_dusty(uint64_t minimum_output_value) const NOEXCEPT
6✔
623
{
624
    const auto dusty = [=](const auto& output) NOEXCEPT
9✔
625
    {
626
        return output->is_dust(minimum_output_value);
9✔
627
    };
6✔
628

629
    return std::any_of(outputs_->begin(), outputs_->end(), dusty);
6✔
630
}
631

632
size_t transaction::signature_operations(bool bip16, bool bip141) const NOEXCEPT
1✔
633
{
634
    // Includes BIP16 p2sh additional sigops, max_size_t if prevout invalid.
635
    const auto in = [=](size_t total, const auto& input) NOEXCEPT
×
636
    {
637
        return ceilinged_add(total, input->signature_operations(bip16, bip141));
×
638
    };
1✔
639

640
    const auto out = [=](size_t total, const auto& output) NOEXCEPT
×
641
    {
642
        return ceilinged_add(total, output->signature_operations(bip141));
×
643
    };
1✔
644

645
    // Overflow returns max_size_t.
646
    return ceilinged_add(
1✔
647
        std::accumulate(inputs_->begin(), inputs_->end(), zero, in),
648
        std::accumulate(outputs_->begin(), outputs_->end(), zero, out));
1✔
649
}
650

651
chain::points transaction::points() const NOEXCEPT
4✔
652
{
653
    chain::points out(inputs_->size());
4✔
654

655
    const auto point = [](const auto& input) NOEXCEPT
8✔
656
    {
657
        return input->point();
8✔
658
    };
659

660
    std::transform(inputs_->begin(), inputs_->end(), out.begin(), point);
4✔
661
    return out;
4✔
662
}
663

664
hash_digest transaction::outputs_hash() const NOEXCEPT
8✔
665
{
666
    if (sighash_cache_)
8✔
667
        return sighash_cache_->outputs;
×
668

669
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
670
    hash_digest digest;
8✔
671
    BC_POP_WARNING()
672
        
673
    stream::out::fast stream{ digest };
8✔
674
    hash::sha256x2::fast sink{ stream };
8✔
675

676
    const auto& outs = *outputs_;
8✔
677
    for (const auto& output: outs)
22✔
678
        output->to_data(sink);
14✔
679

680
    sink.flush();
8✔
681
    return digest;
8✔
682
}
8✔
683

684
hash_digest transaction::points_hash() const NOEXCEPT
11✔
685
{
686
    if (sighash_cache_)
11✔
687
        return sighash_cache_->points;
×
688

689
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
690
    hash_digest digest;
11✔
691
    BC_POP_WARNING()
692

693
    stream::out::fast stream{ digest };
11✔
694
    hash::sha256x2::fast sink{ stream };
11✔
695

696
    const auto& ins = *inputs_;
11✔
697
    for (const auto& input: ins)
27✔
698
        input->point().to_data(sink);
16✔
699

700
    sink.flush();
11✔
701
    return digest;
11✔
702
}
11✔
703

704
hash_digest transaction::sequences_hash() const NOEXCEPT
7✔
705
{
706
    if (sighash_cache_)
7✔
707
        return sighash_cache_->sequences;
×
708

709
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
710
    hash_digest digest;
7✔
711
    BC_POP_WARNING()
712

713
    stream::out::fast stream{ digest };
7✔
714
    hash::sha256x2::fast sink{ stream };
7✔
715

716
    const auto& ins = *inputs_;
7✔
717
    for (const auto& input: ins)
17✔
718
        sink.write_4_bytes_little_endian(input->sequence());
10✔
719

720
    sink.flush();
7✔
721
    return digest;
7✔
722
}
7✔
723

724
// Signing (unversioned).
725
// ----------------------------------------------------------------------------
726

727
// private
728
transaction::input_iterator transaction::input_at(
4✔
729
    uint32_t index) const NOEXCEPT
730
{
731
    // Guarded by check_signature and create_endorsement.
732
    BC_ASSERT_MSG(index < inputs_->size(), "invalid input index");
4✔
733

734
    return std::next(inputs_->begin(), index);
4✔
735
}
736

737
// private
738
uint32_t transaction::input_index(const input_iterator& input) const NOEXCEPT
25✔
739
{
740
    // Guarded by unversioned_signature_hash and output_hash.
741
    BC_ASSERT_MSG(inputs_->begin() != inputs_->end(), "invalid input iterator");
25✔
742

743
    return possible_narrow_and_sign_cast<uint32_t>(
25✔
744
        std::distance(inputs_->begin(), input));
×
745
}
746

747
//*****************************************************************************
748
// CONSENSUS: Due to masking of bits 6/7 (8 is the anyone_can_pay flag),
749
// there are 4 possible 7 bit values that can set "single" and 4 others that
750
// can set none, and yet all other values set "all".
751
//*****************************************************************************
752
inline coverage mask_sighash(uint8_t sighash_flags) NOEXCEPT
41✔
753
{
754
    switch (sighash_flags & coverage::mask)
41✔
755
    {
756
        case coverage::hash_single:
757
            return coverage::hash_single;
758
        case coverage::hash_none:
2✔
759
            return coverage::hash_none;
2✔
760
        default:
18✔
761
            return coverage::hash_all;
18✔
762
    }
763
}
764

765
void transaction::signature_hash_single(writer& sink,
4✔
766
    const input_iterator& input, const script& sub,
767
    uint8_t sighash_flags) const NOEXCEPT
768
{
769
    const auto write_inputs = [this, &input, &sub, sighash_flags](
8✔
770
        writer& sink) NOEXCEPT
4✔
771
    {
772
        const auto& self = **input;
4✔
773
        const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
4✔
774
        input_cptrs::const_iterator in;
4✔
775

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

778
        for (in = inputs_->begin(); !anyone && in != input; ++in)
4✔
779
        {
780
            (*in)->point().to_data(sink);
×
781
            sink.write_bytes(empty_script());
×
782
            sink.write_bytes(zero_sequence());
×
783
        }
784

785
        self.point().to_data(sink);
4✔
786
        sub.to_data(sink, prefixed);
4✔
787
        sink.write_4_bytes_little_endian(self.sequence());
4✔
788

789
        for (++in; !anyone && in != inputs_->end(); ++in)
5✔
790
        {
791
            (*in)->point().to_data(sink);
1✔
792
            sink.write_bytes(empty_script());
1✔
793
            sink.write_bytes(zero_sequence());
1✔
794
        }
795
    };
4✔
796

797
    const auto write_outputs = [this, &input](writer& sink) NOEXCEPT
12✔
798
    {
799
        const auto index = input_index(input);
4✔
800

801
        sink.write_variable(add1(index));
4✔
802

803
        for (size_t output = 0; output < index; ++output)
5✔
804
            sink.write_bytes(null_output());
1✔
805

806
        // Guarded by unversioned_signature_hash.
807
        outputs_->at(index)->to_data(sink);
4✔
808
    };
8✔
809

810
    sink.write_4_bytes_little_endian(version_);
4✔
811
    write_inputs(sink);
4✔
812
    write_outputs(sink);
4✔
813
    sink.write_4_bytes_little_endian(locktime_);
4✔
814
    sink.write_4_bytes_little_endian(sighash_flags);
4✔
815
}
4✔
816

817
void transaction::signature_hash_none(writer& sink,
×
818
    const input_iterator& input, const script& sub,
819
    uint8_t sighash_flags) const NOEXCEPT
820
{
821
    const auto write_inputs = [this, &input, &sub, sighash_flags](
×
822
        writer& sink) NOEXCEPT
×
823
    {
824
        const auto& self = **input;
×
825
        const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
×
826
        input_cptrs::const_iterator in;
×
827

828
        sink.write_variable(anyone ? one : inputs_->size());
×
829

830
        for (in = inputs_->begin(); !anyone && in != input; ++in)
×
831
        {
832
            (*in)->point().to_data(sink);
×
833
            sink.write_bytes(empty_script());
×
834
            sink.write_bytes(zero_sequence());
×
835
        }
836

837
        self.point().to_data(sink);
×
838
        sub.to_data(sink, prefixed);
×
839
        sink.write_4_bytes_little_endian(self.sequence());
×
840

841
        for (++in; !anyone && in != inputs_->end(); ++in)
×
842
        {
843
            (*in)->point().to_data(sink);
×
844
            sink.write_bytes(empty_script());
×
845
            sink.write_bytes(zero_sequence());
×
846
        }
847
    };
×
848

849
    sink.write_4_bytes_little_endian(version_);
×
850
    write_inputs(sink);
×
851
    sink.write_variable(zero);
×
852
    sink.write_4_bytes_little_endian(locktime_);
×
853
    sink.write_4_bytes_little_endian(sighash_flags);
×
854
}
×
855

856
void transaction::signature_hash_all(writer& sink,
12✔
857
    const input_iterator& input, const script& sub,
858
    uint8_t flags) const NOEXCEPT
859
{
860
    const auto write_inputs = [this, &input, &sub, flags](
24✔
861
        writer& sink) NOEXCEPT
43✔
862
    {
863
        const auto& self = **input;
12✔
864
        const auto anyone = to_bool(flags & coverage::anyone_can_pay);
12✔
865
        input_cptrs::const_iterator in;
12✔
866

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

869
        for (in = inputs_->begin(); !anyone && in != input; ++in)
15✔
870
        {
871
            (*in)->point().to_data(sink);
3✔
872
            sink.write_bytes(empty_script());
3✔
873
            sink.write_4_bytes_little_endian((*in)->sequence());
3✔
874
        }
875

876
        self.point().to_data(sink);
12✔
877
        sub.to_data(sink, prefixed);
12✔
878
        sink.write_4_bytes_little_endian(self.sequence());
12✔
879

880
        for (++in; !anyone && in != inputs_->end(); ++in)
16✔
881
        {
882
            (*in)->point().to_data(sink);
4✔
883
            sink.write_bytes(empty_script());
4✔
884
            sink.write_4_bytes_little_endian((*in)->sequence());
4✔
885
        }
886
    };
12✔
887

888
    const auto write_outputs = [this](writer& sink) NOEXCEPT
36✔
889
    {
890
        sink.write_variable(outputs_->size());
12✔
891
        for (const auto& output: *outputs_)
27✔
892
            output->to_data(sink);
15✔
893
    };
24✔
894

895
    sink.write_4_bytes_little_endian(version_);
12✔
896
    write_inputs(sink);
12✔
897
    write_outputs(sink);
12✔
898
    sink.write_4_bytes_little_endian(locktime_);
12✔
899
    sink.write_4_bytes_little_endian(flags);
12✔
900
}
12✔
901

902
// private
903
hash_digest transaction::unversioned_signature_hash(
19✔
904
    const input_iterator& input, const script& sub,
905
    uint8_t sighash_flags) const NOEXCEPT
906
{
907
    // Set options.
908
    const auto flag = mask_sighash(sighash_flags);
19✔
909

910
    // Create hash writer.
911
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
912
    hash_digest digest;
19✔
913
    BC_POP_WARNING()
914

915
    stream::out::fast stream{ digest };
19✔
916
    hash::sha256x2::fast sink{ stream };
19✔
917

918
    switch (flag)
19✔
919
    {
920
        case coverage::hash_single:
7✔
921
        {
7✔
922
            //*****************************************************************
923
            // CONSENSUS: return one_hash if index exceeds outputs in sighash.
924
            // Related Bug: bitcointalk.org/index.php?topic=260595
925
            // Exploit: joncave.co.uk/2014/08/bitcoin-sighash-single/
926
            //*****************************************************************
927
            if (input_index(input) >= outputs_->size())
7✔
928
                return one_hash;
3✔
929

930
            signature_hash_single(sink, input, sub, sighash_flags);
4✔
931
            break;
4✔
932
        }
933
        case coverage::hash_none:
×
934
        {
×
935
            signature_hash_none(sink, input, sub, sighash_flags);
×
936
            break;
×
937
        }
938
        default:
12✔
939
        case coverage::hash_all:
12✔
940
        {
12✔
941
            signature_hash_all(sink, input, sub, sighash_flags);
12✔
942
        }
943
    }
944

945
    sink.flush();
16✔
946
    return digest;
16✔
947
}
19✔
948

949
// Signing (version 0).
950
// ----------------------------------------------------------------------------
951

952
// private
953
// TODO: taproot requires both single and double hash of each.
954
void transaction::initialize_sighash_cache() const NOEXCEPT
2✔
955
{
956
    // This overconstructs the cache (anyone or !all), however it is simple.
957
    if (!segregated_)
2✔
958
        return;
959

960
    sighash_cache_ = to_unique<sighash_cache>
2✔
961
    (
4✔
962
        outputs_hash(),
2✔
963
        points_hash(),
2✔
964
        sequences_hash()
4✔
965
    );
966
}
967

968
// private
969
hash_digest transaction::output_hash(const input_iterator& input) const NOEXCEPT
14✔
970
{
971
    const auto index = input_index(input);
14✔
972

973
    //*************************************************************************
974
    // CONSENSUS: if index exceeds outputs in signature hash, return null_hash.
975
    //*************************************************************************
976
    if (index >= outputs_->size())
14✔
977
        return null_hash;
2✔
978

979
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
980
    hash_digest digest;
12✔
981
    BC_POP_WARNING()
982

983
    stream::out::fast stream{ digest };
12✔
984
    hash::sha256x2::fast sink{ stream };
12✔
985
    outputs_->at(index)->to_data(sink);
12✔
986
    sink.flush();
12✔
987
    return digest;
12✔
988
}
12✔
989

990
// private
991
hash_digest transaction::version_0_signature_hash(const input_iterator& input,
29✔
992
    const script& sub, uint64_t value, uint8_t sighash_flags,
993
    bool bip143) const NOEXCEPT
994
{
995
    // bip143/v0: the way of serialization is changed.
996
    if (!bip143)
29✔
997
        return unversioned_signature_hash(input, sub, sighash_flags);
7✔
998

999
    // Set options.
1000
    const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
22✔
1001
    const auto flag = mask_sighash(sighash_flags);
22✔
1002
    const auto all = (flag == coverage::hash_all);
22✔
1003
    const auto single = (flag == coverage::hash_single);
22✔
1004
    const auto& self = **input;
22✔
1005

1006
    // Create hash writer.
1007
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
1008
    hash_digest digest;
22✔
1009
    BC_POP_WARNING()
1010

1011
    stream::out::fast stream{ digest };
22✔
1012
    hash::sha256x2::fast sink{ stream };
22✔
1013

1014
    // Create signature hash.
1015
    sink.write_little_endian(version_);
22✔
1016

1017
    // Conditioning points, sequences, and outputs writes on cache_ instead of
1018
    // conditionally passing them from methods avoids copying the cached hash.
1019

1020
    // points
1021
    sink.write_bytes(!anyone ? points_hash() : null_hash);
22✔
1022

1023
    // sequences
1024
    sink.write_bytes(!anyone && all ? sequences_hash() : null_hash);
22✔
1025

1026
    self.point().to_data(sink);
22✔
1027
    sub.to_data(sink, prefixed);
22✔
1028
    sink.write_little_endian(value);
22✔
1029
    sink.write_little_endian(self.sequence());
22✔
1030

1031
    // outputs
1032
    if (single)
22✔
1033
        sink.write_bytes(output_hash(input));
14✔
1034
    else
1035
        sink.write_bytes(all ? outputs_hash() : null_hash);
8✔
1036

1037
    sink.write_little_endian(locktime_);
22✔
1038
    sink.write_4_bytes_little_endian(sighash_flags);
22✔
1039

1040
    sink.flush();
22✔
1041
    return digest;
22✔
1042
}
22✔
1043

1044
// Signing (unversioned and version 0).
1045
// ----------------------------------------------------------------------------
1046

1047
// ****************************************************************************
1048
// CONSENSUS: sighash flags are carried in a single byte but are encoded as 4
1049
// bytes in the signature hash preimage serialization.
1050
// ****************************************************************************
1051

1052
hash_digest transaction::signature_hash(const input_iterator& input,
41✔
1053
    const script& sub, uint64_t value, uint8_t sighash_flags,
1054
    script_version version, bool bip143) const NOEXCEPT
1055
{
1056
    // There is no rational interpretation of a signature hash for a coinbase.
1057
    BC_ASSERT(!is_coinbase());
41✔
1058

1059
    switch (version)
41✔
1060
    {
1061
        case script_version::unversioned:
12✔
1062
            return unversioned_signature_hash(input, sub, sighash_flags);
12✔
1063
        case script_version::zero:
29✔
1064
            return version_0_signature_hash(input, sub, value, sighash_flags,
29✔
1065
                bip143);
29✔
1066
        case script_version::reserved:
×
1067
        default:
×
1068
            return {};
×
1069
    }
1070
}
1071

1072
// This is not used internal to the library.
1073
bool transaction::check_signature(const ec_signature& signature,
2✔
1074
    const data_slice& public_key, const script& sub, uint32_t index,
1075
    uint64_t value, uint8_t sighash_flags, script_version version,
1076
    bool bip143) const NOEXCEPT
1077
{
1078
    if ((index >= inputs_->size()) || signature.empty() || public_key.empty())
2✔
1079
        return false;
1080

1081
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
1082
        sighash_flags, version, bip143);
1083

1084
    // Validate the EC signature.
1085
    return verify_signature(public_key, sighash, signature);
2✔
1086
}
1087

1088
// This is not used internal to the library.
1089
bool transaction::create_endorsement(endorsement& out, const ec_secret& secret,
2✔
1090
    const script& sub, uint32_t index, uint64_t value, uint8_t sighash_flags,
1091
    script_version version, bool bip143) const NOEXCEPT
1092
{
1093
    if (index >= inputs_->size())
2✔
1094
        return false;
1095

1096
    out.reserve(max_endorsement_size);
2✔
1097
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
1098
        sighash_flags, version, bip143);
1099

1100
    // Create the EC signature and encode as DER.
1101
    ec_signature signature;
2✔
1102
    if (!sign(signature, secret, sighash) || !encode_signature(out, signature))
2✔
1103
        return false;
×
1104

1105
    // Add the sighash type to the end of the DER signature -> endorsement.
1106
    out.push_back(sighash_flags);
2✔
1107
    ////out.shrink_to_fit();
1108
    return true;
2✔
1109
}
1110

1111
// Guard (context free).
1112
// ----------------------------------------------------------------------------
1113

1114
bool transaction::is_coinbase() const NOEXCEPT
80✔
1115
{
1116
    return is_one(inputs_->size()) && inputs_->front()->point().is_null();
80✔
1117
}
1118

1119
bool transaction::is_internal_double_spend() const NOEXCEPT
4✔
1120
{
1121
    // TODO: optimize (see block.is_internal_double_spend).
1122
    return !is_distinct(points());
4✔
1123
}
1124

1125
// TODO: a pool (non-coinbase) tx must fit into a block (with a coinbase).
1126
bool transaction::is_oversized() const NOEXCEPT
×
1127
{
1128
    return serialized_size(false) > max_block_size;
×
1129
}
1130

1131
// Guard (contextual).
1132
// ----------------------------------------------------------------------------
1133

1134
// static/private
1135
bool transaction::segregated(const chain::inputs& inputs) NOEXCEPT
1✔
1136
{
1137
    const auto witnessed = [](const auto& input) NOEXCEPT
2✔
1138
    {
1139
        return !input.witness().stack().empty();
1✔
1140
    };
1141

1142
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
1✔
1143
}
1144

1145
// static/private
1146
bool transaction::segregated(const chain::input_cptrs& inputs) NOEXCEPT
903✔
1147
{
1148
    const auto witnessed = [](const auto& input) NOEXCEPT
906✔
1149
    {
1150
        return !input->witness().stack().empty();
906✔
1151
    };
1152

1153
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
903✔
1154
}
1155

1156
bool transaction::is_segregated() const NOEXCEPT
4✔
1157
{
1158
    return segregated_;
4✔
1159
}
1160

1161
size_t transaction::weight() const NOEXCEPT
×
1162
{
1163
    // Block weight is 3 * base size * + 1 * total size (bip141).
1164
    return ceilinged_add(
×
1165
        ceilinged_multiply(base_size_contribution, serialized_size(false)),
1166
        ceilinged_multiply(total_size_contribution, serialized_size(true)));
×
1167
}
1168

1169
bool transaction::is_overweight() const NOEXCEPT
×
1170
{
1171
    return weight() > max_block_weight;
×
1172
}
1173

1174
//*****************************************************************************
1175
// CONSENSUS: Legacy sigops are counted in coinbase scripts despite the fact
1176
// that coinbase input scripts are never executed. There is no need to exclude
1177
// p2sh coinbase sigops since there is never a script to count.
1178
//*****************************************************************************
1179
bool transaction::is_signature_operations_limit(bool bip16,
×
1180
    bool bip141) const NOEXCEPT
1181
{
1182
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
1183
    return signature_operations(bip16, bip141) > limit;
×
1184
}
1185

1186
// Check (context free).
1187
// ----------------------------------------------------------------------------
1188

1189
bool transaction::is_empty() const NOEXCEPT
9✔
1190
{
1191
    return inputs_->empty() || outputs_->empty();
9✔
1192
}
1193

1194
bool transaction::is_null_non_coinbase() const NOEXCEPT
7✔
1195
{
1196
    BC_ASSERT(!is_coinbase());
7✔
1197

1198
    const auto invalid = [](const auto& input) NOEXCEPT
9✔
1199
    {
1200
        return input->point().is_null();
9✔
1201
    };
1202

1203
    // True if not coinbase but has null previous_output(s).
1204
    return std::any_of(inputs_->begin(), inputs_->end(), invalid);
7✔
1205
}
1206

1207
bool transaction::is_invalid_coinbase_size() const NOEXCEPT
9✔
1208
{
1209
    BC_ASSERT(is_coinbase());
9✔
1210

1211
    // True if coinbase and has invalid input[0] script size.
1212
    const auto script_size = inputs_->front()->script().serialized_size(false);
9✔
1213
    return script_size < min_coinbase_size || script_size > max_coinbase_size;
9✔
1214
}
1215

1216
// Accept (contextual).
1217
// ----------------------------------------------------------------------------
1218

1219
bool transaction::is_non_final(size_t height, uint32_t timestamp,
5✔
1220
    uint32_t median_time_past, bool bip113) const NOEXCEPT
1221
{
1222
    // BIP113: comparing the locktime against the median of the past 11 block
1223
    // timestamps, rather than the timestamp of the block including the tx.
1224
    const auto time = bip113 ? median_time_past : timestamp;
5✔
1225

1226
    const auto finalized = [](const auto& input) NOEXCEPT
2✔
1227
    {
1228
        return input->is_final();
2✔
1229
    };
1230

1231
    const auto height_time = locktime_ < locktime_threshold ? height : time;
5✔
1232

1233
    return !(is_zero(locktime_) || locktime_ < height_time ||
8✔
1234
        std::all_of(inputs_->begin(), inputs_->end(), finalized));
3✔
1235
}
1236

1237
bool transaction::is_missing_prevouts() const NOEXCEPT
3✔
1238
{
1239
    BC_ASSERT(!is_coinbase());
3✔
1240

1241
    // Null or invalid prevout indicates not found.
1242
    const auto missing = [](const auto& input) NOEXCEPT
2✔
1243
    {
1244
        return !input->prevout;
1245
    };
1246

1247
    return std::any_of(inputs_->begin(), inputs_->end(), missing);
3✔
1248
}
1249

1250
uint64_t transaction::claim() const NOEXCEPT
8✔
1251
{
1252
    // Overflow returns max_uint64.
1253
    const auto sum = [](uint64_t total, const auto& output) NOEXCEPT
8✔
1254
    {
1255
        return ceilinged_add(total, output->value());
8✔
1256
    };
1257

1258
    // The amount claimed by outputs.
1259
    return std::accumulate(outputs_->begin(), outputs_->end(), 0_u64, sum);
8✔
1260
}
1261

1262
uint64_t transaction::value() const NOEXCEPT
9✔
1263
{
1264
    // Overflow, not populated, and coinbase (default) return max_uint64.
1265
    const auto sum = [](uint64_t total, const auto& input) NOEXCEPT
7✔
1266
    {
1267
        const auto value = input->prevout ? input->prevout->value() : max_uint64;
7✔
1268
        return ceilinged_add(total, value);
7✔
1269
    };
1270

1271
    // The amount of prevouts (referenced by inputs).
1272
    return std::accumulate(inputs_->begin(), inputs_->end(), 0_u64, sum);
9✔
1273
}
1274

1275
bool transaction::is_overspent() const NOEXCEPT
2✔
1276
{
1277
    BC_ASSERT(!is_coinbase());
2✔
1278

1279
    return claim() > value();
2✔
1280
}
1281

1282
constexpr bool is_non_coinbase_mature(size_t tx_height, size_t height) NOEXCEPT
2✔
1283
{
1284
    return tx_height <= height;
2✔
1285
}
1286

1287
//*****************************************************************************
1288
// CONSENSUS: Coinbase output matures at 100 blocks depth.
1289
// CONSENSUS: Genesis coinbase is forever immature (exception).
1290
//*****************************************************************************
1291
bool transaction::is_coinbase_mature(size_t coinbase_height,
3✔
1292
    size_t height) NOEXCEPT
1293
{
1294
    return !is_zero(coinbase_height) &&
5✔
1295
        ceilinged_add(coinbase_height, coinbase_maturity) <= height;
3✔
1296
}
1297

1298
bool transaction::is_immature(size_t height) const NOEXCEPT
6✔
1299
{
1300
    BC_ASSERT(!is_coinbase());
6✔
1301

1302
    // Spends internal to a block are handled by block validation.
1303
    const auto mature = [=](const auto& input) NOEXCEPT
5✔
1304
    {
1305
        return input->metadata.coinbase ?
5✔
1306
            is_coinbase_mature(input->metadata.height, height) :
3✔
1307
            is_non_coinbase_mature(input->metadata.height, height);
2✔
1308
    };
6✔
1309

1310
    return !std::all_of(inputs_->begin(), inputs_->end(), mature);
6✔
1311
}
1312

1313
bool transaction::is_locked(size_t height,
4✔
1314
    uint32_t median_time_past) const NOEXCEPT
1315
{
1316
    // BIP68: not applied to the sequence of the input of a coinbase.
1317
    BC_ASSERT(!is_coinbase());
4✔
1318

1319
    // BIP68: applied to txs with a version greater than or equal to two.
1320
    if (version_ < relative_locktime_min_version)
4✔
1321
        return false;
1322

1323
    // BIP68: references to median time past are as defined by bip113.
1324
    const auto locked = [=](const auto& input) NOEXCEPT
2✔
1325
    {
1326
        return input->is_locked(height, median_time_past);
2✔
1327
    };
2✔
1328

1329
    // BIP68: when the relative lock time is block based, it is interpreted as
1330
    // a minimum block height constraint over the age of the input.
1331
    return std::any_of(inputs_->begin(), inputs_->end(), locked);
2✔
1332
}
1333

1334
// Spends internal to a block are handled by block validation.
1335
bool transaction::is_unconfirmed_spend(size_t height) const NOEXCEPT
×
1336
{
1337
    BC_ASSERT(!is_coinbase());
×
1338

1339
    // Zero is either genesis or not found.
1340
    // Test maturity first to obtain proper error code.
1341
    // Spends internal to a block are handled by block validation.
1342
    const auto unconfirmed = [=](const auto& input) NOEXCEPT
×
1343
    {
1344
        const auto prevout_height = input->metadata.height;
×
1345
        return is_zero(prevout_height) && !(height > prevout_height);
×
1346
    };
×
1347

1348
    return std::any_of(inputs_->begin(), inputs_->end(), unconfirmed);
×
1349
}
1350

1351
bool transaction::is_confirmed_double_spend(size_t height) const NOEXCEPT
4✔
1352
{
1353
    BC_ASSERT(!is_coinbase());
4✔
1354

1355
    // Spends internal to a block are handled by block validation.
1356
    const auto spent = [=](const auto& input) NOEXCEPT
4✔
1357
    {
1358
        return input->metadata.spent && height > input->metadata.height;
4✔
1359
    };
4✔
1360

1361
    return std::any_of(inputs_->begin(), inputs_->end(), spent);
4✔
1362
}
1363

1364
// Guards (for tx pool without compact blocks).
1365
// ----------------------------------------------------------------------------
1366

1367
// Pools do not have coinbases.
1368
// Redundant with block is_internal_double_spend check.
1369
// Redundant with block max_block_size check.
1370
code transaction::guard_check() const NOEXCEPT
×
1371
{
1372
    if (is_coinbase())
×
1373
        return error::coinbase_transaction;
×
1374
    if (is_internal_double_spend())
×
1375
        return error::transaction_internal_double_spend;
×
1376
    if (is_oversized())
×
1377
        return error::transaction_size_limit;
×
1378

1379
    return error::transaction_success;
×
1380
}
1381

1382
// Redundant with block max_block_weight accept.
1383
code transaction::guard_check(const context& ctx) const NOEXCEPT
×
1384
{
1385
    const auto bip141 = ctx.is_enabled(flags::bip141_rule);
×
1386

1387
     if (!bip141 && is_segregated())
×
1388
        return error::unexpected_witness_transaction;
×
1389
    if (bip141 && is_overweight())
×
1390
        return error::transaction_weight_limit;
×
1391

1392
    return error::transaction_success;
×
1393
}
1394

1395
// Redundant with block max_block_sigops accept.
1396
code transaction::guard_accept(const context& ctx) const NOEXCEPT
×
1397
{
1398
    const auto bip16 = ctx.is_enabled(flags::bip16_rule);
×
1399
    const auto bip141 = ctx.is_enabled(flags::bip141_rule);
×
1400

1401
    if (is_missing_prevouts())
×
1402
        return error::missing_previous_output;
×
1403
    if (is_signature_operations_limit(bip16, bip141))
×
1404
        return error::transaction_sigop_limit;
×
1405

1406
    return error::transaction_success;
×
1407
}
1408

1409
// Validation.
1410
// ----------------------------------------------------------------------------
1411

1412
// DO invoke on coinbase.
1413
code transaction::check() const NOEXCEPT
5✔
1414
{
1415
    const auto coinbase = is_coinbase();
5✔
1416

1417
    if (is_empty())
5✔
1418
        return error::empty_transaction;
×
1419
    if (coinbase && is_invalid_coinbase_size())
5✔
1420
        return error::invalid_coinbase_script_size;
×
1421
    if (!coinbase && is_null_non_coinbase())
5✔
1422
        return error::previous_output_null;
×
1423

1424
    return error::transaction_success;
5✔
1425
}
1426

1427
// forks
1428
// height
1429
// timestamp
1430
// median_time_past
1431

1432
// DO invoke on coinbase.
1433
code transaction::check(const context& ctx) const NOEXCEPT
×
1434
{
1435
    const auto bip113 = ctx.is_enabled(bip113_rule);
×
1436

1437
    if (is_non_final(ctx.height, ctx.timestamp, ctx.median_time_past, bip113))
×
1438
        return error::transaction_non_final;
×
1439

1440
    return error::transaction_success;
×
1441
}
1442

1443
// Do not need to invoke on coinbase.
1444
// This assumes that prevout caching is completed on all inputs.
1445
code transaction::accept(const context&) const NOEXCEPT
×
1446
{
1447
    ////BC_ASSERT(!is_coinbase());
1448

1449
    if (is_coinbase())
×
1450
        return error::transaction_success;
×
1451
    if (is_missing_prevouts())
×
1452
        return error::missing_previous_output;
×
1453
    if (is_overspent())
×
1454
        return error::spend_exceeds_value;
×
1455

1456
    return error::transaction_success;
×
1457
}
1458

1459
// forks
1460
// height
1461
// median_time_past
1462

1463
// Do not need to invoke on coinbase.
1464
// Node performs these checks through database query.
1465
// This assumes that prevout and metadata caching are completed on all inputs.
1466
code transaction::confirm(const context& ctx) const NOEXCEPT
×
1467
{
1468
    ////BC_ASSERT(!is_coinbase());
1469
    const auto bip68 = ctx.is_enabled(bip68_rule);
×
1470

1471
    if (is_coinbase())
×
1472
        return error::transaction_success;
×
1473
    if (bip68 && is_locked(ctx.height, ctx.median_time_past))
×
1474
        return error::relative_time_locked;
×
1475
    if (is_immature(ctx.height))
×
1476
        return error::coinbase_maturity;
×
1477
    if (is_unconfirmed_spend(ctx.height))
×
1478
        return error::unconfirmed_spend;
×
1479
    if (is_confirmed_double_spend(ctx.height))
×
1480
        return error::confirmed_double_spend;
×
1481

1482
    return error::transaction_success;
×
1483
}
1484

1485
// Connect (contextual).
1486
// ----------------------------------------------------------------------------
1487

1488
// forks
1489

1490
// Do not need to invoke on coinbase.
1491
code transaction::connect(const context& ctx) const NOEXCEPT
2✔
1492
{
1493
    ////BC_ASSERT(!is_coinbase());
1494

1495
    if (is_coinbase())
2✔
1496
        return error::transaction_success;
×
1497

1498
    code ec{};
2✔
1499
    using namespace machine;
2✔
1500
    initialize_sighash_cache();
2✔
1501

1502
    // Validate scripts.
1503
    for (auto input = inputs_->begin(); input != inputs_->end(); ++input)
6✔
1504
    {
1505
        // Evaluate rolling scripts with linear search but constant erase.
1506
        // Evaluate non-rolling scripts with constant search but linear erase.
1507
        if ((ec = (*input)->is_roller() ?
8✔
1508
            interpreter<linked_stack>::connect(ctx, *this, input) :
×
1509
            interpreter<contiguous_stack>::connect(ctx, *this, input)))
4✔
1510
            return ec;
×
1511
    }
1512

1513
    // TODO: accumulate sigops from each connect result and add coinbase.
1514
    // TODO: return in override with out parameter. more impactful with segwit.
1515
    return error::transaction_success;
2✔
1516
}
1517

1518
BC_POP_WARNING()
1519

1520
// JSON value convertors.
1521
// ----------------------------------------------------------------------------
1522

1523
namespace json = boost::json;
1524

1525
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
1526
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
1527

1528
transaction tag_invoke(json::value_to_tag<transaction>,
2✔
1529
    const json::value& value) NOEXCEPT
1530
{
1531
    return
2✔
1532
    {
1533
        value.at("version").to_number<uint32_t>(),
2✔
1534
        json::value_to<chain::inputs>(value.at("inputs")),
2✔
1535
        json::value_to<chain::outputs>(value.at("outputs")),
4✔
1536
        value.at("locktime").to_number<uint32_t>()
4✔
1537
    };
4✔
1538
}
1539

1540
void tag_invoke(json::value_from_tag, json::value& value,
4✔
1541
    const transaction& tx) NOEXCEPT
1542
{
1543
    value =
4✔
1544
    {
1545
        { "version", tx.version() },
1546
        { "inputs", *tx.inputs_ptr() },
1547
        { "outputs", *tx.outputs_ptr() },
1548
        { "locktime", tx.locktime() }
1549
    };
4✔
1550
}
4✔
1551

1552
BC_POP_WARNING()
1553

1554
transaction::cptr tag_invoke(json::value_to_tag<transaction::cptr>,
×
1555
    const json::value& value) NOEXCEPT
1556
{
1557
    return to_shared(tag_invoke(json::value_to_tag<transaction>{}, value));
×
1558
}
1559

1560
// Shared pointer overload is required for navigation.
1561
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
1562
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
1563

1564
void tag_invoke(json::value_from_tag tag, json::value& value,
2✔
1565
    const transaction::cptr& tx) NOEXCEPT
1566
{
1567
    tag_invoke(tag, value, *tx);
2✔
1568
}
2✔
1569

1570
BC_POP_WARNING()
1571
BC_POP_WARNING()
1572

1573
} // namespace chain
1574
} // namespace system
1575
} // 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