BSHA3  0.17.99
P2P Blockchain, based on Bitcoin
addrdb.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 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.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 {
24  CHashWriter hasher(SER_DISK, CLIENT_VERSION);
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  return error("%s: Failed to open file %s", __func__, pathTmp.string());
49 
50  // Serialize
51  if (!SerializeDB(fileout, data)) return false;
52  if (!FileCommit(fileout.Get()))
53  return error("%s: Failed to flush file %s", __func__, pathTmp.string());
54  fileout.fclose();
55 
56  // replace existing file, if any, with new file
57  if (!RenameOver(pathTmp, path))
58  return error("%s: Rename-into-place failed", __func__);
59 
60  return true;
61 }
62 
63 template <typename Stream, typename Data>
64 bool DeserializeDB(Stream& stream, Data& data, bool fCheckSum = true)
65 {
66  try {
67  CHashVerifier<Stream> verifier(&stream);
68  // de-serialize file header (network specific magic number) and ..
69  unsigned char pchMsgTmp[4];
70  verifier >> pchMsgTmp;
71  // ... verify the network matches ours
72  if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
73  return error("%s: Invalid network magic number", __func__);
74 
75  // de-serialize data
76  verifier >> data;
77 
78  // verify checksum
79  if (fCheckSum) {
80  uint256 hashTmp;
81  stream >> hashTmp;
82  if (hashTmp != verifier.GetHash()) {
83  return error("%s: Checksum mismatch, data corrupted", __func__);
84  }
85  }
86  }
87  catch (const std::exception& e) {
88  return error("%s: Deserialize or I/O error - %s", __func__, e.what());
89  }
90 
91  return true;
92 }
93 
94 template <typename Data>
95 bool DeserializeFileDB(const fs::path& path, Data& data)
96 {
97  // open input file, and associate with CAutoFile
98  FILE *file = fsbridge::fopen(path, "rb");
99  CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
100  if (filein.IsNull())
101  return error("%s: Failed to open file %s", __func__, path.string());
102 
103  return DeserializeDB(filein, data);
104 }
105 
106 }
107 
109 {
110  pathBanlist = GetDataDir() / "banlist.dat";
111 }
112 
113 bool CBanDB::Write(const banmap_t& banSet)
114 {
115  return SerializeFileDB("banlist", pathBanlist, banSet);
116 }
117 
118 bool CBanDB::Read(banmap_t& banSet)
119 {
120  return DeserializeFileDB(pathBanlist, banSet);
121 }
122 
124 {
125  pathAddr = GetDataDir() / "peers.dat";
126 }
127 
128 bool CAddrDB::Write(const CAddrMan& addr)
129 {
130  return SerializeFileDB("peers", pathAddr, addr);
131 }
132 
134 {
135  return DeserializeFileDB(pathAddr, addr);
136 }
137 
138 bool CAddrDB::Read(CAddrMan& addr, CDataStream& ssPeers)
139 {
140  bool ret = DeserializeDB(ssPeers, addr, false);
141  if (!ret) {
142  // Ensure addrman is left in a clean state
143  addr.Clear();
144  }
145  return ret;
146 }
bool FileCommit(FILE *file)
Definition: util.cpp:1029
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:13
CBanDB()
Definition: addrdb.cpp:108
#define strprintf
Definition: tinyformat.h:1066
CAddrDB()
Definition: addrdb.cpp:123
UniValue ret(UniValue::VARR)
Definition: rpcwallet.cpp:1140
const char * prefix
Definition: rest.cpp:581
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:221
Reads data from an underlying stream, while hashing the read data (SHA-256).
Definition: hash.h:200
Stochastical (IP) address manager.
Definition: addrman.h:188
std::map< CSubNet, CBanEntry > banmap_t
Definition: addrdb.h:77
bool Write(const CAddrMan &addr)
Definition: addrdb.cpp:128
const CMessageHeader::MessageStartChars & MessageStart() const
Definition: chainparams.h:61
bool RenameOver(fs::path src, fs::path dest)
Definition: util.cpp:999
bool Write(const banmap_t &banSet)
Definition: addrdb.cpp:113
fs::path pathBanlist
Definition: addrdb.h:95
bool Read(banmap_t &banSet)
Definition: addrdb.cpp:118
256-bit opaque blob.
Definition: uint256.h:122
void Clear()
Definition: addrman.h:472
const CChainParams & Params()
Return the currently selected parameters.
fs::path pathAddr
Definition: addrdb.h:83
void GetRandBytes(unsigned char *buf, int num)
Functions to gather random data via the OpenSSL PRNG.
Definition: random.cpp:275
bool error(const char *fmt, const Args &... args)
Definition: util.h:59
A writer stream (for serialization) that computes a 256-bit SHA-3-256 hash.
Definition: hash.h:165
const fs::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:766
bool Read(CAddrMan &addr)
Definition: addrdb.cpp:133
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:621