1use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
7
8use crate::governance::consent_contract::ConsentGrant;
9use crate::sensing::authority::certificates::{
10 CalibrationError, CalibrationValidityWindow, RationalInstant,
11};
12use crate::sensing::authorization::{
13 AuthorizationError, RevocationAuthority, TrustedUnixClock,
14};
15use crate::sensing::SemanticId;
16
17pub const COMMAND_RECEIPT_DOMAIN: &[u8] = b"QUALIA-SIMULATOR-COMMAND-RECEIPT-v1\0";
19
20pub const COMMAND_SIG_DOMAIN: &[u8] = b"QUALIA-SIMULATOR-COMMAND-SIG-v1\0";
22
23pub const MAX_COMMAND_REPLAY_ENTRIES: usize = 64;
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28#[repr(u32)]
29pub enum ProvenanceRole {
30 Measured = 0,
31 Model = 1,
32 Derived = 2,
33 Command = 3,
34 OpaquePreserved = 4,
35}
36
37impl ProvenanceRole {
38 pub const fn from_code(code: u32) -> Result<Self, ActuationGateError> {
39 match code {
40 0 => Ok(Self::Measured),
41 1 => Ok(Self::Model),
42 2 => Ok(Self::Derived),
43 3 => Ok(Self::Command),
44 4 => Ok(Self::OpaquePreserved),
45 _ => Err(ActuationGateError::InvalidProvenanceRoleCode(code)),
46 }
47 }
48}
49
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum EpistemicClass {
53 Empirical,
54 ModelEstimate,
55 Hypothesis,
56 Counterfactual,
57 Fictional,
58}
59
60impl EpistemicClass {
61 pub fn from_wire_str(s: &str) -> Result<Self, ActuationGateError> {
62 match s {
63 "empirical" => Ok(Self::Empirical),
64 "model_estimate" => Ok(Self::ModelEstimate),
65 "hypothesis" => Ok(Self::Hypothesis),
66 "counterfactual" => Ok(Self::Counterfactual),
67 "fictional" => Ok(Self::Fictional),
68 _ => Err(ActuationGateError::UnknownEpistemicClass),
69 }
70 }
71
72 pub const fn as_wire_str(self) -> &'static str {
73 match self {
74 Self::Empirical => "empirical",
75 Self::ModelEstimate => "model_estimate",
76 Self::Hypothesis => "hypothesis",
77 Self::Counterfactual => "counterfactual",
78 Self::Fictional => "fictional",
79 }
80 }
81
82 pub const fn is_admissible_in_empirical_join(self) -> bool {
84 matches!(self, Self::Empirical)
85 }
86}
87
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub enum HapticSchema207Role {
91 Measurement,
92 ReceptorModel,
93 ActuatorCommand,
94}
95
96impl HapticSchema207Role {
97 pub fn from_wire_str(s: &str) -> Result<Self, ActuationGateError> {
98 match s {
99 "measurement" => Ok(Self::Measurement),
100 "receptor-model" => Ok(Self::ReceptorModel),
101 "actuator-command" => Ok(Self::ActuatorCommand),
102 _ => Err(ActuationGateError::UnknownDomainRole),
103 }
104 }
105}
106
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109pub enum UltrasoundSchema208Role {
110 RawRf,
111 BasebandIq,
112 BeamSummary,
113 TransmitCommand,
114}
115
116impl UltrasoundSchema208Role {
117 pub fn from_wire_str(s: &str) -> Result<Self, ActuationGateError> {
118 match s {
119 "raw-RF" => Ok(Self::RawRf),
120 "baseband-IQ" => Ok(Self::BasebandIq),
121 "beam-summary" => Ok(Self::BeamSummary),
122 "transmit-command" => Ok(Self::TransmitCommand),
123 _ => Err(ActuationGateError::UnknownDomainRole),
124 }
125 }
126}
127
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub enum PassiveArtifactKind {
132 IonizingDoseGyOrSv,
134 UltrasoundMechanicalOrThermalIndex,
136 MeasuredHapticForceOrIndentation,
138 PerceptualPitchOrVoiceFeature,
140 IntegrityCrcOrBlake3Digest,
142 PassiveConsentGrantId,
144 CalibrationCertificateDigest,
146}
147
148pub const fn reject_passive_artifact_for_actuation(
151 artifact: PassiveArtifactKind,
152) -> Result<(), ActuationGateError> {
153 Err(ActuationGateError::PassiveObservationCannotAuthorizeActuation(artifact))
154}
155
156#[derive(Clone, Copy, Debug, PartialEq, Eq)]
158pub struct ProvenanceRoleRecord {
159 pub role: ProvenanceRole,
160 pub source_digest: Option<[u8; 32]>,
161 pub algorithm_id: SemanticId,
162 pub algorithm_version: SemanticId,
163 pub instrument_uri: SemanticId,
164 pub authority_receipt_digest: Option<[u8; 32]>,
165}
166
167impl ProvenanceRoleRecord {
168 pub fn validate(&self) -> Result<(), ActuationGateError> {
174 if let Some(d) = self.source_digest {
175 if d == [0u8; 32] {
176 return Err(ActuationGateError::InvalidIdentifier);
177 }
178 }
179 if let Some(r) = self.authority_receipt_digest {
180 if r == [0u8; 32] {
181 return Err(ActuationGateError::InvalidIdentifier);
182 }
183 }
184 match self.role {
185 ProvenanceRole::Measured => {
186 if self.instrument_uri.value().is_none() {
187 return Err(ActuationGateError::MissingInstrumentForMeasuredRole);
188 }
189 }
190 ProvenanceRole::Model | ProvenanceRole::Derived => {
191 if self.algorithm_id.value().is_none()
192 || self.algorithm_version.value().is_none()
193 || self.source_digest.is_none()
194 {
195 return Err(ActuationGateError::MissingAlgorithmOrSourceForModelDerivedRole);
196 }
197 }
198 ProvenanceRole::OpaquePreserved => {
199 if self.source_digest.is_none() {
200 return Err(ActuationGateError::MissingSourceDigestForOpaqueRole);
201 }
202 }
203 ProvenanceRole::Command => {
204 if self.authority_receipt_digest.is_none() {
205 return Err(ActuationGateError::MissingCommandReceiptForCommandRole);
206 }
207 }
208 }
209 Ok(())
210 }
211}
212
213pub fn verify_empirical_join_admission(
220 left_role: ProvenanceRole,
221 left_class: EpistemicClass,
222 right_role: ProvenanceRole,
223 right_class: EpistemicClass,
224) -> Result<(), ActuationGateError> {
225 for role in [left_role, right_role] {
226 if !matches!(role, ProvenanceRole::Measured | ProvenanceRole::Derived) {
227 return Err(ActuationGateError::RoleForbiddenInEmpiricalJoin(role));
228 }
229 }
230 for class in [left_class, right_class] {
231 if !class.is_admissible_in_empirical_join() {
232 return Err(ActuationGateError::NonEmpiricalClassRejected(class));
233 }
234 }
235 Ok(())
236}
237
238#[derive(Clone, Copy, Debug, PartialEq, Eq)]
240#[repr(u16)]
241pub enum SimulatorCommandKind {
242 HapticActuatorCommandSchema207 = 207,
244 UltrasoundTransmitCommandSchema208 = 208,
246}
247
248impl SimulatorCommandKind {
249 pub const fn schema_id(self) -> u16 {
250 self as u16
251 }
252
253 pub const fn from_haptic_role(role: HapticSchema207Role) -> Result<Self, ActuationGateError> {
255 match role {
256 HapticSchema207Role::ActuatorCommand => Ok(Self::HapticActuatorCommandSchema207),
257 HapticSchema207Role::Measurement | HapticSchema207Role::ReceptorModel => {
258 Err(ActuationGateError::NonCommandDomainRoleRejected)
259 }
260 }
261 }
262
263 pub const fn from_ultrasound_role(
265 role: UltrasoundSchema208Role,
266 ) -> Result<Self, ActuationGateError> {
267 match role {
268 UltrasoundSchema208Role::TransmitCommand => {
269 Ok(Self::UltrasoundTransmitCommandSchema208)
270 }
271 UltrasoundSchema208Role::RawRf
272 | UltrasoundSchema208Role::BasebandIq
273 | UltrasoundSchema208Role::BeamSummary => {
274 Err(ActuationGateError::NonCommandDomainRoleRejected)
275 }
276 }
277 }
278}
279
280#[derive(Clone, Copy, Debug, PartialEq, Eq)]
282pub struct SimulatorCommandClaims {
283 pub command_id: [u8; 32],
284 pub command_nonce: u64,
285 pub command_kind: SimulatorCommandKind,
286 pub provenance_role: ProvenanceRole,
287 pub grant_id: [u8; 32],
288 pub grant_digest: [u8; 32],
289 pub actor_id: [u8; 32],
290 pub source_id: u64,
291 pub device_profile_digest: [u8; 32],
292 pub contact_or_array_frame_id: u32,
293 pub validity_window: CalibrationValidityWindow,
294}
295
296impl SimulatorCommandClaims {
297 pub fn validate(&self) -> Result<(), ActuationGateError> {
298 if self.provenance_role != ProvenanceRole::Command {
299 return Err(ActuationGateError::NonCommandProvenanceRoleRejected(
300 self.provenance_role,
301 ));
302 }
303 if self.command_id == [0u8; 32]
304 || self.command_nonce == 0
305 || self.grant_id == [0u8; 32]
306 || self.grant_digest == [0u8; 32]
307 || self.actor_id == [0u8; 32]
308 || self.source_id == 0
309 || self.device_profile_digest == [0u8; 32]
310 || self.contact_or_array_frame_id == 0
311 {
312 return Err(ActuationGateError::InvalidIdentifier);
313 }
314 Ok(())
315 }
316}
317
318#[derive(Clone, Copy, Debug, PartialEq, Eq)]
321pub struct SignedSimulatorCommandReceipt {
322 claims: SimulatorCommandClaims,
323 signer_public_key: [u8; 32],
324 signature: [u8; 64],
325}
326
327impl SignedSimulatorCommandReceipt {
328 pub fn sign(
329 claims: SimulatorCommandClaims,
330 signing_key: &SigningKey,
331 ) -> Result<Self, ActuationGateError> {
332 claims.validate()?;
333 let signer_public_key = signing_key.verifying_key().to_bytes();
334 let preimage = Self::signing_preimage(&claims, &signer_public_key);
335 let signature = signing_key.sign(&preimage).to_bytes();
336 Ok(Self {
337 claims,
338 signer_public_key,
339 signature,
340 })
341 }
342
343 pub const fn claims(&self) -> &SimulatorCommandClaims {
344 &self.claims
345 }
346
347 pub const fn signer_public_key(&self) -> &[u8; 32] {
348 &self.signer_public_key
349 }
350
351 pub const fn signature(&self) -> &[u8; 64] {
352 &self.signature
353 }
354
355 pub fn receipt_digest(&self) -> [u8; 32] {
358 let mut hasher = blake3::Hasher::new();
359 hasher.update(COMMAND_RECEIPT_DOMAIN);
360 Self::hash_claims(&mut hasher, &self.claims);
361 hasher.update(&self.signer_public_key);
362 hasher.update(&self.signature);
363 *hasher.finalize().as_bytes()
364 }
365
366 pub fn verify_signature(
367 &self,
368 trusted_command_authority_key: &[u8; 32],
369 ) -> Result<(), ActuationGateError> {
370 self.claims.validate()?;
371 if &self.signer_public_key != trusted_command_authority_key {
372 return Err(ActuationGateError::UntrustedCommandSigner);
373 }
374 let vk = VerifyingKey::from_bytes(&self.signer_public_key)
375 .map_err(|_| ActuationGateError::InvalidSignature)?;
376 let sig = Signature::from_bytes(&self.signature);
377 vk.verify_strict(
378 &Self::signing_preimage(&self.claims, &self.signer_public_key),
379 &sig,
380 )
381 .map_err(|_| ActuationGateError::InvalidSignature)
382 }
383
384 fn signing_preimage(
385 claims: &SimulatorCommandClaims,
386 signer_public_key: &[u8; 32],
387 ) -> [u8; 32] {
388 let mut hasher = blake3::Hasher::new();
389 hasher.update(COMMAND_SIG_DOMAIN);
390 Self::hash_claims(&mut hasher, claims);
391 hasher.update(signer_public_key);
392 *hasher.finalize().as_bytes()
393 }
394
395 fn hash_claims(hasher: &mut blake3::Hasher, claims: &SimulatorCommandClaims) {
396 hasher.update(&claims.command_id);
397 hasher.update(&claims.command_nonce.to_le_bytes());
398 hasher.update(&claims.command_kind.schema_id().to_le_bytes());
399 hasher.update(&(claims.provenance_role as u32).to_le_bytes());
400 hasher.update(&claims.grant_id);
401 hasher.update(&claims.grant_digest);
402 hasher.update(&claims.actor_id);
403 hasher.update(&claims.source_id.to_le_bytes());
404 hasher.update(&claims.device_profile_digest);
405 hasher.update(&claims.contact_or_array_frame_id.to_le_bytes());
406 hash_instant(hasher, claims.validity_window.valid_from());
407 hash_instant(hasher, claims.validity_window.valid_until());
408 }
409}
410
411#[derive(Clone, Copy, Debug, PartialEq, Eq)]
412struct ConsumedCommandEntry {
413 receipt_digest: [u8; 32],
414 command_id: [u8; 32],
415 command_nonce: u64,
416}
417
418#[derive(Clone, Debug)]
420pub struct CommandReplayLedger {
421 entries: [Option<ConsumedCommandEntry>; MAX_COMMAND_REPLAY_ENTRIES],
422 len: usize,
423}
424
425impl Default for CommandReplayLedger {
426 fn default() -> Self {
427 Self::new()
428 }
429}
430
431impl CommandReplayLedger {
432 pub const fn new() -> Self {
433 Self {
434 entries: [None; MAX_COMMAND_REPLAY_ENTRIES],
435 len: 0,
436 }
437 }
438
439 pub fn record_consumption(
440 &mut self,
441 receipt: &SignedSimulatorCommandReceipt,
442 ) -> Result<[u8; 32], ActuationGateError> {
443 let digest = receipt.receipt_digest();
444 let claims = receipt.claims();
445 for slot in self.entries.iter().take(self.len).flatten() {
446 if slot.receipt_digest == digest
447 || slot.command_id == claims.command_id
448 || slot.command_nonce == claims.command_nonce
449 {
450 return Err(ActuationGateError::CommandReplayDetected);
451 }
452 }
453 if self.len >= MAX_COMMAND_REPLAY_ENTRIES {
454 return Err(ActuationGateError::CommandReplayLedgerFull);
455 }
456 self.entries[self.len] = Some(ConsumedCommandEntry {
457 receipt_digest: digest,
458 command_id: claims.command_id,
459 command_nonce: claims.command_nonce,
460 });
461 self.len += 1;
462 Ok(digest)
463 }
464}
465
466#[derive(Clone, Copy, Debug, PartialEq, Eq)]
468pub struct SimulatorCommandRequest {
469 pub requested_kind: SimulatorCommandKind,
470 pub descriptor_provenance_role: ProvenanceRole,
471 pub stored_authority_receipt_digest: [u8; 32],
472 pub device_profile_digest: [u8; 32],
473 pub contact_or_array_frame_id: u32,
474 pub actor_id: [u8; 32],
475 pub source_id: u64,
476 pub execution_instant: RationalInstant,
477}
478
479#[derive(Debug, PartialEq, Eq)]
481pub struct AdmittedSimulatorCommand {
482 receipt_digest: [u8; 32],
483 command_kind: SimulatorCommandKind,
484 device_profile_digest: [u8; 32],
485 contact_or_array_frame_id: u32,
486 execution_instant: RationalInstant,
487}
488
489impl AdmittedSimulatorCommand {
490 pub const fn receipt_digest(&self) -> &[u8; 32] {
491 &self.receipt_digest
492 }
493 pub const fn command_kind(&self) -> SimulatorCommandKind {
494 self.command_kind
495 }
496 pub const fn device_profile_digest(&self) -> &[u8; 32] {
497 &self.device_profile_digest
498 }
499 pub const fn contact_or_array_frame_id(&self) -> u32 {
500 self.contact_or_array_frame_id
501 }
502 pub const fn execution_instant(&self) -> RationalInstant {
503 self.execution_instant
504 }
505}
506
507pub fn admit_simulator_command(
518 request: &SimulatorCommandRequest,
519 receipt: &SignedSimulatorCommandReceipt,
520 trusted_command_authority_key: &[u8; 32],
521 grant: &ConsentGrant,
522 revocations: &impl RevocationAuthority,
523 trusted_clock: &mut impl TrustedUnixClock,
524 replay_ledger: &mut CommandReplayLedger,
525) -> Result<AdmittedSimulatorCommand, ActuationGateError> {
526 if request.descriptor_provenance_role != ProvenanceRole::Command {
527 return Err(ActuationGateError::NonCommandProvenanceRoleRejected(
528 request.descriptor_provenance_role,
529 ));
530 }
531 receipt.verify_signature(trusted_command_authority_key)?;
532 let computed_digest = receipt.receipt_digest();
533 if computed_digest != request.stored_authority_receipt_digest {
534 return Err(ActuationGateError::CommandReceiptDigestMismatch);
535 }
536
537 let claims = receipt.claims();
538 if claims.command_kind != request.requested_kind {
539 return Err(ActuationGateError::CommandKindMismatch);
540 }
541 if claims.device_profile_digest != request.device_profile_digest {
542 return Err(ActuationGateError::DeviceProfileDigestMismatch);
543 }
544 if claims.contact_or_array_frame_id != request.contact_or_array_frame_id
545 || request.contact_or_array_frame_id == 0
546 {
547 return Err(ActuationGateError::ContactOrArrayFrameMismatch);
548 }
549 if claims.actor_id != request.actor_id || claims.actor_id != grant.recipient_did {
550 return Err(ActuationGateError::ActorMismatch);
551 }
552 if claims.source_id != request.source_id {
553 return Err(ActuationGateError::SourceIdMismatch);
554 }
555 if claims.grant_id != grant.grant_id || claims.grant_digest != grant.compute_digest() {
556 return Err(ActuationGateError::GrantBindingMismatch);
557 }
558
559 claims
561 .validity_window
562 .verify_contains(request.execution_instant)
563 .map_err(ActuationGateError::CommandWindow)?;
564
565 let now_unix = trusted_clock
566 .now_unix()
567 .map_err(|_| ActuationGateError::ClockUnavailable)?;
568 if now_unix < grant.created_at {
569 return Err(ActuationGateError::GrantNotYetValid);
570 }
571 grant
572 .verify(now_unix)
573 .map_err(|_| ActuationGateError::GrantExpiredOrInvalid)?;
574 let is_revoked = revocations
575 .is_revoked(&grant.grant_id, &claims.grant_digest, now_unix)
576 .map_err(|_| ActuationGateError::RevocationCheckFailed)?;
577 if is_revoked {
578 return Err(ActuationGateError::GrantRevoked);
579 }
580
581 let recorded_digest = replay_ledger.record_consumption(receipt)?;
582 Ok(AdmittedSimulatorCommand {
583 receipt_digest: recorded_digest,
584 command_kind: claims.command_kind,
585 device_profile_digest: claims.device_profile_digest,
586 contact_or_array_frame_id: claims.contact_or_array_frame_id,
587 execution_instant: request.execution_instant,
588 })
589}
590
591fn hash_instant(hasher: &mut blake3::Hasher, instant: RationalInstant) {
592 hasher.update(&instant.clock_origin().value().unwrap_or(0).to_le_bytes());
593 hasher.update(&instant.restart_epoch().to_le_bytes());
594 hasher.update(&instant.scale().to_le_bytes());
595 hasher.update(&instant.numerator().to_le_bytes());
596 hasher.update(&instant.denominator().to_le_bytes());
597}
598
599#[derive(Clone, Copy, Debug, PartialEq, Eq)]
600pub enum ActuationGateError {
601 InvalidIdentifier,
602 InvalidProvenanceRoleCode(u32),
603 UnknownEpistemicClass,
604 UnknownDomainRole,
605 MissingInstrumentForMeasuredRole,
606 MissingAlgorithmOrSourceForModelDerivedRole,
607 MissingSourceDigestForOpaqueRole,
608 MissingCommandReceiptForCommandRole,
609 RoleForbiddenInEmpiricalJoin(ProvenanceRole),
610 NonEmpiricalClassRejected(EpistemicClass),
611 PassiveObservationCannotAuthorizeActuation(PassiveArtifactKind),
612 NonCommandDomainRoleRejected,
613 NonCommandProvenanceRoleRejected(ProvenanceRole),
614 UntrustedCommandSigner,
615 InvalidSignature,
616 CommandReceiptDigestMismatch,
617 CommandKindMismatch,
618 DeviceProfileDigestMismatch,
619 ContactOrArrayFrameMismatch,
620 ActorMismatch,
621 SourceIdMismatch,
622 GrantBindingMismatch,
623 CommandWindow(CalibrationError),
624 ClockUnavailable,
625 GrantNotYetValid,
626 GrantExpiredOrInvalid,
627 RevocationCheckFailed,
628 GrantRevoked,
629 CommandReplayDetected,
630 CommandReplayLedgerFull,
631 Authorization(AuthorizationError),
632}