 |
Bitcoin Core
21.99.0
P2P Digital Currency
|
Go to the documentation of this file.
39 const std::string
FLAGS{
"flags"};
42 const std::string
KEY{
"key"};
45 const std::string
NAME{
"name"};
48 const std::string
POOL{
"pool"};
51 const std::string
TX{
"tx"};
109 std::vector<unsigned char> vchKey;
110 vchKey.reserve(vchPubKey.
size() + vchPrivKey.size());
111 vchKey.insert(vchKey.end(), vchPubKey.
begin(), vchPubKey.
end());
112 vchKey.insert(vchKey.end(), vchPrivKey.begin(), vchPrivKey.end());
118 const std::vector<unsigned char>& vchCryptedSecret,
129 if (!
WriteIC(key, std::make_pair(vchCryptedSecret, checksum),
false)) {
131 std::vector<unsigned char> val;
132 if (!
m_batch->Read(key, val)) {
135 if (!
WriteIC(key, std::make_pair(val, checksum),
true)) {
209 return WriteIC(make_pair(key, type),
id);
215 std::vector<unsigned char> key;
216 key.reserve(pubkey.
size() + privkey.size());
217 key.insert(key.end(), pubkey.
begin(), pubkey.
end());
218 key.insert(key.end(), privkey.begin(), privkey.end());
240 xpub.
Encode(ser_xpub.data());
247 xpub.
Encode(ser_xpub.data());
282 if (filter_fn && !filter_fn(strType)) {
286 std::string strAddress;
292 std::string strAddress;
300 auto fill_wtx = [&](
CWalletTx& wtx,
bool new_tx) {
303 if (wtx.GetHash() != hash)
307 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
309 if (!ssValue.
empty())
313 std::string unused_string;
314 ssValue >> fTmp >> fUnused >> unused_string;
315 strErr =
strprintf(
"LoadWallet() upgrading tx ver=%d %d %s",
316 wtx.fTimeReceivedIsTxTime, fTmp, hash.ToString());
317 wtx.fTimeReceivedIsTxTime = fTmp;
321 strErr =
strprintf(
"LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString());
322 wtx.fTimeReceivedIsTxTime = 0;
327 if (wtx.nOrderPos == -1)
347 if (!vchPubKey.IsValid())
349 strErr =
"Error reading wallet database: CPubKey corrupt";
368 catch (
const std::ios_base::failure&) {}
370 bool fSkipCheck =
false;
375 std::vector<unsigned char> vchKey;
376 vchKey.reserve(vchPubKey.size() + pkey.size());
377 vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
378 vchKey.insert(vchKey.end(), pkey.begin(), pkey.end());
380 if (
Hash(vchKey) != hash)
382 strErr =
"Error reading wallet database: CPubKey/CPrivKey corrupt";
389 if (!key.
Load(pkey, vchPubKey, fSkipCheck))
391 strErr =
"Error reading wallet database: CPrivKey corrupt";
396 strErr =
"Error reading wallet database: LegacyScriptPubKeyMan::LoadKey failed";
404 ssValue >> kMasterKey;
407 strErr =
strprintf(
"Error reading wallet database: duplicate CMasterKey id %u", nID);
416 if (!vchPubKey.IsValid())
418 strErr =
"Error reading wallet database: CPubKey corrupt";
421 std::vector<unsigned char> vchPrivKey;
422 ssValue >> vchPrivKey;
425 bool checksum_valid =
false;
426 if (!ssValue.
eof()) {
429 if ((checksum_valid =
Hash(vchPrivKey) != checksum)) {
430 strErr =
"Error reading wallet database: Encrypted key corrupt";
439 strErr =
"Error reading wallet database: LegacyScriptPubKeyMan::LoadCryptedKey failed";
456 bool internal =
false;
458 if (keyMeta.hdKeypath !=
"s" && keyMeta.hdKeypath !=
"m") {
459 std::vector<uint32_t> path;
460 if (keyMeta.has_key_origin) {
462 path = keyMeta.key_origin.path;
466 strErr =
"Error reading wallet database: keymeta with invalid HD keypath";
475 if (path.size() != 3) {
476 strErr =
"Error reading wallet database: keymeta found with unexpected path";
479 if (path[0] != 0x80000000) {
480 strErr =
strprintf(
"Unexpected path index of 0x%08x (expected 0x80000000) for the element at index 0", path[0]);
483 if (path[1] != 0x80000000 && path[1] != (1 | 0x80000000)) {
484 strErr =
strprintf(
"Unexpected path index of 0x%08x (expected 0x80000000 or 0x80000001) for the element at index 1", path[1]);
487 if ((path[2] & 0x80000000) == 0) {
488 strErr =
strprintf(
"Unexpected path index of 0x%08x (expected to be greater than or equal to 0x80000000)", path[2]);
491 internal = path[1] == (1 | 0x80000000);
492 index = path[2] & ~0x80000000;
497 CHDChain& chain = ins.first->second;
501 chain.
seed_id = keyMeta.hd_seed_id;
521 ssValue >> vchPubKey;
522 if (!vchPubKey.IsValid()) {
523 strErr =
"Error reading wallet database: Default Key corrupt";
540 strErr =
"Error reading wallet database: LegacyScriptPubKeyMan::LoadCScript failed";
544 ssValue >> pwallet->nOrderPosNext;
546 std::string strAddress, strKey, strValue;
556 strErr =
"Found unsupported 'wkey' record, try loading with version 0.18";
566 if (spk_mans.count(
static_cast<OutputType>(type)) > 0) {
567 strErr =
"Multiple ScriptPubKeyMans specified for a single type";
583 uint32_t key_exp_index;
586 ssKey >> key_exp_index;
599 xpub.
Decode(ser_xpub.data());
610 if (!pubkey.IsValid())
612 strErr =
"Error reading wallet database: CPubKey corrupt";
624 std::vector<unsigned char> to_hash;
625 to_hash.reserve(pubkey.size() + pkey.size());
626 to_hash.insert(to_hash.end(), pubkey.begin(), pubkey.end());
627 to_hash.insert(to_hash.end(), pkey.begin(), pkey.end());
629 if (
Hash(to_hash) != hash)
631 strErr =
"Error reading wallet database: CPubKey/CPrivKey corrupt";
635 if (!key.
Load(pkey, pubkey,
true))
637 strErr =
"Error reading wallet database: CPrivKey corrupt";
640 wss.
m_descriptor_keys.insert(std::make_pair(std::make_pair(desc_id, pubkey.GetID()), key));
646 if (!pubkey.IsValid())
648 strErr =
"Error reading wallet database: CPubKey corrupt";
651 std::vector<unsigned char> privkey;
655 wss.
m_descriptor_crypt_keys.insert(std::make_pair(std::make_pair(desc_id, pubkey.GetID()), std::make_pair(pubkey, privkey)));
663 }
catch (
const std::exception& e) {
664 if (strErr.empty()) {
669 if (strErr.empty()) {
670 strErr =
"Caught unknown exception in ReadKeyValue";
681 return ReadKeyValue(pwallet, ssKey, ssValue, dummy_wss, strType, strErr, filter_fn);
693 bool fNoncriticalErrors =
false;
710 pwallet->
WalletLogPrintf(
"Error reading wallet database: Unknown non-tolerable wallet flags found\n");
728 bool ret =
m_batch->ReadAtCursor(ssKey, ssValue, complete);
735 pwallet->
WalletLogPrintf(
"Error reading next record from wallet database\n");
740 std::string strType, strErr;
741 if (!
ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr))
752 fNoncriticalErrors =
true;
788 ((
DescriptorScriptPubKeyMan*)spk_man)->AddCryptedKey(desc_key_pair.first.second, desc_key_pair.second.first, desc_key_pair.second.second);
804 pwallet->
WalletLogPrintf(
"Wallet File Version = %d\n", wallet_version > 0 ? wallet_version : last_client);
806 pwallet->
WalletLogPrintf(
"Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total. Unknown wallet records: %u\n",
813 LOCK(spk_man->cs_KeyStore);
814 spk_man->UpdateTimeFirstKey(1);
819 WriteTx(pwallet->mapWallet.at(hash));
822 if (wss.
fIsEncrypted && (last_client == 40000 || last_client == 50000))
843 pwallet->
WalletLogPrintf(
"Inactive HD Chains found but no Legacy ScriptPubKeyMan\n");
870 LogPrintf(
"Error getting wallet database cursor\n");
880 bool ret =
m_batch->ReadAtCursor(ssKey, ssValue, complete);
885 LogPrintf(
"Error reading next record from wallet database\n");
894 vTxHash.push_back(hash);
895 vWtx.emplace_back(
nullptr ,
nullptr );
896 ssValue >> vWtx.back();
910 std::vector<uint256> vTxHash;
911 std::list<CWalletTx> vWtx;
917 std::sort(vTxHash.begin(), vTxHash.end());
918 std::sort(vTxHashIn.begin(), vTxHashIn.end());
921 bool delerror =
false;
922 std::vector<uint256>::iterator
it = vTxHashIn.begin();
923 for (
const uint256& hash : vTxHash) {
924 while (
it < vTxHashIn.end() && (*
it) < hash) {
927 if (
it == vTxHashIn.end()) {
930 else if ((*
it) == hash) {
932 LogPrint(
BCLog::WALLETDB,
"Transaction was found for deletion but returned database error: %s\n", hash.GetHex());
935 vTxHashOut.push_back(hash);
947 static std::atomic<bool> fOneThread(
false);
948 if (fOneThread.exchange(
true)) {
952 for (
const std::shared_ptr<CWallet>& pwallet :
GetWallets()) {
1012 exists = fs::symlink_status(path).type() != fs::file_not_found;
1013 }
catch (
const fs::filesystem_error& e) {
1019 std::optional<DatabaseFormat>
format;
1074 error =
Untranslated(
strprintf(
"Failed to open database path '%s'. Build does not support SQLite database format.", path.string()));
1082 error =
Untranslated(
strprintf(
"Failed to open database path '%s'. Build does not support Berkeley DB database format.", path.string()));
1090 return std::make_unique<DummyDatabase>();
1097 return std::make_unique<BerkeleyDatabase>(std::make_shared<BerkeleyEnvironment>(),
"");
1099 return std::make_unique<SQLiteDatabase>(
"",
"",
true);
bool WritePool(int64_t nPool, const CKeyPool &keypool)
void WalletLogPrintf(std::string fmt, Params... parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
const unsigned int BIP32_EXTKEY_SIZE
bool WriteDestData(const std::string &address, const std::string &key, const std::string &value)
Write destination data key,value tuple to database.
bool WriteDescriptor(const uint256 &desc_id, const WalletDescriptor &descriptor)
unsigned int nMasterKeyMaxID
static bool IsKeyType(const std::string &strType)
uint32_t nExternalChainCounter
const std::string OLD_KEY
std::vector< std::shared_ptr< CWallet > > GetWallets()
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
bool WriteCryptedDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const std::vector< unsigned char > &secret)
const std::string CSCRIPT
std::unique_ptr< DatabaseBatch > m_batch
bool WriteName(const std::string &strAddress, const std::string &strName)
void MaybeCompactWalletDB()
Compacts BDB state so that wallet.dat is self-contained (if there are changes)
std::unique_ptr< WalletDatabase > CreateDummyWalletDatabase()
Return object for accessing dummy database with no read/write capabilities.
const std::string BESTBLOCK
A key from a CWallet's keypool.
const CHDChain & GetHDChain() const
const std::string MASTER_KEY
bool EraseTx(uint256 hash)
const std::string ORDERPOSNEXT
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
std::map< std::pair< uint256, CKeyID >, CKey > m_descriptor_keys
DBErrors LoadWallet(CWallet *pwallet)
const std::string CRYPTED_KEY
void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
Load a keypool entry.
std::map< std::pair< uint256, CKeyID >, std::pair< CPubKey, std::vector< unsigned char > > > m_descriptor_crypt_keys
std::string get_filesystem_error_message(const fs::filesystem_error &e)
void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor &desc)
Instantiate a descriptor ScriptPubKeyMan from the WalletDescriptor and load it.
bool IsSQLiteFile(const fs::path &path)
std::vector< unsigned char, secure_allocator< unsigned char > > CPrivKey
secure_allocator is defined in allocators.h CPrivKey is a serialized private key, with all parameters...
void LoadKeyMetadata(const CKeyID &keyID, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
int64_t GetTime()
DEPRECATED Use either GetSystemTimeInSeconds (not mockable) or GetTime<T> (mockable)
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)
const std::string WALLETDESCRIPTORCACHE
Private key encryption is done based on a CMasterKey, which holds a salt and random encryption key.
An instance of this class represents one database.
static const int VERSION_HD_CHAIN_SPLIT
void Decode(const unsigned char code[BIP32_EXTKEY_SIZE])
std::unique_ptr< WalletDatabase > MakeDatabase(const fs::path &path, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
bool LoadKey(const CKey &key, const CPubKey &pubkey)
Adds a key to the store, without saving it to disk (used by LoadWallet)
const std::string VERSION
const std::string MINVERSION
bool WriteActiveScriptPubKeyMan(uint8_t type, const uint256 &id, bool internal)
const std::string ACTIVEINTERNALSPK
bool TxnCommit()
Commit current transaction.
const std::string WATCHMETA
int GetVersion() const
get the current wallet format (the oldest client version guaranteed to understand this wallet)
bool WriteDescriptorParentCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index)
const std::string WALLETDESCRIPTORCKEY
const unsigned char * begin() const
const std::string PURPOSE
std::atomic< unsigned int > nUpdateCounter
uint256 Hash(const T &in1)
Compute the 256-bit hash of an object.
bool LoadCScript(const CScript &redeemScript)
Adds a CScript to the store.
void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo.
static const int VERSION_HD_BASE
int64_t nLastWalletUpdate
const std::string KEYMETA
void LoadHDChain(const CHDChain &chain)
Load a HD chain model (used by LoadWallet)
bool LoadWalletFlags(uint64_t flags)
Loads the flags into the wallet.
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
bool EraseIC(const K &key)
bool ReadPool(int64_t nPool, CKeyPool &keypool)
bool WriteOrderPosNext(int64_t nOrderPosNext)
bool EraseDestData(const std::string &address, const std::string &key)
Erase destination data tuple from wallet database.
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.
const std::string WALLETDESCRIPTOR
std::unique_ptr< SQLiteDatabase > MakeSQLiteDatabase(const fs::path &path, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
const unsigned char * end() const
const std::string BESTBLOCK_NOMERKLE
bool IsBDBFile(const fs::path &path)
bool WritePurpose(const std::string &strAddress, const std::string &purpose)
const std::string SETTINGS
bool EraseWatchOnly(const CScript &script)
std::vector< uint256 > vWalletUpgrade
uint32_t nInternalChainCounter
const std::string DEFAULTKEY
unsigned int nLastFlushed
bool WriteBestBlock(const CBlockLocator &locator)
bool ErasePool(int64_t nPool)
fs::path BDBDataFile(const fs::path &wallet_path)
bool WriteDescriptorDerivedCache(const CExtPubKey &xpub, const uint256 &desc_id, uint32_t key_exp_index, uint32_t der_index)
MasterKeyMap mapMasterKeys
DBErrors ReorderTransactions()
unsigned int size() const
Simple read-only vector-like interface to the pubkey data.
bool EraseName(const std::string &strAddress)
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg)
#define LogPrint(category,...)
void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const
Serialized script, used inside transaction inputs and outputs.
std::map< OutputType, uint256 > m_active_internal_spks
LegacyScriptPubKeyMan * GetLegacyScriptPubKeyMan() const
Get the LegacyScriptPubKeyMan which is used for all types, internal, and external.
bool WriteHDChain(const CHDChain &chain)
write the hdchain model (external chain child index counter)
const std::string ACTIVEEXTERNALSPK
Cache for single descriptor's derived extended pubkeys.
unsigned int m_unknown_records
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)
std::map< OutputType, uint256 > m_active_external_spks
bool ReadBestBlock(CBlockLocator &locator)
bool WriteDescriptorKey(const uint256 &desc_id, const CPubKey &pubkey, const CPrivKey &privkey)
void LoadScriptMetadata(const CScriptID &script_id, const CKeyMetadata &metadata)
DBErrors
Error statuses for the wallet database.
An encapsulated public key.
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, const CKeyMetadata &keyMeta)
An encapsulated private key.
std::map< uint160, CHDChain > m_hd_chains
#define EXCLUSIVE_LOCKS_REQUIRED(...)
std::vector< uint256 > vHave
fs::path SQLiteDataFile(const fs::path &path)
std::unique_ptr< WalletDatabase > CreateMockWalletDatabase()
Return object for accessing temporary in-memory database.
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
CKeyID seed_id
seed hash160
const uint256 & GetHash() const
A transaction with a bunch of additional info that only the owner cares about.
DBErrors FindWalletTx(std::vector< uint256 > &vTxHash, std::list< CWalletTx > &vWtx)
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
bool WriteKeyMetadata(const CKeyMetadata &meta, const CPubKey &pubkey, const bool overwrite)
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 IsLegacy() const
Determine if we are a legacy wallet.
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
virtual bool PeriodicFlush()=0
Double ended buffer combining vector and stream-like interfaces.
bool WriteIC(const K &key, const T &value, bool fOverwrite=true)
ScriptPubKeyMan * GetScriptPubKeyMan(const OutputType &type, bool internal) const
Get the ScriptPubKeyMan for the given OutputType and internal/external chain.
bool ErasePurpose(const std::string &strAddress)
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut)
bool WriteMinVersion(int nVersion)
Descriptor with some wallet metadata.
std::function< bool(const std::string &)> KeyFilterFn
Callback for filtering key types to deserialize in ReadKeyValue.
const std::string ACENTRY
const std::string HDCHAIN
bool Load(const CPrivKey &privkey, const CPubKey &vchPubKey, bool fSkipCheck)
Load private key and check that public key matches.
bool TxnBegin()
Begin a new transaction.
bool error(const char *fmt, const Args &... args)
bool WriteTx(const CWalletTx &wtx)
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
void AddInactiveHDChain(const CHDChain &chain)
bool ParseHDKeypath(const std::string &keypath_str, std::vector< uint32_t > &keypath)
Parse an HD keypaths like "m/7/0'/2000".
void LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
Loads an active ScriptPubKeyMan for the specified type and internal.
A reference to a CScript: the Hash160 of its serialization (see script.h)
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
std::map< uint256, DescriptorCache > m_descriptor_caches
assert(std::addressof(::ChainstateActive().CoinsTip())==std::addressof(coins_cache))
std::optional< DatabaseFormat > require_format
bool LoadToWallet(const uint256 &hash, const UpdateWalletTxFn &fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
LegacyScriptPubKeyMan * GetOrCreateLegacyScriptPubKeyMan()
bool LoadMinVersion(int nVersion) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
const std::string WALLETDESCRIPTORKEY
bool WriteWalletFlags(const uint64_t flags)
bool TxnAbort()
Abort current transaction.
const std::string DESTDATA