Bitcoin Core Fuzz Coverage Report

Coverage Report

Created: 2026-03-24 13:57

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