Bitcoin Core 32.99.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 <limits>
25#include <optional>
26
28using util::ToString;
29
30namespace wallet {
31
32typedef std::vector<unsigned char> valtype;
33
34// Legacy wallet IsMine(). Used only in migration
35// DO NOT USE ANYTHING IN THIS NAMESPACE OUTSIDE OF MIGRATION
36namespace {
37
44enum class IsMineSigVersion
45{
46 TOP = 0,
47 P2SH = 1,
48 WITNESS_V0 = 2,
49};
50
56enum class IsMineResult
57{
58 NO = 0,
59 WATCH_ONLY = 1,
60 SPENDABLE = 2,
61 INVALID = 3,
62};
63
64bool PermitsUncompressed(IsMineSigVersion sigversion)
65{
66 return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
67}
68
69bool HaveKeys(const std::vector<valtype>& pubkeys, const LegacyDataSPKM& keystore)
70{
71 for (const valtype& pubkey : pubkeys) {
72 CKeyID keyID = CPubKey(pubkey).GetID();
73 if (!keystore.HaveKey(keyID)) return false;
74 }
75 return true;
76}
77
86// NOLINTNEXTLINE(misc-no-recursion)
87IsMineResult LegacyWalletIsMineInnerDONOTUSE(const LegacyDataSPKM& keystore, const CScript& scriptPubKey, IsMineSigVersion sigversion, bool recurse_scripthash=true)
88{
89 IsMineResult ret = IsMineResult::NO;
90
91 std::vector<valtype> vSolutions;
92 TxoutType whichType = Solver(scriptPubKey, vSolutions);
93
95 switch (whichType) {
101 break;
104 if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
105 return IsMineResult::INVALID;
106 }
107 if (keystore.HaveKey(keyID)) {
108 ret = std::max(ret, IsMineResult::SPENDABLE);
109 }
110 break;
112 {
113 if (sigversion == IsMineSigVersion::WITNESS_V0) {
114 // P2WPKH inside P2WSH is invalid.
115 return IsMineResult::INVALID;
116 }
117 if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
118 // We do not support bare witness outputs unless the P2SH version of it would be
119 // acceptable as well. This protects against matching before segwit activates.
120 // This also applies to the P2WSH case.
121 break;
122 }
123 ret = std::max(ret, LegacyWalletIsMineInnerDONOTUSE(keystore, GetScriptForDestination(PKHash(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
124 break;
125 }
129 CPubKey pubkey;
130 if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
131 return IsMineResult::INVALID;
132 }
133 }
134 if (keystore.HaveKey(keyID)) {
135 ret = std::max(ret, IsMineResult::SPENDABLE);
136 }
137 break;
139 {
140 if (sigversion != IsMineSigVersion::TOP) {
141 // P2SH inside P2WSH or P2SH is invalid.
142 return IsMineResult::INVALID;
143 }
146 if (keystore.GetCScript(scriptID, subscript)) {
147 ret = std::max(ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
148 }
149 break;
150 }
152 {
153 if (sigversion == IsMineSigVersion::WITNESS_V0) {
154 // P2WSH inside P2WSH is invalid.
155 return IsMineResult::INVALID;
156 }
157 if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
158 break;
159 }
162 if (keystore.GetCScript(scriptID, subscript)) {
163 ret = std::max(ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::WITNESS_V0) : IsMineResult::SPENDABLE);
164 }
165 break;
166 }
167
169 {
170 // Never treat bare multisig outputs as ours (they can still be made watchonly-though)
171 if (sigversion == IsMineSigVersion::TOP) {
172 break;
173 }
174
175 // Only consider transactions "mine" if we own ALL the
176 // keys involved. Multi-signature transactions that are
177 // partially owned (somebody else has a key that can spend
178 // them) enable spend-out-from-under-you attacks, especially
179 // in shared-wallet situations.
180 std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
182 for (size_t i = 0; i < keys.size(); i++) {
183 if (keys[i].size() != 33) {
184 return IsMineResult::INVALID;
185 }
186 }
187 }
188 if (HaveKeys(keys, keystore)) {
189 ret = std::max(ret, IsMineResult::SPENDABLE);
190 }
191 break;
192 }
193 } // no default case, so the compiler can warn about missing cases
194
195 if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
196 ret = std::max(ret, IsMineResult::WATCH_ONLY);
197 }
198 return ret;
199}
200
201} // namespace
202
204{
205 switch (LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP)) {
206 case IsMineResult::INVALID:
207 case IsMineResult::NO:
208 return false;
209 case IsMineResult::WATCH_ONLY:
210 case IsMineResult::SPENDABLE:
211 return true;
212 }
213 assert(false);
214}
215
217{
218 {
220 assert(mapKeys.empty());
221
222 bool keyPass = mapCryptedKeys.empty(); // Always pass when there are no encrypted keys
223 bool keyFail = false;
224 CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
226 for (; mi != mapCryptedKeys.end(); ++mi)
227 {
228 const CPubKey &vchPubKey = (*mi).second.first;
229 const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
230 CKey key;
231 if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
232 {
233 keyFail = true;
234 break;
235 }
236 keyPass = true;
238 break;
239 else {
240 // Rewrite these encrypted keys with checksums
242 }
243 }
244 if (keyPass && keyFail)
245 {
246 LogWarning("The wallet is probably corrupted: Some keys decrypt but not all.");
247 throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
248 }
249 if (keyFail || !keyPass)
250 return false;
252 }
253 return true;
254}
255
256std::unique_ptr<SigningProvider> LegacyDataSPKM::GetSolvingProvider(const CScript& script) const
257{
258 return std::make_unique<LegacySigningProvider>(*this);
259}
260
262{
263 IsMineResult ismine = LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
264 if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
265 // If ismine, it means we recognize keys or script ids in the script, or
266 // are watching the script itself, and we can at least provide metadata
267 // or solving information, even if not able to sign fully.
268 return true;
269 } else {
270 // If, given the stuff in sigdata, we could make a valid signature, then we can provide for this script
272 if (!sigdata.signatures.empty()) {
273 // If we could make signatures, make sure we have a private key to actually make a signature
274 bool has_privkeys = false;
275 for (const auto& key_sig_pair : sigdata.signatures) {
277 }
278 return has_privkeys;
279 }
280 return false;
281 }
282}
283
284bool LegacyDataSPKM::LoadKey(const CKey& key, const CPubKey &pubkey)
285{
286 return AddKeyPubKeyInner(key, pubkey);
287}
288
290{
291 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
292 * that never can be redeemed. However, old wallets may still contain
293 * these. Do not add them to the wallet and warn. */
295 {
297 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.", __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
298 return true;
299 }
300
302}
303
309
315
316bool LegacyDataSPKM::AddKeyPubKeyInner(const CKey& key, const CPubKey& pubkey)
317{
319 return FillableSigningProvider::AddKeyPubKey(key, pubkey);
320}
321
322bool LegacyDataSPKM::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid)
323{
324 // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
325 if (!checksum_valid) {
327 }
328
330}
331
332bool LegacyDataSPKM::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
333{
335 assert(mapKeys.empty());
336
339 return true;
340}
341
343{
345 return setWatchOnly.contains(dest);
346}
347
349{
350 return AddWatchOnlyInMem(dest);
351}
352
353static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
354{
355 std::vector<std::vector<unsigned char>> solutions;
356 return Solver(dest, solutions) == TxoutType::PUBKEY &&
357 (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
358}
359
361{
363 setWatchOnly.insert(dest);
365 if (ExtractPubKey(dest, pubKey)) {
366 mapWatchKeys[pubKey.GetID()] = pubKey;
368 }
369 return true;
370}
371
373{
375 m_hd_chain = chain;
376}
377
379{
381 assert(!chain.seed_id.IsNull());
382 m_inactive_hd_chains[chain.seed_id] = chain;
383}
384
385bool LegacyDataSPKM::HaveKey(const CKeyID &address) const
386{
389 return FillableSigningProvider::HaveKey(address);
390 }
391 return mapCryptedKeys.contains(address);
392}
393
394bool LegacyDataSPKM::GetKey(const CKeyID &address, CKey& keyOut) const
395{
399 }
400
401 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
402 if (mi != mapCryptedKeys.end())
403 {
404 const CPubKey &vchPubKey = (*mi).second.first;
405 const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
408 });
409 }
410 return false;
411}
412
414{
416 {
418 auto it = mapKeyMetadata.find(keyID);
419 if (it == mapKeyMetadata.end()) {
420 return false;
421 }
422 meta = it->second;
423 }
424 if (meta.has_key_origin) {
425 info.fingerprint = meta.key_origin.fingerprint;
426 info.path = meta.key_origin.path;
427 } else { // Single pubkeys get the master fingerprint of themselves
428 info.fingerprint = keyID.fingerprint();
429 }
430 return true;
431}
432
434{
436 WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
437 if (it != mapWatchKeys.end()) {
438 pubkey_out = it->second;
439 return true;
440 }
441 return false;
442}
443
445{
449 return GetWatchPubKey(address, vchPubKeyOut);
450 }
451 return true;
452 }
453
454 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
455 if (mi != mapCryptedKeys.end())
456 {
457 vchPubKeyOut = (*mi).second.first;
458 return true;
459 }
460 // Check for watch-only pubkeys
461 return GetWatchPubKey(address, vchPubKeyOut);
462}
463
464std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetCandidateScriptPubKeys() const
465{
467 std::unordered_set<CScript, SaltedSipHasher> candidate_spks;
468
469 // For every private key in the wallet, there should be a P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH
470 const auto& add_pubkey = [&candidate_spks](const CPubKey& pub) -> void {
473
475 candidate_spks.insert(wpkh);
477 };
478 for (const auto& [_, key] : mapKeys) {
479 add_pubkey(key.GetPubKey());
480 }
481 for (const auto& [_, ckeypair] : mapCryptedKeys) {
482 add_pubkey(ckeypair.first);
483 }
484
485 // mapScripts contains all redeemScripts and witnessScripts. Therefore each script in it has
486 // itself, P2SH, P2WSH, and P2SH-P2WSH as a candidate.
487 // Invalid scripts such as P2SH-P2SH and P2WSH-P2SH, among others, will be added as candidates.
488 // Callers of this function will need to remove such scripts.
489 const auto& add_script = [&candidate_spks](const CScript& script) -> void {
490 candidate_spks.insert(script);
492
494 candidate_spks.insert(wsh);
496 };
497 for (const auto& [_, script] : mapScripts) {
499 }
500
501 // Although setWatchOnly should only contain output scripts, we will also include each script's
502 // P2SH, P2WSH, and P2SH-P2WSH as a precaution.
503 for (const auto& script : setWatchOnly) {
505 }
506
507 return candidate_spks;
508}
509
510std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetScriptPubKeys() const
511{
512 // Run IsMine() on each candidate output script. Any script that IsMine is an output
513 // script to return.
514 // This both filters out things that are not watched by the wallet, and things that are invalid.
515 std::unordered_set<CScript, SaltedSipHasher> spks;
516 for (const CScript& script : GetCandidateScriptPubKeys()) {
517 if (IsMine(script)) {
518 spks.insert(script);
519 }
520 }
521
522 return spks;
523}
524
525std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetNotMineScriptPubKeys() const
526{
528 std::unordered_set<CScript, SaltedSipHasher> spks;
529 for (const CScript& script : setWatchOnly) {
530 if (!IsMine(script)) spks.insert(script);
531 }
532 return spks;
533}
534
535std::optional<MigrationData> LegacyDataSPKM::MigrateToDescriptor()
536{
538 if (m_storage.IsLocked()) {
539 return std::nullopt;
540 }
541
542 MigrationData out;
543
544 std::unordered_set<CScript, SaltedSipHasher> spks{GetScriptPubKeys()};
545
546 // Get all key ids
547 std::set<CKeyID> keyids;
548 for (const auto& key_pair : mapKeys) {
549 keyids.insert(key_pair.first);
550 }
551 for (const auto& key_pair : mapCryptedKeys) {
552 keyids.insert(key_pair.first);
553 }
554
555 // Get key metadata and figure out which keys don't have a seed
556 // Note that we do not ignore the seeds themselves because they are considered IsMine!
557 for (auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
558 const CKeyID& keyid = *keyid_it;
559 const auto& it = mapKeyMetadata.find(keyid);
560 if (it != mapKeyMetadata.end()) {
561 const CKeyMetadata& meta = it->second;
562 if (meta.hdKeypath == "s" || meta.hdKeypath == "m") {
563 keyid_it++;
564 continue;
565 }
566 if (!meta.hd_seed_id.IsNull() && (m_hd_chain.seed_id == meta.hd_seed_id || m_inactive_hd_chains.contains(meta.hd_seed_id))) {
567 keyid_it = keyids.erase(keyid_it);
568 continue;
569 }
570 }
571 keyid_it++;
572 }
573
575 if (!batch.TxnBegin()) {
576 LogWarning("Error generating descriptors for migration, cannot initialize db transaction");
577 return std::nullopt;
578 }
579
580 // keyids is now all non-HD keys. Each key will have its own combo descriptor
581 for (const CKeyID& keyid : keyids) {
582 CKey key;
583 if (!GetKey(keyid, key)) {
584 assert(false);
585 }
586
587 // Get birthdate from key meta
588 uint64_t creation_time = 0;
589 const auto& it = mapKeyMetadata.find(keyid);
590 if (it != mapKeyMetadata.end()) {
591 creation_time = it->second.nCreateTime;
592 }
593
594 // Get the key origin
595 // Maybe this doesn't matter because floating keys here shouldn't have origins
596 KeyOriginInfo info;
597 bool has_info = GetKeyOrigin(keyid, info);
598 std::string origin_str = has_info ? "[" + HexStr(info.fingerprint) + FormatHDKeypath(info.path) + "]" : "";
599
600 // Construct the combo descriptor
601 std::string desc_str = "combo(" + origin_str + HexStr(key.GetPubKey()) + ")";
603 std::string error;
604 std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, provider, error, false);
605 CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
606 WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
607
608 // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
609 provider.keys.emplace(key.GetPubKey().GetID(), key);
611 auto desc_spks = desc_spk_man->GetScriptPubKeys();
612
613 // Remove the scriptPubKeys from our current set
614 for (const CScript& spk : desc_spks) {
615 size_t erased = spks.erase(spk);
616 assert(erased == 1);
617 assert(IsMine(spk));
618 }
619
620 out.desc_spkms.push_back(std::move(desc_spk_man));
621 }
622
623 // Handle HD keys by using the CHDChains
624 std::set<CHDChain> chains;
625 chains.insert(m_hd_chain);
626 for (const auto& chain_pair : m_inactive_hd_chains) {
627 chains.insert(chain_pair.second);
628 }
629
631
632 std::set<CExtPubKey> master_xpubs;
633 for (const CHDChain& chain : chains) {
634 if (chain.seed_id.IsNull()) continue;
635
636 // Get the master xprv
638 if (!GetKey(chain.seed_id, seed_key)) {
639 assert(false);
640 }
641 CExtKey master_key;
642 master_key.SetSeed(seed_key);
643
644 // Get the xpub and verify that we haven't already seen this xpub before
645 CExtPubKey master_xpub = master_key.Neuter();
646 const auto& [_, inserted] = master_xpubs.insert(master_xpub);
647 if (!inserted) continue;
648
649 for (int i = 0; i < 2; ++i) {
650 // Skip if doing internal chain and split chain is not supported
651 if (i == 1 && !can_support_hd_split_feature) {
652 continue;
653 }
654
655 // Make the combo descriptor
656 std::string xpub = EncodeExtPubKey(master_key.Neuter());
657 std::string desc_str = "combo(" + xpub + "/0h/" + ToString(i) + "h/*h)";
659 std::string error;
660 std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, provider, error, false);
661 CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
662 uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
663 WalletDescriptor w_desc(std::move(descs.at(0)), 0, 0, chain_counter, 0);
664
665 // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
666 provider.keys.emplace(master_key.key.GetPubKey().GetID(), master_key.key);
668 auto desc_spks = desc_spk_man->GetScriptPubKeys();
669
670 // Remove the scriptPubKeys from our current set
671 for (const CScript& spk : desc_spks) {
672 size_t erased = spks.erase(spk);
673 assert(erased == 1);
674 assert(IsMine(spk));
675 }
676
677 out.desc_spkms.push_back(std::move(desc_spk_man));
678 }
679 }
680 // Add the current master seed to the migration data
681 if (!m_hd_chain.seed_id.IsNull()) {
684 assert(false);
685 }
686 out.master_key.SetSeed(seed_key);
687 }
688
689 // Handle the rest of the scriptPubKeys which must be imports and may not have all info
690 for (auto it = spks.begin(); it != spks.end();) {
691 const CScript& spk = *it;
692
693 // Get birthdate from script meta
694 uint64_t creation_time = 0;
695 const auto& mit = m_script_metadata.find(CScriptID(spk));
696 if (mit != m_script_metadata.end()) {
697 creation_time = mit->second.nCreateTime;
698 }
699
700 // InferDescriptor as that will get us all the solving info if it is there
701 std::unique_ptr<Descriptor> desc = InferDescriptor(spk, *GetSolvingProvider(spk));
702
703 // Past bugs in InferDescriptor have caused it to create descriptors which cannot be re-parsed.
704 // Re-parse the descriptors to detect that, and skip any that do not parse.
705 {
706 std::string desc_str = desc->ToString();
708 std::string parse_error;
709 std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error);
710 if (parsed_descs.empty()) {
711 // Remove this scriptPubKey from the set
712 it = spks.erase(it);
713 continue;
714 }
715 }
716
717 // Get the private keys for this descriptor
718 std::vector<CScript> scripts;
720 if (!desc->Expand(0, DUMMY_SIGNING_PROVIDER, scripts, keys)) {
721 assert(false);
722 }
723 std::set<CKeyID> privkeyids;
724 for (const auto& key_orig_pair : keys.origins) {
725 privkeyids.insert(key_orig_pair.first);
726 }
727
728 std::vector<CScript> desc_spks;
729
730 // If we can't provide all private keys for this inferred descriptor,
731 // but this wallet is not watch-only, migrate it to the watch-only wallet.
732 if (!desc->HavePrivateKeys(*this) && !m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
733 out.watch_descs.emplace_back(desc->ToString(), creation_time);
734
735 // Get the scriptPubKeys without writing this to the wallet
737 desc->Expand(0, provider, desc_spks, provider);
738 } else {
739 // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
740 for (const auto& keyid : privkeyids) {
741 CKey key;
742 if (!GetKey(keyid, key)) {
743 continue;
744 }
745 keys.keys.emplace(key.GetPubKey().GetID(), key);
746 }
747 WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
749 auto desc_spks_set = desc_spk_man->GetScriptPubKeys();
750 desc_spks.insert(desc_spks.end(), desc_spks_set.begin(), desc_spks_set.end());
751
752 out.desc_spkms.push_back(std::move(desc_spk_man));
753 }
754
755 // Remove the scriptPubKeys from our current set
756 for (const CScript& desc_spk : desc_spks) {
757 auto del_it = spks.find(desc_spk);
758 assert(del_it != spks.end());
760 it = spks.erase(del_it);
761 }
762 }
763
764 // Make sure that we have accounted for all scriptPubKeys
765 if (!Assume(spks.empty())) {
766 LogError("%s", STR_INTERNAL_BUG("Error: Some output scripts were not migrated."));
767 return std::nullopt;
768 }
769
770 // Legacy wallets can also contain scripts whose P2SH, P2WSH, or P2SH-P2WSH it is not watching for
771 // but can provide script data to a PSBT spending them. These "solvable" output scripts will need to
772 // be put into the separate "solvables" wallet.
773 // These can be detected by going through the entire candidate output scripts, finding the not IsMine scripts,
774 // and checking CanProvide() which will dummy sign.
775 for (const CScript& script : GetCandidateScriptPubKeys()) {
776 // Since we only care about P2SH, P2WSH, and P2SH-P2WSH, filter out any scripts that are not those
777 if (!script.IsPayToScriptHash() && !script.IsPayToWitnessScriptHash()) {
778 continue;
779 }
780 if (IsMine(script)) {
781 continue;
782 }
785 continue;
786 }
787
788 // Get birthdate from script meta
789 uint64_t creation_time = 0;
790 const auto& it = m_script_metadata.find(CScriptID(script));
791 if (it != m_script_metadata.end()) {
792 creation_time = it->second.nCreateTime;
793 }
794
795 // InferDescriptor as that will get us all the solving info if it is there
796 std::unique_ptr<Descriptor> desc = InferDescriptor(script, *GetSolvingProvider(script));
797 if (!desc->IsSolvable()) {
798 // The wallet was able to provide some information, but not enough to make a descriptor that actually
799 // contains anything useful. This is probably because the script itself is actually unsignable (e.g. P2WSH-P2WSH).
800 continue;
801 }
802
803 // Past bugs in InferDescriptor have caused it to create descriptors which cannot be re-parsed
804 // Re-parse the descriptors to detect that, and skip any that do not parse.
805 {
806 std::string desc_str = desc->ToString();
808 std::string parse_error;
809 std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error, false);
810 if (parsed_descs.empty()) {
811 continue;
812 }
813 }
814
815 out.solvable_descs.emplace_back(desc->ToString(), creation_time);
816 }
817
818 // Finalize transaction
819 if (!batch.TxnCommit()) {
820 LogWarning("Error generating descriptors for migration, cannot commit db transaction");
821 return std::nullopt;
822 }
823
824 return out;
825}
826
832
834{
835 auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, descriptor, keypool_size));
836 LOCK(spkm->cs_desc_man);
837 WalletBatch batch(storage.GetDatabase());
838 spkm->UpdateWithSigningProvider(batch, provider);
839 return spkm;
840}
841
843{
844 auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, descriptor, keypool_size));
845 LOCK(spkm->cs_desc_man);
846 spkm->UpdateWithSigningProvider(batch, provider);
847 return spkm;
848}
849
854 m_keypool_size(keypool_size),
855 m_id(id),
856 m_wallet_descriptor(descriptor)
857{
858 if (!keys.empty() && !ckeys.empty()) {
859 throw std::runtime_error("Wallet contains both unencrypted and encrypted keys");
860 }
861 Load();
862}
863
864std::unique_ptr<DescriptorScriptPubKeyMan> DescriptorScriptPubKeyMan::LoadFromStorage(WalletStorage& storage, const uint256& id, WalletDescriptor& descriptor, int64_t keypool_size, const KeyMap& keys, const CryptedKeyMap& ckeys)
865{
866 return std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, id, descriptor, keypool_size, keys, ckeys));
867}
868
869std::unique_ptr<DescriptorScriptPubKeyMan> DescriptorScriptPubKeyMan::GenerateNewSingleSig(WalletStorage& storage, WalletBatch& batch, int64_t keypool_size, const CExtKey& master_key, OutputType addr_type, bool internal)
870{
871 WalletDescriptor desc = GenerateWalletDescriptor(master_key.Neuter(), addr_type, internal);
872
873 auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(storage, desc, keypool_size));
874
875 LOCK(spkm->cs_desc_man);
876 Assert(spkm->m_storage.IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));
877
878 // Store the master private key, and descriptor
879 if (!spkm->AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey())) {
880 throw std::runtime_error(std::string(__func__) + ": writing descriptor master private key failed");
881 }
882 if (!batch.WriteDescriptor(spkm->GetID(), spkm->m_wallet_descriptor)) {
883 throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
884 }
885
886 // Set m_decryption_thoroughly_checked for encrypted wallets
887 if (spkm->m_storage.HasEncryptionKeys()) {
888 spkm->m_decryption_thoroughly_checked = true;
889 }
890
891 // TopUp
892 spkm->TopUpWithDB(batch);
893
894 spkm->m_storage.UnsetBlankWalletFlag(batch);
895 return spkm;
896}
897
899{
901
902 const auto old_can = CanGetAddresses();
903 m_wallet_descriptor.IncNext();
904 const auto new_can = CanGetAddresses();
905 if (old_can != new_can) {
907 }
908}
909
911{
913
914 const auto old_can = CanGetAddresses();
915 m_wallet_descriptor.DecNext();
916 const auto new_can = CanGetAddresses();
917 if (old_can != new_can) {
919 }
920}
921
923{
925
926 const auto old_can = CanGetAddresses();
927 m_wallet_descriptor.SetEnd(end);
928 const auto new_can = CanGetAddresses();
929 if (old_can != new_can) {
931 }
932}
933
935{
936 // Returns true if this descriptor supports getting new addresses. Conditions where we may be unable to fetch them (e.g. locked) are caught later
937 if (!CanGetAddresses()) {
938 return util::Error{_("No addresses available")};
939 }
940 {
942 assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
943 std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
945 if (type != *desc_addr_type) {
946 throw std::runtime_error(std::string(__func__) + ": Types are inconsistent. Stored type does not match type of newly generated address");
947 }
948
949 TopUp();
950
951 // Get the scriptPubKey from the descriptor
953 std::vector<CScript> scripts_temp;
954 if (m_wallet_descriptor.GetEnd() <= m_max_cached_index && !TopUp(1)) {
955 // We can't generate anymore keys
956 return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
957 }
958 if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.GetNext(), m_wallet_descriptor.cache, scripts_temp, out_keys)) {
959 // We can't generate anymore keys
960 return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
961 }
962
963 CTxDestination dest;
964 if (!ExtractDestination(scripts_temp[0], dest)) {
965 return util::Error{_("Error: Cannot extract destination from the generated scriptpubkey")}; // shouldn't happen
966 }
967 IncIndex();
969 return dest;
970 }
971}
972
974{
976 return m_map_script_pub_keys.contains(script);
977}
978
980{
982 if (!m_map_keys.empty()) {
983 return false;
984 }
985
986 bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
987 bool keyFail = false;
988 for (const auto& mi : m_map_crypted_keys) {
989 const CPubKey &pubkey = mi.second.first;
990 const std::vector<unsigned char> &crypted_secret = mi.second.second;
991 CKey key;
992 if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
993 keyFail = true;
994 break;
995 }
996 keyPass = true;
998 break;
999 }
1000 if (keyPass && keyFail) {
1001 LogWarning("The wallet is probably corrupted: Some keys decrypt but not all.");
1002 throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
1003 }
1004 if (keyFail || !keyPass) {
1005 return false;
1006 }
1008 return true;
1009}
1010
1012{
1014 if (!m_map_crypted_keys.empty()) {
1015 return false;
1016 }
1017
1019 for (const KeyMap::value_type& key_in : m_map_keys)
1020 {
1021 const CKey &key = key_in.second;
1022 CPubKey pubkey = key.GetPubKey();
1024 std::vector<unsigned char> crypted_secret;
1025 if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
1026 return false;
1027 }
1028 if (!batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret)) {
1029 return false;
1030 }
1031 crypted_keys[pubkey.GetID()] = make_pair(pubkey, std::move(crypted_secret));
1032 }
1033
1034 batch->RegisterTxnListener({
1035 .on_commit = [this, keys = std::move(crypted_keys)]() mutable {
1037 m_map_crypted_keys = std::move(keys);
1038 m_map_keys.clear();
1039 },
1040 .on_abort = [] {}});
1041 return true;
1042}
1043
1045{
1047 auto op_dest = GetNewDestination(type);
1048 index = m_wallet_descriptor.GetNext() - 1;
1049 return op_dest;
1050}
1051
1053{
1055 // Only return when the index was the most recent
1056 if (m_wallet_descriptor.GetNext() - 1 == index) {
1057 DecIndex();
1058 }
1060}
1061
1062std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
1063{
1066 KeyMap keys;
1067 for (const auto& key_pair : m_map_crypted_keys) {
1068 const CPubKey& pubkey = key_pair.second.first;
1069 const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
1070 CKey key;
1072 return DecryptKey(encryption_key, crypted_secret, pubkey, key);
1073 });
1074 keys[pubkey.GetID()] = key;
1075 }
1076 return keys;
1077 }
1078 return m_map_keys;
1079}
1080
1082{
1084 return m_map_keys.contains(keyid) || m_map_crypted_keys.contains(keyid);
1085}
1086
1087std::optional<CKey> DescriptorScriptPubKeyMan::GetKey(const CKeyID& keyid) const
1088{
1091 const auto& it = m_map_crypted_keys.find(keyid);
1092 if (it == m_map_crypted_keys.end()) {
1093 return std::nullopt;
1094 }
1095 const std::vector<unsigned char>& crypted_secret = it->second.second;
1096 CKey key;
1098 return DecryptKey(encryption_key, crypted_secret, it->second.first, key);
1099 }))) {
1100 return std::nullopt;
1101 }
1102 return key;
1103 }
1104 const auto& it = m_map_keys.find(keyid);
1105 if (it == m_map_keys.end()) {
1106 return std::nullopt;
1107 }
1108 return it->second;
1109}
1110
1112{
1114 if (!batch.TxnBegin()) return false;
1115 bool res = TopUpWithDB(batch, size);
1116 if (!batch.TxnCommit()) throw std::runtime_error(strprintf("Error during descriptors keypool top up. Cannot commit changes for wallet [%s]", m_storage.LogName()));
1117 return res;
1118}
1119
1121{
1123 std::set<CScript> new_spks;
1124 unsigned int target_size;
1125 if (size > 0) {
1126 target_size = size;
1127 } else {
1128 target_size = m_keypool_size;
1129 }
1130
1131 // Calculate the new range_end. next_index can be as high as 2^31-1 on an imported
1132 // descriptor and target_size is user controlled, so compute the end in a wider type.
1133 // The range is left unchanged if that end does not fit in the int32_t it is stored in.
1136 if (target_end <= std::numeric_limits<int32_t>::max()) {
1137 new_range_end = std::max(static_cast<int32_t>(target_end), m_wallet_descriptor.GetEnd());
1138 }
1139
1140 // If the descriptor is not ranged, we actually just want to fill the first cache item
1141 if (!m_wallet_descriptor.descriptor->IsRange()) {
1142 new_range_end = 1;
1143 }
1144
1146 provider.keys = GetKeys();
1147
1148 uint256 id = GetID();
1149 for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
1151 std::vector<CScript> scripts_temp;
1153 // Maybe we have a cached xpub and we can expand from the cache first
1154 if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1155 if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
1156 }
1157 // Add all of the scriptPubKeys to the scriptPubKey set
1158 new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1159 for (const CScript& script : scripts_temp) {
1161 }
1162 for (const auto& pk_pair : out_keys.pubkeys) {
1163 const CPubKey& pubkey = pk_pair.second;
1164 if (m_map_pubkeys.contains(pubkey)) {
1165 // We don't need to give an error here.
1166 // 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
1167 continue;
1168 }
1169 m_map_pubkeys[pubkey] = i;
1170 }
1171 // Merge and write the cache
1173 if (!batch.WriteDescriptorCacheItems(id, new_items)) {
1174 throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
1175 }
1177 }
1180
1181 // By this point, the cache size should be the size of the entire range
1183
1185 return true;
1186}
1187
1189{
1191 std::vector<WalletDestination> result;
1192 if (IsMine(script)) {
1194 if (index >= m_wallet_descriptor.GetNext()) {
1195 WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used", __func__, index);
1196 auto out_keys = std::make_unique<FlatSigningProvider>();
1197 std::vector<CScript> scripts_temp;
1198 while (index >= m_wallet_descriptor.GetNext()) {
1199 if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.GetNext(), m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
1200 throw std::runtime_error(std::string(__func__) + ": Unable to expand descriptor from cache");
1201 }
1202 CTxDestination dest;
1204 result.push_back({dest, std::nullopt});
1205 IncIndex();
1206 }
1207 }
1208 if (!TopUp()) {
1209 WalletLogPrintf("%s: Topping up keypool failed (locked wallet)", __func__);
1210 }
1211 }
1212
1213 return result;
1214}
1215
1217{
1220
1221 // Check if provided key already exists
1222 if (m_map_keys.contains(pubkey.GetID()) ||
1223 m_map_crypted_keys.contains(pubkey.GetID())) {
1224 return true;
1225 }
1226
1228 if (m_storage.IsLocked()) {
1229 return false;
1230 }
1231
1232 std::vector<unsigned char> crypted_secret;
1235 return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
1236 })) {
1237 return false;
1238 }
1239
1240 if (!batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret)) {
1241 return false;
1242 }
1243 m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, std::move(crypted_secret));
1244 } else {
1245 if (!batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey())) {
1246 return false;
1247 }
1248 m_map_keys[pubkey.GetID()] = key;
1249 }
1250 return true;
1251}
1252
1254{
1256 return m_wallet_descriptor.descriptor->IsRange();
1257}
1258
1260{
1261 // We can only give out addresses from descriptors that are single type (not combo), ranged,
1262 // and either have cached keys or can generate more keys (ignoring encryption)
1264 return m_wallet_descriptor.descriptor->IsSingleType() &&
1265 m_wallet_descriptor.descriptor->IsRange() &&
1266 (HavePrivateKeys() || m_wallet_descriptor.GetNext() < m_wallet_descriptor.GetEnd() || m_wallet_descriptor.descriptor->CanSelfExpand());
1267}
1268
1270{
1272 return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
1273}
1274
1276{
1278 return !m_map_crypted_keys.empty();
1279}
1280
1282{
1284 return m_wallet_descriptor.GetEnd() - m_wallet_descriptor.GetNext();
1285}
1286
1288{
1290 return m_wallet_descriptor.creation_time;
1291}
1292
1293std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
1294{
1296
1297 // Find the index of the script
1298 auto it = m_map_script_pub_keys.find(script);
1299 if (it == m_map_script_pub_keys.end()) {
1300 return nullptr;
1301 }
1302 int32_t index = it->second;
1303
1304 return GetSigningProvider(index, include_private);
1305}
1306
1307std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
1308{
1310
1311 // Find index of the pubkey
1312 auto it = m_map_pubkeys.find(pubkey);
1313 if (it == m_map_pubkeys.end()) {
1314 return nullptr;
1315 }
1316 int32_t index = it->second;
1317
1318 // Always try to get the signing provider with private keys. This function should only be called during signing anyways
1319 std::unique_ptr<FlatSigningProvider> out = GetSigningProvider(index, true);
1320 if (!out->HaveKey(pubkey.GetID())) {
1321 return nullptr;
1322 }
1323 return out;
1324}
1325
1326std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
1327{
1329
1330 std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
1331
1332 // Fetch SigningProvider from cache to avoid re-deriving
1333 auto it = m_map_signing_providers.find(index);
1334 if (it != m_map_signing_providers.end()) {
1335 out_keys->Merge(FlatSigningProvider{it->second});
1336 } else {
1337 // Get the scripts, keys, and key origins for this script
1338 std::vector<CScript> scripts_temp;
1339 if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
1340
1341 // Cache SigningProvider so we don't need to re-derive if we need this SigningProvider again
1343 }
1344
1348 m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
1349
1350 // Always include musig_secnonces as this descriptor may have a participant private key
1351 // but not a musig() descriptor
1352 out_keys->musig2_secnonces = &m_musig2_secnonces;
1353 }
1354
1355 return out_keys;
1356}
1357
1358std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
1359{
1360 return GetSigningProvider(script, false);
1361}
1362
1364{
1365 return IsMine(script);
1366}
1367
1368bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
1369{
1370 std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1371 for (const auto& coin_pair : coins) {
1372 std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
1373 if (!coin_keys) {
1374 continue;
1375 }
1376 keys->Merge(std::move(*coin_keys));
1377 }
1378
1379 return ::SignTransaction(tx, keys.get(), coins, {.sighash_type = sighash}, input_errors);
1380}
1381
1382SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
1383{
1384 std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
1385 if (!keys) {
1387 }
1388
1389 CKey key;
1390 if (!keys->GetKey(ToKeyID(pkhash), key)) {
1392 }
1393
1394 if (!MessageSign(key, message, str_sig)) {
1396 }
1397 return SigningResult::OK;
1398}
1399
1401{
1402 if (n_signed) {
1403 *n_signed = 0;
1404 }
1405 for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
1406 PSBTInput& input = psbtx.inputs.at(i);
1407
1408 if (PSBTInputSigned(input)) {
1409 continue;
1410 }
1411
1412 // Get the scriptPubKey to know which SigningProvider to use
1414 if (!input.witness_utxo.IsNull()) {
1416 } else if (input.non_witness_utxo) {
1417 if (input.prev_out >= input.non_witness_utxo->vout.size()) {
1418 return PSBTError::MISSING_INPUTS;
1419 }
1420 script = input.non_witness_utxo->vout[input.prev_out].scriptPubKey;
1421 } else {
1422 // There's no UTXO so we can just skip this now
1423 continue;
1424 }
1425
1426 std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1427 std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, /*include_private=*/options.sign);
1428 if (script_keys) {
1429 keys->Merge(std::move(*script_keys));
1430 } else {
1431 // Maybe there are pubkeys listed that we can sign for
1432 std::vector<CPubKey> pubkeys;
1433 pubkeys.reserve(input.hd_keypaths.size() + 2);
1434
1435 // ECDSA Pubkeys
1436 for (const auto& [pk, _] : input.hd_keypaths) {
1437 pubkeys.push_back(pk);
1438 }
1439
1440 // Taproot output pubkey
1441 std::vector<std::vector<unsigned char>> sols;
1443 sols[0].insert(sols[0].begin(), 0x02);
1444 pubkeys.emplace_back(sols[0]);
1445 sols[0][0] = 0x03;
1446 pubkeys.emplace_back(sols[0]);
1447 }
1448
1449 // Taproot pubkeys
1450 for (const auto& pk_pair : input.m_tap_bip32_paths) {
1451 const XOnlyPubKey& pubkey = pk_pair.first;
1452 for (unsigned char prefix : {0x02, 0x03}) {
1453 unsigned char b[33] = {prefix};
1454 std::copy(pubkey.begin(), pubkey.end(), b + 1);
1456 fullpubkey.Set(b, b + 33);
1457 pubkeys.push_back(fullpubkey);
1458 }
1459 }
1460
1461 for (const auto& pubkey : pubkeys) {
1462 std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
1463 if (pk_keys) {
1464 keys->Merge(std::move(*pk_keys));
1465 }
1466 }
1467 }
1468
1469 const auto sign_result = SignPSBTInput(HidingSigningProvider(keys.get(), /*hide_secret=*/!options.sign, /*hide_origin=*/!options.bip32_derivs), psbtx, i, &txdata, options, /*out_sigdata=*/nullptr);
1470 if (!sign_result.has_value() && sign_result.error() != PSBTError::INCOMPLETE) {
1471 return sign_result.error();
1472 }
1473
1474 bool signed_one = PSBTInputSigned(input);
1475 if (n_signed && (signed_one || !options.sign)) {
1476 // If sign is false, we assume that we _could_ sign if we get here. This
1477 // will never have false negatives; it is hard to tell under what i
1478 // circumstances it could have false positives.
1479 (*n_signed)++;
1480 }
1481 }
1482
1483 // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
1484 for (unsigned int i = 0; i < psbtx.outputs.size(); ++i) {
1485 std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.outputs.at(i).script);
1486 if (!keys) {
1487 continue;
1488 }
1489 UpdatePSBTOutput(HidingSigningProvider(keys.get(), /*hide_secret=*/true, /*hide_origin=*/!options.bip32_derivs), psbtx, i);
1490 }
1491
1492 return {};
1493}
1494
1495std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
1496{
1497 std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
1498 if (provider) {
1501 if (provider->GetKeyOrigin(key_id, orig)) {
1503 std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
1504 meta->key_origin = orig;
1505 meta->has_key_origin = true;
1506 meta->nCreateTime = m_wallet_descriptor.creation_time;
1507 return meta;
1508 }
1509 }
1510 return nullptr;
1511}
1512
1514{
1515 return m_id;
1516}
1517
1519{
1521 std::set<CScript> new_spks;
1522 for (int32_t i = m_wallet_descriptor.GetStart(); i < m_wallet_descriptor.GetEnd(); ++i) {
1524 std::vector<CScript> scripts_temp;
1525 if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1526 throw std::runtime_error("Error: Unable to expand wallet descriptor from cache");
1527 }
1528 // Add all of the scriptPubKeys to the scriptPubKey set
1529 new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1530 for (const CScript& script : scripts_temp) {
1531 if (m_map_script_pub_keys.contains(script)) {
1532 throw std::runtime_error(strprintf("Error: Already loaded script at index %d as being at index %d", i, m_map_script_pub_keys[script]));
1533 }
1535 }
1536 for (const auto& pk_pair : out_keys.pubkeys) {
1537 const CPubKey& pubkey = pk_pair.second;
1538 if (m_map_pubkeys.contains(pubkey)) {
1539 // We don't need to give an error here.
1540 // 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
1541 continue;
1542 }
1543 m_map_pubkeys[pubkey] = i;
1544 }
1546 }
1547 // Make sure the wallet knows about our new spks
1549}
1550
1552{
1554 return m_wallet_descriptor.IsCanonicallyEquivalent(desc);
1555}
1556
1558{
1561 if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
1562 throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
1563 }
1564}
1565
1570
1571std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
1572{
1573 return GetScriptPubKeys(0);
1574}
1575
1576std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys(int32_t minimum_index) const
1577{
1579 std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
1580 script_pub_keys.reserve(m_map_script_pub_keys.size());
1581
1582 for (auto const& [script_pub_key, index] : m_map_script_pub_keys) {
1583 if (index >= minimum_index) script_pub_keys.insert(script_pub_key);
1584 }
1585 return script_pub_keys;
1586}
1587
1592
1593bool DescriptorScriptPubKeyMan::GetDescriptorString(std::string& out, const bool priv) const
1594{
1596
1598 provider.keys = GetKeys();
1599
1600 if (priv) {
1601 // For the private version, always return the master key to avoid
1602 // exposing child private keys. The risk implications of exposing child
1603 // private keys together with the parent xpub may be non-obvious for users.
1604 return m_wallet_descriptor.descriptor->ToPrivateString(provider, out);
1605 }
1606
1607 return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
1608}
1609
1611{
1614 return;
1615 }
1616
1617 // Skip if we have the last hardened xpub cache
1618 if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
1619 return;
1620 }
1621
1622 // Expand the descriptor
1624 provider.keys = GetKeys();
1626 std::vector<CScript> scripts_temp;
1628 if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
1629 throw std::runtime_error("Unable to expand descriptor");
1630 }
1631
1632 // Cache the last hardened xpubs
1635 throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
1636 }
1637}
1638
1640{
1642 std::string error;
1643 if (!CanUpdateToWalletDescriptor(descriptor, error)) {
1644 return util::Error{Untranslated(std::move(error))};
1645 }
1646
1648 m_map_script_pub_keys.clear();
1649 m_max_cached_index = -1;
1650 m_wallet_descriptor.UpdateFrom(descriptor);
1651
1655 return {};
1656}
1657
1659{
1661 // Add the private keys to the descriptor
1662 for (const auto& entry : signing_provider.keys) {
1663 const CKey& key = entry.second;
1664 if (!AddDescriptorKeyWithDB(batch, key, key.GetPubKey())) {
1665 throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
1666 }
1667 }
1668
1669 // Top up key pool, to generate scriptPubKeys
1670 if (!TopUpWithDB(batch)) {
1671 throw std::runtime_error("Could not top up scriptPubKeys");
1672 }
1673}
1674
1676{
1678 if (!HasWalletDescriptor(descriptor)) {
1679 error = "can only update matching descriptor";
1680 return false;
1681 }
1682
1683 if (!descriptor.descriptor->IsRange()) {
1684 // Skip range check for non-range descriptors
1685 return true;
1686 }
1687
1688 if (descriptor.GetStart() > m_wallet_descriptor.GetStart() ||
1689 descriptor.GetEnd() < m_wallet_descriptor.GetEnd()) {
1690 // Use inclusive range for error
1691 error = strprintf("new range must include current range = [%d,%d]",
1692 m_wallet_descriptor.GetStart(),
1693 m_wallet_descriptor.GetEnd() - 1);
1694 return false;
1695 }
1696
1697 return true;
1698}
1699} // 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
#define CHECK_NONFATAL(condition)
Identity function.
Definition check.h:115
#define Assert(val)
Identity function.
Definition check.h:119
#define STR_INTERNAL_BUG(msg)
Definition check.h:100
#define Assume(val)
Assume is the identity function.
Definition check.h:131
An encapsulated private key.
Definition key.h:46
const std::byte * begin() const
Definition key.h:130
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:131
A reference to a CKey: the Hash160 of its serialized public key.
Definition pubkey.h:29
An encapsulated public key.
Definition pubkey.h:43
bool IsCompressed() const
Check whether this is a compressed public key.
Definition pubkey.h:209
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition pubkey.h:169
uint256 GetHash() const
Get the 256-bit hash of this public key.
Definition pubkey.h:175
void Set(const T pbegin, const T pend)
Initialize a public key using begin/end iterators to byte data.
Definition pubkey.h:98
Serialized script, used inside transaction inputs and outputs.
Definition script.h:406
A reference to a CScript: the Hash160 of its serialization.
Definition script.h:597
CScript scriptPubKey
bool IsNull() const
Cache for single descriptor's derived extended pubkeys.
Definition descriptor.h:30
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 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 HaveKey(const CKeyID &address) const override
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
const unsigned char * end() const
Definition pubkey.h:305
const unsigned char * begin() const
Definition pubkey.h:304
constexpr bool IsNull() const
Definition uint256.h:50
160-bit opaque blob.
Definition uint256.h:184
256-bit opaque blob.
Definition uint256.h:196
static constexpr int VERSION_HD_CHAIN_SPLIT
Definition walletdb.h:106
CKeyID seed_id
seed hash160
Definition walletdb.h:103
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
Encrypt keys and write them to a batch with an active transaction. Update in-memory keys only after t...
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)
void WalletLogPrintf(util::log::FormatString< sizeof...(Params)> wallet_fmt, const Params &... params) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
btcsignals::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
btcsignals::signal< void(const ScriptPubKeyMan *spkm, int64_t new_birth_time)> NotifyFirstKeyTimeChanged
Birth time changed.
WalletStorage & m_storage
Access to the wallet database.
Definition walletdb.h:199
bool WriteDescriptor(const uint256 &desc_id, const WalletDescriptor &descriptor)
Definition walletdb.cpp:253
bool WriteDescriptorCacheItems(const uint256 &desc_id, const DescriptorCache &cache)
Definition walletdb.cpp:279
bool TxnBegin()
Begin a new transaction.
bool TxnCommit()
Commit current transaction.
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:145
void RegisterTxnListener(DbTxnListener l)
Registers db txn callback functions.
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< unsigned char > &secret)
Definition walletdb.cpp:237
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
Definition walletdb.cpp:229
Descriptor with some wallet metadata.
Definition walletutil.h:86
int32_t GetStart() const
Definition walletutil.h:101
int32_t GetEnd() const
Definition walletutil.h:103
const std::shared_ptr< const Descriptor > descriptor
Definition walletutil.h:97
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().
static UniValue Parse(std::string_view raw, ParamFormat format=ParamFormat::JSON)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition client.cpp:411
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:292
std::string EncodeExtPubKey(const CExtPubKey &key)
Definition key_io.cpp:259
#define LogWarning(...)
Definition log.h:137
#define LogError(...)
Definition log.h:138
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:66
std::vector< unsigned char > valtype
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition crypter.h:63
std::map< CKeyID, std::pair< CPubKey, std::vector< unsigned char > > > CryptedKeyMap
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)
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
std::map< CKeyID, CKey > KeyMap
WalletDescriptor GenerateWalletDescriptor(const CExtPubKey &master_key, const OutputType &addr_type, bool internal)
is a home for public enum and struct type definitions that are used internally by node code,...
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
const char * prefix
Definition rest.cpp:1197
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
@ 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:750
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition sign.cpp:1008
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
@ OK
No error.
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
@ WITNESS_UNKNOWN
Only for Witness versions not already defined above.
@ ANCHOR
anyone can spend script
@ WITNESS_V0_SCRIPTHASH
@ NULL_DATA
unspendable OP_RETURN script that carries data
@ WITNESS_V0_KEYHASH
unsigned char * UCharCast(char *c)
Definition span.h:95
Definition key.h:238
CExtPubKey Neuter() const
Definition key.cpp:394
CKey key
Definition key.h:243
void SetSeed(std::span< const std::byte > seed)
Definition key.cpp:381
A mutable version of CTransaction.
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
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
assert(!tx.IsCoinBase())