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