Flooding a listing's inbox now gets dearer with every envelope. Relays ask more proof-of-work from half full on, the node tells browsers the current price, and the browser mines to it (or says the listing is too busy). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
341 lines
11 KiB
Go
341 lines
11 KiB
Go
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")
|
|
)
|
|
|
|
// WorkError means an owner-bound envelope did not carry enough proof-of-work
|
|
// for the queue it is going into right now. It is not misbehaviour: the price
|
|
// rises as a listing's queue fills, so the sender just has to mine more.
|
|
// errors.Is(err, ErrQueueFull) is true for it.
|
|
type WorkError struct{ Required int }
|
|
|
|
func (e *WorkError) Error() string {
|
|
return fmt.Sprintf("store: this listing's queue needs %d bits of proof-of-work right now", e.Required)
|
|
}
|
|
func (e *WorkError) Is(target error) bool { return target == ErrQueueFull }
|
|
|
|
// RequiredWork is the proof-of-work, in bits, an envelope to the owner of ref
|
|
// needs right now. It is the node's message difficulty while the queue is
|
|
// quiet and rises with it: one bit more from half full, two from three
|
|
// quarters. Once the queue is full it is one bit more than the weakest
|
|
// envelope waiting, since a newcomer must beat what it would displace.
|
|
// Flooding a listing therefore costs more with every envelope, instead of
|
|
// locking honest senders out at a price they cannot see.
|
|
func (s *Store) RequiredWork(ctx context.Context, ref message.Ref) (int, error) {
|
|
return s.requiredWork(ctx, s.db, ref)
|
|
}
|
|
|
|
func (s *Store) requiredWork(ctx context.Context, q rowQuerier, ref message.Ref) (int, error) {
|
|
var n, least int
|
|
err := q.QueryRowContext(ctx, `
|
|
SELECT COUNT(*), COALESCE(MIN(work), 0) FROM messages
|
|
WHERE to_dir = 'owner' AND author = ? AND listing_id = ? AND expires_at > ?`,
|
|
ref.Author, ref.ID, s.clock().Unix()).Scan(&n, &least)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
need := s.msgDifficulty
|
|
switch {
|
|
case n >= s.ownerQueue:
|
|
if least+1 > need {
|
|
need = least + 1
|
|
}
|
|
case 4*n >= 3*s.ownerQueue:
|
|
need += 2
|
|
case 2*n >= s.ownerQueue:
|
|
need++
|
|
}
|
|
return need, nil
|
|
}
|
|
|
|
// 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
|
|
}
|
|
if e.To == message.ToOwner {
|
|
need, err := s.requiredWork(ctx, q, e.Listing)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if work, err := e.Work(); err != nil {
|
|
return err
|
|
} else if work < need {
|
|
return &WorkError{Required: need}
|
|
}
|
|
}
|
|
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()
|
|
}
|