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

libbitcoin / libbitcoin-system / 9260923845

27 May 2024 10:40PM UTC coverage: 82.837% (-0.02%) from 82.858%
9260923845

push

github

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

Replace !is_coinbase() assertions with runtime bypass.

1 of 6 new or added lines in 1 file covered. (16.67%)

1 existing line in 1 file now uncovered.

9759 of 11781 relevant lines covered (82.84%)

4841970.55 hits per line

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

75.72
/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
// Precompute fixed elements of signature hashing.
47
// ----------------------------------------------------------------------------
48

49
constexpr auto prefixed = true;
50

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

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

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

69
// Constructors.
70
// ----------------------------------------------------------------------------
71

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

80
transaction::~transaction() NOEXCEPT
2,186✔
81
{
82
}
2,186✔
83

84
transaction::transaction(transaction&& other) NOEXCEPT
29✔
85
  : transaction(other)
29✔
86
{
87
}
29✔
88

89
// Cache not copied or moved.
90
transaction::transaction(const transaction& other) NOEXCEPT
1,069✔
91
  : transaction(
92
      other.version_,
1,069✔
93
      other.inputs_,
1,069✔
94
      other.outputs_,
1,069✔
95
      other.locktime_,
1,069✔
96
      other.segregated_,
1,069✔
97
      other.valid_)
1,069✔
98
{
99
}
1,069✔
100

101
transaction::transaction(uint32_t version, chain::inputs&& inputs,
813✔
102
    chain::outputs&& outputs, uint32_t locktime) NOEXCEPT
813✔
103
  : transaction(version, to_shareds(std::move(inputs)),
1,626✔
104
      to_shareds(std::move(outputs)), locktime, false, true)
2,439✔
105
{
106
    // Defer execution for constructor move.
107
    segregated_ = segregated(*inputs_);
813✔
108
}
813✔
109

110
transaction::transaction(uint32_t version, const chain::inputs& inputs,
1✔
111
    const chain::outputs& outputs, uint32_t locktime) NOEXCEPT
1✔
112
  : transaction(version, to_shareds(inputs), to_shareds(outputs), locktime,
2✔
113
      segregated(inputs), true)
4✔
114
{
115
}
1✔
116

117
transaction::transaction(uint32_t version, const chain::inputs_cptr& inputs,
×
118
    const chain::outputs_cptr& outputs, uint32_t locktime) NOEXCEPT
×
119
  : transaction(version, inputs, outputs, locktime, segregated(*inputs), true)
×
120
{
121
}
×
122

123
transaction::transaction(const data_slice& data, bool witness) NOEXCEPT
40✔
124
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
125
  : transaction(stream::in::copy(data), witness)
40✔
126
    BC_POP_WARNING()
127
{
128
}
40✔
129

130
////transaction::transaction(stream::in::fast&& stream, bool witness) NOEXCEPT
131
////  : transaction(read::bytes::fast(stream), witness)
132
////{
133
////}
134

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

140
transaction::transaction(std::istream&& stream, bool witness) NOEXCEPT
40✔
141
  : transaction(read::bytes::istream(stream), witness)
40✔
142
{
143
}
40✔
144

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

150
transaction::transaction(reader&& source, bool witness) NOEXCEPT
46✔
151
  : transaction(from_data(source, witness))
46✔
152
{
153
}
46✔
154

155
transaction::transaction(reader& source, bool witness) NOEXCEPT
119✔
156
  : transaction(from_data(source, witness))
119✔
157
{
158
}
119✔
159

160
// protected
161
transaction::transaction(uint32_t version,
2,069✔
162
    const chain::inputs_cptr& inputs, const chain::outputs_cptr& outputs,
163
    uint32_t locktime, bool segregated, bool valid) NOEXCEPT
2,069✔
164
  : version_(version),
2,069✔
165
    inputs_(inputs ? inputs : to_shared<input_cptrs>()),
4,138✔
166
    outputs_(outputs ? outputs : to_shared<output_cptrs>()),
2,069✔
167
    locktime_(locktime),
2,069✔
168
    segregated_(segregated),
2,069✔
169
    valid_(valid)
2,069✔
170
{
171
}
2,069✔
172

173
// Operators.
174
// ----------------------------------------------------------------------------
175

176
transaction& transaction::operator=(transaction&& other) NOEXCEPT
×
177
{
178
    *this = other;
×
179
    return *this;
×
180
}
181

182
transaction& transaction::operator=(const transaction& other) NOEXCEPT
×
183
{
184
    // Cache not assigned.
185
    version_ = other.version_;
×
186
    inputs_ = other.inputs_;
×
187
    outputs_ = other.outputs_;
×
188
    locktime_ = other.locktime_;
×
189
    segregated_ = other.segregated_;
×
190
    valid_ = other.valid_;
×
191
    return *this;
×
192
}
193

194
bool transaction::operator==(const transaction& other) const NOEXCEPT
58✔
195
{
196
    // Compares input/output elements, not pointers, cache not compared.
197
    return (version_ == other.version_)
58✔
198
        && (locktime_ == other.locktime_)
56✔
199
        && ((inputs_ == other.inputs_) || 
70✔
200
            deep_equal(*inputs_, *other.inputs_))
14✔
201
        && ((outputs_ == other.outputs_) ||
128✔
202
            deep_equal(*outputs_, *other.outputs_));
14✔
203
}
204

205
bool transaction::operator!=(const transaction& other) const NOEXCEPT
2✔
206
{
207
    return !(*this == other);
2✔
208
}
209

210
// Deserialization.
211
// ----------------------------------------------------------------------------
212

213
template<class Put, class Source>
214
std::shared_ptr<const std::vector<std::shared_ptr<const Put>>>
215
read_puts(Source& source) NOEXCEPT
342✔
216
{
217
    auto puts = to_shared<std::vector<std::shared_ptr<const Put>>>();
218

219
    // Subsequent emplace is non-allocating, but still THROWS.
220
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
221
    puts->reserve(source.read_size(max_block_size));
342✔
222
    BC_POP_WARNING()
223

224
    for (auto put = zero; put < puts->capacity(); ++put)
805✔
225
    {
226
        BC_PUSH_WARNING(NO_NEW_OR_DELETE)
227
        BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
228
        puts->emplace_back(new Put{ source });
463✔
229
        BC_POP_WARNING()
230
        BC_POP_WARNING()
231
    }
232

233
    // This is a pointer copy (non-const to const).
234
    return puts;
342✔
235
}
236

237
// static/private
238
transaction transaction::from_data(reader& source, bool witness) NOEXCEPT
165✔
239
{
240
    const auto version = source.read_4_bytes_little_endian();
165✔
241

242
    // Inputs must be non-const so that they may assign the witness.
243
    auto inputs = read_puts<input>(source);
165✔
244
    chain::outputs_cptr outputs;
165✔
245

246
    // Expensive repeated recomputation, so cache segregated state.
247
    const auto segregated =
165✔
248
        inputs->size() == witness_marker &&
177✔
249
        source.peek_byte() == witness_enabled;
12✔
250

251
    // Detect witness as no inputs (marker) and expected flag (bip144).
252
    if (segregated)
165✔
253
    {
254
        // Skip over the peeked witness flag.
255
        source.skip_byte();
12✔
256

257
        // Inputs and outputs are constructed on a vector of const pointers.
258
        inputs = read_puts<input>(source);
12✔
259
        outputs = read_puts<output>(source);
12✔
260

261
        // Read or skip witnesses as specified.
262
        for (auto& input: *inputs)
28✔
263
        {
264
            if (witness)
16✔
265
            {
266
                // Safe to cast as this method exclusively owns the input and
267
                // input::witness_ a mutable public property of the instance.
268
                const auto setter = const_cast<chain::input*>(input.get());
16✔
269
                setter->witness_ = to_shared<chain::witness>(source, true);
32✔
270
            }
271
            else
272
            {
273
                witness::skip(source, true);
×
274
            }
275
        }
276
    }
277
    else
278
    {
279
        // Default witness is populated on input construct.
280
        outputs = read_puts<const output>(source);
306✔
281
    }
282

283
    const auto locktime = source.read_4_bytes_little_endian();
165✔
284
    return { version, inputs, outputs, locktime, segregated, source };
165✔
285
}
286

287
// Serialization.
288
// ----------------------------------------------------------------------------
289

290
// Transactions with empty witnesses always use old serialization (bip144).
291
// If no inputs are witness programs then witness hash is tx hash (bip141).
292
data_chunk transaction::to_data(bool witness) const NOEXCEPT
10✔
293
{
294
    witness &= segregated_;
10✔
295

296
    data_chunk data(serialized_size(witness));
10✔
297

298
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
299
    stream::out::copy ostream(data);
10✔
300
    BC_POP_WARNING()
301

302
    to_data(ostream, witness);
10✔
303
    return data;
20✔
304
}
10✔
305

306
void transaction::to_data(std::ostream& stream, bool witness) const NOEXCEPT
11✔
307
{
308
    witness &= segregated_;
11✔
309

310
    write::bytes::ostream out(stream);
11✔
311
    to_data(out, witness);
11✔
312
}
11✔
313

314
void transaction::to_data(writer& sink, bool witness) const NOEXCEPT
963✔
315
{
316
    witness &= segregated_;
963✔
317

318
    sink.write_4_bytes_little_endian(version_);
963✔
319

320
    if (witness)
963✔
321
    {
322
        sink.write_byte(witness_marker);
×
323
        sink.write_byte(witness_enabled);
×
324
    }
325

326
    sink.write_variable(inputs_->size());
963✔
327
    for (const auto& input: *inputs_)
2,341✔
328
        input->to_data(sink);
1,378✔
329

330
    sink.write_variable(outputs_->size());
963✔
331
    for (const auto& output: *outputs_)
2,619✔
332
        output->to_data(sink);
1,656✔
333

334
    if (witness)
963✔
335
        for (auto& input: *inputs_)
×
336
            input->witness().to_data(sink, true);
×
337

338
    sink.write_4_bytes_little_endian(locktime_);
963✔
339
}
963✔
340

341
// TODO: this is expensive.
342
size_t transaction::serialized_size(bool witness) const NOEXCEPT
64✔
343
{
344
    witness &= segregated_;
64✔
345

346
    const auto ins = [=](size_t total, const auto& input) NOEXCEPT
80✔
347
    {
348
        // Inputs account for witness bytes. 
349
        return total + input->serialized_size(witness);
80✔
350
    };
64✔
351

352
    const auto outs = [](size_t total, const auto& output) NOEXCEPT
82✔
353
    {
354
        return total + output->serialized_size();
82✔
355
    };
356

357
    return sizeof(version_)
64✔
358
        + (witness ? sizeof(witness_marker) + sizeof(witness_enabled) : zero)
64✔
359
        + variable_size(inputs_->size())
64✔
360
        + std::accumulate(inputs_->begin(), inputs_->end(), zero, ins)
64✔
361
        + variable_size(outputs_->size())
64✔
362
        + std::accumulate(outputs_->begin(), outputs_->end(), zero, outs)
64✔
363
        + sizeof(locktime_);
64✔
364
}
365

366
// Properties.
367
// ----------------------------------------------------------------------------
368

369
bool transaction::is_valid() const NOEXCEPT
775✔
370
{
371
    return valid_;
775✔
372
}
373

374
size_t transaction::inputs() const NOEXCEPT
1,563✔
375
{
376
    return inputs_->size();
1,563✔
377
}
378

379
size_t transaction::outputs() const NOEXCEPT
1✔
380
{
381
    return outputs_->size();
1✔
382
}
383

384
uint32_t transaction::version() const NOEXCEPT
6✔
385
{
386
    return version_;
4✔
387
}
388

389
uint32_t transaction::locktime() const NOEXCEPT
15✔
390
{
391
    return locktime_;
4✔
392
}
393

394
const inputs_cptr& transaction::inputs_ptr() const NOEXCEPT
2,432✔
395
{
396
    return inputs_;
2,432✔
397
}
398

399
const outputs_cptr& transaction::outputs_ptr() const NOEXCEPT
62✔
400
{
401
    return outputs_;
62✔
402
}
403

404
uint64_t transaction::fee() const NOEXCEPT
4✔
405
{
406
    // Underflow returns zero (and is_overspent() will be true).
407
    // This is value of prevouts spent by inputs minus that claimed by outputs.
408
    return floored_subtract(value(), claim());
4✔
409
}
410

411
void transaction::set_hash(hash_digest&& hash) const NOEXCEPT
×
412
{
413
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
414
    nominal_hash_ = std::make_unique<const hash_digest>(std::move(hash));
×
415
    BC_POP_WARNING()
416
}
×
417

418
void transaction::set_witness_hash(hash_digest&& hash) const NOEXCEPT
×
419
{
420
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
421
    witness_hash_ = std::make_unique<const hash_digest>(std::move(hash));
×
422
    BC_POP_WARNING()
423
}
×
424

425
hash_digest transaction::hash(bool witness) const NOEXCEPT
925✔
426
{
427
    if (segregated_)
925✔
428
    {
429
        if (witness)
18✔
430
        {
431
            // Avoid is_coinbase call if cache present (and avoid caching it).
432
            if (witness_hash_) return *witness_hash_;
×
433

434
            // Witness coinbase tx hash is assumed to be null_hash (bip141).
435
            if (is_coinbase()) return null_hash;
×
436
        }
437
        else
438
        {
439
            if (nominal_hash_) return *nominal_hash_;
18✔
440
        }
441
    }
442
    else
443
    {
444
        if (nominal_hash_) return *nominal_hash_;
907✔
445
        if (witness_hash_) return *witness_hash_;
907✔
446
    }
447

448
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
449
    hash_digest digest;
925✔
450
    BC_POP_WARNING()
451

452
    stream::out::fast stream{ digest };
925✔
453
    hash::sha256x2::fast sink{ stream };
925✔
454
    to_data(sink, witness);
925✔
455
    sink.flush();
925✔
456
    return digest;
925✔
457
}
925✔
458

459
// Methods.
460
// ----------------------------------------------------------------------------
461

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

469
    return std::any_of(outputs_->begin(), outputs_->end(), dusty);
6✔
470
}
471

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

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

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

491
chain::points transaction::points() const NOEXCEPT
13✔
492
{
493
    chain::points out(inputs_->size());
13✔
494

495
    const auto point = [](const auto& input) NOEXCEPT
17✔
496
    {
497
        return input->point();
17✔
498
    };
499

500
    std::transform(inputs_->begin(), inputs_->end(), out.begin(), point);
13✔
501
    return out;
13✔
502
}
503

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

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

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

521
hash_digest transaction::points_hash() const NOEXCEPT
11✔
522
{
523
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
524
    hash_digest digest;
11✔
525
    BC_POP_WARNING()
526

527
    stream::out::fast stream{ digest };
11✔
528
    hash::sha256x2::fast sink{ stream };
11✔
529

530
    const auto& ins = *inputs_;
11✔
531
    for (const auto& input: ins)
27✔
532
        input->point().to_data(sink);
16✔
533

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

538
hash_digest transaction::sequences_hash() const NOEXCEPT
7✔
539
{
540
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
541
    hash_digest digest;
7✔
542
    BC_POP_WARNING()
543

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

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

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

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

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

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

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

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

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

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

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

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

618
        self.point().to_data(sink);
4✔
619
        sub.to_data(sink, prefixed);
4✔
620
        sink.write_4_bytes_little_endian(self.sequence());
4✔
621

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

630
    const auto write_outputs = [this, &input](
8✔
631
        writer& sink) NOEXCEPT
8✔
632
    {
633
        // Guarded by unversioned_signature_hash.
634
        const auto index = input_index(input);
4✔
635

636
        sink.write_variable(add1(index));
4✔
637

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

641
        outputs_->at(index)->to_data(sink);
4✔
642
    };
8✔
643

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

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

662
        sink.write_variable(anyone ? one : inputs_->size());
×
663

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

671
        self.point().to_data(sink);
×
672
        sub.to_data(sink, prefixed);
×
673
        sink.write_4_bytes_little_endian(self.sequence());
×
674

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

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

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

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

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

710
        self.point().to_data(sink);
12✔
711
        sub.to_data(sink, prefixed);
12✔
712
        sink.write_4_bytes_little_endian(self.sequence());
12✔
713

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

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

729
    sink.write_4_bytes_little_endian(version_);
12✔
730
    write_inputs(sink);
12✔
731
    write_outputs(sink);
12✔
732
    sink.write_4_bytes_little_endian(locktime_);
12✔
733
    sink.write_4_bytes_little_endian(flags);
12✔
734
}
12✔
735

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

744
    // Create hash writer.
745
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
746
    hash_digest digest;
19✔
747
    BC_POP_WARNING()
748

749
    stream::out::fast stream{ digest };
19✔
750
    hash::sha256x2::fast sink{ stream };
19✔
751

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

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

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

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

782
// private
783
// TODO: taproot requires both single and double hash of each.
784
void transaction::initialize_hash_cache() const NOEXCEPT
2✔
785
{
786
    // This overconstructs the cache (anyone or !all), however it is simple and
787
    // the same criteria applied by satoshi.
788
    if (segregated_)
2✔
789
    {
790
        BC_PUSH_WARNING(NO_NEW_OR_DELETE)
791
        BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
792
        cache_.reset(new hash_cache
2✔
793
        {
794
            outputs_hash(),
2✔
795
            points_hash(),
2✔
796
            sequences_hash()
2✔
797
        });
2✔
798
        BC_POP_WARNING()
799
        BC_POP_WARNING()
800
    }
801
}
2✔
802

803
// private
804
hash_digest transaction::output_hash(const input_iterator& input) const NOEXCEPT
14✔
805
{
806
    const auto index = input_index(input);
14✔
807

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

814
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
815
    hash_digest digest;
12✔
816
    BC_POP_WARNING()
817

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

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

834
    // Set options.
835
    // C++14: switch in constexpr.
836
    const auto anyone = to_bool(sighash_flags & coverage::anyone_can_pay);
22✔
837
    const auto flag = mask_sighash(sighash_flags);
22✔
838
    const auto all = (flag == coverage::hash_all);
22✔
839
    const auto single = (flag == coverage::hash_single);
22✔
840
    const auto& self = **input;
22✔
841

842
    // Create hash writer.
843
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
844
    hash_digest digest;
22✔
845
    BC_POP_WARNING()
846

847
    stream::out::fast stream{ digest };
22✔
848
    hash::sha256x2::fast sink{ stream };
22✔
849

850
    // Create signature hash.
851
    sink.write_little_endian(version_);
22✔
852

853
    // Conditioning points, sequences, and outputs writes on cache_ instead of
854
    // conditionally passing them from methods avoids copying the cached hash.
855

856
    // points
857
    if (cache_)
22✔
858
        sink.write_bytes(!anyone ? cache_->points : null_hash);
6✔
859
    else
860
        sink.write_bytes(!anyone ? points_hash() : null_hash);
16✔
861

862
    // sequences
863
    if (cache_)
22✔
864
        sink.write_bytes(!anyone && all ? cache_->sequences : null_hash);
6✔
865
    else
866
        sink.write_bytes(!anyone && all ? sequences_hash() : null_hash);
16✔
867

868
    self.point().to_data(sink);
22✔
869
    sub.to_data(sink, prefixed);
22✔
870
    sink.write_little_endian(value);
22✔
871
    sink.write_little_endian(self.sequence());
22✔
872

873
    // outputs
874
    if (single)
22✔
875
        sink.write_bytes(output_hash(input));
14✔
876
    else if (cache_)
8✔
877
        sink.write_bytes(all ? cache_->outputs : null_hash);
×
878
    else
879
        sink.write_bytes(all ? outputs_hash() : null_hash);
8✔
880

881
    sink.write_little_endian(locktime_);
22✔
882
    sink.write_4_bytes_little_endian(sighash_flags);
22✔
883

884
    sink.flush();
22✔
885
    return digest;
22✔
886
}
22✔
887

888
// Signing (unversioned and version 0).
889
// ----------------------------------------------------------------------------
890

891
// ****************************************************************************
892
// CONSENSUS: sighash flags are carried in a single byte but are encoded as 4
893
// bytes in the signature hash preimage serialization.
894
// ****************************************************************************
895

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

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

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

925
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
926
        sighash_flags, version, bip143);
927

928
    // Validate the EC signature.
929
    return verify_signature(public_key, sighash, signature);
2✔
930
}
931

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

940
    out.reserve(max_endorsement_size);
2✔
941
    const auto sighash = signature_hash(input_at(index), sub, value,
2✔
942
        sighash_flags, version, bip143);
943

944
    // Create the EC signature and encode as DER.
945
    ec_signature signature;
2✔
946
    if (!sign(signature, secret, sighash) || !encode_signature(out, signature))
2✔
947
        return false;
×
948

949
    // Add the sighash type to the end of the DER signature -> endorsement.
950
    out.push_back(sighash_flags);
2✔
951
    out.shrink_to_fit();
2✔
952
    return true;
2✔
953
}
954

955
// Guard (context free).
956
// ----------------------------------------------------------------------------
957

958
bool transaction::is_coinbase() const NOEXCEPT
70✔
959
{
960
    return inputs_->size() == one && inputs_->front()->point().is_null();
70✔
961
}
962

963
bool transaction::is_internal_double_spend() const NOEXCEPT
4✔
964
{
965
    return !is_distinct(points());
4✔
966
}
967

968
// TODO: a pool (non-coinbase) tx must fit into a block (with a coinbase).
969
bool transaction::is_oversized() const NOEXCEPT
×
970
{
971
    return serialized_size(false) > max_block_size;
×
972
}
973

974
// Guard (contextual).
975
// ----------------------------------------------------------------------------
976

977
// static/private
978
bool transaction::segregated(const chain::inputs& inputs) NOEXCEPT
1✔
979
{
980
    const auto witnessed = [](const auto& input) NOEXCEPT
2✔
981
    {
982
        return !input.witness().stack().empty();
1✔
983
    };
984

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

988
// static/private
989
bool transaction::segregated(const chain::input_cptrs& inputs) NOEXCEPT
813✔
990
{
991
    const auto witnessed = [](const auto& input) NOEXCEPT
816✔
992
    {
993
        return !input->witness().stack().empty();
816✔
994
    };
995

996
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
813✔
997
}
998

999
bool transaction::is_segregated() const NOEXCEPT
×
1000
{
1001
    return segregated_;
×
1002
}
1003

1004
size_t transaction::weight() const NOEXCEPT
×
1005
{
1006
    // Block weight is 3 * base size * + 1 * total size (bip141).
1007
    return base_size_contribution * serialized_size(false) +
×
1008
        total_size_contribution * serialized_size(true);
×
1009
}
1010

1011
bool transaction::is_overweight() const NOEXCEPT
×
1012
{
1013
    return weight() > max_block_weight;
×
1014
}
1015

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

1028
// Check (context free).
1029
// ----------------------------------------------------------------------------
1030

1031
bool transaction::is_empty() const NOEXCEPT
4✔
1032
{
1033
    return inputs_->empty() || outputs_->empty();
4✔
1034
}
1035

1036
bool transaction::is_null_non_coinbase() const NOEXCEPT
5✔
1037
{
1038
    BC_ASSERT(!is_coinbase());
5✔
1039

1040
    const auto invalid = [](const auto& input) NOEXCEPT
7✔
1041
    {
1042
        return input->point().is_null();
7✔
1043
    };
1044

1045
    // True if not coinbase but has null previous_output(s).
1046
    return std::any_of(inputs_->begin(), inputs_->end(), invalid);
5✔
1047
}
1048

1049
bool transaction::is_invalid_coinbase_size() const NOEXCEPT
6✔
1050
{
1051
    BC_ASSERT(is_coinbase());
6✔
1052

1053
    // True if coinbase and has invalid input[0] script size.
1054
    const auto script_size = inputs_->front()->script().serialized_size(false);
6✔
1055
    return script_size < min_coinbase_size || script_size > max_coinbase_size;
6✔
1056
}
1057

1058
// Accept (contextual).
1059
// ----------------------------------------------------------------------------
1060

1061
bool transaction::is_non_final(size_t height, uint32_t timestamp,
5✔
1062
    uint32_t median_time_past, bool bip113) const NOEXCEPT
1063
{
1064
    // BIP113: comparing the locktime against the median of the past 11 block
1065
    // timestamps, rather than the timestamp of the block including the tx.
1066
    const auto time = bip113 ? median_time_past : timestamp;
5✔
1067

1068
    const auto finalized = [](const auto& input) NOEXCEPT
2✔
1069
    {
1070
        return input->is_final();
2✔
1071
    };
1072

1073
    const auto height_time = locktime_ < locktime_threshold ? height : time;
5✔
1074

1075
    return !(is_zero(locktime_) || locktime_ < height_time ||
8✔
1076
        std::all_of(inputs_->begin(), inputs_->end(), finalized));
3✔
1077
}
1078

1079
bool transaction::is_missing_prevouts() const NOEXCEPT
3✔
1080
{
1081
    BC_ASSERT(!is_coinbase());
3✔
1082

1083
    // Null or invalid prevout indicates not found.
1084
    const auto missing = [](const auto& input) NOEXCEPT
2✔
1085
    {
1086
        return !input->prevout;
1087
    };
1088

1089
    return std::any_of(inputs_->begin(), inputs_->end(), missing);
3✔
1090
}
1091

1092
uint64_t transaction::claim() const NOEXCEPT
8✔
1093
{
1094
    // Overflow returns max_uint64.
1095
    const auto sum = [](uint64_t total, const auto& output) NOEXCEPT
8✔
1096
    {
1097
        return ceilinged_add(total, output->value());
8✔
1098
    };
1099

1100
    // The amount claimed by outputs.
1101
    return std::accumulate(outputs_->begin(), outputs_->end(), 0_u64, sum);
8✔
1102
}
1103

1104
uint64_t transaction::value() const NOEXCEPT
9✔
1105
{
1106
    // Overflow, not populated, and coinbase (default) return max_uint64.
1107
    const auto sum = [](uint64_t total, const auto& input) NOEXCEPT
7✔
1108
    {
1109
        const auto value = input->prevout ? input->prevout->value() : max_uint64;
7✔
1110
        return ceilinged_add(total, value);
7✔
1111
    };
1112

1113
    // The amount of prevouts (referenced by inputs).
1114
    return std::accumulate(inputs_->begin(), inputs_->end(), 0_u64, sum);
9✔
1115
}
1116

1117
bool transaction::is_overspent() const NOEXCEPT
2✔
1118
{
1119
    BC_ASSERT(!is_coinbase());
2✔
1120

1121
    return claim() > value();
2✔
1122
}
1123

1124
constexpr bool is_non_coinbase_mature(size_t tx_height, size_t height) NOEXCEPT
2✔
1125
{
1126
    return tx_height <= height;
2✔
1127
}
1128

1129
//*****************************************************************************
1130
// CONSENSUS: Coinbase output matures at 100 blocks depth.
1131
// CONSENSUS: Genesis coinbase is forever immature (exception).
1132
//*****************************************************************************
1133
bool transaction::is_coinbase_mature(size_t coinbase_height,
3✔
1134
    size_t height) NOEXCEPT
1135
{
1136
    return !is_zero(coinbase_height) &&
5✔
1137
        ceilinged_add(coinbase_height, coinbase_maturity) <= height;
3✔
1138
}
1139

1140
bool transaction::is_immature(size_t height) const NOEXCEPT
6✔
1141
{
1142
    BC_ASSERT(!is_coinbase());
6✔
1143

1144
    // Spends internal to a block are handled by block validation.
1145
    const auto mature = [=](const auto& input) NOEXCEPT
5✔
1146
    {
1147
        return input->metadata.coinbase ?
5✔
1148
            is_coinbase_mature(input->metadata.height, height) :
3✔
1149
            is_non_coinbase_mature(input->metadata.height, height);
2✔
1150
    };
6✔
1151

1152
    return !std::all_of(inputs_->begin(), inputs_->end(), mature);
6✔
1153
}
1154

1155
bool transaction::is_locked(size_t height,
4✔
1156
    uint32_t median_time_past) const NOEXCEPT
1157
{
1158
    // BIP68: not applied to the sequence of the input of a coinbase.
1159
    BC_ASSERT(!is_coinbase());
4✔
1160

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

1165
    // BIP68: references to median time past are as defined by bip113.
1166
    const auto locked = [=](const auto& input) NOEXCEPT
2✔
1167
    {
1168
        return input->is_locked(height, median_time_past);
2✔
1169
    };
2✔
1170

1171
    // BIP68: when the relative lock time is block based, it is interpreted as
1172
    // a minimum block height constraint over the age of the input.
1173
    return std::any_of(inputs_->begin(), inputs_->end(), locked);
2✔
1174
}
1175

1176
// Spends internal to a block are handled by block validation.
1177
bool transaction::is_unconfirmed_spend(size_t height) const NOEXCEPT
×
1178
{
1179
    BC_ASSERT(!is_coinbase());
×
1180

1181
    // Zero is either genesis or not found.
1182
    // Test maturity first to obtain proper error code.
1183
    // Spends internal to a block are handled by block validation.
1184
    const auto unconfirmed = [=](const auto& input) NOEXCEPT
×
1185
    {
1186
        const auto prevout_height = input->metadata.height;
×
1187
        return is_zero(prevout_height) && !(height > prevout_height);
×
1188
    };
×
1189

1190
    return std::any_of(inputs_->begin(), inputs_->end(), unconfirmed);
×
1191
}
1192

1193
bool transaction::is_confirmed_double_spend(size_t height) const NOEXCEPT
4✔
1194
{
1195
    BC_ASSERT(!is_coinbase());
4✔
1196

1197
    // Spends internal to a block are handled by block validation.
1198
    const auto spent = [=](const auto& input) NOEXCEPT
4✔
1199
    {
1200
        return input->metadata.spent && height > input->metadata.height;
4✔
1201
    };
4✔
1202

1203
    return std::any_of(inputs_->begin(), inputs_->end(), spent);
4✔
1204
}
1205

1206
// Guards (for tx pool without compact blocks).
1207
// ----------------------------------------------------------------------------
1208

1209
// Pools do not have coinbases.
1210
// Redundant with block is_internal_double_spend check.
1211
// Redundant with block max_block_size check.
1212
code transaction::guard_check() const NOEXCEPT
×
1213
{
1214
    if (is_coinbase())
×
1215
        return error::coinbase_transaction;
×
1216
    if (is_internal_double_spend())
×
1217
        return error::transaction_internal_double_spend;
×
1218
    if (is_oversized())
×
1219
        return error::transaction_size_limit;
×
1220

1221
    return error::transaction_success;
×
1222
}
1223

1224
// Redundant with block max_block_weight accept.
1225
code transaction::guard_check(const context& ctx) const NOEXCEPT
×
1226
{
1227
    const auto bip141 = ctx.is_enabled(flags::bip141_rule);
×
1228

1229
     if (!bip141 && is_segregated())
×
1230
        return error::unexpected_witness_transaction;
×
1231
    if (bip141 && is_overweight())
×
1232
        return error::transaction_weight_limit;
×
1233

1234
    return error::transaction_success;
×
1235
}
1236

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

1243
    if (is_missing_prevouts())
×
1244
        return error::missing_previous_output;
×
1245
    if (is_signature_operations_limit(bip16, bip141))
×
1246
        return error::transaction_sigop_limit;
×
1247

1248
    return error::transaction_success;
×
1249
}
1250

1251
// Validation.
1252
// ----------------------------------------------------------------------------
1253

1254
// DO invoke on coinbase.
1255
code transaction::check() const NOEXCEPT
×
1256
{
1257
    const auto coinbase = is_coinbase();
×
1258

1259
    if (is_empty())
×
1260
        return error::empty_transaction;
×
1261
    if (coinbase && is_invalid_coinbase_size())
×
1262
        return error::invalid_coinbase_script_size;
×
1263
    if (!coinbase && is_null_non_coinbase())
×
1264
        return error::previous_output_null;
×
1265

1266
    return error::transaction_success;
×
1267
}
1268

1269
// forks
1270
// height
1271
// timestamp
1272
// median_time_past
1273

1274
// DO invoke on coinbase.
1275
code transaction::check(const context& ctx) const NOEXCEPT
×
1276
{
1277
    const auto bip113 = ctx.is_enabled(bip113_rule);
×
1278

1279
    if (is_non_final(ctx.height, ctx.timestamp, ctx.median_time_past, bip113))
×
1280
        return error::transaction_non_final;
×
1281

1282
    return error::transaction_success;
×
1283
}
1284

1285
// Do not need to invoke on coinbase.
1286
// This assumes that prevout caching is completed on all inputs.
1287
code transaction::accept(const context&) const NOEXCEPT
×
1288
{
1289
    ////BC_ASSERT(!is_coinbase());
1290

NEW
1291
    if (is_coinbase())
×
NEW
1292
        return error::transaction_success;
×
1293
    if (is_missing_prevouts())
×
1294
        return error::missing_previous_output;
×
1295
    if (is_overspent())
×
1296
        return error::spend_exceeds_value;
×
1297

1298
    return error::transaction_success;
×
1299
}
1300

1301
// forks
1302
// height
1303
// median_time_past
1304

1305
// Do not need to invoke on coinbase.
1306
// Node performs these checks through database query.
1307
// This assumes that prevout and metadata caching are completed on all inputs.
1308
code transaction::confirm(const context& ctx) const NOEXCEPT
×
1309
{
1310
    ////BC_ASSERT(!is_coinbase());
1311
    const auto bip68 = ctx.is_enabled(bip68_rule);
×
1312

NEW
1313
    if (is_coinbase())
×
NEW
1314
        return error::transaction_success;
×
1315
    if (bip68 && is_locked(ctx.height, ctx.median_time_past))
×
1316
        return error::relative_time_locked;
×
1317
    if (is_immature(ctx.height))
×
1318
        return error::coinbase_maturity;
×
1319
    if (is_unconfirmed_spend(ctx.height))
×
1320
        return error::unconfirmed_spend;
×
1321
    if (is_confirmed_double_spend(ctx.height))
×
1322
        return error::confirmed_double_spend;
×
1323

1324
    return error::transaction_success;
×
1325
}
1326

1327
// Connect (contextual).
1328
// ----------------------------------------------------------------------------
1329

1330
// forks
1331

1332
// Do not need to invoke on coinbase.
1333
code transaction::connect(const context& ctx) const NOEXCEPT
2✔
1334
{
1335
    ////BC_ASSERT(!is_coinbase());
1336

1337
    if (is_coinbase())
2✔
NEW
1338
        return error::transaction_success;
×
1339

1340
    code ec;
2✔
1341
    using namespace machine;
2✔
1342
    initialize_hash_cache();
2✔
1343
    
1344
    const auto is_roller = [](const auto& input) NOEXCEPT
6✔
1345
    {
1346
        static const auto roll = operation{ opcode::roll };
4✔
1347

1348
        // Naive implementation, any op_roll in either script, late-counted.
1349
        // TODO: precompute on script parse, tune using performance profiling.
1350
        return contains(input.script().ops(), roll)
4✔
1351
            || (input.prevout && contains(input.prevout->script().ops(), roll));
4✔
1352
    };
1353

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

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

1370
// JSON value convertors.
1371
// ----------------------------------------------------------------------------
1372

1373
namespace json = boost::json;
1374

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

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

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

1402
BC_POP_WARNING()
1403

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

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

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

1420
BC_POP_WARNING()
1421
BC_POP_WARNING()
1422

1423
} // namespace chain
1424
} // namespace system
1425
} // 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