Skip to content

sss transforms

Source files: 34 · checked against Etemenanki 3723395
  • Etemenanki/protocols/src/sss/transform/mod.rs
  • Etemenanki/protocols/src/sss/transform/parse.rs
  • Etemenanki/protocols/src/sss/transform/base.rs
  • Etemenanki/protocols/src/sss/transform/stuff.rs
  • Etemenanki/protocols/src/sss/transform/zstd.rs
  • Etemenanki/protocols/src/sss/transform/record.rs
  • Etemenanki/protocols/src/sss/transform/http_chunk.rs
  • Etemenanki/protocols/src/sss/transform/pad.rs
  • Etemenanki/protocols/src/sss/transform/bytemap.rs
  • Etemenanki/protocols/src/sss/transform/block.rs
  • Etemenanki/protocols/src/sss/transform/blockmap.rs
  • Etemenanki/protocols/src/sss/transform/bwt.rs
  • Etemenanki/protocols/src/sss/transform/shape.rs
  • Etemenanki/protocols/src/sss/transform/seed.rs
  • Etemenanki/protocols/src/sss/transform/stream.rs
  • Etemenanki/protocols/src/sss/varint.rs
  • Etemenanki/protocols/tests/unit/sss/transform/chain.rs
  • Etemenanki/protocols/tests/unit/sss/transform/stream.rs
  • Etemenanki/protocols/tests/unit/sss/transform/parse.rs
  • Etemenanki/protocols/tests/unit/sss/transform/base.rs
  • Etemenanki/protocols/tests/unit/sss/transform/stuff.rs
  • Etemenanki/protocols/tests/unit/sss/transform/zstd.rs
  • Etemenanki/protocols/tests/unit/sss/transform/record.rs
  • Etemenanki/protocols/tests/unit/sss/transform/http_chunk.rs
  • Etemenanki/protocols/tests/unit/sss/transform/pad.rs
  • Etemenanki/protocols/tests/unit/sss/transform/bytemap.rs
  • Etemenanki/protocols/tests/unit/sss/transform/block.rs
  • Etemenanki/protocols/tests/unit/sss/transform/blockmap.rs
  • Etemenanki/protocols/tests/unit/sss/transform/bwt.rs
  • Etemenanki/protocols/tests/unit/sss/transform/shape.rs
  • Etemenanki/protocols/tests/unit/sss/transform/seed.rs
  • Etemenanki/protocols/tests/unit/sss/transform/vectors.py
  • Etemenanki/protocols/tests/unit/sss/transform/vectors.tsv
  • Etemenanki/protocols/tests/unit/sss/transform/known_answers.tsv

The transform layer sits between the sss framing and the transport. Each direction of a stream has its own chain, an ordered list of reversible byte-stream codecs, and both ends configure the same two chains as expressions of a small notation. protocols/src/sss/transform/ holds the chain machinery (mod.rs), the notation parser (parse.rs), one module per codec, the block maps (blockmap.rs), the seed derivation (seed.rs), and TransformStream (stream.rs), the AsyncRead + AsyncWrite adapter that every sss endpoint reads its framing from and writes it to.

The layer is sss’s own. No other protocol is configured with a chain, and it is not a generic transport. The rules below come from sections IV and X of the sss whitepaper, which the code follows.

The layer does It leaves to others
Parse and print transforms in the whitepaper’s notation, check the notation’s resource limits before anything is expanded, and refuse anything it cannot be sure both ends agree on. Reading the config keys that hold the expressions: the front ends (app/src/lower.rs, katana src/lower/inbound.rs).
Encode a direction call by call, passing each call down the chain as exactly one call with the same flag. Deciding when to flush: the runtime flushes when it has nothing more to write.
Decode transport bytes through the chain in reverse, checking every length before the bytes it covers. What a decode error means for the connection: the runtime, or the server’s gate before authentication.
State X_T(n), the most one flushed call of n bytes can emit, and from it the server’s pre-authentication budget. Enforcing the header time and choosing drain or fallback: protocols/src/sss/server.rs.
Derive each seed’s tables and round constants once per configuration, shared read-only by every stream.
Keep per-stream state constant apart from one record in flight, borrowing large working memory per call from the thread.
File Contents
mod.rs Flag, Transform, Padding, Chain, ChainEncoder, ChainDecoder, the per-stage Stage, the thread-local scratch; HEADER_MAX, MAX_CHAIN, MAX_PREFIX
parse.rs The grammar and its lowering; FromStr and Display for Transform, Display for BlockMap; ParseError; MAX_EXPRESSION_BYTES, MAX_NODES, MAX_NESTING, MAX_WORK, MAX_ROUNDS, MAX_BODIES
base.rs Radix, Alphabet, the baseN encoder and decoder
stuff.rs stuff
zstd.rs zstd, its thread-local contexts and compress_bound
record.rs record
http_chunk.rs http-chunk and digits
pad.rs pad
bytemap.rs ByteMap, Table and Codec: the six byte codecs; MAX_LAG
block.rs The block envelope
blockmap.rs BlockMap, Body, Shuffle, Mix2, Wordmix, Rounds, and the per-direction Stage that encodes or decodes one block
bwt.rs bwt: rotation sorting, the inverse and its canonical check
shape.rs shape: ranking and unranking of weight-12 words
seed.rs digest, positions, bytes, invert, round and Round; the word arithmetic mask, rol, ror, inverse
stream.rs TransformStream
pub enum Flag { None, Flush, End }
#[non_exhaustive]
pub enum Transform {
Identity,
Base(Alphabet),
Stuff { filler: u8, period: u32 },
Zstd { cap: u32 },
Record { kind: u8, version: u16 },
HttpChunk { header: Arc<[u8]>, cap: u32 },
Pad { cap: u32, padding_cap: u32, padding: Padding, fill: u8 },
Map(ByteMap),
Block { cap: u32, body: Body }, // Body = Arc<[BlockMap]>, in the order the maps apply
Bwt { cap: u32 },
Shape { cap: u32 },
}
pub enum Padding { Fixed(u32), Uniform }
pub struct Chain { transforms: Arc<[Transform]> } // in the order they encode, nearest the sss framing first
impl Chain {
pub fn identity() -> Self;
pub fn new(transforms: Vec<Transform>) -> Result<Self, ParseError>;
pub fn parse<I, S>(items: I) -> Result<Self, ParseError>; // expressions, run in the order listed
pub fn transforms(&self) -> &[Transform];
pub fn is_identity(&self) -> bool;
pub fn bound(&self, n: usize) -> Option<usize>; // X_C(n)
pub fn prefix_budget(&self) -> usize; // B_pre = X_C(276)
pub fn encoder(&self) -> ChainEncoder;
pub fn decoder(&self) -> ChainDecoder;
}

Transform is #[non_exhaustive], so a match outside the crate keeps a wildcard arm and a later constructor is not a breaking change. A Chain prints as its list, [zstd(c=4096), baseN(N=64)], in the order the transforms run.

An encoder is driven by calls: some input, possibly none, and a flag. None lets an encoder hold a partial group; Flush makes it emit everything it holds; End flushes and then emits the transform’s end-of-direction output (only http-chunk has one) and is the last call of the direction.

ChainEncoder::call(input, flag, out) runs input through every encoder in order. What an encoder emits for a call reaches the next as exactly one call with the same flag. A call therefore never splits further down the chain, and a flush never turns into an extra write that a later transform would frame on its own. A call after the one flagged End is an error (sss: a call after the end of the direction). A byte codec copies the call’s input to the output and maps it in place.

ChainDecoder holds the decoders nearest the transport first. feed(raw, out, limit) takes all of raw and appends sss bytes to out. Each Stage keeps an inbox for input its decoder did not take. Only zstd expands, so only it stops early: it starts no new record once out holds limit bytes, leaving the rest in its inbox as a backlog (has_backlog); the caller feeds empty input to drain it before giving more. One feed therefore appends at most limit plus one record. finish() is called when the transport ends cleanly: every inbox must be empty and every decoder on a boundary, or it is sss: stream ends with undecoded input or the decoder’s own truncation error.

Identity transforms build no stage at all, so a chain of identities is free; is_identity tells the stream to bypass its buffers.

Between stages, a multi-stage chain borrows a pair of thread-local Vec<u8> buffers for the duration of one call. They follow threads, not streams, and are released after a call that grew them beyond 256 KiB (KEEP_SCRATCH). A nested call, which does not happen in practice, gets buffers of its own.

Every transform satisfies whitepaper §IV:

  • Flushable: after a call flagged Flush or End, the encoder holds none of its input.
  • Bounded input: every length the decoder reads is checked against its cap before any byte it covers is read.
  • Bounded output: a record decodes to a bounded number of bytes.
  • Bounded state: per-stream state is constant apart from at most one record in flight.
  • Known expansion: Transform::bound(n) is X_T(n), the most the encoder emits for one flushed call of n bytes from a fresh state, non-decreasing in n.

For every record transform, splitting within a call is greedy: every piece but the last has the maximum length, so n > 0 bytes make exactly ceil(n / r) records, and an empty call makes none. block, bwt and shape split the same way, with c as the cap.

Transform X_T(n) Function
identity, the byte codecs n Transform::bound
baseN, N = 16 2n base::bound
baseN, N = 32 8 ceil(n/5) base::bound
baseN, N = 64 4 ceil(n/3) base::bound
stuff n + floor(n/k) stuff::bound
zstd n + floor(n/256) + 67 ceil(n/c) zstd::bound
record n + 5 ceil(n/16384) record::bound
http-chunk len(H) + n + (h_r + 4) ceil(n/r) http_chunk::bound
pad n + (6 + P) ceil(n/r) pad::bound
block n + vlen(c) ceil(n/c) block::bound
bwt n + (vlen(c) + vlen(c − 1)) ceil(n/c) bwt::bound
shape 5 ceil(n/4) + vlen(c) ceil(n/c) shape::bound

h_r is the number of hex digits of r (http_chunk::digits), and vlen(x) the length of x as a varint (varint::len): one byte below 128, two below 16384, three otherwise. pad’s bound uses the cap P the receiver checks, whatever the sender’s mode, so pad(P=128) and pad(P=128,mode="uniform") have the same bound. Chain::bound composes them, X_C(n) = X_Tk(… X_T1(n) …), with checked arithmetic; overflow is None.

Chain::prefix_budget is B_pre = X_C(276): since a client sends its request header (at most HEADER_MAX = 276 bytes) as one flushed call from a fresh state, a valid header always arrives within that many raw transport bytes. Chain::new refuses a chain of more than MAX_CHAIN = 32 transforms, and one whose X_C(276) exceeds MAX_PREFIX = 1 MiB or overflows (the chain expands a 276-byte header beyond 1048576 bytes), so the budget a server applies is never above 1 MiB. prefix_budgets pins these values:

up chain B_pre
feedback8(a=13,b=7,r=3)|affine8(a=197,b=101) 276: byte codecs preserve length
block(c=4096,body=shuffle(seed=17)|bitplane()) 278 = 276 + 2
bwt() 280 = 276 + 2 + 2
stuff(f=0x00,k=5) 331 = 276 + 55
shape() 347 = 5 · 69 + 2
record()|baseN() 373 = 4 · 92 + 5

Three pad(P=65536) exceed MAX_PREFIX; eight baseN(N=16) (276 · 2⁸ = 70,656 bytes) do not.

Passes bytes through. It builds no encoder or decoder stage.

Radix is Base16, Base32 or Base64, with groups of 1 byte to 2 symbols, 5 to 8, and 3 to 4. Alphabet::rfc(radix) is the RFC 4648 alphabet; Alphabet::permuted(radix, symbols) accepts any permutation of it (every symbol exactly once) and refuses anything else, by name: a base64 alphabet has 64 symbols, not 3, '6' appears twice in the alphabet, or a symbol that is not in the RFC alphabet. = is never a symbol.

The encoder holds at most one partial group (up to 4 bytes). It emits full groups as they fill and, on Flush or End, the partial group padded with = as RFC 4648 pads the end of its input. The decoder takes s symbols at a time and decodes each group independently, so a padded group may appear anywhere in the stream, after any flush. It refuses a symbol outside the alphabet, a data symbol after =, a number of data symbols that RFC 4648 never writes for a partial group, and nonzero unused bits: every group has exactly one encoding. At the end of the transport it must sit on a group boundary.

stuff(f, k) inserts the filler f after every k input bytes. Both sides carry only their position within the current k + 1-byte period, so a flush at any offset is exact and neither side buffers a byte. The decoder drops every (k+1)-th byte and refuses it unless it is f (sss stuff: wrong filler byte); a transport that ends where a filler is due is truncated.

A record is m | F: m the varint length of F, and F exactly one zstd frame of a piece of at most c bytes, with its content size declared. The encoder splits each call into pieces of at most c bytes and compresses each with CCtx::compress2 at level 3, the level the whitepaper’s measurements used. Frames share no history, so neither side keeps a window between calls. The notation’s dict parameter is refused when the chain is parsed (zstd: dict: dictionaries are not supported).

The compression and decompression contexts, and a frame scratch, are thread-local (CONTEXTS), created on a thread’s first use and borrowed per call: zstd memory follows worker threads, not connections. The scratch is released after a frame grew it beyond 16 KiB.

The decoder reads m with a varint Reader capped at compress_bound(c) (ZSTD_COMPRESSBOUND), so m = 0 (sss zstd: empty record) and m > B(c) are refused before a byte of F. A frame that arrives whole is decoded where it lies; otherwise up to m bytes are buffered. decode_frame then checks, before any output is allocated:

  1. the zstd magic number, which a skippable frame does not carry;
  2. that find_frame_compressed_size spans exactly the m bytes: one frame, nothing after it;
  3. a declared content size in [1, c];
  4. no dictionary ID.

Only then does it resize the output to exactly the declared size and decompress into it, refusing any other result size. A decompression bomb gets c bytes at most. With the feed limit, a run of small frames stops at the stream’s decoded limit and resumes later.

Each piece of at most 16,384 bytes (MAX_BODY) becomes type[1] | ver[2] | len[2] | body, len big-endian. The decoder collects the five-byte header, refuses another type or ver and a len outside [1, 2^14], then passes the body through as it arrives, holding only the header.

The encoder writes the header block H before its first chunk, each piece of at most r bytes as hex(len) CRLF body CRLF (lowercase, no leading zeros, no extensions), and on the End call the terminator 0 CRLF CRLF, with H first if nothing came before. The decoder matches H byte by byte, keeping only its offset, then runs a small state machine (Size, SizeLf, Body, BodyCrlf, Terminated). It refuses a size line with more than h_r digits, a leading zero other than the terminator’s 0, uppercase or other bytes, a size above r, a size line or body not ended by CRLF, and any byte after the terminator. A transport that ends before the terminator is a truncation, so an http-chunk direction ends only through End.

H is checked when the chain is parsed (http_header in parse.rs): at most 8192 bytes (MAX_HEADER), printable ASCII and tabs, lines ended by CRLF with no bare CR or LF, a first line that is an HTTP/1.1 request line (an upper-case method, a target, HTTP/1.1) or status line (HTTP/1.1 and three digits), header lines with a non-empty name before a :, and a blank line at the end.

Each piece of at most r bytes becomes a data length, a padding length, the data and that many fill bytes f, both lengths varints. With Padding::Fixed(p) the padding length is p; with Padding::Uniform the encoder draws it uniformly from 0 to P with rand::random_range for each piece. The decoder reads the data length with a varint capped at r and the padding length with one capped at P, refuses a data length of 0 (sss pad: empty data), passes the data through and skips the padding without storing it. The mode, p and f are the sender’s alone; the receiver checks only the two caps.

bytemap.rs holds the six codecs that map each byte to one byte, X_T(n) = n. ByteMap is their configuration:

pub enum ByteMap {
Affine8 { a: u8, b: u8, step: u8 },
Sbox8(Table),
Delta8 { lag: u16, init: u8 },
Feedback8 { a: u8, b: u8, r: u8 },
Adaptive8(Table),
Mtf8(Table),
}
pub struct Table { seed: u64, forward: Arc<[u8; 256]>, inverse: Arc<[u8; 256]> }

A Table is the permutation P_D(seed, 256) of its constructor’s domain and its inverse, built once when the configuration is parsed and shared by every stream. Codec is one direction of one codec with its state; ByteMap::encoder and decoder build one. Arithmetic is modulo 256, and the position i counts the direction’s bytes from zero, kept as i mod 256.

Codec Encode Decode State
affine8(a, b, step) y = a·x + b + step·i x = a⁻¹·(y − b − step·i) the position
sbox8(seed) y = P[x] x = P⁻¹[y] none
delta8(lag, init) y = x − x[i − lag] x = y + x[i − lag] the last lag original bytes, at first all init
feedback8(a, b, r) y = rol8(x + a·y[i−1] + b, r) x = ror8(y, r) − a·y[i−1] − b the previous output byte, at first 0
adaptive8(seed) y = P[x], then P’s entries at y and i mod 256 trade places x = P⁻¹[y], with the same update a mutable copy of P and P⁻¹, and the position
mtf8(seed) y is the rank of x in the list, which then moves x to the front x is the entry at rank y, with the same update the list, at first P

affine8 takes a⁻¹ from seed::inverse, so an even a is refused when the chain is parsed (affine8: a=4 is even, so it has no inverse). In a chain a codec keeps its state across calls and flushes, which the peer cannot see. Codec::reset returns it to its initial state; a block body calls it before every block. No byte value is ever refused: a codec with another configuration than the sender’s decodes to wrong bytes, not to an error.

block(c, body) is the envelope for block maps. Each piece of at most c bytes (1 to block::MAX_CAP = 65536) goes out as

varint(d) | Q_{d,j}(piece)

where Q is the body, its maps applied in order, and j the record index: 0 for the direction’s first record and one more for each record after it, counted per record, not per call. An empty call makes no record and does not advance j. j never wraps: a direction that would reach record 2^64 fails with sss block: record index 2^64.

The decoder reads d with a varint capped at c and refuses d = 0 (sss block: empty block) before the body. A block that arrives whole is decoded where it lands in the output; otherwise the body is buffered until it is complete, at most c bytes, and released once decoded if it grew past 16 KiB (KEEP_BODY). Only a complete block is decoded, by the maps’ inverses in reverse order, and released. The transport must end between blocks (sss block: stream ends inside a block).

blockmap.rs holds the maps a body is made of. Each is a bijection on blocks of every length d from 1 to the cap, and may depend on the record index j:

pub enum BlockMap {
Byte(ByteMap),
Reverse,
Rotate { k: u64 },
Shuffle(Shuffle),
Transpose { cols: u32 },
Bitplane,
Mix2(Mix2), // w, a, b, c, d
Wordmix(Wordmix), // w, a, b, r, k
Lift2(Rounds), // w, rounds, seed, and the derived round functions
Feistel(Rounds),
Cycle(Arc<[Body]>),
}

repeat has no variant: the parser writes its body out rounds times, so each copy of a byte codec is an occurrence of its own. identity() in a body adds no map. stages(body, decode) builds the per-direction Stages; decoding applies the inverses in reverse order (blockmap::decode).

Map On a block x of d bytes Inverse
a byte codec the codec from its initial state (Codec::reset before each block) its decoder, also reset
reverse y[i] = x[d−1−i] itself
rotate(k) rotate left by k mod d rotate right
shuffle(seed) y[i] = x[P[i]], P = P_shuffle(seed, d) for the block’s own length x[P[i]] = y[i]
transpose(cols) rows of cols bytes, the last one short, read column by column the same cell order, written back
bitplane the d×8 bit matrix read plane by plane, most significant first, packed most significant bit first the transpose back
mix2(w, a, b, c, d) each pair of whole little-endian w-bit words times [[a, b], [c, d]] mod 2^w times Δ⁻¹·[[d, −b], [−c, a]], Δ = ad − bc odd
wordmix(w, a, b, r, k) each whole word u to rol_w(a·u + b, r) xor k a⁻¹·(ror_w(v xor k, r) − b)
lift2(w, rounds, seed) per pair, each round: L += F_t(R), then R += G_t(L) the rounds backwards, subtracting
feistel(w, rounds, seed) per pair, each round: (L, R) = (R, L xor F_t(R)) (L, R) = (R xor F_t(L), L), backwards
cycle(bodies) body j mod m of the m listed that body’s inverse

Word maps act on whole words or whole pairs of words; a shorter tail is left as it is. Words are little-endian, unlike the big-endian fields of the request header. lift2 takes F_t = F(lift2, seed, w, 2t) and G_t = F(lift2, seed, w, 2t+1), feistel takes F_t = F(feistel, seed, w, t) (Seeds); Rounds derives them once with the configuration. bitplane turns eight bytes at a time with three rounds of delta swaps (transpose8) and handles a tail shorter than eight bytes bit by bit. shuffle, transpose and bitplane borrow a thread-local scratch per block.

P_shuffle(seed, d) costs d − 1 SHA-256 digests, so Shuffle builds the permutation of a full block when the configuration is parsed and keeps those of the eight most recent other lengths (RECENT) behind a parking_lot::Mutex, shared by every stream of the configuration.

The parser counts each body’s work before anything is expanded: one unit for each map, rounds for lift2 and feistel, rounds times the body for repeat, the dearest body for cycle, and the sum along a composition. A body above MAX_WORK = 256 units is refused (a block body does more than 256 units of work).

bwt(c) sends each piece of at most c bytes (1 to 65536) as

varint(d) | varint(p) | L[d]

The piece’s d cyclic rotations are sorted by (rotation, start): byte-wise, then equal rotations by where they start. L is the last byte of each sorted rotation and p the row of the rotation that starts at 0, the piece itself. sort_rotations sorts by prefix doubling with counting sorts over thread-local u32 arrays (Scratch), without building the rotations. The encoder holds nothing between calls.

The decoder reads d capped at c and refuses d = 0 (sss bwt: empty record), then reads p capped at d − 1, both before L. It buffers L until it is complete and inverts it with the LF mapping (invert): C(b), the number of bytes of L below b, plus the occurrence count, walked back from row p. It then encodes what it recovered again and requires the same (p, L); otherwise the record is refused (sss bwt: not the canonical codeword of what it decodes to) and nothing of it is released. The transport must end between records (sss bwt: stream ends inside a record).

shape(c) takes c from 4 to 65536, a multiple of four (shape: c=6 is not a multiple of 4); in, out and ones may be written, but only as 4, 5 and 12. Each piece of at most c bytes goes out as

varint(d) | body[5 · ceil(d/4)]

Every four bytes, read as a big-endian number r < 2^32, become the 40-bit word of rank r among those with exactly twelve one-bits, ordered by value, sent as five big-endian bytes. A final group of one to three bytes is filled with zeros. C(40, 12) = 5,586,853,480 is above 2^32, so every r has a word. rank sums C(p_j, j) over the set bits p_1 < … < p_12, and unrank inverts it with a descending scan; both use a table of binomials built once (BINOMIAL).

The decoder reads d capped at c and refuses d = 0 (sss shape: empty record), then buffers the 5 · ceil(d/4) body bytes. unshape refuses a group whose weight is not twelve, a rank of 2^32 or more, and filler bytes that are not zero (sss shape: a group's weight is not twelve, sss shape: rank of 2^32 or more, sss shape: nonzero filler), and on a refusal truncates the output back, so nothing of the record is released. The transport must end between records.

seed.rs turns a seed, an unsigned 64-bit integer, into tables and round constants. Everything comes from one digest, separated by the constructor’s name D:

H_D(s, n, t) = SHA-256("sss-v2/" ‖ D ‖ 0x00 ‖ LE64(s) ‖ LE32(n) ‖ LE32(t))
  • Permutations. positions builds P_D(s, m): it starts from the identity and, for i from m − 1 down to 1, swaps P[i] and P[q], where q is the first eight bytes of H_D(s, m, i) read little-endian, modulo i + 1. bytes is P_D(s, 256) for sbox8, adaptive8 and mtf8; shuffle uses the block’s length.
  • Round functions. round splits H_D(s, w, t) into four little-endian 64-bit words q0…q3 and takes a = (q0 mod 2^w) | 1, b = q1 mod 2^w, r = q2 mod w and k = q3 mod 2^w, for F(u) = rol_w(a·u + b, r) xor k (Round::apply).
  • Inverses. inverse gives the inverse of an odd a modulo 2^64, and therefore modulo every 2^w, by five Newton steps.

Seeds name deterministic maps, not keys: the same seed gives the same table on every host.

parse.rs implements the whitepaper’s grammar (§X):

expr := term ("|" term)*
term := name "(" args? ")" | "(" expr ")"
args := name "=" value ("," name "=" value)*
value := uint | string | expr | "[" expr ("," expr)* "]"
name := ASCII letter (ASCII letter | digit | "_" | "-")*
uint := "0" | nonzero-digit digit* | "0x" hex-digit+
string := JSON double-quoted string

Chain::parse takes one direction’s configured items, each an expression, and chain runs them in the order listed. Within an expression A|B runs B first, so lower appends an expression’s terms right to left: "baseN()|stuff()|zstd()" lowers to [zstd, stuff, baseN], and ["zstd()", "baseN()|stuff()"] to the same list as "(baseN()|stuff())|zstd()". A group is the same as its terms. An empty list is the identity.

The Lexer skips spaces, tabs, CR and LF between tokens. Names are case-sensitive and every constructor takes its parentheses. A decimal integer has no leading zero (zstd: c: "007" has a leading zero), hexadecimal needs a lower-case 0x, and either must fit 64 bits. A string is JSON: the escapes \" \\ \/ \b \f \n \r \t and \uXXXX, a surrogate pair as two \u escapes, no isolated surrogate and no raw control character. A value that is neither a number, a string nor a list is read as an expression.

Args hands parameters out as each constructor reads them, and done refuses any left over, so an unknown key, a repeated key, a missing required key, a value of the wrong kind and a value out of range are all errors that name the transform and the key: stuff: k=0 is outside [1, 65536], http-chunk: H is required, zstd: c is given twice. A block map outside a body, a block combinator outside a body and a stream codec inside one are each refused with a reason (reverse is a block map: it goes in a block body, block(body=reverse(...)), zstd is not a block map: a block body takes length-preserving maps). Nothing is guessed, and nothing unknown becomes the identity, since both ends must agree on every parameter. An error inside an item is prefixed with that item, quoted: "zstd(c=100)": zstd: c=100 is outside [1024, 65536].

Constructor Parameters (default) Range
identity
baseN N (64), A (the RFC 4648 alphabet) N 16, 32 or 64; A a permutation of that alphabet
stuff f (0), k (5) f 0 to 255, k 1 to 65536
zstd c (16384) MIN_CAP 1024 to MAX_CAP 65536; dict refused
record type (0x17), ver (0x0303) One and two bytes
http-chunk H (required), r (16384) H at most 8192 bytes, checked as above; r 1 to 65536
pad r (16384), P (0), mode ("fixed"), p (0), f (0) r 1 to 65536, P 0 to 65536, p 0 to P; mode "fixed" or "uniform", which takes p = 0; f 0 to 255
affine8 a (197), b (101), step (0) Bytes; a odd
sbox8, adaptive8, mtf8 seed (0) 0 to 2^64 − 1
delta8 lag (1), init (0) lag 1 to MAX_LAG 4096, init a byte
feedback8 a (13), b (7), r (3) a, b bytes, r 0 to 7
block c (4096), body (identity()) c 1 to 65536; body an expression of block maps
bwt c (4096) 1 to 65536
shape c (4096), in (4), out (5), ones (12) c 4 to 65536 and a multiple of 4; the others fixed
reverse, bitplane Body only
rotate k (1) 0 to 2^64 − 1; body only
shuffle seed (0) Body only
transpose cols (16) 1 to 65536; body only
mix2 w (8), a (1), b (1), c (1), d (2) w 8, 16, 32 or 64; the rest 0 to 2^w − 1 with ad − bc odd; body only
wordmix w (32), a (197), b (17), r (3), k (37) a, b, k 0 to 2^w − 1 with a odd, r 0 to w − 1; body only
lift2 w (32), rounds (4), seed (0) rounds 1 to MAX_ROUNDS 64; body only
feistel w (32), rounds (6), seed (0) As lift2
repeat rounds (1), body (identity()) rounds 1 to 64; body only
cycle bodies (required) A list of 1 to MAX_BODIES 16 bodies; body only

The limits of whitepaper §IV bound one direction’s whole configuration. They are counted while the items are read, and a body’s work before repeat writes its copies out:

Limit Value Error
Bytes of all the items MAX_EXPRESSION_BYTES = 8192 the expressions are <n> bytes, more than 8192
Syntax nodes: each item, constructor, group, parameter and list entry MAX_NODES = 256 more than 256 syntax nodes
Nesting: the item, then each group, expression value and list entry one level deeper MAX_NESTING = 16 expressions nest more than 16 deep
Transforms after lowering MAX_CHAIN = 32 the expressions compile to more than 32 transforms
Work in one block body MAX_WORK = 256 a block body does more than 256 units of work

Display prints the canonical form with every parameter written, which parses back to the same transform: stuff(f=0,k=5), record(type=0x17,ver=0x0303), pad(r=16384,P=0,mode="fixed",p=0,f=0), baseN(N=64) (with A only when it is not the RFC alphabet), and a block’s body as one expression, the last map first, repeat written out and an empty body as identity(). Strings are printed as JSON. FromStr for Transform accepts an expression of exactly one transform ("baseN()|zstd()" is an expression of several transforms, not one).

pub struct TransformStream<S> { /* inner, encoder, input, output, decoder, decoded, raw, pre_auth, … */ }
impl<S> TransformStream<S> {
pub fn new(inner: S, encoder: ChainEncoder, decoder: ChainDecoder) -> Self;
pub fn with_flush_delay(self, delay: Duration) -> Self; // t_c, capped at MAX_FLUSH_DELAY
pub fn with_budget(self, budget: usize) -> Self; // B_pre, server only
pub fn recording(self) -> Self; // keep raw bytes for a fallback
pub fn authenticated(&mut self);
pub fn take_record(&mut self) -> Vec<u8>;
pub fn pre_auth_read(&self) -> usize;
pub fn into_inner(self) -> S;
pub async fn peek_header<T>(&mut self, parse: impl FnMut(&[u8]) -> io::Result<Option<T>>)
-> io::Result<T>;
}
impl<S: AsyncRead + Unpin> AsyncRead for TransformStream<S> { … }
impl<S: AsyncWrite + Unpin> AsyncWrite for TransformStream<S> { … }

The protocol cores work in place in their runtime’s buffers and cannot hold what zstd or baseN(N=16) expand to, so the chains run in this adapter around the transport rather than inside a core. The server’s runtime and the client’s runtime both drive their sss codec over a TransformStream.

flowchart LR
  W["poll_write"] --> IN["input: the gathered call"]
  IN -->|"poll_flush: Flag::Flush; 16 KiB: Flag::None; shutdown: Flag::End"| ENC["ChainEncoder::call"]
  ENC --> OUT["output"] --> TW["transport write"]
  TR["transport read, 16 KiB"] --> DEC["ChainDecoder::feed, limit 16 KiB"]
  DEC --> DD["decoded"] --> R["poll_read"]

poll_write does not encode. It appends to the pending call (input) and returns. poll_flush encodes that call with Flag::Flush, writes the output and flushes the transport. Both runtimes flush the moment they have nothing more to write, so the call that carries the last input available is the flushed one, as whitepaper §II-D asks, and a run of small writes becomes one call that a record transform frames once.

  • A call that reaches CALL_SIZE (16 KiB) is encoded with Flag::None and the next call begins; the stream starts writing it at once without waiting.
  • When 64 KiB of encoded output wait for the transport, poll_write drains them before taking more, so backpressure reaches the writer.
  • With an identity encoder and no pending call, writes go straight to the transport.
  • with_flush_delay(t_c) holds each flush after the first for up to t_c with a tokio::time::Sleep, so input that arrives meanwhile joins the call. The first flush, the one that carries a client’s request header, is never held. Values above MAX_FLUSH_DELAY (10 ms) are capped.
  • poll_shutdown encodes the final call with Flag::End, writes it, flushes and shuts the transport’s write side down. A write after that is BrokenPipe (sss: write after the direction ended).

poll_fill reads up to 16 KiB from the transport and feeds it to the decoder chain with DECODED_LIMIT (16 KiB): decoding stops once that much decoded input waits for the reader, so a run of small zstd frames never decompresses past one buffer. A pending backlog is decoded before the transport is read again. With an identity decoder, no budget and nothing buffered, reads go straight to the transport.

A clean end of the transport is checked with ChainDecoder::finish. A decoder that holds part of a record or group, or an http-chunk direction that has not seen its terminator, makes it a truncation error rather than an end of file. A decode or truncation error sets failed, and every later read fails too (sss: the stream already failed to decode).

Buffers that grew beyond 64 KiB are released once drained.

A server builds its stream with_budget(B_pre) and reads the header with peek_header:

  • While the budget is set, each transport read is limited to what is left of it, so the stream never reads a byte past B_pre. When nothing is left and the header is still incomplete, the read fails (sss: no complete header within the pre-authentication budget).
  • With recording(), the raw transport bytes read under the budget are kept, before decoding, for take_record.
  • peek_header decodes until parse finds a complete header at the front of the decoded bytes, and leaves them unread, so the core reads the header again. The transport’s end before the header is UnexpectedEof; a decode error or the budget running out is an error.
  • authenticated() lifts the budget and drops the record.
  • The writes gathered until a flush form one call through the whole chain, with one flag.
  • After a flushed call, no encoder holds input.
  • Every decoder checks each length against its cap before reading the bytes it covers.
  • block, bwt and shape release nothing of a record they refuse.
  • A single ChainDecoder::feed appends at most limit plus one record.
  • A server reads at most B_pre transport bytes before authentication, and B_pre is at most 1 MiB.
  • The first flush of a stream is never delayed.
  • Per-stream state is constant apart from one record in flight; zstd contexts and stage scratch belong to the thread, and seed tables to the configuration.
  • A stream ends cleanly only on a record and group boundary, and an http-chunk direction only through its terminator.
  • A configuration within the notation’s limits never expands past them: work and transform counts are checked before repeat is written out.
Situation Result
A decoder refuses its input ProtocolError::Malformed, as InvalidData from poll_read; every later read fails
The transport ends inside a group or record ProtocolError::Truncated from poll_read
A write after shutdown, or a call after End An error; nothing is encoded
zstd compression or decompression fails An error for this call or this read
A block direction reaches record 2^64 ProtocolError::Overflow
The budget runs out before the header The peek fails; the gate classifies it as Budget
The stream is dropped Pending input and output are dropped with it; borrowed scratch was returned at the end of the call

A byte codec or block map with another configuration than the peer’s raises none of these: it decodes to wrong bytes. On up the gate then sees an unknown UUID or a malformed header; on down the client receives wrong payload.

Limit Value Constant
Transforms per chain 32 MAX_CHAIN
Bytes of one direction’s expressions 8192 MAX_EXPRESSION_BYTES
Syntax nodes 256 MAX_NODES
Nesting 16 levels MAX_NESTING
Work in one block body 256 units MAX_WORK
Rounds of repeat, lift2, feistel 64 MAX_ROUNDS
Bodies of cycle 16 MAX_BODIES
Pre-authentication budget at most 1 MiB MAX_PREFIX
One call before an unflagged encode 16 KiB CALL_SIZE
Decoded bytes waiting for the reader 16 KiB, plus one record DECODED_LIMIT
Transport read 16 KiB READ_SIZE
Encoded output before a write waits 64 KiB OUTPUT_HIGH
Flush delay 10 ms MAX_FLUSH_DELAY
zstd decoded cap c 1024 to 65536 zstd::MIN_CAP, MAX_CAP
record body 16,384 record::MAX_BODY
http-chunk header block, chunk cap 8192, 65536 http_chunk::MAX_HEADER, MAX_CAP
pad data cap, padding cap 65536 each pad::MAX_CAP
stuff period k 1 to 65536 parse.rs
delta8 lag 4096 bytemap::MAX_LAG
block, bwt, shape cap c 65536 each block::MAX_CAP, bwt::MAX_CAP, shape::MAX_CAP
Body buffer kept after a record 16 KiB KEEP_BODY in block.rs, bwt.rs, shape.rs
Short-block permutations one shuffle keeps 8 blockmap::RECENT
Varint 3 bytes, below 2^21 varint::MAX_LEN, LIMIT
Test file Pins
chain.rs the_reference_models_vectors: 4758 byte-exact vectors in vectors.tsv, generated by vectors.py from the specification’s reference models; the_whitepapers_known_answers: the 23 known answers in known_answers.tsv; prefix_budgets; identity_chains; chains_are_capped; a_call_after_the_end_is_refused; chains_run_lists_in_order_and_expressions_right_to_left; random_chains_calls_and_fragments_round_trip (random chains, call splits, flags and transport fragmentation); one_flushed_call_stays_within_the_chain_bound; a_header_arrives_within_the_prefix_budget; truncation_anywhere_inside_a_record_is_an_error
stream.rs writes_gather_into_one_call_until_the_flush, a_full_call_goes_out_without_waiting_for_the_flush, the_end_reaches_the_reader_only_through_the_terminator, a_decode_error_fails_this_read_and_every_later_one, the_header_is_peeked_within_the_budget_and_stays_unread, no_header_within_the_budget_stops_reading_at_the_budget, a_flush_delay_coalesces_later_writes_but_not_the_first, the_flush_delay_is_capped_at_ten_milliseconds
parse.rs defaults_follow_the_registry, composition_runs_right_to_left_and_lists_in_order, integers_strings_and_lists, pad_modes, http_headers_are_checked, mistakes_are_refused_with_a_reason, resource_limits, one_transform_from_a_string
zstd.rs pieces_are_independent_frames, length_zero_and_beyond_the_bound_are_refused_before_the_frame, content_size_must_be_declared_and_within_the_cap, two_frames_or_trailing_bytes_in_one_record_are_refused, a_skippable_frame_is_refused, a_frame_naming_a_dictionary_is_refused, output_stops_at_the_limit_and_resumes, bound_covers_incompressible_input
bytemap.rs state_persists_across_calls_however_they_split, reset_returns_to_the_initial_state, every_odd_affine_multiplier_inverts, formulas
block.rs the_whitepapers_size_counts, the_record_index_counts_records_not_calls, a_flushed_prefix_decodes_without_waiting, lengths_are_checked_before_the_body, nothing_of_a_partial_block_is_released, the_record_index_never_wraps
blockmap.rs every_map_inverts_at_every_length_and_keeps_it, bitplane_matches_its_formula, transpose_rotate_and_reverse, word_maps_leave_a_short_tail, cycle_picks_by_record_index, byte_codecs_restart_at_every_block, short_shuffles_are_kept_and_agree
bwt.rs every_three_symbol_input_up_to_seven, periodic_and_long_inputs, a_codeword_that_is_not_canonical_is_refused, malformed_records_are_refused, bounds
shape.rs enough_words_of_weight_twelve, ranks_are_the_formulas_and_follow_value_order, the_whitepapers_size_counts, every_tail_length_round_trips, malformed_records_are_refused_before_release
seed.rs the_digest_layout, permutations_by_domain_and_length, the_permutation_follows_its_rule, round_constants_and_rotations
base.rs, stuff.rs, record.rs, http_chunk.rs, pad.rs Each codec’s format, its decoder’s refusals, and its bound