Bitcoin Core  24.99.0
P2P Digital Currency
protocol.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2022 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 BITCOIN_PROTOCOL_H
7 #define BITCOIN_PROTOCOL_H
8 
9 #include <netaddress.h>
10 #include <primitives/transaction.h>
11 #include <serialize.h>
12 #include <streams.h>
13 #include <uint256.h>
14 #include <util/time.h>
15 
16 #include <cstdint>
17 #include <limits>
18 #include <string>
19 
27 {
28 public:
29  static constexpr size_t MESSAGE_START_SIZE = 4;
30  static constexpr size_t COMMAND_SIZE = 12;
31  static constexpr size_t MESSAGE_SIZE_SIZE = 4;
32  static constexpr size_t CHECKSUM_SIZE = 4;
36  typedef unsigned char MessageStartChars[MESSAGE_START_SIZE];
37 
38  explicit CMessageHeader() = default;
39 
43  CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn);
44 
45  std::string GetCommand() const;
46  bool IsCommandValid() const;
47 
48  SERIALIZE_METHODS(CMessageHeader, obj) { READWRITE(obj.pchMessageStart, obj.pchCommand, obj.nMessageSize, obj.pchChecksum); }
49 
52  uint32_t nMessageSize{std::numeric_limits<uint32_t>::max()};
54 };
55 
60 namespace NetMsgType {
61 
66 extern const char* VERSION;
71 extern const char* VERACK;
76 extern const char* ADDR;
82 extern const char *ADDRV2;
88 extern const char *SENDADDRV2;
93 extern const char* INV;
97 extern const char* GETDATA;
103 extern const char* MERKLEBLOCK;
108 extern const char* GETBLOCKS;
114 extern const char* GETHEADERS;
118 extern const char* TX;
124 extern const char* HEADERS;
128 extern const char* BLOCK;
133 extern const char* GETADDR;
139 extern const char* MEMPOOL;
144 extern const char* PING;
150 extern const char* PONG;
156 extern const char* NOTFOUND;
164 extern const char* FILTERLOAD;
172 extern const char* FILTERADD;
180 extern const char* FILTERCLEAR;
186 extern const char* SENDHEADERS;
192 extern const char* FEEFILTER;
200 extern const char* SENDCMPCT;
206 extern const char* CMPCTBLOCK;
212 extern const char* GETBLOCKTXN;
218 extern const char* BLOCKTXN;
224 extern const char* GETCFILTERS;
229 extern const char* CFILTER;
237 extern const char* GETCFHEADERS;
242 extern const char* CFHEADERS;
249 extern const char* GETCFCHECKPT;
254 extern const char* CFCHECKPT;
260 extern const char* WTXIDRELAY;
266 extern const char* SENDTXRCNCL;
267 }; // namespace NetMsgType
268 
269 /* Get a vector of all valid message types (see above) */
270 const std::vector<std::string>& getAllNetMessageTypes();
271 
273 enum ServiceFlags : uint64_t {
274  // NOTE: When adding here, be sure to update serviceFlagToStr too
275  // Nothing
277  // NODE_NETWORK means that the node is capable of serving the complete block chain. It is currently
278  // set by all Bitcoin Core non pruned nodes, and is unset by SPV clients or other light clients.
279  NODE_NETWORK = (1 << 0),
280  // NODE_BLOOM means the node is capable and willing to handle bloom-filtered connections.
281  // Bitcoin Core nodes used to support this by default, without advertising this bit,
282  // but no longer do as of protocol version 70011 (= NO_BLOOM_VERSION)
283  NODE_BLOOM = (1 << 2),
284  // NODE_WITNESS indicates that a node can be asked for blocks and transactions including
285  // witness data.
286  NODE_WITNESS = (1 << 3),
287  // NODE_COMPACT_FILTERS means the node will service basic block filter requests.
288  // See BIP157 and BIP158 for details on how this is implemented.
290  // NODE_NETWORK_LIMITED means the same as NODE_NETWORK with the limitation of only
291  // serving the last 288 (2 day) blocks
292  // See BIP159 for details on how this is implemented.
293  NODE_NETWORK_LIMITED = (1 << 10),
294 
295  // Bits 24-31 are reserved for temporary experiments. Just pick a bit that
296  // isn't getting used, or one not being used much, and notify the
297  // bitcoin-development mailing list. Remember that service bits are just
298  // unauthenticated advertisements, so your code must be robust against
299  // collisions and other cases where nodes may be advertising a service they
300  // do not actually support. Other service bits should be allocated via the
301  // BIP process.
302 };
303 
309 std::vector<std::string> serviceFlagsToStr(uint64_t flags);
310 
336 
338 void SetServiceFlagsIBDCache(bool status);
339 
345 static inline bool HasAllDesirableServiceFlags(ServiceFlags services)
346 {
347  return !(GetDesirableServiceFlags(services) & (~services));
348 }
349 
354 static inline bool MayHaveUsefulAddressDB(ServiceFlags services)
355 {
356  return (services & NODE_NETWORK) || (services & NODE_NETWORK_LIMITED);
357 }
358 
360 class CAddress : public CService
361 {
362  static constexpr std::chrono::seconds TIME_INIT{100000000};
363 
380  static constexpr uint32_t DISK_VERSION_INIT{220000};
381  static constexpr uint32_t DISK_VERSION_IGNORE_MASK{0b00000000'00000111'11111111'11111111};
385  static constexpr uint32_t DISK_VERSION_ADDRV2{1 << 29};
386  static_assert((DISK_VERSION_INIT & ~DISK_VERSION_IGNORE_MASK) == 0, "DISK_VERSION_INIT must be covered by DISK_VERSION_IGNORE_MASK");
387  static_assert((DISK_VERSION_ADDRV2 & DISK_VERSION_IGNORE_MASK) == 0, "DISK_VERSION_ADDRV2 must not be covered by DISK_VERSION_IGNORE_MASK");
388 
389 public:
390  CAddress() : CService{} {};
391  CAddress(CService ipIn, ServiceFlags nServicesIn) : CService{ipIn}, nServices{nServicesIn} {};
392  CAddress(CService ipIn, ServiceFlags nServicesIn, NodeSeconds time) : CService{ipIn}, nTime{time}, nServices{nServicesIn} {};
393 
395  {
396  // CAddress has a distinct network serialization and a disk serialization, but it should never
397  // be hashed (except through CHashWriter in addrdb.cpp, which sets SER_DISK), and it's
398  // ambiguous what that would mean. Make sure no code relying on that is introduced:
399  assert(!(s.GetType() & SER_GETHASH));
400  bool use_v2;
401  if (s.GetType() & SER_DISK) {
402  // In the disk serialization format, the encoding (v1 or v2) is determined by a flag version
403  // that's part of the serialization itself. ADDRV2_FORMAT in the stream version only determines
404  // whether V2 is chosen/permitted at all.
405  uint32_t stored_format_version = DISK_VERSION_INIT;
406  if (s.GetVersion() & ADDRV2_FORMAT) stored_format_version |= DISK_VERSION_ADDRV2;
407  READWRITE(stored_format_version);
408  stored_format_version &= ~DISK_VERSION_IGNORE_MASK; // ignore low bits
409  if (stored_format_version == 0) {
410  use_v2 = false;
411  } else if (stored_format_version == DISK_VERSION_ADDRV2 && (s.GetVersion() & ADDRV2_FORMAT)) {
412  // Only support v2 deserialization if ADDRV2_FORMAT is set.
413  use_v2 = true;
414  } else {
415  throw std::ios_base::failure("Unsupported CAddress disk format version");
416  }
417  } else {
418  // In the network serialization format, the encoding (v1 or v2) is determined directly by
419  // the value of ADDRV2_FORMAT in the stream version, as no explicitly encoded version
420  // exists in the stream.
421  assert(s.GetType() & SER_NETWORK);
422  use_v2 = s.GetVersion() & ADDRV2_FORMAT;
423  }
424 
426  // nServices is serialized as CompactSize in V2; as uint64_t in V1.
427  if (use_v2) {
428  uint64_t services_tmp;
429  SER_WRITE(obj, services_tmp = obj.nServices);
431  SER_READ(obj, obj.nServices = static_cast<ServiceFlags>(services_tmp));
432  } else {
433  READWRITE(Using<CustomUintFormatter<8>>(obj.nServices));
434  }
435  // Invoke V1/V2 serializer for CService parent object.
436  OverrideStream<Stream> os(&s, s.GetType(), use_v2 ? ADDRV2_FORMAT : 0);
437  SerReadWriteMany(os, ser_action, ReadWriteAsHelper<CService>(obj));
438  }
439 
444 
445  friend bool operator==(const CAddress& a, const CAddress& b)
446  {
447  return a.nTime == b.nTime &&
448  a.nServices == b.nServices &&
449  static_cast<const CService&>(a) == static_cast<const CService&>(b);
450  }
451 };
452 
454 const uint32_t MSG_WITNESS_FLAG = 1 << 30;
455 const uint32_t MSG_TYPE_MASK = 0xffffffff >> 2;
456 
461 enum GetDataMsg : uint32_t {
463  MSG_TX = 1,
465  MSG_WTX = 5,
466  // The following can only occur in getdata. Invs always use TX/WTX or BLOCK.
471  // MSG_FILTERED_WITNESS_BLOCK is defined in BIP144 as reserved for future
472  // use and remains unused.
473  // MSG_FILTERED_WITNESS_BLOCK = MSG_FILTERED_BLOCK | MSG_WITNESS_FLAG,
474 };
475 
477 class CInv
478 {
479 public:
480  CInv();
481  CInv(uint32_t typeIn, const uint256& hashIn);
482 
483  SERIALIZE_METHODS(CInv, obj) { READWRITE(obj.type, obj.hash); }
484 
485  friend bool operator<(const CInv& a, const CInv& b);
486 
487  std::string GetCommand() const;
488  std::string ToString() const;
489 
490  // Single-message helper methods
491  bool IsMsgTx() const { return type == MSG_TX; }
492  bool IsMsgBlk() const { return type == MSG_BLOCK; }
493  bool IsMsgWtx() const { return type == MSG_WTX; }
494  bool IsMsgFilteredBlk() const { return type == MSG_FILTERED_BLOCK; }
495  bool IsMsgCmpctBlk() const { return type == MSG_CMPCT_BLOCK; }
496  bool IsMsgWitnessBlk() const { return type == MSG_WITNESS_BLOCK; }
497 
498  // Combined-message helper methods
499  bool IsGenTxMsg() const
500  {
501  return type == MSG_TX || type == MSG_WTX || type == MSG_WITNESS_TX;
502  }
503  bool IsGenBlkMsg() const
504  {
506  }
507 
508  uint32_t type;
510 };
511 
513 GenTxid ToGenTxid(const CInv& inv);
514 
515 #endif // BITCOIN_PROTOCOL_H
int flags
Definition: bitcoin-tx.cpp:525
A CService with information about it as peer.
Definition: protocol.h:361
static constexpr uint32_t DISK_VERSION_IGNORE_MASK
Definition: protocol.h:381
SERIALIZE_METHODS(CAddress, obj)
Definition: protocol.h:394
CAddress(CService ipIn, ServiceFlags nServicesIn, NodeSeconds time)
Definition: protocol.h:392
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
Definition: protocol.h:443
NodeSeconds nTime
Always included in serialization. The behavior is unspecified if the value is not representable as ui...
Definition: protocol.h:441
static constexpr uint32_t DISK_VERSION_INIT
Historically, CAddress disk serialization stored the CLIENT_VERSION, optionally OR'ed with the ADDRV2...
Definition: protocol.h:380
CAddress()
Definition: protocol.h:390
friend bool operator==(const CAddress &a, const CAddress &b)
Definition: protocol.h:445
CAddress(CService ipIn, ServiceFlags nServicesIn)
Definition: protocol.h:391
static constexpr std::chrono::seconds TIME_INIT
Definition: protocol.h:362
static constexpr uint32_t DISK_VERSION_ADDRV2
The version number written in disk serialized addresses to indicate V2 serializations.
Definition: protocol.h:385
inv message data
Definition: protocol.h:478
bool IsMsgCmpctBlk() const
Definition: protocol.h:495
friend bool operator<(const CInv &a, const CInv &b)
Definition: protocol.cpp:148
bool IsMsgBlk() const
Definition: protocol.h:492
std::string ToString() const
Definition: protocol.cpp:172
std::string GetCommand() const
Definition: protocol.cpp:153
bool IsMsgWtx() const
Definition: protocol.h:493
CInv()
Definition: protocol.cpp:140
uint32_t type
Definition: protocol.h:508
bool IsGenTxMsg() const
Definition: protocol.h:499
bool IsMsgTx() const
Definition: protocol.h:491
bool IsMsgFilteredBlk() const
Definition: protocol.h:494
uint256 hash
Definition: protocol.h:509
SERIALIZE_METHODS(CInv, obj)
Definition: protocol.h:483
bool IsGenBlkMsg() const
Definition: protocol.h:503
bool IsMsgWitnessBlk() const
Definition: protocol.h:496
Message header.
Definition: protocol.h:27
static constexpr size_t MESSAGE_SIZE_OFFSET
Definition: protocol.h:33
static constexpr size_t CHECKSUM_OFFSET
Definition: protocol.h:34
unsigned char MessageStartChars[MESSAGE_START_SIZE]
Definition: protocol.h:36
char pchMessageStart[MESSAGE_START_SIZE]
Definition: protocol.h:50
static constexpr size_t CHECKSUM_SIZE
Definition: protocol.h:32
CMessageHeader()=default
static constexpr size_t MESSAGE_SIZE_SIZE
Definition: protocol.h:31
char pchCommand[COMMAND_SIZE]
Definition: protocol.h:51
static constexpr size_t HEADER_SIZE
Definition: protocol.h:35
uint8_t pchChecksum[CHECKSUM_SIZE]
Definition: protocol.h:53
static constexpr size_t MESSAGE_START_SIZE
Definition: protocol.h:29
std::string GetCommand() const
Definition: protocol.cpp:104
SERIALIZE_METHODS(CMessageHeader, obj)
Definition: protocol.h:48
static constexpr size_t COMMAND_SIZE
Definition: protocol.h:30
uint32_t nMessageSize
Definition: protocol.h:52
bool IsCommandValid() const
Definition: protocol.cpp:109
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:523
A generic txid reference (txid or wtxid).
Definition: transaction.h:426
256-bit opaque blob.
Definition: uint256.h:119
Bitcoin protocol message types.
Definition: protocol.cpp:12
const char * FILTERLOAD
The filterload message tells the receiving peer to filter all relayed transactions and requested merk...
Definition: protocol.cpp:31
const char * CFHEADERS
cfheaders is a response to a getcfheaders request containing a filter header and a vector of filter h...
Definition: protocol.cpp:43
const char * CFILTER
cfilter is a response to a getcfilters request containing a single compact filter.
Definition: protocol.cpp:41
const char * BLOCK
The block message transmits a single serialized block.
Definition: protocol.cpp:25
const char * FILTERCLEAR
The filterclear message tells the receiving peer to remove a previously-set bloom filter.
Definition: protocol.cpp:33
const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
Definition: protocol.cpp:24
const char * ADDRV2
The addrv2 message relays connection information for peers on the network just like the addr message,...
Definition: protocol.cpp:16
const char * SENDHEADERS
Indicates that a node prefers to receive new block announcements via a "headers" message rather than ...
Definition: protocol.cpp:34
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:29
const char * SENDCMPCT
Contains a 1-byte bool and 8-byte LE version number.
Definition: protocol.cpp:36
const char * GETADDR
The getaddr message requests an addr message from the receiving node, preferably one with lots of IP ...
Definition: protocol.cpp:26
const char * GETCFCHECKPT
getcfcheckpt requests evenly spaced compact filter headers, enabling parallelized download and valida...
Definition: protocol.cpp:44
const char * NOTFOUND
The notfound message is a reply to a getdata message which requested an object the receiving node doe...
Definition: protocol.cpp:30
const char * CMPCTBLOCK
Contains a CBlockHeaderAndShortTxIDs object - providing a header and list of "short txids".
Definition: protocol.cpp:37
const char * SENDTXRCNCL
Contains a 4-byte version number and an 8-byte salt.
Definition: protocol.cpp:47
const char * MEMPOOL
The mempool message requests the TXIDs of transactions that the receiving node has verified as valid ...
Definition: protocol.cpp:27
const char * GETCFILTERS
getcfilters requests compact filters for a range of blocks.
Definition: protocol.cpp:40
const char * TX
The tx message transmits a single transaction.
Definition: protocol.cpp:23
const char * FILTERADD
The filteradd message tells the receiving peer to add a single element to a previously-set bloom filt...
Definition: protocol.cpp:32
const char * ADDR
The addr (IP address) message relays connection information for peers on the network.
Definition: protocol.cpp:15
const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
Definition: protocol.cpp:13
const char * GETBLOCKS
The getblocks message requests an inv message that provides block header hashes starting from a parti...
Definition: protocol.cpp:21
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:35
const char * GETHEADERS
The getheaders message requests a headers message that provides block headers starting from a particu...
Definition: protocol.cpp:22
const char * GETDATA
The getdata message requests one or more data objects from another node.
Definition: protocol.cpp:19
const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
Definition: protocol.cpp:14
const char * BLOCKTXN
Contains a BlockTransactions.
Definition: protocol.cpp:39
const char * GETCFHEADERS
getcfheaders requests a compact filter header and the filter hashes for a range of blocks,...
Definition: protocol.cpp:42
const char * SENDADDRV2
The sendaddrv2 message signals support for receiving ADDRV2 messages (BIP155).
Definition: protocol.cpp:17
const char * WTXIDRELAY
Indicates that a node prefers to relay transactions via wtxid, rather than txid.
Definition: protocol.cpp:46
const char * PING
The ping message is sent periodically to help confirm that the receiving peer is still connected.
Definition: protocol.cpp:28
const char * MERKLEBLOCK
The merkleblock message is a reply to a getdata message which requested a block using the inventory t...
Definition: protocol.cpp:20
const char * CFCHECKPT
cfcheckpt is a response to a getcfcheckpt request containing a vector of evenly spaced filter headers...
Definition: protocol.cpp:45
const char * GETBLOCKTXN
Contains a BlockTransactionsRequest Peer should respond with "blocktxn" message.
Definition: protocol.cpp:38
const char * INV
The inv message (inventory message) transmits one or more inventories of objects known to the transmi...
Definition: protocol.cpp:18
static constexpr int ADDRV2_FORMAT
A flag that is ORed into the protocol version to designate that addresses should be serialized in (un...
Definition: netaddress.h:33
GenTxid ToGenTxid(const CInv &inv)
Convert a TX/WITNESS_TX/WTX CInv to a GenTxid.
Definition: protocol.cpp:220
ServiceFlags GetDesirableServiceFlags(ServiceFlags services)
Gets the set of service flags which are "desirable" for a given peer.
Definition: protocol.cpp:129
const std::vector< std::string > & getAllNetMessageTypes()
Definition: protocol.cpp:181
static bool HasAllDesirableServiceFlags(ServiceFlags services)
A shortcut for (services & GetDesirableServiceFlags(services)) == GetDesirableServiceFlags(services),...
Definition: protocol.h:345
const uint32_t MSG_WITNESS_FLAG
getdata message type flags
Definition: protocol.h:454
void SetServiceFlagsIBDCache(bool status)
Set the current IBD status in order to figure out the desirable service flags.
Definition: protocol.cpp:136
const uint32_t MSG_TYPE_MASK
Definition: protocol.h:455
std::vector< std::string > serviceFlagsToStr(uint64_t flags)
Convert service flags (a bitmask of NODE_*) to human readable strings.
Definition: protocol.cpp:207
GetDataMsg
getdata / inv message types.
Definition: protocol.h:461
@ MSG_TX
Definition: protocol.h:463
@ MSG_FILTERED_BLOCK
Defined in BIP37.
Definition: protocol.h:467
@ MSG_WTX
Defined in BIP 339.
Definition: protocol.h:465
@ MSG_BLOCK
Definition: protocol.h:464
@ UNDEFINED
Definition: protocol.h:462
@ MSG_CMPCT_BLOCK
Defined in BIP152.
Definition: protocol.h:468
@ MSG_WITNESS_BLOCK
Defined in BIP144.
Definition: protocol.h:469
@ MSG_WITNESS_TX
Defined in BIP144.
Definition: protocol.h:470
ServiceFlags
nServices flags
Definition: protocol.h:273
@ NODE_NONE
Definition: protocol.h:276
@ NODE_WITNESS
Definition: protocol.h:286
@ NODE_NETWORK_LIMITED
Definition: protocol.h:293
@ NODE_BLOOM
Definition: protocol.h:283
@ NODE_NETWORK
Definition: protocol.h:279
@ NODE_COMPACT_FILTERS
Definition: protocol.h:289
static bool MayHaveUsefulAddressDB(ServiceFlags services)
Checks if a peer with the given service flags may be capable of having a robust address-storage DB.
Definition: protocol.h:354
#define SER_WRITE(obj, code)
Definition: serialize.h:143
@ SER_DISK
Definition: serialize.h:132
@ SER_NETWORK
Definition: serialize.h:131
@ SER_GETHASH
Definition: serialize.h:133
void SerReadWriteMany(Stream &s, CSerActionSerialize ser_action, const Args &... args)
Definition: serialize.h:1064
static Wrapper< Formatter, T & > Using(T &&t)
Cause serialization/deserialization of an object to be done using a specified formatter class.
Definition: serialize.h:433
#define SER_READ(obj, code)
Definition: serialize.h:142
#define READWRITE(...)
Definition: serialize.h:140
Formatter for integers in CompactSize format.
Definition: serialize.h:502
Serialization wrapper class for custom integers and enums.
Definition: serialize.h:466
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
Definition: time.h:25
assert(!tx.IsCoinBase())