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
use std::convert::TryFrom;

use derive_more::{From, Into};
use paste::paste;
use redis::{ErrorKind, FromRedisValue, RedisError, RedisResult, RedisWrite, ToRedisArgs, Value};
use serde::{Deserialize, Serialize};

use crate::{
    state_machine::coordinator::CoordinatorState,
    storage::{
        LocalSeedDictAdd,
        LocalSeedDictAddError,
        MaskScoreIncr,
        MaskScoreIncrError,
        SumPartAdd,
        SumPartAddError,
    },
};
use xaynet_core::{
    crypto::{ByteObject, PublicEncryptKey, PublicSigningKey},
    mask::{EncryptedMaskSeed, MaskObject},
    LocalSeedDict,
};

fn redis_type_error(desc: &'static str, details: Option<String>) -> RedisError {
    if let Some(details) = details {
        RedisError::from((ErrorKind::TypeError, desc, details))
    } else {
        RedisError::from((ErrorKind::TypeError, desc))
    }
}

fn error_code_type_error(response: &Value) -> RedisError {
    redis_type_error(
        "Response status not valid integer",
        Some(format!("Response was {:?}", response)),
    )
}

/// Implements ['FromRedisValue'] and ['ToRedisArgs'] for types that implement ['ByteObject'].
/// The Redis traits as well as the crypto types are both defined in foreign crates.
/// To bypass the restrictions of orphan rule, we use `Newtypes` for the crypto types.
///
/// Each crypto type has two `Newtypes`, one for reading and one for writing.
/// The difference between `Read` and `Write` is that the write `Newtype` does not take the
/// ownership of the value but only a reference. This allows us to use references in the
/// [`Client`] methods. The `Read` Newtype also implements [`ToRedisArgs`] to reduce the
/// conversion overhead that you would get if you wanted to reuse a `Read` value for another
/// Redis query.
///
/// Example:
///
/// ```ignore
/// let sum_pks: Vec<PublicSigningKeyRead> = self.connection.hkeys("sum_dict").await?;
/// for sum_pk in sum_pks {
///    let sum_pk_seed_dict: HashMap<PublicSigningKeyRead, EncryptedMaskSeedRead>
///       = self.connection.hgetall(&sum_pk).await?; // no need to convert sum_pk from PublicSigningKeyRead to PublicSigningKeyWrite
/// }
/// ```
///
/// [`Client`]: crate::storage::redis::Client
macro_rules! impl_byte_object_redis_traits {
    ($ty: ty) => {
        paste! {
            #[derive(Into, Hash, Eq, PartialEq)]
            pub(crate) struct [<$ty Read>]($ty);

            impl FromRedisValue for [<$ty Read>] {
                fn from_redis_value(v: &Value) -> RedisResult<[<$ty Read>]> {
                    match *v {
                        Value::Data(ref bytes) => {
                            let inner = <$ty>::from_slice(bytes).ok_or_else(|| {
                                redis_type_error(concat!("Invalid ", stringify!($ty)), None)
                            })?;
                            Ok([<$ty Read>](inner))
                        }
                        _ => Err(redis_type_error(
                            concat!("Response not ", stringify!($ty), " compatible"),
                            None,
                        )),
                    }
                }
            }

            impl ToRedisArgs for [<$ty Read>] {
                fn write_redis_args<W>(&self, out: &mut W)
                where
                    W: ?Sized + RedisWrite,
                {
                    self.0.as_slice().write_redis_args(out)
                }
            }

            impl<'a> ToRedisArgs for &'a [<$ty Read>] {
                fn write_redis_args<W>(&self, out: &mut W)
                where
                    W: ?Sized + RedisWrite,
                {
                    self.0.as_slice().write_redis_args(out)
                }
            }

            #[derive(From)]
            pub(crate) struct [<$ty Write>]<'a>(&'a $ty);

            impl ToRedisArgs for [<$ty Write>]<'_> {
                fn write_redis_args<W>(&self, out: &mut W)
                where
                    W: ?Sized + RedisWrite,
                {
                    self.0.as_slice().write_redis_args(out)
                }
            }
        }
    };
}

impl_byte_object_redis_traits!(PublicEncryptKey);
impl_byte_object_redis_traits!(PublicSigningKey);
impl_byte_object_redis_traits!(EncryptedMaskSeed);

/// Implements ['FromRedisValue'] and ['ToRedisArgs'] for types that implement
/// ['Serialize`] and [`Deserialize']. The data is de/serialized via bincode.
///
/// # Panics
///
/// `write_redis_args` will panic if the data cannot be serialized with `bincode`
///
/// More information about what can cause a panic in bincode:
/// - https://github.com/servo/bincode/issues/293
/// - https://github.com/servo/bincode/issues/255
/// - https://github.com/servo/bincode/issues/130#issuecomment-284641263
macro_rules! impl_bincode_redis_traits {
    ($ty: ty) => {
        impl FromRedisValue for $ty {
            fn from_redis_value(v: &Value) -> RedisResult<$ty> {
                match *v {
                    Value::Data(ref bytes) => bincode::deserialize(bytes)
                        .map_err(|e| redis_type_error("Invalid data", Some(e.to_string()))),
                    _ => Err(redis_type_error("Response not bincode compatible", None)),
                }
            }
        }

        impl ToRedisArgs for $ty {
            fn write_redis_args<W>(&self, out: &mut W)
            where
                W: ?Sized + RedisWrite,
            {
                let data = bincode::serialize(self).unwrap();
                data.write_redis_args(out)
            }
        }

        impl<'a> ToRedisArgs for &'a $ty {
            fn write_redis_args<W>(&self, out: &mut W)
            where
                W: ?Sized + RedisWrite,
            {
                (*self).write_redis_args(out)
            }
        }
    };
}

// CoordinatorState is pretty straightforward:
// - all the sequences have known length (
// - no untagged enum
// so bincode will not panic.
impl_bincode_redis_traits!(CoordinatorState);

#[derive(From, Into, Serialize, Deserialize)]
pub(crate) struct MaskObjectRead(MaskObject);

impl_bincode_redis_traits!(MaskObjectRead);

#[derive(From, Serialize)]
pub(crate) struct MaskObjectWrite<'a>(&'a MaskObject);

impl ToRedisArgs for MaskObjectWrite<'_> {
    fn write_redis_args<W>(&self, out: &mut W)
    where
        W: ?Sized + RedisWrite,
    {
        let data = bincode::serialize(self).unwrap();
        data.write_redis_args(out)
    }
}

#[derive(From)]
pub(crate) struct LocalSeedDictWrite<'a>(&'a LocalSeedDict);

impl ToRedisArgs for LocalSeedDictWrite<'_> {
    fn write_redis_args<W>(&self, out: &mut W)
    where
        W: ?Sized + RedisWrite,
    {
        let args: Vec<(PublicSigningKeyWrite, EncryptedMaskSeedWrite)> = self
            .0
            .iter()
            .map(|(pk, seed)| {
                (
                    PublicSigningKeyWrite::from(pk),
                    EncryptedMaskSeedWrite::from(seed),
                )
            })
            .collect();

        args.write_redis_args(out)
    }
}

impl FromRedisValue for LocalSeedDictAdd {
    fn from_redis_value(v: &Value) -> RedisResult<LocalSeedDictAdd> {
        match *v {
            Value::Int(0) => Ok(LocalSeedDictAdd(Ok(()))),
            Value::Int(error_code) => match LocalSeedDictAddError::try_from(error_code) {
                Ok(error_variant) => Ok(LocalSeedDictAdd(Err(error_variant))),
                Err(_) => Err(error_code_type_error(v)),
            },
            _ => Err(error_code_type_error(v)),
        }
    }
}

impl FromRedisValue for SumPartAdd {
    fn from_redis_value(v: &Value) -> RedisResult<SumPartAdd> {
        match *v {
            Value::Int(1) => Ok(SumPartAdd(Ok(()))),
            Value::Int(error_code) => match SumPartAddError::try_from(error_code) {
                Ok(error_variant) => Ok(SumPartAdd(Err(error_variant))),
                Err(_) => Err(error_code_type_error(v)),
            },
            _ => Err(error_code_type_error(v)),
        }
    }
}

impl FromRedisValue for MaskScoreIncr {
    fn from_redis_value(v: &Value) -> RedisResult<MaskScoreIncr> {
        match *v {
            Value::Int(0) => Ok(MaskScoreIncr(Ok(()))),
            Value::Int(error_code) => match MaskScoreIncrError::try_from(error_code) {
                Ok(error_variant) => Ok(MaskScoreIncr(Err(error_variant))),
                Err(_) => Err(error_code_type_error(v)),
            },
            _ => Err(error_code_type_error(v)),
        }
    }
}

#[cfg(test)]
#[derive(derive_more::Deref)]
pub struct SumDictDelete(Result<(), SumDictDeleteError>);

#[cfg(test)]
impl SumDictDelete {
    pub fn into_inner(self) -> Result<(), SumDictDeleteError> {
        self.0
    }
}

#[cfg(test)]
#[derive(thiserror::Error, Debug, num_enum::TryFromPrimitive)]
#[repr(i64)]
pub enum SumDictDeleteError {
    #[error("sum participant does not exist")]
    DoesNotExist = 0,
}

#[cfg(test)]
impl FromRedisValue for SumDictDelete {
    fn from_redis_value(v: &Value) -> RedisResult<SumDictDelete> {
        match *v {
            Value::Int(1) => Ok(SumDictDelete(Ok(()))),
            Value::Int(error_code) => match SumDictDeleteError::try_from(error_code) {
                Ok(error_variant) => Ok(SumDictDelete(Err(error_variant))),
                Err(_) => Err(error_code_type_error(v)),
            },
            _ => Err(error_code_type_error(v)),
        }
    }
}