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