1use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
12use sha2::{Digest, Sha256};
13
14use super::{
15 radio_evidence::{encode_radio_evidence_records, RadioEvidenceError, RadioEvidenceRecord},
16 record::RecordClockStamp,
17};
18
19#[path = "radio_receipt_wire.rs"]
20mod wire;
21
22pub const RADIO_RECEIPT_VERSION: u16 = 1;
23pub const RADIO_RECEIPT_ENCODED_LEN: usize = 328;
24const RECEIPT_MAGIC: [u8; 4] = *b"RCP1";
25const SIGN_DOMAIN: &[u8] = b"qualia:radio-custody-receipt:v1\0";
26const CHAIN_DOMAIN: &[u8] = b"qualia:radio-custody-checkpoint:v1\0";
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum ReceiptTimestamp {
30 Unknown,
33 UnixSeconds(u64),
35 Monotonic(RecordClockStamp),
37 WindowsUtc100ns(i64),
39}
40
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub struct PolicyDecisionReference {
45 grant_digest: [u8; 32],
46 request_digest: [u8; 32],
47 decision_commitment: [u8; 32],
48}
49
50impl PolicyDecisionReference {
51 pub fn new(
52 grant_digest: [u8; 32],
53 request_digest: [u8; 32],
54 decision_commitment: [u8; 32],
55 ) -> Result<Self, RadioReceiptError> {
56 if all_zero(&grant_digest) || all_zero(&request_digest) || all_zero(&decision_commitment) {
57 return Err(RadioReceiptError::InvalidPolicyReference);
58 }
59 Ok(Self {
60 grant_digest,
61 request_digest,
62 decision_commitment,
63 })
64 }
65
66 pub const fn grant_digest(self) -> [u8; 32] {
67 self.grant_digest
68 }
69 pub const fn request_digest(self) -> [u8; 32] {
70 self.request_digest
71 }
72 pub const fn decision_commitment(self) -> [u8; 32] {
73 self.decision_commitment
74 }
75}
76
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub struct RadioCustodyReceipt {
81 version: u16,
82 record_id: u64,
83 source_id: u64,
84 capture_id: u64,
85 record_digest: [u8; 32],
86 sequence: u64,
87 previous_checkpoint: Option<[u8; 32]>,
88 timestamp: ReceiptTimestamp,
89 policy: Option<PolicyDecisionReference>,
90 signer_public_key: [u8; 32],
91 signature: [u8; 64],
92}
93
94impl RadioCustodyReceipt {
95 #[allow(clippy::too_many_arguments)]
99 pub fn sign(
100 record: RadioEvidenceRecord,
101 record_scratch: &mut [u8],
102 sequence: u64,
103 previous_checkpoint: Option<[u8; 32]>,
104 timestamp: ReceiptTimestamp,
105 policy: Option<PolicyDecisionReference>,
106 signer: &SigningKey,
107 ) -> Result<Self, RadioReceiptError> {
108 validate_chain_position(sequence, previous_checkpoint)?;
109 if previous_checkpoint.is_some_and(|digest| all_zero(&digest)) {
110 return Err(RadioReceiptError::InvalidPreviousCheckpoint);
111 }
112 let encoded_len = encode_radio_evidence_records(&[record], record_scratch)
113 .map_err(RadioReceiptError::Record)?;
114 if encoded_len != super::radio_evidence::RADIO_EVIDENCE_RECORD_SIZE {
115 return Err(RadioReceiptError::InvalidRecordEncoding);
116 }
117 let record_digest: [u8; 32] = Sha256::digest(&record_scratch[..encoded_len]).into();
118 let mut receipt = Self {
119 version: RADIO_RECEIPT_VERSION,
120 record_id: record.record_id(),
121 source_id: record.capture().source_id(),
122 capture_id: record.capture().capture_id(),
123 record_digest,
124 sequence,
125 previous_checkpoint,
126 timestamp,
127 policy,
128 signer_public_key: signer.verifying_key().to_bytes(),
129 signature: [0; 64],
130 };
131 receipt.signature = signer.sign(&receipt.signing_digest()).to_bytes();
132 Ok(receipt)
133 }
134
135 pub const fn version(self) -> u16 {
136 self.version
137 }
138 pub const fn record_id(self) -> u64 {
139 self.record_id
140 }
141 pub const fn source_id(self) -> u64 {
142 self.source_id
143 }
144 pub const fn capture_id(self) -> u64 {
145 self.capture_id
146 }
147 pub const fn record_digest(self) -> [u8; 32] {
148 self.record_digest
149 }
150 pub const fn sequence(self) -> u64 {
151 self.sequence
152 }
153 pub const fn previous_checkpoint(self) -> Option<[u8; 32]> {
154 self.previous_checkpoint
155 }
156 pub const fn timestamp(self) -> ReceiptTimestamp {
157 self.timestamp
158 }
159 pub const fn policy(self) -> Option<PolicyDecisionReference> {
160 self.policy
161 }
162 pub const fn signer_public_key(self) -> [u8; 32] {
163 self.signer_public_key
164 }
165 pub const fn signature(self) -> [u8; 64] {
166 self.signature
167 }
168
169 pub fn verify_signature(
173 &self,
174 record: RadioEvidenceRecord,
175 record_scratch: &mut [u8],
176 ) -> Result<ReceiptVerificationStatus, RadioReceiptError> {
177 self.validate_record_bytes(record, record_scratch)?;
178 let key = VerifyingKey::from_bytes(&self.signer_public_key)
179 .map_err(|_| RadioReceiptError::InvalidSignerKey)?;
180 let signature = Signature::from_bytes(&self.signature);
181 key.verify_strict(&self.signing_digest(), &signature)
182 .map_err(|_| RadioReceiptError::InvalidSignature)?;
183 Ok(ReceiptVerificationStatus::SignatureValidUntrusted)
184 }
185
186 pub fn verify_with_authority(
191 &self,
192 record: RadioEvidenceRecord,
193 record_scratch: &mut [u8],
194 authority: &impl RadioReceiptAuthority,
195 ) -> Result<ReceiptVerificationStatus, RadioReceiptError> {
196 self.verify_signature(record, record_scratch)?;
197 if self.version != RADIO_RECEIPT_VERSION
198 || !authority.signer_authorized(self.source_id, &self.signer_public_key)
199 {
200 return Err(RadioReceiptError::SignerNotTrusted);
201 }
202 if !authority.permission_context_valid(&record) {
203 return Err(RadioReceiptError::PermissionContextNotTrusted);
204 }
205 if let Some(policy) = self.policy {
206 if record
207 .permission()
208 .is_some_and(|context| context.grant_digest() != policy.grant_digest())
209 {
210 return Err(RadioReceiptError::PolicyBindingMismatch);
211 }
212 if !authority.policy_decision_valid(&self, &record, policy) {
213 return Err(RadioReceiptError::PolicyDecisionNotTrusted);
214 }
215 }
216 let checkpoint = self.checkpoint_digest();
217 if !authority.chain_position_valid(
218 self.sequence,
219 self.previous_checkpoint.as_ref(),
220 self.timestamp,
221 &checkpoint,
222 ) {
223 return Err(RadioReceiptError::ChainNotTrusted);
224 }
225 Ok(ReceiptVerificationStatus::VerifiedByAuthority)
226 }
227
228 pub fn signing_digest(&self) -> [u8; 32] {
230 let mut hash = Sha256::new();
231 hash.update(SIGN_DOMAIN);
232 hash.update(self.version.to_le_bytes());
233 hash.update(self.record_id.to_le_bytes());
234 hash.update(self.source_id.to_le_bytes());
235 hash.update(self.capture_id.to_le_bytes());
236 hash.update(self.record_digest);
237 hash.update(self.sequence.to_le_bytes());
238 hash_previous(&mut hash, self.previous_checkpoint);
239 hash_timestamp(&mut hash, self.timestamp);
240 hash_policy(&mut hash, self.policy);
241 hash.update(self.signer_public_key);
242 hash.finalize().into()
243 }
244
245 pub fn checkpoint_digest(&self) -> [u8; 32] {
247 let mut hash = Sha256::new();
248 hash.update(CHAIN_DOMAIN);
249 hash.update(self.signing_digest());
250 hash.update(self.signature);
251 hash.finalize().into()
252 }
253
254 pub fn encode_into(&self, out: &mut [u8]) -> Result<usize, RadioReceiptError> {
257 wire::encode(self, out)
258 }
259
260 pub fn decode_from(bytes: &[u8]) -> Result<Self, RadioReceiptError> {
264 wire::decode(bytes)
265 }
266
267 fn validate_record_bytes(
268 &self,
269 record: RadioEvidenceRecord,
270 record_scratch: &mut [u8],
271 ) -> Result<(), RadioReceiptError> {
272 if self.version != RADIO_RECEIPT_VERSION
273 || self.record_id != record.record_id()
274 || self.source_id != record.capture().source_id()
275 || self.capture_id != record.capture().capture_id()
276 {
277 return Err(RadioReceiptError::RecordMismatch);
278 }
279 let encoded_len = encode_radio_evidence_records(&[record], record_scratch)
280 .map_err(RadioReceiptError::Record)?;
281 if encoded_len != super::radio_evidence::RADIO_EVIDENCE_RECORD_SIZE {
282 return Err(RadioReceiptError::InvalidRecordEncoding);
283 }
284 let digest: [u8; 32] = Sha256::digest(&record_scratch[..encoded_len]).into();
285 if digest != self.record_digest {
286 return Err(RadioReceiptError::RecordMismatch);
287 }
288 Ok(())
289 }
290}
291
292#[derive(Clone, Copy, Debug, PartialEq, Eq)]
295pub enum ReceiptVerificationStatus {
296 SignatureValidUntrusted,
297 VerifiedByAuthority,
298}
299
300pub trait RadioReceiptAuthority {
305 fn signer_authorized(&self, source_id: u64, public_key: &[u8; 32]) -> bool;
306
307 fn permission_context_valid(&self, record: &RadioEvidenceRecord) -> bool;
311
312 fn policy_decision_valid(
313 &self,
314 receipt: &RadioCustodyReceipt,
315 record: &RadioEvidenceRecord,
316 policy: PolicyDecisionReference,
317 ) -> bool;
318
319 fn chain_position_valid(
320 &self,
321 sequence: u64,
322 previous_checkpoint: Option<&[u8; 32]>,
323 timestamp: ReceiptTimestamp,
324 current_checkpoint: &[u8; 32],
325 ) -> bool;
326}
327
328fn validate_chain_position(
329 sequence: u64,
330 previous: Option<[u8; 32]>,
331) -> Result<(), RadioReceiptError> {
332 if (sequence == 0) != previous.is_none() {
333 return Err(RadioReceiptError::InvalidChainPosition);
334 }
335 Ok(())
336}
337
338fn hash_previous(hash: &mut Sha256, previous: Option<[u8; 32]>) {
339 match previous {
340 Some(digest) => {
341 hash.update([1]);
342 hash.update(digest);
343 }
344 None => {
345 hash.update([0]);
346 hash.update([0; 32]);
347 }
348 }
349}
350
351fn hash_timestamp(hash: &mut Sha256, timestamp: ReceiptTimestamp) {
352 match timestamp {
353 ReceiptTimestamp::UnixSeconds(seconds) => {
354 hash.update([1]);
355 hash.update(seconds.to_le_bytes());
356 }
357 ReceiptTimestamp::Monotonic(stamp) => {
358 hash.update([2]);
359 hash.update(stamp.clock_id().to_le_bytes());
360 hash.update(stamp.restart_epoch().to_le_bytes());
361 hash.update(stamp.ticks_ns().to_le_bytes());
362 hash.update(stamp.uncertainty_ns().to_le_bytes());
363 }
364 ReceiptTimestamp::WindowsUtc100ns(ticks) => {
365 hash.update([3]);
366 hash.update(ticks.to_le_bytes());
367 }
368 ReceiptTimestamp::Unknown => {
369 hash.update([0]);
370 hash.update([0; 28]);
371 }
372 }
373}
374
375fn hash_policy(hash: &mut Sha256, policy: Option<PolicyDecisionReference>) {
376 match policy {
377 Some(policy) => {
378 hash.update([1]);
379 hash.update(policy.grant_digest);
380 hash.update(policy.request_digest);
381 hash.update(policy.decision_commitment);
382 }
383 None => {
384 hash.update([0]);
385 hash.update([0; 96]);
386 }
387 }
388}
389
390fn encode_previous(out: &mut [u8], cursor: &mut usize, previous: Option<[u8; 32]>) {
391 match previous {
392 Some(digest) => {
393 put(out, cursor, &[1]);
394 put(out, cursor, &digest);
395 }
396 None => {
397 put(out, cursor, &[0]);
398 put(out, cursor, &[0; 32]);
399 }
400 }
401}
402
403fn encode_timestamp(out: &mut [u8], cursor: &mut usize, timestamp: ReceiptTimestamp) {
404 match timestamp {
405 ReceiptTimestamp::Unknown => {
406 put(out, cursor, &[0]);
407 put(out, cursor, &[0; 28]);
408 }
409 ReceiptTimestamp::UnixSeconds(seconds) => {
410 put(out, cursor, &[1]);
411 put(out, cursor, &seconds.to_le_bytes());
412 put(out, cursor, &[0; 20]);
413 }
414 ReceiptTimestamp::Monotonic(stamp) => {
415 put(out, cursor, &[2]);
416 put(out, cursor, &stamp.clock_id().to_le_bytes());
417 put(out, cursor, &stamp.restart_epoch().to_le_bytes());
418 put(out, cursor, &stamp.ticks_ns().to_le_bytes());
419 put(out, cursor, &stamp.uncertainty_ns().to_le_bytes());
420 }
421 ReceiptTimestamp::WindowsUtc100ns(ticks) => {
422 put(out, cursor, &[3]);
423 put(out, cursor, &ticks.to_le_bytes());
424 put(out, cursor, &[0; 20]);
425 }
426 }
427}
428
429fn encode_policy(out: &mut [u8], cursor: &mut usize, policy: Option<PolicyDecisionReference>) {
430 match policy {
431 Some(policy) => {
432 put(out, cursor, &[1]);
433 put(out, cursor, &policy.grant_digest);
434 put(out, cursor, &policy.request_digest);
435 put(out, cursor, &policy.decision_commitment);
436 }
437 None => {
438 put(out, cursor, &[0]);
439 put(out, cursor, &[0; 96]);
440 }
441 }
442}
443
444fn put(out: &mut [u8], cursor: &mut usize, value: &[u8]) {
445 let end = *cursor + value.len();
446 out[*cursor..end].copy_from_slice(value);
447 *cursor = end;
448}
449
450fn all_zero(bytes: &[u8]) -> bool {
451 bytes.iter().all(|byte| *byte == 0)
452}
453
454#[derive(Clone, Copy, Debug, PartialEq, Eq)]
455pub enum RadioReceiptError {
456 Record(RadioEvidenceError),
457 InvalidPolicyReference,
458 InvalidPreviousCheckpoint,
459 InvalidChainPosition,
460 InvalidRecordEncoding,
461 OutputTooSmall { required: usize, available: usize },
462 RecordMismatch,
463 InvalidSignerKey,
464 InvalidSignature,
465 SignerNotTrusted,
466 PolicyDecisionNotTrusted,
467 ChainNotTrusted,
468 PermissionContextNotTrusted,
469 PolicyBindingMismatch,
470 InvalidTransport,
471}
472
473#[cfg(test)]
474#[path = "radio_receipt_tests.rs"]
475mod tests;