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:
207 case IsMineResult::SPENDABLE:
219 bool keyPass = mapCryptedKeys.empty();
220 bool keyFail =
false;
221 CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
223 for (; mi != mapCryptedKeys.end(); ++mi)
225 const CPubKey &vchPubKey = (*mi).second.first;
226 const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
228 if (!
DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
241 if (keyPass && keyFail)
243 LogPrintf(
"The wallet is probably corrupted: Some keys decrypt but not all.\n");
244 throw std::runtime_error(
"Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
246 if (keyFail || !keyPass)
255 return std::make_unique<LegacySigningProvider>(*
this);
260 IsMineResult ismine = LegacyWalletIsMineInnerDONOTUSE(*
this,
script, IsMineSigVersion::TOP,
false);
261 if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
271 bool has_privkeys =
false;
272 for (
const auto& key_sig_pair : sigdata.
signatures) {
273 has_privkeys |=
HaveKey(key_sig_pair.first);
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);
304 mapKeyMetadata[keyID] = meta;
310 m_script_metadata[script_id] = meta;
322 if (!checksum_valid) {
334 mapCryptedKeys[vchPubKey.
GetID()] = make_pair(vchPubKey, vchCryptedSecret);
342 return setWatchOnly.count(dest) > 0;
352 std::vector<std::vector<unsigned char>> solutions;
354 (pubKeyOut =
CPubKey(solutions[0])).IsFullyValid();
360 setWatchOnly.insert(dest);
363 mapWatchKeys[pubKey.
GetID()] = pubKey;
388 return mapCryptedKeys.count(address) > 0;
398 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
399 if (mi != mapCryptedKeys.end())
401 const CPubKey &vchPubKey = (*mi).second.first;
402 const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
404 return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey, keyOut);
415 auto it = mapKeyMetadata.find(keyID);
416 if (it == mapKeyMetadata.end()) {
433 WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
434 if (it != mapWatchKeys.end()) {
435 pubkey_out = it->second;
451 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
452 if (mi != mapCryptedKeys.end())
454 vchPubKeyOut = (*mi).second.first;
464 std::unordered_set<CScript, SaltedSipHasher> candidate_spks;
467 const auto& add_pubkey = [&candidate_spks](
const CPubKey& pub) ->
void {
472 candidate_spks.insert(wpkh);
475 for (
const auto& [
_, key] : mapKeys) {
476 add_pubkey(key.GetPubKey());
478 for (
const auto& [
_, ckeypair] : mapCryptedKeys) {
479 add_pubkey(ckeypair.first);
486 const auto& add_script = [&candidate_spks](
const CScript&
script) ->
void {
487 candidate_spks.insert(
script);
491 candidate_spks.insert(wsh);
494 for (
const auto& [
_,
script] : mapScripts) {
500 for (
const auto&
script : setWatchOnly) {
504 return candidate_spks;
512 std::unordered_set<CScript, SaltedSipHasher> spks;
525 std::unordered_set<CScript, SaltedSipHasher> spks;
544 std::set<CKeyID> keyids;
545 for (
const auto& key_pair : mapKeys) {
546 keyids.insert(key_pair.first);
548 for (
const auto& key_pair : mapCryptedKeys) {
549 keyids.insert(key_pair.first);
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()) {
564 keyid_it = keyids.erase(keyid_it);
573 LogPrintf(
"Error generating descriptors for migration, cannot initialize db transaction\n");
578 for (
const CKeyID& keyid : keyids) {
580 if (!
GetKey(keyid, key)) {
585 uint64_t creation_time = 0;
586 const auto& it = mapKeyMetadata.find(keyid);
587 if (it != mapKeyMetadata.end()) {
588 creation_time = it->second.nCreateTime;
598 std::string desc_str =
"combo(" + origin_str +
HexStr(key.
GetPubKey()) +
")";
601 std::vector<std::unique_ptr<Descriptor>> descs =
Parse(desc_str, keys, error,
false);
606 auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(
m_storage, w_desc, 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();
612 for (
const CScript& spk : desc_spks) {
613 size_t erased = spks.erase(spk);
618 out.desc_spkms.push_back(std::move(desc_spk_man));
622 std::vector<CHDChain> chains;
625 chains.push_back(chain_pair.second);
630 for (
const CHDChain& chain : chains) {
631 for (
int i = 0; i < 2; ++i) {
633 if (chain.seed_id.IsNull() || (i == 1 && !can_support_hd_split_feature)) {
638 if (!
GetKey(chain.seed_id, seed_key)) {
646 std::string desc_str =
"combo(" + xpub +
"/0h/" +
ToString(i) +
"h/*h)";
649 std::vector<std::unique_ptr<Descriptor>> descs =
Parse(desc_str, keys, error,
false);
651 uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
655 auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(
m_storage, w_desc, 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();
661 for (
const CScript& spk : desc_spks) {
662 size_t erased = spks.erase(spk);
667 out.desc_spkms.push_back(std::move(desc_spk_man));
676 out.master_key.SetSeed(seed_key);
680 for (
auto it = spks.begin(); it != spks.end();) {
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;
696 std::string desc_str = desc->ToString();
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()) {
708 std::vector<CScript> scripts;
713 std::set<CKeyID> privkeyids;
714 for (
const auto& key_orig_pair : keys.
origins) {
715 privkeyids.insert(key_orig_pair.first);
718 std::vector<CScript> desc_spks;
721 std::string desc_str;
722 bool watchonly = !desc->ToPrivateString(*
this, desc_str);
724 out.watch_descs.emplace_back(desc->ToString(), creation_time);
728 desc->Expand(0, provider, desc_spks, provider);
732 auto desc_spk_man = std::make_unique<DescriptorScriptPubKeyMan>(
m_storage, w_desc, 0);
733 for (
const auto& keyid : privkeyids) {
735 if (!
GetKey(keyid, key)) {
738 WITH_LOCK(desc_spk_man->cs_desc_man, desc_spk_man->AddDescriptorKeyWithDB(batch, key, key.
GetPubKey()));
740 desc_spk_man->TopUpWithDB(batch);
741 auto desc_spks_set = desc_spk_man->GetScriptPubKeys();
742 desc_spks.insert(desc_spks.end(), desc_spks_set.begin(), desc_spks_set.end());
744 out.desc_spkms.push_back(std::move(desc_spk_man));
748 for (
const CScript& desc_spk : desc_spks) {
749 auto del_it = spks.find(desc_spk);
750 assert(del_it != spks.end());
752 it = spks.erase(del_it);
757 if (!
Assume(spks.empty())) {
769 if (!
script.IsPayToScriptHash() && !
script.IsPayToWitnessScriptHash()) {
781 uint64_t creation_time = 0;
783 if (it != m_script_metadata.end()) {
784 creation_time = it->second.nCreateTime;
789 if (!desc->IsSolvable()) {
798 std::string desc_str = desc->ToString();
800 std::string parse_error;
801 std::vector<std::unique_ptr<Descriptor>> parsed_descs =
Parse(desc_str, parsed_keys, parse_error,
false);
802 if (parsed_descs.empty()) {
807 out.solvable_descs.emplace_back(desc->ToString(), creation_time);
812 LogPrintf(
"Error generating descriptors for migration, cannot commit db transaction\n");
833 assert(m_wallet_descriptor.descriptor->IsSingleType());
834 std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
836 if (type != *desc_addr_type) {
837 throw std::runtime_error(std::string(__func__) +
": Types are inconsistent. Stored type does not match type of newly generated address");
844 std::vector<CScript> scripts_temp;
847 return util::Error{
_(
"Error: Keypool ran out, please call keypoolrefill first")};
849 if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
851 return util::Error{
_(
"Error: Keypool ran out, please call keypoolrefill first")};
856 return util::Error{
_(
"Error: Cannot extract destination from the generated scriptpubkey")};
858 m_wallet_descriptor.next_index++;
867 return m_map_script_pub_keys.contains(
script);
873 if (!m_map_keys.empty()) {
877 bool keyPass = m_map_crypted_keys.empty();
878 bool keyFail =
false;
879 for (
const auto& mi : m_map_crypted_keys) {
880 const CPubKey &pubkey = mi.second.first;
881 const std::vector<unsigned char> &crypted_secret = mi.second.second;
883 if (!
DecryptKey(master_key, crypted_secret, pubkey, key)) {
891 if (keyPass && keyFail) {
892 LogPrintf(
"The wallet is probably corrupted: Some keys decrypt but not all.\n");
893 throw std::runtime_error(
"Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
895 if (keyFail || !keyPass) {
905 if (!m_map_crypted_keys.empty()) {
909 for (
const KeyMap::value_type& key_in : m_map_keys)
911 const CKey &key = key_in.second;
914 std::vector<unsigned char> crypted_secret;
918 m_map_crypted_keys[pubkey.
GetID()] = make_pair(pubkey, crypted_secret);
929 index = m_wallet_descriptor.next_index - 1;
937 if (m_wallet_descriptor.next_index - 1 == index) {
938 m_wallet_descriptor.next_index--;
949 for (
const auto& key_pair : m_map_crypted_keys) {
950 const CPubKey& pubkey = key_pair.second.first;
951 const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
954 return DecryptKey(encryption_key, crypted_secret, pubkey, key);
956 keys[pubkey.
GetID()] = key;
966 return m_map_keys.contains(keyid) || m_map_crypted_keys.contains(keyid);
973 const auto& it = m_map_crypted_keys.find(keyid);
974 if (it == m_map_crypted_keys.end()) {
977 const std::vector<unsigned char>& crypted_secret = it->second.second;
980 return DecryptKey(encryption_key, crypted_secret, it->second.first, key);
986 const auto& it = m_map_keys.find(keyid);
987 if (it == m_map_keys.end()) {
996 if (!batch.
TxnBegin())
return false;
1005 std::set<CScript> new_spks;
1006 unsigned int target_size;
1010 target_size = m_keypool_size;
1014 int32_t new_range_end = std::max(m_wallet_descriptor.next_index + (int32_t)target_size, m_wallet_descriptor.range_end);
1017 if (!m_wallet_descriptor.descriptor->IsRange()) {
1019 m_wallet_descriptor.range_end = 1;
1020 m_wallet_descriptor.range_start = 0;
1029 std::vector<CScript> scripts_temp;
1032 if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1033 if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache))
return false;
1036 new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1038 m_map_script_pub_keys[
script] = i;
1040 for (
const auto& pk_pair : out_keys.
pubkeys) {
1041 const CPubKey& pubkey = pk_pair.second;
1042 if (m_map_pubkeys.count(pubkey) != 0) {
1047 m_map_pubkeys[pubkey] = i;
1052 throw std::runtime_error(std::string(__func__) +
": writing cache items failed");
1056 m_wallet_descriptor.range_end = new_range_end;
1070 std::vector<WalletDestination> result;
1072 int32_t index = m_map_script_pub_keys[
script];
1073 if (index >= m_wallet_descriptor.next_index) {
1074 WalletLogPrintf(
"%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
1075 auto out_keys = std::make_unique<FlatSigningProvider>();
1076 std::vector<CScript> scripts_temp;
1077 while (index >= m_wallet_descriptor.next_index) {
1078 if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
1079 throw std::runtime_error(std::string(__func__) +
": Unable to expand descriptor from cache");
1083 result.push_back({dest, std::nullopt});
1084 m_wallet_descriptor.next_index++;
1088 WalletLogPrintf(
"%s: Topping up keypool failed (locked wallet)\n", __func__);
1100 throw std::runtime_error(std::string(__func__) +
": writing descriptor private key failed");
1110 if (m_map_keys.find(pubkey.
GetID()) != m_map_keys.end() ||
1111 m_map_crypted_keys.find(pubkey.
GetID()) != m_map_crypted_keys.end()) {
1120 std::vector<unsigned char> crypted_secret;
1123 return EncryptSecret(encryption_key, secret, pubkey.GetHash(), crypted_secret);
1128 m_map_crypted_keys[pubkey.
GetID()] = make_pair(pubkey, crypted_secret);
1131 m_map_keys[pubkey.
GetID()] = key;
1142 if (m_wallet_descriptor.descriptor) {
1150 throw std::runtime_error(std::string(__func__) +
": writing descriptor master private key failed");
1153 throw std::runtime_error(std::string(__func__) +
": writing descriptor failed");
1166 return m_wallet_descriptor.descriptor->IsRange();
1174 return m_wallet_descriptor.descriptor->IsSingleType() &&
1175 m_wallet_descriptor.descriptor->IsRange() &&
1176 (
HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
1182 return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
1188 return !m_map_crypted_keys.empty();
1194 return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
1200 return m_wallet_descriptor.creation_time;
1208 auto it = m_map_script_pub_keys.find(
script);
1209 if (it == m_map_script_pub_keys.end()) {
1212 int32_t index = it->second;
1222 auto it = m_map_pubkeys.find(pubkey);
1223 if (it == m_map_pubkeys.end()) {
1226 int32_t index = it->second;
1230 if (!
out->HaveKey(pubkey.
GetID())) {
1240 std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
1248 std::vector<CScript> scripts_temp;
1249 if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys))
return nullptr;
1258 m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
1276 std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1277 for (
const auto& coin_pair : coins) {
1278 std::unique_ptr<FlatSigningProvider> coin_keys =
GetSigningProvider(coin_pair.second.out.scriptPubKey,
true);
1282 keys->Merge(std::move(*coin_keys));
1296 if (!keys->GetKey(
ToKeyID(pkhash), key)) {
1311 for (
unsigned int i = 0; i < psbtx.
tx->vin.size(); ++i) {
1312 const CTxIn& txin = psbtx.
tx->vin[i];
1325 return PSBTError::MISSING_INPUTS;
1333 std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
1336 keys->Merge(std::move(*script_keys));
1339 std::vector<CPubKey> pubkeys;
1344 pubkeys.push_back(
pk);
1348 std::vector<std::vector<unsigned char>> sols;
1350 sols[0].insert(sols[0].begin(), 0x02);
1351 pubkeys.emplace_back(sols[0]);
1353 pubkeys.emplace_back(sols[0]);
1359 for (
unsigned char prefix : {0x02, 0x03}) {
1360 unsigned char b[33] = {
prefix};
1361 std::copy(pubkey.
begin(), pubkey.
end(), b + 1);
1363 fullpubkey.
Set(b, b + 33);
1364 pubkeys.push_back(fullpubkey);
1368 for (
const auto& pubkey : pubkeys) {
1371 keys->Merge(std::move(*pk_keys));
1377 if (res != PSBTError::OK && res != PSBTError::INCOMPLETE) {
1382 if (n_signed && (signed_one || !
sign)) {
1391 for (
unsigned int i = 0; i < psbtx.
tx->vout.size(); ++i) {
1408 if (provider->GetKeyOrigin(key_id, orig)) {
1410 std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
1411 meta->key_origin = orig;
1412 meta->has_key_origin =
true;
1413 meta->nCreateTime = m_wallet_descriptor.creation_time;
1423 return m_wallet_descriptor.id;
1429 std::set<CScript> new_spks;
1430 m_wallet_descriptor.cache = cache;
1431 for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
1433 std::vector<CScript> scripts_temp;
1434 if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
1435 throw std::runtime_error(
"Error: Unable to expand wallet descriptor from cache");
1438 new_spks.insert(scripts_temp.begin(), scripts_temp.end());
1440 if (m_map_script_pub_keys.count(
script) != 0) {
1441 throw std::runtime_error(
strprintf(
"Error: Already loaded script at index %d as being at index %d", i, m_map_script_pub_keys[
script]));
1443 m_map_script_pub_keys[
script] = i;
1445 for (
const auto& pk_pair : out_keys.
pubkeys) {
1446 const CPubKey& pubkey = pk_pair.second;
1447 if (m_map_pubkeys.count(pubkey) != 0) {
1452 m_map_pubkeys[pubkey] = i;
1463 m_map_keys[key_id] = key;
1470 if (!m_map_keys.empty()) {
1474 m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
1481 return !m_wallet_descriptor.id.IsNull() && !desc.
id.
IsNull() && m_wallet_descriptor.id == desc.
id;
1489 throw std::runtime_error(std::string(__func__) +
": writing descriptor failed");
1495 return m_wallet_descriptor;
1506 std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
1507 script_pub_keys.reserve(m_map_script_pub_keys.size());
1509 for (
auto const& [script_pub_key, index] : m_map_script_pub_keys) {
1510 if (index >= minimum_index) script_pub_keys.insert(script_pub_key);
1512 return script_pub_keys;
1531 return m_wallet_descriptor.descriptor->ToPrivateString(provider,
out);
1534 return m_wallet_descriptor.descriptor->ToNormalizedString(provider,
out, &m_wallet_descriptor.cache);
1545 if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
1553 std::vector<CScript> scripts_temp;
1555 if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
1556 throw std::runtime_error(
"Unable to expand descriptor");
1562 throw std::runtime_error(std::string(__func__) +
": writing cache items failed");
1574 m_map_pubkeys.
clear();
1575 m_map_script_pub_keys.clear();
1577 m_wallet_descriptor = descriptor;
1587 error =
"can only update matching descriptor";
1596 if (descriptor.
range_start > m_wallet_descriptor.range_start ||
1597 descriptor.
range_end < m_wallet_descriptor.range_end) {
1599 error =
strprintf(
"new range must include current range = [%d,%d]",
1600 m_wallet_descriptor.range_start,
1601 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()
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)
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
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.
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)
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 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)
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
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.