//! 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::ValueasSqlValue;use serde_json::{Map, Number, ValueasJsonValue};use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization};usecrate::error::{Result, StoreError};usecrate::protocol::js;usecrate::schema::codecs::encode_value;usecrate::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.pubconst 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)]pubenumKind {Create,Change,Retract,}implKind {pubfn as_str(self) -> &'static str {matchself {Kind::Create => "create",Kind::Change => "change",Kind::Retract => "retract", } }pubfn parse(word: &str) -> Option<Kind> {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)]pubstructReceipt {pub table: String,pub row_id: String,pub kind: Kind,/// The HLC stamp, `<ms>:<counter>:<author>`.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<String, JsonValue>,/// 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<String>,/// On a retract that ERASES its row (design 6.2): why — the verb that/// erased it, or `source:<job>` 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<String>,/// 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<String>,}/// The receipt's canonical bytes.pubfn encode(receipt: &Receipt) -> Result<Vec<u8>> {letmut 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.ifletSome(erase) = &receipt.erase {if receipt.kind != Kind::Retract || erase.is_empty() {returnErr(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`.ifletSome(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`.ifletSome(undo) = &receipt.undo {if undo.is_empty() {returnErr(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.pubfn decode(bytes: &[u8]) -> Result<Receipt> {let value: JsonValue = serde_json::from_slice(bytes) .map_err(|e| StoreError::encode(format!("receipt bytes are not JSON: {e}")))?;letJsonValue::Object(object) = value else {returnErr(StoreError::encode("receipt bytes are not an object")); };let text = |name: &str| -> Result<String> {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"))?, _ => returnErr(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::<Result<BTreeMap<_, _>>>()?, _ => returnErr(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(_) => returnErr(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(_) => returnErr(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(_) => returnErr(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 {returnErr(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 {returnErr(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.pubfn canonical_json(value: &JsonValue) -> Result<String> {letmut 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`].pubfn canonical_value(value: &JsonValue) -> Result<JsonValue> {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::<Result<Vec<_>>>()?, ),JsonValue::Object(fields) => {let sorted: BTreeMap<String, JsonValue> = fields .iter() .map(|(k, v)| Ok((nfc(k), canonical_value(v)?))) .collect::<Result<_>>()?;letmut 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`.pubfn after_codec(codec: Codec, value: &JsonValue) -> Result<JsonValue> {// 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.ifletJsonValue::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(_) => {returnErr(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<String>| 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<Number> {ifletSome(i) = n.as_i64() {if i.abs() > EXACT_INTEGER_LIMIT {returnErr(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" ))); }returnOk(Number::from(i)); }if n.as_u64().is_some() {returnErr(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() {returnErr(StoreError::encode("a receipt cannot carry a non-finite number")); }if f.fract() == 0.0 && f.abs() <= EXACT_INTEGER_LIMIT as f64 {returnOk(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: &mutString, key: &str, value: &JsonValue) -> Result<()> { write_string(out, key)?; out.push(':'); write_value(out, value)}fn write_string(out: &mutString, 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();letmut 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: &mutString, 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)?;ifletSome(i) = n.as_i64() { out.push_str(&i.to_string()); } elseifletSome(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) => {letmut 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;