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
+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
}