29typedef std::vector<unsigned char>
valtype;
41enum class IsMineSigVersion
53enum class IsMineResult
61bool PermitsUncompressed(IsMineSigVersion sigversion)
63 return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
66bool HaveKeys(
const std::vector<valtype>& pubkeys,
const LegacyDataSPKM& keystore)
68 for (
const valtype& pubkey : pubkeys) {
70 if (!keystore.
HaveKey(keyID))
return false;
84IsMineResult LegacyWalletIsMineInnerDONOTUSE(
const LegacyDataSPKM& keystore,
const CScript& scriptPubKey, IsMineSigVersion sigversion,
bool recurse_scripthash=
true)
86 IsMineResult
ret = IsMineResult::NO;
88 std::vector<valtype> vSolutions;
101 if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
102 return IsMineResult::INVALID;
105 ret = std::max(
ret, IsMineResult::SPENDABLE);
110 if (sigversion == IsMineSigVersion::WITNESS_V0) {
112 return IsMineResult::INVALID;
125 if (!PermitsUncompressed(sigversion)) {
128 return IsMineResult::INVALID;
132 ret = std::max(
ret, IsMineResult::SPENDABLE);
137 if (sigversion != IsMineSigVersion::TOP) {
139 return IsMineResult::INVALID;
143 if (keystore.
GetCScript(scriptID, subscript)) {
144 ret = std::max(
ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
150 if (sigversion == IsMineSigVersion::WITNESS_V0) {
152 return IsMineResult::INVALID;
159 if (keystore.
GetCScript(scriptID, subscript)) {
160 ret = std::max(
ret, recurse_scripthash ? LegacyWalletIsMineInnerDONOTUSE(keystore, subscript, IsMineSigVersion::WITNESS_V0) : IsMineResult::SPENDABLE);
168 if (sigversion == IsMineSigVersion::TOP) {
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;
185 if (HaveKeys(keys, keystore)) {
186 ret = std::max(
ret, IsMineResult::SPENDABLE);
193 ret = std::max(
ret, IsMineResult::WATCH_ONLY);
202 switch (LegacyWalletIsMineInnerDONOTUSE(*
this,
script, IsMineSigVersion::TOP)) {
203 case IsMineResult::INVALID:
204 case IsMineResult::NO:
206 case IsMineResult::WATCH_ONLY:
208 case IsMineResult::SPENDABLE:
220 bool keyPass = mapCryptedKeys.empty();
221 bool keyFail =
false;
222 CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
224 for (; mi != mapCryptedKeys.end(); ++mi)
226 const CPubKey &vchPubKey = (*mi).second.first;
227 const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
229 if (!
DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
242 if (keyPass && keyFail)
244 LogPrintf(
"The wallet is probably corrupted: Some keys decrypt but not all.\n");
245 throw std::runtime_error(
"Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
247 if (keyFail || !keyPass)
256 return std::make_unique<LegacySigningProvider>(*
this);
261 IsMineResult ismine = LegacyWalletIsMineInnerDONOTUSE(*
this,
script, IsMineSigVersion::TOP,
false);
262 if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
272 bool has_privkeys =
false;
273 for (
const auto& key_sig_pair : sigdata.
signatures) {
274 has_privkeys |=
HaveKey(key_sig_pair.first);
295 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);
305 mapKeyMetadata[keyID] = meta;
311 m_script_metadata[script_id] = meta;
323 if (!checksum_valid) {
335 mapCryptedKeys[vchPubKey.
GetID()] = make_pair(vchPubKey, vchCryptedSecret);
343 return setWatchOnly.count(dest) > 0;
353 std::vector<std::vector<unsigned char>> solutions;
355 (pubKeyOut =
CPubKey(solutions[0])).IsFullyValid();
361 setWatchOnly.insert(dest);
364 mapWatchKeys[pubKey.
GetID()] = pubKey;
389 return mapCryptedKeys.count(address) > 0;
399 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
400 if (mi != mapCryptedKeys.end())
402 const CPubKey &vchPubKey = (*mi).second.first;
403 const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
405 return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey, keyOut);
416 auto it = mapKeyMetadata.find(keyID);
417 if (it == mapKeyMetadata.end()) {
434 WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
435 if (it != mapWatchKeys.end()) {
436 pubkey_out = it->second;
452 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
453 if (mi != mapCryptedKeys.end())
455 vchPubKeyOut = (*mi).second.first;
465 std::unordered_set<CScript, SaltedSipHasher> candidate_spks;
468 const auto& add_pubkey = [&candidate_spks](
const CPubKey& pub) ->
void {
473 candidate_spks.insert(wpkh);
476 for (
const auto& [
_, key] : mapKeys) {
477 add_pubkey(key.GetPubKey());
479 for (
const auto& [
_, ckeypair] : mapCryptedKeys) {
480 add_pubkey(ckeypair.first);
487 const auto& add_script = [&candidate_spks](
const CScript&
script) ->
void {
488 candidate_spks.insert(
script);
492 candidate_spks.insert(wsh);
495 for (
const auto& [
_,
script] : mapScripts) {
501 for (
const auto&
script : setWatchOnly) {
505 return candidate_spks;
513 std::unordered_set<CScript, SaltedSipHasher> spks;
526 std::unordered_set<CScript, SaltedSipHasher> spks;
545 std::set<CKeyID> keyids;
546 for (
const auto& key_pair : mapKeys) {
547 keyids.insert(key_pair.first);
549 for (
const auto& key_pair : mapCryptedKeys) {
550 keyids.insert(key_pair.first);
555 for (
auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
556 const CKeyID& keyid = *keyid_it;
557 const auto& it = mapKeyMetadata.find(keyid);
558 if (it != mapKeyMetadata.end()) {
565 keyid_it = keyids.erase(keyid_it);
574 LogPrintf(
"Error generating descriptors for migration, cannot initialize db transaction\n");
579 for (
const CKeyID& keyid : keyids) {
581 if (!
GetKey(keyid, key)) {
586 uint64_t creation_time = 0;
587 const auto& it = mapKeyMetadata.find(keyid);
588 if (it != mapKeyMetadata.end()) {
589 creation_time = it->second.nCreateTime;
599 std::string desc_str =
"combo(" + origin_str +
HexStr(key.
GetPubKey()) +
")";
602 std::vector<std::unique_ptr<Descriptor>> descs =
Parse(desc_str, keys, error,
false);
607 auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(
m_storage, w_desc, 0);
608 WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, key, key.
GetPubKey()));
609 desc_spk_man->TopUpWithDB(batch);
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::vector<CHDChain> chains;
626 chains.push_back(chain_pair.second);
628 for (
const CHDChain& chain : chains) {
629 for (
int i = 0; i < 2; ++i) {
636 if (!
GetKey(chain.seed_id, seed_key)) {
644 std::string desc_str =
"combo(" + xpub +
"/0h/" +
ToString(i) +
"h/*h)";
647 std::vector<std::unique_ptr<Descriptor>> descs =
Parse(desc_str, keys, error,
false);
649 uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
653 auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(
m_storage, w_desc, 0);
654 WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, master_key.
key, master_key.
key.
GetPubKey()));
655 desc_spk_man->TopUpWithDB(batch);
656 auto desc_spks = desc_spk_man->GetScriptPubKeys();
659 for (
const CScript& spk : desc_spks) {
660 size_t erased = spks.erase(spk);
665 out.desc_spkms.push_back(std::move(desc_spk_man));
674 out.master_key.SetSeed(seed_key);
678 for (
auto it = spks.begin(); it != spks.end();) {
682 uint64_t creation_time = 0;
683 const auto& mit = m_script_metadata.find(
CScriptID(spk));
684 if (mit != m_script_metadata.end()) {
685 creation_time = mit->second.nCreateTime;
694 std::string desc_str = desc->ToString();
696 std::string parse_error;
697 std::vector<std::unique_ptr<Descriptor>> parsed_descs =
Parse(desc_str, parsed_keys, parse_error);
698 if (parsed_descs.empty()) {
706 std::vector<CScript> scripts;
711 std::set<CKeyID> privkeyids;
712 for (
const auto& key_orig_pair : keys.
origins) {
713 privkeyids.insert(key_orig_pair.first);
716 std::vector<CScript> desc_spks;
719 std::string desc_str;
720 bool watchonly = !desc->ToPrivateString(*
this, desc_str);
722 out.watch_descs.emplace_back(desc->ToString(), creation_time);
726 desc->Expand(0, provider, desc_spks, provider);
730 auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(
m_storage, w_desc, 0);
731 for (
const auto& keyid : privkeyids) {
733 if (!
GetKey(keyid, key)) {
736 WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, key, key.
GetPubKey()));
738 desc_spk_man->TopUpWithDB(batch);
739 auto desc_spks_set = desc_spk_man->GetScriptPubKeys();
740 desc_spks.insert(desc_spks.end(), desc_spks_set.begin(), desc_spks_set.end());
742 out.desc_spkms.push_back(std::move(desc_spk_man));
746 for (
const CScript& desc_spk : desc_spks) {
747 auto del_it = spks.find(desc_spk);
748 assert(del_it != spks.end());
750 it = spks.erase(del_it);
755 if (!
Assume(spks.empty())) {
767 if (!
script.IsPayToScriptHash() && !
script.IsPayToWitnessScriptHash()) {
779 uint64_t creation_time = 0;
781 if (it != m_script_metadata.end()) {
782 creation_time = it->second.nCreateTime;
787 if (!desc->IsSolvable()) {
796 std::string desc_str = desc->ToString();
798 std::string parse_error;
799 std::vector<std::unique_ptr<Descriptor>> parsed_descs =
Parse(desc_str, parsed_keys, parse_error,
false);
800 if (parsed_descs.empty()) {
805 out.solvable_descs.emplace_back(desc->ToString(), creation_time);
810 LogPrintf(
"Error generating descriptors for migration, cannot commit db transaction\n");
831 assert(m_wallet_descriptor.descriptor->IsSingleType());
832 std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
834 if (type != *desc_addr_type) {
835 throw std::runtime_error(std::string(__func__) +
": Types are inconsistent. Stored type does not match type of newly generated address");
842 std::vector<CScript> scripts_temp;
845 return util::Error{
_(
"Error: Keypool ran out, please call keypoolrefill first")};
847 if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
849 return util::Error{
_(
"Error: Keypool ran out, please call keypoolrefill first")};
854 return util::Error{
_(
"Error: Cannot extract destination from the generated scriptpubkey")};
856 m_wallet_descriptor.next_index++;
865 if (m_map_script_pub_keys.count(
script) > 0) {
874 if (!m_map_keys.empty()) {
878 bool keyPass = m_map_crypted_keys.empty();
879 bool keyFail =
false;
880 for (
const auto& mi : m_map_crypted_keys) {
881 const CPubKey &pubkey = mi.second.first;
882 const std::vector<unsigned char> &crypted_secret = mi.second.second;
884 if (!
DecryptKey(master_key, crypted_secret, pubkey, key)) {
892 if (keyPass && keyFail) {
893 LogPrintf(
"The wallet is probably corrupted: Some keys decrypt but not all.\n");
894 throw std::runtime_error(
"Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
896 if (keyFail || !keyPass) {
906 if (!m_map_crypted_keys.empty()) {
910 for (
const KeyMap::value_type& key_in : m_map_keys)
912 const CKey &key = key_in.second;
915 std::vector<unsigned char> crypted_secret;
919 m_map_crypted_keys[pubkey.
GetID()] = make_pair(pubkey, crypted_secret);
930 index = m_wallet_descriptor.next_index - 1;
938 if (m_wallet_descriptor.next_index - 1 == index) {
939 m_wallet_descriptor.next_index--;
950 for (
const auto& key_pair : m_map_crypted_keys) {
951 const CPubKey& pubkey = key_pair.second.first;
952 const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
955 return DecryptKey(encryption_key, crypted_secret, pubkey, key);
957 keys[pubkey.
GetID()] = key;
967 return m_map_keys.contains(keyid) || m_map_crypted_keys.contains(keyid);
974 const auto& it = m_map_crypted_keys.find(keyid);
975 if (it == m_map_crypted_keys.end()) {
978 const std::vector<unsigned char>& crypted_secret = it->second.second;
981 return DecryptKey(encryption_key, crypted_secret, it->second.first, key);
987 const auto& it = m_map_keys.find(keyid);
988 if (it == m_map_keys.end()) {
997 if (!batch.
TxnBegin())
return false;
1006 std::set<CScript> new_spks;
1007 unsigned int target_size;
1011 target_size = m_keypool_size;
1015 int32_t new_range_end = std::max(m_wallet_descriptor.next_index + (int32_t)target_size, m_wallet_descriptor.range_end);
1018 if (!m_wallet_descriptor.descriptor->IsRange()) {
1020 m_wallet_descriptor.range_end = 1;
1021 m_wallet_descriptor.range_start = 0;
1030 std::vector<CScript> scripts_temp;
1033 if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1034 if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache))
return false;
1037 new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1039 m_map_script_pub_keys[
script] = i;
1041 for (
const auto& pk_pair : out_keys.
pubkeys) {
1042 const CPubKey& pubkey = pk_pair.second;
1043 if (m_map_pubkeys.count(pubkey) != 0) {
1048 m_map_pubkeys[pubkey] = i;
1053 throw std::runtime_error(std::string(__func__) +
": writing cache items failed");
1057 m_wallet_descriptor.range_end = new_range_end;
1071 std::vector<WalletDestination> result;
1073 int32_t index = m_map_script_pub_keys[
script];
1074 if (index >= m_wallet_descriptor.next_index) {
1075 WalletLogPrintf(
"%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
1076 auto out_keys = std::make_unique<FlatSigningProvider>();
1077 std::vector<CScript> scripts_temp;
1078 while (index >= m_wallet_descriptor.next_index) {
1079 if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
1080 throw std::runtime_error(std::string(__func__) +
": Unable to expand descriptor from cache");
1084 result.push_back({dest, std::nullopt});
1085 m_wallet_descriptor.next_index++;
1089 WalletLogPrintf(
"%s: Topping up keypool failed (locked wallet)\n", __func__);
1101 throw std::runtime_error(std::string(__func__) +
": writing descriptor private key failed");
1111 if (m_map_keys.find(pubkey.
GetID()) != m_map_keys.end() ||
1112 m_map_crypted_keys.find(pubkey.
GetID()) != m_map_crypted_keys.end()) {
1121 std::vector<unsigned char> crypted_secret;
1124 return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
1129 m_map_crypted_keys[pubkey.
GetID()] = make_pair(pubkey, crypted_secret);
1132 m_map_keys[pubkey.
GetID()] = key;
1143 if (m_wallet_descriptor.descriptor) {
1151 throw std::runtime_error(std::string(__func__) +
": writing descriptor master private key failed");
1154 throw std::runtime_error(std::string(__func__) +
": writing descriptor failed");
1167 return m_wallet_descriptor.descriptor->IsRange();
1175 return m_wallet_descriptor.descriptor->IsSingleType() &&
1176 m_wallet_descriptor.descriptor->IsRange() &&
1177 (
HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
1183 return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
1189 return !m_map_crypted_keys.empty();
1195 return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
1201 return m_wallet_descriptor.creation_time;
1209 auto it = m_map_script_pub_keys.find(
script);
1210 if (it == m_map_script_pub_keys.end()) {
1213 int32_t index = it->second;
1223 auto it = m_map_pubkeys.find(pubkey);
1224 if (it == m_map_pubkeys.end()) {
1227 int32_t index = it->second;
1231 if (!
out->HaveKey(pubkey.
GetID())) {
1241 std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
1249 std::vector<CScript> scripts_temp;
1250 if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys))
return nullptr;
1259 m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
1277 std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1278 for (
const auto& coin_pair : coins) {
1279 std::unique_ptr<FlatSigningProvider> coin_keys =
GetSigningProvider(coin_pair.second.out.scriptPubKey,
true);
1283 keys->Merge(std::move(*coin_keys));
1297 if (!keys->GetKey(
ToKeyID(pkhash), key)) {
1312 for (
unsigned int i = 0; i < psbtx.
tx->vin.size(); ++i) {
1313 const CTxIn& txin = psbtx.
tx->vin[i];
1326 return PSBTError::MISSING_INPUTS;
1334 std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1337 keys->Merge(std::move(*script_keys));
1340 std::vector<CPubKey> pubkeys;
1345 pubkeys.push_back(
pk);
1349 std::vector<std::vector<unsigned char>> sols;
1351 sols[0].insert(sols[0].begin(), 0x02);
1352 pubkeys.emplace_back(sols[0]);
1354 pubkeys.emplace_back(sols[0]);
1360 for (
unsigned char prefix : {0x02, 0x03}) {
1361 unsigned char b[33] = {
prefix};
1362 std::copy(pubkey.
begin(), pubkey.
end(), b + 1);
1364 fullpubkey.
Set(b, b + 33);
1365 pubkeys.push_back(fullpubkey);
1369 for (
const auto& pubkey : pubkeys) {
1372 keys->Merge(std::move(*pk_keys));
1378 if (res != PSBTError::OK && res != PSBTError::INCOMPLETE) {
1383 if (n_signed && (signed_one || !
sign)) {
1392 for (
unsigned int i = 0; i < psbtx.
tx->vout.size(); ++i) {
1409 if (provider->GetKeyOrigin(key_id, orig)) {
1411 std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
1412 meta->key_origin = orig;
1413 meta->has_key_origin =
true;
1414 meta->nCreateTime = m_wallet_descriptor.creation_time;
1424 return m_wallet_descriptor.id;
1430 std::set<CScript> new_spks;
1431 m_wallet_descriptor.cache = cache;
1432 for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
1434 std::vector<CScript> scripts_temp;
1435 if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1436 throw std::runtime_error(
"Error: Unable to expand wallet descriptor from cache");
1439 new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1441 if (m_map_script_pub_keys.count(
script) != 0) {
1442 throw std::runtime_error(
strprintf(
"Error: Already loaded script at index %d as being at index %d", i, m_map_script_pub_keys[
script]));
1444 m_map_script_pub_keys[
script] = i;
1446 for (
const auto& pk_pair : out_keys.
pubkeys) {
1447 const CPubKey& pubkey = pk_pair.second;
1448 if (m_map_pubkeys.count(pubkey) != 0) {
1453 m_map_pubkeys[pubkey] = i;
1464 m_map_keys[key_id] = key;
1471 if (!m_map_keys.empty()) {
1475 m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
1482 return !m_wallet_descriptor.id.IsNull() && !desc.
id.
IsNull() && m_wallet_descriptor.id == desc.
id;
1490 throw std::runtime_error(std::string(__func__) +
": writing descriptor failed");
1496 return m_wallet_descriptor;
1507 std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
1508 script_pub_keys.reserve(m_map_script_pub_keys.size());
1510 for (
auto const& [script_pub_key, index] : m_map_script_pub_keys) {
1511 if (index >= minimum_index) script_pub_keys.insert(script_pub_key);
1513 return script_pub_keys;
1532 return m_wallet_descriptor.descriptor->ToPrivateString(provider,
out);
1535 return m_wallet_descriptor.descriptor->ToNormalizedString(provider,
out, &m_wallet_descriptor.cache);
1546 if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
1554 std::vector<CScript> scripts_temp;
1556 if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
1557 throw std::runtime_error(
"Unable to expand descriptor");
1563 throw std::runtime_error(std::string(__func__) +
": writing cache items failed");
1575 m_map_pubkeys.
clear();
1576 m_map_script_pub_keys.clear();
1578 m_wallet_descriptor = descriptor;
1588 error =
"can only update matching descriptor";
1597 if (descriptor.
range_start > m_wallet_descriptor.range_start ||
1598 descriptor.
range_end < m_wallet_descriptor.range_end) {
1600 error =
strprintf(
"new range must include current range = [%d,%d]",
1601 m_wallet_descriptor.range_start,
1602 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 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.
An input of a transaction.
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
const unsigned char * end() const
const unsigned char * begin() const
constexpr bool IsNull() const
constexpr unsigned char * begin()
CKeyID seed_id
seed hash160
KeyMap GetKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
void SetCache(const DescriptorCache &cache)
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< 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::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,...
bool AddCryptedKey(const CKeyID &key_id, const CPubKey &pubkey, const std::vector< unsigned char > &crypted_key)
bool SetupDescriptorGeneration(WalletBatch &batch, const CExtKey &master_key, OutputType addr_type, bool internal)
Setup descriptors based on the given CExtkey.
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
std::map< CKeyID, CKey > KeyMap
unsigned int GetKeyPoolSize() const override
int64_t GetTimeFirstKey() const override
std::unique_ptr< FlatSigningProvider > GetSigningProvider(const CScript &script, bool include_private=false) const
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)
bool GetDescriptorString(std::string &out, const bool priv) const
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
bool HavePrivateKeys() const override
bool AddKey(const CKeyID &key_id, const CKey &key)
util::Result< CTxDestination > GetReservedDestination(const OutputType type, bool internal, int64_t &index) override
util::Result< void > UpdateWalletDescriptor(WalletDescriptor &descriptor)
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...
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.
util::Result< CTxDestination > GetNewDestination(const OutputType type) override
bool IsHDEnabled() const override
isminetype IsMine(const CScript &script) const override
bool HasPrivKey(const CKeyID &keyid) const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
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.
isminetype IsMine(const CScript &script) const override
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.
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)
boost::signals2::signal< void(const ScriptPubKeyMan *spkm, int64_t new_birth_time)> NotifyFirstKeyTimeChanged
Birth time changed.
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.
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 bool CanSupportFeature(enum WalletFeature) const =0
virtual std::string GetDisplayName() 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)
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 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)
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
isminetype
IsMine() return codes, which depend on ScriptPubKeyMan implementation.
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
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.
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed by checking for non-null finalized fields.
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.
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, std::pair< CPubKey, KeyOriginInfo > > origins
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
A version of CTransaction with the PSBT format.
std::vector< PSBTInput > inputs
std::optional< CMutableTransaction > tx
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input. May contain all signatures necessary for producing a ...
struct containing information needed for migrating legacy wallets to descriptor wallets
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
consteval auto _(util::TranslatedLiteral str)
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.