package v2peer import ( "context" "io" "net" "os" "testing" "time" "github.com/btcsuite/btcd/wire/v2" ) // TestHandshakeV2WithARealNode is the measurement the whole connection exists // for: the node completes the BIP324 handshake and answers a getheaders. // // The node is the one BTCD_LITE_P2P_TEST names. Without it the test fails // rather than skipping, because a passed handshake is the claim this package // makes and a skip would hide the claim never being made. func TestHandshakeV2WithARealNode(t *testing.T) { addr := os.Getenv("BTCD_LITE_P2P_TEST") if addr == "" { addr = "127.0.0.1:18444" } nc, err := net.DialTimeout("tcp", addr, 5*time.Second) if err != nil { t.Fatalf("no node at %s: %v", addr, err) } defer nc.Close() p, err := Dial(Config{ Conn: nc, Net: wire.TestNet, UserAgent: "/btcd-lite:0.1.0/", Services: wire.SFNodeNetwork, V2: true, Timeout: 20 * time.Second, Logf: t.Logf, }) if err != nil { t.Fatalf("dial and handshake: %v", err) } defer p.Close() if !p.V2() { t.Fatal("the node fell back to v1; BIP324 is the transport this test is for") } t.Logf("negotiated protocol %d over the v2 transport, user agent %q", p.Protocol(), "btcd messages") nonce := uint64(time.Now().UnixNano()) vtrace = func(format string, args ...any) { t.Logf(format, args...) } if err := p.Write(wire.NewMsgPing(nonce)); err != nil { t.Fatal(err) } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() for { select { case <-ctx.Done(): t.Fatal("the node never answered the ping") case m, ok := <-p.Messages(): if !ok { t.Fatalf("the connection ended: %v", p.Err()) } if pong, ok := m.Message.(*wire.MsgPong); ok && pong.Nonce == nonce { return } } } } var _ = io.EOF // TestNodeFirstBytes reports what the node sends before its version, which is // where a handshake that decrypts but does not decode goes wrong. func TestNodeFirstBytes(t *testing.T) { addr := os.Getenv("BTCD_LITE_P2P_TEST") if addr == "" { addr = "127.0.0.1:18444" } nc, err := net.DialTimeout("tcp", addr, 5*time.Second) if err != nil { t.Fatalf("no node at %s: %v", addr, err) } defer nc.Close() vtrace = func(format string, args ...any) { t.Logf(format, args...) } defer func() { vtrace = nil }() _, err = Dial(Config{ Conn: nc, Net: wire.TestNet, UserAgent: "/btcd-lite:0.1.0/", Services: wire.SFNodeNetwork, V2: true, Timeout: 10 * time.Second, }) t.Logf("dial: %v", err) }