Coverage Report

Created: 2026-07-23 20:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/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
2.10k
{
65
2.10k
    return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
66
2.10k
}
67
68
bool HaveKeys(const std::vector<valtype>& pubkeys, const LegacyDataSPKM& keystore)
69
48
{
70
99
    for (const valtype& pubkey : pubkeys) {
71
99
        CKeyID keyID = CPubKey(pubkey).GetID();
72
99
        if (!keystore.HaveKey(keyID)) return false;
73
99
    }
74
9
    return true;
75
48
}
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
5.83k
{
88
5.83k
    IsMineResult ret = IsMineResult::NO;
89
90
5.83k
    std::vector<valtype> vSolutions;
91
5.83k
    TxoutType whichType = Solver(scriptPubKey, vSolutions);
92
93
5.83k
    CKeyID keyID;
94
5.83k
    switch (whichType) {
95
6
    case TxoutType::NONSTANDARD:
96
6
    case TxoutType::NULL_DATA:
97
6
    case TxoutType::WITNESS_UNKNOWN:
98
24
    case TxoutType::WITNESS_V1_TAPROOT:
99
24
    case TxoutType::ANCHOR:
100
24
        break;
101
458
    case TxoutType::PUBKEY:
102
458
        keyID = CPubKey(vSolutions[0]).GetID();
103
458
        if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
104
0
            return IsMineResult::INVALID;
105
0
        }
106
458
        if (keystore.HaveKey(keyID)) {
107
428
            ret = std::max(ret, IsMineResult::SPENDABLE);
108
428
        }
109
458
        break;
110
1.12k
    case TxoutType::WITNESS_V0_KEYHASH:
111
1.12k
    {
112
1.12k
        if (sigversion == IsMineSigVersion::WITNESS_V0) {
113
            // P2WPKH inside P2WSH is invalid.
114
0
            return IsMineResult::INVALID;
115
0
        }
116
1.12k
        if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[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
16
            break;
121
16
        }
122
1.11k
        ret = std::max(ret, LegacyWalletIsMineInnerDONOTUSE(keystore, GetScriptForDestination(PKHash(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
123
1.11k
        break;
124
1.12k
    }
125
1.59k
    case TxoutType::PUBKEYHASH:
126
1.59k
        keyID = CKeyID(uint160(vSolutions[0]));
127
1.59k
        if (!PermitsUncompressed(sigversion)) {
128
1.12k
            CPubKey pubkey;
129
1.12k
            if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
130
5
                return IsMineResult::INVALID;
131
5
            }
132
1.12k
        }
133
1.59k
        if (keystore.HaveKey(keyID)) {
134
1.51k
            ret = std::max(ret, IsMineResult::SPENDABLE);
135
1.51k
        }
136
1.59k
        break;
137
1.68k
    case TxoutType::SCRIPTHASH:
138
1.68k
    {
139
1.68k
        if (sigversion != IsMineSigVersion::TOP) {
140
            // P2SH inside P2WSH or P2SH is invalid.
141
10
            return IsMineResult::INVALID;
142
10
        }
143
1.67k
        CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
144
1.67k
        CScript subscript;
145
1.67k
        if (keystore.GetCScript(scriptID, subscript)) {
146
766
            ret = std::max(ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
147
766
        }
148
1.67k
        break;
149
1.68k
    }
150
896
    case TxoutType::WITNESS_V0_SCRIPTHASH:
151
896
    {
152
896
        if (sigversion == IsMineSigVersion::WITNESS_V0) {
153
            // P2WSH inside P2WSH is invalid.
154
5
            return IsMineResult::INVALID;
155
5
        }
156
891
        if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
157
815
            break;
158
815
        }
159
76
        CScriptID scriptID{RIPEMD160(vSolutions[0])};
160
76
        CScript subscript;
161
76
        if (keystore.GetCScript(scriptID, subscript)) {
162
69
            ret = std::max(ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::WITNESS_V0) : IsMineResult::SPENDABLE);
163
69
        }
164
76
        break;
165
891
    }
166
167
55
    case TxoutType::MULTISIG:
168
55
    {
169
        // Never treat bare multisig outputs as ours (they can still be made watchonly-though)
170
55
        if (sigversion == IsMineSigVersion::TOP) {
171
7
            break;
172
7
        }
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
48
        std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
180
48
        if (!PermitsUncompressed(sigversion)) {
181
112
            for (size_t i = 0; i < keys.size(); i++) {
182
79
                if (keys[i].size() != 33) {
183
0
                    return IsMineResult::INVALID;
184
0
                }
185
79
            }
186
33
        }
187
48
        if (HaveKeys(keys, keystore)) {
188
9
            ret = std::max(ret, IsMineResult::SPENDABLE);
189
9
        }
190
48
        break;
191
48
    }
192
5.83k
    } // no default case, so the compiler can warn about missing cases
193
194
5.81k
    if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
195
158
        ret = std::max(ret, IsMineResult::WATCH_ONLY);
196
158
    }
197
5.81k
    return ret;
198
5.83k
}
199
200
} // namespace
201
202
bool LegacyDataSPKM::IsMine(const CScript& script) const
203
3.32k
{
204
3.32k
    switch (LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP)) {
205
20
    case IsMineResult::INVALID:
206
1.21k
    case IsMineResult::NO:
207
1.21k
        return false;
208
158
    case IsMineResult::WATCH_ONLY:
209
2.11k
    case IsMineResult::SPENDABLE:
210
2.11k
        return true;
211
3.32k
    }
212
3.32k
    assert(false);
213
0
}
214
215
bool LegacyDataSPKM::CheckDecryptionKey(const CKeyingMaterial& master_key)
216
1
{
217
1
    {
218
1
        LOCK(cs_KeyStore);
219
1
        assert(mapKeys.empty());
220
221
1
        bool keyPass = mapCryptedKeys.empty(); // Always pass when there are no encrypted keys
222
1
        bool keyFail = false;
223
1
        CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
224
1
        WalletBatch batch(m_storage.GetDatabase());
225
1
        for (; mi != mapCryptedKeys.end(); ++mi)
226
1
        {
227
1
            const CPubKey &vchPubKey = (*mi).second.first;
228
1
            const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
229
1
            CKey key;
230
1
            if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
231
0
            {
232
0
                keyFail = true;
233
0
                break;
234
0
            }
235
1
            keyPass = true;
236
1
            if (fDecryptionThoroughlyChecked)
237
1
                break;
238
0
            else {
239
                // Rewrite these encrypted keys with checksums
240
0
                batch.WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
241
0
            }
242
1
        }
243
1
        if (keyPass && keyFail)
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
1
        if (keyFail || !keyPass)
249
0
            return false;
250
1
        fDecryptionThoroughlyChecked = true;
251
1
    }
252
0
    return true;
253
1
}
254
255
std::unique_ptr<SigningProvider> LegacyDataSPKM::GetSolvingProvider(const CScript& script) const
256
89
{
257
89
    return std::make_unique<LegacySigningProvider>(*this);
258
89
}
259
260
bool LegacyDataSPKM::CanProvide(const CScript& script, SignatureData& sigdata)
261
597
{
262
597
    IsMineResult ismine = LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
263
597
    if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
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
28
        return true;
268
569
    } else {
269
        // If, given the stuff in sigdata, we could make a valid signature, then we can provide for this script
270
569
        ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
271
569
        if (!sigdata.signatures.empty()) {
272
            // If we could make signatures, make sure we have a private key to actually make a signature
273
1
            bool has_privkeys = false;
274
1
            for (const auto& key_sig_pair : sigdata.signatures) {
275
1
                has_privkeys |= HaveKey(key_sig_pair.first);
276
1
            }
277
1
            return has_privkeys;
278
1
        }
279
568
        return false;
280
569
    }
281
597
}
282
283
bool LegacyDataSPKM::LoadKey(const CKey& key, const CPubKey &pubkey)
284
208
{
285
208
    return AddKeyPubKeyInner(key, pubkey);
286
208
}
287
288
bool LegacyDataSPKM::LoadCScript(const CScript& redeemScript)
289
94
{
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
94
    if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
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
94
    return FillableSigningProvider::AddCScript(redeemScript);
301
94
}
302
303
void LegacyDataSPKM::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
304
236
{
305
236
    LOCK(cs_KeyStore);
306
236
    mapKeyMetadata[keyID] = meta;
307
236
}
308
309
void LegacyDataSPKM::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata& meta)
310
49
{
311
49
    LOCK(cs_KeyStore);
312
49
    m_script_metadata[script_id] = meta;
313
49
}
314
315
bool LegacyDataSPKM::AddKeyPubKeyInner(const CKey& key, const CPubKey& pubkey)
316
208
{
317
208
    LOCK(cs_KeyStore);
318
208
    return FillableSigningProvider::AddKeyPubKey(key, pubkey);
319
208
}
320
321
bool LegacyDataSPKM::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid)
322
24
{
323
    // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
324
24
    if (!checksum_valid) {
325
0
        fDecryptionThoroughlyChecked = false;
326
0
    }
327
328
24
    return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
329
24
}
330
331
bool LegacyDataSPKM::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
332
24
{
333
24
    LOCK(cs_KeyStore);
334
24
    assert(mapKeys.empty());
335
336
24
    mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
337
24
    ImplicitlyLearnRelatedKeyScripts(vchPubKey);
338
24
    return true;
339
24
}
340
341
bool LegacyDataSPKM::HaveWatchOnly(const CScript &dest) const
342
1.99k
{
343
1.99k
    LOCK(cs_KeyStore);
344
1.99k
    return setWatchOnly.contains(dest);
345
1.99k
}
346
347
bool LegacyDataSPKM::LoadWatchOnly(const CScript &dest)
348
49
{
349
49
    return AddWatchOnlyInMem(dest);
350
49
}
351
352
static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
353
49
{
354
49
    std::vector<std::vector<unsigned char>> solutions;
355
49
    return Solver(dest, solutions) == TxoutType::PUBKEY &&
356
49
        (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
357
49
}
358
359
bool LegacyDataSPKM::AddWatchOnlyInMem(const CScript &dest)
360
49
{
361
49
    LOCK(cs_KeyStore);
362
49
    setWatchOnly.insert(dest);
363
49
    CPubKey pubKey;
364
49
    if (ExtractPubKey(dest, pubKey)) {
365
9
        mapWatchKeys[pubKey.GetID()] = pubKey;
366
9
        ImplicitlyLearnRelatedKeyScripts(pubKey);
367
9
    }
368
49
    return true;
369
49
}
370
371
void LegacyDataSPKM::LoadHDChain(const CHDChain& chain)
372
36
{
373
36
    LOCK(cs_KeyStore);
374
36
    m_hd_chain = chain;
375
36
}
376
377
void LegacyDataSPKM::AddInactiveHDChain(const CHDChain& chain)
378
6
{
379
6
    LOCK(cs_KeyStore);
380
6
    assert(!chain.seed_id.IsNull());
381
6
    m_inactive_hd_chains[chain.seed_id] = chain;
382
6
}
383
384
bool LegacyDataSPKM::HaveKey(const CKeyID &address) const
385
2.15k
{
386
2.15k
    LOCK(cs_KeyStore);
387
2.15k
    if (!m_storage.HasEncryptionKeys()) {
388
2.09k
        return FillableSigningProvider::HaveKey(address);
389
2.09k
    }
390
54
    return mapCryptedKeys.contains(address);
391
2.15k
}
392
393
bool LegacyDataSPKM::GetKey(const CKeyID &address, CKey& keyOut) const
394
1.33k
{
395
1.33k
    LOCK(cs_KeyStore);
396
1.33k
    if (!m_storage.HasEncryptionKeys()) {
397
1.32k
        return FillableSigningProvider::GetKey(address, keyOut);
398
1.32k
    }
399
400
5
    CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
401
5
    if (mi != mapCryptedKeys.end())
402
5
    {
403
5
        const CPubKey &vchPubKey = (*mi).second.first;
404
5
        const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
405
5
        return m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
406
5
            return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey, keyOut);
407
5
        });
408
5
    }
409
0
    return false;
410
5
}
411
412
bool LegacyDataSPKM::GetKeyOrigin(const CKeyID& keyID, KeyOriginInfo& info) const
413
144
{
414
144
    CKeyMetadata meta;
415
144
    {
416
144
        LOCK(cs_KeyStore);
417
144
        auto it = mapKeyMetadata.find(keyID);
418
144
        if (it == mapKeyMetadata.end()) {
419
56
            return false;
420
56
        }
421
88
        meta = it->second;
422
88
    }
423
88
    if (meta.has_key_origin) {
424
42
        std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4, info.fingerprint);
425
42
        info.path = meta.key_origin.path;
426
46
    } else { // Single pubkeys get the master fingerprint of themselves
427
46
        std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
428
46
    }
429
88
    return true;
430
144
}
431
432
bool LegacyDataSPKM::GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
433
77
{
434
77
    LOCK(cs_KeyStore);
435
77
    WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
436
77
    if (it != mapWatchKeys.end()) {
437
64
        pubkey_out = it->second;
438
64
        return true;
439
64
    }
440
13
    return false;
441
77
}
442
443
bool LegacyDataSPKM::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
444
1.17k
{
445
1.17k
    LOCK(cs_KeyStore);
446
1.17k
    if (!m_storage.HasEncryptionKeys()) {
447
1.14k
        if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
448
77
            return GetWatchPubKey(address, vchPubKeyOut);
449
77
        }
450
1.06k
        return true;
451
1.14k
    }
452
453
30
    CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
454
30
    if (mi != mapCryptedKeys.end())
455
30
    {
456
30
        vchPubKeyOut = (*mi).second.first;
457
30
        return true;
458
30
    }
459
    // Check for watch-only pubkeys
460
0
    return GetWatchPubKey(address, vchPubKeyOut);
461
30
}
462
463
std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetCandidateScriptPubKeys() const
464
84
{
465
84
    LOCK(cs_KeyStore);
466
84
    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
428
    const auto& add_pubkey = [&candidate_spks](const CPubKey& pub) -> void {
470
428
        candidate_spks.insert(GetScriptForRawPubKey(pub));
471
428
        candidate_spks.insert(GetScriptForDestination(PKHash(pub)));
472
473
428
        CScript wpkh = GetScriptForDestination(WitnessV0KeyHash(pub));
474
428
        candidate_spks.insert(wpkh);
475
428
        candidate_spks.insert(GetScriptForDestination(ScriptHash(wpkh)));
476
428
    };
477
416
    for (const auto& [_, key] : mapKeys) {
478
416
        add_pubkey(key.GetPubKey());
479
416
    }
480
84
    for (const auto& [_, ckeypair] : mapCryptedKeys) {
481
12
        add_pubkey(ckeypair.first);
482
12
    }
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
604
    const auto& add_script = [&candidate_spks](const CScript& script) -> void {
489
604
        candidate_spks.insert(script);
490
604
        candidate_spks.insert(GetScriptForDestination(ScriptHash(script)));
491
492
604
        CScript wsh = GetScriptForDestination(WitnessV0ScriptHash(script));
493
604
        candidate_spks.insert(wsh);
494
604
        candidate_spks.insert(GetScriptForDestination(ScriptHash(wsh)));
495
604
    };
496
506
    for (const auto& [_, script] : mapScripts) {
497
506
        add_script(script);
498
506
    }
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
98
    for (const auto& script : setWatchOnly) {
503
98
        add_script(script);
504
98
    }
505
506
84
    return candidate_spks;
507
84
}
508
509
std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetScriptPubKeys() const
510
42
{
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
42
    std::unordered_set<CScript, SaltedSipHasher> spks;
515
1.52k
    for (const CScript& script : GetCandidateScriptPubKeys()) {
516
1.52k
        if (IsMine(script)) {
517
915
            spks.insert(script);
518
915
        }
519
1.52k
    }
520
521
42
    return spks;
522
42
}
523
524
std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetNotMineScriptPubKeys() const
525
38
{
526
38
    LOCK(cs_KeyStore);
527
38
    std::unordered_set<CScript, SaltedSipHasher> spks;
528
45
    for (const CScript& script : setWatchOnly) {
529
45
        if (!IsMine(script)) spks.insert(script);
530
45
    }
531
38
    return spks;
532
38
}
533
534
std::optional<MigrationData> LegacyDataSPKM::MigrateToDescriptor()
535
42
{
536
42
    LOCK(cs_KeyStore);
537
42
    if (m_storage.IsLocked()) {
538
0
        return std::nullopt;
539
0
    }
540
541
42
    MigrationData out;
542
543
42
    std::unordered_set<CScript, SaltedSipHasher> spks{GetScriptPubKeys()};
544
545
    // Get all key ids
546
42
    std::set<CKeyID> keyids;
547
208
    for (const auto& key_pair : mapKeys) {
548
208
        keyids.insert(key_pair.first);
549
208
    }
550
42
    for (const auto& key_pair : mapCryptedKeys) {
551
6
        keyids.insert(key_pair.first);
552
6
    }
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
256
    for (auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
557
214
        const CKeyID& keyid = *keyid_it;
558
214
        const auto& it = mapKeyMetadata.find(keyid);
559
214
        if (it != mapKeyMetadata.end()) {
560
214
            const CKeyMetadata& meta = it->second;
561
214
            if (meta.hdKeypath == "s" || meta.hdKeypath == "m") {
562
37
                keyid_it++;
563
37
                continue;
564
37
            }
565
177
            if (!meta.hd_seed_id.IsNull() && (m_hd_chain.seed_id == meta.hd_seed_id || m_inactive_hd_chains.contains(meta.hd_seed_id))) {
566
173
                keyid_it = keyids.erase(keyid_it);
567
173
                continue;
568
173
            }
569
177
        }
570
4
        keyid_it++;
571
4
    }
572
573
42
    WalletBatch batch(m_storage.GetDatabase());
574
42
    if (!batch.TxnBegin()) {
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
42
    for (const CKeyID& keyid : keyids) {
581
41
        CKey key;
582
41
        if (!GetKey(keyid, key)) {
583
0
            assert(false);
584
0
        }
585
586
        // Get birthdate from key meta
587
41
        uint64_t creation_time = 0;
588
41
        const auto& it = mapKeyMetadata.find(keyid);
589
41
        if (it != mapKeyMetadata.end()) {
590
41
            creation_time = it->second.nCreateTime;
591
41
        }
592
593
        // Get the key origin
594
        // Maybe this doesn't matter because floating keys here shouldn't have origins
595
41
        KeyOriginInfo info;
596
41
        bool has_info = GetKeyOrigin(keyid, info);
597
41
        std::string origin_str = has_info ? "[" + HexStr(info.fingerprint) + FormatHDKeypath(info.path) + "]" : "";
598
599
        // Construct the combo descriptor
600
41
        std::string desc_str = "combo(" + origin_str + HexStr(key.GetPubKey()) + ")";
601
41
        FlatSigningProvider provider;
602
41
        std::string error;
603
41
        std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, provider, error, false);
604
41
        CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
605
41
        WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
606
607
        // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
608
41
        provider.keys.emplace(key.GetPubKey().GetID(), key);
609
41
        auto desc_spk_man = DescriptorScriptPubKeyMan::CreateFromMigration(m_storage, batch, w_desc, /*keypool_size=*/0, provider);
610
41
        auto desc_spks = desc_spk_man->GetScriptPubKeys();
611
612
        // Remove the scriptPubKeys from our current set
613
162
        for (const CScript& spk : desc_spks) {
614
162
            size_t erased = spks.erase(spk);
615
162
            assert(erased == 1);
616
162
            assert(IsMine(spk));
617
162
        }
618
619
41
        out.desc_spkms.push_back(std::move(desc_spk_man));
620
41
    }
621
622
    // Handle HD keys by using the CHDChains
623
42
    std::set<CHDChain> chains;
624
42
    chains.insert(m_hd_chain);
625
42
    for (const auto& chain_pair : m_inactive_hd_chains) {
626
3
        chains.insert(chain_pair.second);
627
3
    }
628
629
42
    bool can_support_hd_split_feature = m_hd_chain.nVersion >= CHDChain::VERSION_HD_CHAIN_SPLIT;
630
631
42
    std::set<CExtPubKey> master_xpubs;
632
45
    for (const CHDChain& chain : chains) {
633
45
        if (chain.seed_id.IsNull()) continue;
634
635
        // Get the master xprv
636
36
        CKey seed_key;
637
36
        if (!GetKey(chain.seed_id, seed_key)) {
638
0
            assert(false);
639
0
        }
640
36
        CExtKey master_key;
641
36
        master_key.SetSeed(seed_key);
642
643
        // Get the xpub and verify that we haven't already seen this xpub before
644
36
        CExtPubKey master_xpub = master_key.Neuter();
645
36
        const auto& [_, inserted] = master_xpubs.insert(master_xpub);
646
36
        if (!inserted) continue;
647
648
108
        for (int i = 0; i < 2; ++i) {
649
            // Skip if doing internal chain and split chain is not supported
650
72
            if (i == 1 && !can_support_hd_split_feature) {
651
0
                continue;
652
0
            }
653
654
            // Make the combo descriptor
655
72
            std::string xpub = EncodeExtPubKey(master_key.Neuter());
656
72
            std::string desc_str = "combo(" + xpub + "/0h/" + ToString(i) + "h/*h)";
657
72
            FlatSigningProvider provider;
658
72
            std::string error;
659
72
            std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, provider, error, false);
660
72
            CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
661
72
            uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
662
72
            WalletDescriptor w_desc(std::move(descs.at(0)), 0, 0, chain_counter, 0);
663
664
            // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
665
72
            provider.keys.emplace(master_key.key.GetPubKey().GetID(), master_key.key);
666
72
            auto desc_spk_man = DescriptorScriptPubKeyMan::CreateFromMigration(m_storage, batch, w_desc, /*keypool_size=*/0, provider);
667
72
            auto desc_spks = desc_spk_man->GetScriptPubKeys();
668
669
            // Remove the scriptPubKeys from our current set
670
692
            for (const CScript& spk : desc_spks) {
671
692
                size_t erased = spks.erase(spk);
672
692
                assert(erased == 1);
673
692
                assert(IsMine(spk));
674
692
            }
675
676
72
            out.desc_spkms.push_back(std::move(desc_spk_man));
677
72
        }
678
36
    }
679
    // Add the current master seed to the migration data
680
42
    if (!m_hd_chain.seed_id.IsNull()) {
681
33
        CKey seed_key;
682
33
        if (!GetKey(m_hd_chain.seed_id, seed_key)) {
683
0
            assert(false);
684
0
        }
685
33
        out.master_key.SetSeed(seed_key);
686
33
    }
687
688
    // Handle the rest of the scriptPubKeys which must be imports and may not have all info
689
103
    for (auto it = spks.begin(); it != spks.end();) {
690
61
        const CScript& spk = *it;
691
692
        // Get birthdate from script meta
693
61
        uint64_t creation_time = 0;
694
61
        const auto& mit = m_script_metadata.find(CScriptID(spk));
695
61
        if (mit != m_script_metadata.end()) {
696
44
            creation_time = mit->second.nCreateTime;
697
44
        }
698
699
        // InferDescriptor as that will get us all the solving info if it is there
700
61
        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
61
        {
705
61
            std::string desc_str = desc->ToString();
706
61
            FlatSigningProvider parsed_keys;
707
61
            std::string parse_error;
708
61
            std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error);
709
61
            if (parsed_descs.empty()) {
710
                // Remove this scriptPubKey from the set
711
0
                it = spks.erase(it);
712
0
                continue;
713
0
            }
714
61
        }
715
716
        // Get the private keys for this descriptor
717
61
        std::vector<CScript> scripts;
718
61
        FlatSigningProvider keys;
719
61
        if (!desc->Expand(0, DUMMY_SIGNING_PROVIDER, scripts, keys)) {
720
0
            assert(false);
721
0
        }
722
61
        std::set<CKeyID> privkeyids;
723
61
        for (const auto& key_orig_pair : keys.origins) {
724
52
            privkeyids.insert(key_orig_pair.first);
725
52
        }
726
727
61
        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
61
        if (!desc->HavePrivateKeys(*this) && !m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
732
40
            out.watch_descs.emplace_back(desc->ToString(), creation_time);
733
734
            // Get the scriptPubKeys without writing this to the wallet
735
40
            FlatSigningProvider provider;
736
40
            desc->Expand(0, provider, desc_spks, provider);
737
40
        } else {
738
            // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
739
27
            for (const auto& keyid : privkeyids) {
740
27
                CKey key;
741
27
                if (!GetKey(keyid, key)) {
742
10
                    continue;
743
10
                }
744
17
                keys.keys.emplace(key.GetPubKey().GetID(), key);
745
17
            }
746
21
            WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
747
21
            auto desc_spk_man = DescriptorScriptPubKeyMan::CreateFromMigration(m_storage, batch, w_desc, /*keypool_size=*/0, keys);
748
21
            auto desc_spks_set = desc_spk_man->GetScriptPubKeys();
749
21
            desc_spks.insert(desc_spks.end(), desc_spks_set.begin(), desc_spks_set.end());
750
751
21
            out.desc_spkms.push_back(std::move(desc_spk_man));
752
21
        }
753
754
        // Remove the scriptPubKeys from our current set
755
61
        for (const CScript& desc_spk : desc_spks) {
756
61
            auto del_it = spks.find(desc_spk);
757
61
            assert(del_it != spks.end());
758
61
            assert(IsMine(desc_spk));
759
61
            it = spks.erase(del_it);
760
61
        }
761
61
    }
762
763
    // Make sure that we have accounted for all scriptPubKeys
764
42
    if (!Assume(spks.empty())) {
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
1.52k
    for (const CScript& script : GetCandidateScriptPubKeys()) {
775
        // Since we only care about P2SH, P2WSH, and P2SH-P2WSH, filter out any scripts that are not those
776
1.52k
        if (!script.IsPayToScriptHash() && !script.IsPayToWitnessScriptHash()) {
777
686
            continue;
778
686
        }
779
838
        if (IsMine(script)) {
780
241
            continue;
781
241
        }
782
597
        SignatureData dummy_sigdata;
783
597
        if (!CanProvide(script, dummy_sigdata)) {
784
569
            continue;
785
569
        }
786
787
        // Get birthdate from script meta
788
28
        uint64_t creation_time = 0;
789
28
        const auto& it = m_script_metadata.find(CScriptID(script));
790
28
        if (it != m_script_metadata.end()) {
791
4
            creation_time = it->second.nCreateTime;
792
4
        }
793
794
        // InferDescriptor as that will get us all the solving info if it is there
795
28
        std::unique_ptr<Descriptor> desc = InferDescriptor(script, *GetSolvingProvider(script));
796
28
        if (!desc->IsSolvable()) {
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
10
            continue;
800
10
        }
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
18
        {
805
18
            std::string desc_str = desc->ToString();
806
18
            FlatSigningProvider parsed_keys;
807
18
            std::string parse_error;
808
18
            std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error, false);
809
18
            if (parsed_descs.empty()) {
810
0
                continue;
811
0
            }
812
18
        }
813
814
18
        out.solvable_descs.emplace_back(desc->ToString(), creation_time);
815
18
    }
816
817
    // Finalize transaction
818
42
    if (!batch.TxnCommit()) {
819
0
        LogWarning("Error generating descriptors for migration, cannot commit db transaction");
820
0
        return std::nullopt;
821
0
    }
822
823
42
    return out;
824
42
}
825
826
bool LegacyDataSPKM::DeleteRecordsWithDB(WalletBatch& batch)
827
38
{
828
38
    LOCK(cs_KeyStore);
829
38
    return batch.EraseRecords(DBKeys::LEGACY_TYPES);
830
38
}
831
832
std::unique_ptr<DescriptorScriptPubKeyMan> DescriptorScriptPubKeyMan::CreateFromImport(WalletStorage& storage, WalletDescriptor& descriptor, int64_t keypool_size, const FlatSigningProvider& provider)
833
906
{
834
906
    auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, descriptor, keypool_size));
835
906
    LOCK(spkm->cs_desc_man);
836
906
    WalletBatch batch(storage.GetDatabase());
837
906
    spkm->UpdateWithSigningProvider(batch, provider);
838
906
    return spkm;
839
906
}
840
841
std::unique_ptr<DescriptorScriptPubKeyMan> DescriptorScriptPubKeyMan::CreateFromMigration(WalletStorage& storage, WalletBatch& batch, WalletDescriptor& descriptor, int64_t keypool_size, const FlatSigningProvider& provider)
842
134
{
843
134
    auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, descriptor, keypool_size));
844
134
    LOCK(spkm->cs_desc_man);
845
134
    spkm->UpdateWithSigningProvider(batch, provider);
846
134
    return spkm;
847
134
}
848
849
DescriptorScriptPubKeyMan::DescriptorScriptPubKeyMan(WalletStorage& storage, WalletDescriptor& descriptor, int64_t keypool_size, const KeyMap& keys, const CryptedKeyMap& ckeys)
850
2.63k
    : ScriptPubKeyMan(storage),
851
2.63k
    m_map_keys(keys),
852
2.63k
    m_map_crypted_keys(ckeys),
853
2.63k
    m_keypool_size(keypool_size),
854
2.63k
    m_wallet_descriptor(descriptor)
855
2.63k
{
856
2.63k
    if (!keys.empty() && !ckeys.empty()) {
857
1
        throw std::runtime_error("Wallet contains both unencrypted and encrypted keys");
858
1
    }
859
2.63k
    Load();
860
2.63k
}
861
862
std::unique_ptr<DescriptorScriptPubKeyMan> DescriptorScriptPubKeyMan::LoadFromStorage(WalletStorage& storage, WalletDescriptor& descriptor, int64_t keypool_size, const KeyMap& keys, const CryptedKeyMap& ckeys)
863
2.62k
{
864
2.62k
    return std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, descriptor, keypool_size, keys, ckeys));
865
2.62k
}
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
3.79k
{
869
3.79k
    auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, keypool_size));
870
3.79k
    spkm->SetupDescriptorGeneration(batch, master_key, addr_type, internal);
871
3.79k
    return spkm;
872
3.79k
}
873
874
util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetNewDestination(const OutputType type)
875
19.3k
{
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
19.3k
    if (!CanGetAddresses()) {
878
1
        return util::Error{_("No addresses available")};
879
1
    }
880
19.3k
    {
881
19.3k
        LOCK(cs_desc_man);
882
19.3k
        assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
883
19.3k
        std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
884
19.3k
        assert(desc_addr_type);
885
19.3k
        if (type != *desc_addr_type) {
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
19.3k
        TopUp();
890
891
        // Get the scriptPubKey from the descriptor
892
19.3k
        FlatSigningProvider out_keys;
893
19.3k
        std::vector<CScript> scripts_temp;
894
19.3k
        if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
895
            // We can't generate anymore keys
896
0
            return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
897
0
        }
898
19.3k
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
899
            // We can't generate anymore keys
900
8
            return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
901
8
        }
902
903
19.3k
        CTxDestination dest;
904
19.3k
        if (!ExtractDestination(scripts_temp[0], dest)) {
905
0
            return util::Error{_("Error: Cannot extract destination from the generated scriptpubkey")}; // shouldn't happen
906
0
        }
907
19.3k
        m_wallet_descriptor.next_index++;
908
19.3k
        WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
909
19.3k
        return dest;
910
19.3k
    }
911
19.3k
}
912
913
bool DescriptorScriptPubKeyMan::IsMine(const CScript& script) const
914
508k
{
915
508k
    LOCK(cs_desc_man);
916
508k
    return m_map_script_pub_keys.contains(script);
917
508k
}
918
919
bool DescriptorScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key)
920
719
{
921
719
    LOCK(cs_desc_man);
922
719
    if (!m_map_keys.empty()) {
923
0
        return false;
924
0
    }
925
926
719
    bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
927
719
    bool keyFail = false;
928
719
    for (const auto& mi : m_map_crypted_keys) {
929
719
        const CPubKey &pubkey = mi.second.first;
930
719
        const std::vector<unsigned char> &crypted_secret = mi.second.second;
931
719
        CKey key;
932
719
        if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
933
0
            keyFail = true;
934
0
            break;
935
0
        }
936
719
        keyPass = true;
937
719
        if (m_decryption_thoroughly_checked)
938
521
            break;
939
719
    }
940
719
    if (keyPass && keyFail) {
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
719
    if (keyFail || !keyPass) {
945
0
        return false;
946
0
    }
947
719
    m_decryption_thoroughly_checked = true;
948
719
    return true;
949
719
}
950
951
bool DescriptorScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
952
103
{
953
103
    LOCK(cs_desc_man);
954
103
    if (!m_map_crypted_keys.empty()) {
955
0
        return false;
956
0
    }
957
958
103
    for (const KeyMap::value_type& key_in : m_map_keys)
959
103
    {
960
103
        const CKey &key = key_in.second;
961
103
        CPubKey pubkey = key.GetPubKey();
962
103
        CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
963
103
        std::vector<unsigned char> crypted_secret;
964
103
        if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
965
0
            return false;
966
0
        }
967
103
        m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
968
103
        batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
969
103
    }
970
103
    m_map_keys.clear();
971
103
    return true;
972
103
}
973
974
util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, int64_t& index)
975
2.17k
{
976
2.17k
    LOCK(cs_desc_man);
977
2.17k
    auto op_dest = GetNewDestination(type);
978
2.17k
    index = m_wallet_descriptor.next_index - 1;
979
2.17k
    return op_dest;
980
2.17k
}
981
982
void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
983
105
{
984
105
    LOCK(cs_desc_man);
985
    // Only return when the index was the most recent
986
105
    if (m_wallet_descriptor.next_index - 1 == index) {
987
105
        m_wallet_descriptor.next_index--;
988
105
    }
989
105
    WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
990
105
    NotifyCanGetAddressesChanged();
991
105
}
992
993
std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
994
92.0k
{
995
92.0k
    AssertLockHeld(cs_desc_man);
996
92.0k
    if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
997
2.32k
        KeyMap keys;
998
2.32k
        for (const auto& key_pair : m_map_crypted_keys) {
999
2.32k
            const CPubKey& pubkey = key_pair.second.first;
1000
2.32k
            const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
1001
2.32k
            CKey key;
1002
2.32k
            m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
1003
2.32k
                return DecryptKey(encryption_key, crypted_secret, pubkey, key);
1004
2.32k
            });
1005
2.32k
            keys[pubkey.GetID()] = key;
1006
2.32k
        }
1007
2.32k
        return keys;
1008
2.32k
    }
1009
89.7k
    return m_map_keys;
1010
92.0k
}
1011
1012
bool DescriptorScriptPubKeyMan::HasPrivKey(const CKeyID& keyid) const
1013
271
{
1014
271
    AssertLockHeld(cs_desc_man);
1015
271
    return m_map_keys.contains(keyid) || m_map_crypted_keys.contains(keyid);
1016
271
}
1017
1018
std::optional<CKey> DescriptorScriptPubKeyMan::GetKey(const CKeyID& keyid) const
1019
106
{
1020
106
    AssertLockHeld(cs_desc_man);
1021
106
    if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
1022
9
        const auto& it = m_map_crypted_keys.find(keyid);
1023
9
        if (it == m_map_crypted_keys.end()) {
1024
0
            return std::nullopt;
1025
0
        }
1026
9
        const std::vector<unsigned char>& crypted_secret = it->second.second;
1027
9
        CKey key;
1028
9
        if (!Assume(m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
1029
9
            return DecryptKey(encryption_key, crypted_secret, it->second.first, key);
1030
9
        }))) {
1031
0
            return std::nullopt;
1032
0
        }
1033
9
        return key;
1034
9
    }
1035
97
    const auto& it = m_map_keys.find(keyid);
1036
97
    if (it == m_map_keys.end()) {
1037
9
        return std::nullopt;
1038
9
    }
1039
88
    return it->second;
1040
97
}
1041
1042
bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
1043
72.3k
{
1044
72.3k
    WalletBatch batch(m_storage.GetDatabase());
1045
72.3k
    if (!batch.TxnBegin()) return false;
1046
72.3k
    bool res = TopUpWithDB(batch, size);
1047
72.3k
    if (!batch.TxnCommit()) throw std::runtime_error(strprintf("Error during descriptors keypool top up. Cannot commit changes for wallet [%s]", m_storage.LogName()));
1048
72.3k
    return res;
1049
72.3k
}
1050
1051
bool DescriptorScriptPubKeyMan::TopUpWithDB(WalletBatch& batch, unsigned int size)
1052
77.2k
{
1053
77.2k
    LOCK(cs_desc_man);
1054
77.2k
    std::set<CScript> new_spks;
1055
77.2k
    unsigned int target_size;
1056
77.2k
    if (size > 0) {
1057
72
        target_size = size;
1058
77.1k
    } else {
1059
77.1k
        target_size = m_keypool_size;
1060
77.1k
    }
1061
1062
    // Calculate the new range_end
1063
77.2k
    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
77.2k
    if (!m_wallet_descriptor.descriptor->IsRange()) {
1067
11.7k
        new_range_end = 1;
1068
11.7k
        m_wallet_descriptor.range_end = 1;
1069
11.7k
        m_wallet_descriptor.range_start = 0;
1070
11.7k
    }
1071
1072
77.2k
    FlatSigningProvider provider;
1073
77.2k
    provider.keys = GetKeys();
1074
1075
77.2k
    uint256 id = GetID();
1076
506k
    for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
1077
429k
        FlatSigningProvider out_keys;
1078
429k
        std::vector<CScript> scripts_temp;
1079
429k
        DescriptorCache temp_cache;
1080
        // Maybe we have a cached xpub and we can expand from the cache first
1081
429k
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1082
28.5k
            if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
1083
28.5k
        }
1084
        // Add all of the scriptPubKeys to the scriptPubKey set
1085
429k
        new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1086
430k
        for (const CScript& script : scripts_temp) {
1087
430k
            m_map_script_pub_keys[script] = i;
1088
430k
        }
1089
477k
        for (const auto& pk_pair : out_keys.pubkeys) {
1090
477k
            const CPubKey& pubkey = pk_pair.second;
1091
477k
            if (m_map_pubkeys.contains(pubkey)) {
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
10.6k
                continue;
1095
10.6k
            }
1096
467k
            m_map_pubkeys[pubkey] = i;
1097
467k
        }
1098
        // Merge and write the cache
1099
429k
        DescriptorCache new_items = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
1100
429k
        if (!batch.WriteDescriptorCacheItems(id, new_items)) {
1101
0
            throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
1102
0
        }
1103
429k
        m_max_cached_index++;
1104
429k
    }
1105
77.1k
    m_wallet_descriptor.range_end = new_range_end;
1106
77.1k
    batch.WriteDescriptor(GetID(), m_wallet_descriptor);
1107
1108
    // By this point, the cache size should be the size of the entire range
1109
77.1k
    assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
1110
1111
77.1k
    m_storage.TopUpCallback(new_spks, this);
1112
77.1k
    NotifyCanGetAddressesChanged();
1113
77.1k
    return true;
1114
77.1k
}
1115
1116
std::vector<WalletDestination> DescriptorScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
1117
47.2k
{
1118
47.2k
    LOCK(cs_desc_man);
1119
47.2k
    std::vector<WalletDestination> result;
1120
47.2k
    if (IsMine(script)) {
1121
47.2k
        int32_t index = m_map_script_pub_keys[script];
1122
47.2k
        if (index >= m_wallet_descriptor.next_index) {
1123
495
            WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
1124
495
            auto out_keys = std::make_unique<FlatSigningProvider>();
1125
495
            std::vector<CScript> scripts_temp;
1126
24.9k
            while (index >= m_wallet_descriptor.next_index) {
1127
24.4k
                if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
1128
0
                    throw std::runtime_error(std::string(__func__) + ": Unable to expand descriptor from cache");
1129
0
                }
1130
24.4k
                CTxDestination dest;
1131
24.4k
                ExtractDestination(scripts_temp[0], dest);
1132
24.4k
                result.push_back({dest, std::nullopt});
1133
24.4k
                m_wallet_descriptor.next_index++;
1134
24.4k
            }
1135
495
        }
1136
47.2k
        if (!TopUp()) {
1137
0
            WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1138
0
        }
1139
47.2k
    }
1140
1141
47.2k
    return result;
1142
47.2k
}
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)) {
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
4.58k
{
1155
4.58k
    AssertLockHeld(cs_desc_man);
1156
4.58k
    assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
1157
1158
    // Check if provided key already exists
1159
4.58k
    if (m_map_keys.contains(pubkey.GetID()) ||
1160
4.58k
        m_map_crypted_keys.contains(pubkey.GetID())) {
1161
8
        return true;
1162
8
    }
1163
1164
4.57k
    if (m_storage.HasEncryptionKeys()) {
1165
170
        if (m_storage.IsLocked()) {
1166
0
            return false;
1167
0
        }
1168
1169
170
        std::vector<unsigned char> crypted_secret;
1170
170
        CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
1171
170
        if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
1172
170
                return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
1173
170
            })) {
1174
0
            return false;
1175
0
        }
1176
1177
170
        m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1178
170
        return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1179
4.40k
    } else {
1180
4.40k
        m_map_keys[pubkey.GetID()] = key;
1181
4.40k
        return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
1182
4.40k
    }
1183
4.57k
}
1184
1185
void DescriptorScriptPubKeyMan::SetupDescriptorGeneration(WalletBatch& batch, const CExtKey& master_key, OutputType addr_type, bool internal)
1186
3.79k
{
1187
3.79k
    LOCK(cs_desc_man);
1188
3.79k
    Assert(m_storage.IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
1189
3.79k
    Assert(!m_wallet_descriptor.descriptor);
1190
1191
3.79k
    m_wallet_descriptor = GenerateWalletDescriptor(master_key.Neuter(), addr_type, internal);
1192
1193
    // Store the master private key, and descriptor
1194
3.79k
    if (!AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey())) {
1195
0
        throw std::runtime_error(std::string(__func__) + ": writing descriptor master private key failed");
1196
0
    }
1197
3.79k
    if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
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
3.79k
    if (m_storage.HasEncryptionKeys()) {
1203
146
        m_decryption_thoroughly_checked = true;
1204
146
    }
1205
1206
    // TopUp
1207
3.79k
    TopUpWithDB(batch);
1208
1209
3.79k
    m_storage.UnsetBlankWalletFlag(batch);
1210
3.79k
}
1211
1212
bool DescriptorScriptPubKeyMan::IsHDEnabled() const
1213
68
{
1214
68
    LOCK(cs_desc_man);
1215
68
    return m_wallet_descriptor.descriptor->IsRange();
1216
68
}
1217
1218
bool DescriptorScriptPubKeyMan::CanGetAddresses(bool internal) const
1219
30.7k
{
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
30.7k
    LOCK(cs_desc_man);
1223
30.7k
    return m_wallet_descriptor.descriptor->IsSingleType() &&
1224
30.7k
           m_wallet_descriptor.descriptor->IsRange() &&
1225
30.7k
           (HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end || m_wallet_descriptor.descriptor->CanSelfExpand());
1226
30.7k
}
1227
1228
bool DescriptorScriptPubKeyMan::HavePrivateKeys() const
1229
256k
{
1230
256k
    LOCK(cs_desc_man);
1231
256k
    return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
1232
256k
}
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
9.46k
{
1242
9.46k
    LOCK(cs_desc_man);
1243
9.46k
    return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
1244
9.46k
}
1245
1246
int64_t DescriptorScriptPubKeyMan::GetTimeFirstKey() const
1247
7.48k
{
1248
7.48k
    LOCK(cs_desc_man);
1249
7.48k
    return m_wallet_descriptor.creation_time;
1250
7.48k
}
1251
1252
std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
1253
372k
{
1254
372k
    LOCK(cs_desc_man);
1255
1256
    // Find the index of the script
1257
372k
    auto it = m_map_script_pub_keys.find(script);
1258
372k
    if (it == m_map_script_pub_keys.end()) {
1259
148k
        return nullptr;
1260
148k
    }
1261
224k
    int32_t index = it->second;
1262
1263
224k
    return GetSigningProvider(index, include_private);
1264
372k
}
1265
1266
std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
1267
49.3k
{
1268
49.3k
    LOCK(cs_desc_man);
1269
1270
    // Find index of the pubkey
1271
49.3k
    auto it = m_map_pubkeys.find(pubkey);
1272
49.3k
    if (it == m_map_pubkeys.end()) {
1273
48.0k
        return nullptr;
1274
48.0k
    }
1275
1.30k
    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
1.30k
    std::unique_ptr<FlatSigningProvider> out = GetSigningProvider(index, true);
1279
1.30k
    if (!out->HaveKey(pubkey.GetID())) {
1280
830
        return nullptr;
1281
830
    }
1282
477
    return out;
1283
1.30k
}
1284
1285
std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
1286
225k
{
1287
225k
    AssertLockHeld(cs_desc_man);
1288
1289
225k
    std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
1290
1291
    // Fetch SigningProvider from cache to avoid re-deriving
1292
225k
    auto it = m_map_signing_providers.find(index);
1293
225k
    if (it != m_map_signing_providers.end()) {
1294
209k
        out_keys->Merge(FlatSigningProvider{it->second});
1295
209k
    } else {
1296
        // Get the scripts, keys, and key origins for this script
1297
16.2k
        std::vector<CScript> scripts_temp;
1298
16.2k
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
1299
1300
        // Cache SigningProvider so we don't need to re-derive if we need this SigningProvider again
1301
16.2k
        m_map_signing_providers[index] = *out_keys;
1302
16.2k
    }
1303
1304
225k
    if (HavePrivateKeys() && include_private) {
1305
12.4k
        FlatSigningProvider master_provider;
1306
12.4k
        master_provider.keys = GetKeys();
1307
12.4k
        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
12.4k
        out_keys->musig2_secnonces = &m_musig2_secnonces;
1312
12.4k
    }
1313
1314
225k
    return out_keys;
1315
225k
}
1316
1317
std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
1318
287k
{
1319
287k
    return GetSigningProvider(script, false);
1320
287k
}
1321
1322
bool DescriptorScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
1323
266k
{
1324
266k
    return IsMine(script);
1325
266k
}
1326
1327
bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
1328
17.7k
{
1329
17.7k
    std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1330
60.6k
    for (const auto& coin_pair : coins) {
1331
60.6k
        std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
1332
60.6k
        if (!coin_keys) {
1333
51.4k
            continue;
1334
51.4k
        }
1335
9.27k
        keys->Merge(std::move(*coin_keys));
1336
9.27k
    }
1337
1338
17.7k
    return ::SignTransaction(tx, keys.get(), coins, {.sighash_type = sighash}, input_errors);
1339
17.7k
}
1340
1341
SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
1342
9
{
1343
9
    std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
1344
9
    if (!keys) {
1345
0
        return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
1346
0
    }
1347
1348
9
    CKey key;
1349
9
    if (!keys->GetKey(ToKeyID(pkhash), key)) {
1350
0
        return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
1351
0
    }
1352
1353
9
    if (!MessageSign(key, message, str_sig)) {
1354
0
        return SigningResult::SIGNING_FAILED;
1355
0
    }
1356
9
    return SigningResult::OK;
1357
9
}
1358
1359
std::optional<PSBTError> DescriptorScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, const common::PSBTFillOptions& options, int* n_signed) const
1360
9.73k
{
1361
9.73k
    if (n_signed) {
1362
9.73k
        *n_signed = 0;
1363
9.73k
    }
1364
42.0k
    for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
1365
32.3k
        PSBTInput& input = psbtx.inputs.at(i);
1366
1367
32.3k
        if (PSBTInputSigned(input)) {
1368
7.96k
            continue;
1369
7.96k
        }
1370
1371
        // Get the scriptPubKey to know which SigningProvider to use
1372
24.3k
        CScript script;
1373
24.3k
        if (!input.witness_utxo.IsNull()) {
1374
18.2k
            script = input.witness_utxo.scriptPubKey;
1375
18.2k
        } else if (input.non_witness_utxo) {
1376
5.86k
            if (input.prev_out >= input.non_witness_utxo->vout.size()) {
1377
1
                return PSBTError::MISSING_INPUTS;
1378
1
            }
1379
5.86k
            script = input.non_witness_utxo->vout[input.prev_out].scriptPubKey;
1380
5.86k
        } else {
1381
            // There's no UTXO so we can just skip this now
1382
237
            continue;
1383
237
        }
1384
1385
24.1k
        std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1386
24.1k
        std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, /*include_private=*/options.sign);
1387
24.1k
        if (script_keys) {
1388
3.67k
            keys->Merge(std::move(*script_keys));
1389
20.4k
        } else {
1390
            // Maybe there are pubkeys listed that we can sign for
1391
20.4k
            std::vector<CPubKey> pubkeys;
1392
20.4k
            pubkeys.reserve(input.hd_keypaths.size() + 2);
1393
1394
            // ECDSA Pubkeys
1395
20.4k
            for (const auto& [pk, _] : input.hd_keypaths) {
1396
13.1k
                pubkeys.push_back(pk);
1397
13.1k
            }
1398
1399
            // Taproot output pubkey
1400
20.4k
            std::vector<std::vector<unsigned char>> sols;
1401
20.4k
            if (Solver(script, sols) == TxoutType::WITNESS_V1_TAPROOT) {
1402
3.76k
                sols[0].insert(sols[0].begin(), 0x02);
1403
3.76k
                pubkeys.emplace_back(sols[0]);
1404
3.76k
                sols[0][0] = 0x03;
1405
3.76k
                pubkeys.emplace_back(sols[0]);
1406
3.76k
            }
1407
1408
            // Taproot pubkeys
1409
20.4k
            for (const auto& pk_pair : input.m_tap_bip32_paths) {
1410
14.3k
                const XOnlyPubKey& pubkey = pk_pair.first;
1411
28.7k
                for (unsigned char prefix : {0x02, 0x03}) {
1412
28.7k
                    unsigned char b[33] = {prefix};
1413
28.7k
                    std::copy(pubkey.begin(), pubkey.end(), b + 1);
1414
28.7k
                    CPubKey fullpubkey;
1415
28.7k
                    fullpubkey.Set(b, b + 33);
1416
28.7k
                    pubkeys.push_back(fullpubkey);
1417
28.7k
                }
1418
14.3k
            }
1419
1420
49.3k
            for (const auto& pubkey : pubkeys) {
1421
49.3k
                std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
1422
49.3k
                if (pk_keys) {
1423
476
                    keys->Merge(std::move(*pk_keys));
1424
476
                }
1425
49.3k
            }
1426
20.4k
        }
1427
1428
24.1k
        PSBTError res = SignPSBTInput(HidingSigningProvider(keys.get(), /*hide_secret=*/!options.sign, /*hide_origin=*/!options.bip32_derivs), psbtx, i, &txdata, options, /*out_sigdata=*/nullptr);
1429
24.1k
        if (res != PSBTError::OK && res != PSBTError::INCOMPLETE) {
1430
7
            return res;
1431
7
        }
1432
1433
24.1k
        bool signed_one = PSBTInputSigned(input);
1434
24.1k
        if (n_signed && (signed_one || !options.sign)) {
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
16.1k
            (*n_signed)++;
1439
16.1k
        }
1440
24.1k
    }
1441
1442
    // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
1443
87.5k
    for (unsigned int i = 0; i < psbtx.outputs.size(); ++i) {
1444
77.8k
        std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.outputs.at(i).script);
1445
77.8k
        if (!keys) {
1446
76.8k
            continue;
1447
76.8k
        }
1448
1.01k
        UpdatePSBTOutput(HidingSigningProvider(keys.get(), /*hide_secret=*/true, /*hide_origin=*/!options.bip32_derivs), psbtx, i);
1449
1.01k
    }
1450
1451
9.73k
    return {};
1452
9.73k
}
1453
1454
std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
1455
615
{
1456
615
    std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
1457
615
    if (provider) {
1458
615
        KeyOriginInfo orig;
1459
615
        CKeyID key_id = GetKeyForDestination(*provider, dest);
1460
615
        if (provider->GetKeyOrigin(key_id, orig)) {
1461
527
            LOCK(cs_desc_man);
1462
527
            std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
1463
527
            meta->key_origin = orig;
1464
527
            meta->has_key_origin = true;
1465
527
            meta->nCreateTime = m_wallet_descriptor.creation_time;
1466
527
            return meta;
1467
527
        }
1468
615
    }
1469
88
    return nullptr;
1470
615
}
1471
1472
uint256 DescriptorScriptPubKeyMan::GetID() const
1473
188k
{
1474
188k
    LOCK(cs_desc_man);
1475
188k
    return m_wallet_descriptor.id;
1476
188k
}
1477
1478
void DescriptorScriptPubKeyMan::Load()
1479
2.63k
{
1480
2.63k
    LOCK(cs_desc_man);
1481
2.63k
    std::set<CScript> new_spks;
1482
63.8k
    for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
1483
61.2k
        FlatSigningProvider out_keys;
1484
61.2k
        std::vector<CScript> scripts_temp;
1485
61.2k
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
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
61.2k
        new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1490
62.2k
        for (const CScript& script : scripts_temp) {
1491
62.2k
            if (m_map_script_pub_keys.contains(script)) {
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
62.2k
            m_map_script_pub_keys[script] = i;
1495
62.2k
        }
1496
65.3k
        for (const auto& pk_pair : out_keys.pubkeys) {
1497
65.3k
            const CPubKey& pubkey = pk_pair.second;
1498
65.3k
            if (m_map_pubkeys.contains(pubkey)) {
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
38
                continue;
1502
38
            }
1503
65.2k
            m_map_pubkeys[pubkey] = i;
1504
65.2k
        }
1505
61.2k
        m_max_cached_index++;
1506
61.2k
    }
1507
    // Make sure the wallet knows about our new spks
1508
2.63k
    m_storage.TopUpCallback(new_spks, this);
1509
2.63k
}
1510
1511
bool DescriptorScriptPubKeyMan::HasWalletDescriptor(const WalletDescriptor& desc) const
1512
43
{
1513
43
    LOCK(cs_desc_man);
1514
43
    return !m_wallet_descriptor.id.IsNull() && !desc.id.IsNull() && m_wallet_descriptor.id == desc.id;
1515
43
}
1516
1517
void DescriptorScriptPubKeyMan::WriteDescriptor()
1518
923
{
1519
923
    LOCK(cs_desc_man);
1520
923
    WalletBatch batch(m_storage.GetDatabase());
1521
923
    if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
1522
0
        throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
1523
0
    }
1524
923
}
1525
1526
WalletDescriptor DescriptorScriptPubKeyMan::GetWalletDescriptor() const
1527
28.7k
{
1528
28.7k
    return m_wallet_descriptor;
1529
28.7k
}
1530
1531
std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
1532
473
{
1533
473
    return GetScriptPubKeys(0);
1534
473
}
1535
1536
std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys(int32_t minimum_index) const
1537
573
{
1538
573
    LOCK(cs_desc_man);
1539
573
    std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
1540
573
    script_pub_keys.reserve(m_map_script_pub_keys.size());
1541
1542
27.3k
    for (auto const& [script_pub_key, index] : m_map_script_pub_keys) {
1543
27.3k
        if (index >= minimum_index) script_pub_keys.insert(script_pub_key);
1544
27.3k
    }
1545
573
    return script_pub_keys;
1546
573
}
1547
1548
int32_t DescriptorScriptPubKeyMan::GetEndRange() const
1549
4.95k
{
1550
4.95k
    return m_max_cached_index + 1;
1551
4.95k
}
1552
1553
bool DescriptorScriptPubKeyMan::GetDescriptorString(std::string& out, const bool priv) const
1554
2.45k
{
1555
2.45k
    LOCK(cs_desc_man);
1556
1557
2.45k
    FlatSigningProvider provider;
1558
2.45k
    provider.keys = GetKeys();
1559
1560
2.45k
    if (priv) {
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
657
        return m_wallet_descriptor.descriptor->ToPrivateString(provider, out);
1565
657
    }
1566
1567
1.79k
    return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
1568
2.45k
}
1569
1570
void DescriptorScriptPubKeyMan::UpgradeDescriptorCache()
1571
44
{
1572
44
    LOCK(cs_desc_man);
1573
44
    if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED)) {
1574
0
        return;
1575
0
    }
1576
1577
    // Skip if we have the last hardened xpub cache
1578
44
    if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
1579
38
        return;
1580
38
    }
1581
1582
    // Expand the descriptor
1583
6
    FlatSigningProvider provider;
1584
6
    provider.keys = GetKeys();
1585
6
    FlatSigningProvider out_keys;
1586
6
    std::vector<CScript> scripts_temp;
1587
6
    DescriptorCache temp_cache;
1588
6
    if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
1589
0
        throw std::runtime_error("Unable to expand descriptor");
1590
0
    }
1591
1592
    // Cache the last hardened xpubs
1593
6
    DescriptorCache diff = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
1594
6
    if (!WalletBatch(m_storage.GetDatabase()).WriteDescriptorCacheItems(GetID(), diff)) {
1595
0
        throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
1596
0
    }
1597
6
}
1598
1599
util::Result<void> DescriptorScriptPubKeyMan::UpdateWalletDescriptor(WalletDescriptor& descriptor, const FlatSigningProvider& provider)
1600
21
{
1601
21
    LOCK(cs_desc_man);
1602
21
    std::string error;
1603
21
    if (!CanUpdateToWalletDescriptor(descriptor, error)) {
1604
3
        return util::Error{Untranslated(std::move(error))};
1605
3
    }
1606
1607
18
    m_map_pubkeys.clear();
1608
18
    m_map_script_pub_keys.clear();
1609
18
    m_max_cached_index = -1;
1610
18
    m_wallet_descriptor = descriptor;
1611
1612
18
    WalletBatch batch(m_storage.GetDatabase());
1613
18
    UpdateWithSigningProvider(batch, provider);
1614
18
    NotifyFirstKeyTimeChanged(this, m_wallet_descriptor.creation_time);
1615
18
    return {};
1616
21
}
1617
1618
void DescriptorScriptPubKeyMan::UpdateWithSigningProvider(WalletBatch& batch, const FlatSigningProvider& signing_provider)
1619
1.05k
{
1620
1.05k
    AssertLockHeld(cs_desc_man);
1621
    // Add the private keys to the descriptor
1622
1.05k
    for (const auto& entry : signing_provider.keys) {
1623
792
        const CKey& key = entry.second;
1624
792
        if (!AddDescriptorKeyWithDB(batch, key, key.GetPubKey())) {
1625
0
            throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
1626
0
        }
1627
792
    }
1628
1629
    // Top up key pool, to generate scriptPubKeys
1630
1.05k
    if (!TopUpWithDB(batch)) {
1631
1
        throw std::runtime_error("Could not top up scriptPubKeys");
1632
1
    }
1633
1.05k
}
1634
1635
bool DescriptorScriptPubKeyMan::CanUpdateToWalletDescriptor(const WalletDescriptor& descriptor, std::string& error)
1636
21
{
1637
21
    LOCK(cs_desc_man);
1638
21
    if (!HasWalletDescriptor(descriptor)) {
1639
0
        error = "can only update matching descriptor";
1640
0
        return false;
1641
0
    }
1642
1643
21
    if (!descriptor.descriptor->IsRange()) {
1644
        // Skip range check for non-range descriptors
1645
6
        return true;
1646
6
    }
1647
1648
15
    if (descriptor.range_start > m_wallet_descriptor.range_start ||
1649
15
        descriptor.range_end < m_wallet_descriptor.range_end) {
1650
        // Use inclusive range for error
1651
3
        error = strprintf("new range must include current range = [%d,%d]",
1652
3
                          m_wallet_descriptor.range_start,
1653
3
                          m_wallet_descriptor.range_end - 1);
1654
3
        return false;
1655
3
    }
1656
1657
12
    return true;
1658
15
}
1659
} // namespace wallet