messaging: the price of writing to a listing rises as its queue fills

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
This commit is contained in:
2026-11-18 20:59:11 +01:00
co-authored by Claude Sonnet 5.5
parent 13c82f8d59
commit 253eb6e75c
12 changed files with 379 additions and 35 deletions
+19 -1
View File
@@ -314,6 +314,20 @@ the browser had the data and cannot be forced to forget it.
ties); a newcomer with less work than everything queued is rejected. So ties); a newcomer with less work than everything queued is rejected. So
filling a queue costs more than the proof-of-work of the messages it filling a queue costs more than the proof-of-work of the messages it
displaces. displaces.
**The price rises as a listing's owner queue fills**, so flooding gets
dearer with every envelope instead of locking honest senders out at a price
they cannot see. An envelope to the owner of a listing needs the node's
message difficulty while fewer than half of the queue is used, one bit more
from half full, two bits more from three quarters, and once the queue is
full one bit more than the weakest envelope waiting (so it displaces
something). It is a local policy, like the queue itself: a node refuses
(ignoring, without penalty) what is too cheap *for it*, and the sender's
gateway tells the browser the price (`GET /api/v1/messages/required`, and a
429 with `required_bits`). A browser mines up to 24 bits (about half a
minute); a listing that asks for more is being flooded, and the sender is
told to come back later. An attacker must out-work 200 envelopes to keep one
honest sender out, so the cost to hold a listing's inbox is about 200 times
what a sender pays to get in.
Invalid envelopes are rejected and the relaying peer loses score. Unknown Invalid envelopes are rejected and the relaying peer loses score. Unknown
listing, wrong `rcpt` after a device change, and clock failures are **ignored listing, wrong `rcpt` after a device change, and clock failures are **ignored
@@ -370,7 +384,11 @@ text rules below are enforced by endpoints.
`PUT|GET|DELETE /api/v1/listings/{id}/address` (the private address). A `PUT|GET|DELETE /api/v1/listings/{id}/address` (the private address). A
reply body is `{type: "text"|"grant", text, address, phone, email, note, reply body is `{type: "text"|"grant", text, address, phone, email, note,
valid_days}`; a grant without `address` uses the stored one. valid_days}`; a grant without `address` uses the stored one.
- `GET /api/v1/status` reports `message_difficulty`, which the browser mines to. - `GET /api/v1/messages/required?author=<64 hex>&id=<32 hex>` answers
`{"bits": n}`, the proof-of-work a message to that listing needs right now (see
relay validation, step 6). `GET /api/v1/status` reports `message_difficulty`,
the price of a quiet queue; a browser takes the larger of the two and asks
again if a 429 names a higher price.
- **Flags:** `--message-difficulty` (default 14) and `--max-new-threads`. - **Flags:** `--message-difficulty` (default 14) and `--max-new-threads`.
- A gateway sees the buyer's IP address and mailbox tag. Buyers can use any - A gateway sees the buyer's IP address and mailbox tag. Buyers can use any
gateway; nothing else about the conversation is exposed. gateway; nothing else about the conversation is exposed.
+1
View File
@@ -105,6 +105,7 @@ func New(cfg Config) http.Handler {
// Messaging: public relay endpoints for buyers' browsers... // Messaging: public relay endpoints for buyers' browsers...
mux.HandleFunc("POST /api/v1/messages", s.postMessage) mux.HandleFunc("POST /api/v1/messages", s.postMessage)
mux.HandleFunc("GET /api/v1/messages", s.getMailbox) mux.HandleFunc("GET /api/v1/messages", s.getMailbox)
mux.HandleFunc("GET /api/v1/messages/required", s.getRequiredWork)
// ...and the owner's inbox and private address, behind the admin token. // ...and the owner's inbox and private address, behind the admin token.
if cfg.Inbox != nil { if cfg.Inbox != nil {
mux.HandleFunc("GET /api/v1/mine", s.admin(s.mine)) mux.HandleFunc("GET /api/v1/mine", s.admin(s.mine))
+29
View File
@@ -68,6 +68,15 @@ func (s *server) postMessage(w http.ResponseWriter, r *http.Request) {
case errors.Is(err, store.ErrNoListing): case errors.Is(err, store.ErrNoListing):
fail(w, http.StatusNotFound, "that listing is not live here (anymore), or its owner changed device") fail(w, http.StatusNotFound, "that listing is not live here (anymore), or its owner changed device")
case errors.Is(err, store.ErrQueueFull): case errors.Is(err, store.ErrQueueFull):
var we *store.WorkError
if errors.As(err, &we) {
// The price of this listing's queue has risen: say what it is now.
writeJSON(w, http.StatusTooManyRequests, map[string]any{
"error": "this listing is receiving many messages; it now needs more proof-of-work",
"required_bits": we.Required,
})
return
}
fail(w, http.StatusTooManyRequests, "the queue for this listing is full of messages with more proof-of-work; mine more and retry") fail(w, http.StatusTooManyRequests, "the queue for this listing is full of messages with more proof-of-work; mine more and retry")
default: default:
fail(w, http.StatusInternalServerError, "internal error") fail(w, http.StatusInternalServerError, "internal error")
@@ -78,6 +87,26 @@ func (s *server) postMessage(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusAccepted, map[string]string{"hash": h}) writeJSON(w, http.StatusAccepted, map[string]string{"hash": h})
} }
// getRequiredWork tells a buyer's browser how much proof-of-work a message to
// a listing needs right now. The price rises while the listing's queue fills,
// so the browser asks before it mines.
func (s *server) getRequiredWork(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
author, id := q.Get("author"), q.Get("id")
if len(author) != 64 || !isLowerHex(author) || len(id) != 32 || !isLowerHex(id) {
fail(w, http.StatusBadRequest, "author must be 64 and id 32 hex characters")
return
}
bits, err := s.Store.RequiredWork(r.Context(), message.Ref{Author: author, ID: id})
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
noStore(w)
writeJSON(w, http.StatusOK, map[string]int{"bits": bits})
}
func (s *server) getMailbox(w http.ResponseWriter, r *http.Request) { func (s *server) getMailbox(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query() q := r.URL.Query()
tag := q.Get("mailbox") tag := q.Get("mailbox")
+47
View File
@@ -429,6 +429,53 @@ func TestStatusReportsMessageDifficulty(t *testing.T) {
} }
} }
func TestTheMessagePriceRisesWithTheQueueAndBuyersCanAskForIt(t *testing.T) {
f := newFixture(t, token)
l := f.publish(t)
required := func() int {
code, body := f.do(t, "GET", "/api/v1/messages/required?author="+l.Author+"&id="+l.ID, "", false)
var r struct {
Bits int `json:"bits"`
}
if code != 200 || json.Unmarshal(body, &r) != nil {
t.Fatalf("required: %d %s", code, body)
}
return r.Bits
}
if got := required(); got != msgDifficulty {
t.Fatalf("a quiet listing asks %d bits, want %d", got, msgDifficulty)
}
if code, _ := f.do(t, "GET", "/api/v1/messages/required?author=zz&id=1", "", false); code != 400 {
t.Fatalf("bad parameters: %d", code)
}
// Half of the 200-envelope queue costs one bit more.
for i := 0; i < 100; i++ {
if _, err := f.s.PutMessage(t.Context(), listing.Region(l.Geohash), buyerHello(t, l, newThread(t), "Hallo")); err != nil {
t.Fatal(err)
}
}
if got := required(); got != msgDifficulty+1 {
t.Fatalf("a half-full queue asks %d bits, want %d", got, msgDifficulty+1)
}
// A message at the old price is refused, and the answer names the new one.
var weak *message.Envelope
for {
weak = buyerHello(t, l, newThread(t), "Hallo")
if w, _ := weak.Work(); w == msgDifficulty {
break
}
}
code, body := f.send(t, weak)
var refusal struct {
Required int `json:"required_bits"`
}
if code != 429 || json.Unmarshal(body, &refusal) != nil || refusal.Required != msgDifficulty+1 {
t.Fatalf("a message at the old price: %d %s", code, body)
}
}
func TestBlockingAConversationOverTheAPI(t *testing.T) { func TestBlockingAConversationOverTheAPI(t *testing.T) {
f := newFixture(t, token) f := newFixture(t, token)
l := f.publish(t) l := f.publish(t)
+56
View File
@@ -31,6 +31,51 @@ var (
ErrQueueFull = errors.New("store: message queue full") 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. // 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. // Conflict-free: an envelope's identity is its hash, so duplicates are no-ops.
// //
@@ -153,6 +198,17 @@ func (s *Store) route(ctx context.Context, q rowQuerier, now int64, region strin
if e.To == message.ToOwner && (!known || tombstone != 0 || expires <= now || device != e.Rcpt) { if e.To == message.ToOwner && (!known || tombstone != 0 || expires <= now || device != e.Rcpt) {
return ErrNoListing 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 return nil
} }
+56 -7
View File
@@ -249,9 +249,10 @@ func TestQueueEvictsTheLeastWorkOldestFirst(t *testing.T) {
e.put(t, l) e.put(t, l)
at := func(i int) time.Time { return e.now.Add(time.Duration(i) * time.Second) } at := func(i int) time.Time { return e.now.Add(time.Duration(i) * time.Second) }
// Two thirds full already costs a bit more, hence 5 for the third.
a := toOwner(t, l, at(1), 4) a := toOwner(t, l, at(1), 4)
b := toOwner(t, l, at(2), 4) b := toOwner(t, l, at(2), 4)
c := toOwner(t, l, at(3), 4) c := toOwner(t, l, at(3), 5)
for _, m := range []*message.Envelope{a, b, c} { for _, m := range []*message.Envelope{a, b, c} {
e.putMsg(t, m) e.putMsg(t, m)
} }
@@ -272,20 +273,26 @@ func TestQueueEvictsTheLeastWorkOldestFirst(t *testing.T) {
t.Fatalf("after d: a=%v b=%v c=%v d=%v, want a evicted only", 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). // A full queue wants one bit more than its weakest envelope; that newcomer
f := toOwner(t, l, at(5), 4) // displaces the oldest of the weakest.
if _, err := e.s.PutMessage(ctx, region, toOwner(t, l, at(5), 4)); !errors.Is(err, ErrQueueFull) {
t.Fatalf("a newcomer only as strong as the weakest: %v, want ErrQueueFull", err)
}
f := toOwner(t, l, at(5), 5)
e.putMsg(t, f) e.putMsg(t, f)
if has(b) || !has(c) || !has(d) || !has(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)) 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. // A queue full of strong envelopes refuses weaker ones and keeps them all.
for i := 6; i < 9; i++ { for i, w := range []int{9, 9, 10} { // each must beat the weakest it displaces
e.putMsg(t, toOwner(t, l, at(i), 9)) e.putMsg(t, toOwner(t, l, at(6+i), w))
} }
weak := toOwner(t, l, at(10), 4) weak := toOwner(t, l, at(10), 4)
if _, err := e.s.PutMessage(ctx, region, weak); !errors.Is(err, ErrQueueFull) { _, err := e.s.PutMessage(ctx, region, weak)
t.Fatalf("weak newcomer: %v, want ErrQueueFull", err) var we *WorkError
if !errors.Is(err, ErrQueueFull) || !errors.As(err, &we) || we.Required != 10 {
t.Fatalf("weak newcomer: %v, want a WorkError asking for 10 bits", err)
} }
if all, _ := e.s.OwnerMessages(ctx, l.Author); len(all) != 3 { if all, _ := e.s.OwnerMessages(ctx, l.Author); len(all) != 3 {
t.Fatalf("queue holds %d, want 3", len(all)) t.Fatalf("queue holds %d, want 3", len(all))
@@ -330,3 +337,45 @@ func TestOverallCapIsEnforced(t *testing.T) {
t.Fatalf("count = %d after a rejection, want 2", n) t.Fatalf("count = %d after a rejection, want 2", n)
} }
} }
func TestRequiredWorkRisesAsTheQueueFills(t *testing.T) {
e := newMsgEnv(t, Options{OwnerQueue: 8})
l := e.listing(t, nil)
e.put(t, l)
ref := message.Ref{Author: l.Author, ID: l.ID}
need := func() int {
n, err := e.s.RequiredWork(ctx, ref)
if err != nil {
t.Fatal(err)
}
return n
}
at := func(i int) time.Time { return e.now.Add(time.Duration(i) * time.Second) }
// A quiet queue costs the node's difficulty (4 in these tests).
want := []int{4, 4, 4, 4, 5, 5, 6, 6} // by the number of envelopes waiting, 0..7
work := 4
for i := 0; i < 8; i++ {
if got := need(); got != want[i] {
t.Fatalf("with %d waiting the price is %d bits, want %d", i, got, want[i])
}
if i == 7 {
work = 9
}
w := want[i]
if i == 7 {
w = work
}
e.putMsg(t, toOwner(t, l, at(i+1), w))
}
// Full: one bit more than the weakest waiting.
least := 4
if got := need(); got != least+1 {
t.Fatalf("a full queue asks %d bits, want %d", got, least+1)
}
// What the price says is accepted, one bit less is not.
if _, err := e.s.PutMessage(ctx, region, toOwner(t, l, at(20), need()-1)); !errors.Is(err, ErrQueueFull) {
t.Fatalf("one bit short: %v", err)
}
e.putMsg(t, toOwner(t, l, at(21), need()))
}
+42 -12
View File
@@ -45,12 +45,25 @@ async function getListing(author, id) {
var HttpError = class extends Error { var HttpError = class extends Error {
status; status;
detail; detail;
constructor(status, detail) { /** For a refused message: the proof-of-work, in bits, the listing's queue asks right now. */
requiredBits;
constructor(status, detail, requiredBits) {
super(`${status} ${detail}`); super(`${status} ${detail}`);
this.status = status; this.status = status;
this.detail = detail; this.detail = detail;
this.requiredBits = requiredBits;
} }
}; };
async function getRequiredBits(author, id) {
try {
const res = await fetch(`/api/v1/messages/required?author=${author}&id=${id}`);
if (!res.ok) return null;
const { bits } = await res.json();
return typeof bits === "number" && Number.isInteger(bits) && bits > 0 && bits < 256 ? bits : null;
} catch {
return null;
}
}
async function postMessage(envelope) { async function postMessage(envelope) {
const res = await fetch("/api/v1/messages", { const res = await fetch("/api/v1/messages", {
method: "POST", method: "POST",
@@ -60,12 +73,14 @@ async function postMessage(envelope) {
}); });
if (res.ok) return; if (res.ok) return;
let detail = res.statusText; let detail = res.statusText;
let requiredBits;
try { try {
const body = await res.json(); const body = await res.json();
if (typeof body.error === "string") detail = body.error; if (typeof body.error === "string") detail = body.error;
if (typeof body.required_bits === "number" && Number.isInteger(body.required_bits)) requiredBits = body.required_bits;
} catch { } catch {
} }
throw new HttpError(res.status, detail); throw new HttpError(res.status, detail, requiredBits);
} }
async function pollMailbox(tag, since) { async function pollMailbox(tag, since) {
const data = await getJSON(`/api/v1/messages?mailbox=${encodeURIComponent(tag)}&since=${since}`); const data = await getJSON(`/api/v1/messages?mailbox=${encodeURIComponent(tag)}&since=${since}`);
@@ -173,6 +188,7 @@ var de = {
"problem.link": "Die erste Nachricht darf keine Links oder Webadressen enthalten (auch kein \u201EHallo.Ich\u201C ohne Leerzeichen nach dem Punkt).", "problem.link": "Die erste Nachricht darf keine Links oder Webadressen enthalten (auch kein \u201EHallo.Ich\u201C ohne Leerzeichen nach dem Punkt).",
"send.404": "Dieser Knoten kennt die Anzeige nicht (mehr), oder der Anbieter hat sein Ger\xE4t gewechselt. Lade die Anzeige neu.", "send.404": "Dieser Knoten kennt die Anzeige nicht (mehr), oder der Anbieter hat sein Ger\xE4t gewechselt. Lade die Anzeige neu.",
"send.429": "Zu viele Nachrichten. Bitte warte einen Moment.", "send.429": "Zu viele Nachrichten. Bitte warte einen Moment.",
"send.busy": "Diese Anzeige bekommt gerade sehr viele Nachrichten. Versuche es sp\xE4ter noch einmal.",
"send.other": "Senden fehlgeschlagen: {detail}", "send.other": "Senden fehlgeschlagen: {detail}",
"send.network": "Der Knoten ist nicht erreichbar.", "send.network": "Der Knoten ist nicht erreichbar.",
"chat.back": "\u2190 Zur Anzeige", "chat.back": "\u2190 Zur Anzeige",
@@ -430,6 +446,7 @@ var en = {
"problem.link": 'The first message must not contain links or web addresses (that includes "Hello.I" without a space after the full stop).', "problem.link": 'The first message must not contain links or web addresses (that includes "Hello.I" without a space after the full stop).',
"send.404": "This node does not know the listing (anymore), or the owner changed device. Reload the listing.", "send.404": "This node does not know the listing (anymore), or the owner changed device. Reload the listing.",
"send.429": "Too many messages. Please wait a moment.", "send.429": "Too many messages. Please wait a moment.",
"send.busy": "This listing is receiving a lot of messages right now. Please try again later.",
"send.other": "Sending failed: {detail}", "send.other": "Sending failed: {detail}",
"send.network": "The node is not reachable.", "send.network": "The node is not reachable.",
"chat.back": "\u2190 Back to the listing", "chat.back": "\u2190 Back to the listing",
@@ -4439,6 +4456,7 @@ function describe(e2) {
if (e2 instanceof InputError) return t(`problem.${e2.problem}`); if (e2 instanceof InputError) return t(`problem.${e2.problem}`);
if (e2 instanceof HttpError) { if (e2 instanceof HttpError) {
if (e2.status === 404) return t("send.404"); if (e2.status === 404) return t("send.404");
if (e2.status === 429 && e2.requiredBits) return t("send.busy");
if (e2.status === 429) return t("send.429"); if (e2.status === 429) return t("send.429");
return t("send.other", { detail: e2.detail }); return t("send.other", { detail: e2.detail });
} }
@@ -4493,19 +4511,31 @@ function composer(opts) {
); );
return form; return form;
} }
var MAX_WORK_BITS = 24;
async function sendTo(c, listing, text, first) { async function sendTo(c, listing, text, first) {
const n = c.messages.filter((m) => m.dir === "out").length + 1; const n = c.messages.filter((m) => m.dir === "out").length + 1;
const now = nowSeconds(); const now = nowSeconds();
const env = await buildToOwner({ let bits = Math.max(difficulty(), await getRequiredBits(listing.author, listing.id) ?? 0);
listing, for (let attempt = 0; ; attempt++) {
threadSecret: fromHex(c.secret), if (bits > MAX_WORK_BITS) throw new HttpError(429, "this listing is receiving too many messages right now", bits);
text, const env = await buildToOwner({
n, listing,
now, threadSecret: fromHex(c.secret),
difficulty: difficulty(), text,
first n,
}); now,
await postMessage(env); difficulty: bits,
first
});
try {
await postMessage(env);
break;
} catch (e2) {
const asked = e2 instanceof HttpError && e2.status === 429 ? e2.requiredBits : void 0;
if (asked === void 0 || asked <= bits || attempt >= 2) throw e2;
bits = asked;
}
}
c.messages.push({ dir: "out", n, sent_at: now, t: "text", text }); c.messages.push({ dir: "out", n, sent_at: now, t: "text", text });
c.updated = now; c.updated = now;
saveConversation(c); saveConversation(c);
+24 -3
View File
@@ -42,10 +42,29 @@ export async function getListing(author: string, id: string): Promise<unknown |
export class HttpError extends Error { export class HttpError extends Error {
readonly status: number; readonly status: number;
readonly detail: string; readonly detail: string;
constructor(status: number, detail: string) { /** For a refused message: the proof-of-work, in bits, the listing's queue asks right now. */
readonly requiredBits?: number;
constructor(status: number, detail: string, requiredBits?: number) {
super(`${status} ${detail}`); super(`${status} ${detail}`);
this.status = status; this.status = status;
this.detail = detail; this.detail = detail;
this.requiredBits = requiredBits;
}
}
/**
* The proof-of-work a message to this listing needs right now. It rises while
* the listing's queue fills, so a sender asks before mining. Null if the node
* cannot say (an older node): the caller then uses the node's usual difficulty.
*/
export async function getRequiredBits(author: string, id: string): Promise<number | null> {
try {
const res = await fetch(`/api/v1/messages/required?author=${author}&id=${id}`);
if (!res.ok) return null;
const { bits } = (await res.json()) as { bits?: unknown };
return typeof bits === "number" && Number.isInteger(bits) && bits > 0 && bits < 256 ? bits : null;
} catch {
return null;
} }
} }
@@ -58,13 +77,15 @@ export async function postMessage(envelope: Envelope): Promise<void> {
}); });
if (res.ok) return; if (res.ok) return;
let detail = res.statusText; let detail = res.statusText;
let requiredBits: number | undefined;
try { try {
const body = (await res.json()) as { error?: unknown }; const body = (await res.json()) as { error?: unknown; required_bits?: unknown };
if (typeof body.error === "string") detail = body.error; if (typeof body.error === "string") detail = body.error;
if (typeof body.required_bits === "number" && Number.isInteger(body.required_bits)) requiredBits = body.required_bits;
} catch { } catch {
// keep the status text // keep the status text
} }
throw new HttpError(res.status, detail); throw new HttpError(res.status, detail, requiredBits);
} }
/** Envelopes in a mailbox created at or after `since` (unix seconds). Unverified. */ /** Envelopes in a mailbox created at or after `since` (unix seconds). Unverified. */
+32 -11
View File
@@ -2,7 +2,7 @@
// and the list of conversations. Everything from the network is shown as text // and the list of conversations. Everything from the network is shown as text
// only, and owner messages only after message.ts verified them. // only, and owner messages only after message.ts verified them.
import { HttpError, getListing, pollMailbox, postMessage } from "./api.ts"; import { HttpError, getListing, getRequiredBits, pollMailbox, postMessage } from "./api.ts";
import { append, clear, h, sendOnCtrlEnter } from "./dom.ts"; import { append, clear, h, sendOnCtrlEnter } from "./dom.ts";
import { keepFresh } from "./fresh.ts"; import { keepFresh } from "./fresh.ts";
import { date } from "./format.ts"; import { date } from "./format.ts";
@@ -46,6 +46,7 @@ function describe(e: unknown): string {
if (e instanceof InputError) return t(`problem.${e.problem}` as Key); if (e instanceof InputError) return t(`problem.${e.problem}` as Key);
if (e instanceof HttpError) { if (e instanceof HttpError) {
if (e.status === 404) return t("send.404"); if (e.status === 404) return t("send.404");
if (e.status === 429 && e.requiredBits) return t("send.busy");
if (e.status === 429) return t("send.429"); if (e.status === 429) return t("send.429");
return t("send.other", { detail: e.detail }); return t("send.other", { detail: e.detail });
} }
@@ -113,20 +114,40 @@ function composer(opts: {
return form; return form;
} }
/**
* The most proof-of-work a browser mines for one message: 2^24 hashes, about
* half a minute. A listing whose queue asks for more is being flooded, and the
* sender is told to try again later rather than left waiting.
*/
export const MAX_WORK_BITS = 24;
/** Sends the next message of a conversation and records it. */ /** Sends the next message of a conversation and records it. */
async function sendTo(c: Conversation, listing: Listing, text: string, first: boolean): Promise<void> { async function sendTo(c: Conversation, listing: Listing, text: string, first: boolean): Promise<void> {
const n = c.messages.filter((m) => m.dir === "out").length + 1; const n = c.messages.filter((m) => m.dir === "out").length + 1;
const now = nowSeconds(); const now = nowSeconds();
const env = await buildToOwner({ // The price rises as a listing's queue fills: ask first, and if it rose while
listing, // mining (someone else sent a message) mine again at the new price.
threadSecret: fromHex(c.secret), let bits = Math.max(difficulty(), (await getRequiredBits(listing.author, listing.id)) ?? 0);
text, for (let attempt = 0; ; attempt++) {
n, if (bits > MAX_WORK_BITS) throw new HttpError(429, "this listing is receiving too many messages right now", bits);
now, const env = await buildToOwner({
difficulty: difficulty(), listing,
first, threadSecret: fromHex(c.secret),
}); text,
await postMessage(env); n,
now,
difficulty: bits,
first,
});
try {
await postMessage(env);
break;
} catch (e) {
const asked = e instanceof HttpError && e.status === 429 ? e.requiredBits : undefined;
if (asked === undefined || asked <= bits || attempt >= 2) throw e;
bits = asked;
}
}
c.messages.push({ dir: "out", n, sent_at: now, t: "text", text }); c.messages.push({ dir: "out", n, sent_at: now, t: "text", text });
c.updated = now; c.updated = now;
saveConversation(c); saveConversation(c);
+2
View File
@@ -71,6 +71,7 @@ const de = {
"send.404": "send.404":
"Dieser Knoten kennt die Anzeige nicht (mehr), oder der Anbieter hat sein Gerät gewechselt. Lade die Anzeige neu.", "Dieser Knoten kennt die Anzeige nicht (mehr), oder der Anbieter hat sein Gerät gewechselt. Lade die Anzeige neu.",
"send.429": "Zu viele Nachrichten. Bitte warte einen Moment.", "send.429": "Zu viele Nachrichten. Bitte warte einen Moment.",
"send.busy": "Diese Anzeige bekommt gerade sehr viele Nachrichten. Versuche es später noch einmal.",
"send.other": "Senden fehlgeschlagen: {detail}", "send.other": "Senden fehlgeschlagen: {detail}",
"send.network": "Der Knoten ist nicht erreichbar.", "send.network": "Der Knoten ist nicht erreichbar.",
"chat.back": "← Zur Anzeige", "chat.back": "← Zur Anzeige",
@@ -353,6 +354,7 @@ const en: Record<keyof typeof de, string> = {
"send.404": "send.404":
"This node does not know the listing (anymore), or the owner changed device. Reload the listing.", "This node does not know the listing (anymore), or the owner changed device. Reload the listing.",
"send.429": "Too many messages. Please wait a moment.", "send.429": "Too many messages. Please wait a moment.",
"send.busy": "This listing is receiving a lot of messages right now. Please try again later.",
"send.other": "Sending failed: {detail}", "send.other": "Sending failed: {detail}",
"send.network": "The node is not reachable.", "send.network": "The node is not reachable.",
"chat.back": "← Back to the listing", "chat.back": "← Back to the listing",
+59 -1
View File
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
import { after, before, test } from "node:test"; import { after, before, test } from "node:test";
import type { Envelope } from "../src/message.ts"; import type { Envelope } from "../src/message.ts";
import { mailbox } from "../src/message.ts"; import { envelopeHash, mailbox } from "../src/message.ts";
import { NOW, newParty, openAsOwner, openPage, sealReply, startGateway, type Gateway, type Page } from "./helpers.ts"; import { NOW, newParty, openAsOwner, openPage, sealReply, startGateway, type Gateway, type Page } from "./helpers.ts";
const owner = newParty({ title: "Altbau in Ottensen" }); const owner = newParty({ title: "Altbau in Ottensen" });
@@ -110,6 +110,64 @@ test("a node that refuses the message is reported and the text is kept", async (
} }
}); });
/** Leading zero bits of an envelope's hash: the work its sender did. */
function workOf(env: Envelope): number {
let bits = 0;
for (const c of envelopeHash(env)) {
const v = parseInt(c, 16);
if (v === 0) {
bits += 4;
continue;
}
return bits + Math.clz32(v) - 28;
}
return bits;
}
test("the page asks what the listing's queue costs and mines to that price", async () => {
gw.requiredBits = 10; // the node's usual price is 6
const before = gw.posted.length;
const p = openPage(gw.url, detail);
try {
await write(p, "Ist die Wohnung noch frei?");
await p.waitFor(() => gw.posted.length === before + 1, "the message to arrive");
assert.ok(workOf(JSON.parse(gw.posted[before]!) as Envelope) >= 10, "it did the work the node asked for");
} finally {
gw.requiredBits = undefined;
p.close();
}
});
test("a price that rose while mining is paid, once more, and the message gets through", async () => {
gw.refuseOnceAskingFor = 9; // the browser mined 6, then somebody else's message raised the price
const before = gw.posted.length;
const p = openPage(gw.url, detail);
try {
await write(p, "Hallo, noch frei?");
await p.waitFor(() => gw.posted.length === before + 1, "the retried message to arrive");
assert.ok(workOf(JSON.parse(gw.posted[before]!) as Envelope) >= 9);
await p.waitFor(() => p.window.location.hash.startsWith("#/c/"), "the conversation view");
} finally {
gw.refuseOnceAskingFor = undefined;
p.close();
}
});
test("a flooded listing is not mined for: the sender is told to come back later", async () => {
gw.requiredBits = 40; // far more than a browser should be asked to do
const before = gw.posted.length;
const p = openPage(gw.url, detail);
try {
await write(p, "Hallo?");
await p.waitFor(() => /receiving a lot of messages/.test(text(p)), "the busy message");
assert.equal(gw.posted.length, before, "nothing was sent");
assert.equal(p.document.querySelector("textarea")!.value, "Hallo?");
} finally {
gw.requiredBits = undefined;
p.close();
}
});
test("verified replies and grants are shown; forged and expired ones are not", async () => { test("verified replies and grants are shown; forged and expired ones are not", async () => {
const secret = "5".repeat(64); const secret = "5".repeat(64);
// The thread public key follows from the secret; compute it with the same code the page uses. // The thread public key follows from the secret; compute it with the same code the page uses.
+12
View File
@@ -176,6 +176,10 @@ export interface Gateway {
mailboxes: Map<string, unknown[]>; mailboxes: Map<string, unknown[]>;
/** Make POST /api/v1/messages answer with this status and error. */ /** Make POST /api/v1/messages answer with this status and error. */
postFails?: { status: number; error: string }; postFails?: { status: number; error: string };
/** What GET /api/v1/messages/required answers (bits); unset, the route does not exist (an older node). */
requiredBits?: number;
/** Refuse the next POST once with 429, asking for this many bits of proof-of-work. */
refuseOnceAskingFor?: number;
/** Plays the node's owner endpoints (/mine, /inbox, .../address); unset, they answer 404. */ /** Plays the node's owner endpoints (/mine, /inbox, .../address); unset, they answer 404. */
owner?: (req: { owner?: (req: {
method: string; method: string;
@@ -235,12 +239,20 @@ export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
}); });
return; return;
} }
if (url.pathname === "/api/v1/messages/required" && gateway.requiredBits !== undefined) {
return json(200, { bits: gateway.requiredBits });
}
if (url.pathname === "/api/v1/messages") { if (url.pathname === "/api/v1/messages") {
if (req.method === "POST") { if (req.method === "POST") {
let body = ""; let body = "";
req.on("data", (c) => (body += c)); req.on("data", (c) => (body += c));
req.on("end", () => { req.on("end", () => {
if (gateway.postFails) return json(gateway.postFails.status, { error: gateway.postFails.error }); if (gateway.postFails) return json(gateway.postFails.status, { error: gateway.postFails.error });
if (gateway.refuseOnceAskingFor !== undefined) {
const bits = gateway.refuseOnceAskingFor;
gateway.refuseOnceAskingFor = undefined;
return json(429, { error: "needs more work", required_bits: bits });
}
posted.push(body); posted.push(body);
json(202, { hash: "x" }); json(202, { hash: "x" });
}); });