-
Notifications
You must be signed in to change notification settings - Fork 0
/
notify.go
82 lines (77 loc) · 2.16 KB
/
notify.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
75
76
77
78
79
80
81
82
package main
import (
"fmt"
"log"
"log/slog"
"time"
// We need to import libp2p's libraries that we use in this project.
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/network"
ma "github.com/multiformats/go-multiaddr"
// "github.com/libp2p/go-libp2p/core/routing"
)
func Notify(host host.Host, relay ma.Multiaddr) {
notifiee := &network.NotifyBundle{
ListenF: func(n network.Network, a ma.Multiaddr) {
slog.Info(
"[Listen]",
"ma", fmt.Sprintf("%s/p2p/%s", a, host.ID()),
// "localAddrs", host.Addrs(),
)
for i, addr := range host.Addrs() {
log.Println("localAddr", i, addr)
}
},
ListenCloseF: func(n network.Network, a ma.Multiaddr) {
slog.Info(
"[ListenClose]",
"ma", fmt.Sprintf("%s/p2p/%s", a, host.ID()),
// "localAddrs", host.Addrs(),
)
for i, addr := range host.Addrs() {
log.Println("localAddr", i, addr)
}
for i := 0; ; i++ {
err := n.Listen(relay)
if err == nil {
break
}
log.Println(err, "retry in", i, "seconds")
time.Sleep(time.Duration(i) * time.Second)
}
},
ConnectedF: func(n network.Network, c network.Conn) {
slog.Info(
"[Connected]",
"connId", c.ID(),
"connRemotePeerId", c.RemotePeer(),
"direction", c.Stat().Direction.String(),
// "opened", c.Stat().Opened,
// "peers", host.Peerstore().Peers(),
// "connLocalPeerId", c.LocalPeer(),
// "connLocalMa", c.LocalMultiaddr(),
// "connRemoteMa", c.RemoteMultiaddr(),
)
for i, addr := range host.Peerstore().Peers() {
log.Println("peer", i, addr, n.Connectedness(addr).String())
}
},
DisconnectedF: func(n network.Network, c network.Conn) {
slog.Info(
"[Disconnected]",
"connId", c.ID(),
"connRemotePeerId", c.RemotePeer(),
"direction", c.Stat().Direction.String(),
"opened", c.Stat().Opened,
// "peers", host.Peerstore().Peers(),
// "connLocalPeerId", c.LocalPeer(),
// "connLocalMa", c.LocalMultiaddr(),
// "connRemoteMa", c.RemoteMultiaddr(),
)
for i, addr := range host.Peerstore().Peers() {
log.Println("peer", i, addr, n.Connectedness(addr).String())
}
},
}
host.Network().Notify(notifiee)
}