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