Bitcoin Core  24.99.0
P2P Digital Currency
scriptpubkeyman.cpp
Go to the documentation of this file.
1 // Copyright (c) 2019-2021 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 <key_io.h>
6 #include <logging.h>
7 #include <outputtype.h>
8 #include <script/descriptor.h>
9 #include <script/sign.h>
10 #include <util/bip32.h>
11 #include <util/strencodings.h>
12 #include <util/string.h>
13 #include <util/system.h>
14 #include <util/time.h>
15 #include <util/translation.h>
16 #include <wallet/scriptpubkeyman.h>
17 
18 #include <optional>
19 
20 namespace wallet {
22 const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
23 
25 {
26  if (LEGACY_OUTPUT_TYPES.count(type) == 0) {
27  return util::Error{_("Error: Legacy wallets only support the \"legacy\", \"p2sh-segwit\", and \"bech32\" address types")};
28  }
29  assert(type != OutputType::BECH32M);
30 
32 
33  // Generate a new key that is added to wallet
34  CPubKey new_key;
35  if (!GetKeyFromPool(new_key, type)) {
36  return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
37  }
38  LearnRelatedScripts(new_key, type);
39  return GetDestinationForKey(new_key, type);
40 }
41 
42 typedef std::vector<unsigned char> valtype;
43 
44 namespace {
45 
52 enum class IsMineSigVersion
53 {
54  TOP = 0,
55  P2SH = 1,
56  WITNESS_V0 = 2,
57 };
58 
64 enum class IsMineResult
65 {
66  NO = 0,
67  WATCH_ONLY = 1,
68  SPENDABLE = 2,
69  INVALID = 3,
70 };
71 
72 bool PermitsUncompressed(IsMineSigVersion sigversion)
73 {
74  return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
75 }
76 
77 bool HaveKeys(const std::vector<valtype>& pubkeys, const LegacyScriptPubKeyMan& keystore)
78 {
79  for (const valtype& pubkey : pubkeys) {
80  CKeyID keyID = CPubKey(pubkey).GetID();
81  if (!keystore.HaveKey(keyID)) return false;
82  }
83  return true;
84 }
85 
94 IsMineResult IsMineInner(const LegacyScriptPubKeyMan& keystore, const CScript& scriptPubKey, IsMineSigVersion sigversion, bool recurse_scripthash=true)
95 {
96  IsMineResult ret = IsMineResult::NO;
97 
98  std::vector<valtype> vSolutions;
99  TxoutType whichType = Solver(scriptPubKey, vSolutions);
100 
101  CKeyID keyID;
102  switch (whichType) {
107  break;
108  case TxoutType::PUBKEY:
109  keyID = CPubKey(vSolutions[0]).GetID();
110  if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
111  return IsMineResult::INVALID;
112  }
113  if (keystore.HaveKey(keyID)) {
114  ret = std::max(ret, IsMineResult::SPENDABLE);
115  }
116  break;
118  {
119  if (sigversion == IsMineSigVersion::WITNESS_V0) {
120  // P2WPKH inside P2WSH is invalid.
121  return IsMineResult::INVALID;
122  }
123  if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
124  // We do not support bare witness outputs unless the P2SH version of it would be
125  // acceptable as well. This protects against matching before segwit activates.
126  // This also applies to the P2WSH case.
127  break;
128  }
129  ret = std::max(ret, IsMineInner(keystore, GetScriptForDestination(PKHash(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
130  break;
131  }
133  keyID = CKeyID(uint160(vSolutions[0]));
134  if (!PermitsUncompressed(sigversion)) {
135  CPubKey pubkey;
136  if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
137  return IsMineResult::INVALID;
138  }
139  }
140  if (keystore.HaveKey(keyID)) {
141  ret = std::max(ret, IsMineResult::SPENDABLE);
142  }
143  break;
145  {
146  if (sigversion != IsMineSigVersion::TOP) {
147  // P2SH inside P2WSH or P2SH is invalid.
148  return IsMineResult::INVALID;
149  }
150  CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
151  CScript subscript;
152  if (keystore.GetCScript(scriptID, subscript)) {
153  ret = std::max(ret, recurse_scripthash ? IsMineInner(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
154  }
155  break;
156  }
158  {
159  if (sigversion == IsMineSigVersion::WITNESS_V0) {
160  // P2WSH inside P2WSH is invalid.
161  return IsMineResult::INVALID;
162  }
163  if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
164  break;
165  }
166  uint160 hash;
167  CRIPEMD160().Write(vSolutions[0].data(), vSolutions[0].size()).Finalize(hash.begin());
168  CScriptID scriptID = CScriptID(hash);
169  CScript subscript;
170  if (keystore.GetCScript(scriptID, subscript)) {
171  ret = std::max(ret, recurse_scripthash ? IsMineInner(keystore, subscript, IsMineSigVersion::WITNESS_V0) : IsMineResult::SPENDABLE);
172  }
173  break;
174  }
175 
176  case TxoutType::MULTISIG:
177  {
178  // Never treat bare multisig outputs as ours (they can still be made watchonly-though)
179  if (sigversion == IsMineSigVersion::TOP) {
180  break;
181  }
182 
183  // Only consider transactions "mine" if we own ALL the
184  // keys involved. Multi-signature transactions that are
185  // partially owned (somebody else has a key that can spend
186  // them) enable spend-out-from-under-you attacks, especially
187  // in shared-wallet situations.
188  std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
189  if (!PermitsUncompressed(sigversion)) {
190  for (size_t i = 0; i < keys.size(); i++) {
191  if (keys[i].size() != 33) {
192  return IsMineResult::INVALID;
193  }
194  }
195  }
196  if (HaveKeys(keys, keystore)) {
197  ret = std::max(ret, IsMineResult::SPENDABLE);
198  }
199  break;
200  }
201  } // no default case, so the compiler can warn about missing cases
202 
203  if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
204  ret = std::max(ret, IsMineResult::WATCH_ONLY);
205  }
206  return ret;
207 }
208 
209 } // namespace
210 
212 {
213  switch (IsMineInner(*this, script, IsMineSigVersion::TOP)) {
214  case IsMineResult::INVALID:
215  case IsMineResult::NO:
216  return ISMINE_NO;
217  case IsMineResult::WATCH_ONLY:
218  return ISMINE_WATCH_ONLY;
219  case IsMineResult::SPENDABLE:
220  return ISMINE_SPENDABLE;
221  }
222  assert(false);
223 }
224 
225 bool LegacyScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key, bool accept_no_keys)
226 {
227  {
228  LOCK(cs_KeyStore);
229  assert(mapKeys.empty());
230 
231  bool keyPass = mapCryptedKeys.empty(); // Always pass when there are no encrypted keys
232  bool keyFail = false;
233  CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
235  for (; mi != mapCryptedKeys.end(); ++mi)
236  {
237  const CPubKey &vchPubKey = (*mi).second.first;
238  const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
239  CKey key;
240  if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
241  {
242  keyFail = true;
243  break;
244  }
245  keyPass = true;
247  break;
248  else {
249  // Rewrite these encrypted keys with checksums
250  batch.WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
251  }
252  }
253  if (keyPass && keyFail)
254  {
255  LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
256  throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
257  }
258  if (keyFail || (!keyPass && !accept_no_keys))
259  return false;
261  }
262  return true;
263 }
264 
266 {
267  LOCK(cs_KeyStore);
268  encrypted_batch = batch;
269  if (!mapCryptedKeys.empty()) {
270  encrypted_batch = nullptr;
271  return false;
272  }
273 
274  KeyMap keys_to_encrypt;
275  keys_to_encrypt.swap(mapKeys); // Clear mapKeys so AddCryptedKeyInner will succeed.
276  for (const KeyMap::value_type& mKey : keys_to_encrypt)
277  {
278  const CKey &key = mKey.second;
279  CPubKey vchPubKey = key.GetPubKey();
280  CKeyingMaterial vchSecret(key.begin(), key.end());
281  std::vector<unsigned char> vchCryptedSecret;
282  if (!EncryptSecret(master_key, vchSecret, vchPubKey.GetHash(), vchCryptedSecret)) {
283  encrypted_batch = nullptr;
284  return false;
285  }
286  if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) {
287  encrypted_batch = nullptr;
288  return false;
289  }
290  }
291  encrypted_batch = nullptr;
292  return true;
293 }
294 
296 {
297  if (LEGACY_OUTPUT_TYPES.count(type) == 0) {
298  return util::Error{_("Error: Legacy wallets only support the \"legacy\", \"p2sh-segwit\", and \"bech32\" address types")};
299  }
300  assert(type != OutputType::BECH32M);
301 
302  LOCK(cs_KeyStore);
303  if (!CanGetAddresses(internal)) {
304  return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
305  }
306 
307  if (!ReserveKeyFromKeyPool(index, keypool, internal)) {
308  return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
309  }
310  return GetDestinationForKey(keypool.vchPubKey, type);
311 }
312 
313 bool LegacyScriptPubKeyMan::TopUpInactiveHDChain(const CKeyID seed_id, int64_t index, bool internal)
314 {
315  LOCK(cs_KeyStore);
316 
317  auto it = m_inactive_hd_chains.find(seed_id);
318  if (it == m_inactive_hd_chains.end()) {
319  return false;
320  }
321 
322  CHDChain& chain = it->second;
323 
324  if (internal) {
325  chain.m_next_internal_index = std::max(chain.m_next_internal_index, index + 1);
326  } else {
327  chain.m_next_external_index = std::max(chain.m_next_external_index, index + 1);
328  }
329 
330  TopUpChain(chain, 0);
331 
332  return true;
333 }
334 
335 std::vector<WalletDestination> LegacyScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
336 {
337  LOCK(cs_KeyStore);
338  std::vector<WalletDestination> result;
339  // extract addresses and check if they match with an unused keypool key
340  for (const auto& keyid : GetAffectedKeys(script, *this)) {
341  std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
342  if (mi != m_pool_key_to_index.end()) {
343  WalletLogPrintf("%s: Detected a used keypool key, mark all keypool keys up to this key as used\n", __func__);
344  for (const auto& keypool : MarkReserveKeysAsUsed(mi->second)) {
345  // derive all possible destinations as any of them could have been used
346  for (const auto& type : LEGACY_OUTPUT_TYPES) {
347  const auto& dest = GetDestinationForKey(keypool.vchPubKey, type);
348  result.push_back({dest, keypool.fInternal});
349  }
350  }
351 
352  if (!TopUp()) {
353  WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
354  }
355  }
356 
357  // Find the key's metadata and check if it's seed id (if it has one) is inactive, i.e. it is not the current m_hd_chain seed id.
358  // If so, TopUp the inactive hd chain
359  auto it = mapKeyMetadata.find(keyid);
360  if (it != mapKeyMetadata.end()){
361  CKeyMetadata meta = it->second;
362  if (!meta.hd_seed_id.IsNull() && meta.hd_seed_id != m_hd_chain.seed_id) {
363  std::vector<uint32_t> path;
364  if (meta.has_key_origin) {
365  path = meta.key_origin.path;
366  } else if (!ParseHDKeypath(meta.hdKeypath, path)) {
367  WalletLogPrintf("%s: Adding inactive seed keys failed, invalid hdKeypath: %s\n",
368  __func__,
369  meta.hdKeypath);
370  }
371  if (path.size() != 3) {
372  WalletLogPrintf("%s: Adding inactive seed keys failed, invalid path size: %d, has_key_origin: %s\n",
373  __func__,
374  path.size(),
375  meta.has_key_origin);
376  } else {
377  bool internal = (path[1] & ~BIP32_HARDENED_KEY_LIMIT) != 0;
378  int64_t index = path[2] & ~BIP32_HARDENED_KEY_LIMIT;
379 
380  if (!TopUpInactiveHDChain(meta.hd_seed_id, index, internal)) {
381  WalletLogPrintf("%s: Adding inactive seed keys failed\n", __func__);
382  }
383  }
384  }
385  }
386  }
387 
388  return result;
389 }
390 
392 {
393  LOCK(cs_KeyStore);
395  return;
396  }
397 
398  std::unique_ptr<WalletBatch> batch = std::make_unique<WalletBatch>(m_storage.GetDatabase());
399  for (auto& meta_pair : mapKeyMetadata) {
400  CKeyMetadata& meta = meta_pair.second;
401  if (!meta.hd_seed_id.IsNull() && !meta.has_key_origin && meta.hdKeypath != "s") { // If the hdKeypath is "s", that's the seed and it doesn't have a key origin
402  CKey key;
403  GetKey(meta.hd_seed_id, key);
404  CExtKey masterKey;
405  masterKey.SetSeed(key);
406  // Add to map
407  CKeyID master_id = masterKey.key.GetPubKey().GetID();
408  std::copy(master_id.begin(), master_id.begin() + 4, meta.key_origin.fingerprint);
409  if (!ParseHDKeypath(meta.hdKeypath, meta.key_origin.path)) {
410  throw std::runtime_error("Invalid stored hdKeypath");
411  }
412  meta.has_key_origin = true;
415  }
416 
417  // Write meta to wallet
418  CPubKey pubkey;
419  if (GetPubKey(meta_pair.first, pubkey)) {
420  batch->WriteKeyMetadata(meta, pubkey, true);
421  }
422  }
423  }
424 }
425 
427 {
428  if ((CanGenerateKeys() && !force) || m_storage.IsLocked()) {
429  return false;
430  }
431 
433  if (!NewKeyPool()) {
434  return false;
435  }
436  return true;
437 }
438 
440 {
441  return !m_hd_chain.seed_id.IsNull();
442 }
443 
444 bool LegacyScriptPubKeyMan::CanGetAddresses(bool internal) const
445 {
446  LOCK(cs_KeyStore);
447  // Check if the keypool has keys
448  bool keypool_has_keys;
449  if (internal && m_storage.CanSupportFeature(FEATURE_HD_SPLIT)) {
450  keypool_has_keys = setInternalKeyPool.size() > 0;
451  } else {
452  keypool_has_keys = KeypoolCountExternalKeys() > 0;
453  }
454  // If the keypool doesn't have keys, check if we can generate them
455  if (!keypool_has_keys) {
456  return CanGenerateKeys();
457  }
458  return keypool_has_keys;
459 }
460 
461 bool LegacyScriptPubKeyMan::Upgrade(int prev_version, int new_version, bilingual_str& error)
462 {
463  LOCK(cs_KeyStore);
464 
466  // Nothing to do here if private keys are not enabled
467  return true;
468  }
469 
470  bool hd_upgrade = false;
471  bool split_upgrade = false;
472  if (IsFeatureSupported(new_version, FEATURE_HD) && !IsHDEnabled()) {
473  WalletLogPrintf("Upgrading wallet to HD\n");
475 
476  // generate a new master key
477  CPubKey masterPubKey = GenerateNewSeed();
478  SetHDSeed(masterPubKey);
479  hd_upgrade = true;
480  }
481  // Upgrade to HD chain split if necessary
482  if (!IsFeatureSupported(prev_version, FEATURE_HD_SPLIT) && IsFeatureSupported(new_version, FEATURE_HD_SPLIT)) {
483  WalletLogPrintf("Upgrading wallet to use HD chain split\n");
485  split_upgrade = FEATURE_HD_SPLIT > prev_version;
486  // Upgrade the HDChain
490  throw std::runtime_error(std::string(__func__) + ": writing chain failed");
491  }
492  }
493  }
494  // Mark all keys currently in the keypool as pre-split
495  if (split_upgrade) {
497  }
498  // Regenerate the keypool if upgraded to HD
499  if (hd_upgrade) {
500  if (!NewKeyPool()) {
501  error = _("Unable to generate keys");
502  return false;
503  }
504  }
505  return true;
506 }
507 
509 {
510  LOCK(cs_KeyStore);
511  return !mapKeys.empty() || !mapCryptedKeys.empty();
512 }
513 
515 {
516  LOCK(cs_KeyStore);
517  setInternalKeyPool.clear();
518  setExternalKeyPool.clear();
519  m_pool_key_to_index.clear();
520  // Note: can't top-up keypool here, because wallet is locked.
521  // User will be prompted to unlock wallet the next operation
522  // that requires a new key.
523 }
524 
525 static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, WalletBatch& batch) {
526  if (setKeyPool.empty()) {
527  return GetTime();
528  }
529 
530  CKeyPool keypool;
531  int64_t nIndex = *(setKeyPool.begin());
532  if (!batch.ReadPool(nIndex, keypool)) {
533  throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
534  }
535  assert(keypool.vchPubKey.IsValid());
536  return keypool.nTime;
537 }
538 
539 std::optional<int64_t> LegacyScriptPubKeyMan::GetOldestKeyPoolTime() const
540 {
541  LOCK(cs_KeyStore);
542 
544 
545  // load oldest key from keypool, get time and return
546  int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, batch);
548  oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, batch), oldestKey);
549  if (!set_pre_split_keypool.empty()) {
550  oldestKey = std::max(GetOldestKeyTimeInPool(set_pre_split_keypool, batch), oldestKey);
551  }
552  }
553 
554  return oldestKey;
555 }
556 
558 {
559  LOCK(cs_KeyStore);
560  return setExternalKeyPool.size() + set_pre_split_keypool.size();
561 }
562 
564 {
565  LOCK(cs_KeyStore);
566  return setInternalKeyPool.size() + setExternalKeyPool.size() + set_pre_split_keypool.size();
567 }
568 
570 {
571  LOCK(cs_KeyStore);
572  return nTimeFirstKey;
573 }
574 
575 std::unique_ptr<SigningProvider> LegacyScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
576 {
577  return std::make_unique<LegacySigningProvider>(*this);
578 }
579 
581 {
582  IsMineResult ismine = IsMineInner(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
583  if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
584  // If ismine, it means we recognize keys or script ids in the script, or
585  // are watching the script itself, and we can at least provide metadata
586  // or solving information, even if not able to sign fully.
587  return true;
588  } else {
589  // If, given the stuff in sigdata, we could make a valid sigature, then we can provide for this script
590  ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
591  if (!sigdata.signatures.empty()) {
592  // If we could make signatures, make sure we have a private key to actually make a signature
593  bool has_privkeys = false;
594  for (const auto& key_sig_pair : sigdata.signatures) {
595  has_privkeys |= HaveKey(key_sig_pair.first);
596  }
597  return has_privkeys;
598  }
599  return false;
600  }
601 }
602 
603 bool LegacyScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
604 {
605  return ::SignTransaction(tx, this, coins, sighash, input_errors);
606 }
607 
608 SigningResult LegacyScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
609 {
610  CKey key;
611  if (!GetKey(ToKeyID(pkhash), key)) {
613  }
614 
615  if (MessageSign(key, message, str_sig)) {
616  return SigningResult::OK;
617  }
619 }
620 
621 TransactionError LegacyScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, int sighash_type, bool sign, bool bip32derivs, int* n_signed, bool finalize) const
622 {
623  if (n_signed) {
624  *n_signed = 0;
625  }
626  for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
627  const CTxIn& txin = psbtx.tx->vin[i];
628  PSBTInput& input = psbtx.inputs.at(i);
629 
630  if (PSBTInputSigned(input)) {
631  continue;
632  }
633 
634  // Get the Sighash type
635  if (sign && input.sighash_type != std::nullopt && *input.sighash_type != sighash_type) {
637  }
638 
639  // Check non_witness_utxo has specified prevout
640  if (input.non_witness_utxo) {
641  if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
643  }
644  } else if (input.witness_utxo.IsNull()) {
645  // There's no UTXO so we can just skip this now
646  continue;
647  }
648  SignatureData sigdata;
649  input.FillSignatureData(sigdata);
650  SignPSBTInput(HidingSigningProvider(this, !sign, !bip32derivs), psbtx, i, &txdata, sighash_type, nullptr, finalize);
651 
652  bool signed_one = PSBTInputSigned(input);
653  if (n_signed && (signed_one || !sign)) {
654  // If sign is false, we assume that we _could_ sign if we get here. This
655  // will never have false negatives; it is hard to tell under what i
656  // circumstances it could have false positives.
657  (*n_signed)++;
658  }
659  }
660 
661  // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
662  for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
663  UpdatePSBTOutput(HidingSigningProvider(this, true, !bip32derivs), psbtx, i);
664  }
665 
666  return TransactionError::OK;
667 }
668 
669 std::unique_ptr<CKeyMetadata> LegacyScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
670 {
671  LOCK(cs_KeyStore);
672 
673  CKeyID key_id = GetKeyForDestination(*this, dest);
674  if (!key_id.IsNull()) {
675  auto it = mapKeyMetadata.find(key_id);
676  if (it != mapKeyMetadata.end()) {
677  return std::make_unique<CKeyMetadata>(it->second);
678  }
679  }
680 
681  CScript scriptPubKey = GetScriptForDestination(dest);
682  auto it = m_script_metadata.find(CScriptID(scriptPubKey));
683  if (it != m_script_metadata.end()) {
684  return std::make_unique<CKeyMetadata>(it->second);
685  }
686 
687  return nullptr;
688 }
689 
691 {
692  return uint256::ONE;
693 }
694 
700 {
702  if (nCreateTime <= 1) {
703  // Cannot determine birthday information, so set the wallet birthday to
704  // the beginning of time.
705  nTimeFirstKey = 1;
706  } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
707  nTimeFirstKey = nCreateTime;
708  }
709 }
710 
711 bool LegacyScriptPubKeyMan::LoadKey(const CKey& key, const CPubKey &pubkey)
712 {
713  return AddKeyPubKeyInner(key, pubkey);
714 }
715 
716 bool LegacyScriptPubKeyMan::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
717 {
718  LOCK(cs_KeyStore);
720  return LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(batch, secret, pubkey);
721 }
722 
723 bool LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(WalletBatch& batch, const CKey& secret, const CPubKey& pubkey)
724 {
726 
727  // Make sure we aren't adding private keys to private key disabled wallets
729 
730  // FillableSigningProvider has no concept of wallet databases, but calls AddCryptedKey
731  // which is overridden below. To avoid flushes, the database handle is
732  // tunneled through to it.
733  bool needsDB = !encrypted_batch;
734  if (needsDB) {
735  encrypted_batch = &batch;
736  }
737  if (!AddKeyPubKeyInner(secret, pubkey)) {
738  if (needsDB) encrypted_batch = nullptr;
739  return false;
740  }
741  if (needsDB) encrypted_batch = nullptr;
742 
743  // check if we need to remove from watch-only
744  CScript script;
745  script = GetScriptForDestination(PKHash(pubkey));
746  if (HaveWatchOnly(script)) {
747  RemoveWatchOnly(script);
748  }
749  script = GetScriptForRawPubKey(pubkey);
750  if (HaveWatchOnly(script)) {
751  RemoveWatchOnly(script);
752  }
753 
754  if (!m_storage.HasEncryptionKeys()) {
755  return batch.WriteKey(pubkey,
756  secret.GetPrivKey(),
757  mapKeyMetadata[pubkey.GetID()]);
758  }
760  return true;
761 }
762 
764 {
765  /* A sanity check was added in pull #3843 to avoid adding redeemScripts
766  * that never can be redeemed. However, old wallets may still contain
767  * these. Do not add them to the wallet and warn. */
768  if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
769  {
770  std::string strAddr = EncodeDestination(ScriptHash(redeemScript));
771  WalletLogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n", __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
772  return true;
773  }
774 
775  return FillableSigningProvider::AddCScript(redeemScript);
776 }
777 
779 {
780  LOCK(cs_KeyStore);
782  mapKeyMetadata[keyID] = meta;
783 }
784 
786 {
787  LOCK(cs_KeyStore);
789  m_script_metadata[script_id] = meta;
790 }
791 
793 {
794  LOCK(cs_KeyStore);
795  if (!m_storage.HasEncryptionKeys()) {
796  return FillableSigningProvider::AddKeyPubKey(key, pubkey);
797  }
798 
799  if (m_storage.IsLocked()) {
800  return false;
801  }
802 
803  std::vector<unsigned char> vchCryptedSecret;
804  CKeyingMaterial vchSecret(key.begin(), key.end());
805  if (!EncryptSecret(m_storage.GetEncryptionKey(), vchSecret, pubkey.GetHash(), vchCryptedSecret)) {
806  return false;
807  }
808 
809  if (!AddCryptedKey(pubkey, vchCryptedSecret)) {
810  return false;
811  }
812  return true;
813 }
814 
815 bool LegacyScriptPubKeyMan::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid)
816 {
817  // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
818  if (!checksum_valid) {
820  }
821 
822  return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
823 }
824 
825 bool LegacyScriptPubKeyMan::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
826 {
827  LOCK(cs_KeyStore);
828  assert(mapKeys.empty());
829 
830  mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
832  return true;
833 }
834 
836  const std::vector<unsigned char> &vchCryptedSecret)
837 {
838  if (!AddCryptedKeyInner(vchPubKey, vchCryptedSecret))
839  return false;
840  {
841  LOCK(cs_KeyStore);
842  if (encrypted_batch)
843  return encrypted_batch->WriteCryptedKey(vchPubKey,
844  vchCryptedSecret,
845  mapKeyMetadata[vchPubKey.GetID()]);
846  else
847  return WalletBatch(m_storage.GetDatabase()).WriteCryptedKey(vchPubKey,
848  vchCryptedSecret,
849  mapKeyMetadata[vchPubKey.GetID()]);
850  }
851 }
852 
854 {
855  LOCK(cs_KeyStore);
856  return setWatchOnly.count(dest) > 0;
857 }
858 
860 {
861  LOCK(cs_KeyStore);
862  return (!setWatchOnly.empty());
863 }
864 
865 static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
866 {
867  std::vector<std::vector<unsigned char>> solutions;
868  return Solver(dest, solutions) == TxoutType::PUBKEY &&
869  (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
870 }
871 
873 {
874  {
875  LOCK(cs_KeyStore);
876  setWatchOnly.erase(dest);
877  CPubKey pubKey;
878  if (ExtractPubKey(dest, pubKey)) {
879  mapWatchKeys.erase(pubKey.GetID());
880  }
881  // Related CScripts are not removed; having superfluous scripts around is
882  // harmless (see comment in ImplicitlyLearnRelatedKeyScripts).
883  }
884 
885  if (!HaveWatchOnly())
886  NotifyWatchonlyChanged(false);
888  return false;
889 
890  return true;
891 }
892 
894 {
895  return AddWatchOnlyInMem(dest);
896 }
897 
899 {
900  LOCK(cs_KeyStore);
901  setWatchOnly.insert(dest);
902  CPubKey pubKey;
903  if (ExtractPubKey(dest, pubKey)) {
904  mapWatchKeys[pubKey.GetID()] = pubKey;
906  }
907  return true;
908 }
909 
911 {
912  if (!AddWatchOnlyInMem(dest))
913  return false;
914  const CKeyMetadata& meta = m_script_metadata[CScriptID(dest)];
917  if (batch.WriteWatchOnly(dest, meta)) {
919  return true;
920  }
921  return false;
922 }
923 
924 bool LegacyScriptPubKeyMan::AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest, int64_t create_time)
925 {
926  m_script_metadata[CScriptID(dest)].nCreateTime = create_time;
927  return AddWatchOnlyWithDB(batch, dest);
928 }
929 
931 {
933  return AddWatchOnlyWithDB(batch, dest);
934 }
935 
936 bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
937 {
938  m_script_metadata[CScriptID(dest)].nCreateTime = nCreateTime;
939  return AddWatchOnly(dest);
940 }
941 
943 {
944  LOCK(cs_KeyStore);
945  m_hd_chain = chain;
946 }
947 
949 {
950  LOCK(cs_KeyStore);
951  // Store the new chain
953  throw std::runtime_error(std::string(__func__) + ": writing chain failed");
954  }
955  // When there's an old chain, add it as an inactive chain as we are now rotating hd chains
956  if (!m_hd_chain.seed_id.IsNull()) {
958  }
959 
960  m_hd_chain = chain;
961 }
962 
964 {
965  LOCK(cs_KeyStore);
966  assert(!chain.seed_id.IsNull());
967  m_inactive_hd_chains[chain.seed_id] = chain;
968 }
969 
970 bool LegacyScriptPubKeyMan::HaveKey(const CKeyID &address) const
971 {
972  LOCK(cs_KeyStore);
973  if (!m_storage.HasEncryptionKeys()) {
974  return FillableSigningProvider::HaveKey(address);
975  }
976  return mapCryptedKeys.count(address) > 0;
977 }
978 
979 bool LegacyScriptPubKeyMan::GetKey(const CKeyID &address, CKey& keyOut) const
980 {
981  LOCK(cs_KeyStore);
982  if (!m_storage.HasEncryptionKeys()) {
983  return FillableSigningProvider::GetKey(address, keyOut);
984  }
985 
986  CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
987  if (mi != mapCryptedKeys.end())
988  {
989  const CPubKey &vchPubKey = (*mi).second.first;
990  const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
991  return DecryptKey(m_storage.GetEncryptionKey(), vchCryptedSecret, vchPubKey, keyOut);
992  }
993  return false;
994 }
995 
997 {
998  CKeyMetadata meta;
999  {
1000  LOCK(cs_KeyStore);
1001  auto it = mapKeyMetadata.find(keyID);
1002  if (it == mapKeyMetadata.end()) {
1003  return false;
1004  }
1005  meta = it->second;
1006  }
1007  if (meta.has_key_origin) {
1008  std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4, info.fingerprint);
1009  info.path = meta.key_origin.path;
1010  } else { // Single pubkeys get the master fingerprint of themselves
1011  std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
1012  }
1013  return true;
1014 }
1015 
1016 bool LegacyScriptPubKeyMan::GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
1017 {
1018  LOCK(cs_KeyStore);
1019  WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
1020  if (it != mapWatchKeys.end()) {
1021  pubkey_out = it->second;
1022  return true;
1023  }
1024  return false;
1025 }
1026 
1027 bool LegacyScriptPubKeyMan::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
1028 {
1029  LOCK(cs_KeyStore);
1030  if (!m_storage.HasEncryptionKeys()) {
1031  if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
1032  return GetWatchPubKey(address, vchPubKeyOut);
1033  }
1034  return true;
1035  }
1036 
1037  CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
1038  if (mi != mapCryptedKeys.end())
1039  {
1040  vchPubKeyOut = (*mi).second.first;
1041  return true;
1042  }
1043  // Check for watch-only pubkeys
1044  return GetWatchPubKey(address, vchPubKeyOut);
1045 }
1046 
1048 {
1052  bool fCompressed = m_storage.CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
1053 
1054  CKey secret;
1055 
1056  // Create new metadata
1057  int64_t nCreationTime = GetTime();
1058  CKeyMetadata metadata(nCreationTime);
1059 
1060  // use HD key derivation if HD was enabled during wallet creation and a seed is present
1061  if (IsHDEnabled()) {
1062  DeriveNewChildKey(batch, metadata, secret, hd_chain, (m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
1063  } else {
1064  secret.MakeNewKey(fCompressed);
1065  }
1066 
1067  // Compressed public keys were introduced in version 0.6.0
1068  if (fCompressed) {
1070  }
1071 
1072  CPubKey pubkey = secret.GetPubKey();
1073  assert(secret.VerifyPubKey(pubkey));
1074 
1075  mapKeyMetadata[pubkey.GetID()] = metadata;
1076  UpdateTimeFirstKey(nCreationTime);
1077 
1078  if (!AddKeyPubKeyWithDB(batch, secret, pubkey)) {
1079  throw std::runtime_error(std::string(__func__) + ": AddKey failed");
1080  }
1081  return pubkey;
1082 }
1083 
1085 static void DeriveExtKey(CExtKey& key_in, unsigned int index, CExtKey& key_out) {
1086  if (!key_in.Derive(key_out, index)) {
1087  throw std::runtime_error("Could not derive extended key");
1088  }
1089 }
1090 
1091 void LegacyScriptPubKeyMan::DeriveNewChildKey(WalletBatch &batch, CKeyMetadata& metadata, CKey& secret, CHDChain& hd_chain, bool internal)
1092 {
1093  // for now we use a fixed keypath scheme of m/0'/0'/k
1094  CKey seed; //seed (256bit)
1095  CExtKey masterKey; //hd master key
1096  CExtKey accountKey; //key at m/0'
1097  CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
1098  CExtKey childKey; //key at m/0'/0'/<n>'
1099 
1100  // try to get the seed
1101  if (!GetKey(hd_chain.seed_id, seed))
1102  throw std::runtime_error(std::string(__func__) + ": seed not found");
1103 
1104  masterKey.SetSeed(seed);
1105 
1106  // derive m/0'
1107  // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
1108  DeriveExtKey(masterKey, BIP32_HARDENED_KEY_LIMIT, accountKey);
1109 
1110  // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
1111  assert(internal ? m_storage.CanSupportFeature(FEATURE_HD_SPLIT) : true);
1112  DeriveExtKey(accountKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0), chainChildKey);
1113 
1114  // derive child key at next index, skip keys already known to the wallet
1115  do {
1116  // always derive hardened keys
1117  // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
1118  // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
1119  if (internal) {
1120  DeriveExtKey(chainChildKey, hd_chain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT, childKey);
1121  metadata.hdKeypath = "m/0'/1'/" + ToString(hd_chain.nInternalChainCounter) + "'";
1122  metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1123  metadata.key_origin.path.push_back(1 | BIP32_HARDENED_KEY_LIMIT);
1124  metadata.key_origin.path.push_back(hd_chain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
1125  hd_chain.nInternalChainCounter++;
1126  }
1127  else {
1128  DeriveExtKey(chainChildKey, hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT, childKey);
1129  metadata.hdKeypath = "m/0'/0'/" + ToString(hd_chain.nExternalChainCounter) + "'";
1130  metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1131  metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1132  metadata.key_origin.path.push_back(hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
1133  hd_chain.nExternalChainCounter++;
1134  }
1135  } while (HaveKey(childKey.key.GetPubKey().GetID()));
1136  secret = childKey.key;
1137  metadata.hd_seed_id = hd_chain.seed_id;
1138  CKeyID master_id = masterKey.key.GetPubKey().GetID();
1139  std::copy(master_id.begin(), master_id.begin() + 4, metadata.key_origin.fingerprint);
1140  metadata.has_key_origin = true;
1141  // update the chain model in the database
1142  if (hd_chain.seed_id == m_hd_chain.seed_id && !batch.WriteHDChain(hd_chain))
1143  throw std::runtime_error(std::string(__func__) + ": writing HD chain model failed");
1144 }
1145 
1146 void LegacyScriptPubKeyMan::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
1147 {
1148  LOCK(cs_KeyStore);
1149  if (keypool.m_pre_split) {
1150  set_pre_split_keypool.insert(nIndex);
1151  } else if (keypool.fInternal) {
1152  setInternalKeyPool.insert(nIndex);
1153  } else {
1154  setExternalKeyPool.insert(nIndex);
1155  }
1156  m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
1157  m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
1158 
1159  // If no metadata exists yet, create a default with the pool key's
1160  // creation time. Note that this may be overwritten by actually
1161  // stored metadata for that key later, which is fine.
1162  CKeyID keyid = keypool.vchPubKey.GetID();
1163  if (mapKeyMetadata.count(keyid) == 0)
1164  mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
1165 }
1166 
1168 {
1169  // A wallet can generate keys if it has an HD seed (IsHDEnabled) or it is a non-HD wallet (pre FEATURE_HD)
1170  LOCK(cs_KeyStore);
1172 }
1173 
1175 {
1177  CKey key;
1178  key.MakeNewKey(true);
1179  return DeriveNewSeed(key);
1180 }
1181 
1183 {
1184  int64_t nCreationTime = GetTime();
1185  CKeyMetadata metadata(nCreationTime);
1186 
1187  // calculate the seed
1188  CPubKey seed = key.GetPubKey();
1189  assert(key.VerifyPubKey(seed));
1190 
1191  // set the hd keypath to "s" -> Seed, refers the seed to itself
1192  metadata.hdKeypath = "s";
1193  metadata.has_key_origin = false;
1194  metadata.hd_seed_id = seed.GetID();
1195 
1196  {
1197  LOCK(cs_KeyStore);
1198 
1199  // mem store the metadata
1200  mapKeyMetadata[seed.GetID()] = metadata;
1201 
1202  // write the key&metadata to the database
1203  if (!AddKeyPubKey(key, seed))
1204  throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1205  }
1206 
1207  return seed;
1208 }
1209 
1211 {
1212  LOCK(cs_KeyStore);
1213  // store the keyid (hash160) together with
1214  // the child index counter in the database
1215  // as a hdchain object
1216  CHDChain newHdChain;
1218  newHdChain.seed_id = seed.GetID();
1219  AddHDChain(newHdChain);
1223 }
1224 
1230 {
1232  return false;
1233  }
1234  {
1235  LOCK(cs_KeyStore);
1237 
1238  for (const int64_t nIndex : setInternalKeyPool) {
1239  batch.ErasePool(nIndex);
1240  }
1241  setInternalKeyPool.clear();
1242 
1243  for (const int64_t nIndex : setExternalKeyPool) {
1244  batch.ErasePool(nIndex);
1245  }
1246  setExternalKeyPool.clear();
1247 
1248  for (const int64_t nIndex : set_pre_split_keypool) {
1249  batch.ErasePool(nIndex);
1250  }
1251  set_pre_split_keypool.clear();
1252 
1253  m_pool_key_to_index.clear();
1254 
1255  if (!TopUp()) {
1256  return false;
1257  }
1258  WalletLogPrintf("LegacyScriptPubKeyMan::NewKeyPool rewrote keypool\n");
1259  }
1260  return true;
1261 }
1262 
1263 bool LegacyScriptPubKeyMan::TopUp(unsigned int kpSize)
1264 {
1265  if (!CanGenerateKeys()) {
1266  return false;
1267  }
1268 
1269  if (!TopUpChain(m_hd_chain, kpSize)) {
1270  return false;
1271  }
1272  for (auto& [chain_id, chain] : m_inactive_hd_chains) {
1273  if (!TopUpChain(chain, kpSize)) {
1274  return false;
1275  }
1276  }
1278  return true;
1279 }
1280 
1281 bool LegacyScriptPubKeyMan::TopUpChain(CHDChain& chain, unsigned int kpSize)
1282 {
1283  LOCK(cs_KeyStore);
1284 
1285  if (m_storage.IsLocked()) return false;
1286 
1287  // Top up key pool
1288  unsigned int nTargetSize;
1289  if (kpSize > 0) {
1290  nTargetSize = kpSize;
1291  } else {
1292  nTargetSize = std::max(gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), int64_t{0});
1293  }
1294  int64_t target = std::max((int64_t) nTargetSize, int64_t{1});
1295 
1296  // count amount of available keys (internal, external)
1297  // make sure the keypool of external and internal keys fits the user selected target (-keypool)
1298  int64_t missingExternal;
1299  int64_t missingInternal;
1300  if (chain == m_hd_chain) {
1301  missingExternal = std::max(target - (int64_t)setExternalKeyPool.size(), int64_t{0});
1302  missingInternal = std::max(target - (int64_t)setInternalKeyPool.size(), int64_t{0});
1303  } else {
1304  missingExternal = std::max(target - (chain.nExternalChainCounter - chain.m_next_external_index), int64_t{0});
1305  missingInternal = std::max(target - (chain.nInternalChainCounter - chain.m_next_internal_index), int64_t{0});
1306  }
1307 
1309  // don't create extra internal keys
1310  missingInternal = 0;
1311  }
1312  bool internal = false;
1314  for (int64_t i = missingInternal + missingExternal; i--;) {
1315  if (i < missingInternal) {
1316  internal = true;
1317  }
1318 
1319  CPubKey pubkey(GenerateNewKey(batch, chain, internal));
1320  if (chain == m_hd_chain) {
1321  AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1322  }
1323  }
1324  if (missingInternal + missingExternal > 0) {
1325  if (chain == m_hd_chain) {
1326  WalletLogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size() + set_pre_split_keypool.size(), setInternalKeyPool.size());
1327  } else {
1328  WalletLogPrintf("inactive seed with id %s added %d external keys, %d internal keys\n", HexStr(chain.seed_id), missingExternal, missingInternal);
1329  }
1330  }
1331  return true;
1332 }
1333 
1334 void LegacyScriptPubKeyMan::AddKeypoolPubkeyWithDB(const CPubKey& pubkey, const bool internal, WalletBatch& batch)
1335 {
1336  LOCK(cs_KeyStore);
1337  assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
1338  int64_t index = ++m_max_keypool_index;
1339  if (!batch.WritePool(index, CKeyPool(pubkey, internal))) {
1340  throw std::runtime_error(std::string(__func__) + ": writing imported pubkey failed");
1341  }
1342  if (internal) {
1343  setInternalKeyPool.insert(index);
1344  } else {
1345  setExternalKeyPool.insert(index);
1346  }
1347  m_pool_key_to_index[pubkey.GetID()] = index;
1348 }
1349 
1350 void LegacyScriptPubKeyMan::KeepDestination(int64_t nIndex, const OutputType& type)
1351 {
1352  assert(type != OutputType::BECH32M);
1353  // Remove from key pool
1355  batch.ErasePool(nIndex);
1356  CPubKey pubkey;
1357  bool have_pk = GetPubKey(m_index_to_reserved_key.at(nIndex), pubkey);
1358  assert(have_pk);
1359  LearnRelatedScripts(pubkey, type);
1360  m_index_to_reserved_key.erase(nIndex);
1361  WalletLogPrintf("keypool keep %d\n", nIndex);
1362 }
1363 
1364 void LegacyScriptPubKeyMan::ReturnDestination(int64_t nIndex, bool fInternal, const CTxDestination&)
1365 {
1366  // Return to key pool
1367  {
1368  LOCK(cs_KeyStore);
1369  if (fInternal) {
1370  setInternalKeyPool.insert(nIndex);
1371  } else if (!set_pre_split_keypool.empty()) {
1372  set_pre_split_keypool.insert(nIndex);
1373  } else {
1374  setExternalKeyPool.insert(nIndex);
1375  }
1376  CKeyID& pubkey_id = m_index_to_reserved_key.at(nIndex);
1377  m_pool_key_to_index[pubkey_id] = nIndex;
1378  m_index_to_reserved_key.erase(nIndex);
1380  }
1381  WalletLogPrintf("keypool return %d\n", nIndex);
1382 }
1383 
1384 bool LegacyScriptPubKeyMan::GetKeyFromPool(CPubKey& result, const OutputType type, bool internal)
1385 {
1386  assert(type != OutputType::BECH32M);
1387  if (!CanGetAddresses(internal)) {
1388  return false;
1389  }
1390 
1391  CKeyPool keypool;
1392  {
1393  LOCK(cs_KeyStore);
1394  int64_t nIndex;
1396  if (m_storage.IsLocked()) return false;
1398  result = GenerateNewKey(batch, m_hd_chain, internal);
1399  return true;
1400  }
1401  KeepDestination(nIndex, type);
1402  result = keypool.vchPubKey;
1403  }
1404  return true;
1405 }
1406 
1407 bool LegacyScriptPubKeyMan::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
1408 {
1409  nIndex = -1;
1410  keypool.vchPubKey = CPubKey();
1411  {
1412  LOCK(cs_KeyStore);
1413 
1414  bool fReturningInternal = fRequestedInternal;
1416  bool use_split_keypool = set_pre_split_keypool.empty();
1417  std::set<int64_t>& setKeyPool = use_split_keypool ? (fReturningInternal ? setInternalKeyPool : setExternalKeyPool) : set_pre_split_keypool;
1418 
1419  // Get the oldest key
1420  if (setKeyPool.empty()) {
1421  return false;
1422  }
1423 
1425 
1426  auto it = setKeyPool.begin();
1427  nIndex = *it;
1428  setKeyPool.erase(it);
1429  if (!batch.ReadPool(nIndex, keypool)) {
1430  throw std::runtime_error(std::string(__func__) + ": read failed");
1431  }
1432  CPubKey pk;
1433  if (!GetPubKey(keypool.vchPubKey.GetID(), pk)) {
1434  throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
1435  }
1436  // If the key was pre-split keypool, we don't care about what type it is
1437  if (use_split_keypool && keypool.fInternal != fReturningInternal) {
1438  throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
1439  }
1440  if (!keypool.vchPubKey.IsValid()) {
1441  throw std::runtime_error(std::string(__func__) + ": keypool entry invalid");
1442  }
1443 
1444  assert(m_index_to_reserved_key.count(nIndex) == 0);
1445  m_index_to_reserved_key[nIndex] = keypool.vchPubKey.GetID();
1446  m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1447  WalletLogPrintf("keypool reserve %d\n", nIndex);
1448  }
1450  return true;
1451 }
1452 
1454 {
1455  assert(type != OutputType::BECH32M);
1456  if (key.IsCompressed() && (type == OutputType::P2SH_SEGWIT || type == OutputType::BECH32)) {
1457  CTxDestination witdest = WitnessV0KeyHash(key.GetID());
1458  CScript witprog = GetScriptForDestination(witdest);
1459  // Make sure the resulting program is solvable.
1460  const auto desc = InferDescriptor(witprog, *this);
1461  assert(desc && desc->IsSolvable());
1462  AddCScript(witprog);
1463  }
1464 }
1465 
1467 {
1468  // OutputType::P2SH_SEGWIT always adds all necessary scripts for all types.
1470 }
1471 
1472 std::vector<CKeyPool> LegacyScriptPubKeyMan::MarkReserveKeysAsUsed(int64_t keypool_id)
1473 {
1475  bool internal = setInternalKeyPool.count(keypool_id);
1476  if (!internal) assert(setExternalKeyPool.count(keypool_id) || set_pre_split_keypool.count(keypool_id));
1477  std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : (set_pre_split_keypool.empty() ? &setExternalKeyPool : &set_pre_split_keypool);
1478  auto it = setKeyPool->begin();
1479 
1480  std::vector<CKeyPool> result;
1482  while (it != std::end(*setKeyPool)) {
1483  const int64_t& index = *(it);
1484  if (index > keypool_id) break; // set*KeyPool is ordered
1485 
1486  CKeyPool keypool;
1487  if (batch.ReadPool(index, keypool)) { //TODO: This should be unnecessary
1488  m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1489  }
1491  batch.ErasePool(index);
1492  WalletLogPrintf("keypool index %d removed\n", index);
1493  it = setKeyPool->erase(it);
1494  result.push_back(std::move(keypool));
1495  }
1496 
1497  return result;
1498 }
1499 
1500 std::vector<CKeyID> GetAffectedKeys(const CScript& spk, const SigningProvider& provider)
1501 {
1502  std::vector<CScript> dummy;
1503  FlatSigningProvider out;
1504  InferDescriptor(spk, provider)->Expand(0, DUMMY_SIGNING_PROVIDER, dummy, out);
1505  std::vector<CKeyID> ret;
1506  for (const auto& entry : out.pubkeys) {
1507  ret.push_back(entry.first);
1508  }
1509  return ret;
1510 }
1511 
1513 {
1515  for (auto it = setExternalKeyPool.begin(); it != setExternalKeyPool.end();) {
1516  int64_t index = *it;
1517  CKeyPool keypool;
1518  if (!batch.ReadPool(index, keypool)) {
1519  throw std::runtime_error(std::string(__func__) + ": read keypool entry failed");
1520  }
1521  keypool.m_pre_split = true;
1522  if (!batch.WritePool(index, keypool)) {
1523  throw std::runtime_error(std::string(__func__) + ": writing modified keypool entry failed");
1524  }
1525  set_pre_split_keypool.insert(index);
1526  it = setExternalKeyPool.erase(it);
1527  }
1528 }
1529 
1531 {
1533  return AddCScriptWithDB(batch, redeemScript);
1534 }
1535 
1537 {
1538  if (!FillableSigningProvider::AddCScript(redeemScript))
1539  return false;
1540  if (batch.WriteCScript(Hash160(redeemScript), redeemScript)) {
1542  return true;
1543  }
1544  return false;
1545 }
1546 
1548 {
1549  LOCK(cs_KeyStore);
1550  std::copy(info.fingerprint, info.fingerprint + 4, mapKeyMetadata[pubkey.GetID()].key_origin.fingerprint);
1551  mapKeyMetadata[pubkey.GetID()].key_origin.path = info.path;
1552  mapKeyMetadata[pubkey.GetID()].has_key_origin = true;
1553  mapKeyMetadata[pubkey.GetID()].hdKeypath = WriteHDKeypath(info.path);
1554  return batch.WriteKeyMetadata(mapKeyMetadata[pubkey.GetID()], pubkey, true);
1555 }
1556 
1557 bool LegacyScriptPubKeyMan::ImportScripts(const std::set<CScript> scripts, int64_t timestamp)
1558 {
1560  for (const auto& entry : scripts) {
1561  CScriptID id(entry);
1562  if (HaveCScript(id)) {
1563  WalletLogPrintf("Already have script %s, skipping\n", HexStr(entry));
1564  continue;
1565  }
1566  if (!AddCScriptWithDB(batch, entry)) {
1567  return false;
1568  }
1569 
1570  if (timestamp > 0) {
1571  m_script_metadata[CScriptID(entry)].nCreateTime = timestamp;
1572  }
1573  }
1574  if (timestamp > 0) {
1575  UpdateTimeFirstKey(timestamp);
1576  }
1577 
1578  return true;
1579 }
1580 
1581 bool LegacyScriptPubKeyMan::ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp)
1582 {
1584  for (const auto& entry : privkey_map) {
1585  const CKey& key = entry.second;
1586  CPubKey pubkey = key.GetPubKey();
1587  const CKeyID& id = entry.first;
1588  assert(key.VerifyPubKey(pubkey));
1589  // Skip if we already have the key
1590  if (HaveKey(id)) {
1591  WalletLogPrintf("Already have key with pubkey %s, skipping\n", HexStr(pubkey));
1592  continue;
1593  }
1594  mapKeyMetadata[id].nCreateTime = timestamp;
1595  // If the private key is not present in the wallet, insert it.
1596  if (!AddKeyPubKeyWithDB(batch, key, pubkey)) {
1597  return false;
1598  }
1599  UpdateTimeFirstKey(timestamp);
1600  }
1601  return true;
1602 }
1603 
1604 bool LegacyScriptPubKeyMan::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)
1605 {
1607  for (const auto& entry : key_origins) {
1608  AddKeyOriginWithDB(batch, entry.second.first, entry.second.second);
1609  }
1610  for (const CKeyID& id : ordered_pubkeys) {
1611  auto entry = pubkey_map.find(id);
1612  if (entry == pubkey_map.end()) {
1613  continue;
1614  }
1615  const CPubKey& pubkey = entry->second;
1616  CPubKey temp;
1617  if (GetPubKey(id, temp)) {
1618  // Already have pubkey, skipping
1619  WalletLogPrintf("Already have pubkey %s, skipping\n", HexStr(temp));
1620  continue;
1621  }
1622  if (!AddWatchOnlyWithDB(batch, GetScriptForRawPubKey(pubkey), timestamp)) {
1623  return false;
1624  }
1625  mapKeyMetadata[id].nCreateTime = timestamp;
1626 
1627  // Add to keypool only works with pubkeys
1628  if (add_keypool) {
1629  AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1631  }
1632  }
1633  return true;
1634 }
1635 
1636 bool LegacyScriptPubKeyMan::ImportScriptPubKeys(const std::set<CScript>& script_pub_keys, const bool have_solving_data, const int64_t timestamp)
1637 {
1639  for (const CScript& script : script_pub_keys) {
1640  if (!have_solving_data || !IsMine(script)) { // Always call AddWatchOnly for non-solvable watch-only, so that watch timestamp gets updated
1641  if (!AddWatchOnlyWithDB(batch, script, timestamp)) {
1642  return false;
1643  }
1644  }
1645  }
1646  return true;
1647 }
1648 
1649 std::set<CKeyID> LegacyScriptPubKeyMan::GetKeys() const
1650 {
1651  LOCK(cs_KeyStore);
1652  if (!m_storage.HasEncryptionKeys()) {
1654  }
1655  std::set<CKeyID> set_address;
1656  for (const auto& mi : mapCryptedKeys) {
1657  set_address.insert(mi.first);
1658  }
1659  return set_address;
1660 }
1661 
1662 const std::unordered_set<CScript, SaltedSipHasher> LegacyScriptPubKeyMan::GetScriptPubKeys() const
1663 {
1664  LOCK(cs_KeyStore);
1665  std::unordered_set<CScript, SaltedSipHasher> spks;
1666 
1667  // All keys have at least P2PK and P2PKH
1668  for (const auto& key_pair : mapKeys) {
1669  const CPubKey& pub = key_pair.second.GetPubKey();
1670  spks.insert(GetScriptForRawPubKey(pub));
1671  spks.insert(GetScriptForDestination(PKHash(pub)));
1672  }
1673  for (const auto& key_pair : mapCryptedKeys) {
1674  const CPubKey& pub = key_pair.second.first;
1675  spks.insert(GetScriptForRawPubKey(pub));
1676  spks.insert(GetScriptForDestination(PKHash(pub)));
1677  }
1678 
1679  // For every script in mapScript, only the ISMINE_SPENDABLE ones are being tracked.
1680  // The watchonly ones will be in setWatchOnly which we deal with later
1681  // For all keys, if they have segwit scripts, those scripts will end up in mapScripts
1682  for (const auto& script_pair : mapScripts) {
1683  const CScript& script = script_pair.second;
1684  if (IsMine(script) == ISMINE_SPENDABLE) {
1685  // Add ScriptHash for scripts that are not already P2SH
1686  if (!script.IsPayToScriptHash()) {
1687  spks.insert(GetScriptForDestination(ScriptHash(script)));
1688  }
1689  // For segwit scripts, we only consider them spendable if we have the segwit spk
1690  int wit_ver = -1;
1691  std::vector<unsigned char> witprog;
1692  if (script.IsWitnessProgram(wit_ver, witprog) && wit_ver == 0) {
1693  spks.insert(script);
1694  }
1695  } else {
1696  // Multisigs are special. They don't show up as ISMINE_SPENDABLE unless they are in a P2SH
1697  // So check the P2SH of a multisig to see if we should insert it
1698  std::vector<std::vector<unsigned char>> sols;
1699  TxoutType type = Solver(script, sols);
1700  if (type == TxoutType::MULTISIG) {
1701  CScript ms_spk = GetScriptForDestination(ScriptHash(script));
1702  if (IsMine(ms_spk) != ISMINE_NO) {
1703  spks.insert(ms_spk);
1704  }
1705  }
1706  }
1707  }
1708 
1709  // All watchonly scripts are raw
1710  spks.insert(setWatchOnly.begin(), setWatchOnly.end());
1711 
1712  return spks;
1713 }
1714 
1715 std::optional<MigrationData> LegacyScriptPubKeyMan::MigrateToDescriptor()
1716 {
1717  LOCK(cs_KeyStore);
1718  if (m_storage.IsLocked()) {
1719  return std::nullopt;
1720  }
1721 
1722  MigrationData out;
1723 
1724  std::unordered_set<CScript, SaltedSipHasher> spks{GetScriptPubKeys()};
1725 
1726  // Get all key ids
1727  std::set<CKeyID> keyids;
1728  for (const auto& key_pair : mapKeys) {
1729  keyids.insert(key_pair.first);
1730  }
1731  for (const auto& key_pair : mapCryptedKeys) {
1732  keyids.insert(key_pair.first);
1733  }
1734 
1735  // Get key metadata and figure out which keys don't have a seed
1736  // Note that we do not ignore the seeds themselves because they are considered IsMine!
1737  for (auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
1738  const CKeyID& keyid = *keyid_it;
1739  const auto& it = mapKeyMetadata.find(keyid);
1740  if (it != mapKeyMetadata.end()) {
1741  const CKeyMetadata& meta = it->second;
1742  if (meta.hdKeypath == "s" || meta.hdKeypath == "m") {
1743  keyid_it++;
1744  continue;
1745  }
1746  if (m_hd_chain.seed_id == meta.hd_seed_id || m_inactive_hd_chains.count(meta.hd_seed_id) > 0) {
1747  keyid_it = keyids.erase(keyid_it);
1748  continue;
1749  }
1750  }
1751  keyid_it++;
1752  }
1753 
1754  // keyids is now all non-HD keys. Each key will have its own combo descriptor
1755  for (const CKeyID& keyid : keyids) {
1756  CKey key;
1757  if (!GetKey(keyid, key)) {
1758  assert(false);
1759  }
1760 
1761  // Get birthdate from key meta
1762  uint64_t creation_time = 0;
1763  const auto& it = mapKeyMetadata.find(keyid);
1764  if (it != mapKeyMetadata.end()) {
1765  creation_time = it->second.nCreateTime;
1766  }
1767 
1768  // Get the key origin
1769  // Maybe this doesn't matter because floating keys here shouldn't have origins
1770  KeyOriginInfo info;
1771  bool has_info = GetKeyOrigin(keyid, info);
1772  std::string origin_str = has_info ? "[" + HexStr(info.fingerprint) + FormatHDKeypath(info.path) + "]" : "";
1773 
1774  // Construct the combo descriptor
1775  std::string desc_str = "combo(" + origin_str + HexStr(key.GetPubKey()) + ")";
1776  FlatSigningProvider keys;
1777  std::string error;
1778  std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, error, false);
1779  WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
1780 
1781  // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
1782  auto desc_spk_man = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(m_storage, w_desc));
1783  desc_spk_man->AddDescriptorKey(key, key.GetPubKey());
1784  desc_spk_man->TopUp();
1785  auto desc_spks = desc_spk_man->GetScriptPubKeys();
1786 
1787  // Remove the scriptPubKeys from our current set
1788  for (const CScript& spk : desc_spks) {
1789  size_t erased = spks.erase(spk);
1790  assert(erased == 1);
1791  assert(IsMine(spk) == ISMINE_SPENDABLE);
1792  }
1793 
1794  out.desc_spkms.push_back(std::move(desc_spk_man));
1795  }
1796 
1797  // Handle HD keys by using the CHDChains
1798  std::vector<CHDChain> chains;
1799  chains.push_back(m_hd_chain);
1800  for (const auto& chain_pair : m_inactive_hd_chains) {
1801  chains.push_back(chain_pair.second);
1802  }
1803  for (const CHDChain& chain : chains) {
1804  for (int i = 0; i < 2; ++i) {
1805  // Skip if doing internal chain and split chain is not supported
1806  if (chain.seed_id.IsNull() || (i == 1 && !m_storage.CanSupportFeature(FEATURE_HD_SPLIT))) {
1807  continue;
1808  }
1809  // Get the master xprv
1810  CKey seed_key;
1811  if (!GetKey(chain.seed_id, seed_key)) {
1812  assert(false);
1813  }
1814  CExtKey master_key;
1815  master_key.SetSeed(seed_key);
1816 
1817  // Make the combo descriptor
1818  std::string xpub = EncodeExtPubKey(master_key.Neuter());
1819  std::string desc_str = "combo(" + xpub + "/0'/" + ToString(i) + "'/*')";
1820  FlatSigningProvider keys;
1821  std::string error;
1822  std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, error, false);
1823  uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
1824  WalletDescriptor w_desc(std::move(desc), 0, 0, chain_counter, 0);
1825 
1826  // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
1827  auto desc_spk_man = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(m_storage, w_desc));
1828  desc_spk_man->AddDescriptorKey(master_key.key, master_key.key.GetPubKey());
1829  desc_spk_man->TopUp();
1830  auto desc_spks = desc_spk_man->GetScriptPubKeys();
1831 
1832  // Remove the scriptPubKeys from our current set
1833  for (const CScript& spk : desc_spks) {
1834  size_t erased = spks.erase(spk);
1835  assert(erased == 1);
1836  assert(IsMine(spk) == ISMINE_SPENDABLE);
1837  }
1838 
1839  out.desc_spkms.push_back(std::move(desc_spk_man));
1840  }
1841  }
1842  // Add the current master seed to the migration data
1843  if (!m_hd_chain.seed_id.IsNull()) {
1844  CKey seed_key;
1845  if (!GetKey(m_hd_chain.seed_id, seed_key)) {
1846  assert(false);
1847  }
1848  out.master_key.SetSeed(seed_key);
1849  }
1850 
1851  // Handle the rest of the scriptPubKeys which must be imports and may not have all info
1852  for (auto it = spks.begin(); it != spks.end();) {
1853  const CScript& spk = *it;
1854 
1855  // Get birthdate from script meta
1856  uint64_t creation_time = 0;
1857  const auto& mit = m_script_metadata.find(CScriptID(spk));
1858  if (mit != m_script_metadata.end()) {
1859  creation_time = mit->second.nCreateTime;
1860  }
1861 
1862  // InferDescriptor as that will get us all the solving info if it is there
1863  std::unique_ptr<Descriptor> desc = InferDescriptor(spk, *GetSolvingProvider(spk));
1864  // Get the private keys for this descriptor
1865  std::vector<CScript> scripts;
1866  FlatSigningProvider keys;
1867  if (!desc->Expand(0, DUMMY_SIGNING_PROVIDER, scripts, keys)) {
1868  assert(false);
1869  }
1870  std::set<CKeyID> privkeyids;
1871  for (const auto& key_orig_pair : keys.origins) {
1872  privkeyids.insert(key_orig_pair.first);
1873  }
1874 
1875  std::vector<CScript> desc_spks;
1876 
1877  // Make the descriptor string with private keys
1878  std::string desc_str;
1879  bool watchonly = !desc->ToPrivateString(*this, desc_str);
1881  out.watch_descs.push_back({desc->ToString(), creation_time});
1882 
1883  // Get the scriptPubKeys without writing this to the wallet
1884  FlatSigningProvider provider;
1885  desc->Expand(0, provider, desc_spks, provider);
1886  } else {
1887  // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
1888  WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
1889  auto desc_spk_man = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(m_storage, w_desc));
1890  for (const auto& keyid : privkeyids) {
1891  CKey key;
1892  if (!GetKey(keyid, key)) {
1893  continue;
1894  }
1895  desc_spk_man->AddDescriptorKey(key, key.GetPubKey());
1896  }
1897  desc_spk_man->TopUp();
1898  auto desc_spks_set = desc_spk_man->GetScriptPubKeys();
1899  desc_spks.insert(desc_spks.end(), desc_spks_set.begin(), desc_spks_set.end());
1900 
1901  out.desc_spkms.push_back(std::move(desc_spk_man));
1902  }
1903 
1904  // Remove the scriptPubKeys from our current set
1905  for (const CScript& desc_spk : desc_spks) {
1906  auto del_it = spks.find(desc_spk);
1907  assert(del_it != spks.end());
1908  assert(IsMine(desc_spk) != ISMINE_NO);
1909  it = spks.erase(del_it);
1910  }
1911  }
1912 
1913  // Multisigs are special. They don't show up as ISMINE_SPENDABLE unless they are in a P2SH
1914  // So we have to check if any of our scripts are a multisig and if so, add the P2SH
1915  for (const auto& script_pair : mapScripts) {
1916  const CScript script = script_pair.second;
1917 
1918  // Get birthdate from script meta
1919  uint64_t creation_time = 0;
1920  const auto& it = m_script_metadata.find(CScriptID(script));
1921  if (it != m_script_metadata.end()) {
1922  creation_time = it->second.nCreateTime;
1923  }
1924 
1925  std::vector<std::vector<unsigned char>> sols;
1926  TxoutType type = Solver(script, sols);
1927  if (type == TxoutType::MULTISIG) {
1928  CScript sh_spk = GetScriptForDestination(ScriptHash(script));
1929  CTxDestination witdest = WitnessV0ScriptHash(script);
1930  CScript witprog = GetScriptForDestination(witdest);
1931  CScript sh_wsh_spk = GetScriptForDestination(ScriptHash(witprog));
1932 
1933  // We only want the multisigs that we have not already seen, i.e. they are not watchonly and not spendable
1934  // For P2SH, a multisig is not ISMINE_NO when:
1935  // * All keys are in the wallet
1936  // * The multisig itself is watch only
1937  // * The P2SH is watch only
1938  // For P2SH-P2WSH, if the script is in the wallet, then it will have the same conditions as P2SH.
1939  // For P2WSH, a multisig is not ISMINE_NO when, other than the P2SH conditions:
1940  // * The P2WSH script is in the wallet and it is being watched
1941  std::vector<std::vector<unsigned char>> keys(sols.begin() + 1, sols.begin() + sols.size() - 1);
1942  if (HaveWatchOnly(sh_spk) || HaveWatchOnly(script) || HaveKeys(keys, *this) || (HaveCScript(CScriptID(witprog)) && HaveWatchOnly(witprog))) {
1943  // The above emulates IsMine for these 3 scriptPubKeys, so double check that by running IsMine
1944  assert(IsMine(sh_spk) != ISMINE_NO || IsMine(witprog) != ISMINE_NO || IsMine(sh_wsh_spk) != ISMINE_NO);
1945  continue;
1946  }
1947  assert(IsMine(sh_spk) == ISMINE_NO && IsMine(witprog) == ISMINE_NO && IsMine(sh_wsh_spk) == ISMINE_NO);
1948 
1949  std::unique_ptr<Descriptor> sh_desc = InferDescriptor(sh_spk, *GetSolvingProvider(sh_spk));
1950  out.solvable_descs.push_back({sh_desc->ToString(), creation_time});
1951 
1952  const auto desc = InferDescriptor(witprog, *this);
1953  if (desc->IsSolvable()) {
1954  std::unique_ptr<Descriptor> wsh_desc = InferDescriptor(witprog, *GetSolvingProvider(witprog));
1955  out.solvable_descs.push_back({wsh_desc->ToString(), creation_time});
1956  std::unique_ptr<Descriptor> sh_wsh_desc = InferDescriptor(sh_wsh_spk, *GetSolvingProvider(sh_wsh_spk));
1957  out.solvable_descs.push_back({sh_wsh_desc->ToString(), creation_time});
1958  }
1959  }
1960  }
1961 
1962  // Make sure that we have accounted for all scriptPubKeys
1963  assert(spks.size() == 0);
1964  return out;
1965 }
1966 
1968 {
1969  LOCK(cs_KeyStore);
1971  return batch.EraseRecords(DBKeys::LEGACY_TYPES);
1972 }
1973 
1975 {
1976  // Returns true if this descriptor supports getting new addresses. Conditions where we may be unable to fetch them (e.g. locked) are caught later
1977  if (!CanGetAddresses()) {
1978  return util::Error{_("No addresses available")};
1979  }
1980  {
1981  LOCK(cs_desc_man);
1982  assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
1983  std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
1984  assert(desc_addr_type);
1985  if (type != *desc_addr_type) {
1986  throw std::runtime_error(std::string(__func__) + ": Types are inconsistent");
1987  }
1988 
1989  TopUp();
1990 
1991  // Get the scriptPubKey from the descriptor
1992  FlatSigningProvider out_keys;
1993  std::vector<CScript> scripts_temp;
1994  if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
1995  // We can't generate anymore keys
1996  return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
1997  }
1998  if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1999  // We can't generate anymore keys
2000  return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
2001  }
2002 
2003  CTxDestination dest;
2004  std::optional<OutputType> out_script_type = m_wallet_descriptor.descriptor->GetOutputType();
2005  if (out_script_type && out_script_type == type) {
2006  ExtractDestination(scripts_temp[0], dest);
2007  } else {
2008  throw std::runtime_error(std::string(__func__) + ": Types are inconsistent. Stored type does not match type of newly generated address");
2009  }
2010  m_wallet_descriptor.next_index++;
2011  WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
2012  return dest;
2013  }
2014 }
2015 
2017 {
2018  LOCK(cs_desc_man);
2019  if (m_map_script_pub_keys.count(script) > 0) {
2020  return ISMINE_SPENDABLE;
2021  }
2022  return ISMINE_NO;
2023 }
2024 
2025 bool DescriptorScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key, bool accept_no_keys)
2026 {
2027  LOCK(cs_desc_man);
2028  if (!m_map_keys.empty()) {
2029  return false;
2030  }
2031 
2032  bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
2033  bool keyFail = false;
2034  for (const auto& mi : m_map_crypted_keys) {
2035  const CPubKey &pubkey = mi.second.first;
2036  const std::vector<unsigned char> &crypted_secret = mi.second.second;
2037  CKey key;
2038  if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
2039  keyFail = true;
2040  break;
2041  }
2042  keyPass = true;
2044  break;
2045  }
2046  if (keyPass && keyFail) {
2047  LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
2048  throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
2049  }
2050  if (keyFail || (!keyPass && !accept_no_keys)) {
2051  return false;
2052  }
2054  return true;
2055 }
2056 
2058 {
2059  LOCK(cs_desc_man);
2060  if (!m_map_crypted_keys.empty()) {
2061  return false;
2062  }
2063 
2064  for (const KeyMap::value_type& key_in : m_map_keys)
2065  {
2066  const CKey &key = key_in.second;
2067  CPubKey pubkey = key.GetPubKey();
2068  CKeyingMaterial secret(key.begin(), key.end());
2069  std::vector<unsigned char> crypted_secret;
2070  if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
2071  return false;
2072  }
2073  m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
2074  batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
2075  }
2076  m_map_keys.clear();
2077  return true;
2078 }
2079 
2081 {
2082  LOCK(cs_desc_man);
2083  auto op_dest = GetNewDestination(type);
2084  index = m_wallet_descriptor.next_index - 1;
2085  return op_dest;
2086 }
2087 
2088 void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
2089 {
2090  LOCK(cs_desc_man);
2091  // Only return when the index was the most recent
2092  if (m_wallet_descriptor.next_index - 1 == index) {
2093  m_wallet_descriptor.next_index--;
2094  }
2095  WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
2097 }
2098 
2099 std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
2100 {
2103  KeyMap keys;
2104  for (const auto& key_pair : m_map_crypted_keys) {
2105  const CPubKey& pubkey = key_pair.second.first;
2106  const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
2107  CKey key;
2108  DecryptKey(m_storage.GetEncryptionKey(), crypted_secret, pubkey, key);
2109  keys[pubkey.GetID()] = key;
2110  }
2111  return keys;
2112  }
2113  return m_map_keys;
2114 }
2115 
2116 bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
2117 {
2118  LOCK(cs_desc_man);
2119  unsigned int target_size;
2120  if (size > 0) {
2121  target_size = size;
2122  } else {
2123  target_size = std::max(gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 1);
2124  }
2125 
2126  // Calculate the new range_end
2127  int32_t new_range_end = std::max(m_wallet_descriptor.next_index + (int32_t)target_size, m_wallet_descriptor.range_end);
2128 
2129  // If the descriptor is not ranged, we actually just want to fill the first cache item
2130  if (!m_wallet_descriptor.descriptor->IsRange()) {
2131  new_range_end = 1;
2132  m_wallet_descriptor.range_end = 1;
2133  m_wallet_descriptor.range_start = 0;
2134  }
2135 
2136  FlatSigningProvider provider;
2137  provider.keys = GetKeys();
2138 
2140  uint256 id = GetID();
2141  for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
2142  FlatSigningProvider out_keys;
2143  std::vector<CScript> scripts_temp;
2144  DescriptorCache temp_cache;
2145  // Maybe we have a cached xpub and we can expand from the cache first
2146  if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2147  if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
2148  }
2149  // Add all of the scriptPubKeys to the scriptPubKey set
2150  for (const CScript& script : scripts_temp) {
2151  m_map_script_pub_keys[script] = i;
2152  }
2153  for (const auto& pk_pair : out_keys.pubkeys) {
2154  const CPubKey& pubkey = pk_pair.second;
2155  if (m_map_pubkeys.count(pubkey) != 0) {
2156  // We don't need to give an error here.
2157  // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and it's private key
2158  continue;
2159  }
2160  m_map_pubkeys[pubkey] = i;
2161  }
2162  // Merge and write the cache
2163  DescriptorCache new_items = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
2164  if (!batch.WriteDescriptorCacheItems(id, new_items)) {
2165  throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
2166  }
2168  }
2169  m_wallet_descriptor.range_end = new_range_end;
2170  batch.WriteDescriptor(GetID(), m_wallet_descriptor);
2171 
2172  // By this point, the cache size should be the size of the entire range
2173  assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
2174 
2176  return true;
2177 }
2178 
2179 std::vector<WalletDestination> DescriptorScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
2180 {
2181  LOCK(cs_desc_man);
2182  std::vector<WalletDestination> result;
2183  if (IsMine(script)) {
2184  int32_t index = m_map_script_pub_keys[script];
2185  if (index >= m_wallet_descriptor.next_index) {
2186  WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
2187  auto out_keys = std::make_unique<FlatSigningProvider>();
2188  std::vector<CScript> scripts_temp;
2189  while (index >= m_wallet_descriptor.next_index) {
2190  if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
2191  throw std::runtime_error(std::string(__func__) + ": Unable to expand descriptor from cache");
2192  }
2193  CTxDestination dest;
2194  ExtractDestination(scripts_temp[0], dest);
2195  result.push_back({dest, std::nullopt});
2196  m_wallet_descriptor.next_index++;
2197  }
2198  }
2199  if (!TopUp()) {
2200  WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
2201  }
2202  }
2203 
2204  return result;
2205 }
2206 
2208 {
2209  LOCK(cs_desc_man);
2211  if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
2212  throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
2213  }
2214 }
2215 
2217 {
2220 
2221  // Check if provided key already exists
2222  if (m_map_keys.find(pubkey.GetID()) != m_map_keys.end() ||
2223  m_map_crypted_keys.find(pubkey.GetID()) != m_map_crypted_keys.end()) {
2224  return true;
2225  }
2226 
2227  if (m_storage.HasEncryptionKeys()) {
2228  if (m_storage.IsLocked()) {
2229  return false;
2230  }
2231 
2232  std::vector<unsigned char> crypted_secret;
2233  CKeyingMaterial secret(key.begin(), key.end());
2234  if (!EncryptSecret(m_storage.GetEncryptionKey(), secret, pubkey.GetHash(), crypted_secret)) {
2235  return false;
2236  }
2237 
2238  m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
2239  return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
2240  } else {
2241  m_map_keys[pubkey.GetID()] = key;
2242  return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
2243  }
2244 }
2245 
2246 bool DescriptorScriptPubKeyMan::SetupDescriptorGeneration(const CExtKey& master_key, OutputType addr_type, bool internal)
2247 {
2248  LOCK(cs_desc_man);
2250 
2251  // Ignore when there is already a descriptor
2252  if (m_wallet_descriptor.descriptor) {
2253  return false;
2254  }
2255 
2256  int64_t creation_time = GetTime();
2257 
2258  std::string xpub = EncodeExtPubKey(master_key.Neuter());
2259 
2260  // Build descriptor string
2261  std::string desc_prefix;
2262  std::string desc_suffix = "/*)";
2263  switch (addr_type) {
2264  case OutputType::LEGACY: {
2265  desc_prefix = "pkh(" + xpub + "/44'";
2266  break;
2267  }
2268  case OutputType::P2SH_SEGWIT: {
2269  desc_prefix = "sh(wpkh(" + xpub + "/49'";
2270  desc_suffix += ")";
2271  break;
2272  }
2273  case OutputType::BECH32: {
2274  desc_prefix = "wpkh(" + xpub + "/84'";
2275  break;
2276  }
2277  case OutputType::BECH32M: {
2278  desc_prefix = "tr(" + xpub + "/86'";
2279  break;
2280  }
2281  case OutputType::UNKNOWN: {
2282  // We should never have a DescriptorScriptPubKeyMan for an UNKNOWN OutputType,
2283  // so if we get to this point something is wrong
2284  assert(false);
2285  }
2286  } // no default case, so the compiler can warn about missing cases
2287  assert(!desc_prefix.empty());
2288 
2289  // Mainnet derives at 0', testnet and regtest derive at 1'
2290  if (Params().IsTestChain()) {
2291  desc_prefix += "/1'";
2292  } else {
2293  desc_prefix += "/0'";
2294  }
2295 
2296  std::string internal_path = internal ? "/1" : "/0";
2297  std::string desc_str = desc_prefix + "/0'" + internal_path + desc_suffix;
2298 
2299  // Make the descriptor
2300  FlatSigningProvider keys;
2301  std::string error;
2302  std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, error, false);
2303  WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
2304  m_wallet_descriptor = w_desc;
2305 
2306  // Store the master private key, and descriptor
2308  if (!AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey())) {
2309  throw std::runtime_error(std::string(__func__) + ": writing descriptor master private key failed");
2310  }
2311  if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
2312  throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
2313  }
2314 
2315  // TopUp
2316  TopUp();
2317 
2319  return true;
2320 }
2321 
2323 {
2324  LOCK(cs_desc_man);
2325  return m_wallet_descriptor.descriptor->IsRange();
2326 }
2327 
2329 {
2330  // We can only give out addresses from descriptors that are single type (not combo), ranged,
2331  // and either have cached keys or can generate more keys (ignoring encryption)
2332  LOCK(cs_desc_man);
2333  return m_wallet_descriptor.descriptor->IsSingleType() &&
2334  m_wallet_descriptor.descriptor->IsRange() &&
2335  (HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
2336 }
2337 
2339 {
2340  LOCK(cs_desc_man);
2341  return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
2342 }
2343 
2345 {
2346  // This is only used for getwalletinfo output and isn't relevant to descriptor wallets.
2347  return std::nullopt;
2348 }
2349 
2350 
2352 {
2353  LOCK(cs_desc_man);
2354  return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
2355 }
2356 
2358 {
2359  LOCK(cs_desc_man);
2360  return m_wallet_descriptor.creation_time;
2361 }
2362 
2363 std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
2364 {
2365  LOCK(cs_desc_man);
2366 
2367  // Find the index of the script
2368  auto it = m_map_script_pub_keys.find(script);
2369  if (it == m_map_script_pub_keys.end()) {
2370  return nullptr;
2371  }
2372  int32_t index = it->second;
2373 
2374  return GetSigningProvider(index, include_private);
2375 }
2376 
2377 std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
2378 {
2379  LOCK(cs_desc_man);
2380 
2381  // Find index of the pubkey
2382  auto it = m_map_pubkeys.find(pubkey);
2383  if (it == m_map_pubkeys.end()) {
2384  return nullptr;
2385  }
2386  int32_t index = it->second;
2387 
2388  // Always try to get the signing provider with private keys. This function should only be called during signing anyways
2389  return GetSigningProvider(index, true);
2390 }
2391 
2392 std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
2393 {
2395 
2396  std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
2397 
2398  // Fetch SigningProvider from cache to avoid re-deriving
2399  auto it = m_map_signing_providers.find(index);
2400  if (it != m_map_signing_providers.end()) {
2401  out_keys->Merge(FlatSigningProvider{it->second});
2402  } else {
2403  // Get the scripts, keys, and key origins for this script
2404  std::vector<CScript> scripts_temp;
2405  if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
2406 
2407  // Cache SigningProvider so we don't need to re-derive if we need this SigningProvider again
2408  m_map_signing_providers[index] = *out_keys;
2409  }
2410 
2411  if (HavePrivateKeys() && include_private) {
2412  FlatSigningProvider master_provider;
2413  master_provider.keys = GetKeys();
2414  m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
2415  }
2416 
2417  return out_keys;
2418 }
2419 
2420 std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
2421 {
2422  return GetSigningProvider(script, false);
2423 }
2424 
2426 {
2427  return IsMine(script);
2428 }
2429 
2430 bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
2431 {
2432  std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
2433  for (const auto& coin_pair : coins) {
2434  std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
2435  if (!coin_keys) {
2436  continue;
2437  }
2438  keys->Merge(std::move(*coin_keys));
2439  }
2440 
2441  return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
2442 }
2443 
2444 SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
2445 {
2446  std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
2447  if (!keys) {
2449  }
2450 
2451  CKey key;
2452  if (!keys->GetKey(ToKeyID(pkhash), key)) {
2454  }
2455 
2456  if (!MessageSign(key, message, str_sig)) {
2458  }
2459  return SigningResult::OK;
2460 }
2461 
2462 TransactionError DescriptorScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, int sighash_type, bool sign, bool bip32derivs, int* n_signed, bool finalize) const
2463 {
2464  if (n_signed) {
2465  *n_signed = 0;
2466  }
2467  for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
2468  const CTxIn& txin = psbtx.tx->vin[i];
2469  PSBTInput& input = psbtx.inputs.at(i);
2470 
2471  if (PSBTInputSigned(input)) {
2472  continue;
2473  }
2474 
2475  // Get the Sighash type
2476  if (sign && input.sighash_type != std::nullopt && *input.sighash_type != sighash_type) {
2478  }
2479 
2480  // Get the scriptPubKey to know which SigningProvider to use
2481  CScript script;
2482  if (!input.witness_utxo.IsNull()) {
2483  script = input.witness_utxo.scriptPubKey;
2484  } else if (input.non_witness_utxo) {
2485  if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
2487  }
2488  script = input.non_witness_utxo->vout[txin.prevout.n].scriptPubKey;
2489  } else {
2490  // There's no UTXO so we can just skip this now
2491  continue;
2492  }
2493  SignatureData sigdata;
2494  input.FillSignatureData(sigdata);
2495 
2496  std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
2497  std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, sign);
2498  if (script_keys) {
2499  keys->Merge(std::move(*script_keys));
2500  } else {
2501  // Maybe there are pubkeys listed that we can sign for
2502  script_keys = std::make_unique<FlatSigningProvider>();
2503  for (const auto& pk_pair : input.hd_keypaths) {
2504  const CPubKey& pubkey = pk_pair.first;
2505  std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
2506  if (pk_keys) {
2507  keys->Merge(std::move(*pk_keys));
2508  }
2509  }
2510  for (const auto& pk_pair : input.m_tap_bip32_paths) {
2511  const XOnlyPubKey& pubkey = pk_pair.first;
2512  for (unsigned char prefix : {0x02, 0x03}) {
2513  unsigned char b[33] = {prefix};
2514  std::copy(pubkey.begin(), pubkey.end(), b + 1);
2515  CPubKey fullpubkey;
2516  fullpubkey.Set(b, b + 33);
2517  std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(fullpubkey);
2518  if (pk_keys) {
2519  keys->Merge(std::move(*pk_keys));
2520  }
2521  }
2522  }
2523  }
2524 
2525  SignPSBTInput(HidingSigningProvider(keys.get(), !sign, !bip32derivs), psbtx, i, &txdata, sighash_type, nullptr, finalize);
2526 
2527  bool signed_one = PSBTInputSigned(input);
2528  if (n_signed && (signed_one || !sign)) {
2529  // If sign is false, we assume that we _could_ sign if we get here. This
2530  // will never have false negatives; it is hard to tell under what i
2531  // circumstances it could have false positives.
2532  (*n_signed)++;
2533  }
2534  }
2535 
2536  // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
2537  for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
2538  std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
2539  if (!keys) {
2540  continue;
2541  }
2542  UpdatePSBTOutput(HidingSigningProvider(keys.get(), true, !bip32derivs), psbtx, i);
2543  }
2544 
2545  return TransactionError::OK;
2546 }
2547 
2548 std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
2549 {
2550  std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
2551  if (provider) {
2552  KeyOriginInfo orig;
2553  CKeyID key_id = GetKeyForDestination(*provider, dest);
2554  if (provider->GetKeyOrigin(key_id, orig)) {
2555  LOCK(cs_desc_man);
2556  std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
2557  meta->key_origin = orig;
2558  meta->has_key_origin = true;
2559  meta->nCreateTime = m_wallet_descriptor.creation_time;
2560  return meta;
2561  }
2562  }
2563  return nullptr;
2564 }
2565 
2567 {
2568  LOCK(cs_desc_man);
2569  std::string desc_str = m_wallet_descriptor.descriptor->ToString();
2570  uint256 id;
2571  CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
2572  return id;
2573 }
2574 
2576 {
2577  LOCK(cs_desc_man);
2578  m_wallet_descriptor.cache = cache;
2579  for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
2580  FlatSigningProvider out_keys;
2581  std::vector<CScript> scripts_temp;
2582  if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2583  throw std::runtime_error("Error: Unable to expand wallet descriptor from cache");
2584  }
2585  // Add all of the scriptPubKeys to the scriptPubKey set
2586  for (const CScript& script : scripts_temp) {
2587  if (m_map_script_pub_keys.count(script) != 0) {
2588  throw std::runtime_error(strprintf("Error: Already loaded script at index %d as being at index %d", i, m_map_script_pub_keys[script]));
2589  }
2590  m_map_script_pub_keys[script] = i;
2591  }
2592  for (const auto& pk_pair : out_keys.pubkeys) {
2593  const CPubKey& pubkey = pk_pair.second;
2594  if (m_map_pubkeys.count(pubkey) != 0) {
2595  // We don't need to give an error here.
2596  // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and it's private key
2597  continue;
2598  }
2599  m_map_pubkeys[pubkey] = i;
2600  }
2602  }
2603 }
2604 
2605 bool DescriptorScriptPubKeyMan::AddKey(const CKeyID& key_id, const CKey& key)
2606 {
2607  LOCK(cs_desc_man);
2608  m_map_keys[key_id] = key;
2609  return true;
2610 }
2611 
2612 bool DescriptorScriptPubKeyMan::AddCryptedKey(const CKeyID& key_id, const CPubKey& pubkey, const std::vector<unsigned char>& crypted_key)
2613 {
2614  LOCK(cs_desc_man);
2615  if (!m_map_keys.empty()) {
2616  return false;
2617  }
2618 
2619  m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
2620  return true;
2621 }
2622 
2624 {
2625  LOCK(cs_desc_man);
2626  return m_wallet_descriptor.descriptor != nullptr && desc.descriptor != nullptr && m_wallet_descriptor.descriptor->ToString() == desc.descriptor->ToString();
2627 }
2628 
2630 {
2631  LOCK(cs_desc_man);
2633  if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
2634  throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
2635  }
2636 }
2637 
2639 {
2640  return m_wallet_descriptor;
2641 }
2642 
2643 const std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
2644 {
2645  LOCK(cs_desc_man);
2646  std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
2647  script_pub_keys.reserve(m_map_script_pub_keys.size());
2648 
2649  for (auto const& script_pub_key: m_map_script_pub_keys) {
2650  script_pub_keys.insert(script_pub_key.first);
2651  }
2652  return script_pub_keys;
2653 }
2654 
2655 bool DescriptorScriptPubKeyMan::GetDescriptorString(std::string& out, const bool priv) const
2656 {
2657  LOCK(cs_desc_man);
2658 
2659  FlatSigningProvider provider;
2660  provider.keys = GetKeys();
2661 
2662  if (priv) {
2663  // For the private version, always return the master key to avoid
2664  // exposing child private keys. The risk implications of exposing child
2665  // private keys together with the parent xpub may be non-obvious for users.
2666  return m_wallet_descriptor.descriptor->ToPrivateString(provider, out);
2667  }
2668 
2669  return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
2670 }
2671 
2673 {
2674  LOCK(cs_desc_man);
2676  return;
2677  }
2678 
2679  // Skip if we have the last hardened xpub cache
2680  if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
2681  return;
2682  }
2683 
2684  // Expand the descriptor
2685  FlatSigningProvider provider;
2686  provider.keys = GetKeys();
2687  FlatSigningProvider out_keys;
2688  std::vector<CScript> scripts_temp;
2689  DescriptorCache temp_cache;
2690  if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
2691  throw std::runtime_error("Unable to expand descriptor");
2692  }
2693 
2694  // Cache the last hardened xpubs
2695  DescriptorCache diff = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
2697  throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
2698  }
2699 }
2700 
2702 {
2703  LOCK(cs_desc_man);
2704  std::string error;
2705  if (!CanUpdateToWalletDescriptor(descriptor, error)) {
2706  throw std::runtime_error(std::string(__func__) + ": " + error);
2707  }
2708 
2709  m_map_pubkeys.clear();
2710  m_map_script_pub_keys.clear();
2711  m_max_cached_index = -1;
2712  m_wallet_descriptor = descriptor;
2713 }
2714 
2716 {
2717  LOCK(cs_desc_man);
2718  if (!HasWalletDescriptor(descriptor)) {
2719  error = "can only update matching descriptor";
2720  return false;
2721  }
2722 
2723  if (descriptor.range_start > m_wallet_descriptor.range_start ||
2724  descriptor.range_end < m_wallet_descriptor.range_end) {
2725  // Use inclusive range for error
2726  error = strprintf("new range must include current range = [%d,%d]",
2727  m_wallet_descriptor.range_start,
2728  m_wallet_descriptor.range_end - 1);
2729  return false;
2730  }
2731 
2732  return true;
2733 }
2734 } // namespace wallet
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 FormatHDKeypath(const std::vector< uint32_t > &path)
Definition: bip32.cpp:54
std::string WriteHDKeypath(const std::vector< uint32_t > &keypath)
Write HD keypaths as strings.
Definition: bip32.cpp:64
int ret
const CChainParams & Params()
Return the currently selected parameters.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: system.cpp:629
An encapsulated private key.
Definition: key.h:27
const unsigned char * end() const
Definition: key.h:90
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:174
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:160
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:187
const unsigned char * begin() const
Definition: key.h:89
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:241
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:24
uint32_t n
Definition: transaction.h:38
An encapsulated public key.
Definition: pubkey.h:34
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:198
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:164
bool IsValid() const
Definition: pubkey.h:189
uint256 GetHash() const
Get the 256-bit hash of this public key.
Definition: pubkey.h:170
void Set(const T pbegin, const T pend)
Initialize a public key using begin/end iterators to byte data.
Definition: pubkey.h:89
A hasher class for RIPEMD-160.
Definition: ripemd160.h:13
CRIPEMD160 & Write(const unsigned char *data, size_t len)
Definition: ripemd160.cpp:247
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: ripemd160.cpp:273
A hasher class for SHA-256.
Definition: sha256.h:14
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: sha256.cpp:707
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:681
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:411
bool IsPayToScriptHash() const
Definition: script.cpp:201
bool IsWitnessProgram(int &version, std::vector< unsigned char > &program) const
Definition: script.cpp:220
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:27
An input of a transaction.
Definition: transaction.h:74
COutPoint prevout
Definition: transaction.h:76
CScript scriptPubKey
Definition: transaction.h:160
bool IsNull() const
Definition: transaction.h:177
Cache for single descriptor's derived extended pubkeys.
Definition: descriptor.h:19
DescriptorCache MergeAndDiff(const DescriptorCache &other)
Combine another DescriptorCache into this one.
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)
void ImplicitlyLearnRelatedKeyScripts(const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
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
An interface to be implemented by keystores that support signing.
const unsigned char * begin() const
Definition: pubkey.h:282
const unsigned char * end() const
Definition: pubkey.h:283
bool IsNull() const
Definition: uint256.h:34
unsigned char * begin()
Definition: uint256.h:61
size_type size() const
Definition: prevector.h:284
iterator insert(iterator pos, const T &value)
Definition: prevector.h:349
160-bit opaque blob.
Definition: uint256.h:108
256-bit opaque blob.
Definition: uint256.h:119
static const uint256 ONE
Definition: uint256.h:125
uint32_t nInternalChainCounter
Definition: walletdb.h:98
static const int VERSION_HD_BASE
Definition: walletdb.h:103
uint32_t nExternalChainCounter
Definition: walletdb.h:97
int64_t m_next_external_index
Definition: walletdb.h:100
static const int VERSION_HD_CHAIN_SPLIT
Definition: walletdb.h:104
CKeyID seed_id
seed hash160
Definition: walletdb.h:99
int64_t m_next_internal_index
Definition: walletdb.h:101
static const int VERSION_WITH_KEY_ORIGIN
Definition: walletdb.h:137
std::string hdKeypath
Definition: walletdb.h:141
bool has_key_origin
Whether the key_origin is useful.
Definition: walletdb.h:144
KeyOriginInfo key_origin
Definition: walletdb.h:143
A key from a CWallet's keypool.
int64_t nTime
The time at which the key was generated. Set in AddKeypoolPubKeyWithDB.
CPubKey vchPubKey
The public key.
bool fInternal
Whether this keypool entry is in the internal keypool (for change outputs)
bool m_pre_split
Whether this key was generated for a keypool before the wallet was upgraded to HD-split.
KeyMap GetKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
bool SetupDescriptorGeneration(const CExtKey &master_key, OutputType addr_type, bool internal)
Setup descriptors based on the given CExtkey.
void SetCache(const DescriptorCache &cache)
std::map< int32_t, FlatSigningProvider > m_map_signing_providers
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that,...
bool SignTransaction(CMutableTransaction &tx, const std::map< COutPoint, Coin > &coins, int sighash, std::map< int, bilingual_str > &input_errors) const override
Creates new signatures and adds them to the transaction.
const WalletDescriptor GetWalletDescriptor() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
bool AddCryptedKey(const CKeyID &key_id, const CPubKey &pubkey, const std::vector< unsigned char > &crypted_key)
bool TopUp(unsigned int size=0) override
Fills internal address pool.
bool m_decryption_thoroughly_checked
keeps track of whether Unlock has run a thorough check before
std::map< CKeyID, CKey > KeyMap
unsigned int GetKeyPoolSize() const override
int64_t GetTimeFirstKey() const override
std::unique_ptr< FlatSigningProvider > GetSigningProvider(const CScript &script, bool include_private=false) const
bool CanGetAddresses(bool internal=false) const override
bool CanUpdateToWalletDescriptor(const WalletDescriptor &descriptor, std::string &error)
bool GetDescriptorString(std::string &out, const bool priv) const
std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const override
util::Result< CTxDestination > GetReservedDestination(const OutputType type, bool internal, int64_t &index, CKeyPool &keypool) override
const std::unordered_set< CScript, SaltedSipHasher > GetScriptPubKeys() const override
Returns a set of all the scriptPubKeys that this ScriptPubKeyMan watches.
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. it decrypts all of the ke...
void AddDescriptorKey(const CKey &key, const CPubKey &pubkey)
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
bool AddKey(const CKeyID &key_id, const CKey &key)
void ReturnDestination(int64_t index, bool internal, const CTxDestination &addr) override
std::vector< WalletDestination > MarkUnusedAddresses(const CScript &script) override
Mark unused addresses as being used Affects all keys up to and including the one determined by provid...
bool AddDescriptorKeyWithDB(WalletBatch &batch, const CKey &key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
bool HasWalletDescriptor(const WalletDescriptor &desc) const
void UpdateWalletDescriptor(WalletDescriptor &descriptor)
std::optional< int64_t > GetOldestKeyPoolTime() const override
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const override
Sign a message with the given script.
util::Result< CTxDestination > GetNewDestination(const OutputType type) override
TransactionError FillPSBT(PartiallySignedTransaction &psbt, const PrecomputedTransactionData &txdata, int sighash_type=SIGHASH_DEFAULT, bool sign=true, bool bip32derivs=false, int *n_signed=nullptr, bool finalize=true) const override
Adds script and derivation path information to a PSBT, and optionally signs it.
isminetype IsMine(const CScript &script) const override
bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch) override
bool AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
std::vector< CKeyPool > MarkReserveKeysAsUsed(int64_t keypool_id) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Marks all keys in the keypool up to and including the provided key as used.
bool DeleteRecords()
Delete all the records ofthis LegacyScriptPubKeyMan from disk.
bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const override
bool CanGetAddresses(bool internal=false) const override
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Adds a key to the store, and saves it to disk.
util::Result< CTxDestination > GetNewDestination(const OutputType type) override
util::Result< CTxDestination > GetReservedDestination(const OutputType type, bool internal, int64_t &index, CKeyPool &keypool) override
void AddInactiveHDChain(const CHDChain &chain)
bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch) override
void AddHDChain(const CHDChain &chain)
bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, bool checksum_valid)
Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
bool AddCScriptWithDB(WalletBatch &batch, const CScript &script)
Adds a script to the store and saves it to disk.
std::unordered_map< CKeyID, CHDChain, SaltedSipHasher > m_inactive_hd_chains
bool GetKey(const CKeyID &address, CKey &keyOut) const override
bool AddKeyOriginWithDB(WalletBatch &batch, const CPubKey &pubkey, const KeyOriginInfo &info)
Add a KeyOriginInfo to the wallet.
void MarkPreSplitKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const override
Sign a message with the given script.
uint256 GetID() const override
bool AddWatchOnlyInMem(const CScript &dest)
bool HaveWatchOnly() const
Returns whether there are any watch-only things in the wallet.
void LoadKeyMetadata(const CKeyID &keyID, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
bool SignTransaction(CMutableTransaction &tx, const std::map< COutPoint, Coin > &coins, int sighash, std::map< int, bilingual_str > &input_errors) const override
Creates new signatures and adds them to the transaction.
bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
Adds an encrypted key to the store, and saves it to disk.
bool ReserveKeyFromKeyPool(int64_t &nIndex, CKeyPool &keypool, bool fRequestedInternal)
Reserves a key from the keypool and sets nIndex to its index.
void AddKeypoolPubkeyWithDB(const CPubKey &pubkey, const bool internal, WalletBatch &batch)
std::map< int64_t, CKeyID > m_index_to_reserved_key
bool fDecryptionThoroughlyChecked
keeps track of whether Unlock has run a thorough check before
bool ImportScripts(const std::set< CScript > scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
void UpgradeKeyMetadata()
Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo.
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 HavePrivateKeys() const override
void LoadScriptMetadata(const CScriptID &script_id, const CKeyMetadata &metadata)
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
TransactionError FillPSBT(PartiallySignedTransaction &psbt, const PrecomputedTransactionData &txdata, int sighash_type=SIGHASH_DEFAULT, bool sign=true, bool bip32derivs=false, int *n_signed=nullptr, bool finalize=true) const override
Adds script and derivation path information to a PSBT, and optionally signs it.
std::vector< WalletDestination > MarkUnusedAddresses(const CScript &script) override
Mark unused addresses as being used Affects all keys up to and including the one determined by provid...
bool HaveWatchOnly(const CScript &dest) const
Returns whether the watch-only script is in the wallet.
bool LoadKey(const CKey &key, const CPubKey &pubkey)
Adds a key to the store, without saving it to disk (used by LoadWallet)
void UpdateTimeFirstKey(int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Update wallet first key creation time.
bool TopUp(unsigned int size=0) override
Fills internal address pool.
unsigned int GetKeyPoolSize() const override
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
bool TopUpChain(CHDChain &chain, unsigned int size)
void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
Load a keypool entry.
bool TopUpInactiveHDChain(const CKeyID seed_id, int64_t index, bool internal)
Like TopUp() but adds keys for inactive HD chains.
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that,...
void LoadHDChain(const CHDChain &chain)
Load a HD chain model (used by LoadWallet)
std::set< CKeyID > GetKeys() const override
bool AddKeyPubKeyInner(const CKey &key, const CPubKey &pubkey)
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. it decrypts all of the ke...
bool ImportPubKeys(const std::vector< CKeyID > &ordered_pubkeys, const std::map< CKeyID, CPubKey > &pubkey_map, const std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo >> &key_origins, const bool add_keypool, const bool internal, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool IsHDEnabled() const override
bool GetKeyFromPool(CPubKey &key, const OutputType type, bool internal=false)
Fetches a key from the keypool.
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.
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
isminetype IsMine(const CScript &script) const override
bool AddCScript(const CScript &redeemScript) override
int64_t GetTimeFirstKey() const override
bool NewKeyPool()
Mark old keypool keys as used, and generate all new keys.
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
bool SetupGeneration(bool force=false) override
Sets up the key generation stuff, i.e.
void LearnRelatedScripts(const CPubKey &key, OutputType)
Explicitly make the wallet learn the related scripts for outputs to the given key.
void LearnAllRelatedScripts(const CPubKey &key)
Same as LearnRelatedScripts, but when the OutputType is not known (and could be anything).
CPubKey DeriveNewSeed(const CKey &key)
std::optional< MigrationData > MigrateToDescriptor()
Get the DescriptorScriptPubKeyMans (with private keys) that have the same scriptPubKeys as this Legac...
void DeriveNewChildKey(WalletBatch &batch, CKeyMetadata &metadata, CKey &secret, CHDChain &hd_chain, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool LoadCScript(const CScript &redeemScript)
Adds a CScript to the store.
void ReturnDestination(int64_t index, bool internal, const CTxDestination &) override
std::map< CKeyID, int64_t > m_pool_key_to_index
CPubKey GenerateNewKey(WalletBatch &batch, CHDChain &hd_chain, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Generate a new key.
void SetHDSeed(const CPubKey &key)
bool AddWatchOnlyWithDB(WalletBatch &batch, const CScript &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
const std::unordered_set< CScript, SaltedSipHasher > GetScriptPubKeys() const override
Returns a set of all the scriptPubKeys that this ScriptPubKeyMan watches.
bool ImportPrivKeys(const std::map< CKeyID, CKey > &privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const override
bool Upgrade(int prev_version, int new_version, bilingual_str &error) override
Upgrades the wallet to the specified version.
void KeepDestination(int64_t index, const OutputType &type) override
void RewriteDB() override
The action to do when the DB needs rewrite.
std::optional< int64_t > GetOldestKeyPoolTime() const override
bool RemoveWatchOnly(const CScript &dest)
Remove a watch only script from the keystore.
bool HaveKey(const CKeyID &address) const override
bool ImportScriptPubKeys(const std::set< CScript > &script_pub_keys, const bool have_solving_data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
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.
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
WalletStorage & m_storage
Access to the wallet database.
Definition: walletdb.h:188
bool WriteDescriptor(const uint256 &desc_id, const WalletDescriptor &descriptor)
Definition: walletdb.cpp:242
bool WriteDescriptorCacheItems(const uint256 &desc_id, const DescriptorCache &cache)
Definition: walletdb.cpp:268
bool WriteHDChain(const CHDChain &chain)
write the hdchain model (external chain child index counter)
Definition: walletdb.cpp:1092
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
Definition: walletdb.cpp:157
bool EraseRecords(const std::unordered_set< std::string > &types)
Delete records of the given types.
Definition: walletdb.cpp:1102
bool WriteKeyMetadata(const CKeyMetadata &meta, const CPubKey &pubkey, const bool overwrite)
Definition: walletdb.cpp:101
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:106
bool ReadPool(int64_t nPool, CKeyPool &keypool)
Definition: walletdb.cpp:190
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:121
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< unsigned char > &secret)
Definition: walletdb.cpp:233
bool WritePool(int64_t nPool, const CKeyPool &keypool)
Definition: walletdb.cpp:195
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
Definition: walletdb.cpp:222
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
Definition: walletdb.cpp:152
bool ErasePool(int64_t nPool)
Definition: walletdb.cpp:200
bool EraseWatchOnly(const CScript &script)
Definition: walletdb.cpp:165
Descriptor with some wallet metadata.
Definition: walletutil.h:77
std::shared_ptr< Descriptor > descriptor
Definition: walletutil.h:79
virtual bool IsWalletFlagSet(uint64_t) const =0
virtual void SetMinVersion(enum WalletFeature, WalletBatch *=nullptr)=0
virtual bool CanSupportFeature(enum WalletFeature) const =0
virtual const CKeyingMaterial & GetEncryptionKey() const =0
virtual WalletDatabase & GetDatabase() const =0
virtual void UnsetBlankWalletFlag(WalletBatch &)=0
virtual bool IsLocked() const =0
virtual bool HasEncryptionKeys() const =0
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:91
@ WITNESS_V0
Witness v0 (P2WPKH and P2WSH); see BIP 141.
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:276
std::string EncodeExtPubKey(const CExtPubKey &key)
Definition: key_io.cpp:242
#define LogPrintf(...)
Definition: logging.h:234
SigningResult
Definition: message.h:43
@ PRIVATE_KEY_NOT_AVAILABLE
@ OK
No error.
const std::unordered_set< std::string > LEGACY_TYPES
Definition: walletdb.cpp:62
Definition: node.h:39
static int64_t GetOldestKeyTimeInPool(const std::set< int64_t > &setKeyPool, WalletBatch &batch)
std::vector< unsigned char > valtype
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: crypter.h:62
bool DecryptKey(const CKeyingMaterial &vMasterKey, const std::vector< unsigned char > &vchCryptedSecret, const CPubKey &vchPubKey, CKey &key)
Definition: crypter.cpp:128
std::vector< CKeyID > GetAffectedKeys(const CScript &spk, const SigningProvider &provider)
static const unsigned int DEFAULT_KEYPOOL_SIZE
Default for -keypool.
static const std::unordered_set< OutputType > LEGACY_OUTPUT_TYPES
OutputTypes supported by the LegacyScriptPubKeyMan.
const uint32_t BIP32_HARDENED_KEY_LIMIT
Value for the first BIP 32 hardened derivation. Can be used as a bit mask and as a value....
static void DeriveExtKey(CExtKey &key_in, unsigned int index, CExtKey &key_out)
Try to derive an extended key, throw if it fails.
isminetype
IsMine() return codes, which depend on ScriptPubKeyMan implementation.
Definition: ismine.h:41
@ ISMINE_NO
Definition: ismine.h:42
@ ISMINE_SPENDABLE
Definition: ismine.h:44
@ ISMINE_WATCH_ONLY
Definition: ismine.h:43
static bool ExtractPubKey(const CScript &dest, CPubKey &pubKeyOut)
@ FEATURE_COMPRPUBKEY
Definition: walletutil.h:20
@ FEATURE_HD_SPLIT
Definition: walletutil.h:24
@ FEATURE_HD
Definition: walletutil.h:22
@ FEATURE_PRE_SPLIT_KEYPOOL
Definition: walletutil.h:28
bool EncryptSecret(const CKeyingMaterial &vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256 &nIV, std::vector< unsigned char > &vchCiphertext)
Definition: crypter.cpp:108
bool IsFeatureSupported(int wallet_version, int feature_version)
Definition: walletutil.cpp:33
@ WALLET_FLAG_LAST_HARDENED_XPUB_CACHED
Definition: walletutil.h:48
@ WALLET_FLAG_KEY_ORIGIN_METADATA
Definition: walletutil.h:45
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:66
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:51
@ WALLET_FLAG_BLANK_WALLET
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses,...
Definition: walletutil.h:63
CTxDestination GetDestinationForKey(const CPubKey &key, OutputType type)
Get a destination of the requested type (if possible) to the specified key.
Definition: outputtype.cpp:53
OutputType
Definition: outputtype.h:17
void UpdatePSBTOutput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index)
Updates a PSBTOutput with information from provider.
Definition: psbt.cpp:286
bool SignPSBTInput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index, const PrecomputedTransactionData *txdata, int sighash, SignatureData *out_sigdata, bool finalize)
Signs a PSBTInput, verifying that all provided data matches what is being signed.
Definition: psbt.cpp:323
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed.
Definition: psbt.cpp:270
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.
const char * prefix
Definition: rest.cpp:930
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:24
@ OP_0
Definition: script.h:72
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:385
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:635
const SigningProvider & DUMMY_SIGNING_PROVIDER
CKeyID GetKeyForDestination(const SigningProvider &store, const CTxDestination &dest)
Return the CKeyID of the key involved in a script (if there is a unique one).
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:168
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:237
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:339
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:334
CKeyID ToKeyID(const PKHash &key_hash)
Definition: standard.cpp:31
TxoutType
Definition: standard.h:51
@ WITNESS_V1_TAPROOT
@ WITNESS_UNKNOWN
Only for Witness versions not already defined above.
@ WITNESS_V0_SCRIPTHASH
@ NULL_DATA
unspendable OP_RETURN script that carries data
@ WITNESS_V0_KEYHASH
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:149
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:109
Definition: key.h:161
CExtPubKey Neuter() const
Definition: key.cpp:356
bool Derive(CExtKey &out, unsigned int nChild) const
Definition: key.cpp:335
CKey key
Definition: key.h:166
void SetSeed(Span< const std::byte > seed)
Definition: key.cpp:344
A mutable version of CTransaction.
Definition: transaction.h:373
std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo > > origins
std::map< CKeyID, CPubKey > pubkeys
std::map< CKeyID, CKey > keys
unsigned char fingerprint[4]
First 32 bits of the Hash160 of the public key at the root of the path.
Definition: keyorigin.h:13
std::vector< uint32_t > path
Definition: keyorigin.h:14
A structure for PSBTs which contain per-input information.
Definition: psbt.h:192
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:199
CTransactionRef non_witness_utxo
Definition: psbt.h:193
std::optional< int > sighash_type
Definition: psbt.h:216
void FillSignatureData(SignatureData &sigdata) const
Definition: psbt.cpp:92
std::map< XOnlyPubKey, std::pair< std::set< uint256 >, KeyOriginInfo > > m_tap_bip32_paths
Definition: psbt.h:210
CTxOut witness_utxo
Definition: psbt.h:194
A version of CTransaction with the PSBT format.
Definition: psbt.h:952
std::vector< PSBTInput > inputs
Definition: psbt.h:957
std::optional< CMutableTransaction > tx
Definition: psbt.h:953
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input. May contain all signatures necessary for producing a ...
Definition: sign.h:76
Bilingual messages:
Definition: translation.h:18
struct containing information needed for migrating legacy wallets to descriptor wallets
Definition: walletutil.h:113
std::vector< std::unique_ptr< DescriptorScriptPubKeyMan > > desc_spkms
Definition: walletutil.h:117
std::vector< std::pair< std::string, int64_t > > solvable_descs
Definition: walletutil.h:116
std::vector< std::pair< std::string, int64_t > > watch_descs
Definition: walletutil.h:115
#define LOCK(cs)
Definition: sync.h:261
bool error(const char *fmt, const Args &... args)
Definition: system.h:48
int64_t GetTime()
Definition: time.cpp:115
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:65
bool MessageSign(const CKey &privkey, const std::string &message, std::string &signature)
Sign a message.
Definition: message.cpp:58
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
ArgsManager gArgs
Definition: system.cpp:86
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())