Files
allmende/internal/listing/listing.go
T
nilsandClaude Sonnet 5.5 08f6441f03 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 <noreply@anthropic.com>
2026-11-17 17:15:28 +01:00

356 lines
9.6 KiB
Go

// Package listing defines the signed listing record that is replicated
// between nodes. A listing contains no personal data: no address, name, phone
// or email. Those are released by the owner's node on request.
package listing
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"math/bits"
"strings"
"time"
"unicode"
"unicode/utf8"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/jcs"
)
const (
Version = 1
MaxLifetime = 30 * 24 * time.Hour
MaxClockSkew = 10 * time.Minute
GeohashPrecision = 6
MaxSize = 16 << 10
maxSafeInt = 1<<53 - 1
geohashAlphabet = "0123456789bcdefghjkmnpqrstuvwxyz"
)
var (
kinds = map[string]bool{"rent": true, "sale": true}
categories = map[string]bool{"apartment": true, "house": true, "room": true, "commercial": true}
)
type Price struct {
AmountCents int64 `json:"amount_cents"`
Currency string `json:"currency"`
Period string `json:"period"` // "month" for rent, "once" for sale
}
type Image struct {
Hash string `json:"hash"`
ThumbHash string `json:"thumb_hash"`
}
// Listing is the replicated record. Numbers are integers only so the
// canonical JSON encoding is identical in every implementation.
type Listing struct {
Version int `json:"v"`
ID string `json:"id"` // stable across versions
Author string `json:"author"` // hex ed25519 public key
Seq uint64 `json:"seq"` // higher replaces lower
CreatedAt int64 `json:"created_at"`
ExpiresAt int64 `json:"expires_at"`
Tombstone bool `json:"tombstone,omitempty"`
Kind string `json:"kind,omitempty"`
Category string `json:"category,omitempty"`
Geohash string `json:"geohash"`
Price *Price `json:"price,omitempty"`
AreaM2 int `json:"area_m2,omitempty"`
RoomsX2 int `json:"rooms_x2,omitempty"` // rooms*2, so 2.5 rooms = 5
Features []string `json:"features,omitempty"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Images []Image `json:"images,omitempty"`
Endpoint string `json:"endpoint,omitempty"` // owner's peer ID
Delegate string `json:"delegate,omitempty"` // optional always-on host's peer ID
PoW uint64 `json:"pow"`
Sig string `json:"sig,omitempty"` // hex, over canonical bytes without sig
}
// NewID returns a fresh random listing ID (32 hex characters).
func NewID() (string, error) {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
return hex.EncodeToString(b[:]), nil
}
// unsignedBytes is the canonical encoding without the signature. Both the
// signature and the proof-of-work are computed over these bytes.
func (l *Listing) unsignedBytes() ([]byte, error) {
c := *l
c.Sig = ""
return jcs.Marshal(&c)
}
// Bytes returns the full canonical encoding including the signature.
func (l *Listing) Bytes() ([]byte, error) {
return jcs.Marshal(l)
}
// Hash identifies this exact version of the listing (including signature).
func (l *Listing) Hash() (string, error) {
b, err := l.Bytes()
if err != nil {
return "", err
}
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:]), nil
}
func leadingZeroBits(sum [32]byte) int {
n := 0
for _, b := range sum {
if b == 0 {
n += 8
continue
}
return n + bits.LeadingZeros8(b)
}
return n
}
func (l *Listing) powOK(difficulty int) (bool, error) {
b, err := l.unsignedBytes()
if err != nil {
return false, err
}
return leadingZeroBits(sha256.Sum256(b)) >= difficulty, nil
}
// Seal sets the author, mines the proof-of-work and signs the listing.
func (l *Listing) Seal(id *identity.Identity, difficulty int) error {
l.Author = id.PublicKeyHex()
l.Sig = ""
for l.PoW = 0; ; l.PoW++ {
if l.PoW > maxSafeInt {
return errors.New("listing: proof-of-work exhausted")
}
ok, err := l.powOK(difficulty)
if err != nil {
return err
}
if ok {
break
}
}
b, err := l.unsignedBytes()
if err != nil {
return err
}
l.Sig = hex.EncodeToString(id.Sign(b))
return nil
}
// Check fully validates a received listing: structure, size, signature and
// proof-of-work. now is used for lifetime and clock-skew checks.
func (l *Listing) Check(now time.Time, difficulty int) error {
if err := l.validate(now); err != nil {
return err
}
full, err := l.Bytes()
if err != nil {
return err
}
if len(full) > MaxSize {
return fmt.Errorf("listing: %d bytes exceeds limit of %d", len(full), MaxSize)
}
unsigned, err := l.unsignedBytes()
if err != nil {
return err
}
sig, err := hex.DecodeString(l.Sig)
if err != nil || len(sig) != 64 {
return errors.New("listing: malformed signature")
}
if !identity.Verify(l.Author, unsigned, sig) {
return errors.New("listing: bad signature")
}
ok, err := l.powOK(difficulty)
if err != nil {
return err
}
if !ok {
return errors.New("listing: insufficient proof-of-work")
}
return nil
}
// Supersedes reports whether l is a newer version of other.
func (l *Listing) Supersedes(other *Listing) bool {
return l.ID == other.ID && l.Author == other.Author && l.Seq > other.Seq
}
func (l *Listing) validate(now time.Time) error {
if l.Version != Version {
return fmt.Errorf("listing: unsupported version %d", l.Version)
}
if !isHex(l.ID, 32) {
return errors.New("listing: id must be 32 hex characters")
}
if !isHex(l.Author, 64) {
return errors.New("listing: author must be 64 hex characters")
}
if l.Seq > maxSafeInt || l.PoW > maxSafeInt {
return errors.New("listing: number out of range")
}
if l.ExpiresAt <= l.CreatedAt {
return errors.New("listing: expires_at must be after created_at")
}
if time.Duration(l.ExpiresAt-l.CreatedAt)*time.Second > MaxLifetime {
return errors.New("listing: lifetime exceeds 30 days")
}
if time.Unix(l.CreatedAt, 0).After(now.Add(MaxClockSkew)) {
return errors.New("listing: created_at is in the future")
}
if !time.Unix(l.ExpiresAt, 0).After(now) {
return errors.New("listing: expired")
}
if err := validGeohash(l.Geohash); err != nil {
return err
}
if l.Tombstone {
return l.validateTombstone()
}
return l.validateContent()
}
func (l *Listing) validateTombstone() error {
if l.Kind != "" || l.Category != "" || l.Price != nil || l.AreaM2 != 0 || l.RoomsX2 != 0 ||
len(l.Features) > 0 || l.Title != "" || l.Description != "" || len(l.Images) > 0 ||
l.Endpoint != "" || l.Delegate != "" {
return errors.New("listing: tombstone must not carry content")
}
return nil
}
func (l *Listing) validateContent() error {
if !kinds[l.Kind] {
return fmt.Errorf("listing: invalid kind %q", l.Kind)
}
if !categories[l.Category] {
return fmt.Errorf("listing: invalid category %q", l.Category)
}
p := l.Price
if p == nil {
return errors.New("listing: price required")
}
if p.AmountCents <= 0 || p.AmountCents > maxSafeInt {
return errors.New("listing: price out of range")
}
if p.Currency != "EUR" {
return errors.New("listing: only EUR is supported")
}
wantPeriod := map[string]string{"rent": "month", "sale": "once"}[l.Kind]
if p.Period != wantPeriod {
return fmt.Errorf("listing: %s requires period %q", l.Kind, wantPeriod)
}
if l.AreaM2 < 0 || l.AreaM2 > 100000 || l.RoomsX2 < 0 || l.RoomsX2 > 200 {
return errors.New("listing: area or rooms out of range")
}
if err := validText(l.Title, 1, 120, false); err != nil {
return fmt.Errorf("listing: title: %w", err)
}
if err := validText(l.Description, 0, 4000, true); err != nil {
return fmt.Errorf("listing: description: %w", err)
}
if len(l.Features) > 20 {
return errors.New("listing: too many features")
}
for _, f := range l.Features {
if err := validText(f, 1, 40, false); err != nil {
return fmt.Errorf("listing: feature: %w", err)
}
}
if len(l.Images) > 20 {
return errors.New("listing: too many images")
}
for _, im := range l.Images {
if !isHex(im.Hash, 64) || !isHex(im.ThumbHash, 64) {
return errors.New("listing: image hashes must be 64 hex characters")
}
}
if !validPeerID(l.Endpoint) {
return errors.New("listing: invalid endpoint")
}
if l.Delegate != "" && !validPeerID(l.Delegate) {
return errors.New("listing: invalid delegate")
}
return nil
}
func isHex(s string, n int) bool {
if len(s) != n {
return false
}
for i := 0; i < len(s); i++ {
c := s[i]
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
return false
}
}
return true
}
func validGeohash(g string) error {
if len(g) != GeohashPrecision {
return fmt.Errorf("listing: geohash must have precision %d", GeohashPrecision)
}
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
}
for i := 0; i < len(s); i++ {
c := s[i]
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
return false
}
}
return true
}
func validText(s string, min, max int, allowNewlines bool) error {
if !utf8.ValidString(s) {
return errors.New("invalid UTF-8")
}
n := utf8.RuneCountInString(s)
if n < min || n > max {
return fmt.Errorf("length must be %d-%d characters", min, max)
}
for _, r := range s {
if r == '\n' && allowNewlines {
continue
}
if unicode.IsControl(r) {
return errors.New("control characters not allowed")
}
}
return nil
}