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

libbitcoin / libbitcoin-system / 4684436085

pending completion
4684436085

push

github

GitHub
Merge pull request #1356 from evoskuil/master

4 of 4 new or added lines in 1 file covered. (100.0%)

9438 of 11395 relevant lines covered (82.83%)

6701173.09 hits per line

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

75.29
/src/chain/transaction.cpp
1
/**
2
 * Copyright (c) 2011-2022 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();
2✔
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
1,915✔
81
{
82
}
1,915✔
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
811✔
91
  : transaction(
92
      other.version_,
811✔
93
      other.inputs_,
811✔
94
      other.outputs_,
811✔
95
      other.locktime_,
811✔
96
      other.segregated_,
811✔
97
      other.valid_)
811✔
98
{
99
}
811✔
100

101
transaction::transaction(uint32_t version, chain::inputs&& inputs,
806✔
102
    chain::outputs&& outputs, uint32_t locktime) NOEXCEPT
806✔
103
  : transaction(version, to_shareds(std::move(inputs)),
1,612✔
104
      to_shareds(std::move(outputs)), locktime, false, true)
2,418✔
105
{
106
    // Defer execution for constructor move.
107
    segregated_ = segregated(*inputs_);
806✔
108
}
806✔
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(std::istream&& stream, bool witness) NOEXCEPT
40✔
131
  : transaction(read::bytes::istream(stream), witness)
40✔
132
{
133
}
40✔
134

135
transaction::transaction(std::istream& stream, bool witness) NOEXCEPT
4✔
136
  : transaction(read::bytes::istream(stream), witness)
4✔
137
{
138
}
4✔
139

140
transaction::transaction(reader&& source, bool witness) NOEXCEPT
44✔
141
  : transaction(from_data(source, witness))
44✔
142
{
143
}
44✔
144

145
transaction::transaction(reader& source, bool witness) NOEXCEPT
117✔
146
  : transaction(from_data(source, witness))
117✔
147
{
148
}
117✔
149

150
// protected
151
transaction::transaction(uint32_t version,
1,800✔
152
    const chain::inputs_cptr& inputs, const chain::outputs_cptr& outputs,
153
    uint32_t locktime, bool segregated, bool valid) NOEXCEPT
1,800✔
154
  : version_(version),
1,800✔
155
    inputs_(inputs ? inputs : to_shared<input_cptrs>()),
3,600✔
156
    outputs_(outputs ? outputs : to_shared<output_cptrs>()),
1,800✔
157
    locktime_(locktime),
1,800✔
158
    segregated_(segregated),
1,800✔
159
    valid_(valid)
1,800✔
160
{
161
}
1,800✔
162

163
// Operators.
164
// ----------------------------------------------------------------------------
165

166
transaction& transaction::operator=(transaction&& other) NOEXCEPT
×
167
{
168
    *this = other;
×
169
    return *this;
×
170
}
171

172
transaction& transaction::operator=(const transaction& other) NOEXCEPT
×
173
{
174
    // Cache not assigned.
175
    version_ = other.version_;
×
176
    inputs_ = other.inputs_;
×
177
    outputs_ = other.outputs_;
×
178
    locktime_ = other.locktime_;
×
179
    segregated_ = other.segregated_;
×
180
    valid_ = other.valid_;
×
181
    return *this;
×
182
}
183

184
bool transaction::operator==(const transaction& other) const NOEXCEPT
58✔
185
{
186
    // Compares input/output elements, not pointers, cache not compared.
187
    return (version_ == other.version_)
58✔
188
        && (locktime_ == other.locktime_)
56✔
189
        && ((inputs_ == other.inputs_) || 
70✔
190
            deep_equal(*inputs_, *other.inputs_))
14✔
191
        && ((outputs_ == other.outputs_) ||
128✔
192
            deep_equal(*outputs_, *other.outputs_));
14✔
193
}
194

195
bool transaction::operator!=(const transaction& other) const NOEXCEPT
2✔
196
{
197
    return !(*this == other);
2✔
198
}
199

200
// Deserialization.
201
// ----------------------------------------------------------------------------
202

203
template<class Put, class Source>
204
std::shared_ptr<const std::vector<std::shared_ptr<const Put>>>
205
read_puts(Source& source) NOEXCEPT
334✔
206
{
207
    auto puts = to_shared<std::vector<std::shared_ptr<const Put>>>();
208

209
    // Subsequent emplace is non-allocating, but still THROWS.
210
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
211
    puts->reserve(source.read_size(max_block_size));
334✔
212
    BC_POP_WARNING()
213

214
    for (auto put = zero; put < puts->capacity(); ++put)
785✔
215
    {
216
        BC_PUSH_WARNING(NO_NEW_OR_DELETE)
217
        BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
218
        puts->emplace_back(new Put{ source });
451✔
219
        BC_POP_WARNING()
220
        BC_POP_WARNING()
221
    }
222

223
    // This is a pointer copy (non-const to const).
224
    return puts;
334✔
225
}
226

227
// static/private
228
transaction transaction::from_data(reader& source, bool witness) NOEXCEPT
161✔
229
{
230
    const auto version = source.read_4_bytes_little_endian();
161✔
231

232
    // Inputs must be non-const so that they may assign the witness.
233
    auto inputs = read_puts<input>(source);
161✔
234
    chain::outputs_cptr outputs;
161✔
235

236
    // Expensive repeated recomputation, so cache segregated state.
237
    const auto segregated =
161✔
238
        inputs->size() == witness_marker &&
173✔
239
        source.peek_byte() == witness_enabled;
12✔
240

241
    // Detect witness as no inputs (marker) and expected flag (bip144).
242
    if (segregated)
161✔
243
    {
244
        // Skip over the peeked witness flag.
245
        source.skip_byte();
12✔
246

247
        // Inputs and outputs are constructed on a vector of const pointers.
248
        inputs = read_puts<input>(source);
12✔
249
        outputs = read_puts<output>(source);
12✔
250

251
        // Read or skip witnesses as specified.
252
        for (auto& input: *inputs)
28✔
253
        {
254
            if (witness)
16✔
255
            {
256
                // Safe to cast as this method exclusively owns the input and
257
                // input::witness_ a mutable public property of the instance.
258
                const auto setter = const_cast<chain::input*>(input.get());
16✔
259
                setter->witness_ = to_shared<chain::witness>(source, true);
32✔
260
            }
261
            else
262
            {
263
                witness::skip(source, true);
×
264
            }
265
        }
266
    }
267
    else
268
    {
269
        // Default witness is populated on input construct.
270
        outputs = read_puts<const output>(source);
298✔
271
    }
272

273
    const auto locktime = source.read_4_bytes_little_endian();
161✔
274
    return { version, inputs, outputs, locktime, segregated, source };
161✔
275
}
276

277
// Serialization.
278
// ----------------------------------------------------------------------------
279

280
// Transactions with empty witnesses always use old serialization (bip144).
281
// If no inputs are witness programs then witness hash is tx hash (bip141).
282
data_chunk transaction::to_data(bool witness) const NOEXCEPT
8✔
283
{
284
    witness &= segregated_;
8✔
285

286
    data_chunk data(serialized_size(witness));
8✔
287

288
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
289
    stream::out::copy ostream(data);
8✔
290
    BC_POP_WARNING()
291

292
    to_data(ostream, witness);
8✔
293
    return data;
16✔
294
}
8✔
295

296
void transaction::to_data(std::ostream& stream, bool witness) const NOEXCEPT
9✔
297
{
298
    witness &= segregated_;
9✔
299

300
    write::bytes::ostream out(stream);
9✔
301
    to_data(out, witness);
9✔
302
}
9✔
303

304
void transaction::to_data(writer& sink, bool witness) const NOEXCEPT
943✔
305
{
306
    witness &= segregated_;
943✔
307

308
    sink.write_4_bytes_little_endian(version_);
943✔
309

310
    if (witness)
943✔
311
    {
312
        sink.write_byte(witness_marker);
×
313
        sink.write_byte(witness_enabled);
×
314
    }
315

316
    sink.write_variable(inputs_->size());
943✔
317
    for (const auto& input: *inputs_)
2,297✔
318
        input->to_data(sink);
1,354✔
319

320
    sink.write_variable(outputs_->size());
943✔
321
    for (const auto& output: *outputs_)
2,575✔
322
        output->to_data(sink);
1,632✔
323

324
    if (witness)
943✔
325
        for (auto& input: *inputs_)
×
326
            input->witness().to_data(sink, true);
×
327

328
    sink.write_4_bytes_little_endian(locktime_);
943✔
329
}
943✔
330

331
size_t transaction::serialized_size(bool witness) const NOEXCEPT
37✔
332
{
333
    witness &= segregated_;
37✔
334

335
    const auto ins = [=](size_t total, const auto& input) NOEXCEPT
49✔
336
    {
337
        // Inputs account for witness bytes. 
338
        return total + input->serialized_size(witness);
49✔
339
    };
37✔
340

341
    const auto outs = [](size_t total, const auto& output) NOEXCEPT
51✔
342
    {
343
        return total + output->serialized_size();
51✔
344
    };
345

346
    return sizeof(version_)
37✔
347
        + (witness ? sizeof(witness_marker) + sizeof(witness_enabled) : zero)
37✔
348
        + variable_size(inputs_->size())
37✔
349
        + std::accumulate(inputs_->begin(), inputs_->end(), zero, ins)
37✔
350
        + variable_size(outputs_->size())
37✔
351
        + std::accumulate(outputs_->begin(), outputs_->end(), zero, outs)
37✔
352
        + sizeof(locktime_);
37✔
353
}
354

355
// Properties.
356
// ----------------------------------------------------------------------------
357

358
bool transaction::is_valid() const NOEXCEPT
773✔
359
{
360
    return valid_;
773✔
361
}
362

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

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

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

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

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

390
void transaction::set_hash(hash_digest&& hash) const NOEXCEPT
×
391
{
392
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
393
    hash_ = std::make_unique<const hash_digest>(std::move(hash));
×
394
    BC_POP_WARNING()
395
}
×
396

397
void transaction::set_witness_hash(hash_digest&& hash) const NOEXCEPT
×
398
{
399
    BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
400
    witness_hash_ = std::make_unique<const hash_digest>(std::move(hash));
×
401
    BC_POP_WARNING()
402
}
×
403

404
hash_digest transaction::hash(bool witness) const NOEXCEPT
908✔
405
{
406
    if (segregated_)
908✔
407
    {
408
        if (witness)
18✔
409
        {
410
            // Avoid is_coinbase call if cache present (and avoid caching it).
411
            if (witness_hash_) return *witness_hash_;
×
412

413
            // Witness coinbase tx hash is assumed to be null_hash (bip141).
414
            if (is_coinbase()) return null_hash;
×
415
        }
416
        else
417
        {
418
            if (hash_) return *hash_;
18✔
419
        }
420
    }
421
    else
422
    {
423
        if (hash_) return *hash_;
890✔
424
        if (witness_hash_) return *witness_hash_;
890✔
425
    }
426

427
    // This is an out parameter.
428
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
429
    hash_digest digest;
908✔
430
    BC_POP_WARNING()
431

432
    hash::sha256x2::copy sink(digest);
908✔
433
    to_data(sink, witness);
908✔
434
    sink.flush();
908✔
435
    return digest;
908✔
436
}
908✔
437

438
// Methods.
439
// ----------------------------------------------------------------------------
440

441
bool transaction::is_dusty(uint64_t minimum_output_value) const NOEXCEPT
6✔
442
{
443
    const auto dusty = [=](const auto& output) NOEXCEPT
9✔
444
    {
445
        return output->is_dust(minimum_output_value);
9✔
446
    };
6✔
447

448
    return std::any_of(outputs_->begin(), outputs_->end(), dusty);
6✔
449
}
450

451
size_t transaction::signature_operations(bool bip16, bool bip141) const NOEXCEPT
1✔
452
{
453
    // Includes BIP16 p2sh additional sigops, max_size_t if prevout invalid.
454
    const auto in = [=](size_t total, const auto& input) NOEXCEPT
×
455
    {
456
        return ceilinged_add(total, input->signature_operations(bip16, bip141));
×
457
    };
1✔
458

459
    const auto out = [=](size_t total, const auto& output) NOEXCEPT
×
460
    {
461
        return ceilinged_add(total, output->signature_operations(bip141));
×
462
    };
1✔
463

464
    // Overflow returns max_size_t.
465
    return ceilinged_add(
1✔
466
        std::accumulate(inputs_->begin(), inputs_->end(), zero, in),
467
        std::accumulate(outputs_->begin(), outputs_->end(), zero, out));
1✔
468
}
469

470
chain::points transaction::points() const NOEXCEPT
13✔
471
{
472
    chain::points out(inputs_->size());
13✔
473

474
    const auto point = [](const auto& input) NOEXCEPT
17✔
475
    {
476
        return input->point();
17✔
477
    };
478

479
    std::transform(inputs_->begin(), inputs_->end(), out.begin(), point);
13✔
480
    return out;
13✔
481
}
482

483
hash_digest transaction::outputs_hash() const NOEXCEPT
8✔
484
{
485
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
486
    hash_digest digest;
8✔
487
    BC_POP_WARNING()
488

489
    hash::sha256x2::copy sink(digest);
8✔
490

491
    const auto& outs = *outputs_;
8✔
492
    for (const auto& output: outs)
22✔
493
        output->to_data(sink);
14✔
494

495
    sink.flush();
8✔
496
    return digest;
16✔
497
}
8✔
498

499
hash_digest transaction::points_hash() const NOEXCEPT
11✔
500
{
501
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
502
    hash_digest digest;
11✔
503
    BC_POP_WARNING()
504

505
    hash::sha256x2::copy sink(digest);
11✔
506

507
    const auto& ins = *inputs_;
11✔
508
    for (const auto& input: ins)
27✔
509
        input->point().to_data(sink);
16✔
510

511
    sink.flush();
11✔
512
    return digest;
22✔
513
}
11✔
514

515
hash_digest transaction::sequences_hash() const NOEXCEPT
7✔
516
{
517
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
518
    hash_digest digest;
7✔
519
    BC_POP_WARNING()
520

521
    hash::sha256x2::copy sink(digest);
7✔
522

523
    const auto& ins = *inputs_;
7✔
524
    for (const auto& input: ins)
17✔
525
        sink.write_4_bytes_little_endian(input->sequence());
10✔
526

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

531
// Signing (unversioned).
532
// ----------------------------------------------------------------------------
533

534
// private
535
transaction::input_iterator transaction::input_at(
4✔
536
    uint32_t index) const NOEXCEPT
537
{
538
    // Guarded by check_signature and create_endorsement.
539
    BC_ASSERT_MSG(index < inputs_->size(), "invalid input index");
4✔
540

541
    return std::next(inputs_->begin(), index);
4✔
542
}
543

544
// private
545
uint32_t transaction::input_index(const input_iterator& input) const NOEXCEPT
25✔
546
{
547
    // Guarded by unversioned_signature_hash and output_hash.
548
    BC_ASSERT_MSG(inputs_->begin() != inputs_->end(), "invalid input iterator");
25✔
549

550
    return possible_narrow_and_sign_cast<uint32_t>(
25✔
551
        std::distance(inputs_->begin(), input));
25✔
552
}
553

554
// C++14: switch in constexpr.
555
//*****************************************************************************
556
// CONSENSUS: Due to masking of bits 6/7 (8 is the anyone_can_pay flag),
557
// there are 4 possible 7 bit values that can set "single" and 4 others that
558
// can set none, and yet all other values set "all".
559
//*****************************************************************************
560
inline coverage mask_sighash(uint8_t flags) NOEXCEPT
41✔
561
{
562
    switch (flags & coverage::mask)
41✔
563
    {
564
        case coverage::hash_single:
565
            return coverage::hash_single;
566
        case coverage::hash_none:
2✔
567
            return coverage::hash_none;
2✔
568
        default:
18✔
569
            return coverage::hash_all;
18✔
570
    }
571
}
572

573
/// REQUIRES INDEX.
574
void transaction::signature_hash_single(writer& sink,
4✔
575
    const input_iterator& input, const script& sub,
576
    uint8_t flags) const NOEXCEPT
577
{
578
    const auto write_inputs = [this, &input, &sub, flags](
8✔
579
        writer& sink) NOEXCEPT
4✔
580
    {
581
        const auto& self = **input;
4✔
582
        const auto anyone = to_bool(flags & coverage::anyone_can_pay);
4✔
583
        input_cptrs::const_iterator in;
4✔
584

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

587
        for (in = inputs_->begin(); !anyone && in != input; ++in)
4✔
588
        {
589
            (*in)->point().to_data(sink);
×
590
            sink.write_bytes(empty_script());
×
591
            sink.write_bytes(zero_sequence());
×
592
        }
593

594
        self.point().to_data(sink);
4✔
595
        sub.to_data(sink, prefixed);
4✔
596
        sink.write_4_bytes_little_endian(self.sequence());
4✔
597

598
        for (++in; !anyone && in != inputs_->end(); ++in)
5✔
599
        {
600
            (*in)->point().to_data(sink);
1✔
601
            sink.write_bytes(empty_script());
1✔
602
            sink.write_bytes(zero_sequence());
1✔
603
        }
604
    };
4✔
605

606
    const auto write_outputs = [this, &input](
8✔
607
        writer& sink) NOEXCEPT
8✔
608
    {
609
        // Guarded by unversioned_signature_hash.
610
        const auto index = input_index(input);
4✔
611

612
        sink.write_variable(add1(index));
4✔
613

614
        for (size_t output = 0; output < index; ++output)
5✔
615
            sink.write_bytes(null_output());
1✔
616

617
        outputs_->at(index)->to_data(sink);
4✔
618
    };
8✔
619

620
    sink.write_4_bytes_little_endian(version_);
4✔
621
    write_inputs(sink);
4✔
622
    write_outputs(sink);
4✔
623
    sink.write_4_bytes_little_endian(locktime_);
4✔
624
    sink.write_4_bytes_little_endian(flags);
4✔
625
}
4✔
626

627
void transaction::signature_hash_none(writer& sink,
×
628
    const input_iterator& input, const script& sub,
629
    uint8_t flags) const NOEXCEPT
630
{
631
    const auto write_inputs = [this, &input, &sub, flags](
×
632
        writer& sink) NOEXCEPT
×
633
    {
634
        const auto& self = **input;
×
635
        const auto anyone = to_bool(flags & coverage::anyone_can_pay);
×
636
        input_cptrs::const_iterator in;
×
637

638
        sink.write_variable(anyone ? one : inputs_->size());
×
639

640
        for (in = inputs_->begin(); !anyone && in != input; ++in)
×
641
        {
642
            (*in)->point().to_data(sink);
×
643
            sink.write_bytes(empty_script());
×
644
            sink.write_bytes(zero_sequence());
×
645
        }
646

647
        self.point().to_data(sink);
×
648
        sub.to_data(sink, prefixed);
×
649
        sink.write_4_bytes_little_endian(self.sequence());
×
650

651
        for (++in; !anyone && in != inputs_->end(); ++in)
×
652
        {
653
            (*in)->point().to_data(sink);
×
654
            sink.write_bytes(empty_script());
×
655
            sink.write_bytes(zero_sequence());
×
656
        }
657
    };
×
658

659
    sink.write_4_bytes_little_endian(version_);
×
660
    write_inputs(sink);
×
661
    sink.write_variable(zero);
×
662
    sink.write_4_bytes_little_endian(locktime_);
×
663
    sink.write_4_bytes_little_endian(flags);
×
664
}
×
665

666
void transaction::signature_hash_all(writer& sink,
12✔
667
    const input_iterator& input, const script& sub,
668
    uint8_t flags) const NOEXCEPT
669
{
670
    const auto write_inputs = [this, &input, &sub, flags](
24✔
671
        writer& sink) NOEXCEPT
43✔
672
    {
673
        const auto& self = **input;
12✔
674
        const auto anyone = to_bool(flags & coverage::anyone_can_pay);
12✔
675
        input_cptrs::const_iterator in;
12✔
676

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

679
        for (in = inputs_->begin(); !anyone && in != input; ++in)
15✔
680
        {
681
            (*in)->point().to_data(sink);
3✔
682
            sink.write_bytes(empty_script());
3✔
683
            sink.write_4_bytes_little_endian((*in)->sequence());
3✔
684
        }
685

686
        self.point().to_data(sink);
12✔
687
        sub.to_data(sink, prefixed);
12✔
688
        sink.write_4_bytes_little_endian(self.sequence());
12✔
689

690
        for (++in; !anyone && in != inputs_->end(); ++in)
16✔
691
        {
692
            (*in)->point().to_data(sink);
4✔
693
            sink.write_bytes(empty_script());
4✔
694
            sink.write_4_bytes_little_endian((*in)->sequence());
4✔
695
        }
696
    };
12✔
697

698
    const auto write_outputs = [this](writer& sink) NOEXCEPT
36✔
699
    {
700
        sink.write_variable(outputs_->size());
12✔
701
        for (const auto& output: *outputs_)
27✔
702
            output->to_data(sink);
15✔
703
    };
24✔
704

705
    sink.write_4_bytes_little_endian(version_);
12✔
706
    write_inputs(sink);
12✔
707
    write_outputs(sink);
12✔
708
    sink.write_4_bytes_little_endian(locktime_);
12✔
709
    sink.write_4_bytes_little_endian(flags);
12✔
710
}
12✔
711

712
// private
713
hash_digest transaction::unversioned_signature_hash(
19✔
714
    const input_iterator& input, const script& sub,
715
    uint8_t flags) const NOEXCEPT
716
{
717
    // Set options.
718
    const auto flag = mask_sighash(flags);
19✔
719

720
    // Create hash writer.
721
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
722
    hash_digest digest;
19✔
723
    BC_POP_WARNING()
724

725
    hash::sha256x2::copy sink(digest);
19✔
726

727
    switch (flag)
19✔
728
    {
729
        case coverage::hash_single:
7✔
730
        {
7✔
731
            //*****************************************************************
732
            // CONSENSUS: return one_hash if index exceeds outputs in sighash.
733
            // Bug: https://bitcointalk.org/index.php?topic=260595
734
            // Expoit: http://joncave.co.uk/2014/08/bitcoin-sighash-single/
735
            //*****************************************************************
736
            if (input_index(input) >= outputs_->size())
7✔
737
                return one_hash;
3✔
738

739
            signature_hash_single(sink, input, sub, flags);
4✔
740
            break;
4✔
741
        }
742
        case coverage::hash_none:
×
743
            signature_hash_none(sink, input, sub, flags);
×
744
            break;
×
745
        default:
12✔
746
        case coverage::hash_all:
12✔
747
            signature_hash_all(sink, input, sub, flags);
12✔
748
    }
749

750
    sink.flush();
16✔
751
    return digest;
16✔
752
}
19✔
753

754
// Signing (version 0).
755
// ----------------------------------------------------------------------------
756

757
// private
758
// TODO: taproot requires both single and double hash of each.
759
void transaction::initialize_hash_cache() const NOEXCEPT
2✔
760
{
761
    // This overconstructs the cache (anyone or !all), however it is simple and
762
    // the same criteria applied by satoshi.
763
    if (segregated_)
2✔
764
    {
765
        BC_PUSH_WARNING(NO_NEW_OR_DELETE)
766
        BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
767
        cache_.reset(new hash_cache
2✔
768
        {
769
            outputs_hash(),
2✔
770
            points_hash(),
2✔
771
            sequences_hash()
2✔
772
        });
2✔
773
        BC_POP_WARNING()
774
        BC_POP_WARNING()
775
    }
776
}
2✔
777

778
// private
779
hash_digest transaction::output_hash(const input_iterator& input) const NOEXCEPT
14✔
780
{
781
    const auto index = input_index(input);
14✔
782

783
    //*************************************************************************
784
    // CONSENSUS: if index exceeds outputs in signature hash, return null_hash.
785
    //*************************************************************************
786
    if (index >= outputs_->size())
14✔
787
        return null_hash;
2✔
788

789
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
790
    hash_digest digest;
12✔
791
    BC_POP_WARNING()
792

793
    hash::sha256x2::copy sink(digest);
12✔
794
    outputs_->at(index)->to_data(sink);
12✔
795
    sink.flush();
12✔
796
    return digest;
12✔
797
}
12✔
798

799
// private
800
hash_digest transaction::version_0_signature_hash(const input_iterator& input,
29✔
801
    const script& sub, uint64_t value, uint8_t flags,
802
    bool bip143) const NOEXCEPT
803
{
804
    // bip143/v0: the way of serialization is changed.
805
    if (!bip143)
29✔
806
        return unversioned_signature_hash(input, sub, flags);
7✔
807

808
    // Set options.
809
    // C++14: switch in constexpr.
810
    const auto anyone = to_bool(flags & coverage::anyone_can_pay);
22✔
811
    const auto flag = mask_sighash(flags);
22✔
812
    const auto all = (flag == coverage::hash_all);
22✔
813
    const auto single = (flag == coverage::hash_single);
22✔
814
    const auto& self = **input;
22✔
815

816
    // Create hash writer.
817
    BC_PUSH_WARNING(LOCAL_VARIABLE_NOT_INITIALIZED)
818
    hash_digest digest;
22✔
819
    BC_POP_WARNING()
820

821
    hash::sha256x2::copy sink(digest);
22✔
822

823
    // Create signature hash.
824
    sink.write_little_endian(version_);
22✔
825

826
    // Conditioning points, sequences, and outputs writes on cache_ instead of
827
    // conditionally passing them from methods avoids copying the cached hash.
828

829
    // points
830
    if (cache_)
22✔
831
        sink.write_bytes(!anyone ? cache_->points : null_hash);
6✔
832
    else
833
        sink.write_bytes(!anyone ? points_hash() : null_hash);
16✔
834

835
    // sequences
836
    if (cache_)
22✔
837
        sink.write_bytes(!anyone && all ? cache_->sequences : null_hash);
6✔
838
    else
839
        sink.write_bytes(!anyone && all ? sequences_hash() : null_hash);
16✔
840

841
    self.point().to_data(sink);
22✔
842
    sub.to_data(sink, prefixed);
22✔
843
    sink.write_little_endian(value);
22✔
844
    sink.write_little_endian(self.sequence());
22✔
845

846
    // outputs
847
    if (single)
22✔
848
        sink.write_bytes(output_hash(input));
14✔
849
    else if (cache_)
8✔
850
        sink.write_bytes(all ? cache_->outputs : null_hash);
×
851
    else
852
        sink.write_bytes(all ? outputs_hash() : null_hash);
8✔
853

854
    sink.write_little_endian(locktime_);
22✔
855
    sink.write_4_bytes_little_endian(flags);
22✔
856

857
    sink.flush();
22✔
858
    return digest;
22✔
859
}
22✔
860

861
// Signing (unversioned and version 0).
862
// ----------------------------------------------------------------------------
863

864
// ****************************************************************************
865
// CONSENSUS: sighash flags are carried in a single byte but are encoded as 4
866
// bytes in the signature hash preimage serialization.
867
// ****************************************************************************
868

869
hash_digest transaction::signature_hash(const input_iterator& input,
41✔
870
    const script& sub, uint64_t value, uint8_t flags, script_version version,
871
    bool bip143) const NOEXCEPT
872
{
873
    // There is no rational interpretation of a signature hash for a coinbase.
874
    BC_ASSERT(!is_coinbase());
41✔
875

876
    switch (version)
41✔
877
    {
878
        case script_version::unversioned:
12✔
879
            return unversioned_signature_hash(input, sub, flags);
12✔
880
        case script_version::zero:
29✔
881
            return version_0_signature_hash(input, sub, value, flags, bip143);
29✔
882
        case script_version::reserved:
×
883
        default:
×
884
            return {};
×
885
    }
886
}
887

888
// This is not used internal to the library.
889
bool transaction::check_signature(const ec_signature& signature,
2✔
890
    const data_slice& public_key, const script& sub, uint32_t index,
891
    uint64_t value, uint8_t flags, script_version version,
892
    bool bip143) const NOEXCEPT
893
{
894
    if ((index >= inputs_->size()) ||
2✔
895
        signature.empty() || public_key.empty())
2✔
896
        return false;
897

898
    const auto sighash = signature_hash(input_at(index), sub, value, flags,
2✔
899
        version, bip143);
900

901
    // Validate the EC signature.
902
    return verify_signature(public_key, sighash, signature);
2✔
903
}
904

905
// This is not used internal to the library.
906
bool transaction::create_endorsement(endorsement& out, const ec_secret& secret,
2✔
907
    const script& sub, uint32_t index, uint64_t value, uint8_t flags,
908
    script_version version, bool bip143) const NOEXCEPT
909
{
910
    if (index >= inputs_->size())
2✔
911
        return false;
912

913
    out.reserve(max_endorsement_size);
2✔
914
    const auto sighash = signature_hash(input_at(index), sub, value, flags,
2✔
915
        version, bip143);
916

917
    // Create the EC signature and encode as DER.
918
    ec_signature signature;
2✔
919
    if (!sign(signature, secret, sighash) || !encode_signature(out, signature))
2✔
920
        return false;
×
921

922
    // Add the sighash type to the end of the DER signature -> endorsement.
923
    out.push_back(flags);
2✔
924
    out.shrink_to_fit();
2✔
925
    return true;
2✔
926
}
927

928
// Guard (context free).
929
// ----------------------------------------------------------------------------
930

931
bool transaction::is_coinbase() const NOEXCEPT
68✔
932
{
933
    return inputs_->size() == one && inputs_->front()->point().is_null();
68✔
934
}
935

936
bool transaction::is_internal_double_spend() const NOEXCEPT
4✔
937
{
938
    return !is_distinct(points());
4✔
939
}
940

941
// TODO: a pool (non-coinbase) tx must fit into a block (with a coinbase).
942
bool transaction::is_oversized() const NOEXCEPT
×
943
{
944
    return serialized_size(false) > max_block_size;
×
945
}
946

947
// Guard (contextual).
948
// ----------------------------------------------------------------------------
949

950
// static/private
951
bool transaction::segregated(const chain::inputs& inputs) NOEXCEPT
1✔
952
{
953
    const auto witnessed = [](const auto& input) NOEXCEPT
2✔
954
    {
955
        return !input.witness().stack().empty();
1✔
956
    };
957

958
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
1✔
959
}
960

961
// static/private
962
bool transaction::segregated(const chain::input_cptrs& inputs) NOEXCEPT
806✔
963
{
964
    const auto witnessed = [](const auto& input) NOEXCEPT
809✔
965
    {
966
        return !input->witness().stack().empty();
809✔
967
    };
968

969
    return std::any_of(inputs.begin(), inputs.end(), witnessed);
806✔
970
}
971

972
bool transaction::is_segregated() const NOEXCEPT
×
973
{
974
    return segregated_;
×
975
}
976

977
size_t transaction::weight() const NOEXCEPT
×
978
{
979
    // Block weight is 3 * base size * + 1 * total size (bip141).
980
    return base_size_contribution * serialized_size(false) +
×
981
        total_size_contribution * serialized_size(true);
×
982
}
983

984
bool transaction::is_overweight() const NOEXCEPT
×
985
{
986
    return weight() > max_block_weight;
×
987
}
988

989
//*****************************************************************************
990
// CONSENSUS: Legacy sigops are counted in coinbase scripts despite the fact
991
// that coinbase input scripts are never executed. There is no need to exclude
992
// p2sh coinbase sigops since there is never a script to count.
993
//*****************************************************************************
994
bool transaction::is_signature_operations_limit(bool bip16,
×
995
    bool bip141) const NOEXCEPT
996
{
997
    const auto limit = bip141 ? max_fast_sigops : max_block_sigops;
×
998
    return signature_operations(bip16, bip141) > limit;
×
999
}
1000

1001
// Check (context free).
1002
// ----------------------------------------------------------------------------
1003

1004
bool transaction::is_empty() const NOEXCEPT
4✔
1005
{
1006
    return inputs_->empty() || outputs_->empty();
4✔
1007
}
1008

1009
bool transaction::is_null_non_coinbase() const NOEXCEPT
5✔
1010
{
1011
    BC_ASSERT(!is_coinbase());
5✔
1012

1013
    const auto invalid = [](const auto& input) NOEXCEPT
7✔
1014
    {
1015
        return input->point().is_null();
7✔
1016
    };
1017

1018
    // True if not coinbase but has null previous_output(s).
1019
    return std::any_of(inputs_->begin(), inputs_->end(), invalid);
5✔
1020
}
1021

1022
bool transaction::is_invalid_coinbase_size() const NOEXCEPT
6✔
1023
{
1024
    BC_ASSERT(is_coinbase());
6✔
1025

1026
    // True if coinbase and has invalid input[0] script size.
1027
    const auto script_size = inputs_->front()->script().serialized_size(false);
6✔
1028
    return script_size < min_coinbase_size || script_size > max_coinbase_size;
6✔
1029
}
1030

1031
// Accept (contextual).
1032
// ----------------------------------------------------------------------------
1033

1034
bool transaction::is_non_final(size_t height, uint32_t timestamp,
5✔
1035
    uint32_t median_time_past, bool bip113) const NOEXCEPT
1036
{
1037
    // BIP113: comparing the locktime against the median of the past 11 block
1038
    // timestamps, rather than the timestamp of the block including the tx.
1039
    const auto time = bip113 ? median_time_past : timestamp;
5✔
1040

1041
    const auto finalized = [](const auto& input) NOEXCEPT
2✔
1042
    {
1043
        return input->is_final();
2✔
1044
    };
1045

1046
    const auto height_time = locktime_ < locktime_threshold ? height : time;
5✔
1047

1048
    return !(is_zero(locktime_) || locktime_ < height_time ||
5✔
1049
        std::all_of(inputs_->begin(), inputs_->end(), finalized));
3✔
1050
}
1051

1052
bool transaction::is_missing_prevouts() const NOEXCEPT
3✔
1053
{
1054
    BC_ASSERT(!is_coinbase());
3✔
1055

1056
    // Null or invalid prevout indicates not found.
1057
    const auto missing = [](const auto& input) NOEXCEPT
2✔
1058
    {
1059
        return !input->prevout;
1060
    };
1061

1062
    return std::any_of(inputs_->begin(), inputs_->end(), missing);
3✔
1063
}
1064

1065
uint64_t transaction::claim() const NOEXCEPT
8✔
1066
{
1067
    // Overflow returns max_uint64.
1068
    const auto sum = [](uint64_t total, const auto& output) NOEXCEPT
8✔
1069
    {
1070
        return ceilinged_add(total, output->value());
8✔
1071
    };
1072

1073
    // The amount claimed by outputs.
1074
    return std::accumulate(outputs_->begin(), outputs_->end(), 0_u64, sum);
8✔
1075
}
1076

1077
uint64_t transaction::value() const NOEXCEPT
9✔
1078
{
1079
    // Overflow, not populated, and coinbase (default) return max_uint64.
1080
    const auto sum = [](uint64_t total, const auto& input) NOEXCEPT
7✔
1081
    {
1082
        const auto value = input->prevout ? input->prevout->value() : max_uint64;
7✔
1083
        return ceilinged_add(total, value);
7✔
1084
    };
1085

1086
    // The amount of prevouts (referenced by inputs).
1087
    return std::accumulate(inputs_->begin(), inputs_->end(), 0_u64, sum);
9✔
1088
}
1089

1090
bool transaction::is_overspent() const NOEXCEPT
2✔
1091
{
1092
    BC_ASSERT(!is_coinbase());
2✔
1093

1094
    return claim() > value();
2✔
1095
}
1096

1097
constexpr bool is_non_coinbase_mature(size_t tx_height, size_t height) NOEXCEPT
2✔
1098
{
1099
    return tx_height <= height;
2✔
1100
}
1101

1102
//*****************************************************************************
1103
// CONSENSUS: Coinbase output matures at 100 blocks depth.
1104
// CONSENSUS: Genesis coinbase is forever immature (exception).
1105
//*****************************************************************************
1106
bool transaction::is_coinbase_mature(size_t coinbase_height,
3✔
1107
    size_t height) NOEXCEPT
1108
{
1109
    return !is_zero(coinbase_height) &&
5✔
1110
        ceilinged_add(coinbase_height, coinbase_maturity) <= height;
3✔
1111
}
1112

1113
bool transaction::is_immature(size_t height) const NOEXCEPT
6✔
1114
{
1115
    BC_ASSERT(!is_coinbase());
6✔
1116

1117
    // Spends internal to a block are handled by block validation.
1118
    const auto mature = [=](const auto& input) NOEXCEPT
5✔
1119
    {
1120
        return input->metadata.coinbase ?
5✔
1121
            is_coinbase_mature(input->metadata.height, height) :
3✔
1122
            is_non_coinbase_mature(input->metadata.height, height);
2✔
1123
    };
6✔
1124

1125
    return !std::all_of(inputs_->begin(), inputs_->end(), mature);
6✔
1126
}
1127

1128
bool transaction::is_locked(size_t height,
4✔
1129
    uint32_t median_time_past) const NOEXCEPT
1130
{
1131
    // BIP68: not applied to the sequence of the input of a coinbase.
1132
    BC_ASSERT(!is_coinbase());
4✔
1133

1134
    // BIP68: applied to txs with a version greater than or equal to two.
1135
    if (version_ < relative_locktime_min_version)
4✔
1136
        return false;
1137

1138
    // BIP68: references to median time past are as defined by bip113.
1139
    const auto locked = [=](const auto& input) NOEXCEPT
2✔
1140
    {
1141
        return input->is_locked(height, median_time_past);
2✔
1142
    };
2✔
1143

1144
    // BIP68: when the relative lock time is block based, it is interpreted as
1145
    // a minimum block height constraint over the age of the input.
1146
    return std::any_of(inputs_->begin(), inputs_->end(), locked);
2✔
1147
}
1148

1149
// Spends internal to a block are handled by block validation.
1150
bool transaction::is_unconfirmed_spend(size_t height) const NOEXCEPT
×
1151
{
1152
    BC_ASSERT(!is_coinbase());
×
1153

1154
    // Zero is either genesis or not found.
1155
    // Test maturity first to obtain proper error code.
1156
    // Spends internal to a block are handled by block validation.
1157
    const auto unconfirmed = [=](const auto& input) NOEXCEPT
×
1158
    {
1159
        const auto prevout_height = input->metadata.height;
×
1160
        return is_zero(prevout_height) && !(height > prevout_height);
×
1161
    };
×
1162

1163
    return std::any_of(inputs_->begin(), inputs_->end(), unconfirmed);
×
1164
}
1165

1166
bool transaction::is_confirmed_double_spend(size_t height) const NOEXCEPT
4✔
1167
{
1168
    BC_ASSERT(!is_coinbase());
4✔
1169

1170
    // Spends internal to a block are handled by block validation.
1171
    const auto spent = [=](const auto& input) NOEXCEPT
4✔
1172
    {
1173
        return input->metadata.spent && height > input->metadata.height;
4✔
1174
    };
4✔
1175

1176
    return std::any_of(inputs_->begin(), inputs_->end(), spent);
4✔
1177
}
1178

1179
// Guards (for tx pool without compact blocks).
1180
// ----------------------------------------------------------------------------
1181

1182
// Pools do not have coinbases.
1183
// Redundant with block is_internal_double_spend check.
1184
// Redundant with block max_block_size check.
1185
code transaction::guard_check() const NOEXCEPT
×
1186
{
1187
    if (is_coinbase())
×
1188
        return error::coinbase_transaction;
×
1189
    if (is_internal_double_spend())
×
1190
        return error::transaction_internal_double_spend;
×
1191
    if (is_oversized())
×
1192
        return error::transaction_size_limit;
×
1193

1194
    return error::transaction_success;
×
1195
}
1196

1197
// Redundant with block max_block_weight accept.
1198
code transaction::guard_check(const context& ctx) const NOEXCEPT
×
1199
{
1200
    const auto bip141 = ctx.is_enabled(forks::bip141_rule);
×
1201

1202
     if (!bip141 && is_segregated())
×
1203
        return error::unexpected_witness_transaction;
×
1204
    if (bip141 && is_overweight())
×
1205
        return error::transaction_weight_limit;
×
1206

1207
    return error::transaction_success;
×
1208
}
1209

1210
// Redundant with block max_block_sigops accept.
1211
code transaction::guard_accept(const context& ctx) const NOEXCEPT
×
1212
{
1213
    const auto bip16 = ctx.is_enabled(forks::bip16_rule);
×
1214
    const auto bip141 = ctx.is_enabled(forks::bip141_rule);
×
1215

1216
    if (is_missing_prevouts())
×
1217
        return error::missing_previous_output;
×
1218
    if (is_signature_operations_limit(bip16, bip141))
×
1219
        return error::transaction_sigop_limit;
×
1220

1221
    return error::transaction_success;
×
1222
}
1223

1224
// Validation.
1225
// ----------------------------------------------------------------------------
1226

1227
// DO invoke on coinbase.
1228
code transaction::check() const NOEXCEPT
×
1229
{
1230
    const auto coinbase = is_coinbase();
×
1231

1232
    if (is_empty())
×
1233
        return error::empty_transaction;
×
1234
    if (coinbase && is_invalid_coinbase_size())
×
1235
        return error::invalid_coinbase_script_size;
×
1236
    if (!coinbase && is_null_non_coinbase())
×
1237
        return error::previous_output_null;
×
1238

1239
    return error::transaction_success;
×
1240
}
1241

1242
// DO invoke on coinbase.
1243
code transaction::check(const context& ctx) const NOEXCEPT
×
1244
{
1245
    const auto bip113 = ctx.is_enabled(bip113_rule);
×
1246

1247
    if (is_non_final(ctx.height, ctx.timestamp, ctx.median_time_past, bip113))
×
1248
        return error::transaction_non_final;
×
1249

1250
    return error::transaction_success;
×
1251
}
1252

1253
// Do NOT invoke on coinbase.
1254
// These assume that prevout caching is completed on all inputs.
1255
code transaction::accept(const context&) const NOEXCEPT
×
1256
{
1257
    BC_ASSERT(!is_coinbase());
×
1258

1259
    if (is_coinbase())
×
1260
        return error::transaction_success;
×
1261
    if (is_missing_prevouts())
×
1262
        return error::missing_previous_output;
×
1263
    if (is_overspent())
×
1264
        return error::spend_exceeds_value;
×
1265

1266
    return error::transaction_success;
×
1267
}
1268

1269
// Do NOT invoke on coinbase.
1270
// Node performs these checks through database query.
1271
// This assume that prevout and metadata caching are completed on all inputs.
1272
code transaction::confirm(const context& ctx) const NOEXCEPT
×
1273
{
1274
    BC_ASSERT(!is_coinbase());
×
1275
    const auto bip68 = ctx.is_enabled(bip68_rule);
×
1276

1277
    if (is_coinbase())
×
1278
        return error::transaction_success;
×
1279
    if (bip68 && is_locked(ctx.height, ctx.median_time_past))
×
1280
        return error::relative_time_locked;
×
1281
    if (is_immature(ctx.height))
×
1282
        return error::coinbase_maturity;
×
1283
    if (is_unconfirmed_spend(ctx.height))
×
1284
        return error::unconfirmed_spend;
×
1285
    if (is_confirmed_double_spend(ctx.height))
×
1286
        return error::confirmed_double_spend;
×
1287

1288
    return error::transaction_success;
×
1289
}
1290

1291
// Connect (contextual).
1292
// ----------------------------------------------------------------------------
1293

1294
// Do NOT invoke on coinbase.
1295
code transaction::connect(const context& ctx) const NOEXCEPT
2✔
1296
{
1297
    BC_ASSERT(!is_coinbase());
2✔
1298

1299
    ////if (is_coinbase())
1300
    ////    return error::transaction_success;
1301

1302
    code ec;
2✔
1303
    using namespace machine;
2✔
1304
    initialize_hash_cache();
2✔
1305
    
1306
    const auto is_roller = [](const auto& input) NOEXCEPT
6✔
1307
    {
1308
        static const auto roll = operation{ opcode::roll };
4✔
1309

1310
        // Naive implementation, any op_roll in either script, late-counted.
1311
        // TODO: precompute on script parse, tune using performance profiling.
1312
        return contains(input.script().ops(), roll)
4✔
1313
            || (input.prevout && contains(input.prevout->script().ops(), roll));
4✔
1314
    };
1315

1316
    // Validate scripts.
1317
    for (auto input = inputs_->begin(); input != inputs_->end(); ++input)
6✔
1318
    {
1319
        // Evaluate rolling scripts with linear search but constant erase.
1320
        // Evaluate non-rolling scripts with constant search but linear erase.
1321
        if ((ec = is_roller(**input) ?
8✔
1322
            interpreter<linked_stack>::connect(ctx, *this, input) :
×
1323
            interpreter<contiguous_stack>::connect(ctx, *this, input)))
4✔
1324
            return ec;
×
1325
    }
1326

1327
    // TODO: accumulate sigops from each connect result and add coinbase.
1328
    // TODO: return in override with out parameter. more impactful with segwit.
1329
    return error::transaction_success;
2✔
1330
}
1331

1332
// JSON value convertors.
1333
// ----------------------------------------------------------------------------
1334

1335
namespace json = boost::json;
1336

1337
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
1338
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
1339

1340
transaction tag_invoke(json::value_to_tag<transaction>,
2✔
1341
    const json::value& value) NOEXCEPT
1342
{
1343
    return
2✔
1344
    {
1345
        value.at("version").to_number<uint32_t>(),
2✔
1346
        json::value_to<chain::inputs>(value.at("inputs")),
2✔
1347
        json::value_to<chain::outputs>(value.at("outputs")),
4✔
1348
        value.at("locktime").to_number<uint32_t>()
4✔
1349
    };
4✔
1350
}
1351

1352
void tag_invoke(json::value_from_tag, json::value& value,
4✔
1353
    const transaction& tx) NOEXCEPT
1354
{
1355
    value =
4✔
1356
    {
1357
        { "version", tx.version() },
1358
        { "inputs", *tx.inputs_ptr() },
4✔
1359
        { "outputs", *tx.outputs_ptr() },
4✔
1360
        { "locktime", tx.locktime() }
1361
    };
4✔
1362
}
4✔
1363

1364
BC_POP_WARNING()
1365

1366
transaction::cptr tag_invoke(json::value_to_tag<transaction::cptr>,
×
1367
    const json::value& value) NOEXCEPT
1368
{
1369
    return to_shared(tag_invoke(json::value_to_tag<transaction>{}, value));
×
1370
}
1371

1372
// Shared pointer overload is required for navigation.
1373
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
1374
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
1375

1376
void tag_invoke(json::value_from_tag tag, json::value& value,
2✔
1377
    const transaction::cptr& tx) NOEXCEPT
1378
{
1379
    tag_invoke(tag, value, *tx);
2✔
1380
}
2✔
1381

1382
BC_POP_WARNING()
1383
BC_POP_WARNING()
1384

1385
} // namespace chain
1386
} // namespace system
1387
} // 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