Implement end-to-end encrypted buyer/seller messaging
Wire format (internal/message): sealed boxes to the listing's device key (X25519 + HKDF + ChaCha20-Poly1305), padded, proof-of-work stamped, with signed owner replies and address grants. Relay validation, bounded queues, gossip on per-region message topics and sync (store, p2p). Owner side (internal/inbox, API): inbox with hidden link messages and a per-day new-thread limit, replies, grants, and a private per-listing address. Public POST/GET /api/v1/messages for buyers. Browser: noble-based sealing and reply verification checked against a Go fixture, contact form, conversation view, message list, de/en strings. Docs: PROTOCOL.md messaging section matches the implementation. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,284 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
)
|
||||
|
||||
const (
|
||||
// MaxOwnerQueue is how many live envelopes one listing's owner queue holds.
|
||||
MaxOwnerQueue = 200
|
||||
// MaxMailboxQueue is how many live replies one mailbox holds.
|
||||
MaxMailboxQueue = 50
|
||||
|
||||
defaultMaxMessages = 20000
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrNoListing means an owner-bound envelope refers to a listing this node
|
||||
// does not hold live, or to a device that no longer signs for it. This
|
||||
// is usually ordering or a device change, not misbehaviour, so the p2p
|
||||
// layer ignores such envelopes without penalizing the sender.
|
||||
ErrNoListing = errors.New("store: no such live listing")
|
||||
// ErrQueueFull means a queue was full of envelopes with at least as much
|
||||
// proof-of-work as the new one.
|
||||
ErrQueueFull = errors.New("store: message queue full")
|
||||
)
|
||||
|
||||
// PutMessage verifies an envelope as a relay can and stores it in region.
|
||||
// Conflict-free: an envelope's identity is its hash, so duplicates are no-ops.
|
||||
//
|
||||
// Queues are bounded (per listing, per mailbox and overall). When one is full
|
||||
// the envelope with the least proof-of-work is evicted, oldest first, so
|
||||
// filling a queue costs more work than the messages it displaces.
|
||||
func (s *Store) PutMessage(ctx context.Context, region string, e *message.Envelope) (Outcome, error) {
|
||||
now := s.clock()
|
||||
if err := e.Check(now, s.msgDifficulty); err != nil {
|
||||
return Ignored, fmt.Errorf("%w: %w", ErrInvalid, err)
|
||||
}
|
||||
if !listing.ValidRegion(region) {
|
||||
return Ignored, fmt.Errorf("%w: bad region %q", ErrInvalid, region)
|
||||
}
|
||||
hash, err := e.Hash()
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
work, err := e.Work()
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
data, err := e.Bytes()
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM messages WHERE expires_at <= ?`, now.Unix()); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
|
||||
if err := s.route(ctx, tx, now.Unix(), region, e); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
|
||||
var dup int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM messages WHERE hash = ?`, hash).Scan(&dup); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
if dup > 0 {
|
||||
return Ignored, nil
|
||||
}
|
||||
|
||||
// Make room: the queue's own cap first, then the overall cap.
|
||||
var victims []string
|
||||
if e.To == message.ToOwner {
|
||||
v, reject, err := victim(ctx, tx, `to_dir = 'owner' AND author = ? AND listing_id = ?`,
|
||||
[]any{e.Listing.Author, e.Listing.ID}, s.ownerQueue, work)
|
||||
if err != nil || reject {
|
||||
return Ignored, orFull(err)
|
||||
}
|
||||
if v != "" {
|
||||
victims = append(victims, v)
|
||||
}
|
||||
} else {
|
||||
v, reject, err := victim(ctx, tx, `to_dir = 'buyer' AND rcpt = ?`, []any{e.Rcpt}, s.mailboxQueue, work)
|
||||
if err != nil || reject {
|
||||
return Ignored, orFull(err)
|
||||
}
|
||||
if v != "" {
|
||||
victims = append(victims, v)
|
||||
}
|
||||
}
|
||||
// If the queue already frees a slot, count it before checking the total.
|
||||
limit := s.maxMessages + len(victims)
|
||||
v, reject, err := victim(ctx, tx, `1 = 1`, nil, limit, work)
|
||||
if err != nil || reject {
|
||||
return Ignored, orFull(err)
|
||||
}
|
||||
if v != "" {
|
||||
victims = append(victims, v)
|
||||
}
|
||||
for _, h := range victims {
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM messages WHERE hash = ?`, h); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
}
|
||||
|
||||
_, err = tx.ExecContext(ctx, `
|
||||
INSERT INTO messages (hash, to_dir, author, listing_id, rcpt, region, created_at, expires_at, work, data)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
hash, e.To, e.Listing.Author, e.Listing.ID, e.Rcpt, region, e.CreatedAt, e.ExpiresAt, work, data)
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
return Inserted, nil
|
||||
}
|
||||
|
||||
type rowQuerier interface {
|
||||
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
|
||||
}
|
||||
|
||||
// route checks an envelope against the listing it refers to: the region must
|
||||
// match the listing's, and an owner-bound envelope needs a live listing whose
|
||||
// current device is the recipient. Replies to buyers need no listing (the
|
||||
// owner may have deleted it since), but if it is known the region still has
|
||||
// to match.
|
||||
func (s *Store) route(ctx context.Context, q rowQuerier, now int64, region string, e *message.Envelope) error {
|
||||
var geohash, device string
|
||||
var tombstone, expires int64
|
||||
err := q.QueryRowContext(ctx,
|
||||
`SELECT geohash, device, tombstone, expires_at FROM listings WHERE author = ? AND id = ?`,
|
||||
e.Listing.Author, e.Listing.ID).Scan(&geohash, &device, &tombstone, &expires)
|
||||
known := err == nil
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
if known && listing.Region(geohash) != region {
|
||||
return fmt.Errorf("%w: wrong region for this listing", ErrInvalid)
|
||||
}
|
||||
if e.To == message.ToOwner && (!known || tombstone != 0 || expires <= now || device != e.Rcpt) {
|
||||
return ErrNoListing
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CheckMessage is the read-only part of PutMessage: what a relay verifies
|
||||
// before forwarding an envelope. It returns an error wrapping ErrInvalid for
|
||||
// envelopes that are wrong, and ErrNoListing for ones this node cannot place.
|
||||
func (s *Store) CheckMessage(ctx context.Context, region string, e *message.Envelope) error {
|
||||
now := s.clock()
|
||||
if err := e.Check(now, s.msgDifficulty); err != nil {
|
||||
return fmt.Errorf("%w: %w", ErrInvalid, err)
|
||||
}
|
||||
if !listing.ValidRegion(region) {
|
||||
return fmt.Errorf("%w: bad region %q", ErrInvalid, region)
|
||||
}
|
||||
return s.route(ctx, s.db, now.Unix(), region, e)
|
||||
}
|
||||
|
||||
// orFull turns "rejected, no error" into ErrQueueFull.
|
||||
func orFull(err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ErrQueueFull
|
||||
}
|
||||
|
||||
// victim looks at the rows matching where. If there are fewer than limit it
|
||||
// returns nothing. Otherwise it picks the row with the least work (oldest on
|
||||
// ties) to evict, or reject = true if the new envelope has even less work.
|
||||
// where is always a constant fragment from this file, never caller input.
|
||||
func victim(ctx context.Context, tx *sql.Tx, where string, args []any, limit, work int) (hash string, reject bool, err error) {
|
||||
var n int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM messages WHERE `+where, args...).Scan(&n); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if n < limit {
|
||||
return "", false, nil
|
||||
}
|
||||
var least int
|
||||
err = tx.QueryRowContext(ctx,
|
||||
`SELECT hash, work FROM messages WHERE `+where+` ORDER BY work, created_at LIMIT 1`, args...).
|
||||
Scan(&hash, &least)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if work < least {
|
||||
return "", true, nil
|
||||
}
|
||||
return hash, false, nil
|
||||
}
|
||||
|
||||
// OwnerMessages returns the live envelopes addressed to author's listings,
|
||||
// oldest first. The owner's node decrypts them with its device key.
|
||||
func (s *Store) OwnerMessages(ctx context.Context, author string) ([]*message.Envelope, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT data FROM messages
|
||||
WHERE to_dir = 'owner' AND author = ? AND expires_at > ?
|
||||
ORDER BY created_at, hash`, author, s.clock().Unix())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return collectMessages(rows)
|
||||
}
|
||||
|
||||
// Mailbox returns up to limit live replies in a mailbox created at or after
|
||||
// since, oldest first. A browser polls it; it dedupes by hash.
|
||||
func (s *Store) Mailbox(ctx context.Context, tag string, since int64, limit int) ([]*message.Envelope, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT data FROM messages
|
||||
WHERE to_dir = 'buyer' AND rcpt = ? AND created_at >= ? AND expires_at > ?
|
||||
ORDER BY created_at, hash LIMIT ?`, tag, since, s.clock().Unix(), limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return collectMessages(rows)
|
||||
}
|
||||
|
||||
// MessageCursor is a keyset position in the (created_at, hash) order used to
|
||||
// page through envelopes during sync. The zero value is the beginning.
|
||||
type MessageCursor struct {
|
||||
CreatedAt int64
|
||||
Hash string
|
||||
}
|
||||
|
||||
// MessageCursorOf returns the cursor positioned at e.
|
||||
func MessageCursorOf(e *message.Envelope) (MessageCursor, error) {
|
||||
h, err := e.Hash()
|
||||
return MessageCursor{CreatedAt: e.CreatedAt, Hash: h}, err
|
||||
}
|
||||
|
||||
// MessagesSince returns up to limit live envelopes of a region after cur,
|
||||
// oldest first, for peers that are catching up.
|
||||
func (s *Store) MessagesSince(ctx context.Context, region string, cur MessageCursor, limit int) ([]*message.Envelope, error) {
|
||||
if !listing.ValidRegion(region) {
|
||||
return nil, fmt.Errorf("store: invalid region %q", region)
|
||||
}
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT data FROM messages
|
||||
WHERE region = ? AND expires_at > ? AND (created_at, hash) > (?, ?)
|
||||
ORDER BY created_at, hash LIMIT ?`, region, s.clock().Unix(), cur.CreatedAt, cur.Hash, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return collectMessages(rows)
|
||||
}
|
||||
|
||||
// MessageCount returns the number of live envelopes held.
|
||||
func (s *Store) MessageCount(ctx context.Context) (int, error) {
|
||||
var n int
|
||||
err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM messages WHERE expires_at > ?`,
|
||||
s.clock().Unix()).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func collectMessages(rows *sql.Rows) ([]*message.Envelope, error) {
|
||||
defer rows.Close()
|
||||
var out []*message.Envelope
|
||||
for rows.Next() {
|
||||
var data []byte
|
||||
if err := rows.Scan(&data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var e message.Envelope
|
||||
if err := json.Unmarshal(data, &e); err != nil {
|
||||
return nil, fmt.Errorf("store: corrupt message row: %w", err)
|
||||
}
|
||||
out = append(out, &e)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
Reference in New Issue
Block a user