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  txnouttype whichType = Solver(scriptPubKey, vSolutions);
92 
93  CKeyID keyID;
94  switch (whichType)
95  {
96  case TX_NONSTANDARD:
97  case TX_NULL_DATA:
98  case TX_WITNESS_UNKNOWN:
99  break;
100  case TX_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  }
124  case TX_PUBKEYHASH:
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;
136  case TX_SCRIPTHASH:
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 TX_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  CKeyID key_id(pkhash);
577  CKey key;
578  if (!GetKey(key_id, key)) {
580  }
581 
582  if (MessageSign(key, message, str_sig)) {
583  return SigningResult::OK;
584  }
586 }
587 
588 TransactionError LegacyScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, int sighash_type, bool sign, bool bip32derivs) const
589 {
590  for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
591  const CTxIn& txin = psbtx.tx->vin[i];
592  PSBTInput& input = psbtx.inputs.at(i);
593 
594  if (PSBTInputSigned(input)) {
595  continue;
596  }
597 
598  // Verify input looks sane. This will check that we have at most one uxto, witness or non-witness.
599  if (!input.IsSane()) {
601  }
602 
603  // Get the Sighash type
604  if (sign && input.sighash_type > 0 && input.sighash_type != sighash_type) {
606  }
607 
608  // Check non_witness_utxo has specified prevout
609  if (input.non_witness_utxo) {
610  if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
612  }
613  } else if (input.witness_utxo.IsNull()) {
614  // There's no UTXO so we can just skip this now
615  continue;
616  }
617  SignatureData sigdata;
618  input.FillSignatureData(sigdata);
619  SignPSBTInput(HidingSigningProvider(this, !sign, !bip32derivs), psbtx, i, sighash_type);
620  }
621 
622  // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
623  for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
624  UpdatePSBTOutput(HidingSigningProvider(this, true, !bip32derivs), psbtx, i);
625  }
626 
627  return TransactionError::OK;
628 }
629 
630 std::unique_ptr<CKeyMetadata> LegacyScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
631 {
632  LOCK(cs_KeyStore);
633 
634  CKeyID key_id = GetKeyForDestination(*this, dest);
635  if (!key_id.IsNull()) {
636  auto it = mapKeyMetadata.find(key_id);
637  if (it != mapKeyMetadata.end()) {
638  return MakeUnique<CKeyMetadata>(it->second);
639  }
640  }
641 
642  CScript scriptPubKey = GetScriptForDestination(dest);
643  auto it = m_script_metadata.find(CScriptID(scriptPubKey));
644  if (it != m_script_metadata.end()) {
645  return MakeUnique<CKeyMetadata>(it->second);
646  }
647 
648  return nullptr;
649 }
650 
652 {
653  return UINT256_ONE();
654 }
655 
661 {
663  if (nCreateTime <= 1) {
664  // Cannot determine birthday information, so set the wallet birthday to
665  // the beginning of time.
666  nTimeFirstKey = 1;
667  } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
668  nTimeFirstKey = nCreateTime;
669  }
670 }
671 
672 bool LegacyScriptPubKeyMan::LoadKey(const CKey& key, const CPubKey &pubkey)
673 {
674  return AddKeyPubKeyInner(key, pubkey);
675 }
676 
677 bool LegacyScriptPubKeyMan::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
678 {
679  LOCK(cs_KeyStore);
681  return LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(batch, secret, pubkey);
682 }
683 
684 bool LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(WalletBatch& batch, const CKey& secret, const CPubKey& pubkey)
685 {
687 
688  // Make sure we aren't adding private keys to private key disabled wallets
690 
691  // FillableSigningProvider has no concept of wallet databases, but calls AddCryptedKey
692  // which is overridden below. To avoid flushes, the database handle is
693  // tunneled through to it.
694  bool needsDB = !encrypted_batch;
695  if (needsDB) {
696  encrypted_batch = &batch;
697  }
698  if (!AddKeyPubKeyInner(secret, pubkey)) {
699  if (needsDB) encrypted_batch = nullptr;
700  return false;
701  }
702  if (needsDB) encrypted_batch = nullptr;
703 
704  // check if we need to remove from watch-only
705  CScript script;
706  script = GetScriptForDestination(PKHash(pubkey));
707  if (HaveWatchOnly(script)) {
708  RemoveWatchOnly(script);
709  }
710  script = GetScriptForRawPubKey(pubkey);
711  if (HaveWatchOnly(script)) {
712  RemoveWatchOnly(script);
713  }
714 
715  if (!m_storage.HasEncryptionKeys()) {
716  return batch.WriteKey(pubkey,
717  secret.GetPrivKey(),
718  mapKeyMetadata[pubkey.GetID()]);
719  }
721  return true;
722 }
723 
725 {
726  /* A sanity check was added in pull #3843 to avoid adding redeemScripts
727  * that never can be redeemed. However, old wallets may still contain
728  * these. Do not add them to the wallet and warn. */
729  if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
730  {
731  std::string strAddr = EncodeDestination(ScriptHash(redeemScript));
732  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);
733  return true;
734  }
735 
736  return FillableSigningProvider::AddCScript(redeemScript);
737 }
738 
740 {
741  LOCK(cs_KeyStore);
743  mapKeyMetadata[keyID] = meta;
744 }
745 
747 {
748  LOCK(cs_KeyStore);
750  m_script_metadata[script_id] = meta;
751 }
752 
754 {
755  LOCK(cs_KeyStore);
756  if (!m_storage.HasEncryptionKeys()) {
757  return FillableSigningProvider::AddKeyPubKey(key, pubkey);
758  }
759 
760  if (m_storage.IsLocked()) {
761  return false;
762  }
763 
764  std::vector<unsigned char> vchCryptedSecret;
765  CKeyingMaterial vchSecret(key.begin(), key.end());
766  if (!EncryptSecret(m_storage.GetEncryptionKey(), vchSecret, pubkey.GetHash(), vchCryptedSecret)) {
767  return false;
768  }
769 
770  if (!AddCryptedKey(pubkey, vchCryptedSecret)) {
771  return false;
772  }
773  return true;
774 }
775 
776 bool LegacyScriptPubKeyMan::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid)
777 {
778  // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
779  if (!checksum_valid) {
781  }
782 
783  return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
784 }
785 
786 bool LegacyScriptPubKeyMan::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
787 {
788  LOCK(cs_KeyStore);
789  assert(mapKeys.empty());
790 
791  mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
793  return true;
794 }
795 
797  const std::vector<unsigned char> &vchCryptedSecret)
798 {
799  if (!AddCryptedKeyInner(vchPubKey, vchCryptedSecret))
800  return false;
801  {
802  LOCK(cs_KeyStore);
803  if (encrypted_batch)
804  return encrypted_batch->WriteCryptedKey(vchPubKey,
805  vchCryptedSecret,
806  mapKeyMetadata[vchPubKey.GetID()]);
807  else
808  return WalletBatch(m_storage.GetDatabase()).WriteCryptedKey(vchPubKey,
809  vchCryptedSecret,
810  mapKeyMetadata[vchPubKey.GetID()]);
811  }
812 }
813 
815 {
816  LOCK(cs_KeyStore);
817  return setWatchOnly.count(dest) > 0;
818 }
819 
821 {
822  LOCK(cs_KeyStore);
823  return (!setWatchOnly.empty());
824 }
825 
826 static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
827 {
828  std::vector<std::vector<unsigned char>> solutions;
829  return Solver(dest, solutions) == TX_PUBKEY &&
830  (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
831 }
832 
834 {
835  {
836  LOCK(cs_KeyStore);
837  setWatchOnly.erase(dest);
838  CPubKey pubKey;
839  if (ExtractPubKey(dest, pubKey)) {
840  mapWatchKeys.erase(pubKey.GetID());
841  }
842  // Related CScripts are not removed; having superfluous scripts around is
843  // harmless (see comment in ImplicitlyLearnRelatedKeyScripts).
844  }
845 
846  if (!HaveWatchOnly())
847  NotifyWatchonlyChanged(false);
848  if (!WalletBatch(m_storage.GetDatabase()).EraseWatchOnly(dest))
849  return false;
850 
851  return true;
852 }
853 
855 {
856  return AddWatchOnlyInMem(dest);
857 }
858 
860 {
861  LOCK(cs_KeyStore);
862  setWatchOnly.insert(dest);
863  CPubKey pubKey;
864  if (ExtractPubKey(dest, pubKey)) {
865  mapWatchKeys[pubKey.GetID()] = pubKey;
867  }
868  return true;
869 }
870 
872 {
873  if (!AddWatchOnlyInMem(dest))
874  return false;
875  const CKeyMetadata& meta = m_script_metadata[CScriptID(dest)];
878  if (batch.WriteWatchOnly(dest, meta)) {
880  return true;
881  }
882  return false;
883 }
884 
885 bool LegacyScriptPubKeyMan::AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest, int64_t create_time)
886 {
887  m_script_metadata[CScriptID(dest)].nCreateTime = create_time;
888  return AddWatchOnlyWithDB(batch, dest);
889 }
890 
892 {
894  return AddWatchOnlyWithDB(batch, dest);
895 }
896 
897 bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
898 {
899  m_script_metadata[CScriptID(dest)].nCreateTime = nCreateTime;
900  return AddWatchOnly(dest);
901 }
902 
903 void LegacyScriptPubKeyMan::SetHDChain(const CHDChain& chain, bool memonly)
904 {
905  LOCK(cs_KeyStore);
906  // memonly == true means we are loading the wallet file
907  // memonly == false means that the chain is actually being changed
908  if (!memonly) {
909  // Store the new chain
910  if (!WalletBatch(m_storage.GetDatabase()).WriteHDChain(chain)) {
911  throw std::runtime_error(std::string(__func__) + ": writing chain failed");
912  }
913  // When there's an old chain, add it as an inactive chain as we are now rotating hd chains
914  if (!m_hd_chain.seed_id.IsNull()) {
916  }
917  }
918 
919  m_hd_chain = chain;
920 }
921 
923 {
924  LOCK(cs_KeyStore);
925  assert(!chain.seed_id.IsNull());
926  m_inactive_hd_chains[chain.seed_id] = chain;
927 }
928 
929 bool LegacyScriptPubKeyMan::HaveKey(const CKeyID &address) const
930 {
931  LOCK(cs_KeyStore);
932  if (!m_storage.HasEncryptionKeys()) {
933  return FillableSigningProvider::HaveKey(address);
934  }
935  return mapCryptedKeys.count(address) > 0;
936 }
937 
938 bool LegacyScriptPubKeyMan::GetKey(const CKeyID &address, CKey& keyOut) const
939 {
940  LOCK(cs_KeyStore);
941  if (!m_storage.HasEncryptionKeys()) {
942  return FillableSigningProvider::GetKey(address, keyOut);
943  }
944 
945  CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
946  if (mi != mapCryptedKeys.end())
947  {
948  const CPubKey &vchPubKey = (*mi).second.first;
949  const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
950  return DecryptKey(m_storage.GetEncryptionKey(), vchCryptedSecret, vchPubKey, keyOut);
951  }
952  return false;
953 }
954 
956 {
957  CKeyMetadata meta;
958  {
959  LOCK(cs_KeyStore);
960  auto it = mapKeyMetadata.find(keyID);
961  if (it != mapKeyMetadata.end()) {
962  meta = it->second;
963  }
964  }
965  if (meta.has_key_origin) {
966  std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4, info.fingerprint);
967  info.path = meta.key_origin.path;
968  } else { // Single pubkeys get the master fingerprint of themselves
969  std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
970  }
971  return true;
972 }
973 
974 bool LegacyScriptPubKeyMan::GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
975 {
976  LOCK(cs_KeyStore);
977  WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
978  if (it != mapWatchKeys.end()) {
979  pubkey_out = it->second;
980  return true;
981  }
982  return false;
983 }
984 
985 bool LegacyScriptPubKeyMan::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
986 {
987  LOCK(cs_KeyStore);
988  if (!m_storage.HasEncryptionKeys()) {
989  if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
990  return GetWatchPubKey(address, vchPubKeyOut);
991  }
992  return true;
993  }
994 
995  CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
996  if (mi != mapCryptedKeys.end())
997  {
998  vchPubKeyOut = (*mi).second.first;
999  return true;
1000  }
1001  // Check for watch-only pubkeys
1002  return GetWatchPubKey(address, vchPubKeyOut);
1003 }
1004 
1006 {
1010  bool fCompressed = m_storage.CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
1011 
1012  CKey secret;
1013 
1014  // Create new metadata
1015  int64_t nCreationTime = GetTime();
1016  CKeyMetadata metadata(nCreationTime);
1017 
1018  // use HD key derivation if HD was enabled during wallet creation and a seed is present
1019  if (IsHDEnabled()) {
1020  DeriveNewChildKey(batch, metadata, secret, hd_chain, (m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
1021  } else {
1022  secret.MakeNewKey(fCompressed);
1023  }
1024 
1025  // Compressed public keys were introduced in version 0.6.0
1026  if (fCompressed) {
1028  }
1029 
1030  CPubKey pubkey = secret.GetPubKey();
1031  assert(secret.VerifyPubKey(pubkey));
1032 
1033  mapKeyMetadata[pubkey.GetID()] = metadata;
1034  UpdateTimeFirstKey(nCreationTime);
1035 
1036  if (!AddKeyPubKeyWithDB(batch, secret, pubkey)) {
1037  throw std::runtime_error(std::string(__func__) + ": AddKey failed");
1038  }
1039  return pubkey;
1040 }
1041 
1042 void LegacyScriptPubKeyMan::DeriveNewChildKey(WalletBatch &batch, CKeyMetadata& metadata, CKey& secret, CHDChain& hd_chain, bool internal)
1043 {
1044  // for now we use a fixed keypath scheme of m/0'/0'/k
1045  CKey seed; //seed (256bit)
1046  CExtKey masterKey; //hd master key
1047  CExtKey accountKey; //key at m/0'
1048  CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
1049  CExtKey childKey; //key at m/0'/0'/<n>'
1050 
1051  // try to get the seed
1052  if (!GetKey(hd_chain.seed_id, seed))
1053  throw std::runtime_error(std::string(__func__) + ": seed not found");
1054 
1055  masterKey.SetSeed(seed.begin(), seed.size());
1056 
1057  // derive m/0'
1058  // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
1059  masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
1060 
1061  // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
1062  assert(internal ? m_storage.CanSupportFeature(FEATURE_HD_SPLIT) : true);
1063  accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
1064 
1065  // derive child key at next index, skip keys already known to the wallet
1066  do {
1067  // always derive hardened keys
1068  // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
1069  // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
1070  if (internal) {
1071  chainChildKey.Derive(childKey, hd_chain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
1072  metadata.hdKeypath = "m/0'/1'/" + ToString(hd_chain.nInternalChainCounter) + "'";
1073  metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1074  metadata.key_origin.path.push_back(1 | BIP32_HARDENED_KEY_LIMIT);
1075  metadata.key_origin.path.push_back(hd_chain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
1076  hd_chain.nInternalChainCounter++;
1077  }
1078  else {
1079  chainChildKey.Derive(childKey, hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
1080  metadata.hdKeypath = "m/0'/0'/" + ToString(hd_chain.nExternalChainCounter) + "'";
1081  metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1082  metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1083  metadata.key_origin.path.push_back(hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
1084  hd_chain.nExternalChainCounter++;
1085  }
1086  } while (HaveKey(childKey.key.GetPubKey().GetID()));
1087  secret = childKey.key;
1088  metadata.hd_seed_id = hd_chain.seed_id;
1089  CKeyID master_id = masterKey.key.GetPubKey().GetID();
1090  std::copy(master_id.begin(), master_id.begin() + 4, metadata.key_origin.fingerprint);
1091  metadata.has_key_origin = true;
1092  // update the chain model in the database
1093  if (hd_chain.seed_id == m_hd_chain.seed_id && !batch.WriteHDChain(hd_chain))
1094  throw std::runtime_error(std::string(__func__) + ": writing HD chain model failed");
1095 }
1096 
1097 void LegacyScriptPubKeyMan::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
1098 {
1099  LOCK(cs_KeyStore);
1100  if (keypool.m_pre_split) {
1101  set_pre_split_keypool.insert(nIndex);
1102  } else if (keypool.fInternal) {
1103  setInternalKeyPool.insert(nIndex);
1104  } else {
1105  setExternalKeyPool.insert(nIndex);
1106  }
1107  m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
1108  m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
1109 
1110  // If no metadata exists yet, create a default with the pool key's
1111  // creation time. Note that this may be overwritten by actually
1112  // stored metadata for that key later, which is fine.
1113  CKeyID keyid = keypool.vchPubKey.GetID();
1114  if (mapKeyMetadata.count(keyid) == 0)
1115  mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
1116 }
1117 
1119 {
1120  // A wallet can generate keys if it has an HD seed (IsHDEnabled) or it is a non-HD wallet (pre FEATURE_HD)
1121  LOCK(cs_KeyStore);
1123 }
1124 
1126 {
1128  CKey key;
1129  key.MakeNewKey(true);
1130  return DeriveNewSeed(key);
1131 }
1132 
1134 {
1135  int64_t nCreationTime = GetTime();
1136  CKeyMetadata metadata(nCreationTime);
1137 
1138  // calculate the seed
1139  CPubKey seed = key.GetPubKey();
1140  assert(key.VerifyPubKey(seed));
1141 
1142  // set the hd keypath to "s" -> Seed, refers the seed to itself
1143  metadata.hdKeypath = "s";
1144  metadata.has_key_origin = false;
1145  metadata.hd_seed_id = seed.GetID();
1146 
1147  {
1148  LOCK(cs_KeyStore);
1149 
1150  // mem store the metadata
1151  mapKeyMetadata[seed.GetID()] = metadata;
1152 
1153  // write the key&metadata to the database
1154  if (!AddKeyPubKey(key, seed))
1155  throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1156  }
1157 
1158  return seed;
1159 }
1160 
1162 {
1163  LOCK(cs_KeyStore);
1164  // store the keyid (hash160) together with
1165  // the child index counter in the database
1166  // as a hdchain object
1167  CHDChain newHdChain;
1169  newHdChain.seed_id = seed.GetID();
1170  SetHDChain(newHdChain, false);
1174 }
1175 
1181 {
1183  return false;
1184  }
1185  {
1186  LOCK(cs_KeyStore);
1188 
1189  for (const int64_t nIndex : setInternalKeyPool) {
1190  batch.ErasePool(nIndex);
1191  }
1192  setInternalKeyPool.clear();
1193 
1194  for (const int64_t nIndex : setExternalKeyPool) {
1195  batch.ErasePool(nIndex);
1196  }
1197  setExternalKeyPool.clear();
1198 
1199  for (const int64_t nIndex : set_pre_split_keypool) {
1200  batch.ErasePool(nIndex);
1201  }
1202  set_pre_split_keypool.clear();
1203 
1204  m_pool_key_to_index.clear();
1205 
1206  if (!TopUp()) {
1207  return false;
1208  }
1209  WalletLogPrintf("LegacyScriptPubKeyMan::NewKeyPool rewrote keypool\n");
1210  }
1211  return true;
1212 }
1213 
1214 bool LegacyScriptPubKeyMan::TopUp(unsigned int kpSize)
1215 {
1216  if (!CanGenerateKeys()) {
1217  return false;
1218  }
1219  {
1220  LOCK(cs_KeyStore);
1221 
1222  if (m_storage.IsLocked()) return false;
1223 
1224  // Top up key pool
1225  unsigned int nTargetSize;
1226  if (kpSize > 0)
1227  nTargetSize = kpSize;
1228  else
1229  nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
1230 
1231  // count amount of available keys (internal, external)
1232  // make sure the keypool of external and internal keys fits the user selected target (-keypool)
1233  int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
1234  int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
1235 
1237  {
1238  // don't create extra internal keys
1239  missingInternal = 0;
1240  }
1241  bool internal = false;
1243  for (int64_t i = missingInternal + missingExternal; i--;)
1244  {
1245  if (i < missingInternal) {
1246  internal = true;
1247  }
1248 
1249  CPubKey pubkey(GenerateNewKey(batch, m_hd_chain, internal));
1250  AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1251  }
1252  if (missingInternal + missingExternal > 0) {
1253  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());
1254  }
1255  }
1257  return true;
1258 }
1259 
1260 void LegacyScriptPubKeyMan::AddKeypoolPubkeyWithDB(const CPubKey& pubkey, const bool internal, WalletBatch& batch)
1261 {
1262  LOCK(cs_KeyStore);
1263  assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
1264  int64_t index = ++m_max_keypool_index;
1265  if (!batch.WritePool(index, CKeyPool(pubkey, internal))) {
1266  throw std::runtime_error(std::string(__func__) + ": writing imported pubkey failed");
1267  }
1268  if (internal) {
1269  setInternalKeyPool.insert(index);
1270  } else {
1271  setExternalKeyPool.insert(index);
1272  }
1273  m_pool_key_to_index[pubkey.GetID()] = index;
1274 }
1275 
1276 void LegacyScriptPubKeyMan::KeepDestination(int64_t nIndex, const OutputType& type)
1277 {
1278  // Remove from key pool
1280  batch.ErasePool(nIndex);
1281  CPubKey pubkey;
1282  bool have_pk = GetPubKey(m_index_to_reserved_key.at(nIndex), pubkey);
1283  assert(have_pk);
1284  LearnRelatedScripts(pubkey, type);
1285  m_index_to_reserved_key.erase(nIndex);
1286  WalletLogPrintf("keypool keep %d\n", nIndex);
1287 }
1288 
1289 void LegacyScriptPubKeyMan::ReturnDestination(int64_t nIndex, bool fInternal, const CTxDestination&)
1290 {
1291  // Return to key pool
1292  {
1293  LOCK(cs_KeyStore);
1294  if (fInternal) {
1295  setInternalKeyPool.insert(nIndex);
1296  } else if (!set_pre_split_keypool.empty()) {
1297  set_pre_split_keypool.insert(nIndex);
1298  } else {
1299  setExternalKeyPool.insert(nIndex);
1300  }
1301  CKeyID& pubkey_id = m_index_to_reserved_key.at(nIndex);
1302  m_pool_key_to_index[pubkey_id] = nIndex;
1303  m_index_to_reserved_key.erase(nIndex);
1305  }
1306  WalletLogPrintf("keypool return %d\n", nIndex);
1307 }
1308 
1309 bool LegacyScriptPubKeyMan::GetKeyFromPool(CPubKey& result, const OutputType type, bool internal)
1310 {
1311  if (!CanGetAddresses(internal)) {
1312  return false;
1313  }
1314 
1315  CKeyPool keypool;
1316  {
1317  LOCK(cs_KeyStore);
1318  int64_t nIndex;
1320  if (m_storage.IsLocked()) return false;
1322  result = GenerateNewKey(batch, m_hd_chain, internal);
1323  return true;
1324  }
1325  KeepDestination(nIndex, type);
1326  result = keypool.vchPubKey;
1327  }
1328  return true;
1329 }
1330 
1331 bool LegacyScriptPubKeyMan::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
1332 {
1333  nIndex = -1;
1334  keypool.vchPubKey = CPubKey();
1335  {
1336  LOCK(cs_KeyStore);
1337 
1338  bool fReturningInternal = fRequestedInternal;
1340  bool use_split_keypool = set_pre_split_keypool.empty();
1341  std::set<int64_t>& setKeyPool = use_split_keypool ? (fReturningInternal ? setInternalKeyPool : setExternalKeyPool) : set_pre_split_keypool;
1342 
1343  // Get the oldest key
1344  if (setKeyPool.empty()) {
1345  return false;
1346  }
1347 
1349 
1350  auto it = setKeyPool.begin();
1351  nIndex = *it;
1352  setKeyPool.erase(it);
1353  if (!batch.ReadPool(nIndex, keypool)) {
1354  throw std::runtime_error(std::string(__func__) + ": read failed");
1355  }
1356  CPubKey pk;
1357  if (!GetPubKey(keypool.vchPubKey.GetID(), pk)) {
1358  throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
1359  }
1360  // If the key was pre-split keypool, we don't care about what type it is
1361  if (use_split_keypool && keypool.fInternal != fReturningInternal) {
1362  throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
1363  }
1364  if (!keypool.vchPubKey.IsValid()) {
1365  throw std::runtime_error(std::string(__func__) + ": keypool entry invalid");
1366  }
1367 
1368  assert(m_index_to_reserved_key.count(nIndex) == 0);
1369  m_index_to_reserved_key[nIndex] = keypool.vchPubKey.GetID();
1370  m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1371  WalletLogPrintf("keypool reserve %d\n", nIndex);
1372  }
1374  return true;
1375 }
1376 
1378 {
1379  if (key.IsCompressed() && (type == OutputType::P2SH_SEGWIT || type == OutputType::BECH32)) {
1380  CTxDestination witdest = WitnessV0KeyHash(key.GetID());
1381  CScript witprog = GetScriptForDestination(witdest);
1382  // Make sure the resulting program is solvable.
1383  assert(IsSolvable(*this, witprog));
1384  AddCScript(witprog);
1385  }
1386 }
1387 
1389 {
1390  // OutputType::P2SH_SEGWIT always adds all necessary scripts for all types.
1392 }
1393 
1395 {
1397  bool internal = setInternalKeyPool.count(keypool_id);
1398  if (!internal) assert(setExternalKeyPool.count(keypool_id) || set_pre_split_keypool.count(keypool_id));
1399  std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : (set_pre_split_keypool.empty() ? &setExternalKeyPool : &set_pre_split_keypool);
1400  auto it = setKeyPool->begin();
1401 
1403  while (it != std::end(*setKeyPool)) {
1404  const int64_t& index = *(it);
1405  if (index > keypool_id) break; // set*KeyPool is ordered
1406 
1407  CKeyPool keypool;
1408  if (batch.ReadPool(index, keypool)) { //TODO: This should be unnecessary
1409  m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1410  }
1412  batch.ErasePool(index);
1413  WalletLogPrintf("keypool index %d removed\n", index);
1414  it = setKeyPool->erase(it);
1415  }
1416 }
1417 
1418 std::vector<CKeyID> GetAffectedKeys(const CScript& spk, const SigningProvider& provider)
1419 {
1420  std::vector<CScript> dummy;
1421  FlatSigningProvider out;
1422  InferDescriptor(spk, provider)->Expand(0, DUMMY_SIGNING_PROVIDER, dummy, out);
1423  std::vector<CKeyID> ret;
1424  for (const auto& entry : out.pubkeys) {
1425  ret.push_back(entry.first);
1426  }
1427  return ret;
1428 }
1429 
1431 {
1433  for (auto it = setExternalKeyPool.begin(); it != setExternalKeyPool.end();) {
1434  int64_t index = *it;
1435  CKeyPool keypool;
1436  if (!batch.ReadPool(index, keypool)) {
1437  throw std::runtime_error(std::string(__func__) + ": read keypool entry failed");
1438  }
1439  keypool.m_pre_split = true;
1440  if (!batch.WritePool(index, keypool)) {
1441  throw std::runtime_error(std::string(__func__) + ": writing modified keypool entry failed");
1442  }
1443  set_pre_split_keypool.insert(index);
1444  it = setExternalKeyPool.erase(it);
1445  }
1446 }
1447 
1449 {
1451  return AddCScriptWithDB(batch, redeemScript);
1452 }
1453 
1455 {
1456  if (!FillableSigningProvider::AddCScript(redeemScript))
1457  return false;
1458  if (batch.WriteCScript(Hash160(redeemScript), redeemScript)) {
1460  return true;
1461  }
1462  return false;
1463 }
1464 
1466 {
1467  LOCK(cs_KeyStore);
1468  std::copy(info.fingerprint, info.fingerprint + 4, mapKeyMetadata[pubkey.GetID()].key_origin.fingerprint);
1469  mapKeyMetadata[pubkey.GetID()].key_origin.path = info.path;
1470  mapKeyMetadata[pubkey.GetID()].has_key_origin = true;
1471  mapKeyMetadata[pubkey.GetID()].hdKeypath = WriteHDKeypath(info.path);
1472  return batch.WriteKeyMetadata(mapKeyMetadata[pubkey.GetID()], pubkey, true);
1473 }
1474 
1475 bool LegacyScriptPubKeyMan::ImportScripts(const std::set<CScript> scripts, int64_t timestamp)
1476 {
1478  for (const auto& entry : scripts) {
1479  CScriptID id(entry);
1480  if (HaveCScript(id)) {
1481  WalletLogPrintf("Already have script %s, skipping\n", HexStr(entry));
1482  continue;
1483  }
1484  if (!AddCScriptWithDB(batch, entry)) {
1485  return false;
1486  }
1487 
1488  if (timestamp > 0) {
1489  m_script_metadata[CScriptID(entry)].nCreateTime = timestamp;
1490  }
1491  }
1492  if (timestamp > 0) {
1493  UpdateTimeFirstKey(timestamp);
1494  }
1495 
1496  return true;
1497 }
1498 
1499 bool LegacyScriptPubKeyMan::ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp)
1500 {
1502  for (const auto& entry : privkey_map) {
1503  const CKey& key = entry.second;
1504  CPubKey pubkey = key.GetPubKey();
1505  const CKeyID& id = entry.first;
1506  assert(key.VerifyPubKey(pubkey));
1507  // Skip if we already have the key
1508  if (HaveKey(id)) {
1509  WalletLogPrintf("Already have key with pubkey %s, skipping\n", HexStr(pubkey));
1510  continue;
1511  }
1512  mapKeyMetadata[id].nCreateTime = timestamp;
1513  // If the private key is not present in the wallet, insert it.
1514  if (!AddKeyPubKeyWithDB(batch, key, pubkey)) {
1515  return false;
1516  }
1517  UpdateTimeFirstKey(timestamp);
1518  }
1519  return true;
1520 }
1521 
1522 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)
1523 {
1525  for (const auto& entry : key_origins) {
1526  AddKeyOriginWithDB(batch, entry.second.first, entry.second.second);
1527  }
1528  for (const CKeyID& id : ordered_pubkeys) {
1529  auto entry = pubkey_map.find(id);
1530  if (entry == pubkey_map.end()) {
1531  continue;
1532  }
1533  const CPubKey& pubkey = entry->second;
1534  CPubKey temp;
1535  if (GetPubKey(id, temp)) {
1536  // Already have pubkey, skipping
1537  WalletLogPrintf("Already have pubkey %s, skipping\n", HexStr(temp));
1538  continue;
1539  }
1540  if (!AddWatchOnlyWithDB(batch, GetScriptForRawPubKey(pubkey), timestamp)) {
1541  return false;
1542  }
1543  mapKeyMetadata[id].nCreateTime = timestamp;
1544 
1545  // Add to keypool only works with pubkeys
1546  if (add_keypool) {
1547  AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1549  }
1550  }
1551  return true;
1552 }
1553 
1554 bool LegacyScriptPubKeyMan::ImportScriptPubKeys(const std::set<CScript>& script_pub_keys, const bool have_solving_data, const int64_t timestamp)
1555 {
1557  for (const CScript& script : script_pub_keys) {
1558  if (!have_solving_data || !IsMine(script)) { // Always call AddWatchOnly for non-solvable watch-only, so that watch timestamp gets updated
1559  if (!AddWatchOnlyWithDB(batch, script, timestamp)) {
1560  return false;
1561  }
1562  }
1563  }
1564  return true;
1565 }
1566 
1567 std::set<CKeyID> LegacyScriptPubKeyMan::GetKeys() const
1568 {
1569  LOCK(cs_KeyStore);
1570  if (!m_storage.HasEncryptionKeys()) {
1572  }
1573  std::set<CKeyID> set_address;
1574  for (const auto& mi : mapCryptedKeys) {
1575  set_address.insert(mi.first);
1576  }
1577  return set_address;
1578 }
1579 
1581 
1583 {
1584  // Returns true if this descriptor supports getting new addresses. Conditions where we may be unable to fetch them (e.g. locked) are caught later
1585  if (!CanGetAddresses(m_internal)) {
1586  error = "No addresses available";
1587  return false;
1588  }
1589  {
1590  LOCK(cs_desc_man);
1591  assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
1592  Optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
1593  assert(desc_addr_type);
1594  if (type != *desc_addr_type) {
1595  throw std::runtime_error(std::string(__func__) + ": Types are inconsistent");
1596  }
1597 
1598  TopUp();
1599 
1600  // Get the scriptPubKey from the descriptor
1601  FlatSigningProvider out_keys;
1602  std::vector<CScript> scripts_temp;
1603  if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
1604  // We can't generate anymore keys
1605  error = "Error: Keypool ran out, please call keypoolrefill first";
1606  return false;
1607  }
1608  if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1609  // We can't generate anymore keys
1610  error = "Error: Keypool ran out, please call keypoolrefill first";
1611  return false;
1612  }
1613 
1614  Optional<OutputType> out_script_type = m_wallet_descriptor.descriptor->GetOutputType();
1615  if (out_script_type && out_script_type == type) {
1616  ExtractDestination(scripts_temp[0], dest);
1617  } else {
1618  throw std::runtime_error(std::string(__func__) + ": Types are inconsistent. Stored type does not match type of newly generated address");
1619  }
1620  m_wallet_descriptor.next_index++;
1621  WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
1622  return true;
1623  }
1624 }
1625 
1627 {
1628  LOCK(cs_desc_man);
1629  if (m_map_script_pub_keys.count(script) > 0) {
1630  return ISMINE_SPENDABLE;
1631  }
1632  return ISMINE_NO;
1633 }
1634 
1635 bool DescriptorScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key, bool accept_no_keys)
1636 {
1637  LOCK(cs_desc_man);
1638  if (!m_map_keys.empty()) {
1639  return false;
1640  }
1641 
1642  bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
1643  bool keyFail = false;
1644  for (const auto& mi : m_map_crypted_keys) {
1645  const CPubKey &pubkey = mi.second.first;
1646  const std::vector<unsigned char> &crypted_secret = mi.second.second;
1647  CKey key;
1648  if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
1649  keyFail = true;
1650  break;
1651  }
1652  keyPass = true;
1653  if (m_decryption_thoroughly_checked)
1654  break;
1655  }
1656  if (keyPass && keyFail) {
1657  LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
1658  throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
1659  }
1660  if (keyFail || (!keyPass && !accept_no_keys)) {
1661  return false;
1662  }
1663  m_decryption_thoroughly_checked = true;
1664  return true;
1665 }
1666 
1668 {
1669  LOCK(cs_desc_man);
1670  if (!m_map_crypted_keys.empty()) {
1671  return false;
1672  }
1673 
1674  for (const KeyMap::value_type& key_in : m_map_keys)
1675  {
1676  const CKey &key = key_in.second;
1677  CPubKey pubkey = key.GetPubKey();
1678  CKeyingMaterial secret(key.begin(), key.end());
1679  std::vector<unsigned char> crypted_secret;
1680  if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
1681  return false;
1682  }
1683  m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1684  batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1685  }
1686  m_map_keys.clear();
1687  return true;
1688 }
1689 
1690 bool DescriptorScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, CTxDestination& address, int64_t& index, CKeyPool& keypool)
1691 {
1692  LOCK(cs_desc_man);
1693  std::string error;
1694  bool result = GetNewDestination(type, address, error);
1695  index = m_wallet_descriptor.next_index - 1;
1696  return result;
1697 }
1698 
1699 void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
1700 {
1701  LOCK(cs_desc_man);
1702  // Only return when the index was the most recent
1703  if (m_wallet_descriptor.next_index - 1 == index) {
1704  m_wallet_descriptor.next_index--;
1705  }
1706  WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
1708 }
1709 
1710 std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
1711 {
1712  AssertLockHeld(cs_desc_man);
1714  KeyMap keys;
1715  for (auto key_pair : m_map_crypted_keys) {
1716  const CPubKey& pubkey = key_pair.second.first;
1717  const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
1718  CKey key;
1719  DecryptKey(m_storage.GetEncryptionKey(), crypted_secret, pubkey, key);
1720  keys[pubkey.GetID()] = key;
1721  }
1722  return keys;
1723  }
1724  return m_map_keys;
1725 }
1726 
1727 bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
1728 {
1729  LOCK(cs_desc_man);
1730  unsigned int target_size;
1731  if (size > 0) {
1732  target_size = size;
1733  } else {
1734  target_size = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 1);
1735  }
1736 
1737  // Calculate the new range_end
1738  int32_t new_range_end = std::max(m_wallet_descriptor.next_index + (int32_t)target_size, m_wallet_descriptor.range_end);
1739 
1740  // If the descriptor is not ranged, we actually just want to fill the first cache item
1741  if (!m_wallet_descriptor.descriptor->IsRange()) {
1742  new_range_end = 1;
1743  m_wallet_descriptor.range_end = 1;
1744  m_wallet_descriptor.range_start = 0;
1745  }
1746 
1747  FlatSigningProvider provider;
1748  provider.keys = GetKeys();
1749 
1751  uint256 id = GetID();
1752  for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
1753  FlatSigningProvider out_keys;
1754  std::vector<CScript> scripts_temp;
1755  DescriptorCache temp_cache;
1756  // Maybe we have a cached xpub and we can expand from the cache first
1757  if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1758  if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
1759  }
1760  // Add all of the scriptPubKeys to the scriptPubKey set
1761  for (const CScript& script : scripts_temp) {
1762  m_map_script_pub_keys[script] = i;
1763  }
1764  for (const auto& pk_pair : out_keys.pubkeys) {
1765  const CPubKey& pubkey = pk_pair.second;
1766  if (m_map_pubkeys.count(pubkey) != 0) {
1767  // We don't need to give an error here.
1768  // 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
1769  continue;
1770  }
1771  m_map_pubkeys[pubkey] = i;
1772  }
1773  // Write the cache
1774  for (const auto& parent_xpub_pair : temp_cache.GetCachedParentExtPubKeys()) {
1775  CExtPubKey xpub;
1776  if (m_wallet_descriptor.cache.GetCachedParentExtPubKey(parent_xpub_pair.first, xpub)) {
1777  if (xpub != parent_xpub_pair.second) {
1778  throw std::runtime_error(std::string(__func__) + ": New cached parent xpub does not match already cached parent xpub");
1779  }
1780  continue;
1781  }
1782  if (!batch.WriteDescriptorParentCache(parent_xpub_pair.second, id, parent_xpub_pair.first)) {
1783  throw std::runtime_error(std::string(__func__) + ": writing cache item failed");
1784  }
1785  m_wallet_descriptor.cache.CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
1786  }
1787  for (const auto& derived_xpub_map_pair : temp_cache.GetCachedDerivedExtPubKeys()) {
1788  for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
1789  CExtPubKey xpub;
1790  if (m_wallet_descriptor.cache.GetCachedDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, xpub)) {
1791  if (xpub != derived_xpub_pair.second) {
1792  throw std::runtime_error(std::string(__func__) + ": New cached derived xpub does not match already cached derived xpub");
1793  }
1794  continue;
1795  }
1796  if (!batch.WriteDescriptorDerivedCache(derived_xpub_pair.second, id, derived_xpub_map_pair.first, derived_xpub_pair.first)) {
1797  throw std::runtime_error(std::string(__func__) + ": writing cache item failed");
1798  }
1799  m_wallet_descriptor.cache.CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
1800  }
1801  }
1802  m_max_cached_index++;
1803  }
1804  m_wallet_descriptor.range_end = new_range_end;
1805  batch.WriteDescriptor(GetID(), m_wallet_descriptor);
1806 
1807  // By this point, the cache size should be the size of the entire range
1808  assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
1809 
1811  return true;
1812 }
1813 
1815 {
1816  LOCK(cs_desc_man);
1817  if (IsMine(script)) {
1818  int32_t index = m_map_script_pub_keys[script];
1819  if (index >= m_wallet_descriptor.next_index) {
1820  WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
1821  m_wallet_descriptor.next_index = index + 1;
1822  }
1823  if (!TopUp()) {
1824  WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1825  }
1826  }
1827 }
1828 
1830 {
1831  LOCK(cs_desc_man);
1833  if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
1834  throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
1835  }
1836 }
1837 
1839 {
1840  AssertLockHeld(cs_desc_man);
1842 
1843  if (m_storage.HasEncryptionKeys()) {
1844  if (m_storage.IsLocked()) {
1845  return false;
1846  }
1847 
1848  std::vector<unsigned char> crypted_secret;
1849  CKeyingMaterial secret(key.begin(), key.end());
1850  if (!EncryptSecret(m_storage.GetEncryptionKey(), secret, pubkey.GetHash(), crypted_secret)) {
1851  return false;
1852  }
1853 
1854  m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1855  return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1856  } else {
1857  m_map_keys[pubkey.GetID()] = key;
1858  return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
1859  }
1860 }
1861 
1863 {
1864  LOCK(cs_desc_man);
1866 
1867  // Ignore when there is already a descriptor
1868  if (m_wallet_descriptor.descriptor) {
1869  return false;
1870  }
1871 
1872  int64_t creation_time = GetTime();
1873 
1874  std::string xpub = EncodeExtPubKey(master_key.Neuter());
1875 
1876  // Build descriptor string
1877  std::string desc_prefix;
1878  std::string desc_suffix = "/*)";
1879  switch (addr_type) {
1880  case OutputType::LEGACY: {
1881  desc_prefix = "pkh(" + xpub + "/44'";
1882  break;
1883  }
1884  case OutputType::P2SH_SEGWIT: {
1885  desc_prefix = "sh(wpkh(" + xpub + "/49'";
1886  desc_suffix += ")";
1887  break;
1888  }
1889  case OutputType::BECH32: {
1890  desc_prefix = "wpkh(" + xpub + "/84'";
1891  break;
1892  }
1893  default: assert(false);
1894  }
1895 
1896  // Mainnet derives at 0', testnet and regtest derive at 1'
1897  if (Params().IsTestChain()) {
1898  desc_prefix += "/1'";
1899  } else {
1900  desc_prefix += "/0'";
1901  }
1902 
1903  std::string internal_path = m_internal ? "/1" : "/0";
1904  std::string desc_str = desc_prefix + "/0'" + internal_path + desc_suffix;
1905 
1906  // Make the descriptor
1907  FlatSigningProvider keys;
1908  std::string error;
1909  std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, error, false);
1910  WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
1911  m_wallet_descriptor = w_desc;
1912 
1913  // Store the master private key, and descriptor
1915  if (!AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey())) {
1916  throw std::runtime_error(std::string(__func__) + ": writing descriptor master private key failed");
1917  }
1918  if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
1919  throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
1920  }
1921 
1922  // TopUp
1923  TopUp();
1924 
1926  return true;
1927 }
1928 
1930 {
1931  LOCK(cs_desc_man);
1932  return m_wallet_descriptor.descriptor->IsRange();
1933 }
1934 
1936 {
1937  // We can only give out addresses from descriptors that are single type (not combo), ranged,
1938  // and either have cached keys or can generate more keys (ignoring encryption)
1939  LOCK(cs_desc_man);
1940  return m_wallet_descriptor.descriptor->IsSingleType() &&
1941  m_wallet_descriptor.descriptor->IsRange() &&
1942  (HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
1943 }
1944 
1946 {
1947  LOCK(cs_desc_man);
1948  return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
1949 }
1950 
1952 {
1953  // This is only used for getwalletinfo output and isn't relevant to descriptor wallets.
1954  // The magic number 0 indicates that it shouldn't be displayed so that's what we return.
1955  return 0;
1956 }
1957 
1959 {
1960  if (m_internal) {
1961  return 0;
1962  }
1963  return GetKeyPoolSize();
1964 }
1965 
1967 {
1968  LOCK(cs_desc_man);
1969  return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
1970 }
1971 
1973 {
1974  LOCK(cs_desc_man);
1975  return m_wallet_descriptor.creation_time;
1976 }
1977 
1978 std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
1979 {
1980  LOCK(cs_desc_man);
1981 
1982  // Find the index of the script
1983  auto it = m_map_script_pub_keys.find(script);
1984  if (it == m_map_script_pub_keys.end()) {
1985  return nullptr;
1986  }
1987  int32_t index = it->second;
1988 
1989  return GetSigningProvider(index, include_private);
1990 }
1991 
1992 std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
1993 {
1994  LOCK(cs_desc_man);
1995 
1996  // Find index of the pubkey
1997  auto it = m_map_pubkeys.find(pubkey);
1998  if (it == m_map_pubkeys.end()) {
1999  return nullptr;
2000  }
2001  int32_t index = it->second;
2002 
2003  // Always try to get the signing provider with private keys. This function should only be called during signing anyways
2004  return GetSigningProvider(index, true);
2005 }
2006 
2007 std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
2008 {
2009  AssertLockHeld(cs_desc_man);
2010  // Get the scripts, keys, and key origins for this script
2011  std::unique_ptr<FlatSigningProvider> out_keys = MakeUnique<FlatSigningProvider>();
2012  std::vector<CScript> scripts_temp;
2013  if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
2014 
2015  if (HavePrivateKeys() && include_private) {
2016  FlatSigningProvider master_provider;
2017  master_provider.keys = GetKeys();
2018  m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
2019  }
2020 
2021  return out_keys;
2022 }
2023 
2024 std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
2025 {
2026  return GetSigningProvider(script, false);
2027 }
2028 
2030 {
2031  return IsMine(script);
2032 }
2033 
2034 bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const
2035 {
2036  std::unique_ptr<FlatSigningProvider> keys = MakeUnique<FlatSigningProvider>();
2037  for (const auto& coin_pair : coins) {
2038  std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
2039  if (!coin_keys) {
2040  continue;
2041  }
2042  *keys = Merge(*keys, *coin_keys);
2043  }
2044 
2045  return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
2046 }
2047 
2048 SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
2049 {
2050  std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
2051  if (!keys) {
2053  }
2054 
2055  CKeyID key_id(pkhash);
2056  CKey key;
2057  if (!keys->GetKey(key_id, key)) {
2059  }
2060 
2061  if (!MessageSign(key, message, str_sig)) {
2063  }
2064  return SigningResult::OK;
2065 }
2066 
2067 TransactionError DescriptorScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, int sighash_type, bool sign, bool bip32derivs) const
2068 {
2069  for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
2070  const CTxIn& txin = psbtx.tx->vin[i];
2071  PSBTInput& input = psbtx.inputs.at(i);
2072 
2073  if (PSBTInputSigned(input)) {
2074  continue;
2075  }
2076 
2077  // Verify input looks sane. This will check that we have at most one uxto, witness or non-witness.
2078  if (!input.IsSane()) {
2080  }
2081 
2082  // Get the Sighash type
2083  if (sign && input.sighash_type > 0 && input.sighash_type != sighash_type) {
2085  }
2086 
2087  // Get the scriptPubKey to know which SigningProvider to use
2088  CScript script;
2089  if (!input.witness_utxo.IsNull()) {
2090  script = input.witness_utxo.scriptPubKey;
2091  } else if (input.non_witness_utxo) {
2092  if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
2094  }
2095  script = input.non_witness_utxo->vout[txin.prevout.n].scriptPubKey;
2096  } else {
2097  // There's no UTXO so we can just skip this now
2098  continue;
2099  }
2100  SignatureData sigdata;
2101  input.FillSignatureData(sigdata);
2102 
2103  std::unique_ptr<FlatSigningProvider> keys = MakeUnique<FlatSigningProvider>();
2104  std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, sign);
2105  if (script_keys) {
2106  *keys = Merge(*keys, *script_keys);
2107  } else {
2108  // Maybe there are pubkeys listed that we can sign for
2109  script_keys = MakeUnique<FlatSigningProvider>();
2110  for (const auto& pk_pair : input.hd_keypaths) {
2111  const CPubKey& pubkey = pk_pair.first;
2112  std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
2113  if (pk_keys) {
2114  *keys = Merge(*keys, *pk_keys);
2115  }
2116  }
2117  }
2118 
2119  SignPSBTInput(HidingSigningProvider(keys.get(), !sign, !bip32derivs), psbtx, i, sighash_type);
2120  }
2121 
2122  // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
2123  for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
2124  std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
2125  if (!keys) {
2126  continue;
2127  }
2128  UpdatePSBTOutput(HidingSigningProvider(keys.get(), true, !bip32derivs), psbtx, i);
2129  }
2130 
2131  return TransactionError::OK;
2132 }
2133 
2134 std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
2135 {
2136  std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
2137  if (provider) {
2138  KeyOriginInfo orig;
2139  CKeyID key_id = GetKeyForDestination(*provider, dest);
2140  if (provider->GetKeyOrigin(key_id, orig)) {
2141  LOCK(cs_desc_man);
2142  std::unique_ptr<CKeyMetadata> meta = MakeUnique<CKeyMetadata>();
2143  meta->key_origin = orig;
2144  meta->has_key_origin = true;
2145  meta->nCreateTime = m_wallet_descriptor.creation_time;
2146  return meta;
2147  }
2148  }
2149  return nullptr;
2150 }
2151 
2153 {
2154  LOCK(cs_desc_man);
2155  std::string desc_str = m_wallet_descriptor.descriptor->ToString();
2156  uint256 id;
2157  CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
2158  return id;
2159 }
2160 
2162 {
2163  this->m_internal = internal;
2164 }
2165 
2167 {
2168  LOCK(cs_desc_man);
2169  m_wallet_descriptor.cache = cache;
2170  for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
2171  FlatSigningProvider out_keys;
2172  std::vector<CScript> scripts_temp;
2173  if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2174  throw std::runtime_error("Error: Unable to expand wallet descriptor from cache");
2175  }
2176  // Add all of the scriptPubKeys to the scriptPubKey set
2177  for (const CScript& script : scripts_temp) {
2178  if (m_map_script_pub_keys.count(script) != 0) {
2179  throw std::runtime_error(strprintf("Error: Already loaded script at index %d as being at index %d", i, m_map_script_pub_keys[script]));
2180  }
2181  m_map_script_pub_keys[script] = i;
2182  }
2183  for (const auto& pk_pair : out_keys.pubkeys) {
2184  const CPubKey& pubkey = pk_pair.second;
2185  if (m_map_pubkeys.count(pubkey) != 0) {
2186  // We don't need to give an error here.
2187  // 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
2188  continue;
2189  }
2190  m_map_pubkeys[pubkey] = i;
2191  }
2192  m_max_cached_index++;
2193  }
2194 }
2195 
2196 bool DescriptorScriptPubKeyMan::AddKey(const CKeyID& key_id, const CKey& key)
2197 {
2198  LOCK(cs_desc_man);
2199  m_map_keys[key_id] = key;
2200  return true;
2201 }
2202 
2203 bool DescriptorScriptPubKeyMan::AddCryptedKey(const CKeyID& key_id, const CPubKey& pubkey, const std::vector<unsigned char>& crypted_key)
2204 {
2205  LOCK(cs_desc_man);
2206  if (!m_map_keys.empty()) {
2207  return false;
2208  }
2209 
2210  m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
2211  return true;
2212 }
2213 
2215 {
2216  LOCK(cs_desc_man);
2217  return m_wallet_descriptor.descriptor != nullptr && desc.descriptor != nullptr && m_wallet_descriptor.descriptor->ToString() == desc.descriptor->ToString();
2218 }
2219 
2221 {
2222  LOCK(cs_desc_man);
2224  if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
2225  throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
2226  }
2227 }
2228 
2230 {
2231  return m_wallet_descriptor;
2232 }
2233 
2234 const std::vector<CScript> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
2235 {
2236  LOCK(cs_desc_man);
2237  std::vector<CScript> script_pub_keys;
2238  script_pub_keys.reserve(m_map_script_pub_keys.size());
2239 
2240  for (auto const& script_pub_key: m_map_script_pub_keys) {
2241  script_pub_keys.push_back(script_pub_key.first);
2242  }
2243  return script_pub_keys;
2244 }
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:133
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:156
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
unspendable OP_RETURN script that carries data
Definition: standard.h:63
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:124
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:394
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:1039
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:236
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
Definition: walletdb.cpp:147
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:297
uint256 GetHash() const
Get the 256-bit hash of this public key.
Definition: pubkey.h:161
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:164
virtual std::set< CKeyID > GetKeys() const
uint256 GetID() const override
static std::string WriteHDKeypath(std::vector< uint32_t > &keypath)
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:91
void LearnRelatedScripts(const CPubKey &key, OutputType)
Explicitly make the wallet learn the related scripts for outputs to the given key.
txnouttype Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:91
std::string translated
Definition: translation.h:18
virtual WalletDatabase & GetDatabase()=0
A version of CTransaction with the PSBT format.
Definition: psbt.h:392
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)
uint160 Hash160(const T1 pbegin, const T1 pend)
Compute the 160-bit hash an object.
Definition: hash.h:94
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:54
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)
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:155
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:141
Access to the wallet database.
Definition: walletdb.h:179
static bool ExtractPubKey(const CScript &dest, CPubKey &pubKeyOut)
void WalletLogPrintf(std::string fmt, Params... parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
TransactionError FillPSBT(PartiallySignedTransaction &psbt, int sighash_type=1, bool sign=true, bool bip32derivs=false) const override
Adds script and derivation path information to a PSBT, and optionally signs it.
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:217
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.
void SetHDChain(const CHDChain &chain, bool memonly)
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.
Only for Witness versions not already defined above.
Definition: standard.h:66
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:142
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:57
bool AddWatchOnlyInMem(const CScript &dest)
#define LOCK(cs)
Definition: sync.h:218
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:52
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:171
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:22
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:217
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:289
Descriptor with some wallet metadata.
Definition: walletutil.h:91
bool AddKey(const CKeyID &key_id, const CKey &key)
KeyOriginInfo key_origin
Definition: walletdb.h:135
int64_t nCreateTime
Definition: walletdb.h:132
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:136
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:395
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:91
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:131
int64_t GetTimeFirstKey() const override
P2SH redeemScript.
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:190
bool WritePool(int64_t nPool, const CKeyPool &keypool)
Definition: walletdb.cpp:185
txnouttype
Definition: standard.h:55
256-bit opaque blob.
Definition: uint256.h:120
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 IsSane() const
Definition: psbt.cpp:161
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
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:379
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...
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:76
TransactionError
Definition: error.h:22
160-bit opaque blob.
Definition: uint256.h:109
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:129
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:180
int64_t GetTimeFirstKey() const override
static const int VERSION_HD_CHAIN_SPLIT
Definition: walletdb.h:96
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:21
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:210
virtual bool HasEncryptionKeys() const =0
A mutable version of CTransaction.
Definition: transaction.h:345
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:212
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:96
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:134
void FillSignatureData(SignatureData &sigdata) const
Definition: psbt.cpp:88
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:143
AssertLockHeld(g_cs_orphans)
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:61
CKeyID seed_id
seed hash160
Definition: walletdb.h:93
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:380
COutPoint prevout
Definition: transaction.h:60
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:49
bool AddCScriptWithDB(WalletBatch &batch, const CScript &script)
Adds a script to the store and saves it to disk.
int nVersion
Definition: walletdb.h:98
TransactionError FillPSBT(PartiallySignedTransaction &psbt, int sighash_type=1, bool sign=true, bool bip32derivs=false) const override
Adds script and derivation path information to a PSBT, and optionally signs it.
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:95
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
uint32_t nInternalChainCounter
Definition: walletdb.h:92
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
Definition: walletdb.cpp:206
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:180
virtual bool HaveKey(const CKeyID &address) const override