From 08f6441f03889856ceea0e09dade7c1b0af8e041 Mon Sep 17 00:00:00 2001 From: Nils Stinnesbeck Date: Tue, 17 Nov 2026 17:15:28 +0100 Subject: [PATCH] Add SQLite listing store with deterministic conflict rules - Put verifies listings and keeps only the newest version per (author, id); equal seq resolves to the smaller hash so replicas converge - Tombstones are stored so old versions cannot be resurrected - Search by geohash prefix, kind, category, price, area, rooms - Expire removes listings and tombstones past their lifetime Co-Authored-By: Claude Sonnet 5.5 --- go.mod | 14 ++ go.sum | 50 ++++++ internal/listing/listing.go | 28 +-- internal/store/store.go | 306 +++++++++++++++++++++++++++++++++ internal/store/store_test.go | 321 +++++++++++++++++++++++++++++++++++ 5 files changed, 708 insertions(+), 11 deletions(-) create mode 100644 go.sum create mode 100644 internal/store/store.go create mode 100644 internal/store/store_test.go diff --git a/go.mod b/go.mod index d50a488..7897a7d 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,17 @@ module git.stinnesbeck.com/nils/allmende go 1.27.3 + +require modernc.org/sqlite v1.62.0 + +require ( + github.com/dustin/go-humanize v1.1.0 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/mattn/go-isatty v0.0.24 // indirect + github.com/ncruces/go-strftime v1.1.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + golang.org/x/sys v0.49.0 // indirect + modernc.org/libc v1.80.1 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.12.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..9f88b65 --- /dev/null +++ b/go.sum @@ -0,0 +1,50 @@ +github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= +github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= +github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= +golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= +golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= +modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b h1:WE5SLOURcNd8s6uPR/n4WV4weQxxYKi5OpEZkfNVvdE= +modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= +modernc.org/ccgo/v4 v4.38.1 h1:wdxJVBuFT8JufZnnQyS6Bbz3NOWhViD0xJOGR96Bpd4= +modernc.org/ccgo/v4 v4.38.1/go.mod h1:kOpEkJRbFwBvjUWwn4j1j9B7iFHbl1+orhgTMCDkDBk= +modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= +modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/gc/v3 v3.2.0 h1:/Y3LGDMQaoYf55PebP1qsZ5FDGgAZyG1RYKEHeQzh1o= +modernc.org/gc/v3 v3.2.0/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= +modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= +modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= +modernc.org/libc v1.80.1 h1:ejn7HtTV3GknNKbklqWQ1nvUrfX8mTxs1D+xp/JQwy4= +modernc.org/libc v1.80.1/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g= +modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= +modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.62.0 h1:gMaCjSM1qpl+iOjiWhR1LYP3zqrYDI+5GYLGt6veP2g= +modernc.org/sqlite v1.62.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/internal/listing/listing.go b/internal/listing/listing.go index 87b4ac8..a233761 100644 --- a/internal/listing/listing.go +++ b/internal/listing/listing.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" "math/bits" + "strings" "time" "unicode" "unicode/utf8" @@ -301,21 +302,26 @@ func validGeohash(g string) error { if len(g) != GeohashPrecision { return fmt.Errorf("listing: geohash must have precision %d", GeohashPrecision) } - for i := 0; i < len(g); i++ { - found := false - for j := 0; j < len(geohashAlphabet); j++ { - if g[i] == geohashAlphabet[j] { - found = true - break - } - } - if !found { - return errors.New("listing: invalid geohash character") - } + if !ValidGeohashPrefix(g) { + return errors.New("listing: invalid geohash character") } return nil } +// ValidGeohashPrefix reports whether p is a non-empty geohash prefix of at +// most GeohashPrecision characters from the geohash alphabet. +func ValidGeohashPrefix(p string) bool { + if len(p) == 0 || len(p) > GeohashPrecision { + return false + } + for i := 0; i < len(p); i++ { + if !strings.ContainsRune(geohashAlphabet, rune(p[i])) { + return false + } + } + return true +} + func validPeerID(s string) bool { if len(s) < 8 || len(s) > 128 { return false diff --git a/internal/store/store.go b/internal/store/store.go new file mode 100644 index 0000000..a84afe1 --- /dev/null +++ b/internal/store/store.go @@ -0,0 +1,306 @@ +// 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/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") +) + +// 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, + 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); +` + +// 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 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, 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, + 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() +} + +// 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. +func (s *Store) Expire(ctx context.Context) (int64, error) { + res, err := s.db.ExecContext(ctx, `DELETE FROM listings WHERE expires_at <= ?`, s.clock().Unix()) + if err != nil { + return 0, err + } + return res.RowsAffected() +} + +// 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 +} + +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 +} diff --git a/internal/store/store_test.go b/internal/store/store_test.go new file mode 100644 index 0000000..a357813 --- /dev/null +++ b/internal/store/store_test.go @@ -0,0 +1,321 @@ +package store + +import ( + "context" + "errors" + "path/filepath" + "testing" + "time" + + "git.stinnesbeck.com/nils/allmende/internal/identity" + "git.stinnesbeck.com/nils/allmende/internal/listing" +) + +const difficulty = 8 + +var ( + ctx = context.Background() + t0 = time.Unix(1_800_000_000, 0) +) + +type env struct { + s *Store + now time.Time + key *identity.Identity +} + +func newEnv(t *testing.T) *env { + t.Helper() + e := &env{now: t0} + e.key, _ = identity.Generate() + s, err := Open(":memory:", Options{Difficulty: difficulty, Clock: func() time.Time { return e.now }}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { s.Close() }) + e.s = s + return e +} + +func (e *env) listing(t *testing.T, mutate func(*listing.Listing)) *listing.Listing { + t.Helper() + id, _ := listing.NewID() + l := &listing.Listing{ + Version: listing.Version, + ID: id, + Seq: 1, + CreatedAt: e.now.Unix(), + ExpiresAt: e.now.Add(7 * 24 * time.Hour).Unix(), + Kind: "rent", + Category: "apartment", + Geohash: "u1xjhx", + Price: &listing.Price{AmountCents: 100000, Currency: "EUR", Period: "month"}, + AreaM2: 50, + RoomsX2: 4, + Title: "Wohnung", + Endpoint: "12D3KooWExamplePeerID", + } + if mutate != nil { + mutate(l) + } + if err := l.Seal(e.key, difficulty); err != nil { + t.Fatal(err) + } + return l +} + +func (e *env) put(t *testing.T, l *listing.Listing) Outcome { + t.Helper() + o, err := e.s.Put(ctx, l) + if err != nil { + t.Fatal(err) + } + return o +} + +func TestPutGet(t *testing.T) { + e := newEnv(t) + l := e.listing(t, nil) + if o := e.put(t, l); o != Inserted { + t.Fatalf("got %v want inserted", o) + } + got, err := e.s.Get(ctx, l.Author, l.ID) + if err != nil { + t.Fatal(err) + } + a, _ := l.Bytes() + b, _ := got.Bytes() + if string(a) != string(b) { + t.Fatal("stored listing differs from original") + } + if o := e.put(t, l); o != Ignored { + t.Fatalf("duplicate: got %v want ignored", o) + } +} + +func TestRejectsInvalid(t *testing.T) { + e := newEnv(t) + l := e.listing(t, nil) + l.Price.AmountCents = 1 // breaks signature + _, err := e.s.Put(ctx, l) + if !errors.Is(err, ErrInvalid) { + t.Fatalf("got %v, want ErrInvalid", err) + } + if n, _ := e.s.Count(ctx); n != 0 { + t.Fatal("invalid listing was stored") + } +} + +func TestHigherSeqWinsInAnyOrder(t *testing.T) { + e := newEnv(t) + v1 := e.listing(t, nil) + v2 := *v1 + v2.Seq = 2 + v2.Title = "Neuer Titel" + if err := v2.Seal(e.key, difficulty); err != nil { + t.Fatal(err) + } + + // Newer first, older second: older must be ignored. + if o := e.put(t, &v2); o != Inserted { + t.Fatalf("v2: %v", o) + } + if o := e.put(t, v1); o != Ignored { + t.Fatalf("v1 after v2: got %v want ignored", o) + } + got, _ := e.s.Get(ctx, v1.Author, v1.ID) + if got.Title != "Neuer Titel" { + t.Fatalf("got %q", got.Title) + } + + // Fresh store, natural order: second is a replacement. + e2 := newEnv(t) + e2.key = e.key + e2.put(t, v1) + if o := e2.put(t, &v2); o != Replaced { + t.Fatalf("got %v want replaced", o) + } +} + +func TestEqualSeqConvergesOnSmallerHash(t *testing.T) { + e := newEnv(t) + a := e.listing(t, nil) + b := *a + b.Title = "Anderer Titel" + if err := b.Seal(e.key, difficulty); err != nil { + t.Fatal(err) + } + ha, _ := a.Hash() + hb, _ := b.Hash() + winner, loser := a, &b + if hb < ha { + winner, loser = &b, a + } + + for name, order := range map[string][]*listing.Listing{ + "winner first": {winner, loser}, + "loser first": {loser, winner}, + } { + t.Run(name, func(t *testing.T) { + e2 := newEnv(t) + e2.key = e.key + for _, l := range order { + e2.put(t, l) + } + got, _ := e2.s.Get(ctx, a.Author, a.ID) + if got.Title != winner.Title { + t.Fatalf("converged on %q, want %q", got.Title, winner.Title) + } + }) + } +} + +func TestTombstoneDeletesAndBlocksResurrection(t *testing.T) { + e := newEnv(t) + l := e.listing(t, nil) + e.put(t, l) + + 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 { + t.Fatal(err) + } + if o := e.put(t, ts); o != Replaced { + t.Fatalf("got %v want replaced", o) + } + if _, err := e.s.Get(ctx, l.Author, l.ID); !errors.Is(err, ErrNotFound) { + t.Fatalf("deleted listing still readable: %v", err) + } + if o := e.put(t, l); o != Ignored { + t.Fatalf("old version resurrected: %v", o) + } + if n, _ := e.s.Count(ctx); n != 0 { + t.Fatalf("count %d, want 0", n) + } + + // A tombstone arriving before the listing it deletes still wins. + e2 := newEnv(t) + e2.key = e.key + e2.put(t, ts) + if o := e2.put(t, l); o != Ignored { + t.Fatalf("listing after tombstone: %v", o) + } +} + +func TestSameIDDifferentAuthorsDoNotCollide(t *testing.T) { + e := newEnv(t) + victim := e.listing(t, nil) + e.put(t, victim) + + other, _ := identity.Generate() + squat := *victim + squat.Seq = 99 + squat.Title = "Betrug" + if err := squat.Seal(other, difficulty); err != nil { + t.Fatal(err) + } + e.put(t, &squat) + + got, err := e.s.Get(ctx, victim.Author, victim.ID) + if err != nil || got.Title != "Wohnung" { + t.Fatalf("victim listing disturbed: %v %v", got, err) + } +} + +func TestSearch(t *testing.T) { + e := newEnv(t) + mk := func(geo, kind string, cents int64, area, rooms int) { + period := map[string]string{"rent": "month", "sale": "once"}[kind] + e.put(t, e.listing(t, func(l *listing.Listing) { + l.Geohash, l.Kind = geo, kind + l.Price = &listing.Price{AmountCents: cents, Currency: "EUR", Period: period} + l.AreaM2, l.RoomsX2 = area, rooms + })) + } + mk("u1xjhx", "rent", 90000, 40, 3) + mk("u1xjhz", "rent", 150000, 80, 6) + mk("u1xkbb", "rent", 120000, 60, 4) + mk("u1xjhx", "sale", 30000000, 90, 6) + mk("u30000", "rent", 100000, 50, 4) // different region + + count := func(q Query) int { + t.Helper() + got, err := e.s.Search(ctx, q) + if err != nil { + t.Fatal(err) + } + return len(got) + } + cases := []struct { + name string + q Query + want int + }{ + {"all", Query{}, 5}, + {"region prefix", Query{Geohashes: []string{"u1x"}}, 4}, + {"narrow prefix", Query{Geohashes: []string{"u1xjh"}}, 3}, + {"two prefixes", Query{Geohashes: []string{"u1xk", "u3"}}, 2}, + {"rent in region", Query{Geohashes: []string{"u1x"}, Kind: "rent"}, 3}, + {"price range", Query{Kind: "rent", MinPriceCents: 95000, MaxPriceCents: 130000}, 2}, + {"min area", Query{Kind: "rent", MinAreaM2: 55}, 2}, + {"min rooms", Query{MinRoomsX2: 6}, 2}, + {"limit", Query{Limit: 2}, 2}, + {"offset", Query{Offset: 4}, 1}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := count(tc.q); got != tc.want { + t.Fatalf("got %d want %d", got, tc.want) + } + }) + } + + if _, err := e.s.Search(ctx, Query{Geohashes: []string{"u1x' OR 1=1 --"}}); err == nil { + t.Fatal("invalid geohash prefix accepted") + } +} + +func TestExpiry(t *testing.T) { + e := newEnv(t) + l := e.listing(t, nil) + e.put(t, l) + + e.now = e.now.Add(8 * 24 * time.Hour) + if _, err := e.s.Get(ctx, l.Author, l.ID); !errors.Is(err, ErrNotFound) { + t.Fatal("expired listing still readable") + } + if got, _ := e.s.Search(ctx, Query{}); len(got) != 0 { + t.Fatal("expired listing in search results") + } + n, err := e.s.Expire(ctx) + if err != nil || n != 1 { + t.Fatalf("Expire = %d, %v; want 1", n, err) + } +} + +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} + l := e.listing(t, nil) + e.put(t, l) + s.Close() + + s, err = Open(path, opt) + if err != nil { + t.Fatal(err) + } + defer s.Close() + if _, err := s.Get(ctx, l.Author, l.ID); err != nil { + t.Fatalf("listing lost after reopen: %v", err) + } +}