// 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" "strings" "time" "unicode" "unicode/utf8" "git.stinnesbeck.com/nils/allmende/internal/identity" "git.stinnesbeck.com/nils/allmende/internal/jcs" "git.stinnesbeck.com/nils/allmende/internal/pow" ) const ( Version = 1 MaxLifetime = 30 * 24 * time.Hour MaxClockSkew = 10 * time.Minute GeohashPrecision = 6 // RegionPrecision is the geohash prefix length that names a gossip // region (~150 km cells). RegionPrecision = 3 MaxSize = 16 << 10 maxSafeInt = 1<<53 - 1 geohashAlphabet = "0123456789bcdefghjkmnpqrstuvwxyz" listingContext = "allmende-listing-v1\n" ) // DefaultDifficulty is the proof-of-work (leading zero bits) the network // requires. All nodes must agree on it, or they reject each other's messages. const DefaultDifficulty = 16 // ErrTimeWindow marks failures caused by the clock (expired, or created in // the future). They are not the sender's fault, so the p2p layer ignores such // messages instead of penalizing the peer that relayed them. var ErrTimeWindow = errors.New("outside time window") // Region returns the gossip region of a geohash. func Region(geohash string) string { if len(geohash) < RegionPrecision { return geohash } return geohash[:RegionPrecision] } // ValidRegion reports whether s is a well-formed region name. func ValidRegion(s string) bool { return len(s) == RegionPrecision && ValidGeohashPrefix(s) } 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"` // identity public key (hex) Device string `json:"device"` // signing device's public key (hex) 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"` Delegate string `json:"delegate,omitempty"` // optional always-on host's peer ID PoW uint64 `json:"pow"` // Cert proves that Device may sign for Author. The owner's node is the // peer whose ID derives from Device. Cert *identity.Cert `json:"cert"` Sig string `json:"sig,omitempty"` // device signature, hex } // 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 (l *Listing) powOK(difficulty int) (bool, error) { b, err := l.unsignedBytes() if err != nil { return false, err } return pow.LeadingZeroBits(b) >= difficulty, nil } // Seal fills in author, device and certificate from dev, mines the // proof-of-work and signs the listing with the device key. func (l *Listing) Seal(dev *identity.Device, difficulty int) error { l.Author = dev.Cert.Author l.Device = dev.Cert.Device l.Cert = dev.Cert 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(dev.Key.Sign(append([]byte(listingContext), 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.Device, append([]byte(listingContext), 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) || !isHex(l.Device, 64) { return errors.New("listing: author and device must be 64 hex characters") } if l.Cert == nil { return errors.New("listing: certificate required") } if err := l.Cert.Check(); err != nil { return fmt.Errorf("listing: %w", err) } if l.Cert.Author != l.Author || l.Cert.Device != l.Device { return errors.New("listing: certificate does not match author and device") } if !l.Cert.Covers(l.CreatedAt) { return errors.New("listing: created outside the certificate's validity") } if now.Unix() >= l.Cert.ExpiresAt { return fmt.Errorf("listing: certificate expired: %w", ErrTimeWindow) } 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 fmt.Errorf("listing: created_at is in the future: %w", ErrTimeWindow) } if !time.Unix(l.ExpiresAt, 0).After(now) { return fmt.Errorf("listing: expired: %w", ErrTimeWindow) } 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.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 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 } // ValidText applies the text rules shared by listings and messages: valid // UTF-8, a length of min to max characters and no control characters // (newlines only if allowNewlines). func ValidText(s string, min, max int, allowNewlines bool) error { return validText(s, min, max, allowNewlines) } 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 }