Bitcoin Core  26.99.0
P2P Digital Currency
addrdb.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2022 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 <addrdb.h>
7 
8 #include <addrman.h>
9 #include <chainparams.h>
10 #include <clientversion.h>
11 #include <common/args.h>
12 #include <common/settings.h>
13 #include <cstdint>
14 #include <hash.h>
15 #include <logging.h>
16 #include <logging/timer.h>
17 #include <netbase.h>
18 #include <netgroup.h>
19 #include <random.h>
20 #include <streams.h>
21 #include <tinyformat.h>
22 #include <univalue.h>
23 #include <util/fs.h>
24 #include <util/fs_helpers.h>
25 #include <util/translation.h>
26 
27 namespace {
28 
29 class DbNotFoundError : public std::exception
30 {
31  using std::exception::exception;
32 };
33 
34 template <typename Stream, typename Data>
35 bool SerializeDB(Stream& stream, const Data& data)
36 {
37  // Write and commit header, data
38  try {
39  HashedSourceWriter hashwriter{stream};
40  hashwriter << Params().MessageStart() << data;
41  stream << hashwriter.GetHash();
42  } catch (const std::exception& e) {
43  return error("%s: Serialize or I/O error - %s", __func__, e.what());
44  }
45 
46  return true;
47 }
48 
49 template <typename Data>
50 bool SerializeFileDB(const std::string& prefix, const fs::path& path, const Data& data)
51 {
52  // Generate random temporary filename
53  const uint16_t randv{GetRand<uint16_t>()};
54  std::string tmpfn = strprintf("%s.%04x", prefix, randv);
55 
56  // open temp output file
57  fs::path pathTmp = gArgs.GetDataDirNet() / fs::u8path(tmpfn);
58  FILE *file = fsbridge::fopen(pathTmp, "wb");
59  AutoFile fileout{file};
60  if (fileout.IsNull()) {
61  fileout.fclose();
62  remove(pathTmp);
63  return error("%s: Failed to open file %s", __func__, fs::PathToString(pathTmp));
64  }
65 
66  // Serialize
67  if (!SerializeDB(fileout, data)) {
68  fileout.fclose();
69  remove(pathTmp);
70  return false;
71  }
72  if (!FileCommit(fileout.Get())) {
73  fileout.fclose();
74  remove(pathTmp);
75  return error("%s: Failed to flush file %s", __func__, fs::PathToString(pathTmp));
76  }
77  fileout.fclose();
78 
79  // replace existing file, if any, with new file
80  if (!RenameOver(pathTmp, path)) {
81  remove(pathTmp);
82  return error("%s: Rename-into-place failed", __func__);
83  }
84 
85  return true;
86 }
87 
88 template <typename Stream, typename Data>
89 void DeserializeDB(Stream& stream, Data&& data, bool fCheckSum = true)
90 {
91  HashVerifier verifier{stream};
92  // de-serialize file header (network specific magic number) and ..
93  MessageStartChars pchMsgTmp;
94  verifier >> pchMsgTmp;
95  // ... verify the network matches ours
96  if (pchMsgTmp != Params().MessageStart()) {
97  throw std::runtime_error{"Invalid network magic number"};
98  }
99 
100  // de-serialize data
101  verifier >> data;
102 
103  // verify checksum
104  if (fCheckSum) {
105  uint256 hashTmp;
106  stream >> hashTmp;
107  if (hashTmp != verifier.GetHash()) {
108  throw std::runtime_error{"Checksum mismatch, data corrupted"};
109  }
110  }
111 }
112 
113 template <typename Data>
114 void DeserializeFileDB(const fs::path& path, Data&& data)
115 {
116  FILE* file = fsbridge::fopen(path, "rb");
117  AutoFile filein{file};
118  if (filein.IsNull()) {
119  throw DbNotFoundError{};
120  }
121  DeserializeDB(filein, data);
122 }
123 } // namespace
124 
125 CBanDB::CBanDB(fs::path ban_list_path)
126  : m_banlist_dat(ban_list_path + ".dat"),
127  m_banlist_json(ban_list_path + ".json")
128 {
129 }
130 
131 bool CBanDB::Write(const banmap_t& banSet)
132 {
133  std::vector<std::string> errors;
134  if (common::WriteSettings(m_banlist_json, {{JSON_KEY, BanMapToJson(banSet)}}, errors)) {
135  return true;
136  }
137 
138  for (const auto& err : errors) {
139  error("%s", err);
140  }
141  return false;
142 }
143 
144 bool CBanDB::Read(banmap_t& banSet)
145 {
146  if (fs::exists(m_banlist_dat)) {
147  LogPrintf("banlist.dat ignored because it can only be read by " PACKAGE_NAME " version 22.x. Remove %s to silence this warning.\n", fs::quoted(fs::PathToString(m_banlist_dat)));
148  }
149  // If the JSON banlist does not exist, then recreate it
150  if (!fs::exists(m_banlist_json)) {
151  return false;
152  }
153 
154  std::map<std::string, common::SettingsValue> settings;
155  std::vector<std::string> errors;
156 
157  if (!common::ReadSettings(m_banlist_json, settings, errors)) {
158  for (const auto& err : errors) {
159  LogPrintf("Cannot load banlist %s: %s\n", fs::PathToString(m_banlist_json), err);
160  }
161  return false;
162  }
163 
164  try {
165  BanMapFromJson(settings[JSON_KEY], banSet);
166  } catch (const std::runtime_error& e) {
167  LogPrintf("Cannot parse banlist %s: %s\n", fs::PathToString(m_banlist_json), e.what());
168  return false;
169  }
170 
171  return true;
172 }
173 
174 bool DumpPeerAddresses(const ArgsManager& args, const AddrMan& addr)
175 {
176  const auto pathAddr = args.GetDataDirNet() / "peers.dat";
177  return SerializeFileDB("peers", pathAddr, addr);
178 }
179 
180 void ReadFromStream(AddrMan& addr, DataStream& ssPeers)
181 {
182  DeserializeDB(ssPeers, addr, false);
183 }
184 
186 {
187  auto check_addrman = std::clamp<int32_t>(args.GetIntArg("-checkaddrman", DEFAULT_ADDRMAN_CONSISTENCY_CHECKS), 0, 1000000);
188  auto addrman{std::make_unique<AddrMan>(netgroupman, /*deterministic=*/false, /*consistency_check_ratio=*/check_addrman)};
189 
190  const auto start{SteadyClock::now()};
191  const auto path_addr{args.GetDataDirNet() / "peers.dat"};
192  try {
193  DeserializeFileDB(path_addr, *addrman);
194  LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman->Size(), Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));
195  } catch (const DbNotFoundError&) {
196  // Addrman can be in an inconsistent state after failure, reset it
197  addrman = std::make_unique<AddrMan>(netgroupman, /*deterministic=*/false, /*consistency_check_ratio=*/check_addrman);
198  LogPrintf("Creating peers.dat because the file was not found (%s)\n", fs::quoted(fs::PathToString(path_addr)));
199  DumpPeerAddresses(args, *addrman);
200  } catch (const InvalidAddrManVersionError&) {
201  if (!RenameOver(path_addr, (fs::path)path_addr + ".bak")) {
202  return util::Error{strprintf(_("Failed to rename invalid peers.dat file. Please move or delete it and try again."))};
203  }
204  // Addrman can be in an inconsistent state after failure, reset it
205  addrman = std::make_unique<AddrMan>(netgroupman, /*deterministic=*/false, /*consistency_check_ratio=*/check_addrman);
206  LogPrintf("Creating new peers.dat because the file version was not compatible (%s). Original backed up to peers.dat.bak\n", fs::quoted(fs::PathToString(path_addr)));
207  DumpPeerAddresses(args, *addrman);
208  } catch (const std::exception& e) {
209  return util::Error{strprintf(_("Invalid or corrupt peers.dat (%s). If you believe this is a bug, please report it to %s. As a workaround, you can move the file (%s) out of the way (rename, move, or delete) to have a new one created on the next start."),
210  e.what(), PACKAGE_BUGREPORT, fs::quoted(fs::PathToString(path_addr)))};
211  }
212  return addrman;
213 }
214 
215 void DumpAnchors(const fs::path& anchors_db_path, const std::vector<CAddress>& anchors)
216 {
217  LOG_TIME_SECONDS(strprintf("Flush %d outbound block-relay-only peer addresses to anchors.dat", anchors.size()));
218  SerializeFileDB("anchors", anchors_db_path, CAddress::V2_DISK(anchors));
219 }
220 
221 std::vector<CAddress> ReadAnchors(const fs::path& anchors_db_path)
222 {
223  std::vector<CAddress> anchors;
224  try {
225  DeserializeFileDB(anchors_db_path, CAddress::V2_DISK(anchors));
226  LogPrintf("Loaded %i addresses from %s\n", anchors.size(), fs::quoted(fs::PathToString(anchors_db_path.filename())));
227  } catch (const std::exception&) {
228  anchors.clear();
229  }
230 
231  fs::remove(anchors_db_path);
232  return anchors;
233 }
std::vector< CAddress > ReadAnchors(const fs::path &anchors_db_path)
Read the anchor IP address database (anchors.dat)
Definition: addrdb.cpp:221
bool DumpPeerAddresses(const ArgsManager &args, const AddrMan &addr)
Definition: addrdb.cpp:174
util::Result< std::unique_ptr< AddrMan > > LoadAddrman(const NetGroupManager &netgroupman, const ArgsManager &args)
Returns an error string on failure.
Definition: addrdb.cpp:185
void ReadFromStream(AddrMan &addr, DataStream &ssPeers)
Only used by tests.
Definition: addrdb.cpp:180
void DumpAnchors(const fs::path &anchors_db_path, const std::vector< CAddress > &anchors)
Dump the anchor IP address database (anchors.dat)
Definition: addrdb.cpp:215
static constexpr int32_t DEFAULT_ADDRMAN_CONSISTENCY_CHECKS
Default for -checkaddrman.
Definition: addrman.h:31
ArgsManager gArgs
Definition: args.cpp:41
#define PACKAGE_NAME
#define PACKAGE_BUGREPORT
ArgsManager & args
Definition: bitcoind.cpp:269
const CChainParams & Params()
Return the currently selected parameters.
Stochastic address manager.
Definition: addrman.h:88
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: args.h:232
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:480
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:389
int fclose()
Definition: streams.h:405
static constexpr SerParams V2_DISK
Definition: protocol.h:407
bool Write(const banmap_t &banSet)
Definition: addrdb.cpp:131
const fs::path m_banlist_dat
Definition: addrdb.h:36
bool Read(banmap_t &banSet)
Read the banlist from disk.
Definition: addrdb.cpp:144
static constexpr const char * JSON_KEY
JSON key under which the data is stored in the json database.
Definition: addrdb.h:34
const fs::path m_banlist_json
Definition: addrdb.h:37
CBanDB(fs::path ban_list_path)
Definition: addrdb.cpp:125
const MessageStartChars & MessageStart() const
Definition: chainparams.h:94
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:147
Reads data from an underlying stream, while hashing the read data.
Definition: hash.h:151
Writes data to an underlying source stream, while hashing the written data.
Definition: hash.h:185
Netgroup manager.
Definition: netgroup.h:16
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:31
path filename() const
Definition: fs.h:67
256-bit opaque blob.
Definition: uint256.h:106
bool RenameOver(fs::path src, fs::path dest)
Rename src to dest.
Definition: fs_helpers.cpp:260
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
Definition: fs_helpers.cpp:119
bool error(const char *fmt, const Args &... args)
Definition: logging.h:262
#define LogPrintf(...)
Definition: logging.h:237
std::array< uint8_t, 4 > MessageStartChars
bool WriteSettings(const fs::path &path, const std::map< std::string, SettingsValue > &values, std::vector< std::string > &errors)
Write settings file.
Definition: settings.cpp:112
bool ReadSettings(const fs::path &path, std::map< std::string, SettingsValue > &values, std::vector< std::string > &errors)
Read settings file.
Definition: settings.cpp:67
static path u8path(const std::string &utf8_str)
Definition: fs.h:70
static auto quoted(const std::string &s)
Definition: fs.h:94
static bool exists(const path &p)
Definition: fs.h:88
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:150
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:25
void BanMapFromJson(const UniValue &bans_json, banmap_t &bans)
Convert a JSON array to a banmap_t object.
Definition: net_types.cpp:58
UniValue BanMapToJson(const banmap_t &bans)
Convert a banmap_t object to a JSON array.
Definition: net_types.cpp:38
std::map< CSubNet, CBanEntry > banmap_t
Definition: net_types.h:41
const char * prefix
Definition: rest.cpp:1002
#define LOG_TIME_SECONDS(end_msg)
Definition: timer.h:107
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:74