1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 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 #ifndef __cplusplus
7 #error This header can only be compiled as C++.
8 #endif
9
10 #ifndef BITCOIN_PROTOCOL_H
11 #define BITCOIN_PROTOCOL_H
12
13 #include <netaddress.h>
14 #include <serialize.h>
15 #include <uint256.h>
16 #include <version.h>
17
18 #include <atomic>
19 #include <stdint.h>
20 #include <string>
21
22 /** Message header.
23 * (4) message start.
24 * (12) command.
25 * (4) size.
26 * (4) checksum.
27 */
28 class CMessageHeader
29 {
30 public:
31 static constexpr size_t MESSAGE_START_SIZE = 4;
32 static constexpr size_t COMMAND_SIZE = 12;
33 static constexpr size_t MESSAGE_SIZE_SIZE = 4;
34 static constexpr size_t CHECKSUM_SIZE = 4;
35 static constexpr size_t MESSAGE_SIZE_OFFSET = MESSAGE_START_SIZE + COMMAND_SIZE;
36 static constexpr size_t CHECKSUM_OFFSET = MESSAGE_SIZE_OFFSET + MESSAGE_SIZE_SIZE;
37 static constexpr size_t HEADER_SIZE = MESSAGE_START_SIZE + COMMAND_SIZE + MESSAGE_SIZE_SIZE + CHECKSUM_SIZE;
38 typedef unsigned char MessageStartChars[MESSAGE_START_SIZE];
39
40 explicit CMessageHeader(const MessageStartChars& pchMessageStartIn);
41 CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn);
42
43 std::string GetCommand() const;
44 bool IsValid(const MessageStartChars& messageStart) const;
45
46 ADD_SERIALIZE_METHODS;
47
48 template <typename Stream, typename Operation>
SerializationOp(Stream & s,Operation ser_action)49 inline void SerializationOp(Stream& s, Operation ser_action)
50 {
51 READWRITE(pchMessageStart);
52 READWRITE(pchCommand);
53 READWRITE(nMessageSize);
54 READWRITE(pchChecksum);
55 }
56
57 char pchMessageStart[MESSAGE_START_SIZE];
58 char pchCommand[COMMAND_SIZE];
59 uint32_t nMessageSize;
60 uint8_t pchChecksum[CHECKSUM_SIZE];
61 };
62
63 /**
64 * Bitcoin protocol message types. When adding new message types, don't forget
65 * to update allNetMessageTypes in protocol.cpp.
66 */
67 namespace NetMsgType {
68
69 /**
70 * The version message provides information about the transmitting node to the
71 * receiving node at the beginning of a connection.
72 * @see https://bitcoin.org/en/developer-reference#version
73 */
74 extern const char *VERSION;
75 /**
76 * The verack message acknowledges a previously-received version message,
77 * informing the connecting node that it can begin to send other messages.
78 * @see https://bitcoin.org/en/developer-reference#verack
79 */
80 extern const char *VERACK;
81 /**
82 * The addr (IP address) message relays connection information for peers on the
83 * network.
84 * @see https://bitcoin.org/en/developer-reference#addr
85 */
86 extern const char *ADDR;
87 /**
88 * The inv message (inventory message) transmits one or more inventories of
89 * objects known to the transmitting peer.
90 * @see https://bitcoin.org/en/developer-reference#inv
91 */
92 extern const char *INV;
93 /**
94 * The getdata message requests one or more data objects from another node.
95 * @see https://bitcoin.org/en/developer-reference#getdata
96 */
97 extern const char *GETDATA;
98 /**
99 * The merkleblock message is a reply to a getdata message which requested a
100 * block using the inventory type MSG_MERKLEBLOCK.
101 * @since protocol version 70001 as described by BIP37.
102 * @see https://bitcoin.org/en/developer-reference#merkleblock
103 */
104 extern const char *MERKLEBLOCK;
105 /**
106 * The getblocks message requests an inv message that provides block header
107 * hashes starting from a particular point in the block chain.
108 * @see https://bitcoin.org/en/developer-reference#getblocks
109 */
110 extern const char *GETBLOCKS;
111 /**
112 * The getheaders message requests a headers message that provides block
113 * headers starting from a particular point in the block chain.
114 * @since protocol version 31800.
115 * @see https://bitcoin.org/en/developer-reference#getheaders
116 */
117 extern const char *GETHEADERS;
118 /**
119 * The tx message transmits a single transaction.
120 * @see https://bitcoin.org/en/developer-reference#tx
121 */
122 extern const char *TX;
123 /**
124 * The headers message sends one or more block headers to a node which
125 * previously requested certain headers with a getheaders message.
126 * @since protocol version 31800.
127 * @see https://bitcoin.org/en/developer-reference#headers
128 */
129 extern const char *HEADERS;
130 /**
131 * The block message transmits a single serialized block.
132 * @see https://bitcoin.org/en/developer-reference#block
133 */
134 extern const char *BLOCK;
135 /**
136 * The getaddr message requests an addr message from the receiving node,
137 * preferably one with lots of IP addresses of other receiving nodes.
138 * @see https://bitcoin.org/en/developer-reference#getaddr
139 */
140 extern const char *GETADDR;
141 /**
142 * The mempool message requests the TXIDs of transactions that the receiving
143 * node has verified as valid but which have not yet appeared in a block.
144 * @since protocol version 60002.
145 * @see https://bitcoin.org/en/developer-reference#mempool
146 */
147 extern const char *MEMPOOL;
148 /**
149 * The ping message is sent periodically to help confirm that the receiving
150 * peer is still connected.
151 * @see https://bitcoin.org/en/developer-reference#ping
152 */
153 extern const char *PING;
154 /**
155 * The pong message replies to a ping message, proving to the pinging node that
156 * the ponging node is still alive.
157 * @since protocol version 60001 as described by BIP31.
158 * @see https://bitcoin.org/en/developer-reference#pong
159 */
160 extern const char *PONG;
161 /**
162 * The notfound message is a reply to a getdata message which requested an
163 * object the receiving node does not have available for relay.
164 * @since protocol version 70001.
165 * @see https://bitcoin.org/en/developer-reference#notfound
166 */
167 extern const char *NOTFOUND;
168 /**
169 * The filterload message tells the receiving peer to filter all relayed
170 * transactions and requested merkle blocks through the provided filter.
171 * @since protocol version 70001 as described by BIP37.
172 * Only available with service bit NODE_BLOOM since protocol version
173 * 70011 as described by BIP111.
174 * @see https://bitcoin.org/en/developer-reference#filterload
175 */
176 extern const char *FILTERLOAD;
177 /**
178 * The filteradd message tells the receiving peer to add a single element to a
179 * previously-set bloom filter, such as a new public key.
180 * @since protocol version 70001 as described by BIP37.
181 * Only available with service bit NODE_BLOOM since protocol version
182 * 70011 as described by BIP111.
183 * @see https://bitcoin.org/en/developer-reference#filteradd
184 */
185 extern const char *FILTERADD;
186 /**
187 * The filterclear message tells the receiving peer to remove a previously-set
188 * bloom filter.
189 * @since protocol version 70001 as described by BIP37.
190 * Only available with service bit NODE_BLOOM since protocol version
191 * 70011 as described by BIP111.
192 * @see https://bitcoin.org/en/developer-reference#filterclear
193 */
194 extern const char *FILTERCLEAR;
195 /**
196 * The reject message informs the receiving node that one of its previous
197 * messages has been rejected.
198 * @since protocol version 70002 as described by BIP61.
199 * @see https://bitcoin.org/en/developer-reference#reject
200 */
201 extern const char *REJECT;
202 /**
203 * Indicates that a node prefers to receive new block announcements via a
204 * "headers" message rather than an "inv".
205 * @since protocol version 70012 as described by BIP130.
206 * @see https://bitcoin.org/en/developer-reference#sendheaders
207 */
208 extern const char *SENDHEADERS;
209 /**
210 * The feefilter message tells the receiving peer not to inv us any txs
211 * which do not meet the specified min fee rate.
212 * @since protocol version 70013 as described by BIP133
213 */
214 extern const char *FEEFILTER;
215 /**
216 * Contains a 1-byte bool and 8-byte LE version number.
217 * Indicates that a node is willing to provide blocks via "cmpctblock" messages.
218 * May indicate that a node prefers to receive new block announcements via a
219 * "cmpctblock" message rather than an "inv", depending on message contents.
220 * @since protocol version 70014 as described by BIP 152
221 */
222 extern const char *SENDCMPCT;
223 /**
224 * Contains a CBlockHeaderAndShortTxIDs object - providing a header and
225 * list of "short txids".
226 * @since protocol version 70014 as described by BIP 152
227 */
228 extern const char *CMPCTBLOCK;
229 /**
230 * Contains a BlockTransactionsRequest
231 * Peer should respond with "blocktxn" message.
232 * @since protocol version 70014 as described by BIP 152
233 */
234 extern const char *GETBLOCKTXN;
235 /**
236 * Contains a BlockTransactions.
237 * Sent in response to a "getblocktxn" message.
238 * @since protocol version 70014 as described by BIP 152
239 */
240 extern const char *BLOCKTXN;
241 };
242
243 /* Get a vector of all valid message types (see above) */
244 const std::vector<std::string> &getAllNetMessageTypes();
245
246 /** nServices flags */
247 enum ServiceFlags : uint64_t {
248 // Nothing
249 NODE_NONE = 0,
250 // NODE_NETWORK means that the node is capable of serving the complete block chain. It is currently
251 // set by all Bitcoin Core non pruned nodes, and is unset by SPV clients or other light clients.
252 NODE_NETWORK = (1 << 0),
253 // NODE_GETUTXO means the node is capable of responding to the getutxo protocol request.
254 // Bitcoin Core does not support this but a patch set called Bitcoin XT does.
255 // See BIP 64 for details on how this is implemented.
256 NODE_GETUTXO = (1 << 1),
257 // NODE_BLOOM means the node is capable and willing to handle bloom-filtered connections.
258 // Bitcoin Core nodes used to support this by default, without advertising this bit,
259 // but no longer do as of protocol version 70011 (= NO_BLOOM_VERSION)
260 NODE_BLOOM = (1 << 2),
261 // NODE_WITNESS indicates that a node can be asked for blocks and transactions including
262 // witness data.
263 NODE_WITNESS = (1 << 3),
264 // NODE_XTHIN means the node supports Xtreme Thinblocks
265 // If this is turned off then the node will not service nor make xthin requests
266 NODE_XTHIN = (1 << 4),
267 // NODE_NETWORK_LIMITED means the same as NODE_NETWORK with the limitation of only
268 // serving the last 288 (2 day) blocks
269 // See BIP159 for details on how this is implemented.
270 NODE_NETWORK_LIMITED = (1 << 10),
271
272 // Bits 24-31 are reserved for temporary experiments. Just pick a bit that
273 // isn't getting used, or one not being used much, and notify the
274 // bitcoin-development mailing list. Remember that service bits are just
275 // unauthenticated advertisements, so your code must be robust against
276 // collisions and other cases where nodes may be advertising a service they
277 // do not actually support. Other service bits should be allocated via the
278 // BIP process.
279 };
280
281 /**
282 * Gets the set of service flags which are "desirable" for a given peer.
283 *
284 * These are the flags which are required for a peer to support for them
285 * to be "interesting" to us, ie for us to wish to use one of our few
286 * outbound connection slots for or for us to wish to prioritize keeping
287 * their connection around.
288 *
289 * Relevant service flags may be peer- and state-specific in that the
290 * version of the peer may determine which flags are required (eg in the
291 * case of NODE_NETWORK_LIMITED where we seek out NODE_NETWORK peers
292 * unless they set NODE_NETWORK_LIMITED and we are out of IBD, in which
293 * case NODE_NETWORK_LIMITED suffices).
294 *
295 * Thus, generally, avoid calling with peerServices == NODE_NONE, unless
296 * state-specific flags must absolutely be avoided. When called with
297 * peerServices == NODE_NONE, the returned desirable service flags are
298 * guaranteed to not change dependent on state - ie they are suitable for
299 * use when describing peers which we know to be desirable, but for which
300 * we do not have a confirmed set of service flags.
301 *
302 * If the NODE_NONE return value is changed, contrib/seeds/makeseeds.py
303 * should be updated appropriately to filter for the same nodes.
304 */
305 ServiceFlags GetDesirableServiceFlags(ServiceFlags services);
306
307 /** Set the current IBD status in order to figure out the desirable service flags */
308 void SetServiceFlagsIBDCache(bool status);
309
310 /**
311 * A shortcut for (services & GetDesirableServiceFlags(services))
312 * == GetDesirableServiceFlags(services), ie determines whether the given
313 * set of service flags are sufficient for a peer to be "relevant".
314 */
HasAllDesirableServiceFlags(ServiceFlags services)315 static inline bool HasAllDesirableServiceFlags(ServiceFlags services) {
316 return !(GetDesirableServiceFlags(services) & (~services));
317 }
318
319 /**
320 * Checks if a peer with the given service flags may be capable of having a
321 * robust address-storage DB.
322 */
MayHaveUsefulAddressDB(ServiceFlags services)323 static inline bool MayHaveUsefulAddressDB(ServiceFlags services) {
324 return (services & NODE_NETWORK) || (services & NODE_NETWORK_LIMITED);
325 }
326
327 /** A CService with information about it as peer */
328 class CAddress : public CService
329 {
330 public:
331 CAddress();
332 explicit CAddress(CService ipIn, ServiceFlags nServicesIn);
333
334 void Init();
335
336 ADD_SERIALIZE_METHODS;
337
338 template <typename Stream, typename Operation>
SerializationOp(Stream & s,Operation ser_action)339 inline void SerializationOp(Stream& s, Operation ser_action)
340 {
341 if (ser_action.ForRead())
342 Init();
343 int nVersion = s.GetVersion();
344 if (s.GetType() & SER_DISK)
345 READWRITE(nVersion);
346 if ((s.GetType() & SER_DISK) ||
347 (nVersion >= CADDR_TIME_VERSION && !(s.GetType() & SER_GETHASH)))
348 READWRITE(nTime);
349 uint64_t nServicesInt = nServices;
350 READWRITE(nServicesInt);
351 nServices = static_cast<ServiceFlags>(nServicesInt);
352 READWRITEAS(CService, *this);
353 }
354
355 // TODO: make private (improves encapsulation)
356 public:
357 ServiceFlags nServices;
358
359 // disk and network only
360 unsigned int nTime;
361 };
362
363 /** getdata message type flags */
364 const uint32_t MSG_WITNESS_FLAG = 1 << 30;
365 const uint32_t MSG_TYPE_MASK = 0xffffffff >> 2;
366
367 /** getdata / inv message types.
368 * These numbers are defined by the protocol. When adding a new value, be sure
369 * to mention it in the respective BIP.
370 */
371 enum GetDataMsg
372 {
373 UNDEFINED = 0,
374 MSG_TX = 1,
375 MSG_BLOCK = 2,
376 // The following can only occur in getdata. Invs always use TX or BLOCK.
377 MSG_FILTERED_BLOCK = 3, //!< Defined in BIP37
378 MSG_CMPCT_BLOCK = 4, //!< Defined in BIP152
379 MSG_WITNESS_BLOCK = MSG_BLOCK | MSG_WITNESS_FLAG, //!< Defined in BIP144
380 MSG_WITNESS_TX = MSG_TX | MSG_WITNESS_FLAG, //!< Defined in BIP144
381 MSG_FILTERED_WITNESS_BLOCK = MSG_FILTERED_BLOCK | MSG_WITNESS_FLAG,
382 };
383
384 /** inv message data */
385 class CInv
386 {
387 public:
388 CInv();
389 CInv(int typeIn, const uint256& hashIn);
390
391 ADD_SERIALIZE_METHODS;
392
393 template <typename Stream, typename Operation>
SerializationOp(Stream & s,Operation ser_action)394 inline void SerializationOp(Stream& s, Operation ser_action)
395 {
396 READWRITE(type);
397 READWRITE(hash);
398 }
399
400 friend bool operator<(const CInv& a, const CInv& b);
401
402 std::string GetCommand() const;
403 std::string ToString() const;
404
405 public:
406 int type;
407 uint256 hash;
408 };
409
410 #endif // BITCOIN_PROTOCOL_H
411