What you will learn
Every legacy Bitcoin peer-to-peer message starts with a 24-byte header. The header says which network the message belongs to, names the command, declares the payload length, and commits to the payload with a four-byte checksum. Those fields let a node find message boundaries and reject malformed data before interpreting the command itself.
This guide builds a synthetic mainnet ping message and inspects that envelope offline. The payload is an invented eight-byte nonce. No socket opens, no node starts, and no peer receives anything. The program then changes one field at a time and confirms that four malformed messages are rejected.
The field layout is grounded in the tagged Bitcoin Core 32.1 message header, while the mainnet start bytes come from the same release's chain parameters. Bitcoin Core 32.1 is the current published release, announced on the official release page.
Prerequisites
You need Python 3.9 or newer and a text editor. The script uses only hashlib and struct from Python's standard library. Run it in a disposable empty directory. It does not need Bitcoin Core, internet access, credentials, a wallet, or funds.
The exercise checks the outer message envelope. It does not implement a peer handshake or decide whether an eight-byte payload is valid for every negotiated protocol version.
1. Mark the 24-byte boundary
Bitcoin Core serializes four fields before the payload:
- Four message-start bytes identify the network. Mainnet uses
f9beb4d9. Regtest, signet, testnet3, and testnet4 use different values. - Twelve bytes hold a printable ASCII command followed by zero padding. The command
pingbecomes70696e67plus eight zero bytes. - Four little-endian bytes declare the payload length. An eight-byte payload is encoded as
08000000. - Four bytes contain the start of
SHA256(SHA256(payload)).
The payload begins at byte 24. The Bitcoin developer reference documents the same container layout. The exact Bitcoin Core 32.1 class sets the command width to 12, the checksum width to four, and the total header size to 24.
2. Save the checker
Create p2p_header_fixture.py with this code:
import hashlib
import struct
MAINNET_MAGIC = bytes.fromhex("f9beb4d9")
HEADER_SIZE = 24
def checksum(payload: bytes) -> bytes:
return hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
def encode_command(command: str) -> bytes:
encoded = command.encode("ascii")
if not encoded or len(encoded) > 12:
raise ValueError("command must contain 1 to 12 ASCII characters")
if any(byte < 0x20 or byte > 0x7E for byte in encoded):
raise ValueError("command contains a non-printable character")
return encoded.ljust(12, b"\x00")
def build_message(command: str, payload: bytes) -> bytes:
return (
MAINNET_MAGIC
+ encode_command(command)
+ struct.pack("<I", len(payload))
+ checksum(payload)
+ payload
)
def parse_message(raw: bytes, expected_magic: bytes = MAINNET_MAGIC) -> dict:
if len(raw) < HEADER_SIZE:
raise ValueError("message is shorter than the 24-byte header")
magic = raw[:4]
command_field = raw[4:16]
declared_length = struct.unpack("<I", raw[16:20])[0]
declared_checksum = raw[20:24]
payload = raw[24:]
if magic != expected_magic:
raise ValueError("unexpected network magic")
command, separator, padding = command_field.partition(b"\x00")
if separator and any(padding):
raise ValueError("command padding must remain zero after the first zero")
if not command or any(byte < 0x20 or byte > 0x7E for byte in command):
raise ValueError("command must use printable ASCII")
if declared_length != len(payload):
raise ValueError(
f"payload length mismatch: header says {declared_length}, got {len(payload)}"
)
if declared_checksum != checksum(payload):
raise ValueError("payload checksum mismatch")
return {
"magic": magic.hex(),
"command": command.decode("ascii"),
"payload_length": declared_length,
"checksum": declared_checksum.hex(),
"payload": payload.hex(),
}
def expect_rejection(label: str, raw: bytes, expected_text: str) -> None:
try:
parse_message(raw)
except ValueError as error:
if expected_text not in str(error):
raise AssertionError(f"{label}: unexpected error: {error}") from error
print(f"rejected {label}: {error}")
return
raise AssertionError(f"{label}: malformed message was accepted")
nonce = 0x0102030405060708
payload = struct.pack("<Q", nonce)
message = build_message("ping", payload)
expected_hex = (
"f9beb4d9"
"70696e670000000000000000"
"08000000"
"3b5a7513"
"0807060504030201"
)
assert message.hex() == expected_hex
decoded = parse_message(message)
assert decoded == {
"magic": "f9beb4d9",
"command": "ping",
"payload_length": 8,
"checksum": "3b5a7513",
"payload": "0807060504030201",
}
print(decoded)
wrong_magic = bytes.fromhex("fabfb5da") + message[4:]
expect_rejection("wrong network", wrong_magic, "network magic")
wrong_length = message[:16] + struct.pack("<I", 9) + message[20:]
expect_rejection("wrong length", wrong_length, "length mismatch")
bad_padding = message[:9] + b"x" + message[10:]
expect_rejection("non-zero command padding", bad_padding, "padding")
corrupt_payload = message[:-1] + bytes([message[-1] ^ 1])
expect_rejection("corrupt payload", corrupt_payload, "checksum mismatch")
print("all checks passed")
The parser reads fixed offsets only after proving that the 24-byte header exists. It treats the declared payload length as a claim to verify against the bytes actually present. It also verifies the command rule implemented by Bitcoin Core 32.1: bytes must be printable, and every byte after the first zero must remain zero.
3. Run the fixture
From the disposable directory, run:
python3 p2p_header_fixture.py
The expected result is:
{'magic': 'f9beb4d9', 'command': 'ping', 'payload_length': 8, 'checksum': '3b5a7513', 'payload': '0807060504030201'}
rejected wrong network: unexpected network magic
rejected wrong length: payload length mismatch: header says 9, got 8
rejected non-zero command padding: command padding must remain zero after the first zero
rejected corrupt payload: payload checksum mismatch
all checks passed
The exact output matters. A final success line without the four rejection lines would mean the negative controls did not run. An assertion failure means the constructed bytes or one expected value changed.
4. Read the valid message
The output shows each boundary in a form you can compare with a hex viewer:
f9beb4d9is the expected mainnet marker. The parser accepts it because the caller asked for mainnet.pingcomes from the 12-byte command field after its zero padding is removed.8is read as an unsigned little-endian 32-bit integer. It matches the eight bytes after the header.3b5a7513is recalculated from the payload. Changing any payload byte changes this value with overwhelming probability.0807060504030201is the serialized nonce.struct.pack("<Q", nonce)places the least significant byte first.
The checksum detects accidental or malformed payload changes. It is only four bytes long and carries no authentication. Anyone who changes a payload can calculate a matching checksum, so this check does not establish who sent the message or whether the message is safe.
5. Follow the rejected cases
The wrong-network case replaces the first four bytes with the regtest marker fabfb5da. Those bytes are valid for another Bitcoin network, but they are invalid when the parser expects mainnet. A tool must know which network it is inspecting instead of calling any recognized marker acceptable.
The wrong-length case changes the header to claim nine payload bytes while leaving eight. This catches truncation and extra-byte boundary mistakes before a command parser reads the payload.
The command-padding case writes a nonzero byte after the first zero. Bitcoin Core's command validator rejects that shape even though the visible prefix still begins with ping. The checksum case flips the final payload bit without changing the header checksum, so the recomputed value no longer matches.
Troubleshooting
The checksum differs
Confirm that you hashed only the payload, applied SHA-256 twice, and kept the first four digest bytes. Do not reverse the digest for display. Also confirm that the nonce was serialized with <Q, which means an unsigned 64-bit little-endian value.
The length is a large unexpected number
The four-byte length field is little-endian. 08000000 is eight. Reading it as big-endian produces 134,217,728 and moves the expected boundary far beyond this fixture.
A different network marker is present
Choose the expected network deliberately. Bitcoin Core 32.1 defines separate start bytes for mainnet, testnet3, testnet4, signet, and regtest. Do not relabel bytes from one network as another to make a check pass.
A captured message has trailing bytes
This fixture expects exactly one complete message. A network capture may contain multiple messages or a partial stream. Split the stream with the declared length, preserve incomplete data until more bytes arrive, and apply a reasonable size limit before allocating memory. Do not feed an unbounded declared length into an allocation.
Limits
This exercise validates one synthetic envelope and four error paths. It does not connect to a peer, negotiate a protocol version, parse the semantic rules of ping, authenticate a sender, or reproduce Bitcoin Core's full transport limits and denial-of-service protections. Modern peer connections may also use encrypted transport, whose framing is outside this guide.
The fixture was executed with Python 3 in a disposable workspace. It produced the displayed valid fields, rejected all four malformed messages with the expected errors, and ended with all checks passed. No node, socket, wallet, credentials, secrets, real transaction, or funds were used.
Sources
- Bitcoin Core, version 32.1 release
- Bitcoin Core 32.1,
CMessageHeaderfield layout - Bitcoin Core 32.1, command validation
- Bitcoin Core 32.1, network message-start bytes
- Bitcoin developer reference, P2P message headers
