fuzz coverage

Coverage Report

Created: 2025-06-01 19:34

/Users/eugenesiegel/btc/bitcoin/src/script/sign.cpp
Line
Count
Source (jump to first uncovered line)
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 <policy/policy.h>
11
#include <primitives/transaction.h>
12
#include <script/keyorigin.h>
13
#include <script/miniscript.h>
14
#include <script/script.h>
15
#include <script/signingprovider.h>
16
#include <script/solver.h>
17
#include <uint256.h>
18
#include <util/translation.h>
19
#include <util/vector.h>
20
21
typedef std::vector<unsigned char> valtype;
22
23
MutableTransactionSignatureCreator::MutableTransactionSignatureCreator(const CMutableTransaction& tx, unsigned int input_idx, const CAmount& amount, int hash_type)
24
0
    : m_txto{tx}, nIn{input_idx}, nHashType{hash_type}, amount{amount}, checker{&m_txto, nIn, amount, MissingDataBehavior::FAIL},
25
0
      m_txdata(nullptr)
26
0
{
27
0
}
28
29
MutableTransactionSignatureCreator::MutableTransactionSignatureCreator(const CMutableTransaction& tx, unsigned int input_idx, const CAmount& amount, const PrecomputedTransactionData* txdata, int hash_type)
30
0
    : m_txto{tx}, nIn{input_idx}, nHashType{hash_type}, amount{amount},
31
0
      checker{txdata ? MutableTransactionSignatureChecker{&m_txto, nIn, amount, *txdata, MissingDataBehavior::FAIL} :
32
0
                       MutableTransactionSignatureChecker{&m_txto, nIn, amount, MissingDataBehavior::FAIL}},
33
0
      m_txdata(txdata)
34
0
{
35
0
}
36
37
bool MutableTransactionSignatureCreator::CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& address, const CScript& scriptCode, SigVersion sigversion) const
38
0
{
39
0
    assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0);
40
41
0
    CKey key;
42
0
    if (!provider.GetKey(address, key))
43
0
        return false;
44
45
    // Signing with uncompressed keys is disabled in witness scripts
46
0
    if (sigversion == SigVersion::WITNESS_V0 && !key.IsCompressed())
47
0
        return false;
48
49
    // Signing without known amount does not work in witness scripts.
50
0
    if (sigversion == SigVersion::WITNESS_V0 && !MoneyRange(amount)) return false;
51
52
    // BASE/WITNESS_V0 signatures don't support explicit SIGHASH_DEFAULT, use SIGHASH_ALL instead.
53
0
    const int hashtype = nHashType == SIGHASH_DEFAULT ? SIGHASH_ALL : nHashType;
54
55
0
    uint256 hash = SignatureHash(scriptCode, m_txto, nIn, hashtype, amount, sigversion, m_txdata);
56
0
    if (!key.Sign(hash, vchSig))
57
0
        return false;
58
0
    vchSig.push_back((unsigned char)hashtype);
59
0
    return true;
60
0
}
61
62
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
63
0
{
64
0
    assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
65
66
0
    CKey key;
67
0
    if (!provider.GetKeyByXOnly(pubkey, key)) return false;
68
69
    // BIP341/BIP342 signing needs lots of precomputed transaction data. While some
70
    // (non-SIGHASH_DEFAULT) sighash modes exist that can work with just some subset
71
    // of data present, for now, only support signing when everything is provided.
72
0
    if (!m_txdata || !m_txdata->m_bip341_taproot_ready || !m_txdata->m_spent_outputs_ready) return false;
73
74
0
    ScriptExecutionData execdata;
75
0
    execdata.m_annex_init = true;
76
0
    execdata.m_annex_present = false; // Only support annex-less signing for now.
77
0
    if (sigversion == SigVersion::TAPSCRIPT) {
78
0
        execdata.m_codeseparator_pos_init = true;
79
0
        execdata.m_codeseparator_pos = 0xFFFFFFFF; // Only support non-OP_CODESEPARATOR BIP342 signing for now.
80
0
        if (!leaf_hash) return false; // BIP342 signing needs leaf hash.
81
0
        execdata.m_tapleaf_hash_init = true;
82
0
        execdata.m_tapleaf_hash = *leaf_hash;
83
0
    }
84
0
    uint256 hash;
85
0
    if (!SignatureHashSchnorr(hash, execdata, m_txto, nIn, nHashType, sigversion, *m_txdata, MissingDataBehavior::FAIL)) return false;
86
0
    sig.resize(64);
87
    // Use uint256{} as aux_rnd for now.
88
0
    if (!key.SignSchnorr(hash, sig, merkle_root, {})) return false;
89
0
    if (nHashType) sig.push_back(nHashType);
90
0
    return true;
91
0
}
92
93
static bool GetCScript(const SigningProvider& provider, const SignatureData& sigdata, const CScriptID& scriptid, CScript& script)
94
0
{
95
0
    if (provider.GetCScript(scriptid, script)) {
96
0
        return true;
97
0
    }
98
    // Look for scripts in SignatureData
99
0
    if (CScriptID(sigdata.redeem_script) == scriptid) {
100
0
        script = sigdata.redeem_script;
101
0
        return true;
102
0
    } else if (CScriptID(sigdata.witness_script) == scriptid) {
103
0
        script = sigdata.witness_script;
104
0
        return true;
105
0
    }
106
0
    return false;
107
0
}
108
109
static bool GetPubKey(const SigningProvider& provider, const SignatureData& sigdata, const CKeyID& address, CPubKey& pubkey)
110
0
{
111
    // Look for pubkey in all partial sigs
112
0
    const auto it = sigdata.signatures.find(address);
113
0
    if (it != sigdata.signatures.end()) {
114
0
        pubkey = it->second.first;
115
0
        return true;
116
0
    }
117
    // Look for pubkey in pubkey lists
118
0
    const auto& pk_it = sigdata.misc_pubkeys.find(address);
119
0
    if (pk_it != sigdata.misc_pubkeys.end()) {
120
0
        pubkey = pk_it->second.first;
121
0
        return true;
122
0
    }
123
0
    const auto& tap_pk_it = sigdata.tap_pubkeys.find(address);
124
0
    if (tap_pk_it != sigdata.tap_pubkeys.end()) {
125
0
        pubkey = tap_pk_it->second.GetEvenCorrespondingCPubKey();
126
0
        return true;
127
0
    }
128
    // Query the underlying provider
129
0
    return provider.GetPubKey(address, pubkey);
130
0
}
131
132
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)
133
0
{
134
0
    CKeyID keyid = pubkey.GetID();
135
0
    const auto it = sigdata.signatures.find(keyid);
136
0
    if (it != sigdata.signatures.end()) {
137
0
        sig_out = it->second.second;
138
0
        return true;
139
0
    }
140
0
    KeyOriginInfo info;
141
0
    if (provider.GetKeyOrigin(keyid, info)) {
142
0
        sigdata.misc_pubkeys.emplace(keyid, std::make_pair(pubkey, std::move(info)));
143
0
    }
144
0
    if (creator.CreateSig(provider, sig_out, keyid, scriptcode, sigversion)) {
145
0
        auto i = sigdata.signatures.emplace(keyid, SigPair(pubkey, sig_out));
146
0
        assert(i.second);
147
0
        return true;
148
0
    }
149
    // Could not make signature or signature not found, add keyid to missing
150
0
    sigdata.missing_sigs.push_back(keyid);
151
0
    return false;
152
0
}
153
154
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)
155
0
{
156
0
    KeyOriginInfo info;
157
0
    if (provider.GetKeyOriginByXOnly(pubkey, info)) {
158
0
        auto it = sigdata.taproot_misc_pubkeys.find(pubkey);
159
0
        if (it == sigdata.taproot_misc_pubkeys.end()) {
160
0
            sigdata.taproot_misc_pubkeys.emplace(pubkey, std::make_pair(std::set<uint256>({leaf_hash}), info));
161
0
        } else {
162
0
            it->second.first.insert(leaf_hash);
163
0
        }
164
0
    }
165
166
0
    auto lookup_key = std::make_pair(pubkey, leaf_hash);
167
0
    auto it = sigdata.taproot_script_sigs.find(lookup_key);
168
0
    if (it != sigdata.taproot_script_sigs.end()) {
169
0
        sig_out = it->second;
170
0
        return true;
171
0
    }
172
0
    if (creator.CreateSchnorrSig(provider, sig_out, pubkey, &leaf_hash, nullptr, sigversion)) {
173
0
        sigdata.taproot_script_sigs[lookup_key] = sig_out;
174
0
        return true;
175
0
    }
176
0
    return false;
177
0
}
178
179
template<typename M, typename K, typename V>
180
miniscript::Availability MsLookupHelper(const M& map, const K& key, V& value)
181
0
{
182
0
    auto it = map.find(key);
183
0
    if (it != map.end()) {
184
0
        value = it->second;
185
0
        return miniscript::Availability::YES;
186
0
    }
187
0
    return miniscript::Availability::NO;
188
0
}
189
190
/**
191
 * Context for solving a Miniscript.
192
 * If enough material (access to keys, hash preimages, ..) is given, produces a valid satisfaction.
193
 */
194
template<typename Pk>
195
struct Satisfier {
196
    using Key = Pk;
197
198
    const SigningProvider& m_provider;
199
    SignatureData& m_sig_data;
200
    const BaseSignatureCreator& m_creator;
201
    const CScript& m_witness_script;
202
    //! The context of the script we are satisfying (either P2WSH or Tapscript).
203
    const miniscript::MiniscriptContext m_script_ctx;
204
205
    explicit Satisfier(const SigningProvider& provider LIFETIMEBOUND, SignatureData& sig_data LIFETIMEBOUND,
206
                       const BaseSignatureCreator& creator LIFETIMEBOUND,
207
                       const CScript& witscript LIFETIMEBOUND,
208
0
                       miniscript::MiniscriptContext script_ctx) : m_provider(provider),
209
0
                                                                   m_sig_data(sig_data),
210
0
                                                                   m_creator(creator),
211
0
                                                                   m_witness_script(witscript),
212
0
                                                                   m_script_ctx(script_ctx) {}
Unexecuted instantiation: _ZN9SatisfierI11XOnlyPubKeyEC2ERK15SigningProviderR13SignatureDataRK20BaseSignatureCreatorRK7CScriptN10miniscript17MiniscriptContextE
Unexecuted instantiation: _ZN9SatisfierI7CPubKeyEC2ERK15SigningProviderR13SignatureDataRK20BaseSignatureCreatorRK7CScriptN10miniscript17MiniscriptContextE
213
214
0
    static bool KeyCompare(const Key& a, const Key& b) {
215
0
        return a < b;
216
0
    }
Unexecuted instantiation: _ZN9SatisfierI11XOnlyPubKeyE10KeyCompareERKS0_S3_
Unexecuted instantiation: _ZN9SatisfierI7CPubKeyE10KeyCompareERKS0_S3_
217
218
    //! Get a CPubKey from a key hash. Note the key hash may be of an xonly pubkey.
219
    template<typename I>
220
0
    std::optional<CPubKey> CPubFromPKHBytes(I first, I last) const {
221
0
        assert(last - first == 20);
222
0
        CPubKey pubkey;
223
0
        CKeyID key_id;
224
0
        std::copy(first, last, key_id.begin());
225
0
        if (GetPubKey(m_provider, m_sig_data, key_id, pubkey)) return pubkey;
226
0
        m_sig_data.missing_pubkeys.push_back(key_id);
227
0
        return {};
228
0
    }
Unexecuted instantiation: _ZNK9SatisfierI11XOnlyPubKeyE16CPubFromPKHBytesINSt3__111__wrap_iterIPhEEEENS3_8optionalI7CPubKeyEET_SA_
Unexecuted instantiation: _ZNK9SatisfierI7CPubKeyE16CPubFromPKHBytesINSt3__111__wrap_iterIPhEEEENS3_8optionalIS0_EET_S9_
229
230
    //! Conversion to raw public key.
231
0
    std::vector<unsigned char> ToPKBytes(const Key& key) const { return {key.begin(), key.end()}; }
Unexecuted instantiation: _ZNK9SatisfierI11XOnlyPubKeyE9ToPKBytesERKS0_
Unexecuted instantiation: _ZNK9SatisfierI7CPubKeyE9ToPKBytesERKS0_
232
233
    //! Time lock satisfactions.
234
0
    bool CheckAfter(uint32_t value) const { return m_creator.Checker().CheckLockTime(CScriptNum(value)); }
Unexecuted instantiation: _ZNK9SatisfierI11XOnlyPubKeyE10CheckAfterEj
Unexecuted instantiation: _ZNK9SatisfierI7CPubKeyE10CheckAfterEj
235
0
    bool CheckOlder(uint32_t value) const { return m_creator.Checker().CheckSequence(CScriptNum(value)); }
Unexecuted instantiation: _ZNK9SatisfierI11XOnlyPubKeyE10CheckOlderEj
Unexecuted instantiation: _ZNK9SatisfierI7CPubKeyE10CheckOlderEj
236
237
    //! Hash preimage satisfactions.
238
0
    miniscript::Availability SatSHA256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
239
0
        return MsLookupHelper(m_sig_data.sha256_preimages, hash, preimage);
240
0
    }
Unexecuted instantiation: _ZNK9SatisfierI11XOnlyPubKeyE9SatSHA256ERKNSt3__16vectorIhNS2_9allocatorIhEEEERS6_
Unexecuted instantiation: _ZNK9SatisfierI7CPubKeyE9SatSHA256ERKNSt3__16vectorIhNS2_9allocatorIhEEEERS6_
241
0
    miniscript::Availability SatRIPEMD160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
242
0
        return MsLookupHelper(m_sig_data.ripemd160_preimages, hash, preimage);
243
0
    }
Unexecuted instantiation: _ZNK9SatisfierI11XOnlyPubKeyE12SatRIPEMD160ERKNSt3__16vectorIhNS2_9allocatorIhEEEERS6_
Unexecuted instantiation: _ZNK9SatisfierI7CPubKeyE12SatRIPEMD160ERKNSt3__16vectorIhNS2_9allocatorIhEEEERS6_
244
0
    miniscript::Availability SatHASH256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
245
0
        return MsLookupHelper(m_sig_data.hash256_preimages, hash, preimage);
246
0
    }
Unexecuted instantiation: _ZNK9SatisfierI11XOnlyPubKeyE10SatHASH256ERKNSt3__16vectorIhNS2_9allocatorIhEEEERS6_
Unexecuted instantiation: _ZNK9SatisfierI7CPubKeyE10SatHASH256ERKNSt3__16vectorIhNS2_9allocatorIhEEEERS6_
247
0
    miniscript::Availability SatHASH160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
248
0
        return MsLookupHelper(m_sig_data.hash160_preimages, hash, preimage);
249
0
    }
Unexecuted instantiation: _ZNK9SatisfierI11XOnlyPubKeyE10SatHASH160ERKNSt3__16vectorIhNS2_9allocatorIhEEEERS6_
Unexecuted instantiation: _ZNK9SatisfierI7CPubKeyE10SatHASH160ERKNSt3__16vectorIhNS2_9allocatorIhEEEERS6_
250
251
0
    miniscript::MiniscriptContext MsContext() const {
252
0
        return m_script_ctx;
253
0
    }
Unexecuted instantiation: _ZNK9SatisfierI11XOnlyPubKeyE9MsContextEv
Unexecuted instantiation: _ZNK9SatisfierI7CPubKeyE9MsContextEv
254
};
255
256
/** Miniscript satisfier specific to P2WSH context. */
257
struct WshSatisfier: Satisfier<CPubKey> {
258
    explicit WshSatisfier(const SigningProvider& provider LIFETIMEBOUND, SignatureData& sig_data LIFETIMEBOUND,
259
                          const BaseSignatureCreator& creator LIFETIMEBOUND, const CScript& witscript LIFETIMEBOUND)
260
0
                          : Satisfier(provider, sig_data, creator, witscript, miniscript::MiniscriptContext::P2WSH) {}
261
262
    //! Conversion from a raw compressed public key.
263
    template <typename I>
264
0
    std::optional<CPubKey> FromPKBytes(I first, I last) const {
265
0
        CPubKey pubkey{first, last};
266
0
        if (pubkey.IsValid()) return pubkey;
267
0
        return {};
268
0
    }
269
270
    //! Conversion from a raw compressed public key hash.
271
    template<typename I>
272
0
    std::optional<CPubKey> FromPKHBytes(I first, I last) const {
273
0
        return Satisfier::CPubFromPKHBytes(first, last);
274
0
    }
275
276
    //! Satisfy an ECDSA signature check.
277
0
    miniscript::Availability Sign(const CPubKey& key, std::vector<unsigned char>& sig) const {
278
0
        if (CreateSig(m_creator, m_sig_data, m_provider, sig, key, m_witness_script, SigVersion::WITNESS_V0)) {
279
0
            return miniscript::Availability::YES;
280
0
        }
281
0
        return miniscript::Availability::NO;
282
0
    }
283
};
284
285
/** Miniscript satisfier specific to Tapscript context. */
286
struct TapSatisfier: Satisfier<XOnlyPubKey> {
287
    const uint256& m_leaf_hash;
288
289
    explicit TapSatisfier(const SigningProvider& provider LIFETIMEBOUND, SignatureData& sig_data LIFETIMEBOUND,
290
                          const BaseSignatureCreator& creator LIFETIMEBOUND, const CScript& script LIFETIMEBOUND,
291
                          const uint256& leaf_hash LIFETIMEBOUND)
292
0
                          : Satisfier(provider, sig_data, creator, script, miniscript::MiniscriptContext::TAPSCRIPT),
293
0
                            m_leaf_hash(leaf_hash) {}
294
295
    //! Conversion from a raw xonly public key.
296
    template <typename I>
297
0
    std::optional<XOnlyPubKey> FromPKBytes(I first, I last) const {
298
0
        if (last - first != 32) return {};
299
0
        XOnlyPubKey pubkey;
300
0
        std::copy(first, last, pubkey.begin());
301
0
        return pubkey;
302
0
    }
303
304
    //! Conversion from a raw xonly public key hash.
305
    template<typename I>
306
0
    std::optional<XOnlyPubKey> FromPKHBytes(I first, I last) const {
307
0
        if (auto pubkey = Satisfier::CPubFromPKHBytes(first, last)) return XOnlyPubKey{*pubkey};
308
0
        return {};
309
0
    }
310
311
    //! Satisfy a BIP340 signature check.
312
0
    miniscript::Availability Sign(const XOnlyPubKey& key, std::vector<unsigned char>& sig) const {
313
0
        if (CreateTaprootScriptSig(m_creator, m_sig_data, m_provider, sig, key, m_leaf_hash, SigVersion::TAPSCRIPT)) {
314
0
            return miniscript::Availability::YES;
315
0
        }
316
0
        return miniscript::Availability::NO;
317
0
    }
318
};
319
320
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)
321
0
{
322
    // Only BIP342 tapscript signing is supported for now.
323
0
    if (leaf_version != TAPROOT_LEAF_TAPSCRIPT) return false;
324
325
0
    uint256 leaf_hash = ComputeTapleafHash(leaf_version, script_bytes);
326
0
    CScript script = CScript(script_bytes.begin(), script_bytes.end());
327
328
0
    TapSatisfier ms_satisfier{provider, sigdata, creator, script, leaf_hash};
329
0
    const auto ms = miniscript::FromScript(script, ms_satisfier);
330
0
    return ms && ms->Satisfy(ms_satisfier, result) == miniscript::Availability::YES;
331
0
}
332
333
static bool SignTaproot(const SigningProvider& provider, const BaseSignatureCreator& creator, const WitnessV1Taproot& output, SignatureData& sigdata, std::vector<valtype>& result)
334
0
{
335
0
    TaprootSpendData spenddata;
336
0
    TaprootBuilder builder;
337
338
    // Gather information about this output.
339
0
    if (provider.GetTaprootSpendData(output, spenddata)) {
340
0
        sigdata.tr_spenddata.Merge(spenddata);
341
0
    }
342
0
    if (provider.GetTaprootBuilder(output, builder)) {
343
0
        sigdata.tr_builder = builder;
344
0
    }
345
346
    // Try key path spending.
347
0
    {
348
0
        KeyOriginInfo info;
349
0
        if (provider.GetKeyOriginByXOnly(sigdata.tr_spenddata.internal_key, info)) {
350
0
            auto it = sigdata.taproot_misc_pubkeys.find(sigdata.tr_spenddata.internal_key);
351
0
            if (it == sigdata.taproot_misc_pubkeys.end()) {
352
0
                sigdata.taproot_misc_pubkeys.emplace(sigdata.tr_spenddata.internal_key, std::make_pair(std::set<uint256>(), info));
353
0
            }
354
0
        }
355
356
0
        std::vector<unsigned char> sig;
357
0
        if (sigdata.taproot_key_path_sig.size() == 0) {
358
0
            if (creator.CreateSchnorrSig(provider, sig, sigdata.tr_spenddata.internal_key, nullptr, &sigdata.tr_spenddata.merkle_root, SigVersion::TAPROOT)) {
359
0
                sigdata.taproot_key_path_sig = sig;
360
0
            }
361
0
        }
362
0
        if (sigdata.taproot_key_path_sig.size() == 0) {
363
0
            if (creator.CreateSchnorrSig(provider, sig, output, nullptr, nullptr, SigVersion::TAPROOT)) {
364
0
                sigdata.taproot_key_path_sig = sig;
365
0
            }
366
0
        }
367
0
        if (sigdata.taproot_key_path_sig.size()) {
368
0
            result = Vector(sigdata.taproot_key_path_sig);
369
0
            return true;
370
0
        }
371
0
    }
372
373
    // Try script path spending.
374
0
    std::vector<std::vector<unsigned char>> smallest_result_stack;
375
0
    for (const auto& [key, control_blocks] : sigdata.tr_spenddata.scripts) {
376
0
        const auto& [script, leaf_ver] = key;
377
0
        std::vector<std::vector<unsigned char>> result_stack;
378
0
        if (SignTaprootScript(provider, creator, sigdata, leaf_ver, script, result_stack)) {
379
0
            result_stack.emplace_back(std::begin(script), std::end(script)); // Push the script
380
0
            result_stack.push_back(*control_blocks.begin()); // Push the smallest control block
381
0
            if (smallest_result_stack.size() == 0 ||
382
0
                GetSerializeSize(result_stack) < GetSerializeSize(smallest_result_stack)) {
383
0
                smallest_result_stack = std::move(result_stack);
384
0
            }
385
0
        }
386
0
    }
387
0
    if (smallest_result_stack.size() != 0) {
388
0
        result = std::move(smallest_result_stack);
389
0
        return true;
390
0
    }
391
392
0
    return false;
393
0
}
394
395
/**
396
 * Sign scriptPubKey using signature made with creator.
397
 * Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
398
 * unless whichTypeRet is TxoutType::SCRIPTHASH, in which case scriptSigRet is the redemption script.
399
 * Returns false if scriptPubKey could not be completely satisfied.
400
 */
401
static bool SignStep(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& scriptPubKey,
402
                     std::vector<valtype>& ret, TxoutType& whichTypeRet, SigVersion sigversion, SignatureData& sigdata)
403
0
{
404
0
    CScript scriptRet;
405
0
    ret.clear();
406
0
    std::vector<unsigned char> sig;
407
408
0
    std::vector<valtype> vSolutions;
409
0
    whichTypeRet = Solver(scriptPubKey, vSolutions);
410
411
0
    switch (whichTypeRet) {
412
0
    case TxoutType::NONSTANDARD:
413
0
    case TxoutType::NULL_DATA:
414
0
    case TxoutType::WITNESS_UNKNOWN:
415
0
        return false;
416
0
    case TxoutType::PUBKEY:
417
0
        if (!CreateSig(creator, sigdata, provider, sig, CPubKey(vSolutions[0]), scriptPubKey, sigversion)) return false;
418
0
        ret.push_back(std::move(sig));
419
0
        return true;
420
0
    case TxoutType::PUBKEYHASH: {
421
0
        CKeyID keyID = CKeyID(uint160(vSolutions[0]));
422
0
        CPubKey pubkey;
423
0
        if (!GetPubKey(provider, sigdata, keyID, pubkey)) {
424
            // Pubkey could not be found, add to missing
425
0
            sigdata.missing_pubkeys.push_back(keyID);
426
0
            return false;
427
0
        }
428
0
        if (!CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion)) return false;
429
0
        ret.push_back(std::move(sig));
430
0
        ret.push_back(ToByteVector(pubkey));
431
0
        return true;
432
0
    }
433
0
    case TxoutType::SCRIPTHASH: {
434
0
        uint160 h160{vSolutions[0]};
435
0
        if (GetCScript(provider, sigdata, CScriptID{h160}, scriptRet)) {
436
0
            ret.emplace_back(scriptRet.begin(), scriptRet.end());
437
0
            return true;
438
0
        }
439
        // Could not find redeemScript, add to missing
440
0
        sigdata.missing_redeem_script = h160;
441
0
        return false;
442
0
    }
443
0
    case TxoutType::MULTISIG: {
444
0
        size_t required = vSolutions.front()[0];
445
0
        ret.emplace_back(); // workaround CHECKMULTISIG bug
446
0
        for (size_t i = 1; i < vSolutions.size() - 1; ++i) {
447
0
            CPubKey pubkey = CPubKey(vSolutions[i]);
448
            // We need to always call CreateSig in order to fill sigdata with all
449
            // possible signatures that we can create. This will allow further PSBT
450
            // processing to work as it needs all possible signature and pubkey pairs
451
0
            if (CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion)) {
452
0
                if (ret.size() < required + 1) {
453
0
                    ret.push_back(std::move(sig));
454
0
                }
455
0
            }
456
0
        }
457
0
        bool ok = ret.size() == required + 1;
458
0
        for (size_t i = 0; i + ret.size() < required + 1; ++i) {
459
0
            ret.emplace_back();
460
0
        }
461
0
        return ok;
462
0
    }
463
0
    case TxoutType::WITNESS_V0_KEYHASH:
464
0
        ret.push_back(vSolutions[0]);
465
0
        return true;
466
467
0
    case TxoutType::WITNESS_V0_SCRIPTHASH:
468
0
        if (GetCScript(provider, sigdata, CScriptID{RIPEMD160(vSolutions[0])}, scriptRet)) {
469
0
            ret.emplace_back(scriptRet.begin(), scriptRet.end());
470
0
            return true;
471
0
        }
472
        // Could not find witnessScript, add to missing
473
0
        sigdata.missing_witness_script = uint256(vSolutions[0]);
474
0
        return false;
475
476
0
    case TxoutType::WITNESS_V1_TAPROOT:
477
0
        return SignTaproot(provider, creator, WitnessV1Taproot(XOnlyPubKey{vSolutions[0]}), sigdata, ret);
478
479
0
    case TxoutType::ANCHOR:
480
0
        return true;
481
0
    } // no default case, so the compiler can warn about missing cases
482
0
    assert(false);
483
0
}
484
485
static CScript PushAll(const std::vector<valtype>& values)
486
0
{
487
0
    CScript result;
488
0
    for (const valtype& v : values) {
489
0
        if (v.size() == 0) {
490
0
            result << OP_0;
491
0
        } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
492
0
            result << CScript::EncodeOP_N(v[0]);
493
0
        } else if (v.size() == 1 && v[0] == 0x81) {
494
0
            result << OP_1NEGATE;
495
0
        } else {
496
0
            result << v;
497
0
        }
498
0
    }
499
0
    return result;
500
0
}
501
502
bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& fromPubKey, SignatureData& sigdata)
503
0
{
504
0
    if (sigdata.complete) return true;
505
506
0
    std::vector<valtype> result;
507
0
    TxoutType whichType;
508
0
    bool solved = SignStep(provider, creator, fromPubKey, result, whichType, SigVersion::BASE, sigdata);
509
0
    bool P2SH = false;
510
0
    CScript subscript;
511
512
0
    if (solved && whichType == TxoutType::SCRIPTHASH)
513
0
    {
514
        // Solver returns the subscript that needs to be evaluated;
515
        // the final scriptSig is the signatures from that
516
        // and then the serialized subscript:
517
0
        subscript = CScript(result[0].begin(), result[0].end());
518
0
        sigdata.redeem_script = subscript;
519
0
        solved = solved && SignStep(provider, creator, subscript, result, whichType, SigVersion::BASE, sigdata) && whichType != TxoutType::SCRIPTHASH;
520
0
        P2SH = true;
521
0
    }
522
523
0
    if (solved && whichType == TxoutType::WITNESS_V0_KEYHASH)
524
0
    {
525
0
        CScript witnessscript;
526
0
        witnessscript << OP_DUP << OP_HASH160 << ToByteVector(result[0]) << OP_EQUALVERIFY << OP_CHECKSIG;
527
0
        TxoutType subType;
528
0
        solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0, sigdata);
529
0
        sigdata.scriptWitness.stack = result;
530
0
        sigdata.witness = true;
531
0
        result.clear();
532
0
    }
533
0
    else if (solved && whichType == TxoutType::WITNESS_V0_SCRIPTHASH)
534
0
    {
535
0
        CScript witnessscript(result[0].begin(), result[0].end());
536
0
        sigdata.witness_script = witnessscript;
537
538
0
        TxoutType subType{TxoutType::NONSTANDARD};
539
0
        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;
540
541
        // If we couldn't find a solution with the legacy satisfier, try satisfying the script using Miniscript.
542
        // Note we need to check if the result stack is empty before, because it might be used even if the Script
543
        // isn't fully solved. For instance the CHECKMULTISIG satisfaction in SignStep() pushes partial signatures
544
        // and the extractor relies on this behaviour to combine witnesses.
545
0
        if (!solved && result.empty()) {
546
0
            WshSatisfier ms_satisfier{provider, sigdata, creator, witnessscript};
547
0
            const auto ms = miniscript::FromScript(witnessscript, ms_satisfier);
548
0
            solved = ms && ms->Satisfy(ms_satisfier, result) == miniscript::Availability::YES;
549
0
        }
550
0
        result.emplace_back(witnessscript.begin(), witnessscript.end());
551
552
0
        sigdata.scriptWitness.stack = result;
553
0
        sigdata.witness = true;
554
0
        result.clear();
555
0
    } else if (whichType == TxoutType::WITNESS_V1_TAPROOT && !P2SH) {
556
0
        sigdata.witness = true;
557
0
        if (solved) {
558
0
            sigdata.scriptWitness.stack = std::move(result);
559
0
        }
560
0
        result.clear();
561
0
    } else if (solved && whichType == TxoutType::WITNESS_UNKNOWN) {
562
0
        sigdata.witness = true;
563
0
    }
564
565
0
    if (!sigdata.witness) sigdata.scriptWitness.stack.clear();
566
0
    if (P2SH) {
567
0
        result.emplace_back(subscript.begin(), subscript.end());
568
0
    }
569
0
    sigdata.scriptSig = PushAll(result);
570
571
    // Test solution
572
0
    sigdata.complete = solved && VerifyScript(sigdata.scriptSig, fromPubKey, &sigdata.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker());
573
0
    return sigdata.complete;
574
0
}
575
576
namespace {
577
class SignatureExtractorChecker final : public DeferringSignatureChecker
578
{
579
private:
580
    SignatureData& sigdata;
581
582
public:
583
0
    SignatureExtractorChecker(SignatureData& sigdata, BaseSignatureChecker& checker) : DeferringSignatureChecker(checker), sigdata(sigdata) {}
584
585
    bool CheckECDSASignature(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override
586
0
    {
587
0
        if (m_checker.CheckECDSASignature(scriptSig, vchPubKey, scriptCode, sigversion)) {
588
0
            CPubKey pubkey(vchPubKey);
589
0
            sigdata.signatures.emplace(pubkey.GetID(), SigPair(pubkey, scriptSig));
590
0
            return true;
591
0
        }
592
0
        return false;
593
0
    }
594
};
595
596
struct Stacks
597
{
598
    std::vector<valtype> script;
599
    std::vector<valtype> witness;
600
601
    Stacks() = delete;
602
    Stacks(const Stacks&) = delete;
603
0
    explicit Stacks(const SignatureData& data) : witness(data.scriptWitness.stack) {
604
0
        EvalScript(script, data.scriptSig, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SigVersion::BASE);
605
0
    }
606
};
607
}
608
609
// Extracts signatures and scripts from incomplete scriptSigs. Please do not extend this, use PSBT instead
610
SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn, const CTxOut& txout)
611
0
{
612
0
    SignatureData data;
613
0
    assert(tx.vin.size() > nIn);
614
0
    data.scriptSig = tx.vin[nIn].scriptSig;
615
0
    data.scriptWitness = tx.vin[nIn].scriptWitness;
616
0
    Stacks stack(data);
617
618
    // Get signatures
619
0
    MutableTransactionSignatureChecker tx_checker(&tx, nIn, txout.nValue, MissingDataBehavior::FAIL);
620
0
    SignatureExtractorChecker extractor_checker(data, tx_checker);
621
0
    if (VerifyScript(data.scriptSig, txout.scriptPubKey, &data.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, extractor_checker)) {
622
0
        data.complete = true;
623
0
        return data;
624
0
    }
625
626
    // Get scripts
627
0
    std::vector<std::vector<unsigned char>> solutions;
628
0
    TxoutType script_type = Solver(txout.scriptPubKey, solutions);
629
0
    SigVersion sigversion = SigVersion::BASE;
630
0
    CScript next_script = txout.scriptPubKey;
631
632
0
    if (script_type == TxoutType::SCRIPTHASH && !stack.script.empty() && !stack.script.back().empty()) {
633
        // Get the redeemScript
634
0
        CScript redeem_script(stack.script.back().begin(), stack.script.back().end());
635
0
        data.redeem_script = redeem_script;
636
0
        next_script = std::move(redeem_script);
637
638
        // Get redeemScript type
639
0
        script_type = Solver(next_script, solutions);
640
0
        stack.script.pop_back();
641
0
    }
642
0
    if (script_type == TxoutType::WITNESS_V0_SCRIPTHASH && !stack.witness.empty() && !stack.witness.back().empty()) {
643
        // Get the witnessScript
644
0
        CScript witness_script(stack.witness.back().begin(), stack.witness.back().end());
645
0
        data.witness_script = witness_script;
646
0
        next_script = std::move(witness_script);
647
648
        // Get witnessScript type
649
0
        script_type = Solver(next_script, solutions);
650
0
        stack.witness.pop_back();
651
0
        stack.script = std::move(stack.witness);
652
0
        stack.witness.clear();
653
0
        sigversion = SigVersion::WITNESS_V0;
654
0
    }
655
0
    if (script_type == TxoutType::MULTISIG && !stack.script.empty()) {
656
        // Build a map of pubkey -> signature by matching sigs to pubkeys:
657
0
        assert(solutions.size() > 1);
658
0
        unsigned int num_pubkeys = solutions.size()-2;
659
0
        unsigned int last_success_key = 0;
660
0
        for (const valtype& sig : stack.script) {
661
0
            for (unsigned int i = last_success_key; i < num_pubkeys; ++i) {
662
0
                const valtype& pubkey = solutions[i+1];
663
                // We either have a signature for this pubkey, or we have found a signature and it is valid
664
0
                if (data.signatures.count(CPubKey(pubkey).GetID()) || extractor_checker.CheckECDSASignature(sig, pubkey, next_script, sigversion)) {
665
0
                    last_success_key = i + 1;
666
0
                    break;
667
0
                }
668
0
            }
669
0
        }
670
0
    }
671
672
0
    return data;
673
0
}
674
675
void UpdateInput(CTxIn& input, const SignatureData& data)
676
0
{
677
0
    input.scriptSig = data.scriptSig;
678
0
    input.scriptWitness = data.scriptWitness;
679
0
}
680
681
void SignatureData::MergeSignatureData(SignatureData sigdata)
682
0
{
683
0
    if (complete) return;
684
0
    if (sigdata.complete) {
685
0
        *this = std::move(sigdata);
686
0
        return;
687
0
    }
688
0
    if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
689
0
        redeem_script = sigdata.redeem_script;
690
0
    }
691
0
    if (witness_script.empty() && !sigdata.witness_script.empty()) {
692
0
        witness_script = sigdata.witness_script;
693
0
    }
694
0
    signatures.insert(std::make_move_iterator(sigdata.signatures.begin()), std::make_move_iterator(sigdata.signatures.end()));
695
0
}
696
697
namespace {
698
/** Dummy signature checker which accepts all signatures. */
699
class DummySignatureChecker final : public BaseSignatureChecker
700
{
701
public:
702
0
    DummySignatureChecker() = default;
703
0
    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; }
704
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; }
705
0
    bool CheckLockTime(const CScriptNum& nLockTime) const override { return true; }
706
0
    bool CheckSequence(const CScriptNum& nSequence) const override { return true; }
707
};
708
}
709
710
const BaseSignatureChecker& DUMMY_CHECKER = DummySignatureChecker();
711
712
namespace {
713
class DummySignatureCreator final : public BaseSignatureCreator {
714
private:
715
    char m_r_len = 32;
716
    char m_s_len = 32;
717
public:
718
0
    DummySignatureCreator(char r_len, char s_len) : m_r_len(r_len), m_s_len(s_len) {}
719
0
    const BaseSignatureChecker& Checker() const override { return DUMMY_CHECKER; }
720
    bool CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const override
721
0
    {
722
        // Create a dummy signature that is a valid DER-encoding
723
0
        vchSig.assign(m_r_len + m_s_len + 7, '\000');
724
0
        vchSig[0] = 0x30;
725
0
        vchSig[1] = m_r_len + m_s_len + 4;
726
0
        vchSig[2] = 0x02;
727
0
        vchSig[3] = m_r_len;
728
0
        vchSig[4] = 0x01;
729
0
        vchSig[4 + m_r_len] = 0x02;
730
0
        vchSig[5 + m_r_len] = m_s_len;
731
0
        vchSig[6 + m_r_len] = 0x01;
732
0
        vchSig[6 + m_r_len + m_s_len] = SIGHASH_ALL;
733
0
        return true;
734
0
    }
735
    bool CreateSchnorrSig(const SigningProvider& provider, std::vector<unsigned char>& sig, const XOnlyPubKey& pubkey, const uint256* leaf_hash, const uint256* tweak, SigVersion sigversion) const override
736
0
    {
737
0
        sig.assign(64, '\000');
738
0
        return true;
739
0
    }
740
};
741
742
}
743
744
const BaseSignatureCreator& DUMMY_SIGNATURE_CREATOR = DummySignatureCreator(32, 32);
745
const BaseSignatureCreator& DUMMY_MAXIMUM_SIGNATURE_CREATOR = DummySignatureCreator(33, 32);
746
747
bool IsSegWitOutput(const SigningProvider& provider, const CScript& script)
748
0
{
749
0
    int version;
750
0
    valtype program;
751
0
    if (script.IsWitnessProgram(version, program)) return true;
752
0
    if (script.IsPayToScriptHash()) {
753
0
        std::vector<valtype> solutions;
754
0
        auto whichtype = Solver(script, solutions);
755
0
        if (whichtype == TxoutType::SCRIPTHASH) {
756
0
            auto h160 = uint160(solutions[0]);
757
0
            CScript subscript;
758
0
            if (provider.GetCScript(CScriptID{h160}, subscript)) {
759
0
                if (subscript.IsWitnessProgram(version, program)) return true;
760
0
            }
761
0
        }
762
0
    }
763
0
    return false;
764
0
}
765
766
bool SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore, const std::map<COutPoint, Coin>& coins, int nHashType, std::map<int, bilingual_str>& input_errors)
767
0
{
768
0
    bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
769
770
    // Use CTransaction for the constant parts of the
771
    // transaction to avoid rehashing.
772
0
    const CTransaction txConst(mtx);
773
774
0
    PrecomputedTransactionData txdata;
775
0
    std::vector<CTxOut> spent_outputs;
776
0
    for (unsigned int i = 0; i < mtx.vin.size(); ++i) {
777
0
        CTxIn& txin = mtx.vin[i];
778
0
        auto coin = coins.find(txin.prevout);
779
0
        if (coin == coins.end() || coin->second.IsSpent()) {
780
0
            txdata.Init(txConst, /*spent_outputs=*/{}, /*force=*/true);
781
0
            break;
782
0
        } else {
783
0
            spent_outputs.emplace_back(coin->second.out.nValue, coin->second.out.scriptPubKey);
784
0
        }
785
0
    }
786
0
    if (spent_outputs.size() == mtx.vin.size()) {
787
0
        txdata.Init(txConst, std::move(spent_outputs), true);
788
0
    }
789
790
    // Sign what we can:
791
0
    for (unsigned int i = 0; i < mtx.vin.size(); ++i) {
792
0
        CTxIn& txin = mtx.vin[i];
793
0
        auto coin = coins.find(txin.prevout);
794
0
        if (coin == coins.end() || coin->second.IsSpent()) {
795
0
            input_errors[i] = _("Input not found or already spent");
796
0
            continue;
797
0
        }
798
0
        const CScript& prevPubKey = coin->second.out.scriptPubKey;
799
0
        const CAmount& amount = coin->second.out.nValue;
800
801
0
        SignatureData sigdata = DataFromTransaction(mtx, i, coin->second.out);
802
        // Only sign SIGHASH_SINGLE if there's a corresponding output:
803
0
        if (!fHashSingle || (i < mtx.vout.size())) {
804
0
            ProduceSignature(*keystore, MutableTransactionSignatureCreator(mtx, i, amount, &txdata, nHashType), prevPubKey, sigdata);
805
0
        }
806
807
0
        UpdateInput(txin, sigdata);
808
809
        // amount must be specified for valid segwit signature
810
0
        if (amount == MAX_MONEY && !txin.scriptWitness.IsNull()) {
811
0
            input_errors[i] = _("Missing amount");
812
0
            continue;
813
0
        }
814
815
0
        ScriptError serror = SCRIPT_ERR_OK;
816
0
        if (!sigdata.complete && !VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount, txdata, MissingDataBehavior::FAIL), &serror)) {
817
0
            if (serror == SCRIPT_ERR_INVALID_STACK_OPERATION) {
818
                // Unable to sign input and verification failed (possible attempt to partially sign).
819
0
                input_errors[i] = Untranslated("Unable to sign input, invalid stack size (possibly missing key)");
820
0
            } else if (serror == SCRIPT_ERR_SIG_NULLFAIL) {
821
                // Verification failed (possibly due to insufficient signatures).
822
0
                input_errors[i] = Untranslated("CHECK(MULTI)SIG failing with non-zero signature (possibly need more signatures)");
823
0
            } else {
824
0
                input_errors[i] = Untranslated(ScriptErrorString(serror));
825
0
            }
826
0
        } else {
827
            // If this input succeeds, make sure there is no error set for it
828
0
            input_errors.erase(i);
829
0
        }
830
0
    }
831
0
    return input_errors.empty();
832
0
}