package v2peer import ( "io" "net" "testing" "time" "github.com/btcsuite/btcd/v2transport" ) // countingConn records the size of every read. type countingConn struct { net.Conn reads []int } func (c *countingConn) Read(p []byte) (int, error) { n, err := c.Conn.Read(p) c.reads = append(c.reads, n) return n, err } // TestLoopbackHandshake runs two btcd peers over a real loopback TCP socket, // which is the connection the daemon has and a channel is not. func TestLoopbackHandshake(t *testing.T) { ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Skipf("no loopback: %v", err) } defer ln.Close() type accepted struct { c net.Conn e error } got := make(chan accepted, 1) go func() { c, err := ln.Accept() got <- accepted{c, err} }() client, err := net.Dial("tcp", ln.Addr().String()) if err != nil { t.Fatal(err) } defer client.Close() acc := <-got if acc.e != nil { t.Fatal(acc.e) } defer acc.c.Close() cc := &countingConn{Conn: client} sc := &countingConn{Conn: acc.c} init := v2transport.NewPeer() init.UseReadWriter(cc) resp := v2transport.NewPeer() resp.UseReadWriter(sc) const netMagic = v2transport.BitcoinNet(0xdab5bffa) done := make(chan error, 2) go func() { if err := init.InitiateV2Handshake(0); err != nil { done <- err return } done <- init.CompleteHandshake(true, []int{0, 0}, netMagic) }() go func() { if err := resp.RespondV2Handshake(0, netMagic); err != nil { done <- err return } done <- resp.CompleteHandshake(false, []int{0}, netMagic) }() for i := 0; i < 2; i++ { select { case err := <-done: if err != nil { t.Fatalf("handshake: %v", err) } case <-time.After(10 * time.Second): t.Fatalf("the handshake did not finish over loopback; initiator reads %v", cc.reads) } } t.Logf("loopback: initiator reads %v, responder reads %v", cc.reads, sc.reads) // And with a peer that writes its terminator and packet in one send, the // way Bitcoin Core does: a proxy in the middle that joins the writes. _ = time.Now _ = io.EOF }