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