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
+42 -12
View File
@@ -45,12 +45,25 @@ async function getListing(author, id) {
var HttpError = class extends Error {
status;
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}`);
this.status = status;
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) {
const res = await fetch("/api/v1/messages", {
method: "POST",
@@ -60,12 +73,14 @@ async function postMessage(envelope) {
});
if (res.ok) return;
let detail = res.statusText;
let requiredBits;
try {
const body = await res.json();
if (typeof body.error === "string") detail = body.error;
if (typeof body.required_bits === "number" && Number.isInteger(body.required_bits)) requiredBits = body.required_bits;
} catch {
}
throw new HttpError(res.status, detail);
throw new HttpError(res.status, detail, requiredBits);
}
async function pollMailbox(tag, 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).",
"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.busy": "Diese Anzeige bekommt gerade sehr viele Nachrichten. Versuche es sp\xE4ter noch einmal.",
"send.other": "Senden fehlgeschlagen: {detail}",
"send.network": "Der Knoten ist nicht erreichbar.",
"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).',
"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.busy": "This listing is receiving a lot of messages right now. Please try again later.",
"send.other": "Sending failed: {detail}",
"send.network": "The node is not reachable.",
"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 HttpError) {
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");
return t("send.other", { detail: e2.detail });
}
@@ -4493,19 +4511,31 @@ function composer(opts) {
);
return form;
}
var MAX_WORK_BITS = 24;
async function sendTo(c, listing, text, first) {
const n = c.messages.filter((m) => m.dir === "out").length + 1;
const now = nowSeconds();
const env = await buildToOwner({
listing,
threadSecret: fromHex(c.secret),
text,
n,
now,
difficulty: difficulty(),
first
});
await postMessage(env);
let bits = Math.max(difficulty(), await getRequiredBits(listing.author, listing.id) ?? 0);
for (let attempt = 0; ; attempt++) {
if (bits > MAX_WORK_BITS) throw new HttpError(429, "this listing is receiving too many messages right now", bits);
const env = await buildToOwner({
listing,
threadSecret: fromHex(c.secret),
text,
n,
now,
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.updated = now;
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 {
readonly status: number;
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}`);
this.status = status;
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;
let detail = res.statusText;
let requiredBits: number | undefined;
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.required_bits === "number" && Number.isInteger(body.required_bits)) requiredBits = body.required_bits;
} catch {
// 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. */
+32 -11
View File
@@ -2,7 +2,7 @@
// and the list of conversations. Everything from the network is shown as text
// 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 { keepFresh } from "./fresh.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 HttpError) {
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");
return t("send.other", { detail: e.detail });
}
@@ -113,20 +114,40 @@ function composer(opts: {
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. */
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 now = nowSeconds();
const env = await buildToOwner({
listing,
threadSecret: fromHex(c.secret),
text,
n,
now,
difficulty: difficulty(),
first,
});
await postMessage(env);
// The price rises as a listing's queue fills: ask first, and if it rose while
// mining (someone else sent a message) mine again at the new price.
let bits = Math.max(difficulty(), (await getRequiredBits(listing.author, listing.id)) ?? 0);
for (let attempt = 0; ; attempt++) {
if (bits > MAX_WORK_BITS) throw new HttpError(429, "this listing is receiving too many messages right now", bits);
const env = await buildToOwner({
listing,
threadSecret: fromHex(c.secret),
text,
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.updated = now;
saveConversation(c);
+2
View File
@@ -71,6 +71,7 @@ const de = {
"send.404":
"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.busy": "Diese Anzeige bekommt gerade sehr viele Nachrichten. Versuche es später noch einmal.",
"send.other": "Senden fehlgeschlagen: {detail}",
"send.network": "Der Knoten ist nicht erreichbar.",
"chat.back": "← Zur Anzeige",
@@ -353,6 +354,7 @@ const en: Record<keyof typeof de, string> = {
"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.busy": "This listing is receiving a lot of messages right now. Please try again later.",
"send.other": "Sending failed: {detail}",
"send.network": "The node is not reachable.",
"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 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";
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 () => {
const secret = "5".repeat(64);
// 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[]>;
/** Make POST /api/v1/messages answer with this status and error. */
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. */
owner?: (req: {
method: string;
@@ -235,12 +239,20 @@ export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
});
return;
}
if (url.pathname === "/api/v1/messages/required" && gateway.requiredBits !== undefined) {
return json(200, { bits: gateway.requiredBits });
}
if (url.pathname === "/api/v1/messages") {
if (req.method === "POST") {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => {
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);
json(202, { hash: "x" });
});