diff --git a/lib/only_connect.go b/lib/only_connect.go new file mode 100644 index 0000000..4dd0a42 --- /dev/null +++ b/lib/only_connect.go @@ -0,0 +1,46 @@ +package vole + +import ( + "context" + "fmt" + "time" + + "github.com/libp2p/go-libp2p/core/peer" + "github.com/libp2p/go-libp2p/core/peerstore" + "github.com/libp2p/go-libp2p/p2p/protocol/ping" +) + +func OnlyConnect(ctx context.Context, p *peer.AddrInfo) error { + h, err := libp2pHost() + if err != nil { + return err + } + defer h.Close() + + start := time.Now() + h.Peerstore().AddAddrs(p.ID, p.Addrs, peerstore.TempAddrTTL) + _, err = h.Network().DialPeer(ctx, p.ID) + if err != nil { + return err + } + connectTime := time.Since(start) + fmt.Println("Connect took:", connectTime) + + pingService := ping.NewPingService(h) + ctx, cancel := context.WithCancel(ctx) + defer cancel() + resCh := pingService.Ping(ctx, p.ID) + var avg time.Duration + trials := 3 + for i := 0; i < trials; i++ { + res := <-resCh + if res.Error != nil { + return res.Error + } + avg += res.RTT + } + avg /= time.Duration(trials) + fmt.Println("Average RTT:", avg) + fmt.Println("Number of roundtrips to Connect:", float64(connectTime)/float64(avg)) + return nil +} diff --git a/main.go b/main.go index 6adbb7e..0e5cfca 100644 --- a/main.go +++ b/main.go @@ -366,6 +366,23 @@ Note: may not work with some transports such as p2p-circuit (not applicable) and } return vole.Ping(c.Context, c.Bool("force-relay"), ai) }, + }, { + Name: "connect", + ArgsUsage: "", + Flags: []cli.Flag{}, + Usage: "connect to a peer", + Description: "connects to the target address and pings", + Action: func(c *cli.Context) error { + if c.NArg() != 1 { + return fmt.Errorf("invalid number of arguments") + } + maStr := c.Args().First() + ai, err := peer.AddrInfoFromString(maStr) + if err != nil { + return err + } + return vole.OnlyConnect(c.Context, ai) + }, }, }, },