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

libbitcoin / libbitcoin-system / 9310800761

31 May 2024 12:08AM UTC coverage: 82.732% (-0.01%) from 82.746%
9310800761

push

github

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

Performance optimizations, style, comments.

233 of 289 new or added lines in 11 files covered. (80.62%)

8 existing lines in 4 files now uncovered.

9812 of 11860 relevant lines covered (82.73%)

4808594.09 hits per line

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

83.88
/src/chain/script.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/script.hpp>
20

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

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

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

50
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
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
//*************************************************************************
UNCOV
60
bool script::is_coinbase_pattern(const operations& ops, size_t height) NOEXCEPT
×
61
{
62
    BC_PUSH_WARNING(NO_ARRAY_INDEXING)
63
    return !ops.empty()
×
64
        && ops[0].is_nominal_push()
×
65
        && ops[0].data() == number::chunk::from_integer(to_unsigned(height));
×
66
    BC_POP_WARNING()
67
}
68

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

72
script::script() NOEXCEPT
116✔
73
  : script(operations{}, false, false, zero)
116✔
74
{
75
}
116✔
76

77
script::~script() NOEXCEPT
4,474✔
78
{
79
}
4,474✔
80

81
script::script(script&& other) NOEXCEPT
190✔
82
  : script(std::move(other.ops_), other.valid_, other.prefail_, other.size_)
190✔
83
{
84
}
190✔
85

86
script::script(const script& other) NOEXCEPT
1,470✔
87
  : script(other.ops_, other.valid_, other.prefail_, other.size_)
1,470✔
88
{
89
}
1,470✔
90

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

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

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

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

115
script::script(const data_slice& data, bool prefix) NOEXCEPT
133✔
116
  : script(stream::in::copy(data), prefix)
133✔
117
{
118
}
133✔
119

120
////script::script(stream::in::fast&& stream, bool prefix) NOEXCEPT
121
////  : script(read::bytes::fast(stream), prefix)
122
////{
123
////}
124

125
script::script(stream::in::fast& stream, bool prefix) NOEXCEPT
1✔
126
  : script(read::bytes::fast(stream), prefix)
1✔
127
{
128
}
1✔
129

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

135
script::script(std::istream& stream, bool prefix) NOEXCEPT
1✔
136
  : script(read::bytes::istream(stream), prefix)
1✔
137
{
138
}
1✔
139

140
script::script(reader&& source, bool prefix) NOEXCEPT
135✔
141
  : script(from_data(source, prefix))
135✔
142
{
143
}
135✔
144

145
script::script(reader& source, bool prefix) NOEXCEPT
483✔
146
  : script(from_data(source, prefix))
483✔
147
{
148
}
483✔
149

150
script::script(const std::string& mnemonic) NOEXCEPT
1,498✔
151
  : script(from_string(mnemonic))
1,498✔
152
{
153
}
1,498✔
154

155
// protected
156
script::script(operations&& ops, bool valid, bool prefail) NOEXCEPT
1,553✔
157
  : ops_(std::move(ops)),
1,553✔
158
    valid_(valid),
1,553✔
159
    prefail_(prefail),
1,553✔
160
    size_(serialized_size(ops_)),
1,553✔
161
    offset(ops_.begin())
1,553✔
162
{
163
}
1,553✔
164

165
// protected
166
script::script(const operations& ops, bool valid, bool prefail) NOEXCEPT
×
167
  : ops_(ops),
×
168
    valid_(valid),
×
169
    prefail_(prefail),
×
170
    size_(serialized_size(ops_)),
×
171
    offset(ops_.begin())
×
172
{
173
}
×
174

175
// protected
176
script::script(const operations& ops, bool valid, bool prefail,
2,395✔
177
    size_t size) NOEXCEPT
1,777✔
178
  : ops_(ops),
2,395✔
179
    valid_(valid),
2,395✔
180
    prefail_(prefail),
2,395✔
181
    size_(size),
734✔
182
    offset(ops_.begin())
2,395✔
183
{
184
}
×
185

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

189
script& script::operator=(script&& other) NOEXCEPT
4✔
190
{
191
    ops_ = std::move(other.ops_);
4✔
192
    valid_ = other.valid_;
4✔
193
    prefail_ = other.prefail_;
4✔
194
    size_ = other.size_;
4✔
195
    offset = ops_.begin();
4✔
196
    return *this;
4✔
197
}
198

199
script& script::operator=(const script& other) NOEXCEPT
×
200
{
201
    ops_ = other.ops_;
×
202
    valid_ = other.valid_;
×
203
    prefail_ = other.prefail_;
×
204
    size_ = other.size_;
×
205
    offset = ops_.begin();
×
206
    return *this;
×
207
}
208

209
bool script::operator==(const script& other) const NOEXCEPT
63✔
210
{
211
    return size_ == other.size_
63✔
212
        && ops_ == other.ops_;
63✔
213
}
214

215
bool script::operator!=(const script& other) const NOEXCEPT
×
216
{
217
    return !(*this == other);
×
218
}
219

220
// Deserialization.
221
// ----------------------------------------------------------------------------
222

223
// static/private
224
size_t script::op_count(reader& source) NOEXCEPT
618✔
225
{
226
    // Stream errors reset by set_position so trap here.
227
    if (!source)
618✔
228
        return zero;
229

230
    const auto start = source.get_read_position();
618✔
231
    auto count = zero;
618✔
232

233
    // This is expensive (1.1%) but far less than vector reallocs (11.6%).
234
    while (operation::count_op(source))
83,750✔
235
        ++count;
82,514✔
236

237
    source.set_position(start);
618✔
238
    return count;
618✔
239
}
240

241
// static/private
242
script script::from_data(reader& source, bool prefix) NOEXCEPT
618✔
243
{
244
    auto expected = zero;
618✔
245
    auto prefail = false;
618✔
246

247
    if (prefix)
618✔
248
    {
249
        expected = source.read_size();
489✔
250
        source.set_limit(expected);
489✔
251
    }
252

253
    operations ops;
618✔
254
    ops.reserve(op_count(source));
618✔
255
    const auto start = source.get_read_position();
618✔
256

257
    while (!source.is_exhausted())
83,750✔
258
    {
259
        ops.emplace_back(source);
82,514✔
260
        prefail |= ops.back().is_invalid();
82,514✔
261
    }
262

263
    const auto size = source.get_read_position() - start;
618✔
264

265
    if (prefix)
618✔
266
    {
267
        source.set_limit();
489✔
268
        if (size != expected)
489✔
269
            source.invalidate();
2✔
270
    }
271

272
    return { std::move(ops), source, prefail, size };
618✔
273
}
618✔
274

275
// static/private
276
script script::from_string(const std::string& mnemonic) NOEXCEPT
1,498✔
277
{
278
    // There is always one operation per non-empty string token.
279
    auto tokens = split(mnemonic);
1,498✔
280
    auto prefail = false;
1,498✔
281

282
    // Split always returns at least one token, and when trimming it will be
283
    // empty only if there was nothing but whitespace in the mnemonic.
284
    if (tokens.front().empty())
1,498✔
285
        tokens.clear();
65✔
286

287
    operations ops;
1,498✔
288
    ops.reserve(tokens.size());
1,498✔
289

290
    // Create an op list from the split tokens.
291
    for (const auto& token: tokens)
12,187✔
292
    {
293
        ops.emplace_back(token);
10,693✔
294
        prefail |= ops.back().is_invalid();
10,693✔
295

296
        // This is a deserialization failure, not just an invalid code.
297
        if (!ops.back().is_valid())
10,693✔
298
            return {};
4✔
299
    }
300

301
    return { std::move(ops), prefail };
1,494✔
302
}
1,498✔
303

304
// Serialization.
305
// ----------------------------------------------------------------------------
306

307
data_chunk script::to_data(bool prefix) const NOEXCEPT
165✔
308
{
309
    data_chunk data(serialized_size(prefix));
165✔
310
    stream::out::copy ostream(data);
165✔
311
    to_data(ostream, prefix);
165✔
312
    return data;
330✔
313
}
165✔
314

315
void script::to_data(std::ostream& stream, bool prefix) const NOEXCEPT
165✔
316
{
317
    write::bytes::ostream out(stream);
165✔
318
    to_data(out, prefix);
165✔
319
}
165✔
320

321
// see also: subscript.to_data().
322
void script::to_data(writer& sink, bool prefix) const NOEXCEPT
3,316✔
323
{
324
    if (prefix)
3,316✔
325
        sink.write_variable(serialized_size(false));
3,134✔
326

327
    // Data serialization is affected by offset metadata.
328
    for (iterator op{ offset }; op != ops().end(); ++op)
1,494,711✔
329
        op->to_data(sink);
1,491,395✔
330
}
3,316✔
331

332
std::string script::to_string(uint32_t active_flags) const NOEXCEPT
28✔
333
{
334
    auto first = true;
28✔
335
    std::ostringstream text;
28✔
336

337
    // Throwing stream aborts.
338
    for (const auto& op: ops())
82✔
339
    {
340
        text << (first ? "" : " ") << op.to_string(active_flags);
80✔
341
        first = false;
54✔
342
    }
343

344
    // An invalid operation has a specialized serialization.
345
    return text.str();
28✔
346
}
28✔
347

348

349
// Properties.
350
// ----------------------------------------------------------------------------
351

352
bool script::is_valid() const NOEXCEPT
1,509✔
353
{
354
    // Any byte vector is a valid script.
355
    // This is false only if the byte count did not match the size prefix.
356
    return valid_;
1,509✔
357
}
358

359
bool script::is_prefail() const NOEXCEPT
3,087✔
360
{
361
    // The script contains an invalid opcode and will thus fail evaluation.
362
    return prefail_;
3,087✔
363
}
364

365
const operations& script::ops() const NOEXCEPT
31,304✔
366
{
367
    return ops_;
31,304✔
368
}
369

370
bool script::is_roller() const NOEXCEPT
8✔
371
{
372
    static const auto roll = operation{ opcode::roll };
8✔
373

374
    // Naive implementation, any op_roll in script, late-counted.
375
    // TODO: precompute on script parse, tune using performance profiling.
376
    return contains(ops_, roll);
8✔
377
};
378

379
// Consensus (witness::extract_script) and Electrum server payments key.
380
hash_digest script::hash() const NOEXCEPT
18✔
381
{
382
    hash_digest sha256{};
18✔
383
    hash::sha256::copy sink(sha256);
18✔
384
    to_data(sink, false);
18✔
385
    sink.flush();
18✔
386
    return sha256;
36✔
387
}
18✔
388

389
// static/private
390
size_t script::serialized_size(const operations& ops) NOEXCEPT
1,554✔
391
{
392
    return std::accumulate(ops.begin(), ops.end(), zero, op_size);
1,554✔
393
}
394

395
size_t script::serialized_size(bool prefix) const NOEXCEPT
6,501✔
396
{
397
    // Recompute it serialization has been affected by offset metadata.
398
    auto size = (offset == ops_.begin()) ? size_ :
6,501✔
399
        std::accumulate(offset, ops_.end(), zero, op_size);
8✔
400

401
    if (prefix)
6,501✔
402
        size += variable_size(size);
168✔
403

404
    return size;
6,501✔
405
}
406

407
// Utilities.
408
// ----------------------------------------------------------------------------
409

410
const data_chunk& script::witness_program() const NOEXCEPT
24✔
411
{
412
    static const data_chunk empty{};
24✔
413

414
    BC_PUSH_WARNING(NO_ARRAY_INDEXING)
415
    return is_witness_program_pattern(ops()) ? ops()[1].data() : empty;
24✔
416
    BC_POP_WARNING()
417
}
418

419
script_version script::version() const NOEXCEPT
48✔
420
{
421
    if (!is_witness_program_pattern(ops()))
48✔
422
        return script_version::unversioned;
423

424
    switch (ops_.front().code())
48✔
425
    {
426
        case opcode::push_size_0:
427
            return script_version::zero;
428
        default:
×
429
            return script_version::reserved;
×
430
    }
431
}
432

433
// Caller should test for is_sign_script_hash_pattern when sign_key_hash result
434
// as it is possible for an input script to match both patterns.
435
script_pattern script::pattern() const NOEXCEPT
11✔
436
{
437
    const auto input = output_pattern();
11✔
438
    return input == script_pattern::non_standard ? input_pattern() : input;
11✔
439
}
440

441
// Output patterns are mutually and input unambiguous.
442
// The bip141 coinbase pattern is not tested here, must test independently.
443
script_pattern script::output_pattern() const NOEXCEPT
22✔
444
{
445
    if (is_pay_key_hash_pattern(ops()))
22✔
446
        return script_pattern::pay_key_hash;
447

448
    if (is_pay_script_hash_pattern(ops()))
22✔
449
        return script_pattern::pay_script_hash;
450

451
    if (is_pay_null_data_pattern(ops()))
22✔
452
        return script_pattern::pay_null_data;
453

454
    if (is_pay_public_key_pattern(ops()))
18✔
455
        return script_pattern::pay_public_key;
456

457
    // Limited to 16 signatures though op_check_multisig allows 20.
458
    if (is_pay_multisig_pattern(ops()))
18✔
459
        return script_pattern::pay_multisig;
8✔
460

461
    return script_pattern::non_standard;
462
}
463

464
// A sign_key_hash result always implies sign_script_hash as well.
465
// The bip34 coinbase pattern is not tested here, must test independently.
466
script_pattern script::input_pattern() const NOEXCEPT
16✔
467
{
468
    if (is_sign_key_hash_pattern(ops()))
16✔
469
        return script_pattern::sign_key_hash;
470

471
    // This must follow is_sign_key_hash_pattern for ambiguity comment to hold.
472
    if (is_sign_script_hash_pattern(ops()))
16✔
473
        return script_pattern::sign_script_hash;
474

475
    if (is_sign_public_key_pattern(ops()))
16✔
476
        return script_pattern::sign_public_key;
477

478
    if (is_sign_multisig_pattern(ops()))
16✔
479
        return script_pattern::sign_multisig;
×
480

481
    return script_pattern::non_standard;
482
}
483

484
bool script::is_pay_to_witness(uint32_t active_flags) const NOEXCEPT
957✔
485
{
486
    // This is an optimization over using script::pattern.
487
    return is_enabled(active_flags, flags::bip141_rule) &&
1,413✔
488
        is_witness_program_pattern(ops());
456✔
489
}
490

491
bool script::is_pay_to_script_hash(uint32_t active_flags) const NOEXCEPT
965✔
492
{
493
    // This is an optimization over using script::pattern.
494
    return is_enabled(active_flags, flags::bip16_rule) &&
1,418✔
495
        is_pay_script_hash_pattern(ops());
453✔
496
}
497

498
// Count 1..16 multisig accurately for embedded (bip16) and witness (bip141).
499
constexpr size_t multisig_sigops(bool accurate, opcode code) NOEXCEPT
×
500
{
501
    return accurate && operation::is_positive(code) ?
×
502
        operation::opcode_to_positive(code) : multisig_default_sigops;
×
503
}
504

505
constexpr bool is_single_sigop(opcode code) NOEXCEPT
24✔
506
{
507
    return code == opcode::checksig || code == opcode::checksigverify;
24✔
508
}
509

510
constexpr bool is_multiple_sigop(opcode code) NOEXCEPT
×
511
{
512
    return code == opcode::checkmultisig || code == opcode::checkmultisigverify;
×
513
}
514

515
// TODO: compute in or at script evaluation and add coinbase input scripts.
516
// TODO: this precludes second deserialization of script for sigop counting.
517
size_t script::signature_operations(bool accurate) const NOEXCEPT
12✔
518
{
519
    auto total = zero;
12✔
520
    auto preceding = opcode::push_negative_1;
12✔
521

522
    for (const auto& op: ops())
36✔
523
    {
524
        const auto code = op.code();
24✔
525

526
        if (is_single_sigop(code))
24✔
527
            total = ceilinged_add(total, one);
24✔
528
        else if (is_multiple_sigop(code))
×
529
            total = ceilinged_add(total, multisig_sigops(accurate, preceding));
×
530

531
        preceding = code;
24✔
532
    }
533

534
    return total;
12✔
535
}
536

537
bool script::is_oversized() const NOEXCEPT
3,027✔
538
{
539
    return serialized_size(false) > max_script_size;
3,027✔
540
}
541

542
// An unspendable script is any that can provably not be spent under any
543
// circumstance. This allows for exclusion of the output as unspendable.
544
// The criteria below are not comprehensive but are fast to evaluate.
545
bool script::is_unspendable() const NOEXCEPT
3✔
546
{
547
    if (ops_.empty())
3✔
548
        return false;
549

550
    const auto& code = ops_.front().code();
3✔
551

552
    // There is no condition prior to the first opcode in a script, so
553
    // is_reserved must be checked. is_invalid short-circuits evaluation for
554
    // scripts that fail to parse, but would otherwise be caught in evaluation.
555
    return operation::is_reserved(code) || operation::is_invalid(code);
3✔
556
}
557

558
BC_POP_WARNING()
559

560
// JSON value convertors.
561
// ----------------------------------------------------------------------------
562

563
namespace json = boost::json;
564

565
// boost/json will soon have NOEXCEPT: github.com/boostorg/json/pull/636
566
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
567

568
script tag_invoke(json::value_to_tag<script>,
11✔
569
    const json::value& value) NOEXCEPT
570
{
571
    return script{ std::string(value.get_string().c_str()) };
11✔
572
}
573

574
void tag_invoke(json::value_from_tag, json::value& value,
22✔
575
    const script& script) NOEXCEPT
576
{
577
    value = script.to_string(flags::all_rules);
22✔
578
}
22✔
579

580
BC_POP_WARNING()
581

582
script::cptr tag_invoke(json::value_to_tag<script::cptr>,
×
583
    const json::value& value) NOEXCEPT
584
{
585
    return to_shared(tag_invoke(json::value_to_tag<script>{}, value));
×
586
}
587

588
// Shared pointer overload is required for navigation.
589
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
590
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
591

592
void tag_invoke(json::value_from_tag tag, json::value& value,
×
593
    const script::cptr& script) NOEXCEPT
594
{
595
    tag_invoke(tag, value, *script);
×
596
}
×
597

598
BC_POP_WARNING()
599
BC_POP_WARNING()
600

601
} // namespace chain
602
} // namespace system
603
} // 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