Files
allmende/docs/PROTOCOL.md
T

825 lines
50 KiB
Markdown

# Protocol (draft v1)
A distributed, free marketplace for buying/selling and renting. Listing requires
running a node; searching is browser-only through any node's HTTP gateway.
## Architecture
- **Nodes** (Go, single binary): libp2p between nodes, HTTP gateway + web UI +
search API on every node.
- **Browsers** never join the P2P network. They fetch from any gateway and
**verify signatures themselves**, so a gateway cannot forge listings.
- **Sharding**: a listing carries a precision-6 `geohash` (~1 km) and is gossiped
on the topic of its precision-3 *region* (~150 km cell),
`/allmende/1/listings/<region>`. Nodes subscribe to the regions they care
about, replicate them, and index them locally. Fine-grained filtering
(precision, kind, category, price) happens in local search.
- **Discovery**: a DNS-based bootstrap list, remembered peers, a Kademlia DHT per
region and mDNS on the local network (see "Finding peers"); NAT traversal
through hole punching and relaying bootstrap nodes.
- **License**: AGPL-3.0, so modified nodes and gateways must publish their source.
- **Launch scope**: one German state or metro area.
## Identity and keys
Designed so non-technical people can use it and a compromised node can be
revoked. There are no accounts.
- **Identity key** (ed25519): derived from a **12-word recovery phrase** shown
once at first run. Its public key is the `author`. It signs *certificates*
and *revocations* only, and is **deleted from the machine** right after
enrolling the first device.
- **Device key** (ed25519): generated per node, stored on that node. It signs
listings and is also the node's libp2p identity, so the node's peer ID derives
from the `device` field. There is no separate `endpoint` field.
- **Certificate**: `{v, author, device, issued_at, expires_at (<= 1 year), sig}`
signed by the identity key. Travels inside every listing.
- **Revocation**: `{v, author, device, revoked_at, cert_expires_at, pow, sig}`
signed by the identity key, gossiped on `/allmende/1/revocations` (all nodes
subscribe), kept until `cert_expires_at`. A revoked device's signatures are
void: its listings are purged and refused. Two forms:
- **one device** (`device` set): voids exactly that device;
- **all devices** (`device` empty): voids every device of the author whose
certificate was issued *before* `revoked_at`. This is what recovery uses,
because on a new machine the owner has only the phrase and does not know
the old device's key. The replacement device is enrolled at the same
instant (`issued_at == revoked_at`), which stays valid.
- **Recovery** (`allmende recover`): phrase in, all-devices revocation out, fresh
device enrolled, the node's own listings re-signed (`seq + 1`) from the new
device. The same command renews the yearly certificate.
- **Renewal in the browser** (no recovery, no terminal): within the last 30
days of the certificate the owner page says so and asks for the 12 words. The
node derives the identity key for that one request, signs a **new
certificate for the same device key** (so the peer ID stays, nothing is
revoked, no new admin token), saves `device.cert`, signs again (`seq + 1`)
every own listing that would outlive the old certificate (a listing is
refused once its certificate has expired), and forgets the key and the
words. A phrase of another identity is refused. An identity made with
`init --no-phrase` cannot be renewed. A node whose certificate has already
expired does not start, so then only `allmende recover` helps. The phrase
crosses the connection to the node like the admin token does: over anything
but localhost put the node behind TLS.
- **Peer IDs change on recovery** because the device key is the libp2p
identity. Anyone who listed the old peer ID as a bootstrap address has a
stale entry; the recovered node dials out to its own bootstrap peers.
- Lost phrase and lost device: start a new identity. Cheap, because listings
expire within 30 days anyway.
- Signed payloads are domain-separated (`allmende-cert-v1\n`,
`allmende-revocation-v1\n`, `allmende-listing-v1\n` prefixes).
## Listing record
Canonical JSON (RFC 8785), integers only. See `internal/listing`.
| field | notes |
|---|---|
| `v` | format version, currently 1 |
| `id` | 32 hex, stable across versions |
| `author` | identity public key (hex) |
| `device` | signing device's public key (hex) |
| `cert` | certificate binding `device` to `author` |
| `seq` | higher replaces lower for the same `author` + `id` (any device of the author may supersede) |
| `created_at`, `expires_at` | unix seconds; lifetime <= 30 days, owner re-signs to renew |
| `tombstone` | deletion marker: higher `seq`, no content, only routing `geohash` |
| `kind` | `rent` or `sale` |
| `category` | `apartment`, `house`, `room`, `commercial` |
| `geohash` | precision 6 |
| `price` | `{amount_cents, currency: "EUR", period: month|once}` |
| `area_m2`, `rooms_x2` | rooms * 2 (2.5 rooms = 5) |
| `features`, `title`, `description` | bounded text |
| `images` | `{hash, thumb_hash}`, content-addressed, **no location** |
| `delegate` | optional always-on host's peer ID, chosen by the owner |
| `pow` | nonce; sha256 of the unsigned canonical bytes has at least the network's *difficulty* leading zero bits (default **24**, `--difficulty`) |
| `sig` | device signature over the unsigned canonical bytes (with context prefix) |
There is **no address, name, phone or email** in the record.
## Personal data (GDPR)
Only non-personal data is replicated. Exact address and contact details are
released by the owner as a signed `grant` message inside an end-to-end
encrypted thread (see Messaging). Deletion =
signed tombstone, honored by honest nodes, plus the owner's node ceasing to
serve details.
## Images (illegal-content risk, e.g. CSAM)
- Images are **origin-hosted**: only the owner's node (or a host the owner
explicitly delegates to) stores them. Third parties never replicate or
persistently cache them. Gateways stream without storing.
- Uploads are re-encoded, metadata stripped, size-capped, and checked against
hash lists where access is available.
- Signed abuse reports feed subscribable blocklists.
- **Get a German lawyer's review before any public launch** (§184b StGB).
## Availability
Metadata (~2 KB) replicates regionally, so listings remain searchable while the
owner is offline. Images and contact details need the owner's node or its
delegate. UI shows an "owner offline" badge; listings expire if not re-signed
within 30 days.
## Replication
- **Gossip**: every message is checked by a topic validator *before* it is
relayed: canonical encoding, size, signature chain, proof-of-work, region
match, not revoked. Invalid messages are rejected (the relaying peer loses
score); clock-related failures (expired, future) are ignored without penalty.
Publishers flood to all subscribed peers so a listing published right after
connecting is not lost before the mesh forms.
- **Conflict rules** (identical on every node, so replicas converge): keyed by
`(author, id)`; higher `seq` wins; equal `seq` -> smaller hash wins;
tombstones are stored like any version so old copies cannot resurrect a
deleted listing.
- **Sync** (`/allmende/1/sync`): on every new connection to a peer a node
catches up incrementally. Simultaneous connections to the same peer (e.g.
TCP and QUIC) share one running sync.
1. `digest` (no region) returns a digest `{n, root}` of the peer's
revocations; if it differs from ours, the revocations are pulled (they
are few). Revocations go first so listings of revoked devices are
refused.
2. For each subscribed region, `digest` returns digests of the region's
listings and of its messages. A digest is the record count and a SHA-256
over the sorted identities and versions (`author id hash` per listing,
`hash` per message; tombstones count, expired records do not). Equal
digests: nothing more is sent, which is the usual case.
3. When listing digests differ, `inventory` pages through the peer's
`(author, id, seq, hash)` list (about 100 bytes per listing). The node
keeps the versions it lacks or that beat the one it holds (the conflict
rules above) and asks for them with `fetch` (up to 100 `author/id` keys
per request). Messages work the same way, keyed by hash. Listings are
synced before messages, since owner-bound messages are only accepted for
listings we hold.
A peer that answers `digest` with a reset (a node from before digests
existed) is caught up the original way: kinds `revocations`, `listings` and
`messages`, paged by `(created_at, author, id)` and `(created_at, hash)`
cursors, which servers still answer. Gossip lost *while connected* is only
repaired by the next reconnect, and by anti-entropy: every 10 minutes (a
fifth more or less, so nodes do not ask together) a node runs this sync again
with up to 3 random connected peers that share a region (a matching digest
makes a round nearly free).
- **Peer exchange** (`internal/p2p/peerexchange.go`): while a followed region
has fewer than 8 peers, a node asks its connected peers every 20 s who they
know there (sync request `{"kind":"peers","region":...}`, answered with up to
20 `{"id","addrs"}` lines). A peer answers even if it follows another region:
gossip tells it which topics its own connections subscribe to, so it names
those first (marked `near`) and then other connected peers. The asker dials
the `near` ones, and the others only while it knows nobody in the region, as a
way on (so discovery stays per region); then it asks the new connections, for
up to 3 rounds and 24 dials. Old nodes
do not know the kind and ignore it. The peer cache records which of the
node's regions a peer was seen in, and a restart redials those first.
- **Getting your own listings back** (`internal/p2p/recover.go`): a node that
starts on an empty or old database (lost disk, restore from the phrase) asks
the first 3 peers it syncs with for everything signed by its own author key
(sync request `{"kind":"author","author":<64 hex>}`, paged by id; deletions
included, expired records not). Region sync only brings back the regions the
node follows; this also finds the rest, and it restores the newest `seq` of
each listing, without which an edit after the restore would lose against the
copy the network holds. Only peers that hold the listings can answer, which
means peers that follow the listing's region; a listing that no connected
peer holds cannot be found this way. Listings are public, so any peer may
ask for any author's. Old nodes do not know the kind and ignore it.
- **Reconnection**: bootstrap peers are redialed every 20 s when disconnected.
- **Re-announce**: a running node re-gossips its own live listings and
revocations every 30 minutes, so newcomers hear about them without waiting
for a sync.
## Finding peers
Four sources, tried together; none is required once a node has met the network.
1. **Bootstrap.** A fresh node resolves the built-in name
`/dnsaddr/allmende.stinnesbeck.com` (`p2p.DefaultBootstrap`): libp2p reads the
TXT records of `_dnsaddr.allmende.stinnesbeck.com`, each
`dnsaddr=/ip4/<ip>/tcp/4001/p2p/<peer id>` (also `udp/…/quic-v1` and `ip6`).
The list of bootstrap nodes therefore changes in DNS, without a new release.
`--bootstrap` adds `/p2p/` addresses or other `/dnsaddr/` names;
`--no-default-bootstrap` drops the built-in one. A name is resolved at every
redial; the last good answer is kept if DNS is briefly unreachable, and a
failure is logged once, not every 20 s. A node never dials itself.
2. **Remembered peers.** The node saves the peers it is connected to in
`peers.json` in its data directory (every 5 minutes and on shutdown: at most
100, none older than 30 days, relayed addresses left out) and redials the 10
most recent at the next start. After one successful run it no longer needs
a bootstrap node.
3. **DHT.** A Kademlia DHT with its own protocol prefix (`/allmende/kad/1.0.0`,
so it never mixes with the IPFS DHT). For every region it follows, a node
advertises itself under `allmende/region/<region>` and looks up the others,
connecting to up to 20 until its region topic has 8 peers. Lookups start
within seconds and back off to once a minute. Bootstrap nodes only seed the
routing table. `--no-dht` turns it off.
4. **mDNS** on the local network (`--no-mdns` turns it off).
**Behind a NAT.** Most nodes run behind a home router. Each node asks the router
for a port mapping (UPnP/NAT-PMP), asks other nodes whether it is reachable
(AutoNAT), and when it is not, takes a reservation on a bootstrap node (a
circuit-relay v2 slot) so others can reach it; the two then try a direct
connection by hole punching (DCUtR). Relayed connections are limited by libp2p
(2 minutes, 128 KB) and only carry that hand-over. If hole punching fails, a
node still takes part: it dials out, and gossip reaches it through the nodes it
is connected to.
**Running a bootstrap node.** `allmende run --public --listen
/ip4/0.0.0.0/tcp/4001 --listen /ip4/0.0.0.0/udp/4001/quic-v1` on a machine with
a public address (or forwarded ports). `--public` makes it a DHT server and a
relay for nodes behind NATs, and it may follow no region at all. It prints the
TXT records to publish at `_dnsaddr.<name>`; add one record set per bootstrap
node, so several can coexist. Run at least two, on different networks.
## Messaging
Implemented in `internal/message` (wire format), `internal/inbox` (owner side)
and `web/src/message.ts` (buyer side). Both crypto implementations are tested
against a fixture written by the Go code
(`internal/message/testdata/fixture.json`, refresh with
`UPDATE_FIXTURES=1 go test ./internal/message -run TestGoldenFixture`).
A browser-only buyer contacts a listing's owner, and the owner can answer and
release the exact address. Messages are **end-to-end encrypted**, short,
text-only and **anonymous towards the network**: relays see that *someone*
wrote about listing X, and when, not who or what.
### Model
- A **thread** is one buyer talking to one listing. The buyer's browser makes a
fresh X25519 **thread key** per thread (kept in browser storage; the
bookmarkable reply link is derived from it). It is never reused across
listings, so threads cannot be linked.
- **Buyer -> owner** messages are sealed to the listing's current `device` key.
**Owner -> buyer** messages are sealed to the thread public key.
- Both travel as an **envelope**: an unsigned, encrypted, proof-of-work-stamped
record gossiped on the listing's region topic and kept by every node that
replicates the region for at most 14 days. The owner's node collects its
envelopes on sync, including after being offline.
- Only the **owner's replies are signed** (device key + certificate), so a
buyer can tell the real owner from an impersonator. Buyer messages are
authenticated only by knowing the thread key, which only the owner learns.
### Envelope (what is gossiped)
Canonical JSON, integers only, max **10 KB**:
| field | notes |
|---|---|
| `v` | 1 |
| `listing` | `{author, id}` of the listing this thread is about |
| `to` | `owner` or `buyer` |
| `rcpt` | `owner`: the listing's `device` public key (64 hex). `buyer`: the **mailbox tag** (32 hex) = first 16 bytes of `sha256("allmende-mailbox-v1\n" ‖ thread public key)` |
| `epk` | sender's fresh ephemeral X25519 public key (64 hex), new for every envelope |
| `created_at`, `expires_at` | unix seconds; `expires_at - created_at` in (0, 14 days] |
| `ct` | hex ciphertext, see below |
| `pow` | nonce; `sha256` of the canonical bytes of the envelope (including `pow`) has at least *message difficulty* leading zero bits (default **14**, lower than listings; configurable per node) |
The envelope's identity is the sha256 of its canonical bytes; nodes dedupe on it.
The topic is `/allmende/1/messages/<region>`, with the region taken from the
listing's geohash.
### Sealing
```
rpk = X25519 public key of the recipient
(owner: the device ed25519 key converted with the standard birational map,
as libsodium's crypto_sign_ed25519_pk_to_curve25519; buyer: the thread key)
esk = fresh X25519 secret key, epk its public key
key = HKDF-SHA256(ikm = X25519(esk, rpk), salt = epk ‖ rpk, info = "allmende-seal-v1", 32 bytes)
header = canonical JSON of the envelope without `ct` and `pow`
ct = ChaCha20-Poly1305(key, nonce = 12 zero bytes, aad = header, padded plaintext)
```
The nonce may be fixed because every envelope uses a fresh `esk`, hence a fresh
`key`. The AAD binds listing, recipient and timestamps, so a relay cannot
alter or re-date an envelope without making it undecryptable. An all-zero
shared secret (low-order point) is rejected. Reusing the device key for both
signing and Diffie-Hellman follows libsodium practice and is separated by the
different contexts; no separate encryption key is added to certificates.
**Padding:** plaintext = canonical JSON, then `0x80`, then zero bytes up to the
next size of 512, 1024, 2048 or 4096 bytes, so length reveals little.
Plaintext before padding is at most 4095 bytes (one byte is the marker). Relay
and owner/buyer limits are in UTF-8 bytes. The plaintext must be *canonical*:
a receiver re-encodes what it decoded and rejects any difference (unknown
fields, odd escapes, reordering).
### Plaintext (inside `ct`)
Canonical JSON. Every message has:
| field | notes |
|---|---|
| `t` | `text` or `grant` |
| `thread` | the thread public key (64 hex) |
| `n` | the sender's counter in this thread, from 1 (orders messages despite clock skew) |
| `sent_at` | unix seconds |
- **`text`** (either direction): `text`, at most 1000 bytes in the buyer's first
message and 2000 bytes afterwards. No control characters (same text rules as
listings).
- **`grant`** (owner only): the signed **address release**:
`address` (<= 300 bytes), optional `phone` (<= 40), `email` (<= 120), `note`
(<= 1000, free text from the owner, e.g. "Saturday at 10, ring twice"),
`valid_until` (unix seconds, in `(sent_at, sent_at + 30 days]`).
Every **owner -> buyer** plaintext (`text` and `grant`) also carries
`listing` (`{author, id}`), `device`, `cert` and `sig`. `sig` is the device
signature over the canonical plaintext without `sig`, with the prefix
`allmende-reply-v1\n`. Because it covers `listing` and `thread`, a reply cannot
be replayed into another thread. The browser accepts it only if `cert` is a
valid certificate of the listing's `author` for `device`, valid at `sent_at`,
and the signature verifies. As elsewhere, a browser cannot know about later
revocations; the UI says so.
The buyer's UI shows a `grant` as a distinct card ("Address released by the
owner of this listing") and hides it after `valid_until`. Hiding is advisory:
the browser had the data and cannot be forced to forget it.
### Relay validation (before gossiping, ciphertext only)
1. size, canonical encoding, `v`, field formats, `to`/`rcpt` shape;
2. lifetime and expiry; a `created_at` far in the future is ignored;
3. proof-of-work at the node's message difficulty;
4. `to = owner`: the listing must be known, live (not expired or deleted) and
in this region, and `rcpt` must equal its current `device`;
5. `to = buyer`: the listing need not exist (the owner may have deleted it
since, and replies must still arrive). If the listing *is* known, the
envelope's region must still match it;
6. per-queue caps: at most 200 live envelopes per listing (`owner`), 50 per
mailbox (`buyer`) and 20000 per node (all configurable in the store). When
full, the envelope with the **least work** is evicted (oldest first on
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
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
listing, wrong `rcpt` after a device change, and clock failures are **ignored
without penalty**, as with listings. Relays **cannot** check content, so the
text rules below are enforced by endpoints.
### Endpoint rules (owner's node and buyer's browser)
- The owner's node trial-decrypts only envelopes addressed to its own
`device` key for its own listings, and drops anything that fails AEAD or
has a malformed plaintext. Buyer messages are shown as plain text, never as
clickable links.
- **First-message restriction:** until the owner has sent a message in a
thread, the buyer's messages must be short text with **no links**: no
`://`, no `www.`, no hostname-like `label.tld` token (a regexp over letters,
digits and `-`, after lowercasing; it also flags "Hallo.Ich", which the UI
says). The owner's node stores such messages but marks them **hidden**: the
API withholds their text. The buyer's browser refuses to send them. The
rule is shared by Go and TypeScript and checked against common test vectors.
This is a heuristic against scams, not a guarantee.
- **Owner-side rate limit:** a node accepts at most N new threads per listing
per 24 hours (`--max-new-threads`, default 20). Surplus first messages stay
unseen until room frees up (or they expire); highest work first, then oldest.
Envelopes that fail to decrypt are remembered (`inbox_seen`) and not tried
again.
- **Block.** The owner can block a conversation (`PUT
/api/v1/inbox/{listing}/{thread}/block`): it is erased, and every later
envelope of that thread key is dropped unread, unannounced and not counted
against the new-conversation limit. `DELETE` on the same path lifts the block
(what arrived meanwhile is gone), `GET /api/v1/blocked` lists blocks. The
buyer is not told. A block lasts as long as its listing is stored. It
stops a thread key, not a person: a buyer can start over with a new key,
which costs a first message again (proof-of-work, the link ban, the daily
limit). Plain *delete* only erases; the thread would reappear as a new
conversation if the buyer wrote again.
- Messages carry **no attachments and no images**.
- The decrypted inbox is stored only on the owner's node, in its database. The
exact address is a private per-listing field there, never signed or
gossiped; "release address" pre-fills a `grant` that the owner can edit.
### Transport
- **Gossip** on `/allmende/1/messages/<region>`; **sync** extends
`/allmende/1/sync` with kind `messages`, paged by `(created_at, hash)`.
- **HTTP**, public: `POST /api/v1/messages` (the canonical envelope as the
body, at most 10 KB; the node validates, stores and gossips it; answers 202
`{"hash"}`; 400 invalid, 404 unknown listing, 413 too large, 429 rate
limited per client IP) and
`GET /api/v1/messages?mailbox=<tag>&since=<created_at>&limit=<n ≤ 100>` for
the buyer's browser to poll (`since` is inclusive; the browser re-reads the
last hour each time and dedupes by hash). Responses are `no-store`.
- **HTTP**, owner (admin token): `GET /api/v1/inbox` (threads),
`GET|POST|DELETE /api/v1/inbox/{listing}/{thread}` (read, reply, erase) and
`PUT|GET|DELETE /api/v1/listings/{id}/address` (the private address). A
reply body is `{type: "text"|"grant", text, address, phone, email, note,
valid_days}`; a grant without `address` uses the stored one.
- `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`.
- A gateway sees the buyer's IP address and mailbox tag. Buyers can use any
gateway; nothing else about the conversation is exposed.
- **Buyer UI:** a contact form on every verified listing; a private link
`#/c/<author>/<id>/<thread secret>` (the secret stays in the URL fragment,
which is never sent to a server) that polls every 8 s while the tab is
visible (paused in a background tab, resumed at once when it returns; there is
no push channel), shows only verified owner replies and counts the rest as
rejected; `#/messages` lists the conversations stored in this browser. The
owner's "My listings" screen refreshes the same way.
- **Owner UI** (`#/mine`): your listings (requests needing a reply, whether an
address is saved), the requests of one listing (status, preview, effort,
filters), a conversation, and a sheet to **release the address** (prefilled
from the saved one; address, phone, email, a free-text note, validity 1 to 30
days). When the buyer's latest message contains words like "address" or "wo
genau", the conversation suggests releasing it; that is a keyword guess and
only ever a suggestion.
Three panes side by side on a wide screen, one at a time on a phone. It uses
the admin API above plus `GET /api/v1/mine` (own listings with request counts
and `address_saved`) and `GET /api/v1/inbox?listing=<id>`, whose rows also
carry `last_dir`, `needs_reply`, a text `preview` (empty for hidden messages),
`effort` (proof-of-work bits of the first message) and `grant_until`.
- **Terminal notice.** The node checks for new messages every 10 s (and on every
UI request), so it reports them even with no browser open. For each
conversation it logs one line, `new conversation` or `new message`, with the
listing's title, a count if there are several, a short conversation id and a
link `http://127.0.0.1:8080/#/mine/<listing>/<thread>`. It never prints what
the buyer wrote (untrusted text, and it belongs in the browser), and hidden
messages are not announced. A backlog is capped at 5 lines plus a summary.
- **Owner login.** The page itself never contains the admin token (every node
serves the same page, including public gateways). `allmende run` prints a link
`http://127.0.0.1:8080/#/login/<token>` to the terminal, not to its log. The
token is in the URL fragment, which a browser never sends to a server; the
page moves it into `sessionStorage` (so closing the tab signs out), removes it
from the address bar and sends it only to the node that served the page. A
paste field is the fallback; a token the node refuses (for example after
`recover`) is forgotten.
### Limits of this design
- No forward secrecy: a leaked device key reads envelopes still stored
(<= 14 days) or captured earlier. A device enrolled after recovery cannot read
older envelopes.
- Buyer storage loss loses the thread (no account to recover it).
- Only the listing's current device can read buyer messages, not the owner's
other devices.
- Everything in a thread is visible to the owner's node. Abuse reporting for
messages is not designed yet; the size cap, text-only content and link ban
keep messages from carrying images or bulk content, and the legal review
(§184b StGB, GDPR) should cover messaging before launch.
## HTTP API (`internal/api`)
Public reads serve the signed records in their **canonical encoding**, so a
browser verifies signatures itself and need not trust the gateway. Writes act
as the node's owner and need `Authorization: Bearer <admin token>` (a random
token written to `admin.token` at init, mode 0600).
| method and path | auth | |
|---|---|---|
| `GET /api/v1/status` | no | peer ID, addresses, identity, regions, peer and listing counts, `cert_expires_at` (unix seconds) and `can_renew` |
| `PUT /api/v1/certificate` | token | `{"phrase": "<12 words>"}`: renew the device certificate (see "Recovery" and renewal above); answers `{"cert_expires_at"}`. 400 malformed phrase, 409 another identity's phrase or an identity without a phrase |
| `GET /api/v1/listings` | no | filters: `geohash` (comma-separated prefixes), `kind`, `category`, `min_price`, `max_price`, `min_area`, `min_rooms`, `limit` (max 200), `offset` |
| `GET /api/v1/listings/{author}/{id}` | no | one listing |
| `POST /api/v1/listings` | token | publish a draft; the node adds identity, time, PoW and signature |
| `PUT /api/v1/listings/{id}` | token | replace own listing (`seq + 1`); the region cannot change |
| `DELETE /api/v1/listings/{id}` | token | publish a tombstone |
| `GET /api/v1/mine` | token | your live listings with request counts and whether an address is saved (messaging, see above) |
Reads send `Access-Control-Allow-Origin: *` (the data is public). Writes are
not cross-origin. Images are not supported yet. `status` also reports the
node's PoW `difficulty`, which the browser uses as its minimum.
## Web UI (`web/`)
Every node serves a search UI at `GET /`. It is vanilla TypeScript, bundled by
esbuild into `web/dist` (unminified, so it can be read) and **committed**, then
embedded with `go:embed`: `go build` is enough to run a node, Node.js is only
needed to change the UI (`cd web && npm ci && npm run build`).
- **Verification in the browser.** Every listing is checked locally with
pure-JS ed25519/SHA-256 (works over plain http): format, device certificate,
certificate/listing binding, validity windows, signature, proof-of-work.
Failing results are hidden (with a count) and their content is never shown.
A gateway can therefore withhold listings but not forge them. What a browser
cannot know is whether a device was revoked since; the UI says so.
- **Canonical JSON** is reimplemented in TypeScript and tested against a
fixture signed by the Go code (`internal/listing/testdata/fixture.json`,
refresh with `UPDATE_FIXTURES=1 go test ./internal/listing -run Golden`).
- **Untrusted text.** Listing text is only ever inserted with `textContent`.
The CSP is `default-src 'none'; script-src 'self'; style-src 'self'; ...`
(no inline script or style), plus `nosniff` and `no-referrer`.
- **Publishing** (owner only, after the login link): `#/mine/new` creates a
listing, `#/mine/<id>/edit` changes one, and the owner view offers Renew and
Delete. The form maps to the draft of `POST`/`PUT /api/v1/listings`:
- *Location*: the owner pastes coordinates (`53.5511, 9.9937`, German decimal
comma with `;`, or an OpenStreetMap/Google Maps link). The browser encodes a
precision-6 geohash itself, shows its size (about 1 km) and an
OpenStreetMap link to check it; no map tiles are loaded. "Use my location"
appears only where the browser allows geolocation. A place outside the
regions the node follows is refused client-side, since the node would not
receive messages for it; a region cannot change on edit.
- *Price*: entered in euros (`1.150,50`, `1,150.50`, `1150`), sent as cents;
the period follows the offer (month for rent, once for sale).
- *Exact address*, phone and email: optional, only when creating. They are
saved with `PUT .../address` after the listing exists and never enter the
listing. Later they are edited on the request screen.
- *Renewal* is manual: Renew re-publishes the listing unchanged with a
fresh 30-day term (a new `seq`). Cards show the days left and warn under
5 days. There is no auto-renew; an unattended node's listings simply expire.
- *Delete* asks first, then publishes a tombstone.
- The node mines the proof-of-work while the request is open, so the form
shows a "publishing" state for a few seconds.
## Running a node (`cmd/allmende`)
```
allmende init # create identity, show the 12-word phrase (once)
allmende run --region u1x [--bootstrap <addr>] # replicate a region, serve the API on 127.0.0.1:8080
allmende run --public [--listen …] # a bootstrap node: DHT server and relay
allmende recover # restore from the phrase; also yearly cert renewal
```
`run` also takes `--no-default-bootstrap`, `--no-dht` and `--no-mdns`, and keeps
the peers it has met in `peers.json` next to its keys.
## Spam
Proof-of-work per listing and per revocation, abuse reports (below), and
subscribable blocklists (not built yet). The format leaves room for vouching
signatures later.
**Mining** (`internal/pow`, `pow.Mine`): the nonce is the smallest number that
makes the canonical bytes hash to enough leading zero bits, so every miner that
tries 0, 1, 2, ... finds the same one. The node hashes the bytes before the
nonce once and, per attempt, only the number and what follows, on every core
but one. Measured on an 8-core machine under other load, mining one listing
takes about 19 ms at difficulty 16, 0.14 s at 20, 1.1 s at 22, 3.6 s at 24
(the default since 2026-11-19; it was 16) and 15 s at 26: about 16 times longer
per 4 bits, with a spread of about three times either way from one listing to
the next. On fewer cores it takes proportionally longer. (Before the fast
miner every attempt re-encoded the JSON and one listing at 16 took about 2 s.)
Listings, reports and revocations use this difficulty (`--difficulty`);
messages have their own, lower one (`--message-difficulty`, 14). A listing
mined for 16 is refused by a node at 24, so nodes of the old default and of
the new one do not exchange listings until both are updated.
**What it can and cannot do.** The difficulty is a number of hashes, so it
prices the work the same for everyone, but hardware is not equal: an attacker
with an optimized miner or a GPU does what the node does in a fraction of the
time. A difficulty that takes an honest laptop 30 s (about 27 bits) takes a GPU
well under a second, and one that takes a GPU 30 s would take the laptop hours.
So proof-of-work stops casual bulk posting, not a determined spammer, and is
only one layer: it is paired with what a node does with the traffic it gets
(rate limits and peer scoring, the reports and the hide rule, later vouching
and blocklists). The difficulty is network-wide: nodes check it against their
own `--difficulty`, so changing the default needs every node to change, and a
node with a higher value refuses listings mined for a lower one.
## Abuse reports
Implemented in `internal/report` (the record), `internal/store/reports.go`
(storage and the hide rule) and `internal/api/reports.go`. A report is
**information, not a verdict**: no report removes anything from the network.
Each node decides whose reports count, and what a listing that enough trusted
reporters flagged looks like *on that node*: hidden from search, behind a
notice, still stored and still reachable by its link.
**The record.** Canonical JSON, at most 4 KB, signed like a listing (device
key plus the certificate that chains to the reporter's identity key, and
proof-of-work at the listing difficulty): `listing {author, id}`, `category`
(`scam`, `illegal`, `category`, `other` or `withdrawn`), `note` (at most 300
bytes, no control characters), `created_at`, `expires_at` (at most 30 days
later, so a hide lapses unless it is renewed), `reporter`, `device`, `cert`,
`pow`, `sig`. A reporter has **one report per listing**: a newer one replaces
the older (the smaller hash on a tie), and `withdrawn` takes a report back.
Reports of a revoked device are dropped, and none are accepted from it.
**Network.** Reports travel on one global topic, `/allmende/1/reports`
(they are few, and every node may want them), validated like revocations:
canonical form, signature, proof-of-work, certificate; a clock mismatch or a
revoked device is ignored without penalty. Sync adds a `reports` digest to the
`digest` reply and a `reports` kind that returns the live reports (up to
5000); so a node that was offline catches up, and anti-entropy repairs the
rest.
**Who counts (the hide rule).** Local, in `store.Trust`:
- the **node's own operator** (`Self`): one report as `scam` or `illegal`
hides the listing on this node at once;
- **one** report of `illegal` from any trusted reporter hides it;
- `--hide-after N` (default 2) distinct trusted reporters flagging `scam` or
`illegal` hide it;
- trusted reporters are the operator and the keys given with
`--trust-reporter <identity key>` (repeatable; a node shows its key as
`author` in `/api/v1/status`);
- reports from anyone else are kept, shown as a count, and **never** counted;
- `category` and `other` only label.
A hidden listing is left out of search unless `?hidden=1`; its own page
(`#/l/<author>/<id>`) shows who flagged it.
**What visitors can do.** A visitor has no key, so they cannot sign. On a
listing page they can *tip off* the node they are using: `POST
/api/v1/signals` with category, note and proof-of-work at the message
difficulty (a canonical JSON body; the browser mines it as it does for
messages). The node keeps it **only for its operator** (a signal is not
gossiped, hides nothing, is limited per listing and overall, expires after 30
days, and sending the same one twice adds nothing). The operator sees the tips
(`GET /api/v1/signals`, strongest first) and may sign a report of their own
(`POST /api/v1/reports`), which also clears the tips about that listing, or
dismiss them (`DELETE /api/v1/signals/{author}/{id}`). So harassing a seller
with many tips costs work and changes nothing unless the operator agrees.
**HTTP.** Public: `GET /api/v1/reports?author=&id=` (what this node makes of
the reports: `hidden`, `trusted` counts per category, `others`, `signals`,
`own`), `POST /api/v1/signals`, and `GET /api/v1/listings?hidden=1`. Operator
(admin token): `GET /api/v1/signals`, `DELETE /api/v1/signals/{author}/{id}`,
`POST /api/v1/reports` (`{listing, category, note}`).
**In the browser** (`web/src/reports.ts`). Every listing page asks the node what
it makes of the reports and says so if the node hides the listing, and who
flagged it (counts per reason; reports from reporters the node does not trust
are mentioned and not counted). A "Report this listing" form mines the proof-of-work
and sends a tip. When the operator is signed in, a second form signs a report
(or withdraws it). `#/mine/reports` is the operator's queue of tips, grouped by
listing: report as the reason a visitor gave, or dismiss.
**Not built yet:** vouching (who becomes trusted is the operator's choice for
now), signed blocklists you subscribe to by curator key, an owner's signed
reply to a report, and reputation for reporters whose reports are overruled.
## Simulation (`cmd/allmende-sim`)
`go run ./cmd/allmende-sim -nodes 100` runs many real nodes (libp2p, gossipsub,
DHT, store, sync, each with its own identity) in one process over loopback and
reports how long listings, messages and reports take to reach everyone, what
happens when 20% of the nodes go offline and come back, whether all nodes end
with identical data, and the memory, CPU and traffic it cost. Flags: `-regions`,
`-listings`, `-messages`, `-reports`, `-churn`, `-seed` (repeatable run).
Reference run (100 nodes, 3 seeds, 5 regions, 60 listings at 5/s, 20% churn):
every listing reached all 1300 followers (p50 14 ms, p99 61 ms), every message
reached its owner (p95 0.4 s), a report reached all 99 other nodes (p95 0.17 s),
returning nodes caught up in under 3 s, and all nodes agreed afterwards.
About 165 KB of traffic per node in total.
More scenarios, each a flag: `-latency 60ms -lifetime 30s` (delay on every
write of dialed connections, ±50%, and connections cut at random; this is what
packet loss looks like above TCP), `-hostile` (an attacker with no validators),
`-kill-seeds`, `-repair` (with `-anti-entropy 5s`), `-seed-conns N`. Ran on
2026-11-18 (100 nodes, 5 regions unless noted):
| Scenario | Result |
|---|---|
| 60 ms latency, 1130 connections cut in the run | 100% delivered; listings p95 67 ms, messages p95 0.4 s; returning nodes 6 s; all nodes agreed |
| 500 junk, forged, under-worked and wrong-region listings at one region | **0 stored**; honest listings during the attack 100% (p95 31 ms) |
| 400 valid envelopes flooding one listing | queue stayed under the limit (138 of 200 at the owner); the price rose from 6 to 7 bits; a buyer paying its own gateway's price still got through (43 ms) |
| listing only one node's store has (no gossip) | anti-entropy every 5 s, one peer per round (the old way): 108 of 109, p50 25.9 s, p95 44 s, max 49.9 s. With 3 peers per round: 109 of 109, p50 5.7 s, p95 10.6 s, max 13.7 s. Scaled to the new default of 10 min that is a median of about 11 minutes (it was about 2 hours at 30 min and one peer) |
| all seeds shut down | the network keeps working (329 of 329 listings); newcomers that remember two live peers of their own region got everything (160 of 160) |
| 300 nodes, 8 regions | 100% delivered (listings p95 75 ms, messages p95 0.8 s, reports p95 0.5 s), all agreed; 1.3 GB heap, 100k goroutines, 137 KB per node |
**How large a network can it carry?** `scripts/sim-sweep.sh` runs growing
networks (8 regions, 3 seeds, 30 listings, 20 messages, 3 reports, 10% churn)
and records each as JSON in `.tmp/sim/` (run it only when you mean to: it takes
many minutes and several GB of memory). `node scripts/sim-report.mjs` turns the
runs into tables and `node scripts/sim-dashboard.mjs` builds
`.tmp/sim/dashboard.html`, a self-contained page with the graphs; nothing is
uploaded anywhere. Result on a 16 GB, 8-core machine:
| Nodes | As shipped (`--public` accepts 1000) | libp2p's own default limit (before the fix) |
|---|---|---|
| 100 | complete in 3.4 s, 100% delivered | complete in 3.2 s, 100% |
| 200 | 6.3 s, 100% (p95 57 ms) | **never completed**: 12 nodes without any peer, 91.8% delivered |
| 300 | 9.4 s, 100% (p95 79 ms) | 112 nodes without a peer, 43% delivered |
| 400 | 14 s, 100% (p95 99 ms) | 212 nodes without a peer, 16% delivered |
| 600 | 24.5 s, 100% (p95 117 ms) | not run |
| 800 | 35.6 s, 100% (p95 128 ms) | not run |
As shipped, delivery stayed at 100% and agreement held up to 800 nodes, the
largest run; time to form the mesh grows with the network size (3.4 s at 100,
24.5 s at 600, 35.6 s at 800), and so does the simulator's cost (3.3 GB heap,
320k goroutines, 350 CPU-seconds at 800). That cost is the sum of all the
nodes sharing one machine, so it measures the limit of the simulation as much
as of the protocol; larger runs were not tried to keep this machine's memory
free. With libp2p's default the network stopped working where the seeds ran
out of inbound connections (three seeds held about 187 each).
Findings (see "What is left" in SPECS.md for the open ones):
1. **Connection limit on the bootstrap node (fixed).** libp2p's resource
manager capped inbound connections in proportion to memory (about 190 on 16
GB, fewer in a small container): with 200 nodes, 12 never got a single peer.
A `--public` node now accepts 1000 inbound connections (`--max-conns`
changes it; `-1` restores libp2p's default), and the table above shows the
result. **Memory with 1000 connections** (`cmd/allmende-conns`, one real
`--public` node, 1000 small libp2p clients on the same machine, each
subscribed to the region's topic): 35 MB idle, 131 MB with the 1000
connections (about 100 KB each), 156 MB at the peak after 100 listings were
published and flooded to all 1000 (the Go heap on Linux, `VmHWM`). A
further 100 connection attempts were refused as intended (1000 connected,
100 failed). That is about 30% of the 512 MiB pod limit. Real peers do more
than these clients (identify, DHT queries, relayed streams), so the
manifest also sets `GOMEMLIMIT=400MiB`, which makes the Go runtime collect
harder as the limit nears instead of being killed by it.
**With a large database and real nodes** (50,000 listings, 269 MB database,
in the regions u0u and u1h, made with `allmende-load`): the same node idled
at 53 MB, so the database costs no resident memory to speak of. With 1000
clients connected it held 137 MB. With 1000 clients connected *and* 30 real
`allmende run` processes (DHT on) catching up from it at the same time it
peaked at 174 MB, a third of the pod limit. About a minute after the
connections were opened the node's connection manager closed most of the
idle ones (970 connected, 154 left after 2.5 minutes) once real nodes had
joined, which is its job at the high-water mark. Relayed streams were not
tried (they need a node behind a NAT).
The run also found a slow spot, not in the serving node but in the
newcomer: a catch-up is cut off after 2 minutes (`syncTimeout`), and with
SQLite's default `synchronous=FULL` a newcomer stored only about 137
listings a second, so one sync from a region of 20,140 listings ended at
16,438 and the rest waited for the next round. With `synchronous=NORMAL`
(WAL mode: no corruption on a crash, only the last few commits may be lost,
and listings come back from peers) the same sync took 63 s for all 20,140.
The store now uses `NORMAL`.
Two more changes make a big catch-up faster and no longer depend on a
fixed deadline. A sync page is stored in one transaction
(`Store.PutMany`), with the signature checks spread over the cores, and
a sync is cut off after 2 minutes *without progress* (any record, request
or stored page counts) or 30 minutes in all, instead of 2 minutes flat.
One newcomer following two regions of a node that holds 20,000 listings
(same machine, same data): old store 120 s, cut off at 15,126 of 20,000;
`synchronous=NORMAL` 38 s for all; plus pages in one transaction 24 s.
2. **Peer limits are crude.** The first run had no peer scoring: the attacker
stayed connected to all 10 nodes it dialed after 500 bad messages. Now every
node counts, per relaying peer and minute, the messages it gets (over 1200
are dropped unread, without penalty) and the invalid ones (20 get the peer
banned for an hour: closed connection, gossip blacklist; `internal/p2p/guard.go`).
In the sim the attacker was cut off from all 6 nodes it reached and honest
listings still arrived 50 of 50. What it does not stop: an attacker with many
peer IDs, a peer that sends only valid but unwanted records, or one that
stays under the limits. Three more limits close part of that:
- **Sync:** a peer may hold 4 sync streams at once and open 1500 a minute
(a full sync of 100,000 listings is about 1200); a banned peer gets none.
- **Per author:** a node keeps at most 100 unexpired listings per author
(`--max-per-author`, -1 for no limit); a 101st new one is neither stored
nor passed on, while updates, renewals and deletions of held ones still
work. Each node decides for itself, so nodes with different values hold
different sets and anti-entropy keeps offering the refused ones.
- **Per address:** at most 16 inbound connections from one public IP, or one
IPv6 /64 (`--max-conns-per-ip`, -1 for no limit); loopback, private and
link-local addresses are exempt, and a banned peer ID is refused when it
redials. A new peer ID from the same machine therefore does not help.
Behind a Kubernetes service the real source address is only visible with
`externalTrafficPolicy: Local` (the base manifest has it; the nodeport
overlay uses `Cluster`, which hides it, so the limit does nothing there).
- **HTTP API:** at most 600 `/api/` requests a minute per client address
(`--requests-per-minute`, -1 for no limit), answered with 429 and
`Retry-After`; the UI's static files are not counted, and requests from the
node's own machine are exempt so the owner is never locked out. On top of
that, posting messages and tips keep their own, much lower limit (30 a
minute). Behind a reverse proxy the client is read from `X-Forwarded-For`
only when the connection comes from a `--trusted-proxy` (address or
network, repeatable), and then it is the last entry that is not itself a
trusted proxy, so what a client writes itself is never believed. Without a
trusted proxy every client behind the proxy shares one allowance; the
manifest sets `TRUSTED_PROXY` to the private ranges for that reason. A
request carrying forwarding headers is never treated as local, so a proxy
on the node's machine does not exempt its clients.
Bans are per node and not shared (a shared ban would let one node get
honest ones banned).
3. **The DHT is only as good as its servers.** Only publicly reachable nodes
serve it. With every seed gone, a newcomer whose remembered peers are all in
another region found nobody (0 of 114 listings), and one that remembers no
live peer found no peer at all. A node that remembers peers of its own
region (the usual case) is fine. Peer exchange (see "Reconnection") now
covers the first case: a newcomer connected to any peer that is connected to
the region finds it through that peer. Re-run with `-kill-seeds` (100 nodes,
seeds down): 6 newcomers whose two remembered peers were all in another
region got 56 of 56 listings, after about 5 s (the first exchange round),
where before they got none. One that remembers no live peer at all still
needs a seed or the DNS name.
4. **Repair at the default interval** takes about 11 minutes to the median
node (see the table); it was about 2 hours.
It shows protocol behaviour and cost, **not** the internet: no real packet
loss, NATs, clock skew or bandwidth limits, and all nodes share one machine, so
CPU and memory figures are totals for all of them. Treat the times as a lower
bound and the agreement and cost figures as the useful part.
## Open
Abuse reporting for messages (reports cover listings only so far), vouching
and blocklists for reports, reciprocity rules, anti-
discrimination (AGG) content rules, peer scoring and rate limits,
a fallback bootstrap list inside the binary
for networks that block DNS, image hosting,
recovering listings onto a fresh machine with an empty database, a helper to
turn a place name into a region.