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
use crate::cryptography::{Ciphertext, HybridCiphertext, PublicKey, SecretKey};
use crate::encrypted_vote::{EncryptedVote, ProofOfCorrectVote, Vote};
use crate::math::polynomial::Polynomial;
use crate::tally::Crs;
use crate::{GroupElement, Scalar, CURVE_HRP};
use chain_crypto::bech32::{to_bech32_from_bytes, try_from_bech32_to_bytes, Bech32, Error};
use const_format::concatcp;
use rand_core::{CryptoRng, RngCore};

/// Committee member election secret key
#[derive(Clone)]
pub struct MemberSecretKey(pub(crate) SecretKey);

/// Committee member election public key
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct MemberPublicKey(pub(crate) PublicKey);

#[derive(Clone)]
pub struct MemberCommunicationKey(SecretKey);

/// Committee Member communication public key (with other committee members)
#[derive(Clone)]
pub struct MemberCommunicationPublicKey(PublicKey);

/// The overall committee public key used for everyone to encrypt their vote to.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ElectionPublicKey(pub(crate) PublicKey);

impl ElectionPublicKey {
    #[doc(hidden)]
    pub fn as_raw(&self) -> &PublicKey {
        &self.0
    }

    /// Take a vote and encrypt it + provide a proof of correct voting
    pub fn encrypt_and_prove_vote<R: RngCore + CryptoRng>(
        &self,
        rng: &mut R,
        crs: &Crs,
        vote: Vote,
    ) -> (EncryptedVote, ProofOfCorrectVote) {
        let encryption_randomness = vec![Scalar::random(rng); vote.len()];
        let ciphertexts: Vec<Ciphertext> = encryption_randomness
            .iter()
            .zip(vote.iter())
            .map(|(r, v)| self.as_raw().encrypt_with_r(&Scalar::from(v), r))
            .collect();

        let proof = ProofOfCorrectVote::generate(
            rng,
            crs,
            &self.0,
            &vote,
            &encryption_randomness,
            &ciphertexts,
        );
        (ciphertexts, proof)
    }

    /// Create an election public key from all the participants of this committee
    pub fn from_participants(pks: &[MemberPublicKey]) -> Self {
        let mut k = pks[0].0.pk.clone();
        for pk in &pks[1..] {
            k = k + &pk.0.pk;
        }
        ElectionPublicKey(PublicKey { pk: k })
    }

    pub fn to_bytes(&self) -> Vec<u8> {
        self.0.to_bytes()
    }

    pub fn from_bytes(buf: &[u8]) -> Option<Self> {
        PublicKey::from_bytes(buf).map(ElectionPublicKey)
    }
}

impl Bech32 for ElectionPublicKey {
    const BECH32_HRP: &'static str = concatcp!(CURVE_HRP, "_votepk");
    const BYTES_LEN: usize = PublicKey::BYTES_LEN;

    fn try_from_bech32_str(bech32_str: &str) -> Result<Self, Error> {
        try_from_bech32_to_bytes::<Self>(bech32_str).and_then(|raw| {
            Self::from_bytes(&raw)
                .ok_or_else(|| Error::DataInvalid("invalid election public key binary data".into()))
        })
    }

    fn to_bech32_str(&self) -> String {
        to_bech32_from_bytes::<Self>(&self.to_bytes())
    }
}

/// Initial state generated by a Member, which include keys for this election
#[derive(Clone)]
// TODO: some of the fields are needed for DKG features which are
// not yet implemented
#[allow(dead_code)]
pub struct MemberState {
    sk: MemberSecretKey,
    owner_index: usize,
    apubs: Vec<GroupElement>,
    es: Vec<GroupElement>,
    encrypted: Vec<(HybridCiphertext, HybridCiphertext)>,
}

impl MemberState {
    /// Generate a new member state from random, where the number
    pub fn new<R: RngCore + CryptoRng>(
        rng: &mut R,
        t: usize,
        h: &Crs, // TODO: document
        committee_pks: &[MemberCommunicationPublicKey],
        my: usize,
    ) -> MemberState {
        let n = committee_pks.len();
        assert!(t > 0);
        assert!(t <= n);
        assert!(my < n);

        let pcomm = Polynomial::random(rng, t);
        let pshek = Polynomial::random(rng, t);

        let mut apubs = Vec::new();
        let mut es = Vec::new();

        for (ai, bi) in pshek.get_coefficients().zip(pcomm.get_coefficients()) {
            let apub = GroupElement::generator() * ai;
            let e = &apub + h * bi;
            apubs.push(apub);
            es.push(e);
        }

        let mut encrypted = Vec::new();
        #[allow(clippy::needless_range_loop)]
        for i in 0..n {
            // don't generate share for self
            if i == my {
                continue;
            } else {
                let idx = Scalar::from_u64((i + 1) as u64);
                let share_comm = pcomm.evaluate(&idx);
                let share_shek = pshek.evaluate(&idx);

                let pk = &committee_pks[i];

                let ecomm = pk.0.hybrid_encrypt(&share_comm.to_bytes(), rng);
                let eshek = pk.0.hybrid_encrypt(&share_shek.to_bytes(), rng);

                encrypted.push((ecomm, eshek));
            }
        }

        assert_eq!(apubs.len(), t + 1);
        assert_eq!(es.len(), t + 1);
        assert_eq!(encrypted.len(), n - 1);

        MemberState {
            sk: MemberSecretKey(SecretKey {
                sk: pshek.at_zero(),
            }),
            owner_index: my + 1, // committee member are 1-indexed
            apubs,
            es,
            encrypted,
        }
    }

    pub fn secret_key(&self) -> &MemberSecretKey {
        &self.sk
    }

    pub fn member_secret_key(&self) -> MemberSecretKey {
        self.sk.clone()
    }

    pub fn public_key(&self) -> MemberPublicKey {
        MemberPublicKey(PublicKey {
            pk: self.apubs[0].clone(),
        })
    }
}

impl MemberSecretKey {
    pub fn to_bytes(&self) -> [u8; 32] {
        self.0.sk.to_bytes()
    }

    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
        let sk = Scalar::from_bytes(bytes)?;
        Some(Self(SecretKey { sk }))
    }

    pub fn to_public(&self) -> MemberPublicKey {
        MemberPublicKey(PublicKey {
            pk: GroupElement::generator() * &self.0.sk,
        })
    }
}

impl Bech32 for MemberSecretKey {
    const BECH32_HRP: &'static str = concatcp!(CURVE_HRP, "_membersk");
    const BYTES_LEN: usize = SecretKey::BYTES_LEN;

    fn try_from_bech32_str(bech32_str: &str) -> Result<Self, Error> {
        try_from_bech32_to_bytes::<Self>(bech32_str).and_then(|raw| {
            Self::from_bytes(&raw)
                .ok_or_else(|| Error::DataInvalid("invalid member secret key binary data".into()))
        })
    }

    fn to_bech32_str(&self) -> String {
        to_bech32_from_bytes::<Self>(&self.to_bytes())
    }
}

impl MemberPublicKey {
    pub const BYTES_LEN: usize = PublicKey::BYTES_LEN;

    pub fn to_bytes(&self) -> Vec<u8> {
        self.0.to_bytes()
    }

    pub fn from_bytes(buf: &[u8]) -> Option<Self> {
        Some(Self(PublicKey::from_bytes(buf)?))
    }
}

impl Bech32 for MemberPublicKey {
    const BECH32_HRP: &'static str = concatcp!(CURVE_HRP, "_memberpk");
    const BYTES_LEN: usize = PublicKey::BYTES_LEN;

    fn try_from_bech32_str(bech32_str: &str) -> Result<Self, Error> {
        try_from_bech32_to_bytes::<Self>(bech32_str).and_then(|raw| {
            Self::from_bytes(&raw)
                .ok_or_else(|| Error::DataInvalid("invalid member public key binary data".into()))
        })
    }

    fn to_bech32_str(&self) -> String {
        to_bech32_from_bytes::<Self>(&self.to_bytes())
    }
}

impl From<PublicKey> for MemberPublicKey {
    fn from(pk: PublicKey) -> MemberPublicKey {
        MemberPublicKey(pk)
    }
}

impl MemberCommunicationKey {
    pub fn new<R: RngCore + CryptoRng>(rng: &mut R) -> Self {
        let sk = SecretKey::generate(rng);
        MemberCommunicationKey(sk)
    }

    pub fn to_public(&self) -> MemberCommunicationPublicKey {
        MemberCommunicationPublicKey(PublicKey {
            pk: &GroupElement::generator() * &self.0.sk,
        })
    }

    pub fn from_bytes(bytes: &[u8]) -> Option<MemberCommunicationKey> {
        SecretKey::from_bytes(bytes).map(MemberCommunicationKey)
    }

    pub fn to_bytes(&self) -> [u8; 32] {
        self.0.sk.to_bytes()
    }
}

impl Bech32 for MemberCommunicationKey {
    const BECH32_HRP: &'static str = concatcp!(CURVE_HRP, "_vcommsk");
    const BYTES_LEN: usize = SecretKey::BYTES_LEN;

    fn try_from_bech32_str(bech32_str: &str) -> Result<Self, Error> {
        try_from_bech32_to_bytes::<Self>(bech32_str).and_then(|raw| {
            Self::from_bytes(&raw).ok_or_else(|| {
                Error::DataInvalid("invalid member communication secret key binary data".into())
            })
        })
    }

    fn to_bech32_str(&self) -> String {
        to_bech32_from_bytes::<Self>(&self.to_bytes())
    }
}

impl From<PublicKey> for MemberCommunicationPublicKey {
    fn from(pk: PublicKey) -> MemberCommunicationPublicKey {
        Self(pk)
    }
}

impl MemberCommunicationPublicKey {
    pub fn to_bytes(&self) -> Vec<u8> {
        self.0.to_bytes()
    }

    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
        PublicKey::from_bytes(bytes).map(Self)
    }
}

impl Bech32 for MemberCommunicationPublicKey {
    const BECH32_HRP: &'static str = concatcp!(CURVE_HRP, "_vcommpk");
    const BYTES_LEN: usize = PublicKey::BYTES_LEN;

    fn try_from_bech32_str(bech32_str: &str) -> Result<Self, Error> {
        try_from_bech32_to_bytes::<Self>(bech32_str).and_then(|raw| {
            Self::from_bytes(&raw).ok_or_else(|| {
                Error::DataInvalid("invalid member communication public key binary data".into())
            })
        })
    }

    fn to_bech32_str(&self) -> String {
        to_bech32_from_bytes::<Self>(&self.to_bytes())
    }
}