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