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

libbitcoin / libbitcoin-system / 14372307207

10 Apr 2025 04:26AM UTC coverage: 82.893% (-0.02%) from 82.917%
14372307207

push

github

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

Optimize siphash and chain to_data() stream readers.

32 of 35 new or added lines in 11 files covered. (91.43%)

4 existing lines in 1 file now uncovered.

10166 of 12264 relevant lines covered (82.89%)

3831090.94 hits per line

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

81.74
/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

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

68
// Constructors.
69
// ----------------------------------------------------------------------------
70

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

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

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

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

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

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

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

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

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

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

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

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

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

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

144
script::script(reader& source, bool prefix) NOEXCEPT
696✔
145
  : ops_(source.get_arena())
696✔
146
{
147
    assign_data(source, prefix);
696✔
148
}
696✔
149

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

155
// protected
156
script::script(operations&& ops, bool valid, bool prefail) NOEXCEPT
1,723✔
157
  : ops_(std::move(ops)),
158
    valid_(valid),
1,723✔
159
    prefail_(prefail),
1,723✔
160
    size_(serialized_size(ops_)),
1,723✔
161
    offset(ops_.begin())
1,723✔
162
{
163
}
1,723✔
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,
1,975✔
177
    size_t size) NOEXCEPT
1,975✔
178
  : ops_(ops),
1,975✔
179
    valid_(valid),
1,975✔
180
    prefail_(prefail),
1,975✔
181
    size_(size),
130✔
182
    offset(ops_.begin())
1,975✔
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
87✔
210
{
211
    return size_ == other.size_
87✔
212
        && ops_ == other.ops_;
87✔
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
696✔
225
{
226
    // Stream errors reset by set_position so trap here.
227
    if (!source)
696✔
228
        return zero;
229

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

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

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

241
// private
242
void script::assign_data(reader& source, bool prefix) NOEXCEPT
696✔
243
{
244
    size_t expected{};
696✔
245
    prefail_ = false;
696✔
246

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

253
    ops_.reserve(op_count(source));
696✔
254
    const auto start = source.get_read_position();
696✔
255

256
    while (!source.is_exhausted())
84,083✔
257
    {
258
        ops_.emplace_back(source);
82,691✔
259
        prefail_ |= ops_.back().is_invalid();
82,691✔
260
    }
261

262
    size_ = source.get_read_position() - start;
696✔
263

264
    if (prefix)
696✔
265
    {
266
        source.set_limit();
567✔
267
        if (size_ != expected)
567✔
268
            source.invalidate();
2✔
269
    }
270

271
    valid_ = source;
696✔
272
    offset = ops_.begin();
696✔
273
}
696✔
274

275
// static/private
276
script script::from_string(const std::string& mnemonic) NOEXCEPT
1,502✔
277
{
278
    // There is always one operation per non-empty string token.
279
    auto tokens = split(mnemonic);
1,502✔
280
    auto prefail = false;
1,502✔
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,502✔
285
        tokens.clear();
66✔
286

287
    operations ops{};
1,502✔
288
    ops.reserve(tokens.size());
1,502✔
289

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

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

301
    return { std::move(ops), prefail };
1,498✔
302
}
1,502✔
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::fast ostream(data);
165✔
311
    write::bytes::fast out(ostream);
165✔
312
    to_data(out, prefix);
165✔
313
    return data;
165✔
314
}
165✔
315

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

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

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

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

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

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

349

350
// Properties.
351
// ----------------------------------------------------------------------------
352

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

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

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

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

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

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

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

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

402
    return prefix ? ceilinged_add(size, variable_size(size)) : size;
8,789✔
403
}
404

405
// Utilities.
406
// ----------------------------------------------------------------------------
407

408
const data_chunk& script::witness_program() const NOEXCEPT
24✔
409
{
410
    static const data_chunk empty{};
25✔
411

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

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

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

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

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

446
    if (is_pay_script_hash_pattern(ops()))
22✔
447
        return script_pattern::pay_script_hash;
448

449
    if (is_pay_null_data_pattern(ops()))
22✔
450
        return script_pattern::pay_null_data;
451

452
    if (is_pay_public_key_pattern(ops()))
18✔
453
        return script_pattern::pay_public_key;
454

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

459
    return script_pattern::non_standard;
460
}
461

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

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

473
    if (is_sign_public_key_pattern(ops()))
16✔
474
        return script_pattern::sign_public_key;
475

476
    if (is_sign_multisig_pattern(ops()))
16✔
477
        return script_pattern::sign_multisig;
×
478

479
    return script_pattern::non_standard;
480
}
481

482
bool script::is_pay_to_witness(uint32_t active_flags) const NOEXCEPT
961✔
483
{
484
    // This is an optimization over using script::pattern.
485
    return is_enabled(active_flags, flags::bip141_rule) &&
1,419✔
486
        is_witness_program_pattern(ops());
458✔
487
}
488

489
bool script::is_pay_to_script_hash(uint32_t active_flags) const NOEXCEPT
969✔
490
{
491
    // This is an optimization over using script::pattern.
492
    return is_enabled(active_flags, flags::bip16_rule) &&
1,424✔
493
        is_pay_script_hash_pattern(ops());
455✔
494
}
495

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

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

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

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

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

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

529
        preceding = code;
24✔
530
    }
531

532
    return total;
12✔
533
}
534

535
bool script::is_oversized() const NOEXCEPT
3,035✔
536
{
537
    return serialized_size(false) > max_script_size;
3,035✔
538
}
539

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

548
    const auto& code = ops_.front().code();
3✔
549

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

556
BC_POP_WARNING()
557

558
// JSON value convertors.
559
// ----------------------------------------------------------------------------
560

561
namespace json = boost::json;
562

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

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

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

578
BC_POP_WARNING()
579

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

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

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

596
BC_POP_WARNING()
597
BC_POP_WARNING()
598

599
} // namespace chain
600
} // namespace system
601
} // 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