//! The canonical form of a receipt (design 3.2): one encoder, so that two //! devices that minted or received the same write hold the same bytes, and //! so that the bytes keys will sign later are the bytes stored today. //! //! A receipt is what one write leaves behind (3.1 rule 3): table, row, kind, //! stamp, author, actor, the schema version it was minted under, and each //! field it names with its value AFTER the column's codec. A RE-DATED receipt //! (slice 1's release pass, 5.2) also names the op id of the receipt it //! replaces, `restamps` — in the bytes, so the claim "this replaces that" is //! what keys signs, and no forwarder can add one to drop another's write. Every //! other receipt leaves the key out, so its bytes are what they always were. The op id is kept //! OUT of the bytes and beside them (`_writes.op_id`, the wire), so a re-keyed //! op id can never break a signature. //! //! The rules, each pinned by `canonical_encoding_frozen_vectors_and_roundtrip`: //! keys sorted by byte order; no white space; UTF-8; every string in NFC; //! numbers in their shortest exact form (an integral number has no `.0`, a //! fraction has the shortest digits that read back exactly, the way //! `JSON.stringify` writes one); an integer an `f64` cannot hold exactly is //! refused, so no reader on any platform rounds it. `encode(decode(x)) == x`, //! and `decode` refuses bytes that are not already canonical, so a receipt is //! never re-encoded: it is stored, carried and compared as minted. use std::collections::BTreeMap; use rusqlite::types::Value as SqlValue; use serde_json::{Map, Number, Value as JsonValue}; use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization}; use crate::error::{Result, StoreError}; use crate::protocol::js; use crate::schema::codecs::encode_value; use crate::schema::decl::Codec; /// The largest magnitude an `f64` holds exactly: 2^53. A receipt never /// carries an integer beyond it, because a reader that parses numbers as /// doubles (every JavaScript one) would round it and the files would differ. pub const EXACT_INTEGER_LIMIT: i64 = 1 << 53; /// What a write does to its row — the three words `_writes.kind` admits. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Kind { Create, Change, Retract, } impl Kind { pub fn as_str(self) -> &'static str { match self { Kind::Create => "create", Kind::Change => "change", Kind::Retract => "retract", } } pub fn parse(word: &str) -> Option { match word { "create" => Some(Kind::Create), "change" => Some(Kind::Change), "retract" => Some(Kind::Retract), _ => None, } } } /// One write, as minted. `fields` holds each named field's value after the /// column's codec (see [`after_codec`]); a retract names none. A per-key /// field of a JSON column is named `column.key` and holds the key's own /// value, canonical. #[derive(Debug, Clone, PartialEq)] pub struct Receipt { pub table: String, pub row_id: String, pub kind: Kind, /// The HLC stamp, `::`. pub stamp: String, pub author: String, pub actor: String, /// `SCHEMA_VERSION` at mint. In the bytes, so a forwarder cannot raise it. pub schema: u32, pub fields: BTreeMap, /// The op id of the receipt this one re-dates, or `None` for a receipt /// that replaces nothing — every receipt but the release pass's. pub restamps: Option, /// On a retract that ERASES its row (design 6.2): why — the verb that /// erased it, or `source:` for a source-erase. In the bytes, so every /// device applies the same erase and keeps the same `_gone` reason; `None` /// on every other receipt, whose bytes are what they always were. pub erase: Option, /// On every receipt of an UNDO act but its fact (slice 3b): the id of the /// `cotton_undos` fact the act wrote. Of two devices undoing one change, /// the fold keeps the act whose fact stands and parks the other's /// receipts (`crate::fact_hooks::undo_refusal`). `None` on every other /// receipt, whose bytes are what they always were. pub undo: Option, } /// The receipt's canonical bytes. pub fn encode(receipt: &Receipt) -> Result> { let mut out = String::with_capacity(256); out.push('{'); write_key_value(&mut out, "actor", &JsonValue::String(receipt.actor.clone()))?; out.push(','); write_key_value(&mut out, "author", &JsonValue::String(receipt.author.clone()))?; out.push(','); // Between `author` and `fields` in byte order; absent unless the receipt // is an erase, never `null`, and never on anything but a retract. if let Some(erase) = &receipt.erase { if receipt.kind != Kind::Retract || erase.is_empty() { return Err(StoreError::encode("only a retract erases, and an erase names why")); } write_key_value(&mut out, "erase", &JsonValue::String(erase.clone()))?; out.push(','); } write_string(&mut out, "fields")?; out.push(':'); out.push('{'); for (i, (name, value)) in receipt.fields.iter().enumerate() { if i > 0 { out.push(','); } write_key_value(&mut out, name, value)?; } out.push('}'); out.push(','); write_key_value(&mut out, "kind", &JsonValue::String(receipt.kind.as_str().to_string()))?; out.push(','); // Between `kind` and `row` in byte order; absent unless the receipt // re-dates one, never `null`. if let Some(restamps) = &receipt.restamps { write_key_value(&mut out, "restamps", &JsonValue::String(restamps.clone()))?; out.push(','); } write_key_value(&mut out, "row", &JsonValue::String(receipt.row_id.clone()))?; out.push(','); write_string(&mut out, "schema")?; out.push(':'); out.push_str(&receipt.schema.to_string()); out.push(','); write_key_value(&mut out, "stamp", &JsonValue::String(receipt.stamp.clone()))?; out.push(','); write_key_value(&mut out, "table", &JsonValue::String(receipt.table.clone()))?; // Last in byte order; absent unless the receipt is part of an undo, // never `null`. if let Some(undo) = &receipt.undo { if undo.is_empty() { return Err(StoreError::encode("a receipt of an undo names its fact")); } out.push(','); write_key_value(&mut out, "undo", &JsonValue::String(undo.clone()))?; } out.push('}'); Ok(out.into_bytes()) } /// The receipt the bytes carry. Refuses bytes that are not canonical — the /// one way a stored receipt could differ from a re-encoding of itself. pub fn decode(bytes: &[u8]) -> Result { let value: JsonValue = serde_json::from_slice(bytes) .map_err(|e| StoreError::encode(format!("receipt bytes are not JSON: {e}")))?; let JsonValue::Object(object) = value else { return Err(StoreError::encode("receipt bytes are not an object")); }; let text = |name: &str| -> Result { match object.get(name) { Some(JsonValue::String(s)) => Ok(s.clone()), Some(_) => Err(StoreError::encode(format!("receipt `{name}` is not a string"))), None => Err(StoreError::encode(format!("receipt has no `{name}`"))), } }; let kind_word = text("kind")?; let kind = Kind::parse(&kind_word) .ok_or_else(|| StoreError::encode(format!("receipt kind `{kind_word}` is not one of create, change, retract")))?; let schema = match object.get("schema") { Some(JsonValue::Number(n)) => n .as_u64() .and_then(|n| u32::try_from(n).ok()) .ok_or_else(|| StoreError::encode("receipt `schema` is not a schema version"))?, _ => return Err(StoreError::encode("receipt has no `schema`")), }; let fields = match object.get("fields") { Some(JsonValue::Object(fields)) => fields .iter() .map(|(name, value)| Ok((name.clone(), canonical_value(value)?))) .collect::>>()?, _ => return Err(StoreError::encode("receipt has no `fields` object")), }; let restamps = match object.get("restamps") { None => None, Some(JsonValue::String(old)) if !old.is_empty() => Some(old.clone()), Some(_) => return Err(StoreError::encode("receipt `restamps` is not an op id")), }; let erase = match object.get("erase") { None => None, Some(JsonValue::String(why)) if !why.is_empty() && kind == Kind::Retract => Some(why.clone()), Some(_) => return Err(StoreError::encode("receipt `erase` is not the reason of a retract")), }; let undo = match object.get("undo") { None => None, Some(JsonValue::String(fact)) if !fact.is_empty() => Some(fact.clone()), Some(_) => return Err(StoreError::encode("receipt `undo` is not the fact of an undo")), }; let expected = 8 + usize::from(restamps.is_some()) + usize::from(erase.is_some()) + usize::from(undo.is_some()); if object.len() != expected { return Err(StoreError::encode(format!( "receipt carries {} keys, not the {expected} of the canonical form", object.len() ))); } let receipt = Receipt { table: text("table")?, row_id: text("row")?, kind, stamp: text("stamp")?, author: text("author")?, actor: text("actor")?, schema, fields, restamps, erase, undo, }; if encode(&receipt)? != bytes { return Err(StoreError::encode( "receipt bytes are not in the canonical form — a receipt is stored as minted and never rewritten", )); } Ok(receipt) } /// `canonical_json` as a string: any JSON value, keys sorted, strings in NFC, /// numbers shortest and exact. pub fn canonical_json(value: &JsonValue) -> Result { let mut out = String::new(); write_value(&mut out, value)?; Ok(out) } /// The value as the canonical form reads it: strings in NFC, objects with /// their keys sorted, integers checked against [`EXACT_INTEGER_LIMIT`]. pub fn canonical_value(value: &JsonValue) -> Result { Ok(match value { JsonValue::Null | JsonValue::Bool(_) => value.clone(), JsonValue::Number(n) => JsonValue::Number(canonical_number(n)?), JsonValue::String(s) => JsonValue::String(nfc(s)), JsonValue::Array(items) => JsonValue::Array( items.iter().map(canonical_value).collect::>>()?, ), JsonValue::Object(fields) => { let sorted: BTreeMap = fields .iter() .map(|(k, v)| Ok((nfc(k), canonical_value(v)?))) .collect::>()?; let mut map = Map::with_capacity(sorted.len()); for (k, v) in sorted { map.insert(k, v); } JsonValue::Object(map) } }) } /// A field's value after the column's codec, as the receipt carries it: what /// SQLite would store, read back as JSON. Text is a string (in NFC, so the /// row shows what the receipt says), an integer or a real is a number, a /// boolean is `0` or `1`, a timestamp is its UTC `Z` form, a JSON column is /// its stored text, and `null` is `null`. pub fn after_codec(codec: Codec, value: &JsonValue) -> Result { // The codecs read a number as an f64, which would ROUND an integer // beyond 2^53 before anything here could see it; so the raw number is // checked first. if let JsonValue::Number(n) = value { canonical_number(n)?; } Ok(match encode_value(codec, value)? { SqlValue::Null => JsonValue::Null, SqlValue::Integer(i) => JsonValue::Number(canonical_number(&Number::from(i))?), SqlValue::Real(f) => JsonValue::Number(canonical_number( &Number::from_f64(f).ok_or_else(|| StoreError::encode("a receipt cannot carry a non-finite number"))?, )?), SqlValue::Text(s) => JsonValue::String(nfc(&s)), SqlValue::Blob(_) => { return Err(StoreError::encode("a receipt cannot carry a blob")); } }) } /// Would [`decode`] of this receipt's [`encode`] give back this very struct, /// and take it? True when every string the encode would normalise is in NFC /// already and no optional key is empty — so a minted receipt kept beside its /// bytes (`fold::keep_minted`) is what decoding them would read. Its field /// values are canonical by construction (`after_codec`, `canonical_value`). pub(crate) fn reads_back_as_itself(receipt: &Receipt) -> bool { let normal = |s: &str| is_normal(s); let present = |o: &Option| o.as_deref().is_none_or(|s| !s.is_empty()); [&receipt.table, &receipt.row_id, &receipt.stamp, &receipt.author, &receipt.actor].iter().all(|s| normal(s)) && receipt.fields.keys().all(|name| normal(name)) && present(&receipt.restamps) && present(&receipt.erase) && present(&receipt.undo) && (receipt.erase.is_none() || receipt.kind == Kind::Retract) } fn nfc(s: &str) -> String { if is_normal(s) { s.to_string() } else { s.nfc().collect() } } /// Is `s` in NFC already, by the quick check? ASCII always is, and is told /// at once (an asset's base64 runs to megabytes). fn is_normal(s: &str) -> bool { s.is_ascii() || matches!(is_nfc_quick(s.chars()), IsNormalized::Yes) } /// An integral number as an integer, anything else as the shortest `f64`; /// refused beyond what an `f64` holds exactly. fn canonical_number(n: &Number) -> Result { if let Some(i) = n.as_i64() { if i.abs() > EXACT_INTEGER_LIMIT { return Err(StoreError::encode(format!( "{i} is beyond the integer an f64 holds exactly (±2^53) — a receipt refuses it rather than let a reader round it" ))); } return Ok(Number::from(i)); } if n.as_u64().is_some() { return Err(StoreError::encode(format!( "{n} is beyond the integer an f64 holds exactly (±2^53) — a receipt refuses it rather than let a reader round it" ))); } let f = n .as_f64() .ok_or_else(|| StoreError::encode("a receipt cannot carry a non-finite number"))?; if !f.is_finite() { return Err(StoreError::encode("a receipt cannot carry a non-finite number")); } if f.fract() == 0.0 && f.abs() <= EXACT_INTEGER_LIMIT as f64 { return Ok(Number::from(f as i64)); } Number::from_f64(f).ok_or_else(|| StoreError::encode("a receipt cannot carry a non-finite number")) } fn write_key_value(out: &mut String, key: &str, value: &JsonValue) -> Result<()> { write_string(out, key)?; out.push(':'); write_value(out, value) } fn write_string(out: &mut String, s: &str) -> Result<()> { // Already in NFC (nearly every string): written as it is, never copied. let normalized: std::borrow::Cow<'_, str> = if is_normal(s) { std::borrow::Cow::Borrowed(s) } else { std::borrow::Cow::Owned(s.nfc().collect()) }; out.reserve(normalized.len() + 2); out.push('"'); // Runs of bytes that need no escape are copied whole: every escape is an // ASCII byte, and no byte of a multi-byte character is one. let bytes = normalized.as_bytes(); let mut run = 0; for (at, &byte) in bytes.iter().enumerate() { let escape = match byte { b'"' => "\\\"", b'\\' => "\\\\", 0x08 => "\\b", 0x0c => "\\f", b'\n' => "\\n", b'\r' => "\\r", b'\t' => "\\t", b if b < 0x20 => "", _ => continue, }; out.push_str(&normalized[run..at]); if escape.is_empty() { out.push_str(&format!("\\u{:04x}", byte)); } else { out.push_str(escape); } run = at + 1; } out.push_str(&normalized[run..]); out.push('"'); Ok(()) } fn write_value(out: &mut String, value: &JsonValue) -> Result<()> { match value { JsonValue::Null => out.push_str("null"), JsonValue::Bool(true) => out.push_str("true"), JsonValue::Bool(false) => out.push_str("false"), JsonValue::Number(n) => { let n = canonical_number(n)?; if let Some(i) = n.as_i64() { out.push_str(&i.to_string()); } else if let Some(f) = n.as_f64() { out.push_str(&js::number_to_string(f)); } } JsonValue::String(s) => write_string(out, s)?, JsonValue::Array(items) => { out.push('['); for (i, item) in items.iter().enumerate() { if i > 0 { out.push(','); } write_value(out, item)?; } out.push(']'); } JsonValue::Object(fields) => { let mut sorted: Vec<(String, &JsonValue)> = fields.iter().map(|(k, v)| (nfc(k), v)).collect(); sorted.sort_by(|a, b| a.0.as_bytes().cmp(b.0.as_bytes())); out.push('{'); for (i, (key, val)) in sorted.iter().enumerate() { if i > 0 { out.push(','); } write_string(out, key)?; out.push(':'); write_value(out, val)?; } out.push('}'); } } Ok(()) } #[cfg(test)] #[path = "canonical_tests.rs"] mod canonical_tests;