Bitcoin Core  0.20.99
P2P Digital Currency
addrdb.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 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 <hash.h>
12 #include <random.h>
13 #include <streams.h>
14 #include <tinyformat.h>
15 #include <util/system.h>
16 
17 namespace {
18 
19 template <typename Stream, typename Data>
20 bool SerializeDB(Stream& stream, const Data& data)
21 {
22  // Write and commit header, data
23  try {
25  stream << Params().MessageStart() << data;
26  hasher << Params().MessageStart() << data;
27  stream << hasher.GetHash();
28  } catch (const std::exception& e) {
29  return error("%s: Serialize or I/O error - %s", __func__, e.what());
30  }
31 
32  return true;
33 }
34 
35 template <typename Data>
36 bool SerializeFileDB(const std::string& prefix, const fs::path& path, const Data& data)
37 {
38  // Generate random temporary filename
39  unsigned short randv = 0;
40  GetRandBytes((unsigned char*)&randv, sizeof(randv));
41  std::string tmpfn = strprintf("%s.%04x", prefix, randv);
42 
43  // open temp output file, and associate with CAutoFile
44  fs::path pathTmp = GetDataDir() / tmpfn;
45  FILE *file = fsbridge::fopen(pathTmp, "wb");
46  CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
47  if (fileout.IsNull()) {
48  fileout.fclose();
49  remove(pathTmp);
50  return error("%s: Failed to open file %s", __func__, pathTmp.string());
51  }
52 
53  // Serialize
54  if (!SerializeDB(fileout, data)) {
55  fileout.fclose();
56  remove(pathTmp);
57  return false;
58  }
59  if (!FileCommit(fileout.Get())) {
60  fileout.fclose();
61  remove(pathTmp);
62  return error("%s: Failed to flush file %s", __func__, pathTmp.string());
63  }
64  fileout.fclose();
65 
66  // replace existing file, if any, with new file
67  if (!RenameOver(pathTmp, path)) {
68  remove(pathTmp);
69  return error("%s: Rename-into-place failed", __func__);
70  }
71 
72  return true;
73 }
74 
75 template <typename Stream, typename Data>
76 bool DeserializeDB(Stream& stream, Data& data, bool fCheckSum = true)
77 {
78  try {
79  CHashVerifier<Stream> verifier(&stream);
80  // de-serialize file header (network specific magic number) and ..
81  unsigned char pchMsgTmp[4];
82  verifier >> pchMsgTmp;
83  // ... verify the network matches ours
84  if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
85  return error("%s: Invalid network magic number", __func__);
86 
87  // de-serialize data
88  verifier >> data;
89 
90  // verify checksum
91  if (fCheckSum) {
92  uint256 hashTmp;
93  stream >> hashTmp;
94  if (hashTmp != verifier.GetHash()) {
95  return error("%s: Checksum mismatch, data corrupted", __func__);
96  }
97  }
98  }
99  catch (const std::exception& e) {
100  return error("%s: Deserialize or I/O error - %s", __func__, e.what());
101  }
102 
103  return true;
104 }
105 
106 template <typename Data>
107 bool DeserializeFileDB(const fs::path& path, Data& data)
108 {
109  // open input file, and associate with CAutoFile
110  FILE *file = fsbridge::fopen(path, "rb");
111  CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
112  if (filein.IsNull())
113  return error("%s: Failed to open file %s", __func__, path.string());
114 
115  return DeserializeDB(filein, data);
116 }
117 
118 }
119 
120 CBanDB::CBanDB(fs::path ban_list_path) : m_ban_list_path(std::move(ban_list_path))
121 {
122 }
123 
124 bool CBanDB::Write(const banmap_t& banSet)
125 {
126  return SerializeFileDB("banlist", m_ban_list_path, banSet);
127 }
128 
129 bool CBanDB::Read(banmap_t& banSet)
130 {
131  return DeserializeFileDB(m_ban_list_path, banSet);
132 }
133 
135 {
136  pathAddr = GetDataDir() / "peers.dat";
137 }
138 
139 bool CAddrDB::Write(const CAddrMan& addr)
140 {
141  return SerializeFileDB("peers", pathAddr, addr);
142 }
143 
145 {
146  return DeserializeFileDB(pathAddr, addr);
147 }
148 
149 bool CAddrDB::Read(CAddrMan& addr, CDataStream& ssPeers)
150 {
151  bool ret = DeserializeDB(ssPeers, addr, false);
152  if (!ret) {
153  // Ensure addrman is left in a clean state
154  addr.Clear();
155  }
156  return ret;
157 }
bool FileCommit(FILE *file)
Definition: system.cpp:929
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:22
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
CAddrDB()
Definition: addrdb.cpp:134
const char * prefix
Definition: rest.cpp:648
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:201
void GetRandBytes(unsigned char *buf, int num) noexcept
Overall design of the RNG and entropy sources.
Definition: random.cpp:579
const fs::path m_ban_list_path
Definition: addrdb.h:91
Reads data from an underlying stream, while hashing the read data.
Definition: hash.h:161
Stochastical (IP) address manager.
Definition: addrman.h:176
bool Write(const CAddrMan &addr)
Definition: addrdb.cpp:139
CBanDB(fs::path ban_list_path)
Definition: addrdb.cpp:120
const fs::path & GetDataDir(bool fNetSpecific)
Definition: system.cpp:620
const CMessageHeader::MessageStartChars & MessageStart() const
Definition: chainparams.h:61
bool Write(const banmap_t &banSet)
Definition: addrdb.cpp:124
bool RenameOver(fs::path src, fs::path dest)
Definition: system.cpp:899
bool Read(banmap_t &banSet)
Definition: addrdb.cpp:129
256-bit opaque blob.
Definition: uint256.h:120
void Clear()
Definition: addrman.h:502
const CChainParams & Params()
Return the currently selected parameters.
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:117
std::map< CSubNet, CBanEntry > banmap_t
Definition: net_types.h:13
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:38
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
bool Read(CAddrMan &addr)
Definition: addrdb.cpp:144
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:601