auths-core 0.1.1

Core cryptography and keychain integration for Auths
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
//! Duplicity detection for KERI witness infrastructure.
//!
//! This module implements the "first-seen-always-seen" policy that is central
//! to KERI's duplicity detection mechanism. When a witness observes an event
//! for the first time, it records the event's SAID. Any subsequent event with
//! the same (prefix, sequence) but different SAID indicates duplicity.
//!
//! # First-Seen-Always-Seen Policy
//!
//! The policy is simple but powerful:
//!
//! 1. First time seeing (prefix, seq) → record the SAID
//! 2. Same (prefix, seq) with same SAID → OK (idempotent)
//! 3. Same (prefix, seq) with different SAID → **DUPLICITY**
//!
//! This works because KERI sequence numbers are monotonic and each sequence
//! number should map to exactly one event SAID.

use std::collections::HashMap;

use auths_keri::{Prefix, Said};

use super::error::{DuplicityEvidence, WitnessReport};
#[cfg(test)]
use super::receipt::ReceiptTag;
use super::receipt::{Receipt, StoredReceipt};

/// Duplicity detector implementing first-seen-always-seen policy.
///
/// This detector maintains an in-memory map of (prefix, seq) → SAID.
/// It can detect when a controller presents different events with the
/// same sequence number to different witnesses (split-view attack).
///
/// # Thread Safety
///
/// This type is NOT thread-safe. For concurrent use, wrap in a `Mutex`
/// or `RwLock`.
///
/// # Example
///
/// ```rust
/// use auths_core::witness::DuplicityDetector;
/// use auths_keri::{Prefix, Said};
///
/// let mut detector = DuplicityDetector::new();
/// let prefix = Prefix::new_unchecked("EPrefix".into());
/// let said_a = Said::new_unchecked("ESAID_A".into());
/// let said_b = Said::new_unchecked("ESAID_B".into());
///
/// // First event at seq 0
/// assert!(detector.check_event(&prefix, 0, &said_a).is_none());
///
/// // Same event again (idempotent)
/// assert!(detector.check_event(&prefix, 0, &said_a).is_none());
///
/// // Different event at same seq → DUPLICITY!
/// let evidence = detector.check_event(&prefix, 0, &said_b);
/// assert!(evidence.is_some());
/// ```
#[derive(Debug, Clone, Default)]
pub struct DuplicityDetector {
    /// Map of (prefix, seq) → first-seen SAID
    first_seen: HashMap<(String, u128), String>,
}

impl DuplicityDetector {
    /// Create a new empty detector.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a detector with pre-populated state.
    ///
    /// This is useful for restoring state from persistent storage.
    pub fn with_state(first_seen: HashMap<(String, u128), String>) -> Self {
        Self { first_seen }
    }

    /// Check an event for duplicity.
    ///
    /// Implements the first-seen-always-seen policy:
    /// - First time: records SAID, returns None
    /// - Same SAID: returns None (idempotent)
    /// - Different SAID: returns Some(evidence)
    ///
    /// # Arguments
    ///
    /// * `prefix` - The KERI prefix of the identity
    /// * `seq` - The sequence number of the event
    /// * `said` - The SAID (Self-Addressing IDentifier) of the event
    ///
    /// # Returns
    ///
    /// * `None` - No duplicity detected
    /// * `Some(evidence)` - Duplicity detected with evidence
    pub fn check_event(
        &mut self,
        prefix: &Prefix,
        seq: u128,
        said: &Said,
    ) -> Option<DuplicityEvidence> {
        let key = (prefix.as_str().to_string(), seq);

        match self.first_seen.get(&key) {
            None => {
                // First time seeing this (prefix, seq)
                self.first_seen.insert(key, said.as_str().to_string());
                None
            }
            Some(existing_said) => {
                if existing_said == said.as_str() {
                    // Same event (idempotent)
                    None
                } else {
                    // DUPLICITY: different SAID for same (prefix, seq)
                    Some(DuplicityEvidence {
                        prefix: prefix.clone(),
                        sequence: seq,
                        event_a_said: Said::new_unchecked(existing_said.clone()),
                        event_b_said: said.clone(),
                        witness_reports: vec![],
                    })
                }
            }
        }
    }

    /// Check if a specific (prefix, seq) has been seen.
    pub fn has_seen(&self, prefix: &Prefix, seq: u128) -> bool {
        self.first_seen
            .contains_key(&(prefix.as_str().to_string(), seq))
    }

    /// Get the SAID for a (prefix, seq) if seen.
    pub fn get_said(&self, prefix: &Prefix, seq: u128) -> Option<Said> {
        self.first_seen
            .get(&(prefix.as_str().to_string(), seq))
            .map(|s| Said::new_unchecked(s.clone()))
    }

    /// Verify that a set of receipts are consistent (same event SAID).
    ///
    /// This checks that all receipts are for the same event. If receipts
    /// have different `d` (event SAID) fields, this indicates duplicity.
    ///
    /// # Arguments
    ///
    /// * `receipts` - The receipts to verify
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All receipts are consistent
    /// * `Err(evidence)` - Inconsistent receipts indicate duplicity
    pub fn verify_receipts(&self, receipts: &[Receipt]) -> Result<(), DuplicityEvidence> {
        if receipts.is_empty() {
            return Ok(());
        }

        let first = &receipts[0];
        let expected_said = &first.d;

        for receipt in receipts.iter().skip(1) {
            if receipt.d != *expected_said {
                // Different receipts claim different SAIDs
                return Err(DuplicityEvidence {
                    prefix: Prefix::default(),
                    sequence: first.s.value(),
                    event_a_said: expected_said.clone(),
                    event_b_said: receipt.d.clone(),
                    witness_reports: receipts
                        .iter()
                        .map(|r| WitnessReport {
                            witness_id: r.i.as_str().to_string(),
                            observed_said: r.d.clone(),
                            observed_at: None,
                        })
                        .collect(),
                });
            }
        }

        Ok(())
    }

    /// Get the current state for persistence.
    pub fn state(&self) -> &HashMap<(String, u128), String> {
        &self.first_seen
    }

    /// Clear all recorded state.
    pub fn clear(&mut self) {
        self.first_seen.clear();
    }

    /// Get the number of events tracked.
    pub fn len(&self) -> usize {
        self.first_seen.len()
    }

    /// Check if the detector is empty.
    pub fn is_empty(&self) -> bool {
        self.first_seen.is_empty()
    }
}

/// Detect conflicting witness receipts: two stored receipts attesting **different**
/// event SAIDs for the same controller event.
///
/// Unlike [`DuplicityDetector::verify_receipts`] (which keys on the receipt body's
/// controller `i`), this keys provenance on the real **witness AID**
/// ([`StoredReceipt::witness`]), so the resulting [`DuplicityEvidence::witness_reports`]
/// names *which witnesses* disagree. A conflict is irreconcilable — the controller
/// equivocated and at least one witness receipted a fork.
///
/// Args:
/// * `receipts`: The stored receipts collected for one controller event.
///
/// Returns `Some(evidence)` with populated `witness_reports` on a SAID conflict,
/// or `None` when every receipt attests the same SAID.
///
/// Usage:
/// ```ignore
/// if let Some(evidence) = detect_receipt_conflict(&stored) {
///     refuse_trust(evidence);
/// }
/// ```
pub fn detect_receipt_conflict(receipts: &[StoredReceipt]) -> Option<DuplicityEvidence> {
    let first = receipts.first()?;
    let expected_said = &first.signed.receipt.d;

    let conflict = receipts
        .iter()
        .find(|r| r.signed.receipt.d != *expected_said)?;

    Some(DuplicityEvidence {
        prefix: first.signed.receipt.i.clone(),
        sequence: first.signed.receipt.s.value(),
        event_a_said: expected_said.clone(),
        event_b_said: conflict.signed.receipt.d.clone(),
        witness_reports: receipts
            .iter()
            .map(|r| WitnessReport {
                witness_id: r.witness.as_str().to_string(),
                observed_said: r.signed.receipt.d.clone(),
                observed_at: None,
            })
            .collect(),
    })
}

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

    fn prefix(s: &str) -> Prefix {
        Prefix::new_unchecked(s.into())
    }

    fn said(s: &str) -> Said {
        Said::new_unchecked(s.into())
    }

    fn stored_receipt(witness: &str, event_said: &str) -> StoredReceipt {
        use crate::witness::SignedReceipt;
        use auths_keri::{KeriSequence, VersionString};
        StoredReceipt {
            signed: SignedReceipt {
                receipt: Receipt {
                    v: VersionString::placeholder(),
                    t: ReceiptTag,
                    d: said(event_said),
                    i: prefix("EController"),
                    s: KeriSequence::new(0),
                },
                signature: vec![],
            },
            witness: prefix(witness),
        }
    }

    #[test]
    fn conflicting_witness_receipts_irreconcilable() {
        // Two witnesses receipt different SAIDs for the same controller event.
        let receipts = vec![
            stored_receipt("BWit1", "ESAID_A"),
            stored_receipt("BWit2", "ESAID_B"),
        ];
        let evidence = detect_receipt_conflict(&receipts).expect("conflict must be detected");
        assert_eq!(evidence.event_a_said, said("ESAID_A"));
        assert_eq!(evidence.event_b_said, said("ESAID_B"));
        // witness_reports names the real witness AIDs, not the controller `i`.
        assert_eq!(evidence.witness_reports.len(), 2);
        let ids: Vec<&str> = evidence
            .witness_reports
            .iter()
            .map(|w| w.witness_id.as_str())
            .collect();
        assert!(ids.contains(&"BWit1") && ids.contains(&"BWit2"));
    }

    #[test]
    fn agreeing_witness_receipts_no_conflict() {
        let receipts = vec![
            stored_receipt("BWit1", "ESAID_A"),
            stored_receipt("BWit2", "ESAID_A"),
        ];
        assert!(detect_receipt_conflict(&receipts).is_none());
    }

    #[test]
    fn first_seen_records_said() {
        let mut detector = DuplicityDetector::new();
        let p = prefix("EPrefix");

        // First event
        let result = detector.check_event(&p, 0, &said("ESAID_A"));
        assert!(result.is_none());

        // Verify it was recorded
        assert!(detector.has_seen(&p, 0));
        assert_eq!(detector.get_said(&p, 0), Some(said("ESAID_A")));
    }

    #[test]
    fn same_said_is_idempotent() {
        let mut detector = DuplicityDetector::new();
        let p = prefix("EPrefix");

        // First event
        detector.check_event(&p, 0, &said("ESAID_A"));

        // Same event again
        let result = detector.check_event(&p, 0, &said("ESAID_A"));
        assert!(result.is_none());
    }

    #[test]
    fn different_said_is_duplicity() {
        let mut detector = DuplicityDetector::new();
        let p = prefix("EPrefix");

        // First event
        detector.check_event(&p, 0, &said("ESAID_A"));

        // Different SAID at same seq
        let result = detector.check_event(&p, 0, &said("ESAID_B"));
        assert!(result.is_some());

        let evidence = result.unwrap();
        assert_eq!(evidence.prefix, "EPrefix");
        assert_eq!(evidence.sequence, 0);
        assert_eq!(evidence.event_a_said, "ESAID_A");
        assert_eq!(evidence.event_b_said, "ESAID_B");
    }

    #[test]
    fn different_seq_is_ok() {
        let mut detector = DuplicityDetector::new();
        let p = prefix("EPrefix");

        // Events at different sequences
        assert!(detector.check_event(&p, 0, &said("ESAID_A")).is_none());
        assert!(detector.check_event(&p, 1, &said("ESAID_B")).is_none());
        assert!(detector.check_event(&p, 2, &said("ESAID_C")).is_none());
    }

    #[test]
    fn different_prefix_is_ok() {
        let mut detector = DuplicityDetector::new();

        // Same seq but different prefixes
        assert!(
            detector
                .check_event(&prefix("EPrefix1"), 0, &said("ESAID_A"))
                .is_none()
        );
        assert!(
            detector
                .check_event(&prefix("EPrefix2"), 0, &said("ESAID_B"))
                .is_none()
        );
    }

    #[test]
    fn verify_receipts_consistent() {
        use auths_keri::{KeriSequence, VersionString};
        let detector = DuplicityDetector::new();

        let receipts = vec![
            Receipt {
                v: VersionString::placeholder(),
                t: ReceiptTag,
                d: Said::new_unchecked("EEVENT_SAID".into()),
                i: Prefix::new_unchecked("W1".into()),
                s: KeriSequence::new(5),
            },
            Receipt {
                v: VersionString::placeholder(),
                t: ReceiptTag,
                d: Said::new_unchecked("EEVENT_SAID".into()),
                i: Prefix::new_unchecked("W2".into()),
                s: KeriSequence::new(5),
            },
        ];

        assert!(detector.verify_receipts(&receipts).is_ok());
    }

    #[test]
    fn verify_receipts_inconsistent() {
        use auths_keri::{KeriSequence, VersionString};
        let detector = DuplicityDetector::new();

        let receipts = vec![
            Receipt {
                v: VersionString::placeholder(),
                t: ReceiptTag,
                d: Said::new_unchecked("ESAID_A".into()),
                i: Prefix::new_unchecked("W1".into()),
                s: KeriSequence::new(5),
            },
            Receipt {
                v: VersionString::placeholder(),
                t: ReceiptTag,
                d: Said::new_unchecked("ESAID_B".into()),
                i: Prefix::new_unchecked("W2".into()),
                s: KeriSequence::new(5),
            },
        ];

        let result = detector.verify_receipts(&receipts);
        assert!(result.is_err());

        let evidence = result.unwrap_err();
        assert_eq!(evidence.event_a_said, "ESAID_A");
        assert_eq!(evidence.event_b_said, "ESAID_B");
        assert_eq!(evidence.witness_reports.len(), 2);
    }

    #[test]
    fn verify_receipts_empty() {
        let detector = DuplicityDetector::new();
        assert!(detector.verify_receipts(&[]).is_ok());
    }

    #[test]
    fn with_state_restores() {
        let mut state = HashMap::new();
        state.insert(("EPrefix".to_string(), 0), "ESAID_A".to_string());
        state.insert(("EPrefix".to_string(), 1), "ESAID_B".to_string());

        let detector = DuplicityDetector::with_state(state);
        let p = prefix("EPrefix");

        assert!(detector.has_seen(&p, 0));
        assert!(detector.has_seen(&p, 1));
        assert!(!detector.has_seen(&p, 2));
    }

    #[test]
    fn len_and_is_empty() {
        let mut detector = DuplicityDetector::new();
        assert!(detector.is_empty());
        assert_eq!(detector.len(), 0);

        detector.check_event(&prefix("E1"), 0, &said("ES1"));
        detector.check_event(&prefix("E2"), 0, &said("ES2"));

        assert!(!detector.is_empty());
        assert_eq!(detector.len(), 2);

        detector.clear();
        assert!(detector.is_empty());
    }
}