fprint_core/print.rs
1// SPDX-FileCopyrightText: 2026 fprintd (pure-Rust) contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! Fingerprint prints/templates — the domain model behind libfprint's `FpPrint` and the
6//! on-disk FP3 format.
7//!
8//! A [`Print`] is metadata plus a [`Template`] payload. Serialization to/from the FP3
9//! byte format (`"FP3"` magic + GVariant `(issbymsmsia{sv}v)`) lives in the downstream
10//! `fprint-fp3` crate; this module is the in-memory model it maps to.
11
12use crate::{DeviceId, DriverId, Finger};
13
14/// A single detected minutia (MINDTCT output / BOZORTH3 input).
15///
16/// Maps to one column across libfprint's `xyt_struct` parallel arrays: `x`, `y`, and
17/// `theta` (orientation, degrees). In the FP3 payload these are stored as three int32
18/// arrays per enrolled sample (GVariant `(aiaiai)`).
19///
20/// The `fprint-mindtct` and `fprint-bozorth3` kernels stay dependency-free and define their own
21/// `Minutia` of the same shape; a backend maps between them at the boundary (via [`Self::from_xyt`] /
22/// [`Self::as_xyt`]). The derives match those kernels' so the three types line up.
23#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
24pub struct Minutia {
25 /// Column in the source image, in pixels.
26 pub x: i32,
27 /// Row in the source image, in pixels.
28 pub y: i32,
29 /// Ridge orientation in degrees.
30 pub theta: i32,
31}
32
33impl Minutia {
34 /// Construct a minutia from the `xyt` triple that crosses every kernel boundary.
35 #[must_use]
36 pub const fn from_xyt(x: i32, y: i32, theta: i32) -> Self {
37 Self { x, y, theta }
38 }
39
40 /// The `(x, y, theta)` triple, for handing this minutia to a matcher or detector that names
41 /// the same interoperability fact.
42 #[must_use]
43 pub const fn as_xyt(&self) -> (i32, i32, i32) {
44 (self.x, self.y, self.theta)
45 }
46}
47
48impl From<(i32, i32, i32)> for Minutia {
49 fn from((x, y, theta): (i32, i32, i32)) -> Self {
50 Self { x, y, theta }
51 }
52}
53
54/// Enrollment date (libfprint serializes this as a Julian-day int32; `None` ⇒ the
55/// `G_MININT32` "unset" sentinel).
56///
57/// Deliberately not `#[non_exhaustive]`: a fully-specified value type — three public fields, a
58/// checked [`try_new`](EnrollDate::try_new) and an unchecked [`new`](EnrollDate::new) — that
59/// callers construct and exhaustively match, matching its sibling [`InvalidEnrollDate`].
60#[derive(Clone, Copy, PartialEq, Eq, Debug)]
61pub struct EnrollDate {
62 /// Gregorian year.
63 pub year: i32,
64 /// Month, `1..=12`.
65 pub month: u8,
66 /// Day of month, `1..=31`.
67 pub day: u8,
68}
69
70impl EnrollDate {
71 /// An enrollment date from a `year`, `month`, and `day` the caller vouches for, without
72 /// range-checking — for reconstructing a known-good date (the FP3 Julian decoder). Untrusted
73 /// input goes through [`try_new`](EnrollDate::try_new).
74 #[must_use]
75 pub fn new(year: i32, month: u8, day: u8) -> Self {
76 EnrollDate { year, month, day }
77 }
78
79 /// An enrollment date, rejecting a `month` outside `1..=12` or a `day` outside `1..=31` with
80 /// an [`InvalidEnrollDate`] naming the offending field.
81 pub fn try_new(year: i32, month: u8, day: u8) -> Result<Self, InvalidEnrollDate> {
82 if !(1..=12).contains(&month) {
83 return Err(InvalidEnrollDate::Month(month));
84 }
85 if !(1..=31).contains(&day) {
86 return Err(InvalidEnrollDate::Day(day));
87 }
88 Ok(EnrollDate { year, month, day })
89 }
90}
91
92/// The error [`EnrollDate::try_new`] returns for a month outside `1..=12` or a day outside
93/// `1..=31`, naming the offending field and value.
94///
95/// Deliberately not `#[non_exhaustive]`: a fully-specified value error callers exhaustively match.
96#[derive(Clone, Copy, PartialEq, Eq, Debug)]
97pub enum InvalidEnrollDate {
98 /// The month was not in `1..=12`.
99 Month(u8),
100 /// The day was not in `1..=31`.
101 Day(u8),
102}
103
104impl core::fmt::Display for InvalidEnrollDate {
105 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
106 match self {
107 InvalidEnrollDate::Month(m) => write!(f, "{m} is not a valid month (expected 1..=12)"),
108 InvalidEnrollDate::Day(d) => write!(f, "{d} is not a valid day (expected 1..=31)"),
109 }
110 }
111}
112
113impl std::error::Error for InvalidEnrollDate {}
114
115/// The biometric payload of a print, matching libfprint's `FpiPrintType`.
116///
117/// `#[non_exhaustive]`: `FpiPrintType` is an external vocabulary that could grow, so adding a
118/// payload kind must not be a breaking change for downstream matchers.
119#[derive(Clone, PartialEq, Eq, Debug, Default)]
120#[non_exhaustive]
121pub enum Template {
122 /// `FPI_PRINT_UNDEFINED` — a fresh print handed to `enroll` before it is filled in.
123 #[default]
124 Undefined,
125 /// `FPI_PRINT_NBIS` — host-side minutiae comparison. One `Vec<Minutia>` per enrolled
126 /// capture (image-capture sensors typically enroll several samples).
127 Nbis(Vec<Vec<Minutia>>),
128 /// `FPI_PRINT_RAW` — data compared directly. For match-on-chip devices this is the
129 /// driver's opaque blob (often just a handle to a template stored on the sensor).
130 ///
131 /// Invariant relied on by `fprint-fp3` but not enforced here: the bytes are a
132 /// *self-describing, standalone GVariant variant* (`v`) — the driver's `print->data` —
133 /// which the codec writes and reads verbatim so a match-on-chip print round-trips
134 /// byte-for-byte.
135 Raw(Vec<u8>),
136}
137
138impl Template {
139 /// True for match-on-chip / device-stored payloads that libfprint never runs through
140 /// MINDTCT/BOZORTH3.
141 #[must_use]
142 pub fn is_raw(&self) -> bool {
143 matches!(self, Template::Raw(_))
144 }
145}
146
147/// A fingerprint print: biometric [`Template`] plus the metadata libfprint serializes
148/// alongside it.
149#[derive(Clone, PartialEq, Eq, Debug, Default)]
150#[non_exhaustive]
151pub struct Print {
152 /// The biometric payload. [`Template::Undefined`] until an enrollment fills it in.
153 pub template: Template,
154 /// Which finger this is, when known.
155 pub finger: Option<Finger>,
156 /// Owning user, as fprintd stores it under `/var/lib/fprint/<user>/`.
157 pub username: Option<String>,
158 /// Free-form label libfprint carries alongside the template.
159 pub description: Option<String>,
160 /// Driver id this template is bound to (templates are device/driver-specific).
161 pub driver: Option<DriverId>,
162 /// The specific reader this template came from, when the driver binds that tightly.
163 pub device_id: Option<DeviceId>,
164 /// True when the real template lives on the sensor and this `Print` is only a handle
165 /// (`fpi_print_set_device_stored`). Always true for MOC prints.
166 pub device_stored: bool,
167 /// When the print was enrolled, when the backend records it.
168 pub enroll_date: Option<EnrollDate>,
169}
170
171impl Print {
172 /// A blank print to hand to [`crate::Device::enroll`], tagged with the target finger.
173 #[must_use]
174 pub fn new_for_enroll(finger: Finger) -> Print {
175 Print {
176 finger: Some(finger),
177 ..Print::default()
178 }
179 }
180
181 /// A [`PrintBuilder`] with every field unset, the canonical way to construct a `Print`.
182 #[must_use]
183 pub fn builder() -> PrintBuilder {
184 PrintBuilder::default()
185 }
186
187 /// Whether this print's template is compatible with a device advertising `driver`.
188 ///
189 /// Corresponds to libfprint's `fp_print_compatible`, which additionally checks
190 /// `device_id` for some drivers; those transport-specific rules are left to the backend.
191 #[must_use]
192 pub fn is_compatible_with_driver(&self, driver: &DriverId) -> bool {
193 match &self.driver {
194 Some(d) => d == driver,
195 None => true, // not yet bound
196 }
197 }
198}
199
200/// Builder for [`Print`], one setter per field, terminated by [`build`](PrintBuilder::build).
201///
202/// `Print::default()` with field writes stays available; this is the fluent construction path
203/// and the one that survives new fields on `Print`.
204///
205/// Every optional-field setter takes `impl Into<Option<T>>`, so it accepts the bare value on the
206/// construction path (`.finger(Finger::RightIndex)`) and an `Option<T>` on a plumbing path that
207/// already holds one (`.finger(some_print.finger)`) — no `Some(...)` wrapping either way.
208#[derive(Clone, PartialEq, Eq, Debug, Default)]
209pub struct PrintBuilder {
210 template: Template,
211 finger: Option<Finger>,
212 username: Option<String>,
213 description: Option<String>,
214 driver: Option<DriverId>,
215 device_id: Option<DeviceId>,
216 device_stored: bool,
217 enroll_date: Option<EnrollDate>,
218}
219
220impl PrintBuilder {
221 /// Set the biometric payload.
222 #[must_use]
223 pub fn template(mut self, template: Template) -> Self {
224 self.template = template;
225 self
226 }
227
228 /// Set which finger this is. Takes a [`Finger`] or an `Option<Finger>`.
229 #[must_use]
230 pub fn finger(mut self, finger: impl Into<Option<Finger>>) -> Self {
231 self.finger = finger.into();
232 self
233 }
234
235 /// Set the owning user. Takes a [`String`] or an `Option<String>`.
236 #[must_use]
237 pub fn username(mut self, username: impl Into<Option<String>>) -> Self {
238 self.username = username.into();
239 self
240 }
241
242 /// Set the free-form label. Takes a [`String`] or an `Option<String>`.
243 #[must_use]
244 pub fn description(mut self, description: impl Into<Option<String>>) -> Self {
245 self.description = description.into();
246 self
247 }
248
249 /// Set the driver this template is bound to. Takes a [`DriverId`] or an `Option<DriverId>`.
250 #[must_use]
251 pub fn driver(mut self, driver: impl Into<Option<DriverId>>) -> Self {
252 self.driver = driver.into();
253 self
254 }
255
256 /// Set the specific reader this template came from. Takes a [`DeviceId`] or an `Option<DeviceId>`.
257 #[must_use]
258 pub fn device_id(mut self, device_id: impl Into<Option<DeviceId>>) -> Self {
259 self.device_id = device_id.into();
260 self
261 }
262
263 /// Set whether the real template lives on the sensor.
264 #[must_use]
265 pub fn device_stored(mut self, device_stored: bool) -> Self {
266 self.device_stored = device_stored;
267 self
268 }
269
270 /// Set the enrollment date. Takes an [`EnrollDate`] or an `Option<EnrollDate>`.
271 #[must_use]
272 pub fn enroll_date(mut self, enroll_date: impl Into<Option<EnrollDate>>) -> Self {
273 self.enroll_date = enroll_date.into();
274 self
275 }
276
277 /// Finish building the [`Print`].
278 #[must_use]
279 pub fn build(self) -> Print {
280 Print {
281 template: self.template,
282 finger: self.finger,
283 username: self.username,
284 description: self.description,
285 driver: self.driver,
286 device_id: self.device_id,
287 device_stored: self.device_stored,
288 enroll_date: self.enroll_date,
289 }
290 }
291}
292
293#[cfg(test)]
294mod tests {
295 use super::{EnrollDate, InvalidEnrollDate, Minutia, Print, Template};
296 use crate::{DriverId, Finger};
297
298 /// [`EnrollDate::try_new`] accepts an in-range date and rejects a month or day out of range,
299 /// naming the offending field. The boundaries `1..=12` / `1..=31` are inclusive.
300 #[test]
301 fn try_new_accepts_in_range_and_rejects_out_of_range() {
302 assert_eq!(
303 EnrollDate::try_new(2026, 7, 15),
304 Ok(EnrollDate::new(2026, 7, 15))
305 );
306 // Inclusive boundaries are accepted.
307 for (month, day) in [(1u8, 1u8), (12, 31)] {
308 assert_eq!(
309 EnrollDate::try_new(2026, month, day),
310 Ok(EnrollDate::new(2026, month, day))
311 );
312 }
313 // Out-of-range month/day are rejected, and the error names the offending value.
314 assert_eq!(
315 EnrollDate::try_new(2026, 0, 1),
316 Err(InvalidEnrollDate::Month(0))
317 );
318 assert_eq!(
319 EnrollDate::try_new(2026, 13, 1),
320 Err(InvalidEnrollDate::Month(13))
321 );
322 assert_eq!(
323 EnrollDate::try_new(2026, 1, 0),
324 Err(InvalidEnrollDate::Day(0))
325 );
326 assert_eq!(
327 EnrollDate::try_new(2026, 1, 32),
328 Err(InvalidEnrollDate::Day(32))
329 );
330 }
331
332 /// **A print built by [`Print::new_for_enroll`] carries its finger and nothing else.**
333 ///
334 /// The `Undefined` template is a cross-crate contract stated from this side: it is the one
335 /// `Print` that `fprint_fp3::to_bytes` must reject, because there is no biometric payload to
336 /// serialize. Pinned here as a shape, without depending on the codec.
337 #[test]
338 fn new_for_enroll_sets_the_finger_and_leaves_the_template_undefined() {
339 for finger in Finger::ALL.iter().chain(&[Finger::Unknown]) {
340 let print = Print::new_for_enroll(*finger);
341 assert_eq!(print.finger, Some(*finger));
342 assert_eq!(print.template, Template::Undefined);
343 assert!(!print.template.is_raw());
344 // Everything a backend fills in later is still absent.
345 assert_eq!(print.driver, None);
346 assert_eq!(print.device_id, None);
347 assert_eq!(print.username, None);
348 assert_eq!(print.description, None);
349 assert_eq!(print.enroll_date, None);
350 assert!(!print.device_stored);
351 }
352 }
353
354 /// An unbound print is compatible with every driver — a documented decision, so it is tested
355 /// rather than left to be rediscovered by whoever changes the `None` arm.
356 #[test]
357 fn an_unbound_print_is_compatible_with_any_driver() {
358 let print = Print::new_for_enroll(Finger::LeftIndex);
359 assert_eq!(print.driver, None);
360 for driver in ["goodixmoc", "synaptics", ""] {
361 assert!(print.is_compatible_with_driver(&DriverId::new(driver)));
362 }
363 }
364
365 /// A bound print is compatible with its own driver and no other.
366 #[test]
367 fn a_bound_print_is_compatible_only_with_its_own_driver() {
368 let print = Print {
369 driver: Some(DriverId::new("goodixmoc")),
370 ..Print::new_for_enroll(Finger::LeftIndex)
371 };
372 assert!(print.is_compatible_with_driver(&DriverId::new("goodixmoc")));
373 for other in ["synaptics", "GOODIXMOC", "goodixmoc2", ""] {
374 assert!(
375 !print.is_compatible_with_driver(&DriverId::new(other)),
376 "{other:?} must not match goodixmoc"
377 );
378 }
379 }
380
381 /// `is_raw` selects the match-on-chip payload and only it.
382 #[test]
383 fn is_raw_holds_only_for_the_raw_template() {
384 assert!(Template::Raw(Vec::new()).is_raw());
385 assert!(Template::Raw(b"handle".to_vec()).is_raw());
386 assert!(!Template::Undefined.is_raw());
387 assert!(!Template::default().is_raw());
388 assert!(!Template::Nbis(Vec::new()).is_raw());
389 assert!(!Template::Nbis(vec![vec![Minutia {
390 x: 1,
391 y: 2,
392 theta: 3
393 }]])
394 .is_raw());
395 }
396
397 /// `Template::default()` is `Undefined`: [`Print::default`] must not invent a payload.
398 #[test]
399 fn the_default_template_is_undefined() {
400 assert_eq!(Template::default(), Template::Undefined);
401 assert_eq!(Print::default().template, Template::Undefined);
402 assert_eq!(Print::default().finger, None);
403 }
404}