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
+155 -8
View File
@@ -15,6 +15,7 @@ import (
_ "modernc.org/sqlite"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
)
@@ -23,6 +24,8 @@ var (
ErrInvalid = errors.New("store: invalid listing")
// ErrNotFound is returned when a listing is absent, expired or deleted.
ErrNotFound = errors.New("store: not found")
// ErrRevoked is returned for listings signed by a revoked device.
ErrRevoked = errors.New("store: device revoked")
)
// Outcome tells the caller what Put did, so the p2p layer knows whether a
@@ -54,6 +57,7 @@ const schema = `
CREATE TABLE IF NOT EXISTS listings (
author TEXT NOT NULL,
id TEXT NOT NULL,
device TEXT NOT NULL,
seq INTEGER NOT NULL,
hash TEXT NOT NULL,
tombstone INTEGER NOT NULL,
@@ -70,6 +74,16 @@ CREATE TABLE IF NOT EXISTS listings (
) WITHOUT ROWID;
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_created ON listings (created_at, author, id);
CREATE TABLE IF NOT EXISTS revocations (
author TEXT NOT NULL,
device TEXT NOT NULL,
cert_expires_at INTEGER NOT NULL,
data BLOB NOT NULL,
PRIMARY KEY (author, device)
) WITHOUT ROWID;
`
// Open opens (creating if needed) the database at path. Use ":memory:" for
@@ -125,6 +139,17 @@ 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)
if err != nil {
return Ignored, err
}
if revoked > 0 {
return Ignored, ErrRevoked
}
var curSeq int64
var curHash string
err = tx.QueryRowContext(ctx,
@@ -149,10 +174,10 @@ func (s *Store) Put(ctx context.Context, l *listing.Listing) (Outcome, error) {
}
_, err = tx.ExecContext(ctx, `
INSERT OR REPLACE INTO listings
(author, id, seq, hash, tombstone, created_at, expires_at, geohash,
(author, id, device, seq, hash, tombstone, created_at, expires_at, geohash,
kind, category, price_cents, area_m2, rooms_x2, data)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
l.Author, l.ID, int64(l.Seq), hash, boolInt(l.Tombstone), l.CreatedAt, l.ExpiresAt,
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
l.Author, l.ID, l.Device, 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
@@ -270,15 +295,137 @@ func (s *Store) Search(ctx context.Context, q Query) ([]*listing.Listing, error)
return out, rows.Err()
}
// Expire deletes everything whose lifetime has ended, tombstones included,
// and returns how many rows were removed. A tombstone outlives any version it
// supersedes because listings live at most 30 days from creation.
// Cursor is a keyset position in the (created_at, author, id) order, used to
// page through listings during sync. The zero Cursor is the very beginning.
type Cursor struct {
CreatedAt int64
Author string
ID string
}
// CursorOf returns the cursor positioned at l.
func CursorOf(l *listing.Listing) Cursor {
return Cursor{CreatedAt: l.CreatedAt, Author: l.Author, ID: l.ID}
}
// Since returns up to limit unexpired records (tombstones included, since
// peers need them to learn about deletions) in region prefix that sort after
// cur, oldest first.
func (s *Store) Since(ctx context.Context, prefix string, cur Cursor, limit int) ([]*listing.Listing, error) {
if !listing.ValidGeohashPrefix(prefix) {
return nil, fmt.Errorf("store: invalid geohash prefix %q", prefix)
}
rows, err := s.db.QueryContext(ctx, `
SELECT data FROM listings
WHERE geohash >= ? AND geohash <= ? AND expires_at > ?
AND (created_at, author, id) > (?, ?, ?)
ORDER BY created_at, author, id LIMIT ?`,
prefix, prefix+"~", s.clock().Unix(), cur.CreatedAt, cur.Author, cur.ID, limit)
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()
}
// PutRevocation verifies and stores a revocation, and removes every listing
// the revoked device signed. The owner re-publishes 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
}
data, err := r.Bytes()
if err != nil {
return Ignored, err
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return Ignored, err
}
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)
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 {
return Ignored, err
}
if err := tx.Commit(); err != nil {
return Ignored, err
}
return Inserted, nil
}
// Revocations returns every revocation still relevant (certificate unexpired).
func (s *Store) Revocations(ctx context.Context) ([]*identity.Revocation, error) {
rows, err := s.db.QueryContext(ctx,
`SELECT data FROM revocations WHERE cert_expires_at > ? ORDER BY author, device`, s.clock().Unix())
if err != nil {
return nil, err
}
defer rows.Close()
var out []*identity.Revocation
for rows.Next() {
var data []byte
if err := rows.Scan(&data); err != nil {
return nil, err
}
var r identity.Revocation
if err := json.Unmarshal(data, &r); err != nil {
return nil, fmt.Errorf("store: corrupt revocation: %w", err)
}
out = append(out, &r)
}
return out, rows.Err()
}
// IsRevoked reports whether the device has been revoked.
func (s *Store) IsRevoked(ctx context.Context, author, device string) (bool, error) {
var n int
err := s.db.QueryRowContext(ctx,
`SELECT COUNT(*) FROM revocations WHERE author = ? AND device = ?`, author, device).Scan(&n)
return n > 0, err
}
// Expire deletes everything whose lifetime has ended (listings, tombstones
// and revocations) and returns how many rows were removed. A tombstone
// outlives any version it supersedes because listings live at most 30 days
// from creation.
func (s *Store) Expire(ctx context.Context) (int64, error) {
res, err := s.db.ExecContext(ctx, `DELETE FROM listings WHERE expires_at <= ?`, s.clock().Unix())
now := s.clock().Unix()
res, err := s.db.ExecContext(ctx, `DELETE FROM listings WHERE expires_at <= ?`, now)
if err != nil {
return 0, err
}
return res.RowsAffected()
n, _ := res.RowsAffected()
res, err = s.db.ExecContext(ctx, `DELETE FROM revocations WHERE cert_expires_at <= ?`, now)
if err != nil {
return n, err
}
m, _ := res.RowsAffected()
return n + m, nil
}
// Count returns the number of live listings.
+172 -24
View File
@@ -19,15 +19,26 @@ var (
)
type env struct {
s *Store
now time.Time
key *identity.Identity
s *Store
now time.Time
root *identity.Identity
dev *identity.Device
}
func newDevice(t *testing.T, root *identity.Identity) *identity.Device {
t.Helper()
dev, err := identity.Enroll(root, t0.Add(-time.Hour), 180*24*time.Hour)
if err != nil {
t.Fatal(err)
}
return dev
}
func newEnv(t *testing.T) *env {
t.Helper()
e := &env{now: t0}
e.key, _ = identity.Generate()
e.root, _, _ = identity.NewRoot()
e.dev = newDevice(t, e.root)
s, err := Open(":memory:", Options{Difficulty: difficulty, Clock: func() time.Time { return e.now }})
if err != nil {
t.Fatal(err)
@@ -37,6 +48,14 @@ func newEnv(t *testing.T) *env {
return e
}
// sibling returns a second store sharing e's identity and clock.
func (e *env) sibling(t *testing.T) *env {
t.Helper()
e2 := newEnv(t)
e2.root, e2.dev = e.root, e.dev
return e2
}
func (e *env) listing(t *testing.T, mutate func(*listing.Listing)) *listing.Listing {
t.Helper()
id, _ := listing.NewID()
@@ -53,12 +72,11 @@ func (e *env) listing(t *testing.T, mutate func(*listing.Listing)) *listing.List
AreaM2: 50,
RoomsX2: 4,
Title: "Wohnung",
Endpoint: "12D3KooWExamplePeerID",
}
if mutate != nil {
mutate(l)
}
if err := l.Seal(e.key, difficulty); err != nil {
if err := l.Seal(e.dev, difficulty); err != nil {
t.Fatal(err)
}
return l
@@ -112,7 +130,7 @@ func TestHigherSeqWinsInAnyOrder(t *testing.T) {
v2 := *v1
v2.Seq = 2
v2.Title = "Neuer Titel"
if err := v2.Seal(e.key, difficulty); err != nil {
if err := v2.Seal(e.dev, difficulty); err != nil {
t.Fatal(err)
}
@@ -129,8 +147,7 @@ func TestHigherSeqWinsInAnyOrder(t *testing.T) {
}
// Fresh store, natural order: second is a replacement.
e2 := newEnv(t)
e2.key = e.key
e2 := e.sibling(t)
e2.put(t, v1)
if o := e2.put(t, &v2); o != Replaced {
t.Fatalf("got %v want replaced", o)
@@ -142,7 +159,7 @@ func TestEqualSeqConvergesOnSmallerHash(t *testing.T) {
a := e.listing(t, nil)
b := *a
b.Title = "Anderer Titel"
if err := b.Seal(e.key, difficulty); err != nil {
if err := b.Seal(e.dev, difficulty); err != nil {
t.Fatal(err)
}
ha, _ := a.Hash()
@@ -157,8 +174,7 @@ func TestEqualSeqConvergesOnSmallerHash(t *testing.T) {
"loser first": {loser, winner},
} {
t.Run(name, func(t *testing.T) {
e2 := newEnv(t)
e2.key = e.key
e2 := e.sibling(t)
for _, l := range order {
e2.put(t, l)
}
@@ -170,19 +186,25 @@ func TestEqualSeqConvergesOnSmallerHash(t *testing.T) {
}
}
func TestTombstoneDeletesAndBlocksResurrection(t *testing.T) {
e := newEnv(t)
l := e.listing(t, nil)
e.put(t, l)
func (e *env) tombstone(t *testing.T, l *listing.Listing) *listing.Listing {
t.Helper()
ts := &listing.Listing{
Version: listing.Version, ID: l.ID, Seq: l.Seq + 1,
CreatedAt: e.now.Unix(), ExpiresAt: e.now.Add(30 * 24 * time.Hour).Unix(),
Tombstone: true, Geohash: l.Geohash,
}
if err := ts.Seal(e.key, difficulty); err != nil {
if err := ts.Seal(e.dev, difficulty); err != nil {
t.Fatal(err)
}
return ts
}
func TestTombstoneDeletesAndBlocksResurrection(t *testing.T) {
e := newEnv(t)
l := e.listing(t, nil)
e.put(t, l)
ts := e.tombstone(t, l)
if o := e.put(t, ts); o != Replaced {
t.Fatalf("got %v want replaced", o)
}
@@ -197,8 +219,7 @@ func TestTombstoneDeletesAndBlocksResurrection(t *testing.T) {
}
// A tombstone arriving before the listing it deletes still wins.
e2 := newEnv(t)
e2.key = e.key
e2 := e.sibling(t)
e2.put(t, ts)
if o := e2.put(t, l); o != Ignored {
t.Fatalf("listing after tombstone: %v", o)
@@ -210,11 +231,11 @@ func TestSameIDDifferentAuthorsDoNotCollide(t *testing.T) {
victim := e.listing(t, nil)
e.put(t, victim)
other, _ := identity.Generate()
otherRoot, _, _ := identity.NewRoot()
squat := *victim
squat.Seq = 99
squat.Title = "Betrug"
if err := squat.Seal(other, difficulty); err != nil {
if err := squat.Seal(newDevice(t, otherRoot), difficulty); err != nil {
t.Fatal(err)
}
e.put(t, &squat)
@@ -225,6 +246,88 @@ func TestSameIDDifferentAuthorsDoNotCollide(t *testing.T) {
}
}
func TestRevocationVoidsDevice(t *testing.T) {
e := newEnv(t)
stolen := e.dev
mine := e.listing(t, nil)
e.put(t, mine)
// The attacker hijacks the listing with the stolen device and a huge seq.
hijack := *mine
hijack.Seq = 1 << 40
hijack.Title = "Betrug"
if err := hijack.Seal(stolen, difficulty); err != nil {
t.Fatal(err)
}
if o := e.put(t, &hijack); o != Replaced {
t.Fatalf("hijack: %v", o)
}
// The owner restores from the recovery phrase and revokes the device.
rev, err := identity.Revoke(e.root, stolen.Cert, e.now, 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("revoked device's listing still readable")
}
if _, err := e.s.Put(ctx, &hijack); !errors.Is(err, ErrRevoked) {
t.Fatalf("revoked device accepted again: %v", err)
}
if o, _ := e.s.PutRevocation(ctx, rev); o != Ignored {
t.Fatalf("duplicate revocation: %v", o)
}
// The owner republishes from a new device with a low seq: it must win,
// because the attacker's huge seq was purged with the revocation.
newDev := newDevice(t, e.root)
again := *mine
again.Seq = 2
if err := again.Seal(newDev, difficulty); err != nil {
t.Fatal(err)
}
if o := e.put(t, &again); o != Inserted {
t.Fatalf("republish from new device: %v", o)
}
got, _ := e.s.Get(ctx, mine.Author, mine.ID)
if got.Title != "Wohnung" {
t.Fatalf("got %q", got.Title)
}
}
func TestRevocationValidation(t *testing.T) {
e := newEnv(t)
other, _, _ := identity.NewRoot()
// Someone else's identity cannot revoke our device.
if _, err := identity.Revoke(other, e.dev.Cert, e.now, difficulty); err == nil {
t.Fatal("foreign identity could create a revocation")
}
rev, _ := identity.Revoke(e.root, e.dev.Cert, e.now, difficulty)
rev.Device = other.PublicKeyHex()
if _, err := e.s.PutRevocation(ctx, rev); !errors.Is(err, ErrInvalid) {
t.Fatalf("tampered revocation: %v", err)
}
}
func TestRevocationExpiresWithCertificate(t *testing.T) {
e := newEnv(t)
rev, _ := identity.Revoke(e.root, e.dev.Cert, e.now, difficulty)
e.s.PutRevocation(ctx, rev)
if list, _ := e.s.Revocations(ctx); len(list) != 1 {
t.Fatalf("got %d revocations, want 1", len(list))
}
e.now = time.Unix(e.dev.Cert.ExpiresAt+1, 0)
if list, _ := e.s.Revocations(ctx); len(list) != 0 {
t.Fatal("expired revocation still listed")
}
if n, _ := e.s.Expire(ctx); n != 1 {
t.Fatalf("Expire removed %d, want 1", n)
}
}
func TestSearch(t *testing.T) {
e := newEnv(t)
mk := func(geo, kind string, cents int64, area, rooms int) {
@@ -278,6 +381,51 @@ func TestSearch(t *testing.T) {
}
}
func TestSinceKeysetPaging(t *testing.T) {
e := newEnv(t)
// Five listings in the same second plus one tombstone and one outside the region.
var all []*listing.Listing
for i := 0; i < 5; i++ {
l := e.listing(t, nil)
e.put(t, l)
all = append(all, l)
}
e.put(t, e.tombstone(t, all[0]))
e.put(t, e.listing(t, func(l *listing.Listing) { l.Geohash = "u30000" }))
var got []*listing.Listing
cur := Cursor{}
for pages := 0; pages < 10; pages++ {
page, err := e.s.Since(ctx, "u1x", cur, 2)
if err != nil {
t.Fatal(err)
}
if len(page) == 0 {
break
}
got = append(got, page...)
cur = CursorOf(page[len(page)-1])
}
// 5 distinct listings; one of them is now a tombstone.
if len(got) != 5 {
t.Fatalf("paged %d records, want 5", len(got))
}
tombstones := 0
seen := map[string]bool{}
for _, l := range got {
if seen[l.ID] {
t.Fatalf("duplicate %s across pages", l.ID)
}
seen[l.ID] = true
if l.Tombstone {
tombstones++
}
}
if tombstones != 1 {
t.Fatalf("got %d tombstones, want 1 (peers need them to learn deletions)", tombstones)
}
}
func TestExpiry(t *testing.T) {
e := newEnv(t)
l := e.listing(t, nil)
@@ -298,14 +446,14 @@ func TestExpiry(t *testing.T) {
func TestPersistence(t *testing.T) {
path := filepath.Join(t.TempDir(), "allmende.db")
key, _ := identity.Generate()
opt := Options{Difficulty: difficulty, Clock: func() time.Time { return t0 }}
s, err := Open(path, opt)
if err != nil {
t.Fatal(err)
}
e := &env{s: s, now: t0, key: key}
e := newEnv(t)
e.s = s
l := e.listing(t, nil)
e.put(t, l)
s.Close()