Coverage Report

Created: 2026-08-25 19:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/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
105k
{
65
105k
    return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
  Branch (65:12): [True: 37.9k, False: 67.8k]
  Branch (65:51): [True: 26.7k, False: 41.1k]
66
105k
}
67
68
bool HaveKeys(const std::vector<valtype>& pubkeys, const LegacyDataSPKM& keystore)
69
25.2k
{
70
163k
    for (const valtype& pubkey : pubkeys) {
  Branch (70:32): [True: 163k, False: 17.5k]
71
163k
        CKeyID keyID = CPubKey(pubkey).GetID();
72
163k
        if (!keystore.HaveKey(keyID)) return false;
  Branch (72:13): [True: 7.65k, False: 156k]
73
163k
    }
74
17.5k
    return true;
75
25.2k
}
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
400k
{
88
400k
    IsMineResult ret = IsMineResult::NO;
89
90
400k
    std::vector<valtype> vSolutions;
91
400k
    TxoutType whichType = Solver(scriptPubKey, vSolutions);
92
93
400k
    CKeyID keyID;
94
400k
    switch (whichType) {
  Branch (94:13): [True: 0, False: 400k]
95
8.45k
    case TxoutType::NONSTANDARD:
  Branch (95:5): [True: 8.45k, False: 392k]
96
8.57k
    case TxoutType::NULL_DATA:
  Branch (96:5): [True: 117, False: 400k]
97
8.67k
    case TxoutType::WITNESS_UNKNOWN:
  Branch (97:5): [True: 102, False: 400k]
98
8.72k
    case TxoutType::WITNESS_V1_TAPROOT:
  Branch (98:5): [True: 54, False: 400k]
99
8.73k
    case TxoutType::ANCHOR:
  Branch (99:5): [True: 3, False: 400k]
100
8.73k
        break;
101
17.7k
    case TxoutType::PUBKEY:
  Branch (101:5): [True: 17.7k, False: 383k]
102
17.7k
        keyID = CPubKey(vSolutions[0]).GetID();
103
17.7k
        if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
  Branch (103:13): [True: 0, False: 17.7k]
  Branch (103:49): [True: 0, False: 0]
104
0
            return IsMineResult::INVALID;
105
0
        }
106
17.7k
        if (keystore.HaveKey(keyID)) {
  Branch (106:13): [True: 17.6k, False: 114]
107
17.6k
            ret = std::max(ret, IsMineResult::SPENDABLE);
108
17.6k
        }
109
17.7k
        break;
110
43.7k
    case TxoutType::WITNESS_V0_KEYHASH:
  Branch (110:5): [True: 43.7k, False: 357k]
111
43.7k
    {
112
43.7k
        if (sigversion == IsMineSigVersion::WITNESS_V0) {
  Branch (112:13): [True: 0, False: 43.7k]
113
            // P2WPKH inside P2WSH is invalid.
114
0
            return IsMineResult::INVALID;
115
0
        }
116
43.7k
        if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
  Branch (116:13): [True: 18.9k, False: 24.7k]
  Branch (116:13): [True: 2.59k, False: 41.1k]
  Branch (116:52): [True: 2.59k, False: 16.3k]
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
2.59k
            break;
121
2.59k
        }
122
41.1k
        ret = std::max(ret, LegacyWalletIsMineInnerDONOTUSE(keystore, GetScriptForDestination(PKHash(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
123
41.1k
        break;
124
43.7k
    }
125
62.8k
    case TxoutType::PUBKEYHASH:
  Branch (125:5): [True: 62.8k, False: 338k]
126
62.8k
        keyID = CKeyID(uint160(vSolutions[0]));
127
62.8k
        if (!PermitsUncompressed(sigversion)) {
  Branch (127:13): [True: 41.1k, False: 21.7k]
128
41.1k
            CPubKey pubkey;
129
41.1k
            if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
  Branch (129:17): [True: 40.3k, False: 741]
  Branch (129:54): [True: 57, False: 40.3k]
130
57
                return IsMineResult::INVALID;
131
57
            }
132
41.1k
        }
133
62.7k
        if (keystore.HaveKey(keyID)) {
  Branch (133:13): [True: 58.9k, False: 3.84k]
134
58.9k
            ret = std::max(ret, IsMineResult::SPENDABLE);
135
58.9k
        }
136
62.7k
        break;
137
157k
    case TxoutType::SCRIPTHASH:
  Branch (137:5): [True: 157k, False: 243k]
138
157k
    {
139
157k
        if (sigversion != IsMineSigVersion::TOP) {
  Branch (139:13): [True: 2.72k, False: 154k]
140
            // P2SH inside P2WSH or P2SH is invalid.
141
2.72k
            return IsMineResult::INVALID;
142
2.72k
        }
143
154k
        CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
144
154k
        CScript subscript;
145
154k
        if (keystore.GetCScript(scriptID, subscript)) {
  Branch (145:13): [True: 68.6k, False: 86.1k]
146
68.6k
            ret = std::max(ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
  Branch (146:33): [True: 60.0k, False: 8.65k]
147
68.6k
        }
148
154k
        break;
149
157k
    }
150
75.2k
    case TxoutType::WITNESS_V0_SCRIPTHASH:
  Branch (150:5): [True: 75.2k, False: 325k]
151
75.2k
    {
152
75.2k
        if (sigversion == IsMineSigVersion::WITNESS_V0) {
  Branch (152:13): [True: 0, False: 75.2k]
153
            // P2WSH inside P2WSH is invalid.
154
0
            return IsMineResult::INVALID;
155
0
        }
156
75.2k
        if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
  Branch (156:13): [True: 75.2k, False: 60]
  Branch (156:13): [True: 75.1k, False: 150]
  Branch (156:52): [True: 75.1k, False: 90]
157
75.1k
            break;
158
75.1k
        }
159
150
        CScriptID scriptID{RIPEMD160(vSolutions[0])};
160
150
        CScript subscript;
161
150
        if (keystore.GetCScript(scriptID, subscript)) {
  Branch (161:13): [True: 0, False: 150]
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
150
        break;
165
75.2k
    }
166
167
34.9k
    case TxoutType::MULTISIG:
  Branch (167:5): [True: 34.9k, False: 365k]
168
34.9k
    {
169
        // Never treat bare multisig outputs as ours (they can still be made watchonly-though)
170
34.9k
        if (sigversion == IsMineSigVersion::TOP) {
  Branch (170:13): [True: 9.69k, False: 25.2k]
171
9.69k
            break;
172
9.69k
        }
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
25.2k
        std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
180
25.2k
        if (!PermitsUncompressed(sigversion)) {
  Branch (180:13): [True: 0, False: 25.2k]
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
25.2k
        if (HaveKeys(keys, keystore)) {
  Branch (187:13): [True: 17.5k, False: 7.65k]
188
17.5k
            ret = std::max(ret, IsMineResult::SPENDABLE);
189
17.5k
        }
190
25.2k
        break;
191
25.2k
    }
192
400k
    } // no default case, so the compiler can warn about missing cases
193
194
398k
    if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
  Branch (194:9): [True: 209k, False: 188k]
  Branch (194:36): [True: 4.30k, False: 205k]
195
4.30k
        ret = std::max(ret, IsMineResult::WATCH_ONLY);
196
4.30k
    }
197
398k
    return ret;
198
400k
}
199
200
} // namespace
201
202
bool LegacyDataSPKM::IsMine(const CScript& script) const
203
237k
{
204
237k
    switch (LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP)) {
  Branch (204:13): [True: 0, False: 237k]
205
2.77k
    case IsMineResult::INVALID:
  Branch (205:5): [True: 2.77k, False: 234k]
206
138k
    case IsMineResult::NO:
  Branch (206:5): [True: 136k, False: 101k]
207
138k
        return false;
208
4.30k
    case IsMineResult::WATCH_ONLY:
  Branch (208:5): [True: 4.30k, False: 232k]
209
98.4k
    case IsMineResult::SPENDABLE:
  Branch (209:5): [True: 94.1k, False: 143k]
210
98.4k
        return true;
211
237k
    }
212
237k
    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
25.6k
{
257
25.6k
    return std::make_unique<LegacySigningProvider>(*this);
258
25.6k
}
259
260
bool LegacyDataSPKM::CanProvide(const CScript& script, SignatureData& sigdata)
261
62.4k
{
262
62.4k
    IsMineResult ismine = LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
263
62.4k
    if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
  Branch (263:9): [True: 8.65k, False: 53.8k]
  Branch (263:46): [True: 0, False: 53.8k]
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
8.65k
        return true;
268
53.8k
    } else {
269
        // If, given the stuff in sigdata, we could make a valid signature, then we can provide for this script
270
53.8k
        ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
271
53.8k
        if (!sigdata.signatures.empty()) {
  Branch (271:13): [True: 10.0k, False: 43.7k]
272
            // If we could make signatures, make sure we have a private key to actually make a signature
273
10.0k
            bool has_privkeys = false;
274
15.5k
            for (const auto& key_sig_pair : sigdata.signatures) {
  Branch (274:43): [True: 15.5k, False: 10.0k]
275
15.5k
                has_privkeys |= HaveKey(key_sig_pair.first);
276
15.5k
            }
277
10.0k
            return has_privkeys;
278
10.0k
        }
279
43.7k
        return false;
280
53.8k
    }
281
62.4k
}
282
283
bool LegacyDataSPKM::LoadKey(const CKey& key, const CPubKey &pubkey)
284
10.2k
{
285
10.2k
    return AddKeyPubKeyInner(key, pubkey);
286
10.2k
}
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
10.2k
{
317
10.2k
    LOCK(cs_KeyStore);
318
10.2k
    return FillableSigningProvider::AddKeyPubKey(key, pubkey);
319
10.2k
}
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
209k
{
343
209k
    LOCK(cs_KeyStore);
344
209k
    return setWatchOnly.contains(dest);
345
209k
}
346
347
bool LegacyDataSPKM::LoadWatchOnly(const CScript &dest)
348
2.15k
{
349
2.15k
    return AddWatchOnlyInMem(dest);
350
2.15k
}
351
352
static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
353
2.15k
{
354
2.15k
    std::vector<std::vector<unsigned char>> solutions;
355
2.15k
    return Solver(dest, solutions) == TxoutType::PUBKEY &&
  Branch (355:12): [True: 0, False: 2.15k]
356
2.15k
        (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
  Branch (356:9): [True: 0, False: 0]
357
2.15k
}
358
359
bool LegacyDataSPKM::AddWatchOnlyInMem(const CScript &dest)
360
2.15k
{
361
2.15k
    LOCK(cs_KeyStore);
362
2.15k
    setWatchOnly.insert(dest);
363
2.15k
    CPubKey pubKey;
364
2.15k
    if (ExtractPubKey(dest, pubKey)) {
  Branch (364:9): [True: 0, False: 2.15k]
365
0
        mapWatchKeys[pubKey.GetID()] = pubKey;
366
0
        ImplicitlyLearnRelatedKeyScripts(pubKey);
367
0
    }
368
2.15k
    return true;
369
2.15k
}
370
371
void LegacyDataSPKM::LoadHDChain(const CHDChain& chain)
372
688
{
373
688
    LOCK(cs_KeyStore);
374
688
    m_hd_chain = chain;
375
688
}
376
377
void LegacyDataSPKM::AddInactiveHDChain(const CHDChain& chain)
378
680
{
379
680
    LOCK(cs_KeyStore);
380
680
    assert(!chain.seed_id.IsNull());
  Branch (380:5): [True: 680, False: 0]
381
680
    m_inactive_hd_chains[chain.seed_id] = chain;
382
680
}
383
384
bool LegacyDataSPKM::HaveKey(const CKeyID &address) const
385
259k
{
386
259k
    LOCK(cs_KeyStore);
387
259k
    if (!m_storage.HasEncryptionKeys()) {
  Branch (387:9): [True: 259k, False: 0]
388
259k
        return FillableSigningProvider::HaveKey(address);
389
259k
    }
390
0
    return mapCryptedKeys.contains(address);
391
259k
}
392
393
bool LegacyDataSPKM::GetKey(const CKeyID &address, CKey& keyOut) const
394
108k
{
395
108k
    LOCK(cs_KeyStore);
396
108k
    if (!m_storage.HasEncryptionKeys()) {
  Branch (396:9): [True: 108k, False: 0]
397
108k
        return FillableSigningProvider::GetKey(address, keyOut);
398
108k
    }
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
170k
{
414
170k
    CKeyMetadata meta;
415
170k
    {
416
170k
        LOCK(cs_KeyStore);
417
170k
        auto it = mapKeyMetadata.find(keyID);
418
170k
        if (it == mapKeyMetadata.end()) {
  Branch (418:13): [True: 170k, False: 0]
419
170k
            return false;
420
170k
        }
421
0
        meta = it->second;
422
0
    }
423
0
    if (meta.has_key_origin) {
  Branch (423:9): [True: 0, False: 0]
424
0
        info.fingerprint = meta.key_origin.fingerprint;
425
0
        info.path = meta.key_origin.path;
426
0
    } else { // Single pubkeys get the master fingerprint of themselves
427
0
        info.fingerprint = keyID.fingerprint();
428
0
    }
429
0
    return true;
430
170k
}
431
432
bool LegacyDataSPKM::GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
433
3.80k
{
434
3.80k
    LOCK(cs_KeyStore);
435
3.80k
    WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
436
3.80k
    if (it != mapWatchKeys.end()) {
  Branch (436:9): [True: 0, False: 3.80k]
437
0
        pubkey_out = it->second;
438
0
        return true;
439
0
    }
440
3.80k
    return false;
441
3.80k
}
442
443
bool LegacyDataSPKM::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
444
45.1k
{
445
45.1k
    LOCK(cs_KeyStore);
446
45.1k
    if (!m_storage.HasEncryptionKeys()) {
  Branch (446:9): [True: 45.1k, False: 0]
447
45.1k
        if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
  Branch (447:13): [True: 3.80k, False: 41.3k]
448
3.80k
            return GetWatchPubKey(address, vchPubKeyOut);
449
3.80k
        }
450
41.3k
        return true;
451
45.1k
    }
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
4.30k
{
465
4.30k
    LOCK(cs_KeyStore);
466
4.30k
    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
17.6k
    const auto& add_pubkey = [&candidate_spks](const CPubKey& pub) -> void {
470
17.6k
        candidate_spks.insert(GetScriptForRawPubKey(pub));
471
17.6k
        candidate_spks.insert(GetScriptForDestination(PKHash(pub)));
472
473
17.6k
        CScript wpkh = GetScriptForDestination(WitnessV0KeyHash(pub));
474
17.6k
        candidate_spks.insert(wpkh);
475
17.6k
        candidate_spks.insert(GetScriptForDestination(ScriptHash(wpkh)));
476
17.6k
    };
477
17.6k
    for (const auto& [_, key] : mapKeys) {
  Branch (477:31): [True: 17.6k, False: 4.30k]
478
17.6k
        add_pubkey(key.GetPubKey());
479
17.6k
    }
480
4.30k
    for (const auto& [_, ckeypair] : mapCryptedKeys) {
  Branch (480:36): [True: 0, False: 4.30k]
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
50.0k
    const auto& add_script = [&candidate_spks](const CScript& script) -> void {
489
50.0k
        candidate_spks.insert(script);
490
50.0k
        candidate_spks.insert(GetScriptForDestination(ScriptHash(script)));
491
492
50.0k
        CScript wsh = GetScriptForDestination(WitnessV0ScriptHash(script));
493
50.0k
        candidate_spks.insert(wsh);
494
50.0k
        candidate_spks.insert(GetScriptForDestination(ScriptHash(wsh)));
495
50.0k
    };
496
45.7k
    for (const auto& [_, script] : mapScripts) {
  Branch (496:34): [True: 45.7k, False: 4.30k]
497
45.7k
        add_script(script);
498
45.7k
    }
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
4.30k
    for (const auto& script : setWatchOnly) {
  Branch (502:29): [True: 4.30k, False: 4.30k]
503
4.30k
        add_script(script);
504
4.30k
    }
505
506
4.30k
    return candidate_spks;
507
4.30k
}
508
509
std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetScriptPubKeys() const
510
2.15k
{
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
2.15k
    std::unordered_set<CScript, SaltedSipHasher> spks;
515
118k
    for (const CScript& script : GetCandidateScriptPubKeys()) {
  Branch (515:32): [True: 118k, False: 2.15k]
516
118k
        if (IsMine(script)) {
  Branch (516:13): [True: 42.0k, False: 76.3k]
517
42.0k
            spks.insert(script);
518
42.0k
        }
519
118k
    }
520
521
2.15k
    return spks;
522
2.15k
}
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
2.15k
{
536
2.15k
    LOCK(cs_KeyStore);
537
2.15k
    if (m_storage.IsLocked()) {
  Branch (537:9): [True: 0, False: 2.15k]
538
0
        return std::nullopt;
539
0
    }
540
541
2.15k
    MigrationData out;
542
543
2.15k
    std::unordered_set<CScript, SaltedSipHasher> spks{GetScriptPubKeys()};
544
545
    // Get all key ids
546
2.15k
    std::set<CKeyID> keyids;
547
8.82k
    for (const auto& key_pair : mapKeys) {
  Branch (547:31): [True: 8.82k, False: 2.15k]
548
8.82k
        keyids.insert(key_pair.first);
549
8.82k
    }
550
2.15k
    for (const auto& key_pair : mapCryptedKeys) {
  Branch (550:31): [True: 0, False: 2.15k]
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
10.9k
    for (auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
  Branch (556:42): [True: 8.82k, False: 2.15k]
557
8.82k
        const CKeyID& keyid = *keyid_it;
558
8.82k
        const auto& it = mapKeyMetadata.find(keyid);
559
8.82k
        if (it != mapKeyMetadata.end()) {
  Branch (559:13): [True: 0, False: 8.82k]
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
8.82k
        keyid_it++;
571
8.82k
    }
572
573
2.15k
    WalletBatch batch(m_storage.GetDatabase());
574
2.15k
    if (!batch.TxnBegin()) {
  Branch (574:9): [True: 0, False: 2.15k]
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
8.82k
    for (const CKeyID& keyid : keyids) {
  Branch (580:30): [True: 8.82k, False: 2.15k]
581
8.82k
        CKey key;
582
8.82k
        if (!GetKey(keyid, key)) {
  Branch (582:13): [True: 0, False: 8.82k]
583
0
            assert(false);
  Branch (583:13): [Folded - Ignored]
584
0
        }
585
586
        // Get birthdate from key meta
587
8.82k
        uint64_t creation_time = 0;
588
8.82k
        const auto& it = mapKeyMetadata.find(keyid);
589
8.82k
        if (it != mapKeyMetadata.end()) {
  Branch (589:13): [True: 0, False: 8.82k]
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
8.82k
        KeyOriginInfo info;
596
8.82k
        bool has_info = GetKeyOrigin(keyid, info);
597
8.82k
        std::string origin_str = has_info ? "[" + HexStr(info.fingerprint) + FormatHDKeypath(info.path) + "]" : "";
  Branch (597:34): [True: 0, False: 8.82k]
598
599
        // Construct the combo descriptor
600
8.82k
        std::string desc_str = "combo(" + origin_str + HexStr(key.GetPubKey()) + ")";
601
8.82k
        FlatSigningProvider provider;
602
8.82k
        std::string error;
603
8.82k
        std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, provider, error, false);
604
8.82k
        CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
605
8.82k
        WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
606
607
        // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
608
8.82k
        provider.keys.emplace(key.GetPubKey().GetID(), key);
609
8.82k
        auto desc_spk_man = DescriptorScriptPubKeyMan::CreateFromMigration(m_storage, batch, w_desc, /*keypool_size=*/0, provider);
610
8.82k
        auto desc_spks = desc_spk_man->GetScriptPubKeys();
611
612
        // Remove the scriptPubKeys from our current set
613
33.7k
        for (const CScript& spk : desc_spks) {
  Branch (613:33): [True: 33.7k, False: 8.82k]
614
33.7k
            size_t erased = spks.erase(spk);
615
33.7k
            assert(erased == 1);
  Branch (615:13): [True: 33.7k, False: 0]
616
33.7k
            assert(IsMine(spk));
  Branch (616:13): [True: 33.7k, False: 0]
617
33.7k
        }
618
619
8.82k
        out.desc_spkms.push_back(std::move(desc_spk_man));
620
8.82k
    }
621
622
    // Handle HD keys by using the CHDChains
623
2.15k
    std::set<CHDChain> chains;
624
2.15k
    chains.insert(m_hd_chain);
625
2.15k
    for (const auto& chain_pair : m_inactive_hd_chains) {
  Branch (625:33): [True: 663, False: 2.15k]
626
663
        chains.insert(chain_pair.second);
627
663
    }
628
629
2.15k
    bool can_support_hd_split_feature = m_hd_chain.nVersion >= CHDChain::VERSION_HD_CHAIN_SPLIT;
630
631
2.15k
    std::set<CExtPubKey> master_xpubs;
632
2.56k
    for (const CHDChain& chain : chains) {
  Branch (632:32): [True: 2.56k, False: 2.15k]
633
2.56k
        if (chain.seed_id.IsNull()) continue;
  Branch (633:13): [True: 1.47k, False: 1.08k]
634
635
        // Get the master xprv
636
1.08k
        CKey seed_key;
637
1.08k
        if (!GetKey(chain.seed_id, seed_key)) {
  Branch (637:13): [True: 0, False: 1.08k]
638
0
            assert(false);
  Branch (638:13): [Folded - Ignored]
639
0
        }
640
1.08k
        CExtKey master_key;
641
1.08k
        master_key.SetSeed(seed_key);
642
643
        // Get the xpub and verify that we haven't already seen this xpub before
644
1.08k
        CExtPubKey master_xpub = master_key.Neuter();
645
1.08k
        const auto& [_, inserted] = master_xpubs.insert(master_xpub);
646
1.08k
        if (!inserted) continue;
  Branch (646:13): [True: 2, False: 1.08k]
647
648
3.25k
        for (int i = 0; i < 2; ++i) {
  Branch (648:25): [True: 2.17k, False: 1.08k]
649
            // Skip if doing internal chain and split chain is not supported
650
2.17k
            if (i == 1 && !can_support_hd_split_feature) {
  Branch (650:17): [True: 1.08k, False: 1.08k]
  Branch (650:27): [True: 117, False: 968]
651
117
                continue;
652
117
            }
653
654
            // Make the combo descriptor
655
2.05k
            std::string xpub = EncodeExtPubKey(master_key.Neuter());
656
2.05k
            std::string desc_str = "combo(" + xpub + "/0h/" + ToString(i) + "h/*h)";
657
2.05k
            FlatSigningProvider provider;
658
2.05k
            std::string error;
659
2.05k
            std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, provider, error, false);
660
2.05k
            CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
661
2.05k
            uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
  Branch (661:48): [True: 968, False: 1.08k]
662
2.05k
            WalletDescriptor w_desc(std::move(descs.at(0)), 0, 0, chain_counter, 0);
663
664
            // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
665
2.05k
            provider.keys.emplace(master_key.key.GetPubKey().GetID(), master_key.key);
666
2.05k
            auto desc_spk_man = DescriptorScriptPubKeyMan::CreateFromMigration(m_storage, batch, w_desc, /*keypool_size=*/0, provider);
667
2.05k
            auto desc_spks = desc_spk_man->GetScriptPubKeys();
668
669
            // Remove the scriptPubKeys from our current set
670
2.05k
            for (const CScript& spk : desc_spks) {
  Branch (670:37): [True: 0, False: 2.05k]
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
2.05k
            out.desc_spkms.push_back(std::move(desc_spk_man));
677
2.05k
        }
678
1.08k
    }
679
    // Add the current master seed to the migration data
680
2.15k
    if (!m_hd_chain.seed_id.IsNull()) {
  Branch (680:9): [True: 674, False: 1.47k]
681
674
        CKey seed_key;
682
674
        if (!GetKey(m_hd_chain.seed_id, seed_key)) {
  Branch (682:13): [True: 0, False: 674]
683
0
            assert(false);
  Branch (683:13): [Folded - Ignored]
684
0
        }
685
674
        out.master_key.SetSeed(seed_key);
686
674
    }
687
688
    // Handle the rest of the scriptPubKeys which must be imports and may not have all info
689
10.4k
    for (auto it = spks.begin(); it != spks.end();) {
  Branch (689:34): [True: 8.33k, False: 2.15k]
690
8.33k
        const CScript& spk = *it;
691
692
        // Get birthdate from script meta
693
8.33k
        uint64_t creation_time = 0;
694
8.33k
        const auto& mit = m_script_metadata.find(CScriptID(spk));
695
8.33k
        if (mit != m_script_metadata.end()) {
  Branch (695:13): [True: 0, False: 8.33k]
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
8.33k
        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
8.33k
        {
705
8.33k
            std::string desc_str = desc->ToString();
706
8.33k
            FlatSigningProvider parsed_keys;
707
8.33k
            std::string parse_error;
708
8.33k
            std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error);
709
8.33k
            if (parsed_descs.empty()) {
  Branch (709:17): [True: 0, False: 8.33k]
710
                // Remove this scriptPubKey from the set
711
0
                it = spks.erase(it);
712
0
                continue;
713
0
            }
714
8.33k
        }
715
716
        // Get the private keys for this descriptor
717
8.33k
        std::vector<CScript> scripts;
718
8.33k
        FlatSigningProvider keys;
719
8.33k
        if (!desc->Expand(0, DUMMY_SIGNING_PROVIDER, scripts, keys)) {
  Branch (719:13): [True: 0, False: 8.33k]
720
0
            assert(false);
  Branch (720:13): [Folded - Ignored]
721
0
        }
722
8.33k
        std::set<CKeyID> privkeyids;
723
8.33k
        for (const auto& key_orig_pair : keys.origins) {
  Branch (723:40): [True: 7.42k, False: 8.33k]
724
7.42k
            privkeyids.insert(key_orig_pair.first);
725
7.42k
        }
726
727
8.33k
        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
8.33k
        if (!desc->HavePrivateKeys(*this) && !m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
  Branch (731:13): [True: 2.15k, False: 6.18k]
  Branch (731:46): [True: 2.15k, False: 0]
732
2.15k
            out.watch_descs.emplace_back(desc->ToString(), creation_time);
733
734
            // Get the scriptPubKeys without writing this to the wallet
735
2.15k
            FlatSigningProvider provider;
736
2.15k
            desc->Expand(0, provider, desc_spks, provider);
737
6.18k
        } else {
738
            // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
739
7.42k
            for (const auto& keyid : privkeyids) {
  Branch (739:36): [True: 7.42k, False: 6.18k]
740
7.42k
                CKey key;
741
7.42k
                if (!GetKey(keyid, key)) {
  Branch (741:21): [True: 0, False: 7.42k]
742
0
                    continue;
743
0
                }
744
7.42k
                keys.keys.emplace(key.GetPubKey().GetID(), key);
745
7.42k
            }
746
6.18k
            WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
747
6.18k
            auto desc_spk_man = DescriptorScriptPubKeyMan::CreateFromMigration(m_storage, batch, w_desc, /*keypool_size=*/0, keys);
748
6.18k
            auto desc_spks_set = desc_spk_man->GetScriptPubKeys();
749
6.18k
            desc_spks.insert(desc_spks.end(), desc_spks_set.begin(), desc_spks_set.end());
750
751
6.18k
            out.desc_spkms.push_back(std::move(desc_spk_man));
752
6.18k
        }
753
754
        // Remove the scriptPubKeys from our current set
755
8.33k
        for (const CScript& desc_spk : desc_spks) {
  Branch (755:38): [True: 8.33k, False: 8.33k]
756
8.33k
            auto del_it = spks.find(desc_spk);
757
8.33k
            assert(del_it != spks.end());
  Branch (757:13): [True: 8.33k, False: 0]
758
8.33k
            assert(IsMine(desc_spk));
  Branch (758:13): [True: 8.33k, False: 0]
759
8.33k
            it = spks.erase(del_it);
760
8.33k
        }
761
8.33k
    }
762
763
    // Make sure that we have accounted for all scriptPubKeys
764
2.15k
    if (!Assume(spks.empty())) {
  Branch (764:9): [True: 0, False: 2.15k]
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
118k
    for (const CScript& script : GetCandidateScriptPubKeys()) {
  Branch (774:32): [True: 118k, False: 2.15k]
775
        // Since we only care about P2SH, P2WSH, and P2SH-P2WSH, filter out any scripts that are not those
776
118k
        if (!script.IsPayToScriptHash() && !script.IsPayToWitnessScriptHash()) {
  Branch (776:13): [True: 66.7k, False: 51.6k]
  Branch (776:44): [True: 41.7k, False: 25.0k]
777
41.7k
            continue;
778
41.7k
        }
779
76.7k
        if (IsMine(script)) {
  Branch (779:13): [True: 14.2k, False: 62.4k]
780
14.2k
            continue;
781
14.2k
        }
782
62.4k
        SignatureData dummy_sigdata;
783
62.4k
        if (!CanProvide(script, dummy_sigdata)) {
  Branch (783:13): [True: 45.1k, False: 17.3k]
784
45.1k
            continue;
785
45.1k
        }
786
787
        // Get birthdate from script meta
788
17.3k
        uint64_t creation_time = 0;
789
17.3k
        const auto& it = m_script_metadata.find(CScriptID(script));
790
17.3k
        if (it != m_script_metadata.end()) {
  Branch (790:13): [True: 0, False: 17.3k]
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
17.3k
        std::unique_ptr<Descriptor> desc = InferDescriptor(script, *GetSolvingProvider(script));
796
17.3k
        if (!desc->IsSolvable()) {
  Branch (796:13): [True: 6.16k, False: 11.1k]
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
6.16k
            continue;
800
6.16k
        }
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
11.1k
        {
805
11.1k
            std::string desc_str = desc->ToString();
806
11.1k
            FlatSigningProvider parsed_keys;
807
11.1k
            std::string parse_error;
808
11.1k
            std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error, false);
809
11.1k
            if (parsed_descs.empty()) {
  Branch (809:17): [True: 25, False: 11.1k]
810
25
                continue;
811
25
            }
812
11.1k
        }
813
814
11.1k
        out.solvable_descs.emplace_back(desc->ToString(), creation_time);
815
11.1k
    }
816
817
    // Finalize transaction
818
2.15k
    if (!batch.TxnCommit()) {
  Branch (818:9): [True: 0, False: 2.15k]
819
0
        LogWarning("Error generating descriptors for migration, cannot commit db transaction");
820
0
        return std::nullopt;
821
0
    }
822
823
2.15k
    return out;
824
2.15k
}
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
29.2k
{
834
29.2k
    auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, descriptor, keypool_size));
835
29.2k
    LOCK(spkm->cs_desc_man);
836
29.2k
    WalletBatch batch(storage.GetDatabase());
837
29.2k
    spkm->UpdateWithSigningProvider(batch, provider);
838
29.2k
    return spkm;
839
29.2k
}
840
841
std::unique_ptr<DescriptorScriptPubKeyMan> DescriptorScriptPubKeyMan::CreateFromMigration(WalletStorage& storage, WalletBatch& batch, WalletDescriptor& descriptor, int64_t keypool_size, const FlatSigningProvider& provider)
842
17.0k
{
843
17.0k
    auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, descriptor, keypool_size));
844
17.0k
    LOCK(spkm->cs_desc_man);
845
17.0k
    spkm->UpdateWithSigningProvider(batch, provider);
846
17.0k
    return spkm;
847
17.0k
}
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
void DescriptorScriptPubKeyMan::IncIndex()
875
283k
{
876
283k
    AssertLockHeld(cs_desc_man);
877
878
283k
    const auto old_can = CanGetAddresses();
879
283k
    m_wallet_descriptor.IncNext();
880
283k
    const auto new_can = CanGetAddresses();
881
283k
    if (old_can != new_can) {
  Branch (881:9): [True: 0, False: 283k]
882
0
        NotifyCanGetAddressesChanged();
883
0
    }
884
283k
}
885
886
void DescriptorScriptPubKeyMan::DecIndex()
887
429
{
888
429
    AssertLockHeld(cs_desc_man);
889
890
429
    const auto old_can = CanGetAddresses();
891
429
    m_wallet_descriptor.DecNext();
892
429
    const auto new_can = CanGetAddresses();
893
429
    if (old_can != new_can) {
  Branch (893:9): [True: 0, False: 429]
894
0
        NotifyCanGetAddressesChanged();
895
0
    }
896
429
}
897
898
void DescriptorScriptPubKeyMan::SetRangeEnd(int32_t end)
899
332k
{
900
332k
    AssertLockHeld(cs_desc_man);
901
902
332k
    const auto old_can = CanGetAddresses();
903
332k
    m_wallet_descriptor.SetEnd(end);
904
332k
    const auto new_can = CanGetAddresses();
905
332k
    if (old_can != new_can) {
  Branch (905:9): [True: 0, False: 332k]
906
0
        NotifyCanGetAddressesChanged();
907
0
    }
908
332k
}
909
910
util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetNewDestination(const OutputType type)
911
283k
{
912
    // Returns true if this descriptor supports getting new addresses. Conditions where we may be unable to fetch them (e.g. locked) are caught later
913
283k
    if (!CanGetAddresses()) {
  Branch (913:9): [True: 1.27k, False: 282k]
914
1.27k
        return util::Error{_("No addresses available")};
915
1.27k
    }
916
282k
    {
917
282k
        LOCK(cs_desc_man);
918
282k
        assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
  Branch (918:9): [True: 282k, False: 0]
919
282k
        std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
920
282k
        assert(desc_addr_type);
  Branch (920:9): [True: 282k, False: 0]
921
282k
        if (type != *desc_addr_type) {
  Branch (921:13): [True: 0, False: 282k]
922
0
            throw std::runtime_error(std::string(__func__) + ": Types are inconsistent. Stored type does not match type of newly generated address");
923
0
        }
924
925
282k
        TopUp();
926
927
        // Get the scriptPubKey from the descriptor
928
282k
        FlatSigningProvider out_keys;
929
282k
        std::vector<CScript> scripts_temp;
930
282k
        if (m_wallet_descriptor.GetEnd() <= m_max_cached_index && !TopUp(1)) {
  Branch (930:13): [True: 0, False: 282k]
  Branch (930:67): [True: 0, False: 0]
931
            // We can't generate anymore keys
932
0
            return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
933
0
        }
934
282k
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.GetNext(), m_wallet_descriptor.cache, scripts_temp, out_keys)) {
  Branch (934:13): [True: 0, False: 282k]
935
            // We can't generate anymore keys
936
0
            return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
937
0
        }
938
939
282k
        CTxDestination dest;
940
282k
        if (!ExtractDestination(scripts_temp[0], dest)) {
  Branch (940:13): [True: 0, False: 282k]
941
0
            return util::Error{_("Error: Cannot extract destination from the generated scriptpubkey")}; // shouldn't happen
942
0
        }
943
282k
        IncIndex();
944
282k
        WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
945
282k
        return dest;
946
282k
    }
947
282k
}
948
949
bool DescriptorScriptPubKeyMan::IsMine(const CScript& script) const
950
663k
{
951
663k
    LOCK(cs_desc_man);
952
663k
    return m_map_script_pub_keys.contains(script);
953
663k
}
954
955
bool DescriptorScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key)
956
0
{
957
0
    LOCK(cs_desc_man);
958
0
    if (!m_map_keys.empty()) {
  Branch (958:9): [True: 0, False: 0]
959
0
        return false;
960
0
    }
961
962
0
    bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
963
0
    bool keyFail = false;
964
0
    for (const auto& mi : m_map_crypted_keys) {
  Branch (964:25): [True: 0, False: 0]
965
0
        const CPubKey &pubkey = mi.second.first;
966
0
        const std::vector<unsigned char> &crypted_secret = mi.second.second;
967
0
        CKey key;
968
0
        if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
  Branch (968:13): [True: 0, False: 0]
969
0
            keyFail = true;
970
0
            break;
971
0
        }
972
0
        keyPass = true;
973
0
        if (m_decryption_thoroughly_checked)
  Branch (973:13): [True: 0, False: 0]
974
0
            break;
975
0
    }
976
0
    if (keyPass && keyFail) {
  Branch (976:9): [True: 0, False: 0]
  Branch (976:20): [True: 0, False: 0]
977
0
        LogWarning("The wallet is probably corrupted: Some keys decrypt but not all.");
978
0
        throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
979
0
    }
980
0
    if (keyFail || !keyPass) {
  Branch (980:9): [True: 0, False: 0]
  Branch (980:20): [True: 0, False: 0]
981
0
        return false;
982
0
    }
983
0
    m_decryption_thoroughly_checked = true;
984
0
    return true;
985
0
}
986
987
bool DescriptorScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
988
0
{
989
0
    LOCK(cs_desc_man);
990
0
    if (!m_map_crypted_keys.empty()) {
  Branch (990:9): [True: 0, False: 0]
991
0
        return false;
992
0
    }
993
994
0
    for (const KeyMap::value_type& key_in : m_map_keys)
  Branch (994:43): [True: 0, False: 0]
995
0
    {
996
0
        const CKey &key = key_in.second;
997
0
        CPubKey pubkey = key.GetPubKey();
998
0
        CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
999
0
        std::vector<unsigned char> crypted_secret;
1000
0
        if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
  Branch (1000:13): [True: 0, False: 0]
1001
0
            return false;
1002
0
        }
1003
0
        m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1004
0
        batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1005
0
    }
1006
0
    m_map_keys.clear();
1007
0
    return true;
1008
0
}
1009
1010
util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, int64_t& index)
1011
63.0k
{
1012
63.0k
    LOCK(cs_desc_man);
1013
63.0k
    auto op_dest = GetNewDestination(type);
1014
63.0k
    index = m_wallet_descriptor.GetNext() - 1;
1015
63.0k
    return op_dest;
1016
63.0k
}
1017
1018
void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
1019
429
{
1020
429
    LOCK(cs_desc_man);
1021
    // Only return when the index was the most recent
1022
429
    if (m_wallet_descriptor.GetNext() - 1 == index) {
  Branch (1022:9): [True: 429, False: 0]
1023
429
        DecIndex();
1024
429
    }
1025
429
    WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
1026
429
}
1027
1028
std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
1029
390k
{
1030
390k
    AssertLockHeld(cs_desc_man);
1031
390k
    if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
  Branch (1031:9): [True: 0, False: 390k]
  Branch (1031:42): [True: 0, False: 0]
1032
0
        KeyMap keys;
1033
0
        for (const auto& key_pair : m_map_crypted_keys) {
  Branch (1033:35): [True: 0, False: 0]
1034
0
            const CPubKey& pubkey = key_pair.second.first;
1035
0
            const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
1036
0
            CKey key;
1037
0
            m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
1038
0
                return DecryptKey(encryption_key, crypted_secret, pubkey, key);
1039
0
            });
1040
0
            keys[pubkey.GetID()] = key;
1041
0
        }
1042
0
        return keys;
1043
0
    }
1044
390k
    return m_map_keys;
1045
390k
}
1046
1047
bool DescriptorScriptPubKeyMan::HasPrivKey(const CKeyID& keyid) const
1048
0
{
1049
0
    AssertLockHeld(cs_desc_man);
1050
0
    return m_map_keys.contains(keyid) || m_map_crypted_keys.contains(keyid);
  Branch (1050:12): [True: 0, False: 0]
  Branch (1050:42): [True: 0, False: 0]
1051
0
}
1052
1053
std::optional<CKey> DescriptorScriptPubKeyMan::GetKey(const CKeyID& keyid) const
1054
0
{
1055
0
    AssertLockHeld(cs_desc_man);
1056
0
    if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
  Branch (1056:9): [True: 0, False: 0]
  Branch (1056:42): [True: 0, False: 0]
1057
0
        const auto& it = m_map_crypted_keys.find(keyid);
1058
0
        if (it == m_map_crypted_keys.end()) {
  Branch (1058:13): [True: 0, False: 0]
1059
0
            return std::nullopt;
1060
0
        }
1061
0
        const std::vector<unsigned char>& crypted_secret = it->second.second;
1062
0
        CKey key;
1063
0
        if (!Assume(m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
  Branch (1063:13): [True: 0, False: 0]
1064
0
            return DecryptKey(encryption_key, crypted_secret, it->second.first, key);
1065
0
        }))) {
1066
0
            return std::nullopt;
1067
0
        }
1068
0
        return key;
1069
0
    }
1070
0
    const auto& it = m_map_keys.find(keyid);
1071
0
    if (it == m_map_keys.end()) {
  Branch (1071:9): [True: 0, False: 0]
1072
0
        return std::nullopt;
1073
0
    }
1074
0
    return it->second;
1075
0
}
1076
1077
bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
1078
286k
{
1079
286k
    WalletBatch batch(m_storage.GetDatabase());
1080
286k
    if (!batch.TxnBegin()) return false;
  Branch (1080:9): [True: 0, False: 286k]
1081
286k
    bool res = TopUpWithDB(batch, size);
1082
286k
    if (!batch.TxnCommit()) throw std::runtime_error(strprintf("Error during descriptors keypool top up. Cannot commit changes for wallet [%s]", m_storage.LogName()));
  Branch (1082:9): [True: 0, False: 286k]
1083
286k
    return res;
1084
286k
}
1085
1086
bool DescriptorScriptPubKeyMan::TopUpWithDB(WalletBatch& batch, unsigned int size)
1087
332k
{
1088
332k
    LOCK(cs_desc_man);
1089
332k
    std::set<CScript> new_spks;
1090
332k
    unsigned int target_size;
1091
332k
    if (size > 0) {
  Branch (1091:9): [True: 0, False: 332k]
1092
0
        target_size = size;
1093
332k
    } else {
1094
332k
        target_size = m_keypool_size;
1095
332k
    }
1096
1097
    // Calculate the new range_end
1098
332k
    int32_t new_range_end = std::max(m_wallet_descriptor.GetNext() + (int32_t)target_size, m_wallet_descriptor.GetEnd());
1099
1100
    // If the descriptor is not ranged, we actually just want to fill the first cache item
1101
332k
    if (!m_wallet_descriptor.descriptor->IsRange()) {
  Branch (1101:9): [True: 26.3k, False: 306k]
1102
26.3k
        new_range_end = 1;
1103
26.3k
    }
1104
1105
332k
    FlatSigningProvider provider;
1106
332k
    provider.keys = GetKeys();
1107
1108
332k
    uint256 id = GetID();
1109
654k
    for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
  Branch (1109:46): [True: 321k, False: 332k]
1110
321k
        FlatSigningProvider out_keys;
1111
321k
        std::vector<CScript> scripts_temp;
1112
321k
        DescriptorCache temp_cache;
1113
        // Maybe we have a cached xpub and we can expand from the cache first
1114
321k
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
  Branch (1114:13): [True: 35.0k, False: 286k]
1115
35.0k
            if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
  Branch (1115:17): [True: 0, False: 35.0k]
1116
35.0k
        }
1117
        // Add all of the scriptPubKeys to the scriptPubKey set
1118
321k
        new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1119
349k
        for (const CScript& script : scripts_temp) {
  Branch (1119:36): [True: 349k, False: 321k]
1120
349k
            m_map_script_pub_keys[script] = i;
1121
349k
        }
1122
475k
        for (const auto& pk_pair : out_keys.pubkeys) {
  Branch (1122:34): [True: 475k, False: 321k]
1123
475k
            const CPubKey& pubkey = pk_pair.second;
1124
475k
            if (m_map_pubkeys.contains(pubkey)) {
  Branch (1124:17): [True: 120k, False: 355k]
1125
                // We don't need to give an error here.
1126
                // 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
1127
120k
                continue;
1128
120k
            }
1129
355k
            m_map_pubkeys[pubkey] = i;
1130
355k
        }
1131
        // Merge and write the cache
1132
321k
        DescriptorCache new_items = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
1133
321k
        if (!batch.WriteDescriptorCacheItems(id, new_items)) {
  Branch (1133:13): [True: 0, False: 321k]
1134
0
            throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
1135
0
        }
1136
321k
        m_max_cached_index++;
1137
321k
    }
1138
332k
    SetRangeEnd(new_range_end);
1139
332k
    batch.WriteDescriptor(GetID(), m_wallet_descriptor);
1140
1141
    // By this point, the cache size should be the size of the entire range
1142
332k
    assert(m_wallet_descriptor.GetEnd() - 1 == m_max_cached_index);
  Branch (1142:5): [True: 332k, False: 0]
1143
1144
332k
    m_storage.TopUpCallback(new_spks, this);
1145
332k
    return true;
1146
332k
}
1147
1148
std::vector<WalletDestination> DescriptorScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
1149
4.06k
{
1150
4.06k
    LOCK(cs_desc_man);
1151
4.06k
    std::vector<WalletDestination> result;
1152
4.06k
    if (IsMine(script)) {
  Branch (1152:9): [True: 4.06k, False: 0]
1153
4.06k
        int32_t index = m_map_script_pub_keys[script];
1154
4.06k
        if (index >= m_wallet_descriptor.GetNext()) {
  Branch (1154:13): [True: 978, False: 3.08k]
1155
978
            WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
1156
978
            auto out_keys = std::make_unique<FlatSigningProvider>();
1157
978
            std::vector<CScript> scripts_temp;
1158
1.95k
            while (index >= m_wallet_descriptor.GetNext()) {
  Branch (1158:20): [True: 978, False: 978]
1159
978
                if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.GetNext(), m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
  Branch (1159:21): [True: 0, False: 978]
1160
0
                    throw std::runtime_error(std::string(__func__) + ": Unable to expand descriptor from cache");
1161
0
                }
1162
978
                CTxDestination dest;
1163
978
                ExtractDestination(scripts_temp[0], dest);
1164
978
                result.push_back({dest, std::nullopt});
1165
978
                IncIndex();
1166
978
            }
1167
978
        }
1168
4.06k
        if (!TopUp()) {
  Branch (1168:13): [True: 0, False: 4.06k]
1169
0
            WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1170
0
        }
1171
4.06k
    }
1172
1173
4.06k
    return result;
1174
4.06k
}
1175
1176
void DescriptorScriptPubKeyMan::AddDescriptorKey(const CKey& key, const CPubKey &pubkey)
1177
0
{
1178
0
    LOCK(cs_desc_man);
1179
0
    WalletBatch batch(m_storage.GetDatabase());
1180
0
    if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
  Branch (1180:9): [True: 0, False: 0]
1181
0
        throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
1182
0
    }
1183
0
}
1184
1185
bool DescriptorScriptPubKeyMan::AddDescriptorKeyWithDB(WalletBatch& batch, const CKey& key, const CPubKey &pubkey)
1186
50.6k
{
1187
50.6k
    AssertLockHeld(cs_desc_man);
1188
50.6k
    assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
  Branch (1188:5): [True: 50.6k, False: 0]
1189
1190
    // Check if provided key already exists
1191
50.6k
    if (m_map_keys.contains(pubkey.GetID()) ||
  Branch (1191:9): [True: 117, False: 50.4k]
  Branch (1191:9): [True: 117, False: 50.4k]
1192
50.6k
        m_map_crypted_keys.contains(pubkey.GetID())) {
  Branch (1192:9): [True: 0, False: 50.4k]
1193
117
        return true;
1194
117
    }
1195
1196
50.4k
    if (m_storage.HasEncryptionKeys()) {
  Branch (1196:9): [True: 0, False: 50.4k]
1197
0
        if (m_storage.IsLocked()) {
  Branch (1197:13): [True: 0, False: 0]
1198
0
            return false;
1199
0
        }
1200
1201
0
        std::vector<unsigned char> crypted_secret;
1202
0
        CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
1203
0
        if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
  Branch (1203:13): [True: 0, False: 0]
1204
0
                return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
1205
0
            })) {
1206
0
            return false;
1207
0
        }
1208
1209
0
        m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1210
0
        return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1211
50.4k
    } else {
1212
50.4k
        m_map_keys[pubkey.GetID()] = key;
1213
50.4k
        return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
1214
50.4k
    }
1215
50.4k
}
1216
1217
void DescriptorScriptPubKeyMan::SetupDescriptorGeneration(WalletBatch& batch, const CExtKey& master_key, OutputType addr_type, bool internal)
1218
0
{
1219
0
    LOCK(cs_desc_man);
1220
0
    Assert(m_storage.IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
1221
0
    Assert(!m_wallet_descriptor.descriptor);
1222
1223
0
    m_wallet_descriptor = GenerateWalletDescriptor(master_key.Neuter(), addr_type, internal);
1224
1225
    // Store the master private key, and descriptor
1226
0
    if (!AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey())) {
  Branch (1226:9): [True: 0, False: 0]
1227
0
        throw std::runtime_error(std::string(__func__) + ": writing descriptor master private key failed");
1228
0
    }
1229
0
    if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
  Branch (1229:9): [True: 0, False: 0]
1230
0
        throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
1231
0
    }
1232
1233
    // Set m_decryption_thoroughly_checked for encrypted wallets
1234
0
    if (m_storage.HasEncryptionKeys()) {
  Branch (1234:9): [True: 0, False: 0]
1235
0
        m_decryption_thoroughly_checked = true;
1236
0
    }
1237
1238
    // TopUp
1239
0
    TopUpWithDB(batch);
1240
1241
0
    m_storage.UnsetBlankWalletFlag(batch);
1242
0
}
1243
1244
bool DescriptorScriptPubKeyMan::IsHDEnabled() const
1245
15.5k
{
1246
15.5k
    LOCK(cs_desc_man);
1247
15.5k
    return m_wallet_descriptor.descriptor->IsRange();
1248
15.5k
}
1249
1250
bool DescriptorScriptPubKeyMan::CanGetAddresses(bool internal) const
1251
1.51M
{
1252
    // We can only give out addresses from descriptors that are single type (not combo), ranged,
1253
    // and either have cached keys or can generate more keys (ignoring encryption)
1254
1.51M
    LOCK(cs_desc_man);
1255
1.51M
    return m_wallet_descriptor.descriptor->IsSingleType() &&
  Branch (1255:12): [True: 1.49M, False: 24.1k]
1256
1.51M
           m_wallet_descriptor.descriptor->IsRange() &&
  Branch (1256:12): [True: 1.45M, False: 36.1k]
1257
1.51M
           (HavePrivateKeys() || m_wallet_descriptor.GetNext() < m_wallet_descriptor.GetEnd() || m_wallet_descriptor.descriptor->CanSelfExpand());
  Branch (1257:13): [True: 1.45M, False: 2.60k]
  Branch (1257:34): [True: 1.25k, False: 1.34k]
  Branch (1257:98): [True: 1.34k, False: 0]
1258
1.51M
}
1259
1260
bool DescriptorScriptPubKeyMan::HavePrivateKeys() const
1261
1.69M
{
1262
1.69M
    LOCK(cs_desc_man);
1263
1.69M
    return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
  Branch (1263:12): [True: 1.69M, False: 5.14k]
  Branch (1263:37): [True: 0, False: 5.14k]
1264
1.69M
}
1265
1266
bool DescriptorScriptPubKeyMan::HaveCryptedKeys() const
1267
0
{
1268
0
    LOCK(cs_desc_man);
1269
0
    return !m_map_crypted_keys.empty();
1270
0
}
1271
1272
unsigned int DescriptorScriptPubKeyMan::GetKeyPoolSize() const
1273
11.6k
{
1274
11.6k
    LOCK(cs_desc_man);
1275
11.6k
    return m_wallet_descriptor.GetEnd() - m_wallet_descriptor.GetNext();
1276
11.6k
}
1277
1278
int64_t DescriptorScriptPubKeyMan::GetTimeFirstKey() const
1279
29.2k
{
1280
29.2k
    LOCK(cs_desc_man);
1281
29.2k
    return m_wallet_descriptor.creation_time;
1282
29.2k
}
1283
1284
std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
1285
490k
{
1286
490k
    LOCK(cs_desc_man);
1287
1288
    // Find the index of the script
1289
490k
    auto it = m_map_script_pub_keys.find(script);
1290
490k
    if (it == m_map_script_pub_keys.end()) {
  Branch (1290:9): [True: 249k, False: 240k]
1291
249k
        return nullptr;
1292
249k
    }
1293
240k
    int32_t index = it->second;
1294
1295
240k
    return GetSigningProvider(index, include_private);
1296
490k
}
1297
1298
std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
1299
4.03k
{
1300
4.03k
    LOCK(cs_desc_man);
1301
1302
    // Find index of the pubkey
1303
4.03k
    auto it = m_map_pubkeys.find(pubkey);
1304
4.03k
    if (it == m_map_pubkeys.end()) {
  Branch (1304:9): [True: 3.97k, False: 59]
1305
3.97k
        return nullptr;
1306
3.97k
    }
1307
59
    int32_t index = it->second;
1308
1309
    // Always try to get the signing provider with private keys. This function should only be called during signing anyways
1310
59
    std::unique_ptr<FlatSigningProvider> out = GetSigningProvider(index, true);
1311
59
    if (!out->HaveKey(pubkey.GetID())) {
  Branch (1311:9): [True: 3, False: 56]
1312
3
        return nullptr;
1313
3
    }
1314
56
    return out;
1315
59
}
1316
1317
std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
1318
240k
{
1319
240k
    AssertLockHeld(cs_desc_man);
1320
1321
240k
    std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
1322
1323
    // Fetch SigningProvider from cache to avoid re-deriving
1324
240k
    auto it = m_map_signing_providers.find(index);
1325
240k
    if (it != m_map_signing_providers.end()) {
  Branch (1325:9): [True: 127k, False: 112k]
1326
127k
        out_keys->Merge(FlatSigningProvider{it->second});
1327
127k
    } else {
1328
        // Get the scripts, keys, and key origins for this script
1329
112k
        std::vector<CScript> scripts_temp;
1330
112k
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
  Branch (1330:13): [True: 0, False: 112k]
1331
1332
        // Cache SigningProvider so we don't need to re-derive if we need this SigningProvider again
1333
112k
        m_map_signing_providers[index] = *out_keys;
1334
112k
    }
1335
1336
240k
    if (HavePrivateKeys() && include_private) {
  Branch (1336:9): [True: 238k, False: 2.54k]
  Branch (1336:30): [True: 45.7k, False: 192k]
1337
45.7k
        FlatSigningProvider master_provider;
1338
45.7k
        master_provider.keys = GetKeys();
1339
45.7k
        m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
1340
1341
        // Always include musig_secnonces as this descriptor may have a participant private key
1342
        // but not a musig() descriptor
1343
45.7k
        out_keys->musig2_secnonces = &m_musig2_secnonces;
1344
45.7k
    }
1345
1346
240k
    return out_keys;
1347
240k
}
1348
1349
std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
1350
173k
{
1351
173k
    return GetSigningProvider(script, false);
1352
173k
}
1353
1354
bool DescriptorScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
1355
168k
{
1356
168k
    return IsMine(script);
1357
168k
}
1358
1359
bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
1360
13.2k
{
1361
13.2k
    std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1362
262k
    for (const auto& coin_pair : coins) {
  Branch (1362:32): [True: 262k, False: 13.2k]
1363
262k
        std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
1364
262k
        if (!coin_keys) {
  Branch (1364:13): [True: 222k, False: 39.8k]
1365
222k
            continue;
1366
222k
        }
1367
39.8k
        keys->Merge(std::move(*coin_keys));
1368
39.8k
    }
1369
1370
13.2k
    return ::SignTransaction(tx, keys.get(), coins, {.sighash_type = sighash}, input_errors);
1371
13.2k
}
1372
1373
SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
1374
26.2k
{
1375
26.2k
    std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
1376
26.2k
    if (!keys) {
  Branch (1376:9): [True: 20.0k, False: 6.24k]
1377
20.0k
        return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
1378
20.0k
    }
1379
1380
6.24k
    CKey key;
1381
6.24k
    if (!keys->GetKey(ToKeyID(pkhash), key)) {
  Branch (1381:9): [True: 392, False: 5.85k]
1382
392
        return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
1383
392
    }
1384
1385
5.85k
    if (!MessageSign(key, message, str_sig)) {
  Branch (1385:9): [True: 0, False: 5.85k]
1386
0
        return SigningResult::SIGNING_FAILED;
1387
0
    }
1388
5.85k
    return SigningResult::OK;
1389
5.85k
}
1390
1391
std::optional<PSBTError> DescriptorScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, const common::PSBTFillOptions& options, int* n_signed) const
1392
8.81k
{
1393
8.81k
    if (n_signed) {
  Branch (1393:9): [True: 0, False: 8.81k]
1394
0
        *n_signed = 0;
1395
0
    }
1396
13.4k
    for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
  Branch (1396:30): [True: 4.93k, False: 8.50k]
1397
4.93k
        PSBTInput& input = psbtx.inputs.at(i);
1398
1399
4.93k
        if (PSBTInputSigned(input)) {
  Branch (1399:13): [True: 597, False: 4.33k]
1400
597
            continue;
1401
597
        }
1402
1403
        // Get the scriptPubKey to know which SigningProvider to use
1404
4.33k
        CScript script;
1405
4.33k
        if (!input.witness_utxo.IsNull()) {
  Branch (1405:13): [True: 1.76k, False: 2.57k]
1406
1.76k
            script = input.witness_utxo.scriptPubKey;
1407
2.57k
        } else if (input.non_witness_utxo) {
  Branch (1407:20): [True: 7, False: 2.56k]
1408
7
            if (input.prev_out >= input.non_witness_utxo->vout.size()) {
  Branch (1408:17): [True: 0, False: 7]
1409
0
                return PSBTError::MISSING_INPUTS;
1410
0
            }
1411
7
            script = input.non_witness_utxo->vout[input.prev_out].scriptPubKey;
1412
2.56k
        } else {
1413
            // There's no UTXO so we can just skip this now
1414
2.56k
            continue;
1415
2.56k
        }
1416
1417
1.76k
        std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1418
1.76k
        std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, /*include_private=*/options.sign);
1419
1.76k
        if (script_keys) {
  Branch (1419:13): [True: 0, False: 1.76k]
1420
0
            keys->Merge(std::move(*script_keys));
1421
1.76k
        } else {
1422
            // Maybe there are pubkeys listed that we can sign for
1423
1.76k
            std::vector<CPubKey> pubkeys;
1424
1.76k
            pubkeys.reserve(input.hd_keypaths.size() + 2);
1425
1426
            // ECDSA Pubkeys
1427
1.76k
            for (const auto& [pk, _] : input.hd_keypaths) {
  Branch (1427:38): [True: 342, False: 1.76k]
1428
342
                pubkeys.push_back(pk);
1429
342
            }
1430
1431
            // Taproot output pubkey
1432
1.76k
            std::vector<std::vector<unsigned char>> sols;
1433
1.76k
            if (Solver(script, sols) == TxoutType::WITNESS_V1_TAPROOT) {
  Branch (1433:17): [True: 0, False: 1.76k]
1434
0
                sols[0].insert(sols[0].begin(), 0x02);
1435
0
                pubkeys.emplace_back(sols[0]);
1436
0
                sols[0][0] = 0x03;
1437
0
                pubkeys.emplace_back(sols[0]);
1438
0
            }
1439
1440
            // Taproot pubkeys
1441
1.84k
            for (const auto& pk_pair : input.m_tap_bip32_paths) {
  Branch (1441:38): [True: 1.84k, False: 1.76k]
1442
1.84k
                const XOnlyPubKey& pubkey = pk_pair.first;
1443
3.69k
                for (unsigned char prefix : {0x02, 0x03}) {
  Branch (1443:43): [True: 3.69k, False: 1.84k]
1444
3.69k
                    unsigned char b[33] = {prefix};
1445
3.69k
                    std::copy(pubkey.begin(), pubkey.end(), b + 1);
1446
3.69k
                    CPubKey fullpubkey;
1447
3.69k
                    fullpubkey.Set(b, b + 33);
1448
3.69k
                    pubkeys.push_back(fullpubkey);
1449
3.69k
                }
1450
1.84k
            }
1451
1452
4.03k
            for (const auto& pubkey : pubkeys) {
  Branch (1452:37): [True: 4.03k, False: 1.76k]
1453
4.03k
                std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
1454
4.03k
                if (pk_keys) {
  Branch (1454:21): [True: 56, False: 3.97k]
1455
56
                    keys->Merge(std::move(*pk_keys));
1456
56
                }
1457
4.03k
            }
1458
1.76k
        }
1459
1460
1.76k
        const auto sign_result = SignPSBTInput(HidingSigningProvider(keys.get(), /*hide_secret=*/!options.sign, /*hide_origin=*/!options.bip32_derivs), psbtx, i, &txdata, options, /*out_sigdata=*/nullptr);
1461
1.76k
        if (!sign_result.has_value() && sign_result.error() != PSBTError::INCOMPLETE) {
  Branch (1461:13): [True: 1.69k, False: 73]
  Branch (1461:41): [True: 309, False: 1.38k]
1462
309
            return sign_result.error();
1463
309
        }
1464
1465
1.46k
        bool signed_one = PSBTInputSigned(input);
1466
1.46k
        if (n_signed && (signed_one || !options.sign)) {
  Branch (1466:13): [True: 0, False: 1.46k]
  Branch (1466:26): [True: 0, False: 0]
  Branch (1466:40): [True: 0, False: 0]
1467
            // If sign is false, we assume that we _could_ sign if we get here. This
1468
            // will never have false negatives; it is hard to tell under what i
1469
            // circumstances it could have false positives.
1470
0
            (*n_signed)++;
1471
0
        }
1472
1.46k
    }
1473
1474
    // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
1475
14.1k
    for (unsigned int i = 0; i < psbtx.outputs.size(); ++i) {
  Branch (1475:30): [True: 5.62k, False: 8.50k]
1476
5.62k
        std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.outputs.at(i).script);
1477
5.62k
        if (!keys) {
  Branch (1477:13): [True: 5.62k, False: 0]
1478
5.62k
            continue;
1479
5.62k
        }
1480
0
        UpdatePSBTOutput(HidingSigningProvider(keys.get(), /*hide_secret=*/true, /*hide_origin=*/!options.bip32_derivs), psbtx, i);
1481
0
    }
1482
1483
8.50k
    return {};
1484
8.81k
}
1485
1486
std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
1487
26.2k
{
1488
26.2k
    std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
1489
26.2k
    if (provider) {
  Branch (1489:9): [True: 26.2k, False: 0]
1490
26.2k
        KeyOriginInfo orig;
1491
26.2k
        CKeyID key_id = GetKeyForDestination(*provider, dest);
1492
26.2k
        if (provider->GetKeyOrigin(key_id, orig)) {
  Branch (1492:13): [True: 14.7k, False: 11.5k]
1493
14.7k
            LOCK(cs_desc_man);
1494
14.7k
            std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
1495
14.7k
            meta->key_origin = orig;
1496
14.7k
            meta->has_key_origin = true;
1497
14.7k
            meta->nCreateTime = m_wallet_descriptor.creation_time;
1498
14.7k
            return meta;
1499
14.7k
        }
1500
26.2k
    }
1501
11.5k
    return nullptr;
1502
26.2k
}
1503
1504
uint256 DescriptorScriptPubKeyMan::GetID() const
1505
1.07M
{
1506
1.07M
    LOCK(cs_desc_man);
1507
1.07M
    return m_wallet_descriptor.id;
1508
1.07M
}
1509
1510
void DescriptorScriptPubKeyMan::Load()
1511
0
{
1512
0
    LOCK(cs_desc_man);
1513
0
    std::set<CScript> new_spks;
1514
0
    for (int32_t i = m_wallet_descriptor.GetStart(); i < m_wallet_descriptor.GetEnd(); ++i) {
  Branch (1514:54): [True: 0, False: 0]
1515
0
        FlatSigningProvider out_keys;
1516
0
        std::vector<CScript> scripts_temp;
1517
0
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
  Branch (1517:13): [True: 0, False: 0]
1518
0
            throw std::runtime_error("Error: Unable to expand wallet descriptor from cache");
1519
0
        }
1520
        // Add all of the scriptPubKeys to the scriptPubKey set
1521
0
        new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1522
0
        for (const CScript& script : scripts_temp) {
  Branch (1522:36): [True: 0, False: 0]
1523
0
            if (m_map_script_pub_keys.contains(script)) {
  Branch (1523:17): [True: 0, False: 0]
1524
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]));
1525
0
            }
1526
0
            m_map_script_pub_keys[script] = i;
1527
0
        }
1528
0
        for (const auto& pk_pair : out_keys.pubkeys) {
  Branch (1528:34): [True: 0, False: 0]
1529
0
            const CPubKey& pubkey = pk_pair.second;
1530
0
            if (m_map_pubkeys.contains(pubkey)) {
  Branch (1530:17): [True: 0, False: 0]
1531
                // We don't need to give an error here.
1532
                // 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
1533
0
                continue;
1534
0
            }
1535
0
            m_map_pubkeys[pubkey] = i;
1536
0
        }
1537
0
        m_max_cached_index++;
1538
0
    }
1539
    // Make sure the wallet knows about our new spks
1540
0
    m_storage.TopUpCallback(new_spks, this);
1541
0
}
1542
1543
bool DescriptorScriptPubKeyMan::HasWalletDescriptor(const WalletDescriptor& desc) const
1544
2.60k
{
1545
2.60k
    LOCK(cs_desc_man);
1546
2.60k
    return !m_wallet_descriptor.id.IsNull() && !desc.id.IsNull() && m_wallet_descriptor.id == desc.id;
  Branch (1546:12): [True: 2.60k, False: 0]
  Branch (1546:48): [True: 2.60k, False: 0]
  Branch (1546:69): [True: 386, False: 2.21k]
1547
2.60k
}
1548
1549
void DescriptorScriptPubKeyMan::WriteDescriptor()
1550
29.3k
{
1551
29.3k
    LOCK(cs_desc_man);
1552
29.3k
    WalletBatch batch(m_storage.GetDatabase());
1553
29.3k
    if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
  Branch (1553:9): [True: 0, False: 29.3k]
1554
0
        throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
1555
0
    }
1556
29.3k
}
1557
1558
WalletDescriptor DescriptorScriptPubKeyMan::GetWalletDescriptor() const
1559
20.8k
{
1560
20.8k
    return m_wallet_descriptor;
1561
20.8k
}
1562
1563
std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
1564
41.1k
{
1565
41.1k
    return GetScriptPubKeys(0);
1566
41.1k
}
1567
1568
std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys(int32_t minimum_index) const
1569
41.1k
{
1570
41.1k
    LOCK(cs_desc_man);
1571
41.1k
    std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
1572
41.1k
    script_pub_keys.reserve(m_map_script_pub_keys.size());
1573
1574
103k
    for (auto const& [script_pub_key, index] : m_map_script_pub_keys) {
  Branch (1574:46): [True: 103k, False: 41.1k]
1575
103k
        if (index >= minimum_index) script_pub_keys.insert(script_pub_key);
  Branch (1575:13): [True: 103k, False: 0]
1576
103k
    }
1577
41.1k
    return script_pub_keys;
1578
41.1k
}
1579
1580
int32_t DescriptorScriptPubKeyMan::GetEndRange() const
1581
11.6k
{
1582
11.6k
    return m_max_cached_index + 1;
1583
11.6k
}
1584
1585
bool DescriptorScriptPubKeyMan::GetDescriptorString(std::string& out, const bool priv) const
1586
11.6k
{
1587
11.6k
    LOCK(cs_desc_man);
1588
1589
11.6k
    FlatSigningProvider provider;
1590
11.6k
    provider.keys = GetKeys();
1591
1592
11.6k
    if (priv) {
  Branch (1592:9): [True: 1.52k, False: 10.0k]
1593
        // For the private version, always return the master key to avoid
1594
        // exposing child private keys. The risk implications of exposing child
1595
        // private keys together with the parent xpub may be non-obvious for users.
1596
1.52k
        return m_wallet_descriptor.descriptor->ToPrivateString(provider, out);
1597
1.52k
    }
1598
1599
10.0k
    return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
1600
11.6k
}
1601
1602
void DescriptorScriptPubKeyMan::UpgradeDescriptorCache()
1603
0
{
1604
0
    LOCK(cs_desc_man);
1605
0
    if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED)) {
  Branch (1605:9): [True: 0, False: 0]
  Branch (1605:33): [True: 0, False: 0]
1606
0
        return;
1607
0
    }
1608
1609
    // Skip if we have the last hardened xpub cache
1610
0
    if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
  Branch (1610:9): [True: 0, False: 0]
1611
0
        return;
1612
0
    }
1613
1614
    // Expand the descriptor
1615
0
    FlatSigningProvider provider;
1616
0
    provider.keys = GetKeys();
1617
0
    FlatSigningProvider out_keys;
1618
0
    std::vector<CScript> scripts_temp;
1619
0
    DescriptorCache temp_cache;
1620
0
    if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
  Branch (1620:9): [True: 0, False: 0]
1621
0
        throw std::runtime_error("Unable to expand descriptor");
1622
0
    }
1623
1624
    // Cache the last hardened xpubs
1625
0
    DescriptorCache diff = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
1626
0
    if (!WalletBatch(m_storage.GetDatabase()).WriteDescriptorCacheItems(GetID(), diff)) {
  Branch (1626:9): [True: 0, False: 0]
1627
0
        throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
1628
0
    }
1629
0
}
1630
1631
util::Result<void> DescriptorScriptPubKeyMan::UpdateWalletDescriptor(WalletDescriptor& descriptor, const FlatSigningProvider& provider)
1632
125
{
1633
125
    LOCK(cs_desc_man);
1634
125
    std::string error;
1635
125
    if (!CanUpdateToWalletDescriptor(descriptor, error)) {
  Branch (1635:9): [True: 0, False: 125]
1636
0
        return util::Error{Untranslated(std::move(error))};
1637
0
    }
1638
1639
125
    m_map_pubkeys.clear();
1640
125
    m_map_script_pub_keys.clear();
1641
125
    m_max_cached_index = -1;
1642
125
    m_wallet_descriptor = descriptor;
1643
1644
125
    WalletBatch batch(m_storage.GetDatabase());
1645
125
    UpdateWithSigningProvider(batch, provider);
1646
125
    NotifyFirstKeyTimeChanged(this, m_wallet_descriptor.creation_time);
1647
125
    return {};
1648
125
}
1649
1650
void DescriptorScriptPubKeyMan::UpdateWithSigningProvider(WalletBatch& batch, const FlatSigningProvider& signing_provider)
1651
46.4k
{
1652
46.4k
    AssertLockHeld(cs_desc_man);
1653
    // Add the private keys to the descriptor
1654
50.6k
    for (const auto& entry : signing_provider.keys) {
  Branch (1654:28): [True: 50.6k, False: 46.4k]
1655
50.6k
        const CKey& key = entry.second;
1656
50.6k
        if (!AddDescriptorKeyWithDB(batch, key, key.GetPubKey())) {
  Branch (1656:13): [True: 0, False: 50.6k]
1657
0
            throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
1658
0
        }
1659
50.6k
    }
1660
1661
    // Top up key pool, to generate scriptPubKeys
1662
46.4k
    if (!TopUpWithDB(batch)) {
  Branch (1662:9): [True: 0, False: 46.4k]
1663
0
        throw std::runtime_error("Could not top up scriptPubKeys");
1664
0
    }
1665
46.4k
}
1666
1667
bool DescriptorScriptPubKeyMan::CanUpdateToWalletDescriptor(const WalletDescriptor& descriptor, std::string& error)
1668
2.47k
{
1669
2.47k
    LOCK(cs_desc_man);
1670
2.47k
    if (!HasWalletDescriptor(descriptor)) {
  Branch (1670:9): [True: 2.21k, False: 261]
1671
2.21k
        error = "can only update matching descriptor";
1672
2.21k
        return false;
1673
2.21k
    }
1674
1675
261
    if (!descriptor.descriptor->IsRange()) {
  Branch (1675:9): [True: 250, False: 11]
1676
        // Skip range check for non-range descriptors
1677
250
        return true;
1678
250
    }
1679
1680
11
    if (descriptor.GetStart() > m_wallet_descriptor.GetStart() ||
  Branch (1680:9): [True: 0, False: 11]
1681
11
        descriptor.GetEnd() < m_wallet_descriptor.GetEnd()) {
  Branch (1681:9): [True: 11, False: 0]
1682
        // Use inclusive range for error
1683
11
        error = strprintf("new range must include current range = [%d,%d]",
1684
11
                          m_wallet_descriptor.GetStart(),
1685
11
                          m_wallet_descriptor.GetEnd() - 1);
1686
11
        return false;
1687
11
    }
1688
1689
0
    return true;
1690
11
}
1691
} // namespace wallet