Coverage Report

Created: 2026-07-14 18:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/bitcoin/src/script/interpreter.cpp
Line
Count
Source
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Copyright (c) 2009-present The Bitcoin Core developers
3
// Distributed under the MIT software license, see the accompanying
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6
#include <script/interpreter.h>
7
8
#include <crypto/ripemd160.h>
9
#include <crypto/sha1.h>
10
#include <crypto/sha256.h>
11
#include <prevector.h>
12
#include <pubkey.h>
13
#include <script/script.h>
14
#include <serialize.h>
15
#include <span.h>
16
#include <tinyformat.h>
17
#include <uint256.h>
18
19
#include <algorithm>
20
#include <cassert>
21
#include <compare>
22
#include <cstring>
23
#include <limits>
24
#include <stdexcept>
25
26
typedef std::vector<unsigned char> valtype;
27
28
namespace {
29
30
inline bool set_success(ScriptError* ret)
31
3.76M
{
32
3.76M
    if (ret)
  Branch (32:9): [True: 3.76M, False: 1.53k]
33
3.76M
        *ret = SCRIPT_ERR_OK;
34
3.76M
    return true;
35
3.76M
}
36
37
inline bool set_error(ScriptError* ret, const ScriptError serror)
38
3.81M
{
39
3.81M
    if (ret)
  Branch (39:9): [True: 3.81M, False: 1.53k]
40
3.81M
        *ret = serror;
41
3.81M
    return false;
42
3.81M
}
43
44
} // namespace
45
46
bool CastToBool(const valtype& vch)
47
1.85M
{
48
1.85M
    for (unsigned int i = 0; i < vch.size(); i++)
  Branch (48:30): [True: 1.85M, False: 1.56k]
49
1.85M
    {
50
1.85M
        if (vch[i] != 0)
  Branch (50:13): [True: 1.85M, False: 1.08k]
51
1.85M
        {
52
            // Can be negative zero
53
1.85M
            if (i == vch.size()-1 && vch[i] == 0x80)
  Branch (53:17): [True: 900k, False: 950k]
  Branch (53:38): [True: 13, False: 900k]
54
13
                return false;
55
1.85M
            return true;
56
1.85M
        }
57
1.85M
    }
58
1.56k
    return false;
59
1.85M
}
60
61
/**
62
 * Script is a stack machine (like Forth) that evaluates a predicate
63
 * returning a bool indicating valid or not.  There are no loops.
64
 */
65
54.3k
#define stacktop(i) (stack.at(size_t(int64_t(stack.size()) + int64_t{i})))
66
39
#define altstacktop(i) (altstack.at(size_t(int64_t(altstack.size()) + int64_t{i})))
67
static inline void popstack(std::vector<valtype>& stack)
68
37.5k
{
69
37.5k
    if (stack.empty())
  Branch (69:9): [True: 0, False: 37.5k]
70
0
        throw std::runtime_error("popstack(): stack empty");
71
37.5k
    stack.pop_back();
72
37.5k
}
73
74
2.72k
bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
75
2.72k
    if (vchPubKey.size() < CPubKey::COMPRESSED_SIZE) {
  Branch (75:9): [True: 85, False: 2.64k]
76
        //  Non-canonical public key: too short
77
85
        return false;
78
85
    }
79
2.64k
    if (vchPubKey[0] == 0x04) {
  Branch (79:9): [True: 13, False: 2.62k]
80
13
        if (vchPubKey.size() != CPubKey::SIZE) {
  Branch (80:13): [True: 13, False: 0]
81
            //  Non-canonical public key: invalid length for uncompressed key
82
13
            return false;
83
13
        }
84
2.62k
    } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
  Branch (84:16): [True: 2.31k, False: 310]
  Branch (84:40): [True: 286, False: 24]
85
2.60k
        if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
  Branch (85:13): [True: 29, False: 2.57k]
86
            //  Non-canonical public key: invalid length for compressed key
87
29
            return false;
88
29
        }
89
2.60k
    } else {
90
        //  Non-canonical public key: neither compressed nor uncompressed
91
24
        return false;
92
24
    }
93
2.57k
    return true;
94
2.64k
}
95
96
5
bool static IsCompressedPubKey(const valtype &vchPubKey) {
97
5
    if (vchPubKey.size() != CPubKey::COMPRESSED_SIZE) {
  Branch (97:9): [True: 0, False: 5]
98
        //  Non-canonical public key: invalid length for compressed key
99
0
        return false;
100
0
    }
101
5
    if (vchPubKey[0] != 0x02 && vchPubKey[0] != 0x03) {
  Branch (101:9): [True: 0, False: 5]
  Branch (101:33): [True: 0, False: 0]
102
        //  Non-canonical public key: invalid prefix for compressed key
103
0
        return false;
104
0
    }
105
5
    return true;
106
5
}
107
108
/**
109
 * A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
110
 * Where R and S are not negative (their first byte has its highest bit not set), and not
111
 * excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
112
 * in which case a single 0 byte is necessary and even required).
113
 *
114
 * See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
115
 *
116
 * This function is consensus-critical since BIP66.
117
 */
118
6.70k
bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
119
    // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
120
    // * total-length: 1-byte length descriptor of everything that follows,
121
    //   excluding the sighash byte.
122
    // * R-length: 1-byte length descriptor of the R value that follows.
123
    // * R: arbitrary-length big-endian encoded R value. It must use the shortest
124
    //   possible encoding for a positive integer (which means no null bytes at
125
    //   the start, except a single one when the next byte has its highest bit set).
126
    // * S-length: 1-byte length descriptor of the S value that follows.
127
    // * S: arbitrary-length big-endian encoded S value. The same rules apply.
128
    // * sighash: 1-byte value indicating what data is hashed (not part of the DER
129
    //   signature)
130
131
    // Minimum and maximum size constraints.
132
6.70k
    if (sig.size() < 9) return false;
  Branch (132:9): [True: 328, False: 6.37k]
133
6.37k
    if (sig.size() > 73) return false;
  Branch (133:9): [True: 63, False: 6.31k]
134
135
    // A signature is of type 0x30 (compound).
136
6.31k
    if (sig[0] != 0x30) return false;
  Branch (136:9): [True: 55, False: 6.26k]
137
138
    // Make sure the length covers the entire signature.
139
6.26k
    if (sig[1] != sig.size() - 3) return false;
  Branch (139:9): [True: 14, False: 6.24k]
140
141
    // Extract the length of the R element.
142
6.24k
    unsigned int lenR = sig[3];
143
144
    // Make sure the length of the S element is still inside the signature.
145
6.24k
    if (5 + lenR >= sig.size()) return false;
  Branch (145:9): [True: 0, False: 6.24k]
146
147
    // Extract the length of the S element.
148
6.24k
    unsigned int lenS = sig[5 + lenR];
149
150
    // Verify that the length of the signature matches the sum of the length
151
    // of the elements.
152
6.24k
    if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
  Branch (152:9): [True: 0, False: 6.24k]
153
154
    // Check whether the R element is an integer.
155
6.24k
    if (sig[2] != 0x02) return false;
  Branch (155:9): [True: 0, False: 6.24k]
156
157
    // Zero-length integers are not allowed for R.
158
6.24k
    if (lenR == 0) return false;
  Branch (158:9): [True: 0, False: 6.24k]
159
160
    // Negative numbers are not allowed for R.
161
6.24k
    if (sig[4] & 0x80) return false;
  Branch (161:9): [True: 0, False: 6.24k]
162
163
    // Null bytes at the start of R are not allowed, unless R would
164
    // otherwise be interpreted as a negative number.
165
6.24k
    if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
  Branch (165:9): [True: 6.24k, False: 0]
  Branch (165:21): [True: 3.39k, False: 2.85k]
  Branch (165:41): [True: 0, False: 3.39k]
166
167
    // Check whether the S element is an integer.
168
6.24k
    if (sig[lenR + 4] != 0x02) return false;
  Branch (168:9): [True: 0, False: 6.24k]
169
170
    // Zero-length integers are not allowed for S.
171
6.24k
    if (lenS == 0) return false;
  Branch (171:9): [True: 0, False: 6.24k]
172
173
    // Negative numbers are not allowed for S.
174
6.24k
    if (sig[lenR + 6] & 0x80) return false;
  Branch (174:9): [True: 0, False: 6.24k]
175
176
    // Null bytes at the start of S are not allowed, unless S would otherwise be
177
    // interpreted as a negative number.
178
6.24k
    if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
  Branch (178:9): [True: 6.24k, False: 0]
  Branch (178:21): [True: 87, False: 6.16k]
  Branch (178:48): [True: 0, False: 87]
179
180
6.24k
    return true;
181
6.24k
}
182
183
2.57k
bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
184
2.57k
    if (!IsValidSignatureEncoding(vchSig)) {
  Branch (184:9): [True: 0, False: 2.57k]
185
0
        return set_error(serror, SCRIPT_ERR_SIG_DER);
186
0
    }
187
    // https://bitcoin.stackexchange.com/a/12556:
188
    //     Also note that inside transaction signatures, an extra hashtype byte
189
    //     follows the actual signature data.
190
2.57k
    std::vector<unsigned char> vchSigCopy(vchSig.begin(), vchSig.begin() + vchSig.size() - 1);
191
    // If the S value is above the order of the curve divided by two, its
192
    // complement modulo the order could have been used instead, which is
193
    // one byte shorter when encoded correctly.
194
2.57k
    if (!CPubKey::CheckLowS(vchSigCopy)) {
  Branch (194:9): [True: 0, False: 2.57k]
195
0
        return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
196
0
    }
197
2.57k
    return true;
198
2.57k
}
199
200
2.57k
bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
201
2.57k
    if (vchSig.size() == 0) {
  Branch (201:9): [True: 0, False: 2.57k]
202
0
        return false;
203
0
    }
204
2.57k
    unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
205
2.57k
    if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
  Branch (205:9): [True: 0, False: 2.57k]
  Branch (205:36): [True: 0, False: 2.57k]
206
0
        return false;
207
208
2.57k
    return true;
209
2.57k
}
210
211
4.41k
bool CheckSignatureEncoding(const std::vector<unsigned char> &vchSig, script_verify_flags flags, ScriptError* serror) {
212
    // Empty signature. Not strictly DER encoded, but allowed to provide a
213
    // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
214
4.41k
    if (vchSig.size() == 0) {
  Branch (214:9): [True: 281, False: 4.13k]
215
281
        return true;
216
281
    }
217
4.13k
    if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
  Branch (217:9): [True: 4.13k, False: 0]
  Branch (217:9): [True: 460, False: 3.67k]
  Branch (217:98): [True: 460, False: 3.67k]
218
460
        return set_error(serror, SCRIPT_ERR_SIG_DER);
219
3.67k
    } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
  Branch (219:16): [True: 2.57k, False: 1.10k]
  Branch (219:16): [True: 0, False: 3.67k]
  Branch (219:54): [True: 0, False: 2.57k]
220
        // serror is set
221
0
        return false;
222
3.67k
    } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
  Branch (222:16): [True: 2.57k, False: 1.10k]
  Branch (222:16): [True: 0, False: 3.67k]
  Branch (222:58): [True: 0, False: 2.57k]
223
0
        return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
224
0
    }
225
3.67k
    return true;
226
4.13k
}
227
228
3.95k
bool static CheckPubKeyEncoding(const valtype &vchPubKey, script_verify_flags flags, const SigVersion &sigversion, ScriptError* serror) {
229
3.95k
    if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey)) {
  Branch (229:9): [True: 2.72k, False: 1.23k]
  Branch (229:9): [True: 151, False: 3.80k]
  Branch (229:51): [True: 151, False: 2.57k]
230
151
        return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
231
151
    }
232
    // Only compressed keys are accepted in segwit
233
3.80k
    if ((flags & SCRIPT_VERIFY_WITNESS_PUBKEYTYPE) != 0 && sigversion == SigVersion::WITNESS_V0 && !IsCompressedPubKey(vchPubKey)) {
  Branch (233:9): [True: 2.57k, False: 1.23k]
  Branch (233:9): [True: 0, False: 3.80k]
  Branch (233:60): [True: 5, False: 2.57k]
  Branch (233:100): [True: 0, False: 5]
234
0
        return set_error(serror, SCRIPT_ERR_WITNESS_PUBKEYTYPE);
235
0
    }
236
3.80k
    return true;
237
3.80k
}
238
239
int FindAndDelete(CScript& script, const CScript& b)
240
4.02k
{
241
4.02k
    int nFound = 0;
242
4.02k
    if (b.empty())
  Branch (242:9): [True: 0, False: 4.02k]
243
0
        return nFound;
244
4.02k
    CScript result;
245
4.02k
    CScript::const_iterator pc = script.begin(), pc2 = script.begin(), end = script.end();
246
4.02k
    opcodetype opcode;
247
4.02k
    do
248
20.2k
    {
249
20.2k
        result.insert(result.end(), pc2, pc);
250
20.7k
        while (static_cast<size_t>(end - pc) >= b.size() && std::equal(b.begin(), b.end(), pc))
  Branch (250:16): [True: 7.52k, False: 13.2k]
  Branch (250:61): [True: 521, False: 7.00k]
251
521
        {
252
521
            pc = pc + b.size();
253
521
            ++nFound;
254
521
        }
255
20.2k
        pc2 = pc;
256
20.2k
    }
257
20.2k
    while (script.GetOp(pc, opcode));
  Branch (257:12): [True: 16.2k, False: 4.02k]
258
259
4.02k
    if (nFound > 0) {
  Branch (259:9): [True: 132, False: 3.89k]
260
132
        result.insert(result.end(), pc2, end);
261
132
        script = std::move(result);
262
132
    }
263
264
4.02k
    return nFound;
265
4.02k
}
266
267
namespace {
268
/** A data type to abstract out the condition stack during script execution.
269
 *
270
 * Conceptually it acts like a vector of booleans, one for each level of nested
271
 * IF/THEN/ELSE, indicating whether we're in the active or inactive branch of
272
 * each.
273
 *
274
 * The elements on the stack cannot be observed individually; we only need to
275
 * expose whether the stack is empty and whether or not any false values are
276
 * present at all. To implement OP_ELSE, a toggle_top modifier is added, which
277
 * flips the last value without returning it.
278
 *
279
 * This uses an optimized implementation that does not materialize the
280
 * actual stack. Instead, it just stores the size of the would-be stack,
281
 * and the position of the first false value in it.
282
 */
283
class ConditionStack {
284
private:
285
    //! A constant for m_first_false_pos to indicate there are no falses.
286
    static constexpr uint32_t NO_FALSE = std::numeric_limits<uint32_t>::max();
287
288
    //! The size of the implied stack.
289
    uint32_t m_stack_size = 0;
290
    //! The position of the first false value on the implied stack, or NO_FALSE if all true.
291
    uint32_t m_first_false_pos = NO_FALSE;
292
293
public:
294
2.81M
    bool empty() const { return m_stack_size == 0; }
295
2.92M
    bool all_true() const { return m_first_false_pos == NO_FALSE; }
296
    void push_back(bool f)
297
2.20k
    {
298
2.20k
        if (m_first_false_pos == NO_FALSE && !f) {
  Branch (298:13): [True: 1.06k, False: 1.14k]
  Branch (298:46): [True: 273, False: 795]
299
            // The stack consists of all true values, and a false is added.
300
            // The first false value will appear at the current size.
301
273
            m_first_false_pos = m_stack_size;
302
273
        }
303
2.20k
        ++m_stack_size;
304
2.20k
    }
305
    void pop_back()
306
161
    {
307
161
        assert(m_stack_size > 0);
  Branch (307:9): [True: 161, False: 0]
308
161
        --m_stack_size;
309
161
        if (m_first_false_pos == m_stack_size) {
  Branch (309:13): [True: 18, False: 143]
310
            // When popping off the first false value, everything becomes true.
311
18
            m_first_false_pos = NO_FALSE;
312
18
        }
313
161
    }
314
    void toggle_top()
315
889
    {
316
889
        assert(m_stack_size > 0);
  Branch (316:9): [True: 889, False: 0]
317
889
        if (m_first_false_pos == NO_FALSE) {
  Branch (317:13): [True: 324, False: 565]
318
            // The current stack is all true values; the first false will be the top.
319
324
            m_first_false_pos = m_stack_size - 1;
320
565
        } else if (m_first_false_pos == m_stack_size - 1) {
  Branch (320:20): [True: 329, False: 236]
321
            // The top is the first false value; toggling it will make everything true.
322
329
            m_first_false_pos = NO_FALSE;
323
329
        } else {
324
            // There is a false value, but not on top. No action is needed as toggling
325
            // anything but the first false value is unobservable.
326
236
        }
327
889
    }
328
};
329
}
330
331
static bool EvalChecksigPreTapscript(const valtype& vchSig, const valtype& vchPubKey, CScript::const_iterator pbegincodehash, CScript::const_iterator pend, script_verify_flags flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror, bool& fSuccess)
332
4.25k
{
333
4.25k
    assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0);
  Branch (333:5): [True: 4.00k, False: 250]
  Branch (333:5): [True: 250, False: 0]
  Branch (333:5): [True: 4.25k, False: 0]
334
335
    // Subset of script starting at the most recent codeseparator
336
4.25k
    CScript scriptCode(pbegincodehash, pend);
337
338
    // Drop the signature in pre-segwit scripts but not segwit scripts
339
4.25k
    if (sigversion == SigVersion::BASE) {
  Branch (339:9): [True: 4.00k, False: 249]
340
4.00k
        int found = FindAndDelete(scriptCode, CScript() << vchSig);
341
4.00k
        if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
  Branch (341:13): [True: 132, False: 3.87k]
  Branch (341:13): [True: 34, False: 3.96k]
  Branch (341:26): [True: 34, False: 98]
342
34
            return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
343
4.00k
    }
344
345
4.21k
    if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
  Branch (345:9): [True: 275, False: 3.94k]
  Branch (345:59): [True: 146, False: 3.79k]
346
        //serror is set
347
423
        return false;
348
423
    }
349
3.79k
    fSuccess = checker.CheckECDSASignature(vchSig, vchPubKey, scriptCode, sigversion);
350
351
3.79k
    if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size())
  Branch (351:9): [True: 1.59k, False: 2.20k]
  Branch (351:9): [True: 1.38k, False: 2.41k]
  Branch (351:22): [True: 1.38k, False: 205]
  Branch (351:58): [True: 1.38k, False: 5]
352
1.38k
        return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
353
354
2.41k
    return true;
355
3.79k
}
356
357
static bool EvalChecksigTapscript(const valtype& sig, const valtype& pubkey, ScriptExecutionData& execdata, script_verify_flags flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror, bool& success)
358
186
{
359
186
    assert(sigversion == SigVersion::TAPSCRIPT);
  Branch (359:5): [True: 186, False: 0]
360
361
    /*
362
     *  The following validation sequence is consensus critical. Please note how --
363
     *    upgradable public key versions precede other rules;
364
     *    the script execution fails when using empty signature with invalid public key;
365
     *    the script execution fails when using non-empty invalid signature.
366
     */
367
186
    success = !sig.empty();
368
186
    if (success) {
  Branch (368:9): [True: 186, False: 0]
369
        // Implement the sigops/witnesssize ratio test.
370
        // Passing with an upgradable public key version is also counted.
371
186
        assert(execdata.m_validation_weight_left_init);
  Branch (371:9): [True: 186, False: 0]
372
186
        execdata.m_validation_weight_left -= VALIDATION_WEIGHT_PER_SIGOP_PASSED;
373
186
        if (execdata.m_validation_weight_left < 0) {
  Branch (373:13): [True: 0, False: 186]
374
0
            return set_error(serror, SCRIPT_ERR_TAPSCRIPT_VALIDATION_WEIGHT);
375
0
        }
376
186
    }
377
186
    if (pubkey.size() == 0) {
  Branch (377:9): [True: 0, False: 186]
378
0
        return set_error(serror, SCRIPT_ERR_TAPSCRIPT_EMPTY_PUBKEY);
379
186
    } else if (pubkey.size() == 32) {
  Branch (379:16): [True: 186, False: 0]
380
186
        if (success && !checker.CheckSchnorrSignature(sig, pubkey, sigversion, execdata, serror)) {
  Branch (380:13): [True: 186, False: 0]
  Branch (380:24): [True: 186, False: 0]
381
186
            return false; // serror is set
382
186
        }
383
186
    } else {
384
        /*
385
         *  New public key version softforks should be defined before this `else` block.
386
         *  Generally, the new code should not do anything but failing the script execution. To avoid
387
         *  consensus bugs, it should not modify any existing values (including `success`).
388
         */
389
0
        if ((flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_PUBKEYTYPE) != 0) {
  Branch (389:13): [True: 0, False: 0]
390
0
            return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_PUBKEYTYPE);
391
0
        }
392
0
    }
393
394
0
    return true;
395
186
}
396
397
/** Helper for OP_CHECKSIG, OP_CHECKSIGVERIFY, and (in Tapscript) OP_CHECKSIGADD.
398
 *
399
 * A return value of false means the script fails entirely. When true is returned, the
400
 * success variable indicates whether the signature check itself succeeded.
401
 */
402
static bool EvalChecksig(const valtype& sig, const valtype& pubkey, CScript::const_iterator pbegincodehash, CScript::const_iterator pend, ScriptExecutionData& execdata, script_verify_flags flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror, bool& success)
403
4.43k
{
404
4.43k
    switch (sigversion) {
  Branch (404:13): [True: 0, False: 4.43k]
405
4.00k
    case SigVersion::BASE:
  Branch (405:5): [True: 4.00k, False: 436]
406
4.25k
    case SigVersion::WITNESS_V0:
  Branch (406:5): [True: 250, False: 4.18k]
407
4.25k
        return EvalChecksigPreTapscript(sig, pubkey, pbegincodehash, pend, flags, checker, sigversion, serror, success);
408
186
    case SigVersion::TAPSCRIPT:
  Branch (408:5): [True: 186, False: 4.25k]
409
186
        return EvalChecksigTapscript(sig, pubkey, execdata, flags, checker, sigversion, serror, success);
410
0
    case SigVersion::TAPROOT:
  Branch (410:5): [True: 0, False: 4.43k]
411
        // Key path spending in Taproot has no script, so this is unreachable.
412
0
        break;
413
4.43k
    }
414
4.43k
    assert(false);
  Branch (414:5): [Folded - Ignored]
415
0
}
416
417
bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, script_verify_flags flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror)
418
2.83M
{
419
2.83M
    static const CScriptNum bnZero(0);
420
2.83M
    static const CScriptNum bnOne(1);
421
    // static const CScriptNum bnFalse(0);
422
    // static const CScriptNum bnTrue(1);
423
2.83M
    static const valtype vchFalse(0);
424
    // static const valtype vchZero(0);
425
2.83M
    static const valtype vchTrue(1, 1);
426
427
    // sigversion cannot be TAPROOT here, as it admits no script execution.
428
2.83M
    assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0 || sigversion == SigVersion::TAPSCRIPT);
  Branch (428:5): [True: 1.92M, False: 908k]
  Branch (428:5): [True: 908k, False: 380]
  Branch (428:5): [True: 380, False: 0]
  Branch (428:5): [True: 2.83M, False: 18.4E]
429
430
2.83M
    CScript::const_iterator pc = script.begin();
431
2.83M
    CScript::const_iterator pend = script.end();
432
2.83M
    CScript::const_iterator pbegincodehash = script.begin();
433
2.83M
    opcodetype opcode;
434
2.83M
    valtype vchPushValue;
435
2.83M
    ConditionStack vfExec;
436
2.83M
    std::vector<valtype> altstack;
437
2.83M
    set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
438
2.83M
    if ((sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) && script.size() > MAX_SCRIPT_SIZE) {
  Branch (438:10): [True: 1.92M, False: 908k]
  Branch (438:44): [True: 908k, False: 380]
  Branch (438:85): [True: 339, False: 2.83M]
439
339
        return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
440
339
    }
441
2.83M
    int nOpCount = 0;
442
2.83M
    bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
443
2.83M
    uint32_t opcode_pos = 0;
444
2.83M
    execdata.m_codeseparator_pos = 0xFFFFFFFFUL;
445
2.83M
    execdata.m_codeseparator_pos_init = true;
446
447
2.83M
    try
448
2.83M
    {
449
5.73M
        for (; pc < pend; ++opcode_pos) {
  Branch (449:16): [True: 2.92M, False: 2.81M]
450
2.92M
            bool fExec = vfExec.all_true();
451
452
            //
453
            // Read instruction
454
            //
455
2.92M
            if (!script.GetOp(pc, opcode, vchPushValue))
  Branch (455:17): [True: 2.33k, False: 2.91M]
456
2.33k
                return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
457
2.91M
            if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
  Branch (457:17): [True: 44, False: 2.91M]
458
44
                return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
459
460
2.91M
            if (sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) {
  Branch (460:17): [True: 1.95M, False: 961k]
  Branch (460:51): [True: 960k, False: 566]
461
                // Note how OP_RESERVED does not count towards the opcode limit.
462
2.91M
                if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT) {
  Branch (462:21): [True: 49.2k, False: 2.86M]
  Branch (462:39): [True: 0, False: 49.2k]
463
0
                    return set_error(serror, SCRIPT_ERR_OP_COUNT);
464
0
                }
465
2.91M
            }
466
467
2.91M
            if (opcode == OP_CAT ||
  Branch (467:17): [True: 37, False: 2.91M]
468
2.91M
                opcode == OP_SUBSTR ||
  Branch (468:17): [True: 195, False: 2.91M]
469
2.91M
                opcode == OP_LEFT ||
  Branch (469:17): [True: 312, False: 2.91M]
470
2.91M
                opcode == OP_RIGHT ||
  Branch (470:17): [True: 106, False: 2.91M]
471
2.91M
                opcode == OP_INVERT ||
  Branch (471:17): [True: 60, False: 2.91M]
472
2.91M
                opcode == OP_AND ||
  Branch (472:17): [True: 127, False: 2.91M]
473
2.91M
                opcode == OP_OR ||
  Branch (473:17): [True: 65, False: 2.91M]
474
2.91M
                opcode == OP_XOR ||
  Branch (474:17): [True: 67, False: 2.91M]
475
2.91M
                opcode == OP_2MUL ||
  Branch (475:17): [True: 99, False: 2.91M]
476
2.91M
                opcode == OP_2DIV ||
  Branch (476:17): [True: 68, False: 2.91M]
477
2.91M
                opcode == OP_MUL ||
  Branch (477:17): [True: 43, False: 2.91M]
478
2.91M
                opcode == OP_DIV ||
  Branch (478:17): [True: 46, False: 2.91M]
479
2.91M
                opcode == OP_MOD ||
  Branch (479:17): [True: 69, False: 2.91M]
480
2.91M
                opcode == OP_LSHIFT ||
  Branch (480:17): [True: 111, False: 2.91M]
481
2.91M
                opcode == OP_RSHIFT)
  Branch (481:17): [True: 66, False: 2.91M]
482
1.50k
                return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes (CVE-2010-5137).
483
484
            // With SCRIPT_VERIFY_CONST_SCRIPTCODE, OP_CODESEPARATOR in non-segwit script is rejected even in an unexecuted branch
485
2.91M
            if (opcode == OP_CODESEPARATOR && sigversion == SigVersion::BASE && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
  Branch (485:17): [True: 529, False: 2.91M]
  Branch (485:17): [True: 24, False: 2.91M]
  Branch (485:47): [True: 60, False: 469]
  Branch (485:81): [True: 24, False: 36]
486
24
                return set_error(serror, SCRIPT_ERR_OP_CODESEPARATOR);
487
488
2.91M
            if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
  Branch (488:17): [True: 2.91M, False: 3.74k]
  Branch (488:26): [True: 2.91M, False: 0]
  Branch (488:41): [True: 1.91M, False: 1.00M]
489
1.91M
                if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
  Branch (489:21): [True: 902k, False: 1.01M]
  Branch (489:40): [True: 286, False: 901k]
490
286
                    return set_error(serror, SCRIPT_ERR_MINIMALDATA);
491
286
                }
492
1.91M
                stack.push_back(vchPushValue);
493
1.91M
            } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
  Branch (493:24): [True: 1.00M, False: 3.80k]
  Branch (493:34): [True: 2.48k, False: 1.31k]
  Branch (493:53): [True: 1.75k, False: 730]
494
1.00M
            switch (opcode)
495
1.00M
            {
496
                //
497
                // Push value
498
                //
499
1.71k
                case OP_1NEGATE:
  Branch (499:17): [True: 1.71k, False: 1.00M]
500
938k
                case OP_1:
  Branch (500:17): [True: 937k, False: 65.2k]
501
940k
                case OP_2:
  Branch (501:17): [True: 1.96k, False: 1.00M]
502
942k
                case OP_3:
  Branch (502:17): [True: 1.36k, False: 1.00M]
503
943k
                case OP_4:
  Branch (503:17): [True: 1.48k, False: 1.00M]
504
944k
                case OP_5:
  Branch (504:17): [True: 1.08k, False: 1.00M]
505
945k
                case OP_6:
  Branch (505:17): [True: 752, False: 1.00M]
506
946k
                case OP_7:
  Branch (506:17): [True: 663, False: 1.00M]
507
946k
                case OP_8:
  Branch (507:17): [True: 649, False: 1.00M]
508
948k
                case OP_9:
  Branch (508:17): [True: 1.23k, False: 1.00M]
509
949k
                case OP_10:
  Branch (509:17): [True: 1.54k, False: 1.00M]
510
950k
                case OP_11:
  Branch (510:17): [True: 1.21k, False: 1.00M]
511
951k
                case OP_12:
  Branch (511:17): [True: 823, False: 1.00M]
512
952k
                case OP_13:
  Branch (512:17): [True: 1.09k, False: 1.00M]
513
953k
                case OP_14:
  Branch (513:17): [True: 488, False: 1.00M]
514
953k
                case OP_15:
  Branch (514:17): [True: 656, False: 1.00M]
515
955k
                case OP_16:
  Branch (515:17): [True: 1.13k, False: 1.00M]
516
955k
                {
517
                    // ( -- value)
518
955k
                    CScriptNum bn((int)opcode - (int)(OP_1 - 1));
519
955k
                    stack.push_back(bn.getvch());
520
                    // The result of these opcodes should always be the minimal way to push the data
521
                    // they push, so no need for a CheckMinimalPush here.
522
955k
                }
523
955k
                break;
524
525
526
                //
527
                // Control
528
                //
529
599
                case OP_NOP:
  Branch (529:17): [True: 599, False: 1.00M]
530
599
                    break;
531
532
362
                case OP_CHECKLOCKTIMEVERIFY:
  Branch (532:17): [True: 362, False: 1.00M]
533
362
                {
534
362
                    if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
  Branch (534:25): [True: 0, False: 362]
535
                        // not enabled; treat as a NOP2
536
0
                        break;
537
0
                    }
538
539
362
                    if (stack.size() < 1)
  Branch (539:25): [True: 71, False: 291]
540
71
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
541
542
                    // Note that elsewhere numeric opcodes are limited to
543
                    // operands in the range -2**31+1 to 2**31-1, however it is
544
                    // legal for opcodes to produce results exceeding that
545
                    // range. This limitation is implemented by CScriptNum's
546
                    // default 4-byte limit.
547
                    //
548
                    // If we kept to that limit we'd have a year 2038 problem,
549
                    // even though the nLockTime field in transactions
550
                    // themselves is uint32 which only becomes meaningless
551
                    // after the year 2106.
552
                    //
553
                    // Thus as a special case we tell CScriptNum to accept up
554
                    // to 5-byte bignums, which are good until 2**39-1, well
555
                    // beyond the 2**32-1 limit of the nLockTime field itself.
556
291
                    const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
557
558
                    // In the rare event that the argument may be < 0 due to
559
                    // some arithmetic being done first, you can always use
560
                    // 0 MAX CHECKLOCKTIMEVERIFY.
561
291
                    if (nLockTime < 0)
  Branch (561:25): [True: 59, False: 232]
562
59
                        return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
563
564
                    // Actually compare the specified lock time with the transaction.
565
232
                    if (!checker.CheckLockTime(nLockTime))
  Branch (565:25): [True: 61, False: 171]
566
61
                        return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
567
568
171
                    break;
569
232
                }
570
571
292
                case OP_CHECKSEQUENCEVERIFY:
  Branch (571:17): [True: 292, False: 1.00M]
572
292
                {
573
292
                    if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
  Branch (573:25): [True: 0, False: 292]
574
                        // not enabled; treat as a NOP3
575
0
                        break;
576
0
                    }
577
578
292
                    if (stack.size() < 1)
  Branch (578:25): [True: 43, False: 249]
579
43
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
580
581
                    // nSequence, like nLockTime, is a 32-bit unsigned integer
582
                    // field. See the comment in CHECKLOCKTIMEVERIFY regarding
583
                    // 5-byte numeric operands.
584
249
                    const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
585
586
                    // In the rare event that the argument may be < 0 due to
587
                    // some arithmetic being done first, you can always use
588
                    // 0 MAX CHECKSEQUENCEVERIFY.
589
249
                    if (nSequence < 0)
  Branch (589:25): [True: 50, False: 199]
590
50
                        return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
591
592
                    // To provide for future soft-fork extensibility, if the
593
                    // operand has the disabled lock-time flag set,
594
                    // CHECKSEQUENCEVERIFY behaves as a NOP.
595
199
                    if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
  Branch (595:25): [True: 20, False: 179]
596
20
                        break;
597
598
                    // Compare the specified sequence number with the input.
599
179
                    if (!checker.CheckSequence(nSequence))
  Branch (599:25): [True: 123, False: 56]
600
123
                        return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
601
602
56
                    break;
603
179
                }
604
605
1.13k
                case OP_NOP1: case OP_NOP4: case OP_NOP5:
  Branch (605:17): [True: 358, False: 1.00M]
  Branch (605:31): [True: 323, False: 1.00M]
  Branch (605:45): [True: 457, False: 1.00M]
606
2.50k
                case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
  Branch (606:17): [True: 246, False: 1.00M]
  Branch (606:31): [True: 193, False: 1.00M]
  Branch (606:45): [True: 497, False: 1.00M]
  Branch (606:59): [True: 184, False: 1.00M]
  Branch (606:73): [True: 242, False: 1.00M]
607
2.50k
                {
608
2.50k
                    if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
  Branch (608:25): [True: 373, False: 2.12k]
609
373
                        return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
610
2.50k
                }
611
2.12k
                break;
612
613
2.12k
                case OP_IF:
  Branch (613:17): [True: 717, False: 1.00M]
614
2.60k
                case OP_NOTIF:
  Branch (614:17): [True: 1.88k, False: 1.00M]
615
2.60k
                {
616
                    // <expression> if [statements] [else [statements]] endif
617
2.60k
                    bool fValue = false;
618
2.60k
                    if (fExec)
  Branch (618:25): [True: 1.46k, False: 1.14k]
619
1.46k
                    {
620
1.46k
                        if (stack.size() < 1)
  Branch (620:29): [True: 205, False: 1.25k]
621
205
                            return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
622
1.25k
                        valtype& vch = stacktop(-1);
623
                        // Tapscript requires minimal IF/NOTIF inputs as a consensus rule.
624
1.25k
                        if (sigversion == SigVersion::TAPSCRIPT) {
  Branch (624:29): [True: 0, False: 1.25k]
625
                            // The input argument to the OP_IF and OP_NOTIF opcodes must be either
626
                            // exactly 0 (the empty vector) or exactly 1 (the one-byte vector with value 1).
627
0
                            if (vch.size() > 1 || (vch.size() == 1 && vch[0] != 1)) {
  Branch (627:33): [True: 0, False: 0]
  Branch (627:52): [True: 0, False: 0]
  Branch (627:71): [True: 0, False: 0]
628
0
                                return set_error(serror, SCRIPT_ERR_TAPSCRIPT_MINIMALIF);
629
0
                            }
630
0
                        }
631
                        // Under witness v0 rules it is only a policy rule, enabled through SCRIPT_VERIFY_MINIMALIF.
632
1.25k
                        if (sigversion == SigVersion::WITNESS_V0 && (flags & SCRIPT_VERIFY_MINIMALIF)) {
  Branch (632:29): [True: 1.06k, False: 194]
  Branch (632:29): [True: 795, False: 461]
  Branch (632:69): [True: 795, False: 267]
633
795
                            if (vch.size() > 1)
  Branch (633:33): [True: 133, False: 662]
634
133
                                return set_error(serror, SCRIPT_ERR_MINIMALIF);
635
662
                            if (vch.size() == 1 && vch[0] != 1)
  Branch (635:33): [True: 235, False: 427]
  Branch (635:52): [True: 54, False: 181]
636
54
                                return set_error(serror, SCRIPT_ERR_MINIMALIF);
637
662
                        }
638
1.06k
                        fValue = CastToBool(vch);
639
1.06k
                        if (opcode == OP_NOTIF)
  Branch (639:29): [True: 861, False: 208]
640
861
                            fValue = !fValue;
641
1.06k
                        popstack(stack);
642
1.06k
                    }
643
2.21k
                    vfExec.push_back(fValue);
644
2.21k
                }
645
0
                break;
646
647
962
                case OP_ELSE:
  Branch (647:17): [True: 962, False: 1.00M]
648
962
                {
649
962
                    if (vfExec.empty())
  Branch (649:25): [True: 73, False: 889]
650
73
                        return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
651
889
                    vfExec.toggle_top();
652
889
                }
653
0
                break;
654
655
208
                case OP_ENDIF:
  Branch (655:17): [True: 208, False: 1.00M]
656
208
                {
657
208
                    if (vfExec.empty())
  Branch (657:25): [True: 47, False: 161]
658
47
                        return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
659
161
                    vfExec.pop_back();
660
161
                }
661
0
                break;
662
663
301
                case OP_VERIFY:
  Branch (663:17): [True: 301, False: 1.00M]
664
301
                {
665
                    // (true -- ) or
666
                    // (false -- false) and return
667
301
                    if (stack.size() < 1)
  Branch (667:25): [True: 67, False: 234]
668
67
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
669
234
                    bool fValue = CastToBool(stacktop(-1));
670
234
                    if (fValue)
  Branch (670:25): [True: 163, False: 71]
671
163
                        popstack(stack);
672
71
                    else
673
71
                        return set_error(serror, SCRIPT_ERR_VERIFY);
674
234
                }
675
163
                break;
676
677
163
                case OP_RETURN:
  Branch (677:17): [True: 137, False: 1.00M]
678
137
                {
679
137
                    return set_error(serror, SCRIPT_ERR_OP_RETURN);
680
234
                }
681
0
                break;
682
683
684
                //
685
                // Stack ops
686
                //
687
481
                case OP_TOALTSTACK:
  Branch (687:17): [True: 481, False: 1.00M]
688
481
                {
689
481
                    if (stack.size() < 1)
  Branch (689:25): [True: 107, False: 374]
690
107
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
691
374
                    altstack.push_back(stacktop(-1));
692
374
                    popstack(stack);
693
374
                }
694
0
                break;
695
696
137
                case OP_FROMALTSTACK:
  Branch (696:17): [True: 137, False: 1.00M]
697
137
                {
698
137
                    if (altstack.size() < 1)
  Branch (698:25): [True: 98, False: 39]
699
98
                        return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
700
39
                    stack.push_back(altstacktop(-1));
701
39
                    popstack(altstack);
702
39
                }
703
0
                break;
704
705
138
                case OP_2DROP:
  Branch (705:17): [True: 138, False: 1.00M]
706
138
                {
707
                    // (x1 x2 -- )
708
138
                    if (stack.size() < 2)
  Branch (708:25): [True: 73, False: 65]
709
73
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
710
65
                    popstack(stack);
711
65
                    popstack(stack);
712
65
                }
713
0
                break;
714
715
719
                case OP_2DUP:
  Branch (715:17): [True: 719, False: 1.00M]
716
719
                {
717
                    // (x1 x2 -- x1 x2 x1 x2)
718
719
                    if (stack.size() < 2)
  Branch (718:25): [True: 79, False: 640]
719
79
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
720
640
                    valtype vch1 = stacktop(-2);
721
640
                    valtype vch2 = stacktop(-1);
722
640
                    stack.push_back(vch1);
723
640
                    stack.push_back(vch2);
724
640
                }
725
0
                break;
726
727
594
                case OP_3DUP:
  Branch (727:17): [True: 594, False: 1.00M]
728
594
                {
729
                    // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
730
594
                    if (stack.size() < 3)
  Branch (730:25): [True: 65, False: 529]
731
65
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
732
529
                    valtype vch1 = stacktop(-3);
733
529
                    valtype vch2 = stacktop(-2);
734
529
                    valtype vch3 = stacktop(-1);
735
529
                    stack.push_back(vch1);
736
529
                    stack.push_back(vch2);
737
529
                    stack.push_back(vch3);
738
529
                }
739
0
                break;
740
741
258
                case OP_2OVER:
  Branch (741:17): [True: 258, False: 1.00M]
742
258
                {
743
                    // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
744
258
                    if (stack.size() < 4)
  Branch (744:25): [True: 44, False: 214]
745
44
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
746
214
                    valtype vch1 = stacktop(-4);
747
214
                    valtype vch2 = stacktop(-3);
748
214
                    stack.push_back(vch1);
749
214
                    stack.push_back(vch2);
750
214
                }
751
0
                break;
752
753
496
                case OP_2ROT:
  Branch (753:17): [True: 496, False: 1.00M]
754
496
                {
755
                    // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
756
496
                    if (stack.size() < 6)
  Branch (756:25): [True: 76, False: 420]
757
76
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
758
420
                    valtype vch1 = stacktop(-6);
759
420
                    valtype vch2 = stacktop(-5);
760
420
                    stack.erase(stack.end()-6, stack.end()-4);
761
420
                    stack.push_back(vch1);
762
420
                    stack.push_back(vch2);
763
420
                }
764
0
                break;
765
766
598
                case OP_2SWAP:
  Branch (766:17): [True: 598, False: 1.00M]
767
598
                {
768
                    // (x1 x2 x3 x4 -- x3 x4 x1 x2)
769
598
                    if (stack.size() < 4)
  Branch (769:25): [True: 65, False: 533]
770
65
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
771
533
                    swap(stacktop(-4), stacktop(-2));
772
533
                    swap(stacktop(-3), stacktop(-1));
773
533
                }
774
0
                break;
775
776
993
                case OP_IFDUP:
  Branch (776:17): [True: 993, False: 1.00M]
777
993
                {
778
                    // (x - 0 | x x)
779
993
                    if (stack.size() < 1)
  Branch (779:25): [True: 118, False: 875]
780
118
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
781
875
                    valtype vch = stacktop(-1);
782
875
                    if (CastToBool(vch))
  Branch (782:25): [True: 448, False: 427]
783
448
                        stack.push_back(vch);
784
875
                }
785
0
                break;
786
787
439
                case OP_DEPTH:
  Branch (787:17): [True: 439, False: 1.00M]
788
439
                {
789
                    // -- stacksize
790
439
                    CScriptNum bn(stack.size());
791
439
                    stack.push_back(bn.getvch());
792
439
                }
793
439
                break;
794
795
276
                case OP_DROP:
  Branch (795:17): [True: 276, False: 1.00M]
796
276
                {
797
                    // (x -- )
798
276
                    if (stack.size() < 1)
  Branch (798:25): [True: 107, False: 169]
799
107
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
800
169
                    popstack(stack);
801
169
                }
802
0
                break;
803
804
1.74k
                case OP_DUP:
  Branch (804:17): [True: 1.74k, False: 1.00M]
805
1.74k
                {
806
                    // (x -- x x)
807
1.74k
                    if (stack.size() < 1)
  Branch (807:25): [True: 25, False: 1.71k]
808
25
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
809
1.71k
                    valtype vch = stacktop(-1);
810
1.71k
                    stack.push_back(vch);
811
1.71k
                }
812
0
                break;
813
814
165
                case OP_NIP:
  Branch (814:17): [True: 165, False: 1.00M]
815
165
                {
816
                    // (x1 x2 -- x2)
817
165
                    if (stack.size() < 2)
  Branch (817:25): [True: 76, False: 89]
818
76
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
819
89
                    stack.erase(stack.end() - 2);
820
89
                }
821
0
                break;
822
823
630
                case OP_OVER:
  Branch (823:17): [True: 630, False: 1.00M]
824
630
                {
825
                    // (x1 x2 -- x1 x2 x1)
826
630
                    if (stack.size() < 2)
  Branch (826:25): [True: 62, False: 568]
827
62
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
828
568
                    valtype vch = stacktop(-2);
829
568
                    stack.push_back(vch);
830
568
                }
831
0
                break;
832
833
648
                case OP_PICK:
  Branch (833:17): [True: 648, False: 1.00M]
834
1.02k
                case OP_ROLL:
  Branch (834:17): [True: 381, False: 1.00M]
835
1.02k
                {
836
                    // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
837
                    // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
838
1.02k
                    if (stack.size() < 2)
  Branch (838:25): [True: 101, False: 928]
839
101
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
840
928
                    int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
841
928
                    popstack(stack);
842
928
                    if (n < 0 || n >= (int)stack.size())
  Branch (842:25): [True: 109, False: 819]
  Branch (842:34): [True: 47, False: 772]
843
72
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
844
856
                    valtype vch = stacktop(-n-1);
845
856
                    if (opcode == OP_ROLL)
  Branch (845:25): [True: 279, False: 577]
846
279
                        stack.erase(stack.end()-n-1);
847
856
                    stack.push_back(vch);
848
856
                }
849
0
                break;
850
851
377
                case OP_ROT:
  Branch (851:17): [True: 377, False: 1.00M]
852
377
                {
853
                    // (x1 x2 x3 -- x2 x3 x1)
854
                    //  x2 x1 x3  after first swap
855
                    //  x2 x3 x1  after second swap
856
377
                    if (stack.size() < 3)
  Branch (856:25): [True: 103, False: 274]
857
103
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
858
274
                    swap(stacktop(-3), stacktop(-2));
859
274
                    swap(stacktop(-2), stacktop(-1));
860
274
                }
861
0
                break;
862
863
329
                case OP_SWAP:
  Branch (863:17): [True: 329, False: 1.00M]
864
329
                {
865
                    // (x1 x2 -- x2 x1)
866
329
                    if (stack.size() < 2)
  Branch (866:25): [True: 82, False: 247]
867
82
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
868
247
                    swap(stacktop(-2), stacktop(-1));
869
247
                }
870
0
                break;
871
872
654
                case OP_TUCK:
  Branch (872:17): [True: 654, False: 1.00M]
873
654
                {
874
                    // (x1 x2 -- x2 x1 x2)
875
654
                    if (stack.size() < 2)
  Branch (875:25): [True: 44, False: 610]
876
44
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
877
610
                    valtype vch = stacktop(-1);
878
610
                    stack.insert(stack.end()-2, vch);
879
610
                }
880
0
                break;
881
882
883
414
                case OP_SIZE:
  Branch (883:17): [True: 414, False: 1.00M]
884
414
                {
885
                    // (in -- in size)
886
414
                    if (stack.size() < 1)
  Branch (886:25): [True: 37, False: 377]
887
37
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
888
377
                    CScriptNum bn(stacktop(-1).size());
889
377
                    stack.push_back(bn.getvch());
890
377
                }
891
0
                break;
892
893
894
                //
895
                // Bitwise logic
896
                //
897
3.13k
                case OP_EQUAL:
  Branch (897:17): [True: 3.13k, False: 999k]
898
4.26k
                case OP_EQUALVERIFY:
  Branch (898:17): [True: 1.12k, False: 1.00M]
899
                //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
900
4.26k
                {
901
                    // (x1 x2 - bool)
902
4.26k
                    if (stack.size() < 2)
  Branch (902:25): [True: 125, False: 4.13k]
903
125
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
904
4.13k
                    valtype& vch1 = stacktop(-2);
905
4.13k
                    valtype& vch2 = stacktop(-1);
906
4.13k
                    bool fEqual = (vch1 == vch2);
907
                    // OP_NOTEQUAL is disabled because it would be too easy to say
908
                    // something like n != 1 and have some wiseguy pass in 1 with extra
909
                    // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
910
                    //if (opcode == OP_NOTEQUAL)
911
                    //    fEqual = !fEqual;
912
4.13k
                    popstack(stack);
913
4.13k
                    popstack(stack);
914
4.13k
                    stack.push_back(fEqual ? vchTrue : vchFalse);
  Branch (914:37): [True: 3.14k, False: 989]
915
4.13k
                    if (opcode == OP_EQUALVERIFY)
  Branch (915:25): [True: 1.05k, False: 3.08k]
916
1.05k
                    {
917
1.05k
                        if (fEqual)
  Branch (917:29): [True: 150, False: 905]
918
150
                            popstack(stack);
919
905
                        else
920
905
                            return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
921
1.05k
                    }
922
4.13k
                }
923
3.23k
                break;
924
925
926
                //
927
                // Numeric
928
                //
929
3.23k
                case OP_1ADD:
  Branch (929:17): [True: 685, False: 1.00M]
930
1.19k
                case OP_1SUB:
  Branch (930:17): [True: 508, False: 1.00M]
931
1.90k
                case OP_NEGATE:
  Branch (931:17): [True: 716, False: 1.00M]
932
3.18k
                case OP_ABS:
  Branch (932:17): [True: 1.27k, False: 1.00M]
933
3.83k
                case OP_NOT:
  Branch (933:17): [True: 653, False: 1.00M]
934
4.71k
                case OP_0NOTEQUAL:
  Branch (934:17): [True: 882, False: 1.00M]
935
4.71k
                {
936
                    // (in -- out)
937
4.71k
                    if (stack.size() < 1)
  Branch (937:25): [True: 140, False: 4.57k]
938
140
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
939
4.57k
                    CScriptNum bn(stacktop(-1), fRequireMinimal);
940
4.57k
                    switch (opcode)
941
4.57k
                    {
942
661
                    case OP_1ADD:       bn += bnOne; break;
  Branch (942:21): [True: 661, False: 3.91k]
943
454
                    case OP_1SUB:       bn -= bnOne; break;
  Branch (943:21): [True: 454, False: 4.12k]
944
611
                    case OP_NEGATE:     bn = -bn; break;
  Branch (944:21): [True: 611, False: 3.96k]
945
1.25k
                    case OP_ABS:        if (bn < bnZero) bn = -bn; break;
  Branch (945:21): [True: 1.25k, False: 3.32k]
  Branch (945:45): [True: 54, False: 1.19k]
946
624
                    case OP_NOT:        bn = (bn == bnZero); break;
  Branch (946:21): [True: 624, False: 3.95k]
947
870
                    case OP_0NOTEQUAL:  bn = (bn != bnZero); break;
  Branch (947:21): [True: 870, False: 3.70k]
948
0
                    default:            assert(!"invalid opcode"); break;
  Branch (948:21): [True: 0, False: 4.57k]
  Branch (948:41): [Folded - Ignored]
949
4.57k
                    }
950
4.47k
                    popstack(stack);
951
4.47k
                    stack.push_back(bn.getvch());
952
4.47k
                }
953
0
                break;
954
955
218
                case OP_ADD:
  Branch (955:17): [True: 218, False: 1.00M]
956
826
                case OP_SUB:
  Branch (956:17): [True: 608, False: 1.00M]
957
1.05k
                case OP_BOOLAND:
  Branch (957:17): [True: 224, False: 1.00M]
958
1.32k
                case OP_BOOLOR:
  Branch (958:17): [True: 274, False: 1.00M]
959
1.66k
                case OP_NUMEQUAL:
  Branch (959:17): [True: 338, False: 1.00M]
960
1.84k
                case OP_NUMEQUALVERIFY:
  Branch (960:17): [True: 183, False: 1.00M]
961
2.46k
                case OP_NUMNOTEQUAL:
  Branch (961:17): [True: 624, False: 1.00M]
962
2.68k
                case OP_LESSTHAN:
  Branch (962:17): [True: 215, False: 1.00M]
963
3.06k
                case OP_GREATERTHAN:
  Branch (963:17): [True: 384, False: 1.00M]
964
3.66k
                case OP_LESSTHANOREQUAL:
  Branch (964:17): [True: 597, False: 1.00M]
965
3.90k
                case OP_GREATERTHANOREQUAL:
  Branch (965:17): [True: 237, False: 1.00M]
966
4.07k
                case OP_MIN:
  Branch (966:17): [True: 168, False: 1.00M]
967
4.32k
                case OP_MAX:
  Branch (967:17): [True: 253, False: 1.00M]
968
4.32k
                {
969
                    // (x1 x2 -- out)
970
4.32k
                    if (stack.size() < 2)
  Branch (970:25): [True: 1.03k, False: 3.28k]
971
1.03k
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
972
3.28k
                    CScriptNum bn1(stacktop(-2), fRequireMinimal);
973
3.28k
                    CScriptNum bn2(stacktop(-1), fRequireMinimal);
974
3.28k
                    CScriptNum bn(0);
975
3.28k
                    switch (opcode)
976
3.28k
                    {
977
126
                    case OP_ADD:
  Branch (977:21): [True: 126, False: 3.16k]
978
126
                        bn = bn1 + bn2;
979
126
                        break;
980
981
355
                    case OP_SUB:
  Branch (981:21): [True: 355, False: 2.93k]
982
355
                        bn = bn1 - bn2;
983
355
                        break;
984
985
169
                    case OP_BOOLAND:             bn = (bn1 != bnZero && bn2 != bnZero); break;
  Branch (985:21): [True: 169, False: 3.11k]
  Branch (985:56): [True: 134, False: 35]
  Branch (985:73): [True: 118, False: 16]
986
146
                    case OP_BOOLOR:              bn = (bn1 != bnZero || bn2 != bnZero); break;
  Branch (986:21): [True: 146, False: 3.14k]
  Branch (986:56): [True: 50, False: 96]
  Branch (986:73): [True: 30, False: 66]
987
174
                    case OP_NUMEQUAL:            bn = (bn1 == bn2); break;
  Branch (987:21): [True: 174, False: 3.11k]
988
97
                    case OP_NUMEQUALVERIFY:      bn = (bn1 == bn2); break;
  Branch (988:21): [True: 97, False: 3.19k]
989
540
                    case OP_NUMNOTEQUAL:         bn = (bn1 != bn2); break;
  Branch (989:21): [True: 540, False: 2.74k]
990
161
                    case OP_LESSTHAN:            bn = (bn1 < bn2); break;
  Branch (990:21): [True: 161, False: 3.12k]
991
338
                    case OP_GREATERTHAN:         bn = (bn1 > bn2); break;
  Branch (991:21): [True: 338, False: 2.95k]
992
520
                    case OP_LESSTHANOREQUAL:     bn = (bn1 <= bn2); break;
  Branch (992:21): [True: 520, False: 2.76k]
993
119
                    case OP_GREATERTHANOREQUAL:  bn = (bn1 >= bn2); break;
  Branch (993:21): [True: 119, False: 3.16k]
994
116
                    case OP_MIN:                 bn = (bn1 < bn2 ? bn1 : bn2); break;
  Branch (994:21): [True: 116, False: 3.17k]
  Branch (994:56): [True: 0, False: 116]
995
188
                    case OP_MAX:                 bn = (bn1 > bn2 ? bn1 : bn2); break;
  Branch (995:21): [True: 188, False: 3.10k]
  Branch (995:56): [True: 0, False: 188]
996
0
                    default:                     assert(!"invalid opcode"); break;
  Branch (996:21): [True: 0, False: 3.28k]
  Branch (996:50): [Folded - Ignored]
997
3.28k
                    }
998
3.04k
                    popstack(stack);
999
3.04k
                    popstack(stack);
1000
3.04k
                    stack.push_back(bn.getvch());
1001
1002
3.04k
                    if (opcode == OP_NUMEQUALVERIFY)
  Branch (1002:25): [True: 97, False: 2.95k]
1003
97
                    {
1004
97
                        if (CastToBool(stacktop(-1)))
  Branch (1004:29): [True: 38, False: 59]
1005
38
                            popstack(stack);
1006
59
                        else
1007
59
                            return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
1008
97
                    }
1009
3.04k
                }
1010
2.99k
                break;
1011
1012
2.99k
                case OP_WITHIN:
  Branch (1012:17): [True: 282, False: 1.00M]
1013
282
                {
1014
                    // (x min max -- out)
1015
282
                    if (stack.size() < 3)
  Branch (1015:25): [True: 60, False: 222]
1016
60
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1017
222
                    CScriptNum bn1(stacktop(-3), fRequireMinimal);
1018
222
                    CScriptNum bn2(stacktop(-2), fRequireMinimal);
1019
222
                    CScriptNum bn3(stacktop(-1), fRequireMinimal);
1020
222
                    bool fValue = (bn2 <= bn1 && bn1 < bn3);
  Branch (1020:36): [True: 120, False: 102]
  Branch (1020:50): [True: 7, False: 113]
1021
222
                    popstack(stack);
1022
222
                    popstack(stack);
1023
222
                    popstack(stack);
1024
222
                    stack.push_back(fValue ? vchTrue : vchFalse);
  Branch (1024:37): [True: 7, False: 215]
1025
222
                }
1026
0
                break;
1027
1028
1029
                //
1030
                // Crypto
1031
                //
1032
677
                case OP_RIPEMD160:
  Branch (1032:17): [True: 677, False: 1.00M]
1033
1.42k
                case OP_SHA1:
  Branch (1033:17): [True: 751, False: 1.00M]
1034
1.85k
                case OP_SHA256:
  Branch (1034:17): [True: 428, False: 1.00M]
1035
6.31k
                case OP_HASH160:
  Branch (1035:17): [True: 4.46k, False: 997k]
1036
6.73k
                case OP_HASH256:
  Branch (1036:17): [True: 414, False: 1.00M]
1037
6.73k
                {
1038
                    // (in -- hash)
1039
6.73k
                    if (stack.size() < 1)
  Branch (1039:25): [True: 256, False: 6.47k]
1040
256
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1041
6.47k
                    valtype& vch = stacktop(-1);
1042
6.47k
                    valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
  Branch (1042:38): [True: 640, False: 5.83k]
  Branch (1042:64): [True: 564, False: 5.27k]
  Branch (1042:85): [True: 4.45k, False: 820]
1043
6.47k
                    if (opcode == OP_RIPEMD160)
  Branch (1043:25): [True: 640, False: 5.83k]
1044
640
                        CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
1045
5.83k
                    else if (opcode == OP_SHA1)
  Branch (1045:30): [True: 564, False: 5.27k]
1046
564
                        CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
1047
5.27k
                    else if (opcode == OP_SHA256)
  Branch (1047:30): [True: 420, False: 4.85k]
1048
420
                        CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
1049
4.85k
                    else if (opcode == OP_HASH160)
  Branch (1049:30): [True: 4.45k, False: 400]
1050
4.45k
                        CHash160().Write(vch).Finalize(vchHash);
1051
400
                    else if (opcode == OP_HASH256)
  Branch (1051:30): [True: 400, False: 0]
1052
400
                        CHash256().Write(vch).Finalize(vchHash);
1053
6.47k
                    popstack(stack);
1054
6.47k
                    stack.push_back(vchHash);
1055
6.47k
                }
1056
0
                break;
1057
1058
453
                case OP_CODESEPARATOR:
  Branch (1058:17): [True: 453, False: 1.00M]
1059
453
                {
1060
                    // If SCRIPT_VERIFY_CONST_SCRIPTCODE flag is set, use of OP_CODESEPARATOR is rejected in pre-segwit
1061
                    // script, even in an unexecuted branch (this is checked above the opcode case statement).
1062
1063
                    // Hash starts after the code separator
1064
453
                    pbegincodehash = pc;
1065
453
                    execdata.m_codeseparator_pos = opcode_pos;
1066
453
                }
1067
453
                break;
1068
1069
4.19k
                case OP_CHECKSIG:
  Branch (1069:17): [True: 4.19k, False: 998k]
1070
4.60k
                case OP_CHECKSIGVERIFY:
  Branch (1070:17): [True: 404, False: 1.00M]
1071
4.60k
                {
1072
                    // (sig pubkey -- bool)
1073
4.60k
                    if (stack.size() < 2)
  Branch (1073:25): [True: 163, False: 4.43k]
1074
163
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1075
1076
4.43k
                    valtype& vchSig    = stacktop(-2);
1077
4.43k
                    valtype& vchPubKey = stacktop(-1);
1078
1079
4.43k
                    bool fSuccess = true;
1080
4.43k
                    if (!EvalChecksig(vchSig, vchPubKey, pbegincodehash, pend, execdata, flags, checker, sigversion, serror, fSuccess)) return false;
  Branch (1080:25): [True: 2.02k, False: 2.41k]
1081
2.41k
                    popstack(stack);
1082
2.41k
                    popstack(stack);
1083
2.41k
                    stack.push_back(fSuccess ? vchTrue : vchFalse);
  Branch (1083:37): [True: 2.20k, False: 207]
1084
2.41k
                    if (opcode == OP_CHECKSIGVERIFY)
  Branch (1084:25): [True: 113, False: 2.30k]
1085
113
                    {
1086
113
                        if (fSuccess)
  Branch (1086:29): [True: 0, False: 113]
1087
0
                            popstack(stack);
1088
113
                        else
1089
113
                            return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
1090
113
                    }
1091
2.41k
                }
1092
2.30k
                break;
1093
1094
2.30k
                case OP_CHECKSIGADD:
  Branch (1094:17): [True: 60, False: 1.00M]
1095
60
                {
1096
                    // OP_CHECKSIGADD is only available in Tapscript
1097
60
                    if (sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
  Branch (1097:25): [True: 3, False: 57]
  Branch (1097:59): [True: 57, False: 0]
1098
1099
                    // (sig num pubkey -- num)
1100
0
                    if (stack.size() < 3) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
  Branch (1100:25): [True: 0, False: 0]
1101
1102
0
                    const valtype& sig = stacktop(-3);
1103
0
                    const CScriptNum num(stacktop(-2), fRequireMinimal);
1104
0
                    const valtype& pubkey = stacktop(-1);
1105
1106
0
                    bool success = true;
1107
0
                    if (!EvalChecksig(sig, pubkey, pbegincodehash, pend, execdata, flags, checker, sigversion, serror, success)) return false;
  Branch (1107:25): [True: 0, False: 0]
1108
0
                    popstack(stack);
1109
0
                    popstack(stack);
1110
0
                    popstack(stack);
1111
0
                    stack.push_back((num + (success ? 1 : 0)).getvch());
  Branch (1111:45): [True: 0, False: 0]
1112
0
                }
1113
0
                break;
1114
1115
430
                case OP_CHECKMULTISIG:
  Branch (1115:17): [True: 430, False: 1.00M]
1116
1.17k
                case OP_CHECKMULTISIGVERIFY:
  Branch (1116:17): [True: 744, False: 1.00M]
1117
1.17k
                {
1118
1.17k
                    if (sigversion == SigVersion::TAPSCRIPT) return set_error(serror, SCRIPT_ERR_TAPSCRIPT_CHECKMULTISIG);
  Branch (1118:25): [True: 0, False: 1.17k]
1119
1120
                    // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1121
1122
1.17k
                    int i = 1;
1123
1.17k
                    if ((int)stack.size() < i)
  Branch (1123:25): [True: 262, False: 912]
1124
262
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1125
1126
912
                    int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
1127
912
                    if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
  Branch (1127:25): [True: 112, False: 800]
  Branch (1127:43): [True: 58, False: 742]
1128
102
                        return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
1129
810
                    nOpCount += nKeysCount;
1130
810
                    if (nOpCount > MAX_OPS_PER_SCRIPT)
  Branch (1130:25): [True: 0, False: 810]
1131
0
                        return set_error(serror, SCRIPT_ERR_OP_COUNT);
1132
810
                    int ikey = ++i;
1133
                    // ikey2 is the position of last non-signature item in the stack. Top stack item = 1.
1134
                    // With SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if operation fails.
1135
810
                    int ikey2 = nKeysCount + 2;
1136
810
                    i += nKeysCount;
1137
810
                    if ((int)stack.size() < i)
  Branch (1137:25): [True: 73, False: 737]
1138
73
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1139
1140
737
                    int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
1141
737
                    if (nSigsCount < 0 || nSigsCount > nKeysCount)
  Branch (1141:25): [True: 151, False: 586]
  Branch (1141:43): [True: 45, False: 541]
1142
45
                        return set_error(serror, SCRIPT_ERR_SIG_COUNT);
1143
692
                    int isig = ++i;
1144
692
                    i += nSigsCount;
1145
692
                    if ((int)stack.size() < i)
  Branch (1145:25): [True: 55, False: 637]
1146
55
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1147
1148
                    // Subset of script starting at the most recent codeseparator
1149
637
                    CScript scriptCode(pbegincodehash, pend);
1150
1151
                    // Drop the signature in pre-segwit scripts but not segwit scripts
1152
921
                    for (int k = 0; k < nSigsCount; k++)
  Branch (1152:37): [True: 284, False: 637]
1153
284
                    {
1154
284
                        valtype& vchSig = stacktop(-isig-k);
1155
284
                        if (sigversion == SigVersion::BASE) {
  Branch (1155:29): [True: 26, False: 258]
1156
26
                            int found = FindAndDelete(scriptCode, CScript() << vchSig);
1157
26
                            if (found > 0 && (flags & SCRIPT_VERIFY_CONST_SCRIPTCODE))
  Branch (1157:33): [True: 0, False: 26]
  Branch (1157:33): [True: 0, False: 26]
  Branch (1157:46): [True: 0, False: 0]
1158
0
                                return set_error(serror, SCRIPT_ERR_SIG_FINDANDDELETE);
1159
26
                        }
1160
284
                    }
1161
1162
637
                    bool fSuccess = true;
1163
647
                    while (fSuccess && nSigsCount > 0)
  Branch (1163:28): [True: 486, False: 161]
  Branch (1163:40): [True: 198, False: 288]
1164
198
                    {
1165
198
                        valtype& vchSig    = stacktop(-isig);
1166
198
                        valtype& vchPubKey = stacktop(-ikey);
1167
1168
                        // Note how this makes the exact order of pubkey/signature evaluation
1169
                        // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
1170
                        // See the script_(in)valid tests for details.
1171
198
                        if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
  Branch (1171:29): [True: 183, False: 15]
  Branch (1171:79): [True: 5, False: 10]
1172
                            // serror is set
1173
188
                            return false;
1174
188
                        }
1175
1176
                        // Check signature
1177
10
                        bool fOk = checker.CheckECDSASignature(vchSig, vchPubKey, scriptCode, sigversion);
1178
1179
10
                        if (fOk) {
  Branch (1179:29): [True: 0, False: 10]
1180
0
                            isig++;
1181
0
                            nSigsCount--;
1182
0
                        }
1183
10
                        ikey++;
1184
10
                        nKeysCount--;
1185
1186
                        // If there are more signatures left than keys left,
1187
                        // then too many signatures have failed. Exit early,
1188
                        // without checking any further signatures.
1189
10
                        if (nSigsCount > nKeysCount)
  Branch (1189:29): [True: 10, False: 0]
1190
10
                            fSuccess = false;
1191
10
                    }
1192
1193
                    // Clean up stack of actual arguments
1194
1.07k
                    while (i-- > 1) {
  Branch (1194:28): [True: 629, False: 449]
1195
                        // If the operation failed, we require that all signatures must be empty vector
1196
629
                        if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
  Branch (1196:29): [True: 40, False: 589]
  Branch (1196:29): [True: 0, False: 629]
  Branch (1196:42): [True: 0, False: 40]
  Branch (1196:78): [True: 0, False: 0]
  Branch (1196:88): [True: 0, False: 0]
1197
0
                            return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
1198
629
                        if (ikey2 > 0)
  Branch (1198:29): [True: 619, False: 10]
1199
619
                            ikey2--;
1200
629
                        popstack(stack);
1201
629
                    }
1202
1203
                    // A bug causes CHECKMULTISIG to consume one extra argument
1204
                    // whose contents were not checked in any way.
1205
                    //
1206
                    // Unfortunately this is a potential source of mutability,
1207
                    // so optionally verify it is exactly equal to zero prior
1208
                    // to removing it from the stack.
1209
449
                    if (stack.size() < 1)
  Branch (1209:25): [True: 0, False: 449]
1210
0
                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1211
449
                    if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
  Branch (1211:25): [True: 298, False: 151]
  Branch (1211:25): [True: 56, False: 393]
  Branch (1211:62): [True: 56, False: 242]
1212
56
                        return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
1213
393
                    popstack(stack);
1214
1215
393
                    stack.push_back(fSuccess ? vchTrue : vchFalse);
  Branch (1215:37): [True: 232, False: 161]
1216
1217
393
                    if (opcode == OP_CHECKMULTISIGVERIFY)
  Branch (1217:25): [True: 223, False: 170]
1218
223
                    {
1219
223
                        if (fSuccess)
  Branch (1219:29): [True: 213, False: 10]
1220
213
                            popstack(stack);
1221
10
                        else
1222
10
                            return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
1223
223
                    }
1224
393
                }
1225
383
                break;
1226
1227
2.32k
                default:
  Branch (1227:17): [True: 2.32k, False: 1.00M]
1228
2.32k
                    return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1229
1.00M
            }
1230
1231
            // Size limits
1232
2.90M
            if (stack.size() + altstack.size() > MAX_STACK_SIZE)
  Branch (1232:17): [True: 0, False: 2.90M]
1233
0
                return set_error(serror, SCRIPT_ERR_STACK_SIZE);
1234
2.90M
        }
1235
2.83M
    }
1236
2.83M
    catch (const scriptnum_error&)
1237
2.83M
    {
1238
783
        return set_error(serror, SCRIPT_ERR_SCRIPTNUM);
1239
783
    }
1240
2.83M
    catch (...)
1241
2.83M
    {
1242
0
        return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1243
0
    }
1244
1245
2.81M
    if (!vfExec.empty())
  Branch (1245:9): [True: 276, False: 2.81M]
1246
276
        return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
1247
1248
2.81M
    return set_success(serror);
1249
2.81M
}
1250
1251
bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, script_verify_flags flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
1252
1.92M
{
1253
1.92M
    ScriptExecutionData execdata;
1254
1.92M
    return EvalScript(stack, script, flags, checker, sigversion, execdata, serror);
1255
1.92M
}
1256
1257
namespace {
1258
1259
/**
1260
 * Wrapper that serializes like CTransaction, but with the modifications
1261
 *  required for the signature hash done in-place
1262
 */
1263
template <class T>
1264
class CTransactionSignatureSerializer
1265
{
1266
private:
1267
    const T& txTo;             //!< reference to the spending transaction (the one being serialized)
1268
    const CScript& scriptCode; //!< output script being consumed
1269
    const unsigned int nIn;    //!< input index of txTo being signed
1270
    const bool fAnyoneCanPay;  //!< whether the hashtype has the SIGHASH_ANYONECANPAY flag set
1271
    const bool fHashSingle;    //!< whether the hashtype is SIGHASH_SINGLE
1272
    const bool fHashNone;      //!< whether the hashtype is SIGHASH_NONE
1273
1274
public:
1275
    CTransactionSignatureSerializer(const T& txToIn, const CScript& scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
1276
3.41k
        txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1277
3.41k
        fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
1278
3.41k
        fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
1279
3.41k
        fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
interpreter.cpp:(anonymous namespace)::CTransactionSignatureSerializer<CTransaction>::CTransactionSignatureSerializer(CTransaction const&, CScript const&, unsigned int, int)
Line
Count
Source
1276
3.41k
        txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1277
3.41k
        fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
1278
3.41k
        fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
1279
3.41k
        fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
Unexecuted instantiation: interpreter.cpp:(anonymous namespace)::CTransactionSignatureSerializer<CMutableTransaction>::CTransactionSignatureSerializer(CMutableTransaction const&, CScript const&, unsigned int, int)
1280
1281
    /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
1282
    template<typename S>
1283
3.41k
    void SerializeScriptCode(S &s) const {
1284
3.41k
        CScript::const_iterator it = scriptCode.begin();
1285
3.41k
        CScript::const_iterator itBegin = it;
1286
3.41k
        opcodetype opcode;
1287
3.41k
        unsigned int nCodeSeparators = 0;
1288
10.2k
        while (scriptCode.GetOp(it, opcode)) {
  Branch (1288:16): [True: 6.83k, False: 3.41k]
  Branch (1288:16): [True: 0, False: 0]
1289
6.83k
            if (opcode == OP_CODESEPARATOR)
  Branch (1289:17): [True: 0, False: 6.83k]
  Branch (1289:17): [True: 0, False: 0]
1290
0
                nCodeSeparators++;
1291
6.83k
        }
1292
3.41k
        ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1293
3.41k
        it = itBegin;
1294
10.2k
        while (scriptCode.GetOp(it, opcode)) {
  Branch (1294:16): [True: 6.83k, False: 3.41k]
  Branch (1294:16): [True: 0, False: 0]
1295
6.83k
            if (opcode == OP_CODESEPARATOR) {
  Branch (1295:17): [True: 0, False: 6.83k]
  Branch (1295:17): [True: 0, False: 0]
1296
0
                s.write(std::as_bytes(std::span{&itBegin[0], size_t(it - itBegin - 1)}));
1297
0
                itBegin = it;
1298
0
            }
1299
6.83k
        }
1300
3.41k
        if (itBegin != scriptCode.end())
  Branch (1300:13): [True: 3.41k, False: 18.4E]
  Branch (1300:13): [True: 0, False: 0]
1301
3.41k
            s.write(std::as_bytes(std::span{&itBegin[0], size_t(it - itBegin)}));
1302
3.41k
    }
interpreter.cpp:void (anonymous namespace)::CTransactionSignatureSerializer<CTransaction>::SerializeScriptCode<HashWriter>(HashWriter&) const
Line
Count
Source
1283
3.41k
    void SerializeScriptCode(S &s) const {
1284
3.41k
        CScript::const_iterator it = scriptCode.begin();
1285
3.41k
        CScript::const_iterator itBegin = it;
1286
3.41k
        opcodetype opcode;
1287
3.41k
        unsigned int nCodeSeparators = 0;
1288
10.2k
        while (scriptCode.GetOp(it, opcode)) {
  Branch (1288:16): [True: 6.83k, False: 3.41k]
1289
6.83k
            if (opcode == OP_CODESEPARATOR)
  Branch (1289:17): [True: 0, False: 6.83k]
1290
0
                nCodeSeparators++;
1291
6.83k
        }
1292
3.41k
        ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1293
3.41k
        it = itBegin;
1294
10.2k
        while (scriptCode.GetOp(it, opcode)) {
  Branch (1294:16): [True: 6.83k, False: 3.41k]
1295
6.83k
            if (opcode == OP_CODESEPARATOR) {
  Branch (1295:17): [True: 0, False: 6.83k]
1296
0
                s.write(std::as_bytes(std::span{&itBegin[0], size_t(it - itBegin - 1)}));
1297
0
                itBegin = it;
1298
0
            }
1299
6.83k
        }
1300
3.41k
        if (itBegin != scriptCode.end())
  Branch (1300:13): [True: 3.41k, False: 18.4E]
1301
3.41k
            s.write(std::as_bytes(std::span{&itBegin[0], size_t(it - itBegin)}));
1302
3.41k
    }
Unexecuted instantiation: interpreter.cpp:void (anonymous namespace)::CTransactionSignatureSerializer<CMutableTransaction>::SerializeScriptCode<HashWriter>(HashWriter&) const
1303
1304
    /** Serialize an input of txTo */
1305
    template<typename S>
1306
6.56k
    void SerializeInput(S &s, unsigned int nInput) const {
1307
        // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1308
6.56k
        if (fAnyoneCanPay)
  Branch (1308:13): [True: 1.44k, False: 5.12k]
  Branch (1308:13): [True: 0, False: 0]
1309
1.44k
            nInput = nIn;
1310
        // Serialize the prevout
1311
6.56k
        ::Serialize(s, txTo.vin[nInput].prevout);
1312
        // Serialize the script
1313
6.56k
        if (nInput != nIn)
  Branch (1313:13): [True: 3.14k, False: 3.41k]
  Branch (1313:13): [True: 0, False: 0]
1314
            // Blank out other inputs' signatures
1315
3.14k
            ::Serialize(s, CScript());
1316
3.41k
        else
1317
3.41k
            SerializeScriptCode(s);
1318
        // Serialize the nSequence
1319
6.56k
        if (nInput != nIn && (fHashSingle || fHashNone))
  Branch (1319:13): [True: 3.14k, False: 3.41k]
  Branch (1319:31): [True: 393, False: 2.75k]
  Branch (1319:46): [True: 551, False: 2.20k]
  Branch (1319:13): [True: 0, False: 0]
  Branch (1319:31): [True: 0, False: 0]
  Branch (1319:46): [True: 0, False: 0]
1320
            // let the others update at will
1321
944
            ::Serialize(s, int32_t{0});
1322
5.62k
        else
1323
5.62k
            ::Serialize(s, txTo.vin[nInput].nSequence);
1324
6.56k
    }
interpreter.cpp:void (anonymous namespace)::CTransactionSignatureSerializer<CTransaction>::SerializeInput<HashWriter>(HashWriter&, unsigned int) const
Line
Count
Source
1306
6.56k
    void SerializeInput(S &s, unsigned int nInput) const {
1307
        // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1308
6.56k
        if (fAnyoneCanPay)
  Branch (1308:13): [True: 1.44k, False: 5.12k]
1309
1.44k
            nInput = nIn;
1310
        // Serialize the prevout
1311
6.56k
        ::Serialize(s, txTo.vin[nInput].prevout);
1312
        // Serialize the script
1313
6.56k
        if (nInput != nIn)
  Branch (1313:13): [True: 3.14k, False: 3.41k]
1314
            // Blank out other inputs' signatures
1315
3.14k
            ::Serialize(s, CScript());
1316
3.41k
        else
1317
3.41k
            SerializeScriptCode(s);
1318
        // Serialize the nSequence
1319
6.56k
        if (nInput != nIn && (fHashSingle || fHashNone))
  Branch (1319:13): [True: 3.14k, False: 3.41k]
  Branch (1319:31): [True: 393, False: 2.75k]
  Branch (1319:46): [True: 551, False: 2.20k]
1320
            // let the others update at will
1321
944
            ::Serialize(s, int32_t{0});
1322
5.62k
        else
1323
5.62k
            ::Serialize(s, txTo.vin[nInput].nSequence);
1324
6.56k
    }
Unexecuted instantiation: interpreter.cpp:void (anonymous namespace)::CTransactionSignatureSerializer<CMutableTransaction>::SerializeInput<HashWriter>(HashWriter&, unsigned int) const
1325
1326
    /** Serialize an output of txTo */
1327
    template<typename S>
1328
4.78k
    void SerializeOutput(S &s, unsigned int nOutput) const {
1329
4.78k
        if (fHashSingle && nOutput != nIn)
  Branch (1329:13): [True: 670, False: 4.11k]
  Branch (1329:28): [True: 198, False: 472]
  Branch (1329:13): [True: 0, False: 0]
  Branch (1329:28): [True: 0, False: 0]
1330
            // Do not lock-in the txout payee at other indices as txin
1331
198
            ::Serialize(s, CTxOut());
1332
4.59k
        else
1333
4.59k
            ::Serialize(s, txTo.vout[nOutput]);
1334
4.78k
    }
interpreter.cpp:void (anonymous namespace)::CTransactionSignatureSerializer<CTransaction>::SerializeOutput<HashWriter>(HashWriter&, unsigned int) const
Line
Count
Source
1328
4.78k
    void SerializeOutput(S &s, unsigned int nOutput) const {
1329
4.78k
        if (fHashSingle && nOutput != nIn)
  Branch (1329:13): [True: 670, False: 4.11k]
  Branch (1329:28): [True: 198, False: 472]
1330
            // Do not lock-in the txout payee at other indices as txin
1331
198
            ::Serialize(s, CTxOut());
1332
4.59k
        else
1333
4.59k
            ::Serialize(s, txTo.vout[nOutput]);
1334
4.78k
    }
Unexecuted instantiation: interpreter.cpp:void (anonymous namespace)::CTransactionSignatureSerializer<CMutableTransaction>::SerializeOutput<HashWriter>(HashWriter&, unsigned int) const
1335
1336
    /** Serialize txTo */
1337
    template<typename S>
1338
3.41k
    void Serialize(S &s) const {
1339
        // Serialize version
1340
3.41k
        ::Serialize(s, txTo.version);
1341
        // Serialize vin
1342
3.41k
        unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
  Branch (1342:32): [True: 1.44k, False: 1.97k]
  Branch (1342:32): [True: 0, False: 0]
1343
3.41k
        ::WriteCompactSize(s, nInputs);
1344
9.98k
        for (unsigned int nInput = 0; nInput < nInputs; nInput++)
  Branch (1344:39): [True: 6.56k, False: 3.41k]
  Branch (1344:39): [True: 0, False: 0]
1345
6.56k
             SerializeInput(s, nInput);
1346
        // Serialize vout
1347
3.41k
        unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
  Branch (1347:33): [True: 908, False: 2.50k]
  Branch (1347:50): [True: 472, False: 2.03k]
  Branch (1347:33): [True: 0, False: 0]
  Branch (1347:50): [True: 0, False: 0]
1348
3.41k
        ::WriteCompactSize(s, nOutputs);
1349
8.20k
        for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
  Branch (1349:40): [True: 4.78k, False: 3.41k]
  Branch (1349:40): [True: 0, False: 0]
1350
4.78k
             SerializeOutput(s, nOutput);
1351
        // Serialize nLockTime
1352
3.41k
        ::Serialize(s, txTo.nLockTime);
1353
3.41k
    }
interpreter.cpp:void (anonymous namespace)::CTransactionSignatureSerializer<CTransaction>::Serialize<HashWriter>(HashWriter&) const
Line
Count
Source
1338
3.41k
    void Serialize(S &s) const {
1339
        // Serialize version
1340
3.41k
        ::Serialize(s, txTo.version);
1341
        // Serialize vin
1342
3.41k
        unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
  Branch (1342:32): [True: 1.44k, False: 1.97k]
1343
3.41k
        ::WriteCompactSize(s, nInputs);
1344
9.98k
        for (unsigned int nInput = 0; nInput < nInputs; nInput++)
  Branch (1344:39): [True: 6.56k, False: 3.41k]
1345
6.56k
             SerializeInput(s, nInput);
1346
        // Serialize vout
1347
3.41k
        unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
  Branch (1347:33): [True: 908, False: 2.50k]
  Branch (1347:50): [True: 472, False: 2.03k]
1348
3.41k
        ::WriteCompactSize(s, nOutputs);
1349
8.20k
        for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
  Branch (1349:40): [True: 4.78k, False: 3.41k]
1350
4.78k
             SerializeOutput(s, nOutput);
1351
        // Serialize nLockTime
1352
3.41k
        ::Serialize(s, txTo.nLockTime);
1353
3.41k
    }
Unexecuted instantiation: interpreter.cpp:void (anonymous namespace)::CTransactionSignatureSerializer<CMutableTransaction>::Serialize<HashWriter>(HashWriter&) const
1354
};
1355
1356
/** Compute the (single) SHA256 of the concatenation of all prevouts of a tx. */
1357
template <class T>
1358
uint256 GetPrevoutsSHA256(const T& txTo)
1359
513k
{
1360
513k
    HashWriter ss{};
1361
540k
    for (const auto& txin : txTo.vin) {
  Branch (1361:27): [True: 540k, False: 513k]
  Branch (1361:27): [True: 0, False: 0]
1362
540k
        ss << txin.prevout;
1363
540k
    }
1364
513k
    return ss.GetSHA256();
1365
513k
}
interpreter.cpp:uint256 (anonymous namespace)::GetPrevoutsSHA256<CTransaction>(CTransaction const&)
Line
Count
Source
1359
513k
{
1360
513k
    HashWriter ss{};
1361
540k
    for (const auto& txin : txTo.vin) {
  Branch (1361:27): [True: 540k, False: 513k]
1362
540k
        ss << txin.prevout;
1363
540k
    }
1364
513k
    return ss.GetSHA256();
1365
513k
}
Unexecuted instantiation: interpreter.cpp:uint256 (anonymous namespace)::GetPrevoutsSHA256<CMutableTransaction>(CMutableTransaction const&)
1366
1367
/** Compute the (single) SHA256 of the concatenation of all nSequences of a tx. */
1368
template <class T>
1369
uint256 GetSequencesSHA256(const T& txTo)
1370
513k
{
1371
513k
    HashWriter ss{};
1372
540k
    for (const auto& txin : txTo.vin) {
  Branch (1372:27): [True: 540k, False: 513k]
  Branch (1372:27): [True: 0, False: 0]
1373
540k
        ss << txin.nSequence;
1374
540k
    }
1375
513k
    return ss.GetSHA256();
1376
513k
}
interpreter.cpp:uint256 (anonymous namespace)::GetSequencesSHA256<CTransaction>(CTransaction const&)
Line
Count
Source
1370
513k
{
1371
513k
    HashWriter ss{};
1372
540k
    for (const auto& txin : txTo.vin) {
  Branch (1372:27): [True: 540k, False: 513k]
1373
540k
        ss << txin.nSequence;
1374
540k
    }
1375
513k
    return ss.GetSHA256();
1376
513k
}
Unexecuted instantiation: interpreter.cpp:uint256 (anonymous namespace)::GetSequencesSHA256<CMutableTransaction>(CMutableTransaction const&)
1377
1378
/** Compute the (single) SHA256 of the concatenation of all txouts of a tx. */
1379
template <class T>
1380
uint256 GetOutputsSHA256(const T& txTo)
1381
513k
{
1382
513k
    HashWriter ss{};
1383
587k
    for (const auto& txout : txTo.vout) {
  Branch (1383:28): [True: 587k, False: 513k]
  Branch (1383:28): [True: 0, False: 0]
1384
587k
        ss << txout;
1385
587k
    }
1386
513k
    return ss.GetSHA256();
1387
513k
}
interpreter.cpp:uint256 (anonymous namespace)::GetOutputsSHA256<CTransaction>(CTransaction const&)
Line
Count
Source
1381
513k
{
1382
513k
    HashWriter ss{};
1383
587k
    for (const auto& txout : txTo.vout) {
  Branch (1383:28): [True: 587k, False: 513k]
1384
587k
        ss << txout;
1385
587k
    }
1386
513k
    return ss.GetSHA256();
1387
513k
}
Unexecuted instantiation: interpreter.cpp:uint256 (anonymous namespace)::GetOutputsSHA256<CMutableTransaction>(CMutableTransaction const&)
1388
1389
/** Compute the (single) SHA256 of the concatenation of all amounts spent by a tx. */
1390
uint256 GetSpentAmountsSHA256(const std::vector<CTxOut>& outputs_spent)
1391
9.62k
{
1392
9.62k
    HashWriter ss{};
1393
18.6k
    for (const auto& txout : outputs_spent) {
  Branch (1393:28): [True: 18.6k, False: 9.62k]
1394
18.6k
        ss << txout.nValue;
1395
18.6k
    }
1396
9.62k
    return ss.GetSHA256();
1397
9.62k
}
1398
1399
/** Compute the (single) SHA256 of the concatenation of all scriptPubKeys spent by a tx. */
1400
uint256 GetSpentScriptsSHA256(const std::vector<CTxOut>& outputs_spent)
1401
9.62k
{
1402
9.62k
    HashWriter ss{};
1403
18.6k
    for (const auto& txout : outputs_spent) {
  Branch (1403:28): [True: 18.6k, False: 9.62k]
1404
18.6k
        ss << txout.scriptPubKey;
1405
18.6k
    }
1406
9.62k
    return ss.GetSHA256();
1407
9.62k
}
1408
1409
1410
} // namespace
1411
1412
template <class T>
1413
void PrecomputedTransactionData::Init(const T& txTo, std::vector<CTxOut>&& spent_outputs, bool force)
1414
533k
{
1415
533k
    assert(!m_spent_outputs_ready);
  Branch (1415:5): [True: 533k, False: 0]
  Branch (1415:5): [True: 0, False: 0]
1416
1417
533k
    m_spent_outputs = std::move(spent_outputs);
1418
533k
    if (!m_spent_outputs.empty()) {
  Branch (1418:9): [True: 533k, False: 0]
  Branch (1418:9): [True: 0, False: 0]
1419
533k
        assert(m_spent_outputs.size() == txTo.vin.size());
  Branch (1419:9): [True: 533k, False: 0]
  Branch (1419:9): [True: 0, False: 0]
1420
533k
        m_spent_outputs_ready = true;
1421
533k
    }
1422
1423
    // Determine which precomputation-impacting features this transaction uses.
1424
533k
    bool uses_bip143_segwit = force;
1425
533k
    bool uses_bip341_taproot = force;
1426
1.09M
    for (size_t inpos = 0; inpos < txTo.vin.size() && !(uses_bip143_segwit && uses_bip341_taproot); ++inpos) {
  Branch (1426:28): [True: 561k, False: 531k]
  Branch (1426:57): [True: 17.7k, False: 543k]
  Branch (1426:79): [True: 0, False: 17.7k]
  Branch (1426:28): [True: 0, False: 0]
  Branch (1426:57): [True: 0, False: 0]
  Branch (1426:79): [True: 0, False: 0]
1427
561k
        if (!txTo.vin[inpos].scriptWitness.IsNull()) {
  Branch (1427:13): [True: 531k, False: 29.7k]
  Branch (1427:13): [True: 0, False: 0]
1428
531k
            if (m_spent_outputs_ready && m_spent_outputs[inpos].scriptPubKey.size() == 2 + WITNESS_V1_TAPROOT_SIZE &&
  Branch (1428:17): [True: 531k, False: 0]
  Branch (1428:42): [True: 531k, False: 481]
  Branch (1428:17): [True: 0, False: 0]
  Branch (1428:42): [True: 0, False: 0]
1429
531k
                m_spent_outputs[inpos].scriptPubKey[0] == OP_1) {
  Branch (1429:17): [True: 10.8k, False: 520k]
  Branch (1429:17): [True: 0, False: 0]
1430
                // Treat every witness-bearing spend with 34-byte scriptPubKey that starts with OP_1 as a Taproot
1431
                // spend. This only works if spent_outputs was provided as well, but if it wasn't, actual validation
1432
                // will fail anyway. Note that this branch may trigger for scriptPubKeys that aren't actually segwit
1433
                // but in that case validation will fail as SCRIPT_ERR_WITNESS_UNEXPECTED anyway.
1434
10.8k
                uses_bip341_taproot = true;
1435
520k
            } else {
1436
                // Treat every spend that's not known to native witness v1 as a Witness v0 spend. This branch may
1437
                // also be taken for unknown witness versions, but it is harmless, and being precise would require
1438
                // P2SH evaluation to find the redeemScript.
1439
520k
                uses_bip143_segwit = true;
1440
520k
            }
1441
531k
        }
1442
561k
        if (uses_bip341_taproot && uses_bip143_segwit) break; // No need to scan further if we already need all.
  Branch (1442:13): [True: 14.8k, False: 546k]
  Branch (1442:36): [True: 1.74k, False: 13.1k]
  Branch (1442:13): [True: 0, False: 0]
  Branch (1442:36): [True: 0, False: 0]
1443
561k
    }
1444
1445
533k
    if (uses_bip143_segwit || uses_bip341_taproot) {
  Branch (1445:9): [True: 505k, False: 27.6k]
  Branch (1445:31): [True: 7.87k, False: 19.7k]
  Branch (1445:9): [True: 0, False: 0]
  Branch (1445:31): [True: 0, False: 0]
1446
        // Computations shared between both sighash schemes.
1447
513k
        m_prevouts_single_hash = GetPrevoutsSHA256(txTo);
1448
513k
        m_sequences_single_hash = GetSequencesSHA256(txTo);
1449
513k
        m_outputs_single_hash = GetOutputsSHA256(txTo);
1450
513k
    }
1451
533k
    if (uses_bip143_segwit) {
  Branch (1451:9): [True: 505k, False: 27.6k]
  Branch (1451:9): [True: 0, False: 0]
1452
505k
        hashPrevouts = SHA256Uint256(m_prevouts_single_hash);
1453
505k
        hashSequence = SHA256Uint256(m_sequences_single_hash);
1454
505k
        hashOutputs = SHA256Uint256(m_outputs_single_hash);
1455
505k
        m_bip143_segwit_ready = true;
1456
505k
    }
1457
533k
    if (uses_bip341_taproot && m_spent_outputs_ready) {
  Branch (1457:9): [True: 9.62k, False: 523k]
  Branch (1457:32): [True: 9.62k, False: 0]
  Branch (1457:9): [True: 0, False: 0]
  Branch (1457:32): [True: 0, False: 0]
1458
9.62k
        m_spent_amounts_single_hash = GetSpentAmountsSHA256(m_spent_outputs);
1459
9.62k
        m_spent_scripts_single_hash = GetSpentScriptsSHA256(m_spent_outputs);
1460
9.62k
        m_bip341_taproot_ready = true;
1461
9.62k
    }
1462
533k
}
void PrecomputedTransactionData::Init<CTransaction>(CTransaction const&, std::vector<CTxOut, std::allocator<CTxOut> >&&, bool)
Line
Count
Source
1414
533k
{
1415
533k
    assert(!m_spent_outputs_ready);
  Branch (1415:5): [True: 533k, False: 0]
1416
1417
533k
    m_spent_outputs = std::move(spent_outputs);
1418
533k
    if (!m_spent_outputs.empty()) {
  Branch (1418:9): [True: 533k, False: 0]
1419
533k
        assert(m_spent_outputs.size() == txTo.vin.size());
  Branch (1419:9): [True: 533k, False: 0]
1420
533k
        m_spent_outputs_ready = true;
1421
533k
    }
1422
1423
    // Determine which precomputation-impacting features this transaction uses.
1424
533k
    bool uses_bip143_segwit = force;
1425
533k
    bool uses_bip341_taproot = force;
1426
1.09M
    for (size_t inpos = 0; inpos < txTo.vin.size() && !(uses_bip143_segwit && uses_bip341_taproot); ++inpos) {
  Branch (1426:28): [True: 561k, False: 531k]
  Branch (1426:57): [True: 17.7k, False: 543k]
  Branch (1426:79): [True: 0, False: 17.7k]
1427
561k
        if (!txTo.vin[inpos].scriptWitness.IsNull()) {
  Branch (1427:13): [True: 531k, False: 29.7k]
1428
531k
            if (m_spent_outputs_ready && m_spent_outputs[inpos].scriptPubKey.size() == 2 + WITNESS_V1_TAPROOT_SIZE &&
  Branch (1428:17): [True: 531k, False: 0]
  Branch (1428:42): [True: 531k, False: 481]
1429
531k
                m_spent_outputs[inpos].scriptPubKey[0] == OP_1) {
  Branch (1429:17): [True: 10.8k, False: 520k]
1430
                // Treat every witness-bearing spend with 34-byte scriptPubKey that starts with OP_1 as a Taproot
1431
                // spend. This only works if spent_outputs was provided as well, but if it wasn't, actual validation
1432
                // will fail anyway. Note that this branch may trigger for scriptPubKeys that aren't actually segwit
1433
                // but in that case validation will fail as SCRIPT_ERR_WITNESS_UNEXPECTED anyway.
1434
10.8k
                uses_bip341_taproot = true;
1435
520k
            } else {
1436
                // Treat every spend that's not known to native witness v1 as a Witness v0 spend. This branch may
1437
                // also be taken for unknown witness versions, but it is harmless, and being precise would require
1438
                // P2SH evaluation to find the redeemScript.
1439
520k
                uses_bip143_segwit = true;
1440
520k
            }
1441
531k
        }
1442
561k
        if (uses_bip341_taproot && uses_bip143_segwit) break; // No need to scan further if we already need all.
  Branch (1442:13): [True: 14.8k, False: 546k]
  Branch (1442:36): [True: 1.74k, False: 13.1k]
1443
561k
    }
1444
1445
533k
    if (uses_bip143_segwit || uses_bip341_taproot) {
  Branch (1445:9): [True: 505k, False: 27.6k]
  Branch (1445:31): [True: 7.87k, False: 19.7k]
1446
        // Computations shared between both sighash schemes.
1447
513k
        m_prevouts_single_hash = GetPrevoutsSHA256(txTo);
1448
513k
        m_sequences_single_hash = GetSequencesSHA256(txTo);
1449
513k
        m_outputs_single_hash = GetOutputsSHA256(txTo);
1450
513k
    }
1451
533k
    if (uses_bip143_segwit) {
  Branch (1451:9): [True: 505k, False: 27.6k]
1452
505k
        hashPrevouts = SHA256Uint256(m_prevouts_single_hash);
1453
505k
        hashSequence = SHA256Uint256(m_sequences_single_hash);
1454
505k
        hashOutputs = SHA256Uint256(m_outputs_single_hash);
1455
505k
        m_bip143_segwit_ready = true;
1456
505k
    }
1457
533k
    if (uses_bip341_taproot && m_spent_outputs_ready) {
  Branch (1457:9): [True: 9.62k, False: 523k]
  Branch (1457:32): [True: 9.62k, False: 0]
1458
9.62k
        m_spent_amounts_single_hash = GetSpentAmountsSHA256(m_spent_outputs);
1459
9.62k
        m_spent_scripts_single_hash = GetSpentScriptsSHA256(m_spent_outputs);
1460
9.62k
        m_bip341_taproot_ready = true;
1461
9.62k
    }
1462
533k
}
Unexecuted instantiation: void PrecomputedTransactionData::Init<CMutableTransaction>(CMutableTransaction const&, std::vector<CTxOut, std::allocator<CTxOut> >&&, bool)
1463
1464
template <class T>
1465
PrecomputedTransactionData::PrecomputedTransactionData(const T& txTo)
1466
0
{
1467
0
    Init(txTo, {});
1468
0
}
Unexecuted instantiation: PrecomputedTransactionData::PrecomputedTransactionData<CTransaction>(CTransaction const&)
Unexecuted instantiation: PrecomputedTransactionData::PrecomputedTransactionData<CMutableTransaction>(CMutableTransaction const&)
1469
1470
// explicit instantiation
1471
template void PrecomputedTransactionData::Init(const CTransaction& txTo, std::vector<CTxOut>&& spent_outputs, bool force);
1472
template void PrecomputedTransactionData::Init(const CMutableTransaction& txTo, std::vector<CTxOut>&& spent_outputs, bool force);
1473
template PrecomputedTransactionData::PrecomputedTransactionData(const CTransaction& txTo);
1474
template PrecomputedTransactionData::PrecomputedTransactionData(const CMutableTransaction& txTo);
1475
1476
const HashWriter HASHER_TAPSIGHASH{TaggedHash("TapSighash")};
1477
const HashWriter HASHER_TAPLEAF{TaggedHash("TapLeaf")};
1478
const HashWriter HASHER_TAPBRANCH{TaggedHash("TapBranch")};
1479
1480
static bool HandleMissingData(MissingDataBehavior mdb)
1481
0
{
1482
0
    switch (mdb) {
  Branch (1482:13): [True: 0, False: 0]
1483
0
    case MissingDataBehavior::ASSERT_FAIL:
  Branch (1483:5): [True: 0, False: 0]
1484
0
        assert(!"Missing data");
  Branch (1484:9): [Folded - Ignored]
1485
0
        break;
1486
0
    case MissingDataBehavior::FAIL:
  Branch (1486:5): [True: 0, False: 0]
1487
0
        return false;
1488
0
    }
1489
0
    assert(!"Unknown MissingDataBehavior value");
  Branch (1489:5): [Folded - Ignored]
1490
0
}
1491
1492
template<typename T>
1493
bool SignatureHashSchnorr(uint256& hash_out, ScriptExecutionData& execdata, const T& tx_to, uint32_t in_pos, uint8_t hash_type, SigVersion sigversion, const PrecomputedTransactionData& cache, MissingDataBehavior mdb)
1494
12.7k
{
1495
12.7k
    uint8_t ext_flag, key_version;
1496
12.7k
    switch (sigversion) {
1497
12.6k
    case SigVersion::TAPROOT:
  Branch (1497:5): [True: 12.6k, False: 188]
  Branch (1497:5): [True: 0, False: 0]
1498
12.6k
        ext_flag = 0;
1499
        // key_version is not used and left uninitialized.
1500
12.6k
        break;
1501
186
    case SigVersion::TAPSCRIPT:
  Branch (1501:5): [True: 186, False: 12.6k]
  Branch (1501:5): [True: 0, False: 0]
1502
186
        ext_flag = 1;
1503
        // key_version must be 0 for now, representing the current version of
1504
        // 32-byte public keys in the tapscript signature opcode execution.
1505
        // An upgradable public key version (with a size not 32-byte) may
1506
        // request a different key_version with a new sigversion.
1507
186
        key_version = 0;
1508
186
        break;
1509
0
    default:
  Branch (1509:5): [True: 0, False: 12.7k]
  Branch (1509:5): [True: 0, False: 0]
1510
0
        assert(false);
  Branch (1510:9): [Folded - Ignored]
  Branch (1510:9): [Folded - Ignored]
1511
12.7k
    }
1512
12.7k
    assert(in_pos < tx_to.vin.size());
  Branch (1512:5): [True: 12.7k, False: 18.4E]
  Branch (1512:5): [True: 0, False: 0]
1513
12.7k
    if (!(cache.m_bip341_taproot_ready && cache.m_spent_outputs_ready)) {
  Branch (1513:11): [True: 12.7k, False: 0]
  Branch (1513:43): [True: 12.7k, False: 18.4E]
  Branch (1513:11): [True: 0, False: 0]
  Branch (1513:43): [True: 0, False: 0]
1514
0
        return HandleMissingData(mdb);
1515
0
    }
1516
1517
12.7k
    HashWriter ss{HASHER_TAPSIGHASH};
1518
1519
    // Epoch
1520
12.7k
    static constexpr uint8_t EPOCH = 0;
1521
12.7k
    ss << EPOCH;
1522
1523
    // Hash type
1524
18.4E
    const uint8_t output_type = (hash_type == SIGHASH_DEFAULT) ? SIGHASH_ALL : (hash_type & SIGHASH_OUTPUT_MASK); // Default (no sighash byte) is equivalent to SIGHASH_ALL
  Branch (1524:33): [True: 12.7k, False: 18.4E]
  Branch (1524:33): [True: 0, False: 0]
1525
12.7k
    const uint8_t input_type = hash_type & SIGHASH_INPUT_MASK;
1526
12.7k
    if (!(hash_type <= 0x03 || (hash_type >= 0x81 && hash_type <= 0x83))) return false;
  Branch (1526:11): [True: 12.7k, False: 0]
  Branch (1526:33): [True: 0, False: 0]
  Branch (1526:54): [True: 0, False: 0]
  Branch (1526:11): [True: 0, False: 0]
  Branch (1526:33): [True: 0, False: 0]
  Branch (1526:54): [True: 0, False: 0]
1527
12.7k
    ss << hash_type;
1528
1529
    // Transaction level data
1530
12.7k
    ss << tx_to.version;
1531
12.7k
    ss << tx_to.nLockTime;
1532
12.7k
    if (input_type != SIGHASH_ANYONECANPAY) {
  Branch (1532:9): [True: 12.7k, False: 18.4E]
  Branch (1532:9): [True: 0, False: 0]
1533
12.7k
        ss << cache.m_prevouts_single_hash;
1534
12.7k
        ss << cache.m_spent_amounts_single_hash;
1535
12.7k
        ss << cache.m_spent_scripts_single_hash;
1536
12.7k
        ss << cache.m_sequences_single_hash;
1537
12.7k
    }
1538
12.7k
    if (output_type == SIGHASH_ALL) {
  Branch (1538:9): [True: 12.7k, False: 18.4E]
  Branch (1538:9): [True: 0, False: 0]
1539
12.7k
        ss << cache.m_outputs_single_hash;
1540
12.7k
    }
1541
1542
    // Data about the input/prevout being spent
1543
12.7k
    assert(execdata.m_annex_init);
  Branch (1543:5): [True: 12.7k, False: 18.4E]
  Branch (1543:5): [True: 0, False: 0]
1544
12.7k
    const bool have_annex = execdata.m_annex_present;
1545
12.7k
    const uint8_t spend_type = (ext_flag << 1) + (have_annex ? 1 : 0); // The low bit indicates whether an annex is present.
  Branch (1545:51): [True: 0, False: 12.7k]
  Branch (1545:51): [True: 0, False: 0]
1546
12.7k
    ss << spend_type;
1547
12.7k
    if (input_type == SIGHASH_ANYONECANPAY) {
  Branch (1547:9): [True: 0, False: 12.7k]
  Branch (1547:9): [True: 0, False: 0]
1548
0
        ss << tx_to.vin[in_pos].prevout;
1549
0
        ss << cache.m_spent_outputs[in_pos];
1550
0
        ss << tx_to.vin[in_pos].nSequence;
1551
12.7k
    } else {
1552
12.7k
        ss << in_pos;
1553
12.7k
    }
1554
12.7k
    if (have_annex) {
  Branch (1554:9): [True: 0, False: 12.7k]
  Branch (1554:9): [True: 0, False: 0]
1555
0
        ss << execdata.m_annex_hash;
1556
0
    }
1557
1558
    // Data about the output (if only one).
1559
12.7k
    if (output_type == SIGHASH_SINGLE) {
  Branch (1559:9): [True: 0, False: 12.7k]
  Branch (1559:9): [True: 0, False: 0]
1560
0
        if (in_pos >= tx_to.vout.size()) return false;
  Branch (1560:13): [True: 0, False: 0]
  Branch (1560:13): [True: 0, False: 0]
1561
0
        if (!execdata.m_output_hash) {
  Branch (1561:13): [True: 0, False: 0]
  Branch (1561:13): [True: 0, False: 0]
1562
0
            HashWriter sha_single_output{};
1563
0
            sha_single_output << tx_to.vout[in_pos];
1564
0
            execdata.m_output_hash = sha_single_output.GetSHA256();
1565
0
        }
1566
0
        ss << execdata.m_output_hash.value();
1567
0
    }
1568
1569
    // Additional data for BIP 342 signatures
1570
12.7k
    if (sigversion == SigVersion::TAPSCRIPT) {
  Branch (1570:9): [True: 186, False: 12.6k]
  Branch (1570:9): [True: 0, False: 0]
1571
186
        assert(execdata.m_tapleaf_hash_init);
  Branch (1571:9): [True: 186, False: 0]
  Branch (1571:9): [True: 0, False: 0]
1572
186
        ss << execdata.m_tapleaf_hash;
1573
186
        ss << key_version;
1574
186
        assert(execdata.m_codeseparator_pos_init);
  Branch (1574:9): [True: 186, False: 0]
  Branch (1574:9): [True: 0, False: 0]
1575
186
        ss << execdata.m_codeseparator_pos;
1576
186
    }
1577
1578
12.7k
    hash_out = ss.GetSHA256();
1579
12.7k
    return true;
1580
12.7k
}
bool SignatureHashSchnorr<CTransaction>(uint256&, ScriptExecutionData&, CTransaction const&, unsigned int, unsigned char, SigVersion, PrecomputedTransactionData const&, MissingDataBehavior)
Line
Count
Source
1494
12.7k
{
1495
12.7k
    uint8_t ext_flag, key_version;
1496
12.7k
    switch (sigversion) {
1497
12.6k
    case SigVersion::TAPROOT:
  Branch (1497:5): [True: 12.6k, False: 188]
1498
12.6k
        ext_flag = 0;
1499
        // key_version is not used and left uninitialized.
1500
12.6k
        break;
1501
186
    case SigVersion::TAPSCRIPT:
  Branch (1501:5): [True: 186, False: 12.6k]
1502
186
        ext_flag = 1;
1503
        // key_version must be 0 for now, representing the current version of
1504
        // 32-byte public keys in the tapscript signature opcode execution.
1505
        // An upgradable public key version (with a size not 32-byte) may
1506
        // request a different key_version with a new sigversion.
1507
186
        key_version = 0;
1508
186
        break;
1509
0
    default:
  Branch (1509:5): [True: 0, False: 12.7k]
1510
0
        assert(false);
  Branch (1510:9): [Folded - Ignored]
1511
12.7k
    }
1512
12.7k
    assert(in_pos < tx_to.vin.size());
  Branch (1512:5): [True: 12.7k, False: 18.4E]
1513
12.7k
    if (!(cache.m_bip341_taproot_ready && cache.m_spent_outputs_ready)) {
  Branch (1513:11): [True: 12.7k, False: 0]
  Branch (1513:43): [True: 12.7k, False: 18.4E]
1514
0
        return HandleMissingData(mdb);
1515
0
    }
1516
1517
12.7k
    HashWriter ss{HASHER_TAPSIGHASH};
1518
1519
    // Epoch
1520
12.7k
    static constexpr uint8_t EPOCH = 0;
1521
12.7k
    ss << EPOCH;
1522
1523
    // Hash type
1524
18.4E
    const uint8_t output_type = (hash_type == SIGHASH_DEFAULT) ? SIGHASH_ALL : (hash_type & SIGHASH_OUTPUT_MASK); // Default (no sighash byte) is equivalent to SIGHASH_ALL
  Branch (1524:33): [True: 12.7k, False: 18.4E]
1525
12.7k
    const uint8_t input_type = hash_type & SIGHASH_INPUT_MASK;
1526
12.7k
    if (!(hash_type <= 0x03 || (hash_type >= 0x81 && hash_type <= 0x83))) return false;
  Branch (1526:11): [True: 12.7k, False: 0]
  Branch (1526:33): [True: 0, False: 0]
  Branch (1526:54): [True: 0, False: 0]
1527
12.7k
    ss << hash_type;
1528
1529
    // Transaction level data
1530
12.7k
    ss << tx_to.version;
1531
12.7k
    ss << tx_to.nLockTime;
1532
12.7k
    if (input_type != SIGHASH_ANYONECANPAY) {
  Branch (1532:9): [True: 12.7k, False: 18.4E]
1533
12.7k
        ss << cache.m_prevouts_single_hash;
1534
12.7k
        ss << cache.m_spent_amounts_single_hash;
1535
12.7k
        ss << cache.m_spent_scripts_single_hash;
1536
12.7k
        ss << cache.m_sequences_single_hash;
1537
12.7k
    }
1538
12.7k
    if (output_type == SIGHASH_ALL) {
  Branch (1538:9): [True: 12.7k, False: 18.4E]
1539
12.7k
        ss << cache.m_outputs_single_hash;
1540
12.7k
    }
1541
1542
    // Data about the input/prevout being spent
1543
12.7k
    assert(execdata.m_annex_init);
  Branch (1543:5): [True: 12.7k, False: 18.4E]
1544
12.7k
    const bool have_annex = execdata.m_annex_present;
1545
12.7k
    const uint8_t spend_type = (ext_flag << 1) + (have_annex ? 1 : 0); // The low bit indicates whether an annex is present.
  Branch (1545:51): [True: 0, False: 12.7k]
1546
12.7k
    ss << spend_type;
1547
12.7k
    if (input_type == SIGHASH_ANYONECANPAY) {
  Branch (1547:9): [True: 0, False: 12.7k]
1548
0
        ss << tx_to.vin[in_pos].prevout;
1549
0
        ss << cache.m_spent_outputs[in_pos];
1550
0
        ss << tx_to.vin[in_pos].nSequence;
1551
12.7k
    } else {
1552
12.7k
        ss << in_pos;
1553
12.7k
    }
1554
12.7k
    if (have_annex) {
  Branch (1554:9): [True: 0, False: 12.7k]
1555
0
        ss << execdata.m_annex_hash;
1556
0
    }
1557
1558
    // Data about the output (if only one).
1559
12.7k
    if (output_type == SIGHASH_SINGLE) {
  Branch (1559:9): [True: 0, False: 12.7k]
1560
0
        if (in_pos >= tx_to.vout.size()) return false;
  Branch (1560:13): [True: 0, False: 0]
1561
0
        if (!execdata.m_output_hash) {
  Branch (1561:13): [True: 0, False: 0]
1562
0
            HashWriter sha_single_output{};
1563
0
            sha_single_output << tx_to.vout[in_pos];
1564
0
            execdata.m_output_hash = sha_single_output.GetSHA256();
1565
0
        }
1566
0
        ss << execdata.m_output_hash.value();
1567
0
    }
1568
1569
    // Additional data for BIP 342 signatures
1570
12.7k
    if (sigversion == SigVersion::TAPSCRIPT) {
  Branch (1570:9): [True: 186, False: 12.6k]
1571
186
        assert(execdata.m_tapleaf_hash_init);
  Branch (1571:9): [True: 186, False: 0]
1572
186
        ss << execdata.m_tapleaf_hash;
1573
186
        ss << key_version;
1574
186
        assert(execdata.m_codeseparator_pos_init);
  Branch (1574:9): [True: 186, False: 0]
1575
186
        ss << execdata.m_codeseparator_pos;
1576
186
    }
1577
1578
12.7k
    hash_out = ss.GetSHA256();
1579
12.7k
    return true;
1580
12.7k
}
Unexecuted instantiation: bool SignatureHashSchnorr<CMutableTransaction>(uint256&, ScriptExecutionData&, CMutableTransaction const&, unsigned int, unsigned char, SigVersion, PrecomputedTransactionData const&, MissingDataBehavior)
1581
1582
int SigHashCache::CacheIndex(int32_t hash_type) const noexcept
1583
6.83k
{
1584
    // Note that we do not distinguish between BASE and WITNESS_V0 to determine the cache index,
1585
    // because no input can simultaneously use both.
1586
6.83k
    return 3 * !!(hash_type & SIGHASH_ANYONECANPAY) +
1587
6.83k
           2 * ((hash_type & 0x1f) == SIGHASH_SINGLE) +
1588
6.83k
           1 * ((hash_type & 0x1f) == SIGHASH_NONE);
1589
6.83k
}
1590
1591
bool SigHashCache::Load(int32_t hash_type, const CScript& script_code, HashWriter& writer) const noexcept
1592
3.41k
{
1593
3.41k
    auto& entry = m_cache_entries[CacheIndex(hash_type)];
1594
3.41k
    if (entry.has_value()) {
  Branch (1594:9): [True: 0, False: 3.41k]
1595
0
        if (script_code == entry->first) {
  Branch (1595:13): [True: 0, False: 0]
1596
0
            writer = HashWriter(entry->second);
1597
0
            return true;
1598
0
        }
1599
0
    }
1600
3.41k
    return false;
1601
3.41k
}
1602
1603
void SigHashCache::Store(int32_t hash_type, const CScript& script_code, const HashWriter& writer) noexcept
1604
3.41k
{
1605
3.41k
    auto& entry = m_cache_entries[CacheIndex(hash_type)];
1606
3.41k
    entry.emplace(script_code, writer);
1607
3.41k
}
1608
1609
template <class T>
1610
uint256 SignatureHash(const CScript& scriptCode, const T& txTo, unsigned int nIn, int32_t nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache, SigHashCache* sighash_cache)
1611
3.67k
{
1612
3.67k
    assert(nIn < txTo.vin.size());
  Branch (1612:5): [True: 3.67k, False: 0]
  Branch (1612:5): [True: 0, False: 0]
1613
1614
3.67k
    if (sigversion != SigVersion::WITNESS_V0) {
  Branch (1614:9): [True: 3.67k, False: 0]
  Branch (1614:9): [True: 0, False: 0]
1615
        // Check for invalid use of SIGHASH_SINGLE
1616
3.67k
        if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
  Branch (1616:13): [True: 730, False: 2.94k]
  Branch (1616:13): [True: 0, False: 0]
1617
730
            if (nIn >= txTo.vout.size()) {
  Branch (1617:17): [True: 258, False: 472]
  Branch (1617:17): [True: 0, False: 0]
1618
                //  nOut out of range
1619
258
                return uint256::ONE;
1620
258
            }
1621
730
        }
1622
3.67k
    }
1623
1624
3.41k
    HashWriter ss{};
1625
1626
    // Try to compute using cached SHA256 midstate.
1627
3.41k
    if (sighash_cache && sighash_cache->Load(nHashType, scriptCode, ss)) {
  Branch (1627:9): [True: 3.41k, False: 1]
  Branch (1627:26): [True: 0, False: 3.41k]
  Branch (1627:9): [True: 0, False: 0]
  Branch (1627:26): [True: 0, False: 0]
1628
        // Add sighash type and hash.
1629
0
        ss << nHashType;
1630
0
        return ss.GetHash();
1631
0
    }
1632
1633
3.41k
    if (sigversion == SigVersion::WITNESS_V0) {
  Branch (1633:9): [True: 0, False: 3.41k]
  Branch (1633:9): [True: 0, False: 0]
1634
0
        uint256 hashPrevouts;
1635
0
        uint256 hashSequence;
1636
0
        uint256 hashOutputs;
1637
0
        const bool cacheready = cache && cache->m_bip143_segwit_ready;
  Branch (1637:33): [True: 0, False: 0]
  Branch (1637:42): [True: 0, False: 0]
  Branch (1637:33): [True: 0, False: 0]
  Branch (1637:42): [True: 0, False: 0]
1638
1639
0
        if (!(nHashType & SIGHASH_ANYONECANPAY)) {
  Branch (1639:13): [True: 0, False: 0]
  Branch (1639:13): [True: 0, False: 0]
1640
0
            hashPrevouts = cacheready ? cache->hashPrevouts : SHA256Uint256(GetPrevoutsSHA256(txTo));
  Branch (1640:28): [True: 0, False: 0]
  Branch (1640:28): [True: 0, False: 0]
1641
0
        }
1642
1643
0
        if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
  Branch (1643:13): [True: 0, False: 0]
  Branch (1643:52): [True: 0, False: 0]
  Branch (1643:92): [True: 0, False: 0]
  Branch (1643:13): [True: 0, False: 0]
  Branch (1643:52): [True: 0, False: 0]
  Branch (1643:92): [True: 0, False: 0]
1644
0
            hashSequence = cacheready ? cache->hashSequence : SHA256Uint256(GetSequencesSHA256(txTo));
  Branch (1644:28): [True: 0, False: 0]
  Branch (1644:28): [True: 0, False: 0]
1645
0
        }
1646
1647
0
        if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
  Branch (1647:13): [True: 0, False: 0]
  Branch (1647:53): [True: 0, False: 0]
  Branch (1647:13): [True: 0, False: 0]
  Branch (1647:53): [True: 0, False: 0]
1648
0
            hashOutputs = cacheready ? cache->hashOutputs : SHA256Uint256(GetOutputsSHA256(txTo));
  Branch (1648:27): [True: 0, False: 0]
  Branch (1648:27): [True: 0, False: 0]
1649
0
        } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
  Branch (1649:20): [True: 0, False: 0]
  Branch (1649:60): [True: 0, False: 0]
  Branch (1649:20): [True: 0, False: 0]
  Branch (1649:60): [True: 0, False: 0]
1650
0
            HashWriter inner_ss{};
1651
0
            inner_ss << txTo.vout[nIn];
1652
0
            hashOutputs = inner_ss.GetHash();
1653
0
        }
1654
1655
        // Version
1656
0
        ss << txTo.version;
1657
        // Input prevouts/nSequence (none/all, depending on flags)
1658
0
        ss << hashPrevouts;
1659
0
        ss << hashSequence;
1660
        // The input being signed (replacing the scriptSig with scriptCode + amount)
1661
        // The prevout may already be contained in hashPrevout, and the nSequence
1662
        // may already be contain in hashSequence.
1663
0
        ss << txTo.vin[nIn].prevout;
1664
0
        ss << scriptCode;
1665
0
        ss << amount;
1666
0
        ss << txTo.vin[nIn].nSequence;
1667
        // Outputs (none/one/all, depending on flags)
1668
0
        ss << hashOutputs;
1669
        // Locktime
1670
0
        ss << txTo.nLockTime;
1671
3.41k
    } else {
1672
        // Wrapper to serialize only the necessary parts of the transaction being signed
1673
3.41k
        CTransactionSignatureSerializer<T> txTmp(txTo, scriptCode, nIn, nHashType);
1674
1675
        // Serialize
1676
3.41k
        ss << txTmp;
1677
3.41k
    }
1678
1679
    // If a cache object was provided, store the midstate there.
1680
3.41k
    if (sighash_cache != nullptr) {
  Branch (1680:9): [True: 3.41k, False: 0]
  Branch (1680:9): [True: 0, False: 0]
1681
3.41k
        sighash_cache->Store(nHashType, scriptCode, ss);
1682
3.41k
    }
1683
1684
    // Add sighash type and hash.
1685
3.41k
    ss << nHashType;
1686
3.41k
    return ss.GetHash();
1687
3.41k
}
uint256 SignatureHash<CTransaction>(CScript const&, CTransaction const&, unsigned int, int, long const&, SigVersion, PrecomputedTransactionData const*, SigHashCache*)
Line
Count
Source
1611
3.67k
{
1612
3.67k
    assert(nIn < txTo.vin.size());
  Branch (1612:5): [True: 3.67k, False: 0]
1613
1614
3.67k
    if (sigversion != SigVersion::WITNESS_V0) {
  Branch (1614:9): [True: 3.67k, False: 0]
1615
        // Check for invalid use of SIGHASH_SINGLE
1616
3.67k
        if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
  Branch (1616:13): [True: 730, False: 2.94k]
1617
730
            if (nIn >= txTo.vout.size()) {
  Branch (1617:17): [True: 258, False: 472]
1618
                //  nOut out of range
1619
258
                return uint256::ONE;
1620
258
            }
1621
730
        }
1622
3.67k
    }
1623
1624
3.41k
    HashWriter ss{};
1625
1626
    // Try to compute using cached SHA256 midstate.
1627
3.41k
    if (sighash_cache && sighash_cache->Load(nHashType, scriptCode, ss)) {
  Branch (1627:9): [True: 3.41k, False: 1]
  Branch (1627:26): [True: 0, False: 3.41k]
1628
        // Add sighash type and hash.
1629
0
        ss << nHashType;
1630
0
        return ss.GetHash();
1631
0
    }
1632
1633
3.41k
    if (sigversion == SigVersion::WITNESS_V0) {
  Branch (1633:9): [True: 0, False: 3.41k]
1634
0
        uint256 hashPrevouts;
1635
0
        uint256 hashSequence;
1636
0
        uint256 hashOutputs;
1637
0
        const bool cacheready = cache && cache->m_bip143_segwit_ready;
  Branch (1637:33): [True: 0, False: 0]
  Branch (1637:42): [True: 0, False: 0]
1638
1639
0
        if (!(nHashType & SIGHASH_ANYONECANPAY)) {
  Branch (1639:13): [True: 0, False: 0]
1640
0
            hashPrevouts = cacheready ? cache->hashPrevouts : SHA256Uint256(GetPrevoutsSHA256(txTo));
  Branch (1640:28): [True: 0, False: 0]
1641
0
        }
1642
1643
0
        if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
  Branch (1643:13): [True: 0, False: 0]
  Branch (1643:52): [True: 0, False: 0]
  Branch (1643:92): [True: 0, False: 0]
1644
0
            hashSequence = cacheready ? cache->hashSequence : SHA256Uint256(GetSequencesSHA256(txTo));
  Branch (1644:28): [True: 0, False: 0]
1645
0
        }
1646
1647
0
        if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
  Branch (1647:13): [True: 0, False: 0]
  Branch (1647:53): [True: 0, False: 0]
1648
0
            hashOutputs = cacheready ? cache->hashOutputs : SHA256Uint256(GetOutputsSHA256(txTo));
  Branch (1648:27): [True: 0, False: 0]
1649
0
        } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
  Branch (1649:20): [True: 0, False: 0]
  Branch (1649:60): [True: 0, False: 0]
1650
0
            HashWriter inner_ss{};
1651
0
            inner_ss << txTo.vout[nIn];
1652
0
            hashOutputs = inner_ss.GetHash();
1653
0
        }
1654
1655
        // Version
1656
0
        ss << txTo.version;
1657
        // Input prevouts/nSequence (none/all, depending on flags)
1658
0
        ss << hashPrevouts;
1659
0
        ss << hashSequence;
1660
        // The input being signed (replacing the scriptSig with scriptCode + amount)
1661
        // The prevout may already be contained in hashPrevout, and the nSequence
1662
        // may already be contain in hashSequence.
1663
0
        ss << txTo.vin[nIn].prevout;
1664
0
        ss << scriptCode;
1665
0
        ss << amount;
1666
0
        ss << txTo.vin[nIn].nSequence;
1667
        // Outputs (none/one/all, depending on flags)
1668
0
        ss << hashOutputs;
1669
        // Locktime
1670
0
        ss << txTo.nLockTime;
1671
3.41k
    } else {
1672
        // Wrapper to serialize only the necessary parts of the transaction being signed
1673
3.41k
        CTransactionSignatureSerializer<T> txTmp(txTo, scriptCode, nIn, nHashType);
1674
1675
        // Serialize
1676
3.41k
        ss << txTmp;
1677
3.41k
    }
1678
1679
    // If a cache object was provided, store the midstate there.
1680
3.41k
    if (sighash_cache != nullptr) {
  Branch (1680:9): [True: 3.41k, False: 0]
1681
3.41k
        sighash_cache->Store(nHashType, scriptCode, ss);
1682
3.41k
    }
1683
1684
    // Add sighash type and hash.
1685
3.41k
    ss << nHashType;
1686
3.41k
    return ss.GetHash();
1687
3.41k
}
Unexecuted instantiation: uint256 SignatureHash<CMutableTransaction>(CScript const&, CMutableTransaction const&, unsigned int, int, long const&, SigVersion, PrecomputedTransactionData const*, SigHashCache*)
1688
1689
template <class T>
1690
bool GenericTransactionSignatureChecker<T>::VerifyECDSASignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
1691
2.78k
{
1692
2.78k
    return pubkey.Verify(sighash, vchSig);
1693
2.78k
}
GenericTransactionSignatureChecker<CTransaction>::VerifyECDSASignature(std::vector<unsigned char, std::allocator<unsigned char> > const&, CPubKey const&, uint256 const&) const
Line
Count
Source
1691
2.78k
{
1692
2.78k
    return pubkey.Verify(sighash, vchSig);
1693
2.78k
}
Unexecuted instantiation: GenericTransactionSignatureChecker<CMutableTransaction>::VerifyECDSASignature(std::vector<unsigned char, std::allocator<unsigned char> > const&, CPubKey const&, uint256 const&) const
1694
1695
template <class T>
1696
bool GenericTransactionSignatureChecker<T>::VerifySchnorrSignature(std::span<const unsigned char> sig, const XOnlyPubKey& pubkey, const uint256& sighash) const
1697
7.97k
{
1698
7.97k
    return pubkey.VerifySchnorr(sighash, sig);
1699
7.97k
}
GenericTransactionSignatureChecker<CTransaction>::VerifySchnorrSignature(std::span<unsigned char const, 18446744073709551615ul>, XOnlyPubKey const&, uint256 const&) const
Line
Count
Source
1697
7.97k
{
1698
7.97k
    return pubkey.VerifySchnorr(sighash, sig);
1699
7.97k
}
Unexecuted instantiation: GenericTransactionSignatureChecker<CMutableTransaction>::VerifySchnorrSignature(std::span<unsigned char const, 18446744073709551615ul>, XOnlyPubKey const&, uint256 const&) const
1700
1701
template <class T>
1702
bool GenericTransactionSignatureChecker<T>::CheckECDSASignature(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
1703
3.80k
{
1704
3.80k
    CPubKey pubkey(vchPubKey);
1705
3.80k
    if (!pubkey.IsValid())
  Branch (1705:9): [True: 125, False: 3.68k]
  Branch (1705:9): [True: 0, False: 0]
1706
125
        return false;
1707
1708
    // Hash type is one byte tacked on to the end of the signature
1709
3.68k
    std::vector<unsigned char> vchSig(vchSigIn);
1710
3.68k
    if (vchSig.empty())
  Branch (1710:9): [True: 5, False: 3.67k]
  Branch (1710:9): [True: 0, False: 0]
1711
5
        return false;
1712
3.67k
    int nHashType = vchSig.back();
1713
3.67k
    vchSig.pop_back();
1714
1715
    // Witness sighashes need the amount.
1716
3.67k
    if (sigversion == SigVersion::WITNESS_V0 && amount < 0) return HandleMissingData(m_mdb);
  Branch (1716:9): [True: 0, False: 3.67k]
  Branch (1716:49): [True: 0, False: 0]
  Branch (1716:9): [True: 0, False: 0]
  Branch (1716:49): [True: 0, False: 0]
1717
1718
3.67k
    uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata, &m_sighash_cache);
1719
1720
3.67k
    if (!VerifyECDSASignature(vchSig, pubkey, sighash))
  Branch (1720:9): [True: 1.47k, False: 2.20k]
  Branch (1720:9): [True: 0, False: 0]
1721
1.47k
        return false;
1722
1723
2.20k
    return true;
1724
3.67k
}
GenericTransactionSignatureChecker<CTransaction>::CheckECDSASignature(std::vector<unsigned char, std::allocator<unsigned char> > const&, std::vector<unsigned char, std::allocator<unsigned char> > const&, CScript const&, SigVersion) const
Line
Count
Source
1703
3.80k
{
1704
3.80k
    CPubKey pubkey(vchPubKey);
1705
3.80k
    if (!pubkey.IsValid())
  Branch (1705:9): [True: 125, False: 3.68k]
1706
125
        return false;
1707
1708
    // Hash type is one byte tacked on to the end of the signature
1709
3.68k
    std::vector<unsigned char> vchSig(vchSigIn);
1710
3.68k
    if (vchSig.empty())
  Branch (1710:9): [True: 5, False: 3.67k]
1711
5
        return false;
1712
3.67k
    int nHashType = vchSig.back();
1713
3.67k
    vchSig.pop_back();
1714
1715
    // Witness sighashes need the amount.
1716
3.67k
    if (sigversion == SigVersion::WITNESS_V0 && amount < 0) return HandleMissingData(m_mdb);
  Branch (1716:9): [True: 0, False: 3.67k]
  Branch (1716:49): [True: 0, False: 0]
1717
1718
3.67k
    uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata, &m_sighash_cache);
1719
1720
3.67k
    if (!VerifyECDSASignature(vchSig, pubkey, sighash))
  Branch (1720:9): [True: 1.47k, False: 2.20k]
1721
1.47k
        return false;
1722
1723
2.20k
    return true;
1724
3.67k
}
Unexecuted instantiation: GenericTransactionSignatureChecker<CMutableTransaction>::CheckECDSASignature(std::vector<unsigned char, std::allocator<unsigned char> > const&, std::vector<unsigned char, std::allocator<unsigned char> > const&, CScript const&, SigVersion) const
1725
1726
template <class T>
1727
bool GenericTransactionSignatureChecker<T>::CheckSchnorrSignature(std::span<const unsigned char> sig, std::span<const unsigned char> pubkey_in, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror) const
1728
12.8k
{
1729
12.8k
    assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
  Branch (1729:5): [True: 12.6k, False: 186]
  Branch (1729:5): [True: 186, False: 0]
  Branch (1729:5): [True: 12.8k, False: 0]
  Branch (1729:5): [True: 0, False: 0]
  Branch (1729:5): [True: 0, False: 0]
  Branch (1729:5): [True: 0, False: 0]
1730
    // Schnorr signatures have 32-byte public keys. The caller is responsible for enforcing this.
1731
12.8k
    assert(pubkey_in.size() == 32);
  Branch (1731:5): [True: 12.8k, False: 2]
  Branch (1731:5): [True: 0, False: 0]
1732
    // Note that in Tapscript evaluation, empty signatures are treated specially (invalid signature that does not
1733
    // abort script execution). This is implemented in EvalChecksigTapscript, which won't invoke
1734
    // CheckSchnorrSignature in that case. In other contexts, they are invalid like every other signature with
1735
    // size different from 64 or 65.
1736
12.8k
    if (sig.size() != 64 && sig.size() != 65) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_SIZE);
  Branch (1736:9): [True: 12, False: 12.7k]
  Branch (1736:29): [True: 12, False: 0]
  Branch (1736:9): [True: 0, False: 0]
  Branch (1736:29): [True: 0, False: 0]
1737
1738
12.7k
    XOnlyPubKey pubkey{pubkey_in};
1739
1740
12.7k
    uint8_t hashtype = SIGHASH_DEFAULT;
1741
12.7k
    if (sig.size() == 65) {
  Branch (1741:9): [True: 0, False: 12.7k]
  Branch (1741:9): [True: 0, False: 0]
1742
0
        hashtype = SpanPopBack(sig);
1743
0
        if (hashtype == SIGHASH_DEFAULT) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_HASHTYPE);
  Branch (1743:13): [True: 0, False: 0]
  Branch (1743:13): [True: 0, False: 0]
1744
0
    }
1745
12.7k
    uint256 sighash;
1746
12.7k
    if (!this->txdata) return HandleMissingData(m_mdb);
  Branch (1746:9): [True: 0, False: 12.7k]
  Branch (1746:9): [True: 0, False: 0]
1747
12.7k
    if (!SignatureHashSchnorr(sighash, execdata, *txTo, nIn, hashtype, sigversion, *this->txdata, m_mdb)) {
  Branch (1747:9): [True: 0, False: 12.7k]
  Branch (1747:9): [True: 0, False: 0]
1748
0
        return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_HASHTYPE);
1749
0
    }
1750
12.7k
    if (!VerifySchnorrSignature(sig, pubkey, sighash)) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG);
  Branch (1750:9): [True: 186, False: 12.6k]
  Branch (1750:9): [True: 0, False: 0]
1751
12.6k
    return true;
1752
12.7k
}
GenericTransactionSignatureChecker<CTransaction>::CheckSchnorrSignature(std::span<unsigned char const, 18446744073709551615ul>, std::span<unsigned char const, 18446744073709551615ul>, SigVersion, ScriptExecutionData&, ScriptError_t*) const
Line
Count
Source
1728
12.8k
{
1729
12.8k
    assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
  Branch (1729:5): [True: 12.6k, False: 186]
  Branch (1729:5): [True: 186, False: 0]
  Branch (1729:5): [True: 12.8k, False: 0]
1730
    // Schnorr signatures have 32-byte public keys. The caller is responsible for enforcing this.
1731
12.8k
    assert(pubkey_in.size() == 32);
  Branch (1731:5): [True: 12.8k, False: 2]
1732
    // Note that in Tapscript evaluation, empty signatures are treated specially (invalid signature that does not
1733
    // abort script execution). This is implemented in EvalChecksigTapscript, which won't invoke
1734
    // CheckSchnorrSignature in that case. In other contexts, they are invalid like every other signature with
1735
    // size different from 64 or 65.
1736
12.8k
    if (sig.size() != 64 && sig.size() != 65) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_SIZE);
  Branch (1736:9): [True: 12, False: 12.7k]
  Branch (1736:29): [True: 12, False: 0]
1737
1738
12.7k
    XOnlyPubKey pubkey{pubkey_in};
1739
1740
12.7k
    uint8_t hashtype = SIGHASH_DEFAULT;
1741
12.7k
    if (sig.size() == 65) {
  Branch (1741:9): [True: 0, False: 12.7k]
1742
0
        hashtype = SpanPopBack(sig);
1743
0
        if (hashtype == SIGHASH_DEFAULT) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_HASHTYPE);
  Branch (1743:13): [True: 0, False: 0]
1744
0
    }
1745
12.7k
    uint256 sighash;
1746
12.7k
    if (!this->txdata) return HandleMissingData(m_mdb);
  Branch (1746:9): [True: 0, False: 12.7k]
1747
12.7k
    if (!SignatureHashSchnorr(sighash, execdata, *txTo, nIn, hashtype, sigversion, *this->txdata, m_mdb)) {
  Branch (1747:9): [True: 0, False: 12.7k]
1748
0
        return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_HASHTYPE);
1749
0
    }
1750
12.7k
    if (!VerifySchnorrSignature(sig, pubkey, sighash)) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG);
  Branch (1750:9): [True: 186, False: 12.6k]
1751
12.6k
    return true;
1752
12.7k
}
Unexecuted instantiation: GenericTransactionSignatureChecker<CMutableTransaction>::CheckSchnorrSignature(std::span<unsigned char const, 18446744073709551615ul>, std::span<unsigned char const, 18446744073709551615ul>, SigVersion, ScriptExecutionData&, ScriptError_t*) const
1753
1754
template <class T>
1755
bool GenericTransactionSignatureChecker<T>::CheckLockTime(const CScriptNum& nLockTime) const
1756
167
{
1757
    // There are two kinds of nLockTime: lock-by-blockheight
1758
    // and lock-by-blocktime, distinguished by whether
1759
    // nLockTime < LOCKTIME_THRESHOLD.
1760
    //
1761
    // We want to compare apples to apples, so fail the script
1762
    // unless the type of nLockTime being tested is the same as
1763
    // the nLockTime in the transaction.
1764
167
    if (!(
  Branch (1764:9): [True: 30, False: 137]
  Branch (1764:9): [True: 0, False: 0]
1765
167
        (txTo->nLockTime <  LOCKTIME_THRESHOLD && nLockTime <  LOCKTIME_THRESHOLD) ||
  Branch (1765:10): [True: 132, False: 35]
  Branch (1765:51): [True: 117, False: 15]
  Branch (1765:10): [True: 0, False: 0]
  Branch (1765:51): [True: 0, False: 0]
1766
167
        (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
  Branch (1766:10): [True: 35, False: 15]
  Branch (1766:51): [True: 20, False: 15]
  Branch (1766:10): [True: 0, False: 0]
  Branch (1766:51): [True: 0, False: 0]
1767
167
    ))
1768
30
        return false;
1769
1770
    // Now that we know we're comparing apples-to-apples, the
1771
    // comparison is a simple numeric one.
1772
137
    if (nLockTime > (int64_t)txTo->nLockTime)
  Branch (1772:9): [True: 16, False: 121]
  Branch (1772:9): [True: 0, False: 0]
1773
16
        return false;
1774
1775
    // Finally the nLockTime feature can be disabled in IsFinalTx()
1776
    // and thus CHECKLOCKTIMEVERIFY bypassed if every txin has
1777
    // been finalized by setting nSequence to maxint. The
1778
    // transaction would be allowed into the blockchain, making
1779
    // the opcode ineffective.
1780
    //
1781
    // Testing if this vin is not final is sufficient to
1782
    // prevent this condition. Alternatively we could test all
1783
    // inputs, but testing just this input minimizes the data
1784
    // required to prove correct CHECKLOCKTIMEVERIFY execution.
1785
121
    if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
  Branch (1785:9): [True: 15, False: 106]
  Branch (1785:9): [True: 0, False: 0]
1786
15
        return false;
1787
1788
106
    return true;
1789
121
}
GenericTransactionSignatureChecker<CTransaction>::CheckLockTime(CScriptNum const&) const
Line
Count
Source
1756
167
{
1757
    // There are two kinds of nLockTime: lock-by-blockheight
1758
    // and lock-by-blocktime, distinguished by whether
1759
    // nLockTime < LOCKTIME_THRESHOLD.
1760
    //
1761
    // We want to compare apples to apples, so fail the script
1762
    // unless the type of nLockTime being tested is the same as
1763
    // the nLockTime in the transaction.
1764
167
    if (!(
  Branch (1764:9): [True: 30, False: 137]
1765
167
        (txTo->nLockTime <  LOCKTIME_THRESHOLD && nLockTime <  LOCKTIME_THRESHOLD) ||
  Branch (1765:10): [True: 132, False: 35]
  Branch (1765:51): [True: 117, False: 15]
1766
167
        (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
  Branch (1766:10): [True: 35, False: 15]
  Branch (1766:51): [True: 20, False: 15]
1767
167
    ))
1768
30
        return false;
1769
1770
    // Now that we know we're comparing apples-to-apples, the
1771
    // comparison is a simple numeric one.
1772
137
    if (nLockTime > (int64_t)txTo->nLockTime)
  Branch (1772:9): [True: 16, False: 121]
1773
16
        return false;
1774
1775
    // Finally the nLockTime feature can be disabled in IsFinalTx()
1776
    // and thus CHECKLOCKTIMEVERIFY bypassed if every txin has
1777
    // been finalized by setting nSequence to maxint. The
1778
    // transaction would be allowed into the blockchain, making
1779
    // the opcode ineffective.
1780
    //
1781
    // Testing if this vin is not final is sufficient to
1782
    // prevent this condition. Alternatively we could test all
1783
    // inputs, but testing just this input minimizes the data
1784
    // required to prove correct CHECKLOCKTIMEVERIFY execution.
1785
121
    if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
  Branch (1785:9): [True: 15, False: 106]
1786
15
        return false;
1787
1788
106
    return true;
1789
121
}
Unexecuted instantiation: GenericTransactionSignatureChecker<CMutableTransaction>::CheckLockTime(CScriptNum const&) const
1790
1791
template <class T>
1792
bool GenericTransactionSignatureChecker<T>::CheckSequence(const CScriptNum& nSequence) const
1793
123
{
1794
    // Relative lock times are supported by comparing the passed
1795
    // in operand to the sequence number of the input.
1796
123
    const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
1797
1798
    // Fail if the transaction's version number is not set high
1799
    // enough to trigger BIP 68 rules.
1800
123
    if (txTo->version < 2)
  Branch (1800:9): [True: 53, False: 70]
  Branch (1800:9): [True: 0, False: 0]
1801
53
        return false;
1802
1803
    // Sequence numbers with their most significant bit set are not
1804
    // consensus constrained. Testing that the transaction's sequence
1805
    // number do not have this bit set prevents using this property
1806
    // to get around a CHECKSEQUENCEVERIFY check.
1807
70
    if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
  Branch (1807:9): [True: 70, False: 0]
  Branch (1807:9): [True: 0, False: 0]
1808
70
        return false;
1809
1810
    // Mask off any bits that do not have consensus-enforced meaning
1811
    // before doing the integer comparisons
1812
0
    const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
1813
0
    const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
1814
0
    const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
1815
1816
    // There are two kinds of nSequence: lock-by-blockheight
1817
    // and lock-by-blocktime, distinguished by whether
1818
    // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
1819
    //
1820
    // We want to compare apples to apples, so fail the script
1821
    // unless the type of nSequenceMasked being tested is the same as
1822
    // the nSequenceMasked in the transaction.
1823
0
    if (!(
  Branch (1823:9): [True: 0, False: 0]
  Branch (1823:9): [True: 0, False: 0]
1824
0
        (txToSequenceMasked <  CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked <  CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
  Branch (1824:10): [True: 0, False: 0]
  Branch (1824:70): [True: 0, False: 0]
  Branch (1824:10): [True: 0, False: 0]
  Branch (1824:70): [True: 0, False: 0]
1825
0
        (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
  Branch (1825:10): [True: 0, False: 0]
  Branch (1825:70): [True: 0, False: 0]
  Branch (1825:10): [True: 0, False: 0]
  Branch (1825:70): [True: 0, False: 0]
1826
0
    )) {
1827
0
        return false;
1828
0
    }
1829
1830
    // Now that we know we're comparing apples-to-apples, the
1831
    // comparison is a simple numeric one.
1832
0
    if (nSequenceMasked > txToSequenceMasked)
  Branch (1832:9): [True: 0, False: 0]
  Branch (1832:9): [True: 0, False: 0]
1833
0
        return false;
1834
1835
0
    return true;
1836
0
}
GenericTransactionSignatureChecker<CTransaction>::CheckSequence(CScriptNum const&) const
Line
Count
Source
1793
123
{
1794
    // Relative lock times are supported by comparing the passed
1795
    // in operand to the sequence number of the input.
1796
123
    const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
1797
1798
    // Fail if the transaction's version number is not set high
1799
    // enough to trigger BIP 68 rules.
1800
123
    if (txTo->version < 2)
  Branch (1800:9): [True: 53, False: 70]
1801
53
        return false;
1802
1803
    // Sequence numbers with their most significant bit set are not
1804
    // consensus constrained. Testing that the transaction's sequence
1805
    // number do not have this bit set prevents using this property
1806
    // to get around a CHECKSEQUENCEVERIFY check.
1807
70
    if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
  Branch (1807:9): [True: 70, False: 0]
1808
70
        return false;
1809
1810
    // Mask off any bits that do not have consensus-enforced meaning
1811
    // before doing the integer comparisons
1812
0
    const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
1813
0
    const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
1814
0
    const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
1815
1816
    // There are two kinds of nSequence: lock-by-blockheight
1817
    // and lock-by-blocktime, distinguished by whether
1818
    // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
1819
    //
1820
    // We want to compare apples to apples, so fail the script
1821
    // unless the type of nSequenceMasked being tested is the same as
1822
    // the nSequenceMasked in the transaction.
1823
0
    if (!(
  Branch (1823:9): [True: 0, False: 0]
1824
0
        (txToSequenceMasked <  CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked <  CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
  Branch (1824:10): [True: 0, False: 0]
  Branch (1824:70): [True: 0, False: 0]
1825
0
        (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
  Branch (1825:10): [True: 0, False: 0]
  Branch (1825:70): [True: 0, False: 0]
1826
0
    )) {
1827
0
        return false;
1828
0
    }
1829
1830
    // Now that we know we're comparing apples-to-apples, the
1831
    // comparison is a simple numeric one.
1832
0
    if (nSequenceMasked > txToSequenceMasked)
  Branch (1832:9): [True: 0, False: 0]
1833
0
        return false;
1834
1835
0
    return true;
1836
0
}
Unexecuted instantiation: GenericTransactionSignatureChecker<CMutableTransaction>::CheckSequence(CScriptNum const&) const
1837
1838
// explicit instantiation
1839
template class GenericTransactionSignatureChecker<CTransaction>;
1840
template class GenericTransactionSignatureChecker<CMutableTransaction>;
1841
1842
static bool ExecuteWitnessScript(const std::span<const valtype>& stack_span, const CScript& exec_script, script_verify_flags flags, SigVersion sigversion, const BaseSignatureChecker& checker, ScriptExecutionData& execdata, ScriptError* serror)
1843
909k
{
1844
909k
    std::vector<valtype> stack{stack_span.begin(), stack_span.end()};
1845
1846
909k
    if (sigversion == SigVersion::TAPSCRIPT) {
  Branch (1846:9): [True: 601, False: 908k]
1847
        // OP_SUCCESSx processing overrides everything, including stack element size limits
1848
601
        CScript::const_iterator pc = exec_script.begin();
1849
1.16k
        while (pc < exec_script.end()) {
  Branch (1849:16): [True: 787, False: 380]
1850
787
            opcodetype opcode;
1851
787
            if (!exec_script.GetOp(pc, opcode)) {
  Branch (1851:17): [True: 0, False: 787]
1852
                // Note how this condition would not be reached if an unknown OP_SUCCESSx was found
1853
0
                return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1854
0
            }
1855
            // New opcodes will be listed here. May use a different sigversion to modify existing opcodes.
1856
787
            if (IsOpSuccess(opcode)) {
  Branch (1856:17): [True: 221, False: 566]
1857
221
                if (flags & SCRIPT_VERIFY_DISCOURAGE_OP_SUCCESS) {
  Branch (1857:21): [True: 169, False: 52]
1858
169
                    return set_error(serror, SCRIPT_ERR_DISCOURAGE_OP_SUCCESS);
1859
169
                }
1860
52
                return set_success(serror);
1861
221
            }
1862
787
        }
1863
1864
        // Tapscript enforces initial stack size limits (altstack is empty here)
1865
380
        if (stack.size() > MAX_STACK_SIZE) return set_error(serror, SCRIPT_ERR_STACK_SIZE);
  Branch (1865:13): [True: 0, False: 380]
1866
380
    }
1867
1868
    // Disallow stack item size > MAX_SCRIPT_ELEMENT_SIZE in witness stack
1869
908k
    for (const valtype& elem : stack) {
  Branch (1869:30): [True: 4.94k, False: 908k]
1870
4.94k
        if (elem.size() > MAX_SCRIPT_ELEMENT_SIZE) return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
  Branch (1870:13): [True: 0, False: 4.94k]
1871
4.94k
    }
1872
1873
    // Run the script interpreter.
1874
908k
    if (!EvalScript(stack, exec_script, flags, checker, sigversion, execdata, serror)) return false;
  Branch (1874:9): [True: 13.0k, False: 895k]
1875
1876
    // Scripts inside witness implicitly require cleanstack behaviour
1877
895k
    if (stack.size() != 1) return set_error(serror, SCRIPT_ERR_CLEANSTACK);
  Branch (1877:9): [True: 2.07k, False: 893k]
1878
893k
    if (!CastToBool(stack.back())) return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
  Branch (1878:9): [True: 258, False: 893k]
1879
893k
    return true;
1880
893k
}
1881
1882
uint256 ComputeTapleafHash(uint8_t leaf_version, std::span<const unsigned char> script)
1883
1.52k
{
1884
1.52k
    return (HashWriter{HASHER_TAPLEAF} << leaf_version << CompactSizeWriter(script.size()) << script).GetSHA256();
1885
1.52k
}
1886
1887
uint256 ComputeTapbranchHash(std::span<const unsigned char> a, std::span<const unsigned char> b)
1888
1.72k
{
1889
1.72k
    HashWriter ss_branch{HASHER_TAPBRANCH};
1890
1.72k
    if (std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end())) {
  Branch (1890:9): [True: 753, False: 970]
1891
753
        ss_branch << a << b;
1892
970
    } else {
1893
970
        ss_branch << b << a;
1894
970
    }
1895
1.72k
    return ss_branch.GetSHA256();
1896
1.72k
}
1897
1898
uint256 ComputeTaprootMerkleRoot(std::span<const unsigned char> control, const uint256& tapleaf_hash)
1899
1.52k
{
1900
1.52k
    assert(control.size() >= TAPROOT_CONTROL_BASE_SIZE);
  Branch (1900:5): [True: 1.52k, False: 0]
1901
1.52k
    assert(control.size() <= TAPROOT_CONTROL_MAX_SIZE);
  Branch (1901:5): [True: 1.52k, False: 0]
1902
1.52k
    assert((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE == 0);
  Branch (1902:5): [True: 1.52k, False: 0]
1903
1904
1.52k
    const int path_len = (control.size() - TAPROOT_CONTROL_BASE_SIZE) / TAPROOT_CONTROL_NODE_SIZE;
1905
1.52k
    uint256 k = tapleaf_hash;
1906
3.24k
    for (int i = 0; i < path_len; ++i) {
  Branch (1906:21): [True: 1.72k, False: 1.52k]
1907
1.72k
        std::span node{std::span{control}.subspan(TAPROOT_CONTROL_BASE_SIZE + TAPROOT_CONTROL_NODE_SIZE * i, TAPROOT_CONTROL_NODE_SIZE)};
1908
1.72k
        k = ComputeTapbranchHash(k, node);
1909
1.72k
    }
1910
1.52k
    return k;
1911
1.52k
}
1912
1913
static bool VerifyTaprootCommitment(const std::vector<unsigned char>& control, const std::vector<unsigned char>& program, const uint256& tapleaf_hash)
1914
1.52k
{
1915
1.52k
    assert(control.size() >= TAPROOT_CONTROL_BASE_SIZE);
  Branch (1915:5): [True: 1.52k, False: 0]
1916
1.52k
    assert(program.size() >= uint256::size());
  Branch (1916:5): [True: 1.52k, False: 0]
1917
    //! The internal pubkey (x-only, so no Y coordinate parity).
1918
1.52k
    const XOnlyPubKey p{std::span{control}.subspan(1, TAPROOT_CONTROL_BASE_SIZE - 1)};
1919
    //! The output pubkey (taken from the scriptPubKey).
1920
1.52k
    const XOnlyPubKey q{program};
1921
    // Compute the Merkle root from the leaf and the provided path.
1922
1.52k
    const uint256 merkle_root = ComputeTaprootMerkleRoot(control, tapleaf_hash);
1923
    // Verify that the output pubkey matches the tweaked internal pubkey, after correcting for parity.
1924
1.52k
    return q.CheckTapTweak(p, merkle_root, control[0] & 1);
1925
1.52k
}
1926
1927
static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion, const std::vector<unsigned char>& program, script_verify_flags flags, const BaseSignatureChecker& checker, ScriptError* serror, bool is_p2sh)
1928
950k
{
1929
950k
    CScript exec_script; //!< Actually executed script (last stack item in P2WSH; implied P2PKH script in P2WPKH; leaf script in P2TR)
1930
950k
    std::span stack{witness.stack};
1931
950k
    ScriptExecutionData execdata;
1932
1933
950k
    if (witversion == 0) {
  Branch (1933:9): [True: 913k, False: 36.3k]
1934
913k
        if (program.size() == WITNESS_V0_SCRIPTHASH_SIZE) {
  Branch (1934:13): [True: 913k, False: 336]
1935
            // BIP141 P2WSH: 32-byte witness v0 program (which encodes SHA256(script))
1936
913k
            if (stack.size() == 0) {
  Branch (1936:17): [True: 5.45k, False: 908k]
1937
5.45k
                return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
1938
5.45k
            }
1939
908k
            const valtype& script_bytes = SpanPopBack(stack);
1940
908k
            exec_script = CScript(script_bytes.begin(), script_bytes.end());
1941
908k
            uint256 hash_exec_script;
1942
908k
            CSHA256().Write(exec_script.data(), exec_script.size()).Finalize(hash_exec_script.begin());
1943
908k
            if (memcmp(hash_exec_script.begin(), program.data(), 32)) {
  Branch (1943:17): [True: 0, False: 908k]
1944
0
                return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
1945
0
            }
1946
908k
            return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
1947
908k
        } else if (program.size() == WITNESS_V0_KEYHASH_SIZE) {
  Branch (1947:20): [True: 336, False: 0]
1948
            // BIP141 P2WPKH: 20-byte witness v0 program (which encodes Hash160(pubkey))
1949
336
            if (stack.size() != 2) {
  Branch (1949:17): [True: 58, False: 278]
1950
58
                return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH); // 2 items in witness
1951
58
            }
1952
278
            exec_script << OP_DUP << OP_HASH160 << program << OP_EQUALVERIFY << OP_CHECKSIG;
1953
278
            return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
1954
336
        } else {
1955
0
            return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH);
1956
0
        }
1957
913k
    } else if (witversion == 1 && program.size() == WITNESS_V1_TAPROOT_SIZE && !is_p2sh) {
  Branch (1957:16): [True: 36.2k, False: 17]
  Branch (1957:35): [True: 14.6k, False: 21.6k]
  Branch (1957:80): [True: 14.6k, False: 0]
1958
        // BIP341 Taproot: 32-byte non-P2SH witness v1 program (which encodes a P2C-tweaked pubkey)
1959
14.6k
        if (!(flags & SCRIPT_VERIFY_TAPROOT)) return set_success(serror);
  Branch (1959:13): [True: 0, False: 14.6k]
1960
14.6k
        if (stack.size() == 0) return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
  Branch (1960:13): [True: 444, False: 14.1k]
1961
14.1k
        if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) {
  Branch (1961:13): [True: 1.57k, False: 12.6k]
  Branch (1961:34): [True: 1.57k, False: 0]
  Branch (1961:59): [True: 12, False: 1.56k]
1962
            // Drop annex (this is non-standard; see IsWitnessStandard)
1963
12
            const valtype& annex = SpanPopBack(stack);
1964
12
            execdata.m_annex_hash = (HashWriter{} << annex).GetSHA256();
1965
12
            execdata.m_annex_present = true;
1966
14.1k
        } else {
1967
14.1k
            execdata.m_annex_present = false;
1968
14.1k
        }
1969
14.1k
        execdata.m_annex_init = true;
1970
14.1k
        if (stack.size() == 1) {
  Branch (1970:13): [True: 12.6k, False: 1.56k]
1971
            // Key path spending (stack size is 1 after removing optional annex)
1972
12.6k
            if (!checker.CheckSchnorrSignature(stack.front(), program, SigVersion::TAPROOT, execdata, serror)) {
  Branch (1972:17): [True: 12, False: 12.6k]
1973
12
                return false; // serror is set
1974
12
            }
1975
12.6k
            return set_success(serror);
1976
12.6k
        } else {
1977
            // Script path spending (stack size is >1 after removing optional annex)
1978
1.56k
            const valtype& control = SpanPopBack(stack);
1979
1.56k
            const valtype& script = SpanPopBack(stack);
1980
1.56k
            if (control.size() < TAPROOT_CONTROL_BASE_SIZE || control.size() > TAPROOT_CONTROL_MAX_SIZE || ((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE) != 0) {
  Branch (1980:17): [True: 0, False: 1.56k]
  Branch (1980:63): [True: 0, False: 1.56k]
  Branch (1980:108): [True: 39, False: 1.52k]
1981
39
                return set_error(serror, SCRIPT_ERR_TAPROOT_WRONG_CONTROL_SIZE);
1982
39
            }
1983
1.52k
            execdata.m_tapleaf_hash = ComputeTapleafHash(control[0] & TAPROOT_LEAF_MASK, script);
1984
1.52k
            if (!VerifyTaprootCommitment(control, program, execdata.m_tapleaf_hash)) {
  Branch (1984:17): [True: 28, False: 1.49k]
1985
28
                return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
1986
28
            }
1987
1.49k
            execdata.m_tapleaf_hash_init = true;
1988
1.49k
            if ((control[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) {
  Branch (1988:17): [True: 601, False: 896]
1989
                // Tapscript (leaf version 0xc0)
1990
601
                exec_script = CScript(script.begin(), script.end());
1991
601
                execdata.m_validation_weight_left = ::GetSerializeSize(witness.stack) + VALIDATION_WEIGHT_OFFSET;
1992
601
                execdata.m_validation_weight_left_init = true;
1993
601
                return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::TAPSCRIPT, checker, execdata, serror);
1994
601
            }
1995
896
            if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION) {
  Branch (1995:17): [True: 620, False: 276]
1996
620
                return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION);
1997
620
            }
1998
276
            return set_success(serror);
1999
896
        }
2000
21.6k
    } else if (!is_p2sh && CScript::IsPayToAnchor(witversion, program)) {
  Branch (2000:16): [True: 21.6k, False: 15]
  Branch (2000:28): [True: 21.6k, False: 0]
2001
21.6k
        return true;
2002
21.6k
    } else {
2003
15
        if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
  Branch (2003:13): [True: 0, False: 15]
2004
0
            return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM);
2005
0
        }
2006
        // Other version/size/p2sh combinations return true for future softfork compatibility
2007
15
        return true;
2008
15
    }
2009
    // There is intentionally no return statement here, to be able to use "control reaches end of non-void function" warnings to detect gaps in the logic above.
2010
950k
}
2011
2012
bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, script_verify_flags flags, const BaseSignatureChecker& checker, ScriptError* serror)
2013
957k
{
2014
957k
    static const CScriptWitness emptyWitness;
2015
957k
    if (witness == nullptr) {
  Branch (2015:9): [True: 0, False: 957k]
2016
0
        witness = &emptyWitness;
2017
0
    }
2018
957k
    bool hadWitness = false;
2019
2020
957k
    set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
2021
2022
957k
    if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
  Branch (2022:9): [True: 0, False: 957k]
  Branch (2022:9): [True: 0, False: 957k]
  Branch (2022:53): [True: 0, False: 0]
2023
0
        return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
2024
0
    }
2025
2026
    // scriptSig and scriptPubKey must be evaluated sequentially on the same stack
2027
    // rather than being simply concatenated (see CVE-2010-5141)
2028
957k
    std::vector<std::vector<unsigned char> > stack, stackCopy;
2029
957k
    if (!EvalScript(stack, scriptSig, flags, checker, SigVersion::BASE, serror))
  Branch (2029:9): [True: 39, False: 957k]
2030
        // serror is set
2031
39
        return false;
2032
957k
    if (flags & SCRIPT_VERIFY_P2SH)
  Branch (2032:9): [True: 957k, False: 31]
2033
957k
        stackCopy = stack;
2034
957k
    if (!EvalScript(stack, scriptPubKey, flags, checker, SigVersion::BASE, serror))
  Branch (2034:9): [True: 2.40k, False: 955k]
2035
        // serror is set
2036
2.40k
        return false;
2037
955k
    if (stack.empty())
  Branch (2037:9): [True: 0, False: 955k]
2038
0
        return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
2039
955k
    if (CastToBool(stack.back()) == false)
  Branch (2039:9): [True: 90, False: 955k]
2040
90
        return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
2041
2042
    // Bare witness programs
2043
955k
    int witnessversion;
2044
955k
    std::vector<unsigned char> witnessprogram;
2045
955k
    if (flags & SCRIPT_VERIFY_WITNESS) {
  Branch (2045:9): [True: 955k, False: 13]
2046
955k
        if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
  Branch (2046:13): [True: 950k, False: 5.14k]
2047
950k
            hadWitness = true;
2048
950k
            if (scriptSig.size() != 0) {
  Branch (2048:17): [True: 0, False: 950k]
2049
                // The scriptSig must be _exactly_ CScript(), otherwise we reintroduce malleability.
2050
0
                return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED);
2051
0
            }
2052
950k
            if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror, /*is_p2sh=*/false)) {
  Branch (2052:17): [True: 22.1k, False: 928k]
2053
22.1k
                return false;
2054
22.1k
            }
2055
            // Bypass the cleanstack check at the end. The actual stack is obviously not clean
2056
            // for witness programs.
2057
928k
            stack.resize(1);
2058
928k
        }
2059
955k
    }
2060
2061
    // Additional validation for spend-to-script-hash transactions:
2062
933k
    if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
  Branch (2062:9): [True: 933k, False: 6]
  Branch (2062:9): [True: 2.95k, False: 930k]
  Branch (2062:41): [True: 2.95k, False: 930k]
2063
2.95k
    {
2064
        // scriptSig must be literals-only or validation fails
2065
2.95k
        if (!scriptSig.IsPushOnly())
  Branch (2065:13): [True: 0, False: 2.95k]
2066
0
            return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
2067
2068
        // Restore stack.
2069
2.95k
        swap(stack, stackCopy);
2070
2071
        // stack cannot be empty here, because if it was the
2072
        // P2SH  HASH <> EQUAL  scriptPubKey would be evaluated with
2073
        // an empty stack and the EvalScript above would return false.
2074
2.95k
        assert(!stack.empty());
  Branch (2074:9): [True: 2.95k, False: 0]
2075
2076
2.95k
        const valtype& pubKeySerialized = stack.back();
2077
2.95k
        CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
2078
2.95k
        popstack(stack);
2079
2080
2.95k
        if (!EvalScript(stack, pubKey2, flags, checker, SigVersion::BASE, serror))
  Branch (2080:13): [True: 1.15k, False: 1.80k]
2081
            // serror is set
2082
1.15k
            return false;
2083
1.80k
        if (stack.empty())
  Branch (2083:13): [True: 16, False: 1.78k]
2084
16
            return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
2085
1.78k
        if (!CastToBool(stack.back()))
  Branch (2085:13): [True: 46, False: 1.74k]
2086
46
            return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
2087
2088
        // P2SH witness program
2089
1.74k
        if (flags & SCRIPT_VERIFY_WITNESS) {
  Branch (2089:13): [True: 1.74k, False: 0]
2090
1.74k
            if (pubKey2.IsWitnessProgram(witnessversion, witnessprogram)) {
  Branch (2090:17): [True: 94, False: 1.64k]
2091
94
                hadWitness = true;
2092
94
                if (scriptSig != CScript() << std::vector<unsigned char>(pubKey2.begin(), pubKey2.end())) {
  Branch (2092:21): [True: 94, False: 0]
2093
                    // The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we
2094
                    // reintroduce malleability.
2095
94
                    return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED_P2SH);
2096
94
                }
2097
0
                if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror, /*is_p2sh=*/true)) {
  Branch (2097:21): [True: 0, False: 0]
2098
0
                    return false;
2099
0
                }
2100
                // Bypass the cleanstack check at the end. The actual stack is obviously not clean
2101
                // for witness programs.
2102
0
                stack.resize(1);
2103
0
            }
2104
1.74k
        }
2105
1.74k
    }
2106
2107
    // The CLEANSTACK check is only performed after potential P2SH evaluation,
2108
    // as the non-P2SH evaluation of a P2SH script will obviously not result in
2109
    // a clean stack (the P2SH inputs remain). The same holds for witness evaluation.
2110
931k
    if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
  Branch (2110:9): [True: 429k, False: 502k]
2111
        // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
2112
        // would be possible, which is not a softfork (and P2SH should be one).
2113
429k
        assert((flags & SCRIPT_VERIFY_P2SH) != 0);
  Branch (2113:9): [True: 429k, False: 0]
2114
429k
        assert((flags & SCRIPT_VERIFY_WITNESS) != 0);
  Branch (2114:9): [True: 429k, False: 0]
2115
429k
        if (stack.size() != 1) {
  Branch (2115:13): [True: 688, False: 428k]
2116
688
            return set_error(serror, SCRIPT_ERR_CLEANSTACK);
2117
688
        }
2118
429k
    }
2119
2120
931k
    if (flags & SCRIPT_VERIFY_WITNESS) {
  Branch (2120:9): [True: 931k, False: 69]
2121
        // We can't check for correct unexpected witness data if P2SH was off, so require
2122
        // that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be
2123
        // possible, which is not a softfork.
2124
931k
        assert((flags & SCRIPT_VERIFY_P2SH) != 0);
  Branch (2124:9): [True: 931k, False: 83]
2125
931k
        if (!hadWitness && !witness->IsNull()) {
  Branch (2125:13): [True: 3.16k, False: 927k]
  Branch (2125:28): [True: 0, False: 3.16k]
2126
0
            return set_error(serror, SCRIPT_ERR_WITNESS_UNEXPECTED);
2127
0
        }
2128
931k
    }
2129
2130
931k
    return set_success(serror);
2131
931k
}
2132
2133
size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& witprogram, const CScriptWitness& witness)
2134
686k
{
2135
686k
    if (witversion == 0) {
  Branch (2135:9): [True: 638k, False: 48.0k]
2136
638k
        if (witprogram.size() == WITNESS_V0_KEYHASH_SIZE)
  Branch (2136:13): [True: 1.68k, False: 636k]
2137
1.68k
            return 1;
2138
2139
636k
        if (witprogram.size() == WITNESS_V0_SCRIPTHASH_SIZE && witness.stack.size() > 0) {
  Branch (2139:13): [True: 636k, False: 120]
  Branch (2139:64): [True: 622k, False: 13.9k]
2140
622k
            CScript subscript(witness.stack.back().begin(), witness.stack.back().end());
2141
622k
            return subscript.GetSigOpCount(true);
2142
622k
        }
2143
636k
    }
2144
2145
    // Future flags may be implemented here.
2146
62.1k
    return 0;
2147
686k
}
2148
2149
size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness& witness, script_verify_flags flags)
2150
708k
{
2151
708k
    if ((flags & SCRIPT_VERIFY_WITNESS) == 0) {
  Branch (2151:9): [True: 0, False: 708k]
2152
0
        return 0;
2153
0
    }
2154
708k
    assert((flags & SCRIPT_VERIFY_P2SH) != 0);
  Branch (2154:5): [True: 708k, False: 0]
2155
2156
708k
    int witnessversion;
2157
708k
    std::vector<unsigned char> witnessprogram;
2158
708k
    if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
  Branch (2158:9): [True: 686k, False: 22.2k]
2159
686k
        return WitnessSigOps(witnessversion, witnessprogram, witness);
2160
686k
    }
2161
2162
22.2k
    if (scriptPubKey.IsPayToScriptHash() && scriptSig.IsPushOnly()) {
  Branch (2162:9): [True: 6.63k, False: 15.6k]
  Branch (2162:45): [True: 6.63k, False: 0]
2163
6.63k
        CScript::const_iterator pc = scriptSig.begin();
2164
6.63k
        std::vector<unsigned char> data;
2165
23.2k
        while (pc < scriptSig.end()) {
  Branch (2165:16): [True: 16.6k, False: 6.63k]
2166
16.6k
            opcodetype opcode;
2167
16.6k
            scriptSig.GetOp(pc, opcode, data);
2168
16.6k
        }
2169
6.63k
        CScript subscript(data.begin(), data.end());
2170
6.63k
        if (subscript.IsWitnessProgram(witnessversion, witnessprogram)) {
  Branch (2170:13): [True: 158, False: 6.48k]
2171
158
            return WitnessSigOps(witnessversion, witnessprogram, witness);
2172
158
        }
2173
6.63k
    }
2174
2175
22.1k
    return 0;
2176
22.2k
}
2177
2178
const std::map<std::string, script_verify_flag_name>& ScriptFlagNamesToEnum()
2179
0
{
2180
0
#define FLAG_NAME(flag) {std::string(#flag), SCRIPT_VERIFY_##flag}
2181
0
    static const std::map<std::string, script_verify_flag_name> g_names_to_enum{
2182
0
        FLAG_NAME(P2SH),
2183
0
        FLAG_NAME(STRICTENC),
2184
0
        FLAG_NAME(DERSIG),
2185
0
        FLAG_NAME(LOW_S),
2186
0
        FLAG_NAME(SIGPUSHONLY),
2187
0
        FLAG_NAME(MINIMALDATA),
2188
0
        FLAG_NAME(NULLDUMMY),
2189
0
        FLAG_NAME(DISCOURAGE_UPGRADABLE_NOPS),
2190
0
        FLAG_NAME(CLEANSTACK),
2191
0
        FLAG_NAME(MINIMALIF),
2192
0
        FLAG_NAME(NULLFAIL),
2193
0
        FLAG_NAME(CHECKLOCKTIMEVERIFY),
2194
0
        FLAG_NAME(CHECKSEQUENCEVERIFY),
2195
0
        FLAG_NAME(WITNESS),
2196
0
        FLAG_NAME(DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM),
2197
0
        FLAG_NAME(WITNESS_PUBKEYTYPE),
2198
0
        FLAG_NAME(CONST_SCRIPTCODE),
2199
0
        FLAG_NAME(TAPROOT),
2200
0
        FLAG_NAME(DISCOURAGE_UPGRADABLE_PUBKEYTYPE),
2201
0
        FLAG_NAME(DISCOURAGE_OP_SUCCESS),
2202
0
        FLAG_NAME(DISCOURAGE_UPGRADABLE_TAPROOT_VERSION),
2203
0
    };
2204
0
#undef FLAG_NAME
2205
0
    return g_names_to_enum;
2206
0
}
2207
2208
std::vector<std::string> GetScriptFlagNames(script_verify_flags flags)
2209
0
{
2210
0
    std::vector<std::string> res;
2211
0
    if (flags == SCRIPT_VERIFY_NONE) {
  Branch (2211:9): [True: 0, False: 0]
2212
0
        return res;
2213
0
    }
2214
0
    script_verify_flags leftover = flags;
2215
0
    for (const auto& [name, flag] : ScriptFlagNamesToEnum()) {
  Branch (2215:35): [True: 0, False: 0]
2216
0
        if ((flags & flag) != 0) {
  Branch (2216:13): [True: 0, False: 0]
2217
0
            res.push_back(name);
2218
0
            leftover &= ~flag;
2219
0
        }
2220
0
    }
2221
0
    if (leftover != 0) {
  Branch (2221:9): [True: 0, False: 0]
2222
0
        res.push_back(strprintf("0x%08x", leftover.as_int()));
2223
0
    }
2224
0
    return res;
2225
0
}