Inside Bitcoin
Opening the selected file…
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2009-2010 Satoshi Nakamoto2// Copyright (c) 2009-present The Bitcoin Core developers3// Distributed under the MIT software license, see the accompanying4// file COPYING or http://www.opensource.org/licenses/mit-license.php.6#include <chainparams.h>7#include <common/args.h>8#include <util/fs.h>9#include <util/log.h>10#include <wallet/db.h>12#include <algorithm>13#include <exception>14#include <fstream>15#include <string>16#include <system_error>17#include <vector>19namespace wallet {20bool operator<(BytePrefix a, std::span<const std::byte> b) { return std::ranges::lexicographical_compare(a.prefix, b.subspan(0, std::min(a.prefix.size(), b.size()))); }21bool operator<(std::span<const std::byte> a, BytePrefix b) { return std::ranges::lexicographical_compare(a.subspan(0, std::min(a.size(), b.prefix.size())), b.prefix); }23std::vector<std::pair<fs::path, std::string>> ListDatabases(const fs::path& wallet_dir)24{25std::vector<std::pair<fs::path, std::string>> paths;26std::error_code ec;28for (auto it = fs::recursive_directory_iterator(wallet_dir, ec); it != fs::recursive_directory_iterator(); it.increment(ec)) {29assert(!ec); // Loop should exit on error.30try {31const fs::path path{it->path().lexically_relative(wallet_dir)};33if (it->status().type() == fs::file_type::directory) {34if (IsBDBFile(BDBDataFile(it->path()))) {35// Found a directory which contains wallet.dat btree file, add it as a wallet with BERKELEY format.36paths.emplace_back(path, "bdb");37} else if (IsSQLiteFile(SQLiteDataFile(it->path()))) {38// Found a directory which contains wallet.dat sqlite file, add it as a wallet with SQLITE format.39paths.emplace_back(path, "sqlite");40}41} else if (it.depth() == 0 && it->symlink_status().type() == fs::file_type::regular && it->path().extension() != ".bak") {42if (it->path().filename() == "wallet.dat") {43// Found top-level wallet.dat file, add top level directory ""44// as a wallet.45if (IsBDBFile(it->path())) {46paths.emplace_back(fs::path(), "bdb");47} else if (IsSQLiteFile(it->path())) {48paths.emplace_back(fs::path(), "sqlite");49}50} else if (IsBDBFile(it->path())) {51// Found top-level btree file not called wallet.dat. Current bitcoin52// software will never create these files but will allow them to be53// opened in a shared database environment for backwards compatibility.54// Add it to the list of available wallets.55paths.emplace_back(path, "bdb");56}57}58} catch (const std::exception& e) {59LogWarning("Error while scanning wallet dir item: %s [%s].", e.what(), fs::PathToString(it->path()));60it.disable_recursion_pending();61}62}63if (ec) {64// Loop could have exited with an error due to one of:65// * wallet_dir itself not being scannable.66// * increment() failure. (Observed on Windows native builds when67// removing the ACL read permissions of a wallet directory after the68// process started).69LogWarning("Error scanning directory entries under %s: %s", fs::PathToString(wallet_dir), ec.message());70}72return paths;73}75fs::path BDBDataFile(const fs::path& wallet_path)76{77if (fs::is_regular_file(wallet_path)) {78// Special case for backwards compatibility: if wallet path points to an79// existing file, treat it as the path to a BDB data file in a parent80// directory that also contains BDB log files.81return wallet_path;82} else {83// Normal case: Interpret wallet path as a directory path containing84// data and log files.85return wallet_path / "wallet.dat";86}87}89fs::path SQLiteDataFile(const fs::path& path)90{91return path / "wallet.dat";92}94bool IsBDBFile(const fs::path& path)95{96if (!fs::exists(path)) return false;98// A Berkeley DB Btree file has at least 4K.99// This check also prevents opening lock files.100std::error_code ec;101auto size = fs::file_size(path, ec);102if (ec) LogWarning("Error reading file_size: %s [%s]", ec.message(), fs::PathToString(path));103if (size < 4096) return false;105std::ifstream file{path.std_path(), std::ios::binary};106if (!file.is_open()) return false;108file.seekg(12, std::ios::beg); // Magic bytes start at offset 12109uint32_t data = 0;110file.read((char*) &data, sizeof(data)); // Read 4 bytes of file to compare against magic112// Berkeley DB Btree magic bytes, from:113// https://github.com/file/file/blob/5824af38469ec1ca9ac3ffd251e7afe9dc11e227/magic/Magdir/database#L74-L75114// - big endian systems - 00 05 31 62115// - little endian systems - 62 31 05 00116return data == 0x00053162 || data == 0x62310500;117}119bool IsSQLiteFile(const fs::path& path)120{121if (!fs::exists(path)) return false;123// A SQLite Database file is at least 512 bytes.124std::error_code ec;125auto size = fs::file_size(path, ec);126if (ec) LogWarning("Error reading file_size: %s [%s]", ec.message(), fs::PathToString(path));127if (size < 512) return false;129std::ifstream file{path.std_path(), std::ios::binary};130if (!file.is_open()) return false;132// Magic is at beginning and is 16 bytes long133char magic[16];134file.read(magic, 16);136// Application id is at offset 68 and 4 bytes long137file.seekg(68, std::ios::beg);138char app_id[4];139file.read(app_id, 4);141file.close();143// Check the magic, see https://sqlite.org/fileformat.html144std::string magic_str(magic, 16);145if (magic_str != std::string{"SQLite format 3\000", 16}) {146return false;147}149// Check the application id matches our network magic150return memcmp(Params().MessageStart().data(), app_id, 4) == 0;151}153void ReadDatabaseArgs(const ArgsManager& args, DatabaseOptions& options)154{155// Override current options with args values, if any were specified156options.use_unsafe_sync = args.GetBoolArg("-unsafesqlitesync", options.use_unsafe_sync);157}159} // namespace wallet