Bitcoin ABC  0.22.12
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 <config.h>
7 #include <key_io.h>
8 #include <outputtype.h>
9 #include <script/descriptor.h>
10 #include <script/sign.h>
11 #include <util/bip32.h>
12 #include <util/strencodings.h>
13 #include <util/string.h>
14 #include <util/translation.h>
15 #include <wallet/scriptpubkeyman.h>
16 
18  CTxDestination &dest,
19  std::string &error) {
21  error.clear();
22 
23  // Generate a new key that is added to wallet
24  CPubKey new_key;
25  if (!GetKeyFromPool(new_key, type)) {
26  error = _("Error: Keypool ran out, please call keypoolrefill first")
27  .translated;
28  return false;
29  }
30  LearnRelatedScripts(new_key, type);
31  dest = GetDestinationForKey(new_key, type);
32  return true;
33 }
34 
35 typedef std::vector<uint8_t> valtype;
36 
37 namespace {
38 
45 enum class IsMineSigVersion {
46  TOP = 0,
47  P2SH = 1,
48 };
49 
55 enum class IsMineResult {
56  NO = 0,
57  WATCH_ONLY = 1,
58  SPENDABLE = 2,
59  INVALID = 3,
60 };
61 
62 bool HaveKeys(const std::vector<valtype> &pubkeys,
63  const LegacyScriptPubKeyMan &keystore) {
64  for (const valtype &pubkey : pubkeys) {
65  CKeyID keyID = CPubKey(pubkey).GetID();
66  if (!keystore.HaveKey(keyID)) {
67  return false;
68  }
69  }
70  return true;
71 }
72 
73 IsMineResult IsMineInner(const LegacyScriptPubKeyMan &keystore,
74  const CScript &scriptPubKey,
75  IsMineSigVersion sigversion) {
76  IsMineResult ret = IsMineResult::NO;
77 
78  std::vector<valtype> vSolutions;
79  txnouttype whichType = Solver(scriptPubKey, vSolutions);
80 
81  CKeyID keyID;
82  switch (whichType) {
83  case TX_NONSTANDARD:
84  case TX_NULL_DATA:
85  break;
86  case TX_PUBKEY:
87  keyID = CPubKey(vSolutions[0]).GetID();
88  if (keystore.HaveKey(keyID)) {
89  ret = std::max(ret, IsMineResult::SPENDABLE);
90  }
91  break;
92  case TX_PUBKEYHASH:
93  keyID = CKeyID(uint160(vSolutions[0]));
94  if (keystore.HaveKey(keyID)) {
95  ret = std::max(ret, IsMineResult::SPENDABLE);
96  }
97  break;
98  case TX_SCRIPTHASH: {
99  if (sigversion != IsMineSigVersion::TOP) {
100  // P2SH inside P2SH is invalid.
101  return IsMineResult::INVALID;
102  }
103  CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
104  CScript subscript;
105  if (keystore.GetCScript(scriptID, subscript)) {
106  ret = std::max(ret, IsMineInner(keystore, subscript,
107  IsMineSigVersion::P2SH));
108  }
109  break;
110  }
111  case TX_MULTISIG: {
112  // Never treat bare multisig outputs as ours (they can still be made
113  // watchonly-though)
114  if (sigversion == IsMineSigVersion::TOP) {
115  break;
116  }
117 
118  // Only consider transactions "mine" if we own ALL the keys
119  // involved. Multi-signature transactions that are partially owned
120  // (somebody else has a key that can spend them) enable
121  // spend-out-from-under-you attacks, especially in shared-wallet
122  // situations.
123  std::vector<valtype> keys(vSolutions.begin() + 1,
124  vSolutions.begin() + vSolutions.size() -
125  1);
126  if (HaveKeys(keys, keystore)) {
127  ret = std::max(ret, IsMineResult::SPENDABLE);
128  }
129  break;
130  }
131  }
132 
133  if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
134  ret = std::max(ret, IsMineResult::WATCH_ONLY);
135  }
136  return ret;
137 }
138 
139 } // namespace
140 
142  switch (IsMineInner(*this, script, IsMineSigVersion::TOP)) {
143  case IsMineResult::INVALID:
144  case IsMineResult::NO:
145  return ISMINE_NO;
146  case IsMineResult::WATCH_ONLY:
147  return ISMINE_WATCH_ONLY;
148  case IsMineResult::SPENDABLE:
149  return ISMINE_SPENDABLE;
150  }
151  assert(false);
152 }
153 
155  const CKeyingMaterial &master_key, bool accept_no_keys) {
156  {
157  LOCK(cs_KeyStore);
158  assert(mapKeys.empty());
159 
160  // Always pass when there are no encrypted keys
161  bool keyPass = mapCryptedKeys.empty();
162  bool keyFail = false;
163  CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
164  for (; mi != mapCryptedKeys.end(); ++mi) {
165  const CPubKey &vchPubKey = (*mi).second.first;
166  const std::vector<uint8_t> &vchCryptedSecret = (*mi).second.second;
167  CKey key;
168  if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key)) {
169  keyFail = true;
170  break;
171  }
172  keyPass = true;
174  break;
175  }
176  }
177  if (keyPass && keyFail) {
178  LogPrintf("The wallet is probably corrupted: Some keys decrypt but "
179  "not all.\n");
180  throw std::runtime_error(
181  "Error unlocking wallet: some keys decrypt but not all. Your "
182  "wallet file may be corrupt.");
183  }
184  if (keyFail || (!keyPass && !accept_no_keys)) {
185  return false;
186  }
188  }
189  return true;
190 }
191 
193  WalletBatch *batch) {
194  LOCK(cs_KeyStore);
195  encrypted_batch = batch;
196  if (!mapCryptedKeys.empty()) {
197  encrypted_batch = nullptr;
198  return false;
199  }
200 
201  KeyMap keys_to_encrypt;
202  // Clear mapKeys so AddCryptedKeyInner will succeed.
203  keys_to_encrypt.swap(mapKeys);
204  for (const KeyMap::value_type &mKey : keys_to_encrypt) {
205  const CKey &key = mKey.second;
206  CPubKey vchPubKey = key.GetPubKey();
207  CKeyingMaterial vchSecret(key.begin(), key.end());
208  std::vector<uint8_t> vchCryptedSecret;
209  if (!EncryptSecret(master_key, vchSecret, vchPubKey.GetHash(),
210  vchCryptedSecret)) {
211  encrypted_batch = nullptr;
212  return false;
213  }
214  if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) {
215  encrypted_batch = nullptr;
216  return false;
217  }
218  }
219  encrypted_batch = nullptr;
220  return true;
221 }
222 
224  bool internal,
225  CTxDestination &address,
226  int64_t &index,
227  CKeyPool &keypool) {
228  LOCK(cs_KeyStore);
229  if (!CanGetAddresses(internal)) {
230  return false;
231  }
232 
233  if (!ReserveKeyFromKeyPool(index, keypool, internal)) {
234  return false;
235  }
236  address = GetDestinationForKey(keypool.vchPubKey, type);
237  return true;
238 }
239 
241  LOCK(cs_KeyStore);
242  // extract addresses and check if they match with an unused keypool key
243  for (const auto &keyid : GetAffectedKeys(script, *this)) {
244  std::map<CKeyID, int64_t>::const_iterator mi =
245  m_pool_key_to_index.find(keyid);
246  if (mi != m_pool_key_to_index.end()) {
247  WalletLogPrintf("%s: Detected a used keypool key, mark all keypool "
248  "key up to this key as used\n",
249  __func__);
250  MarkReserveKeysAsUsed(mi->second);
251 
252  if (!TopUp()) {
254  "%s: Topping up keypool failed (locked wallet)\n",
255  __func__);
256  }
257  }
258  }
259 }
260 
262  LOCK(cs_KeyStore);
263  if (m_storage.IsLocked() ||
265  return;
266  }
267 
268  auto batch = std::make_unique<WalletBatch>(m_storage.GetDatabase());
269  for (auto &meta_pair : mapKeyMetadata) {
270  CKeyMetadata &meta = meta_pair.second;
271  // If the hdKeypath is "s", that's the seed and it doesn't have a key
272  // origin
273  if (!meta.hd_seed_id.IsNull() && !meta.has_key_origin &&
274  meta.hdKeypath != "s") {
275  CKey key;
276  GetKey(meta.hd_seed_id, key);
277  CExtKey masterKey;
278  masterKey.SetSeed(key.begin(), key.size());
279  // Add to map
280  CKeyID master_id = masterKey.key.GetPubKey().GetID();
281  std::copy(master_id.begin(), master_id.begin() + 4,
282  meta.key_origin.fingerprint);
283  if (!ParseHDKeypath(meta.hdKeypath, meta.key_origin.path)) {
284  throw std::runtime_error("Invalid stored hdKeypath");
285  }
286  meta.has_key_origin = true;
289  }
290 
291  // Write meta to wallet
292  CPubKey pubkey;
293  if (GetPubKey(meta_pair.first, pubkey)) {
294  batch->WriteKeyMetadata(meta, pubkey, true);
295  }
296  }
297  }
298 }
299 
301  if ((CanGenerateKeys() && !force) || m_storage.IsLocked()) {
302  return false;
303  }
304 
306  if (!NewKeyPool()) {
307  return false;
308  }
309  return true;
310 }
311 
313  return !hdChain.seed_id.IsNull();
314 }
315 
316 bool LegacyScriptPubKeyMan::CanGetAddresses(bool internal) const {
317  LOCK(cs_KeyStore);
318  // Check if the keypool has keys
319  bool keypool_has_keys;
320  if (internal && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
321  keypool_has_keys = setInternalKeyPool.size() > 0;
322  } else {
323  keypool_has_keys = KeypoolCountExternalKeys() > 0;
324  }
325  // If the keypool doesn't have keys, check if we can generate them
326  if (!keypool_has_keys) {
327  return CanGenerateKeys();
328  }
329  return keypool_has_keys;
330 }
331 
333  LOCK(cs_KeyStore);
334  bool hd_upgrade = false;
335  bool split_upgrade = false;
337  WalletLogPrintf("Upgrading wallet to HD\n");
339 
340  // generate a new master key
341  CPubKey masterPubKey = GenerateNewSeed();
342  SetHDSeed(masterPubKey);
343  hd_upgrade = true;
344  }
345  // Upgrade to HD chain split if necessary
348  WalletLogPrintf("Upgrading wallet to use HD chain split\n");
350  split_upgrade = FEATURE_HD_SPLIT > prev_version;
351  }
352  // Mark all keys currently in the keypool as pre-split
353  if (split_upgrade) {
355  }
356  // Regenerate the keypool if upgraded to HD
357  if (hd_upgrade) {
358  if (!TopUp()) {
359  error = _("Unable to generate keys");
360  return false;
361  }
362  }
363  return true;
364 }
365 
367  LOCK(cs_KeyStore);
368  return !mapKeys.empty() || !mapCryptedKeys.empty();
369 }
370 
372  LOCK(cs_KeyStore);
373  setInternalKeyPool.clear();
374  setExternalKeyPool.clear();
375  m_pool_key_to_index.clear();
376  // Note: can't top-up keypool here, because wallet is locked.
377  // User will be prompted to unlock wallet the next operation
378  // that requires a new key.
379 }
380 
381 static int64_t GetOldestKeyTimeInPool(const std::set<int64_t> &setKeyPool,
382  WalletBatch &batch) {
383  if (setKeyPool.empty()) {
384  return GetTime();
385  }
386 
387  CKeyPool keypool;
388  int64_t nIndex = *(setKeyPool.begin());
389  if (!batch.ReadPool(nIndex, keypool)) {
390  throw std::runtime_error(std::string(__func__) +
391  ": read oldest key in keypool failed");
392  }
393 
394  assert(keypool.vchPubKey.IsValid());
395  return keypool.nTime;
396 }
397 
399  LOCK(cs_KeyStore);
400 
402 
403  // load oldest key from keypool, get time and return
404  int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, batch);
406  oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, batch),
407  oldestKey);
408  if (!set_pre_split_keypool.empty()) {
409  oldestKey =
410  std::max(GetOldestKeyTimeInPool(set_pre_split_keypool, batch),
411  oldestKey);
412  }
413  }
414 
415  return oldestKey;
416 }
417 
419  LOCK(cs_KeyStore);
420  return setExternalKeyPool.size() + set_pre_split_keypool.size();
421 }
422 
424  LOCK(cs_KeyStore);
425  return setInternalKeyPool.size() + setExternalKeyPool.size() +
426  set_pre_split_keypool.size();
427 }
428 
430  LOCK(cs_KeyStore);
431  return nTimeFirstKey;
432 }
433 
434 std::unique_ptr<SigningProvider>
436  return std::make_unique<LegacySigningProvider>(*this);
437 }
438 
440  SignatureData &sigdata) {
441  if (IsMine(script) != ISMINE_NO) {
442  // If it IsMine, we can always provide in some way
443  return true;
444  }
445  if (HaveCScript(CScriptID(script))) {
446  // We can still provide some stuff if we have the script, but IsMine
447  // failed because we don't have keys
448  return true;
449  }
450  // If, given the stuff in sigdata, we could make a valid sigature, then
451  // we can provide for this script
452  ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
453  if (!sigdata.signatures.empty()) {
454  // If we could make signatures, make sure we have a private key to
455  // actually make a signature
456  bool has_privkeys = false;
457  for (const auto &key_sig_pair : sigdata.signatures) {
458  has_privkeys |= HaveKey(key_sig_pair.first);
459  }
460  return has_privkeys;
461  }
462  return false;
463 }
464 
466  CMutableTransaction &tx, const std::map<COutPoint, Coin> &coins,
467  SigHashType sighash, std::map<int, std::string> &input_errors) const {
468  return ::SignTransaction(tx, this, coins, sighash, input_errors);
469 }
470 
472  const PKHash &pkhash,
473  std::string &str_sig) const {
474  CKeyID key_id(pkhash);
475  CKey key;
476  if (!GetKey(key_id, key)) {
478  }
479 
480  if (MessageSign(key, message, str_sig)) {
481  return SigningResult::OK;
482  }
484 }
485 
488  SigHashType sighash_type, bool sign,
489  bool bip32derivs) const {
490  for (size_t i = 0; i < psbtx.tx->vin.size(); ++i) {
491  PSBTInput &input = psbtx.inputs.at(i);
492 
493  if (PSBTInputSigned(input)) {
494  continue;
495  }
496 
497  // Verify input looks sane. This will check that we have at most one
498  // uxto, witness or non-witness.
499  if (!input.IsSane()) {
501  }
502 
503  // Get the Sighash type
504  if (sign && input.sighash_type.getRawSigHashType() > 0 &&
505  input.sighash_type != sighash_type) {
507  }
508 
509  if (input.utxo.IsNull()) {
510  // There's no UTXO so we can just skip this now
511  continue;
512  }
513  SignatureData sigdata;
514  input.FillSignatureData(sigdata);
515  SignPSBTInput(HidingSigningProvider(this, !sign, !bip32derivs), psbtx,
516  i, sighash_type);
517  }
518 
519  // Fill in the bip32 keypaths and redeemscripts for the outputs so that
520  // hardware wallets can identify change
521  for (size_t i = 0; i < psbtx.tx->vout.size(); ++i) {
522  UpdatePSBTOutput(HidingSigningProvider(this, true, !bip32derivs), psbtx,
523  i);
524  }
525 
526  return TransactionError::OK;
527 }
528 
529 std::unique_ptr<CKeyMetadata>
531  LOCK(cs_KeyStore);
532 
533  CKeyID key_id = GetKeyForDestination(*this, dest);
534  if (!key_id.IsNull()) {
535  auto it = mapKeyMetadata.find(key_id);
536  if (it != mapKeyMetadata.end()) {
537  return std::make_unique<CKeyMetadata>(it->second);
538  }
539  }
540 
541  CScript scriptPubKey = GetScriptForDestination(dest);
542  auto it = m_script_metadata.find(CScriptID(scriptPubKey));
543  if (it != m_script_metadata.end()) {
544  return std::make_unique<CKeyMetadata>(it->second);
545  }
546 
547  return nullptr;
548 }
549 
551  return UINT256_ONE();
552 }
553 
558 void LegacyScriptPubKeyMan::UpdateTimeFirstKey(int64_t nCreateTime) {
560  if (nCreateTime <= 1) {
561  // Cannot determine birthday information, so set the wallet birthday to
562  // the beginning of time.
563  nTimeFirstKey = 1;
564  } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
565  nTimeFirstKey = nCreateTime;
566  }
567 }
568 
569 bool LegacyScriptPubKeyMan::LoadKey(const CKey &key, const CPubKey &pubkey) {
570  return AddKeyPubKeyInner(key, pubkey);
571 }
572 
574  const CPubKey &pubkey) {
575  LOCK(cs_KeyStore);
577  return LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(batch, secret, pubkey);
578 }
579 
581  const CKey &secret,
582  const CPubKey &pubkey) {
584 
585  // Make sure we aren't adding private keys to private key disabled wallets
587 
588  // FillableSigningProvider has no concept of wallet databases, but calls
589  // AddCryptedKey which is overridden below. To avoid flushes, the database
590  // handle is tunneled through to it.
591  bool needsDB = !encrypted_batch;
592  if (needsDB) {
593  encrypted_batch = &batch;
594  }
595  if (!AddKeyPubKeyInner(secret, pubkey)) {
596  if (needsDB) {
597  encrypted_batch = nullptr;
598  }
599  return false;
600  }
601 
602  if (needsDB) {
603  encrypted_batch = nullptr;
604  }
605 
606  // Check if we need to remove from watch-only.
607  CScript script;
608  script = GetScriptForDestination(PKHash(pubkey));
609  if (HaveWatchOnly(script)) {
610  RemoveWatchOnly(script);
611  }
612 
613  script = GetScriptForRawPubKey(pubkey);
614  if (HaveWatchOnly(script)) {
615  RemoveWatchOnly(script);
616  }
617 
618  if (!m_storage.HasEncryptionKeys()) {
619  return batch.WriteKey(pubkey, secret.GetPrivKey(),
620  mapKeyMetadata[pubkey.GetID()]);
621  }
623  return true;
624 }
625 
626 bool LegacyScriptPubKeyMan::LoadCScript(const CScript &redeemScript) {
632  if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) {
633  std::string strAddr =
634  EncodeDestination(ScriptHash(redeemScript), GetConfig());
635  WalletLogPrintf("%s: Warning: This wallet contains a redeemScript "
636  "of size %i which exceeds maximum size %i thus can "
637  "never be redeemed. Do not use address %s.\n",
638  __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE,
639  strAddr);
640  return true;
641  }
642 
643  return FillableSigningProvider::AddCScript(redeemScript);
644 }
645 
647  const CKeyMetadata &meta) {
648  LOCK(cs_KeyStore);
650  mapKeyMetadata[keyID] = meta;
651 }
652 
654  const CKeyMetadata &meta) {
655  LOCK(cs_KeyStore);
657  m_script_metadata[script_id] = meta;
658 }
659 
661  const CPubKey &pubkey) {
662  LOCK(cs_KeyStore);
663  if (!m_storage.HasEncryptionKeys()) {
664  return FillableSigningProvider::AddKeyPubKey(key, pubkey);
665  }
666 
667  if (m_storage.IsLocked()) {
668  return false;
669  }
670 
671  std::vector<uint8_t> vchCryptedSecret;
672  CKeyingMaterial vchSecret(key.begin(), key.end());
673  if (!EncryptSecret(m_storage.GetEncryptionKey(), vchSecret,
674  pubkey.GetHash(), vchCryptedSecret)) {
675  return false;
676  }
677 
678  if (!AddCryptedKey(pubkey, vchCryptedSecret)) {
679  return false;
680  }
681  return true;
682 }
683 
685  const CPubKey &vchPubKey, const std::vector<uint8_t> &vchCryptedSecret) {
686  return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
687 }
688 
690  const CPubKey &vchPubKey, const std::vector<uint8_t> &vchCryptedSecret) {
691  LOCK(cs_KeyStore);
692  assert(mapKeys.empty());
693 
694  mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
695  return true;
696 }
697 
699  const CPubKey &vchPubKey, const std::vector<uint8_t> &vchCryptedSecret) {
700  if (!AddCryptedKeyInner(vchPubKey, vchCryptedSecret)) {
701  return false;
702  }
703 
704  LOCK(cs_KeyStore);
705  if (encrypted_batch) {
706  return encrypted_batch->WriteCryptedKey(
707  vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
708  }
709 
711  .WriteCryptedKey(vchPubKey, vchCryptedSecret,
712  mapKeyMetadata[vchPubKey.GetID()]);
713 }
714 
716  LOCK(cs_KeyStore);
717  return setWatchOnly.count(dest) > 0;
718 }
719 
721  LOCK(cs_KeyStore);
722  return (!setWatchOnly.empty());
723 }
724 
725 static bool ExtractPubKey(const CScript &dest, CPubKey &pubKeyOut) {
726  std::vector<std::vector<uint8_t>> solutions;
727  return Solver(dest, solutions) == TX_PUBKEY &&
728  (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
729 }
730 
732  {
733  LOCK(cs_KeyStore);
734  setWatchOnly.erase(dest);
735  CPubKey pubKey;
736  if (ExtractPubKey(dest, pubKey)) {
737  mapWatchKeys.erase(pubKey.GetID());
738  }
739  }
740 
741  if (!HaveWatchOnly()) {
742  NotifyWatchonlyChanged(false);
743  }
744 
745  return WalletBatch(m_storage.GetDatabase()).EraseWatchOnly(dest);
746 }
747 
749  return AddWatchOnlyInMem(dest);
750 }
751 
753  LOCK(cs_KeyStore);
754  setWatchOnly.insert(dest);
755  CPubKey pubKey;
756  if (ExtractPubKey(dest, pubKey)) {
757  mapWatchKeys[pubKey.GetID()] = pubKey;
758  }
759  return true;
760 }
761 
763  const CScript &dest) {
764  if (!AddWatchOnlyInMem(dest)) {
765  return false;
766  }
767 
768  const CKeyMetadata &meta = m_script_metadata[CScriptID(dest)];
771  if (batch.WriteWatchOnly(dest, meta)) {
773  return true;
774  }
775  return false;
776 }
777 
779  const CScript &dest,
780  int64_t create_time) {
781  m_script_metadata[CScriptID(dest)].nCreateTime = create_time;
782  return AddWatchOnlyWithDB(batch, dest);
783 }
784 
787  return AddWatchOnlyWithDB(batch, dest);
788 }
789 
791  int64_t nCreateTime) {
792  m_script_metadata[CScriptID(dest)].nCreateTime = nCreateTime;
793  return AddWatchOnly(dest);
794 }
795 
796 void LegacyScriptPubKeyMan::SetHDChain(const CHDChain &chain, bool memonly) {
797  LOCK(cs_KeyStore);
798  if (!memonly && !WalletBatch(m_storage.GetDatabase()).WriteHDChain(chain)) {
799  throw std::runtime_error(std::string(__func__) +
800  ": writing chain failed");
801  }
802 
803  hdChain = chain;
804 }
805 
806 bool LegacyScriptPubKeyMan::HaveKey(const CKeyID &address) const {
807  LOCK(cs_KeyStore);
808  if (!m_storage.HasEncryptionKeys()) {
809  return FillableSigningProvider::HaveKey(address);
810  }
811  return mapCryptedKeys.count(address) > 0;
812 }
813 
814 bool LegacyScriptPubKeyMan::GetKey(const CKeyID &address, CKey &keyOut) const {
815  LOCK(cs_KeyStore);
816  if (!m_storage.HasEncryptionKeys()) {
817  return FillableSigningProvider::GetKey(address, keyOut);
818  }
819 
820  CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
821  if (mi != mapCryptedKeys.end()) {
822  const CPubKey &vchPubKey = (*mi).second.first;
823  const std::vector<uint8_t> &vchCryptedSecret = (*mi).second.second;
824  return DecryptKey(m_storage.GetEncryptionKey(), vchCryptedSecret,
825  vchPubKey, keyOut);
826  }
827  return false;
828 }
829 
831  KeyOriginInfo &info) const {
832  CKeyMetadata meta;
833  {
834  LOCK(cs_KeyStore);
835  auto it = mapKeyMetadata.find(keyID);
836  if (it != mapKeyMetadata.end()) {
837  meta = it->second;
838  }
839  }
840  if (meta.has_key_origin) {
841  std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4,
842  info.fingerprint);
843  info.path = meta.key_origin.path;
844  } else {
845  // Single pubkeys get the master fingerprint of themselves
846  std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
847  }
848  return true;
849 }
850 
852  CPubKey &pubkey_out) const {
853  LOCK(cs_KeyStore);
854  WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
855  if (it != mapWatchKeys.end()) {
856  pubkey_out = it->second;
857  return true;
858  }
859  return false;
860 }
861 
863  CPubKey &vchPubKeyOut) const {
864  LOCK(cs_KeyStore);
865  if (!m_storage.HasEncryptionKeys()) {
866  if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
867  return GetWatchPubKey(address, vchPubKeyOut);
868  }
869  return true;
870  }
871 
872  CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
873  if (mi != mapCryptedKeys.end()) {
874  vchPubKeyOut = (*mi).second.first;
875  return true;
876  }
877 
878  // Check for watch-only pubkeys
879  return GetWatchPubKey(address, vchPubKeyOut);
880 }
881 
883  bool internal) {
887  // default to compressed public keys if we want 0.6.0 wallets
888  bool fCompressed = m_storage.CanSupportFeature(FEATURE_COMPRPUBKEY);
889 
890  CKey secret;
891 
892  // Create new metadata
893  int64_t nCreationTime = GetTime();
894  CKeyMetadata metadata(nCreationTime);
895 
896  // use HD key derivation if HD was enabled during wallet creation and a seed
897  // is present
898  if (IsHDEnabled()) {
900  batch, metadata, secret,
901  (m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
902  } else {
903  secret.MakeNewKey(fCompressed);
904  }
905 
906  // Compressed public keys were introduced in version 0.6.0
907  if (fCompressed) {
909  }
910 
911  CPubKey pubkey = secret.GetPubKey();
912  assert(secret.VerifyPubKey(pubkey));
913 
914  mapKeyMetadata[pubkey.GetID()] = metadata;
915  UpdateTimeFirstKey(nCreationTime);
916 
917  if (!AddKeyPubKeyWithDB(batch, secret, pubkey)) {
918  throw std::runtime_error(std::string(__func__) + ": AddKey failed");
919  }
920 
921  return pubkey;
922 }
923 
924 const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
925 
927  CKeyMetadata &metadata,
928  CKey &secret, bool internal) {
929  // for now we use a fixed keypath scheme of m/0'/0'/k
930  // seed (256bit)
931  CKey seed;
932  // hd master key
933  CExtKey masterKey;
934  // key at m/0'
935  CExtKey accountKey;
936  // key at m/0'/0' (external) or m/0'/1' (internal)
937  CExtKey chainChildKey;
938  // key at m/0'/0'/<n>'
939  CExtKey childKey;
940 
941  // try to get the seed
942  if (!GetKey(hdChain.seed_id, seed)) {
943  throw std::runtime_error(std::string(__func__) + ": seed not found");
944  }
945 
946  masterKey.SetSeed(seed.begin(), seed.size());
947 
948  // derive m/0'
949  // use hardened derivation (child keys >= 0x80000000 are hardened after
950  // bip32)
951  masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
952 
953  // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
954  assert(internal ? m_storage.CanSupportFeature(FEATURE_HD_SPLIT) : true);
955  accountKey.Derive(chainChildKey,
956  BIP32_HARDENED_KEY_LIMIT + (internal ? 1 : 0));
957 
958  // derive child key at next index, skip keys already known to the wallet
959  do {
960  // always derive hardened keys
961  // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened
962  // child-index-range
963  // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
964  if (internal) {
965  chainChildKey.Derive(childKey, hdChain.nInternalChainCounter |
967  metadata.hdKeypath =
968  "m/0'/1'/" + ToString(hdChain.nInternalChainCounter) + "'";
969  metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
970  metadata.key_origin.path.push_back(1 | BIP32_HARDENED_KEY_LIMIT);
971  metadata.key_origin.path.push_back(hdChain.nInternalChainCounter |
974  } else {
975  chainChildKey.Derive(childKey, hdChain.nExternalChainCounter |
977  metadata.hdKeypath =
978  "m/0'/0'/" + ToString(hdChain.nExternalChainCounter) + "'";
979  metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
980  metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
981  metadata.key_origin.path.push_back(hdChain.nExternalChainCounter |
984  }
985  } while (HaveKey(childKey.key.GetPubKey().GetID()));
986  secret = childKey.key;
987  metadata.hd_seed_id = hdChain.seed_id;
988  CKeyID master_id = masterKey.key.GetPubKey().GetID();
989  std::copy(master_id.begin(), master_id.begin() + 4,
990  metadata.key_origin.fingerprint);
991  metadata.has_key_origin = true;
992  // update the chain model in the database
993  if (!batch.WriteHDChain(hdChain)) {
994  throw std::runtime_error(std::string(__func__) +
995  ": Writing HD chain model failed");
996  }
997 }
998 
1000  const CKeyPool &keypool) {
1001  LOCK(cs_KeyStore);
1002  if (keypool.m_pre_split) {
1003  set_pre_split_keypool.insert(nIndex);
1004  } else if (keypool.fInternal) {
1005  setInternalKeyPool.insert(nIndex);
1006  } else {
1007  setExternalKeyPool.insert(nIndex);
1008  }
1009  m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
1010  m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
1011 
1012  // If no metadata exists yet, create a default with the pool key's
1013  // creation time. Note that this may be overwritten by actually
1014  // stored metadata for that key later, which is fine.
1015  CKeyID keyid = keypool.vchPubKey.GetID();
1016  if (mapKeyMetadata.count(keyid) == 0) {
1017  mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
1018  }
1019 }
1020 
1022  // A wallet can generate keys if it has an HD seed (IsHDEnabled) or it is a
1023  // non-HD wallet (pre FEATURE_HD)
1024  LOCK(cs_KeyStore);
1026 }
1027 
1030  CKey key;
1031  key.MakeNewKey(true);
1032  return DeriveNewSeed(key);
1033 }
1034 
1036  int64_t nCreationTime = GetTime();
1037  CKeyMetadata metadata(nCreationTime);
1038 
1039  // Calculate the seed
1040  CPubKey seed = key.GetPubKey();
1041  assert(key.VerifyPubKey(seed));
1042 
1043  // Set the hd keypath to "s" -> Seed, refers the seed to itself
1044  metadata.hdKeypath = "s";
1045  metadata.has_key_origin = false;
1046  metadata.hd_seed_id = seed.GetID();
1047 
1048  LOCK(cs_KeyStore);
1049 
1050  // mem store the metadata
1051  mapKeyMetadata[seed.GetID()] = metadata;
1052 
1053  // Write the key&metadata to the database
1054  if (!AddKeyPubKey(key, seed)) {
1055  throw std::runtime_error(std::string(__func__) +
1056  ": AddKeyPubKey failed");
1057  }
1058 
1059  return seed;
1060 }
1061 
1063  LOCK(cs_KeyStore);
1064 
1065  // Store the keyid (hash160) together with the child index counter in the
1066  // database as a hdchain object.
1067  CHDChain newHdChain;
1071  newHdChain.seed_id = seed.GetID();
1072  SetHDChain(newHdChain, false);
1076 }
1077 
1083  return false;
1084  }
1085  LOCK(cs_KeyStore);
1087 
1088  for (const int64_t nIndex : setInternalKeyPool) {
1089  batch.ErasePool(nIndex);
1090  }
1091  setInternalKeyPool.clear();
1092 
1093  for (const int64_t nIndex : setExternalKeyPool) {
1094  batch.ErasePool(nIndex);
1095  }
1096  setExternalKeyPool.clear();
1097 
1098  for (int64_t nIndex : set_pre_split_keypool) {
1099  batch.ErasePool(nIndex);
1100  }
1101  set_pre_split_keypool.clear();
1102 
1103  m_pool_key_to_index.clear();
1104 
1105  if (!TopUp()) {
1106  return false;
1107  }
1108 
1109  WalletLogPrintf("LegacyScriptPubKeyMan::NewKeyPool rewrote keypool\n");
1110  return true;
1111 }
1112 
1113 bool LegacyScriptPubKeyMan::TopUp(unsigned int kpSize) {
1114  if (!CanGenerateKeys()) {
1115  return false;
1116  }
1117  {
1118  LOCK(cs_KeyStore);
1119 
1120  if (m_storage.IsLocked()) {
1121  return false;
1122  }
1123 
1124  // Top up key pool
1125  unsigned int nTargetSize;
1126  if (kpSize > 0) {
1127  nTargetSize = kpSize;
1128  } else {
1129  nTargetSize = std::max<int64_t>(
1130  gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), 0);
1131  }
1132 
1133  // count amount of available keys (internal, external)
1134  // make sure the keypool of external and internal keys fits the user
1135  // selected target (-keypool)
1136  int64_t missingExternal = std::max<int64_t>(
1137  std::max<int64_t>(nTargetSize, 1) - setExternalKeyPool.size(), 0);
1138  int64_t missingInternal = std::max<int64_t>(
1139  std::max<int64_t>(nTargetSize, 1) - setInternalKeyPool.size(), 0);
1140 
1142  // don't create extra internal keys
1143  missingInternal = 0;
1144  }
1145  bool internal = false;
1147  for (int64_t i = missingInternal + missingExternal; i--;) {
1148  if (i < missingInternal) {
1149  internal = true;
1150  }
1151 
1152  CPubKey pubkey(GenerateNewKey(batch, internal));
1153  AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1154  }
1155  if (missingInternal + missingExternal > 0) {
1157  "keypool added %d keys (%d internal), size=%u (%u internal)\n",
1158  missingInternal + missingExternal, missingInternal,
1159  setInternalKeyPool.size() + setExternalKeyPool.size() +
1160  set_pre_split_keypool.size(),
1161  setInternalKeyPool.size());
1162  }
1163  }
1165  return true;
1166 }
1167 
1169  const bool internal,
1170  WalletBatch &batch) {
1171  LOCK(cs_KeyStore);
1172  // How in the hell did you use so many keys?
1173  assert(m_max_keypool_index < std::numeric_limits<int64_t>::max());
1174  int64_t index = ++m_max_keypool_index;
1175  if (!batch.WritePool(index, CKeyPool(pubkey, internal))) {
1176  throw std::runtime_error(std::string(__func__) +
1177  ": writing imported pubkey failed");
1178  }
1179  if (internal) {
1180  setInternalKeyPool.insert(index);
1181  } else {
1182  setExternalKeyPool.insert(index);
1183  }
1184  m_pool_key_to_index[pubkey.GetID()] = index;
1185 }
1186 
1188  const OutputType &type) {
1189  // Remove from key pool.
1191  batch.ErasePool(nIndex);
1192  CPubKey pubkey;
1193  bool have_pk = GetPubKey(m_index_to_reserved_key.at(nIndex), pubkey);
1194  assert(have_pk);
1195  LearnRelatedScripts(pubkey, type);
1196  m_index_to_reserved_key.erase(nIndex);
1197  WalletLogPrintf("keypool keep %d\n", nIndex);
1198 }
1199 
1200 void LegacyScriptPubKeyMan::ReturnDestination(int64_t nIndex, bool fInternal,
1201  const CTxDestination &) {
1202  // Return to key pool
1203  {
1204  LOCK(cs_KeyStore);
1205  if (fInternal) {
1206  setInternalKeyPool.insert(nIndex);
1207  } else if (!set_pre_split_keypool.empty()) {
1208  set_pre_split_keypool.insert(nIndex);
1209  } else {
1210  setExternalKeyPool.insert(nIndex);
1211  }
1212  CKeyID &pubkey_id = m_index_to_reserved_key.at(nIndex);
1213  m_pool_key_to_index[pubkey_id] = nIndex;
1214  m_index_to_reserved_key.erase(nIndex);
1216  }
1217 
1218  WalletLogPrintf("keypool return %d\n", nIndex);
1219 }
1220 
1222  const OutputType type,
1223  bool internal) {
1224  if (!CanGetAddresses(internal)) {
1225  return false;
1226  }
1227 
1228  CKeyPool keypool;
1229  LOCK(cs_KeyStore);
1230  int64_t nIndex;
1231  if (!ReserveKeyFromKeyPool(nIndex, keypool, internal) &&
1233  if (m_storage.IsLocked()) {
1234  return false;
1235  }
1237  result = GenerateNewKey(batch, internal);
1238  return true;
1239  }
1240 
1241  KeepDestination(nIndex, type);
1242  result = keypool.vchPubKey;
1243 
1244  return true;
1245 }
1246 
1248  CKeyPool &keypool,
1249  bool fRequestedInternal) {
1250  nIndex = -1;
1251  keypool.vchPubKey = CPubKey();
1252  {
1253  LOCK(cs_KeyStore);
1254 
1255  bool fReturningInternal = fRequestedInternal;
1256  fReturningInternal &=
1259  bool use_split_keypool = set_pre_split_keypool.empty();
1260  std::set<int64_t> &setKeyPool =
1261  use_split_keypool
1262  ? (fReturningInternal ? setInternalKeyPool : setExternalKeyPool)
1263  : set_pre_split_keypool;
1264 
1265  // Get the oldest key
1266  if (setKeyPool.empty()) {
1267  return false;
1268  }
1269 
1271 
1272  auto it = setKeyPool.begin();
1273  nIndex = *it;
1274  setKeyPool.erase(it);
1275  if (!batch.ReadPool(nIndex, keypool)) {
1276  throw std::runtime_error(std::string(__func__) + ": read failed");
1277  }
1278  CPubKey pk;
1279  if (!GetPubKey(keypool.vchPubKey.GetID(), pk)) {
1280  throw std::runtime_error(std::string(__func__) +
1281  ": unknown key in key pool");
1282  }
1283  // If the key was pre-split keypool, we don't care about what type it is
1284  if (use_split_keypool && keypool.fInternal != fReturningInternal) {
1285  throw std::runtime_error(std::string(__func__) +
1286  ": keypool entry misclassified");
1287  }
1288  if (!keypool.vchPubKey.IsValid()) {
1289  throw std::runtime_error(std::string(__func__) +
1290  ": keypool entry invalid");
1291  }
1292 
1293  assert(m_index_to_reserved_key.count(nIndex) == 0);
1294  m_index_to_reserved_key[nIndex] = keypool.vchPubKey.GetID();
1295  m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1296  WalletLogPrintf("keypool reserve %d\n", nIndex);
1297  }
1299  return true;
1300 }
1301 
1303  OutputType type) {
1304  // Nothing to do...
1305 }
1306 
1308  // Nothing to do...
1309 }
1310 
1313  bool internal = setInternalKeyPool.count(keypool_id);
1314  if (!internal) {
1315  assert(setExternalKeyPool.count(keypool_id) ||
1316  set_pre_split_keypool.count(keypool_id));
1317  }
1318 
1319  std::set<int64_t> *setKeyPool =
1320  internal ? &setInternalKeyPool
1321  : (set_pre_split_keypool.empty() ? &setExternalKeyPool
1322  : &set_pre_split_keypool);
1323  auto it = setKeyPool->begin();
1324 
1326  while (it != std::end(*setKeyPool)) {
1327  const int64_t &index = *(it);
1328  if (index > keypool_id) {
1329  // set*KeyPool is ordered
1330  break;
1331  }
1332 
1333  CKeyPool keypool;
1334  if (batch.ReadPool(index, keypool)) {
1335  // TODO: This should be unnecessary
1336  m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1337  }
1339  batch.ErasePool(index);
1340  WalletLogPrintf("keypool index %d removed\n", index);
1341  it = setKeyPool->erase(it);
1342  }
1343 }
1344 
1345 std::vector<CKeyID> GetAffectedKeys(const CScript &spk,
1346  const SigningProvider &provider) {
1347  std::vector<CScript> dummy;
1348  FlatSigningProvider out;
1349  InferDescriptor(spk, provider)
1350  ->Expand(0, DUMMY_SIGNING_PROVIDER, dummy, out);
1351  std::vector<CKeyID> ret;
1352  for (const auto &entry : out.pubkeys) {
1353  ret.push_back(entry.first);
1354  }
1355  return ret;
1356 }
1357 
1360  for (auto it = setExternalKeyPool.begin();
1361  it != setExternalKeyPool.end();) {
1362  int64_t index = *it;
1363  CKeyPool keypool;
1364  if (!batch.ReadPool(index, keypool)) {
1365  throw std::runtime_error(std::string(__func__) +
1366  ": read keypool entry failed");
1367  }
1368  keypool.m_pre_split = true;
1369  if (!batch.WritePool(index, keypool)) {
1370  throw std::runtime_error(std::string(__func__) +
1371  ": writing modified keypool entry failed");
1372  }
1373  set_pre_split_keypool.insert(index);
1374  it = setExternalKeyPool.erase(it);
1375  }
1376 }
1377 
1378 bool LegacyScriptPubKeyMan::AddCScript(const CScript &redeemScript) {
1380  return AddCScriptWithDB(batch, redeemScript);
1381 }
1382 
1384  const CScript &redeemScript) {
1385  if (!FillableSigningProvider::AddCScript(redeemScript)) {
1386  return false;
1387  }
1388  if (batch.WriteCScript(Hash160(redeemScript), redeemScript)) {
1390  return true;
1391  }
1392  return false;
1393 }
1394 
1396  const CPubKey &pubkey,
1397  const KeyOriginInfo &info) {
1398  LOCK(cs_KeyStore);
1399  std::copy(info.fingerprint, info.fingerprint + 4,
1400  mapKeyMetadata[pubkey.GetID()].key_origin.fingerprint);
1401  mapKeyMetadata[pubkey.GetID()].key_origin.path = info.path;
1402  mapKeyMetadata[pubkey.GetID()].has_key_origin = true;
1403  mapKeyMetadata[pubkey.GetID()].hdKeypath = WriteHDKeypath(info.path);
1404  return batch.WriteKeyMetadata(mapKeyMetadata[pubkey.GetID()], pubkey, true);
1405 }
1406 
1407 bool LegacyScriptPubKeyMan::ImportScripts(const std::set<CScript> scripts,
1408  int64_t timestamp) {
1410  for (const auto &entry : scripts) {
1411  CScriptID id(entry);
1412  if (HaveCScript(id)) {
1413  WalletLogPrintf("Already have script %s, skipping\n",
1414  HexStr(entry));
1415  continue;
1416  }
1417  if (!AddCScriptWithDB(batch, entry)) {
1418  return false;
1419  }
1420 
1421  if (timestamp > 0) {
1422  m_script_metadata[CScriptID(entry)].nCreateTime = timestamp;
1423  }
1424  }
1425  if (timestamp > 0) {
1426  UpdateTimeFirstKey(timestamp);
1427  }
1428 
1429  return true;
1430 }
1431 
1433  const std::map<CKeyID, CKey> &privkey_map, const int64_t timestamp) {
1435  for (const auto &entry : privkey_map) {
1436  const CKey &key = entry.second;
1437  CPubKey pubkey = key.GetPubKey();
1438  const CKeyID &id = entry.first;
1439  assert(key.VerifyPubKey(pubkey));
1440  // Skip if we already have the key
1441  if (HaveKey(id)) {
1442  WalletLogPrintf("Already have key with pubkey %s, skipping\n",
1443  HexStr(pubkey));
1444  continue;
1445  }
1446  mapKeyMetadata[id].nCreateTime = timestamp;
1447  // If the private key is not present in the wallet, insert it.
1448  if (!AddKeyPubKeyWithDB(batch, key, pubkey)) {
1449  return false;
1450  }
1451  UpdateTimeFirstKey(timestamp);
1452  }
1453  return true;
1454 }
1455 
1457  const std::vector<CKeyID> &ordered_pubkeys,
1458  const std::map<CKeyID, CPubKey> &pubkey_map,
1459  const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>> &key_origins,
1460  const bool add_keypool, const bool internal, const int64_t timestamp) {
1462  for (const auto &entry : key_origins) {
1463  AddKeyOriginWithDB(batch, entry.second.first, entry.second.second);
1464  }
1465  for (const CKeyID &id : ordered_pubkeys) {
1466  auto entry = pubkey_map.find(id);
1467  if (entry == pubkey_map.end()) {
1468  continue;
1469  }
1470  const CPubKey &pubkey = entry->second;
1471  CPubKey temp;
1472  if (GetPubKey(id, temp)) {
1473  // Already have pubkey, skipping
1474  WalletLogPrintf("Already have pubkey %s, skipping\n", HexStr(temp));
1475  continue;
1476  }
1477  if (!AddWatchOnlyWithDB(batch, GetScriptForRawPubKey(pubkey),
1478  timestamp)) {
1479  return false;
1480  }
1481  mapKeyMetadata[id].nCreateTime = timestamp;
1482 
1483  // Add to keypool only works with pubkeys
1484  if (add_keypool) {
1485  AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1487  }
1488  }
1489  return true;
1490 }
1491 
1493  const std::set<CScript> &script_pub_keys, const bool have_solving_data,
1494  const int64_t timestamp) {
1496  for (const CScript &script : script_pub_keys) {
1497  if (!have_solving_data || !IsMine(script)) {
1498  // Always call AddWatchOnly for non-solvable watch-only, so that
1499  // watch timestamp gets updated
1500  if (!AddWatchOnlyWithDB(batch, script, timestamp)) {
1501  return false;
1502  }
1503  }
1504  }
1505  return true;
1506 }
1507 
1508 std::set<CKeyID> LegacyScriptPubKeyMan::GetKeys() const {
1509  LOCK(cs_KeyStore);
1510  if (!m_storage.HasEncryptionKeys()) {
1512  }
1513  std::set<CKeyID> set_address;
1514  for (const auto &mi : mapCryptedKeys) {
1515  set_address.insert(mi.first);
1516  }
1517  return set_address;
1518 }
1519 
1520 void LegacyScriptPubKeyMan::SetType(OutputType type, bool internal) {}
1521 
1523  CTxDestination &dest,
1524  std::string &error) {
1525  // Returns true if this descriptor supports getting new addresses.
1526  // Conditions where we may be unable to fetch them (e.g. locked) are caught
1527  // later
1528  if (!CanGetAddresses(m_internal)) {
1529  error = "No addresses available";
1530  return false;
1531  }
1532  {
1533  LOCK(cs_desc_man);
1534  // This is a combo descriptor which should not be an active descriptor
1535  assert(m_wallet_descriptor.descriptor->IsSingleType());
1536  if (type != m_address_type) {
1537  throw std::runtime_error(std::string(__func__) +
1538  ": Types are inconsistent");
1539  }
1540 
1541  TopUp();
1542 
1543  // Get the scriptPubKey from the descriptor
1544  FlatSigningProvider out_keys;
1545  std::vector<CScript> scripts_temp;
1546  if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
1547  // We can't generate anymore keys
1548  error = "Error: Keypool ran out, please call keypoolrefill first";
1549  return false;
1550  }
1551  if (!m_wallet_descriptor.descriptor->ExpandFromCache(
1552  m_wallet_descriptor.next_index, m_wallet_descriptor.cache,
1553  scripts_temp, out_keys)) {
1554  // We can't generate anymore keys
1555  error = "Error: Keypool ran out, please call keypoolrefill first";
1556  return false;
1557  }
1558 
1559  std::optional<OutputType> out_script_type =
1560  m_wallet_descriptor.descriptor->GetOutputType();
1561  if (out_script_type && out_script_type == type) {
1562  ExtractDestination(scripts_temp[0], dest);
1563  } else {
1564  throw std::runtime_error(
1565  std::string(__func__) +
1566  ": Types are inconsistent. Stored type does not match type of "
1567  "newly generated address");
1568  }
1569  m_wallet_descriptor.next_index++;
1571  .WriteDescriptor(GetID(), m_wallet_descriptor);
1572  return true;
1573  }
1574 }
1575 
1577  LOCK(cs_desc_man);
1578  if (m_map_script_pub_keys.count(script) > 0) {
1579  return ISMINE_SPENDABLE;
1580  }
1581  return ISMINE_NO;
1582 }
1583 
1585  const CKeyingMaterial &master_key, bool accept_no_keys) {
1586  LOCK(cs_desc_man);
1587  if (!m_map_keys.empty()) {
1588  return false;
1589  }
1590 
1591  // Always pass when there are no encrypted keys
1592  bool keyPass = m_map_crypted_keys.empty();
1593  bool keyFail = false;
1594  for (const auto &mi : m_map_crypted_keys) {
1595  const CPubKey &pubkey = mi.second.first;
1596  const std::vector<uint8_t> &crypted_secret = mi.second.second;
1597  CKey key;
1598  if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
1599  keyFail = true;
1600  break;
1601  }
1602  keyPass = true;
1603  if (m_decryption_thoroughly_checked) {
1604  break;
1605  }
1606  }
1607  if (keyPass && keyFail) {
1608  LogPrintf("The wallet is probably corrupted: Some keys decrypt but not "
1609  "all.\n");
1610  throw std::runtime_error(
1611  "Error unlocking wallet: some keys decrypt but not all. Your "
1612  "wallet file may be corrupt.");
1613  }
1614  if (keyFail || (!keyPass && !accept_no_keys)) {
1615  return false;
1616  }
1617  m_decryption_thoroughly_checked = true;
1618  return true;
1619 }
1620 
1622  WalletBatch *batch) {
1623  LOCK(cs_desc_man);
1624  if (!m_map_crypted_keys.empty()) {
1625  return false;
1626  }
1627 
1628  for (const KeyMap::value_type &key_in : m_map_keys) {
1629  const CKey &key = key_in.second;
1630  CPubKey pubkey = key.GetPubKey();
1631  CKeyingMaterial secret(key.begin(), key.end());
1632  std::vector<uint8_t> crypted_secret;
1633  if (!EncryptSecret(master_key, secret, pubkey.GetHash(),
1634  crypted_secret)) {
1635  return false;
1636  }
1637  m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1638  batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1639  }
1640  m_map_keys.clear();
1641  return true;
1642 }
1643 
1645  bool internal,
1646  CTxDestination &address,
1647  int64_t &index,
1648  CKeyPool &keypool) {
1649  LOCK(cs_desc_man);
1650  std::string error;
1651  bool result = GetNewDestination(type, address, error);
1652  index = m_wallet_descriptor.next_index - 1;
1653  return result;
1654 }
1655 
1656 void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal,
1657  const CTxDestination &addr) {
1658  LOCK(cs_desc_man);
1659  // Only return when the index was the most recent
1660  if (m_wallet_descriptor.next_index - 1 == index) {
1661  m_wallet_descriptor.next_index--;
1662  }
1664  .WriteDescriptor(GetID(), m_wallet_descriptor);
1666 }
1667 
1668 std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const {
1669  AssertLockHeld(cs_desc_man);
1671  KeyMap keys;
1672  for (auto key_pair : m_map_crypted_keys) {
1673  const CPubKey &pubkey = key_pair.second.first;
1674  const std::vector<uint8_t> &crypted_secret = key_pair.second.second;
1675  CKey key;
1676  DecryptKey(m_storage.GetEncryptionKey(), crypted_secret, pubkey,
1677  key);
1678  keys[pubkey.GetID()] = key;
1679  }
1680  return keys;
1681  }
1682  return m_map_keys;
1683 }
1684 
1685 bool DescriptorScriptPubKeyMan::TopUp(unsigned int size) {
1686  LOCK(cs_desc_man);
1687  unsigned int target_size;
1688  if (size > 0) {
1689  target_size = size;
1690  } else {
1691  target_size = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE),
1692  int64_t(1));
1693  }
1694 
1695  // Calculate the new range_end
1696  int32_t new_range_end =
1697  std::max(m_wallet_descriptor.next_index + int32_t(target_size),
1698  m_wallet_descriptor.range_end);
1699 
1700  // If the descriptor is not ranged, we actually just want to fill the first
1701  // cache item
1702  if (!m_wallet_descriptor.descriptor->IsRange()) {
1703  new_range_end = 1;
1704  m_wallet_descriptor.range_end = 1;
1705  m_wallet_descriptor.range_start = 0;
1706  }
1707 
1708  FlatSigningProvider provider;
1709  provider.keys = GetKeys();
1710 
1712  uint256 id = GetID();
1713  for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
1714  FlatSigningProvider out_keys;
1715  std::vector<CScript> scripts_temp;
1716  DescriptorCache temp_cache;
1717  // Maybe we have a cached xpub and we can expand from the cache first
1718  if (!m_wallet_descriptor.descriptor->ExpandFromCache(
1719  i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1720  if (!m_wallet_descriptor.descriptor->Expand(
1721  i, provider, scripts_temp, out_keys, &temp_cache)) {
1722  return false;
1723  }
1724  }
1725  // Add all of the scriptPubKeys to the scriptPubKey set
1726  for (const CScript &script : scripts_temp) {
1727  m_map_script_pub_keys[script] = i;
1728  }
1729  for (const auto &pk_pair : out_keys.pubkeys) {
1730  const CPubKey &pubkey = pk_pair.second;
1731  if (m_map_pubkeys.count(pubkey) != 0) {
1732  // We don't need to give an error here.
1733  // It doesn't matter which of many valid indexes the pubkey has,
1734  // we just need an index where we can derive it and it's private
1735  // key
1736  continue;
1737  }
1738  m_map_pubkeys[pubkey] = i;
1739  }
1740  // Write the cache
1741  for (const auto &parent_xpub_pair :
1742  temp_cache.GetCachedParentExtPubKeys()) {
1743  CExtPubKey xpub;
1744  if (m_wallet_descriptor.cache.GetCachedParentExtPubKey(
1745  parent_xpub_pair.first, xpub)) {
1746  if (xpub != parent_xpub_pair.second) {
1747  throw std::runtime_error(
1748  std::string(__func__) +
1749  ": New cached parent xpub does not match already "
1750  "cached parent xpub");
1751  }
1752  continue;
1753  }
1754  if (!batch.WriteDescriptorParentCache(parent_xpub_pair.second, id,
1755  parent_xpub_pair.first)) {
1756  throw std::runtime_error(std::string(__func__) +
1757  ": writing cache item failed");
1758  }
1759  m_wallet_descriptor.cache.CacheParentExtPubKey(
1760  parent_xpub_pair.first, parent_xpub_pair.second);
1761  }
1762  for (const auto &derived_xpub_map_pair :
1763  temp_cache.GetCachedDerivedExtPubKeys()) {
1764  for (const auto &derived_xpub_pair : derived_xpub_map_pair.second) {
1765  CExtPubKey xpub;
1766  if (m_wallet_descriptor.cache.GetCachedDerivedExtPubKey(
1767  derived_xpub_map_pair.first, derived_xpub_pair.first,
1768  xpub)) {
1769  if (xpub != derived_xpub_pair.second) {
1770  throw std::runtime_error(
1771  std::string(__func__) +
1772  ": New cached derived xpub does not match already "
1773  "cached derived xpub");
1774  }
1775  continue;
1776  }
1777  if (!batch.WriteDescriptorDerivedCache(
1778  derived_xpub_pair.second, id,
1779  derived_xpub_map_pair.first, derived_xpub_pair.first)) {
1780  throw std::runtime_error(std::string(__func__) +
1781  ": writing cache item failed");
1782  }
1783  m_wallet_descriptor.cache.CacheDerivedExtPubKey(
1784  derived_xpub_map_pair.first, derived_xpub_pair.first,
1785  derived_xpub_pair.second);
1786  }
1787  }
1788  m_max_cached_index++;
1789  }
1790  m_wallet_descriptor.range_end = new_range_end;
1791  batch.WriteDescriptor(GetID(), m_wallet_descriptor);
1792 
1793  // By this point, the cache size should be the size of the entire range
1794  assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
1795 
1797  return true;
1798 }
1799 
1801  LOCK(cs_desc_man);
1802  if (IsMine(script)) {
1803  int32_t index = m_map_script_pub_keys[script];
1804  if (index >= m_wallet_descriptor.next_index) {
1805  WalletLogPrintf("%s: Detected a used keypool item at index %d, "
1806  "mark all keypool items up to this item as used\n",
1807  __func__, index);
1808  m_wallet_descriptor.next_index = index + 1;
1809  }
1810  if (!TopUp()) {
1811  WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n",
1812  __func__);
1813  }
1814  }
1815 }
1816 
1818  const CPubKey &pubkey) {
1819  LOCK(cs_desc_man);
1821  if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
1822  throw std::runtime_error(std::string(__func__) +
1823  ": writing descriptor private key failed");
1824  }
1825 }
1826 
1828  const CKey &key,
1829  const CPubKey &pubkey) {
1830  AssertLockHeld(cs_desc_man);
1832 
1833  if (m_storage.HasEncryptionKeys()) {
1834  if (m_storage.IsLocked()) {
1835  return false;
1836  }
1837 
1838  std::vector<uint8_t> crypted_secret;
1839  CKeyingMaterial secret(key.begin(), key.end());
1840  if (!EncryptSecret(m_storage.GetEncryptionKey(), secret,
1841  pubkey.GetHash(), crypted_secret)) {
1842  return false;
1843  }
1844 
1845  m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1846  return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1847  } else {
1848  m_map_keys[pubkey.GetID()] = key;
1849  return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
1850  }
1851 }
1852 
1854  const CExtKey &master_key) {
1855  LOCK(cs_desc_man);
1857 
1858  // Ignore when there is already a descriptor
1859  if (m_wallet_descriptor.descriptor) {
1860  return false;
1861  }
1862 
1863  int64_t creation_time = GetTime();
1864 
1865  std::string xpub = EncodeExtPubKey(master_key.Neuter());
1866 
1867  // Build descriptor string
1868  std::string desc_prefix;
1869  std::string desc_suffix = "/*)";
1870  switch (m_address_type) {
1871  case OutputType::LEGACY: {
1872  desc_prefix = "pkh(" + xpub + "/44'";
1873  break;
1874  }
1875  default:
1876  assert(false);
1877  }
1878 
1879  // Mainnet derives at 0', testnet and regtest derive at 1'
1881  desc_prefix += "/1'";
1882  } else {
1883  desc_prefix += "/0'";
1884  }
1885 
1886  std::string internal_path = m_internal ? "/1" : "/0";
1887  std::string desc_str = desc_prefix + "/0'" + internal_path + desc_suffix;
1888 
1889  // Make the descriptor
1890  FlatSigningProvider keys;
1891  std::string error;
1892  std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, error, false);
1893  WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
1894  m_wallet_descriptor = w_desc;
1895 
1896  // Store the master private key, and descriptor
1898  if (!AddDescriptorKeyWithDB(batch, master_key.key,
1899  master_key.key.GetPubKey())) {
1900  throw std::runtime_error(
1901  std::string(__func__) +
1902  ": writing descriptor master private key failed");
1903  }
1904  if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
1905  throw std::runtime_error(std::string(__func__) +
1906  ": writing descriptor failed");
1907  }
1908 
1909  // TopUp
1910  TopUp();
1911 
1913  return true;
1914 }
1915 
1917  LOCK(cs_desc_man);
1918  return m_wallet_descriptor.descriptor->IsRange();
1919 }
1920 
1922  // We can only give out addresses from descriptors that are single type (not
1923  // combo), ranged, and either have cached keys or can generate more keys
1924  // (ignoring encryption)
1925  LOCK(cs_desc_man);
1926  return m_wallet_descriptor.descriptor->IsSingleType() &&
1927  m_wallet_descriptor.descriptor->IsRange() &&
1928  (HavePrivateKeys() ||
1929  m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
1930 }
1931 
1933  LOCK(cs_desc_man);
1934  return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
1935 }
1936 
1938  // This is only used for getwalletinfo output and isn't relevant to
1939  // descriptor wallets. The magic number 0 indicates that it shouldn't be
1940  // displayed so that's what we return.
1941  return 0;
1942 }
1943 
1945  if (m_internal) {
1946  return 0;
1947  }
1948  return GetKeyPoolSize();
1949 }
1950 
1952  LOCK(cs_desc_man);
1953  return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
1954 }
1955 
1957  LOCK(cs_desc_man);
1958  return m_wallet_descriptor.creation_time;
1959 }
1960 
1961 std::unique_ptr<FlatSigningProvider>
1963  bool include_private) const {
1964  LOCK(cs_desc_man);
1965 
1966  // Find the index of the script
1967  auto it = m_map_script_pub_keys.find(script);
1968  if (it == m_map_script_pub_keys.end()) {
1969  return nullptr;
1970  }
1971  int32_t index = it->second;
1972 
1973  return GetSigningProvider(index, include_private);
1974 }
1975 
1976 std::unique_ptr<FlatSigningProvider>
1978  LOCK(cs_desc_man);
1979 
1980  // Find index of the pubkey
1981  auto it = m_map_pubkeys.find(pubkey);
1982  if (it == m_map_pubkeys.end()) {
1983  return nullptr;
1984  }
1985  int32_t index = it->second;
1986 
1987  // Always try to get the signing provider with private keys. This function
1988  // should only be called during signing anyways
1989  return GetSigningProvider(index, true);
1990 }
1991 
1992 std::unique_ptr<FlatSigningProvider>
1994  bool include_private) const {
1995  AssertLockHeld(cs_desc_man);
1996  // Get the scripts, keys, and key origins for this script
1997  std::unique_ptr<FlatSigningProvider> out_keys =
1998  std::make_unique<FlatSigningProvider>();
1999  std::vector<CScript> scripts_temp;
2000  if (!m_wallet_descriptor.descriptor->ExpandFromCache(
2001  index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
2002  return nullptr;
2003  }
2004 
2005  if (HavePrivateKeys() && include_private) {
2006  FlatSigningProvider master_provider;
2007  master_provider.keys = GetKeys();
2008  m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider,
2009  *out_keys);
2010  }
2011 
2012  return out_keys;
2013 }
2014 
2015 std::unique_ptr<SigningProvider>
2017  return GetSigningProvider(script, false);
2018 }
2019 
2021  SignatureData &sigdata) {
2022  return IsMine(script);
2023 }
2024 
2026  CMutableTransaction &tx, const std::map<COutPoint, Coin> &coins,
2027  SigHashType sighash, std::map<int, std::string> &input_errors) const {
2028  std::unique_ptr<FlatSigningProvider> keys =
2029  std::make_unique<FlatSigningProvider>();
2030  for (const auto &coin_pair : coins) {
2031  std::unique_ptr<FlatSigningProvider> coin_keys =
2032  GetSigningProvider(coin_pair.second.GetTxOut().scriptPubKey, true);
2033  if (!coin_keys) {
2034  continue;
2035  }
2036  *keys = Merge(*keys, *coin_keys);
2037  }
2038 
2039  return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
2040 }
2041 
2043 DescriptorScriptPubKeyMan::SignMessage(const std::string &message,
2044  const PKHash &pkhash,
2045  std::string &str_sig) const {
2046  std::unique_ptr<FlatSigningProvider> keys =
2047  GetSigningProvider(GetScriptForDestination(pkhash), true);
2048  if (!keys) {
2050  }
2051 
2052  CKeyID key_id(pkhash);
2053  CKey key;
2054  if (!keys->GetKey(key_id, key)) {
2056  }
2057 
2058  if (!MessageSign(key, message, str_sig)) {
2060  }
2061  return SigningResult::OK;
2062 }
2063 
2066  SigHashType sighash_type, bool sign,
2067  bool bip32derivs) const {
2068  for (size_t i = 0; i < psbtx.tx->vin.size(); ++i) {
2069  PSBTInput &input = psbtx.inputs.at(i);
2070 
2071  if (PSBTInputSigned(input)) {
2072  continue;
2073  }
2074 
2075  // Verify input looks sane. This will check that we have at most one
2076  // uxto, witness or non-witness.
2077  if (!input.IsSane()) {
2079  }
2080 
2081  // Get the Sighash type
2082  if (sign && input.sighash_type.getRawSigHashType() > 0 &&
2083  input.sighash_type != sighash_type) {
2085  }
2086 
2087  // Get the scriptPubKey to know which SigningProvider to use
2088  CScript script;
2089  if (!input.utxo.IsNull()) {
2090  script = input.utxo.scriptPubKey;
2091  } else {
2092  // There's no UTXO so we can just skip this now
2093  continue;
2094  }
2095  SignatureData sigdata;
2096  input.FillSignatureData(sigdata);
2097 
2098  std::unique_ptr<FlatSigningProvider> keys =
2099  std::make_unique<FlatSigningProvider>();
2100  std::unique_ptr<FlatSigningProvider> script_keys =
2101  GetSigningProvider(script, sign);
2102  if (script_keys) {
2103  *keys = Merge(*keys, *script_keys);
2104  } else {
2105  // Maybe there are pubkeys listed that we can sign for
2106  script_keys = std::make_unique<FlatSigningProvider>();
2107  for (const auto &pk_pair : input.hd_keypaths) {
2108  const CPubKey &pubkey = pk_pair.first;
2109  std::unique_ptr<FlatSigningProvider> pk_keys =
2110  GetSigningProvider(pubkey);
2111  if (pk_keys) {
2112  *keys = Merge(*keys, *pk_keys);
2113  }
2114  }
2115  }
2116 
2117  SignPSBTInput(HidingSigningProvider(keys.get(), !sign, !bip32derivs),
2118  psbtx, i, sighash_type);
2119  }
2120 
2121  // Fill in the bip32 keypaths and redeemscripts for the outputs so that
2122  // hardware wallets can identify change
2123  for (size_t i = 0; i < psbtx.tx->vout.size(); ++i) {
2124  std::unique_ptr<SigningProvider> keys =
2125  GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
2126  if (!keys) {
2127  continue;
2128  }
2129  UpdatePSBTOutput(HidingSigningProvider(keys.get(), true, !bip32derivs),
2130  psbtx, i);
2131  }
2132 
2133  return TransactionError::OK;
2134 }
2135 
2136 std::unique_ptr<CKeyMetadata>
2138  std::unique_ptr<SigningProvider> provider =
2139  GetSigningProvider(GetScriptForDestination(dest));
2140  if (provider) {
2141  KeyOriginInfo orig;
2142  CKeyID key_id = GetKeyForDestination(*provider, dest);
2143  if (provider->GetKeyOrigin(key_id, orig)) {
2144  LOCK(cs_desc_man);
2145  std::unique_ptr<CKeyMetadata> meta =
2146  std::make_unique<CKeyMetadata>();
2147  meta->key_origin = orig;
2148  meta->has_key_origin = true;
2149  meta->nCreateTime = m_wallet_descriptor.creation_time;
2150  return meta;
2151  }
2152  }
2153  return nullptr;
2154 }
2155 
2157  LOCK(cs_desc_man);
2158  std::string desc_str = m_wallet_descriptor.descriptor->ToString();
2159  uint256 id;
2160  CSHA256()
2161  .Write((uint8_t *)desc_str.data(), desc_str.size())
2162  .Finalize(id.begin());
2163  return id;
2164 }
2165 
2167  this->m_address_type = type;
2168  this->m_internal = internal;
2169 }
2170 
2172  LOCK(cs_desc_man);
2173  m_wallet_descriptor.cache = cache;
2174  for (int32_t i = m_wallet_descriptor.range_start;
2175  i < m_wallet_descriptor.range_end; ++i) {
2176  FlatSigningProvider out_keys;
2177  std::vector<CScript> scripts_temp;
2178  if (!m_wallet_descriptor.descriptor->ExpandFromCache(
2179  i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2180  throw std::runtime_error(
2181  "Error: Unable to expand wallet descriptor from cache");
2182  }
2183  // Add all of the scriptPubKeys to the scriptPubKey set
2184  for (const CScript &script : scripts_temp) {
2185  if (m_map_script_pub_keys.count(script) != 0) {
2186  throw std::runtime_error(
2187  strprintf("Error: Already loaded script at index %d as "
2188  "being at index %d",
2189  i, m_map_script_pub_keys[script]));
2190  }
2191  m_map_script_pub_keys[script] = i;
2192  }
2193  for (const auto &pk_pair : out_keys.pubkeys) {
2194  const CPubKey &pubkey = pk_pair.second;
2195  if (m_map_pubkeys.count(pubkey) != 0) {
2196  // We don't need to give an error here.
2197  // It doesn't matter which of many valid indexes the pubkey has,
2198  // we just need an index where we can derive it and it's private
2199  // key
2200  continue;
2201  }
2202  m_map_pubkeys[pubkey] = i;
2203  }
2204  m_max_cached_index++;
2205  }
2206 }
2207 
2208 bool DescriptorScriptPubKeyMan::AddKey(const CKeyID &key_id, const CKey &key) {
2209  LOCK(cs_desc_man);
2210  m_map_keys[key_id] = key;
2211  return true;
2212 }
2213 
2215  const CKeyID &key_id, const CPubKey &pubkey,
2216  const std::vector<uint8_t> &crypted_key) {
2217  LOCK(cs_desc_man);
2218  if (!m_map_keys.empty()) {
2219  return false;
2220  }
2221 
2222  m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
2223  return true;
2224 }
2225 
2227  const WalletDescriptor &desc) const {
2228  LOCK(cs_desc_man);
2229  return m_wallet_descriptor.descriptor != nullptr &&
2230  desc.descriptor != nullptr &&
2231  m_wallet_descriptor.descriptor->ToString() ==
2232  desc.descriptor->ToString();
2233 }
2234 
2236  LOCK(cs_desc_man);
2238  if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
2239  throw std::runtime_error(std::string(__func__) +
2240  ": writing descriptor failed");
2241  }
2242 }
2243 
2245  return m_wallet_descriptor;
2246 }
2247 
2248 const std::vector<CScript> DescriptorScriptPubKeyMan::GetScriptPubKeys() const {
2249  LOCK(cs_desc_man);
2250  std::vector<CScript> script_pub_keys;
2251  script_pub_keys.reserve(m_map_script_pub_keys.size());
2252 
2253  for (auto const &script_pub_key : m_map_script_pub_keys) {
2254  script_pub_keys.push_back(script_pub_key.first);
2255  }
2256  return script_pub_keys;
2257 }
txnouttype Solver(const CScript &scriptPubKey, std::vector< std::vector< uint8_t >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:102
void ReturnDestination(int64_t index, bool internal, const CTxDestination &) override
virtual bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
Top-level scriptPubKey.
bool NewKeyPool()
Mark old keypool keys as used, and generate all new keys.
bool AddKeyPubKeyInner(const CKey &key, const CPubKey &pubkey)
void LoadScriptMetadata(const CScriptID &script_id, const CKeyMetadata &metadata)
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:196
std::string hdKeypath
Definition: walletdb.h:134
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.
const std::unordered_map< uint32_t, ExtPubKeyMap > GetCachedDerivedExtPubKeys() const
Retrieve all cached derived xpubs.
void KeepDestination(int64_t index, const OutputType &type) override
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.
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:152
void RewriteDB() override
The action to do when the DB needs rewrite.
bool GetNewDestination(const OutputType type, CTxDestination &dest, std::string &error) override
virtual const CKeyingMaterial & GetEncryptionKey() const =0
virtual void UnsetBlankWalletFlag(WalletBatch &)=0
virtual bool GetCScript(const CScriptID &hash, CScript &redeemScriptOut) const override
void LearnAllRelatedScripts(const CPubKey &key)
Same as LearnRelatedScripts, but when the OutputType is not known (and could be anything).
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.
std::shared_ptr< Descriptor > descriptor
Definition: walletutil.h:101
bool ImportScriptPubKeys(const std::set< CScript > &script_pub_keys, const bool have_solving_data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool LoadCScript(const CScript &redeemScript)
Adds a CScript to the store.
CScript scriptPubKey
Definition: transaction.h:144
bool AddKeyOriginWithDB(WalletBatch &batch, const CPubKey &pubkey, const KeyOriginInfo &info)
Add a KeyOriginInfo to the wallet.
bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const override
CKey key
Definition: key.h:163
std::vector< uint8_t > valtype
bool Derive(CExtKey &out, unsigned int nChild) const
Definition: key.cpp:378
uint32_t getRawSigHashType() const
Definition: sighashtype.h:83
Bilingual messages:
Definition: translation.h:17
isminetype IsMine(const CScript &script) const override
bool AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector< uint8_t > &vchCryptedSecret)
virtual const CChainParams & GetChainParams() const =0
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
RecursiveMutex cs_KeyStore
uint256 GetID() const override
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:303
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:210
std::vector< uint8_t, secure_allocator< uint8_t > > CKeyingMaterial
Definition: crypter.h:63
bool AddCryptedKey(const CKeyID &key_id, const CPubKey &pubkey, const std::vector< uint8_t > &crypted_key)
std::map< CKeyID, CKey > keys
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.
SigningResult
Definition: message.h:47
int64_t GetOldestKeyPoolTime() const override
FlatSigningProvider Merge(const FlatSigningProvider &a, const FlatSigningProvider &b)
bool WriteHDChain(const CHDChain &chain)
write the hdchain model (external chain child index counter)
Definition: walletdb.cpp:984
void AddKeypoolPubkeyWithDB(const CPubKey &pubkey, const bool internal, WalletBatch &batch)
virtual bool AddCScript(const CScript &redeemScript)
Definition: key.h:158
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
Definition: walletdb.cpp:152
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:418
void SetType(OutputType type, bool internal) override
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:253
uint256 GetHash() const
Get the 256-bit hash of this public key.
Definition: pubkey.h:140
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that...
unsigned int GetKeyPoolSize() const override
bool CanGetAddresses(bool internal=false) const override
Returns true if the wallet can give out new addresses.
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:171
virtual std::set< CKeyID > GetKeys() const
bool DecryptKey(const CKeyingMaterial &vMasterKey, const std::vector< uint8_t > &vchCryptedSecret, const CPubKey &vchPubKey, CKey &key)
Definition: crypter.cpp:147
uint256 GetID() const override
static std::string WriteHDKeypath(std::vector< uint32_t > &keypath)
CKeyID GetKeyForDestination(const SigningProvider &store, const CTxDestination &dest)
Return the CKeyID of the key involved in a script (if there is a unique one).
uint32_t nExternalChainCounter
Definition: walletdb.h:93
void LearnRelatedScripts(const CPubKey &key, OutputType)
Explicitly make the wallet learn the related scripts for outputs to the given key.
std::string EncodeDestination(const CTxDestination &dest, const Config &config)
Definition: key_io.cpp:170
std::string translated
Definition: translation.h:19
virtual WalletDatabase & GetDatabase()=0
A version of CTransaction with the PSBT format.
Definition: psbt.h:335
void LoadKeyMetadata(const CKeyID &keyID, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
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)
uint160 Hash160(const T1 pbegin, const T1 pend)
Compute the 160-bit hash an object.
Definition: hash.h:98
bool GetReservedDestination(const OutputType type, bool internal, CTxDestination &address, int64_t &index, CKeyPool &keypool) override
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:23
const WalletDescriptor GetWalletDescriptor() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
uint256 & UINT256_ONE()
Definition: uint256.cpp:70
virtual bool IsWalletFlagSet(uint64_t) const =0
bool RemoveWatchOnly(const CScript &dest)
Remove a watch only script from the keystore.
std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const override
KeyMap GetKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:137
bool IsNull() const
Definition: uint256.h:26
OutputType
Definition: outputtype.h:17
bool IsHDEnabled() const override
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Adds a key to the store, and saves it to disk.
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 IsNull() const
Definition: transaction.h:164
Access to the wallet database.
Definition: walletdb.h:183
static bool ExtractPubKey(const CScript &dest, CPubKey &pubKeyOut)
void WalletLogPrintf(std::string fmt, Params... parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
void MarkPreSplitKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch) override
const std::vector< CScript > GetScriptPubKeys() const
int64_t GetOldestKeyPoolTime() const override
bool AddWatchOnlyWithDB(WalletBatch &batch, const CScript &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
CTxOut utxo
Definition: psbt.h:44
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:67
unsigned int GetKeyPoolSize() const override
void SetHDChain(const CHDChain &chain, bool memonly)
bool MessageSign(const CKey &privkey, const std::string &message, std::string &signature)
Sign a message.
Definition: message.cpp:56
bool IsHDEnabled() const override
IsMineSigVersion
This is an enum that tracks the execution context of a script, similar to SigVersion in script/interp...
CPubKey GenerateNewKey(WalletBatch &batch, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Generate a new key.
size_t KeypoolCountExternalKeys() const override
int64_t nTime
The time at which the key was generated. Set in AddKeypoolPubKeyWithDB.
bool Upgrade(int prev_version, bilingual_str &error) override
Upgrades the wallet to the specified version.
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 UpdateTimeFirstKey(int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Update wallet first key creation time.
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
Definition: walletdb.cpp:147
void SetSeed(const uint8_t *seed, unsigned int nSeedLen)
Definition: key.cpp:386
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that...
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
bool AddWatchOnlyInMem(const CScript &dest)
#define LOCK(cs)
Definition: sync.h:230
void MarkUnusedAddresses(const CScript &script) override
Mark unused addresses as being used.
static const unsigned int DEFAULT_KEYPOOL_SIZE
Default for -keypool.
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:55
const SigningProvider & DUMMY_SIGNING_PROVIDER
bool TopUp(unsigned int size=0) override
Fills internal address pool.
bool IsValid() const
Definition: pubkey.h:147
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:47
An encapsulated public key.
Definition: pubkey.h:31
std::map< CKeyID, CPubKey > pubkeys
void SetHDSeed(const CPubKey &key)
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:183
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses, and other watch only things, and is therefore "blank.".
Definition: walletutil.h:67
void ReturnDestination(int64_t index, bool internal, const CTxDestination &addr) override
bool m_pre_split
Whether this key was generated for a keypool before the wallet was upgraded to HD-split.
bool GetKey(const CKeyID &address, CKey &keyOut) const override
const Config & GetConfig()
Definition: config.cpp:34
A structure for PSBTs which contain per-input information.
Definition: psbt.h:43
isminetype
IsMine() return codes.
Definition: ismine.h:18
unsigned int size() const
Simple read-only vector-like interface.
Definition: key.h:82
void MarkUnusedAddresses(const CScript &script) override
Mark unused addresses as being used.
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
uint8_t * begin()
Definition: uint256.h:76
void UpdatePSBTOutput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index)
Updates a PSBTOutput with information from provider.
Definition: psbt.cpp:176
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:246
Descriptor with some wallet metadata.
Definition: walletutil.h:99
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:198
bool AddKey(const CKeyID &key_id, const CKey &key)
KeyOriginInfo key_origin
Definition: walletdb.h:138
int64_t nCreateTime
Definition: walletdb.h:131
const uint8_t * begin() const
Definition: key.h:83
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet) ...
bool has_key_origin
Whether the key_origin is useful.
Definition: walletdb.h:140
bool ReserveKeyFromKeyPool(int64_t &nIndex, CKeyPool &keypool, bool fRequestedInternal)
Reserves a key from the keypool and sets nIndex to its index.
std::vector< PSBTInput > inputs
Definition: psbt.h:337
bool GetKeyFromPool(CPubKey &key, const OutputType type, bool internal=false)
Fetches a key from the keypool.
virtual bool IsLocked() const =0
bool HasWalletDescriptor(const WalletDescriptor &desc) const
bool HavePrivateKeys() const override
bool WriteKeyMetadata(const CKeyMetadata &meta, const CPubKey &pubkey, const bool overwrite)
Definition: walletdb.cpp:104
virtual bool GetKey(const CKeyID &address, CKey &keyOut) const override
std::map< int64_t, CKeyID > m_index_to_reserved_key
bool AddCScript(const CScript &redeemScript) override
std::vector< CKeyID > GetAffectedKeys(const CScript &spk, const SigningProvider &provider)
int nVersion
Definition: walletdb.h:129
int64_t GetTimeFirstKey() const override
SigHashType sighash_type
Definition: psbt.h:50
P2SH redeemScript.
static int64_t GetOldestKeyTimeInPool(const std::set< int64_t > &setKeyPool, WalletBatch &batch)
bool ErasePool(int64_t nPool)
Definition: walletdb.cpp:193
bool WritePool(int64_t nPool, const CKeyPool &keypool)
Definition: walletdb.cpp:189
txnouttype
Definition: standard.h:41
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.
256-bit opaque blob.
Definition: uint256.h:120
bool GetReservedDestination(const OutputType type, bool internal, CTxDestination &address, int64_t &index, CKeyPool &keypool) override
CPubKey vchPubKey
The public key.
bool LoadKey(const CKey &key, const CPubKey &pubkey)
Adds a key to the store, without saving it to disk (used by LoadWallet)
virtual bool CanSupportFeature(enum WalletFeature) const =0
bool AddDescriptorKeyWithDB(WalletBatch &batch, const CKey &key, const CPubKey &pubkey)
void SetCache(const DescriptorCache &cache)
bool HaveWatchOnly() const
Returns whether there are any watch-only things in the wallet.
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< uint8_t > &secret)
Definition: walletdb.cpp:223
std::string EncodeExtPubKey(const CExtPubKey &key)
Definition: key_io.cpp:135
bool IsSane() const
Definition: psbt.cpp:137
bool IsTestChain() const
If this chain is exclusively used for testing.
Definition: chainparams.h:70
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector< uint8_t > &vchCryptedSecret)
Adds an encrypted key to the store, without saving it to disk (used by LoadWallet) ...
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible...
An interface to be implemented by keystores that support signing.
CExtPubKey Neuter() const
Definition: key.cpp:400
bool ParseHDKeypath(const std::string &keypath_str, std::vector< uint32_t > &keypath)
Parse an HD keypaths like "m/7/0&#39;/2000".
Definition: bip32.cpp:13
Cache for single descriptor&#39;s derived extended pubkeys.
Definition: descriptor.h:18
bool GetNewDestination(const OutputType type, CTxDestination &dest, std::string &error) override
bool HaveKey(const CKeyID &address) const override
std::map< CKeyID, CKey > KeyMap
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:429
std::unique_ptr< FlatSigningProvider > GetSigningProvider(const CScript &script, bool include_private=false) const
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:479
void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
Load a keypool entry.
void DeriveNewChildKey(WalletBatch &batch, CKeyMetadata &metadata, CKey &secret, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
A mutable version of CTransaction.
Definition: transaction.h:297
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:22
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.
CSHA256 & Write(const uint8_t *data, size_t len)
Definition: sha256.cpp:819
bool CanGetAddresses(bool internal=false) const override
Returns true if the wallet can give out new addresses.
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
std::string HexStr(const T itbegin, const T itend)
Definition: strencodings.h:132
ArgsManager gArgs
Definition: system.cpp:76
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.
TransactionError
Definition: error.h:22
virtual bool HaveCScript(const CScriptID &hash) const override
160-bit opaque blob.
Definition: uint256.h:108
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 EncryptSecret(const CKeyingMaterial &vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256 &nIV, std::vector< uint8_t > &vchCiphertext)
Definition: crypter.cpp:121
IsMineResult
This is an internal representation of isminetype + invalidity.
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:197
void UpgradeKeyMetadata()
Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo.
static const int VERSION_WITH_KEY_ORIGIN
Definition: walletdb.h:127
CPubKey DeriveNewSeed(const CKey &key)
CTxDestination GetDestinationForKey(const CPubKey &key, OutputType type)
Get a destination of the requested type (if possible) to the specified key.
Definition: outputtype.cpp:36
bool ReadPool(int64_t nPool, CKeyPool &keypool)
Definition: walletdb.cpp:185
int64_t GetTimeFirstKey() const override
static const int VERSION_HD_CHAIN_SPLIT
Definition: walletdb.h:99
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:22
virtual bool HasEncryptionKeys() const =0
size_type size() const
Definition: prevector.h:384
const uint8_t * end() const
Definition: key.h:84
virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed.
Definition: psbt.cpp:172
bool SetupGeneration(bool force=false) override
Sets up the key generation stuff, i.e.
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:110
bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch) override
bool HavePrivateKeys() const override
std::map< CKeyID, CKey > KeyMap
void AddDescriptorKey(const CKey &key, const CPubKey &pubkey)
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const override
Sign a message with the given script.
An encapsulated secp256k1 private key.
Definition: key.h:25
std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const override
CKeyID hd_seed_id
Definition: walletdb.h:136
bool SetupDescriptorGeneration(const CExtKey &master_key)
Setup descriptors based on the given CExtkey.
std::optional< CMutableTransaction > tx
Definition: psbt.h:336
void FillSignatureData(SignatureData &sigdata) const
Definition: psbt.cpp:81
bool TopUp(unsigned int size=0) override
Fills internal address pool.
WalletStorage & m_storage
AssertLockHeld(g_cs_orphans)
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:70
CKeyID seed_id
seed hash160
Definition: walletdb.h:96
A hasher class for SHA-256.
Definition: sha256.h:13
bool ImportPrivKeys(const std::map< CKeyID, CKey > &privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
const ExtPubKeyMap GetCachedParentExtPubKeys() const
Retrieve all cached parent xpubs.
int64_t GetTime()
Return system time (or mocked time, if set)
Definition: time.cpp:27
std::vector< uint32_t > path
Definition: keyorigin.h:14
virtual void SetMinVersion(enum WalletFeature, WalletBatch *=nullptr, bool=false)=0
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
bool error(const char *fmt, const Args &... args)
Definition: system.h:47
bool AddCScriptWithDB(WalletBatch &batch, const CScript &script)
Adds a script to the store and saves it to disk.
int nVersion
Definition: walletdb.h:101
void SetType(OutputType type, bool internal) override
size_t KeypoolCountExternalKeys() const override
bool fDecryptionThoroughlyChecked
keeps track of whether Unlock has run a thorough check before
bool fInternal
Whether this keypool entry is in the internal keypool (for change outputs)
boost::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:87
std::set< CKeyID > GetKeys() const override
static const int VERSION_HD_BASE
Definition: walletdb.h:98
isminetype IsMine(const CScript &script) const override
bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< uint8_t > &vchCryptedSecret)
Adds an encrypted key to the store, and saves it to disk.
bool ImportScripts(const std::set< CScript > scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input.
Definition: sign.h:76
uint32_t nInternalChainCounter
Definition: walletdb.h:94
Signature hash type wrapper class.
Definition: sighashtype.h:37
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
Definition: walletdb.cpp:208
std::map< CKeyID, int64_t > m_pool_key_to_index
A key from a CWallet&#39;s keypool.
std::vector< uint8_t > valtype
Definition: sigencoding.h:16
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const override
Sign a message with the given script.
bool HaveWatchOnly(const CScript &dest) const
Returns whether the watch-only script is in the wallet.
const uint32_t BIP32_HARDENED_KEY_LIMIT
uint8_t fingerprint[4]
First 32 bits of the Hash160 of the public key at the root of the path.
Definition: keyorigin.h:13
virtual bool HaveKey(const CKeyID &address) const override