Coverage Report

Created: 2026-04-29 19:21

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