9#include <chainparams.h>
35const std::string
FLAGS{
"flags"};
38const std::string
KEY{
"key"};
41const std::string
NAME{
"name"};
44const std::string
POOL{
"pool"};
47const std::string
TX{
"tx"};
62 const std::string &strName) {
83 const std::string &strPurpose) {
110 const bool overwrite) {
121 std::vector<uint8_t> vchKey;
122 vchKey.reserve(vchPubKey.
size() + vchPrivKey.size());
123 vchKey.insert(vchKey.end(), vchPubKey.
begin(), vchPubKey.
end());
124 vchKey.insert(vchKey.end(), vchPrivKey.begin(), vchPrivKey.end());
127 std::make_pair(vchPrivKey,
Hash(vchKey)),
false);
131 const std::vector<uint8_t> &vchCryptedSecret,
141 if (!
WriteIC(key, std::make_pair(vchCryptedSecret, checksum),
false)) {
143 std::vector<uint8_t> val;
144 if (!
m_batch->Read(key, val)) {
147 if (!
WriteIC(key, std::make_pair(val, checksum),
true)) {
218 return WriteIC(make_pair(key, type),
id);
224 return EraseIC(make_pair(key, type));
231 std::vector<uint8_t> key;
232 key.reserve(pubkey.
size() + privkey.size());
233 key.insert(key.end(), pubkey.
begin(), pubkey.
end());
234 key.insert(key.end(), privkey.begin(), privkey.end());
237 std::make_pair(desc_id, pubkey)),
238 std::make_pair(privkey,
Hash(key)),
false);
243 const std::vector<uint8_t> &secret) {
245 std::make_pair(desc_id, pubkey)),
250 std::make_pair(desc_id, pubkey)));
261 uint32_t key_exp_index,
262 uint32_t der_index) {
264 xpub.
Encode(ser_xpub.data());
267 std::make_pair(key_exp_index, der_index)),
273 uint32_t key_exp_index) {
275 xpub.
Encode(ser_xpub.data());
296 std::map<std::pair<uint256, CKeyID>,
297 std::pair<CPubKey, std::vector<uint8_t>>>
306 std::string &strType, std::string &strErr,
315 if (filter_fn && !filter_fn(strType)) {
319 std::string strAddress;
328 std::string strAddress;
339 auto fill_wtx = [&](
CWalletTx &wtx,
bool new_tx) {
342 if (wtx.GetId() != txid) {
347 if (31404 <= wtx.fTimeReceivedIsTxTime &&
348 wtx.fTimeReceivedIsTxTime <= 31703) {
349 if (!ssValue.
empty()) {
352 std::string unused_string;
353 ssValue >> fTmp >> fUnused >> unused_string;
355 "LoadWallet() upgrading tx ver=%d %d %s",
356 wtx.fTimeReceivedIsTxTime, fTmp, txid.
ToString());
357 wtx.fTimeReceivedIsTxTime = fTmp;
360 "LoadWallet() repairing tx ver=%d %s",
361 wtx.fTimeReceivedIsTxTime, txid.
ToString());
362 wtx.fTimeReceivedIsTxTime = 0;
367 if (wtx.nOrderPos == -1) {
390 strErr =
"Error reading wallet database: CPubKey corrupt";
411 bool fSkipCheck =
false;
415 std::vector<uint8_t> vchKey;
416 vchKey.reserve(vchPubKey.
size() + pkey.size());
417 vchKey.insert(vchKey.end(), vchPubKey.
begin(), vchPubKey.
end());
418 vchKey.insert(vchKey.end(), pkey.begin(), pkey.end());
420 if (
Hash(vchKey) != hash) {
421 strErr =
"Error reading wallet database: CPubKey/CPrivKey "
429 if (!key.
Load(pkey, vchPubKey, fSkipCheck)) {
430 strErr =
"Error reading wallet database: CPrivKey corrupt";
435 strErr =
"Error reading wallet database: "
436 "LegacyScriptPubKeyMan::LoadKey failed";
445 ssValue >> kMasterKey;
448 "Error reading wallet database: duplicate CMasterKey id %u",
460 strErr =
"Error reading wallet database: CPubKey corrupt";
463 std::vector<uint8_t> vchPrivKey;
464 ssValue >> vchPrivKey;
467 bool checksum_valid =
false;
468 if (!ssValue.
eof()) {
471 if ((checksum_valid =
Hash(vchPrivKey) != checksum)) {
473 "Error reading wallet database: Crypted key corrupt";
481 vchPubKey, vchPrivKey, checksum_valid)) {
482 strErr =
"Error reading wallet database: "
483 "LegacyScriptPubKeyMan::LoadCryptedKey failed";
494 vchPubKey.
GetID(), keyMeta);
503 bool internal =
false;
506 std::vector<uint32_t> path;
513 strErr =
"Error reading wallet database: keymeta "
514 "with invalid HD keypath";
524 if (path.size() != 3) {
525 strErr =
"Error reading wallet database: keymeta found "
526 "with unexpected path";
529 if (path[0] != 0x80000000) {
531 "Unexpected path index of 0x%08x (expected "
532 "0x80000000) for the element at index 0",
536 if (path[1] != 0x80000000 && path[1] != (1 | 0x80000000)) {
538 strprintf(
"Unexpected path index of 0x%08x "
539 "(expected 0x80000000 or 0x80000001) for "
540 "the element at index 1",
544 if ((path[2] & 0x80000000) == 0) {
546 "Unexpected path index of 0x%08x (expected to be "
547 "greater than or equal to 0x80000000)",
551 internal = path[1] == (1 | 0x80000000);
552 index = path[2] & ~0x80000000;
558 CHDChain &chain = ins.first->second;
587 ssValue >> vchPubKey;
589 strErr =
"Error reading wallet database: Default Key corrupt";
607 strErr =
"Error reading wallet database: "
608 "LegacyScriptPubKeyMan::LoadCScript failed";
612 ssValue >> pwallet->nOrderPosNext;
614 std::string strAddress, strKey, strValue;
629 strErr =
"Error reading wallet database: Unknown non-tolerable "
630 "wallet flags found";
634 strErr =
"Found unsupported 'wkey' record, try loading with "
647 if (spk_mans.count(
static_cast<OutputType>(type)) > 0) {
649 "Multiple ScriptPubKeyMans specified for a single type";
665 uint32_t key_exp_index;
668 ssKey >> key_exp_index;
680 xpub.
Decode(ser_xpub.data());
683 key_exp_index, xpub);
686 key_exp_index, der_index, xpub);
694 strErr =
"Error reading wallet database: CPubKey corrupt";
706 std::vector<uint8_t> to_hash;
707 to_hash.reserve(pubkey.
size() + pkey.size());
708 to_hash.insert(to_hash.end(), pubkey.
begin(), pubkey.
end());
709 to_hash.insert(to_hash.end(), pkey.begin(), pkey.end());
711 if (
Hash(to_hash) != hash) {
713 "Error reading wallet database: CPubKey/CPrivKey corrupt";
717 if (!key.
Load(pkey, pubkey,
true)) {
718 strErr =
"Error reading wallet database: CPrivKey corrupt";
722 std::make_pair(std::make_pair(desc_id, pubkey.
GetID()), key));
729 strErr =
"Error reading wallet database: CPubKey corrupt";
732 std::vector<uint8_t> privkey;
737 std::make_pair(std::make_pair(desc_id, pubkey.
GetID()),
738 std::make_pair(pubkey, privkey)));
747 }
catch (
const std::exception &e) {
748 if (strErr.empty()) {
753 if (strErr.empty()) {
754 strErr =
"Caught unknown exception in ReadKeyValue";
762 std::string &strType, std::string &strErr,
766 return ReadKeyValue(pwallet, ssKey, ssValue, dummy_wss, strType, strErr,
777 bool fNoncriticalErrors =
false;
801 bool ret =
m_batch->ReadAtCursor(ssKey, ssValue, complete);
808 "Error reading next record from wallet database\n");
813 std::string strType, strErr;
814 if (!
ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr)) {
827 fNoncriticalErrors =
true;
834 if (!strErr.empty()) {
846 spk_man_pair.second, spk_man_pair.first,
false);
850 spk_man_pair.second, spk_man_pair.first,
true);
858 ->SetCache(desc_cache_pair.second);
865 ->AddKey(desc_key_pair.first.second, desc_key_pair.second);
870 ->AddCryptedKey(desc_key_pair.first.second,
871 desc_key_pair.second.first,
872 desc_key_pair.second.second);
889 "Wallet file version = %d, last client version = %d\n",
893 "metadata, %u total. Unknown wallet records: %u\n",
902 LOCK(spk_man->cs_KeyStore);
903 spk_man->UpdateTimeFirstKey(1);
908 WriteTx(pwallet->mapWallet.at(txid));
912 if (wss.
fIsEncrypted && (last_client == 40000 || last_client == 50000)) {
940 "Inactive HD Chains found but no Legacy ScriptPubKeyMan\n");
944 if (chain_pair.first !=
956 std::list<CWalletTx> &vWtx) {
969 LogPrintf(
"Error getting wallet database cursor\n");
978 bool ret =
m_batch->ReadAtCursor(ssKey, ssValue, complete);
985 LogPrintf(
"Error reading next record from wallet database\n");
994 txIds.push_back(txid);
995 vWtx.emplace_back(
nullptr );
996 ssValue >> vWtx.back();
1008 std::vector<TxId> &txIdsOut) {
1010 std::vector<TxId> txIds;
1011 std::list<CWalletTx> vWtx;
1017 std::sort(txIds.begin(), txIds.end());
1018 std::sort(txIdsIn.begin(), txIdsIn.end());
1021 bool delerror =
false;
1022 std::vector<TxId>::iterator it = txIdsIn.begin();
1023 for (
const TxId &txid : txIds) {
1024 while (it < txIdsIn.end() && (*it) < txid) {
1027 if (it == txIdsIn.end()) {
1031 if ((*it) == txid) {
1034 "Transaction was found for deletion but returned "
1035 "database error: %s\n",
1039 txIdsOut.push_back(txid);
1050 static std::atomic<bool> fOneThread(
false);
1051 if (fOneThread.exchange(
true)) {
1055 for (
const std::shared_ptr<CWallet> &pwallet :
GetWallets(context)) {
1077 const std::string &key,
1078 const std::string &value) {
1090 const std::string &key) {
1094 return EraseIC(std::make_pair(
1125 exists = fs::symlink_status(path).type() != fs::file_type::not_found;
1126 }
catch (
const fs::filesystem_error &e) {
1134 std::optional<DatabaseFormat>
format;
1141 strprintf(
"Failed to load database path '%s'. Path does not exist.",
1149 "Data is not in recognized format.",
1157 "Failed to create database path '%s'. Database already exists.",
1170 return std::make_unique<DummyDatabase>();
1175 return std::make_unique<BerkeleyDatabase>(
1176 std::make_shared<BerkeleyEnvironment>(),
"");
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
bool ExistsBerkeleyDatabase(const fs::path &path)
Check if Berkeley database exists at specified path.
std::unique_ptr< BerkeleyDatabase > MakeBerkeleyDatabase(const fs::path &path, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
Return object giving access to Berkeley database at specified path.
bool ParseHDKeypath(const std::string &keypath_str, std::vector< uint32_t > &keypath)
Parse an HD keypaths like "m/7/0'/2000".
const CScript redeemScript
const CChainParams & Params()
Return the currently selected parameters.
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
static const int VERSION_HD_BASE
uint32_t nInternalChainCounter
CKeyID seed_id
seed hash160
static const int VERSION_HD_CHAIN_SPLIT
uint32_t nExternalChainCounter
An encapsulated secp256k1 private key.
bool Load(const CPrivKey &privkey, const CPubKey &vchPubKey, bool fSkipCheck)
Load private key and check that public key matches.
A key from a CWallet's keypool.
Private key encryption is done based on a CMasterKey, which holds a salt and random encryption key.
An encapsulated public key.
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
const uint8_t * end() const
unsigned int size() const
Simple read-only vector-like interface to the pubkey data.
const uint8_t * begin() const
A reference to a CScript: the Hash160 of its serialization.
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
MasterKeyMap mapMasterKeys
void WalletLogPrintf(std::string fmt, Params... parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
LegacyScriptPubKeyMan * GetOrCreateLegacyScriptPubKeyMan()
bool IsLegacy() const
Determine if we are a legacy wallet.
void LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
Loads an active ScriptPubKeyMan for the specified type and internal.
void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor &desc)
Instantiate a descriptor ScriptPubKeyMan from the WalletDescriptor and load it.
LegacyScriptPubKeyMan * GetLegacyScriptPubKeyMan() const
Get the LegacyScriptPubKeyMan which is used for all types, internal, and external.
bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
int GetVersion() const
get the current wallet format (the oldest client version guaranteed to understand this wallet)
ScriptPubKeyMan * GetScriptPubKeyMan(const OutputType &type, bool internal) const
Get the ScriptPubKeyMan for the given OutputType and internal/external chain.
void LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Adds a destination data tuple to the store, without saving it to disk.
unsigned int nMasterKeyMaxID
unsigned int m_unknown_records
std::map< uint160, CHDChain > m_hd_chains
std::map< uint256, DescriptorCache > m_descriptor_caches
std::vector< TxId > vWalletUpgrade
CWalletScanState()=default
std::map< OutputType, uint256 > m_active_internal_spks
std::map< std::pair< uint256, CKeyID >, std::pair< CPubKey, std::vector< uint8_t > > > m_descriptor_crypt_keys
std::map< OutputType, uint256 > m_active_external_spks
std::map< std::pair< uint256, CKeyID >, CKey > m_descriptor_keys
A transaction with a bunch of additional info that only the owner cares about.
Double ended buffer combining vector and stream-like interfaces.
Cache for single descriptor's derived extended pubkeys.
const CHDChain & GetHDChain() const
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector< uint8_t > &vchCryptedSecret, bool checksum_valid)
Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
Load a keypool entry.
bool LoadKey(const CKey &key, const CPubKey &pubkey)
Adds a key to the store, without saving it to disk (used by LoadWallet)
void LoadKeyMetadata(const CKeyID &keyID, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
void LoadHDChain(const CHDChain &chain)
Load a HD chain model (used by LoadWallet)
void AddInactiveHDChain(const CHDChain &chain)
void LoadScriptMetadata(const CScriptID &script_id, const CKeyMetadata &metadata)
bool LoadCScript(const CScript &redeemScript)
Adds a CScript to the store.
bool TxnCommit()
Commit current transaction.
bool WriteDescriptor(const uint256 &desc_id, const WalletDescriptor &descriptor)
bool WriteActiveScriptPubKeyMan(uint8_t type, const uint256 &id, bool internal)
bool WriteDescriptorDerivedCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index, uint32_t der_index)
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
bool WriteName(const CTxDestination &address, const std::string &strName)
bool ErasePool(int64_t nPool)
bool WritePurpose(const CTxDestination &address, const std::string &purpose)
bool WriteMinVersion(int nVersion)
bool WriteDescriptorParentCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index)
static bool IsKeyType(const std::string &strType)
bool ErasePurpose(const CTxDestination &address)
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
bool EraseWatchOnly(const CScript &script)
bool EraseDestData(const CTxDestination &address, const std::string &key)
Erase destination data tuple from wallet database.
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
bool ReadPool(int64_t nPool, CKeyPool &keypool)
bool WriteWalletFlags(const uint64_t flags)
bool WriteIC(const K &key, const T &value, bool fOverwrite=true)
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
std::unique_ptr< DatabaseBatch > m_batch
bool WriteHDChain(const CHDChain &chain)
write the hdchain model (external chain child index counter)
bool ReadBestBlock(CBlockLocator &locator)
DBErrors FindWalletTx(std::vector< TxId > &txIds, std::list< CWalletTx > &vWtx)
bool WriteKeyMetadata(const CKeyMetadata &meta, const CPubKey &pubkey, const bool overwrite)
bool WriteOrderPosNext(int64_t nOrderPosNext)
bool EraseActiveScriptPubKeyMan(uint8_t type, bool internal)
bool WriteTx(const CWalletTx &wtx)
bool EraseIC(const K &key)
bool TxnBegin()
Begin a new transaction.
bool TxnAbort()
Abort current transaction.
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
bool EraseName(const CTxDestination &address)
bool WritePool(int64_t nPool, const CKeyPool &keypool)
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< uint8_t > &vchCryptedSecret, const CKeyMetadata &keyMeta)
bool WriteBestBlock(const CBlockLocator &locator)
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< uint8_t > &secret)
bool EraseTx(uint256 hash)
DBErrors ZapSelectTx(std::vector< TxId > &txIdsIn, std::vector< TxId > &txIdsOut)
DBErrors LoadWallet(CWallet *pwallet)
bool WriteDestData(const CTxDestination &address, const std::string &key, const std::string &value)
Write destination data key,value tuple to database.
An instance of this class represents one database.
unsigned int nLastFlushed
std::atomic< unsigned int > nUpdateCounter
int64_t nLastWalletUpdate
virtual bool PeriodicFlush()=0
Descriptor with some wallet metadata.
constexpr bool IsNull() const
std::string ToString() const
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
bool LoadToWallet(const TxId &txid, const UpdateWalletTxFn &fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo.
bool LoadWalletFlags(uint64_t flags)
Loads the flags into the wallet.
const CChainParams & GetChainParams() const override
DBErrors ReorderTransactions()
uint256 Hash(const T &in1)
Compute the 256-bit hash of an object.
std::vector< uint8_t, secure_allocator< uint8_t > > CPrivKey
secure_allocator is defined in allocators.h CPrivKey is a serialized private key, with all parameters...
CTxDestination DecodeDestination(const std::string &addr, const CChainParams ¶ms)
std::string EncodeLegacyAddr(const CTxDestination &dest, const CChainParams ¶ms)
#define LogDebug(category,...)
const std::string ORDERPOSNEXT
const std::string DEFAULTKEY
const std::string CSCRIPT
const std::string BESTBLOCK_NOMERKLE
const std::string DESTDATA
const std::string WALLETDESCRIPTORKEY
const std::string SETTINGS
const std::string WALLETDESCRIPTORCKEY
const std::string ACTIVEEXTERNALSPK
const std::string MINVERSION
const std::string HDCHAIN
const std::string WALLETDESCRIPTORCACHE
const std::string WALLETDESCRIPTOR
const std::string VERSION
const std::string KEYMETA
const std::string WATCHMETA
const std::string ACENTRY
const std::string MASTER_KEY
const std::string ACTIVEINTERNALSPK
const std::string PURPOSE
const std::string OLD_KEY
const std::string CRYPTED_KEY
const std::string BESTBLOCK
static bool exists(const path &p)
static std::string PathToString(const path &path)
Convert path object to byte string.
const unsigned int BIP32_EXTKEY_SIZE
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
std::vector< BlockHash > vHave
void Encode(uint8_t code[BIP32_EXTKEY_SIZE]) const
void Decode(const uint8_t code[BIP32_EXTKEY_SIZE])
std::vector< uint32_t > path
A TxId is the identifier of a transaction.
WalletContext struct containing references to state shared between CWallet instances,...
#define EXCLUSIVE_LOCKS_REQUIRED(...)
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
std::vector< std::shared_ptr< CWallet > > GetWallets(WalletContext &context)
std::unique_ptr< WalletDatabase > MakeDatabase(const fs::path &path, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
static bool ReadKeyValue(CWallet *pwallet, DataStream &ssKey, DataStream &ssValue, CWalletScanState &wss, std::string &strType, std::string &strErr, const KeyFilterFn &filter_fn=nullptr) EXCLUSIVE_LOCKS_REQUIRED(pwallet -> cs_wallet)
std::unique_ptr< WalletDatabase > CreateDummyWalletDatabase()
Return object for accessing dummy database with no read/write capabilities.
void MaybeCompactWalletDB(WalletContext &context)
Compacts BDB state so that wallet.dat is self-contained (if there are changes)
std::unique_ptr< WalletDatabase > CreateMockWalletDatabase()
Return object for accessing temporary in-memory database.
DBErrors
Error statuses for the wallet database.
std::function< bool(const std::string &)> KeyFilterFn
Callback for filtering key types to deserialize in ReadKeyValue.