Coverage Report

Created: 2026-08-14 20:23

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.95k
{
65
2.95k
    return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
66
2.95k
}
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
8.02k
{
88
8.02k
    IsMineResult ret = IsMineResult::NO;
89
90
8.02k
    std::vector<valtype> vSolutions;
91
8.02k
    TxoutType whichType = Solver(scriptPubKey, vSolutions);
92
93
8.02k
    CKeyID keyID;
94
8.02k
    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
648
    case TxoutType::PUBKEY:
102
648
        keyID = CPubKey(vSolutions[0]).GetID();
103
648
        if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
104
0
            return IsMineResult::INVALID;
105
0
        }
106
648
        if (keystore.HaveKey(keyID)) {
107
618
            ret = std::max(ret, IsMineResult::SPENDABLE);
108
618
        }
109
648
        break;
110
1.60k
    case TxoutType::WITNESS_V0_KEYHASH:
111
1.60k
    {
112
1.60k
        if (sigversion == IsMineSigVersion::WITNESS_V0) {
113
            // P2WPKH inside P2WSH is invalid.
114
0
            return IsMineResult::INVALID;
115
0
        }
116
1.60k
        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.58k
        ret = std::max(ret, LegacyWalletIsMineInnerDONOTUSE(keystore, GetScriptForDestination(PKHash(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
123
1.58k
        break;
124
1.60k
    }
125
2.26k
    case TxoutType::PUBKEYHASH:
126
2.26k
        keyID = CKeyID(uint160(vSolutions[0]));
127
2.26k
        if (!PermitsUncompressed(sigversion)) {
128
1.60k
            CPubKey pubkey;
129
1.60k
            if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
130
5
                return IsMineResult::INVALID;
131
5
            }
132
1.60k
        }
133
2.25k
        if (keystore.HaveKey(keyID)) {
134
2.18k
            ret = std::max(ret, IsMineResult::SPENDABLE);
135
2.18k
        }
136
2.25k
        break;
137
2.25k
    case TxoutType::SCRIPTHASH:
138
2.25k
    {
139
2.25k
        if (sigversion != IsMineSigVersion::TOP) {
140
            // P2SH inside P2WSH or P2SH is invalid.
141
10
            return IsMineResult::INVALID;
142
10
        }
143
2.24k
        CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
144
2.24k
        CScript subscript;
145
2.24k
        if (keystore.GetCScript(scriptID, subscript)) {
146
1.05k
            ret = std::max(ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
147
1.05k
        }
148
2.24k
        break;
149
2.25k
    }
150
1.18k
    case TxoutType::WITNESS_V0_SCRIPTHASH:
151
1.18k
    {
152
1.18k
        if (sigversion == IsMineSigVersion::WITNESS_V0) {
153
            // P2WSH inside P2WSH is invalid.
154
5
            return IsMineResult::INVALID;
155
5
        }
156
1.17k
        if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
157
1.10k
            break;
158
1.10k
        }
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
1.17k
    }
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
8.02k
    } // no default case, so the compiler can warn about missing cases
193
194
8.00k
    if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
195
158
        ret = std::max(ret, IsMineResult::WATCH_ONLY);
196
158
    }
197
8.00k
    return ret;
198
8.02k
}
199
200
} // namespace
201
202
bool LegacyDataSPKM::IsMine(const CScript& script) const
203
4.55k
{
204
4.55k
    switch (LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP)) {
205
20
    case IsMineResult::INVALID:
206
1.59k
    case IsMineResult::NO:
207
1.59k
        return false;
208
158
    case IsMineResult::WATCH_ONLY:
209
2.96k
    case IsMineResult::SPENDABLE:
210
2.96k
        return true;
211
4.55k
    }
212
4.55k
    assert(false);
213
0
}
214
215
bool LegacyDataSPKM::CheckDecryptionKey(const CKeyingMaterial& master_key)
216
3
{
217
3
    {
218
3
        LOCK(cs_KeyStore);
219
3
        assert(mapKeys.empty());
220
221
3
        bool keyPass = mapCryptedKeys.empty(); // Always pass when there are no encrypted keys
222
3
        bool keyFail = false;
223
3
        CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
224
3
        WalletBatch batch(m_storage.GetDatabase());
225
63
        for (; mi != mapCryptedKeys.end(); ++mi)
226
61
        {
227
61
            const CPubKey &vchPubKey = (*mi).second.first;
228
61
            const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
229
61
            CKey key;
230
61
            if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
231
0
            {
232
0
                keyFail = true;
233
0
                break;
234
0
            }
235
61
            keyPass = true;
236
61
            if (fDecryptionThoroughlyChecked)
237
1
                break;
238
60
            else {
239
                // Rewrite these encrypted keys with checksums
240
60
                batch.WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
241
60
            }
242
61
        }
243
3
        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
3
        if (keyFail || !keyPass)
249
0
            return false;
250
3
        fDecryptionThoroughlyChecked = true;
251
3
    }
252
0
    return true;
253
3
}
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
787
{
262
787
    IsMineResult ismine = LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
263
787
    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
759
    } else {
269
        // If, given the stuff in sigdata, we could make a valid signature, then we can provide for this script
270
759
        ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
271
759
        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
758
        return false;
280
759
    }
281
787
}
282
283
bool LegacyDataSPKM::LoadKey(const CKey& key, const CPubKey &pubkey)
284
243
{
285
243
    return AddKeyPubKeyInner(key, pubkey);
286
243
}
287
288
bool LegacyDataSPKM::LoadCScript(const CScript& redeemScript)
289
90
{
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
90
    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
90
    return FillableSigningProvider::AddCScript(redeemScript);
301
90
}
302
303
void LegacyDataSPKM::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
304
331
{
305
331
    LOCK(cs_KeyStore);
306
331
    mapKeyMetadata[keyID] = meta;
307
331
}
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
243
{
317
243
    LOCK(cs_KeyStore);
318
243
    return FillableSigningProvider::AddKeyPubKey(key, pubkey);
319
243
}
320
321
bool LegacyDataSPKM::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid)
322
84
{
323
    // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
324
84
    if (!checksum_valid) {
325
60
        fDecryptionThoroughlyChecked = false;
326
60
    }
327
328
84
    return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
329
84
}
330
331
bool LegacyDataSPKM::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
332
84
{
333
84
    LOCK(cs_KeyStore);
334
84
    assert(mapKeys.empty());
335
336
84
    mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
337
84
    ImplicitlyLearnRelatedKeyScripts(vchPubKey);
338
84
    return true;
339
84
}
340
341
bool LegacyDataSPKM::HaveWatchOnly(const CScript &dest) const
342
2.56k
{
343
2.56k
    LOCK(cs_KeyStore);
344
2.56k
    return setWatchOnly.contains(dest);
345
2.56k
}
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
38
{
373
38
    LOCK(cs_KeyStore);
374
38
    m_hd_chain = chain;
375
38
}
376
377
void LegacyDataSPKM::AddInactiveHDChain(const CHDChain& chain)
378
7
{
379
7
    LOCK(cs_KeyStore);
380
7
    assert(!chain.seed_id.IsNull());
381
7
    m_inactive_hd_chains[chain.seed_id] = chain;
382
7
}
383
384
bool LegacyDataSPKM::HaveKey(const CKeyID &address) const
385
3.00k
{
386
3.00k
    LOCK(cs_KeyStore);
387
3.00k
    if (!m_storage.HasEncryptionKeys()) {
388
2.41k
        return FillableSigningProvider::HaveKey(address);
389
2.41k
    }
390
594
    return mapCryptedKeys.contains(address);
391
3.00k
}
392
393
bool LegacyDataSPKM::GetKey(const CKeyID &address, CKey& keyOut) const
394
1.56k
{
395
1.56k
    LOCK(cs_KeyStore);
396
1.56k
    if (!m_storage.HasEncryptionKeys()) {
397
1.52k
        return FillableSigningProvider::GetKey(address, keyOut);
398
1.52k
    }
399
400
39
    CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
401
39
    if (mi != mapCryptedKeys.end())
402
39
    {
403
39
        const CPubKey &vchPubKey = (*mi).second.first;
404
39
        const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
405
39
        return m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
406
39
            return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey, keyOut);
407
39
        });
408
39
    }
409
0
    return false;
410
39
}
411
412
bool LegacyDataSPKM::GetKeyOrigin(const CKeyID& keyID, KeyOriginInfo& info) const
413
195
{
414
195
    CKeyMetadata meta;
415
195
    {
416
195
        LOCK(cs_KeyStore);
417
195
        auto it = mapKeyMetadata.find(keyID);
418
195
        if (it == mapKeyMetadata.end()) {
419
56
            return false;
420
56
        }
421
139
        meta = it->second;
422
139
    }
423
139
    if (meta.has_key_origin) {
424
42
        info.fingerprint = meta.key_origin.fingerprint;
425
42
        info.path = meta.key_origin.path;
426
97
    } else { // Single pubkeys get the master fingerprint of themselves
427
97
        info.fingerprint = keyID.fingerprint();
428
97
    }
429
139
    return true;
430
195
}
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.64k
{
445
1.64k
    LOCK(cs_KeyStore);
446
1.64k
    if (!m_storage.HasEncryptionKeys()) {
447
1.31k
        if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
448
77
            return GetWatchPubKey(address, vchPubKeyOut);
449
77
        }
450
1.23k
        return true;
451
1.31k
    }
452
453
330
    CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
454
330
    if (mi != mapCryptedKeys.end())
455
330
    {
456
330
        vchPubKeyOut = (*mi).second.first;
457
330
        return true;
458
330
    }
459
    // Check for watch-only pubkeys
460
0
    return GetWatchPubKey(address, vchPubKeyOut);
461
330
}
462
463
std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetCandidateScriptPubKeys() const
464
92
{
465
92
    LOCK(cs_KeyStore);
466
92
    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
618
    const auto& add_pubkey = [&candidate_spks](const CPubKey& pub) -> void {
470
618
        candidate_spks.insert(GetScriptForRawPubKey(pub));
471
618
        candidate_spks.insert(GetScriptForDestination(PKHash(pub)));
472
473
618
        CScript wpkh = GetScriptForDestination(WitnessV0KeyHash(pub));
474
618
        candidate_spks.insert(wpkh);
475
618
        candidate_spks.insert(GetScriptForDestination(ScriptHash(wpkh)));
476
618
    };
477
486
    for (const auto& [_, key] : mapKeys) {
478
486
        add_pubkey(key.GetPubKey());
479
486
    }
480
132
    for (const auto& [_, ckeypair] : mapCryptedKeys) {
481
132
        add_pubkey(ckeypair.first);
482
132
    }
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
794
    const auto& add_script = [&candidate_spks](const CScript& script) -> void {
489
794
        candidate_spks.insert(script);
490
794
        candidate_spks.insert(GetScriptForDestination(ScriptHash(script)));
491
492
794
        CScript wsh = GetScriptForDestination(WitnessV0ScriptHash(script));
493
794
        candidate_spks.insert(wsh);
494
794
        candidate_spks.insert(GetScriptForDestination(ScriptHash(wsh)));
495
794
    };
496
696
    for (const auto& [_, script] : mapScripts) {
497
696
        add_script(script);
498
696
    }
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
92
    return candidate_spks;
507
92
}
508
509
std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetScriptPubKeys() const
510
46
{
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
46
    std::unordered_set<CScript, SaltedSipHasher> spks;
515
2.09k
    for (const CScript& script : GetCandidateScriptPubKeys()) {
516
2.09k
        if (IsMine(script)) {
517
1.29k
            spks.insert(script);
518
1.29k
        }
519
2.09k
    }
520
521
46
    return spks;
522
46
}
523
524
std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetNotMineScriptPubKeys() const
525
42
{
526
42
    LOCK(cs_KeyStore);
527
42
    std::unordered_set<CScript, SaltedSipHasher> spks;
528
45
    for (const CScript& script : setWatchOnly) {
529
45
        if (!IsMine(script)) spks.insert(script);
530
45
    }
531
42
    return spks;
532
42
}
533
534
std::optional<MigrationData> LegacyDataSPKM::MigrateToDescriptor()
535
46
{
536
46
    LOCK(cs_KeyStore);
537
46
    if (m_storage.IsLocked()) {
538
0
        return std::nullopt;
539
0
    }
540
541
46
    MigrationData out;
542
543
46
    std::unordered_set<CScript, SaltedSipHasher> spks{GetScriptPubKeys()};
544
545
    // Get all key ids
546
46
    std::set<CKeyID> keyids;
547
243
    for (const auto& key_pair : mapKeys) {
548
243
        keyids.insert(key_pair.first);
549
243
    }
550
66
    for (const auto& key_pair : mapCryptedKeys) {
551
66
        keyids.insert(key_pair.first);
552
66
    }
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
355
    for (auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
557
309
        const CKeyID& keyid = *keyid_it;
558
309
        const auto& it = mapKeyMetadata.find(keyid);
559
309
        if (it != mapKeyMetadata.end()) {
560
309
            const CKeyMetadata& meta = it->second;
561
309
            if (meta.hdKeypath == "s" || meta.hdKeypath == "m") {
562
40
                keyid_it++;
563
40
                continue;
564
40
            }
565
269
            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
217
                keyid_it = keyids.erase(keyid_it);
567
217
                continue;
568
217
            }
569
269
        }
570
52
        keyid_it++;
571
52
    }
572
573
46
    WalletBatch batch(m_storage.GetDatabase());
574
46
    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
92
    for (const CKeyID& keyid : keyids) {
581
92
        CKey key;
582
92
        if (!GetKey(keyid, key)) {
583
0
            assert(false);
584
0
        }
585
586
        // Get birthdate from key meta
587
92
        uint64_t creation_time = 0;
588
92
        const auto& it = mapKeyMetadata.find(keyid);
589
92
        if (it != mapKeyMetadata.end()) {
590
92
            creation_time = it->second.nCreateTime;
591
92
        }
592
593
        // Get the key origin
594
        // Maybe this doesn't matter because floating keys here shouldn't have origins
595
92
        KeyOriginInfo info;
596
92
        bool has_info = GetKeyOrigin(keyid, info);
597
92
        std::string origin_str = has_info ? "[" + HexStr(info.fingerprint) + FormatHDKeypath(info.path) + "]" : "";
598
599
        // Construct the combo descriptor
600
92
        std::string desc_str = "combo(" + origin_str + HexStr(key.GetPubKey()) + ")";
601
92
        FlatSigningProvider provider;
602
92
        std::string error;
603
92
        std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, provider, error, false);
604
92
        CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
605
92
        WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
606
607
        // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
608
92
        provider.keys.emplace(key.GetPubKey().GetID(), key);
609
92
        auto desc_spk_man = DescriptorScriptPubKeyMan::CreateFromMigration(m_storage, batch, w_desc, /*keypool_size=*/0, provider);
610
92
        auto desc_spks = desc_spk_man->GetScriptPubKeys();
611
612
        // Remove the scriptPubKeys from our current set
613
366
        for (const CScript& spk : desc_spks) {
614
366
            size_t erased = spks.erase(spk);
615
366
            assert(erased == 1);
616
366
            assert(IsMine(spk));
617
366
        }
618
619
92
        out.desc_spkms.push_back(std::move(desc_spk_man));
620
92
    }
621
622
    // Handle HD keys by using the CHDChains
623
46
    std::set<CHDChain> chains;
624
46
    chains.insert(m_hd_chain);
625
46
    for (const auto& chain_pair : m_inactive_hd_chains) {
626
4
        chains.insert(chain_pair.second);
627
4
    }
628
629
46
    bool can_support_hd_split_feature = m_hd_chain.nVersion >= CHDChain::VERSION_HD_CHAIN_SPLIT;
630
631
46
    std::set<CExtPubKey> master_xpubs;
632
50
    for (const CHDChain& chain : chains) {
633
50
        if (chain.seed_id.IsNull()) continue;
634
635
        // Get the master xprv
636
39
        CKey seed_key;
637
39
        if (!GetKey(chain.seed_id, seed_key)) {
638
0
            assert(false);
639
0
        }
640
39
        CExtKey master_key;
641
39
        master_key.SetSeed(seed_key);
642
643
        // Get the xpub and verify that we haven't already seen this xpub before
644
39
        CExtPubKey master_xpub = master_key.Neuter();
645
39
        const auto& [_, inserted] = master_xpubs.insert(master_xpub);
646
39
        if (!inserted) continue;
647
648
117
        for (int i = 0; i < 2; ++i) {
649
            // Skip if doing internal chain and split chain is not supported
650
78
            if (i == 1 && !can_support_hd_split_feature) {
651
3
                continue;
652
3
            }
653
654
            // Make the combo descriptor
655
75
            std::string xpub = EncodeExtPubKey(master_key.Neuter());
656
75
            std::string desc_str = "combo(" + xpub + "/0h/" + ToString(i) + "h/*h)";
657
75
            FlatSigningProvider provider;
658
75
            std::string error;
659
75
            std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, provider, error, false);
660
75
            CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
661
75
            uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
662
75
            WalletDescriptor w_desc(std::move(descs.at(0)), 0, 0, chain_counter, 0);
663
664
            // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
665
75
            provider.keys.emplace(master_key.key.GetPubKey().GetID(), master_key.key);
666
75
            auto desc_spk_man = DescriptorScriptPubKeyMan::CreateFromMigration(m_storage, batch, w_desc, /*keypool_size=*/0, provider);
667
75
            auto desc_spks = desc_spk_man->GetScriptPubKeys();
668
669
            // Remove the scriptPubKeys from our current set
670
868
            for (const CScript& spk : desc_spks) {
671
868
                size_t erased = spks.erase(spk);
672
868
                assert(erased == 1);
673
868
                assert(IsMine(spk));
674
868
            }
675
676
75
            out.desc_spkms.push_back(std::move(desc_spk_man));
677
75
        }
678
39
    }
679
    // Add the current master seed to the migration data
680
46
    if (!m_hd_chain.seed_id.IsNull()) {
681
35
        CKey seed_key;
682
35
        if (!GetKey(m_hd_chain.seed_id, seed_key)) {
683
0
            assert(false);
684
0
        }
685
35
        out.master_key.SetSeed(seed_key);
686
35
    }
687
688
    // Handle the rest of the scriptPubKeys which must be imports and may not have all info
689
107
    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
46
    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
2.09k
    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
2.09k
        if (!script.IsPayToScriptHash() && !script.IsPayToWitnessScriptHash()) {
777
971
            continue;
778
971
        }
779
1.12k
        if (IsMine(script)) {
780
336
            continue;
781
336
        }
782
787
        SignatureData dummy_sigdata;
783
787
        if (!CanProvide(script, dummy_sigdata)) {
784
759
            continue;
785
759
        }
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
46
    if (!batch.TxnCommit()) {
819
0
        LogWarning("Error generating descriptors for migration, cannot commit db transaction");
820
0
        return std::nullopt;
821
0
    }
822
823
46
    return out;
824
46
}
825
826
bool LegacyDataSPKM::DeleteRecordsWithDB(WalletBatch& batch)
827
42
{
828
42
    LOCK(cs_KeyStore);
829
42
    return batch.EraseRecords(DBKeys::LEGACY_TYPES);
830
42
}
831
832
std::unique_ptr<DescriptorScriptPubKeyMan> DescriptorScriptPubKeyMan::CreateFromImport(WalletStorage& storage, WalletDescriptor& descriptor, int64_t keypool_size, const FlatSigningProvider& provider)
833
914
{
834
914
    auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, descriptor, keypool_size));
835
914
    LOCK(spkm->cs_desc_man);
836
914
    WalletBatch batch(storage.GetDatabase());
837
914
    spkm->UpdateWithSigningProvider(batch, provider);
838
914
    return spkm;
839
914
}
840
841
std::unique_ptr<DescriptorScriptPubKeyMan> DescriptorScriptPubKeyMan::CreateFromMigration(WalletStorage& storage, WalletBatch& batch, WalletDescriptor& descriptor, int64_t keypool_size, const FlatSigningProvider& provider)
842
188
{
843
188
    auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, descriptor, keypool_size));
844
188
    LOCK(spkm->cs_desc_man);
845
188
    spkm->UpdateWithSigningProvider(batch, provider);
846
188
    return spkm;
847
188
}
848
849
DescriptorScriptPubKeyMan::DescriptorScriptPubKeyMan(WalletStorage& storage, WalletDescriptor& descriptor, int64_t keypool_size, const KeyMap& keys, const CryptedKeyMap& ckeys)
850
2.74k
    : ScriptPubKeyMan(storage),
851
2.74k
    m_map_keys(keys),
852
2.74k
    m_map_crypted_keys(ckeys),
853
2.74k
    m_keypool_size(keypool_size),
854
2.74k
    m_wallet_descriptor(descriptor)
855
2.74k
{
856
2.74k
    if (!keys.empty() && !ckeys.empty()) {
857
1
        throw std::runtime_error("Wallet contains both unencrypted and encrypted keys");
858
1
    }
859
2.74k
    Load();
860
2.74k
}
861
862
std::unique_ptr<DescriptorScriptPubKeyMan> DescriptorScriptPubKeyMan::LoadFromStorage(WalletStorage& storage, WalletDescriptor& descriptor, int64_t keypool_size, const KeyMap& keys, const CryptedKeyMap& ckeys)
863
2.74k
{
864
2.74k
    return std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, descriptor, keypool_size, keys, ckeys));
865
2.74k
}
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.85k
{
869
3.85k
    auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, keypool_size));
870
3.85k
    spkm->SetupDescriptorGeneration(batch, master_key, addr_type, internal);
871
3.85k
    return spkm;
872
3.85k
}
873
874
util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetNewDestination(const OutputType type)
875
19.4k
{
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.4k
    if (!CanGetAddresses()) {
878
1
        return util::Error{_("No addresses available")};
879
1
    }
880
19.4k
    {
881
19.4k
        LOCK(cs_desc_man);
882
19.4k
        assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
883
19.4k
        std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
884
19.4k
        assert(desc_addr_type);
885
19.4k
        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.4k
        TopUp();
890
891
        // Get the scriptPubKey from the descriptor
892
19.4k
        FlatSigningProvider out_keys;
893
19.4k
        std::vector<CScript> scripts_temp;
894
19.4k
        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.4k
        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
504k
{
915
504k
    LOCK(cs_desc_man);
916
504k
    return m_map_script_pub_keys.contains(script);
917
504k
}
918
919
bool DescriptorScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key)
920
768
{
921
768
    LOCK(cs_desc_man);
922
768
    if (!m_map_keys.empty()) {
923
0
        return false;
924
0
    }
925
926
768
    bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
927
768
    bool keyFail = false;
928
768
    for (const auto& mi : m_map_crypted_keys) {
929
768
        const CPubKey &pubkey = mi.second.first;
930
768
        const std::vector<unsigned char> &crypted_secret = mi.second.second;
931
768
        CKey key;
932
768
        if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
933
0
            keyFail = true;
934
0
            break;
935
0
        }
936
768
        keyPass = true;
937
768
        if (m_decryption_thoroughly_checked)
938
521
            break;
939
768
    }
940
768
    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
768
    if (keyFail || !keyPass) {
945
0
        return false;
946
0
    }
947
768
    m_decryption_thoroughly_checked = true;
948
768
    return true;
949
768
}
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.19k
{
976
2.19k
    LOCK(cs_desc_man);
977
2.19k
    auto op_dest = GetNewDestination(type);
978
2.19k
    index = m_wallet_descriptor.next_index - 1;
979
2.19k
    return op_dest;
980
2.19k
}
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
89.6k
{
995
89.6k
    AssertLockHeld(cs_desc_man);
996
89.6k
    if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
997
2.39k
        KeyMap keys;
998
2.39k
        for (const auto& key_pair : m_map_crypted_keys) {
999
2.39k
            const CPubKey& pubkey = key_pair.second.first;
1000
2.39k
            const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
1001
2.39k
            CKey key;
1002
2.39k
            m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
1003
2.39k
                return DecryptKey(encryption_key, crypted_secret, pubkey, key);
1004
2.39k
            });
1005
2.39k
            keys[pubkey.GetID()] = key;
1006
2.39k
        }
1007
2.39k
        return keys;
1008
2.39k
    }
1009
87.2k
    return m_map_keys;
1010
89.6k
}
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
99
{
1020
99
    AssertLockHeld(cs_desc_man);
1021
99
    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
90
    const auto& it = m_map_keys.find(keyid);
1036
90
    if (it == m_map_keys.end()) {
1037
2
        return std::nullopt;
1038
2
    }
1039
88
    return it->second;
1040
90
}
1041
1042
bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
1043
69.6k
{
1044
69.6k
    WalletBatch batch(m_storage.GetDatabase());
1045
69.6k
    if (!batch.TxnBegin()) return false;
1046
69.6k
    bool res = TopUpWithDB(batch, size);
1047
69.6k
    if (!batch.TxnCommit()) throw std::runtime_error(strprintf("Error during descriptors keypool top up. Cannot commit changes for wallet [%s]", m_storage.LogName()));
1048
69.6k
    return res;
1049
69.6k
}
1050
1051
bool DescriptorScriptPubKeyMan::TopUpWithDB(WalletBatch& batch, unsigned int size)
1052
74.6k
{
1053
74.6k
    LOCK(cs_desc_man);
1054
74.6k
    std::set<CScript> new_spks;
1055
74.6k
    unsigned int target_size;
1056
74.6k
    if (size > 0) {
1057
72
        target_size = size;
1058
74.5k
    } else {
1059
74.5k
        target_size = m_keypool_size;
1060
74.5k
    }
1061
1062
    // Calculate the new range_end
1063
74.6k
    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
74.6k
    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
74.6k
    FlatSigningProvider provider;
1073
74.6k
    provider.keys = GetKeys();
1074
1075
74.6k
    uint256 id = GetID();
1076
504k
    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.6k
            if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
1083
28.6k
        }
1084
        // Add all of the scriptPubKeys to the scriptPubKey set
1085
429k
        new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1086
431k
        for (const CScript& script : scripts_temp) {
1087
431k
            m_map_script_pub_keys[script] = i;
1088
431k
        }
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
74.5k
    m_wallet_descriptor.range_end = new_range_end;
1106
74.5k
    batch.WriteDescriptor(GetID(), m_wallet_descriptor);
1107
1108
    // By this point, the cache size should be the size of the entire range
1109
74.5k
    assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
1110
1111
74.5k
    m_storage.TopUpCallback(new_spks, this);
1112
74.5k
    NotifyCanGetAddressesChanged();
1113
74.5k
    return true;
1114
74.5k
}
1115
1116
std::vector<WalletDestination> DescriptorScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
1117
44.3k
{
1118
44.3k
    LOCK(cs_desc_man);
1119
44.3k
    std::vector<WalletDestination> result;
1120
44.3k
    if (IsMine(script)) {
1121
44.3k
        int32_t index = m_map_script_pub_keys[script];
1122
44.3k
        if (index >= m_wallet_descriptor.next_index) {
1123
481
            WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
1124
481
            auto out_keys = std::make_unique<FlatSigningProvider>();
1125
481
            std::vector<CScript> scripts_temp;
1126
24.8k
            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
481
        }
1136
44.3k
        if (!TopUp()) {
1137
0
            WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1138
0
        }
1139
44.3k
    }
1140
1141
44.3k
    return result;
1142
44.3k
}
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.70k
{
1155
4.70k
    AssertLockHeld(cs_desc_man);
1156
4.70k
    assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
1157
1158
    // Check if provided key already exists
1159
4.70k
    if (m_map_keys.contains(pubkey.GetID()) ||
1160
4.70k
        m_map_crypted_keys.contains(pubkey.GetID())) {
1161
8
        return true;
1162
8
    }
1163
1164
4.69k
    if (m_storage.HasEncryptionKeys()) {
1165
219
        if (m_storage.IsLocked()) {
1166
0
            return false;
1167
0
        }
1168
1169
219
        std::vector<unsigned char> crypted_secret;
1170
219
        CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
1171
219
        if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
1172
219
                return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
1173
219
            })) {
1174
0
            return false;
1175
0
        }
1176
1177
219
        m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1178
219
        return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1179
4.47k
    } else {
1180
4.47k
        m_map_keys[pubkey.GetID()] = key;
1181
4.47k
        return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
1182
4.47k
    }
1183
4.69k
}
1184
1185
void DescriptorScriptPubKeyMan::SetupDescriptorGeneration(WalletBatch& batch, const CExtKey& master_key, OutputType addr_type, bool internal)
1186
3.85k
{
1187
3.85k
    LOCK(cs_desc_man);
1188
3.85k
    Assert(m_storage.IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
1189
3.85k
    Assert(!m_wallet_descriptor.descriptor);
1190
1191
3.85k
    m_wallet_descriptor = GenerateWalletDescriptor(master_key.Neuter(), addr_type, internal);
1192
1193
    // Store the master private key, and descriptor
1194
3.85k
    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.85k
    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.85k
    if (m_storage.HasEncryptionKeys()) {
1203
162
        m_decryption_thoroughly_checked = true;
1204
162
    }
1205
1206
    // TopUp
1207
3.85k
    TopUpWithDB(batch);
1208
1209
3.85k
    m_storage.UnsetBlankWalletFlag(batch);
1210
3.85k
}
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.8k
{
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.8k
    LOCK(cs_desc_man);
1223
30.8k
    return m_wallet_descriptor.descriptor->IsSingleType() &&
1224
30.8k
           m_wallet_descriptor.descriptor->IsRange() &&
1225
30.8k
           (HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end || m_wallet_descriptor.descriptor->CanSelfExpand());
1226
30.8k
}
1227
1228
bool DescriptorScriptPubKeyMan::HavePrivateKeys() const
1229
258k
{
1230
258k
    LOCK(cs_desc_man);
1231
258k
    return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
1232
258k
}
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.60k
{
1242
9.60k
    LOCK(cs_desc_man);
1243
9.60k
    return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
1244
9.60k
}
1245
1246
int64_t DescriptorScriptPubKeyMan::GetTimeFirstKey() const
1247
7.71k
{
1248
7.71k
    LOCK(cs_desc_man);
1249
7.71k
    return m_wallet_descriptor.creation_time;
1250
7.71k
}
1251
1252
std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
1253
353k
{
1254
353k
    LOCK(cs_desc_man);
1255
1256
    // Find the index of the script
1257
353k
    auto it = m_map_script_pub_keys.find(script);
1258
353k
    if (it == m_map_script_pub_keys.end()) {
1259
127k
        return nullptr;
1260
127k
    }
1261
226k
    int32_t index = it->second;
1262
1263
226k
    return GetSigningProvider(index, include_private);
1264
353k
}
1265
1266
std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
1267
50.2k
{
1268
50.2k
    LOCK(cs_desc_man);
1269
1270
    // Find index of the pubkey
1271
50.2k
    auto it = m_map_pubkeys.find(pubkey);
1272
50.2k
    if (it == m_map_pubkeys.end()) {
1273
48.8k
        return nullptr;
1274
48.8k
    }
1275
1.33k
    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.33k
    std::unique_ptr<FlatSigningProvider> out = GetSigningProvider(index, true);
1279
1.33k
    if (!out->HaveKey(pubkey.GetID())) {
1280
823
        return nullptr;
1281
823
    }
1282
507
    return out;
1283
1.33k
}
1284
1285
std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
1286
227k
{
1287
227k
    AssertLockHeld(cs_desc_man);
1288
1289
227k
    std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
1290
1291
    // Fetch SigningProvider from cache to avoid re-deriving
1292
227k
    auto it = m_map_signing_providers.find(index);
1293
227k
    if (it != m_map_signing_providers.end()) {
1294
211k
        out_keys->Merge(FlatSigningProvider{it->second});
1295
211k
    } else {
1296
        // Get the scripts, keys, and key origins for this script
1297
16.3k
        std::vector<CScript> scripts_temp;
1298
16.3k
        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.3k
        m_map_signing_providers[index] = *out_keys;
1302
16.3k
    }
1303
1304
227k
    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
227k
    return out_keys;
1315
227k
}
1316
1317
std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
1318
290k
{
1319
290k
    return GetSigningProvider(script, false);
1320
290k
}
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.4k
{
1329
17.4k
    std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1330
38.6k
    for (const auto& coin_pair : coins) {
1331
38.6k
        std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
1332
38.6k
        if (!coin_keys) {
1333
29.3k
            continue;
1334
29.3k
        }
1335
9.26k
        keys->Merge(std::move(*coin_keys));
1336
9.26k
    }
1337
1338
17.4k
    return ::SignTransaction(tx, keys.get(), coins, {.sighash_type = sighash}, input_errors);
1339
17.4k
}
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
10.1k
{
1361
10.1k
    if (n_signed) {
1362
10.1k
        *n_signed = 0;
1363
10.1k
    }
1364
43.0k
    for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
1365
32.8k
        PSBTInput& input = psbtx.inputs.at(i);
1366
1367
32.8k
        if (PSBTInputSigned(input)) {
1368
8.13k
            continue;
1369
8.13k
        }
1370
1371
        // Get the scriptPubKey to know which SigningProvider to use
1372
24.6k
        CScript script;
1373
24.6k
        if (!input.witness_utxo.IsNull()) {
1374
17.8k
            script = input.witness_utxo.scriptPubKey;
1375
17.8k
        } else if (input.non_witness_utxo) {
1376
6.59k
            if (input.prev_out >= input.non_witness_utxo->vout.size()) {
1377
1
                return PSBTError::MISSING_INPUTS;
1378
1
            }
1379
6.59k
            script = input.non_witness_utxo->vout[input.prev_out].scriptPubKey;
1380
6.59k
        } else {
1381
            // There's no UTXO so we can just skip this now
1382
237
            continue;
1383
237
        }
1384
1385
24.4k
        std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1386
24.4k
        std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, /*include_private=*/options.sign);
1387
24.4k
        if (script_keys) {
1388
3.72k
            keys->Merge(std::move(*script_keys));
1389
20.7k
        } else {
1390
            // Maybe there are pubkeys listed that we can sign for
1391
20.7k
            std::vector<CPubKey> pubkeys;
1392
20.7k
            pubkeys.reserve(input.hd_keypaths.size() + 2);
1393
1394
            // ECDSA Pubkeys
1395
20.7k
            for (const auto& [pk, _] : input.hd_keypaths) {
1396
13.2k
                pubkeys.push_back(pk);
1397
13.2k
            }
1398
1399
            // Taproot output pubkey
1400
20.7k
            std::vector<std::vector<unsigned char>> sols;
1401
20.7k
            if (Solver(script, sols) == TxoutType::WITNESS_V1_TAPROOT) {
1402
3.83k
                sols[0].insert(sols[0].begin(), 0x02);
1403
3.83k
                pubkeys.emplace_back(sols[0]);
1404
3.83k
                sols[0][0] = 0x03;
1405
3.83k
                pubkeys.emplace_back(sols[0]);
1406
3.83k
            }
1407
1408
            // Taproot pubkeys
1409
20.7k
            for (const auto& pk_pair : input.m_tap_bip32_paths) {
1410
14.6k
                const XOnlyPubKey& pubkey = pk_pair.first;
1411
29.3k
                for (unsigned char prefix : {0x02, 0x03}) {
1412
29.3k
                    unsigned char b[33] = {prefix};
1413
29.3k
                    std::copy(pubkey.begin(), pubkey.end(), b + 1);
1414
29.3k
                    CPubKey fullpubkey;
1415
29.3k
                    fullpubkey.Set(b, b + 33);
1416
29.3k
                    pubkeys.push_back(fullpubkey);
1417
29.3k
                }
1418
14.6k
            }
1419
1420
50.2k
            for (const auto& pubkey : pubkeys) {
1421
50.2k
                std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
1422
50.2k
                if (pk_keys) {
1423
506
                    keys->Merge(std::move(*pk_keys));
1424
506
                }
1425
50.2k
            }
1426
20.7k
        }
1427
1428
24.4k
        PSBTError res = SignPSBTInput(HidingSigningProvider(keys.get(), /*hide_secret=*/!options.sign, /*hide_origin=*/!options.bip32_derivs), psbtx, i, &txdata, options, /*out_sigdata=*/nullptr);
1429
24.4k
        if (res != PSBTError::OK && res != PSBTError::INCOMPLETE) {
1430
7
            return res;
1431
7
        }
1432
1433
24.4k
        bool signed_one = PSBTInputSigned(input);
1434
24.4k
        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.3k
            (*n_signed)++;
1439
16.3k
        }
1440
24.4k
    }
1441
1442
    // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
1443
88.8k
    for (unsigned int i = 0; i < psbtx.outputs.size(); ++i) {
1444
78.6k
        std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.outputs.at(i).script);
1445
78.6k
        if (!keys) {
1446
77.5k
            continue;
1447
77.5k
        }
1448
1.09k
        UpdatePSBTOutput(HidingSigningProvider(keys.get(), /*hide_secret=*/true, /*hide_origin=*/!options.bip32_derivs), psbtx, i);
1449
1.09k
    }
1450
1451
10.1k
    return {};
1452
10.1k
}
1453
1454
std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
1455
647
{
1456
647
    std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
1457
647
    if (provider) {
1458
647
        KeyOriginInfo orig;
1459
647
        CKeyID key_id = GetKeyForDestination(*provider, dest);
1460
647
        if (provider->GetKeyOrigin(key_id, orig)) {
1461
559
            LOCK(cs_desc_man);
1462
559
            std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
1463
559
            meta->key_origin = orig;
1464
559
            meta->has_key_origin = true;
1465
559
            meta->nCreateTime = m_wallet_descriptor.creation_time;
1466
559
            return meta;
1467
559
        }
1468
647
    }
1469
88
    return nullptr;
1470
647
}
1471
1472
uint256 DescriptorScriptPubKeyMan::GetID() const
1473
184k
{
1474
184k
    LOCK(cs_desc_man);
1475
184k
    return m_wallet_descriptor.id;
1476
184k
}
1477
1478
void DescriptorScriptPubKeyMan::Load()
1479
2.74k
{
1480
2.74k
    LOCK(cs_desc_man);
1481
2.74k
    std::set<CScript> new_spks;
1482
64.1k
    for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
1483
61.3k
        FlatSigningProvider out_keys;
1484
61.3k
        std::vector<CScript> scripts_temp;
1485
61.3k
        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.3k
        new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1490
62.6k
        for (const CScript& script : scripts_temp) {
1491
62.6k
            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.6k
            m_map_script_pub_keys[script] = i;
1495
62.6k
        }
1496
65.4k
        for (const auto& pk_pair : out_keys.pubkeys) {
1497
65.4k
            const CPubKey& pubkey = pk_pair.second;
1498
65.4k
            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.4k
            m_map_pubkeys[pubkey] = i;
1504
65.4k
        }
1505
61.3k
        m_max_cached_index++;
1506
61.3k
    }
1507
    // Make sure the wallet knows about our new spks
1508
2.74k
    m_storage.TopUpCallback(new_spks, this);
1509
2.74k
}
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
931
{
1519
931
    LOCK(cs_desc_man);
1520
931
    WalletBatch batch(m_storage.GetDatabase());
1521
931
    if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
1522
0
        throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
1523
0
    }
1524
931
}
1525
1526
WalletDescriptor DescriptorScriptPubKeyMan::GetWalletDescriptor() const
1527
29.8k
{
1528
29.8k
    return m_wallet_descriptor;
1529
29.8k
}
1530
1531
std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
1532
531
{
1533
531
    return GetScriptPubKeys(0);
1534
531
}
1535
1536
std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys(int32_t minimum_index) const
1537
631
{
1538
631
    LOCK(cs_desc_man);
1539
631
    std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
1540
631
    script_pub_keys.reserve(m_map_script_pub_keys.size());
1541
1542
27.7k
    for (auto const& [script_pub_key, index] : m_map_script_pub_keys) {
1543
27.7k
        if (index >= minimum_index) script_pub_keys.insert(script_pub_key);
1544
27.7k
    }
1545
631
    return script_pub_keys;
1546
631
}
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.56k
{
1555
2.56k
    LOCK(cs_desc_man);
1556
1557
2.56k
    FlatSigningProvider provider;
1558
2.56k
    provider.keys = GetKeys();
1559
1560
2.56k
    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.91k
    return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
1568
2.56k
}
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.12k
{
1620
1.12k
    AssertLockHeld(cs_desc_man);
1621
    // Add the private keys to the descriptor
1622
1.12k
    for (const auto& entry : signing_provider.keys) {
1623
856
        const CKey& key = entry.second;
1624
856
        if (!AddDescriptorKeyWithDB(batch, key, key.GetPubKey())) {
1625
0
            throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
1626
0
        }
1627
856
    }
1628
1629
    // Top up key pool, to generate scriptPubKeys
1630
1.12k
    if (!TopUpWithDB(batch)) {
1631
1
        throw std::runtime_error("Could not top up scriptPubKeys");
1632
1
    }
1633
1.12k
}
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