- cmd/node: init (recovery phrase onboarding), run, recover - api: public reads of canonical signed records, token-protected writes - identity: RevokeAll voids every device certified before a cutoff, so recovery works with only the phrase; store purges by certificate age - p2p: redial bootstrap peers, sync on every new connection (in-flight guard only), validate bootstrap addresses up front - docs: API, recovery semantics, peer-ID change on recovery Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
227 lines
5.6 KiB
Go
227 lines
5.6 KiB
Go
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 starts a catch-up with p for a new connection. Every genuinely new
|
|
// connection syncs, so a peer that reconnects after a restart or outage gets
|
|
// everything it missed. Connections that arrive while a sync with the same
|
|
// peer is still running (e.g. TCP and QUIC opened together) are collapsed.
|
|
func (n *Node) syncSoon(p peer.ID) {
|
|
n.mu.Lock()
|
|
if n.syncing[p] {
|
|
n.mu.Unlock()
|
|
return
|
|
}
|
|
n.syncing[p] = true
|
|
n.mu.Unlock()
|
|
|
|
n.wg.Add(1)
|
|
go func() {
|
|
defer n.wg.Done()
|
|
defer func() {
|
|
n.mu.Lock()
|
|
delete(n.syncing, p)
|
|
n.mu.Unlock()
|
|
}()
|
|
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
|
|
}
|