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