package gate import ( "bytes" "context" "encoding/binary" "net" "testing" "time" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/p2p" ) // TestConnVersionEncoding pins the bytes of a version message from nostrino's // p2p package, which is the client every p2p path in this repository uses. A // node that answers a handshake with a disconnect is usually answering the // bytes, so the bytes are what a test should be holding to the specification. // // The fields are the ones the client sends and in their order: protocol // version, services, time, two net_addr records, nonce, a var-string user // agent, last block and the relay flag. The net_addr records' services field is // eight zero bytes, as the format says; a node fills it in and no node requires // a client to. func TestConnVersionEncoding(t *testing.T) { v := &btcwire.Version{ ProtocolVersion: 70016, Services: 0, Timestamp: 1683837600, // 2023-05-11T20:40:00Z Nonce: 7, UserAgent: "/x:1/", LastBlock: 0, Relay: false, } got, err := v.EncodePayload() if err != nil { t.Fatal(err) } // A hand-assembled frame from the protocol's field list: protocol version // (4), services (8), time (8), addr_recv (26), addr_from (26), nonce (8), // user agent (var), last block (4), relay (1). const fields = 4 + 8 + 8 + 26 + 26 + 8 + 1 + 5 + 4 + 1 if len(got) != fields { t.Fatalf("payload is %d bytes, the field list is %d", len(got), fields) } u32 := func(b []byte) uint32 { return binary.LittleEndian.Uint32(b) } u64 := func(b []byte) uint64 { return binary.LittleEndian.Uint64(b) } if got := u32(got[0:4]); got != 70016 { t.Fatalf("protocol version %d", got) } if got := u64(got[4:12]); got != 0 { t.Fatalf("services %#x", got) } if got := u64(got[12:20]); got != 1683837600 { t.Fatalf("time %d", got) } if got := u64(got[20:28]); got != 0 { t.Fatalf("addr_recv services %#x", got) } if got := u64(got[46:54]); got != 0 { t.Fatalf("addr_from services %#x", got) } if got := u64(got[72:80]); got != 7 { t.Fatalf("nonce %d", got) } if got[80] != 5 || string(got[81:86]) != "/x:1/" { t.Fatalf("user agent %q", got[80:86]) } if got := u32(got[86:90]); got != 0 { t.Fatalf("last block %d", got) } if got[90] != 0 { t.Fatalf("relay %d", got) } } // TestConnHandshakeBytes drives p2p.Conn against a listener this test owns, so // the exact bytes of the version frame the client writes are checked: magic, // command, length, checksum and payload. func TestConnHandshakeBytes(t *testing.T) { ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } defer ln.Close() got := make(chan []byte, 1) go func() { conn, err := ln.Accept() if err != nil { return } defer conn.Close() buf := make([]byte, 4096) _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second)) n, _ := conn.Read(buf) got <- append([]byte(nil), buf[:n]...) // Answer with a version and a verack, so the client's handshake has // what it needs for as long as it needs it. peerVersion := &btcwire.Version{ProtocolVersion: 70016, UserAgent: "/node:1/", Services: btcwire.ServiceNodeNetwork} raw, _ := peerVersion.EncodePayload() frame, _ := btcwire.EncodeMessage(0xDAB5BFFA, btcwire.CmdVersion, raw) _, _ = conn.Write(frame) verack, _ := btcwire.EncodeMessage(0xDAB5BFFA, btcwire.CmdVerAck, nil) _, _ = conn.Write(verack) time.Sleep(200 * time.Millisecond) }() c, err := p2p.DialTCP(context.Background(), ln.Addr().String(), p2p.Config{Magic: 0xDAB5BFFA, UserAgent: "/x:1/"}) if err != nil { t.Fatal(err) } defer c.Close() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() _, _ = c.Handshake(ctx) select { case frame := <-got: if len(frame) < 24 { t.Fatalf("frame of %d bytes", len(frame)) } if magic := frame[0:4]; !bytes.Equal(magic, []byte{0xda, 0xb5, 0xbf, 0xfa}) { t.Fatalf("magic %x", magic) } if cmd := bytes.TrimRight(frame[4:16], "\x00"); string(cmd) != "version" { t.Fatalf("command %q", cmd) } length := binary.LittleEndian.Uint32(frame[16:20]) payload := frame[24:] if int(length) != len(payload) { t.Fatalf("length %d for %d payload bytes", length, len(payload)) } checksum := chainhash.DoubleHashB(payload)[:4] if !bytes.Equal(frame[20:24], checksum) { t.Fatalf("checksum %x, want %x", frame[20:24], checksum) } // The payload is the spec check the other test makes; this one adds the // frame around it. proto := binary.LittleEndian.Uint32(payload[0:4]) if proto < 70001 { t.Fatalf("protocol version %d", proto) } case <-time.After(3 * time.Second): t.Fatal("the client wrote nothing") } } // TestNodeSpeaksEllswift is the measurement the handshake question turns on. // // Since BIP324 a node that has it chooses between the v1 and the v2 handshake // by the first byte a client sends: 0x00 is v2, anything else is v1. A v2 // negotiation starts as an 80-byte ellswift key with no length and no checksum // in front of it, so a reader that reads a frame header first consumes the key // as if it were a header and the node drops the connection. This test sends // both forms and records which one the node answers. func TestNodeSpeaksEllswift(t *testing.T) { addr := p2pAddr(t) // v2: 64 random bytes, which a node takes as an ellswift key. It answers // with its own 64-byte key and then the garbage terminator of the BIP324 // handshake, and nothing of it is a frame. { nc, err := net.Dial("tcp", addr) if err != nil { t.Skipf("no node at %s: %v", addr, err) } key := make([]byte, 64) for i := range key { key[i] = byte(i + 1) } if _, err := nc.Write(key); err != nil { t.Fatal(err) } _ = nc.SetReadDeadline(time.Now().Add(5 * time.Second)) buf := make([]byte, 128) n, err := nc.Read(buf) nc.Close() t.Logf("v2 attempt: node answered %d bytes, err=%v, first=%x", n, err, buf[:minInt(n, 32)]) if n == 0 { t.Fatalf("the node did not answer a v2 ellswift key: it accepts the v1 fallback") } } } func minInt(a, b int) int { if a < b { return a } return b }