Coverage Report

Created: 2026-10-03 10:33

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
73.5k
    : m_txto{tx}, nIn{input_idx}, m_options{options}, amount{amount},
48
73.5k
      checker{txdata ? MutableTransactionSignatureChecker{&m_txto, nIn, amount, *txdata, MissingDataBehavior::FAIL} :
49
73.5k
                       MutableTransactionSignatureChecker{&m_txto, nIn, amount, MissingDataBehavior::FAIL}},
50
73.5k
      m_txdata(txdata)
51
73.5k
{
52
73.5k
}
53
54
bool MutableTransactionSignatureCreator::CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& address, const CScript& scriptCode, SigVersion sigversion) const
55
34.7k
{
56
34.7k
    assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0);
57
58
34.7k
    CKey key;
59
34.7k
    if (!provider.GetKey(address, key))
60
16.2k
        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.59k
{
86
1.59k
    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.59k
    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
798
        execdata.m_codeseparator_pos_init = true;
98
798
        execdata.m_codeseparator_pos = 0xFFFFFFFF; // Only support non-OP_CODESEPARATOR BIP342 signing for now.
99
798
        if (!leaf_hash) return std::nullopt; // BIP342 signing needs leaf hash.
100
798
        execdata.m_tapleaf_hash_init = true;
101
798
        execdata.m_tapleaf_hash = *leaf_hash;
102
798
    }
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
110k
{
110
110k
    CKey key;
111
110k
    if (!provider.GetKeyByXOnly(pubkey, key)) return false;
112
113
1.08k
    std::optional<uint256> hash = ComputeSchnorrSignatureHash(leaf_hash, sigversion);
114
1.08k
    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.33k
{
125
5.33k
    assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
126
127
    // Retrieve the private key
128
5.33k
    CKey key;
129
5.33k
    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
11.1k
{
153
11.1k
    assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
154
155
    // Retrieve private key
156
11.1k
    CKey key;
157
11.1k
    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
517
    const std::map<CPubKey, std::vector<uint8_t>>& pubnonces = pubnonce_it->second;
170
171
    // Check if enough pubnonces
172
517
    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.06k
{
199
4.06k
    assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
200
4.06k
    if (!participants.size()) return false;
201
202
    // Retrieve pubnonces and partial sigs
203
4.06k
    auto this_leaf_aggkey = std::make_pair(script_pubkey, leaf_hash ? *leaf_hash : uint256());
204
4.06k
    auto pubnonce_it = sigdata.musig2_pubnonces.find(this_leaf_aggkey);
205
4.06k
    if (pubnonce_it == sigdata.musig2_pubnonces.end()) return false;
206
3.71k
    const std::map<CPubKey, std::vector<uint8_t>>& pubnonces = pubnonce_it->second;
207
3.71k
    auto partial_sigs_it = sigdata.musig2_partial_sigs.find(this_leaf_aggkey);
208
3.71k
    if (partial_sigs_it == sigdata.musig2_partial_sigs.end()) return false;
209
819
    const std::map<CPubKey, uint256>& partial_sigs = partial_sigs_it->second;
210
211
    // Check if enough pubnonces and partial sigs
212
819
    if (pubnonces.size() != participants.size()) return false;
213
819
    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
7.82k
{
229
7.82k
    if (provider.GetCScript(scriptid, script)) {
230
2.05k
        return true;
231
2.05k
    }
232
    // Look for scripts in SignatureData
233
5.76k
    if (CScriptID(sigdata.redeem_script) == scriptid) {
234
3.93k
        script = sigdata.redeem_script;
235
3.93k
        return true;
236
3.93k
    } else if (CScriptID(sigdata.witness_script) == scriptid) {
237
348
        script = sigdata.witness_script;
238
348
        return true;
239
348
    }
240
1.48k
    return false;
241
5.76k
}
242
243
static bool GetPubKey(const SigningProvider& provider, const SignatureData& sigdata, const CKeyID& address, CPubKey& pubkey)
244
66.9k
{
245
    // Look for pubkey in all partial sigs
246
66.9k
    const auto it = sigdata.signatures.find(address);
247
66.9k
    if (it != sigdata.signatures.end()) {
248
116
        pubkey = it->second.first;
249
116
        return true;
250
116
    }
251
    // Look for pubkey in pubkey lists
252
66.8k
    const auto& pk_it = sigdata.misc_pubkeys.find(address);
253
66.8k
    if (pk_it != sigdata.misc_pubkeys.end()) {
254
14.3k
        pubkey = pk_it->second.first;
255
14.3k
        return true;
256
14.3k
    }
257
52.4k
    const auto& tap_pk_it = sigdata.tap_pubkeys.find(address);
258
52.4k
    if (tap_pk_it != sigdata.tap_pubkeys.end()) {
259
346
        pubkey = tap_pk_it->second.GetEvenCorrespondingCPubKey();
260
346
        return true;
261
346
    }
262
    // Query the underlying provider
263
52.1k
    return provider.GetPubKey(address, pubkey);
264
52.4k
}
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.4k
{
268
35.4k
    CKeyID keyid = pubkey.GetID();
269
35.4k
    const auto it = sigdata.signatures.find(keyid);
270
35.4k
    if (it != sigdata.signatures.end()) {
271
673
        sig_out = it->second.second;
272
673
        return true;
273
673
    }
274
34.7k
    KeyOriginInfo info;
275
34.7k
    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.7k
    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.2k
    sigdata.missing_sigs.push_back(keyid);
285
16.2k
    return false;
286
34.7k
}
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
109k
{
290
109k
    Assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
291
292
    // Lookup derivation paths for the script pubkey
293
109k
    KeyOriginInfo agg_info;
294
109k
    auto misc_pk_it = sigdata.taproot_misc_pubkeys.find(script_pubkey);
295
109k
    if (misc_pk_it != sigdata.taproot_misc_pubkeys.end()) {
296
98.3k
        agg_info = misc_pk_it->second.second;
297
98.3k
    }
298
299
109k
    for (const auto& [agg_pub, part_pks] : sigdata.musig2_pubkeys) {
300
12.3k
        if (part_pks.empty()) continue;
301
302
        // Fill participant derivation path info
303
33.5k
        for (const auto& part_pk : part_pks) {
304
33.5k
            KeyOriginInfo part_info;
305
33.5k
            if (provider.GetKeyOrigin(part_pk.GetID(), part_info)) {
306
6.71k
                XOnlyPubKey xonly_part(part_pk);
307
6.71k
                auto it = sigdata.taproot_misc_pubkeys.find(xonly_part);
308
6.71k
                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.71k
                if (leaf_hash) it->second.first.insert(*leaf_hash);
312
6.71k
            }
313
33.5k
        }
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.3k
        std::vector<std::pair<uint256, bool>> tweaks;
318
12.3k
        CPubKey plain_pub = agg_pub;
319
12.3k
        if (XOnlyPubKey(agg_pub) != script_pubkey) {
320
11.1k
            if (agg_info.path.empty()) continue;
321
5.31k
            if (agg_info.fingerprint != agg_pub.GetID().fingerprint()) {
322
2.39k
                continue;
323
2.39k
            }
324
            // Get the BIP32 derivation tweaks
325
2.92k
            CExtPubKey extpub = CreateMuSig2SyntheticXpub(agg_pub);
326
5.84k
            for (const uint32_t i : agg_info.path) {
327
5.84k
                if (i >> 31) return false; // Hardened derivation is not possible from a public key
328
5.84k
                auto& [t, xonly] = tweaks.emplace_back();
329
5.84k
                xonly = false;
330
5.84k
                if (!extpub.Derive(extpub, i, &t)) {
331
0
                    return false;
332
0
                }
333
5.84k
            }
334
2.92k
            if (XOnlyPubKey(extpub.pubkey) != script_pubkey) continue;
335
2.91k
            plain_pub = extpub.pubkey;
336
2.91k
        }
337
338
        // Add the merkle root tweak
339
4.06k
        if (sigversion == SigVersion::TAPROOT && merkle_root) {
340
917
            tweaks.emplace_back(script_pubkey.ComputeTapTweakHash(merkle_root->IsNull() ? nullptr : merkle_root), true);
341
917
            std::optional<std::pair<XOnlyPubKey, bool>> tweaked = script_pubkey.CreateTapTweak(merkle_root->IsNull() ? nullptr : merkle_root);
342
917
            if (!Assume(tweaked)) return false;
343
917
            plain_pub = tweaked->first.GetCPubKeys().at(tweaked->second ? 1 : 0);
344
917
        }
345
346
        // First try to aggregate
347
4.06k
        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.98k
        auto pub_key_leaf_hash = std::make_pair(plain_pub, leaf_hash ? *leaf_hash : uint256());
358
11.1k
        for (const CPubKey& part_pk : part_pks) {
359
11.1k
            uint256 partial_sig;
360
11.1k
            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
11.1k
        }
364
        // If there are any partial signatures, continue with next aggregate pubkey
365
3.98k
        auto partial_sigs_it = sigdata.musig2_partial_sigs.find(pub_key_leaf_hash);
366
3.98k
        if (partial_sigs_it != sigdata.musig2_partial_sigs.end() && !partial_sigs_it->second.empty()) {
367
896
            continue;
368
896
        }
369
        // No partial sigs, try to make pubnonces
370
3.09k
        std::map<CPubKey, std::vector<uint8_t>>& pubnonces = sigdata.musig2_pubnonces[pub_key_leaf_hash];
371
8.57k
        for (const CPubKey& part_pk : part_pks) {
372
8.57k
            if (pubnonces.contains(part_pk)) continue;
373
5.33k
            std::vector<uint8_t> pubnonce = creator.CreateMuSig2Nonce(provider, agg_pub, plain_pub, part_pk, leaf_hash, merkle_root, sigversion, sigdata);
374
5.33k
            if (pubnonce.empty()) continue;
375
163
            pubnonces[part_pk] = std::move(pubnonce);
376
163
        }
377
3.09k
    }
378
109k
    return true;
379
109k
}
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.7k
{
383
94.7k
    KeyOriginInfo info;
384
94.7k
    if (provider.GetKeyOriginByXOnly(pubkey, info)) {
385
48.6k
        auto it = sigdata.taproot_misc_pubkeys.find(pubkey);
386
48.6k
        if (it == sigdata.taproot_misc_pubkeys.end()) {
387
706
            sigdata.taproot_misc_pubkeys.emplace(pubkey, std::make_pair(std::set<uint256>({leaf_hash}), info));
388
47.9k
        } else {
389
47.9k
            it->second.first.insert(leaf_hash);
390
47.9k
        }
391
48.6k
    }
392
393
94.7k
    auto lookup_key = std::make_pair(pubkey, leaf_hash);
394
94.7k
    auto it = sigdata.taproot_script_sigs.find(lookup_key);
395
94.7k
    if (it != sigdata.taproot_script_sigs.end()) {
396
549
        sig_out = it->second;
397
549
        return true;
398
549
    }
399
400
94.1k
    if (creator.CreateSchnorrSig(provider, sig_out, pubkey, &leaf_hash, nullptr, sigversion)) {
401
491
        sigdata.taproot_script_sigs[lookup_key] = sig_out;
402
93.6k
    } else if (!SignMuSig2(creator, sigdata, provider, sig_out, pubkey, /*merkle_root=*/nullptr, &leaf_hash, sigversion)) {
403
0
        return false;
404
0
    }
405
406
94.1k
    return sigdata.taproot_script_sigs.contains(lookup_key);
407
94.1k
}
408
409
template<typename M, typename K, typename V>
410
miniscript::Availability MsLookupHelper(const M& map, const K& key, V& value)
411
73
{
412
73
    auto it = map.find(key);
413
73
    if (it != map.end()) {
414
32
        value = it->second;
415
32
        return miniscript::Availability::YES;
416
32
    }
417
41
    return miniscript::Availability::NO;
418
73
}
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.82k
                       miniscript::MiniscriptContext script_ctx) : m_provider(provider),
439
4.82k
                                                                   m_sig_data(sig_data),
440
4.82k
                                                                   m_creator(creator),
441
4.82k
                                                                   m_witness_script(witscript),
442
4.82k
                                                                   m_script_ctx(script_ctx) {}
Satisfier<XOnlyPubKey>::Satisfier(SigningProvider const&, SignatureData&, BaseSignatureCreator const&, CScript const&, miniscript::MiniscriptContext)
Line
Count
Source
438
4.57k
                       miniscript::MiniscriptContext script_ctx) : m_provider(provider),
439
4.57k
                                                                   m_sig_data(sig_data),
440
4.57k
                                                                   m_creator(creator),
441
4.57k
                                                                   m_witness_script(witscript),
442
4.57k
                                                                   m_script_ctx(script_ctx) {}
Satisfier<CPubKey>::Satisfier(SigningProvider const&, SignatureData&, BaseSignatureCreator const&, CScript const&, miniscript::MiniscriptContext)
Line
Count
Source
438
252
                       miniscript::MiniscriptContext script_ctx) : m_provider(provider),
439
252
                                                                   m_sig_data(sig_data),
440
252
                                                                   m_creator(creator),
441
252
                                                                   m_witness_script(witscript),
442
252
                                                                   m_script_ctx(script_ctx) {}
443
444
320k
    static bool KeyCompare(const Key& a, const Key& b) {
445
320k
        return a < b;
446
320k
    }
Satisfier<XOnlyPubKey>::KeyCompare(XOnlyPubKey const&, XOnlyPubKey const&)
Line
Count
Source
444
319k
    static bool KeyCompare(const Key& a, const Key& b) {
445
319k
        return a < b;
446
319k
    }
Satisfier<CPubKey>::KeyCompare(CPubKey const&, CPubKey const&)
Line
Count
Source
444
1.51k
    static bool KeyCompare(const Key& a, const Key& b) {
445
1.51k
        return a < b;
446
1.51k
    }
447
448
    //! Get a CPubKey from a key hash. Note the key hash may be of an xonly pubkey.
449
    template<typename I>
450
460
    std::optional<CPubKey> CPubFromPKHBytes(I first, I last) const {
451
460
        assert(last - first == 20);
452
460
        CPubKey pubkey;
453
460
        CKeyID key_id;
454
460
        std::copy(first, last, key_id.begin());
455
460
        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
460
    }
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
360
    std::optional<CPubKey> CPubFromPKHBytes(I first, I last) const {
451
360
        assert(last - first == 20);
452
360
        CPubKey pubkey;
453
360
        CKeyID key_id;
454
360
        std::copy(first, last, key_id.begin());
455
360
        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
360
    }
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
100
    std::optional<CPubKey> CPubFromPKHBytes(I first, I last) const {
451
100
        assert(last - first == 20);
452
100
        CPubKey pubkey;
453
100
        CKeyID key_id;
454
100
        std::copy(first, last, key_id.begin());
455
100
        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
100
    }
459
460
    //! Conversion to raw public key.
461
459
    std::vector<unsigned char> ToPKBytes(const Key& key) const { return {key.begin(), key.end()}; }
Satisfier<XOnlyPubKey>::ToPKBytes(XOnlyPubKey const&) const
Line
Count
Source
461
360
    std::vector<unsigned char> ToPKBytes(const Key& key) const { return {key.begin(), key.end()}; }
Satisfier<CPubKey>::ToPKBytes(CPubKey const&) const
Line
Count
Source
461
99
    std::vector<unsigned char> ToPKBytes(const Key& key) const { return {key.begin(), key.end()}; }
462
463
    //! Time lock satisfactions.
464
1.04k
    bool CheckAfter(uint32_t value) const { return m_creator.Checker().CheckLockTime(CScriptNum(value)); }
Satisfier<XOnlyPubKey>::CheckAfter(unsigned int) const
Line
Count
Source
464
790
    bool CheckAfter(uint32_t value) const { return m_creator.Checker().CheckLockTime(CScriptNum(value)); }
Satisfier<CPubKey>::CheckAfter(unsigned int) const
Line
Count
Source
464
254
    bool CheckAfter(uint32_t value) const { return m_creator.Checker().CheckLockTime(CScriptNum(value)); }
465
165
    bool CheckOlder(uint32_t value) const { return m_creator.Checker().CheckSequence(CScriptNum(value)); }
Satisfier<XOnlyPubKey>::CheckOlder(unsigned int) const
Line
Count
Source
465
62
    bool CheckOlder(uint32_t value) const { return m_creator.Checker().CheckSequence(CScriptNum(value)); }
Satisfier<CPubKey>::CheckOlder(unsigned int) const
Line
Count
Source
465
103
    bool CheckOlder(uint32_t value) const { return m_creator.Checker().CheckSequence(CScriptNum(value)); }
466
467
    //! Hash preimage satisfactions.
468
25
    miniscript::Availability SatSHA256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
469
25
        return MsLookupHelper(m_sig_data.sha256_preimages, hash, preimage);
470
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
468
25
    miniscript::Availability SatSHA256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
469
25
        return MsLookupHelper(m_sig_data.sha256_preimages, hash, preimage);
470
25
    }
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
3.64M
    miniscript::MiniscriptContext MsContext() const {
482
3.64M
        return m_script_ctx;
483
3.64M
    }
Satisfier<XOnlyPubKey>::MsContext() const
Line
Count
Source
481
3.64M
    miniscript::MiniscriptContext MsContext() const {
482
3.64M
        return m_script_ctx;
483
3.64M
    }
Satisfier<CPubKey>::MsContext() const
Line
Count
Source
481
3.96k
    miniscript::MiniscriptContext MsContext() const {
482
3.96k
        return m_script_ctx;
483
3.96k
    }
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
252
                          : Satisfier(provider, sig_data, creator, witscript, miniscript::MiniscriptContext::P2WSH) {}
491
492
    //! Conversion from a raw compressed public key.
493
    template <typename I>
494
599
    std::optional<CPubKey> FromPKBytes(I first, I last) const {
495
599
        CPubKey pubkey{first, last};
496
599
        if (pubkey.IsValid()) return pubkey;
497
1
        return {};
498
599
    }
499
500
    //! Conversion from a raw compressed public key hash.
501
    template<typename I>
502
100
    std::optional<CPubKey> FromPKHBytes(I first, I last) const {
503
100
        return Satisfier::CPubFromPKHBytes(first, last);
504
100
    }
505
506
    //! Satisfy an ECDSA signature check.
507
697
    miniscript::Availability Sign(const CPubKey& key, std::vector<unsigned char>& sig) const {
508
697
        if (CreateSig(m_creator, m_sig_data, m_provider, sig, key, m_witness_script, SigVersion::WITNESS_V0)) {
509
350
            return miniscript::Availability::YES;
510
350
        }
511
347
        return miniscript::Availability::NO;
512
697
    }
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.57k
                          : Satisfier(provider, sig_data, creator, script, miniscript::MiniscriptContext::TAPSCRIPT),
523
4.57k
                            m_leaf_hash(leaf_hash) {}
524
525
    //! Conversion from a raw xonly public key.
526
    template <typename I>
527
94.3k
    std::optional<XOnlyPubKey> FromPKBytes(I first, I last) const {
528
94.3k
        if (last - first != 32) return {};
529
94.3k
        XOnlyPubKey pubkey;
530
94.3k
        std::copy(first, last, pubkey.begin());
531
94.3k
        return pubkey;
532
94.3k
    }
533
534
    //! Conversion from a raw xonly public key hash.
535
    template<typename I>
536
360
    std::optional<XOnlyPubKey> FromPKHBytes(I first, I last) const {
537
360
        if (auto pubkey = Satisfier::CPubFromPKHBytes(first, last)) return XOnlyPubKey{*pubkey};
538
0
        return {};
539
360
    }
540
541
    //! Satisfy a BIP340 signature check.
542
94.7k
    miniscript::Availability Sign(const XOnlyPubKey& key, std::vector<unsigned char>& sig) const {
543
94.7k
        if (CreateTaprootScriptSig(m_creator, m_sig_data, m_provider, sig, key, m_leaf_hash, SigVersion::TAPSCRIPT)) {
544
1.08k
            return miniscript::Availability::YES;
545
1.08k
        }
546
93.6k
        return miniscript::Availability::NO;
547
94.7k
    }
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.57k
{
552
    // Only BIP342 tapscript signing is supported for now.
553
4.57k
    if (leaf_version != TAPROOT_LEAF_TAPSCRIPT) return false;
554
555
4.57k
    uint256 leaf_hash = ComputeTapleafHash(leaf_version, script_bytes);
556
4.57k
    CScript script = CScript(script_bytes.begin(), script_bytes.end());
557
558
4.57k
    TapSatisfier ms_satisfier{provider, sigdata, creator, script, leaf_hash};
559
4.57k
    const auto ms = miniscript::FromScript(script, ms_satisfier);
560
4.57k
    return ms && ms->Satisfy(ms_satisfier, result) == miniscript::Availability::YES;
561
4.57k
}
562
563
static bool SignTaproot(const SigningProvider& provider, const BaseSignatureCreator& creator, const WitnessV1Taproot& output, SignatureData& sigdata, std::vector<valtype>& result)
564
8.48k
{
565
8.48k
    TaprootSpendData spenddata;
566
8.48k
    TaprootBuilder builder;
567
568
    // Gather information about this output.
569
8.48k
    if (provider.GetTaprootSpendData(output, spenddata)) {
570
1.52k
        sigdata.tr_spenddata.Merge(spenddata);
571
1.52k
    }
572
8.48k
    if (provider.GetTaprootBuilder(output, builder)) {
573
1.52k
        sigdata.tr_builder = builder;
574
1.52k
    }
575
8.48k
    if (auto agg_keys = provider.GetAllMuSig2ParticipantPubkeys(); !agg_keys.empty()) {
576
539
        sigdata.musig2_pubkeys.insert(agg_keys.begin(), agg_keys.end());
577
539
    }
578
579
580
    // Try key path spending.
581
8.48k
    {
582
8.48k
        KeyOriginInfo internal_key_info;
583
8.48k
        if (provider.GetKeyOriginByXOnly(sigdata.tr_spenddata.internal_key, internal_key_info)) {
584
1.57k
            auto it = sigdata.taproot_misc_pubkeys.find(sigdata.tr_spenddata.internal_key);
585
1.57k
            if (it == sigdata.taproot_misc_pubkeys.end()) {
586
828
                sigdata.taproot_misc_pubkeys.emplace(sigdata.tr_spenddata.internal_key, std::make_pair(std::set<uint256>(), internal_key_info));
587
828
            }
588
1.57k
        }
589
590
8.48k
        KeyOriginInfo output_key_info;
591
8.48k
        if (provider.GetKeyOriginByXOnly(output, output_key_info)) {
592
141
            auto it = sigdata.taproot_misc_pubkeys.find(output);
593
141
            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
141
        }
597
598
16.0k
        auto make_keypath_sig = [&](const XOnlyPubKey& pk, const uint256* merkle_root) {
599
16.0k
            std::vector<unsigned char> sig;
600
16.0k
            if (creator.CreateSchnorrSig(provider, sig, pk, nullptr, merkle_root, SigVersion::TAPROOT)) {
601
593
                sigdata.taproot_key_path_sig = sig;
602
15.4k
            } else {
603
15.4k
                SignMuSig2(creator, sigdata, provider, sig, pk, merkle_root, /*leaf_hash=*/nullptr, SigVersion::TAPROOT);
604
15.4k
            }
605
16.0k
        };
606
607
        // First try signing with internal key
608
8.48k
        if (sigdata.taproot_key_path_sig.size() == 0) {
609
8.32k
            make_keypath_sig(sigdata.tr_spenddata.internal_key, &sigdata.tr_spenddata.merkle_root);
610
8.32k
        }
611
        // Try signing with output key if still no signature
612
8.48k
        if (sigdata.taproot_key_path_sig.size() == 0) {
613
7.75k
            make_keypath_sig(output, nullptr);
614
7.75k
        }
615
8.48k
        if (sigdata.taproot_key_path_sig.size()) {
616
780
            result = Vector(sigdata.taproot_key_path_sig);
617
780
            return true;
618
780
        }
619
8.48k
    }
620
621
    // Try script path spending.
622
7.70k
    std::vector<std::vector<unsigned char>> smallest_result_stack;
623
7.70k
    for (const auto& [key, control_blocks] : sigdata.tr_spenddata.scripts) {
624
4.57k
        const auto& [script, leaf_ver] = key;
625
4.57k
        std::vector<std::vector<unsigned char>> result_stack;
626
4.57k
        if (SignTaprootScript(provider, creator, sigdata, leaf_ver, script, result_stack)) {
627
718
            result_stack.emplace_back(std::begin(script), std::end(script)); // Push the script
628
718
            result_stack.push_back(*control_blocks.begin()); // Push the smallest control block
629
718
            if (smallest_result_stack.size() == 0 ||
630
718
                GetSerializeSize(result_stack) < GetSerializeSize(smallest_result_stack)) {
631
708
                smallest_result_stack = std::move(result_stack);
632
708
            }
633
718
        }
634
4.57k
    }
635
7.70k
    if (smallest_result_stack.size() != 0) {
636
686
        result = std::move(smallest_result_stack);
637
686
        return true;
638
686
    }
639
640
7.02k
    return false;
641
7.70k
}
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
122k
{
652
122k
    CScript scriptRet;
653
122k
    ret.clear();
654
122k
    std::vector<unsigned char> sig;
655
656
122k
    std::vector<valtype> vSolutions;
657
122k
    whichTypeRet = Solver(scriptPubKey, vSolutions);
658
659
122k
    switch (whichTypeRet) {
660
239
    case TxoutType::NONSTANDARD:
661
239
    case TxoutType::NULL_DATA:
662
239
    case TxoutType::WITNESS_UNKNOWN:
663
239
        return false;
664
241
    case TxoutType::PUBKEY:
665
241
        if (!CreateSig(creator, sigdata, provider, sig, CPubKey(vSolutions[0]), scriptPubKey, sigversion)) return false;
666
180
        ret.push_back(std::move(sig));
667
180
        return true;
668
66.4k
    case TxoutType::PUBKEYHASH: {
669
66.4k
        CKeyID keyID = CKeyID(uint160(vSolutions[0]));
670
66.4k
        CPubKey pubkey;
671
66.4k
        if (!GetPubKey(provider, sigdata, keyID, pubkey)) {
672
            // Pubkey could not be found, add to missing
673
34.1k
            sigdata.missing_pubkeys.push_back(keyID);
674
34.1k
            return false;
675
34.1k
        }
676
32.2k
        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.2k
    }
681
6.67k
    case TxoutType::SCRIPTHASH: {
682
6.67k
        uint160 h160{vSolutions[0]};
683
6.67k
        if (GetCScript(provider, sigdata, CScriptID{h160}, scriptRet)) {
684
5.34k
            ret.emplace_back(scriptRet.begin(), scriptRet.end());
685
5.34k
            return true;
686
5.34k
        }
687
        // Could not find redeemScript, add to missing
688
1.32k
        sigdata.missing_redeem_script = h160;
689
1.32k
        return false;
690
6.67k
    }
691
514
    case TxoutType::MULTISIG: {
692
514
        size_t required = vSolutions.front()[0];
693
514
        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.26k
                if (ret.size() < required + 1) {
701
1.21k
                    ret.push_back(std::move(sig));
702
1.21k
                }
703
1.26k
            }
704
2.17k
        }
705
514
        bool ok = ret.size() == required + 1;
706
890
        for (size_t i = 0; i + ret.size() < required + 1; ++i) {
707
376
            ret.emplace_back();
708
376
        }
709
514
        return ok;
710
6.67k
    }
711
39.2k
    case TxoutType::WITNESS_V0_KEYHASH:
712
39.2k
        ret.push_back(vSolutions[0]);
713
39.2k
        return true;
714
715
1.14k
    case TxoutType::WITNESS_V0_SCRIPTHASH:
716
1.14k
        if (GetCScript(provider, sigdata, CScriptID{RIPEMD160(vSolutions[0])}, scriptRet)) {
717
994
            ret.emplace_back(scriptRet.begin(), scriptRet.end());
718
994
            return true;
719
994
        }
720
        // Could not find witnessScript, add to missing
721
154
        sigdata.missing_witness_script = uint256(vSolutions[0]);
722
154
        return false;
723
724
8.48k
    case TxoutType::WITNESS_V1_TAPROOT:
725
8.48k
        return SignTaproot(provider, creator, WitnessV1Taproot(XOnlyPubKey{vSolutions[0]}), sigdata, ret);
726
727
1
    case TxoutType::ANCHOR:
728
1
        return true;
729
122k
    } // no default case, so the compiler can warn about missing cases
730
122k
    assert(false);
731
0
}
732
733
static CScript PushAll(const std::vector<valtype>& values)
734
77.7k
{
735
77.7k
    CScript result;
736
77.7k
    for (const valtype& v : values) {
737
21.3k
        if (v.size() == 0) {
738
249
            result << OP_0;
739
21.1k
        } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
740
0
            result << CScript::EncodeOP_N(v[0]);
741
21.1k
        } else if (v.size() == 1 && v[0] == 0x81) {
742
0
            result << OP_1NEGATE;
743
21.1k
        } else {
744
21.1k
            result << v;
745
21.1k
        }
746
21.3k
    }
747
77.7k
    return result;
748
77.7k
}
749
750
bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& fromPubKey, SignatureData& sigdata)
751
80.1k
{
752
80.1k
    if (sigdata.complete) return true;
753
754
77.7k
    std::vector<valtype> result;
755
77.7k
    TxoutType whichType;
756
77.7k
    bool solved = SignStep(provider, creator, fromPubKey, result, whichType, SigVersion::BASE, sigdata);
757
77.7k
    bool P2SH = false;
758
77.7k
    CScript subscript;
759
760
77.7k
    if (solved && whichType == TxoutType::SCRIPTHASH)
761
5.34k
    {
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.34k
        subscript = CScript(result[0].begin(), result[0].end());
766
5.34k
        sigdata.redeem_script = subscript;
767
5.34k
        solved = solved && SignStep(provider, creator, subscript, result, whichType, SigVersion::BASE, sigdata) && whichType != TxoutType::SCRIPTHASH;
768
5.34k
        P2SH = true;
769
5.34k
    }
770
771
77.7k
    if (solved && whichType == TxoutType::WITNESS_V0_KEYHASH)
772
38.9k
    {
773
38.9k
        CScript witnessscript;
774
38.9k
        witnessscript << OP_DUP << OP_HASH160 << ToByteVector(result[0]) << OP_EQUALVERIFY << OP_CHECKSIG;
775
38.9k
        TxoutType subType;
776
38.9k
        solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0, sigdata);
777
38.9k
        sigdata.scriptWitness.stack = result;
778
38.9k
        sigdata.witness = true;
779
38.9k
        result.clear();
780
38.9k
    }
781
38.8k
    else if (solved && whichType == TxoutType::WITNESS_V0_SCRIPTHASH)
782
983
    {
783
983
        CScript witnessscript(result[0].begin(), result[0].end());
784
983
        sigdata.witness_script = witnessscript;
785
786
983
        TxoutType subType{TxoutType::NONSTANDARD};
787
983
        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
983
        if (!solved && result.empty()) {
794
252
            WshSatisfier ms_satisfier{provider, sigdata, creator, witnessscript};
795
252
            const auto ms = miniscript::FromScript(witnessscript, ms_satisfier);
796
252
            solved = ms && ms->Satisfy(ms_satisfier, result) == miniscript::Availability::YES;
797
252
        }
798
983
        result.emplace_back(witnessscript.begin(), witnessscript.end());
799
800
983
        sigdata.scriptWitness.stack = result;
801
983
        sigdata.witness = true;
802
983
        result.clear();
803
37.8k
    } else if (whichType == TxoutType::WITNESS_V1_TAPROOT && !P2SH) {
804
8.48k
        sigdata.witness = true;
805
8.48k
        if (solved) {
806
1.46k
            sigdata.scriptWitness.stack = std::move(result);
807
1.46k
        }
808
8.48k
        result.clear();
809
29.3k
    } else if (solved && whichType == TxoutType::WITNESS_UNKNOWN) {
810
0
        sigdata.witness = true;
811
0
    }
812
813
77.7k
    if (!sigdata.witness) sigdata.scriptWitness.stack.clear();
814
77.7k
    if (P2SH) {
815
5.34k
        result.emplace_back(subscript.begin(), subscript.end());
816
5.34k
    }
817
77.7k
    sigdata.scriptSig = PushAll(result);
818
819
    // Test solution
820
77.7k
    sigdata.complete = solved && VerifyScript(sigdata.scriptSig, fromPubKey, &sigdata.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker());
821
77.7k
    return sigdata.complete;
822
80.1k
}
823
824
namespace {
825
class SignatureExtractorChecker final : public DeferringSignatureChecker
826
{
827
private:
828
    SignatureData& sigdata;
829
830
public:
831
48.0k
    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.28k
    {
835
3.28k
        if (m_checker.CheckECDSASignature(scriptSig, vchPubKey, scriptCode, sigversion)) {
836
2.50k
            CPubKey pubkey(vchPubKey);
837
2.50k
            sigdata.signatures.emplace(pubkey.GetID(), SigPair(pubkey, scriptSig));
838
2.50k
            return true;
839
2.50k
        }
840
775
        return false;
841
3.28k
    }
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
48.0k
    explicit Stacks(const SignatureData& data) : witness(data.scriptWitness.stack) {
852
48.0k
        EvalScript(script, data.scriptSig, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SigVersion::BASE);
853
48.0k
    }
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
48.0k
{
860
48.0k
    SignatureData data;
861
48.0k
    assert(tx.vin.size() > nIn);
862
48.0k
    data.scriptSig = tx.vin[nIn].scriptSig;
863
48.0k
    data.scriptWitness = tx.vin[nIn].scriptWitness;
864
48.0k
    Stacks stack(data);
865
866
    // Get signatures
867
48.0k
    MutableTransactionSignatureChecker tx_checker(&tx, nIn, txout.nValue, MissingDataBehavior::FAIL);
868
48.0k
    SignatureExtractorChecker extractor_checker(data, tx_checker);
869
48.0k
    if (VerifyScript(data.scriptSig, txout.scriptPubKey, &data.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, extractor_checker)) {
870
2.37k
        data.complete = true;
871
2.37k
        return data;
872
2.37k
    }
873
874
    // Get scripts
875
45.6k
    std::vector<std::vector<unsigned char>> solutions;
876
45.6k
    TxoutType script_type = Solver(txout.scriptPubKey, solutions);
877
45.6k
    SigVersion sigversion = SigVersion::BASE;
878
45.6k
    CScript next_script = txout.scriptPubKey;
879
880
45.6k
    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
45.6k
    if (script_type == TxoutType::WITNESS_V0_SCRIPTHASH && !stack.witness.empty() && !stack.witness.back().empty()) {
891
        // Get the witnessScript
892
44
        CScript witness_script(stack.witness.back().begin(), stack.witness.back().end());
893
44
        data.witness_script = witness_script;
894
44
        next_script = std::move(witness_script);
895
896
        // Get witnessScript type
897
44
        script_type = Solver(next_script, solutions);
898
44
        stack.witness.pop_back();
899
44
        stack.script = std::move(stack.witness);
900
44
        stack.witness.clear();
901
44
        sigversion = SigVersion::WITNESS_V0;
902
44
    }
903
45.6k
    if (script_type == TxoutType::MULTISIG && !stack.script.empty()) {
904
        // Build a map of pubkey -> signature by matching sigs to pubkeys:
905
60
        assert(solutions.size() > 1);
906
60
        unsigned int num_pubkeys = solutions.size()-2;
907
60
        unsigned int last_success_key = 0;
908
321
        for (const valtype& sig : stack.script) {
909
980
            for (unsigned int i = last_success_key; i < num_pubkeys; ++i) {
910
816
                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
816
                if (data.signatures.contains(CPubKey(pubkey).GetID()) || extractor_checker.CheckECDSASignature(sig, pubkey, next_script, sigversion)) {
913
157
                    last_success_key = i + 1;
914
157
                    break;
915
157
                }
916
816
            }
917
321
        }
918
60
    }
919
920
45.6k
    return data;
921
45.6k
}
922
923
void UpdateInput(CTxIn& input, const SignatureData& data)
924
52.6k
{
925
52.6k
    input.scriptSig = data.scriptSig;
926
52.6k
    input.scriptWitness = data.scriptWitness;
927
52.6k
}
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.57k
    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.15k
    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
65.1k
    for (unsigned int i = 0; i < mtx.vin.size(); ++i) {
1039
47.9k
        CTxIn& txin = mtx.vin[i];
1040
47.9k
        auto coin = coins.find(txin.prevout);
1041
47.9k
        if (coin == coins.end() || coin->second.IsSpent()) {
1042
10
            txdata.Init(txConst, /*spent_outputs=*/{}, /*force=*/true);
1043
10
            break;
1044
47.9k
        } else {
1045
47.9k
            spent_outputs.emplace_back(coin->second.out.nValue, coin->second.out.scriptPubKey);
1046
47.9k
        }
1047
47.9k
    }
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
65.1k
    for (unsigned int i = 0; i < mtx.vin.size(); ++i) {
1054
47.9k
        CTxIn& txin = mtx.vin[i];
1055
47.9k
        auto coin = coins.find(txin.prevout);
1056
47.9k
        if (coin == coins.end() || coin->second.IsSpent()) {
1057
19
            input_errors[i] = _("Input not found or already spent");
1058
19
            continue;
1059
19
        }
1060
47.9k
        const CScript& prevPubKey = coin->second.out.scriptPubKey;
1061
47.9k
        const CAmount& amount = coin->second.out.nValue;
1062
1063
47.9k
        SignatureData sigdata = DataFromTransaction(mtx, i, coin->second.out);
1064
47.9k
        ProduceSignature(*keystore, MutableTransactionSignatureCreator(mtx, i, amount, &txdata, options), prevPubKey, sigdata);
1065
1066
47.9k
        UpdateInput(txin, sigdata);
1067
1068
        // amount must be specified for valid segwit signature
1069
47.9k
        if (amount == MAX_MONEY && !txin.scriptWitness.IsNull()) {
1070
15
            input_errors[i] = _("Missing amount");
1071
15
            continue;
1072
15
        }
1073
1074
47.9k
        ScriptError serror = SCRIPT_ERR_OK;
1075
47.9k
        if (!sigdata.complete && !VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount, txdata, MissingDataBehavior::FAIL), &serror)) {
1076
33.7k
            if (serror == SCRIPT_ERR_INVALID_STACK_OPERATION) {
1077
                // Unable to sign input and verification failed (possible attempt to partially sign).
1078
16.2k
                input_errors[i] = Untranslated("Unable to sign input, invalid stack size (possibly missing key)");
1079
17.4k
            } else if (serror == SCRIPT_ERR_SIG_NULLFAIL) {
1080
                // Verification failed (possibly due to insufficient signatures).
1081
78
                input_errors[i] = Untranslated("CHECK(MULTI)SIG failing with non-zero signature (possibly need more signatures)");
1082
17.3k
            } else {
1083
17.3k
                input_errors[i] = Untranslated(ScriptErrorString(serror));
1084
17.3k
            }
1085
33.7k
        } else {
1086
            // If this input succeeds, make sure there is no error set for it
1087
14.2k
            input_errors.erase(i);
1088
14.2k
        }
1089
47.9k
    }
1090
17.1k
    return input_errors.empty();
1091
17.1k
}