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 ISMINE_NO;
206 case IsMineResult::WATCH_ONLY:
207 return ISMINE_WATCH_ONLY;
208 case IsMineResult::SPENDABLE:
209 return ISMINE_SPENDABLE;
210 }
211 assert(false);
212}
213
215{
216 {
218 assert(mapKeys.empty());
219
220 bool keyPass = mapCryptedKeys.empty(); // Always pass when there are no encrypted keys
221 bool keyFail = false;
222 CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
224 for (; mi != mapCryptedKeys.end(); ++mi)
225 {
226 const CPubKey &vchPubKey = (*mi).second.first;
227 const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
228 CKey key;
229 if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
230 {
231 keyFail = true;
232 break;
233 }
234 keyPass = true;
236 break;
237 else {
238 // Rewrite these encrypted keys with checksums
239 batch.WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
240 }
241 }
242 if (keyPass && keyFail)
243 {
244 LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
245 throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
246 }
247 if (keyFail || !keyPass)
248 return false;
250 }
251 return true;
252}
253
254std::unique_ptr<SigningProvider> LegacyDataSPKM::GetSolvingProvider(const CScript& script) const
255{
256 return std::make_unique<LegacySigningProvider>(*this);
257}
258
260{
261 IsMineResult ismine = LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
262 if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
263 // If ismine, it means we recognize keys or script ids in the script, or
264 // are watching the script itself, and we can at least provide metadata
265 // or solving information, even if not able to sign fully.
266 return true;
267 } else {
268 // If, given the stuff in sigdata, we could make a valid signature, then we can provide for this script
270 if (!sigdata.signatures.empty()) {
271 // If we could make signatures, make sure we have a private key to actually make a signature
272 bool has_privkeys = false;
273 for (const auto& key_sig_pair : sigdata.signatures) {
274 has_privkeys |= HaveKey(key_sig_pair.first);
275 }
276 return has_privkeys;
277 }
278 return false;
279 }
280}
281
282bool LegacyDataSPKM::LoadKey(const CKey& key, const CPubKey &pubkey)
283{
284 return AddKeyPubKeyInner(key, pubkey);
285}
286
287bool LegacyDataSPKM::LoadCScript(const CScript& redeemScript)
288{
289 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
290 * that never can be redeemed. However, old wallets may still contain
291 * these. Do not add them to the wallet and warn. */
292 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
293 {
294 std::string strAddr = EncodeDestination(ScriptHash(redeemScript));
295 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);
296 return true;
297 }
298
299 return FillableSigningProvider::AddCScript(redeemScript);
300}
301
303{
305 mapKeyMetadata[keyID] = meta;
306}
307
309{
311 m_script_metadata[script_id] = meta;
312}
313
314bool LegacyDataSPKM::AddKeyPubKeyInner(const CKey& key, const CPubKey& pubkey)
315{
317 return FillableSigningProvider::AddKeyPubKey(key, pubkey);
318}
319
320bool LegacyDataSPKM::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid)
321{
322 // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
323 if (!checksum_valid) {
325 }
326
327 return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
328}
329
330bool LegacyDataSPKM::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
331{
333 assert(mapKeys.empty());
334
335 mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
337 return true;
338}
339
341{
343 return setWatchOnly.count(dest) > 0;
344}
345
347{
348 return AddWatchOnlyInMem(dest);
349}
350
351static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
352{
353 std::vector<std::vector<unsigned char>> solutions;
354 return Solver(dest, solutions) == TxoutType::PUBKEY &&
355 (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
356}
357
359{
361 setWatchOnly.insert(dest);
362 CPubKey pubKey;
363 if (ExtractPubKey(dest, pubKey)) {
364 mapWatchKeys[pubKey.GetID()] = pubKey;
366 }
367 return true;
368}
369
371{
373 m_hd_chain = chain;
374}
375
377{
379 assert(!chain.seed_id.IsNull());
380 m_inactive_hd_chains[chain.seed_id] = chain;
381}
382
383bool LegacyDataSPKM::HaveKey(const CKeyID &address) const
384{
387 return FillableSigningProvider::HaveKey(address);
388 }
389 return mapCryptedKeys.count(address) > 0;
390}
391
392bool LegacyDataSPKM::GetKey(const CKeyID &address, CKey& keyOut) const
393{
396 return FillableSigningProvider::GetKey(address, keyOut);
397 }
398
399 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
400 if (mi != mapCryptedKeys.end())
401 {
402 const CPubKey &vchPubKey = (*mi).second.first;
403 const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
404 return m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
405 return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey, keyOut);
406 });
407 }
408 return false;
409}
410
411bool LegacyDataSPKM::GetKeyOrigin(const CKeyID& keyID, KeyOriginInfo& info) const
412{
413 CKeyMetadata meta;
414 {
416 auto it = mapKeyMetadata.find(keyID);
417 if (it == mapKeyMetadata.end()) {
418 return false;
419 }
420 meta = it->second;
421 }
422 if (meta.has_key_origin) {
423 std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4, info.fingerprint);
424 info.path = meta.key_origin.path;
425 } else { // Single pubkeys get the master fingerprint of themselves
426 std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
427 }
428 return true;
429}
430
431bool LegacyDataSPKM::GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
432{
434 WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
435 if (it != mapWatchKeys.end()) {
436 pubkey_out = it->second;
437 return true;
438 }
439 return false;
440}
441
442bool LegacyDataSPKM::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
443{
446 if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
447 return GetWatchPubKey(address, vchPubKeyOut);
448 }
449 return true;
450 }
451
452 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
453 if (mi != mapCryptedKeys.end())
454 {
455 vchPubKeyOut = (*mi).second.first;
456 return true;
457 }
458 // Check for watch-only pubkeys
459 return GetWatchPubKey(address, vchPubKeyOut);
460}
461
462std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetCandidateScriptPubKeys() const
463{
465 std::unordered_set<CScript, SaltedSipHasher> candidate_spks;
466
467 // For every private key in the wallet, there should be a P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH
468 const auto& add_pubkey = [&candidate_spks](const CPubKey& pub) -> void {
469 candidate_spks.insert(GetScriptForRawPubKey(pub));
470 candidate_spks.insert(GetScriptForDestination(PKHash(pub)));
471
473 candidate_spks.insert(wpkh);
474 candidate_spks.insert(GetScriptForDestination(ScriptHash(wpkh)));
475 };
476 for (const auto& [_, key] : mapKeys) {
477 add_pubkey(key.GetPubKey());
478 }
479 for (const auto& [_, ckeypair] : mapCryptedKeys) {
480 add_pubkey(ckeypair.first);
481 }
482
483 // mapScripts contains all redeemScripts and witnessScripts. Therefore each script in it has
484 // itself, P2SH, P2WSH, and P2SH-P2WSH as a candidate.
485 // Invalid scripts such as P2SH-P2SH and P2WSH-P2SH, among others, will be added as candidates.
486 // Callers of this function will need to remove such scripts.
487 const auto& add_script = [&candidate_spks](const CScript& script) -> void {
488 candidate_spks.insert(script);
489 candidate_spks.insert(GetScriptForDestination(ScriptHash(script)));
490
492 candidate_spks.insert(wsh);
493 candidate_spks.insert(GetScriptForDestination(ScriptHash(wsh)));
494 };
495 for (const auto& [_, script] : mapScripts) {
496 add_script(script);
497 }
498
499 // Although setWatchOnly should only contain output scripts, we will also include each script's
500 // P2SH, P2WSH, and P2SH-P2WSH as a precaution.
501 for (const auto& script : setWatchOnly) {
502 add_script(script);
503 }
504
505 return candidate_spks;
506}
507
508std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetScriptPubKeys() const
509{
510 // Run IsMine() on each candidate output script. Any script that is not ISMINE_NO is an output
511 // script to return.
512 // This both filters out things that are not watched by the wallet, and things that are invalid.
513 std::unordered_set<CScript, SaltedSipHasher> spks;
514 for (const CScript& script : GetCandidateScriptPubKeys()) {
515 if (IsMine(script) != ISMINE_NO) {
516 spks.insert(script);
517 }
518 }
519
520 return spks;
521}
522
523std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetNotMineScriptPubKeys() const
524{
526 std::unordered_set<CScript, SaltedSipHasher> spks;
527 for (const CScript& script : setWatchOnly) {
528 if (IsMine(script) == ISMINE_NO) spks.insert(script);
529 }
530 return spks;
531}
532
533std::optional<MigrationData> LegacyDataSPKM::MigrateToDescriptor()
534{
536 if (m_storage.IsLocked()) {
537 return std::nullopt;
538 }
539
541
542 std::unordered_set<CScript, SaltedSipHasher> spks{GetScriptPubKeys()};
543
544 // Get all key ids
545 std::set<CKeyID> keyids;
546 for (const auto& key_pair : mapKeys) {
547 keyids.insert(key_pair.first);
548 }
549 for (const auto& key_pair : mapCryptedKeys) {
550 keyids.insert(key_pair.first);
551 }
552
553 // Get key metadata and figure out which keys don't have a seed
554 // Note that we do not ignore the seeds themselves because they are considered IsMine!
555 for (auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
556 const CKeyID& keyid = *keyid_it;
557 const auto& it = mapKeyMetadata.find(keyid);
558 if (it != mapKeyMetadata.end()) {
559 const CKeyMetadata& meta = it->second;
560 if (meta.hdKeypath == "s" || meta.hdKeypath == "m") {
561 keyid_it++;
562 continue;
563 }
564 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)) {
565 keyid_it = keyids.erase(keyid_it);
566 continue;
567 }
568 }
569 keyid_it++;
570 }
571
573 if (!batch.TxnBegin()) {
574 LogPrintf("Error generating descriptors for migration, cannot initialize db transaction\n");
575 return std::nullopt;
576 }
577
578 // keyids is now all non-HD keys. Each key will have its own combo descriptor
579 for (const CKeyID& keyid : keyids) {
580 CKey key;
581 if (!GetKey(keyid, key)) {
582 assert(false);
583 }
584
585 // Get birthdate from key meta
586 uint64_t creation_time = 0;
587 const auto& it = mapKeyMetadata.find(keyid);
588 if (it != mapKeyMetadata.end()) {
589 creation_time = it->second.nCreateTime;
590 }
591
592 // Get the key origin
593 // Maybe this doesn't matter because floating keys here shouldn't have origins
594 KeyOriginInfo info;
595 bool has_info = GetKeyOrigin(keyid, info);
596 std::string origin_str = has_info ? "[" + HexStr(info.fingerprint) + FormatHDKeypath(info.path) + "]" : "";
597
598 // Construct the combo descriptor
599 std::string desc_str = "combo(" + origin_str + HexStr(key.GetPubKey()) + ")";
601 std::string error;
602 std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, error, false);
603 CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
604 WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
605
606 // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
607 auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
608 WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, key, key.GetPubKey()));
609 desc_spk_man->TopUpWithDB(batch);
610 auto desc_spks = desc_spk_man->GetScriptPubKeys();
611
612 // Remove the scriptPubKeys from our current set
613 for (const CScript& spk : desc_spks) {
614 size_t erased = spks.erase(spk);
615 assert(erased == 1);
617 }
618
619 out.desc_spkms.push_back(std::move(desc_spk_man));
620 }
621
622 // Handle HD keys by using the CHDChains
623 std::vector<CHDChain> chains;
624 chains.push_back(m_hd_chain);
625 for (const auto& chain_pair : m_inactive_hd_chains) {
626 chains.push_back(chain_pair.second);
627 }
628 for (const CHDChain& chain : chains) {
629 for (int i = 0; i < 2; ++i) {
630 // Skip if doing internal chain and split chain is not supported
631 if (chain.seed_id.IsNull() || (i == 1 && !m_storage.CanSupportFeature(FEATURE_HD_SPLIT))) {
632 continue;
633 }
634 // Get the master xprv
635 CKey seed_key;
636 if (!GetKey(chain.seed_id, seed_key)) {
637 assert(false);
638 }
639 CExtKey master_key;
640 master_key.SetSeed(seed_key);
641
642 // Make the combo descriptor
643 std::string xpub = EncodeExtPubKey(master_key.Neuter());
644 std::string desc_str = "combo(" + xpub + "/0h/" + ToString(i) + "h/*h)";
646 std::string error;
647 std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, error, false);
648 CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
649 uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
650 WalletDescriptor w_desc(std::move(descs.at(0)), 0, 0, chain_counter, 0);
651
652 // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
653 auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
654 WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey()));
655 desc_spk_man->TopUpWithDB(batch);
656 auto desc_spks = desc_spk_man->GetScriptPubKeys();
657
658 // Remove the scriptPubKeys from our current set
659 for (const CScript& spk : desc_spks) {
660 size_t erased = spks.erase(spk);
661 assert(erased == 1);
663 }
664
665 out.desc_spkms.push_back(std::move(desc_spk_man));
666 }
667 }
668 // Add the current master seed to the migration data
669 if (!m_hd_chain.seed_id.IsNull()) {
670 CKey seed_key;
671 if (!GetKey(m_hd_chain.seed_id, seed_key)) {
672 assert(false);
673 }
674 out.master_key.SetSeed(seed_key);
675 }
676
677 // Handle the rest of the scriptPubKeys which must be imports and may not have all info
678 for (auto it = spks.begin(); it != spks.end();) {
679 const CScript& spk = *it;
680
681 // Get birthdate from script meta
682 uint64_t creation_time = 0;
683 const auto& mit = m_script_metadata.find(CScriptID(spk));
684 if (mit != m_script_metadata.end()) {
685 creation_time = mit->second.nCreateTime;
686 }
687
688 // InferDescriptor as that will get us all the solving info if it is there
689 std::unique_ptr<Descriptor> desc = InferDescriptor(spk, *GetSolvingProvider(spk));
690
691 // Past bugs in InferDescriptor have caused it to create descriptors which cannot be re-parsed.
692 // Re-parse the descriptors to detect that, and skip any that do not parse.
693 {
694 std::string desc_str = desc->ToString();
695 FlatSigningProvider parsed_keys;
696 std::string parse_error;
697 std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error);
698 if (parsed_descs.empty()) {
699 // Remove this scriptPubKey from the set
700 it = spks.erase(it);
701 continue;
702 }
703 }
704
705 // Get the private keys for this descriptor
706 std::vector<CScript> scripts;
708 if (!desc->Expand(0, DUMMY_SIGNING_PROVIDER, scripts, keys)) {
709 assert(false);
710 }
711 std::set<CKeyID> privkeyids;
712 for (const auto& key_orig_pair : keys.origins) {
713 privkeyids.insert(key_orig_pair.first);
714 }
715
716 std::vector<CScript> desc_spks;
717
718 // Make the descriptor string with private keys
719 std::string desc_str;
720 bool watchonly = !desc->ToPrivateString(*this, desc_str);
722 out.watch_descs.emplace_back(desc->ToString(), creation_time);
723
724 // Get the scriptPubKeys without writing this to the wallet
725 FlatSigningProvider provider;
726 desc->Expand(0, provider, desc_spks, provider);
727 } else {
728 // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
729 WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
730 auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
731 for (const auto& keyid : privkeyids) {
732 CKey key;
733 if (!GetKey(keyid, key)) {
734 continue;
735 }
736 WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, key, key.GetPubKey()));
737 }
738 desc_spk_man->TopUpWithDB(batch);
739 auto desc_spks_set = desc_spk_man->GetScriptPubKeys();
740 desc_spks.insert(desc_spks.end(), desc_spks_set.begin(), desc_spks_set.end());
741
742 out.desc_spkms.push_back(std::move(desc_spk_man));
743 }
744
745 // Remove the scriptPubKeys from our current set
746 for (const CScript& desc_spk : desc_spks) {
747 auto del_it = spks.find(desc_spk);
748 assert(del_it != spks.end());
749 assert(IsMine(desc_spk) != ISMINE_NO);
750 it = spks.erase(del_it);
751 }
752 }
753
754 // Make sure that we have accounted for all scriptPubKeys
755 if (!Assume(spks.empty())) {
756 LogPrintf("%s\n", STR_INTERNAL_BUG("Error: Some output scripts were not migrated.\n"));
757 return std::nullopt;
758 }
759
760 // Legacy wallets can also contain scripts whose P2SH, P2WSH, or P2SH-P2WSH it is not watching for
761 // but can provide script data to a PSBT spending them. These "solvable" output scripts will need to
762 // be put into the separate "solvables" wallet.
763 // These can be detected by going through the entire candidate output scripts, finding the ISMINE_NO scripts,
764 // and checking CanProvide() which will dummy sign.
765 for (const CScript& script : GetCandidateScriptPubKeys()) {
766 // Since we only care about P2SH, P2WSH, and P2SH-P2WSH, filter out any scripts that are not those
767 if (!script.IsPayToScriptHash() && !script.IsPayToWitnessScriptHash()) {
768 continue;
769 }
770 if (IsMine(script) != ISMINE_NO) {
771 continue;
772 }
773 SignatureData dummy_sigdata;
774 if (!CanProvide(script, dummy_sigdata)) {
775 continue;
776 }
777
778 // Get birthdate from script meta
779 uint64_t creation_time = 0;
780 const auto& it = m_script_metadata.find(CScriptID(script));
781 if (it != m_script_metadata.end()) {
782 creation_time = it->second.nCreateTime;
783 }
784
785 // InferDescriptor as that will get us all the solving info if it is there
786 std::unique_ptr<Descriptor> desc = InferDescriptor(script, *GetSolvingProvider(script));
787 if (!desc->IsSolvable()) {
788 // The wallet was able to provide some information, but not enough to make a descriptor that actually
789 // contains anything useful. This is probably because the script itself is actually unsignable (e.g. P2WSH-P2WSH).
790 continue;
791 }
792
793 // Past bugs in InferDescriptor have caused it to create descriptors which cannot be re-parsed
794 // Re-parse the descriptors to detect that, and skip any that do not parse.
795 {
796 std::string desc_str = desc->ToString();
797 FlatSigningProvider parsed_keys;
798 std::string parse_error;
799 std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error, false);
800 if (parsed_descs.empty()) {
801 continue;
802 }
803 }
804
805 out.solvable_descs.emplace_back(desc->ToString(), creation_time);
806 }
807
808 // Finalize transaction
809 if (!batch.TxnCommit()) {
810 LogPrintf("Error generating descriptors for migration, cannot commit db transaction\n");
811 return std::nullopt;
812 }
813
814 return out;
815}
816
818{
821}
822
824{
825 // Returns true if this descriptor supports getting new addresses. Conditions where we may be unable to fetch them (e.g. locked) are caught later
826 if (!CanGetAddresses()) {
827 return util::Error{_("No addresses available")};
828 }
829 {
831 assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
832 std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
833 assert(desc_addr_type);
834 if (type != *desc_addr_type) {
835 throw std::runtime_error(std::string(__func__) + ": Types are inconsistent. Stored type does not match type of newly generated address");
836 }
837
838 TopUp();
839
840 // Get the scriptPubKey from the descriptor
841 FlatSigningProvider out_keys;
842 std::vector<CScript> scripts_temp;
843 if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
844 // We can't generate anymore keys
845 return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
846 }
847 if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
848 // We can't generate anymore keys
849 return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
850 }
851
852 CTxDestination dest;
853 if (!ExtractDestination(scripts_temp[0], dest)) {
854 return util::Error{_("Error: Cannot extract destination from the generated scriptpubkey")}; // shouldn't happen
855 }
856 m_wallet_descriptor.next_index++;
857 WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
858 return dest;
859 }
860}
861
863{
865 if (m_map_script_pub_keys.count(script) > 0) {
866 return ISMINE_SPENDABLE;
867 }
868 return ISMINE_NO;
869}
870
872{
874 if (!m_map_keys.empty()) {
875 return false;
876 }
877
878 bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
879 bool keyFail = false;
880 for (const auto& mi : m_map_crypted_keys) {
881 const CPubKey &pubkey = mi.second.first;
882 const std::vector<unsigned char> &crypted_secret = mi.second.second;
883 CKey key;
884 if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
885 keyFail = true;
886 break;
887 }
888 keyPass = true;
890 break;
891 }
892 if (keyPass && keyFail) {
893 LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
894 throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
895 }
896 if (keyFail || !keyPass) {
897 return false;
898 }
900 return true;
901}
902
904{
906 if (!m_map_crypted_keys.empty()) {
907 return false;
908 }
909
910 for (const KeyMap::value_type& key_in : m_map_keys)
911 {
912 const CKey &key = key_in.second;
913 CPubKey pubkey = key.GetPubKey();
914 CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
915 std::vector<unsigned char> crypted_secret;
916 if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
917 return false;
918 }
919 m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
920 batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
921 }
922 m_map_keys.clear();
923 return true;
924}
925
927{
929 auto op_dest = GetNewDestination(type);
930 index = m_wallet_descriptor.next_index - 1;
931 return op_dest;
932}
933
934void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
935{
937 // Only return when the index was the most recent
938 if (m_wallet_descriptor.next_index - 1 == index) {
939 m_wallet_descriptor.next_index--;
940 }
941 WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
943}
944
945std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
946{
949 KeyMap keys;
950 for (const auto& key_pair : m_map_crypted_keys) {
951 const CPubKey& pubkey = key_pair.second.first;
952 const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
953 CKey key;
954 m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
955 return DecryptKey(encryption_key, crypted_secret, pubkey, key);
956 });
957 keys[pubkey.GetID()] = key;
958 }
959 return keys;
960 }
961 return m_map_keys;
962}
963
965{
967 return m_map_keys.contains(keyid) || m_map_crypted_keys.contains(keyid);
968}
969
970std::optional<CKey> DescriptorScriptPubKeyMan::GetKey(const CKeyID& keyid) const
971{
974 const auto& it = m_map_crypted_keys.find(keyid);
975 if (it == m_map_crypted_keys.end()) {
976 return std::nullopt;
977 }
978 const std::vector<unsigned char>& crypted_secret = it->second.second;
979 CKey key;
980 if (!Assume(m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
981 return DecryptKey(encryption_key, crypted_secret, it->second.first, key);
982 }))) {
983 return std::nullopt;
984 }
985 return key;
986 }
987 const auto& it = m_map_keys.find(keyid);
988 if (it == m_map_keys.end()) {
989 return std::nullopt;
990 }
991 return it->second;
992}
993
994bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
995{
997 if (!batch.TxnBegin()) return false;
998 bool res = TopUpWithDB(batch, size);
999 if (!batch.TxnCommit()) throw std::runtime_error(strprintf("Error during descriptors keypool top up. Cannot commit changes for wallet %s", m_storage.GetDisplayName()));
1000 return res;
1001}
1002
1004{
1006 std::set<CScript> new_spks;
1007 unsigned int target_size;
1008 if (size > 0) {
1009 target_size = size;
1010 } else {
1011 target_size = m_keypool_size;
1012 }
1013
1014 // Calculate the new range_end
1015 int32_t new_range_end = std::max(m_wallet_descriptor.next_index + (int32_t)target_size, m_wallet_descriptor.range_end);
1016
1017 // If the descriptor is not ranged, we actually just want to fill the first cache item
1018 if (!m_wallet_descriptor.descriptor->IsRange()) {
1019 new_range_end = 1;
1020 m_wallet_descriptor.range_end = 1;
1021 m_wallet_descriptor.range_start = 0;
1022 }
1023
1024 FlatSigningProvider provider;
1025 provider.keys = GetKeys();
1026
1027 uint256 id = GetID();
1028 for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
1029 FlatSigningProvider out_keys;
1030 std::vector<CScript> scripts_temp;
1031 DescriptorCache temp_cache;
1032 // Maybe we have a cached xpub and we can expand from the cache first
1033 if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1034 if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
1035 }
1036 // Add all of the scriptPubKeys to the scriptPubKey set
1037 new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1038 for (const CScript& script : scripts_temp) {
1039 m_map_script_pub_keys[script] = i;
1040 }
1041 for (const auto& pk_pair : out_keys.pubkeys) {
1042 const CPubKey& pubkey = pk_pair.second;
1043 if (m_map_pubkeys.count(pubkey) != 0) {
1044 // We don't need to give an error here.
1045 // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and it's private key
1046 continue;
1047 }
1048 m_map_pubkeys[pubkey] = i;
1049 }
1050 // Merge and write the cache
1051 DescriptorCache new_items = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
1052 if (!batch.WriteDescriptorCacheItems(id, new_items)) {
1053 throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
1054 }
1056 }
1057 m_wallet_descriptor.range_end = new_range_end;
1058 batch.WriteDescriptor(GetID(), m_wallet_descriptor);
1059
1060 // By this point, the cache size should be the size of the entire range
1061 assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
1062
1063 m_storage.TopUpCallback(new_spks, this);
1065 return true;
1066}
1067
1069{
1071 std::vector<WalletDestination> result;
1072 if (IsMine(script)) {
1073 int32_t index = m_map_script_pub_keys[script];
1074 if (index >= m_wallet_descriptor.next_index) {
1075 WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
1076 auto out_keys = std::make_unique<FlatSigningProvider>();
1077 std::vector<CScript> scripts_temp;
1078 while (index >= m_wallet_descriptor.next_index) {
1079 if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
1080 throw std::runtime_error(std::string(__func__) + ": Unable to expand descriptor from cache");
1081 }
1082 CTxDestination dest;
1083 ExtractDestination(scripts_temp[0], dest);
1084 result.push_back({dest, std::nullopt});
1085 m_wallet_descriptor.next_index++;
1086 }
1087 }
1088 if (!TopUp()) {
1089 WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1090 }
1091 }
1092
1093 return result;
1094}
1095
1097{
1100 if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
1101 throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
1102 }
1103}
1104
1106{
1109
1110 // Check if provided key already exists
1111 if (m_map_keys.find(pubkey.GetID()) != m_map_keys.end() ||
1112 m_map_crypted_keys.find(pubkey.GetID()) != m_map_crypted_keys.end()) {
1113 return true;
1114 }
1115
1117 if (m_storage.IsLocked()) {
1118 return false;
1119 }
1120
1121 std::vector<unsigned char> crypted_secret;
1122 CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
1123 if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
1124 return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
1125 })) {
1126 return false;
1127 }
1128
1129 m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1130 return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1131 } else {
1132 m_map_keys[pubkey.GetID()] = key;
1133 return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
1134 }
1135}
1136
1137bool DescriptorScriptPubKeyMan::SetupDescriptorGeneration(WalletBatch& batch, const CExtKey& master_key, OutputType addr_type, bool internal)
1138{
1141
1142 // Ignore when there is already a descriptor
1143 if (m_wallet_descriptor.descriptor) {
1144 return false;
1145 }
1146
1147 m_wallet_descriptor = GenerateWalletDescriptor(master_key.Neuter(), addr_type, internal);
1148
1149 // Store the master private key, and descriptor
1150 if (!AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey())) {
1151 throw std::runtime_error(std::string(__func__) + ": writing descriptor master private key failed");
1152 }
1153 if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
1154 throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
1155 }
1156
1157 // TopUp
1158 TopUpWithDB(batch);
1159
1161 return true;
1162}
1163
1165{
1167 return m_wallet_descriptor.descriptor->IsRange();
1168}
1169
1171{
1172 // We can only give out addresses from descriptors that are single type (not combo), ranged,
1173 // and either have cached keys or can generate more keys (ignoring encryption)
1175 return m_wallet_descriptor.descriptor->IsSingleType() &&
1176 m_wallet_descriptor.descriptor->IsRange() &&
1177 (HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
1178}
1179
1181{
1183 return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
1184}
1185
1187{
1189 return !m_map_crypted_keys.empty();
1190}
1191
1193{
1195 return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
1196}
1197
1199{
1201 return m_wallet_descriptor.creation_time;
1202}
1203
1204std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
1205{
1207
1208 // Find the index of the script
1209 auto it = m_map_script_pub_keys.find(script);
1210 if (it == m_map_script_pub_keys.end()) {
1211 return nullptr;
1212 }
1213 int32_t index = it->second;
1214
1215 return GetSigningProvider(index, include_private);
1216}
1217
1218std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
1219{
1221
1222 // Find index of the pubkey
1223 auto it = m_map_pubkeys.find(pubkey);
1224 if (it == m_map_pubkeys.end()) {
1225 return nullptr;
1226 }
1227 int32_t index = it->second;
1228
1229 // Always try to get the signing provider with private keys. This function should only be called during signing anyways
1230 std::unique_ptr<FlatSigningProvider> out = GetSigningProvider(index, true);
1231 if (!out->HaveKey(pubkey.GetID())) {
1232 return nullptr;
1233 }
1234 return out;
1235}
1236
1237std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
1238{
1240
1241 std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
1242
1243 // Fetch SigningProvider from cache to avoid re-deriving
1244 auto it = m_map_signing_providers.find(index);
1245 if (it != m_map_signing_providers.end()) {
1246 out_keys->Merge(FlatSigningProvider{it->second});
1247 } else {
1248 // Get the scripts, keys, and key origins for this script
1249 std::vector<CScript> scripts_temp;
1250 if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
1251
1252 // Cache SigningProvider so we don't need to re-derive if we need this SigningProvider again
1253 m_map_signing_providers[index] = *out_keys;
1254 }
1255
1256 if (HavePrivateKeys() && include_private) {
1257 FlatSigningProvider master_provider;
1258 master_provider.keys = GetKeys();
1259 m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
1260 }
1261
1262 return out_keys;
1263}
1264
1265std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
1266{
1267 return GetSigningProvider(script, false);
1268}
1269
1271{
1272 return IsMine(script);
1273}
1274
1275bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
1276{
1277 std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1278 for (const auto& coin_pair : coins) {
1279 std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
1280 if (!coin_keys) {
1281 continue;
1282 }
1283 keys->Merge(std::move(*coin_keys));
1284 }
1285
1286 return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
1287}
1288
1289SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
1290{
1291 std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
1292 if (!keys) {
1294 }
1295
1296 CKey key;
1297 if (!keys->GetKey(ToKeyID(pkhash), key)) {
1299 }
1300
1301 if (!MessageSign(key, message, str_sig)) {
1303 }
1304 return SigningResult::OK;
1305}
1306
1307std::optional<PSBTError> DescriptorScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, std::optional<int> sighash_type, bool sign, bool bip32derivs, int* n_signed, bool finalize) const
1308{
1309 if (n_signed) {
1310 *n_signed = 0;
1311 }
1312 for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
1313 const CTxIn& txin = psbtx.tx->vin[i];
1314 PSBTInput& input = psbtx.inputs.at(i);
1315
1316 if (PSBTInputSigned(input)) {
1317 continue;
1318 }
1319
1320 // Get the scriptPubKey to know which SigningProvider to use
1322 if (!input.witness_utxo.IsNull()) {
1324 } else if (input.non_witness_utxo) {
1325 if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
1326 return PSBTError::MISSING_INPUTS;
1327 }
1328 script = input.non_witness_utxo->vout[txin.prevout.n].scriptPubKey;
1329 } else {
1330 // There's no UTXO so we can just skip this now
1331 continue;
1332 }
1333
1334 std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1335 std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, /*include_private=*/sign);
1336 if (script_keys) {
1337 keys->Merge(std::move(*script_keys));
1338 } else {
1339 // Maybe there are pubkeys listed that we can sign for
1340 std::vector<CPubKey> pubkeys;
1341 pubkeys.reserve(input.hd_keypaths.size() + 2);
1342
1343 // ECDSA Pubkeys
1344 for (const auto& [pk, _] : input.hd_keypaths) {
1345 pubkeys.push_back(pk);
1346 }
1347
1348 // Taproot output pubkey
1349 std::vector<std::vector<unsigned char>> sols;
1351 sols[0].insert(sols[0].begin(), 0x02);
1352 pubkeys.emplace_back(sols[0]);
1353 sols[0][0] = 0x03;
1354 pubkeys.emplace_back(sols[0]);
1355 }
1356
1357 // Taproot pubkeys
1358 for (const auto& pk_pair : input.m_tap_bip32_paths) {
1359 const XOnlyPubKey& pubkey = pk_pair.first;
1360 for (unsigned char prefix : {0x02, 0x03}) {
1361 unsigned char b[33] = {prefix};
1362 std::copy(pubkey.begin(), pubkey.end(), b + 1);
1363 CPubKey fullpubkey;
1364 fullpubkey.Set(b, b + 33);
1365 pubkeys.push_back(fullpubkey);
1366 }
1367 }
1368
1369 for (const auto& pubkey : pubkeys) {
1370 std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
1371 if (pk_keys) {
1372 keys->Merge(std::move(*pk_keys));
1373 }
1374 }
1375 }
1376
1377 PSBTError res = SignPSBTInput(HidingSigningProvider(keys.get(), /*hide_secret=*/!sign, /*hide_origin=*/!bip32derivs), psbtx, i, &txdata, sighash_type, nullptr, finalize);
1378 if (res != PSBTError::OK && res != PSBTError::INCOMPLETE) {
1379 return res;
1380 }
1381
1382 bool signed_one = PSBTInputSigned(input);
1383 if (n_signed && (signed_one || !sign)) {
1384 // If sign is false, we assume that we _could_ sign if we get here. This
1385 // will never have false negatives; it is hard to tell under what i
1386 // circumstances it could have false positives.
1387 (*n_signed)++;
1388 }
1389 }
1390
1391 // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
1392 for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
1393 std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
1394 if (!keys) {
1395 continue;
1396 }
1397 UpdatePSBTOutput(HidingSigningProvider(keys.get(), /*hide_secret=*/true, /*hide_origin=*/!bip32derivs), psbtx, i);
1398 }
1399
1400 return {};
1401}
1402
1403std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
1404{
1405 std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
1406 if (provider) {
1407 KeyOriginInfo orig;
1408 CKeyID key_id = GetKeyForDestination(*provider, dest);
1409 if (provider->GetKeyOrigin(key_id, orig)) {
1411 std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
1412 meta->key_origin = orig;
1413 meta->has_key_origin = true;
1414 meta->nCreateTime = m_wallet_descriptor.creation_time;
1415 return meta;
1416 }
1417 }
1418 return nullptr;
1419}
1420
1422{
1424 return m_wallet_descriptor.id;
1425}
1426
1428{
1430 std::set<CScript> new_spks;
1431 m_wallet_descriptor.cache = cache;
1432 for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
1433 FlatSigningProvider out_keys;
1434 std::vector<CScript> scripts_temp;
1435 if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1436 throw std::runtime_error("Error: Unable to expand wallet descriptor from cache");
1437 }
1438 // Add all of the scriptPubKeys to the scriptPubKey set
1439 new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1440 for (const CScript& script : scripts_temp) {
1441 if (m_map_script_pub_keys.count(script) != 0) {
1442 throw std::runtime_error(strprintf("Error: Already loaded script at index %d as being at index %d", i, m_map_script_pub_keys[script]));
1443 }
1444 m_map_script_pub_keys[script] = i;
1445 }
1446 for (const auto& pk_pair : out_keys.pubkeys) {
1447 const CPubKey& pubkey = pk_pair.second;
1448 if (m_map_pubkeys.count(pubkey) != 0) {
1449 // We don't need to give an error here.
1450 // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and it's private key
1451 continue;
1452 }
1453 m_map_pubkeys[pubkey] = i;
1454 }
1456 }
1457 // Make sure the wallet knows about our new spks
1458 m_storage.TopUpCallback(new_spks, this);
1459}
1460
1461bool DescriptorScriptPubKeyMan::AddKey(const CKeyID& key_id, const CKey& key)
1462{
1464 m_map_keys[key_id] = key;
1465 return true;
1466}
1467
1468bool DescriptorScriptPubKeyMan::AddCryptedKey(const CKeyID& key_id, const CPubKey& pubkey, const std::vector<unsigned char>& crypted_key)
1469{
1471 if (!m_map_keys.empty()) {
1472 return false;
1473 }
1474
1475 m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
1476 return true;
1477}
1478
1480{
1482 return !m_wallet_descriptor.id.IsNull() && !desc.id.IsNull() && m_wallet_descriptor.id == desc.id;
1483}
1484
1486{
1489 if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
1490 throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
1491 }
1492}
1493
1495{
1496 return m_wallet_descriptor;
1497}
1498
1499std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
1500{
1501 return GetScriptPubKeys(0);
1502}
1503
1504std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys(int32_t minimum_index) const
1505{
1507 std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
1508 script_pub_keys.reserve(m_map_script_pub_keys.size());
1509
1510 for (auto const& [script_pub_key, index] : m_map_script_pub_keys) {
1511 if (index >= minimum_index) script_pub_keys.insert(script_pub_key);
1512 }
1513 return script_pub_keys;
1514}
1515
1517{
1518 return m_max_cached_index + 1;
1519}
1520
1521bool DescriptorScriptPubKeyMan::GetDescriptorString(std::string& out, const bool priv) const
1522{
1524
1525 FlatSigningProvider provider;
1526 provider.keys = GetKeys();
1527
1528 if (priv) {
1529 // For the private version, always return the master key to avoid
1530 // exposing child private keys. The risk implications of exposing child
1531 // private keys together with the parent xpub may be non-obvious for users.
1532 return m_wallet_descriptor.descriptor->ToPrivateString(provider, out);
1533 }
1534
1535 return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
1536}
1537
1539{
1542 return;
1543 }
1544
1545 // Skip if we have the last hardened xpub cache
1546 if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
1547 return;
1548 }
1549
1550 // Expand the descriptor
1551 FlatSigningProvider provider;
1552 provider.keys = GetKeys();
1553 FlatSigningProvider out_keys;
1554 std::vector<CScript> scripts_temp;
1555 DescriptorCache temp_cache;
1556 if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
1557 throw std::runtime_error("Unable to expand descriptor");
1558 }
1559
1560 // Cache the last hardened xpubs
1561 DescriptorCache diff = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
1563 throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
1564 }
1565}
1566
1568{
1570 std::string error;
1571 if (!CanUpdateToWalletDescriptor(descriptor, error)) {
1572 return util::Error{Untranslated(std::move(error))};
1573 }
1574
1575 m_map_pubkeys.clear();
1576 m_map_script_pub_keys.clear();
1577 m_max_cached_index = -1;
1578 m_wallet_descriptor = descriptor;
1579
1580 NotifyFirstKeyTimeChanged(this, m_wallet_descriptor.creation_time);
1581 return {};
1582}
1583
1585{
1587 if (!HasWalletDescriptor(descriptor)) {
1588 error = "can only update matching descriptor";
1589 return false;
1590 }
1591
1592 if (!descriptor.descriptor->IsRange()) {
1593 // Skip range check for non-range descriptors
1594 return true;
1595 }
1596
1597 if (descriptor.range_start > m_wallet_descriptor.range_start ||
1598 descriptor.range_end < m_wallet_descriptor.range_end) {
1599 // Use inclusive range for error
1600 error = strprintf("new range must include current range = [%d,%d]",
1601 m_wallet_descriptor.range_start,
1602 m_wallet_descriptor.range_end - 1);
1603 return false;
1604 }
1605
1606 return true;
1607}
1608} // 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:415
A reference to a CScript: the Hash160 of its serialization.
Definition: script.h:604
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:296
const unsigned char * begin() const
Definition: pubkey.h:295
constexpr bool IsNull() const
Definition: uint256.h:48
constexpr unsigned char * begin()
Definition: uint256.h:101
size_type size() const
Definition: prevector.h:253
160-bit opaque blob.
Definition: uint256.h:184
256-bit opaque blob.
Definition: uint256.h:196
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
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
isminetype IsMine(const CScript &script) const 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.
isminetype IsMine(const CScript &script) const override
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.
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:239
bool WriteDescriptorCacheItems(const uint256 &desc_id, const DescriptorCache &cache)
Definition: walletdb.cpp:265
bool TxnBegin()
Begin a new transaction.
Definition: walletdb.cpp:1307
bool TxnCommit()
Commit current transaction.
Definition: walletdb.cpp:1312
bool EraseRecords(const std::unordered_set< std::string > &types)
Delete records of the given types.
Definition: walletdb.cpp:1300
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:230
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
Definition: walletdb.cpp:219
Descriptor with some wallet metadata.
Definition: walletutil.h:85
std::shared_ptr< Descriptor > descriptor
Definition: walletutil.h:87
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 bool CanSupportFeature(enum WalletFeature) const =0
virtual std::string GetDisplayName() 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:317
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:266
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:233
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
isminetype
IsMine() return codes, which depend on ScriptPubKeyMan implementation.
Definition: types.h:41
@ ISMINE_NO
Definition: types.h:42
@ ISMINE_SPENDABLE
Definition: types.h:44
@ ISMINE_WATCH_ONLY
Definition: types.h:43
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)
@ FEATURE_HD_SPLIT
Definition: walletutil.h:24
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:48
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:74
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:51
WalletDescriptor GenerateWalletDescriptor(const CExtPubKey &master_key, const OutputType &addr_type, bool internal)
Definition: walletutil.cpp:49
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:1009
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:257
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:302
#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())