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