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