1use 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
20const FPI_PRINT_UNDEFINED: i32 = 0;
22const FPI_PRINT_RAW: i32 = 1;
24const FPI_PRINT_NBIS: i32 = 2;
26
27const NBIS_SIGNATURE: &[u8] = b"(a(aiaiai))";
29
30pub(crate) const TOP_SPECS: [Spec; 10] = [
32 Spec::fixed(4, 4), Spec::var(1), Spec::var(1), Spec::fixed(1, 1), Spec::fixed(1, 1), Spec::var(1), Spec::var(1), Spec::fixed(4, 4), Spec::var(8), Spec::var(8), ];
43
44pub 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 Template::Raw(raw) => (FPI_PRINT_RAW, gvariant::raw_variant(raw.clone())),
67 _ => return Err(Fp3Error::UndefinedTemplate),
69 };
70
71 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
100pub 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 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 FPI_PRINT_RAW => Template::Raw(payload.to_vec()),
138 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
161fn non_empty(s: String) -> Option<String> {
164 (!s.is_empty()).then_some(s)
165}
166
167fn 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
187fn 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 fn minutia(x: i32, y: i32, theta: i32) -> Minutia {
211 Minutia { x, y, theta }
212 }
213
214 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 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 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 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 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 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 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 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 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 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 const RAW_INNER_U64: &[u8] = &[0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74];
316
317 #[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 #[test]
368 fn goldens_decode_back() {
369 assert_eq!(from_bytes(GOLDEN_NBIS_FULL).unwrap(), nbis_print());
370 }
371
372 #[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 #[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 let mut forged = bytes.clone();
410 forged[3] = 0; assert!(matches!(from_bytes(&forged), Err(Fp3Error::UnknownType(0))));
412 forged[3] = 7; assert!(matches!(from_bytes(&forged), Err(Fp3Error::UnknownType(7))));
414 }
415
416 #[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 #[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 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 #[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 let bytes = to_bytes(&print).unwrap();
488 assert_eq!(from_bytes(&bytes).unwrap(), print);
489 assert_eq!(to_bytes(&from_bytes(&bytes).unwrap()).unwrap(), bytes);
491 }
492 }
493
494 #[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 #[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 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 #[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 #[test]
563 fn extreme_julian_from_wire_reencodes_unchanged() {
564 let mut bytes = to_bytes(&nbis_print()).unwrap();
565 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 #[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 #[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}