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

libbitcoin / libbitcoin-system / 14507858421

17 Apr 2025 04:11AM UTC coverage: 82.822% (+0.007%) from 82.815%
14507858421

push

github

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

Fix inverted NOEXCEPT define (regression), style, comments, whitespace.

7 of 8 new or added lines in 1 file covered. (87.5%)

15 existing lines in 6 files now uncovered.

10183 of 12295 relevant lines covered (82.82%)

3821900.38 hits per line

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

80.5
/src/chain/script.cpp
1
/**
2
 * Copyright (c) 2011-2025 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/script.hpp>
20

21
#include <algorithm>
22
#include <iterator>
23
#include <numeric>
24
#include <sstream>
25
#include <utility>
26
#include <bitcoin/system/chain/enums/coverage.hpp>
27
#include <bitcoin/system/chain/enums/flags.hpp>
28
#include <bitcoin/system/chain/enums/script_pattern.hpp>
29
#include <bitcoin/system/chain/enums/script_version.hpp>
30
#include <bitcoin/system/chain/enums/magic_numbers.hpp>
31
#include <bitcoin/system/chain/enums/opcode.hpp>
32
#include <bitcoin/system/chain/operation.hpp>
33
#include <bitcoin/system/chain/transaction.hpp>
34
#include <bitcoin/system/chain/witness.hpp>
35
#include <bitcoin/system/data/data.hpp>
36
#include <bitcoin/system/define.hpp>
37
#include <bitcoin/system/error/error.hpp>
38
#include <bitcoin/system/hash/hash.hpp>
39
#include <bitcoin/system/machine/machine.hpp>
40
#include <bitcoin/system/radix/radix.hpp>
41
#include <bitcoin/system/stream/stream.hpp>
42

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

47
using namespace bc::system::machine;
48

49
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
50
BC_PUSH_WARNING(NO_ARRAY_INDEXING)
51

52
// static
53
// TODO: would be inlined but machine is a circular include.
54
//*****************************************************************************
55
// CONSENSUS: BIP34 requires coinbase input script to begin with one byte
56
// that indicates height size. This is inconsistent with an extreme future
57
// where the size byte overflows. However satoshi actually requires nominal
58
// encoding.
59
//*************************************************************************
60
bool script::is_coinbase_pattern(const operations& ops, size_t height) NOEXCEPT
×
61
{
UNCOV
62
    return !ops.empty()
×
63
        && ops[0].is_nominal_push()
×
64
        && ops[0].data() == number::chunk::from_integer(to_unsigned(height));
×
65
}
66

67
// Constructors.
68
// ----------------------------------------------------------------------------
69

70
script::script() NOEXCEPT
130✔
71
  : script(operations{}, false, false, zero)
260✔
72
{
73
}
130✔
74

75
script::~script() NOEXCEPT
4,394✔
76
{
77
}
4,394✔
78

79
script::script(script&& other) NOEXCEPT
370✔
80
  : script(std::move(other.ops_), other.valid_, other.prefail_, other.size_)
370✔
81
{
82
}
370✔
83

84
script::script(const script& other) NOEXCEPT
1,474✔
85
  : script(other.ops_, other.valid_, other.prefail_, other.size_)
1,474✔
86
{
87
}
1,474✔
88

89
// Prefail is false.
90
script::script(operations&& ops) NOEXCEPT
225✔
91
  : script(std::move(ops), true, false)
225✔
92
{
93
    // ops moved so cannot pass serialized_size(ops), order not guaranteed.
94
}
225✔
95

96
// Prefail is false.
97
script::script(const operations& ops) NOEXCEPT
1✔
98
  : script(ops, true, false, serialized_size(ops))
1✔
99
{
100
}
1✔
101

102
script::script(operations&& ops, bool prefail) NOEXCEPT
1,498✔
103
  : script(std::move(ops), true, prefail)
1,498✔
104
{
105
    // ops moved so cannot pass serialized_size(ops), order not guaranteed.
106
}
1,498✔
107

108
script::script(const operations& ops, bool prefail) NOEXCEPT
×
109
  : script(ops, true, prefail, serialized_size(ops))
×
110
{
111
}
×
112

113
script::script(stream::in::fast&& stream, bool prefix) NOEXCEPT
133✔
114
  : script(read::bytes::fast(stream), prefix)
133✔
115
{
116
}
133✔
117

118
script::script(stream::in::fast& stream, bool prefix) NOEXCEPT
1✔
119
  : script(read::bytes::fast(stream), prefix)
1✔
120
{
121
}
1✔
122

123
script::script(std::istream&& stream, bool prefix) NOEXCEPT
×
124
  : script(read::bytes::istream(stream), prefix)
×
125
{
126
}
×
127

128
script::script(std::istream& stream, bool prefix) NOEXCEPT
1✔
129
  : script(read::bytes::istream(stream), prefix)
1✔
130
{
131
}
1✔
132

133
script::script(reader&& source, bool prefix) NOEXCEPT
135✔
134
  : script(source, prefix)
135✔
135
{
136
}
×
137

138
script::script(reader& source, bool prefix) NOEXCEPT
696✔
139
  : ops_(source.get_arena())
696✔
140
{
141
    assign_data(source, prefix);
696✔
142
}
696✔
143

144
script::script(const std::string& mnemonic) NOEXCEPT
1,502✔
145
  : script(from_string(mnemonic))
1,502✔
146
{
147
}
1,502✔
148

149
// protected
150
script::script(operations&& ops, bool valid, bool prefail) NOEXCEPT
1,723✔
151
  : ops_(std::move(ops)),
152
    valid_(valid),
1,723✔
153
    prefail_(prefail),
1,723✔
154
    size_(serialized_size(ops_)),
1,723✔
155
    offset(ops_.begin())
1,723✔
156
{
157
}
1,723✔
158

159
// protected
160
script::script(const operations& ops, bool valid, bool prefail) NOEXCEPT
×
161
  : ops_(ops),
×
162
    valid_(valid),
×
163
    prefail_(prefail),
×
164
    size_(serialized_size(ops)),
×
165
    offset(ops_.begin())
×
166
{
167
}
×
168

169
// protected
170
script::script(const operations& ops, bool valid, bool prefail,
1,975✔
171
    size_t size) NOEXCEPT
1,975✔
172
  : ops_(ops),
1,975✔
173
    valid_(valid),
1,975✔
174
    prefail_(prefail),
1,975✔
175
    size_(size),
130✔
176
    offset(ops_.begin())
1,975✔
177
{
178
}
×
179

180
// Operators.
181
// ----------------------------------------------------------------------------
182

183
script& script::operator=(script&& other) NOEXCEPT
4✔
184
{
185
    ops_ = std::move(other.ops_);
4✔
186
    valid_ = other.valid_;
4✔
187
    prefail_ = other.prefail_;
4✔
188
    size_ = other.size_;
4✔
189
    offset = ops_.begin();
4✔
190
    return *this;
4✔
191
}
192

193
script& script::operator=(const script& other) NOEXCEPT
×
194
{
195
    ops_ = other.ops_;
×
196
    valid_ = other.valid_;
×
197
    prefail_ = other.prefail_;
×
198
    size_ = other.size_;
×
199
    offset = ops_.begin();
×
200
    return *this;
×
201
}
202

203
bool script::operator==(const script& other) const NOEXCEPT
87✔
204
{
205
    return size_ == other.size_
87✔
206
        && ops_ == other.ops_;
87✔
207
}
208

209
bool script::operator!=(const script& other) const NOEXCEPT
×
210
{
211
    return !(*this == other);
×
212
}
213

214
// Deserialization.
215
// ----------------------------------------------------------------------------
216

217
// static/private
218
size_t script::op_count(reader& source) NOEXCEPT
696✔
219
{
220
    // Stream errors reset by set_position so trap here.
221
    if (!source)
696✔
222
        return zero;
223

224
    const auto start = source.get_read_position();
696✔
225
    auto count = zero;
696✔
226

227
    // This is expensive (1.1%) but far less than vector reallocs (11.6%).
228
    while (operation::count_op(source))
84,083✔
229
        ++count;
82,691✔
230

231
    source.set_position(start);
696✔
232
    return count;
696✔
233
}
234

235
// private
236
void script::assign_data(reader& source, bool prefix) NOEXCEPT
696✔
237
{
238
    size_t expected{};
696✔
239
    prefail_ = false;
696✔
240

241
    if (prefix)
696✔
242
    {
243
        expected = source.read_size();
567✔
244
        source.set_limit(expected);
567✔
245
    }
246

247
    ops_.reserve(op_count(source));
696✔
248
    const auto start = source.get_read_position();
696✔
249

250
    while (!source.is_exhausted())
84,083✔
251
    {
252
        ops_.emplace_back(source);
82,691✔
253
        prefail_ |= ops_.back().is_invalid();
82,691✔
254
    }
255

256
    size_ = source.get_read_position() - start;
696✔
257

258
    if (prefix)
696✔
259
    {
260
        source.set_limit();
567✔
261
        if (size_ != expected)
567✔
262
            source.invalidate();
2✔
263
    }
264

265
    valid_ = source;
696✔
266
    offset = ops_.begin();
696✔
267
}
696✔
268

269
// static/private
270
script script::from_string(const std::string& mnemonic) NOEXCEPT
1,502✔
271
{
272
    // There is always one operation per non-empty string token.
273
    auto tokens = split(mnemonic);
1,502✔
274
    auto prefail = false;
1,502✔
275

276
    // Split always returns at least one token, and when trimming it will be
277
    // empty only if there was nothing but whitespace in the mnemonic.
278
    if (tokens.front().empty())
1,502✔
279
        tokens.clear();
66✔
280

281
    operations ops{};
1,502✔
282
    ops.reserve(tokens.size());
1,502✔
283

284
    // Create an op list from the split tokens.
285
    for (const auto& token: tokens)
12,200✔
286
    {
287
        ops.emplace_back(token);
10,702✔
288
        prefail |= ops.back().is_invalid();
10,702✔
289

290
        // This is a deserialization failure, not just an invalid code.
291
        if (!ops.back().is_valid())
10,702✔
292
            return {};
4✔
293
    }
294

295
    return { std::move(ops), prefail };
1,498✔
296
}
1,502✔
297

298
// Serialization.
299
// ----------------------------------------------------------------------------
300

301
data_chunk script::to_data(bool prefix) const NOEXCEPT
165✔
302
{
303
    data_chunk data(serialized_size(prefix));
165✔
304
    stream::out::fast ostream(data);
165✔
305
    write::bytes::fast out(ostream);
165✔
306
    to_data(out, prefix);
165✔
307
    return data;
330✔
308
}
165✔
309

310
void script::to_data(std::ostream& stream, bool prefix) const NOEXCEPT
×
311
{
312
    write::bytes::ostream out(stream);
×
313
    to_data(out, prefix);
×
314
}
×
315

316
// see also: subscript.to_data().
317
void script::to_data(writer& sink, bool prefix) const NOEXCEPT
3,327✔
318
{
319
    if (prefix)
3,327✔
320
        sink.write_variable(serialized_size(false));
3,145✔
321

322
    // Data serialization is affected by offset metadata.
323
    for (iterator op{ offset }; op != ops().end(); ++op)
1,494,744✔
324
        op->to_data(sink);
1,491,417✔
325
}
3,327✔
326

327
std::string script::to_string(uint32_t active_flags) const NOEXCEPT
28✔
328
{
329
    auto first = true;
28✔
330
    std::ostringstream text;
28✔
331

332
    // Throwing stream aborts.
333
    for (const auto& op: ops())
82✔
334
    {
335
        text << (first ? "" : " ") << op.to_string(active_flags);
80✔
336
        first = false;
54✔
337
    }
338

339
    // An invalid operation has a specialized serialization.
340
    return text.str();
28✔
341
}
28✔
342

343

344
// Properties.
345
// ----------------------------------------------------------------------------
346

347
bool script::is_valid() const NOEXCEPT
1,513✔
348
{
349
    // Any byte vector is a valid script.
350
    // This is false only if the byte count did not match the size prefix.
351
    return valid_;
1,513✔
352
}
353

354
bool script::is_prefail() const NOEXCEPT
3,095✔
355
{
356
    // The script contains an invalid opcode and will thus fail evaluation.
357
    return prefail_;
3,095✔
358
}
359

360
const operations& script::ops() const NOEXCEPT
31,342✔
361
{
362
    return ops_;
31,342✔
363
}
364

365
bool script::is_roller() const NOEXCEPT
8✔
366
{
367
    static const auto roll = operation{ opcode::roll };
8✔
368

369
    // Naive implementation, any op_roll in script, late-counted.
370
    // TODO: precompute on script parse, tune using performance profiling.
371
    return contains(ops_, roll);
8✔
372
};
373

374
// Consensus (witness::extract_script) and Electrum server payments key.
375
hash_digest script::hash() const NOEXCEPT
18✔
376
{
377
    hash_digest sha256{};
18✔
378
    hash::sha256::copy sink(sha256);
18✔
379
    to_data(sink, false);
18✔
380
    sink.flush();
18✔
381
    return sha256;
36✔
382
}
18✔
383

384
// static/private
385
size_t script::serialized_size(const operations& ops) NOEXCEPT
1,724✔
386
{
387
    return std::accumulate(ops.begin(), ops.end(), zero, op_size);
1,724✔
388
}
389

390
size_t script::serialized_size(bool prefix) const NOEXCEPT
8,789✔
391
{
392
    // Recompute it serialization has been affected by offset metadata.
393
    const auto size = (offset == ops_.begin()) ? size_ :
8,789✔
394
        std::accumulate(offset, ops_.end(), zero, op_size);
8✔
395

396
    return prefix ? ceilinged_add(size, variable_size(size)) : size;
8,789✔
397
}
398

399
// Utilities.
400
// ----------------------------------------------------------------------------
401

402
const data_chunk& script::witness_program() const NOEXCEPT
24✔
403
{
404
    static const data_chunk empty{};
24✔
405
    return is_witness_program_pattern(ops()) ? ops()[1].data() : empty;
24✔
406
}
407

408
script_version script::version() const NOEXCEPT
48✔
409
{
410
    if (!is_witness_program_pattern(ops()))
48✔
411
        return script_version::unversioned;
412

413
    switch (ops_.front().code())
48✔
414
    {
415
        case opcode::push_size_0:
416
            return script_version::zero;
417
        default:
×
418
            return script_version::reserved;
×
419
    }
420
}
421

422
// Caller should test for is_sign_script_hash_pattern when sign_key_hash result
423
// as it is possible for an input script to match both patterns.
424
script_pattern script::pattern() const NOEXCEPT
11✔
425
{
426
    const auto input = output_pattern();
11✔
427
    return input == script_pattern::non_standard ? input_pattern() : input;
11✔
428
}
429

430
// Output patterns are mutually and input unambiguous.
431
// The bip141 coinbase pattern is not tested here, must test independently.
432
script_pattern script::output_pattern() const NOEXCEPT
22✔
433
{
434
    if (is_pay_key_hash_pattern(ops()))
22✔
435
        return script_pattern::pay_key_hash;
436

437
    if (is_pay_script_hash_pattern(ops()))
22✔
438
        return script_pattern::pay_script_hash;
439

440
    if (is_pay_null_data_pattern(ops()))
22✔
441
        return script_pattern::pay_null_data;
442

443
    if (is_pay_public_key_pattern(ops()))
18✔
444
        return script_pattern::pay_public_key;
445

446
    // Limited to 16 signatures though op_check_multisig allows 20.
447
    if (is_pay_multisig_pattern(ops()))
18✔
448
        return script_pattern::pay_multisig;
8✔
449

450
    return script_pattern::non_standard;
451
}
452

453
// A sign_key_hash result always implies sign_script_hash as well.
454
// The bip34 coinbase pattern is not tested here, must test independently.
455
script_pattern script::input_pattern() const NOEXCEPT
16✔
456
{
457
    if (is_sign_key_hash_pattern(ops()))
16✔
458
        return script_pattern::sign_key_hash;
459

460
    // This must follow is_sign_key_hash_pattern for ambiguity comment to hold.
461
    if (is_sign_script_hash_pattern(ops()))
16✔
462
        return script_pattern::sign_script_hash;
463

464
    if (is_sign_public_key_pattern(ops()))
16✔
465
        return script_pattern::sign_public_key;
466

467
    if (is_sign_multisig_pattern(ops()))
16✔
468
        return script_pattern::sign_multisig;
×
469

470
    return script_pattern::non_standard;
471
}
472

473
bool script::is_pay_to_witness(uint32_t active_flags) const NOEXCEPT
961✔
474
{
475
    // This is an optimization over using script::pattern.
476
    return is_enabled(active_flags, flags::bip141_rule) &&
1,419✔
477
        is_witness_program_pattern(ops());
458✔
478
}
479

480
bool script::is_pay_to_script_hash(uint32_t active_flags) const NOEXCEPT
969✔
481
{
482
    // This is an optimization over using script::pattern.
483
    return is_enabled(active_flags, flags::bip16_rule) &&
1,424✔
484
        is_pay_script_hash_pattern(ops());
455✔
485
}
486

487
// Count 1..16 multisig accurately for embedded (bip16) and witness (bip141).
488
constexpr size_t multisig_sigops(bool accurate, opcode code) NOEXCEPT
×
489
{
490
    return accurate && operation::is_positive(code) ?
×
491
        operation::opcode_to_positive(code) : multisig_default_sigops;
×
492
}
493

494
constexpr bool is_single_sigop(opcode code) NOEXCEPT
24✔
495
{
496
    return code == opcode::checksig || code == opcode::checksigverify;
24✔
497
}
498

499
constexpr bool is_multiple_sigop(opcode code) NOEXCEPT
×
500
{
501
    return code == opcode::checkmultisig || code == opcode::checkmultisigverify;
×
502
}
503

504
// TODO: compute in or at script evaluation and add coinbase input scripts.
505
// TODO: this precludes second deserialization of script for sigop counting.
506
size_t script::signature_operations(bool accurate) const NOEXCEPT
12✔
507
{
508
    auto total = zero;
12✔
509
    auto preceding = opcode::push_negative_1;
12✔
510

511
    for (const auto& op: ops())
36✔
512
    {
513
        const auto code = op.code();
24✔
514

515
        if (is_single_sigop(code))
24✔
516
            total = ceilinged_add(total, one);
24✔
517
        else if (is_multiple_sigop(code))
×
518
            total = ceilinged_add(total, multisig_sigops(accurate, preceding));
×
519

520
        preceding = code;
24✔
521
    }
522

523
    return total;
12✔
524
}
525

526
bool script::is_oversized() const NOEXCEPT
3,035✔
527
{
528
    return serialized_size(false) > max_script_size;
3,035✔
529
}
530

531
// An unspendable script is any that can provably not be spent under any
532
// circumstance. This allows for exclusion of the output as unspendable.
533
// The criteria below are not comprehensive but are fast to evaluate.
534
bool script::is_unspendable() const NOEXCEPT
3✔
535
{
536
    if (ops_.empty())
3✔
537
        return false;
538

539
    const auto& code = ops_.front().code();
3✔
540

541
    // There is no condition prior to the first opcode in a script, so
542
    // is_reserved must be checked. is_invalid short-circuits evaluation for
543
    // scripts that fail to parse, but would otherwise be caught in evaluation.
544
    return operation::is_reserved(code) || operation::is_invalid(code);
3✔
545
}
546

547
BC_POP_WARNING()
548
BC_POP_WARNING()
549

550
// JSON value convertors.
551
// ----------------------------------------------------------------------------
552

553
namespace json = boost::json;
554

555
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
556
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
557

558
script tag_invoke(json::value_to_tag<script>,
11✔
559
    const json::value& value) NOEXCEPT
560
{
561
    return script{ std::string(value.get_string().c_str()) };
11✔
562
}
563

564
void tag_invoke(json::value_from_tag, json::value& value,
22✔
565
    const script& script) NOEXCEPT
566
{
567
    value = script.to_string(flags::all_rules);
22✔
568
}
22✔
569

570
BC_POP_WARNING()
571

572
script::cptr tag_invoke(json::value_to_tag<script::cptr>,
×
573
    const json::value& value) NOEXCEPT
574
{
575
    return to_shared(tag_invoke(json::value_to_tag<script>{}, value));
×
576
}
577

578
// Shared pointer overload is required for navigation.
579
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
580
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
581

582
void tag_invoke(json::value_from_tag tag, json::value& value,
×
583
    const script::cptr& script) NOEXCEPT
584
{
585
    tag_invoke(tag, value, *script);
×
586
}
×
587

588
BC_POP_WARNING()
589
BC_POP_WARNING()
590

591
} // namespace chain
592
} // namespace system
593
} // 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

© 2026 Coveralls, Inc