Coverage Report

Created: 2026-04-29 19:21

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