rust_ev_verifier_lib 0.4.5

Main library for the E-Voting system of Swiss Post.
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
// Copyright © 2025 Denis Morel
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option) any
// later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License and
// a copy of the GNU General Public License along with this program. If not, see
// <https://www.gnu.org/licenses/>.

//! Module defining mocking structure for [VerificationDirectory]
//!
//! Example of usage:
//! ```ignore
//!     let mut mock_dir = MockVerificationDirectory::new(&VerificationPeriod::Setup, &location);
//!     // Change the data
//!     mock_dir
//!         .context_mut()
//!         .mock_control_component_public_keys_payload(2, |d| {
//!             d.encryption_group.set_p(&Integer::from(1234usize));
//!             d.encryption_group.set_q(&Integer::from(1234usize))
//!     });
//!     // Test the verification that should generate failures
//!     fn_verification(&mock_dir, &mut result);
//! ```

mod context_directory_data;
mod tally_directory_data;

use super::VerificationDirectoryTrait;
use super::{
    file_group::FileGroupFileIter, ContextDirectoryTrait, FileStructureError,
    FileStructureErrorImpl,
};
use crate::{
    data_structures::{VerifierDataDecode, VerifierDataToTypeTrait},
    verification::VerificationPeriod,
};
pub(crate) use context_directory_data::MockContextDirectory;
use std::{collections::HashMap, path::Path, sync::Arc};
pub(crate) use tally_directory_data::MockTallyDirectory;

/// Mock for [VerificationDirectory]
pub(crate) struct MockVerificationDirectory {
    context: MockContextDirectory,
    tally: Option<MockTallyDirectory>,
}

impl VerificationDirectoryTrait for MockVerificationDirectory {
    type ContextDirType = MockContextDirectory;
    type TallyDirType = MockTallyDirectory;

    fn unwrap_tally(&self) -> &MockTallyDirectory {
        match &self.tally {
            Some(t) => t,
            None => panic!("called `unwrap_tally()` on a `Setup` value"),
        }
    }

    fn context(&self) -> &Self::ContextDirType {
        &self.context
    }

    fn path(&self) -> &Path {
        self.context().dir.location().parent().unwrap()
    }
}

impl MockVerificationDirectory {
    /// Create a new [MockVerificationDirectory]
    pub fn new(period: &VerificationPeriod, location: &Path) -> Self {
        let context = MockContextDirectory::new(location);
        match period {
            VerificationPeriod::Setup => MockVerificationDirectory {
                context,
                tally: None,
            },
            VerificationPeriod::Tally => MockVerificationDirectory {
                context,
                tally: Some(MockTallyDirectory::new(location)),
            },
        }
    }

    /// Context mut
    pub fn context_mut(&mut self) -> &mut MockContextDirectory {
        &mut self.context
    }

    /// Unwrap [TallyDirectory] as mutable
    #[allow(dead_code)]
    pub fn unwrap_tally_mut(&mut self) -> &mut MockTallyDirectory {
        match &mut self.tally {
            Some(t) => t,
            None => panic!("called `unwrap_tally()` on a `Setup` value"),
        }
    }
}

/// Macro to add the mock methods to mock the data
///
/// The following methods will be generated (example with `setup_component_public_keys_payload`
/// and `SetupComponentPublicKeysPayload`):
/// ```ignore
/// pub fn mock_setup_component_public_keys_payload(
///     &mut self,
///     mut closure: impl FnMut(&mut SetupComponentPublicKeysPayload),
/// ) {todo!()}
/// pub fn mock_setup_component_public_keys_payload_error(&mut self, error: FileStructureError) {
///     todo!()
/// }
/// pub fn mock_setup_component_public_keys_payload_remove_error(&mut self) {
///     todo!()
/// }
/// ```
///
/// Parameters:
/// - $data_name: The name of the data
/// - $data_type: The type of the data
macro_rules! impl_mock_methods_for_mocked_data {
    ($data_name: ident, $data_type: ident) => {
        paste! {
            #[allow(dead_code)]
            #[doc = "Mock `$data_name`"]
            pub fn [<mock_ $data_name>](
                &mut self,
                mut closure: impl FnMut(&mut $data_type),
            ) {
                let orig_payload = match self.dir.[<$data_name>]() {
                    Ok(p) => p.as_ref().clone(),
                    Err(_) => return
                };
                let mut payload = match self.[<mocked_ $data_name>].as_ref() {
                    Some(p) => match p.as_ref() {
                        MockedDataType::Data(p) => Some(p.clone()),
                        _ => None
                    }
                    None => None
                }.unwrap_or_else(|| orig_payload);
                closure(
                    &mut payload
                );
                self.[<mocked_ $data_name>] = Some(Box::new(MockedDataType::Data(payload.clone())));
            }
            #[doc = "Mock `$data_name` with error"]
            #[allow(dead_code)]
            pub fn [<mock_ $data_name _error>](
                &mut self,
                error: FileStructureError,
            ) {
                self.[<mocked_ $data_name>] = Some(Box::new(MockedDataType::Error(error.to_string())))
            }
            #[doc = "Reset the original data for `$data_name`"]
            #[allow(dead_code)]
            pub fn  [<mock_ $data_name _reset>](&mut self) {
                self.[<mocked_ $data_name>] = None;
            }
        }
    };
}
use impl_mock_methods_for_mocked_data;

/// Macro to add the trait method to the get the data in the directory traits.
///
/// The following methods will be generated (example with `setup_component_public_keys_payload`
/// and `SetupComponentPublicKeysPayload`):
/// ```ignore
/// pub fn setup_component_public_keys_payload(
///     &mut self,
/// ) Result<Arc<SetupComponentPublicKeysPayload>, FileStructureError>
/// {todo!()}
/// ```
///
/// Parameters:
/// - $data_name: The name of the data
/// - $data_type: The type of the data
macro_rules! impl_trait_get_method_for_mocked_data {
    ($data_name: ident, $data_type: ident) => {
        paste! {
            fn $data_name(
                &self,
            ) -> Result<Arc<$data_type>, FileStructureError> {
                match &self.[<mocked_ $data_name>] {
                    None => self.dir.$data_name(),
                    Some(e) => match e.as_ref() {
                        MockedDataType::Data(d) => Ok(Arc::new(d.clone())),
                        MockedDataType::Error(e) => Err(FileStructureError::from(FileStructureErrorImpl::Mock(e.to_string()))),
                        MockedDataType::Deleted => Err(FileStructureError::from(FileStructureErrorImpl::Mock("Something wrong. Data cannot be deleted".to_string())))
                    }
                }
            }
        }
    };
}
use impl_trait_get_method_for_mocked_data;

/// Macro to add the mock methods to mock the data group
///
/// The following methods will be generated (example with `setup_component_public_keys_payload`
/// and `SetupComponentPublicKeysPayload`):
/// ```ignore
/// pub fn mock_[<$data_type>](
///     &mut self,
///     pos: usize,
///     mut closure: impl FnMut(&mut ControlComponentPublicKeysPayload),
/// ) { todo!()}
/// pub fn mock_[<$data_type>]_as_deleted(&mut self, i: usize) {
///     todo!() }
/// pub fn mock_[<$data_type>]_remove_deleted(&mut self, i: usize) {
///     todo!()}
/// pub fn mock_[<$data_type>]_error(
///     &mut self,
///     i: usize,
///     error: FileStructureError,
/// ) {todo!()}
/// pub fn mock_[<$data_type>]_remove_error(&mut self, i: usize) {
///     todo!()}
/// pub fn mock_[<$data_type>]_reset(&mut self, i: usize) {
///     todo!()
/// }
/// ```
///
/// Parameters:
/// - $data_name: The name of the data
/// - $data_type: The type of the data
macro_rules! impl_mock_methods_for_mocked_group {
    ($data_name: ident, $data_type: ident) => {
        paste! {
            #[allow(dead_code)]
            pub fn [<mock_ $data_name>](
                &mut self,
                pos: usize,
                mut closure: impl FnMut(&mut $data_type),
            ) {
                let orig_payload = match self.dir.[<$data_name _iter>]().find(|(i, _)| i == &pos) {
                    Some((_, res)) => match res {
                        Ok(p) => p.as_ref().clone(),
                        Err(_) => return
                    },
                    None => return
                };
                let mut payload = match self.[<mocked_ $data_name>].get(&pos) {
                    Some(p) => match &p.element_type {
                        MockedDataType::Data(p) => Some(p.clone()),
                        _ => None
                    }
                    None => None
                }.unwrap_or_else(|| orig_payload);
                closure(
                    &mut payload
                );
                let _ = self.[<mocked_ $data_name>].insert(pos, Box::new(MockFileGroupElement::new(
                    MockedDataType::Data(payload.clone()))));
            }

            #[allow(dead_code)]
            pub fn [<mock_ $data_name _as_deleted>](&mut self, pos: usize) {
                let _ = self.[<mocked_ $data_name>].insert(pos, Box::new(MockFileGroupElement::new(
                    MockedDataType::Deleted)));
            }

            #[allow(dead_code)]
            pub fn [<mock_ $data_name _error>](
                &mut self,
                pos: usize,
                error: FileStructureError,
            ) {
                let _ = self.[<mocked_ $data_name>].insert(pos, Box::new(MockFileGroupElement::new(
                    MockedDataType::Error(error.to_string()))));
            }

            #[allow(dead_code)]
            pub fn [<mock_ $data_name _reset>](&mut self, pos: usize) {
                let _ = self.[<mocked_ $data_name>].remove(&pos);
            }
        }
    };
}
use impl_mock_methods_for_mocked_group;

/// Macro to add the trait method to the get the data in the directory traits.
///
/// The following methods will be generated (example with `setup_component_public_keys_payload`
/// and `SetupComponentPublicKeysPayload`):
/// ```ignore
/// fn control_component_public_keys_payload_iter(
///     &self,
/// ) -> Self::ControlComponentPublicKeysPayloadAsResultIterType {todo!()}
/// ```
///
/// Parameters:
/// - $data_name: The name of the data
/// - $data_type: The type of the data
macro_rules! impl_trait_get_method_for_mocked_group {
    ($data_name: ident, $data_type: ident) => {
        paste! {
            fn [<$data_name _iter>](
                &self,
            ) -> impl Iterator<
            Item = (
                usize,
                Result<Arc<$data_type>, FileStructureError>,
            ),
        > {
            MockFileGroupDataIter::new(FileGroupFileIter::new(
                &self.dir.[<$data_name _group>]()), &self.[<mocked_ $data_name>])
            }
        }
    };
}
use impl_trait_get_method_for_mocked_group;

/// Mocked data type
#[derive(Clone)]
pub enum MockedDataType<D>
where
    D: VerifierDataDecode + VerifierDataToTypeTrait,
{
    Data(D),
    Deleted,
    Error(String),
}

/// File group element
#[derive(Clone)]
pub struct MockFileGroupElement<D>
where
    D: VerifierDataDecode + VerifierDataToTypeTrait + Clone,
{
    element_type: MockedDataType<D>,
}

impl<D> MockFileGroupElement<D>
where
    D: VerifierDataDecode + VerifierDataToTypeTrait + Clone,
{
    /// Transform to result
    ///
    /// Return `None` if the element is mocked as deleted
    fn to_data_res(&self) -> Option<Result<D, FileStructureError>> {
        match &self.element_type {
            MockedDataType::Data(d) => Some(Ok(d.clone())),
            MockedDataType::Deleted => None,
            MockedDataType::Error(e) => Some(Err(FileStructureError::from(
                FileStructureErrorImpl::Mock(e.to_string()),
            ))),
        }
    }
}

impl<D> MockFileGroupElement<D>
where
    D: VerifierDataDecode + VerifierDataToTypeTrait + Clone,
{
    /// New [MockFileGroupIter]
    ///
    /// fg_iter is the original iterator and mock_data contains the mocked data
    ///
    /// During the iteration, the data of the mocked data will be return if the index exists in the hashmap,
    /// else the original data will be returned
    pub fn new(element_type: MockedDataType<D>) -> Self {
        MockFileGroupElement { element_type }
    }
}

/// Iterator for the mock data in a file group
pub struct MockFileGroupDataIter<'a, D: VerifierDataDecode + VerifierDataToTypeTrait + Clone> {
    pub file_group_iter: FileGroupFileIter<D>,
    pub mocked: &'a HashMap<usize, Box<MockFileGroupElement<D>>>,
}

impl<'a, D: VerifierDataDecode + VerifierDataToTypeTrait + Clone> MockFileGroupDataIter<'a, D> {
    pub fn new(
        file_group_iter: FileGroupFileIter<D>,
        mocked: &'a HashMap<usize, Box<MockFileGroupElement<D>>>,
    ) -> Self {
        Self {
            file_group_iter,
            mocked,
        }
    }
}

/// Implement iterator for all the [MockFileGroupDataIter]
impl<D: VerifierDataDecode + VerifierDataToTypeTrait + Clone> Iterator
    for MockFileGroupDataIter<'_, D>
{
    type Item = (usize, Result<Arc<D>, FileStructureError>);

    fn next(&mut self) -> Option<Self::Item> {
        let (pos, file_res) = self.file_group_iter.next()?;
        match self.mocked.get(&pos) {
            Some(m) => match m.to_data_res() {
                Some(res) => Some((pos, res.map(Arc::new))),
                None => self.next(),
            },
            None => Some((pos, file_res.decode_verifier_data())),
        }
    }
}