Bitcoin Core  0.20.99
P2P Digital Currency
protocol.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 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 <util/strencodings.h>
9 #include <util/system.h>
10 
11 static std::atomic<bool> g_initial_block_download_completed(false);
12 
13 namespace NetMsgType {
14 const char *VERSION="version";
15 const char *VERACK="verack";
16 const char *ADDR="addr";
17 const char *INV="inv";
18 const char *GETDATA="getdata";
19 const char *MERKLEBLOCK="merkleblock";
20 const char *GETBLOCKS="getblocks";
21 const char *GETHEADERS="getheaders";
22 const char *TX="tx";
23 const char *HEADERS="headers";
24 const char *BLOCK="block";
25 const char *GETADDR="getaddr";
26 const char *MEMPOOL="mempool";
27 const char *PING="ping";
28 const char *PONG="pong";
29 const char *NOTFOUND="notfound";
30 const char *FILTERLOAD="filterload";
31 const char *FILTERADD="filteradd";
32 const char *FILTERCLEAR="filterclear";
33 const char *SENDHEADERS="sendheaders";
34 const char *FEEFILTER="feefilter";
35 const char *SENDCMPCT="sendcmpct";
36 const char *CMPCTBLOCK="cmpctblock";
37 const char *GETBLOCKTXN="getblocktxn";
38 const char *BLOCKTXN="blocktxn";
39 const char *GETCFILTERS="getcfilters";
40 const char *CFILTER="cfilter";
41 const char *GETCFHEADERS="getcfheaders";
42 const char *CFHEADERS="cfheaders";
43 const char *GETCFCHECKPT="getcfcheckpt";
44 const char *CFCHECKPT="cfcheckpt";
45 const char *WTXIDRELAY="wtxidrelay";
46 } // namespace NetMsgType
47 
51 const static std::string allNetMessageTypes[] = {
84 };
86 
87 CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn)
88 {
89  memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);
90  memset(pchCommand, 0, sizeof(pchCommand));
91  nMessageSize = -1;
92  memset(pchChecksum, 0, CHECKSUM_SIZE);
93 }
94 
95 CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn)
96 {
97  memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);
98 
99  // Copy the command name, zero-padding to COMMAND_SIZE bytes
100  size_t i = 0;
101  for (; i < COMMAND_SIZE && pszCommand[i] != 0; ++i) pchCommand[i] = pszCommand[i];
102  assert(pszCommand[i] == 0); // Assert that the command name passed in is not longer than COMMAND_SIZE
103  for (; i < COMMAND_SIZE; ++i) pchCommand[i] = 0;
104 
105  nMessageSize = nMessageSizeIn;
106  memset(pchChecksum, 0, CHECKSUM_SIZE);
107 }
108 
109 std::string CMessageHeader::GetCommand() const
110 {
111  return std::string(pchCommand, pchCommand + strnlen(pchCommand, COMMAND_SIZE));
112 }
113 
114 bool CMessageHeader::IsValid(const MessageStartChars& pchMessageStartIn) const
115 {
116  // Check start string
117  if (memcmp(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE) != 0)
118  return false;
119 
120  // Check the command string for errors
121  for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
122  {
123  if (*p1 == 0)
124  {
125  // Must be all zeros after the first zero
126  for (; p1 < pchCommand + COMMAND_SIZE; p1++)
127  if (*p1 != 0)
128  return false;
129  }
130  else if (*p1 < ' ' || *p1 > 0x7E)
131  return false;
132  }
133 
134  // Message size
135  if (nMessageSize > MAX_SIZE)
136  {
137  LogPrintf("CMessageHeader::IsValid(): (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand(), nMessageSize);
138  return false;
139  }
140 
141  return true;
142 }
143 
144 
147  return ServiceFlags(NODE_NETWORK_LIMITED | NODE_WITNESS);
148  }
150 }
151 
152 void SetServiceFlagsIBDCache(bool state) {
154 }
155 
157 {
158  type = 0;
159  hash.SetNull();
160 }
161 
162 CInv::CInv(uint32_t typeIn, const uint256& hashIn) : type(typeIn), hash(hashIn) {}
163 
164 bool operator<(const CInv& a, const CInv& b)
165 {
166  return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
167 }
168 
169 std::string CInv::GetCommand() const
170 {
171  std::string cmd;
172  if (type & MSG_WITNESS_FLAG)
173  cmd.append("witness-");
174  int masked = type & MSG_TYPE_MASK;
175  switch (masked)
176  {
177  case MSG_TX: return cmd.append(NetMsgType::TX);
178  // WTX is not a message type, just an inv type
179  case MSG_WTX: return cmd.append("wtx");
180  case MSG_BLOCK: return cmd.append(NetMsgType::BLOCK);
181  case MSG_FILTERED_BLOCK: return cmd.append(NetMsgType::MERKLEBLOCK);
182  case MSG_CMPCT_BLOCK: return cmd.append(NetMsgType::CMPCTBLOCK);
183  default:
184  throw std::out_of_range(strprintf("CInv::GetCommand(): type=%d unknown type", type));
185  }
186 }
187 
188 std::string CInv::ToString() const
189 {
190  try {
191  return strprintf("%s %s", GetCommand(), hash.ToString());
192  } catch(const std::out_of_range &) {
193  return strprintf("0x%08x %s", type, hash.ToString());
194  }
195 }
196 
197 const std::vector<std::string> &getAllNetMessageTypes()
198 {
199  return allNetMessageTypesVec;
200 }
201 
207 static std::string serviceFlagToStr(size_t bit)
208 {
209  const uint64_t service_flag = 1ULL << bit;
210  switch ((ServiceFlags)service_flag) {
211  case NODE_NONE: abort(); // impossible
212  case NODE_NETWORK: return "NETWORK";
213  case NODE_GETUTXO: return "GETUTXO";
214  case NODE_BLOOM: return "BLOOM";
215  case NODE_WITNESS: return "WITNESS";
216  case NODE_COMPACT_FILTERS: return "COMPACT_FILTERS";
217  case NODE_NETWORK_LIMITED: return "NETWORK_LIMITED";
218  // Not using default, so we get warned when a case is missing
219  }
220 
221  std::ostringstream stream;
222  stream.imbue(std::locale::classic());
223  stream << "UNKNOWN[";
224  stream << "2^" << bit;
225  stream << "]";
226  return stream.str();
227 }
228 
229 std::vector<std::string> serviceFlagsToStr(uint64_t flags)
230 {
231  std::vector<std::string> str_flags;
232 
233  for (size_t i = 0; i < sizeof(flags) * 8; ++i) {
234  if (flags & (1ULL << i)) {
235  str_flags.emplace_back(serviceFlagToStr(i));
236  }
237  }
238 
239  return str_flags;
240 }
241 
242 GenTxid ToGenTxid(const CInv& inv)
243 {
244  assert(inv.IsGenTxMsg());
245  return {inv.IsMsgWtx(), inv.hash};
246 }
const char * GETCFILTERS
getcfilters requests compact filters for a range of blocks.
Definition: protocol.cpp:39
bool IsMsgWtx() const
Definition: protocol.h:423
const char * PING
The ping message is sent periodically to help confirm that the receiving peer is still connected...
Definition: protocol.cpp:27
const char * FILTERLOAD
The filterload message tells the receiving peer to filter all relayed transactions and requested merk...
Definition: protocol.cpp:30
const char * MERKLEBLOCK
The merkleblock message is a reply to a getdata message which requested a block using the inventory t...
Definition: protocol.cpp:19
const char * BLOCKTXN
Contains a BlockTransactions.
Definition: protocol.cpp:38
static const std::string allNetMessageTypes[]
All known message types.
Definition: protocol.cpp:51
ServiceFlags
nServices flags
Definition: protocol.h:257
std::string GetCommand() const
Definition: protocol.cpp:169
std::string ToString() const
Definition: protocol.cpp:188
const char * GETADDR
The getaddr message requests an addr message from the receiving node, preferably one with lots of IP ...
Definition: protocol.cpp:25
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
inv message data
Definition: protocol.h:407
const char * SENDCMPCT
Contains a 1-byte bool and 8-byte LE version number.
Definition: protocol.cpp:35
static const std::vector< std::string > allNetMessageTypesVec(allNetMessageTypes, allNetMessageTypes+ARRAYLEN(allNetMessageTypes))
#define ARRAYLEN(array)
Utilities for converting data from/to strings.
Definition: strencodings.h:20
const char * CFHEADERS
cfheaders is a response to a getcfheaders request containing a filter header and a vector of filter h...
Definition: protocol.cpp:42
Defined in BIP152.
Definition: protocol.h:398
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:166
void SetServiceFlagsIBDCache(bool state)
Set the current IBD status in order to figure out the desirable service flags.
Definition: protocol.cpp:152
CMessageHeader(const MessageStartChars &pchMessageStartIn)
Definition: protocol.cpp:87
std::vector< std::string > serviceFlagsToStr(uint64_t flags)
Convert service flags (a bitmask of NODE_*) to human readable strings.
Definition: protocol.cpp:229
const uint32_t MSG_WITNESS_FLAG
getdata message type flags
Definition: protocol.h:384
const char * CFILTER
cfilter is a response to a getcfilters request containing a single compact filter.
Definition: protocol.cpp:40
const uint32_t MSG_TYPE_MASK
Definition: protocol.h:385
std::string GetCommand() const
Definition: protocol.cpp:109
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:28
bool IsValid(const MessageStartChars &messageStart) const
Definition: protocol.cpp:114
const char * WTXIDRELAY
Indicates that a node prefers to relay transactions via wtxid, rather than txid.
Definition: protocol.cpp:45
const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
Definition: protocol.cpp:23
const char * GETCFCHECKPT
getcfcheckpt requests evenly spaced compact filter headers, enabling parallelized download and valida...
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:17
static std::atomic< bool > g_initial_block_download_completed(false)
GenTxid ToGenTxid(const CInv &inv)
Convert a TX/WITNESS_TX/WTX CInv to a GenTxid.
Definition: protocol.cpp:242
const char * GETHEADERS
The getheaders message requests a headers message that provides block headers starting from a particu...
Definition: protocol.cpp:21
Bitcoin protocol message types.
Definition: protocol.cpp:13
const char * SENDHEADERS
Indicates that a node prefers to receive new block announcements via a "headers" message rather than ...
Definition: protocol.cpp:33
const char * MEMPOOL
The mempool message requests the TXIDs of transactions that the receiving node has verified as valid ...
Definition: protocol.cpp:26
bool IsGenTxMsg() const
Definition: protocol.h:429
const std::vector< std::string > & getAllNetMessageTypes()
Definition: protocol.cpp:197
uint256 hash
Definition: protocol.h:439
const char * ADDR
The addr (IP address) message relays connection information for peers on the network.
Definition: protocol.cpp:16
const char * FILTERCLEAR
The filterclear message tells the receiving peer to remove a previously-set bloom filter...
Definition: protocol.cpp:32
std::string ToString() const
Definition: uint256.cpp:64
const char * NOTFOUND
The notfound message is a reply to a getdata message which requested an object the receiving node doe...
Definition: protocol.cpp:29
const char * BLOCK
The block message transmits a single serialized block.
Definition: protocol.cpp:24
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:34
const char * GETCFHEADERS
getcfheaders requests a compact filter header and the filter hashes for a range of blocks...
Definition: protocol.cpp:41
const char * GETBLOCKS
The getblocks message requests an inv message that provides block header hashes starting from a parti...
Definition: protocol.cpp:20
int flags
Definition: bitcoin-tx.cpp:506
static std::string serviceFlagToStr(size_t bit)
Convert a service flag (NODE_*) to a human readable string.
Definition: protocol.cpp:207
const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
Definition: protocol.cpp:15
256-bit opaque blob.
Definition: uint256.h:123
const char * CMPCTBLOCK
Contains a CBlockHeaderAndShortTxIDs object - providing a header and list of "short txids"...
Definition: protocol.cpp:36
static const unsigned int MAX_SIZE
Definition: serialize.h:27
const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
Definition: protocol.cpp:14
void * memcpy(void *a, const void *b, size_t c)
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:145
uint32_t type
Definition: protocol.h:438
const char * GETDATA
The getdata message requests one or more data objects from another node.
Definition: protocol.cpp:18
const char * CFCHECKPT
cfcheckpt is a response to a getcfcheckpt request containing a vector of evenly spaced filter headers...
Definition: protocol.cpp:44
CInv()
Definition: protocol.cpp:156
const char * TX
The tx message transmits a single transaction.
Definition: protocol.cpp:22
Defined in BIP37.
Definition: protocol.h:397
Defined in BIP 339.
Definition: protocol.h:395
friend bool operator<(const CInv &a, const CInv &b)
Definition: protocol.cpp:164
A generic txid reference (txid or wtxid).
Definition: transaction.h:394
const char * FILTERADD
The filteradd message tells the receiving peer to add a single element to a previously-set bloom filt...
Definition: protocol.cpp:31
const char * GETBLOCKTXN
Contains a BlockTransactionsRequest Peer should respond with "blocktxn" message.
Definition: protocol.cpp:37