Add device keys, revocation and libp2p gossip with sync

- 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>
This commit is contained in:
2026-11-17 17:43:25 +01:00
co-authored by Claude Sonnet 5.5
parent 08f6441f03
commit d3efe5a3a7
16 changed files with 2306 additions and 119 deletions
+437
View File
@@ -0,0 +1,437 @@
// 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)
}
}
}
}
+257
View File
@@ -0,0 +1,257 @@
package p2p
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"testing"
"time"
pubsub "github.com/libp2p/go-libp2p-pubsub"
pb "github.com/libp2p/go-libp2p-pubsub/pb"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
const difficulty = 6
type tnode struct {
*Node
s *store.Store
root *identity.Identity
dev *identity.Device
}
func startNode(t *testing.T, root *identity.Identity, regions ...string) *tnode {
t.Helper()
if root == nil {
root, _, _ = identity.NewRoot()
}
dev, err := identity.Enroll(root, time.Now().Add(-time.Hour), 90*24*time.Hour)
if err != nil {
t.Fatal(err)
}
s, err := store.Open(":memory:", store.Options{Difficulty: difficulty})
if err != nil {
t.Fatal(err)
}
n, err := New(context.Background(), Config{
Device: dev,
Store: s,
ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
Regions: regions,
Difficulty: difficulty,
SyncPageSize: 3,
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { n.Close(); s.Close() })
return &tnode{Node: n, s: s, root: root, dev: dev}
}
func (tn *tnode) listing(t *testing.T, geohash string) *listing.Listing {
t.Helper()
id, _ := listing.NewID()
now := time.Now()
l := &listing.Listing{
Version: listing.Version,
ID: id,
Seq: 1,
CreatedAt: now.Unix(),
ExpiresAt: now.Add(7 * 24 * time.Hour).Unix(),
Kind: "rent",
Category: "apartment",
Geohash: geohash,
Price: &listing.Price{AmountCents: 100000, Currency: "EUR", Period: "month"},
Title: "Wohnung",
}
if err := l.Seal(tn.dev, difficulty); err != nil {
t.Fatal(err)
}
return l
}
func connect(t *testing.T, from, to *tnode) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := from.Connect(ctx, to.Addrs()[0]); err != nil {
t.Fatal(err)
}
}
func eventually(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(15 * time.Second)
for time.Now().Before(deadline) {
if cond() {
return
}
time.Sleep(50 * time.Millisecond)
}
t.Fatalf("timed out waiting for: %s", what)
}
func count(tn *tnode) int {
n, _ := tn.s.Count(context.Background())
return n
}
func TestGossipDeliversWithinRegion(t *testing.T) {
a := startNode(t, nil, "u1x")
b := startNode(t, nil, "u1x")
c := startNode(t, nil, "u30") // different region
connect(t, b, a)
connect(t, c, a)
eventually(t, "a sees b on the region topic", func() bool { return len(a.RegionPeers("u1x")) == 1 })
l := a.listing(t, "u1xjhx")
if err := a.Publish(context.Background(), l); err != nil {
t.Fatal(err)
}
eventually(t, "b receives the listing", func() bool { return count(b) == 1 })
got, err := b.s.Get(context.Background(), l.Author, l.ID)
if err != nil || got.Title != "Wohnung" {
t.Fatalf("b has %v, %v", got, err)
}
time.Sleep(500 * time.Millisecond)
if count(c) != 0 {
t.Fatal("node in another region received the listing")
}
}
func TestSyncCatchesUpLateJoiner(t *testing.T) {
a := startNode(t, nil, "u1x")
ctx := context.Background()
// Seven listings (page size is 3, so three pages), one of them deleted,
// plus one in a region b does not replicate.
var ls []*listing.Listing
for i := 0; i < 7; i++ {
l := a.listing(t, "u1xjhx")
if _, err := a.s.Put(ctx, l); err != nil {
t.Fatal(err)
}
ls = append(ls, l)
}
ts := &listing.Listing{
Version: listing.Version, ID: ls[0].ID, Seq: 2,
CreatedAt: time.Now().Unix(), ExpiresAt: time.Now().Add(30 * 24 * time.Hour).Unix(),
Tombstone: true, Geohash: ls[0].Geohash,
}
if err := ts.Seal(a.dev, difficulty); err != nil {
t.Fatal(err)
}
if _, err := a.s.Put(ctx, ts); err != nil {
t.Fatal(err)
}
other := a.listing(t, "u30000")
if _, err := a.s.Put(ctx, other); err != nil {
t.Fatal(err)
}
b := startNode(t, nil, "u1x") // joins after everything was published
connect(t, b, a)
eventually(t, "b has caught up", func() bool { return count(b) == 6 })
if _, err := b.s.Get(ctx, ls[0].Author, ls[0].ID); !errors.Is(err, store.ErrNotFound) {
t.Fatal("deleted listing was not deleted on the late joiner")
}
if _, err := b.s.Get(ctx, other.Author, other.ID); !errors.Is(err, store.ErrNotFound) {
t.Fatal("b stored a listing from a region it does not replicate")
}
}
func TestRevocationPropagatesAndBlocks(t *testing.T) {
owner, _, _ := identity.NewRoot()
a := startNode(t, owner, "u1x") // the owner's (soon to be compromised) node
b := startNode(t, nil, "u1x")
connect(t, b, a)
eventually(t, "mesh formed", func() bool {
return len(a.RegionPeers("u1x")) == 1 && len(b.RegionPeers("u1x")) == 1
})
ctx := context.Background()
l := a.listing(t, "u1xjhx")
if err := a.Publish(ctx, l); err != nil {
t.Fatal(err)
}
eventually(t, "b has the listing", func() bool { return count(b) == 1 })
// The owner enters the recovery phrase on a new machine and revokes node a.
rev, err := identity.Revoke(owner, a.dev.Cert, time.Now(), difficulty)
if err != nil {
t.Fatal(err)
}
newMachine := startNode(t, owner, "u1x")
connect(t, newMachine, b)
if err := newMachine.PublishRevocation(ctx, rev); err != nil {
t.Fatal(err)
}
eventually(t, "b dropped the revoked device's listing", func() bool { return count(b) == 0 })
eventually(t, "a dropped it too", func() bool { return count(a) == 0 })
// The compromised node can no longer publish anything.
if err := a.Publish(ctx, a.listing(t, "u1xjhx")); !errors.Is(err, store.ErrRevoked) {
t.Fatalf("revoked node could publish: %v", err)
}
// A node joining later learns about the revocation through sync.
late := startNode(t, nil, "u1x")
connect(t, late, b)
eventually(t, "late joiner learns the revocation", func() bool {
ok, _ := late.s.IsRevoked(ctx, a.dev.Cert.Author, a.dev.Cert.Device)
return ok
})
}
func TestValidatorRejectsBadMessages(t *testing.T) {
a := startNode(t, nil, "u1x")
good := a.listing(t, "u1xjhx")
goodBytes, _ := good.Bytes()
validate := func(region string, data []byte) pubsub.ValidationResult {
v := a.listingValidator(region)
return v(context.Background(), "", &pubsub.Message{Message: &pb.Message{Data: data}})
}
if r := validate("u1x", goodBytes); r != pubsub.ValidationAccept {
t.Fatalf("good listing: %v", r)
}
if r := validate("u30", goodBytes); r != pubsub.ValidationReject {
t.Fatalf("listing on the wrong region topic: %v", r)
}
if r := validate("u1x", []byte(`{"v":1`)); r != pubsub.ValidationReject {
t.Fatalf("garbage: %v", r)
}
tampered := *good
tampered.Title = "Betrug"
tb, _ := tampered.Bytes()
if r := validate("u1x", tb); r != pubsub.ValidationReject {
t.Fatalf("tampered listing: %v", r)
}
// Valid content, but not in canonical form (extra whitespace).
var m map[string]any
_ = json.Unmarshal(goodBytes, &m)
pretty, _ := json.MarshalIndent(m, "", " ")
if r := validate("u1x", pretty); r != pubsub.ValidationReject {
t.Fatalf("non-canonical encoding: %v", r)
}
// Expired: ignored (clock difference), not penalized.
old := a.listing(t, "u1xjhx")
a.clock = func() time.Time { return time.Now().Add(30 * 24 * time.Hour) }
ob, _ := old.Bytes()
if r := validate("u1x", ob); r != pubsub.ValidationIgnore {
t.Fatalf("expired listing: %v", r)
}
}
+218
View File
@@ -0,0 +1,218 @@
package p2p
import (
"bufio"
"context"
"encoding/json"
"io"
"time"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
// SyncProtocol lets a node catch up with everything a peer holds for a
// region. Gossip only delivers what is published while you are online.
//
// Request: one JSON object. Response: newline-delimited canonical JSON
// records, then EOF. Listings are paged with a keyset cursor over
// (created_at, author, id), so pages are stable and cannot loop.
const SyncProtocol = "/allmende/1/sync"
const (
syncTimeout = 2 * time.Minute
maxSyncPages = 200 // bounds work per region against a misbehaving peer
maxRevocations = 5000
)
type syncRequest struct {
Kind string `json:"kind"` // "listings" or "revocations"
Region string `json:"region,omitempty"`
AfterCreated int64 `json:"after_created,omitempty"`
AfterAuthor string `json:"after_author,omitempty"`
AfterID string `json:"after_id,omitempty"`
Limit int `json:"limit,omitempty"`
}
// --- server ---------------------------------------------------------------
func (n *Node) handleSync(s network.Stream) {
defer s.Close()
_ = s.SetDeadline(time.Now().Add(syncTimeout))
var req syncRequest
if err := json.NewDecoder(io.LimitReader(s, 4096)).Decode(&req); err != nil {
_ = s.Reset()
return
}
w := bufio.NewWriter(s)
write := func(b []byte, err error) bool {
if err != nil {
return false
}
w.Write(b)
w.WriteByte('\n')
return true
}
switch req.Kind {
case "listings":
if !listing.ValidRegion(req.Region) {
_ = s.Reset()
return
}
limit := req.Limit
if limit <= 0 || limit > n.cfg.SyncPageSize {
limit = n.cfg.SyncPageSize
}
items, err := n.cfg.Store.Since(n.ctx, req.Region,
store.Cursor{CreatedAt: req.AfterCreated, Author: req.AfterAuthor, ID: req.AfterID}, limit)
if err != nil {
_ = s.Reset()
return
}
for _, l := range items {
if !write(l.Bytes()) {
_ = s.Reset()
return
}
}
case "revocations":
revs, err := n.cfg.Store.Revocations(n.ctx)
if err != nil {
_ = s.Reset()
return
}
if len(revs) > maxRevocations {
revs = revs[:maxRevocations]
}
for _, r := range revs {
if !write(r.Bytes()) {
_ = s.Reset()
return
}
}
default:
_ = s.Reset()
return
}
_ = w.Flush()
}
// --- client ---------------------------------------------------------------
// syncSoon schedules a catch-up with p, at most once per resyncInterval.
func (n *Node) syncSoon(p peer.ID) {
n.mu.Lock()
if last, ok := n.synced[p]; ok && n.clock().Sub(last) < resyncInterval {
n.mu.Unlock()
return
}
n.synced[p] = n.clock()
n.mu.Unlock()
n.wg.Add(1)
go func() {
defer n.wg.Done()
ctx, cancel := context.WithTimeout(n.ctx, syncTimeout)
defer cancel()
if err := n.SyncFrom(ctx, p); err != nil {
n.log.Debug("sync", "peer", p, "err", err)
}
}()
}
// SyncFrom pulls revocations and then every subscribed region from p.
// Revocations go first so listings from revoked devices are refused.
func (n *Node) SyncFrom(ctx context.Context, p peer.ID) error {
if err := n.syncRevocations(ctx, p); err != nil {
return err
}
n.mu.Lock()
regions := append([]string(nil), n.subscribed...)
n.mu.Unlock()
for _, region := range regions {
if err := n.syncRegion(ctx, p, region); err != nil {
return err
}
}
return nil
}
func (n *Node) syncRevocations(ctx context.Context, p peer.ID) error {
return n.request(ctx, p, syncRequest{Kind: "revocations"}, func(line []byte) {
var r identity.Revocation
if json.Unmarshal(line, &r) != nil {
return
}
if _, err := n.cfg.Store.PutRevocation(ctx, &r); err != nil {
n.log.Debug("sync: revocation rejected", "peer", p, "err", err)
}
})
}
func (n *Node) syncRegion(ctx context.Context, p peer.ID, region string) error {
var cur store.Cursor
for page := 0; page < maxSyncPages; page++ {
var count int
var last *listing.Listing
err := n.request(ctx, p, syncRequest{
Kind: "listings", Region: region, Limit: n.cfg.SyncPageSize,
AfterCreated: cur.CreatedAt, AfterAuthor: cur.Author, AfterID: cur.ID,
}, func(line []byte) {
var l listing.Listing
if json.Unmarshal(line, &l) != nil {
return
}
count++
last = &l
if listing.Region(l.Geohash) != region {
return // peer sent something we did not ask for
}
if _, err := n.cfg.Store.Put(ctx, &l); err != nil {
n.log.Debug("sync: listing rejected", "peer", p, "err", err)
}
})
if err != nil {
return err
}
if count < n.cfg.SyncPageSize || last == nil {
return nil
}
cur = store.CursorOf(last)
}
return nil
}
// request opens a sync stream, sends req and calls handle for each line.
func (n *Node) request(ctx context.Context, p peer.ID, req syncRequest, handle func([]byte)) error {
s, err := n.host.NewStream(ctx, p, SyncProtocol)
if err != nil {
return err
}
defer s.Close()
_ = s.SetDeadline(time.Now().Add(syncTimeout))
if err := json.NewEncoder(s).Encode(req); err != nil {
_ = s.Reset()
return err
}
if err := s.CloseWrite(); err != nil {
_ = s.Reset()
return err
}
sc := bufio.NewScanner(s)
sc.Buffer(make([]byte, 0, 64<<10), listing.MaxSize+4096)
for sc.Scan() {
handle(sc.Bytes())
}
if err := sc.Err(); err != nil {
_ = s.Reset()
return err
}
return nil
}