Skip to content

About

BSV peer-to-peer messaging service on Cloudflare Workers. Rust → WASM. 1:1 parity with message-box-server (TS) and go-messagebox-server. Live-verified byte-for-byte against messagebox.babbage.systems.

Resources

Stars

4 stars

Watchers

0 watching

Forks

Repository files navigation

The code of record. This repository is the home of bsv-messagebox-cloudflare since 0.5.5: every change lands here through a pull request under the machine gate (the test, fmt, clippy, wasm32 and scrub checks, linear history), and a v* tag publishes the crate through crates.io trusted publishing. The deployment config carries placeholders only; the deployed Workers' identifiers live in the operator's private infra repository, never here, and the scrub check (tools/scrub.sh) refuses an identifier, a deployment hostname, a key-shaped or token-shaped string, a second wrangler config or a secrets file on every pull request.

bsv-messagebox-cloudflare

A BSV messaging relay on Cloudflare Workers: BRC-31 authentication, delivery permissions, optional paid delivery, D1 message storage, KV sessions, raw WebSockets through a hibernatable Durable Object, and a Socket.IO transport for unmodified @bsv/authsocket-client and @bsv/message-box-client. This repository is the code of record: development happens on its branches and lands on main through pull requests.

Version and dependencies

The relay is 0.7.0, published on crates.io as bsv-messagebox-cloudflare (the library keeps its identifier rust_message_box). The release of record is the tag v0.7.0. Cargo.toml pins bsv-rs =0.7.0, bsv-middleware-cloudflare =0.7.0 and bsv-middleware-core =0.4.0; the bsv-middleware-rs dependency is the compatible 0.6.1 requirement, not an exact pin. CHANGELOG.md is the record of changes.

Routes

The router is handle in src/lib.rs.

Method Path Auth
GET /api-docs Public; the OpenAPI description in src/api_docs.rs
POST /push, /broadcast, /session/attest Bearer BROADCAST_TOKEN (producer workers, not end users)
GET /ws BRC-31 on the upgrade; raw WebSocket to the MessageHub Durable Object
GET, POST /socket.io/* Engine.IO and Socket.IO; BRC-103 over the authMessage event
GET /, /health BRC-31
POST /sendMessage, /listMessages, /acknowledgeMessage BRC-31
POST /listTranscript, /purgeTranscript BRC-31; boxes in RETAIN_BOX_PREFIXES only
POST /permissions/set BRC-31
GET /permissions/get, /permissions/list, /permissions/quote BRC-31
POST /registerDevice BRC-31
GET /devices BRC-31
POST /beef/upload-url, /beef/download-url BRC-31; presigned R2 URLs
GET /presence BRC-31
POST /rejoin-deadline BRC-31
POST /turn-credentials, /turn-credentials/revoke BRC-31; TURN_CREDENTIALS = "on" only

HTTP and WebSocket sends share src/routes/send_message.rs. The scheduled event drains deferred delivery fees and reclaims released payment objects.

Messages and payment words

The paid door checks the fee and verifies BEEF ancestry and unproven spends. It reads BEEF as a stream, including R2 objects, with a saved cursor when a request pauses between elements or inputs. A local script-work or stack-memory decline is no verdict on the payment: the payment is not judged.

HTTP Word Meaning
400 ERR_INVALID_PAYMENT Invalid bytes, spend, output or merkle-root refusal; byte errors name offset and kind.
400 ERR_INSUFFICIENT_PAYMENT The delivery output pays less than the fee; or the host's wallet did not take the payment, for a reason the payer's own bytes cause (handoff::PAYER_REFUSALS) or by its answer accepted: false: nothing was charged; send again later, or with another payment. The send is refused and nothing is stored. Every other answer of the wallet is the host's own, and the fee is deferred.
400 ERR_SUBJECT_NOT_LAST This door judges the transaction written last: write the subject last. The Atomic prefix names another transaction than the one written last (subject, last); the bytes may be valid, and the door asks for them in that order. No honest writer is turned away: bsv-rs 0.8.15's Beef::to_binary_atomic (src/transaction/beef.rs:981) puts the subject last (:1068-1073), and @bsv/sdk's Beef.toBinaryAtomic (bsv-blockchain/ts-stack 57c5f13, packages/sdk/src/transaction/Beef.ts:1210) writes the subject last (:385-388, :1390). The refusal goes when the door finds the subject by its txid, as the readers of both libraries do.
408 ERR_AUTH_BODY_TIMEOUT Any authenticated route, and /push, /session/attest and /broadcast after their bearer: the request's body did not arrive within 30 seconds, the longest this host waits for one. Nothing of the request is done. Unsigned (no caller is authenticated yet).
409 ERR_PAYMENT_USED The delivery-fee payment was already used for another send (txid, outputIndex): a delivery-fee payment serves one send. Nothing is handed to the wallet, announced or stored. Pay again for a new send. The same send again is answered as it was the first time, and a send whose message id is stored is answered ERR_DUPLICATE_MESSAGE before the wallet is asked, whatever send its payment is claimed for.
413 ERR_BODY_TOO_LARGE Any authenticated route: the request's body is over this host's bound for one request, 12,582,912 bytes (12 MiB, validation::SEND_BODY_BYTES). A declared Content-Length over it is answered before the body is read, and the read stops one byte past it. {status, code, description}; the description names the body's size where it is known and says "more than" the bound where the read stopped. On /sendMessage it names the send (The send is 12582913 bytes and the relay reads at most 12582912 in one request.); on every other authenticated route, the request's body (The request's body is 12582913 bytes and the relay reads at most 12582912 in one request.). A body over the figure is answered before the caller is authenticated, so that answer carries no BRC-104 signature; a client that requires signed answers reports it as an unsigned answer, with the status 413 and the code ERR_BODY_TOO_LARGE in the answer itself. Also a payment a box keeps unjudged that is over its row's bound. On /push, /session/attest and /broadcast, after their bearer: the body is over the route's figure (/push 12,583,040 bytes, /session/attest 16,384, /broadcast 1,049,600; src/body_bounds.rs says why), the description naming the route and its figure (The /broadcast body is 1049601 bytes and the relay reads at most 1049600 of it in one request.), before the body is read where its declared length is over.
413 ERR_PAYMENT_SIZE Not judged: the payment's bytes (its BEEF as bytes, inline in any shape of tx or uploaded) are over this host's bound (budget, the figure in force: [limits] payment_bytes, 614,400 bytes by default; size the payment's bytes). Refused from the encoding's or the stored length before any of it is parsed; the door keeps no state of the reading and no spool for it. A bound of this host, not a rule of the chain, and no verdict on the payment: pay with other coins. A send whose first message id is already stored answers ERR_DUPLICATE_MESSAGE instead. The figure is provisional: it is read again at each bsv-rs pin of this crate and raised to the door's natural figure when a pin allows it. Each refusal is logged for the operator (AUDIT payment.not_judged).
422 ERR_PAYMENT_WORK Local work budget exhausted; validity remains undetermined.
422 ERR_PAYMENT_MEMORY Not judged: this host declined memory for a script of an unproven transaction in the payment's BEEF, the payment itself or one of its ancestors, at its stack-memory bound (1,000,000 bytes per stack, named in budget) or for a step. The bound is this host's, not a rule of the chain, and the answer is no verdict on the payment. txid and input name that transaction and input; the description is one sentence that says so. The way out, the free one first: present the payment again once that transaction has its proof (a transaction with its own proof is not run), or pay with other coins. Each decline is logged for the operator (AUDIT payment.not_judged).
500 ERR_SERVER_MISCONFIGURED No header service is configured.
503 ERR_PAYMENT_UNAVAILABLE The header service could not answer: send the same request again. Or the payment's claim, or the send's message ids, could not be read (the claim's table not migrated among the reasons): the send was not served, and nothing was charged or stored.
503 ERR_PAYMENT_PENDING Reading paused; repeat the same request to resume.
503 ERR_PAYMENT_CHANGED Object changed between verification and hand-off.
503 ERR_AUTH_BODIES_FULL Any authenticated route, and /push, /session/attest and /broadcast after their bearer: this host is holding as many request bodies as it reads at once; send the same request again after the Retry-After seconds. A bound of this host, not a fault of the request. Unsigned (no caller is authenticated yet).
413, 503, 408 (plain text) The Socket.IO polling POST (POST /socket.io/?transport=polling&sid=…): its body is over 1,000,000 bytes, the maxPayload the Engine.IO handshake names (413, before the body is read where its declared length is over, and the read stops one byte past it); this host is reading as many polling bodies as it reads at once, 4 MiB, a count of the polling POST's own (503, with Retry-After); the body did not arrive within 30 seconds (408). text/plain with the CORS headers of the route's other polling answers; the text is one sentence naming the bound.

The reference message box server answers a payment it cannot verify with 503 or 500; this relay answers a local work or memory decline with 422, because the same bytes would be declined again. A memory decline's way out, the free one first, is the payment presented again once the transaction it names has its proof, or other coins: a decline keeps no state of the reading, so the next presentation is read afresh.

A payment's bytes are held to one figure at both of its doors, the inline payment.tx of a /sendMessage and an upload named by payment.beefR2Key: [limits] payment_bytes in wrangler.toml, read at build time beside work_units (rebuild after changing it), 614,400 bytes (600 KiB) when the key is absent; a value that is not a whole number of bytes above zero stops the build. An ordinary payment is about a kilobyte (in 727 real payments the median was 1.2 KB and the largest 434 KB); a host that must read a larger payment raises the setting. The rest of the body keeps its own bound (12 MiB). A Worker's isolate is memory-limited, and a door bounds what it reads.

Every body of a client's request the Worker reads is bounded before it is read past a figure. Before its caller is known, at three doors: the BRC-31 layer (bsv-middleware-cloudflare 0.7.8, called through process_auth_do_with_body_bounds for the HTTP routes and the /ws upgrade) and the HTTP session lane each read at most 12 MiB of one request (validation::SEND_BODY_BYTES, the one figure for a send, so the doors and the relay's own check after the read agree), and the Socket.IO polling POST reads at most 1,000,000 bytes, the maxPayload its handshake names. After the bearer, /push reads at most 12,583,040 bytes (a send's 12 MiB and 128 bytes for the sender it adds), /session/attest 16 KiB (the hub's verify body) and /broadcast 1,049,600 bytes (the largest event payload a subscriber accepts, 1 MiB, and 1 KiB for the broadcast's own fields). The /broadcast figure counts the bytes of the request as the producer sends it, so a producer whose JSON encoder adds whitespace or escapes characters counts those bytes too. Each door keeps a separate count of the bodies it is reading at once: 24 MiB for the BRC-31 layer, 12 MiB for the session lane, 4 MiB for the polling POST (four polls at its figure), 12,583,040 bytes for the bearer-gated routes. The sum of these read totals is 52 MiB and 128 bytes (src/body_bounds.rs holds it at most 53 MiB). A body handed to a route is the route's and is not in these counts. Each door waits at most 30 seconds for a body. The figures are constants of this crate, not settings. The answers are in the table above: 413 ERR_BODY_TOO_LARGE, 503 ERR_AUTH_BODIES_FULL with Retry-After, 408 ERR_AUTH_BODY_TIMEOUT. /beef/upload-url presigns a PUT straight to R2, so an upload's bytes never pass through the Worker. The reference names no figure for a payment; only its whole body is bounded (bsv-blockchain/ts-stack 57c5f13, infra/message-box-server/src/app.ts:203-213, and the socket's at src/compose.ts:195).

/sendMessage also carries a per-identity send budget (src/send_budget.rs): past it the answer is 429 ERR_SEND_BUDGET naming the window (SEND_BUDGET_SENDS, SEND_BUDGET_BYTES, SEND_BUDGET_WINDOW_SECS).

wrangler.toml sets [limits] cpu_ms = 43000 and work_units = 10000000. The latter is compiled by build.rs into a per-input budget; changing it requires a rebuild. bsv-rs reserves reached opcodes and hash bytes before doing that work. The work refusal carries resource, input, budget, workSpent, attempted, offset and txid. Every resumed reader receives the budget again; the cursor does not store it. There is no resume within a script and this is not a wall-clock guarantee.

Build and gate

cargo fmt --all -- --check
cargo clippy --all-targets -- -D warnings
cargo clippy --target wasm32-unknown-unknown --lib -- -D warnings
cargo test --no-fail-fast
cargo build --release --target wasm32-unknown-unknown --lib

.github/workflows/ci.yml runs exactly these on every PR and main push. The full deployment artifact also requires worker-build compatible with the Worker SDK in the manifest, and a clang with the WebAssembly target for ring's C on wasm32. The payment reader's host witnesses are in src/beef_door.rs; integration suites are in tests. Live paid tests require a separately authorized environment.

Releases

The tag is the release of record. From 0.5.6 on, the crate bsv-messagebox-cloudflare on crates.io carries the same version as the tag: .github/workflows/release.yml publishes it on a v* tag push through crates.io trusted publishing, after checking the tag against the manifest's version, the tag's commit against main, and the ci.yml gate. The Worker in production is deployed from the tag by the stack's infra. No earlier version was published to crates.io under this name or as rust-message-box.

Deploy and operate a charging tenant

Use the public release tag v0.5.6, provision the bindings described in wrangler.toml, apply migrations in order, build the Worker and deploy with an operator-owned configuration. Carry the CPU limit into that configuration; the work limit comes from the build's source config. Keep the payment door closed until the release is reviewed for that tenant and the header service is bound and answering. A charging tenant needs a working HEADER_SERVICE binding or HEADER_SERVICE_URL, and a wallet storage service for fee internalization; a missing header service fails closed.

The archive queue (0.8.0). The Worker binds the queue relay-archive as its producer (ARCHIVE_QUEUE) and is its consumer; migration 0011 adds the version the consumer writes. Before deploying 0.8.0 the operator applies the migration and creates the queue, once each:

wrangler d1 migrations apply <your-d1-database> -c <your-config> --remote
wrangler queues create relay-archive

Nothing enqueues in 0.8.0: the consumer is ready for the release that moves the live mailbox into the recipient's hub, and every route still reads D1. A rollback to 0.7.1 is whole: 0.7.1 binds no queue and never reads the column.

The fee claims (0.8.12). Migration 0012 adds the table fee_claims and nothing else; it is forward only (nothing dropped or renamed). Apply it with the same wrangler d1 migrations apply before the Worker of 0.8.12 serves: a Worker without the table answers every send that owes a delivery fee 503 ERR_PAYMENT_UNAVAILABLE before the wallet is asked, and nothing is charged or stored.

A second environment (a beta Worker beside a production one) needs its own queue and its own consumer, because a queue has one consumer Worker and the consumer writes its batches through its own D1 binding: a shared queue would carry one environment's archive rows into the other's database. Wrangler does not inherit queue bindings into [env.*], so the operator creates wrangler queues create relay-archive-<env> and declares, under [env.<name>], a [[env.<name>.queues.producers]] block binding ARCHIVE_QUEUE to it and a [[env.<name>.queues.consumers]] block with the template's settings (max_batch_size = 100, max_batch_timeout = 2, max_retries = 3, retry_delay = 10). The template stays single-environment.

The listing's and the acknowledge's worst wait (message box #22). Each of the two is bounded on its own: a D1 read that stalls on every attempt costs 6,150 ms and answers 503 ERR_D1_UNAVAILABLE with Retry-After. A send that owes a delivery fee whose batch the store did not take answers 503 ERR_D1_UNAVAILABLE (with Retry-After) or 500 ERR_INTERNAL, by the store's own classification, saying the send was not stored (and, when the host's wallet took the payment in the request, that it did, and to send the same request again), and never the store's own words. A client that lists and then acknowledges may meet both bounds in a row, so its worst wait before either answer arrives is two bounds (and a listing whose box read answers slowly before its row read stalls is two reads in series, up to 12,300 ms).

The mailbox's class (0.8.1, R2 of the relay mailbox). The deploy carries the Durable Object migration v5, new_sqlite_classes = ["MessageHubSql"], and the binding MESSAGE_HUB_SQL; both are in the template and ship with the deploy, no command before it. A class lifecycle change refuses wrangler rollback across it, so the rollback of 0.8.1 is forward only: a deploy that keeps v5 and the class exported. Two operator vars, neither set in the template:

  • HUB_STORE names the hub store: kv (the default when unset) keeps every path of 0.8.0 (hub ids to MESSAGE_HUB, sends, listings and acknowledgments through D1) and no request reaches MessageHubSql; sql sends hub ids to MESSAGE_HUB_SQL, stores each unpaid send in the recipient hub's mailbox (bounded at 10,000 unacknowledged rows and 1 GiB per identity, past which a send answers 429 ERR_INBOX_QUOTA_EXCEEDED), and archives each change to D1 through relay-archive. A send that owes a delivery fee stores its rows in D1 with their claim, in one batch, as on every host; before the wallet is asked, each recipient's mailbox is asked whether it holds one of the send's message ids (400 ERR_DUPLICATE_MESSAGE) and whether it is at its bound (the 429), and nothing is charged or stored on either answer. Paid rows are not counted toward the bound; the hub lists them with its own rows and acknowledges them in D1; kv-drain, the rollback of sql, routes as kv and also lists and acknowledges the rows each identity's MessageHubSql still holds, and before the wallet asks each recipient's mailbox whether it holds one of a paid send's message ids (400 ERR_DUPLICATE_MESSAGE; not its bound, as no send stores a row there). Any other value refuses every request with 500 ERR_HUB_STORE_INVALID naming the var. A change of the var is a new version, not a class change, so wrangler rollback between two versions that both carry v5 stays allowed. A deploy restarts every hub and disconnects every socket.
  • BOXES_OFF is a comma-separated list of box names whose sends are refused 403 ERR_BOX_OFF ("box is off") before the send budget and before any store, on HTTP, on /push and on the socket; listings and acknowledgments of those boxes are served. Unset or empty, no box is off.

The code also reads names the template does not set: the BROADCAST_TOKEN secret (the bearer of /push, /broadcast and /session/attest), the BROADCAST_REGISTRY Durable Object (the /broadcast subscriber registry), ARC_URL and ARC_API_KEY (the broadcaster a verified payment is announced to once the send is stored; its word is written into the rows that carry the payment, payment.announced), and RETAIN_BOX_PREFIXES (the transcript-retained box class). A deployment that uses those features declares them itself.

The ICE credentials of a WebRTC hand are off until TURN_CREDENTIALS = "on". The routes need the Cloudflare Realtime TURN key's id in TURN_KEY_ID (the operator's configuration, never the template) and its API token as a secret, beside SERVER_PRIVATE_KEY's:

wrangler secret put SERVER_PRIVATE_KEY
wrangler secret put TURN_KEY_API_TOKEN

POST /turn-credentials (an empty body or {}) answers {iceServers, expiresAt} for the authenticated identity, expiresAt in milliseconds since the epoch, counted from the start of the request to Cloudflare. A mint is charged, before Cloudflare is asked, to the hourly budgets in wrangler.toml (the identity, the source group from CF-Connecting-IP, the IPv6 /48, the Worker), all or none; a spent budget is 429 ERR_TURN_BUDGET naming it, and a Cloudflare failure is 502 ERR_TURN_PROVIDER with the charge standing. POST /turn-credentials/revoke {"username"} revokes a username its caller minted; any other is 404. Apply migration 0010 before deploying.

For bytes at rest, bind BEEF_BLOBS, configure presigning privately and retain the lifecycle policy for door-state/. Inline payments can be spooled to R2; large fee internalizations are deferred through fee_internalize. The wallet service must be able to read the referenced bucket and verify recipient metadata. Without an R2 binding, the inline door must finish in one request. Retry pending reads and unavailable headers; do not interpret a work decline as proof of invalidity. Cloudflare's request-body limit still applies before an inline request reaches the Worker.

An unverifiable WebSocket General closes the socket with code 1008 and reason authentication failed; reconnect. The client must reconnect, re-handshake on a fresh session and rejoin its rooms.

The source for these contracts is src/beef_door.rs, src/payments.rs and src/routes/send_message.rs. Licensed under MIT.

About

BSV peer-to-peer messaging service on Cloudflare Workers. Rust → WASM. 1:1 parity with message-box-server (TS) and go-messagebox-server. Live-verified byte-for-byte against messagebox.babbage.systems.

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages