iscc-lib 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/Cargo.lock +2027 -0
- data/Cargo.toml +17 -6
- data/README.md +6 -3
- data/core/CLAUDE.md +177 -0
- data/core/Cargo.lock +959 -0
- data/core/Cargo.toml +131 -0
- data/core/README.md +84 -0
- data/core/benches/benchmarks.rs +294 -0
- data/core/benches/iai_benches.rs +171 -0
- data/core/src/cdc.rs +488 -0
- data/core/src/codec.rs +2074 -0
- data/core/src/conformance.rs +754 -0
- data/core/src/dct.rs +148 -0
- data/core/src/lib.rs +2693 -0
- data/core/src/minhash.rs +286 -0
- data/core/src/simhash.rs +356 -0
- data/core/src/streaming.rs +688 -0
- data/core/src/types.rs +116 -0
- data/core/src/utils.rs +361 -0
- data/core/src/wtahash.rs +389 -0
- data/core/src/xxh32.rs +134 -0
- data/core/tests/codec_clean.rs +247 -0
- data/core/tests/data.json +645 -0
- data/core/tests/test_algorithm_primitives.rs +303 -0
- data/core/tests/test_seq.rs +565 -0
- data/core/tests/test_strict_base32.rs +158 -0
- data/core/tests/test_text_utils.rs +157 -0
- data/lib/iscc_lib/version.rb +1 -1
- data/src/lib.rs +108 -25
- metadata +43 -4
data/core/src/lib.rs
ADDED
|
@@ -0,0 +1,2693 @@
|
|
|
1
|
+
//! High-performance Rust implementation of ISO 24138:2024 (ISCC).
|
|
2
|
+
//!
|
|
3
|
+
//! This crate provides the core ISCC algorithm implementations, designed to be
|
|
4
|
+
//! compatible with the `iscc-core` Python reference implementation. The Tier 1
|
|
5
|
+
//! API is the set of symbols defined or re-exported at the crate root: the
|
|
6
|
+
//! `gen_*` functions, utilities, codec functions, constants, `DataHasher`,
|
|
7
|
+
//! `InstanceHasher` and `conformance_selftest`, with their result structs and
|
|
8
|
+
//! `IsccError`. The `codec` module and `streaming::SumHasher` are Tier 2:
|
|
9
|
+
//! public Rust API that is not bound in every language.
|
|
10
|
+
|
|
11
|
+
pub(crate) mod cdc;
|
|
12
|
+
pub mod codec;
|
|
13
|
+
pub(crate) mod conformance;
|
|
14
|
+
pub(crate) mod dct;
|
|
15
|
+
pub(crate) mod minhash;
|
|
16
|
+
pub(crate) mod simhash;
|
|
17
|
+
pub mod streaming;
|
|
18
|
+
pub mod types;
|
|
19
|
+
pub(crate) mod utils;
|
|
20
|
+
pub(crate) mod wtahash;
|
|
21
|
+
pub(crate) mod xxh32;
|
|
22
|
+
|
|
23
|
+
pub use cdc::alg_cdc_chunks;
|
|
24
|
+
pub use codec::encode_base64;
|
|
25
|
+
pub use codec::iscc_decompose;
|
|
26
|
+
pub use codec::{decode_seq, encode_seq};
|
|
27
|
+
pub use conformance::conformance_selftest;
|
|
28
|
+
pub use minhash::alg_minhash_256;
|
|
29
|
+
pub use simhash::{alg_simhash, sliding_window};
|
|
30
|
+
pub use streaming::{DataHasher, InstanceHasher};
|
|
31
|
+
pub use types::*;
|
|
32
|
+
#[cfg(feature = "text-processing")]
|
|
33
|
+
pub use utils::{text_clean, text_collapse};
|
|
34
|
+
pub use utils::{text_remove_newlines, text_trim};
|
|
35
|
+
|
|
36
|
+
/// Max UTF-8 byte length for name metadata trimming.
|
|
37
|
+
#[cfg(feature = "meta-code")]
|
|
38
|
+
pub const META_TRIM_NAME: usize = 128;
|
|
39
|
+
|
|
40
|
+
/// Max UTF-8 byte length for description metadata trimming.
|
|
41
|
+
#[cfg(feature = "meta-code")]
|
|
42
|
+
pub const META_TRIM_DESCRIPTION: usize = 4096;
|
|
43
|
+
|
|
44
|
+
/// Max decoded payload size in bytes for the meta element.
|
|
45
|
+
#[cfg(feature = "meta-code")]
|
|
46
|
+
pub const META_TRIM_META: usize = 128_000;
|
|
47
|
+
|
|
48
|
+
/// Buffer size in bytes for streaming file reads (4 MB).
|
|
49
|
+
pub const IO_READ_SIZE: usize = 4_194_304;
|
|
50
|
+
|
|
51
|
+
/// Character n-gram width for text content features.
|
|
52
|
+
pub const TEXT_NGRAM_SIZE: usize = 13;
|
|
53
|
+
|
|
54
|
+
/// Error type for ISCC operations.
|
|
55
|
+
#[derive(Debug, thiserror::Error)]
|
|
56
|
+
pub enum IsccError {
|
|
57
|
+
/// Input data is invalid.
|
|
58
|
+
#[error("invalid input: {0}")]
|
|
59
|
+
InvalidInput(String),
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/// Result type alias for ISCC operations.
|
|
63
|
+
pub type IsccResult<T> = Result<T, IsccError>;
|
|
64
|
+
|
|
65
|
+
/// Interleave two 32-byte SimHash digests in 4-byte chunks.
|
|
66
|
+
///
|
|
67
|
+
/// Takes the first 16 bytes of each digest and interleaves them into
|
|
68
|
+
/// a 32-byte result: 4 bytes from `a`, 4 bytes from `b`, alternating
|
|
69
|
+
/// for 4 rounds (8 chunks total).
|
|
70
|
+
#[cfg(feature = "meta-code")]
|
|
71
|
+
fn interleave_digests(a: &[u8], b: &[u8]) -> Vec<u8> {
|
|
72
|
+
let mut result = vec![0u8; 32];
|
|
73
|
+
for chunk in 0..4 {
|
|
74
|
+
let src = chunk * 4;
|
|
75
|
+
let dst_a = chunk * 8;
|
|
76
|
+
let dst_b = chunk * 8 + 4;
|
|
77
|
+
result[dst_a..dst_a + 4].copy_from_slice(&a[src..src + 4]);
|
|
78
|
+
result[dst_b..dst_b + 4].copy_from_slice(&b[src..src + 4]);
|
|
79
|
+
}
|
|
80
|
+
result
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/// Compute a SimHash digest from the name text for meta hashing.
|
|
84
|
+
///
|
|
85
|
+
/// Applies `text_collapse`, generates width-3 sliding window n-grams,
|
|
86
|
+
/// hashes each with BLAKE3, and produces a SimHash.
|
|
87
|
+
#[cfg(feature = "meta-code")]
|
|
88
|
+
fn meta_name_simhash(name: &str) -> Vec<u8> {
|
|
89
|
+
let collapsed_name = utils::text_collapse(name);
|
|
90
|
+
let name_ngrams = simhash::sliding_window_strs(&collapsed_name, 3);
|
|
91
|
+
let name_hashes: Vec<[u8; 32]> = name_ngrams
|
|
92
|
+
.iter()
|
|
93
|
+
.map(|ng| *blake3::hash(ng.as_bytes()).as_bytes())
|
|
94
|
+
.collect();
|
|
95
|
+
simhash::alg_simhash_inner(&name_hashes)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/// Compute a similarity-preserving 256-bit hash from metadata text.
|
|
99
|
+
///
|
|
100
|
+
/// Produces a SimHash digest from `name` n-grams. When `extra` is provided,
|
|
101
|
+
/// interleaves the name and extra SimHash digests in 4-byte chunks.
|
|
102
|
+
#[cfg(feature = "meta-code")]
|
|
103
|
+
fn soft_hash_meta_v0(name: &str, extra: Option<&str>) -> Vec<u8> {
|
|
104
|
+
let name_simhash = meta_name_simhash(name);
|
|
105
|
+
|
|
106
|
+
match extra {
|
|
107
|
+
None | Some("") => name_simhash,
|
|
108
|
+
Some(extra_str) => {
|
|
109
|
+
let collapsed_extra = utils::text_collapse(extra_str);
|
|
110
|
+
let extra_ngrams = simhash::sliding_window_strs(&collapsed_extra, 3);
|
|
111
|
+
let extra_hashes: Vec<[u8; 32]> = extra_ngrams
|
|
112
|
+
.iter()
|
|
113
|
+
.map(|ng| *blake3::hash(ng.as_bytes()).as_bytes())
|
|
114
|
+
.collect();
|
|
115
|
+
let extra_simhash = simhash::alg_simhash_inner(&extra_hashes);
|
|
116
|
+
|
|
117
|
+
interleave_digests(&name_simhash, &extra_simhash)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/// Compute a similarity-preserving 256-bit hash from name text and raw bytes.
|
|
123
|
+
///
|
|
124
|
+
/// Like `soft_hash_meta_v0` but the extra data is raw bytes instead of text.
|
|
125
|
+
/// Uses width-4 byte n-grams (no `text_collapse`) for the bytes path,
|
|
126
|
+
/// and interleaves name/bytes SimHash digests in 4-byte chunks.
|
|
127
|
+
#[cfg(feature = "meta-code")]
|
|
128
|
+
fn soft_hash_meta_v0_with_bytes(name: &str, extra: &[u8]) -> Vec<u8> {
|
|
129
|
+
let name_simhash = meta_name_simhash(name);
|
|
130
|
+
|
|
131
|
+
if extra.is_empty() {
|
|
132
|
+
return name_simhash;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
let byte_ngrams = simhash::sliding_window_bytes(extra, 4);
|
|
136
|
+
let byte_hashes: Vec<[u8; 32]> = byte_ngrams
|
|
137
|
+
.iter()
|
|
138
|
+
.map(|ng| *blake3::hash(ng).as_bytes())
|
|
139
|
+
.collect();
|
|
140
|
+
let byte_simhash = simhash::alg_simhash_inner(&byte_hashes);
|
|
141
|
+
|
|
142
|
+
interleave_digests(&name_simhash, &byte_simhash)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/// Decode a Data-URL's base64 payload.
|
|
146
|
+
///
|
|
147
|
+
/// Expects a string starting with `"data:"`. Splits on the first `,` and
|
|
148
|
+
/// decodes the remainder as standard base64. Returns `InvalidInput` on
|
|
149
|
+
/// missing comma or invalid base64.
|
|
150
|
+
#[cfg(feature = "meta-code")]
|
|
151
|
+
fn decode_data_url(data_url: &str) -> IsccResult<Vec<u8>> {
|
|
152
|
+
let payload_b64 = data_url
|
|
153
|
+
.split_once(',')
|
|
154
|
+
.map(|(_, b64)| b64)
|
|
155
|
+
.ok_or_else(|| IsccError::InvalidInput("Data-URL missing comma separator".into()))?;
|
|
156
|
+
data_encoding::BASE64
|
|
157
|
+
.decode(payload_b64.as_bytes())
|
|
158
|
+
.map_err(|e| IsccError::InvalidInput(format!("invalid base64 in Data-URL: {e}")))
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/// JSON metadata parsed once and re-serialized to RFC 8785 (JCS) canonical bytes.
|
|
162
|
+
#[cfg(feature = "meta-code")]
|
|
163
|
+
struct CanonicalJson {
|
|
164
|
+
/// JCS canonical serialization of the parsed JSON.
|
|
165
|
+
bytes: Vec<u8>,
|
|
166
|
+
/// Whether the top-level JSON object has an `@context` key (JSON-LD).
|
|
167
|
+
is_json_ld: bool,
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/// Parse a JSON string and canonicalize it per RFC 8785 (JCS).
|
|
171
|
+
///
|
|
172
|
+
/// `parse_error_prefix` is prepended to the parser's error message, so each
|
|
173
|
+
/// caller keeps its own error text. Canonicalization errors read
|
|
174
|
+
/// `JSON canonicalization failed: …` for every caller.
|
|
175
|
+
#[cfg(feature = "meta-code")]
|
|
176
|
+
fn canonicalize_json(json: &str, parse_error_prefix: &str) -> IsccResult<CanonicalJson> {
|
|
177
|
+
let parsed: serde_json::Value = serde_json::from_str(json)
|
|
178
|
+
.map_err(|e| IsccError::InvalidInput(format!("{parse_error_prefix}: {e}")))?;
|
|
179
|
+
let mut bytes = Vec::new();
|
|
180
|
+
serde_json_canonicalizer::to_writer(&parsed, &mut bytes)
|
|
181
|
+
.map_err(|e| IsccError::InvalidInput(format!("JSON canonicalization failed: {e}")))?;
|
|
182
|
+
Ok(CanonicalJson {
|
|
183
|
+
bytes,
|
|
184
|
+
is_json_ld: parsed.get("@context").is_some(),
|
|
185
|
+
})
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/// Build a Data-URL from canonical JSON.
|
|
189
|
+
///
|
|
190
|
+
/// Uses `application/ld+json` media type if the JSON has an `@context` key,
|
|
191
|
+
/// otherwise `application/json`. Encodes payload as standard base64 with padding.
|
|
192
|
+
#[cfg(feature = "meta-code")]
|
|
193
|
+
fn build_meta_data_url(json: &CanonicalJson) -> String {
|
|
194
|
+
let media_type = if json.is_json_ld {
|
|
195
|
+
"application/ld+json"
|
|
196
|
+
} else {
|
|
197
|
+
"application/json"
|
|
198
|
+
};
|
|
199
|
+
let b64 = data_encoding::BASE64.encode(&json.bytes);
|
|
200
|
+
format!("data:{media_type};base64,{b64}")
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/// Encode a raw digest into an ISCC unit string.
|
|
204
|
+
///
|
|
205
|
+
/// Takes integer type identifiers (matching `MainType`, `SubType`, `Version` enum values)
|
|
206
|
+
/// and a raw digest, returns a base32-encoded ISCC unit string.
|
|
207
|
+
///
|
|
208
|
+
/// # Errors
|
|
209
|
+
///
|
|
210
|
+
/// Returns `IsccError::InvalidInput` if enum values are out of range, if `mtype` is
|
|
211
|
+
/// `MainType::Iscc` (5), if `digest.len() < bit_length / 8`, or if `bit_length` is
|
|
212
|
+
/// not valid for `mtype` (for Meta through Flake: a multiple of 32 from 32 to 256;
|
|
213
|
+
/// for ID: 64, 72, 80 or 96).
|
|
214
|
+
pub fn encode_component(
|
|
215
|
+
mtype: u8,
|
|
216
|
+
stype: u8,
|
|
217
|
+
version: u8,
|
|
218
|
+
bit_length: u32,
|
|
219
|
+
digest: &[u8],
|
|
220
|
+
) -> IsccResult<String> {
|
|
221
|
+
let mt = codec::MainType::try_from(mtype)?;
|
|
222
|
+
let st = codec::SubType::try_from(stype)?;
|
|
223
|
+
let vs = codec::Version::try_from(version)?;
|
|
224
|
+
let needed = (bit_length / 8) as usize;
|
|
225
|
+
if digest.len() < needed {
|
|
226
|
+
return Err(IsccError::InvalidInput(format!(
|
|
227
|
+
"digest length {} < bit_length/8 ({})",
|
|
228
|
+
digest.len(),
|
|
229
|
+
needed
|
|
230
|
+
)));
|
|
231
|
+
}
|
|
232
|
+
codec::encode_component(mt, st, vs, bit_length, digest)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/// Normalize an ISCC to its canonical shortest form, without the `"ISCC:"` prefix.
|
|
236
|
+
///
|
|
237
|
+
/// Mirrors `iscc_core.codec.iscc_normalize`: decomposes the input into ISCC-UNITs
|
|
238
|
+
/// and recomposes them into a single ISCC-CODE when two or more units are present,
|
|
239
|
+
/// otherwise returns the sole unit unchanged. This is what lets a concatenated unit
|
|
240
|
+
/// sequence and a composite ISCC-CODE normalize to the same canonical string.
|
|
241
|
+
///
|
|
242
|
+
/// Multiformat (multibase-prefixed) inputs are not supported here; the reference
|
|
243
|
+
/// handles them in `normalize_multiformat` before this step.
|
|
244
|
+
fn iscc_normalize(iscc: &str) -> IsccResult<String> {
|
|
245
|
+
// Wide-mode detection reads the *original* header, before decomposition.
|
|
246
|
+
let clean = codec::iscc_clean(iscc)?;
|
|
247
|
+
|
|
248
|
+
// Validate the two-character prefix against the reference allow-list before
|
|
249
|
+
// any decoding, exactly as `iscc_core.codec.iscc_normalize` does. Without
|
|
250
|
+
// this, a structurally decodable header with an invalid (MainType, SubType)
|
|
251
|
+
// combination (e.g. `MQ` = ID subtype 4) would be accepted.
|
|
252
|
+
let prefix: String = clean.to_ascii_uppercase().chars().take(2).collect();
|
|
253
|
+
if !codec::PREFIXES.contains(&prefix.as_str()) {
|
|
254
|
+
return Err(IsccError::InvalidInput(format!(
|
|
255
|
+
"ISCC starts with invalid prefix {prefix}"
|
|
256
|
+
)));
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
let raw = codec::decode_base32(&clean)?;
|
|
260
|
+
let (mt, st, _, _, _) = codec::decode_header(&raw)?;
|
|
261
|
+
let is_wide = mt == codec::MainType::Iscc && st == codec::SubType::Wide;
|
|
262
|
+
|
|
263
|
+
// Pass the cleaned form: iscc_decompose does not itself strip dashes.
|
|
264
|
+
let decomposed = codec::iscc_decompose(&clean)?;
|
|
265
|
+
if decomposed.len() >= 2 {
|
|
266
|
+
let units: Vec<&str> = decomposed.iter().map(String::as_str).collect();
|
|
267
|
+
let composed = gen_iscc_code_v0(&units, is_wide)?.iscc;
|
|
268
|
+
Ok(composed
|
|
269
|
+
.strip_prefix("ISCC:")
|
|
270
|
+
.unwrap_or(&composed)
|
|
271
|
+
.to_string())
|
|
272
|
+
} else {
|
|
273
|
+
decomposed
|
|
274
|
+
.into_iter()
|
|
275
|
+
.next()
|
|
276
|
+
.ok_or_else(|| IsccError::InvalidInput("decomposed to zero ISCC-UNITs".to_string()))
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/// Decode an ISCC string into its header components and raw digest.
|
|
281
|
+
///
|
|
282
|
+
/// Normalizes the input to its canonical form first (matching
|
|
283
|
+
/// `iscc_core.codec.iscc_decode`), then base32-decodes it, parses the
|
|
284
|
+
/// variable-length header, and returns the digest.
|
|
285
|
+
///
|
|
286
|
+
/// Normalization means a concatenated sequence of ISCC-UNITs is composed into a
|
|
287
|
+
/// single ISCC-CODE before decoding, so a sequence and its composite form decode
|
|
288
|
+
/// identically. Trailing bytes after a composite are discarded by decomposition,
|
|
289
|
+
/// exactly as in the reference.
|
|
290
|
+
///
|
|
291
|
+
/// Returns `(maintype, subtype, version, length_index, digest)` where the
|
|
292
|
+
/// integer fields match [`codec::MainType`], [`codec::SubType`], and
|
|
293
|
+
/// [`codec::Version`] enum values.
|
|
294
|
+
///
|
|
295
|
+
/// # Errors
|
|
296
|
+
///
|
|
297
|
+
/// Returns `IsccError::InvalidInput` on invalid base32 input, a malformed
|
|
298
|
+
/// header, a unit length above 256 bits, an ISCC-ID length other than 64, 72,
|
|
299
|
+
/// 80 or 96 bits, a body shorter than its encoded
|
|
300
|
+
/// bit-length, or a unit sequence that cannot be composed into an ISCC-CODE.
|
|
301
|
+
pub fn iscc_decode(iscc: &str) -> IsccResult<(u8, u8, u8, u8, Vec<u8>)> {
|
|
302
|
+
let normalized = iscc_normalize(iscc)?;
|
|
303
|
+
let raw = codec::decode_base32(&normalized)?;
|
|
304
|
+
let (mt, st, vs, length_index, tail) = codec::decode_header(&raw)?;
|
|
305
|
+
let bit_length = codec::unit_bit_length(mt, length_index, st)?;
|
|
306
|
+
let nbytes = (bit_length / 8) as usize;
|
|
307
|
+
// No length check here: normalization guarantees an exact body. `iscc_decompose`
|
|
308
|
+
// rejects a short unit body and truncates each unit to its encoded length, and a
|
|
309
|
+
// recomposed ISCC-CODE is well-formed by construction.
|
|
310
|
+
Ok((
|
|
311
|
+
mt as u8,
|
|
312
|
+
st as u8,
|
|
313
|
+
vs as u8,
|
|
314
|
+
length_index as u8,
|
|
315
|
+
tail[..nbytes].to_vec(),
|
|
316
|
+
))
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/// Convert a JSON string into a `data:` URL with JCS canonicalization.
|
|
320
|
+
///
|
|
321
|
+
/// Parses the JSON, re-serializes to [RFC 8785 (JCS)](https://www.rfc-editor.org/rfc/rfc8785)
|
|
322
|
+
/// canonical form, base64-encodes the result, and wraps it in a `data:` URL.
|
|
323
|
+
/// Uses `application/ld+json` media type when the JSON contains an `@context`
|
|
324
|
+
/// key, otherwise `application/json`.
|
|
325
|
+
///
|
|
326
|
+
/// This enables all language bindings to support dict/object meta parameters
|
|
327
|
+
/// by serializing to JSON once (language-specific) then delegating encoding
|
|
328
|
+
/// to Rust.
|
|
329
|
+
///
|
|
330
|
+
/// # Errors
|
|
331
|
+
///
|
|
332
|
+
/// Returns [`IsccError::InvalidInput`] if `json` is not valid JSON or if
|
|
333
|
+
/// JCS canonicalization fails.
|
|
334
|
+
///
|
|
335
|
+
/// # Examples
|
|
336
|
+
///
|
|
337
|
+
/// ```
|
|
338
|
+
/// # use iscc_lib::json_to_data_url;
|
|
339
|
+
/// let url = json_to_data_url(r#"{"key": "value"}"#).unwrap();
|
|
340
|
+
/// assert!(url.starts_with("data:application/json;base64,"));
|
|
341
|
+
///
|
|
342
|
+
/// let ld_url = json_to_data_url(r#"{"@context": "https://schema.org"}"#).unwrap();
|
|
343
|
+
/// assert!(ld_url.starts_with("data:application/ld+json;base64,"));
|
|
344
|
+
/// ```
|
|
345
|
+
#[cfg(feature = "meta-code")]
|
|
346
|
+
pub fn json_to_data_url(json: &str) -> IsccResult<String> {
|
|
347
|
+
Ok(build_meta_data_url(&canonicalize_json(
|
|
348
|
+
json,
|
|
349
|
+
"invalid JSON",
|
|
350
|
+
)?))
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/// Generate a Meta-Code from name and optional metadata.
|
|
354
|
+
///
|
|
355
|
+
/// Produces an ISCC Meta-Code by hashing the provided name, description,
|
|
356
|
+
/// and metadata fields using the SimHash algorithm. When `meta` is provided,
|
|
357
|
+
/// it is treated as either a Data-URL (if starting with `"data:"`) or a JSON
|
|
358
|
+
/// string, and the decoded/serialized bytes are used for similarity hashing
|
|
359
|
+
/// and metahash computation.
|
|
360
|
+
#[cfg(feature = "meta-code")]
|
|
361
|
+
pub fn gen_meta_code_v0(
|
|
362
|
+
name: &str,
|
|
363
|
+
description: Option<&str>,
|
|
364
|
+
meta: Option<&str>,
|
|
365
|
+
bits: u32,
|
|
366
|
+
) -> IsccResult<MetaCodeResult> {
|
|
367
|
+
// Normalize name: clean → remove newlines → trim to 128 bytes
|
|
368
|
+
let name = utils::text_clean(name);
|
|
369
|
+
let name = utils::text_remove_newlines(&name);
|
|
370
|
+
let name = utils::text_trim(&name, META_TRIM_NAME);
|
|
371
|
+
|
|
372
|
+
if name.is_empty() {
|
|
373
|
+
return Err(IsccError::InvalidInput(
|
|
374
|
+
"name is empty after normalization".into(),
|
|
375
|
+
));
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// Normalize description: clean → trim to 4096 bytes
|
|
379
|
+
let desc_str = description.unwrap_or("");
|
|
380
|
+
let desc_clean = utils::text_clean(desc_str);
|
|
381
|
+
let desc_clean = utils::text_trim(&desc_clean, META_TRIM_DESCRIPTION);
|
|
382
|
+
|
|
383
|
+
// Pre-decode fast check: reject obviously oversized meta strings
|
|
384
|
+
if let Some(meta_str) = meta {
|
|
385
|
+
const PRE_DECODE_LIMIT: usize = META_TRIM_META * 4 / 3 + 256;
|
|
386
|
+
if meta_str.len() > PRE_DECODE_LIMIT {
|
|
387
|
+
return Err(IsccError::InvalidInput(format!(
|
|
388
|
+
"meta string exceeds size limit ({} > {PRE_DECODE_LIMIT} bytes)",
|
|
389
|
+
meta_str.len()
|
|
390
|
+
)));
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// Resolve meta payload bytes and the result's Data-URL (if meta is provided)
|
|
395
|
+
let meta_payload: Option<(Vec<u8>, String)> = match meta {
|
|
396
|
+
Some(meta_str) if meta_str.starts_with("data:") => {
|
|
397
|
+
Some((decode_data_url(meta_str)?, meta_str.to_string()))
|
|
398
|
+
}
|
|
399
|
+
Some(meta_str) => {
|
|
400
|
+
let json = canonicalize_json(meta_str, "invalid JSON in meta")?;
|
|
401
|
+
let data_url = build_meta_data_url(&json);
|
|
402
|
+
Some((json.bytes, data_url))
|
|
403
|
+
}
|
|
404
|
+
None => None,
|
|
405
|
+
};
|
|
406
|
+
|
|
407
|
+
// Post-decode check: reject payloads exceeding META_TRIM_META
|
|
408
|
+
if let Some((ref payload, _)) = meta_payload {
|
|
409
|
+
if payload.len() > META_TRIM_META {
|
|
410
|
+
return Err(IsccError::InvalidInput(format!(
|
|
411
|
+
"decoded meta payload exceeds size limit ({} > {META_TRIM_META} bytes)",
|
|
412
|
+
payload.len()
|
|
413
|
+
)));
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// Branch: meta bytes path vs. description text path
|
|
418
|
+
if let Some((payload, meta_value)) = meta_payload {
|
|
419
|
+
let meta_code_digest = soft_hash_meta_v0_with_bytes(&name, &payload);
|
|
420
|
+
let metahash = utils::multi_hash_blake3(&payload);
|
|
421
|
+
|
|
422
|
+
let meta_code = codec::encode_component(
|
|
423
|
+
codec::MainType::Meta,
|
|
424
|
+
codec::SubType::None,
|
|
425
|
+
codec::Version::V0,
|
|
426
|
+
bits,
|
|
427
|
+
&meta_code_digest,
|
|
428
|
+
)?;
|
|
429
|
+
|
|
430
|
+
Ok(MetaCodeResult {
|
|
431
|
+
iscc: format!("ISCC:{meta_code}"),
|
|
432
|
+
name: name.clone(),
|
|
433
|
+
description: if desc_clean.is_empty() {
|
|
434
|
+
None
|
|
435
|
+
} else {
|
|
436
|
+
Some(desc_clean)
|
|
437
|
+
},
|
|
438
|
+
meta: Some(meta_value),
|
|
439
|
+
metahash,
|
|
440
|
+
})
|
|
441
|
+
} else {
|
|
442
|
+
// Compute metahash from normalized text payload
|
|
443
|
+
let payload = if desc_clean.is_empty() {
|
|
444
|
+
name.clone()
|
|
445
|
+
} else {
|
|
446
|
+
format!("{name} {desc_clean}")
|
|
447
|
+
};
|
|
448
|
+
let payload = payload.trim().to_string();
|
|
449
|
+
let metahash = utils::multi_hash_blake3(payload.as_bytes());
|
|
450
|
+
|
|
451
|
+
// Compute similarity digest
|
|
452
|
+
let extra = if desc_clean.is_empty() {
|
|
453
|
+
None
|
|
454
|
+
} else {
|
|
455
|
+
Some(desc_clean.as_str())
|
|
456
|
+
};
|
|
457
|
+
let meta_code_digest = soft_hash_meta_v0(&name, extra);
|
|
458
|
+
|
|
459
|
+
let meta_code = codec::encode_component(
|
|
460
|
+
codec::MainType::Meta,
|
|
461
|
+
codec::SubType::None,
|
|
462
|
+
codec::Version::V0,
|
|
463
|
+
bits,
|
|
464
|
+
&meta_code_digest,
|
|
465
|
+
)?;
|
|
466
|
+
|
|
467
|
+
Ok(MetaCodeResult {
|
|
468
|
+
iscc: format!("ISCC:{meta_code}"),
|
|
469
|
+
name: name.clone(),
|
|
470
|
+
description: if desc_clean.is_empty() {
|
|
471
|
+
None
|
|
472
|
+
} else {
|
|
473
|
+
Some(desc_clean)
|
|
474
|
+
},
|
|
475
|
+
meta: None,
|
|
476
|
+
metahash,
|
|
477
|
+
})
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/// Compute a 256-bit similarity-preserving hash from collapsed text.
|
|
482
|
+
///
|
|
483
|
+
/// Generates character n-grams with a sliding window of width 13,
|
|
484
|
+
/// hashes each with xxh32, then applies MinHash to produce a 32-byte digest.
|
|
485
|
+
#[cfg(feature = "text-processing")]
|
|
486
|
+
fn soft_hash_text_v0(text: &str) -> Vec<u8> {
|
|
487
|
+
let ngrams = simhash::sliding_window_strs(text, TEXT_NGRAM_SIZE);
|
|
488
|
+
let features: Vec<u32> = ngrams
|
|
489
|
+
.iter()
|
|
490
|
+
.map(|ng| xxh32::xxh32(ng.as_bytes(), 0))
|
|
491
|
+
.collect();
|
|
492
|
+
minhash::alg_minhash_256_inner(&features)
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/// Generate a Text-Code from plain text content.
|
|
496
|
+
///
|
|
497
|
+
/// Produces an ISCC Content-Code for text by collapsing the input,
|
|
498
|
+
/// extracting character n-gram features, and applying MinHash to
|
|
499
|
+
/// create a similarity-preserving fingerprint.
|
|
500
|
+
#[cfg(feature = "text-processing")]
|
|
501
|
+
pub fn gen_text_code_v0(text: &str, bits: u32) -> IsccResult<TextCodeResult> {
|
|
502
|
+
let collapsed = utils::text_collapse(text);
|
|
503
|
+
let characters = collapsed.chars().count();
|
|
504
|
+
let hash_digest = soft_hash_text_v0(&collapsed);
|
|
505
|
+
let component = codec::encode_component(
|
|
506
|
+
codec::MainType::Content,
|
|
507
|
+
codec::SubType::TEXT,
|
|
508
|
+
codec::Version::V0,
|
|
509
|
+
bits,
|
|
510
|
+
&hash_digest,
|
|
511
|
+
)?;
|
|
512
|
+
Ok(TextCodeResult {
|
|
513
|
+
iscc: format!("ISCC:{component}"),
|
|
514
|
+
characters,
|
|
515
|
+
})
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/// Transpose a matrix represented as a Vec of Vecs.
|
|
519
|
+
fn transpose_matrix(matrix: &[Vec<f64>]) -> Vec<Vec<f64>> {
|
|
520
|
+
let rows = matrix.len();
|
|
521
|
+
if rows == 0 {
|
|
522
|
+
return vec![];
|
|
523
|
+
}
|
|
524
|
+
let cols = matrix[0].len();
|
|
525
|
+
let mut result = vec![vec![0.0f64; rows]; cols];
|
|
526
|
+
for (r, row) in matrix.iter().enumerate() {
|
|
527
|
+
for (c, &val) in row.iter().enumerate() {
|
|
528
|
+
result[c][r] = val;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
result
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/// Extract an 8×8 block from a matrix and flatten to 64 values.
|
|
535
|
+
///
|
|
536
|
+
/// Block position `(col, row)` means the block starts at
|
|
537
|
+
/// `matrix[row][col]` and spans 8 rows and 8 columns.
|
|
538
|
+
fn flatten_8x8(matrix: &[Vec<f64>], col: usize, row: usize) -> Vec<f64> {
|
|
539
|
+
let mut flat = Vec::with_capacity(64);
|
|
540
|
+
for matrix_row in matrix.iter().skip(row).take(8) {
|
|
541
|
+
for &val in matrix_row.iter().skip(col).take(8) {
|
|
542
|
+
flat.push(val);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
flat
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/// Compute the median of a slice of f64 values.
|
|
549
|
+
///
|
|
550
|
+
/// For even-length slices, returns the average of the two middle values
|
|
551
|
+
/// (matching Python `statistics.median` behavior).
|
|
552
|
+
fn compute_median(values: &[f64]) -> f64 {
|
|
553
|
+
let mut sorted: Vec<f64> = values.to_vec();
|
|
554
|
+
sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
|
555
|
+
let n = sorted.len();
|
|
556
|
+
if n % 2 == 1 {
|
|
557
|
+
sorted[n / 2]
|
|
558
|
+
} else {
|
|
559
|
+
(sorted[n / 2 - 1] + sorted[n / 2]) / 2.0
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/// Convert a slice of bools to a byte vector (MSB first per byte).
|
|
564
|
+
fn bits_to_bytes(bits: &[bool]) -> Vec<u8> {
|
|
565
|
+
bits.chunks(8)
|
|
566
|
+
.map(|chunk| {
|
|
567
|
+
let mut byte = 0u8;
|
|
568
|
+
for (i, &bit) in chunk.iter().enumerate() {
|
|
569
|
+
if bit {
|
|
570
|
+
byte |= 1 << (7 - i);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
byte
|
|
574
|
+
})
|
|
575
|
+
.collect()
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/// Compute a DCT-based perceptual hash from 32×32 grayscale pixels.
|
|
579
|
+
///
|
|
580
|
+
/// Applies a 2D DCT to the pixel matrix, extracts four 8×8 low-frequency
|
|
581
|
+
/// blocks, and generates a bitstring by comparing each coefficient against
|
|
582
|
+
/// the block median. Returns up to `bits` bits as a byte vector.
|
|
583
|
+
fn soft_hash_image_v0(pixels: &[u8], bits: u32) -> IsccResult<Vec<u8>> {
|
|
584
|
+
if pixels.len() != 1024 {
|
|
585
|
+
return Err(IsccError::InvalidInput(format!(
|
|
586
|
+
"expected 1024 pixels, got {}",
|
|
587
|
+
pixels.len()
|
|
588
|
+
)));
|
|
589
|
+
}
|
|
590
|
+
if bits > 256 {
|
|
591
|
+
return Err(IsccError::InvalidInput(format!(
|
|
592
|
+
"bits must be <= 256, got {bits}"
|
|
593
|
+
)));
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// Step 1: Row-wise DCT (32 rows of 32 pixels)
|
|
597
|
+
let rows: Vec<Vec<f64>> = pixels
|
|
598
|
+
.chunks(32)
|
|
599
|
+
.map(|row| {
|
|
600
|
+
let row_f64: Vec<f64> = row.iter().map(|&p| p as f64).collect();
|
|
601
|
+
dct::alg_dct(&row_f64)
|
|
602
|
+
})
|
|
603
|
+
.collect::<IsccResult<Vec<Vec<f64>>>>()?;
|
|
604
|
+
|
|
605
|
+
// Step 2: Transpose
|
|
606
|
+
let transposed = transpose_matrix(&rows);
|
|
607
|
+
|
|
608
|
+
// Step 3: Column-wise DCT
|
|
609
|
+
let dct_cols: Vec<Vec<f64>> = transposed
|
|
610
|
+
.iter()
|
|
611
|
+
.map(|col| dct::alg_dct(col))
|
|
612
|
+
.collect::<IsccResult<Vec<Vec<f64>>>>()?;
|
|
613
|
+
|
|
614
|
+
// Step 4: Transpose back → dct_matrix
|
|
615
|
+
let dct_matrix = transpose_matrix(&dct_cols);
|
|
616
|
+
|
|
617
|
+
// Step 5: Extract the top-left, top-right, bottom-left and bottom-right 8×8
|
|
618
|
+
// squares of the upper-left 16×16 at positions (col, row) (ISO 24138 5.4.5.2 e)
|
|
619
|
+
let positions = [(0, 0), (8, 0), (0, 8), (8, 8)];
|
|
620
|
+
let mut bitstring = Vec::<bool>::with_capacity(256);
|
|
621
|
+
|
|
622
|
+
for (col, row) in positions {
|
|
623
|
+
let flat = flatten_8x8(&dct_matrix, col, row);
|
|
624
|
+
let median = compute_median(&flat);
|
|
625
|
+
for val in &flat {
|
|
626
|
+
bitstring.push(*val > median);
|
|
627
|
+
}
|
|
628
|
+
if bitstring.len() >= bits as usize {
|
|
629
|
+
break;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// Step 6: Convert first `bits` bools to bytes
|
|
634
|
+
Ok(bits_to_bytes(&bitstring[..bits as usize]))
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/// Generate an Image-Code from pixel data.
|
|
638
|
+
///
|
|
639
|
+
/// Produces an ISCC Content-Code for images from a sequence of 1024
|
|
640
|
+
/// grayscale pixel values (32×32, values 0-255) using a DCT-based
|
|
641
|
+
/// perceptual hash.
|
|
642
|
+
pub fn gen_image_code_v0(pixels: &[u8], bits: u32) -> IsccResult<ImageCodeResult> {
|
|
643
|
+
let hash_digest = soft_hash_image_v0(pixels, bits)?;
|
|
644
|
+
let component = codec::encode_component(
|
|
645
|
+
codec::MainType::Content,
|
|
646
|
+
codec::SubType::Image,
|
|
647
|
+
codec::Version::V0,
|
|
648
|
+
bits,
|
|
649
|
+
&hash_digest,
|
|
650
|
+
)?;
|
|
651
|
+
Ok(ImageCodeResult {
|
|
652
|
+
iscc: format!("ISCC:{component}"),
|
|
653
|
+
})
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/// Split a slice into `n` parts, distributing remainder across first chunks.
|
|
657
|
+
///
|
|
658
|
+
/// Equivalent to `numpy.array_split` / `more_itertools.divide`:
|
|
659
|
+
/// each part gets `len / n` elements, and the first `len % n` parts
|
|
660
|
+
/// get one extra element. Returns empty slices for excess parts.
|
|
661
|
+
fn array_split<T>(slice: &[T], n: usize) -> Vec<&[T]> {
|
|
662
|
+
if n == 0 {
|
|
663
|
+
return vec![];
|
|
664
|
+
}
|
|
665
|
+
let len = slice.len();
|
|
666
|
+
let base = len / n;
|
|
667
|
+
let remainder = len % n;
|
|
668
|
+
let mut parts = Vec::with_capacity(n);
|
|
669
|
+
let mut offset = 0;
|
|
670
|
+
for i in 0..n {
|
|
671
|
+
let size = base + if i < remainder { 1 } else { 0 };
|
|
672
|
+
parts.push(&slice[offset..offset + size]);
|
|
673
|
+
offset += size;
|
|
674
|
+
}
|
|
675
|
+
parts
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/// Compute a multi-stage SimHash digest from Chromaprint features.
|
|
679
|
+
///
|
|
680
|
+
/// Builds a 32-byte digest by concatenating 4-byte SimHash chunks:
|
|
681
|
+
/// - Stage 1: overall SimHash of all features (4 bytes)
|
|
682
|
+
/// - Stage 2: SimHash of each quarter of features (4 × 4 = 16 bytes)
|
|
683
|
+
/// - Stage 3: SimHash of each third of sorted features (3 × 4 = 12 bytes)
|
|
684
|
+
fn soft_hash_audio_v0(cv: &[i32]) -> Vec<u8> {
|
|
685
|
+
// Convert each i32 to 4-byte big-endian digest
|
|
686
|
+
let digests: Vec<[u8; 4]> = cv.iter().map(|&v| v.to_be_bytes()).collect();
|
|
687
|
+
|
|
688
|
+
if digests.is_empty() {
|
|
689
|
+
return vec![0u8; 32];
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
// Stage 1: overall SimHash (4 bytes)
|
|
693
|
+
let mut parts: Vec<u8> = simhash::alg_simhash_inner(&digests);
|
|
694
|
+
|
|
695
|
+
// Stage 2: quarter-based SimHashes (4 × 4 = 16 bytes)
|
|
696
|
+
let quarters = array_split(&digests, 4);
|
|
697
|
+
for quarter in &quarters {
|
|
698
|
+
if quarter.is_empty() {
|
|
699
|
+
parts.extend_from_slice(&[0u8; 4]);
|
|
700
|
+
} else {
|
|
701
|
+
parts.extend_from_slice(&simhash::alg_simhash_inner(quarter));
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
// Stage 3: sorted-third-based SimHashes (3 × 4 = 12 bytes)
|
|
706
|
+
let mut sorted_values: Vec<i32> = cv.to_vec();
|
|
707
|
+
sorted_values.sort();
|
|
708
|
+
let sorted_digests: Vec<[u8; 4]> = sorted_values.iter().map(|&v| v.to_be_bytes()).collect();
|
|
709
|
+
let thirds = array_split(&sorted_digests, 3);
|
|
710
|
+
for third in &thirds {
|
|
711
|
+
if third.is_empty() {
|
|
712
|
+
parts.extend_from_slice(&[0u8; 4]);
|
|
713
|
+
} else {
|
|
714
|
+
parts.extend_from_slice(&simhash::alg_simhash_inner(third));
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
parts
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/// Generate an Audio-Code from a Chromaprint feature vector.
|
|
722
|
+
///
|
|
723
|
+
/// Produces an ISCC Content-Code for audio from a Chromaprint signed
|
|
724
|
+
/// integer fingerprint vector using multi-stage SimHash.
|
|
725
|
+
pub fn gen_audio_code_v0(cv: &[i32], bits: u32) -> IsccResult<AudioCodeResult> {
|
|
726
|
+
let hash_digest = soft_hash_audio_v0(cv);
|
|
727
|
+
let component = codec::encode_component(
|
|
728
|
+
codec::MainType::Content,
|
|
729
|
+
codec::SubType::Audio,
|
|
730
|
+
codec::Version::V0,
|
|
731
|
+
bits,
|
|
732
|
+
&hash_digest,
|
|
733
|
+
)?;
|
|
734
|
+
Ok(AudioCodeResult {
|
|
735
|
+
iscc: format!("ISCC:{component}"),
|
|
736
|
+
})
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/// Check that every frame signature has the length of the first one.
|
|
740
|
+
///
|
|
741
|
+
/// Walks `frame_sigs` in input order and reports the first signature whose
|
|
742
|
+
/// length differs from `frame_sigs[0]`. An empty slice passes.
|
|
743
|
+
fn check_frame_sig_lengths<S: AsRef<[i32]>>(frame_sigs: &[S]) -> IsccResult<()> {
|
|
744
|
+
let Some(first) = frame_sigs.first().map(|s| s.as_ref().len()) else {
|
|
745
|
+
return Ok(());
|
|
746
|
+
};
|
|
747
|
+
match frame_sigs
|
|
748
|
+
.iter()
|
|
749
|
+
.map(|s| s.as_ref().len())
|
|
750
|
+
.enumerate()
|
|
751
|
+
.find(|&(_, n)| n != first)
|
|
752
|
+
{
|
|
753
|
+
Some((i, n)) => Err(IsccError::InvalidInput(format!(
|
|
754
|
+
"frame_sigs[{i}] has length {n}, expected {first}"
|
|
755
|
+
))),
|
|
756
|
+
None => Ok(()),
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/// Compute a similarity-preserving hash from video frame signatures.
|
|
761
|
+
///
|
|
762
|
+
/// Deduplicates frame signatures, computes column-wise sums across all
|
|
763
|
+
/// unique frames, then applies WTA-Hash to produce a digest of `bits/8` bytes.
|
|
764
|
+
///
|
|
765
|
+
/// Returns `IsccError::InvalidInput` for an empty `frame_sigs` or for frame
|
|
766
|
+
/// signatures of unequal length (iscc-core truncates to the shortest instead).
|
|
767
|
+
pub fn soft_hash_video_v0<S: AsRef<[i32]> + Ord>(
|
|
768
|
+
frame_sigs: &[S],
|
|
769
|
+
bits: u32,
|
|
770
|
+
) -> IsccResult<Vec<u8>> {
|
|
771
|
+
if frame_sigs.is_empty() {
|
|
772
|
+
return Err(IsccError::InvalidInput(
|
|
773
|
+
"frame_sigs must not be empty".into(),
|
|
774
|
+
));
|
|
775
|
+
}
|
|
776
|
+
check_frame_sig_lengths(frame_sigs)?;
|
|
777
|
+
|
|
778
|
+
// Deduplicate using BTreeSet (S: Ord)
|
|
779
|
+
let unique: std::collections::BTreeSet<&S> = frame_sigs.iter().collect();
|
|
780
|
+
|
|
781
|
+
// Column-wise sum into i64 to avoid overflow
|
|
782
|
+
let cols = frame_sigs[0].as_ref().len();
|
|
783
|
+
let mut vecsum = vec![0i64; cols];
|
|
784
|
+
for sig in &unique {
|
|
785
|
+
for (c, &val) in sig.as_ref().iter().enumerate() {
|
|
786
|
+
vecsum[c] += val as i64;
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
wtahash::alg_wtahash(&vecsum, bits)
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/// Generate a Video-Code from frame signature data.
|
|
794
|
+
///
|
|
795
|
+
/// Produces an ISCC Content-Code for video from a sequence of MPEG-7 frame
|
|
796
|
+
/// signatures. Each frame signature is a 380-element integer vector; frame
|
|
797
|
+
/// signatures of unequal length return `IsccError::InvalidInput`.
|
|
798
|
+
pub fn gen_video_code_v0<S: AsRef<[i32]> + Ord>(
|
|
799
|
+
frame_sigs: &[S],
|
|
800
|
+
bits: u32,
|
|
801
|
+
) -> IsccResult<VideoCodeResult> {
|
|
802
|
+
let digest = soft_hash_video_v0(frame_sigs, bits)?;
|
|
803
|
+
let component = codec::encode_component(
|
|
804
|
+
codec::MainType::Content,
|
|
805
|
+
codec::SubType::Video,
|
|
806
|
+
codec::Version::V0,
|
|
807
|
+
bits,
|
|
808
|
+
&digest,
|
|
809
|
+
)?;
|
|
810
|
+
Ok(VideoCodeResult {
|
|
811
|
+
iscc: format!("ISCC:{component}"),
|
|
812
|
+
})
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
/// Combine multiple Content-Code digests into a single similarity hash.
|
|
816
|
+
///
|
|
817
|
+
/// Takes raw decoded ISCC bytes (header + body) for each Content-Code and
|
|
818
|
+
/// produces a SimHash digest. Each input is trimmed to `bits/8` bytes by
|
|
819
|
+
/// keeping the first header byte (encodes type info) plus `nbytes-1` body bytes.
|
|
820
|
+
/// Requires at least 2 codes, all of MainType::Content, and `bits` to be a
|
|
821
|
+
/// valid Content-Code length.
|
|
822
|
+
fn soft_hash_codes_v0(cc_digests: &[Vec<u8>], bits: u32) -> IsccResult<Vec<u8>> {
|
|
823
|
+
if cc_digests.len() < 2 {
|
|
824
|
+
return Err(IsccError::InvalidInput(
|
|
825
|
+
"at least 2 Content-Codes required for mixing".into(),
|
|
826
|
+
));
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
// Reject an invalid length here: `nbytes - 1` below needs at least one byte
|
|
830
|
+
codec::encode_length(codec::MainType::Content, bits)?;
|
|
831
|
+
let nbytes = (bits / 8) as usize;
|
|
832
|
+
let mut prepared: Vec<Vec<u8>> = Vec::with_capacity(cc_digests.len());
|
|
833
|
+
|
|
834
|
+
for raw in cc_digests {
|
|
835
|
+
let (mtype, stype, _ver, blen, body) = codec::decode_header(raw)?;
|
|
836
|
+
if mtype != codec::MainType::Content {
|
|
837
|
+
return Err(IsccError::InvalidInput(
|
|
838
|
+
"all codes must be Content-Codes".into(),
|
|
839
|
+
));
|
|
840
|
+
}
|
|
841
|
+
let unit_bits = codec::unit_bit_length(mtype, blen, stype)?;
|
|
842
|
+
if unit_bits < bits {
|
|
843
|
+
return Err(IsccError::InvalidInput(format!(
|
|
844
|
+
"Content-Code too short for {bits}-bit length (has {unit_bits} bits)"
|
|
845
|
+
)));
|
|
846
|
+
}
|
|
847
|
+
let mut entry = Vec::with_capacity(nbytes);
|
|
848
|
+
entry.push(raw[0]); // first byte preserves type info
|
|
849
|
+
let take = std::cmp::min(nbytes - 1, body.len());
|
|
850
|
+
entry.extend_from_slice(&body[..take]);
|
|
851
|
+
// Pad with zeros if body is shorter than nbytes-1
|
|
852
|
+
while entry.len() < nbytes {
|
|
853
|
+
entry.push(0);
|
|
854
|
+
}
|
|
855
|
+
prepared.push(entry);
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
Ok(simhash::alg_simhash_inner(&prepared))
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
/// Generate a Mixed-Code from multiple Content-Code strings.
|
|
862
|
+
///
|
|
863
|
+
/// Produces a Mixed Content-Code by combining multiple ISCC Content-Codes
|
|
864
|
+
/// of different types (text, image, audio, video) using SimHash. Input codes
|
|
865
|
+
/// may optionally include the "ISCC:" prefix.
|
|
866
|
+
pub fn gen_mixed_code_v0(codes: &[&str], bits: u32) -> IsccResult<MixedCodeResult> {
|
|
867
|
+
let decoded: Vec<Vec<u8>> = codes
|
|
868
|
+
.iter()
|
|
869
|
+
.map(|code| {
|
|
870
|
+
let clean = codec::iscc_clean(code)?;
|
|
871
|
+
codec::decode_base32(&clean)
|
|
872
|
+
})
|
|
873
|
+
.collect::<IsccResult<Vec<Vec<u8>>>>()?;
|
|
874
|
+
|
|
875
|
+
let digest = soft_hash_codes_v0(&decoded, bits)?;
|
|
876
|
+
|
|
877
|
+
let component = codec::encode_component(
|
|
878
|
+
codec::MainType::Content,
|
|
879
|
+
codec::SubType::Mixed,
|
|
880
|
+
codec::Version::V0,
|
|
881
|
+
bits,
|
|
882
|
+
&digest,
|
|
883
|
+
)?;
|
|
884
|
+
|
|
885
|
+
Ok(MixedCodeResult {
|
|
886
|
+
iscc: format!("ISCC:{component}"),
|
|
887
|
+
parts: codes.iter().map(|s| s.to_string()).collect(),
|
|
888
|
+
})
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
/// Generate a Data-Code from raw byte data.
|
|
892
|
+
///
|
|
893
|
+
/// Produces an ISCC Data-Code by splitting data into content-defined chunks,
|
|
894
|
+
/// hashing each chunk with xxh32, and applying MinHash to create a
|
|
895
|
+
/// similarity-preserving fingerprint.
|
|
896
|
+
pub fn gen_data_code_v0(data: &[u8], bits: u32) -> IsccResult<DataCodeResult> {
|
|
897
|
+
let chunks = cdc::alg_cdc_chunks_unchecked(data, false, cdc::DATA_AVG_CHUNK_SIZE);
|
|
898
|
+
let mut features: Vec<u32> = chunks.iter().map(|chunk| xxh32::xxh32(chunk, 0)).collect();
|
|
899
|
+
|
|
900
|
+
// Defensive: ensure at least one feature (alg_cdc_chunks guarantees >= 1 chunk)
|
|
901
|
+
if features.is_empty() {
|
|
902
|
+
features.push(xxh32::xxh32(b"", 0));
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
let digest = minhash::alg_minhash_256_inner(&features);
|
|
906
|
+
let component = codec::encode_component(
|
|
907
|
+
codec::MainType::Data,
|
|
908
|
+
codec::SubType::None,
|
|
909
|
+
codec::Version::V0,
|
|
910
|
+
bits,
|
|
911
|
+
&digest,
|
|
912
|
+
)?;
|
|
913
|
+
|
|
914
|
+
Ok(DataCodeResult {
|
|
915
|
+
iscc: format!("ISCC:{component}"),
|
|
916
|
+
})
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/// Generate an Instance-Code from raw byte data.
|
|
920
|
+
///
|
|
921
|
+
/// Produces an ISCC Instance-Code by hashing the complete byte stream
|
|
922
|
+
/// with BLAKE3. Captures the exact binary identity of the data.
|
|
923
|
+
pub fn gen_instance_code_v0(data: &[u8], bits: u32) -> IsccResult<InstanceCodeResult> {
|
|
924
|
+
let digest = blake3::hash(data);
|
|
925
|
+
let datahash = utils::blake3_multihash_hex(&digest);
|
|
926
|
+
let filesize = data.len() as u64;
|
|
927
|
+
let component = codec::encode_component(
|
|
928
|
+
codec::MainType::Instance,
|
|
929
|
+
codec::SubType::None,
|
|
930
|
+
codec::Version::V0,
|
|
931
|
+
bits,
|
|
932
|
+
digest.as_bytes(),
|
|
933
|
+
)?;
|
|
934
|
+
Ok(InstanceCodeResult {
|
|
935
|
+
iscc: format!("ISCC:{component}"),
|
|
936
|
+
datahash,
|
|
937
|
+
filesize,
|
|
938
|
+
})
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
/// Return whether every decoded unit header carries at least 128 bits.
|
|
942
|
+
///
|
|
943
|
+
/// Stops at the first unit below 128 bits, as iscc-core's `all(...)` does, and
|
|
944
|
+
/// rejects a unit length above 256 bits on the way.
|
|
945
|
+
fn units_reach_128_bits(
|
|
946
|
+
decoded: &[(
|
|
947
|
+
codec::MainType,
|
|
948
|
+
codec::SubType,
|
|
949
|
+
codec::Version,
|
|
950
|
+
u32,
|
|
951
|
+
Vec<u8>,
|
|
952
|
+
)],
|
|
953
|
+
) -> IsccResult<bool> {
|
|
954
|
+
for &(mt, st, _, len, _) in decoded {
|
|
955
|
+
if codec::unit_bit_length(mt, len, st)? < 128 {
|
|
956
|
+
return Ok(false);
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
Ok(true)
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
/// Generate a composite ISCC-CODE from individual ISCC unit codes.
|
|
963
|
+
///
|
|
964
|
+
/// Combines multiple ISCC unit codes (Meta-Code, Content-Code, Data-Code,
|
|
965
|
+
/// Instance-Code) into a single composite ISCC-CODE. Input codes may
|
|
966
|
+
/// optionally include the "ISCC:" prefix. At least Data-Code and
|
|
967
|
+
/// Instance-Code are required. When `wide` is true and exactly two
|
|
968
|
+
/// 128-bit+ codes (Data + Instance) are provided, produces a 256-bit
|
|
969
|
+
/// wide-mode code.
|
|
970
|
+
pub fn gen_iscc_code_v0(codes: &[&str], wide: bool) -> IsccResult<IsccCodeResult> {
|
|
971
|
+
// Step 1: Clean inputs — strip scheme prefix, dashes, and whitespace
|
|
972
|
+
let cleaned: Vec<std::borrow::Cow<'_, str>> = codes
|
|
973
|
+
.iter()
|
|
974
|
+
.map(|c| codec::iscc_clean(c))
|
|
975
|
+
.collect::<IsccResult<Vec<_>>>()?;
|
|
976
|
+
|
|
977
|
+
// Step 2: Validate minimum count
|
|
978
|
+
if cleaned.len() < 2 {
|
|
979
|
+
return Err(IsccError::InvalidInput(
|
|
980
|
+
"at least 2 ISCC unit codes required".into(),
|
|
981
|
+
));
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
// Step 3: Validate minimum length (16 base32 chars = 64-bit minimum)
|
|
985
|
+
for code in &cleaned {
|
|
986
|
+
if code.len() < 16 {
|
|
987
|
+
return Err(IsccError::InvalidInput(format!(
|
|
988
|
+
"ISCC unit code too short (min 16 chars): {code}"
|
|
989
|
+
)));
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
// Step 4: Decode each code
|
|
994
|
+
let mut decoded: Vec<(
|
|
995
|
+
codec::MainType,
|
|
996
|
+
codec::SubType,
|
|
997
|
+
codec::Version,
|
|
998
|
+
u32,
|
|
999
|
+
Vec<u8>,
|
|
1000
|
+
)> = Vec::with_capacity(cleaned.len());
|
|
1001
|
+
for code in &cleaned {
|
|
1002
|
+
let raw = codec::decode_base32(code)?;
|
|
1003
|
+
let header = codec::decode_header(&raw)?;
|
|
1004
|
+
decoded.push(header);
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
// Step 5: Sort by MainType (ascending)
|
|
1008
|
+
decoded.sort_by_key(|&(mt, ..)| mt);
|
|
1009
|
+
|
|
1010
|
+
// Step 6: Extract main_types
|
|
1011
|
+
let main_types: Vec<codec::MainType> = decoded.iter().map(|&(mt, ..)| mt).collect();
|
|
1012
|
+
|
|
1013
|
+
// Step 7: Validate last two are Data + Instance (mandatory)
|
|
1014
|
+
let n = main_types.len();
|
|
1015
|
+
if main_types[n - 2] != codec::MainType::Data || main_types[n - 1] != codec::MainType::Instance
|
|
1016
|
+
{
|
|
1017
|
+
return Err(IsccError::InvalidInput(
|
|
1018
|
+
"Data-Code and Instance-Code are mandatory".into(),
|
|
1019
|
+
));
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
// Step 8: Determine wide composite
|
|
1023
|
+
let is_wide = wide
|
|
1024
|
+
&& decoded.len() == 2
|
|
1025
|
+
&& main_types == [codec::MainType::Data, codec::MainType::Instance]
|
|
1026
|
+
&& units_reach_128_bits(&decoded)?;
|
|
1027
|
+
|
|
1028
|
+
// Step 9: Determine SubType
|
|
1029
|
+
let st = if is_wide {
|
|
1030
|
+
codec::SubType::Wide
|
|
1031
|
+
} else {
|
|
1032
|
+
// Collect SubTypes of Semantic/Content units
|
|
1033
|
+
let sc_subtypes: Vec<codec::SubType> = decoded
|
|
1034
|
+
.iter()
|
|
1035
|
+
.filter(|&&(mt, ..)| mt == codec::MainType::Semantic || mt == codec::MainType::Content)
|
|
1036
|
+
.map(|&(_, st, ..)| st)
|
|
1037
|
+
.collect();
|
|
1038
|
+
|
|
1039
|
+
if !sc_subtypes.is_empty() {
|
|
1040
|
+
// All must be the same
|
|
1041
|
+
let first = sc_subtypes[0];
|
|
1042
|
+
if sc_subtypes.iter().all(|&s| s == first) {
|
|
1043
|
+
first
|
|
1044
|
+
} else {
|
|
1045
|
+
return Err(IsccError::InvalidInput(
|
|
1046
|
+
"mixed SubTypes among Content/Semantic units".into(),
|
|
1047
|
+
));
|
|
1048
|
+
}
|
|
1049
|
+
} else if decoded.len() == 2 {
|
|
1050
|
+
codec::SubType::Sum
|
|
1051
|
+
} else {
|
|
1052
|
+
codec::SubType::IsccNone
|
|
1053
|
+
}
|
|
1054
|
+
};
|
|
1055
|
+
|
|
1056
|
+
// Step 10–11: Get optional MainTypes and encode
|
|
1057
|
+
let optional_types = &main_types[..n - 2];
|
|
1058
|
+
let encoded_length = codec::encode_units(optional_types)?;
|
|
1059
|
+
|
|
1060
|
+
// Step 12: Build digest body
|
|
1061
|
+
let bytes_per_unit = if is_wide { 16 } else { 8 };
|
|
1062
|
+
let mut digest = Vec::with_capacity(decoded.len() * bytes_per_unit);
|
|
1063
|
+
for (_, _, _, _, tail) in &decoded {
|
|
1064
|
+
let take = bytes_per_unit.min(tail.len());
|
|
1065
|
+
digest.extend_from_slice(&tail[..take]);
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
// Step 13–14: Encode header + digest as base32
|
|
1069
|
+
let header = codec::encode_header(
|
|
1070
|
+
codec::MainType::Iscc,
|
|
1071
|
+
st,
|
|
1072
|
+
codec::Version::V0,
|
|
1073
|
+
encoded_length,
|
|
1074
|
+
)?;
|
|
1075
|
+
let mut code_bytes = header;
|
|
1076
|
+
code_bytes.extend_from_slice(&digest);
|
|
1077
|
+
let code = codec::encode_base32(&code_bytes);
|
|
1078
|
+
|
|
1079
|
+
// Step 15: Return with prefix
|
|
1080
|
+
Ok(IsccCodeResult {
|
|
1081
|
+
iscc: format!("ISCC:{code}"),
|
|
1082
|
+
})
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
/// Generate a composite ISCC-CODE from a file in a single pass.
|
|
1086
|
+
///
|
|
1087
|
+
/// Opens the file at `path`, reads it with an optimal buffer size, and feeds
|
|
1088
|
+
/// both `DataHasher` (CDC/MinHash) and `InstanceHasher` (BLAKE3) from the
|
|
1089
|
+
/// same read buffer. Composes the final ISCC-CODE from the Data-Code and
|
|
1090
|
+
/// Instance-Code internally. This avoids multiple passes over the file and
|
|
1091
|
+
/// eliminates per-chunk FFI overhead in language bindings.
|
|
1092
|
+
///
|
|
1093
|
+
/// When `add_units` is `true`, the result includes the individual Data-Code
|
|
1094
|
+
/// and Instance-Code ISCC strings at the requested `bits` precision.
|
|
1095
|
+
pub fn gen_sum_code_v0(
|
|
1096
|
+
path: &std::path::Path,
|
|
1097
|
+
bits: u32,
|
|
1098
|
+
wide: bool,
|
|
1099
|
+
add_units: bool,
|
|
1100
|
+
) -> IsccResult<SumCodeResult> {
|
|
1101
|
+
use std::io::Read;
|
|
1102
|
+
|
|
1103
|
+
let mut file = std::fs::File::open(path)
|
|
1104
|
+
.map_err(|e| IsccError::InvalidInput(format!("Cannot open file: {e}")))?;
|
|
1105
|
+
|
|
1106
|
+
let mut hasher = streaming::SumHasher::new();
|
|
1107
|
+
|
|
1108
|
+
let mut buf = vec![0u8; IO_READ_SIZE];
|
|
1109
|
+
loop {
|
|
1110
|
+
let n = file
|
|
1111
|
+
.read(&mut buf)
|
|
1112
|
+
.map_err(|e| IsccError::InvalidInput(format!("Cannot read file: {e}")))?;
|
|
1113
|
+
if n == 0 {
|
|
1114
|
+
break;
|
|
1115
|
+
}
|
|
1116
|
+
hasher.update(&buf[..n]);
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
hasher.finalize(bits, wide, add_units)
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
/// Generate an ISCC-IDv1 from a timestamp and a HUB-ID (experimental).
|
|
1123
|
+
///
|
|
1124
|
+
/// The ISCC-IDv1 is a 64-bit identifier packing a 52-bit microsecond UTC
|
|
1125
|
+
/// timestamp (since the UNIX epoch) into the high bits and a 12-bit HUB-ID
|
|
1126
|
+
/// (0-4095) into the low bits, then encoding it as an ISCC-ID unit with the
|
|
1127
|
+
/// given `realm` as SubType and Version `V1`.
|
|
1128
|
+
///
|
|
1129
|
+
/// `realm` selects the ID realm: `0` for testnet, `1` for the first
|
|
1130
|
+
/// operational mainnet. This function is clock-free — the caller supplies the
|
|
1131
|
+
/// timestamp; there is no dependency on the system clock.
|
|
1132
|
+
///
|
|
1133
|
+
/// **Experimental:** the ISCC-IDv1 format is not yet part of ISO 24138 and may
|
|
1134
|
+
/// change. There is no dedicated decoder — use [`iscc_decode`] to decode.
|
|
1135
|
+
///
|
|
1136
|
+
/// # Errors
|
|
1137
|
+
///
|
|
1138
|
+
/// Returns `IsccError::InvalidInput` if `timestamp >= 2^52`, `hub_id >= 2^12`,
|
|
1139
|
+
/// or `realm` is not `0` or `1`. Failures are reported in that order.
|
|
1140
|
+
pub fn gen_iscc_id_v1(timestamp: u64, hub_id: u16, realm: u8) -> IsccResult<IsccIdResult> {
|
|
1141
|
+
if timestamp >= (1u64 << 52) {
|
|
1142
|
+
return Err(IsccError::InvalidInput("Timestamp overflow".into()));
|
|
1143
|
+
}
|
|
1144
|
+
if hub_id >= (1u16 << 12) {
|
|
1145
|
+
return Err(IsccError::InvalidInput("HUB-ID overflow".into()));
|
|
1146
|
+
}
|
|
1147
|
+
if realm != 0 && realm != 1 {
|
|
1148
|
+
return Err(IsccError::InvalidInput(
|
|
1149
|
+
"Realm-ID must be 0 (test) or 1 (operational)".into(),
|
|
1150
|
+
));
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
// Pack 52-bit timestamp into the high bits and 12-bit HUB-ID into the low bits.
|
|
1154
|
+
let body = (timestamp << 12) | u64::from(hub_id);
|
|
1155
|
+
let digest = body.to_be_bytes();
|
|
1156
|
+
|
|
1157
|
+
let component = codec::encode_component(
|
|
1158
|
+
codec::MainType::Id,
|
|
1159
|
+
codec::SubType::try_from(realm)?,
|
|
1160
|
+
codec::Version::V1,
|
|
1161
|
+
64,
|
|
1162
|
+
&digest,
|
|
1163
|
+
)?;
|
|
1164
|
+
Ok(IsccIdResult {
|
|
1165
|
+
iscc: format!("ISCC:{component}"),
|
|
1166
|
+
})
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
#[cfg(test)]
|
|
1170
|
+
mod tests {
|
|
1171
|
+
use super::*;
|
|
1172
|
+
|
|
1173
|
+
#[test]
|
|
1174
|
+
fn test_gen_iscc_id_v1_golden() {
|
|
1175
|
+
// Golden vector: timestamp/hub-id/realm packed and encoded as ISCC-IDv1.
|
|
1176
|
+
let result = gen_iscc_id_v1(1751831876325218, 1, 0).unwrap();
|
|
1177
|
+
assert_eq!(result.iscc, "ISCC:MAIGHFECJMOPMIAB");
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
#[test]
|
|
1181
|
+
fn test_gen_iscc_id_v1_round_trip() {
|
|
1182
|
+
// Round-trip every corner of the realm × hub_id × timestamp space via iscc_decode.
|
|
1183
|
+
let max_ts = (1u64 << 52) - 1;
|
|
1184
|
+
for realm in [0u8, 1u8] {
|
|
1185
|
+
for hub_id in [0u16, 4095u16] {
|
|
1186
|
+
for timestamp in [0u64, max_ts] {
|
|
1187
|
+
let result = gen_iscc_id_v1(timestamp, hub_id, realm).unwrap();
|
|
1188
|
+
let (mt, st, vs, li, digest) = iscc_decode(&result.iscc).unwrap();
|
|
1189
|
+
assert_eq!(mt, 6, "MainType Id");
|
|
1190
|
+
assert_eq!(st, realm, "SubType is realm");
|
|
1191
|
+
assert_eq!(vs, 1, "Version V1");
|
|
1192
|
+
assert_eq!(li, 0, "64-bit length index");
|
|
1193
|
+
assert_eq!(digest.len(), 8, "8-byte body");
|
|
1194
|
+
let body = u64::from_be_bytes(digest.try_into().unwrap());
|
|
1195
|
+
assert_eq!(body >> 12, timestamp, "timestamp in high 52 bits");
|
|
1196
|
+
assert_eq!(body & 0xFFF, u64::from(hub_id), "hub_id in low 12 bits");
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
#[test]
|
|
1203
|
+
fn test_gen_iscc_id_v1_validation_ordering() {
|
|
1204
|
+
// Timestamp overflow wins over an also-invalid hub_id and realm.
|
|
1205
|
+
let err = gen_iscc_id_v1(1u64 << 52, 4096, 2).unwrap_err();
|
|
1206
|
+
assert_eq!(err.to_string(), "invalid input: Timestamp overflow");
|
|
1207
|
+
|
|
1208
|
+
// HUB-ID overflow wins over an also-invalid realm.
|
|
1209
|
+
let err = gen_iscc_id_v1(0, 1u16 << 12, 2).unwrap_err();
|
|
1210
|
+
assert_eq!(err.to_string(), "invalid input: HUB-ID overflow");
|
|
1211
|
+
|
|
1212
|
+
// Realm out of range is the last check.
|
|
1213
|
+
let err = gen_iscc_id_v1(0, 0, 2).unwrap_err();
|
|
1214
|
+
assert_eq!(
|
|
1215
|
+
err.to_string(),
|
|
1216
|
+
"invalid input: Realm-ID must be 0 (test) or 1 (operational)"
|
|
1217
|
+
);
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
#[cfg(feature = "meta-code")]
|
|
1221
|
+
#[test]
|
|
1222
|
+
fn test_gen_meta_code_v0_title_only() {
|
|
1223
|
+
let result = gen_meta_code_v0("Die Unendliche Geschichte", None, None, 64).unwrap();
|
|
1224
|
+
assert_eq!(result.iscc, "ISCC:AAAZXZ6OU74YAZIM");
|
|
1225
|
+
assert_eq!(result.name, "Die Unendliche Geschichte");
|
|
1226
|
+
assert_eq!(result.description, None);
|
|
1227
|
+
assert_eq!(result.meta, None);
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
#[cfg(feature = "meta-code")]
|
|
1231
|
+
#[test]
|
|
1232
|
+
fn test_gen_meta_code_v0_title_description() {
|
|
1233
|
+
let result = gen_meta_code_v0(
|
|
1234
|
+
"Die Unendliche Geschichte",
|
|
1235
|
+
Some("Von Michael Ende"),
|
|
1236
|
+
None,
|
|
1237
|
+
64,
|
|
1238
|
+
)
|
|
1239
|
+
.unwrap();
|
|
1240
|
+
assert_eq!(result.iscc, "ISCC:AAAZXZ6OU4E45RB5");
|
|
1241
|
+
assert_eq!(result.name, "Die Unendliche Geschichte");
|
|
1242
|
+
assert_eq!(result.description, Some("Von Michael Ende".to_string()));
|
|
1243
|
+
assert_eq!(result.meta, None);
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
#[cfg(feature = "meta-code")]
|
|
1247
|
+
#[test]
|
|
1248
|
+
fn test_gen_meta_code_v0_json_meta() {
|
|
1249
|
+
let result = gen_meta_code_v0("Hello", None, Some(r#"{"some":"object"}"#), 64).unwrap();
|
|
1250
|
+
assert_eq!(result.iscc, "ISCC:AAAWKLHFXN63LHL2");
|
|
1251
|
+
assert!(result.meta.is_some());
|
|
1252
|
+
assert!(
|
|
1253
|
+
result
|
|
1254
|
+
.meta
|
|
1255
|
+
.unwrap()
|
|
1256
|
+
.starts_with("data:application/json;base64,")
|
|
1257
|
+
);
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
#[cfg(feature = "meta-code")]
|
|
1261
|
+
#[test]
|
|
1262
|
+
fn test_gen_meta_code_v0_data_url_meta() {
|
|
1263
|
+
let result = gen_meta_code_v0(
|
|
1264
|
+
"Hello",
|
|
1265
|
+
None,
|
|
1266
|
+
Some("data:application/json;charset=utf-8;base64,eyJzb21lIjogIm9iamVjdCJ9"),
|
|
1267
|
+
64,
|
|
1268
|
+
)
|
|
1269
|
+
.unwrap();
|
|
1270
|
+
assert_eq!(result.iscc, "ISCC:AAAWKLHFXN43ICP2");
|
|
1271
|
+
// Data-URL is passed through as-is
|
|
1272
|
+
assert_eq!(
|
|
1273
|
+
result.meta,
|
|
1274
|
+
Some("data:application/json;charset=utf-8;base64,eyJzb21lIjogIm9iamVjdCJ9".to_string())
|
|
1275
|
+
);
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
/// `json_to_data_url` and the `meta` field of `gen_meta_code_v0` agree for JSON input.
|
|
1279
|
+
#[cfg(feature = "meta-code")]
|
|
1280
|
+
#[test]
|
|
1281
|
+
fn test_json_to_data_url_matches_gen_meta_code_v0_meta() {
|
|
1282
|
+
let inputs = [
|
|
1283
|
+
r#"{"some":"object"}"#,
|
|
1284
|
+
r#"{"b": 1.0, "a": [1e20, "x"]}"#,
|
|
1285
|
+
r#"{"@context": "https://schema.org", "name": "Hello"}"#,
|
|
1286
|
+
];
|
|
1287
|
+
for json in inputs {
|
|
1288
|
+
let meta = gen_meta_code_v0("Hello", None, Some(json), 64)
|
|
1289
|
+
.unwrap()
|
|
1290
|
+
.meta;
|
|
1291
|
+
assert_eq!(meta, Some(json_to_data_url(json).unwrap()), "{json}");
|
|
1292
|
+
}
|
|
1293
|
+
let ld_meta = json_to_data_url(inputs[2]).unwrap();
|
|
1294
|
+
assert!(ld_meta.starts_with("data:application/ld+json;base64,"));
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
/// Each JSON entry point keeps its own parse-error prefix.
|
|
1298
|
+
#[cfg(feature = "meta-code")]
|
|
1299
|
+
#[test]
|
|
1300
|
+
fn test_json_parse_error_texts() {
|
|
1301
|
+
let meta_err = gen_meta_code_v0("Hello", None, Some("{bad"), 64)
|
|
1302
|
+
.unwrap_err()
|
|
1303
|
+
.to_string();
|
|
1304
|
+
assert!(
|
|
1305
|
+
meta_err.starts_with("invalid input: invalid JSON in meta: "),
|
|
1306
|
+
"{meta_err}"
|
|
1307
|
+
);
|
|
1308
|
+
let url_err = json_to_data_url("{bad").unwrap_err().to_string();
|
|
1309
|
+
assert!(
|
|
1310
|
+
url_err.starts_with("invalid input: invalid JSON: "),
|
|
1311
|
+
"{url_err}"
|
|
1312
|
+
);
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
/// Verify that JSON metadata with float values is canonicalized per RFC 8785 (JCS).
|
|
1316
|
+
///
|
|
1317
|
+
/// JCS serializes `1.0` as `1` (integer form), while `serde_json` preserves `1.0`.
|
|
1318
|
+
/// This causes different canonical bytes, different metahash, and different ISCC codes.
|
|
1319
|
+
/// Expected values generated by `iscc-core` with `jcs.canonicalize({"value": 1.0})`.
|
|
1320
|
+
#[cfg(feature = "meta-code")]
|
|
1321
|
+
#[test]
|
|
1322
|
+
fn test_gen_meta_code_v0_jcs_float_canonicalization() {
|
|
1323
|
+
// JCS canonicalizes {"value": 1.0} → {"value":1} (integer form)
|
|
1324
|
+
// serde_json produces {"value":1.0} (preserves float notation)
|
|
1325
|
+
let result = gen_meta_code_v0("Test", None, Some(r#"{"value":1.0}"#), 64).unwrap();
|
|
1326
|
+
|
|
1327
|
+
// Expected values from iscc-core (Python) using jcs.canonicalize()
|
|
1328
|
+
assert_eq!(
|
|
1329
|
+
result.iscc, "ISCC:AAAX4GX3RZH2I6QZ",
|
|
1330
|
+
"ISCC mismatch: canonicalize_json must use RFC 8785 (JCS) canonicalization"
|
|
1331
|
+
);
|
|
1332
|
+
assert_eq!(
|
|
1333
|
+
result.meta,
|
|
1334
|
+
Some("data:application/json;base64,eyJ2YWx1ZSI6MX0=".to_string()),
|
|
1335
|
+
"meta Data-URL mismatch: JCS should serialize 1.0 as 1"
|
|
1336
|
+
);
|
|
1337
|
+
assert_eq!(
|
|
1338
|
+
result.metahash, "1e2010b291d392b6999ffe4aa4661fb343fc371fca3bfb5bb4e8d8226fdf85743232",
|
|
1339
|
+
"metahash mismatch: canonical bytes differ between JCS and serde_json"
|
|
1340
|
+
);
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
/// Verify JCS number formatting for large floats (scientific notation edge case).
|
|
1344
|
+
///
|
|
1345
|
+
/// JCS serializes `1e20` as `100000000000000000000` (expanded integer form).
|
|
1346
|
+
/// Expected values generated by `iscc-core` with `jcs.canonicalize({"value": 1e20})`.
|
|
1347
|
+
#[cfg(feature = "meta-code")]
|
|
1348
|
+
#[test]
|
|
1349
|
+
fn test_gen_meta_code_v0_jcs_large_float_canonicalization() {
|
|
1350
|
+
let result = gen_meta_code_v0("Test", None, Some(r#"{"value":1e20}"#), 64).unwrap();
|
|
1351
|
+
|
|
1352
|
+
assert_eq!(
|
|
1353
|
+
result.iscc, "ISCC:AAAX4GX3R32YH5P7",
|
|
1354
|
+
"ISCC mismatch: JCS should expand 1e20 to 100000000000000000000"
|
|
1355
|
+
);
|
|
1356
|
+
assert_eq!(
|
|
1357
|
+
result.meta,
|
|
1358
|
+
Some(
|
|
1359
|
+
"data:application/json;base64,eyJ2YWx1ZSI6MTAwMDAwMDAwMDAwMDAwMDAwMDAwfQ=="
|
|
1360
|
+
.to_string()
|
|
1361
|
+
),
|
|
1362
|
+
"meta Data-URL mismatch: JCS should expand large float to integer form"
|
|
1363
|
+
);
|
|
1364
|
+
assert_eq!(
|
|
1365
|
+
result.metahash, "1e201ff83c1822c348717658a0b4713739646da7c59832691b337a457416ddd1c73d",
|
|
1366
|
+
"metahash mismatch: canonical bytes differ for large float"
|
|
1367
|
+
);
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
#[cfg(feature = "meta-code")]
|
|
1371
|
+
#[test]
|
|
1372
|
+
fn test_gen_meta_code_v0_invalid_json() {
|
|
1373
|
+
assert!(matches!(
|
|
1374
|
+
gen_meta_code_v0("test", None, Some("not json"), 64),
|
|
1375
|
+
Err(IsccError::InvalidInput(_))
|
|
1376
|
+
));
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
#[cfg(feature = "meta-code")]
|
|
1380
|
+
#[test]
|
|
1381
|
+
fn test_gen_meta_code_v0_invalid_data_url() {
|
|
1382
|
+
assert!(matches!(
|
|
1383
|
+
gen_meta_code_v0("test", None, Some("data:no-comma-here"), 64),
|
|
1384
|
+
Err(IsccError::InvalidInput(_))
|
|
1385
|
+
));
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
#[cfg(feature = "meta-code")]
|
|
1389
|
+
#[test]
|
|
1390
|
+
fn test_gen_meta_code_v0_conformance() {
|
|
1391
|
+
let data = conformance::test_data().unwrap();
|
|
1392
|
+
let cases = conformance::cases(&data, "gen_meta_code_v0").unwrap();
|
|
1393
|
+
|
|
1394
|
+
let mut tested = 0;
|
|
1395
|
+
|
|
1396
|
+
for (tc_name, tc) in cases {
|
|
1397
|
+
let inputs = conformance::meta_inputs(tc)
|
|
1398
|
+
.unwrap_or_else(|| panic!("unparsable inputs in {tc_name}"));
|
|
1399
|
+
let expected_iscc = conformance::expected_iscc(tc).unwrap();
|
|
1400
|
+
let expected_metahash = tc["outputs"]["metahash"].as_str().unwrap();
|
|
1401
|
+
|
|
1402
|
+
// Verify ISCC output from struct
|
|
1403
|
+
let result = gen_meta_code_v0(
|
|
1404
|
+
inputs.name,
|
|
1405
|
+
inputs.description,
|
|
1406
|
+
inputs.meta.as_deref(),
|
|
1407
|
+
inputs.bits,
|
|
1408
|
+
)
|
|
1409
|
+
.unwrap_or_else(|e| panic!("gen_meta_code_v0 failed for {tc_name}: {e}"));
|
|
1410
|
+
assert_eq!(
|
|
1411
|
+
result.iscc, expected_iscc,
|
|
1412
|
+
"ISCC mismatch in test case {tc_name}"
|
|
1413
|
+
);
|
|
1414
|
+
|
|
1415
|
+
// Verify metahash from struct
|
|
1416
|
+
assert_eq!(
|
|
1417
|
+
result.metahash, expected_metahash,
|
|
1418
|
+
"metahash mismatch in test case {tc_name}"
|
|
1419
|
+
);
|
|
1420
|
+
|
|
1421
|
+
// Verify name from struct
|
|
1422
|
+
if let Some(expected_name) = tc["outputs"].get("name") {
|
|
1423
|
+
let expected_name = expected_name.as_str().unwrap();
|
|
1424
|
+
assert_eq!(
|
|
1425
|
+
result.name, expected_name,
|
|
1426
|
+
"name mismatch in test case {tc_name}"
|
|
1427
|
+
);
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
// Verify description from struct
|
|
1431
|
+
if let Some(expected_desc) = tc["outputs"].get("description") {
|
|
1432
|
+
let expected_desc = expected_desc.as_str().unwrap();
|
|
1433
|
+
assert_eq!(
|
|
1434
|
+
result.description.as_deref(),
|
|
1435
|
+
Some(expected_desc),
|
|
1436
|
+
"description mismatch in test case {tc_name}"
|
|
1437
|
+
);
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
// Verify meta from struct
|
|
1441
|
+
if inputs.meta.is_some() {
|
|
1442
|
+
assert!(
|
|
1443
|
+
result.meta.is_some(),
|
|
1444
|
+
"meta should be present in test case {tc_name}"
|
|
1445
|
+
);
|
|
1446
|
+
} else {
|
|
1447
|
+
assert!(
|
|
1448
|
+
result.meta.is_none(),
|
|
1449
|
+
"meta should be absent in test case {tc_name}"
|
|
1450
|
+
);
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
tested += 1;
|
|
1454
|
+
}
|
|
1455
|
+
|
|
1456
|
+
assert_eq!(tested, 20, "expected 20 conformance tests to run");
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
#[cfg(feature = "text-processing")]
|
|
1460
|
+
#[test]
|
|
1461
|
+
fn test_gen_text_code_v0_empty() {
|
|
1462
|
+
let result = gen_text_code_v0("", 64).unwrap();
|
|
1463
|
+
assert_eq!(result.iscc, "ISCC:EAASL4F2WZY7KBXB");
|
|
1464
|
+
assert_eq!(result.characters, 0);
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
#[cfg(feature = "text-processing")]
|
|
1468
|
+
#[test]
|
|
1469
|
+
fn test_gen_text_code_v0_hello_world() {
|
|
1470
|
+
let result = gen_text_code_v0("Hello World", 64).unwrap();
|
|
1471
|
+
assert_eq!(result.iscc, "ISCC:EAASKDNZNYGUUF5A");
|
|
1472
|
+
assert_eq!(result.characters, 10); // "helloworld" after collapse
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
#[cfg(feature = "text-processing")]
|
|
1476
|
+
#[test]
|
|
1477
|
+
fn test_gen_text_code_v0_conformance() {
|
|
1478
|
+
let data = conformance::test_data().unwrap();
|
|
1479
|
+
let cases = conformance::cases(&data, "gen_text_code_v0").unwrap();
|
|
1480
|
+
|
|
1481
|
+
let mut tested = 0;
|
|
1482
|
+
|
|
1483
|
+
for (tc_name, tc) in cases {
|
|
1484
|
+
let (input_text, bits) = conformance::text_inputs(tc)
|
|
1485
|
+
.unwrap_or_else(|| panic!("unparsable inputs in {tc_name}"));
|
|
1486
|
+
let expected_iscc = conformance::expected_iscc(tc).unwrap();
|
|
1487
|
+
let expected_chars = tc["outputs"]["characters"].as_u64().unwrap() as usize;
|
|
1488
|
+
|
|
1489
|
+
// Verify ISCC output from struct
|
|
1490
|
+
let result = gen_text_code_v0(input_text, bits)
|
|
1491
|
+
.unwrap_or_else(|e| panic!("gen_text_code_v0 failed for {tc_name}: {e}"));
|
|
1492
|
+
assert_eq!(
|
|
1493
|
+
result.iscc, expected_iscc,
|
|
1494
|
+
"ISCC mismatch in test case {tc_name}"
|
|
1495
|
+
);
|
|
1496
|
+
|
|
1497
|
+
// Verify character count from struct
|
|
1498
|
+
assert_eq!(
|
|
1499
|
+
result.characters, expected_chars,
|
|
1500
|
+
"character count mismatch in test case {tc_name}"
|
|
1501
|
+
);
|
|
1502
|
+
|
|
1503
|
+
tested += 1;
|
|
1504
|
+
}
|
|
1505
|
+
|
|
1506
|
+
assert_eq!(tested, 5, "expected 5 conformance tests to run");
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
#[test]
|
|
1510
|
+
fn test_gen_image_code_v0_all_black() {
|
|
1511
|
+
let pixels = vec![0u8; 1024];
|
|
1512
|
+
let result = gen_image_code_v0(&pixels, 64).unwrap();
|
|
1513
|
+
assert_eq!(result.iscc, "ISCC:EEAQAAAAAAAAAAAA");
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
#[test]
|
|
1517
|
+
fn test_gen_image_code_v0_all_white() {
|
|
1518
|
+
let pixels = vec![255u8; 1024];
|
|
1519
|
+
let result = gen_image_code_v0(&pixels, 128).unwrap();
|
|
1520
|
+
assert_eq!(result.iscc, "ISCC:EEBYAAAAAAAAAAAAAAAAAAAAAAAAA");
|
|
1521
|
+
}
|
|
1522
|
+
|
|
1523
|
+
#[test]
|
|
1524
|
+
fn test_gen_image_code_v0_invalid_pixel_count() {
|
|
1525
|
+
assert!(gen_image_code_v0(&[0u8; 100], 64).is_err());
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
#[test]
|
|
1529
|
+
fn test_soft_hash_image_v0_256_quadrant_layout() {
|
|
1530
|
+
// Blocks follow the top-left, top-right, bottom-left and bottom-right 8×8 DCT squares
|
|
1531
|
+
let data = conformance::test_data().unwrap();
|
|
1532
|
+
let tc = &conformance::cases(&data, "gen_image_code_v0").unwrap()["test_0003_img_256"];
|
|
1533
|
+
let (pixels, _) = conformance::image_inputs(tc).unwrap();
|
|
1534
|
+
let digest = soft_hash_image_v0(&pixels, 256).unwrap();
|
|
1535
|
+
|
|
1536
|
+
let rows: Vec<Vec<f64>> = pixels
|
|
1537
|
+
.chunks(32)
|
|
1538
|
+
.map(|row| dct::alg_dct(&row.iter().map(|&p| p as f64).collect::<Vec<_>>()).unwrap())
|
|
1539
|
+
.collect();
|
|
1540
|
+
let cols: Vec<Vec<f64>> = transpose_matrix(&rows)
|
|
1541
|
+
.iter()
|
|
1542
|
+
.map(|col| dct::alg_dct(col).unwrap())
|
|
1543
|
+
.collect();
|
|
1544
|
+
let matrix = transpose_matrix(&cols);
|
|
1545
|
+
|
|
1546
|
+
for (i, (x, y)) in [(0, 0), (8, 0), (0, 8), (8, 8)].into_iter().enumerate() {
|
|
1547
|
+
let square: Vec<f64> = (y..y + 8)
|
|
1548
|
+
.flat_map(|r| (x..x + 8).map(move |c| (r, c)))
|
|
1549
|
+
.map(|(r, c)| matrix[r][c])
|
|
1550
|
+
.collect();
|
|
1551
|
+
let median = compute_median(&square);
|
|
1552
|
+
let bits: Vec<bool> = square.iter().map(|&v| v > median).collect();
|
|
1553
|
+
assert_eq!(
|
|
1554
|
+
digest[i * 8..(i + 1) * 8],
|
|
1555
|
+
bits_to_bytes(&bits)[..],
|
|
1556
|
+
"block {i} does not match the 8×8 square at ({x}, {y})"
|
|
1557
|
+
);
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
#[test]
|
|
1562
|
+
fn test_gen_audio_code_v0_empty() {
|
|
1563
|
+
let result = gen_audio_code_v0(&[], 64).unwrap();
|
|
1564
|
+
assert_eq!(result.iscc, "ISCC:EIAQAAAAAAAAAAAA");
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
#[test]
|
|
1568
|
+
fn test_gen_audio_code_v0_single() {
|
|
1569
|
+
let result = gen_audio_code_v0(&[1], 128).unwrap();
|
|
1570
|
+
assert_eq!(result.iscc, "ISCC:EIBQAAAAAEAAAAABAAAAAAAAAAAAA");
|
|
1571
|
+
}
|
|
1572
|
+
|
|
1573
|
+
#[test]
|
|
1574
|
+
fn test_gen_audio_code_v0_negative() {
|
|
1575
|
+
let result = gen_audio_code_v0(&[-1, 0, 1], 256).unwrap();
|
|
1576
|
+
assert_eq!(
|
|
1577
|
+
result.iscc,
|
|
1578
|
+
"ISCC:EIDQAAAAAH777777AAAAAAAAAAAACAAAAAAP777774AAAAAAAAAAAAI"
|
|
1579
|
+
);
|
|
1580
|
+
}
|
|
1581
|
+
|
|
1582
|
+
#[test]
|
|
1583
|
+
fn test_array_split_even() {
|
|
1584
|
+
let data = vec![1, 2, 3, 4];
|
|
1585
|
+
let parts = array_split(&data, 4);
|
|
1586
|
+
assert_eq!(parts, vec![&[1][..], &[2][..], &[3][..], &[4][..]]);
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
#[test]
|
|
1590
|
+
fn test_array_split_remainder() {
|
|
1591
|
+
let data = vec![1, 2, 3, 4, 5];
|
|
1592
|
+
let parts = array_split(&data, 3);
|
|
1593
|
+
assert_eq!(parts, vec![&[1, 2][..], &[3, 4][..], &[5][..]]);
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
#[test]
|
|
1597
|
+
fn test_array_split_more_parts_than_elements() {
|
|
1598
|
+
let data = vec![1, 2];
|
|
1599
|
+
let parts = array_split(&data, 4);
|
|
1600
|
+
assert_eq!(
|
|
1601
|
+
parts,
|
|
1602
|
+
vec![&[1][..], &[2][..], &[][..] as &[i32], &[][..] as &[i32]]
|
|
1603
|
+
);
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
#[test]
|
|
1607
|
+
fn test_array_split_empty() {
|
|
1608
|
+
let data: Vec<i32> = vec![];
|
|
1609
|
+
let parts = array_split(&data, 3);
|
|
1610
|
+
assert_eq!(
|
|
1611
|
+
parts,
|
|
1612
|
+
vec![&[][..] as &[i32], &[][..] as &[i32], &[][..] as &[i32]]
|
|
1613
|
+
);
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
#[test]
|
|
1617
|
+
fn test_soft_hash_video_v0_rejects_longer_later_sig() {
|
|
1618
|
+
let frames: Vec<Vec<i32>> = vec![vec![0; 380], vec![0; 381]];
|
|
1619
|
+
let err = soft_hash_video_v0(&frames, 64).unwrap_err();
|
|
1620
|
+
assert!(
|
|
1621
|
+
matches!(&err, IsccError::InvalidInput(msg) if msg == "frame_sigs[1] has length 381, expected 380"),
|
|
1622
|
+
"unexpected error: {err:?}"
|
|
1623
|
+
);
|
|
1624
|
+
}
|
|
1625
|
+
|
|
1626
|
+
#[test]
|
|
1627
|
+
fn test_soft_hash_video_v0_rejects_shorter_later_sig() {
|
|
1628
|
+
let frames: Vec<Vec<i32>> = vec![vec![0; 380], vec![0; 379]];
|
|
1629
|
+
let err = soft_hash_video_v0(&frames, 64).unwrap_err();
|
|
1630
|
+
assert!(
|
|
1631
|
+
matches!(&err, IsccError::InvalidInput(msg) if msg == "frame_sigs[1] has length 379, expected 380"),
|
|
1632
|
+
"unexpected error: {err:?}"
|
|
1633
|
+
);
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
#[test]
|
|
1637
|
+
fn test_soft_hash_video_v0_rejects_ragged_reversed_order() {
|
|
1638
|
+
let frames: Vec<Vec<i32>> = vec![vec![0; 381], vec![0; 380]];
|
|
1639
|
+
let err = soft_hash_video_v0(&frames, 64).unwrap_err();
|
|
1640
|
+
assert!(
|
|
1641
|
+
matches!(&err, IsccError::InvalidInput(msg) if msg == "frame_sigs[1] has length 380, expected 381"),
|
|
1642
|
+
"unexpected error: {err:?}"
|
|
1643
|
+
);
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
#[test]
|
|
1647
|
+
fn test_soft_hash_video_v0_reports_first_mismatch() {
|
|
1648
|
+
let frames: Vec<Vec<i32>> = vec![vec![0; 380], vec![0; 380], vec![1; 382], vec![0; 1]];
|
|
1649
|
+
let err = soft_hash_video_v0(&frames, 64).unwrap_err();
|
|
1650
|
+
assert!(
|
|
1651
|
+
matches!(&err, IsccError::InvalidInput(msg) if msg == "frame_sigs[2] has length 382, expected 380"),
|
|
1652
|
+
"unexpected error: {err:?}"
|
|
1653
|
+
);
|
|
1654
|
+
}
|
|
1655
|
+
|
|
1656
|
+
#[test]
|
|
1657
|
+
fn test_gen_video_code_v0_rejects_ragged_frames() {
|
|
1658
|
+
let frames: Vec<Vec<i32>> = vec![vec![0; 380], vec![0; 381]];
|
|
1659
|
+
assert!(matches!(
|
|
1660
|
+
gen_video_code_v0(&frames, 64),
|
|
1661
|
+
Err(IsccError::InvalidInput(_))
|
|
1662
|
+
));
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1665
|
+
#[test]
|
|
1666
|
+
fn test_gen_video_code_v0_empty_frames() {
|
|
1667
|
+
let frames: Vec<Vec<i32>> = vec![];
|
|
1668
|
+
assert!(matches!(
|
|
1669
|
+
gen_video_code_v0(&frames, 64),
|
|
1670
|
+
Err(IsccError::InvalidInput(_))
|
|
1671
|
+
));
|
|
1672
|
+
}
|
|
1673
|
+
|
|
1674
|
+
#[test]
|
|
1675
|
+
fn test_gen_mixed_code_v0_conformance() {
|
|
1676
|
+
let data = conformance::test_data().unwrap();
|
|
1677
|
+
let cases = conformance::cases(&data, "gen_mixed_code_v0").unwrap();
|
|
1678
|
+
|
|
1679
|
+
let mut tested = 0;
|
|
1680
|
+
|
|
1681
|
+
for (tc_name, tc) in cases {
|
|
1682
|
+
let (codes, bits) = conformance::mixed_inputs(tc)
|
|
1683
|
+
.unwrap_or_else(|| panic!("unparsable inputs in {tc_name}"));
|
|
1684
|
+
let expected_iscc = conformance::expected_iscc(tc).unwrap();
|
|
1685
|
+
let expected_parts: Vec<&str> = tc["outputs"]["parts"]
|
|
1686
|
+
.as_array()
|
|
1687
|
+
.unwrap()
|
|
1688
|
+
.iter()
|
|
1689
|
+
.map(|v| v.as_str().unwrap())
|
|
1690
|
+
.collect();
|
|
1691
|
+
|
|
1692
|
+
let result = gen_mixed_code_v0(&codes, bits)
|
|
1693
|
+
.unwrap_or_else(|e| panic!("gen_mixed_code_v0 failed for {tc_name}: {e}"));
|
|
1694
|
+
assert_eq!(
|
|
1695
|
+
result.iscc, expected_iscc,
|
|
1696
|
+
"ISCC mismatch in test case {tc_name}"
|
|
1697
|
+
);
|
|
1698
|
+
|
|
1699
|
+
// Verify parts from struct match expected
|
|
1700
|
+
let result_parts: Vec<&str> = result.parts.iter().map(|s| s.as_str()).collect();
|
|
1701
|
+
assert_eq!(
|
|
1702
|
+
result_parts, expected_parts,
|
|
1703
|
+
"parts mismatch in test case {tc_name}"
|
|
1704
|
+
);
|
|
1705
|
+
|
|
1706
|
+
tested += 1;
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
assert_eq!(tested, 2, "expected 2 conformance tests to run");
|
|
1710
|
+
}
|
|
1711
|
+
|
|
1712
|
+
#[test]
|
|
1713
|
+
fn test_gen_mixed_code_v0_too_few_codes() {
|
|
1714
|
+
assert!(matches!(
|
|
1715
|
+
gen_mixed_code_v0(&["EUA6GIKXN42IQV3S"], 64),
|
|
1716
|
+
Err(IsccError::InvalidInput(_))
|
|
1717
|
+
));
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
#[test]
|
|
1721
|
+
fn test_gen_mixed_code_v0_bits_below_one_byte() {
|
|
1722
|
+
let codes = ["EUA6GIKXN42IQV3S", "EIAUKMOUIOYZCKA5"];
|
|
1723
|
+
for bits in 0..8 {
|
|
1724
|
+
assert!(
|
|
1725
|
+
matches!(
|
|
1726
|
+
gen_mixed_code_v0(&codes, bits),
|
|
1727
|
+
Err(IsccError::InvalidInput(_))
|
|
1728
|
+
),
|
|
1729
|
+
"bits {bits}"
|
|
1730
|
+
);
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1734
|
+
/// Build raw Content-Code bytes (header + body) for a given bit length.
|
|
1735
|
+
fn make_content_code_raw(stype: codec::SubType, bit_length: u32) -> Vec<u8> {
|
|
1736
|
+
let nbytes = (bit_length / 8) as usize;
|
|
1737
|
+
let body: Vec<u8> = (0..nbytes).map(|i| (i & 0xFF) as u8).collect();
|
|
1738
|
+
let base32 = codec::encode_component(
|
|
1739
|
+
codec::MainType::Content,
|
|
1740
|
+
stype,
|
|
1741
|
+
codec::Version::V0,
|
|
1742
|
+
bit_length,
|
|
1743
|
+
&body,
|
|
1744
|
+
)
|
|
1745
|
+
.unwrap();
|
|
1746
|
+
codec::decode_base32(&base32).unwrap()
|
|
1747
|
+
}
|
|
1748
|
+
|
|
1749
|
+
#[test]
|
|
1750
|
+
fn test_soft_hash_codes_v0_rejects_short_code() {
|
|
1751
|
+
// One code with 64 bits, one with only 32 bits — should reject when requesting 64
|
|
1752
|
+
let code_64 = make_content_code_raw(codec::SubType::None, 64);
|
|
1753
|
+
let code_32 = make_content_code_raw(codec::SubType::Image, 32);
|
|
1754
|
+
let result = soft_hash_codes_v0(&[code_64, code_32], 64);
|
|
1755
|
+
assert!(
|
|
1756
|
+
matches!(&result, Err(IsccError::InvalidInput(msg)) if msg.contains("too short")),
|
|
1757
|
+
"expected InvalidInput with 'too short', got {result:?}"
|
|
1758
|
+
);
|
|
1759
|
+
}
|
|
1760
|
+
|
|
1761
|
+
#[test]
|
|
1762
|
+
fn test_soft_hash_codes_v0_accepts_exact_length() {
|
|
1763
|
+
// Two codes with exactly 64 bits each — should succeed when requesting 64
|
|
1764
|
+
let code_a = make_content_code_raw(codec::SubType::None, 64);
|
|
1765
|
+
let code_b = make_content_code_raw(codec::SubType::Image, 64);
|
|
1766
|
+
let result = soft_hash_codes_v0(&[code_a, code_b], 64);
|
|
1767
|
+
assert!(result.is_ok(), "expected Ok, got {result:?}");
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
#[test]
|
|
1771
|
+
fn test_soft_hash_codes_v0_accepts_longer_codes() {
|
|
1772
|
+
// Two codes with 128 bits each — should succeed when requesting 64
|
|
1773
|
+
let code_a = make_content_code_raw(codec::SubType::None, 128);
|
|
1774
|
+
let code_b = make_content_code_raw(codec::SubType::Audio, 128);
|
|
1775
|
+
let result = soft_hash_codes_v0(&[code_a, code_b], 64);
|
|
1776
|
+
assert!(result.is_ok(), "expected Ok, got {result:?}");
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1779
|
+
#[test]
|
|
1780
|
+
fn test_gen_instance_code_v0_empty() {
|
|
1781
|
+
let result = gen_instance_code_v0(b"", 64).unwrap();
|
|
1782
|
+
assert_eq!(result.iscc, "ISCC:IAA26E2JXH27TING");
|
|
1783
|
+
assert_eq!(result.filesize, 0);
|
|
1784
|
+
assert_eq!(
|
|
1785
|
+
result.datahash,
|
|
1786
|
+
"1e20af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262"
|
|
1787
|
+
);
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
/// The one-shot datahash equals the multihash helper and the streaming result.
|
|
1791
|
+
#[test]
|
|
1792
|
+
fn test_gen_instance_code_v0_datahash_matches_multihash_and_streaming() {
|
|
1793
|
+
let inputs: [&[u8]; 4] = [b"", b"a", b"hello world", &[0xffu8; 70_000]];
|
|
1794
|
+
for data in inputs {
|
|
1795
|
+
let one_shot = gen_instance_code_v0(data, 64).unwrap();
|
|
1796
|
+
assert_eq!(one_shot.datahash, utils::multi_hash_blake3(data));
|
|
1797
|
+
let mut hasher = InstanceHasher::new();
|
|
1798
|
+
hasher.update(data);
|
|
1799
|
+
let streamed = hasher.finalize(64).unwrap();
|
|
1800
|
+
assert_eq!(one_shot.datahash, streamed.datahash);
|
|
1801
|
+
assert_eq!(one_shot.iscc, streamed.iscc);
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
#[test]
|
|
1806
|
+
fn test_gen_instance_code_v0_conformance() {
|
|
1807
|
+
let data = conformance::test_data().unwrap();
|
|
1808
|
+
let cases = conformance::cases(&data, "gen_instance_code_v0").unwrap();
|
|
1809
|
+
|
|
1810
|
+
for (name, tc) in cases {
|
|
1811
|
+
let (input_bytes, bits) = conformance::stream_inputs(tc)
|
|
1812
|
+
.unwrap_or_else(|| panic!("unparsable inputs in {name}"));
|
|
1813
|
+
let expected_iscc = conformance::expected_iscc(tc).unwrap();
|
|
1814
|
+
|
|
1815
|
+
let result = gen_instance_code_v0(&input_bytes, bits)
|
|
1816
|
+
.unwrap_or_else(|e| panic!("gen_instance_code_v0 failed for {name}: {e}"));
|
|
1817
|
+
assert_eq!(
|
|
1818
|
+
result.iscc, expected_iscc,
|
|
1819
|
+
"ISCC mismatch in test case {name}"
|
|
1820
|
+
);
|
|
1821
|
+
|
|
1822
|
+
// Verify datahash from struct
|
|
1823
|
+
if let Some(expected_datahash) = tc["outputs"].get("datahash") {
|
|
1824
|
+
let expected_datahash = expected_datahash.as_str().unwrap();
|
|
1825
|
+
assert_eq!(
|
|
1826
|
+
result.datahash, expected_datahash,
|
|
1827
|
+
"datahash mismatch in test case {name}"
|
|
1828
|
+
);
|
|
1829
|
+
}
|
|
1830
|
+
|
|
1831
|
+
// Verify filesize from struct
|
|
1832
|
+
if let Some(expected_filesize) = tc["outputs"].get("filesize") {
|
|
1833
|
+
let expected_filesize = expected_filesize.as_u64().unwrap();
|
|
1834
|
+
assert_eq!(
|
|
1835
|
+
result.filesize, expected_filesize,
|
|
1836
|
+
"filesize mismatch in test case {name}"
|
|
1837
|
+
);
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1840
|
+
// Also verify filesize matches input data length
|
|
1841
|
+
assert_eq!(
|
|
1842
|
+
result.filesize,
|
|
1843
|
+
input_bytes.len() as u64,
|
|
1844
|
+
"filesize should match input length in test case {name}"
|
|
1845
|
+
);
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
|
|
1849
|
+
#[test]
|
|
1850
|
+
fn test_gen_iscc_code_v0_too_few_codes() {
|
|
1851
|
+
assert!(matches!(
|
|
1852
|
+
gen_iscc_code_v0(&["AAAWKLHFPV6OPKDG"], false),
|
|
1853
|
+
Err(IsccError::InvalidInput(_))
|
|
1854
|
+
));
|
|
1855
|
+
}
|
|
1856
|
+
|
|
1857
|
+
#[test]
|
|
1858
|
+
fn test_gen_iscc_code_v0_missing_instance() {
|
|
1859
|
+
// Two Meta codes — missing Data and Instance
|
|
1860
|
+
assert!(matches!(
|
|
1861
|
+
gen_iscc_code_v0(&["AAAWKLHFPV6OPKDG", "AAAWKLHFPV6OPKDG"], false),
|
|
1862
|
+
Err(IsccError::InvalidInput(_))
|
|
1863
|
+
));
|
|
1864
|
+
}
|
|
1865
|
+
|
|
1866
|
+
#[test]
|
|
1867
|
+
fn test_gen_iscc_code_v0_short_code() {
|
|
1868
|
+
// Code too short (< 16 chars)
|
|
1869
|
+
assert!(matches!(
|
|
1870
|
+
gen_iscc_code_v0(&["AAAWKLHFPV6", "AAAWKLHFPV6OPKDG"], false),
|
|
1871
|
+
Err(IsccError::InvalidInput(_))
|
|
1872
|
+
));
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
/// Verify that a Data-URL with empty base64 payload enters the meta bytes path.
|
|
1876
|
+
///
|
|
1877
|
+
/// Python reference: `if meta:` is truthy for `"data:application/json;base64,"` (non-empty
|
|
1878
|
+
/// string), so it enters the meta branch with `payload = b""`. The result must have
|
|
1879
|
+
/// `meta = Some(...)` containing the original Data-URL and `metahash` equal to
|
|
1880
|
+
/// `multi_hash_blake3(&[])` (BLAKE3 of empty bytes).
|
|
1881
|
+
#[cfg(feature = "meta-code")]
|
|
1882
|
+
#[test]
|
|
1883
|
+
fn test_gen_meta_code_empty_data_url_enters_meta_branch() {
|
|
1884
|
+
let result =
|
|
1885
|
+
gen_meta_code_v0("Test", None, Some("data:application/json;base64,"), 64).unwrap();
|
|
1886
|
+
|
|
1887
|
+
// Result should be Ok
|
|
1888
|
+
assert_eq!(result.name, "Test");
|
|
1889
|
+
|
|
1890
|
+
// meta should contain the original Data-URL string (not None)
|
|
1891
|
+
assert_eq!(
|
|
1892
|
+
result.meta,
|
|
1893
|
+
Some("data:application/json;base64,".to_string()),
|
|
1894
|
+
"empty Data-URL payload should still enter meta branch"
|
|
1895
|
+
);
|
|
1896
|
+
|
|
1897
|
+
// metahash should be BLAKE3 of empty bytes
|
|
1898
|
+
let expected_metahash = utils::multi_hash_blake3(&[]);
|
|
1899
|
+
assert_eq!(
|
|
1900
|
+
result.metahash, expected_metahash,
|
|
1901
|
+
"metahash should be BLAKE3 of empty bytes"
|
|
1902
|
+
);
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1905
|
+
/// Verify that `soft_hash_meta_v0_with_bytes` with empty bytes produces the same
|
|
1906
|
+
/// digest as `soft_hash_meta_v0` with no extra text.
|
|
1907
|
+
///
|
|
1908
|
+
/// Python reference (`code_meta.py:142`): `if extra in {None, "", b""}:` returns
|
|
1909
|
+
/// name-only simhash without interleaving for all empty-like values.
|
|
1910
|
+
#[cfg(feature = "meta-code")]
|
|
1911
|
+
#[test]
|
|
1912
|
+
fn test_soft_hash_meta_v0_with_bytes_empty_equals_name_only() {
|
|
1913
|
+
let name_only = soft_hash_meta_v0("test", None);
|
|
1914
|
+
let empty_bytes = soft_hash_meta_v0_with_bytes("test", &[]);
|
|
1915
|
+
assert_eq!(
|
|
1916
|
+
name_only, empty_bytes,
|
|
1917
|
+
"empty bytes should produce same digest as name-only (no interleaving)"
|
|
1918
|
+
);
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
// ---- Algorithm constants tests ----
|
|
1922
|
+
|
|
1923
|
+
#[cfg(feature = "meta-code")]
|
|
1924
|
+
#[test]
|
|
1925
|
+
fn test_meta_trim_name_value() {
|
|
1926
|
+
assert_eq!(META_TRIM_NAME, 128);
|
|
1927
|
+
}
|
|
1928
|
+
|
|
1929
|
+
#[cfg(feature = "meta-code")]
|
|
1930
|
+
#[test]
|
|
1931
|
+
fn test_meta_trim_description_value() {
|
|
1932
|
+
assert_eq!(META_TRIM_DESCRIPTION, 4096);
|
|
1933
|
+
}
|
|
1934
|
+
|
|
1935
|
+
#[test]
|
|
1936
|
+
fn test_io_read_size_value() {
|
|
1937
|
+
assert_eq!(IO_READ_SIZE, 4_194_304);
|
|
1938
|
+
}
|
|
1939
|
+
|
|
1940
|
+
#[test]
|
|
1941
|
+
fn test_text_ngram_size_value() {
|
|
1942
|
+
assert_eq!(TEXT_NGRAM_SIZE, 13);
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
// ---- encode_component Tier 1 wrapper tests ----
|
|
1946
|
+
|
|
1947
|
+
/// Encode a known digest and verify the output matches the codec version.
|
|
1948
|
+
#[test]
|
|
1949
|
+
fn test_encode_component_matches_codec() {
|
|
1950
|
+
let digest = [0xABu8; 8];
|
|
1951
|
+
let tier1 = encode_component(3, 0, 0, 64, &digest).unwrap();
|
|
1952
|
+
let tier2 = codec::encode_component(
|
|
1953
|
+
codec::MainType::Data,
|
|
1954
|
+
codec::SubType::None,
|
|
1955
|
+
codec::Version::V0,
|
|
1956
|
+
64,
|
|
1957
|
+
&digest,
|
|
1958
|
+
)
|
|
1959
|
+
.unwrap();
|
|
1960
|
+
assert_eq!(tier1, tier2);
|
|
1961
|
+
}
|
|
1962
|
+
|
|
1963
|
+
/// Round-trip: encode a digest and verify the result is a valid ISCC unit.
|
|
1964
|
+
#[test]
|
|
1965
|
+
fn test_encode_component_round_trip() {
|
|
1966
|
+
let digest = [0x42u8; 32];
|
|
1967
|
+
let result = encode_component(0, 0, 0, 64, &digest).unwrap();
|
|
1968
|
+
// Meta-Code with 64-bit digest should start with "AA"
|
|
1969
|
+
assert!(!result.is_empty());
|
|
1970
|
+
}
|
|
1971
|
+
|
|
1972
|
+
/// Reject MainType::Iscc (value 5).
|
|
1973
|
+
#[test]
|
|
1974
|
+
fn test_encode_component_rejects_iscc() {
|
|
1975
|
+
let result = encode_component(5, 0, 0, 64, &[0u8; 8]);
|
|
1976
|
+
assert!(result.is_err());
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1979
|
+
/// Reject digest shorter than bit_length / 8.
|
|
1980
|
+
#[test]
|
|
1981
|
+
fn test_encode_component_rejects_short_digest() {
|
|
1982
|
+
let result = encode_component(0, 0, 0, 64, &[0u8; 4]);
|
|
1983
|
+
assert!(result.is_err());
|
|
1984
|
+
let err = result.unwrap_err().to_string();
|
|
1985
|
+
assert!(
|
|
1986
|
+
err.contains("digest length 4 < bit_length/8 (8)"),
|
|
1987
|
+
"unexpected error: {err}"
|
|
1988
|
+
);
|
|
1989
|
+
}
|
|
1990
|
+
|
|
1991
|
+
/// Reject invalid MainType value.
|
|
1992
|
+
#[test]
|
|
1993
|
+
fn test_encode_component_rejects_invalid_mtype() {
|
|
1994
|
+
let result = encode_component(99, 0, 0, 64, &[0u8; 8]);
|
|
1995
|
+
assert!(result.is_err());
|
|
1996
|
+
}
|
|
1997
|
+
|
|
1998
|
+
/// Reject invalid SubType value.
|
|
1999
|
+
#[test]
|
|
2000
|
+
fn test_encode_component_rejects_invalid_stype() {
|
|
2001
|
+
let result = encode_component(0, 99, 0, 64, &[0u8; 8]);
|
|
2002
|
+
assert!(result.is_err());
|
|
2003
|
+
}
|
|
2004
|
+
|
|
2005
|
+
/// Reject invalid Version value.
|
|
2006
|
+
#[test]
|
|
2007
|
+
fn test_encode_component_rejects_invalid_version() {
|
|
2008
|
+
let result = encode_component(0, 0, 99, 64, &[0u8; 8]);
|
|
2009
|
+
assert!(result.is_err());
|
|
2010
|
+
}
|
|
2011
|
+
|
|
2012
|
+
// ---- iscc_decode tests ----
|
|
2013
|
+
|
|
2014
|
+
/// Round-trip: encode a Meta-Code digest, decode back, verify all fields match.
|
|
2015
|
+
#[test]
|
|
2016
|
+
fn test_iscc_decode_round_trip_meta() {
|
|
2017
|
+
let digest = [0xaa_u8; 8];
|
|
2018
|
+
let encoded = encode_component(0, 0, 0, 64, &digest).unwrap();
|
|
2019
|
+
let (mt, st, vs, li, decoded_digest) = iscc_decode(&encoded).unwrap();
|
|
2020
|
+
assert_eq!(mt, 0, "MainType::Meta");
|
|
2021
|
+
assert_eq!(st, 0, "SubType::None");
|
|
2022
|
+
assert_eq!(vs, 0, "Version::V0");
|
|
2023
|
+
// encode_length(Meta, 64) → 64/32 - 1 = 1
|
|
2024
|
+
assert_eq!(li, 1, "length_index");
|
|
2025
|
+
assert_eq!(decoded_digest, digest.to_vec());
|
|
2026
|
+
}
|
|
2027
|
+
|
|
2028
|
+
/// Round-trip with Content-Code (MainType=2, SubType::TEXT=0).
|
|
2029
|
+
#[test]
|
|
2030
|
+
fn test_iscc_decode_round_trip_content() {
|
|
2031
|
+
let digest = [0xbb_u8; 8];
|
|
2032
|
+
let encoded = encode_component(2, 0, 0, 64, &digest).unwrap();
|
|
2033
|
+
let (mt, st, vs, _li, decoded_digest) = iscc_decode(&encoded).unwrap();
|
|
2034
|
+
assert_eq!(mt, 2, "MainType::Content");
|
|
2035
|
+
assert_eq!(st, 0, "SubType::TEXT");
|
|
2036
|
+
assert_eq!(vs, 0, "Version::V0");
|
|
2037
|
+
assert_eq!(decoded_digest, digest.to_vec());
|
|
2038
|
+
}
|
|
2039
|
+
|
|
2040
|
+
/// Round-trip with Data-Code (MainType=3).
|
|
2041
|
+
#[test]
|
|
2042
|
+
fn test_iscc_decode_round_trip_data() {
|
|
2043
|
+
let digest = [0xcc_u8; 8];
|
|
2044
|
+
let encoded = encode_component(3, 0, 0, 64, &digest).unwrap();
|
|
2045
|
+
let (mt, _st, _vs, _li, decoded_digest) = iscc_decode(&encoded).unwrap();
|
|
2046
|
+
assert_eq!(mt, 3, "MainType::Data");
|
|
2047
|
+
assert_eq!(decoded_digest, digest.to_vec());
|
|
2048
|
+
}
|
|
2049
|
+
|
|
2050
|
+
/// Round-trip with Instance-Code (MainType=4).
|
|
2051
|
+
#[test]
|
|
2052
|
+
fn test_iscc_decode_round_trip_instance() {
|
|
2053
|
+
let digest = [0xdd_u8; 8];
|
|
2054
|
+
let encoded = encode_component(4, 0, 0, 64, &digest).unwrap();
|
|
2055
|
+
let (mt, _st, _vs, _li, decoded_digest) = iscc_decode(&encoded).unwrap();
|
|
2056
|
+
assert_eq!(mt, 4, "MainType::Instance");
|
|
2057
|
+
assert_eq!(decoded_digest, digest.to_vec());
|
|
2058
|
+
}
|
|
2059
|
+
|
|
2060
|
+
/// Decode with "ISCC:" prefix produces the same result.
|
|
2061
|
+
#[test]
|
|
2062
|
+
fn test_iscc_decode_with_prefix() {
|
|
2063
|
+
let digest = [0xaa_u8; 8];
|
|
2064
|
+
let encoded = encode_component(0, 0, 0, 64, &digest).unwrap();
|
|
2065
|
+
let with_prefix = format!("ISCC:{encoded}");
|
|
2066
|
+
let (mt, st, vs, li, decoded_digest) = iscc_decode(&with_prefix).unwrap();
|
|
2067
|
+
assert_eq!(mt, 0);
|
|
2068
|
+
assert_eq!(st, 0);
|
|
2069
|
+
assert_eq!(vs, 0);
|
|
2070
|
+
assert_eq!(li, 1);
|
|
2071
|
+
assert_eq!(decoded_digest, digest.to_vec());
|
|
2072
|
+
}
|
|
2073
|
+
|
|
2074
|
+
/// Decode with dashes inserted in the string.
|
|
2075
|
+
#[test]
|
|
2076
|
+
fn test_iscc_decode_with_dashes() {
|
|
2077
|
+
let digest = [0xaa_u8; 8];
|
|
2078
|
+
let encoded = encode_component(0, 0, 0, 64, &digest).unwrap();
|
|
2079
|
+
// Insert dashes at arbitrary positions
|
|
2080
|
+
let with_dashes = format!("{}-{}-{}", &encoded[..4], &encoded[4..8], &encoded[8..]);
|
|
2081
|
+
let (mt, st, vs, li, decoded_digest) = iscc_decode(&with_dashes).unwrap();
|
|
2082
|
+
assert_eq!(mt, 0);
|
|
2083
|
+
assert_eq!(st, 0);
|
|
2084
|
+
assert_eq!(vs, 0);
|
|
2085
|
+
assert_eq!(li, 1);
|
|
2086
|
+
assert_eq!(decoded_digest, digest.to_vec());
|
|
2087
|
+
}
|
|
2088
|
+
|
|
2089
|
+
/// Error on invalid base32 characters.
|
|
2090
|
+
#[test]
|
|
2091
|
+
fn test_iscc_decode_invalid_base32() {
|
|
2092
|
+
// Valid prefix `MA`, invalid base32 body — reaches the base32 decoder.
|
|
2093
|
+
let result = iscc_decode("MAAA!!!!");
|
|
2094
|
+
assert!(result.is_err());
|
|
2095
|
+
let err = result.unwrap_err().to_string();
|
|
2096
|
+
assert!(err.contains("base32"), "expected base32 error: {err}");
|
|
2097
|
+
}
|
|
2098
|
+
|
|
2099
|
+
/// Reference parity: `iscc_core.iscc_decode` validates the two-character
|
|
2100
|
+
/// prefix before any decoding, so a structurally decodable header with an
|
|
2101
|
+
/// invalid (MainType, SubType) combination must be rejected.
|
|
2102
|
+
#[test]
|
|
2103
|
+
fn test_iscc_decode_rejects_invalid_prefix() {
|
|
2104
|
+
// ID subtype 4 with Version V1 decodes structurally but `MQ` is not a
|
|
2105
|
+
// valid prefix; the reference raises "ISCC starts with invalid prefix MQ".
|
|
2106
|
+
let err = iscc_decode("ISCC:MQIAAAAAAAAAAAAA")
|
|
2107
|
+
.unwrap_err()
|
|
2108
|
+
.to_string();
|
|
2109
|
+
assert!(err.contains("invalid prefix MQ"), "got: {err}");
|
|
2110
|
+
|
|
2111
|
+
// A prefix shorter than two characters is reported as-is, like the reference.
|
|
2112
|
+
let err = iscc_decode("M").unwrap_err().to_string();
|
|
2113
|
+
assert!(err.contains("invalid prefix M"), "got: {err}");
|
|
2114
|
+
|
|
2115
|
+
// Prefix rejection happens before base32 decoding, matching the reference.
|
|
2116
|
+
let err = iscc_decode("!!!INVALID!!!").unwrap_err().to_string();
|
|
2117
|
+
assert!(err.contains("invalid prefix !!"), "got: {err}");
|
|
2118
|
+
|
|
2119
|
+
// Reference parity: `iscc_decompose` does NOT prefix-check.
|
|
2120
|
+
assert!(iscc_decompose("ISCC:MQIAAAAAAAAAAAAA").is_ok());
|
|
2121
|
+
|
|
2122
|
+
// Lowercase input with a valid prefix still decodes.
|
|
2123
|
+
assert!(iscc_decode("iscc:maighfecjmopmiab").is_ok());
|
|
2124
|
+
}
|
|
2125
|
+
|
|
2126
|
+
/// Known value from conformance vectors: Meta-Code "ISCC:AAAZXZ6OU74YAZIM".
|
|
2127
|
+
/// MainType=Meta(0), SubType=None(0), Version=V0(0), 64-bit digest.
|
|
2128
|
+
#[test]
|
|
2129
|
+
fn test_iscc_decode_known_meta_code() {
|
|
2130
|
+
let (mt, st, vs, li, digest) = iscc_decode("ISCC:AAAZXZ6OU74YAZIM").unwrap();
|
|
2131
|
+
assert_eq!(mt, 0, "MainType::Meta");
|
|
2132
|
+
assert_eq!(st, 0, "SubType::None");
|
|
2133
|
+
assert_eq!(vs, 0, "Version::V0");
|
|
2134
|
+
assert_eq!(li, 1, "length_index for 64-bit");
|
|
2135
|
+
assert_eq!(digest.len(), 8, "64-bit = 8 bytes");
|
|
2136
|
+
}
|
|
2137
|
+
|
|
2138
|
+
/// Known value from conformance vectors: Instance-Code "ISCC:IAA26E2JXH27TING".
|
|
2139
|
+
/// MainType=Instance(4), SubType=None(0), Version=V0(0), 64-bit digest.
|
|
2140
|
+
#[test]
|
|
2141
|
+
fn test_iscc_decode_known_instance_code() {
|
|
2142
|
+
let (mt, st, vs, li, digest) = iscc_decode("ISCC:IAA26E2JXH27TING").unwrap();
|
|
2143
|
+
assert_eq!(mt, 4, "MainType::Instance");
|
|
2144
|
+
assert_eq!(st, 0, "SubType::None");
|
|
2145
|
+
assert_eq!(vs, 0, "Version::V0");
|
|
2146
|
+
assert_eq!(li, 1, "length_index for 64-bit");
|
|
2147
|
+
assert_eq!(digest.len(), 8, "64-bit = 8 bytes");
|
|
2148
|
+
}
|
|
2149
|
+
|
|
2150
|
+
/// Known value: Data-Code "ISCC:GAAXL2XYM5BQIAZ3".
|
|
2151
|
+
/// MainType=Data(3), SubType=None(0), Version=V0(0), 64-bit digest.
|
|
2152
|
+
#[test]
|
|
2153
|
+
fn test_iscc_decode_known_data_code() {
|
|
2154
|
+
let (mt, st, vs, _li, digest) = iscc_decode("ISCC:GAAXL2XYM5BQIAZ3").unwrap();
|
|
2155
|
+
assert_eq!(mt, 3, "MainType::Data");
|
|
2156
|
+
assert_eq!(st, 0, "SubType::None");
|
|
2157
|
+
assert_eq!(vs, 0, "Version::V0");
|
|
2158
|
+
assert_eq!(digest.len(), 8, "64-bit = 8 bytes");
|
|
2159
|
+
}
|
|
2160
|
+
|
|
2161
|
+
/// Verification criterion: round-trip with specific known values.
|
|
2162
|
+
/// encode_component(0, 0, 0, 64, &[0xaa;8]) → iscc_decode → (0, 0, 0, 1, vec![0xaa;8])
|
|
2163
|
+
#[test]
|
|
2164
|
+
fn test_iscc_decode_verification_round_trip() {
|
|
2165
|
+
let digest = [0xaa_u8; 8];
|
|
2166
|
+
let encoded = encode_component(0, 0, 0, 64, &digest).unwrap();
|
|
2167
|
+
let result = iscc_decode(&encoded).unwrap();
|
|
2168
|
+
assert_eq!(result, (0, 0, 0, 1, vec![0xaa; 8]));
|
|
2169
|
+
}
|
|
2170
|
+
|
|
2171
|
+
/// Error on truncated input where body is shorter than expected digest length.
|
|
2172
|
+
/// A concatenated unit sequence normalizes to its composite before decoding.
|
|
2173
|
+
#[test]
|
|
2174
|
+
fn test_iscc_decode_normalizes_unit_sequence() {
|
|
2175
|
+
let data = gen_data_code_v0(&[0x61; 2000], 64).unwrap().iscc;
|
|
2176
|
+
let instance = gen_instance_code_v0(&[0x61; 2000], 64).unwrap().iscc;
|
|
2177
|
+
let composite = gen_iscc_code_v0(&[&data, &instance], false).unwrap().iscc;
|
|
2178
|
+
|
|
2179
|
+
let sequence = format!(
|
|
2180
|
+
"{}{}",
|
|
2181
|
+
data.strip_prefix("ISCC:").unwrap(),
|
|
2182
|
+
instance.strip_prefix("ISCC:").unwrap()
|
|
2183
|
+
);
|
|
2184
|
+
assert_eq!(
|
|
2185
|
+
iscc_decode(&sequence).unwrap(),
|
|
2186
|
+
iscc_decode(&composite).unwrap(),
|
|
2187
|
+
"a unit sequence must decode identically to its composite"
|
|
2188
|
+
);
|
|
2189
|
+
// MainType is ISCC (5), not the leading unit's Data (3).
|
|
2190
|
+
assert_eq!(iscc_decode(&sequence).unwrap().0, 5);
|
|
2191
|
+
}
|
|
2192
|
+
|
|
2193
|
+
/// Trailing base32 after a composite decodes rather than erroring.
|
|
2194
|
+
///
|
|
2195
|
+
/// Appending base32 characters re-aligns the whole byte stream, so the
|
|
2196
|
+
/// reference does not "ignore a trailing byte" — it decodes a shifted body
|
|
2197
|
+
/// and returns a different digest. This asserts only that the input is
|
|
2198
|
+
/// accepted, which is the behaviour normalization restores; the exact
|
|
2199
|
+
/// shifted digest is pinned against `iscc_core` by the Python differential
|
|
2200
|
+
/// in `tests/test_iscc_decode_conformance.py`.
|
|
2201
|
+
#[test]
|
|
2202
|
+
fn test_iscc_decode_accepts_trailing_after_composite() {
|
|
2203
|
+
let data = gen_data_code_v0(&[0x61; 2000], 64).unwrap().iscc;
|
|
2204
|
+
let instance = gen_instance_code_v0(&[0x61; 2000], 64).unwrap().iscc;
|
|
2205
|
+
let composite = gen_iscc_code_v0(&[&data, &instance], false).unwrap().iscc;
|
|
2206
|
+
|
|
2207
|
+
let (mt, _st, _vs, _li, digest) = iscc_decode(&format!("{composite}AA")).unwrap();
|
|
2208
|
+
assert_eq!(mt, 5, "still decodes as an ISCC-CODE");
|
|
2209
|
+
assert_eq!(digest.len(), 16);
|
|
2210
|
+
}
|
|
2211
|
+
|
|
2212
|
+
/// A unit sequence that cannot compose into an ISCC-CODE is rejected.
|
|
2213
|
+
// `meta-code` implies `text-processing`, so this single gate excludes the test
|
|
2214
|
+
// under `--no-default-features` (and `--features text-processing` alone), where
|
|
2215
|
+
// `gen_meta_code_v0`/`gen_text_code_v0` are compiled out.
|
|
2216
|
+
#[cfg(feature = "meta-code")]
|
|
2217
|
+
#[test]
|
|
2218
|
+
fn test_iscc_decode_rejects_uncomposable_sequence() {
|
|
2219
|
+
// Meta + Text has neither a Data-Code nor an Instance-Code, so
|
|
2220
|
+
// gen_iscc_code_v0 rejects it — as the reference does.
|
|
2221
|
+
let meta = gen_meta_code_v0("Hello", None, None, 64).unwrap().iscc;
|
|
2222
|
+
let text = gen_text_code_v0("Hello World", 64).unwrap().iscc;
|
|
2223
|
+
let sequence = format!(
|
|
2224
|
+
"{}{}",
|
|
2225
|
+
meta.strip_prefix("ISCC:").unwrap(),
|
|
2226
|
+
text.strip_prefix("ISCC:").unwrap()
|
|
2227
|
+
);
|
|
2228
|
+
assert!(iscc_decode(&sequence).is_err());
|
|
2229
|
+
}
|
|
2230
|
+
|
|
2231
|
+
/// Wide-mode is detected from the original header and survives normalization.
|
|
2232
|
+
#[test]
|
|
2233
|
+
fn test_iscc_decode_preserves_wide_subtype() {
|
|
2234
|
+
let data = gen_data_code_v0(&[0x61; 2000], 128).unwrap().iscc;
|
|
2235
|
+
let instance = gen_instance_code_v0(&[0x61; 2000], 128).unwrap().iscc;
|
|
2236
|
+
let wide = gen_iscc_code_v0(&[&data, &instance], true).unwrap().iscc;
|
|
2237
|
+
|
|
2238
|
+
let (mt, st, _vs, _li, digest) = iscc_decode(&wide).unwrap();
|
|
2239
|
+
assert_eq!(mt, 5);
|
|
2240
|
+
assert_eq!(st, 7, "SubType must stay WIDE through normalization");
|
|
2241
|
+
assert_eq!(digest.len(), 32);
|
|
2242
|
+
}
|
|
2243
|
+
|
|
2244
|
+
#[test]
|
|
2245
|
+
fn test_iscc_decode_truncated_input() {
|
|
2246
|
+
// Encode a valid 256-bit Meta-Code, then truncate the base32 string
|
|
2247
|
+
let digest = [0xff_u8; 32];
|
|
2248
|
+
let encoded = encode_component(0, 0, 0, 256, &digest).unwrap();
|
|
2249
|
+
// Truncate to just the header portion (first few chars)
|
|
2250
|
+
let truncated = &encoded[..6];
|
|
2251
|
+
let result = iscc_decode(truncated);
|
|
2252
|
+
assert!(result.is_err(), "should fail on truncated input");
|
|
2253
|
+
}
|
|
2254
|
+
|
|
2255
|
+
// --- json_to_data_url tests ---
|
|
2256
|
+
|
|
2257
|
+
/// Basic JSON object produces a data URL with application/json media type.
|
|
2258
|
+
#[cfg(feature = "meta-code")]
|
|
2259
|
+
#[test]
|
|
2260
|
+
fn test_json_to_data_url_basic() {
|
|
2261
|
+
let url = json_to_data_url(r#"{"key": "value"}"#).unwrap();
|
|
2262
|
+
assert!(
|
|
2263
|
+
url.starts_with("data:application/json;base64,"),
|
|
2264
|
+
"expected application/json prefix, got: {url}"
|
|
2265
|
+
);
|
|
2266
|
+
}
|
|
2267
|
+
|
|
2268
|
+
/// JSON with `@context` key uses application/ld+json media type.
|
|
2269
|
+
#[cfg(feature = "meta-code")]
|
|
2270
|
+
#[test]
|
|
2271
|
+
fn test_json_to_data_url_ld_json() {
|
|
2272
|
+
let url = json_to_data_url(r#"{"@context": "https://schema.org"}"#).unwrap();
|
|
2273
|
+
assert!(
|
|
2274
|
+
url.starts_with("data:application/ld+json;base64,"),
|
|
2275
|
+
"expected application/ld+json prefix, got: {url}"
|
|
2276
|
+
);
|
|
2277
|
+
}
|
|
2278
|
+
|
|
2279
|
+
/// JCS canonicalization reorders keys alphabetically.
|
|
2280
|
+
#[cfg(feature = "meta-code")]
|
|
2281
|
+
#[test]
|
|
2282
|
+
fn test_json_to_data_url_jcs_ordering() {
|
|
2283
|
+
let url = json_to_data_url(r#"{"b":1,"a":2}"#).unwrap();
|
|
2284
|
+
// Extract and decode the base64 payload
|
|
2285
|
+
let b64 = url.split_once(',').unwrap().1;
|
|
2286
|
+
let decoded = data_encoding::BASE64.decode(b64.as_bytes()).unwrap();
|
|
2287
|
+
let canonical = std::str::from_utf8(&decoded).unwrap();
|
|
2288
|
+
assert_eq!(canonical, r#"{"a":2,"b":1}"#, "JCS should sort keys");
|
|
2289
|
+
}
|
|
2290
|
+
|
|
2291
|
+
/// Round-trip: json_to_data_url output fed into decode_data_url recovers
|
|
2292
|
+
/// the JCS-canonical bytes.
|
|
2293
|
+
#[cfg(feature = "meta-code")]
|
|
2294
|
+
#[test]
|
|
2295
|
+
fn test_json_to_data_url_round_trip() {
|
|
2296
|
+
let input = r#"{"hello": "world", "num": 42}"#;
|
|
2297
|
+
let url = json_to_data_url(input).unwrap();
|
|
2298
|
+
let decoded_bytes = decode_data_url(&url).unwrap();
|
|
2299
|
+
// The decoded bytes should be JCS-canonical JSON
|
|
2300
|
+
let canonical: serde_json::Value =
|
|
2301
|
+
serde_json::from_slice(&decoded_bytes).expect("decoded bytes should be valid JSON");
|
|
2302
|
+
let original: serde_json::Value = serde_json::from_str(input).unwrap();
|
|
2303
|
+
assert_eq!(canonical, original, "round-trip preserves JSON semantics");
|
|
2304
|
+
}
|
|
2305
|
+
|
|
2306
|
+
/// Invalid JSON string returns an error.
|
|
2307
|
+
#[cfg(feature = "meta-code")]
|
|
2308
|
+
#[test]
|
|
2309
|
+
fn test_json_to_data_url_invalid_json() {
|
|
2310
|
+
let result = json_to_data_url("not json");
|
|
2311
|
+
assert!(result.is_err(), "should reject invalid JSON");
|
|
2312
|
+
let err = result.unwrap_err().to_string();
|
|
2313
|
+
assert!(
|
|
2314
|
+
err.contains("invalid JSON"),
|
|
2315
|
+
"expected 'invalid JSON' in error: {err}"
|
|
2316
|
+
);
|
|
2317
|
+
}
|
|
2318
|
+
|
|
2319
|
+
/// Compatibility with conformance vector test_0016_meta_data_url.
|
|
2320
|
+
///
|
|
2321
|
+
/// The conformance vector's meta field is:
|
|
2322
|
+
/// data:application/json;charset=utf-8;base64,eyJzb21lIjogIm9iamVjdCJ9
|
|
2323
|
+
/// which encodes `{"some": "object"}` (with space after colon).
|
|
2324
|
+
///
|
|
2325
|
+
/// Our function differs in two ways:
|
|
2326
|
+
/// 1. No `charset=utf-8` parameter (matching Python's DataURL.from_byte_data)
|
|
2327
|
+
/// 2. JCS canonicalization removes whitespace: `{"some":"object"}` (no space)
|
|
2328
|
+
///
|
|
2329
|
+
/// We verify: (a) correct media type prefix, and (b) decoded payload equals
|
|
2330
|
+
/// JCS-canonical form of the same JSON input.
|
|
2331
|
+
#[cfg(feature = "meta-code")]
|
|
2332
|
+
#[test]
|
|
2333
|
+
fn test_json_to_data_url_conformance_0016() {
|
|
2334
|
+
let url = json_to_data_url(r#"{"some": "object"}"#).unwrap();
|
|
2335
|
+
// (a) Correct media type prefix (no charset, no @context → application/json)
|
|
2336
|
+
assert!(
|
|
2337
|
+
url.starts_with("data:application/json;base64,"),
|
|
2338
|
+
"expected application/json prefix"
|
|
2339
|
+
);
|
|
2340
|
+
// (b) Decoded payload is JCS-canonical (no whitespace)
|
|
2341
|
+
let b64 = url.split_once(',').unwrap().1;
|
|
2342
|
+
let decoded = data_encoding::BASE64.decode(b64.as_bytes()).unwrap();
|
|
2343
|
+
let canonical = std::str::from_utf8(&decoded).unwrap();
|
|
2344
|
+
assert_eq!(
|
|
2345
|
+
canonical, r#"{"some":"object"}"#,
|
|
2346
|
+
"JCS removes whitespace from JSON"
|
|
2347
|
+
);
|
|
2348
|
+
}
|
|
2349
|
+
|
|
2350
|
+
#[cfg(feature = "meta-code")]
|
|
2351
|
+
#[test]
|
|
2352
|
+
fn test_meta_trim_meta_value() {
|
|
2353
|
+
assert_eq!(META_TRIM_META, 128_000);
|
|
2354
|
+
}
|
|
2355
|
+
|
|
2356
|
+
#[cfg(feature = "meta-code")]
|
|
2357
|
+
#[test]
|
|
2358
|
+
fn test_gen_meta_code_v0_meta_at_limit() {
|
|
2359
|
+
// Create a JSON payload that decodes to exactly 128,000 bytes
|
|
2360
|
+
// JSON: {"x":"<padding>"} where padding fills to 128,000 bytes
|
|
2361
|
+
// The canonical JSON overhead is {"x":""} = 8 bytes, so padding = 127,992 bytes
|
|
2362
|
+
let padding = "a".repeat(128_000 - 8);
|
|
2363
|
+
let json_str = format!(r#"{{"x":"{padding}"}}"#);
|
|
2364
|
+
let result = gen_meta_code_v0("test", None, Some(&json_str), 64);
|
|
2365
|
+
assert!(
|
|
2366
|
+
result.is_ok(),
|
|
2367
|
+
"payload at exactly META_TRIM_META should succeed"
|
|
2368
|
+
);
|
|
2369
|
+
}
|
|
2370
|
+
|
|
2371
|
+
#[cfg(feature = "meta-code")]
|
|
2372
|
+
#[test]
|
|
2373
|
+
fn test_gen_meta_code_v0_meta_over_limit() {
|
|
2374
|
+
// Create a JSON payload that decodes to 128,001 bytes (one over limit)
|
|
2375
|
+
let padding = "a".repeat(128_000 - 8 + 1);
|
|
2376
|
+
let json_str = format!(r#"{{"x":"{padding}"}}"#);
|
|
2377
|
+
let result = gen_meta_code_v0("test", None, Some(&json_str), 64);
|
|
2378
|
+
assert!(
|
|
2379
|
+
matches!(result, Err(IsccError::InvalidInput(ref msg)) if msg.contains("size limit")),
|
|
2380
|
+
"payload exceeding META_TRIM_META should return InvalidInput"
|
|
2381
|
+
);
|
|
2382
|
+
}
|
|
2383
|
+
|
|
2384
|
+
#[cfg(feature = "meta-code")]
|
|
2385
|
+
#[test]
|
|
2386
|
+
fn test_gen_meta_code_v0_data_url_pre_decode_reject() {
|
|
2387
|
+
// Create a Data-URL string exceeding the pre-decode limit
|
|
2388
|
+
// PRE_DECODE_LIMIT = META_TRIM_META * 4 / 3 + 256 = 170,922
|
|
2389
|
+
let pre_decode_limit = META_TRIM_META * 4 / 3 + 256;
|
|
2390
|
+
let padding = "A".repeat(pre_decode_limit + 1);
|
|
2391
|
+
let data_url = format!("data:application/octet-stream;base64,{padding}");
|
|
2392
|
+
let result = gen_meta_code_v0("test", None, Some(&data_url), 64);
|
|
2393
|
+
assert!(
|
|
2394
|
+
matches!(result, Err(IsccError::InvalidInput(ref msg)) if msg.contains("size limit")),
|
|
2395
|
+
"oversized Data-URL should be rejected before decoding"
|
|
2396
|
+
);
|
|
2397
|
+
}
|
|
2398
|
+
|
|
2399
|
+
// ---- gen_sum_code_v0 tests ----
|
|
2400
|
+
|
|
2401
|
+
/// Helper: write data to a unique temp file and return the path.
|
|
2402
|
+
fn write_temp_file(name: &str, data: &[u8]) -> std::path::PathBuf {
|
|
2403
|
+
let path = std::env::temp_dir().join(format!("iscc_test_{name}"));
|
|
2404
|
+
std::fs::write(&path, data).expect("failed to write temp file");
|
|
2405
|
+
path
|
|
2406
|
+
}
|
|
2407
|
+
|
|
2408
|
+
#[test]
|
|
2409
|
+
fn test_gen_sum_code_v0_equivalence() {
|
|
2410
|
+
let data = b"Hello, ISCC World! This is a test of gen_sum_code_v0.";
|
|
2411
|
+
let path = write_temp_file("sum_equiv", data);
|
|
2412
|
+
|
|
2413
|
+
let sum_result = gen_sum_code_v0(&path, 64, false, false).unwrap();
|
|
2414
|
+
|
|
2415
|
+
// Compute the same result via separate functions
|
|
2416
|
+
let data_result = gen_data_code_v0(data, 64).unwrap();
|
|
2417
|
+
let instance_result = gen_instance_code_v0(data, 64).unwrap();
|
|
2418
|
+
let iscc_result =
|
|
2419
|
+
gen_iscc_code_v0(&[&data_result.iscc, &instance_result.iscc], false).unwrap();
|
|
2420
|
+
|
|
2421
|
+
assert_eq!(sum_result.iscc, iscc_result.iscc);
|
|
2422
|
+
assert_eq!(sum_result.datahash, instance_result.datahash);
|
|
2423
|
+
assert_eq!(sum_result.filesize, instance_result.filesize);
|
|
2424
|
+
assert_eq!(sum_result.filesize, data.len() as u64);
|
|
2425
|
+
assert_eq!(sum_result.units, None);
|
|
2426
|
+
|
|
2427
|
+
std::fs::remove_file(&path).ok();
|
|
2428
|
+
}
|
|
2429
|
+
|
|
2430
|
+
#[test]
|
|
2431
|
+
fn test_gen_sum_code_v0_empty_file() {
|
|
2432
|
+
let path = write_temp_file("sum_empty", b"");
|
|
2433
|
+
|
|
2434
|
+
let sum_result = gen_sum_code_v0(&path, 64, false, false).unwrap();
|
|
2435
|
+
|
|
2436
|
+
let data_result = gen_data_code_v0(b"", 64).unwrap();
|
|
2437
|
+
let instance_result = gen_instance_code_v0(b"", 64).unwrap();
|
|
2438
|
+
let iscc_result =
|
|
2439
|
+
gen_iscc_code_v0(&[&data_result.iscc, &instance_result.iscc], false).unwrap();
|
|
2440
|
+
|
|
2441
|
+
assert_eq!(sum_result.iscc, iscc_result.iscc);
|
|
2442
|
+
assert_eq!(sum_result.datahash, instance_result.datahash);
|
|
2443
|
+
assert_eq!(sum_result.filesize, 0);
|
|
2444
|
+
|
|
2445
|
+
std::fs::remove_file(&path).ok();
|
|
2446
|
+
}
|
|
2447
|
+
|
|
2448
|
+
#[test]
|
|
2449
|
+
fn test_gen_sum_code_v0_file_not_found() {
|
|
2450
|
+
let path = std::env::temp_dir().join("iscc_test_nonexistent_file_xyz");
|
|
2451
|
+
let result = gen_sum_code_v0(&path, 64, false, false);
|
|
2452
|
+
assert!(result.is_err());
|
|
2453
|
+
let err_msg = result.unwrap_err().to_string();
|
|
2454
|
+
assert!(
|
|
2455
|
+
err_msg.contains("Cannot open file"),
|
|
2456
|
+
"error message should mention file open failure: {err_msg}"
|
|
2457
|
+
);
|
|
2458
|
+
}
|
|
2459
|
+
|
|
2460
|
+
#[test]
|
|
2461
|
+
fn test_gen_sum_code_v0_wide_mode() {
|
|
2462
|
+
let data = b"Testing wide mode for gen_sum_code_v0 function.";
|
|
2463
|
+
let path = write_temp_file("sum_wide", data);
|
|
2464
|
+
|
|
2465
|
+
let narrow = gen_sum_code_v0(&path, 64, false, false).unwrap();
|
|
2466
|
+
let wide = gen_sum_code_v0(&path, 64, true, false).unwrap();
|
|
2467
|
+
|
|
2468
|
+
// Wide mode with 64-bit codes doesn't trigger (need 128+), so they should be equal
|
|
2469
|
+
assert_eq!(narrow.iscc, wide.iscc);
|
|
2470
|
+
|
|
2471
|
+
// With 128 bits, wide mode should produce a different (longer) ISCC
|
|
2472
|
+
let narrow_128 = gen_sum_code_v0(&path, 128, false, false).unwrap();
|
|
2473
|
+
let wide_128 = gen_sum_code_v0(&path, 128, true, false).unwrap();
|
|
2474
|
+
assert_ne!(narrow_128.iscc, wide_128.iscc);
|
|
2475
|
+
|
|
2476
|
+
// Both should have the same datahash and filesize
|
|
2477
|
+
assert_eq!(narrow_128.datahash, wide_128.datahash);
|
|
2478
|
+
assert_eq!(narrow_128.filesize, wide_128.filesize);
|
|
2479
|
+
|
|
2480
|
+
std::fs::remove_file(&path).ok();
|
|
2481
|
+
}
|
|
2482
|
+
|
|
2483
|
+
#[test]
|
|
2484
|
+
fn test_gen_sum_code_v0_bits_64() {
|
|
2485
|
+
let data = b"Testing 64-bit gen_sum_code_v0.";
|
|
2486
|
+
let path = write_temp_file("sum_bits64", data);
|
|
2487
|
+
|
|
2488
|
+
let sum_result = gen_sum_code_v0(&path, 64, false, false).unwrap();
|
|
2489
|
+
|
|
2490
|
+
let data_result = gen_data_code_v0(data, 64).unwrap();
|
|
2491
|
+
let instance_result = gen_instance_code_v0(data, 64).unwrap();
|
|
2492
|
+
let iscc_result =
|
|
2493
|
+
gen_iscc_code_v0(&[&data_result.iscc, &instance_result.iscc], false).unwrap();
|
|
2494
|
+
|
|
2495
|
+
assert_eq!(sum_result.iscc, iscc_result.iscc);
|
|
2496
|
+
|
|
2497
|
+
std::fs::remove_file(&path).ok();
|
|
2498
|
+
}
|
|
2499
|
+
|
|
2500
|
+
#[test]
|
|
2501
|
+
fn test_gen_sum_code_v0_bits_128() {
|
|
2502
|
+
let data = b"Testing 128-bit gen_sum_code_v0.";
|
|
2503
|
+
let path = write_temp_file("sum_bits128", data);
|
|
2504
|
+
|
|
2505
|
+
let sum_result = gen_sum_code_v0(&path, 128, false, false).unwrap();
|
|
2506
|
+
|
|
2507
|
+
let data_result = gen_data_code_v0(data, 128).unwrap();
|
|
2508
|
+
let instance_result = gen_instance_code_v0(data, 128).unwrap();
|
|
2509
|
+
let iscc_result =
|
|
2510
|
+
gen_iscc_code_v0(&[&data_result.iscc, &instance_result.iscc], false).unwrap();
|
|
2511
|
+
|
|
2512
|
+
assert_eq!(sum_result.iscc, iscc_result.iscc);
|
|
2513
|
+
assert_eq!(sum_result.datahash, instance_result.datahash);
|
|
2514
|
+
assert_eq!(sum_result.filesize, data.len() as u64);
|
|
2515
|
+
|
|
2516
|
+
std::fs::remove_file(&path).ok();
|
|
2517
|
+
}
|
|
2518
|
+
|
|
2519
|
+
#[test]
|
|
2520
|
+
fn test_gen_sum_code_v0_large_data() {
|
|
2521
|
+
// Generate data large enough to produce multiple CDC chunks
|
|
2522
|
+
let data: Vec<u8> = (0..50_000).map(|i| (i % 256) as u8).collect();
|
|
2523
|
+
let path = write_temp_file("sum_large", &data);
|
|
2524
|
+
|
|
2525
|
+
let sum_result = gen_sum_code_v0(&path, 64, false, false).unwrap();
|
|
2526
|
+
|
|
2527
|
+
let data_result = gen_data_code_v0(&data, 64).unwrap();
|
|
2528
|
+
let instance_result = gen_instance_code_v0(&data, 64).unwrap();
|
|
2529
|
+
let iscc_result =
|
|
2530
|
+
gen_iscc_code_v0(&[&data_result.iscc, &instance_result.iscc], false).unwrap();
|
|
2531
|
+
|
|
2532
|
+
assert_eq!(sum_result.iscc, iscc_result.iscc);
|
|
2533
|
+
assert_eq!(sum_result.datahash, instance_result.datahash);
|
|
2534
|
+
assert_eq!(sum_result.filesize, data.len() as u64);
|
|
2535
|
+
|
|
2536
|
+
std::fs::remove_file(&path).ok();
|
|
2537
|
+
}
|
|
2538
|
+
|
|
2539
|
+
#[test]
|
|
2540
|
+
fn test_gen_sum_code_v0_units_enabled() {
|
|
2541
|
+
let data = b"Hello, ISCC World! This is a test of gen_sum_code_v0 units.";
|
|
2542
|
+
let path = write_temp_file("sum_units_on", data);
|
|
2543
|
+
|
|
2544
|
+
let sum_result = gen_sum_code_v0(&path, 64, false, true).unwrap();
|
|
2545
|
+
|
|
2546
|
+
// units should be Some with exactly 2 elements
|
|
2547
|
+
let units = sum_result.units.as_ref().expect("units should be Some");
|
|
2548
|
+
assert_eq!(
|
|
2549
|
+
units.len(),
|
|
2550
|
+
2,
|
|
2551
|
+
"units should contain [Data-Code, Instance-Code]"
|
|
2552
|
+
);
|
|
2553
|
+
|
|
2554
|
+
// First unit should be a Data-Code (MainType::Data = 3)
|
|
2555
|
+
let (maintype, ..) = iscc_decode(&units[0]).unwrap();
|
|
2556
|
+
assert_eq!(
|
|
2557
|
+
maintype, 3,
|
|
2558
|
+
"first unit should be a Data-Code (MainType::Data = 3)"
|
|
2559
|
+
);
|
|
2560
|
+
|
|
2561
|
+
// Second unit should be an Instance-Code (MainType::Instance = 4)
|
|
2562
|
+
let (maintype, ..) = iscc_decode(&units[1]).unwrap();
|
|
2563
|
+
assert_eq!(
|
|
2564
|
+
maintype, 4,
|
|
2565
|
+
"second unit should be an Instance-Code (MainType::Instance = 4)"
|
|
2566
|
+
);
|
|
2567
|
+
|
|
2568
|
+
// Units should match individually computed codes
|
|
2569
|
+
let data_result = gen_data_code_v0(data, 64).unwrap();
|
|
2570
|
+
let instance_result = gen_instance_code_v0(data, 64).unwrap();
|
|
2571
|
+
assert_eq!(units[0], data_result.iscc);
|
|
2572
|
+
assert_eq!(units[1], instance_result.iscc);
|
|
2573
|
+
|
|
2574
|
+
// The composite ISCC should still be correct
|
|
2575
|
+
let iscc_result =
|
|
2576
|
+
gen_iscc_code_v0(&[&data_result.iscc, &instance_result.iscc], false).unwrap();
|
|
2577
|
+
assert_eq!(sum_result.iscc, iscc_result.iscc);
|
|
2578
|
+
|
|
2579
|
+
std::fs::remove_file(&path).ok();
|
|
2580
|
+
}
|
|
2581
|
+
|
|
2582
|
+
#[test]
|
|
2583
|
+
fn test_gen_sum_code_v0_units_disabled() {
|
|
2584
|
+
let data = b"Hello, ISCC World! This is a test of gen_sum_code_v0 no units.";
|
|
2585
|
+
let path = write_temp_file("sum_units_off", data);
|
|
2586
|
+
|
|
2587
|
+
let sum_result = gen_sum_code_v0(&path, 64, false, false).unwrap();
|
|
2588
|
+
|
|
2589
|
+
assert_eq!(
|
|
2590
|
+
sum_result.units, None,
|
|
2591
|
+
"units should be None when add_units is false"
|
|
2592
|
+
);
|
|
2593
|
+
|
|
2594
|
+
// The composite ISCC should still be correct
|
|
2595
|
+
let data_result = gen_data_code_v0(data, 64).unwrap();
|
|
2596
|
+
let instance_result = gen_instance_code_v0(data, 64).unwrap();
|
|
2597
|
+
let iscc_result =
|
|
2598
|
+
gen_iscc_code_v0(&[&data_result.iscc, &instance_result.iscc], false).unwrap();
|
|
2599
|
+
assert_eq!(sum_result.iscc, iscc_result.iscc);
|
|
2600
|
+
|
|
2601
|
+
std::fs::remove_file(&path).ok();
|
|
2602
|
+
}
|
|
2603
|
+
|
|
2604
|
+
/// Build a base32 ISCC-UNIT whose header claims 288 bits (length index 8).
|
|
2605
|
+
fn unit_288_bits(mtype: codec::MainType) -> String {
|
|
2606
|
+
let mut raw =
|
|
2607
|
+
codec::encode_header(mtype, codec::SubType::None, codec::Version::V0, 8).unwrap();
|
|
2608
|
+
raw.extend_from_slice(&[0u8; 36]);
|
|
2609
|
+
codec::encode_base32(&raw)
|
|
2610
|
+
}
|
|
2611
|
+
|
|
2612
|
+
/// Assert that a result is an error that names the 256-bit limit.
|
|
2613
|
+
fn assert_above_256_error<T: std::fmt::Debug>(result: IsccResult<T>) {
|
|
2614
|
+
let err = result.expect_err("a unit above 256 bits must be rejected");
|
|
2615
|
+
assert!(err.to_string().contains("256"), "unexpected error: {err}");
|
|
2616
|
+
}
|
|
2617
|
+
|
|
2618
|
+
#[cfg(feature = "meta-code")]
|
|
2619
|
+
#[test]
|
|
2620
|
+
fn test_gen_meta_code_v0_above_256() {
|
|
2621
|
+
assert_above_256_error(gen_meta_code_v0("Title", None, None, 288));
|
|
2622
|
+
assert!(gen_meta_code_v0("Title", None, None, 256).is_ok());
|
|
2623
|
+
}
|
|
2624
|
+
|
|
2625
|
+
#[cfg(feature = "text-processing")]
|
|
2626
|
+
#[test]
|
|
2627
|
+
fn test_gen_text_code_v0_above_256() {
|
|
2628
|
+
assert_above_256_error(gen_text_code_v0("Hello World", 288));
|
|
2629
|
+
assert!(gen_text_code_v0("Hello World", 256).is_ok());
|
|
2630
|
+
}
|
|
2631
|
+
|
|
2632
|
+
#[test]
|
|
2633
|
+
fn test_gen_audio_code_v0_above_256() {
|
|
2634
|
+
assert_above_256_error(gen_audio_code_v0(&[1, 2, 3], 288));
|
|
2635
|
+
assert!(gen_audio_code_v0(&[1, 2, 3], 256).is_ok());
|
|
2636
|
+
}
|
|
2637
|
+
|
|
2638
|
+
#[test]
|
|
2639
|
+
fn test_gen_mixed_code_v0_bits_above_256() {
|
|
2640
|
+
let a = gen_audio_code_v0(&[1, 2, 3], 256).unwrap().iscc;
|
|
2641
|
+
let b = gen_audio_code_v0(&[4, 5, 6], 256).unwrap().iscc;
|
|
2642
|
+
assert_above_256_error(gen_mixed_code_v0(&[&a, &b], 288));
|
|
2643
|
+
assert!(gen_mixed_code_v0(&[&a, &b], 256).is_ok());
|
|
2644
|
+
}
|
|
2645
|
+
|
|
2646
|
+
#[test]
|
|
2647
|
+
fn test_gen_mixed_code_v0_unit_above_256() {
|
|
2648
|
+
let long = unit_288_bits(codec::MainType::Content);
|
|
2649
|
+
let ok = gen_audio_code_v0(&[1, 2, 3], 64).unwrap().iscc;
|
|
2650
|
+
assert_above_256_error(gen_mixed_code_v0(&[&long, &ok], 64));
|
|
2651
|
+
}
|
|
2652
|
+
|
|
2653
|
+
#[test]
|
|
2654
|
+
fn test_gen_data_code_v0_above_256() {
|
|
2655
|
+
assert_above_256_error(gen_data_code_v0(b"data", 288));
|
|
2656
|
+
assert!(gen_data_code_v0(b"data", 256).is_ok());
|
|
2657
|
+
}
|
|
2658
|
+
|
|
2659
|
+
#[test]
|
|
2660
|
+
fn test_gen_instance_code_v0_above_256() {
|
|
2661
|
+
assert_above_256_error(gen_instance_code_v0(b"data", 288));
|
|
2662
|
+
assert!(gen_instance_code_v0(b"data", 256).is_ok());
|
|
2663
|
+
}
|
|
2664
|
+
|
|
2665
|
+
#[test]
|
|
2666
|
+
fn test_gen_sum_code_v0_above_256() {
|
|
2667
|
+
let path = write_temp_file("sum_above_256", b"some file content");
|
|
2668
|
+
assert_above_256_error(gen_sum_code_v0(&path, 288, false, false));
|
|
2669
|
+
assert!(gen_sum_code_v0(&path, 256, false, false).is_ok());
|
|
2670
|
+
std::fs::remove_file(&path).ok();
|
|
2671
|
+
}
|
|
2672
|
+
|
|
2673
|
+
#[test]
|
|
2674
|
+
fn test_encode_component_above_256() {
|
|
2675
|
+
assert_above_256_error(encode_component(0, 0, 0, 512, &[0u8; 64]));
|
|
2676
|
+
assert_above_256_error(encode_component(0, 0, 0, 288, &[0u8; 36]));
|
|
2677
|
+
assert!(encode_component(0, 0, 0, 256, &[0u8; 32]).is_ok());
|
|
2678
|
+
}
|
|
2679
|
+
|
|
2680
|
+
#[test]
|
|
2681
|
+
fn test_iscc_decode_above_256() {
|
|
2682
|
+
assert_above_256_error(iscc_decode(&unit_288_bits(codec::MainType::Meta)));
|
|
2683
|
+
}
|
|
2684
|
+
|
|
2685
|
+
#[test]
|
|
2686
|
+
fn test_gen_iscc_code_v0_wide_above_256() {
|
|
2687
|
+
let data = unit_288_bits(codec::MainType::Data);
|
|
2688
|
+
let instance = gen_instance_code_v0(b"data", 128).unwrap().iscc;
|
|
2689
|
+
assert_above_256_error(gen_iscc_code_v0(&[&data, &instance], true));
|
|
2690
|
+
// Without `wide` the unit length is never decoded, as in iscc-core.
|
|
2691
|
+
assert!(gen_iscc_code_v0(&[&data, &instance], false).is_ok());
|
|
2692
|
+
}
|
|
2693
|
+
}
|