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
use core::fmt;

use schemars::{
    gen::SchemaGenerator,
    schema::{InstanceType, Schema, SchemaObject},
    JsonSchema,
};
use serde::{
    de::{Error, IgnoredAny, MapAccess, SeqAccess, Visitor},
    ser::SerializeStruct,
    Deserialize, Deserializer, Serialize, Serializer,
};

use crate::{Proof, PublicKey, SecretKey};
use std::{
    fmt::{Formatter, Write},
    num::ParseIntError,
};

impl AsRef<[u8]> for SecretKey {
    fn as_ref(&self) -> &[u8] {
        &self.bytes
    }
}

/// Decodes a hex-encoded string into a byte array.
///
/// # Errors
///
/// This function will return an error if the string is not hex-encoded.
pub fn decode_hex(s: &str) -> Result<Vec<u8>, ParseIntError> {
    (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16))
        .collect()
}

/// Encodes a byte array into a hex-encoded string.
///
/// # Panics
///
/// Panics if the call to [`write!`] returns an error.
#[must_use]
pub fn encode_hex(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for &b in bytes {
        write!(&mut s, "{:02x}", b).unwrap();
    }
    s
}

impl fmt::Display for SecretKey {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", encode_hex(&self.bytes))?;
        Ok(())
    }
}

impl fmt::Display for PublicKey {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", encode_hex(self.point.as_bytes()))?;
        Ok(())
    }
}

impl Serialize for PublicKey {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&encode_hex(self.point.as_bytes()))
    }
}

impl Serialize for SecretKey {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&encode_hex(self.as_bytes()))
    }
}

impl Serialize for Proof {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("Proof", 3)?;
        state.serialize_field("signer", &self.signer)?;
        state.serialize_field("message", &encode_hex(&self.message_bytes))?;
        state.serialize_field("proof", &encode_hex(&self.proof_bytes))?;
        state.end()
    }
}

impl<'de> Deserialize<'de> for PublicKey {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct PublicKeyVisitor;

        impl<'de> Visitor<'de> for PublicKeyVisitor {
            type Value = PublicKey;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("PublicKey bytes")
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: Error,
            {
                Ok(PublicKey::from_bytes(
                    decode_hex(v)
                        .map_err(|_| E::custom("Error decoding PublicKey bytes"))?
                        .as_slice(),
                ))
            }
        }

        deserializer.deserialize_str(PublicKeyVisitor)
    }
}

impl<'de> Deserialize<'de> for SecretKey {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct SecretKeyVisitor;

        impl<'de> Visitor<'de> for SecretKeyVisitor {
            type Value = SecretKey;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("SecretKey bytes")
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: Error,
            {
                Ok(SecretKey::from_slice(
                    decode_hex(v)
                        .map_err(|_| E::custom("Error decoding Secretkey bytes"))?
                        .as_slice(),
                ))
            }
        }

        deserializer.deserialize_str(SecretKeyVisitor)
    }
}

impl<'de> Deserialize<'de> for Proof {
    #[allow(clippy::too_many_lines)]
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        enum Field {
            Signer,
            Message,
            Proof,
            Ignore,
        }

        struct FieldVisitor;

        impl<'de> Visitor<'de> for FieldVisitor {
            type Value = Field;

            fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
                formatter.write_str("field identifier")
            }

            fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
            where
                E: Error,
            {
                match v {
                    0u64 => Ok(Field::Signer),
                    1u64 => Ok(Field::Message),
                    2u64 => Ok(Field::Proof),
                    _ => Ok(Field::Ignore),
                }
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: Error,
            {
                match v {
                    "signer" => Ok(Field::Signer),
                    "message" => Ok(Field::Message),
                    "proof" => Ok(Field::Proof),
                    _ => Ok(Field::Ignore),
                }
            }

            fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
            where
                E: Error,
            {
                match v {
                    b"signer" => Ok(Field::Signer),
                    b"message" => Ok(Field::Message),
                    b"proof" => Ok(Field::Proof),
                    _ => Ok(Field::Ignore),
                }
            }
        }

        impl<'de> Deserialize<'de> for Field {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: Deserializer<'de>,
            {
                deserializer.deserialize_identifier(FieldVisitor)
            }
        }

        struct ProofVisitor;

        impl<'de> Visitor<'de> for ProofVisitor {
            type Value = Proof;

            fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
                formatter.write_str("struct Proof")
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                let signer = seq
                    .next_element::<PublicKey>()?
                    .ok_or_else(|| A::Error::invalid_length(0, &"struct Proof with 3 elements"))?;
                let message = seq
                    .next_element::<String>()?
                    .ok_or_else(|| A::Error::invalid_length(1, &"struct Proof with 3 elements"))?;
                let proof = seq
                    .next_element::<String>()?
                    .ok_or_else(|| A::Error::invalid_length(2, &"struct Proof with 3 elements"))?;
                Ok(Proof {
                    signer,
                    message_bytes: decode_hex(message.as_str())
                        .map_err(|_| A::Error::custom("Error decoding message"))?,
                    proof_bytes: decode_hex(proof.as_str())
                        .map_err(|_| A::Error::custom("Error decoding proof"))?,
                })
            }

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                let mut signer = None;
                let mut message = None;
                let mut proof = None;
                while let Some(key) = map.next_key::<Field>()? {
                    match key {
                        Field::Signer => {
                            if signer.is_some() {
                                return Err(A::Error::duplicate_field("signer"));
                            }
                            signer = Some(map.next_value::<PublicKey>()?);
                        }
                        Field::Message => {
                            if message.is_some() {
                                return Err(A::Error::duplicate_field("message"));
                            }
                            message = Some(map.next_value::<String>()?);
                        }
                        Field::Proof => {
                            if proof.is_some() {
                                return Err(A::Error::duplicate_field("proof"));
                            }
                            proof = Some(map.next_value::<String>()?);
                        }
                        Field::Ignore => {
                            let _ = map.next_value::<IgnoredAny>()?;
                        }
                    }
                }
                let signer = signer.ok_or_else(|| A::Error::missing_field("signer"))?;
                let message = message.ok_or_else(|| A::Error::missing_field("message"))?;
                let proof = proof.ok_or_else(|| A::Error::missing_field("proof"))?;
                Ok(Proof {
                    signer,
                    message_bytes: decode_hex(message.as_str())
                        .map_err(|_| A::Error::custom("Error decoding message"))?,
                    proof_bytes: decode_hex(proof.as_str())
                        .map_err(|_| A::Error::custom("Error decoding proof"))?,
                })
            }
        }

        const FIELDS: &[&str] = &["signer", "message", "proof"];
        deserializer.deserialize_struct("Proof", FIELDS, ProofVisitor)
    }
}

impl JsonSchema for SecretKey {
    fn schema_name() -> String {
        "SecretKey".to_owned()
    }
    fn json_schema(_: &mut SchemaGenerator) -> Schema {
        let mut schema_object = SchemaObject {
            instance_type: Some(InstanceType::String.into()),
            ..Default::default()
        };
        let string_validation = schema_object.string();
        string_validation.min_length = Some(64u32);
        string_validation.max_length = Some(64u32);
        Schema::Object(schema_object)
    }
}

impl JsonSchema for PublicKey {
    fn schema_name() -> String {
        "PublicKey".to_owned()
    }
    fn json_schema(_: &mut SchemaGenerator) -> Schema {
        let mut schema_object = SchemaObject {
            instance_type: Some(InstanceType::String.into()),
            ..Default::default()
        };
        let string_validation = schema_object.string();
        string_validation.min_length = Some(64u32);
        string_validation.max_length = Some(64u32);
        Schema::Object(schema_object)
    }
}

impl JsonSchema for Proof {
    fn schema_name() -> String {
        "Proof".to_owned()
    }

    fn json_schema(gen: &mut SchemaGenerator) -> Schema {
        let mut schema_object = SchemaObject {
            instance_type: Some(InstanceType::Object.into()),
            ..Default::default()
        };
        let object_validation = schema_object.object();
        {
            // signer
            object_validation
                .properties
                .insert("signer".to_owned(), gen.subschema_for::<PublicKey>());
            object_validation.required.insert("signer".to_owned());
        }
        {
            // message
            object_validation
                .properties
                .insert("message".to_owned(), gen.subschema_for::<String>());
            object_validation.required.insert("message".to_owned());
        }

        {
            // proof
            object_validation
                .properties
                .insert("proof".to_owned(), gen.subschema_for::<String>());
            object_validation.required.insert("proof".to_owned());
        }
        Schema::Object(schema_object)
    }
}