Bitcoin ABC  0.26.3
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.GetIntArg("-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.GetIntArg("-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(
1797  gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), 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  // Check if provided key already exists
1939  if (m_map_keys.find(pubkey.GetID()) != m_map_keys.end() ||
1940  m_map_crypted_keys.find(pubkey.GetID()) != m_map_crypted_keys.end()) {
1941  return true;
1942  }
1943 
1944  if (m_storage.HasEncryptionKeys()) {
1945  if (m_storage.IsLocked()) {
1946  return false;
1947  }
1948 
1949  std::vector<uint8_t> crypted_secret;
1950  CKeyingMaterial secret(key.begin(), key.end());
1951  if (!EncryptSecret(m_storage.GetEncryptionKey(), secret,
1952  pubkey.GetHash(), crypted_secret)) {
1953  return false;
1954  }
1955 
1956  m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1957  return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1958  } else {
1959  m_map_keys[pubkey.GetID()] = key;
1960  return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
1961  }
1962 }
1963 
1965  const CExtKey &master_key, OutputType addr_type) {
1966  LOCK(cs_desc_man);
1968 
1969  // Ignore when there is already a descriptor
1970  if (m_wallet_descriptor.descriptor) {
1971  return false;
1972  }
1973 
1974  int64_t creation_time = GetTime();
1975 
1976  std::string xpub = EncodeExtPubKey(master_key.Neuter());
1977 
1978  // Build descriptor string
1979  std::string desc_prefix;
1980  std::string desc_suffix = "/*)";
1981  switch (addr_type) {
1982  case OutputType::LEGACY: {
1983  desc_prefix = "pkh(" + xpub + "/44'";
1984  break;
1985  }
1986  } // no default case, so the compiler can warn about missing cases
1987  assert(!desc_prefix.empty());
1988 
1989  // Mainnet derives at 0', testnet and regtest derive at 1'
1991  desc_prefix += "/1'";
1992  } else {
1993  desc_prefix += "/0'";
1994  }
1995 
1996  std::string internal_path = m_internal ? "/1" : "/0";
1997  std::string desc_str = desc_prefix + "/0'" + internal_path + desc_suffix;
1998 
1999  // Make the descriptor
2000  FlatSigningProvider keys;
2001  std::string error;
2002  std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, error, false);
2003  WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
2004  m_wallet_descriptor = w_desc;
2005 
2006  // Store the master private key, and descriptor
2008  if (!AddDescriptorKeyWithDB(batch, master_key.key,
2009  master_key.key.GetPubKey())) {
2010  throw std::runtime_error(
2011  std::string(__func__) +
2012  ": writing descriptor master private key failed");
2013  }
2014  if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
2015  throw std::runtime_error(std::string(__func__) +
2016  ": writing descriptor failed");
2017  }
2018 
2019  // TopUp
2020  TopUp();
2021 
2023  return true;
2024 }
2025 
2027  LOCK(cs_desc_man);
2028  return m_wallet_descriptor.descriptor->IsRange();
2029 }
2030 
2032  // We can only give out addresses from descriptors that are single type (not
2033  // combo), ranged, and either have cached keys or can generate more keys
2034  // (ignoring encryption)
2035  LOCK(cs_desc_man);
2036  return m_wallet_descriptor.descriptor->IsSingleType() &&
2037  m_wallet_descriptor.descriptor->IsRange() &&
2038  (HavePrivateKeys() ||
2039  m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
2040 }
2041 
2043  LOCK(cs_desc_man);
2044  return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
2045 }
2046 
2048  // This is only used for getwalletinfo output and isn't relevant to
2049  // descriptor wallets. The magic number 0 indicates that it shouldn't be
2050  // displayed so that's what we return.
2051  return 0;
2052 }
2053 
2055  if (m_internal) {
2056  return 0;
2057  }
2058  return GetKeyPoolSize();
2059 }
2060 
2062  LOCK(cs_desc_man);
2063  return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
2064 }
2065 
2067  LOCK(cs_desc_man);
2068  return m_wallet_descriptor.creation_time;
2069 }
2070 
2071 std::unique_ptr<FlatSigningProvider>
2073  bool include_private) const {
2074  LOCK(cs_desc_man);
2075 
2076  // Find the index of the script
2077  auto it = m_map_script_pub_keys.find(script);
2078  if (it == m_map_script_pub_keys.end()) {
2079  return nullptr;
2080  }
2081  int32_t index = it->second;
2082 
2083  return GetSigningProvider(index, include_private);
2084 }
2085 
2086 std::unique_ptr<FlatSigningProvider>
2088  LOCK(cs_desc_man);
2089 
2090  // Find index of the pubkey
2091  auto it = m_map_pubkeys.find(pubkey);
2092  if (it == m_map_pubkeys.end()) {
2093  return nullptr;
2094  }
2095  int32_t index = it->second;
2096 
2097  // Always try to get the signing provider with private keys. This function
2098  // should only be called during signing anyways
2099  return GetSigningProvider(index, true);
2100 }
2101 
2102 std::unique_ptr<FlatSigningProvider>
2104  bool include_private) const {
2106  // Get the scripts, keys, and key origins for this script
2107  std::unique_ptr<FlatSigningProvider> out_keys =
2108  std::make_unique<FlatSigningProvider>();
2109  std::vector<CScript> scripts_temp;
2110  if (!m_wallet_descriptor.descriptor->ExpandFromCache(
2111  index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
2112  return nullptr;
2113  }
2114 
2115  if (HavePrivateKeys() && include_private) {
2116  FlatSigningProvider master_provider;
2117  master_provider.keys = GetKeys();
2118  m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider,
2119  *out_keys);
2120  }
2121 
2122  return out_keys;
2123 }
2124 
2125 std::unique_ptr<SigningProvider>
2127  return GetSigningProvider(script, false);
2128 }
2129 
2131  SignatureData &sigdata) {
2132  return IsMine(script);
2133 }
2134 
2136  CMutableTransaction &tx, const std::map<COutPoint, Coin> &coins,
2137  SigHashType sighash, std::map<int, std::string> &input_errors) const {
2138  std::unique_ptr<FlatSigningProvider> keys =
2139  std::make_unique<FlatSigningProvider>();
2140  for (const auto &coin_pair : coins) {
2141  std::unique_ptr<FlatSigningProvider> coin_keys =
2142  GetSigningProvider(coin_pair.second.GetTxOut().scriptPubKey, true);
2143  if (!coin_keys) {
2144  continue;
2145  }
2146  *keys = Merge(*keys, *coin_keys);
2147  }
2148 
2149  return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
2150 }
2151 
2153 DescriptorScriptPubKeyMan::SignMessage(const std::string &message,
2154  const PKHash &pkhash,
2155  std::string &str_sig) const {
2156  std::unique_ptr<FlatSigningProvider> keys =
2158  if (!keys) {
2160  }
2161 
2162  CKey key;
2163  if (!keys->GetKey(ToKeyID(pkhash), key)) {
2165  }
2166 
2167  if (!MessageSign(key, message, str_sig)) {
2169  }
2170  return SigningResult::OK;
2171 }
2172 
2175  SigHashType sighash_type, bool sign,
2176  bool bip32derivs) const {
2177  for (size_t i = 0; i < psbtx.tx->vin.size(); ++i) {
2178  PSBTInput &input = psbtx.inputs.at(i);
2179 
2180  if (PSBTInputSigned(input)) {
2181  continue;
2182  }
2183 
2184  // Get the Sighash type
2185  if (sign && input.sighash_type.getRawSigHashType() > 0 &&
2186  input.sighash_type != sighash_type) {
2188  }
2189 
2190  // Get the scriptPubKey to know which SigningProvider to use
2191  CScript script;
2192  if (!input.utxo.IsNull()) {
2193  script = input.utxo.scriptPubKey;
2194  } else {
2195  // There's no UTXO so we can just skip this now
2196  continue;
2197  }
2198  SignatureData sigdata;
2199  input.FillSignatureData(sigdata);
2200 
2201  std::unique_ptr<FlatSigningProvider> keys =
2202  std::make_unique<FlatSigningProvider>();
2203  std::unique_ptr<FlatSigningProvider> script_keys =
2204  GetSigningProvider(script, sign);
2205  if (script_keys) {
2206  *keys = Merge(*keys, *script_keys);
2207  } else {
2208  // Maybe there are pubkeys listed that we can sign for
2209  script_keys = std::make_unique<FlatSigningProvider>();
2210  for (const auto &pk_pair : input.hd_keypaths) {
2211  const CPubKey &pubkey = pk_pair.first;
2212  std::unique_ptr<FlatSigningProvider> pk_keys =
2213  GetSigningProvider(pubkey);
2214  if (pk_keys) {
2215  *keys = Merge(*keys, *pk_keys);
2216  }
2217  }
2218  }
2219 
2220  SignPSBTInput(HidingSigningProvider(keys.get(), !sign, !bip32derivs),
2221  psbtx, i, sighash_type);
2222  }
2223 
2224  // Fill in the bip32 keypaths and redeemscripts for the outputs so that
2225  // hardware wallets can identify change
2226  for (size_t i = 0; i < psbtx.tx->vout.size(); ++i) {
2227  std::unique_ptr<SigningProvider> keys =
2228  GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
2229  if (!keys) {
2230  continue;
2231  }
2232  UpdatePSBTOutput(HidingSigningProvider(keys.get(), true, !bip32derivs),
2233  psbtx, i);
2234  }
2235 
2236  return TransactionError::OK;
2237 }
2238 
2239 std::unique_ptr<CKeyMetadata>
2241  std::unique_ptr<SigningProvider> provider =
2243  if (provider) {
2244  KeyOriginInfo orig;
2245  CKeyID key_id = GetKeyForDestination(*provider, dest);
2246  if (provider->GetKeyOrigin(key_id, orig)) {
2247  LOCK(cs_desc_man);
2248  std::unique_ptr<CKeyMetadata> meta =
2249  std::make_unique<CKeyMetadata>();
2250  meta->key_origin = orig;
2251  meta->has_key_origin = true;
2252  meta->nCreateTime = m_wallet_descriptor.creation_time;
2253  return meta;
2254  }
2255  }
2256  return nullptr;
2257 }
2258 
2260  LOCK(cs_desc_man);
2261  std::string desc_str = m_wallet_descriptor.descriptor->ToString();
2262  uint256 id;
2263  CSHA256()
2264  .Write((uint8_t *)desc_str.data(), desc_str.size())
2265  .Finalize(id.begin());
2266  return id;
2267 }
2268 
2270  this->m_internal = internal;
2271 }
2272 
2274  LOCK(cs_desc_man);
2275  m_wallet_descriptor.cache = cache;
2276  for (int32_t i = m_wallet_descriptor.range_start;
2277  i < m_wallet_descriptor.range_end; ++i) {
2278  FlatSigningProvider out_keys;
2279  std::vector<CScript> scripts_temp;
2280  if (!m_wallet_descriptor.descriptor->ExpandFromCache(
2281  i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2282  throw std::runtime_error(
2283  "Error: Unable to expand wallet descriptor from cache");
2284  }
2285  // Add all of the scriptPubKeys to the scriptPubKey set
2286  for (const CScript &script : scripts_temp) {
2287  if (m_map_script_pub_keys.count(script) != 0) {
2288  throw std::runtime_error(
2289  strprintf("Error: Already loaded script at index %d as "
2290  "being at index %d",
2291  i, m_map_script_pub_keys[script]));
2292  }
2293  m_map_script_pub_keys[script] = i;
2294  }
2295  for (const auto &pk_pair : out_keys.pubkeys) {
2296  const CPubKey &pubkey = pk_pair.second;
2297  if (m_map_pubkeys.count(pubkey) != 0) {
2298  // We don't need to give an error here.
2299  // It doesn't matter which of many valid indexes the pubkey has,
2300  // we just need an index where we can derive it and it's private
2301  // key
2302  continue;
2303  }
2304  m_map_pubkeys[pubkey] = i;
2305  }
2307  }
2308 }
2309 
2310 bool DescriptorScriptPubKeyMan::AddKey(const CKeyID &key_id, const CKey &key) {
2311  LOCK(cs_desc_man);
2312  m_map_keys[key_id] = key;
2313  return true;
2314 }
2315 
2317  const CKeyID &key_id, const CPubKey &pubkey,
2318  const std::vector<uint8_t> &crypted_key) {
2319  LOCK(cs_desc_man);
2320  if (!m_map_keys.empty()) {
2321  return false;
2322  }
2323 
2324  m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
2325  return true;
2326 }
2327 
2329  const WalletDescriptor &desc) const {
2330  LOCK(cs_desc_man);
2331  return m_wallet_descriptor.descriptor != nullptr &&
2332  desc.descriptor != nullptr &&
2333  m_wallet_descriptor.descriptor->ToString() ==
2334  desc.descriptor->ToString();
2335 }
2336 
2338  LOCK(cs_desc_man);
2340  if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
2341  throw std::runtime_error(std::string(__func__) +
2342  ": writing descriptor failed");
2343  }
2344 }
2345 
2347  return m_wallet_descriptor;
2348 }
2349 
2350 const std::vector<CScript> DescriptorScriptPubKeyMan::GetScriptPubKeys() const {
2351  LOCK(cs_desc_man);
2352  std::vector<CScript> script_pub_keys;
2353  script_pub_keys.reserve(m_map_script_pub_keys.size());
2354 
2355  for (auto const &script_pub_key : m_map_script_pub_keys) {
2356  script_pub_keys.push_back(script_pub_key.first);
2357  }
2358  return script_pub_keys;
2359 }
2360 
2362  WalletDescriptor &descriptor) {
2363  LOCK(cs_desc_man);
2364  std::string error;
2365  if (!CanUpdateToWalletDescriptor(descriptor, error)) {
2366  throw std::runtime_error(std::string(__func__) + ": " + error);
2367  }
2368 
2369  m_map_pubkeys.clear();
2370  m_map_script_pub_keys.clear();
2371  m_max_cached_index = -1;
2372  m_wallet_descriptor = descriptor;
2373 }
2374 
2376  const WalletDescriptor &descriptor, std::string &error) {
2377  LOCK(cs_desc_man);
2378  if (!HasWalletDescriptor(descriptor)) {
2379  error = "can only update matching descriptor";
2380  return false;
2381  }
2382 
2383  if (descriptor.range_start > m_wallet_descriptor.range_start ||
2384  descriptor.range_end < m_wallet_descriptor.range_end) {
2385  // Use inclusive range for error
2386  error = strprintf("new range must include current range = [%d,%d]",
2387  m_wallet_descriptor.range_start,
2388  m_wallet_descriptor.range_end - 1);
2389  return false;
2390  }
2391 
2392  return true;
2393 }
@ P2SH
P2SH redeemScript.
@ TOP
Top-level scriptPubKey.
bool ParseHDKeypath(const std::string &keypath_str, std::vector< uint32_t > &keypath)
Parse an HD keypaths like "m/7/0'/2000".
Definition: bip32.cpp:13
std::string WriteHDKeypath(const std::vector< uint32_t > &keypath)
Write HD keypaths as strings.
Definition: bip32.cpp:66
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: system.cpp:635
bool IsTestChain() const
If this chain is exclusively used for testing.
Definition: chainparams.h:105
static const int VERSION_HD_BASE
Definition: walletdb.h:94
uint32_t nInternalChainCounter
Definition: walletdb.h:90
CKeyID seed_id
seed hash160
Definition: walletdb.h:92
static const int VERSION_HD_CHAIN_SPLIT
Definition: walletdb.h:95
int nVersion
Definition: walletdb.h:97
uint32_t nExternalChainCounter
Definition: walletdb.h:89
An encapsulated secp256k1 private key.
Definition: key.h:28
const uint8_t * begin() const
Definition: key.h:90
unsigned int size() const
Simple read-only vector-like interface.
Definition: key.h:89
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:196
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:183
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:210
const uint8_t * end() const
Definition: key.h:91
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:302
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:22
static const int VERSION_WITH_KEY_ORIGIN
Definition: walletdb.h:124
KeyOriginInfo key_origin
Definition: walletdb.h:135
bool has_key_origin
Whether the key_origin is useful.
Definition: walletdb.h:137
int nVersion
Definition: walletdb.h:126
std::string hdKeypath
Definition: walletdb.h:131
int64_t nCreateTime
Definition: walletdb.h:128
CKeyID hd_seed_id
Definition: walletdb.h:133
A key from a CWallet's keypool.
bool fInternal
Whether this keypool entry is in the internal keypool (for change outputs)
CPubKey vchPubKey
The public key.
int64_t nTime
The time at which the key was generated. Set in AddKeypoolPubKeyWithDB.
bool m_pre_split
Whether this key was generated for a keypool before the wallet was upgraded to HD-split.
A mutable version of CTransaction.
Definition: transaction.h:274
An encapsulated public key.
Definition: pubkey.h:31
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:137
bool IsValid() const
Definition: pubkey.h:147
uint256 GetHash() const
Get the 256-bit hash of this public key.
Definition: pubkey.h:140
A hasher class for SHA-256.
Definition: sha256.h:13
CSHA256 & Write(const uint8_t *data, size_t len)
Definition: sha256.cpp:819
void Finalize(uint8_t hash[OUTPUT_SIZE])
Definition: sha256.cpp:844
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:431
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:24
CScript scriptPubKey
Definition: transaction.h:131
bool IsNull() const
Definition: transaction.h:145
Cache for single descriptor's derived extended pubkeys.
Definition: descriptor.h:19
const ExtPubKeyMap GetCachedParentExtPubKeys() const
Retrieve all cached parent xpubs.
const std::unordered_map< uint32_t, ExtPubKeyMap > GetCachedDerivedExtPubKeys() const
Retrieve all cached derived xpubs.
int64_t GetOldestKeyPoolTime() const override
void ReturnDestination(int64_t index, bool internal, const CTxDestination &addr) override
bool AddKey(const CKeyID &key_id, const CKey &key)
void MarkUnusedAddresses(const CScript &script) override
Mark unused addresses as being used.
bool HavePrivateKeys() const override
bool AddCryptedKey(const CKeyID &key_id, const CPubKey &pubkey, const std::vector< uint8_t > &crypted_key)
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const override
Sign a message with the given script.
bool CanUpdateToWalletDescriptor(const WalletDescriptor &descriptor, std::string &error)
TransactionError FillPSBT(PartiallySignedTransaction &psbt, SigHashType sighash_type=SigHashType().withForkId(), bool sign=true, bool bip32derivs=false) const override
Adds script and derivation path information to a PSBT, and optionally signs it.
bool TopUp(unsigned int size=0) override
Fills internal address pool.
void SetInternal(bool internal) override
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
bool HasWalletDescriptor(const WalletDescriptor &desc) const
int64_t GetTimeFirstKey() const override
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that,...
bool GetReservedDestination(const OutputType type, bool internal, CTxDestination &address, int64_t &index, CKeyPool &keypool) override
bool GetNewDestination(const OutputType type, CTxDestination &dest, std::string &error) override
unsigned int GetKeyPoolSize() const override
bool SetupDescriptorGeneration(const CExtKey &master_key, OutputType addr_type)
Setup descriptors based on the given CExtkey.
void AddDescriptorKey(const CKey &key, const CPubKey &pubkey)
std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const override
size_t KeypoolCountExternalKeys() const override
bool SignTransaction(CMutableTransaction &tx, const std::map< COutPoint, Coin > &coins, SigHashType sighash, std::map< int, std::string > &input_errors) const override
Creates new signatures and adds them to the transaction.
bool m_decryption_thoroughly_checked
keeps track of whether Unlock has run a thorough check before
KeyMap GetKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
std::unique_ptr< FlatSigningProvider > GetSigningProvider(const CScript &script, bool include_private=false) const
const std::vector< CScript > GetScriptPubKeys() const
std::map< CKeyID, CKey > KeyMap
bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch) override
bool AddDescriptorKeyWithDB(WalletBatch &batch, const CKey &key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
void UpdateWalletDescriptor(WalletDescriptor &descriptor)
void SetCache(const DescriptorCache &cache)
uint256 GetID() const override
const WalletDescriptor GetWalletDescriptor() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
isminetype IsMine(const CScript &script) const override
bool CheckDecryptionKey(const CKeyingMaterial &master_key, bool accept_no_keys=false) override
Check that the given decryption key is valid for this ScriptPubKeyMan, i.e.
bool IsHDEnabled() const override
bool CanGetAddresses(bool internal=false) const override
Returns true if the wallet can give out new addresses.
virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
virtual bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
virtual bool GetCScript(const CScriptID &hash, CScript &redeemScriptOut) const override
virtual bool GetKey(const CKeyID &address, CKey &keyOut) const override
virtual bool AddCScript(const CScript &redeemScript)
virtual std::set< CKeyID > GetKeys() const
std::map< CKeyID, CKey > KeyMap
virtual bool HaveCScript(const CScriptID &hash) const override
RecursiveMutex cs_KeyStore
virtual bool HaveKey(const CKeyID &address) const override
bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const override
std::map< int64_t, CKeyID > m_index_to_reserved_key
void UpgradeKeyMetadata()
Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo.
bool AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector< uint8_t > &vchCryptedSecret)
bool fDecryptionThoroughlyChecked
keeps track of whether Unlock has run a thorough check before
int64_t GetOldestKeyPoolTime() const override
bool GetReservedDestination(const OutputType type, bool internal, CTxDestination &address, int64_t &index, CKeyPool &keypool) override
uint256 GetID() const override
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
void MarkUnusedAddresses(const CScript &script) override
Mark unused addresses as being used.
bool HaveWatchOnly() const
Returns whether there are any watch-only things in the wallet.
bool RemoveWatchOnly(const CScript &dest)
Remove a watch only script from the keystore.
bool GetNewDestination(const OutputType type, CTxDestination &dest, std::string &error) override
bool AddWatchOnlyInMem(const CScript &dest)
void UpdateTimeFirstKey(int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Update wallet first key creation time.
void AddKeypoolPubkeyWithDB(const CPubKey &pubkey, const bool internal, WalletBatch &batch)
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)
size_t KeypoolCountExternalKeys() const override
void ReturnDestination(int64_t index, bool internal, const CTxDestination &) override
void SetHDSeed(const CPubKey &key)
bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector< uint8_t > &vchCryptedSecret, bool checksum_valid)
Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
std::unordered_map< CKeyID, CHDChain, SaltedSipHasher > m_inactive_hd_chains
bool GetKey(const CKeyID &address, CKey &keyOut) const override
void LearnAllRelatedScripts(const CPubKey &key)
Same as LearnRelatedScripts, but when the OutputType is not known (and could be anything).
bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch) override
isminetype IsMine(const CScript &script) const override
bool ImportScripts(const std::set< CScript > scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const override
bool HaveKey(const CKeyID &address) const override
bool ImportPrivKeys(const std::map< CKeyID, CKey > &privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool TopUpInactiveHDChain(const CKeyID seed_id, int64_t index, bool internal)
Like TopUp() but adds keys for inactive HD chains.
bool CanGetAddresses(bool internal=false) const override
Returns true if the wallet can give out new addresses.
bool AddKeyPubKeyInner(const CKey &key, const CPubKey &pubkey)
void AddHDChain(const CHDChain &chain)
Set the HD chain model (chain child index counters) and writes it to the database.
bool CheckDecryptionKey(const CKeyingMaterial &master_key, bool accept_no_keys=false) override
Check that the given decryption key is valid for this ScriptPubKeyMan, i.e.
void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
Load a keypool entry.
bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< uint8_t > &vchCryptedSecret)
Adds an encrypted key to the store, and saves it to disk.
bool Upgrade(int prev_version, bilingual_str &error) override
Upgrades the wallet to the specified version.
bool IsHDEnabled() const override
bool AddWatchOnlyWithDB(WalletBatch &batch, const CScript &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool LoadKey(const CKey &key, const CPubKey &pubkey)
Adds a key to the store, without saving it to disk (used by LoadWallet)
bool AddKeyOriginWithDB(WalletBatch &batch, const CPubKey &pubkey, const KeyOriginInfo &info)
Add a KeyOriginInfo to the wallet.
bool AddWatchOnly(const CScript &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Private version of AddWatchOnly method which does not accept a timestamp, and which will reset the wa...
bool TopUp(unsigned int size=0) override
Fills internal address pool.
void LoadKeyMetadata(const CKeyID &keyID, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
void MarkReserveKeysAsUsed(int64_t keypool_id) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Marks all keys in the keypool up to and including reserve_key as used.
void LoadHDChain(const CHDChain &chain)
Load a HD chain model (used by LoadWallet)
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
void AddInactiveHDChain(const CHDChain &chain)
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
TransactionError FillPSBT(PartiallySignedTransaction &psbt, SigHashType sighash_type=SigHashType().withForkId(), bool sign=true, bool bip32derivs=false) const override
Adds script and derivation path information to a PSBT, and optionally signs it.
void LearnRelatedScripts(const CPubKey &key, OutputType)
Explicitly make the wallet learn the related scripts for outputs to the given key.
bool NewKeyPool()
Mark old keypool keys as used, and generate all new keys.
bool ReserveKeyFromKeyPool(int64_t &nIndex, CKeyPool &keypool, bool fRequestedInternal)
Reserves a key from the keypool and sets nIndex to its index.
std::set< CKeyID > GetKeys() const override
void KeepDestination(int64_t index, const OutputType &type) override
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Adds a key to the store, and saves it to disk.
CPubKey GenerateNewKey(WalletBatch &batch, CHDChain &hd_chain, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Generate a new key.
void MarkPreSplitKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
unsigned int GetKeyPoolSize() const override
bool HavePrivateKeys() const override
bool HaveWatchOnly(const CScript &dest) const
Returns whether the watch-only script is in the wallet.
void SetInternal(bool internal) override
bool SetupGeneration(bool force=false) override
Sets up the key generation stuff, i.e.
bool ImportScriptPubKeys(const std::set< CScript > &script_pub_keys, const bool have_solving_data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool AddKeyPubKeyWithDB(WalletBatch &batch, const CKey &key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Adds a key to the store, and saves it to disk.
void RewriteDB() override
The action to do when the DB needs rewrite.
CPubKey DeriveNewSeed(const CKey &key)
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that,...
int64_t GetTimeFirstKey() const override
bool SignTransaction(CMutableTransaction &tx, const std::map< COutPoint, Coin > &coins, SigHashType sighash, std::map< int, std::string > &input_errors) const override
Creates new signatures and adds them to the transaction.
void LoadScriptMetadata(const CScriptID &script_id, const CKeyMetadata &metadata)
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const override
Sign a message with the given script.
bool LoadCScript(const CScript &redeemScript)
Adds a CScript to the store.
bool AddCScript(const CScript &redeemScript) override
bool AddCScriptWithDB(WalletBatch &batch, const CScript &script)
Adds a script to the store and saves it to disk.
std::map< CKeyID, int64_t > m_pool_key_to_index
bool GetKeyFromPool(CPubKey &key, const OutputType type, bool internal=false)
Fetches a key from the keypool.
void DeriveNewChildKey(WalletBatch &batch, CKeyMetadata &metadata, CKey &secret, CHDChain &hd_chain, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
WalletStorage & m_storage
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
void WalletLogPrintf(std::string fmt, Params... parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
Signature hash type wrapper class.
Definition: sighashtype.h:37
uint32_t getRawSigHashType() const
Definition: sighashtype.h:83
An interface to be implemented by keystores that support signing.
Access to the wallet database.
Definition: walletdb.h:175
bool WriteDescriptor(const uint256 &desc_id, const WalletDescriptor &descriptor)
Definition: walletdb.cpp:253
bool WriteDescriptorDerivedCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index, uint32_t der_index)
Definition: walletdb.cpp:258
bool ErasePool(int64_t nPool)
Definition: walletdb.cpp:205
bool WriteDescriptorParentCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index)
Definition: walletdb.cpp:270
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
Definition: walletdb.cpp:159
bool EraseWatchOnly(const CScript &script)
Definition: walletdb.cpp:172
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
Definition: walletdb.cpp:226
bool ReadPool(int64_t nPool, CKeyPool &keypool)
Definition: walletdb.cpp:197
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:113
bool WriteHDChain(const CHDChain &chain)
write the hdchain model (external chain child index counter)
Definition: walletdb.cpp:1100
bool WriteKeyMetadata(const CKeyMetadata &meta, const CPubKey &pubkey, const bool overwrite)
Definition: walletdb.cpp:107
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
Definition: walletdb.cpp:164
bool WritePool(int64_t nPool, const CKeyPool &keypool)
Definition: walletdb.cpp:201
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< uint8_t > &vchCryptedSecret, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:129
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< uint8_t > &secret)
Definition: walletdb.cpp:240
Descriptor with some wallet metadata.
Definition: walletutil.h:80
int32_t range_end
Definition: walletutil.h:89
int32_t range_start
Definition: walletutil.h:86
std::shared_ptr< Descriptor > descriptor
Definition: walletutil.h:82
virtual bool IsWalletFlagSet(uint64_t) const =0
virtual bool HasEncryptionKeys() const =0
virtual WalletDatabase & GetDatabase()=0
virtual bool IsLocked() const =0
virtual const CKeyingMaterial & GetEncryptionKey() const =0
virtual void UnsetBlankWalletFlag(WalletBatch &)=0
virtual void SetMinVersion(enum WalletFeature, WalletBatch *=nullptr, bool=false)=0
virtual bool CanSupportFeature(enum WalletFeature) const =0
virtual const CChainParams & GetChainParams() const =0
uint8_t * begin()
Definition: uint256.h:85
bool IsNull() const
Definition: uint256.h:32
size_type size() const
Definition: prevector.h:386
160-bit opaque blob.
Definition: uint256.h:117
256-bit opaque blob.
Definition: uint256.h:129
static const uint256 ONE
Definition: uint256.h:135
const Config & GetConfig()
Definition: config.cpp:34
bool DecryptKey(const CKeyingMaterial &vMasterKey, const std::vector< uint8_t > &vchCryptedSecret, const CPubKey &vchPubKey, CKey &key)
Definition: crypter.cpp:146
bool EncryptSecret(const CKeyingMaterial &vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256 &nIV, std::vector< uint8_t > &vchCiphertext)
Definition: crypter.cpp:121
std::vector< uint8_t, secure_allocator< uint8_t > > CKeyingMaterial
Definition: crypter.h:57
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
TransactionError
Definition: error.h:22
uint160 Hash160(const T1 &in1)
Compute the 160-bit hash an object.
Definition: hash.h:92
isminetype
IsMine() return codes.
Definition: ismine.h:18
@ ISMINE_SPENDABLE
Definition: ismine.h:21
@ ISMINE_NO
Definition: ismine.h:19
@ ISMINE_WATCH_ONLY
Definition: ismine.h:20
std::string EncodeDestination(const CTxDestination &dest, const Config &config)
Definition: key_io.cpp:167
std::string EncodeExtPubKey(const CExtPubKey &key)
Definition: key_io.cpp:132
#define LogPrintf(...)
Definition: logging.h:206
bool MessageSign(const CKey &privkey, const std::string &message, std::string &signature)
Sign a message.
Definition: message.cpp:56
SigningResult
Definition: message.h:47
@ PRIVATE_KEY_NOT_AVAILABLE
@ OK
No error.
CTxDestination GetDestinationForKey(const CPubKey &key, OutputType type)
Get a destination of the requested type (if possible) to the specified key.
Definition: outputtype.cpp:35
OutputType
Definition: outputtype.h:16
void UpdatePSBTOutput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index)
Updates a PSBTOutput with information from provider.
Definition: psbt.cpp:164
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed.
Definition: psbt.cpp:160
bool SignPSBTInput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index, SigHashType sighash, SignatureData *out_sigdata, bool use_dummy)
Signs a PSBTInput, verifying that all provided data matches what is being signed.
Definition: psbt.cpp:186
void SignTransaction(CMutableTransaction &mtx, const SigningProvider *keystore, const std::map< COutPoint, Coin > &coins, const UniValue &hashType, UniValue &result)
Sign a transaction with the given keystore and previous transactions.
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:24
std::vector< uint8_t > valtype
static bool ExtractPubKey(const CScript &dest, CPubKey &pubKeyOut)
const uint32_t BIP32_HARDENED_KEY_LIMIT
Value for the first BIP 32 hardened derivation.
static int64_t GetOldestKeyTimeInPool(const std::set< int64_t > &setKeyPool, WalletBatch &batch)
std::vector< CKeyID > GetAffectedKeys(const CScript &spk, const SigningProvider &provider)
static const unsigned int DEFAULT_KEYPOOL_SIZE
Default for -keypool.
std::vector< uint8_t > valtype
Definition: sigencoding.h:16
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
Definition: sign.cpp:198
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:419
const SigningProvider & DUMMY_SIGNING_PROVIDER
FlatSigningProvider Merge(const FlatSigningProvider &a, const FlatSigningProvider &b)
CKeyID GetKeyForDestination(const SigningProvider &store, const CTxDestination &dest)
Return the CKeyID of the key involved in a script (if there is a unique one).
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:158
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:244
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< uint8_t >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:108
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:240
CKeyID ToKeyID(const PKHash &key_hash)
Definition: standard.cpp:25
TxoutType
Definition: standard.h:38
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:85
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:87
Definition: key.h:164
CExtPubKey Neuter() const
Definition: key.cpp:396
bool Derive(CExtKey &out, unsigned int nChild) const
Definition: key.cpp:374
CKey key
Definition: key.h:169
void SetSeed(const uint8_t *seed, unsigned int nSeedLen)
Definition: key.cpp:382
std::map< CKeyID, CPubKey > pubkeys
std::map< CKeyID, CKey > keys
std::vector< uint32_t > path
Definition: keyorigin.h:14
uint8_t fingerprint[4]
First 32 bits of the Hash160 of the public key at the root of the path.
Definition: keyorigin.h:13
A structure for PSBTs which contain per-input information.
Definition: psbt.h:44
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:48
SigHashType sighash_type
Definition: psbt.h:51
void FillSignatureData(SignatureData &sigdata) const
Definition: psbt.cpp:73
CTxOut utxo
Definition: psbt.h:45
A version of CTransaction with the PSBT format.
Definition: psbt.h:334
std::vector< PSBTInput > inputs
Definition: psbt.h:336
std::optional< CMutableTransaction > tx
Definition: psbt.h:335
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input.
Definition: sign.h:76
Bilingual messages:
Definition: translation.h:17
std::string translated
Definition: translation.h:19
#define LOCK(cs)
Definition: sync.h:306
ArgsManager gArgs
Definition: system.cpp:80
bool error(const char *fmt, const Args &...args)
Definition: system.h:45
int64_t GetTime()
Definition: time.cpp:109
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:55
@ WALLET_FLAG_KEY_ORIGIN_METADATA
Definition: walletutil.h:51
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:70
@ WALLET_FLAG_BLANK_WALLET
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses,...
Definition: walletutil.h:67
@ FEATURE_HD_SPLIT
Definition: walletutil.h:28
@ FEATURE_PRE_SPLIT_KEYPOOL
Definition: walletutil.h:34
@ FEATURE_HD
Definition: walletutil.h:25
@ FEATURE_COMPRPUBKEY
Definition: walletutil.h:22