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