Bitcoin ABC  0.28.12
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/system.h>
11 
12 #include <atomic>
13 
14 static std::atomic<bool> g_initial_block_download_completed(false);
15 
16 namespace NetMsgType {
17 const char *VERSION = "version";
18 const char *VERACK = "verack";
19 const char *ADDR = "addr";
20 const char *ADDRV2 = "addrv2";
21 const char *SENDADDRV2 = "sendaddrv2";
22 const char *INV = "inv";
23 const char *GETDATA = "getdata";
24 const char *MERKLEBLOCK = "merkleblock";
25 const char *GETBLOCKS = "getblocks";
26 const char *GETHEADERS = "getheaders";
27 const char *TX = "tx";
28 const char *HEADERS = "headers";
29 const char *BLOCK = "block";
30 const char *GETADDR = "getaddr";
31 const char *MEMPOOL = "mempool";
32 const char *PING = "ping";
33 const char *PONG = "pong";
34 const char *NOTFOUND = "notfound";
35 const char *FILTERLOAD = "filterload";
36 const char *FILTERADD = "filteradd";
37 const char *FILTERCLEAR = "filterclear";
38 const char *SENDHEADERS = "sendheaders";
39 const char *FEEFILTER = "feefilter";
40 const char *SENDCMPCT = "sendcmpct";
41 const char *CMPCTBLOCK = "cmpctblock";
42 const char *GETBLOCKTXN = "getblocktxn";
43 const char *BLOCKTXN = "blocktxn";
44 const char *GETCFILTERS = "getcfilters";
45 const char *CFILTER = "cfilter";
46 const char *GETCFHEADERS = "getcfheaders";
47 const char *CFHEADERS = "cfheaders";
48 const char *GETCFCHECKPT = "getcfcheckpt";
49 const char *CFCHECKPT = "cfcheckpt";
50 const char *AVAHELLO = "avahello";
51 const char *AVAPOLL = "avapoll";
52 const char *AVARESPONSE = "avaresponse";
53 const char *AVAPROOF = "avaproof";
54 const char *GETAVAADDR = "getavaaddr";
55 const char *GETAVAPROOFS = "getavaproofs";
56 const char *AVAPROOFS = "avaproofs";
57 const char *AVAPROOFSREQ = "avaproofsreq";
58 
59 bool IsBlockLike(const std::string &strCommand) {
60  return strCommand == NetMsgType::BLOCK ||
61  strCommand == NetMsgType::CMPCTBLOCK ||
62  strCommand == NetMsgType::BLOCKTXN;
63 }
64 }; // namespace NetMsgType
65 
70 static const std::string allNetMessageTypes[] = {
82 };
83 static const std::vector<std::string>
85  std::end(allNetMessageTypes));
86 
87 CMessageHeader::CMessageHeader(const MessageMagic &pchMessageStartIn) {
88  memcpy(std::begin(pchMessageStart), std::begin(pchMessageStartIn),
90  memset(pchCommand.data(), 0, sizeof(pchCommand));
91  nMessageSize = -1;
92  memset(pchChecksum, 0, CHECKSUM_SIZE);
93 }
94 
96  const char *pszCommand,
97  unsigned int nMessageSizeIn) {
98  memcpy(std::begin(pchMessageStart), std::begin(pchMessageStartIn),
100  // Copy the command name, zero-padding to COMMAND_SIZE bytes
101  size_t i = 0;
102  for (; i < pchCommand.size() && pszCommand[i] != 0; ++i) {
103  pchCommand[i] = pszCommand[i];
104  }
105  // Assert that the command name passed in is not longer than COMMAND_SIZE
106  assert(pszCommand[i] == 0);
107  for (; i < pchCommand.size(); ++i) {
108  pchCommand[i] = 0;
109  }
110 
111  nMessageSize = nMessageSizeIn;
112  memset(pchChecksum, 0, CHECKSUM_SIZE);
113 }
114 
115 std::string CMessageHeader::GetCommand() const {
116  // return std::string(pchCommand.begin(), pchCommand.end());
117  return std::string(pchCommand.data(),
118  pchCommand.data() +
119  strnlen(pchCommand.data(), COMMAND_SIZE));
120 }
121 
122 static bool
124  const CMessageHeader::MessageMagic &magic) {
125  // Check start string
126  if (memcmp(std::begin(header.pchMessageStart), std::begin(magic),
128  return false;
129  }
130 
131  // Check the command string for errors
132  for (const char *p1 = header.pchCommand.data();
133  p1 < header.pchCommand.data() + CMessageHeader::COMMAND_SIZE; p1++) {
134  if (*p1 == 0) {
135  // Must be all zeros after the first zero
136  for (; p1 < header.pchCommand.data() + CMessageHeader::COMMAND_SIZE;
137  p1++) {
138  if (*p1 != 0) {
139  return false;
140  }
141  }
142  } else if (*p1 < ' ' || *p1 > 0x7E) {
143  return false;
144  }
145  }
146 
147  return true;
148 }
149 
150 bool CMessageHeader::IsValid(const Config &config) const {
151  // Check start string
152  if (!CheckHeaderMagicAndCommand(*this,
153  config.GetChainParams().NetMagic())) {
154  return false;
155  }
156 
157  // Message size
158  if (IsOversized(config)) {
159  LogPrintf("CMessageHeader::IsValid(): (%s, %u bytes) is oversized\n",
161  return false;
162  }
163 
164  return true;
165 }
166 
175  // Check start string
176  if (!CheckHeaderMagicAndCommand(*this, magic)) {
177  return false;
178  }
179 
180  // Message size
182  LogPrintf(
183  "CMessageHeader::IsValidForSeeder(): (%s, %u bytes) is oversized\n",
185  return false;
186  }
187 
188  return true;
189 }
190 
191 bool CMessageHeader::IsOversized(const Config &config) const {
192  // If the message doesn't not contain a block content, check against
193  // MAX_PROTOCOL_MESSAGE_LENGTH.
196  return true;
197  }
198 
199  // Scale the maximum accepted size with the block size.
200  if (nMessageSize > 2 * config.GetMaxBlockSize()) {
201  return true;
202  }
203 
204  return false;
205 }
206 
208  if ((services & NODE_NETWORK_LIMITED) &&
211  }
212  return ServiceFlags(NODE_NETWORK);
213 }
214 
215 void SetServiceFlagsIBDCache(bool state) {
217 }
218 
219 std::string CInv::GetCommand() const {
220  std::string cmd;
221  switch (GetKind()) {
222  case MSG_TX:
223  return cmd.append(NetMsgType::TX);
224  case MSG_BLOCK:
225  return cmd.append(NetMsgType::BLOCK);
226  case MSG_FILTERED_BLOCK:
227  return cmd.append(NetMsgType::MERKLEBLOCK);
228  case MSG_CMPCT_BLOCK:
229  return cmd.append(NetMsgType::CMPCTBLOCK);
230  case MSG_AVA_PROOF:
231  return cmd.append(NetMsgType::AVAPROOF);
232  default:
233  throw std::out_of_range(
234  strprintf("CInv::GetCommand(): type=%d unknown type", type));
235  }
236 }
237 
238 std::string CInv::ToString() const {
239  try {
240  return strprintf("%s %s", GetCommand(), hash.ToString());
241  } catch (const std::out_of_range &) {
242  return strprintf("0x%08x %s", type, hash.ToString());
243  }
244 }
245 
246 const std::vector<std::string> &getAllNetMessageTypes() {
247  return allNetMessageTypesVec;
248 }
249 
255 static std::string serviceFlagToStr(const size_t bit) {
256  const uint64_t service_flag = 1ULL << bit;
257  switch (ServiceFlags(service_flag)) {
258  case NODE_NONE:
259  // impossible
260  abort();
261  case NODE_NETWORK:
262  return "NETWORK";
263  case NODE_GETUTXO:
264  return "GETUTXO";
265  case NODE_BLOOM:
266  return "BLOOM";
268  return "NETWORK_LIMITED";
270  return "COMPACT_FILTERS";
271  case NODE_AVALANCHE:
272  return "AVALANCHE";
273  default:
274  std::ostringstream stream;
275  stream.imbue(std::locale::classic());
276  stream << "UNKNOWN[";
277  stream << "2^" << bit;
278  stream << "]";
279  return stream.str();
280  }
281 }
282 
283 std::vector<std::string> serviceFlagsToStr(const uint64_t flags) {
284  std::vector<std::string> str_flags;
285 
286  for (size_t i = 0; i < sizeof(flags) * 8; ++i) {
287  if (flags & (1ULL << i)) {
288  str_flags.emplace_back(serviceFlagToStr(i));
289  }
290  }
291 
292  return str_flags;
293 }
int flags
Definition: bitcoin-tx.cpp:533
const CMessageHeader::MessageMagic & NetMagic() const
Definition: chainparams.h:88
uint32_t GetKind() const
Definition: protocol.h:597
std::string ToString() const
Definition: protocol.cpp:238
std::string GetCommand() const
Definition: protocol.cpp:219
uint32_t type
Definition: protocol.h:582
uint256 hash
Definition: protocol.h:583
Message header.
Definition: protocol.h:34
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:174
bool IsValid(const Config &config) const
Definition: protocol.cpp:150
std::array< char, COMMAND_SIZE > pchCommand
Definition: protocol.h:70
static constexpr size_t CHECKSUM_SIZE
Definition: protocol.h:39
MessageMagic pchMessageStart
Definition: protocol.h:69
bool IsOversized(const Config &config) const
Definition: protocol.cpp:191
uint8_t pchChecksum[CHECKSUM_SIZE]
Definition: protocol.h:72
static constexpr size_t MESSAGE_START_SIZE
Definition: protocol.h:36
std::string GetCommand() const
Definition: protocol.cpp:115
CMessageHeader(const MessageMagic &pchMessageStartIn)
Definition: protocol.cpp:87
static constexpr size_t COMMAND_SIZE
Definition: protocol.h:37
uint32_t nMessageSize
Definition: protocol.h:71
std::array< uint8_t, MESSAGE_START_SIZE > MessageMagic
Definition: protocol.h:46
Definition: config.h:17
virtual uint64_t GetMaxBlockSize() const =0
virtual const CChainParams & GetChainParams() const =0
std::string ToString() const
Definition: uint256.h:78
#define LogPrintf(...)
Definition: logging.h:206
Bitcoin protocol message types.
Definition: protocol.cpp:16
bool IsBlockLike(const std::string &strCommand)
Indicate if the message is used to transmit the content of a block.
Definition: protocol.cpp:59
const char * FILTERLOAD
The filterload message tells the receiving peer to filter all relayed transactions and requested merk...
Definition: protocol.cpp:35
const char * CFHEADERS
cfheaders is a response to a getcfheaders request containing a filter header and a vector of filter h...
Definition: protocol.cpp:47
const char * AVAPROOFSREQ
Request for missing avalanche proofs after an avaproofs message has been processed.
Definition: protocol.cpp:57
const char * CFILTER
cfilter is a response to a getcfilters request containing a single compact filter.
Definition: protocol.cpp:45
const char * BLOCK
The block message transmits a single serialized block.
Definition: protocol.cpp:29
const char * FILTERCLEAR
The filterclear message tells the receiving peer to remove a previously-set bloom filter.
Definition: protocol.cpp:37
const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
Definition: protocol.cpp:28
const char * ADDRV2
The addrv2 message relays connection information for peers on the network just like the addr message,...
Definition: protocol.cpp:20
const char * SENDHEADERS
Indicates that a node prefers to receive new block announcements via a "headers" message rather than ...
Definition: protocol.cpp:38
const char * AVAPROOFS
The avaproofs message the proof short ids of all the valid proofs that we know.
Definition: protocol.cpp:56
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:33
const char * GETAVAPROOFS
The getavaproofs message requests an avaproofs message that provides the proof short ids of all the v...
Definition: protocol.cpp:55
const char * SENDCMPCT
Contains a 1-byte bool and 8-byte LE version number.
Definition: protocol.cpp:40
const char * GETADDR
The getaddr message requests an addr message from the receiving node, preferably one with lots of IP ...
Definition: protocol.cpp:30
const char * GETCFCHECKPT
getcfcheckpt requests evenly spaced compact filter headers, enabling parallelized download and valida...
Definition: protocol.cpp:48
const char * NOTFOUND
The notfound message is a reply to a getdata message which requested an object the receiving node doe...
Definition: protocol.cpp:34
const char * GETAVAADDR
The getavaaddr message requests an addr message from the receiving node, containing IP addresses of t...
Definition: protocol.cpp:54
const char * CMPCTBLOCK
Contains a CBlockHeaderAndShortTxIDs object - providing a header and list of "short txids".
Definition: protocol.cpp:41
const char * MEMPOOL
The mempool message requests the TXIDs of transactions that the receiving node has verified as valid ...
Definition: protocol.cpp:31
const char * GETCFILTERS
getcfilters requests compact filters for a range of blocks.
Definition: protocol.cpp:44
const char * TX
The tx message transmits a single transaction.
Definition: protocol.cpp:27
const char * AVAHELLO
Contains a delegation and a signature.
Definition: protocol.cpp:50
const char * FILTERADD
The filteradd message tells the receiving peer to add a single element to a previously-set bloom filt...
Definition: protocol.cpp:36
const char * ADDR
The addr (IP address) message relays connection information for peers on the network.
Definition: protocol.cpp:19
const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
Definition: protocol.cpp:17
const char * GETBLOCKS
The getblocks message requests an inv message that provides block header hashes starting from a parti...
Definition: protocol.cpp:25
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:39
const char * GETHEADERS
The getheaders message requests a headers message that provides block headers starting from a particu...
Definition: protocol.cpp:26
const char * AVARESPONSE
Contains an avalanche::Response.
Definition: protocol.cpp:52
const char * GETDATA
The getdata message requests one or more data objects from another node.
Definition: protocol.cpp:23
const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
Definition: protocol.cpp:18
const char * BLOCKTXN
Contains a BlockTransactions.
Definition: protocol.cpp:43
const char * GETCFHEADERS
getcfheaders requests a compact filter header and the filter hashes for a range of blocks,...
Definition: protocol.cpp:46
const char * SENDADDRV2
The sendaddrv2 message signals support for receiving ADDRV2 messages (BIP155).
Definition: protocol.cpp:21
const char * PING
The ping message is sent periodically to help confirm that the receiving peer is still connected.
Definition: protocol.cpp:32
const char * AVAPOLL
Contains an avalanche::Poll.
Definition: protocol.cpp:51
const char * MERKLEBLOCK
The merkleblock message is a reply to a getdata message which requested a block using the inventory t...
Definition: protocol.cpp:24
const char * AVAPROOF
Contains an avalanche::Proof.
Definition: protocol.cpp:53
const char * CFCHECKPT
cfcheckpt is a response to a getcfcheckpt request containing a vector of evenly spaced filter headers...
Definition: protocol.cpp:49
const char * GETBLOCKTXN
Contains a BlockTransactionsRequest Peer should respond with "blocktxn" message.
Definition: protocol.cpp:42
const char * INV
The inv message (inventory message) transmits one or more inventories of objects known to the transmi...
Definition: protocol.cpp:22
void SetServiceFlagsIBDCache(bool state)
Set the current IBD status in order to figure out the desirable service flags.
Definition: protocol.cpp:215
ServiceFlags GetDesirableServiceFlags(ServiceFlags services)
Gets the set of service flags which are "desirable" for a given peer.
Definition: protocol.cpp:207
const std::vector< std::string > & getAllNetMessageTypes()
Get a vector of all valid message types (see above)
Definition: protocol.cpp:246
static std::atomic< bool > g_initial_block_download_completed(false)
static const std::vector< std::string > allNetMessageTypesVec(std::begin(allNetMessageTypes), std::end(allNetMessageTypes))
static std::string serviceFlagToStr(const size_t bit)
Convert a service flag (NODE_*) to a human readable string.
Definition: protocol.cpp:255
std::vector< std::string > serviceFlagsToStr(const uint64_t flags)
Convert service flags (a bitmask of NODE_*) to human readable strings.
Definition: protocol.cpp:283
static bool CheckHeaderMagicAndCommand(const CMessageHeader &header, const CMessageHeader::MessageMagic &magic)
Definition: protocol.cpp:123
static const std::string allNetMessageTypes[]
All known message types.
Definition: protocol.cpp:70
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (Currently 2MB).
Definition: protocol.h:25
@ MSG_TX
Definition: protocol.h:565
@ MSG_FILTERED_BLOCK
Defined in BIP37.
Definition: protocol.h:569
@ MSG_AVA_PROOF
Definition: protocol.h:572
@ MSG_BLOCK
Definition: protocol.h:566
@ MSG_CMPCT_BLOCK
Defined in BIP152.
Definition: protocol.h:571
ServiceFlags
nServices flags.
Definition: protocol.h:335
@ NODE_NONE
Definition: protocol.h:338
@ NODE_GETUTXO
Definition: protocol.h:347
@ NODE_NETWORK_LIMITED
Definition: protocol.h:365
@ NODE_BLOOM
Definition: protocol.h:352
@ NODE_NETWORK
Definition: protocol.h:342
@ NODE_COMPACT_FILTERS
Definition: protocol.h:360
@ NODE_AVALANCHE
Definition: protocol.h:380
size_t strnlen(const char *start, size_t max_len)
Definition: strnlen.cpp:12
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
assert(!tx.IsCoinBase())