Coverage Report

Created: 2025-02-21 14:37

/root/bitcoin/src/wallet/scriptpubkeyman.cpp
Line
Count
Source (jump to first uncovered line)
1
// Copyright (c) 2019-2022 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
//! Value for the first BIP 32 hardened derivation. Can be used as a bit mask and as a value. See BIP 32 for more details.
29
const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
30
31
util::Result<CTxDestination> LegacyScriptPubKeyMan::GetNewDestination(const OutputType type)
32
0
{
33
0
    if (LEGACY_OUTPUT_TYPES.count(type) == 0) {
34
0
        return util::Error{_("Error: Legacy wallets only support the \"legacy\", \"p2sh-segwit\", and \"bech32\" address types")};
35
0
    }
36
0
    assert(type != OutputType::BECH32M);
37
38
    // Fill-up keypool if needed
39
0
    TopUp();
40
41
0
    LOCK(cs_KeyStore);
42
43
    // Generate a new key that is added to wallet
44
0
    CPubKey new_key;
45
0
    if (!GetKeyFromPool(new_key, type)) {
46
0
        return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
47
0
    }
48
0
    LearnRelatedScripts(new_key, type);
49
0
    return GetDestinationForKey(new_key, type);
50
0
}
51
52
typedef std::vector<unsigned char> valtype;
53
54
namespace {
55
56
/**
57
 * This is an enum that tracks the execution context of a script, similar to
58
 * SigVersion in script/interpreter. It is separate however because we want to
59
 * distinguish between top-level scriptPubKey execution and P2SH redeemScript
60
 * execution (a distinction that has no impact on consensus rules).
61
 */
62
enum class IsMineSigVersion
63
{
64
    TOP = 0,        //!< scriptPubKey execution
65
    P2SH = 1,       //!< P2SH redeemScript
66
    WITNESS_V0 = 2, //!< P2WSH witness script execution
67
};
68
69
/**
70
 * This is an internal representation of isminetype + invalidity.
71
 * Its order is significant, as we return the max of all explored
72
 * possibilities.
73
 */
74
enum class IsMineResult
75
{
76
    NO = 0,         //!< Not ours
77
    WATCH_ONLY = 1, //!< Included in watch-only balance
78
    SPENDABLE = 2,  //!< Included in all balances
79
    INVALID = 3,    //!< Not spendable by anyone (uncompressed pubkey in segwit, P2SH inside P2SH or witness, witness inside witness)
80
};
81
82
bool PermitsUncompressed(IsMineSigVersion sigversion)
83
0
{
84
0
    return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
85
0
}
86
87
bool HaveKeys(const std::vector<valtype>& pubkeys, const LegacyDataSPKM& keystore)
88
0
{
89
0
    for (const valtype& pubkey : pubkeys) {
90
0
        CKeyID keyID = CPubKey(pubkey).GetID();
91
0
        if (!keystore.HaveKey(keyID)) return false;
92
0
    }
93
0
    return true;
94
0
}
95
96
//! Recursively solve script and return spendable/watchonly/invalid status.
97
//!
98
//! @param keystore            legacy key and script store
99
//! @param scriptPubKey        script to solve
100
//! @param sigversion          script type (top-level / redeemscript / witnessscript)
101
//! @param recurse_scripthash  whether to recurse into nested p2sh and p2wsh
102
//!                            scripts or simply treat any script that has been
103
//!                            stored in the keystore as spendable
104
// NOLINTNEXTLINE(misc-no-recursion)
105
IsMineResult IsMineInner(const LegacyDataSPKM& keystore, const CScript& scriptPubKey, IsMineSigVersion sigversion, bool recurse_scripthash=true)
106
0
{
107
0
    IsMineResult ret = IsMineResult::NO;
108
109
0
    std::vector<valtype> vSolutions;
110
0
    TxoutType whichType = Solver(scriptPubKey, vSolutions);
111
112
0
    CKeyID keyID;
113
0
    switch (whichType) {
114
0
    case TxoutType::NONSTANDARD:
115
0
    case TxoutType::NULL_DATA:
116
0
    case TxoutType::WITNESS_UNKNOWN:
117
0
    case TxoutType::WITNESS_V1_TAPROOT:
118
0
    case TxoutType::ANCHOR:
119
0
        break;
120
0
    case TxoutType::PUBKEY:
121
0
        keyID = CPubKey(vSolutions[0]).GetID();
122
0
        if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
123
0
            return IsMineResult::INVALID;
124
0
        }
125
0
        if (keystore.HaveKey(keyID)) {
126
0
            ret = std::max(ret, IsMineResult::SPENDABLE);
127
0
        }
128
0
        break;
129
0
    case TxoutType::WITNESS_V0_KEYHASH:
130
0
    {
131
0
        if (sigversion == IsMineSigVersion::WITNESS_V0) {
132
            // P2WPKH inside P2WSH is invalid.
133
0
            return IsMineResult::INVALID;
134
0
        }
135
0
        if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
136
            // We do not support bare witness outputs unless the P2SH version of it would be
137
            // acceptable as well. This protects against matching before segwit activates.
138
            // This also applies to the P2WSH case.
139
0
            break;
140
0
        }
141
0
        ret = std::max(ret, IsMineInner(keystore, GetScriptForDestination(PKHash(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
142
0
        break;
143
0
    }
144
0
    case TxoutType::PUBKEYHASH:
145
0
        keyID = CKeyID(uint160(vSolutions[0]));
146
0
        if (!PermitsUncompressed(sigversion)) {
147
0
            CPubKey pubkey;
148
0
            if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
149
0
                return IsMineResult::INVALID;
150
0
            }
151
0
        }
152
0
        if (keystore.HaveKey(keyID)) {
153
0
            ret = std::max(ret, IsMineResult::SPENDABLE);
154
0
        }
155
0
        break;
156
0
    case TxoutType::SCRIPTHASH:
157
0
    {
158
0
        if (sigversion != IsMineSigVersion::TOP) {
159
            // P2SH inside P2WSH or P2SH is invalid.
160
0
            return IsMineResult::INVALID;
161
0
        }
162
0
        CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
163
0
        CScript subscript;
164
0
        if (keystore.GetCScript(scriptID, subscript)) {
165
0
            ret = std::max(ret, recurse_scripthash ? IsMineInner(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
166
0
        }
167
0
        break;
168
0
    }
169
0
    case TxoutType::WITNESS_V0_SCRIPTHASH:
170
0
    {
171
0
        if (sigversion == IsMineSigVersion::WITNESS_V0) {
172
            // P2WSH inside P2WSH is invalid.
173
0
            return IsMineResult::INVALID;
174
0
        }
175
0
        if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
176
0
            break;
177
0
        }
178
0
        CScriptID scriptID{RIPEMD160(vSolutions[0])};
179
0
        CScript subscript;
180
0
        if (keystore.GetCScript(scriptID, subscript)) {
181
0
            ret = std::max(ret, recurse_scripthash ? IsMineInner(keystore, subscript, IsMineSigVersion::WITNESS_V0) : IsMineResult::SPENDABLE);
182
0
        }
183
0
        break;
184
0
    }
185
186
0
    case TxoutType::MULTISIG:
187
0
    {
188
        // Never treat bare multisig outputs as ours (they can still be made watchonly-though)
189
0
        if (sigversion == IsMineSigVersion::TOP) {
190
0
            break;
191
0
        }
192
193
        // Only consider transactions "mine" if we own ALL the
194
        // keys involved. Multi-signature transactions that are
195
        // partially owned (somebody else has a key that can spend
196
        // them) enable spend-out-from-under-you attacks, especially
197
        // in shared-wallet situations.
198
0
        std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
199
0
        if (!PermitsUncompressed(sigversion)) {
200
0
            for (size_t i = 0; i < keys.size(); i++) {
201
0
                if (keys[i].size() != 33) {
202
0
                    return IsMineResult::INVALID;
203
0
                }
204
0
            }
205
0
        }
206
0
        if (HaveKeys(keys, keystore)) {
207
0
            ret = std::max(ret, IsMineResult::SPENDABLE);
208
0
        }
209
0
        break;
210
0
    }
211
0
    } // no default case, so the compiler can warn about missing cases
212
213
0
    if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
214
0
        ret = std::max(ret, IsMineResult::WATCH_ONLY);
215
0
    }
216
0
    return ret;
217
0
}
218
219
} // namespace
220
221
isminetype LegacyDataSPKM::IsMine(const CScript& script) const
222
0
{
223
0
    switch (IsMineInner(*this, script, IsMineSigVersion::TOP)) {
224
0
    case IsMineResult::INVALID:
225
0
    case IsMineResult::NO:
226
0
        return ISMINE_NO;
227
0
    case IsMineResult::WATCH_ONLY:
228
0
        return ISMINE_WATCH_ONLY;
229
0
    case IsMineResult::SPENDABLE:
230
0
        return ISMINE_SPENDABLE;
231
0
    }
232
0
    assert(false);
233
0
}
234
235
bool LegacyDataSPKM::CheckDecryptionKey(const CKeyingMaterial& master_key)
236
0
{
237
0
    {
238
0
        LOCK(cs_KeyStore);
239
0
        assert(mapKeys.empty());
240
241
0
        bool keyPass = mapCryptedKeys.empty(); // Always pass when there are no encrypted keys
242
0
        bool keyFail = false;
243
0
        CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
244
0
        WalletBatch batch(m_storage.GetDatabase());
245
0
        for (; mi != mapCryptedKeys.end(); ++mi)
246
0
        {
247
0
            const CPubKey &vchPubKey = (*mi).second.first;
248
0
            const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
249
0
            CKey key;
250
0
            if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
251
0
            {
252
0
                keyFail = true;
253
0
                break;
254
0
            }
255
0
            keyPass = true;
256
0
            if (fDecryptionThoroughlyChecked)
257
0
                break;
258
0
            else {
259
                // Rewrite these encrypted keys with checksums
260
0
                batch.WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
261
0
            }
262
0
        }
263
0
        if (keyPass && keyFail)
264
0
        {
265
0
            LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
266
0
            throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
267
0
        }
268
0
        if (keyFail || !keyPass)
269
0
            return false;
270
0
        fDecryptionThoroughlyChecked = true;
271
0
    }
272
0
    return true;
273
0
}
274
275
bool LegacyScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
276
0
{
277
0
    LOCK(cs_KeyStore);
278
0
    encrypted_batch = batch;
279
0
    if (!mapCryptedKeys.empty()) {
280
0
        encrypted_batch = nullptr;
281
0
        return false;
282
0
    }
283
284
0
    KeyMap keys_to_encrypt;
285
0
    keys_to_encrypt.swap(mapKeys); // Clear mapKeys so AddCryptedKeyInner will succeed.
286
0
    for (const KeyMap::value_type& mKey : keys_to_encrypt)
287
0
    {
288
0
        const CKey &key = mKey.second;
289
0
        CPubKey vchPubKey = key.GetPubKey();
290
0
        CKeyingMaterial vchSecret{UCharCast(key.begin()), UCharCast(key.end())};
291
0
        std::vector<unsigned char> vchCryptedSecret;
292
0
        if (!EncryptSecret(master_key, vchSecret, vchPubKey.GetHash(), vchCryptedSecret)) {
293
0
            encrypted_batch = nullptr;
294
0
            return false;
295
0
        }
296
0
        if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) {
297
0
            encrypted_batch = nullptr;
298
0
            return false;
299
0
        }
300
0
    }
301
0
    encrypted_batch = nullptr;
302
0
    return true;
303
0
}
304
305
util::Result<CTxDestination> LegacyScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, int64_t& index, CKeyPool& keypool)
306
0
{
307
0
    if (LEGACY_OUTPUT_TYPES.count(type) == 0) {
308
0
        return util::Error{_("Error: Legacy wallets only support the \"legacy\", \"p2sh-segwit\", and \"bech32\" address types")};
309
0
    }
310
0
    assert(type != OutputType::BECH32M);
311
312
0
    LOCK(cs_KeyStore);
313
0
    if (!CanGetAddresses(internal)) {
314
0
        return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
315
0
    }
316
317
    // Fill-up keypool if needed
318
0
    TopUp();
319
320
0
    if (!ReserveKeyFromKeyPool(index, keypool, internal)) {
321
0
        return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
322
0
    }
323
0
    return GetDestinationForKey(keypool.vchPubKey, type);
324
0
}
325
326
bool LegacyScriptPubKeyMan::TopUpInactiveHDChain(const CKeyID seed_id, int64_t index, bool internal)
327
0
{
328
0
    LOCK(cs_KeyStore);
329
330
0
    auto it = m_inactive_hd_chains.find(seed_id);
331
0
    if (it == m_inactive_hd_chains.end()) {
332
0
        return false;
333
0
    }
334
335
0
    CHDChain& chain = it->second;
336
337
0
    if (internal) {
338
0
        chain.m_next_internal_index = std::max(chain.m_next_internal_index, index + 1);
339
0
    } else {
340
0
        chain.m_next_external_index = std::max(chain.m_next_external_index, index + 1);
341
0
    }
342
343
0
    WalletBatch batch(m_storage.GetDatabase());
344
0
    TopUpChain(batch, chain, 0);
345
346
0
    return true;
347
0
}
348
349
std::vector<WalletDestination> LegacyScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
350
0
{
351
0
    LOCK(cs_KeyStore);
352
0
    std::vector<WalletDestination> result;
353
    // extract addresses and check if they match with an unused keypool key
354
0
    for (const auto& keyid : GetAffectedKeys(script, *this)) {
355
0
        std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
356
0
        if (mi != m_pool_key_to_index.end()) {
357
0
            WalletLogPrintf("%s: Detected a used keypool key, mark all keypool keys up to this key as used\n", __func__);
358
0
            for (const auto& keypool : MarkReserveKeysAsUsed(mi->second)) {
359
                // derive all possible destinations as any of them could have been used
360
0
                for (const auto& type : LEGACY_OUTPUT_TYPES) {
361
0
                    const auto& dest = GetDestinationForKey(keypool.vchPubKey, type);
362
0
                    result.push_back({dest, keypool.fInternal});
363
0
                }
364
0
            }
365
366
0
            if (!TopUp()) {
367
0
                WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
368
0
            }
369
0
        }
370
371
        // Find the key's metadata and check if it's seed id (if it has one) is inactive, i.e. it is not the current m_hd_chain seed id.
372
        // If so, TopUp the inactive hd chain
373
0
        auto it = mapKeyMetadata.find(keyid);
374
0
        if (it != mapKeyMetadata.end()){
375
0
            CKeyMetadata meta = it->second;
376
0
            if (!meta.hd_seed_id.IsNull() && meta.hd_seed_id != m_hd_chain.seed_id) {
377
0
                std::vector<uint32_t> path;
378
0
                if (meta.has_key_origin) {
379
0
                    path = meta.key_origin.path;
380
0
                } else if (!ParseHDKeypath(meta.hdKeypath, path)) {
381
0
                    WalletLogPrintf("%s: Adding inactive seed keys failed, invalid hdKeypath: %s\n",
382
0
                                    __func__,
383
0
                                    meta.hdKeypath);
384
0
                }
385
0
                if (path.size() != 3) {
386
0
                    WalletLogPrintf("%s: Adding inactive seed keys failed, invalid path size: %d, has_key_origin: %s\n",
387
0
                                    __func__,
388
0
                                    path.size(),
389
0
                                    meta.has_key_origin);
390
0
                } else {
391
0
                    bool internal = (path[1] & ~BIP32_HARDENED_KEY_LIMIT) != 0;
392
0
                    int64_t index = path[2] & ~BIP32_HARDENED_KEY_LIMIT;
393
394
0
                    if (!TopUpInactiveHDChain(meta.hd_seed_id, index, internal)) {
395
0
                        WalletLogPrintf("%s: Adding inactive seed keys failed\n", __func__);
396
0
                    }
397
0
                }
398
0
            }
399
0
        }
400
0
    }
401
402
0
    return result;
403
0
}
404
405
void LegacyScriptPubKeyMan::UpgradeKeyMetadata()
406
0
{
407
0
    LOCK(cs_KeyStore);
408
0
    if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
409
0
        return;
410
0
    }
411
412
0
    std::unique_ptr<WalletBatch> batch = std::make_unique<WalletBatch>(m_storage.GetDatabase());
413
0
    for (auto& meta_pair : mapKeyMetadata) {
414
0
        CKeyMetadata& meta = meta_pair.second;
415
0
        if (!meta.hd_seed_id.IsNull() && !meta.has_key_origin && meta.hdKeypath != "s") { // If the hdKeypath is "s", that's the seed and it doesn't have a key origin
416
0
            CKey key;
417
0
            GetKey(meta.hd_seed_id, key);
418
0
            CExtKey masterKey;
419
0
            masterKey.SetSeed(key);
420
            // Add to map
421
0
            CKeyID master_id = masterKey.key.GetPubKey().GetID();
422
0
            std::copy(master_id.begin(), master_id.begin() + 4, meta.key_origin.fingerprint);
423
0
            if (!ParseHDKeypath(meta.hdKeypath, meta.key_origin.path)) {
424
0
                throw std::runtime_error("Invalid stored hdKeypath");
425
0
            }
426
0
            meta.has_key_origin = true;
427
0
            if (meta.nVersion < CKeyMetadata::VERSION_WITH_KEY_ORIGIN) {
428
0
                meta.nVersion = CKeyMetadata::VERSION_WITH_KEY_ORIGIN;
429
0
            }
430
431
            // Write meta to wallet
432
0
            CPubKey pubkey;
433
0
            if (GetPubKey(meta_pair.first, pubkey)) {
434
0
                batch->WriteKeyMetadata(meta, pubkey, true);
435
0
            }
436
0
        }
437
0
    }
438
0
}
439
440
bool LegacyScriptPubKeyMan::SetupGeneration(bool force)
441
0
{
442
0
    if ((CanGenerateKeys() && !force) || m_storage.IsLocked()) {
443
0
        return false;
444
0
    }
445
446
0
    SetHDSeed(GenerateNewSeed());
447
0
    if (!NewKeyPool()) {
448
0
        return false;
449
0
    }
450
0
    return true;
451
0
}
452
453
bool LegacyScriptPubKeyMan::IsHDEnabled() const
454
0
{
455
0
    return !m_hd_chain.seed_id.IsNull();
456
0
}
457
458
bool LegacyScriptPubKeyMan::CanGetAddresses(bool internal) const
459
0
{
460
0
    LOCK(cs_KeyStore);
461
    // Check if the keypool has keys
462
0
    bool keypool_has_keys;
463
0
    if (internal && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
464
0
        keypool_has_keys = setInternalKeyPool.size() > 0;
465
0
    } else {
466
0
        keypool_has_keys = KeypoolCountExternalKeys() > 0;
467
0
    }
468
    // If the keypool doesn't have keys, check if we can generate them
469
0
    if (!keypool_has_keys) {
470
0
        return CanGenerateKeys();
471
0
    }
472
0
    return keypool_has_keys;
473
0
}
474
475
bool LegacyScriptPubKeyMan::Upgrade(int prev_version, int new_version, bilingual_str& error)
476
0
{
477
0
    LOCK(cs_KeyStore);
478
479
0
    if (m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
480
        // Nothing to do here if private keys are not enabled
481
0
        return true;
482
0
    }
483
484
0
    bool hd_upgrade = false;
485
0
    bool split_upgrade = false;
486
0
    if (IsFeatureSupported(new_version, FEATURE_HD) && !IsHDEnabled()) {
487
0
        WalletLogPrintf("Upgrading wallet to HD\n");
488
0
        m_storage.SetMinVersion(FEATURE_HD);
489
490
        // generate a new master key
491
0
        CPubKey masterPubKey = GenerateNewSeed();
492
0
        SetHDSeed(masterPubKey);
493
0
        hd_upgrade = true;
494
0
    }
495
    // Upgrade to HD chain split if necessary
496
0
    if (!IsFeatureSupported(prev_version, FEATURE_HD_SPLIT) && IsFeatureSupported(new_version, FEATURE_HD_SPLIT)) {
497
0
        WalletLogPrintf("Upgrading wallet to use HD chain split\n");
498
0
        m_storage.SetMinVersion(FEATURE_PRE_SPLIT_KEYPOOL);
499
0
        split_upgrade = FEATURE_HD_SPLIT > prev_version;
500
        // Upgrade the HDChain
501
0
        if (m_hd_chain.nVersion < CHDChain::VERSION_HD_CHAIN_SPLIT) {
502
0
            m_hd_chain.nVersion = CHDChain::VERSION_HD_CHAIN_SPLIT;
503
0
            if (!WalletBatch(m_storage.GetDatabase()).WriteHDChain(m_hd_chain)) {
504
0
                throw std::runtime_error(std::string(__func__) + ": writing chain failed");
505
0
            }
506
0
        }
507
0
    }
508
    // Mark all keys currently in the keypool as pre-split
509
0
    if (split_upgrade) {
510
0
        MarkPreSplitKeys();
511
0
    }
512
    // Regenerate the keypool if upgraded to HD
513
0
    if (hd_upgrade) {
514
0
        if (!NewKeyPool()) {
515
0
            error = _("Unable to generate keys");
516
0
            return false;
517
0
        }
518
0
    }
519
0
    return true;
520
0
}
521
522
bool LegacyScriptPubKeyMan::HavePrivateKeys() const
523
0
{
524
0
    LOCK(cs_KeyStore);
525
0
    return !mapKeys.empty() || !mapCryptedKeys.empty();
526
0
}
527
528
bool LegacyScriptPubKeyMan::HaveCryptedKeys() const
529
0
{
530
0
    LOCK(cs_KeyStore);
531
0
    return !mapCryptedKeys.empty();
532
0
}
533
534
void LegacyScriptPubKeyMan::RewriteDB()
535
0
{
536
0
    LOCK(cs_KeyStore);
537
0
    setInternalKeyPool.clear();
538
0
    setExternalKeyPool.clear();
539
0
    m_pool_key_to_index.clear();
540
    // Note: can't top-up keypool here, because wallet is locked.
541
    // User will be prompted to unlock wallet the next operation
542
    // that requires a new key.
543
0
}
544
545
0
static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, WalletBatch& batch) {
546
0
    if (setKeyPool.empty()) {
547
0
        return GetTime();
548
0
    }
549
550
0
    CKeyPool keypool;
551
0
    int64_t nIndex = *(setKeyPool.begin());
552
0
    if (!batch.ReadPool(nIndex, keypool)) {
553
0
        throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
554
0
    }
555
0
    assert(keypool.vchPubKey.IsValid());
556
0
    return keypool.nTime;
557
0
}
558
559
std::optional<int64_t> LegacyScriptPubKeyMan::GetOldestKeyPoolTime() const
560
0
{
561
0
    LOCK(cs_KeyStore);
562
563
0
    WalletBatch batch(m_storage.GetDatabase());
564
565
    // load oldest key from keypool, get time and return
566
0
    int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, batch);
567
0
    if (IsHDEnabled() && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
568
0
        oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, batch), oldestKey);
569
0
        if (!set_pre_split_keypool.empty()) {
570
0
            oldestKey = std::max(GetOldestKeyTimeInPool(set_pre_split_keypool, batch), oldestKey);
571
0
        }
572
0
    }
573
574
0
    return oldestKey;
575
0
}
576
577
size_t LegacyScriptPubKeyMan::KeypoolCountExternalKeys() const
578
0
{
579
0
    LOCK(cs_KeyStore);
580
0
    return setExternalKeyPool.size() + set_pre_split_keypool.size();
581
0
}
582
583
unsigned int LegacyScriptPubKeyMan::GetKeyPoolSize() const
584
0
{
585
0
    LOCK(cs_KeyStore);
586
0
    return setInternalKeyPool.size() + setExternalKeyPool.size() + set_pre_split_keypool.size();
587
0
}
588
589
int64_t LegacyScriptPubKeyMan::GetTimeFirstKey() const
590
0
{
591
0
    LOCK(cs_KeyStore);
592
0
    return nTimeFirstKey;
593
0
}
594
595
std::unique_ptr<SigningProvider> LegacyDataSPKM::GetSolvingProvider(const CScript& script) const
596
0
{
597
0
    return std::make_unique<LegacySigningProvider>(*this);
598
0
}
599
600
bool LegacyDataSPKM::CanProvide(const CScript& script, SignatureData& sigdata)
601
0
{
602
0
    IsMineResult ismine = IsMineInner(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
603
0
    if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
604
        // If ismine, it means we recognize keys or script ids in the script, or
605
        // are watching the script itself, and we can at least provide metadata
606
        // or solving information, even if not able to sign fully.
607
0
        return true;
608
0
    } else {
609
        // If, given the stuff in sigdata, we could make a valid signature, then we can provide for this script
610
0
        ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
611
0
        if (!sigdata.signatures.empty()) {
612
            // If we could make signatures, make sure we have a private key to actually make a signature
613
0
            bool has_privkeys = false;
614
0
            for (const auto& key_sig_pair : sigdata.signatures) {
615
0
                has_privkeys |= HaveKey(key_sig_pair.first);
616
0
            }
617
0
            return has_privkeys;
618
0
        }
619
0
        return false;
620
0
    }
621
0
}
622
623
bool LegacyScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
624
0
{
625
0
    return ::SignTransaction(tx, this, coins, sighash, input_errors);
626
0
}
627
628
SigningResult LegacyScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
629
0
{
630
0
    CKey key;
631
0
    if (!GetKey(ToKeyID(pkhash), key)) {
632
0
        return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
633
0
    }
634
635
0
    if (MessageSign(key, message, str_sig)) {
636
0
        return SigningResult::OK;
637
0
    }
638
0
    return SigningResult::SIGNING_FAILED;
639
0
}
640
641
std::optional<PSBTError> LegacyScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, int sighash_type, bool sign, bool bip32derivs, int* n_signed, bool finalize) const
642
0
{
643
0
    if (n_signed) {
644
0
        *n_signed = 0;
645
0
    }
646
0
    for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
647
0
        const CTxIn& txin = psbtx.tx->vin[i];
648
0
        PSBTInput& input = psbtx.inputs.at(i);
649
650
0
        if (PSBTInputSigned(input)) {
651
0
            continue;
652
0
        }
653
654
        // Get the Sighash type
655
0
        if (sign && input.sighash_type != std::nullopt && *input.sighash_type != sighash_type) {
656
0
            return PSBTError::SIGHASH_MISMATCH;
657
0
        }
658
659
        // Check non_witness_utxo has specified prevout
660
0
        if (input.non_witness_utxo) {
661
0
            if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
662
0
                return PSBTError::MISSING_INPUTS;
663
0
            }
664
0
        } else if (input.witness_utxo.IsNull()) {
665
            // There's no UTXO so we can just skip this now
666
0
            continue;
667
0
        }
668
0
        SignPSBTInput(HidingSigningProvider(this, !sign, !bip32derivs), psbtx, i, &txdata, sighash_type, nullptr, finalize);
669
670
0
        bool signed_one = PSBTInputSigned(input);
671
0
        if (n_signed && (signed_one || !sign)) {
672
            // If sign is false, we assume that we _could_ sign if we get here. This
673
            // will never have false negatives; it is hard to tell under what i
674
            // circumstances it could have false positives.
675
0
            (*n_signed)++;
676
0
        }
677
0
    }
678
679
    // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
680
0
    for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
681
0
        UpdatePSBTOutput(HidingSigningProvider(this, true, !bip32derivs), psbtx, i);
682
0
    }
683
684
0
    return {};
685
0
}
686
687
std::unique_ptr<CKeyMetadata> LegacyScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
688
0
{
689
0
    LOCK(cs_KeyStore);
690
691
0
    CKeyID key_id = GetKeyForDestination(*this, dest);
692
0
    if (!key_id.IsNull()) {
693
0
        auto it = mapKeyMetadata.find(key_id);
694
0
        if (it != mapKeyMetadata.end()) {
695
0
            return std::make_unique<CKeyMetadata>(it->second);
696
0
        }
697
0
    }
698
699
0
    CScript scriptPubKey = GetScriptForDestination(dest);
700
0
    auto it = m_script_metadata.find(CScriptID(scriptPubKey));
701
0
    if (it != m_script_metadata.end()) {
702
0
        return std::make_unique<CKeyMetadata>(it->second);
703
0
    }
704
705
0
    return nullptr;
706
0
}
707
708
uint256 LegacyScriptPubKeyMan::GetID() const
709
0
{
710
0
    return uint256::ONE;
711
0
}
712
713
/**
714
 * Update wallet first key creation time. This should be called whenever keys
715
 * are added to the wallet, with the oldest key creation time.
716
 */
717
void LegacyScriptPubKeyMan::UpdateTimeFirstKey(int64_t nCreateTime)
718
0
{
719
0
    AssertLockHeld(cs_KeyStore);
720
0
    if (nCreateTime <= 1) {
721
        // Cannot determine birthday information, so set the wallet birthday to
722
        // the beginning of time.
723
0
        nTimeFirstKey = 1;
724
0
    } else if (nTimeFirstKey == UNKNOWN_TIME || nCreateTime < nTimeFirstKey) {
725
0
        nTimeFirstKey = nCreateTime;
726
0
    }
727
728
0
    NotifyFirstKeyTimeChanged(this, nTimeFirstKey);
729
0
}
730
731
bool LegacyDataSPKM::LoadKey(const CKey& key, const CPubKey &pubkey)
732
0
{
733
0
    return AddKeyPubKeyInner(key, pubkey);
734
0
}
735
736
bool LegacyScriptPubKeyMan::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
737
0
{
738
0
    LOCK(cs_KeyStore);
739
0
    WalletBatch batch(m_storage.GetDatabase());
740
0
    return LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(batch, secret, pubkey);
741
0
}
742
743
bool LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(WalletBatch& batch, const CKey& secret, const CPubKey& pubkey)
744
0
{
745
0
    AssertLockHeld(cs_KeyStore);
746
747
    // Make sure we aren't adding private keys to private key disabled wallets
748
0
    assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
749
750
    // FillableSigningProvider has no concept of wallet databases, but calls AddCryptedKey
751
    // which is overridden below.  To avoid flushes, the database handle is
752
    // tunneled through to it.
753
0
    bool needsDB = !encrypted_batch;
754
0
    if (needsDB) {
755
0
        encrypted_batch = &batch;
756
0
    }
757
0
    if (!AddKeyPubKeyInner(secret, pubkey)) {
758
0
        if (needsDB) encrypted_batch = nullptr;
759
0
        return false;
760
0
    }
761
0
    if (needsDB) encrypted_batch = nullptr;
762
763
    // check if we need to remove from watch-only
764
0
    CScript script;
765
0
    script = GetScriptForDestination(PKHash(pubkey));
766
0
    if (HaveWatchOnly(script)) {
767
0
        RemoveWatchOnly(script);
768
0
    }
769
0
    script = GetScriptForRawPubKey(pubkey);
770
0
    if (HaveWatchOnly(script)) {
771
0
        RemoveWatchOnly(script);
772
0
    }
773
774
0
    m_storage.UnsetBlankWalletFlag(batch);
775
0
    if (!m_storage.HasEncryptionKeys()) {
776
0
        return batch.WriteKey(pubkey,
777
0
                                                 secret.GetPrivKey(),
778
0
                                                 mapKeyMetadata[pubkey.GetID()]);
779
0
    }
780
0
    return true;
781
0
}
782
783
bool LegacyDataSPKM::LoadCScript(const CScript& redeemScript)
784
0
{
785
    /* A sanity check was added in pull #3843 to avoid adding redeemScripts
786
     * that never can be redeemed. However, old wallets may still contain
787
     * these. Do not add them to the wallet and warn. */
788
0
    if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
789
0
    {
790
0
        std::string strAddr = EncodeDestination(ScriptHash(redeemScript));
791
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);
792
0
        return true;
793
0
    }
794
795
0
    return FillableSigningProvider::AddCScript(redeemScript);
796
0
}
797
798
void LegacyDataSPKM::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
799
0
{
800
0
    LOCK(cs_KeyStore);
801
0
    mapKeyMetadata[keyID] = meta;
802
0
}
803
804
void LegacyScriptPubKeyMan::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
805
0
{
806
0
    LOCK(cs_KeyStore);
807
0
    LegacyDataSPKM::LoadKeyMetadata(keyID, meta);
808
0
    UpdateTimeFirstKey(meta.nCreateTime);
809
0
}
810
811
void LegacyDataSPKM::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata& meta)
812
0
{
813
0
    LOCK(cs_KeyStore);
814
0
    m_script_metadata[script_id] = meta;
815
0
}
816
817
void LegacyScriptPubKeyMan::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata& meta)
818
0
{
819
0
    LOCK(cs_KeyStore);
820
0
    LegacyDataSPKM::LoadScriptMetadata(script_id, meta);
821
0
    UpdateTimeFirstKey(meta.nCreateTime);
822
0
}
823
824
bool LegacyDataSPKM::AddKeyPubKeyInner(const CKey& key, const CPubKey& pubkey)
825
0
{
826
0
    LOCK(cs_KeyStore);
827
0
    return FillableSigningProvider::AddKeyPubKey(key, pubkey);
828
0
}
829
830
bool LegacyScriptPubKeyMan::AddKeyPubKeyInner(const CKey& key, const CPubKey &pubkey)
831
0
{
832
0
    LOCK(cs_KeyStore);
833
0
    if (!m_storage.HasEncryptionKeys()) {
834
0
        return FillableSigningProvider::AddKeyPubKey(key, pubkey);
835
0
    }
836
837
0
    if (m_storage.IsLocked()) {
838
0
        return false;
839
0
    }
840
841
0
    std::vector<unsigned char> vchCryptedSecret;
842
0
    CKeyingMaterial vchSecret{UCharCast(key.begin()), UCharCast(key.end())};
843
0
    if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
844
0
            return EncryptSecret(encryption_key, vchSecret, pubkey.GetHash(), vchCryptedSecret);
845
0
        })) {
846
0
        return false;
847
0
    }
848
849
0
    if (!AddCryptedKey(pubkey, vchCryptedSecret)) {
850
0
        return false;
851
0
    }
852
0
    return true;
853
0
}
854
855
bool LegacyDataSPKM::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid)
856
0
{
857
    // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
858
0
    if (!checksum_valid) {
859
0
        fDecryptionThoroughlyChecked = false;
860
0
    }
861
862
0
    return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
863
0
}
864
865
bool LegacyDataSPKM::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
866
0
{
867
0
    LOCK(cs_KeyStore);
868
0
    assert(mapKeys.empty());
869
870
0
    mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
871
0
    ImplicitlyLearnRelatedKeyScripts(vchPubKey);
872
0
    return true;
873
0
}
874
875
bool LegacyScriptPubKeyMan::AddCryptedKey(const CPubKey &vchPubKey,
876
                            const std::vector<unsigned char> &vchCryptedSecret)
877
0
{
878
0
    if (!AddCryptedKeyInner(vchPubKey, vchCryptedSecret))
879
0
        return false;
880
0
    {
881
0
        LOCK(cs_KeyStore);
882
0
        if (encrypted_batch)
883
0
            return encrypted_batch->WriteCryptedKey(vchPubKey,
884
0
                                                        vchCryptedSecret,
885
0
                                                        mapKeyMetadata[vchPubKey.GetID()]);
886
0
        else
887
0
            return WalletBatch(m_storage.GetDatabase()).WriteCryptedKey(vchPubKey,
888
0
                                                            vchCryptedSecret,
889
0
                                                            mapKeyMetadata[vchPubKey.GetID()]);
890
0
    }
891
0
}
892
893
bool LegacyDataSPKM::HaveWatchOnly(const CScript &dest) const
894
0
{
895
0
    LOCK(cs_KeyStore);
896
0
    return setWatchOnly.count(dest) > 0;
897
0
}
898
899
bool LegacyDataSPKM::HaveWatchOnly() const
900
0
{
901
0
    LOCK(cs_KeyStore);
902
0
    return (!setWatchOnly.empty());
903
0
}
904
905
static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
906
0
{
907
0
    std::vector<std::vector<unsigned char>> solutions;
908
0
    return Solver(dest, solutions) == TxoutType::PUBKEY &&
909
0
        (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
910
0
}
911
912
bool LegacyScriptPubKeyMan::RemoveWatchOnly(const CScript &dest)
913
0
{
914
0
    {
915
0
        LOCK(cs_KeyStore);
916
0
        setWatchOnly.erase(dest);
917
0
        CPubKey pubKey;
918
0
        if (ExtractPubKey(dest, pubKey)) {
919
0
            mapWatchKeys.erase(pubKey.GetID());
920
0
        }
921
        // Related CScripts are not removed; having superfluous scripts around is
922
        // harmless (see comment in ImplicitlyLearnRelatedKeyScripts).
923
0
    }
924
925
0
    if (!HaveWatchOnly())
926
0
        NotifyWatchonlyChanged(false);
927
0
    if (!WalletBatch(m_storage.GetDatabase()).EraseWatchOnly(dest))
928
0
        return false;
929
930
0
    return true;
931
0
}
932
933
bool LegacyDataSPKM::LoadWatchOnly(const CScript &dest)
934
0
{
935
0
    return AddWatchOnlyInMem(dest);
936
0
}
937
938
bool LegacyDataSPKM::AddWatchOnlyInMem(const CScript &dest)
939
0
{
940
0
    LOCK(cs_KeyStore);
941
0
    setWatchOnly.insert(dest);
942
0
    CPubKey pubKey;
943
0
    if (ExtractPubKey(dest, pubKey)) {
944
0
        mapWatchKeys[pubKey.GetID()] = pubKey;
945
0
        ImplicitlyLearnRelatedKeyScripts(pubKey);
946
0
    }
947
0
    return true;
948
0
}
949
950
bool LegacyScriptPubKeyMan::AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest)
951
0
{
952
0
    if (!AddWatchOnlyInMem(dest))
953
0
        return false;
954
0
    const CKeyMetadata& meta = m_script_metadata[CScriptID(dest)];
955
0
    UpdateTimeFirstKey(meta.nCreateTime);
956
0
    NotifyWatchonlyChanged(true);
957
0
    if (batch.WriteWatchOnly(dest, meta)) {
958
0
        m_storage.UnsetBlankWalletFlag(batch);
959
0
        return true;
960
0
    }
961
0
    return false;
962
0
}
963
964
bool LegacyScriptPubKeyMan::AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest, int64_t create_time)
965
0
{
966
0
    m_script_metadata[CScriptID(dest)].nCreateTime = create_time;
967
0
    return AddWatchOnlyWithDB(batch, dest);
968
0
}
969
970
bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript& dest)
971
0
{
972
0
    WalletBatch batch(m_storage.GetDatabase());
973
0
    return AddWatchOnlyWithDB(batch, dest);
974
0
}
975
976
bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
977
0
{
978
0
    m_script_metadata[CScriptID(dest)].nCreateTime = nCreateTime;
979
0
    return AddWatchOnly(dest);
980
0
}
981
982
void LegacyDataSPKM::LoadHDChain(const CHDChain& chain)
983
0
{
984
0
    LOCK(cs_KeyStore);
985
0
    m_hd_chain = chain;
986
0
}
987
988
void LegacyScriptPubKeyMan::AddHDChain(const CHDChain& chain)
989
0
{
990
0
    LOCK(cs_KeyStore);
991
    // Store the new chain
992
0
    if (!WalletBatch(m_storage.GetDatabase()).WriteHDChain(chain)) {
993
0
        throw std::runtime_error(std::string(__func__) + ": writing chain failed");
994
0
    }
995
    // When there's an old chain, add it as an inactive chain as we are now rotating hd chains
996
0
    if (!m_hd_chain.seed_id.IsNull()) {
997
0
        AddInactiveHDChain(m_hd_chain);
998
0
    }
999
1000
0
    m_hd_chain = chain;
1001
0
}
1002
1003
void LegacyDataSPKM::AddInactiveHDChain(const CHDChain& chain)
1004
0
{
1005
0
    LOCK(cs_KeyStore);
1006
0
    assert(!chain.seed_id.IsNull());
1007
0
    m_inactive_hd_chains[chain.seed_id] = chain;
1008
0
}
1009
1010
bool LegacyDataSPKM::HaveKey(const CKeyID &address) const
1011
0
{
1012
0
    LOCK(cs_KeyStore);
1013
0
    if (!m_storage.HasEncryptionKeys()) {
1014
0
        return FillableSigningProvider::HaveKey(address);
1015
0
    }
1016
0
    return mapCryptedKeys.count(address) > 0;
1017
0
}
1018
1019
bool LegacyDataSPKM::GetKey(const CKeyID &address, CKey& keyOut) const
1020
0
{
1021
0
    LOCK(cs_KeyStore);
1022
0
    if (!m_storage.HasEncryptionKeys()) {
1023
0
        return FillableSigningProvider::GetKey(address, keyOut);
1024
0
    }
1025
1026
0
    CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
1027
0
    if (mi != mapCryptedKeys.end())
1028
0
    {
1029
0
        const CPubKey &vchPubKey = (*mi).second.first;
1030
0
        const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
1031
0
        return m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
1032
0
            return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey, keyOut);
1033
0
        });
1034
0
    }
1035
0
    return false;
1036
0
}
1037
1038
bool LegacyDataSPKM::GetKeyOrigin(const CKeyID& keyID, KeyOriginInfo& info) const
1039
0
{
1040
0
    CKeyMetadata meta;
1041
0
    {
1042
0
        LOCK(cs_KeyStore);
1043
0
        auto it = mapKeyMetadata.find(keyID);
1044
0
        if (it == mapKeyMetadata.end()) {
1045
0
            return false;
1046
0
        }
1047
0
        meta = it->second;
1048
0
    }
1049
0
    if (meta.has_key_origin) {
1050
0
        std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4, info.fingerprint);
1051
0
        info.path = meta.key_origin.path;
1052
0
    } else { // Single pubkeys get the master fingerprint of themselves
1053
0
        std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
1054
0
    }
1055
0
    return true;
1056
0
}
1057
1058
bool LegacyDataSPKM::GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
1059
0
{
1060
0
    LOCK(cs_KeyStore);
1061
0
    WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
1062
0
    if (it != mapWatchKeys.end()) {
1063
0
        pubkey_out = it->second;
1064
0
        return true;
1065
0
    }
1066
0
    return false;
1067
0
}
1068
1069
bool LegacyDataSPKM::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
1070
0
{
1071
0
    LOCK(cs_KeyStore);
1072
0
    if (!m_storage.HasEncryptionKeys()) {
1073
0
        if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
1074
0
            return GetWatchPubKey(address, vchPubKeyOut);
1075
0
        }
1076
0
        return true;
1077
0
    }
1078
1079
0
    CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
1080
0
    if (mi != mapCryptedKeys.end())
1081
0
    {
1082
0
        vchPubKeyOut = (*mi).second.first;
1083
0
        return true;
1084
0
    }
1085
    // Check for watch-only pubkeys
1086
0
    return GetWatchPubKey(address, vchPubKeyOut);
1087
0
}
1088
1089
CPubKey LegacyScriptPubKeyMan::GenerateNewKey(WalletBatch &batch, CHDChain& hd_chain, bool internal)
1090
0
{
1091
0
    assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
1092
0
    assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET));
1093
0
    AssertLockHeld(cs_KeyStore);
1094
0
    bool fCompressed = m_storage.CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
1095
1096
0
    CKey secret;
1097
1098
    // Create new metadata
1099
0
    int64_t nCreationTime = GetTime();
1100
0
    CKeyMetadata metadata(nCreationTime);
1101
1102
    // use HD key derivation if HD was enabled during wallet creation and a seed is present
1103
0
    if (IsHDEnabled()) {
1104
0
        DeriveNewChildKey(batch, metadata, secret, hd_chain, (m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
1105
0
    } else {
1106
0
        secret.MakeNewKey(fCompressed);
1107
0
    }
1108
1109
    // Compressed public keys were introduced in version 0.6.0
1110
0
    if (fCompressed) {
1111
0
        m_storage.SetMinVersion(FEATURE_COMPRPUBKEY);
1112
0
    }
1113
1114
0
    CPubKey pubkey = secret.GetPubKey();
1115
0
    assert(secret.VerifyPubKey(pubkey));
1116
1117
0
    mapKeyMetadata[pubkey.GetID()] = metadata;
1118
0
    UpdateTimeFirstKey(nCreationTime);
1119
1120
0
    if (!AddKeyPubKeyWithDB(batch, secret, pubkey)) {
1121
0
        throw std::runtime_error(std::string(__func__) + ": AddKey failed");
1122
0
    }
1123
0
    return pubkey;
1124
0
}
1125
1126
//! Try to derive an extended key, throw if it fails.
1127
0
static void DeriveExtKey(CExtKey& key_in, unsigned int index, CExtKey& key_out) {
1128
0
    if (!key_in.Derive(key_out, index)) {
1129
0
        throw std::runtime_error("Could not derive extended key");
1130
0
    }
1131
0
}
1132
1133
void LegacyScriptPubKeyMan::DeriveNewChildKey(WalletBatch &batch, CKeyMetadata& metadata, CKey& secret, CHDChain& hd_chain, bool internal)
1134
0
{
1135
    // for now we use a fixed keypath scheme of m/0'/0'/k
1136
0
    CKey seed;                     //seed (256bit)
1137
0
    CExtKey masterKey;             //hd master key
1138
0
    CExtKey accountKey;            //key at m/0'
1139
0
    CExtKey chainChildKey;         //key at m/0'/0' (external) or m/0'/1' (internal)
1140
0
    CExtKey childKey;              //key at m/0'/0'/<n>'
1141
1142
    // try to get the seed
1143
0
    if (!GetKey(hd_chain.seed_id, seed))
1144
0
        throw std::runtime_error(std::string(__func__) + ": seed not found");
1145
1146
0
    masterKey.SetSeed(seed);
1147
1148
    // derive m/0'
1149
    // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
1150
0
    DeriveExtKey(masterKey, BIP32_HARDENED_KEY_LIMIT, accountKey);
1151
1152
    // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
1153
0
    assert(internal ? m_storage.CanSupportFeature(FEATURE_HD_SPLIT) : true);
1154
0
    DeriveExtKey(accountKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0), chainChildKey);
1155
1156
    // derive child key at next index, skip keys already known to the wallet
1157
0
    do {
1158
        // always derive hardened keys
1159
        // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
1160
        // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
1161
0
        if (internal) {
1162
0
            DeriveExtKey(chainChildKey, hd_chain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT, childKey);
1163
0
            metadata.hdKeypath = "m/0'/1'/" + ToString(hd_chain.nInternalChainCounter) + "'";
1164
0
            metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1165
0
            metadata.key_origin.path.push_back(1 | BIP32_HARDENED_KEY_LIMIT);
1166
0
            metadata.key_origin.path.push_back(hd_chain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
1167
0
            hd_chain.nInternalChainCounter++;
1168
0
        }
1169
0
        else {
1170
0
            DeriveExtKey(chainChildKey, hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT, childKey);
1171
0
            metadata.hdKeypath = "m/0'/0'/" + ToString(hd_chain.nExternalChainCounter) + "'";
1172
0
            metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1173
0
            metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1174
0
            metadata.key_origin.path.push_back(hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
1175
0
            hd_chain.nExternalChainCounter++;
1176
0
        }
1177
0
    } while (HaveKey(childKey.key.GetPubKey().GetID()));
1178
0
    secret = childKey.key;
1179
0
    metadata.hd_seed_id = hd_chain.seed_id;
1180
0
    CKeyID master_id = masterKey.key.GetPubKey().GetID();
1181
0
    std::copy(master_id.begin(), master_id.begin() + 4, metadata.key_origin.fingerprint);
1182
0
    metadata.has_key_origin = true;
1183
    // update the chain model in the database
1184
0
    if (hd_chain.seed_id == m_hd_chain.seed_id && !batch.WriteHDChain(hd_chain))
1185
0
        throw std::runtime_error(std::string(__func__) + ": writing HD chain model failed");
1186
0
}
1187
1188
void LegacyDataSPKM::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
1189
0
{
1190
0
    LOCK(cs_KeyStore);
1191
0
    if (keypool.m_pre_split) {
1192
0
        set_pre_split_keypool.insert(nIndex);
1193
0
    } else if (keypool.fInternal) {
1194
0
        setInternalKeyPool.insert(nIndex);
1195
0
    } else {
1196
0
        setExternalKeyPool.insert(nIndex);
1197
0
    }
1198
0
    m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
1199
0
    m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
1200
1201
    // If no metadata exists yet, create a default with the pool key's
1202
    // creation time. Note that this may be overwritten by actually
1203
    // stored metadata for that key later, which is fine.
1204
0
    CKeyID keyid = keypool.vchPubKey.GetID();
1205
0
    if (mapKeyMetadata.count(keyid) == 0)
1206
0
        mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
1207
0
}
1208
1209
bool LegacyScriptPubKeyMan::CanGenerateKeys() const
1210
0
{
1211
    // A wallet can generate keys if it has an HD seed (IsHDEnabled) or it is a non-HD wallet (pre FEATURE_HD)
1212
0
    LOCK(cs_KeyStore);
1213
0
    return IsHDEnabled() || !m_storage.CanSupportFeature(FEATURE_HD);
1214
0
}
1215
1216
CPubKey LegacyScriptPubKeyMan::GenerateNewSeed()
1217
0
{
1218
0
    assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
1219
0
    CKey key = GenerateRandomKey();
1220
0
    return DeriveNewSeed(key);
1221
0
}
1222
1223
CPubKey LegacyScriptPubKeyMan::DeriveNewSeed(const CKey& key)
1224
0
{
1225
0
    int64_t nCreationTime = GetTime();
1226
0
    CKeyMetadata metadata(nCreationTime);
1227
1228
    // calculate the seed
1229
0
    CPubKey seed = key.GetPubKey();
1230
0
    assert(key.VerifyPubKey(seed));
1231
1232
    // set the hd keypath to "s" -> Seed, refers the seed to itself
1233
0
    metadata.hdKeypath     = "s";
1234
0
    metadata.has_key_origin = false;
1235
0
    metadata.hd_seed_id = seed.GetID();
1236
1237
0
    {
1238
0
        LOCK(cs_KeyStore);
1239
1240
        // mem store the metadata
1241
0
        mapKeyMetadata[seed.GetID()] = metadata;
1242
1243
        // write the key&metadata to the database
1244
0
        if (!AddKeyPubKey(key, seed))
1245
0
            throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1246
0
    }
1247
1248
0
    return seed;
1249
0
}
1250
1251
void LegacyScriptPubKeyMan::SetHDSeed(const CPubKey& seed)
1252
0
{
1253
0
    LOCK(cs_KeyStore);
1254
    // store the keyid (hash160) together with
1255
    // the child index counter in the database
1256
    // as a hdchain object
1257
0
    CHDChain newHdChain;
1258
0
    newHdChain.nVersion = m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1259
0
    newHdChain.seed_id = seed.GetID();
1260
0
    AddHDChain(newHdChain);
1261
0
    NotifyCanGetAddressesChanged();
1262
0
    WalletBatch batch(m_storage.GetDatabase());
1263
0
    m_storage.UnsetBlankWalletFlag(batch);
1264
0
}
1265
1266
/**
1267
 * Mark old keypool keys as used,
1268
 * and generate all new keys
1269
 */
1270
bool LegacyScriptPubKeyMan::NewKeyPool()
1271
0
{
1272
0
    if (m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
1273
0
        return false;
1274
0
    }
1275
0
    {
1276
0
        LOCK(cs_KeyStore);
1277
0
        WalletBatch batch(m_storage.GetDatabase());
1278
1279
0
        for (const int64_t nIndex : setInternalKeyPool) {
1280
0
            batch.ErasePool(nIndex);
1281
0
        }
1282
0
        setInternalKeyPool.clear();
1283
1284
0
        for (const int64_t nIndex : setExternalKeyPool) {
1285
0
            batch.ErasePool(nIndex);
1286
0
        }
1287
0
        setExternalKeyPool.clear();
1288
1289
0
        for (const int64_t nIndex : set_pre_split_keypool) {
1290
0
            batch.ErasePool(nIndex);
1291
0
        }
1292
0
        set_pre_split_keypool.clear();
1293
1294
0
        m_pool_key_to_index.clear();
1295
1296
0
        if (!TopUp()) {
1297
0
            return false;
1298
0
        }
1299
0
        WalletLogPrintf("LegacyScriptPubKeyMan::NewKeyPool rewrote keypool\n");
1300
0
    }
1301
0
    return true;
1302
0
}
1303
1304
bool LegacyScriptPubKeyMan::TopUp(unsigned int kpSize)
1305
0
{
1306
0
    if (!CanGenerateKeys()) {
1307
0
        return false;
1308
0
    }
1309
1310
0
    WalletBatch batch(m_storage.GetDatabase());
1311
0
    if (!batch.TxnBegin()) return false;
1312
0
    if (!TopUpChain(batch, m_hd_chain, kpSize)) {
1313
0
        return false;
1314
0
    }
1315
0
    for (auto& [chain_id, chain] : m_inactive_hd_chains) {
1316
0
        if (!TopUpChain(batch, chain, kpSize)) {
1317
0
            return false;
1318
0
        }
1319
0
    }
1320
0
    if (!batch.TxnCommit()) throw std::runtime_error(strprintf("Error during keypool top up. Cannot commit changes for wallet %s", m_storage.GetDisplayName()));
1321
0
    NotifyCanGetAddressesChanged();
1322
    // Note: Unlike with DescriptorSPKM, LegacySPKM does not need to call
1323
    // m_storage.TopUpCallback() as we do not know what new scripts the LegacySPKM is
1324
    // watching for. CWallet's scriptPubKey cache is not used for LegacySPKMs.
1325
0
    return true;
1326
0
}
1327
1328
bool LegacyScriptPubKeyMan::TopUpChain(WalletBatch& batch, CHDChain& chain, unsigned int kpSize)
1329
0
{
1330
0
    LOCK(cs_KeyStore);
1331
1332
0
    if (m_storage.IsLocked()) return false;
1333
1334
    // Top up key pool
1335
0
    unsigned int nTargetSize;
1336
0
    if (kpSize > 0) {
1337
0
        nTargetSize = kpSize;
1338
0
    } else {
1339
0
        nTargetSize = m_keypool_size;
1340
0
    }
1341
0
    int64_t target = std::max((int64_t) nTargetSize, int64_t{1});
1342
1343
    // count amount of available keys (internal, external)
1344
    // make sure the keypool of external and internal keys fits the user selected target (-keypool)
1345
0
    int64_t missingExternal;
1346
0
    int64_t missingInternal;
1347
0
    if (chain == m_hd_chain) {
1348
0
        missingExternal = std::max(target - (int64_t)setExternalKeyPool.size(), int64_t{0});
1349
0
        missingInternal = std::max(target - (int64_t)setInternalKeyPool.size(), int64_t{0});
1350
0
    } else {
1351
0
        missingExternal = std::max(target - (chain.nExternalChainCounter - chain.m_next_external_index), int64_t{0});
1352
0
        missingInternal = std::max(target - (chain.nInternalChainCounter - chain.m_next_internal_index), int64_t{0});
1353
0
    }
1354
1355
0
    if (!IsHDEnabled() || !m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
1356
        // don't create extra internal keys
1357
0
        missingInternal = 0;
1358
0
    }
1359
0
    bool internal = false;
1360
0
    for (int64_t i = missingInternal + missingExternal; i--;) {
1361
0
        if (i < missingInternal) {
1362
0
            internal = true;
1363
0
        }
1364
1365
0
        CPubKey pubkey(GenerateNewKey(batch, chain, internal));
1366
0
        if (chain == m_hd_chain) {
1367
0
            AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1368
0
        }
1369
0
    }
1370
0
    if (missingInternal + missingExternal > 0) {
1371
0
        if (chain == m_hd_chain) {
1372
0
            WalletLogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size() + set_pre_split_keypool.size(), setInternalKeyPool.size());
1373
0
        } else {
1374
0
            WalletLogPrintf("inactive seed with id %s added %d external keys, %d internal keys\n", HexStr(chain.seed_id), missingExternal, missingInternal);
1375
0
        }
1376
0
    }
1377
0
    return true;
1378
0
}
1379
1380
void LegacyScriptPubKeyMan::AddKeypoolPubkeyWithDB(const CPubKey& pubkey, const bool internal, WalletBatch& batch)
1381
0
{
1382
0
    LOCK(cs_KeyStore);
1383
0
    assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
1384
0
    int64_t index = ++m_max_keypool_index;
1385
0
    if (!batch.WritePool(index, CKeyPool(pubkey, internal))) {
1386
0
        throw std::runtime_error(std::string(__func__) + ": writing imported pubkey failed");
1387
0
    }
1388
0
    if (internal) {
1389
0
        setInternalKeyPool.insert(index);
1390
0
    } else {
1391
0
        setExternalKeyPool.insert(index);
1392
0
    }
1393
0
    m_pool_key_to_index[pubkey.GetID()] = index;
1394
0
}
1395
1396
void LegacyScriptPubKeyMan::KeepDestination(int64_t nIndex, const OutputType& type)
1397
0
{
1398
0
    assert(type != OutputType::BECH32M);
1399
    // Remove from key pool
1400
0
    WalletBatch batch(m_storage.GetDatabase());
1401
0
    batch.ErasePool(nIndex);
1402
0
    CPubKey pubkey;
1403
0
    bool have_pk = GetPubKey(m_index_to_reserved_key.at(nIndex), pubkey);
1404
0
    assert(have_pk);
1405
0
    LearnRelatedScripts(pubkey, type);
1406
0
    m_index_to_reserved_key.erase(nIndex);
1407
0
    WalletLogPrintf("keypool keep %d\n", nIndex);
1408
0
}
1409
1410
void LegacyScriptPubKeyMan::ReturnDestination(int64_t nIndex, bool fInternal, const CTxDestination&)
1411
0
{
1412
    // Return to key pool
1413
0
    {
1414
0
        LOCK(cs_KeyStore);
1415
0
        if (fInternal) {
1416
0
            setInternalKeyPool.insert(nIndex);
1417
0
        } else if (!set_pre_split_keypool.empty()) {
1418
0
            set_pre_split_keypool.insert(nIndex);
1419
0
        } else {
1420
0
            setExternalKeyPool.insert(nIndex);
1421
0
        }
1422
0
        CKeyID& pubkey_id = m_index_to_reserved_key.at(nIndex);
1423
0
        m_pool_key_to_index[pubkey_id] = nIndex;
1424
0
        m_index_to_reserved_key.erase(nIndex);
1425
0
        NotifyCanGetAddressesChanged();
1426
0
    }
1427
0
    WalletLogPrintf("keypool return %d\n", nIndex);
1428
0
}
1429
1430
bool LegacyScriptPubKeyMan::GetKeyFromPool(CPubKey& result, const OutputType type)
1431
0
{
1432
0
    assert(type != OutputType::BECH32M);
1433
0
    if (!CanGetAddresses(/*internal=*/ false)) {
1434
0
        return false;
1435
0
    }
1436
1437
0
    CKeyPool keypool;
1438
0
    {
1439
0
        LOCK(cs_KeyStore);
1440
0
        int64_t nIndex;
1441
0
        if (!ReserveKeyFromKeyPool(nIndex, keypool, /*fRequestedInternal=*/ false) && !m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
1442
0
            if (m_storage.IsLocked()) return false;
1443
0
            WalletBatch batch(m_storage.GetDatabase());
1444
0
            result = GenerateNewKey(batch, m_hd_chain, /*internal=*/ false);
1445
0
            return true;
1446
0
        }
1447
0
        KeepDestination(nIndex, type);
1448
0
        result = keypool.vchPubKey;
1449
0
    }
1450
0
    return true;
1451
0
}
1452
1453
bool LegacyScriptPubKeyMan::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
1454
0
{
1455
0
    nIndex = -1;
1456
0
    keypool.vchPubKey = CPubKey();
1457
0
    {
1458
0
        LOCK(cs_KeyStore);
1459
1460
0
        bool fReturningInternal = fRequestedInternal;
1461
0
        fReturningInternal &= (IsHDEnabled() && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) || m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
1462
0
        bool use_split_keypool = set_pre_split_keypool.empty();
1463
0
        std::set<int64_t>& setKeyPool = use_split_keypool ? (fReturningInternal ? setInternalKeyPool : setExternalKeyPool) : set_pre_split_keypool;
1464
1465
        // Get the oldest key
1466
0
        if (setKeyPool.empty()) {
1467
0
            return false;
1468
0
        }
1469
1470
0
        WalletBatch batch(m_storage.GetDatabase());
1471
1472
0
        auto it = setKeyPool.begin();
1473
0
        nIndex = *it;
1474
0
        setKeyPool.erase(it);
1475
0
        if (!batch.ReadPool(nIndex, keypool)) {
1476
0
            throw std::runtime_error(std::string(__func__) + ": read failed");
1477
0
        }
1478
0
        CPubKey pk;
1479
0
        if (!GetPubKey(keypool.vchPubKey.GetID(), pk)) {
1480
0
            throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
1481
0
        }
1482
        // If the key was pre-split keypool, we don't care about what type it is
1483
0
        if (use_split_keypool && keypool.fInternal != fReturningInternal) {
1484
0
            throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
1485
0
        }
1486
0
        if (!keypool.vchPubKey.IsValid()) {
1487
0
            throw std::runtime_error(std::string(__func__) + ": keypool entry invalid");
1488
0
        }
1489
1490
0
        assert(m_index_to_reserved_key.count(nIndex) == 0);
1491
0
        m_index_to_reserved_key[nIndex] = keypool.vchPubKey.GetID();
1492
0
        m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1493
0
        WalletLogPrintf("keypool reserve %d\n", nIndex);
1494
0
    }
1495
0
    NotifyCanGetAddressesChanged();
1496
0
    return true;
1497
0
}
1498
1499
void LegacyScriptPubKeyMan::LearnRelatedScripts(const CPubKey& key, OutputType type)
1500
0
{
1501
0
    assert(type != OutputType::BECH32M);
1502
0
    if (key.IsCompressed() && (type == OutputType::P2SH_SEGWIT || type == OutputType::BECH32)) {
1503
0
        CTxDestination witdest = WitnessV0KeyHash(key.GetID());
1504
0
        CScript witprog = GetScriptForDestination(witdest);
1505
        // Make sure the resulting program is solvable.
1506
0
        const auto desc = InferDescriptor(witprog, *this);
1507
0
        assert(desc && desc->IsSolvable());
1508
0
        AddCScript(witprog);
1509
0
    }
1510
0
}
1511
1512
void LegacyScriptPubKeyMan::LearnAllRelatedScripts(const CPubKey& key)
1513
0
{
1514
    // OutputType::P2SH_SEGWIT always adds all necessary scripts for all types.
1515
0
    LearnRelatedScripts(key, OutputType::P2SH_SEGWIT);
1516
0
}
1517
1518
std::vector<CKeyPool> LegacyScriptPubKeyMan::MarkReserveKeysAsUsed(int64_t keypool_id)
1519
0
{
1520
0
    AssertLockHeld(cs_KeyStore);
1521
0
    bool internal = setInternalKeyPool.count(keypool_id);
1522
0
    if (!internal) assert(setExternalKeyPool.count(keypool_id) || set_pre_split_keypool.count(keypool_id));
1523
0
    std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : (set_pre_split_keypool.empty() ? &setExternalKeyPool : &set_pre_split_keypool);
1524
0
    auto it = setKeyPool->begin();
1525
1526
0
    std::vector<CKeyPool> result;
1527
0
    WalletBatch batch(m_storage.GetDatabase());
1528
0
    while (it != std::end(*setKeyPool)) {
1529
0
        const int64_t& index = *(it);
1530
0
        if (index > keypool_id) break; // set*KeyPool is ordered
1531
1532
0
        CKeyPool keypool;
1533
0
        if (batch.ReadPool(index, keypool)) { //TODO: This should be unnecessary
1534
0
            m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1535
0
        }
1536
0
        LearnAllRelatedScripts(keypool.vchPubKey);
1537
0
        batch.ErasePool(index);
1538
0
        WalletLogPrintf("keypool index %d removed\n", index);
1539
0
        it = setKeyPool->erase(it);
1540
0
        result.push_back(std::move(keypool));
1541
0
    }
1542
1543
0
    return result;
1544
0
}
1545
1546
std::vector<CKeyID> GetAffectedKeys(const CScript& spk, const SigningProvider& provider)
1547
0
{
1548
0
    std::vector<CScript> dummy;
1549
0
    FlatSigningProvider out;
1550
0
    InferDescriptor(spk, provider)->Expand(0, DUMMY_SIGNING_PROVIDER, dummy, out);
1551
0
    std::vector<CKeyID> ret;
1552
0
    ret.reserve(out.pubkeys.size());
1553
0
    for (const auto& entry : out.pubkeys) {
1554
0
        ret.push_back(entry.first);
1555
0
    }
1556
0
    return ret;
1557
0
}
1558
1559
void LegacyScriptPubKeyMan::MarkPreSplitKeys()
1560
0
{
1561
0
    WalletBatch batch(m_storage.GetDatabase());
1562
0
    for (auto it = setExternalKeyPool.begin(); it != setExternalKeyPool.end();) {
1563
0
        int64_t index = *it;
1564
0
        CKeyPool keypool;
1565
0
        if (!batch.ReadPool(index, keypool)) {
1566
0
            throw std::runtime_error(std::string(__func__) + ": read keypool entry failed");
1567
0
        }
1568
0
        keypool.m_pre_split = true;
1569
0
        if (!batch.WritePool(index, keypool)) {
1570
0
            throw std::runtime_error(std::string(__func__) + ": writing modified keypool entry failed");
1571
0
        }
1572
0
        set_pre_split_keypool.insert(index);
1573
0
        it = setExternalKeyPool.erase(it);
1574
0
    }
1575
0
}
1576
1577
bool LegacyScriptPubKeyMan::AddCScript(const CScript& redeemScript)
1578
0
{
1579
0
    WalletBatch batch(m_storage.GetDatabase());
1580
0
    return AddCScriptWithDB(batch, redeemScript);
1581
0
}
1582
1583
bool LegacyScriptPubKeyMan::AddCScriptWithDB(WalletBatch& batch, const CScript& redeemScript)
1584
0
{
1585
0
    if (!FillableSigningProvider::AddCScript(redeemScript))
1586
0
        return false;
1587
0
    if (batch.WriteCScript(Hash160(redeemScript), redeemScript)) {
1588
0
        m_storage.UnsetBlankWalletFlag(batch);
1589
0
        return true;
1590
0
    }
1591
0
    return false;
1592
0
}
1593
1594
bool LegacyScriptPubKeyMan::AddKeyOriginWithDB(WalletBatch& batch, const CPubKey& pubkey, const KeyOriginInfo& info)
1595
0
{
1596
0
    LOCK(cs_KeyStore);
1597
0
    std::copy(info.fingerprint, info.fingerprint + 4, mapKeyMetadata[pubkey.GetID()].key_origin.fingerprint);
1598
0
    mapKeyMetadata[pubkey.GetID()].key_origin.path = info.path;
1599
0
    mapKeyMetadata[pubkey.GetID()].has_key_origin = true;
1600
0
    mapKeyMetadata[pubkey.GetID()].hdKeypath = WriteHDKeypath(info.path, /*apostrophe=*/true);
1601
0
    return batch.WriteKeyMetadata(mapKeyMetadata[pubkey.GetID()], pubkey, true);
1602
0
}
1603
1604
bool LegacyScriptPubKeyMan::ImportScripts(const std::set<CScript> scripts, int64_t timestamp)
1605
0
{
1606
0
    WalletBatch batch(m_storage.GetDatabase());
1607
0
    for (const auto& entry : scripts) {
1608
0
        CScriptID id(entry);
1609
0
        if (HaveCScript(id)) {
1610
0
            WalletLogPrintf("Already have script %s, skipping\n", HexStr(entry));
1611
0
            continue;
1612
0
        }
1613
0
        if (!AddCScriptWithDB(batch, entry)) {
1614
0
            return false;
1615
0
        }
1616
1617
0
        if (timestamp > 0) {
1618
0
            m_script_metadata[CScriptID(entry)].nCreateTime = timestamp;
1619
0
        }
1620
0
    }
1621
0
    if (timestamp > 0) {
1622
0
        UpdateTimeFirstKey(timestamp);
1623
0
    }
1624
1625
0
    return true;
1626
0
}
1627
1628
bool LegacyScriptPubKeyMan::ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp)
1629
0
{
1630
0
    WalletBatch batch(m_storage.GetDatabase());
1631
0
    for (const auto& entry : privkey_map) {
1632
0
        const CKey& key = entry.second;
1633
0
        CPubKey pubkey = key.GetPubKey();
1634
0
        const CKeyID& id = entry.first;
1635
0
        assert(key.VerifyPubKey(pubkey));
1636
        // Skip if we already have the key
1637
0
        if (HaveKey(id)) {
1638
0
            WalletLogPrintf("Already have key with pubkey %s, skipping\n", HexStr(pubkey));
1639
0
            continue;
1640
0
        }
1641
0
        mapKeyMetadata[id].nCreateTime = timestamp;
1642
        // If the private key is not present in the wallet, insert it.
1643
0
        if (!AddKeyPubKeyWithDB(batch, key, pubkey)) {
1644
0
            return false;
1645
0
        }
1646
0
        UpdateTimeFirstKey(timestamp);
1647
0
    }
1648
0
    return true;
1649
0
}
1650
1651
bool LegacyScriptPubKeyMan::ImportPubKeys(const std::vector<std::pair<CKeyID, bool>>& ordered_pubkeys, const std::map<CKeyID, CPubKey>& pubkey_map, const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& key_origins, const bool add_keypool, const int64_t timestamp)
1652
0
{
1653
0
    WalletBatch batch(m_storage.GetDatabase());
1654
0
    for (const auto& entry : key_origins) {
1655
0
        AddKeyOriginWithDB(batch, entry.second.first, entry.second.second);
1656
0
    }
1657
0
    for (const auto& [id, internal] : ordered_pubkeys) {
1658
0
        auto entry = pubkey_map.find(id);
1659
0
        if (entry == pubkey_map.end()) {
1660
0
            continue;
1661
0
        }
1662
0
        const CPubKey& pubkey = entry->second;
1663
0
        CPubKey temp;
1664
0
        if (GetPubKey(id, temp)) {
1665
            // Already have pubkey, skipping
1666
0
            WalletLogPrintf("Already have pubkey %s, skipping\n", HexStr(temp));
1667
0
            continue;
1668
0
        }
1669
0
        if (!AddWatchOnlyWithDB(batch, GetScriptForRawPubKey(pubkey), timestamp)) {
1670
0
            return false;
1671
0
        }
1672
0
        mapKeyMetadata[id].nCreateTime = timestamp;
1673
1674
        // Add to keypool only works with pubkeys
1675
0
        if (add_keypool) {
1676
0
            AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1677
0
            NotifyCanGetAddressesChanged();
1678
0
        }
1679
0
    }
1680
0
    return true;
1681
0
}
1682
1683
bool LegacyScriptPubKeyMan::ImportScriptPubKeys(const std::set<CScript>& script_pub_keys, const bool have_solving_data, const int64_t timestamp)
1684
0
{
1685
0
    WalletBatch batch(m_storage.GetDatabase());
1686
0
    for (const CScript& script : script_pub_keys) {
1687
0
        if (!have_solving_data || !IsMine(script)) { // Always call AddWatchOnly for non-solvable watch-only, so that watch timestamp gets updated
1688
0
            if (!AddWatchOnlyWithDB(batch, script, timestamp)) {
1689
0
                return false;
1690
0
            }
1691
0
        }
1692
0
    }
1693
0
    return true;
1694
0
}
1695
1696
std::set<CKeyID> LegacyScriptPubKeyMan::GetKeys() const
1697
0
{
1698
0
    LOCK(cs_KeyStore);
1699
0
    if (!m_storage.HasEncryptionKeys()) {
1700
0
        return FillableSigningProvider::GetKeys();
1701
0
    }
1702
0
    std::set<CKeyID> set_address;
1703
0
    for (const auto& mi : mapCryptedKeys) {
1704
0
        set_address.insert(mi.first);
1705
0
    }
1706
0
    return set_address;
1707
0
}
1708
1709
std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetCandidateScriptPubKeys() const
1710
0
{
1711
0
    LOCK(cs_KeyStore);
1712
0
    std::unordered_set<CScript, SaltedSipHasher> candidate_spks;
1713
1714
    // For every private key in the wallet, there should be a P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH
1715
0
    const auto& add_pubkey = [&candidate_spks](const CPubKey& pub) -> void {
1716
0
        candidate_spks.insert(GetScriptForRawPubKey(pub));
1717
0
        candidate_spks.insert(GetScriptForDestination(PKHash(pub)));
1718
1719
0
        CScript wpkh = GetScriptForDestination(WitnessV0KeyHash(pub));
1720
0
        candidate_spks.insert(wpkh);
1721
0
        candidate_spks.insert(GetScriptForDestination(ScriptHash(wpkh)));
1722
0
    };
1723
0
    for (const auto& [_, key] : mapKeys) {
1724
0
        add_pubkey(key.GetPubKey());
1725
0
    }
1726
0
    for (const auto& [_, ckeypair] : mapCryptedKeys) {
1727
0
        add_pubkey(ckeypair.first);
1728
0
    }
1729
1730
    // mapScripts contains all redeemScripts and witnessScripts. Therefore each script in it has
1731
    // itself, P2SH, P2WSH, and P2SH-P2WSH as a candidate.
1732
    // Invalid scripts such as P2SH-P2SH and P2WSH-P2SH, among others, will be added as candidates.
1733
    // Callers of this function will need to remove such scripts.
1734
0
    const auto& add_script = [&candidate_spks](const CScript& script) -> void {
1735
0
        candidate_spks.insert(script);
1736
0
        candidate_spks.insert(GetScriptForDestination(ScriptHash(script)));
1737
1738
0
        CScript wsh = GetScriptForDestination(WitnessV0ScriptHash(script));
1739
0
        candidate_spks.insert(wsh);
1740
0
        candidate_spks.insert(GetScriptForDestination(ScriptHash(wsh)));
1741
0
    };
1742
0
    for (const auto& [_, script] : mapScripts) {
1743
0
        add_script(script);
1744
0
    }
1745
1746
    // Although setWatchOnly should only contain output scripts, we will also include each script's
1747
    // P2SH, P2WSH, and P2SH-P2WSH as a precaution.
1748
0
    for (const auto& script : setWatchOnly) {
1749
0
        add_script(script);
1750
0
    }
1751
1752
0
    return candidate_spks;
1753
0
}
1754
1755
std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetScriptPubKeys() const
1756
0
{
1757
    // Run IsMine() on each candidate output script. Any script that is not ISMINE_NO is an output
1758
    // script to return.
1759
    // This both filters out things that are not watched by the wallet, and things that are invalid.
1760
0
    std::unordered_set<CScript, SaltedSipHasher> spks;
1761
0
    for (const CScript& script : GetCandidateScriptPubKeys()) {
1762
0
        if (IsMine(script) != ISMINE_NO) {
1763
0
            spks.insert(script);
1764
0
        }
1765
0
    }
1766
1767
0
    return spks;
1768
0
}
1769
1770
std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetNotMineScriptPubKeys() const
1771
0
{
1772
0
    LOCK(cs_KeyStore);
1773
0
    std::unordered_set<CScript, SaltedSipHasher> spks;
1774
0
    for (const CScript& script : setWatchOnly) {
1775
0
        if (IsMine(script) == ISMINE_NO) spks.insert(script);
1776
0
    }
1777
0
    return spks;
1778
0
}
1779
1780
std::optional<MigrationData> LegacyDataSPKM::MigrateToDescriptor()
1781
0
{
1782
0
    LOCK(cs_KeyStore);
1783
0
    if (m_storage.IsLocked()) {
1784
0
        return std::nullopt;
1785
0
    }
1786
1787
0
    MigrationData out;
1788
1789
0
    std::unordered_set<CScript, SaltedSipHasher> spks{GetScriptPubKeys()};
1790
1791
    // Get all key ids
1792
0
    std::set<CKeyID> keyids;
1793
0
    for (const auto& key_pair : mapKeys) {
1794
0
        keyids.insert(key_pair.first);
1795
0
    }
1796
0
    for (const auto& key_pair : mapCryptedKeys) {
1797
0
        keyids.insert(key_pair.first);
1798
0
    }
1799
1800
    // Get key metadata and figure out which keys don't have a seed
1801
    // Note that we do not ignore the seeds themselves because they are considered IsMine!
1802
0
    for (auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
1803
0
        const CKeyID& keyid = *keyid_it;
1804
0
        const auto& it = mapKeyMetadata.find(keyid);
1805
0
        if (it != mapKeyMetadata.end()) {
1806
0
            const CKeyMetadata& meta = it->second;
1807
0
            if (meta.hdKeypath == "s" || meta.hdKeypath == "m") {
1808
0
                keyid_it++;
1809
0
                continue;
1810
0
            }
1811
0
            if (!meta.hd_seed_id.IsNull() && (m_hd_chain.seed_id == meta.hd_seed_id || m_inactive_hd_chains.count(meta.hd_seed_id) > 0)) {
1812
0
                keyid_it = keyids.erase(keyid_it);
1813
0
                continue;
1814
0
            }
1815
0
        }
1816
0
        keyid_it++;
1817
0
    }
1818
1819
0
    WalletBatch batch(m_storage.GetDatabase());
1820
0
    if (!batch.TxnBegin()) {
1821
0
        LogPrintf("Error generating descriptors for migration, cannot initialize db transaction\n");
1822
0
        return std::nullopt;
1823
0
    }
1824
1825
    // keyids is now all non-HD keys. Each key will have its own combo descriptor
1826
0
    for (const CKeyID& keyid : keyids) {
1827
0
        CKey key;
1828
0
        if (!GetKey(keyid, key)) {
1829
0
            assert(false);
1830
0
        }
1831
1832
        // Get birthdate from key meta
1833
0
        uint64_t creation_time = 0;
1834
0
        const auto& it = mapKeyMetadata.find(keyid);
1835
0
        if (it != mapKeyMetadata.end()) {
1836
0
            creation_time = it->second.nCreateTime;
1837
0
        }
1838
1839
        // Get the key origin
1840
        // Maybe this doesn't matter because floating keys here shouldn't have origins
1841
0
        KeyOriginInfo info;
1842
0
        bool has_info = GetKeyOrigin(keyid, info);
1843
0
        std::string origin_str = has_info ? "[" + HexStr(info.fingerprint) + FormatHDKeypath(info.path) + "]" : "";
1844
1845
        // Construct the combo descriptor
1846
0
        std::string desc_str = "combo(" + origin_str + HexStr(key.GetPubKey()) + ")";
1847
0
        FlatSigningProvider keys;
1848
0
        std::string error;
1849
0
        std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, error, false);
1850
0
        CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
1851
0
        WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
1852
1853
        // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
1854
0
        auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
1855
0
        WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, key, key.GetPubKey()));
1856
0
        desc_spk_man->TopUpWithDB(batch);
1857
0
        auto desc_spks = desc_spk_man->GetScriptPubKeys();
1858
1859
        // Remove the scriptPubKeys from our current set
1860
0
        for (const CScript& spk : desc_spks) {
1861
0
            size_t erased = spks.erase(spk);
1862
0
            assert(erased == 1);
1863
0
            assert(IsMine(spk) == ISMINE_SPENDABLE);
1864
0
        }
1865
1866
0
        out.desc_spkms.push_back(std::move(desc_spk_man));
1867
0
    }
1868
1869
    // Handle HD keys by using the CHDChains
1870
0
    std::vector<CHDChain> chains;
1871
0
    chains.push_back(m_hd_chain);
1872
0
    for (const auto& chain_pair : m_inactive_hd_chains) {
1873
0
        chains.push_back(chain_pair.second);
1874
0
    }
1875
0
    for (const CHDChain& chain : chains) {
1876
0
        for (int i = 0; i < 2; ++i) {
1877
            // Skip if doing internal chain and split chain is not supported
1878
0
            if (chain.seed_id.IsNull() || (i == 1 && !m_storage.CanSupportFeature(FEATURE_HD_SPLIT))) {
1879
0
                continue;
1880
0
            }
1881
            // Get the master xprv
1882
0
            CKey seed_key;
1883
0
            if (!GetKey(chain.seed_id, seed_key)) {
1884
0
                assert(false);
1885
0
            }
1886
0
            CExtKey master_key;
1887
0
            master_key.SetSeed(seed_key);
1888
1889
            // Make the combo descriptor
1890
0
            std::string xpub = EncodeExtPubKey(master_key.Neuter());
1891
0
            std::string desc_str = "combo(" + xpub + "/0h/" + ToString(i) + "h/*h)";
1892
0
            FlatSigningProvider keys;
1893
0
            std::string error;
1894
0
            std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, error, false);
1895
0
            CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
1896
0
            uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
1897
0
            WalletDescriptor w_desc(std::move(descs.at(0)), 0, 0, chain_counter, 0);
1898
1899
            // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
1900
0
            auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
1901
0
            WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey()));
1902
0
            desc_spk_man->TopUpWithDB(batch);
1903
0
            auto desc_spks = desc_spk_man->GetScriptPubKeys();
1904
1905
            // Remove the scriptPubKeys from our current set
1906
0
            for (const CScript& spk : desc_spks) {
1907
0
                size_t erased = spks.erase(spk);
1908
0
                assert(erased == 1);
1909
0
                assert(IsMine(spk) == ISMINE_SPENDABLE);
1910
0
            }
1911
1912
0
            out.desc_spkms.push_back(std::move(desc_spk_man));
1913
0
        }
1914
0
    }
1915
    // Add the current master seed to the migration data
1916
0
    if (!m_hd_chain.seed_id.IsNull()) {
1917
0
        CKey seed_key;
1918
0
        if (!GetKey(m_hd_chain.seed_id, seed_key)) {
1919
0
            assert(false);
1920
0
        }
1921
0
        out.master_key.SetSeed(seed_key);
1922
0
    }
1923
1924
    // Handle the rest of the scriptPubKeys which must be imports and may not have all info
1925
0
    for (auto it = spks.begin(); it != spks.end();) {
1926
0
        const CScript& spk = *it;
1927
1928
        // Get birthdate from script meta
1929
0
        uint64_t creation_time = 0;
1930
0
        const auto& mit = m_script_metadata.find(CScriptID(spk));
1931
0
        if (mit != m_script_metadata.end()) {
1932
0
            creation_time = mit->second.nCreateTime;
1933
0
        }
1934
1935
        // InferDescriptor as that will get us all the solving info if it is there
1936
0
        std::unique_ptr<Descriptor> desc = InferDescriptor(spk, *GetSolvingProvider(spk));
1937
1938
        // Past bugs in InferDescriptor have caused it to create descriptors which cannot be re-parsed.
1939
        // Re-parse the descriptors to detect that, and skip any that do not parse.
1940
0
        {
1941
0
            std::string desc_str = desc->ToString();
1942
0
            FlatSigningProvider parsed_keys;
1943
0
            std::string parse_error;
1944
0
            std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error);
1945
0
            if (parsed_descs.empty()) {
1946
                // Remove this scriptPubKey from the set
1947
0
                it = spks.erase(it);
1948
0
                continue;
1949
0
            }
1950
0
        }
1951
1952
        // Get the private keys for this descriptor
1953
0
        std::vector<CScript> scripts;
1954
0
        FlatSigningProvider keys;
1955
0
        if (!desc->Expand(0, DUMMY_SIGNING_PROVIDER, scripts, keys)) {
1956
0
            assert(false);
1957
0
        }
1958
0
        std::set<CKeyID> privkeyids;
1959
0
        for (const auto& key_orig_pair : keys.origins) {
1960
0
            privkeyids.insert(key_orig_pair.first);
1961
0
        }
1962
1963
0
        std::vector<CScript> desc_spks;
1964
1965
        // Make the descriptor string with private keys
1966
0
        std::string desc_str;
1967
0
        bool watchonly = !desc->ToPrivateString(*this, desc_str);
1968
0
        if (watchonly && !m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
1969
0
            out.watch_descs.emplace_back(desc->ToString(), creation_time);
1970
1971
            // Get the scriptPubKeys without writing this to the wallet
1972
0
            FlatSigningProvider provider;
1973
0
            desc->Expand(0, provider, desc_spks, provider);
1974
0
        } else {
1975
            // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
1976
0
            WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
1977
0
            auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
1978
0
            for (const auto& keyid : privkeyids) {
1979
0
                CKey key;
1980
0
                if (!GetKey(keyid, key)) {
1981
0
                    continue;
1982
0
                }
1983
0
                WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, key, key.GetPubKey()));
1984
0
            }
1985
0
            desc_spk_man->TopUpWithDB(batch);
1986
0
            auto desc_spks_set = desc_spk_man->GetScriptPubKeys();
1987
0
            desc_spks.insert(desc_spks.end(), desc_spks_set.begin(), desc_spks_set.end());
1988
1989
0
            out.desc_spkms.push_back(std::move(desc_spk_man));
1990
0
        }
1991
1992
        // Remove the scriptPubKeys from our current set
1993
0
        for (const CScript& desc_spk : desc_spks) {
1994
0
            auto del_it = spks.find(desc_spk);
1995
0
            assert(del_it != spks.end());
1996
0
            assert(IsMine(desc_spk) != ISMINE_NO);
1997
0
            it = spks.erase(del_it);
1998
0
        }
1999
0
    }
2000
2001
    // Make sure that we have accounted for all scriptPubKeys
2002
0
    if (!Assume(spks.empty())) {
2003
0
        LogPrintf("%s\n", STR_INTERNAL_BUG("Error: Some output scripts were not migrated.\n"));
2004
0
        return std::nullopt;
2005
0
    }
2006
2007
    // Legacy wallets can also contain scripts whose P2SH, P2WSH, or P2SH-P2WSH it is not watching for
2008
    // but can provide script data to a PSBT spending them. These "solvable" output scripts will need to
2009
    // be put into the separate "solvables" wallet.
2010
    // These can be detected by going through the entire candidate output scripts, finding the ISMINE_NO scripts,
2011
    // and checking CanProvide() which will dummy sign.
2012
0
    for (const CScript& script : GetCandidateScriptPubKeys()) {
2013
        // Since we only care about P2SH, P2WSH, and P2SH-P2WSH, filter out any scripts that are not those
2014
0
        if (!script.IsPayToScriptHash() && !script.IsPayToWitnessScriptHash()) {
2015
0
            continue;
2016
0
        }
2017
0
        if (IsMine(script) != ISMINE_NO) {
2018
0
            continue;
2019
0
        }
2020
0
        SignatureData dummy_sigdata;
2021
0
        if (!CanProvide(script, dummy_sigdata)) {
2022
0
            continue;
2023
0
        }
2024
2025
        // Get birthdate from script meta
2026
0
        uint64_t creation_time = 0;
2027
0
        const auto& it = m_script_metadata.find(CScriptID(script));
2028
0
        if (it != m_script_metadata.end()) {
2029
0
            creation_time = it->second.nCreateTime;
2030
0
        }
2031
2032
        // InferDescriptor as that will get us all the solving info if it is there
2033
0
        std::unique_ptr<Descriptor> desc = InferDescriptor(script, *GetSolvingProvider(script));
2034
0
        if (!desc->IsSolvable()) {
2035
            // The wallet was able to provide some information, but not enough to make a descriptor that actually
2036
            // contains anything useful. This is probably because the script itself is actually unsignable (e.g. P2WSH-P2WSH).
2037
0
            continue;
2038
0
        }
2039
2040
        // Past bugs in InferDescriptor have caused it to create descriptors which cannot be re-parsed
2041
        // Re-parse the descriptors to detect that, and skip any that do not parse.
2042
0
        {
2043
0
            std::string desc_str = desc->ToString();
2044
0
            FlatSigningProvider parsed_keys;
2045
0
            std::string parse_error;
2046
0
            std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error, false);
2047
0
            if (parsed_descs.empty()) {
2048
0
                continue;
2049
0
            }
2050
0
        }
2051
2052
0
        out.solvable_descs.emplace_back(desc->ToString(), creation_time);
2053
0
    }
2054
2055
    // Finalize transaction
2056
0
    if (!batch.TxnCommit()) {
2057
0
        LogPrintf("Error generating descriptors for migration, cannot commit db transaction\n");
2058
0
        return std::nullopt;
2059
0
    }
2060
2061
0
    return out;
2062
0
}
2063
2064
bool LegacyDataSPKM::DeleteRecords()
2065
0
{
2066
0
    return RunWithinTxn(m_storage.GetDatabase(), /*process_desc=*/"delete legacy records", [&](WalletBatch& batch){
2067
0
        return DeleteRecordsWithDB(batch);
2068
0
    });
2069
0
}
2070
2071
bool LegacyDataSPKM::DeleteRecordsWithDB(WalletBatch& batch)
2072
0
{
2073
0
    LOCK(cs_KeyStore);
2074
0
    return batch.EraseRecords(DBKeys::LEGACY_TYPES);
2075
0
}
2076
2077
util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetNewDestination(const OutputType type)
2078
0
{
2079
    // Returns true if this descriptor supports getting new addresses. Conditions where we may be unable to fetch them (e.g. locked) are caught later
2080
0
    if (!CanGetAddresses()) {
2081
0
        return util::Error{_("No addresses available")};
2082
0
    }
2083
0
    {
2084
0
        LOCK(cs_desc_man);
2085
0
        assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
2086
0
        std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
2087
0
        assert(desc_addr_type);
2088
0
        if (type != *desc_addr_type) {
2089
0
            throw std::runtime_error(std::string(__func__) + ": Types are inconsistent. Stored type does not match type of newly generated address");
2090
0
        }
2091
2092
0
        TopUp();
2093
2094
        // Get the scriptPubKey from the descriptor
2095
0
        FlatSigningProvider out_keys;
2096
0
        std::vector<CScript> scripts_temp;
2097
0
        if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
2098
            // We can't generate anymore keys
2099
0
            return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
2100
0
        }
2101
0
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2102
            // We can't generate anymore keys
2103
0
            return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
2104
0
        }
2105
2106
0
        CTxDestination dest;
2107
0
        if (!ExtractDestination(scripts_temp[0], dest)) {
2108
0
            return util::Error{_("Error: Cannot extract destination from the generated scriptpubkey")}; // shouldn't happen
2109
0
        }
2110
0
        m_wallet_descriptor.next_index++;
2111
0
        WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
2112
0
        return dest;
2113
0
    }
2114
0
}
2115
2116
isminetype DescriptorScriptPubKeyMan::IsMine(const CScript& script) const
2117
0
{
2118
0
    LOCK(cs_desc_man);
2119
0
    if (m_map_script_pub_keys.count(script) > 0) {
2120
0
        return ISMINE_SPENDABLE;
2121
0
    }
2122
0
    return ISMINE_NO;
2123
0
}
2124
2125
bool DescriptorScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key)
2126
0
{
2127
0
    LOCK(cs_desc_man);
2128
0
    if (!m_map_keys.empty()) {
2129
0
        return false;
2130
0
    }
2131
2132
0
    bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
2133
0
    bool keyFail = false;
2134
0
    for (const auto& mi : m_map_crypted_keys) {
2135
0
        const CPubKey &pubkey = mi.second.first;
2136
0
        const std::vector<unsigned char> &crypted_secret = mi.second.second;
2137
0
        CKey key;
2138
0
        if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
2139
0
            keyFail = true;
2140
0
            break;
2141
0
        }
2142
0
        keyPass = true;
2143
0
        if (m_decryption_thoroughly_checked)
2144
0
            break;
2145
0
    }
2146
0
    if (keyPass && keyFail) {
2147
0
        LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
2148
0
        throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
2149
0
    }
2150
0
    if (keyFail || !keyPass) {
2151
0
        return false;
2152
0
    }
2153
0
    m_decryption_thoroughly_checked = true;
2154
0
    return true;
2155
0
}
2156
2157
bool DescriptorScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
2158
0
{
2159
0
    LOCK(cs_desc_man);
2160
0
    if (!m_map_crypted_keys.empty()) {
2161
0
        return false;
2162
0
    }
2163
2164
0
    for (const KeyMap::value_type& key_in : m_map_keys)
2165
0
    {
2166
0
        const CKey &key = key_in.second;
2167
0
        CPubKey pubkey = key.GetPubKey();
2168
0
        CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
2169
0
        std::vector<unsigned char> crypted_secret;
2170
0
        if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
2171
0
            return false;
2172
0
        }
2173
0
        m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
2174
0
        batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
2175
0
    }
2176
0
    m_map_keys.clear();
2177
0
    return true;
2178
0
}
2179
2180
util::Result<CTxDestination> DescriptorScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, int64_t& index, CKeyPool& keypool)
2181
0
{
2182
0
    LOCK(cs_desc_man);
2183
0
    auto op_dest = GetNewDestination(type);
2184
0
    index = m_wallet_descriptor.next_index - 1;
2185
0
    return op_dest;
2186
0
}
2187
2188
void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
2189
0
{
2190
0
    LOCK(cs_desc_man);
2191
    // Only return when the index was the most recent
2192
0
    if (m_wallet_descriptor.next_index - 1 == index) {
2193
0
        m_wallet_descriptor.next_index--;
2194
0
    }
2195
0
    WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
2196
0
    NotifyCanGetAddressesChanged();
2197
0
}
2198
2199
std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
2200
0
{
2201
0
    AssertLockHeld(cs_desc_man);
2202
0
    if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
2203
0
        KeyMap keys;
2204
0
        for (const auto& key_pair : m_map_crypted_keys) {
2205
0
            const CPubKey& pubkey = key_pair.second.first;
2206
0
            const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
2207
0
            CKey key;
2208
0
            m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
2209
0
                return DecryptKey(encryption_key, crypted_secret, pubkey, key);
2210
0
            });
2211
0
            keys[pubkey.GetID()] = key;
2212
0
        }
2213
0
        return keys;
2214
0
    }
2215
0
    return m_map_keys;
2216
0
}
2217
2218
bool DescriptorScriptPubKeyMan::HasPrivKey(const CKeyID& keyid) const
2219
0
{
2220
0
    AssertLockHeld(cs_desc_man);
2221
0
    return m_map_keys.contains(keyid) || m_map_crypted_keys.contains(keyid);
2222
0
}
2223
2224
std::optional<CKey> DescriptorScriptPubKeyMan::GetKey(const CKeyID& keyid) const
2225
0
{
2226
0
    AssertLockHeld(cs_desc_man);
2227
0
    if (m_storage.HasEncryptionKeys() && !m_storage.IsLocked()) {
2228
0
        const auto& it = m_map_crypted_keys.find(keyid);
2229
0
        if (it == m_map_crypted_keys.end()) {
2230
0
            return std::nullopt;
2231
0
        }
2232
0
        const std::vector<unsigned char>& crypted_secret = it->second.second;
2233
0
        CKey key;
2234
0
        if (!Assume(m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
2235
0
            return DecryptKey(encryption_key, crypted_secret, it->second.first, key);
2236
0
        }))) {
2237
0
            return std::nullopt;
2238
0
        }
2239
0
        return key;
2240
0
    }
2241
0
    const auto& it = m_map_keys.find(keyid);
2242
0
    if (it == m_map_keys.end()) {
2243
0
        return std::nullopt;
2244
0
    }
2245
0
    return it->second;
2246
0
}
2247
2248
bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
2249
0
{
2250
0
    WalletBatch batch(m_storage.GetDatabase());
2251
0
    if (!batch.TxnBegin()) return false;
2252
0
    bool res = TopUpWithDB(batch, size);
2253
0
    if (!batch.TxnCommit()) throw std::runtime_error(strprintf("Error during descriptors keypool top up. Cannot commit changes for wallet %s", m_storage.GetDisplayName()));
2254
0
    return res;
2255
0
}
2256
2257
bool DescriptorScriptPubKeyMan::TopUpWithDB(WalletBatch& batch, unsigned int size)
2258
0
{
2259
0
    LOCK(cs_desc_man);
2260
0
    std::set<CScript> new_spks;
2261
0
    unsigned int target_size;
2262
0
    if (size > 0) {
2263
0
        target_size = size;
2264
0
    } else {
2265
0
        target_size = m_keypool_size;
2266
0
    }
2267
2268
    // Calculate the new range_end
2269
0
    int32_t new_range_end = std::max(m_wallet_descriptor.next_index + (int32_t)target_size, m_wallet_descriptor.range_end);
2270
2271
    // If the descriptor is not ranged, we actually just want to fill the first cache item
2272
0
    if (!m_wallet_descriptor.descriptor->IsRange()) {
2273
0
        new_range_end = 1;
2274
0
        m_wallet_descriptor.range_end = 1;
2275
0
        m_wallet_descriptor.range_start = 0;
2276
0
    }
2277
2278
0
    FlatSigningProvider provider;
2279
0
    provider.keys = GetKeys();
2280
2281
0
    uint256 id = GetID();
2282
0
    for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
2283
0
        FlatSigningProvider out_keys;
2284
0
        std::vector<CScript> scripts_temp;
2285
0
        DescriptorCache temp_cache;
2286
        // Maybe we have a cached xpub and we can expand from the cache first
2287
0
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2288
0
            if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
2289
0
        }
2290
        // Add all of the scriptPubKeys to the scriptPubKey set
2291
0
        new_spks.insert(scripts_temp.begin(), scripts_temp.end());
2292
0
        for (const CScript& script : scripts_temp) {
2293
0
            m_map_script_pub_keys[script] = i;
2294
0
        }
2295
0
        for (const auto& pk_pair : out_keys.pubkeys) {
2296
0
            const CPubKey& pubkey = pk_pair.second;
2297
0
            if (m_map_pubkeys.count(pubkey) != 0) {
2298
                // We don't need to give an error here.
2299
                // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and it's private key
2300
0
                continue;
2301
0
            }
2302
0
            m_map_pubkeys[pubkey] = i;
2303
0
        }
2304
        // Merge and write the cache
2305
0
        DescriptorCache new_items = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
2306
0
        if (!batch.WriteDescriptorCacheItems(id, new_items)) {
2307
0
            throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
2308
0
        }
2309
0
        m_max_cached_index++;
2310
0
    }
2311
0
    m_wallet_descriptor.range_end = new_range_end;
2312
0
    batch.WriteDescriptor(GetID(), m_wallet_descriptor);
2313
2314
    // By this point, the cache size should be the size of the entire range
2315
0
    assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
2316
2317
0
    m_storage.TopUpCallback(new_spks, this);
2318
0
    NotifyCanGetAddressesChanged();
2319
0
    return true;
2320
0
}
2321
2322
std::vector<WalletDestination> DescriptorScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
2323
0
{
2324
0
    LOCK(cs_desc_man);
2325
0
    std::vector<WalletDestination> result;
2326
0
    if (IsMine(script)) {
2327
0
        int32_t index = m_map_script_pub_keys[script];
2328
0
        if (index >= m_wallet_descriptor.next_index) {
2329
0
            WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
2330
0
            auto out_keys = std::make_unique<FlatSigningProvider>();
2331
0
            std::vector<CScript> scripts_temp;
2332
0
            while (index >= m_wallet_descriptor.next_index) {
2333
0
                if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
2334
0
                    throw std::runtime_error(std::string(__func__) + ": Unable to expand descriptor from cache");
2335
0
                }
2336
0
                CTxDestination dest;
2337
0
                ExtractDestination(scripts_temp[0], dest);
2338
0
                result.push_back({dest, std::nullopt});
2339
0
                m_wallet_descriptor.next_index++;
2340
0
            }
2341
0
        }
2342
0
        if (!TopUp()) {
2343
0
            WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
2344
0
        }
2345
0
    }
2346
2347
0
    return result;
2348
0
}
2349
2350
void DescriptorScriptPubKeyMan::AddDescriptorKey(const CKey& key, const CPubKey &pubkey)
2351
0
{
2352
0
    LOCK(cs_desc_man);
2353
0
    WalletBatch batch(m_storage.GetDatabase());
2354
0
    if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
2355
0
        throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
2356
0
    }
2357
0
}
2358
2359
bool DescriptorScriptPubKeyMan::AddDescriptorKeyWithDB(WalletBatch& batch, const CKey& key, const CPubKey &pubkey)
2360
0
{
2361
0
    AssertLockHeld(cs_desc_man);
2362
0
    assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
2363
2364
    // Check if provided key already exists
2365
0
    if (m_map_keys.find(pubkey.GetID()) != m_map_keys.end() ||
2366
0
        m_map_crypted_keys.find(pubkey.GetID()) != m_map_crypted_keys.end()) {
2367
0
        return true;
2368
0
    }
2369
2370
0
    if (m_storage.HasEncryptionKeys()) {
2371
0
        if (m_storage.IsLocked()) {
2372
0
            return false;
2373
0
        }
2374
2375
0
        std::vector<unsigned char> crypted_secret;
2376
0
        CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
2377
0
        if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
2378
0
                return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
2379
0
            })) {
2380
0
            return false;
2381
0
        }
2382
2383
0
        m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
2384
0
        return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
2385
0
    } else {
2386
0
        m_map_keys[pubkey.GetID()] = key;
2387
0
        return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
2388
0
    }
2389
0
}
2390
2391
bool DescriptorScriptPubKeyMan::SetupDescriptorGeneration(WalletBatch& batch, const CExtKey& master_key, OutputType addr_type, bool internal)
2392
0
{
2393
0
    LOCK(cs_desc_man);
2394
0
    assert(m_storage.IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
2395
2396
    // Ignore when there is already a descriptor
2397
0
    if (m_wallet_descriptor.descriptor) {
2398
0
        return false;
2399
0
    }
2400
2401
0
    m_wallet_descriptor = GenerateWalletDescriptor(master_key.Neuter(), addr_type, internal);
2402
2403
    // Store the master private key, and descriptor
2404
0
    if (!AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey())) {
2405
0
        throw std::runtime_error(std::string(__func__) + ": writing descriptor master private key failed");
2406
0
    }
2407
0
    if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
2408
0
        throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
2409
0
    }
2410
2411
    // TopUp
2412
0
    TopUpWithDB(batch);
2413
2414
0
    m_storage.UnsetBlankWalletFlag(batch);
2415
0
    return true;
2416
0
}
2417
2418
bool DescriptorScriptPubKeyMan::IsHDEnabled() const
2419
0
{
2420
0
    LOCK(cs_desc_man);
2421
0
    return m_wallet_descriptor.descriptor->IsRange();
2422
0
}
2423
2424
bool DescriptorScriptPubKeyMan::CanGetAddresses(bool internal) const
2425
0
{
2426
    // We can only give out addresses from descriptors that are single type (not combo), ranged,
2427
    // and either have cached keys or can generate more keys (ignoring encryption)
2428
0
    LOCK(cs_desc_man);
2429
0
    return m_wallet_descriptor.descriptor->IsSingleType() &&
2430
0
           m_wallet_descriptor.descriptor->IsRange() &&
2431
0
           (HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
2432
0
}
2433
2434
bool DescriptorScriptPubKeyMan::HavePrivateKeys() const
2435
0
{
2436
0
    LOCK(cs_desc_man);
2437
0
    return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
2438
0
}
2439
2440
bool DescriptorScriptPubKeyMan::HaveCryptedKeys() const
2441
0
{
2442
0
    LOCK(cs_desc_man);
2443
0
    return !m_map_crypted_keys.empty();
2444
0
}
2445
2446
std::optional<int64_t> DescriptorScriptPubKeyMan::GetOldestKeyPoolTime() const
2447
0
{
2448
    // This is only used for getwalletinfo output and isn't relevant to descriptor wallets.
2449
0
    return std::nullopt;
2450
0
}
2451
2452
2453
unsigned int DescriptorScriptPubKeyMan::GetKeyPoolSize() const
2454
0
{
2455
0
    LOCK(cs_desc_man);
2456
0
    return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
2457
0
}
2458
2459
int64_t DescriptorScriptPubKeyMan::GetTimeFirstKey() const
2460
0
{
2461
0
    LOCK(cs_desc_man);
2462
0
    return m_wallet_descriptor.creation_time;
2463
0
}
2464
2465
std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
2466
0
{
2467
0
    LOCK(cs_desc_man);
2468
2469
    // Find the index of the script
2470
0
    auto it = m_map_script_pub_keys.find(script);
2471
0
    if (it == m_map_script_pub_keys.end()) {
2472
0
        return nullptr;
2473
0
    }
2474
0
    int32_t index = it->second;
2475
2476
0
    return GetSigningProvider(index, include_private);
2477
0
}
2478
2479
std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
2480
0
{
2481
0
    LOCK(cs_desc_man);
2482
2483
    // Find index of the pubkey
2484
0
    auto it = m_map_pubkeys.find(pubkey);
2485
0
    if (it == m_map_pubkeys.end()) {
2486
0
        return nullptr;
2487
0
    }
2488
0
    int32_t index = it->second;
2489
2490
    // Always try to get the signing provider with private keys. This function should only be called during signing anyways
2491
0
    std::unique_ptr<FlatSigningProvider> out = GetSigningProvider(index, true);
2492
0
    if (!out->HaveKey(pubkey.GetID())) {
2493
0
        return nullptr;
2494
0
    }
2495
0
    return out;
2496
0
}
2497
2498
std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
2499
0
{
2500
0
    AssertLockHeld(cs_desc_man);
2501
2502
0
    std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
2503
2504
    // Fetch SigningProvider from cache to avoid re-deriving
2505
0
    auto it = m_map_signing_providers.find(index);
2506
0
    if (it != m_map_signing_providers.end()) {
2507
0
        out_keys->Merge(FlatSigningProvider{it->second});
2508
0
    } else {
2509
        // Get the scripts, keys, and key origins for this script
2510
0
        std::vector<CScript> scripts_temp;
2511
0
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
2512
2513
        // Cache SigningProvider so we don't need to re-derive if we need this SigningProvider again
2514
0
        m_map_signing_providers[index] = *out_keys;
2515
0
    }
2516
2517
0
    if (HavePrivateKeys() && include_private) {
2518
0
        FlatSigningProvider master_provider;
2519
0
        master_provider.keys = GetKeys();
2520
0
        m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
2521
0
    }
2522
2523
0
    return out_keys;
2524
0
}
2525
2526
std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
2527
0
{
2528
0
    return GetSigningProvider(script, false);
2529
0
}
2530
2531
bool DescriptorScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
2532
0
{
2533
0
    return IsMine(script);
2534
0
}
2535
2536
bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
2537
0
{
2538
0
    std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
2539
0
    for (const auto& coin_pair : coins) {
2540
0
        std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
2541
0
        if (!coin_keys) {
2542
0
            continue;
2543
0
        }
2544
0
        keys->Merge(std::move(*coin_keys));
2545
0
    }
2546
2547
0
    return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
2548
0
}
2549
2550
SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
2551
0
{
2552
0
    std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
2553
0
    if (!keys) {
2554
0
        return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
2555
0
    }
2556
2557
0
    CKey key;
2558
0
    if (!keys->GetKey(ToKeyID(pkhash), key)) {
2559
0
        return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
2560
0
    }
2561
2562
0
    if (!MessageSign(key, message, str_sig)) {
2563
0
        return SigningResult::SIGNING_FAILED;
2564
0
    }
2565
0
    return SigningResult::OK;
2566
0
}
2567
2568
std::optional<PSBTError> DescriptorScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, int sighash_type, bool sign, bool bip32derivs, int* n_signed, bool finalize) const
2569
0
{
2570
0
    if (n_signed) {
2571
0
        *n_signed = 0;
2572
0
    }
2573
0
    for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
2574
0
        const CTxIn& txin = psbtx.tx->vin[i];
2575
0
        PSBTInput& input = psbtx.inputs.at(i);
2576
2577
0
        if (PSBTInputSigned(input)) {
2578
0
            continue;
2579
0
        }
2580
2581
        // Get the Sighash type
2582
0
        if (sign && input.sighash_type != std::nullopt && *input.sighash_type != sighash_type) {
2583
0
            return PSBTError::SIGHASH_MISMATCH;
2584
0
        }
2585
2586
        // Get the scriptPubKey to know which SigningProvider to use
2587
0
        CScript script;
2588
0
        if (!input.witness_utxo.IsNull()) {
2589
0
            script = input.witness_utxo.scriptPubKey;
2590
0
        } else if (input.non_witness_utxo) {
2591
0
            if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
2592
0
                return PSBTError::MISSING_INPUTS;
2593
0
            }
2594
0
            script = input.non_witness_utxo->vout[txin.prevout.n].scriptPubKey;
2595
0
        } else {
2596
            // There's no UTXO so we can just skip this now
2597
0
            continue;
2598
0
        }
2599
2600
0
        std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
2601
0
        std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, /*include_private=*/sign);
2602
0
        if (script_keys) {
2603
0
            keys->Merge(std::move(*script_keys));
2604
0
        } else {
2605
            // Maybe there are pubkeys listed that we can sign for
2606
0
            std::vector<CPubKey> pubkeys;
2607
0
            pubkeys.reserve(input.hd_keypaths.size() + 2);
2608
2609
            // ECDSA Pubkeys
2610
0
            for (const auto& [pk, _] : input.hd_keypaths) {
2611
0
                pubkeys.push_back(pk);
2612
0
            }
2613
2614
            // Taproot output pubkey
2615
0
            std::vector<std::vector<unsigned char>> sols;
2616
0
            if (Solver(script, sols) == TxoutType::WITNESS_V1_TAPROOT) {
2617
0
                sols[0].insert(sols[0].begin(), 0x02);
2618
0
                pubkeys.emplace_back(sols[0]);
2619
0
                sols[0][0] = 0x03;
2620
0
                pubkeys.emplace_back(sols[0]);
2621
0
            }
2622
2623
            // Taproot pubkeys
2624
0
            for (const auto& pk_pair : input.m_tap_bip32_paths) {
2625
0
                const XOnlyPubKey& pubkey = pk_pair.first;
2626
0
                for (unsigned char prefix : {0x02, 0x03}) {
2627
0
                    unsigned char b[33] = {prefix};
2628
0
                    std::copy(pubkey.begin(), pubkey.end(), b + 1);
2629
0
                    CPubKey fullpubkey;
2630
0
                    fullpubkey.Set(b, b + 33);
2631
0
                    pubkeys.push_back(fullpubkey);
2632
0
                }
2633
0
            }
2634
2635
0
            for (const auto& pubkey : pubkeys) {
2636
0
                std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
2637
0
                if (pk_keys) {
2638
0
                    keys->Merge(std::move(*pk_keys));
2639
0
                }
2640
0
            }
2641
0
        }
2642
2643
0
        SignPSBTInput(HidingSigningProvider(keys.get(), /*hide_secret=*/!sign, /*hide_origin=*/!bip32derivs), psbtx, i, &txdata, sighash_type, nullptr, finalize);
2644
2645
0
        bool signed_one = PSBTInputSigned(input);
2646
0
        if (n_signed && (signed_one || !sign)) {
2647
            // If sign is false, we assume that we _could_ sign if we get here. This
2648
            // will never have false negatives; it is hard to tell under what i
2649
            // circumstances it could have false positives.
2650
0
            (*n_signed)++;
2651
0
        }
2652
0
    }
2653
2654
    // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
2655
0
    for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
2656
0
        std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
2657
0
        if (!keys) {
2658
0
            continue;
2659
0
        }
2660
0
        UpdatePSBTOutput(HidingSigningProvider(keys.get(), /*hide_secret=*/true, /*hide_origin=*/!bip32derivs), psbtx, i);
2661
0
    }
2662
2663
0
    return {};
2664
0
}
2665
2666
std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
2667
0
{
2668
0
    std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
2669
0
    if (provider) {
2670
0
        KeyOriginInfo orig;
2671
0
        CKeyID key_id = GetKeyForDestination(*provider, dest);
2672
0
        if (provider->GetKeyOrigin(key_id, orig)) {
2673
0
            LOCK(cs_desc_man);
2674
0
            std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
2675
0
            meta->key_origin = orig;
2676
0
            meta->has_key_origin = true;
2677
0
            meta->nCreateTime = m_wallet_descriptor.creation_time;
2678
0
            return meta;
2679
0
        }
2680
0
    }
2681
0
    return nullptr;
2682
0
}
2683
2684
uint256 DescriptorScriptPubKeyMan::GetID() const
2685
0
{
2686
0
    LOCK(cs_desc_man);
2687
0
    return m_wallet_descriptor.id;
2688
0
}
2689
2690
void DescriptorScriptPubKeyMan::SetCache(const DescriptorCache& cache)
2691
0
{
2692
0
    LOCK(cs_desc_man);
2693
0
    std::set<CScript> new_spks;
2694
0
    m_wallet_descriptor.cache = cache;
2695
0
    for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
2696
0
        FlatSigningProvider out_keys;
2697
0
        std::vector<CScript> scripts_temp;
2698
0
        if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2699
0
            throw std::runtime_error("Error: Unable to expand wallet descriptor from cache");
2700
0
        }
2701
        // Add all of the scriptPubKeys to the scriptPubKey set
2702
0
        new_spks.insert(scripts_temp.begin(), scripts_temp.end());
2703
0
        for (const CScript& script : scripts_temp) {
2704
0
            if (m_map_script_pub_keys.count(script) != 0) {
2705
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]));
2706
0
            }
2707
0
            m_map_script_pub_keys[script] = i;
2708
0
        }
2709
0
        for (const auto& pk_pair : out_keys.pubkeys) {
2710
0
            const CPubKey& pubkey = pk_pair.second;
2711
0
            if (m_map_pubkeys.count(pubkey) != 0) {
2712
                // We don't need to give an error here.
2713
                // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and it's private key
2714
0
                continue;
2715
0
            }
2716
0
            m_map_pubkeys[pubkey] = i;
2717
0
        }
2718
0
        m_max_cached_index++;
2719
0
    }
2720
    // Make sure the wallet knows about our new spks
2721
0
    m_storage.TopUpCallback(new_spks, this);
2722
0
}
2723
2724
bool DescriptorScriptPubKeyMan::AddKey(const CKeyID& key_id, const CKey& key)
2725
0
{
2726
0
    LOCK(cs_desc_man);
2727
0
    m_map_keys[key_id] = key;
2728
0
    return true;
2729
0
}
2730
2731
bool DescriptorScriptPubKeyMan::AddCryptedKey(const CKeyID& key_id, const CPubKey& pubkey, const std::vector<unsigned char>& crypted_key)
2732
0
{
2733
0
    LOCK(cs_desc_man);
2734
0
    if (!m_map_keys.empty()) {
2735
0
        return false;
2736
0
    }
2737
2738
0
    m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
2739
0
    return true;
2740
0
}
2741
2742
bool DescriptorScriptPubKeyMan::HasWalletDescriptor(const WalletDescriptor& desc) const
2743
0
{
2744
0
    LOCK(cs_desc_man);
2745
0
    return !m_wallet_descriptor.id.IsNull() && !desc.id.IsNull() && m_wallet_descriptor.id == desc.id;
2746
0
}
2747
2748
void DescriptorScriptPubKeyMan::WriteDescriptor()
2749
0
{
2750
0
    LOCK(cs_desc_man);
2751
0
    WalletBatch batch(m_storage.GetDatabase());
2752
0
    if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
2753
0
        throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
2754
0
    }
2755
0
}
2756
2757
WalletDescriptor DescriptorScriptPubKeyMan::GetWalletDescriptor() const
2758
0
{
2759
0
    return m_wallet_descriptor;
2760
0
}
2761
2762
std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
2763
0
{
2764
0
    return GetScriptPubKeys(0);
2765
0
}
2766
2767
std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys(int32_t minimum_index) const
2768
0
{
2769
0
    LOCK(cs_desc_man);
2770
0
    std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
2771
0
    script_pub_keys.reserve(m_map_script_pub_keys.size());
2772
2773
0
    for (auto const& [script_pub_key, index] : m_map_script_pub_keys) {
2774
0
        if (index >= minimum_index) script_pub_keys.insert(script_pub_key);
2775
0
    }
2776
0
    return script_pub_keys;
2777
0
}
2778
2779
int32_t DescriptorScriptPubKeyMan::GetEndRange() const
2780
0
{
2781
0
    return m_max_cached_index + 1;
2782
0
}
2783
2784
bool DescriptorScriptPubKeyMan::GetDescriptorString(std::string& out, const bool priv) const
2785
0
{
2786
0
    LOCK(cs_desc_man);
2787
2788
0
    FlatSigningProvider provider;
2789
0
    provider.keys = GetKeys();
2790
2791
0
    if (priv) {
2792
        // For the private version, always return the master key to avoid
2793
        // exposing child private keys. The risk implications of exposing child
2794
        // private keys together with the parent xpub may be non-obvious for users.
2795
0
        return m_wallet_descriptor.descriptor->ToPrivateString(provider, out);
2796
0
    }
2797
2798
0
    return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
2799
0
}
2800
2801
void DescriptorScriptPubKeyMan::UpgradeDescriptorCache()
2802
0
{
2803
0
    LOCK(cs_desc_man);
2804
0
    if (m_storage.IsLocked() || m_storage.IsWalletFlagSet(WALLET_FLAG_LAST_HARDENED_XPUB_CACHED)) {
2805
0
        return;
2806
0
    }
2807
2808
    // Skip if we have the last hardened xpub cache
2809
0
    if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
2810
0
        return;
2811
0
    }
2812
2813
    // Expand the descriptor
2814
0
    FlatSigningProvider provider;
2815
0
    provider.keys = GetKeys();
2816
0
    FlatSigningProvider out_keys;
2817
0
    std::vector<CScript> scripts_temp;
2818
0
    DescriptorCache temp_cache;
2819
0
    if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
2820
0
        throw std::runtime_error("Unable to expand descriptor");
2821
0
    }
2822
2823
    // Cache the last hardened xpubs
2824
0
    DescriptorCache diff = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
2825
0
    if (!WalletBatch(m_storage.GetDatabase()).WriteDescriptorCacheItems(GetID(), diff)) {
2826
0
        throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
2827
0
    }
2828
0
}
2829
2830
void DescriptorScriptPubKeyMan::UpdateWalletDescriptor(WalletDescriptor& descriptor)
2831
0
{
2832
0
    LOCK(cs_desc_man);
2833
0
    std::string error;
2834
0
    if (!CanUpdateToWalletDescriptor(descriptor, error)) {
2835
0
        throw std::runtime_error(std::string(__func__) + ": " + error);
2836
0
    }
2837
2838
0
    m_map_pubkeys.clear();
2839
0
    m_map_script_pub_keys.clear();
2840
0
    m_max_cached_index = -1;
2841
0
    m_wallet_descriptor = descriptor;
2842
2843
0
    NotifyFirstKeyTimeChanged(this, m_wallet_descriptor.creation_time);
2844
0
}
2845
2846
bool DescriptorScriptPubKeyMan::CanUpdateToWalletDescriptor(const WalletDescriptor& descriptor, std::string& error)
2847
0
{
2848
0
    LOCK(cs_desc_man);
2849
0
    if (!HasWalletDescriptor(descriptor)) {
2850
0
        error = "can only update matching descriptor";
2851
0
        return false;
2852
0
    }
2853
2854
0
    if (descriptor.range_start > m_wallet_descriptor.range_start ||
2855
0
        descriptor.range_end < m_wallet_descriptor.range_end) {
2856
        // Use inclusive range for error
2857
0
        error = strprintf("new range must include current range = [%d,%d]",
2858
0
                          m_wallet_descriptor.range_start,
2859
0
                          m_wallet_descriptor.range_end - 1);
2860
0
        return false;
2861
0
    }
2862
2863
0
    return true;
2864
0
}
2865
} // namespace wallet