zqxnode developer guide (embedded fabric SDK)
zqxnode is a Rust library. It makes an application a node on the ZQX fabric:
- with no root or administrator rights;
- with no virtual adapter (no TUN or TAP driver);
- with no separate daemon.
Properties
Section titled “Properties”- User space only. It works in containers that run as non-root, with no
NET_ADMIN. It also works in serverless platforms and hardened Kubernetes pods, if they permit outgoing UDP. - Quantum-safe by default. Each connection uses pinned mutual TLS 1.3 with the hybrid
X25519MLKEM768key exchange (X25519 and ML-KEM-768). Node identities are persistent hybrid keys (Ed25519 and ML-DSA-65). Each connection proves both keys. - Tokio interfaces.
FabricStreamimplementstokio::io::AsyncReadandAsyncWrite. Thus it works with Axum, Hyper, Tower, Actix and Tonic (gRPC).
zqxnode runs in the same process as your application:
| Part | What it does |
|---|---|
| Your application (Axum, Hyper, Tonic or Tokio I/O) | Calls listen(port), dial(peer, port) and ping(peer) |
FabricListener and FabricStream |
Give your application streams to and from peers |
| The QUIC endpoint | Connects to peers directly, with pinned mTLS 1.3 and X25519MLKEM768 |
| Access rules | Come from the controller, over the node’s control session |
Add the library
Section titled “Add the library”zqxnode is available on request. It is not on crates.io. Ask ZQX for access, and then add it as a Git dependency, at the tag of the release that your nodes use:
[dependencies]zqxnode = { git = "https://github.com/zqxnet/zqx-platform", tag = "v<release>" }tokio = { version = "1", features = ["full"] }Start an embedded node
Section titled “Start an embedded node”use zqxnode::ServerBuilder;
#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> { let server = ServerBuilder::new() .hostname("payment-service") .auth_key("zqx_key_xxxx") .controller("fabric.zqxnet.com") .build() .await?;
println!("Node ID: {}", server.node_id()); if let Some(ip) = server.overlay_ip().await { println!("Fabric IP: {ip}"); } Ok(())}.controller() takes the address as you would give it to zqx up --server: fabric.zqxnet.com (the hosted service), a host name or an IP, with an optional port (443 by default) and ;tcp=<port>. With fabric.zqxnet.com, the node asks ZQX where its xnet’s controllers are (by a hash of its key), then connects to them. After that it uses the controllers that its xnet names, and needs no fixed address. A host name is resolved when the node starts. Without .controller(), or with an address that cannot be resolved (a warning in the log), the node runs standalone.
Listen on a fabric port
Section titled “Listen on a fabric port”server.listen(port) accepts connections from peers on a fabric port.
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let mut listener = server.listen(8080).await?;while let Ok((mut stream, peer)) = listener.accept().await { println!("Connection from {} ({})", peer.name, peer.node_id); tokio::spawn(async move { let mut buf = [0u8; 1024]; let _ = stream.read(&mut buf).await; let _ = stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK").await; });}Who can connect:
zqxnodechecks each incoming stream against the access rules of the xnet, as each other node does.- The caller must be a fabric peer, and a rule must permit it to reach this node on that port. If no rule permits it,
zqxnoderefuses the stream, and the caller gets an “access denied” error. - If a rule permits it but nothing listens on the port (no
listenorlisten_udp), the caller gets a “service offline” error.zqxdgives the same errors for the same causes. - The controller sends the rules about requests to this node, and keeps them current.
- A node with no controller refuses all streams until you set rules:
server.set_access_rules("allow src:ops dst:any port:8080"). When a controller sends rules, they replace these rules.
server.listen_udp(port) binds a UDP socket on a fabric port. server.dial_udp(target, port) opens a UDP flow to a peer.
let mut socket = server.listen_udp(53).await?;let mut buf = vec![0u8; 65_535];while let Ok((n, from)) = socket.recv_from(&mut buf).await { println!("{} bytes from {}", n, from.peer().name); socket.send_to(&buf[..n], &from).await?;}let flow = server.dial_udp("dns-1", 53).await?;flow.send(&query).await?;let n = flow.recv(&mut buf).await?;- Who can send: the access rules check each flow with
proto:udp(orproto:any) and the port, as for TCP. - Where datagrams come from: a node with a virtual adapter that sends UDP to this node’s fabric IP, or another node with
dial_udp. Adial_udpto a node withzqxdreaches that node’s UDP service. - Flows: each caller socket is one flow.
recv_fromsays which flow a datagram came on, andsend_toanswers on that flow. A flow ends when the caller closes it, or after 120 s with no datagram either way. - Datagrams are 0 to 65,535 bytes. A datagram longer than the buffer is cut to fit, as with UDP.
- TCP and UDP are separate:
listen(53)andlisten_udp(53)can both run. A UDP flow to a port with no UDP socket is refused. - To publish a UDP service, use
Service::udp(name, port).
Publish a service
Section titled “Publish a service”ServerBuilder::publish gives one of the node’s fabric ports a service name, with the service’s own labels.
use zqxnode::{ServerBuilder, Service};
let server = ServerBuilder::new() .hostname("payment-service") .auth_key("zqx_key_xxxx") .controller("fabric.zqxnet.com") .publish(Service::tcp("payments", 8080).labels(["app:tier=gold"])) .build() .await?;let mut listener = server.listen(8080).await?;- Peers see the service in their view. They connect to it by its name (
paymentsorpayments.internal), as to a service thatzqx sharepublishes. - Rules can name it:
target:payments, its targettarget:127.0.0.1, or its labelstarget:app:tier=gold. - The service’s labels cover only streams to the service: by its name, or to this node’s loopback on the service’s port. A stream to another port gets the node’s own labels.
- The node announces its services when it joins. Set them all on the builder.
buildrefuses a service with no name, a name or port twice, or a label outside your own namespaces (zqx:is reserved). publishnames the port;listen(orlisten_udpforService::udp) still takes its traffic.
Connect to a peer
Section titled “Connect to a peer”server.dial(target, port) connects to a peer by name, fabric IP or service name.
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let mut stream = server.dial("database-primary", 5432).await?;stream.write_all(b"PING").await?;let mut reply = [0u8; 4];stream.read_exact(&mut reply).await?;Refusals: a stream that the destination refuses returns its reason:
| Error | Code | Meaning |
|---|---|---|
ZqxNodeError::AccessDenied |
0x01 |
No access rule allows it |
ZqxNodeError::ServiceOffline |
0x05 |
Nothing listens on the port |
ZqxNodeError::DeviceExpired |
0x07 |
The caller’s node expiry passed (an xnet option, off by default). An Owner or Admin renews the node in the console. |
ZqxNodeError::ReauthRequired |
0x06 |
The stream needs the caller’s person, whose login on the caller expired. The person logs in again on the caller (zqx login). A zqxnode app has no person, so it never gets this as a caller. |
Node expiry: when the xnet uses it, server.device_expires_at() says when this node must be renewed by an Owner or Admin. After it, no node accepts its streams until it is renewed. As a destination, a zqxnode app refuses streams from an expired caller (0x07), as zqxd does.
Login expiry as a destination: a zqxnode app checks each new stream against the caller’s record as it is then. After the caller’s login expiry (5 minutes of clock skew allowed), it evaluates the stream without the caller’s person, as zqxd does, also with the controller offline. A stream that the caller’s labels allow still passes.
Paths: zqxnode connects through a relay first when the xnet has one, and moves to a direct path when one answers. It finds direct paths as a node with zqxd does:
- Public address: before each join, the node asks STUN, from its peer socket, for its public address. It asks the xnet’s STUN servers and the controller. Peers probe that address.
- LAN candidates: the node sends its LAN addresses to each peer, inside the end-to-end connection, and probes the peer’s LAN addresses first. Two nodes on one network go direct even when their router does not hairpin.
ZQX_LAN_CANDIDATES=offstops the sending. - Hole punching: before a direct dial, the node asks the controller to have the peer dial it at the same time, so that both NATs open. When a peer dials it, the node dials back. A dial waits 2.5 s for the peer.
Ping a peer
Section titled “Ping a peer”server.ping(target, timeout) pings a peer, the same as zqx ping. It returns the round-trip time. It returns an error when no reply comes: the peer is not known, cannot be reached, or does not answer in time.
use std::time::Duration;
match server.ping("db-1", Duration::from_secs(3)).await { Ok(rtt) => println!("db-1 answered in {rtt:?}"), Err(e) => eprintln!("db-1 did not answer: {e}"),}Pings to this node: an embedded node answers zqx ping. It also answers the OS ping from peers that have a virtual adapter, if the access rules permit ICMP from them (proto:icmp or proto:any).
Resolve names
Section titled “Resolve names”An embedded node resolves names as a node of the xnet does:
- a node or service of the xnet (
db-1,db-1.acme.zqxnode.com): its fabric IP; - a name in a split DNS route: through that route’s nameservers;
- with “use for all names”: through the xnet’s nameservers;
- any other name: through the host’s DNS.
let ips = server.resolve("db.corp.example.com").await?;let resolver = server.resolver(); // cheap to clonelet addrs = resolver.lookup_with_port("db.corp.example.com", 5432).await?;A nameserver on a node of the xnet is reached over a fabric stream (DNS over TCP to its port 53). The access rules on that node must allow it.
Paths, lanes and counters
Section titled “Paths, lanes and counters”server.peer_status() shows each peer as zqx peers -v does on a node:
connected: a live connection, whichever side opened it;path:direct,direct (LAN)orrelay via <relay>, with, not answeringwhen a direct path has gone quiet;probes: the path probe counters (pings sent and received, answers, refusals, relay probes);connections: each open connection to the peer with its statistics, aszqx peers --statsshows them (round trip, window, packets sent and lost, congestion events, packet size, bytes);- on demand, the rest of the directory, with
listedset.
server.status() adds the probes that came under an unknown key (probes_unknown_key, the last one’s address and age) and the number of lanes.
Lanes: with lanes, the node opens extra connections to a direct peer, so one peer’s streams use more than one core of the runtime. A new stream goes to the connection with the fewest streams. Lanes open when a second stream starts beside another. A peer with zqxd uses the node’s lanes for its own streams too. ServerBuilder::lanes(n) or ZQX_LANES sets the number. The default is half the CPUs, at most 4, on Linux, and none elsewhere. A relayed peer keeps one connection.
Connections: the node serves a peer’s streams on every connection to it, whichever side opened it. A peer that is already connected to the node opens its streams on that connection.
Reconnects and large xnets
Section titled “Reconnects and large xnets”An embedded node keeps its control session as a node with zqxd does:
- Resume: the node holds its view (its peers and rules). After a reconnect, the controller sends only what changed. With
state_dir, the view is saved there (view.json), so a restart of the app resumes it too. - Fabric IP: the node asks for its earlier fabric IP when it joins again. A controller that lost its state then gives the same address back, if it is free.
- On-demand views: in a large xnet, the controller can send a directory (names and fabric IPs) in place of every peer’s details. The node asks for a peer’s details when it first uses it, by name or for an incoming connection. After 10 minutes with no traffic to a peer, the node releases its details (
ZQX_PEER_RELEASE_SECS). Names in the directory resolve with no request.
HTTP client
Section titled “HTTP client”FabricHttpClient sends HTTP requests to fabric targets.
use zqxnode::FabricHttpClient;
let client = FabricHttpClient::new(server);let body = client.get("http://payment-service:8080/health").await?;ServerBuilder options
Section titled “ServerBuilder options”| Method | Default | Meaning |
|---|---|---|
hostname(name) |
zqx-app-<random> |
The node name on the fabric |
auth_key(key) |
None | The pre-auth key from the console |
controller(address) |
None (standalone) | The controller (host:port) |
controller_key(node ID) |
Pinned on first use | Pin the controller’s key |
bind_addr(address) |
0.0.0.0:0 |
The local UDP socket for QUIC |
stir_server(address) |
From the netmap | A preferred relay |
state_dir(path) |
None (memory only) | The directory that keeps the keys, the controller trust and the view across restarts |
publish(service) |
None | Publish a service on a fabric port (Publish a service) |
lanes(n) |
ZQX_LANES, else half the CPUs (at most 4) on Linux |
Extra connections to each direct peer; 1 turns them off |
ephemeral(true) |
false |
Keep the keys in memory only, and tell the controller that the node is short-lived. A node without state_dir does the same. |
relay_settings(settings) |
From the environment: ZQX_NODE_RELAY, ZQX_RELAY_MAX_ROUTES, ZQX_RELAY_MAX_MBIT, ZQX_RELAY_MAX_GB_DAY |
What the node does with the zqx:relay label: switched on or off, and its limits (refer to labels) |
Identity: a node does not name its own identity. Rules select it by its node ID (src:node:<node ID>) and its labels. A zqxnode app joins with a key, so it has no person: server.person().await is None. Give its key a label: a node with no label loses access after its xnet’s identify time (72 hours by default). server.identity_deadline() says when, and is None for a node with a label.
Labels: a node does not set its own labels. An admin sets them, on the pre-auth key or on the node in the console. The node gets them in its view, and its access rules use them.
Server methods
Section titled “Server methods”| Method | What it does |
|---|---|
node_id(), hostname(), person().await |
This node: its node ID, its name, and the person logged in on it (None for an app that joined with a key) |
identity_deadline() |
When this node loses access unless an admin gives it a label (Unix seconds); None when it has a label |
overlay_ip().await |
The fabric IP, when connected |
is_connected().await, status().await |
The connection state |
peers().await |
The known peers |
peer_status().await |
Each peer’s connection, path, probe counters (zqx peers -v) and connection statistics (zqx peers --stats) |
services() |
The services this node publishes |
listen(port).await |
Accept streams on a fabric port |
listen_udp(port).await |
Bind a UDP socket on a fabric port (recv_from, send_to) |
dial_udp(target, port).await |
Open a UDP flow to a peer (send, recv) |
dial(target, port).await |
Open a stream to a peer |
ping(target, timeout).await |
Ping a peer |
resolve(name).await |
Resolve a name as a node of the xnet does: fabric names to fabric IPs, other names as the xnet’s DNS settings say |
resolver() |
A cheap Resolver handle (lookup, lookup_with_port) for a connection pool or an HTTP client |
set_access_rules(rules).await |
Set the rules when there is no controller |
add_peer(peer).await |
Add a peer by hand (tests, or no controller) |
relay_status().await |
Whether the node relays for its xnet, its settings and what it carried (zqx relay status) |
set_relay_settings(settings) |
Change the relay settings while the node runs; switched off, its relay stops |
close().await |
Stop the listeners and close the connections |
leave().await |
Leave the xnet for good, as zqx reset: the controller removes the node, the node closes, and the files in state_dir go. Returns whether the controller had the node. |
For ZQX v0.25.1. Each page describes this release.