Bitcoin ABC 0.32.4
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
26
27 // Generate a new key that is added to wallet
28 CPubKey new_key;
29 if (!GetKeyFromPool(new_key, type)) {
30 return util::Error{
31 _("Error: Keypool ran out, please call keypoolrefill first")};
32 }
33 LearnRelatedScripts(new_key, type);
34 return GetDestinationForKey(new_key, type);
35}
36
37typedef std::vector<uint8_t> valtype;
38
39namespace {
40
47enum class IsMineSigVersion {
48 TOP = 0,
49 P2SH = 1,
50};
51
57enum class IsMineResult {
58 NO = 0,
59 WATCH_ONLY = 1,
60 SPENDABLE = 2,
61 INVALID = 3,
62};
63
64bool HaveKeys(const std::vector<valtype> &pubkeys,
65 const LegacyScriptPubKeyMan &keystore) {
66 for (const valtype &pubkey : pubkeys) {
67 CKeyID keyID = CPubKey(pubkey).GetID();
68 if (!keystore.HaveKey(keyID)) {
69 return false;
70 }
71 }
72 return true;
73}
74
84IsMineResult IsMineInner(const LegacyScriptPubKeyMan &keystore,
85 const CScript &scriptPubKey,
86 IsMineSigVersion sigversion,
87 bool recurse_scripthash = true) {
88 IsMineResult ret = IsMineResult::NO;
89
90 std::vector<valtype> vSolutions;
91 TxoutType whichType = Solver(scriptPubKey, vSolutions);
92
93 CKeyID keyID;
94 switch (whichType) {
97 break;
99 keyID = CPubKey(vSolutions[0]).GetID();
100 if (keystore.HaveKey(keyID)) {
101 ret = std::max(ret, IsMineResult::SPENDABLE);
102 }
103 break;
105 keyID = CKeyID(uint160(vSolutions[0]));
106 if (keystore.HaveKey(keyID)) {
107 ret = std::max(ret, IsMineResult::SPENDABLE);
108 }
109 break;
111 if (sigversion != IsMineSigVersion::TOP) {
112 // P2SH inside P2SH is invalid.
113 return IsMineResult::INVALID;
114 }
115 CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
116 CScript subscript;
117 if (keystore.GetCScript(scriptID, subscript)) {
118 ret = std::max(ret, recurse_scripthash
119 ? IsMineInner(keystore, subscript,
120 IsMineSigVersion::P2SH)
121 : IsMineResult::SPENDABLE);
122 }
123 break;
124 }
125 case TxoutType::MULTISIG: {
126 // Never treat bare multisig outputs as ours (they can still be made
127 // watchonly-though)
128 if (sigversion == IsMineSigVersion::TOP) {
129 break;
130 }
131
132 // Only consider transactions "mine" if we own ALL the keys
133 // involved. Multi-signature transactions that are partially owned
134 // (somebody else has a key that can spend them) enable
135 // spend-out-from-under-you attacks, especially in shared-wallet
136 // situations.
137 std::vector<valtype> keys(vSolutions.begin() + 1,
138 vSolutions.begin() + vSolutions.size() -
139 1);
140 if (HaveKeys(keys, keystore)) {
141 ret = std::max(ret, IsMineResult::SPENDABLE);
142 }
143 break;
144 }
145 }
146
147 if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
148 ret = std::max(ret, IsMineResult::WATCH_ONLY);
149 }
150 return ret;
151}
152
153} // namespace
154
155isminetype LegacyScriptPubKeyMan::IsMine(const CScript &script) const {
156 switch (IsMineInner(*this, script, IsMineSigVersion::TOP)) {
157 case IsMineResult::INVALID:
158 case IsMineResult::NO:
159 return ISMINE_NO;
160 case IsMineResult::WATCH_ONLY:
161 return ISMINE_WATCH_ONLY;
162 case IsMineResult::SPENDABLE:
163 return ISMINE_SPENDABLE;
164 }
165 assert(false);
166}
167
169 const CKeyingMaterial &master_key, bool accept_no_keys) {
170 {
172 assert(mapKeys.empty());
173
174 // Always pass when there are no encrypted keys
175 bool keyPass = mapCryptedKeys.empty();
176 bool keyFail = false;
177 CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
179 for (; mi != mapCryptedKeys.end(); ++mi) {
180 const CPubKey &vchPubKey = (*mi).second.first;
181 const std::vector<uint8_t> &vchCryptedSecret = (*mi).second.second;
182 CKey key;
183 if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key)) {
184 keyFail = true;
185 break;
186 }
187 keyPass = true;
189 break;
190 } else {
191 // Rewrite these encrypted keys with checksums
192 batch.WriteCryptedKey(vchPubKey, vchCryptedSecret,
193 mapKeyMetadata[vchPubKey.GetID()]);
194 }
195 }
196 if (keyPass && keyFail) {
197 LogPrintf("The wallet is probably corrupted: Some keys decrypt but "
198 "not all.\n");
199 throw std::runtime_error(
200 "Error unlocking wallet: some keys decrypt but not all. Your "
201 "wallet file may be corrupt.");
202 }
203 if (keyFail || (!keyPass && !accept_no_keys)) {
204 return false;
205 }
207 }
208 return true;
209}
210
212 WalletBatch *batch) {
214 encrypted_batch = batch;
215 if (!mapCryptedKeys.empty()) {
216 encrypted_batch = nullptr;
217 return false;
218 }
219
220 KeyMap keys_to_encrypt;
221 // Clear mapKeys so AddCryptedKeyInner will succeed.
222 keys_to_encrypt.swap(mapKeys);
223 for (const KeyMap::value_type &mKey : keys_to_encrypt) {
224 const CKey &key = mKey.second;
225 CPubKey vchPubKey = key.GetPubKey();
226 CKeyingMaterial vchSecret(key.begin(), key.end());
227 std::vector<uint8_t> vchCryptedSecret;
228 if (!EncryptSecret(master_key, vchSecret, vchPubKey.GetHash(),
229 vchCryptedSecret)) {
230 encrypted_batch = nullptr;
231 return false;
232 }
233 if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) {
234 encrypted_batch = nullptr;
235 return false;
236 }
237 }
238 encrypted_batch = nullptr;
239 return true;
240}
241
243 bool internal,
244 CTxDestination &address,
245 int64_t &index,
246 CKeyPool &keypool) {
248 if (!CanGetAddresses(internal)) {
249 return false;
250 }
251
252 if (!ReserveKeyFromKeyPool(index, keypool, internal)) {
253 return false;
254 }
255 address = GetDestinationForKey(keypool.vchPubKey, type);
256 return true;
257}
258
260 int64_t index, bool internal) {
262
263 if (m_storage.IsLocked()) {
264 return false;
265 }
266
267 auto it = m_inactive_hd_chains.find(seed_id);
268 if (it == m_inactive_hd_chains.end()) {
269 return false;
270 }
271
272 CHDChain &chain = it->second;
273
274 // Top up key pool
275 int64_t target_size =
276 std::max(gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t)1);
277
278 // "size" of the keypools. Not really the size, actually the difference
279 // between index and the chain counter Since chain counter is 1 based and
280 // index is 0 based, one of them needs to be offset by 1.
281 int64_t kp_size =
282 (internal ? chain.nInternalChainCounter : chain.nExternalChainCounter) -
283 (index + 1);
284
285 // make sure the keypool fits the user-selected target (-keypool)
286 int64_t missing = std::max(target_size - kp_size, (int64_t)0);
287
288 if (missing > 0) {
290 for (int64_t i = missing; i > 0; --i) {
291 GenerateNewKey(batch, chain, internal);
292 }
293 if (internal) {
294 WalletLogPrintf("inactive seed with id %s added %d internal keys\n",
295 HexStr(seed_id), missing);
296 } else {
297 WalletLogPrintf("inactive seed with id %s added %d keys\n",
298 HexStr(seed_id), missing);
299 }
300 }
301 return true;
302}
303
306 // extract addresses and check if they match with an unused keypool key
307 for (const auto &keyid : GetAffectedKeys(script, *this)) {
308 std::map<CKeyID, int64_t>::const_iterator mi =
309 m_pool_key_to_index.find(keyid);
310 if (mi != m_pool_key_to_index.end()) {
311 WalletLogPrintf("%s: Detected a used keypool key, mark all keypool "
312 "keys up to this key as used\n",
313 __func__);
314 MarkReserveKeysAsUsed(mi->second);
315
316 if (!TopUp()) {
318 "%s: Topping up keypool failed (locked wallet)\n",
319 __func__);
320 }
321 }
322
323 // Find the key's metadata and check if it's seed id (if it has one) is
324 // inactive, i.e. it is not the current m_hd_chain seed id. If so, TopUp
325 // the inactive hd chain
326 auto it = mapKeyMetadata.find(keyid);
327 if (it != mapKeyMetadata.end()) {
328 CKeyMetadata meta = it->second;
329 if (!meta.hd_seed_id.IsNull() &&
330 meta.hd_seed_id != m_hd_chain.seed_id) {
331 bool internal =
332 (meta.key_origin.path[1] & ~BIP32_HARDENED_KEY_LIMIT) != 0;
333 int64_t index =
334 meta.key_origin.path[2] & ~BIP32_HARDENED_KEY_LIMIT;
335
336 if (!TopUpInactiveHDChain(meta.hd_seed_id, index, internal)) {
337 WalletLogPrintf("%s: Adding inactive seed keys failed\n",
338 __func__);
339 }
340 }
341 }
342 }
343}
344
347 if (m_storage.IsLocked() ||
349 return;
350 }
351
352 auto batch = std::make_unique<WalletBatch>(m_storage.GetDatabase());
353 for (auto &meta_pair : mapKeyMetadata) {
354 CKeyMetadata &meta = meta_pair.second;
355 // If the hdKeypath is "s", that's the seed and it doesn't have a key
356 // origin
357 if (!meta.hd_seed_id.IsNull() && !meta.has_key_origin &&
358 meta.hdKeypath != "s") {
359 CKey key;
360 GetKey(meta.hd_seed_id, key);
361 CExtKey masterKey;
362 masterKey.SetSeed(key);
363 // Add to map
364 CKeyID master_id = masterKey.key.GetPubKey().GetID();
365 std::copy(master_id.begin(), master_id.begin() + 4,
367 if (!ParseHDKeypath(meta.hdKeypath, meta.key_origin.path)) {
368 throw std::runtime_error("Invalid stored hdKeypath");
369 }
370 meta.has_key_origin = true;
373 }
374
375 // Write meta to wallet
376 CPubKey pubkey;
377 if (GetPubKey(meta_pair.first, pubkey)) {
378 batch->WriteKeyMetadata(meta, pubkey, true);
379 }
380 }
381 }
382}
383
385 if ((CanGenerateKeys() && !force) || m_storage.IsLocked()) {
386 return false;
387 }
388
390 if (!NewKeyPool()) {
391 return false;
392 }
393 return true;
394}
395
397 return !m_hd_chain.seed_id.IsNull();
398}
399
400bool LegacyScriptPubKeyMan::CanGetAddresses(bool internal) const {
402 // Check if the keypool has keys
403 bool keypool_has_keys;
405 keypool_has_keys = setInternalKeyPool.size() > 0;
406 } else {
407 keypool_has_keys = KeypoolCountExternalKeys() > 0;
408 }
409 // If the keypool doesn't have keys, check if we can generate them
410 if (!keypool_has_keys) {
411 return CanGenerateKeys();
412 }
413 return keypool_has_keys;
414}
415
416bool LegacyScriptPubKeyMan::Upgrade(int prev_version, bilingual_str &error) {
418 bool hd_upgrade = false;
419 bool split_upgrade = false;
421 WalletLogPrintf("Upgrading wallet to HD\n");
423
424 // generate a new master key
425 CPubKey masterPubKey = GenerateNewSeed();
426 SetHDSeed(masterPubKey);
427 hd_upgrade = true;
428 }
429 // Upgrade to HD chain split if necessary
431 WalletLogPrintf("Upgrading wallet to use HD chain split\n");
433 split_upgrade = FEATURE_HD_SPLIT > prev_version;
434 }
435 // Mark all keys currently in the keypool as pre-split
436 if (split_upgrade) {
438 }
439 // Regenerate the keypool if upgraded to HD
440 if (hd_upgrade) {
441 if (!TopUp()) {
442 error = _("Unable to generate keys");
443 return false;
444 }
445 }
446 return true;
447}
448
451 return !mapKeys.empty() || !mapCryptedKeys.empty();
452}
453
456 setInternalKeyPool.clear();
457 setExternalKeyPool.clear();
458 m_pool_key_to_index.clear();
459 // Note: can't top-up keypool here, because wallet is locked.
460 // User will be prompted to unlock wallet the next operation
461 // that requires a new key.
462}
463
464static int64_t GetOldestKeyTimeInPool(const std::set<int64_t> &setKeyPool,
465 WalletBatch &batch) {
466 if (setKeyPool.empty()) {
467 return GetTime();
468 }
469
470 CKeyPool keypool;
471 int64_t nIndex = *(setKeyPool.begin());
472 if (!batch.ReadPool(nIndex, keypool)) {
473 throw std::runtime_error(std::string(__func__) +
474 ": read oldest key in keypool failed");
475 }
476
477 assert(keypool.vchPubKey.IsValid());
478 return keypool.nTime;
479}
480
483
485
486 // load oldest key from keypool, get time and return
487 int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, batch);
489 oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, batch),
490 oldestKey);
491 if (!set_pre_split_keypool.empty()) {
492 oldestKey =
493 std::max(GetOldestKeyTimeInPool(set_pre_split_keypool, batch),
494 oldestKey);
495 }
496 }
497
498 return oldestKey;
499}
500
503 return setExternalKeyPool.size() + set_pre_split_keypool.size();
504}
505
508 return setInternalKeyPool.size() + setExternalKeyPool.size() +
509 set_pre_split_keypool.size();
510}
511
514 return nTimeFirstKey;
515}
516
517std::unique_ptr<SigningProvider>
518LegacyScriptPubKeyMan::GetSolvingProvider(const CScript &script) const {
519 return std::make_unique<LegacySigningProvider>(*this);
520}
521
522bool LegacyScriptPubKeyMan::CanProvide(const CScript &script,
523 SignatureData &sigdata) {
524 IsMineResult ismine = IsMineInner(*this, script, IsMineSigVersion::TOP,
525 /* recurse_scripthash= */ false);
526 if (ismine == IsMineResult::SPENDABLE ||
527 ismine == IsMineResult::WATCH_ONLY) {
528 // If ismine, it means we recognize keys or script ids in the script, or
529 // are watching the script itself, and we can at least provide metadata
530 // or solving information, even if not able to sign fully.
531 return true;
532 }
533 // If, given the stuff in sigdata, we could make a valid sigature, then
534 // we can provide for this script
535 ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
536 if (!sigdata.signatures.empty()) {
537 // If we could make signatures, make sure we have a private key to
538 // actually make a signature
539 bool has_privkeys = false;
540 for (const auto &key_sig_pair : sigdata.signatures) {
541 has_privkeys |= HaveKey(key_sig_pair.first);
542 }
543 return has_privkeys;
544 }
545 return false;
546}
547
549 CMutableTransaction &tx, const std::map<COutPoint, Coin> &coins,
550 SigHashType sighash, std::map<int, std::string> &input_errors) const {
551 return ::SignTransaction(tx, this, coins, sighash, input_errors);
552}
553
555 const PKHash &pkhash,
556 std::string &str_sig) const {
557 CKey key;
558 if (!GetKey(ToKeyID(pkhash), key)) {
560 }
561
562 if (MessageSign(key, message, str_sig)) {
563 return SigningResult::OK;
564 }
566}
567
570 SigHashType sighash_type, bool sign,
571 bool bip32derivs) const {
572 for (size_t i = 0; i < psbtx.tx->vin.size(); ++i) {
573 PSBTInput &input = psbtx.inputs.at(i);
574
575 if (PSBTInputSigned(input)) {
576 continue;
577 }
578
579 // Get the Sighash type
580 if (sign && input.sighash_type.getRawSigHashType() > 0 &&
581 input.sighash_type != sighash_type) {
583 }
584
585 if (input.utxo.IsNull()) {
586 // There's no UTXO so we can just skip this now
587 continue;
588 }
589 SignatureData sigdata;
590 input.FillSignatureData(sigdata);
591 SignPSBTInput(HidingSigningProvider(this, !sign, !bip32derivs), psbtx,
592 i, sighash_type);
593 }
594
595 // Fill in the bip32 keypaths and redeemscripts for the outputs so that
596 // hardware wallets can identify change
597 for (size_t i = 0; i < psbtx.tx->vout.size(); ++i) {
598 UpdatePSBTOutput(HidingSigningProvider(this, true, !bip32derivs), psbtx,
599 i);
600 }
601
603}
604
605std::unique_ptr<CKeyMetadata>
608
609 CKeyID key_id = GetKeyForDestination(*this, dest);
610 if (!key_id.IsNull()) {
611 auto it = mapKeyMetadata.find(key_id);
612 if (it != mapKeyMetadata.end()) {
613 return std::make_unique<CKeyMetadata>(it->second);
614 }
615 }
616
617 CScript scriptPubKey = GetScriptForDestination(dest);
618 auto it = m_script_metadata.find(CScriptID(scriptPubKey));
619 if (it != m_script_metadata.end()) {
620 return std::make_unique<CKeyMetadata>(it->second);
621 }
622
623 return nullptr;
624}
625
627 return uint256::ONE;
628}
629
636 if (nCreateTime <= 1) {
637 // Cannot determine birthday information, so set the wallet birthday to
638 // the beginning of time.
639 nTimeFirstKey = 1;
640 } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
641 nTimeFirstKey = nCreateTime;
642 }
643}
644
645bool LegacyScriptPubKeyMan::LoadKey(const CKey &key, const CPubKey &pubkey) {
646 return AddKeyPubKeyInner(key, pubkey);
647}
648
650 const CPubKey &pubkey) {
653 return LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(batch, secret, pubkey);
654}
655
657 const CKey &secret,
658 const CPubKey &pubkey) {
660
661 // Make sure we aren't adding private keys to private key disabled wallets
663
664 // FillableSigningProvider has no concept of wallet databases, but calls
665 // AddCryptedKey which is overridden below. To avoid flushes, the database
666 // handle is tunneled through to it.
667 bool needsDB = !encrypted_batch;
668 if (needsDB) {
669 encrypted_batch = &batch;
670 }
671 if (!AddKeyPubKeyInner(secret, pubkey)) {
672 if (needsDB) {
673 encrypted_batch = nullptr;
674 }
675 return false;
676 }
677
678 if (needsDB) {
679 encrypted_batch = nullptr;
680 }
681
682 // Check if we need to remove from watch-only.
683 CScript script;
684 script = GetScriptForDestination(PKHash(pubkey));
685 if (HaveWatchOnly(script)) {
686 RemoveWatchOnly(script);
687 }
688
689 script = GetScriptForRawPubKey(pubkey);
690 if (HaveWatchOnly(script)) {
691 RemoveWatchOnly(script);
692 }
693
695 return batch.WriteKey(pubkey, secret.GetPrivKey(),
696 mapKeyMetadata[pubkey.GetID()]);
697 }
699 return true;
700}
701
709 std::string strAddr =
711 WalletLogPrintf("%s: Warning: This wallet contains a redeemScript "
712 "of size %i which exceeds maximum size %i thus can "
713 "never be redeemed. Do not use address %s.\n",
714 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE,
715 strAddr);
716 return true;
717 }
718
720}
721
723 const CKeyMetadata &meta) {
726 mapKeyMetadata[keyID] = meta;
727}
728
730 const CKeyMetadata &meta) {
733 m_script_metadata[script_id] = meta;
734}
735
737 const CPubKey &pubkey) {
740 return FillableSigningProvider::AddKeyPubKey(key, pubkey);
741 }
742
743 if (m_storage.IsLocked()) {
744 return false;
745 }
746
747 std::vector<uint8_t> vchCryptedSecret;
748 CKeyingMaterial vchSecret(key.begin(), key.end());
750 [&](const CKeyingMaterial &encryption_key) {
751 return EncryptSecret(encryption_key, vchSecret,
752 pubkey.GetHash(), vchCryptedSecret);
753 })) {
754 return false;
755 }
756
757 if (!AddCryptedKey(pubkey, vchCryptedSecret)) {
758 return false;
759 }
760 return true;
761}
762
764 const CPubKey &vchPubKey, const std::vector<uint8_t> &vchCryptedSecret,
765 bool checksum_valid) {
766 // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
767 if (!checksum_valid) {
769 }
770
771 return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
772}
773
775 const CPubKey &vchPubKey, const std::vector<uint8_t> &vchCryptedSecret) {
777 assert(mapKeys.empty());
778
779 mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
780 return true;
781}
782
784 const CPubKey &vchPubKey, const std::vector<uint8_t> &vchCryptedSecret) {
785 if (!AddCryptedKeyInner(vchPubKey, vchCryptedSecret)) {
786 return false;
787 }
788
790 if (encrypted_batch) {
791 return encrypted_batch->WriteCryptedKey(
792 vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
793 }
794
796 .WriteCryptedKey(vchPubKey, vchCryptedSecret,
797 mapKeyMetadata[vchPubKey.GetID()]);
798}
799
800bool LegacyScriptPubKeyMan::HaveWatchOnly(const CScript &dest) const {
802 return setWatchOnly.count(dest) > 0;
803}
804
807 return (!setWatchOnly.empty());
808}
809
810static bool ExtractPubKey(const CScript &dest, CPubKey &pubKeyOut) {
811 std::vector<std::vector<uint8_t>> solutions;
812 return Solver(dest, solutions) == TxoutType::PUBKEY &&
813 (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
814}
815
816bool LegacyScriptPubKeyMan::RemoveWatchOnly(const CScript &dest) {
817 {
819 setWatchOnly.erase(dest);
820 CPubKey pubKey;
821 if (ExtractPubKey(dest, pubKey)) {
822 mapWatchKeys.erase(pubKey.GetID());
823 }
824 }
825
826 if (!HaveWatchOnly()) {
828 }
829
831}
832
833bool LegacyScriptPubKeyMan::LoadWatchOnly(const CScript &dest) {
834 return AddWatchOnlyInMem(dest);
835}
836
839 setWatchOnly.insert(dest);
840 CPubKey pubKey;
841 if (ExtractPubKey(dest, pubKey)) {
842 mapWatchKeys[pubKey.GetID()] = pubKey;
843 }
844 return true;
845}
846
848 const CScript &dest) {
849 if (!AddWatchOnlyInMem(dest)) {
850 return false;
851 }
852
853 const CKeyMetadata &meta = m_script_metadata[CScriptID(dest)];
856 if (batch.WriteWatchOnly(dest, meta)) {
858 return true;
859 }
860 return false;
861}
862
864 const CScript &dest,
865 int64_t create_time) {
866 m_script_metadata[CScriptID(dest)].nCreateTime = create_time;
867 return AddWatchOnlyWithDB(batch, dest);
868}
869
870bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript &dest) {
872 return AddWatchOnlyWithDB(batch, dest);
873}
874
875bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript &dest,
876 int64_t nCreateTime) {
877 m_script_metadata[CScriptID(dest)].nCreateTime = nCreateTime;
878 return AddWatchOnly(dest);
879}
880
883 m_hd_chain = chain;
884}
885
888 // Store the new chain
890 throw std::runtime_error(std::string(__func__) +
891 ": writing chain failed");
892 }
893 // When there's an old chain, add it as an inactive chain as we are now
894 // rotating hd chains
895 if (!m_hd_chain.seed_id.IsNull()) {
897 }
898
899 m_hd_chain = chain;
900}
901
904 assert(!chain.seed_id.IsNull());
905 m_inactive_hd_chains[chain.seed_id] = chain;
906}
907
908bool LegacyScriptPubKeyMan::HaveKey(const CKeyID &address) const {
911 return FillableSigningProvider::HaveKey(address);
912 }
913 return mapCryptedKeys.count(address) > 0;
914}
915
916bool LegacyScriptPubKeyMan::GetKey(const CKeyID &address, CKey &keyOut) const {
919 return FillableSigningProvider::GetKey(address, keyOut);
920 }
921
922 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
923 if (mi != mapCryptedKeys.end()) {
924 const CPubKey &vchPubKey = (*mi).second.first;
925 const std::vector<uint8_t> &vchCryptedSecret = (*mi).second.second;
927 [&](const CKeyingMaterial &encryption_key) {
928 return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey,
929 keyOut);
930 });
931 }
932 return false;
933}
934
936 KeyOriginInfo &info) const {
937 CKeyMetadata meta;
938 {
940 auto it = mapKeyMetadata.find(keyID);
941 if (it != mapKeyMetadata.end()) {
942 meta = it->second;
943 }
944 }
945 if (meta.has_key_origin) {
946 std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4,
947 info.fingerprint);
948 info.path = meta.key_origin.path;
949 } else {
950 // Single pubkeys get the master fingerprint of themselves
951 std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
952 }
953 return true;
954}
955
957 CPubKey &pubkey_out) const {
959 WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
960 if (it != mapWatchKeys.end()) {
961 pubkey_out = it->second;
962 return true;
963 }
964 return false;
965}
966
968 CPubKey &vchPubKeyOut) const {
971 if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
972 return GetWatchPubKey(address, vchPubKeyOut);
973 }
974 return true;
975 }
976
977 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
978 if (mi != mapCryptedKeys.end()) {
979 vchPubKeyOut = (*mi).second.first;
980 return true;
981 }
982
983 // Check for watch-only pubkeys
984 return GetWatchPubKey(address, vchPubKeyOut);
985}
986
988 CHDChain &hd_chain,
989 bool internal) {
993 // default to compressed public keys if we want 0.6.0 wallets
995
996 CKey secret;
997
998 // Create new metadata
999 int64_t nCreationTime = GetTime();
1000 CKeyMetadata metadata(nCreationTime);
1001
1002 // use HD key derivation if HD was enabled during wallet creation and a seed
1003 // is present
1004 if (IsHDEnabled()) {
1006 batch, metadata, secret, hd_chain,
1007 (m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
1008 } else {
1009 secret.MakeNewKey(fCompressed);
1010 }
1011
1012 // Compressed public keys were introduced in version 0.6.0
1013 if (fCompressed) {
1015 }
1016
1017 CPubKey pubkey = secret.GetPubKey();
1018 assert(secret.VerifyPubKey(pubkey));
1019
1020 mapKeyMetadata[pubkey.GetID()] = metadata;
1021 UpdateTimeFirstKey(nCreationTime);
1022
1023 if (!AddKeyPubKeyWithDB(batch, secret, pubkey)) {
1024 throw std::runtime_error(std::string(__func__) + ": AddKey failed");
1025 }
1026
1027 return pubkey;
1028}
1029
1031 CKeyMetadata &metadata,
1032 CKey &secret, CHDChain &hd_chain,
1033 bool internal) {
1034 // for now we use a fixed keypath scheme of m/0'/0'/k
1035 // seed (256bit)
1036 CKey seed;
1037 // hd master key
1038 CExtKey masterKey;
1039 // key at m/0'
1040 CExtKey accountKey;
1041 // key at m/0'/0' (external) or m/0'/1' (internal)
1042 CExtKey chainChildKey;
1043 // key at m/0'/0'/<n>'
1044 CExtKey childKey;
1045
1046 // try to get the seed
1047 if (!GetKey(hd_chain.seed_id, seed)) {
1048 throw std::runtime_error(std::string(__func__) + ": seed not found");
1049 }
1050
1051 masterKey.SetSeed(seed);
1052
1053 // derive m/0'
1054 // use hardened derivation (child keys >= 0x80000000 are hardened after
1055 // bip32)
1056 masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
1057
1058 // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
1060 accountKey.Derive(chainChildKey,
1061 BIP32_HARDENED_KEY_LIMIT + (internal ? 1 : 0));
1062
1063 // derive child key at next index, skip keys already known to the wallet
1064 do {
1065 // always derive hardened keys
1066 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened
1067 // child-index-range
1068 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
1069 if (internal) {
1070 chainChildKey.Derive(childKey, hd_chain.nInternalChainCounter |
1072 metadata.hdKeypath =
1073 "m/0'/1'/" + ToString(hd_chain.nInternalChainCounter) + "'";
1074 metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1075 metadata.key_origin.path.push_back(1 | BIP32_HARDENED_KEY_LIMIT);
1076 metadata.key_origin.path.push_back(hd_chain.nInternalChainCounter |
1078 hd_chain.nInternalChainCounter++;
1079 } else {
1080 chainChildKey.Derive(childKey, hd_chain.nExternalChainCounter |
1082 metadata.hdKeypath =
1083 "m/0'/0'/" + ToString(hd_chain.nExternalChainCounter) + "'";
1084 metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1085 metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1086 metadata.key_origin.path.push_back(hd_chain.nExternalChainCounter |
1088 hd_chain.nExternalChainCounter++;
1089 }
1090 } while (HaveKey(childKey.key.GetPubKey().GetID()));
1091 secret = childKey.key;
1092 metadata.hd_seed_id = hd_chain.seed_id;
1093 CKeyID master_id = masterKey.key.GetPubKey().GetID();
1094 std::copy(master_id.begin(), master_id.begin() + 4,
1095 metadata.key_origin.fingerprint);
1096 metadata.has_key_origin = true;
1097 // update the chain model in the database
1098 if (hd_chain.seed_id == m_hd_chain.seed_id &&
1099 !batch.WriteHDChain(hd_chain)) {
1100 throw std::runtime_error(std::string(__func__) +
1101 ": writing HD chain model failed");
1102 }
1103}
1104
1106 const CKeyPool &keypool) {
1108 if (keypool.m_pre_split) {
1109 set_pre_split_keypool.insert(nIndex);
1110 } else if (keypool.fInternal) {
1111 setInternalKeyPool.insert(nIndex);
1112 } else {
1113 setExternalKeyPool.insert(nIndex);
1114 }
1115 m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
1116 m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
1117
1118 // If no metadata exists yet, create a default with the pool key's
1119 // creation time. Note that this may be overwritten by actually
1120 // stored metadata for that key later, which is fine.
1121 CKeyID keyid = keypool.vchPubKey.GetID();
1122 if (mapKeyMetadata.count(keyid) == 0) {
1123 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
1124 }
1125}
1126
1128 // A wallet can generate keys if it has an HD seed (IsHDEnabled) or it is a
1129 // non-HD wallet (pre FEATURE_HD)
1132}
1133
1136 CKey key;
1137 key.MakeNewKey(true);
1138 return DeriveNewSeed(key);
1139}
1140
1142 int64_t nCreationTime = GetTime();
1143 CKeyMetadata metadata(nCreationTime);
1144
1145 // Calculate the seed
1146 CPubKey seed = key.GetPubKey();
1147 assert(key.VerifyPubKey(seed));
1148
1149 // Set the hd keypath to "s" -> Seed, refers the seed to itself
1150 metadata.hdKeypath = "s";
1151 metadata.has_key_origin = false;
1152 metadata.hd_seed_id = seed.GetID();
1153
1155
1156 // mem store the metadata
1157 mapKeyMetadata[seed.GetID()] = metadata;
1158
1159 // Write the key&metadata to the database
1160 if (!AddKeyPubKey(key, seed)) {
1161 throw std::runtime_error(std::string(__func__) +
1162 ": AddKeyPubKey failed");
1163 }
1164
1165 return seed;
1166}
1167
1170
1171 // Store the keyid (hash160) together with the child index counter in the
1172 // database as a hdchain object.
1173 CHDChain newHdChain;
1177 newHdChain.seed_id = seed.GetID();
1178 AddHDChain(newHdChain);
1182}
1183
1189 return false;
1190 }
1193
1194 for (const int64_t nIndex : setInternalKeyPool) {
1195 batch.ErasePool(nIndex);
1196 }
1197 setInternalKeyPool.clear();
1198
1199 for (const int64_t nIndex : setExternalKeyPool) {
1200 batch.ErasePool(nIndex);
1201 }
1202 setExternalKeyPool.clear();
1203
1204 for (int64_t nIndex : set_pre_split_keypool) {
1205 batch.ErasePool(nIndex);
1206 }
1207 set_pre_split_keypool.clear();
1208
1209 m_pool_key_to_index.clear();
1210
1211 if (!TopUp()) {
1212 return false;
1213 }
1214
1215 WalletLogPrintf("LegacyScriptPubKeyMan::NewKeyPool rewrote keypool\n");
1216 return true;
1217}
1218
1219bool LegacyScriptPubKeyMan::TopUp(unsigned int kpSize) {
1220 if (!CanGenerateKeys()) {
1221 return false;
1222 }
1223 {
1225
1226 if (m_storage.IsLocked()) {
1227 return false;
1228 }
1229
1230 // Top up key pool
1231 unsigned int nTargetSize;
1232 if (kpSize > 0) {
1233 nTargetSize = kpSize;
1234 } else {
1235 nTargetSize = std::max<int64_t>(
1236 gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), 0);
1237 }
1238
1239 // count amount of available keys (internal, external)
1240 // make sure the keypool of external and internal keys fits the user
1241 // selected target (-keypool)
1242 int64_t missingExternal = std::max<int64_t>(
1243 std::max<int64_t>(nTargetSize, 1) - setExternalKeyPool.size(), 0);
1244 int64_t missingInternal = std::max<int64_t>(
1245 std::max<int64_t>(nTargetSize, 1) - setInternalKeyPool.size(), 0);
1246
1248 // don't create extra internal keys
1249 missingInternal = 0;
1250 }
1251 bool internal = false;
1253 for (int64_t i = missingInternal + missingExternal; i--;) {
1254 if (i < missingInternal) {
1255 internal = true;
1256 }
1257
1258 CPubKey pubkey(GenerateNewKey(batch, m_hd_chain, internal));
1259 AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1260 }
1261 if (missingInternal + missingExternal > 0) {
1263 "keypool added %d keys (%d internal), size=%u (%u internal)\n",
1264 missingInternal + missingExternal, missingInternal,
1265 setInternalKeyPool.size() + setExternalKeyPool.size() +
1266 set_pre_split_keypool.size(),
1267 setInternalKeyPool.size());
1268 }
1269 }
1271 return true;
1272}
1273
1275 const bool internal,
1276 WalletBatch &batch) {
1278 // How in the hell did you use so many keys?
1279 assert(m_max_keypool_index < std::numeric_limits<int64_t>::max());
1280 int64_t index = ++m_max_keypool_index;
1281 if (!batch.WritePool(index, CKeyPool(pubkey, internal))) {
1282 throw std::runtime_error(std::string(__func__) +
1283 ": writing imported pubkey failed");
1284 }
1285 if (internal) {
1286 setInternalKeyPool.insert(index);
1287 } else {
1288 setExternalKeyPool.insert(index);
1289 }
1290 m_pool_key_to_index[pubkey.GetID()] = index;
1291}
1292
1294 const OutputType &type) {
1295 // Remove from key pool.
1297 batch.ErasePool(nIndex);
1298 CPubKey pubkey;
1299 bool have_pk = GetPubKey(m_index_to_reserved_key.at(nIndex), pubkey);
1300 assert(have_pk);
1301 LearnRelatedScripts(pubkey, type);
1302 m_index_to_reserved_key.erase(nIndex);
1303 WalletLogPrintf("keypool keep %d\n", nIndex);
1304}
1305
1306void LegacyScriptPubKeyMan::ReturnDestination(int64_t nIndex, bool fInternal,
1307 const CTxDestination &) {
1308 // Return to key pool
1309 {
1311 if (fInternal) {
1312 setInternalKeyPool.insert(nIndex);
1313 } else if (!set_pre_split_keypool.empty()) {
1314 set_pre_split_keypool.insert(nIndex);
1315 } else {
1316 setExternalKeyPool.insert(nIndex);
1317 }
1318 CKeyID &pubkey_id = m_index_to_reserved_key.at(nIndex);
1319 m_pool_key_to_index[pubkey_id] = nIndex;
1320 m_index_to_reserved_key.erase(nIndex);
1322 }
1323
1324 WalletLogPrintf("keypool return %d\n", nIndex);
1325}
1326
1328 const OutputType type,
1329 bool internal) {
1330 if (!CanGetAddresses(internal)) {
1331 return false;
1332 }
1333
1334 CKeyPool keypool;
1336 int64_t nIndex;
1337 if (!ReserveKeyFromKeyPool(nIndex, keypool, internal) &&
1339 if (m_storage.IsLocked()) {
1340 return false;
1341 }
1343 result = GenerateNewKey(batch, m_hd_chain, internal);
1344 return true;
1345 }
1346
1347 KeepDestination(nIndex, type);
1348 result = keypool.vchPubKey;
1349
1350 return true;
1351}
1352
1354 CKeyPool &keypool,
1355 bool fRequestedInternal) {
1356 nIndex = -1;
1357 keypool.vchPubKey = CPubKey();
1358 {
1360
1361 bool fReturningInternal = fRequestedInternal;
1362 fReturningInternal &=
1365 bool use_split_keypool = set_pre_split_keypool.empty();
1366 std::set<int64_t> &setKeyPool =
1367 use_split_keypool
1368 ? (fReturningInternal ? setInternalKeyPool : setExternalKeyPool)
1369 : set_pre_split_keypool;
1370
1371 // Get the oldest key
1372 if (setKeyPool.empty()) {
1373 return false;
1374 }
1375
1377
1378 auto it = setKeyPool.begin();
1379 nIndex = *it;
1380 setKeyPool.erase(it);
1381 if (!batch.ReadPool(nIndex, keypool)) {
1382 throw std::runtime_error(std::string(__func__) + ": read failed");
1383 }
1384 CPubKey pk;
1385 if (!GetPubKey(keypool.vchPubKey.GetID(), pk)) {
1386 throw std::runtime_error(std::string(__func__) +
1387 ": unknown key in key pool");
1388 }
1389 // If the key was pre-split keypool, we don't care about what type it is
1390 if (use_split_keypool && keypool.fInternal != fReturningInternal) {
1391 throw std::runtime_error(std::string(__func__) +
1392 ": keypool entry misclassified");
1393 }
1394 if (!keypool.vchPubKey.IsValid()) {
1395 throw std::runtime_error(std::string(__func__) +
1396 ": keypool entry invalid");
1397 }
1398
1399 assert(m_index_to_reserved_key.count(nIndex) == 0);
1400 m_index_to_reserved_key[nIndex] = keypool.vchPubKey.GetID();
1401 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1402 WalletLogPrintf("keypool reserve %d\n", nIndex);
1403 }
1405 return true;
1406}
1407
1409 OutputType type) {
1410 // Nothing to do...
1411}
1412
1414 // Nothing to do...
1415}
1416
1419 bool internal = setInternalKeyPool.count(keypool_id);
1420 if (!internal) {
1421 assert(setExternalKeyPool.count(keypool_id) ||
1422 set_pre_split_keypool.count(keypool_id));
1423 }
1424
1425 std::set<int64_t> *setKeyPool =
1426 internal ? &setInternalKeyPool
1427 : (set_pre_split_keypool.empty() ? &setExternalKeyPool
1428 : &set_pre_split_keypool);
1429 auto it = setKeyPool->begin();
1430
1432 while (it != std::end(*setKeyPool)) {
1433 const int64_t &index = *(it);
1434 if (index > keypool_id) {
1435 // set*KeyPool is ordered
1436 break;
1437 }
1438
1439 CKeyPool keypool;
1440 if (batch.ReadPool(index, keypool)) {
1441 // TODO: This should be unnecessary
1442 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1443 }
1445 batch.ErasePool(index);
1446 WalletLogPrintf("keypool index %d removed\n", index);
1447 it = setKeyPool->erase(it);
1448 }
1449}
1450
1451std::vector<CKeyID> GetAffectedKeys(const CScript &spk,
1452 const SigningProvider &provider) {
1453 std::vector<CScript> dummy;
1455 InferDescriptor(spk, provider)
1456 ->Expand(0, DUMMY_SIGNING_PROVIDER, dummy, out);
1457 std::vector<CKeyID> ret;
1458 ret.reserve(out.pubkeys.size());
1459 for (const auto &entry : out.pubkeys) {
1460 ret.push_back(entry.first);
1461 }
1462 return ret;
1463}
1464
1467 for (auto it = setExternalKeyPool.begin();
1468 it != setExternalKeyPool.end();) {
1469 int64_t index = *it;
1470 CKeyPool keypool;
1471 if (!batch.ReadPool(index, keypool)) {
1472 throw std::runtime_error(std::string(__func__) +
1473 ": read keypool entry failed");
1474 }
1475 keypool.m_pre_split = true;
1476 if (!batch.WritePool(index, keypool)) {
1477 throw std::runtime_error(std::string(__func__) +
1478 ": writing modified keypool entry failed");
1479 }
1480 set_pre_split_keypool.insert(index);
1481 it = setExternalKeyPool.erase(it);
1482 }
1483}
1484
1487 return AddCScriptWithDB(batch, redeemScript);
1488}
1489
1491 const CScript &redeemScript) {
1493 return false;
1494 }
1497 return true;
1498 }
1499 return false;
1500}
1501
1503 const CPubKey &pubkey,
1504 const KeyOriginInfo &info) {
1506 std::copy(info.fingerprint, info.fingerprint + 4,
1507 mapKeyMetadata[pubkey.GetID()].key_origin.fingerprint);
1508 mapKeyMetadata[pubkey.GetID()].key_origin.path = info.path;
1509 mapKeyMetadata[pubkey.GetID()].has_key_origin = true;
1510 mapKeyMetadata[pubkey.GetID()].hdKeypath = WriteHDKeypath(info.path);
1511 return batch.WriteKeyMetadata(mapKeyMetadata[pubkey.GetID()], pubkey, true);
1512}
1513
1514bool LegacyScriptPubKeyMan::ImportScripts(const std::set<CScript> scripts,
1515 int64_t timestamp) {
1517 for (const auto &entry : scripts) {
1518 CScriptID id(entry);
1519 if (HaveCScript(id)) {
1520 WalletLogPrintf("Already have script %s, skipping\n",
1521 HexStr(entry));
1522 continue;
1523 }
1524 if (!AddCScriptWithDB(batch, entry)) {
1525 return false;
1526 }
1527
1528 if (timestamp > 0) {
1529 m_script_metadata[CScriptID(entry)].nCreateTime = timestamp;
1530 }
1531 }
1532 if (timestamp > 0) {
1533 UpdateTimeFirstKey(timestamp);
1534 }
1535
1536 return true;
1537}
1538
1540 const std::map<CKeyID, CKey> &privkey_map, const int64_t timestamp) {
1542 for (const auto &entry : privkey_map) {
1543 const CKey &key = entry.second;
1544 CPubKey pubkey = key.GetPubKey();
1545 const CKeyID &id = entry.first;
1546 assert(key.VerifyPubKey(pubkey));
1547 // Skip if we already have the key
1548 if (HaveKey(id)) {
1549 WalletLogPrintf("Already have key with pubkey %s, skipping\n",
1550 HexStr(pubkey));
1551 continue;
1552 }
1553 mapKeyMetadata[id].nCreateTime = timestamp;
1554 // If the private key is not present in the wallet, insert it.
1555 if (!AddKeyPubKeyWithDB(batch, key, pubkey)) {
1556 return false;
1557 }
1558 UpdateTimeFirstKey(timestamp);
1559 }
1560 return true;
1561}
1562
1564 const std::vector<CKeyID> &ordered_pubkeys,
1565 const std::map<CKeyID, CPubKey> &pubkey_map,
1566 const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>> &key_origins,
1567 const bool add_keypool, const bool internal, const int64_t timestamp) {
1569 for (const auto &entry : key_origins) {
1570 AddKeyOriginWithDB(batch, entry.second.first, entry.second.second);
1571 }
1572 for (const CKeyID &id : ordered_pubkeys) {
1573 auto entry = pubkey_map.find(id);
1574 if (entry == pubkey_map.end()) {
1575 continue;
1576 }
1577 const CPubKey &pubkey = entry->second;
1578 CPubKey temp;
1579 if (GetPubKey(id, temp)) {
1580 // Already have pubkey, skipping
1581 WalletLogPrintf("Already have pubkey %s, skipping\n", HexStr(temp));
1582 continue;
1583 }
1584 if (!AddWatchOnlyWithDB(batch, GetScriptForRawPubKey(pubkey),
1585 timestamp)) {
1586 return false;
1587 }
1588 mapKeyMetadata[id].nCreateTime = timestamp;
1589
1590 // Add to keypool only works with pubkeys
1591 if (add_keypool) {
1592 AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1594 }
1595 }
1596 return true;
1597}
1598
1600 const std::set<CScript> &script_pub_keys, const bool have_solving_data,
1601 const int64_t timestamp) {
1603 for (const CScript &script : script_pub_keys) {
1604 if (!have_solving_data || !IsMine(script)) {
1605 // Always call AddWatchOnly for non-solvable watch-only, so that
1606 // watch timestamp gets updated
1607 if (!AddWatchOnlyWithDB(batch, script, timestamp)) {
1608 return false;
1609 }
1610 }
1611 }
1612 return true;
1613}
1614
1615std::set<CKeyID> LegacyScriptPubKeyMan::GetKeys() const {
1619 }
1620 std::set<CKeyID> set_address;
1621 for (const auto &mi : mapCryptedKeys) {
1622 set_address.insert(mi.first);
1623 }
1624 return set_address;
1625}
1626
1628
1631 // Returns true if this descriptor supports getting new addresses.
1632 // Conditions where we may be unable to fetch them (e.g. locked) are caught
1633 // later
1635 return util::Error{_("No addresses available")};
1636 }
1637 {
1639 // This is a combo descriptor which should not be an active descriptor
1640 assert(m_wallet_descriptor.descriptor->IsSingleType());
1641 std::optional<OutputType> desc_addr_type =
1642 m_wallet_descriptor.descriptor->GetOutputType();
1643 assert(desc_addr_type);
1644 if (type != *desc_addr_type) {
1645 throw std::runtime_error(std::string(__func__) +
1646 ": Types are inconsistent");
1647 }
1648
1649 TopUp();
1650
1651 // Get the scriptPubKey from the descriptor
1652 FlatSigningProvider out_keys;
1653 std::vector<CScript> scripts_temp;
1654 if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
1655 // We can't generate anymore keys
1656 return util::Error{
1657 _("Error: Keypool ran out, please call keypoolrefill first")};
1658 }
1659 if (!m_wallet_descriptor.descriptor->ExpandFromCache(
1660 m_wallet_descriptor.next_index, m_wallet_descriptor.cache,
1661 scripts_temp, out_keys)) {
1662 // We can't generate anymore keys
1663 return util::Error{
1664 _("Error: Keypool ran out, please call keypoolrefill first")};
1665 }
1666
1667 CTxDestination dest;
1668 std::optional<OutputType> out_script_type =
1669 m_wallet_descriptor.descriptor->GetOutputType();
1670 if (out_script_type && out_script_type == type) {
1671 ExtractDestination(scripts_temp[0], dest);
1672 } else {
1673 throw std::runtime_error(
1674 std::string(__func__) +
1675 ": Types are inconsistent. Stored type does not match type of "
1676 "newly generated address");
1677 }
1678 m_wallet_descriptor.next_index++;
1680 .WriteDescriptor(GetID(), m_wallet_descriptor);
1681 return dest;
1682 }
1683}
1684
1685isminetype DescriptorScriptPubKeyMan::IsMine(const CScript &script) const {
1687 if (m_map_script_pub_keys.count(script) > 0) {
1688 return ISMINE_SPENDABLE;
1689 }
1690 return ISMINE_NO;
1691}
1692
1694 const CKeyingMaterial &master_key, bool accept_no_keys) {
1696 if (!m_map_keys.empty()) {
1697 return false;
1698 }
1699
1700 // Always pass when there are no encrypted keys
1701 bool keyPass = m_map_crypted_keys.empty();
1702 bool keyFail = false;
1703 for (const auto &mi : m_map_crypted_keys) {
1704 const CPubKey &pubkey = mi.second.first;
1705 const std::vector<uint8_t> &crypted_secret = mi.second.second;
1706 CKey key;
1707 if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
1708 keyFail = true;
1709 break;
1710 }
1711 keyPass = true;
1713 break;
1714 }
1715 }
1716 if (keyPass && keyFail) {
1717 LogPrintf("The wallet is probably corrupted: Some keys decrypt but not "
1718 "all.\n");
1719 throw std::runtime_error(
1720 "Error unlocking wallet: some keys decrypt but not all. Your "
1721 "wallet file may be corrupt.");
1722 }
1723 if (keyFail || (!keyPass && !accept_no_keys)) {
1724 return false;
1725 }
1727 return true;
1728}
1729
1731 WalletBatch *batch) {
1733 if (!m_map_crypted_keys.empty()) {
1734 return false;
1735 }
1736
1737 for (const KeyMap::value_type &key_in : m_map_keys) {
1738 const CKey &key = key_in.second;
1739 CPubKey pubkey = key.GetPubKey();
1740 CKeyingMaterial secret(key.begin(), key.end());
1741 std::vector<uint8_t> crypted_secret;
1742 if (!EncryptSecret(master_key, secret, pubkey.GetHash(),
1743 crypted_secret)) {
1744 return false;
1745 }
1746 m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1747 batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1748 }
1749 m_map_keys.clear();
1750 return true;
1751}
1752
1754 bool internal,
1755 CTxDestination &address,
1756 int64_t &index,
1757 CKeyPool &keypool) {
1759 auto op_dest = GetNewDestination(type);
1760 index = m_wallet_descriptor.next_index - 1;
1761 if (op_dest) {
1762 address = *op_dest;
1763 }
1764 return bool{op_dest};
1765}
1766
1767void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal,
1768 const CTxDestination &addr) {
1770 // Only return when the index was the most recent
1771 if (m_wallet_descriptor.next_index - 1 == index) {
1772 m_wallet_descriptor.next_index--;
1773 }
1775 .WriteDescriptor(GetID(), m_wallet_descriptor);
1777}
1778
1779std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const {
1782 KeyMap keys;
1783 for (const auto &key_pair : m_map_crypted_keys) {
1784 const CPubKey &pubkey = key_pair.second.first;
1785 const std::vector<uint8_t> &crypted_secret = key_pair.second.second;
1786 CKey key;
1788 [&](const CKeyingMaterial &encryption_key) {
1789 return DecryptKey(encryption_key, crypted_secret, pubkey,
1790 key);
1791 });
1792 keys[pubkey.GetID()] = key;
1793 }
1794 return keys;
1795 }
1796 return m_map_keys;
1797}
1798
1799bool DescriptorScriptPubKeyMan::TopUp(unsigned int size) {
1801 unsigned int target_size;
1802 if (size > 0) {
1803 target_size = size;
1804 } else {
1805 target_size = std::max(
1806 gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), int64_t(1));
1807 }
1808
1809 // Calculate the new range_end
1810 int32_t new_range_end =
1811 std::max(m_wallet_descriptor.next_index + int32_t(target_size),
1812 m_wallet_descriptor.range_end);
1813
1814 // If the descriptor is not ranged, we actually just want to fill the first
1815 // cache item
1816 if (!m_wallet_descriptor.descriptor->IsRange()) {
1817 new_range_end = 1;
1818 m_wallet_descriptor.range_end = 1;
1819 m_wallet_descriptor.range_start = 0;
1820 }
1821
1822 FlatSigningProvider provider;
1823 provider.keys = GetKeys();
1824
1826 uint256 id = GetID();
1827 for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
1828 FlatSigningProvider out_keys;
1829 std::vector<CScript> scripts_temp;
1830 DescriptorCache temp_cache;
1831 // Maybe we have a cached xpub and we can expand from the cache first
1832 if (!m_wallet_descriptor.descriptor->ExpandFromCache(
1833 i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1834 if (!m_wallet_descriptor.descriptor->Expand(
1835 i, provider, scripts_temp, out_keys, &temp_cache)) {
1836 return false;
1837 }
1838 }
1839 // Add all of the scriptPubKeys to the scriptPubKey set
1840 for (const CScript &script : scripts_temp) {
1841 m_map_script_pub_keys[script] = i;
1842 }
1843 for (const auto &pk_pair : out_keys.pubkeys) {
1844 const CPubKey &pubkey = pk_pair.second;
1845 if (m_map_pubkeys.count(pubkey) != 0) {
1846 // We don't need to give an error here.
1847 // It doesn't matter which of many valid indexes the pubkey has,
1848 // we just need an index where we can derive it and it's private
1849 // key
1850 continue;
1851 }
1852 m_map_pubkeys[pubkey] = i;
1853 }
1854 // Write the cache
1855 for (const auto &parent_xpub_pair :
1856 temp_cache.GetCachedParentExtPubKeys()) {
1857 CExtPubKey xpub;
1858 if (m_wallet_descriptor.cache.GetCachedParentExtPubKey(
1859 parent_xpub_pair.first, xpub)) {
1860 if (xpub != parent_xpub_pair.second) {
1861 throw std::runtime_error(
1862 std::string(__func__) +
1863 ": New cached parent xpub does not match already "
1864 "cached parent xpub");
1865 }
1866 continue;
1867 }
1868 if (!batch.WriteDescriptorParentCache(parent_xpub_pair.second, id,
1869 parent_xpub_pair.first)) {
1870 throw std::runtime_error(std::string(__func__) +
1871 ": writing cache item failed");
1872 }
1873 m_wallet_descriptor.cache.CacheParentExtPubKey(
1874 parent_xpub_pair.first, parent_xpub_pair.second);
1875 }
1876 for (const auto &derived_xpub_map_pair :
1877 temp_cache.GetCachedDerivedExtPubKeys()) {
1878 for (const auto &derived_xpub_pair : derived_xpub_map_pair.second) {
1879 CExtPubKey xpub;
1880 if (m_wallet_descriptor.cache.GetCachedDerivedExtPubKey(
1881 derived_xpub_map_pair.first, derived_xpub_pair.first,
1882 xpub)) {
1883 if (xpub != derived_xpub_pair.second) {
1884 throw std::runtime_error(
1885 std::string(__func__) +
1886 ": New cached derived xpub does not match already "
1887 "cached derived xpub");
1888 }
1889 continue;
1890 }
1891 if (!batch.WriteDescriptorDerivedCache(
1892 derived_xpub_pair.second, id,
1893 derived_xpub_map_pair.first, derived_xpub_pair.first)) {
1894 throw std::runtime_error(std::string(__func__) +
1895 ": writing cache item failed");
1896 }
1897 m_wallet_descriptor.cache.CacheDerivedExtPubKey(
1898 derived_xpub_map_pair.first, derived_xpub_pair.first,
1899 derived_xpub_pair.second);
1900 }
1901 }
1903 }
1904 m_wallet_descriptor.range_end = new_range_end;
1905 batch.WriteDescriptor(GetID(), m_wallet_descriptor);
1906
1907 // By this point, the cache size should be the size of the entire range
1908 assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
1909
1911 return true;
1912}
1913
1916 if (IsMine(script)) {
1917 int32_t index = m_map_script_pub_keys[script];
1918 if (index >= m_wallet_descriptor.next_index) {
1919 WalletLogPrintf("%s: Detected a used keypool item at index %d, "
1920 "mark all keypool items up to this item as used\n",
1921 __func__, index);
1922 m_wallet_descriptor.next_index = index + 1;
1923 }
1924 if (!TopUp()) {
1925 WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n",
1926 __func__);
1927 }
1928 }
1929}
1930
1932 const CPubKey &pubkey) {
1935 if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
1936 throw std::runtime_error(std::string(__func__) +
1937 ": writing descriptor private key failed");
1938 }
1939}
1940
1942 const CKey &key,
1943 const CPubKey &pubkey) {
1946
1947 // Check if provided key already exists
1948 if (m_map_keys.find(pubkey.GetID()) != m_map_keys.end() ||
1949 m_map_crypted_keys.find(pubkey.GetID()) != m_map_crypted_keys.end()) {
1950 return true;
1951 }
1952
1954 if (m_storage.IsLocked()) {
1955 return false;
1956 }
1957
1958 std::vector<uint8_t> crypted_secret;
1959 CKeyingMaterial secret(key.begin(), key.end());
1961 [&](const CKeyingMaterial &encryption_key) {
1962 return EncryptSecret(encryption_key, secret,
1963 pubkey.GetHash(), crypted_secret);
1964 })) {
1965 return false;
1966 }
1967
1968 m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1969 return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1970 } else {
1971 m_map_keys[pubkey.GetID()] = key;
1972 return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
1973 }
1974}
1975
1977 const CExtKey &master_key, OutputType addr_type) {
1980
1981 // Ignore when there is already a descriptor
1982 if (m_wallet_descriptor.descriptor) {
1983 return false;
1984 }
1985
1986 int64_t creation_time = GetTime();
1987
1988 std::string xpub = EncodeExtPubKey(master_key.Neuter());
1989
1990 // Build descriptor string
1991 std::string desc_prefix;
1992 std::string desc_suffix = "/*)";
1993 switch (addr_type) {
1994 case OutputType::LEGACY: {
1995 desc_prefix = "pkh(" + xpub + "/44'";
1996 break;
1997 }
1998 } // no default case, so the compiler can warn about missing cases
1999 assert(!desc_prefix.empty());
2000
2001 // Mainnet derives at 0', testnet and regtest derive at 1'
2003 desc_prefix += "/1'";
2004 } else {
2005 desc_prefix += "/0'";
2006 }
2007
2008 std::string internal_path = m_internal ? "/1" : "/0";
2009 std::string desc_str = desc_prefix + "/0'" + internal_path + desc_suffix;
2010
2011 // Make the descriptor
2013 std::string error;
2014 std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, error, false);
2015 WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
2016 m_wallet_descriptor = w_desc;
2017
2018 // Store the master private key, and descriptor
2020 if (!AddDescriptorKeyWithDB(batch, master_key.key,
2021 master_key.key.GetPubKey())) {
2022 throw std::runtime_error(
2023 std::string(__func__) +
2024 ": writing descriptor master private key failed");
2025 }
2026 if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
2027 throw std::runtime_error(std::string(__func__) +
2028 ": writing descriptor failed");
2029 }
2030
2031 // TopUp
2032 TopUp();
2033
2035 return true;
2036}
2037
2040 return m_wallet_descriptor.descriptor->IsRange();
2041}
2042
2044 // We can only give out addresses from descriptors that are single type (not
2045 // combo), ranged, and either have cached keys or can generate more keys
2046 // (ignoring encryption)
2048 return m_wallet_descriptor.descriptor->IsSingleType() &&
2049 m_wallet_descriptor.descriptor->IsRange() &&
2050 (HavePrivateKeys() ||
2051 m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
2052}
2053
2056 return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
2057}
2058
2060 // This is only used for getwalletinfo output and isn't relevant to
2061 // descriptor wallets. The magic number 0 indicates that it shouldn't be
2062 // displayed so that's what we return.
2063 return 0;
2064}
2065
2067 if (m_internal) {
2068 return 0;
2069 }
2070 return GetKeyPoolSize();
2071}
2072
2075 return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
2076}
2077
2080 return m_wallet_descriptor.creation_time;
2081}
2082
2083std::unique_ptr<FlatSigningProvider>
2085 bool include_private) const {
2087
2088 // Find the index of the script
2089 auto it = m_map_script_pub_keys.find(script);
2090 if (it == m_map_script_pub_keys.end()) {
2091 return nullptr;
2092 }
2093 int32_t index = it->second;
2094
2095 return GetSigningProvider(index, include_private);
2096}
2097
2098std::unique_ptr<FlatSigningProvider>
2101
2102 // Find index of the pubkey
2103 auto it = m_map_pubkeys.find(pubkey);
2104 if (it == m_map_pubkeys.end()) {
2105 return nullptr;
2106 }
2107 int32_t index = it->second;
2108
2109 // Always try to get the signing provider with private keys. This function
2110 // should only be called during signing anyways
2111 return GetSigningProvider(index, true);
2112}
2113
2114std::unique_ptr<FlatSigningProvider>
2116 bool include_private) const {
2118 // Get the scripts, keys, and key origins for this script
2119 std::unique_ptr<FlatSigningProvider> out_keys =
2120 std::make_unique<FlatSigningProvider>();
2121 std::vector<CScript> scripts_temp;
2122 if (!m_wallet_descriptor.descriptor->ExpandFromCache(
2123 index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
2124 return nullptr;
2125 }
2126
2127 if (HavePrivateKeys() && include_private) {
2128 FlatSigningProvider master_provider;
2129 master_provider.keys = GetKeys();
2130 m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider,
2131 *out_keys);
2132 }
2133
2134 return out_keys;
2135}
2136
2137std::unique_ptr<SigningProvider>
2139 return GetSigningProvider(script, false);
2140}
2141
2142bool DescriptorScriptPubKeyMan::CanProvide(const CScript &script,
2143 SignatureData &sigdata) {
2144 return IsMine(script);
2145}
2146
2148 CMutableTransaction &tx, const std::map<COutPoint, Coin> &coins,
2149 SigHashType sighash, std::map<int, std::string> &input_errors) const {
2150 std::unique_ptr<FlatSigningProvider> keys =
2151 std::make_unique<FlatSigningProvider>();
2152 for (const auto &coin_pair : coins) {
2153 std::unique_ptr<FlatSigningProvider> coin_keys =
2154 GetSigningProvider(coin_pair.second.GetTxOut().scriptPubKey, true);
2155 if (!coin_keys) {
2156 continue;
2157 }
2158 *keys = Merge(*keys, *coin_keys);
2159 }
2160
2161 return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
2162}
2163
2166 const PKHash &pkhash,
2167 std::string &str_sig) const {
2168 std::unique_ptr<FlatSigningProvider> keys =
2170 if (!keys) {
2172 }
2173
2174 CKey key;
2175 if (!keys->GetKey(ToKeyID(pkhash), key)) {
2177 }
2178
2179 if (!MessageSign(key, message, str_sig)) {
2181 }
2182 return SigningResult::OK;
2183}
2184
2187 SigHashType sighash_type, bool sign,
2188 bool bip32derivs) const {
2189 for (size_t i = 0; i < psbtx.tx->vin.size(); ++i) {
2190 PSBTInput &input = psbtx.inputs.at(i);
2191
2192 if (PSBTInputSigned(input)) {
2193 continue;
2194 }
2195
2196 // Get the Sighash type
2197 if (sign && input.sighash_type.getRawSigHashType() > 0 &&
2198 input.sighash_type != sighash_type) {
2200 }
2201
2202 // Get the scriptPubKey to know which SigningProvider to use
2203 CScript script;
2204 if (!input.utxo.IsNull()) {
2205 script = input.utxo.scriptPubKey;
2206 } else {
2207 // There's no UTXO so we can just skip this now
2208 continue;
2209 }
2210 SignatureData sigdata;
2211 input.FillSignatureData(sigdata);
2212
2213 std::unique_ptr<FlatSigningProvider> keys =
2214 std::make_unique<FlatSigningProvider>();
2215 std::unique_ptr<FlatSigningProvider> script_keys =
2216 GetSigningProvider(script, sign);
2217 if (script_keys) {
2218 *keys = Merge(*keys, *script_keys);
2219 } else {
2220 // Maybe there are pubkeys listed that we can sign for
2221 script_keys = std::make_unique<FlatSigningProvider>();
2222 for (const auto &pk_pair : input.hd_keypaths) {
2223 const CPubKey &pubkey = pk_pair.first;
2224 std::unique_ptr<FlatSigningProvider> pk_keys =
2225 GetSigningProvider(pubkey);
2226 if (pk_keys) {
2227 *keys = Merge(*keys, *pk_keys);
2228 }
2229 }
2230 }
2231
2232 SignPSBTInput(HidingSigningProvider(keys.get(), !sign, !bip32derivs),
2233 psbtx, i, sighash_type);
2234 }
2235
2236 // Fill in the bip32 keypaths and redeemscripts for the outputs so that
2237 // hardware wallets can identify change
2238 for (size_t i = 0; i < psbtx.tx->vout.size(); ++i) {
2239 std::unique_ptr<SigningProvider> keys =
2240 GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
2241 if (!keys) {
2242 continue;
2243 }
2244 UpdatePSBTOutput(HidingSigningProvider(keys.get(), true, !bip32derivs),
2245 psbtx, i);
2246 }
2247
2248 return TransactionError::OK;
2249}
2250
2251std::unique_ptr<CKeyMetadata>
2253 std::unique_ptr<SigningProvider> provider =
2255 if (provider) {
2256 KeyOriginInfo orig;
2257 CKeyID key_id = GetKeyForDestination(*provider, dest);
2258 if (provider->GetKeyOrigin(key_id, orig)) {
2260 std::unique_ptr<CKeyMetadata> meta =
2261 std::make_unique<CKeyMetadata>();
2262 meta->key_origin = orig;
2263 meta->has_key_origin = true;
2264 meta->nCreateTime = m_wallet_descriptor.creation_time;
2265 return meta;
2266 }
2267 }
2268 return nullptr;
2269}
2270
2273 std::string desc_str = m_wallet_descriptor.descriptor->ToString();
2274 uint256 id;
2275 CSHA256()
2276 .Write((uint8_t *)desc_str.data(), desc_str.size())
2277 .Finalize(id.begin());
2278 return id;
2279}
2280
2282 this->m_internal = internal;
2283}
2284
2287 m_wallet_descriptor.cache = cache;
2288 for (int32_t i = m_wallet_descriptor.range_start;
2289 i < m_wallet_descriptor.range_end; ++i) {
2290 FlatSigningProvider out_keys;
2291 std::vector<CScript> scripts_temp;
2292 if (!m_wallet_descriptor.descriptor->ExpandFromCache(
2293 i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2294 throw std::runtime_error(
2295 "Error: Unable to expand wallet descriptor from cache");
2296 }
2297 // Add all of the scriptPubKeys to the scriptPubKey set
2298 for (const CScript &script : scripts_temp) {
2299 if (m_map_script_pub_keys.count(script) != 0) {
2300 throw std::runtime_error(
2301 strprintf("Error: Already loaded script at index %d as "
2302 "being at index %d",
2303 i, m_map_script_pub_keys[script]));
2304 }
2305 m_map_script_pub_keys[script] = i;
2306 }
2307 for (const auto &pk_pair : out_keys.pubkeys) {
2308 const CPubKey &pubkey = pk_pair.second;
2309 if (m_map_pubkeys.count(pubkey) != 0) {
2310 // We don't need to give an error here.
2311 // It doesn't matter which of many valid indexes the pubkey has,
2312 // we just need an index where we can derive it and it's private
2313 // key
2314 continue;
2315 }
2316 m_map_pubkeys[pubkey] = i;
2317 }
2319 }
2320}
2321
2322bool DescriptorScriptPubKeyMan::AddKey(const CKeyID &key_id, const CKey &key) {
2324 m_map_keys[key_id] = key;
2325 return true;
2326}
2327
2329 const CKeyID &key_id, const CPubKey &pubkey,
2330 const std::vector<uint8_t> &crypted_key) {
2332 if (!m_map_keys.empty()) {
2333 return false;
2334 }
2335
2336 m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
2337 return true;
2338}
2339
2341 const WalletDescriptor &desc) const {
2343 return m_wallet_descriptor.descriptor != nullptr &&
2344 desc.descriptor != nullptr &&
2345 m_wallet_descriptor.descriptor->ToString() ==
2346 desc.descriptor->ToString();
2347}
2348
2352 if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
2353 throw std::runtime_error(std::string(__func__) +
2354 ": writing descriptor failed");
2355 }
2356}
2357
2359 return m_wallet_descriptor;
2360}
2361
2364 std::vector<CScript> script_pub_keys;
2365 script_pub_keys.reserve(m_map_script_pub_keys.size());
2366
2367 for (auto const &script_pub_key : m_map_script_pub_keys) {
2368 script_pub_keys.push_back(script_pub_key.first);
2369 }
2370 return script_pub_keys;
2371}
2372
2374 WalletDescriptor &descriptor) {
2376 std::string error;
2377 if (!CanUpdateToWalletDescriptor(descriptor, error)) {
2378 throw std::runtime_error(std::string(__func__) + ": " + error);
2379 }
2380
2381 m_map_pubkeys.clear();
2382 m_map_script_pub_keys.clear();
2383 m_max_cached_index = -1;
2384 m_wallet_descriptor = descriptor;
2385}
2386
2388 const WalletDescriptor &descriptor, std::string &error) {
2390 if (!HasWalletDescriptor(descriptor)) {
2391 error = "can only update matching descriptor";
2392 return false;
2393 }
2394
2395 if (descriptor.range_start > m_wallet_descriptor.range_start ||
2396 descriptor.range_end < m_wallet_descriptor.range_end) {
2397 // Use inclusive range for error
2398 error = strprintf("new range must include current range = [%d,%d]",
2399 m_wallet_descriptor.range_start,
2400 m_wallet_descriptor.range_end - 1);
2401 return false;
2402 }
2403
2404 return true;
2405}
ArgsManager gArgs
Definition: args.cpp:40
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:495
bool IsTestChain() const
If this chain is exclusively used for testing.
Definition: chainparams.h:118
static const int VERSION_HD_BASE
Definition: walletdb.h:95
uint32_t nInternalChainCounter
Definition: walletdb.h:91
CKeyID seed_id
seed hash160
Definition: walletdb.h:93
static const int VERSION_HD_CHAIN_SPLIT
Definition: walletdb.h:96
int nVersion
Definition: walletdb.h:98
uint32_t nExternalChainCounter
Definition: walletdb.h:90
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:125
KeyOriginInfo key_origin
Definition: walletdb.h:136
bool has_key_origin
Whether the key_origin is useful.
Definition: walletdb.h:138
int nVersion
Definition: walletdb.h:127
std::string hdKeypath
Definition: walletdb.h:132
int64_t nCreateTime
Definition: walletdb.h:129
CKeyID hd_seed_id
Definition: walletdb.h:134
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
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)
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
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::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)
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:176
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:1098
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:228
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:93
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
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:25
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:108
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
#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:105
#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