Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
27a37387be | ||
|
|
d65d790a20 | ||
|
|
7d0820dd44 | ||
|
|
efaad8e734 | ||
|
|
1b4dcfe63e | ||
|
|
f7e8ed52bf | ||
|
|
399c5fe8c6 | ||
|
|
43e46dd8cc | ||
|
|
551de8039f | ||
|
|
a45d764eaa | ||
|
|
836254a4c6 | ||
|
|
93925b257c | ||
|
|
6ef38a6ee7 | ||
|
|
209f7826cb | ||
|
|
be58967a86 | ||
|
|
c9ebf72e80 | ||
|
|
2dff11a808 | ||
|
|
98391fd677 | ||
|
|
d32a25c988 | ||
|
|
b2bdade380 | ||
|
|
92598c2ddb | ||
|
|
84724bc03e | ||
|
|
91cb297e9e | ||
|
|
74a86043cc | ||
|
|
958de3bfca | ||
|
|
45b21ec1db | ||
|
|
aca1d9a462 | ||
|
|
056314396d | ||
|
|
df6c53f830 | ||
|
|
220371cec1 | ||
|
|
44898bf7f6 | ||
|
|
8e0b8de529 | ||
|
|
db3e98f13a | ||
|
|
8a1b5608bf | ||
|
|
e250a9ec9d | ||
|
|
376d6a261a | ||
|
|
9f9b6c8e88 | ||
|
|
24e464926e | ||
|
|
7d3cfa56d3 | ||
|
|
53bc0fe663 | ||
|
|
b981dcb70b |
@@ -24,6 +24,8 @@ jobs:
|
||||
- name: Clone project
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Build changelog
|
||||
id: build_changelog
|
||||
@@ -114,6 +116,8 @@ jobs:
|
||||
- name: Clone project
|
||||
if: matrix.should_run == true
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
if: matrix.should_run == true
|
||||
|
||||
@@ -20,6 +20,8 @@ jobs:
|
||||
steps:
|
||||
- name: Clone project
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: simplex-chat/docker-login-action@v3
|
||||
|
||||
@@ -11,6 +11,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Get latest release
|
||||
shell: bash
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
[submodule "cbits/libbbs"]
|
||||
path = cbits/libbbs
|
||||
url = https://github.com/simplex-chat/libbbs.git
|
||||
[submodule "cbits/blst"]
|
||||
path = cbits/blst
|
||||
url = https://github.com/supranational/blst.git
|
||||
@@ -1,210 +0,0 @@
|
||||
# simplexmq — LLM Navigation Guide
|
||||
|
||||
This file is the entry point for LLMs working on simplexmq. Read it before making any code changes.
|
||||
|
||||
## Three-Layer Architecture
|
||||
|
||||
simplexmq maintains three documentation layers alongside source code:
|
||||
|
||||
| Layer | Directory | Answers | Audience |
|
||||
|-------|-----------|---------|----------|
|
||||
| **Product** | `product/` | What does this do? Who uses it? What must never break? | Anyone reasoning about behavior, privacy, security |
|
||||
| **Spec** | `spec/` | How does the code work? What does each function do? What are the security invariants? | LLMs and developers modifying code |
|
||||
| **Protocol** | `protocol/` | What is the wire protocol? What are the message formats and state machines? | Protocol implementors, formal verification |
|
||||
|
||||
Additionally:
|
||||
- `rfcs/` — Protocol evolution: each RFC describes a delta to a protocol spec
|
||||
- `product/threat-model.md` — Comprehensive threat model across all protocols
|
||||
- `spec/security-invariants.md` — Every security invariant with enforcement and test coverage
|
||||
|
||||
## Navigation Workflow
|
||||
|
||||
When modifying code, follow this sequence:
|
||||
|
||||
1. **Identify scope** — Find the relevant component in `product/concepts.md`
|
||||
2. **Load product context** — Read the component file in `product/components/` to understand what users depend on
|
||||
3. **Load spec context** — Read the relevant `spec/` file(s) for implementation details and call graphs
|
||||
4. **Check security** — Read `spec/security-invariants.md` for any invariants enforced by the code you're changing
|
||||
5. **Load source** — Read the actual source files referenced in spec/
|
||||
6. **Identify impact** — Trace the call graph to understand what your change affects
|
||||
7. **Implement** — Make the change
|
||||
8. **Update all layers** — Update spec/, product/, and protocol/ (if wire protocol changed) to stay coherent
|
||||
|
||||
## Protocol Specifications
|
||||
|
||||
Consolidated protocol specs live in `protocol/`. These describe the wire protocols as originally specified. Code has advanced beyond these versions — Phase 2 of this project will synchronize them.
|
||||
|
||||
| File | Protocol | Spec version | Code version |
|
||||
|------|----------|-------------|--------------|
|
||||
| `simplex-messaging.md` | SMP (simplex messaging) | v9 | SMP relay v18, SMP client v4 |
|
||||
| `agent-protocol.md` | Agent (duplex connections) | v5 | Agent v7 |
|
||||
| `xftp.md` | XFTP (file transfer) | v2 | XFTP v3 |
|
||||
| `xrcp.md` | XRCP (remote control) | v1 | RCP v1 |
|
||||
| `push-notifications.md` | Push notifications | v2 | NTF v3 |
|
||||
| `pqdr.md` | PQDR (post-quantum double ratchet) | v1 | E2E v3 |
|
||||
| `overview-tjr.md` | Cross-protocol overview | — | — |
|
||||
|
||||
Note: SMP has multiple version axes — `VersionSMP` (relay/transport, currently 18), `VersionSMPC` (client protocol, currently 4), and `VersionSMPA` (agent, currently 7). These are negotiated independently.
|
||||
|
||||
Protocol specs are amended in place when implementation changes. RFCs in `rfcs/` track the evolution history.
|
||||
|
||||
## Source Structure
|
||||
|
||||
```
|
||||
src/Simplex/
|
||||
Messaging/
|
||||
Protocol.hs, Protocol/Types.hs — SMP wire protocol types + encoding
|
||||
Client.hs — SMP client (protocol operations, proxy relay)
|
||||
Client/Agent.hs — Low-level async SMP agent
|
||||
Server.hs — SMP server request handling
|
||||
Server/Env/STM.hs — Server environment + STM state
|
||||
Server/Main.hs, Server/Main/Init.hs — Server CLI + initialization
|
||||
Server/QueueStore/ — Queue storage (STM, Postgres)
|
||||
Server/MsgStore/ — Message storage (STM, Journal, Postgres)
|
||||
Server/MsgStore/Journal.hs — Journal message store (1000 lines)
|
||||
Server/StoreLog/ — Store log (append-only write, read-compact-rewrite restore)
|
||||
Server/NtfStore.hs — Message notification store
|
||||
Server/Control.hs, Server/CLI.hs — Control protocol + CLI utilities
|
||||
Server/Stats.hs, Server/Prometheus.hs — Metrics
|
||||
Server/Information.hs — Server public information / metadata
|
||||
Agent.hs — SMP agent: duplex connections, queue rotation
|
||||
Agent/Client.hs — Agent's SMP/XFTP/NTF client management
|
||||
Agent/Protocol.hs — Agent wire protocol types + encoding (2200 lines)
|
||||
Agent/Store.hs — Agent storage types (queues, connections, messages)
|
||||
Agent/Store/AgentStore.hs — Agent storage implementation (3500 lines)
|
||||
Agent/Store/ — Agent storage backends (SQLite, Postgres)
|
||||
Agent/Env/SQLite.hs — Agent environment + configuration
|
||||
Agent/NtfSubSupervisor.hs — Notification subscription management
|
||||
Agent/TSessionSubs.hs — Transport session subscriptions
|
||||
Agent/Stats.hs — Agent statistics
|
||||
Agent/RetryInterval.hs — Retry interval logic
|
||||
Agent/Lock.hs — Named locks
|
||||
Agent/QueryString.hs — Query string parsing
|
||||
Transport.hs — TLS transport abstraction + handshake
|
||||
Transport/Client.hs, Transport/Server.hs — TLS client + server
|
||||
Transport/HTTP2.hs — HTTP/2 transport setup
|
||||
Transport/HTTP2/Client.hs — HTTP/2 client
|
||||
Transport/HTTP2/Server.hs — HTTP/2 server
|
||||
Transport/HTTP2/File.hs — HTTP/2 file streaming
|
||||
Transport/WebSockets.hs — WebSocket adapter
|
||||
Transport/Buffer.hs — Transport buffering
|
||||
Transport/KeepAlive.hs — TCP keepalive
|
||||
Transport/Shared.hs — Certificate chain validation
|
||||
Transport/Credentials.hs — TLS credential generation
|
||||
Crypto.hs — All cryptographic primitives
|
||||
Crypto/File.hs — File encryption (NaCl secret box + lazy)
|
||||
Crypto/Lazy.hs — Lazy hashing + encryption
|
||||
Crypto/Ratchet.hs — Double ratchet + PQDR
|
||||
Crypto/ShortLink.hs — Short link key derivation
|
||||
Crypto/SNTRUP761.hs — Post-quantum KEM hybrid secret
|
||||
Crypto/SNTRUP761/Bindings.hs — sntrup761 C FFI bindings
|
||||
Notifications/Protocol.hs — NTF wire protocol types + encoding
|
||||
Notifications/Types.hs — NTF agent types (tokens, subscriptions)
|
||||
Notifications/Transport.hs — NTF transport handshake
|
||||
Notifications/Client.hs — NTF client operations
|
||||
Notifications/Server.hs — NTF server
|
||||
Notifications/Server/Env.hs — NTF server environment + config
|
||||
Notifications/Server/Store.hs — NTF server storage (STM)
|
||||
Notifications/Server/Store/Postgres.hs — NTF server storage (Postgres)
|
||||
Notifications/Server/Push/APNS.hs — Apple push notification integration
|
||||
Notifications/Server/Push/APNS/Internal.hs — APNS HTTP/2 client
|
||||
Notifications/Server/Main.hs — NTF server CLI
|
||||
Notifications/Server/Stats.hs — NTF server metrics
|
||||
Notifications/Server/Prometheus.hs — NTF Prometheus metrics
|
||||
Notifications/Server/Control.hs — NTF server control
|
||||
Encoding.hs, Encoding/String.hs — Binary + string encoding
|
||||
Version.hs, Version/Internal.hs — Version ranges + negotiation
|
||||
Util.hs — Utilities (error handling, STM, grouping)
|
||||
Parsers.hs — Attoparsec parser combinators
|
||||
TMap.hs — Transactional map (STM)
|
||||
Compression.hs — Zstd compression
|
||||
ServiceScheme.hs — Service scheme + server location types
|
||||
Session.hs — Session variables (TVar-based)
|
||||
SystemTime.hs — Rounded system time types
|
||||
FileTransfer/
|
||||
Protocol.hs — XFTP wire protocol types + encoding
|
||||
Client.hs — XFTP client operations
|
||||
Client/Agent.hs — XFTP client agent (connection pooling)
|
||||
Client/Main.hs — XFTP CLI client implementation
|
||||
Client/Presets.hs — Default XFTP servers
|
||||
Server.hs — XFTP server request handling
|
||||
Server/Env.hs — XFTP server environment + config
|
||||
Server/Store.hs — XFTP server storage
|
||||
Server/StoreLog.hs — XFTP server store log
|
||||
Server/Main.hs — XFTP server CLI
|
||||
Server/Stats.hs — XFTP server metrics
|
||||
Server/Prometheus.hs — XFTP Prometheus metrics
|
||||
Server/Control.hs — XFTP server control
|
||||
Agent.hs — XFTP agent operations
|
||||
Description.hs — File description format
|
||||
Transport.hs — XFTP transport
|
||||
Crypto.hs — File encryption for transfer
|
||||
Types.hs — File transfer types
|
||||
Chunks.hs — Chunk sizing
|
||||
RemoteControl/
|
||||
Client.hs — XRCP client (ctrl device)
|
||||
Invitation.hs — XRCP invitation handling
|
||||
Discovery.hs — Local network discovery
|
||||
Discovery/Multicast.hsc — Multicast discovery (C FFI)
|
||||
Types.hs — XRCP types + version
|
||||
|
||||
apps/
|
||||
smp-server/Main.hs — SMP server executable
|
||||
smp-server/web/Static.hs — SMP server web static files
|
||||
xftp-server/Main.hs — XFTP server executable
|
||||
xftp/Main.hs — XFTP CLI executable
|
||||
ntf-server/Main.hs — Notification server executable
|
||||
smp-agent/Main.hs — SMP agent (experimental, not in cabal)
|
||||
```
|
||||
|
||||
## Linking Conventions
|
||||
|
||||
### spec → src
|
||||
Fully qualified exported function names inline in prose: `Simplex.Messaging.Client.connectSMPProxiedRelay`. Use Grep/Glob to locate in source. For app targets: `xftp/Main.main`.
|
||||
|
||||
### src → spec
|
||||
Comment above function:
|
||||
```haskell
|
||||
-- spec/crypto-tls.md#certificate-chain-validation
|
||||
-- Validates relay certificate chain to prevent proxy MITM (SI-XX)
|
||||
connectSMPProxiedRelay :: ...
|
||||
```
|
||||
|
||||
### spec ↔ spec
|
||||
Named markdown heading anchors: `spec/crypto.md#ed25519-signing`
|
||||
|
||||
### spec ↔ product
|
||||
Cross-references: `product/rules.md#pr-05`, `spec/security-invariants.md#si-01`
|
||||
|
||||
### protocol/ references
|
||||
`protocol/simplex-messaging.md` with section name
|
||||
|
||||
## Build Flags
|
||||
|
||||
simplexmq builds with several flag combinations:
|
||||
|
||||
| Flag | Effect |
|
||||
|------|--------|
|
||||
| (none) | Default: SQLite storage, all executables |
|
||||
| `-fserver_postgres` | Postgres backend for SMP server |
|
||||
| `-fclient_postgres` | Postgres backend for agent storage |
|
||||
| `-fclient_library` | Library-only build (no server executables) |
|
||||
| `-fswift` | Swift JSON format for mobile bindings |
|
||||
| `-fuse_crypton` | Use crypton in cryptostore |
|
||||
|
||||
All flag combinations must compile with `--enable-tests`. Verify with:
|
||||
```
|
||||
cabal build all --ghc-options="-O0" [-flags] [--enable-tests]
|
||||
```
|
||||
|
||||
## Change Protocol
|
||||
|
||||
Every code change must maintain coherence across all three layers:
|
||||
|
||||
1. **Code change** — Implement in src/
|
||||
2. **Spec update** — Update the relevant spec/ file(s): types, call graphs, security notes
|
||||
3. **Product update** — If user-visible behavior changed, update product/ files
|
||||
4. **Protocol update** — If wire protocol changed, amend protocol/ spec (requires user approval)
|
||||
5. **Security check** — If the change touches a trust boundary, update spec/security-invariants.md
|
||||
|
||||
Protocol spec amendments require explicit user approval before committing.
|
||||
@@ -1,79 +1,86 @@
|
||||
# SimpleX Network
|
||||
# SimpleXMQ
|
||||
|
||||
[](https://github.com/simplex-chat/simplexmq/actions/workflows/build.yml)
|
||||
[](https://github.com/simplex-chat/simplexmq/releases)
|
||||
|
||||
The simplexmq package provides the software for [SimpleX Network](./protocol/overview-tjr.md) — a general-purpose packet routing network where endpoints exchange data through independently operated routers using resource-based addressing. Unlike IP networks, SimpleX addresses identify resources on routers (queues, data packets), not endpoint devices. Participants do not need globally unique identifiers to communicate.
|
||||
📢 SimpleXMQ v1 is released - with many security, privacy and efficiency improvements, new functionality - see [release notes](https://github.com/simplex-chat/simplexmq/releases/tag/v1.0.0).
|
||||
|
||||
The software is organized in three layers:
|
||||
**Please note**: v1 is not backwards compatible, but it has the version negotiation built into all protocol layers for forwards compatibility of this version and backwards compatibility of the future versions, that will be backwards compatible for at least two versions back.
|
||||
|
||||
```
|
||||
Application (e.g. SimpleX Chat)
|
||||
+----------------------------------+
|
||||
| SimpleX Agent | Layer 3 — duplex connections, e2e encryption
|
||||
+----------------------------------+
|
||||
| SimpleX Client Libraries | Layer 2 — protocol clients for SMP, XFTP
|
||||
+----------------------------------+
|
||||
| SimpleX Routers | Layer 1 — network infrastructure (SMP, XFTP, NTF)
|
||||
+----------------------------------+
|
||||
If you have a server deployed please deploy a new server to a new host and retire the previous version once it is no longer used.
|
||||
|
||||
## Message broker for unidirectional (simplex) queues
|
||||
|
||||
SimpleXMQ is a message broker for managing message queues and sending messages over public network. It consists of SMP server, SMP client library and SMP agent that implement [SMP protocol](./protocol/simplex-messaging.md) for client-server communication and [SMP agent protocol](./protocol/agent-protocol.md) to manage duplex connections via simplex queues on multiple SMP servers.
|
||||
|
||||
SMP protocol is inspired by [Redis serialization protocol](https://redis.io/topics/protocol), but it is much simpler - it currently has only 10 client commands and 8 server responses.
|
||||
|
||||
SimpleXMQ is implemented in Haskell - it benefits from robust software transactional memory (STM) and concurrency primitives that Haskell provides.
|
||||
|
||||
## SimpleXMQ roadmap
|
||||
|
||||
- SimpleX service protocol and application template - to enable users building services and chat bots that work over SimpleX protocol stack. The first such service will be a notification service for a mobile app.
|
||||
- SMP queue redundancy and rotation in SMP agent connections.
|
||||
- SMP agents synchronization to share connections and messages between multiple agents (it would allow using multiple devices for [simplex-chat](https://github.com/simplex-chat/simplex-chat)).
|
||||
|
||||
## Components
|
||||
|
||||
### SMP server
|
||||
|
||||
[SMP server](./apps/smp-server/Main.hs) can be run on any Linux distribution, including low power/low memory devices. OpenSSL library is required for initialization.
|
||||
|
||||
To initialize the server use `smp-server init -n <fqdn>` (or `smp-server init --ip <ip>` for IP based address) command - it will generate keys and certificates for TLS transport. The fingerprint of offline certificate is used as part of the server address to protect client/server connection against man-in-the-middle attacks: `smp://<fingerprint>@<hostname>[:5223]`.
|
||||
|
||||
SMP server uses in-memory persistence with an optional append-only log of created queues that allows to re-start the server without losing the connections. This log is compacted on every server restart, permanently removing suspended and removed queues.
|
||||
|
||||
To enable store log, initialize server using `smp-server -l` command, or modify `smp-server.ini` created during initialization (uncomment `enable = on` option in the store log section). Use `smp-server --help` for other usage tips.
|
||||
|
||||
Starting from version 2.3.0, when store log is enabled, the server would also enable saving undelivered messages on exit and restoring them on start. This can be disabled via a separate setting `restore_messages` in `smp-server.ini` file. Saving messages would only work if the server is stopped with SIGINT signal (keyboard interrupt), if it is stopped with SIGTERM signal the messages would not be saved.
|
||||
|
||||
> **Please note:** On initialization SMP server creates a chain of two certificates: a self-signed CA certificate ("offline") and a server certificate used for TLS handshake ("online"). **You should store CA certificate private key securely and delete it from the server. If server TLS credential is compromised this key can be used to sign a new one, keeping the same server identity and established connections.** CA private key location by default is `/etc/opt/simplex/ca.key`.
|
||||
|
||||
SMP server implements [SMP protocol](./protocol/simplex-messaging.md).
|
||||
|
||||
#### Running SMP server on MacOS
|
||||
|
||||
SMP server requires OpenSSL library for initialization. On MacOS OpenSSL library may be replaced with LibreSSL, which doesn't support required algorithms. Before initializing SMP server verify you have OpenSSL installed:
|
||||
|
||||
```sh
|
||||
openssl version
|
||||
```
|
||||
|
||||
[SimpleX Chat](https://github.com/simplex-chat/simplex-chat) is one application built on Layer 3. IoT devices, AI services, monitoring systems, and automated services are other applications that can use Layers 2 or 3 directly.
|
||||
If it says "LibreSSL", please install original OpenSSL:
|
||||
|
||||
The simplexmq package is implemented in Haskell, benefiting from robust software transactional memory (STM) and concurrency primitives.
|
||||
```sh
|
||||
brew update
|
||||
brew install openssl
|
||||
echo 'PATH="/opt/homebrew/opt/openssl@3/bin:$PATH"' >> ~/.zprofile # or follow whatever instructions brew suggests
|
||||
. ~/.zprofile # or restart your terminal to start a new session
|
||||
```
|
||||
|
||||
See the [SimpleX Network overview](./protocol/overview-tjr.md) for the full protocol architecture, trust model, and [security analysis](./protocol/security.md).
|
||||
Now `openssl version` should be saying "OpenSSL". You can now run `smp-server init` to initialize your SMP server.
|
||||
|
||||
## Architecture
|
||||
### SMP client library
|
||||
|
||||
### SimpleX Routers
|
||||
[SMP client](./src/Simplex/Messaging/Client.hs) is a Haskell library to connect to SMP servers that allows to:
|
||||
|
||||
Routers are the network infrastructure — they accept, buffer, and deliver packets. Three router types serve different purposes:
|
||||
- execute commands with a functional API.
|
||||
- receive messages and other notifications via STM queue.
|
||||
- automatically send keep-alive commands.
|
||||
|
||||
- **SMP routers** provide messaging queues — unidirectional, ordered sequences of fixed-size packets (16,384 bytes). Protocol: [SMP](./protocol/simplex-messaging.md). Module spec: [`Simplex.Messaging.Server`](./spec/modules/Simplex/Messaging/Server.md).
|
||||
- **XFTP routers** accept and deliver data packets over HTTP/2 — individually addressed blocks in fixed sizes (64KB–4MB) for larger payloads. Protocol: [XFTP](./protocol/xftp.md). Module spec: [`Simplex.FileTransfer.Server`](./spec/modules/Simplex/FileTransfer/Server.md).
|
||||
- **NTF routers** bridge to platform push services (APNS) for mobile notification delivery. Protocol: [Push Notifications](./protocol/push-notifications.md). Module spec: [`Simplex.Messaging.Notifications.Server`](./spec/modules/Simplex/Messaging/Notifications/Server.md).
|
||||
### SMP agent
|
||||
|
||||
[SMP agent library](./src/Simplex/Messaging/Agent.hs) can be used to run SMP agent as part of another application and to communicate with the agent via STM queues, without serializing and parsing commands and responses.
|
||||
|
||||
#### Running an SMP router
|
||||
Haskell type [ACommand](./src/Simplex/Messaging/Agent/Protocol.hs) represents SMP agent protocol to communicate via STM queues.
|
||||
|
||||
[SMP server](./apps/smp-server/Main.hs) runs on any Linux distribution. OpenSSL is required for initialization.
|
||||
See [simplex-chat](https://github.com/simplex-chat/simplex-chat) terminal UI for the example of integrating SMP agent into another application.
|
||||
|
||||
Initialize: `smp-server init -n <fqdn>` (or `--ip <ip>`). This generates TLS certificates. The CA certificate fingerprint becomes part of the server address: `smp://<fingerprint>@<hostname>[:5223]`.
|
||||
[SMP agent executable](./apps/smp-agent/Main.hs) can be used to run a standalone SMP agent process that implements plaintext [SMP agent protocol](./protocol/agent-protocol.md) via TCP port 5224, so it can be used via telnet. It can be deployed in private networks to share access to the connections between multiple applications and services.
|
||||
|
||||
By default, the server uses in-memory persistence with an optional append-only store log for queue persistence across restarts. Enable with `smp-server init -l` or in `smp-server.ini`. The log is compacted on every restart.
|
||||
## Using SMP server and SMP agent
|
||||
|
||||
When store log is enabled, undelivered messages are saved on exit (SIGINT only, not SIGTERM) and restored on start. Control this independently with the `restore_messages` setting.
|
||||
|
||||
> **Please note:** On initialization, SMP server creates a certificate chain: a self-signed CA certificate ("offline") and a server certificate for TLS ("online"). **Store the CA private key securely and delete it from the server.** If the server TLS credential is compromised, this key can sign a new one while keeping the same server identity. Default location: `/etc/opt/simplex/ca.key`.
|
||||
|
||||
See [docs/ROUTERS.md](./docs/ROUTERS.md) for XFTP/NTF router setup, advanced configuration, MacOS notes, and all deployment options (Docker, installation script, building from source, Linode, DigitalOcean).
|
||||
|
||||
### SimpleX Client Libraries
|
||||
|
||||
[Client libraries](./docs/CLIENT.md) provide low-level protocol access to SimpleX routers. They implement the wire protocols (SMP, XFTP, NTF) and handle connection lifecycle, command authentication, and keep-alive.
|
||||
|
||||
The [SMP client](./src/Simplex/Messaging/Client.hs) ([module spec](./spec/modules/Simplex/Messaging/Client.md)) offers a functional Haskell API with STM queues for asynchronous event delivery. The [XFTP client](./src/Simplex/FileTransfer/Client.hs) ([module spec](./spec/modules/Simplex/FileTransfer/Client.md)) sends and receives data packets over HTTP/2 with per-request forward secrecy. The [NTF client](./src/Simplex/Messaging/Notifications/Client.hs) ([module spec](./spec/modules/Simplex/Messaging/Notifications/Client.md)) manages push notification tokens and subscriptions.
|
||||
|
||||
Applications that manage their own encryption and connection logic — IoT devices, sensors, simple data pipelines — can use this layer directly. See [docs/CLIENT.md](./docs/CLIENT.md).
|
||||
|
||||
### SimpleX Agent
|
||||
|
||||
The [Agent](./docs/AGENT.md) builds duplex encrypted connections on top of the client libraries. It manages:
|
||||
|
||||
- Duplex connections from simplex queue pairs
|
||||
- End-to-end encryption with double ratchet and post-quantum extensions
|
||||
- File transfer with chunking, encryption, and multi-router distribution
|
||||
- Queue rotation for metadata privacy
|
||||
- Push notification subscriptions
|
||||
|
||||
The [Agent library](./src/Simplex/Messaging/Agent.hs) ([module spec](./spec/modules/Simplex/Messaging/Agent.md)) communicates via STM queues using the [ACommand](./src/Simplex/Messaging/Agent/Protocol.hs) type — no serialization needed. The Agent implements the [Agent protocol](./protocol/agent-protocol.md) for duplex connections and uses the [PQDR protocol](./protocol/pqdr.md) for end-to-end encryption. Cross-device remote control uses the [XRCP protocol](./protocol/xrcp.md).
|
||||
|
||||
See [docs/AGENT.md](./docs/AGENT.md).
|
||||
|
||||
## Quick start
|
||||
|
||||
Public SMP routers for testing:
|
||||
You can either run your own SMP server locally or deploy using [Linode StackScript](https://cloud.linode.com/stackscripts/748014), or try local SMP agent with the deployed servers:
|
||||
|
||||
`smp://u2dS9sG8nMNURyZwqASV4yROM28Er0luVTx5X1CsMrU=@smp4.simplex.im`
|
||||
|
||||
@@ -81,16 +88,233 @@ Public SMP routers for testing:
|
||||
|
||||
`smp://PQUV2eL0t7OStZOoAsPEV2QYWt4-xilbakvGUGOItUo=@smp6.simplex.im`
|
||||
|
||||
## Deploy routers
|
||||
It's the easiest to try SMP agent via a prototype [simplex-chat](https://github.com/simplex-chat/simplex-chat) terminal UI.
|
||||
|
||||
You can run SMP/XFTP routers on any Linux distribution. OpenSSL is required:
|
||||
## Deploy SMP/XFTP servers on Linux
|
||||
|
||||
You can run your SMP/XFTP server as a Linux process, optionally using a service manager for booting and restarts.
|
||||
|
||||
Notice that `smp-server` and `xftp-server` requires `openssl` as run-time dependency (it is used to generate server certificates during initialization). Install it with your packet manager:
|
||||
|
||||
```sh
|
||||
# Ubuntu
|
||||
# For Ubuntu
|
||||
apt update && apt install openssl
|
||||
```
|
||||
|
||||
See [docs/ROUTERS.md](./docs/ROUTERS.md) for Docker, binary installation, building from source, and cloud deployment (Linode, DigitalOcean).
|
||||
### Install binaries
|
||||
|
||||
#### Using Docker
|
||||
|
||||
On Linux, you can deploy smp and xftp server using Docker. This will download image from [Docker Hub](https://hub.docker.com/r/simplexchat).
|
||||
|
||||
1. Create directories for persistent Docker configuration:
|
||||
|
||||
```sh
|
||||
mkdir -p $HOME/simplex/{xftp,smp}/{config,logs} && mkdir -p $HOME/simplex/xftp/files
|
||||
```
|
||||
|
||||
2. Run your Docker container.
|
||||
|
||||
- `smp-server`
|
||||
|
||||
You must change **your_ip_or_domain**. `-e "pass=password"` is optional variable to password-protect your `smp` server:
|
||||
```sh
|
||||
docker run -d \
|
||||
-e "ADDR=your_ip_or_domain" \
|
||||
-e "PASS=password" \
|
||||
-p 5223:5223 \
|
||||
-v $HOME/simplex/smp/config:/etc/opt/simplex:z \
|
||||
-v $HOME/simplex/smp/logs:/var/opt/simplex:z \
|
||||
simplexchat/smp-server:latest
|
||||
```
|
||||
|
||||
- `xftp-server`
|
||||
|
||||
You must change **your_ip_or_domain** and **maximum_storage**.
|
||||
```sh
|
||||
docker run -d \
|
||||
-e "ADDR=your_ip_or_domain" \
|
||||
-e "QUOTA=maximum_storage" \
|
||||
-p 443:443 \
|
||||
-v $HOME/simplex/xftp/config:/etc/opt/simplex-xftp:z \
|
||||
-v $HOME/simplex/xftp/logs:/var/opt/simplex-xftp:z \
|
||||
-v $HOME/simplex/xftp/files:/srv/xftp:z \
|
||||
simplexchat/xftp-server:latest
|
||||
```
|
||||
|
||||
#### Using installation script
|
||||
|
||||
**Please note** that currently, only Ubuntu distribution is supported.
|
||||
|
||||
You can install and setup servers automatically using our script:
|
||||
|
||||
```sh
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/simplex-chat/simplexmq/stable/install.sh -o simplex-server-install.sh &&\
|
||||
if echo '53fcdb4ceab324316e2c4cda7e84dbbb344f32550a65975a7895425e5a1be757 simplex-server-install.sh' | sha256sum -c; then
|
||||
chmod +x ./simplex-server-install.sh
|
||||
./simplex-server-install.sh
|
||||
rm ./simplex-server-install.sh
|
||||
else
|
||||
echo "SHA-256 checksum is incorrect!"
|
||||
rm ./simplex-server-install.sh
|
||||
fi
|
||||
```
|
||||
|
||||
### Build from source
|
||||
|
||||
#### Using Docker
|
||||
|
||||
> **Please note:** to build the app use source code from [stable branch](https://github.com/simplex-chat/simplexmq/tree/stable).
|
||||
|
||||
On Linux, you can build smp server using Docker.
|
||||
|
||||
1. Build your images:
|
||||
|
||||
```sh
|
||||
git clone https://github.com/simplex-chat/simplexmq
|
||||
cd simplexmq
|
||||
git checkout stable
|
||||
DOCKER_BUILDKIT=1 docker build -t local/smp-server --build-arg APP="smp-server" --build-arg APP_PORT="5223" . # For xmp-server
|
||||
DOCKER_BUILDKIT=1 docker build -t local/xftp-server --build-arg APP="xftp-server" --build-arg APP_PORT="443" . # For xftp-server
|
||||
```
|
||||
|
||||
2. Create directories for persistent Docker configuration:
|
||||
|
||||
```sh
|
||||
mkdir -p $HOME/simplex/{xftp,smp}/{config,logs} && mkdir -p $HOME/simplex/xftp/files
|
||||
```
|
||||
|
||||
3. Run your Docker container.
|
||||
|
||||
- `smp-server`
|
||||
|
||||
You must change **your_ip_or_domain**. `-e "pass=password"` is optional variable to password-protect your `smp` server:
|
||||
```sh
|
||||
docker run -d \
|
||||
-e "ADDR=your_ip_or_domain" \
|
||||
-e "PASS=password" \
|
||||
-p 5223:5223 \
|
||||
-v $HOME/simplex/smp/config:/etc/opt/simplex:z \
|
||||
-v $HOME/simplex/smp/logs:/var/opt/simplex:z \
|
||||
simplexchat/smp-server:latest
|
||||
```
|
||||
|
||||
- `xftp-server`
|
||||
|
||||
You must change **your_ip_or_domain** and **maximum_storage**.
|
||||
```sh
|
||||
docker run -d \
|
||||
-e "ADDR=your_ip_or_domain" \
|
||||
-e "QUOTA=maximum_storage" \
|
||||
-p 443:443 \
|
||||
-v $HOME/simplex/xftp/config:/etc/opt/simplex-xftp:z \
|
||||
-v $HOME/simplex/xftp/logs:/var/opt/simplex-xftp:z \
|
||||
-v $HOME/simplex/xftp/files:/srv/xftp:z \
|
||||
simplexchat/xftp-server:latest
|
||||
```
|
||||
|
||||
#### Using your distribution
|
||||
|
||||
1. Install dependencies and build tools (`GHC`, `cabal` and dev libs):
|
||||
|
||||
```sh
|
||||
# On Ubuntu. Depending on your distribution, use your package manager to determine package names.
|
||||
sudo apt-get update && apt-get install -y build-essential curl libffi-dev libffi7 libgmp3-dev libgmp10 libncurses-dev libncurses5 libtinfo5 pkg-config zlib1g-dev libnuma-dev libssl-dev
|
||||
export BOOTSTRAP_HASKELL_GHC_VERSION=9.6.3
|
||||
export BOOTSTRAP_HASKELL_CABAL_VERSION=3.10.3.0
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://get-ghcup.haskell.org | BOOTSTRAP_HASKELL_NONINTERACTIVE=1 sh
|
||||
ghcup set ghc "${BOOTSTRAP_HASKELL_GHC_VERSION}"
|
||||
ghcup set cabal "${BOOTSTRAP_HASKELL_CABAL_VERSION}"
|
||||
source ~/.ghcup/env
|
||||
```
|
||||
|
||||
2. Build the project:
|
||||
|
||||
```sh
|
||||
git clone https://github.com/simplex-chat/simplexmq
|
||||
cd simplexmq
|
||||
git checkout stable
|
||||
cabal update
|
||||
cabal build exe:smp-server exe:xftp-server
|
||||
```
|
||||
|
||||
3. List compiled binaries:
|
||||
|
||||
`smp-server`
|
||||
```sh
|
||||
cabal list-bin exe:smp-server
|
||||
```
|
||||
|
||||
`xftp-server`
|
||||
```sh
|
||||
cabal list-bin exe:xftp-server
|
||||
```
|
||||
|
||||
- Initialize SMP server with `smp-server init [-l] -n <fqdn>` or `smp-server init [-l] --ip <ip>` - depending on how you initialize it, either FQDN or IP will be used for server's address.
|
||||
|
||||
- Run `smp-server start` to start SMP server, or you can configure a service manager to run it as a service.
|
||||
|
||||
- Optionally, `smp-server` can be setup for having an onion address in `tor` network. See: [`scripts/tor`](./scripts/tor/). In this case, the server address can have both public and onion hostname pointing to the same server, to allow two people connect when only one of them is using Tor. The server address would be: `smp://<fingerprint>@<public_hostname>,<onion_hostname>`
|
||||
|
||||
See [this section](#smp-server) for more information. Run `smp-server -h` and `smp-server init -h` for explanation of commands and options.
|
||||
|
||||
[<img alt="Linode" src="./img/linode.svg" align="right" width="200">](https://cloud.linode.com/stackscripts/748014)
|
||||
|
||||
## Deploy SMP server on Linode
|
||||
|
||||
\* You can use free credit Linode offers when [creating a new account](https://www.linode.com/) to deploy an SMP server.
|
||||
|
||||
Deployment on Linode is performed via StackScripts, which serve as recipes for Linode instances, also called Linodes. To deploy SMP server on Linode:
|
||||
|
||||
- Create a Linode account or login with an already existing one.
|
||||
- Open [SMP server StackScript](https://cloud.linode.com/stackscripts/748014) and click "Deploy New Linode".
|
||||
- You can optionally configure the following parameters:
|
||||
- SMP Server store log flag for queue persistence on server restart, recommended.
|
||||
- [Linode API token](https://www.linode.com/docs/guides/getting-started-with-the-linode-api#get-an-access-token) to attach server address etc. as tags to Linode and to add A record to your 2nd level domain (e.g. `example.com` [domain should be created](https://cloud.linode.com/domains/create) in your account prior to deployment). The API token access scopes:
|
||||
- read/write for "linodes"
|
||||
- read/write for "domains"
|
||||
- Domain name to use instead of Linode IP address, e.g. `smp1.example.com`.
|
||||
- Choose the region and plan, Shared CPU Nanode with 1Gb is sufficient.
|
||||
- Provide ssh key to be able to connect to your Linode via ssh. If you haven't provided a Linode API token this step is required to login to your Linode and get the server's fingerprint either from the welcome message or from the file `/etc/opt/simplex/fingerprint` after server starts. See [Linode's guide on ssh](https://www.linode.com/docs/guides/use-public-key-authentication-with-ssh/) .
|
||||
- Deploy your Linode. After it starts wait for SMP server to start and for tags to appear (if a Linode API token was provided). It may take up to 5 minutes depending on the connection speed on the Linode. Connecting Linode IP address to provided domain name may take some additional time.
|
||||
- Get `address` and `fingerprint` either from Linode tags (click on a tag and copy it's value from the browser search panel) or via ssh.
|
||||
- Great, your own SMP server is ready! If you provided FQDN use `smp://<fingerprint>@<fqdn>` as SMP server address in the client, otherwise use `smp://<fingerprint>@<ip_address>`.
|
||||
|
||||
Please submit an [issue](https://github.com/simplex-chat/simplexmq/issues) if any problems occur.
|
||||
|
||||
[<img alt="DigitalOcean" src="/img/digitalocean.png" align="right" width="300">](https://marketplace.digitalocean.com/apps/simplex-server)
|
||||
|
||||
## Deploy SMP server on DigitalOcean
|
||||
|
||||
> 🚧 DigitalOcean snapshot is currently not up to date, it will soon be updated 🏗️
|
||||
|
||||
\* When creating a DigitalOcean account you can use [this link](https://try.digitalocean.com/freetrialoffer/) to get free credit. (You would still be required either to provide your credit card details or make a confirmation pre-payment with PayPal)
|
||||
|
||||
To deploy SMP server use [SimpleX Server 1-click app](https://marketplace.digitalocean.com/apps/simplex-server) from DigitalOcean marketplace:
|
||||
|
||||
- Create a DigitalOcean account or login with an already existing one.
|
||||
- Click 'Create SimpleX server Droplet' button.
|
||||
- Choose the region and plan according to your requirements (Basic plan should be sufficient).
|
||||
- Finalize Droplet creation.
|
||||
- Open "Console" on your Droplet management page to get SMP server fingerprint - either from the welcome message or from `/etc/opt/simplex/fingerprint`. Alternatively you can manually SSH to created Droplet, see [DigitalOcean instruction](https://docs.digitalocean.com/products/droplets/how-to/connect-with-ssh/).
|
||||
- Great, your own SMP server is ready! Use `smp://<fingerprint>@<ip_address>` as SMP server address in the client.
|
||||
|
||||
Please submit an [issue](https://github.com/simplex-chat/simplexmq/issues) if any problems occur.
|
||||
|
||||
> **Please note:** SMP server uses server address as a Common Name for server certificate generated during initialization. If you would like your server address to be FQDN instead of IP address, you can log in to your Droplet and run the commands below to re-initialize the server. Alternatively you can use [Linode StackScript](https://cloud.linode.com/stackscripts/748014) which allows this parameterization.
|
||||
|
||||
```sh
|
||||
smp-server delete
|
||||
smp-server init [-l] -n <fqdn>
|
||||
```
|
||||
|
||||
## SMP server design
|
||||
|
||||

|
||||
|
||||
## SMP agent design
|
||||
|
||||

|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -619,7 +619,6 @@ async function handleEncrypt(id, data, fileName) {
|
||||
const digest = sha512Streaming([encData], (done) => {
|
||||
self.postMessage({ id, type: "progress", done: source.length + done, total });
|
||||
}, encDataLen);
|
||||
console.log(`[WORKER-DBG] encrypt: encData.len=${encData.length} digest=${_whex(digest, 64)} chunkSizes=[${chunkSizes.join(",")}]`);
|
||||
const dir = await getSessionDir();
|
||||
const fileHandle = await dir.getFileHandle("upload.bin", { create: true });
|
||||
const writeHandle = await fileHandle.createSyncAccessHandle();
|
||||
@@ -643,9 +642,7 @@ function handleReadChunk(id, offset, size) {
|
||||
}
|
||||
async function handleDecryptAndStore(id, dhSecret, nonce, body, chunkDigest, chunkNo) {
|
||||
const bodyArr = new Uint8Array(body);
|
||||
console.log(`[WORKER-DBG] store chunk=${chunkNo} body.len=${bodyArr.length} nonce=${_whex(nonce, 24)} dhSecret=${_whex(dhSecret)} digest=${_whex(chunkDigest, 32)} body[0..8]=${_whex(bodyArr)} body[-8..]=${_whex(bodyArr.slice(-8))}`);
|
||||
const decrypted = decryptReceivedChunk(dhSecret, nonce, bodyArr, chunkDigest);
|
||||
console.log(`[WORKER-DBG] decrypted chunk=${chunkNo} len=${decrypted.length} [0..8]=${_whex(decrypted)} [-8..]=${_whex(decrypted.slice(-8))}`);
|
||||
if (useMemory) {
|
||||
memoryChunks.set(chunkNo, decrypted);
|
||||
self.postMessage({ id, type: "stored" });
|
||||
@@ -660,7 +657,6 @@ async function handleDecryptAndStore(id, dhSecret, nonce, body, chunkDigest, chu
|
||||
currentDownloadOffset += decrypted.length;
|
||||
chunkMeta.set(chunkNo, { offset, size: decrypted.length });
|
||||
const written = downloadWriteHandle.write(decrypted, { at: offset });
|
||||
console.log(`[WORKER-DBG] OPFS write chunk=${chunkNo} offset=${offset} size=${decrypted.length} written=${written}`);
|
||||
if (written !== decrypted.length) {
|
||||
console.warn(`[WORKER] OPFS write failed chunk=${chunkNo}: ${written}/${decrypted.length}, falling back to in-memory storage`);
|
||||
for (const [cn, meta] of chunkMeta.entries()) {
|
||||
@@ -684,23 +680,16 @@ async function handleDecryptAndStore(id, dhSecret, nonce, body, chunkDigest, chu
|
||||
return;
|
||||
}
|
||||
downloadWriteHandle.flush();
|
||||
const verifyBuf = new Uint8Array(Math.min(8, decrypted.length));
|
||||
downloadWriteHandle.read(verifyBuf, { at: offset });
|
||||
const verifyEnd = new Uint8Array(Math.min(8, decrypted.length));
|
||||
downloadWriteHandle.read(verifyEnd, { at: offset + decrypted.length - verifyEnd.length });
|
||||
console.log(`[WORKER-DBG] OPFS verify chunk=${chunkNo} readBack[0..8]=${_whex(verifyBuf)} readBack[-8..]=${_whex(verifyEnd)} expected[0..8]=${_whex(decrypted)} expected[-8..]=${_whex(decrypted.slice(-8))}`);
|
||||
self.postMessage({ id, type: "stored" });
|
||||
}
|
||||
async function handleVerifyAndDecrypt(id, size, digest, key, nonce) {
|
||||
console.log(`[WORKER-DBG] verify: expectedSize=${size} expectedDigest=${_whex(digest, 64)} useMemory=${useMemory} chunkMeta.size=${chunkMeta.size} memoryChunks.size=${memoryChunks.size}`);
|
||||
const chunks = [];
|
||||
let totalSize = 0;
|
||||
const total = size * 3;
|
||||
let done = 0;
|
||||
if (useMemory) {
|
||||
const sorted = [...memoryChunks.entries()].sort((a, b) => a[0] - b[0]);
|
||||
for (const [chunkNo, data] of sorted) {
|
||||
console.log(`[WORKER-DBG] verify memory chunk=${chunkNo} size=${data.length}`);
|
||||
for (const [, data] of sorted) {
|
||||
chunks.push(data);
|
||||
totalSize += data.length;
|
||||
done += data.length;
|
||||
@@ -715,12 +704,10 @@ async function handleVerifyAndDecrypt(id, size, digest, key, nonce) {
|
||||
const dir = await getSessionDir();
|
||||
const fileHandle = await dir.getFileHandle("download.bin");
|
||||
const readHandle = await fileHandle.createSyncAccessHandle();
|
||||
console.log(`[WORKER-DBG] verify: OPFS file size=${readHandle.getSize()}`);
|
||||
const sortedEntries = [...chunkMeta.entries()].sort((a, b) => a[0] - b[0]);
|
||||
for (const [chunkNo, meta] of sortedEntries) {
|
||||
for (const [, meta] of sortedEntries) {
|
||||
const buf = new Uint8Array(meta.size);
|
||||
const bytesRead = readHandle.read(buf, { at: meta.offset });
|
||||
console.log(`[WORKER-DBG] verify read chunk=${chunkNo} offset=${meta.offset} size=${meta.size} bytesRead=${bytesRead} [0..8]=${_whex(buf)} [-8..]=${_whex(buf.slice(-8))}`);
|
||||
readHandle.read(buf, { at: meta.offset });
|
||||
chunks.push(buf);
|
||||
totalSize += meta.size;
|
||||
done += meta.size;
|
||||
@@ -745,20 +732,9 @@ async function handleVerifyAndDecrypt(id, size, digest, key, nonce) {
|
||||
}
|
||||
const actualDigest = r.crypto_hash_sha512_final(state);
|
||||
if (!digestEqual(actualDigest, digest)) {
|
||||
console.error(`[WORKER-DBG] DIGEST MISMATCH: expected=${_whex(digest, 64)} actual=${_whex(actualDigest, 64)} chunks=${chunks.length} totalSize=${totalSize}`);
|
||||
const state2 = r.crypto_hash_sha512_init();
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
const chunk = chunks[i];
|
||||
for (let off = 0; off < chunk.length; off += hashSEG) {
|
||||
r.crypto_hash_sha512_update(state2, chunk.subarray(off, Math.min(off + hashSEG, chunk.length)));
|
||||
}
|
||||
const chunkDigest = sha512Streaming([chunk]);
|
||||
console.error(`[WORKER-DBG] chunk[${i}] size=${chunk.length} sha512=${_whex(chunkDigest, 32)}… [0..8]=${_whex(chunk)} [-8..]=${_whex(chunk.slice(-8))}`);
|
||||
}
|
||||
self.postMessage({ id, type: "error", message: "File digest mismatch" });
|
||||
return;
|
||||
}
|
||||
console.log(`[WORKER-DBG] verify: digest OK`);
|
||||
const result = decryptChunks(BigInt(size), chunks, key, nonce, (d) => {
|
||||
self.postMessage({ id, type: "progress", done: size * 2 + d, total });
|
||||
});
|
||||
|
||||
@@ -334,11 +334,6 @@ class WorkerBackend {
|
||||
const nonceCopy = new Uint8Array(nonce);
|
||||
const digestCopy = new Uint8Array(digest);
|
||||
const buf = this.toTransferable(body);
|
||||
const hex = (b, n = 8) => {
|
||||
const u = b instanceof ArrayBuffer ? new Uint8Array(b) : b;
|
||||
return Array.from(u.slice(0, n)).map((x) => x.toString(16).padStart(2, "0")).join("");
|
||||
};
|
||||
console.log(`[BACKEND-DBG] chunk=${chunkNo} body.len=${body.length} body.byteOff=${body.byteOffset} buf.byteLen=${buf.byteLength} nonce=${hex(nonceCopy, 24)} dhSecret=${hex(dhSecretCopy)} digest=${hex(digestCopy, 32)} buf[0..8]=${hex(buf)} body[-8..]=${hex(body.slice(-8))}`);
|
||||
await this.send(
|
||||
{ type: "decryptAndStoreChunk", dhSecret: dhSecretCopy, nonce: nonceCopy, body: buf, chunkDigest: digestCopy, chunkNo },
|
||||
[buf]
|
||||
@@ -10913,14 +10908,12 @@ async function sendXFTPCommandOnce(client, privateKey, entityId, cmdBytes, chunk
|
||||
const block = encodeAuthTransmission(client.sessionId, corrId, entityId, cmdBytes, privateKey);
|
||||
const reqBody = chunkData ? concatBytes$1(block, chunkData) : block;
|
||||
const fullResp = await client.transport.post(reqBody);
|
||||
console.log(`[XFTP-DBG] sendOnce: fullResp.length=${fullResp.length} entityId=${_hex(entityId)} cmdTag=${cmdBytes[0]}`);
|
||||
if (fullResp.length < XFTP_BLOCK_SIZE) {
|
||||
console.error("[XFTP] Response too short: %d bytes (expected >= %d)", fullResp.length, XFTP_BLOCK_SIZE);
|
||||
throw new Error("Server response too short");
|
||||
}
|
||||
const respBlock = fullResp.subarray(0, XFTP_BLOCK_SIZE);
|
||||
const body = fullResp.subarray(XFTP_BLOCK_SIZE);
|
||||
console.log(`[XFTP-DBG] sendOnce: body.length=${body.length} body.byteOffset=${body.byteOffset} body.buffer.byteLength=${body.buffer.byteLength}`);
|
||||
const raw = blockUnpad(respBlock);
|
||||
if (raw.length < 20) {
|
||||
const text = new TextDecoder().decode(raw);
|
||||
@@ -10939,18 +10932,13 @@ async function sendXFTPCommandOnce(client, privateKey, entityId, cmdBytes, chunk
|
||||
}
|
||||
return { response, body };
|
||||
}
|
||||
function _hex(b, n = 8) {
|
||||
return Array.from(b.slice(0, n)).map((x) => x.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
async function sendXFTPCommand(agent, server, privateKey, entityId, cmdBytes, chunkData, maxRetries = 3) {
|
||||
let clientP = getXFTPServerClient(agent, server);
|
||||
let client = await clientP;
|
||||
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
if (attempt > 1) console.log(`[XFTP-DBG] sendCmd: retry attempt=${attempt}/${maxRetries}`);
|
||||
return await sendXFTPCommandOnce(client, privateKey, entityId, cmdBytes, chunkData);
|
||||
} catch (e) {
|
||||
console.log(`[XFTP-DBG] sendCmd: attempt=${attempt} failed: ${e instanceof Error ? e.message : String(e)} retriable=${isRetriable(e)}`);
|
||||
if (!isRetriable(e)) {
|
||||
throw categorizeError(e);
|
||||
}
|
||||
@@ -10979,7 +10967,6 @@ async function downloadXFTPChunkRaw(agent, server, rpKey, fId) {
|
||||
const { response, body } = await sendXFTPCommand(agent, server, rpKey, fId, cmd);
|
||||
if (response.type !== "FRFile") throw new Error("unexpected response: " + response.type);
|
||||
const dhSecret = dh(response.rcvDhKey, privateKey);
|
||||
console.log(`[XFTP-DBG] dlChunkRaw: body.length=${body.length} nonce=${_hex(response.nonce, 24)} dhSecret=${_hex(dhSecret)} body[0..8]=${_hex(body)} body[-8..]=${_hex(body.slice(-8))}`);
|
||||
return { dhSecret, nonce: response.nonce, body };
|
||||
}
|
||||
async function downloadXFTPChunk(agent, server, rpKey, fId, digest) {
|
||||
@@ -11012,7 +10999,6 @@ function encryptFileForUpload(source, fileName) {
|
||||
const encSize = BigInt(chunkSizes.reduce((a, b) => a + b, 0));
|
||||
const encData = encryptFile(source, fileHdr, key, nonce, fileSize, encSize);
|
||||
const digest = sha512Streaming([encData]);
|
||||
console.log(`[AGENT-DBG] encrypt: encData.len=${encData.length} digest=${_dbgHex(digest, 64)} chunkSizes=[${chunkSizes.join(",")}]`);
|
||||
return { encData, digest, key, nonce, chunkSizes };
|
||||
}
|
||||
const DEFAULT_REDIRECT_THRESHOLD = 400;
|
||||
@@ -11169,9 +11155,7 @@ async function downloadFileRaw(agent, fd, onRawChunk, options) {
|
||||
if (err) throw new Error("downloadFileRaw: " + err);
|
||||
const { onProgress} = options ?? {};
|
||||
if (fd.redirect !== null) {
|
||||
console.log(`[AGENT-DBG] resolving redirect: outer size=${fd.size} chunks=${fd.chunks.length}`);
|
||||
fd = await resolveRedirect(agent, fd);
|
||||
console.log(`[AGENT-DBG] resolved: size=${fd.size} chunks=${fd.chunks.length} digest=${Array.from(fd.digest.slice(0, 16)).map((x) => x.toString(16).padStart(2, "0")).join("")}…`);
|
||||
}
|
||||
const resolvedFd = fd;
|
||||
let downloaded = 0;
|
||||
@@ -11189,7 +11173,6 @@ async function downloadFileRaw(agent, fd, onRawChunk, options) {
|
||||
const seed = decodePrivKeyEd25519(replica.replicaKey);
|
||||
const kp = ed25519KeyPairFromSeed(seed);
|
||||
const raw = await downloadXFTPChunkRaw(agent, server, kp.privateKey, replica.replicaId);
|
||||
console.log(`[AGENT-DBG] chunk=${chunk.chunkNo} body.len=${raw.body.length} expectedChunkSize=${chunk.chunkSize} digest=${_dbgHex(chunk.digest, 32)} body.byteOffset=${raw.body.byteOffset} body.buffer.byteLength=${raw.body.buffer.byteLength}`);
|
||||
await onRawChunk({
|
||||
chunkNo: chunk.chunkNo,
|
||||
dhSecret: raw.dhSecret,
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// getentropy() shim for Windows, where it is absent from the CRT.
|
||||
// Follows the POSIX contract: fills `buffer` with `length` random bytes
|
||||
// (length must not exceed 256), returns 0 on success or -1 with errno set.
|
||||
#ifdef _WIN32
|
||||
#include <errno.h>
|
||||
#include <stddef.h>
|
||||
#include <windows.h>
|
||||
#include <bcrypt.h>
|
||||
|
||||
int getentropy(void *buffer, size_t length) {
|
||||
if (length > 256) {
|
||||
errno = EIO;
|
||||
return -1;
|
||||
}
|
||||
NTSTATUS status = BCryptGenRandom(NULL, (PUCHAR)buffer, (ULONG)length,
|
||||
BCRYPT_USE_SYSTEM_PREFERRED_RNG);
|
||||
if (!BCRYPT_SUCCESS(status)) {
|
||||
errno = EIO;
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
@@ -92,7 +92,6 @@ cabal list-bin exe:smp-server
|
||||
### Cabal Flags
|
||||
|
||||
- `swift`: Enable Swift JSON format
|
||||
- `use_crypton`: Use crypton in cryptostore (default: enabled)
|
||||
- `client_library`: Build without server code
|
||||
- `client_postgres`: Use PostgreSQL instead of SQLite for agent persistence
|
||||
- `server_postgres`: PostgreSQL support for server queue/notification store
|
||||
|
||||
@@ -13,7 +13,7 @@ Key components:
|
||||
- **SMP Client**: Functional API with STM-based message delivery ([code](../src/Simplex/Messaging/Client.hs)).
|
||||
- **SMP Agent**: High-level duplex connections via multiple simplex queues with E2E encryption ([code](../src/Simplex/Messaging/Agent.hs)). Implements Agent-to-agent protocol ([code](../src/Simplex/Messaging/Agent/Protocol.hs), [spec](../protocol/agent-protocol.md)) via intermediary agent client ([code](../src/Simplex/Messaging/Agent/Client.hs)).
|
||||
- **XFTP**: SimpleX File Transfer Protocol, server and CLI client ([code](../src/Simplex/FileTransfer/), [spec](../protocol/xftp.md)).
|
||||
- **XRCP**: SimpleX Remote Control Protocol ([code](../src/Simplex/RemoteControl/), [spec](../protocol/xrcp.md)).
|
||||
- **XRCP**: SimpleX Remote Control Protocol ([code](`../src/Simplex/RemoteControl/`), [spec](../protocol/xrcp.md)).
|
||||
- **Notifications**: Push notifications server requires PostgreSQL ([code](../src/Simplex/Messaging/Notifications), [executable](../apps/ntf-server/)). Client protocol is used for clients to communicate with the server ([code](../src/Simplex/Messaging/Notifications/Protocol.hs), [spec](../protocol/push-notifications.md)). For subscribing to SMP notifications the server uses [lightweight SMP client](../src/Simplex/Messaging/Client/Agent.hs).
|
||||
|
||||
## Architecture
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
# SimpleX Agent
|
||||
|
||||
The SimpleX Agent builds duplex encrypted connections on top of [SimpleX client libraries](CLIENT.md). It manages the full lifecycle of secure communication: connection establishment, end-to-end encryption, queue rotation, file transfer, and push notifications.
|
||||
|
||||
This is **Layer 3** of the [SimpleX Network architecture](../protocol/overview-tjr.md). Layer 1 is the routers; Layer 2 is the [client libraries](CLIENT.md) that speak the wire protocols. The Agent adds the connection semantics that applications need. For internal architecture diagrams (thread topology, message processing flows), see [`spec/agent.md`](../spec/agent.md).
|
||||
|
||||
**Source**: [`Simplex.Messaging.Agent`](../src/Simplex/Messaging/Agent.hs). **Module spec**: [`spec/modules/Simplex/Messaging/Agent.md`](../spec/modules/Simplex/Messaging/Agent.md)
|
||||
|
||||
## Connections
|
||||
|
||||
The Agent turns simplex (unidirectional) SMP queues into duplex connections, implementing the [Agent protocol](../protocol/agent-protocol.md):
|
||||
|
||||
- **Duplex connections**: each connection uses a pair of SMP queues - one for each direction. The queues can be on different routers chosen independently by each party. See the [duplex connection procedure](../protocol/agent-protocol.md) for the full handshake.
|
||||
- **Connection establishment**: one party creates a connection and generates an invitation (containing router address, queue ID, and public keys). The invitation is passed out-of-band (QR code, link, etc.). The other party joins by creating a reverse queue and completing the handshake.
|
||||
- **Connection links**: the Agent supports connection links (long and short) for sharing connection invitations via URLs. Short links use a separate SMP queue to store the full invitation, allowing compact QR codes.
|
||||
- **Queue rotation**: the Agent has API to rotate the SMP queues, to reduce metadata correlation. The connection identity remain the same when the underlying queue changes.
|
||||
|
||||
## Encryption
|
||||
|
||||
The Agent provides end-to-end encryption with forward secrecy and break-in recovery, specified in the [Post-Quantum Double Ratchet protocol](../protocol/pqdr.md):
|
||||
|
||||
- **Double ratchet**: messages are encrypted using a double ratchet protocol. Each message uses a unique key; compromising one key does not reveal past or future messages. See the [PQDR specification](../protocol/pqdr.md) for the full ratchet state machine.
|
||||
- **Post-quantum extensions**: the ratchet supports hybrid key exchange using SNTRUP761 (a lattice-based KEM) combined with X25519 DH. This provides protection against future quantum computers that could break classical DH. See the [SNTRUP761 module spec](../spec/modules/Simplex/Messaging/Crypto/SNTRUP761.md) and [Ratchet module spec](../spec/modules/Simplex/Messaging/Crypto/Ratchet.md) for implementation details.
|
||||
- **Ratchet synchronization**: if the ratchet state becomes desynchronized (e.g., due to message loss or device restore), the Agent detects this and can negotiate resynchronization with the peer.
|
||||
- **Per-queue encryption**: in addition to end-to-end encryption, the [SMP protocol](../protocol/simplex-messaging.md) provides a separate encryption layer on each queue between sender and router, preventing traffic correlation even if TLS is compromised.
|
||||
|
||||
## File Transfer
|
||||
|
||||
The Agent handles file transfer over [XFTP](../protocol/xftp.md) routers. File transfer orchestration is implemented in the [XFTP Agent module](../spec/modules/Simplex/FileTransfer/Agent.md):
|
||||
|
||||
- **Chunking**: files are split into chunks, each sent as a data packet to an XFTP router. Chunk sizes are fixed powers of 2 (64KB to 4MB), hiding the actual file size. See the [file description module spec](../spec/modules/Simplex/FileTransfer/Description.md) for chunk size selection and file descriptor format.
|
||||
- **Client-side encryption**: files are encrypted and padded before being sent to XFTP routers. The recipient decrypts after receiving all chunks. The encryption key and file metadata are sent through the SMP connection, not through XFTP. See [file crypto module spec](../spec/modules/Simplex/FileTransfer/Crypto.md).
|
||||
- **Multi-router distribution**: chunks can be sent to different XFTP routers, and each chunk can have multiple replicas on different routers for redundancy.
|
||||
- **Redirect chains**: for metadata privacy, file descriptors can be sent as XFTP data packets themselves, creating an indirection layer between the SMP message and the actual file location.
|
||||
|
||||
## Notifications
|
||||
|
||||
The Agent manages push notification subscriptions for mobile devices, using the [Push Notifications protocol](../protocol/push-notifications.md). Notification supervision is handled by the [NtfSubSupervisor](../spec/modules/Simplex/Messaging/Agent/NtfSubSupervisor.md):
|
||||
|
||||
- **Token registration**: registers device push tokens with NTF (notification) routers, which bridge to platform push services (APNS). See the [NTF client module spec](../spec/modules/Simplex/Messaging/Notifications/Client.md).
|
||||
- **Notification subscriptions**: creates NTF subscriptions for SMP queues so that incoming messages trigger push notifications without requiring persistent connections.
|
||||
- **Privacy preservation**: push notifications contain only a notification ID, not message content. The device wakes, connects to the SMP router, and retrieves the actual message. See the [Push Notifications protocol](../protocol/push-notifications.md) for the full flow.
|
||||
|
||||
## Integration
|
||||
|
||||
The Agent is designed to be embedded as a Haskell library:
|
||||
|
||||
- **STM queues**: the application communicates with the Agent via STM queues. Commands go in (`ACommand`), events come out (`AEvent`). No serialization or parsing - direct Haskell values. The command/event types are defined in the [Agent Protocol module](../spec/modules/Simplex/Messaging/Agent/Protocol.md).
|
||||
- **Async operation**: all network operations are asynchronous. The Agent manages internal worker threads for each router connection, message processing, and background tasks (cleanup, statistics, notification supervision). See the [Agent Client module spec](../spec/modules/Simplex/Messaging/Agent/Client.md) for worker architecture.
|
||||
- **Background mode**: on mobile platforms, the Agent can run in a reduced mode with only the message receiver active, minimizing resource usage when the app is backgrounded.
|
||||
- **Dual database backends**: the Agent supports both SQLite (for mobile/desktop) and PostgreSQL (for server deployments) as persistence backends, selected at compile time. See [Agent Store Interface](../spec/modules/Simplex/Messaging/Agent/Store/Interface.md) and [Agent Store Postgres](../spec/modules/Simplex/Messaging/Agent/Store/Postgres.md).
|
||||
|
||||
## Use cases
|
||||
|
||||
- **Chat applications**: [SimpleX Chat](https://github.com/simplex-chat/simplex-chat) is the reference application, using the full Agent API for messaging, file sharing, groups, and calls.
|
||||
- **Bots and automated services**: services that need duplex encrypted communication with SimpleX Chat users or other Agent-based applications.
|
||||
- **Any application needing secure duplex communication** over the SimpleX Network without implementing the connection management, encryption, and queue rotation logic directly.
|
||||
|
||||
## What this layer adds over client libraries
|
||||
|
||||
| Capability | Client (Layer 2) | Agent (Layer 3) |
|
||||
|---|---|---|
|
||||
| Queue operations | Direct | Managed transparently |
|
||||
| Connection model | Simplex (unidirectional) queues | Duplex connections |
|
||||
| Encryption | Application's responsibility | Double ratchet with PQ extensions |
|
||||
| File transfer | Raw data packet send/receive | Chunking, encryption, reassembly |
|
||||
| Identity | Per-queue keys | Per-connection, rotatable |
|
||||
| Notifications | Direct NTF protocol operations | Automated subscription supervision |
|
||||
|
||||
## Protocol references
|
||||
|
||||
- [Agent Protocol](../protocol/agent-protocol.md) - duplex connection procedure, message format
|
||||
- [SimpleX Network overview](../protocol/overview-tjr.md) - architecture, trust model
|
||||
- [PQDR](../protocol/pqdr.md) - post-quantum double ratchet specification
|
||||
- [SimpleX Messaging Protocol](../protocol/simplex-messaging.md) - SMP queue operations used by the Agent
|
||||
- [XFTP Protocol](../protocol/xftp.md) - data packet operations for file transfer
|
||||
- [Push Notifications Protocol](../protocol/push-notifications.md) - NTF token and subscription management
|
||||
## Peer library: Remote Control
|
||||
|
||||
The Agent exposes the [XRCP protocol](../protocol/xrcp.md) API for cross-device remote control (e.g., controlling a mobile app from a desktop). The actual logic is in the standalone [`Simplex.RemoteControl.Client`](../src/Simplex/RemoteControl/Client.hs) library - the Agent provides thin wrappers that pass through its random and multicast state. XRCP is not a managed Agent capability (no workers, persistence, or background supervision). See the [RemoteControl module specs](../spec/modules/Simplex/RemoteControl/Types.md).
|
||||
|
||||
## Module specs
|
||||
|
||||
- [Agent](../spec/modules/Simplex/Messaging/Agent.md) - main Agent module, connection lifecycle, message processing
|
||||
- [Agent Client](../spec/modules/Simplex/Messaging/Agent/Client.md) - worker threads, router connections, subscription management
|
||||
- [Agent Protocol](../spec/modules/Simplex/Messaging/Agent/Protocol.md) - ACommand/AEvent types, connection invitations
|
||||
- [Agent Store Interface](../spec/modules/Simplex/Messaging/Agent/Store/Interface.md) - database abstraction for SQLite/Postgres
|
||||
- [Agent Store (AgentStore)](../spec/modules/Simplex/Messaging/Agent/Store/AgentStore.md) - connection, queue, and message persistence
|
||||
- [NtfSubSupervisor](../spec/modules/Simplex/Messaging/Agent/NtfSubSupervisor.md) - notification subscription management
|
||||
- [XFTP Agent](../spec/modules/Simplex/FileTransfer/Agent.md) - file transfer orchestration
|
||||
- [Ratchet](../spec/modules/Simplex/Messaging/Crypto/Ratchet.md) - double ratchet implementation
|
||||
- [SNTRUP761](../spec/modules/Simplex/Messaging/Crypto/SNTRUP761.md) - post-quantum KEM
|
||||
@@ -1,96 +0,0 @@
|
||||
# SimpleX Client Libraries
|
||||
|
||||
SimpleX client libraries provide low-level protocol access to SimpleX routers. They implement the wire protocols ([SMP](../protocol/simplex-messaging.md), [XFTP](../protocol/xftp.md), [NTF](../protocol/push-notifications.md)) and handle connection lifecycle, but leave encryption, identity management, and connection orchestration to the application.
|
||||
|
||||
This is **Layer 2** of the [SimpleX Network architecture](../protocol/overview-tjr.md). Layer 1 is the routers themselves; Layer 3 is the [Agent](AGENT.md), which builds duplex encrypted connections on top of these libraries. For internal architecture diagrams (thread topology, command processing flows), see [`spec/clients.md`](../spec/clients.md).
|
||||
|
||||
## SMP Client
|
||||
|
||||
**Source**: [`Simplex.Messaging.Client`](../src/Simplex/Messaging/Client.hs). For architecture and module specs, see [SMP Client](../spec/clients.md#smp-client-protocolclient).
|
||||
|
||||
The SMP client connects to SMP routers and manages simplex messaging queues, the fundamental addressing primitive of the SimpleX Network. Each simplex queue is a unidirectional, ordered sequence of fixed-size packets (16,384 bytes) with separate cryptographic credentials for sending and receiving. The queue model and command set are defined in the [SMP protocol](../protocol/simplex-messaging.md).
|
||||
|
||||
### Capabilities
|
||||
|
||||
- **Queue management**: create, secure, subscribe to, and delete queues on any SMP router. Queue operations use the [SMP command set](../protocol/simplex-messaging.md) (NEW, KEY, SUB, DEL, etc.).
|
||||
- **Message sending and receiving**: send messages to a queue's sender address; receive messages from a queue's recipient address
|
||||
- **Command authentication**: each queue operation is authenticated with per-queue cryptographic keys (Ed25519, Ed448, or X25519). See the [SMP protocol security model](../protocol/simplex-messaging.md) for key roles.
|
||||
- **Keep-alive**: automatic ping loop detects and recovers from half-open connections
|
||||
- **Proxy forwarding**: send messages through a proxy router via 2-hop onion routing (PRXY/PFWD/RFWD commands), protecting the sender's IP address from the destination router. See [proxy forwarding details](../spec/modules/Simplex/Messaging/Client.md) in the module spec.
|
||||
- **Batched commands**: multiple commands can be sent in a single transmission for efficiency
|
||||
|
||||
### API model
|
||||
|
||||
The client uses a functional Haskell API with STM queues for asynchronous event delivery:
|
||||
|
||||
- **Commands** are sent via `sendProtocolCommand` (single) or `sendBatch` (multiple). Each returns a result synchronously or via timeout.
|
||||
- **Router events** (incoming messages, subscription notifications) arrive on `msgQ`, an STM `TBQueue` that the application reads from its own thread.
|
||||
- **Connection lifecycle** is managed automatically: the client maintains send, receive, process, and monitor threads internally. When any thread fails, all are torn down and the `disconnected` callback fires.
|
||||
|
||||
### Router identity
|
||||
|
||||
Routers are identified by the SHA-256 hash of their CA certificate fingerprint, not by hostname. The client validates the full X.509 certificate chain on every TLS connection and compares the CA fingerprint against the expected hash from the queue address. This means a DNS or IP-level attacker who cannot produce the correct certificate is detected at connection time.
|
||||
|
||||
## SMPClientAgent
|
||||
|
||||
**Source**: [`Simplex.Messaging.Client.Agent`](../src/Simplex/Messaging/Client/Agent.hs). For architecture and module specs, see [SMPClientAgent](../spec/clients.md#smpclientagent).
|
||||
|
||||
Connection manager that multiplexes multiple SMP client connections. Maintains one ProtocolClient per SMP router, tracks queue and service subscriptions, and handles reconnection with exponential backoff. Used by the SMP router (for proxy forwarding) and the NTF router (for message subscriptions).
|
||||
|
||||
### Capabilities
|
||||
|
||||
- **Connection pooling**: maintains a pool of ProtocolClient connections keyed by SMP router, creating connections on demand and reusing existing ones
|
||||
- **Subscription tracking**: tracks active and pending subscriptions (both queue-based and service-based) with automatic state transitions on connect/disconnect
|
||||
- **Automatic reconnection**: on connection loss, moves subscriptions from active to pending, then spawns a background worker that retries with backoff and resubscribes
|
||||
- **Session-scoped disconnect handling**: uses session IDs to ensure only subscriptions belonging to the disconnected session are affected, preventing races with newly established connections
|
||||
|
||||
## XFTP Client
|
||||
|
||||
**Source**: [`Simplex.FileTransfer.Client`](../src/Simplex/FileTransfer/Client.hs). For architecture and module specs, see [XFTP Client](../spec/clients.md#xftp-client).
|
||||
|
||||
The XFTP client connects to XFTP routers and manages data packets, individually addressed blocks used for larger payload delivery. Data packets come in fixed sizes (64KB, 256KB, 1MB, 4MB), hiding the actual payload size. The XFTP protocol runs over HTTP/2, simplifying browser integration. The data packet lifecycle and command set are defined in the [XFTP protocol](../protocol/xftp.md).
|
||||
|
||||
### Capabilities
|
||||
|
||||
- **Data packet creation**: create data packets on routers with sender, recipient, and optional additional recipient credentials. See the [XFTP protocol](../protocol/xftp.md) for credential roles and packet lifecycle.
|
||||
- **Send** (FPUT): send encrypted data to the router in a single HTTP/2 streaming request (command + body)
|
||||
- **Receive** (FGET): receive data packets with per-request ephemeral Diffie-Hellman key exchange, providing forward secrecy: compromising one DH key does not reveal other received data packets
|
||||
- **Acknowledgment and deletion**: recipients acknowledge receipt; senders delete data packets after delivery
|
||||
|
||||
## NTF Client
|
||||
|
||||
**Source**: [`Simplex.Messaging.Notifications.Client`](../src/Simplex/Messaging/Notifications/Client.hs). For architecture and module specs, see [NTF Client](../spec/clients.md#ntf-client).
|
||||
|
||||
The NTF client connects to NTF (notification) routers and manages push notification tokens and subscriptions. It implements the [Push Notifications protocol](../protocol/push-notifications.md).
|
||||
|
||||
### Capabilities
|
||||
|
||||
- **Token management**: register, verify, replace, and delete push notification tokens on NTF routers
|
||||
- **Subscription management**: create, check, and delete notification subscriptions that link SMP queues to push tokens
|
||||
- **Batch operations**: create or check multiple subscriptions in a single request, with per-item error handling for partial success
|
||||
|
||||
## Use cases
|
||||
|
||||
These libraries are appropriate when the application manages its own encryption and connection logic:
|
||||
|
||||
- **IoT sensor data collection**: a sensor creates an SMP queue and sends readings; a collector subscribes and receives them. The queue address (router + queue ID + keys) is provisioned once, out-of-band.
|
||||
- **Device control**: a controller sends commands to an actuator's queue. Separate queues for commands and telemetry provide unidirectional isolation.
|
||||
- **Bulk data delivery**: an application encrypts and chunks a file, sends data packets to XFTP routers, and shares the packet addresses with the recipient out-of-band.
|
||||
- **Custom protocols**: any application that needs unidirectional, router-mediated packet delivery without the overhead of the Agent's connection management.
|
||||
|
||||
## What this layer does NOT provide
|
||||
|
||||
The following capabilities require the [Agent](AGENT.md) (Layer 3):
|
||||
|
||||
- **Duplex connections** - the Agent pairs two simplex queues into a duplex connection
|
||||
- **End-to-end encryption** - the Agent manages double ratchet with post-quantum extensions
|
||||
- **File transfer** - the Agent handles chunking, encryption, padding, multi-router distribution, and reassembly
|
||||
- **Queue rotation** - the Agent transparently rotates queues to limit metadata correlation
|
||||
- **Connection discovery** - connection links, short links, and contact addresses are Agent-level abstractions
|
||||
- **Push notifications** - notification token management and subscription is Agent-level
|
||||
|
||||
## Protocol references
|
||||
|
||||
- [SimpleX Messaging Protocol](../protocol/simplex-messaging.md) - SMP wire format, commands, and security properties
|
||||
- [XFTP Protocol](../protocol/xftp.md) - XFTP wire format, data packet lifecycle
|
||||
- [SimpleX Network overview](../protocol/overview-tjr.md) - architecture, trust model, and design rationale
|
||||
@@ -1,181 +0,0 @@
|
||||
# SimpleX Routers: Deployment and Configuration
|
||||
|
||||
SimpleX routers are the network infrastructure of the [SimpleX Network](../protocol/overview-tjr.md). They accept, buffer, and deliver data packets between endpoints. Each router operates independently and can be run by any party on standard computing hardware.
|
||||
|
||||
This document covers deployment and advanced configuration. For an overview of the router architecture and trust model, see the [SimpleX Network overview](../protocol/overview-tjr.md). For internal architecture diagrams (thread topology, command processing flows), see [`spec/routers.md`](../spec/routers.md).
|
||||
|
||||
## SMP Router
|
||||
|
||||
The SMP router provides messaging queues - unidirectional, ordered sequences of fixed-size packets (16,384 bytes each). It implements the [SimpleX Messaging Protocol](../protocol/simplex-messaging.md). For architecture and module specs, see [SMP Router](../spec/routers.md#smp-router).
|
||||
|
||||
### Advanced configuration
|
||||
|
||||
`smp-server.ini` is created during initialization and controls all runtime behavior.
|
||||
|
||||
**Message persistence**: when store log is enabled (`enable = on`), the server saves undelivered messages on exit and restores them on start. This only works with SIGINT (keyboard interrupt); SIGTERM does not trigger message saving. The `restore_messages` setting can be used to override this behavior independently of the store log setting.
|
||||
|
||||
**Tor onion addresses**: the server can have both a public hostname and an onion hostname, allowing two users to connect when only one is using Tor. Configure as: `smp://<fingerprint>@<public_hostname>,<onion_hostname>`. See [`scripts/tor/`](../scripts/tor/) for setup instructions.
|
||||
|
||||
### Running on MacOS
|
||||
|
||||
SMP server requires OpenSSL for initialization. MacOS may ship LibreSSL instead, which doesn't support the required algorithms.
|
||||
|
||||
```sh
|
||||
openssl version
|
||||
```
|
||||
|
||||
If it says "LibreSSL", install OpenSSL:
|
||||
|
||||
```sh
|
||||
brew update
|
||||
brew install openssl
|
||||
echo 'PATH="/opt/homebrew/opt/openssl@3/bin:$PATH"' >> ~/.zprofile
|
||||
. ~/.zprofile
|
||||
```
|
||||
|
||||
## XFTP Router
|
||||
|
||||
The XFTP router accepts and delivers data packets over HTTP/2 - individually addressed blocks in fixed sizes (64KB, 256KB, 1MB, 4MB). It implements the [XFTP protocol](../protocol/xftp.md). Data packets are used for larger payload delivery (files, media) where SMP queue packet sizes would be inefficient. The use of HTTP/2 simplifies browser integration. For architecture and module specs, see [XFTP Router](../spec/routers.md#xftp-router).
|
||||
|
||||
Initialize with `xftp-server init` and configure storage quota in `xftp-server.ini`.
|
||||
|
||||
## NTF Router
|
||||
|
||||
The NTF router bridges SimpleX Network to platform push notification services (APNS). It implements the [Push Notifications protocol](../protocol/push-notifications.md). Mobile clients register push tokens with the NTF router, which subscribes to their SMP queues and sends push notifications when messages arrive. The push notification contains only a notification ID, not message content. For architecture and module specs, see [NTF Router](../spec/routers.md#ntf-router).
|
||||
|
||||
Initialize with `ntf-server init` and configure APNS credentials in `ntf-server.ini`.
|
||||
|
||||
## Deployment methods
|
||||
|
||||
All routers require `openssl` as a runtime dependency for certificate generation during initialization:
|
||||
|
||||
```sh
|
||||
# Ubuntu
|
||||
apt update && apt install openssl
|
||||
```
|
||||
|
||||
### Docker (prebuilt images)
|
||||
|
||||
Prebuilt images are available from [Docker Hub](https://hub.docker.com/r/simplexchat).
|
||||
|
||||
1. Create directories for persistent configuration:
|
||||
|
||||
```sh
|
||||
mkdir -p $HOME/simplex/{xftp,smp}/{config,logs} && mkdir -p $HOME/simplex/xftp/files
|
||||
```
|
||||
|
||||
2. Run:
|
||||
|
||||
**SMP router** - change `your_ip_or_domain`; `-e "PASS=password"` is optional:
|
||||
```sh
|
||||
docker run -d \
|
||||
-e "ADDR=your_ip_or_domain" \
|
||||
-e "PASS=password" \
|
||||
-p 5223:5223 \
|
||||
-v $HOME/simplex/smp/config:/etc/opt/simplex:z \
|
||||
-v $HOME/simplex/smp/logs:/var/opt/simplex:z \
|
||||
simplexchat/smp-server:latest
|
||||
```
|
||||
|
||||
**XFTP router** - change `your_ip_or_domain` and `maximum_storage`:
|
||||
```sh
|
||||
docker run -d \
|
||||
-e "ADDR=your_ip_or_domain" \
|
||||
-e "QUOTA=maximum_storage" \
|
||||
-p 443:443 \
|
||||
-v $HOME/simplex/xftp/config:/etc/opt/simplex-xftp:z \
|
||||
-v $HOME/simplex/xftp/logs:/var/opt/simplex-xftp:z \
|
||||
-v $HOME/simplex/xftp/files:/srv/xftp:z \
|
||||
simplexchat/xftp-server:latest
|
||||
```
|
||||
|
||||
### Installation script (Ubuntu)
|
||||
|
||||
```sh
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/simplex-chat/simplexmq/stable/install.sh -o simplex-server-install.sh &&\
|
||||
if echo '53fcdb4ceab324316e2c4cda7e84dbbb344f32550a65975a7895425e5a1be757 simplex-server-install.sh' | sha256sum -c; then
|
||||
chmod +x ./simplex-server-install.sh
|
||||
./simplex-server-install.sh
|
||||
rm ./simplex-server-install.sh
|
||||
else
|
||||
echo "SHA-256 checksum is incorrect!"
|
||||
rm ./simplex-server-install.sh
|
||||
fi
|
||||
```
|
||||
|
||||
### Build from source
|
||||
|
||||
#### Using Docker
|
||||
|
||||
Build from the [stable branch](https://github.com/simplex-chat/simplexmq/tree/stable):
|
||||
|
||||
```sh
|
||||
git clone https://github.com/simplex-chat/simplexmq
|
||||
cd simplexmq
|
||||
git checkout stable
|
||||
DOCKER_BUILDKIT=1 docker build -t local/smp-server --build-arg APP="smp-server" --build-arg APP_PORT="5223" .
|
||||
DOCKER_BUILDKIT=1 docker build -t local/xftp-server --build-arg APP="xftp-server" --build-arg APP_PORT="443" .
|
||||
```
|
||||
|
||||
Then run with the same Docker commands as above, replacing `simplexchat/smp-server:latest` with `local/smp-server` (and similarly for XFTP).
|
||||
|
||||
#### Native build
|
||||
|
||||
1. Install dependencies:
|
||||
|
||||
```sh
|
||||
# Ubuntu
|
||||
sudo apt-get update && apt-get install -y build-essential curl libffi-dev libffi7 libgmp3-dev libgmp10 libncurses-dev libncurses5 libtinfo5 pkg-config zlib1g-dev libnuma-dev libssl-dev
|
||||
export BOOTSTRAP_HASKELL_GHC_VERSION=9.6.3
|
||||
export BOOTSTRAP_HASKELL_CABAL_VERSION=3.10.3.0
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://get-ghcup.haskell.org | BOOTSTRAP_HASKELL_NONINTERACTIVE=1 sh
|
||||
ghcup set ghc "${BOOTSTRAP_HASKELL_GHC_VERSION}"
|
||||
ghcup set cabal "${BOOTSTRAP_HASKELL_CABAL_VERSION}"
|
||||
source ~/.ghcup/env
|
||||
```
|
||||
|
||||
2. Build:
|
||||
|
||||
```sh
|
||||
git clone https://github.com/simplex-chat/simplexmq
|
||||
cd simplexmq
|
||||
git checkout stable
|
||||
cabal update
|
||||
cabal build exe:smp-server exe:xftp-server
|
||||
```
|
||||
|
||||
3. Find binaries:
|
||||
|
||||
```sh
|
||||
cabal list-bin exe:smp-server
|
||||
cabal list-bin exe:xftp-server
|
||||
```
|
||||
|
||||
4. Initialize and run:
|
||||
|
||||
```sh
|
||||
smp-server init [-l] -n <fqdn> # or --ip <ip>
|
||||
smp-server start
|
||||
```
|
||||
|
||||
### Linode StackScript
|
||||
|
||||
[Deploy via Linode StackScript](https://cloud.linode.com/stackscripts/748014). Shared CPU Nanode with 1GB is sufficient.
|
||||
|
||||
Configuration options:
|
||||
- SMP Server store log flag for queue persistence (recommended)
|
||||
- [Linode API token](https://www.linode.com/docs/guides/getting-started-with-the-linode-api#get-an-access-token) for automatic DNS and tagging (scopes: read/write for "linodes" and "domains")
|
||||
- Domain name (e.g., `smp1.example.com`) - the [domain must exist](https://cloud.linode.com/domains/create) in your Linode account
|
||||
|
||||
After deployment (up to 5 minutes), get the server address from Linode tags or SSH: `smp://<fingerprint>@<fqdn>`.
|
||||
|
||||
## Monitoring
|
||||
|
||||
SMP and XFTP routers expose Prometheus metrics via a control port. The control port also supports commands for runtime inspection (queue counts, client counts, statistics). See module specs linked from each router section in [`spec/routers.md`](../spec/routers.md) (Control, Prometheus, Stats).
|
||||
|
||||
## Protocol references
|
||||
|
||||
- [SimpleX Messaging Protocol](../protocol/simplex-messaging.md) - SMP wire format and security properties
|
||||
- [XFTP Protocol](../protocol/xftp.md) - data packet protocol
|
||||
- [Push Notifications Protocol](../protocol/push-notifications.md) - NTF protocol
|
||||
- [SimpleX Network overview](../protocol/overview-tjr.md) - architecture and trust model
|
||||
@@ -0,0 +1,126 @@
|
||||
# BBS+ Bindings for simplexmq
|
||||
|
||||
Haskell FFI bindings to libbbs for BBS+ signatures. General-purpose - the module knows nothing about specific applications.
|
||||
|
||||
## How BBS+ works
|
||||
|
||||
BBS+ signs a fixed list of N messages. Each message is an arbitrary byte array. The signer signs all N messages at once with one signature.
|
||||
|
||||
The holder of the signature can then generate a proof that selectively discloses some messages and hides others. The verifier learns the disclosed messages and confirms they were signed by the signer, but learns nothing about the hidden messages. Different proofs from the same signature are unlinkable.
|
||||
|
||||
Key constraint: the total number of messages N is fixed at signing time. The verifier must know N. A proof generated from a 3-message signature cannot be verified as a 2-message proof.
|
||||
|
||||
## Types
|
||||
|
||||
```haskell
|
||||
newtype BBSSecretKey = BBSSecretKey ByteString -- 32 bytes
|
||||
newtype BBSPublicKey = BBSPublicKey ByteString -- 96 bytes (BLS12-381 G2 point)
|
||||
newtype BBSSignature = BBSSignature ByteString -- 80 bytes
|
||||
newtype BBSProof = BBSProof ByteString -- 272 + 32 * numUndisclosed bytes
|
||||
newtype BBSHeader = BBSHeader ByteString -- always-disclosed context (e.g. protocol identifier)
|
||||
newtype BBSPresHeader = BBSPresHeader ByteString -- random nonce for proof unlinkability
|
||||
```
|
||||
|
||||
All newtypes get StrEncoding (base64url), ToJSON/FromJSON (via strToJSON/strParseJSON), Eq, Show.
|
||||
|
||||
## Functions
|
||||
|
||||
```haskell
|
||||
bbsKeyGen :: IO (Either String BBSKeyPair) -- BBSKeyPair = (BBSPublicKey, BBSSecretKey)
|
||||
|
||||
-- pk is derived from sk internally, so it is not a parameter
|
||||
bbsSign
|
||||
:: BBSSecretKey
|
||||
-> BBSHeader -- always-disclosed context
|
||||
-> [ByteString] -- all N messages
|
||||
-> IO (Either String BBSSignature)
|
||||
|
||||
-- C order: pk, signature, header, presentation_header, disclosed_indexes, messages
|
||||
bbsProofGen
|
||||
:: BBSPublicKey
|
||||
-> BBSSignature
|
||||
-> BBSHeader -- must match what was signed
|
||||
-> BBSPresHeader -- random nonce bound into the proof
|
||||
-> [Int] -- disclosed indexes (0-based)
|
||||
-> [ByteString] -- all N messages (needed internally, hidden ones not revealed in proof)
|
||||
-> IO (Either String BBSProof)
|
||||
|
||||
-- C order: pk, proof, header, presentation_header, disclosed_indexes, n, messages
|
||||
bbsProofVerify
|
||||
:: BBSPublicKey
|
||||
-> BBSProof
|
||||
-> BBSHeader -- must match what was signed
|
||||
-> BBSPresHeader -- must match what was used in bbsProofGen
|
||||
-> [Int] -- disclosed indexes
|
||||
-> Int -- total message count N
|
||||
-> [ByteString] -- disclosed messages only
|
||||
-> IO Bool
|
||||
```
|
||||
|
||||
## How applications use it
|
||||
|
||||
An application defines:
|
||||
- A message layout: which index means what
|
||||
- Which indexes are disclosed vs hidden
|
||||
- How to encode application values as ByteString messages
|
||||
|
||||
### Badge example (in simplex-chat, not in this module)
|
||||
|
||||
Message layout (always 3 messages):
|
||||
- Index 0: master secret (32 random bytes) - HIDDEN
|
||||
- Index 1: expiry (UTF-8 encoded timestamp string) - DISCLOSED
|
||||
- Index 2: badge type (UTF-8 encoded, e.g. "supporter") - DISCLOSED
|
||||
|
||||
Signing (v2, on the server):
|
||||
```
|
||||
bbsSign sk header [ms, encodeUtf8 "2026-07-31", encodeUtf8 "supporter"]
|
||||
```
|
||||
|
||||
Proof generation (v2, on the client):
|
||||
```
|
||||
bbsProofGen pk sig header presHeader [1, 2] [ms, encodeUtf8 "2026-07-31", encodeUtf8 "supporter"]
|
||||
```
|
||||
|
||||
Proof verification (v1, on the recipient):
|
||||
```
|
||||
bbsProofVerify pk proof header presHeader 3 [1, 2] [encodeUtf8 "2026-07-31", encodeUtf8 "supporter"]
|
||||
```
|
||||
|
||||
The recipient only sees the proof, presentationHeader, expiry string, and badge type string. They verify these were signed by the server (pk is hardcoded). They never see the master secret.
|
||||
|
||||
Expiry is always present as a string. Monthly badges use a date like `"2026-07-31"`, lifetime badges use `"lifetime"`. BBS+ doesn't interpret the bytes - expiry semantics are the application's responsibility. This keeps the message count fixed at 3 for all badge types.
|
||||
|
||||
## libbbs C API mapping
|
||||
|
||||
```c
|
||||
int bbs_keygen_full(ciphersuite, sk, pk)
|
||||
int bbs_sign(ciphersuite, sk, pk, signature, header, header_len, n, messages, message_lens)
|
||||
int bbs_proof_gen(ciphersuite, pk, signature, proof, header, header_len, presentation_header, presentation_header_len, disclosed_indexes, disclosed_indexes_len, n, messages, message_lens)
|
||||
int bbs_proof_verify(ciphersuite, pk, proof, proof_len, header, header_len, presentation_header, presentation_header_len, disclosed_indexes, disclosed_indexes_len, n, messages, message_lens)
|
||||
```
|
||||
|
||||
We use `bbs_sha256_ciphersuite`. The header parameter is exposed in all Haskell functions - the application decides what to put there. Tests use `"SimpleX"` as header.
|
||||
|
||||
The `presentation_header` parameter is what we call `presentationHeader`.
|
||||
|
||||
In `bbs_proof_verify`, the `n` parameter is the total number of messages (not the number of disclosed messages). The `messages` array contains only the disclosed messages, and `disclosed_indexes` maps each to its position in the original message list.
|
||||
|
||||
## Build
|
||||
|
||||
Submodules in cbits/:
|
||||
- `cbits/libbbs` - https://github.com/Fraunhofer-AISEC/libbbs
|
||||
- `cbits/blst` - https://github.com/supranational/blst (libbbs dependency)
|
||||
|
||||
C sources in cabal: `cbits/blst/src/server.c`, `cbits/blst/build/assembly.S`, libbbs source files.
|
||||
Include dirs: `cbits/blst/bindings/`, `cbits/blst/src/`, `cbits/libbbs/include/`, `cbits/libbbs/src/`.
|
||||
C flags: `-D__BLST_PORTABLE__` for cross-CPU-generation compatibility.
|
||||
|
||||
## Tests
|
||||
|
||||
- Keygen produces keys of correct size
|
||||
- Sign + proofGen + proofVerify roundtrip succeeds
|
||||
- Tampered proof fails verification
|
||||
- Tampered disclosed message fails verification
|
||||
- Wrong public key fails verification
|
||||
- Two proofs from same credential with different nonces both verify
|
||||
- Proof size matches expected (272 + 32 * numUndisclosed)
|
||||
@@ -0,0 +1,57 @@
|
||||
## Root cause: orphaned `Sub` entries in the service client's `subscriptions` map
|
||||
|
||||
**The leak is service-specific and was introduced by PR #1667 "messaging services" (`f0b7a4be`).** A long-lived messaging-service connection accumulates per-queue `Sub` records in its `Client.subscriptions` map that are **never removed** when the associated queues are deleted or unassociated — only the counter is decremented. Over normal queue churn the map grows monotonically for the entire lifetime of the service connection.
|
||||
|
||||
### The proof — an asymmetry between two handlers in `serverThread`
|
||||
|
||||
Both individual queue subscriptions and service subscriptions store a `Sub` per queue in `Client.subscriptions` (= `clientSubs` for the SMP subscriber thread, wired at `Server.hs:189`). When a queue ends/is deleted, the two paths diverge:
|
||||
|
||||
**Individual subscriber — entry IS removed** (`Server.hs:332`, `346`):
|
||||
```haskell
|
||||
CSAEndSub qId -> atomically (endSub c qId) >>= a unsub_ -- :332
|
||||
...
|
||||
endSub c qId = TM.lookupDelete qId (clientSubs c) >>= (removeWhenNoSubs c $>) -- :346
|
||||
```
|
||||
|
||||
**Service subscriber — entry is NOT removed** (`Server.hs:336-340`):
|
||||
```haskell
|
||||
CSAEndServiceSub qId -> atomically $ do
|
||||
modifyTVar' (clientServiceSubs c) decrease -- decrements serviceSubsCount
|
||||
modifyTVar' totalServiceSubs decrease -- decrements global count
|
||||
where decrease = subtractServiceSubs (1, queueIdHash qId)
|
||||
-- never touches (clientSubs c) — the Sub for qId stays forever
|
||||
```
|
||||
|
||||
### Where the orphaned entries are added (both new in this PR)
|
||||
- `Server.hs:1860-1862` — on service subscribe (`SSUB`), one `Sub` inserted per queue that has a pending message.
|
||||
- `Server.hs:2039-2043` (`newServiceDeliverySub`) — on **every** `SEND` to a service-associated queue with no existing sub, a `Sub` is inserted into the service client's `subscriptions`. After delivery the thread state resets to `NoSub` (`:2069`) but the map entry remains as a "already delivering" marker (`:1856-1859`).
|
||||
|
||||
### Why they leak
|
||||
The only places the service client's `subscriptions` map is cleared are:
|
||||
- `clientDisconnected` — `swapTVar subscriptions M.empty` (`Server.hs:1097`) — only on disconnect.
|
||||
- `CSADecreaseSubs` — `swapTVar (clientSubs c) M.empty` (`Server.hs:343`) — only on full service takeover by another connection.
|
||||
- `delQueueAndMsgs` — `TM.lookupDelete entId $ subscriptions clnt` (`Server.hs:2164`) — but `clnt` here is **the recipient deleting its own queue, not the service client**. The service's entry for that queue is reached only via the `CSDeleted → endServiceSub → CSAEndServiceSub` path (`Server.hs:306, 313, 336`), which decrements the counter but leaves the map entry.
|
||||
|
||||
**Concrete scenario (fully traced):** Service `S` subscribes (`SSUB`) and stays connected for days. Recipient `R` owns service-associated queue `Q`. A `SEND` to `Q` inserts a `Sub` into `S.subscriptions[Q]` (`:2042`). `R` later deletes `Q` → `delQueueAndMsgs` runs on `R`'s connection, removes `Q` from `R.subscriptions`, decrements counters, enqueues `CSDeleted Q (Just S)` (`:2167`) → `serverThread` runs `CSAEndServiceSub Q` for `S` (`:336`), decrementing `S.serviceSubsCount` but **leaving `S.subscriptions[Q]` in place**. Net: one orphaned `Sub` (record + 2 TVars) per service-associated queue ever deleted/unassociated, never reclaimed until `S` disconnects. The logical counter `serviceSubsCount` correctly drops, so the map size diverges from the counter — making the leak invisible to the existing service-sub metric.
|
||||
|
||||
### Verdict
|
||||
This is a deterministic, static-provable memory leak — no production logging needed to confirm the existence; the asymmetry between `CSAEndSub` (removes) and `CSAEndServiceSub` (doesn't) is the smoking gun. It is specific to messaging-service certificate clients, which is exactly the population added by the services/certificate PR.
|
||||
|
||||
### Secondary findings (lower impact, same PR area, not the primary cause)
|
||||
- **`forkClient` register-after-fork race** (`Server.hs:1356-1359`): if the forked action's `finally` delete (`:1358`) runs before the parent's `IM.insert` (`:1359`), a `Weak ThreadId` of a dead thread is left in `endThreads` until disconnect. Pre-existing, tiny per-entry, but exercised far more by the PR's higher END/DELD volume.
|
||||
- **Wrong-client counter decrement** (`Server.hs:2166`): `delQueueAndMsgs` decrements `serviceSubsCount` of the *deleting* client, not the service; harmless for non-service deleters (floored at 0) but corrupts accounting if a service deletes its own queue.
|
||||
|
||||
---
|
||||
|
||||
### Recommended fix (mirror `endSub` in the service path)
|
||||
Make `CSAEndServiceSub` also delete the per-queue `Sub` and cancel its delivery thread, exactly as `CSAEndSub`/`endSub` do for individual subscribers. Roughly:
|
||||
|
||||
```haskell
|
||||
CSAEndServiceSub qId -> do
|
||||
s_ <- atomically $ do
|
||||
modifyTVar' (clientServiceSubs c) decrease
|
||||
modifyTVar' totalServiceSubs decrease
|
||||
TM.lookupDelete qId (clientSubs c) <* removeWhenNoSubs c
|
||||
forM_ unsub_ $ \unsub -> mapM_ unsub s_
|
||||
where decrease = subtractServiceSubs (1, queueIdHash qId)
|
||||
```
|
||||
@@ -0,0 +1,455 @@
|
||||
# Server: SMP support for public namespaces
|
||||
|
||||
> **⚠ Implementation diverged from this plan.** Six audit rounds reshaped the
|
||||
> original design. **The shipped code differs in several load-bearing ways:**
|
||||
>
|
||||
> - **Wire format**: `NameRecord` is now JSON (aeson), not the custom binary
|
||||
> ABNF this plan documents. See `protocol/simplex-messaging.md` §Resolver
|
||||
> commands and `src/Simplex/Messaging/Protocol.hs` ToJSON/FromJSON instances.
|
||||
> - **No cache**: the TTL + FIFO + byte-cap cache, in-flight coalescing,
|
||||
> `psqueues` dep, and `cache_*` INI keys are all gone. Every RSLV becomes
|
||||
> one `eth_call` bounded by `rpcMaxConcurrency` + `rpcTimeoutMs`. See
|
||||
> `src/Simplex/Messaging/Server/Names.hs`.
|
||||
> - **No `allow_dangerous_colocation` flag**: the proxy co-location guard
|
||||
> was demoted to a startup `logWarn` (the flag was always-on because
|
||||
> `[PROXY]` has no enable toggle).
|
||||
> - **Module shape**: `Names/Resolver.hs` was merged into `Names.hs`; only
|
||||
> `Names/Eth/RPC.hs` and `Names/Eth/SNRC.hs` remain as separate modules.
|
||||
> - **Test list**: of the 15 specs listed below, ~7 shipped; the rest were
|
||||
> either superseded by the cache removal (CacheSpec) or deferred
|
||||
> (ForwardedRslvSpec, MockRpcSpec, StartupGuardSpec, UrlValidationSpec,
|
||||
> EipChecksumSpec).
|
||||
>
|
||||
> Sources of truth: `CHANGELOG.md` (release notes),
|
||||
> `protocol/simplex-messaging.md` §Resolver commands (wire format),
|
||||
> `src/Simplex/Messaging/Server/Names*.hs` (implementation). This file is
|
||||
> retained as historical context; do not treat it as a specification.
|
||||
|
||||
Implementation plan for Part 2 of [RFC 2026-05-21-public-namespaces](https://github.com/simplex-chat/simplex-chat/blob/ep/namespace/docs/rfcs/2026-05-21-public-namespaces.md). Adds a forwarded-only `RSLV <lookup_key>` SMP command that returns `NAME <NameRecord>` read from the SNRC contract via a Reth+Nimbus JSON-RPC endpoint. Smp-server becomes name-capable by `[NAMES] enable: on`.
|
||||
|
||||
Out of scope: `Simplex.Messaging.Client` API, agent-side resolution flow, `ServerRoles.names` in the agent, default-router list, reverse resolution, multicoin/text records, state proofs.
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Client
|
||||
participant P as Proxy (storage role)
|
||||
participant N as Name server (names role)
|
||||
participant E as Ethereum endpoint<br/>(Reth+Nimbus)
|
||||
|
||||
C ->> P: PFWD(enc(RSLV key))
|
||||
P ->> N: RFWD(enc(RSLV key))
|
||||
note over N: verifyTransmission True →<br/>vc SResolver (RSLV _) → VRVerified
|
||||
N ->> N: cache lookup
|
||||
alt cache miss
|
||||
N ->> E: eth_call(SNRC, namehash(key))
|
||||
E -->> N: ABI bytes
|
||||
note over N: ABI decode + zero-owner check + cache insert
|
||||
end
|
||||
N -->> P: RFWD(enc(NAME rec | ERR AUTH))
|
||||
P -->> C: PRES(enc(NAME rec | ERR AUTH))
|
||||
```
|
||||
|
||||
RSLV is **forwarded-only** — direct RSLV is rejected `CMD PROHIBITED`. This preserves the RFC's two-server resolution: the name server sees the lookup key but never the client's IP, session, or identity.
|
||||
|
||||
## Protocol
|
||||
|
||||
Shared library: `src/Simplex/Messaging/Protocol.hs` and `src/Simplex/Messaging/Transport.hs`.
|
||||
|
||||
**Version.** `Transport.hs:226`: `namesSMPVersion = VersionSMP 20`. Bump `currentClientSMPRelayVersion`, `currentServerSMPRelayVersion`, `proxiedSMPRelayVersion` to 20. Pre-v20 binaries lack the `RSLV_` tag; v20 binaries with sessions negotiated at v < 20 reject `RSLV_` at the parameter parser. The proxied-version bump 18 → 20 is safe (v19's `RecipientService`/`NotifierService` aren't in the forwarded whitelist; v18's `BLOCKED info` is already version-branched at `Protocol.hs:1943`).
|
||||
|
||||
**Party kind.** Append `Resolver` to `Party` (line 335); add `SResolver` (line 349), `TestEquality` clause (line 361), `PartyI Resolver` (line 394). `queueParty SResolver = Nothing` (falls through line 412). `partyClientRole SResolver = Nothing`.
|
||||
|
||||
**`RSLV` command.**
|
||||
|
||||
```haskell
|
||||
RSLV :: LookupKey -> Command Resolver
|
||||
newtype LookupKey = LookupKey ByteString
|
||||
|
||||
instance Encoding LookupKey where
|
||||
smpEncode (LookupKey s) = smpEncode s
|
||||
smpP = do
|
||||
n <- lenP
|
||||
when (n > 64) $ fail "LookupKey too large"
|
||||
LookupKey <$> A.take n
|
||||
```
|
||||
|
||||
Name-syntax validation is client-side per RFC; the server treats the key as opaque bytes. Tag `"RSLV"`, version guard inside `protocolP v (CT SResolver RSLV_)`: `| v >= namesSMPVersion -> Cmd SResolver . RSLV <$> _smpP`.
|
||||
|
||||
**Testnet/mainnet selector**: how the `#testnet:name` namespace appears in `LookupKey` bytes is determined by the SNRC contract (Part 1) — confirm with Part 1 before merging.
|
||||
|
||||
**`NAME` response.**
|
||||
|
||||
```haskell
|
||||
NAME :: NameRecord -> BrokerMsg
|
||||
```
|
||||
|
||||
Tag `"NAME"`. Symmetric version guards on encode (in `encodeProtocol v`) and decode (in `protocolP v NAME_`): `| v >= namesSMPVersion -> ...`. `NameRecord` has **no `Encoding` typeclass instance** — the typeclass cannot version-branch. Use top-level helpers `nameRecBytes :: VersionSMP -> NameRecord -> ByteString` and `parseNameRec :: VersionSMP -> Parser NameRecord`, mirroring the `IDS QIK` precedent at `Protocol.hs:1912–1979`.
|
||||
|
||||
**`NameRecord` schema and wire layout.**
|
||||
|
||||
```haskell
|
||||
data NameRecord = NameRecord
|
||||
{ nrDisplayName :: Text -- ≤255 bytes UTF-8
|
||||
, nrOwner :: NameOwner -- 20 raw bytes
|
||||
, nrChannelLinks :: [NameLink]
|
||||
, nrContactLinks :: [NameLink]
|
||||
, nrAdminAddress :: Maybe Text
|
||||
, nrAdminEmail :: Maybe Text
|
||||
, nrExpiry :: Int64 -- Unix seconds, ≥ 0
|
||||
, nrIsTest :: Bool
|
||||
}
|
||||
|
||||
newtype NameOwner = NameOwner ByteString -- bare ctor NOT exported; smart ctor enforces length 20
|
||||
newtype NameLink = NameLink Text -- bare ctor NOT exported; smart ctor enforces ≤1024 bytes
|
||||
|
||||
unNameOwner :: NameOwner -> ByteString
|
||||
unNameOwner (NameOwner bs) = bs
|
||||
|
||||
unNameLink :: NameLink -> Text
|
||||
unNameLink (NameLink t) = t
|
||||
```
|
||||
|
||||
Field additions are gated by future SMP version bumps (matching the `IDS QIK` precedent at `Protocol.hs:1912–1979`) — no separate record-version field.
|
||||
|
||||
| Field | Encoding | Max bytes |
|
||||
|---|---|---|
|
||||
| `nrDisplayName` | 1-byte length prefix + UTF-8 | 1 + 255 |
|
||||
| `nrOwner` | 20 raw bytes, no prefix | 20 |
|
||||
| `nrChannelLinks`, `nrContactLinks` | 1-byte count + per-element (Word16 BE len + UTF-8); combined cap **8 entries** across both lists | 1 + Σ(2 + ≤1024) |
|
||||
| `nrAdminAddress`, `nrAdminEmail` | `'0'` or `'1'` + (1-byte length + UTF-8 if `'1'`) | 1 + 1 + 255 |
|
||||
| `nrExpiry` | two big-endian `Word32` | 8 |
|
||||
| `nrIsTest` | `'T'` or `'F'` | 1 |
|
||||
|
||||
`Encoding NameLink` reads the Word16 length **before** `A.take` allocates — going through the existing `Large` wrapper allows up to 65 535 bytes per element. There is no `Encoding [a]` instance — use `smpEncodeList` / `smpListP` / a bounded variant:
|
||||
|
||||
```haskell
|
||||
smpListPUpTo :: Encoding a => Int -> Parser [a]
|
||||
smpListPUpTo cap = do
|
||||
n <- lenP
|
||||
when (n > cap) $ fail "list too long"
|
||||
A.count n smpP
|
||||
|
||||
parseNameRec _v = do
|
||||
nrDisplayName <- smpP
|
||||
nrOwner <- smpP
|
||||
nrChannelLinks <- smpListPUpTo 8
|
||||
nrContactLinks <- smpListPUpTo (8 - length nrChannelLinks)
|
||||
nrAdminAddress <- smpP
|
||||
nrAdminEmail <- smpP
|
||||
nrExpiry <- smpP
|
||||
when (nrExpiry < 0) $ fail "expiry must be non-negative"
|
||||
nrIsTest <- smpP
|
||||
pure NameRecord{..}
|
||||
```
|
||||
|
||||
Both list parsers fail at the count step before allocating; the second inherits the residual budget. Canonical encoding by construction: every primitive has exactly one valid byte form — two name servers reading the same SNRC state produce byte-identical responses.
|
||||
|
||||
**Wire-size budget.** `paddedProxiedTLength = 16226` is the plaintext input to `cbEncrypt` (`Server.hs:2117`); `pad` reserves 2 bytes → framed transmission ≤ 16 224 bytes. Combined-link cap 8 yields max payload ≈ 9 050 bytes — generous margin.
|
||||
|
||||
**Error semantics.** A single wire code: `ERR AUTH`. Per RFC, this collapses every failure (name not found, malformed key, names disabled, RPC unreachable, decode error, timeout). Resolver internally distinguishes the cause for stats only.
|
||||
|
||||
**Forwarded-only access.** Direct RSLV is rejected with `CMD PROHIBITED`. The shape of `THAuthServer` alone cannot discriminate direct from forwarded (`Transport.hs:852` sets `sessSecret' = Just _` for every v6+ direct client too). An explicit `forwarded :: Bool` flag is threaded through `verifyTransmission` (see below).
|
||||
|
||||
## Server changes
|
||||
|
||||
All edits in `src/Simplex/Messaging/Server.hs`.
|
||||
|
||||
**`forwarded :: Bool` plumbing.** Three signatures change:
|
||||
|
||||
- `verifyTransmission :: Bool -> ...` (line 1233) — direct path passes `False` (lines 1152–1153), forwarded path passes `True` (line 2129).
|
||||
- `verifyLoadedQueue :: Bool -> ...` (line 1238) — receives the flag from `verifyTransmission` (lines 1235, 1240).
|
||||
- `verifyQueueTransmission :: Bool -> ...` (line 1244) — receives and uses the flag.
|
||||
|
||||
New `vc` clauses inside `verifyQueueTransmission`:
|
||||
|
||||
```haskell
|
||||
vc SResolver (RSLV _) | forwarded = VRVerified Nothing
|
||||
| otherwise = VRFailed (CMD PROHIBITED)
|
||||
vc SResolver _ = VRFailed (CMD PROHIBITED) -- defensive catch-all
|
||||
```
|
||||
|
||||
**Forwarded whitelist** (`Server.hs:2132`):
|
||||
|
||||
```haskell
|
||||
Cmd SResolver (RSLV _) -> True
|
||||
```
|
||||
|
||||
**`processCommand` branch** (alongside line 1481):
|
||||
|
||||
```haskell
|
||||
Cmd SResolver (RSLV (LookupKey key)) -> do
|
||||
st <- asks (rslvStats . serverStats)
|
||||
incStat (rslvReqs st)
|
||||
asks namesEnv >>= \case
|
||||
Nothing -> incStat (rslvDisabled st) $> response (corrId, NoEntity, ERR AUTH)
|
||||
Just nenv -> liftIO (resolveName nenv key) >>= \case
|
||||
Right rec -> incStat (rslvSucc st) $> response (corrId, NoEntity, NAME rec)
|
||||
Left NotFound -> incStat (rslvNotFound st) $> response (corrId, NoEntity, ERR AUTH)
|
||||
Left _ -> incStat (rslvEthErrs st) $> response (corrId, NoEntity, ERR AUTH)
|
||||
```
|
||||
|
||||
**Shutdown.** Add `closeNamesEnv :: NamesEnv -> IO ()` calling `closeManager`. Wire into `closeServer` (`Server.hs:247`):
|
||||
|
||||
```haskell
|
||||
closeServer = do
|
||||
asks (smpAgent . proxyAgent) >>= liftIO . closeSMPClientAgent
|
||||
asks namesEnv >>= liftIO . mapM_ closeNamesEnv
|
||||
```
|
||||
|
||||
In-flight `resolveName` calls during shutdown receive `ConnectionClosed` → `EthHttpErr` → masked-leader cleanup runs → waiters unblock with `ERR AUTH`.
|
||||
|
||||
**`incStat` relocation.** Defined at `Server.hs:2220`, currently unexported. Move to `Server/Stats.hs` (one-line transplant + export) so `Resolver.hs` can use it.
|
||||
|
||||
**Co-located proxy warning.** `newEnv` logs a startup warning whenever `allowSMPProxy = True` and `namesConfig = Just _`. RSLV is the first slow forwarded command; on a proxy host it can serialise other forwarded commands on the same proxy-relay session up to `rpcTimeoutMs` per cache miss. The warning is not a hard refusal because `[PROXY]` has no `enable: on/off` toggle — proxy is always on for every smp-server. `forkForwardedCmd` async dispatch is the longer-term fix, tracked as a follow-up; once the proxy role is gateable per-server, the warning can be tightened back to a refusal.
|
||||
|
||||
## Resolver subtree
|
||||
|
||||
New module tree at `src/Simplex/Messaging/Server/Names/`:
|
||||
|
||||
| Module | Contents |
|
||||
|---|---|
|
||||
| `Names.hs` | Façade — re-exports `NamesConfig`, `NamesEnv`, `ResolveError`, `resolveName`, `newNamesEnv`, `closeNamesEnv`. |
|
||||
| `Names/Resolver.hs` | All types + cache + in-flight + `resolveName`. Helpers exported directly (no `.Internal` per codebase convention). **Test seam**: `NamesEnv` holds `ethCall` as a function value, so tests construct stubs via `newNamesEnvWith`. |
|
||||
| `Names/Eth/RPC.hs` | `EthRpcEnv`; `ethCallReal` via `http-client` + `withResponse` + `brReadSome rpcMaxResponseBytes`. JSON-RPC error / HTTP error split. `rpcMaxConcurrency` semaphore. `Authorization` header from `rpcAuth`. |
|
||||
| `Names/Eth/SNRC.hs` | `EthAddress`, Keccak-256 namehash via `crypton`'s `Crypto.Hash.Algorithms.Keccak_256` (mirroring `Crypto.hs:1023–1025` for SHA3), hand-rolled bounded Solidity ABI codec, `getRecord` with zero-owner detection. **Ethereum's Keccak ≠ NIST SHA3-256.** |
|
||||
|
||||
**ABI codec invariants**, enforced before any allocation: `offset + 32 ≤ buf.length`; `offset + 32 + length ≤ buf.length`; `offset ≥ headEnd` (no backward jumps); every length ≤ per-field cap; `string[]` outer length × 32 ≤ buf.length; recursion depth ≤ 2; `uint256 → Int64` rejects if any high 24 bytes non-zero; UTF-8 via `decodeUtf8'` returns `EthDecodeErr`.
|
||||
|
||||
**Zero-owner → `NotFound`**: ENS-style resolvers return zeroed records for non-existent names. After ABI decode, if `nrOwner == NameOwner (B.replicate 20 0)` return `Left NotFound`.
|
||||
|
||||
**Errors.**
|
||||
|
||||
```haskell
|
||||
data ResolveError = NotFound | EthHttpErr | EthRpcErr { rpcCode :: Int, rpcMessage :: Text }
|
||||
| EthDecodeErr | TimedOut
|
||||
```
|
||||
|
||||
All collapse to `ERR AUTH`. `EthRpcErr` carries JSON-RPC `error` object — method-not-found (SNRC not deployed at `snrc_address`) is logged immediately on the first error after a recent success: `logError "NAMES: JSON-RPC error from endpoint — check snrc_address: <code> <message>"`. No automatic retry.
|
||||
|
||||
**Cache.** TTL + FIFO eviction. `TVar (OrdPSQ LookupKey Word64 NameRecord, Int)` — priority = monotonic-ns at insert; the `Int` is running byte count. `cacheLookup` is one STM transaction (read, expiry-check, expired-delete-with-byte-decrement). `cacheInsert` is one STM transaction: while `size > cacheMaxEntries` OR `bytes + sizeOf(rec) > cacheMaxBytes`, `minView` to drop oldest, then `insert`. Byte counter prevents `100 000 × 9 KB ≈ 900 MB` worst-case blow-up.
|
||||
|
||||
**Request coalescing** (async-exception safe via `E.mask`):
|
||||
|
||||
```haskell
|
||||
resolveName env bs = do
|
||||
let k = LookupKey bs
|
||||
now <- getMonotonicTimeNSec
|
||||
atomically (cacheLookup env k now) >>= \case
|
||||
Just rec -> incStat (rslvCacheHits ...) $> Right rec
|
||||
Nothing -> do
|
||||
incStat (rslvCacheMiss ...)
|
||||
ticket <- atomically $ TM.lookup k (inflight env) >>= \case
|
||||
Just mv -> pure (Waiter mv)
|
||||
Nothing -> newEmptyTMVar >>= \mv -> TM.insert k mv (inflight env) $> Leader mv
|
||||
case ticket of
|
||||
Waiter mv -> atomically (readTMVar mv)
|
||||
Leader mv -> E.mask $ \restore -> do
|
||||
r <- restore (fetchOnceTimed env bs)
|
||||
`E.catch` \(e :: E.SomeException) -> pure (Left (mapEthErr e))
|
||||
atomically $ putTMVar mv r >> TM.delete k (inflight env)
|
||||
case r of Right rec -> atomically (cacheInsert env k now rec); Left _ -> pure ()
|
||||
pure r
|
||||
|
||||
fetchOnceTimed env bs =
|
||||
System.Timeout.timeout (rpcTimeoutMs (config env) * 1000) (fetchOnce env bs) >>= \case
|
||||
Just r -> pure r
|
||||
Nothing -> pure (Left TimedOut)
|
||||
```
|
||||
|
||||
`E.mask` ensures `putTMVar + TM.delete` runs even on async exception; `fetchOnceTimed` runs under `restore` so it remains interruptible. Waiters always see a value; the in-flight TMap entry is always removed.
|
||||
|
||||
`fetchOnce`, `mapEthErr`, `scrubUrl`, `cacheLookup`, `cacheInsert` are internal to `Resolver.hs`. `getMonotonicTimeNSec` from `GHC.Clock` — first monotonic-clock use in the codebase; clock-jump safe.
|
||||
|
||||
**STM contention.** Cache hits are read-only `readTVar` — STM scales. Cache writes under sustained miss traffic can retry; `CacheSpec` asserts < 5% retry at 4 readers + 1 writer @ 1k RPS. If observed higher, swap `TVar` for `IORef` + `atomicModifyIORef'`.
|
||||
|
||||
**Multicoin and text records** are not in `NameRecord`. If Part 1 contract returns them from `getRecord`, extend `NameRecord` and the wire-size budget. **Confirm with Part 1 author before implementing `Eth/SNRC.hs`.**
|
||||
|
||||
## Configuration
|
||||
|
||||
`ServerConfig` (`Env/STM.hs:142`) gains one field `namesConfig :: Maybe NamesConfig`. `Env` (`Env/STM.hs:261`) gains `namesEnv :: Maybe NamesEnv`. `newEnv` constructs it after `proxyAgent` (line 605) with the co-location guard.
|
||||
|
||||
```haskell
|
||||
data NamesConfig = NamesConfig
|
||||
{ ethereumEndpoint :: Text -- http(s), no userinfo, explicit port required
|
||||
, snrcAddress :: NameOwner -- 20 bytes
|
||||
, rpcAuth :: Maybe RpcAuth -- required when https & non-loopback host
|
||||
, cacheSeconds :: Int -- 300
|
||||
, cacheMaxEntries :: Int -- 100000
|
||||
, cacheMaxBytes :: Int -- 67108864 (64 MB)
|
||||
, rpcTimeoutMs :: Int -- 3000
|
||||
, rpcMaxResponseBytes :: Int -- 262144 (256 KB)
|
||||
, rpcMaxConcurrency :: Int -- 8
|
||||
}
|
||||
|
||||
data RpcAuth = AuthBearer Text | AuthBasic Text Text
|
||||
```
|
||||
|
||||
INI parsing in `Server/Main.hs`:
|
||||
|
||||
- `validateUrl` (using new `network-uri` dep): accepts only http(s), non-empty host, **explicit port** (rejects `http://localhost` defaulting to 80 while Reth is on 8545), no userinfo, no query/fragment. Rejects `https://...` without `rpc_auth` when host is non-loopback. On rejection: `logError` + `exitFailure`.
|
||||
- `parseEthAddr`: accepts `0x[0-9a-fA-F]{40}` and the same without `0x`. Mixed-case → verify EIP-55 checksum and reject mismatch (catches typos).
|
||||
- `parseRpcAuth`: reads optional `rpc_auth` key; format `bearer <token>` or `basic <user>:<pass>`.
|
||||
- `scrubUrl`: strips userinfo from all log lines mentioning the endpoint, including inside `mapEthErr`.
|
||||
- Transition-aware error logging: log immediately on first error after a recent success, then at most hourly while persisting + summary at every stats reset.
|
||||
|
||||
Default INI template (`Server/Main/Init.hs`, after `[PROXY]`):
|
||||
|
||||
```
|
||||
[NAMES]
|
||||
# Public-namespace resolution (SNRC on Ethereum).
|
||||
# Requires an Ethereum JSON-RPC endpoint (Reth+Nimbus). See deployment guide.
|
||||
# Cannot be combined with [PROXY] enable: on by default — see allow_dangerous_colocation.
|
||||
# Restart required to change settings.
|
||||
enable: off
|
||||
# Same-host:
|
||||
# ethereum_endpoint: http://127.0.0.1:8545
|
||||
# Central Reth via Caddy:
|
||||
# ethereum_endpoint: https://eth.simplex.chat:443
|
||||
# rpc_auth: basic <username>:<password>
|
||||
# snrc_address: 0x0000000000000000000000000000000000000000
|
||||
# cache_seconds: 300
|
||||
# cache_max_entries: 100000
|
||||
# cache_max_bytes: 67108864
|
||||
# rpc_timeout_ms: 3000
|
||||
# rpc_max_response_bytes: 262144
|
||||
# rpc_max_concurrency: 8
|
||||
# allow_dangerous_colocation: off
|
||||
```
|
||||
|
||||
Upgrade from a pre-v6.6 INI: missing `[NAMES]` section → disabled. No operator action required.
|
||||
|
||||
## Operator deployment
|
||||
|
||||
Two supported topologies. smp-server is agnostic — only `ethereum_endpoint` changes.
|
||||
|
||||
**Topology A (same-host)**: smp-server, Caddy (optional), Reth, Nimbus all on one box. `ethereum_endpoint: http://127.0.0.1:8545`.
|
||||
|
||||
**Topology B (central Reth, N smp-server hosts — recommended for fleets)**: one operator runs one eth host with Reth+Nimbus behind Caddy on public HTTPS. Each smp-server has its own credential.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph eth-host
|
||||
Caddy["Caddy<br/>(public :443, basic auth)"]
|
||||
Reth["Reth<br/>(127.0.0.1:8545)"]
|
||||
Nimbus["Nimbus"]
|
||||
Caddy --> Reth
|
||||
Nimbus -- Engine API (jwt.hex) --> Reth
|
||||
end
|
||||
subgraph smp-host-1
|
||||
S1["smp-server #1"]
|
||||
end
|
||||
subgraph smp-host-N
|
||||
SN["smp-server #N"]
|
||||
end
|
||||
S1 -- HTTPS + Authorization --> Caddy
|
||||
SN -- HTTPS + Authorization --> Caddy
|
||||
Reth <-- Ethereum p2p --> internet
|
||||
Nimbus <-- beacon sync --> internet
|
||||
```
|
||||
|
||||
Sharing one Reth across **multiple operators** is **not** supported — collapses the RFC's two-server resolution privacy.
|
||||
|
||||
**Reth + Nimbus**: Reth (execution layer) holds Ethereum state on ~260 GB pruned NVMe; Nimbus (consensus light client) follows beacon-chain headers. Paired via Engine API on `127.0.0.1:8551` with a shared `jwt.hex`. Recommended Reth flags:
|
||||
|
||||
```bash
|
||||
reth node \
|
||||
--http.addr 127.0.0.1 \
|
||||
--http.api eth \ # only eth namespace
|
||||
--rpc.gascap 50000000 \ # cap gas per eth_call
|
||||
--rpc.max-response-size 5242880 \ # 5 MB
|
||||
--http.corsdomain none \
|
||||
--authrpc.jwtsecret /opt/eth/jwt.hex \
|
||||
--authrpc.addr 127.0.0.1 --authrpc.port 8551
|
||||
```
|
||||
|
||||
**Caddy + Let's Encrypt + Basic auth** (Topology B):
|
||||
|
||||
```caddy
|
||||
eth.simplex.chat {
|
||||
basicauth {
|
||||
smp-server-1 $2a$14$<bcrypt-hash-1>
|
||||
smp-server-2 $2a$14$<bcrypt-hash-2>
|
||||
}
|
||||
log { format filter { wrap json; fields { request>headers>Authorization delete } } }
|
||||
reverse_proxy 127.0.0.1:8545
|
||||
}
|
||||
```
|
||||
|
||||
Caddy auto-fetches Let's Encrypt cert. Each smp-server has its own credential; revoking one = delete the line. `Authorization` stripped from access logs. Port 80 needed for the ACME HTTP-01 challenge (use TLS-ALPN-01 or DNS-01 to drop it). The threat being defended against is DoS (SNRC state is public); mTLS would be overkill. WireGuard/Tailscale are alternative network-layer approaches — both compatible with the plan.
|
||||
|
||||
**Capacity.** One Reth+Nimbus box handles a realistic operator fleet by 10–1000× margin. Per-smp-server peak RSLV ≈ 1700 RPS (pessimistic); cache hit rate ≥ 95% → ~85 RPS cache miss per smp-server; 10 smp-servers → ~850 RPS aggregate cache miss reaching Reth; Reth `eth_call` throughput on warm NVMe ≈ 1k–10k RPS. Sizing: 8 vCPU, 32 GB RAM, 1 TB NVMe is comfortable. Scale-out path: more Reth+Nimbus pairs, smp-servers round-robin or shard.
|
||||
|
||||
## Implementation
|
||||
|
||||
**Order**:
|
||||
|
||||
1. Protocol: party/SParty/PartyI, RSLV+tag, NAME+tag, NameRecord + helpers, version constants in `Transport.hs`.
|
||||
2. `verifyTransmission`/`verifyLoadedQueue`/`verifyQueueTransmission` `forwarded :: Bool` flag + `vc SResolver` clauses.
|
||||
3. Forwarded whitelist + `processCommand` branch + `incStat` move to `Stats.hs`.
|
||||
4. Env plumbing: `Server/Env/STM.hs`, `Server/Main.hs` INI parse, `Server/Main/Init.hs` template.
|
||||
5. Resolver subtree: `Eth/SNRC.hs` → `Eth/RPC.hs` → `Resolver.hs`.
|
||||
6. `NameResolverStats` sub-record + CSV log + Prometheus `names =` block.
|
||||
7. Replace stub in (3) with real `resolveName`.
|
||||
8. Tests.
|
||||
9. `protocol/simplex-messaging.md`: header version line 1 (`19 → 20`), sentence at line 86, version-history list (lines 93–105) v20 entry, TOC (lines 25–68) "Resolver commands" subsection, new section with ABNF + byte layout + error semantics, "Router security requirements" paragraph about names-role outbound HTTP, cross-ref `Transport.hs:226`.
|
||||
10. `CHANGELOG.md`: v6.6 entry.
|
||||
|
||||
**Cabal** (`simplexmq.cabal`): bump `version: 6.6.0.0`. Add to `if !flag(client_library)` block: `http-client >=0.7 && <0.8`, `http-client-tls >=0.3 && <0.4`, `network-uri >=2.6 && <2.7`, `psqueues >=0.2.7 && <0.3`. Expose 4 new `Server.Names.*` modules in the same block. `crypton` already provides `Keccak_256`.
|
||||
|
||||
**Files changed**:
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `Protocol.hs` | Resolver party + RSLV/NAME tags + version guards; `NameRecord` + newtypes + smart ctors; `nameRecBytes`/`parseNameRec`/`smpListPUpTo` helpers (no Encoding NameRecord instance); `LookupKey` parser-side cap |
|
||||
| `Transport.hs` | `namesSMPVersion = 20`; bump current/proxied SMP versions |
|
||||
| `Server.hs` | Thread `forwarded :: Bool`; `vc SResolver` clauses; whitelist (2132); Resolver branch in `processCommand` (1481); `closeServer` calls `closeNamesEnv`; CSV log (579–618); **remove** local `incStat` |
|
||||
| `Server/Env/STM.hs` | `namesConfig` field; `namesEnv` field; `newEnv` constructs `NamesEnv` with co-location guard |
|
||||
| `Server/Main.hs` | `[NAMES]` parse: `validateUrl`/`parseEthAddr`/`parseRpcAuth`; `scrubUrl` in logs |
|
||||
| `Server/Main/Init.hs` | `[NAMES]` block in default INI |
|
||||
| `Server/Stats.hs` | `incStat` moved here + exported; `NameResolverStats` sub-record + helpers; `rslvStats` field |
|
||||
| `Server/Prometheus.hs` | `names =` metric block |
|
||||
| `Server/Names.hs` (new) | Façade re-exports |
|
||||
| `Server/Names/Resolver.hs` (new) | All resolver types + cache + coalescing + `fetchOnceTimed` + `newNamesEnv[With]` + `closeNamesEnv` |
|
||||
| `Server/Names/Eth/RPC.hs` (new) | `EthRpcEnv`, `ethCallReal` with bounded body + concurrency semaphore + `Authorization` header |
|
||||
| `Server/Names/Eth/SNRC.hs` (new) | `EthAddress`, Keccak namehash, bounded ABI (8 invariants), `getRecord` with zero-owner detection |
|
||||
| `simplexmq.cabal` | Bump `6.6.0.0`; 4 new deps + 4 new modules in `if !flag(client_library)` block |
|
||||
| `protocol/simplex-messaging.md` | Header version, version-history v20 entry, new "Resolver commands" section |
|
||||
| `CHANGELOG.md` | v6.6 entry |
|
||||
|
||||
## Testing
|
||||
|
||||
`tests/SMPNamesTests/` registered in `tests/Test.hs:112–151`. Build only when `client_library = False`.
|
||||
|
||||
1. **ProtocolEncodingSpec** — `nameRecBytes` ↔ `parseNameRec` round-trip; oversized fields rejected at parse; combined-list cap 8 enforced; negative `nrExpiry` rejected; canonical encoding byte-stable.
|
||||
2. **MaxSizeSpec** — max `NameRecord` encodes ≤ ~9 KB; `encodeTransmission v ≤ paddedProxiedTLength - 2`; `cbEncrypt` succeeds.
|
||||
3. **CommandTagSpec** — `"RSLV"`/`"NAME"` parse; v < 20 sessions reject `RSLV_` at parameter parser.
|
||||
4. **ForwardedGateSpec** — direct RSLV → `CMD PROHIBITED`; forwarded RSLV reaches handler.
|
||||
5. **ForwardedRslvSpec** — RSLV wrapped in PFWD reaches the handler end-to-end. **Test infra cost**: first protocol-level PFWD test; budget for `runProxiedSmpCommand` helper performing `PRXY`/`PKEY`/`PFWD` manually.
|
||||
6. **CacheSpec** — hit avoids RPC; TTL expiry forces re-fetch; bytes cap evicts before entries cap on large records; concurrent same-key callers issue one RPC; leader exception → all waiters get `Left _`, TMap entry removed; leader async-cancel → cleanup STM still runs.
|
||||
7. **AbiSpec** — encode/decode against pinned fixtures (`tests/fixtures/snrc/`); QuickCheck fuzz on random buffers ≤ `rpcMaxResponseBytes` must never crash.
|
||||
8. **NamehashSpec** — Keccak-256 reference vectors; assert Keccak ≠ SHA3-256.
|
||||
9. **MockRpcSpec** — fake HTTP server; missing → `EthHttpErr`; slow → `TimedOut`; multi-GB body truncated → `EthDecodeErr`. `rpcAuth = AuthBasic` sends correct header.
|
||||
10. **Uint256OverflowSpec** — `expiry > Int64.maxBound` → `EthDecodeErr`.
|
||||
11. **ZeroOwnerSpec** — `owner = 0x000...000` → `NotFound`.
|
||||
12. **StartupGuardSpec** — `allowSMPProxy + names.enable` aborts; `allow_dangerous_colocation = on` starts with warning.
|
||||
13. **UrlValidationSpec** — userinfo/scheme/host/port edge cases; rejects `https://` without `rpc_auth` for non-loopback.
|
||||
14. **EipChecksumSpec** — `parseEthAddr` accepts lower/upper; verifies mixed-case checksum; rejects typos.
|
||||
15. **AbiBoundsSpec** — each of 8 ABI invariants triggers `EthDecodeErr` without crash/allocation blow-up.
|
||||
|
||||
Integration against real Reth+Nimbus mainnet deferred to ops.
|
||||
|
||||
## Threat model, scope, coordination
|
||||
|
||||
| Actor | Can | Cannot |
|
||||
|---|---|---|
|
||||
| Name server | See lookup-key bytes; see query timing; see Eth endpoint URL (operator-self) | See client IP/session; correlate clients across queries |
|
||||
| Compromised Eth endpoint | Poison this server's cache for one TTL window; see every lookup key the server queries | Bypass two-server agreement (client-side, out of scope) |
|
||||
| Adversarial client (high-rate unique keys) | Cache-thrash DoS; fill `Manager` connection pool up to `managerConnCount = 8` | Bypass `rpcMaxResponseBytes` or `fetchOnceTimed` |
|
||||
| Adversarial proxy (slow inner RSLVs) | Block other forwarded commands on that proxy connection up to `rpcTimeoutMs` per miss | Affect other proxy connections |
|
||||
| Operator with footgun config (https no auth, public Eth RPC) | (rejected at startup, or operator-acknowledged data leak) | — |
|
||||
|
||||
Mitigations: caching + coalescing + `rpcTimeoutMs` + `rpcMaxResponseBytes` + `rpcMaxConcurrency`; co-location refused at startup; URL validation; Caddy + auth in front of Reth; Reth's own gas/size caps. Timing side-channels (cache-hit vs miss latency) not mitigated — flagged for post-MVP. State proofs deferred to post-MVP per RFC.
|
||||
|
||||
**Cross-repo coordination.** The `simplex-chat` `ep/namespace` branch currently contains only the RFC commit — no agent-side wire-format code yet. This plan's wire format is validated only by simplexmq's own tests until a matching agent PR lands (structurally weak — encoder/decoder bugs are mutually consistent with themselves). Coordinate with the agent-side implementer **before merging** on: exact `NameRecord` field order and types; `LookupKey` namespace-prefix convention; error-code semantics; Part 1 SNRC contract `getRecord` ABI surface.
|
||||
@@ -1,4 +1,4 @@
|
||||
Version 19, 2025-01-24
|
||||
Version 20, 2026-05-25
|
||||
|
||||
# Simplex Messaging Protocol (SMP)
|
||||
|
||||
@@ -67,6 +67,9 @@ Version 19, 2025-01-24
|
||||
- [Queue deleted notification](#queue-deleted-notification)
|
||||
- [Error responses](#error-responses)
|
||||
- [OK response](#ok-response)
|
||||
- [Resolver commands](#resolver-commands)
|
||||
- [Resolve name command](#resolve-name-command)
|
||||
- [Name record response](#name-record-response)
|
||||
- [Transport connection with the SMP router](#transport-connection-with-the-SMP-router)
|
||||
- [General transport protocol considerations](#general-transport-protocol-considerations)
|
||||
- [TLS transport encryption](#tls-transport-encryption)
|
||||
@@ -83,7 +86,7 @@ It's designed with the focus on communication security and integrity, under the
|
||||
|
||||
It is designed as a low level protocol for other application protocols to solve the problem of secure and private message transmission, making [MITM attack][1] very difficult at any part of the message transmission system.
|
||||
|
||||
This document describes SMP protocol version 19. Versions 1-5 are discontinued. The version history:
|
||||
This document describes SMP protocol version 20. Versions 1-5 are discontinued. The version history:
|
||||
|
||||
- v1: binary protocol encoding
|
||||
- v2: message flags (used to control notifications)
|
||||
@@ -103,6 +106,7 @@ This document describes SMP protocol version 19. Versions 1-5 are discontinued.
|
||||
- v17: create notification credentials with NEW command
|
||||
- v18: support client notices in BLOCKED error
|
||||
- v19: service subscriptions to messages (SUBS, NSUBS, SOKS, ENDS, ALLS commands)
|
||||
- v20: public namespaces resolver (RSLV command, RNAME response) — direct or forwarded via PFWD
|
||||
|
||||
## Introduction
|
||||
|
||||
@@ -424,6 +428,8 @@ Simplex messaging router implementations MUST NOT create, store or send to any o
|
||||
|
||||
- Any other information that may compromise privacy or [forward secrecy][4] of communication between clients using simplex messaging routers (the routers cannot compromise forward secrecy of any application layer protocol, such as double ratchet).
|
||||
|
||||
Routers with the names role make outbound HTTP calls to a backing resolver service (the reference implementation is `scripts/resolver/snrc-resolve.py`, which in turn makes JSON-RPC calls to an Ethereum endpoint) to read `NameRecord` data; the lookup key reaches that resolver and its upstream RPC endpoint. Operators MUST run both the resolver process and its upstream RPC endpoint themselves (loopback Reth + Nimbus, or a self-hosted central deployment) — sharing them across multiple operators collapses the two-server privacy property because the resolver / RPC operator would see every lookup key across all of them. The names role and the SMP-proxy role MUST NOT be enabled on the same router by default: a client forwarding `RSLV` through a proxy that is also the names router would expose both its connection and the lookup key to one operator, collapsing the two-server privacy property. (Resolution itself runs on a forked thread, so a slow `RSLV` does not serialise other forwarded commands on the session.)
|
||||
|
||||
## Message delivery notifications
|
||||
|
||||
Supporting message delivery while the client mobile app is not running requires sending push notifications with the device token. All alternative mechanisms for background message delivery are unreliable, particularly on iOS platform.
|
||||
@@ -1422,6 +1428,120 @@ When the command is successfully executed by the router, it should respond with
|
||||
ok = %s"OK"
|
||||
```
|
||||
|
||||
### Resolver commands
|
||||
|
||||
Resolver commands implement public-namespace name resolution on the names-role
|
||||
router. A names router translates an opaque lookup key (such as `alice` or
|
||||
`alice.simplex.eth`) into a `NameRecord` carrying the channel and contact links
|
||||
the named party publishes.
|
||||
|
||||
**Direct or forwarded.** RSLV is an unauthenticated command accepted both
|
||||
directly from a transport client and inside a `PFWD` block via the SMP proxy;
|
||||
the client chooses. Forwarded delivery preserves the two-server privacy property
|
||||
of the resolver design: the names router sees the lookup key but never the
|
||||
client IP, session, or identity, while the proxy router sees the client
|
||||
connection but cannot read the encrypted lookup key inside the forwarded
|
||||
transmission. Direct delivery is simpler but exposes the client's connection to
|
||||
the names router, so clients SHOULD prefer the forwarded path when proxying is
|
||||
available.
|
||||
|
||||
**Backing store.** This protocol does not prescribe where the names router
|
||||
reads `NameRecord` from. The reference implementation forwards each RSLV to a
|
||||
companion REST resolver process (`scripts/resolver/snrc-resolve.py`) that
|
||||
queries the SNRC contract on Ethereum; alternative backings (different chains,
|
||||
DHT, etc.) are valid as long as they expose the documented HTTP shape (`GET
|
||||
/resolve/<name>` returning a `NameRecord` on 200, 404 / 400 for unknown names
|
||||
or TLDs, 502 for upstream RPC failures) or substitute a different transport
|
||||
while still returning a `NameRecord` matching the encoding below.
|
||||
|
||||
#### Resolve name command
|
||||
|
||||
The `RSLV` command carries the canonical fully-qualified name directly as the
|
||||
payload (not JSON):
|
||||
|
||||
```abnf
|
||||
rslv = %s"RSLV" SP domain ; domain = canonical name as non-space bytes, consuming the remainder of the transmission
|
||||
```
|
||||
|
||||
`domain` is the UTF-8 canonical fully-qualified name with the TLD always
|
||||
explicit (e.g. `privacy.simplex`, `test.testing`, `example.com`), bounded to
|
||||
253 bytes.
|
||||
|
||||
**Server-side validation.** The names router parses `domain` as a
|
||||
fully-qualified name (TLD required — bare labels are rejected) and forwards it
|
||||
to the configured backing resolver, which is the source of truth for which
|
||||
on-chain registry maps to each TLD.
|
||||
|
||||
The names router responds with either an `RNAME` response carrying the resolved
|
||||
record, or an `ERR NAME` error whose subcode a client iterating across several
|
||||
configured servers can act on distinctly:
|
||||
|
||||
| Response | Condition | Client action |
|
||||
|---|---|---|
|
||||
| `RNAME` | record resolved | use it |
|
||||
| `ERR NAME NOT_FOUND` | name not registered, unknown TLD, or malformed name | authoritative "no such name" — stop |
|
||||
| `ERR NAME NO_RESOLVER` | this router has no resolver (names role not enabled) | skip this server, try the next |
|
||||
| `ERR NAME RESOLVER <detail>` | transient failure: backing resolver error (upstream 5xx, transport, timeout, decode) | transient — retry or surface, do not treat as "not found" |
|
||||
|
||||
A client SHOULD NOT broadcast a `name` to further servers after a name-capable
|
||||
router has answered (`NOT_FOUND` or `RESOLVER`), since that router has already
|
||||
seen the lookup key; `NO_RESOLVER` discloses nothing about the name beyond the
|
||||
fact that this router cannot resolve, so iterating past it is safe.
|
||||
|
||||
#### Name record response
|
||||
|
||||
The `RNAME` response carries a JSON-encoded record as the payload:
|
||||
|
||||
```abnf
|
||||
rname = %s"RNAME" SP json-bytes ; json-bytes consumes the remainder of the transmission
|
||||
```
|
||||
|
||||
`json-bytes` MUST be a UTF-8 JSON object with the following schema:
|
||||
|
||||
| Field | JSON type | Constraints |
|
||||
|---|---|---|
|
||||
| `name` | string | ≤ 255 bytes UTF-8 |
|
||||
| `nickname` | string | ≤ 255 bytes UTF-8; senders MUST emit the empty string `""` when unset |
|
||||
| `website` | string | ≤ 255 bytes UTF-8; same empty-string-when-unset rule |
|
||||
| `location` | string | ≤ 255 bytes UTF-8; same empty-string-when-unset rule |
|
||||
| `simplexContact` | array of strings | each a SimpleX contact link (primary first); empty array `[]` when unset |
|
||||
| `simplexChannel` | array of strings | each a SimpleX channel link (primary first); empty array `[]` when unset |
|
||||
| `eth` | string or null | ≤ 255 bytes UTF-8; senders MUST emit `null` when unset; receivers MUST also accept absent keys as unset |
|
||||
| `btc` | string or null | ≤ 255 bytes UTF-8; same null / absent rules |
|
||||
| `xmr` | string or null | ≤ 255 bytes UTF-8; same null / absent rules |
|
||||
| `dot` | string or null | ≤ 255 bytes UTF-8; same null / absent rules |
|
||||
| `owner` | string | `"0x"` followed by 40 lowercase hex characters (20 raw bytes) |
|
||||
| `resolver` | string | `"0x"` followed by 40 lowercase hex characters; the resolver contract address that produced the record |
|
||||
|
||||
Text fields (`nickname`, `website`, `location`) use the empty string `""` as
|
||||
the "unset" sentinel: a backing resolver with no value for the field MUST emit
|
||||
an empty string, not JSON `null` and not an absent key. Link fields
|
||||
(`simplexContact`, `simplexChannel`) are arrays, primary link first, and use the
|
||||
empty array `[]` when unset. Coin fields (`eth`, `btc`, `xmr`, `dot`) use JSON
|
||||
`null` as the "unset" sentinel and MAY also be absent from the object entirely.
|
||||
|
||||
The backing resolver filters records that are expired or otherwise unavailable
|
||||
(the names router then returns `ERR NAME NOT_FOUND` to the client), so the wire
|
||||
format carries no expiry field. Testnet-vs-mainnet status is derived from the
|
||||
queried TLD rather than an in-record flag.
|
||||
|
||||
Receivers MUST tolerate extra unknown fields (forward-compatibility for future
|
||||
field additions). Adding a required field is a breaking change requiring an
|
||||
SMP version bump.
|
||||
|
||||
**Field order is not significant.** Receivers parse JSON by key name, so object
|
||||
key order, insignificant whitespace, and number formatting carry no meaning;
|
||||
records are interpreted by decoded value, never compared byte-for-byte. Peers
|
||||
MUST NOT rely on a byte-canonical form — a different resolver or server may emit
|
||||
the same record with different key order or spacing. This order-independence is
|
||||
what makes the format forward-compatible (see the unknown-field rule above).
|
||||
|
||||
**Wire-size budget.** The names router caps the resolver response it will
|
||||
accept (`resolver_max_response_bytes`, ≤ 16000 bytes, the default) so the
|
||||
re-encoded `RNAME` stays within the SMP proxied transmission budget of 16224
|
||||
bytes; a response over the cap is rejected as `ERR NAME RESOLVER`. The link
|
||||
arrays are bounded by this overall budget rather than a fixed per-field count.
|
||||
|
||||
## Transport connection with the SMP router
|
||||
|
||||
### General transport protocol considerations
|
||||
|
||||
@@ -237,11 +237,11 @@ checks() {
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$path_conf_info" "$path_tmp_bin"
|
||||
|
||||
check_versions
|
||||
check_distro
|
||||
|
||||
mkdir -p $path_conf_info $path_tmp_bin
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# ============================================================================
|
||||
# Required settings — the stack will not start without these.
|
||||
# ============================================================================
|
||||
|
||||
# Ethereum network: mainnet (the SNRC `.testing` contracts live on mainnet)
|
||||
# or holesky (test). Mainnet full sync needs ~1 day and ~1.2 TB NVMe.
|
||||
NETWORK=mainnet
|
||||
|
||||
# Beacon checkpoint-sync URL — used ONCE on first sync. Must expose the heavy
|
||||
# /eth/v2/debug/beacon/states/finalized endpoint (generic beacon APIs do not;
|
||||
# use a dedicated checkpoint provider). List: https://eth-clients.github.io/checkpoint-sync-endpoints/
|
||||
# mainnet: https://mainnet-checkpoint-sync.attestant.io (also beaconstate.info, sync-mainnet.beaconcha.in)
|
||||
# holesky: https://checkpoint-sync.holesky.ethpandaops.io
|
||||
TRUSTED_NODE_URL=https://mainnet-checkpoint-sync.attestant.io
|
||||
|
||||
# ============================================================================
|
||||
# Optional overrides — sensible defaults are baked into docker-compose.yml,
|
||||
# so leave these commented unless you need to change them.
|
||||
# ============================================================================
|
||||
|
||||
# Nimbus NAT (default: any). For a stable public node set an explicit IP:
|
||||
# NAT=extip:1.2.3.4 # your public IPv4: curl -s ifconfig.me
|
||||
@@ -0,0 +1,146 @@
|
||||
# Self-hosted SNRC stack
|
||||
|
||||
One `docker compose up` runs the self-hosted SimpleX Namespace (SNRC) backend
|
||||
against **Ethereum mainnet** (where the `.testing` contracts live):
|
||||
|
||||
| # | Component | What it does |
|
||||
|---|---|---|
|
||||
| 1 | **reth + nimbus** | self-hosted Ethereum node (`--minimal` — enough for the resolver's `eth_call` at chain head) |
|
||||
| 2 | **resolver** | the REST resolver the smp-server's `[NAMES]` role queries (`snrc-resolve.py`) |
|
||||
|
||||
## Requirements
|
||||
|
||||
- **Docker** + Compose v2.
|
||||
- **≥ 300 GB NVMe SSD** for `reth --minimal` (~260 GB on mainnet; TLC, not QLC
|
||||
— QLC stalls during sync) + **32 GB RAM**, fast multi-core CPU.
|
||||
- **~1 day** for the initial reth sync. The resolver returns errors until reth
|
||||
has caught up — that's expected.
|
||||
- Firewall: open p2p ports `30303` (tcp/udp) and `9000` (tcp/udp).
|
||||
|
||||
## 1. Configure
|
||||
|
||||
Edit `.env` — the defaults work as-is; override only if needed:
|
||||
|
||||
```sh
|
||||
NETWORK=mainnet # default
|
||||
TRUSTED_NODE_URL=https://mainnet-checkpoint-sync.attestant.io # default
|
||||
```
|
||||
|
||||
Everything else (NAT) has a working default baked into `docker-compose.yml`;
|
||||
uncomment the hints in `.env` only to override.
|
||||
|
||||
## 2. Run
|
||||
|
||||
```sh
|
||||
cd scripts/resolver
|
||||
docker compose up -d
|
||||
docker compose logs -f reth resolver
|
||||
```
|
||||
|
||||
`depends_on` handles ordering automatically (start node → start resolver).
|
||||
|
||||
## 3. Wait for the node to sync
|
||||
|
||||
```sh
|
||||
docker compose logs --tail=20 reth
|
||||
```
|
||||
|
||||
This is the long pole (~1 day on mainnet). Until reth is synced the resolver
|
||||
returns `502`.
|
||||
|
||||
## Verify
|
||||
|
||||
Run these once the stack is up (the node-dependent ones pass after sync):
|
||||
|
||||
**1. reth is reachable and reporting a block:**
|
||||
```sh
|
||||
curl -s -X POST http://127.0.0.1:8545 \
|
||||
-H 'content-type: application/json' \
|
||||
-d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' | jq
|
||||
```
|
||||
|
||||
**2. resolver is healthy:**
|
||||
```sh
|
||||
curl -s http://127.0.0.1:8000/health | jq
|
||||
# → {"ok": true, "rpc": "http://reth:8545", "registries": {"testing": "0x…", "simplex": ""}}
|
||||
```
|
||||
|
||||
**3. resolver resolves a live name** (`foobar.testing` is a populated test name):
|
||||
```sh
|
||||
curl -s http://127.0.0.1:8000/resolve/foobar.testing | jq
|
||||
# → {"name":"foobar.testing","nickname":"Foo","simplexContact":["https://smp16.simplex.im/a#…"], … }
|
||||
```
|
||||
|
||||
**Wire your smp-server:** in its `[NAMES]` section set
|
||||
`resolver_endpoint: http://127.0.0.1:8000` (no auth needed for loopback).
|
||||
|
||||
## Ports (all loopback unless noted)
|
||||
|
||||
| Service | Host | Purpose |
|
||||
|---|---|---|
|
||||
| reth JSON-RPC | `127.0.0.1:8545` | smp-server RPC |
|
||||
| reth p2p | `:30303` tcp/udp | Ethereum sync (open on firewall) |
|
||||
| nimbus p2p | `:9000` tcp/udp | beacon sync (open on firewall) |
|
||||
| nimbus REST | `127.0.0.1:5052` | beacon API |
|
||||
| **resolver** | `127.0.0.1:8000` | SNRC REST (`/resolve`, `/health`) |
|
||||
|
||||
## Caveats
|
||||
|
||||
- **All images track `:latest`** (reth, nimbus) — you get upstream fixes on each
|
||||
`docker compose pull`; re-run the verify checks after pulling.
|
||||
- All ports bind to loopback; expose only what you put behind a TLS reverse proxy.
|
||||
|
||||
## Teardown
|
||||
|
||||
```sh
|
||||
docker compose down # stop, keep all state
|
||||
docker compose down -v # also wipe volumes → full re-sync
|
||||
```
|
||||
|
||||
`down -v` wipes the chain data (full re-sync on the next `up`).
|
||||
|
||||
---
|
||||
|
||||
## Resolver API reference
|
||||
|
||||
The resolver (`snrc-resolve.py`, host `127.0.0.1:8000`) is also runnable
|
||||
standalone for local dev (no Docker), via [`uv`](https://docs.astral.sh/uv/):
|
||||
|
||||
```sh
|
||||
uv run scripts/resolver/service/snrc-resolve.py # defaults to local reth + mainnet .testing
|
||||
```
|
||||
|
||||
### Response shape
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"name": "foobar.testing",
|
||||
"nickname": "Foo", "website": "https://foo.bar", "location": "",
|
||||
"simplexContact": ["https://smp16.simplex.im/a#…", "https://smp11…"], // primary first, fallbacks after
|
||||
"simplexChannel": [],
|
||||
"eth": null, "btc": "bc1q…", "xmr": "4ANz…", "dot": "139G…",
|
||||
"owner": "0xd83b…", "resolver": "0x80fa…"
|
||||
}
|
||||
```
|
||||
|
||||
`simplexContact`/`simplexChannel` are arrays (a name can advertise multiple SMP
|
||||
servers; clients try them in order). On-chain they're a single comma-separated
|
||||
text record; the resolver splits/trims/drops-empties. Address encodings are
|
||||
canonical per chain (EIP-55 / bech32 / SS58 / Monero-base58). Subnames work
|
||||
identically (`bar.foobar.testing`).
|
||||
|
||||
### Status codes
|
||||
|
||||
| Status | Meaning |
|
||||
|---|---|
|
||||
| 200 | resolved |
|
||||
| 400 | TLD not configured, or not a fully-qualified name |
|
||||
| 404 | name has no resolver set on the registry |
|
||||
| 502 | upstream RPC error / reth not synced |
|
||||
|
||||
### Configuring registries
|
||||
|
||||
Defaults to mainnet `.testing` (`0x03f438…`); `.simplex` is unset until
|
||||
deployed. Override per TLD via env on the `resolver` service in
|
||||
`docker-compose.yml` (`SNRC_REGISTRY_TESTING` / `SNRC_REGISTRY_SIMPLEX`), or as
|
||||
env vars for the standalone script.
|
||||
@@ -0,0 +1,160 @@
|
||||
services:
|
||||
# One-shot setup (runs as root): generates /jwt/jwt.hex and chowns the
|
||||
# nimbus-data volume to UID 1000 (the user Nimbus runs as inside its image).
|
||||
# Without this chown Nimbus gets "Permission denied" on its data dir
|
||||
# because docker creates fresh named volumes owned by root.
|
||||
init:
|
||||
image: alpine:latest
|
||||
volumes:
|
||||
- jwt:/jwt
|
||||
- nimbus-data:/nimbus-data
|
||||
command: >
|
||||
sh -c '
|
||||
set -e;
|
||||
if [ ! -f /jwt/jwt.hex ]; then
|
||||
apk add --no-cache openssl >/dev/null;
|
||||
openssl rand -hex 32 | tr -d "\n" > /jwt/jwt.hex;
|
||||
chmod 644 /jwt/jwt.hex;
|
||||
echo "Generated /jwt/jwt.hex";
|
||||
else
|
||||
echo "jwt.hex already exists";
|
||||
fi;
|
||||
chown 1000:1000 /nimbus-data;
|
||||
echo "Chowned /nimbus-data to 1000:1000";
|
||||
'
|
||||
restart: "no"
|
||||
|
||||
# One-shot: fetches a recent finalised checkpoint into the Nimbus data dir
|
||||
# using the trustedNodeSync subcommand. Skipped if the data dir is already
|
||||
# initialised, so subsequent compose-ups are no-ops.
|
||||
nimbus-checkpoint-sync:
|
||||
image: statusim/nimbus-eth2:multiarch-latest
|
||||
depends_on:
|
||||
init:
|
||||
condition: service_completed_successfully
|
||||
volumes:
|
||||
- nimbus-data:/home/user/nimbus-eth2/build/data
|
||||
entrypoint:
|
||||
- sh
|
||||
- -c
|
||||
- |
|
||||
if [ -d /home/user/nimbus-eth2/build/data/${NETWORK}/db ]; then
|
||||
echo "Nimbus data dir already initialised — skipping checkpoint sync";
|
||||
exit 0;
|
||||
fi;
|
||||
/home/user/nimbus-eth2/build/nimbus_beacon_node trustedNodeSync \
|
||||
--network=${NETWORK} \
|
||||
--data-dir=/home/user/nimbus-eth2/build/data/${NETWORK} \
|
||||
--trusted-node-url=${TRUSTED_NODE_URL} \
|
||||
--backfill=false
|
||||
restart: "no"
|
||||
|
||||
# One-shot: downloads a pre-synced snapshot from snapshots.reth.rs into the
|
||||
# Reth data dir. Turns a multi-day from-scratch sync into a ~hour download.
|
||||
# Skipped if the data dir is already initialised — re-runs are no-ops.
|
||||
# Privacy note: snapshots.reth.rs sees this download (operator existence).
|
||||
# Subsequent eth_call traffic stays local.
|
||||
reth-snapshot-init:
|
||||
image: ghcr.io/paradigmxyz/reth:latest
|
||||
depends_on:
|
||||
init:
|
||||
condition: service_completed_successfully
|
||||
volumes:
|
||||
- reth-data:/data
|
||||
entrypoint:
|
||||
- sh
|
||||
- -c
|
||||
- |
|
||||
if [ -f /data/.snapshot-done ] || [ -d /data/db ]; then
|
||||
echo "Reth data already initialised — skipping snapshot download";
|
||||
exit 0;
|
||||
fi;
|
||||
echo "Downloading Reth ${NETWORK} --minimal snapshot...";
|
||||
reth download --datadir /data --chain ${NETWORK} --minimal && \
|
||||
touch /data/.snapshot-done && \
|
||||
echo "Snapshot download complete"
|
||||
restart: "no"
|
||||
|
||||
reth:
|
||||
image: ghcr.io/paradigmxyz/reth:latest
|
||||
depends_on:
|
||||
reth-snapshot-init:
|
||||
condition: service_completed_successfully
|
||||
volumes:
|
||||
- reth-data:/data
|
||||
- jwt:/jwt:ro
|
||||
ports:
|
||||
# JSON-RPC for smp-server. Bound to loopback — put Caddy in front for remote access.
|
||||
- "127.0.0.1:8545:8545"
|
||||
# p2p (Ethereum network). Open these on your firewall for sync.
|
||||
- "30303:30303/tcp"
|
||||
- "30303:30303/udp"
|
||||
command: >
|
||||
node
|
||||
--datadir /data
|
||||
--chain ${NETWORK}
|
||||
--minimal
|
||||
--authrpc.jwtsecret /jwt/jwt.hex
|
||||
--authrpc.addr 0.0.0.0 --authrpc.port 8551
|
||||
--http
|
||||
--http.addr 0.0.0.0 --http.port 8545
|
||||
--http.api eth,net
|
||||
--rpc.gascap 50000000
|
||||
--port 30303
|
||||
--discovery.port 30303
|
||||
restart: unless-stopped
|
||||
|
||||
nimbus:
|
||||
image: statusim/nimbus-eth2:multiarch-latest
|
||||
depends_on:
|
||||
nimbus-checkpoint-sync:
|
||||
condition: service_completed_successfully
|
||||
volumes:
|
||||
- nimbus-data:/home/user/nimbus-eth2/build/data
|
||||
- jwt:/jwt:ro
|
||||
ports:
|
||||
- "9000:9000/tcp"
|
||||
- "9000:9000/udp"
|
||||
- "127.0.0.1:5052:5052"
|
||||
command: >
|
||||
--network=${NETWORK}
|
||||
--data-dir=/home/user/nimbus-eth2/build/data/${NETWORK}
|
||||
--el=http://reth:8551
|
||||
--jwt-secret=/jwt/jwt.hex
|
||||
--non-interactive
|
||||
--rest --rest-address=0.0.0.0 --rest-port=5052
|
||||
--nat=${NAT:-any}
|
||||
restart: unless-stopped
|
||||
|
||||
# SNRC REST resolver. Talks to reth on the compose-internal network,
|
||||
# exposes /resolve and /health on 127.0.0.1:8000 by default. The
|
||||
# smp-server points its [NAMES] resolver_endpoint at this URL.
|
||||
# To change the host port, edit the LEFT side of the port mapping below.
|
||||
resolver:
|
||||
build:
|
||||
context: ./service
|
||||
dockerfile: Dockerfile
|
||||
depends_on:
|
||||
# reth's `service_started` is sufficient — the resolver tolerates
|
||||
# eth_call failures gracefully (returns 502 with the error body), so
|
||||
# starting before reth has finished snapshot replay just yields a few
|
||||
# 502s until the chain is queryable. The upstream reth image doesn't
|
||||
# ship a HEALTHCHECK, so we can't gate on healthy.
|
||||
reth:
|
||||
condition: service_started
|
||||
environment:
|
||||
SNRC_RPC: http://reth:8545
|
||||
SNRC_BIND: 0.0.0.0
|
||||
# Registry addresses cascade through the script's own defaults
|
||||
# (mainnet `.testing`; `.simplex` unconfigured). Set explicitly here
|
||||
# only if you're deploying against a different network or contract.
|
||||
# SNRC_REGISTRY_TESTING: 0x...
|
||||
# SNRC_REGISTRY_SIMPLEX: 0x...
|
||||
ports:
|
||||
- "127.0.0.1:8000:8000"
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
reth-data:
|
||||
nimbus-data:
|
||||
jwt:
|
||||
@@ -0,0 +1,48 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
# ---------- builder ----------
|
||||
# Use the official uv image (Astral) on top of a slim Python base.
|
||||
# uv resolves and installs the lockfile-free pyproject.toml in seconds and
|
||||
# produces a portable .venv we can copy into the runtime stage.
|
||||
FROM ghcr.io/astral-sh/uv:python3.13-bookworm-slim AS builder
|
||||
|
||||
ENV UV_LINK_MODE=copy \
|
||||
UV_COMPILE_BYTECODE=1 \
|
||||
UV_PYTHON_DOWNLOADS=never \
|
||||
UV_NO_PROGRESS=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install deps first (separate layer) — script edits won't bust this cache.
|
||||
COPY pyproject.toml ./
|
||||
RUN --mount=type=cache,target=/root/.cache/uv \
|
||||
uv sync --no-dev --no-install-project
|
||||
|
||||
# Script is added after the dep layer for cache friendliness.
|
||||
COPY snrc-resolve.py ./
|
||||
|
||||
# ---------- runtime ----------
|
||||
# Slim runtime — only the venv + script. No uv, no apt.
|
||||
FROM python:3.13-slim AS runtime
|
||||
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
PYTHONDONTWRITEBYTECODE=1 \
|
||||
PATH="/app/.venv/bin:$PATH"
|
||||
|
||||
# Non-root user (matches resolver privacy posture: it has no need for root).
|
||||
RUN groupadd --system --gid 10001 snrc && \
|
||||
useradd --system --uid 10001 --gid snrc --no-create-home --shell /usr/sbin/nologin snrc
|
||||
|
||||
WORKDIR /app
|
||||
COPY --from=builder --chown=snrc:snrc /app /app
|
||||
|
||||
USER snrc:snrc
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
# Liveness check hits the script's own /health route. ThreadingHTTPServer is
|
||||
# fast enough that 3s is generous for a localhost probe; restart if it stops
|
||||
# responding entirely.
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||
CMD ["python", "-c", "import urllib.request, sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3).status == 200 else 1)"]
|
||||
|
||||
ENTRYPOINT ["python", "snrc-resolve.py"]
|
||||
@@ -0,0 +1,13 @@
|
||||
[project]
|
||||
name = "snrc-resolve"
|
||||
version = "0.1.0"
|
||||
description = "SimpleX Namespace (SNRC) resolver — REST API over ENS-shaped Ethereum registries"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
license = "AGPL-3.0-only"
|
||||
dependencies = [
|
||||
"eth-hash[pycryptodome]>=0.7",
|
||||
]
|
||||
|
||||
[tool.uv]
|
||||
package = false
|
||||
@@ -0,0 +1,517 @@
|
||||
#!/usr/bin/env python3
|
||||
# /// script
|
||||
# requires-python = ">=3.11"
|
||||
# dependencies = [
|
||||
# "eth-hash[pycryptodome]>=0.7",
|
||||
# ]
|
||||
# ///
|
||||
"""SimpleX Namespace (SNRC) resolver — REST API.
|
||||
|
||||
Resolves names like `alice.testing` / `bob.simplex` against the SNRC
|
||||
deployment on Ethereum mainnet (or any compatible ENS-shaped registry)
|
||||
and returns a flat JSON document with these fields:
|
||||
|
||||
name, nickname, website, location,
|
||||
simplexContact, simplexChannel, -- list[str], primary first
|
||||
eth, btc, xmr, dot,
|
||||
owner, resolver
|
||||
|
||||
`simplexContact` and `simplexChannel` are arrays so a name can advertise
|
||||
multiple SMP servers for redundancy. Clients SHOULD try the URLs in the
|
||||
order returned. The on-chain text record stores them as a single
|
||||
`LINK_SEPARATOR` (`;`)-joined string; this resolver splits and trims into a list.
|
||||
|
||||
All keys are valid Haskell record-field identifiers (lowercase initial,
|
||||
no dots), so consumers can derive aeson FromJSON instances directly
|
||||
without a key-rewriting layer.
|
||||
|
||||
Usage:
|
||||
./snrc-resolve.py # serve on :8000
|
||||
|
||||
curl -s http://127.0.0.1:8000/resolve/foobar.testing | jq .
|
||||
curl -s http://127.0.0.1:8000/health
|
||||
|
||||
Environment:
|
||||
SNRC_RPC JSON-RPC endpoint (default: http://127.0.0.1:8545)
|
||||
SNRC_REGISTRY_TESTING ENSRegistry for the .testing deployment
|
||||
(default: mainnet,
|
||||
0x58fc46996d975c57883564648bda5206d1a0102b)
|
||||
SNRC_REGISTRY_SIMPLEX ENSRegistry for the .simplex deployment
|
||||
(default: empty — TLD not yet deployed)
|
||||
SNRC_PORT Listen port (default: 8000)
|
||||
SNRC_BIND Bind address (default: 0.0.0.0)
|
||||
|
||||
Each TLD is a separate SNRC deployment with its own ENSRegistry; the
|
||||
resolver dispatches by the queried name's rightmost label.
|
||||
|
||||
Dependencies are declared inline (PEP 723) at the top of this file. Run with:
|
||||
uv run snrc-resolve.py # uv resolves & caches deps; one-line setup
|
||||
python snrc-resolve.py # if eth-hash[pycryptodome] is already installed
|
||||
|
||||
Addresses are returned in each chain's canonical presentation:
|
||||
eth EIP-55 mixed-case checksummed hex (e.g. 0xEa65A0…1572)
|
||||
btc bech32(m) for segwit/taproot, base58check for P2PKH/P2SH
|
||||
(e.g. bc1q… / 1A1zP1…)
|
||||
dot SS58 with Polkadot network prefix 0 (e.g. 15oF4u…)
|
||||
xmr Monero base58 (e.g. 4Aux5y…)
|
||||
Unrecognised payloads fall back to `0x`-prefixed raw hex.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import unquote, urlparse
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from eth_hash.auto import keccak
|
||||
|
||||
RPC = os.environ.get("SNRC_RPC", "http://127.0.0.1:8545")
|
||||
BIND = os.environ.get("SNRC_BIND", "0.0.0.0")
|
||||
PORT = int(os.environ.get("SNRC_PORT", "8000"))
|
||||
|
||||
# Each TLD is its own SNRC deployment with its own ENSRegistry. Dispatch
|
||||
# happens on the rightmost label of the queried name. Empty / unset means
|
||||
# "not deployed" — requests for that TLD return 400 with a clear error.
|
||||
# `... or "..."` makes the script's defaults the single source of truth:
|
||||
# unset AND empty-string both fall through to the literal. docker-compose
|
||||
# can therefore pass `SNRC_REGISTRY_TESTING=${SNRC_REGISTRY_TESTING:-}`
|
||||
# without duplicating the registry address.
|
||||
REGISTRIES = {
|
||||
"testing": os.environ.get("SNRC_REGISTRY_TESTING", "")
|
||||
or "0x58fc46996d975c57883564648bda5206d1a0102b", # mainnet .testing
|
||||
"simplex": os.environ.get("SNRC_REGISTRY_SIMPLEX", ""), # not deployed yet
|
||||
}
|
||||
|
||||
# SLIP-44 coin types (https://github.com/satoshilabs/slips/blob/master/slip-0044.md)
|
||||
COIN_ETH = 60
|
||||
COIN_BTC = 0
|
||||
COIN_XMR = 128
|
||||
COIN_DOT = 354
|
||||
|
||||
ZERO_ADDR = "0x0000000000000000000000000000000000000000"
|
||||
|
||||
|
||||
# ---------- RPC + ABI helpers (mirrors ens-lookup.py shape) ----------
|
||||
|
||||
def rpc(method, params):
|
||||
body = json.dumps(
|
||||
{"jsonrpc": "2.0", "method": method, "params": params, "id": 1}
|
||||
).encode()
|
||||
# Set a non-default User-Agent; Cloudflare-fronted public RPCs (drpc,
|
||||
# publicnode, etc.) reject `Python-urllib/3.x` with 403.
|
||||
req = Request(
|
||||
RPC,
|
||||
data=body,
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": "snrc-resolve/1.0",
|
||||
},
|
||||
)
|
||||
res = json.loads(urlopen(req, timeout=15).read())
|
||||
if "error" in res:
|
||||
raise RuntimeError(res["error"])
|
||||
return res["result"]
|
||||
|
||||
|
||||
def namehash(name: str) -> bytes:
|
||||
node = b"\x00" * 32
|
||||
if name:
|
||||
for label in reversed(name.split(".")):
|
||||
node = keccak(node + keccak(label.encode()))
|
||||
return node
|
||||
|
||||
|
||||
def selector(signature: str) -> str:
|
||||
return "0x" + keccak(signature.encode())[:4].hex()
|
||||
|
||||
|
||||
def eth_call(to: str, data: str) -> str:
|
||||
return rpc("eth_call", [{"to": to, "data": data}, "latest"])
|
||||
|
||||
|
||||
def decode_address(hex_data: str) -> str:
|
||||
return "0x" + hex_data[-40:]
|
||||
|
||||
|
||||
def decode_bytes(hex_data: str) -> bytes:
|
||||
raw = bytes.fromhex(hex_data[2:] if hex_data.startswith("0x") else hex_data)
|
||||
if len(raw) < 64:
|
||||
return b""
|
||||
length = int.from_bytes(raw[32:64], "big")
|
||||
return raw[64:64 + length]
|
||||
|
||||
|
||||
def encode_text_call(node: bytes, key: str) -> str:
|
||||
sel = selector("text(bytes32,string)")
|
||||
head = node.hex() + (0x40).to_bytes(32, "big").hex()
|
||||
key_bytes = key.encode()
|
||||
body = len(key_bytes).to_bytes(32, "big").hex() + key_bytes.hex()
|
||||
body += "00" * ((-len(key_bytes)) % 32)
|
||||
return sel + head + body
|
||||
|
||||
|
||||
def text(resolver: str, node: bytes, key: str) -> str:
|
||||
raw = decode_bytes(eth_call(resolver, encode_text_call(node, key)))
|
||||
return raw.decode("utf-8", errors="replace") if raw else ""
|
||||
|
||||
|
||||
def encode_addr_multicoin_call(node: bytes, coin_type: int) -> str:
|
||||
"""ENSIP-9 addr(bytes32 node, uint256 coinType) — both static, no offsets."""
|
||||
return (
|
||||
selector("addr(bytes32,uint256)")
|
||||
+ node.hex()
|
||||
+ coin_type.to_bytes(32, "big").hex()
|
||||
)
|
||||
|
||||
|
||||
def addr_multicoin(resolver: str, node: bytes, coin_type: int):
|
||||
"""Read ENSIP-9 raw bytes for `coinType`, then encode to that chain's
|
||||
canonical presentation form. Falls back to `0x`-prefixed hex if the
|
||||
payload doesn't match any recognised on-chain shape. Returns None when
|
||||
the record is unset."""
|
||||
try:
|
||||
raw = decode_bytes(eth_call(resolver, encode_addr_multicoin_call(node, coin_type)))
|
||||
except RuntimeError:
|
||||
return None
|
||||
if not raw:
|
||||
return None
|
||||
# An all-zero payload is the ENS convention for "unset" — many tools
|
||||
# write 20 zero bytes for coinType=60 instead of clearing the slot.
|
||||
# Treat it as null so the response doesn't surface a zero address.
|
||||
if raw == b"\x00" * len(raw):
|
||||
return None
|
||||
encoder = COIN_ENCODERS.get(coin_type)
|
||||
if encoder is None:
|
||||
return "0x" + raw.hex()
|
||||
try:
|
||||
return encoder(raw) or ("0x" + raw.hex())
|
||||
except Exception:
|
||||
return "0x" + raw.hex()
|
||||
|
||||
|
||||
# ---------- Coin-specific address encoders ----------
|
||||
# Each takes raw bytes as stored under ENSIP-9 and returns the canonical
|
||||
# user-facing string for that chain (EIP-55 for ETH, bech32/base58check
|
||||
# for BTC, SS58 for DOT, Monero-base58 for XMR). All stdlib + eth_hash.
|
||||
|
||||
|
||||
B58_ALPHA = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
||||
|
||||
|
||||
def _b58_encode(b: bytes) -> str:
|
||||
n = int.from_bytes(b, "big")
|
||||
out = ""
|
||||
while n:
|
||||
n, r = divmod(n, 58)
|
||||
out = B58_ALPHA[r] + out
|
||||
# leading zero bytes → leading '1's
|
||||
pad = len(b) - len(b.lstrip(b"\x00"))
|
||||
return "1" * pad + out
|
||||
|
||||
|
||||
def _b58check_encode(payload: bytes) -> str:
|
||||
"""Base58Check used by BTC legacy/P2SH: payload + dSHA256(payload)[:4]."""
|
||||
chk = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]
|
||||
return _b58_encode(payload + chk)
|
||||
|
||||
|
||||
# ---- Bech32 / Bech32m (BIP-173 / BIP-350) ----
|
||||
|
||||
_BECH32_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
|
||||
_BECH32_GEN = [0x3B6A57B2, 0x26508E6D, 0x1EA119FA, 0x3D4233DD, 0x2A1462B3]
|
||||
|
||||
|
||||
def _bech32_polymod(values):
|
||||
chk = 1
|
||||
for v in values:
|
||||
b = chk >> 25
|
||||
chk = ((chk & 0x1FFFFFF) << 5) ^ v
|
||||
for i in range(5):
|
||||
if (b >> i) & 1:
|
||||
chk ^= _BECH32_GEN[i]
|
||||
return chk
|
||||
|
||||
|
||||
def _bech32_hrp_expand(hrp):
|
||||
return [ord(c) >> 5 for c in hrp] + [0] + [ord(c) & 31 for c in hrp]
|
||||
|
||||
|
||||
def _bech32_create_checksum(hrp, data, spec):
|
||||
const = 1 if spec == "bech32" else 0x2BC830A3 # bech32m
|
||||
values = _bech32_hrp_expand(hrp) + data + [0] * 6
|
||||
polymod = _bech32_polymod(values) ^ const
|
||||
return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]
|
||||
|
||||
|
||||
def _bech32_encode(hrp, data, spec):
|
||||
combined = data + _bech32_create_checksum(hrp, data, spec)
|
||||
return hrp + "1" + "".join(_BECH32_CHARSET[d] for d in combined)
|
||||
|
||||
|
||||
def _convertbits(data, frombits, tobits, pad=True):
|
||||
acc = 0
|
||||
bits = 0
|
||||
ret = []
|
||||
maxv = (1 << tobits) - 1
|
||||
max_acc = (1 << (frombits + tobits - 1)) - 1
|
||||
for value in data:
|
||||
if value < 0 or (value >> frombits):
|
||||
return None
|
||||
acc = ((acc << frombits) | value) & max_acc
|
||||
bits += frombits
|
||||
while bits >= tobits:
|
||||
bits -= tobits
|
||||
ret.append((acc >> bits) & maxv)
|
||||
if pad and bits:
|
||||
ret.append((acc << (tobits - bits)) & maxv)
|
||||
elif not pad and (bits >= frombits or ((acc << (tobits - bits)) & maxv)):
|
||||
return None
|
||||
return ret
|
||||
|
||||
|
||||
def _segwit_encode(hrp: str, witver: int, witprog: bytes) -> str:
|
||||
spec = "bech32" if witver == 0 else "bech32m"
|
||||
data = [witver] + _convertbits(list(witprog), 8, 5)
|
||||
return _bech32_encode(hrp, data, spec)
|
||||
|
||||
|
||||
# ---- BTC scriptPubKey → address ----
|
||||
# ENSIP-9 stores the raw output script. Dispatch by length + opcode prefix.
|
||||
|
||||
def _btc_encode(raw: bytes) -> str | None:
|
||||
hrp = "bc" # mainnet
|
||||
if len(raw) == 25 and raw[:3] == b"\x76\xa9\x14" and raw[23:25] == b"\x88\xac":
|
||||
return _b58check_encode(b"\x00" + raw[3:23]) # P2PKH
|
||||
if len(raw) == 23 and raw[:2] == b"\xa9\x14" and raw[22:23] == b"\x87":
|
||||
return _b58check_encode(b"\x05" + raw[2:22]) # P2SH
|
||||
if len(raw) == 22 and raw[:2] == b"\x00\x14":
|
||||
return _segwit_encode(hrp, 0, raw[2:22]) # P2WPKH
|
||||
if len(raw) == 34 and raw[:2] == b"\x00\x20":
|
||||
return _segwit_encode(hrp, 0, raw[2:34]) # P2WSH
|
||||
if len(raw) == 34 and raw[:2] == b"\x51\x20":
|
||||
return _segwit_encode(hrp, 1, raw[2:34]) # P2TR
|
||||
return None
|
||||
|
||||
|
||||
# ---- Polkadot SS58 ----
|
||||
# Per SS58 spec: base58( prefix_byte + pubkey + blake2b-512("SS58PRE" + body)[:2] )
|
||||
# Polkadot mainnet uses network prefix 0 (single byte); Kusama uses 2.
|
||||
|
||||
_SS58_PRE = b"SS58PRE"
|
||||
|
||||
|
||||
def _ss58_encode(pubkey: bytes, network_prefix: int = 0) -> str:
|
||||
if len(pubkey) != 32:
|
||||
return None
|
||||
body = bytes([network_prefix]) + pubkey
|
||||
checksum = hashlib.blake2b(_SS58_PRE + body, digest_size=64).digest()[:2]
|
||||
return _b58_encode(body + checksum)
|
||||
|
||||
|
||||
def _dot_encode(raw: bytes) -> str | None:
|
||||
return _ss58_encode(raw, network_prefix=0)
|
||||
|
||||
|
||||
# ---- Monero base58 ----
|
||||
# Monero base58 encodes in 8-byte blocks; each full block → 11 chars, partial
|
||||
# block sizes per fixed table. Alphabet is identical to Bitcoin's.
|
||||
|
||||
_XMR_BLOCK_SIZES = [0, 2, 3, 5, 6, 7, 9, 10, 11]
|
||||
|
||||
|
||||
def _xmr_encode(raw: bytes) -> str:
|
||||
out = []
|
||||
for i in range(0, len(raw), 8):
|
||||
chunk = raw[i:i + 8]
|
||||
n = int.from_bytes(chunk, "big")
|
||||
width = 11 if len(chunk) == 8 else _XMR_BLOCK_SIZES[len(chunk)]
|
||||
block = []
|
||||
for _ in range(width):
|
||||
n, r = divmod(n, 58)
|
||||
block.append(B58_ALPHA[r])
|
||||
out.append("".join(reversed(block)))
|
||||
return "".join(out)
|
||||
|
||||
|
||||
# ---- ETH EIP-55 mixed-case checksum ----
|
||||
|
||||
def _eth_encode(raw: bytes) -> str | None:
|
||||
if len(raw) != 20:
|
||||
return None
|
||||
hex_addr = raw.hex()
|
||||
hash_hex = keccak(hex_addr.encode()).hex()
|
||||
return "0x" + "".join(
|
||||
c.upper() if c.isalpha() and int(hash_hex[i], 16) >= 8 else c
|
||||
for i, c in enumerate(hex_addr)
|
||||
)
|
||||
|
||||
|
||||
COIN_ENCODERS = {
|
||||
COIN_ETH: _eth_encode,
|
||||
COIN_BTC: _btc_encode,
|
||||
COIN_XMR: _xmr_encode,
|
||||
COIN_DOT: _dot_encode,
|
||||
}
|
||||
|
||||
|
||||
# ---------- Resolution logic ----------
|
||||
|
||||
# Text-record keys we read from the resolver. Surfaced under the response
|
||||
# field names listed in the docstring above. `name` and `description` are
|
||||
# common ENS fallbacks for a human-readable nickname.
|
||||
TEXT_KEYS = [
|
||||
"name",
|
||||
"nickname",
|
||||
"description",
|
||||
"url",
|
||||
"location",
|
||||
"simplex.contact",
|
||||
"simplex.channel",
|
||||
]
|
||||
|
||||
|
||||
# Separator that joins the SMP-server URL list inside a simplex.contact /
|
||||
# simplex.channel text record. MUST match SIMPLEX_LINK_SEPARATOR in the dApp
|
||||
# (ens-app-v3 src/constants/simplex.ts) — the two sides decode the same record.
|
||||
LINK_SEPARATOR = ";"
|
||||
|
||||
|
||||
def split_links(value: str) -> list:
|
||||
"""Split a separator-joined text record into an ordered list of entries.
|
||||
|
||||
Trims whitespace around each element and drops empties so trailing
|
||||
separators, doubled separators, and all-whitespace inputs all yield clean
|
||||
output. Single-value records yield a 1-element list; empty inputs
|
||||
yield `[]`. Used for `simplex.contact` / `simplex.channel`, which
|
||||
store one-or-more SMP-server URLs as a single `LINK_SEPARATOR`-joined string.
|
||||
"""
|
||||
return [item.strip() for item in value.split(LINK_SEPARATOR) if item.strip()]
|
||||
|
||||
|
||||
def resolve(name: str):
|
||||
tld = name.rsplit(".", 1)[-1]
|
||||
registry = REGISTRIES.get(tld)
|
||||
if not registry:
|
||||
configured = [k for k, v in REGISTRIES.items() if v]
|
||||
return 400, {
|
||||
"name": name,
|
||||
"error": f"TLD '{tld}' is not configured on this resolver",
|
||||
"configured_tlds": configured,
|
||||
}
|
||||
|
||||
node = namehash(name)
|
||||
node_hex = node.hex()
|
||||
|
||||
resolver_raw = eth_call(registry, selector("resolver(bytes32)") + node_hex)
|
||||
resolver_addr = decode_address(resolver_raw)
|
||||
if resolver_addr == ZERO_ADDR:
|
||||
return 404, {"name": name, "error": "no resolver set for this name"}
|
||||
|
||||
owner_raw = eth_call(registry, selector("owner(bytes32)") + node_hex)
|
||||
owner = decode_address(owner_raw)
|
||||
|
||||
texts = {}
|
||||
for k in TEXT_KEYS:
|
||||
try:
|
||||
v = text(resolver_addr, node, k)
|
||||
except RuntimeError:
|
||||
v = ""
|
||||
if v:
|
||||
texts[k] = v
|
||||
|
||||
# The user-facing "nickname" prefers an explicit `nickname` record,
|
||||
# falls back to `name`, then `description` (ENSIP-5 convention).
|
||||
nickname = texts.get("nickname") or texts.get("name") or texts.get("description") or ""
|
||||
|
||||
# Keys chosen to be valid Haskell record-field identifiers (lowercase
|
||||
# initial, no dots) so consumers can derive aeson FromJSON instances
|
||||
# without a key-rewriting layer. On-chain text-record names still
|
||||
# use the ENSIP-5 dot convention (e.g. "simplex.contact") — only the
|
||||
# resolver's JSON surface camelCases them.
|
||||
return 200, {
|
||||
"name": name,
|
||||
"nickname": nickname,
|
||||
"website": texts.get("url", ""),
|
||||
"location": texts.get("location", ""),
|
||||
"simplexContact": split_links(texts.get("simplex.contact", "")),
|
||||
"simplexChannel": split_links(texts.get("simplex.channel", "")),
|
||||
"eth": addr_multicoin(resolver_addr, node, COIN_ETH),
|
||||
"btc": addr_multicoin(resolver_addr, node, COIN_BTC),
|
||||
"xmr": addr_multicoin(resolver_addr, node, COIN_XMR),
|
||||
"dot": addr_multicoin(resolver_addr, node, COIN_DOT),
|
||||
"owner": owner,
|
||||
"resolver": resolver_addr,
|
||||
}
|
||||
|
||||
|
||||
# ---------- HTTP layer ----------
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self): # noqa: N802 - http.server contract
|
||||
path = urlparse(self.path).path
|
||||
parts = [unquote(p) for p in path.split("/") if p]
|
||||
|
||||
if parts == ["health"]:
|
||||
self._respond(
|
||||
200,
|
||||
{"ok": True, "rpc": RPC, "registries": REGISTRIES},
|
||||
)
|
||||
return
|
||||
|
||||
if len(parts) == 2 and parts[0] == "resolve":
|
||||
name = parts[1].strip().lower()
|
||||
if not name or "." not in name:
|
||||
self._respond(
|
||||
400,
|
||||
{
|
||||
"error": "expected fully-qualified name, e.g. /resolve/alice.testing",
|
||||
"got": name,
|
||||
},
|
||||
)
|
||||
return
|
||||
try:
|
||||
status, body = resolve(name)
|
||||
except Exception as e: # surface upstream errors as 502
|
||||
status, body = 502, {"name": name, "error": f"{type(e).__name__}: {e}"}
|
||||
self._respond(status, body)
|
||||
return
|
||||
|
||||
self._respond(
|
||||
404,
|
||||
{"error": "not found", "routes": ["/health", "/resolve/<name>"]},
|
||||
)
|
||||
|
||||
def _respond(self, status: int, body: dict):
|
||||
data = json.dumps(body, indent=2).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
# Quiet the default per-request access log; route to stderr in one line.
|
||||
sys.stderr.write(f"{self.address_string()} - {fmt % args}\n")
|
||||
|
||||
|
||||
def main():
|
||||
server = ThreadingHTTPServer((BIND, PORT), Handler)
|
||||
sys.stderr.write(
|
||||
f"snrc-resolve listening on {BIND}:{PORT}\n"
|
||||
f" RPC = {RPC}\n"
|
||||
f" Registries:\n"
|
||||
)
|
||||
for tld, addr in REGISTRIES.items():
|
||||
sys.stderr.write(f" .{tld:<8s} = {addr or '(not configured)'}\n")
|
||||
sys.stderr.write(" GET /resolve/<name> GET /health\n")
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
sys.stderr.write("\nshutting down\n")
|
||||
server.server_close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit tests for snrc-resolve helpers.
|
||||
|
||||
Run with `python3 -m unittest scripts/resolver/service/test_snrc_resolve.py`.
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
import unittest
|
||||
|
||||
# snrc-resolve.py has a hyphen, so import it via importlib instead of `import`.
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
_SPEC = importlib.util.spec_from_file_location(
|
||||
"snrc_resolve", os.path.join(_HERE, "snrc-resolve.py")
|
||||
)
|
||||
snrc = importlib.util.module_from_spec(_SPEC)
|
||||
_SPEC.loader.exec_module(snrc)
|
||||
|
||||
|
||||
class SplitLinksTests(unittest.TestCase):
|
||||
"""`split_links` decodes the multi-URL convention for simplex.contact /
|
||||
simplex.channel text records. Reuses the same rule the dApp's
|
||||
`parseSimplexUrls` uses (separator `;`), so the two sides round-trip
|
||||
cleanly."""
|
||||
|
||||
def test_empty_string_yields_empty_list(self):
|
||||
self.assertEqual(snrc.split_links(""), [])
|
||||
|
||||
def test_whitespace_only_yields_empty_list(self):
|
||||
self.assertEqual(snrc.split_links(" "), [])
|
||||
self.assertEqual(snrc.split_links(" ; ; "), [])
|
||||
|
||||
def test_single_url_yields_singleton_list(self):
|
||||
self.assertEqual(
|
||||
snrc.split_links("https://smp16.simplex.im/a#H1"),
|
||||
["https://smp16.simplex.im/a#H1"],
|
||||
)
|
||||
|
||||
def test_two_urls_split_on_separator(self):
|
||||
self.assertEqual(
|
||||
snrc.split_links(
|
||||
"https://smp16.simplex.im/a#H1;https://smp19.simplex.im/a#H1"
|
||||
),
|
||||
[
|
||||
"https://smp16.simplex.im/a#H1",
|
||||
"https://smp19.simplex.im/a#H1",
|
||||
],
|
||||
)
|
||||
|
||||
def test_whitespace_around_separators_is_trimmed(self):
|
||||
self.assertEqual(
|
||||
snrc.split_links(
|
||||
" https://smp16.simplex.im/a#H1 ;\thttps://smp19.simplex.im/a#H1 "
|
||||
),
|
||||
[
|
||||
"https://smp16.simplex.im/a#H1",
|
||||
"https://smp19.simplex.im/a#H1",
|
||||
],
|
||||
)
|
||||
|
||||
def test_trailing_separator_does_not_produce_empty_entry(self):
|
||||
self.assertEqual(
|
||||
snrc.split_links("https://smp16.simplex.im/a#H1;"),
|
||||
["https://smp16.simplex.im/a#H1"],
|
||||
)
|
||||
|
||||
def test_doubled_separator_does_not_produce_empty_entry(self):
|
||||
self.assertEqual(
|
||||
snrc.split_links(
|
||||
"https://smp16.simplex.im/a#H1;;https://smp19.simplex.im/a#H1"
|
||||
),
|
||||
[
|
||||
"https://smp16.simplex.im/a#H1",
|
||||
"https://smp19.simplex.im/a#H1",
|
||||
],
|
||||
)
|
||||
|
||||
def test_order_is_preserved(self):
|
||||
self.assertEqual(
|
||||
snrc.split_links("c;a;b"),
|
||||
["c", "a", "b"],
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Resolve an ENS name via local Reth (the same shape SNRC will use).
|
||||
|
||||
Usage:
|
||||
./ens-lookup.py # defaults to simplexchat.eth
|
||||
./ens-lookup.py vitalik.eth
|
||||
./ens-lookup.py corevo.eth
|
||||
|
||||
Requires: pip install --break-system-packages 'eth-hash[pycryptodome]'
|
||||
"""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from eth_hash.auto import keccak
|
||||
|
||||
RPC = "http://127.0.0.1:8545"
|
||||
# ENS Registry (current, post-2020 migration)
|
||||
ENS_REGISTRY = "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"
|
||||
|
||||
|
||||
def rpc(method, params):
|
||||
body = json.dumps({"jsonrpc": "2.0", "method": method, "params": params, "id": 1}).encode()
|
||||
req = Request(RPC, data=body, headers={"Content-Type": "application/json"})
|
||||
res = json.loads(urlopen(req, timeout=15).read())
|
||||
if "error" in res:
|
||||
raise RuntimeError(res["error"])
|
||||
return res["result"]
|
||||
|
||||
|
||||
def namehash(name: str) -> bytes:
|
||||
"""ENS namehash — recursive keccak256 over reversed labels."""
|
||||
node = b"\x00" * 32
|
||||
if name:
|
||||
for label in reversed(name.split(".")):
|
||||
node = keccak(node + keccak(label.encode()))
|
||||
return node
|
||||
|
||||
|
||||
def selector(signature: str) -> str:
|
||||
return "0x" + keccak(signature.encode())[:4].hex()
|
||||
|
||||
|
||||
def eth_call(to: str, data: str) -> str:
|
||||
return rpc("eth_call", [{"to": to, "data": data}, "latest"])
|
||||
|
||||
|
||||
def decode_address(hex_data: str) -> str:
|
||||
return "0x" + hex_data[-40:]
|
||||
|
||||
|
||||
def decode_bytes(hex_data: str) -> bytes:
|
||||
raw = bytes.fromhex(hex_data[2:] if hex_data.startswith("0x") else hex_data)
|
||||
if len(raw) < 64:
|
||||
return b""
|
||||
length = int.from_bytes(raw[32:64], "big")
|
||||
return raw[64:64 + length]
|
||||
|
||||
|
||||
def encode_text_call(node: bytes, key: str) -> str:
|
||||
"""ABI-encode text(bytes32 node, string key). String arg is dynamic:
|
||||
offset (=0x40) + length + right-padded data."""
|
||||
sel = selector("text(bytes32,string)")
|
||||
head = node.hex() + (0x40).to_bytes(32, "big").hex()
|
||||
key_bytes = key.encode()
|
||||
body = len(key_bytes).to_bytes(32, "big").hex() + key_bytes.hex()
|
||||
# right-pad to 32-byte boundary
|
||||
pad = (-len(key_bytes)) % 32
|
||||
body += "00" * pad
|
||||
return sel + head + body
|
||||
|
||||
|
||||
def text(resolver: str, node: bytes, key: str) -> str:
|
||||
raw = decode_bytes(eth_call(resolver, encode_text_call(node, key)))
|
||||
return raw.decode("utf-8", errors="replace") if raw else ""
|
||||
|
||||
|
||||
# Common ENS text keys (ENSIP-5). Resolvers may return empty for any of these.
|
||||
TEXT_KEYS = [
|
||||
"url",
|
||||
"avatar",
|
||||
"description",
|
||||
"email",
|
||||
"notice",
|
||||
"keywords",
|
||||
"com.twitter",
|
||||
"com.github",
|
||||
"com.discord",
|
||||
"org.telegram",
|
||||
"io.keybase",
|
||||
"xyz.farcaster",
|
||||
]
|
||||
|
||||
|
||||
def decode_contenthash(raw: bytes) -> str:
|
||||
"""ENS contenthash → human-readable URI (best-effort)."""
|
||||
if not raw:
|
||||
return "(empty)"
|
||||
# Multicodec prefixes:
|
||||
# 0xe301 = ipfs-ns + dag-pb (CIDv0/v1)
|
||||
# 0xe501 = ipns-ns
|
||||
# 0xe40101701b... = swarm
|
||||
if raw[:2] == b"\xe3\x01":
|
||||
cid_bytes = raw[2:]
|
||||
# Base32 lowercase + 'b' prefix per CIDv1 spec
|
||||
b32 = base64.b32encode(cid_bytes).decode().lower().rstrip("=")
|
||||
return f"ipfs://b{b32}"
|
||||
if raw[:2] == b"\xe5\x01":
|
||||
cid_bytes = raw[2:]
|
||||
b32 = base64.b32encode(cid_bytes).decode().lower().rstrip("=")
|
||||
return f"ipns://b{b32}"
|
||||
return "0x" + raw.hex()
|
||||
|
||||
|
||||
def main():
|
||||
name = sys.argv[1] if len(sys.argv) > 1 else "simplexchat.eth"
|
||||
|
||||
print(f" name: {name}")
|
||||
node = namehash(name)
|
||||
print(f" namehash: 0x{node.hex()}")
|
||||
|
||||
# 1. Ask the registry which resolver is responsible for this name
|
||||
resolver_data = selector("resolver(bytes32)") + node.hex()
|
||||
resolver_raw = eth_call(ENS_REGISTRY, resolver_data)
|
||||
resolver = decode_address(resolver_raw)
|
||||
print(f" resolver: {resolver}")
|
||||
if resolver == "0x0000000000000000000000000000000000000000":
|
||||
print(" → no resolver set for this name")
|
||||
return
|
||||
|
||||
node_hex = node.hex()
|
||||
|
||||
# 2. Ask the resolver for the address
|
||||
try:
|
||||
addr = decode_address(eth_call(resolver, selector("addr(bytes32)") + node_hex))
|
||||
print(f" address: {addr}")
|
||||
except Exception as e:
|
||||
print(f" address: (error: {e})")
|
||||
|
||||
# 3. Ask the resolver for the content hash (IPFS pointer)
|
||||
try:
|
||||
ch = decode_bytes(eth_call(resolver, selector("contenthash(bytes32)") + node_hex))
|
||||
print(f" contenthash: {decode_contenthash(ch)}")
|
||||
except Exception as e:
|
||||
print(f" contenthash: (not supported: {e})")
|
||||
|
||||
# 4. Owner from the registry
|
||||
try:
|
||||
owner = decode_address(eth_call(ENS_REGISTRY, selector("owner(bytes32)") + node_hex))
|
||||
print(f" owner: {owner}")
|
||||
except Exception as e:
|
||||
print(f" owner: (error: {e})")
|
||||
|
||||
# 5. Text records (EIP-634). Print only the non-empty ones.
|
||||
print(" text records:")
|
||||
for key in TEXT_KEYS:
|
||||
try:
|
||||
v = text(resolver, node, key)
|
||||
if v:
|
||||
print(f" {key:<16s} {v}")
|
||||
except Exception as e:
|
||||
print(f" {key:<16s} (error: {e})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,246 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sync progress for the Reth + Nimbus stack.
|
||||
|
||||
Usage:
|
||||
./progress.py # continuous (Ctrl-C to exit, auto-exits when synced)
|
||||
./progress.py --once # single snapshot
|
||||
|
||||
Requires Nimbus REST port exposed at 127.0.0.1:5052 (add --rest flag in compose).
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from collections import deque
|
||||
from datetime import timedelta
|
||||
from urllib.error import URLError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
RETH = "http://127.0.0.1:8545"
|
||||
NIMBUS = "http://127.0.0.1:5052"
|
||||
INTERVAL = 5
|
||||
WINDOW = 60
|
||||
BAR_W = 40
|
||||
|
||||
# ANSI helpers
|
||||
def c(s, code): return f"\033[{code}m{s}\033[0m"
|
||||
GREEN, YELLOW, RED, DIM, BOLD = "32", "33", "31", "2;37", "1"
|
||||
|
||||
|
||||
def rpc(method):
|
||||
body = json.dumps({"jsonrpc": "2.0", "method": method, "params": [], "id": 1}).encode()
|
||||
req = Request(RETH, data=body, headers={"Content-Type": "application/json"})
|
||||
return json.loads(urlopen(req, timeout=5).read())["result"]
|
||||
|
||||
|
||||
def get_reth():
|
||||
try:
|
||||
r = rpc("eth_syncing")
|
||||
try:
|
||||
peers = int(rpc("net_peerCount"), 16)
|
||||
except Exception:
|
||||
peers = -1 # net namespace not exposed
|
||||
if r is False:
|
||||
head = int(rpc("eth_blockNumber"), 16)
|
||||
return {"state": "synced", "current": head, "target": head, "peers": peers,
|
||||
"stage": None, "stages": {}, "err": None}
|
||||
current = int(r["currentBlock"], 16)
|
||||
highest = int(r["highestBlock"], 16)
|
||||
# Build stage map (name -> block).
|
||||
stages = {s["name"]: int(s["block"], 16) for s in r.get("stages", [])}
|
||||
active_stages = {k: v for k, v in stages.items() if v > 0}
|
||||
# Headers download phase: nothing has progressed yet.
|
||||
if current == 0 and highest == 0 and not active_stages:
|
||||
return {"state": "headers", "current": 0, "target": 0, "peers": peers,
|
||||
"stage": "Headers", "stages": stages, "err": None}
|
||||
# Derive progress from the stages pipeline.
|
||||
# Bottleneck (rate-limiting stage) = stage with lowest non-zero block.
|
||||
# Target = leading stage block (typically Headers = chain tip).
|
||||
# Reth's top-level currentBlock/highestBlock are unreliable during initial
|
||||
# sync (often 0 until execution stage runs), so prefer stages-derived values.
|
||||
if active_stages:
|
||||
bottleneck = min(active_stages, key=active_stages.get)
|
||||
stage_current = active_stages[bottleneck]
|
||||
stage_target = max(stages.values()) if stages else 0
|
||||
# Trust the stages-derived values if highest is unset or stages tip is higher.
|
||||
if highest <= 0 or stage_target > highest:
|
||||
current = stage_current
|
||||
highest = stage_target
|
||||
elif current <= 0:
|
||||
current = stage_current
|
||||
else:
|
||||
bottleneck = None
|
||||
return {"state": "syncing", "current": current, "target": highest,
|
||||
"peers": peers, "stage": bottleneck, "stages": stages, "err": None}
|
||||
except URLError as e:
|
||||
return {"state": "down", "current": 0, "target": 0, "peers": 0,
|
||||
"stage": None, "stages": {}, "err": str(e.reason)}
|
||||
except Exception as e:
|
||||
return {"state": "error", "current": 0, "target": 0, "peers": 0,
|
||||
"stage": None, "stages": {}, "err": str(e)}
|
||||
|
||||
|
||||
def get_nimbus():
|
||||
try:
|
||||
d = json.loads(urlopen(f"{NIMBUS}/eth/v1/node/syncing", timeout=5).read())["data"]
|
||||
peers_d = json.loads(urlopen(f"{NIMBUS}/eth/v1/node/peer_count", timeout=5).read())["data"]
|
||||
head = int(d["head_slot"])
|
||||
dist = int(d["sync_distance"])
|
||||
peers = int(peers_d.get("connected", "0"))
|
||||
return {"state": "synced" if not d["is_syncing"] else "syncing",
|
||||
"current": head, "target": head + dist, "peers": peers,
|
||||
"optimistic": bool(d.get("is_optimistic", False)),
|
||||
"el_offline": bool(d.get("el_offline", False)),
|
||||
"err": None}
|
||||
except URLError as e:
|
||||
return {"state": "down", "current": 0, "target": 0, "peers": 0,
|
||||
"optimistic": False, "el_offline": False, "err": str(e.reason)}
|
||||
except Exception as e:
|
||||
return {"state": "error", "current": 0, "target": 0, "peers": 0,
|
||||
"optimistic": False, "el_offline": False, "err": str(e)}
|
||||
|
||||
|
||||
def format_num(n): return f"{n:,}"
|
||||
|
||||
|
||||
def format_eta(seconds):
|
||||
if seconds is None: return "?"
|
||||
if seconds < 0: return "?"
|
||||
if seconds < 60: return f"{int(seconds)}s"
|
||||
if seconds < 3600:
|
||||
return f"{int(seconds // 60)}m {int(seconds % 60)}s"
|
||||
if seconds < 86400:
|
||||
return f"{int(seconds // 3600)}h {int((seconds % 3600) // 60)}m"
|
||||
return f"{int(seconds // 86400)}d {int((seconds % 86400) // 3600)}h"
|
||||
|
||||
|
||||
def rate_per_sec(history):
|
||||
if len(history) < 2: return None
|
||||
t0, c0 = history[0]
|
||||
t1, c1 = history[-1]
|
||||
if t1 <= t0: return None
|
||||
return (c1 - c0) / (t1 - t0)
|
||||
|
||||
|
||||
def eta_seconds(history, target):
|
||||
r = rate_per_sec(history)
|
||||
if r is None or r <= 0: return None
|
||||
remaining = target - history[-1][1]
|
||||
if remaining <= 0: return 0
|
||||
return remaining / r
|
||||
|
||||
|
||||
def progress_bar(pct):
|
||||
pct = max(0.0, min(100.0, pct))
|
||||
filled = int(pct / 100 * BAR_W)
|
||||
return c("█" * filled, GREEN) + c("░" * (BAR_W - filled), DIM)
|
||||
|
||||
|
||||
def peers_label(peers):
|
||||
if peers < 0:
|
||||
return c("· peers unknown (enable net namespace)", DIM)
|
||||
return c(f"· {peers} peers", DIM)
|
||||
|
||||
|
||||
def stages_summary(stages):
|
||||
"""One-line view: stages that have progressed, with their block numbers."""
|
||||
if not stages:
|
||||
return ""
|
||||
advanced = [(n, b) for n, b in stages.items() if b > 0]
|
||||
if not advanced:
|
||||
return c(" stages: all 0 (headers downloading)", DIM)
|
||||
advanced.sort(key=lambda kv: kv[1], reverse=True)
|
||||
parts = [f"{n}={format_num(b)}" for n, b in advanced[:4]]
|
||||
return c(" stages: " + ", ".join(parts), DIM)
|
||||
|
||||
|
||||
def render_one(name, x, hist):
|
||||
state = x["state"]
|
||||
peers = x.get("peers", 0)
|
||||
extras = []
|
||||
if name == "Nimbus":
|
||||
if x.get("optimistic"):
|
||||
extras.append(c("(optimistic head — Reth not yet verifying)", YELLOW))
|
||||
if x.get("el_offline"):
|
||||
extras.append(c("⚠ EL OFFLINE", RED))
|
||||
if state == "synced":
|
||||
out = [f" {c(name, BOLD):<14s} {c('✓ synced', GREEN)} {c(format_num(x['current']), BOLD)} {peers_label(peers)}"]
|
||||
elif state == "headers":
|
||||
out = [
|
||||
f" {c(name, BOLD):<14s} {c('⧗ headers', YELLOW)} {c('downloading initial chain', DIM)} {peers_label(peers)}",
|
||||
f" {c('(per-block progress unavailable until headers validated — see docker logs)', DIM)}",
|
||||
]
|
||||
elif state == "syncing" and x["target"] <= 0:
|
||||
out = [f" {c(name, BOLD):<14s} {c('⧗ syncing', YELLOW)} {c('waiting for fork-choice', DIM)} {peers_label(peers)}"]
|
||||
elif state == "syncing":
|
||||
pct = x["current"] / x["target"] * 100
|
||||
r = rate_per_sec(hist)
|
||||
eta = eta_seconds(hist, x["target"])
|
||||
rate_s = f"{format_num(int(r))} /s" if r and r > 0 else c("stalled", RED)
|
||||
eta_s = format_eta(eta) if eta is not None else "?"
|
||||
stage = x.get("stage")
|
||||
stage_s = c(f"[{stage}]", DIM) if stage else ""
|
||||
out = [
|
||||
f" {c(name, BOLD):<14s} {c('⧗ syncing', YELLOW)} {format_num(x['current'])} / {format_num(x['target'])} {stage_s} {peers_label(peers)}",
|
||||
f" {progress_bar(pct)} {c(f'{pct:6.2f}%', BOLD)}",
|
||||
f" {c(rate_s, DIM)} ETA {c(eta_s, BOLD)}",
|
||||
]
|
||||
else:
|
||||
out = [
|
||||
f" {c(name, BOLD):<14s} {c('✗ ' + state, RED)}",
|
||||
f" {c(x.get('err') or '', DIM)}",
|
||||
]
|
||||
# Reth-only: stages summary
|
||||
if name == "Reth" and x.get("stages"):
|
||||
out.append(f" {stages_summary(x['stages'])}")
|
||||
for e in extras:
|
||||
out.append(f" {e}")
|
||||
return out
|
||||
|
||||
|
||||
def render(reth, nimbus, reth_hist, nim_hist):
|
||||
print("\033[2J\033[H", end="")
|
||||
width = 64
|
||||
title = f"Reth + Nimbus sync"
|
||||
ts = time.strftime("%H:%M:%S")
|
||||
print()
|
||||
print(f" {c(title, BOLD)} {c(ts, DIM)}")
|
||||
print(f" {c('─' * width, DIM)}")
|
||||
print()
|
||||
for line in render_one("Reth", reth, reth_hist):
|
||||
print(line)
|
||||
print()
|
||||
for line in render_one("Nimbus", nimbus, nim_hist):
|
||||
print(line)
|
||||
print()
|
||||
win_s = (len(reth_hist) - 1) * INTERVAL if len(reth_hist) > 1 else 0
|
||||
print(f" {c(f'window {win_s}s · refresh {INTERVAL}s · Ctrl-C to exit', DIM)}")
|
||||
print()
|
||||
|
||||
|
||||
def main():
|
||||
once = "--once" in sys.argv
|
||||
reth_hist = deque(maxlen=WINDOW)
|
||||
nim_hist = deque(maxlen=WINDOW)
|
||||
try:
|
||||
while True:
|
||||
r = get_reth()
|
||||
n = get_nimbus()
|
||||
now = time.time()
|
||||
if r["target"] > 0 or r["state"] == "syncing":
|
||||
reth_hist.append((now, r["current"]))
|
||||
if n["target"] > 0 or n["state"] == "syncing":
|
||||
nim_hist.append((now, n["current"]))
|
||||
render(r, n, reth_hist, nim_hist)
|
||||
if once:
|
||||
break
|
||||
if r["state"] == "synced" and n["state"] == "synced":
|
||||
print(f" {c('✓ all synced.', GREEN)}\n")
|
||||
break
|
||||
time.sleep(INTERVAL)
|
||||
except KeyboardInterrupt:
|
||||
print()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -22,7 +22,7 @@ smp-server --version
|
||||
|
||||
# Initialize server
|
||||
ip_address=$(curl ifconfig.me)
|
||||
smp-server init -l --ip $ip_address
|
||||
smp-server init -l --disable-web --ip $ip_address
|
||||
|
||||
# Server fingerprint
|
||||
fingerprint=$(cat /etc/opt/simplex/fingerprint)
|
||||
|
||||
@@ -12,6 +12,11 @@ Check SMP server status with: systemctl status smp-server
|
||||
To keep this server secure, the UFW firewall is enabled.
|
||||
All ports are BLOCKED except 22 (SSH), 443 (HTTPS), 5223 (SMP server).
|
||||
|
||||
Embedded HTTPS web is disabled because this image does not provision
|
||||
/etc/opt/simplex/web.crt or /etc/opt/simplex/web.key. To enable it, provision
|
||||
those files, uncomment WEB https/cert/key in /etc/opt/simplex/smp-server.ini,
|
||||
and restart smp-server.
|
||||
|
||||
********************************************************************************
|
||||
To stop seeing this message delete line - bash /opt/simplex/on_login.sh - from /root/.bashrc
|
||||
EOF
|
||||
|
||||
@@ -75,6 +75,9 @@ init_opts=()
|
||||
|
||||
[[ $ENABLE_STORE_LOG == "on" ]] && init_opts+=(-l)
|
||||
|
||||
# This script does not provision /etc/opt/simplex/web.crt or web.key.
|
||||
init_opts+=(--disable-web)
|
||||
|
||||
ip_address=$(curl ifconfig.me)
|
||||
init_opts+=(--ip $ip_address)
|
||||
|
||||
@@ -111,6 +114,11 @@ Check SMP server status with: systemctl status smp-server
|
||||
To keep this server secure, the UFW firewall is enabled.
|
||||
All ports are BLOCKED except 22 (SSH), 443 (HTTPS), 5223 (SMP server).
|
||||
|
||||
Embedded HTTPS web is disabled because this script does not provision
|
||||
/etc/opt/simplex/web.crt or /etc/opt/simplex/web.key. To enable it, provision
|
||||
those files, uncomment WEB https/cert/key in /etc/opt/simplex/smp-server.ini,
|
||||
and restart smp-server.
|
||||
|
||||
********************************************************************************
|
||||
To stop seeing this message delete line - bash /opt/simplex/on_login.sh - from /root/.bashrc
|
||||
EOF2
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
cabal-version: 1.12
|
||||
cabal-version: 3.0
|
||||
|
||||
name: simplexmq
|
||||
version: 6.5.2.0
|
||||
version: 7.0.1.0
|
||||
synopsis: SimpleXMQ message broker
|
||||
description: This package includes <./docs/Simplex-Messaging-Server.html server>,
|
||||
<./docs/Simplex-Messaging-Client.html client> and
|
||||
@@ -16,7 +16,7 @@ homepage: https://github.com/simplex-chat/simplexmq#readme
|
||||
author: simplex.chat
|
||||
maintainer: chat@simplex.chat
|
||||
copyright: 2020-2022 simplex.chat
|
||||
license: AGPL-3
|
||||
license: AGPL-3.0-only
|
||||
license-file: LICENSE
|
||||
build-type: Simple
|
||||
extra-source-files:
|
||||
@@ -24,6 +24,13 @@ extra-source-files:
|
||||
CHANGELOG.md
|
||||
cbits/sha512.h
|
||||
cbits/sntrup761.h
|
||||
cbits/blst/**/*.c
|
||||
cbits/blst/**/*.h
|
||||
cbits/blst/**/*.s
|
||||
cbits/blst/**/*.S
|
||||
cbits/blst/**/*.asm
|
||||
cbits/libbbs/**/*.c
|
||||
cbits/libbbs/**/*.h
|
||||
apps/common/Web/static/index.html
|
||||
apps/common/Web/static/link.html
|
||||
apps/common/Web/static/media/apk_icon.png
|
||||
@@ -82,6 +89,11 @@ flag server_postgres
|
||||
manual: True
|
||||
default: False
|
||||
|
||||
flag commoncrypto
|
||||
description: On Apple platforms, use SecRandomCopyBytes (Security.framework) for libbbs randomness. getentropy is a non-public symbol on iOS and triggers App Store rejection (ITMS-90338).
|
||||
manual: True
|
||||
default: False
|
||||
|
||||
library
|
||||
exposed-modules:
|
||||
Simplex.FileTransfer.Agent
|
||||
@@ -122,6 +134,7 @@ library
|
||||
Simplex.Messaging.Crypto.File
|
||||
Simplex.Messaging.Crypto.Lazy
|
||||
Simplex.Messaging.Crypto.Ratchet
|
||||
Simplex.Messaging.Crypto.BBS
|
||||
Simplex.Messaging.Crypto.SNTRUP761
|
||||
Simplex.Messaging.Crypto.SNTRUP761.Bindings
|
||||
Simplex.Messaging.Crypto.SNTRUP761.Bindings.Defines
|
||||
@@ -130,6 +143,7 @@ library
|
||||
Simplex.Messaging.Crypto.ShortLink
|
||||
Simplex.Messaging.Encoding
|
||||
Simplex.Messaging.Encoding.String
|
||||
Simplex.Messaging.Names.Record
|
||||
Simplex.Messaging.Notifications.Client
|
||||
Simplex.Messaging.Notifications.Protocol
|
||||
Simplex.Messaging.Notifications.Transport
|
||||
@@ -141,6 +155,7 @@ library
|
||||
Simplex.Messaging.Server.QueueStore.Postgres.Config
|
||||
Simplex.Messaging.Server.QueueStore.QueueInfo
|
||||
Simplex.Messaging.ServiceScheme
|
||||
Simplex.Messaging.SimplexName
|
||||
Simplex.Messaging.Session
|
||||
Simplex.Messaging.SystemTime
|
||||
Simplex.Messaging.TMap
|
||||
@@ -261,6 +276,8 @@ library
|
||||
Simplex.Messaging.Server.MsgStore.Journal.SharedLock
|
||||
Simplex.Messaging.Server.MsgStore.STM
|
||||
Simplex.Messaging.Server.MsgStore.Types
|
||||
Simplex.Messaging.Server.Names
|
||||
Simplex.Messaging.Server.Names.HttpResolver
|
||||
Simplex.Messaging.Server.NtfStore
|
||||
Simplex.Messaging.Server.Prometheus
|
||||
Simplex.Messaging.Server.QueueStore
|
||||
@@ -300,11 +317,33 @@ library
|
||||
ghc-options: -Weverything -Wno-missing-exported-signatures -Wno-missing-import-lists -Wno-missed-specialisations -Wno-all-missed-specialisations -Wno-unsafe -Wno-safe -Wno-missing-local-signatures -Wno-missing-kind-signatures -Wno-missing-deriving-strategies -Wno-monomorphism-restriction -Wno-prepositive-qualified-module -Wno-implicit-prelude -Wno-missing-safe-haskell-mode -Wno-missing-export-lists -Wno-partial-fields -Wcompat -Werror=incomplete-record-updates -Werror=incomplete-patterns -Werror=incomplete-uni-patterns -Werror=missing-home-modules -Werror=missing-methods -Werror=tabs -Wredundant-constraints -Wincomplete-record-updates -Wunused-type-patterns -O2
|
||||
include-dirs:
|
||||
cbits
|
||||
cbits/blst/bindings
|
||||
cbits/blst/src
|
||||
cbits/libbbs/include
|
||||
cbits/libbbs/src
|
||||
cc-options: -D__BLST_PORTABLE__
|
||||
if flag(commoncrypto)
|
||||
cc-options: -DBBS_CRYPTO_CC
|
||||
frameworks: Security
|
||||
c-sources:
|
||||
cbits/sha512.c
|
||||
cbits/sntrup761.c
|
||||
cbits/blst/src/server.c
|
||||
cbits/libbbs/src/bbs.c
|
||||
cbits/libbbs/src/bbs_ciphersuites.c
|
||||
cbits/libbbs/src/bbs_util.c
|
||||
cbits/libbbs/src/compat-string.c
|
||||
cbits/libbbs/src/sha256.c
|
||||
cbits/libbbs/src/shake256.c
|
||||
asm-sources:
|
||||
cbits/blst/build/assembly.S
|
||||
extra-libraries:
|
||||
crypto
|
||||
if os(windows)
|
||||
c-sources:
|
||||
cbits/getentropy_win.c
|
||||
extra-libraries:
|
||||
bcrypt
|
||||
build-depends:
|
||||
aeson ==2.2.*
|
||||
, asn1-encoding ==0.9.*
|
||||
@@ -355,7 +394,10 @@ library
|
||||
build-depends:
|
||||
case-insensitive ==1.2.*
|
||||
, hashable ==1.4.*
|
||||
, http-client >=0.7 && <0.8
|
||||
, http-client-tls >=0.3 && <0.4
|
||||
, ini ==0.4.1
|
||||
, network-uri >=2.6 && <2.7
|
||||
, optparse-applicative >=0.15 && <0.17
|
||||
, process ==1.6.*
|
||||
, temporary ==1.3.*
|
||||
@@ -489,6 +531,7 @@ test-suite simplexmq-test
|
||||
AgentTests.EqInstances
|
||||
AgentTests.FunctionalAPITests
|
||||
AgentTests.MigrationTests
|
||||
AgentTests.ResolveNameTests
|
||||
AgentTests.ServerChoice
|
||||
AgentTests.ShortLinkTests
|
||||
CLITests
|
||||
@@ -505,9 +548,12 @@ test-suite simplexmq-test
|
||||
CoreTests.VersionRangeTests
|
||||
FileDescriptionTests
|
||||
RemoteControl
|
||||
NamesResolverServer
|
||||
RSLVTests
|
||||
ServerTests
|
||||
SMPAgentClient
|
||||
SMPClient
|
||||
SMPNamesTests
|
||||
SMPProxyTests
|
||||
Util
|
||||
XFTPAgent
|
||||
@@ -588,6 +634,8 @@ test-suite simplexmq-test
|
||||
, unliftio
|
||||
, unliftio-core
|
||||
, unordered-containers
|
||||
, wai
|
||||
, warp
|
||||
, yaml
|
||||
default-language: Haskell2010
|
||||
if flag(server_postgres)
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
node_modules
|
||||
dist
|
||||
dist-test
|
||||
@@ -1,93 +0,0 @@
|
||||
# Specifications
|
||||
|
||||
Disclaimer: specifications in this folder and its subfolders are generated by LLM. While they were reviewed and appear to be correct, they may contain mistakes, and should not be considered a protocol specification.
|
||||
|
||||
## Structure
|
||||
|
||||
Spec has two levels:
|
||||
|
||||
### `spec/modules/` — Per-module documentation
|
||||
|
||||
Mirrors the `src/Simplex/` directory structure exactly. Each `.hs` file has a corresponding `.md` file at the same relative path. Contains only information that is **not obvious from reading the code** and cannot fit in a one-line source comment:
|
||||
|
||||
- Non-obvious behavior (subtle invariants, ordering dependencies, concurrency assumptions)
|
||||
- Usage considerations (when to use X vs Y, common mistakes, caller obligations)
|
||||
- Relationships to other modules not visible from imports
|
||||
- Security notes specific to this module
|
||||
|
||||
**Not included**: type signatures, code snippets, function-by-function prose that restates the source. If reading the code tells you everything, the module doc says so briefly.
|
||||
|
||||
Function references use fully qualified names with markdown links:
|
||||
```
|
||||
[Simplex.Messaging.Server.subscribeServiceMessages](./modules/Simplex/Messaging/Server.md#subscribeServiceMessages)
|
||||
```
|
||||
|
||||
Source code links back via comments:
|
||||
```haskell
|
||||
-- spec: spec/modules/Simplex/Messaging/Server.md#subscribeServiceMessages
|
||||
subscribeServiceMessages :: ...
|
||||
```
|
||||
|
||||
### `spec/` root — Topic documentation
|
||||
|
||||
Cross-module documentation that follows a feature, mechanism, or concern across the entire stack. Topics answer "how does X work end-to-end?" rather than "what does this file do?"
|
||||
|
||||
Topics reference module docs rather than restating implementation details. They focus on:
|
||||
- End-to-end data flow across modules
|
||||
- Cross-cutting security analysis and invariants
|
||||
- Design rationale, risks, test gaps
|
||||
- Version gates and compatibility concerns
|
||||
|
||||
Some topics may migrate to `product/` if they are primarily about user-visible behavior and guarantees rather than implementation mechanics.
|
||||
|
||||
### `spec/security-invariants.md` — All security invariants
|
||||
|
||||
Cross-referenced from both module docs and topic docs.
|
||||
|
||||
## Conventions
|
||||
|
||||
Module doc entry format:
|
||||
```
|
||||
## functionName
|
||||
**Purpose**: ...
|
||||
**Calls**: [Module.a](./modules/path.md#a), [Module.b](./modules/path.md#b)
|
||||
**Called by**: [Module.c](./modules/path.md#c)
|
||||
**Invariant**: SI-XX
|
||||
**Security**: ...
|
||||
```
|
||||
|
||||
## Index
|
||||
|
||||
### Architecture
|
||||
|
||||
Component topology and message flow diagrams for each layer:
|
||||
|
||||
- [routers.md](routers.md) — Layer 1: SMP, XFTP, NTF routers
|
||||
- [clients.md](clients.md) — Layer 2: protocol client libraries
|
||||
- [agent.md](agent.md) — Layer 3: connection manager
|
||||
|
||||
### Topics
|
||||
|
||||
Cross-cutting concerns that span multiple modules:
|
||||
|
||||
- [topics/transport.md](topics/transport.md) — TLS, HTTP/2, WebSocket transport layers
|
||||
- [topics/patterns.md](topics/patterns.md) — Exception handling, encoding, compression, TMap
|
||||
- [topics/subscriptions.md](topics/subscriptions.md) — Queue subscriptions and delivery
|
||||
- [topics/notifications.md](topics/notifications.md) — Push notification flow
|
||||
- [topics/xftp.md](topics/xftp.md) — File transfer protocol
|
||||
- [topics/client-services.md](topics/client-services.md) — Service certificates for bulk operations
|
||||
- [topics/encryption.md](topics/encryption.md) — Encryption layers (TODO)
|
||||
|
||||
### Agent internals
|
||||
|
||||
- [agent/infrastructure.md](agent/infrastructure.md) — Workers, store, operation suspension
|
||||
- [agent/connections.md](agent/connections.md) — Connection lifecycle and states
|
||||
- [agent/xrcp.md](agent/xrcp.md) — Remote control protocol
|
||||
|
||||
### Modules
|
||||
|
||||
See `spec/modules/` — mirrors `src/Simplex/` structure.
|
||||
|
||||
### Security
|
||||
|
||||
- [security-invariants.md](security-invariants.md) — All security invariants
|
||||
@@ -1,69 +0,0 @@
|
||||
# Topic Candidates
|
||||
|
||||
> Cross-cutting patterns noticed during module documentation. Each entry may become a topic doc in `spec/` after all module docs are complete.
|
||||
|
||||
- **Exception handling strategy**: `catchOwn`/`catchAll`/`tryAllErrors` pattern (defined in Util.hs) used across router, client, and agent modules. The three-category classification (synchronous, own-async, cancellation) and when to use which catch variant is not obvious from any single call site.
|
||||
|
||||
- **Padding schemes**: Three different padding formats across the codebase — Crypto.hs uses 2-byte Word16 length prefix (max ~65KB), Crypto/Lazy.hs uses 8-byte Int64 prefix (file-sized), and both use '#' fill character. Ratchet header padding uses fixed sizes (88 or 2310 bytes). All use `pad`/`unPad` but with incompatible formats. The relationship between padding, encryption, and message size limits spans Crypto, Lazy, Ratchet, and the protocol layer.
|
||||
|
||||
- **NaCl construction variants**: crypto_box, secret_box, and KEM hybrid secret all use the same XSalsa20+Poly1305 core (Crypto.hs `xSalsa20`), but with different key sources (DH, symmetric, SHA3_256(DH||KEM)). The lazy streaming variant (Lazy.hs) adds prepend-tag vs tail-tag placement. File.hs wraps lazy streaming with handle-based I/O. Full picture requires reading Crypto.hs, Lazy.hs, File.hs, and SNTRUP761.hs together.
|
||||
|
||||
- **Transport encryption layering**: Three encryption layers overlap — TLS (Transport.hs), optional block encryption via sbcHkdf chains (Transport.hs tPutBlock/tGetBlock), and SMP protocol-level encryption. Block encryption is disabled for proxy connections (already encrypted), and absent for NTF protocol. The interaction of these layers with proxy version downgrade logic spans Transport.hs, Client.hs, and the SMP proxy module.
|
||||
|
||||
- **Certificate chain trust model**: ChainCertificates (Shared.hs) defines 0–4 cert chain semantics, used by both Client.hs (validateCertificateChain) and Server.hs (validateClientCertificate, SNI credential switching). The 4-length case skipping index 2 (operator cert) and the FQHN-disabled x509validate are decisions that span the entire transport security model.
|
||||
|
||||
- **SMP proxy protocol flow**: The PRXY/PFWD/RFWD proxy protocol involves Client.hs (proxySMPCommand with 10 error scenarios, forwardSMPTransmission with sessionSecret encryption), Protocol.hs (command types, version-dependent encoding), Transport.hs (proxiedSMPRelayVersion cap, proxyServer flag disabling block encryption). The double encryption (client-relay via PFWD + proxy-relay via RFWD), combined timeout (tcpConnect + tcpTimeout), nonce/reverseNonce pairing, and version downgrade logic are not visible from any single module.
|
||||
|
||||
- **Service certificate subscription model**: Service subscriptions (SUBS/NSUBS) and per-queue subscriptions (SUB/NSUB) coexist with complex state transitions. Client/Agent.hs manages dual active/pending subscription maps with session-aware cleanup. Protocol.hs defines useServiceAuth (only NEW/SUB/NSUB). Client.hs implements authTransmission with dual signing (entity key over cert hash + transmission, service key over transmission only). Transport.hs handles the service certificate handshake extension (v16+). The full subscription lifecycle — from DBService credentials through handshake to service subscription to disconnect/reconnect — spans all four modules.
|
||||
|
||||
- **Two agent layers**: Client/Agent.hs ("small agent") is used only in routers — SMP proxy and notification router — to manage client connections to other SMP routers. Agent.hs + Agent/Client.hs ("big agent") is used in client applications. Both manage SMP client connections with subscription tracking and reconnection, but the big agent adds the full messaging agent layer (connections, double ratchet, file transfer). When documenting Agent/Client.hs, Client/Agent.hs should be reviewed for shared patterns and differences.
|
||||
|
||||
- **Handshake protocol family**: SMP (Transport.hs), NTF (Notifications/Transport.hs), and XFTP (FileTransfer/Transport.hs) all have handshake protocols with the same structure (version negotiation + session binding + key exchange) but different feature sets. NTF is a strict subset. XFTP doesn't use the TLS handshake at all (HTTP2 layer). The shared types (THandle, THandleParams, THandleAuth) mean changes to the handshake infrastructure affect all three protocols.
|
||||
|
||||
- **Router subscription architecture**: The SMP router's subscription model spans Server.hs (serverThread split-STM lifecycle, tryDeliverMessage sync/async, ProhibitSub/ServerSub state machine), Env/STM.hs (SubscribedClients TVar-of-Maybe continuity, Client three-queue architecture), and Client/Agent.hs (small agent dual subscription model). The interaction between service subscriptions, direct queue subscriptions, notification subscriptions, and the serverThread subQ processing is not visible from any single module.
|
||||
|
||||
- **Duplex connection handshake**: The SMP duplex connection procedure (standard 10-step and fast 7-step) spans Agent.hs (orchestration, state machine), Agent/Protocol.hs (message types: AgentConfirmation/AgentConnInfoReply/AgentInvitation/HELLO, queue status types), Client.hs (SMP command dispatch), Protocol.hs (SMP-level KEY/SKEY commands). The handshake involves two-layer encryption (per-queue E2E + double ratchet), version-dependent paths (v2+ duplex, v6+ sender auth key, v7+ ratchet on confirmation, v9+ fast handshake with SKEY), and the asymmetry between initiating and accepting parties (different message types, different confirmation processing). The protocol spec (`agent-protocol.md`) defines the procedure but the implementation details — error handling, state persistence across restarts, race conditions between confirmation and message delivery — are only visible by reading the code across these modules.
|
||||
|
||||
- **Connection links**: Full connection links (URI format with `#/?` query parameters) and binary-encoded links (`Encoding` instances) serve different contexts — URIs for out-of-band sharing, binary for agent-to-agent messages. Each has independent version-conditional encoding with different backward-compat rules (URI parser adjusts agent version ranges for old contact links, binary parser patches `queueMode` for forward compat). The `VersionI`/`VersionRangeI` typeclasses convert between `SMPQueueInfo` (versioned, in confirmations) and `SMPQueueUri` (version-ranged, in links). Full picture requires Agent/Protocol.hs, Protocol.hs, and agent-protocol.md.
|
||||
|
||||
- **Short links**: Short links are a compact representation for sharing via URLs, not a replacement for full connection links — both are used. Short links store encrypted link data on the router and encode only a router hostname, link type character, and key hash in the URL. The link data lifecycle (creation, encryption with key derivation, owner chain-of-trust validation, mutable user data updates) spans Agent/Protocol.hs (types, serialization, owner validation, router shortening/restoration), Agent.hs (link creation and resolution API), and the router-side link storage. The `FixedLinkData`/`ConnLinkData` split (immutable vs mutable), `OwnerAuth` chain validation, and `PreparedLinkParams` pre-computation are not visible from any single module.
|
||||
|
||||
- **Agent worker framework**: `getAgentWorker` (lifecycle, restart rate limiting, crash recovery) + `withWork`/`withWork_`/`withWorkItems` (task retrieval with doWork flag atomics) defined in Agent/Client.hs, consumed by Agent.hs (async commands, message delivery), NtfSubSupervisor.hs (notification workers), FileTransfer/Agent.hs (XFTP workers), and simplex-chat. The framework separates two concerns: worker lifecycle (create-or-reuse, fork async, rate-limit restarts, escalate to CRITICAL) and task pattern (get next task, do task, as separate parameters). The doWork TMVar flag choreography (clear before query to prevent race) and the work-item-error vs store-error distinction are not obvious from any single consumer.
|
||||
|
||||
- **Agent operation suspension**: Five `AgentOpState` TVars (RcvNetwork, MsgDelivery, SndNetwork, Database, NtfNetwork) with a cascade ordering: ending RcvNetwork suspends MsgDelivery, ending MsgDelivery suspends SndNetwork + Database, ending SndNetwork suspends Database. `beginAgentOperation` retries if suspended, `endAgentOperation` decrements and cascades. All DB access goes through `withStore` which brackets with AODatabase. This ensures graceful shutdown propagates through dependent operations. Defined in Agent/Client.hs, used by Agent.hs subscriber and worker loops.
|
||||
|
||||
- **Queue rotation protocol**: Four agent messages (QADD → QKEY → QUSE → QTEST) on top of SMP commands, with asymmetric state machines on receiver side (`RcvSwitchStatus`: 4 states) and sender side (`SndSwitchStatus`: 2 states). Receiver initiates, creates new queue, sends QADD. Sender responds with QKEY. Receiver sends QUSE. Sender sends QTEST to complete. State types in Agent/Protocol.hs, orchestration in Agent.hs, queue creation/deletion in Agent/Client.hs. Protocol spec in agent-protocol.md. The fast variant (v9+ SMP with SKEY) skips the KEY command step.
|
||||
|
||||
- **Outside-STM lookup pattern**: Multiple modules use the pattern of looking up TVar references outside STM (via readTVarIO/TM.lookupIO), then reading/modifying the TVar contents inside STM. This avoids transaction re-evaluation from unrelated map changes. Used in: Server.hs (serverThread client lookup, tryDeliverMessage subscriber lookup), Env/STM.hs (deleteSubcribedClient), Client/Agent.hs (removeClientAndSubs, reconnectSMPClient). The safety invariant is that the outer map entries (TVars) are never removed — only their contents change.
|
||||
|
||||
- **NTF token lifecycle**: Token registration (TNEW) → verification push → NTConfirmed → TVFY → NTActive, with idempotent re-registration (DH secret check), TRPL (device token replacement reusing DH key), status repair for stuck tokens, and `PPApnsNull` test tokens suppressing stats. The lifecycle spans [Server.hs](modules/Simplex/Messaging/Notifications/Server.md) (command handling, verification push delivery), [Store/Postgres.hs](modules/Simplex/Messaging/Notifications/Server/Store/Postgres.md) (conditional status updates, duplicate registration cleanup), [Types.hs](modules/Simplex/Messaging/Notifications/Types.md) (NtfTknStatus state machine), and [Env.hs](modules/Simplex/Messaging/Notifications/Server/Env.md) (push client lazy initialization).
|
||||
|
||||
- **NTF push delivery pipeline**: Bounded TBQueue (`pushQ`) creates backpressure → `ntfPush` thread reads → `checkActiveTkn` gates PNMessage (but not PNVerification or PNCheckMessages) → APNS delivery with single retry on connection errors (new push client on retry) → PPTokenInvalid marks token NTInvalid. Spans [Server.hs](modules/Simplex/Messaging/Notifications/Server.md), [APNS.hs](modules/Simplex/Messaging/Notifications/Server/Push/APNS.md) (DER JWT signing, HTTP/2 serializing queue, fire-and-forget connection), [Env.hs](modules/Simplex/Messaging/Notifications/Server/Env.md) (push client caching with race tolerance).
|
||||
|
||||
- **NTF service subscription model**: Service-level subscriptions (SUBS/NSUBS on SMP) vs individual queue subscriptions, with fallback from service to individual when `CAServiceUnavailable`. Service credentials are lazily generated per SMP router with 25h backdating and ~2700yr validity. XOR hash triggers on PostgreSQL maintain subscription aggregate counts. Subscription status tracking uses `ntf_service_assoc` flag to distinguish service-associated from individually-subscribed queues. Spans [Server.hs](modules/Simplex/Messaging/Notifications/Server.md) (subscriber thread, service fallback), [Env.hs](modules/Simplex/Messaging/Notifications/Server/Env.md) (lazy credential generation, Weak ThreadId subscriber cleanup), [Store/Postgres.hs](modules/Simplex/Messaging/Notifications/Server/Store/Postgres.md) (XOR hash triggers, batch status updates, cursor-based pagination).
|
||||
|
||||
- **NTF startup resubscription**: `resubscribe` runs as detached `forkIO` (not in `raceAny_` group), uses `mapConcurrently` across SMP routers, each with `subscribeLoop` using 100x database batch multiplier and cursor-based pagination. `ExitCode` exceptions from `exitFailure` on DB error propagate to main thread despite `forkIO`. `getServerNtfSubscriptions` claims subscriptions by batch-updating to `NSPending`. Spans [Server.hs](modules/Simplex/Messaging/Notifications/Server.md), [Store/Postgres.hs](modules/Simplex/Messaging/Notifications/Server/Store/Postgres.md).
|
||||
|
||||
- **XFTP file upload pipeline**: Agent-side encryption (streaming 64KB blocks, fixed-size padding) → chunk size selection (75% threshold algorithm) → per-router data packet creation with ID collision retry (3 attempts) → recipient registration (recursive batching up to `maxRecipients` per FADD) → per-router data packet upload (command + data in single HTTP/2 streaming request) → file description generation (cross-product: M chunks × R replicas × N recipients → N descriptions). Spans [Agent.hs](modules/Simplex/FileTransfer/Agent.md) (worker orchestration, description generation), [Client.hs](modules/Simplex/FileTransfer/Client.md) (upload protocol), [Server.hs](modules/Simplex/FileTransfer/Server.md) (quota reservation with rollback, skipCommitted idempotency), [Crypto.hs](modules/Simplex/FileTransfer/Crypto.md) (streaming encryption with embedded header), [Description.hs](modules/Simplex/FileTransfer/Description.md) (validation, first-replica-only digest optimization).
|
||||
|
||||
- **XFTP file download pipeline**: Description parsing (ValidFileDescription validation, YAML or web URI) → per-router data packet download with ephemeral DH key pair per download (forward secrecy) → size and digest verification before decryption → streaming decryption with auth tag verification (output deleted on failure) → redirect resolution (depth-1 chain: decrypt redirect YAML, validate size/digest, download actual file). Spans [Agent.hs](modules/Simplex/FileTransfer/Agent.md) (worker orchestration, redirect handling), [Client.hs](modules/Simplex/FileTransfer/Client.md) (ephemeral DH, size-proportional timeout), [Client/Main.hs](modules/Simplex/FileTransfer/Client/Main.md) (web URI decoding, parallel download with router grouping), [Crypto.hs](modules/Simplex/FileTransfer/Crypto.md) (dual decrypt paths, auth tag deletion), [Description.hs](modules/Simplex/FileTransfer/Description.md) (redirect file descriptions).
|
||||
|
||||
- **XFTP handshake state machine**: Three-state session-cached handshake (`No entry` → `HandshakeSent` → `HandshakeAccepted`) per HTTP/2 session. Web clients use `xftp-web-hello` header and challenge-response identity proof; native clients use standard ALPN. SNI presence gates CORS headers, web serving, and SESSION error for unrecognized connections. Key reuse on re-hello preserves existing DH keys. Spans [Server.hs](modules/Simplex/FileTransfer/Server.md) (handshake logic, CORS, web serving), [Client.hs](modules/Simplex/FileTransfer/Client.md) (ALPN selection, cert chain validation), [Transport.hs](modules/Simplex/FileTransfer/Transport.md) (block size, version).
|
||||
|
||||
- **XFTP storage lifecycle**: Quota reservation via atomic `stateTVar` before upload → rollback on failure (subtract + delete partial data packet) → stored data packet deleted before store cleanup (crash risk: store references missing data packet) → `RoundedSystemTime 3600` for privacy-preserving expiration timestamps → expiration with configurable throttling (100ms between data packets) → startup storage reconciliation (override stats from live store). Spans [Server.hs](modules/Simplex/FileTransfer/Server.md), [Server/Store.hs](modules/Simplex/FileTransfer/Server/Store.md), [Server/Env.hs](modules/Simplex/FileTransfer/Server/Env.md), [Server/StoreLog.hs](modules/Simplex/FileTransfer/Server/StoreLog.md) (error-resilient replay, compaction).
|
||||
|
||||
- **XFTP worker architecture**: Five worker types in three categories: rcv (per-router data packet download + local decryption), snd (local prepare/encrypt + per-router data packet upload), del (per-router data packet delete). TMVar-based connection sharing with async retry on temporary errors, permanent error cleanup (put Left + delete from TMap). `withRetryIntervalLimit` caps consecutive retries; exhausted temporary errors silently abandon work cycle (chunk stays pending). `assertAgentForeground` dual check (throw if inactive + wait if backgrounded) gates every data packet operation. Spans [Agent.hs](modules/Simplex/FileTransfer/Agent.md), [Client/Agent.hs](modules/Simplex/FileTransfer/Client/Agent.md).
|
||||
|
||||
- **SessionVar protocol client lifecycle**: Protocol client connections (SMP, NTF, XFTP) use a lazy singleton pattern: `getSessVar` atomically checks TMap → `newProtocolClient` fills TMVar on success/failure → `waitForProtocolClient` reads with timeout. Error caching via `persistErrorInterval` prevents connection storms (failed connections cache the error with expiry; callers receive cached error without reconnecting). `removeSessVar` uses monotonic `sessionVarId` compare-and-swap to prevent stale disconnect callbacks from removing newer clients. SMP has additional complexity: `SMPConnectedClient` wraps client with per-connection proxied relay map, `updateClientService` synchronizes service credentials post-connect, disconnect callback moves subscriptions to pending with session-ID matching. XFTP always uses `NRMBackground` timing regardless of caller request. Spans [Session.md](modules/Simplex/Messaging/Session.md), [Agent/Client.md](modules/Simplex/Messaging/Agent/Client.md) (lifecycle, disconnect callbacks, reconnection workers), [Agent.md](modules/Simplex/Messaging/Agent.md) (subscriber loop consuming events).
|
||||
|
||||
- **Dual-backend agent store**: The agent store (~3700 lines in AgentStore.hs) compiles for both SQLite and PostgreSQL via `#if defined(dbPostgres)` CPP guards. Key behavioral differences: PostgreSQL uses `FOR UPDATE` row locking on reads preceding writes (SQLite relies on single-writer model); PostgreSQL uses `IN ?` with `In` wrapper for batch queries (SQLite falls back to per-row `forM` loops); PostgreSQL uses `constraintViolation` (SQLite checks `SQL.ErrorConstraint`); `createWithRandomId'` uses savepoints on PostgreSQL (failed statement aborts entire transaction without them). One known bug: `checkConfirmedSndQueueExists_` uses `#if defined(dpPostgres)` (typo: `dp` not `db`), so the `FOR UPDATE` clause is never included on any backend. Spans [AgentStore.md](modules/Simplex/Messaging/Agent/Store/AgentStore.md), [SQLite.md](modules/Simplex/Messaging/Agent/Store/SQLite.md).
|
||||
|
||||
- **Deferred message encryption**: Message bodies are NOT encrypted at enqueue time. `enqueueMessageB` advances the ratchet header and validates padding, but stores only the body reference (`sndMsgBodyId`) and encryption key. Actual encryption (`rcEncryptMsg`) happens at delivery time in `runSmpQueueMsgDelivery`. This enables body deduplication via `VRValue`/`VRRef` — identical bodies (common for group messages) share one database row, but each connection's delivery encrypts independently with its own ratchet. Confirmation and ratchet key messages bypass deferred encryption (pre-encrypted at enqueue time). Spans [Agent.md](modules/Simplex/Messaging/Agent.md) (enqueue + delivery), [AgentStore.md](modules/Simplex/Messaging/Agent/Store/AgentStore.md) (`snd_message_bodies` storage).
|
||||
|
||||
- **NTF agent subscription lifecycle**: The agent-side notification subscription system uses a supervisor-worker architecture with three worker pools (NTF router, SMP router, token deletion). `NSCCreate` triggers a four-way partition (`partitionQueueSubActions`): new sub, reset sub (credential mismatch or null action), continue SMP work, continue NTF work. Workers coordinate with the supervisor via `updated_by_supervisor` flag — workers only update local fields when the flag is set, preventing overwrite of supervisor decisions. The null-action sentinel (`workerErrors` sets action to NULL on permanent failure) bridges worker failure recovery to supervisor-driven re-creation. `retrySubActions` uses a shrinking TVar — each iteration only retries subs with temporary errors, so batches get smaller over time. `rescheduleWork` handles time-scheduled health checks by forking a sleep thread that re-signals `doWork`. Spans [NtfSubSupervisor.md](modules/Simplex/Messaging/Agent/NtfSubSupervisor.md) (supervisor, worker pools), [AgentStore.md](modules/Simplex/Messaging/Agent/Store/AgentStore.md) (updated_by_supervisor, null-action sentinel), [Agent/Client.md](modules/Simplex/Messaging/Agent/Client.md) (worker framework).
|
||||
|
||||
- **Session-aware SMP subscription management**: SMP queue subscriptions are tracked per transport session with session-ID validation at multiple points. `subscribeQueues` groups queues by transport session, subscribes concurrently, then validates `activeClientSession` post-RPC — if the client was replaced during the RPC, results are discarded and converted to temporary errors for retry. `removeClientAndSubs` (disconnect cleanup) only demotes subscriptions whose session ID matches the disconnecting client. Batch UP notifications are accumulated across transmissions and deduplicated against already-active subscriptions. When ALL results are temporary errors and no connections were already active, the SMP client is closed to force fresh connection. `maxPending` throttles concurrent pending subscriptions with STM retry backpressure. Spans [Agent/Client.md](modules/Simplex/Messaging/Agent/Client.md) (subscription state, session validation), [Agent.md](modules/Simplex/Messaging/Agent.md) (subscriber loop, processSMPTransmissions, UP accumulation).
|
||||
|
||||
- **Agent message envelope**: Agent messages use a two-layer format — outer `AgentMsgEnvelope` (version + type tag C/M/I/R + payload) and inner `AgentMessage` (after double-ratchet decryption, tags I/D/R/M + AMessage). Tag characters deliberately overlap between layers (disambiguated by context). `AgentInvitation` uses only per-queue E2E encryption (no ratchet established yet); `AgentRatchetKey` uses per-queue E2E (can't use ratchet to renegotiate ratchet); `AgentConfirmation` uses double ratchet. PQ support *shrinks* message size budgets (ratchet header + reply link grow with SNTRUP761 keys). `AEvent` is a GADT indexed by `AEntity` — prevents file events on connection entities at the type level. Spans [Agent/Protocol.md](modules/Simplex/Messaging/Agent/Protocol.md) (types, encoding, size budgets), [Agent.md](modules/Simplex/Messaging/Agent.md) (four e2e key states dispatch, message processing).
|
||||
|
||||
- **Ratchet synchronization protocol**: When the double ratchet gets out of sync (backup restoration, message loss), both parties exchange `AgentRatchetKey` messages with fresh DH keys. Role determination uses hash-ordering: `rkHash(k1, k2)` is computed by both sides — the party with the lower hash initializes the receiving ratchet, the other initializes sending and sends EREADY. This breaks symmetry when both parties simultaneously initiate. State machine: `RSOk`/`RSAllowed`/`RSRequired` → generate keys + reply; `RSStarted` → use stored keys; `RSAgreed` → error (reset to `RSRequired`). EREADY carries `lastExternalSndId` so the peer knows which messages used the old ratchet. `checkRatchetKeyHashExists` prevents processing the same key twice. Successful message decryption resets sync state to `RSOk` (the recovery signal). Spans [Agent.md](modules/Simplex/Messaging/Agent.md) (newRatchetKey, ereadyMsg, resetRatchetSync), [Agent/Protocol.md](modules/Simplex/Messaging/Agent/Protocol.md) (AgentRatchetKey type, cryptoErrToSyncState classification).
|
||||
@@ -1,191 +0,0 @@
|
||||
# Agent Architecture
|
||||
|
||||
The SimpleX Agent is the Layer 3 connection manager. It builds duplex encrypted connections on top of Layer 2 client libraries. This document shows its internal architecture: component topology and message processing flows.
|
||||
|
||||
For usage and API overview, see [docs/AGENT.md](../docs/AGENT.md). For protocol specifications, see [Agent Protocol](../protocol/agent-protocol.md), [PQDR](../protocol/pqdr.md).
|
||||
|
||||
**Split-phase encryption**: Message sending separates ratchet advancement (API thread, serialized) from body encryption (delivery worker, parallel). This prevents ratchet lock contention across queues while maintaining correct message ordering. See [infrastructure.md](agent/infrastructure.md#message-delivery).
|
||||
|
||||
**Worker taxonomy**: Three worker families handle background operations - delivery workers (per send queue), async command workers (per connection), and NTF workers (per server). All use the same create-or-reuse pattern with restart rate limiting. See [infrastructure.md](agent/infrastructure.md#worker-framework).
|
||||
|
||||
**Suspension cascade**: Operations drain in dependency order: `AORcvNetwork` → `AOMsgDelivery` → `AOSndNetwork` → `AODatabase`. Suspending receive processing cascades through to database access, ensuring clean shutdown. See [infrastructure.md](agent/infrastructure.md#operation-suspension-cascade).
|
||||
|
||||
---
|
||||
|
||||
**Module specs**: [Agent](modules/Simplex/Messaging/Agent.md) · [Agent Client](modules/Simplex/Messaging/Agent/Client.md) · [Agent Protocol](modules/Simplex/Messaging/Agent/Protocol.md) · [Store Interface](modules/Simplex/Messaging/Agent/Store/Interface.md) · [NtfSubSupervisor](modules/Simplex/Messaging/Agent/NtfSubSupervisor.md) · [XFTP Agent](modules/Simplex/FileTransfer/Agent.md) · [Ratchet](modules/Simplex/Messaging/Crypto/Ratchet.md)
|
||||
|
||||
### Agent components
|
||||
|
||||

|
||||
|
||||
### Message receive flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant R as SMP Router
|
||||
|
||||
box Agent
|
||||
participant SC as smpClients<br>(ProtocolClient pool)
|
||||
participant MQ as msgQ<br>(TBQueue)
|
||||
participant S as subscriber
|
||||
participant St as Store
|
||||
participant SQ as subQ<br>(TBQueue)
|
||||
end
|
||||
|
||||
participant App as Application
|
||||
|
||||
R->>SC: MSG (encrypted packet)
|
||||
SC->>MQ: write batch
|
||||
|
||||
S->>MQ: read batch
|
||||
S->>S: withConnLock<br>(serialize per connection)
|
||||
S->>St: load ratchet state<br>(lockConnForUpdate)
|
||||
S->>S: agentRatchetDecrypt<br>(double ratchet)
|
||||
S->>S: checkMsgIntegrity<br>(sequence + hash chain)
|
||||
S->>St: store received message,<br>update ratchet
|
||||
S->>SQ: write AEvt (MSG + metadata)
|
||||
|
||||
App->>SQ: read event
|
||||
|
||||
Note over App: application processes message
|
||||
|
||||
App->>S: ackMessage (agentMsgId)
|
||||
Note over S,R: ACK is async<br>(enqueued as internal command)
|
||||
S->>SC: ACK
|
||||
SC->>R: ACK
|
||||
```
|
||||
|
||||
### Message send flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant App as Application
|
||||
|
||||
box Agent
|
||||
participant API as sendMessage
|
||||
participant St as Store
|
||||
participant DW as deliveryWorker<br>(per send queue)
|
||||
participant SC as smpClients<br>(ProtocolClient pool)
|
||||
end
|
||||
|
||||
participant R as SMP Router
|
||||
|
||||
App->>API: sendMessage<br>(connId, body)
|
||||
API->>St: agentRatchetEncryptHeader<br>(advance ratchet, store<br>encrypt key + pending message)
|
||||
API->>DW: signal doWork (TMVar)
|
||||
API->>App: return msgId
|
||||
|
||||
DW->>St: getPendingQueueMsg
|
||||
DW->>DW: rcEncryptMsg<br>(encrypt body with stored key)
|
||||
DW->>DW: encode AgentMsgEnvelope
|
||||
DW->>SC: sendAgentMessage<br>(per-queue encrypt + SEND)
|
||||
SC->>R: SEND (encrypted packet)
|
||||
R->>SC: OK
|
||||
|
||||
DW->>St: delete pending message
|
||||
DW->>App: SENT msgId (via subQ)
|
||||
```
|
||||
|
||||
### Connection establishment flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant A as Alice (initiator)
|
||||
|
||||
box Agent A
|
||||
participant AA as Agent
|
||||
end
|
||||
|
||||
participant SMP as SMP Router
|
||||
|
||||
box Agent B
|
||||
participant AB as Agent
|
||||
end
|
||||
|
||||
participant B as Bob (joiner)
|
||||
|
||||
A->>AA: createConnection
|
||||
AA->>SMP: NEW<br>(Alice's receive queue)
|
||||
SMP->>AA: queue ID + keys
|
||||
AA->>A: invitation URI<br>(queue address + DH keys)
|
||||
|
||||
Note over A,B: invitation passed out-of-band<br>(QR code, link)
|
||||
|
||||
B->>AB: joinConnection<br>(invitation)
|
||||
AB->>AB: initSndRatchet<br>(PQ X3DH key agreement)
|
||||
AB->>SMP: SKEY (sender auth on<br>Alice's queue)
|
||||
AB->>SMP: NEW<br>(Bob's receive queue)
|
||||
SMP->>AB: queue ID
|
||||
AB->>SMP: SEND confirmation to<br>Alice's queue (Bob's queue<br>address + ratchet keys)
|
||||
|
||||
SMP->>AA: MSG (confirmation)
|
||||
AA->>AA: initRcvRatchet<br>(PQ X3DH key agreement),<br>decrypt confirmation
|
||||
AA->>A: CONF (request approval)
|
||||
A->>AA: allowConnection(confId)
|
||||
AA->>SMP: KEY (register sender key<br>on Alice's rcv queue)
|
||||
AA->>SMP: SKEY (sender auth on<br>Bob's queue)
|
||||
AA->>SMP: SEND reply to Bob's queue<br>(Alice's connection info)
|
||||
|
||||
SMP->>AB: MSG (reply)
|
||||
AB->>SMP: KEY (register sender key<br>on Bob's rcv queue)
|
||||
AB->>SMP: SEND HELLO to Alice
|
||||
|
||||
SMP->>AA: MSG (HELLO)
|
||||
AA->>SMP: SEND HELLO to Bob
|
||||
AA->>A: CON (connected)
|
||||
|
||||
SMP->>AB: MSG (HELLO)
|
||||
AB->>B: CON (connected)
|
||||
```
|
||||
|
||||
### File delivery flow (XFTP)
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant SA as Sender App
|
||||
|
||||
box Sender Agent
|
||||
participant S as xftpSnd workers
|
||||
participant SS as Store
|
||||
end
|
||||
|
||||
participant XFTP as XFTP Routers
|
||||
participant SMP as SMP Router
|
||||
|
||||
box Receiver Agent
|
||||
participant RS as Store
|
||||
participant R as xftpRcv workers
|
||||
end
|
||||
|
||||
participant RA as Receiver App
|
||||
|
||||
SA->>S: xftpSendFile(file)
|
||||
S->>S: encrypt file<br>(XSalsa20-Poly1305, random key + nonce)
|
||||
S->>S: split into chunks<br>(fixed sizes: 64KB - 4MB)
|
||||
S->>SS: store SndFile + chunks
|
||||
|
||||
loop each chunk
|
||||
S->>XFTP: FNEW (create data packet)
|
||||
XFTP->>S: sender ID + recipient IDs
|
||||
S->>XFTP: FPUT (upload encrypted chunk)
|
||||
end
|
||||
|
||||
S->>S: assemble FileDescription<br>(chunk locations, replicas,<br>encryption key + nonce)
|
||||
S->>SA: SFDONE<br>(sender + recipient descriptions)
|
||||
|
||||
Note over SA,RA: recipient description sent as<br>SMP message (encrypted, via double ratchet)
|
||||
|
||||
SA->>SMP: description in A_MSG
|
||||
SMP->>RA: description in MSG
|
||||
|
||||
RA->>R: xftpReceiveFile<br>(description)
|
||||
R->>RS: store RcvFile + chunks
|
||||
|
||||
loop each chunk (parallel per server)
|
||||
R->>XFTP: FGET (per-recipient auth key)
|
||||
XFTP->>R: encrypted chunk stream
|
||||
end
|
||||
|
||||
R->>R: stream chunks through<br>stateful decrypt (key + nonce),<br>verify auth tag at end
|
||||
R->>RA: RFDONE<br>(decrypted file path)
|
||||
```
|
||||
@@ -1,232 +0,0 @@
|
||||
# Agent Connections
|
||||
|
||||
Duplex connection lifecycle: establishment, queue rotation, ratchet synchronization, and message integrity. These cross-module flows span the Agent, protocol client, and store layers.
|
||||
|
||||
For per-module details: [Agent](../modules/Simplex/Messaging/Agent.md) · [Agent Protocol](../modules/Simplex/Messaging/Agent/Protocol.md) · [Ratchet](../modules/Simplex/Messaging/Crypto/Ratchet.md) · [Store Interface](../modules/Simplex/Messaging/Agent/Store/Interface.md). For the component diagram, see [agent.md](../agent.md). For protocol specification, see [Agent Protocol](../../protocol/agent-protocol.md) and [PQDR](../../protocol/pqdr.md).
|
||||
|
||||
- [Design constraints](#design-constraints)
|
||||
- [Connection establishment](#connection-establishment)
|
||||
- [Queue rotation](#queue-rotation)
|
||||
- [Ratchet synchronization](#ratchet-synchronization)
|
||||
- [Message envelope hierarchy](#message-envelope-hierarchy)
|
||||
- [Integrity chain](#integrity-chain)
|
||||
|
||||
---
|
||||
|
||||
## Design constraints
|
||||
|
||||
**Source**: [Agent.hs](../../src/Simplex/Messaging/Agent.hs), [Agent/Client.hs](../../src/Simplex/Messaging/Agent/Client.hs)
|
||||
|
||||
Two properties of the protocol drive much of the agent's complexity:
|
||||
|
||||
**TOFU retry safety**: Queues and links are secured via trust-on-first-use - the router accepts the first key presented (SKEY, KEY) and rejects any subsequent different key. If a network call succeeds but the response is lost, the client must retry with the *same* key, or the router will reject it. This means all cryptographic keys must be generated and persisted *before* the network call that uses them. The agent's pervasive store-then-execute pattern (`enqueueCommand` persists to DB, then worker executes with stored keys) exists primarily to satisfy this constraint.
|
||||
|
||||
**Network asymmetry**: After a client sends a message to a queue, the peer's response can arrive at the agent before the originating API call returns to the application. The application must already know the connection exists when it receives the event, otherwise it gets handshake events for an unknown connection. This drives split-phase APIs where the connection is registered locally before any network call.
|
||||
|
||||
Together, these constraints explain why the agent separates key generation from network operations, why commands are persisted before execution, and why connection creation is split into prepare + create phases.
|
||||
|
||||
---
|
||||
|
||||
## Connection establishment
|
||||
|
||||
**Source**: [Agent.hs](../../src/Simplex/Messaging/Agent.hs), [Agent/Protocol.hs](../../src/Simplex/Messaging/Agent/Protocol.hs)
|
||||
|
||||
### Split-phase connection creation
|
||||
|
||||
Connection creation is split into two phases to satisfy both design constraints:
|
||||
|
||||
**`prepareConnectionLink`** (no network, no database): generates root Ed25519 signing key pair and queue-level X25519 DH keys. Derives a short link key as `SHA3_256` of the encoded fixed link data. Returns the connection link URI and `PreparedLinkParams` in memory. The application can now embed the link in link data (e.g., for short link resolution) before the queue exists.
|
||||
|
||||
**`createConnectionForLink`** (single network call): uses the prepared parameters to create the queue on the router with NEW (root signing key as owner auth). The sender ID is deterministically derived from the correlation nonce (`SMP.EntityId $ B.take 24 $ C.sha3_384 corrId`), so a lost response can be retried - the router validates the same sender ID.
|
||||
|
||||
Without split-phase, the application would need to create the queue first, get the link, then update the queue with link data containing the link - requiring an extra round-trip.
|
||||
|
||||
### Standard handshake
|
||||
|
||||
The connection establishment flow is shown in [agent.md](../agent.md#connection-establishment-flow). The key non-obvious details:
|
||||
|
||||
**Ratchet initialization is asymmetric**: The initiator (Alice) generates X3DH key parameters during `newRcvConnSrv` and stores them via `createRatchetX3dhKeys`, but does not initialize any ratchet yet. The *receiving* ratchet is only initialized later in `smpConfirmation` via `initRcvRatchet` when the confirmation arrives with the responder's parameters. The responder (Bob) initializes a *sending* ratchet during `startJoinInvitation` via `initSndRatchet`. The names `RcvE2ERatchetParams`/`SndE2ERatchetParams` are historical - what matters is that the responder initializes first (sending direction), and the initiator initializes second (receiving direction) using the responder's parameters.
|
||||
|
||||
**Confirmation decryption proves key agreement**: In `smpConfirmation`, the initiator creates a fresh receiving ratchet from the responder's parameters and immediately uses it to decrypt the confirmation body. If decryption fails, the entire confirmation is rejected - there is no state where a connection has mismatched ratchets.
|
||||
|
||||
**HELLO exchange completes the handshake**: After `allowConnection`, both sides have duplex queues but haven't confirmed liveness. The responder (Bob) sends the first HELLO (with `notification = True` in MsgFlags), triggered by `ICDuplexSecure`. The initiator (Alice) receives it and sends her own HELLO back (also with `notification = True`). The initiator emits `CON` in the *delivery callback* of her HELLO (her rcvQueue is already Active from receiving Bob's HELLO). The responder emits `CON` when he *receives* the initiator's reply HELLO (his sndQueue is already Active from his own HELLO delivery). There are exactly two HELLO messages.
|
||||
|
||||
### Contact URI async path
|
||||
|
||||
For contact URIs (`joinConnectionAsync` with `CRContactUri`), the join is enqueued as an async command. The connection record is created locally (NewConnection state) before the network call, satisfying the network asymmetry constraint. The background worker then creates the receive queue, sends the invitation, and processes the handshake.
|
||||
|
||||
### PQ key agreement
|
||||
|
||||
PQ support is negotiated via version numbers: `agentVersion >= pqdrSMPAgentVersion && e2eVersion >= pqRatchetE2EEncryptVersion`. When both sides support PQ, the KEM public key travels in the confirmation body (too large for invitation URI). The responder encapsulates, producing `(kemCiphertext, kemSharedKey)`, and the hybrid key is derived via HKDF-SHA512 over the concatenation of three X3DH shared secrets plus the KEM shared secret, with info string `"SimpleXX3DH"`.
|
||||
|
||||
**PQ support is monotonic**: once enabled for a connection (`PQSupport PQSupportOn`), it cannot be downgraded. This affects header padding size (88 bytes without PQ vs 2310 bytes with PQ).
|
||||
|
||||
### Connection type state machine
|
||||
|
||||
```
|
||||
NewConnection
|
||||
+-> RcvConnection (initiator, after newRcvConnSrv)
|
||||
| +-> DuplexConnection (after allowConnection + connectReplyQueues)
|
||||
| +-> ContactConnection (contact address case)
|
||||
+-> SndConnection (responder, before reply queue created)
|
||||
| +-> DuplexConnection (after reply queue created)
|
||||
+-> ContactConnection (short link / contact address)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Queue rotation
|
||||
|
||||
**Source**: [Agent.hs](../../src/Simplex/Messaging/Agent.hs), [Agent/Store.hs](../../src/Simplex/Messaging/Agent/Store.hs)
|
||||
|
||||
Queue rotation replaces a receive queue with a new one on a different router, providing forward secrecy for the transport layer. The protocol uses a 4-message handshake.
|
||||
|
||||
### Protocol sequence
|
||||
|
||||
Rotation is initiated by the switching party calling `switchConnectionAsync` (client API), which sends QADD. The peer responds to QADD by creating a new send queue and replying with QKEY. Preconditions: connection must be duplex, no switch already in progress, ratchet must not be syncing.
|
||||
|
||||
```
|
||||
Receiver (switching party) Sender (peer)
|
||||
| |
|
||||
|-- QADD (new queue address) ---------->|
|
||||
| |-- creates SndQueue to new address
|
||||
|<--------- QKEY (sender auth key) ----|
|
||||
| |
|
||||
|-- secures new queue (ICQSecure) ----->|
|
||||
|-- QUSE (start using new queue) ----->|
|
||||
| |-- switches delivery to new queue
|
||||
|<--------- QTEST (on new queue) ------|
|
||||
| |
|
||||
|-- deletes old queue (ICQDelete) ---->|
|
||||
```
|
||||
|
||||
### State machines
|
||||
|
||||
**Receiver (RcvQueue switch)**: `RSSwitchStarted` -> `RSSendingQADD` -> `RSSendingQUSE` -> `RSReceivedMessage`. The switch becomes non-abortable at `RSSendingQUSE` - by this point the sender may have already deleted the old queue, so aborting would break the connection. `canAbortRcvSwitch` enforces this.
|
||||
|
||||
**Sender (SndQueue switch)**: creates new SndQueue on QADD, sends QKEY, marks old as `SSSendingQKEY`. On QUSE: sends QTEST *only to the new queue*, marks as `SSSendingQTEST`. Completes when QTEST delivery succeeds.
|
||||
|
||||
### Consecutive rotation handling
|
||||
|
||||
`dbReplaceQueueId` tracks which old queue a new one replaces. Each new queue stores `dbReplaceQueueId = Just oldQueueId`. When QADD is processed, send queues whose `dbReplaceQueueId` points to the current queue's `dbQueueId` are found and deleted in bulk. This handles consecutive rotation requests - only the latest rotation survives.
|
||||
|
||||
### Old queue deletion
|
||||
|
||||
Three triggers delete the old queue:
|
||||
1. **Sender-side**: QTEST delivery succeeds - old queue removed from `smpDeliveryWorkers` (worker thread stops)
|
||||
2. **Receiver-side**: first message arrives on new queue - receiver marks old queue for deletion via `ICQDelete`
|
||||
3. **Abort cleanup**: `abortConnectionSwitch` explicitly deletes new queues created during a failed switch attempt
|
||||
|
||||
---
|
||||
|
||||
## Ratchet synchronization
|
||||
|
||||
**Source**: [Agent.hs](../../src/Simplex/Messaging/Agent.hs), [Agent/Protocol.hs](../../src/Simplex/Messaging/Agent/Protocol.hs)
|
||||
|
||||
When double ratchet state becomes desynchronized (e.g., one side restores from backup), the agent can re-establish the ratchet without breaking the connection.
|
||||
|
||||
### State machine
|
||||
|
||||
```
|
||||
RSOk (synchronized)
|
||||
|
|
||||
v (crypto error detected)
|
||||
RSAllowed / RSRequired
|
||||
|
|
||||
v (synchronizeRatchet called)
|
||||
RSStarted (waiting for peer)
|
||||
|
|
||||
v (peer responds with own keys)
|
||||
RSAgreed (both exchanged keys)
|
||||
|
|
||||
v (ratchet recreated, EREADY sent/received)
|
||||
RSOk
|
||||
```
|
||||
|
||||
**Send prohibition**: `ratchetSyncSendProhibited` returns `True` for `RSRequired`, `RSStarted`, and `RSAgreed`. This blocks *all* messages including queue rotation messages - preventing state corruption while the ratchet is being re-established.
|
||||
|
||||
### Key exchange protocol
|
||||
|
||||
1. Initiator calls `synchronizeRatchet`, which generates new X3DH keys and sends them in an `AgentRatchetKey` envelope (discriminant `'R'`). State becomes `RSStarted`.
|
||||
2. Peer receives the ratchet key in `newRatchetKey`. If peer hasn't started sync, it generates own keys and sends a reply `AgentRatchetKey`.
|
||||
3. Both sides now have each other's keys. State becomes `RSAgreed`.
|
||||
|
||||
### Hash-ordered role assignment
|
||||
|
||||
Both parties compute `rkHash = SHA256(pubKeyBytes k1 || pubKeyBytes k2)` for their own keys. The party with the *smaller* hash initializes the receiving ratchet (`pqX3dhRcv`); the party with the larger hash initializes the sending ratchet (`pqX3dhSnd`) and sends `EREADY`. This deterministic tie-breaking avoids a separate negotiation round.
|
||||
|
||||
### EREADY completion
|
||||
|
||||
`EREADY` carries `lastExternalSndId` - the ID of the last message the sender received from the peer before switching ratchets. The receiving party uses this to know when the old ratchet's messages are exhausted and the new ratchet is fully active. Until EREADY arrives, messages may arrive encrypted with either the old or new ratchet.
|
||||
|
||||
### Error recovery
|
||||
|
||||
- **Crypto error during decrypt**: `cryptoErrToSyncState` classifies the error and sets state to `RSAllowed` or `RSRequired`. Client is notified via `RSYNC`.
|
||||
- **Successful decrypt during non-RSOk state**: if state is not `RSStarted` (which means sync is actively in progress), reset to `RSOk`. A successful message proves the ratchets are synchronized.
|
||||
- **Duplicate handling**: `rkHash` of received keys is checked against stored hashes to prevent reprocessing the same ratchet key message.
|
||||
|
||||
---
|
||||
|
||||
## Message envelope hierarchy
|
||||
|
||||
**Source**: [Agent/Protocol.hs](../../src/Simplex/Messaging/Agent/Protocol.hs)
|
||||
|
||||
Messages use three nesting levels, each adding a layer of structure:
|
||||
|
||||
### Level 1: AgentMsgEnvelope (transport)
|
||||
|
||||
Four variants with single-character discriminants:
|
||||
|
||||
| Variant | Disc. | Encryption | When |
|
||||
|---------|-------|-----------|------|
|
||||
| `AgentConfirmation` | `'C'` | Per-queue E2E (outer) + double ratchet (inner `encConnInfo`) | Connection handshake |
|
||||
| `AgentMsgEnvelope` | `'M'` | Double ratchet | Normal messages |
|
||||
| `AgentInvitation` | `'I'` | Per-queue E2E only | Contact URI join |
|
||||
| `AgentRatchetKey` | `'R'` | Per-queue E2E only | Ratchet sync |
|
||||
|
||||
`AgentMsgEnvelope` is fully double-ratchet encrypted. `AgentConfirmation` uses per-queue E2E for the outer envelope but also contains `encConnInfo` which is double-ratchet encrypted (the ratchet is initialized during confirmation processing). `AgentInvitation` and `AgentRatchetKey` use only per-queue E2E - the double ratchet is either not yet established or being replaced.
|
||||
|
||||
### Level 2: AgentMessage (application)
|
||||
|
||||
Inside the decrypted envelope:
|
||||
- `AgentConnInfo` / `AgentConnInfoReply` - connection info during handshake (double-ratchet encrypted inside `encConnInfo`)
|
||||
- `AgentRatchetInfo` - ratchet sync payload (not double-ratchet encrypted)
|
||||
- `AgentMessage APrivHeader AMessage` - user and control messages (double-ratchet encrypted)
|
||||
|
||||
The private header (`APrivHeader`) carries `sndMsgId` and `prevMsgHash` for the integrity chain.
|
||||
|
||||
### Level 3: AMessage (semantic)
|
||||
|
||||
Message types with 1-2 character discriminants:
|
||||
- User messages: `HELLO_`, `A_MSG_`, `A_RCVD_`, `A_QCONT_`, `EREADY_`
|
||||
- Queue rotation: `QADD_`, `QKEY_`, `QUSE_`, `QTEST_`
|
||||
|
||||
### ACK semantics
|
||||
|
||||
- **User messages** (`A_MSG_`): NOT auto-ACKed. Agent returns `ACKPending`; application must call `ackMessage`.
|
||||
- **Receipts** (`A_RCVD`): returns `ACKPending` when valid receipts are present (application must ACK after processing); auto-ACKed only when all receipts fail.
|
||||
- **Other control messages** (HELLO, QADD, QKEY, QUSE, QTEST, EREADY, A_QCONT): auto-ACKed by the agent.
|
||||
- **Error during processing**: `handleNotifyAck` sends `ERR` to the application but still ACKs to the router, preventing re-delivery of a message that will fail again.
|
||||
|
||||
---
|
||||
|
||||
## Integrity chain
|
||||
|
||||
**Source**: [Agent.hs](../../src/Simplex/Messaging/Agent.hs), [Agent/Protocol.hs](../../src/Simplex/Messaging/Agent/Protocol.hs)
|
||||
|
||||
Each message in a connection commits to the previous message via two mechanisms:
|
||||
|
||||
1. **External sender ID** (`lastExternalSndId`): monotonically increasing counter per connection
|
||||
2. **Previous message hash** (`prevMsgHash`): SHA256 of the previous message body
|
||||
|
||||
`checkMsgIntegrity` produces one of five outcomes:
|
||||
|
||||
| Outcome | Condition |
|
||||
|---------|-----------|
|
||||
| `MsgOk` | Sequential ID and matching hash |
|
||||
| `MsgBadId` | ID from the past (less than previous) |
|
||||
| `MsgDuplicate` | Same ID as previous |
|
||||
| `MsgSkipped` | Gap in IDs (messages lost) |
|
||||
| `MsgBadHash` | Sequential ID but hash mismatch |
|
||||
|
||||
**Non-rejecting semantics**: the agent does NOT reject messages with integrity failures. The result is reported to the application via `MsgMeta.integrity`. The application decides the policy - warn, ignore, or terminate the connection.
|
||||
@@ -1,211 +0,0 @@
|
||||
# Agent Infrastructure
|
||||
|
||||
The Agent's internal machinery: worker lifecycle, command dispatch, message delivery, subscription tracking, operation suspension, protocol client management, and dual-backend store. These cross-module patterns are not visible from any single module spec.
|
||||
|
||||
This document covers the "big agent" (`Agent.hs` + `Agent/Client.hs`) used in client applications. The "small agent" (`SMPClientAgent`) used in routers is documented in [clients.md](../clients.md).
|
||||
|
||||
For per-module details: [Agent](../modules/Simplex/Messaging/Agent.md) · [Agent Client](../modules/Simplex/Messaging/Agent/Client.md) · [Store Interface](../modules/Simplex/Messaging/Agent/Store/Interface.md) · [NtfSubSupervisor](../modules/Simplex/Messaging/Agent/NtfSubSupervisor.md) · [XFTP Agent](../modules/Simplex/FileTransfer/Agent.md). For the component diagram, see [agent.md](../agent.md).
|
||||
|
||||
- [Worker framework](#worker-framework)
|
||||
- [Async command processing](#async-command-processing)
|
||||
- [Message delivery](#message-delivery)
|
||||
- [Subscription tracking](#subscription-tracking)
|
||||
- [Operation suspension cascade](#operation-suspension-cascade)
|
||||
- [SessionVar lifecycle](#sessionvar-lifecycle)
|
||||
- [Dual-backend store](#dual-backend-store)
|
||||
|
||||
---
|
||||
|
||||
## Worker framework
|
||||
|
||||
**Source**: [Agent/Client.hs](../../src/Simplex/Messaging/Agent/Client.hs), [Agent/Env/SQLite.hs](../../src/Simplex/Messaging/Agent/Env/SQLite.hs) (Worker type)
|
||||
|
||||
All agent background processing - async commands, message delivery, notification workers, XFTP workers - uses a shared worker infrastructure defined in `Agent/Client.hs`.
|
||||
|
||||
**Create-or-reuse**: `getAgentWorker` atomically checks a `TMap` for an existing worker keyed by the work item (connection+server, send queue address, etc.). If absent, creates a new `Worker` with a unique monotonic `workerId` from `workerSeq` and inserts it. If present and `hasWork=True`, signals the existing worker via `tryPutTMVar doWork ()`.
|
||||
|
||||
**Fork and run**: `runWorkerAsync` uses bracket on the worker's `action` TMVar. If the taken value is `Nothing`, the worker is idle - start it. If `Just _`, it's already running - put it back and return. The `action` TMVar holds `Just (Weak ThreadId)` to avoid preventing GC of the worker thread.
|
||||
|
||||
**Task retrieval race prevention**: `withWork` clears the `doWork` flag *before* calling `getWork` (not after). This prevents a race: query finds nothing → another thread adds work + signals → worker clears flag (losing the signal). By clearing first, any signal that arrives during the query is preserved.
|
||||
|
||||
**Error classification**: `withWork` distinguishes two failure modes:
|
||||
- *Work-item error* (`isWorkItemError`): the task itself is broken (likely recurring). Worker stops and sends `CRITICAL False`.
|
||||
- *Other error*: any non-work-item error (e.g., transient database issue). Worker re-signals `doWork` and reports `INTERNAL` (retry may succeed).
|
||||
|
||||
**Restart rate limiting**: On worker exit, `restartOrDelete` checks the `restarts` counter against `maxWorkerRestartsPerMin`. Under the limit: reset action, re-signal, restart. Over the limit: delete the worker from the map and send `CRITICAL True` (escalation to the application). A restart only proceeds if the `workerId` in the map still matches the current worker - a stale restart from a replaced worker is a no-op.
|
||||
|
||||
**Consumers**: Four families use this framework:
|
||||
- Async command workers - keyed by `(ConnId, Maybe SMPServer)`, in `asyncCmdWorkers` TMap
|
||||
- Delivery workers - keyed by `SndQAddr`, in `smpDeliveryWorkers` TMap, paired with a `TMVar ()` retry lock
|
||||
- NTF workers - three pools (`ntfWorkers` per NTF server, `ntfSMPWorkers` per SMP server, `ntfTknDelWorkers` for token deletion) in `NtfSubSupervisor`
|
||||
- XFTP workers - three worker types (rcv, snd, del) with TMVar-based connection sharing
|
||||
|
||||
---
|
||||
|
||||
## Async command processing
|
||||
|
||||
**Source**: [Agent.hs](../../src/Simplex/Messaging/Agent.hs), [Agent/Protocol.hs](../../src/Simplex/Messaging/Agent/Protocol.hs) (command types), [Agent/Store.hs](../../src/Simplex/Messaging/Agent/Store.hs) (internal command types)
|
||||
|
||||
Async commands handle state transitions that require network calls but shouldn't block the API thread: securing queues, deleting old queues during rotation, acknowledging messages. The dispatch loop `runCommandProcessing` runs one worker per `(ConnId, Maybe SMPServer)` key.
|
||||
|
||||
**Enqueueing**: API functions call `enqueueCommand`, which persists the command to the `commands` table (crash-safe) and spawns/wakes the worker via `getAsyncCmdWorker`. On agent startup, `resumeAllCommands` fetches all pending commands grouped by connection+server and signals their workers.
|
||||
|
||||
**Command types**: Two categories share the same dispatch loop:
|
||||
- *Client commands* (`AClientCommand`): `NEW`, `JOIN`, `LET` (allow connection), `ACK`, `LSET`/`LGET` (set/get connection link data), `SWCH` (switch queue), `DEL`. Triggered by application API calls.
|
||||
- *Internal commands* (`AInternalCommand`): `ICAck` (ack to router), `ICAckDel` (ack + delete local message), `ICAllowSecure`/`ICDuplexSecure` (secure after confirmation), `ICQSecure` (secure queue during switch), `ICQDelete` (delete old queue after switch), `ICDeleteConn` (delete connection), `ICDeleteRcvQueue` (delete specific receive queue). Generated *during* message processing to handle state transitions asynchronously.
|
||||
|
||||
**Retry and movement**: `tryMoveableCommand` wraps execution with `withRetryInterval`. On `temporaryOrHostError`, it retries with backoff. Individual command handlers can return `CCMoved` (e.g., when a queue has moved to a different router) after updating the command's server field in the store - `tryMoveableCommand` then exits cleanly, letting the moved command be picked up by the appropriate worker.
|
||||
|
||||
**Locking**: State-sensitive commands use `tryWithLock` / `tryMoveableWithLock`, which acquire `withConnLock` before execution. This serializes operations on the same connection, preventing races between concurrent command processing and message receipt.
|
||||
|
||||
**Event overflow**: Events are written directly to `subQ` if there is room. When `subQ` is full, events overflow into a local `pendingCmds` list and are flushed to `subQ` after the command completes, providing backpressure handling.
|
||||
|
||||
---
|
||||
|
||||
## Message delivery
|
||||
|
||||
**Source**: [Agent.hs](../../src/Simplex/Messaging/Agent.hs), [Agent/RetryInterval.hs](../../src/Simplex/Messaging/Agent/RetryInterval.hs)
|
||||
|
||||
Message delivery uses a split-phase encryption design: the ratchet advances in the API thread (serialized), while the actual body encryption happens in the per-queue delivery worker (parallel). This avoids ratchet lock contention across queues.
|
||||
|
||||
**Phase 1 - API thread** (`enqueueMessageB`):
|
||||
1. Encode the agent message with `internalSndId` + `prevMsgHash` (for the receiver's integrity chain)
|
||||
2. Call `agentRatchetEncryptHeader` - advances the double ratchet, produces a message encryption key (MEK), padded length, and PQ encryption status
|
||||
3. Store `SndMsg` with `SndMsgPrepData` (MEK, paddedLen, sndMsgBodyId) in the database
|
||||
4. Create `SndMsgDelivery` record for each send queue
|
||||
5. `submitPendingMsg` - increments `msgDeliveryOp.opsInProgress` (for suspension tracking) and signals delivery workers via `getDeliveryWorker`
|
||||
|
||||
**Phase 2 - delivery worker** (`runSmpQueueMsgDelivery`):
|
||||
1. `throwWhenNoDelivery` - kills the worker thread if the queue's address has been removed from `smpDeliveryWorkers` (prevents delivery to queues replaced during switch)
|
||||
2. `getPendingQueueMsg` - fetches the next pending message from the store, resolving the `sndMsgBodyId` reference into the actual message body and constructing `PendingMsgPrepData`
|
||||
3. Re-encode the message with `internalSndId`/`prevMsgHash`, then `rcEncryptMsg` to encrypt with the stored MEK (no ratchet access needed)
|
||||
4. `sendAgentMessage` - per-queue encrypt + SEND to the router
|
||||
|
||||
**Connection info messages** (`AM_CONN_INFO`, `AM_CONN_INFO_REPLY`) skip split-phase encryption entirely - they are sent as per-queue E2E encrypted confirmation bodies via `sendConfirmation` (encrypted with `agentCbEncrypt`, not with the double ratchet).
|
||||
|
||||
**Retry with dual intervals**: Delivery uses `withRetryLock2`, which maintains two retry interval states (slow and fast) but only one wait is active at a time. A background thread sleeps for the current interval, then signals the delivery worker via `tryPutTMVar`. When the router sends `QCONT` (queue buffer cleared), the agent calls `tryPutTMVar retryLock ()` to wake the delivery thread immediately, avoiding unnecessary delay.
|
||||
|
||||
**Error handling**:
|
||||
- `SMP QUOTA` - switch to slow retry, don't penalize (backpressure from router)
|
||||
- `SMP AUTH` - permanent failure: for data messages, notify and delete; for handshake messages, report connection error; for queue-switch messages, report queue error
|
||||
- `temporaryOrHostError` - retry with backoff
|
||||
- Other errors - report to application, delete command
|
||||
|
||||
---
|
||||
|
||||
## Subscription tracking
|
||||
|
||||
**Source**: [Agent/TSessionSubs.hs](../../src/Simplex/Messaging/Agent/TSessionSubs.hs), [Agent/Client.hs](../../src/Simplex/Messaging/Agent/Client.hs)
|
||||
|
||||
The agent tracks per-queue subscription state in `TSessionSubs` (defined in `Agent/TSessionSubs.hs`), keyed by `SMPTransportSession = (UserId, SMPServer, Maybe ByteString)` where the `ByteString` carries the entity ID in entity-session mode or `Nothing` in shared mode. Each transport session holds:
|
||||
|
||||
```
|
||||
SessSubs
|
||||
├── subsSessId :: TVar (Maybe SessionId) -- TLS session ID
|
||||
├── activeSubs :: TMap RecipientId RcvQueueSub
|
||||
├── pendingSubs :: TMap RecipientId RcvQueueSub
|
||||
├── activeServiceSub :: TVar (Maybe ServiceSub)
|
||||
└── pendingServiceSub :: TVar (Maybe ServiceSub)
|
||||
```
|
||||
|
||||
**State machine**: Subscriptions move between three states:
|
||||
|
||||
- **Pending → Active**: After subscription RPC succeeds, `addActiveSub'` promotes the queue - but only if the returned session ID matches the stored TLS session ID (`Just sessId == sessId'`). On mismatch (TLS reconnected between RPC send and response), the subscription is silently added to pending instead. No exception - concurrent resubscription paths handle this naturally.
|
||||
|
||||
- **Active → Pending**: When `setSessionId` is called with a *different* session ID (TLS reconnect), all active subscriptions are atomically demoted to pending. Session ID is updated to the new value.
|
||||
|
||||
- **Pending → Removed**: `failSubscriptions` moves permanently-failed queues (non-temporary SMP errors) to `removedSubs` - a separate `TMap` in `AgentClient`, not part of `TSessionSubs`. The removal is tracked for diagnostic reporting via `getSubscriptions`.
|
||||
|
||||
**Service-associated queues**: Queues with `serviceAssoc=True` are *not* added to `activeSubs` individually. Instead, the service subscription's count is incremented and its `idsHash` XOR-accumulates the queue's hash. The router tracks individual queues via the service subscription; the agent only tracks the aggregate. Consequence: `hasActiveSub(rId)` returns `False` for service-associated queues - callers must check the service subscription separately.
|
||||
|
||||
**Disconnect cleanup** (`smpClientDisconnected`):
|
||||
1. `removeSessVar` with CAS check (monotonic `sessionVarId` prevents stale callbacks from removing newer clients)
|
||||
2. `setSubsPending` - demote active→pending, filtered by matching `SessionId` only
|
||||
3. Delete proxied relay sessions created by this client
|
||||
4. Fire `DISCONNECT`, `DOWN` (affected connections), `SERVICE_DOWN` (if service sub existed)
|
||||
5. Release GET locks for affected queues
|
||||
6. Resubscribe: either spawn `resubscribeSMPSession` worker (entity-session mode) or directly resubscribe queues and services (other modes)
|
||||
|
||||
**Resubscription worker**: Per-transport-session worker with exponential backoff. Loops until `pendingSubs` and `pendingServiceSub` are both empty. Uses `waitForUserNetwork` with bounded wait - proceeds even without network (prevents indefinite blocking). Worker self-cleans via `removeSessVar` on exit.
|
||||
|
||||
**UP event deduplication**: After a batch subscription RPC, `UP` events are emitted only for connections that were *not* already in `activeSubs` before the batch. This prevents duplicate notifications for already-subscribed connections.
|
||||
|
||||
---
|
||||
|
||||
## Operation suspension cascade
|
||||
|
||||
**Source**: [Agent/Client.hs](../../src/Simplex/Messaging/Agent/Client.hs)
|
||||
|
||||
Five `AgentOpState` TVars track in-flight operations for graceful shutdown. Each holds `{opSuspended :: Bool, opsInProgress :: Int}`.
|
||||
|
||||
**Cascade ordering**:
|
||||
```
|
||||
AONtfNetwork (independent - no cascading)
|
||||
|
||||
AORcvNetwork → AOMsgDelivery → AOSndNetwork → AODatabase
|
||||
```
|
||||
|
||||
**Mechanics**: `endAgentOperation` decrements `opsInProgress`. If the count reaches zero and the operation is suspended, it calls the cascade action: `AORcvNetwork` suspends `AOMsgDelivery`, which suspends `AOSndNetwork`, which suspends `AODatabase`. At the leaf (`AODatabase`), `notifySuspended` writes `SUSPENDED` to `subQ` and sets `agentState = ASSuspended`.
|
||||
|
||||
**Blocking**: `beginAgentOperation` blocks (STM `retry`) while `opSuspended == True`. This means new operations of a suspended type cannot start - they wait until the operation is resumed. `agentOperationBracket` provides structured bracketing (begin on entry, end on exit).
|
||||
|
||||
**Two wait modes**:
|
||||
- `waitWhileSuspended` - blocks only during `ASSuspended`, proceeds during `ASSuspending` (allows in-flight operations to complete)
|
||||
- `waitUntilForeground` - blocks during both `ASSuspending` and `ASSuspended` (stricter, for operations that need full foreground)
|
||||
|
||||
**Usage**: `withStore` brackets all database access with `AODatabase`. Message delivery uses `AOSndNetwork` + `AOMsgDelivery`. Receive processing uses `AORcvNetwork`. This ensures that suspending receive processing cascades through delivery to database, and nothing touches the database after all operations drain.
|
||||
|
||||
---
|
||||
|
||||
## SessionVar lifecycle
|
||||
|
||||
**Source**: [Agent/Client.hs](../../src/Simplex/Messaging/Agent/Client.hs)
|
||||
|
||||
Protocol client connections (SMP, XFTP, NTF) use a lazy singleton pattern via `SessionVar` - a `TMVar` in a `TMap` keyed by transport session.
|
||||
|
||||
**Connection**: `getSessVar` atomically checks the TMap. Returns `Left newVar` (absent - caller must connect) or `Right existingVar` (present - wait for result). `newProtocolClient` wraps the connection attempt: on success, fills the TMVar with `Right client` and writes `CONNECT` event; on failure, fills with `Left (error, maybeRetryTime)` and re-throws.
|
||||
|
||||
**Error caching**: Failed connections cache the error with an expiry timestamp based on `persistErrorInterval`. Future attempts during the interval immediately receive the cached error without reconnecting - this prevents connection storms when a router is down. When `persistErrorInterval == 0`, the SessionVar is removed immediately on failure (fresh connection on next attempt).
|
||||
|
||||
**Compare-and-swap**: Each SessionVar has a monotonic `sessionVarId` from `workerSeq`. `removeSessVar` only removes if the `sessionVarId` matches the current map entry. This prevents a stale disconnect callback (from an old client) from removing a newer client that connected after the old one disconnected.
|
||||
|
||||
**Service credential synchronization** (`updateClientService`): On SMP reconnect, the agent reconciles service credentials between client and router state - updating, creating, or removing service associations as needed. Router version downgrade (router loses service support) triggers client-side service deletion.
|
||||
|
||||
**XFTP special case**: `getProtocolServerClient` ignores the caller's `NetworkRequestMode` parameter for XFTP, always using `NRMBackground` timing. XFTP connections always use background retry timing regardless of the caller's request.
|
||||
|
||||
---
|
||||
|
||||
## Dual-backend store
|
||||
|
||||
**Source**: [Agent/Store/SQLite.hs](../../src/Simplex/Messaging/Agent/Store/SQLite.hs), [Agent/Store/Postgres.hs](../../src/Simplex/Messaging/Agent/Store/Postgres.hs), [Agent/Store/AgentStore.hs](../../src/Simplex/Messaging/Agent/Store/AgentStore.hs)
|
||||
|
||||
The agent supports SQLite and PostgreSQL via CPP compilation flags (`#if defined(dbPostgres)`). Three wrapper modules (`Interface.hs`, `Common.hs`, `DB.hs`) re-export the appropriate backend. A single binary compiles with one active backend.
|
||||
|
||||
**Key behavioral differences**:
|
||||
|
||||
| Aspect | SQLite | PostgreSQL |
|
||||
|--------|--------|------------|
|
||||
| Row locking | Single-writer model (no locking needed) | `FOR UPDATE` on reads preceding writes |
|
||||
| Batch queries | Per-row `forM` loops | `IN ?` with `In` wrapper |
|
||||
| Constraint violations | `SQL.ErrorConstraint` pattern match | `constraintViolation` function |
|
||||
| Transaction savepoints | Not needed | Used in `createWithRandomId'` (failed statement aborts entire transaction without them) |
|
||||
| Busy/locked errors | `ErrorBusy`/`ErrorLocked` → `SEDatabaseBusy` → `CRITICAL True` | All SQL errors → `SEInternal` |
|
||||
|
||||
**Store access bracketing**: `withStore` wraps all database operations with `agentOperationBracket AODatabase`, connecting the store to the suspension cascade. `withStoreBatch` / `withStoreBatch'` run multiple operations in a single transaction with per-operation error catching.
|
||||
|
||||
**Known bug**: `checkConfirmedSndQueueExists_` uses `#if defined(dpPostgres)` (typo - should be `dbPostgres`), so the `FOR UPDATE` clause is never included on either backend.
|
||||
|
||||
### Migration framework
|
||||
|
||||
**Source**: [Agent/Store/Migrations.hs](../../src/Simplex/Messaging/Agent/Store/Migrations.hs), [Agent/Store/Shared.hs](../../src/Simplex/Messaging/Agent/Store/Shared.hs)
|
||||
|
||||
Migrations are Haskell modules under `Agent/Store/SQLite/Migrations/` and `Agent/Store/Postgres/Migrations/`. Each has `up` SQL and optional `down` SQL.
|
||||
|
||||
**Key behaviors**:
|
||||
|
||||
- `migrationsToRun` compares app migrations against the `migrations` table by name. Divergent histories (app has `[a,b]`, DB has `[a,c]`) produce `MTREDifferent` error - manual intervention required.
|
||||
- Each migration runs in its own transaction with the `migrations` insert *before* the schema change - failure rolls back both.
|
||||
- Downgrades require all intermediate migrations to have `down` SQL; missing any produces `MTRENoDown`.
|
||||
- `MigrationConfirmation` controls whether upgrades/downgrades auto-apply, prompt, or error.
|
||||
|
||||
**Special case**: `m20220811_onion_hosts` triggers `updateServers` to expand host entries with Tor addresses - this is data migration, not just schema.
|
||||
@@ -1,99 +0,0 @@
|
||||
# XRCP - Cross-Device Remote Control
|
||||
|
||||
XRCP enables a desktop application to control a mobile device over the local network. The protocol establishes an encrypted session between two devices using TLS, post-quantum hybrid key exchange, and optional multicast discovery.
|
||||
|
||||
This document covers the cross-module flows that are not visible from individual module specs. For message formats and cryptographic operations, see [protocol/xrcp.md](../../protocol/xrcp.md). For per-module details: [Client](../modules/Simplex/RemoteControl/Client.md) · [Invitation](../modules/Simplex/RemoteControl/Invitation.md) · [Discovery](../modules/Simplex/RemoteControl/Discovery.md) · [Types](../modules/Simplex/RemoteControl/Types.md).
|
||||
|
||||
**Terminology note**: in the code, "host" is the mobile device (being controlled) and "ctrl" is the desktop (controlling). The protocol spec uses the reverse convention - "host" serves, "controller" connects. This document uses the code convention.
|
||||
|
||||
- [Session handshake flow](#session-handshake-flow)
|
||||
- [KEM hybrid key exchange](#kem-hybrid-key-exchange)
|
||||
- [Multicast discovery](#multicast-discovery)
|
||||
- [Block framing and padding](#block-framing-and-padding)
|
||||
|
||||
---
|
||||
|
||||
## Session handshake flow
|
||||
|
||||
**Source**: [RemoteControl/Client.hs](../../src/Simplex/RemoteControl/Client.hs), [RemoteControl/Discovery.hs](../../src/Simplex/RemoteControl/Discovery.hs)
|
||||
|
||||
The handshake spans `Client.connectRCHost` (controller side, despite the name), `Client.connectRCCtrl` (host side), `Invitation.mkInvitation`, and `Discovery.startTLSServer`. The full sequence:
|
||||
|
||||
1. **Controller starts TLS server**: generates ephemeral session keys + DH keys, creates a signed invitation containing the CA fingerprint and identity key, starts a TLS server on an ephemeral port. The TLS hook `onNewHandshake` enforces single-session - a second connection attempt is rejected by checking whether the session TMVar is already filled.
|
||||
|
||||
2. **Invitation delivery**: the invitation reaches the host either out-of-band (QR code scan for first pairing) or via encrypted multicast announcement (subsequent sessions - see [Multicast discovery](#multicast-discovery)).
|
||||
|
||||
3. **Host connects via TLS**: `connectRCCtrl` establishes a TLS connection. Both sides validate certificate chains. On the controller side, `onClientCertificate` explicitly checks for a 2-certificate chain (leaf + CA root) and validates the host's CA fingerprint against `KnownHostPairing.hostFingerprint` (or stores it on first pairing). On the host side, the controller's CA fingerprint is validated against `RCCtrlPairing.ctrlFingerprint` in `updateCtrlPairing`.
|
||||
|
||||
4. **User confirmation barrier**: after TLS connects, both sides extract the TLS channel binding (`tlsUniq`) as a session code. The application displays this code on both devices for the user to verify. On the host side, `confirmCtrlSession` uses a double `putTMVar` - the first put signals the decision (accept/reject), the second blocks until the session thread acknowledges the value, ensuring `confirmCtrlSession` does not return prematurely.
|
||||
|
||||
5. **Hello exchange** (asymmetric encryption):
|
||||
- Host sends `RCHostEncHello` (`prepareHostHello`): DH public key in plaintext + encrypted body containing the KEM encapsulation key, CA fingerprint, and app info. Encrypted with `cbEncrypt` (classical DH secret).
|
||||
- Controller decrypts the hello, performs KEM encapsulation (see [KEM hybrid key exchange](#kem-hybrid-key-exchange)), derives the hybrid session key, initializes a chain via `sbcInit`, and sends `RCCtrlEncHello` (`prepareHostSession`) encrypted with a key derived from the chain (`sbcHkdf` + `sbEncrypt`).
|
||||
- The asymmetry is deliberate: at the time the host sends its hello, KEM hasn't completed yet, so only classical DH encryption is available. After the controller encapsulates, both sides have the hybrid key.
|
||||
|
||||
6. **Chain key initialization**: both sides call `sbcInit` with the hybrid key to derive send/receive chain keys. The host explicitly **swaps** the key pair (`swap` call in `prepareCtrlSession`, which runs on the host side despite its name) - both sides derive keys in the same order from `sbcInit`, but have opposite send/receive roles, so the host must reverse them. The controller does not swap.
|
||||
|
||||
7. **Error path**: if KEM encapsulation fails, the controller sends `RCCtrlEncError` (a variant of `RCCtrlEncHello`) encrypted with the DH key (not the hybrid key, which doesn't exist yet). The host can decrypt the error because it has the DH secret from step 5. Note: this error path is not yet fully implemented in the code.
|
||||
|
||||
---
|
||||
|
||||
## KEM hybrid key exchange
|
||||
|
||||
**Source**: [RemoteControl/Client.hs](../../src/Simplex/RemoteControl/Client.hs)
|
||||
|
||||
The session key combines classical Diffie-Hellman with SNTRUP761 (lattice-based KEM) via `SHA3_256(dhSecret || kemSharedKey)` (`kemHybridSecret` in `Crypto/SNTRUP761.hs`). This provides protection against quantum computers while maintaining classical security as a fallback.
|
||||
|
||||
The KEM public key is too large for a QR code invitation, so it travels in the encrypted hello body. Fresh KEM keys are generated every session - no KEM state is cached between sessions.
|
||||
|
||||
1. Host generates a fresh KEM key pair (`prepareHostHello`), puts the KEM public key in the host hello body
|
||||
2. Controller decrypts hello with DH secret, extracts KEM public key
|
||||
3. Controller encapsulates (`sntrup761Enc`): produces `(kemCiphertext, kemSharedKey)`
|
||||
4. Controller derives hybrid key: `SHA3_256(dhSecret || kemSharedKey)`
|
||||
5. Controller sends `kemCiphertext` in the ctrl hello body (`RCCtrlEncHello`)
|
||||
6. Host decapsulates `kemCiphertext` (`sntrup761Dec`) to recover `kemSharedKey`, derives the same hybrid key
|
||||
|
||||
The KEM exchange is identical for first and subsequent sessions. The only difference between sessions is how the invitation is delivered (QR code vs multicast) and whether TLS fingerprints are stored for the first time or verified against known pairings.
|
||||
|
||||
`updateKnownHost` (called in `prepareHostSession` on the controller) updates the stored host DH public key (`hostDhPubKey` in `KnownHostPairing`) - this is used for encrypting multicast announcements in subsequent sessions, not for KEM.
|
||||
|
||||
**Key rotation and `prevDhPrivKey`**: when the host updates its DH key pair for a new session, it retains the previous private key in `RCCtrlPairing.prevDhPrivKey`. This is critical for multicast - during the transition window, the controller may send announcements encrypted with the old public key. `findRCCtrlPairing` tries decryption with both the current and previous DH keys. Without this fallback, key rotation would break multicast discovery.
|
||||
|
||||
---
|
||||
|
||||
## Multicast discovery
|
||||
|
||||
**Source**: [RemoteControl/Client.hs](../../src/Simplex/RemoteControl/Client.hs), [RemoteControl/Invitation.hs](../../src/Simplex/RemoteControl/Invitation.hs), [RemoteControl/Discovery.hs](../../src/Simplex/RemoteControl/Discovery.hs)
|
||||
|
||||
For subsequent sessions (after initial QR pairing), the controller announces its presence via UDP multicast so the host can connect without scanning a new QR code. The flow spans `Client.announceRC`, `Client.discoverRCCtrl`, `Client.findRCCtrlPairing`, `Invitation.signInvitation`/`verifySignedInvitation`, and `Discovery.withListener`/`withSender`.
|
||||
|
||||
**Announcement creation** (`announceRC`):
|
||||
|
||||
1. The invitation is signed with a dual-signature chain: the session key signs the invitation URI, then the identity key signs the concatenation `URI + "&ssig=" + sessionSignature`. This chain means a compromised session key alone cannot forge a valid identity-signed announcement - the identity key must also be compromised.
|
||||
2. The signed invitation is encrypted with a DH shared secret between the host's known DH public key and the controller's ephemeral DH private key.
|
||||
3. The encrypted packet is padded to 900 bytes (privacy: all announcements are indistinguishable by size).
|
||||
4. Sent 60 times at 1-second intervals to multicast group `224.0.0.251:5227`.
|
||||
5. Runs as a cancellable async task - cancelled in `connectRCHost` after `prepareHostSession` returns, once the session is established.
|
||||
|
||||
**Listener and discovery** (`discoverRCCtrl`):
|
||||
|
||||
1. Host calls `joinMulticast` to subscribe to the multicast group. A shared `TMVar Int` counter tracks active listeners - OS-level `IP_ADD_MEMBERSHIP` is only issued on 0→1 transition, `IP_DROP_MEMBERSHIP` on 1→0. This prevents duplicate syscalls when multiple listeners are active.
|
||||
2. For each received packet, `findRCCtrlPairing` iterates over known pairings and tries decryption with the current DH key, falling back to `prevDhPrivKey` if present.
|
||||
3. After successful decryption, the invitation's `dh` field is verified against the announcement's `dhPubKey` to prevent relay attacks.
|
||||
4. The source IP address is checked against the invitation's `host` field - prevents re-broadcasting a legitimate announcement from a different host.
|
||||
5. Dual signatures are verified: session signature first, then identity signature.
|
||||
6. 30-second timeout on the entire discovery process (`RCENotDiscovered` on expiry).
|
||||
|
||||
---
|
||||
|
||||
## Block framing and padding
|
||||
|
||||
**Source**: [RemoteControl/Client.hs](../../src/Simplex/RemoteControl/Client.hs), [RemoteControl/Types.hs](../../src/Simplex/RemoteControl/Types.hs)
|
||||
|
||||
XRCP uses three padding sizes at different protocol layers:
|
||||
|
||||
- **16,384 bytes** - XRCP block size for all session messages (hello, commands, responses). Matches SMP's block size. Hides message content size variation within the TLS session.
|
||||
- **12,288 bytes** - hello body padding within the 16,384-byte block, after encryption overhead.
|
||||
- **900 bytes** - multicast announcement padding. Constrained by typical UDP MTU to avoid fragmentation.
|
||||
|
||||
All padding uses the standard `pad`/`unPad` format (2-byte length prefix + `#` fill). The fixed sizes ensure that an observer monitoring network traffic cannot distinguish different XRCP operations by packet size.
|
||||
@@ -1,179 +0,0 @@
|
||||
# Client Architecture
|
||||
|
||||
SimpleX clients are the Layer 2 libraries that connect to routers. This document shows their internal architecture: component topology and command processing flows.
|
||||
|
||||
For deployment and usage, see [docs/CLIENT.md](../docs/CLIENT.md). For protocol specifications, see [SMP](../protocol/simplex-messaging.md), [XFTP](../protocol/xftp.md), [Push Notifications](../protocol/push-notifications.md).
|
||||
|
||||
---
|
||||
|
||||
## SMP Client (ProtocolClient)
|
||||
|
||||
**Four threads**: Send and receive threads are separate to allow backpressure - a slow receiver doesn't block sending. The process thread decouples parsing from delivery, preventing a slow consumer from stalling the receive loop. The monitor thread provides application-level keepalive beyond TCP - detecting protocol-level stalls. See [transport.md](topics/transport.md#connection-management).
|
||||
|
||||
**Correlation ID lifecycle**: IDs are generated before send and removed on response OR timeout. Removal on timeout prevents unbounded growth of `sentCommands` when the router is unresponsive.
|
||||
|
||||
**Module specs**: [Client](modules/Simplex/Messaging/Client.md) · [Protocol](modules/Simplex/Messaging/Protocol.md) · [Transport](modules/Simplex/Messaging/Transport.md) · [Crypto](modules/Simplex/Messaging/Crypto.md)
|
||||
|
||||
Generic protocol client used for both SMP and NTF connections. Manages a single TLS connection with multiplexed command/response matching via correlation IDs.
|
||||
|
||||
### SMP Client components
|
||||
|
||||

|
||||
|
||||
### Command/result flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Caller<br>(Agent / router)
|
||||
|
||||
box ProtocolClient
|
||||
participant SC as sentCommands<br>(TMap CorrId Request)
|
||||
participant SQ as sndQ
|
||||
participant S as send thread
|
||||
participant R as receive thread
|
||||
participant RQ as rcvQ
|
||||
participant P as process thread
|
||||
end
|
||||
|
||||
participant Router as SMP Router
|
||||
|
||||
C->>SC: mkTransmission<br/>(generate CorrId, create Request<br/>with empty responseVar)
|
||||
C->>SQ: write (Request, encoded command)
|
||||
S->>SQ: read
|
||||
S-->>S: check pending flag (drop if timed out)
|
||||
S->>Router: tPutLog (transmit bytes)
|
||||
|
||||
Router->>R: tGetClient (receive batch)
|
||||
R->>RQ: write transmissions
|
||||
|
||||
P->>RQ: read
|
||||
P->>SC: lookup CorrId
|
||||
alt command response (CorrId matches, pending)
|
||||
P->>SC: remove CorrId + fill responseVar (TMVar)
|
||||
else expired response (CorrId matches, already timed out)
|
||||
P->>C: write to msgQ (STResponse)
|
||||
else server event (empty CorrId)
|
||||
P->>C: write to msgQ (STEvent)
|
||||
end
|
||||
|
||||
Note over C: getResponse: takeTMVar with timeout
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## SMPClientAgent
|
||||
|
||||
**Dual consumers**: Used by both SMP router (for proxy connections to relays) and NTF router (for NSUB subscriptions to SMP routers). Same connection pooling and reconnection logic, different command sets.
|
||||
|
||||
**Session ID gating**: Subscription responses are validated against the current TLS session ID. A response from a stale session (connection dropped and reconnected between send and receive) is discarded rather than corrupting state. See [infrastructure.md](agent/infrastructure.md#subscription-tracking).
|
||||
|
||||
**Module specs**: [Client Agent](modules/Simplex/Messaging/Client/Agent.md)
|
||||
|
||||
Connection manager that multiplexes multiple ProtocolClient connections. Tracks subscriptions, handles reconnection with backoff, and forwards server messages and connection events upward. Used by SMP router (proxying) and NTF router (subscriptions).
|
||||
|
||||
### SMPClientAgent components
|
||||
|
||||

|
||||
|
||||
### Connection lifecycle
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Consumer<br>(router / app)
|
||||
|
||||
box
|
||||
participant A as SMPClientAgent
|
||||
participant PC as ProtocolClient
|
||||
end
|
||||
|
||||
participant Router as SMP Router
|
||||
|
||||
C->>A: getSMPServerClient'' (server)
|
||||
alt client exists in smpClients
|
||||
A->>C: return existing client
|
||||
else no client
|
||||
A->>PC: connectClient (create new ProtocolClient)
|
||||
PC->>Router: TLS handshake
|
||||
A->>A: register disconnect handler
|
||||
A->>C: return new client
|
||||
end
|
||||
|
||||
C->>A: subscribeQueuesNtfs (queueIds)
|
||||
A->>A: add to pendingQueueSubs
|
||||
A->>PC: sendProtocolCommands (SUB batch)
|
||||
PC->>Router: SUB commands
|
||||
Router->>PC: OK responses
|
||||
A->>A: move pending → activeQueueSubs
|
||||
A->>C: CASubscribed (via agentQ)
|
||||
|
||||
Note over Router: connection drops
|
||||
|
||||
PC->>A: disconnect handler fires
|
||||
A->>A: filter by SessionId (only remove subs matching disconnected session)
|
||||
A->>A: move active → pending (queue subs + service subs)
|
||||
A->>C: CAServiceDisconnected (via agentQ, if service sub existed)
|
||||
A->>C: CADisconnected (via agentQ, if queue subs existed)
|
||||
A->>A: spawn smpSubWorker (retry with backoff)
|
||||
A->>PC: reconnect + resubscribe pending subs
|
||||
A->>C: CAConnected + CASubscribed (via agentQ)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## XFTP Client
|
||||
|
||||
**No subscriptions**: File operations complete independently - no persistent server-side state to track. This allows XFTPClient to be a thin wrapper with no threads of its own.
|
||||
|
||||
**Module specs**: [Client](modules/Simplex/FileTransfer/Client.md) · [Protocol](modules/Simplex/FileTransfer/Protocol.md) · [HTTP/2 Client](modules/Simplex/Messaging/Transport/HTTP2/Client.md)
|
||||
|
||||
Stateless wrapper around HTTP2Client. XFTPClient adds no threads of its own. Serialization and multiplexing happen inside HTTP2Client's internal request queue and process thread.
|
||||
|
||||
### XFTP Client components
|
||||
|
||||

|
||||
|
||||
### Packet delivery flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Caller<br>(Agent / app)
|
||||
participant X as XFTPClient
|
||||
participant H as HTTP2Client
|
||||
participant Router as XFTP Router
|
||||
|
||||
C->>X: createXFTPChunk (FNEW)
|
||||
X->>H: HTTP/2 POST (encoded command)
|
||||
H->>Router: request
|
||||
Router->>H: response (sender ID + recipient IDs)
|
||||
H->>X: decode response
|
||||
X->>C: return IDs
|
||||
|
||||
C->>X: uploadXFTPChunk (FPUT + file data)
|
||||
X->>H: HTTP/2 POST (streaming body)
|
||||
H->>Router: request with file stream
|
||||
Router->>H: OK
|
||||
H->>X: OK
|
||||
X->>C: return OK
|
||||
|
||||
C->>X: downloadXFTPChunk (FGET + ephemeral DH key)
|
||||
X->>H: HTTP/2 POST (command)
|
||||
H->>Router: request
|
||||
Router->>H: streaming response (server DH key + nonce + encrypted data)
|
||||
H->>X: streaming body
|
||||
X->>X: compute DH secret, decrypt + save to file
|
||||
X->>C: return ()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## NTF Client
|
||||
|
||||
**Module specs**: [Client](modules/Simplex/Messaging/Notifications/Client.md) · [Protocol](modules/Simplex/Messaging/Notifications/Protocol.md)
|
||||
|
||||
Type alias for ProtocolClient - same architecture as SMP Client:
|
||||
|
||||
```haskell
|
||||
type NtfClient = ProtocolClient NTFVersion ErrorType NtfResponse
|
||||
```
|
||||
|
||||
Same threads (send, receive, process, monitor), same queues (sndQ, rcvQ, sentCommands, msgQ), same command/response flow. Different command types: TNEW, TVFY, TCHK, TRPL, TDEL, TCRN, SNEW, SCHK, SDEL, PING.
|
||||
@@ -1,288 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 960 780" font-family="monospace" font-size="12">
|
||||
<defs>
|
||||
<marker id="arr" viewBox="0 0 10 10" refX="9" refY="5"
|
||||
markerWidth="6" markerHeight="6" orient="auto-start-reverse">
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill="#333" />
|
||||
</marker>
|
||||
<marker id="arr-g" viewBox="0 0 10 10" refX="9" refY="5"
|
||||
markerWidth="6" markerHeight="6" orient="auto-start-reverse">
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill="#999" />
|
||||
</marker>
|
||||
<marker id="arr-x" viewBox="0 0 10 10" refX="9" refY="5"
|
||||
markerWidth="6" markerHeight="6" orient="auto-start-reverse">
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill="#c62828" />
|
||||
</marker>
|
||||
</defs>
|
||||
|
||||
<!-- ===== ROW 0: APPLICATION (external) ===== -->
|
||||
<rect x="350" y="10" width="180" height="34" rx="4"
|
||||
fill="#fce8e6" stroke="#ea4335" />
|
||||
<text x="440" y="32" text-anchor="middle">Application</text>
|
||||
|
||||
<!-- subQ queue box (right of Application) -->
|
||||
<rect x="560" y="10" width="120" height="34" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="620" y="25" text-anchor="middle" font-weight="bold">subQ</text>
|
||||
<text x="620" y="39" text-anchor="middle" font-size="9">(TBQueue)</text>
|
||||
|
||||
<!-- subQ -> Application -->
|
||||
<line x1="560" y1="27" x2="532" y2="27"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- ===== subQ BUS: three stubs up from columns → horizontal → up → into subQ ===== -->
|
||||
|
||||
<!-- Three vertical stubs from column tops up to bus at y=142 -->
|
||||
<line x1="172" y1="158" x2="172" y2="142" stroke="#333" />
|
||||
<line x1="483" y1="158" x2="483" y2="142" stroke="#333" />
|
||||
<line x1="788" y1="158" x2="788" y2="142" stroke="#333" />
|
||||
|
||||
<!-- Bus: horizontal across, right margin up, into subQ -->
|
||||
<polyline points="172,142 940,142 940,27 682,27"
|
||||
fill="none" stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- ===== App -> API arrows (down) ===== -->
|
||||
<line x1="400" y1="44" x2="170" y2="76"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
<line x1="440" y1="44" x2="480" y2="76"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
<line x1="480" y1="44" x2="786" y2="76"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
|
||||
<!-- ===== ROW 1: API FUNCTIONS ===== -->
|
||||
|
||||
<!-- SMP API -->
|
||||
<rect x="25" y="76" width="290" height="50" rx="4"
|
||||
fill="#f4f4f4" stroke="#999" />
|
||||
<text x="170" y="94" text-anchor="middle" font-size="10">sendMessage, createConnection</text>
|
||||
<text x="170" y="109" text-anchor="middle" font-size="10">joinConnection, subscribe...</text>
|
||||
|
||||
<!-- XFTP API -->
|
||||
<rect x="335" y="76" width="290" height="50" rx="4"
|
||||
fill="#f4f4f4" stroke="#999" />
|
||||
<text x="480" y="94" text-anchor="middle" font-size="10">xftpSendFile</text>
|
||||
<text x="480" y="109" text-anchor="middle" font-size="10">xftpReceiveFile...</text>
|
||||
|
||||
<!-- NTF API -->
|
||||
<rect x="641" y="76" width="290" height="50" rx="4"
|
||||
fill="#f4f4f4" stroke="#999" />
|
||||
<text x="786" y="94" text-anchor="middle" font-size="10">registerNtfToken</text>
|
||||
<text x="786" y="109" text-anchor="middle" font-size="10">toggleConnectionNtfs...</text>
|
||||
|
||||
<!-- ===== ROW 2: THREE PROTOCOL COLUMNS ===== -->
|
||||
|
||||
<!-- ====== SMP COLUMN ====== -->
|
||||
<rect x="20" y="158" width="305" height="260" rx="6"
|
||||
fill="none" stroke="#888" stroke-dasharray="6,3" />
|
||||
<text x="30" y="174" fill="#888" font-size="10">SMP</text>
|
||||
|
||||
<!-- msgQ queue box (inside SMP column, left side) -->
|
||||
<rect x="35" y="180" width="110" height="30" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="90" y="194" text-anchor="middle" font-weight="bold" font-size="10">msgQ</text>
|
||||
<text x="90" y="206" text-anchor="middle" font-size="8">(TBQueue)</text>
|
||||
|
||||
<!-- subscriber (green, singleton, right side) -->
|
||||
<rect x="160" y="180" width="150" height="44" rx="4"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="235" y="198" text-anchor="middle">subscriber</text>
|
||||
<text x="235" y="212" text-anchor="middle" font-size="9" fill="#666">(reads msgQ)</text>
|
||||
|
||||
<!-- msgQ -> subscriber -->
|
||||
<line x1="147" y1="198" x2="158" y2="198"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- SMP worker pools label -->
|
||||
<text x="35" y="246" fill="#888" font-size="9">worker pools (on-demand, one per queue / conn+server / session)</text>
|
||||
|
||||
<!-- delivery worker -->
|
||||
<rect x="35" y="256" width="128" height="38" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="99" y="273" text-anchor="middle" font-size="11">delivery</text>
|
||||
<text x="99" y="286" text-anchor="middle" font-size="8" fill="#666">(per send queue)</text>
|
||||
|
||||
<!-- asyncCmd worker -->
|
||||
<rect x="175" y="256" width="135" height="38" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="242" y="273" text-anchor="middle" font-size="11">asyncCmd</text>
|
||||
<text x="242" y="286" text-anchor="middle" font-size="8" fill="#666">(per conn + server)</text>
|
||||
|
||||
<!-- smpSub worker -->
|
||||
<rect x="35" y="308" width="128" height="38" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="99" y="325" text-anchor="middle" font-size="11">smpSub</text>
|
||||
<text x="99" y="338" text-anchor="middle" font-size="8" fill="#666">(per session)</text>
|
||||
|
||||
<!-- ====== XFTP COLUMN ====== -->
|
||||
<rect x="335" y="158" width="296" height="260" rx="6"
|
||||
fill="none" stroke="#888" stroke-dasharray="6,3" />
|
||||
<text x="345" y="174" fill="#888" font-size="10">XFTP</text>
|
||||
|
||||
<!-- XFTP worker pools label -->
|
||||
<text x="345" y="246" fill="#888" font-size="9">worker pools (on-demand, one per server)</text>
|
||||
|
||||
<!-- xftpRcv worker -->
|
||||
<rect x="350" y="256" width="130" height="38" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="415" y="273" text-anchor="middle" font-size="11">xftpRcv</text>
|
||||
<text x="415" y="286" text-anchor="middle" font-size="8" fill="#666">(per server + local)</text>
|
||||
|
||||
<!-- xftpSnd worker -->
|
||||
<rect x="490" y="256" width="130" height="38" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="555" y="273" text-anchor="middle" font-size="11">xftpSnd</text>
|
||||
<text x="555" y="286" text-anchor="middle" font-size="8" fill="#666">(per server + local)</text>
|
||||
|
||||
<!-- xftpDel worker -->
|
||||
<rect x="350" y="308" width="130" height="38" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="415" y="325" text-anchor="middle" font-size="11">xftpDel</text>
|
||||
<text x="415" y="338" text-anchor="middle" font-size="8" fill="#666">(per server)</text>
|
||||
|
||||
<!-- ====== NTF COLUMN ====== -->
|
||||
<rect x="641" y="158" width="295" height="260" rx="6"
|
||||
fill="none" stroke="#888" stroke-dasharray="6,3" />
|
||||
<text x="651" y="174" fill="#888" font-size="10">NTF</text>
|
||||
|
||||
<!-- ntfSubQ queue box (inside NTF column, left side) -->
|
||||
<rect x="656" y="180" width="88" height="30" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="700" y="194" text-anchor="middle" font-weight="bold" font-size="10">ntfSubQ</text>
|
||||
<text x="700" y="206" text-anchor="middle" font-size="8">(TBQueue)</text>
|
||||
|
||||
<!-- ntfSupervisor (green, singleton, right side) -->
|
||||
<rect x="756" y="180" width="168" height="44" rx="4"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="840" y="198" text-anchor="middle">ntfSupervisor</text>
|
||||
<text x="840" y="212" text-anchor="middle" font-size="9" fill="#666">(reads ntfSubQ)</text>
|
||||
|
||||
<!-- ntfSubQ -> ntfSupervisor -->
|
||||
<line x1="746" y1="198" x2="754" y2="198"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- NTF API -> ntfSubQ -->
|
||||
<line x1="700" y1="126" x2="700" y2="178"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- NTF worker pools label -->
|
||||
<text x="656" y="246" fill="#888" font-size="9">worker pools (on-demand, one per server)</text>
|
||||
|
||||
<!-- ntfWorkers -->
|
||||
<rect x="656" y="256" width="125" height="38" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="718" y="273" text-anchor="middle" font-size="11">ntfWorkers</text>
|
||||
<text x="718" y="286" text-anchor="middle" font-size="8" fill="#666">(per NTF server)</text>
|
||||
|
||||
<!-- ntfSMP worker -->
|
||||
<rect x="793" y="256" width="128" height="38" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="857" y="273" text-anchor="middle" font-size="11">ntfSMP</text>
|
||||
<text x="857" y="286" text-anchor="middle" font-size="8" fill="#666">(per SMP server)</text>
|
||||
|
||||
<!-- ntfTknDel worker -->
|
||||
<rect x="656" y="308" width="125" height="38" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="718" y="325" text-anchor="middle" font-size="11">ntfTknDel</text>
|
||||
<text x="718" y="338" text-anchor="middle" font-size="8" fill="#666">(per NTF server)</text>
|
||||
|
||||
<!-- ===== CROSS-PROTOCOL: asyncCmd -> ntfSubQ (ICQDelete) ===== -->
|
||||
<polyline points="310,272 500,195 654,195"
|
||||
fill="none" stroke="#c62828" stroke-dasharray="4,3" marker-end="url(#arr-x)" />
|
||||
<text x="420" y="218" font-size="9" fill="#c62828">ntfSubQ (queue rotation)</text>
|
||||
|
||||
<!-- ===== SHARED SINGLETON THREADS ===== -->
|
||||
<text x="30" y="448" fill="#888" font-size="9">shared singletons (all green run in raceAny_)</text>
|
||||
<rect x="320" y="436" width="135" height="24" rx="4"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="387" y="452" text-anchor="middle" font-size="10">cleanupManager</text>
|
||||
|
||||
<rect x="470" y="436" width="135" height="24" rx="4"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="537" y="452" text-anchor="middle" font-size="10">logServersStats</text>
|
||||
|
||||
<!-- ===== CROSS-PROTOCOL: ntfSMP -> smpClients ===== -->
|
||||
<polyline points="857,294 857,482 170,482 170,558"
|
||||
fill="none" stroke="#c62828" stroke-dasharray="4,3" marker-end="url(#arr-x)" />
|
||||
<text x="500" y="478" font-size="9" fill="#c62828">ntfSMP uses smpClients</text>
|
||||
|
||||
<!-- ===== ROW 3: CENTRAL STATE ===== -->
|
||||
<rect x="25" y="494" width="450" height="46" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="250" y="514" text-anchor="middle" font-weight="bold">Store</text>
|
||||
<text x="250" y="530" text-anchor="middle" font-size="10">(SQLite / Postgres)</text>
|
||||
|
||||
<rect x="490" y="494" width="445" height="46" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="712" y="514" text-anchor="middle" font-weight="bold">Operation State</text>
|
||||
<text x="712" y="530" text-anchor="middle" font-size="10">(5-op suspension cascade)</text>
|
||||
|
||||
<!-- store access: representative dashed line -->
|
||||
<line x1="242" y1="294" x2="220" y2="492"
|
||||
stroke="#555" stroke-dasharray="3,2" marker-end="url(#arr)" />
|
||||
<text x="248" y="400" font-size="9" fill="#555">store</text>
|
||||
|
||||
<!-- ===== ROW 4: PROTOCOL CLIENT POOLS ===== -->
|
||||
<rect x="25" y="558" width="290" height="46" rx="4"
|
||||
fill="#fce8e6" stroke="#ea4335" />
|
||||
<text x="170" y="578" text-anchor="middle">smpClients</text>
|
||||
<text x="170" y="594" text-anchor="middle" font-size="9" fill="#666">(TMap SMPTransportSession)</text>
|
||||
|
||||
<rect x="335" y="558" width="290" height="46" rx="4"
|
||||
fill="#fce8e6" stroke="#ea4335" />
|
||||
<text x="480" y="578" text-anchor="middle">xftpClients</text>
|
||||
<text x="480" y="594" text-anchor="middle" font-size="9" fill="#666">(TMap XFTPTransportSession)</text>
|
||||
|
||||
<rect x="641" y="558" width="290" height="46" rx="4"
|
||||
fill="#fce8e6" stroke="#ea4335" />
|
||||
<text x="786" y="578" text-anchor="middle">ntfClients</text>
|
||||
<text x="786" y="594" text-anchor="middle" font-size="9" fill="#666">(TMap NtfTransportSession)</text>
|
||||
|
||||
<!-- ===== ROW 5: EXTERNAL ROUTERS ===== -->
|
||||
<text x="170" y="630" text-anchor="middle" font-size="9" fill="#999">SMP Routers</text>
|
||||
<line x1="170" y1="604" x2="170" y2="620"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
|
||||
<text x="480" y="630" text-anchor="middle" font-size="9" fill="#999">XFTP Routers</text>
|
||||
<line x1="480" y1="604" x2="480" y2="620"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
|
||||
<text x="786" y="630" text-anchor="middle" font-size="9" fill="#999">NTF Routers</text>
|
||||
<line x1="786" y1="604" x2="786" y2="620"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
|
||||
<!-- ===== smpClients -> msgQ (left margin) ===== -->
|
||||
<polyline points="25,581 8,581 8,195 33,195"
|
||||
fill="none" stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- ===== LEGEND ===== -->
|
||||
<rect x="20" y="654" width="920" height="60" rx="4"
|
||||
fill="none" stroke="#ddd" />
|
||||
|
||||
<rect x="35" y="668" width="14" height="11" rx="2"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="55" y="678" font-size="10">on-demand worker</text>
|
||||
|
||||
<rect x="185" y="668" width="14" height="11" rx="2"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="205" y="678" font-size="10">singleton thread</text>
|
||||
|
||||
<rect x="325" y="668" width="14" height="11" rx="2"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="345" y="678" font-size="10">queue / state</text>
|
||||
|
||||
<rect x="445" y="668" width="14" height="11" rx="2"
|
||||
fill="#fce8e6" stroke="#ea4335" />
|
||||
<text x="465" y="678" font-size="10">external connection</text>
|
||||
|
||||
<rect x="595" y="668" width="14" height="11" rx="2"
|
||||
fill="#f4f4f4" stroke="#999" />
|
||||
<text x="615" y="678" font-size="10">API entry point</text>
|
||||
|
||||
<line x1="730" y1="673" x2="770" y2="673"
|
||||
stroke="#c62828" stroke-dasharray="4,3" marker-end="url(#arr-x)" />
|
||||
<text x="780" y="677" font-size="10">cross-protocol</text>
|
||||
|
||||
<text x="35" y="704" font-size="10" fill="#666">
|
||||
Solid arrows: TBQueue flow. Dashed grey: store access. Dashed red: cross-protocol link. All threads and pools write events to subQ.
|
||||
</text>
|
||||
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 13 KiB |
@@ -1,210 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 830 610" font-family="monospace" font-size="12">
|
||||
<defs>
|
||||
<marker id="arr" viewBox="0 0 10 10" refX="9" refY="5"
|
||||
markerWidth="6" markerHeight="6" orient="auto-start-reverse">
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill="#333" />
|
||||
</marker>
|
||||
<marker id="arr-g" viewBox="0 0 10 10" refX="9" refY="5"
|
||||
markerWidth="6" markerHeight="6" orient="auto-start-reverse">
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill="#999" />
|
||||
</marker>
|
||||
</defs>
|
||||
|
||||
<!-- ===== PER-CLIENT GROUP (left) ===== -->
|
||||
<rect x="25" y="40" width="300" height="170" rx="6"
|
||||
fill="none" stroke="#888" stroke-dasharray="6,3" />
|
||||
<text x="35" y="55" fill="#888" font-size="10">per client (raceAny_)</text>
|
||||
|
||||
<!-- network in -->
|
||||
<text x="13" y="78" font-size="9" fill="#999">net</text>
|
||||
<line x1="12" y1="82" x2="40" y2="82"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
|
||||
<!-- receive -->
|
||||
<rect x="42" y="66" width="78" height="34" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="81" y="88" text-anchor="middle">receive</text>
|
||||
|
||||
<!-- rcvQ -->
|
||||
<line x1="120" y1="83" x2="158" y2="83"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
<text x="139" y="77" text-anchor="middle" font-size="10" fill="#555">rcvQ</text>
|
||||
|
||||
<!-- client -->
|
||||
<rect x="160" y="66" width="78" height="34" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="199" y="88" text-anchor="middle">client</text>
|
||||
|
||||
<!-- sndQ -->
|
||||
<line x1="238" y1="83" x2="268" y2="83"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
<text x="253" y="77" text-anchor="middle" font-size="10" fill="#555">sndQ</text>
|
||||
|
||||
<!-- send -->
|
||||
<rect x="270" y="66" width="48" height="34" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="294" y="88" text-anchor="middle">send</text>
|
||||
|
||||
<!-- network out -->
|
||||
<text x="326" y="88" font-size="9" fill="#999">net</text>
|
||||
|
||||
<!-- commands label -->
|
||||
<text x="52" y="120" font-size="10" fill="#666">TNEW, TVFY, TCHK, TRPL, TDEL, TCRN</text>
|
||||
<text x="52" y="134" font-size="10" fill="#666">SNEW, SCHK, SDEL, PING</text>
|
||||
|
||||
<!-- client -> store (down) -->
|
||||
<line x1="199" y1="100" x2="199" y2="278"
|
||||
stroke="#555" stroke-dasharray="3,2" marker-end="url(#arr)" />
|
||||
<text x="211" y="230" font-size="10" fill="#555">store</text>
|
||||
|
||||
<!-- client -> pushQ (PNVerification on TNEW/TRPL) -->
|
||||
<line x1="160" y1="100" x2="50" y2="388"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
<text x="62" y="260" font-size="9" fill="#555">pushQ</text>
|
||||
|
||||
<!-- ===== SMP CLIENT AGENT GROUP (right) ===== -->
|
||||
<rect x="370" y="40" width="435" height="220" rx="6"
|
||||
fill="none" stroke="#888" stroke-dasharray="6,3" />
|
||||
<text x="380" y="55" fill="#888" font-size="10">SMP Client Agent (connects to SMP routers)</text>
|
||||
|
||||
<!-- SMP routers external label -->
|
||||
<text x="620" y="38" font-size="9" fill="#999">SMP routers</text>
|
||||
<line x1="620" y1="40" x2="620" y2="62"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
|
||||
<!-- SMPClientAgent -->
|
||||
<rect x="530" y="64" width="220" height="34" rx="4"
|
||||
fill="#fce8e6" stroke="#ea4335" />
|
||||
<text x="640" y="86" text-anchor="middle">SMPClientAgent</text>
|
||||
|
||||
<!-- msgQ arrow: SMPClientAgent -> receiveSMP -->
|
||||
<line x1="580" y1="98" x2="510" y2="128"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
<text x="530" y="112" font-size="10" fill="#555">msgQ</text>
|
||||
|
||||
<!-- agentQ arrow: SMPClientAgent -> receiveAgent -->
|
||||
<line x1="690" y1="98" x2="690" y2="128"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
<text x="702" y="117" font-size="10" fill="#555">agentQ</text>
|
||||
|
||||
<!-- ntfSubscriber/receiveSMP -->
|
||||
<rect x="390" y="130" width="195" height="34" rx="4"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="487" y="152" text-anchor="middle" font-size="11">ntfSubscriber/receiveSMP</text>
|
||||
|
||||
<!-- ntfSubscriber/receiveAgent -->
|
||||
<rect x="605" y="130" width="185" height="34" rx="4"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="697" y="152" text-anchor="middle" font-size="11">receiveAgent</text>
|
||||
|
||||
<!-- race_ label between them -->
|
||||
<text x="597" y="144" font-size="9" fill="#888">race_</text>
|
||||
|
||||
<!-- receiveSMP -> pushQ (down) -->
|
||||
<line x1="487" y1="164" x2="487" y2="195"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
<text x="500" y="183" font-size="10" fill="#555">pushQ</text>
|
||||
|
||||
<!-- receiveAgent -> store (down) -->
|
||||
<line x1="697" y1="164" x2="697" y2="278"
|
||||
stroke="#555" stroke-dasharray="3,2" marker-end="url(#arr)" />
|
||||
<text x="709" y="230" font-size="10" fill="#555">store</text>
|
||||
|
||||
<!-- per-SMP-server subscriber -->
|
||||
<rect x="390" y="200" width="200" height="44" rx="4"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="490" y="219" text-anchor="middle" font-size="11">runSMPSubscriber</text>
|
||||
<text x="490" y="236" text-anchor="middle" font-size="9" fill="#666">(one per SMP router)</text>
|
||||
|
||||
<!-- subscriberSubQ label -->
|
||||
<text x="408" y="196" font-size="9" fill="#555">subscriberSubQ</text>
|
||||
|
||||
<!-- ===== CENTRAL STORE ===== -->
|
||||
<rect x="100" y="280" width="620" height="50" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="400" y="301" text-anchor="middle" font-weight="bold">tokens / subscriptions / tokenLastNtfs</text>
|
||||
<text x="400" y="319" text-anchor="middle" font-size="10">(PostgreSQL)</text>
|
||||
|
||||
<!-- ===== PUSH DELIVERY ===== -->
|
||||
<rect x="25" y="355" width="780" height="90" rx="6"
|
||||
fill="none" stroke="#888" stroke-dasharray="6,3" />
|
||||
<text x="35" y="370" fill="#888" font-size="10">push delivery pipeline</text>
|
||||
|
||||
<!-- pushQ hub: store -> ntfPush -->
|
||||
<line x1="400" y1="330" x2="400" y2="388"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
<text x="412" y="365" font-size="10" fill="#555">pushQ</text>
|
||||
|
||||
<!-- ntfPush -->
|
||||
<rect x="350" y="390" width="110" height="34" rx="4"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="405" y="412" text-anchor="middle">ntfPush</text>
|
||||
|
||||
<!-- APNS provider -->
|
||||
<line x1="460" y1="407" x2="528" y2="407"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
<rect x="530" y="390" width="135" height="34" rx="4"
|
||||
fill="#fce8e6" stroke="#ea4335" />
|
||||
<text x="597" y="412" text-anchor="middle">APNS provider</text>
|
||||
|
||||
<!-- periodicNtfsThread -->
|
||||
<rect x="45" y="390" width="175" height="34" rx="4"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="132" y="412" text-anchor="middle" font-size="11">periodicNtfsThread</text>
|
||||
|
||||
<!-- periodic -> pushQ -->
|
||||
<line x1="220" y1="407" x2="348" y2="407"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
<text x="284" y="401" font-size="10" fill="#555">pushQ</text>
|
||||
|
||||
<!-- periodic reads store -->
|
||||
<line x1="132" y1="390" x2="132" y2="330"
|
||||
stroke="#555" stroke-dasharray="3,2" marker-end="url(#arr)" />
|
||||
<text x="117" y="365" font-size="9" fill="#555">reads</text>
|
||||
|
||||
<!-- ===== OPTIONAL ===== -->
|
||||
<rect x="25" y="462" width="780" height="45" rx="6"
|
||||
fill="none" stroke="#bbb" stroke-dasharray="4,3" />
|
||||
<text x="35" y="477" fill="#bbb" font-size="10">optional</text>
|
||||
|
||||
<rect x="45" y="484" width="128" height="18" rx="3"
|
||||
fill="#f5f5f5" stroke="#bbb" />
|
||||
<text x="109" y="497" text-anchor="middle" font-size="9">logServerStats</text>
|
||||
|
||||
<rect x="190" y="484" width="108" height="18" rx="3"
|
||||
fill="#f5f5f5" stroke="#bbb" />
|
||||
<text x="244" y="497" text-anchor="middle" font-size="9">prometheus</text>
|
||||
|
||||
<rect x="315" y="484" width="108" height="18" rx="3"
|
||||
fill="#f5f5f5" stroke="#bbb" />
|
||||
<text x="369" y="497" text-anchor="middle" font-size="9">controlPort</text>
|
||||
|
||||
<rect x="440" y="484" width="108" height="18" rx="3"
|
||||
fill="#f5f5f5" stroke="#bbb" />
|
||||
<text x="494" y="497" text-anchor="middle" font-size="9">resubscribe</text>
|
||||
|
||||
<!-- ===== LEGEND ===== -->
|
||||
<rect x="25" y="525" width="780" height="55" rx="4"
|
||||
fill="none" stroke="#ddd" />
|
||||
|
||||
<rect x="40" y="540" width="14" height="11" rx="2"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="60" y="550" font-size="10">per-client thread</text>
|
||||
|
||||
<rect x="195" y="540" width="14" height="11" rx="2"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="215" y="550" font-size="10">singleton thread</text>
|
||||
|
||||
<rect x="350" y="540" width="14" height="11" rx="2"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="370" y="550" font-size="10">storage</text>
|
||||
|
||||
<rect x="445" y="540" width="14" height="11" rx="2"
|
||||
fill="#fce8e6" stroke="#ea4335" />
|
||||
<text x="465" y="550" font-size="10">external connection</text>
|
||||
|
||||
<text x="40" y="572" font-size="10" fill="#666">
|
||||
Solid arrows: TBQueue connections. Dashed: store access.
|
||||
</text>
|
||||
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 8.4 KiB |
@@ -1,143 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 740 400" font-family="monospace" font-size="12">
|
||||
<defs>
|
||||
<marker id="arr" viewBox="0 0 10 10" refX="9" refY="5"
|
||||
markerWidth="6" markerHeight="6" orient="auto-start-reverse">
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill="#333" />
|
||||
</marker>
|
||||
<marker id="arr-g" viewBox="0 0 10 10" refX="9" refY="5"
|
||||
markerWidth="6" markerHeight="6" orient="auto-start-reverse">
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill="#999" />
|
||||
</marker>
|
||||
</defs>
|
||||
|
||||
<!-- ===== CONSUMER (top left) ===== -->
|
||||
<text x="15" y="35" font-size="9" fill="#999">consumer</text>
|
||||
<text x="15" y="48" font-size="9" fill="#999">(NTF router /</text>
|
||||
<text x="15" y="61" font-size="9" fill="#999"> SMP proxy /</text>
|
||||
<text x="15" y="74" font-size="9" fill="#999"> application)</text>
|
||||
|
||||
<!-- ===== agentQ (upper right) ===== -->
|
||||
<rect x="360" y="15" width="210" height="35" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="465" y="33" text-anchor="middle" font-weight="bold">agentQ</text>
|
||||
<text x="465" y="46" text-anchor="middle" font-size="10">(TBQueue SMPClientAgentEvent)</text>
|
||||
|
||||
<!-- consumer <- agentQ -->
|
||||
<line x1="360" y1="32" x2="80" y2="32"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
|
||||
<!-- agentQ events note -->
|
||||
<text x="580" y="22" font-size="9" fill="#666">CAConnected / Disconnected</text>
|
||||
<text x="580" y="33" font-size="9" fill="#666">CASubscribed / SubError</text>
|
||||
<text x="580" y="44" font-size="9" fill="#666">CAServiceDisconnected</text>
|
||||
<text x="580" y="55" font-size="9" fill="#666">CAServiceSubscribed / SubError</text>
|
||||
<text x="580" y="66" font-size="9" fill="#666">CAServiceUnavailable</text>
|
||||
|
||||
<!-- ===== msgQ (upper left, below agentQ) ===== -->
|
||||
<rect x="130" y="55" width="195" height="35" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="227" y="73" text-anchor="middle" font-weight="bold">msgQ</text>
|
||||
<text x="227" y="86" text-anchor="middle" font-size="10">(TBQueue, server messages)</text>
|
||||
|
||||
<!-- consumer <- msgQ -->
|
||||
<line x1="130" y1="72" x2="80" y2="72"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
|
||||
<!-- ===== AGENT CORE ===== -->
|
||||
<rect x="25" y="100" width="700" height="82" rx="6"
|
||||
fill="none" stroke="#888" stroke-dasharray="6,3" />
|
||||
<text x="35" y="113" fill="#888" font-size="10">SMPClientAgent (connection manager)</text>
|
||||
|
||||
<!-- smpClients -->
|
||||
<rect x="45" y="120" width="170" height="48" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="130" y="141" text-anchor="middle" font-weight="bold">smpClients</text>
|
||||
<text x="130" y="159" text-anchor="middle" font-size="9">(TMap SMPServer SMPClientVar)</text>
|
||||
|
||||
<!-- smpClients -> msgQ (server messages forwarded up) -->
|
||||
<line x1="145" y1="120" x2="145" y2="92"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- smpSubWorkers -->
|
||||
<rect x="250" y="120" width="130" height="48" rx="4"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="315" y="141" text-anchor="middle" font-size="11">smpSubWorkers</text>
|
||||
<text x="315" y="159" text-anchor="middle" font-size="9" fill="#666">(one per server)</text>
|
||||
|
||||
<!-- workers -> smpClients (reconnect, dashed) -->
|
||||
<line x1="250" y1="144" x2="215" y2="144"
|
||||
stroke="#555" stroke-dasharray="3,2" marker-end="url(#arr)" />
|
||||
<text x="222" y="138" font-size="8" fill="#555">reconnect</text>
|
||||
|
||||
<!-- subscription tracking -->
|
||||
<rect x="415" y="118" width="275" height="56" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="552" y="134" text-anchor="middle" font-size="10">activeQueueSubs / pendingQueueSubs</text>
|
||||
<text x="552" y="146" text-anchor="middle" font-size="9" fill="#666">(TMap SMPServer (TMap QueueId ...))</text>
|
||||
<text x="552" y="159" text-anchor="middle" font-size="10">activeServiceSubs / pendingServiceSubs</text>
|
||||
<text x="552" y="171" text-anchor="middle" font-size="9" fill="#666">(TMap SMPServer (TVar (Maybe ...)))</text>
|
||||
|
||||
<!-- subscription state -> agentQ (connection events forwarded up) -->
|
||||
<line x1="465" y1="118" x2="465" y2="52"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- ===== PROTOCOL CLIENTS (bottom) ===== -->
|
||||
<rect x="25" y="198" width="700" height="72" rx="6"
|
||||
fill="none" stroke="#888" stroke-dasharray="6,3" />
|
||||
<text x="35" y="213" fill="#888" font-size="10">ProtocolClient connections (one per SMP Router)</text>
|
||||
|
||||
<!-- Client 1 -->
|
||||
<rect x="45" y="220" width="140" height="40" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="115" y="238" text-anchor="middle">ProtocolClient</text>
|
||||
<text x="115" y="253" text-anchor="middle" font-size="10">→ SMP Router A</text>
|
||||
|
||||
<!-- Client 2 -->
|
||||
<rect x="210" y="220" width="140" height="40" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="280" y="238" text-anchor="middle">ProtocolClient</text>
|
||||
<text x="280" y="253" text-anchor="middle" font-size="10">→ SMP Router B</text>
|
||||
|
||||
<!-- Client N -->
|
||||
<rect x="375" y="220" width="140" height="40" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="445" y="238" text-anchor="middle">ProtocolClient</text>
|
||||
<text x="445" y="253" text-anchor="middle" font-size="10">→ SMP Router N</text>
|
||||
|
||||
<!-- dots -->
|
||||
<text x="530" y="245" font-size="14" fill="#888">...</text>
|
||||
|
||||
<!-- smpClients -> clients -->
|
||||
<line x1="100" y1="168" x2="100" y2="218"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
<line x1="185" y1="168" x2="265" y2="218"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- ===== NOTES ===== -->
|
||||
<text x="45" y="292" font-size="10" fill="#666">getSMPServerClient'': get or create client</text>
|
||||
<text x="45" y="306" font-size="10" fill="#666">connectClient: create ProtocolClient, register disconnect handler</text>
|
||||
<text x="45" y="320" font-size="10" fill="#666">on disconnect: filter by SessionId, move active to pending, notify agentQ, spawn worker</text>
|
||||
<text x="45" y="334" font-size="10" fill="#666">worker: retry connect with backoff, resubscribe pending subs</text>
|
||||
<text x="45" y="348" font-size="10" fill="#666">subscribeQueuesNtfs / subscribeServiceNtfs: subscribe + track state</text>
|
||||
|
||||
<!-- ===== LEGEND ===== -->
|
||||
<rect x="25" y="365" width="700" height="30" rx="4"
|
||||
fill="none" stroke="#ddd" />
|
||||
|
||||
<rect x="40" y="374" width="14" height="11" rx="2"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="60" y="384" font-size="10">ProtocolClient</text>
|
||||
|
||||
<rect x="185" y="374" width="14" height="11" rx="2"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="205" y="384" font-size="10">state / queue</text>
|
||||
|
||||
<rect x="310" y="374" width="14" height="11" rx="2"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="330" y="384" font-size="10">background worker</text>
|
||||
|
||||
<text x="480" y="384" font-size="10" fill="#666">
|
||||
Solid arrows: TBQueue flow. Dashed: reconnection.
|
||||
</text>
|
||||
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 6.7 KiB |
@@ -1,170 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 380" font-family="monospace" font-size="12">
|
||||
<defs>
|
||||
<marker id="arr" viewBox="0 0 10 10" refX="9" refY="5"
|
||||
markerWidth="6" markerHeight="6" orient="auto-start-reverse">
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill="#333" />
|
||||
</marker>
|
||||
<marker id="arr-g" viewBox="0 0 10 10" refX="9" refY="5"
|
||||
markerWidth="6" markerHeight="6" orient="auto-start-reverse">
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill="#999" />
|
||||
</marker>
|
||||
</defs>
|
||||
|
||||
<!-- ===== PER-CONNECTION GROUP ===== -->
|
||||
<rect x="100" y="15" width="435" height="250" rx="6"
|
||||
fill="none" stroke="#888" stroke-dasharray="6,3" />
|
||||
<text x="110" y="30" fill="#888" font-size="10">per connection (raceAny_: any exit tears down all threads)</text>
|
||||
|
||||
<!-- ===== MONITOR (optional, above sndQ area) ===== -->
|
||||
<rect x="275" y="38" width="88" height="24" rx="4"
|
||||
fill="#f5f5f5" stroke="#bbb" />
|
||||
<text x="319" y="55" text-anchor="middle" font-size="11">monitor</text>
|
||||
<text x="370" y="54" font-size="9" fill="#bbb">optional</text>
|
||||
|
||||
<!-- monitor -> API (PING via sendProtocolCommand) -->
|
||||
<line x1="300" y1="62" x2="265" y2="74"
|
||||
stroke="#555" stroke-dasharray="3,2" marker-end="url(#arr)" />
|
||||
<text x="305" y="73" font-size="9" fill="#555">PING</text>
|
||||
|
||||
<!-- ===== ROW 1: SEND PATH ===== -->
|
||||
|
||||
<!-- caller label -->
|
||||
<text x="15" y="92" font-size="9" fill="#999">caller</text>
|
||||
<text x="10" y="105" font-size="9" fill="#999">(Agent /</text>
|
||||
<text x="10" y="118" font-size="9" fill="#999"> router)</text>
|
||||
|
||||
<!-- caller -> API -->
|
||||
<line x1="55" y1="98" x2="143" y2="98"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
|
||||
<!-- API functions block -->
|
||||
<rect x="145" y="76" width="165" height="42" rx="4"
|
||||
fill="#f4f4f4" stroke="#999" />
|
||||
<text x="227" y="93" text-anchor="middle" font-size="10">sendProtocolCommand</text>
|
||||
<text x="227" y="107" text-anchor="middle" font-size="10">mkTransmission</text>
|
||||
|
||||
<!-- API -> sndQ -->
|
||||
<line x1="310" y1="97" x2="335" y2="97"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- sndQ -->
|
||||
<rect x="337" y="82" width="88" height="34" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="381" y="98" text-anchor="middle" font-weight="bold">sndQ</text>
|
||||
<text x="381" y="111" text-anchor="middle" font-size="9">(TBQueue, 64)</text>
|
||||
|
||||
<!-- sndQ -> send -->
|
||||
<line x1="425" y1="97" x2="448" y2="97"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- send thread -->
|
||||
<rect x="450" y="84" width="60" height="28" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="480" y="103" text-anchor="middle">send</text>
|
||||
|
||||
<!-- send -> Router (exits per-connection box) -->
|
||||
<line x1="510" y1="97" x2="543" y2="97"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
|
||||
<!-- Router label (outside box) -->
|
||||
<text x="548" y="88" font-size="9" fill="#999">SMP</text>
|
||||
<text x="548" y="101" font-size="9" fill="#999">Router</text>
|
||||
<text x="548" y="114" font-size="9" fill="#999">(TLS)</text>
|
||||
|
||||
<!-- ===== ROW 2: RECEIVE PATH + SENTCOMMANDS ===== -->
|
||||
|
||||
<!-- API -> sentCommands (insert CorrId + Request) -->
|
||||
<line x1="227" y1="118" x2="227" y2="148"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
<text x="235" y="138" font-size="9" fill="#555">insert</text>
|
||||
|
||||
<!-- sentCommands -->
|
||||
<rect x="145" y="150" width="165" height="38" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="227" y="167" text-anchor="middle" font-weight="bold">sentCommands</text>
|
||||
<text x="227" y="182" text-anchor="middle" font-size="9">(TMap CorrId Request)</text>
|
||||
|
||||
<!-- sentCommands -> caller (responseVar, dashed) -->
|
||||
<line x1="145" y1="169" x2="55" y2="125"
|
||||
stroke="#555" stroke-dasharray="3,2" marker-end="url(#arr)" />
|
||||
<text x="62" y="152" font-size="9" fill="#555">responseVar</text>
|
||||
<text x="62" y="164" font-size="9" fill="#555">(TMVar)</text>
|
||||
|
||||
<!-- Router -> receive (enters per-connection box) -->
|
||||
<line x1="543" y1="163" x2="510" y2="163"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
|
||||
<!-- receive thread -->
|
||||
<rect x="450" y="150" width="60" height="28" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="480" y="169" text-anchor="middle">receive</text>
|
||||
|
||||
<!-- receive -> rcvQ -->
|
||||
<line x1="450" y1="163" x2="425" y2="163"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- rcvQ -->
|
||||
<rect x="337" y="148" width="88" height="34" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="381" y="164" text-anchor="middle" font-weight="bold">rcvQ</text>
|
||||
<text x="381" y="177" text-anchor="middle" font-size="9">(TBQueue, 64)</text>
|
||||
|
||||
<!-- ===== ROW 3: PROCESS ===== -->
|
||||
|
||||
<!-- rcvQ -> process -->
|
||||
<line x1="370" y1="182" x2="300" y2="216"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- process -> sentCommands (match CorrId, dashed upward) -->
|
||||
<line x1="245" y1="218" x2="245" y2="190"
|
||||
stroke="#555" stroke-dasharray="3,2" marker-end="url(#arr)" />
|
||||
<text x="252" y="208" font-size="9" fill="#555">match</text>
|
||||
|
||||
<!-- process thread -->
|
||||
<rect x="195" y="220" width="110" height="28" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="250" y="239" text-anchor="middle">process</text>
|
||||
|
||||
<!-- ===== msgQ (outside per-connection box) ===== -->
|
||||
|
||||
<!-- process -> msgQ -->
|
||||
<line x1="250" y1="248" x2="250" y2="278"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
<text x="258" y="268" font-size="9" fill="#555">events</text>
|
||||
|
||||
<!-- msgQ -->
|
||||
<rect x="175" y="280" width="160" height="33" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="255" y="296" text-anchor="middle" font-weight="bold">msgQ (optional)</text>
|
||||
<text x="255" y="308" text-anchor="middle" font-size="9">(TBQueue, server events)</text>
|
||||
|
||||
<!-- msgQ -> consumer -->
|
||||
<line x1="175" y1="296" x2="55" y2="296"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
<text x="65" y="290" font-size="9" fill="#999">to Agent / SMPClientAgent</text>
|
||||
|
||||
<!-- ===== LEGEND ===== -->
|
||||
<rect x="25" y="325" width="590" height="48" rx="4"
|
||||
fill="none" stroke="#ddd" />
|
||||
|
||||
<rect x="40" y="337" width="14" height="11" rx="2"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="60" y="347" font-size="10">thread</text>
|
||||
|
||||
<rect x="130" y="337" width="14" height="11" rx="2"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="150" y="347" font-size="10">queue / state</text>
|
||||
|
||||
<rect x="270" y="337" width="14" height="11" rx="2"
|
||||
fill="#f4f4f4" stroke="#999" />
|
||||
<text x="290" y="347" font-size="10">API entry point</text>
|
||||
|
||||
<rect x="410" y="337" width="14" height="11" rx="2"
|
||||
fill="#f5f5f5" stroke="#bbb" />
|
||||
<text x="430" y="347" font-size="10">optional</text>
|
||||
|
||||
<text x="40" y="365" font-size="10" fill="#666">
|
||||
Solid arrows: TBQueue flow. Dashed: STM lookups / TMVar responses.
|
||||
</text>
|
||||
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 6.7 KiB |
@@ -1,193 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 860 590" font-family="monospace" font-size="12">
|
||||
<defs>
|
||||
<marker id="arr" viewBox="0 0 10 10" refX="9" refY="5"
|
||||
markerWidth="6" markerHeight="6" orient="auto-start-reverse">
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill="#333" />
|
||||
</marker>
|
||||
<marker id="arr-g" viewBox="0 0 10 10" refX="9" refY="5"
|
||||
markerWidth="6" markerHeight="6" orient="auto-start-reverse">
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill="#999" />
|
||||
</marker>
|
||||
</defs>
|
||||
|
||||
<!-- ===== PER-CLIENT GROUP ===== -->
|
||||
<rect x="25" y="38" width="570" height="210" rx="6"
|
||||
fill="none" stroke="#888" stroke-dasharray="6,3" />
|
||||
<text x="35" y="53" fill="#888" font-size="10">per client connection (raceAny_: any exit tears down connection)</text>
|
||||
|
||||
<!-- receive -->
|
||||
<rect x="45" y="68" width="90" height="34" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="90" y="90" text-anchor="middle">receive</text>
|
||||
|
||||
<!-- rcvQ arrow: receive -> client -->
|
||||
<line x1="135" y1="85" x2="198" y2="85"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
<text x="166" y="79" text-anchor="middle" font-size="10" fill="#555">rcvQ</text>
|
||||
|
||||
<!-- client -->
|
||||
<rect x="200" y="68" width="100" height="34" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="250" y="90" text-anchor="middle">client</text>
|
||||
|
||||
<!-- sndQ arrow: client -> send -->
|
||||
<line x1="300" y1="78" x2="388" y2="78"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
<text x="344" y="72" text-anchor="middle" font-size="10" fill="#555">sndQ</text>
|
||||
|
||||
<!-- send -->
|
||||
<rect x="390" y="62" width="70" height="34" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="425" y="84" text-anchor="middle">send</text>
|
||||
|
||||
<!-- msgQ arrow: client -> sendMsg -->
|
||||
<line x1="300" y1="93" x2="388" y2="113"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
<text x="336" y="112" text-anchor="middle" font-size="10" fill="#555">msgQ</text>
|
||||
|
||||
<!-- sendMsg -->
|
||||
<rect x="390" y="102" width="90" height="34" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="435" y="124" text-anchor="middle">sendMsg</text>
|
||||
|
||||
<!-- network in label + arrow -->
|
||||
<text x="13" y="81" font-size="9" fill="#999">net</text>
|
||||
<line x1="12" y1="85" x2="45" y2="85"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
|
||||
<!-- network out arrows -->
|
||||
<line x1="460" y1="79" x2="498" y2="79"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
<line x1="480" y1="119" x2="498" y2="119"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
<text x="504" y="100" font-size="9" fill="#999">net</text>
|
||||
|
||||
<!-- client -> QueueStore (down-left) -->
|
||||
<line x1="228" y1="102" x2="130" y2="150"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- client -> MsgStore (down-right) -->
|
||||
<line x1="278" y1="102" x2="395" y2="150"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- QueueStore -->
|
||||
<rect x="45" y="150" width="155" height="48" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="122" y="171" text-anchor="middle" font-weight="bold">QueueStore</text>
|
||||
<text x="122" y="189" text-anchor="middle" font-size="10">(STM or Postgres)</text>
|
||||
|
||||
<!-- MsgStore -->
|
||||
<rect x="320" y="150" width="155" height="48" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="397" y="171" text-anchor="middle" font-weight="bold">MsgStore</text>
|
||||
<text x="397" y="189" text-anchor="middle" font-size="10">(STM or Postgres)</text>
|
||||
|
||||
<!-- StoreLog under QueueStore only (queues are logged, msgs stored directly) -->
|
||||
<rect x="45" y="208" width="155" height="18" rx="3"
|
||||
fill="#f5f5f5" stroke="#ccc" />
|
||||
<text x="122" y="221" text-anchor="middle" font-size="9" fill="#888">StoreLog (optional)</text>
|
||||
|
||||
<!-- NtfStore under MsgStore (in-memory notification queue, read by deliverNtfs/expireNtfs) -->
|
||||
<rect x="320" y="208" width="155" height="18" rx="3"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="397" y="221" text-anchor="middle" font-size="9" fill="#888">NtfStore (STM TMap)</text>
|
||||
|
||||
<!-- subQ arrow: from client bottom-center, through gap between stores, to serverThread -->
|
||||
<!-- Gap between stores: x=200..320 -->
|
||||
<line x1="250" y1="102" x2="250" y2="296"
|
||||
stroke="#4285f4" stroke-width="1.5" stroke-dasharray="5,3"
|
||||
marker-end="url(#arr)" />
|
||||
<text x="262" y="238" font-size="10" fill="#4285f4">subQ</text>
|
||||
|
||||
<!-- ===== SINGLETON GROUP ===== -->
|
||||
<rect x="25" y="258" width="810" height="195" rx="6"
|
||||
fill="none" stroke="#888" stroke-dasharray="6,3" />
|
||||
<text x="35" y="273" fill="#888" font-size="10">singleton threads (one instance each, all in raceAny_)</text>
|
||||
|
||||
<!-- serverThread (SMP subs) -->
|
||||
<rect x="45" y="288" width="175" height="46" rx="4"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="132" y="308" text-anchor="middle">serverThread</text>
|
||||
<text x="132" y="324" text-anchor="middle" font-size="10">(SMP subscriptions)</text>
|
||||
|
||||
<!-- serverThread (NTF subs) -->
|
||||
<rect x="240" y="288" width="175" height="46" rx="4"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="327" y="308" text-anchor="middle">serverThread</text>
|
||||
<text x="327" y="324" text-anchor="middle" font-size="10">(NTF subscriptions)</text>
|
||||
|
||||
<!-- pendingEvents: serverThread -> sendPendingEvts -->
|
||||
<line x1="195" y1="334" x2="230" y2="355"
|
||||
stroke="#555" stroke-dasharray="3,2" marker-end="url(#arr)" />
|
||||
<text x="176" y="352" font-size="9" fill="#555">pendingEvents</text>
|
||||
|
||||
<!-- deliverNtfs -->
|
||||
<rect x="45" y="352" width="128" height="30" rx="4"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="109" y="372" text-anchor="middle" font-size="11">deliverNtfs</text>
|
||||
|
||||
<!-- sendPendingEvts -->
|
||||
<rect x="195" y="352" width="148" height="30" rx="4"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="269" y="372" text-anchor="middle" font-size="11">sendPendingEvts</text>
|
||||
|
||||
<!-- expireMessages -->
|
||||
<rect x="365" y="352" width="138" height="30" rx="4"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="434" y="372" text-anchor="middle" font-size="11">expireMessages</text>
|
||||
|
||||
<!-- expireNtfs -->
|
||||
<rect x="45" y="396" width="115" height="30" rx="4"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="102" y="416" text-anchor="middle" font-size="11">expireNtfs</text>
|
||||
|
||||
<!-- proxyAgent -->
|
||||
<rect x="180" y="396" width="118" height="30" rx="4"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="239" y="416" text-anchor="middle" font-size="11">proxyAgent</text>
|
||||
|
||||
<!-- ===== OPTIONAL (nested inside singleton, right side) ===== -->
|
||||
<rect x="610" y="278" width="215" height="130" rx="6"
|
||||
fill="none" stroke="#bbb" stroke-dasharray="4,3" />
|
||||
<text x="620" y="293" fill="#bbb" font-size="10">optional</text>
|
||||
|
||||
<!-- logServerStats -->
|
||||
<rect x="625" y="302" width="140" height="24" rx="3"
|
||||
fill="#f5f5f5" stroke="#bbb" />
|
||||
<text x="695" y="319" text-anchor="middle" font-size="10">logServerStats</text>
|
||||
|
||||
<!-- prometheus -->
|
||||
<rect x="625" y="336" width="140" height="24" rx="3"
|
||||
fill="#f5f5f5" stroke="#bbb" />
|
||||
<text x="695" y="353" text-anchor="middle" font-size="10">prometheus</text>
|
||||
|
||||
<!-- controlPort -->
|
||||
<rect x="625" y="370" width="140" height="24" rx="3"
|
||||
fill="#f5f5f5" stroke="#bbb" />
|
||||
<text x="695" y="387" text-anchor="middle" font-size="10">controlPort</text>
|
||||
|
||||
<!-- ===== LEGEND ===== -->
|
||||
<rect x="25" y="472" width="810" height="60" rx="4"
|
||||
fill="none" stroke="#ddd" />
|
||||
|
||||
<rect x="40" y="486" width="14" height="11" rx="2"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="60" y="496" font-size="10">per-client thread</text>
|
||||
|
||||
<rect x="195" y="486" width="14" height="11" rx="2"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="215" y="496" font-size="10">singleton thread</text>
|
||||
|
||||
<rect x="350" y="486" width="14" height="11" rx="2"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="370" y="496" font-size="10">storage</text>
|
||||
|
||||
<rect x="445" y="486" width="14" height="11" rx="2"
|
||||
fill="#f5f5f5" stroke="#bbb" />
|
||||
<text x="465" y="496" font-size="10">optional</text>
|
||||
|
||||
<text x="40" y="522" font-size="10" fill="#666">
|
||||
Solid arrows: TBQueue connections. Dashed blue: subQ linking per-client to singleton threads.
|
||||
</text>
|
||||
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 8.0 KiB |
@@ -1,80 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 620 280" font-family="monospace" font-size="12">
|
||||
<defs>
|
||||
<marker id="arr" viewBox="0 0 10 10" refX="9" refY="5"
|
||||
markerWidth="6" markerHeight="6" orient="auto-start-reverse">
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill="#333" />
|
||||
</marker>
|
||||
<marker id="arr-g" viewBox="0 0 10 10" refX="9" refY="5"
|
||||
markerWidth="6" markerHeight="6" orient="auto-start-reverse">
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill="#999" />
|
||||
</marker>
|
||||
</defs>
|
||||
|
||||
<!-- ===== CLIENT WRAPPER ===== -->
|
||||
<rect x="120" y="40" width="380" height="130" rx="6"
|
||||
fill="none" stroke="#888" stroke-dasharray="6,3" />
|
||||
<text x="130" y="55" fill="#888" font-size="10">per connection (XFTPClient adds no threads; serialization in HTTP2Client)</text>
|
||||
|
||||
<!-- caller label -->
|
||||
<text x="15" y="95" font-size="9" fill="#999">caller</text>
|
||||
<text x="10" y="108" font-size="9" fill="#999">(Agent/</text>
|
||||
<text x="10" y="121" font-size="9" fill="#999"> router)</text>
|
||||
|
||||
<!-- caller -> XFTPClient -->
|
||||
<line x1="55" y1="100" x2="138" y2="100"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
|
||||
<!-- XFTPClient -->
|
||||
<rect x="140" y="68" width="150" height="48" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="215" y="89" text-anchor="middle" font-weight="bold">XFTPClient</text>
|
||||
<text x="215" y="107" text-anchor="middle" font-size="10">sendXFTPCommand</text>
|
||||
|
||||
<!-- XFTPClient -> HTTP2Client -->
|
||||
<line x1="290" y1="92" x2="328" y2="92"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- HTTP2Client -->
|
||||
<rect x="330" y="68" width="150" height="48" rx="4"
|
||||
fill="#fce8e6" stroke="#ea4335" />
|
||||
<text x="405" y="89" text-anchor="middle" font-weight="bold">HTTP2Client</text>
|
||||
<text x="405" y="107" text-anchor="middle" font-size="10">(TLS + HTTP/2 streams)</text>
|
||||
|
||||
<!-- HTTP2Client -> network -->
|
||||
<line x1="480" y1="92" x2="518" y2="92"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
<text x="525" y="88" font-size="9" fill="#999">XFTP</text>
|
||||
<text x="525" y="101" font-size="9" fill="#999">Router</text>
|
||||
<text x="525" y="114" font-size="9" fill="#999">(HTTP/2)</text>
|
||||
|
||||
<!-- Handshake state -->
|
||||
<rect x="140" y="130" width="150" height="32" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="215" y="151" text-anchor="middle" font-size="10">thParams (negotiated)</text>
|
||||
|
||||
<!-- upload/download note -->
|
||||
<text x="330" y="143" font-size="10" fill="#666">uploads: streaming request body</text>
|
||||
<text x="330" y="157" font-size="10" fill="#666">downloads: ephemeral DH + streaming</text>
|
||||
<text x="330" y="171" font-size="10" fill="#666"> response body (per-chunk forward secrecy)</text>
|
||||
|
||||
<!-- ===== LEGEND ===== -->
|
||||
<rect x="25" y="195" width="570" height="70" rx="4"
|
||||
fill="none" stroke="#ddd" />
|
||||
|
||||
<rect x="40" y="210" width="14" height="11" rx="2"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="60" y="220" font-size="10">client wrapper</text>
|
||||
|
||||
<rect x="195" y="210" width="14" height="11" rx="2"
|
||||
fill="#fce8e6" stroke="#ea4335" />
|
||||
<text x="215" y="220" font-size="10">external connection</text>
|
||||
|
||||
<rect x="385" y="210" width="14" height="11" rx="2"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="405" y="220" font-size="10">state</text>
|
||||
|
||||
<text x="40" y="248" font-size="10" fill="#666">
|
||||
XFTPClient adds no threads. HTTP2Client has internal reqQ + process thread.
|
||||
</text>
|
||||
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 3.4 KiB |
@@ -1,130 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 740 460" font-family="monospace" font-size="12">
|
||||
<defs>
|
||||
<marker id="arr" viewBox="0 0 10 10" refX="9" refY="5"
|
||||
markerWidth="6" markerHeight="6" orient="auto-start-reverse">
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill="#333" />
|
||||
</marker>
|
||||
<marker id="arr-g" viewBox="0 0 10 10" refX="9" refY="5"
|
||||
markerWidth="6" markerHeight="6" orient="auto-start-reverse">
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill="#999" />
|
||||
</marker>
|
||||
</defs>
|
||||
|
||||
<!-- ===== REQUEST HANDLING (no persistent threads) ===== -->
|
||||
<rect x="25" y="38" width="510" height="280" rx="6"
|
||||
fill="none" stroke="#888" stroke-dasharray="6,3" />
|
||||
<text x="35" y="53" fill="#888" font-size="10">per request (inline HTTP/2 callback, no spawned threads)</text>
|
||||
|
||||
<!-- network in -->
|
||||
<text x="13" y="78" font-size="9" fill="#999">net</text>
|
||||
<line x1="12" y1="82" x2="45" y2="82"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
|
||||
<!-- HTTP/2 Transport -->
|
||||
<rect x="45" y="66" width="190" height="34" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="140" y="88" text-anchor="middle">HTTP/2 handler</text>
|
||||
|
||||
<!-- Handshake state -->
|
||||
<rect x="280" y="60" width="240" height="48" rx="4"
|
||||
fill="#fce8e6" stroke="#ea4335" />
|
||||
<text x="400" y="78" text-anchor="middle" font-size="11">Handshake State (per session)</text>
|
||||
<text x="400" y="96" text-anchor="middle" font-size="10" fill="#666">None -> Sent -> Accepted</text>
|
||||
|
||||
<!-- sessions TMap link -->
|
||||
<line x1="235" y1="80" x2="278" y2="80"
|
||||
stroke="#555" stroke-dasharray="3,2" marker-end="url(#arr)" />
|
||||
<text x="256" y="74" text-anchor="middle" font-size="9" fill="#555">sessions</text>
|
||||
|
||||
<!-- HTTP/2 handler -> Command Processing -->
|
||||
<line x1="140" y1="100" x2="140" y2="118"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- Command Processing -->
|
||||
<rect x="45" y="120" width="475" height="36" rx="4"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="282" y="143" text-anchor="middle">Command Processing (FNEW, FADD, FPUT, FGET, FACK, FDEL, PING)</text>
|
||||
|
||||
<!-- Command Processing -> FileStore -->
|
||||
<line x1="160" y1="156" x2="130" y2="180"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- Command Processing -> Disk Storage -->
|
||||
<line x1="380" y1="156" x2="390" y2="180"
|
||||
stroke="#333" marker-end="url(#arr)" />
|
||||
|
||||
<!-- FileStore -->
|
||||
<rect x="45" y="182" width="180" height="48" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="135" y="203" text-anchor="middle" font-weight="bold">FileStore</text>
|
||||
<text x="135" y="221" text-anchor="middle" font-size="10">(TMap in STM)</text>
|
||||
|
||||
<!-- Disk Storage -->
|
||||
<rect x="300" y="182" width="220" height="48" rx="4"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="410" y="203" text-anchor="middle" font-weight="bold">Disk Storage</text>
|
||||
<text x="410" y="221" text-anchor="middle" font-size="10">filesPath / base64(senderId)</text>
|
||||
|
||||
<!-- Quota note -->
|
||||
<text x="410" y="246" text-anchor="middle" font-size="9" fill="#888">quota-managed via usedStorage TVar</text>
|
||||
|
||||
<!-- StoreLog -->
|
||||
<rect x="45" y="260" width="180" height="18" rx="3"
|
||||
fill="#f5f5f5" stroke="#ccc" />
|
||||
<text x="135" y="273" text-anchor="middle" font-size="9" fill="#888">StoreLog (append-only)</text>
|
||||
|
||||
<!-- FileStore -> StoreLog -->
|
||||
<line x1="135" y1="230" x2="135" y2="258"
|
||||
stroke="#555" stroke-dasharray="3,2" marker-end="url(#arr)" />
|
||||
|
||||
<!-- network out (command result) -->
|
||||
<line x1="520" y1="138" x2="548" y2="138"
|
||||
stroke="#999" marker-end="url(#arr-g)" />
|
||||
<text x="555" y="143" font-size="9" fill="#999">net</text>
|
||||
|
||||
<!-- ===== BACKGROUND THREADS ===== -->
|
||||
<rect x="25" y="335" width="690" height="50" rx="6"
|
||||
fill="none" stroke="#888" stroke-dasharray="6,3" />
|
||||
<text x="35" y="350" fill="#888" font-size="10">background threads (singleton, in raceAny_)</text>
|
||||
|
||||
<!-- expireFiles -->
|
||||
<rect x="45" y="358" width="118" height="22" rx="3"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="104" y="374" text-anchor="middle" font-size="10">expireFiles</text>
|
||||
|
||||
<!-- logServerStats -->
|
||||
<rect x="180" y="358" width="128" height="22" rx="3"
|
||||
fill="#f5f5f5" stroke="#bbb" />
|
||||
<text x="244" y="374" text-anchor="middle" font-size="10">logServerStats</text>
|
||||
|
||||
<!-- prometheus -->
|
||||
<rect x="325" y="358" width="118" height="22" rx="3"
|
||||
fill="#f5f5f5" stroke="#bbb" />
|
||||
<text x="384" y="374" text-anchor="middle" font-size="10">prometheus</text>
|
||||
|
||||
<!-- controlPort -->
|
||||
<rect x="460" y="358" width="118" height="22" rx="3"
|
||||
fill="#f5f5f5" stroke="#bbb" />
|
||||
<text x="519" y="374" text-anchor="middle" font-size="10">controlPort</text>
|
||||
|
||||
<!-- ===== LEGEND ===== -->
|
||||
<rect x="25" y="400" width="690" height="50" rx="4"
|
||||
fill="none" stroke="#ddd" />
|
||||
|
||||
<rect x="40" y="414" width="14" height="11" rx="2"
|
||||
fill="#e8f0fe" stroke="#4285f4" />
|
||||
<text x="60" y="424" font-size="10">request handler (no threads)</text>
|
||||
|
||||
<rect x="250" y="414" width="14" height="11" rx="2"
|
||||
fill="#fef7e0" stroke="#f9ab00" />
|
||||
<text x="270" y="424" font-size="10">storage</text>
|
||||
|
||||
<rect x="350" y="414" width="14" height="11" rx="2"
|
||||
fill="#fce8e6" stroke="#ea4335" />
|
||||
<text x="370" y="424" font-size="10">per-session state</text>
|
||||
|
||||
<rect x="500" y="414" width="14" height="11" rx="2"
|
||||
fill="#e6f4ea" stroke="#34a853" />
|
||||
<text x="520" y="424" font-size="10">background thread</text>
|
||||
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 5.4 KiB |
@@ -1,155 +0,0 @@
|
||||
# Design Notes
|
||||
|
||||
Non-bug observations from module specs that are worth tracking. These remain documented in their respective module specs — this file serves as an index.
|
||||
|
||||
## Backend Observations
|
||||
|
||||
### N-01: SNotifier path doesn't cache
|
||||
|
||||
**Location**: `Simplex.Messaging.Server.QueueStore.Postgres` — `getQueues_` SNotifier branch
|
||||
**Description**: The SRecipient path caches loaded queues via `cacheRcvQueue` with double-check locking. The SNotifier path does NOT cache — it uses a stale TMap snapshot and `maybe (mkQ False rId qRec) pure`, so concurrent loads for the same notifier can create duplicate ephemeral queue objects. Functionally correct but wasteful.
|
||||
**Module spec**: [QueueStore/Postgres.md](Simplex/Messaging/Server/QueueStore/Postgres.md)
|
||||
|
||||
### N-02: assertUpdated error conflation
|
||||
|
||||
**Location**: `Simplex.Messaging.Server.QueueStore.Postgres` — `assertUpdated`
|
||||
**Description**: `assertUpdated` returns `AUTH` for zero-rows-affected. This is the same error code used for "not found" (via `readQueueRecIO`) and "duplicate" (via `handleDuplicate`). The actual cause — stale cache, deleted queue, or constraint violation — is indistinguishable in logs.
|
||||
**Module spec**: [QueueStore/Postgres.md](Simplex/Messaging/Server/QueueStore/Postgres.md)
|
||||
|
||||
## Design Characteristics
|
||||
|
||||
### N-03: RCVerifiedInvitation constructor exported
|
||||
|
||||
**Location**: `Simplex.RemoteControl.Invitation` — `RCVerifiedInvitation`
|
||||
**Description**: `RCVerifiedInvitation` is a newtype with constructor exported via `(..)`. It can be constructed without calling `verifySignedInvitation`, bypassing signature verification. The trust boundary is conventional, not enforced by the type system. `connectRCCtrl` accepts only `RCVerifiedInvitation`.
|
||||
**Module spec**: [RemoteControl/Invitation.md](Simplex/RemoteControl/Invitation.md)
|
||||
|
||||
### N-04: smpEncode Word16 silent truncation
|
||||
|
||||
**Location**: `Simplex.Messaging.Encoding` — `Encoding Word16` instance
|
||||
**Description**: `smpEncode` for ByteString uses a 1-byte length prefix. Maximum encodable length is 255 bytes. Longer values silently wrap via `w2c . fromIntegral`. Callers must ensure ByteStrings fit or use `Large`.
|
||||
**Module spec**: [Encoding.md](Simplex/Messaging/Encoding.md)
|
||||
|
||||
### N-05: writeIORef for period stats — not atomic
|
||||
|
||||
**Location**: `Simplex.Messaging.Server.Stats` — `setPeriodStats`
|
||||
**Description**: Uses `writeIORef` (not atomic). Only safe during router startup when no other threads are running. If called concurrently, period data could be corrupted.
|
||||
**Module spec**: [Server/Stats.md](Simplex/Messaging/Server/Stats.md)
|
||||
|
||||
### N-06: setStatsByServer orphans old TVars
|
||||
|
||||
**Location**: `Simplex.Messaging.Notifications.Server.Stats` — `setStatsByServer`
|
||||
**Description**: Builds a fresh `Map Text (TVar Int)` in IO, then atomically replaces the TMap's root TVar. Old per-router TVars are not reused — any other thread holding a reference from a prior `TM.lookupIO` would modify an orphaned counter. Called at startup, but lacks the explicit "not thread safe" comment.
|
||||
**Module spec**: [Notifications/Server/Stats.md](Simplex/Messaging/Notifications/Server/Stats.md)
|
||||
|
||||
### N-07: Lazy.unPad doesn't validate data length
|
||||
|
||||
**Location**: `Simplex.Messaging.Crypto.Lazy` — `unPad` / `splitLen`
|
||||
**Description**: `splitLen` does not validate that the remaining data is at least `len` bytes — `LB.take len` silently returns a shorter result. The source comment notes this is intentional to avoid consuming all lazy chunks for validation.
|
||||
**Module spec**: [Crypto/Lazy.md](Simplex/Messaging/Crypto/Lazy.md)
|
||||
|
||||
### N-08: Batched commands have no timeout-based expiry
|
||||
|
||||
**Location**: `Simplex.Messaging.Client` — `sendBatch`
|
||||
**Description**: Batched commands are written with `Nothing` as the request parameter — the send thread skips the `pending` flag check. Individual commands have timeout-based expiry. If the router stops returning results, batched commands can block the send queue indefinitely.
|
||||
**Module spec**: [Client.md](Simplex/Messaging/Client.md)
|
||||
|
||||
### N-09: Postgres MsgStore nanosecond precision
|
||||
|
||||
**Location**: `Simplex.Messaging.Server.MsgStore.Postgres` — `toMessage`
|
||||
**Description**: `MkSystemTime ts 0` constructs timestamps with zero nanoseconds. Only whole seconds are stored. Messages read from Postgres have coarser timestamps than STM/Journal stores. Not a practical issue — timestamps are typically rounded to hours or days.
|
||||
**Module spec**: [Server/MsgStore/Postgres.md](Simplex/Messaging/Server/MsgStore/Postgres.md)
|
||||
|
||||
### N-10: MsgStore Postgres — error stubs crash at runtime
|
||||
|
||||
**Location**: `Simplex.Messaging.Server.MsgStore.Postgres` — multiple `MsgStoreClass` methods
|
||||
**Description**: Multiple `MsgStoreClass` methods are `error "X not used"`. Required by the type class but not applicable to Postgres. Calling any at runtime crashes. Safe because Postgres overrides the relevant default methods, but a new caller using the wrong method would crash with no compile-time warning.
|
||||
**Module spec**: [Server/MsgStore/Postgres.md](Simplex/Messaging/Server/MsgStore/Postgres.md)
|
||||
|
||||
### N-11: strP default assumes base64url for all types
|
||||
|
||||
**Location**: `Simplex.Messaging.Encoding.String` — `StrEncoding` class default
|
||||
**Description**: The `MINIMAL` pragma allows defining only `strDecode` without `strP`. The default `strP = strDecode <$?> base64urlP` assumes input is base64url-encoded for any type. A new `StrEncoding` instance that defines only `strDecode` for non-base64 data would get a broken parser.
|
||||
**Module spec**: [Encoding/String.md](Simplex/Messaging/Encoding/String.md)
|
||||
|
||||
## Silent Behaviors
|
||||
|
||||
Intentional design choices that are correct but non-obvious. A code modifier who doesn't know these could introduce bugs.
|
||||
|
||||
### N-12: Service signing silently skipped on empty authenticator
|
||||
|
||||
**Location**: `Simplex.Messaging.Client` — service signature path
|
||||
**Description**: The service signature is only added when the entity authenticator is non-empty. If authenticator generation fails silently (returns empty bytes), service signing is silently skipped.
|
||||
**Module spec**: [Client.md](Simplex/Messaging/Client.md)
|
||||
|
||||
### N-13: stmDeleteNtfToken — nonexistent token indistinguishable from empty
|
||||
|
||||
**Location**: `Simplex.Messaging.Notifications.Server.Store` — `stmDeleteNtfToken`
|
||||
**Description**: If the token ID doesn't exist in the `tokens` map, the registration-cleanup branch is skipped and the function returns an empty list. The caller cannot distinguish "deleted a token with no subscriptions" from "token never existed."
|
||||
**Module spec**: [Notifications/Server/Store.md](Simplex/Messaging/Notifications/Server/Store.md)
|
||||
|
||||
### N-14: createCommand silently drops commands for deleted connections
|
||||
|
||||
**Location**: `Simplex.Messaging.Agent.Store.AgentStore` — `createCommand`
|
||||
**Description**: When `createCommand` encounters a constraint violation (the referenced connection was already deleted), it logs the error and returns successfully. Commands targeting deleted connections are silently dropped.
|
||||
**Module spec**: [Agent/Store/AgentStore.md](Simplex/Messaging/Agent/Store/AgentStore.md)
|
||||
|
||||
### N-15: Redirect chain loading errors silently swallowed
|
||||
|
||||
**Location**: `Simplex.Messaging.Agent.Store.AgentStore`
|
||||
**Description**: When loading redirect chains, errors loading individual redirect files are silently swallowed via `either (const $ pure Nothing) (pure . Just)`. Prevents a corrupt redirect from blocking access to the main file.
|
||||
**Module spec**: [Agent/Store/AgentStore.md](Simplex/Messaging/Agent/Store/AgentStore.md)
|
||||
|
||||
### N-16: BLOCKED encoded as AUTH for old XFTP clients
|
||||
|
||||
**Location**: `Simplex.FileTransfer.Protocol` — `encodeProtocol`
|
||||
**Description**: If the protocol version is below `blockedFilesXFTPVersion`, a `BLOCKED` result is encoded as `AUTH` instead. The blocking information (reason) is permanently lost for these clients.
|
||||
**Module spec**: [FileTransfer/Protocol.md](Simplex/FileTransfer/Protocol.md)
|
||||
|
||||
### N-17: restore_messages three-valued logic with implicit default
|
||||
|
||||
**Location**: `Simplex.Messaging.Server.Main` — INI config
|
||||
**Description**: The `restore_messages` INI setting has three-valued logic: explicit "on" → restore, explicit "off" → skip, missing → inherits from `enable_store_log`. This implicit default is not captured in the type system — callers see `Maybe Bool`.
|
||||
**Module spec**: [Server/Main.md](Simplex/Messaging/Server/Main.md)
|
||||
|
||||
### N-18: Stats format migration permanently loses precision
|
||||
|
||||
**Location**: `Simplex.Messaging.Server.Stats` — `strP` for `ServerStatsData`
|
||||
**Description**: The parser handles multiple format generations. Old format `qDeleted=` is read as `(value, 0, 0)`. `qSubNoMsg` is parsed and discarded. `subscribedQueues` is parsed but replaced with empty data. Data loaded from old formats is coerced — precision is permanently lost.
|
||||
**Module spec**: [Server/Stats.md](Simplex/Messaging/Server/Stats.md)
|
||||
|
||||
### N-19: resubscribe exceptions silently lost
|
||||
|
||||
**Location**: `Simplex.Messaging.Notifications.Server` — `resubscribe`
|
||||
**Description**: `resubscribe` is launched via `forkIO` before `raceAny_` starts — not part of the `raceAny_` group. Most exceptions are silently lost per `forkIO` semantics. `ExitCode` exceptions are special-cased by GHC's runtime and do propagate.
|
||||
**Module spec**: [Notifications/Server.md](Simplex/Messaging/Notifications/Server.md)
|
||||
|
||||
### N-20: closeSMPClientAgent worker cancellation is fire-and-forget
|
||||
|
||||
**Location**: `Simplex.Messaging.Client.Agent` — `closeSMPClientAgent`
|
||||
**Description**: Executes in order: set `active = False`, close all client connections, swap workers map to empty and fork cancellation threads. Cancel threads use `uninterruptibleCancel` but are fire-and-forget — the function may return before all workers are cancelled.
|
||||
**Module spec**: [Client/Agent.md](Simplex/Messaging/Client/Agent.md)
|
||||
|
||||
### N-21: APNS unknown 410 reasons trigger retry instead of permanent failure
|
||||
|
||||
**Location**: `Simplex.Messaging.Notifications.Server.Push.APNS`
|
||||
**Description**: Unknown 410 (Gone) reasons fall through to `PPRetryLater`, while unknown 400 and 403 reasons fall through to `PPResponseError`. An unexpected APNS 410 reason string triggers retry rather than permanent failure.
|
||||
**Module spec**: [Notifications/Server/Push/APNS.md](Simplex/Messaging/Notifications/Server/Push/APNS.md)
|
||||
|
||||
### N-22: NTInvalid/NTExpired tokens can create subscriptions
|
||||
|
||||
**Location**: `Simplex.Messaging.Notifications.Protocol` — token status permissions
|
||||
**Description**: Token status `NTInvalid` allows subscription commands (SNEW, SCHK, SDEL). A TODO comment explains: invalidation can happen after verification, and existing subscriptions should remain manageable. `NTExpired` is also permitted.
|
||||
**Module spec**: [Notifications/Protocol.md](Simplex/Messaging/Notifications/Protocol.md)
|
||||
|
||||
### N-23: removeInactiveTokenRegistrations doesn't clean up empty inner maps
|
||||
|
||||
**Location**: `Simplex.Messaging.Notifications.Server.Store` — `stmRemoveInactiveTokenRegistrations`
|
||||
**Description**: `stmDeleteNtfToken` checks whether inner TMap is empty after removal and cleans up the outer key. `stmRemoveInactiveTokenRegistrations` does not — surviving active tokens' registrations remain, but empty inner maps can persist.
|
||||
**Module spec**: [Notifications/Server/Store.md](Simplex/Messaging/Notifications/Server/Store.md)
|
||||
|
||||
### N-24: cbNonce silently truncates or pads
|
||||
|
||||
**Location**: `Simplex.Messaging.Crypto` — `cbNonce`
|
||||
**Description**: If the input is longer than 24 bytes, it is silently truncated. If shorter, it is silently padded. No error is raised. Callers must ensure correct length.
|
||||
**Module spec**: [Crypto.md](Simplex/Messaging/Crypto.md)
|
||||
@@ -1,197 +0,0 @@
|
||||
# How to Document a Module
|
||||
|
||||
> Read this before writing any module doc. It defines what goes in, what stays out, and why.
|
||||
|
||||
## Purpose
|
||||
|
||||
Module docs exist for one reason: to capture knowledge that **cannot be obtained by reading the source code**. If reading the `.hs` file tells you everything you need to know, the module doc should be brief or empty.
|
||||
|
||||
These docs are an investment — their value compounds over time as multiple people (and LLMs) work on the code. Optimize for long-term value, not for looking thorough today.
|
||||
|
||||
## Process
|
||||
|
||||
**Read every line of the source file.** The non-obvious filter applies to what you *write*, not to what you *read*. Without reading each line, you will produce documentation from inferences rather than facts. Many non-obvious behaviors only become visible when you see a specific line of code and recognize that its implications would surprise a reader who doesn't have the surrounding context.
|
||||
|
||||
## File structure
|
||||
|
||||
Module docs mirror `src/Simplex/` exactly. Same subfolder structure, `.hs` replaced with `.md`:
|
||||
|
||||
```
|
||||
src/Simplex/Messaging/Server.hs → spec/modules/Simplex/Messaging/Server.md
|
||||
src/Simplex/Messaging/Crypto.hs → spec/modules/Simplex/Messaging/Crypto.md
|
||||
src/Simplex/FileTransfer/Agent.hs → spec/modules/Simplex/FileTransfer/Agent.md
|
||||
```
|
||||
|
||||
## What to include
|
||||
|
||||
### 1. Non-obvious behavior
|
||||
Things that would surprise a competent Haskell developer reading the code for the first time:
|
||||
- Subtle invariants maintained across function calls
|
||||
- Ordering dependencies ("must call X before Y because...")
|
||||
- Concurrency assumptions ("this TVar is only written from thread Z")
|
||||
- Implicit contracts between caller and callee not captured by types
|
||||
|
||||
### 2. Usage considerations
|
||||
- When to use function X vs function Y
|
||||
- Common mistakes callers make
|
||||
- Caller obligations not enforced by the type system
|
||||
- Performance characteristics that affect usage decisions
|
||||
|
||||
### 3. Cross-module relationships
|
||||
- Dependencies on other modules' behavior not visible from import lists
|
||||
- Assumptions about how other modules use this one
|
||||
- Coordination patterns (e.g., "Server.hs reads this TVar, Agent.hs writes it")
|
||||
|
||||
### 4. Security notes
|
||||
- Trust boundaries this module enforces or relies on
|
||||
- What happens if inputs are malicious
|
||||
- Which functions are security-critical and why (reference SI-XX invariants)
|
||||
|
||||
### 5. Design rationale
|
||||
- Why the code is structured this way (when not obvious)
|
||||
- Alternatives considered and rejected
|
||||
- Known limitations and their justification
|
||||
|
||||
## Non-obvious threshold
|
||||
|
||||
The guiding principle: **non-obvious state machines and flows require documentation; standard things don't.**
|
||||
|
||||
Document:
|
||||
- Multi-step protocols and negotiation flows (e.g., KEM propose/accept round-trips)
|
||||
- Monotonic or irreversible state transitions (e.g., PQ support can only be enabled, never disabled)
|
||||
- Silent error behaviors (e.g., `verify` returns `False` on algorithm mismatch instead of an error)
|
||||
- Design rationale for non-standard choices (e.g., why byte-reverse a nonce, why hash-then-encrypt for authenticators)
|
||||
|
||||
Do NOT document:
|
||||
- Standard algorithm properties (e.g., Ed25519 public key derivable from private key)
|
||||
- Well-known protocol mechanics (e.g., HKDF usage per RFC 5869, deterministic nonce derivation in double ratchet)
|
||||
- Implementation details that follow directly from the type signatures
|
||||
|
||||
## What NOT to include
|
||||
|
||||
- **Type signatures** — the code has them
|
||||
- **Code snippets** — if you're pasting code, you're making a stale copy
|
||||
- **Function-by-function prose that restates the implementation** — "this function takes X and returns Y by doing Z" adds nothing
|
||||
- **Line numbers** — they're brittle and break on every edit
|
||||
- **Comments that fit in one line in source** — put those in the source file instead as `-- spec:` comments
|
||||
- **Verbatim quotes of source comments** — reference them instead: "See comment on `functionName`." Then add only what the comment doesn't cover (cross-module implications, what breaks if violated). If the source comment says everything, the function doesn't need a doc entry.
|
||||
- **Tables that reproduce code structure** — if the information is self-evident from reading the code's pattern matching or type definitions, it doesn't belong in the doc (e.g., per-command credential requirements, version-conditional encoding branches)
|
||||
|
||||
## Format
|
||||
|
||||
Each module doc has a header, then entries for functions/types that need documentation.
|
||||
|
||||
```markdown
|
||||
# Module.Name
|
||||
|
||||
> One-line description of what this module does.
|
||||
|
||||
**Source**: [`Path/To/Module.hs`](relative link to source)
|
||||
|
||||
## Overview
|
||||
|
||||
[Only if the module's purpose or architecture is non-obvious.
|
||||
Skip for simple modules.]
|
||||
|
||||
## functionName
|
||||
|
||||
**Purpose**: [What this does that isn't obvious from the name and type]
|
||||
**Calls**: [Qualified.Name.a](link), [Qualified.Name.b](link)
|
||||
**Called by**: [Qualified.Name.c](link)
|
||||
**Invariant**: SI-XX
|
||||
**Security**: [What this function ensures for the threat model]
|
||||
|
||||
[Free-form notes about non-obvious behavior, gotchas, etc.]
|
||||
|
||||
## anotherFunction
|
||||
|
||||
...
|
||||
```
|
||||
|
||||
**For trivial modules** (< 100 LOC, no non-obvious behavior):
|
||||
|
||||
```markdown
|
||||
# Module.Name
|
||||
|
||||
> One-line description.
|
||||
|
||||
**Source**: [`Path/To/Module.hs`](relative link to source)
|
||||
|
||||
No non-obvious behavior. See source.
|
||||
```
|
||||
|
||||
This is valuable — it confirms someone looked and found nothing to document.
|
||||
|
||||
## Linking conventions
|
||||
|
||||
### Module doc → protocol docs
|
||||
When a module implements or is governed by a protocol specification in `protocol/`, link to it near the top of the module doc (after the overview). Do not duplicate protocol content — just reference it:
|
||||
```markdown
|
||||
**Protocol spec**: [`protocol/pqdr.md`](../../../../protocol/pqdr.md) — Post-quantum resistant augmented double ratchet algorithm.
|
||||
```
|
||||
|
||||
This is especially important for modules in transport, protocol, client, server, and agent layers where behavior is defined by the protocol spec rather than being self-evident from the code.
|
||||
|
||||
### Module doc → other module docs
|
||||
Use fully qualified names as link text:
|
||||
```markdown
|
||||
[Simplex.Messaging.Server.subscribeServiceMessages](./Simplex/Messaging/Server.md#subscribeServiceMessages)
|
||||
```
|
||||
|
||||
### Module doc → topic docs
|
||||
```markdown
|
||||
See [rcv-services](../rcv-services.md) for the end-to-end service subscription flow.
|
||||
```
|
||||
|
||||
### Source → module doc
|
||||
|
||||
Add `-- spec:` comments as part of the module documentation work — when you document something non-obvious, add the link in source at the same time. Two levels:
|
||||
|
||||
**Module-level** (below the module declaration): when the Overview section has value.
|
||||
```haskell
|
||||
module Simplex.Messaging.Util (...) where
|
||||
-- spec: spec/modules/Simplex/Messaging/Util.md
|
||||
```
|
||||
|
||||
**Function-level** (above the function): when that function has a doc entry worth pointing to.
|
||||
```haskell
|
||||
-- spec: spec/modules/Simplex/Messaging/Util.md#catchOwn
|
||||
-- Catches all exceptions except async cancellations (misleading name)
|
||||
catchOwn :: ...
|
||||
```
|
||||
|
||||
Only add `-- spec:` comments where the module doc actually says something the code doesn't. Don't add links to "No non-obvious behavior" docs or to entries that merely restate the source.
|
||||
|
||||
## Topic candidate tracking
|
||||
|
||||
While documenting modules, you will notice cross-cutting patterns — behaviors that span multiple modules and can't be understood from any single one. Note these in `spec/TOPICS.md` for later. Don't write the topic doc during module work; just record:
|
||||
|
||||
```markdown
|
||||
- **Queue rotation**: Agent.hs initiates, Client.hs sends commands, Server.hs processes,
|
||||
Protocol.hs defines types. End-to-end flow not obvious from any single module.
|
||||
```
|
||||
|
||||
## Quality bar
|
||||
|
||||
Before finishing a module doc, ask:
|
||||
1. Does every entry document something NOT in the source code?
|
||||
2. Would removing any entry lose information? If not, remove it.
|
||||
3. Are cross-module relationships captured that imports alone don't reveal?
|
||||
4. Are security-critical functions flagged with invariant IDs?
|
||||
5. Is this doc short enough that someone will actually read it?
|
||||
|
||||
If any answer reveals a problem, fix it and repeat from question 1. Only finish when a full pass produces no changes.
|
||||
|
||||
## Terminology — the spec as translation boundary
|
||||
|
||||
The protocol documents (`protocol/overview-tjr.md`, `protocol/simplex-messaging.md`, `protocol/agent-protocol.md`) define the canonical terminology. Code uses different names for some of the same concepts. The spec is where the translation happens.
|
||||
|
||||
The most important distinction: SimpleX protocol routers are referred to as "servers" in code. The term "server" was adopted historically because SimpleX routers were implemented as Linux-based software that is deployed in the same way as servers. But the similarity is entirely formal. Functionally, servers serve responses to the requests of their users - that is why the term "server" was adopted for computers and software that provide Internet services. SimpleX protocol routers don't serve responses - they route packets between endpoints, and they have no concept of a user. Functionally they are similar to Internet Protocol routers, but with a resource-based addressing scheme. Further, SimpleX protocol routers are hardware and software agnostic. SimpleX protocols are open and documented, so they can be implemented in any language and run on a different architecture. For example, [SimpleGo](https://simplego.dev) is a prototype implementation of the SimpleX protocol stack in C for a microcontroller architecture.
|
||||
|
||||
**The rule**: use protocol terms for concepts, code terms for identifiers. Write "router" when describing the network node's role, `SMPServer` or `Server.hs` when referencing code. Similarly, "router identity" for the concept (called "server key hash" or "fingerprint" in code). When the distinction matters, bridge explicitly: "the SMP router (implemented by the `Server` module)" or "the `SMPServer` type (representing a router address)."
|
||||
|
||||
## Exclusions
|
||||
|
||||
- **Individual migration files** (M20XXXXXX_*.hs): Self-describing SQL. No per-migration docs.
|
||||
- **Auto-generated files** (GitCommit.hs): Skip.
|
||||
- **Pure boilerplate** (Prometheus.hs metrics, Web/Embedded.hs static files): Document only if non-obvious.
|
||||
@@ -1,90 +0,0 @@
|
||||
# Simplex.FileTransfer.Agent
|
||||
|
||||
> XFTP agent: worker-based file send/receive/delete with retry, encryption, redirect chains, and file description generation.
|
||||
|
||||
**Source**: [`FileTransfer/Agent.hs`](../../../../src/Simplex/FileTransfer/Agent.hs)
|
||||
|
||||
## Terminology
|
||||
|
||||
The agent splits a **file** into **chunks** determined by the chunking algorithm. Each chunk is stored on an XFTP router as a **data packet** — the router has no concept of files or chunks, only directly addressable data packets. This document uses "chunk" for the agent's internal tracking and "data packet" when referring to what is transferred to/from or stored on routers.
|
||||
|
||||
## Architecture
|
||||
|
||||
The XFTP agent uses five worker types organized in three categories:
|
||||
|
||||
| Worker | Key (router) | Purpose |
|
||||
|--------|-------------|---------|
|
||||
| `xftpRcvWorker` | `Just server` | Download data packets from a specific XFTP router |
|
||||
| `xftpRcvLocalWorker` | `Nothing` | Decrypt completed downloads locally |
|
||||
| `xftpSndPrepareWorker` | `Nothing` | Encrypt files and create data packets on routers |
|
||||
| `xftpSndWorker` | `Just server` | Upload data packets to a specific XFTP router |
|
||||
| `xftpDelWorker` | `Just server` | Delete data packets from a specific XFTP router |
|
||||
|
||||
Workers are created on-demand via `getAgentWorker` and keyed by router address. The local workers (keyed by `Nothing`) handle CPU-bound operations that don't require network access.
|
||||
|
||||
## Non-obvious behavior
|
||||
|
||||
### 1. startXFTPWorkers vs startXFTPSndWorkers
|
||||
|
||||
`startXFTPWorkers` starts all three worker categories (rcv, snd, del). `startXFTPSndWorkers` starts only snd workers. This distinction exists because receiving and deleting require a full agent context, while sending can operate with a partial setup (used when the agent is in send-only mode).
|
||||
|
||||
### 2. Download completion triggers local worker
|
||||
|
||||
When `downloadFileChunk` determines that all chunks are received (`all chunkReceived chunks`), it calls `getXFTPRcvWorker True c Nothing` to wake the local decryption worker. The `True` parameter signals that work is available. Without this, the local worker would sleep until the next `waitForWork` check.
|
||||
|
||||
### 3. Decryption verifies both digest and size before decrypting
|
||||
|
||||
`decryptFile` first computes the total size of all encrypted chunk files, then their SHA-512 digest. If either mismatches the expected values, it throws an error *before* starting decryption. This prevents wasting CPU on corrupted or tampered downloads.
|
||||
|
||||
### 4. Redirect chain with depth limit
|
||||
|
||||
When a received file has a `redirect`, the local worker:
|
||||
1. Decrypts the redirect file (a YAML file description)
|
||||
2. Validates the inner description's size and digest against `RedirectFileInfo`
|
||||
3. Registers the inner file's chunks and starts downloading them
|
||||
|
||||
The redirect chain is implicitly limited to depth 1: `createRcvFileRedirect` creates the destination file entry with `redirect = Nothing`, and `updateRcvFileRedirect` does not update the redirect column. So even if the decoded inner description contains a redirect field, the database record for the destination file has no redirect, preventing further chaining.
|
||||
|
||||
### 5. Decrypting worker resumes from RFSDecrypting
|
||||
|
||||
If the agent restarts while a file is in `RFSDecrypting` status, the local worker detects this and deletes the partially-decrypted output file before restarting decryption. This prevents corrupted output from a previous incomplete decryption attempt.
|
||||
|
||||
### 6. Encryption worker resumes from SFSEncrypting
|
||||
|
||||
Similarly, `prepareFile` checks `status /= SFSEncrypted` and deletes the partial encrypted file if status is `SFSEncrypting`. This allows clean restart of interrupted encryption.
|
||||
|
||||
### 7. Redirect files must be single-chunk
|
||||
|
||||
`encryptFileForUpload` for redirect files calls `singleChunkSize` instead of `prepareChunkSizes`. If the redirect file description doesn't fit in a single chunk, it throws `FILE SIZE`. This ensures redirect files are atomic — they either download completely or not at all.
|
||||
|
||||
### 8. addRecipients recursive batching
|
||||
|
||||
During upload, `addRecipients` recursively calls itself if a data packet needs more recipients than `xftpMaxRecipientsPerRequest`. Each iteration sends an FADD command for up to `maxRecipients` new recipients, accumulates the results, and recurses until all recipients are registered.
|
||||
|
||||
### 9. File description generation cross-product
|
||||
|
||||
`createRcvFileDescriptions` (in both `Agent.hs` and `Client/Main.hs`) performs a cross-product transformation: M chunks × R replicas × N recipients → N file descriptions, each containing M chunks with R replicas. The `addRcvChunk` accumulator builds a `Map rcvNo (Map chunkNo FileChunk)` to correctly distribute replicas across recipient descriptions.
|
||||
|
||||
### 10. withRetryIntervalLimit caps consecutive retries
|
||||
|
||||
`withRetryIntervalLimit maxN` allows at most `maxN` total attempts (initial attempt at `n=0` plus `maxN-1` retries). When all attempts are exhausted for temporary errors, the operation is silently abandoned for this work cycle — the chunk remains in pending state and may be retried on the next cycle. Only permanent errors (handled by `retryDone`) mark the file as errored.
|
||||
|
||||
### 11. Retry distinguishes temporary from permanent errors
|
||||
|
||||
`retryOnError` checks `temporaryOrHostError`: temporary/host errors trigger retry with exponential backoff; permanent errors (AUTH, SIZE, etc.) immediately mark the file as failed. On host errors during retry, a warning notification is sent to the client.
|
||||
|
||||
### 12. Delete workers skip files older than rcvFilesTTL
|
||||
|
||||
`runXFTPDelWorker` uses `rcvFilesTTL` (not a dedicated delete TTL) to filter pending deletions. Data packets older than this TTL would already be expired on the router, so attempting deletion is pointless. This reuses the receive TTL as a proxy for router-side expiration.
|
||||
|
||||
### 13. closeXFTPAgent atomically swaps worker maps
|
||||
|
||||
`closeXFTPAgent` uses `swapTVar workers M.empty` to atomically replace each worker map with an empty map, then cancels all retrieved workers. This prevents races where a new worker could be inserted between reading and clearing the map.
|
||||
|
||||
### 14. assertAgentForeground dual check
|
||||
|
||||
`assertAgentForeground` both throws if the agent is inactive (`throwWhenInactive`) and blocks until it's in the foreground (`waitUntilForeground`). This is called before every chunk operation to ensure the agent isn't suspended or backgrounded during file transfers.
|
||||
|
||||
### 15. Per-router stats tracking
|
||||
|
||||
Every data packet download, upload, and delete operation increments per-router statistics (`downloads`, `uploads`, `deletions`, `downloadAttempts`, `uploadAttempts`, `deleteAttempts`, and error variants). Size-based stats (`downloadsSize`, `uploadsSize`) track throughput in kilobytes.
|
||||
@@ -1,37 +0,0 @@
|
||||
# Simplex.FileTransfer.Client
|
||||
|
||||
> XFTP client: connection management, handshake, data packet upload/download with forward secrecy.
|
||||
|
||||
**Source**: [`FileTransfer/Client.hs`](../../../../src/Simplex/FileTransfer/Client.hs)
|
||||
|
||||
## Non-obvious behavior
|
||||
|
||||
### 1. ALPN-based handshake version selection
|
||||
|
||||
`getXFTPClient` checks the ALPN result after TLS negotiation:
|
||||
- **`xftpALPNv1` or `httpALPN11`**: performs v1 handshake with key exchange (`httpALPN11` is used for web port connections)
|
||||
- **No ALPN or unrecognized**: uses legacy v1 transport parameters without handshake
|
||||
|
||||
### 2. Router certificate chain validation
|
||||
|
||||
`xftpClientHandshakeV1` validates the router's identity by checking that the CA fingerprint from the certificate chain matches the expected `keyHash` from the router address. The router signs an authentication public key (X25519) with its long-term key. The client verifies this signature against the certificate chain, then extracts the X25519 key for HMAC-based command authentication. This authentication key is distinct from the per-download ephemeral DH keys.
|
||||
|
||||
### 3. Ephemeral DH key pair per download
|
||||
|
||||
`downloadXFTPChunk` generates a fresh X25519 key pair for each data packet download. The public key is sent with the FGET command; the router returns its own ephemeral key. The derived shared secret encrypts the data packet in transit. This provides forward secrecy — compromising a past DH key doesn't decrypt other downloads.
|
||||
|
||||
### 4. Size-proportional download timeout
|
||||
|
||||
`downloadXFTPChunk` calculates the timeout as `baseTimeout + (sizeInKB * perKbTimeout)`, where `baseTimeout` is the base TCP timeout and `perKbTimeout` is a per-kilobyte timeout from the network config. Larger data packets get proportionally more time. This prevents premature timeouts on large data packets over slow connections.
|
||||
|
||||
### 5. prepareChunkSizes threshold algorithm
|
||||
|
||||
`prepareChunkSizes` selects data packet sizes using a 75% threshold: if the remaining payload exceeds 75% of the next larger size, it uses the larger size. Otherwise, it uses the smaller size. `singleChunkSize` returns `Just size` only if the payload fits in a single data packet (used for redirect files which must be single-packet).
|
||||
|
||||
### 6. Upload sends data packet after command block
|
||||
|
||||
`uploadXFTPChunk` sends the FPUT command and data packet body in the same streaming HTTP/2 request: the protocol command block is sent first, followed immediately by the raw encrypted data via `hSendFile`. The command result (`FROk` or error) is received only after both the command and data have been fully sent. This is a single HTTP/2 round trip, not a two-phase interaction.
|
||||
|
||||
### 7. Empty corrId as nonce
|
||||
|
||||
`sendXFTPCommand` uses `""` (empty bytestring) as the correlation ID for all commands. XFTP is strictly request-response within a single HTTP/2 stream, so correlation IDs are unnecessary. The empty value is passed to `C.cbNonce` to produce a constant nonce for command authentication (HMAC/signing), not encryption — XFTP authenticates commands but does not encrypt them within the TLS tunnel.
|
||||
@@ -1,27 +0,0 @@
|
||||
# Simplex.FileTransfer.Client.Agent
|
||||
|
||||
> XFTP client: router connection management with TMVar-based sharing, async retry, and connection lifecycle.
|
||||
|
||||
**Source**: [`FileTransfer/Client/Agent.hs`](../../../../../src/Simplex/FileTransfer/Client/Agent.hs)
|
||||
|
||||
## Non-obvious behavior
|
||||
|
||||
### 1. TMVar-based connection sharing
|
||||
|
||||
`getXFTPServerClient` first checks the `TMap XFTPServer (TMVar (Either XFTPClientAgentError XFTPClient))`. If no entry exists, it atomically inserts an empty `TMVar` and initiates connection. Other threads requesting the same router block on `readTMVar` until the connection is established or fails. This prevents duplicate connections to the same router.
|
||||
|
||||
### 2. Async retry on temporary errors
|
||||
|
||||
When `newXFTPClient` encounters a temporary error, it launches an async retry loop that attempts reconnection with backoff. The `TMVar` remains in the map but is empty until the retry succeeds. Other threads waiting on `readTMVar` block until either the retry succeeds or a permanent error occurs.
|
||||
|
||||
### 3. Permanent error cleanup
|
||||
|
||||
On permanent error, `newXFTPClient` puts the `Left error` into the `TMVar` (unblocking waiters) AND deletes the entry from the `TMap`. This means the next caller will see no entry and create a fresh connection attempt, rather than reading a stale error. Waiters that already read the `Left` receive the error.
|
||||
|
||||
### 4. Connection timeout
|
||||
|
||||
`waitForXFTPClient` wraps `readTMVar` in a timeout. If the connection establishment takes too long (e.g., router unreachable and retry loop is slow), the caller gets a timeout error rather than blocking indefinitely. The underlying connection attempt continues in the background.
|
||||
|
||||
### 5. closeXFTPServerClient removes from TMap
|
||||
|
||||
Closing a router client deletes its entry from the TMap, so the next request will establish a fresh connection. This is called on connection errors during data packet operations to force reconnection.
|
||||
@@ -1,43 +0,0 @@
|
||||
# Simplex.FileTransfer.Client.Main
|
||||
|
||||
> XFTP CLI client: send, receive, delete files with parallel chunk operations and web URI encoding.
|
||||
|
||||
**Source**: [`FileTransfer/Client/Main.hs`](../../../../../src/Simplex/FileTransfer/Client/Main.hs)
|
||||
|
||||
## Non-obvious behavior
|
||||
|
||||
### 1. Web URI encoding: base64url(deflate(YAML))
|
||||
|
||||
`encodeWebURI` compresses the YAML-encoded file description with raw DEFLATE, then base64url-encodes the result. `decodeWebURI` reverses this. The compressed description goes in the URL fragment (after `#`), which is never sent to the router — the file description stays client-side.
|
||||
|
||||
### 2. CLI receive accepts both file paths and URLs
|
||||
|
||||
`getInputFileDescription` checks if the input starts with `http://` or `https://`. If so, it extracts the URL fragment, decodes it via `decodeWebURI`, and uses the resulting file description. Otherwise, it reads a YAML file from disk. This allows receiving files via web links without a browser.
|
||||
|
||||
### 3. Redirect chain depth limited to 1
|
||||
|
||||
`receive` tracks a `depth` parameter starting at 1. After following one redirect, `depth` becomes 0. A second redirect throws "Redirect chain too long". This prevents infinite redirect loops from malicious file descriptions.
|
||||
|
||||
### 4. Parallel data packet uploads with router grouping
|
||||
|
||||
`uploadFile` groups data packets by router via `groupAllOn`, then uses `pooledForConcurrentlyN 16` to process up to 16 router-groups concurrently. Within each group, data packets are uploaded sequentially (`mapM`). Errors from any upload are collected and the first one is thrown.
|
||||
|
||||
### 5. Random router selection
|
||||
|
||||
`getXFTPServer` selects a random router from the provided list for each chunk. With a single router, it's deterministic. With multiple routers, it uses `StdGen` in a TVar for thread-safe random selection via `stateTVar`.
|
||||
|
||||
### 6. withReconnect nests retry with reconnection
|
||||
|
||||
`withReconnect` wraps `withRetry` twice: the outer retry reconnects to the router, and the inner operation runs against the connection. On failure, the router connection is explicitly closed before retrying, forcing a fresh connection on the next attempt.
|
||||
|
||||
### 7. withRetry rejects zero retries
|
||||
|
||||
`withRetry' 0` returns an "internal: no retry attempts" error. `withRetry' 1` executes the action once without retry. This off-by-one convention means `retryCount = 3` (the default) gives 3 total attempts (1 initial + 2 retries).
|
||||
|
||||
### 8. File description auto-deletion prompt
|
||||
|
||||
After successful receive or delete, `removeFD` either auto-deletes the file description (if `--yes` flag) or prompts the user. This prevents accidental reuse of one-time file descriptions — each receive consumes the description by ACKing data packets on the router.
|
||||
|
||||
### 9. Sender description uses first replica's router
|
||||
|
||||
`createSndFileDescription` takes the router from the first replica of each chunk for the sender's `FileChunkReplica`. This reflects the current limitation that each data packet is uploaded to exactly one router — the sender description records that single router.
|
||||
@@ -1,31 +0,0 @@
|
||||
# Simplex.FileTransfer.Crypto
|
||||
|
||||
> File encryption and decryption with streaming, padding, and auth tag verification.
|
||||
|
||||
**Source**: [`FileTransfer/Crypto.hs`](../../../../src/Simplex/FileTransfer/Crypto.hs)
|
||||
|
||||
## Non-obvious behavior
|
||||
|
||||
### 1. Embedded file header in encrypted stream
|
||||
|
||||
`encryptFile` prepends the `FileHeader` (containing filename and optional `fileExtra`) to the plaintext before encryption. A total data size field (8 bytes, `fileSizeLen`) is prepended before the header, encoding the combined size of header + file content. The decryptor uses this to distinguish real data from padding. The recipient must parse the header after decryption to recover the original filename — the header is not transmitted separately.
|
||||
|
||||
### 2. Fixed-size padding hides actual file size
|
||||
|
||||
The encrypted output is padded to `encSize` (the sum of data packet sizes). Since data packet sizes are fixed powers of 2 (64KB, 256KB, 1MB, 4MB), the encrypted file size reveals only which size bucket the file falls into, not the actual size. The encryption streams data with `LC.sbEncryptChunk` in a loop, pads the remaining space, then manually appends the auth tag via `LC.sbAuth`. This manual streaming approach (rather than using the all-at-once `LC.sbEncryptTailTag`) is necessary because encryption is interleaved with file I/O.
|
||||
|
||||
### 3. Dual decrypt paths: single-chunk vs multi-chunk
|
||||
|
||||
`decryptChunks` takes different paths based on chunk count:
|
||||
- **Single chunk**: reads the entire file into memory via `LB.readFile`, decrypts in-memory with `LC.sbDecryptTailTag`
|
||||
- **Multiple chunks**: opens the destination file for writing and streams through each chunk file with `LC.sbDecryptChunkLazy` (lazy bytestring variant), verifying the auth tag from the final chunk
|
||||
|
||||
The single-chunk path avoids file handle management overhead for small files.
|
||||
|
||||
### 4. Auth tag failure deletes output file
|
||||
|
||||
In the multi-chunk streaming path, if `BA.constEq` detects an auth tag mismatch after decrypting all chunks, the partially-written output file is deleted before returning `FTCEInvalidAuthTag`. This prevents consumers from using a file whose integrity is unverified.
|
||||
|
||||
### 5. Streaming encryption uses 64KB blocks
|
||||
|
||||
`encryptFile` reads plaintext in 65536-byte blocks (`LC.sbEncryptChunk`), regardless of the XFTP data packet size. These are encryption blocks within a single continuous stream — not to be confused with XFTP data packets which are much larger (64KB–4MB).
|
||||
@@ -1,43 +0,0 @@
|
||||
# Simplex.FileTransfer.Description
|
||||
|
||||
> File description: YAML encoding/decoding, validation, URI format, and replica optimization. A file description maps a file's chunks to data packets stored on XFTP routers — each chunk corresponds to one data packet, and each data packet may have multiple replicas on different routers.
|
||||
|
||||
**Source**: [`FileTransfer/Description.hs`](../../../../src/Simplex/FileTransfer/Description.hs)
|
||||
|
||||
## Non-obvious behavior
|
||||
|
||||
### 1. ValidFileDescription non-exported constructor
|
||||
|
||||
`ValidFileDescription` is a newtype with a non-exported data constructor (`ValidFD`), but the module exports a bidirectional pattern synonym `ValidFileDescription` that can be used as a constructor. Despite this, `validateFileDescription` provides the canonical validation path, checking:
|
||||
- Chunk numbers are sequential starting from 1
|
||||
- Total chunk sizes equal the declared file size
|
||||
|
||||
Note: an empty chunk list with size 0 passes validation — there is no explicit "at least one chunk" check.
|
||||
|
||||
### 2. First-replica-only digest and chunkSize
|
||||
|
||||
When encoding chunks to YAML via `unfoldChunksToReplicas`, the `digest` and non-default `chunkSize` fields are only included on the first replica of each chunk. Subsequent replicas of the same chunk omit these fields. `foldReplicasToChunks` reconstructs them by carrying forward the digest/size from the first replica. If replicas have conflicting digests or sizes, validation fails.
|
||||
|
||||
### 3. Default chunkSize elision
|
||||
|
||||
The top-level `FileDescription` has a `chunkSize` field. Individual chunk replicas only serialize their `chunkSize` if it differs from this default. This saves space in the common case where most chunks are the same size (only the last chunk may be smaller).
|
||||
|
||||
### 4. YAML encoding groups replicas by router
|
||||
|
||||
`groupReplicasByServer` groups all data packet replicas by their router, producing `FileServerReplica` records. This is the serialization format — replicas are organized by router, not by chunk. The parser (`foldReplicasToChunks`) reverses this grouping back to per-chunk replica lists.
|
||||
|
||||
### 5. FileDescriptionURI uses query-string encoding
|
||||
|
||||
`FileDescriptionURI` serializes file descriptions into a compact query-string format (key=value pairs separated by `&`) with `QEscape` encoding for binary values. This is distinct from the YAML format used for file-based descriptions. The URI format is designed for embedding in links.
|
||||
|
||||
### 6. QR code size limit
|
||||
|
||||
`qrSizeLimit = 1002` bytes limits the maximum size of a file description URI that can be encoded as a QR code. Descriptions exceeding this limit cannot be shared via QR code and require alternative transport.
|
||||
|
||||
### 7. Soft and hard file size limits
|
||||
|
||||
Two limits exist: `maxFileSize = 1GB` (soft limit, checked by CLI client) and `maxFileSizeHard = 5GB` (hard limit, checked during agent-side encryption). The soft limit is a user-facing guard; the hard limit prevents resource exhaustion during encryption.
|
||||
|
||||
### 8. Redirect file descriptions
|
||||
|
||||
A `FileDescription` can contain a `redirect` field pointing to another file's metadata (`RedirectFileInfo` with size and digest). The outer description downloads an encrypted YAML data packet that, once decrypted, yields the actual `FileDescription` for the real file. This adds one level of indirection for privacy — the routers hosting the redirect data packet don't know the actual file's routers.
|
||||
@@ -1,36 +0,0 @@
|
||||
# Simplex.FileTransfer.Protocol
|
||||
|
||||
> XFTP protocol types, commands, command results, and credential verification.
|
||||
|
||||
**Source**: [`FileTransfer/Protocol.hs`](../../../../src/Simplex/FileTransfer/Protocol.hs)
|
||||
|
||||
## Non-obvious behavior
|
||||
|
||||
### 1. Asymmetric credential checks by command
|
||||
|
||||
`checkCredentials` enforces different rules per command:
|
||||
- **FNEW**: requires `auth` (signature) but must NOT have a `fileId` — the sender key from the command body is used for verification
|
||||
- **PING**: must have NEITHER `auth` NOR `fileId` — actively rejects their presence
|
||||
- **All others** (FADD, FPUT, FDEL, FGET, FACK): require both `fileId` AND auth key
|
||||
|
||||
This asymmetry means FNEW and PING bypass the standard entity-lookup path entirely — they are handled as separate `XFTPRequest` constructors (`XFTPReqNew`, `XFTPReqPing`).
|
||||
|
||||
### 2. BLOCKED result downgraded to AUTH for old clients
|
||||
|
||||
`encodeProtocol` checks the protocol version: if `v < blockedFilesXFTPVersion`, a `BLOCKED` result is encoded as `AUTH` instead. This prevents old clients that don't understand `BLOCKED` from receiving an unknown error type. The blocking information is silently lost for these clients.
|
||||
|
||||
### 3. Single-transmission batch enforcement
|
||||
|
||||
`xftpDecodeTServer` calls `xftpDecodeTransmission` which rejects batches containing more than one transmission. Despite using the batch framing format (length-prefixed), XFTP requires exactly one command per request. This differs from SMP where true batching is supported.
|
||||
|
||||
### 4. xftpEncodeBatch1 always uses batch framing
|
||||
|
||||
Even for single transmissions, `xftpEncodeBatch1` wraps the encoded transmission in batch format (1-byte count prefix + 2-byte length-prefixed transmission). There is no "non-batch" mode in XFTP — all protocol messages use the batch wire format regardless of the negotiated version.
|
||||
|
||||
### 5. FileParty GADT partitions command space
|
||||
|
||||
Commands are indexed by `FileParty` (`SFSender` / `SFRecipient`) at the type level via `FileCmd`. This ensures at compile time that sender commands (FNEW, FADD, FPUT, FDEL) and recipient commands (FGET, FACK, PING) cannot be confused. The router pattern-matches on `SFileParty` to determine which index (sender vs recipient) to look up in the file store.
|
||||
|
||||
### 6. Empty corrId and implicit session ID
|
||||
|
||||
`sendXFTPCommand` in the client uses an empty bytestring as `corrId`. This empty value is passed to `C.cbNonce` to produce a constant nonce for command authentication (HMAC/signing). With `implySessId = False` in the default XFTP transport setup, the session ID is not prepended to entity IDs during parsing. Session identity is provided by the TLS connection itself.
|
||||
@@ -1,87 +0,0 @@
|
||||
# Simplex.FileTransfer.Server
|
||||
|
||||
> XFTP router: HTTP/2 request handling, handshake state machine, data packet operations, and statistics.
|
||||
|
||||
**Source**: [`FileTransfer/Server.hs`](../../../../src/Simplex/FileTransfer/Server.hs)
|
||||
|
||||
## Architecture
|
||||
|
||||
The XFTP router runs several concurrent threads via `raceAny_`:
|
||||
|
||||
| Thread | Purpose |
|
||||
|--------|---------|
|
||||
| `runServer` | HTTP/2 router accepting data packet transfer requests |
|
||||
| `expireFiles` | Periodic data packet expiration with throttling |
|
||||
| `logServerStats` | Periodic stats flush to CSV |
|
||||
| `savePrometheusMetrics` | Periodic Prometheus metrics dump |
|
||||
| `runCPServer` | Control port for admin commands |
|
||||
|
||||
See [spec/routers.md](../../routers.md) for component and sequence diagrams.
|
||||
|
||||
## Non-obvious behavior
|
||||
|
||||
### 1. Three-state handshake with session caching
|
||||
|
||||
The router maintains a `TMap SessionId Handshake` with three states:
|
||||
- **No entry**: first request — for non-SNI or `xftp-web-hello` requests, `processHello` generates DH key pair and sends router handshake; for SNI requests without `xftp-web-hello`, returns `SESSION` error
|
||||
- **`HandshakeSent pk`**: router hello sent, waiting for client handshake with version negotiation
|
||||
- **`HandshakeAccepted thParams`**: handshake complete, subsequent requests use cached params
|
||||
|
||||
Web clients can re-send hello (`xftp-web-hello` header) even in `HandshakeSent` or `HandshakeAccepted` states — the router reuses the existing private key rather than generating a new one.
|
||||
|
||||
### 2. Web identity proof via challenge-response
|
||||
|
||||
When a web client sends a hello with a non-empty body, the router parses an `XFTPClientHello` containing a `webChallenge`. The router signs `challenge <> sessionId` with its long-term key and includes the signature in the handshake result. This proves router identity to web clients that cannot verify TLS certificates directly.
|
||||
|
||||
### 3. skipCommitted drains request body on re-upload
|
||||
|
||||
If `receiveServerFile` detects the data packet is already uploaded (`filePath` TVar is `Just`), it cannot simply ignore the request body — the HTTP/2 client would block waiting for the router to consume it. Instead, `skipCommitted` reads and discards the entire body in `fileBlockSize` increments, returning `FROk` when complete. This makes FPUT idempotent from the client's perspective.
|
||||
|
||||
### 4. Atomic quota reservation with rollback
|
||||
|
||||
`receiveServerFile` uses `stateTVar` to atomically check and reserve storage quota before receiving the data packet. If the upload fails (timeout, size mismatch, IO error), the reserved size is subtracted from `usedStorage` and the partial data packet is deleted on the router. This prevents failed uploads from permanently consuming quota.
|
||||
|
||||
### 5. retryAdd generates new IDs on collision
|
||||
|
||||
`createFile` and `addRecipient` use `retryAdd` which generates a random ID and makes up to 3 total attempts (initial + 2 retries) on `DUPLICATE_` errors. This handles the astronomically unlikely case of random ID collision without requiring uniqueness checking before insertion.
|
||||
|
||||
### 6. Timing attack mitigation on entity lookup
|
||||
|
||||
`verifyXFTPTransmission` calls `dummyVerifyCmd` (imported from SMP router) when a data packet entity is not found. This equalizes result timing to prevent attackers from distinguishing "entity doesn't exist" from "signature invalid" based on latency.
|
||||
|
||||
### 7. BLOCKED vs EntityOff distinction
|
||||
|
||||
When `verifyXFTPTransmission` reads `fileStatus`:
|
||||
- `EntityActive` → proceed with command
|
||||
- `EntityBlocked info` → return `BLOCKED` with blocking reason
|
||||
- `EntityOff` → return `AUTH` (same as entity-not-found)
|
||||
|
||||
`EntityOff` is treated identically to missing entities for information-hiding purposes.
|
||||
|
||||
### 8. blockServerFile deletes the stored data packet
|
||||
|
||||
Despite the name suggesting it only marks a data packet as blocked, `blockServerFile` also deletes the stored data packet from disk via `deleteOrBlockServerFile_`. The `deleted = True` parameter to `blockFile` in the store adjusts `usedStorage`. A blocked data packet returns `BLOCKED` errors on access but has no data on disk.
|
||||
|
||||
### 9. Stats restore overrides counts from live store
|
||||
|
||||
`restoreServerStats` loads stats from the backup file but overrides `_filesCount` and `_filesSize` with values computed from the live file store (TMap size and `usedStorage` TVar). If the backup values differ, warnings are logged. This handles cases where data packets were expired or deleted while the router was down.
|
||||
|
||||
### 10. Data packet expiration with configurable throttling
|
||||
|
||||
`expireServerFiles` accepts an optional `itemDelay` (100ms when called from the periodic thread, `Nothing` at router startup). Between each data packet check, `threadDelay itemDelay` prevents expiration from monopolizing IO. At startup, data packets are expired without delay to clean up quickly.
|
||||
|
||||
### 11. Stats log aligns to wall-clock midnight
|
||||
|
||||
`logServerStats` computes an `initialDelay` to align the first stats flush to `logStatsStartTime` (default 0 = midnight UTC). If the target time already passed today, it adds 86400 seconds for the next day. Subsequent flushes use exact `logInterval` cadence.
|
||||
|
||||
### 12. Stored data packet deleted before store cleanup
|
||||
|
||||
`deleteOrBlockServerFile_` removes the stored data packet first, then runs the STM store action. If the process crashes between these two operations, the store will reference a data packet that no longer exists on disk. The next access would return `AUTH` (data packet not found on disk), and eventual expiration would clean the store entry.
|
||||
|
||||
### 13. SNI-dependent CORS and web serving
|
||||
|
||||
CORS headers require both `sniUsed = True` and `addCORSHeaders = True` in the transport config. Static web page serving is enabled when `sniUsed = True`. Non-SNI connections (direct TLS without hostname) skip both CORS and web serving. This separates the web-facing and protocol-facing behaviors of the same router port.
|
||||
|
||||
### 14. Control port data packet operations use recipient index
|
||||
|
||||
`CPDelete` and `CPBlock` commands look up data packets via `getFile fs SFRecipient fileId`, meaning the control port takes a recipient ID, not a sender ID. This is the ID visible to recipients and contained in data packet descriptions.
|
||||
@@ -1,24 +0,0 @@
|
||||
# Simplex.FileTransfer.Server.Env
|
||||
|
||||
> XFTP router environment: configuration, storage quota tracking, and request routing.
|
||||
|
||||
**Source**: [`FileTransfer/Server/Env.hs`](../../../../../src/Simplex/FileTransfer/Server/Env.hs)
|
||||
|
||||
## Non-obvious behavior
|
||||
|
||||
### 1. Startup storage accounting with quota warning
|
||||
|
||||
`newXFTPServerEnv` computes `usedStorage` by summing data packet sizes from the in-memory store at startup. If the computed usage exceeds the configured `fileSizeQuota`, a warning is logged but the router still starts. This allows the router to come up even if it's over quota (e.g., after a quota reduction), relying on expiration to reclaim space.
|
||||
|
||||
### 2. XFTPRequest ADT separates new data packets from commands
|
||||
|
||||
`XFTPRequest` has three constructors:
|
||||
- `XFTPReqNew`: data packet creation (carries `FileInfo`, recipient keys, optional basic auth)
|
||||
- `XFTPReqCmd`: command on an existing data packet (carries file ID, `FileRec`, and the command)
|
||||
- `XFTPReqPing`: health check
|
||||
|
||||
This separation occurs after credential verification in `Server.hs`. `XFTPReqNew` bypasses entity lookup entirely since the data packet doesn't exist yet.
|
||||
|
||||
### 3. fileTimeout for upload deadline
|
||||
|
||||
`fileTimeout` in `XFTPServerConfig` sets the maximum time allowed for a single data packet upload (FPUT). The router wraps the receive operation in `timeout fileTimeout`. Default is 5 minutes (for 4MB chunks). This prevents slow or stalled uploads from holding router resources indefinitely.
|
||||
@@ -1,28 +0,0 @@
|
||||
# Simplex.FileTransfer.Server.Main
|
||||
|
||||
> XFTP router CLI: INI configuration parsing, TLS setup, and default constants.
|
||||
|
||||
**Source**: [`FileTransfer/Server/Main.hs`](../../../../../src/Simplex/FileTransfer/Server/Main.hs)
|
||||
|
||||
## Non-obvious behavior
|
||||
|
||||
### 1. Key router constants
|
||||
|
||||
| Constant | Value | Purpose |
|
||||
|----------|-------|---------|
|
||||
| `fileIdSize` | 16 bytes | Random data packet/recipient ID length |
|
||||
| `fileTimeout` | 5 minutes | Maximum upload duration per chunk |
|
||||
| `logStatsInterval` | 86400s (daily) | Stats CSV flush interval |
|
||||
| `logStatsStartTime` | 0 (midnight UTC) | First stats flush time-of-day |
|
||||
|
||||
### 2. allowedChunkSizes defaults to all four sizes
|
||||
|
||||
If not configured, `allowedChunkSizes` defaults to `[kb 64, kb 256, mb 1, mb 4]`. The INI file can restrict this to a subset, controlling which chunk sizes the router accepts.
|
||||
|
||||
### 3. Storage quota from INI with unit parsing
|
||||
|
||||
`fileSizeQuota` is parsed from the INI `[STORE_LOG]` section using `FileSize` parsing, which accepts byte values with optional unit suffixes (KB, MB, GB). Absence means unlimited quota (`Nothing`).
|
||||
|
||||
### 4. Dual TLS credential support
|
||||
|
||||
The router supports both primary TLS credentials (`caCertificateFile`/`certificateFile`/`privateKeyFile`) and optional HTTP-specific credentials (`httpCaCertificateFile`/etc.). When HTTP credentials are present, the router uses `defaultSupportedParamsHTTPS` which enables broader TLS compatibility for web clients.
|
||||
@@ -1,19 +0,0 @@
|
||||
# Simplex.FileTransfer.Server.Stats
|
||||
|
||||
> XFTP router statistics: IORef-based counters with backward-compatible persistence.
|
||||
|
||||
**Source**: [`FileTransfer/Server/Stats.hs`](../../../../../src/Simplex/FileTransfer/Server/Stats.hs)
|
||||
|
||||
## Non-obvious behavior
|
||||
|
||||
### 1. setFileServerStats is not thread safe
|
||||
|
||||
`setFileServerStats` directly writes to IORefs without synchronization. It is explicitly intended for router startup only (restoring from backup file), before any concurrent threads are running.
|
||||
|
||||
### 2. Backward-compatible parsing
|
||||
|
||||
The `strP` parser uses `opt` for newer fields, defaulting missing fields to 0. This allows reading stats files from older router versions that don't include fields like `filesBlocked` or `fileDownloadAcks`.
|
||||
|
||||
### 3. PeriodStats for download tracking
|
||||
|
||||
`filesDownloaded` uses `PeriodStats` (not a simple `IORef Int`) to track unique data packet downloads over time periods (day/week/month). This enables the CSV stats log to report distinct data packets downloaded per period, not just total download count.
|
||||
@@ -1,39 +0,0 @@
|
||||
# Simplex.FileTransfer.Server.Store
|
||||
|
||||
> STM-based in-memory file store with dual indices, storage accounting, and privacy-preserving expiration.
|
||||
|
||||
**Source**: [`FileTransfer/Server/Store.hs`](../../../../../src/Simplex/FileTransfer/Server/Store.hs)
|
||||
|
||||
## Non-obvious behavior
|
||||
|
||||
### 1. Dual-index lookup by sender and recipient
|
||||
|
||||
The file store maintains two indices: `files :: TMap SenderId FileRec` (by sender ID) and `recipients :: TMap RecipientId (SenderId, RcvPublicAuthKey)` (by recipient ID, storing the sender ID and the recipient's public auth key). `getFile` dispatches on `SFileParty`: sender lookups use `files` directly, recipient lookups use `recipients` to find the `SenderId` then look up the `FileRec` in `files`. This means recipient operations require two TMap lookups.
|
||||
|
||||
### 2. addRecipient checks both inner Set and global TMap
|
||||
|
||||
`addRecipient` first checks the per-file `recipientIds` Set for duplicates, then inserts into the global `recipients` TMap. If either has a collision, it returns `DUPLICATE_`. The dual check is necessary because the Set tracks per-file membership while the TMap enforces global uniqueness of recipient IDs.
|
||||
|
||||
### 3. Storage accounting on upload completion
|
||||
|
||||
`setFilePath` adds the data packet size to `usedStorage` and records the file path in the `filePath` TVar. However, during normal FPUT handling, `Server.hs` does NOT call `setFilePath` — it directly writes `filePath` via `writeTVar`. The quota reservation in `Server.hs` (`stateTVar` on `usedStorage`) is the sole `usedStorage` increment during upload. `setFilePath` IS called during store log replay (`StoreLog.hs`), where it increments `usedStorage`; `newXFTPServerEnv` then overwrites with the correct value computed from the live store.
|
||||
|
||||
### 4. deleteFile removes all recipients atomically
|
||||
|
||||
`deleteFile` atomically removes the sender entry from `files`, all recipient entries from the global `recipients` TMap, and unconditionally subtracts the data packet size from `usedStorage` (regardless of whether the data packet was actually uploaded). The entire operation runs in a single STM transaction.
|
||||
|
||||
### 5. RoundedSystemTime for privacy-preserving expiration
|
||||
|
||||
Data packet timestamps use `RoundedFileTime` which is `RoundedSystemTime 3600` — system time rounded to 1-hour precision. This means data packets created within the same hour have identical timestamps. An observer with access to the store cannot determine exact data packet creation times, only the hour.
|
||||
|
||||
### 6. expiredFilePath returns path only if expired
|
||||
|
||||
`expiredFilePath` returns `STM (Maybe (Maybe FilePath))`. The outer `Maybe` is `Nothing` when the data packet doesn't exist or isn't expired; the inner `Maybe` is the file path (present only if the data packet was uploaded). The expiration check adds `fileTimePrecision` (one hour) to the creation timestamp before comparing, providing a grace period. The caller uses the inner path to decide whether to also delete the stored data packet.
|
||||
|
||||
### 7. ackFile removes single recipient
|
||||
|
||||
`ackFile` removes a specific recipient from both the global `recipients` TMap and the per-file `recipientIds` Set. Unlike `deleteFile` which removes the entire data packet, `ackFile` only removes one recipient's access. The data packet and other recipients remain intact.
|
||||
|
||||
### 8. blockFile conditional storage adjustment
|
||||
|
||||
`blockFile` takes a `deleted :: Bool` parameter. When `True` (data packet blocked with physical deletion), it subtracts the data packet size from `usedStorage`. When `False` (block without deletion), storage is unchanged. This allows blocking without physical deletion for audit purposes. Currently, both the router's `blockServerFile` and the store log replay path pass `True`.
|
||||
@@ -1,33 +0,0 @@
|
||||
# Simplex.FileTransfer.Server.StoreLog
|
||||
|
||||
> Append-only store log for XFTP router data packet operations with error-resilient replay and compaction.
|
||||
|
||||
**Source**: [`FileTransfer/Server/StoreLog.hs`](../../../../../src/Simplex/FileTransfer/Server/StoreLog.hs)
|
||||
|
||||
## Non-obvious behavior
|
||||
|
||||
### 1. Error-resilient replay
|
||||
|
||||
`readFileStore` parses the store log line-by-line. Lines that fail to parse or fail to process (e.g., referencing a nonexistent sender ID) are logged as errors but do not halt replay. The store is reconstructed from whatever valid entries exist. This allows the router to recover from partial log corruption.
|
||||
|
||||
### 2. Sender ID validation on recipient writes
|
||||
|
||||
`writeFileStore` during compaction validates that each recipient's sender ID in the `recipients` TMap matches the `senderId` of the corresponding `FileRec`. This guards against in-memory state corruption (e.g., if a bug caused the `recipients` TMap and `FileRec.recipientIds` to get out of sync), not log corruption — the validation happens before writing the compacted log.
|
||||
|
||||
### 3. Backward-compatible status parsing
|
||||
|
||||
`AddFile` log entries include an `EntityStatus` field. The parser uses `<|> pure EntityActive` as a fallback, defaulting to `EntityActive` when the status field is missing. This allows reading store logs from older router versions that didn't record entity status.
|
||||
|
||||
### 4. Compaction on restart
|
||||
|
||||
`readFileStore` replays the full log to rebuild the in-memory store. The caller (in `Server/Env.hs`) then writes a fresh, compacted store log containing only the current state. This eliminates deleted entries and redundant operations, keeping the log size proportional to active state rather than total history.
|
||||
|
||||
### 5. Log entry types track operation lifecycle
|
||||
|
||||
Six log entry types capture the complete data packet lifecycle:
|
||||
- `AddFile`: data packet creation with sender ID, file info, timestamp, and status
|
||||
- `AddRecipients`: recipient registration (batched as `NonEmpty FileRecipient`) with sender ID association
|
||||
- `PutFile`: upload completion with file path
|
||||
- `DeleteFile`: data packet deletion by sender ID
|
||||
- `AckFile`: single recipient acknowledgment
|
||||
- `BlockFile`: data packet blocking with blocking info
|
||||
@@ -1,23 +0,0 @@
|
||||
# Simplex.FileTransfer.Transport
|
||||
|
||||
> XFTP protocol types, version negotiation, and encrypted file streaming with integrity verification.
|
||||
|
||||
**Source**: [`FileTransfer/Transport.hs`](../../../../src/Simplex/FileTransfer/Transport.hs)
|
||||
|
||||
## xftpClientHandshakeStub — XFTP doesn't use TLS handshake
|
||||
|
||||
`xftpClientHandshakeStub` always fails with `throwE TEVersion`. The source comment states: "XFTP protocol does not use this handshake method." The XFTP handshake is performed at the HTTP/2 layer — `XFTPServerHandshake` and `XFTPClientHandshake` are sent as HTTP/2 request/response bodies (see `FileTransfer/Client.hs` and `FileTransfer/Server.hs`).
|
||||
|
||||
## receiveSbFile — constant-time auth tag verification
|
||||
|
||||
`receiveSbFile` validates the authentication tag using `BA.constEq` (constant-time byte comparison). The auth tag is collected from the stream after all file data — if the file data ends mid-chunk, the remaining bytes of that chunk are used first, and a follow-up read provides the rest of the tag if needed.
|
||||
|
||||
## receiveFile_ — two-phase integrity verification
|
||||
|
||||
File reception has two verification phases:
|
||||
1. **During receive**: either size checking (plaintext via `hReceiveFile`) or auth tag validation (encrypted via `receiveSbFile`)
|
||||
2. **After receive**: `LC.sha256Hash` of the entire received file is compared to `chunkDigest`
|
||||
|
||||
## sendEncFile — auth tag appended after all chunks
|
||||
|
||||
`sendEncFile` streams encrypted chunks via `LC.sbEncryptChunk`, then sends `LC.sbAuth sbState` (the authentication tag) as a final frame when the remaining size reaches zero.
|
||||
@@ -1,27 +0,0 @@
|
||||
# Simplex.FileTransfer.Types
|
||||
|
||||
> Agent-side file transfer types: receive/send file records, status state machines, and chunk/replica structures. Chunks are the agent's view of file pieces; each chunk maps to a data packet on an XFTP router.
|
||||
|
||||
**Source**: [`FileTransfer/Types.hs`](../../../../src/Simplex/FileTransfer/Types.hs)
|
||||
|
||||
## Non-obvious behavior
|
||||
|
||||
### 1. Receive file status state machine
|
||||
|
||||
`RcvFileStatus` progresses: `RFSReceiving` → `RFSReceived` → `RFSDecrypting` → `RFSComplete`, with `RFSError` as a terminal state reachable from any non-complete state. The `RFSReceived` → `RFSDecrypting` transition is significant: all chunks are downloaded but decryption hasn't started. The local worker (server=Nothing) picks up files in `RFSReceived` status.
|
||||
|
||||
### 2. Send file status state machine
|
||||
|
||||
`SndFileStatus` progresses: `SFSNew` → `SFSEncrypting` → `SFSEncrypted` → `SFSUploading` → `SFSComplete`, with `SFSError` as terminal. The prepare worker handles `SFSNew` → `SFSEncrypted` (including retry from `SFSEncrypting`), while per-router upload workers handle `SFSUploading` → `SFSComplete`.
|
||||
|
||||
### 3. Encrypted file path convention
|
||||
|
||||
`sndFileEncPath` constructs the path as `prefixPath </> "xftp.encrypted"`. This is a convention shared between the agent (`Agent.hs`) and this module — both must agree on where the encrypted intermediate file lives relative to the prefix directory.
|
||||
|
||||
### 4. FileHeader fileExtra for future extension
|
||||
|
||||
`FileHeader` contains `fileName` and an optional `fileExtra :: Maybe Text` field. Currently unused (`Nothing` in all callers), it provides a forward-compatible extension point embedded in the encrypted file header without requiring protocol version changes.
|
||||
|
||||
### 5. authTagSize = 16 bytes
|
||||
|
||||
`authTagSize` is defined as `fromIntegral C.authTagSize` (16 bytes). This is the AES-GCM authentication tag appended to the encrypted file stream. It is included in the payload size calculation (`payloadSize = fileSize' + fileSizeLen + authTagSize`), which is then passed to `prepareChunkSizes` to determine data packet allocation.
|
||||
@@ -1,334 +0,0 @@
|
||||
# Simplex.Messaging.Agent
|
||||
|
||||
> Orchestration layer: duplex connection lifecycle, message processing dispatch, queue rotation, ratchet synchronization, and async command framework.
|
||||
|
||||
**Source**: [`Agent.hs`](../../../../../src/Simplex/Messaging/Agent.hs)
|
||||
|
||||
**See also**: [Agent/Client.md](./Agent/Client.md) — the infrastructure layer (AgentClient, worker framework, protocol client lifecycle, subscription state, operation suspension).
|
||||
|
||||
**Protocol spec**: [`agent-protocol.md`](../../../../protocol/agent-protocol.md) — duplex connection procedure, agent message syntax.
|
||||
|
||||
## Overview
|
||||
|
||||
This module is the top-level SimpleX agent, consumed by simplex-chat and other client applications. It passes specific worker bodies, task queries, and handler logic into the frameworks defined in [Agent/Client.hs](./Agent/Client.md), and implements the orchestration policies: duplex handshake, queue rotation, ratchet synchronization, message integrity validation.
|
||||
|
||||
### Agent startup — backgroundMode
|
||||
|
||||
`getSMPAgentClient_` accepts a `backgroundMode` flag that fundamentally changes agent capabilities:
|
||||
- **Normal mode** (`backgroundMode = False`): starts four threads raced via `raceAny_` — `subscriber` (main event loop), `runNtfSupervisor` (notification management), `cleanupManager` (garbage collection), `logServersStats` (statistics). Also restores persisted router statistics. If any thread crashes, all are cancelled; statistics are saved in a `finally` block.
|
||||
- **Background mode** (`backgroundMode = True`): starts only the `subscriber` thread. No cleanup, no notifications, no stats persistence. Used when the agent needs minimal receive-only operation.
|
||||
|
||||
Thread crashes are caught by the `run` wrapper: if the agent is still active (`acThread` is set), the exception is reported as `CRITICAL True` to `subQ`. If the agent is being disposed, crashes are silently ignored.
|
||||
|
||||
### Service + entity session mode prohibition
|
||||
|
||||
Service certificates and entity transport session mode (`TSMEntity`) are mutually exclusive. This is checked in four places: `getSMPAgentClient_`, `setNetworkConfig`, `createUser'`, `setUserService'`. If violated, throws `CMD PROHIBITED`. The constraint exists because service certificates associate multiple queues under one identity, which contradicts entity session mode's goal of preventing queue correlation.
|
||||
|
||||
## Split-phase connection creation
|
||||
|
||||
`prepareConnectionLink` and `createConnectionForLink` separate link preparation (key generation, link formatting — no network) from queue creation (single network call). This prevents the race where a link is published before the queue exists on the router.
|
||||
|
||||
**Sender ID derivation.** The sender ID is deterministic: `SMP.EntityId $ B.take 24 $ C.sha3_384 corrId` where `corrId` is a random nonce. `createConnectionForLink` validates `actualSndId == sndId` — if the router returns a different sender ID, the connection is rejected. See source comment: "the remaining 24 bytes are reserved, possibly for notifier ID in the new notifications protocol."
|
||||
|
||||
**PQ restriction.** `IKUsePQ` is prohibited for prepared links — throws `CMD PROHIBITED`. PQ keys are too large for the short link format.
|
||||
|
||||
## Subscriber loop — processSMPTransmissions
|
||||
|
||||
The subscriber thread reads batches from `msgQ` (filled by SMP protocol clients) and dispatches to `processSMPTransmissions`. Each batch is processed within `agentOperationBracket c AORcvNetwork waitUntilActive`, tying into the operation suspension cascade.
|
||||
|
||||
**Batch UP notification accumulation.** Successful subscription confirmations (`processSubOk`) append to a shared `upConnIds` TVar across the batch. A single `UP` event is emitted after all transmissions are processed, not per-transmission. Similarly, `serviceRQs` accumulates service-associated receive queues for batch processing via `processRcvServiceAssocs`.
|
||||
|
||||
**Double validation for subscription results.** `isPendingSub` checks two conditions atomically: the queue must be in the pending map AND the client session must still be active (`activeClientSession`). If either fails, the result is counted as ignored (statistics only). This handles the race where a subscription result arrives after reconnection.
|
||||
|
||||
**SUB result piggybacking MSG.** When a SUB result arrives as `Right msg@SMP.MSG {}`, the connection is marked UP (via `processSubOk`) AND the MSG is processed. The UP notification happens even if the MSG processing fails — the connection is up regardless.
|
||||
|
||||
**subQ overflow to pendingMsgs.** `processSMP` writes events to `subQ` (bounded TBQueue) but when full, events go into a `pendingMsgs` TVar. After processing, pending messages are drained in reverse order (LIFO). This prevents the message processing thread from blocking on a full queue, which would stall the entire SMP client.
|
||||
|
||||
**END/ENDS session validation.** Both check `activeClientSession` before removing subscriptions. If the session doesn't match (stale disconnect), the event is logged but ignored.
|
||||
|
||||
## Message processing — processSMP
|
||||
|
||||
`processSMP` dispatches on the SMP message type within a per-connection lock (`withConnLock`).
|
||||
|
||||
### Four e2e key states
|
||||
|
||||
The MSG handler discriminates on `(e2eDhSecret, e2ePubKey_)`:
|
||||
|
||||
- `(Nothing, Just key)` — **Handshake**: computes DH, decrypts with per-queue E2E. Dispatches to `smpConfirmation` or `smpInvitation`.
|
||||
- `(Just dh, Nothing)` — **Established**: normal message flow. Dispatches to `AgentRatchetKey` or `AgentMsgEnvelope`.
|
||||
- `(Just dh, Just _)` — **Repeated confirmation**: only AgentConfirmation is accepted (ACK for previous one failed), everything else is rejected.
|
||||
- `(Nothing, Nothing)` — **Error**: no keys at all.
|
||||
|
||||
### ACK semantics
|
||||
|
||||
ACK is NOT automatic for `A_MSG` — the function returns `ACKPending` and the user must call `ackMessage`. ACK IS automatic for all control messages (HELLO, QADD, QKEY, QUSE, QTEST, EREADY, A_RCVD).
|
||||
|
||||
`handleNotifyAck` wraps the MSG processing: if any error occurs, it sends `ERR` to the client but still ACKs the SMP message. This prevents a processing error from causing infinite re-delivery.
|
||||
|
||||
### agentClientMsg — transactional message processing
|
||||
|
||||
Performs ratchet decryption, message parsing, and integrity checking inside a single `withStore` transaction with `lockConnForUpdate`. This serializes all message processing for a given connection, preventing concurrent ratchet state modifications. Returns the pre-decryption ratchet state (`rcPrev`) alongside the message — needed by `ereadyMsg` to decide whether to send EREADY.
|
||||
|
||||
### Additional queue status transitions on message receipt
|
||||
|
||||
When receiving an `AgentMsgEnvelope` on a non-Active queue, the queue is set to Active. For primary queues during rotation (`dbReplaceQueueId` is set), the new queue is set as primary and the old queue is scheduled for deletion via `ICQDelete`. This is how the receiving side completes queue rotation — any message on the new queue triggers cleanup of the old one.
|
||||
|
||||
### Duplicate message handling
|
||||
|
||||
Three paths for `A_DUPLICATE` errors:
|
||||
|
||||
1. **Stored and user-acked**: `getLastMsg` finds it with `userAck = True` → `ackDel`.
|
||||
2. **Stored, A_MSG, not user-acked**: re-notify the user with `MSG` event and return `ACKPending`. The user may not have seen the original.
|
||||
3. **Not stored or non-A_MSG**: `checkDuplicateHash` verifies the encrypted hash exists in the DB. If not, re-throws (real decryption failure, not duplicate).
|
||||
|
||||
For crypto errors (`A_CRYPTO`): if the encrypted hash already exists, suppressed (duplicate). If not, `notifySync` classifies via `cryptoErrToSyncState` (RSAllowed or RSRequired) and updates the connection's ratchet sync state.
|
||||
|
||||
### resetRatchetSync on successful decryption
|
||||
|
||||
When a double-ratchet message is successfully decrypted and the connection's ratchet sync state is not `RSOk` or `RSStarted`, the state is reset to `RSOk` and `RSYNC RSOk` is notified. Successful message delivery is the recovery signal for ratchet desynchronization.
|
||||
|
||||
### updateConnVersion — monotonic upgrade
|
||||
|
||||
Every received `AgentMsgEnvelope` triggers `updateConnVersion`. If the message's agent version is higher than the current agreed version and compatible, the agreed version is upgraded. Versions only increase. `safeVersionRange` handles the case where the sender's version exceeds the receiver's maximum — creates a range from `minVersion` to the sender's version.
|
||||
|
||||
## Duplex handshake
|
||||
|
||||
See [agent-protocol.md](../../../../protocol/agent-protocol.md) for the protocol description. Implementation-specific details:
|
||||
|
||||
### Initiating party (RcvConnection)
|
||||
|
||||
Receives AgentConfirmation with `e2eEncryption = Just sndParams`. Initializes the receive ratchet from the sender's E2E parameters. **v7+ (ratchetOnConfSMPAgentVersion)**: creates the ratchet immediately on confirmation processing, not later on `allowConnection`. See source comment on `processConf` — this supports decrypting messages that may arrive before `allowConnection` is called. The ratchet creation, E2E secret setup, and confirmation storage all happen in one `withStore` transaction.
|
||||
|
||||
### Accepting party (DuplexConnection)
|
||||
|
||||
Receives AgentConfirmation with `e2eEncryption = Nothing` and `AgentConnInfo` (not `AgentConnInfoReply`). The ratchet was already initialized during `joinConnection`. If `senderKey` is present, enqueues `ICDuplexSecure` (queue needs securing with SKEY). If absent (sender already secured via LKEY), sends `CON` immediately and sets the queue Active.
|
||||
|
||||
### HELLO exchange
|
||||
|
||||
HELLO is processed in `helloMsg`. The key dispatch is on `sndStatus`:
|
||||
- `sndStatus == Active`: this side already sent HELLO, so receiving HELLO means both sides are connected → emit `CON`.
|
||||
- Otherwise: this side hasn't sent HELLO yet → enqueue HELLO reply.
|
||||
|
||||
HELLO is not used in fast duplex connection (v9+ SMP with SKEY).
|
||||
|
||||
### startJoinInvitation — retry-safe ratchet creation
|
||||
|
||||
When retrying a join (existing `SndQueue`), `startJoinInvitation` tries to get the existing ratchet via `getSndRatchet` before creating a new one. If the ratchet exists, it reuses it. If not (error), it logs a non-blocking error via `nonBlockingWriteTBQueue` and creates a fresh ratchet. This prevents a retry from corrupting an already-established ratchet. The same pattern appears in `mkJoinInvitation` for contact URI joins.
|
||||
|
||||
### PQ support negotiation
|
||||
|
||||
PQ support is the AND of four conditions: the local client's PQ preference, the peer's agent version (>= `pqdrSMPAgentVersion`), the E2E encryption version (>= `pqRatchetE2EEncryptVersion`), and the connection's current PQ support. This negotiation happens at `joinConn` and `smpConfirmation` time via `versionPQSupport_` and `pqSupportAnd`.
|
||||
|
||||
## Queue rotation
|
||||
|
||||
Four agent messages implement queue rotation. See [agent-protocol.md](../../../../protocol/agent-protocol.md#rotating-messaging-queue) for the protocol. Implementation-specific details:
|
||||
|
||||
**QADD** (processed by sender in `qAddMsg`): Creates a new `SndQueue` with DH key exchange. Deletes any previous pending replacement (`delSqs` partitioned by `dbReplaceQId`). Responds with `QKEY`. The replacement chain means consecutive rotation requests are handled correctly — only the latest survives.
|
||||
|
||||
**QKEY** (processed by recipient in `qKeyMsg`): Validates queue is `New` or `Confirmed` and switch status is `RSSendingQADD`. Enqueues `ICQSecure` for async processing.
|
||||
|
||||
**QUSE** (processed by sender in `qUseMsg`): Marks new queue `Secured`. Sends `QTEST` **only to the new queue**.
|
||||
|
||||
**QTEST** (no handler in processSMP): Any message on the new queue triggers old queue deletion via `dbReplaceQueueId` logic. QTEST exists only to ensure at least one message traverses the new queue.
|
||||
|
||||
**Sender-side completion in delivery handler.** When `AM_QTEST_` is successfully sent in `runSmpQueueMsgDelivery`, the old send queue is removed from the connection: pending messages are deleted, the queue record is removed, and the old queue's delivery worker is deleted from `smpDeliveryWorkers` (stopping its thread). This happens inside `withConnLockNotify` to prevent deadlock with the subscriber.
|
||||
|
||||
**ICQDelete error tolerance.** In `runCommandProcessing`, if deleting the old receive queue fails with a permanent error (e.g., queue already gone on router), `finalizeSwitch` still runs — the local switch completes. Only temporary errors prevent completion.
|
||||
|
||||
**Ratchet sync guard**: All four message handlers check `ratchetSyncSendProhibited` before proceeding.
|
||||
|
||||
## Ratchet synchronization — newRatchetKey
|
||||
|
||||
When an `AgentRatchetKey` message is received, `newRatchetKey` handles ratchet re-establishment.
|
||||
|
||||
### Hash-ordering for initialization role
|
||||
|
||||
Both parties generate key pairs and exchange them. The party whose `rkHash(k1, k2)` is **lower** (lexicographic comparison) initializes the **receiving** ratchet; the other initializes **sending** and sends EREADY. This breaks the symmetry when both parties simultaneously request ratchet sync.
|
||||
|
||||
### State machine
|
||||
|
||||
- `RSOk`, `RSAllowed`, `RSRequired` → **receiving client**: generate new keys, send `AgentRatchetKey` reply, then proceed with hash-ordering.
|
||||
- `RSStarted` → **initiating client**: use keys already stored (from `synchronizeRatchet'`), proceed with hash-ordering.
|
||||
- `RSAgreed` → **error**: sets state to `RSRequired`, throws `RATCHET_SYNC`. Handles the edge case where both parties initiate simultaneously and one has completed.
|
||||
|
||||
### Deduplication
|
||||
|
||||
`checkRatchetKeyHashExists` prevents processing the same ratchet key twice. The hash is stored atomically before processing begins.
|
||||
|
||||
### EREADY
|
||||
|
||||
Sent when the ratchet was initialized as receiving (`rcSnd` is `Nothing` in the pre-decryption ratchet state). Carries `lastExternalSndId` so the other party knows which messages were sent with the old ratchet.
|
||||
|
||||
## Message integrity — checkMsgIntegrity
|
||||
|
||||
Sequential external sender ID + previous message hash chain. Five outcomes: `MsgOk` (sequential + hashes match), `MsgBadId` (ID from the past), `MsgDuplicate` (same ID), `MsgSkipped` (gap in sequence), `MsgBadHash` (sequential but hashes differ).
|
||||
|
||||
The integrity result is delivered to the client application via `MsgMeta`. The agent does not reject messages with integrity failures — it reports them and continues processing. The client decides the policy.
|
||||
|
||||
## Async command processing — runCommandProcessing
|
||||
|
||||
Uses the worker framework from [Agent/Client.hs](./Agent/Client.md#worker-framework). Keyed by `(connId, server)` — each connection/server combination gets its own command worker. Uses `AOSndNetwork` for operation suspension.
|
||||
|
||||
### Internal commands
|
||||
|
||||
- **ICAllowSecure**: User-initiated handshake completion (from `allowConnection`). On DuplexConnection (SKEY retry), if the error is temporary and the send queue's server differs from the command's server, the command is **moved** to the correct server queue via `updateCommandServer` + `getAsyncCmdWorker`. Returns `CCMoved` instead of `CCCompleted`.
|
||||
- **ICDuplexSecure**: Automatic handshake completion (from receiving AgentConnInfo with senderKey). Secures queue and sends HELLO.
|
||||
- **ICQSecure / ICQDelete**: Queue rotation — secure the new queue (KEY) and delete the old queue.
|
||||
- **ICAck / ICAckDel**: Send ACK to the router, optionally deleting the internal message record.
|
||||
- **ICDeleteConn**: No longer used, but may exist in old databases — cleaned up by deleting the command record.
|
||||
- **ICDeleteRcvQueue**: Queue cleanup during rotation.
|
||||
|
||||
### Retry semantics
|
||||
|
||||
`tryMoveableCommand` wraps execution with `withRetryInterval`: waits for `waitWhileSuspended` and `waitForUserNetwork`, then executes. Temporary/host errors trigger retry via `retrySndOp`. On success, the command is deleted. On permanent error, the error is notified and the command is deleted. `retrySndOp` separates `endAgentOperation`/`beginAgentOperation` into separate `atomically` blocks — see source comment: if `beginAgentOperation` blocks, `SUSPENDED` won't be sent.
|
||||
|
||||
### withConnLockNotify — deadlock prevention
|
||||
|
||||
Returns `Maybe ATransmission` and writes to `subQ` **after** releasing the lock. This prevents deadlock: if the lock holder writes to a full `subQ` while the subscriber thread needs the lock to process a message, both block indefinitely.
|
||||
|
||||
## Message delivery — runSmpQueueMsgDelivery
|
||||
|
||||
Per-queue delivery loop. Each `SndQueue` has its own worker keyed by queue address in `smpDeliveryWorkers`, paired with a `TMVar ()` retry lock (via `getAgentWorker'`).
|
||||
|
||||
### Deferred encryption
|
||||
|
||||
Message bodies are NOT encrypted at enqueue time. `enqueueMessageB` advances the ratchet header (`agentRatchetEncryptHeader`) and validates padding (`rcCheckCanPad`), but stores only the body reference (`sndMsgBodyId`) and encryption key (`encryptKey`, `paddedLen`). The actual message body encoding (`encodeAgentMsgStr`) and encryption (`rcEncryptMsg`) happen at delivery time. This allows the same body to be shared across multiple send queues via `sndMsgBodyId` — each delivery encrypts independently with its connection's ratchet.
|
||||
|
||||
For confirmation and ratchet key messages (AM_CONN_INFO, AM_CONN_INFO_REPLY, AM_RATCHET_INFO), the body is pre-encrypted and stored in `msgBody` directly — no deferred encryption.
|
||||
|
||||
### Per-message-type error handling
|
||||
|
||||
**QUOTA**: Checks `internalTs` against `quotaExceededTimeout`. If the message is older than the timeout, expires it and all subsequent expired messages in the queue (via `getExpiredSndMessages` → bulk `MERRS` notification). If not expired, sends `MWARN` and retries with `RISlow`. For confirmation messages (AM_CONN_INFO/AM_CONN_INFO_REPLY), QUOTA is treated as `NOT_AVAILABLE`.
|
||||
|
||||
**AUTH**: Per message type:
|
||||
- `AM_CONN_INFO` / `AM_CONN_INFO_REPLY` / `AM_RATCHET_INFO`: connection error `NOT_AVAILABLE`
|
||||
- `AM_HELLO_` with receive queue (initiating party): `NOT_AVAILABLE`. Without receive queue (joining party): `NOT_ACCEPTED`.
|
||||
- `AM_A_MSG_` / `AM_A_RCVD_` / `AM_QCONT_` / `AM_EREADY_`: delete message and notify `MERR`.
|
||||
- Queue rotation messages (`AM_QADD_` through `AM_QTEST_`): queue error with descriptive string.
|
||||
|
||||
**Timeout/network errors**: message-type-aware timeout — `AM_HELLO_` uses `helloTimeout`, all others use `messageTimeout`. If expired, uses `notifyDelMsgs` which expires the current message AND fetches all expired messages for the queue in bulk. If `serverHostError`, sends `MWARN` before retrying. Non-host temporary errors retry silently.
|
||||
|
||||
### Delivery success handling
|
||||
|
||||
On successful send, per message type:
|
||||
- `AM_CONN_INFO` with `senderCanSecure` (fast handshake): sends `CON` + sets status `Active`.
|
||||
- `AM_CONN_INFO` without `senderCanSecure`: sets status `Confirmed` only.
|
||||
- `AM_CONN_INFO_REPLY`: sets status `Confirmed`.
|
||||
- `AM_HELLO_`: sets status `Active`. If receive queue exists AND its status is `Active`, sends `CON` (accepting party in v2).
|
||||
- `AM_A_MSG_`: sends `SENT msgId proxySrv_` to notify the client.
|
||||
- `AM_QKEY_`: re-reads connection and sends `SWITCH QDSnd SPConfirmed`.
|
||||
- `AM_QTEST_`: see "Sender-side completion" under Queue rotation above.
|
||||
- All other types: no notification.
|
||||
|
||||
After success, the delivery record is deleted. For `AM_A_MSG_`, `keepForReceipt = True` — the record is kept until a receipt is received.
|
||||
|
||||
### withRetryLock2 — external retry signaling
|
||||
|
||||
The delivery loop uses `withRetryLock2` which combines the standard retry interval with `qLock` (the `TMVar ()` paired with the worker). When `A_QCONT` is received, the handler puts `()` into the retry lock, causing the retry to fire immediately instead of waiting for the backoff interval. See `continueSending` in `processSMP`.
|
||||
|
||||
### submitPendingMsg — operation counting
|
||||
|
||||
`submitPendingMsg` increments `opsInProgress` on `msgDeliveryOp` BEFORE spawning the delivery worker. This means the operation is counted even before the worker starts, ensuring the suspension cascade waits for all enqueued deliveries.
|
||||
|
||||
## Batch message sending — sendMessagesB_
|
||||
|
||||
### MsgReq grouping contract
|
||||
|
||||
Messages to the same connection must be contiguous in the traversable, with only the first having a non-empty `connId`. Subsequent messages for the same connection must have empty `connId`. This is validated by `addConnId` which rejects duplicate `connId` values and empty first `connId`. The `getConn_` function uses a `TVar prev` to cache the last connection lookup, avoiding redundant database reads.
|
||||
|
||||
### Connection locking
|
||||
|
||||
`withConnLocks` takes locks for ALL connections in the batch before processing. This prevents concurrent sends to the same connection from interleaving ratchet state updates.
|
||||
|
||||
### PQ support monotonic upgrade
|
||||
|
||||
When `pqEnc == PQEncOn` but the connection has `pqSupport == PQSupportOff`, PQ support is upgraded via `setConnPQSupport`. PQ support can only be enabled, never disabled. The upgrade IDs are accumulated via `mapAccumL` and applied in a single batch database write.
|
||||
|
||||
### VRValue/VRRef — database body deduplication
|
||||
|
||||
VRValue/VRRef deduplication operates at the **database body storage** level, not encryption. `enqueueMessageB` tracks an `IntMap (Maybe Int64, AMessage)` mapping integer indices to database body IDs (`sndMsgBodyId`):
|
||||
|
||||
- `VRValue (Just i) body`: stores the body in `snd_message_bodies`, records the `sndMsgBodyId`, and associates it with index `i` for future reference.
|
||||
- `VRRef i`: looks up index `i` to get the previously stored `sndMsgBodyId`, and creates a new `snd_messages` record linked to the same body.
|
||||
|
||||
Encryption is NOT deduplicated — each connection's ratchet header is independently advanced at enqueue time, and each delivery encrypts the body independently. The optimization is purely about avoiding redundant database storage of identical message bodies (common for group messages).
|
||||
|
||||
### Error propagation constraint
|
||||
|
||||
When a connection type is wrong (e.g., SndConnection, NewConnection), the error is returned per-message but the batch continues. See source comment: "we can't fail here, as it may prevent delivery of subsequent messages that reference the body of the failed message." If a VRValue message fails, subsequent VRRef messages that reference it would break.
|
||||
|
||||
## Subscription management
|
||||
|
||||
### subscribeConnections_
|
||||
|
||||
Partitions connections by type. SndConnection with `Confirmed` status returns success (it's not subscribed, just waiting). SndConnection with `Active` status returns `CONN SIMPLEX` (can't subscribe a send-only connection). After subscribing queues, resumes delivery workers for connections with pending deliveries (via `getConnectionsForDelivery`).
|
||||
|
||||
**Multi-queue result combining.** For connections with multiple receive queues, results are combined using a priority system: Active+Success (1) > Active+Error (2) > non-Active+Success (3) > non-Active+Error (4). The highest-priority (lowest number) result is used. This ensures that if at least one Active queue subscribes successfully, the connection reports success.
|
||||
|
||||
### subscribeAllConnections'
|
||||
|
||||
**Active user priority.** If `activeUserId_` is provided, that user's subscriptions are processed first (`sortOn`).
|
||||
|
||||
**Service subscription with fallback.** Service subscriptions are attempted first. If a service subscription fails with `SSErrorServiceId` or zero subscribed queues, the queues are unassociated from the service and subscribed individually. If the error is a client-level error (not a service-specific error), the same fallback applies.
|
||||
|
||||
**Pending throttle.** `maxPending` limits concurrent pending subscriptions. The counter is incremented inside the database transaction (before leaving `withStore'`) and decremented in a `finally` block. When the count exceeds the limit, `subscribeUserServer` blocks in STM via `retry`.
|
||||
|
||||
### resubscribeConnections'
|
||||
|
||||
Filters out connections that already have active subscriptions (via `hasActiveSubscription`). For store errors, returns `True` for `isActiveConn` — this causes the error to be processed by `subscribeConnections_` which will report it.
|
||||
|
||||
## Notification token lifecycle
|
||||
|
||||
`registerNtfToken'` is a complex state machine. Key non-obvious behavior: on `NTF AUTH` error during token operations, the token is removed and re-registered from scratch (see `withToken` catch of `NTF AUTH`). Device token changes trigger `replaceToken`, which attempts an in-place replacement; if that fails with a permanent error, the token is removed and recreated.
|
||||
|
||||
## Cleanup manager
|
||||
|
||||
Runs periodically with a `cleanupStepInterval` delay BETWEEN each cleanup operation (not just between cycles). This prevents cleanup from monopolizing database access.
|
||||
|
||||
Additional cleanup not previously mentioned:
|
||||
- **Expired receive message hashes**: `deleteRcvMsgHashesExpired`
|
||||
- **Expired send messages**: `deleteSndMsgsExpired`
|
||||
- **Expired ratchet key hashes**: `deleteRatchetKeyHashesExpired`
|
||||
- **Expired notification tokens**: `deleteExpiredNtfTokensToDelete`
|
||||
- **Expired send chunk replicas**: `deleteDeletedSndChunkReplicasExpired`
|
||||
|
||||
## Agent suspension
|
||||
|
||||
`suspendAgent` has two modes:
|
||||
- **Immediate** (`maxDelay = 0`): sets `ASSuspended` and suspends all operations immediately.
|
||||
- **Gradual** (`maxDelay > 0`): sets `ASSuspending` and triggers the cascade (NtfNetwork independent; RcvNetwork → MsgDelivery → SndNetwork → Database). A timeout thread fires after `maxDelay` and forces suspension of sending and database if still suspending.
|
||||
|
||||
`foregroundAgent` resumes in reverse order: database → sending → delivery → receiving → notifications.
|
||||
|
||||
## connectReplyQueues — background duplex upgrade
|
||||
|
||||
Used during async command processing to complete the duplex handshake. Handles two cases:
|
||||
- **Fresh connection** (`sq_ = Nothing`): upgrades `RcvConnection` to `DuplexConnection`.
|
||||
- **SKEY retry** (`sq_ = Just sq`): connection is already duplex. See source comment: "in case of SKEY retry the connection is already duplex."
|
||||
|
||||
## secureConfirmQueue vs secureConfirmQueueAsync
|
||||
|
||||
- **secureConfirmQueue** (synchronous): secures queue and sends confirmation directly via network. Used in `joinConnection`.
|
||||
- **secureConfirmQueueAsync** (asynchronous): secures queue, stores confirmation, submits to delivery worker. Used in `allowConnection` (via `ICAllowSecure`).
|
||||
|
||||
Both call `agentSecureSndQueue`, which returns `initiatorRatchetOnConf` — whether the initiator's ratchet should be created on confirmation (v7+ behavior). When the queue was already secured (retry), returns the same flag without re-securing.
|
||||
|
||||
## smpConfirmation — version compatibility
|
||||
|
||||
The confirmation handler accepts messages where the agent version or client version is either within the configured range OR at-or-below the already-agreed version. See source comment. This means a downgraded client can still complete in-progress handshakes.
|
||||
|
||||
## smpInvitation — contact address handling
|
||||
|
||||
Invitation messages received on a contact address are passed through even if version-incompatible. See source comment. The client application sees `REQ` with `PQSupportOff` when incompatible.
|
||||
|
||||
## ackMessage' — receipt sending
|
||||
|
||||
After ACKing a message, if the user provides receipt info (`rcptInfo_`), a receipt message (`A_RCVD`) is enqueued. Receipts are only allowed for `AM_A_MSG_` type. If the user ACKs without receipt info and the message already has a receipt with `MROk` status, the corresponding sent message is deleted from the database — it's confirmed delivered.
|
||||
|
||||
## acceptContactAsync' — rollback on failure
|
||||
|
||||
See source comment. Unlike the synchronous `acceptContact'` which takes a lock first, `acceptContactAsync'` marks the invitation as accepted before joining. On failure, `unacceptInvitation` rolls back. The comment notes this could be improved with an invitation lock map.
|
||||
|
||||
## prepareConnectionToJoin — race prevention
|
||||
|
||||
See source comment. Creates a connection record without queues, returning a `ConnId`. The caller saves this ID before the peer can send a confirmation. Without this, the sequence "joinConnection → peer sends confirmation → caller saves ConnId" could result in the confirmation arriving before the caller has the ID.
|
||||
@@ -1,300 +0,0 @@
|
||||
# Simplex.Messaging.Agent.Client
|
||||
|
||||
> Agent infrastructure layer: protocol client lifecycle, worker framework, subscription management, operation suspension, and concurrency primitives.
|
||||
|
||||
**Source**: [`Agent/Client.hs`](../../../../../../src/Simplex/Messaging/Agent/Client.hs)
|
||||
|
||||
**See also**: [Agent.hs](./Agent.md) — the orchestration layer that consumes these primitives.
|
||||
|
||||
## Overview
|
||||
|
||||
This module defines `AgentClient`, the central state container for the SimpleX agent, and all reusable infrastructure that Agent.hs and other consumers (NtfSubSupervisor.hs, FileTransfer/Agent.hs, simplex-chat) build upon. It covers:
|
||||
|
||||
- **Protocol client lifecycle**: lazy singleton connections to SMP/NTF/XFTP routers via `SessionVar` pattern, with disconnect callbacks and reconnection workers
|
||||
- **Worker framework**: `getAgentWorker` (lifecycle, restart rate limiting, crash recovery) + `withWork`/`withWork_`/`withWorkItems` (task retrieval with doWork flag atomics)
|
||||
- **Subscription state**: active/pending/removed queues, session-aware cleanup on disconnect, batch subscription RPCs with post-hoc session validation
|
||||
- **Operation suspension**: five `AgentOpState` TVars with cascade ordering for graceful shutdown
|
||||
- **Concurrency primitives**: per-connection locks, transport session batching, proxy routing
|
||||
|
||||
The module is consumed by Agent.hs (which passes specific worker bodies, task queries, and handler logic into these frameworks) and by external consumers that reuse the worker and protocol client infrastructure.
|
||||
|
||||
## AgentClient — central state container
|
||||
|
||||
`AgentClient` has ~43 fields, almost all TVars or TMaps. Key architectural groupings:
|
||||
|
||||
- **Event queues**: `subQ` (events to client application), `msgQ` (messages from SMP routers)
|
||||
- **Protocol client pools**: `smpClients`, `ntfClients`, `xftpClients` — all are TMaps of `TransportSession` → `SessionVar`, implementing lazy singletons via `getSessVar`
|
||||
- **Subscription tracking**: `currentSubs` (TSessionSubs, active+pending per transport session), `removedSubs` (failed subscriptions with errors), `subscrConns` (set of connection IDs currently subscribed)
|
||||
- **Worker pools**: `smpDeliveryWorkers`, `asyncCmdWorkers` — TMaps keyed by work address/connection. `smpSubWorkers` — TMaps keyed by transport session for resubscription.
|
||||
- **Operation states**: `ntfNetworkOp`, `rcvNetworkOp`, `msgDeliveryOp`, `sndNetworkOp`, `databaseOp`
|
||||
- **Locking**: `connLocks`, `invLocks`, `deleteLock`, `getMsgLocks`, `clientNoticesLock`
|
||||
- **Service state**: `useClientServices` (per-user boolean controlling whether service certificates are used)
|
||||
- **Proxy routing**: `smpProxiedRelays` (maps destination transport session → proxy router used)
|
||||
- **Network state**: `userNetworkInfo`, `userNetworkUpdated`, `useNetworkConfig` (slow/fast pair)
|
||||
|
||||
All TVars are initialized in `newAgentClient`. The `active` TVar is the global kill switch — `closeAgentClient` sets it to `False`, and all protocol client getters check it first.
|
||||
|
||||
## Protocol client lifecycle — SessionVar singleton pattern
|
||||
|
||||
Protocol client connections (SMP, NTF, XFTP) use a lazy singleton pattern implemented by [Session.hs](../../../Session.md):
|
||||
|
||||
1. **`getSessVar`** atomically checks the TMap. Returns `Left newVar` if absent (caller must connect), `Right existingVar` if present (caller waits for the TMVar).
|
||||
2. **`newProtocolClient`** wraps the connection attempt. On success, fills the `sessionVar` TMVar with `Right client` and writes a `CONNECT` event to `subQ`. On failure, fills with `Left (error, maybeRetryTime)` and re-throws.
|
||||
3. **`waitForProtocolClient`** reads the TMVar with a timeout. If the stored error has an expiry time that has passed, it removes the SessionVar and retries from scratch — this is the `persistErrorInterval` retry mechanism.
|
||||
|
||||
### Error caching with persistErrorInterval
|
||||
|
||||
When `newProtocolClient` fails and `persistErrorInterval > 0`, the error is cached with an expiry timestamp (`Just ts`). Future connection attempts during the interval immediately receive the cached error from `waitForProtocolClient` without attempting a connection. When `persistErrorInterval == 0`, the SessionVar is removed immediately on failure, so the next attempt starts a fresh connection. This prevents connection storms to unreachable routers.
|
||||
|
||||
### SessionVar compare-and-swap
|
||||
|
||||
`removeSessVar` (Session.hs) only removes a SessionVar from the map if its `sessionVarId` matches the current entry. The `sessionVarId` is a monotonically increasing counter from `workerSeq`. This prevents a stale disconnection callback from removing a *new* client that was created after the old one disconnected. Without this, the sequence "client A disconnects → client B connects → client A's callback runs" would incorrectly remove client B.
|
||||
|
||||
### SMP connection — service credentials and session setup
|
||||
|
||||
`smpConnectClient` connects an SMP client, with two important post-connection steps:
|
||||
|
||||
1. **Session ID registration**: `SS.setSessionId` records the TLS session ID in `currentSubs`, linking the transport session to the actual TLS connection for later session validation.
|
||||
|
||||
2. **Service credential synchronization** (`updateClientService`): After connecting, compares client-side and router-side service state. Four cases:
|
||||
- Both have service and IDs match → update DB (no-op if same)
|
||||
- Both have service but IDs differ → update DB and remove old queue-service associations
|
||||
- Client has service, router doesn't → delete client service (handles router version downgrade)
|
||||
- Router has service, client doesn't → log error (should not happen in normal flow)
|
||||
|
||||
On connection failure, `smpConnectClient` triggers `resubscribeSMPSession` before re-throwing the error. This ensures pending subscriptions get retry logic even when the initial connection attempt fails.
|
||||
|
||||
### SMP disconnect callback
|
||||
|
||||
`smpClientDisconnected` is the most complex disconnect handler (NTF/XFTP have simpler versions that remove the SessionVar and write a `DISCONNECT` event):
|
||||
|
||||
1. `removeSessVar` atomically removes the client if still current
|
||||
2. If `active`, moves active subscriptions to pending (only those matching the disconnecting client's `sessionId` — see next section)
|
||||
3. Removes proxied relay sessions that this client created
|
||||
4. Fires `DISCONNECT`, `DOWN`, and `SERVICE_DOWN` events for affected connections
|
||||
5. Releases GET locks for affected queues
|
||||
6. Triggers resubscription (see below)
|
||||
|
||||
**Resubscription mode switching**: The disconnect handler chooses between two resubscription paths based on whether the session mode matches the entity presence: `(mode == TSMEntity) == isJust cId`. When they match, it calls `resubscribeSMPSession` which handles both service and queue resubscription in a single worker. When they don't match (e.g., entity-mode session disconnects but there's also a shared session), it separately resubscribes the service and queues, because they belong to different transport sessions.
|
||||
|
||||
### Session-aware subscription cleanup
|
||||
|
||||
`removeClientAndSubs` (inside `smpClientDisconnected`) uses `SS.setSubsPending` with the disconnecting client's `sessionId`. Only subscriptions whose session ID matches the disconnecting client are moved to pending. If a new client already connected and made its own subscriptions active, those are *not* disturbed. This prevents the race: "old client disconnects → new client subscribes → old client's cleanup incorrectly demotes new client's subscriptions."
|
||||
|
||||
## ProtocolServerClient typeclass
|
||||
|
||||
Unifies SMP/NTF/XFTP client management with associated types:
|
||||
- `Client msg` — the connected client type (SMP wraps in `SMPConnectedClient` with proxied relay map; NTF and XFTP use the raw protocol client)
|
||||
- `ProtoClient msg` — the underlying protocol client for logging/closing
|
||||
|
||||
SMP is special: `SMPConnectedClient` bundles the protocol client with `proxiedRelays :: TMap SMPServer ProxiedRelayVar`, a per-connection map of relay sessions for proxy routing.
|
||||
|
||||
XFTP is special in a different way: its `getProtocolServerClient` ignores the `NetworkRequestMode` parameter and always uses `NRMBackground` for `waitForProtocolClient`. This means XFTP connections always use background timing regardless of the caller's request mode.
|
||||
|
||||
## Worker framework
|
||||
|
||||
Defined here, consumed by Agent.hs, NtfSubSupervisor.hs, FileTransfer/Agent.hs, and simplex-chat. Two separable parts:
|
||||
|
||||
### getAgentWorker — lifecycle management
|
||||
|
||||
Creates or reuses a worker for a given key. Workers are stored in a TMap keyed by their work address.
|
||||
|
||||
- **Create-or-reuse**: atomically checks the map. If absent, creates a new `Worker` (with `doWork` TMVar pre-filled with `()`). If present and `hasWork=True`, signals the existing worker.
|
||||
- **Fork**: `runWorkerAsync` takes the `action` TMVar. If `Nothing` (worker idle), it starts work. If `Just weakThreadId` (worker running), it puts the value back and returns. This bracket ensures at-most-one concurrent execution.
|
||||
- **Restart rate limiting**: on worker exit (success or error), `restartOrDelete` checks `restartCount` against `maxWorkerRestartsPerMin`. If under the limit, resets `action` to `Nothing` (idle), signals `hasWorkToDo`, and reports `INTERNAL` error. If over the limit, deletes the worker from the map and sends a `CRITICAL True` error. The restart only happens if the worker's `workerId` still matches the map entry — a stale restart from a replaced worker silently no-ops.
|
||||
|
||||
`getAgentWorker'` is the generic version with custom worker wrapper — used by `smpDeliveryWorkers` which pairs each Worker with a `TMVar ()` retry lock.
|
||||
|
||||
### withWork / withWork_ / withWorkItems — task retrieval
|
||||
|
||||
Takes `getWork` (fetch next task) and `action` (process it) as separate parameters. The consumer's worker body loops: `waitForWork doWork` → `withWork doWork getTask handleTask`.
|
||||
|
||||
**Critical: doWork flag race prevention.** `noWorkToDo` (clearing the flag) happens BEFORE `getWork` (querying for tasks), not after. This prevents the race where: (1) worker queries, finds nothing, (2) another thread adds work and sets the flag, (3) worker clears the flag — losing the signal. By clearing first, any concurrent signal after the query will be preserved.
|
||||
|
||||
**Error classification**: `withWork_` distinguishes work-item errors from store errors:
|
||||
- **Work item error** (`isWorkItemError`): the worker stops and sends `CRITICAL False`. The next iteration would likely produce the same error, so stopping prevents infinite loops.
|
||||
- **Store error**: the flag is re-set and an `INTERNAL` error is reported. The assumption is that store errors are transient (e.g., DB busy) and retrying may succeed.
|
||||
|
||||
`withWorkItems` handles batched work — a list of items where some may have individual errors. If all items are work-item errors, the worker stops. If only some are, the worker continues with the successful items and reports errors via `ERRS` event.
|
||||
|
||||
### runWorkerAsync — at-most-one execution
|
||||
|
||||
Uses a bracket on the `action` TMVar:
|
||||
- `takeTMVar action` — blocks if another thread is starting the worker (TMVar empty during start)
|
||||
- If the taken value is `Nothing` — worker is idle, start it. Store `Just weakThreadId` in the TMVar via `forkIO`.
|
||||
- If `Just _` — worker is already running, put it back and return.
|
||||
|
||||
The `Weak ThreadId` in `action` is a weak reference — it doesn't prevent the worker thread from being garbage collected. It is used by `cancelWorker`, which calls `deRefWeak` to get the thread ID and kills it; if the thread was already GC'd, the kill is a no-op. The primary lifecycle management is through the `restartOrDelete` chain in `getAgentWorker'`, not the weak reference.
|
||||
|
||||
### throwWhenNoDelivery — delivery worker self-termination
|
||||
|
||||
Delivery workers call `throwWhenNoDelivery` to check if their entry still exists in the `smpDeliveryWorkers` map. If the worker was removed (delivery complete), it throws `ThreadKilled` to terminate the worker thread. This is distinct from `throwWhenInactive` (which checks global `active` state) — it allows individual workers to be stopped without shutting down the entire agent.
|
||||
|
||||
## Operation suspension cascade
|
||||
|
||||
Five `AgentOpState` TVars track whether each operation category is suspended and how many operations are in-flight:
|
||||
|
||||
```
|
||||
AONtfNetwork (independent)
|
||||
AORcvNetwork → AOMsgDelivery → AOSndNetwork → AODatabase
|
||||
```
|
||||
|
||||
The cascade means:
|
||||
- `endAgentOperation AORcvNetwork` suspends `AOMsgDelivery`, which cascades to `AOSndNetwork` → `AODatabase`
|
||||
- `endAgentOperation AOMsgDelivery` suspends `AOSndNetwork` → `AODatabase`
|
||||
- `endAgentOperation AOSndNetwork` suspends `AODatabase`
|
||||
- Each leaf in the cascade calls `notifySuspended` (writes `SUSPENDED` to `subQ`, sets `agentState` to `ASSuspended`)
|
||||
|
||||
**`beginAgentOperation`** retries (blocks in STM) if the operation is suspended. This provides backpressure: new operations wait until the operation is resumed.
|
||||
|
||||
**`agentOperationBracket`** wraps an operation with begin/end. It takes a `check` function that runs before `beginAgentOperation` — typically `throwWhenInactive`, which throws `ThreadKilled` if the agent is inactive. All database access goes through `withStore` which brackets with `AODatabase`. This ensures graceful shutdown propagates: suspending `AORcvNetwork` eventually suspends all downstream operations, and `notifySuspended` only fires when all in-flight operations have completed.
|
||||
|
||||
**`waitWhileSuspended`** vs **`waitUntilForeground`**: `waitWhileSuspended` proceeds during `ASSuspending` (allowing in-flight operations to complete), while `waitUntilForeground` blocks during both `ASSuspending` and `ASSuspended`.
|
||||
|
||||
**`waitForUserNetwork`**: bounded wait for network — if the network doesn't come online within `userNetworkInterval`, proceeds anyway. Uses `registerDelay` for the timeout.
|
||||
|
||||
## Subscription management
|
||||
|
||||
### subscribeQueues — batch-by-transport-session
|
||||
|
||||
`subscribeQueues` is the main entry point for subscribing to receive queues:
|
||||
|
||||
1. `checkQueues` filters out queues with active GET locks (prevents concurrent GET + SUB on the same queue)
|
||||
2. `batchQueues` groups queues by transport session
|
||||
3. `addPendingSubs` marks all queues as pending before the RPC
|
||||
4. `mapConcurrently` subscribes each session batch in parallel
|
||||
|
||||
### subscribeSessQueues_ — post-hoc session validation and atomicity
|
||||
|
||||
After the subscription RPC completes, `subscribeSessQueues_` validates `activeClientSession` — checking that the SessionVar still holds the same client that was used for the RPC. If the client was replaced during the RPC (reconnection happened), the results are discarded (errors converted to temporary `BROKER NETWORK` to ensure retry) and resubscription is triggered.
|
||||
|
||||
The post-RPC processing runs under `uninterruptibleMask_` for atomicity. The sequence is:
|
||||
1. **Atomically**: `processSubResults` partitions results and updates subscription state; if there are client notices, takes `clientNoticesLock` TMVar
|
||||
2. **IO**: `processRcvServiceAssocs` updates service associations in the DB
|
||||
3. **IO**: `processClientNotices` updates notice state, always releases `clientNoticesLock` in `finally`
|
||||
|
||||
The `clientNoticesLock` TMVar serializes notice processing across concurrent subscription batches.
|
||||
|
||||
**UP events for newly-active connections only**: After processing, UP events are sent only for connections that were NOT already active before this batch — existing active subscriptions (from `SS.getActiveSubs`) are excluded to prevent duplicate notifications.
|
||||
|
||||
**Client close on all-temporary-error**: When ALL subscription results are temporary errors, no connections were already active, and the session is still current, the SMP client session is closed. This forces a fresh connection on the next attempt rather than reusing a potentially broken one.
|
||||
|
||||
### processSubResults — partitioning
|
||||
|
||||
Subscription results are partitioned into five categories:
|
||||
1. **Failed with client notice** — error has an associated router-side notice (e.g., queue status change). Queue is treated as failed (removed from pending, added to `removedSubs`) AND the notice is recorded for processing.
|
||||
2. **Failed permanently** — non-temporary error without notice, queue is removed from pending and added to `removedSubs`
|
||||
3. **Failed temporarily** — error is transient, queue stays in pending unchanged for retry on reconnect
|
||||
4. **Subscribed** — moved from pending to active. Further split into: queues whose service ID matches the session service (added as service-associated) and others. If the queue had a tracked `clientNoticeId`, it is cleared (notice resolved by successful subscription).
|
||||
5. **Ignored** — queue was not in the pending map (already activated by a concurrent path), counted for statistics only
|
||||
|
||||
### Resubscription worker
|
||||
|
||||
`resubscribeSMPSession` spawns a worker per transport session that retries pending subscriptions with exponential backoff (`withRetryForeground`). The worker:
|
||||
|
||||
1. Reads pending subs and pending service sub
|
||||
2. Waits for foreground and network
|
||||
3. Resubscribes service and queues
|
||||
4. Loops until no pending subs remain
|
||||
|
||||
**Spawn guard**: Before creating a new worker, `resubscribeSMPSession` checks `SS.hasPendingSubs`. If there are no pending subs, it returns without spawning. This prevents creating idle workers.
|
||||
|
||||
**Cleanup blocks on TMVar fill** — the `cleanup` STM action retries (`whenM (isEmptyTMVar $ sessionVar v) retry`) until the async handle is inserted. This prevents the race where cleanup runs before the worker async is stored, which would leave a terminated worker in the map.
|
||||
|
||||
## Proxy routing — sendOrProxySMPCommand
|
||||
|
||||
Implements SMP proxy/direct routing with fallback:
|
||||
|
||||
1. `shouldUseProxy` checks `smpProxyMode` (Always/Unknown/Unprotected/Never) and whether the destination router is "known" (in the user's router list)
|
||||
2. If proxying: `getSMPProxyClient` creates or reuses a proxy connection, then `connectSMPProxiedRelay` establishes the relay session. On `NO_SESSION` error, re-creates the relay session through the same proxy.
|
||||
3. If proxying fails with a host error and `smpProxyFallback` allows it: falls back to direct connection
|
||||
4. `deleteRelaySession` carefully validates that the current relay session matches the one that failed before removing it (prevents removing a concurrently-created replacement session)
|
||||
|
||||
**NO_SESSION retry limit**: On `NO_SESSION`, `sendViaProxy` is called recursively with `Just proxySrv` to reuse the same proxy router. If the recursive call also gets `NO_SESSION`, it throws `proxyError` instead of recursing again — `proxySrv_` is `Just`, so the `Nothing` branch (which recurses) is not taken. This limits retry to exactly one attempt.
|
||||
|
||||
**Proxy selection caching** (`smpProxiedRelays`): When `getSMPProxyClient` selects a proxy for a destination, it atomically inserts the proxy→destination mapping into `smpProxiedRelays`. If a mapping already exists (another thread selected a proxy for the same destination), the existing mapping is used. On relay creation failure with non-host errors, both the relay session and proxy mapping are removed. On host errors, they are preserved to allow fallback logic.
|
||||
|
||||
## Service credentials lifecycle
|
||||
|
||||
`getServiceCredentials` manages per-user, per-router service certificate credentials:
|
||||
|
||||
1. Checks `useClientServices` — if the user has services disabled, returns `Nothing`
|
||||
2. Looks up existing credentials in DB via `getClientServiceCredentials`
|
||||
3. If none exist, generates new TLS credentials on-the-fly (`genCredentials`) and stores them
|
||||
4. Extracts the private signing key from the X.509 certificate
|
||||
|
||||
The generated credentials are Ed25519 self-signed certificates with `simplex` organization, valid for ~2740 years. The certificate chain and hash are bundled into `ServiceCredentials` for the SMP handshake.
|
||||
|
||||
## withStore — database access bracket
|
||||
|
||||
`withStore` wraps database access with `agentOperationBracket c AODatabase`, ensuring the operation suspension cascade is respected. SQLite errors are classified:
|
||||
- `ErrorBusy`/`ErrorLocked` → `SEDatabaseBusy` → `CRITICAL True` (prompts user restart)
|
||||
- Other SQL errors → `SEInternal`
|
||||
|
||||
`SEAgentError` is a special wrapper that allows agent-level errors to be threaded through store operations — used when "transaction-like" access is needed but the operation involves agent logic, not just DB queries. See source comment: "network IO should NOT be used inside AgentStoreMonad."
|
||||
|
||||
`withStoreBatch` / `withStoreBatch'` run multiple DB operations in a single transaction, catching exceptions per-operation to report individual failures. The entire batch is within one `agentOperationBracket`.
|
||||
|
||||
## Router selection — getNextServer / withNextSrv
|
||||
|
||||
Router selection has two-level diversity:
|
||||
1. **Operator diversity**: prefer routers from operators not already used (tracked by `usedOperators` set)
|
||||
2. **Host diversity**: prefer routers with hosts not already used (tracked by `usedHosts` set)
|
||||
|
||||
`filterOrAll` ensures that if all routers are "used," the full list is returned rather than an empty one.
|
||||
|
||||
`withNextSrv` is designed for retry loops — it re-reads user routers on each call (allowing configuration changes during retries) and tracks `triedHosts` across attempts. When all hosts are tried, the tried set is reset (`S.empty`), creating a round-robin effect.
|
||||
|
||||
## Locking primitives
|
||||
|
||||
**`withConnLock`**: Per-connection lock via `connLocks` TMap. Non-obvious: `withConnLock'` with empty `ConnId` is a no-op (identity function) — allows agent operations on entities without real connection IDs to skip locking.
|
||||
|
||||
**`withConnLocks`**: Takes a `Set ConnId` and acquires locks for all connections. Uses `withGetLocks` which acquires all locks concurrently via `forConcurrently`. Note: concurrent acquisition of overlapping lock sets from different threads could theoretically deadlock, so callers must ensure non-overlapping lock sets or use a higher-level coordination.
|
||||
|
||||
**`getMapLock`**: Creates a lock on first access and caches it in the TMap. Locks are never removed — the TMap grows monotonically.
|
||||
|
||||
## Network configuration — slow/fast selection
|
||||
|
||||
`getNetworkConfig` selects between slow and fast network configs based on `userNetworkInfo`:
|
||||
- `UNCellular` or `UNNone` → slow config (1.5× timeouts via `slowNetworkConfig`)
|
||||
- `UNWifi`, `UNEthernet`, `UNOther` → fast config
|
||||
|
||||
Both configs are stored together in `useNetworkConfig :: TVar (NetworkConfig, NetworkConfig)`. The slow config is derived from the fast config in `newAgentClient`.
|
||||
|
||||
## closeAgentClient — shutdown sequence
|
||||
|
||||
1. Sets `active = False` — all protocol client getters will throw `INACTIVE`
|
||||
2. Closes all protocol server clients (SMP, NTF, XFTP) by swapping maps to empty and forking close threads
|
||||
3. Clears proxied relays
|
||||
4. Cancels resubscription workers — forks cancellation threads (fire-and-forget, `closeAgentClient` may return before all workers are cancelled)
|
||||
5. Clears delivery and async command workers (delivery workers are also cancelled via `cancelWorker`)
|
||||
6. Clears subscription state
|
||||
|
||||
The cancellation of resubscription workers reads the TMVar first (to get the Async handle), then calls `uninterruptibleCancel`. This is wrapped in a forked thread to avoid blocking the shutdown sequence.
|
||||
|
||||
**`closeClient_` edge case**: When closing individual clients, `closeClient_` handles `BlockedIndefinitelyOnSTM` — which occurs if the SessionVar TMVar was never filled (connection attempt in progress when shutdown started). The exception is caught and treated as a no-op.
|
||||
|
||||
**`reconnectServerClients` vs `closeProtocolServerClients`**: `closeProtocolServerClients` swaps the map to empty and closes all clients — no new connections can be made to those sessions. `reconnectServerClients` reads the map without clearing it and closes current clients — the disconnect callbacks trigger reconnection, effectively forcing fresh connections while keeping the session entries.
|
||||
|
||||
## Transport session modes
|
||||
|
||||
`TransportSessionMode` (`TSMEntity` vs other) determines whether the transport session key includes the entity ID (connection/queue ID). When `TSMEntity`, each queue gets its own TLS connection to the router. When not, queues to the same router share a connection. This is controlled by `sessionMode` in the network config.
|
||||
|
||||
`mkSMPTSession` and related functions compute the transport session key based on the current mode. This affects connection multiplexing — entity-mode sessions provide better privacy (router can't correlate queues) at the cost of more connections.
|
||||
|
||||
## getMsgLocks — GET exclusion
|
||||
|
||||
`getQueueMessage` creates a TMVar lock keyed by `(server, rcvId)` and takes it before sending GET. This prevents concurrent GET and SUB on the same queue (SUB is checked via `hasGetLock` in `checkQueues`). The lock is released by `releaseGetLock` after ACK or on error.
|
||||
|
||||
The lock creation uses `TM.alterF` to atomically create-or-reuse: if no lock exists, creates a new `TMVar ()` and immediately takes it; if one exists, takes it. This avoids a race between two concurrent GET attempts on the same queue.
|
||||
|
||||
## Error classification — temporaryAgentError
|
||||
|
||||
Classifies errors as temporary (retryable) or permanent. Notable non-obvious classifications:
|
||||
- `TEHandshake BAD_SERVICE` is temporary — it indicates a DB error on the router, not a permanent rejection
|
||||
- `CRITICAL True` is temporary — `True` means the error shows a restart button, implying the user should retry. `CRITICAL False` is permanent.
|
||||
- `INACTIVE` is temporary — the agent may be reactivated
|
||||
- `SMP.PROXY NO_SESSION` via proxy is temporary — session can be re-established
|
||||
- `SMP.STORE _` is temporary — router-side store error, not a client issue
|
||||
|
||||
`temporaryOrHostError` extends `temporaryAgentError` to also include host-related errors (`HOST`, `TRANSPORT TEVersion`). Used in subscription management where host errors should trigger resubscription rather than permanent failure.
|
||||
@@ -1,9 +0,0 @@
|
||||
# Simplex.Messaging.Agent.Env.SQLite
|
||||
|
||||
> Agent environment configuration, default values, and worker/supervisor record types.
|
||||
|
||||
**Source**: [`Agent/Env/SQLite.hs`](../../../../../../src/Simplex/Messaging/Agent/Env/SQLite.hs)
|
||||
|
||||
## mkUserServers — silent fallback on all-disabled
|
||||
|
||||
See comment on `mkUserServers`. If filtering routers by `enabled && role` yields an empty list, `fromMaybe srvs` falls back to *all* routers regardless of enabled/role status. This prevents a configuration where all routers are disabled from leaving the user with no routers — but means disabled routers can still be used if every router in a role is disabled.
|
||||
@@ -1,7 +0,0 @@
|
||||
# Simplex.Messaging.Agent.Lock
|
||||
|
||||
> TMVar-based named mutex with concurrent multi-lock acquisition.
|
||||
|
||||
**Source**: [`Agent/Lock.hs`](../../../../../src/Simplex/Messaging/Agent/Lock.hs)
|
||||
|
||||
No non-obvious behavior. See source. See comment on `getPutLock` for the atomicity argument.
|
||||
@@ -1,95 +0,0 @@
|
||||
# Simplex.Messaging.Agent.NtfSubSupervisor
|
||||
|
||||
> Supervisor-worker architecture for notification subscription lifecycle management.
|
||||
|
||||
**Source**: [`Agent/NtfSubSupervisor.hs`](../../../../../src/Simplex/Messaging/Agent/NtfSubSupervisor.hs)
|
||||
|
||||
## Architecture
|
||||
|
||||
The notification system uses a supervisor with **three worker pools**, each keyed by router address:
|
||||
|
||||
| Pool | Key | Purpose |
|
||||
|------|-----|---------|
|
||||
| `ntfWorkers` | NtfServer | Create/check/delete/rotate subscriptions on notification router |
|
||||
| `ntfSMPWorkers` | SMPServer | Create/delete notifier credentials on messaging router |
|
||||
| `ntfTknDelWorkers` | NtfServer | Delete tokens on notification router (background cleanup) |
|
||||
|
||||
The supervisor (`runNtfSupervisor`) reads commands from `ntfSubQ` and dispatches work to the appropriate pools. Workers are created lazily via `getAgentWorker` and process batches from the database.
|
||||
|
||||
## Non-obvious behavior
|
||||
|
||||
### 1. NSCCreate four-way partition
|
||||
|
||||
`partitionQueueSubActions` classifies each (queue, subscription) pair into one of four buckets:
|
||||
|
||||
- **New sub**: no existing subscription record — create from scratch
|
||||
- **Reset sub**: credentials mismatch (SMP router changed, notifier ID changed, action was nulled by error, or action is a delete) — wipe and restart from SMP key exchange
|
||||
- **Continue SMP work**: existing action is `NSASMP` and credentials are consistent — kick the SMP worker
|
||||
- **Continue NTF work**: existing action is `NSANtf` and credentials are consistent — kick the NTF worker
|
||||
|
||||
The key decision point: when `subAction_` is `Nothing` (set by `workerErrors` after permanent failures), the subscription is treated as needing a full reset. This interacts with the null-action sentinel pattern from `AgentStore`.
|
||||
|
||||
### 2. retrySubActions shrinking retry with TVar
|
||||
|
||||
`retrySubActions` holds the list of subs-to-retry in a `TVar`. Each iteration, the action function returns only the subs that got temporary errors (via `splitResults`). The `TVar` is overwritten with this shrinking list. On success or permanent error, subs drop out. This means retry batches get smaller over time.
|
||||
|
||||
`splitResults` implements a three-way partition: temporary or host errors → retry, permanent errors → null the action + notify, successes → continue pipeline.
|
||||
|
||||
### 3. rescheduleWork deferred wake-up
|
||||
|
||||
When the NTF worker finds that all pending `NSACheck` actions have future timestamps, it does not spin-wait. Instead it:
|
||||
1. Takes itself out of the `doWork` TMVar (so the worker blocks on `waitForWork`)
|
||||
2. Forks a thread that sleeps until the first action's timestamp
|
||||
3. The forked thread re-signals `doWork` when the time arrives
|
||||
|
||||
This is the mechanism for time-scheduled subscription health checks.
|
||||
|
||||
### 4. checkSubs AUTH triggers full recreation
|
||||
|
||||
When the notification router returns `AUTH` for a subscription check, the subscription is not simply marked as failed — it is fully recreated from scratch by resetting to `NSASMP NSASmpKey` state. This handles the case where the notification router has lost its subscription state (restart, data loss). The SMP worker is kicked to re-establish notifier credentials.
|
||||
|
||||
Successful check results with statuses not in `subscribeNtfStatuses` also trigger recreation via `recreateNtfSub`.
|
||||
|
||||
### 5. deleteToken two-phase with restart survival
|
||||
|
||||
Token deletion splits into two phases:
|
||||
1. **Store phase**: Remove token from active store, persist `(server, privateKey, tokenId)` to a deletion queue via `addNtfTokenToDelete`
|
||||
2. **Network phase**: `runNtfTknDelWorker` reads from the queue and performs the actual router-side deletion
|
||||
|
||||
On supervisor startup, `startTknDelete` scans for any pending deletion queue entries and launches workers. This ensures token cleanup survives agent restarts.
|
||||
|
||||
If the token has no router-side ID (`ntfTokenId = Nothing`), only the store phase runs — no worker is launched.
|
||||
|
||||
### 6. workerErrors nulls subscription action
|
||||
|
||||
When permanent (non-temporary, non-host) errors occur in batch operations, `workerErrors` sets the subscription's action to `NULL` in the database and notifies the client. The next `NSCCreate` for that connection will see `subAction_ = Nothing` in `contOrReset` and trigger a full subscription reset.
|
||||
|
||||
This null-action sentinel is the bridge between worker failure recovery and supervisor-driven re-creation.
|
||||
|
||||
### 7. NSADelete and NSARotate are deprecated
|
||||
|
||||
These NTF worker actions are no longer generated by current code but are kept for processing legacy database records. They are explicitly not batched (processed one at a time via `mapM`). `NSARotate` deletes the subscription then re-queues `NSCCreate` back to the supervisor.
|
||||
|
||||
### 8. Stats counting groups by userId
|
||||
|
||||
`incStatByUserId` groups batch subscriptions by `userId` before incrementing stats counters, ensuring per-user counts are accurate even when a single batch contains subscriptions from multiple users.
|
||||
|
||||
### 9. sendNtfSubCommand — gated on instant mode
|
||||
|
||||
`sendNtfSubCommand` only enqueues work if instant notifications are active (`hasInstantNotifications` checks `NTActive` status + `NMInstant` mode). In periodic mode, the entire subscription creation pipeline is dormant — no commands reach the supervisor.
|
||||
|
||||
### 10. deleteNotifierKeys — credential reset before disable
|
||||
|
||||
`resetCredsGetQueue` clears the queue's notification credentials in the store *before* sending the disable command to the SMP router. This "clean first" ordering means local state is already consistent even if the network call fails.
|
||||
|
||||
### 11. runNtfTknDelWorker — permanent error discards record
|
||||
|
||||
When token deletion gets a permanent (non-temporary, non-host) error, the deletion record is removed from the queue rather than retried. This prevents stuck deletion records from blocking the worker. The error is reported to the client.
|
||||
|
||||
### 12. getNtfServer — random selection from multiple
|
||||
|
||||
When multiple notification routers are configured, one is selected randomly using `randomR` with a session-stable `TVar` generator. Single-router configurations skip the randomness.
|
||||
|
||||
### 13. closeNtfSupervisor — atomic swap then cancel
|
||||
|
||||
`swapTVar` atomically replaces the workers map with empty, then cancels all extracted workers. This ensures all existing workers at the point of shutdown are captured for cancellation. Prevention of new work is handled by the supervisor loop termination and operation bracket lifecycle, not by the swap itself.
|
||||
@@ -1,118 +0,0 @@
|
||||
# Simplex.Messaging.Agent.Protocol
|
||||
|
||||
> Agent protocol types, wire formats, connection link serialization, and error taxonomy.
|
||||
|
||||
**Source**: [`Agent/Protocol.hs`](../../../../../../src/Simplex/Messaging/Agent/Protocol.hs)
|
||||
|
||||
**Protocol spec**: [`protocol/agent-protocol.md`](../../../../../protocol/agent-protocol.md) — duplex connection procedure, agent message syntax, connection link formats.
|
||||
|
||||
## Overview
|
||||
|
||||
This module defines the agent-level protocol: the types exchanged between agents (via SMP routers) and between agent and client application. It contains no IO — purely types, serialization, and validation logic.
|
||||
|
||||
The module carries two independent version scopes: `SMPAgentVersion` (agent-to-agent protocol, currently v2–v7) and `SMPClientVersion` (agent-to-router protocol, imported from `Protocol.hs`). These version scopes interact but are negotiated independently — see [Protocol.md](../Protocol.md#two-separate-version-scopes).
|
||||
|
||||
## Two-layer message format
|
||||
|
||||
Agent messages use a two-layer envelope structure:
|
||||
|
||||
1. **Outer envelope** (`AgentMsgEnvelope`): version + single-char type tag (`C`/`M`/`I`/`R`) + type-specific payload. The `C` (confirmation) and `M` (message) variants carry double-ratchet encrypted content. The `I` (invitation) variant is encrypted only with per-queue E2E. The `R` (ratchet key) variant carries ratchet renegotiation parameters.
|
||||
|
||||
2. **Inner message** (`AgentMessage`): after double-ratchet decryption, discriminated by tags `I`/`D`/`R`/`M`. The `M` variant contains `APrivHeader` (sequential message ID + previous message hash for integrity) followed by `AMessage` (the actual command: `HELLO`, `A_MSG`, queue rotation, etc).
|
||||
|
||||
The tag characters overlap between layers (`I` means confirmation-conninfo in inner, invitation in outer; `M` means message-envelope in outer, agent-message in inner). These are disambiguated by context — outer parsing happens first, then decryption, then inner parsing.
|
||||
|
||||
## e2eEncConnInfoLength / e2eEncAgentMsgLength — PQ-dependent size budgets
|
||||
|
||||
Connection info and agent message size limits depend on both agent version and PQ support. When PQ is enabled (v5+), the limits are *smaller* — not larger — because the ratchet header and reply link grow with PQ keys (SNTRUP761), consuming space from the fixed SMP message block. The specific reductions (3726 for conninfo, 2222 for messages) are documented in source comments.
|
||||
|
||||
## AgentMsgEnvelope — connInfo encryption asymmetry
|
||||
|
||||
`AgentInvitation` encrypts `connInfo` only with per-queue E2E (no double ratchet) — see source comment. This is because invitations are sent to contact address queues where no ratchet has been established. `AgentConfirmation` encrypts with double ratchet. `AgentRatchetKey` uses per-queue E2E for the ratchet parameters themselves (bootstrapping problem: can't use ratchet to renegotiate the ratchet).
|
||||
|
||||
## AgentMessageType — dual encoding paths
|
||||
|
||||
`AgentMessageType` and `AMsgType` encode the same set of message types but serve different purposes: `AgentMessageType` includes the envelope types (`AM_CONN_INFO`, `AM_CONN_INFO_REPLY`, `AM_RATCHET_INFO`) for database storage, while `AMsgType` only covers the inner `AMessage` types. Both share the same wire tags for the overlapping types (`H`, `M`, `V`, `QC`, `QA`, `QK`, `QU`, `QT`, `E`). The `Q`-prefixed types use two-character tags (prefix dispatch), all others use single characters.
|
||||
|
||||
## HELLO — sent once after securing
|
||||
|
||||
`HELLO` is sent exactly once, when the queue is known to be secured (duplex handshake). Not used at all in fast duplex connection (v9+ SMP). The v1 slow handshake (which sent HELLO multiple times until securing succeeded) is no longer supported — `minSupportedSMPAgentVersion = duplexHandshakeSMPAgentVersion` (v2).
|
||||
|
||||
## AEvent entity type system
|
||||
|
||||
`AEvent` is a GADT indexed by `AEntity` (phantom type: `AEConn`, `AERcvFile`, `AESndFile`, `AENone`). This prevents the type system from allowing file events on connection entities and vice versa. The existential wrapper `AEvt` erases the entity type for storage in heterogeneous collections — equality comparison (`Eq AEvt`) uses `testEquality` on the singleton witness to recover type information.
|
||||
|
||||
`AENone` is used for events that aren't associated with any specific entity (e.g., `DOWN`, `UP`, `SUSPENDED`, `DEL_USER`). These are router-level or agent-level notifications, not connection-level.
|
||||
|
||||
## ConnectionMode singleton pattern
|
||||
|
||||
`ConnectionMode` / `SConnectionMode` / `ConnectionModeI` implement the singleton pattern: `SConnectionMode` is the type-level witness, `ConnectionModeI` is the typeclass that lets you recover the singleton from a type parameter. Many types are parameterized by `ConnectionMode` (`ConnectionRequestUri m`, `ConnShortLink m`, `ConnectionLink m`, etc.) to prevent mixing invitation and contact types at compile time.
|
||||
|
||||
`checkConnMode` is the runtime escape hatch — it uses `testEquality` to cast between mode-parameterized types, returning `Left "bad connection mode"` on mismatch. This is used extensively in parsers where the mode is determined at parse time.
|
||||
|
||||
## ConnReqUriData smpP — queueMode patch
|
||||
|
||||
The binary parser for `ConnReqUriData` applies `patchQueueMode` to all queues, setting `queueMode = Just QMContact` when it's `Nothing`. See source comment: this compensates for `QMContact` not being included in queue encoding until min SMP client version >= 3. This patch is safe because the binary encoding path was not used before SMP client version 4.
|
||||
|
||||
## Connection link URI parsing — version range adjustment
|
||||
|
||||
`connReqUriP` adjusts the agent version range for contact links: `adjustAgentVRange` clamps the minimum to `minSupportedSMPAgentVersion`. This preserves compatibility with old contact links published online — they may advertise version ranges starting below the current minimum, and clamping prevents negotiation from failing on an unsupported version.
|
||||
|
||||
The semicolon separator for SMP queues in the URI query string is deliberate — commas are used within server addresses to separate hostnames, so semicolons separate queues to avoid ambiguity.
|
||||
|
||||
## Short link encoding — contactConnType as URL path character
|
||||
|
||||
Short links encode `ContactConnType` as a single lowercase letter in the URL path: `a` (contact), `c` (channel), `g` (group), `r` (relay). Invitation links use `i`. The parser uses `toUpper` before dispatching to `ctTypeP` (which expects uppercase), while the encoder uses `toLower` on `ctTypeChar` output. This case dance happens because the wire format wants lowercase URLs but the internal representation uses uppercase.
|
||||
|
||||
## Short link router shortening
|
||||
|
||||
`shortenShortLink` strips port and key hash from preset routers, leaving only the hostname (`SMPServerOnlyHost` pattern). This makes short links shorter for well-known routers. `restoreShortLink` reverses this by looking up the full router definition from the preset list. Both functions match on primary hostname only (first in the `NonEmpty` list).
|
||||
|
||||
`isPresetServer` has a non-obvious port matching rule: empty port in the preset matches `"443"` or `"5223"` in the link. This handles servers that use default ports without explicitly listing them.
|
||||
|
||||
## OwnerAuth — chain-of-trust validation
|
||||
|
||||
`OwnerAuth` is double-encoded: the inner fields are `smpEncode`d, then the result is encoded as a `ByteString` (with length prefix). See source comment: "additionally encoded as ByteString to have known length and allow OwnerAuth extension." The parser uses `parseOnly` on the inner bytes, which silently ignores trailing data — providing forward compatibility for future field additions.
|
||||
|
||||
`validateLinkOwners` enforces a chain-of-trust: each owner must be signed by either the root key or any *preceding* owner in the list. Order matters — an owner signed by a later owner in the list will fail validation. Duplicate keys or IDs are rejected. An owner key matching the root key is rejected (prevents trivial self-authorization).
|
||||
|
||||
## UserLinkData — length-prefix switchover
|
||||
|
||||
`UserLinkData` uses a 1-byte length prefix for data ≤ 254 bytes, switching to a `\255` sentinel byte followed by a 2-byte (`Large`) length prefix for longer data. This is a backward-compatible extension of the standard `smpEncode` string format (which uses 1-byte length, capping at 255 bytes).
|
||||
|
||||
## FixedLinkData / ConnLinkData — forward-compatible parsing
|
||||
|
||||
Both `FixedLinkData` and `ConnLinkData` (invitation variant) consume trailing bytes with `A.takeByteString` after parsing known fields. See source comment: "ignoring tail for forward compatibility with the future link data encoding." This allows newer agents to add fields without breaking older parsers.
|
||||
|
||||
## AgentErrorType — BlockedIndefinitely promotion
|
||||
|
||||
`fromSomeException` in the `AnyError` instance promotes `BlockedIndefinitelyOnSTM` and `BlockedIndefinitelyOnMVar` to `CRITICAL` errors (with `offerRestart = True`) rather than generic `INTERNAL`. These are thread deadlock signals from the GHC runtime — they indicate a program bug, not a transient error. The `CRITICAL` classification with restart offer means the client application should prompt the user.
|
||||
|
||||
## cryptoErrToSyncState — error severity classification
|
||||
|
||||
Maps crypto errors to ratchet sync states: `DECRYPT_AES`, `DECRYPT_CB`, and `RATCHET_EARLIER` map to `RSAllowed` (sync is optional, may self-recover). `RATCHET_HEADER`, `RATCHET_SKIPPED`, and `RATCHET_SYNC` map to `RSRequired` (sync must happen before communication can continue). This classification determines whether the agent automatically initiates ratchet resynchronization.
|
||||
|
||||
## extraSMPServerHosts — hardcoded onion mappings
|
||||
|
||||
Maps clearnet hostnames of preset SMP routers to their `.onion` addresses. `updateSMPServerHosts` adds the onion host as a second hostname when parsing legacy queue URIs that only have one host. This is used for backward compatibility with queue URIs created before multi-host support — modern URIs include all hosts directly.
|
||||
|
||||
## Queue rotation state machines
|
||||
|
||||
`RcvSwitchStatus` and `SndSwitchStatus` encode the two sides of the queue rotation protocol:
|
||||
|
||||
- **Receiver side**: `RSSwitchStarted` → `RSSendingQADD` → `RSSendingQUSE` → `RSReceivedMessage`
|
||||
- **Sender side**: `SSSendingQKEY` → `SSSendingQTEST`
|
||||
|
||||
The asymmetry reflects the protocol: the receiver initiates rotation and sends more messages (QADD, QUSE), while the sender responds (QKEY, QTEST). These states are persisted to the database — the `StrEncoding` instances use snake_case strings as the canonical serialization format. See [agent-protocol.md — Rotating messaging queue](../../../../../protocol/agent-protocol.md#rotating-messaging-queue).
|
||||
|
||||
## SMPQueueInfo / SMPQueueUri — version duality
|
||||
|
||||
`SMPQueueInfo` (single version) and `SMPQueueUri` (version range) represent the same queue address but in different contexts. `VersionI` / `VersionRangeI` typeclasses convert between them — `toVersionT` pins a version range to a specific version, `toVersionRangeT` wraps a versioned type in a range. See source comment on `VersionI SMPClientVersion SMPQueueInfo`: the current conversion is trivial (just swapping the version/range field) but the typeclass exists so that future field additions can have version-dependent conversion logic.
|
||||
|
||||
`SMPQueueInfo` encoding has four version-conditional paths: v1 (legacy server encoding), v2+ (standard encoding), v3+ with secure sender (appends `sndSecure` bool), v4+ (appends `queueMode`). The parser uses `clientVersion` to select between `legacyServerP` and standard `smpP` for the server field, and `updateSMPServerHosts` backfills onion addresses for legacy URIs.
|
||||
|
||||
## ACommand — binary body parsing
|
||||
|
||||
`commandP` takes a custom body parser. `dbCommandP` uses `A.take =<< A.decimal <* "\n"` — length-prefixed binary read. This is for commands stored in the database where the body must be fully parsed (not left as unparsed trailing bytes). The standard command parser uses `A.takeByteString` for bodies, consuming remaining input.
|
||||
|
||||
`pqIKP` defaults to `IKLinkPQ PQSupportOff` when PQ support is not specified, and `pqSupP` defaults to `PQSupportOff`. These defaults maintain backward compatibility with commands serialized before PQ support was added.
|
||||
@@ -1,7 +0,0 @@
|
||||
# Simplex.Messaging.Agent.QueryString
|
||||
|
||||
> HTTP query string parsing utilities for connection link URIs.
|
||||
|
||||
**Source**: [`Agent/QueryString.hs`](../../../../../src/Simplex/Messaging/Agent/QueryString.hs)
|
||||
|
||||
No non-obvious behavior. See source.
|
||||
@@ -1,35 +0,0 @@
|
||||
# Simplex.Messaging.Agent.RetryInterval
|
||||
|
||||
> Retry-with-backoff combinators for agent reconnection and worker loops.
|
||||
|
||||
**Source**: [`Agent/RetryInterval.hs`](../../../../../src/Simplex/Messaging/Agent/RetryInterval.hs)
|
||||
|
||||
## Overview
|
||||
|
||||
Four retry combinators with increasing sophistication: basic (`withRetryInterval`), counted (`withRetryIntervalCount`), foreground-aware (`withRetryForeground`), and dual-interval with external wake-up (`withRetryLock2`). All share the same backoff curve via `nextRetryDelay`.
|
||||
|
||||
## Backoff curve — nextRetryDelay
|
||||
|
||||
Delay stays constant at `initialInterval` until `elapsed >= increaseAfter`, then grows by 1.5x per step (`delay * 3 / 2`) up to `maxInterval`. The `delay == maxInterval` guard short-circuits the comparison once the cap is reached.
|
||||
|
||||
## updateRetryInterval2 — resume from saved state
|
||||
|
||||
Sets `increaseAfter = 0` on both intervals. This skips the initial constant-delay phase — the next retry will immediately begin increasing from the saved interval. Used to restore retry state across reconnections without restarting from the initial interval.
|
||||
|
||||
## withRetryForeground — reset on foreground/online transition
|
||||
|
||||
The retry loop resets to `initialInterval` when either:
|
||||
- The app transitions from background to foreground (`not wasForeground && foreground`)
|
||||
- The network transitions from offline to online (`not wasOnline && online`)
|
||||
|
||||
The STM transaction blocks on three things simultaneously: the `registerDelay` timer, the `isForeground` TVar, and the `isOnline` TVar. Whichever fires first unblocks the retry. On reset, elapsed time is zeroed.
|
||||
|
||||
The `registerDelay` is capped at `maxBound :: Int` (~36 minutes on 32-bit) to prevent overflow.
|
||||
|
||||
## withRetryLock2 — interruptible dual-interval retry
|
||||
|
||||
Maintains two independent backoff states (slow and fast) that the action toggles between by calling the loop continuation with `RISlow` or `RIFast`. Only the chosen interval advances; the other preserves its state.
|
||||
|
||||
The `wait` function is the non-obvious part: it spawns a timer thread that puts `()` into the `lock` TMVar after the delay, while the main thread blocks on `takeTMVar lock`. This means the retry can be woken early by *external code* putting into the same TMVar — the timer is just a fallback. The `waiting` TVar prevents a stale timer from firing after the main thread has already been woken by an external signal.
|
||||
|
||||
**Consumed by**: [Agent/Client.hs](./Client.md) — `reconnectSMPClient` uses the lock TMVar to allow immediate reconnection when new subscriptions arrive, rather than waiting for the full backoff delay.
|
||||
@@ -1,7 +0,0 @@
|
||||
# Simplex.Messaging.Agent.Stats
|
||||
|
||||
> Per-router statistics counters (SMP, XFTP, NTF) with TVar-based live state and serializable snapshots.
|
||||
|
||||
**Source**: [`Agent/Stats.hs`](../../../../../src/Simplex/Messaging/Agent/Stats.hs)
|
||||
|
||||
No non-obvious behavior. See source.
|
||||
@@ -1,72 +0,0 @@
|
||||
# Simplex.Messaging.Agent.Store
|
||||
|
||||
> Domain entity types for agent persistence — queues, connections, messages, commands, and store errors.
|
||||
|
||||
**Source**: [`Agent/Store.hs`](../../../../../src/Simplex/Messaging/Agent/Store.hs)
|
||||
|
||||
## Overview
|
||||
|
||||
This module defines the data types that represent agent state. It contains no database operations — those are in [AgentStore.hs](./Store/AgentStore.md). The key abstractions are:
|
||||
|
||||
- **Queue types** (`StoredRcvQueue`, `StoredSndQueue`) parameterized by `DBStored` phantom type for new vs persisted distinction
|
||||
- **Connection GADT** (`Connection'`) encoding the connection state machine at the type level
|
||||
- **Message containers** (`RcvMsgData`, `SndMsgData`, `PendingMsgData`) for the message lifecycle
|
||||
- **Store errors** (`StoreError`) including two sentinel errors with special semantics
|
||||
|
||||
## Connection' — type-level state machine
|
||||
|
||||
The `Connection'` GADT encodes connection lifecycle as a type parameter: `CNew` → `CRcv`/`CSnd` → `CDuplex`, plus `CContact` for reusable contact connections. `SomeConn` wraps an existential to store connections of unknown type.
|
||||
|
||||
`TestEquality SConnType` deliberately omits `SCNew` — `testEquality SCNew SCNew` returns `Nothing`. This is intentional: `NewConnection` has no queues and is not a valid target for type-level connection matching in store operations.
|
||||
|
||||
## canAbortRcvSwitch — race condition boundary
|
||||
|
||||
See comments on `canAbortRcvSwitch`. The `RSSendingQUSE` and `RSReceivedMessage` states cannot be aborted because the sender may have already deleted the original queue. Aborting (deleting the new queue) at that point would break the connection with no recovery path.
|
||||
|
||||
## ratchetSyncAllowed / ratchetSyncSendProhibited — cross-repo contract
|
||||
|
||||
See comments on `ratchetSyncAllowed`. Both functions carry the comment "this function should be mirrored in the clients" — simplex-chat must implement identical logic. The agent enforces these state checks, but the chat client also needs them for UI decisions (e.g., disabling send when `ratchetSyncSendProhibited`).
|
||||
|
||||
## SEWorkItemError — worker suspension sentinel
|
||||
|
||||
`SEWorkItemError` is a sentinel error that triggers worker suspension when encountered during work item retrieval. The `AnyStoreError` typeclass exposes `isWorkItemError` for the worker framework ([Agent/Client.hs](./Client.md)) to detect this case. The comment "do not use!" means it should not be thrown for normal error conditions — only when the work item itself is corrupt/unreadable and the worker should stop rather than retry.
|
||||
|
||||
## SEAgentError — store-level error wrapping
|
||||
|
||||
`SEAgentError` wraps `AgentErrorType` inside store operations. This allows store functions to return agent-level errors (e.g., connection state violations detected during a DB transaction) without breaking the `ExceptT StoreError` type. The "to avoid race conditions" rationale: checking a condition and acting on it must happen in the same DB transaction, so the agent error is returned through the store error channel.
|
||||
|
||||
## InvShortLink — secure-on-read semantics
|
||||
|
||||
See comment on `InvShortLink`. Stored separately from the connection because 1-time invitation short links have a "secure-on-read" property: accessing the link data on the router marks it as read, preventing undetected observation. The `sndPrivateKey` is persisted to allow retries of the link creation without generating new keys.
|
||||
|
||||
## RcvQueueSub — subscription-optimized projection
|
||||
|
||||
`RcvQueueSub` strips cryptographic fields from `RcvQueue`, keeping only what's needed for subscription tracking in [TSessionSubs](./TSessionSubs.md). This reduces memory pressure when tracking thousands of subscriptions in STM.
|
||||
|
||||
## rcvSMPQueueAddress exposes sender-facing ID
|
||||
|
||||
`rcvSMPQueueAddress` constructs the `SMPQueueAddress` from a receive queue using `sndId` (not `rcvId`). The address shared with senders in connection requests contains the sender ID, the public key derived from `e2ePrivKey`, and `queueMode`. The `rcvId` is never exposed externally.
|
||||
|
||||
## enableNtfs is duplicated between queue and connection
|
||||
|
||||
`enableNtfs` exists on both `StoredRcvQueue` and `ConnData`. The comment marks it as "duplicated from ConnData." The queue-level copy enables subscription operations (which work at the queue level) to check notification status without loading the full connection.
|
||||
|
||||
## deleteErrors — queue deletion retry counter
|
||||
|
||||
`StoredRcvQueue` has a `deleteErrors :: Int` field that counts failed deletion attempts. This allows the agent to give up on queue deletion after repeated failures rather than retrying indefinitely.
|
||||
|
||||
## Two-level message preparation
|
||||
|
||||
`SndMsgData` optionally carries `SndMsgPrepData` with a `sndMsgBodyId` reference to a separately stored message body. `PendingMsgData` optionally carries `PendingMsgPrepData` with the actual `AMessage` body. This split allows large message bodies to be stored once and referenced by ID during the send pipeline, avoiding redundant serialization.
|
||||
|
||||
## Per-message retry backoff
|
||||
|
||||
`PendingMsgData` includes `msgRetryState :: Maybe RI2State` — each pending message independently tracks its retry backoff state. This means messages that fail to send don't reset the retry timers of other pending messages in the same connection.
|
||||
|
||||
## Soft deletion and optional contact connection
|
||||
|
||||
`ConnData` has `deleted :: Bool` for soft deletion — connections are marked deleted before queue cleanup completes. `Invitation` has `contactConnId_ :: Maybe ConnId` (note the trailing underscore) — invitations can outlive their originating contact connection.
|
||||
|
||||
## SEBadQueueStatus is vestigial
|
||||
|
||||
`SEBadQueueStatus` is documented in the source as "Currently not used." It was intended for queue status transition validation but was never implemented.
|
||||
@@ -1,124 +0,0 @@
|
||||
# Simplex.Messaging.Agent.Store.AgentStore
|
||||
|
||||
> Core CRUD operations for agent persistence — users, connections, queues, messages, ratchets, notifications, and file transfers.
|
||||
|
||||
**Source**: [`Agent/Store/AgentStore.hs`](../../../../../../src/Simplex/Messaging/Agent/Store/AgentStore.hs)
|
||||
|
||||
## Overview
|
||||
|
||||
At ~3700 lines, this is the largest module in the codebase. It implements all database operations for the agent, compiled with CPP for both SQLite and PostgreSQL backends. Most functions are straightforward SQL CRUD, but several patterns are non-obvious.
|
||||
|
||||
The module re-exports `withConnection`, `withTransaction`, `withTransactionPriority`, `firstRow`, `firstRow'`, and `maybeFirstRow` from the backend-specific Common module. It also exports `fromOnlyBI` (a local helper) and `getWorkItem`/`getWorkItems`.
|
||||
|
||||
## Dual-backend compilation
|
||||
|
||||
The module uses `#if defined(dbPostgres)` throughout. Key behavioral differences:
|
||||
- **Row locking**: PostgreSQL uses `FOR UPDATE` on reads that precede writes (e.g., `getConnForUpdate`, `getRatchetForUpdate`, `retrieveLastIdsAndHashRcv_`). SQLite relies on its single-writer model instead.
|
||||
- **Batch queries**: PostgreSQL uses `IN ?` with `In` wrapper for batch operations. SQLite falls back to per-row `forM` loops.
|
||||
- **Constraint handling**: PostgreSQL uses `constraintViolation`, SQLite checks `SQL.ErrorConstraint`.
|
||||
|
||||
## getWorkItem / getWorkItems — worker store pattern
|
||||
|
||||
`getWorkItem` implements the store-side pattern for the [worker framework](../Client.md): `getId → getItem → markFailed`. If `getId` throws an IO exception, `handleWrkErr` wraps it as `SEWorkItemError` (via `mkWorkItemError`), which signals the worker to suspend rather than retry. If `getItem` fails (returning Left or throwing), `tryGetItem` calls `markFailed` (also wrapped by `handleWrkErr`) and rethrows the original error. This prevents crash loops on corrupt data.
|
||||
|
||||
`getWorkItems` extends this to batch work items, where each item failure is independent.
|
||||
|
||||
**Consumed by**: `getPendingQueueMsg`, `getPendingServerCommand`, `getNextNtfSubNTFActions`, `getNextNtfSubSMPActions`, `getNextDeletedSndChunkReplica`, `getNextNtfTokenToDelete`, `getNextRcvChunkToDownload`, `getNextRcvFileToDecrypt`, `getNextSndChunkToUpload`, `getNextSndFileToPrepare`.
|
||||
|
||||
## Notification subscription — supervisor/worker coordination
|
||||
|
||||
`updateNtfSubscription`, `setNullNtfSubscriptionAction`, and `deleteNtfSubscription` all check `updated_by_supervisor` before writing. When `True`, the worker only updates local fields (ntf IDs, status) and skips action/server fields that the supervisor may have changed. This prevents the worker from overwriting supervisor decisions during concurrent execution.
|
||||
|
||||
`markUpdatedByWorker` resets the flag to `False` before each work item is processed, so the worker "claims" the subscription for the duration of its operation.
|
||||
|
||||
## createServer / getServerKeyHash_ — key hash migration
|
||||
|
||||
`createServer` returns `Maybe KeyHash`: `Nothing` means the server was newly created with the passed hash; `Just kh` means the server already existed and the passed hash differs from the stored one. This `Just` value is stored as `server_key_hash` on queues to allow per-queue key hash overrides.
|
||||
|
||||
The `COALESCE(q.server_key_hash, s.key_hash)` pattern appears throughout queries — queues can override the server-level hash, enabling gradual migration when a router's identity key changes.
|
||||
|
||||
## updateRcvMsgHash / updateSndMsgHash — race condition guard
|
||||
|
||||
Both functions include `AND last_internal_*_msg_id = ?` in their UPDATE WHERE clause. This prevents a race: if another message was processed between `updateIds` and `updateHash` (incrementing the last ID), the hash update is silently skipped rather than corrupting the chain. See comments on these functions.
|
||||
|
||||
## deleteConn — conditional delivery wait
|
||||
|
||||
Four paths:
|
||||
1. No timeout: immediate delete.
|
||||
2. Timeout + no pending deliveries: immediate delete.
|
||||
3. Timeout + pending deliveries + `deleted_at_wait_delivery` expired: delete.
|
||||
4. Timeout + pending deliveries + not expired: return `Nothing` (skip deletion).
|
||||
|
||||
This allows graceful delivery completion before connection cleanup.
|
||||
|
||||
## createSndConn — confirmed queue guard
|
||||
|
||||
See comment on `createSndConn`. Checks `checkConfirmedSndQueueExists_` before creating, because `insertSndQueue_` uses `ON CONFLICT DO UPDATE` which would silently replace an existing confirmed send queue. The pre-check prevents this destructive upsert.
|
||||
|
||||
## insertRcvQueue_ / insertSndQueue_ — queue ID preservation
|
||||
|
||||
Both functions check if a queue already exists (by server + queue ID) and reuse the existing database `queue_id`. If not found, they generate the next sequential ID (`MAX + 1`). This preserves database IDs across retries of queue creation.
|
||||
|
||||
## createClientService — service_id reset on upsert
|
||||
|
||||
The `ON CONFLICT DO UPDATE` clause sets `service_id = NULL` when credentials are updated. This forces re-registration with the router after credential rotation — the old service ID is invalidated.
|
||||
|
||||
## deleteSndMsgDelivery — conditional message retention
|
||||
|
||||
After removing the delivery record, checks whether any pending deliveries remain for the message. If none remain and the receipt status is `MROk`, the entire message is deleted. Otherwise, if `keepForReceipt` is true, only the message body is cleared (for debugging receipt mismatches). Handles shared `snd_message_bodies` with `FOR UPDATE` locking on PostgreSQL to prevent concurrent deletion races.
|
||||
|
||||
## createWithRandomId' — bounded retry
|
||||
|
||||
Generates random 12-byte IDs (base64url encoded) and retries up to 3 times on constraint violations (unique ID collision). Returns `SEUniqueID` if all attempts fail.
|
||||
|
||||
## setRcvQueuePrimary / setSndQueuePrimary — two-step primary swap
|
||||
|
||||
First clears primary flag on all queues in the connection, then sets it on the target queue. Also clears `replace_*_queue_id` on the new primary — this completes the queue rotation by removing the "replacing" marker.
|
||||
|
||||
## createCommand — silent drop for deleted connections
|
||||
|
||||
When `createCommand` encounters a constraint violation (the referenced connection was already deleted), it logs the error and returns successfully rather than throwing. This means commands targeting deleted connections are silently dropped. The rationale: the connection is already gone, so there's nothing useful to do with the error.
|
||||
|
||||
## updateNewConnRcv — retry tolerance
|
||||
|
||||
`updateNewConnRcv` accepts both `NewConnection` and `RcvConnection` connection states. The `RcvConnection` case is explicitly commented as "to allow retries" — if the initial queue insertion succeeded but the caller didn't get the response, a retry would find the connection already upgraded. `updateNewConnSnd` does not have this tolerance.
|
||||
|
||||
## setLastBrokerTs — monotonic advance
|
||||
|
||||
The WHERE clause includes `AND (last_broker_ts IS NULL OR last_broker_ts < ?)`, which ensures the timestamp only moves forward. Out-of-order message processing (e.g., from different queues) cannot regress the broker timestamp.
|
||||
|
||||
## deleteDeliveredSndMsg — FOR UPDATE + count zero check
|
||||
|
||||
On PostgreSQL, acquires a `FOR UPDATE` lock on the message row before counting pending deliveries. This prevents a race where two concurrent delivery completions both see count > 0 before either deletes, then both try to delete. Only deletes the message when the count reaches exactly 0.
|
||||
|
||||
## createWithRandomId' — savepoint-based retry
|
||||
|
||||
Uses `withSavepoint` around each insertion attempt rather than bare execute. This is critical for PostgreSQL: a failed statement within a transaction aborts the entire transaction, but savepoints allow rolling back just the failed INSERT and retrying with a new ID.
|
||||
|
||||
## Explicit row-lock functions
|
||||
|
||||
`lockConnForUpdate`, `lockRcvFileForUpdate`, and `lockSndFileForUpdate` are PostgreSQL-only explicit lock acquisition that compile to no-ops on SQLite. They acquire `FOR UPDATE` locks on rows that need serialized access without modifying them.
|
||||
|
||||
## XFTP work item retry ordering
|
||||
|
||||
`getNextRcvChunkToDownload` and `getNextSndChunkToUpload` order by `retries ASC, created_at ASC`. This prioritizes chunks with fewer retries, ensuring a repeatedly-failing chunk doesn't starve others. Same pattern for `getNextDeletedSndChunkReplica`.
|
||||
|
||||
## getRcvFileRedirects — error resilience
|
||||
|
||||
When loading redirect chains, errors loading individual redirect files are silently swallowed (`either (const $ pure Nothing) (pure . Just)`). This prevents a corrupt redirect from blocking access to the main file.
|
||||
|
||||
## enableNtfs defaults to True when NULL
|
||||
|
||||
Both `toRcvQueue` and `rowToConnData` default `enableNtfs` to `True` when the database value is NULL (`maybe True unBI enableNtfs_`). This is a backward-compatibility default for connections created before the field existed.
|
||||
|
||||
## primaryFirst — queue ordering
|
||||
|
||||
The `primaryFirst` comparator sorts queues with the primary queue first (`Down` on primary flag), then by `dbReplaceQId` to place the "replacing" queue second. This ensures all queue lists are consistently ordered for connection reconstruction.
|
||||
|
||||
## getAnyConn_ — connection GADT reconstruction
|
||||
|
||||
Reconstructs the type-level `Connection'` GADT by combining connection mode with the presence/absence of receive and send queues. The `CMContact` mode only maps to `ContactConnection` (receive-only); all other combinations use `CMInvitation` mode. When neither rcv nor snd queues exist, the result is always `NewConnection` regardless of mode.
|
||||
|
||||
## deleteNtfSubscription — soft delete when supervisor active
|
||||
|
||||
When `updated_by_supervisor` is true, `deleteNtfSubscription` doesn't actually delete the row. Instead, it nulls out the IDs and sets status to `NASDeleted`, preserving the row for the supervisor to observe. Only when the supervisor has not intervened does it perform a real DELETE.
|
||||
@@ -1,7 +0,0 @@
|
||||
# Simplex.Messaging.Agent.Store.Common
|
||||
|
||||
> CPP-conditional re-export of backend-specific common utilities (DBStore, withConnection, withTransaction).
|
||||
|
||||
**Source**: [`Agent/Store/Common.hs`](../../../../../../src/Simplex/Messaging/Agent/Store/Common.hs)
|
||||
|
||||
No non-obvious behavior. See source. One of three CPP re-export wrappers (Interface, Common, DB).
|
||||
@@ -1,7 +0,0 @@
|
||||
# Simplex.Messaging.Agent.Store.DB
|
||||
|
||||
> CPP-conditional re-export of backend-specific database primitives (Connection, FromField, ToField).
|
||||
|
||||
**Source**: [`Agent/Store/DB.hs`](../../../../../../src/Simplex/Messaging/Agent/Store/DB.hs)
|
||||
|
||||
No non-obvious behavior. See source. One of three CPP re-export wrappers (Interface, Common, DB).
|
||||
@@ -1,7 +0,0 @@
|
||||
# Simplex.Messaging.Agent.Store.Entity
|
||||
|
||||
> Phantom-typed database entity IDs distinguishing new (unsaved) from stored records.
|
||||
|
||||
**Source**: [`Agent/Store/Entity.hs`](../../../../../../src/Simplex/Messaging/Agent/Store/Entity.hs)
|
||||
|
||||
No non-obvious behavior. See source.
|
||||
@@ -1,7 +0,0 @@
|
||||
# Simplex.Messaging.Agent.Store.Interface
|
||||
|
||||
> CPP-conditional re-export of the active database backend (SQLite or PostgreSQL).
|
||||
|
||||
**Source**: [`Agent/Store/Interface.hs`](../../../../../../src/Simplex/Messaging/Agent/Store/Interface.hs)
|
||||
|
||||
No non-obvious behavior. See source. One of three CPP re-export wrappers (Interface, Common, DB) that select the active backend at compile time via `dbPostgres`.
|
||||
@@ -1,23 +0,0 @@
|
||||
# Simplex.Messaging.Agent.Store.Postgres
|
||||
|
||||
> PostgreSQL backend — dual-pool connection management, schema lifecycle, and migration.
|
||||
|
||||
**Source**: [`Agent/Store/Postgres.hs`](../../../../../../src/Simplex/Messaging/Agent/Store/Postgres.hs)
|
||||
|
||||
## Dual pool architecture
|
||||
|
||||
`connectPostgresStore` creates two connection pools (`dbPriorityPool` and `dbPool`), each with `poolSize` connections. Priority pool is used by `withTransactionPriority` for operations that shouldn't be blocked by regular queries. Both pools are TBQueue-based — connections are taken and returned after use.
|
||||
|
||||
All connections are created eagerly at initialization, not lazily on demand.
|
||||
|
||||
## uninterruptibleMask_ — pool atomicity invariant
|
||||
|
||||
See comment on `connectStore`. `uninterruptibleMask_` prevents async exceptions from interrupting pool filling or draining. The invariant: when `dbClosed = True`, queues are empty; when `False`, queues are full (or connections are in-flight with threads that will return them). Interruption mid-fill would break this invariant.
|
||||
|
||||
## Schema creation — fail-fast on missing
|
||||
|
||||
If the PostgreSQL schema doesn't exist and `createSchema` is `False`, the process logs an error and calls `exitFailure`. This prevents silent operation against the wrong schema.
|
||||
|
||||
## execSQL — not implemented
|
||||
|
||||
`execSQL` throws "not implemented" — the PostgreSQL client doesn't support raw SQL execution via the agent API. The function exists only to satisfy the shared interface.
|
||||
@@ -1,30 +0,0 @@
|
||||
# Simplex.Messaging.Agent.Store.SQLite
|
||||
|
||||
> SQLite backend — store creation, encrypted connection management, migration, and custom SQL functions.
|
||||
|
||||
**Source**: [`Agent/Store/SQLite.hs`](../../../../../../src/Simplex/Messaging/Agent/Store/SQLite.hs)
|
||||
|
||||
## Security-relevant PRAGMAs
|
||||
|
||||
`connectDB` sets PRAGMAs at connection time:
|
||||
- `secure_delete = ON`: data is overwritten (not just unlinked) on DELETE
|
||||
- `auto_vacuum = FULL`: freed pages are reclaimed immediately
|
||||
- `foreign_keys = ON`: referential integrity enforced
|
||||
|
||||
These are set per-connection, not per-database — every new connection (including re-opens) gets them.
|
||||
|
||||
## simplex_xor_md5_combine — custom SQLite function
|
||||
|
||||
A C-exported SQLite function registered at connection time. Takes an existing `IdsHash` and a `RecipientId`, XORs the hash with the MD5 of the ID. This is the SQLite implementation of the accumulative IdsHash used by service subscriptions (see [TSessionSubs.md](../TSessionSubs.md#updateActiveService--accumulative-xor-merge)). PostgreSQL uses `pgcrypto`'s `digest()` function for MD5 and a custom `xor_combine` PL/pgSQL function for the XOR.
|
||||
|
||||
## openSQLiteStore_ — connection swap under MVar
|
||||
|
||||
Uses `bracketOnError` with `takeMVar`/`tryPutMVar`: takes the connection MVar, creates a new connection, and puts the new one back. If connection fails, `tryPutMVar` restores the old connection. The `dbClosed` TVar is flipped atomically with the key update.
|
||||
|
||||
## storeKey — conditional key retention
|
||||
|
||||
`storeKey key keepKey` stores the encryption key in the `dbKey` TVar if `keepKey` is true or if the key is empty (no encryption). This means unencrypted stores can always be reopened. If `keepKey` is false and the key is non-empty, `reopenDBStore` fails with "no key".
|
||||
|
||||
## dbBusyLoop — initial connection retry
|
||||
|
||||
`connectSQLiteStore` wraps `connectDB` in `dbBusyLoop` to handle database locking during initial connection. All transactions (`withTransactionPriority`) are also wrapped in `dbBusyLoop` as a retry layer on top of the `busy_timeout` PRAGMA.
|
||||
@@ -1,7 +0,0 @@
|
||||
# Simplex.Messaging.Agent.Store.Shared
|
||||
|
||||
> Migration types, error reporting, and confirmation modes shared across database backends.
|
||||
|
||||
**Source**: [`Agent/Store/Shared.hs`](../../../../../../src/Simplex/Messaging/Agent/Store/Shared.hs)
|
||||
|
||||
No non-obvious behavior. See source.
|
||||
@@ -1,60 +0,0 @@
|
||||
# Simplex.Messaging.Agent.TSessionSubs
|
||||
|
||||
> Per-session subscription state machine tracking active and pending queue subscriptions.
|
||||
|
||||
**Source**: [`Agent/TSessionSubs.hs`](../../../../../src/Simplex/Messaging/Agent/TSessionSubs.hs)
|
||||
|
||||
## Overview
|
||||
|
||||
TSessionSubs manages the two-tier (active/pending) subscription state for SMP queues, keyed by transport session. Every subscription confirmation from a router is validated against the current session ID before being promoted to active — if the session has changed (reconnect happened), the subscription is demoted to pending for resubscription.
|
||||
|
||||
Service subscriptions (aggregate, router-managed) and queue subscriptions (individual, per-recipient-ID) are tracked separately but follow the same active/pending pattern.
|
||||
|
||||
**Consumed by**: [Agent/Client.hs](./Client.md) — `subscribeSMPQueues`, `subscribeSessQueues_`, `resubscribeSMPSession`, `smpClientDisconnected`.
|
||||
|
||||
## Session ID gating
|
||||
|
||||
The central invariant: a subscription is only active if it was confirmed on the *current* TLS session. Every function that promotes subscriptions to active (`addActiveSub'`, `batchAddActiveSubs`, `setActiveServiceSub`) checks `Just sessId == sessId'` (stored session ID). On mismatch, the subscription goes to pending instead — silently, with no error.
|
||||
|
||||
This means subscription RPCs that succeed but return after a reconnect are safely caught: the result carries the old session ID, which won't match the new one stored by `setSessionId`.
|
||||
|
||||
## setSessionId — silent demotion on reconnect
|
||||
|
||||
`setSessionId` has two behaviors:
|
||||
- **First call** (stored is `Nothing`): stores the session ID. No side effects.
|
||||
- **Subsequent call with different ID**: calls `setSubsPending_`, which moves *all* active subscriptions to pending and demotes the active service subscription. The new session ID is stored.
|
||||
- **Same ID**: no-op (the `unless` guard).
|
||||
|
||||
This is the mechanism by which reconnection invalidates all prior subscriptions. Callers don't need to explicitly move subscriptions — setting the new session ID does it atomically.
|
||||
|
||||
## addActiveSub' — service-associated queue elision
|
||||
|
||||
When `serviceId_` is `Just` and `serviceAssoc` is `True`, the queue is **not** added to `activeSubs`. Instead, `updateActiveService` increments the service subscription's count and XORs the queue's `IdsHash`. The queue is also removed from `pendingSubs`.
|
||||
|
||||
This means service-associated queues have no individual representation in `activeSubs` — they exist only as aggregated count + hash in `activeServiceSub`. The router tracks them via the service subscription; the agent doesn't need per-queue state.
|
||||
|
||||
When `serviceAssoc` is `False` (or no service ID), the queue goes to `activeSubs` normally.
|
||||
|
||||
## updateActiveService — accumulative XOR merge
|
||||
|
||||
`updateActiveService` adds to an existing `ServiceSub` rather than replacing it. It increments the queue count (`n + addN`) and appends the IdsHash (`idsHash <> addIdsHash`). The `<>` on `IdsHash` is XOR — this means the hash is order-independent and can be built incrementally as individual subscription confirmations arrive.
|
||||
|
||||
The guard `serviceId == serviceId'` silently drops updates if the service ID has changed (e.g., credential rotation happened between individual queue confirmations).
|
||||
|
||||
## setSubsPending — mode-dependent redistribution
|
||||
|
||||
`setSubsPending` handles two cases based on whether the transport session mode (entity vs shared) matches the session key shape:
|
||||
|
||||
1. **Mode matches key shape** (`entitySession == isJust connId_`): in-place demotion via `setSubsPending_` — active subs move to pending within the same `SessSubs` entry. Session ID is cleared (`Nothing`).
|
||||
|
||||
2. **Mode mismatch** (e.g., switching from shared session to entity mode): the entire `SessSubs` entry is **deleted** from the map (`TM.lookupDelete`), and all subscriptions are redistributed to new per-entity session keys via `addPendingSub (uId, srv, sessEntId (connId rq))`. This changes the map granularity — one shared entry becomes many entity entries.
|
||||
|
||||
Both paths check `Just sessId == sessId'` first — if the stored session ID doesn't match the one being invalidated, no work is done (returns empty).
|
||||
|
||||
## getSessSubs — lazy initialization
|
||||
|
||||
`getSessSubs` creates a new `SessSubs` entry if none exists for the transport session. This means any write operation (`addPendingSub`, `setSessionId`, etc.) will create map entries as a side effect. Read operations (`hasActiveSub`, `getActiveSubs`) use `lookupSubs` instead, which returns `Nothing`/empty without creating entries.
|
||||
|
||||
## updateClientNotices
|
||||
|
||||
Adjusts the `clientNoticeId` field on pending subscriptions in bulk. Uses `M.adjust`, so missing recipient IDs are silently skipped. Only modifies pending subs — active subs are not touched because they've already been confirmed.
|
||||
@@ -1,85 +0,0 @@
|
||||
# Simplex.Messaging.Client
|
||||
|
||||
> Generic protocol client: connection management, command sending/receiving, batching, proxy protocol, reconnection.
|
||||
|
||||
**Source**: [`Client.hs`](../../../../src/Simplex/Messaging/Client.hs)
|
||||
|
||||
**Protocol spec**: [`protocol/simplex-messaging.md`](../../../../protocol/simplex-messaging.md) — SimpleX Messaging Protocol.
|
||||
|
||||
## Overview
|
||||
|
||||
This module implements the client side of the `Protocol` typeclass — connecting to SMP routers, sending commands, receiving command results, and managing connection lifecycle. It is generic over `Protocol v err msg`, instantiated for SMP as `SMPClient` (= `ProtocolClient SMPVersion ErrorType BrokerMsg`). The SMP proxy protocol (PRXY/PFWD/RFWD) is also implemented here.
|
||||
|
||||
## Four concurrent threads — teardown semantics
|
||||
|
||||
`getProtocolClient` launches four threads via `raceAny_`:
|
||||
- `send`: reads from `sndQ` (TBQueue) and writes to TLS
|
||||
- `receive`: reads from TLS and writes to `rcvQ` (TBQueue), updates `lastReceived`
|
||||
- `process`: reads from `rcvQ` and dispatches to result vars or `msgQ`
|
||||
- `monitor`: periodic ping loop (only when `smpPingInterval > 0`)
|
||||
|
||||
When ANY thread exits (normally or exceptionally), `raceAny_` cancels all others. `E.finally` ensures the `disconnected` callback always fires. Implication: a single stuck thread (e.g., TLS read blocked on a half-open connection) keeps the entire client alive until `monitor` drops it. There is no per-thread health check — liveness depends entirely on the monitor's timeout logic.
|
||||
|
||||
## Request lifecycle and leak risk
|
||||
|
||||
`mkRequest` inserts a `Request` into `sentCommands` TMap BEFORE the transmission is written to TLS. If the TLS write fails silently or the connection drops before the result arrives, the entry remains in `sentCommands` until the monitor's timeout counter exceeds `maxCnt` and drops the entire client. There is no per-request cleanup on send failure — individual request entries are only removed by `processMsg` (on result) or by `getResponse` timeout (which sets `pending = False` but doesn't remove the entry).
|
||||
|
||||
## getResponse — pending flag race contract
|
||||
|
||||
This is the core concurrency contract between timeout and result processing:
|
||||
|
||||
1. `getResponse` waits with `timeout` for `takeTMVar responseVar`
|
||||
2. Regardless of result, atomically sets `pending = False` and tries `tryTakeTMVar` again (see comment on `getResponse`)
|
||||
3. In `processMsg`, when a result arrives for a request where `pending` is already `False` (timeout won), `wasPending` is `False` and the result is forwarded to `msgQ` as `STResponse` rather than discarded
|
||||
|
||||
The double-check pattern (`swapTVar pending False` + `tryTakeTMVar`) handles the race window where a result arrives between timeout firing and `pending` being set to `False`. Without this, results arriving in that gap would be silently lost.
|
||||
|
||||
`timeoutErrorCount` is reset to 0 in three places: in `getResponse` when a result arrives, in `receive` on every TLS read, and the monitor uses this count to decide when to drop the connection.
|
||||
|
||||
## processMsg — router events vs expired results
|
||||
|
||||
When `corrId` is empty, the message is an `STEvent` (router-initiated). When non-empty and the request was already expired (`wasPending` is `False`), the result becomes `STResponse` — not discarded, but forwarded to `msgQ` with the original command context. Entity ID mismatch is `STUnexpectedError`.
|
||||
|
||||
## nonBlockingWriteTBQueue — fork on full
|
||||
|
||||
If `tryWriteTBQueue` returns `False` (queue full), a new thread is forked for the blocking write. The caller never blocks, preventing deadlock between send and process threads.
|
||||
|
||||
## Batch commands do not expire
|
||||
|
||||
See comment on `sendBatch`. Batched commands are written with `Nothing` as the request parameter — the send thread skips the `pending` flag check. Individual commands use `Just r` and the send thread checks `pending` after dequeue. The coupling: if the router stops returning results, batched commands can block the send queue indefinitely since they have no timeout-based expiry.
|
||||
|
||||
## monitor — quasi-periodic adaptive ping
|
||||
|
||||
The ping loop sleeps for `smpPingInterval`, then checks elapsed time since `lastReceived`. If significant time remains in the interval (> 1 second), it re-sleeps for just the remaining time rather than sending a ping. This means ping frequency adapts to actual receive activity — frequent receives suppress pings.
|
||||
|
||||
Pings are only sent when `sendPings` is `True`, set by `enablePings` (called from `subscribeSMPQueue`, `subscribeSMPQueues`, `subscribeSMPQueueNotifications`, `subscribeSMPQueuesNtfs`, `subscribeService`). The client drops the connection when `maxCnt` commands have timed out in sequence AND at least `recoverWindow` (15 minutes) has passed since the last received result.
|
||||
|
||||
## clientCorrId — dual-purpose random values
|
||||
|
||||
`clientCorrId` is a `TVar ChaChaDRG` generating random `CbNonce` values that serve as both correlation IDs and nonces for proxy encryption. When a nonce is explicitly passed (e.g., by `createSMPQueue`), it is used instead of generating a random one.
|
||||
|
||||
## Proxy command re-parameterization
|
||||
|
||||
`proxySMPCommand` constructs modified `thParams` per-request — setting `sessionId`, `peerServerPubKey`, and `thVersion` to the proxy-relay connection's parameters rather than the client-proxy connection's. A single `SMPClient` connection to the proxy carries commands with different auth parameters per destination relay. The encoding, signing, and encryption all use these per-request params, not the connection's original params.
|
||||
|
||||
## proxySMPCommand — error classification
|
||||
|
||||
See comment above `proxySMPCommand` for the 9 error scenarios (0-9) mapping each combination of success/error at client-proxy and proxy-relay boundaries. Errors from the destination relay wrapped in `PRES` are thrown as `ExceptT` errors (transparent proxy). Errors from the proxy itself are returned as `Left ProxyClientError`.
|
||||
|
||||
## forwardSMPTransmission — proxy-side forwarding
|
||||
|
||||
Used by the proxy router to forward `RFWD` to the destination relay. Uses `cbEncryptNoPad`/`cbDecryptNoPad` (no padding) with the session secret from the proxy-relay connection. Result nonce is `reverseNonce` of the request nonce.
|
||||
|
||||
## authTransmission — dual auth with service signature
|
||||
|
||||
When `useServiceAuth` is `True` and a service certificate is present, the entity key signs over `serviceCertHash <> transmission` (not just the transmission) — see comment on `authTransmission`. The service key only signs the transmission itself. For X25519 keys, `cbAuthenticate` produces a `TAAuthenticator`; for Ed25519/Ed448, `C.sign'` produces a `TASignature`.
|
||||
|
||||
The service signature is only added when the entity authenticator is non-empty. If authenticator generation fails silently (returns empty bytes), service signing is silently skipped. This mirrors the [state-dependent parser contract](./Protocol.md#service-signature--state-dependent-parser-contract) in Protocol.hs.
|
||||
|
||||
## action — weak thread reference
|
||||
|
||||
`action` stores a `Weak ThreadId` (via `mkWeakThreadId`) to the main client thread. `closeProtocolClient` dereferences and kills it. The weak reference allows the thread to be garbage collected if all other references are dropped.
|
||||
|
||||
## writeSMPMessage — router-side event injection
|
||||
|
||||
`writeSMPMessage` writes directly to `msgQ` as `STEvent`, bypassing the entire command/result pipeline. This is used by the router to inject MSG events into the subscription result path.
|
||||
@@ -1,92 +0,0 @@
|
||||
# Simplex.Messaging.Client.Agent
|
||||
|
||||
> SMP client connections with subscription management, reconnection, and service certificate support.
|
||||
|
||||
**Source**: [`Client/Agent.hs`](../../../../../src/Simplex/Messaging/Client/Agent.hs)
|
||||
|
||||
## Overview
|
||||
|
||||
This is the "small agent" — used only in routers (SMP proxy, notification router) to manage client connections to other SMP routers. The "big agent" in `Simplex.Messaging.Agent` + `Simplex.Messaging.Agent.Client` serves client applications and adds the full messaging agent layer. See [Two agent layers](../../../../TOPICS.md) topic.
|
||||
|
||||
`SMPClientAgent` manages `SMPClient` connections via `smpClients :: TMap SMPServer SMPClientVar` (one per router), tracks active and pending subscriptions, and handles automatic reconnection. It is parameterized by `Party` (`p`) and uses the `ServiceParty` constraint to support both `RecipientService` and `NotifierService` modes.
|
||||
|
||||
## Dual subscription model
|
||||
|
||||
Four TMap fields track subscriptions in two dimensions:
|
||||
|
||||
| | Active | Pending |
|
||||
|---|---|---|
|
||||
| **Service** | `activeServiceSubs` (TMap SMPServer (TVar (Maybe (ServiceSub, SessionId)))) | `pendingServiceSubs` (TMap SMPServer (TVar (Maybe ServiceSub))) |
|
||||
| **Queue** | `activeQueueSubs` (TMap SMPServer (TMap QueueId (SessionId, C.APrivateAuthKey))) | `pendingQueueSubs` (TMap SMPServer (TMap QueueId C.APrivateAuthKey)) |
|
||||
|
||||
See comments on `activeServiceSubs` and `pendingServiceSubs` for the coexistence rules. Key constraint: only one service subscription per router. Active subs store the `SessionId` that established them.
|
||||
|
||||
## SessionVar compare-and-swap — core concurrency safety
|
||||
|
||||
`removeSessVar` (in Session.hs) uses `sessionVarId` (monotonically increasing counter from `sessSeq`) to prevent stale removal. When a disconnected client's cleanup runs after a new client already replaced the map entry, the ID mismatch causes removal to silently no-op. See comment on `removeSessVar`. This is used throughout: `removeClientAndSubs` for client map, `cleanup` for worker map.
|
||||
|
||||
## removeClientAndSubs — outside-STM lookup optimization
|
||||
|
||||
See comment on `removeClientAndSubs`. Subscription TVar references are obtained outside STM (via `TM.lookupIO`), then modified inside `atomically`. This is safe because the invariant is that subscription TVar entries for a router are never deleted from the outer TMap, only their contents change. Moving lookups inside the STM transaction would cause excessive re-evaluation under contention.
|
||||
|
||||
## Disconnect preserves others' subscriptions
|
||||
|
||||
`updateServiceSub` only moves active→pending when `sessId` matches the disconnected client (see its comment). If a new client already established different subscriptions on the same router, those are preserved. Queue subs use `M.partition` to split by SessionId — only matching subs move to pending, non-matching remain active.
|
||||
|
||||
## Pending never reset to Nothing on disconnect
|
||||
|
||||
See comment on `updateServiceSub`. After clearing an active service sub, the code sets pending to the cleared value but does NOT reset pending to `Nothing`. This avoids the race where a concurrent new client session has already set a different pending subscription. Implication: pending subs can only grow (be set) during disconnect, never shrink (be cleared).
|
||||
|
||||
## persistErrorInterval — delayed error cleanup
|
||||
|
||||
When `connectClient` calls `newSMPClient` and it fails, the error is stored with an expiry timestamp. `waitForSMPClient` checks expiry before retrying. When `persistErrorInterval` is 0, the error is stored without timestamp and the SessionVar is immediately removed from the map.
|
||||
|
||||
## Session validation after subscription RPC
|
||||
|
||||
Both `smpSubscribeQueues` and `smpSubscribeService` validate `activeClientSession` AFTER the subscription RPC completes, before committing results to state. If the session changed during the RPC (client reconnected), results are discarded and reconnection is triggered. This is optimistic execution with post-hoc validation — the RPC may succeed but its results are thrown away if the session is stale.
|
||||
|
||||
## groupSub — subscription result classification
|
||||
|
||||
Each queue result is classified by a `foldr` over the (subs, results) zip:
|
||||
|
||||
- **Success with matching serviceId**: counted as service-subscribed (`sQs` list)
|
||||
- **Success without matching serviceId**: counted as queue-only (`qOks` list with SessionId and key)
|
||||
- **Not in pending map**: silently skipped (handles concurrent activation by another path)
|
||||
- **Temporary error** (network, timeout): sets the `tempErrs` flag but does NOT remove from pending — queue stays pending for retry on reconnect
|
||||
- **Permanent error**: removes from pending and added to `finalErrs` — terminal, no automatic retry
|
||||
|
||||
Even if multiple temporary errors occur in a batch, only one `reconnectClient` call is made (via the boolean accumulator flag).
|
||||
|
||||
## updateActiveServiceSub — accumulative merge
|
||||
|
||||
When serviceId and sessionId match the existing active subscription, queue count is added (`n + n'`) and IdsHash is XOR-merged (`idsHash <> idsHash'`). This accumulates across multiple subscription batches for the same service. When they don't match, the subscription is replaced entirely (silently drops old data).
|
||||
|
||||
## CAServiceUnavailable — cascade to queue resubscription
|
||||
|
||||
When `smpSubscribeService` detects service ID or role mismatch with the connection, it fires `CAServiceUnavailable`. See comment on `CAServiceUnavailable` for the full implication: the app must resubscribe all queues individually, creating new associations. This can happen if the SMP router reassigns service IDs (e.g., after downgrade and upgrade).
|
||||
|
||||
## getPending — polymorphic over STM/IO
|
||||
|
||||
`getPending` uses rank-2 polymorphism to work in both STM (for the "should we spawn a worker?" check, providing a consistent snapshot) and IO (for the actual reconnection data read, providing fresh data). Between these two calls, new pending subs could be added — the worker loop handles this by re-checking on each iteration.
|
||||
|
||||
## Reconnect worker lifecycle
|
||||
|
||||
### Spawn decision
|
||||
`reconnectClient` checks `active` outside STM, then atomically checks for pending subs and gets/creates a worker SessionVar. If no pending subs exist, no worker is spawned — this prevents race with cleanup and adding pending queues in another call.
|
||||
|
||||
### Worker cleanup blocks on TMVar fill
|
||||
See comment on `cleanup`. The STM `retry` loop waits until the async handle is inserted into the TMVar before removing the worker from the map. Without this, cleanup could race ahead of the `putTMVar` in `newSubWorker`, leaving a terminated worker in the map.
|
||||
|
||||
### Double timeout on reconnection
|
||||
`runSubWorker` wraps the entire reconnection in `System.Timeout.timeout` using `tcpConnectTimeout` in addition to the network-layer timeout. Two layers — network for the connection attempt, outer for the entire operation including subscription.
|
||||
|
||||
### Reconnect filters already-active queues
|
||||
During reconnection, `reconnectSMPClient` reads current active queue subs (outside STM, same "vars never removed" invariant) and filters them out before resubscribing. Subscription is chunked by `agentSubsBatchSize` — partial success is possible across chunks.
|
||||
|
||||
## Agent shutdown ordering
|
||||
|
||||
`closeSMPClientAgent` executes in order: set `active = False`, close all client connections, then swap workers map to empty and fork cancellation threads. The cancel threads use `uninterruptibleCancel` but are fire-and-forget — `closeSMPClientAgent` may return before all workers are actually cancelled.
|
||||
|
||||
## addSubs_ — left-biased union
|
||||
|
||||
`addSubs_` uses `TM.union` which delegates to `M.union` (left-biased). If a queue subscription already exists, the new auth key from the incoming map wins. Service subs use `writeTVar` (overwrite) since only one service sub exists per router.
|
||||
@@ -1,17 +0,0 @@
|
||||
# Simplex.Messaging.Compression
|
||||
|
||||
> Zstd compression with passthrough for short messages.
|
||||
|
||||
**Source**: [`Compression.hs`](../../../../src/Simplex/Messaging/Compression.hs)
|
||||
|
||||
## compress1
|
||||
|
||||
Messages <= 180 bytes are wrapped as `Passthrough` (no compression). The threshold is empirically derived from real client data — messages above 180 bytes rapidly gain compression ratio.
|
||||
|
||||
## decompress1
|
||||
|
||||
**Security**: decompression bomb protection. Requires `decompressedSize` to be present in the zstd frame header AND within the caller-specified `limit`. If the compressed data doesn't declare its decompressed size (non-standard zstd frames), decompression is refused entirely. This prevents memory exhaustion from malicious compressed payloads.
|
||||
|
||||
## Wire format
|
||||
|
||||
Tag byte `'0'` (0x30) = passthrough (1-byte length prefix, raw data). Tag byte `'1'` (0x31) = compressed (2-byte `Large` length prefix, zstd data). The passthrough path uses the standard `ByteString` encoding (255-byte limit); the compressed path uses `Large` (65535-byte limit).
|
||||
@@ -1,94 +0,0 @@
|
||||
# Simplex.Messaging.Crypto
|
||||
|
||||
> Core cryptographic primitives: key types, NaCl crypto_box/secret_box, AEAD-GCM, signing, padding, X509, HKDF.
|
||||
|
||||
**Source**: [`Crypto.hs`](../../../../src/Simplex/Messaging/Crypto.hs)
|
||||
|
||||
## Overview
|
||||
|
||||
This is the largest crypto module (~1540 lines). It defines the type-level algorithm system (GADTs + type families), all key types, and the fundamental encrypt/decrypt/sign/verify operations used throughout the protocol stack. Higher-level modules ([Ratchet](./Crypto/Ratchet.md), [Lazy](./Crypto/Lazy.md), [File](./Crypto/File.md)) build on these primitives.
|
||||
|
||||
## Algorithm type system
|
||||
|
||||
Four algorithms (`Ed25519`, `Ed448`, `X25519`, `X448`) are encoded as a promoted data kind `Algorithm`. Type families constrain which algorithms support which operations:
|
||||
|
||||
- `SignatureAlgorithm`: only `Ed25519`, `Ed448`
|
||||
- `DhAlgorithm`: only `X25519`, `X448`
|
||||
- `AuthAlgorithm`: `Ed25519`, `Ed448`, `X25519` (but NOT `X448`)
|
||||
|
||||
Using the wrong algorithm produces a **compile-time error** via `TypeError`. The runtime bridge uses `Dict` from `Data.Constraint` — functions like `signatureAlgorithm :: SAlgorithm a -> Maybe (Dict (SignatureAlgorithm a))` allow dynamic dispatch while preserving type safety.
|
||||
|
||||
## PrivateKeyEd25519 StrEncoding deliberately omitted
|
||||
|
||||
The `StrEncoding` instance for `PrivateKey Ed25519` is commented out with the note "Do not enable, to avoid leaking key data." Only `PrivateKey X25519` has `StrEncoding`, used specifically for the notification store log. This is a deliberate security decision — Ed25519 signing keys should never appear in human-readable formats.
|
||||
|
||||
## Two AEAD initialization paths
|
||||
|
||||
- **`initAEAD`**: Takes 16-byte `IV`, transforms it internally via `cryptonite_aes_gcm_init`. Used by the double ratchet.
|
||||
- **`initAEADGCM`**: Takes 12-byte `GCMIV`, does NOT transform. Used for WebRTC frame encryption.
|
||||
|
||||
These are **not interchangeable** — using the wrong IV size or init function produces silent corruption. The code comments note that WebCrypto compatibility requires `initAEADGCM`, and the ratchet may need to migrate away from `initAEAD` in the future.
|
||||
|
||||
## cbNonce — silent truncation/padding
|
||||
|
||||
`cbNonce` adjusts any ByteString to exactly 24 bytes:
|
||||
- If longer: silently truncates to first 24 bytes
|
||||
- If shorter: silently pads with zero bytes
|
||||
|
||||
No error is raised for incorrect input lengths. This means a programming error passing the wrong-length nonce will produce valid but wrong encryption, not a failure.
|
||||
|
||||
## pad / unPad — 2-byte length prefix
|
||||
|
||||
`pad` prepends a 2-byte big-endian `Word16` length, then the message, then `'#'` padding characters to fill `paddedLen`. Maximum message length is `2^16 - 3 = 65533` bytes. The `'#'` padding character is a convention, not verified on decode — `unPad` only reads the length prefix and extracts that many bytes.
|
||||
|
||||
Contrast with [Simplex.Messaging.Crypto.Lazy.pad](./Crypto/Lazy.md#padding-8-byte-length-prefix) which uses an 8-byte `Int64` prefix for file-sized data.
|
||||
|
||||
## crypto_box / secret_box
|
||||
|
||||
Both use the same underlying `xSalsa20` + `Poly1305.auth` implementation. The difference is only in the key:
|
||||
- **crypto_box** (`cbEncrypt`/`cbDecrypt`): uses a DH shared secret (`DhSecret X25519`)
|
||||
- **secret_box** (`sbEncrypt`/`sbDecrypt`): uses a symmetric key (`SbKey`, 32 bytes)
|
||||
|
||||
Both apply `pad`/`unPad` by default. The `NoPad` variants skip padding.
|
||||
|
||||
## xSalsa20
|
||||
|
||||
The XSalsa20 implementation splits the 24-byte nonce into two 8-byte halves. The first half initializes the cipher state (prepended with 16 zero bytes), the second derives a subkey. The first 32 bytes of output become the Poly1305 one-time key (`rs`), then the rest encrypts the message. This is the standard NaCl construction.
|
||||
|
||||
## Secret box chains (sbcInit / sbcHkdf)
|
||||
|
||||
HKDF-based key chains for deriving sequential key+nonce pairs:
|
||||
- `sbcInit`: derives two 32-byte chain keys from a salt and shared secret using `HKDF(salt, secret, "SimpleXSbChainInit", 64)`
|
||||
- `sbcHkdf`: advances a chain key, producing a new chain key (32 bytes), an SbKey (32 bytes), and a CbNonce (24 bytes) from `HKDF("", chainKey, "SimpleXSbChain", 88)`
|
||||
|
||||
## Key encoding
|
||||
|
||||
All keys are encoded as ASN.1 DER (X.509 SubjectPublicKeyInfo for public, PKCS#8 for private). The algorithm is determined by the encoded key length on decode — `decodePubKey` / `decodePrivKey` parse the ASN.1 structure, then dispatch on the X.509 key type.
|
||||
|
||||
## Signature algorithm detection
|
||||
|
||||
`decodeSignature` determines the algorithm by signature length: Ed25519 signatures are 64 bytes, Ed448 signatures are 114 bytes. Any other size is rejected.
|
||||
|
||||
## GCMIV constructor not exported
|
||||
|
||||
`GCMIV` constructor is not exported — only `gcmIV :: ByteString -> Either CryptoError GCMIV` is available, which validates that the input is exactly 12 bytes. This prevents construction of invalid IVs.
|
||||
|
||||
## verify silently returns False on algorithm mismatch
|
||||
|
||||
`verify :: APublicVerifyKey -> ASignature -> ByteString -> Bool` uses `testEquality` on the algorithm singletons. If the key is Ed25519 but the signature is Ed448 (or vice versa), `testEquality` fails and `verify` returns `False` — no error, no indication of a type mismatch. A correctly-formed signature can "fail" simply because the wrong algorithm key was passed.
|
||||
|
||||
## dh' returns raw DH output — no key derivation
|
||||
|
||||
`dh'` returns the raw X25519/X448 shared point with no hashing or HKDF. Callers must apply their own KDF: [SNTRUP761](./Crypto/SNTRUP761.md) hashes with SHA3-256, the [ratchet](./Crypto/Ratchet.md#kdf-functions) uses HKDF-SHA512. Not all DH libraries behave this way — some hash the output automatically.
|
||||
|
||||
## reverseNonce
|
||||
|
||||
`reverseNonce` creates a "reply" nonce by byte-reversing the original 24-byte nonce. Used for bidirectional communication where both sides need distinct nonces derived from the same starting value. The two nonces are guaranteed distinct unless the original is a byte palindrome, which is astronomically unlikely for random 24-byte values.
|
||||
|
||||
## CbAuthenticator
|
||||
|
||||
An authentication scheme that encrypts the SHA-512 hash of the message using crypto_box, rather than the message itself. The result is 80 bytes (64 hash + 16 auth tag). This is the djb-recommended authenticator scheme: it proves knowledge of the shared secret and the message content, without requiring the message to fit in a single crypto_box, and without revealing message content even to someone who compromises the shared key after verification.
|
||||
|
||||
## generateKeyPair is STM
|
||||
|
||||
Key generation uses `TVar ChaChaDRG` and runs in `STM`, not `IO`. This allows key generation inside `atomically` blocks, which is used extensively in handshake and ratchet initialization code.
|
||||
@@ -1,25 +0,0 @@
|
||||
# Simplex.Messaging.Crypto.File
|
||||
|
||||
> Streaming encrypted file I/O using NaCl secret_box with tail auth tag.
|
||||
|
||||
**Source**: [`Crypto/File.hs`](../../../../../src/Simplex/Messaging/Crypto/File.hs)
|
||||
|
||||
## Overview
|
||||
|
||||
`CryptoFileHandle` wraps a file `Handle` with an optional `TVar SbState` for streaming encryption/decryption. When `cryptoArgs` is `Nothing`, the file is plaintext and all operations pass through directly.
|
||||
|
||||
## Auth tag position
|
||||
|
||||
The auth tag is written/read **at the end of the file** (tail tag pattern), not prepended. This is important for streaming: `hPut` encrypts chunks as they arrive, accumulating the Poly1305 state in the TVar, and `hPutTag` finalizes and writes the 16-byte tag only after all data is written.
|
||||
|
||||
## hGetTag
|
||||
|
||||
**Security**: Uses `BA.constEq` for constant-time tag comparison, preventing timing side-channels. Must be called after reading all content bytes — it reads exactly `authTagSize` (16) remaining bytes and compares against the finalized Poly1305 state. Caller must know the file size and read only the content portion before calling this.
|
||||
|
||||
## getFileContentsSize
|
||||
|
||||
Subtracts `authTagSize` from the file size when crypto args are present. This gives the content size without the tag, which is needed to know how many bytes to read before calling `hGetTag`.
|
||||
|
||||
## readFile / writeFile
|
||||
|
||||
Whole-file variants that read/write everything at once. `readFile` uses `sbDecryptChunk` (encrypt-then-MAC verification — feeds ciphertext to Poly1305), while `writeFile` uses `sbEncryptChunk`. Both use the tail tag layout via [Simplex.Messaging.Crypto.Lazy](./Lazy.md) functions.
|
||||
@@ -1,40 +0,0 @@
|
||||
# Simplex.Messaging.Crypto.Lazy
|
||||
|
||||
> Streaming NaCl secret_box (XSalsa20 + Poly1305) for lazy ByteStrings.
|
||||
|
||||
**Source**: [`Crypto/Lazy.hs`](../../../../../src/Simplex/Messaging/Crypto/Lazy.hs)
|
||||
|
||||
## Overview
|
||||
|
||||
Lazy counterpart to the strict NaCl operations in [Simplex.Messaging.Crypto](../Crypto.md). Processes data chunk-by-chunk via `SbState = (XSalsa.State, Poly1305.State)`, enabling streaming encryption of large files without loading everything into memory.
|
||||
|
||||
## Encrypt-then-MAC asymmetry
|
||||
|
||||
`sbEncryptChunk` and `sbDecryptChunk` both use XSalsa20 for the cipher operation, but feed different data to Poly1305:
|
||||
|
||||
- **Encrypt**: feeds the **ciphertext** to Poly1305 (`Poly1305.update authSt c`)
|
||||
- **Decrypt**: feeds the **original ciphertext** (the input chunk) to Poly1305 (`Poly1305.update authSt chunk`), not the decrypted plaintext
|
||||
|
||||
This is the correct encrypt-then-MAC pattern: the MAC is always computed over ciphertext, so both sides compute the same tag.
|
||||
|
||||
## Padding: 8-byte length prefix
|
||||
|
||||
`pad` uses an 8-byte `Int64` length prefix (via `smpEncode`), unlike [Simplex.Messaging.Crypto.pad](../Crypto.md#pad) which uses a 2-byte `Word16` prefix. This is because lazy operations handle file-sized data that can exceed 65535 bytes.
|
||||
|
||||
`unPad` / `splitLen` does not validate that the remaining data is at least `len` bytes — it uses `LB.take len` which silently returns a shorter result. The comment notes this is intentional to avoid consuming all chunks for validation.
|
||||
|
||||
## Auth tag placement: prepend vs tail
|
||||
|
||||
Two families of functions:
|
||||
- **`sbEncrypt` / `sbDecrypt`**: tag is **prepended** (first 16 bytes of output). Used for message-sized data.
|
||||
- **`sbEncryptTailTag` / `sbDecryptTailTag`**: tag is **appended** (last 16 bytes). More efficient for large files because you don't need to buffer the tag before the content.
|
||||
|
||||
The tail-tag variants also support `KEMHybridSecret` via `kcbEncryptTailTag` / `kcbDecryptTailTag`.
|
||||
|
||||
## sbDecryptTailTag validity
|
||||
|
||||
`sbDecryptTailTag` returns `(Bool, LazyByteString)` — the `Bool` indicates whether the auth tag was valid, but the decrypted data is returned regardless. This allows the caller to decide how to handle invalid tags (e.g., [Simplex.Messaging.Crypto.File](./File.md) uses strict `unless` checks).
|
||||
|
||||
## fastReplicate
|
||||
|
||||
Optimizes large padding by building the lazy ByteString from 64KB chunks (minus GHC overhead for `Int` size) rather than one enormous strict ByteString. This avoids allocating a single contiguous buffer for multi-megabyte padding.
|
||||
@@ -1,125 +0,0 @@
|
||||
# Simplex.Messaging.Crypto.Ratchet
|
||||
|
||||
> Double ratchet with post-quantum KEM extension (PQ X3DH + header encryption).
|
||||
|
||||
**Source**: [`Crypto/Ratchet.hs`](../../../../../src/Simplex/Messaging/Crypto/Ratchet.hs)
|
||||
|
||||
## Overview
|
||||
|
||||
Implements the Signal double ratchet protocol extended with:
|
||||
- **Header encryption** (HE variant): message headers are encrypted with separate header keys, hiding the ratchet public key and message counters from observers.
|
||||
- **Post-quantum KEM** (PQ variant): SNTRUP761 key encapsulation is folded into each ratchet step, providing PQ-resistance alongside X448 DH.
|
||||
|
||||
The ratchet uses X448 (not X25519) for DH operations — `type RatchetX448 = Ratchet 'X448`.
|
||||
|
||||
**Protocol spec**: [`protocol/pqdr.md`](../../../../protocol/pqdr.md) — Post-quantum resistant augmented double ratchet algorithm.
|
||||
|
||||
## PQ X3DH key agreement
|
||||
|
||||
`pqX3dhSnd` / `pqX3dhRcv` perform the extended X3DH:
|
||||
- Standard triple DH: `DH(rk1, spk2)`, `DH(rk2, spk1)`, `DH(rk2, spk2)`
|
||||
- Optional KEM shared secret from SNTRUP761 encapsulation
|
||||
- Combined via `HKDF(salt=64_zeroes, DHs || KEMss, "SimpleXX3DH", 96)` → root key, header key, next-header key
|
||||
|
||||
The roles (who is "Alice" vs "Bob") are **reversed from the double ratchet spec**: the party initiating the connection is Bob (`generateRcvE2EParams`, `initRcvRatchet`), and the party accepting is Alice (`generateSndE2EParams`, `initSndRatchet`). Comments in the source explicitly note this.
|
||||
|
||||
## KDF functions
|
||||
|
||||
- **rootKdf**: `HKDF(rootKey, DH(pubKey, privKey) || KEMss, "SimpleXRootRatchet", 96)` → new root key (32), chain key (32), next header key (32)
|
||||
- **chainKdf**: `HKDF("", chainKey, "SimpleXChainRatchet", 96)` → new chain key (32), message key (32), two IVs (16 + 16)
|
||||
|
||||
All use HKDF-SHA512 via [Simplex.Messaging.Crypto.hkdf](../Crypto.md).
|
||||
|
||||
## Header encryption and padding
|
||||
|
||||
Headers are encrypted with AEAD-GCM using the header key. The padded header length depends on whether PQ is supported:
|
||||
- **Without PQ**: 88 bytes (fits DH key + counters)
|
||||
- **With PQ**: 2310 bytes (fits DH key + KEM params + counters, with reserve for future extension)
|
||||
|
||||
The actual header is ~69 bytes without PQ, ~2288 with PQ. The padding ensures all messages have identical header sizes regardless of content.
|
||||
|
||||
## Version negotiation in headers
|
||||
|
||||
Each message header carries `msgMaxVersion` (the sender's max supported ratchet version). On decryption, the receiver upgrades its `current` version to `min(msgMaxVersion, maxSupported)` but never downgrades. The current version determines:
|
||||
- Whether KEM params are included in headers (v3+)
|
||||
- Whether 2-byte length prefixes are used for headers (v3+)
|
||||
|
||||
## largeP — backward-compatible length prefix parsing
|
||||
|
||||
`largeP` detects the length-prefix format by peeking at the first byte: if < 32, it's a 2-byte `Large` prefix (new format); otherwise it's a 1-byte prefix (old format). This allows upgrading the header encoding format in a single message without a version bump.
|
||||
|
||||
## maxSkip = 512 — DoS protection
|
||||
|
||||
`maxSkip` is a hardcoded constant (not configurable). Messages claiming to be more than 512 positions ahead of the current counter are rejected with `CERatchetTooManySkipped`. This prevents an attacker from forcing the receiver to compute and store an unbounded number of skipped message keys.
|
||||
|
||||
## Skipped message keys
|
||||
|
||||
When messages arrive out of order, the ratchet computes and stores the message keys for skipped messages (up to `maxSkip`). Skipped keys are stored in a `Map HeaderKey (Map Word32 MessageKey)` — keyed first by header key, then by message number.
|
||||
|
||||
The `SkippedMsgDiff` type represents changes to the skipped key store as a diff rather than a full replacement — this is persisted to the database, and the full state is loaded for the next message. `applySMDiff` is only used in tests.
|
||||
|
||||
## rcDecrypt flow
|
||||
|
||||
Decryption tries three strategies in order:
|
||||
1. **Skipped message keys**: try all stored header keys to decrypt the header, then look up the message number in skipped keys
|
||||
2. **Current receiving ratchet**: decrypt header with `rcHKr`
|
||||
3. **Next header key**: decrypt header with `rcNHKr` (triggers a ratchet advance)
|
||||
|
||||
If strategy 1 decrypts the header but the message number isn't in skipped keys, it checks whether this header key corresponds to the current or next ratchet to decide whether to advance.
|
||||
|
||||
### decryptSkipped — linear scan through all stored header keys
|
||||
|
||||
`decryptSkipped` iterates through ALL `(HeaderKey, SkippedHdrMsgKeys)` pairs, attempting header decryption with each key. When header decryption succeeds but the message number is NOT in the skipped keys for that header, the result is `SMHeader` — which includes whether the key matches the current ratchet (`rcHKr` → `SameRatchet`) or the next ratchet (`rcNHKr` → `AdvanceRatchet`). This falls through to normal decryption processing rather than producing an error.
|
||||
|
||||
### decryptMessage — ratchet advances even on failure
|
||||
|
||||
`decryptMessage` returns `Either CryptoError ByteString` inside the `ExceptT` monad — a message decryption failure does NOT abort the ratchet state update. The ratchet counter advances (`rcNr + 1`) and chain key updates (`rcCKr'`) regardless of whether the message body decrypts successfully. This preserves ratchet state consistency for retransmission and error recovery.
|
||||
|
||||
## rcEncryptHeader — separated from rcEncryptMsg
|
||||
|
||||
Encryption is split into two steps: `rcEncryptHeader` produces a `MsgEncryptKey` (containing the encrypted header and message key), then `rcEncryptMsg` uses that key to encrypt the message body. This separation allows the ratchet state to be updated (persisted) before the message is encrypted, which is important for crash recovery — if the process crashes after encrypting but before sending, the ratchet state must already reflect the advanced counter.
|
||||
|
||||
## PQ ratchet step
|
||||
|
||||
During each ratchet advance (`pqRatchetStep`), the PQ KEM is folded in:
|
||||
1. Receive: if the header contains a KEM ciphertext and we have the decapsulation key, compute the shared secret
|
||||
2. Send: generate a new KEM keypair, encapsulate against the received public key, include in the next header
|
||||
3. The KEM shared secret is concatenated with the DH shared secret before `rootKdf`
|
||||
|
||||
PQ can be enabled/disabled per-message via `pqEnc_` parameter. `rcSupportKEM` can only be enabled (never disabled) — once PQ headers are used, the larger header size is permanent.
|
||||
|
||||
## PQSupport vs PQEncryption
|
||||
|
||||
Two distinct newtypes with identical structure (`Bool` wrapper):
|
||||
- `PQSupport`: whether PQ **can** be used (determines header padding size, cannot be disabled once enabled)
|
||||
- `PQEncryption`: whether PQ **is** being used for the current send/receive ratchet
|
||||
|
||||
### pqEnableSupport is monotonic
|
||||
|
||||
`pqEnableSupport v sup enc = PQSupport $ sup || (v >= pqRatchetE2EEncryptVersion && enc)`. The `||` means once PQ support is `True`, it stays `True` regardless of subsequent messages. PQ encryption (usage) can be toggled per-message; PQ support (capability / header size) only ratchets up. This prevents the larger header format from being downgraded once negotiated.
|
||||
|
||||
## replyKEM_ — two-step KEM negotiation
|
||||
|
||||
KEM establishment requires two message round-trips, as described in the [PQDR KEM state machine](../../../../protocol/pqdr.md#kem-state-machine):
|
||||
|
||||
1. **Propose**: if the sender has no KEM in their header but the replier supports PQ at sufficient version, the replier includes a KEM proposal (`RKParamsProposed` — their encapsulation public key)
|
||||
2. **Accept**: if the sender proposed KEM, the replier accepts by encapsulating against the proposed key and including the ciphertext + their own new encapsulation key (`RKParamsAccepted`)
|
||||
|
||||
After acceptance, both sides have a shared KEM secret that is folded into the root KDF. Subsequent ratchet steps continue the KEM exchange with fresh keypairs on each side.
|
||||
|
||||
## Error semantics
|
||||
|
||||
- `CERatchetEarlierMessage n`: message number is `n` positions before the next expected (already processed or skipped-and-consumed)
|
||||
- `CERatchetDuplicateMessage`: message number is the most recently received (exact repeat)
|
||||
- `CERatchetTooManySkipped n`: would need to skip `n` messages, exceeding `maxSkip`
|
||||
- `CERatchetHeader`: header decryption failed with all available keys
|
||||
- `CERatchetState`: no sending chain (ratchet not initialized for sending)
|
||||
- `CERatchetKEMState`: KEM state mismatch between parties
|
||||
|
||||
## InitialKeys
|
||||
|
||||
Controls PQ key inclusion in connection establishment:
|
||||
- `IKUsePQ`: always include PQ keys (used in contact requests and short link data)
|
||||
- `IKLinkPQ pq`: include PQ keys only in short link data, if `pq` is enabled
|
||||
|
||||
`initialPQEncryption` resolves this based on whether it's a short link context.
|
||||
@@ -1,13 +0,0 @@
|
||||
# Simplex.Messaging.Crypto.SNTRUP761
|
||||
|
||||
> Hybrid KEM+DH shared secret combining SNTRUP761 and X25519.
|
||||
|
||||
**Source**: [`Crypto/SNTRUP761.hs`](../../../../../src/Simplex/Messaging/Crypto/SNTRUP761.hs)
|
||||
|
||||
## kemHybridSecret
|
||||
|
||||
The hybrid secret is `SHA3_256(DHSecret || KEMSharedKey)` — not a simple concatenation, not HKDF. This follows the approach in draft-josefsson-ntruprime-hybrid. The result is a `ScrubbedBytes` value used as a symmetric key for NaCl crypto_box operations via `sbEncrypt_`/`sbDecrypt_`.
|
||||
|
||||
## kcbEncrypt / kcbDecrypt
|
||||
|
||||
These delegate directly to `sbEncrypt_` / `sbDecrypt_` from [Simplex.Messaging.Crypto](../Crypto.md), using the hybrid secret as the symmetric key. The hybrid secret is 32 bytes (SHA3-256 output), matching the expected key size for XSalsa20.
|
||||
@@ -1,36 +0,0 @@
|
||||
# Simplex.Messaging.Crypto.ShortLink
|
||||
|
||||
> Short link key derivation, encryption, and signature verification for contact/invitation links.
|
||||
|
||||
**Source**: [`Crypto/ShortLink.hs`](../../../../../src/Simplex/Messaging/Crypto/ShortLink.hs)
|
||||
|
||||
## Overview
|
||||
|
||||
Short links encode connection data in two encrypted blobs: fixed data (2048 bytes padded) and user data (13824 bytes padded). Both are encrypted with `sbEncrypt` using a key derived from the link key via HKDF.
|
||||
|
||||
## KDF schemes
|
||||
|
||||
Two distinct HKDF derivations with different info strings:
|
||||
|
||||
- **contactShortLinkKdf**: `HKDF("", linkKey, "SimpleXContactLink", 56)` → splits into 24-byte LinkId + 32-byte SbKey. The LinkId is used as the router-side identifier.
|
||||
- **invShortLinkKdf**: `HKDF("", linkKey, "SimpleXInvLink", 32)` → 32-byte SbKey only. No LinkId because invitation links don't use router-side lookup.
|
||||
|
||||
## Fixed padding lengths
|
||||
|
||||
- `fixedDataPaddedLength = 2008` (2048 - 24 nonce - 16 auth tag)
|
||||
- `userDataPaddedLength = 13784` (13824 - 24 - 16)
|
||||
|
||||
These are chosen so the encrypted output (with prepended nonce and appended auth tag) fits exactly in round sizes.
|
||||
|
||||
## decryptLinkData
|
||||
|
||||
**Security**: Performs three-layer verification in order:
|
||||
1. Hash check: `SHA3_256(fixedData) == linkKey` — ensures data integrity
|
||||
2. Root key signature: `verify(rootKey, sig1, fixedData)` — ensures authenticity
|
||||
3. User data signature: `verify(rootKey, sig2, userData)` for invitations, or verify against any owner key for contact links
|
||||
|
||||
For contact links, also calls `validateLinkOwners` to verify the owner chain of trust (each owner is signed by the root key).
|
||||
|
||||
## encodeSign
|
||||
|
||||
Prepends the Ed25519 signature to the data: `smpEncode(sign(pk, data)) <> data`. This is the format expected by `decryptLinkData`'s parser.
|
||||
@@ -1,39 +0,0 @@
|
||||
# Simplex.Messaging.Encoding
|
||||
|
||||
> Binary wire-format encoding for SMP protocol transmission.
|
||||
|
||||
**Source**: [`Encoding.hs`](../../../../src/Simplex/Messaging/Encoding.hs)
|
||||
|
||||
## Overview
|
||||
|
||||
`Encoding` is the binary wire format — fixed-size or length-prefixed, no delimiters between fields. Contrast with [Simplex.Messaging.Encoding.String](./Encoding/String.md) which is the human-readable, space-delimited, base64url format used in URIs and logs.
|
||||
|
||||
The two encoding classes share some instances (`Char`, `Bool`, `SystemTime`) but differ fundamentally: `Encoding` is self-delimiting via length prefixes, `StrEncoding` is delimiter-based (spaces, commas).
|
||||
|
||||
## ByteString instance
|
||||
|
||||
**Length prefix is 1 byte.** Maximum encodable length is 255 bytes. If a ByteString exceeds 255 bytes, the length silently wraps via `w2c . fromIntegral` — a 300-byte string encodes length as 44 (300 mod 256). Callers must ensure ByteStrings fit in 255 bytes, or use `Large` for longer values.
|
||||
|
||||
## Large
|
||||
|
||||
2-byte length prefix (`Word16`). Use for ByteStrings that may exceed 255 bytes. Maximum 65535 bytes.
|
||||
|
||||
## Maybe instance
|
||||
|
||||
Tags are ASCII characters `'0'` (0x30) and `'1'` (0x31), not bytes 0x00/0x01. `Nothing` encodes as the single byte 0x30; `Just x` encodes as 0x31 followed by `smpEncode x`.
|
||||
|
||||
## Tail
|
||||
|
||||
Consumes all remaining input. Must be the last field in any composite encoding — placing it elsewhere silently eats subsequent fields.
|
||||
|
||||
## Tuple instances
|
||||
|
||||
Sequential concatenation with no separators. Works because each element's encoding is self-delimiting (length-prefixed ByteString, fixed-size Word16/Word32/Int64/Char, etc.). If an element type isn't self-delimiting, the tuple won't round-trip.
|
||||
|
||||
## SystemTime
|
||||
|
||||
Only seconds are encoded (as Int64); nanoseconds are discarded on encode and set to 0 on decode.
|
||||
|
||||
## smpEncodeList / smpListP
|
||||
|
||||
1-byte length prefix for lists — same 255-item limit as ByteString's 255-byte limit.
|
||||
@@ -1,43 +0,0 @@
|
||||
# Simplex.Messaging.Encoding.String
|
||||
|
||||
> Human-readable, URI-friendly string encoding for SMP and agent protocols.
|
||||
|
||||
**Source**: [`Encoding/String.hs`](../../../../../src/Simplex/Messaging/Encoding/String.hs)
|
||||
|
||||
## Overview
|
||||
|
||||
`StrEncoding` is the human-readable counterpart to [Simplex.Messaging.Encoding](../Encoding.md)'s binary `Encoding`. Key differences:
|
||||
|
||||
| Aspect | `Encoding` (binary) | `StrEncoding` (string) |
|
||||
|--------|---------------------|------------------------|
|
||||
| ByteString | 1-byte length prefix, raw bytes | base64url encoded |
|
||||
| Tuple separator | none (self-delimiting) | space-delimited |
|
||||
| List separator | 1-byte count prefix | comma-separated |
|
||||
| Default parser fallback | `smpP` via `parseAll` | `strP` via `base64urlP` |
|
||||
|
||||
## ByteString instance
|
||||
|
||||
Encodes as base64url. The parser (`strP`) only accepts non-empty strings — empty base64url input fails.
|
||||
|
||||
## String instance
|
||||
|
||||
Inherits from ByteString via `B.pack` / `B.unpack`. Only Char8 (Latin-1) characters round-trip.
|
||||
|
||||
## strToJSON / strParseJSON
|
||||
|
||||
`strToJSON` uses `decodeLatin1`, not `decodeUtf8'`. This preserves arbitrary byte sequences (e.g., base64url-encoded binary data) as JSON strings without UTF-8 validation errors, but means the JSON representation is Latin-1, not UTF-8.
|
||||
|
||||
## Class default: strP assumes base64url for all types
|
||||
|
||||
The `MINIMAL` pragma allows defining only `strDecode` without `strP`. But the default `strP = strDecode <$?> base64urlP` then assumes input is base64url-encoded — for *any* type, not just ByteString. Two consequences:
|
||||
|
||||
1. The type's `strDecode` receives raw decoded bytes, not the base64url text. Easy to confuse when implementing a new instance.
|
||||
2. `base64urlP` requires non-empty input (`takeWhile1`), so the default `strP` cannot parse empty values — even if `strDecode ""` would succeed. Types that can encode to empty output must define `strP` explicitly.
|
||||
|
||||
## listItem
|
||||
|
||||
Items are delimited by `,`, ` `, or `\n`. List items cannot contain these characters in their `strEncode` output. No escaping mechanism exists.
|
||||
|
||||
## Str newtype
|
||||
|
||||
Plain text (no base64). Delimited by spaces. `strP` consumes the trailing space — this is unusual and means `Str` parsing has a side effect on the input position that other `StrEncoding` parsers don't.
|
||||
@@ -1,23 +0,0 @@
|
||||
# Simplex.Messaging.Notifications.Client
|
||||
|
||||
> Typed wrappers around `ProtocolClient` for NTF protocol commands.
|
||||
|
||||
**Source**: [`Notifications/Client.hs`](../../../../../src/Simplex/Messaging/Notifications/Client.hs)
|
||||
|
||||
## Non-obvious behavior
|
||||
|
||||
### 1. Subscription operations always use NRMBackground
|
||||
|
||||
`ntfCreateSubscription`, `ntfCheckSubscription`, `ntfDeleteSubscription`, and their batch variants hardcode `NRMBackground` as the network request mode. Token operations (`ntfRegisterToken`, `ntfVerifyToken`, etc.) accept the mode as a parameter. This reflects that subscription management is a background activity driven by the supervisor, while token operations can be user-initiated.
|
||||
|
||||
### 2. Batch operations return per-item errors
|
||||
|
||||
`ntfCreateSubscriptions` and `ntfCheckSubscriptions` return `NonEmpty (Either NtfClientError result)` — individual items in a batch can fail independently. Callers must handle partial success (some created, some failed). The singular variants throw on any error.
|
||||
|
||||
### 3. Default port is 443
|
||||
|
||||
`defaultNTFClientConfig` sets the default transport to `("443", transport @TLS)`. Unlike the SMP protocol which typically uses port 5223, the NTF protocol defaults to the standard HTTPS port.
|
||||
|
||||
### 4. okNtfCommand parameter ordering
|
||||
|
||||
`okNtfCommand` has an unusual parameter order — the command comes first, then client, mode, key, entityId. This enables partial application in the `ntfDeleteToken`, `ntfVerifyToken` etc. definitions, where the command is fixed and the remaining parameters flow through.
|
||||
@@ -1,55 +0,0 @@
|
||||
# Simplex.Messaging.Notifications.Protocol
|
||||
|
||||
> NTF protocol entities, commands, command results, and wire encoding for the notification system.
|
||||
|
||||
**Source**: [`Notifications/Protocol.hs`](../../../../../src/Simplex/Messaging/Notifications/Protocol.hs)
|
||||
|
||||
## Non-obvious behavior
|
||||
|
||||
### 1. Asymmetric credential validation
|
||||
|
||||
`checkCredentials` enforces different rules per command category:
|
||||
|
||||
| Category | Signature required | Entity ID |
|
||||
|----------|-------------------|-----------|
|
||||
| TNEW, SNEW | Yes | Must be empty (new entity) |
|
||||
| PING | No | Must be empty |
|
||||
| All others | Yes | Must be present |
|
||||
|
||||
For command results, the rule inverts: `NRTknId`, `NRSubId`, and `NRPong` must NOT have entity IDs (they are returned before/without entity context), while `NRErr` optionally has one (errors can occur with or without entity context).
|
||||
|
||||
### 2. PNMessageData semicolon separator
|
||||
|
||||
`encodePNMessages` uses `;` as the separator between push notification message items instead of the standard `,` used by `NonEmpty` `strEncode`. This is because `SMPQueueNtf` contains an `SMPServer` whose host list encoding already uses commas, which would create ambiguous parsing.
|
||||
|
||||
### 3. NTInvalid reason is version-gated
|
||||
|
||||
When encoding `NRTkn` results, the `NTInvalid` reason is only included if the negotiated protocol version is >= `invalidReasonNTFVersion` (v3). Older clients receive `NTInvalid Nothing`. This prevents parse failures on clients that don't understand the reason field.
|
||||
|
||||
### 4. subscribeNtfStatuses migration invariant
|
||||
|
||||
The comment on `subscribeNtfStatuses` (`[NSNew, NSPending, NSActive, NSInactive]`) warns that changing these statuses requires a new database migration for queue ID hashes (see `m20250830_queue_ids_hash`). This is a cross-module invariant between protocol types and router storage.
|
||||
|
||||
### 5. allowNtfSubCommands permits NTInvalid and NTExpired
|
||||
|
||||
Token status `NTInvalid` allows subscription commands (SNEW, SCHK, SDEL), which is counterintuitive. The rationale (noted in a TODO comment) is that invalidation can happen after verification, and existing subscriptions should remain manageable. `NTExpired` is also permitted for the same reason.
|
||||
|
||||
### 6. PPApnsNull test provider
|
||||
|
||||
`PPApnsNull` is a push provider that never communicates with APNS. It's used for end-to-end testing of the notification router from clients without requiring actual push infrastructure.
|
||||
|
||||
### 7. DeviceToken hex validation
|
||||
|
||||
`DeviceToken` string parsing has two paths: a hardcoded literal match for `"apns_null test_ntf_token"` (test tokens), and hex string validation for real tokens (must be even-length hex). The wire encoding (`smpP`) does not perform this validation — it accepts any `ByteString`.
|
||||
|
||||
### 8. SMPQueueNtf parsing applies updateSMPServerHosts
|
||||
|
||||
Both `smpP` and `strP` for `SMPQueueNtf` apply `updateSMPServerHosts` to the parsed SMP server. This normalizes router host addresses on deserialization, ensuring consistent comparison even if the on-wire format uses different host representations.
|
||||
|
||||
### 9. NRTknId result tag comment
|
||||
|
||||
The `NRTknId_` tag encodes as `"IDTKN"` with a source comment: "it should be 'TID', 'SID'". This indicates a naming inconsistency that was preserved for backward compatibility — the tag names don't follow the pattern of other NTF protocol tags.
|
||||
|
||||
### 10. useServiceAuth is False
|
||||
|
||||
The `Protocol` instance explicitly returns `False` for `useServiceAuth`, meaning the NTF protocol never uses service-level authentication. All authentication is entity-level (per token/subscription).
|
||||
@@ -1,133 +0,0 @@
|
||||
# Simplex.Messaging.Notifications.Server
|
||||
|
||||
> NTF router: manages tokens, subscriptions, SMP subscriber connections, and push notification delivery.
|
||||
|
||||
**Source**: [`Notifications/Server.hs`](../../../../../src/Simplex/Messaging/Notifications/Server.hs)
|
||||
|
||||
## Architecture
|
||||
|
||||
The NTF router runs several concurrent threads via `raceAny_`:
|
||||
|
||||
| Thread | Purpose |
|
||||
|--------|---------|
|
||||
| `ntfSubscriber` | Receives SMP messages (NMSG, END, DELD) and agent events (connect/disconnect/subscribe) |
|
||||
| `ntfPush` | Reads push queue and delivers via APNS provider |
|
||||
| `periodicNtfsThread` | Sends periodic "check messages" push notifications (cron) |
|
||||
| `runServer` (per transport) | Accepts client connections and runs NTF protocol |
|
||||
| Stats/Prometheus/Control | Optional monitoring and admin threads |
|
||||
|
||||
Each client connection spawns `receive`, `send`, and `client` threads via `raceAny_`.
|
||||
|
||||
See [spec/routers.md](../../../routers.md) for component and sequence diagrams.
|
||||
|
||||
## Non-obvious behavior
|
||||
|
||||
### 1. Timing attack mitigation on entity lookup
|
||||
|
||||
When `verifyNtfTransmission` encounters an AUTH error (entity not found), it calls `dummyVerifyCmd` to equalize result timing before returning the error. This prevents attackers from distinguishing "entity doesn't exist" from "signature invalid" based on result latency.
|
||||
|
||||
### 2. TNEW idempotent re-registration
|
||||
|
||||
When TNEW is received for an already-registered token, the router:
|
||||
1. Looks up the existing token via `findNtfTokenRegistration` (matches on push provider, device token, AND verify key)
|
||||
2. Verifies the DH secret matches (recomputed from the new `dhPubKey` and stored `tknDhPrivKey`)
|
||||
3. If DH secrets differ → AUTH error (prevents token hijacking)
|
||||
4. If they match → re-sends verification push notification
|
||||
|
||||
If the verify key doesn't match in step 1, the lookup returns `Nothing` and a new token is created instead — the DH secret check never runs. This makes TNEW safe for client retransmission after connection drops.
|
||||
|
||||
### 3. SNEW idempotent subscription
|
||||
|
||||
When SNEW is received for an existing subscription (same token + SMP queue), the router returns the existing `ntfSubId` if the notifier key matches. If keys differ, AUTH error. New subscriptions are only created when no match exists in `findNtfSubscription`.
|
||||
|
||||
### 4. PPApnsNull suppresses statistics
|
||||
|
||||
`incNtfStatT` skips all stat increments when the device token uses `PPApnsNull` provider. This prevents test tokens from polluting production metrics.
|
||||
|
||||
### 5. END requires active session validation
|
||||
|
||||
SMP END messages are only processed when the originating session is the currently active session for that router (`activeClientSession'` check). This prevents stale END messages from previous (reconnected) sessions from incorrectly marking subscriptions as ended.
|
||||
|
||||
### 6. waitForSMPSubscriber two-phase wait
|
||||
|
||||
`waitForSMPSubscriber` first tries a non-blocking `tryReadTMVar`. If the subscriber isn't ready yet, it falls back to a blocking `readTMVar` with a 10-second timeout. This avoids creating an extra timeout thread in the common case where the subscriber is already available.
|
||||
|
||||
### 7. CAServiceUnavailable triggers individual resubscription
|
||||
|
||||
When a service subscription becomes unavailable (SMP router rejects service credentials), the NTF router:
|
||||
1. Removes the service association from the database
|
||||
2. Resubscribes all individual queues for that router via `subscribeSrvSubs`
|
||||
|
||||
This is the fallback path from service-level to queue-level SMP subscriptions.
|
||||
|
||||
### 8. Push delivery single retry
|
||||
|
||||
`deliverNotification` retries exactly once on connection errors (`PPConnection`) or `PPRetryLater`:
|
||||
1. Creates a new push client (`newPushClient`) to get a fresh connection
|
||||
2. Retries the delivery
|
||||
|
||||
On the second failure, the error is logged and returned. `PPTokenInvalid` marks the token as `NTInvalid` on either the first or retry attempt.
|
||||
|
||||
### 9. TCRN minimum interval enforcement
|
||||
|
||||
Cron notification interval has a hard minimum of 20 minutes. `TCRN 0` disables cron notifications. `TCRN n` where `1 <= n < 20` returns `QUOTA` error.
|
||||
|
||||
### 10. Startup resubscription is concurrent per router
|
||||
|
||||
`resubscribe` uses `mapConcurrently` to resubscribe to all known SMP routers in parallel. Within each router, subscriptions are paginated via `subscribeLoop` using cursor-based pagination (`afterSubId_`).
|
||||
|
||||
### 11. receive separates error results from commands
|
||||
|
||||
The `receive` function processes incoming transmissions and partitions results: malformed/unauthorized requests are written directly to `sndQ` as error results, while valid commands go to `rcvQ` for processing. This ensures protocol errors get immediate results without competing for the command processing queue.
|
||||
|
||||
### 12. Maintenance mode saves state then exits immediately
|
||||
|
||||
When `maintenance` is set in `startOptions`, the router restores stats, calls `stopServer` (closes DB, saves stats), and exits with `exitSuccess`. It never starts transport listeners, subscriber threads, or resubscription. This provides a way to run database migrations without the router serving traffic.
|
||||
|
||||
### 13. Resubscription runs as a detached fork
|
||||
|
||||
`resubscribe` is launched via `forkIO` before `raceAny_` starts — it is **not part of the `raceAny_` group**. Most exceptions are silently lost per `forkIO` semantics. However, `ExitCode` exceptions (like `exitFailure` from pattern 20) are special-cased by GHC's runtime and propagate to the main thread, terminating the process.
|
||||
|
||||
### 14. TNEW re-registration resets status for non-verifiable tokens
|
||||
|
||||
When a re-registration TNEW matches on DH secret but `allowTokenVerification tknStatus` is `False` (token is `NTNew`, `NTInvalid`, or `NTExpired`), the router resets status to `NTRegistered` before sending the verification push. This makes TNEW a "status repair" mechanism — clients with stuck tokens can restart the verification flow by re-registering with the same DH key.
|
||||
|
||||
### 15. DELD unconditionally updates status (no session validation)
|
||||
|
||||
Unlike `SMP.END` which checks `activeClientSession'` to prevent stale session messages from changing state, `SMP.DELD` updates subscription status to `NSDeleted` unconditionally. This is correct because DELD means the queue was permanently deleted on the SMP router — the information is valid regardless of which session reports it.
|
||||
|
||||
### 16. TRPL generates new code but reuses the DH key
|
||||
|
||||
`TRPL` (token replace) creates a new registration code and resets status to `NTRegistered`, but does NOT generate a new router DH key pair. The existing `tknDhPrivKey` and `tknDhSecret` are preserved — only the push provider token and registration code change. The encrypted channel between client and NTF router persists across device token replacements.
|
||||
|
||||
### 17. PNMessage delivery requires NTActive, verification and cron do not
|
||||
|
||||
`ntfPush` applies `checkActiveTkn` only to `PNMessage` notifications. Verification pushes (`PNVerification`) and cron check-messages pushes (`PNCheckMessages`) are delivered regardless of token status. This is necessary because verification pushes must be sent before NTActive, and cron pushes are already filtered at the database level.
|
||||
|
||||
### 18. CAServiceSubscribed validates count and hash with warning-only behavior
|
||||
|
||||
When a service subscription is confirmed, the NTF router compares expected and confirmed subscription count and IDs hash. Mismatches in either are logged as warnings but no corrective action is taken. Only when both match is an informational message logged.
|
||||
|
||||
### 19. subscribeLoop uses 100x database batch multiplier
|
||||
|
||||
`dbBatchSize = batchSize * 100` reads subscriptions from the database in chunks 100 times larger than the SMP subscription batches. This reduces database round-trips during resubscription while keeping individual SMP batches small enough to avoid overwhelming SMP routers.
|
||||
|
||||
### 20. subscribeLoop calls exitFailure on database error
|
||||
|
||||
If `getServerNtfSubscriptions` returns `Left _` during startup resubscription, the router terminates via `exitFailure`. Since `resubscribe` runs in a forked thread (pattern 13), this `exitFailure` terminates the entire process — a transient database error during startup resubscription kills the router.
|
||||
|
||||
### 21. Stats log aligns to wall-clock time of day
|
||||
|
||||
The stats logging thread calculates an `initialDelay` to synchronize the first flush to `logStatsStartTime`. If the target time already passed today, it adds 86400 seconds to schedule for the next day. Subsequent flushes occur at exact `logInterval` cadence from that aligned start point.
|
||||
|
||||
### 22. NMSG AUTH errors silently counted, not logged
|
||||
|
||||
When `addTokenLastNtf` returns `Left AUTH` (notification for a queue whose subscription/token association is invalid), the router increments `ntfReceivedAuth` but takes no corrective action. Other error types are silently ignored. This is expected — subscriptions may be deleted while messages are in-flight.
|
||||
|
||||
### 23. PNVerification delivery transitions token to NTConfirmed
|
||||
|
||||
When a verification push is successfully delivered to the push provider, `setTknStatusConfirmed` transitions the token to `NTConfirmed`, but only if not already `NTConfirmed` or `NTActive`. This creates a two-phase confirmation: push delivery confirms the channel works (`NTConfirmed`), then TVFY confirms the client received it (`NTActive`).
|
||||
|
||||
### 24. disconnectTransport always passes noSubscriptions = True
|
||||
|
||||
Unlike the SMP router which checks active subscriptions before disconnecting idle clients, the NTF router always returns `True` for the "no subscriptions" check. NTF clients are disconnected purely on inactivity timeout — the NTF protocol has no long-lived client subscriptions.
|
||||
@@ -1,7 +0,0 @@
|
||||
# Simplex.Messaging.Notifications.Server.Control
|
||||
|
||||
> Control port command protocol for NTF router administration.
|
||||
|
||||
**Source**: [`Notifications/Server/Control.hs`](../../../../../../src/Simplex/Messaging/Notifications/Server/Control.hs)
|
||||
|
||||
No non-obvious behavior. See source.
|
||||