package v2peer import ( "bytes" "sync" "testing" "time" "github.com/btcsuite/btcd/v2transport" ) // testWire is a one-way pipe: writers append, the reader takes everything // queued at once. type testWire struct { in chan []byte buf bytes.Buffer reads []int mu sync.Mutex } type peerConn struct { r *testWire w chan []byte } func (c *peerConn) Read(p []byte) (int, error) { // Wait for junk to form: a socket does not hand a peer the wire one write // at a time, it hands over whatever has arrived, so a reader that comes // back for more than the current buffer gets the queued writes too. time.Sleep(2 * time.Millisecond) if c.r.buf.Len() == 0 { select { case chunk := <-c.r.in: c.r.buf.Write(chunk) case <-time.After(5 * time.Second): return 0, bytes.ErrTooLarge } for { select { case more := <-c.r.in: c.r.buf.Write(more) continue default: } break } } n, err := c.r.buf.Read(p) c.r.mu.Lock() c.r.reads = append(c.r.reads, n) c.r.mu.Unlock() return n, err } func (c *peerConn) Write(p []byte) (int, error) { c.w <- append([]byte(nil), p...) return len(p), nil } func newPair() (*peerConn, *peerConn, chan []byte, chan []byte) { x := make(chan []byte, 128) y := make(chan []byte, 128) initSide := &peerConn{r: &testWire{in: y}, w: x} respSide := &peerConn{r: &testWire{in: x}, w: y} return initSide, respSide, x, y } // TestBothPeersHandshakeCoalesced runs two of btcd's peers over a connection // whose reads coalesce, with and without decoy packets. If one of the pairs // hangs, this is the daemon gate's failure reproduced without a node. func TestBothPeersHandshakeCoalesced(t *testing.T) { for _, decoys := range []int{0, 3} { initSide, respSide, _, _ := newPair() init := v2transport.NewPeer() init.UseReadWriter(initSide) resp := v2transport.NewPeer() resp.UseReadWriter(respSide) const net = v2transport.BitcoinNet(0xdab5bffa) done := make(chan error, 2) decoyLens := make([]int, decoys) go func() { if err := init.InitiateV2Handshake(0); err != nil { done <- err return } done <- init.CompleteHandshake(true, decoyLens, net) }() go func() { if err := resp.RespondV2Handshake(0, net); err != nil { done <- err return } done <- resp.CompleteHandshake(false, decoyLens, net) }() ok := 0 for i := 0; i < 2; i++ { select { case err := <-done: if err == nil { ok++ continue } t.Fatalf("%d decoys: %v", decoys, err) case <-time.After(5 * time.Second): // Report the read pattern so the failure is the terminator's. initSide.r.mu.Lock() reads := append([]int(nil), initSide.r.reads...) initSide.r.mu.Unlock() t.Fatalf("%d decoys: the handshake did not finish; initiator reads %v", decoys, reads) } } t.Logf("%d decoys: both sides done, initiator reads %v", decoys, readSizes(initSide.r)) } } func readSizes(w *testWire) []int { w.mu.Lock() defer w.mu.Unlock() return append([]int(nil), w.reads...) }