Skip to main content

fprint_fp3/
codec.rs

1// SPDX-FileCopyrightText: 2026 fprintd (pure-Rust) contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! The two verbs: [`to_bytes`] and [`from_bytes`].
6//!
7//! Maps the [`fprint_core::Print`] model onto the FP3 GVariant tuple `(issbymsmsia{sv}v)`,
8//! delegating date math to [`crate::date`] and the byte framing to [`crate::gvariant`].
9//! The FP3-specific decisions (the magic prefix, the empty reserved vardict, the
10//! payload-per-type dispatch, the "empty string ⇒ absent" convention for the driver/device
11//! ids) are made here.
12
13use fprint_core::{DeviceId, DriverId, Finger, Minutia, Print, Template};
14
15use crate::date;
16use crate::error::{Fp3Error, Result};
17use crate::gvariant::{self, Spec, Val};
18use crate::MAGIC;
19
20/// `FpiPrintType::UNDEFINED` — a fresh print; never serialized.
21const FPI_PRINT_UNDEFINED: i32 = 0;
22/// `FpiPrintType::RAW` — the payload is the driver's own opaque variant.
23const FPI_PRINT_RAW: i32 = 1;
24/// `FpiPrintType::NBIS` — the payload is host-side minutiae samples.
25const FPI_PRINT_NBIS: i32 = 2;
26
27/// The GVariant type signature of the NBIS payload's inner value.
28const NBIS_SIGNATURE: &[u8] = b"(a(aiaiai))";
29
30/// The static shape of the top-level tuple `(issbymsmsia{sv}v)`, in member order.
31pub(crate) const TOP_SPECS: [Spec; 10] = [
32    Spec::fixed(4, 4), // 0 `i`  kind
33    Spec::var(1),      // 1 `s`  driver
34    Spec::var(1),      // 2 `s`  device_id
35    Spec::fixed(1, 1), // 3 `b`  device_stored
36    Spec::fixed(1, 1), // 4 `y`  finger
37    Spec::var(1),      // 5 `ms` username
38    Spec::var(1),      // 6 `ms` description
39    Spec::fixed(4, 4), // 7 `i`  enroll_date
40    Spec::var(8),      // 8 `a{sv}` reserved
41    Spec::var(8),      // 9 `v`  payload
42];
43
44/// Serialize a [`Print`] to an FP3 blob: `"FP3"` magic followed by the GVariant tuple.
45///
46/// Partial in exactly two ways:
47///
48/// * [`Fp3Error::UndefinedTemplate`] for an un-enrolled print — it has no on-disk form.
49/// * [`Fp3Error::DateOutOfRange`] for an `enroll_date` whose Julian day leaves `i32`.
50///   [`EnrollDate`](fprint_core::EnrollDate)'s year is an unvalidated `i32`, so the domain model
51///   can name dates the wire cannot hold.
52pub fn to_bytes(print: &Print) -> Result<Vec<u8>> {
53    let (kind, payload) = match &print.template {
54        Template::Undefined => return Err(Fp3Error::UndefinedTemplate),
55        Template::Nbis(samples) => {
56            let inner = gvariant::tuple(
57                vec![gvariant::array(
58                    samples.iter().map(|s| sample_to_wire(s)).collect(),
59                    4,
60                )],
61                4,
62            );
63            (FPI_PRINT_NBIS, gvariant::variant(inner, NBIS_SIGNATURE))
64        }
65        // `raw` is a self-describing standalone `v`; write it into the tuple slot verbatim.
66        Template::Raw(raw) => (FPI_PRINT_RAW, gvariant::raw_variant(raw.clone())),
67        // `Template` is `#[non_exhaustive]`; an unknown future kind has no FP3 form.
68        _ => return Err(Fp3Error::UndefinedTemplate),
69    };
70
71    // An absent date is the sentinel; a present one must fit the wire's `i32` day count.
72    let julian = match print.enroll_date {
73        Some(date) => date::to_julian(date)?,
74        None => date::G_MININT32,
75    };
76
77    let tuple = gvariant::tuple(
78        vec![
79            gvariant::int32(kind),
80            gvariant::string(print.driver.as_ref().map_or("", DriverId::as_str)),
81            gvariant::string(print.device_id.as_ref().map_or("", DeviceId::as_str)),
82            gvariant::boolean(print.device_stored),
83            gvariant::byte(print.finger.map_or(0, Finger::as_u8)),
84            gvariant::maybe_string(print.username.as_deref()),
85            gvariant::maybe_string(print.description.as_deref()),
86            gvariant::int32(julian),
87            gvariant::empty_vardict(),
88            payload,
89        ],
90        8,
91    );
92
93    let body = tuple.into_bytes();
94    let mut out = Vec::with_capacity(MAGIC.len() + body.len());
95    out.extend_from_slice(MAGIC);
96    out.extend_from_slice(&body);
97    Ok(out)
98}
99
100/// Parse an FP3 blob back into a [`Print`].
101///
102/// The inverse of [`to_bytes`] for every print this crate can produce, up to the wire's two
103/// collapses: a zero `finger` byte decodes to `Some(Finger::Unknown)`, and empty driver/device
104/// ids decode to `None`. `tests/property.rs` states that law exactly and sweeps it.
105///
106/// Total over arbitrary bytes: every input yields `Ok` or `Err`, never a panic
107/// (`tests/malformed.rs`).
108pub fn from_bytes(bytes: &[u8]) -> Result<Print> {
109    if bytes.len() < MAGIC.len() {
110        return Err(Fp3Error::Truncated);
111    }
112    if &bytes[..MAGIC.len()] != MAGIC.as_slice() {
113        return Err(Fp3Error::BadMagic);
114    }
115
116    let members = gvariant::walk_tuple(&bytes[MAGIC.len()..], &TOP_SPECS)?;
117    let kind = gvariant::read_i32(members[0])?;
118    let driver = gvariant::read_string(members[1])?;
119    let device_id = gvariant::read_string(members[2])?;
120    let device_stored = gvariant::read_bool(members[3])?;
121    let finger_byte = gvariant::read_byte(members[4])?;
122    let username = gvariant::read_maybe_string(members[5])?;
123    let description = gvariant::read_maybe_string(members[6])?;
124    let enroll_date = gvariant::read_i32(members[7])?;
125    // members[8] is the reserved `a{sv}`; always empty, ignored on read.
126    let payload = members[9];
127
128    let template = match kind {
129        FPI_PRINT_NBIS => {
130            let (child, signature) = gvariant::split_variant(payload)?;
131            if signature != NBIS_SIGNATURE {
132                return Err(Fp3Error::PayloadType);
133            }
134            Template::Nbis(gvariant::read_var_array(child, 4, sample_from_wire)?)
135        }
136        // Preserve the driver's opaque variant exactly by keeping its bytes verbatim.
137        FPI_PRINT_RAW => Template::Raw(payload.to_vec()),
138        // UNDEFINED is never serialized; treat it and any stray discriminant alike.
139        FPI_PRINT_UNDEFINED => return Err(Fp3Error::UnknownType(FPI_PRINT_UNDEFINED)),
140        other => return Err(Fp3Error::UnknownType(other)),
141    };
142
143    let finger = Finger::from_u8(finger_byte).ok_or(Fp3Error::BadFinger(finger_byte))?;
144
145    Ok(Print::builder()
146        .template(template)
147        .finger(Some(finger))
148        .username(username)
149        .description(description)
150        .driver(non_empty(driver).map(DriverId::new))
151        .device_id(non_empty(device_id).map(DeviceId::new))
152        .device_stored(device_stored)
153        .enroll_date(
154            (enroll_date != date::G_MININT32)
155                .then(|| date::from_julian(enroll_date))
156                .flatten(),
157        )
158        .build())
159}
160
161/// An empty string means "unset" for the driver/device-id slots (GVariant `s` has no
162/// nullability); everything else is a real value.
163fn non_empty(s: String) -> Option<String> {
164    (!s.is_empty()).then_some(s)
165}
166
167/// Serialize one enrolled sample as the GVariant `(aiaiai)` triple of parallel columns.
168fn sample_to_wire(sample: &[Minutia]) -> Val {
169    let mut x = Vec::with_capacity(sample.len());
170    let mut y = Vec::with_capacity(sample.len());
171    let mut theta = Vec::with_capacity(sample.len());
172    for m in sample {
173        x.push(m.x);
174        y.push(m.y);
175        theta.push(m.theta);
176    }
177    gvariant::tuple(
178        vec![
179            gvariant::int32_array(&x),
180            gvariant::int32_array(&y),
181            gvariant::int32_array(&theta),
182        ],
183        4,
184    )
185}
186
187/// Parse one `(aiaiai)` sample slice back into minutiae, enforcing the equal-length invariant.
188fn sample_from_wire(slice: &[u8]) -> Result<Vec<Minutia>> {
189    let cols = gvariant::walk_tuple(slice, &[Spec::var(4), Spec::var(4), Spec::var(4)])?;
190    let x = gvariant::read_i32_array(cols[0])?;
191    let y = gvariant::read_i32_array(cols[1])?;
192    let theta = gvariant::read_i32_array(cols[2])?;
193    if x.len() != y.len() || y.len() != theta.len() {
194        return Err(Fp3Error::UnevenSampleArrays);
195    }
196    Ok(x.into_iter()
197        .zip(y)
198        .zip(theta)
199        .map(|((x, y), theta)| Minutia { x, y, theta })
200        .collect())
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206    use fprint_core::EnrollDate;
207
208    // ---- fixtures ---------------------------------------------------------------------
209
210    fn minutia(x: i32, y: i32, theta: i32) -> Minutia {
211        Minutia { x, y, theta }
212    }
213
214    /// A representative NBIS print with every metadata field set and several samples of
215    /// differing (non-zero) minutia counts, so a round-trip exercises the whole tuple.
216    fn nbis_print() -> Print {
217        Print::builder()
218            .template(Template::Nbis(vec![
219                vec![minutia(1, 2, 3), minutia(4, 5, 6)],
220                vec![minutia(7, 8, 9)],
221                vec![
222                    minutia(10, 11, 12),
223                    minutia(13, 14, 15),
224                    minutia(-1, -2, -3),
225                ],
226            ]))
227            .finger(Some(Finger::RightIndex))
228            .username(Some("alice".into()))
229            .description(Some("work laptop".into()))
230            .driver(Some(DriverId::new("goodix")))
231            .device_id(Some(DeviceId::new("0000")))
232            .enroll_date(Some(EnrollDate::new(2026, 7, 15)))
233            .build()
234    }
235
236    // ---- golden byte-strings ----------------------------------------------------------
237    //
238    // Frozen GLib-normal-form bytes, captured from a zvariant-based encoder whose output was
239    // validated against libfprint's framing. They are the oracle: the encoder must reproduce
240    // each byte-for-byte. Shapes with a zero-minutia sample carry no golden here — that
241    // encoder framed them wrong — and are covered by the round-trip tests instead.
242
243    /// (a) full NBIS: all metadata, samples of counts 2/1/3, a real enroll date.
244    const GOLDEN_NBIS_FULL: &[u8] = &[
245        0x46, 0x50, 0x33, 0x02, 0x00, 0x00, 0x00, 0x67, 0x6f, 0x6f, 0x64, 0x69, 0x78, 0x00, 0x30,
246        0x30, 0x30, 0x30, 0x00, 0x00, 0x07, 0x61, 0x6c, 0x69, 0x63, 0x65, 0x00, 0x00, 0x77, 0x6f,
247        0x72, 0x6b, 0x20, 0x6c, 0x61, 0x70, 0x74, 0x6f, 0x70, 0x00, 0x00, 0x00, 0x00, 0xe4, 0x49,
248        0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x02,
249        0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
250        0x10, 0x08, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00,
251        0x00, 0x08, 0x04, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0xff, 0xff,
252        0xff, 0xff, 0x0b, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0xfe, 0xff, 0xff, 0xff, 0x0c,
253        0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0xfd, 0xff, 0xff, 0xff, 0x18, 0x0c, 0x1a, 0x2a,
254        0x52, 0x00, 0x28, 0x61, 0x28, 0x61, 0x69, 0x61, 0x69, 0x61, 0x69, 0x29, 0x29, 0x30, 0x26,
255        0x19, 0x10, 0x0b,
256    ];
257
258    /// (b) NBIS with zero samples (`Nbis(vec![])`), finger = LeftThumb.
259    const GOLDEN_NBIS_ZERO_SAMPLES: &[u8] = &[
260        0x46, 0x50, 0x33, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x80,
261        0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x61, 0x28, 0x61, 0x69, 0x61, 0x69, 0x61, 0x69, 0x29,
262        0x29, 0x10, 0x08, 0x08, 0x06, 0x05,
263    ];
264
265    /// (d) RAW whose inner variant is a string, device_stored set, driver bound.
266    const GOLDEN_RAW_STRING: &[u8] = &[
267        0x46, 0x50, 0x33, 0x01, 0x00, 0x00, 0x00, 0x65, 0x6c, 0x61, 0x6e, 0x00, 0x00, 0x01, 0x03,
268        0x00, 0x00, 0x00, 0x80, 0x6f, 0x6e, 0x2d, 0x63, 0x68, 0x69, 0x70, 0x2d, 0x68, 0x61, 0x6e,
269        0x64, 0x6c, 0x65, 0x00, 0x00, 0x73, 0x10, 0x0c, 0x0c, 0x0a, 0x09,
270    ];
271
272    /// (e) RAW whose inner variant is `(su)`.
273    const GOLDEN_RAW_SU: &[u8] = &[
274        0x46, 0x50, 0x33, 0x01, 0x00, 0x00, 0x00, 0x65, 0x6c, 0x61, 0x6e, 0x00, 0x00, 0x01, 0x03,
275        0x00, 0x00, 0x00, 0x80, 0x73, 0x6c, 0x6f, 0x74, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00,
276        0x00, 0x05, 0x00, 0x28, 0x73, 0x75, 0x29, 0x10, 0x0c, 0x0c, 0x0a, 0x09,
277    ];
278
279    /// (f) maybe-strings: both present (`Some`/`Some`), single-minutia NBIS.
280    const GOLDEN_MAYBE_BOTH: &[u8] = &[
281        0x46, 0x50, 0x33, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x62, 0x6f, 0x62, 0x00,
282        0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x01, 0x00, 0x00,
283        0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x04, 0x0e, 0x00, 0x28, 0x61,
284        0x28, 0x61, 0x69, 0x61, 0x69, 0x61, 0x69, 0x29, 0x29, 0x18, 0x13, 0x0d, 0x06, 0x05,
285    ];
286
287    /// (f) maybe-strings: both absent (`None`/`None`), single-minutia NBIS.
288    const GOLDEN_MAYBE_NONE: &[u8] = &[
289        0x46, 0x50, 0x33, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x80,
290        0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
291        0x00, 0x08, 0x04, 0x0e, 0x00, 0x28, 0x61, 0x28, 0x61, 0x69, 0x61, 0x69, 0x61, 0x69, 0x29,
292        0x29, 0x10, 0x08, 0x08, 0x06, 0x05,
293    ];
294
295    /// (g) finger = Unknown(0), zero samples.
296    const GOLDEN_FINGER_UNKNOWN: &[u8] = &[
297        0x46, 0x50, 0x33, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
298        0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x61, 0x28, 0x61, 0x69, 0x61, 0x69, 0x61, 0x69, 0x29,
299        0x29, 0x10, 0x08, 0x08, 0x06, 0x05,
300    ];
301
302    /// The inner standalone `v` bytes for a RAW string handle (child + `0x00` + `"s"`).
303    const RAW_INNER_STRING: &[u8] = &[
304        0x6f, 0x6e, 0x2d, 0x63, 0x68, 0x69, 0x70, 0x2d, 0x68, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x00,
305        0x00, 0x73,
306    ];
307
308    /// The inner standalone `v` bytes for a RAW `(su)` handle (`("slot", 7u32)` + `0x00` + `"(su)"`).
309    const RAW_INNER_SU: &[u8] = &[
310        0x73, 0x6c, 0x6f, 0x74, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x05, 0x00, 0x28,
311        0x73, 0x75, 0x29,
312    ];
313
314    /// The inner standalone `v` bytes for a RAW `u64` handle (`42u64` + `0x00` + `"t"`).
315    const RAW_INNER_U64: &[u8] = &[0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74];
316
317    // ---- golden byte-exactness --------------------------------------------------------
318
319    #[test]
320    fn encoder_reproduces_goldens_byte_for_byte() {
321        assert_eq!(to_bytes(&nbis_print()).unwrap(), GOLDEN_NBIS_FULL);
322
323        let zero = Print::builder()
324            .template(Template::Nbis(vec![]))
325            .finger(Some(Finger::LeftThumb))
326            .build();
327        assert_eq!(to_bytes(&zero).unwrap(), GOLDEN_NBIS_ZERO_SAMPLES);
328
329        let raw_string = Print::builder()
330            .template(Template::Raw(RAW_INNER_STRING.to_vec()))
331            .finger(Some(Finger::LeftMiddle))
332            .driver(Some(DriverId::new("elan")))
333            .device_stored(true)
334            .build();
335        assert_eq!(to_bytes(&raw_string).unwrap(), GOLDEN_RAW_STRING);
336
337        let raw_su = Print::builder()
338            .template(Template::Raw(RAW_INNER_SU.to_vec()))
339            .finger(Some(Finger::LeftMiddle))
340            .driver(Some(DriverId::new("elan")))
341            .device_stored(true)
342            .build();
343        assert_eq!(to_bytes(&raw_su).unwrap(), GOLDEN_RAW_SU);
344
345        let both = Print::builder()
346            .template(Template::Nbis(vec![vec![minutia(1, 1, 1)]]))
347            .finger(Some(Finger::RightThumb))
348            .username(Some("bob".into()))
349            .description(Some("desc".into()))
350            .build();
351        assert_eq!(to_bytes(&both).unwrap(), GOLDEN_MAYBE_BOTH);
352
353        let none = Print::builder()
354            .template(Template::Nbis(vec![vec![minutia(1, 1, 1)]]))
355            .finger(Some(Finger::RightThumb))
356            .build();
357        assert_eq!(to_bytes(&none).unwrap(), GOLDEN_MAYBE_NONE);
358
359        let unknown = Print::builder()
360            .template(Template::Nbis(vec![]))
361            .finger(Some(Finger::Unknown))
362            .build();
363        assert_eq!(to_bytes(&unknown).unwrap(), GOLDEN_FINGER_UNKNOWN);
364    }
365
366    /// Every frozen golden must also decode back to the print that produced it.
367    #[test]
368    fn goldens_decode_back() {
369        assert_eq!(from_bytes(GOLDEN_NBIS_FULL).unwrap(), nbis_print());
370    }
371
372    // ---- container: magic & truncation ------------------------------------------------
373
374    #[test]
375    fn magic_prefix_is_written() {
376        let bytes = to_bytes(&nbis_print()).unwrap();
377        assert_eq!(&bytes[..3], MAGIC.as_slice());
378        assert_eq!(MAGIC, b"FP3");
379    }
380
381    #[test]
382    fn bad_magic_is_rejected() {
383        let mut bytes = to_bytes(&nbis_print()).unwrap();
384        bytes[0] = b'X';
385        assert!(matches!(from_bytes(&bytes), Err(Fp3Error::BadMagic)));
386    }
387
388    #[test]
389    fn truncated_is_rejected() {
390        assert!(matches!(from_bytes(&[]), Err(Fp3Error::Truncated)));
391        assert!(matches!(from_bytes(b"FP"), Err(Fp3Error::Truncated)));
392    }
393
394    // ---- type dispatch ----------------------------------------------------------------
395
396    #[test]
397    fn undefined_not_serializable() {
398        let print = Print::builder()
399            .template(Template::Undefined)
400            .finger(Some(Finger::Unknown))
401            .build();
402        assert!(matches!(to_bytes(&print), Err(Fp3Error::UndefinedTemplate)));
403    }
404
405    #[test]
406    fn undefined_discriminant_decodes_to_unknown_type() {
407        let bytes = to_bytes(&nbis_print()).unwrap();
408        // The `kind` i32 is the first tuple field, right after the 3-byte magic.
409        let mut forged = bytes.clone();
410        forged[3] = 0; // NBIS(2) -> UNDEFINED(0)
411        assert!(matches!(from_bytes(&forged), Err(Fp3Error::UnknownType(0))));
412        forged[3] = 7; // an out-of-range discriminant
413        assert!(matches!(from_bytes(&forged), Err(Fp3Error::UnknownType(7))));
414    }
415
416    // ---- NBIS -------------------------------------------------------------------------
417
418    #[test]
419    fn nbis_roundtrip() {
420        let print = nbis_print();
421        assert_eq!(from_bytes(&to_bytes(&print).unwrap()).unwrap(), print);
422    }
423
424    #[test]
425    fn nbis_roundtrip_zero_samples() {
426        let print = Print::builder()
427            .template(Template::Nbis(vec![]))
428            .finger(Some(Finger::LeftThumb))
429            .build();
430        assert_eq!(from_bytes(&to_bytes(&print).unwrap()).unwrap(), print);
431    }
432
433    // A capture that yielded no minutiae serializes to the degenerate `([], [], [])` sample —
434    // a zero-sized element of the `a(aiaiai)` array, framed as its two zero framing offsets.
435    // MINDTCT always emits minutiae, so this never occurs in real enrollment, but it
436    // round-trips exactly, both alone and mixed with real samples.
437    #[test]
438    fn nbis_zero_minutia_sample_roundtrips() {
439        let lone = Print::builder()
440            .template(Template::Nbis(vec![vec![]]))
441            .finger(Some(Finger::LeftIndex))
442            .build();
443        assert_eq!(from_bytes(&to_bytes(&lone).unwrap()).unwrap(), lone);
444
445        let mixed = Print::builder()
446            .template(Template::Nbis(vec![
447                vec![minutia(1, 2, 3)],
448                vec![],
449                vec![minutia(4, 5, 6), minutia(7, 8, 9)],
450            ]))
451            .finger(Some(Finger::LeftMiddle))
452            .build();
453        assert_eq!(from_bytes(&to_bytes(&mixed).unwrap()).unwrap(), mixed);
454    }
455
456    #[test]
457    fn nbis_uneven_arrays_rejected() {
458        // Hand-frame a `(aiaiai)` whose columns differ in length (x: 2, y: 1, theta: 2) and
459        // confirm the sample reader rejects it.
460        let sample = gvariant::tuple(
461            vec![
462                gvariant::int32_array(&[1, 2]),
463                gvariant::int32_array(&[3]),
464                gvariant::int32_array(&[4, 5]),
465            ],
466            4,
467        )
468        .into_bytes();
469        assert!(matches!(
470            sample_from_wire(&sample),
471            Err(Fp3Error::UnevenSampleArrays)
472        ));
473    }
474
475    // ---- RAW --------------------------------------------------------------------------
476
477    #[test]
478    fn raw_roundtrip() {
479        for inner in [RAW_INNER_STRING, RAW_INNER_SU, RAW_INNER_U64] {
480            let print = Print::builder()
481                .template(Template::Raw(inner.to_vec()))
482                .finger(Some(Finger::LeftMiddle))
483                .driver(Some(DriverId::new("elan")))
484                .device_stored(true)
485                .build();
486            // Print -> bytes -> Print
487            let bytes = to_bytes(&print).unwrap();
488            assert_eq!(from_bytes(&bytes).unwrap(), print);
489            // bytes -> Print -> bytes (byte-identical)
490            assert_eq!(to_bytes(&from_bytes(&bytes).unwrap()).unwrap(), bytes);
491        }
492    }
493
494    // ---- maybe-strings ----------------------------------------------------------------
495
496    #[test]
497    fn maybe_strings_all_combinations() {
498        for (u, d) in [
499            (None, None),
500            (Some("bob".to_string()), None),
501            (None, Some("desc".to_string())),
502            (Some("bob".to_string()), Some("desc".to_string())),
503        ] {
504            let print = Print::builder()
505                .template(Template::Nbis(vec![vec![minutia(1, 1, 1)]]))
506                .finger(Some(Finger::RightThumb))
507                .username(u)
508                .description(d)
509                .build();
510            assert_eq!(from_bytes(&to_bytes(&print).unwrap()).unwrap(), print);
511        }
512    }
513
514    // ---- finger byte ------------------------------------------------------------------
515
516    #[test]
517    fn finger_zero_is_unknown() {
518        let print = Print::builder()
519            .template(Template::Nbis(vec![]))
520            .finger(Some(Finger::Unknown))
521            .build();
522        let decoded = from_bytes(&to_bytes(&print).unwrap()).unwrap();
523        assert_eq!(decoded.finger, Some(Finger::Unknown));
524    }
525
526    #[test]
527    fn out_of_range_finger_byte_is_rejected() {
528        // Locate the finger byte by diffing two encodings that differ only in it, then poke
529        // an out-of-range value.
530        let mk = |f| {
531            Print::builder()
532                .template(Template::Nbis(vec![]))
533                .finger(Some(f))
534                .build()
535        };
536        let mut a = to_bytes(&mk(Finger::LeftThumb)).unwrap();
537        let b = to_bytes(&mk(Finger::LeftIndex)).unwrap();
538        let idx = a.iter().zip(&b).position(|(x, y)| x != y).unwrap();
539        a[idx] = 11;
540        assert!(matches!(from_bytes(&a), Err(Fp3Error::BadFinger(11))));
541    }
542
543    // ---- enroll date ------------------------------------------------------------------
544
545    /// `EnrollDate.year` is a public `i32` with no validation, and an `i32` year outranges the
546    /// wire's `i32` Julian day. **An unrepresentable date is an error, not a panic and not a
547    /// silently wrapped day.** No hostile bytes are needed to reach this.
548    #[test]
549    fn enroll_date_outside_the_julian_range_is_rejected() {
550        for year in [i32::MIN, i32::MAX] {
551            let print = Print::builder()
552                .template(Template::Nbis(vec![]))
553                .finger(Some(Finger::Unknown))
554                .enroll_date(Some(EnrollDate::new(year, 1, 1)))
555                .build();
556            assert!(matches!(to_bytes(&print), Err(Fp3Error::DateOutOfRange(_))));
557        }
558    }
559
560    /// The lowest Julian day a non-sentinel blob can carry decodes to a date that re-encodes to
561    /// the same day. The intermediate day count leaves `i32` here while the Julian day does not.
562    #[test]
563    fn extreme_julian_from_wire_reencodes_unchanged() {
564        let mut bytes = to_bytes(&nbis_print()).unwrap();
565        // The `enroll_date` i32 is tuple member 7; find it by diffing against a print whose
566        // date differs only in that field.
567        let mut other = nbis_print();
568        other.enroll_date = Some(EnrollDate::new(2026, 7, 16));
569        let idx = bytes
570            .iter()
571            .zip(&to_bytes(&other).unwrap())
572            .position(|(a, b)| a != b)
573            .unwrap();
574        bytes[idx..idx + 4].copy_from_slice(&(i32::MIN + 1).to_le_bytes());
575        let print = from_bytes(&bytes).unwrap();
576        assert_eq!(to_bytes(&print).unwrap(), bytes);
577    }
578
579    // ---- determinism ------------------------------------------------------------------
580
581    #[test]
582    fn deterministic_encode() {
583        let print = nbis_print();
584        assert_eq!(to_bytes(&print).unwrap(), to_bytes(&print).unwrap());
585        let bytes = to_bytes(&print).unwrap();
586        assert_eq!(to_bytes(&from_bytes(&bytes).unwrap()).unwrap(), bytes);
587    }
588
589    // ---- the primary invariant across a spread of prints ------------------------------
590
591    #[test]
592    fn roundtrip_is_identity() {
593        let prints = [
594            nbis_print(),
595            Print::builder()
596                .template(Template::Nbis(vec![
597                    vec![minutia(5, 5, 5)],
598                    vec![minutia(9, 9, 9)],
599                ]))
600                .finger(Some(Finger::RightLittle))
601                .device_stored(true)
602                .enroll_date(Some(EnrollDate::new(1, 1, 1)))
603                .build(),
604            Print::builder()
605                .template(Template::Raw(RAW_INNER_U64.to_vec()))
606                .finger(Some(Finger::LeftRing))
607                .device_stored(true)
608                .build(),
609        ];
610        for print in prints {
611            assert_eq!(from_bytes(&to_bytes(&print).unwrap()).unwrap(), print);
612        }
613    }
614}