27 return util::Error{
_(
"Error: Legacy wallets only support the \"legacy\", \"p2sh-segwit\", and \"bech32\" address types")};
36 return util::Error{
_(
"Error: Keypool ran out, please call keypoolrefill first")};
42 typedef std::vector<unsigned char>
valtype;
72 bool PermitsUncompressed(IsMineSigVersion sigversion)
77 bool HaveKeys(
const std::vector<valtype>& pubkeys,
const LegacyScriptPubKeyMan& keystore)
79 for (
const valtype& pubkey : pubkeys) {
81 if (!keystore.HaveKey(keyID))
return false;
94 IsMineResult IsMineInner(
const LegacyScriptPubKeyMan& keystore,
const CScript& scriptPubKey, IsMineSigVersion sigversion,
bool recurse_scripthash=
true)
98 std::vector<valtype> vSolutions;
110 if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
111 return IsMineResult::INVALID;
113 if (keystore.HaveKey(keyID)) {
114 ret = std::max(
ret, IsMineResult::SPENDABLE);
121 return IsMineResult::INVALID;
134 if (!PermitsUncompressed(sigversion)) {
136 if (keystore.GetPubKey(keyID, pubkey) && !pubkey.
IsCompressed()) {
137 return IsMineResult::INVALID;
140 if (keystore.HaveKey(keyID)) {
141 ret = std::max(
ret, IsMineResult::SPENDABLE);
148 return IsMineResult::INVALID;
152 if (keystore.GetCScript(scriptID, subscript)) {
161 return IsMineResult::INVALID;
170 if (keystore.GetCScript(scriptID, subscript)) {
188 std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
189 if (!PermitsUncompressed(sigversion)) {
190 for (
size_t i = 0; i < keys.size(); i++) {
191 if (keys[i].size() != 33) {
192 return IsMineResult::INVALID;
196 if (HaveKeys(keys, keystore)) {
197 ret = std::max(
ret, IsMineResult::SPENDABLE);
203 if (
ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
204 ret = std::max(
ret, IsMineResult::WATCH_ONLY);
214 case IsMineResult::INVALID:
215 case IsMineResult::NO:
217 case IsMineResult::WATCH_ONLY:
219 case IsMineResult::SPENDABLE:
231 bool keyPass = mapCryptedKeys.empty();
232 bool keyFail =
false;
233 CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
235 for (; mi != mapCryptedKeys.end(); ++mi)
237 const CPubKey &vchPubKey = (*mi).second.first;
238 const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
240 if (!
DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
250 batch.WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.
GetID()]);
253 if (keyPass && keyFail)
255 LogPrintf(
"The wallet is probably corrupted: Some keys decrypt but not all.\n");
256 throw std::runtime_error(
"Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
258 if (keyFail || (!keyPass && !accept_no_keys))
268 encrypted_batch = batch;
269 if (!mapCryptedKeys.empty()) {
270 encrypted_batch =
nullptr;
275 keys_to_encrypt.swap(mapKeys);
276 for (
const KeyMap::value_type& mKey : keys_to_encrypt)
278 const CKey &key = mKey.second;
281 std::vector<unsigned char> vchCryptedSecret;
283 encrypted_batch =
nullptr;
287 encrypted_batch =
nullptr;
291 encrypted_batch =
nullptr;
298 return util::Error{
_(
"Error: Legacy wallets only support the \"legacy\", \"p2sh-segwit\", and \"bech32\" address types")};
304 return util::Error{
_(
"Error: Keypool ran out, please call keypoolrefill first")};
308 return util::Error{
_(
"Error: Keypool ran out, please call keypoolrefill first")};
338 std::vector<WalletDestination> result;
343 WalletLogPrintf(
"%s: Detected a used keypool key, mark all keypool keys up to this key as used\n", __func__);
348 result.push_back({dest, keypool.fInternal});
353 WalletLogPrintf(
"%s: Topping up keypool failed (locked wallet)\n", __func__);
359 auto it = mapKeyMetadata.find(keyid);
360 if (it != mapKeyMetadata.end()){
363 std::vector<uint32_t> path;
367 WalletLogPrintf(
"%s: Adding inactive seed keys failed, invalid hdKeypath: %s\n",
371 if (path.size() != 3) {
372 WalletLogPrintf(
"%s: Adding inactive seed keys failed, invalid path size: %d, has_key_origin: %s\n",
399 for (
auto& meta_pair : mapKeyMetadata) {
410 throw std::runtime_error(
"Invalid stored hdKeypath");
419 if (
GetPubKey(meta_pair.first, pubkey)) {
420 batch->WriteKeyMetadata(meta, pubkey,
true);
448 bool keypool_has_keys;
450 keypool_has_keys = setInternalKeyPool.size() > 0;
455 if (!keypool_has_keys) {
458 return keypool_has_keys;
470 bool hd_upgrade =
false;
471 bool split_upgrade =
false;
490 throw std::runtime_error(std::string(__func__) +
": writing chain failed");
501 error =
_(
"Unable to generate keys");
511 return !mapKeys.empty() || !mapCryptedKeys.empty();
517 setInternalKeyPool.clear();
518 setExternalKeyPool.clear();
526 if (setKeyPool.empty()) {
531 int64_t nIndex = *(setKeyPool.begin());
532 if (!batch.
ReadPool(nIndex, keypool)) {
533 throw std::runtime_error(std::string(__func__) +
": read oldest key in keypool failed");
536 return keypool.
nTime;
549 if (!set_pre_split_keypool.empty()) {
560 return setExternalKeyPool.size() + set_pre_split_keypool.size();
566 return setInternalKeyPool.size() + setExternalKeyPool.size() + set_pre_split_keypool.size();
572 return nTimeFirstKey;
577 return std::make_unique<LegacySigningProvider>(*this);
583 if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
593 bool has_privkeys =
false;
594 for (
const auto& key_sig_pair : sigdata.
signatures) {
595 has_privkeys |=
HaveKey(key_sig_pair.first);
626 for (
unsigned int i = 0; i < psbtx.
tx->vin.size(); ++i) {
627 const CTxIn& txin = psbtx.
tx->vin[i];
653 if (n_signed && (signed_one || !sign)) {
662 for (
unsigned int i = 0; i < psbtx.
tx->vout.size(); ++i) {
675 auto it = mapKeyMetadata.find(key_id);
676 if (it != mapKeyMetadata.end()) {
677 return std::make_unique<CKeyMetadata>(it->second);
682 auto it = m_script_metadata.find(
CScriptID(scriptPubKey));
683 if (it != m_script_metadata.end()) {
684 return std::make_unique<CKeyMetadata>(it->second);
702 if (nCreateTime <= 1) {
706 }
else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
707 nTimeFirstKey = nCreateTime;
733 bool needsDB = !encrypted_batch;
735 encrypted_batch = &batch;
738 if (needsDB) encrypted_batch =
nullptr;
741 if (needsDB) encrypted_batch =
nullptr;
757 mapKeyMetadata[pubkey.
GetID()]);
771 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);
782 mapKeyMetadata[keyID] = meta;
789 m_script_metadata[script_id] = meta;
803 std::vector<unsigned char> vchCryptedSecret;
818 if (!checksum_valid) {
830 mapCryptedKeys[vchPubKey.
GetID()] = make_pair(vchPubKey, vchCryptedSecret);
836 const std::vector<unsigned char> &vchCryptedSecret)
843 return encrypted_batch->WriteCryptedKey(vchPubKey,
845 mapKeyMetadata[vchPubKey.
GetID()]);
849 mapKeyMetadata[vchPubKey.
GetID()]);
856 return setWatchOnly.count(dest) > 0;
862 return (!setWatchOnly.empty());
867 std::vector<std::vector<unsigned char>> solutions;
869 (pubKeyOut =
CPubKey(solutions[0])).IsFullyValid();
876 setWatchOnly.erase(dest);
879 mapWatchKeys.erase(pubKey.
GetID());
901 setWatchOnly.insert(dest);
904 mapWatchKeys[pubKey.
GetID()] = pubKey;
926 m_script_metadata[
CScriptID(dest)].nCreateTime = create_time;
938 m_script_metadata[
CScriptID(dest)].nCreateTime = nCreateTime;
953 throw std::runtime_error(std::string(__func__) +
": writing chain failed");
976 return mapCryptedKeys.count(address) > 0;
986 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
987 if (mi != mapCryptedKeys.end())
989 const CPubKey &vchPubKey = (*mi).second.first;
990 const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
1001 auto it = mapKeyMetadata.find(keyID);
1002 if (it == mapKeyMetadata.end()) {
1019 WatchKeyMap::const_iterator it = mapWatchKeys.find(address);
1020 if (it != mapWatchKeys.end()) {
1021 pubkey_out = it->second;
1037 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
1038 if (mi != mapCryptedKeys.end())
1040 vchPubKeyOut = (*mi).second.first;
1057 int64_t nCreationTime =
GetTime();
1075 mapKeyMetadata[pubkey.
GetID()] = metadata;
1079 throw std::runtime_error(std::string(__func__) +
": AddKey failed");
1086 if (!key_in.
Derive(key_out, index)) {
1087 throw std::runtime_error(
"Could not derive extended key");
1102 throw std::runtime_error(std::string(__func__) +
": seed not found");
1136 secret = childKey.
key;
1143 throw std::runtime_error(std::string(__func__) +
": writing HD chain model failed");
1150 set_pre_split_keypool.insert(nIndex);
1152 setInternalKeyPool.insert(nIndex);
1154 setExternalKeyPool.insert(nIndex);
1156 m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
1163 if (mapKeyMetadata.count(keyid) == 0)
1184 int64_t nCreationTime =
GetTime();
1200 mapKeyMetadata[seed.
GetID()] = metadata;
1204 throw std::runtime_error(std::string(__func__) +
": AddKeyPubKey failed");
1238 for (
const int64_t nIndex : setInternalKeyPool) {
1241 setInternalKeyPool.clear();
1243 for (
const int64_t nIndex : setExternalKeyPool) {
1244 batch.ErasePool(nIndex);
1246 setExternalKeyPool.clear();
1248 for (
const int64_t nIndex : set_pre_split_keypool) {
1249 batch.ErasePool(nIndex);
1251 set_pre_split_keypool.clear();
1258 WalletLogPrintf(
"LegacyScriptPubKeyMan::NewKeyPool rewrote keypool\n");
1288 unsigned int nTargetSize;
1290 nTargetSize = kpSize;
1294 int64_t target = std::max((int64_t) nTargetSize, int64_t{1});
1298 int64_t missingExternal;
1299 int64_t missingInternal;
1301 missingExternal = std::max(target - (int64_t)setExternalKeyPool.size(), int64_t{0});
1302 missingInternal = std::max(target - (int64_t)setInternalKeyPool.size(), int64_t{0});
1310 missingInternal = 0;
1312 bool internal =
false;
1314 for (int64_t i = missingInternal + missingExternal; i--;) {
1315 if (i < missingInternal) {
1324 if (missingInternal + missingExternal > 0) {
1326 WalletLogPrintf(
"keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size() + set_pre_split_keypool.size(), setInternalKeyPool.size());
1328 WalletLogPrintf(
"inactive seed with id %s added %d external keys, %d internal keys\n",
HexStr(chain.
seed_id), missingExternal, missingInternal);
1337 assert(m_max_keypool_index < std::numeric_limits<int64_t>::max());
1338 int64_t index = ++m_max_keypool_index;
1340 throw std::runtime_error(std::string(__func__) +
": writing imported pubkey failed");
1343 setInternalKeyPool.insert(index);
1345 setExternalKeyPool.insert(index);
1370 setInternalKeyPool.insert(nIndex);
1371 }
else if (!set_pre_split_keypool.empty()) {
1372 set_pre_split_keypool.insert(nIndex);
1374 setExternalKeyPool.insert(nIndex);
1414 bool fReturningInternal = fRequestedInternal;
1416 bool use_split_keypool = set_pre_split_keypool.empty();
1417 std::set<int64_t>& setKeyPool = use_split_keypool ? (fReturningInternal ? setInternalKeyPool : setExternalKeyPool) : set_pre_split_keypool;
1420 if (setKeyPool.empty()) {
1426 auto it = setKeyPool.begin();
1428 setKeyPool.erase(it);
1429 if (!batch.ReadPool(nIndex, keypool)) {
1430 throw std::runtime_error(std::string(__func__) +
": read failed");
1434 throw std::runtime_error(std::string(__func__) +
": unknown key in key pool");
1437 if (use_split_keypool && keypool.
fInternal != fReturningInternal) {
1438 throw std::runtime_error(std::string(__func__) +
": keypool entry misclassified");
1441 throw std::runtime_error(std::string(__func__) +
": keypool entry invalid");
1461 assert(desc && desc->IsSolvable());
1475 bool internal = setInternalKeyPool.count(keypool_id);
1476 if (!
internal)
assert(setExternalKeyPool.count(keypool_id) || set_pre_split_keypool.count(keypool_id));
1477 std::set<int64_t> *setKeyPool =
internal ? &setInternalKeyPool : (set_pre_split_keypool.empty() ? &setExternalKeyPool : &set_pre_split_keypool);
1478 auto it = setKeyPool->begin();
1480 std::vector<CKeyPool> result;
1482 while (it != std::end(*setKeyPool)) {
1483 const int64_t& index = *(it);
1484 if (index > keypool_id)
break;
1487 if (batch.ReadPool(index, keypool)) {
1491 batch.ErasePool(index);
1493 it = setKeyPool->erase(it);
1494 result.push_back(std::move(keypool));
1502 std::vector<CScript> dummy;
1505 std::vector<CKeyID>
ret;
1506 for (
const auto& entry : out.
pubkeys) {
1507 ret.push_back(entry.first);
1515 for (
auto it = setExternalKeyPool.begin(); it != setExternalKeyPool.end();) {
1516 int64_t index = *it;
1518 if (!batch.ReadPool(index, keypool)) {
1519 throw std::runtime_error(std::string(__func__) +
": read keypool entry failed");
1522 if (!batch.WritePool(index, keypool)) {
1523 throw std::runtime_error(std::string(__func__) +
": writing modified keypool entry failed");
1525 set_pre_split_keypool.insert(index);
1526 it = setExternalKeyPool.erase(it);
1551 mapKeyMetadata[pubkey.
GetID()].key_origin.path = info.
path;
1552 mapKeyMetadata[pubkey.
GetID()].has_key_origin =
true;
1560 for (
const auto& entry : scripts) {
1570 if (timestamp > 0) {
1571 m_script_metadata[
CScriptID(entry)].nCreateTime = timestamp;
1574 if (timestamp > 0) {
1584 for (
const auto& entry : privkey_map) {
1585 const CKey& key = entry.second;
1587 const CKeyID&
id = entry.first;
1594 mapKeyMetadata[id].nCreateTime = timestamp;
1604 bool LegacyScriptPubKeyMan::ImportPubKeys(
const std::vector<CKeyID>& ordered_pubkeys,
const std::map<CKeyID, CPubKey>& pubkey_map,
const std::map<
CKeyID, std::pair<CPubKey, KeyOriginInfo>>& key_origins,
const bool add_keypool,
const bool internal,
const int64_t timestamp)
1607 for (
const auto& entry : key_origins) {
1610 for (
const CKeyID&
id : ordered_pubkeys) {
1611 auto entry = pubkey_map.find(
id);
1612 if (entry == pubkey_map.end()) {
1615 const CPubKey& pubkey = entry->second;
1625 mapKeyMetadata[id].nCreateTime = timestamp;
1639 for (
const CScript& script : script_pub_keys) {
1640 if (!have_solving_data || !
IsMine(script)) {
1655 std::set<CKeyID> set_address;
1656 for (
const auto& mi : mapCryptedKeys) {
1657 set_address.insert(mi.first);
1665 std::unordered_set<CScript, SaltedSipHasher> spks;
1668 for (
const auto& key_pair : mapKeys) {
1669 const CPubKey& pub = key_pair.second.GetPubKey();
1673 for (
const auto& key_pair : mapCryptedKeys) {
1674 const CPubKey& pub = key_pair.second.first;
1682 for (
const auto& script_pair : mapScripts) {
1683 const CScript& script = script_pair.second;
1691 std::vector<unsigned char> witprog;
1693 spks.insert(script);
1698 std::vector<std::vector<unsigned char>> sols;
1703 spks.insert(ms_spk);
1710 spks.insert(setWatchOnly.begin(), setWatchOnly.end());
1719 return std::nullopt;
1727 std::set<CKeyID> keyids;
1728 for (
const auto& key_pair : mapKeys) {
1729 keyids.insert(key_pair.first);
1731 for (
const auto& key_pair : mapCryptedKeys) {
1732 keyids.insert(key_pair.first);
1737 for (
auto keyid_it = keyids.begin(); keyid_it != keyids.end();) {
1738 const CKeyID& keyid = *keyid_it;
1739 const auto& it = mapKeyMetadata.find(keyid);
1740 if (it != mapKeyMetadata.end()) {
1747 keyid_it = keyids.erase(keyid_it);
1755 for (
const CKeyID& keyid : keyids) {
1757 if (!
GetKey(keyid, key)) {
1762 uint64_t creation_time = 0;
1763 const auto& it = mapKeyMetadata.find(keyid);
1764 if (it != mapKeyMetadata.end()) {
1765 creation_time = it->second.nCreateTime;
1775 std::string desc_str =
"combo(" + origin_str +
HexStr(key.
GetPubKey()) +
")";
1778 std::unique_ptr<Descriptor> desc =
Parse(desc_str, keys,
error,
false);
1783 desc_spk_man->AddDescriptorKey(key, key.
GetPubKey());
1784 desc_spk_man->TopUp();
1785 auto desc_spks = desc_spk_man->GetScriptPubKeys();
1788 for (
const CScript& spk : desc_spks) {
1789 size_t erased = spks.erase(spk);
1794 out.
desc_spkms.push_back(std::move(desc_spk_man));
1798 std::vector<CHDChain> chains;
1801 chains.push_back(chain_pair.second);
1803 for (
const CHDChain& chain : chains) {
1804 for (
int i = 0; i < 2; ++i) {
1811 if (!
GetKey(chain.seed_id, seed_key)) {
1819 std::string desc_str =
"combo(" + xpub +
"/0'/" +
ToString(i) +
"'/*')";
1822 std::unique_ptr<Descriptor> desc =
Parse(desc_str, keys,
error,
false);
1823 uint32_t chain_counter = std::max((i == 1 ? chain.nInternalChainCounter : chain.nExternalChainCounter), (uint32_t)0);
1828 desc_spk_man->AddDescriptorKey(master_key.
key, master_key.
key.
GetPubKey());
1829 desc_spk_man->TopUp();
1830 auto desc_spks = desc_spk_man->GetScriptPubKeys();
1833 for (
const CScript& spk : desc_spks) {
1834 size_t erased = spks.erase(spk);
1839 out.
desc_spkms.push_back(std::move(desc_spk_man));
1852 for (
auto it = spks.begin(); it != spks.end();) {
1856 uint64_t creation_time = 0;
1857 const auto& mit = m_script_metadata.find(
CScriptID(spk));
1858 if (mit != m_script_metadata.end()) {
1859 creation_time = mit->second.nCreateTime;
1865 std::vector<CScript> scripts;
1870 std::set<CKeyID> privkeyids;
1871 for (
const auto& key_orig_pair : keys.
origins) {
1872 privkeyids.insert(key_orig_pair.first);
1875 std::vector<CScript> desc_spks;
1878 std::string desc_str;
1879 bool watchonly = !desc->ToPrivateString(*
this, desc_str);
1881 out.
watch_descs.push_back({desc->ToString(), creation_time});
1885 desc->Expand(0, provider, desc_spks, provider);
1890 for (
const auto& keyid : privkeyids) {
1892 if (!
GetKey(keyid, key)) {
1895 desc_spk_man->AddDescriptorKey(key, key.
GetPubKey());
1897 desc_spk_man->TopUp();
1898 auto desc_spks_set = desc_spk_man->GetScriptPubKeys();
1899 desc_spks.insert(desc_spks.end(), desc_spks_set.begin(), desc_spks_set.end());
1901 out.
desc_spkms.push_back(std::move(desc_spk_man));
1905 for (
const CScript& desc_spk : desc_spks) {
1906 auto del_it = spks.find(desc_spk);
1907 assert(del_it != spks.end());
1909 it = spks.erase(del_it);
1915 for (
const auto& script_pair : mapScripts) {
1916 const CScript script = script_pair.second;
1919 uint64_t creation_time = 0;
1920 const auto& it = m_script_metadata.find(
CScriptID(script));
1921 if (it != m_script_metadata.end()) {
1922 creation_time = it->second.nCreateTime;
1925 std::vector<std::vector<unsigned char>> sols;
1941 std::vector<std::vector<unsigned char>> keys(sols.begin() + 1, sols.begin() + sols.size() - 1);
1950 out.
solvable_descs.push_back({sh_desc->ToString(), creation_time});
1953 if (desc->IsSolvable()) {
1955 out.
solvable_descs.push_back({wsh_desc->ToString(), creation_time});
1957 out.
solvable_descs.push_back({sh_wsh_desc->ToString(), creation_time});
1963 assert(spks.size() == 0);
1982 assert(m_wallet_descriptor.descriptor->IsSingleType());
1983 std::optional<OutputType> desc_addr_type = m_wallet_descriptor.descriptor->GetOutputType();
1985 if (type != *desc_addr_type) {
1986 throw std::runtime_error(std::string(__func__) +
": Types are inconsistent");
1993 std::vector<CScript> scripts_temp;
1996 return util::Error{
_(
"Error: Keypool ran out, please call keypoolrefill first")};
1998 if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2000 return util::Error{
_(
"Error: Keypool ran out, please call keypoolrefill first")};
2004 std::optional<OutputType> out_script_type = m_wallet_descriptor.descriptor->GetOutputType();
2005 if (out_script_type && out_script_type == type) {
2008 throw std::runtime_error(std::string(__func__) +
": Types are inconsistent. Stored type does not match type of newly generated address");
2010 m_wallet_descriptor.next_index++;
2019 if (m_map_script_pub_keys.count(script) > 0) {
2028 if (!m_map_keys.empty()) {
2032 bool keyPass = m_map_crypted_keys.empty();
2033 bool keyFail =
false;
2034 for (
const auto& mi : m_map_crypted_keys) {
2035 const CPubKey &pubkey = mi.second.first;
2036 const std::vector<unsigned char> &crypted_secret = mi.second.second;
2038 if (!
DecryptKey(master_key, crypted_secret, pubkey, key)) {
2046 if (keyPass && keyFail) {
2047 LogPrintf(
"The wallet is probably corrupted: Some keys decrypt but not all.\n");
2048 throw std::runtime_error(
"Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
2050 if (keyFail || (!keyPass && !accept_no_keys)) {
2060 if (!m_map_crypted_keys.empty()) {
2064 for (
const KeyMap::value_type& key_in : m_map_keys)
2066 const CKey &key = key_in.second;
2069 std::vector<unsigned char> crypted_secret;
2073 m_map_crypted_keys[pubkey.
GetID()] = make_pair(pubkey, crypted_secret);
2084 index = m_wallet_descriptor.next_index - 1;
2092 if (m_wallet_descriptor.next_index - 1 == index) {
2093 m_wallet_descriptor.next_index--;
2104 for (
const auto& key_pair : m_map_crypted_keys) {
2105 const CPubKey& pubkey = key_pair.second.first;
2106 const std::vector<unsigned char>& crypted_secret = key_pair.second.second;
2109 keys[pubkey.GetID()] = key;
2119 unsigned int target_size;
2127 int32_t new_range_end = std::max(m_wallet_descriptor.next_index + (int32_t)target_size, m_wallet_descriptor.range_end);
2130 if (!m_wallet_descriptor.descriptor->IsRange()) {
2132 m_wallet_descriptor.range_end = 1;
2133 m_wallet_descriptor.range_start = 0;
2143 std::vector<CScript> scripts_temp;
2146 if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2147 if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache))
return false;
2150 for (
const CScript& script : scripts_temp) {
2151 m_map_script_pub_keys[script] = i;
2153 for (
const auto& pk_pair : out_keys.
pubkeys) {
2154 const CPubKey& pubkey = pk_pair.second;
2155 if (m_map_pubkeys.count(pubkey) != 0) {
2160 m_map_pubkeys[pubkey] = i;
2164 if (!batch.WriteDescriptorCacheItems(
id, new_items)) {
2165 throw std::runtime_error(std::string(__func__) +
": writing cache items failed");
2169 m_wallet_descriptor.range_end = new_range_end;
2170 batch.WriteDescriptor(
GetID(), m_wallet_descriptor);
2182 std::vector<WalletDestination> result;
2184 int32_t index = m_map_script_pub_keys[script];
2185 if (index >= m_wallet_descriptor.next_index) {
2186 WalletLogPrintf(
"%s: Detected a used keypool item at index %d, mark all keypool items up to this item as used\n", __func__, index);
2187 auto out_keys = std::make_unique<FlatSigningProvider>();
2188 std::vector<CScript> scripts_temp;
2189 while (index >= m_wallet_descriptor.next_index) {
2190 if (!m_wallet_descriptor.descriptor->ExpandFromCache(m_wallet_descriptor.next_index, m_wallet_descriptor.cache, scripts_temp, *out_keys)) {
2191 throw std::runtime_error(std::string(__func__) +
": Unable to expand descriptor from cache");
2195 result.push_back({dest, std::nullopt});
2196 m_wallet_descriptor.next_index++;
2200 WalletLogPrintf(
"%s: Topping up keypool failed (locked wallet)\n", __func__);
2212 throw std::runtime_error(std::string(__func__) +
": writing descriptor private key failed");
2222 if (m_map_keys.find(pubkey.
GetID()) != m_map_keys.end() ||
2223 m_map_crypted_keys.find(pubkey.
GetID()) != m_map_crypted_keys.end()) {
2232 std::vector<unsigned char> crypted_secret;
2238 m_map_crypted_keys[pubkey.
GetID()] = make_pair(pubkey, crypted_secret);
2241 m_map_keys[pubkey.
GetID()] = key;
2252 if (m_wallet_descriptor.descriptor) {
2256 int64_t creation_time =
GetTime();
2261 std::string desc_prefix;
2262 std::string desc_suffix =
"/*)";
2263 switch (addr_type) {
2265 desc_prefix =
"pkh(" + xpub +
"/44'";
2269 desc_prefix =
"sh(wpkh(" + xpub +
"/49'";
2274 desc_prefix =
"wpkh(" + xpub +
"/84'";
2278 desc_prefix =
"tr(" + xpub +
"/86'";
2287 assert(!desc_prefix.empty());
2291 desc_prefix +=
"/1'";
2293 desc_prefix +=
"/0'";
2296 std::string internal_path =
internal ?
"/1" :
"/0";
2297 std::string desc_str = desc_prefix +
"/0'" + internal_path + desc_suffix;
2302 std::unique_ptr<Descriptor> desc =
Parse(desc_str, keys,
error,
false);
2304 m_wallet_descriptor = w_desc;
2309 throw std::runtime_error(std::string(__func__) +
": writing descriptor master private key failed");
2311 if (!batch.WriteDescriptor(
GetID(), m_wallet_descriptor)) {
2312 throw std::runtime_error(std::string(__func__) +
": writing descriptor failed");
2325 return m_wallet_descriptor.descriptor->IsRange();
2333 return m_wallet_descriptor.descriptor->IsSingleType() &&
2334 m_wallet_descriptor.descriptor->IsRange() &&
2335 (
HavePrivateKeys() || m_wallet_descriptor.next_index < m_wallet_descriptor.range_end);
2341 return m_map_keys.size() > 0 || m_map_crypted_keys.size() > 0;
2347 return std::nullopt;
2354 return m_wallet_descriptor.range_end - m_wallet_descriptor.next_index;
2360 return m_wallet_descriptor.creation_time;
2368 auto it = m_map_script_pub_keys.find(script);
2369 if (it == m_map_script_pub_keys.end()) {
2372 int32_t index = it->second;
2382 auto it = m_map_pubkeys.find(pubkey);
2383 if (it == m_map_pubkeys.end()) {
2386 int32_t index = it->second;
2396 std::unique_ptr<FlatSigningProvider> out_keys = std::make_unique<FlatSigningProvider>();
2404 std::vector<CScript> scripts_temp;
2405 if (!m_wallet_descriptor.descriptor->ExpandFromCache(index, m_wallet_descriptor.cache, scripts_temp, *out_keys))
return nullptr;
2414 m_wallet_descriptor.descriptor->ExpandPrivate(index, master_provider, *out_keys);
2432 std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
2433 for (
const auto& coin_pair : coins) {
2434 std::unique_ptr<FlatSigningProvider> coin_keys =
GetSigningProvider(coin_pair.second.out.scriptPubKey,
true);
2438 keys->Merge(std::move(*coin_keys));
2452 if (!keys->GetKey(
ToKeyID(pkhash), key)) {
2467 for (
unsigned int i = 0; i < psbtx.
tx->vin.size(); ++i) {
2468 const CTxIn& txin = psbtx.
tx->vin[i];
2496 std::unique_ptr<FlatSigningProvider> keys = std::make_unique<FlatSigningProvider>();
2499 keys->Merge(std::move(*script_keys));
2502 std::vector<CPubKey> pubkeys;
2506 pubkeys.push_back(pk);
2510 std::vector<std::vector<unsigned char>> sols;
2512 sols[0].insert(sols[0].begin(), 0x02);
2513 pubkeys.emplace_back(sols[0]);
2515 pubkeys.emplace_back(sols[0]);
2521 for (
unsigned char prefix : {0x02, 0x03}) {
2522 unsigned char b[33] = {
prefix};
2523 std::copy(pubkey.
begin(), pubkey.
end(), b + 1);
2525 fullpubkey.
Set(b, b + 33);
2526 pubkeys.push_back(fullpubkey);
2530 for (
const auto& pubkey : pubkeys) {
2533 keys->Merge(std::move(*pk_keys));
2541 if (n_signed && (signed_one || !sign)) {
2550 for (
unsigned int i = 0; i < psbtx.
tx->vout.size(); ++i) {
2567 if (provider->GetKeyOrigin(key_id, orig)) {
2569 std::unique_ptr<CKeyMetadata> meta = std::make_unique<CKeyMetadata>();
2570 meta->key_origin = orig;
2571 meta->has_key_origin =
true;
2572 meta->nCreateTime = m_wallet_descriptor.creation_time;
2582 std::string desc_str = m_wallet_descriptor.descriptor->ToString();
2584 CSHA256().
Write((
unsigned char*)desc_str.data(), desc_str.size()).Finalize(
id.begin());
2591 m_wallet_descriptor.cache = cache;
2592 for (int32_t i = m_wallet_descriptor.range_start; i < m_wallet_descriptor.range_end; ++i) {
2594 std::vector<CScript> scripts_temp;
2595 if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
2596 throw std::runtime_error(
"Error: Unable to expand wallet descriptor from cache");
2599 for (
const CScript& script : scripts_temp) {
2600 if (m_map_script_pub_keys.count(script) != 0) {
2601 throw std::runtime_error(
strprintf(
"Error: Already loaded script at index %d as being at index %d", i, m_map_script_pub_keys[script]));
2603 m_map_script_pub_keys[script] = i;
2605 for (
const auto& pk_pair : out_keys.
pubkeys) {
2606 const CPubKey& pubkey = pk_pair.second;
2607 if (m_map_pubkeys.count(pubkey) != 0) {
2612 m_map_pubkeys[pubkey] = i;
2621 m_map_keys[key_id] = key;
2628 if (!m_map_keys.empty()) {
2632 m_map_crypted_keys[key_id] = make_pair(pubkey, crypted_key);
2639 return m_wallet_descriptor.descriptor !=
nullptr && desc.
descriptor !=
nullptr && m_wallet_descriptor.descriptor->ToString() == desc.
descriptor->ToString();
2646 if (!batch.WriteDescriptor(
GetID(), m_wallet_descriptor)) {
2647 throw std::runtime_error(std::string(__func__) +
": writing descriptor failed");
2653 return m_wallet_descriptor;
2659 std::unordered_set<CScript, SaltedSipHasher> script_pub_keys;
2660 script_pub_keys.reserve(m_map_script_pub_keys.size());
2662 for (
auto const& script_pub_key: m_map_script_pub_keys) {
2663 script_pub_keys.insert(script_pub_key.first);
2665 return script_pub_keys;
2679 return m_wallet_descriptor.descriptor->ToPrivateString(provider, out);
2682 return m_wallet_descriptor.descriptor->ToNormalizedString(provider, out, &m_wallet_descriptor.cache);
2693 if (m_wallet_descriptor.cache.GetCachedLastHardenedExtPubKeys().size() > 0) {
2701 std::vector<CScript> scripts_temp;
2703 if (!m_wallet_descriptor.descriptor->Expand(0, provider, scripts_temp, out_keys, &temp_cache)){
2704 throw std::runtime_error(
"Unable to expand descriptor");
2710 throw std::runtime_error(std::string(__func__) +
": writing cache items failed");
2719 throw std::runtime_error(std::string(__func__) +
": " +
error);
2722 m_map_pubkeys.clear();
2723 m_map_script_pub_keys.clear();
2725 m_wallet_descriptor = descriptor;
2732 error =
"can only update matching descriptor";
2736 if (descriptor.
range_start > m_wallet_descriptor.range_start ||
2737 descriptor.
range_end < m_wallet_descriptor.range_end) {
2739 error =
strprintf(
"new range must include current range = [%d,%d]",
2740 m_wallet_descriptor.range_start,
2741 m_wallet_descriptor.range_end - 1);
int64_t GetTimeFirstKey() const override
bool SignPSBTInput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index, const PrecomputedTransactionData *txdata, int sighash, SignatureData *out_sigdata, bool finalize)
Signs a PSBTInput, verifying that all provided data matches what is being signed. ...
bool AddWatchOnlyInMem(const CScript &dest)
virtual bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
bool ImportPrivKeys(const std::map< CKeyID, CKey > &privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
CSHA256 & Write(const unsigned char *data, size_t len)
void UpdateTimeFirstKey(int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Update wallet first key creation time.
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Adds a key to the store, and saves it to disk.
const std::unordered_set< CScript, SaltedSipHasher > GetScriptPubKeys() const override
Returns a set of all the scriptPubKeys that this ScriptPubKeyMan watches.
unsigned char fingerprint[4]
First 32 bits of the Hash160 of the public key at the root of the path.
bool RemoveWatchOnly(const CScript &dest)
Remove a watch only script from the keystore.
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
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 AddCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
Adds an encrypted key to the store, and saves it to disk.
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.
void UpgradeKeyMetadata()
Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo.
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
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 Upgrade(int prev_version, int new_version, bilingual_str &error) override
Upgrades the wallet to the specified version.
virtual bool IsWalletFlagSet(uint64_t) const =0
virtual WalletDatabase & GetDatabase() const =0
util::Result< CTxDestination > GetNewDestination(const OutputType type) override
isminetype IsMine(const CScript &script) const override
void AddKeypoolPubkeyWithDB(const CPubKey &pubkey, const bool internal, WalletBatch &batch)
iterator insert(iterator pos, const T &value)
bool WriteHDChain(const CHDChain &chain)
write the hdchain model (external chain child index counter)
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet) ...
bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const override
bool Derive(CExtKey &out, unsigned int nChild) const
std::map< int64_t, CKeyID > m_index_to_reserved_key
bool NewKeyPool()
Mark old keypool keys as used, and generate all new keys.
bool CanGenerateKeys() const
void LoadKeyMetadata(const CKeyID &keyID, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
unsigned int GetKeyPoolSize() const override
static bool ExtractPubKey(const CScript &dest, CPubKey &pubKeyOut)
bool IsPayToScriptHash() const
RecursiveMutex cs_KeyStore
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
CPubKey GetPubKey() const
Compute the public key from a private key.
bool TopUpInactiveHDChain(const CKeyID seed_id, int64_t index, bool internal)
Like TopUp() but adds keys for inactive HD chains.
std::map< CKeyID, CKey > keys
bool AddCScript(const CScript &redeemScript) override
std::optional< MigrationData > MigrateToDescriptor()
Get the DescriptorScriptPubKeyMans (with private keys) that have the same scriptPubKeys as this Legac...
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const override
Sign a message with the given script.
bool MessageSign(const CKey &privkey, const std::string &message, std::string &signature)
Sign a message.
virtual bool AddCScript(const CScript &redeemScript)
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< unsigned char > &secret)
uint32_t nExternalChainCounter
bool CanGetAddresses(bool internal=false) const override
struct containing information needed for migrating legacy wallets to descriptor wallets ...
int64_t m_next_internal_index
std::vector< std::pair< std::string, int64_t > > solvable_descs
bool SetupDescriptorGeneration(const CExtKey &master_key, OutputType addr_type, bool internal)
Setup descriptors based on the given CExtkey.
std::map< CKeyID, CKey > KeyMap
void Set(const T pbegin, const T pend)
Initialize a public key using begin/end iterators to byte data.
bool CanUpdateToWalletDescriptor(const WalletDescriptor &descriptor, std::string &error)
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
uint256 GetHash() const
Get the 256-bit hash of this public key.
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
static const unsigned int DEFAULT_KEYPOOL_SIZE
Default for -keypool.
static unsigned const char sighash[]
bool AddWatchOnly(const CScript &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Private version of AddWatchOnly method which does not accept a timestamp, and which will reset the wa...
bool LoadCScript(const CScript &redeemScript)
Adds a CScript to the store.
std::vector< std::pair< std::string, int64_t > > watch_descs
virtual std::set< CKeyID > GetKeys() const
void LoadScriptMetadata(const CScriptID &script_id, const CKeyMetadata &metadata)
std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo > > origins
bool AddKeyPubKeyWithDB(WalletBatch &batch, const CKey &key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Adds a key to the store, and saves it to disk.
bool m_pre_split
Whether this key was generated for a keypool before the wallet was upgraded to HD-split.
void UpdateWalletDescriptor(WalletDescriptor &descriptor)
std::string FormatHDKeypath(const std::vector< uint32_t > &path)
bool ImportScriptPubKeys(const std::set< CScript > &script_pub_keys, const bool have_solving_data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
const std::unordered_set< CScript, SaltedSipHasher > GetScriptPubKeys() const override
Returns a set of all the scriptPubKeys that this ScriptPubKeyMan watches.
CKeyID GetKeyForDestination(const SigningProvider &store, const CTxDestination &dest)
Return the CKeyID of the key involved in a script (if there is a unique one).
void SetHDSeed(const CPubKey &key)
bool DeleteRecords()
Delete all the records ofthis LegacyScriptPubKeyMan from disk.
A version of CTransaction with the PSBT format.
bool IsWitnessProgram(int &version, std::vector< unsigned char > &program) const
virtual void UnsetBlankWalletFlag(WalletBatch &)=0
void WalletLogPrintf(std::string fmt, Params... parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
Access to the wallet database.
bool WritePool(int64_t nPool, const CKeyPool &keypool)
A key from a CWallet's keypool.
bool GetKey(const CKeyID &address, CKey &keyOut) const override
bool AddKey(const CKeyID &key_id, const CKey &key)
bool AddWatchOnlyWithDB(WalletBatch &batch, const CScript &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch) override
IsMineResult
This is an internal representation of isminetype + invalidity.
const unsigned char * begin() const
virtual bool IsLocked() const =0
bool GetKeyFromPool(CPubKey &key, const OutputType type, bool internal=false)
Fetches a key from the keypool.
unsigned int GetKeyPoolSize() const override
bool IsHDEnabled() const override
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
unspendable OP_RETURN script that carries data
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
const std::unordered_set< std::string > LEGACY_TYPES
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses, and other watch only things, and is therefore "blank.".
int64_t nTime
The time at which the key was generated. Set in AddKeypoolPubKeyWithDB.
bool WriteKeyMetadata(const CKeyMetadata &meta, const CPubKey &pubkey, const bool overwrite)
bool CanGetAddresses(bool internal=false) const override
int64_t m_next_external_index
void SetCache(const DescriptorCache &cache)
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that...
bool AddCryptedKey(const CKeyID &key_id, const CPubKey &pubkey, const std::vector< unsigned char > &crypted_key)
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
bool HaveKey(const CKeyID &address) const override
std::string ToString(const T &t)
Locale-independent version of std::to_string.
virtual const CKeyingMaterial & GetEncryptionKey() const =0
size_t KeypoolCountExternalKeys() const
bool CanProvide(const CScript &script, SignatureData &sigdata) override
Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that...
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
std::set< CKeyID > GetKeys() const override
static void DeriveExtKey(CExtKey &key_in, unsigned int index, CExtKey &key_out)
Try to derive an extended key, throw if it fails.
bool HavePrivateKeys() const override
const unsigned char * begin() const
virtual bool CanSupportFeature(enum WalletFeature) const =0
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
const WalletDescriptor GetWalletDescriptor() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
CPubKey vchPubKey
The public key.
bool ReadPool(int64_t nPool, CKeyPool &keypool)
bool fInternal
Whether this keypool entry is in the internal keypool (for change outputs)
void ReturnDestination(int64_t index, bool internal, const CTxDestination &addr) override
std::vector< CKeyID > GetAffectedKeys(const CScript &spk, const SigningProvider &provider)
An input of a transaction.
virtual void SetMinVersion(enum WalletFeature, WalletBatch *=nullptr)=0
void RewriteDB() override
The action to do when the DB needs rewrite.
void LoadHDChain(const CHDChain &chain)
Load a HD chain model (used by LoadWallet)
virtual bool HasEncryptionKeys() const =0
bool Encrypt(const CKeyingMaterial &master_key, WalletBatch *batch) override
std::optional< int64_t > GetOldestKeyPoolTime() const override
bilingual_str _(const char *psz)
Translation function.
void AddHDChain(const CHDChain &chain)
const SigningProvider & DUMMY_SIGNING_PROVIDER
uint256 GetID() const override
std::shared_ptr< Descriptor > descriptor
An encapsulated public key.
isminetype
IsMine() return codes, which depend on ScriptPubKeyMan implementation.
bool LoadKey(const CKey &key, const CPubKey &pubkey)
Adds a key to the store, without saving it to disk (used by LoadWallet)
std::map< CKeyID, CPubKey > pubkeys
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const override
Sign a message with the given script.
bool IsFeatureSupported(int wallet_version, int feature_version)
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
bool EraseRecords(const std::unordered_set< std::string > &types)
Delete records of the given types.
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
Indicate that this wallet supports DescriptorScriptPubKeyMan.
void ImplicitlyLearnRelatedKeyScripts(const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
isminetype IsMine(const CScript &script) const override
void ReturnDestination(int64_t index, bool internal, const CTxDestination &) override
uint32_t nInternalChainCounter
bool AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
util::Result< CTxDestination > GetReservedDestination(const OutputType type, bool internal, int64_t &index, CKeyPool &keypool) override
void UpdatePSBTOutput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index)
Updates a PSBTOutput with information from provider.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
static const std::unordered_set< OutputType > LEGACY_OUTPUT_TYPES
OutputTypes supported by the LegacyScriptPubKeyMan.
std::optional< int64_t > GetOldestKeyPoolTime() const override
std::vector< PSBTInput > inputs
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.
bool ErasePool(int64_t nPool)
uint256 GetID() const override
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 UpgradeDescriptorCache()
Descriptor with some wallet metadata.
bool ImportPubKeys(const std::vector< CKeyID > &ordered_pubkeys, const std::map< CKeyID, CPubKey > &pubkey_map, const std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo >> &key_origins, const bool add_keypool, const bool internal, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool AddCScriptWithDB(WalletBatch &batch, const CScript &script)
Adds a script to the store and saves it to disk.
virtual bool GetKey(const CKeyID &address, CKey &keyOut) const override
const uint32_t BIP32_HARDENED_KEY_LIMIT
Value for the first BIP 32 hardened derivation. Can be used as a bit mask and as a value...
CRIPEMD160 & Write(const unsigned char *data, size_t len)
uint160 Hash160(const T1 &in1)
Compute the 160-bit hash an object.
bool CheckDecryptionKey(const CKeyingMaterial &master_key, bool accept_no_keys=false) override
Check that the given decryption key is valid for this ScriptPubKeyMan, i.e. it decrypts all of the ke...
bool TopUpChain(CHDChain &chain, unsigned int size)
CPubKey DeriveNewSeed(const CKey &key)
void LearnRelatedScripts(const CPubKey &key, OutputType)
Explicitly make the wallet learn the related scripts for outputs to the given key.
bool DecryptKey(const CKeyingMaterial &vMasterKey, const std::vector< unsigned char > &vchCryptedSecret, const CPubKey &vchPubKey, CKey &key)
IsMineSigVersion
This is an enum that tracks the execution context of a script, similar to SigVersion in script/interp...
std::string EncodeExtPubKey(const CExtPubKey &key)
bool IsTestChain() const
If this chain is exclusively used for testing.
void SetSeed(Span< const std::byte > seed)
bool EncryptSecret(const CKeyingMaterial &vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256 &nIV, std::vector< unsigned char > &vchCiphertext)
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible...
An interface to be implemented by keystores that support signing.
util::Result< CTxDestination > GetReservedDestination(const OutputType type, bool internal, int64_t &index, CKeyPool &keypool) override
CExtPubKey Neuter() const
std::unordered_map< CKeyID, CHDChain, SaltedSipHasher > m_inactive_hd_chains
bool ImportScripts(const std::set< CScript > scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
bool ParseHDKeypath(const std::string &keypath_str, std::vector< uint32_t > &keypath)
Parse an HD keypaths like "m/7/0'/2000".
const CChainParams & Params()
Return the currently selected parameters.
Cache for single descriptor's derived extended pubkeys.
std::map< CKeyID, CKey > KeyMap
bool GetDescriptorString(std::string &out, const bool priv) const
Serialized script, used inside transaction inputs and outputs.
CPubKey GenerateNewSeed()
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
std::string WriteHDKeypath(const std::vector< uint32_t > &keypath)
Write HD keypaths as strings.
const unsigned char * end() const
RecursiveMutex cs_desc_man
bool SetupGeneration(bool force=false) override
Sets up the key generation stuff, i.e.
void LearnAllRelatedScripts(const CPubKey &key)
Same as LearnRelatedScripts, but when the OutputType is not known (and could be anything).
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
A reference to a CKey: the Hash160 of its serialized public key.
std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const override
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
std::map< int32_t, FlatSigningProvider > m_map_signing_providers
DescriptorCache MergeAndDiff(const DescriptorCache &other)
Combine another DescriptorCache into this one.
Only for Witness versions not already defined above.
bool m_decryption_thoroughly_checked
keeps track of whether Unlock has run a thorough check before
bool AddKeyPubKeyInner(const CKey &key, const CPubKey &pubkey)
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
virtual bool HaveCScript(const CScriptID &hash) const override
std::vector< unsigned char > valtype
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const
Fetches a pubkey from mapWatchKeys if it exists there.
bool HaveWatchOnly() const
Returns whether there are any watch-only things in the wallet.
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
CTxDestination GetDestinationForKey(const CPubKey &key, OutputType type)
Get a destination of the requested type (if possible) to the specified key.
static const int VERSION_HD_BASE
void AddDescriptorKey(const CKey &key, const CPubKey &pubkey)
void AddInactiveHDChain(const CHDChain &chain)
A reference to a CScript: the Hash160 of its serialization (see script.h)
std::string EncodeDestination(const CTxDestination &dest)
A mutable version of CTransaction.
bool IsHDEnabled() const override
CPubKey GenerateNewKey(WalletBatch &batch, CHDChain &hd_chain, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Generate a new key.
virtual bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey)
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed.
static int64_t GetOldestKeyTimeInPool(const std::set< int64_t > &setKeyPool, WalletBatch &batch)
bool fDecryptionThoroughlyChecked
keeps track of whether Unlock has run a thorough check before
bool AddDescriptorKeyWithDB(WalletBatch &batch, const CKey &key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
KeyMap GetKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_desc_man)
void KeepDestination(int64_t index, const OutputType &type) override
std::unique_ptr< CKeyMetadata > GetMetadata(const CTxDestination &dest) const override
bool TopUp(unsigned int size=0) override
Fills internal address pool.
std::vector< CKeyPool > MarkReserveKeysAsUsed(int64_t keypool_id) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
Marks all keys in the keypool up to and including the provided key as used.
TransactionError FillPSBT(PartiallySignedTransaction &psbt, const PrecomputedTransactionData &txdata, int sighash_type=SIGHASH_DEFAULT, 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.
An encapsulated private key.
std::map< CKeyID, int64_t > m_pool_key_to_index
bool HavePrivateKeys() const override
bool ReserveKeyFromKeyPool(int64_t &nIndex, CKeyPool &keypool, bool fRequestedInternal)
Reserves a key from the keypool and sets nIndex to its index.
TransactionError FillPSBT(PartiallySignedTransaction &psbt, const PrecomputedTransactionData &txdata, int sighash_type=SIGHASH_DEFAULT, 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< CMutableTransaction > tx
std::vector< unsigned char > valtype
bool CheckDecryptionKey(const CKeyingMaterial &master_key, bool accept_no_keys=false) override
Check that the given decryption key is valid for this ScriptPubKeyMan, i.e. it decrypts all of the ke...
void Finalize(unsigned char hash[OUTPUT_SIZE])
void DeriveNewChildKey(WalletBatch &batch, CKeyMetadata &metadata, CKey &secret, CHDChain &hd_chain, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
A hasher class for SHA-256.
int32_t m_max_cached_index
int64_t GetTime()
DEPRECATED, see GetTime.
std::vector< uint32_t > path
const unsigned char * end() const
CKeyID seed_id
seed hash160
bool error(const char *fmt, const Args &... args)
bool HasWalletDescriptor(const WalletDescriptor &desc) const
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
int64_t GetTimeFirstKey() const override
bool TopUp(unsigned int size=0) override
Fills internal address pool.
void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
Load a keypool entry.
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
void MarkPreSplitKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore)
std::vector< std::unique_ptr< DescriptorScriptPubKeyMan > > desc_spkms
util::Result< CTxDestination > GetNewDestination(const OutputType type) override
bool SignTransaction(CMutableTransaction &tx, const std::map< COutPoint, Coin > &coins, int sighash, std::map< int, bilingual_str > &input_errors) const override
Creates new signatures and adds them to the transaction.
std::map< CKeyID, SigPair > signatures
BIP 174 style partial signatures for the input. May contain all signatures necessary for producing a ...
A hasher class for RIPEMD-160.
CKeyID ToKeyID(const PKHash &key_hash)
std::unique_ptr< FlatSigningProvider > GetSigningProvider(const CScript &script, bool include_private=false) const
WalletStorage & m_storage
bool AddKeyOriginWithDB(WalletBatch &batch, const CPubKey &pubkey, const KeyOriginInfo &info)
Add a KeyOriginInfo to the wallet.
bool IsCompressed() const
Check whether this is a compressed public key.
virtual bool HaveKey(const CKeyID &address) const override
static const int VERSION_HD_CHAIN_SPLIT