Coverage Report

Created: 2026-07-20 20:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/script/sign.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/sign.h>
7
8
#include <addresstype.h>
9
#include <coins.h>
10
#include <consensus/amount.h>
11
#include <hash.h>
12
#include <key.h>
13
#include <musig.h>
14
#include <policy/policy.h>
15
#include <prevector.h>
16
#include <primitives/transaction.h>
17
#include <script/keyorigin.h>
18
#include <script/miniscript.h>
19
#include <script/script.h>
20
#include <script/script_error.h>
21
#include <script/signingprovider.h>
22
#include <script/solver.h>
23
#include <script/verify_flags.h>
24
#include <serialize.h>
25
#include <uint256.h>
26
#include <util/check.h>
27
#include <util/translation.h>
28
#include <util/vector.h>
29
30
#include <algorithm>
31
#include <cstddef>
32
#include <functional>
33
#include <iterator>
34
#include <span>
35
#include <string>
36
37
typedef std::vector<unsigned char> valtype;
38
39
MutableTransactionSignatureCreator::MutableTransactionSignatureCreator(const CMutableTransaction& tx, unsigned int input_idx, const CAmount& amount, const SignOptions& options)
40
5.66k
    : m_txto{tx}, nIn{input_idx}, m_options{options}, amount{amount}, checker{&m_txto, nIn, amount, MissingDataBehavior::FAIL},
41
5.66k
      m_txdata(nullptr)
42
5.66k
{
43
5.66k
}
44
45
MutableTransactionSignatureCreator::MutableTransactionSignatureCreator(const CMutableTransaction& tx, unsigned int input_idx, const CAmount& amount, const PrecomputedTransactionData* txdata, const SignOptions& options)
46
63.2k
    : m_txto{tx}, nIn{input_idx}, m_options{options}, amount{amount},
47
63.2k
      checker{txdata ? MutableTransactionSignatureChecker{&m_txto, nIn, amount, *txdata, MissingDataBehavior::FAIL} :
48
63.2k
                       MutableTransactionSignatureChecker{&m_txto, nIn, amount, MissingDataBehavior::FAIL}},
49
63.2k
      m_txdata(txdata)
50
63.2k
{
51
63.2k
}
52
53
bool MutableTransactionSignatureCreator::CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& address, const CScript& scriptCode, SigVersion sigversion) const
54
31.8k
{
55
31.8k
    assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0);
56
57
31.8k
    CKey key;
58
31.8k
    if (!provider.GetKey(address, key))
59
15.4k
        return false;
60
61
    // Signing with uncompressed keys is disabled in witness scripts
62
16.4k
    if (sigversion == SigVersion::WITNESS_V0 && !key.IsCompressed())
63
4
        return false;
64
65
    // Signing without known amount does not work in witness scripts.
66
16.4k
    if (sigversion == SigVersion::WITNESS_V0 && !MoneyRange(amount)) return false;
67
68
    // BASE/WITNESS_V0 signatures don't support explicit SIGHASH_DEFAULT, use SIGHASH_ALL instead.
69
16.4k
    const int hashtype = m_options.sighash_type == SIGHASH_DEFAULT ? SIGHASH_ALL : m_options.sighash_type;
70
71
16.4k
    uint256 hash = SignatureHash(scriptCode, m_txto, nIn, hashtype, amount, sigversion, m_txdata);
72
16.4k
    if (!key.Sign(hash, vchSig))
73
0
        return false;
74
16.4k
    vchSig.push_back((unsigned char)hashtype);
75
16.4k
    return true;
76
16.4k
}
77
78
std::optional<uint256> MutableTransactionSignatureCreator::ComputeSchnorrSignatureHash(const uint256* leaf_hash, SigVersion sigversion) const
79
1.55k
{
80
1.55k
    assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
81
82
    // BIP341/BIP342 signing needs lots of precomputed transaction data. While some
83
    // (non-SIGHASH_DEFAULT) sighash modes exist that can work with just some subset
84
    // of data present, for now, only support signing when everything is provided.
85
1.55k
    if (!m_txdata || !m_txdata->m_bip341_taproot_ready || !m_txdata->m_spent_outputs_ready) return std::nullopt;
86
87
1.55k
    ScriptExecutionData execdata;
88
1.55k
    execdata.m_annex_init = true;
89
1.55k
    execdata.m_annex_present = false; // Only support annex-less signing for now.
90
1.55k
    if (sigversion == SigVersion::TAPSCRIPT) {
91
744
        execdata.m_codeseparator_pos_init = true;
92
744
        execdata.m_codeseparator_pos = 0xFFFFFFFF; // Only support non-OP_CODESEPARATOR BIP342 signing for now.
93
744
        if (!leaf_hash) return std::nullopt; // BIP342 signing needs leaf hash.
94
744
        execdata.m_tapleaf_hash_init = true;
95
744
        execdata.m_tapleaf_hash = *leaf_hash;
96
744
    }
97
1.55k
    uint256 hash;
98
1.55k
    if (!SignatureHashSchnorr(hash, execdata, m_txto, nIn, m_options.sighash_type, sigversion, *m_txdata, MissingDataBehavior::FAIL)) return std::nullopt;
99
1.55k
    return hash;
100
1.55k
}
101
102
bool MutableTransactionSignatureCreator::CreateSchnorrSig(const SigningProvider& provider, std::vector<unsigned char>& sig, const XOnlyPubKey& pubkey, const uint256* leaf_hash, const uint256* merkle_root, SigVersion sigversion) const
103
111k
{
104
111k
    CKey key;
105
111k
    if (!provider.GetKeyByXOnly(pubkey, key)) return false;
106
107
1.08k
    std::optional<uint256> hash = ComputeSchnorrSignatureHash(leaf_hash, sigversion);
108
1.08k
    if (!hash.has_value()) return false;
109
110
1.08k
    sig.resize(64);
111
    // Use uint256{} as aux_rnd for now.
112
1.08k
    if (!key.SignSchnorr(*hash, sig, merkle_root, {})) return false;
113
1.08k
    if (m_options.sighash_type) sig.push_back(m_options.sighash_type);
114
1.08k
    return true;
115
1.08k
}
116
117
std::vector<uint8_t> MutableTransactionSignatureCreator::CreateMuSig2Nonce(const SigningProvider& provider, const CPubKey& aggregate_pubkey, const CPubKey& script_pubkey, const CPubKey& part_pubkey, const uint256* leaf_hash, const uint256* merkle_root, SigVersion sigversion, const SignatureData& sigdata) const
118
4.91k
{
119
4.91k
    assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
120
121
    // Retrieve the private key
122
4.91k
    CKey key;
123
4.91k
    if (!provider.GetKey(part_pubkey.GetID(), key)) return {};
124
125
    // Retrieve participant pubkeys
126
151
    auto it = sigdata.musig2_pubkeys.find(aggregate_pubkey);
127
151
    if (it == sigdata.musig2_pubkeys.end()) return {};
128
151
    const std::vector<CPubKey>& pubkeys = it->second;
129
151
    if (std::find(pubkeys.begin(), pubkeys.end(), part_pubkey) == pubkeys.end()) return {};
130
131
    // Compute sighash
132
151
    std::optional<uint256> sighash = ComputeSchnorrSignatureHash(leaf_hash, sigversion);
133
151
    if (!sighash.has_value()) return {};
134
135
151
    MuSig2SecNonce secnonce;
136
151
    std::vector<uint8_t> out = ::CreateMuSig2Nonce(secnonce, *sighash, key, aggregate_pubkey, pubkeys);
137
151
    if (out.empty()) return {};
138
139
    // Store the secnonce in the SigningProvider
140
151
    provider.SetMuSig2SecNonce(MuSig2SessionID(script_pubkey, part_pubkey, *sighash, out), std::move(secnonce));
141
142
151
    return out;
143
151
}
144
145
bool MutableTransactionSignatureCreator::CreateMuSig2PartialSig(const SigningProvider& provider, uint256& partial_sig, const CPubKey& aggregate_pubkey, const CPubKey& script_pubkey, const CPubKey& part_pubkey, const uint256* leaf_hash, const std::vector<std::pair<uint256, bool>>& tweaks, SigVersion sigversion, const SignatureData& sigdata) const
146
10.2k
{
147
10.2k
    assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
148
149
    // Retrieve private key
150
10.2k
    CKey key;
151
10.2k
    if (!provider.GetKey(part_pubkey.GetID(), key)) return false;
152
153
    // Retrieve participant pubkeys
154
533
    auto it = sigdata.musig2_pubkeys.find(aggregate_pubkey);
155
533
    if (it == sigdata.musig2_pubkeys.end()) return false;
156
533
    const std::vector<CPubKey>& pubkeys = it->second;
157
533
    if (std::find(pubkeys.begin(), pubkeys.end(), part_pubkey) == pubkeys.end()) return {};
158
159
    // Retrieve pubnonces
160
533
    auto this_leaf_aggkey = std::make_pair(script_pubkey, leaf_hash ? *leaf_hash : uint256());
161
533
    auto pubnonce_it = sigdata.musig2_pubnonces.find(this_leaf_aggkey);
162
533
    if (pubnonce_it == sigdata.musig2_pubnonces.end()) return false;
163
475
    const std::map<CPubKey, std::vector<uint8_t>>& pubnonces = pubnonce_it->second;
164
165
    // Check if enough pubnonces
166
475
    if (pubnonces.size() != pubkeys.size()) return false;
167
168
    // Compute sighash
169
248
    std::optional<uint256> sighash = ComputeSchnorrSignatureHash(leaf_hash, sigversion);
170
248
    if (!sighash.has_value()) return false;
171
172
    // Retrieve the secnonce
173
248
    auto part_pubnonce_it = pubnonces.find(part_pubkey);
174
248
    if (part_pubnonce_it == pubnonces.end()) return false;
175
248
    uint256 session_id = MuSig2SessionID(script_pubkey, part_pubkey, *sighash, part_pubnonce_it->second);
176
248
    std::optional<std::reference_wrapper<MuSig2SecNonce>> secnonce = provider.GetMuSig2SecNonce(session_id);
177
248
    if (!secnonce || !secnonce->get().IsValid()) return false;
178
179
    // Compute the sig
180
140
    std::optional<uint256> sig = ::CreateMuSig2PartialSig(*sighash, key, aggregate_pubkey, pubkeys, pubnonces, *secnonce, tweaks);
181
140
    if (!sig) return false;
182
140
    partial_sig = std::move(*sig);
183
184
    // Delete the secnonce now that we're done with it
185
140
    assert(!secnonce->get().IsValid());
186
140
    provider.DeleteMuSig2Session(session_id);
187
188
140
    return true;
189
140
}
190
191
bool MutableTransactionSignatureCreator::CreateMuSig2AggregateSig(const std::vector<CPubKey>& participants, std::vector<uint8_t>& sig, const CPubKey& aggregate_pubkey, const CPubKey& script_pubkey, const uint256* leaf_hash, const std::vector<std::pair<uint256, bool>>& tweaks, SigVersion sigversion, const SignatureData& sigdata) const
192
3.77k
{
193
3.77k
    assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
194
3.77k
    if (!participants.size()) return false;
195
196
    // Retrieve pubnonces and partial sigs
197
3.77k
    auto this_leaf_aggkey = std::make_pair(script_pubkey, leaf_hash ? *leaf_hash : uint256());
198
3.77k
    auto pubnonce_it = sigdata.musig2_pubnonces.find(this_leaf_aggkey);
199
3.77k
    if (pubnonce_it == sigdata.musig2_pubnonces.end()) return false;
200
3.45k
    const std::map<CPubKey, std::vector<uint8_t>>& pubnonces = pubnonce_it->second;
201
3.45k
    auto partial_sigs_it = sigdata.musig2_partial_sigs.find(this_leaf_aggkey);
202
3.45k
    if (partial_sigs_it == sigdata.musig2_partial_sigs.end()) return false;
203
768
    const std::map<CPubKey, uint256>& partial_sigs = partial_sigs_it->second;
204
205
    // Check if enough pubnonces and partial sigs
206
768
    if (pubnonces.size() != participants.size()) return false;
207
768
    if (partial_sigs.size() != participants.size()) return false;
208
209
    // Compute sighash
210
69
    std::optional<uint256> sighash = ComputeSchnorrSignatureHash(leaf_hash, sigversion);
211
69
    if (!sighash.has_value()) return false;
212
213
69
    std::optional<std::vector<uint8_t>> res = ::CreateMuSig2AggregateSig(participants, aggregate_pubkey, tweaks, *sighash, pubnonces, partial_sigs);
214
69
    if (!res) return false;
215
69
    sig = res.value();
216
69
    if (m_options.sighash_type) sig.push_back(m_options.sighash_type);
217
218
69
    return true;
219
69
}
220
221
static bool GetCScript(const SigningProvider& provider, const SignatureData& sigdata, const CScriptID& scriptid, CScript& script)
222
7.77k
{
223
7.77k
    if (provider.GetCScript(scriptid, script)) {
224
2.01k
        return true;
225
2.01k
    }
226
    // Look for scripts in SignatureData
227
5.75k
    if (CScriptID(sigdata.redeem_script) == scriptid) {
228
3.90k
        script = sigdata.redeem_script;
229
3.90k
        return true;
230
3.90k
    } else if (CScriptID(sigdata.witness_script) == scriptid) {
231
374
        script = sigdata.witness_script;
232
374
        return true;
233
374
    }
234
1.47k
    return false;
235
5.75k
}
236
237
static bool GetPubKey(const SigningProvider& provider, const SignatureData& sigdata, const CKeyID& address, CPubKey& pubkey)
238
56.1k
{
239
    // Look for pubkey in all partial sigs
240
56.1k
    const auto it = sigdata.signatures.find(address);
241
56.1k
    if (it != sigdata.signatures.end()) {
242
48
        pubkey = it->second.first;
243
48
        return true;
244
48
    }
245
    // Look for pubkey in pubkey lists
246
56.1k
    const auto& pk_it = sigdata.misc_pubkeys.find(address);
247
56.1k
    if (pk_it != sigdata.misc_pubkeys.end()) {
248
13.6k
        pubkey = pk_it->second.first;
249
13.6k
        return true;
250
13.6k
    }
251
42.5k
    const auto& tap_pk_it = sigdata.tap_pubkeys.find(address);
252
42.5k
    if (tap_pk_it != sigdata.tap_pubkeys.end()) {
253
301
        pubkey = tap_pk_it->second.GetEvenCorrespondingCPubKey();
254
301
        return true;
255
301
    }
256
    // Query the underlying provider
257
42.2k
    return provider.GetPubKey(address, pubkey);
258
42.5k
}
259
260
static bool CreateSig(const BaseSignatureCreator& creator, SignatureData& sigdata, const SigningProvider& provider, std::vector<unsigned char>& sig_out, const CPubKey& pubkey, const CScript& scriptcode, SigVersion sigversion)
261
32.5k
{
262
32.5k
    CKeyID keyid = pubkey.GetID();
263
32.5k
    const auto it = sigdata.signatures.find(keyid);
264
32.5k
    if (it != sigdata.signatures.end()) {
265
659
        sig_out = it->second.second;
266
659
        return true;
267
659
    }
268
31.8k
    KeyOriginInfo info;
269
31.8k
    if (provider.GetKeyOrigin(keyid, info)) {
270
11.6k
        sigdata.misc_pubkeys.emplace(keyid, std::make_pair(pubkey, std::move(info)));
271
11.6k
    }
272
31.8k
    if (creator.CreateSig(provider, sig_out, keyid, scriptcode, sigversion)) {
273
16.4k
        auto i = sigdata.signatures.emplace(keyid, SigPair(pubkey, sig_out));
274
16.4k
        assert(i.second);
275
16.4k
        return true;
276
16.4k
    }
277
    // Could not make signature or signature not found, add keyid to missing
278
15.4k
    sigdata.missing_sigs.push_back(keyid);
279
15.4k
    return false;
280
31.8k
}
281
282
static bool SignMuSig2(const BaseSignatureCreator& creator, SignatureData& sigdata, const SigningProvider& provider, std::vector<unsigned char>& sig_out, const XOnlyPubKey& script_pubkey, const uint256* merkle_root, const uint256* leaf_hash, SigVersion sigversion)
283
110k
{
284
110k
    Assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
285
286
    // Lookup derivation paths for the script pubkey
287
110k
    KeyOriginInfo agg_info;
288
110k
    auto misc_pk_it = sigdata.taproot_misc_pubkeys.find(script_pubkey);
289
110k
    if (misc_pk_it != sigdata.taproot_misc_pubkeys.end()) {
290
99.6k
        agg_info = misc_pk_it->second.second;
291
99.6k
    }
292
293
110k
    for (const auto& [agg_pub, part_pks] : sigdata.musig2_pubkeys) {
294
11.7k
        if (part_pks.empty()) continue;
295
296
        // Fill participant derivation path info
297
31.8k
        for (const auto& part_pk : part_pks) {
298
31.8k
            KeyOriginInfo part_info;
299
31.8k
            if (provider.GetKeyOrigin(part_pk.GetID(), part_info)) {
300
6.30k
                XOnlyPubKey xonly_part(part_pk);
301
6.30k
                auto it = sigdata.taproot_misc_pubkeys.find(xonly_part);
302
6.30k
                if (it == sigdata.taproot_misc_pubkeys.end()) {
303
133
                    it = sigdata.taproot_misc_pubkeys.emplace(xonly_part, std::make_pair(std::set<uint256>(), part_info)).first;
304
133
                }
305
6.30k
                if (leaf_hash) it->second.first.insert(*leaf_hash);
306
6.30k
            }
307
31.8k
        }
308
309
        // The pubkey in the script may not be the actual aggregate of the participants, but derived from it.
310
        // Check the derivation, and compute the BIP 32 derivation tweaks
311
11.7k
        std::vector<std::pair<uint256, bool>> tweaks;
312
11.7k
        CPubKey plain_pub = agg_pub;
313
11.7k
        if (XOnlyPubKey(agg_pub) != script_pubkey) {
314
10.6k
            if (agg_info.path.empty()) continue;
315
            // Compute and compare fingerprint
316
5.02k
            CKeyID keyid = agg_pub.GetID();
317
5.02k
            if (!std::equal(agg_info.fingerprint, agg_info.fingerprint + sizeof(agg_info.fingerprint), keyid.data())) {
318
2.38k
                continue;
319
2.38k
            }
320
            // Get the BIP32 derivation tweaks
321
2.63k
            CExtPubKey extpub = CreateMuSig2SyntheticXpub(agg_pub);
322
5.27k
            for (const int i : agg_info.path) {
323
5.27k
                auto& [t, xonly] = tweaks.emplace_back();
324
5.27k
                xonly = false;
325
5.27k
                if (!extpub.Derive(extpub, i, &t)) {
326
0
                    return false;
327
0
                }
328
5.27k
            }
329
2.63k
            Assert(XOnlyPubKey(extpub.pubkey) == script_pubkey);
330
2.63k
            plain_pub = extpub.pubkey;
331
2.63k
        }
332
333
        // Add the merkle root tweak
334
3.77k
        if (sigversion == SigVersion::TAPROOT && merkle_root) {
335
916
            tweaks.emplace_back(script_pubkey.ComputeTapTweakHash(merkle_root->IsNull() ? nullptr : merkle_root), true);
336
916
            std::optional<std::pair<XOnlyPubKey, bool>> tweaked = script_pubkey.CreateTapTweak(merkle_root->IsNull() ? nullptr : merkle_root);
337
916
            if (!Assume(tweaked)) return false;
338
916
            plain_pub = tweaked->first.GetCPubKeys().at(tweaked->second ? 1 : 0);
339
916
        }
340
341
        // First try to aggregate
342
3.77k
        if (creator.CreateMuSig2AggregateSig(part_pks, sig_out, agg_pub, plain_pub, leaf_hash, tweaks, sigversion, sigdata)) {
343
69
            if (sigversion == SigVersion::TAPROOT) {
344
30
                sigdata.taproot_key_path_sig = sig_out;
345
39
            } else {
346
39
                auto lookup_key = std::make_pair(script_pubkey, leaf_hash ? *leaf_hash : uint256());
347
39
                sigdata.taproot_script_sigs[lookup_key] = sig_out;
348
39
            }
349
69
            continue;
350
69
        }
351
        // Cannot aggregate, try making partial sigs for every participant
352
3.71k
        auto pub_key_leaf_hash = std::make_pair(plain_pub, leaf_hash ? *leaf_hash : uint256());
353
10.2k
        for (const CPubKey& part_pk : part_pks) {
354
10.2k
            uint256 partial_sig;
355
10.2k
            if (creator.CreateMuSig2PartialSig(provider, partial_sig, agg_pub, plain_pub, part_pk, leaf_hash, tweaks, sigversion, sigdata) && Assume(!partial_sig.IsNull())) {
356
140
                sigdata.musig2_partial_sigs[pub_key_leaf_hash].emplace(part_pk, partial_sig);
357
140
            }
358
10.2k
        }
359
        // If there are any partial signatures, continue with next aggregate pubkey
360
3.71k
        auto partial_sigs_it = sigdata.musig2_partial_sigs.find(pub_key_leaf_hash);
361
3.71k
        if (partial_sigs_it != sigdata.musig2_partial_sigs.end() && !partial_sigs_it->second.empty()) {
362
839
            continue;
363
839
        }
364
        // No partial sigs, try to make pubnonces
365
2.87k
        std::map<CPubKey, std::vector<uint8_t>>& pubnonces = sigdata.musig2_pubnonces[pub_key_leaf_hash];
366
7.91k
        for (const CPubKey& part_pk : part_pks) {
367
7.91k
            if (pubnonces.contains(part_pk)) continue;
368
4.91k
            std::vector<uint8_t> pubnonce = creator.CreateMuSig2Nonce(provider, agg_pub, plain_pub, part_pk, leaf_hash, merkle_root, sigversion, sigdata);
369
4.91k
            if (pubnonce.empty()) continue;
370
151
            pubnonces[part_pk] = std::move(pubnonce);
371
151
        }
372
2.87k
    }
373
110k
    return true;
374
110k
}
375
376
static bool CreateTaprootScriptSig(const BaseSignatureCreator& creator, SignatureData& sigdata, const SigningProvider& provider, std::vector<unsigned char>& sig_out, const XOnlyPubKey& pubkey, const uint256& leaf_hash, SigVersion sigversion)
377
96.2k
{
378
96.2k
    KeyOriginInfo info;
379
96.2k
    if (provider.GetKeyOriginByXOnly(pubkey, info)) {
380
45.6k
        auto it = sigdata.taproot_misc_pubkeys.find(pubkey);
381
45.6k
        if (it == sigdata.taproot_misc_pubkeys.end()) {
382
707
            sigdata.taproot_misc_pubkeys.emplace(pubkey, std::make_pair(std::set<uint256>({leaf_hash}), info));
383
44.9k
        } else {
384
44.9k
            it->second.first.insert(leaf_hash);
385
44.9k
        }
386
45.6k
    }
387
388
96.2k
    auto lookup_key = std::make_pair(pubkey, leaf_hash);
389
96.2k
    auto it = sigdata.taproot_script_sigs.find(lookup_key);
390
96.2k
    if (it != sigdata.taproot_script_sigs.end()) {
391
541
        sig_out = it->second;
392
541
        return true;
393
541
    }
394
395
95.6k
    if (creator.CreateSchnorrSig(provider, sig_out, pubkey, &leaf_hash, nullptr, sigversion)) {
396
479
        sigdata.taproot_script_sigs[lookup_key] = sig_out;
397
95.2k
    } else if (!SignMuSig2(creator, sigdata, provider, sig_out, pubkey, /*merkle_root=*/nullptr, &leaf_hash, sigversion)) {
398
0
        return false;
399
0
    }
400
401
95.6k
    return sigdata.taproot_script_sigs.contains(lookup_key);
402
95.6k
}
403
404
template<typename M, typename K, typename V>
405
miniscript::Availability MsLookupHelper(const M& map, const K& key, V& value)
406
74
{
407
74
    auto it = map.find(key);
408
74
    if (it != map.end()) {
409
42
        value = it->second;
410
42
        return miniscript::Availability::YES;
411
42
    }
412
32
    return miniscript::Availability::NO;
413
74
}
414
415
/**
416
 * Context for solving a Miniscript.
417
 * If enough material (access to keys, hash preimages, ..) is given, produces a valid satisfaction.
418
 */
419
template<typename Pk>
420
struct Satisfier {
421
    using Key = Pk;
422
423
    const SigningProvider& m_provider;
424
    SignatureData& m_sig_data;
425
    const BaseSignatureCreator& m_creator;
426
    const CScript& m_witness_script;
427
    //! The context of the script we are satisfying (either P2WSH or Tapscript).
428
    const miniscript::MiniscriptContext m_script_ctx;
429
430
    explicit Satisfier(const SigningProvider& provider LIFETIMEBOUND, SignatureData& sig_data LIFETIMEBOUND,
431
                       const BaseSignatureCreator& creator LIFETIMEBOUND,
432
                       const CScript& witscript LIFETIMEBOUND,
433
4.59k
                       miniscript::MiniscriptContext script_ctx) : m_provider(provider),
434
4.59k
                                                                   m_sig_data(sig_data),
435
4.59k
                                                                   m_creator(creator),
436
4.59k
                                                                   m_witness_script(witscript),
437
4.59k
                                                                   m_script_ctx(script_ctx) {}
Satisfier<XOnlyPubKey>::Satisfier(SigningProvider const&, SignatureData&, BaseSignatureCreator const&, CScript const&, miniscript::MiniscriptContext)
Line
Count
Source
433
4.32k
                       miniscript::MiniscriptContext script_ctx) : m_provider(provider),
434
4.32k
                                                                   m_sig_data(sig_data),
435
4.32k
                                                                   m_creator(creator),
436
4.32k
                                                                   m_witness_script(witscript),
437
4.32k
                                                                   m_script_ctx(script_ctx) {}
Satisfier<CPubKey>::Satisfier(SigningProvider const&, SignatureData&, BaseSignatureCreator const&, CScript const&, miniscript::MiniscriptContext)
Line
Count
Source
433
268
                       miniscript::MiniscriptContext script_ctx) : m_provider(provider),
434
268
                                                                   m_sig_data(sig_data),
435
268
                                                                   m_creator(creator),
436
268
                                                                   m_witness_script(witscript),
437
268
                                                                   m_script_ctx(script_ctx) {}
438
439
318k
    static bool KeyCompare(const Key& a, const Key& b) {
440
318k
        return a < b;
441
318k
    }
Satisfier<XOnlyPubKey>::KeyCompare(XOnlyPubKey const&, XOnlyPubKey const&)
Line
Count
Source
439
316k
    static bool KeyCompare(const Key& a, const Key& b) {
440
316k
        return a < b;
441
316k
    }
Satisfier<CPubKey>::KeyCompare(CPubKey const&, CPubKey const&)
Line
Count
Source
439
1.28k
    static bool KeyCompare(const Key& a, const Key& b) {
440
1.28k
        return a < b;
441
1.28k
    }
442
443
    //! Get a CPubKey from a key hash. Note the key hash may be of an xonly pubkey.
444
    template<typename I>
445
374
    std::optional<CPubKey> CPubFromPKHBytes(I first, I last) const {
446
374
        assert(last - first == 20);
447
374
        CPubKey pubkey;
448
374
        CKeyID key_id;
449
374
        std::copy(first, last, key_id.begin());
450
374
        if (GetPubKey(m_provider, m_sig_data, key_id, pubkey)) return pubkey;
451
1
        m_sig_data.missing_pubkeys.push_back(key_id);
452
1
        return {};
453
374
    }
std::optional<CPubKey> Satisfier<XOnlyPubKey>::CPubFromPKHBytes<__gnu_cxx::__normal_iterator<unsigned char*, std::vector<unsigned char, std::allocator<unsigned char>>>>(__gnu_cxx::__normal_iterator<unsigned char*, std::vector<unsigned char, std::allocator<unsigned char>>>, __gnu_cxx::__normal_iterator<unsigned char*, std::vector<unsigned char, std::allocator<unsigned char>>>) const
Line
Count
Source
445
315
    std::optional<CPubKey> CPubFromPKHBytes(I first, I last) const {
446
315
        assert(last - first == 20);
447
315
        CPubKey pubkey;
448
315
        CKeyID key_id;
449
315
        std::copy(first, last, key_id.begin());
450
315
        if (GetPubKey(m_provider, m_sig_data, key_id, pubkey)) return pubkey;
451
0
        m_sig_data.missing_pubkeys.push_back(key_id);
452
0
        return {};
453
315
    }
std::optional<CPubKey> Satisfier<CPubKey>::CPubFromPKHBytes<__gnu_cxx::__normal_iterator<unsigned char*, std::vector<unsigned char, std::allocator<unsigned char>>>>(__gnu_cxx::__normal_iterator<unsigned char*, std::vector<unsigned char, std::allocator<unsigned char>>>, __gnu_cxx::__normal_iterator<unsigned char*, std::vector<unsigned char, std::allocator<unsigned char>>>) const
Line
Count
Source
445
59
    std::optional<CPubKey> CPubFromPKHBytes(I first, I last) const {
446
59
        assert(last - first == 20);
447
59
        CPubKey pubkey;
448
59
        CKeyID key_id;
449
59
        std::copy(first, last, key_id.begin());
450
59
        if (GetPubKey(m_provider, m_sig_data, key_id, pubkey)) return pubkey;
451
1
        m_sig_data.missing_pubkeys.push_back(key_id);
452
1
        return {};
453
59
    }
454
455
    //! Conversion to raw public key.
456
373
    std::vector<unsigned char> ToPKBytes(const Key& key) const { return {key.begin(), key.end()}; }
Satisfier<XOnlyPubKey>::ToPKBytes(XOnlyPubKey const&) const
Line
Count
Source
456
315
    std::vector<unsigned char> ToPKBytes(const Key& key) const { return {key.begin(), key.end()}; }
Satisfier<CPubKey>::ToPKBytes(CPubKey const&) const
Line
Count
Source
456
58
    std::vector<unsigned char> ToPKBytes(const Key& key) const { return {key.begin(), key.end()}; }
457
458
    //! Time lock satisfactions.
459
1.04k
    bool CheckAfter(uint32_t value) const { return m_creator.Checker().CheckLockTime(CScriptNum(value)); }
Satisfier<XOnlyPubKey>::CheckAfter(unsigned int) const
Line
Count
Source
459
790
    bool CheckAfter(uint32_t value) const { return m_creator.Checker().CheckLockTime(CScriptNum(value)); }
Satisfier<CPubKey>::CheckAfter(unsigned int) const
Line
Count
Source
459
253
    bool CheckAfter(uint32_t value) const { return m_creator.Checker().CheckLockTime(CScriptNum(value)); }
460
115
    bool CheckOlder(uint32_t value) const { return m_creator.Checker().CheckSequence(CScriptNum(value)); }
Satisfier<XOnlyPubKey>::CheckOlder(unsigned int) const
Line
Count
Source
460
41
    bool CheckOlder(uint32_t value) const { return m_creator.Checker().CheckSequence(CScriptNum(value)); }
Satisfier<CPubKey>::CheckOlder(unsigned int) const
Line
Count
Source
460
74
    bool CheckOlder(uint32_t value) const { return m_creator.Checker().CheckSequence(CScriptNum(value)); }
461
462
    //! Hash preimage satisfactions.
463
26
    miniscript::Availability SatSHA256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
464
26
        return MsLookupHelper(m_sig_data.sha256_preimages, hash, preimage);
465
26
    }
Unexecuted instantiation: Satisfier<XOnlyPubKey>::SatSHA256(std::vector<unsigned char, std::allocator<unsigned char>> const&, std::vector<unsigned char, std::allocator<unsigned char>>&) const
Satisfier<CPubKey>::SatSHA256(std::vector<unsigned char, std::allocator<unsigned char>> const&, std::vector<unsigned char, std::allocator<unsigned char>>&) const
Line
Count
Source
463
26
    miniscript::Availability SatSHA256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
464
26
        return MsLookupHelper(m_sig_data.sha256_preimages, hash, preimage);
465
26
    }
466
12
    miniscript::Availability SatRIPEMD160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
467
12
        return MsLookupHelper(m_sig_data.ripemd160_preimages, hash, preimage);
468
12
    }
Unexecuted instantiation: Satisfier<XOnlyPubKey>::SatRIPEMD160(std::vector<unsigned char, std::allocator<unsigned char>> const&, std::vector<unsigned char, std::allocator<unsigned char>>&) const
Satisfier<CPubKey>::SatRIPEMD160(std::vector<unsigned char, std::allocator<unsigned char>> const&, std::vector<unsigned char, std::allocator<unsigned char>>&) const
Line
Count
Source
466
12
    miniscript::Availability SatRIPEMD160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
467
12
        return MsLookupHelper(m_sig_data.ripemd160_preimages, hash, preimage);
468
12
    }
469
24
    miniscript::Availability SatHASH256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
470
24
        return MsLookupHelper(m_sig_data.hash256_preimages, hash, preimage);
471
24
    }
Satisfier<XOnlyPubKey>::SatHASH256(std::vector<unsigned char, std::allocator<unsigned char>> const&, std::vector<unsigned char, std::allocator<unsigned char>>&) const
Line
Count
Source
469
12
    miniscript::Availability SatHASH256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
470
12
        return MsLookupHelper(m_sig_data.hash256_preimages, hash, preimage);
471
12
    }
Satisfier<CPubKey>::SatHASH256(std::vector<unsigned char, std::allocator<unsigned char>> const&, std::vector<unsigned char, std::allocator<unsigned char>>&) const
Line
Count
Source
469
12
    miniscript::Availability SatHASH256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
470
12
        return MsLookupHelper(m_sig_data.hash256_preimages, hash, preimage);
471
12
    }
472
12
    miniscript::Availability SatHASH160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
473
12
        return MsLookupHelper(m_sig_data.hash160_preimages, hash, preimage);
474
12
    }
Unexecuted instantiation: Satisfier<XOnlyPubKey>::SatHASH160(std::vector<unsigned char, std::allocator<unsigned char>> const&, std::vector<unsigned char, std::allocator<unsigned char>>&) const
Satisfier<CPubKey>::SatHASH160(std::vector<unsigned char, std::allocator<unsigned char>> const&, std::vector<unsigned char, std::allocator<unsigned char>>&) const
Line
Count
Source
472
12
    miniscript::Availability SatHASH160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
473
12
        return MsLookupHelper(m_sig_data.hash160_preimages, hash, preimage);
474
12
    }
475
476
5.62M
    miniscript::MiniscriptContext MsContext() const {
477
5.62M
        return m_script_ctx;
478
5.62M
    }
Satisfier<XOnlyPubKey>::MsContext() const
Line
Count
Source
476
5.61M
    miniscript::MiniscriptContext MsContext() const {
477
5.61M
        return m_script_ctx;
478
5.61M
    }
Satisfier<CPubKey>::MsContext() const
Line
Count
Source
476
3.76k
    miniscript::MiniscriptContext MsContext() const {
477
3.76k
        return m_script_ctx;
478
3.76k
    }
479
};
480
481
/** Miniscript satisfier specific to P2WSH context. */
482
struct WshSatisfier: Satisfier<CPubKey> {
483
    explicit WshSatisfier(const SigningProvider& provider LIFETIMEBOUND, SignatureData& sig_data LIFETIMEBOUND,
484
                          const BaseSignatureCreator& creator LIFETIMEBOUND, const CScript& witscript LIFETIMEBOUND)
485
268
                          : Satisfier(provider, sig_data, creator, witscript, miniscript::MiniscriptContext::P2WSH) {}
486
487
    //! Conversion from a raw compressed public key.
488
    template <typename I>
489
623
    std::optional<CPubKey> FromPKBytes(I first, I last) const {
490
623
        CPubKey pubkey{first, last};
491
623
        if (pubkey.IsValid()) return pubkey;
492
1
        return {};
493
623
    }
494
495
    //! Conversion from a raw compressed public key hash.
496
    template<typename I>
497
59
    std::optional<CPubKey> FromPKHBytes(I first, I last) const {
498
59
        return Satisfier::CPubFromPKHBytes(first, last);
499
59
    }
500
501
    //! Satisfy an ECDSA signature check.
502
680
    miniscript::Availability Sign(const CPubKey& key, std::vector<unsigned char>& sig) const {
503
680
        if (CreateSig(m_creator, m_sig_data, m_provider, sig, key, m_witness_script, SigVersion::WITNESS_V0)) {
504
370
            return miniscript::Availability::YES;
505
370
        }
506
310
        return miniscript::Availability::NO;
507
680
    }
508
};
509
510
/** Miniscript satisfier specific to Tapscript context. */
511
struct TapSatisfier: Satisfier<XOnlyPubKey> {
512
    const uint256& m_leaf_hash;
513
514
    explicit TapSatisfier(const SigningProvider& provider LIFETIMEBOUND, SignatureData& sig_data LIFETIMEBOUND,
515
                          const BaseSignatureCreator& creator LIFETIMEBOUND, const CScript& script LIFETIMEBOUND,
516
                          const uint256& leaf_hash LIFETIMEBOUND)
517
4.32k
                          : Satisfier(provider, sig_data, creator, script, miniscript::MiniscriptContext::TAPSCRIPT),
518
4.32k
                            m_leaf_hash(leaf_hash) {}
519
520
    //! Conversion from a raw xonly public key.
521
    template <typename I>
522
95.9k
    std::optional<XOnlyPubKey> FromPKBytes(I first, I last) const {
523
95.9k
        if (last - first != 32) return {};
524
95.9k
        XOnlyPubKey pubkey;
525
95.9k
        std::copy(first, last, pubkey.begin());
526
95.9k
        return pubkey;
527
95.9k
    }
528
529
    //! Conversion from a raw xonly public key hash.
530
    template<typename I>
531
315
    std::optional<XOnlyPubKey> FromPKHBytes(I first, I last) const {
532
315
        if (auto pubkey = Satisfier::CPubFromPKHBytes(first, last)) return XOnlyPubKey{*pubkey};
533
0
        return {};
534
315
    }
535
536
    //! Satisfy a BIP340 signature check.
537
96.2k
    miniscript::Availability Sign(const XOnlyPubKey& key, std::vector<unsigned char>& sig) const {
538
96.2k
        if (CreateTaprootScriptSig(m_creator, m_sig_data, m_provider, sig, key, m_leaf_hash, SigVersion::TAPSCRIPT)) {
539
1.05k
            return miniscript::Availability::YES;
540
1.05k
        }
541
95.1k
        return miniscript::Availability::NO;
542
96.2k
    }
543
};
544
545
static bool SignTaprootScript(const SigningProvider& provider, const BaseSignatureCreator& creator, SignatureData& sigdata, int leaf_version, std::span<const unsigned char> script_bytes, std::vector<valtype>& result)
546
4.32k
{
547
    // Only BIP342 tapscript signing is supported for now.
548
4.32k
    if (leaf_version != TAPROOT_LEAF_TAPSCRIPT) return false;
549
550
4.32k
    uint256 leaf_hash = ComputeTapleafHash(leaf_version, script_bytes);
551
4.32k
    CScript script = CScript(script_bytes.begin(), script_bytes.end());
552
553
4.32k
    TapSatisfier ms_satisfier{provider, sigdata, creator, script, leaf_hash};
554
4.32k
    const auto ms = miniscript::FromScript(script, ms_satisfier);
555
4.32k
    return ms && ms->Satisfy(ms_satisfier, result) == miniscript::Availability::YES;
556
4.32k
}
557
558
static bool SignTaproot(const SigningProvider& provider, const BaseSignatureCreator& creator, const WitnessV1Taproot& output, SignatureData& sigdata, std::vector<valtype>& result)
559
8.21k
{
560
8.21k
    TaprootSpendData spenddata;
561
8.21k
    TaprootBuilder builder;
562
563
    // Gather information about this output.
564
8.21k
    if (provider.GetTaprootSpendData(output, spenddata)) {
565
1.49k
        sigdata.tr_spenddata.Merge(spenddata);
566
1.49k
    }
567
8.21k
    if (provider.GetTaprootBuilder(output, builder)) {
568
1.49k
        sigdata.tr_builder = builder;
569
1.49k
    }
570
8.21k
    if (auto agg_keys = provider.GetAllMuSig2ParticipantPubkeys(); !agg_keys.empty()) {
571
505
        sigdata.musig2_pubkeys.insert(agg_keys.begin(), agg_keys.end());
572
505
    }
573
574
575
    // Try key path spending.
576
8.21k
    {
577
8.21k
        KeyOriginInfo internal_key_info;
578
8.21k
        if (provider.GetKeyOriginByXOnly(sigdata.tr_spenddata.internal_key, internal_key_info)) {
579
1.54k
            auto it = sigdata.taproot_misc_pubkeys.find(sigdata.tr_spenddata.internal_key);
580
1.54k
            if (it == sigdata.taproot_misc_pubkeys.end()) {
581
833
                sigdata.taproot_misc_pubkeys.emplace(sigdata.tr_spenddata.internal_key, std::make_pair(std::set<uint256>(), internal_key_info));
582
833
            }
583
1.54k
        }
584
585
8.21k
        KeyOriginInfo output_key_info;
586
8.21k
        if (provider.GetKeyOriginByXOnly(output, output_key_info)) {
587
138
            auto it = sigdata.taproot_misc_pubkeys.find(output);
588
138
            if (it == sigdata.taproot_misc_pubkeys.end()) {
589
44
                sigdata.taproot_misc_pubkeys.emplace(output, std::make_pair(std::set<uint256>(), output_key_info));
590
44
            }
591
138
        }
592
593
15.4k
        auto make_keypath_sig = [&](const XOnlyPubKey& pk, const uint256* merkle_root) {
594
15.4k
            std::vector<unsigned char> sig;
595
15.4k
            if (creator.CreateSchnorrSig(provider, sig, pk, nullptr, merkle_root, SigVersion::TAPROOT)) {
596
599
                sigdata.taproot_key_path_sig = sig;
597
14.8k
            } else {
598
14.8k
                SignMuSig2(creator, sigdata, provider, sig, pk, merkle_root, /*leaf_hash=*/nullptr, SigVersion::TAPROOT);
599
14.8k
            }
600
15.4k
        };
601
602
        // First try signing with internal key
603
8.21k
        if (sigdata.taproot_key_path_sig.size() == 0) {
604
8.03k
            make_keypath_sig(sigdata.tr_spenddata.internal_key, &sigdata.tr_spenddata.merkle_root);
605
8.03k
        }
606
        // Try signing with output key if still no signature
607
8.21k
        if (sigdata.taproot_key_path_sig.size() == 0) {
608
7.44k
            make_keypath_sig(output, nullptr);
609
7.44k
        }
610
8.21k
        if (sigdata.taproot_key_path_sig.size()) {
611
809
            result = Vector(sigdata.taproot_key_path_sig);
612
809
            return true;
613
809
        }
614
8.21k
    }
615
616
    // Try script path spending.
617
7.40k
    std::vector<std::vector<unsigned char>> smallest_result_stack;
618
7.40k
    for (const auto& [key, control_blocks] : sigdata.tr_spenddata.scripts) {
619
4.32k
        const auto& [script, leaf_ver] = key;
620
4.32k
        std::vector<std::vector<unsigned char>> result_stack;
621
4.32k
        if (SignTaprootScript(provider, creator, sigdata, leaf_ver, script, result_stack)) {
622
685
            result_stack.emplace_back(std::begin(script), std::end(script)); // Push the script
623
685
            result_stack.push_back(*control_blocks.begin()); // Push the smallest control block
624
685
            if (smallest_result_stack.size() == 0 ||
625
685
                GetSerializeSize(result_stack) < GetSerializeSize(smallest_result_stack)) {
626
672
                smallest_result_stack = std::move(result_stack);
627
672
            }
628
685
        }
629
4.32k
    }
630
7.40k
    if (smallest_result_stack.size() != 0) {
631
668
        result = std::move(smallest_result_stack);
632
668
        return true;
633
668
    }
634
635
6.73k
    return false;
636
7.40k
}
637
638
/**
639
 * Sign scriptPubKey using signature made with creator.
640
 * Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
641
 * unless whichTypeRet is TxoutType::SCRIPTHASH, in which case scriptSigRet is the redemption script.
642
 * Returns false if scriptPubKey could not be completely satisfied.
643
 */
644
static bool SignStep(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& scriptPubKey,
645
                     std::vector<valtype>& ret, TxoutType& whichTypeRet, SigVersion sigversion, SignatureData& sigdata)
646
111k
{
647
111k
    CScript scriptRet;
648
111k
    ret.clear();
649
111k
    std::vector<unsigned char> sig;
650
651
111k
    std::vector<valtype> vSolutions;
652
111k
    whichTypeRet = Solver(scriptPubKey, vSolutions);
653
654
111k
    switch (whichTypeRet) {
655
242
    case TxoutType::NONSTANDARD:
656
242
    case TxoutType::NULL_DATA:
657
242
    case TxoutType::WITNESS_UNKNOWN:
658
242
        return false;
659
261
    case TxoutType::PUBKEY:
660
261
        if (!CreateSig(creator, sigdata, provider, sig, CPubKey(vSolutions[0]), scriptPubKey, sigversion)) return false;
661
177
        ret.push_back(std::move(sig));
662
177
        return true;
663
55.8k
    case TxoutType::PUBKEYHASH: {
664
55.8k
        CKeyID keyID = CKeyID(uint160(vSolutions[0]));
665
55.8k
        CPubKey pubkey;
666
55.8k
        if (!GetPubKey(provider, sigdata, keyID, pubkey)) {
667
            // Pubkey could not be found, add to missing
668
26.4k
            sigdata.missing_pubkeys.push_back(keyID);
669
26.4k
            return false;
670
26.4k
        }
671
29.3k
        if (!CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion)) return false;
672
15.2k
        ret.push_back(std::move(sig));
673
15.2k
        ret.push_back(ToByteVector(pubkey));
674
15.2k
        return true;
675
29.3k
    }
676
6.70k
    case TxoutType::SCRIPTHASH: {
677
6.70k
        uint160 h160{vSolutions[0]};
678
6.70k
        if (GetCScript(provider, sigdata, CScriptID{h160}, scriptRet)) {
679
5.38k
            ret.emplace_back(scriptRet.begin(), scriptRet.end());
680
5.38k
            return true;
681
5.38k
        }
682
        // Could not find redeemScript, add to missing
683
1.31k
        sigdata.missing_redeem_script = h160;
684
1.31k
        return false;
685
6.70k
    }
686
517
    case TxoutType::MULTISIG: {
687
517
        size_t required = vSolutions.front()[0];
688
517
        ret.emplace_back(); // workaround CHECKMULTISIG bug
689
2.70k
        for (size_t i = 1; i < vSolutions.size() - 1; ++i) {
690
2.19k
            CPubKey pubkey = CPubKey(vSolutions[i]);
691
            // We need to always call CreateSig in order to fill sigdata with all
692
            // possible signatures that we can create. This will allow further PSBT
693
            // processing to work as it needs all possible signature and pubkey pairs
694
2.19k
            if (CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion)) {
695
1.25k
                if (ret.size() < required + 1) {
696
1.20k
                    ret.push_back(std::move(sig));
697
1.20k
                }
698
1.25k
            }
699
2.19k
        }
700
517
        bool ok = ret.size() == required + 1;
701
902
        for (size_t i = 0; i + ret.size() < required + 1; ++i) {
702
385
            ret.emplace_back();
703
385
        }
704
517
        return ok;
705
6.70k
    }
706
38.7k
    case TxoutType::WITNESS_V0_KEYHASH:
707
38.7k
        ret.push_back(vSolutions[0]);
708
38.7k
        return true;
709
710
1.07k
    case TxoutType::WITNESS_V0_SCRIPTHASH:
711
1.07k
        if (GetCScript(provider, sigdata, CScriptID{RIPEMD160(vSolutions[0])}, scriptRet)) {
712
914
            ret.emplace_back(scriptRet.begin(), scriptRet.end());
713
914
            return true;
714
914
        }
715
        // Could not find witnessScript, add to missing
716
159
        sigdata.missing_witness_script = uint256(vSolutions[0]);
717
159
        return false;
718
719
8.21k
    case TxoutType::WITNESS_V1_TAPROOT:
720
8.21k
        return SignTaproot(provider, creator, WitnessV1Taproot(XOnlyPubKey{vSolutions[0]}), sigdata, ret);
721
722
1
    case TxoutType::ANCHOR:
723
1
        return true;
724
111k
    } // no default case, so the compiler can warn about missing cases
725
111k
    assert(false);
726
0
}
727
728
static CScript PushAll(const std::vector<valtype>& values)
729
66.7k
{
730
66.7k
    CScript result;
731
66.7k
    for (const valtype& v : values) {
732
17.1k
        if (v.size() == 0) {
733
247
            result << OP_0;
734
16.9k
        } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
735
0
            result << CScript::EncodeOP_N(v[0]);
736
16.9k
        } else if (v.size() == 1 && v[0] == 0x81) {
737
0
            result << OP_1NEGATE;
738
16.9k
        } else {
739
16.9k
            result << v;
740
16.9k
        }
741
17.1k
    }
742
66.7k
    return result;
743
66.7k
}
744
745
bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& fromPubKey, SignatureData& sigdata)
746
69.4k
{
747
69.4k
    if (sigdata.complete) return true;
748
749
66.7k
    std::vector<valtype> result;
750
66.7k
    TxoutType whichType;
751
66.7k
    bool solved = SignStep(provider, creator, fromPubKey, result, whichType, SigVersion::BASE, sigdata);
752
66.7k
    bool P2SH = false;
753
66.7k
    CScript subscript;
754
755
66.7k
    if (solved && whichType == TxoutType::SCRIPTHASH)
756
5.38k
    {
757
        // Solver returns the subscript that needs to be evaluated;
758
        // the final scriptSig is the signatures from that
759
        // and then the serialized subscript:
760
5.38k
        subscript = CScript(result[0].begin(), result[0].end());
761
5.38k
        sigdata.redeem_script = subscript;
762
5.38k
        solved = solved && SignStep(provider, creator, subscript, result, whichType, SigVersion::BASE, sigdata) && whichType != TxoutType::SCRIPTHASH;
763
5.38k
        P2SH = true;
764
5.38k
    }
765
766
66.7k
    if (solved && whichType == TxoutType::WITNESS_V0_KEYHASH)
767
38.5k
    {
768
38.5k
        CScript witnessscript;
769
38.5k
        witnessscript << OP_DUP << OP_HASH160 << ToByteVector(result[0]) << OP_EQUALVERIFY << OP_CHECKSIG;
770
38.5k
        TxoutType subType;
771
38.5k
        solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0, sigdata);
772
38.5k
        sigdata.scriptWitness.stack = result;
773
38.5k
        sigdata.witness = true;
774
38.5k
        result.clear();
775
38.5k
    }
776
28.1k
    else if (solved && whichType == TxoutType::WITNESS_V0_SCRIPTHASH)
777
903
    {
778
903
        CScript witnessscript(result[0].begin(), result[0].end());
779
903
        sigdata.witness_script = witnessscript;
780
781
903
        TxoutType subType{TxoutType::NONSTANDARD};
782
903
        solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0, sigdata) && subType != TxoutType::SCRIPTHASH && subType != TxoutType::WITNESS_V0_SCRIPTHASH && subType != TxoutType::WITNESS_V0_KEYHASH;
783
784
        // If we couldn't find a solution with the legacy satisfier, try satisfying the script using Miniscript.
785
        // Note we need to check if the result stack is empty before, because it might be used even if the Script
786
        // isn't fully solved. For instance the CHECKMULTISIG satisfaction in SignStep() pushes partial signatures
787
        // and the extractor relies on this behaviour to combine witnesses.
788
903
        if (!solved && result.empty()) {
789
268
            WshSatisfier ms_satisfier{provider, sigdata, creator, witnessscript};
790
268
            const auto ms = miniscript::FromScript(witnessscript, ms_satisfier);
791
268
            solved = ms && ms->Satisfy(ms_satisfier, result) == miniscript::Availability::YES;
792
268
        }
793
903
        result.emplace_back(witnessscript.begin(), witnessscript.end());
794
795
903
        sigdata.scriptWitness.stack = result;
796
903
        sigdata.witness = true;
797
903
        result.clear();
798
27.2k
    } else if (whichType == TxoutType::WITNESS_V1_TAPROOT && !P2SH) {
799
8.20k
        sigdata.witness = true;
800
8.20k
        if (solved) {
801
1.47k
            sigdata.scriptWitness.stack = std::move(result);
802
1.47k
        }
803
8.20k
        result.clear();
804
19.0k
    } else if (solved && whichType == TxoutType::WITNESS_UNKNOWN) {
805
0
        sigdata.witness = true;
806
0
    }
807
808
66.7k
    if (!sigdata.witness) sigdata.scriptWitness.stack.clear();
809
66.7k
    if (P2SH) {
810
5.38k
        result.emplace_back(subscript.begin(), subscript.end());
811
5.38k
    }
812
66.7k
    sigdata.scriptSig = PushAll(result);
813
814
    // Test solution
815
66.7k
    sigdata.complete = solved && VerifyScript(sigdata.scriptSig, fromPubKey, &sigdata.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker());
816
66.7k
    return sigdata.complete;
817
69.4k
}
818
819
namespace {
820
class SignatureExtractorChecker final : public DeferringSignatureChecker
821
{
822
private:
823
    SignatureData& sigdata;
824
825
public:
826
37.9k
    SignatureExtractorChecker(SignatureData& sigdata, BaseSignatureChecker& checker) : DeferringSignatureChecker(checker), sigdata(sigdata) {}
827
828
    bool CheckECDSASignature(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override
829
3.62k
    {
830
3.62k
        if (m_checker.CheckECDSASignature(scriptSig, vchPubKey, scriptCode, sigversion)) {
831
2.83k
            CPubKey pubkey(vchPubKey);
832
2.83k
            sigdata.signatures.emplace(pubkey.GetID(), SigPair(pubkey, scriptSig));
833
2.83k
            return true;
834
2.83k
        }
835
794
        return false;
836
3.62k
    }
837
};
838
839
struct Stacks
840
{
841
    std::vector<valtype> script;
842
    std::vector<valtype> witness;
843
844
    Stacks() = delete;
845
    Stacks(const Stacks&) = delete;
846
37.9k
    explicit Stacks(const SignatureData& data) : witness(data.scriptWitness.stack) {
847
37.9k
        EvalScript(script, data.scriptSig, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SigVersion::BASE);
848
37.9k
    }
849
};
850
}
851
852
// Extracts signatures and scripts from incomplete scriptSigs. Please do not extend this, use PSBT instead
853
SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn, const CTxOut& txout)
854
37.9k
{
855
37.9k
    SignatureData data;
856
37.9k
    assert(tx.vin.size() > nIn);
857
37.9k
    data.scriptSig = tx.vin[nIn].scriptSig;
858
37.9k
    data.scriptWitness = tx.vin[nIn].scriptWitness;
859
37.9k
    Stacks stack(data);
860
861
    // Get signatures
862
37.9k
    MutableTransactionSignatureChecker tx_checker(&tx, nIn, txout.nValue, MissingDataBehavior::FAIL);
863
37.9k
    SignatureExtractorChecker extractor_checker(data, tx_checker);
864
37.9k
    if (VerifyScript(data.scriptSig, txout.scriptPubKey, &data.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, extractor_checker)) {
865
2.69k
        data.complete = true;
866
2.69k
        return data;
867
2.69k
    }
868
869
    // Get scripts
870
35.2k
    std::vector<std::vector<unsigned char>> solutions;
871
35.2k
    TxoutType script_type = Solver(txout.scriptPubKey, solutions);
872
35.2k
    SigVersion sigversion = SigVersion::BASE;
873
35.2k
    CScript next_script = txout.scriptPubKey;
874
875
35.2k
    if (script_type == TxoutType::SCRIPTHASH && !stack.script.empty() && !stack.script.back().empty()) {
876
        // Get the redeemScript
877
30
        CScript redeem_script(stack.script.back().begin(), stack.script.back().end());
878
30
        data.redeem_script = redeem_script;
879
30
        next_script = std::move(redeem_script);
880
881
        // Get redeemScript type
882
30
        script_type = Solver(next_script, solutions);
883
30
        stack.script.pop_back();
884
30
    }
885
35.2k
    if (script_type == TxoutType::WITNESS_V0_SCRIPTHASH && !stack.witness.empty() && !stack.witness.back().empty()) {
886
        // Get the witnessScript
887
47
        CScript witness_script(stack.witness.back().begin(), stack.witness.back().end());
888
47
        data.witness_script = witness_script;
889
47
        next_script = std::move(witness_script);
890
891
        // Get witnessScript type
892
47
        script_type = Solver(next_script, solutions);
893
47
        stack.witness.pop_back();
894
47
        stack.script = std::move(stack.witness);
895
47
        stack.witness.clear();
896
47
        sigversion = SigVersion::WITNESS_V0;
897
47
    }
898
35.2k
    if (script_type == TxoutType::MULTISIG && !stack.script.empty()) {
899
        // Build a map of pubkey -> signature by matching sigs to pubkeys:
900
63
        assert(solutions.size() > 1);
901
63
        unsigned int num_pubkeys = solutions.size()-2;
902
63
        unsigned int last_success_key = 0;
903
330
        for (const valtype& sig : stack.script) {
904
1.00k
            for (unsigned int i = last_success_key; i < num_pubkeys; ++i) {
905
834
                const valtype& pubkey = solutions[i+1];
906
                // We either have a signature for this pubkey, or we have found a signature and it is valid
907
834
                if (data.signatures.contains(CPubKey(pubkey).GetID()) || extractor_checker.CheckECDSASignature(sig, pubkey, next_script, sigversion)) {
908
160
                    last_success_key = i + 1;
909
160
                    break;
910
160
                }
911
834
            }
912
330
        }
913
63
    }
914
915
35.2k
    return data;
916
35.2k
}
917
918
void UpdateInput(CTxIn& input, const SignatureData& data)
919
42.5k
{
920
42.5k
    input.scriptSig = data.scriptSig;
921
42.5k
    input.scriptWitness = data.scriptWitness;
922
42.5k
}
923
924
void SignatureData::MergeSignatureData(SignatureData sigdata)
925
82
{
926
82
    if (complete) return;
927
77
    if (sigdata.complete) {
928
8
        *this = std::move(sigdata);
929
8
        return;
930
8
    }
931
69
    if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
932
13
        redeem_script = sigdata.redeem_script;
933
13
    }
934
69
    if (witness_script.empty() && !sigdata.witness_script.empty()) {
935
16
        witness_script = sigdata.witness_script;
936
16
    }
937
69
    signatures.insert(std::make_move_iterator(sigdata.signatures.begin()), std::make_move_iterator(sigdata.signatures.end()));
938
69
}
939
940
namespace {
941
/** Dummy signature checker which accepts all signatures. */
942
class DummySignatureChecker final : public BaseSignatureChecker
943
{
944
public:
945
1.49k
    DummySignatureChecker() = default;
946
8
    bool CheckECDSASignature(const std::vector<unsigned char>& sig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override { return sig.size() != 0; }
947
0
    bool CheckSchnorrSignature(std::span<const unsigned char> sig, std::span<const unsigned char> pubkey, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror) const override { return sig.size() != 0; }
948
0
    bool CheckLockTime(const CScriptNum& nLockTime) const override { return true; }
949
0
    bool CheckSequence(const CScriptNum& nSequence) const override { return true; }
950
};
951
}
952
953
const BaseSignatureChecker& DUMMY_CHECKER = DummySignatureChecker();
954
955
namespace {
956
class DummySignatureCreator final : public BaseSignatureCreator {
957
private:
958
    char m_r_len = 32;
959
    char m_s_len = 32;
960
public:
961
2.99k
    DummySignatureCreator(char r_len, char s_len) : m_r_len(r_len), m_s_len(s_len) {}
962
7
    const BaseSignatureChecker& Checker() const override { return DUMMY_CHECKER; }
963
    bool CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const override
964
4
    {
965
        // Create a dummy signature that is a valid DER-encoding
966
4
        vchSig.assign(m_r_len + m_s_len + 7, '\000');
967
4
        vchSig[0] = 0x30;
968
4
        vchSig[1] = m_r_len + m_s_len + 4;
969
4
        vchSig[2] = 0x02;
970
4
        vchSig[3] = m_r_len;
971
4
        vchSig[4] = 0x01;
972
4
        vchSig[4 + m_r_len] = 0x02;
973
4
        vchSig[5 + m_r_len] = m_s_len;
974
4
        vchSig[6 + m_r_len] = 0x01;
975
4
        vchSig[6 + m_r_len + m_s_len] = SIGHASH_ALL;
976
4
        return true;
977
4
    }
978
    bool CreateSchnorrSig(const SigningProvider& provider, std::vector<unsigned char>& sig, const XOnlyPubKey& pubkey, const uint256* leaf_hash, const uint256* tweak, SigVersion sigversion) const override
979
3
    {
980
3
        sig.assign(64, '\000');
981
3
        return true;
982
3
    }
983
    std::vector<uint8_t> CreateMuSig2Nonce(const SigningProvider& provider, const CPubKey& aggregate_pubkey, const CPubKey& script_pubkey, const CPubKey& part_pubkey, const uint256* leaf_hash, const uint256* merkle_root, SigVersion sigversion, const SignatureData& sigdata) const override
984
0
    {
985
0
        std::vector<uint8_t> out;
986
0
        out.assign(MUSIG2_PUBNONCE_SIZE, '\000');
987
0
        return out;
988
0
    }
989
    bool CreateMuSig2PartialSig(const SigningProvider& provider, uint256& partial_sig, const CPubKey& aggregate_pubkey, const CPubKey& script_pubkey, const CPubKey& part_pubkey, const uint256* leaf_hash, const std::vector<std::pair<uint256, bool>>& tweaks, SigVersion sigversion, const SignatureData& sigdata) const override
990
0
    {
991
0
        partial_sig = uint256::ONE;
992
0
        return true;
993
0
    }
994
    bool CreateMuSig2AggregateSig(const std::vector<CPubKey>& participants, std::vector<uint8_t>& sig, const CPubKey& aggregate_pubkey, const CPubKey& script_pubkey, const uint256* leaf_hash, const std::vector<std::pair<uint256, bool>>& tweaks, SigVersion sigversion, const SignatureData& sigdata) const override
995
0
    {
996
0
        sig.assign(64, '\000');
997
0
        return true;
998
0
    }
999
};
1000
1001
}
1002
1003
const BaseSignatureCreator& DUMMY_SIGNATURE_CREATOR = DummySignatureCreator(32, 32);
1004
const BaseSignatureCreator& DUMMY_MAXIMUM_SIGNATURE_CREATOR = DummySignatureCreator(33, 32);
1005
1006
bool IsSegWitOutput(const SigningProvider& provider, const CScript& script)
1007
0
{
1008
0
    int version;
1009
0
    valtype program;
1010
0
    if (script.IsWitnessProgram(version, program)) return true;
1011
0
    if (script.IsPayToScriptHash()) {
1012
0
        std::vector<valtype> solutions;
1013
0
        auto whichtype = Solver(script, solutions);
1014
0
        if (whichtype == TxoutType::SCRIPTHASH) {
1015
0
            auto h160 = uint160(solutions[0]);
1016
0
            CScript subscript;
1017
0
            if (provider.GetCScript(CScriptID{h160}, subscript)) {
1018
0
                if (subscript.IsWitnessProgram(version, program)) return true;
1019
0
            }
1020
0
        }
1021
0
    }
1022
0
    return false;
1023
0
}
1024
1025
bool SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore, const std::map<COutPoint, Coin>& coins, const SignOptions& options, std::map<int, bilingual_str>& input_errors)
1026
17.0k
{
1027
17.0k
    bool fHashSingle = ((options.sighash_type & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
1028
1029
    // Use CTransaction for the constant parts of the
1030
    // transaction to avoid rehashing.
1031
17.0k
    const CTransaction txConst(mtx);
1032
1033
17.0k
    PrecomputedTransactionData txdata;
1034
17.0k
    std::vector<CTxOut> spent_outputs;
1035
54.8k
    for (unsigned int i = 0; i < mtx.vin.size(); ++i) {
1036
37.8k
        CTxIn& txin = mtx.vin[i];
1037
37.8k
        auto coin = coins.find(txin.prevout);
1038
37.8k
        if (coin == coins.end() || coin->second.IsSpent()) {
1039
10
            txdata.Init(txConst, /*spent_outputs=*/{}, /*force=*/true);
1040
10
            break;
1041
37.8k
        } else {
1042
37.8k
            spent_outputs.emplace_back(coin->second.out.nValue, coin->second.out.scriptPubKey);
1043
37.8k
        }
1044
37.8k
    }
1045
17.0k
    if (spent_outputs.size() == mtx.vin.size()) {
1046
17.0k
        txdata.Init(txConst, std::move(spent_outputs), true);
1047
17.0k
    }
1048
1049
    // Sign what we can:
1050
54.9k
    for (unsigned int i = 0; i < mtx.vin.size(); ++i) {
1051
37.8k
        CTxIn& txin = mtx.vin[i];
1052
37.8k
        auto coin = coins.find(txin.prevout);
1053
37.8k
        if (coin == coins.end() || coin->second.IsSpent()) {
1054
19
            input_errors[i] = _("Input not found or already spent");
1055
19
            continue;
1056
19
        }
1057
37.8k
        const CScript& prevPubKey = coin->second.out.scriptPubKey;
1058
37.8k
        const CAmount& amount = coin->second.out.nValue;
1059
1060
37.8k
        SignatureData sigdata = DataFromTransaction(mtx, i, coin->second.out);
1061
        // Only sign SIGHASH_SINGLE if there's a corresponding output:
1062
37.8k
        if (!fHashSingle || (i < mtx.vout.size())) {
1063
37.8k
            ProduceSignature(*keystore, MutableTransactionSignatureCreator(mtx, i, amount, &txdata, options), prevPubKey, sigdata);
1064
37.8k
        }
1065
1066
37.8k
        UpdateInput(txin, sigdata);
1067
1068
        // amount must be specified for valid segwit signature
1069
37.8k
        if (amount == MAX_MONEY && !txin.scriptWitness.IsNull()) {
1070
13
            input_errors[i] = _("Missing amount");
1071
13
            continue;
1072
13
        }
1073
1074
37.8k
        ScriptError serror = SCRIPT_ERR_OK;
1075
37.8k
        if (!sigdata.complete && !VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount, txdata, MissingDataBehavior::FAIL), &serror)) {
1076
25.2k
            if (serror == SCRIPT_ERR_INVALID_STACK_OPERATION) {
1077
                // Unable to sign input and verification failed (possible attempt to partially sign).
1078
7.88k
                input_errors[i] = Untranslated("Unable to sign input, invalid stack size (possibly missing key)");
1079
17.3k
            } else if (serror == SCRIPT_ERR_SIG_NULLFAIL) {
1080
                // Verification failed (possibly due to insufficient signatures).
1081
81
                input_errors[i] = Untranslated("CHECK(MULTI)SIG failing with non-zero signature (possibly need more signatures)");
1082
17.2k
            } else {
1083
17.2k
                input_errors[i] = Untranslated(ScriptErrorString(serror));
1084
17.2k
            }
1085
25.2k
        } else {
1086
            // If this input succeeds, make sure there is no error set for it
1087
12.6k
            input_errors.erase(i);
1088
12.6k
        }
1089
37.8k
    }
1090
17.0k
    return input_errors.empty();
1091
17.0k
}