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