2022-09-25 22:04:44 +03:00
|
|
|
package p2p
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2022-09-26 20:23:03 +03:00
|
|
|
"fmt"
|
2022-09-25 22:04:44 +03:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/libp2p/go-libp2p-core/host"
|
|
|
|
"github.com/libp2p/go-libp2p-core/network"
|
|
|
|
"github.com/libp2p/go-libp2p-core/peer"
|
|
|
|
dht "github.com/libp2p/go-libp2p-kad-dht"
|
|
|
|
)
|
|
|
|
|
2022-09-26 23:10:29 +03:00
|
|
|
var discoverNow = make(chan bool)
|
|
|
|
|
2022-09-25 22:04:44 +03:00
|
|
|
// Discover starts up a DHT based discovery system finding and adding nodes with the same rendezvous string.
|
2022-09-26 23:10:29 +03:00
|
|
|
func Discover(ctx context.Context, h host.Host, dht *dht.IpfsDHT, peerTable map[string]peer.ID) {
|
2022-09-26 20:23:03 +03:00
|
|
|
dur := time.Second * 1
|
|
|
|
ticker := time.NewTicker(dur)
|
2022-09-25 22:04:44 +03:00
|
|
|
defer ticker.Stop()
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
2022-09-26 20:23:03 +03:00
|
|
|
case <-discoverNow:
|
|
|
|
dur = time.Second * 1
|
|
|
|
// Immediately trigger discovery
|
|
|
|
ticker.Reset(time.Millisecond * 1)
|
2022-09-25 22:04:44 +03:00
|
|
|
case <-ticker.C:
|
2022-09-26 23:10:29 +03:00
|
|
|
connectedToAny := false
|
2022-09-26 20:23:03 +03:00
|
|
|
for nd, id := range peerTable {
|
2022-09-25 22:04:44 +03:00
|
|
|
if h.Network().Connectedness(id) != network.Connected {
|
|
|
|
addrs, err := dht.FindPeer(ctx, id)
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
2022-09-26 20:50:36 +03:00
|
|
|
conn, err := h.Network().DialPeer(ctx, addrs.ID)
|
2022-09-25 22:04:44 +03:00
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
2022-09-26 20:50:36 +03:00
|
|
|
fmt.Printf("[+] Connected to %s at %s\n", nd, conn.RemoteMultiaddr())
|
2022-09-26 23:10:29 +03:00
|
|
|
connectedToAny = true
|
|
|
|
} else {
|
|
|
|
connectedToAny = true
|
2022-09-25 22:04:44 +03:00
|
|
|
}
|
|
|
|
}
|
2022-09-26 23:10:29 +03:00
|
|
|
if !connectedToAny {
|
|
|
|
fmt.Println("[!] Not connected to any peers, attempting to bootstrap again")
|
|
|
|
Rebootstrap()
|
|
|
|
dur = time.Second * 1
|
|
|
|
ticker.Reset(dur)
|
|
|
|
} else {
|
|
|
|
dur = dur * 2
|
|
|
|
if dur >= time.Second*60 {
|
|
|
|
dur = time.Second * 60
|
|
|
|
}
|
|
|
|
ticker.Reset(dur)
|
2022-09-26 20:23:03 +03:00
|
|
|
}
|
2022-09-25 22:04:44 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-09-26 20:23:03 +03:00
|
|
|
|
2022-09-26 23:10:29 +03:00
|
|
|
func Rediscover() {
|
2022-09-26 20:23:03 +03:00
|
|
|
discoverNow <- true
|
|
|
|
}
|