auths-id 0.1.2

Multi-device identity and attestation crate 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
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
//! KERI key rotation wrapper.
//!
//! This module provides high-level wrappers around the KERI rotation
//! functionality, handling key storage and passphrase management.
//!
//! Two backends are supported:
//! - [`rotate_keri_identity`]: GitKel-based storage (legacy, per-identity refs)
//! - [`rotate_registry_identity`]: Packed registry storage (single `refs/auths/registry` ref)

use git2::Repository;
use ring::rand::SystemRandom;
use ring::signature::{Ed25519KeyPair, KeyPair};
use std::path::Path;

use auths_crypto::Pkcs8Der;

use crate::error::InitError;
use crate::identity::helpers::load_keypair_from_der_or_seed;
use crate::keri::{
    CesrKey, Event, GitKel, KeriSequence, Prefix, RotEvent, Said, Threshold, VersionString,
    rotate_keys, serialize_for_signing, validate_kel,
};
use std::sync::Arc;

use crate::storage::layout::StorageLayoutConfig;
use crate::storage::registry::RegistryBackend;
use crate::witness_config::WitnessConfig;
use auths_core::crypto::said::{compute_next_commitment, verify_commitment};
use auths_core::crypto::signer::{decrypt_keypair, encrypt_keypair};
use auths_core::signing::PassphraseProvider;
use auths_core::storage::keychain::{IdentityDID, KeyAlias, KeyRole, KeyStorage};
use auths_keri::compute_said;

/// Result of a rotation operation with keychain-specific info.
pub struct RotationKeyInfo {
    /// The sequence number after rotation
    pub sequence: u128,
    /// The new current keypair (PKCS8 DER encoded, zeroed on drop)
    pub new_current_pkcs8: Pkcs8Der,
    /// The new next keypair (PKCS8 DER encoded, zeroed on drop)
    pub new_next_pkcs8: Pkcs8Der,
}

/// Shape of a rotation request: adds, removes, threshold changes.
///
/// A `RotationShape::default()` is a key-set-preserving rotation: same
/// key count and thresholds, only the pre-committed next keys rotate in.
/// Non-default variants drive multi-device topology changes (new device,
/// removed device, threshold change).
#[derive(Debug, Clone, Default)]
pub struct RotationShape {
    /// Curves for newly-added device slots. One fresh keypair is generated
    /// per entry and appended to the new `k` list.
    pub add_devices: Vec<auths_crypto::CurveType>,
    /// Indices into the prior `n` commitment list to exclude from the new
    /// `k` list. Requires CESR indexed-signature support (tracked for a
    /// future pass); current validator rejects asymmetric rotations.
    pub remove_indices: Vec<u32>,
    /// New signing threshold. `None` keeps the prior `kt`.
    pub new_kt: Option<Threshold>,
    /// New next-rotation threshold. `None` keeps the prior `nt`.
    pub new_nt: Option<Threshold>,
}

/// Rotates a KERI identity using the GitKel backend.
///
/// Reads and writes the KEL via per-identity Git refs (`refs/did/keri/{prefix}/kel`).
/// Use [`rotate_registry_identity`] for the packed registry backend.
///
/// # Arguments
/// * `repo_path` - Path to the Git repository containing the KEL.
/// * `current_alias` - Keychain alias for the current signing keypair.
/// * `next_alias` - Keychain alias to store the **new** current keypair under (after rotation).
/// * `passphrase_provider` - Service to get passphrases for key decryption/re-encryption.
/// * `_config` - Storage layout configuration (unused but kept for API compatibility).
/// * `keychain` - Keychain storage implementation.
///
/// # Returns
/// * `Result<RotationKeyInfo>` - Information about the rotation if successful.
#[allow(clippy::too_many_arguments)]
pub fn rotate_keri_identity(
    repo_path: &Path,
    current_alias: &KeyAlias,
    next_alias: &KeyAlias,
    passphrase_provider: &dyn PassphraseProvider,
    _config: &StorageLayoutConfig,
    keychain: &(dyn KeyStorage + Send + Sync),
    witness_config: Option<&WitnessConfig>,
    now: chrono::DateTime<chrono::Utc>,
) -> Result<RotationKeyInfo, InitError> {
    let repo = Repository::open(repo_path)?;

    let (did, _role, _encrypted_current) = keychain.load_key(current_alias)?;

    if keychain.is_hardware_backend() {
        return Err(InitError::InvalidData(
            "Rotation requires a software-backed key; current key is hardware-backed \
             (Secure Enclave). Rotate by initializing a new identity."
                .into(),
        ));
    }

    let prefix = did.as_str().strip_prefix("did:keri:").ok_or_else(|| {
        InitError::InvalidData(format!("Invalid DID format, expected 'did:keri:': {}", did))
    })?;

    let kel = GitKel::new(&repo, prefix);
    let events = kel
        .get_events()
        .map_err(|e| InitError::Keri(e.to_string()))?;
    let state = validate_kel(&events).map_err(|e| InitError::Keri(e.to_string()))?;

    let derived_next_alias = KeyAlias::new_unchecked(format!(
        "{}--next-{}",
        current_alias, state.last_establishment_sequence
    ));

    let (did_check, _role, encrypted_next) = keychain.load_key(&derived_next_alias)?;

    if did != did_check {
        return Err(InitError::InvalidData(format!(
            "DID mismatch for pre-committed key '{}': expected {}, found {}",
            derived_next_alias, did, did_check
        )));
    }

    let next_pass = passphrase_provider.get_passphrase(&format!(
        "Enter passphrase for pre-committed key '{}':",
        derived_next_alias
    ))?;
    let decrypted_next_pkcs8 =
        Pkcs8Der::new(decrypt_keypair(&encrypted_next, &next_pass)?.to_vec());

    let rotation_result = rotate_keys(
        &repo,
        &Prefix::new_unchecked(prefix.to_string()),
        &decrypted_next_pkcs8,
        witness_config,
        now,
    )
    .map_err(|e| InitError::Keri(e.to_string()))?;

    let new_pass = passphrase_provider.get_passphrase(&format!(
        "Create passphrase for new key alias '{}':",
        next_alias
    ))?;
    let confirm_pass =
        passphrase_provider.get_passphrase(&format!("Confirm passphrase for '{}':", next_alias))?;
    if new_pass != confirm_pass {
        return Err(InitError::InvalidData(format!(
            "Passphrases do not match for alias '{}'",
            next_alias
        )));
    }

    let encrypted_new_current = encrypt_keypair(decrypted_next_pkcs8.as_ref(), &new_pass)?;
    keychain.store_key(next_alias, &did, KeyRole::Primary, &encrypted_new_current)?;

    // pass through the curve-tagged PKCS8 blob directly.
    let encrypted_future =
        encrypt_keypair(rotation_result.new_next_keypair_pkcs8.as_ref(), &new_pass)?;

    let future_key_alias =
        KeyAlias::new_unchecked(format!("{}--next-{}", next_alias, rotation_result.sequence));
    keychain.store_key(
        &future_key_alias,
        &did,
        KeyRole::NextRotation,
        &encrypted_future,
    )?;

    let _ = keychain.delete_key(&derived_next_alias);
    log::debug!("Cleaned up pre-committed key: {}", derived_next_alias);

    Ok(RotationKeyInfo {
        sequence: rotation_result.sequence,
        new_current_pkcs8: rotation_result.new_current_keypair_pkcs8,
        new_next_pkcs8: rotation_result.new_next_keypair_pkcs8,
    })
}

/// Rotates a KERI identity using the packed registry backend.
///
/// Reads and writes the KEL via `refs/auths/registry` (packed single-ref storage).
/// Use [`rotate_keri_identity`] for the legacy GitKel backend.
///
/// Args:
/// * `backend` - The registry backend holding the identity KEL.
/// * `current_alias` - Keychain alias for the current signing keypair.
/// * `next_alias` - Keychain alias to store the **new** current keypair under (after rotation).
/// * `passphrase_provider` - Service to get passphrases for key decryption/re-encryption.
/// * `_config` - Storage layout configuration (unused but kept for API compatibility).
/// * `keychain` - Keychain storage implementation.
/// * `witness_config` - Optional witness configuration.
///
/// Usage:
/// ```ignore
/// let info = rotate_registry_identity(Arc::new(my_backend), "current", "next", &provider, &config, &keychain, None)?;
/// ```
#[allow(clippy::too_many_lines)]
pub fn rotate_registry_identity(
    backend: Arc<dyn RegistryBackend + Send + Sync>,
    current_alias: &KeyAlias,
    next_alias: &KeyAlias,
    passphrase_provider: &dyn PassphraseProvider,
    _config: &StorageLayoutConfig,
    keychain: &(dyn KeyStorage + Send + Sync),
    witness_config: Option<&WitnessConfig>,
) -> Result<RotationKeyInfo, InitError> {
    let rng = SystemRandom::new();

    let (did, _role, _encrypted_current) = keychain.load_key(current_alias)?;

    if keychain.is_hardware_backend() {
        return Err(InitError::InvalidData(
            "Rotation requires a software-backed key; current key is hardware-backed \
             (Secure Enclave). Rotate by initializing a new identity."
                .into(),
        ));
    }

    let prefix_str = did.as_str().strip_prefix("did:keri:").ok_or_else(|| {
        InitError::InvalidData(format!("Invalid DID format, expected 'did:keri:': {}", did))
    })?;
    let prefix = Prefix::new_unchecked(prefix_str.to_string());

    let state = backend
        .get_key_state(&prefix)
        .map_err(|e| InitError::Registry(e.to_string()))?;

    let derived_next_alias = KeyAlias::new_unchecked(format!(
        "{}--next-{}",
        current_alias, state.last_establishment_sequence
    ));

    let (did_check, _role, encrypted_next) = keychain.load_key(&derived_next_alias)?;

    if did != did_check {
        return Err(InitError::InvalidData(format!(
            "DID mismatch for pre-committed key '{}': expected {}, found {}",
            derived_next_alias, did, did_check
        )));
    }

    let next_pass = passphrase_provider.get_passphrase(&format!(
        "Enter passphrase for pre-committed key '{}':",
        derived_next_alias
    ))?;
    let decrypted_next_pkcs8 =
        Pkcs8Der::new(decrypt_keypair(&encrypted_next, &next_pass)?.to_vec());

    if !state.can_rotate() {
        return Err(InitError::InvalidData(
            "Identity is abandoned (cannot rotate)".into(),
        ));
    }

    let next_keypair = load_keypair_from_der_or_seed(decrypted_next_pkcs8.as_ref())?;

    #[allow(clippy::expect_used)] // INVARIANT: ring Ed25519 public key is always 32 bytes
    let next_verkey = auths_keri::KeriPublicKey::ed25519(next_keypair.public_key().as_ref())
        .expect("ring Ed25519 public key is 32 bytes");
    if !verify_commitment(&next_verkey, &state.next_commitment[0]) {
        return Err(InitError::InvalidData(
            "Commitment mismatch: next key does not match previous commitment".into(),
        ));
    }

    let new_next_pkcs8 = Ed25519KeyPair::generate_pkcs8(&rng)
        .map_err(|e| InitError::Crypto(format!("Key generation failed: {}", e)))?;
    let new_next_keypair = Ed25519KeyPair::from_pkcs8(new_next_pkcs8.as_ref())
        .map_err(|e| InitError::Crypto(format!("Key generation failed: {}", e)))?;

    #[allow(clippy::expect_used)]
    // INVARIANT: ring Ed25519 public key is always 32 bytes; cesride encode of a valid 32-byte verkey is infallible
    let new_current_pub_encoded =
        auths_keri::KeriPublicKey::ed25519(next_keypair.public_key().as_ref())
            .expect("ring Ed25519 public key is 32 bytes")
            .to_qb64()
            .expect("cesride verkey encode is infallible");
    #[allow(clippy::expect_used)] // INVARIANT: ring Ed25519 public key is always 32 bytes
    let new_next_verkey =
        auths_keri::KeriPublicKey::ed25519(new_next_keypair.public_key().as_ref())
            .expect("ring Ed25519 public key is 32 bytes");
    let new_next_commitment = compute_next_commitment(&new_next_verkey);

    let bt = match witness_config {
        Some(cfg) if cfg.is_enabled() => Threshold::Simple(cfg.threshold as u64),
        _ => Threshold::Simple(0),
    };

    let new_sequence = state.sequence + 1;
    let mut rot = RotEvent {
        v: VersionString::placeholder(),
        d: Said::default(),
        i: prefix.clone(),
        s: KeriSequence::new(new_sequence),
        p: state.last_event_said.clone(),
        kt: Threshold::Simple(1),
        k: vec![CesrKey::new_unchecked(new_current_pub_encoded)],
        nt: Threshold::Simple(1),
        n: vec![new_next_commitment],
        bt,
        br: vec![],
        ba: vec![],
        c: vec![],
        a: vec![],
    };

    let rot_value = serde_json::to_value(Event::Rot(rot.clone()))
        .map_err(|e| InitError::Keri(format!("Serialization failed: {}", e)))?;
    rot.d = compute_said(&rot_value)
        .map_err(|e| InitError::Keri(format!("SAID computation failed: {}", e)))?;

    let canonical = serialize_for_signing(&Event::Rot(rot.clone()))
        .map_err(|e| InitError::Keri(e.to_string()))?;
    let sig = next_keypair.sign(&canonical);
    let attachment = auths_keri::serialize_attachment(&[auths_keri::IndexedSignature {
        index: 0,
        prior_index: None,
        sig: sig.as_ref().to_vec(),
    }])
    .map_err(|e| InitError::Keri(format!("attachment serialization: {e}")))?;

    backend
        .append_signed_event(&prefix, &Event::Rot(rot), &attachment)
        .map_err(|e| InitError::Registry(e.to_string()))?;

    store_rotated_keys(
        keychain,
        passphrase_provider,
        &did,
        next_alias,
        &derived_next_alias,
        new_sequence,
        decrypted_next_pkcs8.as_ref(),
        new_next_pkcs8.as_ref(),
    )?;

    Ok(RotationKeyInfo {
        sequence: new_sequence,
        new_current_pkcs8: decrypted_next_pkcs8,
        new_next_pkcs8: Pkcs8Der::new(new_next_pkcs8.as_ref()),
    })
}

/// Rotate a KERI identity with a multi-device shape (registry backend).
///
/// Reveals each prior-committed next key at the matching new `k[i]` slot,
/// optionally appends newly-generated device keypairs from `shape.add_devices`,
/// and optionally applies new `kt`/`nt` thresholds. Produces a signed `rot`
/// event appended to the registry KEL.
///
/// Keychain convention: prior next keys are loaded from
/// `{current_alias}--next-{prev_seq}-{idx}`; new keys are stored at
/// `{next_alias}--{idx}` (current) and `{next_alias}--next-{new_seq}-{idx}`
/// (next).
///
/// `shape.remove_indices` authors a dual-index shrink rotation (the validator
/// binds each surviving signature to the prior commitment it reveals). Note:
/// multi-device membership now uses KERI delegation (`keri::delegation`); this
/// shared-`k` path is retained for single-host multi-slot identities.
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
pub fn rotate_registry_identity_multi(
    backend: Arc<dyn RegistryBackend + Send + Sync>,
    current_alias: &KeyAlias,
    next_alias: &KeyAlias,
    passphrase_provider: &dyn PassphraseProvider,
    _config: &StorageLayoutConfig,
    keychain: &(dyn KeyStorage + Send + Sync),
    witness_config: Option<&WitnessConfig>,
    shape: RotationShape,
) -> Result<RotationKeyInfo, InitError> {
    // Load the base DID from the first current slot and verify the registry.
    let first_cur = KeyAlias::new_unchecked(format!("{}--{}", current_alias, 0));
    let (did, _role, _encrypted) = keychain
        .load_key(&first_cur)
        .or_else(|_| keychain.load_key(current_alias))?;

    if keychain.is_hardware_backend() {
        return Err(InitError::InvalidData(
            "Rotation requires software-backed keys; current slot is hardware-backed.".to_string(),
        ));
    }

    let prefix_str = did.as_str().strip_prefix("did:keri:").ok_or_else(|| {
        InitError::InvalidData(format!("Invalid DID format, expected 'did:keri:': {}", did))
    })?;
    let prefix = Prefix::new_unchecked(prefix_str.to_string());

    let state = backend
        .get_key_state(&prefix)
        .map_err(|e| InitError::Registry(e.to_string()))?;

    if !state.can_rotate() {
        return Err(InitError::InvalidData(
            "Identity is abandoned (cannot rotate)".to_string(),
        ));
    }

    let prior_key_count = state.current_keys.len();

    // Validate removal targets (dedup, in range). At least one prior controller
    // must survive to authorise the rotation — a surviving signer reveals a prior
    // commitment (dual-index). Replacing the whole set is the swap/recovery path.
    let mut remove: Vec<usize> = shape.remove_indices.iter().map(|&i| i as usize).collect();
    remove.sort_unstable();
    remove.dedup();
    if let Some(&bad) = remove.iter().find(|&&i| i >= prior_key_count) {
        return Err(InitError::InvalidData(format!(
            "remove index {bad} out of range (prior controller count {prior_key_count})"
        )));
    }
    let surviving_count = prior_key_count - remove.len();
    if surviving_count == 0 {
        return Err(InitError::InvalidData(
            "rotation must retain at least one prior controller to authorise it".to_string(),
        ));
    }
    let new_key_count = surviving_count + shape.add_devices.len();

    let new_kt = shape.new_kt.unwrap_or_else(|| state.threshold.clone());
    let new_nt = shape.new_nt.unwrap_or_else(|| state.next_threshold.clone());

    crate::keri::inception::validate_threshold_for_key_count(&new_kt, new_key_count)
        .map_err(|e| InitError::InvalidData(e.to_string()))?;
    crate::keri::inception::validate_threshold_for_key_count(&new_nt, new_key_count)
        .map_err(|e| InitError::InvalidData(e.to_string()))?;

    // Decrypt each SURVIVING prior-committed next key in slot order. These become
    // the new current keys at indices 0..surviving_count. `prior_indices[new_i]`
    // records the prior `n[]` slot each survivor reveals (its dual-index ondex).
    let mut new_current_pkcs8s: Vec<Pkcs8Der> = Vec::with_capacity(new_key_count);
    let mut new_current_pubs: Vec<auths_keri::KeriPublicKey> = Vec::with_capacity(new_key_count);
    let mut prior_next_aliases: Vec<KeyAlias> = Vec::with_capacity(prior_key_count);
    let mut prior_indices: Vec<u32> = Vec::with_capacity(surviving_count);

    let next_pass = passphrase_provider.get_passphrase(&format!(
        "Enter passphrase for pre-committed keys under alias '{}':",
        current_alias
    ))?;

    for idx in 0..prior_key_count {
        let alias = KeyAlias::new_unchecked(format!(
            "{}--next-{}-{}",
            current_alias, state.sequence, idx
        ));
        if remove.contains(&idx) {
            // Removed controller: its pre-committed next key is dropped from the
            // new set. Keep the alias only so the cleanup pass deletes it.
            prior_next_aliases.push(alias);
            continue;
        }
        let (did_check, _role, encrypted) = keychain.load_key(&alias)?;
        if did_check != did {
            return Err(InitError::InvalidData(format!(
                "DID mismatch for pre-committed key '{}'",
                alias
            )));
        }
        let pkcs8 = Pkcs8Der::new(decrypt_keypair(&encrypted, &next_pass)?.to_vec());
        let keypair = load_keypair_from_der_or_seed(pkcs8.as_ref())?;
        #[allow(clippy::expect_used)] // INVARIANT: ring Ed25519 public key is always 32 bytes
        let next_verkey = auths_keri::KeriPublicKey::ed25519(keypair.public_key().as_ref())
            .expect("ring Ed25519 public key is 32 bytes");
        if !verify_commitment(&next_verkey, &state.next_commitment[idx]) {
            return Err(InitError::InvalidData(format!(
                "Commitment mismatch at slot {idx}: next key does not match previous commitment"
            )));
        }
        new_current_pubs.push(next_verkey);
        new_current_pkcs8s.push(pkcs8);
        prior_indices.push(idx as u32);
        prior_next_aliases.push(alias);
    }

    // Generate added device keypairs and append to the new current set (a pure
    // removal adds none — skip, as the generator rejects an empty curve list).
    if !shape.add_devices.is_empty() {
        let added = crate::keri::inception::generate_keypairs_for_init(&shape.add_devices)
            .map_err(|e| InitError::Crypto(e.to_string()))?;
        for kp in &added {
            new_current_pubs.push(kp.verkey());
            new_current_pkcs8s.push(kp.pkcs8.clone());
        }
    }

    // Generate a fresh next keypair per new slot.
    let new_next_curves: Vec<auths_crypto::CurveType> = (0..new_key_count)
        .map(|_| auths_crypto::CurveType::P256)
        .collect();
    let new_next_kps = crate::keri::inception::generate_keypairs_for_init(&new_next_curves)
        .map_err(|e| InitError::Crypto(e.to_string()))?;

    let k: Vec<CesrKey> = new_current_pubs
        .iter()
        .map(|vk| {
            vk.to_qb64()
                .map(CesrKey::new_unchecked)
                .map_err(|e| InitError::InvalidData(e.to_string()))
        })
        .collect::<Result<_, _>>()?;
    let n: Vec<Said> = new_next_kps
        .iter()
        .map(|kp| compute_next_commitment(&kp.verkey()))
        .collect();

    let bt = match witness_config {
        Some(cfg) if cfg.is_enabled() => Threshold::Simple(cfg.threshold as u64),
        _ => Threshold::Simple(0),
    };

    let new_sequence = state.sequence + 1;
    let mut rot = RotEvent {
        v: VersionString::placeholder(),
        d: Said::default(),
        i: prefix.clone(),
        s: KeriSequence::new(new_sequence),
        p: state.last_event_said.clone(),
        kt: new_kt,
        k,
        nt: new_nt,
        n,
        bt,
        br: vec![],
        ba: vec![],
        c: vec![],
        a: vec![],
    };

    let rot_value = serde_json::to_value(Event::Rot(rot.clone()))
        .map_err(|e| InitError::Keri(format!("Serialization failed: {}", e)))?;
    rot.d = compute_said(&rot_value)
        .map_err(|e| InitError::Keri(format!("SAID computation failed: {}", e)))?;

    // Sign with surviving slot 0's newly-revealed key (kt=1). Its `prior_index`
    // is the prior `n[]` slot it reveals — for a shrink this drives the dual-index
    // CESR siger so the validator can bind it; for a same-cardinality rotation it
    // equals the index and stays byte-identical to the legacy single-index form.
    // Multi-sig aggregation is the signing-workflow module's job.
    let canonical = serialize_for_signing(&Event::Rot(rot.clone()))
        .map_err(|e| InitError::Keri(e.to_string()))?;
    let signer_keypair = load_keypair_from_der_or_seed(new_current_pkcs8s[0].as_ref())?;
    let sig = signer_keypair.sign(&canonical);
    let attachment = auths_keri::serialize_attachment(&[auths_keri::IndexedSignature {
        index: 0,
        prior_index: prior_indices.first().copied(),
        sig: sig.as_ref().to_vec(),
    }])
    .map_err(|e| InitError::Keri(format!("attachment serialization: {e}")))?;

    backend
        .append_signed_event(&prefix, &Event::Rot(rot), &attachment)
        .map_err(|e| InitError::Registry(e.to_string()))?;

    // Persist the new current + next keys under {next_alias}--{idx} and
    // {next_alias}--next-{new_seq}-{idx}. Best-effort cleanup of prior
    // pre-committed slots.
    let new_pass = passphrase_provider.get_passphrase(&format!(
        "Create passphrase for new key alias '{}':",
        next_alias
    ))?;
    let confirm_pass =
        passphrase_provider.get_passphrase(&format!("Confirm passphrase for '{}':", next_alias))?;
    if new_pass != confirm_pass {
        return Err(InitError::InvalidData(format!(
            "Passphrases do not match for alias '{}'",
            next_alias
        )));
    }

    for (idx, cur_pkcs8) in new_current_pkcs8s.iter().enumerate() {
        let slot_alias = KeyAlias::new_unchecked(format!("{}--{}", next_alias, idx));
        let encrypted = encrypt_keypair(cur_pkcs8.as_ref(), &new_pass)?;
        keychain.store_key(&slot_alias, &did, KeyRole::Primary, &encrypted)?;
    }
    for (idx, nxt_kp) in new_next_kps.iter().enumerate() {
        let slot_alias =
            KeyAlias::new_unchecked(format!("{}--next-{}-{}", next_alias, new_sequence, idx));
        let encrypted = encrypt_keypair(nxt_kp.pkcs8.as_ref(), &new_pass)?;
        keychain.store_key(&slot_alias, &did, KeyRole::NextRotation, &encrypted)?;
    }
    for alias in &prior_next_aliases {
        let _ = keychain.delete_key(alias);
    }

    // Return info shaped around slot 0 for API compatibility with single-key
    // callers; callers wanting the full multi-key material can regenerate from
    // the keychain via the slot-indexed aliases above.
    let new_next_pkcs8_bytes = new_next_kps[0].pkcs8.as_ref().to_vec();
    Ok(RotationKeyInfo {
        sequence: new_sequence,
        new_current_pkcs8: new_current_pkcs8s
            .into_iter()
            .next()
            .ok_or_else(|| InitError::Crypto("empty current keyset after rotation".to_string()))?,
        new_next_pkcs8: Pkcs8Der::new(new_next_pkcs8_bytes),
    })
}

#[allow(clippy::too_many_arguments)]
fn store_rotated_keys(
    keychain: &(dyn KeyStorage + Send + Sync),
    passphrase_provider: &dyn PassphraseProvider,
    did: &IdentityDID,
    next_alias: &KeyAlias,
    old_next_alias: &KeyAlias,
    new_sequence: u128,
    current_pkcs8: &[u8],
    new_next_pkcs8: &[u8],
) -> Result<(), InitError> {
    let new_pass = passphrase_provider.get_passphrase(&format!(
        "Create passphrase for new key alias '{}':",
        next_alias
    ))?;
    let confirm_pass =
        passphrase_provider.get_passphrase(&format!("Confirm passphrase for '{}':", next_alias))?;
    if new_pass != confirm_pass {
        return Err(InitError::InvalidData(format!(
            "Passphrases do not match for alias '{}'",
            next_alias
        )));
    }

    let encrypted_new_current = encrypt_keypair(current_pkcs8, &new_pass)?;
    keychain.store_key(next_alias, did, KeyRole::Primary, &encrypted_new_current)?;

    // pass-through avoids the extract-then-re-encode silent-Ed25519 hazard.
    let encrypted_future = encrypt_keypair(new_next_pkcs8, &new_pass)?;

    let future_key_alias =
        KeyAlias::new_unchecked(format!("{}--next-{}", next_alias, new_sequence));
    keychain.store_key(
        &future_key_alias,
        did,
        KeyRole::NextRotation,
        &encrypted_future,
    )?;

    let _ = keychain.delete_key(old_next_alias);

    Ok(())
}