Started Writing Bitcoin Version Handshake
4 Dec 2025
I’ve been studying how Bitcoin version handshake works. After multiple attempts and confusion, it finally does what’s it’s supposed to do. I have added lots of comments to the code and you can find at https://github.com/msolomatin/bitcoinhandshake.
Here’s what I’ve got so far:
- Establish TCP connection with a local Regtest node
BuildVersionPayload,BuildMessage,BuildVerackmethods create header and payload and send it to the TCP connection- Keep exchanging
ping/pongmessages to keep the connection alive
Once I’ve written the code, it didn’t seem overly complicated, however here’re the part I thought worth mentioning:
Handhshake message flow
Surprisingly I haven’t found a message flow diagram on bitcoin website, so I used this diagram as a reference. version and verack messages establish a connection, while ping, pong keep the connection alive.

Message format
Quite straighforward - Bitcoin messages consist of a header and payload. There’s an entire section on p2p networking which documents all fields in great details. It took me some time to figure out encoding version message, although other messages didn’t seem too bad.
Optimised unsigned integer
writeVarIntmethod encodes a user agent field using a Bitcoin-specific data type called compactsize unsigned integers. Which is another name for a variable length integer encoding.
I might extend this solution to connect to a local full node, but I haven’t decided yet.