39const std::string
FLAGS{
"flags"};
42const std::string
KEY{
"key"};
46const std::string
NAME{
"name"};
49const std::string
POOL{
"pool"};
52const std::string
TX{
"tx"};
111 std::vector<unsigned char> vchKey;
112 vchKey.reserve(vchPubKey.
size() + vchPrivKey.size());
113 vchKey.insert(vchKey.end(), vchPubKey.
begin(), vchPubKey.
end());
114 vchKey.insert(vchKey.end(), vchPrivKey.begin(), vchPrivKey.end());
120 const std::vector<unsigned char>& vchCryptedSecret,
131 if (!
WriteIC(key, std::make_pair(vchCryptedSecret, checksum),
false)) {
133 std::vector<unsigned char> val;
134 if (!
m_batch->Read(key, val)) {
137 if (!
WriteIC(key, std::make_pair(val, checksum),
true)) {
211 return WriteIC(make_pair(key, type),
id);
217 return EraseIC(make_pair(key, type));
223 std::vector<unsigned char> key;
224 key.reserve(pubkey.
size() + privkey.size());
225 key.insert(key.end(), pubkey.
begin(), pubkey.
end());
226 key.insert(key.end(), privkey.begin(), privkey.end());
248 xpub.
Encode(ser_xpub.data());
255 xpub.
Encode(ser_xpub.data());
262 xpub.
Encode(ser_xpub.data());
274 for (
const auto& derived_xpub_pair : derived_xpub_map_pair.second) {
330 if (filter_fn && !filter_fn(strType)) {
334 std::string strAddress;
340 std::string strAddress;
348 auto fill_wtx = [&](
CWalletTx& wtx,
bool new_tx) {
357 if (wtx.GetHash() != hash)
361 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
363 if (!ssValue.
empty())
367 std::string unused_string;
368 ssValue >> fTmp >> fUnused >> unused_string;
369 strErr =
strprintf(
"LoadWallet() upgrading tx ver=%d %d %s",
370 wtx.fTimeReceivedIsTxTime, fTmp, hash.
ToString());
371 wtx.fTimeReceivedIsTxTime = fTmp;
375 strErr =
strprintf(
"LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.
ToString());
376 wtx.fTimeReceivedIsTxTime = 0;
381 if (wtx.nOrderPos == -1)
403 strErr =
"Error reading wallet database: CPubKey corrupt";
422 catch (
const std::ios_base::failure&) {}
424 bool fSkipCheck =
false;
429 std::vector<unsigned char> vchKey;
430 vchKey.reserve(vchPubKey.
size() + pkey.size());
431 vchKey.insert(vchKey.end(), vchPubKey.
begin(), vchPubKey.
end());
432 vchKey.insert(vchKey.end(), pkey.begin(), pkey.end());
434 if (
Hash(vchKey) != hash)
436 strErr =
"Error reading wallet database: CPubKey/CPrivKey corrupt";
443 if (!key.
Load(pkey, vchPubKey, fSkipCheck))
445 strErr =
"Error reading wallet database: CPrivKey corrupt";
450 strErr =
"Error reading wallet database: LegacyScriptPubKeyMan::LoadKey failed";
458 ssValue >> kMasterKey;
461 strErr =
strprintf(
"Error reading wallet database: duplicate CMasterKey id %u", nID);
472 strErr =
"Error reading wallet database: CPubKey corrupt";
475 std::vector<unsigned char> vchPrivKey;
476 ssValue >> vchPrivKey;
479 bool checksum_valid =
false;
480 if (!ssValue.
eof()) {
483 if ((checksum_valid =
Hash(vchPrivKey) != checksum)) {
484 strErr =
"Error reading wallet database: Encrypted key corrupt";
493 strErr =
"Error reading wallet database: LegacyScriptPubKeyMan::LoadCryptedKey failed";
510 bool internal =
false;
513 std::vector<uint32_t> path;
520 strErr =
"Error reading wallet database: keymeta with invalid HD keypath";
529 if (path.size() != 3) {
530 strErr =
"Error reading wallet database: keymeta found with unexpected path";
533 if (path[0] != 0x80000000) {
534 strErr =
strprintf(
"Unexpected path index of 0x%08x (expected 0x80000000) for the element at index 0", path[0]);
537 if (path[1] != 0x80000000 && path[1] != (1 | 0x80000000)) {
538 strErr =
strprintf(
"Unexpected path index of 0x%08x (expected 0x80000000 or 0x80000001) for the element at index 1", path[1]);
541 if ((path[2] & 0x80000000) == 0) {
542 strErr =
strprintf(
"Unexpected path index of 0x%08x (expected to be greater than or equal to 0x80000000)", path[2]);
545 internal = path[1] == (1 | 0x80000000);
546 index = path[2] & ~0x80000000;
551 CHDChain& chain = ins.first->second;
575 ssValue >> vchPubKey;
577 strErr =
"Error reading wallet database: Default Key corrupt";
594 strErr =
"Error reading wallet database: LegacyScriptPubKeyMan::LoadCScript failed";
598 ssValue >> pwallet->nOrderPosNext;
600 std::string strAddress, strKey, strValue;
610 strErr =
"Found unsupported 'wkey' record, try loading with version 0.18";
620 if (spk_mans.count(
static_cast<OutputType>(type)) > 0) {
621 strErr =
"Multiple ScriptPubKeyMans specified for a single type";
637 uint32_t key_exp_index;
640 ssKey >> key_exp_index;
653 xpub.
Decode(ser_xpub.data());
661 uint32_t key_exp_index;
663 ssKey >> key_exp_index;
668 xpub.
Decode(ser_xpub.data());
677 strErr =
"Error reading wallet database: CPubKey corrupt";
689 std::vector<unsigned char> to_hash;
690 to_hash.reserve(pubkey.
size() + pkey.size());
691 to_hash.insert(to_hash.end(), pubkey.
begin(), pubkey.
end());
692 to_hash.insert(to_hash.end(), pkey.begin(), pkey.end());
694 if (
Hash(to_hash) != hash)
696 strErr =
"Error reading wallet database: CPubKey/CPrivKey corrupt";
700 if (!key.
Load(pkey, pubkey,
true))
702 strErr =
"Error reading wallet database: CPrivKey corrupt";
713 strErr =
"Error reading wallet database: CPubKey corrupt";
716 std::vector<unsigned char> privkey;
734 }
catch (
const std::exception& e) {
735 if (strErr.empty()) {
740 if (strErr.empty()) {
741 strErr =
"Caught unknown exception in ReadKeyValue";
752 return ReadKeyValue(pwallet, ssKey, ssValue, dummy_wss, strType, strErr, filter_fn);
764 bool fNoncriticalErrors =
false;
765 bool rescan_required =
false;
782 pwallet->
WalletLogPrintf(
"Error reading wallet database: Unknown non-tolerable wallet flags found\n");
787#ifndef ENABLE_EXTERNAL_SIGNER
789 pwallet->
WalletLogPrintf(
"Error: External signer wallet being loaded without external signer support compiled\n");
807 bool ret =
m_batch->ReadAtCursor(ssKey, ssValue, complete);
814 pwallet->
WalletLogPrintf(
"Error reading next record from wallet database\n");
819 std::string strType, strErr;
820 if (!
ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr))
830 pwallet->
WalletLogPrintf(
"Error: Corrupt transaction found. This can be fixed by removing transactions from wallet and rescanning.\n");
836 fNoncriticalErrors =
true;
839 rescan_required =
true;
872 ((
DescriptorScriptPubKeyMan*)spk_man)->AddCryptedKey(desc_key_pair.first.second, desc_key_pair.second.first, desc_key_pair.second.second);
891 pwallet->
WalletLogPrintf(
"Wallet File Version = %d\n", wallet_version > 0 ? wallet_version : last_client);
893 pwallet->
WalletLogPrintf(
"Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total. Unknown wallet records: %u\n",
900 LOCK(spk_man->cs_KeyStore);
901 spk_man->UpdateTimeFirstKey(1);
906 WriteTx(pwallet->mapWallet.at(hash));
909 if (wss.
fIsEncrypted && (last_client == 40000 || last_client == 50000))
938 pwallet->
WalletLogPrintf(
"Inactive HD Chains found but no Legacy ScriptPubKeyMan\n");
965 LogPrintf(
"Error getting wallet database cursor\n");
975 bool ret =
m_batch->ReadAtCursor(ssKey, ssValue, complete);
980 LogPrintf(
"Error reading next record from wallet database\n");
989 vTxHash.push_back(hash);
990 vWtx.emplace_back(
nullptr );
991 ssValue >> vWtx.back();
1005 std::vector<uint256> vTxHash;
1006 std::list<CWalletTx> vWtx;
1012 std::sort(vTxHash.begin(), vTxHash.end());
1013 std::sort(vTxHashIn.begin(), vTxHashIn.end());
1016 bool delerror =
false;
1017 std::vector<uint256>::iterator it = vTxHashIn.begin();
1018 for (
const uint256& hash : vTxHash) {
1019 while (it < vTxHashIn.end() && (*it) < hash) {
1022 if (it == vTxHashIn.end()) {
1025 else if ((*it) == hash) {
1027 LogPrint(
BCLog::WALLETDB,
"Transaction was found for deletion but returned database error: %s\n", hash.GetHex());
1030 vTxHashOut.push_back(hash);
1042 static std::atomic<bool> fOneThread(
false);
1043 if (fOneThread.exchange(
true)) {
1047 for (
const std::shared_ptr<CWallet>& pwallet :
GetWallets(context)) {
1107 exists = fs::symlink_status(path).type() != fs::file_not_found;
1108 }
catch (
const fs::filesystem_error& e) {
1114 std::optional<DatabaseFormat>
format;
1185 return std::make_unique<DummyDatabase>();
1192 return std::make_unique<SQLiteDatabase>(
"",
"",
true);
1194 return std::make_unique<BerkeleyDatabase>(std::make_shared<BerkeleyEnvironment>(),
"");
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".
Double ended buffer combining vector and stream-like interfaces.
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 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 outpoint - a combination of a transaction hash and an index n into its vout.
An encapsulated public key.
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
const unsigned char * end() const
unsigned int size() const
Simple read-only vector-like interface to the pubkey data.
const unsigned char * begin() const
Serialized script, used inside transaction inputs and outputs.
A reference to a CScript: the Hash160 of its serialization (see script.h)
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
MasterKeyMap mapMasterKeys
RecursiveMutex cs_wallet
Main wallet lock.
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::vector< uint256 > vWalletUpgrade
std::map< uint256, DescriptorCache > m_descriptor_caches
std::map< std::pair< uint256, CKeyID >, std::pair< CPubKey, std::vector< unsigned char > > > m_descriptor_crypt_keys
std::map< OutputType, uint256 > m_active_internal_spks
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.
const uint256 & GetHash() const
Cache for single descriptor's derived extended pubkeys.
const ExtPubKeyMap GetCachedLastHardenedExtPubKeys() const
Retrieve all cached last hardened xpubs.
const ExtPubKeyMap GetCachedParentExtPubKeys() const
Retrieve all cached parent xpubs.
const std::unordered_map< uint32_t, ExtPubKeyMap > GetCachedDerivedExtPubKeys() const
Retrieve all cached derived xpubs.
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)
void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
Load a keypool entry.
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)
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 ErasePool(int64_t nPool)
bool WriteName(const std::string &strAddress, const std::string &strName)
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 std::string &strAddress)
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
bool EraseLockedUTXO(const COutPoint &output)
bool EraseWatchOnly(const CScript &script)
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, const CKeyMetadata &keyMeta)
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)
bool EraseDestData(const std::string &address, const std::string &key)
Erase destination data tuple from wallet database.
std::unique_ptr< DatabaseBatch > m_batch
bool WriteHDChain(const CHDChain &chain)
write the hdchain model (external chain child index counter)
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< unsigned char > &secret)
bool ReadBestBlock(CBlockLocator &locator)
bool WriteDescriptorCacheItems(const uint256 &desc_id, const DescriptorCache &cache)
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.
DBErrors FindWalletTx(std::vector< uint256 > &vTxHash, std::list< CWalletTx > &vWtx)
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
bool WritePool(int64_t nPool, const CKeyPool &keypool)
bool WriteBestBlock(const CBlockLocator &locator)
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut)
bool EraseTx(uint256 hash)
bool WritePurpose(const std::string &strAddress, const std::string &purpose)
bool WriteDestData(const std::string &address, const std::string &key, const std::string &value)
Write destination data key,value tuple to database.
bool EraseName(const std::string &strAddress)
DBErrors LoadWallet(CWallet *pwallet)
bool WriteLockedUTXO(const COutPoint &output)
bool WriteDescriptorLastHardenedCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index)
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.
std::string ToString() const
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
fs::path SQLiteDataFile(const fs::path &path)
fs::path BDBDataFile(const fs::path &wallet_path)
bool IsBDBFile(const fs::path &path)
bool IsSQLiteFile(const fs::path &path)
bool LockCoin(const COutPoint &output, WalletBatch *batch=nullptr) 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.
void UpgradeDescriptorCache() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Upgrade DescriptorCaches.
bool LoadToWallet(const uint256 &hash, const UpdateWalletTxFn &fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
bool IsWalletFlagSet(uint64_t flag) const override
check if a certain wallet flag is set
DBErrors ReorderTransactions()
uint256 Hash(const T &in1)
Compute the 256-bit hash of an object.
std::vector< unsigned char, secure_allocator< unsigned char > > CPrivKey
CPrivKey is a serialized private key, with all parameters included (SIZE bytes)
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg)
#define LogPrint(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 WALLETDESCRIPTORLHCACHE
const std::string KEYMETA
const std::string LOCKED_UTXO
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.
std::string get_filesystem_error_message(const fs::filesystem_error &e)
const unsigned int BIP32_EXTKEY_SIZE
std::unique_ptr< SQLiteDatabase > MakeSQLiteDatabase(const fs::path &path, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
std::vector< uint256 > vHave
void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const
void Decode(const unsigned char code[BIP32_EXTKEY_SIZE])
std::optional< DatabaseFormat > require_format
std::vector< uint32_t > path
WalletContext struct containing references to state shared between CWallet instances,...
bool error(const char *fmt, const Args &... args)
#define EXCLUSIVE_LOCKS_REQUIRED(...)
int64_t GetTime()
DEPRECATED Use either GetTimeSeconds (not mockable) or GetTime<T> (mockable)
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, CDataStream &ssKey, CDataStream &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.
@ WALLET_FLAG_EXTERNAL_SIGNER
Indicates that the wallet needs an external signer.