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