Files
allmende/internal/p2p/node.go
T
nilsandClaude Sonnet 5.5 11fd2a88c0 p2p: incremental sync with digests, inventory and fetch
Peers compare a short digest of revocations, listings and messages on
connect and transfer only what differs. Peers without digests are synced
the old way.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
2026-11-18 17:28:22 +01:00

781 lines
22 KiB
Go

// Package p2p connects a node's store to the network.
//
// - Listings are gossiped on one pubsub topic per geohash region
// (precision 3). A node subscribes only to the regions it cares about.
// - Revocations are gossiped on a single global topic.
// - A sync stream protocol lets a node that was offline (or just joined)
// catch up from any peer.
//
// Every message is verified by a topic validator before it is relayed, so a
// node never forwards garbage and misbehaving peers lose reputation.
package p2p
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"slices"
"sync"
"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"
drouting "github.com/libp2p/go-libp2p/p2p/discovery/routing"
"github.com/libp2p/go-libp2p/p2p/host/autorelay"
ma "github.com/multiformats/go-multiaddr"
madns "github.com/multiformats/go-multiaddr-dns"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/message"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
const (
listingTopicPrefix = "/allmende/1/listings/"
// messageTopicPrefix carries encrypted message envelopes, one topic per
// region next to the listing topic.
messageTopicPrefix = "/allmende/1/messages/"
// RevocationTopic carries identity revocations for the whole network.
RevocationTopic = "/allmende/1/revocations"
mdnsService = "allmende"
maintenanceTick = time.Hour
)
// Config describes a node.
type Config struct {
Device *identity.Device
Store *store.Store
ListenAddrs []string // default: TCP and QUIC on all interfaces, random ports
// 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
// Announce lists the addresses other nodes should dial, without /p2p/<id>,
// e.g. /dns4/node.example.org/tcp/4001. A node behind a router or in a
// container does not know its public address; when this is set, only these
// addresses are announced.
Announce []string
// 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
// envelopes; it must match the store's.
MessageDifficulty int
SyncPageSize int // records per sync page (default 500)
RedialInterval time.Duration // how often lost bootstrap peers are redialed (default 20s)
Clock func() time.Time // default time.Now
Logger *slog.Logger
}
// Node is a running participant.
type Node struct {
cfg Config
host host.Host
ps *pubsub.PubSub
clock func() time.Time
log *slog.Logger
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
mdns mdns.Service
mu sync.Mutex
topics map[string]*pubsub.Topic
msgTopics map[string]*pubsub.Topic
subscribed []string
regions map[string]*regionRun
rd *drouting.RoutingDiscovery // nil without a DHT
boot *bootstrapper
dht *dht.IpfsDHT
syncing map[peer.ID]bool
oldSync bool // tests: answer like a node from before digests existed
revTopic *pubsub.Topic
}
// New starts a node. Cancel ctx or call Close to stop it.
func New(ctx context.Context, cfg Config) (*Node, error) {
if cfg.Device == nil || cfg.Store == nil {
return nil, errors.New("p2p: Device and Store are required")
}
for _, r := range cfg.Regions {
if !listing.ValidRegion(r) {
return nil, fmt.Errorf("p2p: invalid region %q (want %d geohash characters)", r, listing.RegionPrecision)
}
}
if len(cfg.ListenAddrs) == 0 {
cfg.ListenAddrs = []string{"/ip4/0.0.0.0/tcp/0", "/ip4/0.0.0.0/udp/0/quic-v1"}
}
if cfg.SyncPageSize <= 0 {
cfg.SyncPageSize = 500
}
if cfg.RedialInterval <= 0 {
cfg.RedialInterval = 20 * time.Second
}
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
}
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 len(cfg.Announce) > 0 {
announce := make([]ma.Multiaddr, 0, len(cfg.Announce))
for _, a := range cfg.Announce {
m, err := ma.NewMultiaddr(a)
if err != nil {
return nil, fmt.Errorf("announce address %q: %w", a, err)
}
announce = append(announce, m)
}
opts = append(opts, libp2p.AddrsFactory(func([]ma.Multiaddr) []ma.Multiaddr { return announce }))
}
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
}
nctx, cancel := context.WithCancel(ctx)
n := &Node{
cfg: cfg,
host: h,
clock: cfg.Clock,
log: log,
ctx: nctx,
cancel: cancel,
topics: map[string]*pubsub.Topic{},
msgTopics: map[string]*pubsub.Topic{},
regions: map[string]*regionRun{},
syncing: map[peer.ID]bool{},
boot: boot,
}
if n.clock == nil {
n.clock = time.Now
}
// Flood-publish: the origin sends to every subscribed peer instead of only
// its mesh. Regional topics are small, and without it a listing published
// in the first second after connecting (before the mesh forms) is lost.
n.ps, err = pubsub.NewGossipSub(nctx, h,
pubsub.WithMaxMessageSize(listing.MaxSize+4096),
pubsub.WithFloodPublish(true))
if err != nil {
n.Close()
return nil, err
}
if err := n.startRevocations(); err != nil {
n.Close()
return nil, err
}
for _, r := range cfg.Regions {
if err := n.subscribeRegion(r); err != nil {
n.Close()
return nil, err
}
}
h.SetStreamHandler(SyncProtocol, n.handleSync)
h.Network().Notify(&network.NotifyBundle{
ConnectedF: func(_ network.Network, c network.Conn) { n.syncSoon(c.RemotePeer()) },
})
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 {
n.Close()
return nil, err
}
}
// 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
}
// ID returns the node's peer ID, which derives from its device key.
func (n *Node) ID() peer.ID { return n.host.ID() }
// Addrs returns dialable multiaddrs including the /p2p/<id> suffix.
func (n *Node) Addrs() []string {
addrs, err := peer.AddrInfoToP2pAddrs(&peer.AddrInfo{ID: n.host.ID(), Addrs: n.host.Addrs()})
if err != nil {
return nil
}
out := make([]string, len(addrs))
for i, a := range addrs {
out[i] = a.String()
}
return out
}
// Connect dials a peer given as a multiaddr ending in /p2p/<peer id>.
func (n *Node) Connect(ctx context.Context, addr string) error {
ai, err := peer.AddrInfoFromString(addr)
if err != nil {
return err
}
return n.host.Connect(ctx, *ai)
}
// PeerCount returns the number of currently connected peers.
func (n *Node) PeerCount() int { return len(n.host.Network().Peers()) }
// RegionPeers lists peers known to be subscribed to the region's topic.
func (n *Node) RegionPeers(region string) []peer.ID {
return n.ps.ListPeers(listingTopicPrefix + region)
}
// Publish stores l locally (which verifies it) and gossips it to its region.
func (n *Node) Publish(ctx context.Context, l *listing.Listing) error {
if _, err := n.cfg.Store.Put(ctx, l); err != nil {
return err
}
data, err := l.Bytes()
if err != nil {
return err
}
t, err := n.regionTopic(listing.Region(l.Geohash))
if err != nil {
return err
}
return t.Publish(ctx, data)
}
// PublishMessage stores an envelope locally (which verifies it) and gossips it
// on the message topic of region. The node must replicate the region: owner-
// bound envelopes are only accepted for listings it holds.
func (n *Node) PublishMessage(ctx context.Context, region string, e *message.Envelope) error {
if _, err := n.cfg.Store.PutMessage(ctx, region, e); err != nil {
return err
}
data, err := e.Bytes()
if err != nil {
return err
}
t, err := n.messageTopic(region)
if err != nil {
return err
}
return t.Publish(ctx, data)
}
// PublishRevocation stores r locally and gossips it to the whole network.
func (n *Node) PublishRevocation(ctx context.Context, r *identity.Revocation) error {
if _, err := n.cfg.Store.PutRevocation(ctx, r); err != nil {
return err
}
data, err := r.Bytes()
if err != nil {
return err
}
return n.revTopic.Publish(ctx, data)
}
// Close stops the node.
func (n *Node) Close() error {
n.cancel()
if n.mdns != nil {
n.mdns.Close()
}
n.wg.Wait()
if n.dht != nil {
n.dht.Close()
}
return n.host.Close()
}
// --- topics ---------------------------------------------------------------
func (n *Node) startRevocations() error {
if err := n.ps.RegisterTopicValidator(RevocationTopic, n.revocationValidator,
pubsub.WithValidatorTimeout(5*time.Second)); err != nil {
return err
}
t, err := n.ps.Join(RevocationTopic)
if err != nil {
return err
}
sub, err := t.Subscribe()
if err != nil {
return err
}
n.revTopic = t
n.wg.Add(1)
go func() {
defer n.wg.Done()
n.consume(n.ctx, sub, func(msg *pubsub.Message) {
r, ok := msg.ValidatorData.(*identity.Revocation)
if !ok {
return
}
if _, err := n.cfg.Store.PutRevocation(n.ctx, r); err != nil {
n.log.Warn("store revocation", "err", err)
}
})
}()
return nil
}
// regionRun is what a followed region keeps running; dropping the region stops it.
type regionRun struct {
ctx context.Context
cancel context.CancelFunc
subs []*pubsub.Subscription
}
// Regions lists the regions this node follows now, in the order they were added.
func (n *Node) Regions() []string {
n.mu.Lock()
defer n.mu.Unlock()
return append([]string(nil), n.subscribed...)
}
// SetRegions makes the node follow exactly these regions, without a restart:
// new ones are joined (and peers looked for), dropped ones are left. Listings
// already stored stay stored. Nothing changes if a region is invalid.
func (n *Node) SetRegions(regions []string) error {
want := make([]string, 0, len(regions))
for _, r := range regions {
if !listing.ValidRegion(r) {
return fmt.Errorf("p2p: invalid region %q (want %d geohash characters)", r, listing.RegionPrecision)
}
if !slices.Contains(want, r) {
want = append(want, r)
}
}
have := n.Regions()
added := false
for _, r := range want {
if !slices.Contains(have, r) {
if err := n.subscribeRegion(r); err != nil {
return err
}
added = true
}
}
if added {
// What was published before is not gossiped again: ask the peers we
// already know for what they hold in the new regions.
for _, p := range n.host.Network().Peers() {
n.syncSoon(p)
}
}
for _, r := range have {
if !slices.Contains(want, r) {
n.unsubscribeRegion(r)
}
}
return nil
}
func (n *Node) unsubscribeRegion(region string) {
n.mu.Lock()
run := n.regions[region]
delete(n.regions, region)
n.subscribed = slices.DeleteFunc(n.subscribed, func(r string) bool { return r == region })
listings, messages := n.topics[region], n.msgTopics[region]
delete(n.topics, region)
delete(n.msgTopics, region)
n.mu.Unlock()
if run == nil {
return
}
run.cancel()
for _, s := range run.subs {
s.Cancel()
}
for name, t := range map[string]*pubsub.Topic{
listingTopicPrefix + region: listings,
messageTopicPrefix + region: messages,
} {
if t == nil {
continue
}
if err := t.Close(); err != nil {
n.log.Debug("leave topic", "topic", name, "err", err)
}
if err := n.ps.UnregisterTopicValidator(name); err != nil {
n.log.Debug("remove validator", "topic", name, "err", err)
}
}
}
func (n *Node) subscribeRegion(region string) error {
t, err := n.regionTopic(region)
if err != nil {
return err
}
sub, err := t.Subscribe()
if err != nil {
return err
}
rctx, cancel := context.WithCancel(n.ctx)
run := &regionRun{ctx: rctx, cancel: cancel, subs: []*pubsub.Subscription{sub}}
n.mu.Lock()
n.subscribed = append(n.subscribed, region)
n.regions[region] = run
rd := n.rd
n.mu.Unlock()
if rd != nil {
n.discoverRegion(rctx, rd, region)
}
n.wg.Add(1)
go func() {
defer n.wg.Done()
n.consume(rctx, sub, func(msg *pubsub.Message) {
l, ok := msg.ValidatorData.(*listing.Listing)
if !ok {
return
}
switch _, err := n.cfg.Store.Put(n.ctx, l); {
case err == nil, errors.Is(err, store.ErrRevoked):
default:
n.log.Warn("store listing", "err", err)
}
})
}()
mt, err := n.messageTopic(region)
if err != nil {
return err
}
msub, err := mt.Subscribe()
if err != nil {
return err
}
n.mu.Lock()
run.subs = append(run.subs, msub)
n.mu.Unlock()
n.wg.Add(1)
go func() {
defer n.wg.Done()
n.consume(rctx, msub, func(msg *pubsub.Message) {
e, ok := msg.ValidatorData.(*message.Envelope)
if !ok {
return
}
switch _, err := n.cfg.Store.PutMessage(n.ctx, region, e); {
case err == nil, errors.Is(err, store.ErrNoListing), errors.Is(err, store.ErrQueueFull):
default:
n.log.Warn("store message", "err", err)
}
})
}()
return nil
}
// messageTopic joins (once) the message topic for region.
func (n *Node) messageTopic(region string) (*pubsub.Topic, error) {
if !listing.ValidRegion(region) {
return nil, fmt.Errorf("p2p: invalid region %q", region)
}
n.mu.Lock()
defer n.mu.Unlock()
if t, ok := n.msgTopics[region]; ok {
return t, nil
}
name := messageTopicPrefix + region
if err := n.ps.RegisterTopicValidator(name, n.messageValidator(region),
pubsub.WithValidatorTimeout(5*time.Second)); err != nil {
return nil, err
}
t, err := n.ps.Join(name)
if err != nil {
return nil, err
}
n.msgTopics[region] = t
return t, nil
}
// regionTopic joins (once) the topic for region and installs its validator.
func (n *Node) regionTopic(region string) (*pubsub.Topic, error) {
if !listing.ValidRegion(region) {
return nil, fmt.Errorf("p2p: invalid region %q", region)
}
n.mu.Lock()
defer n.mu.Unlock()
if t, ok := n.topics[region]; ok {
return t, nil
}
name := listingTopicPrefix + region
if err := n.ps.RegisterTopicValidator(name, n.listingValidator(region),
pubsub.WithValidatorTimeout(5*time.Second)); err != nil {
return nil, err
}
t, err := n.ps.Join(name)
if err != nil {
return nil, err
}
n.topics[region] = t
return t, nil
}
// consume handles what arrives on sub until ctx ends or the subscription is cancelled.
func (n *Node) consume(ctx context.Context, sub *pubsub.Subscription, handle func(*pubsub.Message)) {
for {
msg, err := sub.Next(ctx)
if err != nil {
return
}
handle(msg)
}
}
// --- validation -----------------------------------------------------------
func (n *Node) listingValidator(region string) pubsub.ValidatorEx {
return func(ctx context.Context, _ peer.ID, msg *pubsub.Message) pubsub.ValidationResult {
l, res := n.validateListing(ctx, msg.Data)
if res != pubsub.ValidationAccept {
return res
}
// A listing may only travel on its own region's topic.
if listing.Region(l.Geohash) != region {
return pubsub.ValidationReject
}
msg.ValidatorData = l
return pubsub.ValidationAccept
}
}
// messageValidator checks what a relay can see: the envelope's structure,
// size and proof-of-work, and the listing it points to. It cannot read the
// content. Invalid envelopes cost the relaying peer score; ones this node
// cannot place (unknown listing, a device that changed) or whose clocks
// disagree are ignored without penalty.
func (n *Node) messageValidator(region string) pubsub.ValidatorEx {
return func(ctx context.Context, _ peer.ID, msg *pubsub.Message) pubsub.ValidationResult {
if len(msg.Data) > message.MaxSize {
return pubsub.ValidationReject
}
var e message.Envelope
if err := json.Unmarshal(msg.Data, &e); err != nil {
return pubsub.ValidationReject
}
// Only the canonical encoding, so every node derives the same ID.
if canon, err := e.Bytes(); err != nil || !bytes.Equal(canon, msg.Data) {
return pubsub.ValidationReject
}
err := n.cfg.Store.CheckMessage(ctx, region, &e)
switch {
case err == nil:
msg.ValidatorData = &e
return pubsub.ValidationAccept
case errors.Is(err, listing.ErrTimeWindow), errors.Is(err, store.ErrNoListing):
return pubsub.ValidationIgnore
case errors.Is(err, store.ErrInvalid):
return pubsub.ValidationReject
default:
return pubsub.ValidationIgnore // a local failure is not the peer's fault
}
}
}
func (n *Node) validateListing(ctx context.Context, data []byte) (*listing.Listing, pubsub.ValidationResult) {
if len(data) > listing.MaxSize {
return nil, pubsub.ValidationReject
}
var l listing.Listing
if err := json.Unmarshal(data, &l); err != nil {
return nil, pubsub.ValidationReject
}
// Only the canonical encoding is accepted, so every honest node derives
// the same message ID and nobody can re-encode someone else's listing.
if canon, err := l.Bytes(); err != nil || !bytes.Equal(canon, data) {
return nil, pubsub.ValidationReject
}
if err := l.Check(n.clock(), n.cfg.Difficulty); err != nil {
if errors.Is(err, listing.ErrTimeWindow) {
return nil, pubsub.ValidationIgnore // clocks differ; not the relay's fault
}
return nil, pubsub.ValidationReject
}
if revoked, err := n.cfg.Store.IsRevoked(ctx, l.Author, l.Device, l.Cert.IssuedAt); err != nil || revoked {
return nil, pubsub.ValidationIgnore
}
return &l, pubsub.ValidationAccept
}
func (n *Node) revocationValidator(_ context.Context, _ peer.ID, msg *pubsub.Message) pubsub.ValidationResult {
r, res := n.validateRevocation(msg.Data)
if res == pubsub.ValidationAccept {
msg.ValidatorData = r
}
return res
}
func (n *Node) validateRevocation(data []byte) (*identity.Revocation, pubsub.ValidationResult) {
if len(data) > 4096 {
return nil, pubsub.ValidationReject
}
var r identity.Revocation
if err := json.Unmarshal(data, &r); err != nil {
return nil, pubsub.ValidationReject
}
if canon, err := r.Bytes(); err != nil || !bytes.Equal(canon, data) {
return nil, pubsub.ValidationReject
}
if err := r.Check(n.cfg.Difficulty); err != nil {
return nil, pubsub.ValidationReject
}
if r.CertExpiresAt <= n.clock().Unix() {
return nil, pubsub.ValidationIgnore
}
return &r, pubsub.ValidationAccept
}
// --- discovery and upkeep -------------------------------------------------
type mdnsNotifee struct{ n *Node }
func (m *mdnsNotifee) HandlePeerFound(pi peer.AddrInfo) {
if pi.ID == m.n.host.ID() {
return
}
go func() {
ctx, cancel := context.WithTimeout(m.n.ctx, 15*time.Second)
defer cancel()
if err := m.n.host.Connect(ctx, pi); err != nil {
m.n.log.Debug("mdns connect", "peer", pi.ID, "err", err)
}
}()
}
// dialBootstrap connects to every configured bootstrap peer we are not
// already connected to.
func (n *Node) dialBootstrap() {
var wg sync.WaitGroup
for _, ai := range n.boot.peers(n.ctx) {
if n.host.Network().Connectedness(ai.ID) == network.Connected {
continue
}
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
}
}
// redial keeps the node attached to its bootstrap peers across restarts and
// network outages on either side.
func (n *Node) redial() {
defer n.wg.Done()
if n.boot.empty() {
return
}
t := time.NewTicker(n.cfg.RedialInterval)
defer t.Stop()
for {
select {
case <-n.ctx.Done():
return
case <-t.C:
n.dialBootstrap()
}
}
}
// maintain periodically drops expired data.
func (n *Node) maintain() {
defer n.wg.Done()
t := time.NewTicker(maintenanceTick)
defer t.Stop()
for {
select {
case <-n.ctx.Done():
return
case <-t.C:
if removed, err := n.cfg.Store.Expire(n.ctx); err != nil {
n.log.Warn("expire", "err", err)
} else if removed > 0 {
n.log.Info("expired records", "count", removed)
}
}
}
}