derec-library 0.0.5

Rust SDK for the DeRec protocol, including native and WebAssembly bindings.
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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.

//! Post-recovery rebuild handler.
//!
//! Takes a [`Secret`] handed up by a
//! [`DeRecEvent::SecretRecovered`](super::super::DeRecEvent::SecretRecovered)
//! event and reseats the protocol's `secret_id` namespace from it:
//! writes canonical helper / replica channel records, commits the
//! user-secret snapshot, then unpairs every other channel under the
//! `secret_id` (the recovery-mode channels minted to drive
//! `start(RecoverSecret)` — scrap after restore commits).
//!
//! Two preconditions are reported as [`RestoreError`] (wrapped in
//! [`crate::Error::Restore`]) **before any store mutation** — a
//! precondition error is exactly equivalent to never having called
//! restore:
//!
//! - [`RestoreError::AlreadyRestored`] — a user-secret snapshot
//!   already exists for this `secret_id`.
//! - [`RestoreError::Conflict`] — a channel already lives at one of
//!   the canonical helper / replica ids carried by the recovered
//!   `Secret`.
//!
//! A third, [`crate::Error::Transport`], joins them: the roster stores each
//! peer as a bare `transport_uri`, so its protocol is derived from the URI
//! scheme on the way back in, and a scheme this library serves no stores.transport
//! for cannot become a channel record. Checked with the other preconditions,
//! so it too costs no partial write.
//!
//! Store I/O failures mid-restore propagate as their underlying
//! [`crate::Error`] variant (`ChannelStore`, `SecretStore`, and
//! `ShareStore` — which the user-secret store reuses for the snapshot
//! write, restore having no share writes of its own). The snapshot
//! write is the commit point — nothing
//! is removed before it succeeds, so any mid-flight failure leaves
//! state the next `restore` call can detect as one of the
//! preconditions above.
//!
//! Restore writes no owner-side tracking shares, so the recovered
//! version is not verifiable on this device; publishing once restores
//! that. See [`restore`] for why, and for the replica-identity
//! precondition on that publish.

use super::super::{
    DeRecChannelStore, DeRecEvent, DeRecSecretStore, DeRecUserSecretStore, SecretValue, UnpairAck,
    types::{
        ChannelRecord, ChannelStatus, HelperChannel, HelperInfo, ReplicaMember, ReplicaRole,
        Replicas, Secret, UserSecrets,
    },
};
use crate::protocol::context::Local;
use crate::protocol::stores::{StoreSet, Stores};
use crate::{
    Result,
    types::{ChannelId, SharedKey},
};
use std::collections::HashSet;

use crate::extensions::channel_store::ChannelStoreExt as _;
#[cfg(target_arch = "wasm32")]
use crate::interop::wasm::now_secs;
#[cfg(not(target_arch = "wasm32"))]
use crate::utils::now_secs;

/// Restore-specific failure modes surfaced via [`crate::Error::Restore`].
/// Every variant is reported **before any store mutation** — a
/// precondition error is exactly equivalent to never having called
/// restore. Store I/O failures mid-restore propagate as their
/// underlying [`crate::Error`] variant instead.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum RestoreError {
    /// A user-secret snapshot already exists for the protocol's
    /// `secret_id`. The application must clear it before retrying.
    #[error("user-secret snapshot already exists for secret_id")]
    AlreadyRestored,

    /// One or more channels already live at canonical helper or
    /// replica ids carried by the recovered `Secret`. The contained
    /// list enumerates the collisions; the application clears them
    /// through its own store wrappers and retries.
    #[error("restore blocked by pre-existing channels at canonical ids")]
    Conflict(Vec<ChannelId>),

    /// The recovered [`Secret`] is internally inconsistent. Only
    /// reachable when a `Secret` was hand-crafted — library-produced
    /// ones always satisfy the invariants (rebuilt inside the sharing
    /// handler during a `start(ProtectSecret)` round).
    #[error("recovered Secret is internally inconsistent: {0}")]
    Invariant(&'static str),
}

/// Run the restore flow. On success: canonical helper channels are
/// persisted with their `SharedKey`; canonical replica channels are
/// persisted with the group key from `secret.replicas.shared_key`; the
/// user-secret snapshot is committed at `recovered_version`; every
/// recovery-mode channel under `secret_id` is unpaired
/// (`UnpairAck::NotRequired`). The returned events come from the
/// recovery-channel wipe and should be drained into the protocol's
/// `pending_start_events`.
///
/// # Verification after a restore
///
/// No owner-side tracking [`crate::protocol::types::Share`] is written,
/// so `start(VerifyShares)` at `recovered_version` reports
/// [`crate::Error::InvalidInput`] — this device holds no reference bytes
/// for that version and cannot check a proof against it. That is a
/// property of recovery, not a defect: a `VerifyShare` proof is
/// `SHA-384(share ‖ nonce)` over the *exact* bytes a Helper holds, and
/// recovery cannot attribute a collected share to a canonical Helper
/// channel — the VSS x-coordinate is a random field element and
/// `GetShareResponseMessage` carries no channel id.
///
/// The way back to a verifiable state is to publish:
/// `start(ProtectSecret)` derives `recovered_version + 1` from the
/// snapshot committed here, writes real tracking shares as it
/// distributes, and `start(VerifyShares)` at that version behaves
/// exactly as it does for an owner that never recovered.
///
/// A restored device whose roster carries a replica group cannot
/// publish until the application configures a `replica_id` that the
/// roster names — see step 3 on why restore does not adopt one itself.
///
/// # Sequence
///
/// 1. **Preconditions.** Validate the protocol can restore and collect
///    what the rest of the flow needs (the canonical id set plus the
///    current channel list, reused for the wipe).
///    [`RestoreError::AlreadyRestored`] when a snapshot is already
///    committed, [`RestoreError::Invariant`] when
///    `secret.replicas.shared_key` is mis-sized, and
///    [`RestoreError::Conflict`] when an existing channel sits at a
///    canonical helper / replica id, and [`crate::Error::Transport`] when
///    a roster entry names a URI scheme this library serves no stores.transport
///    for. All four are reported before any store mutation. Channels *not*
///    at canonical ids are recovery channels — wiped in step 5, never
///    flagged as collisions.
/// 2. **Helper channels.** Persist each helper's canonical channel
///    record and its `SharedKey`. No tracking share — see
///    *Verification after a restore* above.
/// 3. **Replica members.** Persist every member of the roster against the
///    one group channel, with the group key as that channel's `SharedKey`.
///    Each member's `role` is taken verbatim from the roster: it is a
///    property of the group, not of the reader.
///
///    The device's own `replica_id` is **not** adopted from the recovered
///    `Secret`. The roster names its source, but a recovering device
///    claiming that identity is a takeover, which is a separate decision
///    with its own convergence rules. A device that was built without a
///    `replica_id` still has none after restore and cannot publish as a
///    replica until the application configures one.
/// 4. **Commit.** Write the user-secret snapshot at
///    `recovered_version`. This write is the commit point — nothing is
///    removed before it succeeds, so any earlier failure is fully
///    retryable.
/// 5. **Wipe.** Send unpair requests to every channel not at a
///    canonical id — the recovery-mode channels minted to drive
///    `start(RecoverSecret)` — and drop their local state.
///
///    `UnpairAck::NotRequired` is forced here, deliberately, and does
///    not follow the protocol's configured ack mode. Waiting on an
///    acknowledgement would keep the ephemeral channels alive for up to
///    the unpair timeout, and those channels are indistinguishable from
///    the canonical ones to
///    [`sharing`](super::sharing) — which selects purely on
///    `peer_role == Helper && status == Paired` — so a subsequent
///    `ProtectSecret` would double-send to every helper. The ephemeral
///    channels must be gone by the time this call returns.
///
///    For the same reason the wipe cannot fail the restore. An old
///    helper that has gone away is the expected condition during
///    recovery, and the commit in step 4 has already happened —
///    returning `Err` here would strand the caller with committed
///    canonical state, un-torn-down ephemeral channels, and
///    [`RestoreError::AlreadyRestored`] blocking any retry. Instead each
///    undeliverable teardown surfaces as
///    [`DeRecEvent::UnpairFailed`] and local state is dropped anyway, so
///    every wiped channel still yields exactly one
///    [`DeRecEvent::Unpaired`].
#[cfg_attr(feature = "logging", tracing::instrument(skip_all))]
pub(in crate::protocol) async fn restore<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    secret: &Secret,
    recovered_version: u32,
) -> Result<Vec<DeRecEvent>> {
    let (canonical_ids, existing_channels) = check_preconditions(stores, local, secret).await?;

    write_helper_channels(stores, local, &secret.helpers).await?;

    if let Some(group) = secret.replicas.as_ref().filter(|g| !g.members.is_empty()) {
        write_replica_channels(stores, local, group).await?;
    }

    commit_snapshot(stores, local, secret, recovered_version).await?;

    let events = unpair_recovery_channels(stores, local, &existing_channels, &canonical_ids).await;

    #[cfg(feature = "logging")]
    tracing::info!(
        local.secret_id,
        helpers_restored = secret.helpers.len(),
        replicas_restored = secret.replicas.as_ref().map_or(0, |g| g.members.len()),
        user_secrets_restored = secret.secrets.len(),
        "DeRecProtocol restored from recovered Secret"
    );

    Ok(events)
}

async fn check_preconditions<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    secret: &Secret,
) -> Result<(HashSet<u64>, Vec<HelperChannel>)> {
    if stores
        .user_secrets
        .load_latest(local.secret_id)
        .await?
        .is_some()
    {
        return Err(RestoreError::AlreadyRestored.into());
    }

    if let Some(group) = &secret.replicas
        && !group.members.is_empty()
        && group.shared_key.len() != 32
    {
        return Err(RestoreError::Invariant(
            "recovered Secret carries replicas but replicas.shared_key is missing or wrong size",
        )
        .into());
    }

    // Rehydrating an endpoint derives its protocol from the URI scheme, so a
    // roster naming a scheme this library does not serve cannot be turned into
    // channel records at all. Checked here, alongside the other preconditions,
    // so the refusal costs no partial write.
    // A roster entry with no endpoint cannot be restored into a usable
    // channel — there would be nothing to send to. Checked here, alongside
    // the other preconditions, so the refusal costs no partial write.
    //
    // The endpoints themselves need no re-derivation: a v3 roster stores each
    // one with its protocol discriminant, and a v2 roster had its single URI
    // resolved during decode.
    let rosters_have_endpoints = secret
        .helpers
        .iter()
        .map(|h| &h.transports)
        .chain(
            secret
                .replicas
                .iter()
                .flat_map(|g| g.members.iter().map(|m| &m.transports)),
        )
        .all(|endpoints| !endpoints.is_empty());

    if !rosters_have_endpoints {
        return Err(crate::Error::InvalidInput(
            "recovered roster has an entry with no transport endpoint",
        ));
    }

    // Every member shares the group channel, so the roster contributes one id
    // rather than one per member.
    let canonical_ids: HashSet<u64> = secret
        .helpers
        .iter()
        .map(|h| h.channel_id)
        .chain(secret.replicas.as_ref().map(|g| g.channel_id))
        .collect();
    // Unfiltered deliberately: the caller partitions this listing, unpairing
    // every channel `canonical_ids` does *not* name while this function
    // rejects the ones it does. Narrowing either way loses the other half.
    let existing_channels = stores
        .channels
        .helpers_matching(
            local.secret_id,
            crate::protocol::types::HelperFilter::default(),
        )
        .await?;
    let collisions: Vec<ChannelId> = existing_channels
        .iter()
        .filter(|c| canonical_ids.contains(&c.channel_id.0))
        .map(|c| c.channel_id)
        .collect();
    if !collisions.is_empty() {
        return Err(RestoreError::Conflict(collisions).into());
    }

    Ok((canonical_ids, existing_channels))
}

async fn write_helper_channels<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    helpers: &[HelperInfo],
) -> Result<()> {
    let secret_id = local.secret_id;
    for h in helpers {
        let cid = ChannelId(h.channel_id);
        let shared_key: SharedKey = h
            .shared_key
            .as_slice()
            .try_into()
            .map_err(|_| RestoreError::Invariant("helper.shared_key must be 32 bytes"))?;
        stores
            .channels
            .save(
                secret_id,
                ChannelRecord::Helper(HelperChannel {
                    channel_id: cid,
                    transports: h.transports.clone(),
                    communication_info: h.communication_info.clone(),
                    status: ChannelStatus::Paired,
                    created_at: now_secs(),
                    peer_role: derec_proto::SenderKind::Helper,
                }),
            )
            .await?;
        stores
            .secrets
            .save(secret_id, cid, SecretValue::SharedKey(shared_key))
            .await?;
    }
    Ok(())
}

async fn write_replica_channels<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    group: &Replicas,
) -> Result<()> {
    let group_key: SharedKey = group.shared_key.as_slice().try_into().map_err(|_| {
        RestoreError::Invariant("replicas.shared_key must be 32 bytes when replicas is non-empty")
    })?;
    let cid = ChannelId(group.channel_id);
    for r in &group.members {
        stores
            .channels
            .save(
                local.secret_id,
                ChannelRecord::Replica(ReplicaMember {
                    channel_id: cid,
                    replica_id: crate::types::ReplicaId::try_from(r.replica_id)?,
                    transports: r.transports.clone(),
                    communication_info: r.communication_info.clone(),
                    role: ReplicaRole::from_i32(r.role).ok_or(RestoreError::Invariant(
                        "roster member carries an unknown role",
                    ))?,
                    status: ChannelStatus::Paired,
                    created_at: now_secs(),
                }),
            )
            .await?;
    }
    // One key at the one channel every member is addressed on.
    stores
        .secrets
        .save(local.secret_id, cid, SecretValue::SharedKey(group_key))
        .await?;
    Ok(())
}

async fn commit_snapshot<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    secret: &Secret,
    recovered_version: u32,
) -> Result<()> {
    stores
        .user_secrets
        .save_latest(
            local.secret_id,
            UserSecrets {
                version: recovered_version,
                secrets: secret.secrets.clone(),
                description: None,
                replicas: secret.replicas.clone(),
            },
        )
        .await?;
    Ok(())
}
async fn unpair_recovery_channels<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    existing_channels: &[HelperChannel],
    canonical_ids: &HashSet<u64>,
) -> Vec<DeRecEvent> {
    let recovery_ids: Vec<ChannelId> = existing_channels
        .iter()
        .filter(|c| !canonical_ids.contains(&c.channel_id.0))
        .map(|c| c.channel_id)
        .collect();
    if recovery_ids.is_empty() {
        return Vec::new();
    }
    let now = now_secs();
    let round = &crate::protocol::context::Round {
        reply_to: &[],
        trace_id: crate::derec_message::fresh_trace_id(),
    };
    let mut events = Vec::new();
    for channel_id in recovery_ids {
        match super::unpairing::start(
            stores,
            local,
            channel_id,
            None,
            UnpairAck::NotRequired,
            now,
            round,
        )
        .await
        {
            Ok(mut per_channel) => events.append(&mut per_channel),
            Err(e) => {
                events.push(DeRecEvent::UnpairFailed {
                    channel_id,
                    error: e.to_string(),
                });
                if super::unpairing::drop_channel_state(stores, local, channel_id)
                    .await
                    .is_ok()
                {
                    events.push(DeRecEvent::Unpaired { channel_id });
                }
            }
        }
    }
    events
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::protocol::DeRecProtocolBuilder;
    use crate::protocol::traits::{
        DeRecChannelStore, DeRecSecretStore, DeRecShareStore, DeRecUserSecretStore,
    };
    use crate::protocol::types::{
        ChannelQuery, ChannelRecord, ChannelStatus, HelperInfo, ReplicaInfo, ReplicaRole, Replicas,
        Secret, SecretKind, SecretValue, UserSecret, UserSecrets,
    };
    use derec_proto::{SenderKind, TransportProtocol};
    use std::collections::HashMap;

    use crate::protocol::test::{
        InMemChannelStore, InMemSecretStore, InMemShareStore, InMemStateStore,
        InMemUserSecretStore, NoopTransport, StoreRig, run_async,
    };

    type TestProto = crate::protocol::DeRecProtocol<
        InMemChannelStore,
        InMemShareStore,
        InMemSecretStore,
        InMemUserSecretStore,
        InMemStateStore,
        NoopTransport,
    >;

    /// Test bundle — keeps clone handles to every store so the test
    /// can both pre-seed before construction AND inspect after the
    /// restore call.
    struct TestRig {
        protocol: TestProto,
        channel_store: InMemChannelStore,
        secret_store: InMemSecretStore,
        share_store: InMemShareStore,
        user_secret_store: InMemUserSecretStore,
    }

    fn build_rig(secret_id: u64) -> TestRig {
        let rig = StoreRig::new();
        let protocol = DeRecProtocolBuilder::new(secret_id)
            .with_channel_store(rig.channels.clone())
            .with_share_store(rig.shares.clone())
            .with_secret_store(rig.secrets.clone())
            .with_user_secret_store(rig.user_secrets.clone())
            .with_transport(NoopTransport)
            .with_state_store(InMemStateStore)
            .with_own_transports(["https://owner.example.com"])
            .with_threshold(2)
            .build()
            .expect("test rig builds");
        TestRig {
            protocol,
            channel_store: rig.channels,
            secret_store: rig.secrets,
            share_store: rig.shares,
            user_secret_store: rig.user_secrets,
        }
    }

    fn fixture_secret() -> Secret {
        Secret {
            helpers: vec![
                HelperInfo {
                    channel_id: 11,
                    transports: vec![derec_proto::TransportProtocol {
                        uri: "https://helper-a.example".to_owned(),
                        protocol: derec_proto::Protocol::Https as i32,
                    }],
                    shared_key: vec![0xAA; 32],
                    communication_info: HashMap::from([("name".to_owned(), "HelperA".to_owned())]),
                },
                HelperInfo {
                    channel_id: 12,
                    transports: vec![derec_proto::TransportProtocol {
                        uri: "https://helper-b.example".to_owned(),
                        protocol: derec_proto::Protocol::Https as i32,
                    }],
                    shared_key: vec![0xBB; 32],
                    communication_info: HashMap::new(),
                },
            ],
            secrets: vec![
                UserSecret {
                    id: vec![0x01],
                    name: "wallet".to_owned(),
                    data: b"correct horse battery staple".to_vec(),
                },
                UserSecret {
                    id: vec![0x02],
                    name: "api token".to_owned(),
                    data: b"hunter2".to_vec(),
                },
            ],
            replicas: Some(Replicas {
                channel_id: 21,
                members: vec![
                    ReplicaInfo {
                        replica_id: 0xBEEF,
                        transports: vec![derec_proto::TransportProtocol {
                            uri: "https://owner.example".to_owned(),
                            protocol: derec_proto::Protocol::Https as i32,
                        }],
                        role: ReplicaRole::Source as i32,
                        communication_info: HashMap::new(),
                    },
                    ReplicaInfo {
                        replica_id: 0xCAFE,
                        transports: vec![derec_proto::TransportProtocol {
                            uri: "https://replica.example".to_owned(),
                            protocol: derec_proto::Protocol::Https as i32,
                        }],
                        role: ReplicaRole::Destination as i32,
                        communication_info: HashMap::new(),
                    },
                ],
                shared_key: vec![0xCC; 32],
            }),
        }
    }

    // ---------------- Happy path ----------------

    #[test]
    fn restore_happy_path_persists_canonical_state() {
        run_async(async {
            let secret_id: u64 = 0xDE_2EC;
            let mut rig = build_rig(secret_id);

            rig.protocol
                .restore(&fixture_secret(), 7)
                .await
                .expect("happy path must succeed");

            // Helper channels: status=Paired, role=Owner, no replica_id.
            for hid in [11_u64, 12] {
                let ch = rig
                    .channel_store
                    .load(
                        secret_id,
                        ChannelQuery::Helper {
                            channel_id: ChannelId(hid),
                        },
                    )
                    .await
                    .unwrap()
                    .expect("helper channel must be persisted");
                let ChannelRecord::Helper(ch) = ch else {
                    panic!("a helper query must never return a replica record");
                };
                assert_eq!(ch.status, ChannelStatus::Paired);
                assert_eq!(ch.peer_role, SenderKind::Helper);
                let sk = rig
                    .secret_store
                    .load(secret_id, ChannelId(hid), SecretKind::SharedKey)
                    .await
                    .unwrap()
                    .expect("helper SharedKey must be persisted");
                assert!(matches!(sk, SecretValue::SharedKey(_)));
                // No tracking share. A fabricated one would hash to
                // something no Helper can produce, so verification would
                // report the Helper's data as corrupt rather than reporting
                // that this device has nothing to check against.
                let shares = rig
                    .share_store
                    .load(secret_id, ChannelId(hid), &[])
                    .await
                    .unwrap();
                assert!(
                    shares.is_empty(),
                    "restore must not invent tracking shares; got {shares:?}"
                );
            }

            // Replica member: the roster records each member's own role
            // verbatim — it is absolute, not relative to the reader.
            let rep = rig
                .channel_store
                .load(
                    secret_id,
                    ChannelQuery::Replica {
                        channel_id: ChannelId(21),
                        replica_id: crate::types::ReplicaId(0xCAFE),
                    },
                )
                .await
                .unwrap()
                .expect("replica member must be persisted");
            let ChannelRecord::Replica(rep) = rep else {
                panic!("a replica query must never return a helper record");
            };
            assert_eq!(rep.status, ChannelStatus::Paired);
            assert_eq!(rep.role, ReplicaRole::Destination);
            assert_eq!(rep.replica_id.0, 0xCAFE);
            let rep_sk = rig
                .secret_store
                .load(secret_id, ChannelId(21), SecretKind::SharedKey)
                .await
                .unwrap()
                .expect("replica group key must be persisted");
            match rep_sk {
                SecretValue::SharedKey(k) => assert_eq!(k.to_vec(), vec![0xCC; 32]),
                _ => panic!("expected SharedKey"),
            }

            // User-secret snapshot at recovered version.
            let snapshot = rig
                .user_secret_store
                .load_latest(secret_id)
                .await
                .unwrap()
                .expect("snapshot must exist");
            assert_eq!(snapshot.version, 7);
            assert_eq!(snapshot.secrets.len(), 2);
            assert_eq!(snapshot.secrets[0].name, "wallet");
            assert_eq!(snapshot.secrets[0].data, b"correct horse battery staple");
            assert_eq!(snapshot.secrets[1].name, "api token");

            // The device does not take the source's identity. The roster
            // names its source, but adopting that id is a takeover — a
            // separate decision with its own convergence rules — so a device
            // built without a replica_id still has none after restore.
            assert_eq!(
                rig.protocol.replica_id(),
                None,
                "restore must not adopt the roster source's replica_id"
            );
        });
    }

    // ---------------- Endpoint rehydration ----------------

    /// The roster stores a bare `transport_uri` and no protocol discriminant,
    /// so restore has to derive one. Pairing it with a fixed `Https` made every
    /// gRPC-paired peer come back as `{grpcs://…, Https}` — a combination
    /// `TransportProtocol::validate` rejects outright, which breaks the first
    /// send after every recovery.
    #[test]
    fn a_grpc_peer_is_rehydrated_as_grpc() {
        run_async(async {
            let secret_id: u64 = 0xDE_2EC;
            let mut rig = build_rig(secret_id);

            let mut secret = fixture_secret();
            secret.helpers[0].transports = vec![derec_proto::TransportProtocol {
                uri: "grpcs://helper-a.example:443".to_owned(),
                protocol: derec_proto::Protocol::Grpc as i32,
            }];
            let members = &mut secret
                .replicas
                .as_mut()
                .expect("fixture has a roster")
                .members;
            members[1].transports = vec![derec_proto::TransportProtocol {
                uri: "grpcs://replica.example:443".to_owned(),
                protocol: derec_proto::Protocol::Grpc as i32,
            }];

            rig.protocol
                .restore(&secret, 7)
                .await
                .expect("a grpc roster must restore");

            let helper = rig
                .channel_store
                .load(
                    secret_id,
                    ChannelQuery::Helper {
                        channel_id: ChannelId(11),
                    },
                )
                .await
                .unwrap()
                .expect("helper channel must be persisted");
            let ChannelRecord::Helper(helper) = helper else {
                panic!("a helper query must never return a replica record");
            };
            assert_eq!(helper.transports[0].uri, "grpcs://helper-a.example:443");
            assert_eq!(
                helper.transports[0].protocol,
                derec_proto::Protocol::Grpc as i32,
                "a grpcs:// helper must come back as Grpc, not the historical \
                 hardcoded Https"
            );
            for endpoint in &helper.transports {
                crate::transport::TransportProtocol::try_from(endpoint)
                    .expect("every rehydrated endpoint must be self-consistent");
            }

            let member = rig
                .channel_store
                .load(
                    secret_id,
                    ChannelQuery::Replica {
                        channel_id: ChannelId(21),
                        replica_id: crate::types::ReplicaId(0xCAFE),
                    },
                )
                .await
                .unwrap()
                .expect("replica member must be persisted");
            let ChannelRecord::Replica(member) = member else {
                panic!("a replica query must never return a helper record");
            };
            assert_eq!(member.transports[0].uri, "grpcs://replica.example:443");
            assert_eq!(
                member.transports[0].protocol,
                derec_proto::Protocol::Grpc as i32,
                "a grpcs:// group member must come back as Grpc"
            );

            // The https:// entries in the same roster are unaffected — the
            // discriminant follows each URI, not the roster as a whole.
            let other = rig
                .channel_store
                .load(
                    secret_id,
                    ChannelQuery::Helper {
                        channel_id: ChannelId(12),
                    },
                )
                .await
                .unwrap()
                .expect("helper channel must be persisted");
            let ChannelRecord::Helper(other) = other else {
                panic!("a helper query must never return a replica record");
            };
            assert_eq!(
                other.transports[0].protocol,
                derec_proto::Protocol::Https as i32
            );
        });
    }

    /// A roster entry that names no endpoint cannot become a usable channel
    /// — there would be nothing to send to. Refused with the rest of the
    /// preconditions, so nothing is written and the call stays retryable.
    #[test]
    fn a_roster_entry_without_an_endpoint_is_refused_before_any_write() {
        run_async(async {
            let secret_id: u64 = 0xDE_2EC;
            let mut rig = build_rig(secret_id);

            let mut secret = fixture_secret();
            secret.helpers[1].transports = Vec::new();

            let err = rig
                .protocol
                .restore(&secret, 7)
                .await
                .expect_err("a peer with no endpoint must not restore silently");
            assert!(
                matches!(err, crate::Error::InvalidInput(_)),
                "expected the precondition refusal, got {err:?}"
            );

            assert!(
                rig.channel_store
                    .load(
                        secret_id,
                        ChannelQuery::Helper {
                            channel_id: ChannelId(11)
                        }
                    )
                    .await
                    .unwrap()
                    .is_none(),
                "a precondition failure must leave the stores untouched"
            );
            assert!(
                rig.user_secret_store
                    .load_latest(secret_id)
                    .await
                    .unwrap()
                    .is_none(),
                "a precondition failure must not commit a snapshot"
            );
        });
    }

    // ---------------- Recovery-channel wipe ----------------

    #[test]
    fn restore_unpairs_pre_existing_recovery_channels() {
        run_async(async {
            let secret_id: u64 = 0xDE_2EC;
            let mut rig = build_rig(secret_id);

            // Two recovery channels at ids that don't collide with any
            // canonical helper or replica id from `fixture_secret`.
            // Each needs a SharedKey in `secret_store` so the unpair
            // handler can build the encrypted request envelope.
            for rcid in [99_u64, 100] {
                rig.channel_store.helper_rows.lock().unwrap().insert(
                    (secret_id, rcid),
                    HelperChannel {
                        channel_id: ChannelId(rcid),
                        transports: vec![TransportProtocol {
                            uri: format!("https://recovery-{rcid}.example"),
                            protocol: 0,
                        }],
                        communication_info: HashMap::new(),
                        status: ChannelStatus::Paired,
                        created_at: 1,
                        peer_role: SenderKind::Helper,
                    },
                );
                rig.secret_store.data.lock().unwrap().insert(
                    (secret_id, rcid, SecretKind::SharedKey as u8),
                    SecretValue::SharedKey([0x77; 32]),
                );
            }

            rig.protocol
                .restore(&fixture_secret(), 7)
                .await
                .expect("restore must succeed despite recovery channels");

            // Recovery channels and their SharedKeys are gone.
            for rcid in [99_u64, 100] {
                assert!(
                    rig.channel_store
                        .load(
                            secret_id,
                            ChannelQuery::Helper {
                                channel_id: ChannelId(rcid),
                            },
                        )
                        .await
                        .unwrap()
                        .is_none(),
                    "recovery channel {rcid} must be unpaired"
                );
                assert!(
                    rig.secret_store
                        .load(secret_id, ChannelId(rcid), SecretKind::SharedKey)
                        .await
                        .unwrap()
                        .is_none()
                );
            }

            // Canonical state is in place.
            assert!(
                rig.channel_store
                    .load(
                        secret_id,
                        ChannelQuery::Helper {
                            channel_id: ChannelId(11),
                        },
                    )
                    .await
                    .unwrap()
                    .is_some()
            );
        });
    }

    /// An old helper that has gone away is the *expected* condition
    /// during recovery, so a failed teardown must not undo a committed
    /// restore.
    #[test]
    fn restore_succeeds_when_recovery_channel_unpair_cannot_be_delivered() {
        run_async(async {
            let secret_id: u64 = 0xDE_2EC;
            let rig = StoreRig::new();
            let mut protocol = DeRecProtocolBuilder::new(secret_id)
                .with_channel_store(rig.channels.clone())
                .with_share_store(rig.shares.clone())
                .with_secret_store(rig.secrets.clone())
                .with_user_secret_store(rig.user_secrets.clone())
                .with_transport(crate::protocol::test::FailingTransport)
                .with_state_store(InMemStateStore)
                .with_own_transports(["https://owner.example.com"])
                .with_threshold(2)
                .build()
                .expect("test rig builds");

            rig.channels.helper_rows.lock().unwrap().insert(
                (secret_id, 99),
                HelperChannel {
                    channel_id: ChannelId(99),
                    transports: vec![TransportProtocol {
                        uri: "https://gone.example".to_owned(),
                        protocol: 0,
                    }],
                    communication_info: HashMap::new(),
                    status: ChannelStatus::Paired,
                    created_at: 1,
                    peer_role: SenderKind::Helper,
                },
            );
            rig.secrets.data.lock().unwrap().insert(
                (secret_id, 99, SecretKind::SharedKey as u8),
                SecretValue::SharedKey([0x77; 32]),
            );

            let events = protocol
                .restore(&fixture_secret(), 7)
                .await
                .expect("an unreachable peer must not fail the restore");

            assert!(
                events.iter().any(|e| matches!(
                    e,
                    DeRecEvent::UnpairFailed { channel_id, .. } if *channel_id == ChannelId(99)
                )),
                "the undeliverable teardown must be reported, got {events:?}"
            );
            assert!(
                events
                    .iter()
                    .any(|e| matches!(e, DeRecEvent::Unpaired { channel_id } if *channel_id == ChannelId(99))),
                "local state is dropped regardless, so Unpaired still fires"
            );

            assert!(
                rig.channels
                    .load(
                        secret_id,
                        ChannelQuery::Helper {
                            channel_id: ChannelId(99),
                        },
                    )
                    .await
                    .unwrap()
                    .is_none(),
                "the ephemeral channel must not survive a failed send"
            );
            assert!(
                rig.user_secrets
                    .load_latest(secret_id)
                    .await
                    .unwrap()
                    .is_some(),
                "the recovered snapshot stays committed"
            );
            assert!(
                rig.channels
                    .load(
                        secret_id,
                        ChannelQuery::Helper {
                            channel_id: ChannelId(11),
                        },
                    )
                    .await
                    .unwrap()
                    .is_some(),
                "canonical helper channels stay in place"
            );
        });
    }

    // ---------------- Preconditions ----------------

    /// Restore leaves the recovered version unverifiable, and one publish is
    /// what buys verification back.
    ///
    /// This is the sequence the restore docs point applications at, so it is
    /// asserted rather than described: the snapshot committed at
    /// `recovered_version` is what the next round derives `+ 1` from, and that
    /// round writes tracking shares carrying the bytes it actually sent.
    /// Without this, removing the fabricated share would look like a lost
    /// capability instead of a relocated one.
    #[test]
    fn a_publish_after_restore_writes_real_tracking_shares() {
        run_async(async {
            let secret_id: u64 = 0xDE_2EC;
            let mut rig = build_rig(secret_id);
            // Helpers only. A roster carrying a replica group cannot publish
            // until the application configures a `replica_id` the roster
            // names, which is a separate decision restore declines to make.
            let secret = Secret {
                replicas: None,
                ..fixture_secret()
            };

            rig.protocol
                .restore(&secret, 4)
                .await
                .expect("restore must succeed");

            let events = rig
                .protocol
                .start(crate::protocol::DeRecFlow::ProtectSecret {
                    secrets: secret.secrets.clone(),
                    description: None,
                })
                .await
                .expect("a restored owner must be able to publish again");
            assert!(
                events
                    .iter()
                    .any(|e| matches!(e, DeRecEvent::ProtectSecretStarted { version: 5, .. })),
                "the round after a restore at 4 must be 5; got {events:?}"
            );

            for hid in [11_u64, 12] {
                let rows = rig
                    .share_store
                    .load(secret_id, ChannelId(hid), &[])
                    .await
                    .unwrap();
                let versions: Vec<u32> = rows.iter().map(|r| r.version).collect();
                assert_eq!(
                    versions,
                    vec![5],
                    "helper {hid} must hold exactly the published version, \
                     with nothing left over from the restore"
                );
                assert!(
                    !rows[0].bytes.is_empty(),
                    "helper {hid}'s tracking share must carry the committed \
                     bytes that were sent, or verification has nothing to hash"
                );
            }
        });
    }

    #[test]
    fn restore_returns_already_restored_when_snapshot_exists() {
        run_async(async {
            let secret_id: u64 = 0xDE_2EC;
            let mut rig = build_rig(secret_id);
            rig.user_secret_store.data.lock().unwrap().insert(
                secret_id,
                UserSecrets {
                    version: 1,
                    secrets: Vec::new(),
                    description: None,
                    replicas: None,
                },
            );

            let err = rig
                .protocol
                .restore(&fixture_secret(), 7)
                .await
                .unwrap_err();
            assert!(matches!(
                err,
                crate::Error::Restore(RestoreError::AlreadyRestored)
            ));

            // No mutation: no canonical channel written.
            assert!(
                rig.channel_store
                    .load(
                        secret_id,
                        ChannelQuery::Helper {
                            channel_id: ChannelId(11),
                        },
                    )
                    .await
                    .unwrap()
                    .is_none()
            );
        });
    }

    #[test]
    fn restore_returns_conflict_on_canonical_id_collision() {
        run_async(async {
            let secret_id: u64 = 0xDE_2EC;
            let mut rig = build_rig(secret_id);
            // Pre-seed a channel sitting at canonical helper id 11.
            rig.channel_store.helper_rows.lock().unwrap().insert(
                (secret_id, 11),
                HelperChannel {
                    channel_id: ChannelId(11),
                    transports: vec![TransportProtocol {
                        uri: "https://collision.example".to_owned(),
                        protocol: 0,
                    }],
                    communication_info: HashMap::new(),
                    status: ChannelStatus::Paired,
                    created_at: 1,
                    peer_role: SenderKind::Helper,
                },
            );

            let err = rig
                .protocol
                .restore(&fixture_secret(), 7)
                .await
                .unwrap_err();
            let crate::Error::Restore(RestoreError::Conflict(ids)) = err else {
                panic!("expected Restore(Conflict), got {err:?}");
            };
            assert_eq!(ids, vec![ChannelId(11)]);

            // No mutation beyond the pre-seed.
            assert!(
                rig.user_secret_store
                    .load_latest(secret_id)
                    .await
                    .unwrap()
                    .is_none()
            );
        });
    }

    #[test]
    fn restore_invariant_error_when_replicas_present_but_group_key_missing() {
        run_async(async {
            let secret_id: u64 = 0xDE_2EC;
            let mut rig = build_rig(secret_id);
            let mut secret = fixture_secret();
            if let Some(group) = secret.replicas.as_mut() {
                group.shared_key = Vec::new();
            }

            let err = rig.protocol.restore(&secret, 7).await.unwrap_err();
            assert!(matches!(
                err,
                crate::Error::Restore(RestoreError::Invariant(_))
            ));

            // No mutation.
            assert!(
                rig.channel_store
                    .load(
                        secret_id,
                        ChannelQuery::Helper {
                            channel_id: ChannelId(11),
                        },
                    )
                    .await
                    .unwrap()
                    .is_none()
            );
        });
    }

    // ---------------- Explicit replica_id corner ----------------

    #[test]
    fn restore_does_not_overwrite_explicit_replica_id() {
        run_async(async {
            let secret_id: u64 = 0xDE_2EC;
            // Builder configured WITH a replica id — restore must leave it
            // alone even though the recovered Secret names a source member.
            let mut protocol = DeRecProtocolBuilder::new(secret_id)
                .with_channel_store(InMemChannelStore::default())
                .with_share_store(InMemShareStore::default())
                .with_secret_store(InMemSecretStore::default())
                .with_user_secret_store(InMemUserSecretStore::default())
                .with_transport(NoopTransport)
                .with_state_store(InMemStateStore)
                .with_own_transports(["https://owner.example.com"])
                .with_threshold(2)
                .with_replica_id(0x1234)
                .build()
                .expect("build");

            protocol.restore(&fixture_secret(), 7).await.unwrap();
            assert_eq!(protocol.replica_id(), Some(0x1234));
        });
    }
}