Coverage Report

Created: 2026-10-07 13:27

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