//! The distribution wire format's kernel ([ADR 0072], [`docs/wire-format.md`]): //! type descriptors and the type definitions table, their canonical form //! and structural hash, and the value encoding's primitives (varints, //! heads, the message frame's header, node names). //! //! Shared by the compiler, which emits descriptors and the table, and the //! runtime, whose codec walks a value and its descriptor together. The //! format document is normative; this module implements it, and its tests //! pin the golden values the document quotes. //! //! Nothing here is reachable from a program that does not start //! distribution: the runtime calls it only from the codec, which only the //! transport's hooks reach (`--gc-sections` drops the rest). //! //! [ADR 0072]: ../../../docs/adr/0072-distribution.md //! [`docs/wire-format.md`]: ../../../docs/wire-format.md use std::collections::{BTreeMap, BTreeSet}; use std::fmt; use num_bigint::{BigInt, BigUint, Sign}; use crate::SMALL_INT; // ---- limits ---------------------------------------------------------------------- /// The longest descriptor or table text accepted, in bytes. pub const MAX_DESC_LEN: usize = 1 << 16; pub const MAX_TABLE_LEN: usize = 1 << 24; /// The deepest nesting of a descriptor (`Subject`, `Array`, tuples, type /// arguments): parsing recurses on the native stack. pub const MAX_DESC_DEPTH: usize = 128; /// The longest name (a qualified type name, a constructor name, a field /// label), in bytes once unescaped. pub const MAX_NAME_LEN: usize = 512; /// A type's parameters, and a tuple's components. pub const MAX_PARAMS: u32 = 255; pub const MAX_TUPLE: u32 = 254; /// A type's constructors: indices below `0xFF00` (runtime kinds start /// there, `docs/runtime-abi.md`). pub const MAX_CTORS: u32 = 0xFF00; /// A constructor's fields: a block holds at most 254 (`0xFF` is /// `TL_SCAN_LARGE`; codegen refuses wider constructors). pub const MAX_FIELDS: u32 = 254; /// The table's definitions. pub const MAX_DEFS: usize = 1 << 16; /// The largest payload of a frame, in bytes. pub const MAX_PAYLOAD: u32 = 64 << 20; /// The deepest nesting of a value, counting only nodes whose current /// child is not their last (a list of any length is depth 1). pub const MAX_VALUE_DEPTH: u32 = 1 << 16; /// Pid serials are below 2^46 on the wire (a remote pid's payload, ADR /// 0072); subject tags are non-negative small `Int`s. pub const MAX_PID_SERIAL: u64 = 1 << 46; pub const MAX_TAG: u64 = 1 << 62; /// A node name is a DNS name. pub const MAX_NODE_NAME: usize = 253; /// The transport's bounds, shared with `[cluster]`'s checks /// (`louise_package`) so the two cannot drift. The smallest frame limit a /// node may announce: every handshake frame fits under it, and so does the /// smallest `max_message_bytes`. pub const MIN_FRAME: u32 = 1 << 10; /// The largest useful frame (its length prefix counts the kind byte): a /// message frame of the largest payload. pub const MAX_FRAME: u32 = 1 + HEADER_LEN as u32 + MAX_PAYLOAD; /// The longest delay a configuration may give (a day): deadlines stay far /// from `Instant`'s range. pub const MAX_DELAY_MS: u64 = 86_400_000; /// The most connections past their hello a configuration may allow /// (`max_peers`), seeds aside. pub const MAX_PEERS: usize = 4096; /// What a malformed descriptor, table or payload is refused with: why, /// and where: the byte offset where reading stopped; for the checks /// against a table that follow parsing, the index of the definition at /// fault ([`Table::new`]), or 0 for a descriptor ([`Table::check`]). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct WireError { pub at: usize, pub what: &'static str, } impl fmt::Display for WireError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "wire: {} (at byte {})", self.what, self.at) } } impl std::error::Error for WireError {} fn err(at: usize, what: &'static str) -> Result { Err(WireError { at, what }) } // ---- descriptors ------------------------------------------------------------------- /// A type descriptor (`docs/wire-format.md`, *Type descriptors*). #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum Desc { Int, Float, String, Bytes, U64, Dec, Pid, Unit, Subject(Box), Array(Box), /// Two to [`MAX_TUPLE`] components. Tuple(Vec), /// A data type of the table, by qualified name, applied to arguments. Adt { name: String, args: Vec, }, /// A parameter of the enclosing definition (table field types only). Param(u32), } /// A literal piece of a descriptor, or a hole the caller fills with a /// type argument's descriptor ([`Desc::pieces`]). #[derive(Clone, Debug, PartialEq, Eq)] pub enum Piece { Lit(String), Hole(u32), } impl Desc { /// A closed descriptor (no parameter). pub fn parse(text: &str) -> Result { Self::parse_open(text, 0) } /// A descriptor whose parameters are below `params`. pub fn parse_open(text: &str, params: u32) -> Result { if text.len() > MAX_DESC_LEN { return err(0, "descriptor too long"); } let mut p = Parser::new(text.as_bytes())?; let d = p.desc(params, 0)?; if p.at != p.s.len() { return err(p.at, "trailing bytes after the descriptor"); } Ok(d) } /// Whether it mentions no parameter. pub fn is_closed(&self) -> bool { match self { Desc::Param(_) => false, Desc::Subject(d) | Desc::Array(d) => d.is_closed(), Desc::Tuple(ds) | Desc::Adt { args: ds, .. } => ds.iter().all(Desc::is_closed), _ => true, } } /// The descriptor with each `Param(i)` replaced by `args[i]` (a /// constructor's field types at an instance). /// /// # Panics /// If a parameter has no argument: the table was checked against it. pub fn instantiate(&self, args: &[Desc]) -> Desc { match self { Desc::Param(i) => args[*i as usize].clone(), Desc::Subject(d) => Desc::Subject(Box::new(d.instantiate(args))), Desc::Array(d) => Desc::Array(Box::new(d.instantiate(args))), Desc::Tuple(ds) => Desc::Tuple(ds.iter().map(|d| d.instantiate(args)).collect()), Desc::Adt { name, args: a } => Desc::Adt { name: name.clone(), args: a.iter().map(|d| d.instantiate(args)).collect(), }, leaf => leaf.clone(), } } /// The descriptor as literal pieces and holes, `Param(i)` being hole /// `i`, adjacent literals merged: what the compiler emits for a /// generic instantiation (a monomorphic type is one literal). pub fn pieces(&self) -> Vec { fn go(d: &Desc, out: &mut Vec) { let lit = |out: &mut Vec, s: &str| match out.last_mut() { Some(Piece::Lit(l)) => l.push_str(s), _ => out.push(Piece::Lit(s.to_owned())), }; match d { Desc::Param(i) => out.push(Piece::Hole(*i)), Desc::Subject(x) => { lit(out, "S"); go(x, out); } Desc::Array(x) => { lit(out, "A"); go(x, out); } Desc::Tuple(xs) => { lit(out, &tuple_prefix(xs.len())); xs.iter().for_each(|x| go(x, out)); } Desc::Adt { name, args } => { lit(out, &adt_prefix(name, args.len())); args.iter().for_each(|x| go(x, out)); } leaf => lit(out, &leaf.to_string()), } } let mut out = Vec::new(); go(self, &mut out); out } } impl fmt::Display for Desc { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Desc::Int => f.write_str("i"), Desc::Float => f.write_str("f"), Desc::String => f.write_str("s"), Desc::Bytes => f.write_str("b"), Desc::U64 => f.write_str("w"), Desc::Dec => f.write_str("d"), Desc::Pid => f.write_str("p"), Desc::Unit => f.write_str("u"), Desc::Subject(d) => write!(f, "S{d}"), Desc::Array(d) => write!(f, "A{d}"), Desc::Tuple(ds) => { f.write_str(&tuple_prefix(ds.len()))?; ds.iter().try_for_each(|d| write!(f, "{d}")) } Desc::Adt { name, args } => { f.write_str(&adt_prefix(name, args.len()))?; args.iter().try_for_each(|d| write!(f, "{d}")) } Desc::Param(i) => write!(f, "${i}"), } } } /// The piece a tuple's descriptor starts with; its components follow. pub fn tuple_prefix(arity: usize) -> String { format!("T{arity}") } /// The piece an instance of the data type `qualified` starts with; its /// `args` type arguments' descriptors follow. pub fn adt_prefix(qualified: &str, args: usize) -> String { format!("N{};{args}", escape_name(qualified)) } /// Whether `b` stands for itself in a name; every other byte is `%XX`. fn name_byte(b: u8) -> bool { b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'/' | b'-') } /// A name in descriptor text: its UTF-8 bytes, those outside /// `A-Z a-z 0-9 _ . / -` as `%XX` (uppercase hex). pub fn escape_name(name: &str) -> String { let mut out = String::with_capacity(name.len()); for &b in name.as_bytes() { if name_byte(b) { out.push(char::from(b)); } else { out.push_str(&format!("%{b:02X}")); } } out } struct Parser<'a> { s: &'a [u8], at: usize, } impl<'a> Parser<'a> { fn new(s: &'a [u8]) -> Result { if let Some(i) = s.iter().position(|b| !b.is_ascii()) { return err(i, "descriptor text is not ASCII"); } Ok(Parser { s, at: 0 }) } fn peek(&self) -> Option { self.s.get(self.at).copied() } fn expect(&mut self, b: u8, what: &'static str) -> Result<(), WireError> { if self.peek() != Some(b) { return err(self.at, what); } self.at += 1; Ok(()) } /// A decimal count: no sign, no leading zero, at most `max`. fn count(&mut self, max: u32) -> Result { let start = self.at; while self.peek().is_some_and(|b| b.is_ascii_digit()) { self.at += 1; } let digits = &self.s[start..self.at]; if digits.is_empty() { return err(start, "expected a decimal count"); } if digits.len() > 1 && digits[0] == b'0' { return err(start, "a count has no leading zero"); } if digits.len() > 9 { return err(start, "count out of range"); } let n = digits .iter() .fold(0u32, |n, d| n * 10 + u32::from(d - b'0')); if n > max { return err(start, "count out of range"); } Ok(n) } /// An escaped name up to its `;` (consumed); empty only if `may_be_empty`. fn name(&mut self, may_be_empty: bool) -> Result { let start = self.at; let mut out = Vec::new(); loop { match self.peek() { None => return err(self.at, "unterminated name"), Some(b';') => break, Some(b'%') => { let hex = |i: usize| { self.s .get(i) .filter(|b| b.is_ascii_digit() || (b'A'..=b'F').contains(b)) .map(|b| (*b as char).to_digit(16).expect("hex digit") as u8) }; let (Some(h), Some(l)) = (hex(self.at + 1), hex(self.at + 2)) else { return err(self.at, "bad %XX escape in a name"); }; let b = h << 4 | l; if name_byte(b) { return err(self.at, "a name escapes a byte that stands for itself"); } out.push(b); self.at += 3; } Some(b) if name_byte(b) => { out.push(b); self.at += 1; } Some(_) => return err(self.at, "unexpected byte in a name"), } if out.len() > MAX_NAME_LEN { return err(start, "name too long"); } } self.at += 1; // `;` if out.is_empty() && !may_be_empty { return err(start, "empty name"); } String::from_utf8(out).or_else(|_| err(start, "a name is not UTF-8")) } fn desc(&mut self, params: u32, depth: usize) -> Result { if depth >= MAX_DESC_DEPTH { return err(self.at, "descriptor nested too deeply"); } let at = self.at; let Some(b) = self.peek() else { return err(at, "expected a descriptor"); }; self.at += 1; Ok(match b { b'i' => Desc::Int, b'f' => Desc::Float, b's' => Desc::String, b'b' => Desc::Bytes, b'w' => Desc::U64, b'd' => Desc::Dec, b'p' => Desc::Pid, b'u' => Desc::Unit, b'S' => Desc::Subject(Box::new(self.desc(params, depth + 1)?)), b'A' => Desc::Array(Box::new(self.desc(params, depth + 1)?)), b'T' => { let n = self.count(MAX_TUPLE)?; if n < 2 { return err(at, "a tuple has two components or more"); } let ds = (0..n) .map(|_| self.desc(params, depth + 1)) .collect::>()?; Desc::Tuple(ds) } b'N' => { let name = self.name(false)?; let n = self.count(MAX_PARAMS)?; let args = (0..n) .map(|_| self.desc(params, depth + 1)) .collect::>()?; Desc::Adt { name, args } } b'$' => { let i = self.count(MAX_PARAMS)?; if i >= params { return err(at, "parameter out of range"); } Desc::Param(i) } _ => return err(at, "unknown descriptor"), }) } } // ---- the type definitions table ------------------------------------------------------ /// A data type of the table: its constructors in runtime index order. #[derive(Clone, Debug, PartialEq, Eq)] pub struct TypeDef { pub name: String, pub params: u32, pub ctors: Vec, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct CtorDef { pub name: String, pub fields: Vec, } /// A field: its label (empty when positional) and type, which may /// mention the definition's parameters. #[derive(Clone, Debug, PartialEq, Eq)] pub struct FieldDef { pub label: String, pub ty: Desc, } /// How a constructor's values are represented at run time /// (`docs/runtime-abi.md`, *Values*). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CtorRepr { /// A nullary constructor: the small int of its index. Immediate(u32), /// A block whose tag is its index and whose fields are its fields, in /// order. Block { tag: u32, fields: u32 }, } impl TypeDef { /// The representation of constructor `index`. /// /// # Panics /// If there is no such constructor. pub fn repr(&self, index: u32) -> CtorRepr { let fields = self.ctors[index as usize].fields.len() as u32; if fields == 0 { CtorRepr::Immediate(index) } else { CtorRepr::Block { tag: index, fields } } } /// Every data type its field types apply, with the arguments, nested /// ones included (`List>` gives `List` and `Option`). fn references(&self) -> impl Iterator { let mut work: Vec<&Desc> = self .ctors .iter() .flat_map(|c| c.fields.iter().map(|f| &f.ty)) .collect(); std::iter::from_fn(move || { while let Some(ty) = work.pop() { match ty { Desc::Subject(x) | Desc::Array(x) => work.push(x), Desc::Tuple(xs) => work.extend(xs), Desc::Adt { name, args } => { work.extend(args); return Some((name.as_str(), args.as_slice())); } _ => {} } } None }) } /// Its definition text (`docs/wire-format.md`, *The table*). pub fn write(&self, out: &mut String) { out.push('D'); out.push_str(&escape_name(&self.name)); out.push(';'); out.push_str(&self.params.to_string()); for c in &self.ctors { out.push('C'); out.push_str(&escape_name(&c.name)); out.push(';'); for f in &c.fields { out.push('F'); out.push_str(&escape_name(&f.label)); out.push(';'); out.push_str(&f.ty.to_string()); } } } } /// A program's type definitions table: every data type a `Wire` /// descriptor of the program reaches. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Table { defs: Vec, by_name: BTreeMap, } impl Table { /// A table of `defs`, checked: unique names, well-formed constructors, /// every reference to a defined type with as many arguments as it has /// parameters. pub fn new(defs: Vec) -> Result { if defs.len() > MAX_DEFS { return err(0, "too many definitions"); } let mut by_name = BTreeMap::new(); for (i, d) in defs.iter().enumerate() { if by_name.insert(d.name.clone(), i).is_some() { return err(i, "a type is defined twice"); } } let table = Table { defs, by_name }; for (i, d) in table.defs.iter().enumerate() { table.check_def(d).map_err(|e| WireError { at: i, ..e })?; } table.check_regular()?; Ok(table) } /// Whether every recursion is regular (`docs/wire-format.md`, *Regular /// types only*): a reference from a definition to one of its own /// strongly connected component passes each argument as a bare /// parameter or a closed type. A closed type then reaches finitely /// many instances, each no bigger than it and the table's field types; /// a nested type (`Nest { Nil, Cons(a, Nest<(a, a)>) }`) reaches /// instances that grow with the value. fn check_regular(&self) -> Result<(), WireError> { let component = self.components(); for (i, d) in self.defs.iter().enumerate() { let nested = d.references().any(|(name, args)| { component[self.by_name[name]] == component[i] && !args .iter() .all(|a| matches!(a, Desc::Param(_)) || a.is_closed()) }); if nested { return err(i, "a recursive reference is not regular (a nested type)"); } } Ok(()) } /// The strongly connected component of each definition, in the graph /// of references between definitions (Tarjan's algorithm, iterative: /// a chain of definitions does not recurse on the native stack). fn components(&self) -> Vec { let edges: Vec> = self .defs .iter() .map(|d| d.references().map(|(name, _)| self.by_name[name]).collect()) .collect(); let n = self.defs.len(); let mut index: Vec> = vec![None; n]; let mut low = vec![0; n]; let mut on_stack = vec![false; n]; let mut stack = Vec::new(); let mut component = vec![0; n]; let (mut next_index, mut next_component) = (0, 0); for root in 0..n { if index[root].is_some() { continue; } // (definition, its next edge to visit) let mut calls = vec![(root, 0)]; index[root] = Some(next_index); low[root] = next_index; next_index += 1; stack.push(root); on_stack[root] = true; while let Some(&(v, e)) = calls.last() { if let Some(&w) = edges[v].get(e) { calls.last_mut().expect("a call").1 += 1; match index[w] { None => { index[w] = Some(next_index); low[w] = next_index; next_index += 1; stack.push(w); on_stack[w] = true; calls.push((w, 0)); } Some(iw) if on_stack[w] => low[v] = low[v].min(iw), Some(_) => {} } continue; } calls.pop(); if let Some(&(u, _)) = calls.last() { low[u] = low[u].min(low[v]); } if Some(low[v]) == index[v] { loop { let w = stack.pop().expect("v is on the stack"); on_stack[w] = false; component[w] = next_component; if w == v { break; } } next_component += 1; } } } component } fn check_def(&self, d: &TypeDef) -> Result<(), WireError> { if d.name.is_empty() || d.name.len() > MAX_NAME_LEN { return err(0, "bad type name"); } if d.params > MAX_PARAMS { return err(0, "too many type parameters"); } if d.ctors.len() > MAX_CTORS as usize { return err(0, "too many constructors"); } let mut ctor_names = BTreeSet::new(); for c in &d.ctors { if c.name.is_empty() || c.name.len() > MAX_NAME_LEN || !ctor_names.insert(&c.name) { return err(0, "bad or repeated constructor name"); } if c.fields.len() > MAX_FIELDS as usize { return err(0, "too many fields"); } let mut labels = BTreeSet::new(); for f in &c.fields { if f.label.len() > MAX_NAME_LEN || (!f.label.is_empty() && !labels.insert(&f.label)) { return err(0, "bad or repeated field label"); } self.check_desc(&f.ty, d.params, 0)?; } } Ok(()) } /// Whether `ty` is well-formed here: parameters below `params`, every /// data type defined and fully applied. fn check_desc(&self, ty: &Desc, params: u32, depth: usize) -> Result<(), WireError> { if depth >= MAX_DESC_DEPTH { return err(0, "descriptor nested too deeply"); } match ty { Desc::Param(i) if *i >= params => err(0, "parameter out of range"), Desc::Subject(d) | Desc::Array(d) => self.check_desc(d, params, depth + 1), Desc::Tuple(ds) => { if ds.len() < 2 || ds.len() > MAX_TUPLE as usize { return err(0, "bad tuple arity"); } ds.iter() .try_for_each(|d| self.check_desc(d, params, depth + 1)) } Desc::Adt { name, args } => { let Some(def) = self.get(name) else { return err(0, "reference to an undefined type"); }; if args.len() != def.params as usize { return err(0, "wrong number of type arguments"); } args.iter() .try_for_each(|d| self.check_desc(d, params, depth + 1)) } _ => Ok(()), } } /// The table's text (`docs/wire-format.md`, *The table*). pub fn parse(text: &str) -> Result { if text.len() > MAX_TABLE_LEN { return err(0, "table too long"); } let mut p = Parser::new(text.as_bytes())?; let mut defs = Vec::new(); while p.peek().is_some() { p.expect(b'D', "expected a definition (`D`)")?; let name = p.name(false)?; let params = p.count(MAX_PARAMS)?; let mut ctors = Vec::new(); while p.peek() == Some(b'C') { p.at += 1; let name = p.name(false)?; let mut fields = Vec::new(); while p.peek() == Some(b'F') { p.at += 1; let label = p.name(true)?; let ty = p.desc(params, 0)?; fields.push(FieldDef { label, ty }); } ctors.push(CtorDef { name, fields }); } defs.push(TypeDef { name, params, ctors, }); } Table::new(defs) } /// Its text: what [`Table::parse`] reads back. pub fn write(&self) -> String { let mut out = String::new(); self.defs.iter().for_each(|d| d.write(&mut out)); out } /// The definition of the data type `name`. pub fn get(&self, name: &str) -> Option<&TypeDef> { self.by_name.get(name).map(|&i| &self.defs[i]) } pub fn defs(&self) -> &[TypeDef] { &self.defs } /// A closed descriptor read from `text` and checked against the table: /// what the runtime does with a descriptor a program built. pub fn parse_desc(&self, text: &str) -> Result { let d = Desc::parse(text)?; self.check(&d)?; Ok(d) } /// Whether a closed descriptor is well-formed against the table. pub fn check(&self, ty: &Desc) -> Result<(), WireError> { self.check_desc(ty, 0, 0) } /// The canonical form of a closed type (`docs/wire-format.md`, *The /// structural type hash*): the version line, its descriptor, then the /// definition of every data type it reaches, ordered by name, one per /// line. pub fn canonical(&self, ty: &Desc) -> Result { self.check(ty)?; let mut reached = BTreeSet::new(); let mut work = vec![ty]; while let Some(d) = work.pop() { match d { Desc::Subject(x) | Desc::Array(x) => work.push(x), Desc::Tuple(xs) => work.extend(xs), Desc::Adt { name, args } => { work.extend(args); if reached.insert(name.as_str()) { let def = self.get(name).expect("checked"); work.extend( def.ctors .iter() .flat_map(|c| c.fields.iter().map(|f| &f.ty)), ); } } _ => {} } } let mut out = format!("{CANONICAL_VERSION}\n{ty}\n"); // Sorted by name (a `BTreeSet<&str>` orders by bytes). for name in reached { self.get(name).expect("checked").write(&mut out); out.push('\n'); } Ok(out) } /// The structural hash of a closed type: [`hash_canonical`] of its /// [canonical form](Table::canonical). pub fn type_hash(&self, ty: &Desc) -> Result { Ok(hash_canonical(self.canonical(ty)?.as_bytes())) } /// The schema's canonical form (`docs/wire-format.md`, *The schema /// hash*): [`SCHEMA_LINE`], then every definition, ordered by name, /// one per line. Independent of the table's order. pub fn schema(&self) -> String { let mut out = format!("{SCHEMA_LINE}\n"); // Sorted by name (a `BTreeMap` orders by bytes). for &i in self.by_name.values() { self.defs[i].write(&mut out); out.push('\n'); } out } /// The schema hash, which two nodes compare in their handshake: /// [`hash_canonical`] of the [schema's canonical form](Table::schema). pub fn schema_hash(&self) -> u64 { hash_canonical(self.schema().as_bytes()) } } /// The first line of a schema's canonical form. A type's canonical form /// starts with [`CANONICAL_VERSION`] alone on its line, so no schema /// shares a form, or a hash input, with a type. pub const SCHEMA_LINE: &str = "louise-wire/1 schema"; /// The first line of every canonical form. It changes, and with it every /// hash, whenever the canonical form or the value encoding does. pub const CANONICAL_VERSION: &str = "louise-wire/1"; /// The type hash of a canonical form: the first 8 bytes of its SHA-256, /// big-endian. pub fn hash_canonical(canonical: &[u8]) -> u64 { let digest = sha256(canonical); u64::from_be_bytes(digest[..8].try_into().expect("8 bytes")) } /// The first line of a `@remote` entry's key input. No canonical form /// or schema starts with it, so a key never shares a hash input with a /// type. pub const REMOTE_LINE: &str = "louise-remote/1"; /// The key of the `@remote` function named `qualified` (`module/path.name`, /// UTF-8): [`hash_canonical`] of [`REMOTE_LINE`], LF, the name, shifted /// right by 2. Below 2^62, so it is a non-negative small `Int` everywhere /// and fits a frame's 8 bytes as a tag does (`docs/wire-format.md`, /// *Remote entries*). pub fn remote_key(qualified: &str) -> i64 { let input = format!("{REMOTE_LINE}\n{qualified}"); (hash_canonical(input.as_bytes()) >> 2) as i64 } // ---- the value encoding's primitives ---------------------------------------------------- /// Unsigned LEB128, shortest form. pub fn write_uvarint(out: &mut Vec, v: u64) { write_uvarint128(out, u128::from(v)); } pub fn write_uvarint128(out: &mut Vec, mut v: u128) { loop { let group = (v & 0x7F) as u8; v >>= 7; if v == 0 { out.push(group); return; } out.push(group | 0x80); } } /// Zigzag: `0, -1, 1, -2, ...` to `0, 1, 2, 3, ...`. pub fn zigzag(v: i128) -> u128 { ((v << 1) ^ (v >> 127)) as u128 } pub fn unzigzag(z: u128) -> i128 { ((z >> 1) as i128) ^ -((z & 1) as i128) } /// A node head: a new node and its kind-specific payload (a constructor /// index, a length, or 0), or a back-reference to node `n`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Head { New(u64), Back(u64), } /// A head; its payload or node index is below 2^63. pub fn write_head(out: &mut Vec, head: Head) { debug_assert!(matches!(head, Head::New(n) | Head::Back(n) if n < 1 << 63)); let h = match head { Head::New(p) => u128::from(p) << 1, Head::Back(n) => u128::from(n) << 1 | 1, }; write_uvarint128(out, h); } /// An `Int`'s head: the integer itself, or a back-reference to a node /// that is a big `Int`. #[derive(Clone, Debug, PartialEq, Eq)] pub enum IntHead { /// In [`SMALL_INT`]: an immediate, never a node. Small(i64), /// Outside it: a big integer, a new node. Big(BigInt), Back(u64), } /// An `Int` (`docs/wire-format.md`, *Value encoding*): the shortest LEB128 /// of `zigzag(n) << 1`, of any length. pub fn write_int(out: &mut Vec, n: &BigInt) { if let Ok(v) = i128::try_from(n) && v.unsigned_abs() < 1 << 125 { write_uvarint128(out, zigzag(v) << 1); return; } // zigzag(n) << 1 = 4|n| (n ≥ 0) or 4|n| − 2 (n < 0) let mag = n.magnitude() << 2u32; let h = if n.sign() == Sign::Minus { mag - 2u32 } else { mag }; let groups = h.to_radix_le(128); let last = groups.len() - 1; out.extend( groups .iter() .enumerate() .map(|(i, g)| if i < last { g | 0x80 } else { *g }), ); } pub fn write_small_int(out: &mut Vec, n: i64) { write_uvarint128(out, zigzag(i128::from(n)) << 1); } pub fn write_float(out: &mut Vec, x: f64) { out.extend_from_slice(&x.to_bits().to_le_bytes()); } /// A cursor over a payload: every read checks the bytes left first. pub struct Reader<'a> { bytes: &'a [u8], at: usize, } impl<'a> Reader<'a> { pub fn new(bytes: &'a [u8]) -> Self { Reader { bytes, at: 0 } } pub fn at(&self) -> usize { self.at } pub fn left(&self) -> usize { self.bytes.len() - self.at } pub fn is_empty(&self) -> bool { self.left() == 0 } fn fail(&self, what: &'static str) -> Result { err(self.at, what) } pub fn byte(&mut self) -> Result { let Some(&b) = self.bytes.get(self.at) else { return self.fail("payload ends early"); }; self.at += 1; Ok(b) } /// `n` bytes, checked against the bytes left before anything is /// allocated for them. pub fn take(&mut self, n: u64) -> Result<&'a [u8], WireError> { if n > self.left() as u64 { return self.fail("length past the end of the payload"); } let s = &self.bytes[self.at..self.at + n as usize]; self.at += n as usize; Ok(s) } pub fn u64_le(&mut self) -> Result { Ok(u64::from_le_bytes( self.take(8)?.try_into().expect("8 bytes"), )) } pub fn float(&mut self) -> Result { Ok(f64::from_bits(self.u64_le()?)) } /// The groups of one LEB128 number, its last group not zero unless /// it is the only one (shortest form). fn groups(&mut self) -> Result<&'a [u8], WireError> { let start = self.at; let rest = &self.bytes[start..]; let Some(len) = rest.iter().position(|b| b & 0x80 == 0).map(|i| i + 1) else { return self.fail("payload ends inside a varint"); }; if len > 1 && rest[len - 1] == 0 { return self.fail("varint not in shortest form"); } self.at += len; Ok(&rest[..len]) } /// A LEB128 number below `2^bits` (`bits` ≤ 128). fn uvarint_bits(&mut self, bits: u32) -> Result { let start = self.at; let g = self.groups()?; let max_groups = bits.div_ceil(7) as usize; // The last group of a full-length number holds the top bits only. let top_bits = bits - 7 * (max_groups as u32 - 1); if g.len() > max_groups || (g.len() == max_groups && g[g.len() - 1] >> top_bits != 0) { return err(start, "varint out of range"); } Ok(g.iter() .rev() .fold(0u128, |v, b| v << 7 | u128::from(b & 0x7F))) } /// A `U64`, a length, an index or a count. pub fn uvarint(&mut self) -> Result { Ok(self.uvarint_bits(64)? as u64) } /// A `Dec`: zigzag, then LEB128, of its `i128`. pub fn dec(&mut self) -> Result { Ok(unzigzag(self.uvarint_bits(128)?)) } pub fn head(&mut self) -> Result { let h = self.uvarint()?; Ok(if h & 1 == 1 { Head::Back(h >> 1) } else { Head::New(h >> 1) }) } /// An `Int`'s head, canonical: small exactly when in [`SMALL_INT`]. pub fn int(&mut self) -> Result { let start = self.at; let g = self.groups()?; let back = g[0] & 1 == 1; if g.len() <= 18 { // At most 126 bits. let h = g .iter() .rev() .fold(0u128, |v, b| v << 7 | u128::from(b & 0x7F)); if back { return u64::try_from(h >> 1) .map(IntHead::Back) .or_else(|_| err(start, "back-reference out of range")); } let v = unzigzag(h >> 1); return Ok(match i64::try_from(v) { Ok(s) if SMALL_INT.contains(&s) => IntHead::Small(s), _ => IntHead::Big(BigInt::from(v)), }); } if back { return err(start, "back-reference out of range"); } let digits: Vec = g.iter().map(|b| b & 0x7F).collect(); let h = BigUint::from_radix_le(&digits, 128).expect("7-bit digits"); let z: BigUint = h >> 1u32; // Over 126 bits: never small. let half = BigInt::from(&z >> 1u32); Ok(IntHead::Big(if z.bit(0) { -half - 1 } else { half })) } } // ---- the message frame --------------------------------------------------------------- /// The header of a message frame (`docs/wire-format.md`, *Frames*): 36 /// bytes, little-endian. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct MessageHeader { /// The target actor: the receiving node's incarnation as the sender /// knows it, and the actor's serial there. pub incarnation: u64, pub serial: u64, /// The target subject's tag. pub tag: u64, pub type_hash: u64, pub payload_len: u32, } pub const HEADER_LEN: usize = 36; impl MessageHeader { pub fn encode(&self) -> [u8; HEADER_LEN] { let mut out = [0u8; HEADER_LEN]; out[0..8].copy_from_slice(&self.incarnation.to_le_bytes()); out[8..16].copy_from_slice(&self.serial.to_le_bytes()); out[16..24].copy_from_slice(&self.tag.to_le_bytes()); out[24..32].copy_from_slice(&self.type_hash.to_le_bytes()); out[32..36].copy_from_slice(&self.payload_len.to_le_bytes()); out } /// A header, its fields in range. pub fn decode(bytes: &[u8; HEADER_LEN]) -> Result { let word = |i: usize| u64::from_le_bytes(bytes[i..i + 8].try_into().expect("8 bytes")); let h = MessageHeader { incarnation: word(0), serial: word(8), tag: word(16), type_hash: word(24), payload_len: u32::from_le_bytes(bytes[32..36].try_into().expect("4 bytes")), }; if h.serial >= MAX_PID_SERIAL { return err(8, "pid serial out of range"); } if h.tag >= MAX_TAG { return err(16, "subject tag out of range"); } if h.payload_len > MAX_PAYLOAD { return err(32, "payload too large"); } Ok(h) } } /// Whether `name` is a node name: a lowercase DNS name (labels of /// `a-z 0-9 -`, 1 to 63 bytes, not starting or ending with `-`, /// separated by dots, the last not all digits), at most 253 bytes. Byte /// equality is then name equality. The last label rules out an IPv4 /// address, which a certificate would match against its IP addresses /// rather than its DNS names (RFC 1123 host names end with a letter label /// for the same reason). pub fn check_node_name(name: &[u8]) -> bool { let last = name.rsplit(|&b| b == b'.').next().unwrap_or_default(); !name.is_empty() && name.len() <= MAX_NODE_NAME && !last.iter().all(u8::is_ascii_digit) && name.split(|&b| b == b'.').all(|label| { !label.is_empty() && label.len() <= 63 && label.first() != Some(&b'-') && label.last() != Some(&b'-') && label .iter() .all(|&b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') }) } // ---- SHA-256 (FIPS 180-4) ---------------------------------------------------------------- // The compiler and the runtime without its `crypto` feature have no `ring` // (Cargo.toml), and the hash must be the same everywhere: this one is // checked against `ring`'s and the standard's vectors. const K: [u32; 64] = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, ]; fn sha256(data: &[u8]) -> [u8; 32] { let mut h: [u32; 8] = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, ]; // The message, a 1 bit, zeros, and its length in bits: whole blocks. let mut msg = data.to_vec(); msg.push(0x80); while msg.len() % 64 != 56 { msg.push(0); } msg.extend_from_slice(&((data.len() as u64).wrapping_mul(8)).to_be_bytes()); for block in msg.as_chunks::<64>().0 { let mut w = [0u32; 64]; for (i, word) in block.as_chunks::<4>().0.iter().enumerate() { w[i] = u32::from_be_bytes(*word); } for i in 16..64 { let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); w[i] = w[i - 16] .wrapping_add(s0) .wrapping_add(w[i - 7]) .wrapping_add(s1); } let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h; for i in 0..64 { let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); let ch = (e & f) ^ (!e & g); let t1 = hh .wrapping_add(s1) .wrapping_add(ch) .wrapping_add(K[i]) .wrapping_add(w[i]); let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); let maj = (a & b) ^ (a & c) ^ (b & c); let t2 = s0.wrapping_add(maj); hh = g; g = f; f = e; e = d.wrapping_add(t1); d = c; c = b; b = a; a = t1.wrapping_add(t2); } for (x, y) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) { *x = x.wrapping_add(y); } } let mut out = [0u8; 32]; for (chunk, word) in out.as_chunks_mut::<4>().0.iter_mut().zip(h) { *chunk = word.to_be_bytes(); } out } #[cfg(test)] mod tests { use super::*; fn adt(name: &str, args: Vec) -> Desc { Desc::Adt { name: name.into(), args, } } /// The prelude's types and `docs/wire-format.md`'s example, as the /// compiler would emit them. const TABLE: &str = "Dstd/prelude.Bool;0CFalse;CTrue;\ Dstd/prelude.List;1CNil;CCons;F;$0F;Nstd/prelude.List;1$0\ Dstd/process.ExitReason;0CNormal;CKilled;CCrashed;F;sCShutdown;\ Ddemo.Task;1CDone;CStep;Fpayload;$0Freply;SiFnext;Ndemo.Task;1$0\ Dstd/prelude.Never;0"; fn table() -> Table { Table::parse(TABLE).unwrap() } #[test] fn descriptors_round_trip() { for text in [ "i", "f", "s", "b", "w", "d", "p", "u", "Si", "AAs", "T2is", "T3uSpAd", "Nstd/prelude.Bool;0", "Nstd/prelude.List;1T2iNstd/prelude.List;1s", "Napp/donn%C3%A9es.Th%C3%A9;0", "Nmy-pkg/x_y.Z;2wS$1", ] { let params = if text.contains('$') { 2 } else { 0 }; let d = Desc::parse_open(text, params).unwrap(); assert_eq!(d.to_string(), text); assert_eq!(d.is_closed(), params == 0, "{text}"); } assert_eq!( Desc::parse("Nstd/prelude.List;1i").unwrap(), adt("std/prelude.List", vec![Desc::Int]) ); assert_eq!(escape_name("app/données.Thé"), "app/donn%C3%A9es.Th%C3%A9"); assert_eq!( Desc::parse("Napp/donn%C3%A9es.Th%C3%A9;0").unwrap(), adt("app/données.Thé", vec![]) ); } #[test] fn malformed_descriptors_are_refused() { let deep = format!("{}i", "A".repeat(MAX_DESC_DEPTH)); let wide = format!("T255{}", "i".repeat(255)); for (text, at, what) in [ ("", 0, "expected a descriptor"), ("x", 0, "unknown descriptor"), ("ii", 1, "trailing bytes after the descriptor"), ("T1i", 0, "a tuple has two components or more"), ("T2i", 3, "expected a descriptor"), ("T02ii", 1, "a count has no leading zero"), ("T", 1, "expected a decimal count"), ("T9999999999i", 1, "count out of range"), (wide.as_str(), 1, "count out of range"), ("Nfoo", 4, "unterminated name"), ("Nfoo;", 5, "expected a decimal count"), ("N;0", 1, "empty name"), ("Nfoo;1", 6, "expected a descriptor"), ("Na b;0", 2, "unexpected byte in a name"), ("N%41;0", 1, "a name escapes a byte that stands for itself"), ("N%e9;0", 1, "bad %XX escape in a name"), ("N%E;0", 1, "bad %XX escape in a name"), ("N%FF;0", 1, "a name is not UTF-8"), ("$0", 0, "parameter out of range"), ("Sé", 1, "descriptor text is not ASCII"), ( deep.as_str(), MAX_DESC_DEPTH, "descriptor nested too deeply", ), ] { assert_eq!(Desc::parse(text), Err(WireError { at, what }), "{text:?}"); } assert!(Desc::parse(&"i".repeat(MAX_DESC_LEN + 1)).is_err()); // Nesting just under the limit is fine. let ok = format!("{}i", "A".repeat(MAX_DESC_DEPTH - 1)); assert!(Desc::parse(&ok).is_ok()); } /// The compiler emits a generic instantiation as these pieces, with /// each hole filled by the type argument's descriptor at run time. #[test] fn pieces_concatenate_to_the_instance() { let generic = Desc::parse_open("T2$0SNdemo.Task;1$1", 2).unwrap(); assert_eq!( generic.pieces(), [ Piece::Lit("T2".into()), Piece::Hole(0), Piece::Lit("SNdemo.Task;1".into()), Piece::Hole(1), ] ); let args = [Desc::parse("Nstd/prelude.List;1i").unwrap(), Desc::String]; let built: String = generic .pieces() .iter() .map(|p| match p { Piece::Lit(s) => s.clone(), Piece::Hole(i) => args[*i as usize].to_string(), }) .collect(); assert_eq!(built, generic.instantiate(&args).to_string()); assert_eq!(built, "T2Nstd/prelude.List;1iSNdemo.Task;1s"); // A monomorphic type is one literal. let mono = Desc::parse("ANstd/prelude.List;1T2fs").unwrap(); assert_eq!( mono.pieces(), [Piece::Lit("ANstd/prelude.List;1T2fs".into())] ); assert_eq!(adt_prefix("app/thé.T", 2), "Napp/th%C3%A9.T;2"); assert_eq!(tuple_prefix(3), "T3"); } #[test] fn tables_round_trip_and_resolve() { let t = table(); assert_eq!(t.write(), TABLE); assert_eq!(t.defs().len(), 5); let list = t.get("std/prelude.List").unwrap(); assert_eq!(list.params, 1); assert_eq!(list.repr(0), CtorRepr::Immediate(0)); assert_eq!(list.repr(1), CtorRepr::Block { tag: 1, fields: 2 }); // Indices count nullary and boxed constructors alike. let reason = t.get("std/process.ExitReason").unwrap(); assert_eq!(reason.repr(2), CtorRepr::Block { tag: 2, fields: 1 }); assert_eq!(reason.repr(3), CtorRepr::Immediate(3)); assert!(t.get("std/prelude.Never").unwrap().ctors.is_empty()); let task = t.get("demo.Task").unwrap(); assert_eq!( task.ctors[1] .fields .iter() .map(|f| f.ty.instantiate(&[Desc::String]).to_string()) .collect::>(), ["s", "Si", "Ndemo.Task;1s"] ); assert_eq!( t.parse_desc("Ndemo.Task;1As").unwrap().to_string(), "Ndemo.Task;1As" ); for (text, what) in [ ("Nnope;0", "reference to an undefined type"), ("Nstd/prelude.List;0", "wrong number of type arguments"), ("Nstd/prelude.List;2ii", "wrong number of type arguments"), ("ANstd/prelude.Bool;1i", "wrong number of type arguments"), ] { assert_eq!(t.parse_desc(text).unwrap_err().what, what, "{text}"); } } #[test] fn malformed_tables_are_refused() { for (text, what) in [ ("X", "expected a definition (`D`)"), ("Da;0Da;0", "a type is defined twice"), ("Da;0CX;CX;", "bad or repeated constructor name"), ("Da;0C;", "empty name"), ("Da;0CX;Fl;iFl;s", "bad or repeated field label"), ("Da;1CX;F;$1", "parameter out of range"), ("Da;0CX;F;Nb;0", "reference to an undefined type"), ("Da;1CX;F;Na;0", "wrong number of type arguments"), ("Da;0CX;F;", "expected a descriptor"), ("Da;0CX;F;ii", "expected a definition (`D`)"), ("Da;256", "count out of range"), ] { assert_eq!(Table::parse(text).unwrap_err().what, what, "{text}"); } // Positional fields share the empty label. assert!(Table::parse("Da;0CX;F;iF;i").is_ok()); let wide = TypeDef { name: "a".into(), params: 0, ctors: vec![CtorDef { name: "X".into(), fields: vec![ FieldDef { label: String::new(), ty: Desc::Int }; MAX_FIELDS as usize + 1 ], }], }; assert_eq!(Table::new(vec![wide]).unwrap_err().what, "too many fields"); } #[test] fn canonical_forms_expand_reachable_definitions_once() { let t = table(); let ty = Desc::parse("Ndemo.Task;1s").unwrap(); assert_eq!( t.canonical(&ty).unwrap(), "louise-wire/1\n\ Ndemo.Task;1s\n\ Ddemo.Task;1CDone;CStep;Fpayload;$0Freply;SiFnext;Ndemo.Task;1$0\n" ); // Definitions sorted by name, each once, whatever the table's order // and whatever else it holds. let ty = Desc::parse("T2Nstd/prelude.List;1Nstd/prelude.Bool;0Ndemo.Task;1i").unwrap(); let canonical = t.canonical(&ty).unwrap(); assert_eq!( canonical, "louise-wire/1\n\ T2Nstd/prelude.List;1Nstd/prelude.Bool;0Ndemo.Task;1i\n\ Ddemo.Task;1CDone;CStep;Fpayload;$0Freply;SiFnext;Ndemo.Task;1$0\n\ Dstd/prelude.Bool;0CFalse;CTrue;\n\ Dstd/prelude.List;1CNil;CCons;F;$0F;Nstd/prelude.List;1$0\n" ); let mut defs = t.defs().to_vec(); defs.reverse(); defs.retain(|d| d.name != "std/process.ExitReason"); assert_eq!(Table::new(defs).unwrap().canonical(&ty).unwrap(), canonical); // Leaves reach no definition. assert_eq!(t.canonical(&Desc::Int).unwrap(), "louise-wire/1\ni\n"); } #[test] fn recursion_terminates() { // Mutual recursion, arguments permuted or closed: definitions are // expanded, not instances. let t = Table::parse( "Dm.Even;0CZ;CE;F;Nm.Odd;0\ Dm.Odd;0CO;F;Nm.Even;0\ Dm.Swap;2CS;F;$0F;Nm.Swap;2$1$0\ Dm.Fix;1CX;F;$0F;Nm.Fix;1T2ii", ) .unwrap(); let even = t.canonical(&Desc::parse("Nm.Even;0").unwrap()).unwrap(); assert_eq!(even.lines().count(), 4); let swap = t.canonical(&Desc::parse("Nm.Swap;2is").unwrap()).unwrap(); assert_eq!(swap.lines().count(), 3); let fix = t.canonical(&Desc::parse("Nm.Fix;1s").unwrap()).unwrap(); assert_eq!(fix.lines().count(), 3); } /// A nested type's instances grow with its values (`Nest`'s n-th cell /// is at a type of 2^n leaves): the table refuses it, directly or /// through mutual recursion, and only it. #[test] fn nested_types_are_refused() { for (text, at) in [ ("Dm.Nest;1CNil;CCons;F;$0F;Nm.Nest;1T2$0$0", 0), ("Dm.Nest;1CNil;CCons;F;$0F;ANm.Nest;1A$0", 0), ("Dm.A;1CX;F;Nm.B;1$0Dm.B;1CY;F;Nm.A;1S$0", 1), ( "Dm.Ok;0CO;Dm.A;1CX;F;Nm.A;1Nm.L;1$0Dm.L;1CN;CC;F;$0F;Nm.L;1$0", 1, ), ] { assert_eq!( Table::parse(text).unwrap_err(), WireError { at, what: "a recursive reference is not regular (a nested type)" }, "{text}" ); } // Compound arguments to a type outside the recursion are fine. Table::parse( "Dm.L;1CN;CC;F;$0F;Nm.L;1$0\ Dm.T;1CLeaf;CNode;F;Nm.L;1T2$0Nm.T;1$0", ) .unwrap(); } /// Names, labels and constructor order are part of a type's meaning, /// parameter names are not (they are positions). #[test] fn hashes_follow_meaning() { let hash = |table: &str, ty: &str| { let t = Table::parse(table).unwrap(); t.type_hash(&t.parse_desc(ty).unwrap()).unwrap() }; let base = hash("Dm.P;0CP;Fx;iFy;i", "Nm.P;0"); for (table, ty) in [ ("Dm.Q;0CP;Fx;iFy;i", "Nm.Q;0"), // type name ("Dm.P;0CQ;Fx;iFy;i", "Nm.P;0"), // constructor name ("Dm.P;0CP;Fx;iFz;i", "Nm.P;0"), // label ("Dm.P;0CP;Fy;iFx;i", "Nm.P;0"), // field order ("Dm.P;0CP;Fx;iFy;f", "Nm.P;0"), // field type ("Dm.P;0CP;Fx;iFy;iCR;", "Nm.P;0"), // a new constructor ] { assert_ne!(hash(table, ty), base, "{table}"); } // An unrelated definition changes nothing. assert_eq!(hash("Dm.P;0CP;Fx;iFy;iDm.U;0CU;", "Nm.P;0"), base); let swapped = hash("Dm.E;0CA;CB;", "Nm.E;0"); assert_ne!(hash("Dm.E;0CB;CA;", "Nm.E;0"), swapped); } /// Hashes are part of the protocol: these values must never change /// without a new `CANONICAL_VERSION`. #[test] fn hashes_are_stable() { let t = table(); let h = |ty: &str| t.type_hash(&t.parse_desc(ty).unwrap()).unwrap(); // Python's `hashlib.sha256(canonical).digest()[:8].hex()`. assert_eq!(h("i"), 0xa1f9_0d70_e682_6ce8); assert_eq!(h("Nstd/prelude.List;1i"), 0x75e3_aca9_dd86_7f77); assert_eq!(h("Ndemo.Task;1s"), 0x9949_47b8_73cb_1aa7); } /// The schema covers every definition, whatever the table's order; a /// golden value pins its form. #[test] fn schema_hashes_cover_the_whole_table() { let t = table(); let mut reversed = t.defs().to_vec(); reversed.reverse(); let r = Table::new(reversed).unwrap(); assert_eq!(r.schema(), t.schema()); assert_eq!(r.schema_hash(), t.schema_hash()); assert!(t.schema().starts_with("louise-wire/1 schema\nDdemo.Task;1")); assert_eq!(t.schema().lines().count(), 1 + t.defs().len()); let fewer = Table::new(t.defs()[..4].to_vec()).unwrap(); assert_ne!(fewer.schema_hash(), t.schema_hash()); assert_eq!(Table::default().schema(), "louise-wire/1 schema\n"); // Python: `hashlib.sha256(schema).digest()[:8].hex()`. assert_eq!(t.schema_hash(), 0x4259_3343_7b01_fc4c); } /// Golden values, from Python: `int.from_bytes(hashlib.sha256( /// b"louise-remote/1\n" + name).digest()[:8], "big") >> 2`. #[test] fn remote_keys_are_small_ints() { assert_eq!(remote_key("demo.worker"), 0x0daa_e2c2_50d5_6ded); assert_eq!(remote_key("app/données.thé"), 0x019e_5a45_bd38_b345); for name in ["a.b", "demo.worker", "x/y.z"] { assert!(SMALL_INT.contains(&remote_key(name)) && remote_key(name) >= 0); } assert_ne!(remote_key("demo.worker"), remote_key("demo.worker2")); } #[test] fn sha256_matches_the_standard() { let hex = |d: [u8; 32]| d.iter().map(|b| format!("{b:02x}")).collect::(); assert_eq!( hex(sha256(b"")), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" ); assert_eq!( hex(sha256(b"abc")), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" ); assert_eq!( hex(sha256( b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" )), "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" ); #[cfg(feature = "crypto")] for n in [0, 1, 55, 56, 63, 64, 65, 119, 120, 1000] { let data: Vec = (0..n).map(|i| (i * 7 + 3) as u8).collect(); assert_eq!(sha256(&data), crate::crypto::sha256(&data), "{n} bytes"); } } #[test] fn varints_are_shortest_and_bounded() { for v in [0, 1, 127, 128, 300, u64::from(u32::MAX), u64::MAX] { let mut out = Vec::new(); write_uvarint(&mut out, v); let mut r = Reader::new(&out); assert_eq!(r.uvarint(), Ok(v)); assert!(r.is_empty()); } let mut out = Vec::new(); write_uvarint(&mut out, 300); assert_eq!(out, [0xAC, 0x02]); let bad = |bytes: &[u8]| Reader::new(bytes).uvarint().unwrap_err().what; assert_eq!(bad(&[0x80, 0x00]), "varint not in shortest form"); assert_eq!(bad(&[0x80]), "payload ends inside a varint"); assert_eq!(bad(&[]), "payload ends inside a varint"); // 2^64 needs a 2 in the tenth group. let mut over = vec![0x80; 9]; over.push(0x02); assert_eq!(bad(&over), "varint out of range"); assert_eq!(bad(&[0x80; 11]), "payload ends inside a varint"); for d in [0, 1, -1, i128::MAX, i128::MIN, 10i128.pow(18)] { let mut out = Vec::new(); write_uvarint128(&mut out, zigzag(d)); assert!(out.len() <= 19); assert_eq!(Reader::new(&out).dec(), Ok(d)); } assert_eq!(zigzag(-1), 1); assert_eq!(zigzag(1), 2); } #[test] fn ints_are_canonical_whatever_their_size() { let encode = |n: &BigInt| { let mut out = Vec::new(); write_int(&mut out, n); out }; assert_eq!(encode(&BigInt::from(0)), [0x00]); assert_eq!(encode(&BigInt::from(-1)), [0x02]); assert_eq!(encode(&BigInt::from(1)), [0x04]); assert_eq!(encode(&BigInt::from(31)), [0x7C]); assert_eq!(encode(&BigInt::from(32)), [0x80, 0x01]); let small_max = SMALL_INT.end - 1; let big = |s: &str| s.parse::().unwrap(); for n in [ BigInt::from(0), BigInt::from(-7), BigInt::from(small_max), BigInt::from(SMALL_INT.start), BigInt::from(small_max) + 1, BigInt::from(SMALL_INT.start) - 1, BigInt::from(i64::MAX), BigInt::from(i64::MIN), BigInt::from(i128::MAX), BigInt::from(i128::MIN), big("-123456789012345678901234567890123456789012345678901234567890"), big("340282366920938463463374607431768211456"), // 2^128 BigInt::from(1) << 125u32, -(BigInt::from(1) << 125u32), ] { let bytes = encode(&n); let mut r = Reader::new(&bytes); let head = r.int().unwrap(); assert!(r.is_empty(), "{n}"); let small = i64::try_from(&n).ok().filter(|v| SMALL_INT.contains(v)); match (small, head) { (Some(v), IntHead::Small(w)) => assert_eq!(v, w), (None, IntHead::Big(m)) => assert_eq!(m, n), (_, other) => panic!("{n} decoded as {other:?}"), } if let Some(v) = small { let mut out = Vec::new(); write_small_int(&mut out, v); assert_eq!(out, bytes); } } // Back-references share the low bit with the integers. let mut out = Vec::new(); write_head(&mut out, Head::Back(5)); assert_eq!(out, [0x0B]); assert_eq!(Reader::new(&out).int(), Ok(IntHead::Back(5))); assert_eq!(Reader::new(&out).head(), Ok(Head::Back(5))); assert_eq!( Reader::new(&[0x80, 0x00]).int().unwrap_err().what, "varint not in shortest form" ); } #[test] fn readers_check_lengths_before_taking() { let mut r = Reader::new(&[1, 2, 3]); assert_eq!( r.take(4).unwrap_err().what, "length past the end of the payload" ); assert_eq!( r.take(u64::MAX).unwrap_err().what, "length past the end of the payload" ); assert_eq!(r.take(2), Ok(&[1, 2][..])); assert_eq!(r.left(), 1); assert_eq!(r.u64_le().unwrap_err().at, 2); let nan = f64::from_bits(0x7FF4_0000_0000_0001); let mut out = Vec::new(); write_float(&mut out, nan); assert_eq!(Reader::new(&out).float().unwrap().to_bits(), nan.to_bits()); } #[test] fn headers_round_trip_and_are_bounded() { let h = MessageHeader { incarnation: 0xFEDC_BA98_7654_3210, serial: 12, tag: 40, type_hash: 0x0123_4567_89AB_CDEF, payload_len: 23, }; let bytes = h.encode(); assert_eq!(MessageHeader::decode(&bytes), Ok(h)); for (field, at) in [ (8, "pid serial out of range"), (16, "subject tag out of range"), ] { let mut b = bytes; b[field + 7] = 0x40; assert_eq!(MessageHeader::decode(&b).unwrap_err().what, at); } let mut b = bytes; b[32..36].copy_from_slice(&(MAX_PAYLOAD + 1).to_le_bytes()); assert_eq!( MessageHeader::decode(&b).unwrap_err().what, "payload too large" ); } #[test] fn node_names_are_lowercase_dns_names() { for good in [ "a", "a.example", "node-1.cluster.local", &"a".repeat(63), "10.0.0.5a", "1.example", ] { assert!(check_node_name(good.as_bytes()), "{good}"); } let long = format!("{}.{}", "a".repeat(63), "b".repeat(63)).repeat(2) + ".c"; for bad in [ "", "A.example", "a..b", ".a", "a.", "-a", "a-", "a_b", "é", &"a".repeat(64), &long, // An IPv4 address: a certificate's IP addresses would match it // (#404's security review, SEC-10). "127.0.0.1", "10.0.0.5", "node.42", "7", ] { assert!(!check_node_name(bad.as_bytes()), "{bad}"); } } /// `docs/wire-format.md`'s worked example, byte for byte. #[test] fn the_worked_example() { let t = table(); let ty = t.parse_desc("Ndemo.Task;1s").unwrap(); let hash = t.type_hash(&ty).unwrap(); // The document quotes these. let doc = include_str!("../../../docs/wire-format.md"); let entry = t.get("demo.Task").unwrap(); let mut text = String::new(); entry.write(&mut text); assert!(doc.contains(&format!("Table entry: `{text}`"))); assert!(doc.contains(&format!("```\n{}```", t.canonical(&ty).unwrap()))); assert!(doc.contains(&format!("its hash `{hash:016x}`"))); // Step("hi", r, Step("hi", r, Done)), the string and the subject // shared; r is tag 3 of actor 7 on node a.example. let mut p = Vec::new(); write_uvarint(&mut p, 1); // one node entry write_uvarint(&mut p, 9); p.extend_from_slice(b"a.example"); p.extend_from_slice(&0x0123_4567_89AB_CDEFu64.to_le_bytes()); write_head(&mut p, Head::New(1)); // node 0: Step write_head(&mut p, Head::New(2)); // node 1: "hi" p.extend_from_slice(b"hi"); write_head(&mut p, Head::New(0)); // node 2: the subject write_uvarint(&mut p, 0); // its owner: entry 0, write_uvarint(&mut p, 7); // serial 7 write_uvarint(&mut p, 3); // its tag write_head(&mut p, Head::New(1)); // node 3: Step write_head(&mut p, Head::Back(1)); // "hi" write_head(&mut p, Head::Back(2)); // the subject write_head(&mut p, Head::New(0)); // Done: an immediate let header = MessageHeader { incarnation: 0xFEDC_BA98_7654_3210, serial: 12, tag: 40, type_hash: hash, payload_len: p.len() as u32, }; let hex = |b: &[u8]| { b.chunks(8) .map(|c| { c.iter() .map(|b| format!("{b:02x}")) .collect::>() .join(" ") }) .collect::>() .join("\n") }; assert_eq!( hex(&header.encode()), "10 32 54 76 98 ba dc fe\n\ 0c 00 00 00 00 00 00 00\n\ 28 00 00 00 00 00 00 00\n\ a7 1a cb 73 b8 47 49 99\n\ 1f 00 00 00" ); assert_eq!( hex(&p), "01 09 61 2e 65 78 61 6d\n\ 70 6c 65 ef cd ab 89 67\n\ 45 23 01 02 04 68 69 00\n\ 00 07 03 02 03 05 00" ); // The document's annotated dump is these bytes: on each line, the // two-digit hex tokens before the annotation. let dump = doc .split("```\nheader") .nth(1) .and_then(|rest| rest.split("```").next()) .expect("the example's dump"); let quoted: Vec = dump .lines() .flat_map(|line| { line.split_whitespace() .skip_while(|t| matches!(*t, "header" | "payload")) .take_while(|t| t.len() == 2 && t.bytes().all(|b| b.is_ascii_hexdigit())) .map(|t| u8::from_str_radix(t, 16).expect("hex")) .collect::>() }) .collect(); let mut frame = header.encode().to_vec(); frame.extend_from_slice(&p); assert_eq!(quoted, frame); } }