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
+353
View File
@@ -0,0 +1,353 @@
// Package api is the node's HTTP interface.
//
// Reading is public: it serves the signed listing records exactly as
// replicated, so a browser can verify every signature itself and does not
// have to trust the gateway. Writing (publish, update, delete) acts as the
// node's owner and requires the admin bearer token.
package api
import (
"context"
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"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 (
maxBody = 64 << 10
defaultLifetime = 30 // days
)
// Config wires the API to a running node.
type Config struct {
Store *store.Store
Node *p2p.Node
Device *identity.Device
Regions []string
Token string // admin bearer token; empty disables all writes
Difficulty int
Clock func() time.Time
}
type server struct {
Config
}
// New returns the HTTP handler.
func New(cfg Config) http.Handler {
if cfg.Clock == nil {
cfg.Clock = time.Now
}
s := &server{cfg}
mux := http.NewServeMux()
mux.HandleFunc("GET /api/v1/status", s.status)
mux.HandleFunc("GET /api/v1/listings", s.search)
mux.HandleFunc("GET /api/v1/listings/{author}/{id}", s.get)
mux.HandleFunc("POST /api/v1/listings", s.admin(s.create))
mux.HandleFunc("PUT /api/v1/listings/{id}", s.admin(s.update))
mux.HandleFunc("DELETE /api/v1/listings/{id}", s.admin(s.remove))
return mux
}
// --- reading --------------------------------------------------------------
func (s *server) status(w http.ResponseWriter, r *http.Request) {
n, err := s.Store.Count(r.Context())
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"peer_id": s.Node.ID().String(),
"addrs": s.Node.Addrs(),
"author": s.Device.Cert.Author,
"device": s.Device.Cert.Device,
"regions": s.Regions,
"peers": s.Node.PeerCount(),
"listings": n,
})
}
func (s *server) search(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
query := store.Query{Kind: q.Get("kind"), Category: q.Get("category")}
if g := q.Get("geohash"); g != "" {
for _, p := range strings.Split(g, ",") {
if !listing.ValidGeohashPrefix(p) {
fail(w, http.StatusBadRequest, fmt.Sprintf("invalid geohash prefix %q", p))
return
}
query.Geohashes = append(query.Geohashes, p)
}
}
ints := []struct {
name string
dst any
}{
{"min_price", &query.MinPriceCents}, {"max_price", &query.MaxPriceCents},
{"min_area", &query.MinAreaM2}, {"min_rooms", &query.MinRoomsX2},
{"limit", &query.Limit}, {"offset", &query.Offset},
}
for _, f := range ints {
v := q.Get(f.name)
if v == "" {
continue
}
n, err := strconv.ParseInt(v, 10, 64)
if err != nil || n < 0 {
fail(w, http.StatusBadRequest, fmt.Sprintf("%s must be a non-negative integer", f.name))
return
}
switch d := f.dst.(type) {
case *int64:
*d = n
case *int:
*d = int(n)
}
}
items, err := s.Store.Search(r.Context(), query)
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
writeListings(w, items)
}
func (s *server) get(w http.ResponseWriter, r *http.Request) {
l, err := s.Store.Get(r.Context(), r.PathValue("author"), r.PathValue("id"))
if errors.Is(err, store.ErrNotFound) {
fail(w, http.StatusNotFound, "not found")
return
}
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
b, err := l.Bytes()
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
setPublic(w)
w.Header().Set("Content-Type", "application/json")
w.Write(b)
}
// writeListings sends the records in their canonical encoding so clients can
// verify signatures over the exact bytes.
func writeListings(w http.ResponseWriter, items []*listing.Listing) {
setPublic(w)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("["))
for i, l := range items {
b, err := l.Bytes()
if err != nil {
continue
}
if i > 0 {
w.Write([]byte(","))
}
w.Write(b)
}
w.Write([]byte("]"))
}
// setPublic marks a response as public data that any website may read.
func setPublic(w http.ResponseWriter) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Cache-Control", "public, max-age=15")
}
// --- writing --------------------------------------------------------------
// draft is what the owner provides; the node adds identity, time, proof of
// work and signature. Images are not supported yet.
type draft struct {
Kind string `json:"kind"`
Category string `json:"category"`
Geohash string `json:"geohash"`
Price *listing.Price `json:"price"`
AreaM2 int `json:"area_m2"`
RoomsX2 int `json:"rooms_x2"`
Features []string `json:"features"`
Title string `json:"title"`
Description string `json:"description"`
Delegate string `json:"delegate"`
ExpiresInDays int `json:"expires_in_days"`
}
func (s *server) admin(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if s.Token == "" {
fail(w, http.StatusForbidden, "writing is disabled on this node")
return
}
got := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
if subtle.ConstantTimeCompare([]byte(got), []byte(s.Token)) != 1 {
w.Header().Set("WWW-Authenticate", "Bearer")
fail(w, http.StatusUnauthorized, "missing or wrong admin token")
return
}
next(w, r)
}
}
func (s *server) readDraft(w http.ResponseWriter, r *http.Request) (*draft, bool) {
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBody))
dec.DisallowUnknownFields()
var d draft
if err := dec.Decode(&d); err != nil {
fail(w, http.StatusBadRequest, "invalid JSON body: "+err.Error())
return nil, false
}
if _, err := dec.Token(); err != io.EOF {
fail(w, http.StatusBadRequest, "unexpected data after JSON body")
return nil, false
}
if d.ExpiresInDays < 0 || d.ExpiresInDays > defaultLifetime {
fail(w, http.StatusBadRequest, fmt.Sprintf("expires_in_days must be 1-%d", defaultLifetime))
return nil, false
}
return &d, true
}
func (d *draft) build(id string, seq uint64, now time.Time) *listing.Listing {
days := d.ExpiresInDays
if days == 0 {
days = defaultLifetime
}
return &listing.Listing{
Version: listing.Version,
ID: id,
Seq: seq,
CreatedAt: now.Unix(),
ExpiresAt: now.Add(time.Duration(days) * 24 * time.Hour).Unix(),
Kind: d.Kind,
Category: d.Category,
Geohash: d.Geohash,
Price: d.Price,
AreaM2: d.AreaM2,
RoomsX2: d.RoomsX2,
Features: d.Features,
Title: d.Title,
Description: d.Description,
Delegate: d.Delegate,
}
}
func (s *server) create(w http.ResponseWriter, r *http.Request) {
d, ok := s.readDraft(w, r)
if !ok {
return
}
id, err := listing.NewID()
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
s.seal(w, r, d.build(id, 1, s.Clock()))
}
func (s *server) update(w http.ResponseWriter, r *http.Request) {
d, ok := s.readDraft(w, r)
if !ok {
return
}
old, ok := s.own(w, r)
if !ok {
return
}
if listing.Region(d.Geohash) != listing.Region(old.Geohash) {
fail(w, http.StatusBadRequest,
"the region cannot change; delete this listing and create a new one")
return
}
s.seal(w, r, d.build(old.ID, old.Seq+1, s.Clock()))
}
func (s *server) remove(w http.ResponseWriter, r *http.Request) {
old, ok := s.own(w, r)
if !ok {
return
}
now := s.Clock()
s.seal(w, r, &listing.Listing{
Version: listing.Version,
ID: old.ID,
Seq: old.Seq + 1,
CreatedAt: now.Unix(),
// Outlives every earlier version (<= 30 days), so old copies cannot return.
ExpiresAt: now.Add(listing.MaxLifetime).Unix(),
Tombstone: true,
Geohash: old.Geohash,
})
}
// own loads the caller's live listing named in the URL.
func (s *server) own(w http.ResponseWriter, r *http.Request) (*listing.Listing, bool) {
l, err := s.Store.Get(r.Context(), s.Device.Cert.Author, r.PathValue("id"))
if errors.Is(err, store.ErrNotFound) {
fail(w, http.StatusNotFound, "no such listing of yours")
return nil, false
}
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return nil, false
}
return l, true
}
// seal signs l with the node's device, stores and gossips it, and replies
// with the signed record.
func (s *server) seal(w http.ResponseWriter, r *http.Request, l *listing.Listing) {
if err := l.Seal(s.Device, s.Difficulty); err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
if err := s.Node.Publish(r.Context(), l); err != nil {
switch {
case errors.Is(err, store.ErrInvalid):
fail(w, http.StatusBadRequest, strings.TrimPrefix(err.Error(), store.ErrInvalid.Error()+": "))
case errors.Is(err, store.ErrRevoked):
fail(w, http.StatusConflict, "this node's device has been revoked; run 'allmende recover'")
case errors.Is(err, context.Canceled):
fail(w, http.StatusRequestTimeout, "request cancelled")
default:
fail(w, http.StatusInternalServerError, "internal error")
}
return
}
b, err := l.Bytes()
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(b)
}
// --- helpers --------------------------------------------------------------
func writeJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
json.NewEncoder(w).Encode(v)
}
func fail(w http.ResponseWriter, code int, msg string) {
writeJSON(w, code, map[string]string{"error": msg})
}
+226
View File
@@ -0,0 +1,226 @@
package api
import (
"bytes"
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"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 (
difficulty = 6
token = "s3cret-token"
)
type fixture struct {
srv *httptest.Server
s *store.Store
dev *identity.Device
}
func newFixture(t *testing.T, tok string) *fixture {
t.Helper()
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)
}
node, err := p2p.New(context.Background(), p2p.Config{
Device: dev, Store: s, Regions: []string{"u1x"}, Difficulty: difficulty,
ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
})
if err != nil {
t.Fatal(err)
}
srv := httptest.NewServer(New(Config{
Store: s, Node: node, Device: dev, Regions: []string{"u1x"}, Token: tok, Difficulty: difficulty,
}))
t.Cleanup(func() { srv.Close(); node.Close(); s.Close() })
return &fixture{srv: srv, s: s, dev: dev}
}
func (f *fixture) do(t *testing.T, method, path, body string, auth bool) (int, []byte) {
t.Helper()
req, _ := http.NewRequest(method, f.srv.URL+path, strings.NewReader(body))
if auth {
req.Header.Set("Authorization", "Bearer "+token)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
return resp.StatusCode, b
}
const draftJSON = `{
"kind": "rent", "category": "apartment", "geohash": "u1xjhx",
"price": {"amount_cents": 95000, "currency": "EUR", "period": "month"},
"area_m2": 48, "rooms_x2": 4, "features": ["balcony"],
"title": "Helle Wohnung", "description": "Ruhig gelegen."
}`
func TestCreateSearchGetUpdateDelete(t *testing.T) {
f := newFixture(t, token)
code, body := f.do(t, "POST", "/api/v1/listings", draftJSON, true)
if code != 200 {
t.Fatalf("create: %d %s", code, body)
}
var created listing.Listing
if err := json.Unmarshal(body, &created); err != nil {
t.Fatal(err)
}
// The reply must be the verifiable signed record.
if err := created.Check(time.Now(), difficulty); err != nil {
t.Fatalf("returned listing does not verify: %v", err)
}
if created.Author != f.dev.Cert.Author || created.Seq != 1 {
t.Fatalf("unexpected listing: %+v", created)
}
// Search (public, no token) returns canonical bytes that verify.
code, body = f.do(t, "GET", "/api/v1/listings?geohash=u1x&kind=rent&max_price=100000", "", false)
if code != 200 {
t.Fatalf("search: %d %s", code, body)
}
var found []json.RawMessage
if err := json.Unmarshal(body, &found); err != nil || len(found) != 1 {
t.Fatalf("search returned %d items (%v): %s", len(found), err, body)
}
want, _ := created.Bytes()
if !bytes.Equal(found[0], want) {
t.Fatal("search result is not the canonical encoding")
}
if code, body = f.do(t, "GET", "/api/v1/listings?kind=sale", "", false); string(body) != "[]" {
t.Fatalf("filter ignored: %d %s", code, body)
}
// Get one.
path := "/api/v1/listings/" + created.Author + "/" + created.ID
if code, _ = f.do(t, "GET", path, "", false); code != 200 {
t.Fatalf("get: %d", code)
}
// Update bumps seq and replaces the content.
upd := strings.Replace(draftJSON, "Helle Wohnung", "Sehr helle Wohnung", 1)
code, body = f.do(t, "PUT", "/api/v1/listings/"+created.ID, upd, true)
if code != 200 {
t.Fatalf("update: %d %s", code, body)
}
var updated listing.Listing
_ = json.Unmarshal(body, &updated)
if updated.Seq != 2 || updated.Title != "Sehr helle Wohnung" {
t.Fatalf("unexpected update: %+v", updated)
}
// Moving to another region is refused.
moved := strings.Replace(draftJSON, "u1xjhx", "u30000", 1)
if code, _ = f.do(t, "PUT", "/api/v1/listings/"+created.ID, moved, true); code != 400 {
t.Fatalf("region change: got %d, want 400", code)
}
// Delete publishes a tombstone.
if code, body = f.do(t, "DELETE", "/api/v1/listings/"+created.ID, "", true); code != 200 {
t.Fatalf("delete: %d %s", code, body)
}
if code, _ = f.do(t, "GET", path, "", false); code != 404 {
t.Fatalf("deleted listing still served: %d", code)
}
if code, _ = f.do(t, "DELETE", "/api/v1/listings/"+created.ID, "", true); code != 404 {
t.Fatalf("second delete: got %d, want 404", code)
}
}
func TestWritesRequireToken(t *testing.T) {
f := newFixture(t, token)
for _, tc := range []struct{ method, path string }{
{"POST", "/api/v1/listings"},
{"PUT", "/api/v1/listings/abc"},
{"DELETE", "/api/v1/listings/abc"},
} {
if code, _ := f.do(t, tc.method, tc.path, draftJSON, false); code != 401 {
t.Fatalf("%s %s without token: %d, want 401", tc.method, tc.path, code)
}
}
req, _ := http.NewRequest("POST", f.srv.URL+"/api/v1/listings", strings.NewReader(draftJSON))
req.Header.Set("Authorization", "Bearer wrong")
resp, _ := http.DefaultClient.Do(req)
if resp.StatusCode != 401 {
t.Fatalf("wrong token: %d", resp.StatusCode)
}
off := newFixture(t, "")
if code, _ := off.do(t, "POST", "/api/v1/listings", draftJSON, true); code != 403 {
t.Fatalf("writes on a node without a token: %d, want 403", code)
}
}
func TestValidationErrors(t *testing.T) {
f := newFixture(t, token)
cases := map[string]string{
"unknown field": strings.Replace(draftJSON, `"kind"`, `"owner_phone": "0170", "kind"`, 1),
"bad kind": strings.Replace(draftJSON, `"rent"`, `"swap"`, 1),
"bad geohash": strings.Replace(draftJSON, "u1xjhx", "aaaaaa", 1),
"trailing data": draftJSON + `{}`,
"not json": `nope`,
"too long ttl": strings.Replace(draftJSON, `"kind"`, `"expires_in_days": 90, "kind"`, 1),
"no price": strings.Replace(draftJSON, `"price": {"amount_cents": 95000, "currency": "EUR", "period": "month"},`, "", 1),
"huge body": `{"title":"` + strings.Repeat("x", 70<<10) + `"}`,
"price mismatch": strings.Replace(draftJSON, `"month"`, `"once"`, 1),
}
for name, body := range cases {
t.Run(name, func(t *testing.T) {
if code, resp := f.do(t, "POST", "/api/v1/listings", body, true); code != 400 {
t.Fatalf("got %d (%s), want 400", code, resp)
}
})
}
if n, _ := f.s.Count(context.Background()); n != 0 {
t.Fatalf("%d invalid listings were stored", n)
}
}
func TestSearchParameterValidation(t *testing.T) {
f := newFixture(t, token)
for _, q := range []string{
"geohash=u1x'%20OR%201=1", "geohash=abc", "min_price=-5", "limit=lots", "max_price=1.5",
} {
if code, _ := f.do(t, "GET", "/api/v1/listings?"+q, "", false); code != 400 {
t.Fatalf("%q: got %d, want 400", q, code)
}
}
}
func TestStatus(t *testing.T) {
f := newFixture(t, token)
code, body := f.do(t, "GET", "/api/v1/status", "", false)
if code != 200 {
t.Fatalf("status: %d", code)
}
var st map[string]any
_ = json.Unmarshal(body, &st)
if st["author"] != f.dev.Cert.Author || st["peer_id"] == "" {
t.Fatalf("unexpected status: %s", body)
}
if strings.Contains(string(body), "token") {
t.Fatal("status must never expose the admin token")
}
}
+33
View File
@@ -121,3 +121,36 @@ func TestDeviceSaveLoad(t *testing.T) {
t.Fatal("Save must not overwrite an existing device key")
}
}
func TestRevokeAll(t *testing.T) {
root, _, _ := NewRoot()
oldDev, _ := Enroll(root, testNow.Add(-time.Hour), 24*time.Hour)
newDev, _ := Enroll(root, testNow, 24*time.Hour) // enrolled at the cutoff
other, _, _ := NewRoot()
foreign, _ := Enroll(other, testNow.Add(-time.Hour), 24*time.Hour)
r, err := RevokeAll(root, testNow, 8)
if err != nil {
t.Fatal(err)
}
if err := r.Check(8); err != nil {
t.Fatal(err)
}
if !r.AllDevices() {
t.Fatal("expected an all-devices revocation")
}
if !r.Covers(oldDev.Cert) {
t.Fatal("older device must be covered")
}
if r.Covers(newDev.Cert) {
t.Fatal("device enrolled at the cutoff must stay valid")
}
if r.Covers(foreign.Cert) {
t.Fatal("another identity's device must not be covered")
}
// It must outlive every certificate it covers.
if r.CertExpiresAt < oldDev.Cert.ExpiresAt {
t.Fatal("revocation would be dropped before the covered certificates expire")
}
}
+37 -6
View File
@@ -15,9 +15,12 @@ const (
)
// Revocation voids a device: every signature made by Device is rejected from
// now on. Nodes keep it until the device's certificate would have expired
// anyway (CertExpiresAt). It carries proof-of-work so nobody can flood the
// network with revocations for throwaway identities.
// now on. With Device empty it voids every device of Author whose certificate
// was issued before RevokedAt, which is what recovery on a new machine needs:
// the owner only has the phrase, not the old device's key. Nodes keep it
// until the certificates it covers would have expired anyway
// (CertExpiresAt). It carries proof-of-work so nobody can flood the network
// with revocations for throwaway identities.
type Revocation struct {
Version int `json:"v"`
Author string `json:"author"`
@@ -44,13 +47,27 @@ func Revoke(root *Identity, cert *Cert, at time.Time, difficulty int) (*Revocati
if root.PublicKeyHex() != cert.Author {
return nil, errors.New("identity: cert does not belong to this identity")
}
r := &Revocation{
return mineRevocation(root, &Revocation{
Version: RevocationVersion,
Author: cert.Author,
Device: cert.Device,
RevokedAt: at.Unix(),
CertExpiresAt: cert.ExpiresAt,
}
}, difficulty)
}
// RevokeAll voids every device certified before at. Enroll the replacement
// device with the same timestamp: certificates issued at or after at stay valid.
func RevokeAll(root *Identity, at time.Time, difficulty int) (*Revocation, error) {
return mineRevocation(root, &Revocation{
Version: RevocationVersion,
Author: root.PublicKeyHex(),
RevokedAt: at.Unix(),
CertExpiresAt: at.Add(MaxCertLifetime).Unix(), // older certs all expire before this
}, difficulty)
}
func mineRevocation(root *Identity, r *Revocation, difficulty int) (*Revocation, error) {
for ; ; r.PoW++ {
b, err := r.signingBytes()
if err != nil {
@@ -63,12 +80,26 @@ func Revoke(root *Identity, cert *Cert, at time.Time, difficulty int) (*Revocati
}
}
// AllDevices reports whether r covers every earlier device of the author.
func (r *Revocation) AllDevices() bool { return r.Device == "" }
// Covers reports whether r voids the device certified by c.
func (r *Revocation) Covers(c *Cert) bool {
if r.Author != c.Author {
return false
}
if r.AllDevices() {
return c.IssuedAt < r.RevokedAt
}
return r.Device == c.Device
}
// Check verifies structure, signature and proof-of-work.
func (r *Revocation) Check(difficulty int) error {
if r.Version != RevocationVersion {
return errors.New("identity: unsupported revocation version")
}
if !isHex(r.Author, 64) || !isHex(r.Device, 64) {
if !isHex(r.Author, 64) || (r.Device != "" && !isHex(r.Device, 64)) {
return errors.New("identity: revocation keys must be 64 hex characters")
}
if r.PoW > 1<<53-1 {
+4
View File
@@ -35,6 +35,10 @@ const (
listingContext = "allmende-listing-v1\n"
)
// DefaultDifficulty is the proof-of-work (leading zero bits) the network
// requires. All nodes must agree on it, or they reject each other's messages.
const DefaultDifficulty = 16
// ErrTimeWindow marks failures caused by the clock (expired, or created in
// the future). They are not the sender's fault, so the p2p layer ignores such
// messages instead of penalizing the peer that relayed them.
+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 {
+71 -33
View File
@@ -58,6 +58,7 @@ CREATE TABLE IF NOT EXISTS listings (
author TEXT NOT NULL,
id TEXT NOT NULL,
device TEXT NOT NULL,
cert_issued_at INTEGER NOT NULL,
seq INTEGER NOT NULL,
hash TEXT NOT NULL,
tombstone INTEGER NOT NULL,
@@ -75,11 +76,13 @@ CREATE TABLE IF NOT EXISTS listings (
CREATE INDEX IF NOT EXISTS listings_geohash ON listings (geohash);
CREATE INDEX IF NOT EXISTS listings_expires ON listings (expires_at);
CREATE INDEX IF NOT EXISTS listings_device ON listings (author, device);
CREATE INDEX IF NOT EXISTS listings_cert ON listings (author, cert_issued_at);
CREATE INDEX IF NOT EXISTS listings_created ON listings (created_at, author, id);
CREATE TABLE IF NOT EXISTS revocations (
author TEXT NOT NULL,
device TEXT NOT NULL,
device TEXT NOT NULL, -- '' = every device certified before revoked_at
revoked_at INTEGER NOT NULL,
cert_expires_at INTEGER NOT NULL,
data BLOB NOT NULL,
PRIMARY KEY (author, device)
@@ -140,9 +143,10 @@ func (s *Store) Put(ctx context.Context, l *listing.Listing) (Outcome, error) {
defer tx.Rollback()
var revoked int
err = tx.QueryRowContext(ctx,
`SELECT COUNT(*) FROM revocations WHERE author = ? AND device = ?`, l.Author, l.Device).
Scan(&revoked)
err = tx.QueryRowContext(ctx, `
SELECT COUNT(*) FROM revocations
WHERE author = ? AND (device = ? OR (device = '' AND revoked_at > ?))`,
l.Author, l.Device, l.Cert.IssuedAt).Scan(&revoked)
if err != nil {
return Ignored, err
}
@@ -174,10 +178,10 @@ func (s *Store) Put(ctx context.Context, l *listing.Listing) (Outcome, error) {
}
_, err = tx.ExecContext(ctx, `
INSERT OR REPLACE INTO listings
(author, id, device, seq, hash, tombstone, created_at, expires_at, geohash,
(author, id, device, cert_issued_at, seq, hash, tombstone, created_at, expires_at, geohash,
kind, category, price_cents, area_m2, rooms_x2, data)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
l.Author, l.ID, l.Device, int64(l.Seq), hash, boolInt(l.Tombstone), l.CreatedAt, l.ExpiresAt,
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
l.Author, l.ID, l.Device, l.Cert.IssuedAt, int64(l.Seq), hash, boolInt(l.Tombstone), l.CreatedAt, l.ExpiresAt,
l.Geohash, l.Kind, l.Category, price, l.AreaM2, l.RoomsX2, data)
if err != nil {
return Ignored, err
@@ -324,30 +328,17 @@ func (s *Store) Since(ctx context.Context, prefix string, cur Cursor, limit int)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*listing.Listing
for rows.Next() {
var data []byte
if err := rows.Scan(&data); err != nil {
return nil, err
}
l, err := decode(data)
if err != nil {
return nil, err
}
out = append(out, l)
}
return out, rows.Err()
return collect(rows)
}
// PutRevocation verifies and stores a revocation, and removes every listing
// the revoked device signed. The owner re-publishes them from a new device.
// PutRevocation verifies and stores a revocation and removes every listing it
// voids. The owner republishes them from a new device.
func (s *Store) PutRevocation(ctx context.Context, r *identity.Revocation) (Outcome, error) {
if err := r.Check(s.difficulty); err != nil {
return Ignored, fmt.Errorf("%w: %v", ErrInvalid, err)
}
if r.CertExpiresAt <= s.clock().Unix() {
return Ignored, nil // the certificate is dead anyway
return Ignored, nil // everything it covers is dead anyway
}
data, err := r.Bytes()
if err != nil {
@@ -359,17 +350,31 @@ func (s *Store) PutRevocation(ctx context.Context, r *identity.Revocation) (Outc
}
defer tx.Rollback()
res, err := tx.ExecContext(ctx,
`INSERT OR IGNORE INTO revocations (author, device, cert_expires_at, data) VALUES (?, ?, ?, ?)`,
r.Author, r.Device, r.CertExpiresAt, data)
// Keep only the latest revocation per (author, device); for the
// all-devices form (device = '') that is the one with the newest cutoff.
res, err := tx.ExecContext(ctx, `
INSERT INTO revocations (author, device, revoked_at, cert_expires_at, data)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT (author, device) DO UPDATE SET
revoked_at = excluded.revoked_at,
cert_expires_at = excluded.cert_expires_at,
data = excluded.data
WHERE excluded.revoked_at > revocations.revoked_at`,
r.Author, r.Device, r.RevokedAt, r.CertExpiresAt, data)
if err != nil {
return Ignored, err
}
if n, _ := res.RowsAffected(); n == 0 {
return Ignored, nil // already known
}
if _, err := tx.ExecContext(ctx,
`DELETE FROM listings WHERE author = ? AND device = ?`, r.Author, r.Device); err != nil {
if r.AllDevices() {
_, err = tx.ExecContext(ctx,
`DELETE FROM listings WHERE author = ? AND cert_issued_at < ?`, r.Author, r.RevokedAt)
} else {
_, err = tx.ExecContext(ctx,
`DELETE FROM listings WHERE author = ? AND device = ?`, r.Author, r.Device)
}
if err != nil {
return Ignored, err
}
if err := tx.Commit(); err != nil {
@@ -401,11 +406,14 @@ func (s *Store) Revocations(ctx context.Context) ([]*identity.Revocation, error)
return out, rows.Err()
}
// IsRevoked reports whether the device has been revoked.
func (s *Store) IsRevoked(ctx context.Context, author, device string) (bool, error) {
// IsRevoked reports whether the device, certified at certIssuedAt, has been
// voided by a revocation.
func (s *Store) IsRevoked(ctx context.Context, author, device string, certIssuedAt int64) (bool, error) {
var n int
err := s.db.QueryRowContext(ctx,
`SELECT COUNT(*) FROM revocations WHERE author = ? AND device = ?`, author, device).Scan(&n)
err := s.db.QueryRowContext(ctx, `
SELECT COUNT(*) FROM revocations
WHERE author = ? AND (device = ? OR (device = '' AND revoked_at > ?))`,
author, device, certIssuedAt).Scan(&n)
return n > 0, err
}
@@ -437,6 +445,36 @@ func (s *Store) Count(ctx context.Context) (int, error) {
return n, err
}
// ByAuthor returns the author's live (not deleted, not expired) listings.
func (s *Store) ByAuthor(ctx context.Context, author string) ([]*listing.Listing, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT data FROM listings
WHERE author = ? AND tombstone = 0 AND expires_at > ?
ORDER BY created_at, id`, author, s.clock().Unix())
if err != nil {
return nil, err
}
return collect(rows)
}
// collect decodes a result set of listing blobs and closes it.
func collect(rows *sql.Rows) ([]*listing.Listing, error) {
defer rows.Close()
var out []*listing.Listing
for rows.Next() {
var data []byte
if err := rows.Scan(&data); err != nil {
return nil, err
}
l, err := decode(data)
if err != nil {
return nil, err
}
out = append(out, l)
}
return out, rows.Err()
}
func decode(data []byte) (*listing.Listing, error) {
var l listing.Listing
if err := json.Unmarshal(data, &l); err != nil {
+60
View File
@@ -467,3 +467,63 @@ func TestPersistence(t *testing.T) {
t.Fatalf("listing lost after reopen: %v", err)
}
}
func TestRevokeAllRecovery(t *testing.T) {
e := newEnv(t)
mine := e.listing(t, nil)
e.put(t, mine)
// Recovery on a new machine: only the phrase is known. Everything issued
// before the cutoff is void; the replacement device is enrolled at the cutoff.
cutoff := e.now
rev, err := identity.RevokeAll(e.root, cutoff, difficulty)
if err != nil {
t.Fatal(err)
}
if o, err := e.s.PutRevocation(ctx, rev); err != nil || o != Inserted {
t.Fatalf("PutRevocation = %v, %v", o, err)
}
if _, err := e.s.Get(ctx, mine.Author, mine.ID); !errors.Is(err, ErrNotFound) {
t.Fatal("listing of an older device survived the revocation")
}
// The old device can no longer publish, not even a fresh listing.
if _, err := e.s.Put(ctx, e.listing(t, nil)); !errors.Is(err, ErrRevoked) {
t.Fatalf("old device accepted: %v", err)
}
// The replacement device (issued at the cutoff) works.
fresh, err := identity.Enroll(e.root, cutoff, 90*24*time.Hour)
if err != nil {
t.Fatal(err)
}
e.dev = fresh
again := *mine
again.Seq = 2
if err := again.Seal(fresh, difficulty); err != nil {
t.Fatal(err)
}
if o := e.put(t, &again); o != Inserted {
t.Fatalf("republish from the new device: %v", o)
}
// An older cutoff must not replace a newer one, and a repeat is ignored.
if o, _ := e.s.PutRevocation(ctx, rev); o != Ignored {
t.Fatalf("duplicate all-devices revocation: %v", o)
}
stale, _ := identity.RevokeAll(e.root, cutoff.Add(-time.Hour), difficulty)
if o, _ := e.s.PutRevocation(ctx, stale); o != Ignored {
t.Fatalf("older cutoff replaced a newer one: %v", o)
}
// Other identities are unaffected.
otherRoot, _, _ := identity.NewRoot()
otherDev := newDevice(t, otherRoot)
theirs := e.listing(t, nil)
if err := theirs.Seal(otherDev, difficulty); err != nil {
t.Fatal(err)
}
if o := e.put(t, theirs); o != Inserted {
t.Fatalf("someone else's listing blocked: %v", o)
}
}