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
+163
View File
@@ -0,0 +1,163 @@
package main
import (
"context"
"errors"
"flag"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"git.stinnesbeck.com/nils/allmende/internal/api"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/p2p"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
const (
announceFirst = 10 * time.Second
announceInterval = 30 * time.Minute
certWarnBefore = 30 * 24 * time.Hour
)
func cmdRun(args []string) error {
fs := flag.NewFlagSet("run", flag.ExitOnError)
data := dataFlag(fs)
var regions, bootstrap, listen listFlag
fs.Var(&regions, "region", "geohash region (3 characters, e.g. u1x) to replicate; repeatable")
fs.Var(&bootstrap, "bootstrap", "multiaddr of a known peer (…/p2p/<id>); repeatable")
fs.Var(&listen, "listen", "libp2p listen multiaddr; repeatable (default: all interfaces, random ports)")
httpAddr := fs.String("http", "127.0.0.1:8080", "address for the HTTP API")
noMDNS := fs.Bool("no-mdns", false, "do not look for peers on the local network")
difficulty := fs.Int("difficulty", listing.DefaultDifficulty,
"proof-of-work bits; must match the rest of the network")
fs.Parse(args)
if len(regions) == 0 {
return errors.New("choose at least one region to replicate, e.g. --region u1x (a region is a 3-character geohash, about 150 km wide)")
}
dev, err := identity.LoadDevice(*data)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("%s is not set up yet: run 'node init' first", *data)
}
return err
}
until := time.Until(time.Unix(dev.Cert.ExpiresAt, 0))
if until <= 0 {
return errors.New("this device's certificate has expired; run 'node recover' to renew it")
}
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
if until < certWarnBefore {
log.Warn("device certificate expires soon; run 'node recover' to renew it",
"expires", time.Unix(dev.Cert.ExpiresAt, 0).Format("2006-01-02"))
}
st, err := store.Open(filepath.Join(*data, dbFile), store.Options{Difficulty: *difficulty})
if err != nil {
return err
}
defer st.Close()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
node, err := p2p.New(ctx, p2p.Config{
Device: dev,
Store: st,
ListenAddrs: listen,
Bootstrap: bootstrap,
Regions: regions,
MDNS: !*noMDNS,
Difficulty: *difficulty,
Logger: log,
})
if err != nil {
return err
}
defer node.Close()
token := readToken(*data)
if token == "" {
log.Warn("no admin token found; publishing through the API is disabled")
}
handler := api.New(api.Config{
Store: st, Node: node, Device: dev, Regions: regions, Token: token, Difficulty: *difficulty,
})
ln, err := net.Listen("tcp", *httpAddr)
if err != nil {
return err
}
srv := &http.Server{
Handler: handler,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 60 * time.Second, // publishing mines proof-of-work
IdleTimeout: 2 * time.Minute,
}
go func() {
if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Error("http server", "err", err)
stop()
}
}()
log.Info("node running",
"peer_id", node.ID().String(), "identity", dev.Cert.Author[:12]+"…",
"regions", []string(regions), "http", ln.Addr().String())
for _, a := range node.Addrs() {
log.Info("listening", "addr", a)
}
if host, _, _ := net.SplitHostPort(ln.Addr().String()); host != "127.0.0.1" && host != "::1" {
log.Warn("the HTTP API is reachable from other machines; put it behind TLS if it is public")
}
go announce(ctx, log, node, st, dev.Cert.Author)
<-ctx.Done()
log.Info("shutting down")
shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return srv.Shutdown(shutdown)
}
// announce periodically re-gossips this identity's revocations and live
// listings. Gossip only reaches peers connected at that moment; this makes
// sure newcomers hear about them without waiting for a sync.
func announce(ctx context.Context, log *slog.Logger, node *p2p.Node, st *store.Store, author string) {
timer := time.NewTimer(announceFirst)
defer timer.Stop()
for {
select {
case <-ctx.Done():
return
case <-timer.C:
}
if revs, err := st.Revocations(ctx); err == nil {
for _, r := range revs {
if r.Author == author {
if err := node.PublishRevocation(ctx, r); err != nil {
log.Debug("announce revocation", "err", err)
}
}
}
}
if own, err := st.ByAuthor(ctx, author); err == nil {
for _, l := range own {
if err := node.Publish(ctx, l); err != nil {
log.Debug("announce listing", "id", l.ID, "err", err)
}
}
}
timer.Reset(announceInterval)
}
}