Bitcoin ABC  0.24.7
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 #include <atomic>
14 
15 static std::atomic<bool> g_initial_block_download_completed(false);
16 
17 namespace NetMsgType {
18 const char *VERSION = "version";
19 const char *VERACK = "verack";
20 const char *ADDR = "addr";
21 const char *ADDRV2 = "addrv2";
22 const char *SENDADDRV2 = "sendaddrv2";
23 const char *INV = "inv";
24 const char *GETDATA = "getdata";
25 const char *MERKLEBLOCK = "merkleblock";
26 const char *GETBLOCKS = "getblocks";
27 const char *GETHEADERS = "getheaders";
28 const char *TX = "tx";
29 const char *HEADERS = "headers";
30 const char *BLOCK = "block";
31 const char *GETADDR = "getaddr";
32 const char *MEMPOOL = "mempool";
33 const char *PING = "ping";
34 const char *PONG = "pong";
35 const char *NOTFOUND = "notfound";
36 const char *FILTERLOAD = "filterload";
37 const char *FILTERADD = "filteradd";
38 const char *FILTERCLEAR = "filterclear";
39 const char *SENDHEADERS = "sendheaders";
40 const char *FEEFILTER = "feefilter";
41 const char *SENDCMPCT = "sendcmpct";
42 const char *CMPCTBLOCK = "cmpctblock";
43 const char *GETBLOCKTXN = "getblocktxn";
44 const char *BLOCKTXN = "blocktxn";
45 const char *GETCFILTERS = "getcfilters";
46 const char *CFILTER = "cfilter";
47 const char *GETCFHEADERS = "getcfheaders";
48 const char *CFHEADERS = "cfheaders";
49 const char *GETCFCHECKPT = "getcfcheckpt";
50 const char *CFCHECKPT = "cfcheckpt";
51 const char *AVAHELLO = "avahello";
52 const char *AVAPOLL = "avapoll";
53 const char *AVARESPONSE = "avaresponse";
54 const char *AVAPROOF = "avaproof";
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),
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),
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",
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
179  LogPrintf(
180  "CMessageHeader::IsValidForSeeder(): (%s, %u bytes) is oversized\n",
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.
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) &&
208  }
209  return ServiceFlags(NODE_NETWORK);
210 }
211 
212 void SetServiceFlagsIBDCache(bool state) {
214 }
215 
216 std::string CInv::GetCommand() const {
217  std::string cmd;
218  switch (GetKind()) {
219  case MSG_TX:
220  return cmd.append(NetMsgType::TX);
221  case MSG_BLOCK:
222  return cmd.append(NetMsgType::BLOCK);
223  case MSG_FILTERED_BLOCK:
224  return cmd.append(NetMsgType::MERKLEBLOCK);
225  case MSG_CMPCT_BLOCK:
226  return cmd.append(NetMsgType::CMPCTBLOCK);
227  case MSG_AVA_PROOF:
228  return cmd.append(NetMsgType::AVAPROOF);
229  default:
230  throw std::out_of_range(
231  strprintf("CInv::GetCommand(): type=%d unknown type", type));
232  }
233 }
234 
235 std::string CInv::ToString() const {
236  try {
237  return strprintf("%s %s", GetCommand(), hash.ToString());
238  } catch (const std::out_of_range &) {
239  return strprintf("0x%08x %s", type, hash.ToString());
240  }
241 }
242 
243 const std::vector<std::string> &getAllNetMessageTypes() {
244  return allNetMessageTypesVec;
245 }
246 
252 static std::string serviceFlagToStr(const size_t bit) {
253  const uint64_t service_flag = 1ULL << bit;
254  switch (ServiceFlags(service_flag)) {
255  case NODE_NONE:
256  // impossible
257  abort();
258  case NODE_NETWORK:
259  return "NETWORK";
260  case NODE_GETUTXO:
261  return "GETUTXO";
262  case NODE_BLOOM:
263  return "BLOOM";
265  return "NETWORK_LIMITED";
267  return "COMPACT_FILTERS";
268  case NODE_AVALANCHE:
269  return "AVALANCHE";
270  default:
271  std::ostringstream stream;
272  stream.imbue(std::locale::classic());
273  stream << "UNKNOWN[";
274  stream << "2^" << bit;
275  stream << "]";
276  return stream.str();
277  }
278 }
279 
280 std::vector<std::string> serviceFlagsToStr(const uint64_t flags) {
281  std::vector<std::string> str_flags;
282 
283  for (size_t i = 0; i < sizeof(flags) * 8; ++i) {
284  if (flags & (1ULL << i)) {
285  str_flags.emplace_back(serviceFlagToStr(i));
286  }
287  }
288 
289  return str_flags;
290 }
Config::GetMaxBlockSize
virtual uint64_t GetMaxBlockSize() const =0
SetServiceFlagsIBDCache
void SetServiceFlagsIBDCache(bool state)
Set the current IBD status in order to figure out the desirable service flags.
Definition: protocol.cpp:212
NetMsgType
Bitcoin protocol message types.
Definition: protocol.cpp:17
MSG_FILTERED_BLOCK
@ MSG_FILTERED_BLOCK
Defined in BIP37.
Definition: protocol.h:481
CMessageHeader::nMessageSize
uint32_t nMessageSize
Definition: protocol.h:74
flags
int flags
Definition: bitcoin-tx.cpp:532
CMessageHeader::pchMessageStart
MessageMagic pchMessageStart
Definition: protocol.h:72
NetMsgType::PING
const char * PING
The ping message is sent periodically to help confirm that the receiving peer is still connected.
Definition: protocol.cpp:33
NetMsgType::FILTERLOAD
const char * FILTERLOAD
The filterload message tells the receiving peer to filter all relayed transactions and requested merk...
Definition: protocol.cpp:36
GetDesirableServiceFlags
ServiceFlags GetDesirableServiceFlags(ServiceFlags services)
Gets the set of service flags which are "desirable" for a given peer.
Definition: protocol.cpp:204
NetMsgType::SENDADDRV2
const char * SENDADDRV2
The sendaddrv2 message signals support for receiving ADDRV2 messages (BIP155).
Definition: protocol.cpp:22
MSG_TX
@ MSG_TX
Definition: protocol.h:477
ServiceFlags
ServiceFlags
nServices flags.
Definition: protocol.h:314
CMessageHeader::GetCommand
std::string GetCommand() const
Definition: protocol.cpp:112
NODE_NETWORK_LIMITED
@ NODE_NETWORK_LIMITED
Definition: protocol.h:344
CMessageHeader::CMessageHeader
CMessageHeader(const MessageMagic &pchMessageStartIn)
Definition: protocol.cpp:84
NODE_NETWORK
@ NODE_NETWORK
Definition: protocol.h:321
NetMsgType::CFHEADERS
const char * CFHEADERS
cfheaders is a response to a getcfheaders request containing a filter header and a vector of filter h...
Definition: protocol.cpp:48
chainparams.h
NetMsgType::PONG
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:34
NODE_COMPACT_FILTERS
@ NODE_COMPACT_FILTERS
Definition: protocol.h:339
NetMsgType::AVAHELLO
const char * AVAHELLO
Contains a delegation and a signature.
Definition: protocol.cpp:51
NetMsgType::SENDCMPCT
const char * SENDCMPCT
Contains a 1-byte bool and 8-byte LE version number.
Definition: protocol.cpp:41
NetMsgType::ADDRV2
const char * ADDRV2
The addrv2 message relays connection information for peers on the network just like the addr message,...
Definition: protocol.cpp:21
strencodings.h
Config
Definition: config.h:17
protocol.h
NetMsgType::INV
const char * INV
The inv message (inventory message) transmits one or more inventories of objects known to the transmi...
Definition: protocol.cpp:23
NetMsgType::GETHEADERS
const char * GETHEADERS
The getheaders message requests a headers message that provides block headers starting from a particu...
Definition: protocol.cpp:27
NODE_AVALANCHE
@ NODE_AVALANCHE
Definition: protocol.h:359
NetMsgType::CFILTER
const char * CFILTER
cfilter is a response to a getcfilters request containing a single compact filter.
Definition: protocol.cpp:46
NetMsgType::FEEFILTER
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:40
NetMsgType::HEADERS
const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
Definition: protocol.cpp:29
CMessageHeader::IsOversized
bool IsOversized(const Config &config) const
Definition: protocol.cpp:188
NetMsgType::GETCFCHECKPT
const char * GETCFCHECKPT
getcfcheckpt requests evenly spaced compact filter headers, enabling parallelized download and valida...
Definition: protocol.cpp:49
NODE_GETUTXO
@ NODE_GETUTXO
Definition: protocol.h:326
CMessageHeader::COMMAND_SIZE
static constexpr size_t COMMAND_SIZE
Definition: protocol.h:40
NODE_BLOOM
@ NODE_BLOOM
Definition: protocol.h:331
allNetMessageTypesVec
static const std::vector< std::string > allNetMessageTypesVec(allNetMessageTypes, allNetMessageTypes+ARRAYLEN(allNetMessageTypes))
CMessageHeader::pchCommand
std::array< char, COMMAND_SIZE > pchCommand
Definition: protocol.h:73
strnlen
size_t strnlen(const char *start, size_t max_len)
Definition: strnlen.cpp:12
NetMsgType::GETCFHEADERS
const char * GETCFHEADERS
getcfheaders requests a compact filter header and the filter hashes for a range of blocks,...
Definition: protocol.cpp:47
MAX_PROTOCOL_MESSAGE_LENGTH
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH
Maximum length of incoming protocol messages (Currently 2MB).
Definition: protocol.h:28
NetMsgType::FILTERCLEAR
const char * FILTERCLEAR
The filterclear message tells the receiving peer to remove a previously-set bloom filter.
Definition: protocol.cpp:38
base_blob::ToString
std::string ToString() const
Definition: uint256.h:78
NetMsgType::SENDHEADERS
const char * SENDHEADERS
Indicates that a node prefers to receive new block announcements via a "headers" message rather than ...
Definition: protocol.cpp:39
CMessageHeader::MESSAGE_START_SIZE
static constexpr size_t MESSAGE_START_SIZE
Definition: protocol.h:39
NetMsgType::GETBLOCKS
const char * GETBLOCKS
The getblocks message requests an inv message that provides block header hashes starting from a parti...
Definition: protocol.cpp:26
NetMsgType::GETDATA
const char * GETDATA
The getdata message requests one or more data objects from another node.
Definition: protocol.cpp:24
CInv::GetCommand
std::string GetCommand() const
Definition: protocol.cpp:216
NetMsgType::NOTFOUND
const char * NOTFOUND
The notfound message is a reply to a getdata message which requested an object the receiving node doe...
Definition: protocol.cpp:35
NODE_NONE
@ NODE_NONE
Definition: protocol.h:317
CMessageHeader::CHECKSUM_SIZE
static constexpr size_t CHECKSUM_SIZE
Definition: protocol.h:42
NetMsgType::ADDR
const char * ADDR
The addr (IP address) message relays connection information for peers on the network.
Definition: protocol.cpp:20
NetMsgType::BLOCK
const char * BLOCK
The block message transmits a single serialized block.
Definition: protocol.cpp:30
CMessageHeader::IsValid
bool IsValid(const Config &config) const
Definition: protocol.cpp:147
MSG_AVA_PROOF
@ MSG_AVA_PROOF
Definition: protocol.h:484
system.h
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
NetMsgType::MEMPOOL
const char * MEMPOOL
The mempool message requests the TXIDs of transactions that the receiving node has verified as valid ...
Definition: protocol.cpp:32
CMessageHeader
Message header.
Definition: protocol.h:37
NetMsgType::TX
const char * TX
The tx message transmits a single transaction.
Definition: protocol.cpp:28
CInv::hash
uint256 hash
Definition: protocol.h:495
CheckHeaderMagicAndCommand
static bool CheckHeaderMagicAndCommand(const CMessageHeader &header, const CMessageHeader::MessageMagic &magic)
Definition: protocol.cpp:120
Config::GetChainParams
virtual const CChainParams & GetChainParams() const =0
NetMsgType::AVARESPONSE
const char * AVARESPONSE
Contains an avalanche::Response.
Definition: protocol.cpp:53
ARRAYLEN
#define ARRAYLEN(array)
Utilities for converting data from/to strings.
Definition: strencodings.h:20
NetMsgType::CMPCTBLOCK
const char * CMPCTBLOCK
Contains a CBlockHeaderAndShortTxIDs object - providing a header and list of "short txids".
Definition: protocol.cpp:42
CMessageHeader::MessageMagic
std::array< uint8_t, MESSAGE_START_SIZE > MessageMagic
Definition: protocol.h:49
getAllNetMessageTypes
const std::vector< std::string > & getAllNetMessageTypes()
Get a vector of all valid message types (see above)
Definition: protocol.cpp:243
NetMsgType::VERACK
const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
Definition: protocol.cpp:19
config.h
NetMsgType::AVAPROOF
const char * AVAPROOF
Contains an avalanche::Proof.
Definition: protocol.cpp:54
NetMsgType::FILTERADD
const char * FILTERADD
The filteradd message tells the receiving peer to add a single element to a previously-set bloom filt...
Definition: protocol.cpp:37
NetMsgType::GETBLOCKTXN
const char * GETBLOCKTXN
Contains a BlockTransactionsRequest Peer should respond with "blocktxn" message.
Definition: protocol.cpp:43
NetMsgType::CFCHECKPT
const char * CFCHECKPT
cfcheckpt is a response to a getcfcheckpt request containing a vector of evenly spaced filter headers...
Definition: protocol.cpp:50
MSG_CMPCT_BLOCK
@ MSG_CMPCT_BLOCK
Defined in BIP152.
Definition: protocol.h:483
g_initial_block_download_completed
static std::atomic< bool > g_initial_block_download_completed(false)
NetMsgType::VERSION
const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
Definition: protocol.cpp:18
CMessageHeader::pchChecksum
uint8_t pchChecksum[CHECKSUM_SIZE]
Definition: protocol.h:75
serviceFlagToStr
static std::string serviceFlagToStr(const size_t bit)
Convert a service flag (NODE_*) to a human readable string.
Definition: protocol.cpp:252
CChainParams::NetMagic
const CMessageHeader::MessageMagic & NetMagic() const
Definition: chainparams.h:61
CMessageHeader::IsValidWithoutConfig
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
NetMsgType::BLOCKTXN
const char * BLOCKTXN
Contains a BlockTransactions.
Definition: protocol.cpp:44
MSG_BLOCK
@ MSG_BLOCK
Definition: protocol.h:478
allNetMessageTypes
static const std::string allNetMessageTypes[]
All known message types.
Definition: protocol.cpp:67
NetMsgType::IsBlockLike
bool IsBlockLike(const std::string &strCommand)
Indicate if the message is used to transmit the content of a block.
Definition: protocol.cpp:56
serviceFlagsToStr
std::vector< std::string > serviceFlagsToStr(const uint64_t flags)
Convert service flags (a bitmask of NODE_*) to human readable strings.
Definition: protocol.cpp:280
CInv::type
uint32_t type
Definition: protocol.h:494
LogPrintf
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:175
CInv::ToString
std::string ToString() const
Definition: protocol.cpp:235
NetMsgType::GETCFILTERS
const char * GETCFILTERS
getcfilters requests compact filters for a range of blocks.
Definition: protocol.cpp:45
NetMsgType::AVAPOLL
const char * AVAPOLL
Contains an avalanche::Poll.
Definition: protocol.cpp:52
NetMsgType::GETADDR
const char * GETADDR
The getaddr message requests an addr message from the receiving node, preferably one with lots of IP ...
Definition: protocol.cpp:31
NetMsgType::MERKLEBLOCK
const char * MERKLEBLOCK
The merkleblock message is a reply to a getdata message which requested a block using the inventory t...
Definition: protocol.cpp:25
CInv::GetKind
uint32_t GetKind() const
Definition: protocol.h:509