1use core::num::{NonZeroU32, NonZeroU64};
12
13use crate::{
14 foundation::frame_layout::{self, INLINE_TAG_INTEGER, INLINE_VALUE_MASK},
15 NQuin,
16};
17
18use super::{
19 authorization::{RevalidatedSensingUse, SensingAction, SensingModality},
20 record::RecordClockStamp,
21};
22
23#[path = "radio_evidence_wire.rs"]
24mod wire;
25pub use wire::encode_radio_evidence_records;
26
27pub const RADIO_EVIDENCE_VERSION: u16 = 1;
28pub const RADIO_EVIDENCE_RECORD_SIZE: usize = 256;
29pub const MAX_RADIO_EVIDENCE_RECORDS: usize = 256;
30
31pub const PROPOSED_RADIO_ADDRESS48_PREDICATE: u64 =
34 crate::q_hash("urn:qualia:proposed:sensing:radioAddress48");
35pub const PROPOSED_RADIO_PROTOCOL_PREDICATE: u64 =
36 crate::q_hash("urn:qualia:proposed:sensing:radioProtocol");
37pub const PROPOSED_RADIO_ASSIGNMENT_PREDICATE: u64 =
38 crate::q_hash("urn:qualia:proposed:sensing:radioAddressAssignment");
39pub const PROPOSED_RADIO_VOCABULARY_STATUS: &str = "proposed; not registered";
40
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub struct RadioAddress48([u8; 6]);
43
44impl RadioAddress48 {
45 pub const fn new(octets_msb_first: [u8; 6]) -> Self {
47 Self(octets_msb_first)
48 }
49
50 pub const fn octets_msb_first(self) -> [u8; 6] {
51 self.0
52 }
53
54 pub const fn value_u64(self) -> u64 {
57 ((self.0[0] as u64) << 40)
58 | ((self.0[1] as u64) << 32)
59 | ((self.0[2] as u64) << 24)
60 | ((self.0[3] as u64) << 16)
61 | ((self.0[4] as u64) << 8)
62 | (self.0[5] as u64)
63 }
64}
65
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
69pub enum AddressAssignmentKind {
70 Unknown,
71 Public,
72 Random,
73}
74
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
77pub enum RadioIdentifier {
78 Mac {
79 address: RadioAddress48,
80 assignment: AddressAssignmentKind,
81 },
82 Bssid {
83 address: RadioAddress48,
84 assignment: AddressAssignmentKind,
85 },
86 Bluetooth {
87 address: RadioAddress48,
88 assignment: AddressAssignmentKind,
89 },
90}
91
92impl RadioIdentifier {
93 pub const fn address(self) -> RadioAddress48 {
94 match self {
95 Self::Mac { address, .. }
96 | Self::Bssid { address, .. }
97 | Self::Bluetooth { address, .. } => address,
98 }
99 }
100
101 pub const fn assignment(self) -> AddressAssignmentKind {
102 match self {
103 Self::Mac { assignment, .. }
104 | Self::Bssid { assignment, .. }
105 | Self::Bluetooth { assignment, .. } => assignment,
106 }
107 }
108
109 const fn protocol_tag(self) -> u64 {
110 match self {
111 Self::Mac { .. } => 1,
112 Self::Bssid { .. } => 2,
113 Self::Bluetooth { .. } => 3,
114 }
115 }
116}
117
118#[derive(Clone, Copy, Debug, PartialEq, Eq)]
121pub enum RadioObservationTime {
122 Unknown,
123 QualifiedMonotonic(RecordClockStamp),
124 WindowsUtc100ns(i64),
126 NativeTicks {
127 ticks: i64,
128 clock_domain_id: Option<NonZeroU64>,
129 unit_id: Option<NonZeroU64>,
130 },
131}
132
133impl RadioObservationTime {
134 pub const fn native_ticks(
135 ticks: i64,
136 clock_domain_id: Option<u64>,
137 unit_id: Option<u64>,
138 ) -> Result<Self, RadioEvidenceError> {
139 let clock_domain_id = match clock_domain_id {
140 Some(value) => match NonZeroU64::new(value) {
141 Some(value) => Some(value),
142 None => return Err(RadioEvidenceError::InvalidIdentifier),
143 },
144 None => None,
145 };
146 let unit_id = match unit_id {
147 Some(value) => match NonZeroU64::new(value) {
148 Some(value) => Some(value),
149 None => return Err(RadioEvidenceError::InvalidIdentifier),
150 },
151 None => None,
152 };
153 Ok(Self::NativeTicks {
154 ticks,
155 clock_domain_id,
156 unit_id,
157 })
158 }
159}
160
161#[derive(Clone, Copy, Debug, PartialEq, Eq)]
164pub struct RadioCaptureReference {
165 source_id: NonZeroU64,
166 capture_id: NonZeroU64,
167 stream_id: Option<NonZeroU64>,
168 generation: Option<NonZeroU32>,
169 sequence: Option<u64>,
170}
171
172impl RadioCaptureReference {
173 pub const fn new(
174 source_id: u64,
175 capture_id: u64,
176 stream_id: Option<u64>,
177 generation: Option<u32>,
178 sequence: Option<u64>,
179 ) -> Result<Self, RadioEvidenceError> {
180 let source_id = match NonZeroU64::new(source_id) {
181 Some(value) => value,
182 None => return Err(RadioEvidenceError::InvalidIdentifier),
183 };
184 let capture_id = match NonZeroU64::new(capture_id) {
185 Some(value) => value,
186 None => return Err(RadioEvidenceError::InvalidIdentifier),
187 };
188 let stream_id = match stream_id {
189 Some(value) => match NonZeroU64::new(value) {
190 Some(value) => Some(value),
191 None => return Err(RadioEvidenceError::InvalidIdentifier),
192 },
193 None => None,
194 };
195 let generation = match generation {
196 Some(value) => match NonZeroU32::new(value) {
197 Some(value) => Some(value),
198 None => return Err(RadioEvidenceError::InvalidIdentifier),
199 },
200 None => None,
201 };
202 if stream_id.is_none() && (generation.is_some() || sequence.is_some()) {
205 return Err(RadioEvidenceError::InvalidCaptureReference);
206 }
207 Ok(Self {
208 source_id,
209 capture_id,
210 stream_id,
211 generation,
212 sequence,
213 })
214 }
215
216 pub const fn source_id(self) -> u64 {
217 self.source_id.get()
218 }
219 pub const fn capture_id(self) -> u64 {
220 self.capture_id.get()
221 }
222 pub const fn stream_id(self) -> Option<u64> {
223 match self.stream_id {
224 Some(v) => Some(v.get()),
225 None => None,
226 }
227 }
228 pub const fn generation(self) -> Option<u32> {
229 match self.generation {
230 Some(v) => Some(v.get()),
231 None => None,
232 }
233 }
234 pub const fn sequence(self) -> Option<u64> {
235 self.sequence
236 }
237}
238
239#[derive(Clone, Copy, Debug, PartialEq, Eq)]
240pub enum RadioEvidenceReference {
241 Unknown,
242 NotAttached,
243 Artifact([u8; 32]),
244}
245
246#[derive(Clone, Copy, Debug, PartialEq, Eq)]
249pub struct RadioPermissionContext {
250 grant_id: [u8; 32],
251 grant_digest: [u8; 32],
252 actor_id: [u8; 32],
253 source_id: NonZeroU64,
254 modality: SensingModality,
255 action: SensingAction,
256 purpose_hash: NonZeroU64,
257 checked_at_unix: u64,
258}
259
260impl RadioPermissionContext {
261 pub fn from_revalidated(
262 use_context: &RevalidatedSensingUse,
263 ) -> Result<Self, RadioEvidenceError> {
264 let request = use_context.request();
265 let source_id = NonZeroU64::new(request.source_id())
266 .ok_or(RadioEvidenceError::InvalidPermissionContext)?;
267 let purpose_hash = NonZeroU64::new(request.purpose_hash())
268 .ok_or(RadioEvidenceError::InvalidPermissionContext)?;
269 let grant_id = use_context.grant_id();
270 let grant_digest = use_context.grant_digest();
271 let actor_id = request.actor_id();
272 if all_zero(&grant_id) || all_zero(&grant_digest) || all_zero(&actor_id) {
273 return Err(RadioEvidenceError::InvalidPermissionContext);
274 }
275 Ok(Self {
276 grant_id,
277 grant_digest,
278 actor_id,
279 source_id,
280 modality: request.modality(),
281 action: request.action(),
282 purpose_hash,
283 checked_at_unix: use_context.checked_at_unix(),
284 })
285 }
286
287 pub const fn grant_id(self) -> [u8; 32] {
288 self.grant_id
289 }
290 pub const fn grant_digest(self) -> [u8; 32] {
291 self.grant_digest
292 }
293 pub const fn actor_id(self) -> [u8; 32] {
294 self.actor_id
295 }
296 pub const fn source_id(self) -> u64 {
297 self.source_id.get()
298 }
299 pub const fn modality(self) -> SensingModality {
300 self.modality
301 }
302 pub const fn action(self) -> SensingAction {
303 self.action
304 }
305 pub const fn purpose_hash(self) -> u64 {
306 self.purpose_hash.get()
307 }
308 pub const fn checked_at_unix(self) -> u64 {
309 self.checked_at_unix
310 }
311}
312
313#[derive(Clone, Copy, Debug, PartialEq, Eq)]
314pub struct RadioEvidenceRecord {
315 record_id: NonZeroU64,
316 identifier: RadioIdentifier,
317 capture: RadioCaptureReference,
318 time: RadioObservationTime,
319 evidence: RadioEvidenceReference,
320 permission: Option<RadioPermissionContext>,
321}
322
323impl RadioEvidenceRecord {
324 pub fn new(
325 record_id: u64,
326 identifier: RadioIdentifier,
327 capture: RadioCaptureReference,
328 time: RadioObservationTime,
329 evidence: RadioEvidenceReference,
330 permission: Option<RadioPermissionContext>,
331 ) -> Result<Self, RadioEvidenceError> {
332 let record_id = NonZeroU64::new(record_id).ok_or(RadioEvidenceError::InvalidIdentifier)?;
333 if matches!(evidence, RadioEvidenceReference::Artifact(id) if all_zero(&id)) {
334 return Err(RadioEvidenceError::InvalidEvidenceReference);
335 }
336 if permission.is_some_and(|context| context.source_id() != capture.source_id()) {
337 return Err(RadioEvidenceError::PermissionSourceMismatch);
338 }
339 if let Some(context) = permission {
340 if matches!(identifier, RadioIdentifier::Bssid { .. })
341 && context.modality() != SensingModality::Wifi
342 {
343 return Err(RadioEvidenceError::PermissionModalityMismatch);
344 }
345 if matches!(identifier, RadioIdentifier::Bluetooth { .. })
346 && context.modality() != SensingModality::Bluetooth
347 {
348 return Err(RadioEvidenceError::PermissionModalityMismatch);
349 }
350 }
351 Ok(Self {
352 record_id,
353 identifier,
354 capture,
355 time,
356 evidence,
357 permission,
358 })
359 }
360
361 pub const fn record_id(self) -> u64 {
362 self.record_id.get()
363 }
364 pub const fn identifier(self) -> RadioIdentifier {
365 self.identifier
366 }
367 pub const fn capture(self) -> RadioCaptureReference {
368 self.capture
369 }
370 pub const fn time(self) -> RadioObservationTime {
371 self.time
372 }
373 pub const fn evidence(self) -> RadioEvidenceReference {
374 self.evidence
375 }
376 pub const fn permission(self) -> Option<RadioPermissionContext> {
377 self.permission
378 }
379}
380
381#[derive(Clone, Copy, Debug, PartialEq, Eq)]
384pub struct RadioQuinMapping {
385 record_id: NonZeroU64,
386 observation_subject_hash: NonZeroU64,
387 context_hash: NonZeroU64,
388}
389
390impl RadioQuinMapping {
391 pub const fn new(
392 record_id: u64,
393 observation_subject_hash: u64,
394 context_hash: u64,
395 ) -> Result<Self, RadioEvidenceError> {
396 let record_id = match NonZeroU64::new(record_id) {
397 Some(value) => value,
398 None => return Err(RadioEvidenceError::InvalidIdentifier),
399 };
400 let observation_subject_hash = match NonZeroU64::new(observation_subject_hash) {
401 Some(value) => value,
402 None => return Err(RadioEvidenceError::InvalidIdentifier),
403 };
404 let context_hash = match NonZeroU64::new(context_hash) {
405 Some(value) => value,
406 None => return Err(RadioEvidenceError::InvalidIdentifier),
407 };
408 Ok(Self {
409 record_id,
410 observation_subject_hash,
411 context_hash,
412 })
413 }
414}
415
416pub fn radio_record_to_quins(
421 record: RadioEvidenceRecord,
422 mapping: RadioQuinMapping,
423 out: &mut [NQuin],
424) -> Result<usize, RadioEvidenceError> {
425 if out.len() < 3 {
426 return Err(RadioEvidenceError::OutputTooSmall {
427 required: 3,
428 available: out.len(),
429 });
430 }
431 if mapping.record_id != record.record_id {
432 return Err(RadioEvidenceError::RecordMappingMismatch);
433 }
434 let predicates = [
435 PROPOSED_RADIO_ADDRESS48_PREDICATE,
436 PROPOSED_RADIO_PROTOCOL_PREDICATE,
437 PROPOSED_RADIO_ASSIGNMENT_PREDICATE,
438 ];
439 if predicates[0] == predicates[1]
440 || predicates[0] == predicates[2]
441 || predicates[1] == predicates[2]
442 {
443 return Err(RadioEvidenceError::VocabularyCollision);
444 }
445 let values = [
446 record.identifier.address().value_u64(),
447 record.identifier.protocol_tag(),
448 wire::assignment_tag(record.identifier.assignment()),
449 ];
450 if values.iter().any(|value| value & !INLINE_VALUE_MASK != 0) {
451 return Err(RadioEvidenceError::IdentifierOutOfRange);
452 }
453 let mut staged = [NQuin::default(); 3];
454 for index in 0..3 {
455 staged[index] = frame_layout::sealed(NQuin {
456 subject: mapping.observation_subject_hash.get(),
457 predicate: predicates[index],
458 object: INLINE_TAG_INTEGER | values[index],
459 context: mapping.context_hash.get(),
460 metadata: 0,
461 parity: 0,
462 });
463 }
464 out[..3].copy_from_slice(&staged);
465 Ok(3)
466}
467
468fn all_zero(bytes: &[u8]) -> bool {
469 bytes.iter().all(|byte| *byte == 0)
470}
471
472#[derive(Clone, Copy, Debug, PartialEq, Eq)]
473pub enum RadioEvidenceError {
474 InvalidIdentifier,
475 InvalidCaptureReference,
476 InvalidEvidenceReference,
477 InvalidPermissionContext,
478 PermissionSourceMismatch,
479 PermissionModalityMismatch,
480 RecordMappingMismatch,
481 IdentifierOutOfRange,
482 VocabularyCollision,
483 OutputTooSmall { required: usize, available: usize },
484 TooManyRecords,
485 DuplicateRecordId,
486 RangeOverflow,
487}
488
489#[cfg(test)]
490#[path = "radio_evidence_tests.rs"]
491mod tests;