Bitcoin ABC 0.30.5
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 <outputtype.h>
11#include <script/descriptor.h>
12#include <script/sign.h>
13#include <util/bip32.h>
14#include <util/strencodings.h>
15#include <util/string.h>
16#include <util/translation.h>
18
21const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
22
24 CTxDestination &dest,
25 std::string &error) {
27 error.clear();
28
29 // Generate a new key that is added to wallet
30 CPubKey new_key;
31 if (!GetKeyFromPool(new_key, type)) {
32 error = _("Error: Keypool ran out, please call keypoolrefill first")
34 return false;
35 }
36 LearnRelatedScripts(new_key, type);
37 dest = GetDestinationForKey(new_key, type);
38 return true;
39}
40
41typedef std::vector<uint8_t> valtype;
42
43namespace {
44
51enum class IsMineSigVersion {
52 TOP = 0,
53 P2SH = 1,
54};
55
61enum class IsMineResult {
62 NO = 0,
63 WATCH_ONLY = 1,
64 SPENDABLE = 2,
65 INVALID = 3,
66};
67
68bool HaveKeys(const std::vector<valtype> &pubkeys,
69 const LegacyScriptPubKeyMan &keystore) {
70 for (const valtype &pubkey : pubkeys) {
71 CKeyID keyID = CPubKey(pubkey).GetID();
72 if (!keystore.HaveKey(keyID)) {
73 return false;
74 }
75 }
76 return true;
77}
78
88IsMineResult IsMineInner(const LegacyScriptPubKeyMan &keystore,
89 const CScript &scriptPubKey,
90 IsMineSigVersion sigversion,
91 bool recurse_scripthash = true) {
92 IsMineResult ret = IsMineResult::NO;
93
94 std::vector<valtype> vSolutions;
95 TxoutType whichType = Solver(scriptPubKey, vSolutions);
96
97 CKeyID keyID;
98 switch (whichType) {
101 break;
103 keyID = CPubKey(vSolutions[0]).GetID();
104 if (keystore.HaveKey(keyID)) {
105 ret = std::max(ret, IsMineResult::SPENDABLE);
106 }
107 break;
109 keyID = CKeyID(uint160(vSolutions[0]));
110 if (keystore.HaveKey(keyID)) {
111 ret = std::max(ret, IsMineResult::SPENDABLE);
112 }
113 break;
115 if (sigversion != IsMineSigVersion::TOP) {
116 // P2SH inside P2SH is invalid.
117 return IsMineResult::INVALID;
118 }
119 CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
120 CScript subscript;
121 if (keystore.GetCScript(scriptID, subscript)) {
122 ret = std::max(ret, recurse_scripthash
123 ? IsMineInner(keystore, subscript,
124 IsMineSigVersion::P2SH)
125 : IsMineResult::SPENDABLE);
126 }
127 break;
128 }
129 case TxoutType::MULTISIG: {
130 // Never treat bare multisig outputs as ours (they can still be made
131 // watchonly-though)
132 if (sigversion == IsMineSigVersion::TOP) {
133 break;
134 }
135
136 // Only consider transactions "mine" if we own ALL the keys
137 // involved. Multi-signature transactions that are partially owned
138 // (somebody else has a key that can spend them) enable
139 // spend-out-from-under-you attacks, especially in shared-wallet
140 // situations.
141 std::vector<valtype> keys(vSolutions.begin() + 1,
142 vSolutions.begin() + vSolutions.size() -
143 1);
144 if (HaveKeys(keys, keystore)) {
145 ret = std::max(ret, IsMineResult::SPENDABLE);
146 }
147 break;
148 }
149 }
150
151 if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
152 ret = std::max(ret, IsMineResult::WATCH_ONLY);
153 }
154 return ret;
155}
156
157} // namespace
158
159isminetype LegacyScriptPubKeyMan::IsMine(const CScript &script) const {
160 switch (IsMineInner(*this, script, IsMineSigVersion::TOP)) {
161 case IsMineResult::INVALID:
162 case IsMineResult::NO:
163 return ISMINE_NO;
164 case IsMineResult::WATCH_ONLY:
165 return ISMINE_WATCH_ONLY;
166 case IsMineResult::SPENDABLE:
167 return ISMINE_SPENDABLE;
168 }
169 assert(false);
170}
171
173 const CKeyingMaterial &master_key, bool accept_no_keys) {
174 {
176 assert(mapKeys.empty());
177
178 // Always pass when there are no encrypted keys
179 bool keyPass = mapCryptedKeys.empty();
180 bool keyFail = false;
181 CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
183 for (; mi != mapCryptedKeys.end(); ++mi) {
184 const CPubKey &vchPubKey = (*mi).second.first;
185 const std::vector<uint8_t> &vchCryptedSecret = (*mi).second.second;
186 CKey key;
187 if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key)) {
188 keyFail = true;
189 break;
190 }
191 keyPass = true;
193 break;
194 } else {
195 // Rewrite these encrypted keys with checksums
196 batch.WriteCryptedKey(vchPubKey, vchCryptedSecret,
197 mapKeyMetadata[vchPubKey.GetID()]);
198 }
199 }
200 if (keyPass && keyFail) {
201 LogPrintf("The wallet is probably corrupted: Some keys decrypt but "
202 "not all.\n");
203 throw std::runtime_error(
204 "Error unlocking wallet: some keys decrypt but not all. Your "
205 "wallet file may be corrupt.");
206 }
207 if (keyFail || (!keyPass && !accept_no_keys)) {
208 return false;
209 }
211 }
212 return true;
213}
214
216 WalletBatch *batch) {
218 encrypted_batch = batch;
219 if (!mapCryptedKeys.empty()) {
220 encrypted_batch = nullptr;
221 return false;
222 }
223
224 KeyMap keys_to_encrypt;
225 // Clear mapKeys so AddCryptedKeyInner will succeed.
226 keys_to_encrypt.swap(mapKeys);
227 for (const KeyMap::value_type &mKey : keys_to_encrypt) {
228 const CKey &key = mKey.second;
229 CPubKey vchPubKey = key.GetPubKey();
230 CKeyingMaterial vchSecret(key.begin(), key.end());
231 std::vector<uint8_t> vchCryptedSecret;
232 if (!EncryptSecret(master_key, vchSecret, vchPubKey.GetHash(),
233 vchCryptedSecret)) {
234 encrypted_batch = nullptr;
235 return false;
236 }
237 if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) {
238 encrypted_batch = nullptr;
239 return false;
240 }
241 }
242 encrypted_batch = nullptr;
243 return true;
244}
245
247 bool internal,
248 CTxDestination &address,
249 int64_t &index,
250 CKeyPool &keypool) {
252 if (!CanGetAddresses(internal)) {
253 return false;
254 }
255
256 if (!ReserveKeyFromKeyPool(index, keypool, internal)) {
257 return false;
258 }
259 address = GetDestinationForKey(keypool.vchPubKey, type);
260 return true;
261}
262
264 int64_t index, bool internal) {
266
267 if (m_storage.IsLocked()) {
268 return false;
269 }
270
271 auto it = m_inactive_hd_chains.find(seed_id);
272 if (it == m_inactive_hd_chains.end()) {
273 return false;
274 }
275
276 CHDChain &chain = it->second;
277
278 // Top up key pool
279 int64_t target_size =
280 std::max(gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t)1);
281
282 // "size" of the keypools. Not really the size, actually the difference
283 // between index and the chain counter Since chain counter is 1 based and
284 // index is 0 based, one of them needs to be offset by 1.
285 int64_t kp_size =
286 (internal ? chain.nInternalChainCounter : chain.nExternalChainCounter) -
287 (index + 1);
288
289 // make sure the keypool fits the user-selected target (-keypool)
290 int64_t missing = std::max(target_size - kp_size, (int64_t)0);
291
292 if (missing > 0) {
294 for (int64_t i = missing; i > 0; --i) {
295 GenerateNewKey(batch, chain, internal);
296 }
297 if (internal) {
298 WalletLogPrintf("inactive seed with id %s added %d internal keys\n",
299 HexStr(seed_id), missing);
300 } else {
301 WalletLogPrintf("inactive seed with id %s added %d keys\n",
302 HexStr(seed_id), missing);
303 }
304 }
305 return true;
306}
307
310 // extract addresses and check if they match with an unused keypool key
311 for (const auto &keyid : GetAffectedKeys(script, *this)) {
312 std::map<CKeyID, int64_t>::const_iterator mi =
313 m_pool_key_to_index.find(keyid);
314 if (mi != m_pool_key_to_index.end()) {
315 WalletLogPrintf("%s: Detected a used keypool key, mark all keypool "
316 "keys up to this key as used\n",
317 __func__);
318 MarkReserveKeysAsUsed(mi->second);
319
320 if (!TopUp()) {
322 "%s: Topping up keypool failed (locked wallet)\n",
323 __func__);
324 }
325 }
326
327 // Find the key's metadata and check if it's seed id (if it has one) is
328 // inactive, i.e. it is not the current m_hd_chain seed id. If so, TopUp
329 // the inactive hd chain
330 auto it = mapKeyMetadata.find(keyid);
331 if (it != mapKeyMetadata.end()) {
332 CKeyMetadata meta = it->second;
333 if (!meta.hd_seed_id.IsNull() &&
334 meta.hd_seed_id != m_hd_chain.seed_id) {
335 bool internal =
336 (meta.key_origin.path[1] & ~BIP32_HARDENED_KEY_LIMIT) != 0;
337 int64_t index =
338 meta.key_origin.path[2] & ~BIP32_HARDENED_KEY_LIMIT;
339
340 if (!TopUpInactiveHDChain(meta.hd_seed_id, index, internal)) {
341 WalletLogPrintf("%s: Adding inactive seed keys failed\n",
342 __func__);
343 }
344 }
345 }
346 }
347}
348
351 if (m_storage.IsLocked() ||
353 return;
354 }
355
356 auto batch = std::make_unique<WalletBatch>(m_storage.GetDatabase());
357 for (auto &meta_pair : mapKeyMetadata) {
358 CKeyMetadata &meta = meta_pair.second;
359 // If the hdKeypath is "s", that's the seed and it doesn't have a key
360 // origin
361 if (!meta.hd_seed_id.IsNull() && !meta.has_key_origin &&
362 meta.hdKeypath != "s") {
363 CKey key;
364 GetKey(meta.hd_seed_id, key);
365 CExtKey masterKey;
366 masterKey.SetSeed(key);
367 // Add to map
368 CKeyID master_id = masterKey.key.GetPubKey().GetID();
369 std::copy(master_id.begin(), master_id.begin() + 4,
371 if (!ParseHDKeypath(meta.hdKeypath, meta.key_origin.path)) {
372 throw std::runtime_error("Invalid stored hdKeypath");
373 }
374 meta.has_key_origin = true;
377 }
378
379 // Write meta to wallet
380 CPubKey pubkey;
381 if (GetPubKey(meta_pair.first, pubkey)) {
382 batch->WriteKeyMetadata(meta, pubkey, true);
383 }
384 }
385 }
386}
387
389 if ((CanGenerateKeys() && !force) || m_storage.IsLocked()) {
390 return false;
391 }
392
394 if (!NewKeyPool()) {
395 return false;
396 }
397 return true;
398}
399
401 return !m_hd_chain.seed_id.IsNull();
402}
403
404bool LegacyScriptPubKeyMan::CanGetAddresses(bool internal) const {
406 // Check if the keypool has keys
407 bool keypool_has_keys;
409 keypool_has_keys = setInternalKeyPool.size() > 0;
410 } else {
411 keypool_has_keys = KeypoolCountExternalKeys() > 0;
412 }
413 // If the keypool doesn't have keys, check if we can generate them
414 if (!keypool_has_keys) {
415 return CanGenerateKeys();
416 }
417 return keypool_has_keys;
418}
419
422 bool hd_upgrade = false;
423 bool split_upgrade = false;
425 WalletLogPrintf("Upgrading wallet to HD\n");
427
428 // generate a new master key
429 CPubKey masterPubKey = GenerateNewSeed();
430 SetHDSeed(masterPubKey);
431 hd_upgrade = true;
432 }
433 // Upgrade to HD chain split if necessary
435 WalletLogPrintf("Upgrading wallet to use HD chain split\n");
437 split_upgrade = FEATURE_HD_SPLIT > prev_version;
438 }
439 // Mark all keys currently in the keypool as pre-split
440 if (split_upgrade) {
442 }
443 // Regenerate the keypool if upgraded to HD
444 if (hd_upgrade) {
445 if (!TopUp()) {
446 error = _("Unable to generate keys");
447 return false;
448 }
449 }
450 return true;
451}
452
455 return !mapKeys.empty() || !mapCryptedKeys.empty();
456}
457
460 setInternalKeyPool.clear();
461 setExternalKeyPool.clear();
462 m_pool_key_to_index.clear();
463 // Note: can't top-up keypool here, because wallet is locked.
464 // User will be prompted to unlock wallet the next operation
465 // that requires a new key.
466}
467
468static int64_t GetOldestKeyTimeInPool(const std::set<int64_t> &setKeyPool,
469 WalletBatch &batch) {
470 if (setKeyPool.empty()) {
471 return GetTime();
472 }
473
474 CKeyPool keypool;
475 int64_t nIndex = *(setKeyPool.begin());
476 if (!batch.ReadPool(nIndex, keypool)) {
477 throw std::runtime_error(std::string(__func__) +
478 ": read oldest key in keypool failed");
479 }
480
481 assert(keypool.vchPubKey.IsValid());
482 return keypool.nTime;
483}
484
487
489
490 // load oldest key from keypool, get time and return
491 int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, batch);
493 oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, batch),
494 oldestKey);
495 if (!set_pre_split_keypool.empty()) {
496 oldestKey =
497 std::max(GetOldestKeyTimeInPool(set_pre_split_keypool, batch),
498 oldestKey);
499 }
500 }
501
502 return oldestKey;
503}
504
507 return setExternalKeyPool.size() + set_pre_split_keypool.size();
508}
509
512 return setInternalKeyPool.size() + setExternalKeyPool.size() +
513 set_pre_split_keypool.size();
514}
515
518 return nTimeFirstKey;
519}
520
521std::unique_ptr<SigningProvider>
522LegacyScriptPubKeyMan::GetSolvingProvider(const CScript &script) const {
523 return std::make_unique<LegacySigningProvider>(*this);
524}
525
526bool LegacyScriptPubKeyMan::CanProvide(const CScript &script,
527 SignatureData &sigdata) {
528 IsMineResult ismine = IsMineInner(*this, script, IsMineSigVersion::TOP,
529 /* recurse_scripthash= */ false);
530 if (ismine == IsMineResult::SPENDABLE ||
531 ismine == IsMineResult::WATCH_ONLY) {
532 // If ismine, it means we recognize keys or script ids in the script, or
533 // are watching the script itself, and we can at least provide metadata
534 // or solving information, even if not able to sign fully.
535 return true;
536 }
537 // If, given the stuff in sigdata, we could make a valid sigature, then
538 // we can provide for this script
539 ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
540 if (!sigdata.signatures.empty()) {
541 // If we could make signatures, make sure we have a private key to
542 // actually make a signature
543 bool has_privkeys = false;
544 for (const auto &key_sig_pair : sigdata.signatures) {
545 has_privkeys |= HaveKey(key_sig_pair.first);
546 }
547 return has_privkeys;
548 }
549 return false;
550}
551
553 CMutableTransaction &tx, const std::map<COutPoint, Coin> &coins,
554 SigHashType sighash, std::map<int, std::string> &input_errors) const {
555 return ::SignTransaction(tx, this, coins, sighash, input_errors);
556}
557
559 const PKHash &pkhash,
560 std::string &str_sig) const {
561 CKey key;
562 if (!GetKey(ToKeyID(pkhash), key)) {
564 }
565
566 if (MessageSign(key, message, str_sig)) {
567 return SigningResult::OK;
568 }
570}
571
574 SigHashType sighash_type, bool sign,
575 bool bip32derivs) const {
576 for (size_t i = 0; i < psbtx.tx->vin.size(); ++i) {
577 PSBTInput &input = psbtx.inputs.at(i);
578
579 if (PSBTInputSigned(input)) {
580 continue;
581 }
582
583 // Get the Sighash type
584 if (sign && input.sighash_type.getRawSigHashType() > 0 &&
585 input.sighash_type != sighash_type) {
587 }
588
589 if (input.utxo.IsNull()) {
590 // There's no UTXO so we can just skip this now
591 continue;
592 }
593 SignatureData sigdata;
594 input.FillSignatureData(sigdata);
595 SignPSBTInput(HidingSigningProvider(this, !sign, !bip32derivs), psbtx,
596 i, sighash_type);
597 }
598
599 // Fill in the bip32 keypaths and redeemscripts for the outputs so that
600 // hardware wallets can identify change
601 for (size_t i = 0; i < psbtx.tx->vout.size(); ++i) {
602 UpdatePSBTOutput(HidingSigningProvider(this, true, !bip32derivs), psbtx,
603 i);
604 }
605
607}
608
609std::unique_ptr<CKeyMetadata>
612
613 CKeyID key_id = GetKeyForDestination(*this, dest);
614 if (!key_id.IsNull()) {
615 auto it = mapKeyMetadata.find(key_id);
616 if (it != mapKeyMetadata.end()) {
617 return std::make_unique<CKeyMetadata>(it->second);
618 }
619 }
620
621 CScript scriptPubKey = GetScriptForDestination(dest);
622 auto it = m_script_metadata.find(CScriptID(scriptPubKey));
623 if (it != m_script_metadata.end()) {
624 return std::make_unique<CKeyMetadata>(it->second);
625 }
626
627 return nullptr;
628}
629
631 return uint256::ONE;
632}
633
640 if (nCreateTime <= 1) {
641 // Cannot determine birthday information, so set the wallet birthday to
642 // the beginning of time.
643 nTimeFirstKey = 1;
644 } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
645 nTimeFirstKey = nCreateTime;
646 }
647}
648
649bool LegacyScriptPubKeyMan::LoadKey(const CKey &key, const CPubKey &pubkey) {
650 return AddKeyPubKeyInner(key, pubkey);
651}
652
654 const CPubKey &pubkey) {
657 return LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(batch, secret, pubkey);
658}
659
661 const CKey &secret,
662 const CPubKey &pubkey) {
664
665 // Make sure we aren't adding private keys to private key disabled wallets
667
668 // FillableSigningProvider has no concept of wallet databases, but calls
669 // AddCryptedKey which is overridden below. To avoid flushes, the database
670 // handle is tunneled through to it.
671 bool needsDB = !encrypted_batch;
672 if (needsDB) {
673 encrypted_batch = &batch;
674 }
675 if (!AddKeyPubKeyInner(secret, pubkey)) {
676 if (needsDB) {
677 encrypted_batch = nullptr;
678 }
679 return false;
680 }
681
682 if (needsDB) {
683 encrypted_batch = nullptr;
684 }
685
686 // Check if we need to remove from watch-only.
687 CScript script;
688 script = GetScriptForDestination(PKHash(pubkey));
689 if (HaveWatchOnly(script)) {
690 RemoveWatchOnly(script);
691 }
692
693 script = GetScriptForRawPubKey(pubkey);
694 if (HaveWatchOnly(script)) {
695 RemoveWatchOnly(script);
696 }
697
699 return batch.WriteKey(pubkey, secret.GetPrivKey(),
700 mapKeyMetadata[pubkey.GetID()]);
701 }
703 return true;
704}
705
706bool LegacyScriptPubKeyMan::LoadCScript(const CScript &redeemScript) {
712 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) {
713 std::string strAddr =
714 EncodeDestination(ScriptHash(redeemScript), GetConfig());
715 WalletLogPrintf("%s: Warning: This wallet contains a redeemScript "
716 "of size %i which exceeds maximum size %i thus can "
717 "never be redeemed. Do not use address %s.\n",
718 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE,
719 strAddr);
720 return true;
721 }
722
723 return FillableSigningProvider::AddCScript(redeemScript);
724}
725
727 const CKeyMetadata &meta) {
730 mapKeyMetadata[keyID] = meta;
731}
732
734 const CKeyMetadata &meta) {
737 m_script_metadata[script_id] = meta;
738}
739
741 const CPubKey &pubkey) {
744 return FillableSigningProvider::AddKeyPubKey(key, pubkey);
745 }
746
747 if (m_storage.IsLocked()) {
748 return false;
749 }
750
751 std::vector<uint8_t> vchCryptedSecret;
752 CKeyingMaterial vchSecret(key.begin(), key.end());
754 [&](const CKeyingMaterial &encryption_key) {
755 return EncryptSecret(encryption_key, vchSecret,
756 pubkey.GetHash(), vchCryptedSecret);
757 })) {
758 return false;
759 }
760
761 if (!AddCryptedKey(pubkey, vchCryptedSecret)) {
762 return false;
763 }
764 return true;
765}
766
768 const CPubKey &vchPubKey, const std::vector<uint8_t> &vchCryptedSecret,
769 bool checksum_valid) {
770 // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
771 if (!checksum_valid) {
773 }
774
775 return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
776}
777
779 const CPubKey &vchPubKey, const std::vector<uint8_t> &vchCryptedSecret) {
781 assert(mapKeys.empty());
782
783 mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
784 return true;
785}
786
788 const CPubKey &vchPubKey, const std::vector<uint8_t> &vchCryptedSecret) {
789 if (!AddCryptedKeyInner(vchPubKey, vchCryptedSecret)) {
790 return false;
791 }
792
794 if (encrypted_batch) {
795 return encrypted_batch->WriteCryptedKey(
796 vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
797 }
798
800 .WriteCryptedKey(vchPubKey, vchCryptedSecret,
801 mapKeyMetadata[vchPubKey.GetID()]);
802}
803
804bool LegacyScriptPubKeyMan::HaveWatchOnly(const CScript &dest) const {
806 return setWatchOnly.count(dest) > 0;
807}
808
811 return (!setWatchOnly.empty());
812}
813
814static bool ExtractPubKey(const CScript &dest, CPubKey &pubKeyOut) {
815 std::vector<std::vector<uint8_t>> solutions;
816 return Solver(dest, solutions) == TxoutType::PUBKEY &&
817 (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
818}
819
820bool LegacyScriptPubKeyMan::RemoveWatchOnly(const CScript &dest) {
821 {
823 setWatchOnly.erase(dest);
824 CPubKey pubKey;
825 if (ExtractPubKey(dest, pubKey)) {
826 mapWatchKeys.erase(pubKey.GetID());
827 }
828 }
829
830 if (!HaveWatchOnly()) {
832 }
833
835}
836
837bool LegacyScriptPubKeyMan::LoadWatchOnly(const CScript &dest) {
838 return AddWatchOnlyInMem(dest);
839}
840
843 setWatchOnly.insert(dest);
844 CPubKey pubKey;
845 if (ExtractPubKey(dest, pubKey)) {
846 mapWatchKeys[pubKey.GetID()] = pubKey;
847 }
848 return true;
849}
850
852 const CScript &dest) {
853 if (!AddWatchOnlyInMem(dest)) {
854 return false;
855 }
856
857 const CKeyMetadata &meta = m_script_metadata[CScriptID(dest)];
860 if (batch.WriteWatchOnly(dest, meta)) {
862 return true;
863 }
864 return false;
865}
866
868 const CScript &dest,
869 int64_t create_time) {
870 m_script_metadata[CScriptID(dest)].nCreateTime = create_time;
871 return AddWatchOnlyWithDB(batch, dest);
872}
873
874bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript &dest) {
876 return AddWatchOnlyWithDB(batch, dest);
877}
878
879bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript &dest,
880 int64_t nCreateTime) {
881 m_script_metadata[CScriptID(dest)].nCreateTime = nCreateTime;
882 return AddWatchOnly(dest);
883}
884
887 m_hd_chain = chain;
888}
889
892 // Store the new chain
894 throw std::runtime_error(std::string(__func__) +
895 ": writing chain failed");
896 }
897 // When there's an old chain, add it as an inactive chain as we are now
898 // rotating hd chains
899 if (!m_hd_chain.seed_id.IsNull()) {
901 }
902
903 m_hd_chain = chain;
904}
905
908 assert(!chain.seed_id.IsNull());
909 m_inactive_hd_chains[chain.seed_id] = chain;
910}
911
912bool LegacyScriptPubKeyMan::HaveKey(const CKeyID &address) const {
915 return FillableSigningProvider::HaveKey(address);
916 }
917 return mapCryptedKeys.count(address) > 0;
918}
919
920bool LegacyScriptPubKeyMan::GetKey(const CKeyID &address, CKey &keyOut) const {
923 return FillableSigningProvider::GetKey(address, keyOut);
924 }
925
926 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
927 if (mi != mapCryptedKeys.end()) {
928 const CPubKey &vchPubKey = (*mi).second.first;
929 const std::vector<uint8_t> &vchCryptedSecret = (*mi).second.second;
931 [&](const CKeyingMaterial &encryption_key) {
932 return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey,
933 keyOut);
934 });
935 }
936 return false;
937}
938
940 KeyOriginInfo &info) const {
941 CKeyMetadata meta;
942 {
944 auto it = mapKeyMetadata.find(keyID);
945 if (it != mapKeyMetadata.end()) {
946 meta = it->second;
947 }
948 }
949 if (meta.has_key_origin) {
950 std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4,
951 info.fingerprint);
952 info.path = meta.key_origin.path;
953 } else {
954 // Single pubkeys get the master fingerprint of themselves
955 std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
956 }
957 return true;
958}
959
961 CPubKey &pubkey_out) const {
963 WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
964 if (it != mapWatchKeys.end()) {
965 pubkey_out = it->second;
966 return true;
967 }
968 return false;
969}
970
972 CPubKey &vchPubKeyOut) const {
975 if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
976 return GetWatchPubKey(address, vchPubKeyOut);
977 }
978 return true;
979 }
980
981 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
982 if (mi != mapCryptedKeys.end()) {
983 vchPubKeyOut = (*mi).second.first;
984 return true;
985 }
986
987 // Check for watch-only pubkeys
988 return GetWatchPubKey(address, vchPubKeyOut);
989}
990
992 CHDChain &hd_chain,
993 bool internal) {
997 // default to compressed public keys if we want 0.6.0 wallets
999
1000 CKey secret;
1001
1002 // Create new metadata
1003 int64_t nCreationTime = GetTime();
1004 CKeyMetadata metadata(nCreationTime);
1005
1006 // use HD key derivation if HD was enabled during wallet creation and a seed
1007 // is present
1008 if (IsHDEnabled()) {
1010 batch, metadata, secret, hd_chain,
1011 (m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
1012 } else {
1013 secret.MakeNewKey(fCompressed);
1014 }
1015
1016 // Compressed public keys were introduced in version 0.6.0
1017 if (fCompressed) {
1019 }
1020
1021 CPubKey pubkey = secret.GetPubKey();
1022 assert(secret.VerifyPubKey(pubkey));
1023
1024 mapKeyMetadata[pubkey.GetID()] = metadata;
1025 UpdateTimeFirstKey(nCreationTime);
1026
1027 if (!AddKeyPubKeyWithDB(batch, secret, pubkey)) {
1028 throw std::runtime_error(std::string(__func__) + ": AddKey failed");
1029 }
1030
1031 return pubkey;
1032}
1033
1035 CKeyMetadata &metadata,
1036 CKey &secret, CHDChain &hd_chain,
1037 bool internal) {
1038 // for now we use a fixed keypath scheme of m/0'/0'/k
1039 // seed (256bit)
1040 CKey seed;
1041 // hd master key
1042 CExtKey masterKey;
1043 // key at m/0'
1044 CExtKey accountKey;
1045 // key at m/0'/0' (external) or m/0'/1' (internal)
1046 CExtKey chainChildKey;
1047 // key at m/0'/0'/<n>'
1048 CExtKey childKey;
1049
1050 // try to get the seed
1051 if (!GetKey(hd_chain.seed_id, seed)) {
1052 throw std::runtime_error(std::string(__func__) + ": seed not found");
1053 }
1054
1055 masterKey.SetSeed(seed);
1056
1057 // derive m/0'
1058 // use hardened derivation (child keys >= 0x80000000 are hardened after
1059 // bip32)
1060 masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
1061
1062 // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
1064 accountKey.Derive(chainChildKey,
1065 BIP32_HARDENED_KEY_LIMIT + (internal ? 1 : 0));
1066
1067 // derive child key at next index, skip keys already known to the wallet
1068 do {
1069 // always derive hardened keys
1070 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened
1071 // child-index-range
1072 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
1073 if (internal) {
1074 chainChildKey.Derive(childKey, hd_chain.nInternalChainCounter |
1076 metadata.hdKeypath =
1077 "m/0'/1'/" + ToString(hd_chain.nInternalChainCounter) + "'";
1078 metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1079 metadata.key_origin.path.push_back(1 | BIP32_HARDENED_KEY_LIMIT);
1080 metadata.key_origin.path.push_back(hd_chain.nInternalChainCounter |
1082 hd_chain.nInternalChainCounter++;
1083 } else {
1084 chainChildKey.Derive(childKey, hd_chain.nExternalChainCounter |
1086 metadata.hdKeypath =
1087 "m/0'/0'/" + ToString(hd_chain.nExternalChainCounter) + "'";
1088 metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1089 metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1090 metadata.key_origin.path.push_back(hd_chain.nExternalChainCounter |
1092 hd_chain.nExternalChainCounter++;
1093 }
1094 } while (HaveKey(childKey.key.GetPubKey().GetID()));
1095 secret = childKey.key;
1096 metadata.hd_seed_id = hd_chain.seed_id;
1097 CKeyID master_id = masterKey.key.GetPubKey().GetID();
1098 std::copy(master_id.begin(), master_id.begin() + 4,
1099 metadata.key_origin.fingerprint);
1100 metadata.has_key_origin = true;
1101 // update the chain model in the database
1102 if (hd_chain.seed_id == m_hd_chain.seed_id &&
1103 !batch.WriteHDChain(hd_chain)) {
1104 throw std::runtime_error(std::string(__func__) +
1105 ": writing HD chain model failed");
1106 }
1107}
1108
1110 const CKeyPool &keypool) {
1112 if (keypool.m_pre_split) {
1113 set_pre_split_keypool.insert(nIndex);
1114 } else if (keypool.fInternal) {
1115 setInternalKeyPool.insert(nIndex);
1116 } else {
1117 setExternalKeyPool.insert(nIndex);
1118 }
1119 m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
1120 m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
1121
1122 // If no metadata exists yet, create a default with the pool key's
1123 // creation time. Note that this may be overwritten by actually
1124 // stored metadata for that key later, which is fine.
1125 CKeyID keyid = keypool.vchPubKey.GetID();
1126 if (mapKeyMetadata.count(keyid) == 0) {
1127 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
1128 }
1129}
1130
1132 // A wallet can generate keys if it has an HD seed (IsHDEnabled) or it is a
1133 // non-HD wallet (pre FEATURE_HD)
1136}
1137
1140 CKey key;
1141 key.MakeNewKey(true);
1142 return DeriveNewSeed(key);
1143}
1144
1146 int64_t nCreationTime = GetTime();
1147 CKeyMetadata metadata(nCreationTime);
1148
1149 // Calculate the seed
1150 CPubKey seed = key.GetPubKey();
1151 assert(key.VerifyPubKey(seed));
1152
1153 // Set the hd keypath to "s" -> Seed, refers the seed to itself
1154 metadata.hdKeypath = "s";
1155 metadata.has_key_origin = false;
1156 metadata.hd_seed_id = seed.GetID();
1157
1159
1160 // mem store the metadata
1161 mapKeyMetadata[seed.GetID()] = metadata;
1162
1163 // Write the key&metadata to the database
1164 if (!AddKeyPubKey(key, seed)) {
1165 throw std::runtime_error(std::string(__func__) +
1166 ": AddKeyPubKey failed");
1167 }
1168
1169 return seed;
1170}
1171
1174
1175 // Store the keyid (hash160) together with the child index counter in the
1176 // database as a hdchain object.
1177 CHDChain newHdChain;
1181 newHdChain.seed_id = seed.GetID();
1182 AddHDChain(newHdChain);
1186}
1187
1193 return false;
1194 }
1197
1198 for (const int64_t nIndex : setInternalKeyPool) {
1199 batch.ErasePool(nIndex);
1200 }
1201 setInternalKeyPool.clear();
1202
1203 for (const int64_t nIndex : setExternalKeyPool) {
1204 batch.ErasePool(nIndex);
1205 }
1206 setExternalKeyPool.clear();
1207
1208 for (int64_t nIndex : set_pre_split_keypool) {
1209 batch.ErasePool(nIndex);
1210 }
1211 set_pre_split_keypool.clear();
1212
1213 m_pool_key_to_index.clear();
1214
1215 if (!TopUp()) {
1216 return false;
1217 }
1218
1219 WalletLogPrintf("LegacyScriptPubKeyMan::NewKeyPool rewrote keypool\n");
1220 return true;
1221}
1222
1223bool LegacyScriptPubKeyMan::TopUp(unsigned int kpSize) {
1224 if (!CanGenerateKeys()) {
1225 return false;
1226 }
1227 {
1229
1230 if (m_storage.IsLocked()) {
1231 return false;
1232 }
1233
1234 // Top up key pool
1235 unsigned int nTargetSize;
1236 if (kpSize > 0) {
1237 nTargetSize = kpSize;
1238 } else {
1239 nTargetSize = std::max<int64_t>(
1240 gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), 0);
1241 }
1242
1243 // count amount of available keys (internal, external)
1244 // make sure the keypool of external and internal keys fits the user
1245 // selected target (-keypool)
1246 int64_t missingExternal = std::max<int64_t>(
1247 std::max<int64_t>(nTargetSize, 1) - setExternalKeyPool.size(), 0);
1248 int64_t missingInternal = std::max<int64_t>(
1249 std::max<int64_t>(nTargetSize, 1) - setInternalKeyPool.size(), 0);
1250
1252 // don't create extra internal keys
1253 missingInternal = 0;
1254 }
1255 bool internal = false;
1257 for (int64_t i = missingInternal + missingExternal; i--;) {
1258 if (i < missingInternal) {
1259 internal = true;
1260 }
1261
1262 CPubKey pubkey(GenerateNewKey(batch, m_hd_chain, internal));
1263 AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1264 }
1265 if (missingInternal + missingExternal > 0) {
1267 "keypool added %d keys (%d internal), size=%u (%u internal)\n",
1268 missingInternal + missingExternal, missingInternal,
1269 setInternalKeyPool.size() + setExternalKeyPool.size() +
1270 set_pre_split_keypool.size(),
1271 setInternalKeyPool.size());
1272 }
1273 }
1275 return true;
1276}
1277
1279 const bool internal,
1280 WalletBatch &batch) {
1282 // How in the hell did you use so many keys?
1283 assert(m_max_keypool_index < std::numeric_limits<int64_t>::max());
1284 int64_t index = ++m_max_keypool_index;
1285 if (!batch.WritePool(index, CKeyPool(pubkey, internal))) {
1286 throw std::runtime_error(std::string(__func__) +
1287 ": writing imported pubkey failed");
1288 }
1289 if (internal) {
1290 setInternalKeyPool.insert(index);
1291 } else {
1292 setExternalKeyPool.insert(index);
1293 }
1294 m_pool_key_to_index[pubkey.GetID()] = index;
1295}
1296
1298 const OutputType &type) {
1299 // Remove from key pool.
1301 batch.ErasePool(nIndex);
1302 CPubKey pubkey;
1303 bool have_pk = GetPubKey(m_index_to_reserved_key.at(nIndex), pubkey);
1304 assert(have_pk);
1305 LearnRelatedScripts(pubkey, type);
1306 m_index_to_reserved_key.erase(nIndex);
1307 WalletLogPrintf("keypool keep %d\n", nIndex);
1308}
1309
1310void LegacyScriptPubKeyMan::ReturnDestination(int64_t nIndex, bool fInternal,
1311 const CTxDestination &) {
1312 // Return to key pool
1313 {
1315 if (fInternal) {
1316 setInternalKeyPool.insert(nIndex);
1317 } else if (!set_pre_split_keypool.empty()) {
1318 set_pre_split_keypool.insert(nIndex);
1319 } else {
1320 setExternalKeyPool.insert(nIndex);
1321 }
1322 CKeyID &pubkey_id = m_index_to_reserved_key.at(nIndex);
1323 m_pool_key_to_index[pubkey_id] = nIndex;
1324 m_index_to_reserved_key.erase(nIndex);
1326 }
1327
1328 WalletLogPrintf("keypool return %d\n", nIndex);
1329}
1330
1332 const OutputType type,
1333 bool internal) {
1334 if (!CanGetAddresses(internal)) {
1335 return false;
1336 }
1337
1338 CKeyPool keypool;
1340 int64_t nIndex;
1341 if (!ReserveKeyFromKeyPool(nIndex, keypool, internal) &&
1343 if (m_storage.IsLocked()) {
1344 return false;
1345 }
1347 result = GenerateNewKey(batch, m_hd_chain, internal);
1348 return true;
1349 }
1350
1351 KeepDestination(nIndex, type);
1352 result = keypool.vchPubKey;
1353
1354 return true;
1355}
1356
1358 CKeyPool &keypool,
1359 bool fRequestedInternal) {
1360 nIndex = -1;
1361 keypool.vchPubKey = CPubKey();
1362 {
1364
1365 bool fReturningInternal = fRequestedInternal;
1366 fReturningInternal &=
1369 bool use_split_keypool = set_pre_split_keypool.empty();
1370 std::set<int64_t> &setKeyPool =
1371 use_split_keypool
1372 ? (fReturningInternal ? setInternalKeyPool : setExternalKeyPool)
1373 : set_pre_split_keypool;
1374
1375 // Get the oldest key
1376 if (setKeyPool.empty()) {
1377 return false;
1378 }
1379
1381
1382 auto it = setKeyPool.begin();
1383 nIndex = *it;
1384 setKeyPool.erase(it);
1385 if (!batch.ReadPool(nIndex, keypool)) {
1386 throw std::runtime_error(std::string(__func__) + ": read failed");
1387 }
1388 CPubKey pk;
1389 if (!GetPubKey(keypool.vchPubKey.GetID(), pk)) {
1390 throw std::runtime_error(std::string(__func__) +
1391 ": unknown key in key pool");
1392 }
1393 // If the key was pre-split keypool, we don't care about what type it is
1394 if (use_split_keypool && keypool.fInternal != fReturningInternal) {
1395 throw std::runtime_error(std::string(__func__) +
1396 ": keypool entry misclassified");
1397 }
1398 if (!keypool.vchPubKey.IsValid()) {
1399 throw std::runtime_error(std::string(__func__) +
1400 ": keypool entry invalid");
1401 }
1402
1403 assert(m_index_to_reserved_key.count(nIndex) == 0);
1404 m_index_to_reserved_key[nIndex] = keypool.vchPubKey.GetID();
1405 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1406 WalletLogPrintf("keypool reserve %d\n", nIndex);
1407 }
1409 return true;
1410}
1411
1413 OutputType type) {
1414 // Nothing to do...
1415}
1416
1418 // Nothing to do...
1419}
1420
1423 bool internal = setInternalKeyPool.count(keypool_id);
1424 if (!internal) {
1425 assert(setExternalKeyPool.count(keypool_id) ||
1426 set_pre_split_keypool.count(keypool_id));
1427 }
1428
1429 std::set<int64_t> *setKeyPool =
1430 internal ? &setInternalKeyPool
1431 : (set_pre_split_keypool.empty() ? &setExternalKeyPool
1432 : &set_pre_split_keypool);
1433 auto it = setKeyPool->begin();
1434
1436 while (it != std::end(*setKeyPool)) {
1437 const int64_t &index = *(it);
1438 if (index > keypool_id) {
1439 // set*KeyPool is ordered
1440 break;
1441 }
1442
1443 CKeyPool keypool;
1444 if (batch.ReadPool(index, keypool)) {
1445 // TODO: This should be unnecessary
1446 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1447 }
1449 batch.ErasePool(index);
1450 WalletLogPrintf("keypool index %d removed\n", index);
1451 it = setKeyPool->erase(it);
1452 }
1453}
1454
1455std::vector<CKeyID> GetAffectedKeys(const CScript &spk,
1456 const SigningProvider &provider) {
1457 std::vector<CScript> dummy;
1459 InferDescriptor(spk, provider)
1460 ->Expand(0, DUMMY_SIGNING_PROVIDER, dummy, out);
1461 std::vector<CKeyID> ret;
1462 for (const auto &entry : out.pubkeys) {
1463 ret.push_back(entry.first);
1464 }
1465 return ret;
1466}
1467
1470 for (auto it = setExternalKeyPool.begin();
1471 it != setExternalKeyPool.end();) {
1472 int64_t index = *it;
1473 CKeyPool keypool;
1474 if (!batch.ReadPool(index, keypool)) {
1475 throw std::runtime_error(std::string(__func__) +
1476 ": read keypool entry failed");
1477 }
1478 keypool.m_pre_split = true;
1479 if (!batch.WritePool(index, keypool)) {
1480 throw std::runtime_error(std::string(__func__) +
1481 ": writing modified keypool entry failed");
1482 }
1483 set_pre_split_keypool.insert(index);
1484 it = setExternalKeyPool.erase(it);
1485 }
1486}
1487
1488bool LegacyScriptPubKeyMan::AddCScript(const CScript &redeemScript) {
1490 return AddCScriptWithDB(batch, redeemScript);
1491}
1492
1494 const CScript &redeemScript) {
1495 if (!FillableSigningProvider::AddCScript(redeemScript)) {
1496 return false;
1497 }
1498 if (batch.WriteCScript(Hash160(redeemScript), redeemScript)) {
1500 return true;
1501 }
1502 return false;
1503}
1504
1506 const CPubKey &pubkey,
1507 const KeyOriginInfo &info) {
1509 std::copy(info.fingerprint, info.fingerprint + 4,
1510 mapKeyMetadata[pubkey.GetID()].key_origin.fingerprint);
1511 mapKeyMetadata[pubkey.GetID()].key_origin.path = info.path;
1512 mapKeyMetadata[pubkey.GetID()].has_key_origin = true;
1513 mapKeyMetadata[pubkey.GetID()].hdKeypath = WriteHDKeypath(info.path);
1514 return batch.WriteKeyMetadata(mapKeyMetadata[pubkey.GetID()], pubkey, true);
1515}
1516
1517bool LegacyScriptPubKeyMan::ImportScripts(const std::set<CScript> scripts,
1518 int64_t timestamp) {
1520 for (const auto &entry : scripts) {
1521 CScriptID id(entry);
1522 if (HaveCScript(id)) {
1523 WalletLogPrintf("Already have script %s, skipping\n",
1524 HexStr(entry));
1525 continue;
1526 }
1527 if (!AddCScriptWithDB(batch, entry)) {
1528 return false;
1529 }
1530
1531 if (timestamp > 0) {
1532 m_script_metadata[CScriptID(entry)].nCreateTime = timestamp;
1533 }
1534 }
1535 if (timestamp > 0) {
1536 UpdateTimeFirstKey(timestamp);
1537 }
1538
1539 return true;
1540}
1541
1543 const std::map<CKeyID, CKey> &privkey_map, const int64_t timestamp) {
1545 for (const auto &entry : privkey_map) {
1546 const CKey &key = entry.second;
1547 CPubKey pubkey = key.GetPubKey();
1548 const CKeyID &id = entry.first;
1549 assert(key.VerifyPubKey(pubkey));
1550 // Skip if we already have the key
1551 if (HaveKey(id)) {
1552 WalletLogPrintf("Already have key with pubkey %s, skipping\n",
1553 HexStr(pubkey));
1554 continue;
1555 }
1556 mapKeyMetadata[id].nCreateTime = timestamp;
1557 // If the private key is not present in the wallet, insert it.
1558 if (!AddKeyPubKeyWithDB(batch, key, pubkey)) {
1559 return false;
1560 }
1561 UpdateTimeFirstKey(timestamp);
1562 }
1563 return true;
1564}
1565
1567 const std::vector<CKeyID> &ordered_pubkeys,
1568 const std::map<CKeyID, CPubKey> &pubkey_map,
1569 const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>> &key_origins,
1570 const bool add_keypool, const bool internal, const int64_t timestamp) {
1572 for (const auto &entry : key_origins) {
1573 AddKeyOriginWithDB(batch, entry.second.first, entry.second.second);
1574 }
1575 for (const CKeyID &id : ordered_pubkeys) {
1576 auto entry = pubkey_map.find(id);
1577 if (entry == pubkey_map.end()) {
1578 continue;
1579 }
1580 const CPubKey &pubkey = entry->second;
1581 CPubKey temp;
1582 if (GetPubKey(id, temp)) {
1583 // Already have pubkey, skipping
1584 WalletLogPrintf("Already have pubkey %s, skipping\n", HexStr(temp));
1585 continue;
1586 }
1587 if (!AddWatchOnlyWithDB(batch, GetScriptForRawPubKey(pubkey),
1588 timestamp)) {
1589 return false;
1590 }
1591 mapKeyMetadata[id].nCreateTime = timestamp;
1592
1593 // Add to keypool only works with pubkeys
1594 if (add_keypool) {
1595 AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1597 }
1598 }
1599 return true;
1600}
1601
1603 const std::set<CScript> &script_pub_keys, const bool have_solving_data,
1604 const int64_t timestamp) {
1606 for (const CScript &script : script_pub_keys) {
1607 if (!have_solving_data || !IsMine(script)) {
1608 // Always call AddWatchOnly for non-solvable watch-only, so that
1609 // watch timestamp gets updated
1610 if (!AddWatchOnlyWithDB(batch, script, timestamp)) {
1611 return false;
1612 }
1613 }
1614 }
1615 return true;
1616}
1617
1618std::set<CKeyID> LegacyScriptPubKeyMan::GetKeys() const {
1622 }
1623 std::set<CKeyID> set_address;
1624 for (const auto &mi : mapCryptedKeys) {
1625 set_address.insert(mi.first);
1626 }
1627 return set_address;
1628}
1629
1631
1633 CTxDestination &dest,
1634 std::string &error) {
1635 // Returns true if this descriptor supports getting new addresses.
1636 // Conditions where we may be unable to fetch them (e.g. locked) are caught
1637 // later
1639 error = "No addresses available";
1640 return false;
1641 }
1642 {
1644 // This is a combo descriptor which should not be an active descriptor
1645 assert(m_wallet_descriptor.descriptor->IsSingleType());
1646 std::optional<OutputType> desc_addr_type =
1647 m_wallet_descriptor.descriptor->GetOutputType();
1648 assert(desc_addr_type);
1649 if (type != *desc_addr_type) {
1650 throw std::runtime_error(std::string(__func__) +
1651 ": Types are inconsistent");
1652 }
1653
1654 TopUp();
1655
1656 // Get the scriptPubKey from the descriptor
1657 FlatSigningProvider out_keys;
1658 std::vector<CScript> scripts_temp;
1659 if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
1660 // We can't generate anymore keys
1661 error = "Error: Keypool ran out, please call keypoolrefill first";
1662 return false;
1663 }
1664 if (!m_wallet_descriptor.descriptor->ExpandFromCache(
1665 m_wallet_descriptor.next_index, m_wallet_descriptor.cache,
1666 scripts_temp, out_keys)) {
1667 // We can't generate anymore keys
1668 error = "Error: Keypool ran out, please call keypoolrefill first";
1669 return false;
1670 }
1671
1672 std::optional<OutputType> out_script_type =
1673 m_wallet_descriptor.descriptor->GetOutputType();
1674 if (out_script_type && out_script_type == type) {
1675 ExtractDestination(scripts_temp[0], dest);
1676 } else {
1677 throw std::runtime_error(
1678 std::string(__func__) +
1679 ": Types are inconsistent. Stored type does not match type of "
1680 "newly generated address");
1681 }
1682 m_wallet_descriptor.next_index++;
1684 .WriteDescriptor(GetID(), m_wallet_descriptor);
1685 return true;
1686 }
1687}
1688
1689isminetype DescriptorScriptPubKeyMan::IsMine(const CScript &script) const {
1691 if (m_map_script_pub_keys.count(script) > 0) {
1692 return ISMINE_SPENDABLE;
1693 }
1694 return ISMINE_NO;
1695}
1696
1698 const CKeyingMaterial &master_key, bool accept_no_keys) {
1700 if (!m_map_keys.empty()) {
1701 return false;
1702 }
1703
1704 // Always pass when there are no encrypted keys
1705 bool keyPass = m_map_crypted_keys.empty();
1706 bool keyFail = false;
1707 for (const auto &mi : m_map_crypted_keys) {
1708 const CPubKey &pubkey = mi.second.first;
1709 const std::vector<uint8_t> &crypted_secret = mi.second.second;
1710 CKey key;
1711 if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
1712 keyFail = true;
1713 break;
1714 }
1715 keyPass = true;
1717 break;
1718 }
1719 }
1720 if (keyPass && keyFail) {
1721 LogPrintf("The wallet is probably corrupted: Some keys decrypt but not "
1722 "all.\n");
1723 throw std::runtime_error(
1724 "Error unlocking wallet: some keys decrypt but not all. Your "
1725 "wallet file may be corrupt.");
1726 }
1727 if (keyFail || (!keyPass && !accept_no_keys)) {
1728 return false;
1729 }
1731 return true;
1732}
1733
1735 WalletBatch *batch) {
1737 if (!m_map_crypted_keys.empty()) {
1738 return false;
1739 }
1740
1741 for (const KeyMap::value_type &key_in : m_map_keys) {
1742 const CKey &key = key_in.second;
1743 CPubKey pubkey = key.GetPubKey();
1744 CKeyingMaterial secret(key.begin(), key.end());
1745 std::vector<uint8_t> crypted_secret;
1746 if (!EncryptSecret(master_key, secret, pubkey.GetHash(),
1747 crypted_secret)) {
1748 return false;
1749 }
1750 m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1751 batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1752 }
1753 m_map_keys.clear();
1754 return true;
1755}
1756
1758 bool internal,
1759 CTxDestination &address,
1760 int64_t &index,
1761 CKeyPool &keypool) {
1763 std::string error;
1764 bool result = GetNewDestination(type, address, error);
1765 index = m_wallet_descriptor.next_index - 1;
1766 return result;
1767}
1768
1769void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal,
1770 const CTxDestination &addr) {
1772 // Only return when the index was the most recent
1773 if (m_wallet_descriptor.next_index - 1 == index) {
1774 m_wallet_descriptor.next_index--;
1775 }
1777 .WriteDescriptor(GetID(), m_wallet_descriptor);
1779}
1780
1781std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const {
1784 KeyMap keys;
1785 for (auto key_pair : m_map_crypted_keys) {
1786 const CPubKey &pubkey = key_pair.second.first;
1787 const std::vector<uint8_t> &crypted_secret = key_pair.second.second;
1788 CKey key;
1790 [&](const CKeyingMaterial &encryption_key) {
1791 return DecryptKey(encryption_key, crypted_secret, pubkey,
1792 key);
1793 });
1794 keys[pubkey.GetID()] = key;
1795 }
1796 return keys;
1797 }
1798 return m_map_keys;
1799}
1800
1801bool DescriptorScriptPubKeyMan::TopUp(unsigned int size) {
1803 unsigned int target_size;
1804 if (size > 0) {
1805 target_size = size;
1806 } else {
1807 target_size = std::max(
1808 gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), int64_t(1));
1809 }
1810
1811 // Calculate the new range_end
1812 int32_t new_range_end =
1813 std::max(m_wallet_descriptor.next_index + int32_t(target_size),
1814 m_wallet_descriptor.range_end);
1815
1816 // If the descriptor is not ranged, we actually just want to fill the first
1817 // cache item
1818 if (!m_wallet_descriptor.descriptor->IsRange()) {
1819 new_range_end = 1;
1820 m_wallet_descriptor.range_end = 1;
1821 m_wallet_descriptor.range_start = 0;
1822 }
1823
1824 FlatSigningProvider provider;
1825 provider.keys = GetKeys();
1826
1828 uint256 id = GetID();
1829 for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
1830 FlatSigningProvider out_keys;
1831 std::vector<CScript> scripts_temp;
1832 DescriptorCache temp_cache;
1833 // Maybe we have a cached xpub and we can expand from the cache first
1834 if (!m_wallet_descriptor.descriptor->ExpandFromCache(
1835 i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1836 if (!m_wallet_descriptor.descriptor->Expand(
1837 i, provider, scripts_temp, out_keys, &temp_cache)) {
1838 return false;
1839 }
1840 }
1841 // Add all of the scriptPubKeys to the scriptPubKey set
1842 for (const CScript &script : scripts_temp) {
1843 m_map_script_pub_keys[script] = i;
1844 }
1845 for (const auto &pk_pair : out_keys.pubkeys) {
1846 const CPubKey &pubkey = pk_pair.second;
1847 if (m_map_pubkeys.count(pubkey) != 0) {
1848 // We don't need to give an error here.
1849 // It doesn't matter which of many valid indexes the pubkey has,
1850 // we just need an index where we can derive it and it's private
1851 // key
1852 continue;
1853 }
1854 m_map_pubkeys[pubkey] = i;
1855 }
1856 // Write the cache
1857 for (const auto &parent_xpub_pair :
1858 temp_cache.GetCachedParentExtPubKeys()) {
1859 CExtPubKey xpub;
1860 if (m_wallet_descriptor.cache.GetCachedParentExtPubKey(
1861 parent_xpub_pair.first, xpub)) {
1862 if (xpub != parent_xpub_pair.second) {
1863 throw std::runtime_error(
1864 std::string(__func__) +
1865 ": New cached parent xpub does not match already "
1866 "cached parent xpub");
1867 }
1868 continue;
1869 }
1870 if (!batch.WriteDescriptorParentCache(parent_xpub_pair.second, id,
1871 parent_xpub_pair.first)) {
1872 throw std::runtime_error(std::string(__func__) +
1873 ": writing cache item failed");
1874 }
1875 m_wallet_descriptor.cache.CacheParentExtPubKey(
1876 parent_xpub_pair.first, parent_xpub_pair.second);
1877 }
1878 for (const auto &derived_xpub_map_pair :
1879 temp_cache.GetCachedDerivedExtPubKeys()) {
1880 for (const auto &derived_xpub_pair : derived_xpub_map_pair.second) {
1881 CExtPubKey xpub;
1882 if (m_wallet_descriptor.cache.GetCachedDerivedExtPubKey(
1883 derived_xpub_map_pair.first, derived_xpub_pair.first,
1884 xpub)) {
1885 if (xpub != derived_xpub_pair.second) {
1886 throw std::runtime_error(
1887 std::string(__func__) +
1888 ": New cached derived xpub does not match already "
1889 "cached derived xpub");
1890 }
1891 continue;
1892 }
1893 if (!batch.WriteDescriptorDerivedCache(
1894 derived_xpub_pair.second, id,
1895 derived_xpub_map_pair.first, derived_xpub_pair.first)) {
1896 throw std::runtime_error(std::string(__func__) +
1897 ": writing cache item failed");
1898 }
1899 m_wallet_descriptor.cache.CacheDerivedExtPubKey(
1900 derived_xpub_map_pair.first, derived_xpub_pair.first,
1901 derived_xpub_pair.second);
1902 }
1903 }
1905 }
1906 m_wallet_descriptor.range_end = new_range_end;
1907 batch.WriteDescriptor(GetID(), m_wallet_descriptor);
1908
1909 // By this point, the cache size should be the size of the entire range
1910 assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
1911
1913 return true;
1914}
1915
1918 if (IsMine(script)) {
1919 int32_t index = m_map_script_pub_keys[script];
1920 if (index >= m_wallet_descriptor.next_index) {
1921 WalletLogPrintf("%s: Detected a used keypool item at index %d, "
1922 "mark all keypool items up to this item as used\n",
1923 __func__, index);
1924 m_wallet_descriptor.next_index = index + 1;
1925 }
1926 if (!TopUp()) {
1927 WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n",
1928 __func__);
1929 }
1930 }
1931}
1932
1934 const CPubKey &pubkey) {
1937 if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
1938 throw std::runtime_error(std::string(__func__) +
1939 ": writing descriptor private key failed");
1940 }
1941}
1942
1944 const CKey &key,
1945 const CPubKey &pubkey) {
1948
1949 // Check if provided key already exists
1950 if (m_map_keys.find(pubkey.GetID()) != m_map_keys.end() ||
1951 m_map_crypted_keys.find(pubkey.GetID()) != m_map_crypted_keys.end()) {
1952 return true;
1953 }
1954
1956 if (m_storage.IsLocked()) {
1957 return false;
1958 }
1959
1960 std::vector<uint8_t> crypted_secret;
1961 CKeyingMaterial secret(key.begin(), key.end());
1963 [&](const CKeyingMaterial &encryption_key) {
1964 return EncryptSecret(encryption_key, secret,
1965 pubkey.GetHash(), crypted_secret);
1966 })) {
1967 return false;
1968 }
1969
1970 m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1971 return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1972 } else {
1973 m_map_keys[pubkey.GetID()] = key;
1974 return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
1975 }
1976}
1977
1979 const CExtKey &master_key, OutputType addr_type) {
1982
1983 // Ignore when there is already a descriptor
1984 if (m_wallet_descriptor.descriptor) {
1985 return false;
1986 }
1987
1988 int64_t creation_time = GetTime();
1989
1990 std::string xpub = EncodeExtPubKey(master_key.Neuter());
1991
1992 // Build descriptor string
1993 std::string desc_prefix;
1994 std::string desc_suffix = "/*)";
1995 switch (addr_type) {
1996 case OutputType::LEGACY: {
1997 desc_prefix = "pkh(" + xpub + "/44'";
1998 break;
1999 }
2000 } // no default case, so the compiler can warn about missing cases
2001 assert(!desc_prefix.empty());
2002
2003 // Mainnet derives at 0', testnet and regtest derive at 1'
2005 desc_prefix += "/1'";
2006 } else {
2007 desc_prefix += "/0'";
2008 }
2009
2010 std::string internal_path = m_internal ? "/1" : "/0";
2011 std::string desc_str = desc_prefix + "/0'" + internal_path + desc_suffix;
2012
2013 // Make the descriptor
2015 std::string error;
2016 std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, error, false);
2017 WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
2018 m_wallet_descriptor = w_desc;
2019
2020 // Store the master private key, and descriptor
2022 if (!AddDescriptorKeyWithDB(batch, master_key.key,
2023 master_key.key.GetPubKey())) {
2024 throw std::runtime_error(
2025 std::string(__func__) +
2026 ": writing descriptor master private key failed");
2027 }
2028 if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
2029 throw std::runtime_error(std::string(__func__) +
2030 ": writing descriptor failed");
2031 }
2032
2033 // TopUp
2034 TopUp();
2035
2037 return true;
2038}
2039
2042 return m_wallet_descriptor.descriptor->IsRange();
2043}
2044
2046 // We can only give out addresses from descriptors that are single type (not
2047 // combo), ranged, and either have cached keys or can generate more keys
2048 // (ignoring encryption)
2050 return m_wallet_descriptor.descriptor->IsSingleType() &&
2051 m_wallet_descriptor.descriptor->IsRange() &&
2052 (HavePrivateKeys() ||
2053 m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
2054}
2055
2058 return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
2059}
2060
2062 // This is only used for getwalletinfo output and isn't relevant to
2063 // descriptor wallets. The magic number 0 indicates that it shouldn't be
2064 // displayed so that's what we return.
2065 return 0;
2066}
2067
2069 if (m_internal) {
2070 return 0;
2071 }
2072 return GetKeyPoolSize();
2073}
2074
2077 return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
2078}
2079
2082 return m_wallet_descriptor.creation_time;
2083}
2084
2085std::unique_ptr<FlatSigningProvider>
2087 bool include_private) const {
2089
2090 // Find the index of the script
2091 auto it = m_map_script_pub_keys.find(script);
2092 if (it == m_map_script_pub_keys.end()) {
2093 return nullptr;
2094 }
2095 int32_t index = it->second;
2096
2097 return GetSigningProvider(index, include_private);
2098}
2099
2100std::unique_ptr<FlatSigningProvider>
2103
2104 // Find index of the pubkey
2105 auto it = m_map_pubkeys.find(pubkey);
2106 if (it == m_map_pubkeys.end()) {
2107 return nullptr;
2108 }
2109 int32_t index = it->second;
2110
2111 // Always try to get the signing provider with private keys. This function
2112 // should only be called during signing anyways
2113 return GetSigningProvider(index, true);
2114}
2115
2116std::unique_ptr<FlatSigningProvider>
2118 bool include_private) const {
2120 // Get the scripts, keys, and key origins for this script
2121 std::unique_ptr<FlatSigningProvider> out_keys =
2122 std::make_unique<FlatSigningProvider>();
2123 std::vector<CScript> scripts_temp;
2124 if (!m_wallet_descriptor.descriptor->ExpandFromCache(
2125 index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
2126 return nullptr;
2127 }
2128
2129 if (HavePrivateKeys() && include_private) {
2130 FlatSigningProvider master_provider;
2131 master_provider.keys = GetKeys();
2132 m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider,
2133 *out_keys);
2134 }
2135
2136 return out_keys;
2137}
2138
2139std::unique_ptr<SigningProvider>
2141 return GetSigningProvider(script, false);
2142}
2143
2144bool DescriptorScriptPubKeyMan::CanProvide(const CScript &script,
2145 SignatureData &sigdata) {
2146 return IsMine(script);
2147}
2148
2150 CMutableTransaction &tx, const std::map<COutPoint, Coin> &coins,
2151 SigHashType sighash, std::map<int, std::string> &input_errors) const {
2152 std::unique_ptr<FlatSigningProvider> keys =
2153 std::make_unique<FlatSigningProvider>();
2154 for (const auto &coin_pair : coins) {
2155 std::unique_ptr<FlatSigningProvider> coin_keys =
2156 GetSigningProvider(coin_pair.second.GetTxOut().scriptPubKey, true);
2157 if (!coin_keys) {
2158 continue;
2159 }
2160 *keys = Merge(*keys, *coin_keys);
2161 }
2162
2163 return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
2164}
2165
2168 const PKHash &pkhash,
2169 std::string &str_sig) const {
2170 std::unique_ptr<FlatSigningProvider> keys =
2172 if (!keys) {
2174 }
2175
2176 CKey key;
2177 if (!keys->GetKey(ToKeyID(pkhash), key)) {
2179 }
2180
2181 if (!MessageSign(key, message, str_sig)) {
2183 }
2184 return SigningResult::OK;
2185}
2186
2189 SigHashType sighash_type, bool sign,
2190 bool bip32derivs) const {
2191 for (size_t i = 0; i < psbtx.tx->vin.size(); ++i) {
2192 PSBTInput &input = psbtx.inputs.at(i);
2193
2194 if (PSBTInputSigned(input)) {
2195 continue;
2196 }
2197
2198 // Get the Sighash type
2199 if (sign && input.sighash_type.getRawSigHashType() > 0 &&
2200 input.sighash_type != sighash_type) {
2202 }
2203
2204 // Get the scriptPubKey to know which SigningProvider to use
2205 CScript script;
2206 if (!input.utxo.IsNull()) {
2207 script = input.utxo.scriptPubKey;
2208 } else {
2209 // There's no UTXO so we can just skip this now
2210 continue;
2211 }
2212 SignatureData sigdata;
2213 input.FillSignatureData(sigdata);
2214
2215 std::unique_ptr<FlatSigningProvider> keys =
2216 std::make_unique<FlatSigningProvider>();
2217 std::unique_ptr<FlatSigningProvider> script_keys =
2218 GetSigningProvider(script, sign);
2219 if (script_keys) {
2220 *keys = Merge(*keys, *script_keys);
2221 } else {
2222 // Maybe there are pubkeys listed that we can sign for
2223 script_keys = std::make_unique<FlatSigningProvider>();
2224 for (const auto &pk_pair : input.hd_keypaths) {
2225 const CPubKey &pubkey = pk_pair.first;
2226 std::unique_ptr<FlatSigningProvider> pk_keys =
2227 GetSigningProvider(pubkey);
2228 if (pk_keys) {
2229 *keys = Merge(*keys, *pk_keys);
2230 }
2231 }
2232 }
2233
2234 SignPSBTInput(HidingSigningProvider(keys.get(), !sign, !bip32derivs),
2235 psbtx, i, sighash_type);
2236 }
2237
2238 // Fill in the bip32 keypaths and redeemscripts for the outputs so that
2239 // hardware wallets can identify change
2240 for (size_t i = 0; i < psbtx.tx->vout.size(); ++i) {
2241 std::unique_ptr<SigningProvider> keys =
2242 GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
2243 if (!keys) {
2244 continue;
2245 }
2246 UpdatePSBTOutput(HidingSigningProvider(keys.get(), true, !bip32derivs),
2247 psbtx, i);
2248 }
2249
2250 return TransactionError::OK;
2251}
2252
2253std::unique_ptr<CKeyMetadata>
2255 std::unique_ptr<SigningProvider> provider =
2257 if (provider) {
2258 KeyOriginInfo orig;
2259 CKeyID key_id = GetKeyForDestination(*provider, dest);
2260 if (provider->GetKeyOrigin(key_id, orig)) {
2262 std::unique_ptr<CKeyMetadata> meta =
2263 std::make_unique<CKeyMetadata>();
2264 meta->key_origin = orig;
2265 meta->has_key_origin = true;
2266 meta->nCreateTime = m_wallet_descriptor.creation_time;
2267 return meta;
2268 }
2269 }
2270 return nullptr;
2271}
2272
2275 std::string desc_str = m_wallet_descriptor.descriptor->ToString();
2276 uint256 id;
2277 CSHA256()
2278 .Write((uint8_t *)desc_str.data(), desc_str.size())
2279 .Finalize(id.begin());
2280 return id;
2281}
2282
2284 this->m_internal = internal;
2285}
2286
2289 m_wallet_descriptor.cache = cache;
2290 for (int32_t i = m_wallet_descriptor.range_start;
2291 i < m_wallet_descriptor.range_end; ++i) {
2292 FlatSigningProvider out_keys;
2293 std::vector<CScript> scripts_temp;
2294 if (!m_wallet_descriptor.descriptor->ExpandFromCache(
2295 i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2296 throw std::runtime_error(
2297 "Error: Unable to expand wallet descriptor from cache");
2298 }
2299 // Add all of the scriptPubKeys to the scriptPubKey set
2300 for (const CScript &script : scripts_temp) {
2301 if (m_map_script_pub_keys.count(script) != 0) {
2302 throw std::runtime_error(
2303 strprintf("Error: Already loaded script at index %d as "
2304 "being at index %d",
2305 i, m_map_script_pub_keys[script]));
2306 }
2307 m_map_script_pub_keys[script] = i;
2308 }
2309 for (const auto &pk_pair : out_keys.pubkeys) {
2310 const CPubKey &pubkey = pk_pair.second;
2311 if (m_map_pubkeys.count(pubkey) != 0) {
2312 // We don't need to give an error here.
2313 // It doesn't matter which of many valid indexes the pubkey has,
2314 // we just need an index where we can derive it and it's private
2315 // key
2316 continue;
2317 }
2318 m_map_pubkeys[pubkey] = i;
2319 }
2321 }
2322}
2323
2324bool DescriptorScriptPubKeyMan::AddKey(const CKeyID &key_id, const CKey &key) {
2326 m_map_keys[key_id] = key;
2327 return true;
2328}
2329
2331 const CKeyID &key_id, const CPubKey &pubkey,
2332 const std::vector<uint8_t> &crypted_key) {
2334 if (!m_map_keys.empty()) {
2335 return false;
2336 }
2337
2338 m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
2339 return true;
2340}
2341
2343 const WalletDescriptor &desc) const {
2345 return m_wallet_descriptor.descriptor != nullptr &&
2346 desc.descriptor != nullptr &&
2347 m_wallet_descriptor.descriptor->ToString() ==
2348 desc.descriptor->ToString();
2349}
2350
2354 if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
2355 throw std::runtime_error(std::string(__func__) +
2356 ": writing descriptor failed");
2357 }
2358}
2359
2361 return m_wallet_descriptor;
2362}
2363
2364const std::vector<CScript> DescriptorScriptPubKeyMan::GetScriptPubKeys() const {
2366 std::vector<CScript> script_pub_keys;
2367 script_pub_keys.reserve(m_map_script_pub_keys.size());
2368
2369 for (auto const &script_pub_key : m_map_script_pub_keys) {
2370 script_pub_keys.push_back(script_pub_key.first);
2371 }
2372 return script_pub_keys;
2373}
2374
2376 WalletDescriptor &descriptor) {
2378 std::string error;
2379 if (!CanUpdateToWalletDescriptor(descriptor, error)) {
2380 throw std::runtime_error(std::string(__func__) + ": " + error);
2381 }
2382
2383 m_map_pubkeys.clear();
2384 m_map_script_pub_keys.clear();
2385 m_max_cached_index = -1;
2386 m_wallet_descriptor = descriptor;
2387}
2388
2390 const WalletDescriptor &descriptor, std::string &error) {
2392 if (!HasWalletDescriptor(descriptor)) {
2393 error = "can only update matching descriptor";
2394 return false;
2395 }
2396
2397 if (descriptor.range_start > m_wallet_descriptor.range_start ||
2398 descriptor.range_end < m_wallet_descriptor.range_end) {
2399 // Use inclusive range for error
2400 error = strprintf("new range must include current range = [%d,%d]",
2401 m_wallet_descriptor.range_start,
2402 m_wallet_descriptor.range_end - 1);
2403 return false;
2404 }
2405
2406 return true;
2407}
ArgsManager gArgs
Definition: args.cpp:38
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
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:526
bool IsTestChain() const
If this chain is exclusively used for testing.
Definition: chainparams.h:111
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:196
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:183
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:210
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:302
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 (see script.h)
Definition: standard.h:24
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
const ExtPubKeyMap GetCachedParentExtPubKeys() const
Retrieve all cached parent xpubs.
const std::unordered_map< uint32_t, ExtPubKeyMap > GetCachedDerivedExtPubKeys() const
Retrieve all cached derived 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)
TransactionError FillPSBT(PartiallySignedTransaction &psbt, SigHashType sighash_type=SigHashType().withForkId(), bool sign=true, bool bip32derivs=false) const override
Adds script and derivation path information to a PSBT, and optionally signs it.
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
bool GetNewDestination(const OutputType type, CTxDestination &dest, std::string &error) 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
const std::vector< CScript > GetScriptPubKeys() 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
const WalletDescriptor GetWalletDescriptor() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
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.
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 GetNewDestination(const OutputType type, CTxDestination &dest, std::string &error) override
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
bool AddWatchOnlyWithDB(WalletBatch &batch, const CScript &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
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.
TransactionError FillPSBT(PartiallySignedTransaction &psbt, SigHashType sighash_type=SigHashType().withForkId(), bool sign=true, bool bip32derivs=false) const override
Adds script and derivation path information to a PSBT, and optionally signs it.
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
uint32_t getRawSigHashType() const
Definition: sighashtype.h:83
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:253
bool WriteDescriptorDerivedCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index, uint32_t der_index)
Definition: walletdb.cpp:258
bool ErasePool(int64_t nPool)
Definition: walletdb.cpp:205
bool WriteDescriptorParentCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index)
Definition: walletdb.cpp:270
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
Definition: walletdb.cpp:159
bool EraseWatchOnly(const CScript &script)
Definition: walletdb.cpp:172
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
Definition: walletdb.cpp:226
bool ReadPool(int64_t nPool, CKeyPool &keypool)
Definition: walletdb.cpp:197
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:113
bool WriteHDChain(const CHDChain &chain)
write the hdchain model (external chain child index counter)
Definition: walletdb.cpp:1100
bool WriteKeyMetadata(const CKeyMetadata &meta, const CPubKey &pubkey, const bool overwrite)
Definition: walletdb.cpp:107
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
Definition: walletdb.cpp:164
bool WritePool(int64_t nPool, const CKeyPool &keypool)
Definition: walletdb.cpp:201
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< uint8_t > &vchCryptedSecret, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:129
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< uint8_t > &secret)
Definition: walletdb.cpp:240
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
uint8_t * begin()
Definition: uint256.h:85
bool IsNull() const
Definition: uint256.h:32
160-bit opaque blob.
Definition: uint256.h:117
256-bit opaque blob.
Definition: uint256.h:129
static const uint256 ONE
Definition: uint256.h:135
static UniValue Parse(std::string_view raw)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition: client.cpp:225
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:146
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.
TransactionError
Definition: error.h:22
uint160 Hash160(const T1 &in1)
Compute the 160-bit hash an object.
Definition: hash.h:92
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
bool error(const char *fmt, const Args &...args)
Definition: logging.h:226
#define LogPrintf(...)
Definition: logging.h:207
bool MessageSign(const CKey &privkey, const std::string &message, std::string &signature)
Sign a message.
Definition: message.cpp:54
SigningResult
Definition: message.h:47
@ PRIVATE_KEY_NOT_AVAILABLE
@ OK
No error.
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 PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed.
Definition: psbt.cpp:160
bool SignPSBTInput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index, SigHashType sighash, SignatureData *out_sigdata, bool use_dummy)
Signs a PSBTInput, verifying that all provided data matches what is being signed.
Definition: psbt.cpp:186
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:24
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.
std::vector< uint8_t > valtype
Definition: sigencoding.h:16
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:198
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:419
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).
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:158
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< uint8_t > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:108
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:244
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:240
CKeyID ToKeyID(const PKHash &key_hash)
Definition: standard.cpp:25
TxoutType
Definition: standard.h:38
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:85
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:100
Definition: key.h:167
CExtPubKey Neuter() const
Definition: key.cpp:396
bool Derive(CExtKey &out, unsigned int nChild) const
Definition: key.cpp:374
CKey key
Definition: key.h:172
void SetSeed(Span< const std::byte > seed)
Definition: key.cpp:382
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
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:334
std::vector< PSBTInput > inputs
Definition: psbt.h:336
std::optional< CMutableTransaction > tx
Definition: psbt.h:335
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input.
Definition: sign.h:76
Bilingual messages:
Definition: translation.h:17
std::string translated
Definition: translation.h:19
#define LOCK(cs)
Definition: sync.h:306
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition: time.cpp:109
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
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