commonware_coding/
no_coding.rs

1use crate::Config;
2use commonware_cryptography::Hasher;
3use std::marker::PhantomData;
4use thiserror::Error;
5
6#[derive(Error, Debug)]
7pub enum NoCodingError {
8    #[error("data does not match commitment")]
9    BadData,
10}
11
12/// A trivial scheme which performs no coding at all.
13///
14/// Instead, each shard contains all of the data.
15///
16/// The commitment is simply a hash of that data. This struct is generic
17/// over the choice of [commonware_cryptography::Hasher].
18#[derive(Clone, Copy)]
19pub struct NoCoding<H> {
20    _marker: PhantomData<H>,
21}
22
23impl<H> std::fmt::Debug for NoCoding<H> {
24    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25        f.debug_struct("NoCoding").finish()
26    }
27}
28
29impl<H: Hasher> crate::Scheme for NoCoding<H> {
30    type Commitment = H::Digest;
31
32    type Shard = Vec<u8>;
33
34    type ReShard = ();
35
36    type CheckedShard = ();
37
38    type CheckingData = Vec<u8>;
39
40    type Error = NoCodingError;
41
42    fn encode(
43        config: &crate::Config,
44        mut data: impl bytes::Buf,
45    ) -> Result<(Self::Commitment, Vec<Self::Shard>), Self::Error> {
46        let data: Vec<u8> = data.copy_to_bytes(data.remaining()).to_vec();
47        let commitment = H::new().update(&data).finalize();
48        let shards = (0..config.minimum_shards + config.extra_shards)
49            .map(|_| data.clone())
50            .collect();
51        Ok((commitment, shards))
52    }
53
54    fn reshard(
55        _config: &Config,
56        commitment: &Self::Commitment,
57        _index: u16,
58        shard: Self::Shard,
59    ) -> Result<(Self::CheckingData, Self::CheckedShard, Self::ReShard), Self::Error> {
60        let my_commitment = H::new().update(shard.as_slice()).finalize();
61        if &my_commitment != commitment {
62            return Err(NoCodingError::BadData);
63        }
64        Ok((shard, (), ()))
65    }
66
67    fn check(
68        _config: &Config,
69        _commitment: &Self::Commitment,
70        _checking_data: &Self::CheckingData,
71        _index: u16,
72        _reshard: Self::ReShard,
73    ) -> Result<Self::CheckedShard, Self::Error> {
74        Ok(())
75    }
76
77    fn decode(
78        _config: &Config,
79        _commitment: &Self::Commitment,
80        checking_data: Self::CheckingData,
81        _shards: &[Self::CheckedShard],
82    ) -> Result<Vec<u8>, Self::Error> {
83        Ok(checking_data)
84    }
85}
86
87impl<H: Hasher> crate::ValidatingScheme for NoCoding<H> {}