Bitcoin Core  31.0.0
P2P Digital Currency
scriptpubkeyman.cpp
Go to the documentation of this file.
1 // Copyright (c) 2019-present 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 <hash.h>
6 #include <key_io.h>
7 #include <logging.h>
8 #include <node/types.h>
9 #include <outputtype.h>
10 #include <script/descriptor.h>
11 #include <script/script.h>
12 #include <script/sign.h>
13 #include <script/solver.h>
14 #include <util/bip32.h>
15 #include <util/check.h>
16 #include <util/strencodings.h>
17 #include <util/string.h>
18 #include <util/time.h>
19 #include <util/translation.h>
20 #include <wallet/scriptpubkeyman.h>
21 
22 #include <optional>
23 
24 using common::PSBTError;
25 using util::ToString;
26 
27 namespace wallet {
28 
29 typedef std::vector<unsigned char> valtype;
30 
31 // Legacy wallet IsMine(). Used only in migration
32 // DO NOT USE ANYTHING IN THIS NAMESPACE OUTSIDE OF MIGRATION
33 namespace {
34 
41 enum class IsMineSigVersion
42 {
43  TOP = 0,
44  P2SH = 1,
45  WITNESS_V0 = 2,
46 };
47 
53 enum class IsMineResult
54 {
55  NO = 0,
56  WATCH_ONLY = 1,
57  SPENDABLE = 2,
58  INVALID = 3,
59 };
60 
61 bool PermitsUncompressed(IsMineSigVersion sigversion)
62 {
63  return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
64 }
65 
66 bool HaveKeys(const std::vector<valtype>& pubkeys, const LegacyDataSPKM& keystore)
67 {
68  for (const valtype& pubkey : pubkeys) {
69  CKeyID keyID = CPubKey(pubkey).GetID();
70  if (!keystore.HaveKey(keyID)) return false;
71  }
72  return true;
73 }
74 
83 // NOLINTNEXTLINE(misc-no-recursion)
84 IsMineResult LegacyWalletIsMineInnerDONOTUSE(const LegacyDataSPKM& keystore, const CScript& scriptPubKey, IsMineSigVersion sigversion, bool recurse_scripthash=true)
85 {
86  IsMineResult ret = IsMineResult::NO;
87 
88  std::vector<valtype> vSolutions;
89  TxoutType whichType = Solver(scriptPubKey, vSolutions);
90 
91  CKeyID keyID;
92  switch (whichType) {
97  case TxoutType::ANCHOR:
98  break;
99  case TxoutType::PUBKEY:
100  keyID = CPubKey(vSolutions[0]).GetID();
101  if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
102  return IsMineResult::INVALID;
103  }
104  if (keystore.HaveKey(keyID)) {
105  ret = std::max(ret, IsMineResult::SPENDABLE);
106  }
107  break;
109  {
110  if (sigversion == IsMineSigVersion::WITNESS_V0) {
111  // P2WPKH inside P2WSH is invalid.
112  return IsMineResult::INVALID;
113  }
114  if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
115  // We do not support bare witness outputs unless the P2SH version of it would be
116  // acceptable as well. This protects against matching before segwit activates.
117  // This also applies to the P2WSH case.
118  break;
119  }
120  ret = std::max(ret, LegacyWalletIsMineInnerDONOTUSE(keystore, GetScriptForDestination(PKHash(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0));
121  break;
122  }
124  keyID = CKeyID(uint160(vSolutions[0]));
125  if (!PermitsUncompressed(sigversion)) {
126  CPubKey pubkey;
127  if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
128  return IsMineResult::INVALID;
129  }
130  }
131  if (keystore.HaveKey(keyID)) {
132  ret = std::max(ret, IsMineResult::SPENDABLE);
133  }
134  break;
136  {
137  if (sigversion != IsMineSigVersion::TOP) {
138  // P2SH inside P2WSH or P2SH is invalid.
139  return IsMineResult::INVALID;
140  }
141  CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
142  CScript subscript;
143  if (keystore.GetCScript(scriptID, subscript)) {
144  ret = std::max(ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
145  }
146  break;
147  }
149  {
150  if (sigversion == IsMineSigVersion::WITNESS_V0) {
151  // P2WSH inside P2WSH is invalid.
152  return IsMineResult::INVALID;
153  }
154  if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) {
155  break;
156  }
157  CScriptID scriptID{RIPEMD160(vSolutions[0])};
158  CScript subscript;
159  if (keystore.GetCScript(scriptID, subscript)) {
160  ret = std::max(ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::WITNESS_V0) : IsMineResult::SPENDABLE);
161  }
162  break;
163  }
164 
165  case TxoutType::MULTISIG:
166  {
167  // Never treat bare multisig outputs as ours (they can still be made watchonly-though)
168  if (sigversion == IsMineSigVersion::TOP) {
169  break;
170  }
171 
172  // Only consider transactions "mine" if we own ALL the
173  // keys involved. Multi-signature transactions that are
174  // partially owned (somebody else has a key that can spend
175  // them) enable spend-out-from-under-you attacks, especially
176  // in shared-wallet situations.
177  std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
178  if (!PermitsUncompressed(sigversion)) {
179  for (size_t i = 0; i < keys.size(); i++) {
180  if (keys[i].size() != 33) {
181  return IsMineResult::INVALID;
182  }
183  }
184  }
185  if (HaveKeys(keys, keystore)) {
186  ret = std::max(ret, IsMineResult::SPENDABLE);
187  }
188  break;
189  }
190  } // no default case, so the compiler can warn about missing cases
191 
192  if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
193  ret = std::max(ret, IsMineResult::WATCH_ONLY);
194  }
195  return ret;
196 }
197 
198 } // namespace
199 
201 {
202  switch (LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP)) {
204  case IsMineResult::NO:
205  return false;
206  case IsMineResult::WATCH_ONLY:
207  case IsMineResult::SPENDABLE:
208  return true;
209  }
210  assert(false);
211 }
212 
214 {
215  {
216  LOCK(cs_KeyStore);
217  assert(mapKeys.empty());
218 
219  bool keyPass = mapCryptedKeys.empty(); // Always pass when there are no encrypted keys
220  bool keyFail = false;
221  CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
223  for (; mi != mapCryptedKeys.end(); ++mi)
224  {
225  const CPubKey &vchPubKey = (*mi).second.first;
226  const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
227  CKey key;
228  if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
229  {
230  keyFail = true;
231  break;
232  }
233  keyPass = true;
235  break;
236  else {
237  // Rewrite these encrypted keys with checksums
238  batch.WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
239  }
240  }
241  if (keyPass && keyFail)
242  {
243  LogWarning("The wallet is probably corrupted: Some keys decrypt but not all.");
244  throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
245  }
246  if (keyFail || !keyPass)
247  return false;
249  }
250  return true;
251 }
252 
253 std::unique_ptr<SigningProvider> LegacyDataSPKM::GetSolvingProvider(const CScript& script) const
254 {
255  return std::make_unique<LegacySigningProvider>(*this);
256 }
257 
259 {
260  IsMineResult ismine = LegacyWalletIsMineInnerDONOTUSE(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
261  if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
262  // If ismine, it means we recognize keys or script ids in the script, or
263  // are watching the script itself, and we can at least provide metadata
264  // or solving information, even if not able to sign fully.
265  return true;
266  } else {
267  // If, given the stuff in sigdata, we could make a valid signature, then we can provide for this script
269  if (!sigdata.signatures.empty()) {
270  // If we could make signatures, make sure we have a private key to actually make a signature
271  bool has_privkeys = false;
272  for (const auto& key_sig_pair : sigdata.signatures) {
273  has_privkeys |= HaveKey(key_sig_pair.first);
274  }
275  return has_privkeys;
276  }
277  return false;
278  }
279 }
280 
281 bool LegacyDataSPKM::LoadKey(const CKey& key, const CPubKey &pubkey)
282 {
283  return AddKeyPubKeyInner(key, pubkey);
284 }
285 
286 bool LegacyDataSPKM::LoadCScript(const CScript& redeemScript)
287 {
288  /* A sanity check was added in pull #3843 to avoid adding redeemScripts
289  * that never can be redeemed. However, old wallets may still contain
290  * these. Do not add them to the wallet and warn. */
291  if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
292  {
293  std::string strAddr = EncodeDestination(ScriptHash(redeemScript));
294  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);
295  return true;
296  }
297 
298  return FillableSigningProvider::AddCScript(redeemScript);
299 }
300 
301 void LegacyDataSPKM::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
302 {
303  LOCK(cs_KeyStore);
304  mapKeyMetadata[keyID] = meta;
305 }
306 
307 void LegacyDataSPKM::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata& meta)
308 {
309  LOCK(cs_KeyStore);
310  m_script_metadata[script_id] = meta;
311 }
312 
313 bool LegacyDataSPKM::AddKeyPubKeyInner(const CKey& key, const CPubKey& pubkey)
314 {
315  LOCK(cs_KeyStore);
316  return FillableSigningProvider::AddKeyPubKey(key, pubkey);
317 }
318 
319 bool LegacyDataSPKM::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid)
320 {
321  // Set fDecryptionThoroughlyChecked to false when the checksum is invalid
322  if (!checksum_valid) {
324  }
325 
326  return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
327 }
328 
329 bool LegacyDataSPKM::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
330 {
331  LOCK(cs_KeyStore);
332  assert(mapKeys.empty());
333 
334  mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
336  return true;
337 }
338 
339 bool LegacyDataSPKM::HaveWatchOnly(const CScript &dest) const
340 {
341  LOCK(cs_KeyStore);
342  return setWatchOnly.contains(dest);
343 }
344 
346 {
347  return AddWatchOnlyInMem(dest);
348 }
349 
350 static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut)
351 {
352  std::vector<std::vector<unsigned char>> solutions;
353  return Solver(dest, solutions) == TxoutType::PUBKEY &&
354  (pubKeyOut = CPubKey(solutions[0])).IsFullyValid();
355 }
356 
358 {
359  LOCK(cs_KeyStore);
360  setWatchOnly.insert(dest);
361  CPubKey pubKey;
362  if (ExtractPubKey(dest, pubKey)) {
363  mapWatchKeys[pubKey.GetID()] = pubKey;
365  }
366  return true;
367 }
368 
370 {
371  LOCK(cs_KeyStore);
372  m_hd_chain = chain;
373 }
374 
376 {
377  LOCK(cs_KeyStore);
378  assert(!chain.seed_id.IsNull());
379  m_inactive_hd_chains[chain.seed_id] = chain;
380 }
381 
382 bool LegacyDataSPKM::HaveKey(const CKeyID &address) const
383 {
384  LOCK(cs_KeyStore);
385  if (!m_storage.HasEncryptionKeys()) {
386  return FillableSigningProvider::HaveKey(address);
387  }
388  return mapCryptedKeys.contains(address);
389 }
390 
391 bool LegacyDataSPKM::GetKey(const CKeyID &address, CKey& keyOut) const
392 {
393  LOCK(cs_KeyStore);
394  if (!m_storage.HasEncryptionKeys()) {
395  return FillableSigningProvider::GetKey(address, keyOut);
396  }
397 
398  CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
399  if (mi != mapCryptedKeys.end())
400  {
401  const CPubKey &vchPubKey = (*mi).second.first;
402  const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
403  return m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
404  return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey, keyOut);
405  });
406  }
407  return false;
408 }
409 
410 bool LegacyDataSPKM::GetKeyOrigin(const CKeyID& keyID, KeyOriginInfo& info) const
411 {
412  CKeyMetadata meta;
413  {
414  LOCK(cs_KeyStore);
415  auto it = mapKeyMetadata.find(keyID);
416  if (it == mapKeyMetadata.end()) {
417  return false;
418  }
419  meta = it->second;
420  }
421  if (meta.has_key_origin) {
422  std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4, info.fingerprint);
423  info.path = meta.key_origin.path;
424  } else { // Single pubkeys get the master fingerprint of themselves
425  std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
426  }
427  return true;
428 }
429 
430 bool LegacyDataSPKM::GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
431 {
432  LOCK(cs_KeyStore);
433  WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
434  if (it != mapWatchKeys.end()) {
435  pubkey_out = it->second;
436  return true;
437  }
438  return false;
439 }
440 
441 bool LegacyDataSPKM::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
442 {
443  LOCK(cs_KeyStore);
444  if (!m_storage.HasEncryptionKeys()) {
445  if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
446  return GetWatchPubKey(address, vchPubKeyOut);
447  }
448  return true;
449  }
450 
451  CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
452  if (mi != mapCryptedKeys.end())
453  {
454  vchPubKeyOut = (*mi).second.first;
455  return true;
456  }
457  // Check for watch-only pubkeys
458  return GetWatchPubKey(address, vchPubKeyOut);
459 }
460 
461 std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetCandidateScriptPubKeys() const
462 {
463  LOCK(cs_KeyStore);
464  std::unordered_set<CScript, SaltedSipHasher> candidate_spks;
465 
466  // For every private key in the wallet, there should be a P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH
467  const auto& add_pubkey = [&candidate_spks](const CPubKey& pub) -> void {
468  candidate_spks.insert(GetScriptForRawPubKey(pub));
469  candidate_spks.insert(GetScriptForDestination(PKHash(pub)));
470 
472  candidate_spks.insert(wpkh);
473  candidate_spks.insert(GetScriptForDestination(ScriptHash(wpkh)));
474  };
475  for (const auto& [_, key] : mapKeys) {
476  add_pubkey(key.GetPubKey());
477  }
478  for (const auto& [_, ckeypair] : mapCryptedKeys) {
479  add_pubkey(ckeypair.first);
480  }
481 
482  // mapScripts contains all redeemScripts and witnessScripts. Therefore each script in it has
483  // itself, P2SH, P2WSH, and P2SH-P2WSH as a candidate.
484  // Invalid scripts such as P2SH-P2SH and P2WSH-P2SH, among others, will be added as candidates.
485  // Callers of this function will need to remove such scripts.
486  const auto& add_script = [&candidate_spks](const CScript& script) -> void {
487  candidate_spks.insert(script);
488  candidate_spks.insert(GetScriptForDestination(ScriptHash(script)));
489 
491  candidate_spks.insert(wsh);
492  candidate_spks.insert(GetScriptForDestination(ScriptHash(wsh)));
493  };
494  for (const auto& [_, script] : mapScripts) {
495  add_script(script);
496  }
497 
498  // Although setWatchOnly should only contain output scripts, we will also include each script's
499  // P2SH, P2WSH, and P2SH-P2WSH as a precaution.
500  for (const auto& script : setWatchOnly) {
501  add_script(script);
502  }
503 
504  return candidate_spks;
505 }
506 
507 std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetScriptPubKeys() const
508 {
509  // Run IsMine() on each candidate output script. Any script that IsMine is an output
510  // script to return.
511  // This both filters out things that are not watched by the wallet, and things that are invalid.
512  std::unordered_set<CScript, SaltedSipHasher> spks;
513  for (const CScript& script : GetCandidateScriptPubKeys()) {
514  if (IsMine(script)) {
515  spks.insert(script);
516  }
517  }
518 
519  return spks;
520 }
521 
522 std::unordered_set<CScript, SaltedSipHasher> LegacyDataSPKM::GetNotMineScriptPubKeys() const
523 {
524  LOCK(cs_KeyStore);
525  std::unordered_set<CScript, SaltedSipHasher> spks;
526  for (const CScript& script : setWatchOnly) {
527  if (!IsMine(script)) spks.insert(script);
528  }
529  return spks;
530 }
531 
532 std::optional<MigrationData> LegacyDataSPKM::MigrateToDescriptor()
533 {
534  LOCK(cs_KeyStore);
535  if (m_storage.IsLocked()) {
536  return std::nullopt;
537  }
538 
540 
541  std::unordered_set<CScript, SaltedSipHasher> spks{GetScriptPubKeys()};
542 
543  // Get all key ids
544  std::set<CKeyID> keyids;
545  for (const auto& key_pair : mapKeys) {
546  keyids.insert(key_pair.first);
547  }
548  for (const auto& key_pair : mapCryptedKeys) {
549  keyids.insert(key_pair.first);
550  }
551 
552  // Get key metadata and figure out which keys don't have a seed
553  // Note that we do not ignore the seeds themselves because they are considered IsMine!
554  for (auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
555  const CKeyID& keyid = *keyid_it;
556  const auto& it = mapKeyMetadata.find(keyid);
557  if (it != mapKeyMetadata.end()) {
558  const CKeyMetadata& meta = it->second;
559  if (meta.hdKeypath == "s" || meta.hdKeypath == "m") {
560  keyid_it++;
561  continue;
562  }
563  if (!meta.hd_seed_id.IsNull() && (m_hd_chain.seed_id == meta.hd_seed_id || m_inactive_hd_chains.contains(meta.hd_seed_id))) {
564  keyid_it = keyids.erase(keyid_it);
565  continue;
566  }
567  }
568  keyid_it++;
569  }
570 
572  if (!batch.TxnBegin()) {
573  LogWarning("Error generating descriptors for migration, cannot initialize db transaction");
574  return std::nullopt;
575  }
576 
577  // keyids is now all non-HD keys. Each key will have its own combo descriptor
578  for (const CKeyID& keyid : keyids) {
579  CKey key;
580  if (!GetKey(keyid, key)) {
581  assert(false);
582  }
583 
584  // Get birthdate from key meta
585  uint64_t creation_time = 0;
586  const auto& it = mapKeyMetadata.find(keyid);
587  if (it != mapKeyMetadata.end()) {
588  creation_time = it->second.nCreateTime;
589  }
590 
591  // Get the key origin
592  // Maybe this doesn't matter because floating keys here shouldn't have origins
593  KeyOriginInfo info;
594  bool has_info = GetKeyOrigin(keyid, info);
595  std::string origin_str = has_info ? "[" + HexStr(info.fingerprint) + FormatHDKeypath(info.path) + "]" : "";
596 
597  // Construct the combo descriptor
598  std::string desc_str = "combo(" + origin_str + HexStr(key.GetPubKey()) + ")";
599  FlatSigningProvider keys;
600  std::string error;
601  std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, error, false);
602  CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
603  WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);
604 
605  // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
606  auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
607  WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, key, key.GetPubKey()));
608  desc_spk_man->TopUpWithDB(batch);
609  auto desc_spks = desc_spk_man->GetScriptPubKeys();
610 
611  // Remove the scriptPubKeys from our current set
612  for (const CScript& spk : desc_spks) {
613  size_t erased = spks.erase(spk);
614  assert(erased == 1);
615  assert(IsMine(spk));
616  }
617 
618  out.desc_spkms.push_back(std::move(desc_spk_man));
619  }
620 
621  // Handle HD keys by using the CHDChains
622  std::vector<CHDChain> chains;
623  chains.push_back(m_hd_chain);
624  for (const auto& chain_pair : m_inactive_hd_chains) {
625  chains.push_back(chain_pair.second);
626  }
627 
628  bool can_support_hd_split_feature = m_hd_chain.nVersion >= CHDChain::VERSION_HD_CHAIN_SPLIT;
629 
630  for (const CHDChain& chain : chains) {
631  for (int i = 0; i < 2; ++i) {
632  // Skip if doing internal chain and split chain is not supported
633  if (chain.seed_id.IsNull() || (i == 1 && !can_support_hd_split_feature)) {
634  continue;
635  }
636  // Get the master xprv
637  CKey seed_key;
638  if (!GetKey(chain.seed_id, seed_key)) {
639  assert(false);
640  }
641  CExtKey master_key;
642  master_key.SetSeed(seed_key);
643 
644  // Make the combo descriptor
645  std::string xpub = EncodeExtPubKey(master_key.Neuter());
646  std::string desc_str = "combo(" + xpub + "/0h/" + ToString(i) + "h/*h)";
647  FlatSigningProvider keys;
648  std::string error;
649  std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, error, false);
650  CHECK_NONFATAL(descs.size() == 1); // It shouldn't be possible to have an invalid or multipath descriptor
651  uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
652  WalletDescriptor w_desc(std::move(descs.at(0)), 0, 0, chain_counter, 0);
653 
654  // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
655  auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
656  WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey()));
657  desc_spk_man->TopUpWithDB(batch);
658  auto desc_spks = desc_spk_man->GetScriptPubKeys();
659 
660  // Remove the scriptPubKeys from our current set
661  for (const CScript& spk : desc_spks) {
662  size_t erased = spks.erase(spk);
663  assert(erased == 1);
664  assert(IsMine(spk));
665  }
666 
667  out.desc_spkms.push_back(std::move(desc_spk_man));
668  }
669  }
670  // Add the current master seed to the migration data
671  if (!m_hd_chain.seed_id.IsNull()) {
672  CKey seed_key;
673  if (!GetKey(m_hd_chain.seed_id, seed_key)) {
674  assert(false);
675  }
676  out.master_key.SetSeed(seed_key);
677  }
678 
679  // Handle the rest of the scriptPubKeys which must be imports and may not have all info
680  for (auto it = spks.begin(); it != spks.end();) {
681  const CScript& spk = *it;
682 
683  // Get birthdate from script meta
684  uint64_t creation_time = 0;
685  const auto& mit = m_script_metadata.find(CScriptID(spk));
686  if (mit != m_script_metadata.end()) {
687  creation_time = mit->second.nCreateTime;
688  }
689 
690  // InferDescriptor as that will get us all the solving info if it is there
691  std::unique_ptr<Descriptor> desc = InferDescriptor(spk, *GetSolvingProvider(spk));
692 
693  // Past bugs in InferDescriptor have caused it to create descriptors which cannot be re-parsed.
694  // Re-parse the descriptors to detect that, and skip any that do not parse.
695  {
696  std::string desc_str = desc->ToString();
697  FlatSigningProvider parsed_keys;
698  std::string parse_error;
699  std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error);
700  if (parsed_descs.empty()) {
701  // Remove this scriptPubKey from the set
702  it = spks.erase(it);
703  continue;
704  }
705  }
706 
707  // Get the private keys for this descriptor
708  std::vector<CScript> scripts;
709  FlatSigningProvider keys;
710  if (!desc->Expand(0, DUMMY_SIGNING_PROVIDER, scripts, keys)) {
711  assert(false);
712  }
713  std::set<CKeyID> privkeyids;
714  for (const auto& key_orig_pair : keys.origins) {
715  privkeyids.insert(key_orig_pair.first);
716  }
717 
718  std::vector<CScript> desc_spks;
719 
720  // If we can't provide all private keys for this inferred descriptor,
721  // but this wallet is not watch-only, migrate it to the watch-only wallet.
722  if (!desc->HavePrivateKeys(*this) && !m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
723  out.watch_descs.emplace_back(desc->ToString(), creation_time);
724 
725  // Get the scriptPubKeys without writing this to the wallet
726  FlatSigningProvider provider;
727  desc->Expand(0, provider, desc_spks, provider);
728  } else {
729  // Make the DescriptorScriptPubKeyMan and get the scriptPubKeys
730  WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
731  auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(m_storage, w_desc, /*keypool_size=*/0);
732  for (const auto& keyid : privkeyids) {
733  CKey key;
734  if (!GetKey(keyid, key)) {
735  continue;
736  }
737  WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, key, key.GetPubKey()));
738  }
739  desc_spk_man->TopUpWithDB(batch);
740  auto desc_spks_set = desc_spk_man->GetScriptPubKeys();
741  desc_spks.insert(desc_spks.end(), desc_spks_set.begin(), desc_spks_set.end());
742 
743  out.desc_spkms.push_back(std::move(desc_spk_man));
744  }
745 
746  // Remove the scriptPubKeys from our current set
747  for (const CScript& desc_spk : desc_spks) {
748  auto del_it = spks.find(desc_spk);
749  assert(del_it != spks.end());
750  assert(IsMine(desc_spk));
751  it = spks.erase(del_it);
752  }
753  }
754 
755  // Make sure that we have accounted for all scriptPubKeys
756  if (!Assume(spks.empty())) {
757  LogError("%s", STR_INTERNAL_BUG("Error: Some output scripts were not migrated."));
758  return std::nullopt;
759  }
760 
761  // Legacy wallets can also contain scripts whose P2SH, P2WSH, or P2SH-P2WSH it is not watching for
762  // but can provide script data to a PSBT spending them. These "solvable" output scripts will need to
763  // be put into the separate "solvables" wallet.
764  // These can be detected by going through the entire candidate output scripts, finding the not IsMine scripts,
765  // and checking CanProvide() which will dummy sign.
766  for (const CScript& script : GetCandidateScriptPubKeys()) {
767  // Since we only care about P2SH, P2WSH, and P2SH-P2WSH, filter out any scripts that are not those
768  if (!script.IsPayToScriptHash() && !script.IsPayToWitnessScriptHash()) {
769  continue;
770  }
771  if (IsMine(script)) {
772  continue;
773  }
774  SignatureData dummy_sigdata;
775  if (!CanProvide(script, dummy_sigdata)) {
776  continue;
777  }
778 
779  // Get birthdate from script meta
780  uint64_t creation_time = 0;
781  const auto& it = m_script_metadata.find(CScriptID(script));
782  if (it != m_script_metadata.end()) {
783  creation_time = it->second.nCreateTime;
784  }
785 
786  // InferDescriptor as that will get us all the solving info if it is there
787  std::unique_ptr<Descriptor> desc = InferDescriptor(script, *GetSolvingProvider(script));
788  if (!desc->IsSolvable()) {
789  // The wallet was able to provide some information, but not enough to make a descriptor that actually
790  // contains anything useful. This is probably because the script itself is actually unsignable (e.g. P2WSH-P2WSH).
791  continue;
792  }
793 
794  // Past bugs in InferDescriptor have caused it to create descriptors which cannot be re-parsed
795  // Re-parse the descriptors to detect that, and skip any that do not parse.
796  {
797  std::string desc_str = desc->ToString();
798  FlatSigningProvider parsed_keys;
799  std::string parse_error;
800  std::vector<std::unique_ptr<Descriptor>> parsed_descs = Parse(desc_str, parsed_keys, parse_error, false);
801  if (parsed_descs.empty()) {
802  continue;
803  }
804  }
805 
806  out.solvable_descs.emplace_back(desc->ToString(), creation_time);
807  }
808 
809  // Finalize transaction
810  if (!batch.TxnCommit()) {
811  LogWarning("Error generating descriptors for migration, cannot commit db transaction");
812  return std::nullopt;
813  }
814 
815  return out;
816 }
817 
819 {
820  LOCK(cs_KeyStore);
821  return batch.EraseRecords(DBKeys::LEGACY_TYPES);
822 }
823 
825 {
826  // Returns true if this descriptor supports getting new addresses. Conditions where we may be unable to fetch them (e.g. locked) are caught later
827  if (!CanGetAddresses()) {
828  return util::Error{_("No addresses available")};
829  }
830  {
831  LOCK(cs_desc_man);
832  assert(m_wallet_descriptor.descriptor->IsSingleType()); // This is a combo descriptor which should not be an active descriptor
833  std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
834  assert(desc_addr_type);
835  if (type != *desc_addr_type) {
836  throw std::runtime_error(std::string(__func__) + ": Types are inconsistent. Stored type does not match type of newly generated address");
837  }
838 
839  TopUp();
840 
841  // Get the scriptPubKey from the descriptor
842  FlatSigningProvider out_keys;
843  std::vector<CScript> scripts_temp;
844  if (m_wallet_descriptor.range_end <= m_max_cached_index && !TopUp(1)) {
845  // We can't generate anymore keys
846  return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
847  }
848  if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
849  // We can't generate anymore keys
850  return util::Error{_("Error: Keypool ran out, please call keypoolrefill first")};
851  }
852 
853  CTxDestination dest;
854  if (!ExtractDestination(scripts_temp[0], dest)) {
855  return util::Error{_("Error: Cannot extract destination from the generated scriptpubkey")}; // shouldn't happen
856  }
857  m_wallet_descriptor.next_index++;
858  WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
859  return dest;
860  }
861 }
862 
864 {
865  LOCK(cs_desc_man);
866  return m_map_script_pub_keys.contains(script);
867 }
868 
870 {
871  LOCK(cs_desc_man);
872  if (!m_map_keys.empty()) {
873  return false;
874  }
875 
876  bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
877  bool keyFail = false;
878  for (const auto& mi : m_map_crypted_keys) {
879  const CPubKey &pubkey = mi.second.first;
880  const std::vector<unsigned char> &crypted_secret = mi.second.second;
881  CKey key;
882  if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
883  keyFail = true;
884  break;
885  }
886  keyPass = true;
888  break;
889  }
890  if (keyPass && keyFail) {
891  LogWarning("The wallet is probably corrupted: Some keys decrypt but not all.");
892  throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
893  }
894  if (keyFail || !keyPass) {
895  return false;
896  }
898  return true;
899 }
900 
902 {
903  LOCK(cs_desc_man);
904  if (!m_map_crypted_keys.empty()) {
905  return false;
906  }
907 
908  for (const KeyMap::value_type& key_in : m_map_keys)
909  {
910  const CKey &key = key_in.second;
911  CPubKey pubkey = key.GetPubKey();
912  CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
913  std::vector<unsigned char> crypted_secret;
914  if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
915  return false;
916  }
917  m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
918  batch->WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
919  }
920  m_map_keys.clear();
921  return true;
922 }
923 
925 {
926  LOCK(cs_desc_man);
927  auto op_dest = GetNewDestination(type);
928  index = m_wallet_descriptor.next_index - 1;
929  return op_dest;
930 }
931 
932 void DescriptorScriptPubKeyMan::ReturnDestination(int64_t index, bool internal, const CTxDestination& addr)
933 {
934  LOCK(cs_desc_man);
935  // Only return when the index was the most recent
936  if (m_wallet_descriptor.next_index - 1 == index) {
937  m_wallet_descriptor.next_index--;
938  }
939  WalletBatch(m_storage.GetDatabase()).WriteDescriptor(GetID(), m_wallet_descriptor);
941 }
942 
943 std::map<CKeyID, CKey> DescriptorScriptPubKeyMan::GetKeys() const
944 {
947  KeyMap keys;
948  for (const auto& key_pair : m_map_crypted_keys) {
949  const CPubKey& pubkey = key_pair.second.first;
950  const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
951  CKey key;
952  m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
953  return DecryptKey(encryption_key, crypted_secret, pubkey, key);
954  });
955  keys[pubkey.GetID()] = key;
956  }
957  return keys;
958  }
959  return m_map_keys;
960 }
961 
963 {
965  return m_map_keys.contains(keyid) || m_map_crypted_keys.contains(keyid);
966 }
967 
968 std::optional<CKey> DescriptorScriptPubKeyMan::GetKey(const CKeyID& keyid) const
969 {
972  const auto& it = m_map_crypted_keys.find(keyid);
973  if (it == m_map_crypted_keys.end()) {
974  return std::nullopt;
975  }
976  const std::vector<unsigned char>& crypted_secret = it->second.second;
977  CKey key;
978  if (!Assume(m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
979  return DecryptKey(encryption_key, crypted_secret, it->second.first, key);
980  }))) {
981  return std::nullopt;
982  }
983  return key;
984  }
985  const auto& it = m_map_keys.find(keyid);
986  if (it == m_map_keys.end()) {
987  return std::nullopt;
988  }
989  return it->second;
990 }
991 
992 bool DescriptorScriptPubKeyMan::TopUp(unsigned int size)
993 {
995  if (!batch.TxnBegin()) return false;
996  bool res = TopUpWithDB(batch, size);
997  if (!batch.TxnCommit()) throw std::runtime_error(strprintf("Error during descriptors keypool top up. Cannot commit changes for wallet [%s]", m_storage.LogName()));
998  return res;
999 }
1000 
1002 {
1003  LOCK(cs_desc_man);
1004  std::set<CScript> new_spks;
1005  unsigned int target_size;
1006  if (size > 0) {
1007  target_size = size;
1008  } else {
1009  target_size = m_keypool_size;
1010  }
1011 
1012  // Calculate the new range_end
1013  int32_t new_range_end = std::max(m_wallet_descriptor.next_index + (int32_t)target_size, m_wallet_descriptor.range_end);
1014 
1015  // If the descriptor is not ranged, we actually just want to fill the first cache item
1016  if (!m_wallet_descriptor.descriptor->IsRange()) {
1017  new_range_end = 1;
1018  m_wallet_descriptor.range_end = 1;
1019  m_wallet_descriptor.range_start = 0;
1020  }
1021 
1022  FlatSigningProvider provider;
1023  provider.keys = GetKeys();
1024 
1025  uint256 id = GetID();
1026  for (int32_t i = m_max_cached_index + 1; i < new_range_end; ++i) {
1027  FlatSigningProvider out_keys;
1028  std::vector<CScript> scripts_temp;
1029  DescriptorCache temp_cache;
1030  // Maybe we have a cached xpub and we can expand from the cache first
1031  if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1032  if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
1033  }
1034  // Add all of the scriptPubKeys to the scriptPubKey set
1035  new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1036  for (const CScript& script : scripts_temp) {
1037  m_map_script_pub_keys[script] = i;
1038  }
1039  for (const auto& pk_pair : out_keys.pubkeys) {
1040  const CPubKey& pubkey = pk_pair.second;
1041  if (m_map_pubkeys.contains(pubkey)) {
1042  // We don't need to give an error here.
1043  // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and its private key
1044  continue;
1045  }
1046  m_map_pubkeys[pubkey] = i;
1047  }
1048  // Merge and write the cache
1049  DescriptorCache new_items = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
1050  if (!batch.WriteDescriptorCacheItems(id, new_items)) {
1051  throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
1052  }
1054  }
1055  m_wallet_descriptor.range_end = new_range_end;
1056  batch.WriteDescriptor(GetID(), m_wallet_descriptor);
1057 
1058  // By this point, the cache size should be the size of the entire range
1059  assert(m_wallet_descriptor.range_end - 1 == m_max_cached_index);
1060 
1061  m_storage.TopUpCallback(new_spks, this);
1063  return true;
1064 }
1065 
1066 std::vector<WalletDestination> DescriptorScriptPubKeyMan::MarkUnusedAddresses(const CScript& script)
1067 {
1068  LOCK(cs_desc_man);
1069  std::vector<WalletDestination> result;
1070  if (IsMine(script)) {
1071  int32_t index = m_map_script_pub_keys[script];
1072  if (index >= m_wallet_descriptor.next_index) {
1073  WalletLogPrintf("%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
1074  auto out_keys = std::make_unique<FlatSigningProvider>();
1075  std::vector<CScript> scripts_temp;
1076  while (index >= m_wallet_descriptor.next_index) {
1077  if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
1078  throw std::runtime_error(std::string(__func__) + ": Unable to expand descriptor from cache");
1079  }
1080  CTxDestination dest;
1081  ExtractDestination(scripts_temp[0], dest);
1082  result.push_back({dest, std::nullopt});
1083  m_wallet_descriptor.next_index++;
1084  }
1085  }
1086  if (!TopUp()) {
1087  WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1088  }
1089  }
1090 
1091  return result;
1092 }
1093 
1095 {
1096  LOCK(cs_desc_man);
1098  if (!AddDescriptorKeyWithDB(batch, key, pubkey)) {
1099  throw std::runtime_error(std::string(__func__) + ": writing descriptor private key failed");
1100  }
1101 }
1102 
1104 {
1107 
1108  // Check if provided key already exists
1109  if (m_map_keys.contains(pubkey.GetID()) ||
1110  m_map_crypted_keys.contains(pubkey.GetID())) {
1111  return true;
1112  }
1113 
1114  if (m_storage.HasEncryptionKeys()) {
1115  if (m_storage.IsLocked()) {
1116  return false;
1117  }
1118 
1119  std::vector<unsigned char> crypted_secret;
1120  CKeyingMaterial secret{UCharCast(key.begin()), UCharCast(key.end())};
1121  if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
1122  return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
1123  })) {
1124  return false;
1125  }
1126 
1127  m_map_crypted_keys[pubkey.GetID()] = make_pair(pubkey, crypted_secret);
1128  return batch.WriteCryptedDescriptorKey(GetID(), pubkey, crypted_secret);
1129  } else {
1130  m_map_keys[pubkey.GetID()] = key;
1131  return batch.WriteDescriptorKey(GetID(), pubkey, key.GetPrivKey());
1132  }
1133 }
1134 
1135 bool DescriptorScriptPubKeyMan::SetupDescriptorGeneration(WalletBatch& batch, const CExtKey& master_key, OutputType addr_type, bool internal)
1136 {
1137  LOCK(cs_desc_man);
1139 
1140  // Ignore when there is already a descriptor
1141  if (m_wallet_descriptor.descriptor) {
1142  return false;
1143  }
1144 
1145  m_wallet_descriptor = GenerateWalletDescriptor(master_key.Neuter(), addr_type, internal);
1146 
1147  // Store the master private key, and descriptor
1148  if (!AddDescriptorKeyWithDB(batch, master_key.key, master_key.key.GetPubKey())) {
1149  throw std::runtime_error(std::string(__func__) + ": writing descriptor master private key failed");
1150  }
1151  if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
1152  throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
1153  }
1154 
1155  // TopUp
1156  TopUpWithDB(batch);
1157 
1159  return true;
1160 }
1161 
1163 {
1164  LOCK(cs_desc_man);
1165  return m_wallet_descriptor.descriptor->IsRange();
1166 }
1167 
1169 {
1170  // We can only give out addresses from descriptors that are single type (not combo), ranged,
1171  // and either have cached keys or can generate more keys (ignoring encryption)
1172  LOCK(cs_desc_man);
1173  return m_wallet_descriptor.descriptor->IsSingleType() &&
1174  m_wallet_descriptor.descriptor->IsRange() &&
1175  (HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
1176 }
1177 
1179 {
1180  LOCK(cs_desc_man);
1181  return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
1182 }
1183 
1185 {
1186  LOCK(cs_desc_man);
1187  return !m_map_crypted_keys.empty();
1188 }
1189 
1191 {
1192  LOCK(cs_desc_man);
1193  return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
1194 }
1195 
1197 {
1198  LOCK(cs_desc_man);
1199  return m_wallet_descriptor.creation_time;
1200 }
1201 
1202 std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CScript& script, bool include_private) const
1203 {
1204  LOCK(cs_desc_man);
1205 
1206  // Find the index of the script
1207  auto it = m_map_script_pub_keys.find(script);
1208  if (it == m_map_script_pub_keys.end()) {
1209  return nullptr;
1210  }
1211  int32_t index = it->second;
1212 
1213  return GetSigningProvider(index, include_private);
1214 }
1215 
1216 std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(const CPubKey& pubkey) const
1217 {
1218  LOCK(cs_desc_man);
1219 
1220  // Find index of the pubkey
1221  auto it = m_map_pubkeys.find(pubkey);
1222  if (it == m_map_pubkeys.end()) {
1223  return nullptr;
1224  }
1225  int32_t index = it->second;
1226 
1227  // Always try to get the signing provider with private keys. This function should only be called during signing anyways
1228  std::unique_ptr<FlatSigningProvider> out = GetSigningProvider(index, true);
1229  if (!out->HaveKey(pubkey.GetID())) {
1230  return nullptr;
1231  }
1232  return out;
1233 }
1234 
1235 std::unique_ptr<FlatSigningProvider> DescriptorScriptPubKeyMan::GetSigningProvider(int32_t index, bool include_private) const
1236 {
1238 
1239  std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
1240 
1241  // Fetch SigningProvider from cache to avoid re-deriving
1242  auto it = m_map_signing_providers.find(index);
1243  if (it != m_map_signing_providers.end()) {
1244  out_keys->Merge(FlatSigningProvider{it->second});
1245  } else {
1246  // Get the scripts, keys, and key origins for this script
1247  std::vector<CScript> scripts_temp;
1248  if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) return nullptr;
1249 
1250  // Cache SigningProvider so we don't need to re-derive if we need this SigningProvider again
1251  m_map_signing_providers[index] = *out_keys;
1252  }
1253 
1254  if (HavePrivateKeys() && include_private) {
1255  FlatSigningProvider master_provider;
1256  master_provider.keys = GetKeys();
1257  m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
1258 
1259  // Always include musig_secnonces as this descriptor may have a participant private key
1260  // but not a musig() descriptor
1261  out_keys->musig2_secnonces = &m_musig2_secnonces;
1262  }
1263 
1264  return out_keys;
1265 }
1266 
1267 std::unique_ptr<SigningProvider> DescriptorScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
1268 {
1269  return GetSigningProvider(script, false);
1270 }
1271 
1273 {
1274  return IsMine(script);
1275 }
1276 
1277 bool DescriptorScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
1278 {
1279  std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1280  for (const auto& coin_pair : coins) {
1281  std::unique_ptr<FlatSigningProvider> coin_keys = GetSigningProvider(coin_pair.second.out.scriptPubKey, true);
1282  if (!coin_keys) {
1283  continue;
1284  }
1285  keys->Merge(std::move(*coin_keys));
1286  }
1287 
1288  return ::SignTransaction(tx, keys.get(), coins, sighash, input_errors);
1289 }
1290 
1291 SigningResult DescriptorScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
1292 {
1293  std::unique_ptr<FlatSigningProvider> keys = GetSigningProvider(GetScriptForDestination(pkhash), true);
1294  if (!keys) {
1296  }
1297 
1298  CKey key;
1299  if (!keys->GetKey(ToKeyID(pkhash), key)) {
1301  }
1302 
1303  if (!MessageSign(key, message, str_sig)) {
1305  }
1306  return SigningResult::OK;
1307 }
1308 
1309 std::optional<PSBTError> DescriptorScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, const PrecomputedTransactionData& txdata, std::optional<int> sighash_type, bool sign, bool bip32derivs, int* n_signed, bool finalize) const
1310 {
1311  if (n_signed) {
1312  *n_signed = 0;
1313  }
1314  for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
1315  const CTxIn& txin = psbtx.tx->vin[i];
1316  PSBTInput& input = psbtx.inputs.at(i);
1317 
1318  if (PSBTInputSigned(input)) {
1319  continue;
1320  }
1321 
1322  // Get the scriptPubKey to know which SigningProvider to use
1323  CScript script;
1324  if (!input.witness_utxo.IsNull()) {
1326  } else if (input.non_witness_utxo) {
1327  if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
1328  return PSBTError::MISSING_INPUTS;
1329  }
1330  script = input.non_witness_utxo->vout[txin.prevout.n].scriptPubKey;
1331  } else {
1332  // There's no UTXO so we can just skip this now
1333  continue;
1334  }
1335 
1336  std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1337  std::unique_ptr<FlatSigningProvider> script_keys = GetSigningProvider(script, /*include_private=*/sign);
1338  if (script_keys) {
1339  keys->Merge(std::move(*script_keys));
1340  } else {
1341  // Maybe there are pubkeys listed that we can sign for
1342  std::vector<CPubKey> pubkeys;
1343  pubkeys.reserve(input.hd_keypaths.size() + 2);
1344 
1345  // ECDSA Pubkeys
1346  for (const auto& [pk, _] : input.hd_keypaths) {
1347  pubkeys.push_back(pk);
1348  }
1349 
1350  // Taproot output pubkey
1351  std::vector<std::vector<unsigned char>> sols;
1353  sols[0].insert(sols[0].begin(), 0x02);
1354  pubkeys.emplace_back(sols[0]);
1355  sols[0][0] = 0x03;
1356  pubkeys.emplace_back(sols[0]);
1357  }
1358 
1359  // Taproot pubkeys
1360  for (const auto& pk_pair : input.m_tap_bip32_paths) {
1361  const XOnlyPubKey& pubkey = pk_pair.first;
1362  for (unsigned char prefix : {0x02, 0x03}) {
1363  unsigned char b[33] = {prefix};
1364  std::copy(pubkey.begin(), pubkey.end(), b + 1);
1365  CPubKey fullpubkey;
1366  fullpubkey.Set(b, b + 33);
1367  pubkeys.push_back(fullpubkey);
1368  }
1369  }
1370 
1371  for (const auto& pubkey : pubkeys) {
1372  std::unique_ptr<FlatSigningProvider> pk_keys = GetSigningProvider(pubkey);
1373  if (pk_keys) {
1374  keys->Merge(std::move(*pk_keys));
1375  }
1376  }
1377  }
1378 
1379  PSBTError res = SignPSBTInput(HidingSigningProvider(keys.get(), /*hide_secret=*/!sign, /*hide_origin=*/!bip32derivs), psbtx, i, &txdata, sighash_type, nullptr, finalize);
1380  if (res != PSBTError::OK && res != PSBTError::INCOMPLETE) {
1381  return res;
1382  }
1383 
1384  bool signed_one = PSBTInputSigned(input);
1385  if (n_signed && (signed_one || !sign)) {
1386  // If sign is false, we assume that we _could_ sign if we get here. This
1387  // will never have false negatives; it is hard to tell under what i
1388  // circumstances it could have false positives.
1389  (*n_signed)++;
1390  }
1391  }
1392 
1393  // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
1394  for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
1395  std::unique_ptr<SigningProvider> keys = GetSolvingProvider(psbtx.tx->vout.at(i).scriptPubKey);
1396  if (!keys) {
1397  continue;
1398  }
1399  UpdatePSBTOutput(HidingSigningProvider(keys.get(), /*hide_secret=*/true, /*hide_origin=*/!bip32derivs), psbtx, i);
1400  }
1401 
1402  return {};
1403 }
1404 
1405 std::unique_ptr<CKeyMetadata> DescriptorScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
1406 {
1407  std::unique_ptr<SigningProvider> provider = GetSigningProvider(GetScriptForDestination(dest));
1408  if (provider) {
1409  KeyOriginInfo orig;
1410  CKeyID key_id = GetKeyForDestination(*provider, dest);
1411  if (provider->GetKeyOrigin(key_id, orig)) {
1412  LOCK(cs_desc_man);
1413  std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
1414  meta->key_origin = orig;
1415  meta->has_key_origin = true;
1416  meta->nCreateTime = m_wallet_descriptor.creation_time;
1417  return meta;
1418  }
1419  }
1420  return nullptr;
1421 }
1422 
1424 {
1425  LOCK(cs_desc_man);
1426  return m_wallet_descriptor.id;
1427 }
1428 
1430 {
1431  LOCK(cs_desc_man);
1432  std::set<CScript> new_spks;
1433  m_wallet_descriptor.cache = cache;
1434  for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
1435  FlatSigningProvider out_keys;
1436  std::vector<CScript> scripts_temp;
1437  if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1438  throw std::runtime_error("Error: Unable to expand wallet descriptor from cache");
1439  }
1440  // Add all of the scriptPubKeys to the scriptPubKey set
1441  new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1442  for (const CScript& script : scripts_temp) {
1443  if (m_map_script_pub_keys.contains(script)) {
1444  throw std::runtime_error(strprintf("Error: Already loaded script at index %d as being at index %d", i, m_map_script_pub_keys[script]));
1445  }
1446  m_map_script_pub_keys[script] = i;
1447  }
1448  for (const auto& pk_pair : out_keys.pubkeys) {
1449  const CPubKey& pubkey = pk_pair.second;
1450  if (m_map_pubkeys.contains(pubkey)) {
1451  // We don't need to give an error here.
1452  // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and its private key
1453  continue;
1454  }
1455  m_map_pubkeys[pubkey] = i;
1456  }
1458  }
1459  // Make sure the wallet knows about our new spks
1460  m_storage.TopUpCallback(new_spks, this);
1461 }
1462 
1463 bool DescriptorScriptPubKeyMan::AddKey(const CKeyID& key_id, const CKey& key)
1464 {
1465  LOCK(cs_desc_man);
1466  m_map_keys[key_id] = key;
1467  return true;
1468 }
1469 
1470 bool DescriptorScriptPubKeyMan::AddCryptedKey(const CKeyID& key_id, const CPubKey& pubkey, const std::vector<unsigned char>& crypted_key)
1471 {
1472  LOCK(cs_desc_man);
1473  if (!m_map_keys.empty()) {
1474  return false;
1475  }
1476 
1477  m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
1478  return true;
1479 }
1480 
1482 {
1483  LOCK(cs_desc_man);
1484  return !m_wallet_descriptor.id.IsNull() && !desc.id.IsNull() && m_wallet_descriptor.id == desc.id;
1485 }
1486 
1488 {
1489  LOCK(cs_desc_man);
1491  if (!batch.WriteDescriptor(GetID(), m_wallet_descriptor)) {
1492  throw std::runtime_error(std::string(__func__) + ": writing descriptor failed");
1493  }
1494 }
1495 
1497 {
1498  return m_wallet_descriptor;
1499 }
1500 
1501 std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys() const
1502 {
1503  return GetScriptPubKeys(0);
1504 }
1505 
1506 std::unordered_set<CScript, SaltedSipHasher> DescriptorScriptPubKeyMan::GetScriptPubKeys(int32_t minimum_index) const
1507 {
1508  LOCK(cs_desc_man);
1509  std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
1510  script_pub_keys.reserve(m_map_script_pub_keys.size());
1511 
1512  for (auto const& [script_pub_key, index] : m_map_script_pub_keys) {
1513  if (index >= minimum_index) script_pub_keys.insert(script_pub_key);
1514  }
1515  return script_pub_keys;
1516 }
1517 
1519 {
1520  return m_max_cached_index + 1;
1521 }
1522 
1523 bool DescriptorScriptPubKeyMan::GetDescriptorString(std::string& out, const bool priv) const
1524 {
1525  LOCK(cs_desc_man);
1526 
1527  FlatSigningProvider provider;
1528  provider.keys = GetKeys();
1529 
1530  if (priv) {
1531  // For the private version, always return the master key to avoid
1532  // exposing child private keys. The risk implications of exposing child
1533  // private keys together with the parent xpub may be non-obvious for users.
1534  return m_wallet_descriptor.descriptor->ToPrivateString(provider, out);
1535  }
1536 
1537  return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
1538 }
1539 
1541 {
1542  LOCK(cs_desc_man);
1544  return;
1545  }
1546 
1547  // Skip if we have the last hardened xpub cache
1548  if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
1549  return;
1550  }
1551 
1552  // Expand the descriptor
1553  FlatSigningProvider provider;
1554  provider.keys = GetKeys();
1555  FlatSigningProvider out_keys;
1556  std::vector<CScript> scripts_temp;
1557  DescriptorCache temp_cache;
1558  if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
1559  throw std::runtime_error("Unable to expand descriptor");
1560  }
1561 
1562  // Cache the last hardened xpubs
1563  DescriptorCache diff = m_wallet_descriptor.cache.MergeAndDiff(temp_cache);
1564  if (!WalletBatch(m_storage.GetDatabase()).WriteDescriptorCacheItems(GetID(), diff)) {
1565  throw std::runtime_error(std::string(__func__) + ": writing cache items failed");
1566  }
1567 }
1568 
1570 {
1571  LOCK(cs_desc_man);
1572  std::string error;
1573  if (!CanUpdateToWalletDescriptor(descriptor, error)) {
1574  return util::Error{Untranslated(std::move(error))};
1575  }
1576 
1577  m_map_pubkeys.clear();
1578  m_map_script_pub_keys.clear();
1579  m_max_cached_index = -1;
1580  m_wallet_descriptor = descriptor;
1581 
1582  NotifyFirstKeyTimeChanged(this, m_wallet_descriptor.creation_time);
1583  return {};
1584 }
1585 
1587 {
1588  LOCK(cs_desc_man);
1589  if (!HasWalletDescriptor(descriptor)) {
1590  error = "can only update matching descriptor";
1591  return false;
1592  }
1593 
1594  if (!descriptor.descriptor->IsRange()) {
1595  // Skip range check for non-range descriptors
1596  return true;
1597  }
1598 
1599  if (descriptor.range_start > m_wallet_descriptor.range_start ||
1600  descriptor.range_end < m_wallet_descriptor.range_end) {
1601  // Use inclusive range for error
1602  error = strprintf("new range must include current range = [%d,%d]",
1603  m_wallet_descriptor.range_start,
1604  m_wallet_descriptor.range_end - 1);
1605  return false;
1606  }
1607 
1608  return true;
1609 }
1610 } // namespace wallet
int64_t GetTimeFirstKey() const override
virtual bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
bool CheckDecryptionKey(const CKeyingMaterial &master_key) override
Check that the given decryption key is valid for this ScriptPubKeyMan, i.e. it decrypts all of the ke...
Witness v0 (P2WPKH and P2WSH); see BIP 141.
static UniValue Parse(std::string_view raw, ParamFormat format=ParamFormat::JSON)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition: client.cpp:395
PSBTError
Definition: types.h:17
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that...
bool HaveWatchOnly(const CScript &dest) const
Returns whether the watch-only script is in the wallet.
std::optional< CKey > GetKey(const CKeyID &keyid) const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
Retrieve the particular key if it is available. Returns nullopt if the key is not in the wallet...
int ret
unsigned char fingerprint[4]
First 32 bits of the Hash160 of the public key at the root of the path.
Definition: keyorigin.h:13
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:170
bool CheckDecryptionKey(const CKeyingMaterial &master_key) override
Check that the given decryption key is valid for this ScriptPubKeyMan, i.e. it decrypts all of the ke...
std::vector< WalletDestination > MarkUnusedAddresses(const CScript &script) override
Mark unused addresses as being used Affects all keys up to and including the one determined by provid...
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 SetupDescriptorGeneration(WalletBatch &batch, const CExtKey &master_key, OutputType addr_type, bool internal)
Setup descriptors based on the given CExtkey.
AssertLockHeld(pool.cs)
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
virtual bool IsWalletFlagSet(uint64_t) const =0
virtual WalletDatabase & GetDatabase() const =0
void SetSeed(std::span< const std::byte > seed)
Definition: key.cpp:491
std::unordered_set< CScript, SaltedSipHasher > GetCandidateScriptPubKeys() const
bool has_key_origin
Whether the key_origin is useful.
Definition: walletdb.h:144
assert(!tx.IsCoinBase())
CScript scriptPubKey
Definition: transaction.h:143
PSBTError SignPSBTInput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index, const PrecomputedTransactionData *txdata, std::optional< int > sighash, SignatureData *out_sigdata, bool finalize)
Signs a PSBTInput, verifying that all provided data matches what is being signed. ...
Definition: psbt.cpp:402
CKey key
Definition: key.h:236
#define LogWarning(...)
Definition: log.h:96
uint160 RIPEMD160(std::span< const unsigned char > data)
Compute the 160-bit RIPEMD-160 hash of an array.
Definition: hash.h:222
static bool ExtractPubKey(const CScript &dest, CPubKey &pubKeyOut)
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
RecursiveMutex cs_KeyStore
bool fDecryptionThoroughlyChecked
keeps track of whether Unlock has run a thorough check before
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:183
bool WriteDescriptorCacheItems(const uint256 &desc_id, const DescriptorCache &cache)
Definition: walletdb.cpp:260
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: solver.cpp:141
std::map< CKeyID, CKey > keys
bool DeleteRecordsWithDB(WalletBatch &batch)
Delete all the records of this LegacyScriptPubKeyMan from disk.
bool MessageSign(const CKey &privkey, const std::string &message, std::string &signature)
Sign a message.
Definition: signmessage.cpp:57
WalletDescriptor GenerateWalletDescriptor(const CExtPubKey &master_key, const OutputType &addr_type, bool internal)
Definition: walletutil.cpp:35
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:82
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const override
Sign a message with the given script.
const char * prefix
Definition: rest.cpp:1141
virtual bool AddCScript(const CScript &redeemScript)
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< unsigned char > &secret)
Definition: walletdb.cpp:225
Definition: key.h:231
struct containing information needed for migrating legacy wallets to descriptor wallets ...
bool LoadKey(const CKey &key, const CPubKey &pubkey)
Adds a key to the store, without saving it to disk (used by LoadWallet)
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:109
std::map< CKeyID, CKey > KeyMap
void Set(const T pbegin, const T pend)
Initialize a public key using begin/end iterators to byte data.
Definition: pubkey.h:89
bool CanUpdateToWalletDescriptor(const WalletDescriptor &descriptor, std::string &error)
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:987
uint256 GetHash() const
Get the 256-bit hash of this public key.
Definition: pubkey.h:166
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
void WalletLogPrintf(util::ConstevalFormatString< sizeof...(Params)> wallet_fmt, const Params &... params) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo > > origins
void AddInactiveHDChain(const CHDChain &chain)
CKeyID GetKeyForDestination(const SigningProvider &store, const CTxDestination &dest)
Return the CKeyID of the key involved in a script (if there is a unique one).
const std::byte * end() const
Definition: key.h:121
A version of CTransaction with the PSBT format.
Definition: psbt.h:1138
virtual void UnsetBlankWalletFlag(WalletBatch &)=0
SigningResult
Definition: signmessage.h:43
void LoadHDChain(const CHDChain &chain)
Load a HD chain model (used by LoadWallet)
Access to the wallet database.
Definition: walletdb.h:192
CTxOut witness_utxo
Definition: psbt.h:264
Definition: script.h:76
boost::signals2::signal< void(const ScriptPubKeyMan *spkm, int64_t new_birth_time)> NotifyFirstKeyTimeChanged
Birth time changed.
bool AddKey(const CKeyID &key_id, const CKey &key)
virtual bool IsLocked() const =0
consteval auto _(util::TranslatedLiteral str)
Definition: translation.h:79
unsigned int GetKeyPoolSize() const override
util::Result< CTxDestination > GetNewDestination(OutputType type) override
bool WriteDescriptor(const uint256 &desc_id, const WalletDescriptor &descriptor)
Definition: walletdb.cpp:234
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
Definition: walletdb.cpp:217
std::map< uint256, MuSig2SecNonce > m_musig2_secnonces
Map of a session id to MuSig2 secnonce.
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:160
OutputType
Definition: outputtype.h:18
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
const std::unordered_set< std::string > LEGACY_TYPES
Definition: walletdb.cpp:63
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible...
bool CanGetAddresses(bool internal=false) const override
bool GetDescriptorString(std::string &out, bool priv) const
bool AddWatchOnlyInMem(const CScript &dest)
bool IsNull() const
Definition: transaction.h:160
constexpr unsigned char * begin()
Definition: uint256.h:100
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet) ...
bool AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
void SetCache(const DescriptorCache &cache)
bool AddCryptedKey(const CKeyID &key_id, const CPubKey &pubkey, const std::vector< unsigned char > &crypted_key)
WalletDescriptor GetWalletDescriptor() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
anyone can spend script
bool GetKey(const CKeyID &address, CKey &keyOut) const override
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that...
const unsigned char * begin() const
Definition: pubkey.h:295
KeyOriginInfo key_origin
Definition: walletdb.h:143
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a scriptPubKey for the destination.
Definition: addresstype.cpp:49
bool DecryptKey(const CKeyingMaterial &master_key, const std::span< const unsigned char > crypted_secret, const CPubKey &pub_key, CKey &key)
Definition: crypter.cpp:132
void ReturnDestination(int64_t index, bool internal, const CTxDestination &addr) override
An input of a transaction.
Definition: transaction.h:61
#define LOCK(cs)
Definition: sync.h:258
virtual bool HasEncryptionKeys() const =0
bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch) override
std::string hdKeypath
Definition: walletdb.h:141
const SigningProvider & DUMMY_SIGNING_PROVIDER
void clear()
Definition: translation.h:40
std::optional< common::PSBTError > FillPSBT(PartiallySignedTransaction &psbt, const PrecomputedTransactionData &txdata, std::optional< int > sighash_type=std::nullopt, bool sign=true, bool bip32derivs=false, int *n_signed=nullptr, bool finalize=true) const override
Adds script and derivation path information to a PSBT, and optionally signs it.
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:269
std::shared_ptr< Descriptor > descriptor
Definition: walletutil.h:66
An encapsulated public key.
Definition: pubkey.h:33
std::map< CKeyID, CPubKey > pubkeys
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) ...
uint32_t n
Definition: transaction.h:32
bool EraseRecords(const std::unordered_set< std::string > &types)
Delete records of the given types.
Definition: walletdb.cpp:1254
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:53
void ImplicitlyLearnRelatedKeyScripts(const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const override
std::unordered_set< CScript, SaltedSipHasher > GetScriptPubKeys() const override
Returns a set of all the scriptPubKeys that this ScriptPubKeyMan watches.
A structure for PSBTs which contain per-input information.
Definition: psbt.h:261
IsMineResult
This is an internal representation of isminetype + invalidity.
std::optional< MigrationData > MigrateToDescriptor()
Get the DescriptorScriptPubKeyMans (with private keys) that have the same scriptPubKeys as this Legac...
util::Result< CTxDestination > GetReservedDestination(OutputType type, bool internal, int64_t &index) override
void UpdatePSBTOutput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index)
Updates a PSBTOutput with information from provider.
Definition: psbt.cpp:365
virtual void LoadKeyMetadata(const CKeyID &keyID, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
std::string FormatHDKeypath(const std::vector< uint32_t > &path, bool apostrophe)
Definition: bip32.cpp:51
constexpr bool IsNull() const
Definition: uint256.h:48
std::vector< PSBTInput > inputs
Definition: psbt.h:1144
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:289
#define Assume(val)
Assume is the identity function.
Definition: check.h:125
virtual void TopUpCallback(const std::set< CScript > &, ScriptPubKeyMan *)=0
Callback function for after TopUp completes containing any scripts that were added by a SPKMan...
Descriptor with some wallet metadata.
Definition: walletutil.h:63
virtual bool GetKey(const CKeyID &address, CKey &keyOut) const override
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
std::vector< unsigned char > valtype
Definition: addresstype.cpp:18
virtual bool AddKeyPubKeyInner(const CKey &key, const CPubKey &pubkey)
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
static int sign(const secp256k1_context *ctx, struct signer_secrets *signer_secrets, struct signer *signer, const secp256k1_musig_keyagg_cache *cache, const unsigned char *msg32, unsigned char *sig64)
Definition: musig.c:106
virtual void LoadScriptMetadata(const CScriptID &script_id, const CKeyMetadata &metadata)
256-bit opaque blob.
Definition: uint256.h:195
TxoutType
Definition: solver.h:22
std::string EncodeExtPubKey(const CExtPubKey &key)
Definition: key_io.cpp:257
virtual bool WithEncryptionKey(std::function< bool(const CKeyingMaterial &)> cb) const =0
Pass the encryption key to cb().
auto result
Definition: common-types.h:74
bool EncryptSecret(const CKeyingMaterial &vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256 &nIV, std::vector< unsigned char > &vchCiphertext)
Definition: crypter.cpp:111
CExtPubKey Neuter() const
Definition: key.cpp:503
util::Result< void > UpdateWalletDescriptor(WalletDescriptor &descriptor)
bool IsMine(const CScript &script) const override
Cache for single descriptor&#39;s derived extended pubkeys.
Definition: descriptor.h:19
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:404
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:143
const std::byte * begin() const
Definition: key.h:120
CTransactionRef non_witness_utxo
Definition: psbt.h:263
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
Definition: script.h:28
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:23
std::map< int32_t, FlatSigningProvider > m_map_signing_providers
DescriptorCache MergeAndDiff(const DescriptorCache &other)
Combine another DescriptorCache into this one.
bool m_decryption_thoroughly_checked
keeps track of whether Unlock has run a thorough check before
virtual std::string LogName() const =0
160-bit opaque blob.
Definition: uint256.h:183
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:729
void AddDescriptorKey(const CKey &key, const CPubKey &pubkey)
A reference to a CScript: the Hash160 of its serialization.
Definition: script.h:593
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:294
A mutable version of CTransaction.
Definition: transaction.h:357
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: solver.cpp:213
size_type size() const
Definition: prevector.h:247
unsigned char * UCharCast(char *c)
Definition: span.h:95
virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed by checking for non-null finalized fields.
Definition: psbt.cpp:320
bool AddDescriptorKeyWithDB(WalletBatch &batch, const CKey &key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
KeyMap GetKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const override
#define STR_INTERNAL_BUG(msg)
Definition: check.h:96
An encapsulated private key.
Definition: key.h:35
bool HasPrivKey(const CKeyID &keyid) const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
std::unordered_map< CKeyID, CHDChain, SaltedSipHasher > m_inactive_hd_chains
std::optional< CMutableTransaction > tx
Definition: psbt.h:1140
std::vector< unsigned char > valtype
is a home for public enum and struct type definitions that are used internally by node code...
bool HaveKey(const CKeyID &address) const override
bool LoadCScript(const CScript &redeemScript)
Adds a CScript to the store.
std::unordered_set< CScript, SaltedSipHasher > GetNotMineScriptPubKeys() const
Retrieves scripts that were imported by bugs into the legacy spkm and are simply invalid, such as a sh(sh(pkh())) script, or not watched.
COutPoint prevout
Definition: transaction.h:64
std::vector< uint32_t > path
Definition: keyorigin.h:14
std::unordered_set< CScript, SaltedSipHasher > GetScriptPubKeys() const override
Returns a set of all the scriptPubKeys that this ScriptPubKeyMan watches.
Only for Witness versions not already defined above.
const unsigned char * end() const
Definition: pubkey.h:296
CKeyID seed_id
seed hash160
Definition: walletdb.h:99
bool IsMine(const CScript &script) const override
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:30
bool TopUpWithDB(WalletBatch &batch, unsigned int size=0)
Same as &#39;TopUp&#39; but designed for use within a batch transaction context.
bool HasWalletDescriptor(const WalletDescriptor &desc) const
CKeyID ToKeyID(const PKHash &key_hash)
Definition: addresstype.cpp:29
IsMineSigVersion
This is an enum that tracks the execution context of a script, similar to SigVersion in script/interp...
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:246
bool TopUp(unsigned int size=0) override
Fills internal address pool.
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: crypter.h:63
static const auto INVALID
A stack representing the lack of any (dis)satisfactions.
Definition: miniscript.h:351
#define LogError(...)
Definition: log.h:97
bool SignTransaction(CMutableTransaction &tx, const std::map< COutPoint, Coin > &coins, int sighash, std::map< int, bilingual_str > &input_errors) const override
Creates new signatures and adds them to the transaction.
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input. May contain all signatures necessary for producing a ...
Definition: sign.h:86
std::unique_ptr< FlatSigningProvider > GetSigningProvider(const CScript &script, bool include_private=false) const
WalletStorage & m_storage
unspendable OP_RETURN script that carries data
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:200
virtual bool HaveKey(const CKeyID &address) const override
std::map< XOnlyPubKey, std::pair< std::set< uint256 >, KeyOriginInfo > > m_tap_bip32_paths
Definition: psbt.h:280
static const int VERSION_HD_CHAIN_SPLIT
Definition: walletdb.h:104