Add runnable node, HTTP API, all-devices revocation and reconnect sync

- 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>
This commit is contained in:
2026-11-17 18:03:46 +01:00
co-authored by Claude Sonnet 5.5
parent d3efe5a3a7
commit 918e16ed37
18 changed files with 1550 additions and 82 deletions
+68 -21
View File
@@ -39,7 +39,6 @@ const (
RevocationTopic = "/allmende/1/revocations"
mdnsService = "allmende"
resyncInterval = 5 * time.Minute
maintenanceTick = time.Hour
)
@@ -53,10 +52,11 @@ type Config struct {
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
Difficulty int // required proof-of-work bits
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.
@@ -75,7 +75,8 @@ type Node struct {
mu sync.Mutex
topics map[string]*pubsub.Topic
subscribed []string
synced map[peer.ID]time.Time
bootstrap []peer.AddrInfo
syncing map[peer.ID]bool
revTopic *pubsub.Topic
}
@@ -95,6 +96,17 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
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 {
@@ -107,14 +119,15 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
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{},
cfg: cfg,
host: h,
clock: cfg.Clock,
log: cfg.Logger,
ctx: nctx,
cancel: cancel,
topics: map[string]*pubsub.Topic{},
syncing: map[peer.ID]bool{},
bootstrap: bootstrap,
}
if n.clock == nil {
n.clock = time.Now
@@ -149,11 +162,7 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
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)
}
}
n.dialBootstrap()
if cfg.MDNS {
n.mdns = mdns.NewMdnsService(h, mdnsService, &mdnsNotifee{n: n})
if err := n.mdns.Start(); err != nil {
@@ -162,8 +171,9 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
}
}
n.wg.Add(1)
n.wg.Add(2)
go n.maintain()
go n.redial()
return n, nil
}
@@ -192,6 +202,9 @@ func (n *Node) Connect(ctx context.Context, addr string) error {
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)
@@ -366,7 +379,7 @@ func (n *Node) validateListing(ctx context.Context, data []byte) (*listing.Listi
}
return nil, pubsub.ValidationReject
}
if revoked, err := n.cfg.Store.IsRevoked(ctx, l.Author, l.Device); err != nil || revoked {
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
@@ -417,6 +430,40 @@ func (m *mdnsNotifee) HandlePeerFound(pi peer.AddrInfo) {
}()
}
// 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()
+75 -10
View File
@@ -6,6 +6,7 @@ import (
"errors"
"io"
"log/slog"
"os"
"testing"
"time"
@@ -19,6 +20,14 @@ import (
const difficulty = 6
// testLogger is silent unless P2P_DEBUG is set.
func testLogger() *slog.Logger {
if os.Getenv("P2P_DEBUG") != "" {
return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug}))
}
return slog.New(slog.NewTextHandler(io.Discard, nil))
}
type tnode struct {
*Node
s *store.Store
@@ -27,6 +36,11 @@ type tnode struct {
}
func startNode(t *testing.T, root *identity.Identity, regions ...string) *tnode {
t.Helper()
return startNodeWith(t, root, nil, regions...)
}
func startNodeWith(t *testing.T, root *identity.Identity, tweak func(*Config), regions ...string) *tnode {
t.Helper()
if root == nil {
root, _, _ = identity.NewRoot()
@@ -39,15 +53,20 @@ func startNode(t *testing.T, root *identity.Identity, regions ...string) *tnode
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)),
})
cfg := Config{
Device: dev,
Store: s,
ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
Regions: regions,
Difficulty: difficulty,
SyncPageSize: 3,
RedialInterval: 200 * time.Millisecond,
Logger: testLogger(),
}
if tweak != nil {
tweak(&cfg)
}
n, err := New(context.Background(), cfg)
if err != nil {
t.Fatal(err)
}
@@ -207,7 +226,7 @@ func TestRevocationPropagatesAndBlocks(t *testing.T) {
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)
ok, _ := late.s.IsRevoked(ctx, a.dev.Cert.Author, a.dev.Cert.Device, a.dev.Cert.IssuedAt)
return ok
})
}
@@ -255,3 +274,49 @@ func TestValidatorRejectsBadMessages(t *testing.T) {
t.Fatalf("expired listing: %v", r)
}
}
func TestRedialsBootstrapPeerAfterDisconnect(t *testing.T) {
a := startNode(t, nil, "u1x")
b := startNodeWith(t, nil, func(c *Config) { c.Bootstrap = []string{a.Addrs()[0]} }, "u1x")
eventually(t, "b connected to a", func() bool { return b.PeerCount() == 1 })
if err := b.host.Network().ClosePeer(a.ID()); err != nil {
t.Fatal(err)
}
eventually(t, "b redials its bootstrap peer", func() bool { return b.PeerCount() == 1 })
}
func TestEveryNewConnectionCatchesUp(t *testing.T) {
a := startNode(t, nil, "u1x")
b := startNode(t, nil, "u1x")
connect(t, b, a)
eventually(t, "first connection settled", func() bool { return len(b.RegionPeers("u1x")) == 1 })
// The link drops, and a gains a listing that is never gossiped to b.
l := a.listing(t, "u1xjhx") // sealed up front: proof-of-work is slow under -race
if err := b.host.Network().ClosePeer(a.ID()); err != nil {
t.Fatal(err)
}
eventually(t, "link is down", func() bool { return b.PeerCount() == 0 })
if _, err := a.s.Put(context.Background(), l); err != nil {
t.Fatal(err)
}
// A reconnect, however soon after the last sync, must catch up.
connect(t, b, a)
eventually(t, "b catches up after reconnecting", func() bool { return count(b) == 1 })
}
func TestBadBootstrapAddressRejectedUpFront(t *testing.T) {
root, _, _ := identity.NewRoot()
dev, _ := identity.Enroll(root, time.Now().Add(-time.Hour), 24*time.Hour)
s, _ := store.Open(":memory:", store.Options{Difficulty: difficulty})
defer s.Close()
_, err := New(context.Background(), Config{
Device: dev, Store: s, ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
Bootstrap: []string{"not-an-address"},
})
if err == nil {
t.Fatal("malformed bootstrap address accepted")
}
}
+11 -3
View File
@@ -105,19 +105,27 @@ func (n *Node) handleSync(s network.Stream) {
// --- client ---------------------------------------------------------------
// syncSoon schedules a catch-up with p, at most once per resyncInterval.
// 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 last, ok := n.synced[p]; ok && n.clock().Sub(last) < resyncInterval {
if n.syncing[p] {
n.mu.Unlock()
return
}
n.synced[p] = n.clock()
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 {