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:
2026-11-17 19:44:59 +01:00
co-authored by Claude Sonnet 5.5
parent b9e1b0c058
commit 3b0351c774
45 changed files with 8228 additions and 292 deletions
+239
View File
@@ -0,0 +1,239 @@
package store
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"git.stinnesbeck.com/nils/allmende/internal/jcs"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/message"
)
// Directions of an InboxMessage.
const (
InboxIn = "in" // from a buyer
InboxOut = "out" // our reply
)
// InboxMessage is one decrypted message in the owner's conversations.
type InboxMessage struct {
Hash string // hash of the envelope that carried it
Listing message.Ref
Thread string
Dir string
Plain *message.Plain
Hidden bool // a buyer message that broke the first-message rules
ReceivedAt int64
}
// ThreadSummary describes one conversation.
type ThreadSummary struct {
Listing message.Ref
Thread string
Messages int
Hidden int
Replied bool // we have answered at least once
FirstAt int64
LastAt int64
}
// Address is the exact location and contact data of a listing. It is stored
// only here and used only to prefill an address grant.
type Address struct {
Address string `json:"address"`
Phone string `json:"phone,omitempty"`
Email string `json:"email,omitempty"`
}
// Region returns the gossip region of a listing, even if it is deleted or
// expired but not yet purged, so replies can still be routed.
func (s *Store) Region(ctx context.Context, author, id string) (string, error) {
var geohash string
err := s.db.QueryRowContext(ctx,
`SELECT geohash FROM listings WHERE author = ? AND id = ?`, author, id).Scan(&geohash)
if errors.Is(err, sql.ErrNoRows) {
return "", ErrNotFound
}
if err != nil {
return "", err
}
return listing.Region(geohash), nil
}
// SeenEnvelopes returns which of the given envelope hashes the owner's node
// has already processed.
func (s *Store) SeenEnvelopes(ctx context.Context, hashes []string) (map[string]bool, error) {
seen := map[string]bool{}
for _, h := range hashes {
var n int
if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM inbox_seen WHERE hash = ?`, h).Scan(&n); err != nil {
return nil, err
}
seen[h] = n > 0
}
return seen, nil
}
// MarkSeen records an envelope as processed until expiresAt.
func (s *Store) MarkSeen(ctx context.Context, hash string, expiresAt int64) error {
_, err := s.db.ExecContext(ctx, `INSERT OR IGNORE INTO inbox_seen (hash, expires_at) VALUES (?, ?)`, hash, expiresAt)
return err
}
// AddInbox stores a decrypted message and marks its envelope as seen, in one
// transaction. Adding the same hash twice is a no-op.
func (s *Store) AddInbox(ctx context.Context, m InboxMessage, seenUntil int64) error {
data, err := jcs.Marshal(m.Plain)
if err != nil {
return err
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, `
INSERT OR IGNORE INTO inbox (hash, author, listing_id, thread, dir, n, sent_at, received_at, hidden, data)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
m.Hash, m.Listing.Author, m.Listing.ID, m.Thread, m.Dir, m.Plain.N, m.Plain.SentAt, m.ReceivedAt,
boolInt(m.Hidden), data); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `INSERT OR IGNORE INTO inbox_seen (hash, expires_at) VALUES (?, ?)`,
m.Hash, seenUntil); err != nil {
return err
}
return tx.Commit()
}
// HasThread reports whether a conversation exists.
func (s *Store) HasThread(ctx context.Context, ref message.Ref, thread string) (bool, error) {
var n int
err := s.db.QueryRowContext(ctx,
`SELECT COUNT(*) FROM inbox WHERE author = ? AND listing_id = ? AND thread = ?`,
ref.Author, ref.ID, thread).Scan(&n)
return n > 0, err
}
// Replied reports whether we have sent anything in the conversation.
func (s *Store) Replied(ctx context.Context, ref message.Ref, thread string) (bool, error) {
var n int
err := s.db.QueryRowContext(ctx,
`SELECT COUNT(*) FROM inbox WHERE author = ? AND listing_id = ? AND thread = ? AND dir = 'out'`,
ref.Author, ref.ID, thread).Scan(&n)
return n > 0, err
}
// NewThreadsSince counts conversations of a listing that began (were first
// received) at or after since.
func (s *Store) NewThreadsSince(ctx context.Context, ref message.Ref, since int64) (int, error) {
var n int
err := s.db.QueryRowContext(ctx, `
SELECT COUNT(*) FROM (
SELECT MIN(received_at) AS first FROM inbox
WHERE author = ? AND listing_id = ? GROUP BY thread
) WHERE first >= ?`, ref.Author, ref.ID, since).Scan(&n)
return n, err
}
// NextOut returns the counter for our next message in a conversation.
func (s *Store) NextOut(ctx context.Context, ref message.Ref, thread string) (int64, error) {
var max sql.NullInt64
err := s.db.QueryRowContext(ctx,
`SELECT MAX(n) FROM inbox WHERE author = ? AND listing_id = ? AND thread = ? AND dir = 'out'`,
ref.Author, ref.ID, thread).Scan(&max)
return max.Int64 + 1, err
}
// Threads lists the author's conversations, most recently active first.
func (s *Store) Threads(ctx context.Context, author string) ([]ThreadSummary, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT listing_id, thread, COUNT(*), SUM(hidden), SUM(dir = 'out'), MIN(received_at), MAX(sent_at)
FROM inbox WHERE author = ?
GROUP BY listing_id, thread
ORDER BY MAX(sent_at) DESC, thread`, author)
if err != nil {
return nil, err
}
defer rows.Close()
var out []ThreadSummary
for rows.Next() {
t := ThreadSummary{Listing: message.Ref{Author: author}}
var replies int
if err := rows.Scan(&t.Listing.ID, &t.Thread, &t.Messages, &t.Hidden, &replies, &t.FirstAt, &t.LastAt); err != nil {
return nil, err
}
t.Replied = replies > 0
out = append(out, t)
}
return out, rows.Err()
}
// ThreadMessages returns a conversation in order.
func (s *Store) ThreadMessages(ctx context.Context, ref message.Ref, thread string) ([]InboxMessage, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT hash, dir, hidden, received_at, data FROM inbox
WHERE author = ? AND listing_id = ? AND thread = ?
ORDER BY sent_at, dir, n, hash`, ref.Author, ref.ID, thread)
if err != nil {
return nil, err
}
defer rows.Close()
var out []InboxMessage
for rows.Next() {
m := InboxMessage{Listing: ref, Thread: thread}
var hidden int
var data []byte
if err := rows.Scan(&m.Hash, &m.Dir, &hidden, &m.ReceivedAt, &data); err != nil {
return nil, err
}
m.Hidden = hidden != 0
m.Plain = &message.Plain{}
if err := json.Unmarshal(data, m.Plain); err != nil {
return nil, fmt.Errorf("store: corrupt inbox row: %w", err)
}
out = append(out, m)
}
return out, rows.Err()
}
// DeleteThread erases a conversation from this node.
func (s *Store) DeleteThread(ctx context.Context, ref message.Ref, thread string) (bool, error) {
res, err := s.db.ExecContext(ctx,
`DELETE FROM inbox WHERE author = ? AND listing_id = ? AND thread = ?`, ref.Author, ref.ID, thread)
if err != nil {
return false, err
}
n, _ := res.RowsAffected()
return n > 0, nil
}
// SetAddress stores the exact address of one of the author's listings.
func (s *Store) SetAddress(ctx context.Context, ref message.Ref, a Address) error {
_, err := s.db.ExecContext(ctx, `
INSERT OR REPLACE INTO addresses (author, listing_id, address, phone, email) VALUES (?, ?, ?, ?, ?)`,
ref.Author, ref.ID, a.Address, a.Phone, a.Email)
return err
}
// GetAddress returns the stored address, or ErrNotFound.
func (s *Store) GetAddress(ctx context.Context, ref message.Ref) (Address, error) {
var a Address
err := s.db.QueryRowContext(ctx,
`SELECT address, phone, email FROM addresses WHERE author = ? AND listing_id = ?`,
ref.Author, ref.ID).Scan(&a.Address, &a.Phone, &a.Email)
if errors.Is(err, sql.ErrNoRows) {
return a, ErrNotFound
}
return a, err
}
// DeleteAddress erases the stored address.
func (s *Store) DeleteAddress(ctx context.Context, ref message.Ref) error {
_, err := s.db.ExecContext(ctx,
`DELETE FROM addresses WHERE author = ? AND listing_id = ?`, ref.Author, ref.ID)
return err
}
+284
View File
@@ -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()
}
+332
View File
@@ -0,0 +1,332 @@
package store
import (
"errors"
"strings"
"testing"
"time"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/message"
)
const msgDifficulty = 4
const region = "u1x"
func newMsgEnv(t *testing.T, opt Options) *env {
t.Helper()
e := &env{now: t0}
e.root, _, _ = identity.NewRoot()
e.dev = newDevice(t, e.root)
opt.Difficulty = difficulty
opt.MessageDifficulty = msgDifficulty
opt.Clock = func() time.Time { return e.now }
s, err := Open(":memory:", opt)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { s.Close() })
e.s = s
return e
}
// toOwner makes a buyer's envelope whose work is exactly `work` bits, so
// eviction order can be tested precisely.
func toOwner(t *testing.T, l *listing.Listing, at time.Time, work int) *message.Envelope {
t.Helper()
for {
tk, err := message.NewThreadKey()
if err != nil {
t.Fatal(err)
}
p := &message.Plain{Type: message.TypeText, N: 1, SentAt: at.Unix(), Text: "hi"}
e, err := message.SealToOwner(l, tk, p, at, work)
if err != nil {
t.Fatal(err)
}
if w, _ := e.Work(); w == work {
return e
}
}
}
// toBuyer makes an owner reply to the given thread (a fresh one if tk is nil).
func toBuyer(t *testing.T, e *env, l *listing.Listing, tk *message.ThreadKey, at time.Time, work int) *message.Envelope {
t.Helper()
for {
k := tk
if k == nil {
var err error
if k, err = message.NewThreadKey(); err != nil {
t.Fatal(err)
}
}
p := &message.Plain{Type: message.TypeText, Thread: k.PublicHex(), N: 1, SentAt: at.Unix(), Text: "ok"}
env, err := message.SealToBuyer(e.dev, message.Ref{Author: l.Author, ID: l.ID}, p, at, work)
if err != nil {
t.Fatal(err)
}
if w, _ := env.Work(); w == work {
return env
}
}
}
func (e *env) putMsg(t *testing.T, env *message.Envelope) Outcome {
t.Helper()
o, err := e.s.PutMessage(ctx, region, env)
if err != nil {
t.Fatalf("PutMessage: %v", err)
}
return o
}
func TestMessagesRoundTrip(t *testing.T) {
e := newMsgEnv(t, Options{})
l := e.listing(t, nil)
e.put(t, l)
tk, _ := message.NewThreadKey()
in := toOwner(t, l, e.now, msgDifficulty)
if e.putMsg(t, in) != Inserted {
t.Fatal("not inserted")
}
if e.putMsg(t, in) != Ignored {
t.Fatal("a duplicate must be a no-op")
}
out := toBuyer(t, e, l, tk, e.now.Add(time.Second), msgDifficulty)
e.putMsg(t, out)
got, err := e.s.OwnerMessages(ctx, l.Author)
if err != nil || len(got) != 1 {
t.Fatalf("OwnerMessages = %d, %v", len(got), err)
}
if h1, _ := got[0].Hash(); h1 != mustHash(t, in) {
t.Fatal("stored envelope differs from what was put")
}
mb, _ := tk.Mailbox()
box, err := e.s.Mailbox(ctx, mb, 0, 10)
if err != nil || len(box) != 1 {
t.Fatalf("Mailbox = %d, %v", len(box), err)
}
if _, err := box[0].OpenAsBuyer(tk); err != nil {
t.Fatalf("a stored reply no longer opens: %v", err)
}
if other, _ := e.s.Mailbox(ctx, strings.Repeat("0", 32), 0, 10); len(other) != 0 {
t.Fatal("another mailbox must be empty")
}
if later, _ := e.s.Mailbox(ctx, mb, out.CreatedAt+1, 10); len(later) != 0 {
t.Fatal("since must exclude older envelopes")
}
all, err := e.s.MessagesSince(ctx, region, MessageCursor{}, 10)
if err != nil || len(all) != 2 {
t.Fatalf("MessagesSince = %d, %v", len(all), err)
}
cur, _ := MessageCursorOf(all[0])
rest, _ := e.s.MessagesSince(ctx, region, cur, 10)
if len(rest) != 1 || mustHash(t, rest[0]) != mustHash(t, all[1]) {
t.Fatal("cursor paging is wrong")
}
if n, _ := e.s.MessageCount(ctx); n != 2 {
t.Fatalf("count = %d", n)
}
if other, _ := e.s.MessagesSince(ctx, "u1y", MessageCursor{}, 10); len(other) != 0 {
t.Fatal("another region must be empty")
}
}
func mustHash(t *testing.T, e *message.Envelope) string {
t.Helper()
h, err := e.Hash()
if err != nil {
t.Fatal(err)
}
return h
}
func TestOwnerMessagesNeedALiveListing(t *testing.T) {
e := newMsgEnv(t, Options{})
l := e.listing(t, nil)
env := toOwner(t, l, e.now, msgDifficulty)
if _, err := e.s.PutMessage(ctx, region, env); !errors.Is(err, ErrNoListing) {
t.Fatalf("unknown listing: %v, want ErrNoListing", err)
}
e.put(t, l)
if _, err := e.s.PutMessage(ctx, "u1y", env); !errors.Is(err, ErrInvalid) {
t.Fatalf("wrong region: %v, want ErrInvalid", err)
}
e.putMsg(t, env)
// A message sealed to a device that no longer signs for the listing.
old := toOwner(t, l, e.now.Add(time.Second), msgDifficulty)
e.dev = newDevice(t, e.root) // the owner recovered onto a new device
re := e.listing(t, func(x *listing.Listing) { x.ID = l.ID; x.Seq = 2 })
e.put(t, re)
if _, err := e.s.PutMessage(ctx, region, old); !errors.Is(err, ErrNoListing) {
t.Fatalf("stale device: %v, want ErrNoListing", err)
}
// Deleted listing.
ts := e.listing(t, func(x *listing.Listing) {
*x = listing.Listing{Version: listing.Version, ID: l.ID, Seq: 3, CreatedAt: e.now.Unix(),
ExpiresAt: e.now.Add(24 * time.Hour).Unix(), Tombstone: true, Geohash: "u1xjhx"}
})
e.put(t, ts)
fresh := toOwner(t, re, e.now.Add(2*time.Second), msgDifficulty)
if _, err := e.s.PutMessage(ctx, region, fresh); !errors.Is(err, ErrNoListing) {
t.Fatalf("deleted listing: %v, want ErrNoListing", err)
}
}
func TestBuyerRepliesDoNotNeedTheListing(t *testing.T) {
e := newMsgEnv(t, Options{})
l := e.listing(t, nil) // never stored: the owner may have deleted it meanwhile
e.putMsg(t, toBuyer(t, e, l, nil, e.now, msgDifficulty))
// If the listing is known, the region must still match.
e.put(t, l)
if _, err := e.s.PutMessage(ctx, "u1y", toBuyer(t, e, l, nil, e.now, msgDifficulty)); !errors.Is(err, ErrInvalid) {
t.Fatalf("wrong region for a known listing: %v", err)
}
}
func TestInvalidEnvelopesAreRejected(t *testing.T) {
e := newMsgEnv(t, Options{})
l := e.listing(t, nil)
e.put(t, l)
weak := toOwner(t, l, e.now, msgDifficulty)
strict := newMsgEnv(t, Options{})
strict.s.msgDifficulty = 30
if _, err := strict.s.PutMessage(ctx, region, weak); !errors.Is(err, ErrInvalid) {
t.Fatalf("weak proof-of-work: %v", err)
}
if _, err := e.s.PutMessage(ctx, "nope", weak); !errors.Is(err, ErrInvalid) {
t.Fatalf("bad region: %v", err)
}
// Clock failures stay recognisable so the p2p layer can ignore them.
late := newMsgEnv(t, Options{})
late.now = t0.Add(20 * 24 * time.Hour)
_, err := late.s.PutMessage(ctx, region, weak)
if !errors.Is(err, ErrInvalid) || !errors.Is(err, listing.ErrTimeWindow) {
t.Fatalf("expired: %v, want ErrInvalid wrapping ErrTimeWindow", err)
}
}
func TestMessagesExpire(t *testing.T) {
e := newMsgEnv(t, Options{})
l := e.listing(t, nil)
e.put(t, l)
tk, _ := message.NewThreadKey()
e.putMsg(t, toOwner(t, l, e.now, msgDifficulty))
e.putMsg(t, toBuyer(t, e, l, tk, e.now, msgDifficulty))
e.now = e.now.Add(message.MaxLifetime + time.Minute)
mb, _ := tk.Mailbox()
if box, _ := e.s.Mailbox(ctx, mb, 0, 10); len(box) != 0 {
t.Fatal("expired reply still served")
}
if got, _ := e.s.OwnerMessages(ctx, l.Author); len(got) != 0 {
t.Fatal("expired message still served")
}
if n, _ := e.s.MessageCount(ctx); n != 0 {
t.Fatalf("count = %d", n)
}
if removed, err := e.s.Expire(ctx); err != nil || removed < 2 {
t.Fatalf("Expire removed %d, %v", removed, err)
}
}
func TestQueueEvictsTheLeastWorkOldestFirst(t *testing.T) {
e := newMsgEnv(t, Options{OwnerQueue: 3})
l := e.listing(t, nil)
e.put(t, l)
at := func(i int) time.Time { return e.now.Add(time.Duration(i) * time.Second) }
a := toOwner(t, l, at(1), 4)
b := toOwner(t, l, at(2), 4)
c := toOwner(t, l, at(3), 4)
for _, m := range []*message.Envelope{a, b, c} {
e.putMsg(t, m)
}
// More work than the least: evicts the oldest of the least-work ones.
d := toOwner(t, l, at(4), 9)
e.putMsg(t, d)
has := func(m *message.Envelope) bool {
all, _ := e.s.OwnerMessages(ctx, l.Author)
for _, x := range all {
if mustHash(t, x) == mustHash(t, m) {
return true
}
}
return false
}
if has(a) || !has(b) || !has(c) || !has(d) {
t.Fatalf("after d: a=%v b=%v c=%v d=%v, want a evicted only", has(a), has(b), has(c), has(d))
}
// Equal work: the newcomer displaces the oldest (spec: oldest first on ties).
f := toOwner(t, l, at(5), 4)
e.putMsg(t, f)
if has(b) || !has(c) || !has(d) || !has(f) {
t.Fatalf("after f: b=%v c=%v d=%v f=%v", has(b), has(c), has(d), has(f))
}
// A queue full of strong envelopes refuses weaker ones and keeps them all.
for i := 6; i < 9; i++ {
e.putMsg(t, toOwner(t, l, at(i), 9))
}
weak := toOwner(t, l, at(10), 4)
if _, err := e.s.PutMessage(ctx, region, weak); !errors.Is(err, ErrQueueFull) {
t.Fatalf("weak newcomer: %v, want ErrQueueFull", err)
}
if all, _ := e.s.OwnerMessages(ctx, l.Author); len(all) != 3 {
t.Fatalf("queue holds %d, want 3", len(all))
}
}
func TestMailboxQueueIsBounded(t *testing.T) {
e := newMsgEnv(t, Options{MailboxQueue: 2})
l := e.listing(t, nil)
tk, _ := message.NewThreadKey()
mb, _ := tk.Mailbox()
at := func(i int) time.Time { return e.now.Add(time.Duration(i) * time.Second) }
e.putMsg(t, toBuyer(t, e, l, tk, at(1), 4))
e.putMsg(t, toBuyer(t, e, l, tk, at(2), 4))
e.putMsg(t, toBuyer(t, e, l, tk, at(3), 9))
box, _ := e.s.Mailbox(ctx, mb, 0, 10)
if len(box) != 2 {
t.Fatalf("mailbox holds %d, want 2", len(box))
}
// Another mailbox is not affected.
e.putMsg(t, toBuyer(t, e, l, nil, at(4), 4))
}
func TestOverallCapIsEnforced(t *testing.T) {
e := newMsgEnv(t, Options{MaxMessages: 2})
l := e.listing(t, nil)
at := func(i int) time.Time { return e.now.Add(time.Duration(i) * time.Second) }
e.putMsg(t, toBuyer(t, e, l, nil, at(1), 4))
e.putMsg(t, toBuyer(t, e, l, nil, at(2), 4))
e.putMsg(t, toBuyer(t, e, l, nil, at(3), 9)) // evicts the oldest weak one
e.putMsg(t, toBuyer(t, e, l, nil, at(4), 9)) // evicts the other weak one
if n, _ := e.s.MessageCount(ctx); n != 2 {
t.Fatalf("count = %d, want 2", n)
}
weak := toBuyer(t, e, l, nil, at(5), 4)
if _, err := e.s.PutMessage(ctx, region, weak); !errors.Is(err, ErrQueueFull) {
t.Fatalf("weak newcomer at the overall cap: %v", err)
}
if n, _ := e.s.MessageCount(ctx); n != 2 {
t.Fatalf("count = %d after a rejection, want 2", n)
}
}
+89 -6
View File
@@ -43,14 +43,27 @@ func (o Outcome) String() string {
}
type Options struct {
Difficulty int // required proof-of-work bits
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
}
type Store struct {
db *sql.DB
difficulty int
clock func() time.Time
db *sql.DB
difficulty int
clock func() time.Time
msgDifficulty int
maxMessages int
ownerQueue int
mailboxQueue int
}
const schema = `
@@ -87,6 +100,56 @@ CREATE TABLE IF NOT EXISTS revocations (
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;
-- 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
@@ -106,10 +169,21 @@ func Open(path string, opt Options) (*Store, error) {
db.Close()
return nil, err
}
s := &Store{db: db, difficulty: opt.Difficulty, clock: opt.Clock}
s := &Store{db: db, difficulty: opt.Difficulty, clock: opt.Clock,
msgDifficulty: opt.MessageDifficulty, maxMessages: opt.MaxMessages,
ownerQueue: opt.OwnerQueue, mailboxQueue: opt.MailboxQueue}
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
}
@@ -433,7 +507,16 @@ func (s *Store) Expire(ctx context.Context) (int64, error) {
return n, err
}
m, _ := res.RowsAffected()
return n + m, nil
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
}
return n + m + k, nil
}
// Count returns the number of live listings.