package bridge import ( "bytes" "context" "io" "net" "testing" "time" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/chain" "git.smesh.lol/nostrino/pkg/crypto/chainhash" ) // nodeScript is a node's socket driven by the test: it accepts, runs body, and stops. func nodeScript(t *testing.T, magic uint32, body func(net.Conn, *btcwire.Reader)) string { t.Helper() ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } t.Cleanup(func() { ln.Close() }) go func() { conn, err := ln.Accept() if err != nil { return } defer conn.Close() body(conn, btcwire.NewReader(conn, magic)) }() return ln.Addr().String() } // runSession drives one client against the gateway and returns when the session ends. func runSession(srv *Server, chainName string, client func(net.Conn)) time.Duration { clientConn, serverConn := net.Pipe() done := make(chan struct{}) start := time.Now() go func() { defer close(done) defer serverConn.Close() srv.handleConn(context.Background(), serverConn, chainName, "test:"+chainName) }() go func() { client(clientConn) }() <-done clientConn.Close() return time.Since(start) } func quietServer(address string, magic uint32) *Server { return &Server{ cfg: Config{ Nodes: map[string]Node{ "alpha": {Addr: address, Profile: &chain.Profile{Name: "alpha", Magic: magic}}, }, NodeDialTimeout: 2 * time.Second, IdleTimeout: 2 * time.Second, Logf: func(string, ...any) {}, }, conns: make(map[net.Conn]struct{}), wsPerIP: make(map[string]int), done: make(chan struct{}), } } const testMagic uint32 = 0xdab5bffa // TestAFailedSessionDoesNotStopTheGateway: a node that closes mid-session ends that session, and // the next client is still served. This is the shape of the failure that matters: one bad peer // must not take the gateway down for everyone. func TestAFailedSessionDoesNotStopTheGateway(t *testing.T) { magic := testMagic var sessions int address := nodeScript(t, magic, func(conn net.Conn, reader *btcwire.Reader) { sessions++ // Read one frame, answer, then drop the connection, as a restarted node would. if _, err := reader.Next(); err != nil { return } frame, err := btcwire.EncodeMessage(magic, btcwire.CmdHeaders, nil) if err == nil { _, _ = conn.Write(frame) } }) srv := quietServer(address, magic) // The first session is dropped by the node. runSession(srv, "alpha", func(client net.Conn) { frame, _ := btcwire.EncodeMessage(magic, btcwire.CmdGetHeaders, nil) _, _ = client.Write(frame) // Wait for the node's reply or the close, whichever comes first. _, _ = io.ReadAll(client) }) if sessions == 0 { t.Fatal("the node was never dialed") } // The second session still works: the gateway did not exit or wedge itself. reader := make(chan string, 1) second := nodeScript(t, magic, func(conn net.Conn, r *btcwire.Reader) { msg, err := r.Next() if err != nil { return } reader <- msg.Command }) srv.cfg.Nodes["alpha"] = Node{Addr: second, Profile: &chain.Profile{Name: "alpha", Magic: magic}} runSession(srv, "alpha", func(client net.Conn) { frame, _ := btcwire.EncodeMessage(magic, btcwire.CmdGetHeaders, nil) _, _ = client.Write(frame) time.Sleep(200 * time.Millisecond) }) select { case command := <-reader: if command != btcwire.CmdGetHeaders { t.Fatalf("second session forwarded %q", command) } case <-time.After(2 * time.Second): t.Fatal("the second session never reached the node, so the gateway stopped serving") } } // TestAnUnknownChainNeverReachesANode: a client cannot make the gateway dial an arbitrary address by // naming a chain it does not serve. func TestAnUnknownChainNeverReachesANode(t *testing.T) { dialed := make(chan struct{}, 1) address := nodeScript(t, testMagic, func(conn net.Conn, reader *btcwire.Reader) { dialed <- struct{}{} }) srv := quietServer(address, testMagic) runSession(srv, "ghost", func(client net.Conn) { time.Sleep(100 * time.Millisecond) }) select { case <-dialed: t.Fatal("a node was dialed for a chain the gateway does not serve") case <-time.After(200 * time.Millisecond): } } // TestMalformedFramesEndOneSessionOnly: garbage from a client is its own problem. The test process // would die on an unhandled panic, so surviving this is the assertion. func TestMalformedFramesEndOneSessionOnly(t *testing.T) { magic := testMagic address := nodeScript(t, magic, func(conn net.Conn, reader *btcwire.Reader) { _, _ = reader.Next() }) srv := quietServer(address, magic) for _, junk := range [][]byte{ bytes.Repeat([]byte{0xff}, 64), // never a valid frame {0xfa, 0xbf, 0xb5, 0xda, 0x67, 0x65, 0x74, 0x68}, // right magic, truncated command {0xfa, 0xbf, 0xb5, 0xda}, // magic only } { runSession(srv, "alpha", func(client net.Conn) { _, _ = client.Write(junk) time.Sleep(50 * time.Millisecond) }) } } // TestACommandOutsideTheAllowlistIsNotForwarded: the gateway forwards the handshake and block data // it was told to forward, and nothing else, even if a client asks. func TestACommandOutsideTheAllowlistIsNotForwarded(t *testing.T) { magic := testMagic seen := make(chan string, 4) address := nodeScript(t, magic, func(conn net.Conn, reader *btcwire.Reader) { for { msg, err := reader.Next() if err != nil { return } seen <- msg.Command } }) srv := quietServer(address, magic) runSession(srv, "alpha", func(client net.Conn) { // addrv2 is not in DefaultCommands: address discovery is never forwarded, and no // allow list was configured to add it. frame, _ := btcwire.EncodeMessage(magic, "addrv2", nil) _, _ = client.Write(frame) time.Sleep(200 * time.Millisecond) }) select { case command := <-seen: if command == "addrv2" { t.Fatal("a command outside the allowlist was forwarded") } case <-time.After(200 * time.Millisecond): } } // TestASilentNodeEndsTheSession: a node that accepts and says nothing must not hold a client // forever. The session ends by the idle bound instead of hanging. func TestASilentNodeEndsTheSession(t *testing.T) { magic := testMagic address := nodeScript(t, magic, func(conn net.Conn, reader *btcwire.Reader) { // Accept and stay silent, which is what a wedged node looks like. time.Sleep(10 * time.Second) }) srv := quietServer(address, magic) srv.cfg.IdleTimeout = 500 * time.Millisecond start := time.Now() runSession(srv, "alpha", func(client net.Conn) { frame, _ := btcwire.EncodeMessage(magic, btcwire.CmdGetHeaders, nil) _, _ = client.Write(frame) time.Sleep(3 * time.Second) }) if elapsed := time.Since(start); elapsed > 3*time.Second { t.Fatalf("a silent node held the session for %s", elapsed) } } // TestANodeThatIsNotListeningDoesNotBlockTheGateway: dial failure is a session failure. func TestANodeThatIsNotListeningDoesNotBlockTheGateway(t *testing.T) { srv := quietServer("127.0.0.1:1", testMagic) srv.cfg.NodeDialTimeout = 500 * time.Millisecond elapsed := runSession(srv, "alpha", func(client net.Conn) { time.Sleep(200 * time.Millisecond) }) if elapsed > 2*time.Second { t.Fatalf("a dead node held the session for %s", elapsed) } } // TestBlockRequestsAreSerialisedPerSession: a client that asks for several blocks // at once gets them one at a time. // // A block is the fattest thing a tunnel carries, and a wallet that asked for ten // would put megabytes into the relay's outbound queue behind its own coordination // traffic. The gateway splits the getdata and holds each request until the previous // block has been forwarded; this test is the ordering evidence. func TestBlockRequestsAreSerialisedPerSession(t *testing.T) { magic := testMagic type request struct { count int at time.Time } seen := make(chan request, 8) blocks := make(chan time.Time, 8) address := nodeScript(t, magic, func(conn net.Conn, reader *btcwire.Reader) { for { msg, err := reader.Next() if err != nil { return } if msg.Command != btcwire.CmdGetData { continue } var getdata btcwire.GetData if err := getdata.DecodePayload(msg.Payload); err != nil { return } seen <- request{count: len(getdata.InvList), at: time.Now()} frame, err := btcwire.EncodeMessage(magic, btcwire.CmdBlock, []byte{0x01}) if err != nil { return } if _, err := conn.Write(frame); err != nil { return } blocks <- time.Now() } }) srv := quietServer(address, magic) srv.cfg.Logf = t.Logf runSession(srv, "alpha", func(client net.Conn) { request := btcwire.GetData{InvList: []btcwire.InvVect{ {Type: btcwire.InvVectTypeWitnessBlock, Hash: chainhash.Hash{1}}, {Type: btcwire.InvVectTypeWitnessBlock, Hash: chainhash.Hash{2}}, }} payload, err := request.EncodePayload() if err != nil { return } frame, err := btcwire.EncodeMessage(magic, btcwire.CmdGetData, payload) if err != nil { return } if _, err := client.Write(frame); err != nil { return } // Two blocks come back; read them so the session is not closed by the // client's own idle read deadline. reader := btcwire.NewReader(client, magic) for i := 0; i < 2; i++ { if _, err := reader.Next(); err != nil { return } } time.Sleep(100 * time.Millisecond) }) first := <-seen if first.count == -1 { t.Fatal("the node was dialed but no getdata reached it") } second := <-seen if first.count != 1 || second.count != 1 { t.Fatalf("the node saw getdata requests of %d and %d inventories, want one each", first.count, second.count) } firstBlock := <-blocks secondBlock := <-blocks if !second.at.After(firstBlock) { t.Fatalf("the second block was requested %s before the first was answered", firstBlock.Sub(second.at)) } if !secondBlock.After(firstBlock) { t.Fatal("the node answered the two requests out of order") } }