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