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:
@@ -0,0 +1,185 @@
|
||||
package p2p
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/libp2p/go-libp2p/core/peer"
|
||||
ma "github.com/multiformats/go-multiaddr"
|
||||
madns "github.com/multiformats/go-multiaddr-dns"
|
||||
)
|
||||
|
||||
// DefaultBootstrap is where a fresh node finds its first peers. libp2p reads
|
||||
// the TXT records of _dnsaddr.<name>, each of the form
|
||||
//
|
||||
// dnsaddr=/ip4/203.0.113.5/tcp/4001/p2p/12D3KooW...
|
||||
//
|
||||
// so the list of bootstrap nodes can change without a new release.
|
||||
const DefaultBootstrap = "/dnsaddr/allmende.stinnesbeck.com"
|
||||
|
||||
const resolveTimeout = 10 * time.Second
|
||||
|
||||
// bootstrapper turns the configured bootstrap addresses into peers. An entry is
|
||||
// either a full /p2p/ address or a /dnsaddr/ name; names are resolved every
|
||||
// time (so new servers are picked up), and the last good answer is kept in case
|
||||
// DNS is briefly unreachable.
|
||||
type bootstrapper struct {
|
||||
entries []ma.Multiaddr
|
||||
resolver *madns.Resolver
|
||||
self peer.ID
|
||||
log *slog.Logger
|
||||
|
||||
mu sync.Mutex
|
||||
cache map[string][]peer.AddrInfo // last good resolution per entry
|
||||
failed map[string]bool // entries that failed last time, so it is said once
|
||||
}
|
||||
|
||||
func newBootstrapper(addrs []string, r *madns.Resolver, self peer.ID, log *slog.Logger) (*bootstrapper, error) {
|
||||
if r == nil {
|
||||
r = madns.DefaultResolver
|
||||
}
|
||||
b := &bootstrapper{
|
||||
resolver: r, self: self, log: log,
|
||||
cache: map[string][]peer.AddrInfo{}, failed: map[string]bool{},
|
||||
}
|
||||
for _, a := range addrs {
|
||||
m, err := ma.NewMultiaddr(a)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("p2p: bad bootstrap address %q: %w", a, err)
|
||||
}
|
||||
if !isDNSAddr(m) {
|
||||
if _, err := peer.AddrInfoFromP2pAddr(m); err != nil {
|
||||
return nil, fmt.Errorf("p2p: bad bootstrap address %q: %w (want /p2p/<peer id> or /dnsaddr/<name>)", a, err)
|
||||
}
|
||||
}
|
||||
b.entries = append(b.entries, m)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func isDNSAddr(m ma.Multiaddr) bool {
|
||||
_, err := m.ValueForProtocol(ma.P_DNSADDR)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// empty reports whether nothing was configured.
|
||||
func (b *bootstrapper) empty() bool { return len(b.entries) == 0 }
|
||||
|
||||
// peers returns the current bootstrap peers, without this node itself.
|
||||
func (b *bootstrapper) peers(ctx context.Context) []peer.AddrInfo {
|
||||
var out []peer.AddrInfo
|
||||
for _, e := range b.entries {
|
||||
key := e.String()
|
||||
var got []peer.AddrInfo
|
||||
if isDNSAddr(e) {
|
||||
got = b.resolve(ctx, key, e)
|
||||
} else if ai, err := peer.AddrInfoFromP2pAddr(e); err == nil {
|
||||
got = []peer.AddrInfo{*ai}
|
||||
}
|
||||
out = mergePeers(out, got)
|
||||
}
|
||||
kept := out[:0]
|
||||
for _, ai := range out {
|
||||
if ai.ID != b.self {
|
||||
kept = append(kept, ai)
|
||||
}
|
||||
}
|
||||
return kept
|
||||
}
|
||||
|
||||
func (b *bootstrapper) resolve(ctx context.Context, key string, e ma.Multiaddr) []peer.AddrInfo {
|
||||
ctx, cancel := context.WithTimeout(ctx, resolveTimeout)
|
||||
defer cancel()
|
||||
|
||||
// The resolver can keep going for seconds after its context is cancelled
|
||||
// (DNS that never answers), and the node must not wait for it to stop.
|
||||
type answer struct {
|
||||
addrs []ma.Multiaddr
|
||||
err error
|
||||
}
|
||||
done := make(chan answer, 1)
|
||||
go func() {
|
||||
a, err := b.resolver.Resolve(ctx, e)
|
||||
done <- answer{a, err}
|
||||
}()
|
||||
var resolved []ma.Multiaddr
|
||||
var err error
|
||||
select {
|
||||
case a := <-done:
|
||||
resolved, err = a.addrs, a.err
|
||||
case <-ctx.Done():
|
||||
err = ctx.Err()
|
||||
}
|
||||
if ctx.Err() != nil && errors.Is(err, context.Canceled) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.cache[key] // stopping, not a DNS failure: say nothing
|
||||
}
|
||||
var got []peer.AddrInfo
|
||||
for _, r := range resolved {
|
||||
if ai, perr := peer.AddrInfoFromP2pAddr(r); perr == nil {
|
||||
got = mergePeers(got, []peer.AddrInfo{*ai})
|
||||
}
|
||||
}
|
||||
if err == nil && len(got) == 0 {
|
||||
err = fmt.Errorf("no peers in the records of %s", key)
|
||||
}
|
||||
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if err != nil {
|
||||
if !b.failed[key] { // say it once, not at every redial
|
||||
b.log.Warn("could not resolve bootstrap name", "name", key, "err", err, "using", len(b.cache[key]))
|
||||
}
|
||||
b.failed[key] = true
|
||||
return b.cache[key]
|
||||
}
|
||||
if b.failed[key] {
|
||||
b.log.Info("bootstrap name resolves again", "name", key, "peers", len(got))
|
||||
}
|
||||
b.failed[key] = false
|
||||
b.cache[key] = got
|
||||
return got
|
||||
}
|
||||
|
||||
// mergePeers adds more to into, joining the addresses of a peer seen twice.
|
||||
func mergePeers(into, more []peer.AddrInfo) []peer.AddrInfo {
|
||||
for _, m := range more {
|
||||
found := false
|
||||
for i := range into {
|
||||
if into[i].ID == m.ID {
|
||||
into[i].Addrs = append(into[i].Addrs, m.Addrs...)
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
into = append(into, m)
|
||||
}
|
||||
}
|
||||
return into
|
||||
}
|
||||
|
||||
// relayCandidates feeds AutoRelay: bootstrap nodes run with --public, so they
|
||||
// are the relays a node behind a NAT can use to be reached.
|
||||
func (b *bootstrapper) relayCandidates(ctx context.Context, num int) <-chan peer.AddrInfo {
|
||||
ch := make(chan peer.AddrInfo, num)
|
||||
go func() {
|
||||
defer close(ch)
|
||||
for i, ai := range b.peers(ctx) {
|
||||
if i >= num {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case ch <- ai:
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
package p2p
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/libp2p/go-libp2p/core/crypto"
|
||||
"github.com/libp2p/go-libp2p/core/network"
|
||||
"github.com/libp2p/go-libp2p/core/peer"
|
||||
madns "github.com/multiformats/go-multiaddr-dns"
|
||||
)
|
||||
|
||||
// fakeDNS answers TXT lookups from a table the test can change.
|
||||
type fakeDNS struct {
|
||||
mu sync.Mutex
|
||||
txt map[string][]string
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeDNS) set(name string, records ...string) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.txt == nil {
|
||||
f.txt = map[string][]string{}
|
||||
}
|
||||
f.txt[name] = records
|
||||
}
|
||||
|
||||
func (f *fakeDNS) fail(err error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.err = err
|
||||
}
|
||||
|
||||
func (f *fakeDNS) LookupIPAddr(context.Context, string) ([]net.IPAddr, error) {
|
||||
return nil, errors.New("no addresses in this fake")
|
||||
}
|
||||
|
||||
func (f *fakeDNS) LookupTXT(_ context.Context, name string) ([]string, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.err != nil {
|
||||
return nil, f.err
|
||||
}
|
||||
return f.txt[name], nil
|
||||
}
|
||||
|
||||
func resolverFor(t *testing.T, f *fakeDNS) *madns.Resolver {
|
||||
t.Helper()
|
||||
r, err := madns.NewResolver(madns.WithDefaultResolver(f))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func connected(a *tnode, b *tnode) bool {
|
||||
return a.host.Network().Connectedness(b.ID()) == network.Connected
|
||||
}
|
||||
|
||||
func TestBootstrapNameIsResolvedAndDialled(t *testing.T) {
|
||||
a := startNode(t, nil, "u1x")
|
||||
dns := &fakeDNS{}
|
||||
dns.set("_dnsaddr.boot.test", "dnsaddr="+a.Addrs()[0], "dnsaddr=/ip4/192.0.2.1/tcp/1", "not a record")
|
||||
b := startNodeWith(t, nil, func(c *Config) {
|
||||
c.Bootstrap = []string{"/dnsaddr/boot.test"}
|
||||
c.Resolver = resolverFor(t, dns)
|
||||
}, "u1x")
|
||||
eventually(t, "b reaches a through the name", func() bool { return connected(b, a) })
|
||||
}
|
||||
|
||||
func TestBootstrapNameKeepsTheLastAnswerWhenDNSFails(t *testing.T) {
|
||||
a := startNode(t, nil, "u1x")
|
||||
dns := &fakeDNS{}
|
||||
dns.set("_dnsaddr.boot.test", "dnsaddr="+a.Addrs()[0])
|
||||
b := startNodeWith(t, nil, func(c *Config) {
|
||||
c.Bootstrap = []string{"/dnsaddr/boot.test"}
|
||||
c.Resolver = resolverFor(t, dns)
|
||||
}, "u1x")
|
||||
eventually(t, "first connection", func() bool { return connected(b, a) })
|
||||
|
||||
dns.fail(errors.New("servfail"))
|
||||
b.host.Network().ClosePeer(a.ID())
|
||||
eventually(t, "b dials again from its remembered answer", func() bool { return connected(b, a) })
|
||||
}
|
||||
|
||||
// stuckDNS never answers and ignores cancellation, like a resolver whose
|
||||
// server drops packets.
|
||||
type stuckDNS struct{ release chan struct{} }
|
||||
|
||||
func (s stuckDNS) LookupIPAddr(context.Context, string) ([]net.IPAddr, error) {
|
||||
<-s.release
|
||||
return nil, errors.New("released")
|
||||
}
|
||||
|
||||
func (s stuckDNS) LookupTXT(context.Context, string) ([]string, error) {
|
||||
<-s.release
|
||||
return nil, errors.New("released")
|
||||
}
|
||||
|
||||
func TestStoppingDoesNotWaitForAStuckResolver(t *testing.T) {
|
||||
dns := stuckDNS{release: make(chan struct{})}
|
||||
defer close(dns.release)
|
||||
r, err := madns.NewResolver(madns.WithDefaultResolver(dns))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var logged strings.Builder
|
||||
log := slog.New(slog.NewTextHandler(&logged, nil))
|
||||
b, err := newBootstrapper([]string{"/dnsaddr/boot.test"}, r, "", log)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
b.peers(ctx)
|
||||
close(done)
|
||||
}()
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
cancel() // the node is stopping
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("stopping waited for a resolver that never answers")
|
||||
}
|
||||
if logged.Len() != 0 {
|
||||
t.Errorf("stopping is not a DNS failure, but it was logged: %s", logged.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootstrapEntriesAreCheckedUpFront(t *testing.T) {
|
||||
id := "12D3KooWQYhTNQdmr3ArTeUHRYzFg94BKyTkoWBDWez9kSCVe2Xo"
|
||||
for addr, ok := range map[string]bool{
|
||||
"/dnsaddr/allmende.example": true,
|
||||
"/ip4/203.0.113.5/tcp/4001/p2p/" + id: true,
|
||||
"/dns4/node.example/tcp/4001/p2p/" + id: true,
|
||||
"/ip4/203.0.113.5/tcp/4001": false, // no peer ID to verify
|
||||
"allmende.example": false,
|
||||
"/dnsaddr/": false,
|
||||
"": false,
|
||||
} {
|
||||
_, err := newBootstrapper([]string{addr}, nil, "", testLogger())
|
||||
if (err == nil) != ok {
|
||||
t.Errorf("%q: error = %v, want ok = %v", addr, err, ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootstrapNeverDialsItself(t *testing.T) {
|
||||
a := startNode(t, nil)
|
||||
dns := &fakeDNS{}
|
||||
dns.set("_dnsaddr.boot.test", "dnsaddr="+a.Addrs()[0])
|
||||
b, err := newBootstrapper([]string{"/dnsaddr/boot.test", a.Addrs()[0]}, resolverFor(t, dns), a.ID(), testLogger())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := b.peers(context.Background()); len(got) != 0 {
|
||||
t.Fatalf("a bootstrap node must not dial itself: %v", got)
|
||||
}
|
||||
other, _ := newBootstrapper([]string{"/dnsaddr/boot.test"}, resolverFor(t, dns), peer.ID("someone else"), testLogger())
|
||||
if got := other.peers(context.Background()); len(got) != 1 || got[0].ID != a.ID() {
|
||||
t.Fatalf("got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeersFromEarlierRunsAreRedialled(t *testing.T) {
|
||||
a := startNode(t, nil, "u1x")
|
||||
path := filepath.Join(t.TempDir(), "peers.json")
|
||||
ai := peer.AddrInfo{ID: a.ID(), Addrs: a.host.Addrs()}
|
||||
err := writePeerCache(path, []cachedPeer{{ID: a.ID().String(), Addrs: directAddrs(ai.Addrs), Seen: time.Now().Unix()}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// No bootstrap, no mDNS, no DHT: only the remembered address can lead to a.
|
||||
b := startNodeWith(t, nil, func(c *Config) { c.PeerCache = path }, "u1x")
|
||||
eventually(t, "b finds a from its cache", func() bool { return connected(b, a) })
|
||||
}
|
||||
|
||||
func TestPeersAreRememberedOnTheWayOut(t *testing.T) {
|
||||
a := startNode(t, nil, "u1x")
|
||||
path := filepath.Join(t.TempDir(), "peers.json")
|
||||
b := startNodeWith(t, nil, func(c *Config) { c.PeerCache = path }, "u1x")
|
||||
connect(t, b, a)
|
||||
eventually(t, "connected", func() bool { return connected(b, a) })
|
||||
b.Close() // saves once more as it stops
|
||||
|
||||
got := readPeerCache(path, time.Now())
|
||||
if len(got) != 1 || got[0].ID != a.ID().String() || len(got[0].Addrs) == 0 {
|
||||
t.Fatalf("cache = %+v, want a's address", got)
|
||||
}
|
||||
for _, addr := range got[0].Addrs {
|
||||
if strings.Contains(addr, "p2p-circuit") {
|
||||
t.Errorf("a relayed address was remembered: %s", addr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerCacheIgnoresStaleAndBrokenEntries(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "peers.json")
|
||||
id := "12D3KooWQYhTNQdmr3ArTeUHRYzFg94BKyTkoWBDWez9kSCVe2Xo"
|
||||
now := time.Now()
|
||||
err := writePeerCache(path, []cachedPeer{
|
||||
{ID: id, Addrs: []string{"/ip4/127.0.0.1/tcp/1"}, Seen: now.Unix()},
|
||||
{ID: id + "x", Addrs: []string{"/ip4/127.0.0.1/tcp/2"}, Seen: now.Unix()}, // not a peer ID
|
||||
{ID: id, Addrs: nil, Seen: now.Unix()}, // nothing to dial
|
||||
{ID: id, Addrs: []string{"/ip4/127.0.0.1/tcp/3"}, Seen: now.Add(-31 * 24 * time.Hour).Unix()}, // too old
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := readPeerCache(path, now); len(got) != 1 || got[0].Addrs[0] != "/ip4/127.0.0.1/tcp/1" {
|
||||
t.Fatalf("got %+v", got)
|
||||
}
|
||||
|
||||
for name, content := range map[string]string{"garbage": "{not json", "empty": ""} {
|
||||
p := filepath.Join(dir, name)
|
||||
if err := os.WriteFile(p, []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := readPeerCache(p, now); got != nil {
|
||||
t.Errorf("%s: want an empty cache, got %+v", name, got)
|
||||
}
|
||||
}
|
||||
if got := readPeerCache(filepath.Join(dir, "missing"), now); got != nil {
|
||||
t.Errorf("missing file: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerCacheKeepsTheNewestEntries(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "peers.json")
|
||||
var many []cachedPeer
|
||||
for i := 0; i < maxCachedPeers+20; i++ {
|
||||
_, pub, err := crypto.GenerateEd25519Key(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, err := peer.IDFromPublicKey(pub)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
many = append(many, cachedPeer{ID: id.String(), Addrs: []string{"/ip4/127.0.0.1/tcp/1"}, Seen: int64(1000 + i)})
|
||||
}
|
||||
if err := writePeerCache(path, many); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := readPeerCache(path, time.Unix(2000, 0))
|
||||
if len(got) != maxCachedPeers || got[0].Seen != int64(1000+maxCachedPeers+19) {
|
||||
t.Fatalf("kept %d, newest first = %d", len(got), got[0].Seen)
|
||||
}
|
||||
}
|
||||
|
||||
// Two nodes that only know a bootstrap node must find each other through the
|
||||
// DHT, not by being introduced.
|
||||
func TestDHTFindsPeersOfTheSameRegion(t *testing.T) {
|
||||
r := startNodeWith(t, nil, func(c *Config) {
|
||||
c.Public, c.DHT, c.DiscoverInterval = true, true, 200*time.Millisecond
|
||||
}, "u1x")
|
||||
seed := func(c *Config) {
|
||||
c.Bootstrap = []string{r.Addrs()[0]}
|
||||
c.DHT, c.DiscoverInterval = true, 200*time.Millisecond
|
||||
}
|
||||
a := startNodeWith(t, nil, seed, "u1x")
|
||||
b := startNodeWith(t, nil, seed, "u1x")
|
||||
other := startNodeWith(t, nil, seed, "u1y") // a different region: not for a or b
|
||||
|
||||
eventually(t, "a and b are connected directly", func() bool { return connected(a, b) && connected(b, a) })
|
||||
if connected(a, other) || connected(b, other) {
|
||||
t.Error("a node of another region was dialled; discovery is per region")
|
||||
}
|
||||
}
|
||||
|
||||
// A node that cannot be reached directly takes a reservation on a bootstrap
|
||||
// node, so that others can still get to it through that relay. (libp2p only
|
||||
// advertises relay addresses built on public IPs, so on loopback the test
|
||||
// dials the relayed path itself; that works only if the reservation exists.)
|
||||
func TestNodeBehindANATIsReachableThroughTheBootstrapNode(t *testing.T) {
|
||||
r := startNodeWith(t, nil, func(c *Config) { c.Public = true }, "u1x")
|
||||
a := startNodeWith(t, nil, func(c *Config) {
|
||||
c.Bootstrap = []string{r.Addrs()[0]}
|
||||
c.ForcePrivate = true
|
||||
c.RelayBootDelay = 100 * time.Millisecond
|
||||
}, "u1x")
|
||||
b := startNode(t, nil, "u1x") // knows nothing of a
|
||||
connect(t, b, r)
|
||||
|
||||
via := r.Addrs()[0] + "/p2p-circuit/p2p/" + a.ID().String()
|
||||
ai, err := peer.AddrInfoFromString(via)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
eventually(t, "b reaches a through r", func() bool {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
ctx = network.WithAllowLimitedConn(ctx, "test")
|
||||
return b.host.Connect(ctx, *ai) == nil && b.host.Network().Connectedness(a.ID()) != network.NotConnected
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
+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)
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
package p2p
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/libp2p/go-libp2p/core/network"
|
||||
"github.com/libp2p/go-libp2p/core/peer"
|
||||
ma "github.com/multiformats/go-multiaddr"
|
||||
)
|
||||
|
||||
// The peer cache remembers who this node met, so after the first successful
|
||||
// start it can find the network again without any bootstrap node.
|
||||
const (
|
||||
maxCachedPeers = 100
|
||||
cachedPeerTTL = 30 * 24 * time.Hour
|
||||
dialCachedMax = 10
|
||||
rememberEvery = 5 * time.Minute
|
||||
)
|
||||
|
||||
type cachedPeer struct {
|
||||
ID string `json:"id"`
|
||||
Addrs []string `json:"addrs"`
|
||||
Seen int64 `json:"seen"` // unix seconds
|
||||
}
|
||||
|
||||
type peerFile struct {
|
||||
Peers []cachedPeer `json:"peers"`
|
||||
}
|
||||
|
||||
// readPeerCache returns the usable entries, newest first. A missing, damaged or
|
||||
// stale file is simply an empty cache: it is a convenience, never a requirement.
|
||||
func readPeerCache(path string, now time.Time) []cachedPeer {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var f peerFile
|
||||
if json.Unmarshal(data, &f) != nil {
|
||||
return nil
|
||||
}
|
||||
var out []cachedPeer
|
||||
for _, p := range f.Peers {
|
||||
if _, err := peer.Decode(p.ID); err != nil || len(p.Addrs) == 0 {
|
||||
continue
|
||||
}
|
||||
if now.Sub(time.Unix(p.Seen, 0)) > cachedPeerTTL {
|
||||
continue
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Seen > out[j].Seen })
|
||||
return out
|
||||
}
|
||||
|
||||
func writePeerCache(path string, peers []cachedPeer) error {
|
||||
sort.Slice(peers, func(i, j int) bool { return peers[i].Seen > peers[j].Seen })
|
||||
if len(peers) > maxCachedPeers {
|
||||
peers = peers[:maxCachedPeers]
|
||||
}
|
||||
data, err := json.MarshalIndent(peerFile{Peers: peers}, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp, err := os.CreateTemp(filepath.Dir(path), ".peers-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp.Name(), path)
|
||||
}
|
||||
|
||||
// directAddrs keeps the addresses worth remembering: not relayed, which only
|
||||
// work while that relay does, and not unspecified.
|
||||
func directAddrs(addrs []ma.Multiaddr) []string {
|
||||
var out []string
|
||||
for _, a := range addrs {
|
||||
if strings.Contains(a.String(), "/p2p-circuit") {
|
||||
continue
|
||||
}
|
||||
out = append(out, a.String())
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// rememberPeers records the currently connected peers in the cache file.
|
||||
func (n *Node) rememberPeers() {
|
||||
if n.cfg.PeerCache == "" {
|
||||
return
|
||||
}
|
||||
now := n.clock()
|
||||
byID := map[string]cachedPeer{}
|
||||
for _, p := range readPeerCache(n.cfg.PeerCache, now) {
|
||||
byID[p.ID] = p
|
||||
}
|
||||
for _, id := range n.host.Network().Peers() {
|
||||
addrs := directAddrs(n.host.Peerstore().Addrs(id))
|
||||
if len(addrs) == 0 {
|
||||
continue
|
||||
}
|
||||
byID[id.String()] = cachedPeer{ID: id.String(), Addrs: addrs, Seen: now.Unix()}
|
||||
}
|
||||
list := make([]cachedPeer, 0, len(byID))
|
||||
for _, p := range byID {
|
||||
list = append(list, p)
|
||||
}
|
||||
if err := writePeerCache(n.cfg.PeerCache, list); err != nil {
|
||||
n.log.Warn("could not save known peers", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// remember saves the known peers now and then, and once more on the way out.
|
||||
func (n *Node) remember() {
|
||||
defer n.wg.Done()
|
||||
if n.cfg.PeerCache == "" {
|
||||
return
|
||||
}
|
||||
t := time.NewTicker(rememberEvery)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-n.ctx.Done():
|
||||
n.rememberPeers()
|
||||
return
|
||||
case <-t.C:
|
||||
n.rememberPeers()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// dialCached reconnects to the peers met on earlier runs.
|
||||
func (n *Node) dialCached() {
|
||||
if n.cfg.PeerCache == "" {
|
||||
return
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
dialed := 0
|
||||
for _, p := range readPeerCache(n.cfg.PeerCache, n.clock()) {
|
||||
if dialed == dialCachedMax {
|
||||
break
|
||||
}
|
||||
id, err := peer.Decode(p.ID)
|
||||
if err != nil || id == n.host.ID() || n.host.Network().Connectedness(id) == network.Connected {
|
||||
continue
|
||||
}
|
||||
ai := peer.AddrInfo{ID: id}
|
||||
for _, a := range p.Addrs {
|
||||
if m, err := ma.NewMultiaddr(a); err == nil {
|
||||
ai.Addrs = append(ai.Addrs, m)
|
||||
}
|
||||
}
|
||||
dialed++
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
ctx, cancel := context.WithTimeout(n.ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
if err := n.host.Connect(ctx, ai); err != nil && !errors.Is(err, context.Canceled) {
|
||||
n.log.Debug("remembered peer unreachable", "peer", ai.ID, "err", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
Reference in New Issue
Block a user