// 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 for listings and revocations Clock func() time.Time // defaults to time.Now // MessageDifficulty is the proof-of-work bits required of message // envelopes (message.DefaultDifficulty on a real node). MessageDifficulty int // MaxMessages caps the envelopes this node holds; 0 means 20000. MaxMessages int // OwnerQueue and MailboxQueue cap the envelopes per listing and per // mailbox; 0 means MaxOwnerQueue and MaxMailboxQueue. OwnerQueue, MailboxQueue int // Trust says whose abuse reports hide listings on this node (see Trust). Trust Trust } type Store struct { db *sql.DB difficulty int clock func() time.Time msgDifficulty int maxMessages int ownerQueue int mailboxQueue int trust Trust } 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; -- Encrypted message envelopes this node relays (see internal/message). CREATE TABLE IF NOT EXISTS messages ( hash TEXT PRIMARY KEY, to_dir TEXT NOT NULL, -- 'owner' or 'buyer' author TEXT NOT NULL, -- listing reference listing_id TEXT NOT NULL, rcpt TEXT NOT NULL, -- owner: device key; buyer: mailbox tag region TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, work INTEGER NOT NULL, -- leading zero bits, decides what a full queue evicts data BLOB NOT NULL ) WITHOUT ROWID; CREATE INDEX IF NOT EXISTS messages_listing ON messages (to_dir, author, listing_id); CREATE INDEX IF NOT EXISTS messages_mailbox ON messages (to_dir, rcpt, created_at); CREATE INDEX IF NOT EXISTS messages_region ON messages (region, created_at, hash); CREATE INDEX IF NOT EXISTS messages_expires ON messages (expires_at); CREATE INDEX IF NOT EXISTS messages_work ON messages (work, created_at); -- The owner's decrypted conversations. These exist only on the owner's node: -- they are never gossiped. CREATE TABLE IF NOT EXISTS inbox ( hash TEXT PRIMARY KEY, -- hash of the envelope that carried it author TEXT NOT NULL, listing_id TEXT NOT NULL, thread TEXT NOT NULL, dir TEXT NOT NULL, -- 'in' from a buyer, 'out' our reply n INTEGER NOT NULL, sent_at INTEGER NOT NULL, received_at INTEGER NOT NULL, hidden INTEGER NOT NULL, -- broke the first-message rules data BLOB NOT NULL -- canonical plaintext ) WITHOUT ROWID; CREATE INDEX IF NOT EXISTS inbox_thread ON inbox (author, listing_id, thread, sent_at); -- Envelopes the owner's node has already looked at (decrypted or not), so -- garbage is not decrypted again on every collection. CREATE TABLE IF NOT EXISTS inbox_seen ( hash TEXT PRIMARY KEY, expires_at INTEGER NOT NULL ) WITHOUT ROWID; -- Conversations the owner blocked: further envelopes of the thread are dropped -- unread. Rows go when their listing does (see Expire). CREATE TABLE IF NOT EXISTS inbox_blocked ( author TEXT NOT NULL, listing_id TEXT NOT NULL, thread TEXT NOT NULL, blocked_at INTEGER NOT NULL, PRIMARY KEY (author, listing_id, thread) ) WITHOUT ROWID; -- Signed abuse reports (internal/report): one per (reporter, listing). CREATE TABLE IF NOT EXISTS reports ( reporter TEXT NOT NULL, l_author TEXT NOT NULL, l_id TEXT NOT NULL, device TEXT NOT NULL, cert_issued_at INTEGER NOT NULL, category TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, hash TEXT NOT NULL, data BLOB NOT NULL, PRIMARY KEY (reporter, l_author, l_id) ) WITHOUT ROWID; CREATE INDEX IF NOT EXISTS reports_listing ON reports (l_author, l_id); CREATE INDEX IF NOT EXISTS reports_expires ON reports (expires_at); -- What visitors told this node about a listing (unsigned, proof-of-work -- only). Never gossiped: they are tips for the operator, who may turn one into -- a signed report. CREATE TABLE IF NOT EXISTS signals ( id INTEGER PRIMARY KEY AUTOINCREMENT, hash TEXT NOT NULL UNIQUE, -- of the visitor's request: sending it twice adds nothing l_author TEXT NOT NULL, l_id TEXT NOT NULL, category TEXT NOT NULL, note TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, work INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS signals_listing ON signals (l_author, l_id); -- The exact address of a listing, only ever read by its owner's node. CREATE TABLE IF NOT EXISTS addresses ( author TEXT NOT NULL, listing_id TEXT NOT NULL, address TEXT NOT NULL, phone TEXT NOT NULL, email TEXT NOT NULL, PRIMARY KEY (author, listing_id) ) 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, msgDifficulty: opt.MessageDifficulty, maxMessages: opt.MaxMessages, ownerQueue: opt.OwnerQueue, mailboxQueue: opt.MailboxQueue} s.trust = opt.Trust if s.trust.Threshold <= 0 { s.trust.Threshold = DefaultHideThreshold } if s.ownerQueue <= 0 { s.ownerQueue = MaxOwnerQueue } if s.mailboxQueue <= 0 { s.mailboxQueue = MaxMailboxQueue } if s.clock == nil { s.clock = time.Now } if s.maxMessages <= 0 { s.maxMessages = defaultMaxMessages } 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 // IncludeHidden also returns listings this node hides because trusted // reporters flagged them (see Trust). They are hidden, never deleted. IncludeHidden bool } // 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) } if !q.IncludeHidden { sub, subArgs := s.hiddenSQL() where = append(where, "(author, id) NOT IN ("+sub+")") args = append(args, subArgs...) } 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 } // Reports signed by a voided device do not count either. if r.AllDevices() { _, err = tx.ExecContext(ctx, `DELETE FROM reports WHERE reporter = ? AND cert_issued_at < ?`, r.Author, r.RevokedAt) } else { _, err = tx.ExecContext(ctx, `DELETE FROM reports WHERE reporter = ? 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() res, err = s.db.ExecContext(ctx, `DELETE FROM messages WHERE expires_at <= ?`, now) if err != nil { return n + m, err } k, _ := res.RowsAffected() // Not counted: housekeeping of the owner's "already seen" markers. if _, err := s.db.ExecContext(ctx, `DELETE FROM inbox_seen WHERE expires_at <= ?`, now); err != nil { return n + m + k, err } if _, err := s.db.ExecContext(ctx, `DELETE FROM reports WHERE expires_at <= ?`, now); err != nil { return n + m + k, err } if _, err := s.db.ExecContext(ctx, `DELETE FROM signals WHERE expires_at <= ?`, now); err != nil { return n + m + k, err } if _, err := s.db.ExecContext(ctx, ` DELETE FROM inbox_blocked WHERE NOT EXISTS ( SELECT 1 FROM listings l WHERE l.author = inbox_blocked.author AND l.id = inbox_blocked.listing_id)`); err != nil { return n + m + k, err } return n + m + k, 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 }