walletkit-core 0.18.0

Reference implementation for the World ID Protocol. Core functionality to use a World ID.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
//! Pre-flight check of whether the credential store can satisfy a proof request.
//!
//! # Overview
//!
//! [`crate::proof_request_credential_constraints_check::check_credentials_against_proof_request`]
//! evaluates every request item in a proof request against the contents of the local
//! [`crate::storage::CredentialStore`] and returns a
//! [`crate::proof_request_credential_constraints_check::CredentialConstraintsCheckResult`] describing:
//!
//! - **`is_satisfied`** — whether the overall request (including any constraint
//!   expression) can be fulfilled with the credentials currently in the store.
//! - **`check_results`** — one
//!   [`crate::proof_request_credential_constraints_check::CredentialConstraintsCheckItem`] per request item,
//!   always populated regardless of `is_satisfied`, so the caller can identify
//!   exactly which credentials are present or missing.
//!
//! # Per-item evaluation
//!
//! For each request item the check verifies that the store contains at least one
//! credential that is:
//!
//! 1. **Not expired** — `expires_at > now`.
//! 2. **Fresh enough** — `genesis_issued_at >= genesis_issued_at_min` (defaults to 0
//!    when the request item omits the field, meaning any issuance time is accepted).
//! 3. **Long-lived enough** — `expires_at > expires_at_min` (defaults to the proof
//!    request's `created_at` when the request item omits the field).
//!
//! Multiple credentials with the same `issuer_schema_id` can exist in the store.
//! The item is considered satisfied if **any** of them passes all three checks,
//! which matches proof-generation behaviour (it selects the most recently updated
//! qualifying credential).
//!
//! # Constraint expressions
//!
//! When the proof request carries a constraint expression (`Any`, `All`, or
//! `Enumerate`), `is_satisfied` reflects whether the expression evaluates to `true`
//! given the per-item results. The expression is validated for structural limits
//! (max depth 2, max `MAX_CONSTRAINT_NODES` nodes) before evaluation; violations
//! are returned as errors rather than `is_satisfied = false`.
//!
//! When there is no constraint expression every request item must be satisfied.
//!
//! # UI usage
//!
//! `check_results` is intended for the UI layer. When `is_satisfied` is `false`,
//! iterate `check_results` and surface items where `has_credential` is `false` to
//! tell the user which credentials are missing or do not meet the request's time
//! constraints.
//!
//! # Examples
//!
//! The table below shows how constraints, available credentials, and per-item
//! results combine. ✓ = `has_credential: true`, ✗ = `has_credential: false`.
//!
//! | Request items         | Constraints                      | Credentials in store  | `is_satisfied` | `check_results`                    |
//! |-----------------------|----------------------------------|-----------------------|----------------|------------------------------------|
//! | orb, mnc              | _(none)_                         | orb, mnc              | `true`         | orb ✓, mnc ✓                       |
//! | orb, mnc              | _(none)_                         | orb only              | `false`        | orb ✓, mnc ✗                       |
//! | orb, mnc              | _(none)_                         | mnc only              | `false`        | orb ✗, mnc ✓                       |
//! | orb, mnc              | `Any(orb, mnc)`                  | orb only              | `true`         | orb ✓, mnc ✗                       |
//! | orb, mnc              | `Any(orb, mnc)`                  | mnc only              | `true`         | orb ✗, mnc ✓                       |
//! | orb, mnc              | `Any(orb, mnc)`                  | _(none)_              | `false`        | orb ✗, mnc ✗                       |
//! | orb, mnc              | `All(orb, mnc)`                  | orb only              | `false`        | orb ✓, mnc ✗                       |
//! | orb, mnc              | `All(orb, mnc)`                  | mnc only              | `false`        | orb ✗, mnc ✓                       |
//! | orb, mnc, passport    | `All(orb, Any(mnc, passport))`   | orb, mnc              | `true`         | orb ✓, mnc ✓, passport ✗          |
//! | orb, mnc, passport    | `All(orb, Any(mnc, passport))`   | orb, passport         | `true`         | orb ✓, mnc ✗, passport ✓          |
//! | orb, mnc, passport    | `All(orb, Any(mnc, passport))`   | mnc, passport         | `false`        | orb ✗, mnc ✓, passport ✓          |
//! | orb, mnc, passport    | `All(passport, Any(orb, mnc))`   | passport, mnc         | `true`         | orb ✗, mnc ✓, passport ✓          |
//! | orb, mnc, passport    | `All(passport, Any(orb, mnc))`   | orb only              | `false`        | orb ✓, mnc ✗, passport ✗          |

use std::collections::HashMap;

use world_id_core::requests::MAX_CONSTRAINT_NODES;

use crate::requests::ProofRequest;
use crate::storage::{CredentialRecord, CredentialStore, StorageError};

/// Error returned by [`check_credentials_against_proof_request`].
#[derive(Debug, thiserror::Error, uniffi::Error)]
pub enum CredentialConstraintsCheckError {
    /// Credential store query failed.
    #[error(transparent)]
    Storage(#[from] StorageError),
    /// The constraint expression exceeds the maximum nesting depth of 2.
    #[error("constraint nesting exceeds maximum allowed depth")]
    ConstraintTooDeep,
    /// The constraint expression exceeds the maximum node count.
    #[error("constraints exceed maximum allowed size")]
    ConstraintTooLarge,
}

/// Check result for a single request item.
#[derive(Debug, Clone, uniffi::Record)]
pub struct CredentialConstraintsCheckItem {
    /// The RP-defined identifier for this request item (e.g. `"orb"`, `"document"`).
    pub identifier: String,
    /// Issuer schema ID required by this item.
    pub issuer_schema_id: u64,
    /// `true` when the store contains at least one non-expired credential that meets
    /// all time constraints (`genesis_issued_at_min`, `expires_at_min`) for this item.
    pub has_credential: bool,
}

/// Result of [`check_credentials_against_proof_request`].
#[derive(Debug, Clone, uniffi::Record)]
pub struct CredentialConstraintsCheckResult {
    /// `true` when the constraint tree (or all items, if no constraints) is satisfied.
    pub is_satisfied: bool,
    /// One entry per request item in the proof request, in the same order.
    ///
    /// Always populated regardless of `is_satisfied`. When `is_satisfied` is `false`,
    /// items with `has_credential = false` identify what is missing or does not meet
    /// the request's time constraints.
    pub check_results: Vec<CredentialConstraintsCheckItem>,
}

/// Checks whether `store` holds the credentials required to fulfill `request`.
///
/// See the [module-level documentation](self) for a full description of the
/// evaluation logic and intended usage.
///
/// # Errors
///
/// - [`CredentialConstraintsCheckError::Storage`] if the credential store query fails.
/// - [`CredentialConstraintsCheckError::ConstraintTooDeep`] if the constraint tree exceeds depth 2.
/// - [`CredentialConstraintsCheckError::ConstraintTooLarge`] if the constraint tree exceeds the node limit.
#[uniffi::export]
pub fn check_credentials_against_proof_request(
    request: &ProofRequest,
    store: &CredentialStore,
    now: u64,
) -> Result<CredentialConstraintsCheckResult, CredentialConstraintsCheckError> {
    let records = store.list_credentials(None, now)?;

    let mut by_schema: HashMap<u64, Vec<&CredentialRecord>> = HashMap::new();
    for r in records.iter().filter(|r| !r.is_expired) {
        by_schema.entry(r.issuer_schema_id).or_default().push(r);
    }

    let mut check_results: Vec<CredentialConstraintsCheckItem> = Vec::new();
    for item in &request.0.requests {
        let expires_min = item.expires_at_min.unwrap_or(request.0.created_at);
        let genesis_min = item.genesis_issued_at_min.unwrap_or(0);

        let has_credential =
            by_schema.get(&item.issuer_schema_id).is_some_and(|creds| {
                creds.iter().any(|r| {
                    r.expires_at > expires_min && r.genesis_issued_at >= genesis_min
                })
            });

        check_results.push(CredentialConstraintsCheckItem {
            identifier: item.identifier.clone(),
            issuer_schema_id: item.issuer_schema_id,
            has_credential,
        });
    }

    let is_satisfied = match &request.0.constraints {
        None => check_results.iter().all(|i| i.has_credential),
        Some(expr) => {
            // TODO: replace with `request.0.validate_constraints()?` once
            // walletkit bumps world-id-core to 0.11.x.
            if !expr.validate_max_depth(2) {
                return Err(CredentialConstraintsCheckError::ConstraintTooDeep);
            }
            if !expr.validate_max_nodes(MAX_CONSTRAINT_NODES) {
                return Err(CredentialConstraintsCheckError::ConstraintTooLarge);
            }
            expr.evaluate(&|id: &str| {
                check_results
                    .iter()
                    .any(|i| i.identifier == id && i.has_credential)
            })
        }
    };

    Ok(CredentialConstraintsCheckResult {
        is_satisfied,
        check_results,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    use alloy_core::primitives::{Signature, U160};
    use taceo_oprf::types::OprfKeyId;
    use world_id_core::{
        primitives::rp::RpId,
        requests::{
            ConstraintExpr, ConstraintNode, ProofRequest as CoreProofRequest,
            RequestItem, RequestVersion,
        },
        FieldElement as CoreFieldElement,
    };

    use crate::{
        storage::tests_utils::{
            cleanup_test_storage, temp_root_path, InMemoryStorageProvider,
        },
        Credential, FieldElement,
    };
    use world_id_core::Credential as CoreCredential;

    fn dummy_request(
        items: Vec<RequestItem>,
        constraints: Option<ConstraintExpr<'static>>,
    ) -> ProofRequest {
        let core = CoreProofRequest {
            id: "test".to_string(),
            version: RequestVersion::V1,
            created_at: 0,
            expires_at: u64::MAX,
            rp_id: RpId::new(1),
            oprf_key_id: OprfKeyId::new(U160::from(1u64)),
            session_id: None,
            action: None,
            signature: Signature::test_signature(),
            nonce: CoreFieldElement::ZERO,
            requests: items,
            constraints,
        };
        ProofRequest(core)
    }

    fn store_with_credentials(
        issuer_ids: &[u64],
        now: u64,
    ) -> (CredentialStore, std::path::PathBuf) {
        let root = temp_root_path();
        let provider = InMemoryStorageProvider::new(&root);
        let store = CredentialStore::from_provider(&provider).expect("create store");
        store.init(42, now).expect("init");

        for &id in issuer_ids {
            let cred: Credential = CoreCredential::new()
                .issuer_schema_id(id)
                .genesis_issued_at(now)
                .into();
            store
                .store_credential(
                    &cred,
                    &FieldElement::from(1u64),
                    now + 9999,
                    None,
                    now,
                )
                .expect("store credential");
        }
        (store, root)
    }

    #[test]
    fn no_constraints_all_satisfied() {
        let now = 1000;
        let (store, root) = store_with_credentials(&[100, 200], now);
        let request = dummy_request(
            vec![
                RequestItem::new("a".into(), 100, None, None, None),
                RequestItem::new("b".into(), 200, None, None, None),
            ],
            None,
        );
        let result =
            check_credentials_against_proof_request(&request, &store, now).unwrap();
        assert!(result.is_satisfied);
        assert!(result.check_results.iter().all(|i| i.has_credential));
        cleanup_test_storage(&root);
    }

    #[test]
    fn no_constraints_one_missing() {
        let now = 1000;
        let (store, root) = store_with_credentials(&[100], now);
        let request = dummy_request(
            vec![
                RequestItem::new("a".into(), 100, None, None, None),
                RequestItem::new("b".into(), 999, None, None, None),
            ],
            None,
        );
        let result =
            check_credentials_against_proof_request(&request, &store, now).unwrap();
        assert!(!result.is_satisfied);
        assert!(result.check_results[0].has_credential);
        assert!(!result.check_results[1].has_credential);
        assert_eq!(result.check_results[1].identifier, "b");
        assert_eq!(result.check_results[1].issuer_schema_id, 999);
        cleanup_test_storage(&root);
    }

    #[test]
    fn expired_credential_not_counted() {
        let now = 5000;
        let root = temp_root_path();
        let provider = InMemoryStorageProvider::new(&root);
        let store = CredentialStore::from_provider(&provider).expect("create store");
        store.init(42, 1000).expect("init");

        let cred: Credential = CoreCredential::new()
            .issuer_schema_id(100)
            .genesis_issued_at(1000)
            .into();
        store
            .store_credential(&cred, &FieldElement::from(1u64), 2000, None, 1000)
            .expect("store");

        let request = dummy_request(
            vec![RequestItem::new("a".into(), 100, None, None, None)],
            None,
        );

        let result =
            check_credentials_against_proof_request(&request, &store, now).unwrap();
        assert!(!result.is_satisfied);
        assert!(!result.check_results[0].has_credential);
        cleanup_test_storage(&root);
    }

    #[test]
    fn any_constraint_one_branch_satisfied() {
        let now = 1000;
        let (store, root) = store_with_credentials(&[100], now);
        let request = dummy_request(
            vec![
                RequestItem::new("a".into(), 100, None, None, None),
                RequestItem::new("b".into(), 999, None, None, None),
            ],
            Some(ConstraintExpr::Any {
                any: vec![
                    ConstraintNode::Type("a".into()),
                    ConstraintNode::Type("b".into()),
                ],
            }),
        );
        assert!(
            check_credentials_against_proof_request(&request, &store, now)
                .unwrap()
                .is_satisfied
        );
        cleanup_test_storage(&root);
    }

    #[test]
    fn all_constraint_one_branch_missing() {
        let now = 1000;
        let (store, root) = store_with_credentials(&[100], now);
        let request = dummy_request(
            vec![
                RequestItem::new("a".into(), 100, None, None, None),
                RequestItem::new("b".into(), 999, None, None, None),
            ],
            Some(ConstraintExpr::All {
                all: vec![
                    ConstraintNode::Type("a".into()),
                    ConstraintNode::Type("b".into()),
                ],
            }),
        );
        let result =
            check_credentials_against_proof_request(&request, &store, now).unwrap();
        assert!(!result.is_satisfied);
        assert!(result.check_results[0].has_credential);
        assert!(!result.check_results[1].has_credential);
        cleanup_test_storage(&root);
    }

    #[test]
    fn enumerate_constraint_any_branch_satisfies() {
        let now = 1000;
        let (store, root) = store_with_credentials(&[200], now);
        let request = dummy_request(
            vec![
                RequestItem::new("a".into(), 999, None, None, None),
                RequestItem::new("b".into(), 200, None, None, None),
            ],
            Some(ConstraintExpr::Enumerate {
                enumerate: vec![
                    ConstraintNode::Type("a".into()),
                    ConstraintNode::Type("b".into()),
                ],
            }),
        );
        assert!(
            check_credentials_against_proof_request(&request, &store, now)
                .unwrap()
                .is_satisfied
        );
        cleanup_test_storage(&root);
    }

    #[test]
    fn enumerate_constraint_none_available() {
        let now = 1000;
        let (store, root) = store_with_credentials(&[], now);
        let request = dummy_request(
            vec![
                RequestItem::new("a".into(), 100, None, None, None),
                RequestItem::new("b".into(), 200, None, None, None),
            ],
            Some(ConstraintExpr::Enumerate {
                enumerate: vec![
                    ConstraintNode::Type("a".into()),
                    ConstraintNode::Type("b".into()),
                ],
            }),
        );
        assert!(
            !check_credentials_against_proof_request(&request, &store, now)
                .unwrap()
                .is_satisfied
        );
        cleanup_test_storage(&root);
    }

    // -----------------------------------------------------------------------
    // Table cases: A or B or C / A and (B or C)
    // -----------------------------------------------------------------------

    fn three_item_request(constraints: ConstraintExpr<'static>) -> ProofRequest {
        dummy_request(
            vec![
                RequestItem::new("a".into(), 100, None, None, None),
                RequestItem::new("b".into(), 200, None, None, None),
                RequestItem::new("c".into(), 300, None, None, None),
            ],
            Some(constraints),
        )
    }

    fn any_a_or_b_or_c() -> ConstraintExpr<'static> {
        ConstraintExpr::Any {
            any: vec![
                ConstraintNode::Type("a".into()),
                ConstraintNode::Type("b".into()),
                ConstraintNode::Type("c".into()),
            ],
        }
    }

    fn all_a_and_b_or_c() -> ConstraintExpr<'static> {
        ConstraintExpr::All {
            all: vec![
                ConstraintNode::Type("a".into()),
                ConstraintNode::Expr(ConstraintExpr::Any {
                    any: vec![
                        ConstraintNode::Type("b".into()),
                        ConstraintNode::Type("c".into()),
                    ],
                }),
            ],
        }
    }

    // A or B or C — only A present → True
    #[test]
    fn any_abc_only_a_satisfies() {
        let now = 1000;
        let (store, root) = store_with_credentials(&[100], now);
        let result = check_credentials_against_proof_request(
            &three_item_request(any_a_or_b_or_c()),
            &store,
            now,
        )
        .unwrap();
        assert!(result.is_satisfied);
        assert!(
            result
                .check_results
                .iter()
                .find(|i| i.identifier == "a")
                .unwrap()
                .has_credential
        );
        assert!(
            !result
                .check_results
                .iter()
                .find(|i| i.identifier == "b")
                .unwrap()
                .has_credential
        );
        assert!(
            !result
                .check_results
                .iter()
                .find(|i| i.identifier == "c")
                .unwrap()
                .has_credential
        );
        cleanup_test_storage(&root);
    }

    // A or B or C — only B present → True
    #[test]
    fn any_abc_only_b_satisfies() {
        let now = 1000;
        let (store, root) = store_with_credentials(&[200], now);
        let result = check_credentials_against_proof_request(
            &three_item_request(any_a_or_b_or_c()),
            &store,
            now,
        )
        .unwrap();
        assert!(result.is_satisfied);
        assert!(
            !result
                .check_results
                .iter()
                .find(|i| i.identifier == "a")
                .unwrap()
                .has_credential
        );
        assert!(
            result
                .check_results
                .iter()
                .find(|i| i.identifier == "b")
                .unwrap()
                .has_credential
        );
        assert!(
            !result
                .check_results
                .iter()
                .find(|i| i.identifier == "c")
                .unwrap()
                .has_credential
        );
        cleanup_test_storage(&root);
    }

    // A or B or C — none present → False
    #[test]
    fn any_abc_none_present() {
        let now = 1000;
        let (store, root) = store_with_credentials(&[], now);
        let result = check_credentials_against_proof_request(
            &three_item_request(any_a_or_b_or_c()),
            &store,
            now,
        )
        .unwrap();
        assert!(!result.is_satisfied);
        assert!(result.check_results.iter().all(|i| !i.has_credential));
        cleanup_test_storage(&root);
    }

    // A and (B or C) — none present → False
    #[test]
    fn all_a_any_bc_none_present() {
        let now = 1000;
        let (store, root) = store_with_credentials(&[], now);
        let result = check_credentials_against_proof_request(
            &three_item_request(all_a_and_b_or_c()),
            &store,
            now,
        )
        .unwrap();
        assert!(!result.is_satisfied);
        cleanup_test_storage(&root);
    }

    // A and (B or C) — A, B, C all present → True (A satisfies A; B satisfies B or C)
    #[test]
    fn all_a_any_bc_all_present() {
        let now = 1000;
        let (store, root) = store_with_credentials(&[100, 200, 300], now);
        let result = check_credentials_against_proof_request(
            &three_item_request(all_a_and_b_or_c()),
            &store,
            now,
        )
        .unwrap();
        assert!(result.is_satisfied);
        assert!(result.check_results.iter().all(|i| i.has_credential));
        cleanup_test_storage(&root);
    }

    #[test]
    fn constraint_too_deep_returns_error() {
        let now = 1000;
        let (store, root) = store_with_credentials(&[100], now);
        let deep = ConstraintExpr::All {
            all: vec![ConstraintNode::Expr(ConstraintExpr::Any {
                any: vec![ConstraintNode::Expr(ConstraintExpr::All {
                    all: vec![ConstraintNode::Type("a".into())],
                })],
            })],
        };
        let request = dummy_request(
            vec![RequestItem::new("a".into(), 100, None, None, None)],
            Some(deep),
        );
        let err =
            check_credentials_against_proof_request(&request, &store, now).unwrap_err();
        assert!(matches!(
            err,
            CredentialConstraintsCheckError::ConstraintTooDeep
        ));
        cleanup_test_storage(&root);
    }

    #[test]
    fn constraint_too_large_returns_error() {
        use world_id_core::requests::MAX_CONSTRAINT_NODES;
        let now = 1000;
        let (store, root) = store_with_credentials(&[], now);
        // Build a flat Any with MAX_CONSTRAINT_NODES + 1 leaves to exceed the limit.
        let nodes: Vec<ConstraintNode<'static>> = (0..=MAX_CONSTRAINT_NODES)
            .map(|i| ConstraintNode::Type(format!("t{i}").into()))
            .collect();
        let expr = ConstraintExpr::Any { any: nodes };
        let items: Vec<RequestItem> = (0..=MAX_CONSTRAINT_NODES)
            .map(|i| RequestItem::new(format!("t{i}"), i as u64, None, None, None))
            .collect();
        let request = dummy_request(items, Some(expr));
        let err =
            check_credentials_against_proof_request(&request, &store, now).unwrap_err();
        assert!(matches!(
            err,
            CredentialConstraintsCheckError::ConstraintTooLarge
        ));
        cleanup_test_storage(&root);
    }

    fn store_with_credential_times(
        issuer_id: u64,
        genesis_issued_at: u64,
        expires_at: u64,
        now: u64,
    ) -> (CredentialStore, std::path::PathBuf) {
        let root = temp_root_path();
        let provider = InMemoryStorageProvider::new(&root);
        let store = CredentialStore::from_provider(&provider).expect("create store");
        store.init(42, now).expect("init");
        let cred: Credential = CoreCredential::new()
            .issuer_schema_id(issuer_id)
            .genesis_issued_at(genesis_issued_at)
            .into();
        store
            .store_credential(&cred, &FieldElement::from(1u64), expires_at, None, now)
            .expect("store credential");
        (store, root)
    }

    #[test]
    fn genesis_issued_at_min_not_met_returns_unsatisfied() {
        let now = 1000;
        // Credential was issued at t=500; request requires t>=600.
        let (store, root) = store_with_credential_times(100, 500, now + 9999, now);
        let request = dummy_request(
            vec![RequestItem::new("a".into(), 100, None, Some(600), None)],
            None,
        );
        let result =
            check_credentials_against_proof_request(&request, &store, now).unwrap();
        assert!(!result.is_satisfied);
        assert!(!result.check_results[0].has_credential);
        cleanup_test_storage(&root);
    }

    #[test]
    fn expires_at_min_not_met_returns_unsatisfied() {
        let now = 1000;
        // Credential expires at t=2000; request requires expires_at >= 5000.
        let (store, root) = store_with_credential_times(100, now, 2000, now);
        let request = dummy_request(
            vec![RequestItem::new("a".into(), 100, None, None, Some(5000))],
            None,
        );
        let result =
            check_credentials_against_proof_request(&request, &store, now).unwrap();
        assert!(!result.is_satisfied);
        assert!(!result.check_results[0].has_credential);
        cleanup_test_storage(&root);
    }

    #[test]
    fn expires_at_min_equal_to_expires_at_returns_unsatisfied() {
        let now = 1000;
        // Boundary: expires_at == expires_at_min is rejected by the circuit (strict >).
        let (store, root) = store_with_credential_times(100, now, 5000, now);
        let request = dummy_request(
            vec![RequestItem::new("a".into(), 100, None, None, Some(5000))],
            None,
        );
        let result =
            check_credentials_against_proof_request(&request, &store, now).unwrap();
        assert!(!result.is_satisfied);
        assert!(!result.check_results[0].has_credential);
        cleanup_test_storage(&root);
    }
}