Coverage Report

Created: 2026-05-30 09:47

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