Cotton code
88 lines · 3.9 KB · RustRaw
//! What a receipt's bytes hold and never hold (design 3.2 and 3.4): the//! canonical form after the codec, the schema version inside, the op id//! outside, and the frozen vectors that make every device's bytes equal.use std::collections::BTreeMap;use cotton_store::canonical::{after_codec, canonical_json, decode, encode, Kind, Receipt};use cotton_store::migrate::SCHEMA_VERSION;use cotton_store::schema::decl::Codec;use serde_json::json;fn receipt() -> Receipt {    Receipt {        table: "cotton_todos".to_string(),        row_id: "01J0000000000000000000TODO".to_string(),        kind: Kind::Change,        stamp: "0000001700000000:0001:device:01J000000000000000000000AA".to_string(),        author: "device:01J000000000000000000000AA".to_string(),        actor: "owner:device:01J000000000000000000000AA".to_string(),        schema: SCHEMA_VERSION,        restamps: None,        erase: None,        undo: None,        fields: [            ("title".to_string(), json!("Buy milk")),            ("done".to_string(), json!(1)),        ]        .into_iter()        .collect::<BTreeMap<_, _>>(),    }}/// RULE: A receipt's bytes carry the schema version it was minted under and never its op id, so a re-keyed op id cannot break a signature and a forwarder cannot raise the version.#[test]fn receipt_bytes_hold_no_op_id_and_carry_the_schema_version() {    let bytes = encode(&receipt()).expect("encodes");    let text = std::str::from_utf8(&bytes).expect("utf-8");    for word in ["op_id", "opId", "\"id\"", "01H"] {        assert!(!text.contains(word), "an op id (or its key) is inside the bytes: {text}");    }    assert!(        text.contains(&format!(r#""schema":{SCHEMA_VERSION},"#)),        "the schema version is not inside the bytes: {text}"    );    let decoded = decode(&bytes).expect("decodes");    assert_eq!(decoded.schema, SCHEMA_VERSION);    assert_eq!(decoded, receipt());}/// RULE: The canonical form is one encoder with frozen vectors — keys sorted by byte order, no white space, NFC strings, shortest exact numbers — and encode(decode(x)) == x.#[test]fn canonical_encoding_frozen_vectors_and_roundtrip() {    let vectors: &[(serde_json::Value, &str)] = &[        (json!({"b": [1.0, 2.5, {"d": null, "c": "x"}], "a": true}), r#"{"a":true,"b":[1,2.5,{"c":"x","d":null}]}"#),        (json!("na\u{69}\u{308}ve"), "\"na\u{ef}ve\""),        (json!(1e21), "1e+21"),        (json!(0.000001), "0.000001"),        (json!(1e-7), "1e-7"),        (json!(-1.5), "-1.5"),    ];    for (value, expected) in vectors {        assert_eq!(&canonical_json(value).expect("encodes"), expected, "{value}");    }    let bytes = encode(&receipt()).expect("encodes");    let again = encode(&decode(&bytes).expect("decodes")).expect("re-encodes");    assert_eq!(again, bytes, "encode(decode(x)) must be x");    assert!(canonical_json(&json!(9007199254740993i64)).is_err(), "2^53 + 1 is refused, not rounded");}/// RULE: A receipt carries each field's value after the column's codec — what SQLite stores — so the row on every device shows exactly what the receipt says.#[test]fn receipt_is_the_canonical_form_after_the_codec() {    let mut fields = BTreeMap::new();    fields.insert("done".to_string(), after_codec(Codec::Bool, &json!(true)).expect("bool"));    fields.insert(        "due_at".to_string(),        after_codec(Codec::Timestamp, &json!("2026-08-23T14:30:00+05:30")).expect("timestamp"),    );    fields.insert("title".to_string(), after_codec(Codec::Text, &json!("caf\u{65}\u{301}")).expect("text"));    fields.insert("weight".to_string(), after_codec(Codec::Real, &json!(2.0)).expect("real"));    let mut r = receipt();    r.fields = fields;    let text = String::from_utf8(encode(&r).expect("encodes")).expect("utf-8");    assert!(        text.contains(r#""fields":{"done":1,"due_at":"2026-08-23T09:00:00.000Z","title":"café","weight":2}"#),        "{text}"    );}