1 package gate
2 3 import (
4 "bytes"
5 "context"
6 "encoding/binary"
7 "net"
8 "testing"
9 "time"
10 11 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
12 13 "git.smesh.lol/nostrino/pkg/btcwire"
14 "git.smesh.lol/nostrino/pkg/p2p"
15 )
16 17 // TestConnVersionEncoding pins the bytes of a version message from nostrino's
18 // p2p package, which is the client every p2p path in this repository uses. A
19 // node that answers a handshake with a disconnect is usually answering the
20 // bytes, so the bytes are what a test should be holding to the specification.
21 //
22 // The fields are the ones the client sends and in their order: protocol
23 // version, services, time, two net_addr records, nonce, a var-string user
24 // agent, last block and the relay flag. The net_addr records' services field is
25 // eight zero bytes, as the format says; a node fills it in and no node requires
26 // a client to.
27 func TestConnVersionEncoding(t *testing.T) {
28 v := &btcwire.Version{
29 ProtocolVersion: 70016,
30 Services: 0,
31 Timestamp: 1683837600, // 2023-05-11T20:40:00Z
32 Nonce: 7,
33 UserAgent: "/x:1/",
34 LastBlock: 0,
35 Relay: false,
36 }
37 got, err := v.EncodePayload()
38 if err != nil {
39 t.Fatal(err)
40 }
41 // A hand-assembled frame from the protocol's field list: protocol version
42 // (4), services (8), time (8), addr_recv (26), addr_from (26), nonce (8),
43 // user agent (var), last block (4), relay (1).
44 const fields = 4 + 8 + 8 + 26 + 26 + 8 + 1 + 5 + 4 + 1
45 if len(got) != fields {
46 t.Fatalf("payload is %d bytes, the field list is %d", len(got), fields)
47 }
48 u32 := func(b []byte) uint32 { return binary.LittleEndian.Uint32(b) }
49 u64 := func(b []byte) uint64 { return binary.LittleEndian.Uint64(b) }
50 if got := u32(got[0:4]); got != 70016 {
51 t.Fatalf("protocol version %d", got)
52 }
53 if got := u64(got[4:12]); got != 0 {
54 t.Fatalf("services %#x", got)
55 }
56 if got := u64(got[12:20]); got != 1683837600 {
57 t.Fatalf("time %d", got)
58 }
59 if got := u64(got[20:28]); got != 0 {
60 t.Fatalf("addr_recv services %#x", got)
61 }
62 if got := u64(got[46:54]); got != 0 {
63 t.Fatalf("addr_from services %#x", got)
64 }
65 if got := u64(got[72:80]); got != 7 {
66 t.Fatalf("nonce %d", got)
67 }
68 if got[80] != 5 || string(got[81:86]) != "/x:1/" {
69 t.Fatalf("user agent %q", got[80:86])
70 }
71 if got := u32(got[86:90]); got != 0 {
72 t.Fatalf("last block %d", got)
73 }
74 if got[90] != 0 {
75 t.Fatalf("relay %d", got)
76 }
77 }
78 79 // TestConnHandshakeBytes drives p2p.Conn against a listener this test owns, so
80 // the exact bytes of the version frame the client writes are checked: magic,
81 // command, length, checksum and payload.
82 func TestConnHandshakeBytes(t *testing.T) {
83 ln, err := net.Listen("tcp", "127.0.0.1:0")
84 if err != nil {
85 t.Fatal(err)
86 }
87 defer ln.Close()
88 got := make(chan []byte, 1)
89 go func() {
90 conn, err := ln.Accept()
91 if err != nil {
92 return
93 }
94 defer conn.Close()
95 buf := make([]byte, 4096)
96 _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second))
97 n, _ := conn.Read(buf)
98 got <- append([]byte(nil), buf[:n]...)
99 // Answer with a version and a verack, so the client's handshake has
100 // what it needs for as long as it needs it.
101 peerVersion := &btcwire.Version{ProtocolVersion: 70016, UserAgent: "/node:1/", Services: btcwire.ServiceNodeNetwork}
102 raw, _ := peerVersion.EncodePayload()
103 frame, _ := btcwire.EncodeMessage(0xDAB5BFFA, btcwire.CmdVersion, raw)
104 _, _ = conn.Write(frame)
105 verack, _ := btcwire.EncodeMessage(0xDAB5BFFA, btcwire.CmdVerAck, nil)
106 _, _ = conn.Write(verack)
107 time.Sleep(200 * time.Millisecond)
108 }()
109 c, err := p2p.DialTCP(context.Background(), ln.Addr().String(), p2p.Config{Magic: 0xDAB5BFFA, UserAgent: "/x:1/"})
110 if err != nil {
111 t.Fatal(err)
112 }
113 defer c.Close()
114 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
115 defer cancel()
116 _, _ = c.Handshake(ctx)
117 select {
118 case frame := <-got:
119 if len(frame) < 24 {
120 t.Fatalf("frame of %d bytes", len(frame))
121 }
122 if magic := frame[0:4]; !bytes.Equal(magic, []byte{0xda, 0xb5, 0xbf, 0xfa}) {
123 t.Fatalf("magic %x", magic)
124 }
125 if cmd := bytes.TrimRight(frame[4:16], "\x00"); string(cmd) != "version" {
126 t.Fatalf("command %q", cmd)
127 }
128 length := binary.LittleEndian.Uint32(frame[16:20])
129 payload := frame[24:]
130 if int(length) != len(payload) {
131 t.Fatalf("length %d for %d payload bytes", length, len(payload))
132 }
133 checksum := chainhash.DoubleHashB(payload)[:4]
134 if !bytes.Equal(frame[20:24], checksum) {
135 t.Fatalf("checksum %x, want %x", frame[20:24], checksum)
136 }
137 // The payload is the spec check the other test makes; this one adds the
138 // frame around it.
139 proto := binary.LittleEndian.Uint32(payload[0:4])
140 if proto < 70001 {
141 t.Fatalf("protocol version %d", proto)
142 }
143 case <-time.After(3 * time.Second):
144 t.Fatal("the client wrote nothing")
145 }
146 }
147 148 // TestNodeSpeaksEllswift is the measurement the handshake question turns on.
149 //
150 // Since BIP324 a node that has it chooses between the v1 and the v2 handshake
151 // by the first byte a client sends: 0x00 is v2, anything else is v1. A v2
152 // negotiation starts as an 80-byte ellswift key with no length and no checksum
153 // in front of it, so a reader that reads a frame header first consumes the key
154 // as if it were a header and the node drops the connection. This test sends
155 // both forms and records which one the node answers.
156 func TestNodeSpeaksEllswift(t *testing.T) {
157 addr := p2pAddr(t)
158 // v2: 64 random bytes, which a node takes as an ellswift key. It answers
159 // with its own 64-byte key and then the garbage terminator of the BIP324
160 // handshake, and nothing of it is a frame.
161 {
162 nc, err := net.Dial("tcp", addr)
163 if err != nil {
164 t.Skipf("no node at %s: %v", addr, err)
165 }
166 key := make([]byte, 64)
167 for i := range key {
168 key[i] = byte(i + 1)
169 }
170 if _, err := nc.Write(key); err != nil {
171 t.Fatal(err)
172 }
173 _ = nc.SetReadDeadline(time.Now().Add(5 * time.Second))
174 buf := make([]byte, 128)
175 n, err := nc.Read(buf)
176 nc.Close()
177 t.Logf("v2 attempt: node answered %d bytes, err=%v, first=%x", n, err, buf[:minInt(n, 32)])
178 if n == 0 {
179 t.Fatalf("the node did not answer a v2 ellswift key: it accepts the v1 fallback")
180 }
181 }
182 }
183 184 func minInt(a, b int) int {
185 if a < b {
186 return a
187 }
188 return b
189 }
190