Bitcoin ABC  0.22.13
P2P Digital Currency
protocol.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 <protocol.h>
7 
8 #include <chainparams.h>
9 #include <config.h>
10 #include <util/strencodings.h>
11 #include <util/system.h>
12 
13 #ifndef WIN32
14 #include <arpa/inet.h>
15 #endif
16 #include <atomic>
17 
18 static std::atomic<bool> g_initial_block_download_completed(false);
19 
20 namespace NetMsgType {
21 const char *VERSION = "version";
22 const char *VERACK = "verack";
23 const char *ADDR = "addr";
24 const char *INV = "inv";
25 const char *GETDATA = "getdata";
26 const char *MERKLEBLOCK = "merkleblock";
27 const char *GETBLOCKS = "getblocks";
28 const char *GETHEADERS = "getheaders";
29 const char *TX = "tx";
30 const char *HEADERS = "headers";
31 const char *BLOCK = "block";
32 const char *GETADDR = "getaddr";
33 const char *MEMPOOL = "mempool";
34 const char *PING = "ping";
35 const char *PONG = "pong";
36 const char *NOTFOUND = "notfound";
37 const char *FILTERLOAD = "filterload";
38 const char *FILTERADD = "filteradd";
39 const char *FILTERCLEAR = "filterclear";
40 const char *SENDHEADERS = "sendheaders";
41 const char *FEEFILTER = "feefilter";
42 const char *SENDCMPCT = "sendcmpct";
43 const char *CMPCTBLOCK = "cmpctblock";
44 const char *GETBLOCKTXN = "getblocktxn";
45 const char *BLOCKTXN = "blocktxn";
46 const char *GETCFILTERS = "getcfilters";
47 const char *CFILTER = "cfilter";
48 const char *GETCFHEADERS = "getcfheaders";
49 const char *CFHEADERS = "cfheaders";
50 const char *GETCFCHECKPT = "getcfcheckpt";
51 const char *CFCHECKPT = "cfcheckpt";
52 const char *AVAHELLO = "avahello";
53 const char *AVAPOLL = "avapoll";
54 const char *AVARESPONSE = "avaresponse";
55 
56 bool IsBlockLike(const std::string &strCommand) {
57  return strCommand == NetMsgType::BLOCK ||
58  strCommand == NetMsgType::CMPCTBLOCK ||
59  strCommand == NetMsgType::BLOCKTXN;
60 }
61 }; // namespace NetMsgType
62 
67 static const std::string allNetMessageTypes[] = {
79 };
80 static const std::vector<std::string>
83 
84 CMessageHeader::CMessageHeader(const MessageMagic &pchMessageStartIn) {
85  memcpy(std::begin(pchMessageStart), std::begin(pchMessageStartIn),
86  MESSAGE_START_SIZE);
87  memset(pchCommand.data(), 0, sizeof(pchCommand));
88  nMessageSize = -1;
89  memset(pchChecksum, 0, CHECKSUM_SIZE);
90 }
91 
93  const char *pszCommand,
94  unsigned int nMessageSizeIn) {
95  memcpy(std::begin(pchMessageStart), std::begin(pchMessageStartIn),
96  MESSAGE_START_SIZE);
97  // Copy the command name, zero-padding to COMMAND_SIZE bytes
98  size_t i = 0;
99  for (; i < pchCommand.size() && pszCommand[i] != 0; ++i) {
100  pchCommand[i] = pszCommand[i];
101  }
102  // Assert that the command name passed in is not longer than COMMAND_SIZE
103  assert(pszCommand[i] == 0);
104  for (; i < pchCommand.size(); ++i) {
105  pchCommand[i] = 0;
106  }
107 
108  nMessageSize = nMessageSizeIn;
109  memset(pchChecksum, 0, CHECKSUM_SIZE);
110 }
111 
112 std::string CMessageHeader::GetCommand() const {
113  // return std::string(pchCommand.begin(), pchCommand.end());
114  return std::string(pchCommand.data(),
115  pchCommand.data() +
116  strnlen(pchCommand.data(), COMMAND_SIZE));
117 }
118 
119 static bool
121  const CMessageHeader::MessageMagic &magic) {
122  // Check start string
123  if (memcmp(std::begin(header.pchMessageStart), std::begin(magic),
125  return false;
126  }
127 
128  // Check the command string for errors
129  for (const char *p1 = header.pchCommand.data();
130  p1 < header.pchCommand.data() + CMessageHeader::COMMAND_SIZE; p1++) {
131  if (*p1 == 0) {
132  // Must be all zeros after the first zero
133  for (; p1 < header.pchCommand.data() + CMessageHeader::COMMAND_SIZE;
134  p1++) {
135  if (*p1 != 0) {
136  return false;
137  }
138  }
139  } else if (*p1 < ' ' || *p1 > 0x7E) {
140  return false;
141  }
142  }
143 
144  return true;
145 }
146 
147 bool CMessageHeader::IsValid(const Config &config) const {
148  // Check start string
149  if (!CheckHeaderMagicAndCommand(*this,
150  config.GetChainParams().NetMagic())) {
151  return false;
152  }
153 
154  // Message size
155  if (IsOversized(config)) {
156  LogPrintf("CMessageHeader::IsValid(): (%s, %u bytes) is oversized\n",
157  GetCommand(), nMessageSize);
158  return false;
159  }
160 
161  return true;
162 }
163 
172  // Check start string
173  if (!CheckHeaderMagicAndCommand(*this, magic)) {
174  return false;
175  }
176 
177  // Message size
178  if (nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) {
179  LogPrintf(
180  "CMessageHeader::IsValidForSeeder(): (%s, %u bytes) is oversized\n",
181  GetCommand(), nMessageSize);
182  return false;
183  }
184 
185  return true;
186 }
187 
188 bool CMessageHeader::IsOversized(const Config &config) const {
189  // If the message doesn't not contain a block content, check against
190  // MAX_PROTOCOL_MESSAGE_LENGTH.
191  if (nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH &&
192  !NetMsgType::IsBlockLike(GetCommand())) {
193  return true;
194  }
195 
196  // Scale the maximum accepted size with the block size.
197  if (nMessageSize > 2 * config.GetMaxBlockSize()) {
198  return true;
199  }
200 
201  return false;
202 }
203 
205  if ((services & NODE_NETWORK_LIMITED) &&
207  return ServiceFlags(NODE_NETWORK_LIMITED);
208  }
209  return ServiceFlags(NODE_NETWORK);
210 }
211 
212 void SetServiceFlagsIBDCache(bool state) {
214 }
215 
217  Init();
218 }
219 
220 CAddress::CAddress(CService ipIn, ServiceFlags nServicesIn) : CService(ipIn) {
221  Init();
222  nServices = nServicesIn;
223 }
224 
227  nTime = 100000000;
228 }
229 
230 std::string CInv::GetCommand() const {
231  std::string cmd;
232  switch (GetKind()) {
233  case MSG_TX:
234  return cmd.append(NetMsgType::TX);
235  case MSG_BLOCK:
236  return cmd.append(NetMsgType::BLOCK);
237  case MSG_FILTERED_BLOCK:
238  return cmd.append(NetMsgType::MERKLEBLOCK);
239  case MSG_CMPCT_BLOCK:
240  return cmd.append(NetMsgType::CMPCTBLOCK);
241  default:
242  throw std::out_of_range(
243  strprintf("CInv::GetCommand(): type=%d unknown type", type));
244  }
245 }
246 
247 std::string CInv::ToString() const {
248  try {
249  return strprintf("%s %s", GetCommand(), hash.ToString());
250  } catch (const std::out_of_range &) {
251  return strprintf("0x%08x %s", type, hash.ToString());
252  }
253 }
254 
255 const std::vector<std::string> &getAllNetMessageTypes() {
256  return allNetMessageTypesVec;
257 }
258 
264 static std::string serviceFlagToStr(const size_t bit) {
265  const uint64_t service_flag = 1ULL << bit;
266  switch (ServiceFlags(service_flag)) {
267  case NODE_NONE:
268  // impossible
269  abort();
270  case NODE_NETWORK:
271  return "NETWORK";
272  case NODE_GETUTXO:
273  return "GETUTXO";
274  case NODE_BLOOM:
275  return "BLOOM";
277  return "NETWORK_LIMITED";
279  return "COMPACT_FILTERS";
280  case NODE_AVALANCHE:
281  return "AVALANCHE";
282  default:
283  std::ostringstream stream;
284  stream.imbue(std::locale::classic());
285  stream << "UNKNOWN[";
286  stream << "2^" << bit;
287  stream << "]";
288  return stream.str();
289  }
290 }
291 
292 std::vector<std::string> serviceFlagsToStr(const uint64_t flags) {
293  std::vector<std::string> str_flags;
294 
295  for (size_t i = 0; i < sizeof(flags) * 8; ++i) {
296  if (flags & (1ULL << i)) {
297  str_flags.emplace_back(serviceFlagToStr(i));
298  }
299  }
300 
301  return str_flags;
302 }
const char * GETCFILTERS
getcfilters requests compact filters for a range of blocks.
Definition: protocol.cpp:46
const char * PING
The ping message is sent periodically to help confirm that the receiving peer is still connected...
Definition: protocol.cpp:34
const char * FILTERLOAD
The filterload message tells the receiving peer to filter all relayed transactions and requested merk...
Definition: protocol.cpp:37
const char * MERKLEBLOCK
The merkleblock message is a reply to a getdata message which requested a block using the inventory t...
Definition: protocol.cpp:26
const char * BLOCKTXN
Contains a BlockTransactions.
Definition: protocol.cpp:45
static bool CheckHeaderMagicAndCommand(const CMessageHeader &header, const CMessageHeader::MessageMagic &magic)
Definition: protocol.cpp:120
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (Currently 2MB).
Definition: protocol.h:28
static const std::string allNetMessageTypes[]
All known message types.
Definition: protocol.cpp:67
ServiceFlags
nServices flags.
Definition: protocol.h:320
std::string GetCommand() const
Definition: protocol.cpp:230
CMessageHeader(const MessageMagic &pchMessageStartIn)
Definition: protocol.cpp:84
std::string ToString() const
Definition: protocol.cpp:247
const char * GETADDR
The getaddr message requests an addr message from the receiving node, preferably one with lots of IP ...
Definition: protocol.cpp:32
void Init()
Definition: protocol.cpp:225
Defined in BIP152.
Definition: protocol.h:485
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
const char * AVAHELLO
Contains a delegation and a signature.
Definition: protocol.cpp:52
const char * SENDCMPCT
Contains a 1-byte bool and 8-byte LE version number.
Definition: protocol.cpp:42
static const std::vector< std::string > allNetMessageTypesVec(allNetMessageTypes, allNetMessageTypes+ARRAYLEN(allNetMessageTypes))
#define ARRAYLEN(array)
Utilities for converting data from/to strings.
Definition: strencodings.h:19
const char * CFHEADERS
cfheaders is a response to a getcfheaders request containing a filter header and a vector of filter h...
Definition: protocol.cpp:49
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:174
void SetServiceFlagsIBDCache(bool state)
Set the current IBD status in order to figure out the desirable service flags.
Definition: protocol.cpp:212
const char * CFILTER
cfilter is a response to a getcfilters request containing a single compact filter.
Definition: protocol.cpp:47
MessageMagic pchMessageStart
Definition: protocol.h:77
std::string GetCommand() const
Definition: protocol.cpp:112
const char * PONG
The pong message replies to a ping message, proving to the pinging node that the ponging node is stil...
Definition: protocol.cpp:35
const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
Definition: protocol.cpp:30
virtual const CChainParams & GetChainParams() const =0
const char * GETCFCHECKPT
getcfcheckpt requests evenly spaced compact filter headers, enabling parallelized download and valida...
Definition: protocol.cpp:50
const char * INV
The inv message (inventory message) transmits one or more inventories of objects known to the transmi...
Definition: protocol.cpp:24
static std::atomic< bool > g_initial_block_download_completed(false)
const char * GETHEADERS
The getheaders message requests a headers message that provides block headers starting from a particu...
Definition: protocol.cpp:28
bool IsOversized(const Config &config) const
Definition: protocol.cpp:188
virtual uint64_t GetMaxBlockSize() const =0
Definition: config.h:19
static constexpr size_t COMMAND_SIZE
Definition: protocol.h:40
std::vector< std::string > serviceFlagsToStr(const uint64_t flags)
Convert service flags (a bitmask of NODE_*) to human readable strings.
Definition: protocol.cpp:292
Bitcoin protocol message types.
Definition: protocol.cpp:20
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:179
const char * SENDHEADERS
Indicates that a node prefers to receive new block announcements via a "headers" message rather than ...
Definition: protocol.cpp:40
const char * MEMPOOL
The mempool message requests the TXIDs of transactions that the receiving node has verified as valid ...
Definition: protocol.cpp:33
static std::string serviceFlagToStr(const size_t bit)
Convert a service flag (NODE_*) to a human readable string.
Definition: protocol.cpp:264
const std::vector< std::string > & getAllNetMessageTypes()
Get a vector of all valid message types (see above)
Definition: protocol.cpp:255
const char * ADDR
The addr (IP address) message relays connection information for peers on the network.
Definition: protocol.cpp:23
std::array< char, COMMAND_SIZE > pchCommand
Definition: protocol.h:78
const char * FILTERCLEAR
The filterclear message tells the receiving peer to remove a previously-set bloom filter...
Definition: protocol.cpp:39
const char * NOTFOUND
The notfound message is a reply to a getdata message which requested an object the receiving node doe...
Definition: protocol.cpp:36
const char * BLOCK
The block message transmits a single serialized block.
Definition: protocol.cpp:31
const char * FEEFILTER
The feefilter message tells the receiving peer not to inv us any txs which do not meet the specified ...
Definition: protocol.cpp:41
const char * GETCFHEADERS
getcfheaders requests a compact filter header and the filter hashes for a range of blocks...
Definition: protocol.cpp:48
static constexpr size_t MESSAGE_START_SIZE
Definition: protocol.h:39
const char * GETBLOCKS
The getblocks message requests an inv message that provides block header hashes starting from a parti...
Definition: protocol.cpp:27
int flags
Definition: bitcoin-tx.cpp:529
const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
Definition: protocol.cpp:22
unsigned int nTime
Definition: protocol.h:466
ServiceFlags nServices
Definition: protocol.h:463
const char * AVARESPONSE
Contains an avalanche::Response.
Definition: protocol.cpp:54
const char * CMPCTBLOCK
Contains a CBlockHeaderAndShortTxIDs object - providing a header and list of "short txids"...
Definition: protocol.cpp:43
std::array< uint8_t, MESSAGE_START_SIZE > MessageMagic
Definition: protocol.h:49
const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
Definition: protocol.cpp:21
size_t strnlen(const char *start, size_t max_len)
Definition: strnlen.cpp:12
ServiceFlags GetDesirableServiceFlags(ServiceFlags services)
Gets the set of service flags which are "desirable" for a given peer.
Definition: protocol.cpp:204
const char * GETDATA
The getdata message requests one or more data objects from another node.
Definition: protocol.cpp:25
const char * AVAPOLL
Contains an avalanche::Poll.
Definition: protocol.cpp:53
bool IsValid(const Config &config) const
Definition: protocol.cpp:147
bool IsBlockLike(const std::string &strCommand)
Indicate if the message is used to transmit the content of a block.
Definition: protocol.cpp:56
const char * CFCHECKPT
cfcheckpt is a response to a getcfcheckpt request containing a vector of evenly spaced filter headers...
Definition: protocol.cpp:51
const char * TX
The tx message transmits a single transaction.
Definition: protocol.cpp:29
bool IsValidWithoutConfig(const MessageMagic &magic) const
This is a transition method in order to stay compatible with older code that do not use the config...
Definition: protocol.cpp:171
const CMessageHeader::MessageMagic & NetMagic() const
Definition: chainparams.h:61
Defined in BIP37.
Definition: protocol.h:483
const char * FILTERADD
The filteradd message tells the receiving peer to add a single element to a previously-set bloom filt...
Definition: protocol.cpp:38
const char * GETBLOCKTXN
Contains a BlockTransactionsRequest Peer should respond with "blocktxn" message.
Definition: protocol.cpp:44
Message header.
Definition: protocol.h:37