1use std::collections::BTreeMap;
14use std::sync::{Arc, Mutex, MutexGuard};
15
16use rand_core::{OsRng, RngCore};
17use sha2::{Digest, Sha256};
18
19use crate::types::HybridPrivateKey;
20use crate::v2::checkpoint_ack::V2CheckpointAcknowledgement;
21use crate::v2::claim_store::{
22 challenge_claim_time_current_v2, claim_id_matches_key, validate_v2_finalization_payload, ClaimStoreV2, V2AuthoritativeClock, V2ChallengeClaim, V2ClaimDisposition,
23 V2ClaimResult, V2RateAtFinalizationStore, V2RateReservationStore, V2StoreError,
24};
25use crate::v2::context::V2Context;
26use crate::v2::crypto::{key_id_v2, public_key_v2};
27use crate::v2::errors::{V2Error, V2ErrorClass, V2Result};
28use crate::v2::evaluation_progress::{
29 initial_v2_evaluation_progress, validate_v2_evaluation_progress_inner, V2CommittedClaim,
30 V2CommittedClaimStore, V2EvaluationProgress, V2InterruptedClaim,
31};
32use crate::v2::rate_reservation::V2RateReservation;
33use crate::v2::receipt::{
34 encode_verification_receipt_v2, sign_prepared_verification_receipt_v2, verification_receipt_v2_digest,
35 ReceiptV2Head,
36};
37use crate::v2::release::{
38 receipt_outbox_digest_v2, valid_v2_release_record_outcome, V2ReceiptCheckpoint, V2ReceiptPublisher,
39 V2ReleaseClaimStore, V2ReleaseRecord, V2ReleaseStatus, V2TerminalClaimRecord,
40};
41use crate::v2::stream_sequence::check_v2_stream_sequence;
42
43pub const ERR_NOT_ACKNOWLEDGED: &str = "v2reference: checkpoint refused the acknowledgement";
46pub const ERR_HEAD_OF_LINE_BLOCKED: &str = "v2reference: an earlier receipt-log entry is still pending";
49pub const ERR_SIGNER_UNAVAILABLE: &str = "v2reference: receipt signer unavailable";
51pub const ERR_LOG_FROZEN: &str = "v2reference: the receipt log is frozen after abandonment";
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub(crate) enum ClaimState {
56 Evaluating,
57 Terminal,
58}
59
60#[derive(Debug, Clone)]
61pub(crate) struct ClaimRecord {
62 pub claim: V2ChallengeClaim,
63 pub owner_digest: [u8; 32],
64 pub lease_expires_at: i64,
65 pub state: ClaimState,
66 pub terminal: Vec<u8>,
67 pub receipt_body: Vec<u8>,
68 pub allow_horizon: i64,
69 pub claimed_at: i64,
70 pub finalized_at: i64,
71 pub release: Option<V2ReleaseRecord>,
72 pub progress: V2EvaluationProgress,
73 pub abandoned: bool,
74 pub outbox_index: Option<usize>,
76}
77
78#[derive(Debug, Clone)]
81pub(crate) struct OutboxEntry {
82 pub claim_id: String,
83 pub body: Vec<u8>,
86 pub wire: Option<Vec<u8>>,
87 pub digest: Vec<u8>,
88 pub ack: Option<V2CheckpointAcknowledgement>,
89}
90
91pub(crate) type OwnerTokenRand = Arc<dyn Fn(&mut [u8]) -> Result<(), String> + Send + Sync>;
93
94pub(crate) type StoreAnchor = Arc<dyn Fn(&StoreState, &StoreState) -> Result<(), V2Error> + Send + Sync>;
99
100#[derive(Clone)]
102pub(crate) struct StoreState {
103 pub now: i64,
104 pub high_water: i64,
105 pub lease_seconds: i64,
106 pub claims: BTreeMap<String, ClaimRecord>,
107 pub streams: BTreeMap<StreamKey, i64>,
108 pub verifier_key: HybridPrivateKey,
109 pub verifier_id: String,
110 pub log_id: String,
111 pub outbox: Vec<OutboxEntry>,
112 pub ack_withheld: bool,
113 pub log_frozen: bool,
114 pub checkpoint_frozen: bool,
117 pub signer_failure: bool,
118 pub rate_at_finalization: bool,
119 pub rate_commits: BTreeMap<(String, String, i64), Vec<i64>>,
120 pub owner_token_rand: OwnerTokenRand,
121 pub anchor: Option<StoreAnchor>,
122}
123
124pub struct Store {
129 state: Mutex<StoreState>,
130}
131
132impl std::fmt::Debug for Store {
133 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134 let s = self.lock();
135 f.debug_struct("Store")
136 .field("now", &s.now)
137 .field("claims", &s.claims.len())
138 .field("log_length", &s.outbox.len())
139 .finish_non_exhaustive()
140 }
141}
142
143fn classified(class: V2ErrorClass, message: &str) -> V2StoreError {
144 V2StoreError::Classified(V2Error::new(class, message))
145}
146
147impl Store {
148 pub fn new(now: i64, lease_seconds: i64, log_id: &str, verifier_key: &HybridPrivateKey) -> V2Result<Store> {
152 let id = key_id_v2(&public_key_v2(verifier_key)?)?;
153 if lease_seconds <= 0 || log_id.len() != 32 {
154 return Err(V2Error::new(
155 V2ErrorClass::ConfigurationInvalid,
156 "v2reference: lease must be positive and log ID 32 hex characters",
157 ));
158 }
159 Ok(Store {
160 state: Mutex::new(StoreState {
161 now,
162 high_water: now,
163 lease_seconds,
164 claims: BTreeMap::new(),
165 streams: BTreeMap::new(),
166 verifier_key: verifier_key.clone(),
167 verifier_id: id,
168 log_id: log_id.to_string(),
169 outbox: Vec::new(),
170 ack_withheld: false,
171 log_frozen: false,
172 checkpoint_frozen: false,
173 signer_failure: false,
174 rate_at_finalization: false,
175 rate_commits: BTreeMap::new(),
176 owner_token_rand: Arc::new(|buf: &mut [u8]| OsRng.try_fill_bytes(buf).map_err(|e| e.to_string())),
177 anchor: None,
178 }),
179 })
180 }
181
182 pub(crate) fn lock(&self) -> MutexGuard<'_, StoreState> {
183 self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
184 }
185
186 pub fn clone_store(&self) -> Store {
190 let mut copy = self.lock().clone();
191 copy.anchor = None;
192 Store {
193 state: Mutex::new(copy),
194 }
195 }
196
197 pub fn set_time(&self, now: i64) {
200 self.lock().now = now;
201 }
202
203 pub fn now(&self) -> i64 {
205 self.lock().now
206 }
207
208 pub fn set_signer_failure(&self, failing: bool) {
211 self.lock().signer_failure = failing;
212 }
213
214 pub fn set_acknowledgement_withheld(&self, withheld: bool) {
218 let mut s = self.lock();
219 s.ack_withheld = withheld;
220 if !withheld {
221 s.acknowledge_pending_locked();
222 }
223 }
224
225 pub fn log_length(&self) -> usize {
227 self.lock().outbox.iter().take_while(|e| e.wire.is_some()).count()
228 }
229
230 pub fn plant_release_test_only(&self, claim_id: &str, ack_timestamp: i64) {
234 let mut s = self.lock();
235 let entry_hash = s
236 .claims
237 .get(claim_id)
238 .and_then(|r| r.outbox_index)
239 .and_then(|i| s.outbox.get(i))
240 .filter(|e| e.wire.is_some())
241 .map(|e| e.digest.clone());
242 if let (Some(entry_hash), Some(record)) = (entry_hash, s.claims.get_mut(claim_id)) {
243 record.release = Some(V2ReleaseRecord {
244 claim_id: claim_id.to_string(),
245 entry_hash,
246 ack_timestamp,
247 outcome: V2ReleaseStatus::Released,
248 reason: String::new(),
249 });
250 }
251 }
252
253 pub fn abandon_pending_receipts(&self) -> Vec<String> {
257 let mut s = self.lock();
258 let mut abandoned = Vec::new();
259 let changed = s.change_locked(|s| {
260 s.log_frozen = true;
261 let pending: Vec<String> = s
262 .outbox
263 .iter()
264 .filter(|e| e.wire.is_none())
265 .map(|e| e.claim_id.clone())
266 .collect();
267 for claim_id in pending {
268 if let Some(record) = s.claims.get_mut(&claim_id) {
269 record.abandoned = true;
270 }
271 abandoned.push(claim_id);
272 }
273 });
274 if changed.is_err() {
275 return Vec::new();
276 }
277 abandoned
278 }
279
280 pub fn with_rate_at_finalization(self: &Arc<Self>) -> Arc<RateAtFinalizationStore> {
284 self.lock().rate_at_finalization = true;
285 Arc::new(RateAtFinalizationStore(Arc::clone(self)))
286 }
287}
288
289enum OwnerFailure {
292 Failed(V2StoreError),
293 Terminal(V2StoreError),
294}
295
296impl StoreState {
297 pub(crate) fn change_locked(&mut self, mutate: impl FnOnce(&mut StoreState)) -> Result<(), V2StoreError> {
300 let Some(anchor) = self.anchor.clone() else {
301 mutate(self);
302 return Ok(());
303 };
304 let before = self.clone();
305 mutate(self);
306 if let Err(e) = anchor(&before, self) {
307 self.claims = before.claims;
308 self.streams = before.streams;
309 self.outbox = before.outbox;
310 self.rate_commits = before.rate_commits;
311 self.log_frozen = before.log_frozen;
312 return Err(classified(
313 V2ErrorClass::ClaimStoreUnavailable,
314 &format!("v2reference: durable state change was not anchored: {}", e.message),
315 ));
316 }
317 Ok(())
318 }
319
320 fn acknowledge_pending_locked(&mut self) {
326 if self.checkpoint_frozen {
327 return;
328 }
329 let mut now = None;
330 for i in 0..self.outbox.len() {
331 if self.outbox[i].wire.is_none() {
332 return;
333 }
334 if self.outbox[i].ack.is_some() {
335 continue;
336 }
337 let timestamp = match now {
338 Some(t) => t,
339 None => match self.read_clock_locked() {
340 Ok(t) => *now.insert(t),
341 Err(_) => return,
342 },
343 };
344 let log_id = self.log_id.clone();
345 let entry = &mut self.outbox[i];
346 entry.ack = Some(V2CheckpointAcknowledgement {
347 log_id,
348 sequence: i as i64 + 1,
349 entry_hash: entry.digest.clone(),
350 timestamp,
351 });
352 }
353 }
354
355 fn read_clock_locked(&mut self) -> Result<i64, V2StoreError> {
358 if self.now < self.high_water {
359 return Err(classified(
360 V2ErrorClass::ClockRegressed,
361 &format!(
362 "v2reference: authoritative clock {} is below its high-water mark {}",
363 self.now, self.high_water
364 ),
365 ));
366 }
367 if !(0..=crate::v2::limits::V2_MAX_TIMESTAMP_SECONDS).contains(&self.now) {
369 return Err(classified(
370 V2ErrorClass::ClaimStoreUnavailable,
371 &format!("v2reference: authoritative clock {} is outside the timestamp domain", self.now),
372 ));
373 }
374 self.high_water = self.now;
375 Ok(self.now)
376 }
377
378 fn owner_locked(&mut self, claim_id: &str, owner_token: &[u8]) -> Result<i64, OwnerFailure> {
380 let Some(record) = self.claims.get(claim_id) else {
381 return Err(OwnerFailure::Failed(classified(V2ErrorClass::ClaimNotFound, "v2reference: unknown claim")));
382 };
383 let digest: [u8; 32] = Sha256::digest(owner_token).into();
384 if !constant_time_eq(&digest, &record.owner_digest) {
385 return Err(OwnerFailure::Failed(classified(
386 V2ErrorClass::ClaimLeaseLost,
387 "v2reference: evaluator owner mismatch",
388 )));
389 }
390 if record.state == ClaimState::Terminal {
391 return Err(OwnerFailure::Terminal(classified(
392 V2ErrorClass::ClaimAlreadyTerminal,
393 "v2reference: claim already terminal",
394 )));
395 }
396 let (claimed_at, lease_expires_at) = (record.claimed_at, record.lease_expires_at);
397 let now = self.read_clock_locked().map_err(OwnerFailure::Failed)?;
398 if now < claimed_at {
399 return Err(OwnerFailure::Failed(classified(
400 V2ErrorClass::ClockRegressed,
401 &format!("v2reference: clock {now} is before T_claim {claimed_at}"),
402 )));
403 }
404 if now >= lease_expires_at {
405 return Err(OwnerFailure::Failed(classified(
406 V2ErrorClass::ClaimLeaseLost,
407 "v2reference: evaluator lease expired",
408 )));
409 }
410 Ok(now)
411 }
412
413 fn commit_terminal_locked(&mut self, claim_id: &str, terminal: &[u8], body: &[u8], allow_horizon: i64, final_at: i64) {
416 let index = self.outbox.len();
417 if let Some(record) = self.claims.get_mut(claim_id) {
418 record.state = ClaimState::Terminal;
419 record.terminal = terminal.to_vec();
420 record.receipt_body = body.to_vec();
421 record.allow_horizon = allow_horizon;
422 record.finalized_at = final_at;
423 record.outbox_index = Some(index);
424 self.outbox.push(OutboxEntry {
425 claim_id: claim_id.to_string(),
426 body: body.to_vec(),
427 wire: None,
428 digest: Vec::new(),
429 ack: None,
430 });
431 }
432 }
433}
434
435fn constant_time_eq(a: &[u8; 32], b: &[u8; 32]) -> bool {
436 a.iter().zip(b.iter()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
437}
438
439pub(crate) type StreamKey = (String, String, Vec<u8>);
443
444fn stream_key(claim: &V2ChallengeClaim) -> StreamKey {
445 (
446 claim.namespace.clone(),
447 claim.agent_id.clone(),
448 claim.stream_id.clone().unwrap_or_default(),
449 )
450}
451
452impl V2AuthoritativeClock for Store {
453 fn authoritative_time_v2(&self, _ctx: &V2Context) -> Result<i64, V2StoreError> {
455 self.lock().read_clock_locked()
456 }
457}
458
459impl ClaimStoreV2 for Store {
460 fn claim_v2(&self, _ctx: &V2Context, claim: V2ChallengeClaim) -> Result<V2ClaimResult, V2StoreError> {
467 let mut s = self.lock();
468 if !claim_id_matches_key(&claim) {
469 return Err(classified(
470 V2ErrorClass::ConfigurationInvalid,
471 "v2reference: claim ID is not derived from the claim's namespace, replay epoch and challenge digest",
472 ));
473 }
474 let now = s
475 .read_clock_locked()
476 .map_err(|e| classified(V2ErrorClass::ClaimStoreUnavailable, &e.to_string()))?;
477 if let Some(existing) = s.claims.get(&claim.claim_id) {
478 if existing.claim != claim {
479 return Err(V2StoreError::ClaimProofConflict);
480 }
481 if existing.abandoned {
482 return Err(classified(
483 V2ErrorClass::ReceiptAbandoned,
484 "v2reference: the receipt for this claim was abandoned; a fresh challenge is required",
485 ));
486 }
487 let disposition = if existing.state == ClaimState::Terminal {
488 V2ClaimDisposition::TerminalReplay
489 } else {
490 V2ClaimDisposition::InProgress
491 };
492 return Ok(V2ClaimResult {
493 disposition,
494 claimed_at: existing.claimed_at,
495 owner_token: Vec::new(),
496 });
497 }
498 if !challenge_claim_time_current_v2(&claim, now) {
499 return Err(classified(
500 V2ErrorClass::ChallengeNotFresh,
501 "v2reference: challenge is not current at the store clock",
502 ));
503 }
504 let mut key: Option<StreamKey> = None;
505 if claim.stream_id.is_some() || claim.stream_seq.is_some() {
506 let Some(seq) = claim.stream_seq.filter(|_| claim.stream_id.is_some()) else {
507 return Err(classified(
508 V2ErrorClass::Malformed,
509 "v2reference: stream_id and stream_seq must appear together",
510 ));
511 };
512 let k = stream_key(&claim);
513 let last = s.streams.get(&k).copied();
514 key = Some(k);
515 check_v2_stream_sequence(last.is_some(), last.unwrap_or_default(), seq)?;
516 }
517 let mut owner = vec![0u8; 32];
518 (s.owner_token_rand)(&mut owner).map_err(V2StoreError::Unavailable)?;
519 let owner_digest: [u8; 32] = Sha256::digest(&owner).into();
520 let lease_expires_at = now + s.lease_seconds;
521 s.change_locked(|s| {
522 if let (Some(k), Some(seq)) = (&key, claim.stream_seq) {
523 s.streams.insert(k.clone(), seq);
524 }
525 s.claims.insert(
526 claim.claim_id.clone(),
527 ClaimRecord {
528 claim: claim.clone(),
529 owner_digest,
530 lease_expires_at,
531 state: ClaimState::Evaluating,
532 terminal: Vec::new(),
533 receipt_body: Vec::new(),
534 allow_horizon: 0,
535 claimed_at: now,
536 finalized_at: 0,
537 release: None,
538 progress: initial_v2_evaluation_progress(),
539 abandoned: false,
540 outbox_index: None,
541 },
542 );
543 })?;
544 Ok(V2ClaimResult {
545 disposition: V2ClaimDisposition::Created,
546 claimed_at: now,
547 owner_token: owner,
548 })
549 }
550
551 fn finalize_v2_claim(
563 &self,
564 _ctx: &V2Context,
565 claim_id: &str,
566 owner_token: &[u8],
567 terminal_result: &[u8],
568 receipt_body: &[u8],
569 allow_valid_until: i64,
570 ) -> Result<bool, V2StoreError> {
571 let mut s = self.lock();
572 let final_at = match s.owner_locked(claim_id, owner_token) {
573 Ok(t) => t,
574 Err(OwnerFailure::Terminal(e)) => {
575 let identical = s
576 .claims
577 .get(claim_id)
578 .is_some_and(|r| r.terminal == terminal_result && r.receipt_body == receipt_body);
579 return if identical { Ok(false) } else { Err(e) };
580 }
581 Err(OwnerFailure::Failed(e)) => return Err(e),
582 };
583 let Some(record) = s.claims.get(claim_id) else {
584 return Err(classified(V2ErrorClass::ClaimNotFound, "v2reference: unknown claim"));
585 };
586 validate_v2_finalization_payload(&record.claim, terminal_result, receipt_body)?;
587 let decision = crate::v2::receipt::decode_verification_receipt_body_v2(receipt_body)?.decision;
591 let horizon_ok = if decision == "allow" {
592 allow_valid_until > 0 && allow_valid_until <= crate::v2::limits::V2_MAX_TIMESTAMP_SECONDS
593 } else {
594 allow_valid_until == 0
595 };
596 if !horizon_ok {
597 return Err(classified(
598 V2ErrorClass::ConfigurationInvalid,
599 "v2reference: the allow horizon does not match the decision",
600 ));
601 }
602 if allow_valid_until > 0 && (final_at >= allow_valid_until || final_at >= record.claim.expires_at) {
603 return Err(classified(
604 V2ErrorClass::AllowHorizonPassed,
605 "v2reference: allow is at or beyond its horizon",
606 ));
607 }
608 let batch: Vec<V2RateReservation> = record.claim.rate_batch.clone();
609 let admit_rate = allow_valid_until > 0 && s.rate_at_finalization && !batch.is_empty();
610 if admit_rate {
611 for item in &batch {
612 let key = (item.issuer_id.clone(), item.cert_id.clone(), item.window_s);
613 let active = s
614 .rate_commits
615 .get(&key)
616 .map_or(0, |times| times.iter().filter(|&&at| at > final_at - item.window_s).count());
617 if active as i64 >= item.limit {
618 return Err(V2StoreError::RateLimitExceeded);
619 }
620 }
621 }
622 s.change_locked(|s| {
623 if admit_rate {
624 for item in &batch {
625 s.rate_commits
626 .entry((item.issuer_id.clone(), item.cert_id.clone(), item.window_s))
627 .or_default()
628 .push(final_at);
629 }
630 }
631 s.commit_terminal_locked(claim_id, terminal_result, receipt_body, allow_valid_until, final_at);
632 })?;
633 Ok(true)
634 }
635
636 fn record_v2_evaluation_progress(
639 &self,
640 _ctx: &V2Context,
641 claim_id: &str,
642 owner_token: &[u8],
643 progress: V2EvaluationProgress,
644 ) -> Result<(), V2StoreError> {
645 let mut s = self.lock();
646 match s.owner_locked(claim_id, owner_token) {
647 Ok(_) => {}
648 Err(OwnerFailure::Failed(e)) | Err(OwnerFailure::Terminal(e)) => return Err(e),
649 }
650 if let Err(e) = validate_v2_evaluation_progress_inner(&progress) {
651 return Err(V2StoreError::Classified(e.classify(V2ErrorClass::Malformed)));
652 }
653 s.change_locked(|s| {
654 if let Some(record) = s.claims.get_mut(claim_id) {
655 record.progress = progress;
656 }
657 })
658 }
659
660 fn load_v2_interrupted_claim(&self, _ctx: &V2Context, claim_id: &str) -> Result<V2InterruptedClaim, V2StoreError> {
663 let mut s = self.lock();
664 if !s.claims.contains_key(claim_id) {
665 return Err(classified(V2ErrorClass::ClaimNotFound, "v2reference: unknown claim"));
666 }
667 let now = s.read_clock_locked()?;
668 let Some(record) = s.claims.get(claim_id) else {
669 return Err(classified(V2ErrorClass::ClaimNotFound, "v2reference: unknown claim"));
670 };
671 if record.state == ClaimState::Evaluating && now < record.lease_expires_at {
672 return Err(classified(V2ErrorClass::ClaimLeaseLive, "v2reference: evaluator lease is still live"));
673 }
674 Ok(V2InterruptedClaim {
675 claim: record.claim.clone(),
676 claimed_at: record.claimed_at,
677 progress: record.progress.clone(),
678 })
679 }
680
681 fn recover_interrupted_v2_claim(
688 &self,
689 _ctx: &V2Context,
690 claim_id: &str,
691 terminal_result: &[u8],
692 receipt_body: &[u8],
693 ) -> Result<bool, V2StoreError> {
694 let mut s = self.lock();
695 let Some(record) = s.claims.get(claim_id) else {
696 return Err(classified(V2ErrorClass::ClaimNotFound, "v2reference: unknown claim"));
697 };
698 if record.state == ClaimState::Terminal {
699 if record.terminal == terminal_result && record.receipt_body == receipt_body {
700 return Ok(false);
701 }
702 return Err(classified(V2ErrorClass::ClaimAlreadyTerminal, "v2reference: claim already terminal"));
703 }
704 let lease_expires_at = record.lease_expires_at;
705 let now = s.read_clock_locked()?;
706 if now < lease_expires_at {
707 return Err(classified(V2ErrorClass::ClaimLeaseLive, "v2reference: evaluator lease is still live"));
708 }
709 let Some(record) = s.claims.get(claim_id) else {
710 return Err(classified(V2ErrorClass::ClaimNotFound, "v2reference: unknown claim"));
711 };
712 validate_v2_finalization_payload(&record.claim, terminal_result, receipt_body)?;
713 let body = crate::v2::receipt::decode_verification_receipt_body_v2(receipt_body)?;
716 if body.decision != "indeterminate" || body.decision_reason != "evaluation_interrupted" {
717 return Err(classified(
718 V2ErrorClass::ConfigurationInvalid,
719 "v2reference: recovery may commit only indeterminate/evaluation_interrupted",
720 ));
721 }
722 s.change_locked(|s| s.commit_terminal_locked(claim_id, terminal_result, receipt_body, 0, now))?;
723 Ok(true)
724 }
725}
726
727impl V2CommittedClaimStore for Store {
732 fn load_v2_committed_claim(&self, _ctx: &V2Context, claim_id: &str) -> Result<V2CommittedClaim, V2StoreError> {
733 let mut s = self.lock();
734 let Some(record) = s.claims.get(claim_id) else {
735 return Err(classified(V2ErrorClass::ClaimNotFound, "v2reference: unknown claim"));
736 };
737 if record.state != ClaimState::Terminal {
738 let lease_expires_at = record.lease_expires_at;
739 let now = s.read_clock_locked()?;
740 if now < lease_expires_at {
741 return Err(classified(V2ErrorClass::ClaimLeaseLive, "v2reference: evaluator lease is still live"));
742 }
743 return Err(classified(
744 V2ErrorClass::ClaimLeaseLost,
745 "v2reference: claim is not terminal; recover it first",
746 ));
747 }
748 Ok(V2CommittedClaim {
749 claim: record.claim.clone(),
750 terminal_result: record.terminal.clone(),
751 receipt_body: record.receipt_body.clone(),
752 allow_horizon: record.allow_horizon,
753 })
754 }
755}
756
757impl V2ReleaseClaimStore for Store {
758 fn load_v2_terminal_claim(&self, _ctx: &V2Context, claim_id: &str) -> Result<V2TerminalClaimRecord, V2StoreError> {
759 let s = self.lock();
760 let Some(record) = s.claims.get(claim_id) else {
761 return Err(classified(V2ErrorClass::ClaimNotFound, "v2reference: unknown claim"));
762 };
763 let terminal = record.state == ClaimState::Terminal;
764 Ok(V2TerminalClaimRecord {
765 terminal,
766 receipt_outbox_digest: if terminal {
767 receipt_outbox_digest_v2(&record.receipt_body)
768 } else {
769 String::new()
770 },
771 challenge_expires_at: record.claim.expires_at,
772 allow_horizon: record.allow_horizon,
773 finalized_at: record.finalized_at,
774 receipt_abandoned: record.abandoned,
775 release: record.release.clone(),
776 })
777 }
778
779 fn record_v2_release(&self, _ctx: &V2Context, release: V2ReleaseRecord) -> Result<(), V2StoreError> {
784 let mut s = self.lock();
785 if !valid_v2_release_record_outcome(release.outcome, &release.reason) {
786 return Err(classified(
787 V2ErrorClass::ConfigurationInvalid,
788 &format!(
789 "v2reference: invalid release record outcome {:?} reason {:?}",
790 release.outcome.as_str(),
791 release.reason
792 ),
793 ));
794 }
795 let Some(record) = s.claims.get(&release.claim_id) else {
796 return Err(V2StoreError::ReleaseStateMismatch);
797 };
798 if record.state != ClaimState::Terminal {
799 return Err(V2StoreError::ReleaseStateMismatch);
800 }
801 if let Some(existing) = &record.release {
802 if existing.entry_hash == release.entry_hash
803 && existing.ack_timestamp == release.ack_timestamp
804 && existing.outcome == release.outcome
805 && existing.reason == release.reason
806 {
807 return Ok(());
808 }
809 return Err(V2StoreError::ReleaseStateMismatch);
810 }
811 let claim_id = release.claim_id.clone();
812 s.change_locked(|s| {
813 if let Some(record) = s.claims.get_mut(&claim_id) {
814 record.release = Some(release);
815 }
816 })
817 }
818}
819
820impl V2ReceiptPublisher for Store {
821 fn publish_v2_receipt(&self, _ctx: &V2Context, claim_id: &str, receipt_body: &[u8]) -> Result<Vec<u8>, V2StoreError> {
826 let mut s = self.lock();
827 let index = match s.claims.get(claim_id) {
828 Some(r) if r.state == ClaimState::Terminal && r.receipt_body == receipt_body => r.outbox_index,
829 _ => None,
830 };
831 let Some(index) = index.filter(|&i| i < s.outbox.len()) else {
832 return Err(V2StoreError::Unavailable(
833 "v2reference: no committed outbox body for this claim matches".into(),
834 ));
835 };
836 if let Some(wire) = s.outbox.get(index).and_then(|e| e.wire.clone()) {
837 return Ok(wire);
838 }
839 if s.log_frozen {
840 return Err(V2StoreError::Unavailable(ERR_LOG_FROZEN.into()));
841 }
842 if index > 0 && s.outbox.get(index - 1).is_some_and(|e| e.wire.is_none()) {
843 return Err(V2StoreError::Unavailable(ERR_HEAD_OF_LINE_BLOCKED.into()));
844 }
845 if s.signer_failure {
846 return Err(V2StoreError::Unavailable(ERR_SIGNER_UNAVAILABLE.into()));
847 }
848 let mut head = ReceiptV2Head {
849 log_id: s.log_id.clone(),
850 verifier_id: s.verifier_id.clone(),
851 sequence: index as i64,
852 head_hash: vec![0; 48],
853 accepted_digests: BTreeMap::new(),
854 frozen: false,
855 };
856 for (i, entry) in s.outbox.iter().take(index).enumerate() {
857 head.accepted_digests.insert(i as i64 + 1, entry.digest.clone());
858 }
859 if index > 0 {
860 if let Some(previous) = s.outbox.get(index - 1) {
861 head.head_hash = previous.digest.clone();
862 }
863 }
864 let receipt = sign_prepared_verification_receipt_v2(receipt_body, &head, &s.verifier_key)
865 .map_err(|e| V2StoreError::Unavailable(e.to_string()))?;
866 let wire = encode_verification_receipt_v2(&receipt).map_err(V2StoreError::Classified)?;
867 let digest = verification_receipt_v2_digest(&receipt).map_err(V2StoreError::Classified)?;
868 let stored = wire.clone();
869 s.change_locked(|s| {
870 if let Some(entry) = s.outbox.get_mut(index) {
871 entry.wire = Some(stored);
872 entry.digest = digest;
873 }
874 })?;
875 if !s.ack_withheld {
876 s.acknowledge_pending_locked();
877 }
878 Ok(wire)
879 }
880}
881
882impl V2ReceiptCheckpoint for Store {
883 fn acknowledge_v2_receipt(
892 &self,
893 _ctx: &V2Context,
894 log_id: &str,
895 sequence: i64,
896 previous_entry_hash: &[u8],
897 entry_hash: &[u8],
898 ) -> Result<V2CheckpointAcknowledgement, V2StoreError> {
899 let mut s = self.lock();
900 let refused = || V2StoreError::Unavailable(ERR_NOT_ACKNOWLEDGED.into());
901 if log_id != s.log_id || sequence < 1 || sequence as usize > s.outbox.len() {
902 return Err(refused());
903 }
904 let index = sequence as usize - 1;
905 let acked = s.outbox[index].ack.as_ref().map(|a| a.entry_hash.clone());
906 if acked.as_ref().is_some_and(|h| h != entry_hash) {
907 s.checkpoint_frozen = true;
908 return Err(V2StoreError::Unavailable(format!(
909 "{ERR_NOT_ACKNOWLEDGED}: a different entry hash at acknowledged sequence {sequence} is a fork; the log is frozen"
910 )));
911 }
912 if s.checkpoint_frozen && acked.is_none() {
913 return Err(V2StoreError::Unavailable(format!(
914 "{ERR_NOT_ACKNOWLEDGED}: the log is frozen after a fork"
915 )));
916 }
917 match s.outbox.get(index) {
918 Some(e) if e.wire.is_some() && e.digest == entry_hash => {}
919 _ => return Err(refused()),
920 }
921 let mut previous = vec![0u8; 48];
922 if index > 0 {
923 match s.outbox.get(index - 1) {
924 Some(p) if p.ack.is_some() => previous = p.digest.clone(),
925 _ => return Err(refused()),
926 }
927 }
928 if previous != previous_entry_hash {
929 return Err(refused());
930 }
931 if s.outbox[index].ack.is_none() {
932 let now = s.read_clock_locked()?;
933 let entry = s.outbox.get_mut(index).ok_or_else(refused)?;
934 entry.ack = Some(V2CheckpointAcknowledgement {
935 log_id: log_id.to_string(),
936 sequence,
937 entry_hash: entry_hash.to_vec(),
938 timestamp: now,
939 });
940 }
941 s.outbox[index].ack.clone().ok_or_else(refused)
942 }
943
944 fn get_v2_acknowledgement(
945 &self,
946 _ctx: &V2Context,
947 log_id: &str,
948 sequence: i64,
949 ) -> Result<V2CheckpointAcknowledgement, V2StoreError> {
950 let s = self.lock();
951 if log_id != s.log_id || sequence < 1 {
952 return Err(V2StoreError::AcknowledgementNotFound);
953 }
954 s.outbox
955 .get(sequence as usize - 1)
956 .and_then(|e| e.ack.clone())
957 .ok_or(V2StoreError::AcknowledgementNotFound)
958 }
959}
960
961#[derive(Debug)]
965pub struct RateAtFinalizationStore(pub Arc<Store>);
966
967impl V2AuthoritativeClock for RateAtFinalizationStore {
968 fn authoritative_time_v2(&self, ctx: &V2Context) -> Result<i64, V2StoreError> {
969 self.0.authoritative_time_v2(ctx)
970 }
971}
972
973impl ClaimStoreV2 for RateAtFinalizationStore {
974 fn claim_v2(&self, ctx: &V2Context, claim: V2ChallengeClaim) -> Result<V2ClaimResult, V2StoreError> {
975 self.0.claim_v2(ctx, claim)
976 }
977 fn finalize_v2_claim(
978 &self,
979 ctx: &V2Context,
980 claim_id: &str,
981 owner_token: &[u8],
982 terminal_result: &[u8],
983 receipt_body: &[u8],
984 allow_valid_until: i64,
985 ) -> Result<bool, V2StoreError> {
986 self.0
987 .finalize_v2_claim(ctx, claim_id, owner_token, terminal_result, receipt_body, allow_valid_until)
988 }
989 fn record_v2_evaluation_progress(
990 &self,
991 ctx: &V2Context,
992 claim_id: &str,
993 owner_token: &[u8],
994 progress: V2EvaluationProgress,
995 ) -> Result<(), V2StoreError> {
996 self.0.record_v2_evaluation_progress(ctx, claim_id, owner_token, progress)
997 }
998 fn load_v2_interrupted_claim(&self, ctx: &V2Context, claim_id: &str) -> Result<V2InterruptedClaim, V2StoreError> {
999 self.0.load_v2_interrupted_claim(ctx, claim_id)
1000 }
1001 fn recover_interrupted_v2_claim(
1002 &self,
1003 ctx: &V2Context,
1004 claim_id: &str,
1005 terminal_result: &[u8],
1006 receipt_body: &[u8],
1007 ) -> Result<bool, V2StoreError> {
1008 self.0.recover_interrupted_v2_claim(ctx, claim_id, terminal_result, receipt_body)
1009 }
1010 fn rate_at_finalization_view(&self) -> Option<&dyn V2RateAtFinalizationStore> {
1011 Some(self)
1012 }
1013}
1014
1015impl V2RateReservationStore for RateAtFinalizationStore {
1016 fn reserve_v2_rate_batch(
1020 &self,
1021 _ctx: &V2Context,
1022 _claim_id: &str,
1023 _owner_token: &[u8],
1024 _bundle_hash: &str,
1025 _batch: &[V2RateReservation],
1026 ) -> Result<(), V2StoreError> {
1027 Err(V2StoreError::Unavailable(
1028 "v2reference: provisional rate reservation is not used with admission at finalization".into(),
1029 ))
1030 }
1031 fn rate_at_finalization_view(&self) -> Option<&dyn V2RateAtFinalizationStore> {
1032 Some(self)
1033 }
1034}
1035
1036impl V2RateAtFinalizationStore for RateAtFinalizationStore {
1037 fn admits_v2_rate_at_finalization(&self) {}
1038}
1039
1040impl V2CommittedClaimStore for RateAtFinalizationStore {
1041 fn load_v2_committed_claim(&self, ctx: &V2Context, claim_id: &str) -> Result<V2CommittedClaim, V2StoreError> {
1042 self.0.load_v2_committed_claim(ctx, claim_id)
1043 }
1044}
1045
1046impl V2ReleaseClaimStore for RateAtFinalizationStore {
1047 fn load_v2_terminal_claim(&self, ctx: &V2Context, claim_id: &str) -> Result<V2TerminalClaimRecord, V2StoreError> {
1048 self.0.load_v2_terminal_claim(ctx, claim_id)
1049 }
1050 fn record_v2_release(&self, ctx: &V2Context, record: V2ReleaseRecord) -> Result<(), V2StoreError> {
1051 self.0.record_v2_release(ctx, record)
1052 }
1053}
1054
1055#[cfg(test)]
1056mod tests {
1057 use super::*;
1058 use crate::crypto::generate_hybrid_keypair;
1059
1060 #[test]
1065 fn rate_at_finalization_store_never_reserves_provisionally() {
1066 let (_, private) = generate_hybrid_keypair();
1067 let store = Arc::new(Store::new(1_800_000_000, 30, "dddddddddddddddddddddddddddddd01", &private).unwrap())
1068 .with_rate_at_finalization();
1069 let batch = [V2RateReservation {
1070 issuer_id: "i".into(),
1071 cert_id: "c".into(),
1072 window_s: 60,
1073 limit: 1,
1074 }];
1075 let reserved = store.reserve_v2_rate_batch(&V2Context::background(), "claim", &[0; 32], "sha384:x", &batch);
1076 assert!(reserved.is_err(), "the reference provisional reservation reported capacity");
1077 }
1078}