Bitcoin ABC 0.34.2
P2P Digital Currency
scriptpubkeyman.cpp
Go to the documentation of this file.
1// Copyright (c) 2019 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 <chainparams.h>
6#include <common/args.h>
7#include <config.h>
8#include <key_io.h>
9#include <logging.h>
10#include <node/types.h>
11#include <outputtype.h>
12#include <script/descriptor.h>
13#include <script/script.h>
14#include <script/sign.h>
15#include <util/bip32.h>
16#include <util/strencodings.h>
17#include <util/string.h>
18#include <util/translation.h>
20
22using util::ToString;
23
26const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
27
31
32 // Generate a new key that is added to wallet
33 CPubKey new_key;
34 if (!GetKeyFromPool(new_key, type)) {
35 return util::Error{
36 _("Error: Keypool ran out, please call keypoolrefill first")};
37 }
38 LearnRelatedScripts(new_key, type);
39 return GetDestinationForKey(new_key, type);
40}
41
42typedef std::vector<uint8_t> valtype;
43
44namespace {
45
52enum class IsMineSigVersion {
53 TOP = 0,
54 P2SH = 1,
55};
56
62enum class IsMineResult {
63 NO = 0,
64 WATCH_ONLY = 1,
65 SPENDABLE = 2,
66 INVALID = 3,
67};
68
69bool HaveKeys(const std::vector<valtype> &pubkeys,
70 const LegacyScriptPubKeyMan &keystore) {
71 for (const valtype &pubkey : pubkeys) {
72 CKeyID keyID = CPubKey(pubkey).GetID();
73 if (!keystore.HaveKey(keyID)) {
74 return false;
75 }
76 }
77 return true;
78}
79
89IsMineResult IsMineInner(const LegacyScriptPubKeyMan &keystore,
90 const CScript &scriptPubKey,
91 IsMineSigVersion sigversion,
92 bool recurse_scripthash = true) {
93 IsMineResult ret = IsMineResult::NO;
94
95 std::vector<valtype> vSolutions;
96 TxoutType whichType = Solver(scriptPubKey, vSolutions);
97
98 CKeyID keyID;
99 switch (whichType) {
102 break;
104 keyID = CPubKey(vSolutions[0]).GetID();
105 if (keystore.HaveKey(keyID)) {
106 ret = std::max(ret, IsMineResult::SPENDABLE);
107 }
108 break;
110 keyID = CKeyID(uint160(vSolutions[0]));
111 if (keystore.HaveKey(keyID)) {
112 ret = std::max(ret, IsMineResult::SPENDABLE);
113 }
114 break;
116 if (sigversion != IsMineSigVersion::TOP) {
117 // P2SH inside P2SH is invalid.
118 return IsMineResult::INVALID;
119 }
120 CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
121 CScript subscript;
122 if (keystore.GetCScript(scriptID, subscript)) {
123 ret = std::max(ret, recurse_scripthash
124 ? IsMineInner(keystore, subscript,
125 IsMineSigVersion::P2SH)
126 : IsMineResult::SPENDABLE);
127 }
128 break;
129 }
130 case TxoutType::MULTISIG: {
131 // Never treat bare multisig outputs as ours (they can still be made
132 // watchonly-though)
133 if (sigversion == IsMineSigVersion::TOP) {
134 break;
135 }
136
137 // Only consider transactions "mine" if we own ALL the keys
138 // involved. Multi-signature transactions that are partially owned
139 // (somebody else has a key that can spend them) enable
140 // spend-out-from-under-you attacks, especially in shared-wallet
141 // situations.
142 std::vector<valtype> keys(vSolutions.begin() + 1,
143 vSolutions.begin() + vSolutions.size() -
144 1);
145 if (HaveKeys(keys, keystore)) {
146 ret = std::max(ret, IsMineResult::SPENDABLE);
147 }
148 break;
149 }
150 }
151
152 if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
153 ret = std::max(ret, IsMineResult::WATCH_ONLY);
154 }
155 return ret;
156}
157
158} // namespace
159
161 switch (IsMineInner(*this, script, IsMineSigVersion::TOP)) {
162 case IsMineResult::INVALID:
163 case IsMineResult::NO:
164 return ISMINE_NO;
165 case IsMineResult::WATCH_ONLY:
166 return ISMINE_WATCH_ONLY;
167 case IsMineResult::SPENDABLE:
168 return ISMINE_SPENDABLE;
169 }
170 assert(false);
171}
172
174 const CKeyingMaterial &master_key, bool accept_no_keys) {
175 {
177 assert(mapKeys.empty());
178
179 // Always pass when there are no encrypted keys
180 bool keyPass = mapCryptedKeys.empty();
181 bool keyFail = false;
182 CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
184 for (; mi != mapCryptedKeys.end(); ++mi) {
185 const CPubKey &vchPubKey = (*mi).second.first;
186 const std::vector<uint8_t> &vchCryptedSecret = (*mi).second.second;
187 CKey key;
188 if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key)) {
189 keyFail = true;
190 break;
191 }
192 keyPass = true;
194 break;
195 } else {
196 // Rewrite these encrypted keys with checksums
197 batch.WriteCryptedKey(vchPubKey, vchCryptedSecret,
198 mapKeyMetadata[vchPubKey.GetID()]);
199 }
200 }
201 if (keyPass && keyFail) {
202 LogPrintf("The wallet is probably corrupted: Some keys decrypt but "
203 "not all.\n");
204 throw std::runtime_error(
205 "Error unlocking wallet: some keys decrypt but not all. Your "
206 "wallet file may be corrupt.");
207 }
208 if (keyFail || (!keyPass && !accept_no_keys)) {
209 return false;
210 }
212 }
213 return true;
214}
215
217 WalletBatch *batch) {
219 encrypted_batch = batch;
220 if (!mapCryptedKeys.empty()) {
221 encrypted_batch = nullptr;
222 return false;
223 }
224
225 KeyMap keys_to_encrypt;
226 // Clear mapKeys so AddCryptedKeyInner will succeed.
227 keys_to_encrypt.swap(mapKeys);
228 for (const KeyMap::value_type &mKey : keys_to_encrypt) {
229 const CKey &key = mKey.second;
230 CPubKey vchPubKey = key.GetPubKey();
231 CKeyingMaterial vchSecret(key.begin(), key.end());
232 std::vector<uint8_t> vchCryptedSecret;
233 if (!EncryptSecret(master_key, vchSecret, vchPubKey.GetHash(),
234 vchCryptedSecret)) {
235 encrypted_batch = nullptr;
236 return false;
237 }
238 if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) {
239 encrypted_batch = nullptr;
240 return false;
241 }
242 }
243 encrypted_batch = nullptr;
244 return true;
245}
246
248 bool internal,
249 CTxDestination &address,
250 int64_t &index,
251 CKeyPool &keypool) {
253 if (!CanGetAddresses(internal)) {
254 return false;
255 }
256
257 if (!ReserveKeyFromKeyPool(index, keypool, internal)) {
258 return false;
259 }
260 address = GetDestinationForKey(keypool.vchPubKey, type);
261 return true;
262}
263
265 int64_t index, bool internal) {
267
268 if (m_storage.IsLocked()) {
269 return false;
270 }
271
272 auto it = m_inactive_hd_chains.find(seed_id);
273 if (it == m_inactive_hd_chains.end()) {
274 return false;
275 }
276
277 CHDChain &chain = it->second;
278
279 // Top up key pool
280 int64_t target_size =
281 std::max(gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t)1);
282
283 // "size" of the keypools. Not really the size, actually the difference
284 // between index and the chain counter Since chain counter is 1 based and
285 // index is 0 based, one of them needs to be offset by 1.
286 int64_t kp_size =
287 (internal ? chain.nInternalChainCounter : chain.nExternalChainCounter) -
288 (index + 1);
289
290 // make sure the keypool fits the user-selected target (-keypool)
291 int64_t missing = std::max(target_size - kp_size, (int64_t)0);
292
293 if (missing > 0) {
295 for (int64_t i = missing; i > 0; --i) {
296 GenerateNewKey(batch, chain, internal);
297 }
298 if (internal) {
299 WalletLogPrintf("inactive seed with id %s added %d internal keys\n",
300 HexStr(seed_id), missing);
301 } else {
302 WalletLogPrintf("inactive seed with id %s added %d keys\n",
303 HexStr(seed_id), missing);
304 }
305 }
306 return true;
307}
308
311 // extract addresses and check if they match with an unused keypool key
312 for (const auto &keyid : GetAffectedKeys(script, *this)) {
313 std::map<CKeyID, int64_t>::const_iterator mi =
314 m_pool_key_to_index.find(keyid);
315 if (mi != m_pool_key_to_index.end()) {
316 WalletLogPrintf("%s: Detected a used keypool key, mark all keypool "
317 "keys up to this key as used\n",
318 __func__);
319 MarkReserveKeysAsUsed(mi->second);
320
321 if (!TopUp()) {
323 "%s: Topping up keypool failed (locked wallet)\n",
324 __func__);
325 }
326 }
327
328 // Find the key's metadata and check if it's seed id (if it has one) is
329 // inactive, i.e. it is not the current m_hd_chain seed id. If so, TopUp
330 // the inactive hd chain
331 auto it = mapKeyMetadata.find(keyid);
332 if (it != mapKeyMetadata.end()) {
333 CKeyMetadata meta = it->second;
334 if (!meta.hd_seed_id.IsNull() &&
335 meta.hd_seed_id != m_hd_chain.seed_id) {
336 bool internal =
337 (meta.key_origin.path[1] & ~BIP32_HARDENED_KEY_LIMIT) != 0;
338 int64_t index =
339 meta.key_origin.path[2] & ~BIP32_HARDENED_KEY_LIMIT;
340
341 if (!TopUpInactiveHDChain(meta.hd_seed_id, index, internal)) {
342 WalletLogPrintf("%s: Adding inactive seed keys failed\n",
343 __func__);
344 }
345 }
346 }
347 }
348}
349
352 if (m_storage.IsLocked() ||
354 return;
355 }
356
357 auto batch = std::make_unique<WalletBatch>(m_storage.GetDatabase());
358 for (auto &meta_pair : mapKeyMetadata) {
359 CKeyMetadata &meta = meta_pair.second;
360 // If the hdKeypath is "s", that's the seed and it doesn't have a key
361 // origin
362 if (!meta.hd_seed_id.IsNull() && !meta.has_key_origin &&
363 meta.hdKeypath != "s") {
364 CKey key;
365 GetKey(meta.hd_seed_id, key);
366 CExtKey masterKey;
367 masterKey.SetSeed(key);
368 // Add to map
369 CKeyID master_id = masterKey.key.GetPubKey().GetID();
370 std::copy(master_id.begin(), master_id.begin() + 4,
372 if (!ParseHDKeypath(meta.hdKeypath, meta.key_origin.path)) {
373 throw std::runtime_error("Invalid stored hdKeypath");
374 }
375 meta.has_key_origin = true;
378 }
379
380 // Write meta to wallet
381 CPubKey pubkey;
382 if (GetPubKey(meta_pair.first, pubkey)) {
383 batch->WriteKeyMetadata(meta, pubkey, true);
384 }
385 }
386 }
387}
388
390 if ((CanGenerateKeys() && !force) || m_storage.IsLocked()) {
391 return false;
392 }
393
395 if (!NewKeyPool()) {
396 return false;
397 }
398 return true;
399}
400
402 return !m_hd_chain.seed_id.IsNull();
403}
404
405bool LegacyScriptPubKeyMan::CanGetAddresses(bool internal) const {
407 // Check if the keypool has keys
408 bool keypool_has_keys;
410 keypool_has_keys = setInternalKeyPool.size() > 0;
411 } else {
412 keypool_has_keys = KeypoolCountExternalKeys() > 0;
413 }
414 // If the keypool doesn't have keys, check if we can generate them
415 if (!keypool_has_keys) {
416 return CanGenerateKeys();
417 }
418 return keypool_has_keys;
419}
420
421bool LegacyScriptPubKeyMan::Upgrade(int prev_version, bilingual_str &error) {
423 bool hd_upgrade = false;
424 bool split_upgrade = false;
426 WalletLogPrintf("Upgrading wallet to HD\n");
428
429 // generate a new master key
430 CPubKey masterPubKey = GenerateNewSeed();
431 SetHDSeed(masterPubKey);
432 hd_upgrade = true;
433 }
434 // Upgrade to HD chain split if necessary
436 WalletLogPrintf("Upgrading wallet to use HD chain split\n");
438 split_upgrade = FEATURE_HD_SPLIT > prev_version;
439 }
440 // Mark all keys currently in the keypool as pre-split
441 if (split_upgrade) {
443 }
444 // Regenerate the keypool if upgraded to HD
445 if (hd_upgrade) {
446 if (!TopUp()) {
447 error = _("Unable to generate keys");
448 return false;
449 }
450 }
451 return true;
452}
453
456 return !mapKeys.empty() || !mapCryptedKeys.empty();
457}
458
461 setInternalKeyPool.clear();
462 setExternalKeyPool.clear();
463 m_pool_key_to_index.clear();
464 // Note: can't top-up keypool here, because wallet is locked.
465 // User will be prompted to unlock wallet the next operation
466 // that requires a new key.
467}
468
469static int64_t GetOldestKeyTimeInPool(const std::set<int64_t> &setKeyPool,
470 WalletBatch &batch) {
471 if (setKeyPool.empty()) {
472 return GetTime();
473 }
474
475 CKeyPool keypool;
476 int64_t nIndex = *(setKeyPool.begin());
477 if (!batch.ReadPool(nIndex, keypool)) {
478 throw std::runtime_error(std::string(__func__) +
479 ": read oldest key in keypool failed");
480 }
481
482 assert(keypool.vchPubKey.IsValid());
483 return keypool.nTime;
484}
485
488
490
491 // load oldest key from keypool, get time and return
492 int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, batch);
494 oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, batch),
495 oldestKey);
496 if (!set_pre_split_keypool.empty()) {
497 oldestKey =
498 std::max(GetOldestKeyTimeInPool(set_pre_split_keypool, batch),
499 oldestKey);
500 }
501 }
502
503 return oldestKey;
504}
505
508 return setExternalKeyPool.size() + set_pre_split_keypool.size();
509}
510
513 return setInternalKeyPool.size() + setExternalKeyPool.size() +
514 set_pre_split_keypool.size();
515}
516
519 return nTimeFirstKey;
520}
521
522std::unique_ptr<SigningProvider>
524 return std::make_unique<LegacySigningProvider>(*this);
525}
526
528 SignatureData &sigdata) {
529 IsMineResult ismine = IsMineInner(*this, script, IsMineSigVersion::TOP,
530 /* recurse_scripthash= */ false);
531 if (ismine == IsMineResult::SPENDABLE ||
532 ismine == IsMineResult::WATCH_ONLY) {
533 // If ismine, it means we recognize keys or script ids in the script, or
534 // are watching the script itself, and we can at least provide metadata
535 // or solving information, even if not able to sign fully.
536 return true;
537 }
538 // If, given the stuff in sigdata, we could make a valid sigature, then
539 // we can provide for this script
541 if (!sigdata.signatures.empty()) {
542 // If we could make signatures, make sure we have a private key to
543 // actually make a signature
544 bool has_privkeys = false;
545 for (const auto &key_sig_pair : sigdata.signatures) {
546 has_privkeys |= HaveKey(key_sig_pair.first);
547 }
548 return has_privkeys;
549 }
550 return false;
551}
552
554 CMutableTransaction &tx, const std::map<COutPoint, Coin> &coins,
555 SigHashType sighash, std::map<int, std::string> &input_errors) const {
556 return ::SignTransaction(tx, this, coins, sighash, input_errors);
557}
558
560 const PKHash &pkhash,
561 std::string &str_sig) const {
562 CKey key;
563 if (!GetKey(ToKeyID(pkhash), key)) {
565 }
566
567 if (MessageSign(key, message, str_sig)) {
568 return SigningResult::OK;
569 }
571}
572
573std::optional<PSBTError>
575 SigHashType sighash_type, bool sign,
576 bool bip32derivs, bool finalize) const {
577 for (size_t i = 0; i < psbtx.tx->vin.size(); ++i) {
578 PSBTInput &input = psbtx.inputs.at(i);
579
580 if (PSBTInputSigned(input)) {
581 continue;
582 }
583
584 // Get the Sighash type
585 if (sign && input.sighash_type != std::nullopt &&
586 *input.sighash_type != sighash_type) {
587 return PSBTError::SIGHASH_MISMATCH;
588 }
589
590 if (input.utxo.IsNull()) {
591 // There's no UTXO so we can just skip this now
592 continue;
593 }
594 SignatureData sigdata;
595 input.FillSignatureData(sigdata);
596 SignPSBTInput(HidingSigningProvider(this, !sign, !bip32derivs), psbtx,
597 i, sighash_type, /*out_sigdata=*/nullptr,
598 /*use_dummy=*/false, finalize);
599 }
600
601 // Fill in the bip32 keypaths and redeemscripts for the outputs so that
602 // hardware wallets can identify change
603 for (size_t i = 0; i < psbtx.tx->vout.size(); ++i) {
604 UpdatePSBTOutput(HidingSigningProvider(this, true, !bip32derivs), psbtx,
605 i);
606 }
607
608 return {};
609}
610
611std::unique_ptr<CKeyMetadata>
614
615 CKeyID key_id = GetKeyForDestination(*this, dest);
616 if (!key_id.IsNull()) {
617 auto it = mapKeyMetadata.find(key_id);
618 if (it != mapKeyMetadata.end()) {
619 return std::make_unique<CKeyMetadata>(it->second);
620 }
621 }
622
623 CScript scriptPubKey = GetScriptForDestination(dest);
624 auto it = m_script_metadata.find(CScriptID(scriptPubKey));
625 if (it != m_script_metadata.end()) {
626 return std::make_unique<CKeyMetadata>(it->second);
627 }
628
629 return nullptr;
630}
631
633 return uint256::ONE;
634}
635
642 if (nCreateTime <= 1) {
643 // Cannot determine birthday information, so set the wallet birthday to
644 // the beginning of time.
645 nTimeFirstKey = 1;
646 } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
647 nTimeFirstKey = nCreateTime;
648 }
649}
650
651bool LegacyScriptPubKeyMan::LoadKey(const CKey &key, const CPubKey &pubkey) {
652 return AddKeyPubKeyInner(key, pubkey);
653}
654
656 const CPubKey &pubkey) {
659 return LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(batch, secret, pubkey);
660}
661
663 const CKey &secret,
664 const CPubKey &pubkey) {
666
667 // Make sure we aren't adding private keys to private key disabled wallets
669
670 // FillableSigningProvider has no concept of wallet databases, but calls
671 // AddCryptedKey which is overridden below. To avoid flushes, the database
672 // handle is tunneled through to it.
673 bool needsDB = !encrypted_batch;
674 if (needsDB) {
675 encrypted_batch = &batch;
676 }
677 if (!AddKeyPubKeyInner(secret, pubkey)) {
678 if (needsDB) {
679 encrypted_batch = nullptr;
680 }
681 return false;
682 }
683
684 if (needsDB) {
685 encrypted_batch = nullptr;
686 }
687
688 // Check if we need to remove from watch-only.
689 CScript script;
691 if (HaveWatchOnly(script)) {
693 }
694
696 if (HaveWatchOnly(script)) {
698 }
699
701 return batch.WriteKey(pubkey, secret.GetPrivKey(),
702 mapKeyMetadata[pubkey.GetID()]);
703 }
705 return true;
706}
707
715 std::string strAddr =
717 WalletLogPrintf("%s: Warning: This wallet contains a redeemScript "
718 "of size %i which exceeds maximum size %i thus can "
719 "never be redeemed. Do not use address %s.\n",
720 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE,
721 strAddr);
722 return true;
723 }
724
726}
727
729 const CKeyMetadata &meta) {
732 mapKeyMetadata[keyID] = meta;
733}
734
736 const CKeyMetadata &meta) {
739 m_script_metadata[script_id] = meta;
740}
741
743 const CPubKey &pubkey) {
746 return FillableSigningProvider::AddKeyPubKey(key, pubkey);
747 }
748
749 if (m_storage.IsLocked()) {
750 return false;
751 }
752
753 std::vector<uint8_t> vchCryptedSecret;
754 CKeyingMaterial vchSecret(key.begin(), key.end());
756 [&](const CKeyingMaterial &encryption_key) {
757 return EncryptSecret(encryption_key, vchSecret,
758 pubkey.GetHash(), vchCryptedSecret);
759 })) {
760 return false;
761 }
762
763 if (!AddCryptedKey(pubkey, vchCryptedSecret)) {
764 return false;
765 }
766 return true;
767}
768
770 const CPubKey &vchPubKey, const std::vector<uint8_t> &vchCryptedSecret,
771 bool checksum_valid) {
772 // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
773 if (!checksum_valid) {
775 }
776
777 return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
778}
779
781 const CPubKey &vchPubKey, const std::vector<uint8_t> &vchCryptedSecret) {
783 assert(mapKeys.empty());
784
785 mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
786 return true;
787}
788
790 const CPubKey &vchPubKey, const std::vector<uint8_t> &vchCryptedSecret) {
791 if (!AddCryptedKeyInner(vchPubKey, vchCryptedSecret)) {
792 return false;
793 }
794
796 if (encrypted_batch) {
797 return encrypted_batch->WriteCryptedKey(
798 vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
799 }
800
802 .WriteCryptedKey(vchPubKey, vchCryptedSecret,
803 mapKeyMetadata[vchPubKey.GetID()]);
804}
805
806bool LegacyScriptPubKeyMan::HaveWatchOnly(const CScript &dest) const {
808 return setWatchOnly.count(dest) > 0;
809}
810
813 return (!setWatchOnly.empty());
814}
815
816static bool ExtractPubKey(const CScript &dest, CPubKey &pubKeyOut) {
817 std::vector<std::vector<uint8_t>> solutions;
818 return Solver(dest, solutions) == TxoutType::PUBKEY &&
819 (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
820}
821
822bool LegacyScriptPubKeyMan::RemoveWatchOnly(const CScript &dest) {
823 {
825 setWatchOnly.erase(dest);
826 CPubKey pubKey;
827 if (ExtractPubKey(dest, pubKey)) {
828 mapWatchKeys.erase(pubKey.GetID());
829 }
830 }
831
832 if (!HaveWatchOnly()) {
834 }
835
837}
838
839bool LegacyScriptPubKeyMan::LoadWatchOnly(const CScript &dest) {
840 return AddWatchOnlyInMem(dest);
841}
842
845 setWatchOnly.insert(dest);
846 CPubKey pubKey;
847 if (ExtractPubKey(dest, pubKey)) {
848 mapWatchKeys[pubKey.GetID()] = pubKey;
849 }
850 return true;
851}
852
854 const CScript &dest) {
855 if (!AddWatchOnlyInMem(dest)) {
856 return false;
857 }
858
859 const CKeyMetadata &meta = m_script_metadata[CScriptID(dest)];
862 if (batch.WriteWatchOnly(dest, meta)) {
864 return true;
865 }
866 return false;
867}
868
870 const CScript &dest,
871 int64_t create_time) {
872 m_script_metadata[CScriptID(dest)].nCreateTime = create_time;
873 return AddWatchOnlyWithDB(batch, dest);
874}
875
876bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript &dest) {
878 return AddWatchOnlyWithDB(batch, dest);
879}
880
881bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript &dest,
882 int64_t nCreateTime) {
883 m_script_metadata[CScriptID(dest)].nCreateTime = nCreateTime;
884 return AddWatchOnly(dest);
885}
886
889 m_hd_chain = chain;
890}
891
894 // Store the new chain
896 throw std::runtime_error(std::string(__func__) +
897 ": writing chain failed");
898 }
899 // When there's an old chain, add it as an inactive chain as we are now
900 // rotating hd chains
901 if (!m_hd_chain.seed_id.IsNull()) {
903 }
904
905 m_hd_chain = chain;
906}
907
910 assert(!chain.seed_id.IsNull());
911 m_inactive_hd_chains[chain.seed_id] = chain;
912}
913
914bool LegacyScriptPubKeyMan::HaveKey(const CKeyID &address) const {
917 return FillableSigningProvider::HaveKey(address);
918 }
919 return mapCryptedKeys.count(address) > 0;
920}
921
922bool LegacyScriptPubKeyMan::GetKey(const CKeyID &address, CKey &keyOut) const {
925 return FillableSigningProvider::GetKey(address, keyOut);
926 }
927
928 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
929 if (mi != mapCryptedKeys.end()) {
930 const CPubKey &vchPubKey = (*mi).second.first;
931 const std::vector<uint8_t> &vchCryptedSecret = (*mi).second.second;
933 [&](const CKeyingMaterial &encryption_key) {
934 return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey,
935 keyOut);
936 });
937 }
938 return false;
939}
940
942 KeyOriginInfo &info) const {
943 CKeyMetadata meta;
944 {
946 auto it = mapKeyMetadata.find(keyID);
947 if (it != mapKeyMetadata.end()) {
948 meta = it->second;
949 }
950 }
951 if (meta.has_key_origin) {
952 std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4,
953 info.fingerprint);
954 info.path = meta.key_origin.path;
955 } else {
956 // Single pubkeys get the master fingerprint of themselves
957 std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
958 }
959 return true;
960}
961
963 CPubKey &pubkey_out) const {
965 WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
966 if (it != mapWatchKeys.end()) {
967 pubkey_out = it->second;
968 return true;
969 }
970 return false;
971}
972
974 CPubKey &vchPubKeyOut) const {
977 if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
978 return GetWatchPubKey(address, vchPubKeyOut);
979 }
980 return true;
981 }
982
983 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
984 if (mi != mapCryptedKeys.end()) {
985 vchPubKeyOut = (*mi).second.first;
986 return true;
987 }
988
989 // Check for watch-only pubkeys
990 return GetWatchPubKey(address, vchPubKeyOut);
991}
992
994 CHDChain &hd_chain,
995 bool internal) {
999 // default to compressed public keys if we want 0.6.0 wallets
1001
1002 CKey secret;
1003
1004 // Create new metadata
1005 int64_t nCreationTime = GetTime();
1006 CKeyMetadata metadata(nCreationTime);
1007
1008 // use HD key derivation if HD was enabled during wallet creation and a seed
1009 // is present
1010 if (IsHDEnabled()) {
1012 batch, metadata, secret, hd_chain,
1013 (m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
1014 } else {
1015 secret.MakeNewKey(fCompressed);
1016 }
1017
1018 // Compressed public keys were introduced in version 0.6.0
1019 if (fCompressed) {
1021 }
1022
1023 CPubKey pubkey = secret.GetPubKey();
1024 assert(secret.VerifyPubKey(pubkey));
1025
1026 mapKeyMetadata[pubkey.GetID()] = metadata;
1027 UpdateTimeFirstKey(nCreationTime);
1028
1029 if (!AddKeyPubKeyWithDB(batch, secret, pubkey)) {
1030 throw std::runtime_error(std::string(__func__) + ": AddKey failed");
1031 }
1032
1033 return pubkey;
1034}
1035
1037 CKeyMetadata &metadata,
1038 CKey &secret, CHDChain &hd_chain,
1039 bool internal) {
1040 // for now we use a fixed keypath scheme of m/0'/0'/k
1041 // seed (256bit)
1042 CKey seed;
1043 // hd master key
1044 CExtKey masterKey;
1045 // key at m/0'
1046 CExtKey accountKey;
1047 // key at m/0'/0' (external) or m/0'/1' (internal)
1048 CExtKey chainChildKey;
1049 // key at m/0'/0'/<n>'
1050 CExtKey childKey;
1051
1052 // try to get the seed
1053 if (!GetKey(hd_chain.seed_id, seed)) {
1054 throw std::runtime_error(std::string(__func__) + ": seed not found");
1055 }
1056
1057 masterKey.SetSeed(seed);
1058
1059 // derive m/0'
1060 // use hardened derivation (child keys >= 0x80000000 are hardened after
1061 // bip32)
1062 masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
1063
1064 // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
1066 accountKey.Derive(chainChildKey,
1067 BIP32_HARDENED_KEY_LIMIT + (internal ? 1 : 0));
1068
1069 // derive child key at next index, skip keys already known to the wallet
1070 do {
1071 // always derive hardened keys
1072 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened
1073 // child-index-range
1074 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
1075 if (internal) {
1076 chainChildKey.Derive(childKey, hd_chain.nInternalChainCounter |
1078 metadata.hdKeypath =
1079 "m/0'/1'/" + ToString(hd_chain.nInternalChainCounter) + "'";
1080 metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1081 metadata.key_origin.path.push_back(1 | BIP32_HARDENED_KEY_LIMIT);
1082 metadata.key_origin.path.push_back(hd_chain.nInternalChainCounter |
1084 hd_chain.nInternalChainCounter++;
1085 } else {
1086 chainChildKey.Derive(childKey, hd_chain.nExternalChainCounter |
1088 metadata.hdKeypath =
1089 "m/0'/0'/" + ToString(hd_chain.nExternalChainCounter) + "'";
1090 metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1091 metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1092 metadata.key_origin.path.push_back(hd_chain.nExternalChainCounter |
1094 hd_chain.nExternalChainCounter++;
1095 }
1096 } while (HaveKey(childKey.key.GetPubKey().GetID()));
1097 secret = childKey.key;
1098 metadata.hd_seed_id = hd_chain.seed_id;
1099 CKeyID master_id = masterKey.key.GetPubKey().GetID();
1100 std::copy(master_id.begin(), master_id.begin() + 4,
1101 metadata.key_origin.fingerprint);
1102 metadata.has_key_origin = true;
1103 // update the chain model in the database
1104 if (hd_chain.seed_id == m_hd_chain.seed_id &&
1105 !batch.WriteHDChain(hd_chain)) {
1106 throw std::runtime_error(std::string(__func__) +
1107 ": writing HD chain model failed");
1108 }
1109}
1110
1112 const CKeyPool &keypool) {
1114 if (keypool.m_pre_split) {
1115 set_pre_split_keypool.insert(nIndex);
1116 } else if (keypool.fInternal) {
1117 setInternalKeyPool.insert(nIndex);
1118 } else {
1119 setExternalKeyPool.insert(nIndex);
1120 }
1121 m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
1122 m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
1123
1124 // If no metadata exists yet, create a default with the pool key's
1125 // creation time. Note that this may be overwritten by actually
1126 // stored metadata for that key later, which is fine.
1127 CKeyID keyid = keypool.vchPubKey.GetID();
1128 if (mapKeyMetadata.count(keyid) == 0) {
1129 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
1130 }
1131}
1132
1134 // A wallet can generate keys if it has an HD seed (IsHDEnabled) or it is a
1135 // non-HD wallet (pre FEATURE_HD)
1138}
1139
1142 CKey key;
1143 key.MakeNewKey(true);
1144 return DeriveNewSeed(key);
1145}
1146
1148 int64_t nCreationTime = GetTime();
1149 CKeyMetadata metadata(nCreationTime);
1150
1151 // Calculate the seed
1152 CPubKey seed = key.GetPubKey();
1153 assert(key.VerifyPubKey(seed));
1154
1155 // Set the hd keypath to "s" -> Seed, refers the seed to itself
1156 metadata.hdKeypath = "s";
1157 metadata.has_key_origin = false;
1158 metadata.hd_seed_id = seed.GetID();
1159
1161
1162 // mem store the metadata
1163 mapKeyMetadata[seed.GetID()] = metadata;
1164
1165 // Write the key&metadata to the database
1166 if (!AddKeyPubKey(key, seed)) {
1167 throw std::runtime_error(std::string(__func__) +
1168 ": AddKeyPubKey failed");
1169 }
1170
1171 return seed;
1172}
1173
1176
1177 // Store the keyid (hash160) together with the child index counter in the
1178 // database as a hdchain object.
1179 CHDChain newHdChain;
1183 newHdChain.seed_id = seed.GetID();
1184 AddHDChain(newHdChain);
1188}
1189
1195 return false;
1196 }
1199
1200 for (const int64_t nIndex : setInternalKeyPool) {
1201 batch.ErasePool(nIndex);
1202 }
1203 setInternalKeyPool.clear();
1204
1205 for (const int64_t nIndex : setExternalKeyPool) {
1206 batch.ErasePool(nIndex);
1207 }
1208 setExternalKeyPool.clear();
1209
1210 for (int64_t nIndex : set_pre_split_keypool) {
1211 batch.ErasePool(nIndex);
1212 }
1213 set_pre_split_keypool.clear();
1214
1215 m_pool_key_to_index.clear();
1216
1217 if (!TopUp()) {
1218 return false;
1219 }
1220
1221 WalletLogPrintf("LegacyScriptPubKeyMan::NewKeyPool rewrote keypool\n");
1222 return true;
1223}
1224
1225bool LegacyScriptPubKeyMan::TopUp(unsigned int kpSize) {
1226 if (!CanGenerateKeys()) {
1227 return false;
1228 }
1229 {
1231
1232 if (m_storage.IsLocked()) {
1233 return false;
1234 }
1235
1236 // Top up key pool
1237 unsigned int nTargetSize;
1238 if (kpSize > 0) {
1239 nTargetSize = kpSize;
1240 } else {
1241 nTargetSize = std::max<int64_t>(
1242 gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), 0);
1243 }
1244
1245 // count amount of available keys (internal, external)
1246 // make sure the keypool of external and internal keys fits the user
1247 // selected target (-keypool)
1248 int64_t missingExternal = std::max<int64_t>(
1249 std::max<int64_t>(nTargetSize, 1) - setExternalKeyPool.size(), 0);
1250 int64_t missingInternal = std::max<int64_t>(
1251 std::max<int64_t>(nTargetSize, 1) - setInternalKeyPool.size(), 0);
1252
1254 // don't create extra internal keys
1255 missingInternal = 0;
1256 }
1257 bool internal = false;
1259 for (int64_t i = missingInternal + missingExternal; i--;) {
1260 if (i < missingInternal) {
1261 internal = true;
1262 }
1263
1264 CPubKey pubkey(GenerateNewKey(batch, m_hd_chain, internal));
1265 AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1266 }
1267 if (missingInternal + missingExternal > 0) {
1269 "keypool added %d keys (%d internal), size=%u (%u internal)\n",
1270 missingInternal + missingExternal, missingInternal,
1271 setInternalKeyPool.size() + setExternalKeyPool.size() +
1272 set_pre_split_keypool.size(),
1273 setInternalKeyPool.size());
1274 }
1275 }
1277 return true;
1278}
1279
1281 const bool internal,
1282 WalletBatch &batch) {
1284 // How in the hell did you use so many keys?
1285 assert(m_max_keypool_index < std::numeric_limits<int64_t>::max());
1286 int64_t index = ++m_max_keypool_index;
1287 if (!batch.WritePool(index, CKeyPool(pubkey, internal))) {
1288 throw std::runtime_error(std::string(__func__) +
1289 ": writing imported pubkey failed");
1290 }
1291 if (internal) {
1292 setInternalKeyPool.insert(index);
1293 } else {
1294 setExternalKeyPool.insert(index);
1295 }
1296 m_pool_key_to_index[pubkey.GetID()] = index;
1297}
1298
1300 const OutputType &type) {
1301 // Remove from key pool.
1303 batch.ErasePool(nIndex);
1304 CPubKey pubkey;
1305 bool have_pk = GetPubKey(m_index_to_reserved_key.at(nIndex), pubkey);
1306 assert(have_pk);
1307 LearnRelatedScripts(pubkey, type);
1308 m_index_to_reserved_key.erase(nIndex);
1309 WalletLogPrintf("keypool keep %d\n", nIndex);
1310}
1311
1312void LegacyScriptPubKeyMan::ReturnDestination(int64_t nIndex, bool fInternal,
1313 const CTxDestination &) {
1314 // Return to key pool
1315 {
1317 if (fInternal) {
1318 setInternalKeyPool.insert(nIndex);
1319 } else if (!set_pre_split_keypool.empty()) {
1320 set_pre_split_keypool.insert(nIndex);
1321 } else {
1322 setExternalKeyPool.insert(nIndex);
1323 }
1324 CKeyID &pubkey_id = m_index_to_reserved_key.at(nIndex);
1325 m_pool_key_to_index[pubkey_id] = nIndex;
1326 m_index_to_reserved_key.erase(nIndex);
1328 }
1329
1330 WalletLogPrintf("keypool return %d\n", nIndex);
1331}
1332
1334 const OutputType type,
1335 bool internal) {
1336 if (!CanGetAddresses(internal)) {
1337 return false;
1338 }
1339
1340 CKeyPool keypool;
1342 int64_t nIndex;
1343 if (!ReserveKeyFromKeyPool(nIndex, keypool, internal) &&
1345 if (m_storage.IsLocked()) {
1346 return false;
1347 }
1349 result = GenerateNewKey(batch, m_hd_chain, internal);
1350 return true;
1351 }
1352
1353 KeepDestination(nIndex, type);
1354 result = keypool.vchPubKey;
1355
1356 return true;
1357}
1358
1360 CKeyPool &keypool,
1361 bool fRequestedInternal) {
1362 nIndex = -1;
1363 keypool.vchPubKey = CPubKey();
1364 {
1366
1367 bool fReturningInternal = fRequestedInternal;
1368 fReturningInternal &=
1371 bool use_split_keypool = set_pre_split_keypool.empty();
1372 std::set<int64_t> &setKeyPool =
1373 use_split_keypool
1374 ? (fReturningInternal ? setInternalKeyPool : setExternalKeyPool)
1375 : set_pre_split_keypool;
1376
1377 // Get the oldest key
1378 if (setKeyPool.empty()) {
1379 return false;
1380 }
1381
1383
1384 auto it = setKeyPool.begin();
1385 nIndex = *it;
1386 setKeyPool.erase(it);
1387 if (!batch.ReadPool(nIndex, keypool)) {
1388 throw std::runtime_error(std::string(__func__) + ": read failed");
1389 }
1390 CPubKey pk;
1391 if (!GetPubKey(keypool.vchPubKey.GetID(), pk)) {
1392 throw std::runtime_error(std::string(__func__) +
1393 ": unknown key in key pool");
1394 }
1395 // If the key was pre-split keypool, we don't care about what type it is
1396 if (use_split_keypool && keypool.fInternal != fReturningInternal) {
1397 throw std::runtime_error(std::string(__func__) +
1398 ": keypool entry misclassified");
1399 }
1400 if (!keypool.vchPubKey.IsValid()) {
1401 throw std::runtime_error(std::string(__func__) +
1402 ": keypool entry invalid");
1403 }
1404
1405 assert(m_index_to_reserved_key.count(nIndex) == 0);
1406 m_index_to_reserved_key[nIndex] = keypool.vchPubKey.GetID();
1407 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1408 WalletLogPrintf("keypool reserve %d\n", nIndex);
1409 }
1411 return true;
1412}
1413
1415 OutputType type) {
1416 // Nothing to do...
1417}
1418
1420 // Nothing to do...
1421}
1422
1425 bool internal = setInternalKeyPool.count(keypool_id);
1426 if (!internal) {
1427 assert(setExternalKeyPool.count(keypool_id) ||
1428 set_pre_split_keypool.count(keypool_id));
1429 }
1430
1431 std::set<int64_t> *setKeyPool =
1432 internal ? &setInternalKeyPool
1433 : (set_pre_split_keypool.empty() ? &setExternalKeyPool
1434 : &set_pre_split_keypool);
1435 auto it = setKeyPool->begin();
1436
1438 while (it != std::end(*setKeyPool)) {
1439 const int64_t &index = *(it);
1440 if (index > keypool_id) {
1441 // set*KeyPool is ordered
1442 break;
1443 }
1444
1445 CKeyPool keypool;
1446 if (batch.ReadPool(index, keypool)) {
1447 // TODO: This should be unnecessary
1448 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1449 }
1451 batch.ErasePool(index);
1452 WalletLogPrintf("keypool index %d removed\n", index);
1453 it = setKeyPool->erase(it);
1454 }
1455}
1456
1457std::vector<CKeyID> GetAffectedKeys(const CScript &spk,
1458 const SigningProvider &provider) {
1459 std::vector<CScript> dummy;
1461 InferDescriptor(spk, provider)
1462 ->Expand(0, DUMMY_SIGNING_PROVIDER, dummy, out);
1463 std::vector<CKeyID> ret;
1464 ret.reserve(out.pubkeys.size());
1465 for (const auto &entry : out.pubkeys) {
1466 ret.push_back(entry.first);
1467 }
1468 return ret;
1469}
1470
1473 for (auto it = setExternalKeyPool.begin();
1474 it != setExternalKeyPool.end();) {
1475 int64_t index = *it;
1476 CKeyPool keypool;
1477 if (!batch.ReadPool(index, keypool)) {
1478 throw std::runtime_error(std::string(__func__) +
1479 ": read keypool entry failed");
1480 }
1481 keypool.m_pre_split = true;
1482 if (!batch.WritePool(index, keypool)) {
1483 throw std::runtime_error(std::string(__func__) +
1484 ": writing modified keypool entry failed");
1485 }
1486 set_pre_split_keypool.insert(index);
1487 it = setExternalKeyPool.erase(it);
1488 }
1489}
1490
1493 return AddCScriptWithDB(batch, redeemScript);
1494}
1495
1497 const CScript &redeemScript) {
1499 return false;
1500 }
1503 return true;
1504 }
1505 return false;
1506}
1507
1509 const CPubKey &pubkey,
1510 const KeyOriginInfo &info) {
1512 std::copy(info.fingerprint, info.fingerprint + 4,
1513 mapKeyMetadata[pubkey.GetID()].key_origin.fingerprint);
1514 mapKeyMetadata[pubkey.GetID()].key_origin.path = info.path;
1515 mapKeyMetadata[pubkey.GetID()].has_key_origin = true;
1516 mapKeyMetadata[pubkey.GetID()].hdKeypath = WriteHDKeypath(info.path);
1517 return batch.WriteKeyMetadata(mapKeyMetadata[pubkey.GetID()], pubkey, true);
1518}
1519
1520bool LegacyScriptPubKeyMan::ImportScripts(const std::set<CScript> scripts,
1521 int64_t timestamp) {
1523 for (const auto &entry : scripts) {
1524 CScriptID id(entry);
1525 if (HaveCScript(id)) {
1526 WalletLogPrintf("Already have script %s, skipping\n",
1527 HexStr(entry));
1528 continue;
1529 }
1530 if (!AddCScriptWithDB(batch, entry)) {
1531 return false;
1532 }
1533
1534 if (timestamp > 0) {
1535 m_script_metadata[CScriptID(entry)].nCreateTime = timestamp;
1536 }
1537 }
1538 if (timestamp > 0) {
1539 UpdateTimeFirstKey(timestamp);
1540 }
1541
1542 return true;
1543}
1544
1546 const std::map<CKeyID, CKey> &privkey_map, const int64_t timestamp) {
1548 for (const auto &entry : privkey_map) {
1549 const CKey &key = entry.second;
1550 CPubKey pubkey = key.GetPubKey();
1551 const CKeyID &id = entry.first;
1552 assert(key.VerifyPubKey(pubkey));
1553 // Skip if we already have the key
1554 if (HaveKey(id)) {
1555 WalletLogPrintf("Already have key with pubkey %s, skipping\n",
1556 HexStr(pubkey));
1557 continue;
1558 }
1559 mapKeyMetadata[id].nCreateTime = timestamp;
1560 // If the private key is not present in the wallet, insert it.
1561 if (!AddKeyPubKeyWithDB(batch, key, pubkey)) {
1562 return false;
1563 }
1564 UpdateTimeFirstKey(timestamp);
1565 }
1566 return true;
1567}
1568
1570 const std::vector<CKeyID> &ordered_pubkeys,
1571 const std::map<CKeyID, CPubKey> &pubkey_map,
1572 const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>> &key_origins,
1573 const bool add_keypool, const bool internal, const int64_t timestamp) {
1575 for (const auto &entry : key_origins) {
1576 AddKeyOriginWithDB(batch, entry.second.first, entry.second.second);
1577 }
1578 for (const CKeyID &id : ordered_pubkeys) {
1579 auto entry = pubkey_map.find(id);
1580 if (entry == pubkey_map.end()) {
1581 continue;
1582 }
1583 const CPubKey &pubkey = entry->second;
1584 CPubKey temp;
1585 if (GetPubKey(id, temp)) {
1586 // Already have pubkey, skipping
1587 WalletLogPrintf("Already have pubkey %s, skipping\n", HexStr(temp));
1588 continue;
1589 }
1590 if (!AddWatchOnlyWithDB(batch, GetScriptForRawPubKey(pubkey),
1591 timestamp)) {
1592 return false;
1593 }
1594 mapKeyMetadata[id].nCreateTime = timestamp;
1595
1596 // Add to keypool only works with pubkeys
1597 if (add_keypool) {
1598 AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1600 }
1601 }
1602 return true;
1603}
1604
1606 const std::set<CScript> &script_pub_keys, const bool have_solving_data,
1607 const int64_t timestamp) {
1609 for (const CScript &script : script_pub_keys) {
1610 if (!have_solving_data || !IsMine(script)) {
1611 // Always call AddWatchOnly for non-solvable watch-only, so that
1612 // watch timestamp gets updated
1613 if (!AddWatchOnlyWithDB(batch, script, timestamp)) {
1614 return false;
1615 }
1616 }
1617 }
1618 return true;
1619}
1620
1621std::set<CKeyID> LegacyScriptPubKeyMan::GetKeys() const {
1625 }
1626 std::set<CKeyID> set_address;
1627 for (const auto &mi : mapCryptedKeys) {
1628 set_address.insert(mi.first);
1629 }
1630 return set_address;
1631}
1632
1634
1637 // Returns true if this descriptor supports getting new addresses.
1638 // Conditions where we may be unable to fetch them (e.g. locked) are caught
1639 // later
1641 return util::Error{_("No addresses available")};
1642 }
1643 {
1645 // This is a combo descriptor which should not be an active descriptor
1646 assert(m_wallet_descriptor.descriptor->IsSingleType());
1647 std::optional<OutputType> desc_addr_type =
1648 m_wallet_descriptor.descriptor->GetOutputType();
1649 assert(desc_addr_type);
1650 if (type != *desc_addr_type) {
1651 throw std::runtime_error(std::string(__func__) +
1652 ": Types are inconsistent");
1653 }
1654
1655 TopUp();
1656
1657 // Get the scriptPubKey from the descriptor
1658 FlatSigningProvider out_keys;
1659 std::vector<CScript> scripts_temp;
1660 if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
1661 // We can't generate anymore keys
1662 return util::Error{
1663 _("Error: Keypool ran out, please call keypoolrefill first")};
1664 }
1665 if (!m_wallet_descriptor.descriptor->ExpandFromCache(
1666 m_wallet_descriptor.next_index, m_wallet_descriptor.cache,
1667 scripts_temp, out_keys)) {
1668 // We can't generate anymore keys
1669 return util::Error{
1670 _("Error: Keypool ran out, please call keypoolrefill first")};
1671 }
1672
1673 CTxDestination dest;
1674 std::optional<OutputType> out_script_type =
1675 m_wallet_descriptor.descriptor->GetOutputType();
1676 if (out_script_type && out_script_type == type) {
1677 ExtractDestination(scripts_temp[0], dest);
1678 } else {
1679 throw std::runtime_error(
1680 std::string(__func__) +
1681 ": Types are inconsistent. Stored type does not match type of "
1682 "newly generated address");
1683 }
1684 m_wallet_descriptor.next_index++;
1686 .WriteDescriptor(GetID(), m_wallet_descriptor);
1687 return dest;
1688 }
1689}
1690
1693 if (m_map_script_pub_keys.count(script) > 0) {
1694 return ISMINE_SPENDABLE;
1695 }
1696 return ISMINE_NO;
1697}
1698
1700 const CKeyingMaterial &master_key, bool accept_no_keys) {
1702 if (!m_map_keys.empty()) {
1703 return false;
1704 }
1705
1706 // Always pass when there are no encrypted keys
1707 bool keyPass = m_map_crypted_keys.empty();
1708 bool keyFail = false;
1709 for (const auto &mi : m_map_crypted_keys) {
1710 const CPubKey &pubkey = mi.second.first;
1711 const std::vector<uint8_t> &crypted_secret = mi.second.second;
1712 CKey key;
1713 if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
1714 keyFail = true;
1715 break;
1716 }
1717 keyPass = true;
1719 break;
1720 }
1721 }
1722 if (keyPass && keyFail) {
1723 LogPrintf("The wallet is probably corrupted: Some keys decrypt but not "
1724 "all.\n");
1725 throw std::runtime_error(
1726 "Error unlocking wallet: some keys decrypt but not all. Your "
1727 "wallet file may be corrupt.");
1728 }
1729 if (keyFail || (!keyPass && !accept_no_keys)) {
1730 return false;
1731 }
1733 return true;
1734}
1735
1737 WalletBatch *batch) {
1739 if (!m_map_crypted_keys.empty()) {
1740 return false;
1741 }
1742
1743 for (const KeyMap::value_type &key_in : m_map_keys) {
1744 const CKey &key = key_in.second;
1745 CPubKey pubkey = key.GetPubKey();
1746 CKeyingMaterial secret(key.begin(), key.end());
1747 std::vector<uint8_t> crypted_secret;
1748 if (!EncryptSecret(master_key, secret, pubkey.GetHash(),
1749 crypted_secret)) {
1750 return false;
1751 }
1752 m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1753 batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1754 }
1755 m_map_keys.clear();
1756 return true;
1757}
1758
1760 bool internal,
1761 CTxDestination &address,
1762 int64_t &index,
1763 CKeyPool &keypool) {
1765 auto op_dest = GetNewDestination(type);
1766 index = m_wallet_descriptor.next_index - 1;
1767 if (op_dest) {
1768 address = *op_dest;
1769 }
1770 return bool{op_dest};
1771}
1772
1773void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal,
1774 const CTxDestination &addr) {
1776 // Only return when the index was the most recent
1777 if (m_wallet_descriptor.next_index - 1 == index) {
1778 m_wallet_descriptor.next_index--;
1779 }
1781 .WriteDescriptor(GetID(), m_wallet_descriptor);
1783}
1784
1785std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const {
1788 KeyMap keys;
1789 for (const auto &key_pair : m_map_crypted_keys) {
1790 const CPubKey &pubkey = key_pair.second.first;
1791 const std::vector<uint8_t> &crypted_secret = key_pair.second.second;
1792 CKey key;
1794 [&](const CKeyingMaterial &encryption_key) {
1795 return DecryptKey(encryption_key, crypted_secret, pubkey,
1796 key);
1797 });
1798 keys[pubkey.GetID()] = key;
1799 }
1800 return keys;
1801 }
1802 return m_map_keys;
1803}
1804
1805bool DescriptorScriptPubKeyMan::TopUp(unsigned int size) {
1807 unsigned int target_size;
1808 if (size > 0) {
1809 target_size = size;
1810 } else {
1811 target_size = std::max(
1812 gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), int64_t(1));
1813 }
1814
1815 // Calculate the new range_end
1816 int32_t new_range_end =
1817 std::max(m_wallet_descriptor.next_index + int32_t(target_size),
1818 m_wallet_descriptor.range_end);
1819
1820 // If the descriptor is not ranged, we actually just want to fill the first
1821 // cache item
1822 if (!m_wallet_descriptor.descriptor->IsRange()) {
1823 new_range_end = 1;
1824 m_wallet_descriptor.range_end = 1;
1825 m_wallet_descriptor.range_start = 0;
1826 }
1827
1828 FlatSigningProvider provider;
1829 provider.keys = GetKeys();
1830
1832 uint256 id = GetID();
1833 for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
1834 FlatSigningProvider out_keys;
1835 std::vector<CScript> scripts_temp;
1836 DescriptorCache temp_cache;
1837 // Maybe we have a cached xpub and we can expand from the cache first
1838 if (!m_wallet_descriptor.descriptor->ExpandFromCache(
1839 i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1840 if (!m_wallet_descriptor.descriptor->Expand(
1841 i, provider, scripts_temp, out_keys, &temp_cache)) {
1842 return false;
1843 }
1844 }
1845 // Add all of the scriptPubKeys to the scriptPubKey set
1846 for (const CScript &script : scripts_temp) {
1847 m_map_script_pub_keys[script] = i;
1848 }
1849 for (const auto &pk_pair : out_keys.pubkeys) {
1850 const CPubKey &pubkey = pk_pair.second;
1851 if (m_map_pubkeys.count(pubkey) != 0) {
1852 // We don't need to give an error here.
1853 // It doesn't matter which of many valid indexes the pubkey has,
1854 // we just need an index where we can derive it and it's private
1855 // key
1856 continue;
1857 }
1858 m_map_pubkeys[pubkey] = i;
1859 }
1860 // Write the cache
1861 for (const auto &parent_xpub_pair :
1862 temp_cache.GetCachedParentExtPubKeys()) {
1863 CExtPubKey xpub;
1864 if (m_wallet_descriptor.cache.GetCachedParentExtPubKey(
1865 parent_xpub_pair.first, xpub)) {
1866 if (xpub != parent_xpub_pair.second) {
1867 throw std::runtime_error(
1868 std::string(__func__) +
1869 ": New cached parent xpub does not match already "
1870 "cached parent xpub");
1871 }
1872 continue;
1873 }
1874 if (!batch.WriteDescriptorParentCache(parent_xpub_pair.second, id,
1875 parent_xpub_pair.first)) {
1876 throw std::runtime_error(std::string(__func__) +
1877 ": writing cache item failed");
1878 }
1879 m_wallet_descriptor.cache.CacheParentExtPubKey(
1880 parent_xpub_pair.first, parent_xpub_pair.second);
1881 }
1882 for (const auto &derived_xpub_map_pair :
1883 temp_cache.GetCachedDerivedExtPubKeys()) {
1884 for (const auto &derived_xpub_pair : derived_xpub_map_pair.second) {
1885 CExtPubKey xpub;
1886 if (m_wallet_descriptor.cache.GetCachedDerivedExtPubKey(
1887 derived_xpub_map_pair.first, derived_xpub_pair.first,
1888 xpub)) {
1889 if (xpub != derived_xpub_pair.second) {
1890 throw std::runtime_error(
1891 std::string(__func__) +
1892 ": New cached derived xpub does not match already "
1893 "cached derived xpub");
1894 }
1895 continue;
1896 }
1897 if (!batch.WriteDescriptorDerivedCache(
1898 derived_xpub_pair.second, id,
1899 derived_xpub_map_pair.first, derived_xpub_pair.first)) {
1900 throw std::runtime_error(std::string(__func__) +
1901 ": writing cache item failed");
1902 }
1903 m_wallet_descriptor.cache.CacheDerivedExtPubKey(
1904 derived_xpub_map_pair.first, derived_xpub_pair.first,
1905 derived_xpub_pair.second);
1906 }
1907 }
1909 }
1910 m_wallet_descriptor.range_end = new_range_end;
1911 batch.WriteDescriptor(GetID(), m_wallet_descriptor);
1912
1913 // By this point, the cache size should be the size of the entire range
1914 assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
1915
1917 return true;
1918}
1919
1922 if (IsMine(script)) {
1923 int32_t index = m_map_script_pub_keys[script];
1924 if (index >= m_wallet_descriptor.next_index) {
1925 WalletLogPrintf("%s: Detected a used keypool item at index %d, "
1926 "mark all keypool items up to this item as used\n",
1927 __func__, index);
1928 m_wallet_descriptor.next_index = index + 1;
1929 }
1930 if (!TopUp()) {
1931 WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n",
1932 __func__);
1933 }
1934 }
1935}
1936
1938 const CPubKey &pubkey) {
1941 if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
1942 throw std::runtime_error(std::string(__func__) +
1943 ": writing descriptor private key failed");
1944 }
1945}
1946
1948 const CKey &key,
1949 const CPubKey &pubkey) {
1952
1953 // Check if provided key already exists
1954 if (m_map_keys.find(pubkey.GetID()) != m_map_keys.end() ||
1955 m_map_crypted_keys.find(pubkey.GetID()) != m_map_crypted_keys.end()) {
1956 return true;
1957 }
1958
1960 if (m_storage.IsLocked()) {
1961 return false;
1962 }
1963
1964 std::vector<uint8_t> crypted_secret;
1965 CKeyingMaterial secret(key.begin(), key.end());
1967 [&](const CKeyingMaterial &encryption_key) {
1968 return EncryptSecret(encryption_key, secret,
1969 pubkey.GetHash(), crypted_secret);
1970 })) {
1971 return false;
1972 }
1973
1974 m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1975 return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1976 } else {
1977 m_map_keys[pubkey.GetID()] = key;
1978 return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
1979 }
1980}
1981
1983 const CExtKey &master_key, OutputType addr_type) {
1986
1987 // Ignore when there is already a descriptor
1988 if (m_wallet_descriptor.descriptor) {
1989 return false;
1990 }
1991
1992 int64_t creation_time = GetTime();
1993
1994 std::string xpub = EncodeExtPubKey(master_key.Neuter());
1995
1996 // Build descriptor string
1997 std::string desc_prefix;
1998 std::string desc_suffix = "/*)";
1999 switch (addr_type) {
2000 case OutputType::LEGACY: {
2001 desc_prefix = "pkh(" + xpub + "/44'";
2002 break;
2003 }
2004 } // no default case, so the compiler can warn about missing cases
2005 assert(!desc_prefix.empty());
2006
2007 // Mainnet derives at 0', testnet and regtest derive at 1'
2009 desc_prefix += "/1'";
2010 } else {
2011 desc_prefix += "/0'";
2012 }
2013
2014 std::string internal_path = m_internal ? "/1" : "/0";
2015 std::string desc_str = desc_prefix + "/0'" + internal_path + desc_suffix;
2016
2017 // Make the descriptor
2019 std::string error;
2020 std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, error, false);
2021 WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
2022 m_wallet_descriptor = w_desc;
2023
2024 // Store the master private key, and descriptor
2026 if (!AddDescriptorKeyWithDB(batch, master_key.key,
2027 master_key.key.GetPubKey())) {
2028 throw std::runtime_error(
2029 std::string(__func__) +
2030 ": writing descriptor master private key failed");
2031 }
2032 if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
2033 throw std::runtime_error(std::string(__func__) +
2034 ": writing descriptor failed");
2035 }
2036
2037 // TopUp
2038 TopUp();
2039
2041 return true;
2042}
2043
2046 return m_wallet_descriptor.descriptor->IsRange();
2047}
2048
2050 // We can only give out addresses from descriptors that are single type (not
2051 // combo), ranged, and either have cached keys or can generate more keys
2052 // (ignoring encryption)
2054 return m_wallet_descriptor.descriptor->IsSingleType() &&
2055 m_wallet_descriptor.descriptor->IsRange() &&
2056 (HavePrivateKeys() ||
2057 m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
2058}
2059
2062 return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
2063}
2064
2066 // This is only used for getwalletinfo output and isn't relevant to
2067 // descriptor wallets. The magic number 0 indicates that it shouldn't be
2068 // displayed so that's what we return.
2069 return 0;
2070}
2071
2073 if (m_internal) {
2074 return 0;
2075 }
2076 return GetKeyPoolSize();
2077}
2078
2081 return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
2082}
2083
2086 return m_wallet_descriptor.creation_time;
2087}
2088
2089std::unique_ptr<FlatSigningProvider>
2091 bool include_private) const {
2093
2094 // Find the index of the script
2095 auto it = m_map_script_pub_keys.find(script);
2096 if (it == m_map_script_pub_keys.end()) {
2097 return nullptr;
2098 }
2099 int32_t index = it->second;
2100
2101 return GetSigningProvider(index, include_private);
2102}
2103
2104std::unique_ptr<FlatSigningProvider>
2107
2108 // Find index of the pubkey
2109 auto it = m_map_pubkeys.find(pubkey);
2110 if (it == m_map_pubkeys.end()) {
2111 return nullptr;
2112 }
2113 int32_t index = it->second;
2114
2115 // Always try to get the signing provider with private keys. This function
2116 // should only be called during signing anyways
2117 return GetSigningProvider(index, true);
2118}
2119
2120std::unique_ptr<FlatSigningProvider>
2122 bool include_private) const {
2124 // Get the scripts, keys, and key origins for this script
2125 std::unique_ptr<FlatSigningProvider> out_keys =
2126 std::make_unique<FlatSigningProvider>();
2127 std::vector<CScript> scripts_temp;
2128 if (!m_wallet_descriptor.descriptor->ExpandFromCache(
2129 index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
2130 return nullptr;
2131 }
2132
2133 if (HavePrivateKeys() && include_private) {
2134 FlatSigningProvider master_provider;
2135 master_provider.keys = GetKeys();
2136 m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider,
2137 *out_keys);
2138 }
2139
2140 return out_keys;
2141}
2142
2143std::unique_ptr<SigningProvider>
2145 return GetSigningProvider(script, false);
2146}
2147
2149 SignatureData &sigdata) {
2150 return IsMine(script);
2151}
2152
2154 CMutableTransaction &tx, const std::map<COutPoint, Coin> &coins,
2155 SigHashType sighash, std::map<int, std::string> &input_errors) const {
2156 std::unique_ptr<FlatSigningProvider> keys =
2157 std::make_unique<FlatSigningProvider>();
2158 for (const auto &coin_pair : coins) {
2159 std::unique_ptr<FlatSigningProvider> coin_keys =
2160 GetSigningProvider(coin_pair.second.GetTxOut().scriptPubKey, true);
2161 if (!coin_keys) {
2162 continue;
2163 }
2164 *keys = Merge(*keys, *coin_keys);
2165 }
2166
2167 return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
2168}
2169
2172 const PKHash &pkhash,
2173 std::string &str_sig) const {
2174 std::unique_ptr<FlatSigningProvider> keys =
2176 if (!keys) {
2178 }
2179
2180 CKey key;
2181 if (!keys->GetKey(ToKeyID(pkhash), key)) {
2183 }
2184
2185 if (!MessageSign(key, message, str_sig)) {
2187 }
2188 return SigningResult::OK;
2189}
2190
2191std::optional<PSBTError>
2193 SigHashType sighash_type, bool sign,
2194 bool bip32derivs, bool finalize) const {
2195 for (size_t i = 0; i < psbtx.tx->vin.size(); ++i) {
2196 PSBTInput &input = psbtx.inputs.at(i);
2197
2198 if (PSBTInputSigned(input)) {
2199 continue;
2200 }
2201
2202 // Get the Sighash type
2203 if (sign && input.sighash_type != std::nullopt &&
2204 *input.sighash_type != sighash_type) {
2205 return PSBTError::SIGHASH_MISMATCH;
2206 }
2207
2208 // Get the scriptPubKey to know which SigningProvider to use
2209 CScript script;
2210 if (!input.utxo.IsNull()) {
2211 script = input.utxo.scriptPubKey;
2212 } else {
2213 // There's no UTXO so we can just skip this now
2214 continue;
2215 }
2216 SignatureData sigdata;
2217 input.FillSignatureData(sigdata);
2218
2219 std::unique_ptr<FlatSigningProvider> keys =
2220 std::make_unique<FlatSigningProvider>();
2221 std::unique_ptr<FlatSigningProvider> script_keys =
2223 if (script_keys) {
2224 *keys = Merge(*keys, *script_keys);
2225 } else {
2226 // Maybe there are pubkeys listed that we can sign for
2227 script_keys = std::make_unique<FlatSigningProvider>();
2228 for (const auto &pk_pair : input.hd_keypaths) {
2229 const CPubKey &pubkey = pk_pair.first;
2230 std::unique_ptr<FlatSigningProvider> pk_keys =
2231 GetSigningProvider(pubkey);
2232 if (pk_keys) {
2233 *keys = Merge(*keys, *pk_keys);
2234 }
2235 }
2236 }
2237
2238 SignPSBTInput(HidingSigningProvider(keys.get(), !sign, !bip32derivs),
2239 psbtx, i, sighash_type, /*out_sigdata=*/nullptr,
2240 /*use_dummy=*/false, finalize);
2241 }
2242
2243 // Fill in the bip32 keypaths and redeemscripts for the outputs so that
2244 // hardware wallets can identify change
2245 for (size_t i = 0; i < psbtx.tx->vout.size(); ++i) {
2246 std::unique_ptr<SigningProvider> keys =
2247 GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
2248 if (!keys) {
2249 continue;
2250 }
2251 UpdatePSBTOutput(HidingSigningProvider(keys.get(), true, !bip32derivs),
2252 psbtx, i);
2253 }
2254
2255 return {};
2256}
2257
2258std::unique_ptr<CKeyMetadata>
2260 std::unique_ptr<SigningProvider> provider =
2262 if (provider) {
2263 KeyOriginInfo orig;
2264 CKeyID key_id = GetKeyForDestination(*provider, dest);
2265 if (provider->GetKeyOrigin(key_id, orig)) {
2267 std::unique_ptr<CKeyMetadata> meta =
2268 std::make_unique<CKeyMetadata>();
2269 meta->key_origin = orig;
2270 meta->has_key_origin = true;
2271 meta->nCreateTime = m_wallet_descriptor.creation_time;
2272 return meta;
2273 }
2274 }
2275 return nullptr;
2276}
2277
2280 std::string desc_str = m_wallet_descriptor.descriptor->ToString();
2281 uint256 id;
2282 CSHA256()
2283 .Write((uint8_t *)desc_str.data(), desc_str.size())
2284 .Finalize(id.begin());
2285 return id;
2286}
2287
2289 this->m_internal = internal;
2290}
2291
2294 m_wallet_descriptor.cache = cache;
2295 for (int32_t i = m_wallet_descriptor.range_start;
2296 i < m_wallet_descriptor.range_end; ++i) {
2297 FlatSigningProvider out_keys;
2298 std::vector<CScript> scripts_temp;
2299 if (!m_wallet_descriptor.descriptor->ExpandFromCache(
2300 i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2301 throw std::runtime_error(
2302 "Error: Unable to expand wallet descriptor from cache");
2303 }
2304 // Add all of the scriptPubKeys to the scriptPubKey set
2305 for (const CScript &script : scripts_temp) {
2306 if (m_map_script_pub_keys.count(script) != 0) {
2307 throw std::runtime_error(
2308 strprintf("Error: Already loaded script at index %d as "
2309 "being at index %d",
2310 i, m_map_script_pub_keys[script]));
2311 }
2312 m_map_script_pub_keys[script] = i;
2313 }
2314 for (const auto &pk_pair : out_keys.pubkeys) {
2315 const CPubKey &pubkey = pk_pair.second;
2316 if (m_map_pubkeys.count(pubkey) != 0) {
2317 // We don't need to give an error here.
2318 // It doesn't matter which of many valid indexes the pubkey has,
2319 // we just need an index where we can derive it and it's private
2320 // key
2321 continue;
2322 }
2323 m_map_pubkeys[pubkey] = i;
2324 }
2326 }
2327}
2328
2329bool DescriptorScriptPubKeyMan::AddKey(const CKeyID &key_id, const CKey &key) {
2331 m_map_keys[key_id] = key;
2332 return true;
2333}
2334
2336 const CKeyID &key_id, const CPubKey &pubkey,
2337 const std::vector<uint8_t> &crypted_key) {
2339 if (!m_map_keys.empty()) {
2340 return false;
2341 }
2342
2343 m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
2344 return true;
2345}
2346
2348 const WalletDescriptor &desc) const {
2350 return m_wallet_descriptor.descriptor != nullptr &&
2351 desc.descriptor != nullptr &&
2352 m_wallet_descriptor.descriptor->ToString() ==
2353 desc.descriptor->ToString();
2354}
2355
2359 if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
2360 throw std::runtime_error(std::string(__func__) +
2361 ": writing descriptor failed");
2362 }
2363}
2364
2366 return m_wallet_descriptor;
2367}
2368
2371 std::vector<CScript> script_pub_keys;
2372 script_pub_keys.reserve(m_map_script_pub_keys.size());
2373
2374 for (auto const &script_pub_key : m_map_script_pub_keys) {
2375 script_pub_keys.push_back(script_pub_key.first);
2376 }
2377 return script_pub_keys;
2378}
2379
2381 WalletDescriptor &descriptor) {
2383 std::string error;
2384 if (!CanUpdateToWalletDescriptor(descriptor, error)) {
2385 throw std::runtime_error(std::string(__func__) + ": " + error);
2386 }
2387
2388 m_map_pubkeys.clear();
2389 m_map_script_pub_keys.clear();
2390 m_max_cached_index = -1;
2391 m_wallet_descriptor = descriptor;
2392}
2393
2395 const WalletDescriptor &descriptor, std::string &error) {
2397 if (!HasWalletDescriptor(descriptor)) {
2398 error = "can only update matching descriptor";
2399 return false;
2400 }
2401
2402 if (descriptor.range_start > m_wallet_descriptor.range_start ||
2403 descriptor.range_end < m_wallet_descriptor.range_end) {
2404 // Use inclusive range for error
2405 error = strprintf("new range must include current range = [%d,%d]",
2406 m_wallet_descriptor.range_start,
2407 m_wallet_descriptor.range_end - 1);
2408 return false;
2409 }
2410
2411 return true;
2412}
std::vector< uint8_t > valtype
Definition: addresstype.cpp:16
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: addresstype.cpp:33
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, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: addresstype.h:54
ArgsManager gArgs
Definition: args.cpp:39
bool ParseHDKeypath(const std::string &keypath_str, std::vector< uint32_t > &keypath)
Parse an HD keypaths like "m/7/0'/2000".
Definition: bip32.cpp:13
std::string WriteHDKeypath(const std::vector< uint32_t > &keypath)
Write HD keypaths as strings.
Definition: bip32.cpp:66
const CScript redeemScript
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:494
bool IsTestChain() const
If this chain is exclusively used for testing.
Definition: chainparams.h:118
static const int VERSION_HD_BASE
Definition: walletdb.h:94
uint32_t nInternalChainCounter
Definition: walletdb.h:90
CKeyID seed_id
seed hash160
Definition: walletdb.h:92
static const int VERSION_HD_CHAIN_SPLIT
Definition: walletdb.h:95
int nVersion
Definition: walletdb.h:97
uint32_t nExternalChainCounter
Definition: walletdb.h:89
An encapsulated secp256k1 private key.
Definition: key.h:28
const uint8_t * begin() const
Definition: key.h:93
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:195
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:182
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:209
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:301
const uint8_t * end() const
Definition: key.h:94
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:22
static const int VERSION_WITH_KEY_ORIGIN
Definition: walletdb.h:124
KeyOriginInfo key_origin
Definition: walletdb.h:135
bool has_key_origin
Whether the key_origin is useful.
Definition: walletdb.h:137
int nVersion
Definition: walletdb.h:126
std::string hdKeypath
Definition: walletdb.h:131
int64_t nCreateTime
Definition: walletdb.h:128
CKeyID hd_seed_id
Definition: walletdb.h:133
A key from a CWallet's keypool.
bool fInternal
Whether this keypool entry is in the internal keypool (for change outputs)
CPubKey vchPubKey
The public key.
int64_t nTime
The time at which the key was generated. Set in AddKeypoolPubKeyWithDB.
bool m_pre_split
Whether this key was generated for a keypool before the wallet was upgraded to HD-split.
A mutable version of CTransaction.
Definition: transaction.h:274
An encapsulated public key.
Definition: pubkey.h:31
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:137
bool IsValid() const
Definition: pubkey.h:147
uint256 GetHash() const
Get the 256-bit hash of this public key.
Definition: pubkey.h:140
A hasher class for SHA-256.
Definition: sha256.h:13
CSHA256 & Write(const uint8_t *data, size_t len)
Definition: sha256.cpp:819
void Finalize(uint8_t hash[OUTPUT_SIZE])
Definition: sha256.cpp:844
A reference to a CScript: the Hash160 of its serialization.
Definition: script.h:564
CScript scriptPubKey
Definition: transaction.h:131
bool IsNull() const
Definition: transaction.h:145
Cache for single descriptor's derived extended pubkeys.
Definition: descriptor.h:19
std::unordered_map< uint32_t, ExtPubKeyMap > GetCachedDerivedExtPubKeys() const
Retrieve all cached derived xpubs.
ExtPubKeyMap GetCachedParentExtPubKeys() const
Retrieve all cached parent xpubs.
int64_t GetOldestKeyPoolTime() const override
void ReturnDestination(int64_t index, bool internal, const CTxDestination &addr) override
bool AddKey(const CKeyID &key_id, const CKey &key)
void MarkUnusedAddresses(const CScript &script) override
Mark unused addresses as being used.
bool HavePrivateKeys() const override
bool AddCryptedKey(const CKeyID &key_id, const CPubKey &pubkey, const std::vector< uint8_t > &crypted_key)
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const override
Sign a message with the given script.
bool CanUpdateToWalletDescriptor(const WalletDescriptor &descriptor, std::string &error)
bool TopUp(unsigned int size=0) override
Fills internal address pool.
void SetInternal(bool internal) override
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
bool HasWalletDescriptor(const WalletDescriptor &desc) const
int64_t GetTimeFirstKey() const override
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that,...
bool GetReservedDestination(const OutputType type, bool internal, CTxDestination &address, int64_t &index, CKeyPool &keypool) override
util::Result< CTxDestination > GetNewDestination(const OutputType type) override
unsigned int GetKeyPoolSize() const override
bool SetupDescriptorGeneration(const CExtKey &master_key, OutputType addr_type)
Setup descriptors based on the given CExtkey.
void AddDescriptorKey(const CKey &key, const CPubKey &pubkey)
std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const override
size_t KeypoolCountExternalKeys() const override
bool SignTransaction(CMutableTransaction &tx, const std::map< COutPoint, Coin > &coins, SigHashType sighash, std::map< int, std::string > &input_errors) const override
Creates new signatures and adds them to the transaction.
bool m_decryption_thoroughly_checked
keeps track of whether Unlock has run a thorough check before
KeyMap GetKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
std::unique_ptr< FlatSigningProvider > GetSigningProvider(const CScript &script, bool include_private=false) const
std::map< CKeyID, CKey > KeyMap
bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch) override
bool AddDescriptorKeyWithDB(WalletBatch &batch, const CKey &key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
void UpdateWalletDescriptor(WalletDescriptor &descriptor)
void SetCache(const DescriptorCache &cache)
uint256 GetID() const override
std::optional< common::PSBTError > FillPSBT(PartiallySignedTransaction &psbt, SigHashType sighash_type=SigHashType().withForkId(), bool sign=true, bool bip32derivs=false, bool finalize=true) const override
Adds script and derivation path information to a PSBT, and optionally signs it.
std::vector< CScript > GetScriptPubKeys() const
isminetype IsMine(const CScript &script) const override
bool CheckDecryptionKey(const CKeyingMaterial &master_key, bool accept_no_keys=false) override
Check that the given decryption key is valid for this ScriptPubKeyMan, i.e.
WalletDescriptor GetWalletDescriptor() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
bool IsHDEnabled() const override
bool CanGetAddresses(bool internal=false) const override
Returns true if the wallet can give out new addresses.
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)
virtual std::set< CKeyID > GetKeys() const
std::map< CKeyID, CKey > KeyMap
virtual bool HaveCScript(const CScriptID &hash) const override
RecursiveMutex cs_KeyStore
virtual bool HaveKey(const CKeyID &address) const override
bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const override
std::map< int64_t, CKeyID > m_index_to_reserved_key
void UpgradeKeyMetadata()
Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo.
bool AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector< uint8_t > &vchCryptedSecret)
bool fDecryptionThoroughlyChecked
keeps track of whether Unlock has run a thorough check before
int64_t GetOldestKeyPoolTime() const override
bool GetReservedDestination(const OutputType type, bool internal, CTxDestination &address, int64_t &index, CKeyPool &keypool) override
uint256 GetID() const override
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
void MarkUnusedAddresses(const CScript &script) override
Mark unused addresses as being used.
bool HaveWatchOnly() const
Returns whether there are any watch-only things in the wallet.
bool RemoveWatchOnly(const CScript &dest)
Remove a watch only script from the keystore.
bool AddWatchOnlyInMem(const CScript &dest)
void UpdateTimeFirstKey(int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Update wallet first key creation time.
void AddKeypoolPubkeyWithDB(const CPubKey &pubkey, const bool internal, WalletBatch &batch)
size_t KeypoolCountExternalKeys() const override
void ReturnDestination(int64_t index, bool internal, const CTxDestination &) override
void SetHDSeed(const CPubKey &key)
bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector< uint8_t > &vchCryptedSecret, bool checksum_valid)
Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
std::unordered_map< CKeyID, CHDChain, SaltedSipHasher > m_inactive_hd_chains
bool GetKey(const CKeyID &address, CKey &keyOut) const override
void LearnAllRelatedScripts(const CPubKey &key)
Same as LearnRelatedScripts, but when the OutputType is not known (and could be anything).
bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch) override
isminetype IsMine(const CScript &script) const override
bool ImportScripts(const std::set< CScript > scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const override
bool HaveKey(const CKeyID &address) const override
bool ImportPrivKeys(const std::map< CKeyID, CKey > &privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool TopUpInactiveHDChain(const CKeyID seed_id, int64_t index, bool internal)
Like TopUp() but adds keys for inactive HD chains.
bool CanGetAddresses(bool internal=false) const override
Returns true if the wallet can give out new addresses.
bool AddKeyPubKeyInner(const CKey &key, const CPubKey &pubkey)
void AddHDChain(const CHDChain &chain)
Set the HD chain model (chain child index counters) and writes it to the database.
bool CheckDecryptionKey(const CKeyingMaterial &master_key, bool accept_no_keys=false) override
Check that the given decryption key is valid for this ScriptPubKeyMan, i.e.
void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
Load a keypool entry.
bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< uint8_t > &vchCryptedSecret)
Adds an encrypted key to the store, and saves it to disk.
bool Upgrade(int prev_version, bilingual_str &error) override
Upgrades the wallet to the specified version.
bool IsHDEnabled() const override
util::Result< CTxDestination > GetNewDestination(const OutputType type) override
bool AddWatchOnlyWithDB(WalletBatch &batch, const CScript &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
std::optional< common::PSBTError > FillPSBT(PartiallySignedTransaction &psbt, SigHashType sighash_type=SigHashType().withForkId(), bool sign=true, bool bip32derivs=false, bool finalize=true) const override
Adds script and derivation path information to a PSBT, and optionally signs it.
bool LoadKey(const CKey &key, const CPubKey &pubkey)
Adds a key to the store, without saving it to disk (used by LoadWallet)
bool ImportPubKeys(const std::vector< CKeyID > &ordered_pubkeys, const std::map< CKeyID, CPubKey > &pubkey_map, const std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo > > &key_origins, const bool add_keypool, const bool internal, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool AddKeyOriginWithDB(WalletBatch &batch, const CPubKey &pubkey, const KeyOriginInfo &info)
Add a KeyOriginInfo to the wallet.
bool AddWatchOnly(const CScript &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Private version of AddWatchOnly method which does not accept a timestamp, and which will reset the wa...
bool TopUp(unsigned int size=0) override
Fills internal address pool.
void LoadKeyMetadata(const CKeyID &keyID, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
void MarkReserveKeysAsUsed(int64_t keypool_id) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Marks all keys in the keypool up to and including reserve_key as used.
void LoadHDChain(const CHDChain &chain)
Load a HD chain model (used by LoadWallet)
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
void AddInactiveHDChain(const CHDChain &chain)
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
void LearnRelatedScripts(const CPubKey &key, OutputType)
Explicitly make the wallet learn the related scripts for outputs to the given key.
bool NewKeyPool()
Mark old keypool keys as used, and generate all new keys.
bool ReserveKeyFromKeyPool(int64_t &nIndex, CKeyPool &keypool, bool fRequestedInternal)
Reserves a key from the keypool and sets nIndex to its index.
std::set< CKeyID > GetKeys() const override
void KeepDestination(int64_t index, const OutputType &type) override
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Adds a key to the store, and saves it to disk.
CPubKey GenerateNewKey(WalletBatch &batch, CHDChain &hd_chain, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Generate a new key.
void MarkPreSplitKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
unsigned int GetKeyPoolSize() const override
bool HavePrivateKeys() const override
bool HaveWatchOnly(const CScript &dest) const
Returns whether the watch-only script is in the wallet.
void SetInternal(bool internal) override
bool SetupGeneration(bool force=false) override
Sets up the key generation stuff, i.e.
bool ImportScriptPubKeys(const std::set< CScript > &script_pub_keys, const bool have_solving_data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool AddKeyPubKeyWithDB(WalletBatch &batch, const CKey &key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Adds a key to the store, and saves it to disk.
void RewriteDB() override
The action to do when the DB needs rewrite.
CPubKey DeriveNewSeed(const CKey &key)
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that,...
int64_t GetTimeFirstKey() const override
bool SignTransaction(CMutableTransaction &tx, const std::map< COutPoint, Coin > &coins, SigHashType sighash, std::map< int, std::string > &input_errors) const override
Creates new signatures and adds them to the transaction.
void LoadScriptMetadata(const CScriptID &script_id, const CKeyMetadata &metadata)
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const override
Sign a message with the given script.
bool LoadCScript(const CScript &redeemScript)
Adds a CScript to the store.
bool AddCScript(const CScript &redeemScript) override
bool AddCScriptWithDB(WalletBatch &batch, const CScript &script)
Adds a script to the store and saves it to disk.
std::map< CKeyID, int64_t > m_pool_key_to_index
bool GetKeyFromPool(CPubKey &key, const OutputType type, bool internal=false)
Fetches a key from the keypool.
void DeriveNewChildKey(WalletBatch &batch, CKeyMetadata &metadata, CKey &secret, CHDChain &hd_chain, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
WalletStorage & m_storage
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
void WalletLogPrintf(std::string fmt, Params... parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
Signature hash type wrapper class.
Definition: sighashtype.h:37
An interface to be implemented by keystores that support signing.
Access to the wallet database.
Definition: walletdb.h:175
bool WriteDescriptor(const uint256 &desc_id, const WalletDescriptor &descriptor)
Definition: walletdb.cpp:254
bool WriteDescriptorDerivedCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index, uint32_t der_index)
Definition: walletdb.cpp:259
bool ErasePool(int64_t nPool)
Definition: walletdb.cpp:206
bool WriteDescriptorParentCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index)
Definition: walletdb.cpp:271
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
Definition: walletdb.cpp:160
bool EraseWatchOnly(const CScript &script)
Definition: walletdb.cpp:173
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
Definition: walletdb.cpp:227
bool ReadPool(int64_t nPool, CKeyPool &keypool)
Definition: walletdb.cpp:198
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:114
bool WriteHDChain(const CHDChain &chain)
write the hdchain model (external chain child index counter)
Definition: walletdb.cpp:1099
bool WriteKeyMetadata(const CKeyMetadata &meta, const CPubKey &pubkey, const bool overwrite)
Definition: walletdb.cpp:108
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
Definition: walletdb.cpp:165
bool WritePool(int64_t nPool, const CKeyPool &keypool)
Definition: walletdb.cpp:202
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< uint8_t > &vchCryptedSecret, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:130
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< uint8_t > &secret)
Definition: walletdb.cpp:241
Descriptor with some wallet metadata.
Definition: walletutil.h:80
int32_t range_end
Definition: walletutil.h:89
int32_t range_start
Definition: walletutil.h:86
std::shared_ptr< Descriptor > descriptor
Definition: walletutil.h:82
virtual bool IsWalletFlagSet(uint64_t) const =0
virtual bool HasEncryptionKeys() const =0
virtual bool WithEncryptionKey(const std::function< bool(const CKeyingMaterial &)> &cb) const =0
Pass the encryption key to cb().
virtual WalletDatabase & GetDatabase()=0
virtual bool IsLocked() const =0
virtual void UnsetBlankWalletFlag(WalletBatch &)=0
virtual void SetMinVersion(enum WalletFeature, WalletBatch *=nullptr, bool=false)=0
virtual const CChainParams & GetChainParams() const =0
virtual bool CanSupportFeature(enum WalletFeature) const =0
constexpr bool IsNull() const
Definition: uint256.h:44
constexpr uint8_t * begin()
Definition: uint256.h:122
160-bit opaque blob.
Definition: uint256.h:184
256-bit opaque blob.
Definition: uint256.h:199
static const uint256 ONE
Definition: uint256.h:211
static UniValue Parse(std::string_view raw)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition: client.cpp:234
bool MessageSign(const CKey &privkey, const std::string &message, std::string &signature)
Sign a message.
Definition: signmessage.cpp:54
const Config & GetConfig()
Definition: config.cpp:40
bool DecryptKey(const CKeyingMaterial &vMasterKey, const std::vector< uint8_t > &vchCryptedSecret, const CPubKey &vchPubKey, CKey &key)
Definition: crypter.cpp:145
bool EncryptSecret(const CKeyingMaterial &vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256 &nIV, std::vector< uint8_t > &vchCiphertext)
Definition: crypter.cpp:121
std::vector< uint8_t, secure_allocator< uint8_t > > CKeyingMaterial
Definition: crypter.h:57
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
uint160 Hash160(const T1 &in1)
Compute the 160-bit hash an object.
Definition: hash.h:92
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:30
isminetype
IsMine() return codes.
Definition: ismine.h:18
@ ISMINE_SPENDABLE
Definition: ismine.h:21
@ ISMINE_NO
Definition: ismine.h:19
@ ISMINE_WATCH_ONLY
Definition: ismine.h:20
std::string EncodeDestination(const CTxDestination &dest, const Config &config)
Definition: key_io.cpp:167
std::string EncodeExtPubKey(const CExtPubKey &key)
Definition: key_io.cpp:132
#define LogPrintf(...)
Definition: logging.h:424
PSBTError
Definition: types.h:17
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:156
is a home for public enum and struct type definitions that are used by internally by node code,...
CTxDestination GetDestinationForKey(const CPubKey &key, OutputType type)
Get a destination of the requested type (if possible) to the specified key.
Definition: outputtype.cpp:35
OutputType
Definition: outputtype.h:16
void UpdatePSBTOutput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index)
Updates a PSBTOutput with information from provider.
Definition: psbt.cpp:164
bool SignPSBTInput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index, SigHashType sighash, SignatureData *out_sigdata, bool use_dummy, bool finalize)
Signs a PSBTInput, verifying that all provided data matches what is being signed.
Definition: psbt.cpp:186
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed.
Definition: psbt.cpp:160
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.
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:27
std::vector< uint8_t > valtype
static bool ExtractPubKey(const CScript &dest, CPubKey &pubKeyOut)
std::vector< CKeyID > GetAffectedKeys(const CScript &spk, const SigningProvider &provider)
const uint32_t BIP32_HARDENED_KEY_LIMIT
Value for the first BIP 32 hardened derivation.
static int64_t GetOldestKeyTimeInPool(const std::set< int64_t > &setKeyPool, WalletBatch &batch)
static const unsigned int DEFAULT_KEYPOOL_SIZE
Default for -keypool.
static std::string ToString(const CService &ip)
Definition: db.h:36
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:210
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:431
const SigningProvider & DUMMY_SIGNING_PROVIDER
FlatSigningProvider Merge(const FlatSigningProvider &a, const FlatSigningProvider &b)
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:47
@ PRIVATE_KEY_NOT_AVAILABLE
@ OK
No error.
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< uint8_t > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: solver.cpp:93
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: solver.cpp:143
TxoutType
Definition: solver.h:15
Definition: key.h:167
CExtPubKey Neuter() const
Definition: key.cpp:395
bool Derive(CExtKey &out, unsigned int nChild) const
Definition: key.cpp:373
CKey key
Definition: key.h:172
void SetSeed(Span< const std::byte > seed)
Definition: key.cpp:381
std::map< CKeyID, CPubKey > pubkeys
std::map< CKeyID, CKey > keys
std::vector< uint32_t > path
Definition: keyorigin.h:14
uint8_t fingerprint[4]
First 32 bits of the Hash160 of the public key at the root of the path.
Definition: keyorigin.h:13
A structure for PSBTs which contain per-input information.
Definition: psbt.h:44
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:48
std::optional< SigHashType > sighash_type
Definition: psbt.h:51
void FillSignatureData(SignatureData &sigdata) const
Definition: psbt.cpp:73
CTxOut utxo
Definition: psbt.h:45
A version of CTransaction with the PSBT format.
Definition: psbt.h:336
std::vector< PSBTInput > inputs
Definition: psbt.h:338
std::optional< CMutableTransaction > tx
Definition: psbt.h:337
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input.
Definition: sign.h:77
Bilingual messages:
Definition: translation.h:17
#define LOCK(cs)
Definition: sync.h:295
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition: time.cpp:80
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1203
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:55
@ WALLET_FLAG_KEY_ORIGIN_METADATA
Definition: walletutil.h:51
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:70
@ WALLET_FLAG_BLANK_WALLET
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses,...
Definition: walletutil.h:67
@ FEATURE_HD_SPLIT
Definition: walletutil.h:28
@ FEATURE_PRE_SPLIT_KEYPOOL
Definition: walletutil.h:34
@ FEATURE_HD
Definition: walletutil.h:25
@ FEATURE_COMPRPUBKEY
Definition: walletutil.h:22