Coverage Report

Created: 2026-07-14 18:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/bitcoin/src/wallet/scriptpubkeyman.cpp
Line
Count
Source
1
// Copyright (c) 2019-present The Bitcoin Core developers
2
// Distributed under the MIT software license, see the accompanying
3
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5
#include <wallet/scriptpubkeyman.h>
6
7
#include <coins.h>
8
#include <hash.h>
9
#include <key_io.h>
10
#include <node/types.h>
11
#include <outputtype.h>
12
#include <script/descriptor.h>
13
#include <script/script.h>
14
#include <script/sign.h>
15
#include <script/solver.h>
16
#include <util/bip32.h>
17
#include <util/check.h>
18
#include <util/log.h>
19
#include <util/strencodings.h>
20
#include <util/string.h>
21
#include <util/time.h>
22
#include <util/translation.h>
23
24
#include <optional>
25
26
using common::PSBTError;
27
using util::ToString;
28
29
namespace wallet {
30
31
typedef std::vector<unsigned char> valtype;
32
33
// Legacy wallet IsMine(). Used only in migration
34
// DO NOT USE ANYTHING IN THIS NAMESPACE OUTSIDE OF MIGRATION
35
namespace {
36
37
/**
38
 * This is an enum that tracks the execution context of a script, similar to
39
 * SigVersion in script/interpreter. It is separate however because we want to
40
 * distinguish between top-level scriptPubKey execution and P2SH redeemScript
41
 * execution (a distinction that has no impact on consensus rules).
42
 */
43
enum class IsMineSigVersion
44
{
45
    TOP = 0,        //!< scriptPubKey execution
46
    P2SH = 1,       //!< P2SH redeemScript
47
    WITNESS_V0 = 2, //!< P2WSH witness script execution
48
};
49
50
/**
51
 * This is an internal representation of isminetype + invalidity.
52
 * Its order is significant, as we return the max of all explored
53
 * possibilities.
54
 */
55
enum class IsMineResult
56
{
57
    NO = 0,         //!< Not ours
58
    WATCH_ONLY = 1, //!< Included in watch-only balance
59
    SPENDABLE = 2,  //!< Included in all balances
60
    INVALID = 3,    //!< Not spendable by anyone (uncompressed pubkey in segwit, P2SH inside P2SH or witness, witness inside witness)
61
};
62
63
bool PermitsUncompressed(IsMineSigVersion sigversion)
64
0
{
65
0
    return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
  Branch (65:12): [True: 0, False: 0]
  Branch (65:51): [True: 0, False: 0]
66
0
}
67
68
bool HaveKeys(const std::vector<valtype>& pubkeys, const LegacyDataSPKM& keystore)
69
0
{
70
0
    for (const valtype& pubkey : pubkeys) {
  Branch (70:32): [True: 0, False: 0]
71
0
        CKeyID keyID = CPubKey(pubkey).GetID();
72
0
        if (!keystore.HaveKey(keyID)) return false;
  Branch (72:13): [True: 0, False: 0]
73
0
    }
74
0
    return true;
75
0
}
76
77
//! Recursively solve script and return spendable/watchonly/invalid status.
78
//!
79
//! @param keystore            legacy key and script store
80
//! @param scriptPubKey        script to solve
81
//! @param sigversion          script type (top-level / redeemscript / witnessscript)
82
//! @param recurse_scripthash  whether to recurse into nested p2sh and p2wsh
83
//!                            scripts or simply treat any script that has been
84
//!                            stored in the keystore as spendable
85
// NOLINTNEXTLINE(misc-no-recursion)
86
IsMineResult LegacyWalletIsMineInnerDONOTUSE(const LegacyDataSPKM& keystore, const CScript& scriptPubKey, IsMineSigVersion sigversion, bool recurse_scripthash=true)
87
0
{
88
0
    IsMineResult ret = IsMineResult::NO;
89
90
0
    std::vector<valtype> vSolutions;
91
0
    TxoutType whichType = Solver(scriptPubKey, vSolutions);
92
93
0
    CKeyID keyID;
94
0
    switch (whichType) {
  Branch (94:13): [True: 0, False: 0]
95
0
    case TxoutType::NONSTANDARD:
  Branch (95:5): [True: 0, False: 0]
96
0
    case TxoutType::NULL_DATA:
  Branch (96:5): [True: 0, False: 0]
97
0
    case TxoutType::WITNESS_UNKNOWN:
  Branch (97:5): [True: 0, False: 0]
98
0
    case TxoutType::WITNESS_V1_TAPROOT:
  Branch (98:5): [True: 0, False: 0]
99
0
    case TxoutType::ANCHOR:
  Branch (99:5): [True: 0, False: 0]
100
0
        break;
101
0
    case TxoutType::PUBKEY:
  Branch (101:5): [True: 0, False: 0]
102
0
        keyID = CPubKey(vSolutions[0]).GetID();
103
0
        if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
  Branch (103:13): [True: 0, False: 0]
  Branch (103:49): [True: 0, False: 0]
104
0
            return IsMineResult::INVALID;
105
0
        }
106
0
        if (keystore.HaveKey(keyID)) {
  Branch (106:13): [True: 0, False: 0]
107
0
            ret = std::max(ret, IsMineResult::SPENDABLE);
108
0
        }
109
0
        break;
110
0
    case TxoutType::WITNESS_V0_KEYHASH:
  Branch (110:5): [True: 0, False: 0]
111
0
    {
112
0
        if (sigversion == IsMineSigVersion::WITNESS_V0) {
  Branch (112:13): [True: 0, False: 0]
113
            // P2WPKH inside P2WSH is invalid.
114
0
            return IsMineResult::INVALID;
115
0
        }
116
0
        if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
  Branch (116:13): [True: 0, False: 0]
  Branch (116:13): [True: 0, False: 0]
  Branch (116:52): [True: 0, False: 0]
117
            // We do not support bare witness outputs unless the P2SH version of it would be
118
            // acceptable as well. This protects against matching before segwit activates.
119
            // This also applies to the P2WSH case.
120
0
            break;
121
0
        }
122
0
        ret = std::max(ret, LegacyWalletIsMineInnerDONOTUSE(keystore, GetScriptForDestination(PKHash(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
123
0
        break;
124
0
    }
125
0
    case TxoutType::PUBKEYHASH:
  Branch (125:5): [True: 0, False: 0]
126
0
        keyID = CKeyID(uint160(vSolutions[0]));
127
0
        if (!PermitsUncompressed(sigversion)) {
  Branch (127:13): [True: 0, False: 0]
128
0
            CPubKey pubkey;
129
0
            if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
  Branch (129:17): [True: 0, False: 0]
  Branch (129:54): [True: 0, False: 0]
130
0
                return IsMineResult::INVALID;
131
0
            }
132
0
        }
133
0
        if (keystore.HaveKey(keyID)) {
  Branch (133:13): [True: 0, False: 0]
134
0
            ret = std::max(ret, IsMineResult::SPENDABLE);
135
0
        }
136
0
        break;
137
0
    case TxoutType::SCRIPTHASH:
  Branch (137:5): [True: 0, False: 0]
138
0
    {
139
0
        if (sigversion != IsMineSigVersion::TOP) {
  Branch (139:13): [True: 0, False: 0]
140
            // P2SH inside P2WSH or P2SH is invalid.
141
0
            return IsMineResult::INVALID;
142
0
        }
143
0
        CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
144
0
        CScript subscript;
145
0
        if (keystore.GetCScript(scriptID, subscript)) {
  Branch (145:13): [True: 0, False: 0]
146
0
            ret = std::max(ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
  Branch (146:33): [True: 0, False: 0]
147
0
        }
148
0
        break;
149
0
    }
150
0
    case TxoutType::WITNESS_V0_SCRIPTHASH:
  Branch (150:5): [True: 0, False: 0]
151
0
    {
152
0
        if (sigversion == IsMineSigVersion::WITNESS_V0) {
  Branch (152:13): [True: 0, False: 0]
153
            // P2WSH inside P2WSH is invalid.
154
0
            return IsMineResult::INVALID;
155
0
        }
156
0
        if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
  Branch (156:13): [True: 0, False: 0]
  Branch (156:13): [True: 0, False: 0]
  Branch (156:52): [True: 0, False: 0]
157
0
            break;
158
0
        }
159
0
        CScriptID scriptID{RIPEMD160(vSolutions[0])};
160
0
        CScript subscript;
161
0
        if (keystore.GetCScript(scriptID, subscript)) {
  Branch (161:13): [True: 0, False: 0]
162
0
            ret = std::max(ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::WITNESS_V0) : IsMineResult::SPENDABLE);
  Branch (162:33): [True: 0, False: 0]
163
0
        }
164
0
        break;
165
0
    }
166
167
0
    case TxoutType::MULTISIG:
  Branch (167:5): [True: 0, False: 0]
168
0
    {
169
        // Never treat bare multisig outputs as ours (they can still be made watchonly-though)
170
0
        if (sigversion == IsMineSigVersion::TOP) {
  Branch (170:13): [True: 0, False: 0]
171
0
            break;
172
0
        }
173
174
        // Only consider transactions "mine" if we own ALL the
175
        // keys involved. Multi-signature transactions that are
176
        // partially owned (somebody else has a key that can spend
177
        // them) enable spend-out-from-under-you attacks, especially
178
        // in shared-wallet situations.
179
0
        std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
180
0
        if (!PermitsUncompressed(sigversion)) {
  Branch (180:13): [True: 0, False: 0]
181
0
            for (size_t i = 0; i < keys.size(); i++) {
  Branch (181:32): [True: 0, False: 0]
182
0
                if (keys[i].size() != 33) {
  Branch (182:21): [True: 0, False: 0]
183
0
                    return IsMineResult::INVALID;
184
0
                }
185
0
            }
186
0
        }
187
0
        if (HaveKeys(keys, keystore)) {
  Branch (187:13): [True: 0, False: 0]
188
0
            ret = std::max(ret, IsMineResult::SPENDABLE);
189
0
        }
190
0
        break;
191
0
    }
192
0
    } // no default case, so the compiler can warn about missing cases
193
194
0
    if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
  Branch (194:9): [True: 0, False: 0]
  Branch (194:36): [True: 0, False: 0]
195
0
        ret = std::max(ret, IsMineResult::WATCH_ONLY);
196
0
    }
197
0
    return ret;
198
0
}
199
200
} // namespace
201
202
bool LegacyDataSPKM::IsMine(const CScript& script) const
203
0
{
204
0
    switch (LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP)) {
  Branch (204:13): [True: 0, False: 0]
205
0
    case IsMineResult::INVALID:
  Branch (205:5): [True: 0, False: 0]
206
0
    case IsMineResult::NO:
  Branch (206:5): [True: 0, False: 0]
207
0
        return false;
208
0
    case IsMineResult::WATCH_ONLY:
  Branch (208:5): [True: 0, False: 0]
209
0
    case IsMineResult::SPENDABLE:
  Branch (209:5): [True: 0, False: 0]
210
0
        return true;
211
0
    }
212
0
    assert(false);
  Branch (212:5): [Folded - Ignored]
213
0
}
214
215
bool LegacyDataSPKM::CheckDecryptionKey(const CKeyingMaterial& master_key)
216
0
{
217
0
    {
218
0
        LOCK(cs_KeyStore);
219
0
        assert(mapKeys.empty());
  Branch (219:9): [True: 0, False: 0]
220
221
0
        bool keyPass = mapCryptedKeys.empty(); // Always pass when there are no encrypted keys
222
0
        bool keyFail = false;
223
0
        CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
224
0
        WalletBatch batch(m_storage.GetDatabase());
225
0
        for (; mi != mapCryptedKeys.end(); ++mi)
  Branch (225:16): [True: 0, False: 0]
226
0
        {
227
0
            const CPubKey &vchPubKey = (*mi).second.first;
228
0
            const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
229
0
            CKey key;
230
0
            if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
  Branch (230:17): [True: 0, False: 0]
231
0
            {
232
0
                keyFail = true;
233
0
                break;
234
0
            }
235
0
            keyPass = true;
236
0
            if (fDecryptionThoroughlyChecked)
  Branch (236:17): [True: 0, False: 0]
237
0
                break;
238
0
            else {
239
                // Rewrite these encrypted keys with checksums
240
0
                batch.WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
241
0
            }
242
0
        }
243
0
        if (keyPass && keyFail)
  Branch (243:13): [True: 0, False: 0]
  Branch (243:24): [True: 0, False: 0]
244
0
        {
245
0
            LogWarning("The wallet is probably corrupted: Some keys decrypt but not all.");
246
0
            throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
247
0
        }
248
0
        if (keyFail || !keyPass)
  Branch (248:13): [True: 0, False: 0]
  Branch (248:24): [True: 0, False: 0]
249
0
            return false;
250
0
        fDecryptionThoroughlyChecked = true;
251
0
    }
252
0
    return true;
253
0
}
254
255
std::unique_ptr<SigningProvider> LegacyDataSPKM::GetSolvingProvider(const CScript& script) const
256
0
{
257
0
    return std::make_unique<LegacySigningProvider>(*this);
258
0
}
259
260
bool LegacyDataSPKM::CanProvide(const CScript& script, SignatureData& sigdata)
261
0
{
262
0
    IsMineResult ismine = LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
263
0
    if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
  Branch (263:9): [True: 0, False: 0]
  Branch (263:46): [True: 0, False: 0]
264
        // If ismine, it means we recognize keys or script ids in the script, or
265
        // are watching the script itself, and we can at least provide metadata
266
        // or solving information, even if not able to sign fully.
267
0
        return true;
268
0
    } else {
269
        // If, given the stuff in sigdata, we could make a valid signature, then we can provide for this script
270
0
        ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
271
0
        if (!sigdata.signatures.empty()) {
  Branch (271:13): [True: 0, False: 0]
272
            // If we could make signatures, make sure we have a private key to actually make a signature
273
0
            bool has_privkeys = false;
274
0
            for (const auto& key_sig_pair : sigdata.signatures) {
  Branch (274:43): [True: 0, False: 0]
275
0
                has_privkeys |= HaveKey(key_sig_pair.first);
276
0
            }
277
0
            return has_privkeys;
278
0
        }
279
0
        return false;
280
0
    }
281
0
}
282
283
bool LegacyDataSPKM::LoadKey(const CKey& key, const CPubKey &pubkey)
284
0
{
285
0
    return AddKeyPubKeyInner(key, pubkey);
286
0
}
287
288
bool LegacyDataSPKM::LoadCScript(const CScript& redeemScript)
289
0
{
290
    /* A sanity check was added in pull #3843 to avoid adding redeemScripts
291
     * that never can be redeemed. However, old wallets may still contain
292
     * these. Do not add them to the wallet and warn. */
293
0
    if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
  Branch (293:9): [True: 0, False: 0]
294
0
    {
295
0
        std::string strAddr = EncodeDestination(ScriptHash(redeemScript));
296
0
        WalletLogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n", __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
297
0
        return true;
298
0
    }
299
300
0
    return FillableSigningProvider::AddCScript(redeemScript);
301
0
}
302
303
void LegacyDataSPKM::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
304
0
{
305
0
    LOCK(cs_KeyStore);
306
0
    mapKeyMetadata[keyID] = meta;
307
0
}
308
309
void LegacyDataSPKM::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata& meta)
310
0
{
311
0
    LOCK(cs_KeyStore);
312
0
    m_script_metadata[script_id] = meta;
313
0
}
314
315
bool LegacyDataSPKM::AddKeyPubKeyInner(const CKey& key, const CPubKey& pubkey)
316
0
{
317
0
    LOCK(cs_KeyStore);
318
0
    return FillableSigningProvider::AddKeyPubKey(key, pubkey);
319
0
}
320
321
bool LegacyDataSPKM::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid)
322
0
{
323
    // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
324
0
    if (!checksum_valid) {
  Branch (324:9): [True: 0, False: 0]
325
0
        fDecryptionThoroughlyChecked = false;
326
0
    }
327
328
0
    return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
329
0
}
330
331
bool LegacyDataSPKM::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
332
0
{
333
0
    LOCK(cs_KeyStore);
334
0
    assert(mapKeys.empty());
  Branch (334:5): [True: 0, False: 0]
335
336
0
    mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
337
0
    ImplicitlyLearnRelatedKeyScripts(vchPubKey);
338
0
    return true;
339
0
}
340
341
bool LegacyDataSPKM::HaveWatchOnly(const CScript &dest) const
342
0
{
343
0
    LOCK(cs_KeyStore);
344
0
    return setWatchOnly.contains(dest);
345
0
}
346
347
bool LegacyDataSPKM::LoadWatchOnly(const CScript &dest)
348
0
{
349
0
    return AddWatchOnlyInMem(dest);
350
0
}
351
352
static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
353
0
{
354
0
    std::vector<std::vector<unsigned char>> solutions;
355
0
    return Solver(dest, solutions) == TxoutType::PUBKEY &&
  Branch (355:12): [True: 0, False: 0]
356
0
        (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
  Branch (356:9): [True: 0, False: 0]
357
0
}
358
359
bool LegacyDataSPKM::AddWatchOnlyInMem(const CScript &dest)
360
0
{
361
0
    LOCK(cs_KeyStore);
362
0
    setWatchOnly.insert(dest);
363
0
    CPubKey pubKey;
364
0
    if (ExtractPubKey(dest, pubKey)) {
  Branch (364:9): [True: 0, False: 0]
365
0
        mapWatchKeys[pubKey.GetID()] = pubKey;
366
0
        ImplicitlyLearnRelatedKeyScripts(pubKey);
367
0
    }
368
0
    return true;
369
0
}
370
371
void LegacyDataSPKM::LoadHDChain(const CHDChain& chain)
372
0
{
373
0
    LOCK(cs_KeyStore);
374
0
    m_hd_chain = chain;
375
0
}
376
377
void LegacyDataSPKM::AddInactiveHDChain(const CHDChain& chain)
378
0
{
379
0
    LOCK(cs_KeyStore);
380
0
    assert(!chain.seed_id.IsNull());
  Branch (380:5): [True: 0, False: 0]
381
0
    m_inactive_hd_chains[chain.seed_id] = chain;
382
0
}
383
384
bool LegacyDataSPKM::HaveKey(const CKeyID &address) const
385
0
{
386
0
    LOCK(cs_KeyStore);
387
0
    if (!m_storage.HasEncryptionKeys()) {
  Branch (387:9): [True: 0, False: 0]
388
0
        return FillableSigningProvider::HaveKey(address);
389
0
    }
390
0
    return mapCryptedKeys.contains(address);
391
0
}
392
393
bool LegacyDataSPKM::GetKey(const CKeyID &address, CKey& keyOut) const
394
0
{
395
0
    LOCK(cs_KeyStore);
396
0
    if (!m_storage.HasEncryptionKeys()) {
  Branch (396:9): [True: 0, False: 0]
397
0
        return FillableSigningProvider::GetKey(address, keyOut);
398
0
    }
399
400
0
    CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
401
0
    if (mi != mapCryptedKeys.end())
  Branch (401:9): [True: 0, False: 0]
402
0
    {
403
0
        const CPubKey &vchPubKey = (*mi).second.first;
404
0
        const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
405
0
        return m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
406
0
            return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey, keyOut);
407
0
        });
408
0
    }
409
0
    return false;
410
0
}
411
412
bool LegacyDataSPKM::GetKeyOrigin(const CKeyID& keyID, KeyOriginInfo& info) const
413
0
{
414
0
    CKeyMetadata meta;
415
0
    {
416
0
        LOCK(cs_KeyStore);
417
0
        auto it = mapKeyMetadata.find(keyID);
418
0
        if (it == mapKeyMetadata.end()) {
  Branch (418:13): [True: 0, False: 0]
419
0
            return false;
420
0
        }
421
0
        meta = it->second;
422
0
    }
423
0
    if (meta.has_key_origin) {
  Branch (423:9): [True: 0, False: 0]
424
0
        std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4, info.fingerprint);
425
0
        info.path = meta.key_origin.path;
426
0
    } else { // Single pubkeys get the master fingerprint of themselves
427
0
        std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
428
0
    }
429
0
    return true;
430
0
}
431
432
bool LegacyDataSPKM::GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
433
0
{
434
0
    LOCK(cs_KeyStore);
435
0
    WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
436
0
    if (it != mapWatchKeys.end()) {
  Branch (436:9): [True: 0, False: 0]
437
0
        pubkey_out = it->second;
438
0
        return true;
439
0
    }
440
0
    return false;
441
0
}
442
443
bool LegacyDataSPKM::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
444
0
{
445
0
    LOCK(cs_KeyStore);
446
0
    if (!m_storage.HasEncryptionKeys()) {
  Branch (446:9): [True: 0, False: 0]
447
0
        if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
  Branch (447:13): [True: 0, False: 0]
448
0
            return GetWatchPubKey(address, vchPubKeyOut);
449
0
        }
450
0
        return true;
451
0
    }
452
453
0
    CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
454
0
    if (mi != mapCryptedKeys.end())
  Branch (454:9): [True: 0, False: 0]
455
0
    {
456
0
        vchPubKeyOut = (*mi).second.first;
457
0
        return true;
458
0
    }
459
    // Check for watch-only pubkeys
460
0
    return GetWatchPubKey(address, vchPubKeyOut);
461
0
}
462
463
std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetCandidateScriptPubKeys() const
464
0
{
465
0
    LOCK(cs_KeyStore);
466
0
    std::unordered_set<CScript, SaltedSipHasher> candidate_spks;
467
468
    // For every private key in the wallet, there should be a P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH
469
0
    const auto& add_pubkey = [&candidate_spks](const CPubKey& pub) -> void {
470
0
        candidate_spks.insert(GetScriptForRawPubKey(pub));
471
0
        candidate_spks.insert(GetScriptForDestination(PKHash(pub)));
472
473
0
        CScript wpkh = GetScriptForDestination(WitnessV0KeyHash(pub));
474
0
        candidate_spks.insert(wpkh);
475
0
        candidate_spks.insert(GetScriptForDestination(ScriptHash(wpkh)));
476
0
    };
477
0
    for (const auto& [_, key] : mapKeys) {
  Branch (477:31): [True: 0, False: 0]
478
0
        add_pubkey(key.GetPubKey());
479
0
    }
480
0
    for (const auto& [_, ckeypair] : mapCryptedKeys) {
  Branch (480:36): [True: 0, False: 0]
481
0
        add_pubkey(ckeypair.first);
482
0
    }
483
484
    // mapScripts contains all redeemScripts and witnessScripts. Therefore each script in it has
485
    // itself, P2SH, P2WSH, and P2SH-P2WSH as a candidate.
486
    // Invalid scripts such as P2SH-P2SH and P2WSH-P2SH, among others, will be added as candidates.
487
    // Callers of this function will need to remove such scripts.
488
0
    const auto& add_script = [&candidate_spks](const CScript& script) -> void {
489
0
        candidate_spks.insert(script);
490
0
        candidate_spks.insert(GetScriptForDestination(ScriptHash(script)));
491
492
0
        CScript wsh = GetScriptForDestination(WitnessV0ScriptHash(script));
493
0
        candidate_spks.insert(wsh);
494
0
        candidate_spks.insert(GetScriptForDestination(ScriptHash(wsh)));
495
0
    };
496
0
    for (const auto& [_, script] : mapScripts) {
  Branch (496:34): [True: 0, False: 0]
497
0
        add_script(script);
498
0
    }
499
500
    // Although setWatchOnly should only contain output scripts, we will also include each script's
501
    // P2SH, P2WSH, and P2SH-P2WSH as a precaution.
502
0
    for (const auto& script : setWatchOnly) {
  Branch (502:29): [True: 0, False: 0]
503
0
        add_script(script);
504
0
    }
505
506
0
    return candidate_spks;
507
0
}
508
509
std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetScriptPubKeys() const
510
0
{
511
    // Run IsMine() on each candidate output script. Any script that IsMine is an output
512
    // script to return.
513
    // This both filters out things that are not watched by the wallet, and things that are invalid.
514
0
    std::unordered_set<CScript, SaltedSipHasher> spks;
515
0
    for (const CScript& script : GetCandidateScriptPubKeys()) {
  Branch (515:32): [True: 0, False: 0]
516
0
        if (IsMine(script)) {
  Branch (516:13): [True: 0, False: 0]
517
0
            spks.insert(script);
518
0
        }
519
0
    }
520
521
0
    return spks;
522
0
}
523
524
std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetNotMineScriptPubKeys() const
525
0
{
526
0
    LOCK(cs_KeyStore);
527
0
    std::unordered_set<CScript, SaltedSipHasher> spks;
528
0
    for (const CScript& script : setWatchOnly) {
  Branch (528:32): [True: 0, False: 0]
529
0
        if (!IsMine(script)) spks.insert(script);
  Branch (529:13): [True: 0, False: 0]
530
0
    }
531
0
    return spks;
532
0
}
533
534
std::optional<MigrationData> LegacyDataSPKM::MigrateToDescriptor()
535
0
{
536
0
    LOCK(cs_KeyStore);
537
0
    if (m_storage.IsLocked()) {
  Branch (537:9): [True: 0, False: 0]
538
0
        return std::nullopt;
539
0
    }
540
541
0
    MigrationData out;
542
543
0
    std::unordered_set<CScript, SaltedSipHasher> spks{GetScriptPubKeys()};
544
545
    // Get all key ids
546
0
    std::set<CKeyID> keyids;
547
0
    for (const auto& key_pair : mapKeys) {
  Branch (547:31): [True: 0, False: 0]
548
0
        keyids.insert(key_pair.first);
549
0
    }
550
0
    for (const auto& key_pair : mapCryptedKeys) {
  Branch (550:31): [True: 0, False: 0]
551
0
        keyids.insert(key_pair.first);
552
0
    }
553
554
    // Get key metadata and figure out which keys don't have a seed
555
    // Note that we do not ignore the seeds themselves because they are considered IsMine!
556
0
    for (auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
  Branch (556:42): [True: 0, False: 0]
557
0
        const CKeyID& keyid = *keyid_it;
558
0
        const auto& it = mapKeyMetadata.find(keyid);
559
0
        if (it != mapKeyMetadata.end()) {
  Branch (559:13): [True: 0, False: 0]
560
0
            const CKeyMetadata& meta = it->second;
561
0
            if (meta.hdKeypath == "s" || meta.hdKeypath == "m") {
  Branch (561:17): [True: 0, False: 0]
  Branch (561:42): [True: 0, False: 0]
562
0
                keyid_it++;
563
0
                continue;
564
0
            }
565
0
            if (!meta.hd_seed_id.IsNull() && (m_hd_chain.seed_id == meta.hd_seed_id || m_inactive_hd_chains.contains(meta.hd_seed_id))) {
  Branch (565:17): [True: 0, False: 0]
  Branch (565:47): [True: 0, False: 0]
  Branch (565:88): [True: 0, False: 0]
566
0
                keyid_it = keyids.erase(keyid_it);
567
0
                continue;
568
0
            }
569
0
        }
570
0
        keyid_it++;
571
0
    }
572
573
0
    WalletBatch batch(m_storage.GetDatabase());
574
0
    if (!batch.TxnBegin()) {
  Branch (574:9): [True: 0, False: 0]
575
0
        LogWarning("Error generating descriptors for migration, cannot initialize db transaction");
576
0
        return std::nullopt;
577
0
    }
578
579
    // keyids is now all non-HD keys. Each key will have its own combo descriptor
580
0
    for (const CKeyID& keyid : keyids) {
  Branch (580:30): [True: 0, False: 0]
581
0
        CKey key;
582
0
        if (!GetKey(keyid, key)) {
  Branch (582:13): [True: 0, False: 0]
583
0
            assert(false);
  Branch (583:13): [Folded - Ignored]
584
0
        }
585
586
        // Get birthdate from key meta
587
0
        uint64_t creation_time = 0;
588
0
        const auto& it = mapKeyMetadata.find(keyid);
589
0
        if (it != mapKeyMetadata.end()) {
  Branch (589:13): [True: 0, False: 0]
590
0
            creation_time = it->second.nCreateTime;
591
0
        }
592
593
        // Get the key origin
594
        // Maybe this doesn't matter because floating keys here shouldn't have origins
595
0
        KeyOriginInfo info;
596
0
        bool has_info = GetKeyOrigin(keyid, info);
597
0
        std::string origin_str = has_info ? "[" + HexStr(info.fingerprint) + FormatHDKeypath(info.path) + "]" : "";
  Branch (597:34): [True: 0, False: 0]
598
599
        // Construct the combo descriptor
600
0
        std::string desc_str = "combo(" + origin_str + HexStr(key.GetPubKey()) + ")";
601
0
        FlatSigningProvider provider;
602
0
        std::string error;
603
0
        std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, provider, error, false);
604
0
        CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
605
0
        WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
606
607
        // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
608
0
        provider.keys.emplace(key.GetPubKey().GetID(), key);
609
0
        auto desc_spk_man = DescriptorScriptPubKeyMan::CreateFromMigration(m_storage, batch, w_desc, /*keypool_size=*/0, provider);
610
0
        auto desc_spks = desc_spk_man->GetScriptPubKeys();
611
612
        // Remove the scriptPubKeys from our current set
613
0
        for (const CScript& spk : desc_spks) {
  Branch (613:33): [True: 0, False: 0]
614
0
            size_t erased = spks.erase(spk);
615
0
            assert(erased == 1);
  Branch (615:13): [True: 0, False: 0]
616
0
            assert(IsMine(spk));
  Branch (616:13): [True: 0, False: 0]
617
0
        }
618
619
0
        out.desc_spkms.push_back(std::move(desc_spk_man));
620
0
    }
621
622
    // Handle HD keys by using the CHDChains
623
0
    std::set<CHDChain> chains;
624
0
    chains.insert(m_hd_chain);
625
0
    for (const auto& chain_pair : m_inactive_hd_chains) {
  Branch (625:33): [True: 0, False: 0]
626
0
        chains.insert(chain_pair.second);
627
0
    }
628
629
0
    bool can_support_hd_split_feature = m_hd_chain.nVersion >= CHDChain::VERSION_HD_CHAIN_SPLIT;
630
631
0
    std::set<CExtPubKey> master_xpubs;
632
0
    for (const CHDChain& chain : chains) {
  Branch (632:32): [True: 0, False: 0]
633
0
        if (chain.seed_id.IsNull()) continue;
  Branch (633:13): [True: 0, False: 0]
634
635
        // Get the master xprv
636
0
        CKey seed_key;
637
0
        if (!GetKey(chain.seed_id, seed_key)) {
  Branch (637:13): [True: 0, False: 0]
638
0
            assert(false);
  Branch (638:13): [Folded - Ignored]
639
0
        }
640
0
        CExtKey master_key;
641
0
        master_key.SetSeed(seed_key);
642
643
        // Get the xpub and verify that we haven't already seen this xpub before
644
0
        CExtPubKey master_xpub = master_key.Neuter();
645
0
        const auto& [_, inserted] = master_xpubs.insert(master_xpub);
646
0
        if (!inserted) continue;
  Branch (646:13): [True: 0, False: 0]
647
648
0
        for (int i = 0; i < 2; ++i) {
  Branch (648:25): [True: 0, False: 0]
649
            // Skip if doing internal chain and split chain is not supported
650
0
            if (i == 1 && !can_support_hd_split_feature) {
  Branch (650:17): [True: 0, False: 0]
  Branch (650:27): [True: 0, False: 0]
651
0
                continue;
652
0
            }
653
654
            // Make the combo descriptor
655
0
            std::string xpub = EncodeExtPubKey(master_key.Neuter());
656
0
            std::string desc_str = "combo(" + xpub + "/0h/" + ToString(i) + "h/*h)";
657
0
            FlatSigningProvider provider;
658
0
            std::string error;
659
0
            std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, provider, error, false);
660
0
            CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
661
0
            uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
  Branch (661:48): [True: 0, False: 0]
662
0
            WalletDescriptor w_desc(std::move(descs.at(0)), 0, 0, chain_counter, 0);
663
664
            // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
665
0
            provider.keys.emplace(master_key.key.GetPubKey().GetID(), master_key.key);
666
0
            auto desc_spk_man = DescriptorScriptPubKeyMan::CreateFromMigration(m_storage, batch, w_desc, /*keypool_size=*/0, provider);
667
0
            auto desc_spks = desc_spk_man->GetScriptPubKeys();
668
669
            // Remove the scriptPubKeys from our current set
670
0
            for (const CScript& spk : desc_spks) {
  Branch (670:37): [True: 0, False: 0]
671
0
                size_t erased = spks.erase(spk);
672
0
                assert(erased == 1);
  Branch (672:17): [True: 0, False: 0]
673
0
                assert(IsMine(spk));
  Branch (673:17): [True: 0, False: 0]
674
0
            }
675
676
0
            out.desc_spkms.push_back(std::move(desc_spk_man));
677
0
        }
678
0
    }
679
    // Add the current master seed to the migration data
680
0
    if (!m_hd_chain.seed_id.IsNull()) {
  Branch (680:9): [True: 0, False: 0]
681
0
        CKey seed_key;
682
0
        if (!GetKey(m_hd_chain.seed_id, seed_key)) {
  Branch (682:13): [True: 0, False: 0]
683
0
            assert(false);
  Branch (683:13): [Folded - Ignored]
684
0
        }
685
0
        out.master_key.SetSeed(seed_key);
686
0
    }
687
688
    // Handle the rest of the scriptPubKeys which must be imports and may not have all info
689
0
    for (auto it = spks.begin(); it != spks.end();) {
  Branch (689:34): [True: 0, False: 0]
690
0
        const CScript& spk = *it;
691
692
        // Get birthdate from script meta
693
0
        uint64_t creation_time = 0;
694
0
        const auto& mit = m_script_metadata.find(CScriptID(spk));
695
0
        if (mit != m_script_metadata.end()) {
  Branch (695:13): [True: 0, False: 0]
696
0
            creation_time = mit->second.nCreateTime;
697
0
        }
698
699
        // InferDescriptor as that will get us all the solving info if it is there
700
0
        std::unique_ptr<Descriptor> desc = InferDescriptor(spk, *GetSolvingProvider(spk));
701
702
        // Past bugs in InferDescriptor have caused it to create descriptors which cannot be re-parsed.
703
        // Re-parse the descriptors to detect that, and skip any that do not parse.
704
0
        {
705
0
            std::string desc_str = desc->ToString();
706
0
            FlatSigningProvider parsed_keys;
707
0
            std::string parse_error;
708
0
            std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error);
709
0
            if (parsed_descs.empty()) {
  Branch (709:17): [True: 0, False: 0]
710
                // Remove this scriptPubKey from the set
711
0
                it = spks.erase(it);
712
0
                continue;
713
0
            }
714
0
        }
715
716
        // Get the private keys for this descriptor
717
0
        std::vector<CScript> scripts;
718
0
        FlatSigningProvider keys;
719
0
        if (!desc->Expand(0, DUMMY_SIGNING_PROVIDER, scripts, keys)) {
  Branch (719:13): [True: 0, False: 0]
720
0
            assert(false);
  Branch (720:13): [Folded - Ignored]
721
0
        }
722
0
        std::set<CKeyID> privkeyids;
723
0
        for (const auto& key_orig_pair : keys.origins) {
  Branch (723:40): [True: 0, False: 0]
724
0
            privkeyids.insert(key_orig_pair.first);
725
0
        }
726
727
0
        std::vector<CScript> desc_spks;
728
729
        // If we can't provide all private keys for this inferred descriptor,
730
        // but this wallet is not watch-only, migrate it to the watch-only wallet.
731
0
        if (!desc->HavePrivateKeys(*this) && !m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
  Branch (731:13): [True: 0, False: 0]
  Branch (731:46): [True: 0, False: 0]
732
0
            out.watch_descs.emplace_back(desc->ToString(), creation_time);
733
734
            // Get the scriptPubKeys without writing this to the wallet
735
0
            FlatSigningProvider provider;
736
0
            desc->Expand(0, provider, desc_spks, provider);
737
0
        } else {
738
            // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
739
0
            for (const auto& keyid : privkeyids) {
  Branch (739:36): [True: 0, False: 0]
740
0
                CKey key;
741
0
                if (!GetKey(keyid, key)) {
  Branch (741:21): [True: 0, False: 0]
742
0
                    continue;
743
0
                }
744
0
                keys.keys.emplace(key.GetPubKey().GetID(), key);
745
0
            }
746
0
            WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
747
0
            auto desc_spk_man = DescriptorScriptPubKeyMan::CreateFromMigration(m_storage, batch, w_desc, /*keypool_size=*/0, keys);
748
0
            auto desc_spks_set = desc_spk_man->GetScriptPubKeys();
749
0
            desc_spks.insert(desc_spks.end(), desc_spks_set.begin(), desc_spks_set.end());
750
751
0
            out.desc_spkms.push_back(std::move(desc_spk_man));
752
0
        }
753
754
        // Remove the scriptPubKeys from our current set
755
0
        for (const CScript& desc_spk : desc_spks) {
  Branch (755:38): [True: 0, False: 0]
756
0
            auto del_it = spks.find(desc_spk);
757
0
            assert(del_it != spks.end());
  Branch (757:13): [True: 0, False: 0]
758
0
            assert(IsMine(desc_spk));
  Branch (758:13): [True: 0, False: 0]
759
0
            it = spks.erase(del_it);
760
0
        }
761
0
    }
762
763
    // Make sure that we have accounted for all scriptPubKeys
764
0
    if (!Assume(spks.empty())) {
  Branch (764:9): [True: 0, False: 0]
765
0
        LogError("%s", STR_INTERNAL_BUG("Error: Some output scripts were not migrated."));
766
0
        return std::nullopt;
767
0
    }
768
769
    // Legacy wallets can also contain scripts whose P2SH, P2WSH, or P2SH-P2WSH it is not watching for
770
    // but can provide script data to a PSBT spending them. These "solvable" output scripts will need to
771
    // be put into the separate "solvables" wallet.
772
    // These can be detected by going through the entire candidate output scripts, finding the not IsMine scripts,
773
    // and checking CanProvide() which will dummy sign.
774
0
    for (const CScript& script : GetCandidateScriptPubKeys()) {
  Branch (774:32): [True: 0, False: 0]
775
        // Since we only care about P2SH, P2WSH, and P2SH-P2WSH, filter out any scripts that are not those
776
0
        if (!script.IsPayToScriptHash() && !script.IsPayToWitnessScriptHash()) {
  Branch (776:13): [True: 0, False: 0]
  Branch (776:44): [True: 0, False: 0]
777
0
            continue;
778
0
        }
779
0
        if (IsMine(script)) {
  Branch (779:13): [True: 0, False: 0]
780
0
            continue;
781
0
        }
782
0
        SignatureData dummy_sigdata;
783
0
        if (!CanProvide(script, dummy_sigdata)) {
  Branch (783:13): [True: 0, False: 0]
784
0
            continue;
785
0
        }
786
787
        // Get birthdate from script meta
788
0
        uint64_t creation_time = 0;
789
0
        const auto& it = m_script_metadata.find(CScriptID(script));
790
0
        if (it != m_script_metadata.end()) {
  Branch (790:13): [True: 0, False: 0]
791
0
            creation_time = it->second.nCreateTime;
792
0
        }
793
794
        // InferDescriptor as that will get us all the solving info if it is there
795
0
        std::unique_ptr<Descriptor> desc = InferDescriptor(script, *GetSolvingProvider(script));
796
0
        if (!desc->IsSolvable()) {
  Branch (796:13): [True: 0, False: 0]
797
            // The wallet was able to provide some information, but not enough to make a descriptor that actually
798
            // contains anything useful. This is probably because the script itself is actually unsignable (e.g. P2WSH-P2WSH).
799
0
            continue;
800
0
        }
801
802
        // Past bugs in InferDescriptor have caused it to create descriptors which cannot be re-parsed
803
        // Re-parse the descriptors to detect that, and skip any that do not parse.
804
0
        {
805
0
            std::string desc_str = desc->ToString();
806
0
            FlatSigningProvider parsed_keys;
807
0
            std::string parse_error;
808
0
            std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error, false);
809
0
            if (parsed_descs.empty()) {
  Branch (809:17): [True: 0, False: 0]
810
0
                continue;
811
0
            }
812
0
        }
813
814
0
        out.solvable_descs.emplace_back(desc->ToString(), creation_time);
815
0
    }
816
817
    // Finalize transaction
818
0
    if (!batch.TxnCommit()) {
  Branch (818:9): [True: 0, False: 0]
819
0
        LogWarning("Error generating descriptors for migration, cannot commit db transaction");
820
0
        return std::nullopt;
821
0
    }
822
823
0
    return out;
824
0
}
825
826
bool LegacyDataSPKM::DeleteRecordsWithDB(WalletBatch& batch)
827
0
{
828
0
    LOCK(cs_KeyStore);
829
0
    return batch.EraseRecords(DBKeys::LEGACY_TYPES);
830
0
}
831
832
std::unique_ptr<DescriptorScriptPubKeyMan> DescriptorScriptPubKeyMan::CreateFromImport(WalletStorage& storage, WalletDescriptor& descriptor, int64_t keypool_size, const FlatSigningProvider& provider)
833
0
{
834
0
    auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, descriptor, keypool_size));
835
0
    LOCK(spkm->cs_desc_man);
836
0
    WalletBatch batch(storage.GetDatabase());
837
0
    spkm->UpdateWithSigningProvider(batch, provider);
838
0
    return spkm;
839
0
}
840
841
std::unique_ptr<DescriptorScriptPubKeyMan> DescriptorScriptPubKeyMan::CreateFromMigration(WalletStorage& storage, WalletBatch& batch, WalletDescriptor& descriptor, int64_t keypool_size, const FlatSigningProvider& provider)
842
0
{
843
0
    auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, descriptor, keypool_size));
844
0
    LOCK(spkm->cs_desc_man);
845
0
    spkm->UpdateWithSigningProvider(batch, provider);
846
0
    return spkm;
847
0
}
848
849
DescriptorScriptPubKeyMan::DescriptorScriptPubKeyMan(WalletStorage& storage, WalletDescriptor& descriptor, int64_t keypool_size, const KeyMap& keys, const CryptedKeyMap& ckeys)
850
0
    : ScriptPubKeyMan(storage),
851
0
    m_map_keys(keys),
852
0
    m_map_crypted_keys(ckeys),
853
0
    m_keypool_size(keypool_size),
854
0
    m_wallet_descriptor(descriptor)
855
0
{
856
0
    if (!keys.empty() && !ckeys.empty()) {
  Branch (856:9): [True: 0, False: 0]
  Branch (856:26): [True: 0, False: 0]
857
0
        throw std::runtime_error("Wallet contains both unencrypted and encrypted keys");
858
0
    }
859
0
    Load();
860
0
}
861
862
std::unique_ptr<DescriptorScriptPubKeyMan> DescriptorScriptPubKeyMan::LoadFromStorage(WalletStorage& storage, WalletDescriptor& descriptor, int64_t keypool_size, const KeyMap& keys, const CryptedKeyMap& ckeys)
863
0
{
864
0
    return std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, descriptor, keypool_size, keys, ckeys));
865
0
}
866
867
std::unique_ptr<DescriptorScriptPubKeyMan> DescriptorScriptPubKeyMan::GenerateNewSingleSig(WalletStorage& storage, WalletBatch& batch, int64_t keypool_size, const CExtKey& master_key, OutputType addr_type, bool internal)
868
0
{
869
0
    auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, keypool_size));
870
0
    spkm->SetupDescriptorGeneration(batch, master_key, addr_type, internal);
871
0
    return spkm;
872
0
}
873
874
util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetNewDestination(const OutputType type)
875
0
{
876
    // Returns true if this descriptor supports getting new addresses. Conditions where we may be unable to fetch them (e.g. locked) are caught later
877
0
    if (!CanGetAddresses()) {
  Branch (877:9): [True: 0, False: 0]
878
0
        return util::Error{_("No addresses available")};
879
0
    }
880
0
    {
881
0
        LOCK(cs_desc_man);
882
0
        assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
  Branch (882:9): [True: 0, False: 0]
883
0
        std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
884
0
        assert(desc_addr_type);
  Branch (884:9): [True: 0, False: 0]
885
0
        if (type != *desc_addr_type) {
  Branch (885:13): [True: 0, False: 0]
886
0
            throw std::runtime_error(std::string(__func__) + ": Types are inconsistent. Stored type does not match type of newly generated address");
887
0
        }
888
889
0
        TopUp();
890
891
        // Get the scriptPubKey from the descriptor
892
0
        FlatSigningProvider out_keys;
893
0
        std::vector<CScript> scripts_temp;
894
0
        if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
  Branch (894:13): [True: 0, False: 0]
  Branch (894:68): [True: 0, False: 0]
895
            // We can't generate anymore keys
896
0
            return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
897
0
        }
898
0
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
  Branch (898:13): [True: 0, False: 0]
899
            // We can't generate anymore keys
900
0
            return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
901
0
        }
902
903
0
        CTxDestination dest;
904
0
        if (!ExtractDestination(scripts_temp[0], dest)) {
  Branch (904:13): [True: 0, False: 0]
905
0
            return util::Error{_("Error: Cannot extract destination from the generated scriptpubkey")}; // shouldn't happen
906
0
        }
907
0
        m_wallet_descriptor.next_index++;
908
0
        WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
909
0
        return dest;
910
0
    }
911
0
}
912
913
bool DescriptorScriptPubKeyMan::IsMine(const CScript& script) const
914
0
{
915
0
    LOCK(cs_desc_man);
916
0
    return m_map_script_pub_keys.contains(script);
917
0
}
918
919
bool DescriptorScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key)
920
0
{
921
0
    LOCK(cs_desc_man);
922
0
    if (!m_map_keys.empty()) {
  Branch (922:9): [True: 0, False: 0]
923
0
        return false;
924
0
    }
925
926
0
    bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
927
0
    bool keyFail = false;
928
0
    for (const auto& mi : m_map_crypted_keys) {
  Branch (928:25): [True: 0, False: 0]
929
0
        const CPubKey &pubkey = mi.second.first;
930
0
        const std::vector<unsigned char> &crypted_secret = mi.second.second;
931
0
        CKey key;
932
0
        if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
  Branch (932:13): [True: 0, False: 0]
933
0
            keyFail = true;
934
0
            break;
935
0
        }
936
0
        keyPass = true;
937
0
        if (m_decryption_thoroughly_checked)
  Branch (937:13): [True: 0, False: 0]
938
0
            break;
939
0
    }
940
0
    if (keyPass && keyFail) {
  Branch (940:9): [True: 0, False: 0]
  Branch (940:20): [True: 0, False: 0]
941
0
        LogWarning("The wallet is probably corrupted: Some keys decrypt but not all.");
942
0
        throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
943
0
    }
944
0
    if (keyFail || !keyPass) {
  Branch (944:9): [True: 0, False: 0]
  Branch (944:20): [True: 0, False: 0]
945
0
        return false;
946
0
    }
947
0
    m_decryption_thoroughly_checked = true;
948
0
    return true;
949
0
}
950
951
bool DescriptorScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
952
0
{
953
0
    LOCK(cs_desc_man);
954
0
    if (!m_map_crypted_keys.empty()) {
  Branch (954:9): [True: 0, False: 0]
955
0
        return false;
956
0
    }
957
958
0
    for (const KeyMap::value_type& key_in : m_map_keys)
  Branch (958:43): [True: 0, False: 0]
959
0
    {
960
0
        const CKey &key = key_in.second;
961
0
        CPubKey pubkey = key.GetPubKey();
962
0
        CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
963
0
        std::vector<unsigned char> crypted_secret;
964
0
        if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
  Branch (964:13): [True: 0, False: 0]
965
0
            return false;
966
0
        }
967
0
        m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
968
0
        batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
969
0
    }
970
0
    m_map_keys.clear();
971
0
    return true;
972
0
}
973
974
util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, int64_t& index)
975
0
{
976
0
    LOCK(cs_desc_man);
977
0
    auto op_dest = GetNewDestination(type);
978
0
    index = m_wallet_descriptor.next_index - 1;
979
0
    return op_dest;
980
0
}
981
982
void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
983
0
{
984
0
    LOCK(cs_desc_man);
985
    // Only return when the index was the most recent
986
0
    if (m_wallet_descriptor.next_index - 1 == index) {
  Branch (986:9): [True: 0, False: 0]
987
0
        m_wallet_descriptor.next_index--;
988
0
    }
989
0
    WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
990
0
    NotifyCanGetAddressesChanged();
991
0
}
992
993
std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
994
0
{
995
0
    AssertLockHeld(cs_desc_man);
996
0
    if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
  Branch (996:9): [True: 0, False: 0]
  Branch (996:42): [True: 0, False: 0]
997
0
        KeyMap keys;
998
0
        for (const auto& key_pair : m_map_crypted_keys) {
  Branch (998:35): [True: 0, False: 0]
999
0
            const CPubKey& pubkey = key_pair.second.first;
1000
0
            const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
1001
0
            CKey key;
1002
0
            m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
1003
0
                return DecryptKey(encryption_key, crypted_secret, pubkey, key);
1004
0
            });
1005
0
            keys[pubkey.GetID()] = key;
1006
0
        }
1007
0
        return keys;
1008
0
    }
1009
0
    return m_map_keys;
1010
0
}
1011
1012
bool DescriptorScriptPubKeyMan::HasPrivKey(const CKeyID& keyid) const
1013
0
{
1014
0
    AssertLockHeld(cs_desc_man);
1015
0
    return m_map_keys.contains(keyid) || m_map_crypted_keys.contains(keyid);
  Branch (1015:12): [True: 0, False: 0]
  Branch (1015:42): [True: 0, False: 0]
1016
0
}
1017
1018
std::optional<CKey> DescriptorScriptPubKeyMan::GetKey(const CKeyID& keyid) const
1019
0
{
1020
0
    AssertLockHeld(cs_desc_man);
1021
0
    if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
  Branch (1021:9): [True: 0, False: 0]
  Branch (1021:42): [True: 0, False: 0]
1022
0
        const auto& it = m_map_crypted_keys.find(keyid);
1023
0
        if (it == m_map_crypted_keys.end()) {
  Branch (1023:13): [True: 0, False: 0]
1024
0
            return std::nullopt;
1025
0
        }
1026
0
        const std::vector<unsigned char>& crypted_secret = it->second.second;
1027
0
        CKey key;
1028
0
        if (!Assume(m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
  Branch (1028:13): [True: 0, False: 0]
1029
0
            return DecryptKey(encryption_key, crypted_secret, it->second.first, key);
1030
0
        }))) {
1031
0
            return std::nullopt;
1032
0
        }
1033
0
        return key;
1034
0
    }
1035
0
    const auto& it = m_map_keys.find(keyid);
1036
0
    if (it == m_map_keys.end()) {
  Branch (1036:9): [True: 0, False: 0]
1037
0
        return std::nullopt;
1038
0
    }
1039
0
    return it->second;
1040
0
}
1041
1042
bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
1043
0
{
1044
0
    WalletBatch batch(m_storage.GetDatabase());
1045
0
    if (!batch.TxnBegin()) return false;
  Branch (1045:9): [True: 0, False: 0]
1046
0
    bool res = TopUpWithDB(batch, size);
1047
0
    if (!batch.TxnCommit()) throw std::runtime_error(strprintf("Error during descriptors keypool top up. Cannot commit changes for wallet [%s]", m_storage.LogName()));
  Branch (1047:9): [True: 0, False: 0]
1048
0
    return res;
1049
0
}
1050
1051
bool DescriptorScriptPubKeyMan::TopUpWithDB(WalletBatch& batch, unsigned int size)
1052
0
{
1053
0
    LOCK(cs_desc_man);
1054
0
    std::set<CScript> new_spks;
1055
0
    unsigned int target_size;
1056
0
    if (size > 0) {
  Branch (1056:9): [True: 0, False: 0]
1057
0
        target_size = size;
1058
0
    } else {
1059
0
        target_size = m_keypool_size;
1060
0
    }
1061
1062
    // Calculate the new range_end
1063
0
    int32_t new_range_end = std::max(m_wallet_descriptor.next_index + (int32_t)target_size, m_wallet_descriptor.range_end);
1064
1065
    // If the descriptor is not ranged, we actually just want to fill the first cache item
1066
0
    if (!m_wallet_descriptor.descriptor->IsRange()) {
  Branch (1066:9): [True: 0, False: 0]
1067
0
        new_range_end = 1;
1068
0
        m_wallet_descriptor.range_end = 1;
1069
0
        m_wallet_descriptor.range_start = 0;
1070
0
    }
1071
1072
0
    FlatSigningProvider provider;
1073
0
    provider.keys = GetKeys();
1074
1075
0
    uint256 id = GetID();
1076
0
    for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
  Branch (1076:46): [True: 0, False: 0]
1077
0
        FlatSigningProvider out_keys;
1078
0
        std::vector<CScript> scripts_temp;
1079
0
        DescriptorCache temp_cache;
1080
        // Maybe we have a cached xpub and we can expand from the cache first
1081
0
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
  Branch (1081:13): [True: 0, False: 0]
1082
0
            if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
  Branch (1082:17): [True: 0, False: 0]
1083
0
        }
1084
        // Add all of the scriptPubKeys to the scriptPubKey set
1085
0
        new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1086
0
        for (const CScript& script : scripts_temp) {
  Branch (1086:36): [True: 0, False: 0]
1087
0
            m_map_script_pub_keys[script] = i;
1088
0
        }
1089
0
        for (const auto& pk_pair : out_keys.pubkeys) {
  Branch (1089:34): [True: 0, False: 0]
1090
0
            const CPubKey& pubkey = pk_pair.second;
1091
0
            if (m_map_pubkeys.contains(pubkey)) {
  Branch (1091:17): [True: 0, False: 0]
1092
                // We don't need to give an error here.
1093
                // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and its private key
1094
0
                continue;
1095
0
            }
1096
0
            m_map_pubkeys[pubkey] = i;
1097
0
        }
1098
        // Merge and write the cache
1099
0
        DescriptorCache new_items = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
1100
0
        if (!batch.WriteDescriptorCacheItems(id, new_items)) {
  Branch (1100:13): [True: 0, False: 0]
1101
0
            throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
1102
0
        }
1103
0
        m_max_cached_index++;
1104
0
    }
1105
0
    m_wallet_descriptor.range_end = new_range_end;
1106
0
    batch.WriteDescriptor(GetID(), m_wallet_descriptor);
1107
1108
    // By this point, the cache size should be the size of the entire range
1109
0
    assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
  Branch (1109:5): [True: 0, False: 0]
1110
1111
0
    m_storage.TopUpCallback(new_spks, this);
1112
0
    NotifyCanGetAddressesChanged();
1113
0
    return true;
1114
0
}
1115
1116
std::vector<WalletDestination> DescriptorScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
1117
0
{
1118
0
    LOCK(cs_desc_man);
1119
0
    std::vector<WalletDestination> result;
1120
0
    if (IsMine(script)) {
  Branch (1120:9): [True: 0, False: 0]
1121
0
        int32_t index = m_map_script_pub_keys[script];
1122
0
        if (index >= m_wallet_descriptor.next_index) {
  Branch (1122:13): [True: 0, False: 0]
1123
0
            WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
1124
0
            auto out_keys = std::make_unique<FlatSigningProvider>();
1125
0
            std::vector<CScript> scripts_temp;
1126
0
            while (index >= m_wallet_descriptor.next_index) {
  Branch (1126:20): [True: 0, False: 0]
1127
0
                if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
  Branch (1127:21): [True: 0, False: 0]
1128
0
                    throw std::runtime_error(std::string(__func__) + ": Unable to expand descriptor from cache");
1129
0
                }
1130
0
                CTxDestination dest;
1131
0
                ExtractDestination(scripts_temp[0], dest);
1132
0
                result.push_back({dest, std::nullopt});
1133
0
                m_wallet_descriptor.next_index++;
1134
0
            }
1135
0
        }
1136
0
        if (!TopUp()) {
  Branch (1136:13): [True: 0, False: 0]
1137
0
            WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1138
0
        }
1139
0
    }
1140
1141
0
    return result;
1142
0
}
1143
1144
void DescriptorScriptPubKeyMan::AddDescriptorKey(const CKey& key, const CPubKey &pubkey)
1145
0
{
1146
0
    LOCK(cs_desc_man);
1147
0
    WalletBatch batch(m_storage.GetDatabase());
1148
0
    if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
  Branch (1148:9): [True: 0, False: 0]
1149
0
        throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
1150
0
    }
1151
0
}
1152
1153
bool DescriptorScriptPubKeyMan::AddDescriptorKeyWithDB(WalletBatch& batch, const CKey& key, const CPubKey &pubkey)
1154
0
{
1155
0
    AssertLockHeld(cs_desc_man);
1156
0
    assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
  Branch (1156:5): [True: 0, False: 0]
1157
1158
    // Check if provided key already exists
1159
0
    if (m_map_keys.contains(pubkey.GetID()) ||
  Branch (1159:9): [True: 0, False: 0]
  Branch (1159:9): [True: 0, False: 0]
1160
0
        m_map_crypted_keys.contains(pubkey.GetID())) {
  Branch (1160:9): [True: 0, False: 0]
1161
0
        return true;
1162
0
    }
1163
1164
0
    if (m_storage.HasEncryptionKeys()) {
  Branch (1164:9): [True: 0, False: 0]
1165
0
        if (m_storage.IsLocked()) {
  Branch (1165:13): [True: 0, False: 0]
1166
0
            return false;
1167
0
        }
1168
1169
0
        std::vector<unsigned char> crypted_secret;
1170
0
        CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
1171
0
        if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
  Branch (1171:13): [True: 0, False: 0]
1172
0
                return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
1173
0
            })) {
1174
0
            return false;
1175
0
        }
1176
1177
0
        m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1178
0
        return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1179
0
    } else {
1180
0
        m_map_keys[pubkey.GetID()] = key;
1181
0
        return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
1182
0
    }
1183
0
}
1184
1185
void DescriptorScriptPubKeyMan::SetupDescriptorGeneration(WalletBatch& batch, const CExtKey& master_key, OutputType addr_type, bool internal)
1186
0
{
1187
0
    LOCK(cs_desc_man);
1188
0
    Assert(m_storage.IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
1189
0
    Assert(!m_wallet_descriptor.descriptor);
1190
1191
0
    m_wallet_descriptor = GenerateWalletDescriptor(master_key.Neuter(), addr_type, internal);
1192
1193
    // Store the master private key, and descriptor
1194
0
    if (!AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey())) {
  Branch (1194:9): [True: 0, False: 0]
1195
0
        throw std::runtime_error(std::string(__func__) + ": writing descriptor master private key failed");
1196
0
    }
1197
0
    if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
  Branch (1197:9): [True: 0, False: 0]
1198
0
        throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
1199
0
    }
1200
1201
    // Set m_decryption_thoroughly_checked for encrypted wallets
1202
0
    if (m_storage.HasEncryptionKeys()) {
  Branch (1202:9): [True: 0, False: 0]
1203
0
        m_decryption_thoroughly_checked = true;
1204
0
    }
1205
1206
    // TopUp
1207
0
    TopUpWithDB(batch);
1208
1209
0
    m_storage.UnsetBlankWalletFlag(batch);
1210
0
}
1211
1212
bool DescriptorScriptPubKeyMan::IsHDEnabled() const
1213
0
{
1214
0
    LOCK(cs_desc_man);
1215
0
    return m_wallet_descriptor.descriptor->IsRange();
1216
0
}
1217
1218
bool DescriptorScriptPubKeyMan::CanGetAddresses(bool internal) const
1219
0
{
1220
    // We can only give out addresses from descriptors that are single type (not combo), ranged,
1221
    // and either have cached keys or can generate more keys (ignoring encryption)
1222
0
    LOCK(cs_desc_man);
1223
0
    return m_wallet_descriptor.descriptor->IsSingleType() &&
  Branch (1223:12): [True: 0, False: 0]
1224
0
           m_wallet_descriptor.descriptor->IsRange() &&
  Branch (1224:12): [True: 0, False: 0]
1225
0
           (HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end || m_wallet_descriptor.descriptor->CanSelfExpand());
  Branch (1225:13): [True: 0, False: 0]
  Branch (1225:34): [True: 0, False: 0]
  Branch (1225:100): [True: 0, False: 0]
1226
0
}
1227
1228
bool DescriptorScriptPubKeyMan::HavePrivateKeys() const
1229
0
{
1230
0
    LOCK(cs_desc_man);
1231
0
    return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
  Branch (1231:12): [True: 0, False: 0]
  Branch (1231:37): [True: 0, False: 0]
1232
0
}
1233
1234
bool DescriptorScriptPubKeyMan::HaveCryptedKeys() const
1235
0
{
1236
0
    LOCK(cs_desc_man);
1237
0
    return !m_map_crypted_keys.empty();
1238
0
}
1239
1240
unsigned int DescriptorScriptPubKeyMan::GetKeyPoolSize() const
1241
0
{
1242
0
    LOCK(cs_desc_man);
1243
0
    return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
1244
0
}
1245
1246
int64_t DescriptorScriptPubKeyMan::GetTimeFirstKey() const
1247
0
{
1248
0
    LOCK(cs_desc_man);
1249
0
    return m_wallet_descriptor.creation_time;
1250
0
}
1251
1252
std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
1253
0
{
1254
0
    LOCK(cs_desc_man);
1255
1256
    // Find the index of the script
1257
0
    auto it = m_map_script_pub_keys.find(script);
1258
0
    if (it == m_map_script_pub_keys.end()) {
  Branch (1258:9): [True: 0, False: 0]
1259
0
        return nullptr;
1260
0
    }
1261
0
    int32_t index = it->second;
1262
1263
0
    return GetSigningProvider(index, include_private);
1264
0
}
1265
1266
std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
1267
0
{
1268
0
    LOCK(cs_desc_man);
1269
1270
    // Find index of the pubkey
1271
0
    auto it = m_map_pubkeys.find(pubkey);
1272
0
    if (it == m_map_pubkeys.end()) {
  Branch (1272:9): [True: 0, False: 0]
1273
0
        return nullptr;
1274
0
    }
1275
0
    int32_t index = it->second;
1276
1277
    // Always try to get the signing provider with private keys. This function should only be called during signing anyways
1278
0
    std::unique_ptr<FlatSigningProvider> out = GetSigningProvider(index, true);
1279
0
    if (!out->HaveKey(pubkey.GetID())) {
  Branch (1279:9): [True: 0, False: 0]
1280
0
        return nullptr;
1281
0
    }
1282
0
    return out;
1283
0
}
1284
1285
std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
1286
0
{
1287
0
    AssertLockHeld(cs_desc_man);
1288
1289
0
    std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
1290
1291
    // Fetch SigningProvider from cache to avoid re-deriving
1292
0
    auto it = m_map_signing_providers.find(index);
1293
0
    if (it != m_map_signing_providers.end()) {
  Branch (1293:9): [True: 0, False: 0]
1294
0
        out_keys->Merge(FlatSigningProvider{it->second});
1295
0
    } else {
1296
        // Get the scripts, keys, and key origins for this script
1297
0
        std::vector<CScript> scripts_temp;
1298
0
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
  Branch (1298:13): [True: 0, False: 0]
1299
1300
        // Cache SigningProvider so we don't need to re-derive if we need this SigningProvider again
1301
0
        m_map_signing_providers[index] = *out_keys;
1302
0
    }
1303
1304
0
    if (HavePrivateKeys() && include_private) {
  Branch (1304:9): [True: 0, False: 0]
  Branch (1304:30): [True: 0, False: 0]
1305
0
        FlatSigningProvider master_provider;
1306
0
        master_provider.keys = GetKeys();
1307
0
        m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
1308
1309
        // Always include musig_secnonces as this descriptor may have a participant private key
1310
        // but not a musig() descriptor
1311
0
        out_keys->musig2_secnonces = &m_musig2_secnonces;
1312
0
    }
1313
1314
0
    return out_keys;
1315
0
}
1316
1317
std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
1318
0
{
1319
0
    return GetSigningProvider(script, false);
1320
0
}
1321
1322
bool DescriptorScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
1323
0
{
1324
0
    return IsMine(script);
1325
0
}
1326
1327
bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
1328
0
{
1329
0
    std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1330
0
    for (const auto& coin_pair : coins) {
  Branch (1330:32): [True: 0, False: 0]
1331
0
        std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
1332
0
        if (!coin_keys) {
  Branch (1332:13): [True: 0, False: 0]
1333
0
            continue;
1334
0
        }
1335
0
        keys->Merge(std::move(*coin_keys));
1336
0
    }
1337
1338
0
    return ::SignTransaction(tx, keys.get(), coins, {.sighash_type = sighash}, input_errors);
1339
0
}
1340
1341
SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
1342
0
{
1343
0
    std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
1344
0
    if (!keys) {
  Branch (1344:9): [True: 0, False: 0]
1345
0
        return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
1346
0
    }
1347
1348
0
    CKey key;
1349
0
    if (!keys->GetKey(ToKeyID(pkhash), key)) {
  Branch (1349:9): [True: 0, False: 0]
1350
0
        return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
1351
0
    }
1352
1353
0
    if (!MessageSign(key, message, str_sig)) {
  Branch (1353:9): [True: 0, False: 0]
1354
0
        return SigningResult::SIGNING_FAILED;
1355
0
    }
1356
0
    return SigningResult::OK;
1357
0
}
1358
1359
std::optional<PSBTError> DescriptorScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, const common::PSBTFillOptions& options, int* n_signed) const
1360
0
{
1361
0
    if (n_signed) {
  Branch (1361:9): [True: 0, False: 0]
1362
0
        *n_signed = 0;
1363
0
    }
1364
0
    for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
  Branch (1364:30): [True: 0, False: 0]
1365
0
        PSBTInput& input = psbtx.inputs.at(i);
1366
1367
0
        if (PSBTInputSigned(input)) {
  Branch (1367:13): [True: 0, False: 0]
1368
0
            continue;
1369
0
        }
1370
1371
        // Get the scriptPubKey to know which SigningProvider to use
1372
0
        CScript script;
1373
0
        if (!input.witness_utxo.IsNull()) {
  Branch (1373:13): [True: 0, False: 0]
1374
0
            script = input.witness_utxo.scriptPubKey;
1375
0
        } else if (input.non_witness_utxo) {
  Branch (1375:20): [True: 0, False: 0]
1376
0
            if (input.prev_out >= input.non_witness_utxo->vout.size()) {
  Branch (1376:17): [True: 0, False: 0]
1377
0
                return PSBTError::MISSING_INPUTS;
1378
0
            }
1379
0
            script = input.non_witness_utxo->vout[input.prev_out].scriptPubKey;
1380
0
        } else {
1381
            // There's no UTXO so we can just skip this now
1382
0
            continue;
1383
0
        }
1384
1385
0
        std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1386
0
        std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, /*include_private=*/options.sign);
1387
0
        if (script_keys) {
  Branch (1387:13): [True: 0, False: 0]
1388
0
            keys->Merge(std::move(*script_keys));
1389
0
        } else {
1390
            // Maybe there are pubkeys listed that we can sign for
1391
0
            std::vector<CPubKey> pubkeys;
1392
0
            pubkeys.reserve(input.hd_keypaths.size() + 2);
1393
1394
            // ECDSA Pubkeys
1395
0
            for (const auto& [pk, _] : input.hd_keypaths) {
  Branch (1395:38): [True: 0, False: 0]
1396
0
                pubkeys.push_back(pk);
1397
0
            }
1398
1399
            // Taproot output pubkey
1400
0
            std::vector<std::vector<unsigned char>> sols;
1401
0
            if (Solver(script, sols) == TxoutType::WITNESS_V1_TAPROOT) {
  Branch (1401:17): [True: 0, False: 0]
1402
0
                sols[0].insert(sols[0].begin(), 0x02);
1403
0
                pubkeys.emplace_back(sols[0]);
1404
0
                sols[0][0] = 0x03;
1405
0
                pubkeys.emplace_back(sols[0]);
1406
0
            }
1407
1408
            // Taproot pubkeys
1409
0
            for (const auto& pk_pair : input.m_tap_bip32_paths) {
  Branch (1409:38): [True: 0, False: 0]
1410
0
                const XOnlyPubKey& pubkey = pk_pair.first;
1411
0
                for (unsigned char prefix : {0x02, 0x03}) {
  Branch (1411:43): [True: 0, False: 0]
1412
0
                    unsigned char b[33] = {prefix};
1413
0
                    std::copy(pubkey.begin(), pubkey.end(), b + 1);
1414
0
                    CPubKey fullpubkey;
1415
0
                    fullpubkey.Set(b, b + 33);
1416
0
                    pubkeys.push_back(fullpubkey);
1417
0
                }
1418
0
            }
1419
1420
0
            for (const auto& pubkey : pubkeys) {
  Branch (1420:37): [True: 0, False: 0]
1421
0
                std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
1422
0
                if (pk_keys) {
  Branch (1422:21): [True: 0, False: 0]
1423
0
                    keys->Merge(std::move(*pk_keys));
1424
0
                }
1425
0
            }
1426
0
        }
1427
1428
0
        PSBTError res = SignPSBTInput(HidingSigningProvider(keys.get(), /*hide_secret=*/!options.sign, /*hide_origin=*/!options.bip32_derivs), psbtx, i, &txdata, options, /*out_sigdata=*/nullptr);
1429
0
        if (res != PSBTError::OK && res != PSBTError::INCOMPLETE) {
  Branch (1429:13): [True: 0, False: 0]
  Branch (1429:37): [True: 0, False: 0]
1430
0
            return res;
1431
0
        }
1432
1433
0
        bool signed_one = PSBTInputSigned(input);
1434
0
        if (n_signed && (signed_one || !options.sign)) {
  Branch (1434:13): [True: 0, False: 0]
  Branch (1434:26): [True: 0, False: 0]
  Branch (1434:40): [True: 0, False: 0]
1435
            // If sign is false, we assume that we _could_ sign if we get here. This
1436
            // will never have false negatives; it is hard to tell under what i
1437
            // circumstances it could have false positives.
1438
0
            (*n_signed)++;
1439
0
        }
1440
0
    }
1441
1442
    // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
1443
0
    for (unsigned int i = 0; i < psbtx.outputs.size(); ++i) {
  Branch (1443:30): [True: 0, False: 0]
1444
0
        std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.outputs.at(i).script);
1445
0
        if (!keys) {
  Branch (1445:13): [True: 0, False: 0]
1446
0
            continue;
1447
0
        }
1448
0
        UpdatePSBTOutput(HidingSigningProvider(keys.get(), /*hide_secret=*/true, /*hide_origin=*/!options.bip32_derivs), psbtx, i);
1449
0
    }
1450
1451
0
    return {};
1452
0
}
1453
1454
std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
1455
0
{
1456
0
    std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
1457
0
    if (provider) {
  Branch (1457:9): [True: 0, False: 0]
1458
0
        KeyOriginInfo orig;
1459
0
        CKeyID key_id = GetKeyForDestination(*provider, dest);
1460
0
        if (provider->GetKeyOrigin(key_id, orig)) {
  Branch (1460:13): [True: 0, False: 0]
1461
0
            LOCK(cs_desc_man);
1462
0
            std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
1463
0
            meta->key_origin = orig;
1464
0
            meta->has_key_origin = true;
1465
0
            meta->nCreateTime = m_wallet_descriptor.creation_time;
1466
0
            return meta;
1467
0
        }
1468
0
    }
1469
0
    return nullptr;
1470
0
}
1471
1472
uint256 DescriptorScriptPubKeyMan::GetID() const
1473
0
{
1474
0
    LOCK(cs_desc_man);
1475
0
    return m_wallet_descriptor.id;
1476
0
}
1477
1478
void DescriptorScriptPubKeyMan::Load()
1479
0
{
1480
0
    LOCK(cs_desc_man);
1481
0
    std::set<CScript> new_spks;
1482
0
    for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
  Branch (1482:55): [True: 0, False: 0]
1483
0
        FlatSigningProvider out_keys;
1484
0
        std::vector<CScript> scripts_temp;
1485
0
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
  Branch (1485:13): [True: 0, False: 0]
1486
0
            throw std::runtime_error("Error: Unable to expand wallet descriptor from cache");
1487
0
        }
1488
        // Add all of the scriptPubKeys to the scriptPubKey set
1489
0
        new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1490
0
        for (const CScript& script : scripts_temp) {
  Branch (1490:36): [True: 0, False: 0]
1491
0
            if (m_map_script_pub_keys.contains(script)) {
  Branch (1491:17): [True: 0, False: 0]
1492
0
                throw std::runtime_error(strprintf("Error: Already loaded script at index %d as being at index %d", i, m_map_script_pub_keys[script]));
1493
0
            }
1494
0
            m_map_script_pub_keys[script] = i;
1495
0
        }
1496
0
        for (const auto& pk_pair : out_keys.pubkeys) {
  Branch (1496:34): [True: 0, False: 0]
1497
0
            const CPubKey& pubkey = pk_pair.second;
1498
0
            if (m_map_pubkeys.contains(pubkey)) {
  Branch (1498:17): [True: 0, False: 0]
1499
                // We don't need to give an error here.
1500
                // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and its private key
1501
0
                continue;
1502
0
            }
1503
0
            m_map_pubkeys[pubkey] = i;
1504
0
        }
1505
0
        m_max_cached_index++;
1506
0
    }
1507
    // Make sure the wallet knows about our new spks
1508
0
    m_storage.TopUpCallback(new_spks, this);
1509
0
}
1510
1511
bool DescriptorScriptPubKeyMan::HasWalletDescriptor(const WalletDescriptor& desc) const
1512
0
{
1513
0
    LOCK(cs_desc_man);
1514
0
    return !m_wallet_descriptor.id.IsNull() && !desc.id.IsNull() && m_wallet_descriptor.id == desc.id;
  Branch (1514:12): [True: 0, False: 0]
  Branch (1514:48): [True: 0, False: 0]
  Branch (1514:69): [True: 0, False: 0]
1515
0
}
1516
1517
void DescriptorScriptPubKeyMan::WriteDescriptor()
1518
0
{
1519
0
    LOCK(cs_desc_man);
1520
0
    WalletBatch batch(m_storage.GetDatabase());
1521
0
    if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
  Branch (1521:9): [True: 0, False: 0]
1522
0
        throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
1523
0
    }
1524
0
}
1525
1526
WalletDescriptor DescriptorScriptPubKeyMan::GetWalletDescriptor() const
1527
0
{
1528
0
    return m_wallet_descriptor;
1529
0
}
1530
1531
std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
1532
0
{
1533
0
    return GetScriptPubKeys(0);
1534
0
}
1535
1536
std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys(int32_t minimum_index) const
1537
0
{
1538
0
    LOCK(cs_desc_man);
1539
0
    std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
1540
0
    script_pub_keys.reserve(m_map_script_pub_keys.size());
1541
1542
0
    for (auto const& [script_pub_key, index] : m_map_script_pub_keys) {
  Branch (1542:46): [True: 0, False: 0]
1543
0
        if (index >= minimum_index) script_pub_keys.insert(script_pub_key);
  Branch (1543:13): [True: 0, False: 0]
1544
0
    }
1545
0
    return script_pub_keys;
1546
0
}
1547
1548
int32_t DescriptorScriptPubKeyMan::GetEndRange() const
1549
0
{
1550
0
    return m_max_cached_index + 1;
1551
0
}
1552
1553
bool DescriptorScriptPubKeyMan::GetDescriptorString(std::string& out, const bool priv) const
1554
0
{
1555
0
    LOCK(cs_desc_man);
1556
1557
0
    FlatSigningProvider provider;
1558
0
    provider.keys = GetKeys();
1559
1560
0
    if (priv) {
  Branch (1560:9): [True: 0, False: 0]
1561
        // For the private version, always return the master key to avoid
1562
        // exposing child private keys. The risk implications of exposing child
1563
        // private keys together with the parent xpub may be non-obvious for users.
1564
0
        return m_wallet_descriptor.descriptor->ToPrivateString(provider, out);
1565
0
    }
1566
1567
0
    return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
1568
0
}
1569
1570
void DescriptorScriptPubKeyMan::UpgradeDescriptorCache()
1571
0
{
1572
0
    LOCK(cs_desc_man);
1573
0
    if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED)) {
  Branch (1573:9): [True: 0, False: 0]
  Branch (1573:33): [True: 0, False: 0]
1574
0
        return;
1575
0
    }
1576
1577
    // Skip if we have the last hardened xpub cache
1578
0
    if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
  Branch (1578:9): [True: 0, False: 0]
1579
0
        return;
1580
0
    }
1581
1582
    // Expand the descriptor
1583
0
    FlatSigningProvider provider;
1584
0
    provider.keys = GetKeys();
1585
0
    FlatSigningProvider out_keys;
1586
0
    std::vector<CScript> scripts_temp;
1587
0
    DescriptorCache temp_cache;
1588
0
    if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
  Branch (1588:9): [True: 0, False: 0]
1589
0
        throw std::runtime_error("Unable to expand descriptor");
1590
0
    }
1591
1592
    // Cache the last hardened xpubs
1593
0
    DescriptorCache diff = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
1594
0
    if (!WalletBatch(m_storage.GetDatabase()).WriteDescriptorCacheItems(GetID(), diff)) {
  Branch (1594:9): [True: 0, False: 0]
1595
0
        throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
1596
0
    }
1597
0
}
1598
1599
util::Result<void> DescriptorScriptPubKeyMan::UpdateWalletDescriptor(WalletDescriptor& descriptor, const FlatSigningProvider& provider)
1600
0
{
1601
0
    LOCK(cs_desc_man);
1602
0
    std::string error;
1603
0
    if (!CanUpdateToWalletDescriptor(descriptor, error)) {
  Branch (1603:9): [True: 0, False: 0]
1604
0
        return util::Error{Untranslated(std::move(error))};
1605
0
    }
1606
1607
0
    m_map_pubkeys.clear();
1608
0
    m_map_script_pub_keys.clear();
1609
0
    m_max_cached_index = -1;
1610
0
    m_wallet_descriptor = descriptor;
1611
1612
0
    WalletBatch batch(m_storage.GetDatabase());
1613
0
    UpdateWithSigningProvider(batch, provider);
1614
0
    NotifyFirstKeyTimeChanged(this, m_wallet_descriptor.creation_time);
1615
0
    return {};
1616
0
}
1617
1618
void DescriptorScriptPubKeyMan::UpdateWithSigningProvider(WalletBatch& batch, const FlatSigningProvider& signing_provider)
1619
0
{
1620
0
    AssertLockHeld(cs_desc_man);
1621
    // Add the private keys to the descriptor
1622
0
    for (const auto& entry : signing_provider.keys) {
  Branch (1622:28): [True: 0, False: 0]
1623
0
        const CKey& key = entry.second;
1624
0
        if (!AddDescriptorKeyWithDB(batch, key, key.GetPubKey())) {
  Branch (1624:13): [True: 0, False: 0]
1625
0
            throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
1626
0
        }
1627
0
    }
1628
1629
    // Top up key pool, to generate scriptPubKeys
1630
0
    if (!TopUpWithDB(batch)) {
  Branch (1630:9): [True: 0, False: 0]
1631
0
        throw std::runtime_error("Could not top up scriptPubKeys");
1632
0
    }
1633
0
}
1634
1635
bool DescriptorScriptPubKeyMan::CanUpdateToWalletDescriptor(const WalletDescriptor& descriptor, std::string& error)
1636
0
{
1637
0
    LOCK(cs_desc_man);
1638
0
    if (!HasWalletDescriptor(descriptor)) {
  Branch (1638:9): [True: 0, False: 0]
1639
0
        error = "can only update matching descriptor";
1640
0
        return false;
1641
0
    }
1642
1643
0
    if (!descriptor.descriptor->IsRange()) {
  Branch (1643:9): [True: 0, False: 0]
1644
        // Skip range check for non-range descriptors
1645
0
        return true;
1646
0
    }
1647
1648
0
    if (descriptor.range_start > m_wallet_descriptor.range_start ||
  Branch (1648:9): [True: 0, False: 0]
1649
0
        descriptor.range_end < m_wallet_descriptor.range_end) {
  Branch (1649:9): [True: 0, False: 0]
1650
        // Use inclusive range for error
1651
0
        error = strprintf("new range must include current range = [%d,%d]",
1652
0
                          m_wallet_descriptor.range_start,
1653
0
                          m_wallet_descriptor.range_end - 1);
1654
0
        return false;
1655
0
    }
1656
1657
0
    return true;
1658
0
}
1659
} // namespace wallet