# QUIC

> The SWQoS QUIC protocol, with connection setup, client-certificate keys, channels, reply frames and codes.

<Note>
Supanode issues keys through [Telegram](https://telegram.me/supanode_tgs). Default minimum tip: 0.001 SOL; default rate: 15 sends/s per key per metro. Your key settings can differ. Declared tips are off by default and require enablement and a payment arrangement with Supanode. If your key returns `partner_declared_tips`, use an on-chain transfer instead.
</Note>

QUIC carries the same transactions, bundles and payment rules as HTTP over long-lived connections. Each request is a stream, so a client opens a connection once and keeps it.

## Connect

| Setting | Value |
| --- | --- |
| Address | UDP port 443 of a [metro host](https://supanode.xyz/docs/solana/sender/endpoints) or `fra.tpu.supanode.xyz` |
| ALPN | `zerocopy-swqos/1` |
| TLS | 1.3 only |
| Server certificate | Publicly trusted, valid for the Supanode hostname you connect to. Verify it against the hostname you connect to. |
| Client certificate | Required. Any certificate whose first subject common name is your API key. A self-signed certificate works; the chain is not validated. |
| Idle timeout | 30 seconds. The server sends no keep-alives, so configure your client to send them. |
| Streams | At most 64 bidirectional and 64 unidirectional streams open at once per connection. |
| Handshake | Must complete within 3 seconds. |

A missing, unknown, revoked or paused key closes the connection with application code 8. If the key is revoked or paused after connection, a stream request receives `unauthorized` or `key_paused` before the connection closes.

Send the hostname you connect to as TLS SNI. An unknown or removed hostname closes
the connection with application code 4 and reason text `unknown host`. After a
server refresh removes a domain, existing connections and resumed TLS sessions
cannot keep using it.

| Close code | Reason text | Meaning |
| --- | --- | --- |
| 0 | `shutdown` | The server is shutting down. Reconnect. |
| 1 | `connection limit` | A connection limit was reached. Keep at most 32 open connections per key at one edge. |
| 4 | `unknown host` | The hostname is unknown or has been removed. Use a current endpoint. |
| 8 | `unauthorized` | No client certificate, or the key in it is missing, unknown or revoked. |
| 8 | `key_paused` | The key in the client certificate is paused. It works again once resumed. |

<span id="streams" />

## Channels

A QUIC connection carries three kinds of request, each on its own stream. Every request body is a [payload](https://supanode.xyz/docs/solana/sender/reference/payload-envelope): a bare transaction or an envelope.

| Channel | Request | Reply | Preflight |
| --- | --- | --- | --- |
| Unidirectional stream | One payload, up to 16,403 bytes, then the end of the stream. | None | No |
| Bidirectional stream, kind `0x01` | `[0x01][flags][payload]`, a transaction. | [Transaction frame](#reply-frames) | Flag `0x01` |
| Bidirectional stream, kind `0x03` | `[0x03][payload]`, a bundle envelope with flag `0x02`. | [Bundle frame](#reply-frames) | No |

The server reads each stream to its end, so finish your sending side after the request. The whole request must arrive within 2 seconds of the stream opening, or the server drops it without a reply.

A unidirectional stream gets no answer, and a refusal on it is dropped silently. A transaction sent that way counts against your send rate even when it is then refused. Use a bidirectional stream when you need the outcome.

On a kind `0x01` stream, the flags byte after the kind is `0x00`, or `0x01` to run a preflight simulation at `processed` commitment. No other bits may be set. After the kind byte, the stream may carry up to 16,404 bytes: one flags byte and a payload of up to 16,403 bytes. A bundle payload on this stream is refused as `malformed` with problem `expected_transaction`, and a single transaction on a kind `0x03` stream with problem `expected_bundle`.

Other kind bytes are reserved; do not open streams with them. A stream that starts with an unrecognized byte is refused as `malformed`, problem `invalid_stream_kind`, and ends without a reply.

## Reply frames

The server writes one frame and finishes the stream.

| Frame | Layout |
| --- | --- |
| Transaction | `[0x01][code: u8][detail length: u16 LE][detail]` |
| Bundle | `[0x03][code: u8][bundle id: 32 bytes][detail length: u16 LE][detail]` |

An accepted request has code 0 and an empty detail. An accepted bundle's frame carries its [bundle ID](https://supanode.xyz/docs/solana/sender/reference/json-rpc/send-bundle) as 32 raw bytes; a refused bundle's ID is all zeros. The detail of a refusal is the UTF-8 JSON rejection, the same object `/binary` returns: `reason`, its fields, `message`, `retryable` and optional `docs`. Hosted responses on Supanode domains omit `docs`. A failed simulation whose detail would exceed 65,535 bytes is shortened to `err` and the first 1,024 bytes of `error`.

```text title="Frames in hex"
Accepted transaction   01 00 00 00
Refused transaction    01 03 LL LL {"reason":"missing_tip",...}
Accepted bundle        03 00 ID...(32 bytes) 00 00
```

## Reply codes

A code groups reasons. Read `reason` in the detail for the exact cause.

| Code | Name | Reasons |
| --- | --- | --- |
| 0 | Accepted | none |
| 1 | RateLimited | [`rate_limited`](https://supanode.xyz/docs/solana/sender/reference/errors#rate_limited) |
| 2 | Unsigned | [`unsigned`](https://supanode.xyz/docs/solana/sender/reference/errors#unsigned) |
| 3 | MissingTip | [`missing_tip`](https://supanode.xyz/docs/solana/sender/reference/errors#missing_tip), [`credit_exhausted`](https://supanode.xyz/docs/solana/sender/reference/errors#credit_exhausted) |
| 4 | Malformed | [`malformed`](https://supanode.xyz/docs/solana/sender/reference/errors#malformed), [`invalid_request`](https://supanode.xyz/docs/solana/sender/reference/errors#invalid_request), [`unsupported`](https://supanode.xyz/docs/solana/sender/reference/errors#unsupported) for `tip_floor` or `partner_declared_tips` |
| 5 | TooLarge | [`too_large`](https://supanode.xyz/docs/solana/sender/reference/errors#too_large) |
| 6 | ForwardFailed | [`forward_failed`](https://supanode.xyz/docs/solana/sender/reference/errors#forward_failed) |
| 7 | SignatureCount | [`signature_count`](https://supanode.xyz/docs/solana/sender/reference/errors#signature_count) |
| 8 | Unauthorized | [`unauthorized`](https://supanode.xyz/docs/solana/sender/reference/errors#unauthorized), [`key_paused`](https://supanode.xyz/docs/solana/sender/reference/errors#key_paused) |
| 9 | Simulation | [`simulation_failed`](https://supanode.xyz/docs/solana/sender/reference/errors#simulation_failed) |
| 10 | BundleInvalid | [`bundle_size`](https://supanode.xyz/docs/solana/sender/reference/errors#bundle_size), [`bundle_control`](https://supanode.xyz/docs/solana/sender/reference/errors#bundle_control), [`unsupported`](https://supanode.xyz/docs/solana/sender/reference/errors#unsupported) for `bundles` or `declared_tips` |
| 11 | NotReady | [`not_ready`](https://supanode.xyz/docs/solana/sender/reference/errors#not_ready), [`overloaded`](https://supanode.xyz/docs/solana/sender/reference/errors#overloaded) |
| 12 | Internal | [`preflight_unavailable`](https://supanode.xyz/docs/solana/sender/reference/errors#preflight_unavailable), [`internal`](https://supanode.xyz/docs/solana/sender/reference/errors#internal) |
| 13 | PaymentRequired | [`payment_required`](https://supanode.xyz/docs/solana/sender/reference/errors#payment_required) |

## Example

These clients send one signed transaction on a kind `0x01` stream and print the reply. Each reads the key from `SWQOS_API_KEY` and the transaction's wire bytes from the file named on the command line. Rust uses `quinn`; Go uses `quic-go` in the [example project's module](https://supanode.xyz/docs/solana/sender/reference/json-rpc#example-project). TypeScript uses native `node:quic` and requires Node.js 26.6 or later built with QUIC support, with `--experimental-quic` enabled. It does not run in Bun or browsers.

<Tabs>

<Tab title="Rust">

```toml title="Cargo.toml" tab="Rust" tab-group="language"
[package]
name = "swqos-quic-example"
version = "0.1.0"
edition = "2024"

[dependencies]
quinn = { version = "0.11", default-features = false, features = ["runtime-tokio", "rustls-ring"] }
rcgen = "0.14"
rustls = { version = "0.23", default-features = false, features = ["std", "ring"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net"] }
webpki-roots = "1"
```

</Tab>

<Tab title="Rust">

```rust title="src/main.rs" tab="Rust" tab-group="language"
use std::{net::SocketAddr, sync::Arc, time::Duration};

use quinn::crypto::rustls::QuicClientConfig;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};

const HOST: &str = "fra.tpu.supanode.xyz";

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api_key = std::env::var("SWQOS_API_KEY")?;
    let path = std::env::args().nth(1).ok_or("usage: swqos-quic-example SIGNED_TX_FILE")?;
    let transaction = std::fs::read(path)?;

    // A self-signed client certificate whose subject common name is the API key.
    let mut params = rcgen::CertificateParams::new(Vec::<String>::new())?;
    let mut name = rcgen::DistinguishedName::new();
    name.push(rcgen::DnType::CommonName, api_key.as_str());
    params.distinguished_name = name;
    let key_pair = rcgen::KeyPair::generate()?;
    let certificate = params.self_signed(&key_pair)?;
    let chain = vec![CertificateDer::from(certificate.der().to_vec())];
    let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key_pair.serialize_der()));

    let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
    let provider = Arc::new(rustls::crypto::ring::default_provider());
    let mut tls = rustls::ClientConfig::builder_with_provider(provider)
        .with_protocol_versions(&[&rustls::version::TLS13])?
        .with_root_certificates(roots)
        .with_client_auth_cert(chain, key)?;
    tls.alpn_protocols = vec![b"zerocopy-swqos/1".to_vec()];

    // The server closes a connection after 30 seconds without traffic.
    let mut transport = quinn::TransportConfig::default();
    transport.keep_alive_interval(Some(Duration::from_secs(5)));
    let mut config = quinn::ClientConfig::new(Arc::new(QuicClientConfig::try_from(tls)?));
    config.transport_config(Arc::new(transport));

    let address = tokio::net::lookup_host((HOST, 443))
        .await?
        .find(SocketAddr::is_ipv4)
        .ok_or("no IPv4 address")?;
    let mut endpoint = quinn::Endpoint::client(SocketAddr::from(([0, 0, 0, 0], 0)))?;
    endpoint.set_default_client_config(config);
    let connection = endpoint.connect(address, HOST)?.await?;

    // Kind 0x01, flags 0x00 (no preflight), then the bare signed transaction.
    let (mut send, mut recv) = connection.open_bi().await?;
    send.write_all(&[0x01, 0x00]).await?;
    send.write_all(&transaction).await?;
    send.finish()?;
    let reply = recv.read_to_end(4 + usize::from(u16::MAX)).await?;

    let [0x01, code, low, high, detail @ ..] = reply.as_slice() else {
        return Err("unexpected reply frame".into());
    };
    let length = usize::from(u16::from_le_bytes([*low, *high]));
    if detail.len() != length || *code > 13 || (*code == 0 && length != 0) {
        return Err("invalid reply frame".into());
    }
    if *code == 0 {
        println!("accepted");
    } else {
        println!("refused with code {code}: {}", String::from_utf8_lossy(detail));
    }

    connection.close(0u32.into(), b"done");
    endpoint.wait_idle().await;
    Ok(())
}
```

</Tab>

<Tab title="Go">

```go title="quic/main.go" tab="Go" tab-group="language"
package main

import (
	"context"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"math/big"
	"net"
	"os"
	"time"

	"github.com/quic-go/quic-go"
)

const host = "fra.tpu.supanode.xyz"

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func run() error {
	apiKey := os.Getenv("SWQOS_API_KEY")
	if apiKey == "" {
		return errors.New("set SWQOS_API_KEY")
	}
	if len(os.Args) != 2 {
		return errors.New("usage: swqos-quic-example SIGNED_TX_FILE")
	}
	transaction, err := os.ReadFile(os.Args[1])
	if err != nil {
		return err
	}

	// A self-signed client certificate whose subject common name is the API key.
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return err
	}
	serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
	if err != nil {
		return err
	}
	template := &x509.Certificate{
		SerialNumber: serial,
		Subject:      pkix.Name{CommonName: apiKey},
		NotBefore:    time.Now().Add(-time.Minute),
		NotAfter:     time.Now().Add(24 * time.Hour),
		KeyUsage:     x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
	}
	der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
	if err != nil {
		return err
	}
	tlsConfig := &tls.Config{
		MinVersion:   tls.VersionTLS13,
		MaxVersion:   tls.VersionTLS13,
		ServerName:   host,
		NextProtos:   []string{"zerocopy-swqos/1"},
		Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}},
	}

	// The server closes a connection after 30 seconds without traffic.
	config := &quic.Config{KeepAlivePeriod: 5 * time.Second}
	ctx := context.Background()
	addresses, err := net.DefaultResolver.LookupIP(ctx, "ip4", host)
	if err != nil {
		return err
	}
	if len(addresses) == 0 {
		return errors.New("no IPv4 address")
	}
	address := net.JoinHostPort(addresses[0].String(), "443")
	connection, err := quic.DialAddr(ctx, address, tlsConfig, config)
	if err != nil {
		return err
	}
	defer connection.CloseWithError(0, "done")

	// Kind 0x01, flags 0x00 (no preflight), then the bare signed transaction.
	stream, err := connection.OpenStreamSync(ctx)
	if err != nil {
		return err
	}
	if _, err := stream.Write([]byte{0x01, 0x00}); err != nil {
		return err
	}
	if _, err := stream.Write(transaction); err != nil {
		return err
	}
	if err := stream.Close(); err != nil {
		return err
	}
	reply, err := io.ReadAll(io.LimitReader(stream, 4+65_535+1))
	if err != nil {
		return err
	}
	if len(reply) < 4 || len(reply) > 4+65_535 || reply[0] != 0x01 {
		return errors.New("unexpected reply frame")
	}
	length := int(binary.LittleEndian.Uint16(reply[2:4]))
	if len(reply) != 4+length || reply[1] > 13 || (reply[1] == 0 && length != 0) {
		return errors.New("invalid reply frame")
	}
	code := reply[1]
	detail := reply[4 : 4+length]
	if code == 0 {
		fmt.Println("accepted")
	} else {
		fmt.Printf("refused with code %d: %s\n", code, detail)
	}
	return nil
}
```

</Tab>

<Tab title="TypeScript">

```ts title="quic-send.ts" tab="TypeScript" tab-group="language"
import { createPrivateKey, X509Certificate } from 'node:crypto'
import { lookup } from 'node:dns/promises'
import { readFile } from 'node:fs/promises'
import { connect } from 'node:quic'
import { rootCertificates } from 'node:tls'

const host = 'fra.tpu.supanode.xyz'
const apiKey = process.env.SWQOS_API_KEY
if (!apiKey) throw new Error('set SWQOS_API_KEY')
const path = process.argv[2]
if (!path) throw new Error('usage: node --experimental-quic quic-send.ts SIGNED_TX_FILE')
const transaction = await readFile(path)
const certificatePem = await readFile('client-cert.pem')
const certificate = new X509Certificate(certificatePem)
const key = createPrivateKey(await readFile('client-key.pem'))
const commonName = certificate.toLegacyObject().subject.CN
if ((Array.isArray(commonName) ? commonName[0] : commonName) !== apiKey) {
  throw new Error('the first client certificate common name must equal SWQOS_API_KEY')
}
if (!certificate.checkPrivateKey(key)) throw new Error('client certificate and key do not match')

// Resolve IPv4 explicitly; SNI and certificate verification still use the hostname.
const { address } = await lookup(host, { family: 4 })
const options = {
  alpn: 'zerocopy-swqos/1',
  servername: host,
  verifyPeer: 'strict' as const,
  certs: certificatePem,
  ca: rootCertificates.map((certificate) => Buffer.from(certificate)),
  keys: key,
  handshakeTimeout: 3_000,
  keepAlive: 5_000,
}
const session = await connect(`${address}:443`, options)
const timer = setTimeout(() => session.destroy(new Error('no reply within 5 seconds')), 5_000)
try {
  await session.opened
  if (!session.peerCertificate?.checkHost(host)) {
    throw new Error('server certificate does not match the hosted hostname')
  }
  // Supplying a finite body sends FIN after the bytes, without closing the receive side.
  const stream = await session.createBidirectionalStream({
    body: Buffer.concat([Buffer.from([0x01, 0x00]), transaction]),
  })
  const chunks: Uint8Array[] = []
  let length = 0
  for await (const batch of stream) {
    for (const chunk of batch) {
      length += chunk.byteLength
      if (length > 4 + 65_535) throw new Error('reply exceeds the frame limit')
      chunks.push(chunk)
    }
  }
  const reply = Buffer.concat(chunks, length)
  if (reply.length < 4 || reply[0] !== 0x01) throw new Error('unexpected reply frame')
  const code = reply[1]
  const detailLength = reply.readUInt16LE(2)
  if (reply.length !== 4 + detailLength || code > 13 || (code === 0 && detailLength !== 0)) {
    throw new Error('invalid reply frame')
  }
  const detail = new TextDecoder('utf-8', { fatal: true }).decode(reply.subarray(4))
  console.log(code === 0 ? 'accepted' : `refused with code ${code}: ${detail}`)
} finally {
  clearTimeout(timer)
  session.destroy()
  await session.closed
}
```

</Tab>

</Tabs>

For TypeScript, create the client certificate once with OpenSSL. Keep both files private. Its first common name must match `SWQOS_API_KEY`; the program checks that before connecting. Node verifies the hosted certificate chain and hostname.

```sh title="Prepare and run the Node QUIC client"
umask 077
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \
  -keyout client-key.pem -out client-cert.pem -days 1 \
  -subj "/CN=${SWQOS_API_KEY:?set SWQOS_API_KEY}"
node --experimental-quic quic-send.ts signed-transaction.bin
```
