package main import ( "context" "fmt" "io" "os" "sync" "sync/atomic" "time" "github.com/libp2p/go-libp2p" "github.com/libp2p/go-libp2p/core/host" "github.com/libp2p/go-libp2p/core/network" "github.com/libp2p/go-libp2p/core/peer" "github.com/libp2p/go-libp2p/p2p/host/autorelay" ) const pingProtocol = "/allmende-conns/ping/1" // runRelay measures what a public node pays as a relay: n clients that treat // themselves as unreachable each take a reservation on the node, then pairs of // them talk to each other through it. Each client listens on its own loopback // address (127.0.0.2, 127.0.0.3, …), because the relay limits reservations per // source address and one address would stop it after 8. func runRelay(ctx context.Context, target *peer.AddrInfo, n int, parallel int, hold time.Duration) { var ( mu sync.Mutex hosts []host.Host reserved atomic.Int64 failed atomic.Int64 wg sync.WaitGroup sem = make(chan struct{}, parallel) ) start := time.Now() for i := 0; i < n && ctx.Err() == nil; i++ { sem <- struct{}{} wg.Add(1) go func(i int) { defer wg.Done() defer func() { <-sem }() ip := fmt.Sprintf("127.0.%d.%d", 1+i/250, 2+i%250) h, err := libp2p.New( libp2p.ListenAddrStrings("/ip4/"+ip+"/tcp/0"), libp2p.ForceReachabilityPrivate(), libp2p.EnableAutoRelayWithStaticRelays([]peer.AddrInfo{*target}, autorelay.WithBootDelay(0), autorelay.WithMinCandidates(1), autorelay.WithNumRelays(1)), libp2p.ResourceManager(&network.NullResourceManager{}), ) if err != nil { failed.Add(1) return } h.SetStreamHandler(pingProtocol, func(s network.Stream) { defer s.Close() buf := make([]byte, 4) if _, err := io.ReadFull(s, buf); err == nil { s.Write(buf) } }) cctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() if err := h.Connect(cctx, *target); err != nil { failed.Add(1) h.Close() return } mu.Lock() hosts = append(hosts, h) mu.Unlock() reserved.Add(1) }(i) } wg.Wait() fmt.Printf("%d clients connected to the relay, %d could not, in %s\n", reserved.Load(), failed.Load(), time.Since(start).Round(time.Millisecond)) time.Sleep(3 * time.Second) // let the reservations settle // libp2p does not advertise a relay address built on a loopback IP, so a // reservation cannot be seen from the client. A prober that dials each // client through the relay and exchanges a few bytes shows which ones the // relay really holds a reservation for. // Each client gets a prober of its own (the relay allows 16 open circuits // per peer), and the circuits stay open until the end, as they would for // people who keep talking. var ok, bad atomic.Int64 var pw sync.WaitGroup var probers []host.Host var pmu sync.Mutex psem := make(chan struct{}, 16) for _, b := range hosts { psem <- struct{}{} pw.Add(1) go func() { defer pw.Done() defer func() { <-psem }() prober, err := libp2p.New(libp2p.NoListenAddrs, libp2p.EnableRelay(), libp2p.ResourceManager(&network.NullResourceManager{})) if err != nil { bad.Add(1) return } pmu.Lock() probers = append(probers, prober) pmu.Unlock() if err := pingThrough(ctx, prober, b, target); err != nil { if bad.Add(1) <= 3 { fmt.Fprintln(os.Stderr, "e.g.:", err) } } else { ok.Add(1) } }() } pw.Wait() fmt.Printf("%d of %d clients could be reached through the relay (a reservation held), %d could not\n", ok.Load(), ok.Load()+bad.Load(), bad.Load()) select { case <-ctx.Done(): case <-time.After(hold): } for _, h := range append(hosts, probers...) { h.Close() } } // pingThrough has a dial b by way of the relay and send four bytes. func pingThrough(ctx context.Context, a, b host.Host, relay *peer.AddrInfo) error { ctx, cancel := context.WithTimeout(ctx, 20*time.Second) defer cancel() ctx = network.WithAllowLimitedConn(ctx, "relay measurement") via := relay.Addrs[0].String() + "/p2p/" + relay.ID.String() + "/p2p-circuit" ai, err := peer.AddrInfoFromString(via + "/p2p/" + b.ID().String()) if err != nil { return err } if err := a.Connect(ctx, *ai); err != nil { return fmt.Errorf("dial through the relay: %w", err) } s, err := a.NewStream(ctx, b.ID(), pingProtocol) if err != nil { return fmt.Errorf("stream: %w", err) } defer s.Close() if _, err := s.Write([]byte("ping")); err != nil { return err } buf := make([]byte, 4) if _, err := io.ReadFull(s, buf); err != nil { return err } if string(buf) != "ping" { return fmt.Errorf("answer %q", buf) } return nil }