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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.
use crateSharingError;
use crate::;
use vss;
use ;
use Message;
/// Produces an encrypted response envelope acknowledging an incoming
/// [`derec_proto::StoreShareRequestMessage`] on behalf of a Helper, and returns the
/// committed share to persist locally.
///
/// This function is executed by a **Helper** upon receiving a sharing request from an Owner.
/// It:
///
/// 1. Validates the `share` field of the provided `request` is non-empty
/// 2. Decodes the embedded [`derec_proto::CommittedDeRecShare`] from the `share` field
/// 3. Validates that `de_rec_share`, `commitment`, and `merkle_path` are non-empty
/// 4. Decodes `de_rec_share` as a [`derec_proto::DeRecShare`] to extract `(x, y)` coordinates
/// 5. Verifies the Merkle proof: recomputes the root from `(x, y)` and the path,
/// and rejects the share if it does not match `commitment`
/// 6. Constructs a [`derec_proto::StoreShareResponseMessage`] with `status = Ok`
/// 7. Encrypts and wraps the response into a new [`derec_proto::DeRecMessage`] envelope
///
/// The Helper must persist `committed_share` from the returned result for future verification
/// and recovery requests.
///
/// # Arguments
///
/// * `channel_id` - The channel this request arrived on. Used to build the response envelope.
/// * `request` - The decoded [`derec_proto::StoreShareRequestMessage`] received from the Owner,
/// as extracted from the wire envelope.
/// * `shared_key` - Previously established 32-byte symmetric channel key used to
/// encrypt the inner response.
///
/// # Returns
///
/// On success returns [`ProduceResult`] containing:
///
/// - `envelope`: serialized response [`derec_proto::DeRecMessage`] to send back to the Owner
/// - `committed_share`: the [`derec_proto::CommittedDeRecShare`] extracted from the request, ready to store
/// - `secret_id`: the secret identifier extracted from the inner [`derec_proto::DeRecShare`]
/// - `version`: the share-distribution version extracted from the request
///
/// # Errors
///
/// Returns [`crate::Error`] if:
///
/// - the `share` field of the request is empty
/// - the `share` field cannot be decoded as a valid [`derec_proto::CommittedDeRecShare`]
/// - `CommittedDeRecShare.de_rec_share` is empty
/// - `CommittedDeRecShare.commitment` is empty
/// - `CommittedDeRecShare.merkle_path` is empty
/// - `CommittedDeRecShare.de_rec_share` cannot be decoded as a valid [`derec_proto::DeRecShare`]
/// - the Merkle proof does not verify against `commitment`
/// - response envelope construction or encryption fails
///
/// # Security Notes
///
/// - This function verifies the Merkle proof against the embedded `commitment` before accepting
/// the share. A failed verification is treated as a protocol violation and rejected.
/// - The returned `committed_share` must be persisted securely; it is the input the Helper will
/// later use to answer verification and recovery requests.
///
/// # Example
///
/// ```
/// use derec_library::primitives::sharing::{request, response};
/// use derec_library::types::ChannelId;
///
/// let channels = [ChannelId(1), ChannelId(2), ChannelId(3)];
/// let request::SplitResult { shares } = request::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");
///
/// // Owner: build the sharing request envelope.
/// let request::ProduceResult { envelope: req_envelope } =
/// request::produce(channel_id, 1, 1, committed_share, &[], "", &shared_key, None, None)
/// .expect("produce request failed");
///
/// // Helper: extract the request, then build the response.
/// let request::ExtractResult { request: share_request } =
/// request::extract(&req_envelope, &shared_key).expect("extract request failed");
///
/// let response::ProduceResult { envelope, secret_id, version, .. } =
/// response::produce(channel_id, &share_request, &shared_key)
/// .expect("produce response failed");
///
/// assert!(!envelope.is_empty());
/// assert_eq!(secret_id, 1);
/// assert_eq!(version, 1);
/// ```
/// Decrypts and decodes an incoming [`derec_proto::StoreShareResponseMessage`] from an outer
/// [`derec_proto::DeRecMessage`] envelope.
///
/// This function:
///
/// 1. Decodes the outer [`derec_proto::DeRecMessage`] envelope from `envelope_bytes`
/// 2. Decrypts and decodes the inner [`derec_proto::StoreShareResponseMessage`] using
/// `shared_key`
/// 3. Validates the invariant `envelope.timestamp == response.timestamp`
///
/// Call this on the **Owner** side after receiving the Helper's response to a sharing
/// request envelope. The decrypted response can then be validated using [`process`].
///
/// # Arguments
///
/// * `envelope_bytes` - Serialized outer [`derec_proto::DeRecMessage`] envelope bytes
/// received from the Helper, 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:
///
/// - `response`: the decrypted inner [`derec_proto::StoreShareResponseMessage`]
///
/// # Errors
///
/// Returns [`crate::Error`] if:
///
/// - `envelope_bytes` cannot be decoded as a valid [`derec_proto::DeRecMessage`]
/// - decryption or inner-message decoding fails
/// - `envelope.timestamp != response.timestamp`
/// - the inner message is not a [`derec_proto::StoreShareResponseMessage`]
///
/// # Security: 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, response};
/// use derec_library::types::ChannelId;
///
/// let channels = [ChannelId(1), ChannelId(2), ChannelId(3)];
/// let request::SplitResult { shares } = request::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");
///
/// // Owner → Helper → Owner roundtrip.
/// let request::ProduceResult { envelope: req_envelope } =
/// request::produce(channel_id, 1, 1, committed_share, &[], "", &shared_key, None, None)
/// .expect("produce request failed");
/// let request::ExtractResult { request: share_request } =
/// request::extract(&req_envelope, &shared_key).expect("extract request failed");
/// let response::ProduceResult { envelope: resp_envelope, .. } =
/// response::produce(channel_id, &share_request, &shared_key)
/// .expect("produce response failed");
///
/// let response::ExtractResult { response } =
/// response::extract(&resp_envelope, &shared_key).expect("extract response failed");
///
/// assert!(response.result.is_some());
/// ```
/// Validates a [`derec_proto::StoreShareResponseMessage`] received from a Helper.
///
/// Call this on the **Owner** side after extracting the response with [`extract`].
/// The function:
///
/// 1. Validates that the `result` field is present
/// 2. Validates that the Helper's response status is `Ok`
/// 3. Validates that `response.version == version`
///
/// Any failure — whether a protocol error or the Helper's explicit rejection — is
/// returned as [`crate::Error`].
///
/// # Arguments
///
/// * `version` - The version number that was sent in the original request. Used to
/// cross-check the version echoed back by the Helper.
/// * `response` - The decrypted [`derec_proto::StoreShareResponseMessage`] previously
/// returned by [`extract`].
///
/// # Returns
///
/// `Ok(())` on success.
///
/// # Errors
///
/// Returns [`crate::Error`] (specifically `Error::Sharing(...)`) in the following cases:
///
/// - the `result` field is absent in the response (returned as `crate::Error::Invariant`)
/// - [`SharingError::NonOkStatus`] if `result.status != Ok`, carrying the
/// Helper's status code and memo string
/// - [`SharingError::VersionMismatch`] if `response.version != version`
///
/// # Example
///
/// ```
/// use derec_library::primitives::sharing::{request, response};
/// use derec_library::types::ChannelId;
///
/// let channels = [ChannelId(1), ChannelId(2), ChannelId(3)];
/// let request::SplitResult { shares } = request::split(&channels, 1, 1, b"super_secret_value", 2)
/// .expect("split failed");
///
/// let channel_id = ChannelId(1);
/// let shared_key = [42u8; 32];
/// let version = 1;
/// let committed_share = shares.get(&channel_id).expect("missing share");
///
/// // Owner → Helper → Owner roundtrip.
/// let request::ProduceResult { envelope: req_envelope } =
/// request::produce(channel_id, version, 1, committed_share, &[], "", &shared_key, None, None)
/// .expect("produce request failed");
/// let request::ExtractResult { request: share_request } =
/// request::extract(&req_envelope, &shared_key).expect("extract request failed");
/// let response::ProduceResult { envelope: resp_envelope, .. } =
/// response::produce(channel_id, &share_request, &shared_key)
/// .expect("produce response failed");
/// let response::ExtractResult { response: ack } =
/// response::extract(&resp_envelope, &shared_key).expect("extract response failed");
///
/// response::process(version, &ack).expect("process failed");
/// ```