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>
This commit is contained in:
+97
-26
@@ -21,12 +21,15 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/libp2p/go-libp2p"
|
||||
dht "github.com/libp2p/go-libp2p-kad-dht"
|
||||
pubsub "github.com/libp2p/go-libp2p-pubsub"
|
||||
"github.com/libp2p/go-libp2p/core/crypto"
|
||||
"github.com/libp2p/go-libp2p/core/host"
|
||||
"github.com/libp2p/go-libp2p/core/network"
|
||||
"github.com/libp2p/go-libp2p/core/peer"
|
||||
"github.com/libp2p/go-libp2p/p2p/discovery/mdns"
|
||||
"github.com/libp2p/go-libp2p/p2p/host/autorelay"
|
||||
madns "github.com/multiformats/go-multiaddr-dns"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
@@ -52,9 +55,27 @@ type Config struct {
|
||||
Store *store.Store
|
||||
|
||||
ListenAddrs []string // default: TCP and QUIC on all interfaces, random ports
|
||||
Bootstrap []string // multiaddrs ending in /p2p/<peer id>
|
||||
Regions []string // geohash precision-3 cells to replicate
|
||||
MDNS bool // discover peers on the local network
|
||||
// Bootstrap lists where to find the first peers: multiaddrs ending in
|
||||
// /p2p/<peer id>, or /dnsaddr/<name> (see DefaultBootstrap).
|
||||
Bootstrap []string
|
||||
Regions []string // geohash precision-3 cells to replicate
|
||||
MDNS bool // discover peers on the local network
|
||||
|
||||
// DHT turns on peer discovery through a Kademlia DHT, per region.
|
||||
DHT bool
|
||||
// Public says this node is reachable from the internet (it has a public
|
||||
// address or a forwarded port). It then serves the DHT and acts as a relay
|
||||
// for nodes behind a NAT, which is what a bootstrap node does.
|
||||
Public bool
|
||||
// PeerCache is a file in which the node remembers its peers between runs;
|
||||
// empty turns that off.
|
||||
PeerCache string
|
||||
// Resolver resolves /dnsaddr/ names; the default asks DNS.
|
||||
Resolver *madns.Resolver
|
||||
|
||||
DiscoverInterval time.Duration // how often to look for region peers (default 1 min)
|
||||
RelayBootDelay time.Duration // wait before taking a relay when behind a NAT (default 10s)
|
||||
ForcePrivate bool // treat this node as unreachable; for tests
|
||||
|
||||
Difficulty int // required proof-of-work bits
|
||||
// MessageDifficulty is the proof-of-work bits required of message
|
||||
@@ -83,7 +104,8 @@ type Node struct {
|
||||
topics map[string]*pubsub.Topic
|
||||
msgTopics map[string]*pubsub.Topic
|
||||
subscribed []string
|
||||
bootstrap []peer.AddrInfo
|
||||
boot *bootstrapper
|
||||
dht *dht.IpfsDHT
|
||||
syncing map[peer.ID]bool
|
||||
revTopic *pubsub.Topic
|
||||
}
|
||||
@@ -107,20 +129,47 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
|
||||
if cfg.RedialInterval <= 0 {
|
||||
cfg.RedialInterval = 20 * time.Second
|
||||
}
|
||||
var bootstrap []peer.AddrInfo
|
||||
for _, addr := range cfg.Bootstrap {
|
||||
ai, err := peer.AddrInfoFromString(addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("p2p: bad bootstrap address %q: %w", addr, err)
|
||||
}
|
||||
bootstrap = append(bootstrap, *ai)
|
||||
if cfg.RelayBootDelay <= 0 {
|
||||
cfg.RelayBootDelay = 10 * time.Second
|
||||
}
|
||||
log := cfg.Logger
|
||||
if log == nil {
|
||||
log = slog.Default()
|
||||
}
|
||||
|
||||
priv, err := crypto.UnmarshalEd25519PrivateKey(cfg.Device.Key.PrivateKey())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h, err := libp2p.New(libp2p.Identity(priv), libp2p.ListenAddrStrings(cfg.ListenAddrs...))
|
||||
self, err := peer.IDFromPrivateKey(priv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
boot, err := newBootstrapper(cfg.Bootstrap, cfg.Resolver, self, log)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Reaching nodes behind home routers: map a port on the router when it
|
||||
// allows it, punch holes with the help of a third node, and otherwise take
|
||||
// a reservation on a relay (the bootstrap nodes) so others can find a way in.
|
||||
opts := []libp2p.Option{
|
||||
libp2p.Identity(priv),
|
||||
libp2p.ListenAddrStrings(cfg.ListenAddrs...),
|
||||
libp2p.NATPortMap(),
|
||||
libp2p.EnableHolePunching(),
|
||||
libp2p.EnableAutoRelayWithPeerSource(boot.relayCandidates,
|
||||
autorelay.WithBootDelay(cfg.RelayBootDelay),
|
||||
autorelay.WithMinCandidates(1),
|
||||
autorelay.WithNumRelays(2)),
|
||||
}
|
||||
if cfg.Public {
|
||||
opts = append(opts, libp2p.ForceReachabilityPublic(), libp2p.EnableRelayService(), libp2p.EnableNATService())
|
||||
}
|
||||
if cfg.ForcePrivate {
|
||||
opts = append(opts, libp2p.ForceReachabilityPrivate())
|
||||
}
|
||||
h, err := libp2p.New(opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -130,20 +179,17 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
|
||||
cfg: cfg,
|
||||
host: h,
|
||||
clock: cfg.Clock,
|
||||
log: cfg.Logger,
|
||||
log: log,
|
||||
ctx: nctx,
|
||||
cancel: cancel,
|
||||
topics: map[string]*pubsub.Topic{},
|
||||
msgTopics: map[string]*pubsub.Topic{},
|
||||
syncing: map[peer.ID]bool{},
|
||||
bootstrap: bootstrap,
|
||||
boot: boot,
|
||||
}
|
||||
if n.clock == nil {
|
||||
n.clock = time.Now
|
||||
}
|
||||
if n.log == nil {
|
||||
n.log = slog.Default()
|
||||
}
|
||||
|
||||
// Flood-publish: the origin sends to every subscribed peer instead of only
|
||||
// its mesh. Regional topics are small, and without it a listing published
|
||||
@@ -171,7 +217,12 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
|
||||
ConnectedF: func(_ network.Network, c network.Conn) { n.syncSoon(c.RemotePeer()) },
|
||||
})
|
||||
|
||||
n.dialBootstrap()
|
||||
if cfg.DHT {
|
||||
if err := n.startDiscovery(); err != nil {
|
||||
n.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if cfg.MDNS {
|
||||
n.mdns = mdns.NewMdnsService(h, mdnsService, &mdnsNotifee{n: n})
|
||||
if err := n.mdns.Start(); err != nil {
|
||||
@@ -180,9 +231,17 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
|
||||
}
|
||||
}
|
||||
|
||||
n.wg.Add(2)
|
||||
// Finding the first peers can take a while (DNS, unreachable servers), so it
|
||||
// does not hold up starting the node.
|
||||
n.wg.Add(4)
|
||||
go func() {
|
||||
defer n.wg.Done()
|
||||
n.dialBootstrap()
|
||||
n.dialCached()
|
||||
}()
|
||||
go n.maintain()
|
||||
go n.redial()
|
||||
go n.remember()
|
||||
return n, nil
|
||||
}
|
||||
|
||||
@@ -272,6 +331,9 @@ func (n *Node) Close() error {
|
||||
n.mdns.Close()
|
||||
}
|
||||
n.wg.Wait()
|
||||
if n.dht != nil {
|
||||
n.dht.Close()
|
||||
}
|
||||
return n.host.Close()
|
||||
}
|
||||
|
||||
@@ -540,15 +602,24 @@ func (m *mdnsNotifee) HandlePeerFound(pi peer.AddrInfo) {
|
||||
// dialBootstrap connects to every configured bootstrap peer we are not
|
||||
// already connected to.
|
||||
func (n *Node) dialBootstrap() {
|
||||
for _, ai := range n.bootstrap {
|
||||
var wg sync.WaitGroup
|
||||
for _, ai := range n.boot.peers(n.ctx) {
|
||||
if n.host.Network().Connectedness(ai.ID) == network.Connected {
|
||||
continue
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(n.ctx, 10*time.Second)
|
||||
if err := n.host.Connect(ctx, ai); err != nil {
|
||||
n.log.Warn("bootstrap peer unreachable", "peer", ai.ID, "err", err)
|
||||
}
|
||||
cancel()
|
||||
wg.Add(1)
|
||||
go func(ai peer.AddrInfo) {
|
||||
defer wg.Done()
|
||||
ctx, cancel := context.WithTimeout(n.ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
if err := n.host.Connect(ctx, ai); err != nil && n.ctx.Err() == nil {
|
||||
n.log.Warn("bootstrap peer unreachable", "peer", ai.ID, "err", err)
|
||||
}
|
||||
}(ai)
|
||||
}
|
||||
wg.Wait()
|
||||
if n.dht != nil {
|
||||
n.dht.Bootstrap(n.ctx) // fill the routing table from whoever answered
|
||||
}
|
||||
}
|
||||
|
||||
@@ -556,7 +627,7 @@ func (n *Node) dialBootstrap() {
|
||||
// network outages on either side.
|
||||
func (n *Node) redial() {
|
||||
defer n.wg.Done()
|
||||
if len(n.bootstrap) == 0 {
|
||||
if n.boot.empty() {
|
||||
return
|
||||
}
|
||||
t := time.NewTicker(n.cfg.RedialInterval)
|
||||
|
||||
Reference in New Issue
Block a user