A node with too few peers in a followed region asks its connected peers who they know there (sync kind "peers"); a peer answers even from another region, since gossip tells it which topics its connections subscribe to. Peers of the region are dialed, others only while the region has none. The peer cache records the regions a peer was seen in and a restart redials those first. Anti-entropy now runs every 10 minutes (plus or minus a fifth) with 3 peers per round instead of every 30 with one. Simulator: a newcomer whose remembered peers were all in another region got 0 of 114 listings with the seeds down, now 56 of 56; repair median at the same interval 25.9 s to 5.7 s. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
971 lines
28 KiB
Go
971 lines
28 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"
|
|
"math/rand/v2"
|
|
"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/metrics"
|
|
"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/report"
|
|
"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"
|
|
// ReportTopic carries signed abuse reports for the whole network. They are
|
|
// few (each needs a reporter's certificate and proof-of-work), and a node
|
|
// decides for itself which ones count.
|
|
ReportTopic = "/allmende/1/reports"
|
|
|
|
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)
|
|
// AntiEntropyInterval is how often the node syncs with random peers it
|
|
// shares a region with, to repair what gossip lost while connected
|
|
// (default 10 min, each round a fifth sooner or later so nodes do not
|
|
// all ask at once). AntiEntropyPeers is how many peers a round asks
|
|
// (default 3). A round with matching digests costs almost nothing.
|
|
AntiEntropyInterval time.Duration
|
|
AntiEntropyPeers int
|
|
// IntakeSummaryEvery is how often the node logs how many listings reached
|
|
// it by gossip since the last time (default 1 min; nothing is logged when
|
|
// none did).
|
|
IntakeSummaryEvery time.Duration
|
|
Clock func() time.Time // default time.Now
|
|
Logger *slog.Logger
|
|
// Bandwidth, if set, counts the bytes this node sends and receives (the
|
|
// simulator uses it; a real node leaves it nil).
|
|
Bandwidth metrics.Reporter
|
|
// MaxConns is the number of inbound connections the node accepts. Zero
|
|
// means DefaultPublicConns for a Public node and libp2p's own default
|
|
// (which scales with memory) for any other; a negative number keeps
|
|
// libp2p's default even for a Public node.
|
|
MaxConns int
|
|
// MaxConnsPerIP is how many inbound connections one public IP address (an
|
|
// IPv6 /64) may hold; local and private addresses are exempt. Zero means
|
|
// DefaultConnsPerIP, a negative number no limit.
|
|
MaxConnsPerIP int
|
|
// ExtraOptions are added to the libp2p host's options; the simulator uses
|
|
// them to put latency and connection loss on the transport.
|
|
ExtraOptions []libp2p.Option
|
|
}
|
|
|
|
// Node is a running participant.
|
|
type Node struct {
|
|
cfg Config
|
|
host host.Host
|
|
ps *pubsub.PubSub
|
|
clock func() time.Time
|
|
log *slog.Logger
|
|
// guard rate-limits and bans the peers that relay to us.
|
|
guard *peerGuard
|
|
// gossipIn counts listings that arrived by gossip since the last summary.
|
|
gossipIn tally
|
|
|
|
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
|
|
repTopic *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.AntiEntropyInterval <= 0 {
|
|
cfg.AntiEntropyInterval = 10 * time.Minute
|
|
}
|
|
if cfg.AntiEntropyPeers <= 0 {
|
|
cfg.AntiEntropyPeers = 3
|
|
}
|
|
if cfg.IntakeSummaryEvery <= 0 {
|
|
cfg.IntakeSummaryEvery = defaultIntakeSummary
|
|
}
|
|
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 }))
|
|
}
|
|
conns := cfg.MaxConns
|
|
if conns == 0 && cfg.Public {
|
|
conns = DefaultPublicConns
|
|
}
|
|
if conns > 0 {
|
|
limits, err := connectionLimits(conns)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("connection limits: %w", err)
|
|
}
|
|
opts = append(opts, limits)
|
|
}
|
|
perIP := cfg.MaxConnsPerIP
|
|
if perIP == 0 {
|
|
perIP = DefaultConnsPerIP
|
|
}
|
|
gate := newIPGate(max(perIP, 0))
|
|
opts = append(opts, libp2p.ConnectionGater(gate))
|
|
opts = append(opts, cfg.ExtraOptions...)
|
|
if cfg.Bandwidth != nil {
|
|
opts = append(opts, libp2p.BandwidthReporter(cfg.Bandwidth))
|
|
}
|
|
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.guard, err = newPeerGuard(h.ID(), n.clock, log, func(p peer.ID) { _ = h.Network().ClosePeer(p) })
|
|
if err != nil {
|
|
n.Close()
|
|
return nil, err
|
|
}
|
|
h.Network().Notify(gate.notifee())
|
|
banned := n.guard.banned
|
|
gate.banned.Store(&banned)
|
|
n.ps, err = pubsub.NewGossipSub(nctx, h,
|
|
pubsub.WithMaxMessageSize(listing.MaxSize+4096),
|
|
pubsub.WithFloodPublish(true),
|
|
pubsub.WithBlacklist(n.guard.bl))
|
|
if err != nil {
|
|
n.Close()
|
|
return nil, err
|
|
}
|
|
if err := n.startRevocations(); err != nil {
|
|
n.Close()
|
|
return nil, err
|
|
}
|
|
if err := n.startReports(); 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(6)
|
|
go func() {
|
|
defer n.wg.Done()
|
|
n.dialBootstrap()
|
|
n.dialCached()
|
|
}()
|
|
go n.summarizeIntake()
|
|
go n.maintain()
|
|
go n.redial()
|
|
go n.antiEntropy()
|
|
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)
|
|
}
|
|
|
|
// PublishReport stores r locally and gossips it to the whole network.
|
|
func (n *Node) PublishReport(ctx context.Context, r *report.Report) error {
|
|
if _, err := n.cfg.Store.PutReport(ctx, r); err != nil {
|
|
return err
|
|
}
|
|
data, err := r.Bytes()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return n.repTopic.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.guard.wrap(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
|
|
}
|
|
|
|
func (n *Node) startReports() error {
|
|
if err := n.ps.RegisterTopicValidator(ReportTopic, n.guard.wrap(n.reportValidator),
|
|
pubsub.WithValidatorTimeout(5*time.Second)); err != nil {
|
|
return err
|
|
}
|
|
t, err := n.ps.Join(ReportTopic)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
sub, err := t.Subscribe()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
n.repTopic = t
|
|
n.wg.Add(1)
|
|
go func() {
|
|
defer n.wg.Done()
|
|
n.consume(n.ctx, sub, func(msg *pubsub.Message) {
|
|
r, ok := msg.ValidatorData.(*report.Report)
|
|
if !ok {
|
|
return
|
|
}
|
|
if _, err := n.cfg.Store.PutReport(n.ctx, r); err != nil && !errors.Is(err, store.ErrRevoked) {
|
|
n.log.Warn("store report", "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 := ®ionRun{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 n.exchangePeers(rctx, 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 out, err := n.cfg.Store.Put(n.ctx, l); {
|
|
case err == nil:
|
|
n.noteListing(n.ctx, l, out, "gossip", msg.ReceivedFrom)
|
|
case errors.Is(err, store.ErrRevoked), errors.Is(err, store.ErrQuota):
|
|
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.guard.wrap(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.guard.wrap(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) reportValidator(ctx context.Context, _ peer.ID, msg *pubsub.Message) pubsub.ValidationResult {
|
|
if len(msg.Data) > report.MaxSize {
|
|
return pubsub.ValidationReject
|
|
}
|
|
var r report.Report
|
|
if err := json.Unmarshal(msg.Data, &r); err != nil {
|
|
return pubsub.ValidationReject
|
|
}
|
|
// Only the canonical encoding, so every node derives the same message ID.
|
|
if canon, err := r.Bytes(); err != nil || !bytes.Equal(canon, msg.Data) {
|
|
return pubsub.ValidationReject
|
|
}
|
|
if err := r.Check(n.clock(), n.cfg.Difficulty); err != nil {
|
|
if errors.Is(err, report.ErrTimeWindow) {
|
|
return pubsub.ValidationIgnore // clocks differ; not the relay's fault
|
|
}
|
|
return pubsub.ValidationReject
|
|
}
|
|
if revoked, err := n.cfg.Store.IsRevoked(ctx, r.Reporter, r.Device, r.Cert.IssuedAt); err != nil || revoked {
|
|
return pubsub.ValidationIgnore
|
|
}
|
|
msg.ValidatorData = &r
|
|
return pubsub.ValidationAccept
|
|
}
|
|
|
|
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()
|
|
}
|
|
}
|
|
}
|
|
|
|
// antiEntropy repairs what gossip lost while the node stayed connected, which
|
|
// the sync on a new connection cannot: every interval (give or take a fifth)
|
|
// it syncs with a few random peers that share a region. Matching digests make
|
|
// a round nearly free.
|
|
func (n *Node) antiEntropy() {
|
|
defer n.wg.Done()
|
|
for {
|
|
d := n.cfg.AntiEntropyInterval
|
|
d = d - d/5 + time.Duration(rand.Int64N(int64(d)*2/5+1))
|
|
if !sleepCtx(n.ctx, d) {
|
|
return
|
|
}
|
|
n.antiEntropyOnce()
|
|
}
|
|
}
|
|
|
|
func (n *Node) antiEntropyOnce() {
|
|
n.mu.Lock()
|
|
regions := append([]string(nil), n.subscribed...)
|
|
n.mu.Unlock()
|
|
seen := map[peer.ID]bool{}
|
|
var peers []peer.ID
|
|
for _, r := range regions {
|
|
for _, p := range n.RegionPeers(r) {
|
|
if !seen[p] && n.host.Network().Connectedness(p) == network.Connected {
|
|
seen[p] = true
|
|
peers = append(peers, p)
|
|
}
|
|
}
|
|
}
|
|
rand.Shuffle(len(peers), func(i, j int) { peers[i], peers[j] = peers[j], peers[i] })
|
|
for _, p := range peers[:min(len(peers), n.cfg.AntiEntropyPeers)] {
|
|
n.syncSoon(p)
|
|
}
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
}
|
|
}
|
|
}
|