Peer-To-Peer Protocol
This page describes the Bitcoin Network Protocol used by nodes running SV Node to communicate transaction and block information on the BSV Blockchain network. This is a current standard means for nodes to communicate information about the ledger between each other including valid transactions, block discovery messages and more. For protocol used in mining, see Getminingcandidate. There have been a number of P2P protocol changes made since 2020. These changes are published on the Bitcoin SV Node Github repository
Message structure
4
magic
uint32_t
Magic value indicating message origin network, and used to seek to next message when stream state is unknown
12
command
char[12]
ASCII string identifying the packet content, NULL padded (non-NULL padding results in packet rejected)
4
length
uint32_t
Length of payload in number of bytes
4
checksum
uint32_t
First 4 bytes of sha256(sha256(payload))
?
payload
uchar[]
The actual data
Known magic values:
mainnet
0xE8F3E1E3
E3 E1 F3 E8
testnet 3
0xF4F3E5F4
F4 E5 F3 F4
scaling testnet
0xF9C4CEFB
FB CE C4 F9
regtest
0xFABFB5DA
DA B5 BF FA
Variable length integer Integer can be encoded depending on the represented value to save space. Variable length integers always precede an array/vector of a type of data that may vary in length. Longer numbers are encoded in little endian. | Value | Storage length | Format | |-------|----------------|--------| | = 31402). Not present in version message. | | | | 8 | services | uint64_t | same service(s) listed in version | | 16 | IPv6/4 | char[16] | IPv6 address. Network byte order. The original client only supported IPv4 and only read the last 4 bytes to get the IPv4 address. However, the IPv4 address is written into the message as a 16 byte IPv4-mapped IPv6 address (12 bytes 00 00 00 00 00 00 00 00 00 00 FF FF, followed by the 4 bytes of the IPv4 address). | | 2 | port | uint16_t | port number, network byte order |
Hexdump example of Network address structure
Inventory Vectors Inventory vectors are used for notifying other nodes about objects they have or data which is being requested. Inventory vectors consist of the following data format:
4
type
uint32_t
Identifies the object type linked to this inventory
32
hash
char[32]
Hash of the object
The object type is currently defined as one of the following possibilities:
0
ERROR
Any data of with this number may be ignored
1
MSG_TX
Hash is related to a transaction
2
MSG_BLOCK
Hash is related to a data block
3
MSG_FILTERED_BLOCK
Hash of a block header; identical to MSG_BLOCK. Only to be used in getdata message. Indicates the reply should be a merkleblock message rather than a block message; this only works if a bloom filter has been set.
4
MSG_CMPCT_BLOCK
Hash of a block header; identical to MSG_BLOCK. Only to be used in getdata message. Indicates the reply should be a cmpctblock message. See BIP 152 for more info.
Other Data Type values are considered reserved for future implementations.
Block Headers Block headers are sent in a headers packet in response to a getheaders message.
4
version
int32_t
Block version information (note, this is signed)
32
prev_block
char[32]
The hash value of the previous block this particular block references
32
merkle_root
char[32]
The reference to a Merkle tree collection which is a hash of all transactions related to this block
4
timestamp
uint32_t
A timestamp recording when this block was created (Will overflow in 2106https://en.wikipedia.org/wiki/Unix_time#Notable_events_in_Unix_time)
4
bits
uint32_t
The calculated difficulty target being used for this block
4
nonce
uint32_t
The nonce used to generate this block… to allow variations of the header and compute different hashes
1+
txn_count
var_int
Number of transaction entries, this value is always 0
cf. Block hashing algorithm
Differential encoding Several uses of CompactSize below are "differentially encoded". For these, instead of using raw indexes, the number encoded is the difference between the current index and the previous index, minus one. For example, a first index of 0 implies a real index of 0, a second index of 0 thereafter refers to a real index of 1, etc.
PrefilledTransaction A PrefilledTransaction structure is used in HeaderAndShortIDs to provide a list of a few transactions explicitly.
index
CompactSize
1, 3 bytes
Compact Size, differentially encoded since the last PrefilledTransaction in a list
The index into the block at which this transaction is
tx
Transaction
variable
As encoded in tx messages
The transaction which is in the block at index index.
See BIP 152 for more information.
HeaderAndShortIDs A HeaderAndShortIDs structure is used to relay a block header, the short transactions IDs used for matching already-available transactions, and a select few transactions which we expect a peer may be missing.
header
Block header
80 bytes
First 80 bytes of the block as defined by the encoding used by "block" messages
The header of the block being provided
nonce
uint64_t
8 bytes
Little Endian
A nonce for use in short transaction ID calculations
shortids_length
CompactSize
1 or 3 bytes
As used to encode array lengths elsewhere
The number of short transaction IDs in shortids (ie block tx count - prefilledtxn_length)
shortids
List of 6-byte integers
6*shortids_length bytes
Little Endian
The short transaction IDs calculated from the transactions which were not provided explicitly in prefilledtxn
prefilledtxn_length
CompactSize
1 or 3 bytes
As used to encode array lengths elsewhere
The number of prefilled transactions in prefilledtxn (ie block tx count - shortids_length)
prefilledtxn
List of PrefilledTransactions
variable size*prefilledtxn_length
As defined by PrefilledTransaction definition, above
Used to provide the coinbase transaction and a select few which we expect a peer may be missing
See BIP 152 for more information.
BlockTransactionsRequest A BlockTransactionsRequest structure is used to list transaction indexes in a block being requested.
blockhash
Binary blob
32 bytes
The output from a double-SHA256 of the block header, as used elsewhere
The blockhash of the block which the transactions being requested are in
indexes_length
CompactSize
1 or 3 bytes
As used to encode array lengths elsewhere
The number of transactions being requested
indexes
List of CompactSizes
1 or 3 bytes*indexes_length
Differentially encoded
The indexes of the transactions being requested in the block
See BIP 152 for more information.
BlockTransactions A BlockTransactions structure is used to provide some of the transactions in a block, as requested.
blockhash
Binary blob
32 bytes
The output from a double-SHA256 of the block header, as used elsewhere
The blockhash of the block which the transactions being provided are in
transactions_length
CompactSize
1 or 3 bytes
As used to encode array lengths elsewhere
The number of transactions provided
transactions
List of Transactions
variable
As encoded in tx messages
The transactions provided
See BIP 152 for more information.
Short transaction ID Short transaction IDs are used to represent a transaction without sending a full 256-bit hash. They are calculated by:
single-SHA256 hashing the block header with the nonce appended (in little-endian)
Running SipHash-2-4 with the input being the transaction ID and the keys (k0/k1) set to the first two little-endian 64-bit integers from the above hash, respectively.
Dropping the 2 most significant bytes from the SipHash output to make it 6 bytes. See BIP 152 for more information.
Message types
version When a node creates an outgoing connection, it will immediately advertise its version. The remote node will respond with its version. No further communication is possible until both peers have exchanged their version. Payload:
4
version
int32_t
Identifies protocol version being used by the node
8
services
uint64_t
bitfield of features to be enabled for this connection
8
timestamp
int64_t
standard UNIX timestamp in seconds
26
addr_recv
net_addr
The network address of the node receiving this message
Fields below require version ≥ 106
26
addr_from
net_addr
The network address of the node emitting this message
8
nonce
uint64_t
Node random nonce, randomly generated every time a version packet is sent. This nonce is used to detect connections to self.
4
start_height
int32_t
The last block received by the emitting node
Fields below require version ≥ 70001
A "verack" packet shall be sent if the version packet was accepted. The following services are currently assigned:
Hexdump example of version message (OBSOLETE EXAMPLE: This example lacks a checksum and user-agent):
And here's a modern (60002) protocol version client advertising itself to a local peer... Newer protocol includes the checksum now, this is from a mainline (satoshi) client during an outgoing connection to another local client, notice that it does not fill out the address information at all when the source or destination is "unroutable".
verack The verack message is sent in reply to version. This message consists of only a message header with the command string "verack". Hexdump of the verack message:
addr Provide information on known nodes of the network. Non-advertised nodes should be forgotten after typically 3 hours Payload:
4
version
int32_t
Transaction data format version (note, this is signed)
1+
tx_in count
var_int
Number of Transaction inputs (never zero)
41+
tx_in
tx_in[]
A list of 1 or more transaction inputs or sources for coins
1+
tx_out count
var_int
Number of Transaction outputs
9+
tx_out
tx_out[]
A list of 1 or more transaction outputs or destinations for coins
4
lock_time
uint32_t
The block number or timestamp at which this transaction is unlocked: 0 = Not locked, < 500000000 = Block number at which this transaction is unlocked, >= 500000000 = UNIX timestamp at which this transaction is unlocked
TxIn consists of the following fields:
36
previous_output
outpoint
The previous output transaction reference, as an OutPoint structure
1+
script length
var_int
The length of the signature script
?
signature script
uchar[]
Computational Script for confirming transaction authorization
4
sequence
uint32_t
Transaction version as defined by the sender. Intended for "replacement" of transactions when information is updated before inclusion into a block.
The OutPoint structure consists of the following fields:
32
hash
char[32]
The hash of the referenced transaction.
4
index
uint32_t
The index of the specific output in the transaction. The first output is 0, etc.
The Script structure consists of a series of pieces of information and operations related to the value of the transaction. (Structure to be expanded in the future… see script.h and script.cpp and Script for more information) The TxOut structure consists of the following fields:
8
value
int64_t
Transaction Value
1+
pk_script length
var_int
Length of the pk_script
?
pk_script
uchar[]
Contains the ScriptPubKey setting up conditions to claim this output.
Example tx message:
block The block message is sent in response to a getdata message which requests transaction information from a block hash.
4
version
int32_t
Block version information (note, this is signed)
32
prev_block
char[32]
The hash value of the previous block this particular block references
32
merkle_root
char[32]
The reference to a Merkle tree collection which is a hash of all transactions related to this block
4
timestamp
uint32_t
A Unix timestamp recording when this block was created (Currently limited to dates before the year 2106!)
4
bits
uint32_t
The calculated difficulty target being used for this block
4
nonce
uint32_t
The nonce used to generate this block… to allow variations of the header and compute different hashes
1+
txn_count
var_int
Number of transaction entries
?
txns
tx[]
Block transactions, in format of "tx" command
The SHA256 hash that identifies each block (and which must have a run of 0 bits) is calculated from the first 6 fields of this structure (version, prev_block, merkle_root, timestamp, bits, nonce, and standard SHA256 padding, making two 64-byte chunks in all) and not from the complete block. To calculate the hash, only two chunks need to be processed by the SHA256 algorithm. Since the nonce field is in the second chunk, the first chunk stays constant during mining and therefore only the second chunk needs to be processed. However, a Bitcoin hash is the hash of the hash, so two SHA256 rounds are needed for each mining iteration. See Block hashing algorithm for details and an example.
headers The headers packet returns block headers in response to a getheaders packet. Payload:
1+
count
var_int
Number of block headers
81x?
headers
block_header[]
Block headers
Note that the block headers in this packet include a transaction count (a var_int, so there can be more than 81 bytes per header) as opposed to the block headers that are hashed by miners.
getaddr The getaddr message sends a request to a node asking for information about known active peers to help with finding potential nodes in the network. The response to receiving this message is to transmit one or more addr messages with one or more peers from a database of known active peers. The typical presumption is that a node is likely to be active if it has been sending a message within the last three hours. No additional data is transmitted with this message.
mempool The mempool message sends a request to a node asking for information about transactions it has verified but which have not yet confirmed. The response to receiving this message is an inv message containing the transaction hashes for all the transactions in the node's mempool. No additional data is transmitted with this message. It is specified in BIP 35. Since BIP 37, if a bloom filter is loaded, only transactions matching the filter are replied.
checkorder This message was used for IP Transactions. As IP transactions have been deprecated, it is no longer used.
submitorder This message was used for IP Transactions. As IP transactions have been deprecated, it is no longer used.
reply This message was used for IP Transactions. As IP transactions have been deprecated, it is no longer used.
ping The ping message is sent primarily to confirm that the TCP/IP connection is still valid. An error in transmission is presumed to be a closed connection and the address is removed as a current peer. Payload:
8
nonce
uint64_t
random nonce
pong The pong message is sent in response to a ping message. In modern protocol versions, a pong response is generated using a nonce included in the ping. Payload:
8
nonce
uint64_t
nonce from ping
reject The reject message is sent when messages are rejected. Payload:
1+
message
var_str
type of message rejected
1
ccode
char
code relating to rejected message
1+
reason
var_str
text version of reason for rejection
0+
data
char
Optional extra data provided by some errors. Currently, all errors which provide this field fill it with the TXID or block header hash of the object being rejected, so the field is 32 bytes.
CCodes
0x01
REJECT_MALFORMED
0x10
REJECT_INVALID
0x11
REJECT_OBSOLETE
0x12
REJECT_DUPLICATE
0x40
REJECT_NONSTANDARD
0x41
REJECT_DUST
0x42
REJECT_INSUFFICIENTFEE
0x43
REJECT_CHECKPOINT
filterload, filteradd, filterclear, merkleblock These messages are related to Bloom filtering of connections and are defined in BIP 0037. The
filterloadcommand is defined as follows:
?
filter
uint8_t[]
The filter itself is simply a bit field of arbitrary byte-aligned size. The maximum size is 36,000 bytes.
4
nHashFuncs
uint32_t
The number of hash functions to use in this filter. The maximum value allowed in this field is 50.
4
nTweak
uint32_t
A random value to add to the seed value in the hash function used by the bloom filter.
1
nFlags
uint8_t
A set of flags that control how matched items are added to the filter.
See below for a description of the Bloom filter algorithm and how to select nHashFuncs and filter size for a desired false positive rate. Upon receiving a filterload command, the remote peer will immediately restrict the broadcast transactions it announces (in inv packets) to transactions matching the filter, where the matching algorithm is specified below. The flags control the update behaviour of the matching algorithm. The filteradd command is defined as follows:
?
data
uint8_t[]
The data element to add to the current filter.
The data field must be smaller than or equal to 520 bytes in size (the maximum size of any potentially matched object). The given data element will be added to the Bloom filter. A filter must have been previously provided using filterload. This command is useful if a new key or script is added to a clients wallet whilst it has connections to the network open, it avoids the need to re-calculate and send an entirely new filter to every peer (though doing so is usually advisable to maintain anonymity). The filterclear command has no arguments at all. After a filter has been set, nodes don't merely stop announcing non-matching transactions, they can also serve filtered blocks. A filtered block is defined by the merkleblock message and is defined like this:
4
version
int32_t
Block version information, based upon the software version creating this block (note, this is signed)
32
prev_block
char[32]
The hash value of the previous block this particular block references
32
merkle_root
char[32]
The reference to a Merkle tree collection which is a hash of all transactions related to this block
4
timestamp
uint32_t
A timestamp recording when this block was created (Limited to 2106!)
4
bits
uint32_t
The calculated difficulty target being used for this block
4
nonce
uint32_t
The nonce used to generate this block… to allow variations of the header and compute different hashes
4
total_transactions
uint32_t
Number of transactions in the block (including unmatched ones)
1+
hash_count
var_int
The number of hashes to follow
32x?
hashes
char[32]
Hashes in depth-first order
1+
flag_bytes
var_int
The size of flags (in bytes) to follow
?
flags
byte[]
Flag bits, packed per 8 in a byte, least significant bit first. Extra 0 bits are padded on to reach full byte size.
After a merkleblock, transactions matching the bloom filter are automatically sent in tx messages. A guide to creating a bloom filter, loading a merkle block, and parsing a partial merkle block tree can be found in the Developer Examples.
sendheaders Request for Direct headers announcement. Upon receipt of this message, the node is be permitted, but not required, to announce new blocks by headers command (instead of inv command). This message is supported by the protocol version >= 70012 or Bitcoin Core version >= 0.12.0. See BIP 130 for more information. No additional data is transmitted with this message.
feefilter The payload is always 8 bytes long and it encodes 64 bit integer value (LSB / little endian) of feerate. The value represents a minimal fee and is expressed in satoshis per 1000 bytes. Upon receipt of a "feefilter" message, the node will be permitted, but not required, to filter transaction invs for transactions that fall below the feerate provided in the feefilter message interpreted as satoshis per kilobyte. The fee filter is additive with a bloom filter for transactions so if an SPV client were to load a bloom filter and send a feefilter message, transactions would only be relayed if they passed both filters. Inv's generated from a mempool message are also subject to a fee filter if it exists. Feature discovery is enabled by checking protocol version >= 70013 See BIP 133 for more information.
sendcmpct
The sendcmpct message is defined as a message containing a 1-byte integer followed by a 8-byte integer where pchCommand == "sendcmpct".
The first integer SHALL be interpreted as a boolean (and MUST have a value of either 1 or 0)
The second integer SHALL be interpreted as a little-endian version number. Nodes sending a sendcmpct message MUST currently set this value to 1.
Upon receipt of a "sendcmpct" message with the first and second integers set to 1, the node SHOULD announce new blocks by sending a cmpctblock message.
Upon receipt of a "sendcmpct" message with the first integer set to 0, the node SHOULD NOT announce new blocks by sending a cmpctblock message, but SHOULD announce new blocks by sending invs or headers, as defined by BIP130.
Upon receipt of a "sendcmpct" message with the second integer set to something other than 1, nodes MUST treat the peer as if they had not received the message (as it indicates the peer will provide an unexpected encoding in
cmpctblock, and/or other, messages). This allows future versions to send duplicate sendcmpct messages with different versions as a part of a version handshake for future versions.
Nodes SHOULD check for a protocol version of >= 70014 before sending sendcmpct messages.
Nodes MUST NOT send a request for a MSG_CMPCT_BLOCK object to a peer before having received a sendcmpct message from that peer. This message is only supported by protocol version >= 70014 See BIP 152 for more information.
cmpctblock
The cmpctblock message is defined as as a message containing a serialized HeaderAndShortIDs message and pchCommand == "cmpctblock".
Upon receipt of a cmpctblock message after sending a sendcmpct message, nodes SHOULD calculate the short transaction ID for each unconfirmed transaction they have available (ie in their mempool) and compare each to each short transaction ID in the cmpctblock message.
After finding already-available transactions, nodes which do not have all transactions available to reconstruct the full block SHOULD request the missing transactions using a getblocktxn message.
A node MUST NOT send a cmpctblock message unless they are able to respond to a getblocktxn message which requests every transaction in the block.
A node MUST NOT send a cmpctblock message without having validated that the header properly commits to each transaction in the block, and properly builds on top of the existing chain with a valid proof-of-work. A node MAY send a cmpctblock before validating that each transaction in the block validly spends existing UTXO set entries. This message is only supported by protocol version >= 70014 See BIP 152 for more information.
getblocktxn
The getblocktxn message is defined as as a message containing a serialized BlockTransactionsRequest message and pchCommand == "getblocktxn".
Upon receipt of a properly-formatted getblocktxnmessage, nodes which recently provided the sender of such a message a cmpctblock for the block hash identified in this message MUST respond with an appropriate blocktxn message. Such a blocktxn message MUST contain exactly and only each transaction which is present in the appropriate block at the index specified in the getblocktxn indexes list, in the order requested. This message is only supported by protocol version >= 70014 See BIP 152 for more information.
blocktxn
The blocktxn message is defined as as a message containing a serialized BlockTransactions message and pchCommand == "blocktxn".
Upon receipt of a properly-formatted requested blocktxn message, nodes SHOULD attempt to reconstruct the full block by:
Taking the prefilledtxn transactions from the original cmpctblock and placing them in the marked positions.
For each short transaction ID from the original cmpctblock, in order, find the corresponding transaction either from the blocktxn message or from other sources and place it in the first available position in the block.
Once the block has been reconstructed, it shall be processed as normal, keeping in mind that short transaction IDs are expected to occasionally collide, and that nodes MUST NOT be penalized for such collisions, wherever they appear. This message is only supported by protocol version >= 70014 See BIP 152 for more information.
Scripting See Advanced Bitcoin Scripting.
See Also
Network
Attribution This content is based on content sourced from https://en.bitcoin.it/wiki/Protocol_documentation under Creative Commons Attribution 3.0. Although it may have been extensively revised and updated we acknowledge the original authors.
Last updated
