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

libbitcoin / libbitcoin-system / 9952171247

16 Jul 2024 06:56AM UTC coverage: 83.171% (-0.03%) from 83.203%
9952171247

push

github

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

Avoid unnecessary witness initializations, style, comments.

12 of 27 new or added lines in 3 files covered. (44.44%)

5 existing lines in 1 file now uncovered.

10092 of 12134 relevant lines covered (83.17%)

4758960.56 hits per line

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

78.39
/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
    if (other.nominal_hash_)
989✔
UNCOV
102
        nominal_hash_ = to_unique(*other.nominal_hash_);
×
103
    if (other.witness_hash_)
989✔
UNCOV
104
        witness_hash_ = to_unique(*other.witness_hash_);
×
105
    if (other.sighash_cache_)
989✔
UNCOV
106
        sighash_cache_ = to_unique(*other.sighash_cache_);
×
107
}
989✔
108

109
transaction::transaction(uint32_t version, chain::inputs&& inputs,
903✔
110
    chain::outputs&& outputs, uint32_t locktime) NOEXCEPT
903✔
111
  : transaction(version, to_shareds(std::move(inputs)),
1,806✔
112
      to_shareds(std::move(outputs)), locktime)
3,612✔
113
{
114
}
903✔
115

116
transaction::transaction(uint32_t version, const chain::inputs& inputs,
1✔
117
    const chain::outputs& outputs, uint32_t locktime) NOEXCEPT
1✔
118
  : transaction(version, to_shareds(inputs), to_shareds(outputs), locktime,
2✔
119
      segregated(inputs), true)
4✔
120
{
121
}
1✔
122

123
transaction::transaction(uint32_t version, const chain::inputs_cptr& inputs,
903✔
124
    const chain::outputs_cptr& outputs, uint32_t locktime) NOEXCEPT
903✔
125
  : transaction(version, inputs, outputs, locktime, segregated(*inputs), true)
903✔
126
{
127
}
903✔
128

129
transaction::transaction(const data_slice& data, bool witness) NOEXCEPT
41✔
130
  : transaction(stream::in::copy(data), witness)
41✔
131
{
132
}
41✔
133

134
////transaction::transaction(stream::in::fast&& stream, bool witness) NOEXCEPT
135
////  : transaction(read::bytes::fast(stream), witness)
136
////{
137
////}
138

139
transaction::transaction(stream::in::fast& stream, bool witness) NOEXCEPT
2✔
140
  : transaction(read::bytes::fast(stream), witness)
2✔
141
{
142
}
2✔
143

144
transaction::transaction(std::istream&& stream, bool witness) NOEXCEPT
41✔
145
  : transaction(read::bytes::istream(stream), witness)
41✔
146
{
147
}
41✔
148

149
transaction::transaction(std::istream& stream, bool witness) NOEXCEPT
4✔
150
  : transaction(read::bytes::istream(stream), witness)
4✔
151
{
152
}
4✔
153

154
transaction::transaction(reader&& source, bool witness) NOEXCEPT
47✔
155
  : transaction(source, witness/*from_data(source, witness)*/)
47✔
156
{
157
}
×
158

159
transaction::transaction(reader& source, bool witness) NOEXCEPT
179✔
160
////: transaction(from_data(source, witness))
161
  : version_(source.read_4_bytes_little_endian()),
358✔
162
    inputs_(
179✔
163
        source.get_allocator().new_object<input_cptrs>(),
179✔
164
        source.get_allocator().deleter<input_cptrs>(source.get_arena())),
179✔
165
    outputs_(
358✔
166
        source.get_allocator().new_object<output_cptrs>(),
179✔
167
        source.get_allocator().deleter<output_cptrs>(source.get_arena()))
358✔
168
{
169
    assign_data(source, witness);
179✔
170
}
179✔
171

172
// protected
173
transaction::transaction(uint32_t version,
1,914✔
174
    const chain::inputs_cptr& inputs, const chain::outputs_cptr& outputs,
175
    uint32_t locktime, bool segregated, bool valid) NOEXCEPT
1,914✔
176
  : version_(version),
1,914✔
177
    inputs_(inputs ? inputs : to_shared<input_cptrs>()),
3,828✔
178
    outputs_(outputs ? outputs : to_shared<output_cptrs>()),
1,914✔
179
    locktime_(locktime),
1,914✔
180
    segregated_(segregated),
1,914✔
181
    valid_(valid),
1,914✔
182
    size_(serialized_size(*inputs, *outputs, segregated))
3,828✔
183
{
184
}
1,914✔
185

186
// Operators.
187
// ----------------------------------------------------------------------------
188

189
transaction& transaction::operator=(transaction&& other) NOEXCEPT
×
190
{
191
    *this = other;
×
192
    return *this;
×
193
}
194

195
transaction& transaction::operator=(const transaction& other) NOEXCEPT
×
196
{
197
    version_ = other.version_;
×
198
    inputs_ = other.inputs_;
×
199
    outputs_ = other.outputs_;
×
200
    locktime_ = other.locktime_;
×
201
    segregated_ = other.segregated_;
×
202
    valid_ = other.valid_;
×
203
    size_ = other.size_;
×
204

NEW
205
    nominal_hash_.reset();
×
NEW
206
    witness_hash_.reset();
×
NEW
207
    sighash_cache_.reset();
×
208

209
    // Optimized for faster optional, not for copy.
210
    if (other.nominal_hash_)
×
211
        nominal_hash_ = to_unique(*other.nominal_hash_);
×
UNCOV
212
    if (other.witness_hash_)
×
213
        witness_hash_ = to_unique(*other.witness_hash_);
×
UNCOV
214
    if (other.sighash_cache_)
×
215
        sighash_cache_ = to_unique(*other.sighash_cache_);
×
216

217
    return *this;
×
218
}
219

220
bool transaction::operator==(const transaction& other) const NOEXCEPT
60✔
221
{
222
    // Compares input/output elements, not pointers, cache not compared.
223
    return (version_ == other.version_)
60✔
224
        && (locktime_ == other.locktime_)
58✔
225
        && ((inputs_ == other.inputs_) || 
74✔
226
            deep_equal(*inputs_, *other.inputs_))
16✔
227
        && ((outputs_ == other.outputs_) ||
134✔
228
            deep_equal(*outputs_, *other.outputs_));
16✔
229
}
230

231
bool transaction::operator!=(const transaction& other) const NOEXCEPT
2✔
232
{
233
    return !(*this == other);
2✔
234
}
235

236
// Deserialization.
237
// ----------------------------------------------------------------------------
238

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

310
// private
311
BC_PUSH_WARNING(NO_UNGUARDED_POINTERS)
312
void transaction::assign_data(reader& source, bool witness) NOEXCEPT
179✔
313
{
314
    auto& allocator = source.get_allocator();
179✔
315

316
    ////allocator.construct<inputs_cptr>(&inputs_,
317
    ////    allocator.new_object<input_cptrs>(),
318
    ////    allocator.deleter<input_cptrs>(source.get_arena()));
319
    ////
320
    ////allocator.construct<outputs_cptr>(&outputs_,
321
    ////    allocator.new_object<output_cptrs>(),
322
    ////    allocator.deleter<output_cptrs>(source.get_arena()));
323
    ////
324
    ////version_ = source.read_4_bytes_little_endian();
325

326
    auto ins = to_non_const_raw_ptr(inputs_);
179✔
327
    auto count = source.read_size(max_block_size);
179✔
328
    ins->reserve(count);
179✔
329
    for (size_t in = 0; in < count; ++in)
403✔
330
        ins->emplace_back(
448✔
331
            allocator.new_object<input>(source),
224✔
332
            allocator.deleter<input>(source.get_arena()));
448✔
333

334
    // Expensive repeated recomputation, so cache segregated state.
335
    // Detect witness as no inputs (marker) and expected flag (bip144).
336
    segregated_ = 
179✔
337
        inputs_->size() == witness_marker &&
195✔
338
        source.peek_byte() == witness_enabled;
16✔
339

340
    if (segregated_)
179✔
341
    {
342
        // Skip over the peeked witness flag.
343
        source.skip_byte();
16✔
344

345
        count = source.read_size(max_block_size);
16✔
346
        ins->reserve(count);
16✔
347
        for (size_t in = 0; in < count; ++in)
37✔
348
            ins->emplace_back(
42✔
349
                allocator.new_object<input>(source),
21✔
350
                allocator.deleter<input>(source.get_arena()));
42✔
351

352
        auto outs = to_non_const_raw_ptr(outputs_);
16✔
353
        count = source.read_size(max_block_size);
16✔
354
        outs->reserve(count);
16✔
355
        for (size_t out = 0; out < count; ++out)
41✔
356
            outs->emplace_back(
50✔
357
                allocator.new_object<output>(source),
25✔
358
                allocator.deleter<output>(source.get_arena()));
50✔
359

360
        // Read or skip witnesses as specified.
361
        if (witness)
16✔
362
        {
363
            for (auto& input: *inputs_)
35✔
364
                to_non_const_raw_ptr(input)->set_witness(source);
20✔
365
        }
366
        else
367
        {
368
            // Default witness is populated on input construct.
369
            for (size_t in = 0; in < inputs_->size(); ++in)
2✔
370
                witness::skip(source, true);
1✔
371
        }
372
    }
373
    else
374
    {
375
        auto outs = to_non_const_raw_ptr(outputs_);
163✔
376
        count = source.read_size(max_block_size);
163✔
377
        outs->reserve(count);
163✔
378
        for (size_t out = 0; out < count; ++out)
387✔
379
            outs->emplace_back(
448✔
380
                allocator.new_object<output>(source),
224✔
381
                allocator.deleter<output>(source.get_arena()));
448✔
382
    }
383

384
    locktime_ = source.read_4_bytes_little_endian();
179✔
385
    size_ = serialized_size(*inputs_, *outputs_, segregated_);
179✔
386
    valid_ = source;
179✔
387
}
179✔
388
BC_POP_WARNING()
389

390
// Serialization.
391
// ----------------------------------------------------------------------------
392

393
// Transactions with empty witnesses always use old serialization (bip144).
394
// If no inputs are witness programs then witness hash is tx hash (bip141).
395
data_chunk transaction::to_data(bool witness) const NOEXCEPT
10✔
396
{
397
    witness &= segregated_;
10✔
398

399
    data_chunk data(serialized_size(witness));
10✔
400
    stream::out::copy ostream(data);
10✔
401
    to_data(ostream, witness);
10✔
402
    return data;
20✔
403
}
10✔
404

405
void transaction::to_data(std::ostream& stream, bool witness) const NOEXCEPT
11✔
406
{
407
    witness &= segregated_;
11✔
408

409
    write::bytes::ostream out(stream);
11✔
410
    to_data(out, witness);
11✔
411
}
11✔
412

413
void transaction::to_data(writer& sink, bool witness) const NOEXCEPT
969✔
414
{
415
    witness &= segregated_;
969✔
416

417
    sink.write_4_bytes_little_endian(version_);
969✔
418

419
    if (witness)
969✔
420
    {
421
        sink.write_byte(witness_marker);
2✔
422
        sink.write_byte(witness_enabled);
2✔
423
    }
424

425
    sink.write_variable(inputs_->size());
969✔
426
    for (const auto& input: *inputs_)
2,358✔
427
        input->to_data(sink);
1,389✔
428

429
    sink.write_variable(outputs_->size());
969✔
430
    for (const auto& output: *outputs_)
2,639✔
431
        output->to_data(sink);
1,670✔
432

433
    if (witness)
969✔
434
        for (auto& input: *inputs_)
5✔
435
            input->witness().to_data(sink, true);
3✔
436

437
    sink.write_4_bytes_little_endian(locktime_);
969✔
438
}
969✔
439

440
// static/private
441
transaction::sizes transaction::serialized_size(
2,093✔
442
    const chain::input_cptrs& inputs,
443
    const chain::output_cptrs& outputs, bool segregated) NOEXCEPT
444
{
445
    sizes size{ zero, zero };
2,093✔
446

447
    // Keep the condition outside of the loop.
448
    if (segregated)
2,093✔
449
    {
450
        std::for_each(inputs.begin(), inputs.end(), [&](const auto& in) NOEXCEPT
76✔
451
        {
452
            size.nominal = ceilinged_add(size.nominal, in->nominal_size());
92✔
453
            size.witnessed = ceilinged_add(size.witnessed, in->witnessed_size());
46✔
454
        });
46✔
455
    }
456
    else
457
    {
458
        // Witness must be zeroed because witnesses have nonzero size when they
459
        // are zero-valued, so they can be archived easily. Also it would be
460
        // wasteful to to count mutiple zero sizes, so exclude them here.
461
        std::for_each(inputs.begin(), inputs.end(), [&](const auto& in) NOEXCEPT
4,147✔
462
        {
463
            size.nominal = ceilinged_add(size.nominal, in->nominal_size());
2,084✔
464
        });
2,084✔
465
    }
466

467
    const auto outs = [](size_t total, const auto& output) NOEXCEPT
589✔
468
    {
469
        return ceilinged_add(total, output->serialized_size());
589✔
470
    };
471

472
    constexpr auto base_const_size = ceilinged_add(
2,093✔
473
        sizeof(version_),
474
        sizeof(locktime_));
475

476
    constexpr auto witness_const_size = ceilinged_add(
2,093✔
477
        sizeof(witness_marker),
478
        sizeof(witness_enabled));
479

480
    const auto base_size = ceilinged_add(ceilinged_add(ceilinged_add(
2,093✔
481
        base_const_size,
482
        variable_size(inputs.size())),
483
        variable_size(outputs.size())),
484
        std::accumulate(outputs.begin(), outputs.end(), zero, outs));
485

486
    const auto nominal_size = ceilinged_add(
2,093✔
487
        base_size,
488
        size.nominal);
489

490
    const auto witnessed_size = ceilinged_add(ceilinged_add(
2,093✔
491
        base_size,
492
        witness_const_size),
493
        size.witnessed);
494

495
    return { nominal_size, witnessed_size };
2,093✔
496
}
497

498
size_t transaction::serialized_size(bool witness) const NOEXCEPT
563✔
499
{
500
    witness &= segregated_;
563✔
501

502
    return witness ? size_.witnessed : size_.nominal;
563✔
503
}
504

505
// Properties.
506
// ----------------------------------------------------------------------------
507

508
bool transaction::is_valid() const NOEXCEPT
775✔
509
{
510
    return valid_;
775✔
511
}
512

513
size_t transaction::inputs() const NOEXCEPT
1,565✔
514
{
515
    return inputs_->size();
1,565✔
516
}
517

518
size_t transaction::outputs() const NOEXCEPT
1✔
519
{
520
    return outputs_->size();
1✔
521
}
522

523
uint32_t transaction::version() const NOEXCEPT
6✔
524
{
525
    return version_;
4✔
526
}
527

528
uint32_t transaction::locktime() const NOEXCEPT
15✔
529
{
530
    return locktime_;
4✔
531
}
532

533
const inputs_cptr& transaction::inputs_ptr() const NOEXCEPT
2,440✔
534
{
535
    return inputs_;
2,440✔
536
}
537

538
const outputs_cptr& transaction::outputs_ptr() const NOEXCEPT
62✔
539
{
540
    return outputs_;
62✔
541
}
542

543
uint64_t transaction::fee() const NOEXCEPT
4✔
544
{
545
    // Underflow returns zero (and is_overspent() will be true).
546
    // This is value of prevouts spent by inputs minus that claimed by outputs.
547
    return floored_subtract(value(), claim());
4✔
548
}
549

550
void transaction::set_nominal_hash(hash_digest&& hash) const NOEXCEPT
9✔
551
{
552
    nominal_hash_ = to_unique(std::move(hash));
18✔
553
}
9✔
554

555
void transaction::set_witness_hash(hash_digest&& hash) const NOEXCEPT
2✔
556
{
557
    witness_hash_ = to_unique(std::move(hash));
4✔
558
}
2✔
559

560
const hash_digest& transaction::get_hash(bool witness) const NOEXCEPT
13✔
561
{
562
    if (witness)
13✔
563
    {
564
        if (!witness_hash_) set_witness_hash(hash(witness));
3✔
565
        return *witness_hash_;
3✔
566
    }
567
    else
568
    {
569
        if (!nominal_hash_) set_nominal_hash(hash(witness));
10✔
570
        return *nominal_hash_;
10✔
571
    }
572
}
573

574
hash_digest transaction::hash(bool witness) const NOEXCEPT
937✔
575
{
576
    if (segregated_)
937✔
577
    {
578
        if (witness)
23✔
579
        {
580
            // Witness coinbase tx hash is assumed to be null_hash (bip141).
581
            if (witness_hash_) return *witness_hash_;
×
582
            if (is_coinbase()) return null_hash;
×
583
        }
584
        else
585
        {
586
            if (nominal_hash_) return *nominal_hash_;
23✔
587
        }
588
    }
589
    else
590
    {
591
        if (nominal_hash_) return *nominal_hash_;
914✔
592
    }
593

594
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
595
    hash_digest digest;
930✔
596
    BC_POP_WARNING()
597

598
    stream::out::fast stream{ digest };
930✔
599
    hash::sha256x2::fast sink{ stream };
930✔
600
    to_data(sink, witness);
930✔
601
    sink.flush();
930✔
602
    return digest;
930✔
603
}
930✔
604

605
// Methods.
606
// ----------------------------------------------------------------------------
607

608
bool transaction::is_dusty(uint64_t minimum_output_value) const NOEXCEPT
6✔
609
{
610
    const auto dusty = [=](const auto& output) NOEXCEPT
9✔
611
    {
612
        return output->is_dust(minimum_output_value);
9✔
613
    };
6✔
614

615
    return std::any_of(outputs_->begin(), outputs_->end(), dusty);
6✔
616
}
617

618
size_t transaction::signature_operations(bool bip16, bool bip141) const NOEXCEPT
1✔
619
{
620
    // Includes BIP16 p2sh additional sigops, max_size_t if prevout invalid.
621
    const auto in = [=](size_t total, const auto& input) NOEXCEPT
×
622
    {
623
        return ceilinged_add(total, input->signature_operations(bip16, bip141));
×
624
    };
1✔
625

626
    const auto out = [=](size_t total, const auto& output) NOEXCEPT
×
627
    {
628
        return ceilinged_add(total, output->signature_operations(bip141));
×
629
    };
1✔
630

631
    // Overflow returns max_size_t.
632
    return ceilinged_add(
1✔
633
        std::accumulate(inputs_->begin(), inputs_->end(), zero, in),
634
        std::accumulate(outputs_->begin(), outputs_->end(), zero, out));
1✔
635
}
636

637
chain::points transaction::points() const NOEXCEPT
4✔
638
{
639
    chain::points out(inputs_->size());
4✔
640

641
    const auto point = [](const auto& input) NOEXCEPT
8✔
642
    {
643
        return input->point();
8✔
644
    };
645

646
    std::transform(inputs_->begin(), inputs_->end(), out.begin(), point);
4✔
647
    return out;
4✔
648
}
649

650
hash_digest transaction::outputs_hash() const NOEXCEPT
8✔
651
{
652
    if (sighash_cache_)
8✔
653
        return sighash_cache_->outputs;
×
654

655
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
656
    hash_digest digest;
8✔
657
    BC_POP_WARNING()
658
        
659
    stream::out::fast stream{ digest };
8✔
660
    hash::sha256x2::fast sink{ stream };
8✔
661

662
    const auto& outs = *outputs_;
8✔
663
    for (const auto& output: outs)
22✔
664
        output->to_data(sink);
14✔
665

666
    sink.flush();
8✔
667
    return digest;
8✔
668
}
8✔
669

670
hash_digest transaction::points_hash() const NOEXCEPT
11✔
671
{
672
    if (sighash_cache_)
11✔
673
        return sighash_cache_->points;
×
674

675
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
676
    hash_digest digest;
11✔
677
    BC_POP_WARNING()
678

679
    stream::out::fast stream{ digest };
11✔
680
    hash::sha256x2::fast sink{ stream };
11✔
681

682
    const auto& ins = *inputs_;
11✔
683
    for (const auto& input: ins)
27✔
684
        input->point().to_data(sink);
16✔
685

686
    sink.flush();
11✔
687
    return digest;
11✔
688
}
11✔
689

690
hash_digest transaction::sequences_hash() const NOEXCEPT
7✔
691
{
692
    if (sighash_cache_)
7✔
693
        return sighash_cache_->sequences;
×
694

695
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
696
    hash_digest digest;
7✔
697
    BC_POP_WARNING()
698

699
    stream::out::fast stream{ digest };
7✔
700
    hash::sha256x2::fast sink{ stream };
7✔
701

702
    const auto& ins = *inputs_;
7✔
703
    for (const auto& input: ins)
17✔
704
        sink.write_4_bytes_little_endian(input->sequence());
10✔
705

706
    sink.flush();
7✔
707
    return digest;
7✔
708
}
7✔
709

710
// Signing (unversioned).
711
// ----------------------------------------------------------------------------
712

713
// private
714
transaction::input_iterator transaction::input_at(
4✔
715
    uint32_t index) const NOEXCEPT
716
{
717
    // Guarded by check_signature and create_endorsement.
718
    BC_ASSERT_MSG(index < inputs_->size(), "invalid input index");
4✔
719

720
    return std::next(inputs_->begin(), index);
4✔
721
}
722

723
// private
724
uint32_t transaction::input_index(const input_iterator& input) const NOEXCEPT
25✔
725
{
726
    // Guarded by unversioned_signature_hash and output_hash.
727
    BC_ASSERT_MSG(inputs_->begin() != inputs_->end(), "invalid input iterator");
25✔
728

729
    return possible_narrow_and_sign_cast<uint32_t>(
25✔
730
        std::distance(inputs_->begin(), input));
×
731
}
732

733
//*****************************************************************************
734
// CONSENSUS: Due to masking of bits 6/7 (8 is the anyone_can_pay flag),
735
// there are 4 possible 7 bit values that can set "single" and 4 others that
736
// can set none, and yet all other values set "all".
737
//*****************************************************************************
738
inline coverage mask_sighash(uint8_t sighash_flags) NOEXCEPT
41✔
739
{
740
    switch (sighash_flags & coverage::mask)
41✔
741
    {
742
        case coverage::hash_single:
743
            return coverage::hash_single;
744
        case coverage::hash_none:
2✔
745
            return coverage::hash_none;
2✔
746
        default:
18✔
747
            return coverage::hash_all;
18✔
748
    }
749
}
750

751
void transaction::signature_hash_single(writer& sink,
4✔
752
    const input_iterator& input, const script& sub,
753
    uint8_t sighash_flags) const NOEXCEPT
754
{
755
    const auto write_inputs = [this, &input, &sub, sighash_flags](
8✔
756
        writer& sink) NOEXCEPT
4✔
757
    {
758
        const auto& self = **input;
4✔
759
        const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
4✔
760
        input_cptrs::const_iterator in;
4✔
761

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

764
        for (in = inputs_->begin(); !anyone && in != input; ++in)
4✔
765
        {
766
            (*in)->point().to_data(sink);
×
767
            sink.write_bytes(empty_script());
×
768
            sink.write_bytes(zero_sequence());
×
769
        }
770

771
        self.point().to_data(sink);
4✔
772
        sub.to_data(sink, prefixed);
4✔
773
        sink.write_4_bytes_little_endian(self.sequence());
4✔
774

775
        for (++in; !anyone && in != inputs_->end(); ++in)
5✔
776
        {
777
            (*in)->point().to_data(sink);
1✔
778
            sink.write_bytes(empty_script());
1✔
779
            sink.write_bytes(zero_sequence());
1✔
780
        }
781
    };
4✔
782

783
    const auto write_outputs = [this, &input](writer& sink) NOEXCEPT
12✔
784
    {
785
        const auto index = input_index(input);
4✔
786

787
        sink.write_variable(add1(index));
4✔
788

789
        for (size_t output = 0; output < index; ++output)
5✔
790
            sink.write_bytes(null_output());
1✔
791

792
        // Guarded by unversioned_signature_hash.
793
        outputs_->at(index)->to_data(sink);
4✔
794
    };
8✔
795

796
    sink.write_4_bytes_little_endian(version_);
4✔
797
    write_inputs(sink);
4✔
798
    write_outputs(sink);
4✔
799
    sink.write_4_bytes_little_endian(locktime_);
4✔
800
    sink.write_4_bytes_little_endian(sighash_flags);
4✔
801
}
4✔
802

803
void transaction::signature_hash_none(writer& sink,
×
804
    const input_iterator& input, const script& sub,
805
    uint8_t sighash_flags) const NOEXCEPT
806
{
807
    const auto write_inputs = [this, &input, &sub, sighash_flags](
×
808
        writer& sink) NOEXCEPT
×
809
    {
810
        const auto& self = **input;
×
811
        const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
×
812
        input_cptrs::const_iterator in;
×
813

814
        sink.write_variable(anyone ? one : inputs_->size());
×
815

816
        for (in = inputs_->begin(); !anyone && in != input; ++in)
×
817
        {
818
            (*in)->point().to_data(sink);
×
819
            sink.write_bytes(empty_script());
×
820
            sink.write_bytes(zero_sequence());
×
821
        }
822

823
        self.point().to_data(sink);
×
824
        sub.to_data(sink, prefixed);
×
825
        sink.write_4_bytes_little_endian(self.sequence());
×
826

827
        for (++in; !anyone && in != inputs_->end(); ++in)
×
828
        {
829
            (*in)->point().to_data(sink);
×
830
            sink.write_bytes(empty_script());
×
831
            sink.write_bytes(zero_sequence());
×
832
        }
833
    };
×
834

835
    sink.write_4_bytes_little_endian(version_);
×
836
    write_inputs(sink);
×
837
    sink.write_variable(zero);
×
838
    sink.write_4_bytes_little_endian(locktime_);
×
839
    sink.write_4_bytes_little_endian(sighash_flags);
×
840
}
×
841

842
void transaction::signature_hash_all(writer& sink,
12✔
843
    const input_iterator& input, const script& sub,
844
    uint8_t flags) const NOEXCEPT
845
{
846
    const auto write_inputs = [this, &input, &sub, flags](
24✔
847
        writer& sink) NOEXCEPT
43✔
848
    {
849
        const auto& self = **input;
12✔
850
        const auto anyone = to_bool(flags & coverage::anyone_can_pay);
12✔
851
        input_cptrs::const_iterator in;
12✔
852

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

855
        for (in = inputs_->begin(); !anyone && in != input; ++in)
15✔
856
        {
857
            (*in)->point().to_data(sink);
3✔
858
            sink.write_bytes(empty_script());
3✔
859
            sink.write_4_bytes_little_endian((*in)->sequence());
3✔
860
        }
861

862
        self.point().to_data(sink);
12✔
863
        sub.to_data(sink, prefixed);
12✔
864
        sink.write_4_bytes_little_endian(self.sequence());
12✔
865

866
        for (++in; !anyone && in != inputs_->end(); ++in)
16✔
867
        {
868
            (*in)->point().to_data(sink);
4✔
869
            sink.write_bytes(empty_script());
4✔
870
            sink.write_4_bytes_little_endian((*in)->sequence());
4✔
871
        }
872
    };
12✔
873

874
    const auto write_outputs = [this](writer& sink) NOEXCEPT
36✔
875
    {
876
        sink.write_variable(outputs_->size());
12✔
877
        for (const auto& output: *outputs_)
27✔
878
            output->to_data(sink);
15✔
879
    };
24✔
880

881
    sink.write_4_bytes_little_endian(version_);
12✔
882
    write_inputs(sink);
12✔
883
    write_outputs(sink);
12✔
884
    sink.write_4_bytes_little_endian(locktime_);
12✔
885
    sink.write_4_bytes_little_endian(flags);
12✔
886
}
12✔
887

888
// private
889
hash_digest transaction::unversioned_signature_hash(
19✔
890
    const input_iterator& input, const script& sub,
891
    uint8_t sighash_flags) const NOEXCEPT
892
{
893
    // Set options.
894
    const auto flag = mask_sighash(sighash_flags);
19✔
895

896
    // Create hash writer.
897
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
898
    hash_digest digest;
19✔
899
    BC_POP_WARNING()
900

901
    stream::out::fast stream{ digest };
19✔
902
    hash::sha256x2::fast sink{ stream };
19✔
903

904
    switch (flag)
19✔
905
    {
906
        case coverage::hash_single:
7✔
907
        {
7✔
908
            //*****************************************************************
909
            // CONSENSUS: return one_hash if index exceeds outputs in sighash.
910
            // Related Bug: bitcointalk.org/index.php?topic=260595
911
            // Exploit: joncave.co.uk/2014/08/bitcoin-sighash-single/
912
            //*****************************************************************
913
            if (input_index(input) >= outputs_->size())
7✔
914
                return one_hash;
3✔
915

916
            signature_hash_single(sink, input, sub, sighash_flags);
4✔
917
            break;
4✔
918
        }
919
        case coverage::hash_none:
×
920
        {
×
921
            signature_hash_none(sink, input, sub, sighash_flags);
×
922
            break;
×
923
        }
924
        default:
12✔
925
        case coverage::hash_all:
12✔
926
        {
12✔
927
            signature_hash_all(sink, input, sub, sighash_flags);
12✔
928
        }
929
    }
930

931
    sink.flush();
16✔
932
    return digest;
16✔
933
}
19✔
934

935
// Signing (version 0).
936
// ----------------------------------------------------------------------------
937

938
// private
939
// TODO: taproot requires both single and double hash of each.
940
void transaction::initialize_sighash_cache() const NOEXCEPT
2✔
941
{
942
    // This overconstructs the cache (anyone or !all), however it is simple.
943
    if (!segregated_)
2✔
944
        return;
945

946
    sighash_cache_ = to_unique<sighash_cache>
2✔
947
    (
4✔
948
        outputs_hash(),
2✔
949
        points_hash(),
2✔
950
        sequences_hash()
4✔
951
    );
952
}
953

954
// private
955
hash_digest transaction::output_hash(const input_iterator& input) const NOEXCEPT
14✔
956
{
957
    const auto index = input_index(input);
14✔
958

959
    //*************************************************************************
960
    // CONSENSUS: if index exceeds outputs in signature hash, return null_hash.
961
    //*************************************************************************
962
    if (index >= outputs_->size())
14✔
963
        return null_hash;
2✔
964

965
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
966
    hash_digest digest;
12✔
967
    BC_POP_WARNING()
968

969
    stream::out::fast stream{ digest };
12✔
970
    hash::sha256x2::fast sink{ stream };
12✔
971
    outputs_->at(index)->to_data(sink);
12✔
972
    sink.flush();
12✔
973
    return digest;
12✔
974
}
12✔
975

976
// private
977
hash_digest transaction::version_0_signature_hash(const input_iterator& input,
29✔
978
    const script& sub, uint64_t value, uint8_t sighash_flags,
979
    bool bip143) const NOEXCEPT
980
{
981
    // bip143/v0: the way of serialization is changed.
982
    if (!bip143)
29✔
983
        return unversioned_signature_hash(input, sub, sighash_flags);
7✔
984

985
    // Set options.
986
    const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
22✔
987
    const auto flag = mask_sighash(sighash_flags);
22✔
988
    const auto all = (flag == coverage::hash_all);
22✔
989
    const auto single = (flag == coverage::hash_single);
22✔
990
    const auto& self = **input;
22✔
991

992
    // Create hash writer.
993
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
994
    hash_digest digest;
22✔
995
    BC_POP_WARNING()
996

997
    stream::out::fast stream{ digest };
22✔
998
    hash::sha256x2::fast sink{ stream };
22✔
999

1000
    // Create signature hash.
1001
    sink.write_little_endian(version_);
22✔
1002

1003
    // Conditioning points, sequences, and outputs writes on cache_ instead of
1004
    // conditionally passing them from methods avoids copying the cached hash.
1005

1006
    // points
1007
    sink.write_bytes(!anyone ? points_hash() : null_hash);
22✔
1008

1009
    // sequences
1010
    sink.write_bytes(!anyone && all ? sequences_hash() : null_hash);
22✔
1011

1012
    self.point().to_data(sink);
22✔
1013
    sub.to_data(sink, prefixed);
22✔
1014
    sink.write_little_endian(value);
22✔
1015
    sink.write_little_endian(self.sequence());
22✔
1016

1017
    // outputs
1018
    if (single)
22✔
1019
        sink.write_bytes(output_hash(input));
14✔
1020
    else
1021
        sink.write_bytes(all ? outputs_hash() : null_hash);
8✔
1022

1023
    sink.write_little_endian(locktime_);
22✔
1024
    sink.write_4_bytes_little_endian(sighash_flags);
22✔
1025

1026
    sink.flush();
22✔
1027
    return digest;
22✔
1028
}
22✔
1029

1030
// Signing (unversioned and version 0).
1031
// ----------------------------------------------------------------------------
1032

1033
// ****************************************************************************
1034
// CONSENSUS: sighash flags are carried in a single byte but are encoded as 4
1035
// bytes in the signature hash preimage serialization.
1036
// ****************************************************************************
1037

1038
hash_digest transaction::signature_hash(const input_iterator& input,
41✔
1039
    const script& sub, uint64_t value, uint8_t sighash_flags,
1040
    script_version version, bool bip143) const NOEXCEPT
1041
{
1042
    // There is no rational interpretation of a signature hash for a coinbase.
1043
    BC_ASSERT(!is_coinbase());
41✔
1044

1045
    switch (version)
41✔
1046
    {
1047
        case script_version::unversioned:
12✔
1048
            return unversioned_signature_hash(input, sub, sighash_flags);
12✔
1049
        case script_version::zero:
29✔
1050
            return version_0_signature_hash(input, sub, value, sighash_flags,
29✔
1051
                bip143);
29✔
1052
        case script_version::reserved:
×
1053
        default:
×
1054
            return {};
×
1055
    }
1056
}
1057

1058
// This is not used internal to the library.
1059
bool transaction::check_signature(const ec_signature& signature,
2✔
1060
    const data_slice& public_key, const script& sub, uint32_t index,
1061
    uint64_t value, uint8_t sighash_flags, script_version version,
1062
    bool bip143) const NOEXCEPT
1063
{
1064
    if ((index >= inputs_->size()) || signature.empty() || public_key.empty())
2✔
1065
        return false;
1066

1067
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
1068
        sighash_flags, version, bip143);
1069

1070
    // Validate the EC signature.
1071
    return verify_signature(public_key, sighash, signature);
2✔
1072
}
1073

1074
// This is not used internal to the library.
1075
bool transaction::create_endorsement(endorsement& out, const ec_secret& secret,
2✔
1076
    const script& sub, uint32_t index, uint64_t value, uint8_t sighash_flags,
1077
    script_version version, bool bip143) const NOEXCEPT
1078
{
1079
    if (index >= inputs_->size())
2✔
1080
        return false;
1081

1082
    out.reserve(max_endorsement_size);
2✔
1083
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
1084
        sighash_flags, version, bip143);
1085

1086
    // Create the EC signature and encode as DER.
1087
    ec_signature signature;
2✔
1088
    if (!sign(signature, secret, sighash) || !encode_signature(out, signature))
2✔
1089
        return false;
×
1090

1091
    // Add the sighash type to the end of the DER signature -> endorsement.
1092
    out.push_back(sighash_flags);
2✔
1093
    ////out.shrink_to_fit();
1094
    return true;
2✔
1095
}
1096

1097
// Guard (context free).
1098
// ----------------------------------------------------------------------------
1099

1100
bool transaction::is_coinbase() const NOEXCEPT
80✔
1101
{
1102
    return is_one(inputs_->size()) && inputs_->front()->point().is_null();
80✔
1103
}
1104

1105
bool transaction::is_internal_double_spend() const NOEXCEPT
4✔
1106
{
1107
    // TODO: optimize (see block.is_internal_double_spend).
1108
    return !is_distinct(points());
4✔
1109
}
1110

1111
// TODO: a pool (non-coinbase) tx must fit into a block (with a coinbase).
1112
bool transaction::is_oversized() const NOEXCEPT
×
1113
{
1114
    return serialized_size(false) > max_block_size;
×
1115
}
1116

1117
// Guard (contextual).
1118
// ----------------------------------------------------------------------------
1119

1120
// static/private
1121
bool transaction::segregated(const chain::inputs& inputs) NOEXCEPT
1✔
1122
{
1123
    const auto witnessed = [](const auto& input) NOEXCEPT
2✔
1124
    {
1125
        return !input.witness().stack().empty();
1✔
1126
    };
1127

1128
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
1✔
1129
}
1130

1131
// static/private
1132
bool transaction::segregated(const chain::input_cptrs& inputs) NOEXCEPT
903✔
1133
{
1134
    const auto witnessed = [](const auto& input) NOEXCEPT
906✔
1135
    {
1136
        return !input->witness().stack().empty();
906✔
1137
    };
1138

1139
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
903✔
1140
}
1141

1142
bool transaction::is_segregated() const NOEXCEPT
4✔
1143
{
1144
    return segregated_;
4✔
1145
}
1146

1147
size_t transaction::weight() const NOEXCEPT
×
1148
{
1149
    // Block weight is 3 * base size * + 1 * total size (bip141).
1150
    return ceilinged_add(
×
1151
        ceilinged_multiply(base_size_contribution, serialized_size(false)),
1152
        ceilinged_multiply(total_size_contribution, serialized_size(true)));
×
1153
}
1154

1155
bool transaction::is_overweight() const NOEXCEPT
×
1156
{
1157
    return weight() > max_block_weight;
×
1158
}
1159

1160
//*****************************************************************************
1161
// CONSENSUS: Legacy sigops are counted in coinbase scripts despite the fact
1162
// that coinbase input scripts are never executed. There is no need to exclude
1163
// p2sh coinbase sigops since there is never a script to count.
1164
//*****************************************************************************
1165
bool transaction::is_signature_operations_limit(bool bip16,
×
1166
    bool bip141) const NOEXCEPT
1167
{
1168
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
1169
    return signature_operations(bip16, bip141) > limit;
×
1170
}
1171

1172
// Check (context free).
1173
// ----------------------------------------------------------------------------
1174

1175
bool transaction::is_empty() const NOEXCEPT
9✔
1176
{
1177
    return inputs_->empty() || outputs_->empty();
9✔
1178
}
1179

1180
bool transaction::is_null_non_coinbase() const NOEXCEPT
7✔
1181
{
1182
    BC_ASSERT(!is_coinbase());
7✔
1183

1184
    const auto invalid = [](const auto& input) NOEXCEPT
9✔
1185
    {
1186
        return input->point().is_null();
9✔
1187
    };
1188

1189
    // True if not coinbase but has null previous_output(s).
1190
    return std::any_of(inputs_->begin(), inputs_->end(), invalid);
7✔
1191
}
1192

1193
bool transaction::is_invalid_coinbase_size() const NOEXCEPT
9✔
1194
{
1195
    BC_ASSERT(is_coinbase());
9✔
1196

1197
    // True if coinbase and has invalid input[0] script size.
1198
    const auto script_size = inputs_->front()->script().serialized_size(false);
9✔
1199
    return script_size < min_coinbase_size || script_size > max_coinbase_size;
9✔
1200
}
1201

1202
// Accept (contextual).
1203
// ----------------------------------------------------------------------------
1204

1205
bool transaction::is_non_final(size_t height, uint32_t timestamp,
5✔
1206
    uint32_t median_time_past, bool bip113) const NOEXCEPT
1207
{
1208
    // BIP113: comparing the locktime against the median of the past 11 block
1209
    // timestamps, rather than the timestamp of the block including the tx.
1210
    const auto time = bip113 ? median_time_past : timestamp;
5✔
1211

1212
    const auto finalized = [](const auto& input) NOEXCEPT
2✔
1213
    {
1214
        return input->is_final();
2✔
1215
    };
1216

1217
    const auto height_time = locktime_ < locktime_threshold ? height : time;
5✔
1218

1219
    return !(is_zero(locktime_) || locktime_ < height_time ||
8✔
1220
        std::all_of(inputs_->begin(), inputs_->end(), finalized));
3✔
1221
}
1222

1223
bool transaction::is_missing_prevouts() const NOEXCEPT
3✔
1224
{
1225
    BC_ASSERT(!is_coinbase());
3✔
1226

1227
    // Null or invalid prevout indicates not found.
1228
    const auto missing = [](const auto& input) NOEXCEPT
2✔
1229
    {
1230
        return !input->prevout;
1231
    };
1232

1233
    return std::any_of(inputs_->begin(), inputs_->end(), missing);
3✔
1234
}
1235

1236
uint64_t transaction::claim() const NOEXCEPT
8✔
1237
{
1238
    // Overflow returns max_uint64.
1239
    const auto sum = [](uint64_t total, const auto& output) NOEXCEPT
8✔
1240
    {
1241
        return ceilinged_add(total, output->value());
8✔
1242
    };
1243

1244
    // The amount claimed by outputs.
1245
    return std::accumulate(outputs_->begin(), outputs_->end(), 0_u64, sum);
8✔
1246
}
1247

1248
uint64_t transaction::value() const NOEXCEPT
9✔
1249
{
1250
    // Overflow, not populated, and coinbase (default) return max_uint64.
1251
    const auto sum = [](uint64_t total, const auto& input) NOEXCEPT
7✔
1252
    {
1253
        const auto value = input->prevout ? input->prevout->value() : max_uint64;
7✔
1254
        return ceilinged_add(total, value);
7✔
1255
    };
1256

1257
    // The amount of prevouts (referenced by inputs).
1258
    return std::accumulate(inputs_->begin(), inputs_->end(), 0_u64, sum);
9✔
1259
}
1260

1261
bool transaction::is_overspent() const NOEXCEPT
2✔
1262
{
1263
    BC_ASSERT(!is_coinbase());
2✔
1264

1265
    return claim() > value();
2✔
1266
}
1267

1268
constexpr bool is_non_coinbase_mature(size_t tx_height, size_t height) NOEXCEPT
2✔
1269
{
1270
    return tx_height <= height;
2✔
1271
}
1272

1273
//*****************************************************************************
1274
// CONSENSUS: Coinbase output matures at 100 blocks depth.
1275
// CONSENSUS: Genesis coinbase is forever immature (exception).
1276
//*****************************************************************************
1277
bool transaction::is_coinbase_mature(size_t coinbase_height,
3✔
1278
    size_t height) NOEXCEPT
1279
{
1280
    return !is_zero(coinbase_height) &&
5✔
1281
        ceilinged_add(coinbase_height, coinbase_maturity) <= height;
3✔
1282
}
1283

1284
bool transaction::is_immature(size_t height) const NOEXCEPT
6✔
1285
{
1286
    BC_ASSERT(!is_coinbase());
6✔
1287

1288
    // Spends internal to a block are handled by block validation.
1289
    const auto mature = [=](const auto& input) NOEXCEPT
5✔
1290
    {
1291
        return input->metadata.coinbase ?
5✔
1292
            is_coinbase_mature(input->metadata.height, height) :
3✔
1293
            is_non_coinbase_mature(input->metadata.height, height);
2✔
1294
    };
6✔
1295

1296
    return !std::all_of(inputs_->begin(), inputs_->end(), mature);
6✔
1297
}
1298

1299
bool transaction::is_locked(size_t height,
4✔
1300
    uint32_t median_time_past) const NOEXCEPT
1301
{
1302
    // BIP68: not applied to the sequence of the input of a coinbase.
1303
    BC_ASSERT(!is_coinbase());
4✔
1304

1305
    // BIP68: applied to txs with a version greater than or equal to two.
1306
    if (version_ < relative_locktime_min_version)
4✔
1307
        return false;
1308

1309
    // BIP68: references to median time past are as defined by bip113.
1310
    const auto locked = [=](const auto& input) NOEXCEPT
2✔
1311
    {
1312
        return input->is_locked(height, median_time_past);
2✔
1313
    };
2✔
1314

1315
    // BIP68: when the relative lock time is block based, it is interpreted as
1316
    // a minimum block height constraint over the age of the input.
1317
    return std::any_of(inputs_->begin(), inputs_->end(), locked);
2✔
1318
}
1319

1320
// Spends internal to a block are handled by block validation.
1321
bool transaction::is_unconfirmed_spend(size_t height) const NOEXCEPT
×
1322
{
1323
    BC_ASSERT(!is_coinbase());
×
1324

1325
    // Zero is either genesis or not found.
1326
    // Test maturity first to obtain proper error code.
1327
    // Spends internal to a block are handled by block validation.
1328
    const auto unconfirmed = [=](const auto& input) NOEXCEPT
×
1329
    {
1330
        const auto prevout_height = input->metadata.height;
×
1331
        return is_zero(prevout_height) && !(height > prevout_height);
×
1332
    };
×
1333

1334
    return std::any_of(inputs_->begin(), inputs_->end(), unconfirmed);
×
1335
}
1336

1337
bool transaction::is_confirmed_double_spend(size_t height) const NOEXCEPT
4✔
1338
{
1339
    BC_ASSERT(!is_coinbase());
4✔
1340

1341
    // Spends internal to a block are handled by block validation.
1342
    const auto spent = [=](const auto& input) NOEXCEPT
4✔
1343
    {
1344
        return input->metadata.spent && height > input->metadata.height;
4✔
1345
    };
4✔
1346

1347
    return std::any_of(inputs_->begin(), inputs_->end(), spent);
4✔
1348
}
1349

1350
// Guards (for tx pool without compact blocks).
1351
// ----------------------------------------------------------------------------
1352

1353
// Pools do not have coinbases.
1354
// Redundant with block is_internal_double_spend check.
1355
// Redundant with block max_block_size check.
1356
code transaction::guard_check() const NOEXCEPT
×
1357
{
1358
    if (is_coinbase())
×
1359
        return error::coinbase_transaction;
×
1360
    if (is_internal_double_spend())
×
1361
        return error::transaction_internal_double_spend;
×
1362
    if (is_oversized())
×
1363
        return error::transaction_size_limit;
×
1364

1365
    return error::transaction_success;
×
1366
}
1367

1368
// Redundant with block max_block_weight accept.
1369
code transaction::guard_check(const context& ctx) const NOEXCEPT
×
1370
{
1371
    const auto bip141 = ctx.is_enabled(flags::bip141_rule);
×
1372

1373
     if (!bip141 && is_segregated())
×
1374
        return error::unexpected_witness_transaction;
×
1375
    if (bip141 && is_overweight())
×
1376
        return error::transaction_weight_limit;
×
1377

1378
    return error::transaction_success;
×
1379
}
1380

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

1387
    if (is_missing_prevouts())
×
1388
        return error::missing_previous_output;
×
1389
    if (is_signature_operations_limit(bip16, bip141))
×
1390
        return error::transaction_sigop_limit;
×
1391

1392
    return error::transaction_success;
×
1393
}
1394

1395
// Validation.
1396
// ----------------------------------------------------------------------------
1397

1398
// DO invoke on coinbase.
1399
code transaction::check() const NOEXCEPT
5✔
1400
{
1401
    const auto coinbase = is_coinbase();
5✔
1402

1403
    if (is_empty())
5✔
1404
        return error::empty_transaction;
×
1405
    if (coinbase && is_invalid_coinbase_size())
5✔
1406
        return error::invalid_coinbase_script_size;
×
1407
    if (!coinbase && is_null_non_coinbase())
5✔
1408
        return error::previous_output_null;
×
1409

1410
    return error::transaction_success;
5✔
1411
}
1412

1413
// forks
1414
// height
1415
// timestamp
1416
// median_time_past
1417

1418
// DO invoke on coinbase.
1419
code transaction::check(const context& ctx) const NOEXCEPT
×
1420
{
1421
    const auto bip113 = ctx.is_enabled(bip113_rule);
×
1422

1423
    if (is_non_final(ctx.height, ctx.timestamp, ctx.median_time_past, bip113))
×
1424
        return error::transaction_non_final;
×
1425

1426
    return error::transaction_success;
×
1427
}
1428

1429
// Do not need to invoke on coinbase.
1430
// This assumes that prevout caching is completed on all inputs.
1431
code transaction::accept(const context&) const NOEXCEPT
×
1432
{
1433
    ////BC_ASSERT(!is_coinbase());
1434

1435
    if (is_coinbase())
×
1436
        return error::transaction_success;
×
1437
    if (is_missing_prevouts())
×
1438
        return error::missing_previous_output;
×
1439
    if (is_overspent())
×
1440
        return error::spend_exceeds_value;
×
1441

1442
    return error::transaction_success;
×
1443
}
1444

1445
// forks
1446
// height
1447
// median_time_past
1448

1449
// Do not need to invoke on coinbase.
1450
// Node performs these checks through database query.
1451
// This assumes that prevout and metadata caching are completed on all inputs.
1452
code transaction::confirm(const context& ctx) const NOEXCEPT
×
1453
{
1454
    ////BC_ASSERT(!is_coinbase());
1455
    const auto bip68 = ctx.is_enabled(bip68_rule);
×
1456

1457
    if (is_coinbase())
×
1458
        return error::transaction_success;
×
1459
    if (bip68 && is_locked(ctx.height, ctx.median_time_past))
×
1460
        return error::relative_time_locked;
×
1461
    if (is_immature(ctx.height))
×
1462
        return error::coinbase_maturity;
×
1463
    if (is_unconfirmed_spend(ctx.height))
×
1464
        return error::unconfirmed_spend;
×
1465
    if (is_confirmed_double_spend(ctx.height))
×
1466
        return error::confirmed_double_spend;
×
1467

1468
    return error::transaction_success;
×
1469
}
1470

1471
// Connect (contextual).
1472
// ----------------------------------------------------------------------------
1473

1474
// forks
1475

1476
// Do not need to invoke on coinbase.
1477
code transaction::connect(const context& ctx) const NOEXCEPT
2✔
1478
{
1479
    ////BC_ASSERT(!is_coinbase());
1480

1481
    if (is_coinbase())
2✔
1482
        return error::transaction_success;
×
1483

1484
    code ec{};
2✔
1485
    using namespace machine;
2✔
1486
    initialize_sighash_cache();
2✔
1487

1488
    // Validate scripts.
1489
    for (auto input = inputs_->begin(); input != inputs_->end(); ++input)
6✔
1490
    {
1491
        // Evaluate rolling scripts with linear search but constant erase.
1492
        // Evaluate non-rolling scripts with constant search but linear erase.
1493
        if ((ec = (*input)->is_roller() ?
8✔
1494
            interpreter<linked_stack>::connect(ctx, *this, input) :
×
1495
            interpreter<contiguous_stack>::connect(ctx, *this, input)))
4✔
1496
            return ec;
×
1497
    }
1498

1499
    // TODO: accumulate sigops from each connect result and add coinbase.
1500
    // TODO: return in override with out parameter. more impactful with segwit.
1501
    return error::transaction_success;
2✔
1502
}
1503

1504
BC_POP_WARNING()
1505

1506
// JSON value convertors.
1507
// ----------------------------------------------------------------------------
1508

1509
namespace json = boost::json;
1510

1511
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
1512
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
1513

1514
transaction tag_invoke(json::value_to_tag<transaction>,
2✔
1515
    const json::value& value) NOEXCEPT
1516
{
1517
    return
2✔
1518
    {
1519
        value.at("version").to_number<uint32_t>(),
2✔
1520
        json::value_to<chain::inputs>(value.at("inputs")),
2✔
1521
        json::value_to<chain::outputs>(value.at("outputs")),
4✔
1522
        value.at("locktime").to_number<uint32_t>()
4✔
1523
    };
4✔
1524
}
1525

1526
void tag_invoke(json::value_from_tag, json::value& value,
4✔
1527
    const transaction& tx) NOEXCEPT
1528
{
1529
    value =
4✔
1530
    {
1531
        { "version", tx.version() },
1532
        { "inputs", *tx.inputs_ptr() },
1533
        { "outputs", *tx.outputs_ptr() },
1534
        { "locktime", tx.locktime() }
1535
    };
4✔
1536
}
4✔
1537

1538
BC_POP_WARNING()
1539

1540
transaction::cptr tag_invoke(json::value_to_tag<transaction::cptr>,
×
1541
    const json::value& value) NOEXCEPT
1542
{
1543
    return to_shared(tag_invoke(json::value_to_tag<transaction>{}, value));
×
1544
}
1545

1546
// Shared pointer overload is required for navigation.
1547
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
1548
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
1549

1550
void tag_invoke(json::value_from_tag tag, json::value& value,
2✔
1551
    const transaction::cptr& tx) NOEXCEPT
1552
{
1553
    tag_invoke(tag, value, *tx);
2✔
1554
}
2✔
1555

1556
BC_POP_WARNING()
1557
BC_POP_WARNING()
1558

1559
} // namespace chain
1560
} // namespace system
1561
} // 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