1use std::fmt;
18use std::panic::{catch_unwind, AssertUnwindSafe};
19
20use super::checkpoint_ack::V2CheckpointAcknowledgement;
21use super::claim_store::{V2AuthoritativeClock, V2ChallengeClaim, V2StoreError};
22use super::context::V2Context;
23use super::crypto::{key_id_v2, lower_hex, sha384, verify_v2_statement, V2ObjectType};
24use super::errors::{err, V2Error, V2ErrorClass, V2Result};
25use super::limits::{valid_v2_timestamp, V2_MAX_TIMESTAMP_SECONDS};
26use super::receipt::{
27 decode_verification_receipt_v2, verification_receipt_v2_body, verification_receipt_v2_digest,
28 verification_receipt_v2_signable_bytes, VerificationReceiptV2,
29};
30use crate::types::HybridPublicKey;
31
32pub struct CommittedV2Outcome {
35 claim_id: String,
36 verifier_id: String,
37 receipt_body: Vec<u8>,
38 challenge_expires_at: i64,
39 allow_horizon: i64,
40}
41
42impl fmt::Debug for CommittedV2Outcome {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 f.debug_struct("CommittedV2Outcome")
45 .field("claim_id", &self.claim_id)
46 .field("receipt_body_digest", &self.receipt_body_digest())
47 .finish_non_exhaustive()
48 }
49}
50
51impl CommittedV2Outcome {
52 pub(crate) fn new(claim: &V2ChallengeClaim, body: &[u8], allow_horizon: i64) -> Self {
53 CommittedV2Outcome {
54 claim_id: claim.claim_id.clone(),
55 verifier_id: claim.verifier_id.clone(),
56 receipt_body: body.to_vec(),
57 challenge_expires_at: claim.expires_at,
58 allow_horizon,
59 }
60 }
61
62 pub fn claim_id(&self) -> String {
64 self.claim_id.clone()
65 }
66
67 pub fn receipt_body(&self) -> Vec<u8> {
70 self.receipt_body.clone()
71 }
72
73 pub fn receipt_body_digest(&self) -> String {
75 receipt_outbox_digest_v2(&self.receipt_body)
76 }
77
78 pub fn challenge_expires_at(&self) -> i64 {
80 self.challenge_expires_at
81 }
82
83 pub fn allow_horizon(&self) -> Option<i64> {
86 (self.allow_horizon > 0).then_some(self.allow_horizon)
87 }
88}
89
90#[doc(hidden)]
93#[cfg(feature = "test-hooks")]
94pub fn forged_committed_outcome_test_only() -> CommittedV2Outcome {
95 CommittedV2Outcome {
96 claim_id: String::new(),
97 verifier_id: String::new(),
98 receipt_body: Vec::new(),
99 challenge_expires_at: 0,
100 allow_horizon: 0,
101 }
102}
103
104pub fn receipt_outbox_digest_v2(body: &[u8]) -> String {
106 format!(
107 "sha384:{}",
108 hex::encode(sha384(&[b"ratify-protocol-receipt-outbox-v2", &[0], body]))
109 )
110}
111
112pub trait V2ReceiptPublisher: Send + Sync {
118 fn publish_v2_receipt(&self, ctx: &V2Context, claim_id: &str, receipt_body: &[u8]) -> Result<Vec<u8>, V2StoreError>;
119}
120
121pub trait V2ReceiptCheckpoint: Send + Sync {
128 fn acknowledge_v2_receipt(
129 &self,
130 ctx: &V2Context,
131 log_id: &str,
132 sequence: i64,
133 previous_entry_hash: &[u8],
134 entry_hash: &[u8],
135 ) -> Result<V2CheckpointAcknowledgement, V2StoreError>;
136 fn get_v2_acknowledgement(
137 &self,
138 ctx: &V2Context,
139 log_id: &str,
140 sequence: i64,
141 ) -> Result<V2CheckpointAcknowledgement, V2StoreError>;
142}
143
144#[derive(Debug, Clone, PartialEq, Eq)]
153pub struct V2ReleaseRecord {
154 pub claim_id: String,
155 pub entry_hash: Vec<u8>,
156 pub ack_timestamp: i64,
157 pub outcome: V2ReleaseStatus,
158 pub reason: String,
159}
160
161pub fn valid_v2_release_record_outcome(outcome: V2ReleaseStatus, reason: &str) -> bool {
165 match outcome {
166 V2ReleaseStatus::Released => reason.is_empty(),
167 V2ReleaseStatus::Withheld => {
168 matches!(reason, "clock_regressed" | "challenge_expired" | "allow_horizon_passed")
169 }
170 _ => false,
171 }
172}
173
174#[derive(Debug, Clone, PartialEq, Eq, Default)]
178pub struct V2TerminalClaimRecord {
179 pub terminal: bool,
180 pub receipt_outbox_digest: String,
181 pub challenge_expires_at: i64,
182 pub allow_horizon: i64,
183 pub finalized_at: i64,
184 pub receipt_abandoned: bool,
185 pub release: Option<V2ReleaseRecord>,
186}
187
188pub trait V2ReleaseClaimStore: V2AuthoritativeClock {
195 fn load_v2_terminal_claim(&self, ctx: &V2Context, claim_id: &str) -> Result<V2TerminalClaimRecord, V2StoreError>;
196 fn record_v2_release(&self, ctx: &V2Context, record: V2ReleaseRecord) -> Result<(), V2StoreError>;
197}
198
199#[derive(Clone, Copy)]
201pub struct V2ReleaseConfig<'a> {
202 pub verifier_public_key: &'a HybridPublicKey,
203 pub log_id: &'a str,
204 pub claim_store: &'a dyn V2ReleaseClaimStore,
205 pub checkpoint: &'a dyn V2ReceiptCheckpoint,
206}
207
208#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
210pub enum V2ReleaseStatus {
211 Released,
212 Pending,
213 Withheld,
214 Rejected,
215}
216
217impl V2ReleaseStatus {
218 pub fn as_str(self) -> &'static str {
220 match self {
221 V2ReleaseStatus::Released => "released",
222 V2ReleaseStatus::Pending => "pending",
223 V2ReleaseStatus::Withheld => "withheld",
224 V2ReleaseStatus::Rejected => "rejected",
225 }
226 }
227}
228
229pub struct V2ReleasedDecision {
235 claim_id: String,
236 decision: String,
237 reason: String,
238 identity_status: String,
239 granted_scope: Vec<String>,
240 receipt_wire: Vec<u8>,
241 release_time: i64,
242 challenge_expires_at: i64,
243 allow_horizon: i64,
244}
245
246impl fmt::Debug for V2ReleasedDecision {
247 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248 f.debug_struct("V2ReleasedDecision")
249 .field("claim_id", &self.claim_id)
250 .field("decision", &self.decision)
251 .field("reason", &self.reason)
252 .finish_non_exhaustive()
253 }
254}
255
256impl V2ReleasedDecision {
257 pub fn claim_id(&self) -> String {
259 self.claim_id.clone()
260 }
261
262 pub fn decision(&self) -> String {
265 self.decision.clone()
266 }
267
268 pub fn reason(&self) -> String {
270 self.reason.clone()
271 }
272
273 pub fn identity_status(&self) -> String {
275 self.identity_status.clone()
276 }
277
278 pub fn granted_scope(&self) -> Vec<String> {
280 self.granted_scope.clone()
281 }
282
283 pub fn receipt_wire(&self) -> Vec<u8> {
285 self.receipt_wire.clone()
286 }
287
288 pub fn receipt(&self) -> V2Result<VerificationReceiptV2> {
290 if self.receipt_wire.is_empty() {
291 return err(V2ErrorClass::Malformed, "v2 released decision carries no receipt");
292 }
293 decode_verification_receipt_v2(&self.receipt_wire)
294 }
295
296 pub fn release_time(&self) -> i64 {
298 self.release_time
299 }
300
301 pub fn challenge_expires_at(&self) -> i64 {
303 self.challenge_expires_at
304 }
305
306 pub fn allow_horizon(&self) -> Option<i64> {
309 (self.allow_horizon > 0).then_some(self.allow_horizon)
310 }
311
312 pub fn allowed(&self, ctx: &V2Context, clock: &dyn V2AuthoritativeClock) -> bool {
319 if self.decision != "allow" || self.receipt_wire.is_empty() || self.allow_horizon <= 0 {
320 return false;
321 }
322 match read_v2_authoritative_time(ctx, clock) {
323 Ok(now) => now < self.challenge_expires_at && now < self.allow_horizon,
324 Err(_) => false,
325 }
326 }
327}
328
329#[derive(Debug)]
333pub struct V2ReleaseResult {
334 pub status: V2ReleaseStatus,
335 pub reason: String,
336 decision: Option<V2ReleasedDecision>,
337}
338
339impl V2ReleaseResult {
340 pub fn decision(&self) -> Option<&V2ReleasedDecision> {
342 self.decision.as_ref()
343 }
344
345 pub fn into_decision(self) -> Option<V2ReleasedDecision> {
347 self.decision
348 }
349}
350
351fn release_result_v2(status: V2ReleaseStatus, reason: &str) -> V2ReleaseResult {
352 V2ReleaseResult {
353 status,
354 reason: reason.into(),
355 decision: None,
356 }
357}
358
359pub fn release_v2_decision(
364 ctx: &V2Context,
365 committed: &CommittedV2Outcome,
366 signed_receipt: Option<&[u8]>,
367 config: V2ReleaseConfig<'_>,
368) -> V2ReleaseResult {
369 use V2ReleaseStatus::*;
370 if committed.claim_id.is_empty() || committed.receipt_body.is_empty() {
371 return release_result_v2(Rejected, "release_state_mismatch");
372 }
373 if config.log_id.len() != 32 || !lower_hex(config.log_id) {
374 return release_result_v2(Rejected, "release_state_mismatch");
375 }
376 let record = match catch_unwind(AssertUnwindSafe(|| {
378 config.claim_store.load_v2_terminal_claim(ctx, &committed.claim_id)
379 })) {
380 Ok(Ok(r)) => r,
381 Ok(Err(e)) if e.class() == Some(V2ErrorClass::ClaimNotFound) => {
385 return release_result_v2(Rejected, "release_state_mismatch")
386 }
387 _ => return release_result_v2(Pending, "claim_store_unavailable"),
388 };
389 if record.receipt_abandoned {
390 return release_result_v2(Withheld, "receipt_abandoned");
391 }
392 let verifier_id = key_id_v2(config.verifier_public_key);
393 if !record.terminal
394 || record.receipt_outbox_digest != committed.receipt_body_digest()
395 || record.challenge_expires_at != committed.challenge_expires_at
396 || record.allow_horizon != committed.allow_horizon
397 || verifier_id.as_deref().ok() != Some(committed.verifier_id.as_str())
398 {
399 return release_result_v2(Rejected, "release_state_mismatch");
400 }
401 if let Some(release) = &record.release {
405 if release.claim_id != committed.claim_id || !valid_v2_release_record_outcome(release.outcome, &release.reason) {
406 return release_result_v2(Rejected, "release_state_mismatch");
407 }
408 if release.outcome == Withheld {
409 return release_result_v2(Withheld, &release.reason);
410 }
411 }
412 let Some(signed_receipt) = signed_receipt.filter(|r| !r.is_empty()) else {
414 return release_result_v2(Pending, "receipt_not_appended");
415 };
416 let receipt = match verify_published_v2_receipt(signed_receipt, config) {
417 Ok(r) if r.verifier_id == committed.verifier_id => r,
418 _ => return release_result_v2(Rejected, "receipt_invalid"),
419 };
420 match verification_receipt_v2_body(&receipt) {
422 Ok(body) if body == committed.receipt_body => {}
423 _ => return release_result_v2(Rejected, "receipt_body_mismatch"),
424 }
425 let Ok(entry_hash) = verification_receipt_v2_digest(&receipt) else {
426 return release_result_v2(Rejected, "receipt_invalid");
427 };
428 if record.release.as_ref().is_some_and(|r| r.entry_hash != entry_hash) {
431 return release_result_v2(Rejected, "release_state_mismatch");
432 }
433 if receipt.sequence > 1 {
435 let previous = match get_v2_acknowledgement_safely(ctx, config.checkpoint, &receipt.log_id, receipt.sequence - 1) {
436 Ok(a) => a,
437 Err(_) => return release_result_v2(Pending, "acknowledgement_unavailable"),
438 };
439 if previous.log_id != receipt.log_id
440 || previous.sequence != receipt.sequence - 1
441 || previous.entry_hash != receipt.previous_receipt_hash
442 {
443 return release_result_v2(Rejected, "log_predecessor_mismatch");
444 }
445 }
446 let ack = match get_v2_acknowledgement_safely(ctx, config.checkpoint, &receipt.log_id, receipt.sequence) {
448 Ok(a) => a,
449 Err(_) => return release_result_v2(Pending, "acknowledgement_unavailable"),
450 };
451 if ack.log_id != receipt.log_id || ack.sequence != receipt.sequence || ack.entry_hash != entry_hash {
452 return release_result_v2(Rejected, "acknowledgement_mismatch");
453 }
454 if record.release.as_ref().is_some_and(|r| r.ack_timestamp != ack.timestamp) {
455 return release_result_v2(Rejected, "release_state_mismatch");
456 }
457 let withhold = |reason: &str| -> V2ReleaseResult {
463 if record.release.is_none() {
464 let withheld = V2ReleaseRecord {
465 claim_id: committed.claim_id.clone(),
466 entry_hash: entry_hash.clone(),
467 ack_timestamp: ack.timestamp,
468 outcome: Withheld,
469 reason: reason.into(),
470 };
471 if let Err(V2StoreError::ReleaseStateMismatch) = record_v2_release_safely(ctx, config.claim_store, withheld) {
472 return release_result_v2(Rejected, "release_state_mismatch");
473 }
474 }
475 release_result_v2(Withheld, reason)
476 };
477 let now = match read_v2_authoritative_time(ctx, config.claim_store) {
479 Ok(now) => now,
480 Err(e) if e.class == V2ErrorClass::ClockRegressed && e.is_classified() => return withhold("clock_regressed"),
481 Err(_) => return release_result_v2(Pending, "clock_unavailable"),
482 };
483 if !valid_v2_timestamp(record.finalized_at)
484 || !valid_v2_timestamp(ack.timestamp)
485 || record.finalized_at > ack.timestamp
486 || ack.timestamp > now
487 {
488 return withhold("clock_regressed");
489 }
490 if ack.timestamp >= committed.challenge_expires_at || now >= committed.challenge_expires_at {
492 return withhold("challenge_expired");
493 }
494 if receipt.decision == "allow"
495 && (committed.allow_horizon <= 0 || ack.timestamp >= committed.allow_horizon || now >= committed.allow_horizon)
496 {
497 return withhold("allow_horizon_passed");
498 }
499 if record.release.is_none() {
501 let new_record = V2ReleaseRecord {
502 claim_id: committed.claim_id.clone(),
503 entry_hash: entry_hash.clone(),
504 ack_timestamp: ack.timestamp,
505 outcome: Released,
506 reason: String::new(),
507 };
508 match record_v2_release_safely(ctx, config.claim_store, new_record) {
509 Ok(()) => {}
510 Err(V2StoreError::ReleaseStateMismatch) => return release_result_v2(Rejected, "release_state_mismatch"),
511 Err(_) => return release_result_v2(Pending, "claim_store_unavailable"),
512 }
513 }
514 let allow = receipt.decision == "allow";
516 V2ReleaseResult {
517 status: Released,
518 reason: String::new(),
519 decision: Some(V2ReleasedDecision {
520 claim_id: committed.claim_id.clone(),
521 decision: receipt.decision.clone(),
522 reason: receipt.decision_reason.clone(),
523 identity_status: receipt.identity_status.clone(),
524 granted_scope: receipt.granted_scope.clone(),
525 receipt_wire: signed_receipt.to_vec(),
526 release_time: ack.timestamp,
527 challenge_expires_at: committed.challenge_expires_at,
528 allow_horizon: if allow { committed.allow_horizon } else { 0 },
529 }),
530 }
531}
532
533fn verify_published_v2_receipt(wire: &[u8], config: V2ReleaseConfig<'_>) -> V2Result<VerificationReceiptV2> {
534 let receipt = decode_verification_receipt_v2(wire)?;
535 if receipt.log_id != config.log_id {
536 return err(V2ErrorClass::LogStateMismatch, "v2 published receipt belongs to an unconfigured log");
537 }
538 let body = verification_receipt_v2_signable_bytes(&receipt)?;
539 verify_v2_statement(
540 V2ObjectType::VerificationReceipt,
541 &body,
542 &receipt.signature,
543 config.verifier_public_key,
544 )?;
545 Ok(receipt)
546}
547
548fn record_v2_release_safely(
549 ctx: &V2Context,
550 store: &dyn V2ReleaseClaimStore,
551 record: V2ReleaseRecord,
552) -> Result<(), V2StoreError> {
553 catch_unwind(AssertUnwindSafe(|| store.record_v2_release(ctx, record)))
554 .unwrap_or_else(|_| Err(V2StoreError::Unavailable("claim store panicked".into())))
555}
556
557fn get_v2_acknowledgement_safely(
558 ctx: &V2Context,
559 checkpoint: &dyn V2ReceiptCheckpoint,
560 log_id: &str,
561 sequence: i64,
562) -> Result<V2CheckpointAcknowledgement, V2StoreError> {
563 catch_unwind(AssertUnwindSafe(|| checkpoint.get_v2_acknowledgement(ctx, log_id, sequence)))
564 .unwrap_or_else(|_| Err(V2StoreError::Unavailable("checkpoint panicked".into())))
565}
566
567pub(crate) fn read_v2_authoritative_time(ctx: &V2Context, clock: &dyn V2AuthoritativeClock) -> V2Result<i64> {
571 let now = match catch_unwind(AssertUnwindSafe(|| clock.authoritative_time_v2(ctx))) {
572 Ok(Ok(now)) => now,
573 Ok(Err(e)) => return Err(e.into_v2()),
574 Err(_) => return Err(V2Error::plain("v2 authoritative clock panicked")),
575 };
576 if !valid_v2_timestamp(now) {
577 return Err(V2Error::plain(format!(
578 "v2 authoritative clock returned {now} outside 0..{V2_MAX_TIMESTAMP_SECONDS}"
579 )));
580 }
581 Ok(now)
582}
583
584#[cfg(test)]
585mod tests {
586 use super::*;
587 use crate::crypto::generate_hybrid_keypair;
588 use crate::v2::reference::Store;
589
590 #[test]
594 fn forged_zero_value_outcome_is_rejected() {
595 let (public, private) = generate_hybrid_keypair();
596 let log_id = "dddddddddddddddddddddddddddddd01";
597 let store = Store::new(1_800_000_000, 30, log_id, &private).unwrap();
598 let forged = CommittedV2Outcome {
599 claim_id: String::new(),
600 verifier_id: String::new(),
601 receipt_body: Vec::new(),
602 challenge_expires_at: 0,
603 allow_horizon: 0,
604 };
605 let result = release_v2_decision(
606 &V2Context::background(),
607 &forged,
608 None,
609 V2ReleaseConfig {
610 verifier_public_key: &public,
611 log_id,
612 claim_store: &store,
613 checkpoint: &store,
614 },
615 );
616 assert_eq!(
617 (result.status, result.reason.as_str()),
618 (V2ReleaseStatus::Rejected, "release_state_mismatch")
619 );
620 assert!(result.decision().is_none());
621 }
622}