6#include <bitcoin-build-config.h>
32class DbNotFoundError :
public std::exception
34 using std::exception::exception;
37template <
typename Stream,
typename Data>
38bool SerializeDB(Stream& stream,
const Data& data)
45 }
catch (
const std::exception& e) {
46 LogError(
"%s: Serialize or I/O error - %s\n", __func__, e.what());
53template <
typename Data>
54bool SerializeFileDB(
const std::string&
prefix,
const fs::path& path,
const Data& data)
61 fs::path pathTmp =
gArgs.GetDataDirNet() / fs::u8path(tmpfn);
66 LogError(
"%s: Failed to open file %s\n", __func__, fs::PathToString(pathTmp));
71 if (!SerializeDB(fileout, data)) {
79 LogError(
"%s: Failed to flush file %s\n", __func__, fs::PathToString(pathTmp));
82 if (fileout.
fclose() != 0) {
83 const int errno_save{errno};
85 LogError(
"Failed to close file %s after commit: %s", fs::PathToString(pathTmp),
SysErrorString(errno_save));
92 LogError(
"%s: Rename-into-place failed\n", __func__);
99template <
typename Stream,
typename Data>
100void DeserializeDB(Stream& stream, Data&& data,
bool fCheckSum =
true)
105 verifier >> pchMsgTmp;
107 if (pchMsgTmp !=
Params().MessageStart()) {
108 throw std::runtime_error{
"Invalid network magic number"};
118 if (hashTmp != verifier.
GetHash()) {
119 throw std::runtime_error{
"Checksum mismatch, data corrupted"};
124template <
typename Data>
125void DeserializeFileDB(
const fs::path& path, Data&& data)
130 throw DbNotFoundError{};
132 DeserializeDB(filein, data);
144 std::vector<std::string> errors;
149 for (
const auto& err : errors) {
158 LogWarning(
"banlist.dat ignored because it can only be read by " CLIENT_NAME
" version 22.x. Remove %s to silence this warning.", fs::quoted(fs::PathToString(
m_banlist_dat)));
165 std::map<std::string, common::SettingsValue> settings;
166 std::vector<std::string> errors;
169 for (
const auto& err : errors) {
177 }
catch (
const std::runtime_error& e) {
187 const auto pathAddr =
args.GetDataDirNet() /
"peers.dat";
188 return SerializeFileDB(
"peers", pathAddr, addr);
193 DeserializeDB(ssPeers, addr,
false);
201 auto addrman{std::make_unique<AddrMan>(netgroupman, deterministic, check_addrman)};
203 const auto start{SteadyClock::now()};
204 const auto path_addr{
args.GetDataDirNet() /
"peers.dat"};
206 DeserializeFileDB(path_addr, *addrman);
208 }
catch (
const DbNotFoundError&) {
210 addrman = std::make_unique<AddrMan>(netgroupman, deterministic, check_addrman);
211 LogInfo(
"Creating peers.dat because the file was not found (%s)", fs::quoted(fs::PathToString(path_addr)));
214 if (!
RenameOver(path_addr, (fs::path)path_addr +
".bak")) {
215 return util::Error{
strprintf(
_(
"Failed to rename invalid peers.dat file. Please move or delete it and try again."))};
218 addrman = std::make_unique<AddrMan>(netgroupman, deterministic, check_addrman);
219 LogWarning(
"Creating new peers.dat because the file version was not compatible (%s). Original backed up to peers.dat.bak", fs::quoted(fs::PathToString(path_addr)));
221 }
catch (
const std::exception& e) {
222 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."),
223 e.what(), CLIENT_BUGREPORT, fs::quoted(fs::PathToString(path_addr)))};
228void DumpAnchors(
const fs::path& anchors_db_path,
const std::vector<CAddress>& anchors)
236 std::vector<CAddress> anchors;
239 LogInfo(
"Loaded %i addresses from %s", anchors.size(), fs::quoted(fs::PathToString(anchors_db_path.filename())));
240 }
catch (
const std::exception&) {
244 fs::remove(anchors_db_path);
bool DumpPeerAddresses(const ArgsManager &args, const AddrMan &addr)
std::vector< CAddress > ReadAnchors(const fs::path &anchors_db_path)
Read the anchor IP address database (anchors.dat).
util::Result< std::unique_ptr< AddrMan > > LoadAddrman(const NetGroupManager &netgroupman, const ArgsManager &args)
Returns an error string on failure.
void ReadFromStream(AddrMan &addr, DataStream &ssPeers)
Only used by tests.
void DumpAnchors(const fs::path &anchors_db_path, const std::vector< CAddress > &anchors)
Dump the anchor IP address database (anchors.dat).
static constexpr int32_t DEFAULT_ADDRMAN_CONSISTENCY_CHECKS
Default for -checkaddrman.
bool HasTestOption(const ArgsManager &args, const std::string &test_option)
Checks if a particular test option is present in -test command-line arg options.
const CChainParams & Params()
Return the currently selected parameters.
Stochastic address manager.
Non-refcounted RAII wrapper for FILE*.
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
bool Commit()
Wrapper around FileCommit().
static constexpr SerParams V2_DISK
bool Write(const banmap_t &banSet)
const fs::path m_banlist_dat
bool Read(banmap_t &banSet)
Read the banlist from disk.
static constexpr const char * JSON_KEY
JSON key under which the data is stored in the json database.
const fs::path m_banlist_json
CBanDB(fs::path ban_list_path)
const MessageStartChars & MessageStart() const
Double ended buffer combining vector and stream-like interfaces.
Reads data from an underlying stream, while hashing the read data.
uint256 GetHash()
Compute the double-SHA256 hash of all data written to this object.
Writes data to an underlying source stream, while hashing the written data.
I rand() noexcept
Generate a random integer in its entire (non-negative) range.
bool RenameOver(fs::path src, fs::path dest)
Rename src to dest.
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.
bool ReadSettings(const fs::path &path, std::map< std::string, SettingsValue > &values, std::vector< std::string > &errors)
Read settings file.
FILE * fopen(const fs::path &p, const char *mode)
void BanMapFromJson(const UniValue &bans_json, banmap_t &bans)
Convert a JSON array to a banmap_t object.
UniValue BanMapToJson(const banmap_t &bans)
Convert a banmap_t object to a JSON array.
std::map< CSubNet, CBanEntry > banmap_t
std::string SysErrorString(int err)
Return system error string from errno value.
#define LOG_TIME_SECONDS(end_msg)
consteval auto _(util::TranslatedLiteral str)
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.