1use core::num::{NonZeroU32, NonZeroU64, NonZeroU8};
9
10use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
11use sha2::{Digest, Sha256};
12
13use super::{
14 radio_evidence::{RadioEvidenceReference, RadioObservationTime, RadioPermissionContext},
15 radio_receipt::ReceiptTimestamp,
16};
17
18pub const NFC_EVIDENCE_VERSION: u16 = 1;
19pub const NFC_EVIDENCE_RECORD_SIZE: usize = 320;
20pub const NFC_RECEIPT_ENCODED_LEN: usize = 240;
21pub const NFC_IDENTIFIER_MAX_LEN: usize = 32;
22const NFC_MAGIC: [u8; 4] = *b"NFC1";
23const RECEIPT_DOMAIN: &[u8] = b"qualia:variable-radio-custody:v1\0";
24const CHECKPOINT_DOMAIN: &[u8] = b"qualia:variable-radio-checkpoint:v1\0";
25
26#[path = "nfc_receipt_wire.rs"]
27mod receipt_wire;
28
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub enum VariableRadioIdentifierKind {
31 NfcUid,
32 ProtocolIdentifier,
33 OpaqueProtocolValue,
34}
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub enum ProtocolIdentifier {
38 Unknown,
39 Known(NonZeroU64),
40}
41
42impl ProtocolIdentifier {
43 pub const fn from_optional(value: u64) -> Self {
44 match NonZeroU64::new(value) {
45 Some(value) => Self::Known(value),
46 None => Self::Unknown,
47 }
48 }
49
50 pub const fn value(self) -> Option<u64> {
51 match self {
52 Self::Unknown => None,
53 Self::Known(value) => Some(value.get()),
54 }
55 }
56}
57
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub struct VariableRadioIdentifier {
62 kind: VariableRadioIdentifierKind,
63 protocol: ProtocolIdentifier,
64 len: NonZeroU8,
65 bytes: [u8; NFC_IDENTIFIER_MAX_LEN],
66}
67
68impl VariableRadioIdentifier {
69 pub fn new(
70 kind: VariableRadioIdentifierKind,
71 protocol: ProtocolIdentifier,
72 value: &[u8],
73 ) -> Result<Self, NfcEvidenceError> {
74 if value.is_empty() || value.len() > NFC_IDENTIFIER_MAX_LEN {
75 return Err(NfcEvidenceError::InvalidIdentifierLength);
76 }
77 let len =
78 NonZeroU8::new(value.len() as u8).ok_or(NfcEvidenceError::InvalidIdentifierLength)?;
79 let mut bytes = [0u8; NFC_IDENTIFIER_MAX_LEN];
80 bytes[..value.len()].copy_from_slice(value);
81 Ok(Self {
82 kind,
83 protocol,
84 len,
85 bytes,
86 })
87 }
88
89 pub const fn kind(self) -> VariableRadioIdentifierKind {
90 self.kind
91 }
92 pub const fn protocol(self) -> ProtocolIdentifier {
93 self.protocol
94 }
95 pub const fn len(self) -> usize {
96 self.len.get() as usize
97 }
98 pub fn bytes(&self) -> &[u8] {
99 &self.bytes[..self.len()]
100 }
101}
102
103#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub struct NfcEvidenceRecord {
109 record_id: NonZeroU64,
110 identifier: VariableRadioIdentifier,
111 source_id: NonZeroU64,
112 capture_id: NonZeroU64,
113 stream_id: Option<NonZeroU64>,
114 generation: Option<NonZeroU32>,
115 sequence: Option<u64>,
116 time: RadioObservationTime,
117 evidence: RadioEvidenceReference,
118 permission: Option<RadioPermissionContext>,
119}
120
121impl NfcEvidenceRecord {
122 #[allow(clippy::too_many_arguments)]
123 pub fn new(
124 record_id: u64,
125 identifier: VariableRadioIdentifier,
126 source_id: u64,
127 capture_id: u64,
128 stream_id: Option<u64>,
129 generation: Option<u32>,
130 sequence: Option<u64>,
131 time: RadioObservationTime,
132 evidence: RadioEvidenceReference,
133 permission: Option<RadioPermissionContext>,
134 ) -> Result<Self, NfcEvidenceError> {
135 let record_id = NonZeroU64::new(record_id).ok_or(NfcEvidenceError::InvalidReference)?;
136 let source_id = NonZeroU64::new(source_id).ok_or(NfcEvidenceError::InvalidReference)?;
137 let capture_id = NonZeroU64::new(capture_id).ok_or(NfcEvidenceError::InvalidReference)?;
138 let stream_id = match stream_id {
139 Some(value) => Some(NonZeroU64::new(value).ok_or(NfcEvidenceError::InvalidReference)?),
140 None => None,
141 };
142 let generation = match generation {
143 Some(value) => Some(NonZeroU32::new(value).ok_or(NfcEvidenceError::InvalidReference)?),
144 None => None,
145 };
146 if stream_id.is_none() && (generation.is_some() || sequence.is_some()) {
147 return Err(NfcEvidenceError::InvalidStreamReference);
148 }
149 if permission.is_some_and(|value| value.source_id() != source_id.get()) {
150 return Err(NfcEvidenceError::PermissionSourceMismatch);
151 }
152 if permission.is_some_and(|value| {
153 identifier.kind() == VariableRadioIdentifierKind::NfcUid
154 && value.modality() != super::authorization::SensingModality::Nfc
155 }) {
156 return Err(NfcEvidenceError::PermissionModalityMismatch);
157 }
158 if matches!(evidence, RadioEvidenceReference::Artifact(bytes) if bytes.iter().all(|v| *v == 0))
159 {
160 return Err(NfcEvidenceError::InvalidReference);
161 }
162 Ok(Self {
163 record_id,
164 identifier,
165 source_id,
166 capture_id,
167 stream_id,
168 generation,
169 sequence,
170 time,
171 evidence,
172 permission,
173 })
174 }
175
176 pub const fn record_id(self) -> u64 {
177 self.record_id.get()
178 }
179 pub const fn identifier(self) -> VariableRadioIdentifier {
180 self.identifier
181 }
182 pub const fn source_id(self) -> u64 {
183 self.source_id.get()
184 }
185 pub const fn capture_id(self) -> u64 {
186 self.capture_id.get()
187 }
188 pub const fn stream_id(self) -> Option<u64> {
189 match self.stream_id {
190 Some(value) => Some(value.get()),
191 None => None,
192 }
193 }
194 pub const fn generation(self) -> Option<u32> {
195 match self.generation {
196 Some(value) => Some(value.get()),
197 None => None,
198 }
199 }
200 pub const fn sequence(self) -> Option<u64> {
201 self.sequence
202 }
203 pub const fn time(self) -> RadioObservationTime {
204 self.time
205 }
206 pub const fn evidence(self) -> RadioEvidenceReference {
207 self.evidence
208 }
209 pub const fn permission(self) -> Option<RadioPermissionContext> {
210 self.permission
211 }
212}
213
214pub fn encode_nfc_evidence_record(
216 record: NfcEvidenceRecord,
217 out: &mut [u8],
218) -> Result<usize, NfcEvidenceError> {
219 if out.len() < NFC_EVIDENCE_RECORD_SIZE {
220 return Err(NfcEvidenceError::OutputTooSmall {
221 required: NFC_EVIDENCE_RECORD_SIZE,
222 available: out.len(),
223 });
224 }
225 let mut cursor = 0;
226 put(out, &mut cursor, &NFC_MAGIC);
227 put(out, &mut cursor, &NFC_EVIDENCE_VERSION.to_le_bytes());
228 put(
229 out,
230 &mut cursor,
231 &(NFC_EVIDENCE_RECORD_SIZE as u16).to_le_bytes(),
232 );
233 put(out, &mut cursor, &record.record_id().to_le_bytes());
234 put(out, &mut cursor, &record.source_id().to_le_bytes());
235 put(out, &mut cursor, &record.capture_id().to_le_bytes());
236 put_optional_u64(out, &mut cursor, record.stream_id());
237 put_optional_u32(out, &mut cursor, record.generation());
238 put_optional_u64(out, &mut cursor, record.sequence());
239 put_time(out, &mut cursor, record.time());
240 let identifier = record.identifier();
241 put(out, &mut cursor, &[identifier_kind_tag(identifier.kind())]);
242 match identifier.protocol().value() {
243 Some(value) => {
244 put(out, &mut cursor, &[1]);
245 put(out, &mut cursor, &value.to_le_bytes());
246 }
247 None => {
248 put(out, &mut cursor, &[0]);
249 put(out, &mut cursor, &[0; 8]);
250 }
251 }
252 put(out, &mut cursor, &[identifier.len() as u8]);
253 let mut bytes = [0; NFC_IDENTIFIER_MAX_LEN];
254 bytes[..identifier.len()].copy_from_slice(identifier.bytes());
255 put(out, &mut cursor, &bytes);
256 put_evidence(out, &mut cursor, record.evidence());
257 put_permission(out, &mut cursor, record.permission());
258 if cursor > NFC_EVIDENCE_RECORD_SIZE {
259 return Err(NfcEvidenceError::InvalidEncoding);
260 }
261 out[cursor..NFC_EVIDENCE_RECORD_SIZE].fill(0);
262 Ok(NFC_EVIDENCE_RECORD_SIZE)
263}
264
265#[derive(Clone, Copy, Debug, PartialEq, Eq)]
268pub struct NfcCustodyReceipt {
269 record_id: u64,
270 source_id: u64,
271 capture_id: u64,
272 digest: [u8; 32],
273 sequence: u64,
274 previous: Option<[u8; 32]>,
275 timestamp: ReceiptTimestamp,
276 signer_key: [u8; 32],
277 signature: [u8; 64],
278}
279
280impl NfcCustodyReceipt {
281 pub fn sign(
282 record: NfcEvidenceRecord,
283 scratch: &mut [u8],
284 sequence: u64,
285 previous: Option<[u8; 32]>,
286 timestamp: ReceiptTimestamp,
287 key: &SigningKey,
288 ) -> Result<Self, NfcEvidenceError> {
289 validate_chain(sequence, previous)?;
290 if previous.is_some_and(|value| value.iter().all(|byte| *byte == 0)) {
291 return Err(NfcEvidenceError::InvalidPrevious);
292 }
293 let len = encode_nfc_evidence_record(record, scratch)?;
294 let digest: [u8; 32] = Sha256::digest(&scratch[..len]).into();
295 let mut receipt = Self {
296 record_id: record.record_id(),
297 source_id: record.source_id(),
298 capture_id: record.capture_id(),
299 digest,
300 sequence,
301 previous,
302 timestamp,
303 signer_key: key.verifying_key().to_bytes(),
304 signature: [0; 64],
305 };
306 receipt.signature = key.sign(&receipt.signing_digest()).to_bytes();
307 Ok(receipt)
308 }
309
310 pub const fn record_digest(self) -> [u8; 32] {
311 self.digest
312 }
313 pub const fn sequence(self) -> u64 {
314 self.sequence
315 }
316 pub const fn previous_checkpoint(self) -> Option<[u8; 32]> {
317 self.previous
318 }
319 pub const fn timestamp(self) -> ReceiptTimestamp {
320 self.timestamp
321 }
322 pub const fn signer_key(self) -> [u8; 32] {
323 self.signer_key
324 }
325 pub const fn signature(self) -> [u8; 64] {
326 self.signature
327 }
328
329 pub fn verify_signature(
330 &self,
331 record: NfcEvidenceRecord,
332 scratch: &mut [u8],
333 ) -> Result<NfcReceiptStatus, NfcEvidenceError> {
334 if self.record_id != record.record_id()
335 || self.source_id != record.source_id()
336 || self.capture_id != record.capture_id()
337 {
338 return Err(NfcEvidenceError::RecordMismatch);
339 }
340 let len = encode_nfc_evidence_record(record, scratch)?;
341 let digest: [u8; 32] = Sha256::digest(&scratch[..len]).into();
342 if digest != self.digest {
343 return Err(NfcEvidenceError::RecordMismatch);
344 }
345 let key = VerifyingKey::from_bytes(&self.signer_key)
346 .map_err(|_| NfcEvidenceError::InvalidSignerKey)?;
347 key.verify_strict(
348 &self.signing_digest(),
349 &Signature::from_bytes(&self.signature),
350 )
351 .map_err(|_| NfcEvidenceError::InvalidSignature)?;
352 Ok(NfcReceiptStatus::SignatureValidUntrusted)
353 }
354
355 pub fn verify_with_authority(
356 &self,
357 record: NfcEvidenceRecord,
358 scratch: &mut [u8],
359 authority: &impl NfcReceiptAuthority,
360 ) -> Result<NfcReceiptStatus, NfcEvidenceError> {
361 self.verify_signature(record, scratch)?;
362 if !authority.signer_authorized(self.source_id, &self.signer_key) {
363 return Err(NfcEvidenceError::SignerNotTrusted);
364 }
365 if !authority.permission_context_valid(&record) {
366 return Err(NfcEvidenceError::PermissionNotTrusted);
367 }
368 let checkpoint = self.checkpoint_digest();
369 if !authority.chain_position_valid(
370 self.sequence,
371 self.previous.as_ref(),
372 self.timestamp,
373 &checkpoint,
374 ) {
375 return Err(NfcEvidenceError::ChainNotTrusted);
376 }
377 Ok(NfcReceiptStatus::VerifiedByAuthority)
378 }
379
380 pub fn encode_into(&self, out: &mut [u8]) -> Result<usize, NfcEvidenceError> {
382 receipt_wire::encode(self, out)
383 }
384
385 pub fn decode_from(bytes: &[u8]) -> Result<Self, NfcEvidenceError> {
388 receipt_wire::decode(bytes)
389 }
390
391 fn signing_digest(&self) -> [u8; 32] {
392 let mut hash = Sha256::new();
393 hash.update(RECEIPT_DOMAIN);
394 hash.update(self.record_id.to_le_bytes());
395 hash.update(self.source_id.to_le_bytes());
396 hash.update(self.capture_id.to_le_bytes());
397 hash.update(self.digest);
398 hash.update(self.sequence.to_le_bytes());
399 hash_previous(&mut hash, self.previous);
400 hash_timestamp(&mut hash, self.timestamp);
401 hash.update(self.signer_key);
402 hash.finalize().into()
403 }
404
405 fn checkpoint_digest(&self) -> [u8; 32] {
406 let mut hash = Sha256::new();
407 hash.update(CHECKPOINT_DOMAIN);
408 hash.update(self.signing_digest());
409 hash.update(self.signature);
410 hash.finalize().into()
411 }
412}
413
414#[derive(Clone, Copy, Debug, PartialEq, Eq)]
415pub enum NfcReceiptStatus {
416 SignatureValidUntrusted,
417 VerifiedByAuthority,
418}
419
420pub trait NfcReceiptAuthority {
425 fn signer_authorized(&self, source_id: u64, key: &[u8; 32]) -> bool;
426 fn permission_context_valid(&self, record: &NfcEvidenceRecord) -> bool;
427 fn chain_position_valid(
428 &self,
429 sequence: u64,
430 previous: Option<&[u8; 32]>,
431 timestamp: ReceiptTimestamp,
432 current: &[u8; 32],
433 ) -> bool;
434}
435
436#[derive(Clone, Copy, Debug, PartialEq, Eq)]
437pub enum NfcEvidenceError {
438 InvalidIdentifierLength,
439 InvalidReference,
440 InvalidStreamReference,
441 PermissionSourceMismatch,
442 PermissionModalityMismatch,
443 OutputTooSmall { required: usize, available: usize },
444 InvalidEncoding,
445 InvalidPrevious,
446 InvalidChain,
447 RecordMismatch,
448 InvalidSignerKey,
449 InvalidSignature,
450 SignerNotTrusted,
451 PermissionNotTrusted,
452 ChainNotTrusted,
453 InvalidTransport,
454}
455
456fn identifier_kind_tag(kind: VariableRadioIdentifierKind) -> u8 {
457 match kind {
458 VariableRadioIdentifierKind::NfcUid => 1,
459 VariableRadioIdentifierKind::ProtocolIdentifier => 2,
460 VariableRadioIdentifierKind::OpaqueProtocolValue => 3,
461 }
462}
463
464fn put_time(out: &mut [u8], cursor: &mut usize, time: RadioObservationTime) {
465 match time {
466 RadioObservationTime::Unknown => {
467 put(out, cursor, &[0]);
468 put(out, cursor, &[0; 28]);
469 }
470 RadioObservationTime::QualifiedMonotonic(stamp) => {
471 put(out, cursor, &[1]);
472 put(out, cursor, &stamp.clock_id().to_le_bytes());
473 put(out, cursor, &stamp.restart_epoch().to_le_bytes());
474 put(out, cursor, &stamp.ticks_ns().to_le_bytes());
475 put(out, cursor, &stamp.uncertainty_ns().to_le_bytes());
476 }
477 RadioObservationTime::WindowsUtc100ns(ticks) => {
478 put(out, cursor, &[2]);
479 put(out, cursor, &ticks.to_le_bytes());
480 put(out, cursor, &[0; 20]);
481 }
482 RadioObservationTime::NativeTicks {
483 ticks,
484 clock_domain_id,
485 unit_id,
486 } => {
487 put(out, cursor, &[3]);
488 put(out, cursor, &ticks.to_le_bytes());
489 put_optional_u64(out, cursor, clock_domain_id.map(|value| value.get()));
490 put_optional_u64(out, cursor, unit_id.map(|value| value.get()));
491 put(out, cursor, &[0; 2]);
492 }
493 }
494}
495
496fn put_evidence(out: &mut [u8], cursor: &mut usize, evidence: RadioEvidenceReference) {
497 match evidence {
498 RadioEvidenceReference::Unknown => {
499 put(out, cursor, &[0]);
500 put(out, cursor, &[0; 32]);
501 }
502 RadioEvidenceReference::NotAttached => {
503 put(out, cursor, &[1]);
504 put(out, cursor, &[0; 32]);
505 }
506 RadioEvidenceReference::Artifact(bytes) => {
507 put(out, cursor, &[2]);
508 put(out, cursor, &bytes);
509 }
510 }
511}
512
513fn put_permission(out: &mut [u8], cursor: &mut usize, permission: Option<RadioPermissionContext>) {
514 match permission {
515 None => {
516 put(out, cursor, &[0]);
517 put(out, cursor, &[0; 122]);
518 }
519 Some(value) => {
520 put(out, cursor, &[1]);
521 put(out, cursor, &value.grant_id());
522 put(out, cursor, &value.grant_digest());
523 put(out, cursor, &value.actor_id());
524 put(out, cursor, &value.source_id().to_le_bytes());
525 put(
526 out,
527 cursor,
528 &[modality_tag(value.modality()), action_tag(value.action())],
529 );
530 put(out, cursor, &value.purpose_hash().to_le_bytes());
531 put(out, cursor, &value.checked_at_unix().to_le_bytes());
532 }
533 }
534}
535
536fn modality_tag(value: super::authorization::SensingModality) -> u8 {
537 use super::authorization::SensingModality::*;
538 match value {
539 Wifi => 1,
540 Bluetooth => 2,
541 Cellular => 3,
542 Sdr => 4,
543 Radar => 5,
544 VisibleCamera => 6,
545 NearInfraredCamera => 7,
546 ThermalCamera => 8,
547 Microphone => 9,
548 FieldInstrument => 10,
549 Nfc => 11,
550 }
551}
552fn action_tag(value: super::authorization::SensingAction) -> u8 {
553 use super::authorization::SensingAction::*;
554 match value {
555 Acquire => 1,
556 Process => 2,
557 Store => 3,
558 Export => 4,
559 Share => 5,
560 }
561}
562fn put_optional_u64(out: &mut [u8], cursor: &mut usize, value: Option<u64>) {
563 match value {
564 Some(value) => {
565 put(out, cursor, &[1]);
566 put(out, cursor, &value.to_le_bytes());
567 }
568 None => {
569 put(out, cursor, &[0]);
570 put(out, cursor, &[0; 8]);
571 }
572 }
573}
574fn put_optional_u32(out: &mut [u8], cursor: &mut usize, value: Option<u32>) {
575 match value {
576 Some(value) => {
577 put(out, cursor, &[1]);
578 put(out, cursor, &value.to_le_bytes());
579 }
580 None => {
581 put(out, cursor, &[0]);
582 put(out, cursor, &[0; 4]);
583 }
584 }
585}
586fn put(out: &mut [u8], cursor: &mut usize, bytes: &[u8]) {
587 let end = *cursor + bytes.len();
588 out[*cursor..end].copy_from_slice(bytes);
589 *cursor = end;
590}
591fn validate_chain(sequence: u64, previous: Option<[u8; 32]>) -> Result<(), NfcEvidenceError> {
592 if (sequence == 0) == previous.is_none() {
593 Ok(())
594 } else {
595 Err(NfcEvidenceError::InvalidChain)
596 }
597}
598fn hash_previous(hash: &mut Sha256, previous: Option<[u8; 32]>) {
599 match previous {
600 Some(value) => {
601 hash.update([1]);
602 hash.update(value);
603 }
604 None => {
605 hash.update([0]);
606 hash.update([0; 32]);
607 }
608 }
609}
610fn hash_timestamp(hash: &mut Sha256, timestamp: ReceiptTimestamp) {
611 match timestamp {
612 ReceiptTimestamp::Unknown => {
613 hash.update([0]);
614 hash.update([0; 28]);
615 }
616 ReceiptTimestamp::UnixSeconds(value) => {
617 hash.update([1]);
618 hash.update(value.to_le_bytes());
619 }
620 ReceiptTimestamp::Monotonic(value) => {
621 hash.update([2]);
622 hash.update(value.clock_id().to_le_bytes());
623 hash.update(value.restart_epoch().to_le_bytes());
624 hash.update(value.ticks_ns().to_le_bytes());
625 hash.update(value.uncertainty_ns().to_le_bytes());
626 }
627 ReceiptTimestamp::WindowsUtc100ns(value) => {
628 hash.update([3]);
629 hash.update(value.to_le_bytes());
630 }
631 }
632}
633
634#[cfg(test)]
635#[path = "nfc_evidence_tests.rs"]
636mod tests;