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

libbitcoin / libbitcoin-system / 9324917697

31 May 2024 10:10PM UTC coverage: 82.819% (+0.09%) from 82.732%
9324917697

Pull #1469

github

web-flow
Merge 0155ccfba into 434772ab9
Pull Request #1469: Optimize size computations, use ceilinged_add, style.

71 of 85 new or added lines in 7 files covered. (83.53%)

7 existing lines in 2 files now uncovered.

9848 of 11891 relevant lines covered (82.82%)

4796079.56 hits per line

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

83.75
/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
//*************************************************************************
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),
×
NEW
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
8,505✔
396
{
397
    // Recompute it serialization has been affected by offset metadata.
398
    const auto size = (offset == ops_.begin()) ? size_ :
8,505✔
399
        std::accumulate(offset, ops_.end(), zero, op_size);
8✔
400

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

404
// Utilities.
405
// ----------------------------------------------------------------------------
406

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

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

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

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

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

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

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

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

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

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

458
    return script_pattern::non_standard;
459
}
460

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

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

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

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

478
    return script_pattern::non_standard;
479
}
480

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

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

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

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

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

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

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

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

528
        preceding = code;
24✔
529
    }
530

531
    return total;
12✔
532
}
533

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

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

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

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

555
BC_POP_WARNING()
556

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

560
namespace json = boost::json;
561

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

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

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

577
BC_POP_WARNING()
578

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

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

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

595
BC_POP_WARNING()
596
BC_POP_WARNING()
597

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