// 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/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 []string // multiaddrs ending in /p2p/ Regions []string // geohash precision-3 cells to replicate MDNS bool // discover peers on the local network 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 bootstrap []peer.AddrInfo syncing map[peer.ID]bool 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 } 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) } 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{}, msgTopics: map[string]*pubsub.Topic{}, syncing: map[peer.ID]bool{}, bootstrap: bootstrap, } 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()) }, }) n.dialBootstrap() 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(2) go n.maintain() go n.redial() 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/ 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/. 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() 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) } }) }() mt, err := n.messageTopic(region) if err != nil { return err } msub, err := mt.Subscribe() if err != nil { return err } n.wg.Add(1) go func() { defer n.wg.Done() n.consume(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 } 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 } } // 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() { for _, ai := range n.bootstrap { 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() } } // 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 len(n.bootstrap) == 0 { 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) } } } }