OXYGENHUB
# 5d695d869fbf spectra / crates / spectra-core / src / ledger.rs
20.7 KiB · Rust · last changed Identities instead of tokens: init, owned agents as delegates, verified replay of identities, request authentication, one writer (#4) 2 days ago source blame history raw
1
//! The ledger (spec §9, §9.5): the append-only, hash-chained event log in
2
//! SQLite, its checkpoints signed by the instance key, its verification,
3
//! and the bus that tells everything else what was appended.
4
//!
5
//! One writer at a time (a lock around the chain head and SQLite's own),
6
//! so `seq` is gap-free and every `prev` is the hash of the event before.
7
//! Readers never wait for it (WAL).
8
9
use crate::event::{canonical_json, Auth, Event, Method, NewEvent};
10
use crate::hlc::{Clock, Hlc};
11
use crate::keys::KeyPair;
12
use crate::{ids, projections};
13
use anyhow::{bail, Context, Result};
14
use oxy_core::hash::KeyId;
15
use oxy_core::identity::{Identity, Signature};
16
use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteRow, SqliteSynchronous};
17
use sqlx::{Row, SqlitePool};
18
use std::path::Path;
19
use std::sync::Arc;
20
use tokio::sync::{broadcast, Mutex};
21
22
/// Events between checkpoints (spec §9.5).
23
pub const CHECKPOINT_EVERY: u64 = 256;
24
/// The longest a written event waits for a checkpoint (spec §9.5).
25
pub const CHECKPOINT_INTERVAL_MS: u64 = 10 * 60 * 1000;
26
27
const CHECKPOINT_DOMAIN: &[u8] = b"spectra1 checkpoint ";
28
29
/// The ledger: the database, the chain head, the clock and the bus.
30
pub struct Ledger {
31
    pool: SqlitePool,
32
    /// Held for as long as this ledger may append: one writer per data
33
    /// directory, so the chain never forks (`None` when opened read-only).
34
    _lock: Option<std::fs::File>,
35
    head: Mutex<Head>,
36
    clock: Clock,
37
    bus: broadcast::Sender<Arc<Event>>,
38
    instance: Option<KeyPair>,
39
}
40
41
#[derive(Clone, Copy, Debug)]
42
struct Head {
43
    seq: u64,
44
    hash: [u8; 32],
45
    since_checkpoint: u64,
46
    oldest_unchecked_ms: Option<u64>,
47
}
48
49
impl Ledger {
50
    /// Open (or create) `path`, apply migrations, and refuse a ledger
51
    /// written by a newer format. Checkpoints are signed with `instance`;
52
    /// without one (tests, read-only tools) none are made.
53
    pub async fn open(path: &Path, instance: Option<KeyPair>) -> Result<Ledger> {
54
        let lock_path = path.with_extension("lock");
55
        let lock = std::fs::OpenOptions::new()
56
            .create(true)
57
            .truncate(false)
58
            .write(true)
59
            .open(&lock_path)
60
            .with_context(|| format!("opening {}", lock_path.display()))?;
61
        match lock.try_lock() {
62
            Ok(()) => {}
63
            Err(std::fs::TryLockError::WouldBlock) => {
64
                bail!("another process is writing to {} (is `spectra serve` running? stop it, or do this through it)", path.display())
65
            }
66
            Err(std::fs::TryLockError::Error(e)) => return Err(e).with_context(|| format!("locking {}", lock_path.display())),
67
        }
68
        let mut l = Ledger::open_unlocked(path, instance).await?;
69
        l._lock = Some(lock);
70
        Ok(l)
71
    }
72
73
    /// Open for reading and verifying only, while another process may be
74
    /// writing: no lock, and `append` must not be called.
75
    pub async fn open_read_only(path: &Path) -> Result<Ledger> {
76
        Ledger::open_unlocked(path, None).await
77
    }
78
79
    async fn open_unlocked(path: &Path, instance: Option<KeyPair>) -> Result<Ledger> {
80
        let opts = SqliteConnectOptions::new()
81
            .filename(path)
82
            .create_if_missing(true)
83
            .journal_mode(SqliteJournalMode::Wal)
84
            .synchronous(SqliteSynchronous::Normal)
85
            .foreign_keys(true)
86
            .busy_timeout(std::time::Duration::from_secs(10));
87
        let pool =
88
            SqlitePoolOptions::new().max_connections(8).connect_with(opts).await.with_context(|| format!("opening {}", path.display()))?;
89
        sqlx::migrate!("./migrations").run(&pool).await.context("applying migrations")?;
90
        let format: Option<String> = sqlx::query_scalar("SELECT value FROM meta WHERE key = 'ledger_format'").fetch_optional(&pool).await?;
91
        match format.as_deref().map(str::parse::<u32>) {
92
            None => {
93
                sqlx::query("INSERT INTO meta (key, value) VALUES ('ledger_format', ?)")
94
                    .bind(crate::LEDGER_FORMAT.to_string())
95
                    .execute(&pool)
96
                    .await?;
97
            }
98
            Some(Ok(f)) if f <= crate::LEDGER_FORMAT => {}
99
            Some(_) => {
100
                bail!("{} was written by a newer Spectra (ledger format {}): upgrade spectra", path.display(), format.unwrap_or_default())
101
            }
102
        }
103
        let last =
104
            sqlx::query("SELECT seq, hash, hlc_wall, hlc_logical FROM events ORDER BY seq DESC LIMIT 1").fetch_optional(&pool).await?;
105
        let (seq, hash, hlc) = match last {
106
            Some(r) => (
107
                r.get::<i64, _>(0) as u64,
108
                to32(r.get::<Vec<u8>, _>(1))?,
109
                Hlc { wall_ms: r.get::<i64, _>(2) as u64, logical: r.get::<i64, _>(3) as u32 },
110
            ),
111
            None => (0, [0; 32], Hlc::default()),
112
        };
113
        let checkpoint_seq: i64 =
114
            sqlx::query_scalar("SELECT COALESCE(MAX(seq), 0) FROM events WHERE kind = 'ledger.checkpoint'").fetch_one(&pool).await?;
115
        let since = seq.saturating_sub(checkpoint_seq as u64);
116
        let (bus, _) = broadcast::channel(4096);
117
        Ok(Ledger {
118
            pool,
119
            _lock: None,
120
            head: Mutex::new(Head { seq, hash, since_checkpoint: since, oldest_unchecked_ms: (since > 0).then(ids::now_ms) }),
121
            clock: Clock::starting_at(hlc),
122
            bus,
123
            instance,
124
        })
125
    }
126
127
    /// The database, for projections' readers.
128
    pub fn pool(&self) -> &SqlitePool {
129
        &self.pool
130
    }
131
132
    /// Every appended event, as it commits.
133
    pub fn subscribe(&self) -> broadcast::Receiver<Arc<Event>> {
134
        self.bus.subscribe()
135
    }
136
137
    /// The instance key, when this ledger signs checkpoints.
138
    pub fn instance(&self) -> Option<&KeyPair> {
139
        self.instance.as_ref()
140
    }
141
142
    /// The newest event's sequence number and hash.
143
    pub async fn head(&self) -> (u64, [u8; 32]) {
144
        let h = self.head.lock().await;
145
        (h.seq, h.hash)
146
    }
147
148
    /// Append `events` in one transaction, chained and projected, then
149
    /// publish them; a checkpoint follows when one is due.
150
    pub async fn append(&self, events: Vec<NewEvent>) -> Result<Vec<Arc<Event>>> {
151
        let mut head = self.head.lock().await;
152
        let mut tx = self.pool.begin().await?;
153
        let mut out = Vec::with_capacity(events.len() + 1);
154
        let mut h = *head;
155
        for n in events {
156
            let e = self.chain(&mut h, n);
157
            insert(&mut tx, &e).await?;
158
            projections::apply(&mut tx, &e).await?;
159
            h.since_checkpoint += 1;
160
            h.oldest_unchecked_ms.get_or_insert(e.at_ms);
161
            out.push(e);
162
            // Every 256 events exactly, even inside a large batch.
163
            if h.since_checkpoint >= CHECKPOINT_EVERY && self.instance.is_some() {
164
                let cp = self.checkpoint_event(&mut h);
165
                insert(&mut tx, &cp).await?;
166
                projections::apply(&mut tx, &cp).await?;
167
                out.push(cp);
168
            }
169
        }
170
        let due = h.oldest_unchecked_ms.is_some_and(|t| ids::now_ms().saturating_sub(t) >= CHECKPOINT_INTERVAL_MS);
171
        if due && self.instance.is_some() {
172
            let cp = self.checkpoint_event(&mut h);
173
            insert(&mut tx, &cp).await?;
174
            projections::apply(&mut tx, &cp).await?;
175
            out.push(cp);
176
        }
177
        tx.commit().await?;
178
        *head = h;
179
        drop(head);
180
        let out: Vec<Arc<Event>> = out.into_iter().map(Arc::new).collect();
181
        for e in &out {
182
            let _ = self.bus.send(e.clone());
183
        }
184
        Ok(out)
185
    }
186
187
    /// Append one event.
188
    pub async fn append_one(&self, e: NewEvent) -> Result<Arc<Event>> {
189
        Ok(self.append(vec![e]).await?.remove(0))
190
    }
191
192
    /// Write a checkpoint now if any event is not covered by one (at
193
    /// shutdown, and from the ten-minute timer).
194
    pub async fn checkpoint(&self) -> Result<Option<Arc<Event>>> {
195
        let Some(_) = &self.instance else { return Ok(None) };
196
        let mut head = self.head.lock().await;
197
        if head.since_checkpoint == 0 {
198
            return Ok(None);
199
        }
200
        let mut h = *head;
201
        let cp = self.checkpoint_event(&mut h);
202
        let mut tx = self.pool.begin().await?;
203
        insert(&mut tx, &cp).await?;
204
        projections::apply(&mut tx, &cp).await?;
205
        tx.commit().await?;
206
        *head = h;
207
        drop(head);
208
        let cp = Arc::new(cp);
209
        let _ = self.bus.send(cp.clone());
210
        Ok(Some(cp))
211
    }
212
213
    fn chain(&self, h: &mut Head, n: NewEvent) -> Event {
214
        let at_ms = ids::now_ms();
215
        let mut e = Event {
216
            seq: h.seq + 1,
217
            id: ids::ulid(),
218
            at_ms,
219
            hlc: self.clock.tick(at_ms),
220
            prev: h.hash,
221
            hash: [0; 32],
222
            auth: n.auth,
223
            kind: n.kind,
224
            actor: n.actor,
225
            session: n.session,
226
            project: n.project,
227
            subject: n.subject,
228
            payload: Some(canonical_json(&n.payload)),
229
            trace: n.trace,
230
        };
231
        e.hash = e.computed_hash();
232
        h.seq = e.seq;
233
        h.hash = e.hash;
234
        e
235
    }
236
237
    /// A checkpoint naming the head `h` holds, signed by the instance key
238
    /// over `"spectra1 checkpoint " || hash || seq` (spec §9.5).
239
    fn checkpoint_event(&self, h: &mut Head) -> Event {
240
        let instance = self.instance.as_ref().expect("checked by callers");
241
        let (seq, hash, count) = (h.seq, h.hash, h.since_checkpoint);
242
        let sig = instance.sign(&checkpoint_message(seq, &hash));
243
        let n = NewEvent::system("ledger.checkpoint", serde_json::json!({ "seq": seq, "hash": hex::encode(hash), "count": count })).by(
244
            "system",
245
            Auth {
246
                key: Some(instance.key.0),
247
                method: Method::Signature,
248
                assurance: 2,
249
                proof: Some(oxy_core::cbor::encode(&sig.to_value())),
250
            },
251
        );
252
        let e = self.chain(h, n);
253
        h.since_checkpoint = 0;
254
        h.oldest_unchecked_ms = None;
255
        e
256
    }
257
258
    /// Events from `from` (inclusive), oldest first, at most `limit`.
259
    pub async fn events(&self, from: u64, limit: u32) -> Result<Vec<Event>> {
260
        let rows = sqlx::query(&format!("{SELECT_EVENT} WHERE seq >= ? ORDER BY seq LIMIT ?"))
261
            .bind(from as i64)
262
            .bind(limit as i64)
263
            .fetch_all(&self.pool)
264
            .await?;
265
        rows.iter().map(row_to_event).collect()
266
    }
267
268
    /// Events of the given kinds from `from` (inclusive), oldest first.
269
    pub async fn events_of_kinds(&self, from: u64, kinds: &[&str], limit: u32) -> Result<Vec<Event>> {
270
        let marks = vec!["?"; kinds.len()].join(",");
271
        let sql = format!("{SELECT_EVENT} WHERE seq >= ? AND kind IN ({marks}) ORDER BY seq LIMIT ?");
272
        let mut q = sqlx::query(&sql).bind(from as i64);
273
        for k in kinds {
274
            q = q.bind(*k);
275
        }
276
        let rows = q.bind(limit as i64).fetch_all(&self.pool).await?;
277
        rows.iter().map(row_to_event).collect()
278
    }
279
280
    /// Recompute the chain and check every checkpoint and every proof it
281
    /// can, from the ledger alone (spec §9.5, `spectra admin verify`).
282
    pub async fn verify(&self, keys: &mut dyn KeyResolver) -> Result<Verification> {
283
        let mut v = Verification::default();
284
        let mut prev = [0u8; 32];
285
        let mut expect = 1u64;
286
        let mut instance: Option<Identity> = None;
287
        let mut from = 1;
288
        loop {
289
            let batch = self.events(from, 2_000).await?;
290
            if batch.is_empty() {
291
                break;
292
            }
293
            for e in &batch {
294
                v.events += 1;
295
                if e.seq != expect {
296
                    v.finding(e.seq, Problem::Gap, format!("expected event {expect}"));
297
                    expect = e.seq;
298
                }
299
                if e.prev != prev {
300
                    v.finding(e.seq, Problem::ChainBreak, "prev is not the hash of the event before".into());
301
                }
302
                if e.payload.is_some() && e.computed_hash() != e.hash {
303
                    v.finding(e.seq, Problem::HashMismatch, "the event's fields do not give its hash: it was edited".into());
304
                }
305
                if e.kind == "identity.instance" {
306
                    instance = e
307
                        .json()
308
                        .get("identity")
309
                        .and_then(|h| h.as_str())
310
                        .and_then(|h| hex::decode(h).ok())
311
                        .and_then(|b| Identity::decode(&b).ok());
312
                }
313
                if e.kind == "ledger.checkpoint" {
314
                    v.checkpoints += 1;
315
                    match check_checkpoint(e, prev, instance.as_ref()) {
316
                        Ok(()) => v.last_checkpoint = Some(e.seq),
317
                        Err(why) => v.finding(e.seq, Problem::BadCheckpoint, why),
318
                    }
319
                } else if let Err(why) = keys.check(e) {
320
                    v.finding(e.seq, Problem::BadProof, why);
321
                }
322
                prev = e.hash;
323
                expect += 1;
324
            }
325
            from = batch.last().map(|e| e.seq + 1).unwrap_or(from);
326
        }
327
        v.head = prev;
328
        v.uncovered = v.events.saturating_sub(v.last_checkpoint.unwrap_or(0));
329
        Ok(v)
330
    }
331
332
    /// Clear every projection and replay the ledger into them.
333
    pub async fn rebuild(&self) -> Result<()> {
334
        let _head = self.head.lock().await;
335
        let mut tx = self.pool.begin().await?;
336
        replay(&mut tx).await?;
337
        tx.commit().await?;
338
        Ok(())
339
    }
340
341
    /// Whether the projections equal a rebuild from the ledger: rebuild in
342
    /// a transaction, compare, and roll back. Returns the tables that differ.
343
    pub async fn check(&self) -> Result<Vec<String>> {
344
        let _head = self.head.lock().await;
345
        let mut tx = self.pool.begin().await?;
346
        let mut before = Vec::new();
347
        for t in projections::TABLES {
348
            before.push(dump(&mut tx, t).await?);
349
        }
350
        replay(&mut tx).await?;
351
        let mut differ = Vec::new();
352
        for (t, b) in projections::TABLES.iter().zip(before) {
353
            if dump(&mut tx, t).await? != b {
354
                differ.push(t.to_string());
355
            }
356
        }
357
        tx.rollback().await?;
358
        Ok(differ)
359
    }
360
}
361
362
/// `"spectra1 checkpoint " || hash || seq (8 bytes, big-endian)`.
363
pub fn checkpoint_message(seq: u64, hash: &[u8; 32]) -> Vec<u8> {
364
    let mut m = CHECKPOINT_DOMAIN.to_vec();
365
    m.extend_from_slice(hash);
366
    m.extend_from_slice(&seq.to_be_bytes());
367
    m
368
}
369
370
fn check_checkpoint(e: &Event, prev: [u8; 32], instance: Option<&Identity>) -> std::result::Result<(), String> {
371
    let p = e.json();
372
    let seq = p.get("seq").and_then(|s| s.as_u64()).ok_or("no seq")?;
373
    let hash: [u8; 32] =
374
        p.get("hash").and_then(|h| h.as_str()).and_then(|h| hex::decode(h).ok()).and_then(|b| b.try_into().ok()).ok_or("no hash")?;
375
    if seq + 1 != e.seq || hash != prev {
376
        return Err("names a head other than the event before it".into());
377
    }
378
    let instance = instance.ok_or("no instance identity precedes it")?;
379
    if e.auth.key != Some(instance.hash().0) {
380
        return Err("signed by a key other than the instance's".into());
381
    }
382
    let proof = e.auth.proof.as_deref().ok_or("unsigned")?;
383
    let sig = oxy_core::cbor::decode(proof).ok().and_then(|v| Signature::from_value(&v).ok()).ok_or("malformed signature")?;
384
    oxy_core::identity::verify_challenge(instance, &sig, &checkpoint_message(seq, &hash))
385
        .map_err(|e| format!("signature does not verify: {e}"))
386
}
387
388
/// Checks the proof of a signed event: the identities and delegations that
389
/// say whose key it was (spec §8.5). Principals supply it (`principals`).
390
/// It is given every event but checkpoints, in order, so it can follow
391
/// identities as they are recorded.
392
pub trait KeyResolver: Send {
393
    fn check(&mut self, e: &Event) -> std::result::Result<(), String>;
394
}
395
396
/// A resolver that knows no keys: every signed event is reported.
397
pub struct NoKeys;
398
impl KeyResolver for NoKeys {
399
    fn check(&mut self, e: &Event) -> std::result::Result<(), String> {
400
        match e.auth.method {
401
            Method::Signature | Method::Passkey => Err("no identity is known for its key".into()),
402
            _ => Ok(()),
403
        }
404
    }
405
}
406
407
/// What `verify` found.
408
#[derive(Clone, Debug, Default, serde::Serialize)]
409
pub struct Verification {
410
    pub events: u64,
411
    pub checkpoints: u64,
412
    pub last_checkpoint: Option<u64>,
413
    /// Events after the last good checkpoint: chained, not yet signed.
414
    pub uncovered: u64,
415
    #[serde(serialize_with = "ser_hex")]
416
    pub head: [u8; 32],
417
    pub findings: Vec<Finding>,
418
}
419
420
fn ser_hex<S: serde::Serializer>(h: &[u8; 32], s: S) -> std::result::Result<S::Ok, S::Error> {
421
    s.serialize_str(&hex::encode(h))
422
}
423
424
impl Verification {
425
    pub fn clean(&self) -> bool {
426
        self.findings.is_empty()
427
    }
428
    fn finding(&mut self, seq: u64, problem: Problem, detail: String) {
429
        self.findings.push(Finding { seq, problem, detail });
430
    }
431
}
432
433
/// One thing wrong with the ledger.
434
#[derive(Clone, Debug, serde::Serialize)]
435
pub struct Finding {
436
    pub seq: u64,
437
    pub problem: Problem,
438
    pub detail: String,
439
}
440
441
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
442
#[serde(rename_all = "snake_case")]
443
pub enum Problem {
444
    Gap,
445
    ChainBreak,
446
    HashMismatch,
447
    BadCheckpoint,
448
    BadProof,
449
}
450
451
const SELECT_EVENT: &str = "SELECT seq, id, at_ms, hlc_wall, hlc_logical, prev, hash, auth_key, auth_method, auth_assurance, auth_proof, kind, actor, session, project, subject, payload, trace FROM events";
452
453
async fn insert(conn: &mut sqlx::SqliteConnection, e: &Event) -> sqlx::Result<()> {
454
    sqlx::query(
455
        "INSERT INTO events (seq, id, at_ms, hlc_wall, hlc_logical, prev, hash, auth_key, auth_method, auth_assurance, auth_proof, kind, actor, session, project, subject, payload, trace) \
456
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
457
    )
458
    .bind(e.seq as i64)
459
    .bind(&e.id)
460
    .bind(e.at_ms as i64)
461
    .bind(e.hlc.wall_ms as i64)
462
    .bind(e.hlc.logical as i64)
463
    .bind(e.prev.to_vec())
464
    .bind(e.hash.to_vec())
465
    .bind(e.auth.key.map(|k| k.to_vec()))
466
    .bind(e.auth.method as i64)
467
    .bind(e.auth.assurance as i64)
468
    .bind(e.auth.proof.clone())
469
    .bind(&e.kind)
470
    .bind(&e.actor)
471
    .bind(&e.session)
472
    .bind(&e.project)
473
    .bind(&e.subject)
474
    .bind(e.payload.clone())
475
    .bind(&e.trace)
476
    .execute(conn)
477
    .await?;
478
    Ok(())
479
}
480
481
fn row_to_event(r: &SqliteRow) -> Result<Event> {
482
    Ok(Event {
483
        seq: r.get::<i64, _>(0) as u64,
484
        id: r.get(1),
485
        at_ms: r.get::<i64, _>(2) as u64,
486
        hlc: Hlc { wall_ms: r.get::<i64, _>(3) as u64, logical: r.get::<i64, _>(4) as u32 },
487
        prev: to32(r.get(5))?,
488
        hash: to32(r.get(6))?,
489
        auth: Auth {
490
            key: r.get::<Option<Vec<u8>>, _>(7).map(to32).transpose()?,
491
            method: Method::from_u8(r.get::<i64, _>(8) as u8).context("unknown auth method")?,
492
            assurance: r.get::<i64, _>(9) as u8,
493
            proof: r.get(10),
494
        },
495
        kind: r.get(11),
496
        actor: r.get(12),
497
        session: r.get(13),
498
        project: r.get(14),
499
        subject: r.get(15),
500
        payload: r.get(16),
501
        trace: r.get(17),
502
    })
503
}
504
505
fn to32(v: Vec<u8>) -> Result<[u8; 32]> {
506
    v.try_into().map_err(|_| anyhow::anyhow!("a stored hash is not 32 bytes"))
507
}
508
509
async fn replay(conn: &mut sqlx::SqliteConnection) -> Result<()> {
510
    for t in projections::TABLES {
511
        sqlx::query(&format!("DELETE FROM {t}")).execute(&mut *conn).await?;
512
    }
513
    let mut from = 1i64;
514
    loop {
515
        let rows = sqlx::query(&format!("{SELECT_EVENT} WHERE seq >= ? ORDER BY seq LIMIT 2000")).bind(from).fetch_all(&mut *conn).await?;
516
        if rows.is_empty() {
517
            break;
518
        }
519
        for r in &rows {
520
            let e = row_to_event(r)?;
521
            projections::apply(conn, &e).await?;
522
            from = e.seq as i64 + 1;
523
        }
524
    }
525
    Ok(())
526
}
527
528
async fn dump(conn: &mut sqlx::SqliteConnection, table: &str) -> Result<Vec<String>> {
529
    // Every column as text, rows in a fixed order: enough to compare.
530
    let rows = sqlx::query(&format!("SELECT * FROM {table} ORDER BY 1, 2")).fetch_all(&mut *conn).await?;
531
    Ok(rows
532
        .iter()
533
        .map(|r| {
534
            (0..r.columns().len())
535
                .map(|i| match r.try_get::<Option<String>, _>(i) {
536
                    Ok(v) => format!("{v:?}"),
537
                    Err(_) => match r.try_get::<Option<i64>, _>(i) {
538
                        Ok(n) => format!("{n:?}"),
539
                        Err(_) => format!("{:?}", r.try_get::<Option<Vec<u8>>, _>(i).ok().flatten()),
540
                    },
541
                })
542
                .collect::<Vec<_>>()
543
                .join("|")
544
        })
545
        .collect())
546
}
547
548
/// The identity of `key` among `identities`, by KeyId.
549
pub fn find_identity<'a>(identities: &'a [Identity], key: &KeyId) -> Option<&'a Identity> {
550
    identities.iter().find(|i| &i.hash() == key)
551
}