-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcanonical.rs
More file actions
104 lines (95 loc) · 3.15 KB
/
canonical.rs
File metadata and controls
104 lines (95 loc) · 3.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
use serde::Serialize;
use serde_json::Value;
use sha2::{Digest, Sha256};
/// Serialize a JSON value into deterministic canonical bytes.
#[must_use]
pub fn canonical_json_bytes(value: &Value) -> Vec<u8> {
let mut out = Vec::new();
write_canonical(value, &mut out);
out
}
/// Serialize any serde value into canonical JSON bytes.
#[must_use]
pub fn canonical_bytes<T: Serialize>(value: &T) -> Vec<u8> {
let value = serde_json::to_value(value).expect("value must serialize to JSON");
canonical_json_bytes(&value)
}
/// Compute a SHA-256 digest over canonical JSON bytes.
#[must_use]
pub fn digest_canonical_json<T: Serialize>(value: &T) -> String {
let bytes = canonical_bytes(value);
let mut hasher = Sha256::new();
hasher.update(bytes);
hex::encode(hasher.finalize())
}
fn write_canonical(value: &Value, out: &mut Vec<u8>) {
match value {
Value::Null => out.extend_from_slice(b"null"),
Value::Bool(boolean) => out.extend_from_slice(if *boolean { b"true" } else { b"false" }),
Value::Number(number) => out.extend_from_slice(number.to_string().as_bytes()),
Value::String(string) => out.extend_from_slice(
serde_json::to_string(string)
.expect("string escaping must succeed")
.as_bytes(),
),
Value::Array(array) => {
out.push(b'[');
for (index, item) in array.iter().enumerate() {
if index > 0 {
out.push(b',');
}
write_canonical(item, out);
}
out.push(b']');
}
Value::Object(object) => {
out.push(b'{');
let mut keys: Vec<_> = object.keys().collect();
keys.sort();
for (index, key) in keys.iter().enumerate() {
if index > 0 {
out.push(b',');
}
out.extend_from_slice(
serde_json::to_string(key)
.expect("key escaping must succeed")
.as_bytes(),
);
out.push(b':');
write_canonical(&object[*key], out);
}
out.push(b'}');
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn canonical_object_key_order_independent() {
let first = json!({"b": 1, "a": 2});
let second = json!({"a": 2, "b": 1});
assert_eq!(canonical_json_bytes(&first), canonical_json_bytes(&second));
assert_eq!(
digest_canonical_json(&first),
digest_canonical_json(&second)
);
}
#[test]
fn canonical_nested_object_key_order_independent() {
let first = json!({
"outer": {"z": true, "a": [3, {"b": 2, "a": 1}]},
"name": "adapter"
});
let second = json!({
"name": "adapter",
"outer": {"a": [3, {"a": 1, "b": 2}], "z": true}
});
assert_eq!(canonical_json_bytes(&first), canonical_json_bytes(&second));
assert_eq!(
digest_canonical_json(&first),
digest_canonical_json(&second)
);
}
}