walletkit-core 0.27.2

Reference implementation for the World ID Protocol. Core functionality to use a World ID.
Documentation
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
use std::collections::BTreeSet;

use crate::storage::error::{StorageError, StorageResult};
use crate::storage::types::{
    ActivityEntry, ActivityMetadata, ActivityOutcome, ActivityQuery, ProtocolVersion,
};
use crate::storage::ActivityFailureReason;
use walletkit_sqlite::{params, Connection, Row, StepResult, Value};

use super::util::{map_db_err, to_i64, to_u64};

pub(super) fn record(
    conn: &Connection,
    entry: &ActivityEntry,
    now: u64,
) -> StorageResult<u64> {
    match (entry.outcome, entry.failure_reason) {
        (ActivityOutcome::Failed, None) => {
            return Err(StorageError::ActivityInvalidRecord(
                "failure_reason must be present when outcome is Failed".to_string(),
            ));
        }
        (outcome, Some(_)) if outcome != ActivityOutcome::Failed => {
            return Err(StorageError::ActivityInvalidRecord(
                "failure_reason must be absent unless outcome is Failed".to_string(),
            ));
        }
        _ => {}
    }

    let now_i64 = to_i64(now, "now")?;
    let tx = conn
        .transaction_immediate()
        .map_err(|err| map_db_err(&err))?;

    let entry_id = tx
        .query_row(
            "INSERT INTO activity_entries (
                client_id, protocol, created_at,
                outcome, rp_id, app_identifier, failure_reason
            ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
            RETURNING entry_id",
            params![
                entry.client_id.as_str(),
                entry.protocol.as_i64(),
                now_i64,
                entry.outcome.to_string(),
                entry.rp_id.cast_signed(),
                entry.app_identifier.as_str(),
                entry
                    .failure_reason
                    .map(|v| v.to_string())
                    .unwrap_or_default(),
            ],
            |stmt| Ok(stmt.column_i64(0)),
        )
        .map_err(|err| map_db_err(&err))?;

    for issuer_schema_id in &entry.issuer_schema_ids {
        tx.execute(
            "INSERT OR IGNORE INTO activity_issuer_schema_ids (entry_id, issuer_schema_id)
             VALUES (?1, ?2)",
            params![entry_id, issuer_schema_id.cast_signed()],
        )
        .map_err(|err| map_db_err(&err))?;
    }

    tx.commit().map_err(|err| map_db_err(&err))?;

    to_u64(entry_id, "entry_id")
}

/// Lists activity entries, most recent first.
pub(super) fn list(
    conn: &Connection,
    query: &ActivityQuery,
    limit: u32,
    offset: u32,
) -> StorageResult<Vec<ActivityEntry>> {
    let limit_i64 = i64::from(limit);
    let offset_i64 = i64::from(offset);
    let issuer_schema_ids = query
        .issuer_schema_ids
        .as_ref()
        .map(encode_issuer_schema_ids);

    let sql = if issuer_schema_ids.is_some() {
        format!(
            "{SELECT_ACTIVITY_ENTRIES}
             WHERE e.entry_id IN (
                 SELECT entry_id FROM activity_issuer_schema_ids
                 WHERE issuer_schema_id IN (SELECT value FROM json_each(?1))
             )
             ORDER BY e.created_at DESC, e.entry_id DESC
             LIMIT ?2 OFFSET ?3"
        )
    } else {
        format!(
            "{SELECT_ACTIVITY_ENTRIES}
             ORDER BY e.created_at DESC, e.entry_id DESC
             LIMIT ?1 OFFSET ?2"
        )
    };

    let mut entries = Vec::new();

    let mut stmt = conn.prepare(&sql).map_err(|err| map_db_err(&err))?;

    if let Some(issuer_schema_ids) = issuer_schema_ids {
        stmt.bind_values(params![issuer_schema_ids, limit_i64, offset_i64])
            .map_err(|err| map_db_err(&err))?;
    } else {
        stmt.bind_values(params![limit_i64, offset_i64])
            .map_err(|err| map_db_err(&err))?;
    }

    while let StepResult::Row(row) = stmt.step().map_err(|err| map_db_err(&err))? {
        entries.push(map_entry(&row)?);
    }

    Ok(entries)
}

/// Returns aggregate activity metadata.
pub(super) fn metadata(conn: &Connection) -> StorageResult<ActivityMetadata> {
    let total_count = conn
        .query_row("SELECT COUNT(*) FROM activity_entries", &[], |stmt| {
            Ok(stmt.column_i64(0))
        })
        .map_err(|err| map_db_err(&err))?;

    Ok(ActivityMetadata {
        total_count: to_u64(total_count, "total_count")?,
    })
}

/// Deletes the provided `entry_ids` and returns the count of the deleted entries.
pub(super) fn delete(conn: &Connection, entry_ids: &[u64]) -> StorageResult<u64> {
    if entry_ids.is_empty() {
        return Ok(0);
    }

    let values = entry_ids
        .iter()
        .copied()
        .map(|id| to_i64(id, "entry_id").map(Value::Integer))
        .collect::<StorageResult<Vec<_>>>()?;

    let tx = conn
        .transaction_immediate()
        .map_err(|err| map_db_err(&err))?;

    let mut deleted = 0;
    for batch in values.chunks(MAX_IDS_PER_DELETE) {
        let placeholders = vec!["?"; batch.len()].join(", ");
        let sql =
            format!("DELETE FROM activity_entries WHERE entry_id IN ({placeholders})");

        deleted += tx.execute(&sql, batch).map_err(|err| map_db_err(&err))?;
    }

    tx.commit().map_err(|err| map_db_err(&err))?;

    Ok(deleted as u64)
}

pub(super) fn clear(conn: &Connection) -> StorageResult<u64> {
    let deleted = conn
        .execute("DELETE FROM activity_entries", &[])
        .map_err(|err| map_db_err(&err))?;

    Ok(deleted as u64)
}

const MAX_IDS_PER_DELETE: usize = 1000;

/// The columns of an activity entry, with its issuer schema ids reassembled in
/// a normalized order.
const SELECT_ACTIVITY_ENTRIES: &str =
    "SELECT e.entry_id, e.client_id, e.protocol, e.created_at, e.outcome,
            e.rp_id, e.app_identifier, e.failure_reason,
            (SELECT GROUP_CONCAT(s.issuer_schema_id)
             FROM activity_issuer_schema_ids s
             WHERE s.entry_id = e.entry_id)
     FROM activity_entries e";

fn encode_issuer_schema_ids(issuer_schema_ids: &BTreeSet<u64>) -> String {
    let ids = issuer_schema_ids
        .iter()
        .map(|id| id.cast_signed().to_string())
        .collect::<Vec<_>>()
        .join(",");
    format!("[{ids}]")
}

/// Parses the reassembled issuer schema ids.
///
/// The ids are a set: the result is sorted ascending and duplicates are
/// dropped.
fn decode_issuer_schema_ids(joined: &str) -> StorageResult<Vec<u64>> {
    if joined.is_empty() {
        return Ok(Vec::new());
    }

    let mut ids = joined
        .split(',')
        .map(|value| {
            value.parse::<i64>().map(i64::cast_unsigned).map_err(|_| {
                StorageError::ActivityDb(format!("invalid issuer_schema_id: {value}"))
            })
        })
        .collect::<StorageResult<Vec<_>>>()?;

    ids.sort_unstable();
    ids.dedup();
    Ok(ids)
}

fn map_entry(row: &Row<'_, '_>) -> StorageResult<ActivityEntry> {
    let id = to_u64(row.column_i64(0), "entry_id")?;
    let client_id = row.column_text(1);
    let protocol = ProtocolVersion::try_from(row.column_i64(2))?;
    let timestamp = to_u64(row.column_i64(3), "created_at")?;
    let outcome_text = row.column_text(4);
    let outcome: ActivityOutcome = outcome_text.parse().map_err(|_| {
        StorageError::ActivityDb(format!("invalid outcome: {outcome_text}"))
    })?;
    let rp_id = row.column_i64(5).cast_unsigned();
    let app_identifier = row.column_text(6);
    let failure_reason_text = row.column_text(7);
    let issuer_schema_ids = decode_issuer_schema_ids(&row.column_text(8))?;

    let failure_reason = if failure_reason_text.is_empty() {
        None
    } else {
        Some(
            failure_reason_text
                .parse::<ActivityFailureReason>()
                .map_err(|_| {
                    StorageError::ActivityDb("invalid failure_reason in db".to_string())
                })?,
        )
    };

    Ok(ActivityEntry {
        id: Some(id),
        client_id,
        protocol,
        timestamp: Some(timestamp),
        outcome,
        rp_id,
        app_identifier,
        issuer_schema_ids,
        failure_reason,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::cache::CacheDb;
    use secrecy::SecretBox;
    use std::collections::HashSet;
    use std::fs;
    use std::path::{Path, PathBuf};
    use uuid::Uuid;

    fn temp_cache_path() -> PathBuf {
        let mut path = std::env::temp_dir();
        path.push(format!(
            "walletkit-cache-activity-{}.sqlite",
            Uuid::new_v4()
        ));
        path
    }

    fn cleanup_cache_files(path: &Path) {
        let _ = fs::remove_file(path);
        let _ = fs::remove_file(path.with_extension("sqlite-wal"));
        let _ = fs::remove_file(path.with_extension("sqlite-shm"));
    }

    fn sample_entry() -> ActivityEntry {
        ActivityEntry {
            id: None,
            rp_id: 1,
            app_identifier: "app_test".to_string(),
            client_id: "request-uuid-1".to_string(),
            protocol: ProtocolVersion::V3,
            timestamp: None,
            issuer_schema_ids: vec![10],
            outcome: ActivityOutcome::Completed,
            failure_reason: None,
        }
    }

    #[test]
    fn test_record_and_list_activity() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x42u8; 32]);
        let db = CacheDb::new(&path, &key).expect("create cache");

        let entry_id = db
            .record_activity(&sample_entry(), 1000)
            .expect("record activity");

        let entries = db
            .list_activities(&ActivityQuery::new(), 10, 0)
            .expect("list activities");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].id, Some(entry_id));
        assert_eq!(entries[0].outcome, ActivityOutcome::Completed);
        assert_eq!(entries[0].issuer_schema_ids.len(), 1);

        cleanup_cache_files(&path);
    }

    #[test]
    fn test_clear_activities_removes_issuer_schema_associations() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x08u8; 32]);
        let db = CacheDb::new(&path, &key).expect("create cache");

        db.record_activity(&sample_entry(), 1000)
            .expect("record activity");
        db.clear_activities().expect("clear activities");
        drop(db);

        let conn = walletkit_sqlite::cipher::open_encrypted(&path, &key)
            .expect("open raw connection");
        let associations = conn
            .query_row(
                "SELECT COUNT(*) FROM activity_issuer_schema_ids",
                &[],
                |stmt| Ok(stmt.column_i64(0)),
            )
            .expect("count associations");
        drop(conn);

        assert_eq!(
            associations, 0,
            "clearing activity must cascade to issuer-schema associations"
        );

        cleanup_cache_files(&path);
    }

    #[test]
    fn test_list_activities_filters_by_issuer_schema_id() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x04u8; 32]);
        let db = CacheDb::new(&path, &key).expect("create cache");

        let with_schemas = |ids: Vec<u64>| ActivityEntry {
            issuer_schema_ids: ids,
            ..sample_entry()
        };

        db.record_activity(&with_schemas(vec![10]), 1000)
            .expect("record");
        db.record_activity(&with_schemas(vec![20]), 1001)
            .expect("record");
        db.record_activity(&with_schemas(vec![10, 20]), 1002)
            .expect("record");
        db.record_activity(&with_schemas(vec![]), 1003)
            .expect("record");

        let schema_10 = db
            .list_activities(
                &ActivityQuery::new().with_issuer_schema_ids(HashSet::from([10])),
                10,
                0,
            )
            .expect("list filtered");
        assert_eq!(schema_10.len(), 2);
        assert!(schema_10.iter().all(|e| e.issuer_schema_ids.contains(&10)));

        let schema_20 = db
            .list_activities(
                &ActivityQuery::new().with_issuer_schema_ids(HashSet::from([20])),
                10,
                0,
            )
            .expect("list filtered");
        assert_eq!(schema_20.len(), 2);

        let schema_30 = db
            .list_activities(
                &ActivityQuery::new().with_issuer_schema_ids(HashSet::from([30])),
                10,
                0,
            )
            .expect("list filtered");
        assert!(schema_30.is_empty());

        let all = db
            .list_activities(&ActivityQuery::new(), 10, 0)
            .expect("list all");
        assert_eq!(all.len(), 4, "an unset filter returns every entry");

        cleanup_cache_files(&path);
    }

    #[test]
    fn test_list_activities_filters_by_multiple_issuer_schema_ids() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x0Bu8; 32]);
        let db = CacheDb::new(&path, &key).expect("create cache");

        let with_schemas = |ids: Vec<u64>| ActivityEntry {
            issuer_schema_ids: ids,
            ..sample_entry()
        };

        let only_10 = db
            .record_activity(&with_schemas(vec![10]), 1000)
            .expect("record");
        let only_20 = db
            .record_activity(&with_schemas(vec![20]), 1001)
            .expect("record");
        let both = db
            .record_activity(&with_schemas(vec![10, 20]), 1002)
            .expect("record");

        db.record_activity(&with_schemas(vec![30]), 1003)
            .expect("record");

        db.record_activity(&with_schemas(vec![]), 1004)
            .expect("record");

        let ids = |entries: Vec<ActivityEntry>| {
            entries.into_iter().map(|e| e.id).collect::<Vec<_>>()
        };

        let filtered = db
            .list_activities(
                &ActivityQuery::new().with_issuer_schema_ids(HashSet::from([20, 10])),
                10,
                0,
            )
            .expect("list filtered");

        assert_eq!(
            ids(filtered),
            vec![Some(both), Some(only_20), Some(only_10)],
            "an entry matching several ids is returned once, most recent first"
        );

        let first_page = db
            .list_activities(
                &ActivityQuery::new().with_issuer_schema_ids(HashSet::from([10, 20])),
                2,
                0,
            )
            .expect("list first page");

        let second_page = db
            .list_activities(
                &ActivityQuery::new().with_issuer_schema_ids(HashSet::from([10, 20])),
                2,
                2,
            )
            .expect("list second page");

        assert_eq!(ids(first_page), vec![Some(both), Some(only_20)]);
        assert_eq!(ids(second_page), vec![Some(only_10)]);

        let none = db
            .list_activities(
                &ActivityQuery::new().with_issuer_schema_ids(HashSet::new()),
                10,
                0,
            )
            .expect("list empty filter");

        assert!(none.is_empty(), "an empty id set matches no entries");

        cleanup_cache_files(&path);
    }

    #[test]
    fn test_issuer_schema_ids_are_a_set() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x0Au8; 32]);
        let db = CacheDb::new(&path, &key).expect("create cache");

        let entry = ActivityEntry {
            issuer_schema_ids: vec![20, 10, 10],
            ..sample_entry()
        };
        db.record_activity(&entry, 1000).expect("record activity");

        let entries = db
            .list_activities(&ActivityQuery::new(), 10, 0)
            .expect("list all");
        assert_eq!(entries[0].issuer_schema_ids, vec![10, 20]);

        let filtered = db
            .list_activities(
                &ActivityQuery::new().with_issuer_schema_ids(HashSet::from([10])),
                10,
                0,
            )
            .expect("list filtered");
        assert_eq!(filtered.len(), 1);

        cleanup_cache_files(&path);
    }

    #[test]
    fn test_issuer_schema_id_above_i64_max_round_trips() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x09u8; 32]);
        let db = CacheDb::new(&path, &key).expect("create cache");

        let entry = ActivityEntry {
            issuer_schema_ids: vec![u64::MAX],
            ..sample_entry()
        };
        db.record_activity(&entry, 1000).expect("record activity");

        let entries = db
            .list_activities(
                &ActivityQuery::new().with_issuer_schema_ids(HashSet::from([u64::MAX])),
                10,
                0,
            )
            .expect("list filtered");

        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].issuer_schema_ids, vec![u64::MAX]);

        cleanup_cache_files(&path);
    }

    #[test]
    fn test_record_activity_failed_requires_failure_reason() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x02u8; 32]);
        let db = CacheDb::new(&path, &key).expect("create cache");

        let entry = ActivityEntry {
            outcome: ActivityOutcome::Failed,
            failure_reason: None,
            ..sample_entry()
        };

        let err = db
            .record_activity(&entry, 1000)
            .expect_err("Failed without failure_reason should be rejected");

        assert!(matches!(err, StorageError::ActivityInvalidRecord(_)));

        cleanup_cache_files(&path);
    }

    #[test]
    fn test_record_activity_rejects_failure_reason_without_failed_outcome() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x03u8; 32]);
        let db = CacheDb::new(&path, &key).expect("create cache");

        let entry = ActivityEntry {
            outcome: ActivityOutcome::Completed,
            failure_reason: Some(ActivityFailureReason::NetworkError),
            ..sample_entry()
        };

        let err = db
            .record_activity(&entry, 1000)
            .expect_err("failure_reason without Failed outcome should be rejected");

        assert!(matches!(err, StorageError::ActivityInvalidRecord(_)));

        cleanup_cache_files(&path);
    }

    #[test]
    fn test_list_activities_paginates_with_offset() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x05u8; 32]);
        let db = CacheDb::new(&path, &key).expect("create cache");

        for i in 0..5u64 {
            db.record_activity(&sample_entry(), 1000 + i)
                .expect("record activity");
        }

        let page1 = db
            .list_activities(&ActivityQuery::new(), 2, 0)
            .expect("list page 1");
        let page2 = db
            .list_activities(&ActivityQuery::new(), 2, 2)
            .expect("list page 2");
        let page3 = db
            .list_activities(&ActivityQuery::new(), 2, 4)
            .expect("list page 3");

        assert_eq!(page1.len(), 2);
        assert_eq!(page2.len(), 2);
        assert_eq!(page3.len(), 1);

        assert_eq!(page1[0].timestamp, Some(1004));
        assert_eq!(page1[1].timestamp, Some(1003));
        assert_eq!(page2[0].timestamp, Some(1002));
        assert_eq!(page3[0].timestamp, Some(1000));

        cleanup_cache_files(&path);
    }

    #[test]
    fn test_activity_metadata_total_count() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x06u8; 32]);
        let db = CacheDb::new(&path, &key).expect("create cache");

        assert_eq!(db.activity_metadata().expect("metadata").total_count, 0);

        db.record_activity(&sample_entry(), 1000)
            .expect("record activity");
        db.record_activity(&sample_entry(), 1001)
            .expect("record activity");

        assert_eq!(db.activity_metadata().expect("metadata").total_count, 2);

        cleanup_cache_files(&path);
    }

    #[test]
    fn test_activity_delete_empty_ids() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x06u8; 32]);
        let db = CacheDb::new(&path, &key).expect("create cache");

        db.record_activity(&sample_entry(), 1000)
            .expect("record activity");

        assert_eq!(db.delete_activities(&[]).expect("delete activities"), 0);
        assert_eq!(db.activity_metadata().expect("metadata").total_count, 1);

        cleanup_cache_files(&path);
    }

    #[test]
    fn test_delete_activities_removes_only_given_ids() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x0Bu8; 32]);
        let db = CacheDb::new(&path, &key).expect("create cache");

        let first = db
            .record_activity(&sample_entry(), 1000)
            .expect("record activity");
        let second = db
            .record_activity(&sample_entry(), 1001)
            .expect("record activity");
        let third = db
            .record_activity(&sample_entry(), 1002)
            .expect("record activity");
        let deleted = db
            .delete_activities(&[first, third, third + 100])
            .expect("delete activities");

        assert_eq!(deleted, 2, "unknown ids are not counted");

        let remaining = db
            .list_activities(&ActivityQuery::new(), 10, 0)
            .expect("list activities");

        assert_eq!(remaining.len(), 1);
        assert_eq!(remaining[0].id, Some(second));

        cleanup_cache_files(&path);
    }

    #[test]
    fn test_delete_activities_spans_multiple_batches() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x0Eu8; 32]);
        let db = CacheDb::new(&path, &key).expect("create cache");

        let mut entry_ids = (0..=MAX_IDS_PER_DELETE as u64)
            .map(|i| {
                db.record_activity(&sample_entry(), 1000 + i)
                    .expect("record activity")
            })
            .collect::<Vec<_>>();
        let kept = entry_ids.pop().expect("at least one entry");
        let unknown = kept + 1;
        entry_ids.push(unknown);

        let deleted = db.delete_activities(&entry_ids).expect("delete activities");
        assert_eq!(deleted, MAX_IDS_PER_DELETE as u64);

        let remaining = db
            .list_activities(&ActivityQuery::new(), 10, 0)
            .expect("list activities");
        assert_eq!(remaining.len(), 1);
        assert_eq!(remaining[0].id, Some(kept));

        cleanup_cache_files(&path);
    }

    #[test]
    fn test_delete_activities_removes_issuer_schema_associations() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x0Cu8; 32]);
        let db = CacheDb::new(&path, &key).expect("create cache");

        let with_schemas = |ids: Vec<u64>| ActivityEntry {
            issuer_schema_ids: ids,
            ..sample_entry()
        };

        let deleted_id = db
            .record_activity(&with_schemas(vec![10, 20]), 1000)
            .expect("record activity");

        let retained_id = db
            .record_activity(&with_schemas(vec![30]), 1001)
            .expect("record activity");

        db.delete_activities(&[deleted_id])
            .expect("delete activities");

        drop(db);

        let conn = walletkit_sqlite::cipher::open_encrypted(&path, &key)
            .expect("open raw connection");

        let mut stmt = conn
            .prepare(
                "SELECT entry_id, issuer_schema_id FROM activity_issuer_schema_ids",
            )
            .expect("prepare associations query");

        let mut associations = Vec::new();

        while let StepResult::Row(row) = stmt.step().expect("step associations") {
            associations.push((row.column_i64(0), row.column_i64(1)));
        }

        drop(stmt);
        drop(conn);

        assert_eq!(
            associations,
            vec![(
                i64::try_from(retained_id).expect("retained id fits in i64"),
                30
            )],
            "deleting an activity must cascade to only its issuer-schema associations"
        );

        cleanup_cache_files(&path);
    }

    #[test]
    fn test_delete_activities_rejects_id_above_i64_max_without_deleting() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x0Du8; 32]);
        let db = CacheDb::new(&path, &key).expect("create cache");

        let entry_id = db
            .record_activity(&sample_entry(), 1000)
            .expect("record activity");

        let err = db
            .delete_activities(&[entry_id, u64::MAX])
            .expect_err("an id above i64::MAX should be rejected");

        assert!(matches!(err, StorageError::CacheDb(_)));
        assert_eq!(
            db.activity_metadata().expect("metadata").total_count,
            1,
            "a rejected batch must not delete any entries"
        );

        cleanup_cache_files(&path);
    }

    #[test]
    fn test_activity_survives_cache_reopen() {
        let path = temp_cache_path();
        let key = SecretBox::init_with(|| [0x07u8; 32]);
        let db = CacheDb::new(&path, &key).expect("create cache");
        db.record_activity(&sample_entry(), 1000)
            .expect("record activity");
        drop(db);

        let db = CacheDb::new(&path, &key).expect("reopen cache");
        let entries = db
            .list_activities(&ActivityQuery::new(), 10, 0)
            .expect("list after reopen");
        assert_eq!(
            entries.len(),
            1,
            "activity history must survive a cache reopen"
        );

        cleanup_cache_files(&path);
    }
}