31typedef std::vector<unsigned char>
valtype;
43enum class IsMineSigVersion
55enum class IsMineResult
63bool PermitsUncompressed(IsMineSigVersion sigversion)
65 return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
68bool HaveKeys(
const std::vector<valtype>& pubkeys,
const LegacyDataSPKM& keystore)
70 for (
const valtype& pubkey : pubkeys) {
72 if (!keystore.
HaveKey(keyID))
return false;
86IsMineResult LegacyWalletIsMineInnerDONOTUSE(
const LegacyDataSPKM& keystore,
const CScript& scriptPubKey, IsMineSigVersion sigversion,
bool recurse_scripthash=
true)
88 IsMineResult
ret = IsMineResult::NO;
90 std::vector<valtype> vSolutions;
103 if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
107 ret = std::max(
ret, IsMineResult::SPENDABLE);
112 if (sigversion == IsMineSigVersion::WITNESS_V0) {
127 if (!PermitsUncompressed(sigversion)) {
134 ret = std::max(
ret, IsMineResult::SPENDABLE);
139 if (sigversion != IsMineSigVersion::TOP) {
145 if (keystore.
GetCScript(scriptID, subscript)) {
146 ret = std::max(
ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
152 if (sigversion == IsMineSigVersion::WITNESS_V0) {
161 if (keystore.
GetCScript(scriptID, subscript)) {
162 ret = std::max(
ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::WITNESS_V0) : IsMineResult::SPENDABLE);
170 if (sigversion == IsMineSigVersion::TOP) {
179 std::vector<valtype>
keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
180 if (!PermitsUncompressed(sigversion)) {
181 for (
size_t i = 0; i <
keys.size(); i++) {
182 if (
keys[i].size() != 33) {
187 if (HaveKeys(
keys, keystore)) {
188 ret = std::max(
ret, IsMineResult::SPENDABLE);
195 ret = std::max(
ret, IsMineResult::WATCH_ONLY);
204 switch (LegacyWalletIsMineInnerDONOTUSE(*
this,
script, IsMineSigVersion::TOP)) {
206 case IsMineResult::NO:
208 case IsMineResult::WATCH_ONLY:
209 case IsMineResult::SPENDABLE:
221 bool keyPass = mapCryptedKeys.empty();
222 bool keyFail =
false;
223 CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
225 for (; mi != mapCryptedKeys.end(); ++mi)
227 const CPubKey &vchPubKey = (*mi).second.first;
228 const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
230 if (!
DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
243 if (keyPass && keyFail)
245 LogWarning(
"The wallet is probably corrupted: Some keys decrypt but not all.");
246 throw std::runtime_error(
"Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
248 if (keyFail || !keyPass)
257 return std::make_unique<LegacySigningProvider>(*
this);
262 IsMineResult ismine = LegacyWalletIsMineInnerDONOTUSE(*
this,
script, IsMineSigVersion::TOP,
false);
263 if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
273 bool has_privkeys =
false;
274 for (
const auto& key_sig_pair : sigdata.
signatures) {
275 has_privkeys |=
HaveKey(key_sig_pair.first);
296 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);
306 mapKeyMetadata[keyID] = meta;
312 m_script_metadata[script_id] = meta;
324 if (!checksum_valid) {
336 mapCryptedKeys[vchPubKey.
GetID()] = make_pair(vchPubKey, vchCryptedSecret);
344 return setWatchOnly.contains(dest);
354 std::vector<std::vector<unsigned char>> solutions;
356 (pubKeyOut =
CPubKey(solutions[0])).IsFullyValid();
362 setWatchOnly.insert(dest);
365 mapWatchKeys[pubKey.
GetID()] = pubKey;
390 return mapCryptedKeys.contains(address);
400 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
401 if (mi != mapCryptedKeys.end())
403 const CPubKey &vchPubKey = (*mi).second.first;
404 const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
406 return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey, keyOut);
417 auto it = mapKeyMetadata.find(keyID);
418 if (it == mapKeyMetadata.end()) {
435 WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
436 if (it != mapWatchKeys.end()) {
437 pubkey_out = it->second;
453 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
454 if (mi != mapCryptedKeys.end())
456 vchPubKeyOut = (*mi).second.first;
466 std::unordered_set<CScript, SaltedSipHasher> candidate_spks;
469 const auto& add_pubkey = [&candidate_spks](
const CPubKey& pub) ->
void {
474 candidate_spks.insert(wpkh);
477 for (
const auto& [
_, key] : mapKeys) {
478 add_pubkey(key.GetPubKey());
480 for (
const auto& [
_, ckeypair] : mapCryptedKeys) {
481 add_pubkey(ckeypair.first);
488 const auto& add_script = [&candidate_spks](
const CScript&
script) ->
void {
489 candidate_spks.insert(
script);
493 candidate_spks.insert(wsh);
496 for (
const auto& [
_,
script] : mapScripts) {
502 for (
const auto&
script : setWatchOnly) {
506 return candidate_spks;
514 std::unordered_set<CScript, SaltedSipHasher> spks;
527 std::unordered_set<CScript, SaltedSipHasher> spks;
546 std::set<CKeyID> keyids;
547 for (
const auto& key_pair : mapKeys) {
548 keyids.insert(key_pair.first);
550 for (
const auto& key_pair : mapCryptedKeys) {
551 keyids.insert(key_pair.first);
556 for (
auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
557 const CKeyID& keyid = *keyid_it;
558 const auto& it = mapKeyMetadata.find(keyid);
559 if (it != mapKeyMetadata.end()) {
566 keyid_it = keyids.erase(keyid_it);
575 LogWarning(
"Error generating descriptors for migration, cannot initialize db transaction");
580 for (
const CKeyID& keyid : keyids) {
582 if (!
GetKey(keyid, key)) {
587 uint64_t creation_time = 0;
588 const auto& it = mapKeyMetadata.find(keyid);
589 if (it != mapKeyMetadata.end()) {
590 creation_time = it->second.nCreateTime;
600 std::string desc_str =
"combo(" + origin_str +
HexStr(key.
GetPubKey()) +
")";
603 std::vector<std::unique_ptr<Descriptor>> descs =
Parse(desc_str,
provider, error,
false);
610 auto desc_spks = desc_spk_man->GetScriptPubKeys();
613 for (
const CScript& spk : desc_spks) {
614 size_t erased = spks.erase(spk);
619 out.desc_spkms.push_back(std::move(desc_spk_man));
623 std::set<CHDChain> chains;
626 chains.insert(chain_pair.second);
631 std::set<CExtPubKey> master_xpubs;
632 for (
const CHDChain& chain : chains) {
633 if (chain.seed_id.IsNull())
continue;
637 if (!
GetKey(chain.seed_id, seed_key)) {
645 const auto& [
_, inserted] = master_xpubs.insert(master_xpub);
646 if (!inserted)
continue;
648 for (
int i = 0; i < 2; ++i) {
650 if (i == 1 && !can_support_hd_split_feature) {
656 std::string desc_str =
"combo(" + xpub +
"/0h/" +
ToString(i) +
"h/*h)";
659 std::vector<std::unique_ptr<Descriptor>> descs =
Parse(desc_str,
provider, error,
false);
661 uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
667 auto desc_spks = desc_spk_man->GetScriptPubKeys();
670 for (
const CScript& spk : desc_spks) {
671 size_t erased = spks.erase(spk);
676 out.desc_spkms.push_back(std::move(desc_spk_man));
685 out.master_key.SetSeed(seed_key);
689 for (
auto it = spks.begin(); it != spks.end();) {
693 uint64_t creation_time = 0;
694 const auto& mit = m_script_metadata.find(
CScriptID(spk));
695 if (mit != m_script_metadata.end()) {
696 creation_time = mit->second.nCreateTime;
705 std::string desc_str = desc->ToString();
707 std::string parse_error;
708 std::vector<std::unique_ptr<Descriptor>> parsed_descs =
Parse(desc_str, parsed_keys, parse_error);
709 if (parsed_descs.empty()) {
717 std::vector<CScript> scripts;
722 std::set<CKeyID> privkeyids;
723 for (
const auto& key_orig_pair :
keys.origins) {
724 privkeyids.insert(key_orig_pair.first);
727 std::vector<CScript> desc_spks;
732 out.watch_descs.emplace_back(desc->ToString(), creation_time);
739 for (
const auto& keyid : privkeyids) {
741 if (!
GetKey(keyid, key)) {
748 auto desc_spks_set = desc_spk_man->GetScriptPubKeys();
749 desc_spks.insert(desc_spks.end(), desc_spks_set.begin(), desc_spks_set.end());
751 out.desc_spkms.push_back(std::move(desc_spk_man));
755 for (
const CScript& desc_spk : desc_spks) {
756 auto del_it = spks.find(desc_spk);
757 assert(del_it != spks.end());
759 it = spks.erase(del_it);
764 if (!
Assume(spks.empty())) {
776 if (!
script.IsPayToScriptHash() && !
script.IsPayToWitnessScriptHash()) {
788 uint64_t creation_time = 0;
790 if (it != m_script_metadata.end()) {
791 creation_time = it->second.nCreateTime;
796 if (!desc->IsSolvable()) {
805 std::string desc_str = desc->ToString();
807 std::string parse_error;
808 std::vector<std::unique_ptr<Descriptor>> parsed_descs =
Parse(desc_str, parsed_keys, parse_error,
false);
809 if (parsed_descs.empty()) {
814 out.solvable_descs.emplace_back(desc->ToString(), creation_time);
819 LogWarning(
"Error generating descriptors for migration, cannot commit db transaction");
834 auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(
new DescriptorScriptPubKeyMan(storage, descriptor, keypool_size));
835 LOCK(spkm->cs_desc_man);
837 spkm->UpdateWithSigningProvider(batch,
provider);
843 auto spkm = std::unique_ptr<DescriptorScriptPubKeyMan>(
new DescriptorScriptPubKeyMan(storage, descriptor, keypool_size));
844 LOCK(spkm->cs_desc_man);
845 spkm->UpdateWithSigningProvider(batch,
provider);
852 m_map_crypted_keys(ckeys),
853 m_keypool_size(keypool_size),
854 m_wallet_descriptor(descriptor)
856 if (!
keys.empty() && !ckeys.empty()) {
857 throw std::runtime_error(
"Wallet contains both unencrypted and encrypted keys");
870 spkm->SetupDescriptorGeneration(batch, master_key, addr_type, internal);
882 assert(m_wallet_descriptor.descriptor->IsSingleType());
883 std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
885 if (type != *desc_addr_type) {
886 throw std::runtime_error(std::string(__func__) +
": Types are inconsistent. Stored type does not match type of newly generated address");
893 std::vector<CScript> scripts_temp;
896 return util::Error{
_(
"Error: Keypool ran out, please call keypoolrefill first")};
898 if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
900 return util::Error{
_(
"Error: Keypool ran out, please call keypoolrefill first")};
905 return util::Error{
_(
"Error: Cannot extract destination from the generated scriptpubkey")};
907 m_wallet_descriptor.next_index++;
916 return m_map_script_pub_keys.contains(
script);
922 if (!m_map_keys.empty()) {
926 bool keyPass = m_map_crypted_keys.empty();
927 bool keyFail =
false;
928 for (
const auto& mi : m_map_crypted_keys) {
929 const CPubKey &pubkey = mi.second.first;
930 const std::vector<unsigned char> &crypted_secret = mi.second.second;
932 if (!
DecryptKey(master_key, crypted_secret, pubkey, key)) {
940 if (keyPass && keyFail) {
941 LogWarning(
"The wallet is probably corrupted: Some keys decrypt but not all.");
942 throw std::runtime_error(
"Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
944 if (keyFail || !keyPass) {
954 if (!m_map_crypted_keys.empty()) {
958 for (
const KeyMap::value_type& key_in : m_map_keys)
960 const CKey &key = key_in.second;
963 std::vector<unsigned char> crypted_secret;
967 m_map_crypted_keys[pubkey.
GetID()] = make_pair(pubkey, crypted_secret);
978 index = m_wallet_descriptor.next_index - 1;
986 if (m_wallet_descriptor.next_index - 1 == index) {
987 m_wallet_descriptor.next_index--;
998 for (
const auto& key_pair : m_map_crypted_keys) {
999 const CPubKey& pubkey = key_pair.second.first;
1000 const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
1003 return DecryptKey(encryption_key, crypted_secret, pubkey, key);
1015 return m_map_keys.contains(keyid) || m_map_crypted_keys.contains(keyid);
1022 const auto& it = m_map_crypted_keys.find(keyid);
1023 if (it == m_map_crypted_keys.end()) {
1024 return std::nullopt;
1026 const std::vector<unsigned char>& crypted_secret = it->second.second;
1029 return DecryptKey(encryption_key, crypted_secret, it->second.first, key);
1031 return std::nullopt;
1035 const auto& it = m_map_keys.find(keyid);
1036 if (it == m_map_keys.end()) {
1037 return std::nullopt;
1045 if (!batch.
TxnBegin())
return false;
1054 std::set<CScript> new_spks;
1055 unsigned int target_size;
1059 target_size = m_keypool_size;
1063 int32_t new_range_end = std::max(m_wallet_descriptor.next_index + (int32_t)target_size, m_wallet_descriptor.range_end);
1066 if (!m_wallet_descriptor.descriptor->IsRange()) {
1068 m_wallet_descriptor.range_end = 1;
1069 m_wallet_descriptor.range_start = 0;
1078 std::vector<CScript> scripts_temp;
1081 if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1082 if (!m_wallet_descriptor.descriptor->Expand(i,
provider, scripts_temp, out_keys, &temp_cache))
return false;
1085 new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1087 m_map_script_pub_keys[
script] = i;
1089 for (
const auto& pk_pair : out_keys.
pubkeys) {
1090 const CPubKey& pubkey = pk_pair.second;
1091 if (m_map_pubkeys.contains(pubkey)) {
1096 m_map_pubkeys[pubkey] = i;
1101 throw std::runtime_error(std::string(__func__) +
": writing cache items failed");
1105 m_wallet_descriptor.range_end = new_range_end;
1119 std::vector<WalletDestination> result;
1121 int32_t index = m_map_script_pub_keys[
script];
1122 if (index >= m_wallet_descriptor.next_index) {
1123 WalletLogPrintf(
"%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
1124 auto out_keys = std::make_unique<FlatSigningProvider>();
1125 std::vector<CScript> scripts_temp;
1126 while (index >= m_wallet_descriptor.next_index) {
1127 if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
1128 throw std::runtime_error(std::string(__func__) +
": Unable to expand descriptor from cache");
1132 result.push_back({dest, std::nullopt});
1133 m_wallet_descriptor.next_index++;
1137 WalletLogPrintf(
"%s: Topping up keypool failed (locked wallet)\n", __func__);
1149 throw std::runtime_error(std::string(__func__) +
": writing descriptor private key failed");
1159 if (m_map_keys.contains(pubkey.
GetID()) ||
1160 m_map_crypted_keys.contains(pubkey.
GetID())) {
1169 std::vector<unsigned char> crypted_secret;
1172 return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
1177 m_map_crypted_keys[pubkey.
GetID()] = make_pair(pubkey, crypted_secret);
1180 m_map_keys[pubkey.
GetID()] = key;
1189 Assert(!m_wallet_descriptor.descriptor);
1195 throw std::runtime_error(std::string(__func__) +
": writing descriptor master private key failed");
1198 throw std::runtime_error(std::string(__func__) +
": writing descriptor failed");
1215 return m_wallet_descriptor.descriptor->IsRange();
1223 return m_wallet_descriptor.descriptor->IsSingleType() &&
1224 m_wallet_descriptor.descriptor->IsRange() &&
1225 (
HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
1231 return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
1237 return !m_map_crypted_keys.empty();
1243 return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
1249 return m_wallet_descriptor.creation_time;
1257 auto it = m_map_script_pub_keys.find(
script);
1258 if (it == m_map_script_pub_keys.end()) {
1261 int32_t index = it->second;
1271 auto it = m_map_pubkeys.find(pubkey);
1272 if (it == m_map_pubkeys.end()) {
1275 int32_t index = it->second;
1279 if (!
out->HaveKey(pubkey.
GetID())) {
1289 std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
1297 std::vector<CScript> scripts_temp;
1298 if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys))
return nullptr;
1307 m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
1329 std::unique_ptr<FlatSigningProvider>
keys = std::make_unique<FlatSigningProvider>();
1330 for (
const auto& coin_pair : coins) {
1331 std::unique_ptr<FlatSigningProvider> coin_keys =
GetSigningProvider(coin_pair.second.out.scriptPubKey,
true);
1335 keys->Merge(std::move(*coin_keys));
1364 for (
unsigned int i = 0; i < psbtx.
inputs.size(); ++i) {
1377 return PSBTError::MISSING_INPUTS;
1385 std::unique_ptr<FlatSigningProvider>
keys = std::make_unique<FlatSigningProvider>();
1388 keys->Merge(std::move(*script_keys));
1391 std::vector<CPubKey> pubkeys;
1396 pubkeys.push_back(
pk);
1400 std::vector<std::vector<unsigned char>> sols;
1402 sols[0].insert(sols[0].begin(), 0x02);
1403 pubkeys.emplace_back(sols[0]);
1405 pubkeys.emplace_back(sols[0]);
1411 for (
unsigned char prefix : {0x02, 0x03}) {
1412 unsigned char b[33] = {
prefix};
1413 std::copy(pubkey.
begin(), pubkey.
end(), b + 1);
1415 fullpubkey.
Set(b, b + 33);
1416 pubkeys.push_back(fullpubkey);
1420 for (
const auto& pubkey : pubkeys) {
1423 keys->Merge(std::move(*pk_keys));
1429 if (res != PSBTError::OK && res != PSBTError::INCOMPLETE) {
1434 if (n_signed && (signed_one || !options.
sign)) {
1443 for (
unsigned int i = 0; i < psbtx.
outputs.size(); ++i) {
1460 if (
provider->GetKeyOrigin(key_id, orig)) {
1462 std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
1463 meta->key_origin = orig;
1464 meta->has_key_origin =
true;
1465 meta->nCreateTime = m_wallet_descriptor.creation_time;
1475 return m_wallet_descriptor.id;
1481 std::set<CScript> new_spks;
1482 for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
1484 std::vector<CScript> scripts_temp;
1485 if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1486 throw std::runtime_error(
"Error: Unable to expand wallet descriptor from cache");
1489 new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1491 if (m_map_script_pub_keys.contains(
script)) {
1492 throw std::runtime_error(
strprintf(
"Error: Already loaded script at index %d as being at index %d", i, m_map_script_pub_keys[
script]));
1494 m_map_script_pub_keys[
script] = i;
1496 for (
const auto& pk_pair : out_keys.
pubkeys) {
1497 const CPubKey& pubkey = pk_pair.second;
1498 if (m_map_pubkeys.contains(pubkey)) {
1503 m_map_pubkeys[pubkey] = i;
1514 return !m_wallet_descriptor.id.IsNull() && !desc.
id.
IsNull() && m_wallet_descriptor.id == desc.
id;
1522 throw std::runtime_error(std::string(__func__) +
": writing descriptor failed");
1528 return m_wallet_descriptor;
1539 std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
1540 script_pub_keys.reserve(m_map_script_pub_keys.size());
1542 for (
auto const& [script_pub_key, index] : m_map_script_pub_keys) {
1543 if (index >= minimum_index) script_pub_keys.insert(script_pub_key);
1545 return script_pub_keys;
1564 return m_wallet_descriptor.descriptor->ToPrivateString(
provider,
out);
1567 return m_wallet_descriptor.descriptor->ToNormalizedString(
provider,
out, &m_wallet_descriptor.cache);
1578 if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
1586 std::vector<CScript> scripts_temp;
1588 if (!m_wallet_descriptor.descriptor->Expand(0,
provider, scripts_temp, out_keys, &temp_cache)){
1589 throw std::runtime_error(
"Unable to expand descriptor");
1595 throw std::runtime_error(std::string(__func__) +
": writing cache items failed");
1607 m_map_pubkeys.
clear();
1608 m_map_script_pub_keys.clear();
1610 m_wallet_descriptor = descriptor;
1622 for (
const auto& entry : signing_provider.
keys) {
1623 const CKey& key = entry.second;
1625 throw std::runtime_error(std::string(__func__) +
": writing descriptor private key failed");
1631 throw std::runtime_error(
"Could not top up scriptPubKeys");
1639 error =
"can only update matching descriptor";
1648 if (descriptor.
range_start > m_wallet_descriptor.range_start ||
1649 descriptor.
range_end < m_wallet_descriptor.range_end) {
1651 error =
strprintf(
"new range must include current range = [%d,%d]",
1652 m_wallet_descriptor.range_start,
1653 m_wallet_descriptor.range_end - 1);
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a scriptPubKey for the destination.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
CKeyID ToKeyID(const PKHash &key_hash)
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
std::string FormatHDKeypath(const std::vector< uint32_t > &path, bool apostrophe)
#define CHECK_NONFATAL(condition)
Identity function.
#define Assert(val)
Identity function.
#define STR_INTERNAL_BUG(msg)
#define Assume(val)
Assume is the identity function.
An encapsulated private key.
const std::byte * begin() const
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
CPubKey GetPubKey() const
Compute the public key from a private key.
const std::byte * end() const
A reference to a CKey: the Hash160 of its serialized public key.
An encapsulated public key.
bool IsCompressed() const
Check whether this is a compressed public key.
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
uint256 GetHash() const
Get the 256-bit hash of this public key.
void Set(const T pbegin, const T pend)
Initialize a public key using begin/end iterators to byte data.
Serialized script, used inside transaction inputs and outputs.
A reference to a CScript: the Hash160 of its serialization.
Cache for single descriptor's derived extended pubkeys.
DescriptorCache MergeAndDiff(const DescriptorCache &other)
Combine another DescriptorCache into this one.
virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
virtual bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
virtual bool GetCScript(const CScriptID &hash, CScript &redeemScriptOut) const override
virtual bool GetKey(const CKeyID &address, CKey &keyOut) const override
virtual bool AddCScript(const CScript &redeemScript)
void ImplicitlyLearnRelatedKeyScripts(const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
virtual bool HaveCScript(const CScriptID &hash) const override
RecursiveMutex cs_KeyStore
virtual bool HaveKey(const CKeyID &address) const override
A version of CTransaction with the PSBT format.
std::vector< PSBTInput > inputs
std::vector< PSBTOutput > outputs
const unsigned char * end() const
const unsigned char * begin() const
constexpr bool IsNull() const
constexpr unsigned char * begin()
static const int VERSION_HD_CHAIN_SPLIT
CKeyID seed_id
seed hash160
bool IsMine(const CScript &script) const override
KeyMap GetKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
bool GetDescriptorString(std::string &out, bool priv) const
std::map< int32_t, FlatSigningProvider > m_map_signing_providers
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that,...
void UpgradeDescriptorCache()
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::unordered_set< CScript, SaltedSipHasher > GetScriptPubKeys() const override
Returns a set of all the scriptPubKeys that this ScriptPubKeyMan watches.
WalletDescriptor GetWalletDescriptor() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
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,...
DescriptorScriptPubKeyMan(WalletStorage &storage, WalletDescriptor &descriptor, int64_t keypool_size)
Create a new DescriptorScriptPubKeyMan from an existing descriptor (i.e. from an import)
util::Result< CTxDestination > GetReservedDestination(OutputType type, bool internal, int64_t &index) override
bool TopUp(unsigned int size=0) override
Fills internal address pool.
bool m_decryption_thoroughly_checked
keeps track of whether Unlock has run a thorough check before
unsigned int GetKeyPoolSize() const override
int64_t GetTimeFirstKey() const override
std::unique_ptr< FlatSigningProvider > GetSigningProvider(const CScript &script, bool include_private=false) const
void SetupDescriptorGeneration(WalletBatch &batch, const CExtKey &master_key, OutputType addr_type, bool internal)
Setup descriptors based on the given CExtKey.
static std::unique_ptr< DescriptorScriptPubKeyMan > CreateFromImport(WalletStorage &storage, WalletDescriptor &descriptor, int64_t keypool_size, const FlatSigningProvider &provider)
void UpdateWithSigningProvider(WalletBatch &batch, const FlatSigningProvider &signing_provider) EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
bool HaveCryptedKeys() const override
int32_t GetEndRange() const
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...
bool CanGetAddresses(bool internal=false) const override
bool CanUpdateToWalletDescriptor(const WalletDescriptor &descriptor, std::string &error)
std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const override
void AddDescriptorKey(const CKey &key, const CPubKey &pubkey)
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
static std::unique_ptr< DescriptorScriptPubKeyMan > LoadFromStorage(WalletStorage &storage, WalletDescriptor &descriptor, int64_t keypool_size, const KeyMap &keys, const CryptedKeyMap &ckeys)
bool HavePrivateKeys() const override
bool TopUpWithDB(WalletBatch &batch, unsigned int size=0)
Same as 'TopUp' but designed for use within a batch transaction context.
void ReturnDestination(int64_t index, bool internal, const CTxDestination &addr) override
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...
static std::unique_ptr< DescriptorScriptPubKeyMan > CreateFromMigration(WalletStorage &storage, WalletBatch &batch, WalletDescriptor &descriptor, int64_t keypool_size, const FlatSigningProvider &provider)
bool AddDescriptorKeyWithDB(WalletBatch &batch, const CKey &key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
bool HasWalletDescriptor(const WalletDescriptor &desc) const
int32_t m_max_cached_index
RecursiveMutex cs_desc_man
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const override
Sign a message with the given script.
std::optional< common::PSBTError > FillPSBT(PartiallySignedTransaction &psbt, const PrecomputedTransactionData &txdata, const common::PSBTFillOptions &options, int *n_signed=nullptr) const override
Adds script and derivation path information to a PSBT, and optionally signs it.
util::Result< CTxDestination > GetNewDestination(OutputType type) override
bool IsHDEnabled() const override
std::map< uint256, MuSig2SecNonce > m_musig2_secnonces
Map of a session id to MuSig2 secnonce.
bool HasPrivKey(const CKeyID &keyid) const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
util::Result< void > UpdateWalletDescriptor(WalletDescriptor &descriptor, const FlatSigningProvider &provider)
static std::unique_ptr< DescriptorScriptPubKeyMan > GenerateNewSingleSig(WalletStorage &storage, WalletBatch &batch, int64_t keypool_size, const CExtKey &master_key, OutputType addr_type, bool internal)
bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch) override
uint256 GetID() const override
bool DeleteRecordsWithDB(WalletBatch &batch)
Delete all the records of this LegacyScriptPubKeyMan from disk.
std::optional< MigrationData > MigrateToDescriptor()
Get the DescriptorScriptPubKeyMans (with private keys) that have the same scriptPubKeys as this Legac...
virtual bool AddKeyPubKeyInner(const CKey &key, const CPubKey &pubkey)
std::unordered_set< CScript, SaltedSipHasher > GetCandidateScriptPubKeys() const
virtual void LoadKeyMetadata(const CKeyID &keyID, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
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)
void AddInactiveHDChain(const CHDChain &chain)
bool HaveWatchOnly(const CScript &dest) const
Returns whether the watch-only script is in the wallet.
bool fDecryptionThoroughlyChecked
keeps track of whether Unlock has run a thorough check before
bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const override
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
std::unordered_set< CScript, SaltedSipHasher > GetScriptPubKeys() const override
Returns a set of all the scriptPubKeys that this ScriptPubKeyMan watches.
std::unordered_set< CScript, SaltedSipHasher > GetNotMineScriptPubKeys() const
Retrieves scripts that were imported by bugs into the legacy spkm and are simply invalid,...
bool LoadKey(const CKey &key, const CPubKey &pubkey)
Adds a key to the store, without saving it to disk (used by LoadWallet)
bool AddWatchOnlyInMem(const CScript &dest)
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
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...
bool GetKey(const CKeyID &address, CKey &keyOut) const override
bool LoadCScript(const CScript &redeemScript)
Adds a CScript to the store.
bool IsMine(const CScript &script) const override
virtual void LoadScriptMetadata(const CScriptID &script_id, const CKeyMetadata &metadata)
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that,...
std::unordered_map< CKeyID, CHDChain, SaltedSipHasher > m_inactive_hd_chains
bool AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
bool HaveKey(const CKeyID &address) const override
void LoadHDChain(const CHDChain &chain)
Load a HD chain model (used by LoadWallet)
btcsignals::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
btcsignals::signal< void(const ScriptPubKeyMan *spkm, int64_t new_birth_time)> NotifyFirstKeyTimeChanged
Birth time changed.
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.
WalletStorage & m_storage
Access to the wallet database.
bool WriteDescriptor(const uint256 &desc_id, const WalletDescriptor &descriptor)
bool WriteDescriptorCacheItems(const uint256 &desc_id, const DescriptorCache &cache)
bool TxnBegin()
Begin a new transaction.
bool TxnCommit()
Commit current transaction.
bool EraseRecords(const std::unordered_set< std::string > &types)
Delete records of the given types.
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, const CKeyMetadata &keyMeta)
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< unsigned char > &secret)
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
Descriptor with some wallet metadata.
std::shared_ptr< Descriptor > descriptor
virtual bool IsWalletFlagSet(uint64_t) const =0
virtual void TopUpCallback(const std::set< CScript > &, ScriptPubKeyMan *)=0
Callback function for after TopUp completes containing any scripts that were added by a SPKMan.
virtual std::string LogName() const =0
virtual WalletDatabase & GetDatabase() const =0
virtual void UnsetBlankWalletFlag(WalletBatch &)=0
virtual bool IsLocked() const =0
virtual bool HasEncryptionKeys() const =0
virtual bool WithEncryptionKey(std::function< bool(const CKeyingMaterial &)> cb) const =0
Pass the encryption key to cb().
static UniValue Parse(std::string_view raw, ParamFormat format=ParamFormat::JSON)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
bool MessageSign(const CKey &privkey, const std::string &message, std::string &signature)
Sign a message.
uint160 RIPEMD160(std::span< const unsigned char > data)
Compute the 160-bit RIPEMD-160 hash of an array.
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
@ WITNESS_V0
Witness v0 (P2WPKH and P2WSH); see BIP 141.
std::string EncodeDestination(const CTxDestination &dest)
std::string EncodeExtPubKey(const CExtPubKey &key)
static const auto INVALID
A stack representing the lack of any (dis)satisfactions.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
const std::unordered_set< std::string > LEGACY_TYPES
std::vector< unsigned char > valtype
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
std::map< CKeyID, std::pair< CPubKey, std::vector< unsigned char > > > CryptedKeyMap
bool DecryptKey(const CKeyingMaterial &master_key, const std::span< const unsigned char > crypted_secret, const CPubKey &pub_key, CKey &key)
static bool ExtractPubKey(const CScript &dest, CPubKey &pubKeyOut)
bool EncryptSecret(const CKeyingMaterial &vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256 &nIV, std::vector< unsigned char > &vchCiphertext)
@ WALLET_FLAG_LAST_HARDENED_XPUB_CACHED
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
std::map< CKeyID, CKey > KeyMap
WalletDescriptor GenerateWalletDescriptor(const CExtPubKey &master_key, const OutputType &addr_type, bool internal)
is a home for public enum and struct type definitions that are used internally by node code,...
void UpdatePSBTOutput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index)
Updates a PSBTOutput with information from provider.
PSBTError SignPSBTInput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index, const PrecomputedTransactionData *txdata, const common::PSBTFillOptions &options, SignatureData *out_sigdata)
Signs a PSBTInput, verifying that all provided data matches what is being signed.
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed by checking for non-null finalized fields.
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.
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
const SigningProvider & DUMMY_SIGNING_PROVIDER
CKeyID GetKeyForDestination(const SigningProvider &store, const CTxDestination &dest)
Return the CKeyID of the key involved in a script (if there is a unique one).
@ PRIVATE_KEY_NOT_AVAILABLE
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
@ WITNESS_UNKNOWN
Only for Witness versions not already defined above.
@ ANCHOR
anyone can spend script
@ NULL_DATA
unspendable OP_RETURN script that carries data
unsigned char * UCharCast(char *c)
CExtPubKey Neuter() const
void SetSeed(std::span< const std::byte > seed)
A mutable version of CTransaction.
std::map< CKeyID, CPubKey > pubkeys
std::map< CKeyID, CKey > keys
unsigned char fingerprint[4]
First 32 bits of the Hash160 of the public key at the root of the path.
std::vector< uint32_t > path
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input. May contain all signatures necessary for producing a ...
Instructions for how a PSBT should be signed or filled with information.
bool bip32_derivs
Whether to fill in bip32 derivation information if available.
bool sign
Whether to sign or not.
struct containing information needed for migrating legacy wallets to descriptor wallets
std::vector< uint16_t > keys
FuzzedDataProvider provider
consteval auto _(util::TranslatedLiteral str)
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.