Bitcoin Core 28.99.0
P2P Digital Currency
db.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2021 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#include <chainparams.h>
7#include <common/args.h>
8#include <logging.h>
9#include <util/fs.h>
10#include <wallet/db.h>
11
12#include <algorithm>
13#include <exception>
14#include <fstream>
15#include <string>
16#include <system_error>
17#include <vector>
18
19namespace wallet {
20bool operator<(BytePrefix a, Span<const std::byte> b) { return std::ranges::lexicographical_compare(a.prefix, b.subspan(0, std::min(a.prefix.size(), b.size()))); }
21bool operator<(Span<const std::byte> a, BytePrefix b) { return std::ranges::lexicographical_compare(a.subspan(0, std::min(a.size(), b.prefix.size())), b.prefix); }
22
23std::vector<std::pair<fs::path, std::string>> ListDatabases(const fs::path& wallet_dir)
24{
25 std::vector<std::pair<fs::path, std::string>> paths;
26 std::error_code ec;
27
28 for (auto it = fs::recursive_directory_iterator(wallet_dir, ec); it != fs::recursive_directory_iterator(); it.increment(ec)) {
29 if (ec) {
30 if (fs::is_directory(*it)) {
31 it.disable_recursion_pending();
32 LogPrintf("%s: %s %s -- skipping.\n", __func__, ec.message(), fs::PathToString(it->path()));
33 } else {
34 LogPrintf("%s: %s %s\n", __func__, ec.message(), fs::PathToString(it->path()));
35 }
36 continue;
37 }
38
39 try {
40 const fs::path path{it->path().lexically_relative(wallet_dir)};
41
42 if (it->status().type() == fs::file_type::directory) {
43 if (IsBDBFile(BDBDataFile(it->path()))) {
44 // Found a directory which contains wallet.dat btree file, add it as a wallet with BERKELEY format.
45 paths.emplace_back(path, "bdb");
46 } else if (IsSQLiteFile(SQLiteDataFile(it->path()))) {
47 // Found a directory which contains wallet.dat sqlite file, add it as a wallet with SQLITE format.
48 paths.emplace_back(path, "sqlite");
49 }
50 } else if (it.depth() == 0 && it->symlink_status().type() == fs::file_type::regular && it->path().extension() != ".bak") {
51 if (it->path().filename() == "wallet.dat") {
52 // Found top-level wallet.dat file, add top level directory ""
53 // as a wallet.
54 if (IsBDBFile(it->path())) {
55 paths.emplace_back(fs::path(), "bdb");
56 } else if (IsSQLiteFile(it->path())) {
57 paths.emplace_back(fs::path(), "sqlite");
58 }
59 } else if (IsBDBFile(it->path())) {
60 // Found top-level btree file not called wallet.dat. Current bitcoin
61 // software will never create these files but will allow them to be
62 // opened in a shared database environment for backwards compatibility.
63 // Add it to the list of available wallets.
64 paths.emplace_back(path, "bdb");
65 }
66 }
67 } catch (const std::exception& e) {
68 LogPrintf("%s: Error scanning %s: %s\n", __func__, fs::PathToString(it->path()), e.what());
69 it.disable_recursion_pending();
70 }
71 }
72
73 return paths;
74}
75
76fs::path BDBDataFile(const fs::path& wallet_path)
77{
78 if (fs::is_regular_file(wallet_path)) {
79 // Special case for backwards compatibility: if wallet path points to an
80 // existing file, treat it as the path to a BDB data file in a parent
81 // directory that also contains BDB log files.
82 return wallet_path;
83 } else {
84 // Normal case: Interpret wallet path as a directory path containing
85 // data and log files.
86 return wallet_path / "wallet.dat";
87 }
88}
89
91{
92 return path / "wallet.dat";
93}
94
95bool IsBDBFile(const fs::path& path)
96{
97 if (!fs::exists(path)) return false;
98
99 // A Berkeley DB Btree file has at least 4K.
100 // This check also prevents opening lock files.
101 std::error_code ec;
102 auto size = fs::file_size(path, ec);
103 if (ec) LogPrintf("%s: %s %s\n", __func__, ec.message(), fs::PathToString(path));
104 if (size < 4096) return false;
105
106 std::ifstream file{path, std::ios::binary};
107 if (!file.is_open()) return false;
108
109 file.seekg(12, std::ios::beg); // Magic bytes start at offset 12
110 uint32_t data = 0;
111 file.read((char*) &data, sizeof(data)); // Read 4 bytes of file to compare against magic
112
113 // Berkeley DB Btree magic bytes, from:
114 // https://github.com/file/file/blob/5824af38469ec1ca9ac3ffd251e7afe9dc11e227/magic/Magdir/database#L74-L75
115 // - big endian systems - 00 05 31 62
116 // - little endian systems - 62 31 05 00
117 return data == 0x00053162 || data == 0x62310500;
118}
119
120bool IsSQLiteFile(const fs::path& path)
121{
122 if (!fs::exists(path)) return false;
123
124 // A SQLite Database file is at least 512 bytes.
125 std::error_code ec;
126 auto size = fs::file_size(path, ec);
127 if (ec) LogPrintf("%s: %s %s\n", __func__, ec.message(), fs::PathToString(path));
128 if (size < 512) return false;
129
130 std::ifstream file{path, std::ios::binary};
131 if (!file.is_open()) return false;
132
133 // Magic is at beginning and is 16 bytes long
134 char magic[16];
135 file.read(magic, 16);
136
137 // Application id is at offset 68 and 4 bytes long
138 file.seekg(68, std::ios::beg);
139 char app_id[4];
140 file.read(app_id, 4);
141
142 file.close();
143
144 // Check the magic, see https://sqlite.org/fileformat.html
145 std::string magic_str(magic, 16);
146 if (magic_str != std::string{"SQLite format 3\000", 16}) {
147 return false;
148 }
149
150 // Check the application id matches our network magic
151 return memcmp(Params().MessageStart().data(), app_id, 4) == 0;
152}
153
155{
156 // Override current options with args values, if any were specified
157 options.use_unsafe_sync = args.GetBoolArg("-unsafesqlitesync", options.use_unsafe_sync);
158 options.use_shared_memory = !args.GetBoolArg("-privdb", !options.use_shared_memory);
159 options.max_log_mb = args.GetIntArg("-dblogsize", options.max_log_mb);
160}
161
162} // namespace wallet
ArgsManager & args
Definition: bitcoind.cpp:277
const CChainParams & Params()
Return the currently selected parameters.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:482
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:507
constexpr std::size_t size() const noexcept
Definition: span.h:187
CONSTEXPR_IF_NOT_DEBUG Span< C > subspan(std::size_t offset) const noexcept
Definition: span.h:195
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:33
path(std::filesystem::path path)
Definition: fs.h:38
#define LogPrintf(...)
Definition: logging.h:266
static bool exists(const path &p)
Definition: fs.h:89
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:151
void ReadDatabaseArgs(const ArgsManager &args, DatabaseOptions &options)
Definition: db.cpp:154
fs::path SQLiteDataFile(const fs::path &path)
Definition: db.cpp:90
bool IsBDBFile(const fs::path &path)
Definition: db.cpp:95
fs::path BDBDataFile(const fs::path &wallet_path)
Definition: db.cpp:76
bool operator<(BytePrefix a, Span< const std::byte > b)
Definition: db.cpp:20
bool IsSQLiteFile(const fs::path &path)
Definition: db.cpp:120
std::vector< std::pair< fs::path, std::string > > ListDatabases(const fs::path &wallet_dir)
Recursively list database paths in directory.
Definition: db.cpp:23
Span< const std::byte > prefix
Definition: db.h:25
bool use_shared_memory
Let other processes access the database.
Definition: db.h:201
bool use_unsafe_sync
Disable file sync for faster performance.
Definition: db.h:200
int64_t max_log_mb
Max log size to allow before consolidating.
Definition: db.h:202