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