1use std::fmt;
10
11#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct AssetIdentity {
14 pub asset_id: String,
15 pub content_digest: u64,
16 pub semantic_tag: u32,
17 pub byte_size: usize,
18}
19
20impl AssetIdentity {
21 pub fn new(
23 asset_id: impl Into<String>,
24 content_digest: u64,
25 semantic_tag: u32,
26 byte_size: usize,
27 ) -> Self {
28 Self {
29 asset_id: asset_id.into(),
30 content_digest,
31 semantic_tag,
32 byte_size,
33 }
34 }
35}
36
37#[derive(Debug, Clone, PartialEq)]
39pub struct SceneState {
40 pub state_id: String,
41 pub epoch: u64,
42 pub transform: [f32; 16],
43 pub feature_vector: [f32; 8],
44 pub bounding_box_min: [f32; 3],
45 pub bounding_box_max: [f32; 3],
46 pub flags: u32,
47}
48
49pub const FLAG_ACTIVE: u32 = 1 << 0;
50pub const FLAG_CONDITIONED: u32 = 1 << 1;
51pub const FLAG_SPECIALIST_BOUND: u32 = 1 << 2;
52pub const FLAG_DEGRADED: u32 = 1 << 3;
53
54impl SceneState {
55 pub fn volume(&self) -> f32 {
57 let dx = (self.bounding_box_max[0] - self.bounding_box_min[0]).max(0.0);
58 let dy = (self.bounding_box_max[1] - self.bounding_box_min[1]).max(0.0);
59 let dz = (self.bounding_box_max[2] - self.bounding_box_min[2]).max(0.0);
60 dx * dy * dz
61 }
62
63 pub fn feature_distance(&self, other: &SceneState) -> f32 {
65 let mut sum_sq = 0.0f32;
66 for i in 0..8 {
67 let diff = self.feature_vector[i] - other.feature_vector[i];
68 sum_sq += diff * diff;
69 }
70 sum_sq.sqrt()
71 }
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
76pub enum ContractDisposition {
77 Satisfied,
78 DivergenceExceeded { found: u32, max: u32 },
79 VolumeExpansionExceeded { found: u32, max: u32 },
80 RequiredFlagMissing { expected: u32, found: u32 },
81 ForbiddenFlagPresent { forbidden: u32, found: u32 },
82 AssetMismatch { expected: u64, found: u64 },
83}
84
85impl fmt::Display for ContractDisposition {
86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 match self {
88 Self::Satisfied => write!(f, "contract satisfied"),
89 Self::DivergenceExceeded { found, max } => {
90 write!(
91 f,
92 "feature divergence {}e-4 exceeded limit {}e-4",
93 found, max
94 )
95 }
96 Self::VolumeExpansionExceeded { found, max } => {
97 write!(
98 f,
99 "volume expansion ratio {}e-4 exceeded limit {}e-4",
100 found, max
101 )
102 }
103 Self::RequiredFlagMissing { expected, found } => {
104 write!(
105 f,
106 "required flags {:#x} missing from state flags {:#x}",
107 expected, found
108 )
109 }
110 Self::ForbiddenFlagPresent { forbidden, found } => {
111 write!(
112 f,
113 "forbidden flags {:#x} found in state flags {:#x}",
114 forbidden, found
115 )
116 }
117 Self::AssetMismatch { expected, found } => {
118 write!(
119 f,
120 "asset digest mismatch: expected {:#x}, found {:#x}",
121 expected, found
122 )
123 }
124 }
125 }
126}
127
128#[derive(Debug, Clone, PartialEq)]
130pub struct FunctionalContract {
131 pub contract_id: String,
132 pub target_asset_digest: u64,
133 pub max_divergence_epsilon: f32,
134 pub max_volume_expansion_ratio: f32,
135 pub required_flags: u32,
136 pub forbidden_flags: u32,
137}
138
139#[derive(Debug, Clone, PartialEq)]
141pub struct ContractVerificationReceipt {
142 pub contract_id: String,
143 pub asset_digest: u64,
144 pub state_a_epoch: u64,
145 pub state_b_epoch: u64,
146 pub measured_divergence: f32,
147 pub measured_volume_ratio: f32,
148 pub disposition: ContractDisposition,
149 pub receipt_digest: u64,
150}
151
152impl FunctionalContract {
153 pub fn new(
155 contract_id: impl Into<String>,
156 target_asset_digest: u64,
157 max_divergence_epsilon: f32,
158 max_volume_expansion_ratio: f32,
159 required_flags: u32,
160 forbidden_flags: u32,
161 ) -> Self {
162 Self {
163 contract_id: contract_id.into(),
164 target_asset_digest,
165 max_divergence_epsilon,
166 max_volume_expansion_ratio,
167 required_flags,
168 forbidden_flags,
169 }
170 }
171
172 pub fn verify(
174 &self,
175 asset: &AssetIdentity,
176 state_a: &SceneState,
177 state_b: &SceneState,
178 ) -> ContractVerificationReceipt {
179 if asset.content_digest != self.target_asset_digest {
180 return self.build_receipt(
181 asset.content_digest,
182 state_a.epoch,
183 state_b.epoch,
184 0.0,
185 0.0,
186 ContractDisposition::AssetMismatch {
187 expected: self.target_asset_digest,
188 found: asset.content_digest,
189 },
190 );
191 }
192
193 if (state_b.flags & self.required_flags) != self.required_flags {
195 return self.build_receipt(
196 asset.content_digest,
197 state_a.epoch,
198 state_b.epoch,
199 0.0,
200 0.0,
201 ContractDisposition::RequiredFlagMissing {
202 expected: self.required_flags,
203 found: state_b.flags,
204 },
205 );
206 }
207
208 if (state_b.flags & self.forbidden_flags) != 0 {
209 return self.build_receipt(
210 asset.content_digest,
211 state_a.epoch,
212 state_b.epoch,
213 0.0,
214 0.0,
215 ContractDisposition::ForbiddenFlagPresent {
216 forbidden: self.forbidden_flags,
217 found: state_b.flags,
218 },
219 );
220 }
221
222 let vol_a = state_a.volume();
224 let vol_b = state_b.volume();
225 let volume_ratio = if vol_a > 1e-6 { vol_b / vol_a } else { 1.0 };
226 if volume_ratio > self.max_volume_expansion_ratio {
227 let found_u32 = (volume_ratio * 10000.0) as u32;
228 let max_u32 = (self.max_volume_expansion_ratio * 10000.0) as u32;
229 return self.build_receipt(
230 asset.content_digest,
231 state_a.epoch,
232 state_b.epoch,
233 0.0,
234 volume_ratio,
235 ContractDisposition::VolumeExpansionExceeded {
236 found: found_u32,
237 max: max_u32,
238 },
239 );
240 }
241
242 let divergence = state_a.feature_distance(state_b);
244 if divergence > self.max_divergence_epsilon {
245 let found_u32 = (divergence * 10000.0) as u32;
246 let max_u32 = (self.max_divergence_epsilon * 10000.0) as u32;
247 return self.build_receipt(
248 asset.content_digest,
249 state_a.epoch,
250 state_b.epoch,
251 divergence,
252 volume_ratio,
253 ContractDisposition::DivergenceExceeded {
254 found: found_u32,
255 max: max_u32,
256 },
257 );
258 }
259
260 self.build_receipt(
262 asset.content_digest,
263 state_a.epoch,
264 state_b.epoch,
265 divergence,
266 volume_ratio,
267 ContractDisposition::Satisfied,
268 )
269 }
270
271 fn build_receipt(
272 &self,
273 asset_digest: u64,
274 epoch_a: u64,
275 epoch_b: u64,
276 divergence: f32,
277 volume_ratio: f32,
278 disposition: ContractDisposition,
279 ) -> ContractVerificationReceipt {
280 let mut hasher = 0xcbf29ce484222325u64;
282 for b in self.contract_id.as_bytes() {
283 hasher ^= *b as u64;
284 hasher = hasher.wrapping_mul(0x100000001b3);
285 }
286 hasher ^= asset_digest;
287 hasher = hasher.wrapping_mul(0x100000001b3);
288 hasher ^= epoch_a;
289 hasher = hasher.wrapping_mul(0x100000001b3);
290 hasher ^= epoch_b;
291 hasher = hasher.wrapping_mul(0x100000001b3);
292 hasher ^= (divergence.to_bits() as u64) | ((volume_ratio.to_bits() as u64) << 32);
293 hasher = hasher.wrapping_mul(0x100000001b3);
294
295 ContractVerificationReceipt {
296 contract_id: self.contract_id.clone(),
297 asset_digest,
298 state_a_epoch: epoch_a,
299 state_b_epoch: epoch_b,
300 measured_divergence: divergence,
301 measured_volume_ratio: volume_ratio,
302 disposition,
303 receipt_digest: hasher,
304 }
305 }
306}
307
308#[cfg(test)]
309mod tests {
310 use super::*;
311
312 fn test_asset() -> AssetIdentity {
313 AssetIdentity::new(
314 "did:q42:asset:geometry:terrain_quad_042",
315 0x4242_CAFE_BEEF,
316 1,
317 4096,
318 )
319 }
320
321 fn test_scene_state_a() -> SceneState {
322 SceneState {
323 state_id: "state_a_rest".to_string(),
324 epoch: 100,
325 transform: [
326 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
327 ],
328 feature_vector: [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8],
329 bounding_box_min: [-10.0, -10.0, 0.0],
330 bounding_box_max: [10.0, 10.0, 5.0],
331 flags: FLAG_ACTIVE,
332 }
333 }
334
335 fn test_scene_state_b() -> SceneState {
336 SceneState {
337 state_id: "state_b_active".to_string(),
338 epoch: 101,
339 transform: [
340 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
341 ],
342 feature_vector: [0.11, 0.21, 0.30, 0.42, 0.50, 0.59, 0.71, 0.80],
344 bounding_box_min: [-10.0, -10.0, 0.0],
345 bounding_box_max: [10.0, 10.0, 5.2],
346 flags: FLAG_ACTIVE | FLAG_CONDITIONED,
347 }
348 }
349
350 #[test]
351 fn test_asset_contract_satisfied() {
352 let asset = test_asset();
353 let state_a = test_scene_state_a();
354 let state_b = test_scene_state_b();
355
356 let contract = FunctionalContract::new(
357 "contract_spatial_continuity_v1",
358 asset.content_digest,
359 0.15, 1.20, FLAG_ACTIVE | FLAG_CONDITIONED,
362 FLAG_DEGRADED,
363 );
364
365 let receipt = contract.verify(&asset, &state_a, &state_b);
366 assert_eq!(receipt.disposition, ContractDisposition::Satisfied);
367 assert!(receipt.receipt_digest != 0);
368 assert_eq!(receipt.state_a_epoch, 100);
369 assert_eq!(receipt.state_b_epoch, 101);
370 assert!(receipt.measured_divergence < 0.15);
371 }
372
373 #[test]
374 fn test_divergence_exceeded_fails_closed() {
375 let asset = test_asset();
376 let state_a = test_scene_state_a();
377 let mut state_b = test_scene_state_b();
378 state_b.feature_vector[0] = 5.0;
380
381 let contract = FunctionalContract::new(
382 "contract_spatial_continuity_v1",
383 asset.content_digest,
384 0.05, 1.50,
386 FLAG_ACTIVE,
387 FLAG_DEGRADED,
388 );
389
390 let receipt = contract.verify(&asset, &state_a, &state_b);
391 match receipt.disposition {
392 ContractDisposition::DivergenceExceeded { found, max } => {
393 assert!(found > max);
394 }
395 other => panic!("expected DivergenceExceeded, got {:?}", other),
396 }
397 }
398
399 #[test]
400 fn test_volume_expansion_exceeded_fails_closed() {
401 let asset = test_asset();
402 let state_a = test_scene_state_a();
403 let mut state_b = test_scene_state_b();
404 state_b.bounding_box_max[2] = 20.0;
406
407 let contract = FunctionalContract::new(
408 "contract_spatial_continuity_v1",
409 asset.content_digest,
410 1.0,
411 1.10, FLAG_ACTIVE,
413 FLAG_DEGRADED,
414 );
415
416 let receipt = contract.verify(&asset, &state_a, &state_b);
417 match receipt.disposition {
418 ContractDisposition::VolumeExpansionExceeded { found, max } => {
419 assert!(found > max);
420 }
421 other => panic!("expected VolumeExpansionExceeded, got {:?}", other),
422 }
423 }
424
425 #[test]
426 fn test_forbidden_flag_fails_closed() {
427 let asset = test_asset();
428 let state_a = test_scene_state_a();
429 let mut state_b = test_scene_state_b();
430 state_b.flags |= FLAG_DEGRADED;
431
432 let contract = FunctionalContract::new(
433 "contract_spatial_continuity_v1",
434 asset.content_digest,
435 1.0,
436 2.0,
437 FLAG_ACTIVE,
438 FLAG_DEGRADED, );
440
441 let receipt = contract.verify(&asset, &state_a, &state_b);
442 match receipt.disposition {
443 ContractDisposition::ForbiddenFlagPresent { forbidden, found } => {
444 assert_eq!(forbidden, FLAG_DEGRADED);
445 assert_eq!(found & FLAG_DEGRADED, FLAG_DEGRADED);
446 }
447 other => panic!("expected ForbiddenFlagPresent, got {:?}", other),
448 }
449 }
450
451 #[test]
452 fn test_asset_digest_mismatch_fails_closed() {
453 let mut asset = test_asset();
454 asset.content_digest = 0x9999_9999;
455 let state_a = test_scene_state_a();
456 let state_b = test_scene_state_b();
457
458 let contract = FunctionalContract::new(
459 "contract_spatial_continuity_v1",
460 0x4242_CAFE_BEEF, 1.0,
462 2.0,
463 FLAG_ACTIVE,
464 0,
465 );
466
467 let receipt = contract.verify(&asset, &state_a, &state_b);
468 assert_eq!(
469 receipt.disposition,
470 ContractDisposition::AssetMismatch {
471 expected: 0x4242_CAFE_BEEF,
472 found: 0x9999_9999,
473 }
474 );
475 }
476}