node_app_replica/
digest.rs1use std::fmt::Write as _;
11
12use serde_json::Value;
13use sha2::{Digest, Sha256};
14
15use crate::wire::Row;
16
17pub fn write_canonical(value: &Value, out: &mut String) {
19 match value {
20 Value::Null => out.push_str("null"),
21 Value::Bool(true) => out.push_str("true"),
22 Value::Bool(false) => out.push_str("false"),
23 Value::Number(number) => {
24 let _ = write!(out, "{number}");
26 }
27 Value::String(text) => write_json_string(text, out),
28 Value::Array(items) => {
29 out.push('[');
30 for (index, item) in items.iter().enumerate() {
31 if index > 0 {
32 out.push(',');
33 }
34 write_canonical(item, out);
35 }
36 out.push(']');
37 }
38 Value::Object(object) => {
39 let sorted = object.keys().zip(object.keys().skip(1)).all(|(a, b)| a < b);
42 out.push('{');
43 if sorted {
44 write_entries(object.iter(), out);
45 } else {
46 let mut entries: Vec<(&String, &Value)> = object.iter().collect();
47 entries.sort_by(|a, b| a.0.cmp(b.0));
48 write_entries(entries.into_iter(), out);
49 }
50 out.push('}');
51 }
52 }
53}
54
55fn write_entries<'v>(entries: impl Iterator<Item = (&'v String, &'v Value)>, out: &mut String) {
56 for (index, (key, item)) in entries.enumerate() {
57 if index > 0 {
58 out.push(',');
59 }
60 write_json_string(key, out);
61 out.push(':');
62 write_canonical(item, out);
63 }
64}
65
66pub fn canonical_json(value: &Value) -> String {
68 let mut out = String::new();
69 write_canonical(value, &mut out);
70 out
71}
72
73pub fn canonical_len(value: &Value) -> usize {
75 match value {
76 Value::Null => 4,
77 Value::Bool(true) => 4,
78 Value::Bool(false) => 5,
79 Value::Number(number) => number.to_string().len(),
80 Value::String(text) => json_len_of_str(text),
81 Value::Array(items) => {
82 2 + items.iter().map(canonical_len).sum::<usize>() + items.len().saturating_sub(1)
83 }
84 Value::Object(object) => {
85 2 + object
86 .iter()
87 .map(|(key, item)| json_len_of_str(key) + 1 + canonical_len(item))
88 .sum::<usize>()
89 + object.len().saturating_sub(1)
90 }
91 }
92}
93
94fn write_json_string(text: &str, out: &mut String) {
98 out.push('"');
99 if !text.bytes().any(|b| b == b'"' || b == b'\\' || b < 0x20) {
100 out.push_str(text);
101 out.push('"');
102 return;
103 }
104 for ch in text.chars() {
105 match ch {
106 '"' => out.push_str("\\\""),
107 '\\' => out.push_str("\\\\"),
108 '\u{08}' => out.push_str("\\b"),
109 '\u{0c}' => out.push_str("\\f"),
110 '\n' => out.push_str("\\n"),
111 '\r' => out.push_str("\\r"),
112 '\t' => out.push_str("\\t"),
113 ch if (ch as u32) < 0x20 => {
114 out.push_str("\\u00");
115 out.push(hex_digit((ch as u32 >> 4) as u8));
116 out.push(hex_digit((ch as u32 & 0xf) as u8));
117 }
118 ch => out.push(ch),
119 }
120 }
121 out.push('"');
122}
123
124pub(crate) fn json_len_of_str(text: &str) -> usize {
126 2 + text
127 .chars()
128 .map(|ch| match ch {
129 '"' | '\\' | '\u{08}' | '\u{0c}' | '\n' | '\r' | '\t' => 2,
130 ch if (ch as u32) < 0x20 => 6,
131 ch => ch.len_utf8(),
132 })
133 .sum::<usize>()
134}
135
136fn hex_digit(nibble: u8) -> char {
137 char::from(b"0123456789abcdef"[usize::from(nibble & 0xf)])
138}
139
140pub fn row_digest(row: &Row) -> String {
142 digest_and_value_len(row).0
143}
144
145pub(crate) fn digest_and_value_len(row: &Row) -> (String, usize) {
148 let mut canonical = String::with_capacity(256);
149 canonical.push('[');
150 write_canonical(&row.value, &mut canonical);
151 let value_len = canonical.len() - 1;
152 let _ = write!(canonical, ",{},", row.ord);
153 write_json_string(&row.part, &mut canonical);
154 canonical.push(']');
155 let hash = Sha256::digest(canonical.as_bytes());
156 let mut out = String::with_capacity(32);
157 for byte in hash.iter().take(16) {
158 out.push(hex_digit(byte >> 4));
159 out.push(hex_digit(*byte));
160 }
161 (out, value_len)
162}
163
164#[cfg(test)]
165mod tests {
166 use super::*;
167 use serde_json::json;
168
169 #[test]
170 fn canonical_json_sorts_keys_and_matches_compact_serde_for_strings() {
171 let value = json!({"b": [1, 2.5, "x\"\\\n\u{1}\u{7f}é"], "a": {"d": null, "c": true}});
172 assert_eq!(
173 canonical_json(&value),
174 "{\"a\":{\"c\":true,\"d\":null},\"b\":[1,2.5,\"x\\\"\\\\\\n\\u0001\u{7f}é\"]}"
175 );
176 let text = Value::String("x\"\\\n\u{1}\u{8}\u{c}\t\r\u{1f}\u{7f}é".into());
178 assert_eq!(canonical_json(&text), serde_json::to_string(&text).unwrap());
179 assert_eq!(canonical_len(&value), canonical_json(&value).len());
180 assert_eq!(canonical_len(&text), canonical_json(&text).len());
181 }
182
183 #[test]
184 fn digest_ignores_key_order_and_sees_value_ord_and_part() {
185 let a = Row::new("k", json!({"x": 1, "y": 2}));
186 let b = Row::new("k", serde_json::from_str("{\"y\":2,\"x\":1}").unwrap());
187 assert_eq!(row_digest(&a), row_digest(&b));
188 assert_eq!(row_digest(&a).len(), 32);
189 assert_ne!(row_digest(&a), row_digest(&a.clone().with_ord(1)));
190 assert_ne!(row_digest(&a), row_digest(&a.clone().with_part("p")));
191 assert_ne!(
192 row_digest(&a),
193 row_digest(&Row::new("k", json!({"x": 1, "y": 3})))
194 );
195 assert_eq!(
197 row_digest(&a),
198 row_digest(&Row::new("other", a.value.clone()))
199 );
200 }
201}