1use serde::{Deserialize, Serialize};
20use uuid::Uuid;
21
22use crate::record::{
23 EpistemicStatus, EvidenceType, InstantBridge, RecordEnvelope, SensitivityClass,
24};
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
32#[serde(rename_all = "snake_case")]
33pub enum VerificationState {
34 Unverified,
36 SchemaValid,
38 IssuerTrusted,
40 Revoked,
42 Expired,
44}
45
46impl Default for VerificationState {
47 fn default() -> Self {
48 Self::Unverified
49 }
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct CredentialRecord {
58 pub id: String,
59 pub issuer_did: String,
60 pub subject_did: String,
61 pub credential_type: String,
62 pub claims: Vec<(String, String)>,
63 pub issued_at_unix: u32,
64 #[serde(skip_serializing_if = "Option::is_none", default)]
67 pub issued_at_instant: Option<InstantBridge>,
68 #[serde(default, skip_serializing_if = "Option::is_none")]
69 pub expires_at_unix: Option<u32>,
70 #[serde(skip_serializing_if = "Option::is_none", default)]
73 pub expires_at_instant: Option<InstantBridge>,
74 #[serde(default)]
75 pub verification_state: VerificationState,
76}
77
78impl CredentialRecord {
79 pub fn new(
81 issuer_did: impl Into<String>,
82 subject_did: impl Into<String>,
83 credential_type: impl Into<String>,
84 issued_at_unix: u32,
85 ) -> Self {
86 Self {
87 id: Uuid::new_v4().to_string(),
88 issuer_did: issuer_did.into(),
89 subject_did: subject_did.into(),
90 credential_type: credential_type.into(),
91 claims: Vec::new(),
92 issued_at_unix,
93 issued_at_instant: Some(InstantBridge::from_coarse(issued_at_unix)),
94 expires_at_unix: None,
95 expires_at_instant: None,
96 verification_state: VerificationState::Unverified,
97 }
98 }
99
100 pub fn issued_at(&self) -> InstantBridge {
103 self.issued_at_instant
104 .unwrap_or_else(|| InstantBridge::from_coarse(self.issued_at_unix))
105 }
106
107 pub fn expires_at(&self) -> Option<InstantBridge> {
110 self.expires_at_instant
111 .or_else(|| self.expires_at_unix.map(|t| InstantBridge::from_coarse(t)))
112 }
113
114 pub fn with_claim(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
116 self.claims.push((key.into(), value.into()));
117 self
118 }
119}
120
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct PresentationRequest {
127 pub credential_id: String,
129 pub selected_claim_keys: Vec<String>,
131}
132
133impl PresentationRequest {
134 pub fn new(credential_id: impl Into<String>, selected_claim_keys: Vec<String>) -> Self {
136 Self {
137 credential_id: credential_id.into(),
138 selected_claim_keys,
139 }
140 }
141}
142
143#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
151pub struct FieldSelectedPresentation {
152 pub credential_id: String,
153 pub issuer_did: String,
154 pub subject_did: String,
155 pub credential_type: String,
156 pub disclosed_claims: Vec<(String, String)>,
158 pub verification_state: VerificationState,
161}
162
163pub fn evaluate_state(
173 cred: &CredentialRecord,
174 trusted_issuers: &[String],
175 now_unix: u32,
176) -> VerificationState {
177 if cred.verification_state == VerificationState::Revoked {
178 return VerificationState::Revoked;
179 }
180 if let Some(expiry) = cred.expires_at_unix {
181 if expiry <= now_unix {
182 return VerificationState::Expired;
183 }
184 }
185 if trusted_issuers.iter().any(|i| i == &cred.issuer_did) {
186 return VerificationState::IssuerTrusted;
187 }
188 if !cred.claims.is_empty() {
189 return VerificationState::SchemaValid;
190 }
191 VerificationState::Unverified
192}
193
194pub fn build_presentation(
200 cred: &CredentialRecord,
201 selected_claim_keys: &[String],
202) -> FieldSelectedPresentation {
203 let disclosed_claims: Vec<(String, String)> = cred
204 .claims
205 .iter()
206 .filter(|(k, _)| selected_claim_keys.iter().any(|s| s == k))
207 .cloned()
208 .collect();
209 FieldSelectedPresentation {
210 credential_id: cred.id.clone(),
211 issuer_did: cred.issuer_did.clone(),
212 subject_did: cred.subject_did.clone(),
213 credential_type: cred.credential_type.clone(),
214 disclosed_claims,
215 verification_state: cred.verification_state,
216 }
217}
218
219pub fn credential_record_id(uuid: &str) -> String {
221 format!("urn:wellfair:credential:{uuid}")
222}
223
224pub fn build_credential_envelope(
232 cred: &CredentialRecord,
233 owner_did: &str,
234 author_did: &str,
235 asserted_unix: u32,
236 blob_hash: Option<String>,
237) -> RecordEnvelope {
238 RecordEnvelope {
239 id: credential_record_id(&cred.id),
240 owner_did: owner_did.to_string(),
241 author_did: author_did.to_string(),
242 proxy_did: None,
243 epistemic_status: EpistemicStatus::Asserted,
244 evidence_type: EvidenceType::Inferred,
245 sensitivity: SensitivityClass::Restricted,
246 asserted_time_unix: asserted_unix,
247 asserted_instant: None,
248 valid_time_start_unix: Some(cred.issued_at_unix),
249 valid_time_start_instant: cred.issued_at_instant,
250 valid_time_end_unix: cred.expires_at_unix,
251 valid_time_end_instant: cred.expires_at_instant,
252 predecessor_id: None,
253 blob_hash,
254 tombstone: false,
255 }
256}
257
258pub fn credential_summary(cred: &CredentialRecord) -> String {
260 serde_json::json!({
261 "credential_type": cred.credential_type,
262 "issuer_did": cred.issuer_did,
263 "subject_did": cred.subject_did,
264 "claim_count": cred.claims.len(),
265 "issued_at_unix": cred.issued_at_unix,
266 "expires_at_unix": cred.expires_at_unix,
267 "verification_state": cred.verification_state,
268 })
269 .to_string()
270}
271
272pub fn presentation_summary(pres: &FieldSelectedPresentation) -> String {
274 serde_json::json!({
275 "credential_id": pres.credential_id,
276 "credential_type": pres.credential_type,
277 "issuer_did": pres.issuer_did,
278 "disclosed_keys": pres
279 .disclosed_claims
280 .iter()
281 .map(|(k, _)| k.clone())
282 .collect::<Vec<_>>(),
283 "verification_state": pres.verification_state,
284 "disclosure_kind": "field_selection_not_zk",
286 })
287 .to_string()
288}
289
290#[cfg(test)]
291mod tests {
292 use super::*;
293
294 fn sample_cred() -> CredentialRecord {
295 CredentialRecord::new(
296 "did:wf:issuer",
297 "did:wf:subject",
298 "ProofOfAddress",
299 1_700_000_000,
300 )
301 .with_claim("full_name", "Jane Roe")
302 .with_claim("street", "1 Camper Lane")
303 .with_claim("postcode", "3000")
304 }
305
306 #[test]
307 fn credential_envelope_kind_and_class() {
308 let cred = sample_cred();
309 let env = build_credential_envelope(
310 &cred,
311 "did:wf:owner",
312 "did:wf:owner",
313 1_700_000_100,
314 Some("blobhash".into()),
315 );
316 assert!(env.id.contains(":credential:"));
317 assert_eq!(env.sensitivity, SensitivityClass::Restricted);
318 assert_eq!(env.evidence_type, EvidenceType::Inferred);
319 assert_eq!(env.epistemic_status, EpistemicStatus::Asserted);
320 assert_eq!(
323 crate::conditions::journal_kind_for_record_id(&env.id),
324 "credential"
325 );
326 }
327
328 #[test]
329 fn envelope_valid_time_end_tracks_expiry() {
330 let mut cred = sample_cred();
331 cred.expires_at_unix = Some(1_800_000_000);
332 let env = build_credential_envelope(&cred, "did:wf:owner", "did:wf:owner", 1, None);
333 assert_eq!(env.valid_time_start_unix, Some(1_700_000_000));
334 assert_eq!(env.valid_time_end_unix, Some(1_800_000_000));
335 }
336
337 #[test]
338 fn evaluate_state_expired_beats_trusted() {
339 let mut cred = sample_cred();
340 cred.expires_at_unix = Some(1_000);
341 let trusted = vec!["did:wf:issuer".to_string()];
342 assert_eq!(
344 evaluate_state(&cred, &trusted, 2_000),
345 VerificationState::Expired
346 );
347 }
348
349 #[test]
350 fn evaluate_state_issuer_trusted_when_not_expired() {
351 let mut cred = sample_cred();
352 cred.expires_at_unix = Some(4_000_000_000);
354 let trusted = vec!["did:wf:issuer".to_string()];
355 assert_eq!(
356 evaluate_state(&cred, &trusted, 1_700_000_000),
357 VerificationState::IssuerTrusted
358 );
359 }
360
361 #[test]
362 fn evaluate_state_schema_valid_when_untrusted_issuer_has_claims() {
363 let cred = sample_cred(); assert_eq!(
365 evaluate_state(&cred, &[], 1_700_000_000),
366 VerificationState::SchemaValid
367 );
368 }
369
370 #[test]
371 fn evaluate_state_unverified_when_no_claims_and_untrusted() {
372 let cred = CredentialRecord::new("did:wf:issuer", "did:wf:subject", "Empty", 1_700_000_000);
373 assert_eq!(
374 evaluate_state(&cred, &[], 1_700_000_000),
375 VerificationState::Unverified
376 );
377 }
378
379 #[test]
380 fn evaluate_state_revoked_is_sticky() {
381 let mut cred = sample_cred();
382 cred.verification_state = VerificationState::Revoked;
383 let trusted = vec!["did:wf:issuer".to_string()];
384 assert_eq!(
386 evaluate_state(&cred, &trusted, 1_700_000_000),
387 VerificationState::Revoked
388 );
389 }
390
391 #[test]
392 fn build_presentation_returns_only_selected_claims() {
393 let cred = sample_cred();
394 let selected = vec!["full_name".to_string(), "postcode".to_string()];
395 let pres = build_presentation(&cred, &selected);
396
397 assert_eq!(pres.disclosed_claims.len(), 2);
399 assert_eq!(pres.disclosed_claims[0].0, "full_name");
400 assert_eq!(pres.disclosed_claims[1].0, "postcode");
401
402 assert!(!pres.disclosed_claims.iter().any(|(k, _)| k == "street"));
404 let json = presentation_summary(&pres);
405 assert!(!json.contains("street"));
406 assert!(!json.contains("1 Camper Lane"));
407
408 assert_eq!(pres.credential_id, cred.id);
410 assert_eq!(pres.issuer_did, "did:wf:issuer");
411 assert!(json.contains("field_selection_not_zk"));
413 }
414
415 #[test]
416 fn build_presentation_ignores_unknown_selected_keys() {
417 let cred = sample_cred();
418 let selected = vec!["full_name".to_string(), "does_not_exist".to_string()];
419 let pres = build_presentation(&cred, &selected);
420 assert_eq!(pres.disclosed_claims.len(), 1);
421 assert_eq!(pres.disclosed_claims[0].0, "full_name");
422 }
423
424 #[test]
425 fn build_presentation_empty_selection_discloses_nothing() {
426 let cred = sample_cred();
427 let pres = build_presentation(&cred, &[]);
428 assert!(pres.disclosed_claims.is_empty());
429 }
430
431 #[test]
432 fn credential_summary_includes_primary_fields() {
433 let cred = sample_cred();
434 let summary = credential_summary(&cred);
435 assert!(summary.contains("ProofOfAddress"));
436 assert!(summary.contains("did:wf:issuer"));
437 assert!(summary.contains("\"claim_count\":3"));
439 }
440}