Skip to content

feat(exchange): offers and trade messages over Nostr, no server needed - #162

Open
DimazzzZ wants to merge 22 commits into
mainfrom
feat/exchange-nostr
Open

DimazzzZ wants to merge 22 commits into
mainfrom
feat/exchange-nostr

Conversation

@DimazzzZ

@DimazzzZ DimazzzZ commented Nov 12, 2026 •

Copy link
Copy Markdown
Owner

The exchange needs a place where offers are listed and where the two sides of a trade talk. Until now that was a namehold-relay someone had to run, and nobody runs a public one, so a fresh install could not trade. With this change offers and trade messages go through public Nostr relays that independent people run: the exchange works out of the box and the project operates no server for it. A namehold-relay someone does run can still be entered in Exchange settings and is used instead; the watchtower stays a namehold-relay feature. Spec: docs/specs/2026-11-12-exchange-nostr-transport.md.

How it works

  • Offers are addressable events (kind 37491, d = offer id) whose content is the existing SignedOffer; each heartbeat publishes a new version with a 5-minute NIP-40 expiration. A withdrawal replaces the offer and asks relays to delete it (NIP-09).

  • Trade messages are regular events (kind 7491) whose content is the existing Envelope, encrypted to the recipient with NIP-44 v2.

  • Both are signed by the relay key that signs their content, and readers take an offer only from its maker's key and a message only from its sender's. A relay or a third party can fail to carry them, never forge, renew or withdraw someone else's.

  • The inbox reads back 15 minutes before its cursor, and hands each message to the trade step once: the stored cursor carries the ids of messages handed over, never of junk, so a re-read or a restart does not repeat them.

  • The client is a small NIP-01 implementation over tokio-tungstenite 0.28 with our rustls (ring) and the platform verifier. A publish counts when two relays take the event; a read when one answers. Every event read is checked against the read's own filter and its signature; a frame is at most 128 KiB, one relay's answer at most 4 MiB.

  • Settings: each network has a list of Nostr relays (wss:// only, no logins, confirmed in the secure window). The default on mainnet and testnet is six public relays; regtest and simnet have none.

  • The job and the commands reach the meeting point through one trait, MeetingPoint, whose writes carry the signing key; the watchtower is its own trait.

  • The offer's secure window names where it is published ("Published on": the custom relay, or "Nostr relays" and their list); before, over Nostr, it showed an empty relay.

  • A relay that refused the connection is named in the refusal ("refused the connection (is it running?)"): the page's error mapping turned "Connection refused" into a generic sentence that hid how many relays took the event.

  • Claims and refunds no longer wait on the meeting point. The exchange step read the inboxes and renewed the offers before it stepped the trades; over Nostr each call waits for the slowest relay (up to 25 s when one of the six defaults never answers), so a profile's claims could come minutes late. The step now runs the trades first, then the meeting point within 90 s a tick (the inboxes in turn), and steps again only when messages arrived.

  • A trade's Commit is no longer refused by a sync that changed nothing. Every step rewrote every open trade, moving its version, and the Commit stores only if the version did not move while its secure window was open, so a window open across a sync was refused with "nothing was sent: … changed while the window was open". This came with the exchange (feat(exchange): trade HNS and BTC by atomic swap (beta) #161); a step now writes a trade only when it changed something.

QA

New cases in docs/qa/scenarios/exchange/nostr.md, written so another agent can run them on the regtest stand: the Nostr relays in settings and their secure window (E41), an offer's events from publication to withdrawal (E42), encrypted and addressed trade messages (E43), each message handled once across a restart (E44), relays going down and the quorum (E45), a custom relay in place of Nostr (E46), a whole trade over Nostr (E40), and the public defaults before a release (E47, only with the maintainer's agreement). The procedure docs/qa/procedures/nostr-relay.md starts local relays with scripts/nostr-relay.sh (strfry in Docker, pinned by digest) and reads them with scripts/nostr-req.mjs (read-only). The stand was checked: three local relays took, served, replaced and deleted offers and took a burst of writes. The cases were then run in the app on the regtest stand (build 76721eb), with three local relays:

  • E40 ✅ A whole trade over Nostr with the custom relay empty: terms agreed in about a minute, both sides committed, the Buyer's HNS claim revealed the secret, the Seller's BTC claim used it, and both cards read "Trade complete". The amounts matched the secure windows: the Buyer paid the 60000 sats and 306-sat fee its window showed and received exactly its You receive HNS at its address; the Seller locked exactly 5 HNS and its BTC balance grew by the 58460 sats its window showed. The relay's log took no offer and no message during the trade, only the two watchtower jobs.
  • E41 ✅ Settings texts, the three validation refusals and the secure window rows. E42 ✅ An offer's event on all three relays, authored by the maker key, replaced in place by the heartbeat, deleted from all of them on withdrawal. E44 ✅ Each message handled once, across an app and daemon restart. E45 ✅ One relay down changes nothing; two down give the exact refusal naming both, and the offers come back on their own. E46 ✅ A custom relay replaces Nostr, and the window says which one is used.
  • E43 ◐ Messages are addressed and unreadable on the relays; two toasts were not captured. E47 (public relays) was not run.

The first run found no bug in the app; a recheck of the money paths (below) found the Commit refusal fixed above. It corrected three mistakes in the cases themselves (a check that matched the regtest tag, a wrong expectation about the first offer under a 2-relay outage, and database reads that missed the WAL).

A recheck on the build with both fixes, over the local Nostr relays: E20 ✅ the Seller never confirms; no BTC refund while the Bitcoin median time is 10 minutes short of the refund time, then the refund 22 s after it passes, to the address the Buyer's window showed, and a second such refund 27 s after its time. E18 ✅ with the app closed the daemon read the Buyer's announcement, then sent both claims after the Seller's Commit (the same secret, the amounts and addresses of the windows), and both trades completed. wss:// from the daemon ✅ with wss://relay.primal.net as the only relay and the app closed, the daemon published the offer over TLS within a minute. Every Commit on this build stored on its first press. Ten full test runs under a watchdog: none hung.

Checked

  • cargo test --lib: 4402 passed (earlier, 4401 four runs in a row); the exchange tests passed 25 runs in a row. Frontend: 2123 tests; pnpm build, clippy, fmt, cargo audit and prettier are clean.
  • NIP-01 serialisation against a real note read from a public relay; NIP-44 v2 against the official test vectors (their SHA-256 is the one NIP-44 publishes). Plaintexts are 1–65535 bytes, as in the vectors.
  • Fake-relay tests for the quorum, refused and silent and dropped connections, filters and byte caps, the author binding, withdrawal on relays that ignore NIP-09, once-only delivery and the cursor; a job step announces a lock over Nostr, readable only by the two sides. Mutation checks on the author binding, the withdrawal, the deduplication and NIP-44.
  • live_exchange_nostr (gated by HNS_IT_NOSTR=1) published short-lived test events from throwaway keys to candidate relays. The defaults are the six that took and served both kinds, replaced and listed offers, and took a burst of writes: relay.primal.net, offchain.pub, nostr.bitcoiner.social, relay.nostr.net, nostr.oxtr.dev, relay.mostro.network. relay.damus.io (HTTP 503), nos.lol and nostr.mom (no answer to these kinds) failed on two runs each and are not defaults.
  • An automated security review raised five issues during the work, each fixed with a test that failed first: the byte bound per relay, the filter re-check, once-only delivery (a re-read declined take spent another pooled hash each time), junk moving the cursor, and junk evicting handled ids.

Not checked

  • The older live trade tests (live_exchange_e2e); they need the local regtest chain rolled back before they run again.
  • In E40: the toasts, the notifications and the HNS wallet balances (the HNS amounts were checked in the transactions instead), and the rows of the Seller's window that was confirmed. A first Seller window, read in full, became unreachable when the screen locked; the second one was confirmed unread, and its claim paid the same amount to the Seller's next BTC address, as a window closed without confirming leaves its addresses used.
  • One full local test run spun for a long time and was stopped; it did not happen again in four full runs and 25 runs of the exchange tests, and its cause was not found.

…ral Nostr relays

A publish counts when min(2, relays) relays answer OK true, a read when at least one relay ends with EOSE; every event read is checked and duplicates across relays are dropped. Relays are asked at once, each with a connect and an answer timeout, so a dead or silent relay costs one timeout, not one per relay. TLS is our rustls with the ring provider passed explicitly and the platform verifier; frames are capped at 1 MiB.

tokio-tungstenite 0.28 rather than 0.30: 0.30 brings a second RustCrypto generation (digest 0.11, sha1 0.11) and rand 0.10 into the tree, 0.28 adds four lockfile entries. Tests run against a fake NIP-01 relay on 127.0.0.1 that can accept, refuse, stay silent or serve forged events.
…nly so much

Every event a relay sends is now checked against the read's own filter (kinds, authors, ids, since, until, one-letter tags) and its signature as it arrives, so a relay cannot slip in events of another kind, author or tag. A frame is at most 128 KiB and one relay's answer to one read at most 4 MiB; past that the rest is not read. Before, a count of 1,000 events of up to 1 MiB each bounded nothing useful. Found by an automated security review of the previous commit.
Offers are addressable Nostr events (kind 37491) and trade messages NIP-44-encrypted regular events (kind 7491), both signed by the relay key that signs their content; the content is the SignedOffer or Envelope a namehold-relay received before. Readers take an offer only from its maker's key and a message only from its sender's, so a copied offer cannot be listed, renewed or hidden by anyone else. A withdrawal replaces the offer and asks relays to delete it; it hides the offer on relays that ignore deletions too.

The job and the commands now reach the meeting point through one trait, MeetingPoint, whose writes carry the signing key; the watchtower is its own trait. The meeting point is a custom relay when one is set, otherwise the Nostr relays of the network's settings, which default on mainnet and testnet to six public relays that the live check found taking and serving both kinds. Exchange settings get a Nostr relays field (wss:// only, no logins, confirmed in the secure window) and the custom relay becomes optional.
… move the inbox cursor

The inbox reads back 900 s before its cursor, so the same events came again on the next steps, and the job handled a message once per read: a declined take, for one, spent another pooled hash each time. The stored cursor now carries the ids of the events in the window the next read covers (nostr:<time>:<id>,…, at most 500), so each is handed over once, after a restart too.

The cursor's time now moves only with a message that was handed over: before, any event addressed to the key by its p tag, which anyone can publish with any date, moved it forward and could push a late real message out of the window. Both found by an automated security review of the transport commit.
… ids out of its cursor

The cursor kept the ids of every event in the window the next read covers, newest first, at most 500. Anyone can address events to a key, dated up to 15 minutes ahead, so 500 of them evicted the ids of real messages already handed over, and those were handed over again on a later read. The cursor now keeps only the ids of messages handed over, this read or before, ranked by a time no later than now; junk never enters it. Found by an automated security review of the previous commit.

A test also checks that a relay dropping the connection mid-answer ends the call with that relay counted as failed.
…ne the job already announced in this process
@github-actions github-actions Bot added domain: infra CI/CD, build, sidecar packaging, updater, DB migrations, deps. type: feature New feature or enhancement. labels Nov 12, 2026
@DimazzzZ DimazzzZ self-assigned this Nov 12, 2026
…en behind a generic error

The client passed on the socket's own error, "IO error: Connection refused (os error 61)", and the page's error mapping turns any message containing "connection refused" into "Couldn't reach the configured endpoint". A publish refused because a Nostr relay was down therefore lost its whole explanation: how many relays took the event and which did not. The client now says "refused the connection (is it running?)"; a test of the mapping checks the count and each relay reach the page.
… Nostr relays included

The publication window showed the custom relay's URL under "Relay"; with the Nostr relays as the meeting point that URL is empty, so the user confirmed a publication without seeing where it went. The row is now "Published on": the custom relay's URL, or "Nostr relays" and their list.
scripts/nostr-relay.sh starts one to three strfry relays in Docker on 127.0.0.1:7777 and up (image pinned by digest, data in the git-ignored .regtest/nostr), with the image's config changed to listen inside the container, which its default of 127.0.0.1 does not allow through a published port. scripts/nostr-req.mjs reads events from a relay with one REQ and prints them; it never sends an event. Checked on 2026-11-12: three relays started and live_exchange_nostr against them took, served, replaced and deleted offers and took a burst of 20 writes on each.
…r-relay procedure

A new scenario file covers what the Nostr transport changes: the Nostr relays in Exchange settings and their secure window (E41), an offer's events from publication through renewal to withdrawal (E42), encrypted and addressed trade messages (E43), each message handled once across a restart (E44), relays going down and the two-relay quorum (E45), a custom relay in place of Nostr (E46), a whole trade over Nostr (E40, moved from trades.md), and the check of the public default relays before a release (E47, only with the maintainer's agreement). The procedure nostr-relay starts the local relays and shows how to tie an offer in the run's database to its events. The index, run order and stand requirements name them; E10 expects the publication window's new "Published on" row.
Running E41–E45 on the stand found three mistakes in the cases themselves. E43's check for readable message bodies counted the "regtest" in each event's own tags (2 hits for 0 readable bodies); it now reads only the content field. E45 expected the first offer to stay Live with two relays down; its next heartbeat needs two relays as well, so both offers pause, with the quorum error stored. The database helpers read with -readonly: an immutable=1 read misses the WAL and showed a stale setting.
The exchange step read the inboxes and renewed the offers before it stepped the trades, so every claim and refund waited for the meeting point. Over Nostr each call waits for the slowest relay, up to 25 seconds when one of the six defaults never answers, once per live offer and once per open trade: with a few offers and trades the claims of that profile, and the steps of the profiles after it, came minutes late, and the step decided with the time taken before all that waiting.

The step now runs the trades first, then the meeting point, and steps again only when the meeting point handed messages over, so terms and lock announcements still move their trade in the same tick. The meeting point gets at most 90 seconds a tick (the call under way finishes); the inboxes are read in turn, starting each minute further along, so a slow relay cannot leave one trade's inbox unread for ever.
…hanged nothing

Every step of the background sync rewrote every open trade, and every write moves the trade's version. The Commit stores only if the trade is still the version it read before the secure window opened, so a window open across a step (every 60 s in the daemon, and on the app's own sync) was refused with "nothing was sent: this trade was confirmed already, or changed while the window was open". Found on the regtest stand: the Buyer's Commit failed on three tries in a row while the trade's version moved twice a minute with nothing new on either chain.

A step now writes a trade only when it changed its status, holdings, error, end time or finished flag. A Commit window open across a real change is still refused, as before.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

domain: infra CI/CD, build, sidecar packaging, updater, DB migrations, deps. type: feature New feature or enhancement.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant