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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.
use crateSharingError;
use crateTransportProtocolExt as _;
use crate::;
use vss;
use ;
use Message;
use HashMap;
/// Current share algorithm identifier embedded into [`derec_proto::StoreShareRequestMessage`].
///
/// At present the sharing flow uses the library's VSS-based share generation and
/// encodes that choice using the protocol value `0`.
const SHARE_ALGORITHM_VSS: i32 = 0;
/// `share` bytes carry a **full `Secret` payload** (`DeRecSecret` proto)
/// instead of a single VSS share fragment. Used on replica channels —
/// every replica holds an identical copy of the secret rather than a
/// reconstructable fragment of it.
///
/// Disambiguates the payload semantics on the wire; the receiver's
/// `Channel.role` is the authoritative source of truth, but a distinct
/// `share_algorithm` value lets wire dumps and middle-boxes tell the two
/// payload shapes apart without channel-state context.
pub const SHARE_ALGORITHM_REPLICA_SECRET: i32 = 1;
/// Splits a secret into verifiable committed shares, one per Helper channel.
///
/// In DeRec, the *sharing* flow splits a secret into independently verifiable
/// shares using a Verifiable Secret Sharing (VSS) scheme. Each generated share is:
///
/// - Bound to a specific `secret_id` and `version`
/// - Committed using a Merkle commitment and proof
/// - Returned as a [`CommittedDeRecShare`] ready to be delivered to its Helper
///
/// To send a share to a Helper, pass the returned [`CommittedDeRecShare`] to
/// [`produce`] together with the Helper's shared key to produce the encrypted
/// delivery envelope.
///
/// # Deterministic channel/share assignment
///
/// The input `channels` slice is sorted by [`ChannelId`] before shares are assigned.
/// Generated VSS shares are assigned in that sorted order. Duplicate channel IDs are
/// rejected with [`SharingError::DuplicateChannelId`].
///
/// # Arguments
///
/// * `channels` - Slice of Helper [`ChannelId`] values. Each entry receives exactly
/// one committed share. Must not be empty. Duplicate entries are rejected.
/// * `secret_id` - Identifier of the secret being protected. Embedded into each
/// generated share. Must not be empty.
/// * `version` - Logical version of this secret distribution. Embedded into each
/// generated share.
/// * `secret_data` - Raw secret bytes to split using VSS. Must not be empty.
/// * `threshold` - Minimum number of shares required to reconstruct the secret.
/// Must satisfy `2 <= threshold <= channels.len()`.
///
/// # Returns
///
/// On success returns [`SplitResult`] containing:
///
/// - `shares`: `HashMap<ChannelId, CommittedDeRecShare>` — one committed share per channel.
///
/// # Errors
///
/// Returns [`crate::Error`] (specifically `Error::Sharing(...)`) in the following cases:
///
/// - [`SharingError::EmptyChannels`] if `channels` is empty
/// - [`SharingError::EmptySecretData`] if `secret_data` is empty
/// - [`SharingError::DuplicateChannelId`] if `channels` contains any repeated ID
/// - [`SharingError::InvalidThreshold`] if `threshold` does not satisfy
/// `2 <= threshold <= channels.len()`
/// - [`SharingError::VssShareFailed`] if the underlying VSS algorithm fails
///
/// # Security Notes
///
/// - The caller is responsible for securely managing the original `secret_data`.
///
/// # Example
///
/// ```
/// use derec_library::primitives::sharing::request::{split, SplitResult};
/// use derec_library::types::ChannelId;
///
/// let channels = [ChannelId(1), ChannelId(2), ChannelId(3)];
///
/// let SplitResult { shares } = split(
/// &channels,
/// 1,
/// 1,
/// b"super_secret_value",
/// 2,
/// ).expect("split failed");
///
/// assert_eq!(shares.len(), 3);
/// ```
/// Produces an encrypted [`derec_proto::DeRecMessage`] envelope wrapping a
/// [`CommittedDeRecShare`] as a [`derec_proto::StoreShareRequestMessage`] inner payload.
///
/// Call this once for each share returned by [`split`], providing the corresponding
/// Helper's shared key (established during pairing). The resulting wire bytes should be
/// sent to the Helper over the channel transport. On the Helper side, the inner
/// [`derec_proto::StoreShareRequestMessage`] extracted by [`extract`] must be retained
/// for future verification and recovery flows.
///
/// # Arguments
///
/// * `channel_id` - The Helper channel this share belongs to.
/// * `version` - Share-distribution version, matching the value passed to [`split`].
/// * `secret_id` - Identifier of the secret being distributed. Must match the value
/// passed to [`split`].
/// * `committed_share` - The share for this channel, as returned by [`split`].
/// * `keep_list` - Ordered list of version numbers the Helper should retain. Pass an empty
/// slice to let the Helper apply its default retention policy.
/// * `description` - Human-readable description of this share distribution. May be empty.
/// * `shared_key` - Previously established 32-byte symmetric channel key used to
/// encrypt the inner request.
///
/// # Returns
///
/// On success returns [`ProduceResult`] containing:
///
/// - `envelope`: serialized [`derec_proto::DeRecMessage`] wire bytes carrying an encrypted
/// [`derec_proto::StoreShareRequestMessage`].
///
/// # Errors
///
/// Returns [`crate::Error`] if envelope construction or symmetric encryption fails.
///
/// # Example
///
/// ```
/// use derec_library::primitives::sharing::request::{split, produce, SplitResult, ProduceResult};
/// use derec_library::types::ChannelId;
///
/// let channels = [ChannelId(1), ChannelId(2), ChannelId(3)];
/// let SplitResult { shares } = split(&channels, 1, 1, b"super_secret_value", 2)
/// .expect("split failed");
///
/// let shared_key = [42u8; 32];
/// let channel_id = ChannelId(1);
/// let committed_share = shares.get(&channel_id).expect("missing share");
///
/// let ProduceResult { envelope } =
/// produce(channel_id, 1, 1, committed_share, &[], "", &shared_key, None, None)
/// .expect("produce failed");
///
/// assert!(!envelope.is_empty());
/// ```
/// Decrypts and decodes an incoming [`StoreShareRequestMessage`] from an outer envelope.
///
/// Call this on the **Helper** side after receiving a sharing request from an Owner.
/// The function:
///
/// 1. Decodes the outer [`derec_proto::DeRecMessage`] envelope from `envelope_bytes`
/// 2. Decrypts and decodes the inner [`StoreShareRequestMessage`] using `shared_key`
/// 3. Validates the invariant `envelope.timestamp == request.timestamp`
/// 4. If the request carries a `reply_to`, validates it via
/// [`crate::transport::TransportProtocol::validate`] — same gate the
/// orchestrator runs and the FFI/WASM seams enforce. A mismatched scheme
/// or otherwise malformed peer-supplied endpoint is rejected here, so
/// callers handing the extracted request to
/// [`crate::primitives::sharing::response::produce`] can trust the
/// `reply_to` is structurally sound. Note the asymmetry: [`produce`]
/// on this side does NOT validate the application-supplied `reply_to`
/// on outbound requests; the FFI/WASM seams do, and Rust-direct callers
/// using [`produce`] are responsible for handing in a well-formed
/// `reply_to` themselves.
///
/// The extracted [`StoreShareRequestMessage`] should be passed to
/// [`crate::primitives::sharing::response::produce`] to build the acknowledgement
/// response. The Helper must also persist the [`StoreShareRequestMessage`] itself (e.g.
/// as serialized bytes via `.encode_to_vec()`) for future verification and recovery flows.
///
/// # Arguments
///
/// * `envelope_bytes` - Serialized [`derec_proto::DeRecMessage`] wire bytes received from
/// the Owner, as produced by [`produce`].
/// * `shared_key` - Previously established 32-byte symmetric channel key used to
/// decrypt the inner message.
///
/// # Returns
///
/// On success returns [`ExtractResult`] containing:
///
/// - `request`: the decrypted inner [`derec_proto::StoreShareRequestMessage`].
///
/// # Errors
///
/// Returns [`crate::Error`] if:
///
/// - `envelope_bytes` cannot be decoded as a valid [`derec_proto::DeRecMessage`]
/// - decryption or inner-message decoding fails
/// - the inner message is not a [`derec_proto::StoreShareRequestMessage`]
/// - `envelope.timestamp != request.timestamp`
/// - [`crate::Error::Transport`] if `request.reply_to` is present and fails
/// [`crate::transport::TransportProtocol::validate`] (unknown protocol
/// discriminant, mismatched scheme, oversize URI, etc.)
///
/// # Security Notes
///
/// - The decrypted [`derec_proto::StoreShareRequestMessage`] carries the committed share the
/// Helper must persist for future verification and recovery; treat it as sensitive material
/// and store it securely.
/// - **No freshness or replay protection.** The timestamp check
/// enforced here only binds the envelope to the inner body
/// (`envelope.timestamp == body.timestamp`). It does NOT enforce
/// a freshness window against the receiver's clock and does NOT
/// detect replays of a previously-captured ciphertext. Because
/// the channel key is long-lived, a recorded envelope stays
/// decryptable indefinitely. Callers MUST add a freshness window
/// and per-channel anti-replay (monotonic counter or nonce log)
/// on top before driving any side-effecting state off the parsed
/// body.
///
/// # Example
///
/// ```
/// use derec_library::primitives::sharing::request::{split, produce, extract, SplitResult, ProduceResult, ExtractResult};
/// use derec_library::types::ChannelId;
///
/// let channels = [ChannelId(1), ChannelId(2), ChannelId(3)];
/// let SplitResult { shares } = split(&channels, 1, 1, b"super_secret_value", 2)
/// .expect("split failed");
///
/// let channel_id = ChannelId(1);
/// let shared_key = [42u8; 32];
/// let committed_share = shares.get(&channel_id).expect("missing share");
///
/// let ProduceResult { envelope } =
/// produce(channel_id, 1, 1, committed_share, &[], "", &shared_key, None, None)
/// .expect("produce failed");
///
/// let ExtractResult { request } = extract(&envelope, &shared_key).expect("extract failed");
///
/// assert_eq!(request.secret_id, 1);
/// assert_eq!(request.version, 1);
/// ```