derec-library 0.1.0

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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.

//! Starting a round.
//!
//! [`DeRecProtocol::start`] takes a [`DeRecFlow`](crate::protocol::DeRecFlow) and hands it to the one
//! private starter that owns it. Each starter does only what is specific to
//! its flow — the shared work of resolving targets and dispatching lives in
//! the handlers it calls.

use super::context::{Round, local, pairing_config};
use super::events::{DeRecEvent, DeRecFlow};
use super::stores::borrow_stores;
use super::traits::{
    DeRecChannelStore, DeRecSecretStore, DeRecShareStore, DeRecStateStore, DeRecTransport,
    DeRecUserSecretStore,
};
use super::types::StateItem;
use super::{DeRecProtocol, handlers};
use crate::extensions::channel_store::ChannelStoreExt as _;
use crate::{Result, types::ChannelId};
use std::collections::{HashMap, HashSet};

use crate::Error;
use crate::derec_message;
#[cfg(target_arch = "wasm32")]
use crate::interop::wasm::now_secs;
use crate::protocol::types::Secret;
use crate::protocol::types::SharingRoundState;
use crate::protocol::types::StateKey;
use crate::protocol::types::Target;
use crate::protocol::types::UserSecret;
use crate::types::ReplicaId;
#[cfg(not(target_arch = "wasm32"))]
use crate::utils::now_secs;
use derec_proto::ContactMessage;
use derec_proto::SenderKind;
use derec_proto::TransportProtocol;

impl<
    Ch: DeRecChannelStore,
    Sh: DeRecShareStore,
    Ss: DeRecSecretStore,
    Us: DeRecUserSecretStore,
    T: DeRecTransport,
    St: DeRecStateStore,
> DeRecProtocol<Ch, Sh, Ss, Us, St, T>
{
    /// Unified entry point for initiating any protocol flow.
    ///
    /// Returns the flow's per-target `*Started` / `*Failed` events (one
    /// `PairingStarted` for [`DeRecFlow::Pairing`]; one per targeted
    /// channel for fan-out flows). See each `*Started` /
    /// `*Failed` variant on [`DeRecEvent`] for the per-flow shape.
    ///
    /// # Errors
    ///
    /// - Programmer errors (invalid input, missing preconditions, role
    ///   mismatch) surface as `Err` before any fan-out begins. Once
    ///   fan-out starts for a multi-target flow, per-channel transport
    ///   failures become `*Failed` events in the returned vec — they do
    ///   not abort the round.
    /// - Single-channel flows ([`DeRecFlow::Pairing`],
    ///   [`DeRecFlow::Unpair`]) return `Err` on send failure — no
    ///   `*Failed` event exists, so the single-`Err` signal is
    ///   unambiguous.
    #[cfg_attr(
        feature = "logging",
        tracing::instrument(skip_all, fields(trace_id = tracing::field::Empty))
    )]
    pub async fn start(&mut self, flow: DeRecFlow) -> Result<Vec<DeRecEvent>> {
        let trace_id = derec_message::fresh_trace_id();
        #[cfg(feature = "logging")]
        tracing::Span::current().record("trace_id", trace_id);
        let reply_to: Vec<TransportProtocol> = if self.auto_reply_to {
            self.own_transports.clone()
        } else {
            Vec::new()
        };
        let round = &Round {
            reply_to: &reply_to,
            trace_id,
        };

        match flow {
            DeRecFlow::Pairing {
                kind,
                contact,
                peer_communication_info,
            } => {
                self.start_pairing(kind, contact, peer_communication_info, trace_id)
                    .await
            }
            DeRecFlow::Discovery { target } => self.start_discovery(target, round).await,
            DeRecFlow::ProtectSecret {
                secrets,
                description,
                weights,
                threshold,
            } => {
                self.start_protect_secret(secrets, description, Some(weights), threshold, round)
                    .await
            }
            DeRecFlow::VerifyShares {
                secret_id,
                version,
                target,
            } => {
                self.start_verify_shares(secret_id, version, target, round)
                    .await
            }
            DeRecFlow::RecoverSecret { secret_id, version } => {
                self.start_recover_secret(secret_id, version, round).await
            }
            DeRecFlow::ReplicaDiscovery => {
                handlers::replicas::discovery::start(
                    &mut borrow_stores!(self),
                    &local!(self),
                    trace_id,
                )
                .await
            }
            DeRecFlow::UnpairReplica { replica_id, memo } => {
                let mut events = handlers::replicas::unpairing::start(
                    &mut borrow_stores!(self),
                    &local!(self),
                    replica_id,
                    memo,
                    trace_id,
                )
                .await?;
                events.extend(self.publish_after_replica_removal(round).await?);
                if self.replica_id == Some(replica_id) {
                    events.push(self.leave_replica_group().await?);
                }
                Ok(events)
            }
            DeRecFlow::Unpair { channel_id, memo } => {
                self.start_unpair(channel_id, memo, round).await
            }
            DeRecFlow::UpdateChannelInfo {
                target,
                communication_info,
                own_transports,
            } => {
                self.start_update_channel_info(target, communication_info, own_transports, trace_id)
                    .await
            }
        }
    }

    /// Rebuild this protocol's `secret_id` namespace from a
    /// [`crate::protocol::types::Secret`] handed up by a
    /// [`DeRecEvent::SecretRecovered`] event.
    ///
    /// Recovery and restore are separate steps on purpose.
    /// `SecretRecovered` writes nothing: it hands the recovered secret to the
    /// application, which shows it to the user, or asks them, before calling
    /// `restore`. Only `restore` commits it to this device.
    ///
    /// # Restore or join
    ///
    /// When [`Secret::replicas`](crate::protocol::types::Secret::replicas)
    /// names a group that still has live members, `restore` is the wrong
    /// path: offer the user to join that group as a new replica instead. Pair
    /// with a live member, confirm the fingerprint, then run
    /// [`DeRecFlow::ReplicaDiscovery`]. With no live member left, restore is
    /// the path.
    ///
    /// - Neither path gives this device the proofs of earlier versions. A
    ///   restore writes none, and a joining device gets only the share map of
    ///   the one version each push or catch-up carries, so it can verify that
    ///   version and the ones it receives later. The live members keep the
    ///   proofs they hold.
    /// - A restored device cannot take part in the group by itself: it cannot
    ///   publish, or answer a member's catch-up, until the application
    ///   configures a `replica_id` the roster names (see *Verification needs
    ///   one publish first*).
    /// - Joining keeps the group consistent: the device enters it as a new
    ///   member. Restoring next to live replicas, and then taking the lost
    ///   device's `replica_id`, makes a second device claim that member's
    ///   role.
    ///
    /// See
    /// [Restore or join](https://derec-alliance.gitbook.io/docs/concepts/replicas/restore-or-join).
    ///
    /// # Caller flow
    ///
    /// Call `restore` on the same `DeRecProtocol` instance that ran
    /// recovery — it is the one holding the recovery-mode channels this
    /// call unpairs:
    ///
    /// ```text
    /// re-pair with helpers on a fresh channel-id namespace
    ///   → start(RecoverSecret { secret_id, version })
    ///   → SecretRecovered { secret } event arrives
    ///   → DeRecProtocol::restore(&secret, version)
    /// ```
    ///
    /// What `restore` actually requires is a `secret_id` namespace with
    /// no user-secret snapshot and no channels at the roster ids it is
    /// about to write — i.e. a device that lost its state, not
    /// necessarily a newly-constructed value. See the precondition
    /// errors below for exactly what is checked.
    ///
    /// 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`
    /// with the roster's threshold
    /// ([`Secret::threshold`](crate::protocol::types::Secret::threshold));
    /// every channel under `self.secret_id` at no roster id (i.e. the
    /// recovery-mode channels) is unpaired as `start(`[`DeRecFlow::Unpair`]`)`
    /// would, under the configured
    /// [`with_unpair_ack`](crate::protocol::DeRecProtocolBuilder::with_unpair_ack):
    /// the returned events carry an `UnpairStarted` per channel, and under
    /// `UnpairAck::Required` its `Unpaired` arrives later, from `process`
    /// on the helper's answer or from the timeout sweep. The protocol
    /// resumes normal operation immediately — the next
    /// `start(ProtectSecret)` publishes `recovered_version + 1` to the
    /// restored helpers only, since a channel still being unpaired is
    /// never a publish target.
    ///
    /// A helper or replica member whose `transports` is empty gets no
    /// channel — there would be nothing to send to. It is reported as
    /// [`DeRecEvent::PeerNotRestored`] in the returned events and the rest
    /// of the roster is restored; it is neither a conflict nor wiped. See
    /// the restore handler for the full rule.
    ///
    /// The snapshot write is the commit point — nothing is removed
    /// before it succeeds. Any mid-flight failure leaves state the
    /// next `restore` call will detect as one of the precondition
    /// errors below.
    ///
    /// # Verification needs one publish first
    ///
    /// No owner-side tracking share is written, so
    /// `start(`[`DeRecFlow::VerifyShares`]`)` at `recovered_version`
    /// sends no challenge and reports each channel as
    /// [`DeRecEvent::VerifySharesFailed`]
    /// with [`VerifyFailureReason::NoProof`](crate::protocol::VerifyFailureReason::NoProof):
    /// 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, so this device has no reference bytes for that
    /// version. Run `start(`[`DeRecFlow::ProtectSecret`]`)` once —
    /// it publishes `recovered_version + 1` and writes the tracking
    /// shares that make verification work from then on.
    ///
    /// Pass that publish the stored weights unchanged: restore has written
    /// each Helper's roster weight into its
    /// [`HelperChannel::weight`](crate::protocol::types::HelperChannel::weight),
    /// and the map replaces every stored weight, so a Helper left out
    /// returns to `1`.
    ///
    /// Restore puts the threshold back too: it writes the roster's `t` into
    /// [`UserSecrets::threshold`](crate::protocol::types::UserSecrets::threshold),
    /// and every later publish splits at it, whatever the builder's
    /// [`with_threshold`](crate::protocol::DeRecProtocolBuilder::with_threshold)
    /// says. Pass no `threshold` on the follow-up publish to keep it; to
    /// change it, pass `threshold` on `start(`[`DeRecFlow::ProtectSecret`]`)`.
    /// A roster written before the threshold was recorded carries none, and
    /// the builder's threshold applies.
    ///
    /// If the restored weights do not reach the threshold —
    /// a roster recovered mid-reconfiguration, for instance — that publish
    /// still advances the version and records the restored snapshot as
    /// latest, without sending any Helper a share; see
    /// [`DeRecFlow::ProtectSecret`] for that case.
    ///
    /// When `secret.replicas` carries a group, that publish additionally
    /// requires a configured `replica_id` the roster names: restore
    /// deliberately does not adopt the roster's identity, since claiming
    /// it is a takeover with its own convergence rules. Without one the
    /// publish fails with [`crate::Error::ReplicaIdNotConfigured`] and
    /// no share reaches any Helper.
    ///
    /// # Errors
    ///
    /// Precondition / invariant failures surface as
    /// [`crate::Error::Restore`] wrapping one of:
    ///
    /// - [`RestoreError::AlreadyRestored`](crate::protocol::RestoreError::AlreadyRestored) when a user-secret
    ///   snapshot exists for this `secret_id`.
    /// - [`RestoreError::Conflict`](crate::protocol::RestoreError::Conflict) when one or more channels live
    ///   at the helper / replica ids restore is about to write.
    /// - [`RestoreError::Invariant`](crate::protocol::RestoreError::Invariant) when the recovered `Secret`
    ///   is internally inconsistent (e.g. non-empty `replicas` with
    ///   empty `replicas.shared_key`, a helper key that is not 32
    ///   bytes, or a threshold below `2`). Every roster entry is checked,
    ///   including one skipped for having no endpoint.
    ///
    /// Store I/O failures mid-restore propagate as the underlying
    /// [`crate::Error::ChannelStore`] or [`crate::Error::SecretStore`]
    /// variant, or as [`crate::Error::ShareStore`] — which the
    /// user-secret store reuses for the snapshot write, restore having
    /// no share writes of its own.
    #[cfg_attr(feature = "logging", tracing::instrument(skip_all))]
    pub async fn restore(
        &mut self,
        secret: &Secret,
        recovered_version: u32,
    ) -> Result<Vec<DeRecEvent>> {
        handlers::restore::restore(
            &mut borrow_stores!(self),
            &local!(self),
            secret,
            recovered_version,
            self.unpair_ack,
        )
        .await
    }

    /// Publish the roster that completes a replica removal, right after
    /// [`handlers::replicas::unpairing::start`] took the member out.
    ///
    /// The latest snapshot is published, or an empty payload when there is
    /// none: the roster is what the removal needs. It reaches every remaining
    /// member and the helpers; the departing member is no longer on the
    /// distribution list.
    async fn publish_after_replica_removal(
        &mut self,
        round: &Round<'_>,
    ) -> Result<Vec<DeRecEvent>> {
        let (secrets, description) = self
            .user_secret_store
            .load_latest(self.secret_id)
            .await?
            .map(|held| (held.secrets, held.description))
            .unwrap_or_default();
        self.start_protect_secret(secrets, description, None, None, round)
            .await
    }

    /// Drop this device's whole `secret_id` partition after it removed itself
    /// from the replica group and published the roster without it.
    async fn leave_replica_group(&mut self) -> Result<DeRecEvent> {
        let version = self
            .user_secret_store
            .load_latest(self.secret_id)
            .await?
            .map_or(0, |held| held.version);
        handlers::replicas::unpairing::tear_down(&mut borrow_stores!(self), &local!(self)).await?;
        let _ = self
            .state_store
            .remove(self.secret_id, StateKey::SharingRound { version })
            .await;

        #[cfg(feature = "logging")]
        tracing::info!(version, "left the replica group; partition dropped");

        Ok(DeRecEvent::SelfRemovedFromGroup { version })
    }

    /// Run one publish round: VSS-split for Helpers when the threshold is
    /// met, build the Replica composite payload with the share material
    /// embedded, and fan both out. A no-op (silent return) when no paired
    /// Helpers or Replicas exist.
    ///
    /// Below `threshold`, the split is skipped and no event is returned for
    /// any Helper; paired Replicas, if any, still get a secret-only
    /// composite and their usual events. With no Replicas paired either,
    /// this returns `Ok` with an empty vec — the version still advanced and
    /// the snapshot is saved, so the omission is silent on purpose, not a
    /// dropped round.
    ///
    /// Only targets whose dispatch succeeded join the round's pending set: a
    /// peer that could not be reached will never answer, so counting it would
    /// hold the round open until its timeout. Such a peer is reported once
    /// here, where the transport error is still in hand, and settles as
    /// `behind`.
    ///
    /// `weights` is the full assignment for an explicit
    /// [`DeRecFlow::ProtectSecret`](crate::protocol::DeRecFlow::ProtectSecret):
    /// every paired Helper it does not name gets `1`. Publishes the library
    /// starts on its own pass `None`, which reuses each Helper's stored
    /// weight. Each Helper's dispatch event reports the weight it was given.
    ///
    /// `threshold` is the explicit threshold of a
    /// [`DeRecFlow::ProtectSecret`](crate::protocol::DeRecFlow::ProtectSecret).
    /// Publishes the library starts on its own pass `None`, which reuses the
    /// stored threshold, or the builder's when none is stored.
    pub(super) async fn start_protect_secret(
        &mut self,
        secrets: Vec<UserSecret>,
        description: Option<String>,
        weights: Option<HashMap<ChannelId, u32>>,
        threshold: Option<u32>,
        round: &Round<'_>,
    ) -> Result<Vec<DeRecEvent>> {
        let Some(result) = handlers::sharing::start(
            &mut borrow_stores!(self),
            &local!(self),
            secrets,
            description,
            weights.as_ref(),
            threshold,
            self.threshold,
            self.max_subshares,
            round,
        )
        .await?
        else {
            return Ok(Vec::new());
        };

        let version = result.version;
        let pending: HashSet<ChannelId> = result
            .outcomes
            .iter()
            .filter_map(|(cid, r)| r.as_ref().ok().map(|_| *cid))
            .collect();
        let pending_replicas: HashSet<ReplicaId> = result
            .replica_outcomes
            .iter()
            .filter_map(|(rid, r)| r.as_ref().ok().map(|_| *rid))
            .collect();
        let behind_replicas: HashSet<ReplicaId> = result
            .replica_outcomes
            .iter()
            .filter_map(|(rid, r)| r.as_ref().err().map(|_| *rid))
            .collect();

        let mut undeliverable: Vec<DeRecEvent> = result
            .replica_outcomes
            .iter()
            .filter_map(|(rid, r)| {
                r.as_ref().err().map(|e| DeRecEvent::ReplicaSyncFailed {
                    replica_id: rid.0,
                    version,
                    reason: e.to_string(),
                })
            })
            .collect();

        if !pending.is_empty() || !pending_replicas.is_empty() {
            self.state_store
                .save(
                    self.secret_id,
                    StateItem::SharingRound(Box::new(SharingRoundState {
                        version,
                        pending,
                        confirmed: HashSet::new(),
                        failed: HashSet::new(),
                        pending_replicas,
                        synced_replicas: HashSet::new(),
                        behind_replicas,
                        started_at: now_secs(),
                        keep_version: result.keep_version,
                        threshold: result.threshold,
                    })),
                )
                .await?;
        }

        let mut started: Vec<DeRecEvent> = result
            .outcomes
            .into_iter()
            .map(|(channel_id, res)| {
                let weight = result.weights.get(&channel_id).copied().unwrap_or(1);
                match res {
                    Ok(()) => DeRecEvent::ProtectSecretStarted {
                        channel_id,
                        version,
                        trace_id: round.trace_id,
                        weight,
                    },
                    Err(e) => DeRecEvent::ProtectSecretFailed {
                        channel_id,
                        version,
                        error: e.to_string(),
                        weight,
                    },
                }
            })
            .collect();
        started.append(&mut undeliverable);
        Ok(started)
    }

    async fn start_pairing(
        &mut self,
        kind: SenderKind,
        contact: ContactMessage,
        peer_communication_info: HashMap<String, String>,
        trace_id: u64,
    ) -> Result<Vec<DeRecEvent>> {
        let channel_id = handlers::pairing::start(
            &mut borrow_stores!(self),
            &local!(self),
            &pairing_config!(self),
            kind,
            contact,
            peer_communication_info,
            trace_id,
        )
        .await?;
        Ok(vec![DeRecEvent::PairingStarted {
            channel_id: ChannelId(channel_id),
            kind,
            trace_id,
        }])
    }

    async fn start_discovery(
        &mut self,
        target: Target,
        round: &Round<'_>,
    ) -> Result<Vec<DeRecEvent>> {
        let resolved = self
            .channel_store
            .resolve_target(self.secret_id, target.clone())
            .await?;
        self.channel_store
            .require_role(
                self.secret_id,
                &resolved, // Owner-initiated flow: every target must be a Helper peer.
                SenderKind::Helper,
            )
            .await?;
        handlers::discovery::start(&mut borrow_stores!(self), &local!(self), target, round).await
    }

    async fn start_verify_shares(
        &mut self,
        secret_id: u64,
        version: u32,
        target: Target,
        round: &Round<'_>,
    ) -> Result<Vec<DeRecEvent>> {
        // Verification only ever challenges the helpers holding this
        // instance's own shares, so the flow's `secret_id` has one legal
        // value. Refusing anything else turns a caller's mistaken belief that
        // it was verifying a different secret into an error, rather than
        // reporting success for a secret it never touched.
        if secret_id != self.secret_id {
            return Err(Error::InvalidInput(
                "VerifyShares secret_id must be this instance's own secret_id",
            ));
        }
        let resolved = self
            .channel_store
            .resolve_target(self.secret_id, target.clone())
            .await?;
        self.channel_store
            .require_role(
                self.secret_id,
                &resolved, // Owner-initiated flow: every target must be a Helper peer.
                SenderKind::Helper,
            )
            .await?;
        handlers::verification::start(
            &mut borrow_stores!(self),
            &local!(self),
            version,
            target,
            round,
        )
        .await
    }

    /// No role gate is applied before the fan-out. An instance legitimately
    /// holds replica channels alongside its helper pairings, so requiring
    /// every resolved channel to be Owner-role would abort the recovery over a
    /// peer that was never a target. The handler selects the Owner-role,
    /// `Paired` channels itself.
    async fn start_recover_secret(
        &mut self,
        secret_id: u64,
        version: u32,
        round: &Round<'_>,
    ) -> Result<Vec<DeRecEvent>> {
        handlers::recovery::start(
            &mut borrow_stores!(self),
            &local!(self),
            secret_id,
            version,
            round,
        )
        .await
    }

    /// Emits `UnpairStarted`. When the channel needs no acknowledgement the
    /// handler returns `Unpaired` immediately, interleaved after it; otherwise
    /// the channel is `Unpairing` and `Unpaired` arrives later, from
    /// [`process`](Self::process) on the response or from the timeout sweep.
    async fn start_unpair(
        &mut self,
        channel_id: ChannelId,
        memo: Option<String>,
        round: &Round<'_>,
    ) -> Result<Vec<DeRecEvent>> {
        self.channel_store
            .require_role(
                self.secret_id,
                &[channel_id], // Owner-initiated teardown: the peer must be a Helper.
                SenderKind::Helper,
            )
            .await?;
        handlers::unpairing::start(
            &mut borrow_stores!(self),
            &local!(self),
            channel_id,
            memo,
            self.unpair_ack,
            false,
            round,
        )
        .await
    }

    async fn start_update_channel_info(
        &mut self,
        target: Target,
        communication_info: Option<HashMap<String, String>>,
        own_transports: Vec<TransportProtocol>,
        trace_id: u64,
    ) -> Result<Vec<DeRecEvent>> {
        handlers::update_channel_info::start(
            &mut borrow_stores!(self),
            &local!(self),
            target,
            communication_info,
            own_transports,
            trace_id,
        )
        .await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::protocol::builder::DeRecProtocolBuilder;
    use crate::protocol::tests::{
        InMemChannelStore, InMemPersistedStateStore, InMemSecretStore, InMemShareStore,
        InMemUserSecretStore, StoreRig, run_async,
    };
    use crate::protocol::types::Share;
    use crate::protocol::types::{ChannelRecord, ChannelStatus, HelperChannel, SecretValue};
    use crate::protocol::{DeRecChannelStore, DeRecSecretStore, DeRecShareStore};
    use derec_proto::Protocol;

    const SECRET_ID: u64 = 0x7E57;

    async fn seed_helper(
        channels: &mut InMemChannelStore,
        secrets: &mut InMemSecretStore,
        cid: u64,
        key_byte: u8,
    ) {
        let channel_id = ChannelId(cid);
        channels
            .save(
                SECRET_ID,
                ChannelRecord::Helper(HelperChannel {
                    channel_id,
                    transports: vec![TransportProtocol {
                        uri: format!("https://helper-{cid}.example"),
                        protocol: Protocol::Https as i32,
                    }],
                    communication_info: HashMap::new(),
                    peer_role: SenderKind::Helper,
                    status: ChannelStatus::Paired,
                    created_at: 0,
                    weight: 1,
                }),
            )
            .await
            .expect("seed helper");
        secrets
            .save(
                SECRET_ID,
                channel_id,
                SecretValue::SharedKey([key_byte; 32]),
            )
            .await
            .expect("seed key");
    }

    /// One `start` is one round, so every request it fans out carries the
    /// same token and the `*Started` events report that same value.
    ///
    /// Without this the caller has nothing to correlate a round by: each
    /// dispatch used to draw its own token, so a publish to three helpers
    /// produced three unrelated traces.
    #[test]
    fn one_round_shares_one_trace_id_across_its_fan_out() {
        run_async(async {
            let rig = StoreRig::new();
            let mut channels = rig.channels.clone();
            let mut secrets = rig.secrets.clone();
            seed_helper(&mut channels, &mut secrets, 11, 0xA1).await;
            seed_helper(&mut channels, &mut secrets, 12, 0xA2).await;
            seed_helper(&mut channels, &mut secrets, 13, 0xA3).await;

            let mut protocol = DeRecProtocolBuilder::new(SECRET_ID)
                .with_channel_store(channels)
                .with_share_store(InMemShareStore::default())
                .with_secret_store(secrets)
                .with_user_secret_store(InMemUserSecretStore::default())
                .with_state_store(InMemPersistedStateStore::default())
                .with_transport(rig.transport.clone())
                .with_own_transports(["https://owner.example"])
                .build()
                .expect("test rig builds");

            let events = protocol
                .start(DeRecFlow::Discovery {
                    target: Target::All,
                })
                .await
                .expect("discovery starts");

            let on_the_wire: Vec<u64> = rig
                .transport
                .sent_envelopes()
                .iter()
                .map(|e| derec_message::read_trace_id(e).expect("envelope decodes"))
                .collect();
            assert_eq!(on_the_wire.len(), 3, "one request per helper");
            assert!(
                on_the_wire.windows(2).all(|w| w[0] == w[1]),
                "every request in the round carries one token, got {on_the_wire:?}"
            );
            assert_ne!(on_the_wire[0], 0, "the round must draw a token");

            let reported: Vec<u64> = events
                .iter()
                .filter_map(|e| match e {
                    DeRecEvent::DiscoveryStarted { trace_id, .. } => Some(*trace_id),
                    _ => None,
                })
                .collect();
            assert_eq!(
                reported,
                vec![on_the_wire[0]; 3],
                "each DiscoveryStarted reports the token its request carried"
            );
        });
    }

    /// `VerifyShares` carries a `secret_id` that has exactly one legal value:
    /// verification challenges the helpers holding *this* device's shares.
    /// A caller passing another id is told so, rather than being reported
    /// success for a secret the round never touched.
    #[test]
    fn verify_shares_refuses_a_foreign_secret_id() {
        run_async(async {
            let rig = StoreRig::new();
            let mut protocol = DeRecProtocolBuilder::new(SECRET_ID)
                .with_channel_store(rig.channels.clone())
                .with_share_store(InMemShareStore::default())
                .with_secret_store(rig.secrets.clone())
                .with_user_secret_store(InMemUserSecretStore::default())
                .with_state_store(rig.state.clone())
                .with_transport(rig.transport.clone())
                .with_own_transports(["https://owner.example"])
                .build()
                .expect("test rig builds");

            let err = protocol
                .start(DeRecFlow::VerifyShares {
                    secret_id: SECRET_ID ^ 0xFFFF,
                    version: 1,
                    target: Target::All,
                })
                .await
                .expect_err("a foreign secret_id must be refused");
            assert!(
                matches!(err, Error::InvalidInput(_)),
                "expected InvalidInput, got {err:?}"
            );

            // The instance's own id is accepted — the guard rejects the
            // mismatch, not the flow.
            protocol
                .start(DeRecFlow::VerifyShares {
                    secret_id: SECRET_ID,
                    version: 1,
                    target: Target::All,
                })
                .await
                .expect("this instance's own secret_id is the legal value");
        });
    }

    /// A broadcast flow reaches every paired helper and skips one still
    /// `Pending`: that channel has no shared key yet, so including it would
    /// fail the key load for the whole fan-out.
    #[test]
    fn broadcast_flows_skip_a_pending_channel() {
        run_async(async {
            let rig = StoreRig::new();
            let mut channels = rig.channels.clone();
            let mut secrets = rig.secrets.clone();
            seed_helper(&mut channels, &mut secrets, 11, 0xA1).await;
            channels
                .save(
                    SECRET_ID,
                    ChannelRecord::Helper(HelperChannel {
                        channel_id: ChannelId(12),
                        transports: vec![TransportProtocol {
                            uri: "https://helper-12.example".to_owned(),
                            protocol: Protocol::Https as i32,
                        }],
                        communication_info: HashMap::new(),
                        peer_role: SenderKind::Helper,
                        status: ChannelStatus::Pending,
                        created_at: 0,
                        weight: 1,
                    }),
                )
                .await
                .expect("seed pending helper");

            let mut shares = InMemShareStore::default();
            shares
                .save(
                    SECRET_ID,
                    ChannelId(11),
                    Share {
                        secret_id: SECRET_ID,
                        version: 1,
                        bytes: vec![0x11; 8],
                        subshares: None,
                        threshold: None,
                    },
                )
                .await
                .expect("seed the proof VerifyShares checks the answer against");

            let mut protocol = DeRecProtocolBuilder::new(SECRET_ID)
                .with_channel_store(channels)
                .with_share_store(shares)
                .with_secret_store(secrets)
                .with_user_secret_store(InMemUserSecretStore::default())
                .with_state_store(InMemPersistedStateStore::default())
                .with_transport(rig.transport.clone())
                .with_own_transports(["https://owner.example"])
                .build()
                .expect("test rig builds");

            let flows = [
                (
                    "UpdateChannelInfo",
                    DeRecFlow::UpdateChannelInfo {
                        target: Target::All,
                        communication_info: Some(HashMap::from([(
                            "name".to_owned(),
                            "owner".to_owned(),
                        )])),
                        own_transports: Vec::new(),
                    },
                ),
                (
                    "Discovery",
                    DeRecFlow::Discovery {
                        target: Target::All,
                    },
                ),
                (
                    "VerifyShares",
                    DeRecFlow::VerifyShares {
                        secret_id: SECRET_ID,
                        version: 1,
                        target: Target::All,
                    },
                ),
            ];
            for (name, flow) in flows {
                let sent_before = rig.transport.sent_uris().len();
                let events = protocol
                    .start(flow)
                    .await
                    .unwrap_or_else(|e| panic!("{name} must start: {e:?}"));

                assert_eq!(
                    rig.transport.sent_uris()[sent_before..],
                    ["https://helper-11.example".to_owned()],
                    "{name} reaches the paired helper only"
                );
                let started: Vec<ChannelId> = events
                    .iter()
                    .filter_map(|e| match e {
                        DeRecEvent::UpdateChannelInfoStarted { channel_id, .. }
                        | DeRecEvent::DiscoveryStarted { channel_id, .. }
                        | DeRecEvent::VerifySharesStarted { channel_id, .. } => Some(*channel_id),
                        _ => None,
                    })
                    .collect();
                assert_eq!(started, vec![ChannelId(11)], "{name}: {events:?}");
            }
        });
    }

    /// Two rounds are two traces — the token is per-`start`, not per-process.
    #[test]
    fn separate_rounds_draw_separate_trace_ids() {
        run_async(async {
            let rig = StoreRig::new();
            let mut channels = rig.channels.clone();
            let mut secrets = rig.secrets.clone();
            seed_helper(&mut channels, &mut secrets, 11, 0xA1).await;

            let mut protocol = DeRecProtocolBuilder::new(SECRET_ID)
                .with_channel_store(channels)
                .with_share_store(InMemShareStore::default())
                .with_secret_store(secrets)
                .with_user_secret_store(InMemUserSecretStore::default())
                .with_state_store(InMemPersistedStateStore::default())
                .with_transport(rig.transport.clone())
                .with_own_transports(["https://owner.example"])
                .build()
                .expect("test rig builds");

            for _ in 0..2 {
                protocol
                    .start(DeRecFlow::Discovery {
                        target: Target::All,
                    })
                    .await
                    .expect("discovery starts");
            }

            let tokens: Vec<u64> = rig
                .transport
                .sent_envelopes()
                .iter()
                .map(|e| derec_message::read_trace_id(e).expect("envelope decodes"))
                .collect();
            assert_eq!(tokens.len(), 2);
            assert_ne!(tokens[0], tokens[1], "each round draws its own token");
        });
    }
}

/// The round token is on the span, not just on the wire.
///
/// Every handler entered from [`DeRecProtocol::start`] records it through
/// `#[instrument(fields(trace_id = …))]`, so a log line emitted anywhere
/// under a round is attributable to it. This drives a real instrumented
/// handler rather than a hand-built span, which is what makes it a
/// regression net for the attribute itself.
#[cfg(all(test, feature = "logging"))]
mod trace_id_span_tests {
    use crate::protocol::DeRecFlow;
    use crate::protocol::builder::DeRecProtocolBuilder;
    use crate::protocol::handlers::replicas::discovery;
    use crate::protocol::tests::InMemShareStore;
    use crate::protocol::tests::InMemUserSecretStore;
    use crate::protocol::tests::LocalFixture;
    use crate::protocol::tests::{StoreRig, run_async};
    use crate::protocol::types::Target;
    use std::io;
    use std::sync::{Arc, Mutex};

    #[derive(Clone, Default)]
    struct Captured(Arc<Mutex<Vec<u8>>>);

    impl io::Write for Captured {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.0.lock().unwrap().extend_from_slice(buf);
            Ok(buf.len())
        }
        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    impl Captured {
        fn text(&self) -> String {
            String::from_utf8_lossy(&self.0.lock().unwrap()).into_owned()
        }
    }

    #[test]
    fn a_handler_span_carries_the_round_token() {
        const TRACE_ID: u64 = 0xDEC0_DE15;

        let captured = Captured::default();
        let sink = captured.clone();
        // Span lifecycle events are what carry the recorded fields: the
        // handler's span opens and closes inside `start`, so nothing this
        // test emits itself would sit under it.
        let subscriber = tracing_subscriber::fmt()
            .with_writer(move || sink.clone())
            .with_ansi(false)
            .with_max_level(tracing::Level::TRACE)
            .with_span_events(tracing_subscriber::fmt::format::FmtSpan::NEW)
            .finish();

        tracing::subscriber::with_default(subscriber, || {
            run_async(async {
                let mut rig = StoreRig::new();
                let lf = LocalFixture::with_replica(0x5EC, 1001);
                // No peers, so the flow returns immediately — the span is
                // still entered, which is all this asserts.
                let _ = discovery::start(&mut rig.stores(), &lf.local(), TRACE_ID).await;
            });
        });

        let text = captured.text();
        assert!(
            text.contains(&TRACE_ID.to_string()),
            "the handler's `fields(trace_id = ...)` must reach the subscriber; got: {text}"
        );
    }

    /// `start` draws its token inside the body, so its span declares the field
    /// empty and records it after the draw. That is a different mechanism from
    /// the attribute above, and it has its own way of silently not working.
    #[test]
    fn the_start_span_records_the_token_it_draws() {
        let captured = Captured::default();
        let sink = captured.clone();
        let subscriber = tracing_subscriber::fmt()
            .with_writer(move || sink.clone())
            .with_ansi(false)
            .with_max_level(tracing::Level::TRACE)
            .with_span_events(tracing_subscriber::fmt::format::FmtSpan::CLOSE)
            .finish();

        tracing::subscriber::with_default(subscriber, || {
            run_async(async {
                let rig = StoreRig::new();
                let mut protocol = DeRecProtocolBuilder::new(0x5EC)
                    .with_channel_store(rig.channels.clone())
                    .with_share_store(InMemShareStore::default())
                    .with_secret_store(rig.secrets.clone())
                    .with_user_secret_store(InMemUserSecretStore::default())
                    .with_state_store(rig.state.clone())
                    .with_transport(rig.transport.clone())
                    .with_own_transports(["https://owner.example"])
                    .build()
                    .expect("test rig builds");
                let _ = protocol
                    .start(DeRecFlow::Discovery {
                        target: Target::All,
                    })
                    .await;
            });
        });

        let text = captured.text();
        let recorded = text
            .lines()
            .find(|l| l.contains("start"))
            .unwrap_or_default();
        assert!(
            recorded.contains("trace_id"),
            "`start`'s span must carry the token it drew; got: {text}"
        );
        assert!(
            !recorded.contains("trace_id=Empty"),
            "the field must be recorded, not left empty; got: {recorded}"
        );
    }
}