Bitcoin Core  27.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 <kernel/messagestartchars.h> // IWYU pragma: export
10 #include <netaddress.h>
11 #include <primitives/transaction.h>
12 #include <serialize.h>
13 #include <streams.h>
14 #include <uint256.h>
15 #include <util/time.h>
16 
17 #include <array>
18 #include <cstdint>
19 #include <limits>
20 #include <string>
21 
29 {
30 public:
31  static constexpr size_t COMMAND_SIZE = 12;
32  static constexpr size_t MESSAGE_SIZE_SIZE = 4;
33  static constexpr size_t CHECKSUM_SIZE = 4;
34  static constexpr size_t MESSAGE_SIZE_OFFSET = std::tuple_size_v<MessageStartChars> + COMMAND_SIZE;
36  static constexpr size_t HEADER_SIZE = std::tuple_size_v<MessageStartChars> + COMMAND_SIZE + MESSAGE_SIZE_SIZE + CHECKSUM_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 {
65 inline constexpr const char* VERSION{"version"};
70 inline constexpr const char* VERACK{"verack"};
75 inline constexpr const char* ADDR{"addr"};
81 inline constexpr const char* ADDRV2{"addrv2"};
87 inline constexpr const char* SENDADDRV2{"sendaddrv2"};
92 inline constexpr const char* INV{"inv"};
96 inline constexpr const char* GETDATA{"getdata"};
102 inline constexpr const char* MERKLEBLOCK{"merkleblock"};
107 inline constexpr const char* GETBLOCKS{"getblocks"};
113 inline constexpr const char* GETHEADERS{"getheaders"};
117 inline constexpr const char* TX{"tx"};
123 inline constexpr const char* HEADERS{"headers"};
127 inline constexpr const char* BLOCK{"block"};
132 inline constexpr const char* GETADDR{"getaddr"};
139 inline constexpr const char* MEMPOOL{"mempool"};
144 inline constexpr const char* PING{"ping"};
150 inline constexpr const char* PONG{"pong"};
156 inline constexpr const char* NOTFOUND{"notfound"};
164 inline constexpr const char* FILTERLOAD{"filterload"};
172 inline constexpr const char* FILTERADD{"filteradd"};
180 inline constexpr const char* FILTERCLEAR{"filterclear"};
186 inline constexpr const char* SENDHEADERS{"sendheaders"};
192 inline constexpr const char* FEEFILTER{"feefilter"};
200 inline constexpr const char* SENDCMPCT{"sendcmpct"};
206 inline constexpr const char* CMPCTBLOCK{"cmpctblock"};
212 inline constexpr const char* GETBLOCKTXN{"getblocktxn"};
218 inline constexpr const char* BLOCKTXN{"blocktxn"};
224 inline constexpr const char* GETCFILTERS{"getcfilters"};
229 inline constexpr const char* CFILTER{"cfilter"};
237 inline constexpr const char* GETCFHEADERS{"getcfheaders"};
242 inline constexpr const char* CFHEADERS{"cfheaders"};
249 inline constexpr const char* GETCFCHECKPT{"getcfcheckpt"};
254 inline constexpr const char* CFCHECKPT{"cfcheckpt"};
260 inline constexpr const char* WTXIDRELAY{"wtxidrelay"};
266 inline constexpr const char* SENDTXRCNCL{"sendtxrcncl"};
267 }; // namespace NetMsgType
268 
270 inline const std::array ALL_NET_MESSAGE_TYPES{std::to_array<std::string>({
306 })};
307 
309 enum ServiceFlags : uint64_t {
310  // NOTE: When adding here, be sure to update serviceFlagToStr too
311  // Nothing
313  // NODE_NETWORK means that the node is capable of serving the complete block chain. It is currently
314  // set by all Bitcoin Core non pruned nodes, and is unset by SPV clients or other light clients.
315  NODE_NETWORK = (1 << 0),
316  // NODE_BLOOM means the node is capable and willing to handle bloom-filtered connections.
317  NODE_BLOOM = (1 << 2),
318  // NODE_WITNESS indicates that a node can be asked for blocks and transactions including
319  // witness data.
320  NODE_WITNESS = (1 << 3),
321  // NODE_COMPACT_FILTERS means the node will service basic block filter requests.
322  // See BIP157 and BIP158 for details on how this is implemented.
324  // NODE_NETWORK_LIMITED means the same as NODE_NETWORK with the limitation of only
325  // serving the last 288 (2 day) blocks
326  // See BIP159 for details on how this is implemented.
327  NODE_NETWORK_LIMITED = (1 << 10),
328 
329  // NODE_P2P_V2 means the node supports BIP324 transport
330  NODE_P2P_V2 = (1 << 11),
331 
332  // Bits 24-31 are reserved for temporary experiments. Just pick a bit that
333  // isn't getting used, or one not being used much, and notify the
334  // bitcoin-development mailing list. Remember that service bits are just
335  // unauthenticated advertisements, so your code must be robust against
336  // collisions and other cases where nodes may be advertising a service they
337  // do not actually support. Other service bits should be allocated via the
338  // BIP process.
339 };
340 
346 std::vector<std::string> serviceFlagsToStr(uint64_t flags);
347 
355 
360 static inline bool MayHaveUsefulAddressDB(ServiceFlags services)
361 {
362  return (services & NODE_NETWORK) || (services & NODE_NETWORK_LIMITED);
363 }
364 
366 class CAddress : public CService
367 {
368  static constexpr std::chrono::seconds TIME_INIT{100000000};
369 
386  static constexpr uint32_t DISK_VERSION_INIT{220000};
387  static constexpr uint32_t DISK_VERSION_IGNORE_MASK{0b00000000'00000111'11111111'11111111};
391  static constexpr uint32_t DISK_VERSION_ADDRV2{1 << 29};
392  static_assert((DISK_VERSION_INIT & ~DISK_VERSION_IGNORE_MASK) == 0, "DISK_VERSION_INIT must be covered by DISK_VERSION_IGNORE_MASK");
393  static_assert((DISK_VERSION_ADDRV2 & DISK_VERSION_IGNORE_MASK) == 0, "DISK_VERSION_ADDRV2 must not be covered by DISK_VERSION_IGNORE_MASK");
394 
395 public:
396  CAddress() : CService{} {};
397  CAddress(CService ipIn, ServiceFlags nServicesIn) : CService{ipIn}, nServices{nServicesIn} {};
398  CAddress(CService ipIn, ServiceFlags nServicesIn, NodeSeconds time) : CService{ipIn}, nTime{time}, nServices{nServicesIn} {};
399 
400  enum class Format {
401  Disk,
402  Network,
403  };
405  const Format fmt;
407  };
412 
414  {
415  bool use_v2;
416  auto& params = SER_PARAMS(SerParams);
417  if (params.fmt == Format::Disk) {
418  // In the disk serialization format, the encoding (v1 or v2) is determined by a flag version
419  // that's part of the serialization itself. ADDRV2_FORMAT in the stream version only determines
420  // whether V2 is chosen/permitted at all.
421  uint32_t stored_format_version = DISK_VERSION_INIT;
422  if (params.enc == Encoding::V2) stored_format_version |= DISK_VERSION_ADDRV2;
423  READWRITE(stored_format_version);
424  stored_format_version &= ~DISK_VERSION_IGNORE_MASK; // ignore low bits
425  if (stored_format_version == 0) {
426  use_v2 = false;
427  } else if (stored_format_version == DISK_VERSION_ADDRV2 && params.enc == Encoding::V2) {
428  // Only support v2 deserialization if V2 is set.
429  use_v2 = true;
430  } else {
431  throw std::ios_base::failure("Unsupported CAddress disk format version");
432  }
433  } else {
434  assert(params.fmt == Format::Network);
435  // In the network serialization format, the encoding (v1 or v2) is determined directly by
436  // the value of enc in the stream params, as no explicitly encoded version
437  // exists in the stream.
438  use_v2 = params.enc == Encoding::V2;
439  }
440 
442  // nServices is serialized as CompactSize in V2; as uint64_t in V1.
443  if (use_v2) {
444  uint64_t services_tmp;
445  SER_WRITE(obj, services_tmp = obj.nServices);
447  SER_READ(obj, obj.nServices = static_cast<ServiceFlags>(services_tmp));
448  } else {
449  READWRITE(Using<CustomUintFormatter<8>>(obj.nServices));
450  }
451  // Invoke V1/V2 serializer for CService parent object.
452  const auto ser_params{use_v2 ? CNetAddr::V2 : CNetAddr::V1};
453  READWRITE(ser_params(AsBase<CService>(obj)));
454  }
455 
460 
461  friend bool operator==(const CAddress& a, const CAddress& b)
462  {
463  return a.nTime == b.nTime &&
464  a.nServices == b.nServices &&
465  static_cast<const CService&>(a) == static_cast<const CService&>(b);
466  }
467 };
468 
470 const uint32_t MSG_WITNESS_FLAG = 1 << 30;
471 const uint32_t MSG_TYPE_MASK = 0xffffffff >> 2;
472 
477 enum GetDataMsg : uint32_t {
479  MSG_TX = 1,
481  MSG_WTX = 5,
482  // The following can only occur in getdata. Invs always use TX/WTX or BLOCK.
487  // MSG_FILTERED_WITNESS_BLOCK is defined in BIP144 as reserved for future
488  // use and remains unused.
489  // MSG_FILTERED_WITNESS_BLOCK = MSG_FILTERED_BLOCK | MSG_WITNESS_FLAG,
490 };
491 
493 class CInv
494 {
495 public:
496  CInv();
497  CInv(uint32_t typeIn, const uint256& hashIn);
498 
499  SERIALIZE_METHODS(CInv, obj) { READWRITE(obj.type, obj.hash); }
500 
501  friend bool operator<(const CInv& a, const CInv& b);
502 
503  std::string GetCommand() const;
504  std::string ToString() const;
505 
506  // Single-message helper methods
507  bool IsMsgTx() const { return type == MSG_TX; }
508  bool IsMsgBlk() const { return type == MSG_BLOCK; }
509  bool IsMsgWtx() const { return type == MSG_WTX; }
510  bool IsMsgFilteredBlk() const { return type == MSG_FILTERED_BLOCK; }
511  bool IsMsgCmpctBlk() const { return type == MSG_CMPCT_BLOCK; }
512  bool IsMsgWitnessBlk() const { return type == MSG_WITNESS_BLOCK; }
513 
514  // Combined-message helper methods
515  bool IsGenTxMsg() const
516  {
517  return type == MSG_TX || type == MSG_WTX || type == MSG_WITNESS_TX;
518  }
519  bool IsGenBlkMsg() const
520  {
522  }
523 
524  uint32_t type;
526 };
527 
529 GenTxid ToGenTxid(const CInv& inv);
530 
531 #endif // BITCOIN_PROTOCOL_H
int flags
Definition: bitcoin-tx.cpp:528
A CService with information about it as peer.
Definition: protocol.h:367
static constexpr uint32_t DISK_VERSION_IGNORE_MASK
Definition: protocol.h:387
SERIALIZE_METHODS(CAddress, obj)
Definition: protocol.h:413
CAddress(CService ipIn, ServiceFlags nServicesIn, NodeSeconds time)
Definition: protocol.h:398
ServiceFlags nServices
Serialized as uint64_t in V1, and as CompactSize in V2.
Definition: protocol.h:459
static constexpr SerParams V1_NETWORK
Definition: protocol.h:408
NodeSeconds nTime
Always included in serialization. The behavior is unspecified if the value is not representable as ui...
Definition: protocol.h:457
static constexpr uint32_t DISK_VERSION_INIT
Historically, CAddress disk serialization stored the CLIENT_VERSION, optionally OR'ed with the ADDRV2...
Definition: protocol.h:386
static constexpr SerParams V2_NETWORK
Definition: protocol.h:409
CAddress()
Definition: protocol.h:396
friend bool operator==(const CAddress &a, const CAddress &b)
Definition: protocol.h:461
static constexpr SerParams V1_DISK
Definition: protocol.h:410
CAddress(CService ipIn, ServiceFlags nServicesIn)
Definition: protocol.h:397
static constexpr std::chrono::seconds TIME_INIT
Definition: protocol.h:368
static constexpr uint32_t DISK_VERSION_ADDRV2
The version number written in disk serialized addresses to indicate V2 serializations.
Definition: protocol.h:391
static constexpr SerParams V2_DISK
Definition: protocol.h:411
inv message data
Definition: protocol.h:494
bool IsMsgCmpctBlk() const
Definition: protocol.h:511
friend bool operator<(const CInv &a, const CInv &b)
Definition: protocol.cpp:53
bool IsMsgBlk() const
Definition: protocol.h:508
std::string ToString() const
Definition: protocol.cpp:77
std::string GetCommand() const
Definition: protocol.cpp:58
bool IsMsgWtx() const
Definition: protocol.h:509
CInv()
Definition: protocol.cpp:45
uint32_t type
Definition: protocol.h:524
bool IsGenTxMsg() const
Definition: protocol.h:515
bool IsMsgTx() const
Definition: protocol.h:507
bool IsMsgFilteredBlk() const
Definition: protocol.h:510
uint256 hash
Definition: protocol.h:525
SERIALIZE_METHODS(CInv, obj)
Definition: protocol.h:499
bool IsGenBlkMsg() const
Definition: protocol.h:519
bool IsMsgWitnessBlk() const
Definition: protocol.h:512
Message header.
Definition: protocol.h:29
static constexpr size_t MESSAGE_SIZE_OFFSET
Definition: protocol.h:34
static constexpr size_t CHECKSUM_OFFSET
Definition: protocol.h:35
static constexpr size_t CHECKSUM_SIZE
Definition: protocol.h:33
CMessageHeader()=default
MessageStartChars pchMessageStart
Definition: protocol.h:50
static constexpr size_t MESSAGE_SIZE_SIZE
Definition: protocol.h:32
char pchCommand[COMMAND_SIZE]
Definition: protocol.h:51
static constexpr size_t HEADER_SIZE
Definition: protocol.h:36
uint8_t pchChecksum[CHECKSUM_SIZE]
Definition: protocol.h:53
std::string GetCommand() const
Definition: protocol.cpp:21
SERIALIZE_METHODS(CMessageHeader, obj)
Definition: protocol.h:48
static constexpr size_t COMMAND_SIZE
Definition: protocol.h:31
uint32_t nMessageSize
Definition: protocol.h:52
bool IsCommandValid() const
Definition: protocol.cpp:26
static constexpr SerParams V1
Definition: netaddress.h:231
@ V2
BIP155 encoding.
static constexpr SerParams V2
Definition: netaddress.h:232
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:531
A generic txid reference (txid or wtxid).
Definition: transaction.h:428
256-bit opaque blob.
Definition: uint256.h:106
std::array< uint8_t, 4 > MessageStartChars
Bitcoin protocol message types.
Definition: protocol.h:60
constexpr const char * FILTERCLEAR
The filterclear message tells the receiving peer to remove a previously-set bloom filter.
Definition: protocol.h:180
constexpr const char * FEEFILTER
The feefilter message tells the receiving peer not to inv us any txs which do not meet the specified ...
Definition: protocol.h:192
constexpr const char * SENDHEADERS
Indicates that a node prefers to receive new block announcements via a "headers" message rather than ...
Definition: protocol.h:186
constexpr const char * GETBLOCKS
The getblocks message requests an inv message that provides block header hashes starting from a parti...
Definition: protocol.h:107
constexpr const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
Definition: protocol.h:123
constexpr const char * ADDR
The addr (IP address) message relays connection information for peers on the network.
Definition: protocol.h:75
constexpr const char * GETBLOCKTXN
Contains a BlockTransactionsRequest Peer should respond with "blocktxn" message.
Definition: protocol.h:212
constexpr const char * CMPCTBLOCK
Contains a CBlockHeaderAndShortTxIDs object - providing a header and list of "short txids".
Definition: protocol.h:206
constexpr const char * CFCHECKPT
cfcheckpt is a response to a getcfcheckpt request containing a vector of evenly spaced filter headers...
Definition: protocol.h:254
constexpr const char * SENDADDRV2
The sendaddrv2 message signals support for receiving ADDRV2 messages (BIP155).
Definition: protocol.h:87
constexpr const char * GETADDR
The getaddr message requests an addr message from the receiving node, preferably one with lots of IP ...
Definition: protocol.h:132
constexpr const char * GETCFILTERS
getcfilters requests compact filters for a range of blocks.
Definition: protocol.h:224
constexpr const char * PONG
The pong message replies to a ping message, proving to the pinging node that the ponging node is stil...
Definition: protocol.h:150
constexpr const char * BLOCKTXN
Contains a BlockTransactions.
Definition: protocol.h:218
constexpr const char * CFHEADERS
cfheaders is a response to a getcfheaders request containing a filter header and a vector of filter h...
Definition: protocol.h:242
constexpr const char * PING
The ping message is sent periodically to help confirm that the receiving peer is still connected.
Definition: protocol.h:144
constexpr const char * FILTERLOAD
The filterload message tells the receiving peer to filter all relayed transactions and requested merk...
Definition: protocol.h:164
constexpr const char * SENDTXRCNCL
Contains a 4-byte version number and an 8-byte salt.
Definition: protocol.h:266
constexpr const char * ADDRV2
The addrv2 message relays connection information for peers on the network just like the addr message,...
Definition: protocol.h:81
constexpr const char * VERACK
The verack message acknowledges a previously-received version message, informing the connecting node ...
Definition: protocol.h:70
constexpr const char * GETHEADERS
The getheaders message requests a headers message that provides block headers starting from a particu...
Definition: protocol.h:113
constexpr const char * FILTERADD
The filteradd message tells the receiving peer to add a single element to a previously-set bloom filt...
Definition: protocol.h:172
constexpr const char * CFILTER
cfilter is a response to a getcfilters request containing a single compact filter.
Definition: protocol.h:229
constexpr const char * GETDATA
The getdata message requests one or more data objects from another node.
Definition: protocol.h:96
constexpr const char * SENDCMPCT
Contains a 1-byte bool and 8-byte LE version number.
Definition: protocol.h:200
constexpr const char * GETCFCHECKPT
getcfcheckpt requests evenly spaced compact filter headers, enabling parallelized download and valida...
Definition: protocol.h:249
constexpr const char * INV
The inv message (inventory message) transmits one or more inventories of objects known to the transmi...
Definition: protocol.h:92
constexpr const char * TX
The tx message transmits a single transaction.
Definition: protocol.h:117
constexpr const char * MEMPOOL
The mempool message requests the TXIDs of transactions that the receiving node has verified as valid ...
Definition: protocol.h:139
constexpr const char * NOTFOUND
The notfound message is a reply to a getdata message which requested an object the receiving node doe...
Definition: protocol.h:156
constexpr const char * MERKLEBLOCK
The merkleblock message is a reply to a getdata message which requested a block using the inventory t...
Definition: protocol.h:102
constexpr const char * WTXIDRELAY
Indicates that a node prefers to relay transactions via wtxid, rather than txid.
Definition: protocol.h:260
constexpr const char * BLOCK
The block message transmits a single serialized block.
Definition: protocol.h:127
constexpr const char * GETCFHEADERS
getcfheaders requests a compact filter header and the filter hashes for a range of blocks,...
Definition: protocol.h:237
constexpr const char * VERSION
The version message provides information about the transmitting node to the receiving node at the beg...
Definition: protocol.h:65
const std::array ALL_NET_MESSAGE_TYPES
All known message types (see above).
Definition: protocol.h:270
GenTxid ToGenTxid(const CInv &inv)
Convert a TX/WITNESS_TX/WTX CInv to a GenTxid.
Definition: protocol.cpp:121
const uint32_t MSG_WITNESS_FLAG
getdata message type flags
Definition: protocol.h:470
const uint32_t MSG_TYPE_MASK
Definition: protocol.h:471
std::vector< std::string > serviceFlagsToStr(uint64_t flags)
Convert service flags (a bitmask of NODE_*) to human readable strings.
Definition: protocol.cpp:108
constexpr ServiceFlags SeedsServiceFlags()
State independent service flags.
Definition: protocol.h:354
GetDataMsg
getdata / inv message types.
Definition: protocol.h:477
@ MSG_TX
Definition: protocol.h:479
@ MSG_FILTERED_BLOCK
Defined in BIP37.
Definition: protocol.h:483
@ MSG_WTX
Defined in BIP 339.
Definition: protocol.h:481
@ MSG_BLOCK
Definition: protocol.h:480
@ UNDEFINED
Definition: protocol.h:478
@ MSG_CMPCT_BLOCK
Defined in BIP152.
Definition: protocol.h:484
@ MSG_WITNESS_BLOCK
Defined in BIP144.
Definition: protocol.h:485
@ MSG_WITNESS_TX
Defined in BIP144.
Definition: protocol.h:486
ServiceFlags
nServices flags
Definition: protocol.h:309
@ NODE_NONE
Definition: protocol.h:312
@ NODE_P2P_V2
Definition: protocol.h:330
@ NODE_WITNESS
Definition: protocol.h:320
@ NODE_NETWORK_LIMITED
Definition: protocol.h:327
@ NODE_BLOOM
Definition: protocol.h:317
@ NODE_NETWORK
Definition: protocol.h:315
@ NODE_COMPACT_FILTERS
Definition: protocol.h:323
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:360
#define SER_WRITE(obj, code)
Definition: serialize.h:158
#define SER_PARAMS(type)
Formatter methods can retrieve parameters attached to a stream using the SER_PARAMS(type) macro as lo...
Definition: serialize.h:217
static Wrapper< Formatter, T & > Using(T &&t)
Cause serialization/deserialization of an object to be done using a specified formatter class.
Definition: serialize.h:495
#define SER_READ(obj, code)
Definition: serialize.h:157
#define SER_PARAMS_OPFUNC
Helper macro for SerParams structs.
Definition: serialize.h:1218
#define READWRITE(...)
Definition: serialize.h:156
const Format fmt
Definition: protocol.h:405
Formatter for integers in CompactSize format.
Definition: serialize.h:564
Serialization wrapper class for custom integers and enums.
Definition: serialize.h:528
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
Definition: time.h:23
assert(!tx.IsCoinBase())