- identity: 12-word recovery phrase, device certificates, revocations, device key storage; the identity key is never stored on a node - listing: signed by a device with an embedded certificate, domain-separated signatures, ErrTimeWindow for clock-related failures, region helpers - store: revocations purge a device's listings; keyset-paged Since for sync - p2p: gossipsub topic per geohash region plus a global revocation topic, validators run before relaying, /allmende/1/sync catch-up protocol, bootstrap peers and mDNS - docs: key model, replication and conflict rules Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
438 lines
11 KiB
Go
438 lines
11 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"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/libp2p/go-libp2p"
|
|
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"
|
|
|
|
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
|
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
|
"git.stinnesbeck.com/nils/allmende/internal/store"
|
|
)
|
|
|
|
const (
|
|
listingTopicPrefix = "/allmende/1/listings/"
|
|
// RevocationTopic carries identity revocations for the whole network.
|
|
RevocationTopic = "/allmende/1/revocations"
|
|
|
|
mdnsService = "allmende"
|
|
resyncInterval = 5 * time.Minute
|
|
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 []string // multiaddrs ending in /p2p/<peer id>
|
|
Regions []string // geohash precision-3 cells to replicate
|
|
MDNS bool // discover peers on the local network
|
|
|
|
Difficulty int // required proof-of-work bits
|
|
SyncPageSize int // records per sync page (default 500)
|
|
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
|
|
subscribed []string
|
|
synced map[peer.ID]time.Time
|
|
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
|
|
}
|
|
|
|
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...))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
nctx, cancel := context.WithCancel(ctx)
|
|
n := &Node{
|
|
cfg: cfg,
|
|
host: h,
|
|
clock: cfg.Clock,
|
|
log: cfg.Logger,
|
|
ctx: nctx,
|
|
cancel: cancel,
|
|
topics: map[string]*pubsub.Topic{},
|
|
synced: map[peer.ID]time.Time{},
|
|
}
|
|
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
|
|
// 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()) },
|
|
})
|
|
|
|
for _, addr := range cfg.Bootstrap {
|
|
if err := n.Connect(nctx, addr); err != nil {
|
|
n.log.Warn("bootstrap peer unreachable", "addr", addr, "err", 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
|
|
}
|
|
}
|
|
|
|
n.wg.Add(1)
|
|
go n.maintain()
|
|
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)
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
|
|
// 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()
|
|
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(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
|
|
}
|
|
|
|
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
|
|
}
|
|
n.mu.Lock()
|
|
n.subscribed = append(n.subscribed, region)
|
|
n.mu.Unlock()
|
|
n.wg.Add(1)
|
|
go func() {
|
|
defer n.wg.Done()
|
|
n.consume(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)
|
|
}
|
|
})
|
|
}()
|
|
return 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
|
|
}
|
|
|
|
func (n *Node) consume(sub *pubsub.Subscription, handle func(*pubsub.Message)) {
|
|
for {
|
|
msg, err := sub.Next(n.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
|
|
}
|
|
}
|
|
|
|
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); 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)
|
|
}
|
|
}()
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
}
|
|
}
|
|
}
|