- 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>
492 lines
14 KiB
Go
492 lines
14 KiB
Go
// Package store persists verified listings in SQLite and answers search
|
|
// queries. It is the single place that decides which version of a listing
|
|
// wins, so every node converges on the same state regardless of the order in
|
|
// which versions arrive.
|
|
package store
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
_ "modernc.org/sqlite"
|
|
|
|
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
|
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
|
)
|
|
|
|
var (
|
|
// ErrInvalid wraps any failure of listing.Check.
|
|
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
|
|
// listing is new information worth re-gossiping.
|
|
type Outcome int
|
|
|
|
const (
|
|
Ignored Outcome = iota // duplicate, or older than what we hold
|
|
Inserted // first version we have seen
|
|
Replaced // superseded a stored version
|
|
)
|
|
|
|
func (o Outcome) String() string {
|
|
return [...]string{"ignored", "inserted", "replaced"}[o]
|
|
}
|
|
|
|
type Options struct {
|
|
Difficulty int // required proof-of-work bits
|
|
Clock func() time.Time // defaults to time.Now
|
|
}
|
|
|
|
type Store struct {
|
|
db *sql.DB
|
|
difficulty int
|
|
clock func() time.Time
|
|
}
|
|
|
|
const schema = `
|
|
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,
|
|
created_at INTEGER NOT NULL,
|
|
expires_at INTEGER NOT NULL,
|
|
geohash TEXT NOT NULL,
|
|
kind TEXT NOT NULL,
|
|
category TEXT NOT NULL,
|
|
price_cents INTEGER NOT NULL,
|
|
area_m2 INTEGER NOT NULL,
|
|
rooms_x2 INTEGER NOT NULL,
|
|
data BLOB NOT NULL,
|
|
PRIMARY KEY (author, id)
|
|
) 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_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, -- '' = 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)
|
|
) WITHOUT ROWID;
|
|
`
|
|
|
|
// Open opens (creating if needed) the database at path. Use ":memory:" for
|
|
// an ephemeral store.
|
|
func Open(path string, opt Options) (*Store, error) {
|
|
dsn := "file:" + path + "?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)"
|
|
if path == ":memory:" {
|
|
dsn = "file::memory:?_pragma=busy_timeout(5000)"
|
|
}
|
|
db, err := sql.Open("sqlite", dsn)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// One connection: serializes writers and keeps :memory: coherent.
|
|
db.SetMaxOpenConns(1)
|
|
if _, err := db.Exec(schema); err != nil {
|
|
db.Close()
|
|
return nil, err
|
|
}
|
|
s := &Store{db: db, difficulty: opt.Difficulty, clock: opt.Clock}
|
|
if s.clock == nil {
|
|
s.clock = time.Now
|
|
}
|
|
return s, nil
|
|
}
|
|
|
|
func (s *Store) Close() error { return s.db.Close() }
|
|
|
|
// Put verifies l and stores it if it is the newest version known.
|
|
//
|
|
// Conflict rules (identical on every node, so replicas converge):
|
|
// - listings are keyed by (author, id): nobody can squat another author's id;
|
|
// - a higher seq wins;
|
|
// - on equal seq (an author signing two versions), the smaller hash wins;
|
|
// - tombstones are stored like any other version, so a late-arriving older
|
|
// version cannot resurrect a deleted listing.
|
|
func (s *Store) Put(ctx context.Context, l *listing.Listing) (Outcome, error) {
|
|
if err := l.Check(s.clock(), s.difficulty); err != nil {
|
|
return Ignored, fmt.Errorf("%w: %v", ErrInvalid, err)
|
|
}
|
|
data, err := l.Bytes()
|
|
if err != nil {
|
|
return Ignored, err
|
|
}
|
|
hash, err := l.Hash()
|
|
if err != nil {
|
|
return Ignored, err
|
|
}
|
|
|
|
tx, err := s.db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return Ignored, err
|
|
}
|
|
defer tx.Rollback()
|
|
|
|
var revoked int
|
|
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
|
|
}
|
|
if revoked > 0 {
|
|
return Ignored, ErrRevoked
|
|
}
|
|
|
|
var curSeq int64
|
|
var curHash string
|
|
err = tx.QueryRowContext(ctx,
|
|
`SELECT seq, hash FROM listings WHERE author = ? AND id = ?`, l.Author, l.ID).
|
|
Scan(&curSeq, &curHash)
|
|
outcome := Inserted
|
|
switch {
|
|
case errors.Is(err, sql.ErrNoRows):
|
|
case err != nil:
|
|
return Ignored, err
|
|
default:
|
|
seq := int64(l.Seq)
|
|
if seq < curSeq || (seq == curSeq && hash >= curHash) {
|
|
return Ignored, nil
|
|
}
|
|
outcome = Replaced
|
|
}
|
|
|
|
var price int64
|
|
if l.Price != nil {
|
|
price = l.Price.AmountCents
|
|
}
|
|
_, err = tx.ExecContext(ctx, `
|
|
INSERT OR REPLACE INTO listings
|
|
(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, 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
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
return Ignored, err
|
|
}
|
|
return outcome, nil
|
|
}
|
|
|
|
// Get returns the live (not deleted, not expired) listing.
|
|
func (s *Store) Get(ctx context.Context, author, id string) (*listing.Listing, error) {
|
|
var data []byte
|
|
err := s.db.QueryRowContext(ctx, `
|
|
SELECT data FROM listings
|
|
WHERE author = ? AND id = ? AND tombstone = 0 AND expires_at > ?`,
|
|
author, id, s.clock().Unix()).Scan(&data)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return decode(data)
|
|
}
|
|
|
|
// Query selects live listings. Zero values mean "no constraint".
|
|
type Query struct {
|
|
Geohashes []string // prefixes; a listing matches if it starts with any
|
|
Kind string
|
|
Category string
|
|
MinPriceCents int64
|
|
MaxPriceCents int64
|
|
MinAreaM2 int
|
|
MinRoomsX2 int
|
|
Limit int // default 50, max 200
|
|
Offset int
|
|
}
|
|
|
|
// Search returns live listings, newest first.
|
|
func (s *Store) Search(ctx context.Context, q Query) ([]*listing.Listing, error) {
|
|
where := []string{"tombstone = 0", "expires_at > ?"}
|
|
args := []any{s.clock().Unix()}
|
|
|
|
if len(q.Geohashes) > 0 {
|
|
var ors []string
|
|
for _, p := range q.Geohashes {
|
|
if !listing.ValidGeohashPrefix(p) {
|
|
return nil, fmt.Errorf("store: invalid geohash prefix %q", p)
|
|
}
|
|
ors = append(ors, "(geohash >= ? AND geohash <= ?)")
|
|
// '~' sorts after every geohash character.
|
|
args = append(args, p, p+"~")
|
|
}
|
|
where = append(where, "("+strings.Join(ors, " OR ")+")")
|
|
}
|
|
if q.Kind != "" {
|
|
where = append(where, "kind = ?")
|
|
args = append(args, q.Kind)
|
|
}
|
|
if q.Category != "" {
|
|
where = append(where, "category = ?")
|
|
args = append(args, q.Category)
|
|
}
|
|
if q.MinPriceCents > 0 {
|
|
where = append(where, "price_cents >= ?")
|
|
args = append(args, q.MinPriceCents)
|
|
}
|
|
if q.MaxPriceCents > 0 {
|
|
where = append(where, "price_cents <= ?")
|
|
args = append(args, q.MaxPriceCents)
|
|
}
|
|
if q.MinAreaM2 > 0 {
|
|
where = append(where, "area_m2 >= ?")
|
|
args = append(args, q.MinAreaM2)
|
|
}
|
|
if q.MinRoomsX2 > 0 {
|
|
where = append(where, "rooms_x2 >= ?")
|
|
args = append(args, q.MinRoomsX2)
|
|
}
|
|
|
|
limit := q.Limit
|
|
if limit <= 0 {
|
|
limit = 50
|
|
}
|
|
if limit > 200 {
|
|
limit = 200
|
|
}
|
|
offset := q.Offset
|
|
if offset < 0 {
|
|
offset = 0
|
|
}
|
|
args = append(args, limit, offset)
|
|
|
|
rows, err := s.db.QueryContext(ctx,
|
|
`SELECT data FROM listings WHERE `+strings.Join(where, " AND ")+
|
|
` ORDER BY created_at DESC, author, id LIMIT ? OFFSET ?`, args...)
|
|
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()
|
|
}
|
|
|
|
// 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
|
|
}
|
|
return collect(rows)
|
|
}
|
|
|
|
// 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 // everything it covers 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()
|
|
|
|
// 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 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 {
|
|
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, 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 = ? OR (device = '' AND revoked_at > ?))`,
|
|
author, device, certIssuedAt).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) {
|
|
now := s.clock().Unix()
|
|
res, err := s.db.ExecContext(ctx, `DELETE FROM listings WHERE expires_at <= ?`, now)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
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.
|
|
func (s *Store) Count(ctx context.Context) (int, error) {
|
|
var n int
|
|
err := s.db.QueryRowContext(ctx,
|
|
`SELECT COUNT(*) FROM listings WHERE tombstone = 0 AND expires_at > ?`,
|
|
s.clock().Unix()).Scan(&n)
|
|
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 {
|
|
return nil, fmt.Errorf("store: corrupt row: %w", err)
|
|
}
|
|
return &l, nil
|
|
}
|
|
|
|
func boolInt(b bool) int {
|
|
if b {
|
|
return 1
|
|
}
|
|
return 0
|
|
}
|