Coverage Report

Created: 2026-10-07 13:27

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
3.71k
{
65
3.71k
    return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
66
3.71k
}
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
9.95k
{
88
9.95k
    IsMineResult ret = IsMineResult::NO;
89
90
9.95k
    std::vector<valtype> vSolutions;
91
9.95k
    TxoutType whichType = Solver(scriptPubKey, vSolutions);
92
93
9.95k
    CKeyID keyID;
94
9.95k
    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
816
    case TxoutType::PUBKEY:
102
816
        keyID = CPubKey(vSolutions[0]).GetID();
103
816
        if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
104
0
            return IsMineResult::INVALID;
105
0
        }
106
816
        if (keystore.HaveKey(keyID)) {
107
786
            ret = std::max(ret, IsMineResult::SPENDABLE);
108
786
        }
109
816
        break;
110
2.02k
    case TxoutType::WITNESS_V0_KEYHASH:
111
2.02k
    {
112
2.02k
        if (sigversion == IsMineSigVersion::WITNESS_V0) {
113
            // P2WPKH inside P2WSH is invalid.
114
0
            return IsMineResult::INVALID;
115
0
        }
116
2.02k
        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
2.00k
        ret = std::max(ret, LegacyWalletIsMineInnerDONOTUSE(keystore, GetScriptForDestination(PKHash(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
123
2.00k
        break;
124
2.02k
    }
125
2.85k
    case TxoutType::PUBKEYHASH:
126
2.85k
        keyID = CKeyID(uint160(vSolutions[0]));
127
2.85k
        if (!PermitsUncompressed(sigversion)) {
128
2.02k
            CPubKey pubkey;
129
2.02k
            if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
130
5
                return IsMineResult::INVALID;
131
5
            }
132
2.02k
        }
133
2.84k
        if (keystore.HaveKey(keyID)) {
134
2.77k
            ret = std::max(ret, IsMineResult::SPENDABLE);
135
2.77k
        }
136
2.84k
        break;
137
2.75k
    case TxoutType::SCRIPTHASH:
138
2.75k
    {
139
2.75k
        if (sigversion != IsMineSigVersion::TOP) {
140
            // P2SH inside P2WSH or P2SH is invalid.
141
10
            return IsMineResult::INVALID;
142
10
        }
143
2.74k
        CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
144
2.74k
        CScript subscript;
145
2.74k
        if (keystore.GetCScript(scriptID, subscript)) {
146
1.30k
            ret = std::max(ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
147
1.30k
        }
148
2.74k
        break;
149
2.75k
    }
150
1.43k
    case TxoutType::WITNESS_V0_SCRIPTHASH:
151
1.43k
    {
152
1.43k
        if (sigversion == IsMineSigVersion::WITNESS_V0) {
153
            // P2WSH inside P2WSH is invalid.
154
5
            return IsMineResult::INVALID;
155
5
        }
156
1.42k
        if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
157
1.35k
            break;
158
1.35k
        }
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.42k
    }
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
9.95k
    } // no default case, so the compiler can warn about missing cases
193
194
9.93k
    if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
195
158
        ret = std::max(ret, IsMineResult::WATCH_ONLY);
196
158
    }
197
9.93k
    return ret;
198
9.95k
}
199
200
} // namespace
201
202
bool LegacyDataSPKM::IsMine(const CScript& script) const
203
5.64k
{
204
5.64k
    switch (LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP)) {
205
20
    case IsMineResult::INVALID:
206
1.92k
    case IsMineResult::NO:
207
1.92k
        return false;
208
158
    case IsMineResult::WATCH_ONLY:
209
3.72k
    case IsMineResult::SPENDABLE:
210
3.72k
        return true;
211
5.64k
    }
212
5.64k
    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
955
{
262
955
    IsMineResult ismine = LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
263
955
    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
927
    } else {
269
        // If, given the stuff in sigdata, we could make a valid signature, then we can provide for this script
270
927
        ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
271
927
        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
926
        return false;
280
927
    }
281
955
}
282
283
bool LegacyDataSPKM::LoadKey(const CKey& key, const CPubKey &pubkey)
284
327
{
285
327
    return AddKeyPubKeyInner(key, pubkey);
286
327
}
287
288
bool LegacyDataSPKM::LoadCScript(const CScript& redeemScript)
289
174
{
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
174
    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
174
    return FillableSigningProvider::AddCScript(redeemScript);
301
174
}
302
303
void LegacyDataSPKM::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
304
415
{
305
415
    LOCK(cs_KeyStore);
306
415
    mapKeyMetadata[keyID] = meta;
307
415
}
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
327
{
317
327
    LOCK(cs_KeyStore);
318
327
    return FillableSigningProvider::AddKeyPubKey(key, pubkey);
319
327
}
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
3.07k
{
343
3.07k
    LOCK(cs_KeyStore);
344
3.07k
    return setWatchOnly.contains(dest);
345
3.07k
}
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.76k
{
386
3.76k
    LOCK(cs_KeyStore);
387
3.76k
    if (!m_storage.HasEncryptionKeys()) {
388
3.16k
        return FillableSigningProvider::HaveKey(address);
389
3.16k
    }
390
594
    return mapCryptedKeys.contains(address);
391
3.76k
}
392
393
bool LegacyDataSPKM::GetKey(const CKeyID &address, CKey& keyOut) const
394
1.98k
{
395
1.98k
    LOCK(cs_KeyStore);
396
1.98k
    if (!m_storage.HasEncryptionKeys()) {
397
1.94k
        return FillableSigningProvider::GetKey(address, keyOut);
398
1.94k
    }
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
2.06k
{
445
2.06k
    LOCK(cs_KeyStore);
446
2.06k
    if (!m_storage.HasEncryptionKeys()) {
447
1.73k
        if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
448
77
            return GetWatchPubKey(address, vchPubKeyOut);
449
77
        }
450
1.65k
        return true;
451
1.73k
    }
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
786
    const auto& add_pubkey = [&candidate_spks](const CPubKey& pub) -> void {
470
786
        candidate_spks.insert(GetScriptForRawPubKey(pub));
471
786
        candidate_spks.insert(GetScriptForDestination(PKHash(pub)));
472
473
786
        CScript wpkh = GetScriptForDestination(WitnessV0KeyHash(pub));
474
786
        candidate_spks.insert(wpkh);
475
786
        candidate_spks.insert(GetScriptForDestination(ScriptHash(wpkh)));
476
786
    };
477
654
    for (const auto& [_, key] : mapKeys) {
478
654
        add_pubkey(key.GetPubKey());
479
654
    }
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
962
    const auto& add_script = [&candidate_spks](const CScript& script) -> void {
489
962
        candidate_spks.insert(script);
490
962
        candidate_spks.insert(GetScriptForDestination(ScriptHash(script)));
491
492
962
        CScript wsh = GetScriptForDestination(WitnessV0ScriptHash(script));
493
962
        candidate_spks.insert(wsh);
494
962
        candidate_spks.insert(GetScriptForDestination(ScriptHash(wsh)));
495
962
    };
496
864
    for (const auto& [_, script] : mapScripts) {
497
864
        add_script(script);
498
864
    }
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.59k
    for (const CScript& script : GetCandidateScriptPubKeys()) {
516
2.59k
        if (IsMine(script)) {
517
1.63k
            spks.insert(script);
518
1.63k
        }
519
2.59k
    }
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
327
    for (const auto& key_pair : mapKeys) {
548
327
        keyids.insert(key_pair.first);
549
327
    }
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
439
    for (auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
557
393
        const CKeyID& keyid = *keyid_it;
558
393
        const auto& it = mapKeyMetadata.find(keyid);
559
393
        if (it != mapKeyMetadata.end()) {
560
393
            const CKeyMetadata& meta = it->second;
561
393
            if (meta.hdKeypath == "s" || meta.hdKeypath == "m") {
562
40
                keyid_it++;
563
40
                continue;
564
40
            }
565
353
            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
301
                keyid_it = keyids.erase(keyid_it);
567
301
                continue;
568
301
            }
569
353
        }
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
1.20k
            for (const CScript& spk : desc_spks) {
671
1.20k
                size_t erased = spks.erase(spk);
672
1.20k
                assert(erased == 1);
673
1.20k
                assert(IsMine(spk));
674
1.20k
            }
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.59k
    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.59k
        if (!script.IsPayToScriptHash() && !script.IsPayToWitnessScriptHash()) {
777
1.22k
            continue;
778
1.22k
        }
779
1.37k
        if (IsMine(script)) {
780
420
            continue;
781
420
        }
782
955
        SignatureData dummy_sigdata;
783
955
        if (!CanProvide(script, dummy_sigdata)) {
784
927
            continue;
785
927
        }
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
955
{
834
955
    auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, descriptor, keypool_size));
835
955
    LOCK(spkm->cs_desc_man);
836
955
    WalletBatch batch(storage.GetDatabase());
837
955
    spkm->UpdateWithSigningProvider(batch, provider);
838
955
    return spkm;
839
955
}
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, const uint256& id, WalletDescriptor& descriptor, int64_t keypool_size, const KeyMap& keys, const CryptedKeyMap& ckeys)
850
3.16k
    : ScriptPubKeyMan(storage),
851
3.16k
    m_map_keys(keys),
852
3.16k
    m_map_crypted_keys(ckeys),
853
3.16k
    m_keypool_size(keypool_size),
854
3.16k
    m_id(id),
855
3.16k
    m_wallet_descriptor(descriptor)
856
3.16k
{
857
3.16k
    if (!keys.empty() && !ckeys.empty()) {
858
1
        throw std::runtime_error("Wallet contains both unencrypted and encrypted keys");
859
1
    }
860
3.16k
    Load();
861
3.16k
}
862
863
std::unique_ptr<DescriptorScriptPubKeyMan> DescriptorScriptPubKeyMan::LoadFromStorage(WalletStorage& storage, const uint256& id, WalletDescriptor& descriptor, int64_t keypool_size, const KeyMap& keys, const CryptedKeyMap& ckeys)
864
3.16k
{
865
3.16k
    return std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, id, descriptor, keypool_size, keys, ckeys));
866
3.16k
}
867
868
std::unique_ptr<DescriptorScriptPubKeyMan> DescriptorScriptPubKeyMan::GenerateNewSingleSig(WalletStorage& storage, WalletBatch& batch, int64_t keypool_size, const CExtKey& master_key, OutputType addr_type, bool internal)
869
4.18k
{
870
4.18k
    WalletDescriptor desc = GenerateWalletDescriptor(master_key.Neuter(), addr_type, internal);
871
872
4.18k
    auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, desc, keypool_size));
873
874
4.18k
    LOCK(spkm->cs_desc_man);
875
4.18k
    Assert(spkm->m_storage.IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
876
877
    // Store the master private key, and descriptor
878
4.18k
    if (!spkm->AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey())) {
879
0
        throw std::runtime_error(std::string(__func__) + ": writing descriptor master private key failed");
880
0
    }
881
4.18k
    if (!batch.WriteDescriptor(spkm->GetID(), spkm->m_wallet_descriptor)) {
882
0
        throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
883
0
    }
884
885
    // Set m_decryption_thoroughly_checked for encrypted wallets
886
4.18k
    if (spkm->m_storage.HasEncryptionKeys()) {
887
218
        spkm->m_decryption_thoroughly_checked = true;
888
218
    }
889
890
    // TopUp
891
4.18k
    spkm->TopUpWithDB(batch);
892
893
4.18k
    spkm->m_storage.UnsetBlankWalletFlag(batch);
894
4.18k
    return spkm;
895
4.18k
}
896
897
void DescriptorScriptPubKeyMan::IncIndex()
898
43.9k
{
899
43.9k
    AssertLockHeld(cs_desc_man);
900
901
43.9k
    const auto old_can = CanGetAddresses();
902
43.9k
    m_wallet_descriptor.IncNext();
903
43.9k
    const auto new_can = CanGetAddresses();
904
43.9k
    if (old_can != new_can) {
905
1
        NotifyCanGetAddressesChanged();
906
1
    }
907
43.9k
}
908
909
void DescriptorScriptPubKeyMan::DecIndex()
910
107
{
911
107
    AssertLockHeld(cs_desc_man);
912
913
107
    const auto old_can = CanGetAddresses();
914
107
    m_wallet_descriptor.DecNext();
915
107
    const auto new_can = CanGetAddresses();
916
107
    if (old_can != new_can) {
917
0
        NotifyCanGetAddressesChanged();
918
0
    }
919
107
}
920
921
void DescriptorScriptPubKeyMan::SetRangeEnd(int32_t end)
922
78.1k
{
923
78.1k
    AssertLockHeld(cs_desc_man);
924
925
78.1k
    const auto old_can = CanGetAddresses();
926
78.1k
    m_wallet_descriptor.SetEnd(end);
927
78.1k
    const auto new_can = CanGetAddresses();
928
78.1k
    if (old_can != new_can) {
929
0
        NotifyCanGetAddressesChanged();
930
0
    }
931
78.1k
}
932
933
util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetNewDestination(const OutputType type)
934
19.5k
{
935
    // Returns true if this descriptor supports getting new addresses. Conditions where we may be unable to fetch them (e.g. locked) are caught later
936
19.5k
    if (!CanGetAddresses()) {
937
1
        return util::Error{_("No addresses available")};
938
1
    }
939
19.5k
    {
940
19.5k
        LOCK(cs_desc_man);
941
19.5k
        assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
942
19.5k
        std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
943
19.5k
        assert(desc_addr_type);
944
19.5k
        if (type != *desc_addr_type) {
945
0
            throw std::runtime_error(std::string(__func__) + ": Types are inconsistent. Stored type does not match type of newly generated address");
946
0
        }
947
948
19.5k
        TopUp();
949
950
        // Get the scriptPubKey from the descriptor
951
19.5k
        FlatSigningProvider out_keys;
952
19.5k
        std::vector<CScript> scripts_temp;
953
19.5k
        if (m_wallet_descriptor.GetEnd() <= m_max_cached_index && !TopUp(1)) {
954
            // We can't generate anymore keys
955
0
            return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
956
0
        }
957
19.5k
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.GetNext(), m_wallet_descriptor.cache, scripts_temp, out_keys)) {
958
            // We can't generate anymore keys
959
8
            return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
960
8
        }
961
962
19.5k
        CTxDestination dest;
963
19.5k
        if (!ExtractDestination(scripts_temp[0], dest)) {
964
0
            return util::Error{_("Error: Cannot extract destination from the generated scriptpubkey")}; // shouldn't happen
965
0
        }
966
19.5k
        IncIndex();
967
19.5k
        WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
968
19.5k
        return dest;
969
19.5k
    }
970
19.5k
}
971
972
bool DescriptorScriptPubKeyMan::IsMine(const CScript& script) const
973
518k
{
974
518k
    LOCK(cs_desc_man);
975
518k
    return m_map_script_pub_keys.contains(script);
976
518k
}
977
978
bool DescriptorScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key)
979
940
{
980
940
    LOCK(cs_desc_man);
981
940
    if (!m_map_keys.empty()) {
982
0
        return false;
983
0
    }
984
985
940
    bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
986
940
    bool keyFail = false;
987
940
    for (const auto& mi : m_map_crypted_keys) {
988
934
        const CPubKey &pubkey = mi.second.first;
989
934
        const std::vector<unsigned char> &crypted_secret = mi.second.second;
990
934
        CKey key;
991
934
        if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
992
0
            keyFail = true;
993
0
            break;
994
0
        }
995
934
        keyPass = true;
996
934
        if (m_decryption_thoroughly_checked)
997
599
            break;
998
934
    }
999
940
    if (keyPass && keyFail) {
1000
0
        LogWarning("The wallet is probably corrupted: Some keys decrypt but not all.");
1001
0
        throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
1002
0
    }
1003
940
    if (keyFail || !keyPass) {
1004
0
        return false;
1005
0
    }
1006
940
    m_decryption_thoroughly_checked = true;
1007
940
    return true;
1008
940
}
1009
1010
bool DescriptorScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
1011
172
{
1012
172
    LOCK(cs_desc_man);
1013
172
    if (!m_map_crypted_keys.empty()) {
1014
0
        return false;
1015
0
    }
1016
1017
172
    CryptedKeyMap crypted_keys;
1018
172
    for (const KeyMap::value_type& key_in : m_map_keys)
1019
169
    {
1020
169
        const CKey &key = key_in.second;
1021
169
        CPubKey pubkey = key.GetPubKey();
1022
169
        CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
1023
169
        std::vector<unsigned char> crypted_secret;
1024
169
        if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
1025
0
            return false;
1026
0
        }
1027
169
        if (!batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret)) {
1028
2
            return false;
1029
2
        }
1030
167
        crypted_keys[pubkey.GetID()] = make_pair(pubkey, std::move(crypted_secret));
1031
167
    }
1032
1033
170
    batch->RegisterTxnListener({
1034
170
        .on_commit = [this, keys = std::move(crypted_keys)]() mutable {
1035
160
            LOCK(cs_desc_man);
1036
160
            m_map_crypted_keys = std::move(keys);
1037
160
            m_map_keys.clear();
1038
160
        },
1039
170
        .on_abort = [] {}});
1040
170
    return true;
1041
172
}
1042
1043
util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, int64_t& index)
1044
2.25k
{
1045
2.25k
    LOCK(cs_desc_man);
1046
2.25k
    auto op_dest = GetNewDestination(type);
1047
2.25k
    index = m_wallet_descriptor.GetNext() - 1;
1048
2.25k
    return op_dest;
1049
2.25k
}
1050
1051
void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
1052
107
{
1053
107
    LOCK(cs_desc_man);
1054
    // Only return when the index was the most recent
1055
107
    if (m_wallet_descriptor.GetNext() - 1 == index) {
1056
107
        DecIndex();
1057
107
    }
1058
107
    WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
1059
107
}
1060
1061
std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
1062
95.8k
{
1063
95.8k
    AssertLockHeld(cs_desc_man);
1064
95.8k
    if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
1065
2.84k
        KeyMap keys;
1066
2.84k
        for (const auto& key_pair : m_map_crypted_keys) {
1067
2.84k
            const CPubKey& pubkey = key_pair.second.first;
1068
2.84k
            const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
1069
2.84k
            CKey key;
1070
2.84k
            m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
1071
2.84k
                return DecryptKey(encryption_key, crypted_secret, pubkey, key);
1072
2.84k
            });
1073
2.84k
            keys[pubkey.GetID()] = key;
1074
2.84k
        }
1075
2.84k
        return keys;
1076
2.84k
    }
1077
93.0k
    return m_map_keys;
1078
95.8k
}
1079
1080
bool DescriptorScriptPubKeyMan::HasPrivKey(const CKeyID& keyid) const
1081
280
{
1082
280
    AssertLockHeld(cs_desc_man);
1083
280
    return m_map_keys.contains(keyid) || m_map_crypted_keys.contains(keyid);
1084
280
}
1085
1086
std::optional<CKey> DescriptorScriptPubKeyMan::GetKey(const CKeyID& keyid) const
1087
154
{
1088
154
    AssertLockHeld(cs_desc_man);
1089
154
    if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
1090
20
        const auto& it = m_map_crypted_keys.find(keyid);
1091
20
        if (it == m_map_crypted_keys.end()) {
1092
6
            return std::nullopt;
1093
6
        }
1094
14
        const std::vector<unsigned char>& crypted_secret = it->second.second;
1095
14
        CKey key;
1096
14
        if (!Assume(m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
1097
14
            return DecryptKey(encryption_key, crypted_secret, it->second.first, key);
1098
14
        }))) {
1099
0
            return std::nullopt;
1100
0
        }
1101
14
        return key;
1102
14
    }
1103
134
    const auto& it = m_map_keys.find(keyid);
1104
134
    if (it == m_map_keys.end()) {
1105
28
        return std::nullopt;
1106
28
    }
1107
106
    return it->second;
1108
134
}
1109
1110
bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
1111
72.8k
{
1112
72.8k
    WalletBatch batch(m_storage.GetDatabase());
1113
72.8k
    if (!batch.TxnBegin()) return false;
1114
72.8k
    bool res = TopUpWithDB(batch, size);
1115
72.8k
    if (!batch.TxnCommit()) throw std::runtime_error(strprintf("Error during descriptors keypool top up. Cannot commit changes for wallet [%s]", m_storage.LogName()));
1116
72.8k
    return res;
1117
72.8k
}
1118
1119
bool DescriptorScriptPubKeyMan::TopUpWithDB(WalletBatch& batch, unsigned int size)
1120
78.2k
{
1121
78.2k
    LOCK(cs_desc_man);
1122
78.2k
    std::set<CScript> new_spks;
1123
78.2k
    unsigned int target_size;
1124
78.2k
    if (size > 0) {
1125
72
        target_size = size;
1126
78.1k
    } else {
1127
78.1k
        target_size = m_keypool_size;
1128
78.1k
    }
1129
1130
    // Calculate the new range_end
1131
78.2k
    int32_t new_range_end = std::max(m_wallet_descriptor.GetNext() + (int32_t)target_size, m_wallet_descriptor.GetEnd());
1132
1133
    // If the descriptor is not ranged, we actually just want to fill the first cache item
1134
78.2k
    if (!m_wallet_descriptor.descriptor->IsRange()) {
1135
12.3k
        new_range_end = 1;
1136
12.3k
    }
1137
1138
78.2k
    FlatSigningProvider provider;
1139
78.2k
    provider.keys = GetKeys();
1140
1141
78.2k
    uint256 id = GetID();
1142
556k
    for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
1143
478k
        FlatSigningProvider out_keys;
1144
478k
        std::vector<CScript> scripts_temp;
1145
478k
        DescriptorCache temp_cache;
1146
        // Maybe we have a cached xpub and we can expand from the cache first
1147
478k
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1148
29.0k
            if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
1149
29.0k
        }
1150
        // Add all of the scriptPubKeys to the scriptPubKey set
1151
478k
        new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1152
480k
        for (const CScript& script : scripts_temp) {
1153
480k
            m_map_script_pub_keys[script] = i;
1154
480k
        }
1155
526k
        for (const auto& pk_pair : out_keys.pubkeys) {
1156
526k
            const CPubKey& pubkey = pk_pair.second;
1157
526k
            if (m_map_pubkeys.contains(pubkey)) {
1158
                // We don't need to give an error here.
1159
                // 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
1160
10.7k
                continue;
1161
10.7k
            }
1162
516k
            m_map_pubkeys[pubkey] = i;
1163
516k
        }
1164
        // Merge and write the cache
1165
478k
        DescriptorCache new_items = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
1166
478k
        if (!batch.WriteDescriptorCacheItems(id, new_items)) {
1167
0
            throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
1168
0
        }
1169
478k
        m_max_cached_index++;
1170
478k
    }
1171
78.1k
    SetRangeEnd(new_range_end);
1172
78.1k
    batch.WriteDescriptor(GetID(), m_wallet_descriptor);
1173
1174
    // By this point, the cache size should be the size of the entire range
1175
78.1k
    assert(m_wallet_descriptor.GetEnd() - 1 == m_max_cached_index);
1176
1177
78.1k
    m_storage.TopUpCallback(new_spks, this);
1178
78.1k
    return true;
1179
78.1k
}
1180
1181
std::vector<WalletDestination> DescriptorScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
1182
46.7k
{
1183
46.7k
    LOCK(cs_desc_man);
1184
46.7k
    std::vector<WalletDestination> result;
1185
46.7k
    if (IsMine(script)) {
1186
46.7k
        int32_t index = m_map_script_pub_keys[script];
1187
46.7k
        if (index >= m_wallet_descriptor.GetNext()) {
1188
496
            WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
1189
496
            auto out_keys = std::make_unique<FlatSigningProvider>();
1190
496
            std::vector<CScript> scripts_temp;
1191
24.9k
            while (index >= m_wallet_descriptor.GetNext()) {
1192
24.4k
                if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.GetNext(), m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
1193
0
                    throw std::runtime_error(std::string(__func__) + ": Unable to expand descriptor from cache");
1194
0
                }
1195
24.4k
                CTxDestination dest;
1196
24.4k
                ExtractDestination(scripts_temp[0], dest);
1197
24.4k
                result.push_back({dest, std::nullopt});
1198
24.4k
                IncIndex();
1199
24.4k
            }
1200
496
        }
1201
46.7k
        if (!TopUp()) {
1202
0
            WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1203
0
        }
1204
46.7k
    }
1205
1206
46.7k
    return result;
1207
46.7k
}
1208
1209
bool DescriptorScriptPubKeyMan::AddDescriptorKeyWithDB(WalletBatch& batch, const CKey& key, const CPubKey &pubkey)
1210
5.08k
{
1211
5.08k
    AssertLockHeld(cs_desc_man);
1212
5.08k
    assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
1213
1214
    // Check if provided key already exists
1215
5.08k
    if (m_map_keys.contains(pubkey.GetID()) ||
1216
5.08k
        m_map_crypted_keys.contains(pubkey.GetID())) {
1217
10
        return true;
1218
10
    }
1219
1220
5.07k
    if (m_storage.HasEncryptionKeys()) {
1221
283
        if (m_storage.IsLocked()) {
1222
0
            return false;
1223
0
        }
1224
1225
283
        std::vector<unsigned char> crypted_secret;
1226
283
        CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
1227
283
        if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
1228
283
                return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
1229
283
            })) {
1230
0
            return false;
1231
0
        }
1232
1233
283
        if (!batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret)) {
1234
3
            return false;
1235
3
        }
1236
280
        m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, std::move(crypted_secret));
1237
4.78k
    } else {
1238
4.78k
        if (!batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey())) {
1239
1
            return false;
1240
1
        }
1241
4.78k
        m_map_keys[pubkey.GetID()] = key;
1242
4.78k
    }
1243
5.06k
    return true;
1244
5.07k
}
1245
1246
bool DescriptorScriptPubKeyMan::IsHDEnabled() const
1247
71
{
1248
71
    LOCK(cs_desc_man);
1249
71
    return m_wallet_descriptor.descriptor->IsRange();
1250
71
}
1251
1252
bool DescriptorScriptPubKeyMan::CanGetAddresses(bool internal) const
1253
275k
{
1254
    // We can only give out addresses from descriptors that are single type (not combo), ranged,
1255
    // and either have cached keys or can generate more keys (ignoring encryption)
1256
275k
    LOCK(cs_desc_man);
1257
275k
    return m_wallet_descriptor.descriptor->IsSingleType() &&
1258
275k
           m_wallet_descriptor.descriptor->IsRange() &&
1259
275k
           (HavePrivateKeys() || m_wallet_descriptor.GetNext() < m_wallet_descriptor.GetEnd() || m_wallet_descriptor.descriptor->CanSelfExpand());
1260
275k
}
1261
1262
bool DescriptorScriptPubKeyMan::HavePrivateKeys() const
1263
481k
{
1264
481k
    LOCK(cs_desc_man);
1265
481k
    return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
1266
481k
}
1267
1268
bool DescriptorScriptPubKeyMan::HaveCryptedKeys() const
1269
41
{
1270
41
    LOCK(cs_desc_man);
1271
41
    return !m_map_crypted_keys.empty();
1272
41
}
1273
1274
unsigned int DescriptorScriptPubKeyMan::GetKeyPoolSize() const
1275
10.2k
{
1276
10.2k
    LOCK(cs_desc_man);
1277
10.2k
    return m_wallet_descriptor.GetEnd() - m_wallet_descriptor.GetNext();
1278
10.2k
}
1279
1280
int64_t DescriptorScriptPubKeyMan::GetTimeFirstKey() const
1281
8.50k
{
1282
8.50k
    LOCK(cs_desc_man);
1283
8.50k
    return m_wallet_descriptor.creation_time;
1284
8.50k
}
1285
1286
std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
1287
385k
{
1288
385k
    LOCK(cs_desc_man);
1289
1290
    // Find the index of the script
1291
385k
    auto it = m_map_script_pub_keys.find(script);
1292
385k
    if (it == m_map_script_pub_keys.end()) {
1293
155k
        return nullptr;
1294
155k
    }
1295
229k
    int32_t index = it->second;
1296
1297
229k
    return GetSigningProvider(index, include_private);
1298
385k
}
1299
1300
std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
1301
51.7k
{
1302
51.7k
    LOCK(cs_desc_man);
1303
1304
    // Find index of the pubkey
1305
51.7k
    auto it = m_map_pubkeys.find(pubkey);
1306
51.7k
    if (it == m_map_pubkeys.end()) {
1307
50.3k
        return nullptr;
1308
50.3k
    }
1309
1.37k
    int32_t index = it->second;
1310
1311
    // Always try to get the signing provider with private keys. This function should only be called during signing anyways
1312
1.37k
    std::unique_ptr<FlatSigningProvider> out = GetSigningProvider(index, true);
1313
1.37k
    if (!out->HaveKey(pubkey.GetID())) {
1314
866
        return nullptr;
1315
866
    }
1316
513
    return out;
1317
1.37k
}
1318
1319
std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
1320
230k
{
1321
230k
    AssertLockHeld(cs_desc_man);
1322
1323
230k
    std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
1324
1325
    // Fetch SigningProvider from cache to avoid re-deriving
1326
230k
    auto it = m_map_signing_providers.find(index);
1327
230k
    if (it != m_map_signing_providers.end()) {
1328
214k
        out_keys->Merge(FlatSigningProvider{it->second});
1329
214k
    } else {
1330
        // Get the scripts, keys, and key origins for this script
1331
16.6k
        std::vector<CScript> scripts_temp;
1332
16.6k
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
1333
1334
        // Cache SigningProvider so we don't need to re-derive if we need this SigningProvider again
1335
16.6k
        m_map_signing_providers[index] = *out_keys;
1336
16.6k
    }
1337
1338
230k
    if (HavePrivateKeys() && include_private) {
1339
14.5k
        FlatSigningProvider master_provider;
1340
14.5k
        master_provider.keys = GetKeys();
1341
14.5k
        m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
1342
1343
        // Always include musig_secnonces as this descriptor may have a participant private key
1344
        // but not a musig() descriptor
1345
14.5k
        out_keys->musig2_secnonces = &m_musig2_secnonces;
1346
14.5k
    }
1347
1348
230k
    return out_keys;
1349
230k
}
1350
1351
std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
1352
292k
{
1353
292k
    return GetSigningProvider(script, false);
1354
292k
}
1355
1356
bool DescriptorScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
1357
270k
{
1358
270k
    return IsMine(script);
1359
270k
}
1360
1361
bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
1362
16.9k
{
1363
16.9k
    std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1364
68.0k
    for (const auto& coin_pair : coins) {
1365
68.0k
        std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
1366
68.0k
        if (!coin_keys) {
1367
56.7k
            continue;
1368
56.7k
        }
1369
11.2k
        keys->Merge(std::move(*coin_keys));
1370
11.2k
    }
1371
1372
16.9k
    return ::SignTransaction(tx, keys.get(), coins, {.sighash_type = sighash}, input_errors);
1373
16.9k
}
1374
1375
SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
1376
9
{
1377
9
    std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
1378
9
    if (!keys) {
1379
0
        return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
1380
0
    }
1381
1382
9
    CKey key;
1383
9
    if (!keys->GetKey(ToKeyID(pkhash), key)) {
1384
0
        return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
1385
0
    }
1386
1387
9
    if (!MessageSign(key, message, str_sig)) {
1388
0
        return SigningResult::SIGNING_FAILED;
1389
0
    }
1390
9
    return SigningResult::OK;
1391
9
}
1392
1393
std::optional<PSBTError> DescriptorScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, const common::PSBTFillOptions& options, int* n_signed) const
1394
10.9k
{
1395
10.9k
    if (n_signed) {
1396
10.9k
        *n_signed = 0;
1397
10.9k
    }
1398
44.3k
    for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
1399
33.4k
        PSBTInput& input = psbtx.inputs.at(i);
1400
1401
33.4k
        if (PSBTInputSigned(input)) {
1402
8.89k
            continue;
1403
8.89k
        }
1404
1405
        // Get the scriptPubKey to know which SigningProvider to use
1406
24.5k
        CScript script;
1407
24.5k
        if (!input.witness_utxo.IsNull()) {
1408
17.6k
            script = input.witness_utxo.scriptPubKey;
1409
17.6k
        } else if (input.non_witness_utxo) {
1410
6.66k
            if (input.prev_out >= input.non_witness_utxo->vout.size()) {
1411
1
                return PSBTError::MISSING_INPUTS;
1412
1
            }
1413
6.66k
            script = input.non_witness_utxo->vout[input.prev_out].scriptPubKey;
1414
6.66k
        } else {
1415
            // There's no UTXO so we can just skip this now
1416
237
            continue;
1417
237
        }
1418
1419
24.3k
        std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1420
24.3k
        std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, /*include_private=*/options.sign);
1421
24.3k
        if (script_keys) {
1422
3.78k
            keys->Merge(std::move(*script_keys));
1423
20.5k
        } else {
1424
            // Maybe there are pubkeys listed that we can sign for
1425
20.5k
            std::vector<CPubKey> pubkeys;
1426
20.5k
            pubkeys.reserve(input.hd_keypaths.size() + 2);
1427
1428
            // ECDSA Pubkeys
1429
20.5k
            for (const auto& [pk, _] : input.hd_keypaths) {
1430
13.2k
                pubkeys.push_back(pk);
1431
13.2k
            }
1432
1433
            // Taproot output pubkey
1434
20.5k
            std::vector<std::vector<unsigned char>> sols;
1435
20.5k
            if (Solver(script, sols) == TxoutType::WITNESS_V1_TAPROOT) {
1436
3.95k
                sols[0].insert(sols[0].begin(), 0x02);
1437
3.95k
                pubkeys.emplace_back(sols[0]);
1438
3.95k
                sols[0][0] = 0x03;
1439
3.95k
                pubkeys.emplace_back(sols[0]);
1440
3.95k
            }
1441
1442
            // Taproot pubkeys
1443
20.5k
            for (const auto& pk_pair : input.m_tap_bip32_paths) {
1444
15.2k
                const XOnlyPubKey& pubkey = pk_pair.first;
1445
30.5k
                for (unsigned char prefix : {0x02, 0x03}) {
1446
30.5k
                    unsigned char b[33] = {prefix};
1447
30.5k
                    std::copy(pubkey.begin(), pubkey.end(), b + 1);
1448
30.5k
                    CPubKey fullpubkey;
1449
30.5k
                    fullpubkey.Set(b, b + 33);
1450
30.5k
                    pubkeys.push_back(fullpubkey);
1451
30.5k
                }
1452
15.2k
            }
1453
1454
51.7k
            for (const auto& pubkey : pubkeys) {
1455
51.7k
                std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
1456
51.7k
                if (pk_keys) {
1457
512
                    keys->Merge(std::move(*pk_keys));
1458
512
                }
1459
51.7k
            }
1460
20.5k
        }
1461
1462
24.3k
        const auto sign_result = SignPSBTInput(HidingSigningProvider(keys.get(), /*hide_secret=*/!options.sign, /*hide_origin=*/!options.bip32_derivs), psbtx, i, &txdata, options, /*out_sigdata=*/nullptr);
1463
24.3k
        if (!sign_result.has_value() && sign_result.error() != PSBTError::INCOMPLETE) {
1464
7
            return sign_result.error();
1465
7
        }
1466
1467
24.3k
        bool signed_one = PSBTInputSigned(input);
1468
24.3k
        if (n_signed && (signed_one || !options.sign)) {
1469
            // If sign is false, we assume that we _could_ sign if we get here. This
1470
            // will never have false negatives; it is hard to tell under what i
1471
            // circumstances it could have false positives.
1472
16.6k
            (*n_signed)++;
1473
16.6k
        }
1474
24.3k
    }
1475
1476
    // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
1477
90.4k
    for (unsigned int i = 0; i < psbtx.outputs.size(); ++i) {
1478
79.5k
        std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.outputs.at(i).script);
1479
79.5k
        if (!keys) {
1480
78.3k
            continue;
1481
78.3k
        }
1482
1.15k
        UpdatePSBTOutput(HidingSigningProvider(keys.get(), /*hide_secret=*/true, /*hide_origin=*/!options.bip32_derivs), psbtx, i);
1483
1.15k
    }
1484
1485
10.8k
    return {};
1486
10.9k
}
1487
1488
std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
1489
651
{
1490
651
    std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
1491
651
    if (provider) {
1492
651
        KeyOriginInfo orig;
1493
651
        CKeyID key_id = GetKeyForDestination(*provider, dest);
1494
651
        if (provider->GetKeyOrigin(key_id, orig)) {
1495
563
            LOCK(cs_desc_man);
1496
563
            std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
1497
563
            meta->key_origin = orig;
1498
563
            meta->has_key_origin = true;
1499
563
            meta->nCreateTime = m_wallet_descriptor.creation_time;
1500
563
            return meta;
1501
563
        }
1502
651
    }
1503
88
    return nullptr;
1504
651
}
1505
1506
uint256 DescriptorScriptPubKeyMan::GetID() const
1507
192k
{
1508
192k
    return m_id;
1509
192k
}
1510
1511
void DescriptorScriptPubKeyMan::Load()
1512
3.16k
{
1513
3.16k
    LOCK(cs_desc_man);
1514
3.16k
    std::set<CScript> new_spks;
1515
73.9k
    for (int32_t i = m_wallet_descriptor.GetStart(); i < m_wallet_descriptor.GetEnd(); ++i) {
1516
70.8k
        FlatSigningProvider out_keys;
1517
70.8k
        std::vector<CScript> scripts_temp;
1518
70.8k
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1519
0
            throw std::runtime_error("Error: Unable to expand wallet descriptor from cache");
1520
0
        }
1521
        // Add all of the scriptPubKeys to the scriptPubKey set
1522
70.8k
        new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1523
72.4k
        for (const CScript& script : scripts_temp) {
1524
72.4k
            if (m_map_script_pub_keys.contains(script)) {
1525
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]));
1526
0
            }
1527
72.4k
            m_map_script_pub_keys[script] = i;
1528
72.4k
        }
1529
74.9k
        for (const auto& pk_pair : out_keys.pubkeys) {
1530
74.9k
            const CPubKey& pubkey = pk_pair.second;
1531
74.9k
            if (m_map_pubkeys.contains(pubkey)) {
1532
                // We don't need to give an error here.
1533
                // 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
1534
38
                continue;
1535
38
            }
1536
74.8k
            m_map_pubkeys[pubkey] = i;
1537
74.8k
        }
1538
70.8k
        m_max_cached_index++;
1539
70.8k
    }
1540
    // Make sure the wallet knows about our new spks
1541
3.16k
    m_storage.TopUpCallback(new_spks, this);
1542
3.16k
}
1543
1544
bool DescriptorScriptPubKeyMan::HasWalletDescriptor(const WalletDescriptor& desc) const
1545
4.78k
{
1546
4.78k
    LOCK(cs_desc_man);
1547
4.78k
    return m_wallet_descriptor.IsCanonicallyEquivalent(desc);
1548
4.78k
}
1549
1550
void DescriptorScriptPubKeyMan::WriteDescriptor()
1551
978
{
1552
978
    LOCK(cs_desc_man);
1553
978
    WalletBatch batch(m_storage.GetDatabase());
1554
978
    if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
1555
0
        throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
1556
0
    }
1557
978
}
1558
1559
WalletDescriptor DescriptorScriptPubKeyMan::GetWalletDescriptor() const
1560
30.9k
{
1561
30.9k
    return m_wallet_descriptor;
1562
30.9k
}
1563
1564
std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
1565
557
{
1566
557
    return GetScriptPubKeys(0);
1567
557
}
1568
1569
std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys(int32_t minimum_index) const
1570
676
{
1571
676
    LOCK(cs_desc_man);
1572
676
    std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
1573
676
    script_pub_keys.reserve(m_map_script_pub_keys.size());
1574
1575
37.8k
    for (auto const& [script_pub_key, index] : m_map_script_pub_keys) {
1576
37.8k
        if (index >= minimum_index) script_pub_keys.insert(script_pub_key);
1577
37.8k
    }
1578
676
    return script_pub_keys;
1579
676
}
1580
1581
int32_t DescriptorScriptPubKeyMan::GetEndRange() const
1582
4.96k
{
1583
4.96k
    return m_max_cached_index + 1;
1584
4.96k
}
1585
1586
bool DescriptorScriptPubKeyMan::GetDescriptorString(std::string& out, const bool priv) const
1587
3.08k
{
1588
3.08k
    LOCK(cs_desc_man);
1589
1590
3.08k
    FlatSigningProvider provider;
1591
3.08k
    provider.keys = GetKeys();
1592
1593
3.08k
    if (priv) {
1594
        // For the private version, always return the master key to avoid
1595
        // exposing child private keys. The risk implications of exposing child
1596
        // private keys together with the parent xpub may be non-obvious for users.
1597
689
        return m_wallet_descriptor.descriptor->ToPrivateString(provider, out);
1598
689
    }
1599
1600
2.39k
    return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
1601
3.08k
}
1602
1603
void DescriptorScriptPubKeyMan::UpgradeDescriptorCache()
1604
46
{
1605
46
    LOCK(cs_desc_man);
1606
46
    if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED)) {
1607
0
        return;
1608
0
    }
1609
1610
    // Skip if we have the last hardened xpub cache
1611
46
    if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
1612
40
        return;
1613
40
    }
1614
1615
    // Expand the descriptor
1616
6
    FlatSigningProvider provider;
1617
6
    provider.keys = GetKeys();
1618
6
    FlatSigningProvider out_keys;
1619
6
    std::vector<CScript> scripts_temp;
1620
6
    DescriptorCache temp_cache;
1621
6
    if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
1622
0
        throw std::runtime_error("Unable to expand descriptor");
1623
0
    }
1624
1625
    // Cache the last hardened xpubs
1626
6
    DescriptorCache diff = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
1627
6
    if (!WalletBatch(m_storage.GetDatabase()).WriteDescriptorCacheItems(GetID(), diff)) {
1628
0
        throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
1629
0
    }
1630
6
}
1631
1632
util::Result<void> DescriptorScriptPubKeyMan::UpdateWalletDescriptor(WalletDescriptor& descriptor, const FlatSigningProvider& provider)
1633
31
{
1634
31
    LOCK(cs_desc_man);
1635
31
    std::string error;
1636
31
    if (!CanUpdateToWalletDescriptor(descriptor, error)) {
1637
3
        return util::Error{Untranslated(std::move(error))};
1638
3
    }
1639
1640
28
    m_map_pubkeys.clear();
1641
28
    m_map_script_pub_keys.clear();
1642
28
    m_max_cached_index = -1;
1643
28
    m_wallet_descriptor.UpdateFrom(descriptor);
1644
1645
28
    WalletBatch batch(m_storage.GetDatabase());
1646
28
    UpdateWithSigningProvider(batch, provider);
1647
28
    NotifyFirstKeyTimeChanged(this, m_wallet_descriptor.creation_time);
1648
28
    return {};
1649
31
}
1650
1651
void DescriptorScriptPubKeyMan::UpdateWithSigningProvider(WalletBatch& batch, const FlatSigningProvider& signing_provider)
1652
1.17k
{
1653
1.17k
    AssertLockHeld(cs_desc_man);
1654
    // Add the private keys to the descriptor
1655
1.17k
    for (const auto& entry : signing_provider.keys) {
1656
900
        const CKey& key = entry.second;
1657
900
        if (!AddDescriptorKeyWithDB(batch, key, key.GetPubKey())) {
1658
4
            throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
1659
4
        }
1660
900
    }
1661
1662
    // Top up key pool, to generate scriptPubKeys
1663
1.16k
    if (!TopUpWithDB(batch)) {
1664
1
        throw std::runtime_error("Could not top up scriptPubKeys");
1665
1
    }
1666
1.16k
}
1667
1668
bool DescriptorScriptPubKeyMan::CanUpdateToWalletDescriptor(const WalletDescriptor& descriptor, std::string& error)
1669
31
{
1670
31
    LOCK(cs_desc_man);
1671
31
    if (!HasWalletDescriptor(descriptor)) {
1672
0
        error = "can only update matching descriptor";
1673
0
        return false;
1674
0
    }
1675
1676
31
    if (!descriptor.descriptor->IsRange()) {
1677
        // Skip range check for non-range descriptors
1678
14
        return true;
1679
14
    }
1680
1681
17
    if (descriptor.GetStart() > m_wallet_descriptor.GetStart() ||
1682
17
        descriptor.GetEnd() < m_wallet_descriptor.GetEnd()) {
1683
        // Use inclusive range for error
1684
3
        error = strprintf("new range must include current range = [%d,%d]",
1685
3
                          m_wallet_descriptor.GetStart(),
1686
3
                          m_wallet_descriptor.GetEnd() - 1);
1687
3
        return false;
1688
3
    }
1689
1690
14
    return true;
1691
17
}
1692
} // namespace wallet