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