Understanding the Bitcoin P2P Wire Protocol in Go
Bitcoin peers exchange binary messages over a transport. Legacy v1 framing uses a 24-byte header followed by a payload. This differs from JSON-RPC, which is a separate interface for controlling a node. BIP324 introduces a different encrypted transport.
Go implementation
85func Encode(magic uint32, command string, payload []byte) ([]byte, error) {
86 if !validCommand(command) || len(payload) > MaxPayload {
87 return nil, errors.New("invalid message")
88 }
89 b := make([]byte, 24+len(payload))
90 binary.LittleEndian.PutUint32(b, magic)
91 copy(b[4:16], command)
92 binary.LittleEndian.PutUint32(b[16:20], uint32(len(payload)))
93 c := Checksum(payload)
94 copy(b[20:24], c[:])
95 copy(b[24:], payload)
96 return b, nil
97}Practical exercise
Encode a verack frame and inspect its 24 bytes. No socket connection is needed.
Local verification
From the repository directory golang-bitcoin/005-wire, run:
go test -race -v ./...
1package wirelesson
2
3import (
4 "bytes"
5 "encoding/hex"
6 "testing"
7)
8
9func TestCompact(t *testing.T) {
10 for _, n := range []uint64{0, 252, 253, 65535, 65536, 0xffffffff, 0x100000000, ^uint64(0)} {
11 v, e := ReadCompactSize(bytes.NewReader(CompactSize(n)))
12 if e != nil || v != n {
13 t.Fatal(n, v, e)
14 }
15 }
16 for _, p := range [][]byte{{253, 1, 0}, {254, 1, 0, 0, 0}, {255, 1, 0, 0, 0, 0, 0, 0, 0}, {253, 1}} {
17 if _, e := ReadCompactSize(bytes.NewReader(p)); e == nil {
18 t.Fatal("accepted invalid size")
19 }
20 }
21}
22func TestVerack(t *testing.T) {
23 b, e := Encode(Mainnet, "verack", nil)
24 if e != nil || hex.EncodeToString(b) != "f9beb4d976657261636b000000000000000000005df6e0e2" {
25 t.Fatal(hex.EncodeToString(b), e)
26 }
27 c, p, e := Decode(bytes.NewReader(b), Mainnet)
28 if e != nil || c != "verack" || len(p) != 0 {
29 t.Fatal(c, p, e)
30 }
31}
32func TestPing(t *testing.T) {
33 b, _ := Encode(Testnet3, "ping", NoncePayload(42))
34 c, p, e := Decode(bytes.NewReader(b), Testnet3)
35 n, ne := ReadNonce(p)
36 if e != nil || ne != nil || c != "ping" || n != 42 {
37 t.Fatal(c, n, e, ne)
38 }
39 if _, _, e = Decode(bytes.NewReader(b), Mainnet); e == nil {
40 t.Fatal("wrong network")
41 }
42 if _, _, e = Decode(bytes.NewReader(b[:len(b)-1]), Testnet3); e == nil {
43 t.Fatal("truncated")
44 }
45 b[len(b)-1] ^= 1
46 if _, _, e = Decode(bytes.NewReader(b), Testnet3); e == nil {
47 t.Fatal("corrupt")
48 }
49}
50func TestLimits(t *testing.T) {
51 b, _ := Encode(Mainnet, "ping", nil)
52 b[19] = 255
53 if _, _, e := Decode(bytes.NewReader(b), Mainnet); e == nil {
54 t.Fatal("oversize")
55 }
56 if _, e := Encode(Mainnet, "bad\x00cmd", nil); e == nil {
57 t.Fatal("command")
58 }
59 if _, e := ReadNonce(nil); e == nil {
60 t.Fatal("nonce")
61 }
62}
63func TestVersion(t *testing.T) {
64 p := []byte{0x80, 0x11, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 42, 0, 0, 0, 0, 0, 0, 0}
65 v, s, ts, e := VersionPrefix(p)
66 if e != nil || v != 70016 || s != 1 || ts != 42 {
67 t.Fatal(v, s, ts, e)
68 }
69 if _, _, _, e := VersionPrefix(p[:19]); e == nil {
70 t.Fatal("truncated")
71 }
72}Scope and security
This offline educational library implements legacy v1 framing, CompactSize, nonce payloads and a version prefix only. It does not implement a full peer, encrypted transport, consensus validation or complete message-specific validation. After a decoding error, discard the stream rather than assuming synchronization. Real network clients require deadlines and resource limits.
References
https://developer.bitcoin.org/reference/p2p_networking.html
https://github.com/btcsuite/btcd/tree/master/wire
https://github.com/bitcoin/bips/blob/master/bip-0031.mediawiki
https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki
