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