Skip to main content

ratify_protocol/v2/reference/
challenges.rs

1//! The in-memory REFERENCE challenge issuance store. Mirrors Go
2//! `v2reference/challenges.go`.
3//!
4//! TEST AND CONFORMANCE USE ONLY: it is not durable, does not survive a
5//! restart, and does not span processes, so a verifier using it cannot claim
6//! durable issuance or release conformance.
7
8use std::collections::BTreeMap;
9use std::sync::{Mutex, MutexGuard};
10
11use crate::v2::challenge_issuance::V2ChallengeIssuanceStore;
12use crate::v2::claim_store::V2StoreError;
13use crate::v2::context::V2Context;
14use crate::v2::operation_context::challenge_claim_digest_v2;
15use crate::v2::preflight::ExpectedChallengeV2;
16
17/// The message of a scripted persistence failure (Go `ErrPersistFailed`).
18pub const ERR_PERSIST_FAILED: &str = "v2reference: scripted issuance persistence failure";
19
20/// Scripts the next `persist_v2_challenge` call.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
22pub enum PersistFault {
23    /// Store the record normally.
24    #[default]
25    Ok,
26    /// Fail without storing anything.
27    FailBeforeCommit,
28    /// Store the record, then report failure, as a crash after the durable
29    /// write but before the response would.
30    FailAfterCommit,
31}
32
33struct State {
34    records: BTreeMap<String, ExpectedChallengeV2>,
35    fault: PersistFault,
36}
37
38/// The in-memory reference [`V2ChallengeIssuanceStore`]. TEST ONLY.
39pub struct TestOnlyChallengeIssuanceStore {
40    state: Mutex<State>,
41}
42
43impl std::fmt::Debug for TestOnlyChallengeIssuanceStore {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        f.debug_struct("TestOnlyChallengeIssuanceStore")
46            .field("records", &self.len())
47            .finish()
48    }
49}
50
51impl Default for TestOnlyChallengeIssuanceStore {
52    fn default() -> Self {
53        Self::new()
54    }
55}
56
57pub(crate) fn issuance_key(namespace: &str, epoch: i64, digest: &[u8]) -> String {
58    format!("{}:{}|{}|{}", namespace.len(), namespace, epoch, hex::encode(digest))
59}
60
61impl TestOnlyChallengeIssuanceStore {
62    /// An empty store.
63    pub fn new() -> Self {
64        TestOnlyChallengeIssuanceStore {
65            state: Mutex::new(State {
66                records: BTreeMap::new(),
67                fault: PersistFault::Ok,
68            }),
69        }
70    }
71
72    fn lock(&self) -> MutexGuard<'_, State> {
73        self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
74    }
75
76    /// Arm a fault for the next `persist_v2_challenge` call only.
77    pub fn fail_next_persist(&self, fault: PersistFault) {
78        self.lock().fault = fault;
79    }
80
81    /// The number of stored records.
82    pub fn len(&self) -> usize {
83        self.lock().records.len()
84    }
85
86    /// Whether no record is stored.
87    pub fn is_empty(&self) -> bool {
88        self.len() == 0
89    }
90
91    /// Every stored record by issuance key (read by the single-device
92    /// profile's complete-state digest, copy, and undo).
93    pub(crate) fn records(&self) -> BTreeMap<String, ExpectedChallengeV2> {
94        self.lock().records.clone()
95    }
96
97    /// Replace every stored record.
98    pub(crate) fn set_records(&self, records: BTreeMap<String, ExpectedChallengeV2>) {
99        self.lock().records = records;
100    }
101}
102
103impl V2ChallengeIssuanceStore for TestOnlyChallengeIssuanceStore {
104    /// Insert only, never overwrite.
105    fn persist_v2_challenge(&self, _ctx: &V2Context, record: ExpectedChallengeV2) -> Result<(), V2StoreError> {
106        let mut s = self.lock();
107        let fault = std::mem::take(&mut s.fault);
108        if fault == PersistFault::FailBeforeCommit {
109            return Err(V2StoreError::Unavailable(ERR_PERSIST_FAILED.into()));
110        }
111        let digest = challenge_claim_digest_v2(&record.value)?;
112        let key = issuance_key(&record.verifier_namespace, record.replay_epoch, &digest);
113        if s.records.contains_key(&key) {
114            return Err(V2StoreError::ChallengeIssuanceConflict);
115        }
116        s.records.insert(key, record);
117        if fault == PersistFault::FailAfterCommit {
118            return Err(V2StoreError::Unavailable(ERR_PERSIST_FAILED.into()));
119        }
120        Ok(())
121    }
122
123    fn load_v2_challenge(
124        &self,
125        _ctx: &V2Context,
126        namespace: &str,
127        replay_epoch: i64,
128        claim_digest: &[u8],
129    ) -> Result<ExpectedChallengeV2, V2StoreError> {
130        self.lock()
131            .records
132            .get(&issuance_key(namespace, replay_epoch, claim_digest))
133            .cloned()
134            .ok_or(V2StoreError::ChallengeIssuanceNotFound)
135    }
136}