Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions scripts/tests/proof-gate-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ fail=0
fixture() {
local dir=$work/$1
mkdir -p "$dir/src" "$dir/verification"
cp src/jcs_core.rs src/ijson_core.rs "$dir/src/"
cp src/jcs_core.rs src/ijson_core.rs src/framing_core.rs "$dir/src/"
cp -r verification/creusot "$dir/verification/"
rm -rf "$dir/verification/creusot/target"
git -C "$dir" init -q
Expand All @@ -34,7 +34,7 @@ stub() {
chmod +x "$path"
echo "$path"
}
honest=$(stub honest 'if [[ $1 == false ]]; then echo "error: false_control_ordering: goal not proved"; echo "error: false_control_literal: goal not proved"; echo "error: false_control_noncharacter: goal not proved"; exit 1; fi')
honest=$(stub honest 'if [[ $1 == false ]]; then echo "error: false_control_ordering: goal not proved"; echo "error: false_control_literal: goal not proved"; echo "error: false_control_noncharacter: goal not proved"; echo "error: false_control_framing: goal not proved"; exit 1; fi')
accepts_all=$(stub accepts-all 'exit 0')
refuses_all=$(stub refuses-all 'echo "error: toolchain missing"; exit 1')
wrong_reason=$(stub wrong-reason 'if [[ $1 == false ]]; then echo "error: could not compile"; exit 1; fi')
Expand Down Expand Up @@ -71,7 +71,7 @@ receipt=$work/honest/target/receipt.json
commit=$(git -C "$work/honest" rev-parse HEAD)
digest=$(sha256sum "$work/honest/src/jcs_core.rs" | cut -d' ' -f1)
for want in "\"commit\":\"$commit\"" "\"src/jcs_core.rs\":\"$digest\"" '"verifier":"stub"' \
'"false_refused":["false_control_ordering","false_control_literal","false_control_noncharacter"]'; do
'"false_refused":["false_control_ordering","false_control_literal","false_control_noncharacter","false_control_framing"]'; do
grep -qF "$want" "$receipt" || { echo "FAIL receipt lacks $want" >&2; fail=1; }
done

Expand Down
151 changes: 151 additions & 0 deletions src/framing_core.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
//! SPDX-License-Identifier: MPL-2.0
//! Copyright (c) 2026 Hyperpolymath Estate
//!
//! First-party byte framing: canonical-form comparison and line splitting.
//
// Like `jcs_core.rs`, this file is compiled by this crate and, from the same
// bytes, by the Creusot harness in `verification/creusot`. It depends on
// nothing but `core`, and every contract is behind `cfg(creusot)`.
//
// STATUS: the contracts have NOT been run through Creusot; the rows are
// `OPEN` in `verification/PROOF-STATUS.adoc`. The behaviour is `TESTED` by
// the tests at the end of this file.

#[cfg(creusot)]
use creusot_std::prelude::*;

/// The line feed that ends an estate file and every JSON Lines record.
pub(crate) const LINE_FEED: u8 = b'\n';

/// Whether the first `n` bytes of `a` and of `b` are the same.
#[cfg_attr(creusot, check(terminates))]
#[cfg_attr(creusot, requires(n@ <= a@.len() && n@ <= b@.len()))]
#[cfg_attr(creusot, ensures(result == (forall<j> 0 <= j && j < n@ ==> a@[j] == b@[j])))]
fn prefix_equal(a: &[u8], b: &[u8], n: usize) -> bool {
let mut i = 0;
#[cfg_attr(creusot, variant(n@ - i@))]
#[cfg_attr(creusot, invariant(i@ <= n@))]
#[cfg_attr(creusot, invariant(forall<j> 0 <= j && j < i@ ==> a@[j] == b@[j]))]
while i < n {
if a[i] != b[i] {
return false;
}
i += 1;
}
true
}

/// Whether `input` is exactly `canonical`, or, when `allow_final_lf` is set,
/// `canonical` followed by exactly one line feed.
///
/// With `allow_final_lf` false and `canonical` the JCS bytes this is the
/// library profile; with `canonical` already ending in its line feed it is
/// the estate file profile; with `allow_final_lf` true it is the tolerant
/// rule `ijson-jcs check` has always applied.
#[cfg_attr(creusot, check(terminates))]
#[cfg_attr(creusot, ensures(result == (input@ == canonical@
|| (allow_final_lf && input@ == canonical@.snoc(0x0Au8)))))]
pub(crate) fn matches_canonical(input: &[u8], canonical: &[u8], allow_final_lf: bool) -> bool {
let n = canonical.len();
if input.len() == n {
return prefix_equal(input, canonical, n);
}
allow_final_lf
&& input.len() > n
&& input.len() - 1 == n
&& input[n] == LINE_FEED
&& prefix_equal(input, canonical, n)
}

/// The end of the line that starts at `start`: the index of the first line
/// feed at or after `start`, or the length of `input` if there is none.
#[cfg_attr(creusot, check(terminates))]
#[cfg_attr(creusot, requires(start@ <= input@.len()))]
#[cfg_attr(creusot, ensures(start@ <= result@ && result@ <= input@.len()))]
#[cfg_attr(creusot, ensures(forall<j> start@ <= j && j < result@ ==> input@[j]@ != 0x0A))]
#[cfg_attr(creusot, ensures(result@ < input@.len() ==> input@[result@]@ == 0x0A))]
pub(crate) fn line_end(input: &[u8], start: usize) -> usize {
let mut i = start;
#[cfg_attr(creusot, variant(input@.len() - i@))]
#[cfg_attr(creusot, invariant(start@ <= i@ && i@ <= input@.len()))]
#[cfg_attr(creusot, invariant(forall<j> start@ <= j && j < i@ ==> input@[j]@ != 0x0A))]
while i < input.len() {
if input[i] == LINE_FEED {
return i;
}
i += 1;
}
i
}

#[cfg(test)]
mod tests {
use super::*;

/// The rule this module replaces, as `profile.rs` wrote it.
fn reference_matches(input: &[u8], canonical: &[u8], allow_final_lf: bool) -> bool {
input == canonical
|| (allow_final_lf
&& input
.strip_suffix(&[LINE_FEED])
.is_some_and(|stripped| stripped == canonical))
}

/// Every byte string of length up to 5 over `{a, b, LF}`.
fn short_strings() -> Vec<Vec<u8>> {
let mut all = vec![Vec::new()];
let mut last = all.clone();
for _ in 0..5 {
let mut next = Vec::new();
for prefix in &last {
for byte in [b'a', b'b', LINE_FEED] {
let mut s = prefix.clone();
s.push(byte);
next.push(s);
}
}
all.extend(next.iter().cloned());
last = next;
}
assert_eq!(all.len(), 1 + 3 + 9 + 27 + 81 + 243);
all
}

/// All pairs of short strings, both settings: 364 x 364 x 2 comparisons
/// against the previous rule.
#[test]
fn matches_canonical_as_before() {
let strings = short_strings();
for input in &strings {
for canonical in &strings {
for allow in [false, true] {
assert_eq!(
matches_canonical(input, canonical, allow),
reference_matches(input, canonical, allow),
"{input:?} vs {canonical:?}, allow {allow}"
);
}
}
}
// Exactly one line feed: two are refused, and so is CR LF.
assert!(matches_canonical(b"{}\n", b"{}", true));
assert!(!matches_canonical(b"{}\n\n", b"{}", true));
assert!(!matches_canonical(b"{}\r\n", b"{}", true));
assert!(!matches_canonical(b"{}\n", b"{}", false));
assert!(!matches_canonical(b"", b"{}", true));
}

/// `line_end` finds the first line feed at or after every start.
#[test]
fn line_end_is_the_first_line_feed() {
for input in short_strings() {
for start in 0..=input.len() {
let want = input[start..]
.iter()
.position(|byte| *byte == LINE_FEED)
.map_or(input.len(), |offset| start + offset);
assert_eq!(line_end(&input, start), want, "{input:?} from {start}");
}
}
}
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
#![allow(clippy::needless_doctest_main)]

mod error;
mod framing_core;
mod ijson;
mod ijson_core;
mod jcs;
Expand Down
9 changes: 2 additions & 7 deletions src/profile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ use std::fmt;
use serde_json::Value;

use crate::error::{CanonicalizationError, IJsonError};
use crate::framing_core;
use crate::{JsonMode, parse_json_bytes, to_jcs};

/// The single byte the estate file profile appends to canonical bytes.
Expand Down Expand Up @@ -169,13 +170,7 @@ pub fn classify(input: &[u8], profile: CanonicalProfile) -> Result<Conformance,

/// Whether `input` is the canonical byte string, in a form `profile` allows.
fn is_canonical_form(input: &[u8], canonical: &[u8], profile: CanonicalProfile) -> bool {
if input == canonical {
return true;
}
profile == CanonicalProfile::Tolerant
&& input
.strip_suffix(&[FINAL_LF])
.is_some_and(|stripped| stripped == canonical)
framing_core::matches_canonical(input, canonical, profile == CanonicalProfile::Tolerant)
}

/// Library canonical bytes for JSON text: no trailing line feed.
Expand Down
66 changes: 55 additions & 11 deletions src/records.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
use std::fmt;

use crate::error::IJsonError;
use crate::framing_core;
use crate::profile::{Conformance, canonicalize_bytes};

/// Why a JSON Lines document is not a well-framed sequence of records.
Expand Down Expand Up @@ -94,18 +95,14 @@ impl<'a> Records<'a> {
/// framing *finding*, which [`classify_records`] reports as
/// [`Conformance::NotCanonical`], not a parse error.
pub fn parse(input: &'a [u8]) -> Result<Self, FramingError> {
// Each line runs from `start` to the next line feed, or to the end of
// the input when the last line has none.
let mut lines = Vec::new();
if !input.is_empty() {
let mut start = 0;
for (index, byte) in input.iter().enumerate() {
if *byte == b'\n' {
lines.push(&input[start..index]);
start = index + 1;
}
}
if start < input.len() {
lines.push(&input[start..]);
}
let mut start = 0;
while start < input.len() {
let end = framing_core::line_end(input, start);
lines.push(&input[start..end]);
start = end + 1;
}
for (index, line) in lines.iter().enumerate() {
if line.is_empty() {
Expand Down Expand Up @@ -269,4 +266,51 @@ mod tests {
assert!(crate::to_jcs(&value).is_ok());
}
}

/// The splitter agrees with the previous one (split at every line feed,
/// keep a final unterminated line) on every byte string of length up to
/// 7 over `{a, LF, CR}`: 3,280 inputs.
#[test]
fn splitting_is_unchanged() {
fn reference(input: &[u8]) -> Vec<&[u8]> {
let mut lines = Vec::new();
let mut start = 0;
for (index, byte) in input.iter().enumerate() {
if *byte == b'\n' {
lines.push(&input[start..index]);
start = index + 1;
}
}
if start < input.len() {
lines.push(&input[start..]);
}
lines
}
let mut inputs = vec![Vec::new()];
let mut last = inputs.clone();
for _ in 0..7 {
let mut next = Vec::new();
for prefix in &last {
for byte in *b"a\n\r" {
let mut s = prefix.clone();
s.push(byte);
next.push(s);
}
}
inputs.extend(next.iter().cloned());
last = next;
}
assert_eq!(inputs.len(), 3280);
for input in &inputs {
let want = reference(input);
match Records::parse(input) {
Ok(records) => assert_eq!(records.as_slice(), &want[..], "{input:?}"),
Err(FramingError::BlankLine { line }) => {
let first_blank = want.iter().position(|l| l.is_empty()).unwrap();
assert_eq!(line, first_blank + 1, "{input:?}");
}
Err(other) => panic!("{input:?}: {other}"),
}
}
}
}
69 changes: 69 additions & 0 deletions tests/integer_rendering.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2026 Hyperpolymath Estate
//
// PROOF-STATUS J-9, TESTED evidence. `to_jcs` writes a safe integer through
// a decimal fast path and every other number through ryu-js. For an integer
// in ±(2^53−1) the two must give the same bytes, because RFC 8785 defines
// the output by the ECMAScript algorithm that ryu-js implements.
//
// The same integer is canonicalised twice: as an integer `Value` (fast
// path) and as the equal double (ryu-js path).
//
// Bounds: exhaustive for |i| <= 2^17, boundary neighbourhoods, and a
// fixed-seed sample. The whole domain has about 1.8e16 values. A wider run
// of the same comparison is recorded in `verification/PROOF-STATUS.adoc`.

use ijson_jcs::to_jcs;
use serde_json::{Number, Value};

const SAFE_MAX: i64 = (1 << 53) - 1;

fn both_paths_agree(i: i64) {
let fast = to_jcs(&Value::Number(Number::from(i))).unwrap();
let double = to_jcs(&Value::Number(Number::from_f64(i as f64).unwrap())).unwrap();
assert_eq!(fast, double, "{i}");
assert_eq!(fast, i.to_string().into_bytes(), "{i}");
}

#[test]
fn small_integers_exhaustively() {
for i in -(1i64 << 17)..=(1i64 << 17) {
both_paths_agree(i);
}
}

#[test]
fn boundary_neighbourhoods() {
let mut centres = vec![0, SAFE_MAX];
centres.extend((0..=53).map(|e| 1i64 << e));
let mut power = 1i64;
while power <= SAFE_MAX {
centres.push(power);
power *= 10;
}
let mut checked = 0;
for centre in centres {
for sign in [1i64, -1] {
for delta in -8..=8 {
let i = sign * centre + delta;
if (-SAFE_MAX..=SAFE_MAX).contains(&i) {
both_paths_agree(i);
checked += 1;
}
}
}
}
assert!(checked > 2000, "{checked}");
}

#[test]
fn fixed_seed_sample_over_the_safe_range() {
let mut x = 0x9E37_79B9_7F4A_7C15u64;
for _ in 0..200_000 {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
let magnitude = ((x >> 11) as i64).min(SAFE_MAX);
both_paths_agree(if x & 1 == 0 { magnitude } else { -magnitude });
}
}
23 changes: 23 additions & 0 deletions tests/proven_mutation_kills.rs
Original file line number Diff line number Diff line change
Expand Up @@ -315,3 +315,26 @@ fn prefix_keys_and_reordered_keys_sort_together() {
);
assert_eq!(text(&to_jcs(&Value::Object(object)).unwrap()), want);
}

/// framing_core.rs `prefix_equal`: an input of the same length as its
/// canonical form, differing only in member order, is valid and not
/// canonical under every profile.
#[test]
fn same_length_reordering_is_not_canonical() {
use ijson_jcs::{CanonicalProfile, Conformance, classify};
for profile in [
CanonicalProfile::LibraryBytes,
CanonicalProfile::EstateFile,
CanonicalProfile::Tolerant,
] {
assert_eq!(
classify(br#"{"b":1,"a":2}"#, profile).unwrap(),
Conformance::NotCanonical,
"{profile}"
);
}
assert_eq!(
classify(b"{\"b\":1,\"a\":2}\n", CanonicalProfile::EstateFile).unwrap(),
Conformance::NotCanonical
);
}
Loading
Loading