/
ping.go
74 lines (62 loc) · 1.53 KB
/
ping.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package vole
import (
"bytes"
"context"
"crypto/rand"
"fmt"
"time"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/p2p/protocol/identify"
"github.com/multiformats/go-multiaddr"
)
func Ping(ctx context.Context, forceRelay bool, p *peer.AddrInfo) error {
if forceRelay {
// We don't want a direct connection, so set this to a high value so
// that we don't learn our public address
identify.ActivationThresh = 100
for _, addr := range p.Addrs {
if _, err := addr.ValueForProtocol(multiaddr.P_CIRCUIT); err != nil {
return fmt.Errorf("force-relay=true but peer is not using a relayed address")
}
}
}
h, err := libp2pHost()
if err != nil {
return err
}
defer h.Close()
h.Connect(ctx, *p)
times := 3
if forceRelay {
ctx = network.WithUseTransient(ctx, "ping")
}
// Reimplementing ping because the default implementation may use a relayed connection instead of a direct one
in := [32]byte{}
out := [32]byte{}
s, err := h.NewStream(ctx, p.ID, "/ipfs/ping/1.0.0")
if err != nil {
return err
}
for i := 0; i < times; i++ {
_, err := rand.Reader.Read(in[:])
if err != nil {
return err
}
start := time.Now()
s.Write(in[:])
n, err := s.Read(out[:])
if err != nil {
return err
}
if n != 32 {
return fmt.Errorf("expected 32 bytes, got %d", n)
}
if !bytes.Equal(in[:], out[:]) {
return fmt.Errorf("expected %x, got %x", in[:], out[:])
}
fmt.Println("Took ", time.Since(start))
time.Sleep(time.Second)
}
return nil
}