Coverage Report

Created: 2026-09-02 14:16

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