Bitcoin ABC  0.26.3
P2P Digital Currency
addrdb.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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 <fs.h>
12 #include <hash.h>
13 #include <logging/timer.h>
14 #include <random.h>
15 #include <streams.h>
16 #include <tinyformat.h>
17 #include <util/system.h>
18 #include <util/translation.h>
19 
20 #include <cstdint>
21 
22 namespace {
23 
24 class DbNotFoundError : public std::exception {
25  using std::exception::exception;
26 };
27 
28 template <typename Stream, typename Data>
29 bool SerializeDB(const CChainParams &chainParams, Stream &stream,
30  const Data &data) {
31  // Write and commit header, data
32  try {
33  CHashWriter hasher(stream.GetType(), stream.GetVersion());
34  stream << chainParams.DiskMagic() << data;
35  hasher << chainParams.DiskMagic() << data;
36  stream << hasher.GetHash();
37  } catch (const std::exception &e) {
38  return error("%s: Serialize or I/O error - %s", __func__, e.what());
39  }
40 
41  return true;
42 }
43 
44 template <typename Data>
45 bool SerializeFileDB(const CChainParams &chainParams, const std::string &prefix,
46  const fs::path &path, const Data &data, int version) {
47  // Generate random temporary filename
48  const uint16_t randv{GetRand<uint16_t>()};
49  std::string tmpfn = strprintf("%s.%04x", prefix, randv);
50 
51  // open temp output file, and associate with CAutoFile
52  fs::path pathTmp = gArgs.GetDataDirNet() / tmpfn;
53  FILE *file = fsbridge::fopen(pathTmp, "wb");
54  CAutoFile fileout(file, SER_DISK, version);
55  if (fileout.IsNull()) {
56  fileout.fclose();
57  remove(pathTmp);
58  return error("%s: Failed to open file %s", __func__,
59  fs::PathToString(pathTmp));
60  }
61 
62  // Serialize
63  if (!SerializeDB(chainParams, fileout, data)) {
64  fileout.fclose();
65  remove(pathTmp);
66  return false;
67  }
68  if (!FileCommit(fileout.Get())) {
69  fileout.fclose();
70  remove(pathTmp);
71  return error("%s: Failed to flush file %s", __func__,
72  fs::PathToString(pathTmp));
73  }
74  fileout.fclose();
75 
76  // replace existing file, if any, with new file
77  if (!RenameOver(pathTmp, path)) {
78  remove(pathTmp);
79  return error("%s: Rename-into-place failed", __func__);
80  }
81 
82  return true;
83 }
84 
85 template <typename Stream, typename Data>
86 void DeserializeDB(const CChainParams &chainParams, Stream &stream, Data &data,
87  bool fCheckSum = true) {
88  CHashVerifier<Stream> verifier(&stream);
89  // de-serialize file header (network specific magic number) and ..
90  uint8_t pchMsgTmp[4];
91  verifier >> pchMsgTmp;
92  // ... verify the network matches ours
93  if (memcmp(pchMsgTmp, std::begin(chainParams.DiskMagic()),
94  sizeof(pchMsgTmp))) {
95  throw std::runtime_error{"Invalid network magic number"};
96  }
97 
98  // de-serialize data
99  verifier >> data;
100 
101  // verify checksum
102  if (fCheckSum) {
103  uint256 hashTmp;
104  stream >> hashTmp;
105  if (hashTmp != verifier.GetHash()) {
106  throw std::runtime_error{"Checksum mismatch, data corrupted"};
107  }
108  }
109 }
110 
111 template <typename Data>
112 void DeserializeFileDB(const CChainParams &chainParams, const fs::path &path,
113  Data &data, int version) {
114  // open input file, and associate with CAutoFile
115  FILE *file = fsbridge::fopen(path, "rb");
116  CAutoFile filein(file, SER_DISK, version);
117  if (filein.IsNull()) {
118  throw DbNotFoundError{};
119  }
120 
121  DeserializeDB(chainParams, filein, data);
122 }
123 
124 } // namespace
125 
126 CBanDB::CBanDB(fs::path ban_list_path, const CChainParams &_chainParams)
127  : m_ban_list_path(std::move(ban_list_path)), chainParams(_chainParams) {}
128 
129 bool CBanDB::Write(const banmap_t &banSet) {
130  return SerializeFileDB(chainParams, "banlist", m_ban_list_path, banSet,
132 }
133 
134 bool CBanDB::Read(banmap_t &banSet) {
135  // TODO: this needs to be reworked after banlist.dat is deprecated (in
136  // favor of banlist.json). See:
137  // - https://github.com/bitcoin/bitcoin/pull/20966
138  // - https://github.com/bitcoin/bitcoin/pull/22570
139  try {
140  DeserializeFileDB(chainParams, m_ban_list_path, banSet, CLIENT_VERSION);
141  } catch (const std::exception &) {
142  LogPrintf("Missing or invalid file %s\n",
144  return false;
145  }
146 
147  return true;
148 }
149 
150 bool DumpPeerAddresses(const CChainParams &chainParams, const ArgsManager &args,
151  const AddrMan &addr) {
152  const auto pathAddr = args.GetDataDirNet() / "peers.dat";
153  return SerializeFileDB(chainParams, "peers", pathAddr, addr,
155 }
156 
157 void ReadFromStream(const CChainParams &chainParams, AddrMan &addr,
158  CDataStream &ssPeers) {
159  DeserializeDB(chainParams, ssPeers, addr, false);
160 }
161 
163 LoadAddrman(const CChainParams &chainparams, const std::vector<bool> &asmap,
164  const ArgsManager &args) {
165  auto check_addrman = std::clamp<int32_t>(
166  args.GetIntArg("-checkaddrman", DEFAULT_ADDRMAN_CONSISTENCY_CHECKS), 0,
167  1000000);
168  auto addrman{std::make_unique<AddrMan>(
169  asmap, /* consistency_check_ratio= */ check_addrman)};
170 
171  int64_t nStart = GetTimeMillis();
172  const auto path_addr{args.GetDataDirNet() / "peers.dat"};
173  try {
174  DeserializeFileDB(chainparams, path_addr, *addrman, CLIENT_VERSION);
175  LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman->size(),
176  GetTimeMillis() - nStart);
177  } catch (const DbNotFoundError &) {
178  // Addrman can be in an inconsistent state after failure, reset it
179  addrman = std::make_unique<AddrMan>(
180  asmap, /* consistency_check_ratio= */ check_addrman);
181  LogPrintf("Creating peers.dat because the file was not found (%s)\n",
182  fs::quoted(fs::PathToString(path_addr)));
183  DumpPeerAddresses(chainparams, args, *addrman);
184  } catch (const InvalidAddrManVersionError &) {
185  if (!RenameOver(path_addr, fs::path(path_addr) + ".bak")) {
186  return util::Error{
187  strprintf(_("Failed to rename invalid peers.dat file. "
188  "Please move or delete it and try again."))};
189  }
190  // Addrman can be in an inconsistent state after failure, reset it
191  addrman = std::make_unique<AddrMan>(
192  asmap, /* consistency_check_ratio= */ check_addrman);
193  LogPrintf("Creating new peers.dat because the file version was not "
194  "compatible (%s). Original backed up to peers.dat.bak\n",
195  fs::quoted(fs::PathToString(path_addr)));
196  DumpPeerAddresses(chainparams, args, *addrman);
197  } catch (const std::exception &e) {
198  return util::Error{strprintf(
199  _("Invalid or corrupt peers.dat (%s). If you believe this is a "
200  "bug, please report it to %s. As a workaround, you can move the "
201  "file (%s) out of the way (rename, move, or delete) to have a "
202  "new one created on the next start."),
203  e.what(), PACKAGE_BUGREPORT,
204  fs::quoted(fs::PathToString(path_addr)))};
205  }
206 
207  // std::move should be unneccessary but is temporarily needed to work
208  // around clang bug
209  // (https://github.com/bitcoin/bitcoin/pull/25977#issuecomment-1564350880)
210  return {std::move(addrman)};
211 }
212 
213 void DumpAnchors(const CChainParams &chainParams,
214  const fs::path &anchors_db_path,
215  const std::vector<CAddress> &anchors) {
217  "Flush %d outbound block-relay-only peer addresses to anchors.dat",
218  anchors.size()));
219  SerializeFileDB(chainParams, "anchors", anchors_db_path, anchors,
221 }
222 
223 std::vector<CAddress> ReadAnchors(const CChainParams &chainParams,
224  const fs::path &anchors_db_path) {
225  std::vector<CAddress> anchors;
226  try {
227  DeserializeFileDB(chainParams, anchors_db_path, anchors,
229  LogPrintf("Loaded %i addresses from %s\n", anchors.size(),
230  fs::quoted(fs::PathToString(anchors_db_path.filename())));
231  } catch (const std::exception &) {
232  anchors.clear();
233  }
234 
235  fs::remove(anchors_db_path);
236  return anchors;
237 }
void ReadFromStream(const CChainParams &chainParams, AddrMan &addr, CDataStream &ssPeers)
Only used by tests.
Definition: addrdb.cpp:157
bool DumpPeerAddresses(const CChainParams &chainParams, const ArgsManager &args, const AddrMan &addr)
Definition: addrdb.cpp:150
std::vector< CAddress > ReadAnchors(const CChainParams &chainParams, const fs::path &anchors_db_path)
Read the anchor IP address database (anchors.dat)
Definition: addrdb.cpp:223
void DumpAnchors(const CChainParams &chainParams, const fs::path &anchors_db_path, const std::vector< CAddress > &anchors)
Dump the anchor IP address database (anchors.dat)
Definition: addrdb.cpp:213
util::Result< std::unique_ptr< AddrMan > > LoadAddrman(const CChainParams &chainparams, const std::vector< bool > &asmap, const ArgsManager &args)
Returns an error string on failure.
Definition: addrdb.cpp:163
static constexpr int32_t DEFAULT_ADDRMAN_CONSISTENCY_CHECKS
Default for -checkaddrman.
Definition: addrman.h:29
Stochastic address manager.
Definition: addrman.h:69
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:268
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: system.cpp:635
bool Write(const banmap_t &banSet)
Definition: addrdb.cpp:129
const fs::path m_ban_list_path
Definition: addrdb.h:60
CBanDB(fs::path ban_list_path, const CChainParams &_chainParams)
Definition: addrdb.cpp:126
bool Read(banmap_t &banSet)
Definition: addrdb.cpp:134
const CChainParams & chainParams
Definition: addrdb.h:61
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:74
const CMessageHeader::MessageMagic & DiskMagic() const
Definition: chainparams.h:87
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:199
Reads data from an underlying stream, while hashing the read data.
Definition: hash.h:160
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:99
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
path filename() const
Definition: fs.h:87
256-bit opaque blob.
Definition: uint256.h:127
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:38
#define LogPrintf(...)
Definition: logging.h:206
static auto quoted(const std::string &s)
Definition: fs.h:107
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:142
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:28
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:257
std::map< CSubNet, CBanEntry > banmap_t
Definition: net_types.h:13
static constexpr int ADDRV2_FORMAT
A flag that is ORed into the protocol version to designate that addresses should be serialized in (un...
Definition: netaddress.h:33
const char * prefix
Definition: rest.cpp:819
@ SER_DISK
Definition: serialize.h:167
bool RenameOver(fs::path src, fs::path dest)
Definition: system.cpp:1202
ArgsManager gArgs
Definition: system.cpp:80
bool FileCommit(FILE *file)
Definition: system.cpp:1231
bool error(const char *fmt, const Args &...args)
Definition: system.h:45
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:101
#define LOG_TIME_SECONDS(end_msg)
Definition: timer.h:103
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68