Files
allmende/internal/p2p/discovery.go
T
nilsandClaude Sonnet 5.5 e7bec4fb63 Add bootstrap nodes, DNS-based discovery, a DHT per region and NAT traversal
- Bootstrap: built-in /dnsaddr/allmende.stinnesbeck.com (TXT records at
  _dnsaddr.<name>), resolved at every redial with the last good answer kept;
  --bootstrap takes /p2p/ or /dnsaddr/ entries, --no-default-bootstrap drops
  the built-in one. Stopping never waits for a stuck resolver.
- Remembered peers in peers.json (saved every 5 min and on shutdown, redialled
  at the next start)
- Private Kademlia DHT (/allmende prefix), advertised and looked up per region
  with quick first attempts and a backoff; --no-dht turns it off
- NAT traversal: port mapping, hole punching, AutoRelay through bootstrap nodes
- --public: DHT server and relay for a bootstrap node; prints the TXT records
- Docker, NixOS module (public, defaultBootstrap, QUIC/UDP) and docs updated
- e2e: bootstrap node scenario, seed cache restart, and polling that really polls

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 22:14:34 +01:00

164 lines
4.3 KiB
Go

package p2p
import (
"context"
"errors"
"sync"
"time"
dht "github.com/libp2p/go-libp2p-kad-dht"
"github.com/libp2p/go-libp2p/core/discovery"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
drouting "github.com/libp2p/go-libp2p/p2p/discovery/routing"
)
const (
// dhtProtocolPrefix keeps this network's DHT apart from every other one
// (the IPFS DHT included): the protocol is /allmende/kad/1.0.0.
dhtProtocolPrefix = "/allmende"
// regionNamespace is what nodes advertise and look up, one per region.
regionNamespace = "allmende/region/"
defaultDiscoverInterval = time.Minute
// enoughRegionPeers: with this many peers on a region's topic there is no
// need to look for more.
enoughRegionPeers = 8
findLimit = 20
)
// startDiscovery joins the DHT and, for every region this node follows,
// advertises the node and looks for others. Bootstrap nodes only seed the
// routing table; once a node knows a few peers it no longer depends on them.
func (n *Node) startDiscovery() error {
mode := dht.ModeAuto // a server once AutoNAT finds this node publicly reachable
if n.cfg.Public {
mode = dht.ModeServer
}
d, err := dht.New(n.host, dht.ProtocolPrefix(dhtProtocolPrefix), dht.Mode(mode))
if err != nil {
return err
}
n.dht = d
rd := drouting.NewRoutingDiscovery(d)
for _, r := range n.cfg.Regions {
ns := regionNamespace + r
n.wg.Add(2)
go n.advertise(rd, ns)
go n.findPeers(rd, r, ns)
}
return nil
}
func (n *Node) discoverInterval() time.Duration {
if n.cfg.DiscoverInterval > 0 {
return n.cfg.DiscoverInterval
}
return defaultDiscoverInterval
}
// sleep waits for d or until the node stops; false means it stopped.
func (n *Node) sleep(d time.Duration) bool {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-n.ctx.Done():
return false
case <-t.C:
return true
}
}
// advertise keeps this node findable under the region's name. Until the
// routing table has a peer in it there is nowhere to publish, so it retries.
func (n *Node) advertise(rd *drouting.RoutingDiscovery, ns string) {
defer n.wg.Done()
back := n.backoff()
for {
wait := back.next()
ctx, cancel := context.WithTimeout(n.ctx, 30*time.Second)
ttl, err := rd.Advertise(ctx, ns)
cancel()
switch {
case n.ctx.Err() != nil:
return
case err != nil:
n.log.Debug("advertise", "ns", ns, "err", err) // retried soon, then less often
back.bump()
case ttl > 0:
wait = ttl * 3 / 4 // refresh before the record lapses
back.reset()
}
if !n.sleep(wait) {
return
}
}
}
// backoff paces retries: quick at first, because a fresh node needs its first
// peers now, then settling on the regular interval.
type backoff struct{ cur, max time.Duration }
func (n *Node) backoff() *backoff {
max := n.discoverInterval()
first := 2 * time.Second
if first > max {
first = max
}
return &backoff{cur: first, max: max}
}
func (b *backoff) next() time.Duration { return b.cur }
func (b *backoff) reset() { b.cur = b.max }
// bump doubles the wait up to the limit.
func (b *backoff) bump() {
if b.cur *= 2; b.cur > b.max {
b.cur = b.max
}
}
// findPeers connects to other nodes of the region that the DHT knows.
func (n *Node) findPeers(rd *drouting.RoutingDiscovery, region, ns string) {
defer n.wg.Done()
back := n.backoff()
for {
if !n.sleep(back.next()) {
return
}
back.bump()
if len(n.RegionPeers(region)) >= enoughRegionPeers {
continue
}
ctx, cancel := context.WithTimeout(n.ctx, 30*time.Second)
found, err := rd.FindPeers(ctx, ns, discovery.Limit(findLimit))
if err != nil {
cancel()
if n.ctx.Err() == nil {
n.log.Debug("find peers", "ns", ns, "err", err)
}
continue
}
var wg sync.WaitGroup
for ai := range found {
if ai.ID == n.host.ID() || len(ai.Addrs) == 0 || n.host.Network().Connectedness(ai.ID) == network.Connected {
continue
}
wg.Add(1)
go func(ai peer.AddrInfo) {
defer wg.Done()
cctx, ccancel := context.WithTimeout(ctx, 10*time.Second)
defer ccancel()
if err := n.host.Connect(cctx, ai); err != nil && !errors.Is(err, context.Canceled) {
n.log.Debug("discovered peer unreachable", "peer", ai.ID, "err", err)
} else if err == nil {
n.log.Debug("found a peer through the DHT", "peer", ai.ID, "region", region)
}
}(ai)
}
wg.Wait()
cancel()
}
}