Bitcoin Core  0.20.99
P2P Digital Currency
scriptpubkeyman.cpp
Go to the documentation of this file.
1 // Copyright (c) 2019-2020 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <key_io.h>
6 #include <outputtype.h>
7 #include <script/descriptor.h>
8 #include <script/sign.h>
9 #include <util/bip32.h>
10 #include <util/strencodings.h>
11 #include <util/string.h>
12 #include <util/translation.h>
13 #include <wallet/scriptpubkeyman.h>
14 
16 const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
17 
19 {
21  error.clear();
22 
23  // Generate a new key that is added to wallet
24  CPubKey new_key;
25  if (!GetKeyFromPool(new_key, type)) {
26  error = _("Error: Keypool ran out, please call keypoolrefill first").translated;
27  return false;
28  }
29  LearnRelatedScripts(new_key, type);
30  dest = GetDestinationForKey(new_key, type);
31  return true;
32 }
33 
34 typedef std::vector<unsigned char> valtype;
35 
36 namespace {
37 
44 enum class IsMineSigVersion
45 {
46  TOP = 0,
47  P2SH = 1,
48  WITNESS_V0 = 2,
49 };
50 
56 enum class IsMineResult
57 {
58  NO = 0,
59  WATCH_ONLY = 1,
60  SPENDABLE = 2,
61  INVALID = 3,
62 };
63 
64 bool PermitsUncompressed(IsMineSigVersion sigversion)
65 {
66  return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
67 }
68 
69 bool HaveKeys(const std::vector<valtype>& pubkeys, const LegacyScriptPubKeyMan& keystore)
70 {
71  for (const valtype& pubkey : pubkeys) {
72  CKeyID keyID = CPubKey(pubkey).GetID();
73  if (!keystore.HaveKey(keyID)) return false;
74  }
75  return true;
76 }
77 
86 IsMineResult IsMineInner(const LegacyScriptPubKeyMan& keystore, const CScript& scriptPubKey, IsMineSigVersion sigversion, bool recurse_scripthash=true)
87 {
88  IsMineResult ret = IsMineResult::NO;
89 
90  std::vector<valtype> vSolutions;
91  TxoutType whichType = Solver(scriptPubKey, vSolutions);
92 
93  CKeyID keyID;
94  switch (whichType)
95  {
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 
442 {
443  LOCK(cs_KeyStore);
444  bool hd_upgrade = false;
445  bool split_upgrade = false;
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
457  WalletLogPrintf("Upgrading wallet to use HD chain split\n");
459  split_upgrade = FEATURE_HD_SPLIT > prev_version;
460  }
461  // Mark all keys currently in the keypool as pre-split
462  if (split_upgrade) {
464  }
465  // Regenerate the keypool if upgraded to HD
466  if (hd_upgrade) {
467  if (!TopUp()) {
468  error = _("Unable to generate keys");
469  return false;
470  }
471  }
472  return true;
473 }
474 
476 {
477  LOCK(cs_KeyStore);
478  return !mapKeys.empty() || !mapCryptedKeys.empty();
479 }
480 
482 {
483  LOCK(cs_KeyStore);
484  setInternalKeyPool.clear();
485  setExternalKeyPool.clear();
486  m_pool_key_to_index.clear();
487  // Note: can't top-up keypool here, because wallet is locked.
488  // User will be prompted to unlock wallet the next operation
489  // that requires a new key.
490 }
491 
492 static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, WalletBatch& batch) {
493  if (setKeyPool.empty()) {
494  return GetTime();
495  }
496 
497  CKeyPool keypool;
498  int64_t nIndex = *(setKeyPool.begin());
499  if (!batch.ReadPool(nIndex, keypool)) {
500  throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
501  }
502  assert(keypool.vchPubKey.IsValid());
503  return keypool.nTime;
504 }
505 
507 {
508  LOCK(cs_KeyStore);
509 
511 
512  // load oldest key from keypool, get time and return
513  int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, batch);
515  oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, batch), oldestKey);
516  if (!set_pre_split_keypool.empty()) {
517  oldestKey = std::max(GetOldestKeyTimeInPool(set_pre_split_keypool, batch), oldestKey);
518  }
519  }
520 
521  return oldestKey;
522 }
523 
525 {
526  LOCK(cs_KeyStore);
527  return setExternalKeyPool.size() + set_pre_split_keypool.size();
528 }
529 
531 {
532  LOCK(cs_KeyStore);
533  return setInternalKeyPool.size() + setExternalKeyPool.size() + set_pre_split_keypool.size();
534 }
535 
537 {
538  LOCK(cs_KeyStore);
539  return nTimeFirstKey;
540 }
541 
542 std::unique_ptr<SigningProvider> LegacyScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
543 {
544  return MakeUnique<LegacySigningProvider>(*this);
545 }
546 
548 {
549  IsMineResult ismine = IsMineInner(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
550  if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
551  // If ismine, it means we recognize keys or script ids in the script, or
552  // are watching the script itself, and we can at least provide metadata
553  // or solving information, even if not able to sign fully.
554  return true;
555  } else {
556  // If, given the stuff in sigdata, we could make a valid sigature, then we can provide for this script
557  ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
558  if (!sigdata.signatures.empty()) {
559  // If we could make signatures, make sure we have a private key to actually make a signature
560  bool has_privkeys = false;
561  for (const auto& key_sig_pair : sigdata.signatures) {
562  has_privkeys |= HaveKey(key_sig_pair.first);
563  }
564  return has_privkeys;
565  }
566  return false;
567  }
568 }
569 
570 bool LegacyScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const
571 {
572  return ::SignTransaction(tx, this, coins, sighash, input_errors);
573 }
574 
575 SigningResult LegacyScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
576 {
577  CKey key;
578  if (!GetKey(ToKeyID(pkhash), key)) {
580  }
581 
582  if (MessageSign(key, message, str_sig)) {
583  return SigningResult::OK;
584  }
586 }
587 
588 TransactionError LegacyScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, int sighash_type, bool sign, bool bip32derivs, int* n_signed) const
589 {
590  if (n_signed) {
591  *n_signed = 0;
592  }
593  for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
594  const CTxIn& txin = psbtx.tx->vin[i];
595  PSBTInput& input = psbtx.inputs.at(i);
596 
597  if (PSBTInputSigned(input)) {
598  continue;
599  }
600 
601  // Get the Sighash type
602  if (sign && input.sighash_type > 0 && input.sighash_type != sighash_type) {
604  }
605 
606  // Check non_witness_utxo has specified prevout
607  if (input.non_witness_utxo) {
608  if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
610  }
611  } else if (input.witness_utxo.IsNull()) {
612  // There's no UTXO so we can just skip this now
613  continue;
614  }
615  SignatureData sigdata;
616  input.FillSignatureData(sigdata);
617  SignPSBTInput(HidingSigningProvider(this, !sign, !bip32derivs), psbtx, i, sighash_type);
618 
619  bool signed_one = PSBTInputSigned(input);
620  if (n_signed && (signed_one || !sign)) {
621  // If sign is false, we assume that we _could_ sign if we get here. This
622  // will never have false negatives; it is hard to tell under what i
623  // circumstances it could have false positives.
624  (*n_signed)++;
625  }
626  }
627 
628  // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
629  for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
630  UpdatePSBTOutput(HidingSigningProvider(this, true, !bip32derivs), psbtx, i);
631  }
632 
633  return TransactionError::OK;
634 }
635 
636 std::unique_ptr<CKeyMetadata> LegacyScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
637 {
638  LOCK(cs_KeyStore);
639 
640  CKeyID key_id = GetKeyForDestination(*this, dest);
641  if (!key_id.IsNull()) {
642  auto it = mapKeyMetadata.find(key_id);
643  if (it != mapKeyMetadata.end()) {
644  return MakeUnique<CKeyMetadata>(it->second);
645  }
646  }
647 
648  CScript scriptPubKey = GetScriptForDestination(dest);
649  auto it = m_script_metadata.find(CScriptID(scriptPubKey));
650  if (it != m_script_metadata.end()) {
651  return MakeUnique<CKeyMetadata>(it->second);
652  }
653 
654  return nullptr;
655 }
656 
658 {
659  return uint256::ONE;
660 }
661 
667 {
669  if (nCreateTime <= 1) {
670  // Cannot determine birthday information, so set the wallet birthday to
671  // the beginning of time.
672  nTimeFirstKey = 1;
673  } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
674  nTimeFirstKey = nCreateTime;
675  }
676 }
677 
678 bool LegacyScriptPubKeyMan::LoadKey(const CKey& key, const CPubKey &pubkey)
679 {
680  return AddKeyPubKeyInner(key, pubkey);
681 }
682 
683 bool LegacyScriptPubKeyMan::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
684 {
685  LOCK(cs_KeyStore);
687  return LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(batch, secret, pubkey);
688 }
689 
690 bool LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(WalletBatch& batch, const CKey& secret, const CPubKey& pubkey)
691 {
693 
694  // Make sure we aren't adding private keys to private key disabled wallets
696 
697  // FillableSigningProvider has no concept of wallet databases, but calls AddCryptedKey
698  // which is overridden below. To avoid flushes, the database handle is
699  // tunneled through to it.
700  bool needsDB = !encrypted_batch;
701  if (needsDB) {
702  encrypted_batch = &batch;
703  }
704  if (!AddKeyPubKeyInner(secret, pubkey)) {
705  if (needsDB) encrypted_batch = nullptr;
706  return false;
707  }
708  if (needsDB) encrypted_batch = nullptr;
709 
710  // check if we need to remove from watch-only
711  CScript script;
712  script = GetScriptForDestination(PKHash(pubkey));
713  if (HaveWatchOnly(script)) {
714  RemoveWatchOnly(script);
715  }
716  script = GetScriptForRawPubKey(pubkey);
717  if (HaveWatchOnly(script)) {
718  RemoveWatchOnly(script);
719  }
720 
721  if (!m_storage.HasEncryptionKeys()) {
722  return batch.WriteKey(pubkey,
723  secret.GetPrivKey(),
724  mapKeyMetadata[pubkey.GetID()]);
725  }
727  return true;
728 }
729 
731 {
732  /* A sanity check was added in pull #3843 to avoid adding redeemScripts
733  * that never can be redeemed. However, old wallets may still contain
734  * these. Do not add them to the wallet and warn. */
735  if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
736  {
737  std::string strAddr = EncodeDestination(ScriptHash(redeemScript));
738  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);
739  return true;
740  }
741 
742  return FillableSigningProvider::AddCScript(redeemScript);
743 }
744 
746 {
747  LOCK(cs_KeyStore);
749  mapKeyMetadata[keyID] = meta;
750 }
751 
753 {
754  LOCK(cs_KeyStore);
756  m_script_metadata[script_id] = meta;
757 }
758 
760 {
761  LOCK(cs_KeyStore);
762  if (!m_storage.HasEncryptionKeys()) {
763  return FillableSigningProvider::AddKeyPubKey(key, pubkey);
764  }
765 
766  if (m_storage.IsLocked()) {
767  return false;
768  }
769 
770  std::vector<unsigned char> vchCryptedSecret;
771  CKeyingMaterial vchSecret(key.begin(), key.end());
772  if (!EncryptSecret(m_storage.GetEncryptionKey(), vchSecret, pubkey.GetHash(), vchCryptedSecret)) {
773  return false;
774  }
775 
776  if (!AddCryptedKey(pubkey, vchCryptedSecret)) {
777  return false;
778  }
779  return true;
780 }
781 
782 bool LegacyScriptPubKeyMan::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid)
783 {
784  // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
785  if (!checksum_valid) {
787  }
788 
789  return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
790 }
791 
792 bool LegacyScriptPubKeyMan::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
793 {
794  LOCK(cs_KeyStore);
795  assert(mapKeys.empty());
796 
797  mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
799  return true;
800 }
801 
803  const std::vector<unsigned char> &vchCryptedSecret)
804 {
805  if (!AddCryptedKeyInner(vchPubKey, vchCryptedSecret))
806  return false;
807  {
808  LOCK(cs_KeyStore);
809  if (encrypted_batch)
810  return encrypted_batch->WriteCryptedKey(vchPubKey,
811  vchCryptedSecret,
812  mapKeyMetadata[vchPubKey.GetID()]);
813  else
814  return WalletBatch(m_storage.GetDatabase()).WriteCryptedKey(vchPubKey,
815  vchCryptedSecret,
816  mapKeyMetadata[vchPubKey.GetID()]);
817  }
818 }
819 
821 {
822  LOCK(cs_KeyStore);
823  return setWatchOnly.count(dest) > 0;
824 }
825 
827 {
828  LOCK(cs_KeyStore);
829  return (!setWatchOnly.empty());
830 }
831 
832 static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
833 {
834  std::vector<std::vector<unsigned char>> solutions;
835  return Solver(dest, solutions) == TxoutType::PUBKEY &&
836  (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
837 }
838 
840 {
841  {
842  LOCK(cs_KeyStore);
843  setWatchOnly.erase(dest);
844  CPubKey pubKey;
845  if (ExtractPubKey(dest, pubKey)) {
846  mapWatchKeys.erase(pubKey.GetID());
847  }
848  // Related CScripts are not removed; having superfluous scripts around is
849  // harmless (see comment in ImplicitlyLearnRelatedKeyScripts).
850  }
851 
852  if (!HaveWatchOnly())
853  NotifyWatchonlyChanged(false);
854  if (!WalletBatch(m_storage.GetDatabase()).EraseWatchOnly(dest))
855  return false;
856 
857  return true;
858 }
859 
861 {
862  return AddWatchOnlyInMem(dest);
863 }
864 
866 {
867  LOCK(cs_KeyStore);
868  setWatchOnly.insert(dest);
869  CPubKey pubKey;
870  if (ExtractPubKey(dest, pubKey)) {
871  mapWatchKeys[pubKey.GetID()] = pubKey;
873  }
874  return true;
875 }
876 
878 {
879  if (!AddWatchOnlyInMem(dest))
880  return false;
881  const CKeyMetadata& meta = m_script_metadata[CScriptID(dest)];
884  if (batch.WriteWatchOnly(dest, meta)) {
886  return true;
887  }
888  return false;
889 }
890 
891 bool LegacyScriptPubKeyMan::AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest, int64_t create_time)
892 {
893  m_script_metadata[CScriptID(dest)].nCreateTime = create_time;
894  return AddWatchOnlyWithDB(batch, dest);
895 }
896 
898 {
900  return AddWatchOnlyWithDB(batch, dest);
901 }
902 
903 bool LegacyScriptPubKeyMan::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
904 {
905  m_script_metadata[CScriptID(dest)].nCreateTime = nCreateTime;
906  return AddWatchOnly(dest);
907 }
908 
910 {
911  LOCK(cs_KeyStore);
912  m_hd_chain = chain;
913 }
914 
916 {
917  LOCK(cs_KeyStore);
918  // Store the new chain
919  if (!WalletBatch(m_storage.GetDatabase()).WriteHDChain(chain)) {
920  throw std::runtime_error(std::string(__func__) + ": writing chain failed");
921  }
922  // When there's an old chain, add it as an inactive chain as we are now rotating hd chains
923  if (!m_hd_chain.seed_id.IsNull()) {
925  }
926 
927  m_hd_chain = chain;
928 }
929 
931 {
932  LOCK(cs_KeyStore);
933  assert(!chain.seed_id.IsNull());
934  m_inactive_hd_chains[chain.seed_id] = chain;
935 }
936 
937 bool LegacyScriptPubKeyMan::HaveKey(const CKeyID &address) const
938 {
939  LOCK(cs_KeyStore);
940  if (!m_storage.HasEncryptionKeys()) {
941  return FillableSigningProvider::HaveKey(address);
942  }
943  return mapCryptedKeys.count(address) > 0;
944 }
945 
946 bool LegacyScriptPubKeyMan::GetKey(const CKeyID &address, CKey& keyOut) const
947 {
948  LOCK(cs_KeyStore);
949  if (!m_storage.HasEncryptionKeys()) {
950  return FillableSigningProvider::GetKey(address, keyOut);
951  }
952 
953  CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
954  if (mi != mapCryptedKeys.end())
955  {
956  const CPubKey &vchPubKey = (*mi).second.first;
957  const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
958  return DecryptKey(m_storage.GetEncryptionKey(), vchCryptedSecret, vchPubKey, keyOut);
959  }
960  return false;
961 }
962 
964 {
965  CKeyMetadata meta;
966  {
967  LOCK(cs_KeyStore);
968  auto it = mapKeyMetadata.find(keyID);
969  if (it != mapKeyMetadata.end()) {
970  meta = it->second;
971  }
972  }
973  if (meta.has_key_origin) {
974  std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4, info.fingerprint);
975  info.path = meta.key_origin.path;
976  } else { // Single pubkeys get the master fingerprint of themselves
977  std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
978  }
979  return true;
980 }
981 
982 bool LegacyScriptPubKeyMan::GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
983 {
984  LOCK(cs_KeyStore);
985  WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
986  if (it != mapWatchKeys.end()) {
987  pubkey_out = it->second;
988  return true;
989  }
990  return false;
991 }
992 
993 bool LegacyScriptPubKeyMan::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
994 {
995  LOCK(cs_KeyStore);
996  if (!m_storage.HasEncryptionKeys()) {
997  if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
998  return GetWatchPubKey(address, vchPubKeyOut);
999  }
1000  return true;
1001  }
1002 
1003  CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
1004  if (mi != mapCryptedKeys.end())
1005  {
1006  vchPubKeyOut = (*mi).second.first;
1007  return true;
1008  }
1009  // Check for watch-only pubkeys
1010  return GetWatchPubKey(address, vchPubKeyOut);
1011 }
1012 
1014 {
1018  bool fCompressed = m_storage.CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
1019 
1020  CKey secret;
1021 
1022  // Create new metadata
1023  int64_t nCreationTime = GetTime();
1024  CKeyMetadata metadata(nCreationTime);
1025 
1026  // use HD key derivation if HD was enabled during wallet creation and a seed is present
1027  if (IsHDEnabled()) {
1028  DeriveNewChildKey(batch, metadata, secret, hd_chain, (m_storage.CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
1029  } else {
1030  secret.MakeNewKey(fCompressed);
1031  }
1032 
1033  // Compressed public keys were introduced in version 0.6.0
1034  if (fCompressed) {
1036  }
1037 
1038  CPubKey pubkey = secret.GetPubKey();
1039  assert(secret.VerifyPubKey(pubkey));
1040 
1041  mapKeyMetadata[pubkey.GetID()] = metadata;
1042  UpdateTimeFirstKey(nCreationTime);
1043 
1044  if (!AddKeyPubKeyWithDB(batch, secret, pubkey)) {
1045  throw std::runtime_error(std::string(__func__) + ": AddKey failed");
1046  }
1047  return pubkey;
1048 }
1049 
1050 void LegacyScriptPubKeyMan::DeriveNewChildKey(WalletBatch &batch, CKeyMetadata& metadata, CKey& secret, CHDChain& hd_chain, bool internal)
1051 {
1052  // for now we use a fixed keypath scheme of m/0'/0'/k
1053  CKey seed; //seed (256bit)
1054  CExtKey masterKey; //hd master key
1055  CExtKey accountKey; //key at m/0'
1056  CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
1057  CExtKey childKey; //key at m/0'/0'/<n>'
1058 
1059  // try to get the seed
1060  if (!GetKey(hd_chain.seed_id, seed))
1061  throw std::runtime_error(std::string(__func__) + ": seed not found");
1062 
1063  masterKey.SetSeed(seed.begin(), seed.size());
1064 
1065  // derive m/0'
1066  // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
1067  masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
1068 
1069  // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
1070  assert(internal ? m_storage.CanSupportFeature(FEATURE_HD_SPLIT) : true);
1071  accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
1072 
1073  // derive child key at next index, skip keys already known to the wallet
1074  do {
1075  // always derive hardened keys
1076  // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
1077  // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
1078  if (internal) {
1079  chainChildKey.Derive(childKey, hd_chain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
1080  metadata.hdKeypath = "m/0'/1'/" + ToString(hd_chain.nInternalChainCounter) + "'";
1081  metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1082  metadata.key_origin.path.push_back(1 | BIP32_HARDENED_KEY_LIMIT);
1083  metadata.key_origin.path.push_back(hd_chain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
1084  hd_chain.nInternalChainCounter++;
1085  }
1086  else {
1087  chainChildKey.Derive(childKey, hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
1088  metadata.hdKeypath = "m/0'/0'/" + ToString(hd_chain.nExternalChainCounter) + "'";
1089  metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1090  metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
1091  metadata.key_origin.path.push_back(hd_chain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
1092  hd_chain.nExternalChainCounter++;
1093  }
1094  } while (HaveKey(childKey.key.GetPubKey().GetID()));
1095  secret = childKey.key;
1096  metadata.hd_seed_id = hd_chain.seed_id;
1097  CKeyID master_id = masterKey.key.GetPubKey().GetID();
1098  std::copy(master_id.begin(), master_id.begin() + 4, metadata.key_origin.fingerprint);
1099  metadata.has_key_origin = true;
1100  // update the chain model in the database
1101  if (hd_chain.seed_id == m_hd_chain.seed_id && !batch.WriteHDChain(hd_chain))
1102  throw std::runtime_error(std::string(__func__) + ": writing HD chain model failed");
1103 }
1104 
1105 void LegacyScriptPubKeyMan::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
1106 {
1107  LOCK(cs_KeyStore);
1108  if (keypool.m_pre_split) {
1109  set_pre_split_keypool.insert(nIndex);
1110  } else if (keypool.fInternal) {
1111  setInternalKeyPool.insert(nIndex);
1112  } else {
1113  setExternalKeyPool.insert(nIndex);
1114  }
1115  m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
1116  m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
1117 
1118  // If no metadata exists yet, create a default with the pool key's
1119  // creation time. Note that this may be overwritten by actually
1120  // stored metadata for that key later, which is fine.
1121  CKeyID keyid = keypool.vchPubKey.GetID();
1122  if (mapKeyMetadata.count(keyid) == 0)
1123  mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
1124 }
1125 
1127 {
1128  // A wallet can generate keys if it has an HD seed (IsHDEnabled) or it is a non-HD wallet (pre FEATURE_HD)
1129  LOCK(cs_KeyStore);
1131 }
1132 
1134 {
1136  CKey key;
1137  key.MakeNewKey(true);
1138  return DeriveNewSeed(key);
1139 }
1140 
1142 {
1143  int64_t nCreationTime = GetTime();
1144  CKeyMetadata metadata(nCreationTime);
1145 
1146  // calculate the seed
1147  CPubKey seed = key.GetPubKey();
1148  assert(key.VerifyPubKey(seed));
1149 
1150  // set the hd keypath to "s" -> Seed, refers the seed to itself
1151  metadata.hdKeypath = "s";
1152  metadata.has_key_origin = false;
1153  metadata.hd_seed_id = seed.GetID();
1154 
1155  {
1156  LOCK(cs_KeyStore);
1157 
1158  // mem store the metadata
1159  mapKeyMetadata[seed.GetID()] = metadata;
1160 
1161  // write the key&metadata to the database
1162  if (!AddKeyPubKey(key, seed))
1163  throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1164  }
1165 
1166  return seed;
1167 }
1168 
1170 {
1171  LOCK(cs_KeyStore);
1172  // store the keyid (hash160) together with
1173  // the child index counter in the database
1174  // as a hdchain object
1175  CHDChain newHdChain;
1177  newHdChain.seed_id = seed.GetID();
1178  AddHDChain(newHdChain);
1182 }
1183 
1189 {
1191  return false;
1192  }
1193  {
1194  LOCK(cs_KeyStore);
1196 
1197  for (const int64_t nIndex : setInternalKeyPool) {
1198  batch.ErasePool(nIndex);
1199  }
1200  setInternalKeyPool.clear();
1201 
1202  for (const int64_t nIndex : setExternalKeyPool) {
1203  batch.ErasePool(nIndex);
1204  }
1205  setExternalKeyPool.clear();
1206 
1207  for (const int64_t nIndex : set_pre_split_keypool) {
1208  batch.ErasePool(nIndex);
1209  }
1210  set_pre_split_keypool.clear();
1211 
1212  m_pool_key_to_index.clear();
1213 
1214  if (!TopUp()) {
1215  return false;
1216  }
1217  WalletLogPrintf("LegacyScriptPubKeyMan::NewKeyPool rewrote keypool\n");
1218  }
1219  return true;
1220 }
1221 
1222 bool LegacyScriptPubKeyMan::TopUp(unsigned int kpSize)
1223 {
1224  if (!CanGenerateKeys()) {
1225  return false;
1226  }
1227  {
1228  LOCK(cs_KeyStore);
1229 
1230  if (m_storage.IsLocked()) return false;
1231 
1232  // Top up key pool
1233  unsigned int nTargetSize;
1234  if (kpSize > 0)
1235  nTargetSize = kpSize;
1236  else
1237  nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
1238 
1239  // count amount of available keys (internal, external)
1240  // make sure the keypool of external and internal keys fits the user selected target (-keypool)
1241  int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
1242  int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
1243 
1245  {
1246  // don't create extra internal keys
1247  missingInternal = 0;
1248  }
1249  bool internal = false;
1251  for (int64_t i = missingInternal + missingExternal; i--;)
1252  {
1253  if (i < missingInternal) {
1254  internal = true;
1255  }
1256 
1257  CPubKey pubkey(GenerateNewKey(batch, m_hd_chain, internal));
1258  AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1259  }
1260  if (missingInternal + missingExternal > 0) {
1261  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());
1262  }
1263  }
1265  return true;
1266 }
1267 
1268 void LegacyScriptPubKeyMan::AddKeypoolPubkeyWithDB(const CPubKey& pubkey, const bool internal, WalletBatch& batch)
1269 {
1270  LOCK(cs_KeyStore);
1271  assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
1272  int64_t index = ++m_max_keypool_index;
1273  if (!batch.WritePool(index, CKeyPool(pubkey, internal))) {
1274  throw std::runtime_error(std::string(__func__) + ": writing imported pubkey failed");
1275  }
1276  if (internal) {
1277  setInternalKeyPool.insert(index);
1278  } else {
1279  setExternalKeyPool.insert(index);
1280  }
1281  m_pool_key_to_index[pubkey.GetID()] = index;
1282 }
1283 
1284 void LegacyScriptPubKeyMan::KeepDestination(int64_t nIndex, const OutputType& type)
1285 {
1286  // Remove from key pool
1288  batch.ErasePool(nIndex);
1289  CPubKey pubkey;
1290  bool have_pk = GetPubKey(m_index_to_reserved_key.at(nIndex), pubkey);
1291  assert(have_pk);
1292  LearnRelatedScripts(pubkey, type);
1293  m_index_to_reserved_key.erase(nIndex);
1294  WalletLogPrintf("keypool keep %d\n", nIndex);
1295 }
1296 
1297 void LegacyScriptPubKeyMan::ReturnDestination(int64_t nIndex, bool fInternal, const CTxDestination&)
1298 {
1299  // Return to key pool
1300  {
1301  LOCK(cs_KeyStore);
1302  if (fInternal) {
1303  setInternalKeyPool.insert(nIndex);
1304  } else if (!set_pre_split_keypool.empty()) {
1305  set_pre_split_keypool.insert(nIndex);
1306  } else {
1307  setExternalKeyPool.insert(nIndex);
1308  }
1309  CKeyID& pubkey_id = m_index_to_reserved_key.at(nIndex);
1310  m_pool_key_to_index[pubkey_id] = nIndex;
1311  m_index_to_reserved_key.erase(nIndex);
1313  }
1314  WalletLogPrintf("keypool return %d\n", nIndex);
1315 }
1316 
1317 bool LegacyScriptPubKeyMan::GetKeyFromPool(CPubKey& result, const OutputType type, bool internal)
1318 {
1319  if (!CanGetAddresses(internal)) {
1320  return false;
1321  }
1322 
1323  CKeyPool keypool;
1324  {
1325  LOCK(cs_KeyStore);
1326  int64_t nIndex;
1328  if (m_storage.IsLocked()) return false;
1330  result = GenerateNewKey(batch, m_hd_chain, internal);
1331  return true;
1332  }
1333  KeepDestination(nIndex, type);
1334  result = keypool.vchPubKey;
1335  }
1336  return true;
1337 }
1338 
1339 bool LegacyScriptPubKeyMan::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
1340 {
1341  nIndex = -1;
1342  keypool.vchPubKey = CPubKey();
1343  {
1344  LOCK(cs_KeyStore);
1345 
1346  bool fReturningInternal = fRequestedInternal;
1348  bool use_split_keypool = set_pre_split_keypool.empty();
1349  std::set<int64_t>& setKeyPool = use_split_keypool ? (fReturningInternal ? setInternalKeyPool : setExternalKeyPool) : set_pre_split_keypool;
1350 
1351  // Get the oldest key
1352  if (setKeyPool.empty()) {
1353  return false;
1354  }
1355 
1357 
1358  auto it = setKeyPool.begin();
1359  nIndex = *it;
1360  setKeyPool.erase(it);
1361  if (!batch.ReadPool(nIndex, keypool)) {
1362  throw std::runtime_error(std::string(__func__) + ": read failed");
1363  }
1364  CPubKey pk;
1365  if (!GetPubKey(keypool.vchPubKey.GetID(), pk)) {
1366  throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
1367  }
1368  // If the key was pre-split keypool, we don't care about what type it is
1369  if (use_split_keypool && keypool.fInternal != fReturningInternal) {
1370  throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
1371  }
1372  if (!keypool.vchPubKey.IsValid()) {
1373  throw std::runtime_error(std::string(__func__) + ": keypool entry invalid");
1374  }
1375 
1376  assert(m_index_to_reserved_key.count(nIndex) == 0);
1377  m_index_to_reserved_key[nIndex] = keypool.vchPubKey.GetID();
1378  m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1379  WalletLogPrintf("keypool reserve %d\n", nIndex);
1380  }
1382  return true;
1383 }
1384 
1386 {
1387  if (key.IsCompressed() && (type == OutputType::P2SH_SEGWIT || type == OutputType::BECH32)) {
1388  CTxDestination witdest = WitnessV0KeyHash(key.GetID());
1389  CScript witprog = GetScriptForDestination(witdest);
1390  // Make sure the resulting program is solvable.
1391  assert(IsSolvable(*this, witprog));
1392  AddCScript(witprog);
1393  }
1394 }
1395 
1397 {
1398  // OutputType::P2SH_SEGWIT always adds all necessary scripts for all types.
1400 }
1401 
1403 {
1405  bool internal = setInternalKeyPool.count(keypool_id);
1406  if (!internal) assert(setExternalKeyPool.count(keypool_id) || set_pre_split_keypool.count(keypool_id));
1407  std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : (set_pre_split_keypool.empty() ? &setExternalKeyPool : &set_pre_split_keypool);
1408  auto it = setKeyPool->begin();
1409 
1411  while (it != std::end(*setKeyPool)) {
1412  const int64_t& index = *(it);
1413  if (index > keypool_id) break; // set*KeyPool is ordered
1414 
1415  CKeyPool keypool;
1416  if (batch.ReadPool(index, keypool)) { //TODO: This should be unnecessary
1417  m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
1418  }
1420  batch.ErasePool(index);
1421  WalletLogPrintf("keypool index %d removed\n", index);
1422  it = setKeyPool->erase(it);
1423  }
1424 }
1425 
1426 std::vector<CKeyID> GetAffectedKeys(const CScript& spk, const SigningProvider& provider)
1427 {
1428  std::vector<CScript> dummy;
1429  FlatSigningProvider out;
1430  InferDescriptor(spk, provider)->Expand(0, DUMMY_SIGNING_PROVIDER, dummy, out);
1431  std::vector<CKeyID> ret;
1432  for (const auto& entry : out.pubkeys) {
1433  ret.push_back(entry.first);
1434  }
1435  return ret;
1436 }
1437 
1439 {
1441  for (auto it = setExternalKeyPool.begin(); it != setExternalKeyPool.end();) {
1442  int64_t index = *it;
1443  CKeyPool keypool;
1444  if (!batch.ReadPool(index, keypool)) {
1445  throw std::runtime_error(std::string(__func__) + ": read keypool entry failed");
1446  }
1447  keypool.m_pre_split = true;
1448  if (!batch.WritePool(index, keypool)) {
1449  throw std::runtime_error(std::string(__func__) + ": writing modified keypool entry failed");
1450  }
1451  set_pre_split_keypool.insert(index);
1452  it = setExternalKeyPool.erase(it);
1453  }
1454 }
1455 
1457 {
1459  return AddCScriptWithDB(batch, redeemScript);
1460 }
1461 
1463 {
1464  if (!FillableSigningProvider::AddCScript(redeemScript))
1465  return false;
1466  if (batch.WriteCScript(Hash160(redeemScript), redeemScript)) {
1468  return true;
1469  }
1470  return false;
1471 }
1472 
1474 {
1475  LOCK(cs_KeyStore);
1476  std::copy(info.fingerprint, info.fingerprint + 4, mapKeyMetadata[pubkey.GetID()].key_origin.fingerprint);
1477  mapKeyMetadata[pubkey.GetID()].key_origin.path = info.path;
1478  mapKeyMetadata[pubkey.GetID()].has_key_origin = true;
1479  mapKeyMetadata[pubkey.GetID()].hdKeypath = WriteHDKeypath(info.path);
1480  return batch.WriteKeyMetadata(mapKeyMetadata[pubkey.GetID()], pubkey, true);
1481 }
1482 
1483 bool LegacyScriptPubKeyMan::ImportScripts(const std::set<CScript> scripts, int64_t timestamp)
1484 {
1486  for (const auto& entry : scripts) {
1487  CScriptID id(entry);
1488  if (HaveCScript(id)) {
1489  WalletLogPrintf("Already have script %s, skipping\n", HexStr(entry));
1490  continue;
1491  }
1492  if (!AddCScriptWithDB(batch, entry)) {
1493  return false;
1494  }
1495 
1496  if (timestamp > 0) {
1497  m_script_metadata[CScriptID(entry)].nCreateTime = timestamp;
1498  }
1499  }
1500  if (timestamp > 0) {
1501  UpdateTimeFirstKey(timestamp);
1502  }
1503 
1504  return true;
1505 }
1506 
1507 bool LegacyScriptPubKeyMan::ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp)
1508 {
1510  for (const auto& entry : privkey_map) {
1511  const CKey& key = entry.second;
1512  CPubKey pubkey = key.GetPubKey();
1513  const CKeyID& id = entry.first;
1514  assert(key.VerifyPubKey(pubkey));
1515  // Skip if we already have the key
1516  if (HaveKey(id)) {
1517  WalletLogPrintf("Already have key with pubkey %s, skipping\n", HexStr(pubkey));
1518  continue;
1519  }
1520  mapKeyMetadata[id].nCreateTime = timestamp;
1521  // If the private key is not present in the wallet, insert it.
1522  if (!AddKeyPubKeyWithDB(batch, key, pubkey)) {
1523  return false;
1524  }
1525  UpdateTimeFirstKey(timestamp);
1526  }
1527  return true;
1528 }
1529 
1530 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)
1531 {
1533  for (const auto& entry : key_origins) {
1534  AddKeyOriginWithDB(batch, entry.second.first, entry.second.second);
1535  }
1536  for (const CKeyID& id : ordered_pubkeys) {
1537  auto entry = pubkey_map.find(id);
1538  if (entry == pubkey_map.end()) {
1539  continue;
1540  }
1541  const CPubKey& pubkey = entry->second;
1542  CPubKey temp;
1543  if (GetPubKey(id, temp)) {
1544  // Already have pubkey, skipping
1545  WalletLogPrintf("Already have pubkey %s, skipping\n", HexStr(temp));
1546  continue;
1547  }
1548  if (!AddWatchOnlyWithDB(batch, GetScriptForRawPubKey(pubkey), timestamp)) {
1549  return false;
1550  }
1551  mapKeyMetadata[id].nCreateTime = timestamp;
1552 
1553  // Add to keypool only works with pubkeys
1554  if (add_keypool) {
1555  AddKeypoolPubkeyWithDB(pubkey, internal, batch);
1557  }
1558  }
1559  return true;
1560 }
1561 
1562 bool LegacyScriptPubKeyMan::ImportScriptPubKeys(const std::set<CScript>& script_pub_keys, const bool have_solving_data, const int64_t timestamp)
1563 {
1565  for (const CScript& script : script_pub_keys) {
1566  if (!have_solving_data || !IsMine(script)) { // Always call AddWatchOnly for non-solvable watch-only, so that watch timestamp gets updated
1567  if (!AddWatchOnlyWithDB(batch, script, timestamp)) {
1568  return false;
1569  }
1570  }
1571  }
1572  return true;
1573 }
1574 
1575 std::set<CKeyID> LegacyScriptPubKeyMan::GetKeys() const
1576 {
1577  LOCK(cs_KeyStore);
1578  if (!m_storage.HasEncryptionKeys()) {
1580  }
1581  std::set<CKeyID> set_address;
1582  for (const auto& mi : mapCryptedKeys) {
1583  set_address.insert(mi.first);
1584  }
1585  return set_address;
1586 }
1587 
1589 
1591 {
1592  // Returns true if this descriptor supports getting new addresses. Conditions where we may be unable to fetch them (e.g. locked) are caught later
1593  if (!CanGetAddresses(m_internal)) {
1594  error = "No addresses available";
1595  return false;
1596  }
1597  {
1598  LOCK(cs_desc_man);
1599  assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
1600  Optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
1601  assert(desc_addr_type);
1602  if (type != *desc_addr_type) {
1603  throw std::runtime_error(std::string(__func__) + ": Types are inconsistent");
1604  }
1605 
1606  TopUp();
1607 
1608  // Get the scriptPubKey from the descriptor
1609  FlatSigningProvider out_keys;
1610  std::vector<CScript> scripts_temp;
1611  if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
1612  // We can't generate anymore keys
1613  error = "Error: Keypool ran out, please call keypoolrefill first";
1614  return false;
1615  }
1616  if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1617  // We can't generate anymore keys
1618  error = "Error: Keypool ran out, please call keypoolrefill first";
1619  return false;
1620  }
1621 
1622  Optional<OutputType> out_script_type = m_wallet_descriptor.descriptor->GetOutputType();
1623  if (out_script_type && out_script_type == type) {
1624  ExtractDestination(scripts_temp[0], dest);
1625  } else {
1626  throw std::runtime_error(std::string(__func__) + ": Types are inconsistent. Stored type does not match type of newly generated address");
1627  }
1628  m_wallet_descriptor.next_index++;
1629  WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
1630  return true;
1631  }
1632 }
1633 
1635 {
1636  LOCK(cs_desc_man);
1637  if (m_map_script_pub_keys.count(script) > 0) {
1638  return ISMINE_SPENDABLE;
1639  }
1640  return ISMINE_NO;
1641 }
1642 
1643 bool DescriptorScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key, bool accept_no_keys)
1644 {
1645  LOCK(cs_desc_man);
1646  if (!m_map_keys.empty()) {
1647  return false;
1648  }
1649 
1650  bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
1651  bool keyFail = false;
1652  for (const auto& mi : m_map_crypted_keys) {
1653  const CPubKey &pubkey = mi.second.first;
1654  const std::vector<unsigned char> &crypted_secret = mi.second.second;
1655  CKey key;
1656  if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
1657  keyFail = true;
1658  break;
1659  }
1660  keyPass = true;
1661  if (m_decryption_thoroughly_checked)
1662  break;
1663  }
1664  if (keyPass && keyFail) {
1665  LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
1666  throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
1667  }
1668  if (keyFail || (!keyPass && !accept_no_keys)) {
1669  return false;
1670  }
1671  m_decryption_thoroughly_checked = true;
1672  return true;
1673 }
1674 
1676 {
1677  LOCK(cs_desc_man);
1678  if (!m_map_crypted_keys.empty()) {
1679  return false;
1680  }
1681 
1682  for (const KeyMap::value_type& key_in : m_map_keys)
1683  {
1684  const CKey &key = key_in.second;
1685  CPubKey pubkey = key.GetPubKey();
1686  CKeyingMaterial secret(key.begin(), key.end());
1687  std::vector<unsigned char> crypted_secret;
1688  if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
1689  return false;
1690  }
1691  m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1692  batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1693  }
1694  m_map_keys.clear();
1695  return true;
1696 }
1697 
1698 bool DescriptorScriptPubKeyMan::GetReservedDestination(const OutputType type, bool internal, CTxDestination& address, int64_t& index, CKeyPool& keypool)
1699 {
1700  LOCK(cs_desc_man);
1701  std::string error;
1702  bool result = GetNewDestination(type, address, error);
1703  index = m_wallet_descriptor.next_index - 1;
1704  return result;
1705 }
1706 
1707 void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
1708 {
1709  LOCK(cs_desc_man);
1710  // Only return when the index was the most recent
1711  if (m_wallet_descriptor.next_index - 1 == index) {
1712  m_wallet_descriptor.next_index--;
1713  }
1714  WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
1716 }
1717 
1718 std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
1719 {
1720  AssertLockHeld(cs_desc_man);
1722  KeyMap keys;
1723  for (auto key_pair : m_map_crypted_keys) {
1724  const CPubKey& pubkey = key_pair.second.first;
1725  const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
1726  CKey key;
1727  DecryptKey(m_storage.GetEncryptionKey(), crypted_secret, pubkey, key);
1728  keys[pubkey.GetID()] = key;
1729  }
1730  return keys;
1731  }
1732  return m_map_keys;
1733 }
1734 
1735 bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
1736 {
1737  LOCK(cs_desc_man);
1738  unsigned int target_size;
1739  if (size > 0) {
1740  target_size = size;
1741  } else {
1742  target_size = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 1);
1743  }
1744 
1745  // Calculate the new range_end
1746  int32_t new_range_end = std::max(m_wallet_descriptor.next_index + (int32_t)target_size, m_wallet_descriptor.range_end);
1747 
1748  // If the descriptor is not ranged, we actually just want to fill the first cache item
1749  if (!m_wallet_descriptor.descriptor->IsRange()) {
1750  new_range_end = 1;
1751  m_wallet_descriptor.range_end = 1;
1752  m_wallet_descriptor.range_start = 0;
1753  }
1754 
1755  FlatSigningProvider provider;
1756  provider.keys = GetKeys();
1757 
1759  uint256 id = GetID();
1760  for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
1761  FlatSigningProvider out_keys;
1762  std::vector<CScript> scripts_temp;
1763  DescriptorCache temp_cache;
1764  // Maybe we have a cached xpub and we can expand from the cache first
1765  if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1766  if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
1767  }
1768  // Add all of the scriptPubKeys to the scriptPubKey set
1769  for (const CScript& script : scripts_temp) {
1770  m_map_script_pub_keys[script] = i;
1771  }
1772  for (const auto& pk_pair : out_keys.pubkeys) {
1773  const CPubKey& pubkey = pk_pair.second;
1774  if (m_map_pubkeys.count(pubkey) != 0) {
1775  // We don't need to give an error here.
1776  // 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
1777  continue;
1778  }
1779  m_map_pubkeys[pubkey] = i;
1780  }
1781  // Write the cache
1782  for (const auto& parent_xpub_pair : temp_cache.GetCachedParentExtPubKeys()) {
1783  CExtPubKey xpub;
1784  if (m_wallet_descriptor.cache.GetCachedParentExtPubKey(parent_xpub_pair.first, xpub)) {
1785  if (xpub != parent_xpub_pair.second) {
1786  throw std::runtime_error(std::string(__func__) + ": New cached parent xpub does not match already cached parent xpub");
1787  }
1788  continue;
1789  }
1790  if (!batch.WriteDescriptorParentCache(parent_xpub_pair.second, id, parent_xpub_pair.first)) {
1791  throw std::runtime_error(std::string(__func__) + ": writing cache item failed");
1792  }
1793  m_wallet_descriptor.cache.CacheParentExtPubKey(parent_xpub_pair.first, parent_xpub_pair.second);
1794  }
1795  for (const auto& derived_xpub_map_pair : temp_cache.GetCachedDerivedExtPubKeys()) {
1796  for (const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
1797  CExtPubKey xpub;
1798  if (m_wallet_descriptor.cache.GetCachedDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, xpub)) {
1799  if (xpub != derived_xpub_pair.second) {
1800  throw std::runtime_error(std::string(__func__) + ": New cached derived xpub does not match already cached derived xpub");
1801  }
1802  continue;
1803  }
1804  if (!batch.WriteDescriptorDerivedCache(derived_xpub_pair.second, id, derived_xpub_map_pair.first, derived_xpub_pair.first)) {
1805  throw std::runtime_error(std::string(__func__) + ": writing cache item failed");
1806  }
1807  m_wallet_descriptor.cache.CacheDerivedExtPubKey(derived_xpub_map_pair.first, derived_xpub_pair.first, derived_xpub_pair.second);
1808  }
1809  }
1810  m_max_cached_index++;
1811  }
1812  m_wallet_descriptor.range_end = new_range_end;
1813  batch.WriteDescriptor(GetID(), m_wallet_descriptor);
1814 
1815  // By this point, the cache size should be the size of the entire range
1816  assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
1817 
1819  return true;
1820 }
1821 
1823 {
1824  LOCK(cs_desc_man);
1825  if (IsMine(script)) {
1826  int32_t index = m_map_script_pub_keys[script];
1827  if (index >= m_wallet_descriptor.next_index) {
1828  WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
1829  m_wallet_descriptor.next_index = index + 1;
1830  }
1831  if (!TopUp()) {
1832  WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1833  }
1834  }
1835 }
1836 
1838 {
1839  LOCK(cs_desc_man);
1841  if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
1842  throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
1843  }
1844 }
1845 
1847 {
1848  AssertLockHeld(cs_desc_man);
1850 
1851  if (m_storage.HasEncryptionKeys()) {
1852  if (m_storage.IsLocked()) {
1853  return false;
1854  }
1855 
1856  std::vector<unsigned char> crypted_secret;
1857  CKeyingMaterial secret(key.begin(), key.end());
1858  if (!EncryptSecret(m_storage.GetEncryptionKey(), secret, pubkey.GetHash(), crypted_secret)) {
1859  return false;
1860  }
1861 
1862  m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1863  return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1864  } else {
1865  m_map_keys[pubkey.GetID()] = key;
1866  return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
1867  }
1868 }
1869 
1871 {
1872  LOCK(cs_desc_man);
1874 
1875  // Ignore when there is already a descriptor
1876  if (m_wallet_descriptor.descriptor) {
1877  return false;
1878  }
1879 
1880  int64_t creation_time = GetTime();
1881 
1882  std::string xpub = EncodeExtPubKey(master_key.Neuter());
1883 
1884  // Build descriptor string
1885  std::string desc_prefix;
1886  std::string desc_suffix = "/*)";
1887  switch (addr_type) {
1888  case OutputType::LEGACY: {
1889  desc_prefix = "pkh(" + xpub + "/44'";
1890  break;
1891  }
1892  case OutputType::P2SH_SEGWIT: {
1893  desc_prefix = "sh(wpkh(" + xpub + "/49'";
1894  desc_suffix += ")";
1895  break;
1896  }
1897  case OutputType::BECH32: {
1898  desc_prefix = "wpkh(" + xpub + "/84'";
1899  break;
1900  }
1901  } // no default case, so the compiler can warn about missing cases
1902  assert(!desc_prefix.empty());
1903 
1904  // Mainnet derives at 0', testnet and regtest derive at 1'
1905  if (Params().IsTestChain()) {
1906  desc_prefix += "/1'";
1907  } else {
1908  desc_prefix += "/0'";
1909  }
1910 
1911  std::string internal_path = m_internal ? "/1" : "/0";
1912  std::string desc_str = desc_prefix + "/0'" + internal_path + desc_suffix;
1913 
1914  // Make the descriptor
1915  FlatSigningProvider keys;
1916  std::string error;
1917  std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, error, false);
1918  WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
1919  m_wallet_descriptor = w_desc;
1920 
1921  // Store the master private key, and descriptor
1923  if (!AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey())) {
1924  throw std::runtime_error(std::string(__func__) + ": writing descriptor master private key failed");
1925  }
1926  if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
1927  throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
1928  }
1929 
1930  // TopUp
1931  TopUp();
1932 
1934  return true;
1935 }
1936 
1938 {
1939  LOCK(cs_desc_man);
1940  return m_wallet_descriptor.descriptor->IsRange();
1941 }
1942 
1944 {
1945  // We can only give out addresses from descriptors that are single type (not combo), ranged,
1946  // and either have cached keys or can generate more keys (ignoring encryption)
1947  LOCK(cs_desc_man);
1948  return m_wallet_descriptor.descriptor->IsSingleType() &&
1949  m_wallet_descriptor.descriptor->IsRange() &&
1950  (HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
1951 }
1952 
1954 {
1955  LOCK(cs_desc_man);
1956  return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
1957 }
1958 
1960 {
1961  // This is only used for getwalletinfo output and isn't relevant to descriptor wallets.
1962  // The magic number 0 indicates that it shouldn't be displayed so that's what we return.
1963  return 0;
1964 }
1965 
1967 {
1968  if (m_internal) {
1969  return 0;
1970  }
1971  return GetKeyPoolSize();
1972 }
1973 
1975 {
1976  LOCK(cs_desc_man);
1977  return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
1978 }
1979 
1981 {
1982  LOCK(cs_desc_man);
1983  return m_wallet_descriptor.creation_time;
1984 }
1985 
1986 std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
1987 {
1988  LOCK(cs_desc_man);
1989 
1990  // Find the index of the script
1991  auto it = m_map_script_pub_keys.find(script);
1992  if (it == m_map_script_pub_keys.end()) {
1993  return nullptr;
1994  }
1995  int32_t index = it->second;
1996 
1997  return GetSigningProvider(index, include_private);
1998 }
1999 
2000 std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
2001 {
2002  LOCK(cs_desc_man);
2003 
2004  // Find index of the pubkey
2005  auto it = m_map_pubkeys.find(pubkey);
2006  if (it == m_map_pubkeys.end()) {
2007  return nullptr;
2008  }
2009  int32_t index = it->second;
2010 
2011  // Always try to get the signing provider with private keys. This function should only be called during signing anyways
2012  return GetSigningProvider(index, true);
2013 }
2014 
2015 std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
2016 {
2017  AssertLockHeld(cs_desc_man);
2018  // Get the scripts, keys, and key origins for this script
2019  std::unique_ptr<FlatSigningProvider> out_keys = MakeUnique<FlatSigningProvider>();
2020  std::vector<CScript> scripts_temp;
2021  if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
2022 
2023  if (HavePrivateKeys() && include_private) {
2024  FlatSigningProvider master_provider;
2025  master_provider.keys = GetKeys();
2026  m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
2027  }
2028 
2029  return out_keys;
2030 }
2031 
2032 std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
2033 {
2034  return GetSigningProvider(script, false);
2035 }
2036 
2038 {
2039  return IsMine(script);
2040 }
2041 
2042 bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const
2043 {
2044  std::unique_ptr<FlatSigningProvider> keys = MakeUnique<FlatSigningProvider>();
2045  for (const auto& coin_pair : coins) {
2046  std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
2047  if (!coin_keys) {
2048  continue;
2049  }
2050  *keys = Merge(*keys, *coin_keys);
2051  }
2052 
2053  return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
2054 }
2055 
2056 SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
2057 {
2058  std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
2059  if (!keys) {
2061  }
2062 
2063  CKey key;
2064  if (!keys->GetKey(ToKeyID(pkhash), key)) {
2066  }
2067 
2068  if (!MessageSign(key, message, str_sig)) {
2070  }
2071  return SigningResult::OK;
2072 }
2073 
2074 TransactionError DescriptorScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, int sighash_type, bool sign, bool bip32derivs, int* n_signed) const
2075 {
2076  if (n_signed) {
2077  *n_signed = 0;
2078  }
2079  for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
2080  const CTxIn& txin = psbtx.tx->vin[i];
2081  PSBTInput& input = psbtx.inputs.at(i);
2082 
2083  if (PSBTInputSigned(input)) {
2084  continue;
2085  }
2086 
2087  // Get the Sighash type
2088  if (sign && input.sighash_type > 0 && input.sighash_type != sighash_type) {
2090  }
2091 
2092  // Get the scriptPubKey to know which SigningProvider to use
2093  CScript script;
2094  if (!input.witness_utxo.IsNull()) {
2095  script = input.witness_utxo.scriptPubKey;
2096  } else if (input.non_witness_utxo) {
2097  if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
2099  }
2100  script = input.non_witness_utxo->vout[txin.prevout.n].scriptPubKey;
2101  } else {
2102  // There's no UTXO so we can just skip this now
2103  continue;
2104  }
2105  SignatureData sigdata;
2106  input.FillSignatureData(sigdata);
2107 
2108  std::unique_ptr<FlatSigningProvider> keys = MakeUnique<FlatSigningProvider>();
2109  std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, sign);
2110  if (script_keys) {
2111  *keys = Merge(*keys, *script_keys);
2112  } else {
2113  // Maybe there are pubkeys listed that we can sign for
2114  script_keys = MakeUnique<FlatSigningProvider>();
2115  for (const auto& pk_pair : input.hd_keypaths) {
2116  const CPubKey& pubkey = pk_pair.first;
2117  std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
2118  if (pk_keys) {
2119  *keys = Merge(*keys, *pk_keys);
2120  }
2121  }
2122  }
2123 
2124  SignPSBTInput(HidingSigningProvider(keys.get(), !sign, !bip32derivs), psbtx, i, sighash_type);
2125 
2126  bool signed_one = PSBTInputSigned(input);
2127  if (n_signed && (signed_one || !sign)) {
2128  // If sign is false, we assume that we _could_ sign if we get here. This
2129  // will never have false negatives; it is hard to tell under what i
2130  // circumstances it could have false positives.
2131  (*n_signed)++;
2132  }
2133  }
2134 
2135  // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
2136  for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
2137  std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
2138  if (!keys) {
2139  continue;
2140  }
2141  UpdatePSBTOutput(HidingSigningProvider(keys.get(), true, !bip32derivs), psbtx, i);
2142  }
2143 
2144  return TransactionError::OK;
2145 }
2146 
2147 std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
2148 {
2149  std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
2150  if (provider) {
2151  KeyOriginInfo orig;
2152  CKeyID key_id = GetKeyForDestination(*provider, dest);
2153  if (provider->GetKeyOrigin(key_id, orig)) {
2154  LOCK(cs_desc_man);
2155  std::unique_ptr<CKeyMetadata> meta = MakeUnique<CKeyMetadata>();
2156  meta->key_origin = orig;
2157  meta->has_key_origin = true;
2158  meta->nCreateTime = m_wallet_descriptor.creation_time;
2159  return meta;
2160  }
2161  }
2162  return nullptr;
2163 }
2164 
2166 {
2167  LOCK(cs_desc_man);
2168  std::string desc_str = m_wallet_descriptor.descriptor->ToString();
2169  uint256 id;
2170  CSHA256().Write((unsigned char*)desc_str.data(), desc_str.size()).Finalize(id.begin());
2171  return id;
2172 }
2173 
2175 {
2176  this->m_internal = internal;
2177 }
2178 
2180 {
2181  LOCK(cs_desc_man);
2182  m_wallet_descriptor.cache = cache;
2183  for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
2184  FlatSigningProvider out_keys;
2185  std::vector<CScript> scripts_temp;
2186  if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2187  throw std::runtime_error("Error: Unable to expand wallet descriptor from cache");
2188  }
2189  // Add all of the scriptPubKeys to the scriptPubKey set
2190  for (const CScript& script : scripts_temp) {
2191  if (m_map_script_pub_keys.count(script) != 0) {
2192  throw std::runtime_error(strprintf("Error: Already loaded script at index %d as being at index %d", i, m_map_script_pub_keys[script]));
2193  }
2194  m_map_script_pub_keys[script] = i;
2195  }
2196  for (const auto& pk_pair : out_keys.pubkeys) {
2197  const CPubKey& pubkey = pk_pair.second;
2198  if (m_map_pubkeys.count(pubkey) != 0) {
2199  // We don't need to give an error here.
2200  // 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
2201  continue;
2202  }
2203  m_map_pubkeys[pubkey] = i;
2204  }
2205  m_max_cached_index++;
2206  }
2207 }
2208 
2209 bool DescriptorScriptPubKeyMan::AddKey(const CKeyID& key_id, const CKey& key)
2210 {
2211  LOCK(cs_desc_man);
2212  m_map_keys[key_id] = key;
2213  return true;
2214 }
2215 
2216 bool DescriptorScriptPubKeyMan::AddCryptedKey(const CKeyID& key_id, const CPubKey& pubkey, const std::vector<unsigned char>& crypted_key)
2217 {
2218  LOCK(cs_desc_man);
2219  if (!m_map_keys.empty()) {
2220  return false;
2221  }
2222 
2223  m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
2224  return true;
2225 }
2226 
2228 {
2229  LOCK(cs_desc_man);
2230  return m_wallet_descriptor.descriptor != nullptr && desc.descriptor != nullptr && m_wallet_descriptor.descriptor->ToString() == desc.descriptor->ToString();
2231 }
2232 
2234 {
2235  LOCK(cs_desc_man);
2237  if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
2238  throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
2239  }
2240 }
2241 
2243 {
2244  return m_wallet_descriptor;
2245 }
2246 
2247 const std::vector<CScript> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
2248 {
2249  LOCK(cs_desc_man);
2250  std::vector<CScript> script_pub_keys;
2251  script_pub_keys.reserve(m_map_script_pub_keys.size());
2252 
2253  for (auto const& script_pub_key: m_map_script_pub_keys) {
2254  script_pub_keys.push_back(script_pub_key.first);
2255  }
2256  return script_pub_keys;
2257 }
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
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:171
std::string hdKeypath
Definition: walletdb.h:131
bool AddKeyPubKeyWithDB(WalletBatch &batch, const CKey &key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Adds a key to the store, and saves it to disk.
const std::unordered_map< uint32_t, ExtPubKeyMap > GetCachedDerivedExtPubKeys() const
Retrieve all cached derived xpubs.
void KeepDestination(int64_t index, const OutputType &type) override
void SignTransaction(CMutableTransaction &mtx, const SigningProvider *keystore, const std::map< COutPoint, Coin > &coins, const UniValue &hashType, UniValue &result)
Sign a transaction with the given keystore and previous transactions.
bool AddCryptedKey(const CKeyID &key_id, const CPubKey &pubkey, const std::vector< unsigned char > &crypted_key)
std::deque< CInv >::iterator it
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).
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:74
bool ImportScriptPubKeys(const std::set< CScript > &script_pub_keys, const bool have_solving_data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool LoadCScript(const CScript &redeemScript)
Adds a CScript to the store.
CScript scriptPubKey
Definition: transaction.h:132
bool AddKeyOriginWithDB(WalletBatch &batch, const CPubKey &pubkey, const KeyOriginInfo &info)
Add a KeyOriginInfo to the wallet.
bool SignTransaction(CMutableTransaction &tx, const std::map< COutPoint, Coin > &coins, int sighash, std::map< int, std::string > &input_errors) const override
Creates new signatures and adds them to the transaction.
bool DecryptKey(const CKeyingMaterial &vMasterKey, const std::vector< unsigned char > &vchCryptedSecret, const CPubKey &vchPubKey, CKey &key)
Definition: crypter.cpp:127
bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const override
CKey key
Definition: key.h:149
void SetInternal(bool internal) override
bool Derive(CExtKey &out, unsigned int nChild) const
Definition: key.cpp:293
Bilingual messages:
Definition: translation.h:16
isminetype IsMine(const CScript &script) const override
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
RecursiveMutex cs_KeyStore
uint256 GetID() const override
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:232
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:184
Optional< CMutableTransaction > tx
Definition: psbt.h:392
std::map< CKeyID, CKey > keys
bool CheckDecryptionKey(const CKeyingMaterial &master_key, bool accept_no_keys=false) override
Check that the given decryption key is valid for this ScriptPubKeyMan, i.e. it decrypts all of the ke...
SigningResult
Definition: message.h:42
int64_t GetOldestKeyPoolTime() const override
FlatSigningProvider Merge(const FlatSigningProvider &a, const FlatSigningProvider &b)
bool WriteHDChain(const CHDChain &chain)
write the hdchain model (external chain child index counter)
Definition: walletdb.cpp:974
void AddKeypoolPubkeyWithDB(const CPubKey &pubkey, const bool internal, WalletBatch &batch)
virtual bool AddCScript(const CScript &redeemScript)
Definition: key.h:144
bool SignPSBTInput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index, int sighash, SignatureData *out_sigdata, bool use_dummy)
Signs a PSBTInput, verifying that all provided data matches what is being signed. ...
Definition: psbt.cpp:227
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
Definition: walletdb.cpp:148
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
uint256 GetHash() const
Get the 256-bit hash of this public key.
Definition: pubkey.h:165
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that...
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: crypter.h:61
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
bool SetupDescriptorGeneration(const CExtKey &master_key, OutputType addr_type)
Setup descriptors based on the given CExtkey.
unsigned int GetKeyPoolSize() const override
bool CanGetAddresses(bool internal=false) const override
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:166
virtual std::set< CKeyID > GetKeys() const
uint256 GetID() const override
CKeyID GetKeyForDestination(const SigningProvider &store, const CTxDestination &dest)
Return the CKeyID of the key involved in a script (if there is a unique one).
uint32_t nExternalChainCounter
Definition: walletdb.h: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 unsigned char * begin() const
Definition: key.h:89
const WalletDescriptor GetWalletDescriptor() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
virtual WalletDatabase & GetDatabase() const =0
virtual bool IsWalletFlagSet(uint64_t) const =0
unsigned char * begin()
Definition: uint256.h:58
bool RemoveWatchOnly(const CScript &dest)
Remove a watch only script from the keystore.
std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const override
KeyMap GetKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
unspendable OP_RETURN script that carries data
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:159
bool IsNull() const
Definition: uint256.h:31
OutputType
Definition: outputtype.h:17
bool IsHDEnabled() const override
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Adds a key to the store, and saves it to disk.
void AddInactiveHDChain(const CHDChain &chain)
bool IsNull() const
Definition: transaction.h:149
Access to the wallet database.
Definition: walletdb.h:177
static bool ExtractPubKey(const CScript &dest, CPubKey &pubKeyOut)
TransactionError FillPSBT(PartiallySignedTransaction &psbt, int sighash_type=1, bool sign=true, bool bip32derivs=false, int *n_signed=nullptr) const override
Adds script and derivation path information to a PSBT, and optionally signs it.
void WalletLogPrintf(std::string fmt, Params... parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
void MarkPreSplitKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< unsigned char > &secret)
Definition: walletdb.cpp:218
bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch) override
const std::vector< CScript > GetScriptPubKeys() const
int64_t GetOldestKeyPoolTime() const override
bool AddWatchOnlyWithDB(WalletBatch &batch, const CScript &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:71
unsigned int GetKeyPoolSize() const override
bool TopUpInactiveHDChain(const CKeyID seed_id, int64_t index, bool internal)
Like TopUp() but adds keys for inactive HD chains.
bool MessageSign(const CKey &privkey, const std::string &message, std::string &signature)
Sign a message.
Definition: message.cpp:56
bool IsHDEnabled() const override
IsMineSigVersion
This is an enum that tracks the execution context of a script, similar to SigVersion in script/interp...
size_t KeypoolCountExternalKeys() const override
int64_t nTime
The time at which the key was generated. Set in AddKeypoolPubKeyWithDB.
bool Upgrade(int prev_version, bilingual_str &error) override
Upgrades the wallet to the specified version.
void UpdateTimeFirstKey(int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Update wallet first key creation time.
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
Definition: walletdb.cpp:143
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that...
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
Adds an encrypted key to the store, and saves it to disk.
An input of a transaction.
Definition: transaction.h:65
bool AddWatchOnlyInMem(const CScript &dest)
#define LOCK(cs)
Definition: sync.h: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)
bool IsValid() const
Definition: pubkey.h:175
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:56
An encapsulated public key.
Definition: pubkey.h:31
std::map< CKeyID, CPubKey > pubkeys
uint32_t n
Definition: transaction.h:30
void SetHDSeed(const CPubKey &key)
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:157
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses, and other watch only things, and is therefore "blank.".
Definition: walletutil.h:58
void ReturnDestination(int64_t index, bool internal, const CTxDestination &addr) override
void ImplicitlyLearnRelatedKeyScripts(const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool m_pre_split
Whether this key was generated for a keypool before the wallet was upgraded to HD-split.
bool GetKey(const CKeyID &address, CKey &keyOut) const override
A structure for PSBTs which contain per-input information.
Definition: psbt.h:48
isminetype
IsMine() return codes.
Definition: ismine.h:18
unsigned int size() const
Simple read-only vector-like interface.
Definition: key.h:88
void MarkUnusedAddresses(const CScript &script) override
Mark unused addresses as being used.
void UpdatePSBTOutput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index)
Updates a PSBTOutput with information from provider.
Definition: psbt.cpp:208
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:301
Descriptor with some wallet metadata.
Definition: walletutil.h:71
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 HasWalletDescriptor(const WalletDescriptor &desc) const
bool HavePrivateKeys() const override
bool WriteKeyMetadata(const CKeyMetadata &meta, const CPubKey &pubkey, const bool overwrite)
Definition: walletdb.cpp:92
virtual bool GetKey(const CKeyID &address, CKey &keyOut) const override
std::map< int64_t, CKeyID > m_index_to_reserved_key
bool IsSolvable(const SigningProvider &provider, const CScript &script)
Definition: sign.cpp:437
CRIPEMD160 & Write(const unsigned char *data, size_t len)
Definition: ripemd160.cpp:247
bool AddCScript(const CScript &redeemScript) override
std::vector< CKeyID > GetAffectedKeys(const CScript &spk, const SigningProvider &provider)
int nVersion
Definition: walletdb.h: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:191
bool WritePool(int64_t nPool, const CKeyPool &keypool)
Definition: walletdb.cpp:186
256-bit opaque blob.
Definition: uint256.h:124
bool GetReservedDestination(const OutputType type, bool internal, CTxDestination &address, int64_t &index, CKeyPool &keypool) override
CPubKey vchPubKey
The public key.
bool LoadKey(const CKey &key, const CPubKey &pubkey)
Adds a key to the store, without saving it to disk (used by LoadWallet)
virtual bool CanSupportFeature(enum WalletFeature) const =0
void SetCache(const DescriptorCache &cache)
bool HaveWatchOnly() const
Returns whether there are any watch-only things in the wallet.
std::string EncodeExtPubKey(const CExtPubKey &key)
Definition: key_io.cpp:176
bool IsTestChain() const
If this chain is exclusively used for testing.
Definition: chainparams.h:75
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible...
An interface to be implemented by keystores that support signing.
CExtPubKey Neuter() const
Definition: key.cpp:312
bool ParseHDKeypath(const std::string &keypath_str, std::vector< uint32_t > &keypath)
Parse an HD keypaths like "m/7/0&#39;/2000".
Definition: bip32.cpp:12
const CChainParams & Params()
Return the currently selected parameters.
Cache for single descriptor&#39;s derived extended pubkeys.
Definition: descriptor.h:19
bool GetNewDestination(const OutputType type, CTxDestination &dest, std::string &error) override
bool HaveKey(const CKeyID &address) const override
std::map< CKeyID, CKey > KeyMap
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
void AddHDChain(const CHDChain &chain)
std::string WriteHDKeypath(const std::vector< uint32_t > &keypath)
Write HD keypaths as strings.
Definition: bip32.cpp:63
std::unique_ptr< FlatSigningProvider > GetSigningProvider(const CScript &script, bool include_private=false) const
const unsigned char * end() const
Definition: key.h:90
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:466
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:76
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:181
int64_t GetTimeFirstKey() const override
static const int VERSION_HD_CHAIN_SPLIT
Definition: walletdb.h:94
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:88
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:210
virtual bool HasEncryptionKeys() const =0
A mutable version of CTransaction.
Definition: transaction.h:353
size_type size() const
Definition: prevector.h:282
virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed.
Definition: psbt.cpp:192
bool SignTransaction(CMutableTransaction &tx, const std::map< COutPoint, Coin > &coins, int sighash, std::map< int, std::string > &input_errors) const override
Creates new signatures and adds them to the transaction.
void DeriveNewChildKey(WalletBatch &batch, CKeyMetadata &metadata, CKey &secret, CHDChain &hd_chain, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
std::vector< unsigned char > valtype
bool SetupGeneration(bool force=false) override
Sets up the key generation stuff, i.e.
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:97
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)
void FillSignatureData(SignatureData &sigdata) const
Definition: psbt.cpp:80
bool TopUp(unsigned int size=0) override
Fills internal address pool.
WalletStorage & m_storage
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: ripemd160.cpp:273
boost::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:214
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:61
CKeyID seed_id
seed hash160
Definition: walletdb.h:91
A hasher class for SHA-256.
Definition: sha256.h:13
bool ImportPrivKeys(const std::map< CKeyID, CKey > &privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
const ExtPubKeyMap GetCachedParentExtPubKeys() const
Retrieve all cached parent xpubs.
int64_t GetTime()
Return system time (or mocked time, if set)
Definition: time.cpp:23
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
virtual void SetMinVersion(enum WalletFeature, WalletBatch *=nullptr, bool=false)=0
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
bool error(const char *fmt, const Args &... args)
Definition: system.h:52
bool AddCScriptWithDB(WalletBatch &batch, const CScript &script)
Adds a script to the store and saves it to disk.
int nVersion
Definition: walletdb.h:96
size_t KeypoolCountExternalKeys() const override
bool fDecryptionThoroughlyChecked
keeps track of whether Unlock has run a thorough check before
bool fInternal
Whether this keypool entry is in the internal keypool (for change outputs)
std::set< CKeyID > GetKeys() const override
static const int VERSION_HD_BASE
Definition: walletdb.h:93
isminetype IsMine(const CScript &script) const override
bool ImportScripts(const std::set< CScript > scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input. May contain all signatures necessary for producing a ...
Definition: sign.h: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:207
std::map< CKeyID, int64_t > m_pool_key_to_index
A key from a CWallet&#39;s keypool.
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const override
Sign a message with the given script.
bool HaveWatchOnly(const CScript &dest) const
Returns whether the watch-only script is in the wallet.
const uint32_t BIP32_HARDENED_KEY_LIMIT
Value for the first BIP 32 hardened derivation. Can be used as a bit mask and as a value...
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:184
virtual bool HaveKey(const CKeyID &address) const override