Coverage Report

Created: 2026-10-19 15:22

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