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
//! Wrappers around some of the [sodiumoxide] signing primitives.
//!
//! See the [crypto module] documentation since this is a private module anyways.
//!
//! [sodiumoxide]: https://docs.rs/sodiumoxide/
//! [crypto module]: ../index.html

use derive_more::{AsMut, AsRef, From};
use num::{
    bigint::{BigUint, ToBigInt},
    rational::Ratio,
};
use sodiumoxide::crypto::{hash::sha256, sign};

use super::ByteObject;

#[derive(Debug, Clone)]
/// A `Ed25519` key pair for signatures.
pub struct SigningKeyPair {
    /// The `Ed25519` public key.
    pub public: PublicSigningKey,
    /// The `Ed25519` secret key.
    pub secret: SecretSigningKey,
}

impl SigningKeyPair {
    /// Generates a new random `Ed25519` key pair for signing.
    pub fn generate() -> Self {
        let (pk, sk) = sign::gen_keypair();
        Self {
            public: PublicSigningKey(pk),
            secret: SecretSigningKey(sk),
        }
    }
}

#[derive(
    AsRef,
    AsMut,
    From,
    Serialize,
    Deserialize,
    Hash,
    Eq,
    Ord,
    PartialEq,
    Copy,
    Clone,
    PartialOrd,
    Debug,
)]
/// An `Ed25519` public key for signatures.
pub struct PublicSigningKey(sign::PublicKey);

impl PublicSigningKey {
    /// Verifies the signature `s` against the message `m` and this public key.
    ///
    /// Returns `true` if the signature is valid and `false` otherwise.
    pub fn verify_detached(&self, s: &Signature, m: &[u8]) -> bool {
        sign::verify_detached(s.as_ref(), m, self.as_ref())
    }
}

impl ByteObject for PublicSigningKey {
    const LENGTH: usize = sign::PUBLICKEYBYTES;

    fn zeroed() -> Self {
        Self(sign::PublicKey([0_u8; sign::PUBLICKEYBYTES]))
    }

    fn as_slice(&self) -> &[u8] {
        self.0.as_ref()
    }

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

#[derive(AsRef, AsMut, From, Serialize, Deserialize, Eq, PartialEq, Clone, Debug)]
/// An `Ed25519` secret key for signatures.
///
/// When this goes out of scope, its contents will be zeroed out.
pub struct SecretSigningKey(sign::SecretKey);

impl SecretSigningKey {
    /// Signs a message `m` with this secret key.
    pub fn sign_detached(&self, m: &[u8]) -> Signature {
        sign::sign_detached(m, self.as_ref()).into()
    }

    /// Computes the corresponding public key for this secret key.
    pub fn public_key(&self) -> PublicSigningKey {
        PublicSigningKey(self.0.public_key())
    }
}

impl ByteObject for SecretSigningKey {
    const LENGTH: usize = sign::SECRETKEYBYTES;

    fn zeroed() -> Self {
        Self(sign::SecretKey([0_u8; Self::LENGTH]))
    }

    fn as_slice(&self) -> &[u8] {
        self.0.as_ref()
    }

    fn from_slice(bytes: &[u8]) -> Option<Self> {
        sign::SecretKey::from_slice(bytes).map(Self)
    }
}

#[derive(
    AsRef,
    AsMut,
    From,
    Serialize,
    Deserialize,
    Hash,
    Eq,
    Ord,
    PartialEq,
    Copy,
    Clone,
    PartialOrd,
    Debug,
)]
/// An `Ed25519` signature detached from its message.
pub struct Signature(sign::Signature);

impl ByteObject for Signature {
    const LENGTH: usize = sign::SIGNATUREBYTES;

    fn zeroed() -> Self {
        Self(sign::Signature([0_u8; sign::SIGNATUREBYTES]))
    }

    fn as_slice(&self) -> &[u8] {
        self.0.as_ref()
    }

    fn from_slice(bytes: &[u8]) -> Option<Self> {
        sign::Signature::from_slice(bytes).map(Self)
    }
}

impl Signature {
    /// Computes the floating point representation of the hashed signature and ensures that it is
    /// below the given threshold:
    /// ```no_rust
    /// int(hash(signature)) / (2**hashbits - 1) <= threshold.
    /// ```
    pub fn is_eligible(&self, threshold: f64) -> bool {
        if threshold < 0_f64 {
            return false;
        } else if threshold > 1_f64 {
            return true;
        }
        // safe unwraps: `to_bigint` never fails for `BigUint`s
        let numer = BigUint::from_bytes_le(sha256::hash(self.as_slice()).as_ref())
            .to_bigint()
            .unwrap();
        let denom = BigUint::from_bytes_le([u8::MAX; sha256::DIGESTBYTES].as_ref())
            .to_bigint()
            .unwrap();
        // safe unwrap: `threshold` is guaranteed to be finite
        Ratio::new(numer, denom) <= Ratio::from_float(threshold).unwrap()
    }
}

#[derive(AsRef, AsMut, From, Serialize, Deserialize, Eq, PartialEq, Clone)]
/// A seed that can be used for `Ed25519` signing key pair generation.
///
/// When this goes out of scope, its contents will be zeroed out.
pub struct SigningKeySeed(sign::Seed);

impl SigningKeySeed {
    /// Deterministically derives a new signing key pair from this seed.
    pub fn derive_signing_key_pair(&self) -> (PublicSigningKey, SecretSigningKey) {
        let (pk, sk) = sign::keypair_from_seed(&self.0);
        (PublicSigningKey(pk), SecretSigningKey(sk))
    }
}

impl ByteObject for SigningKeySeed {
    const LENGTH: usize = sign::SEEDBYTES;

    fn from_slice(bytes: &[u8]) -> Option<Self> {
        sign::Seed::from_slice(bytes).map(Self)
    }

    fn zeroed() -> Self {
        Self(sign::Seed([0; sign::PUBLICKEYBYTES]))
    }

    fn as_slice(&self) -> &[u8] {
        self.0.as_ref()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_signature_is_eligible() {
        // eligible signature
        let sig = Signature::from_slice_unchecked(&[
            172, 29, 85, 219, 118, 44, 107, 32, 219, 253, 25, 242, 53, 45, 111, 62, 102, 130, 24,
            8, 222, 199, 34, 120, 166, 163, 223, 229, 100, 50, 252, 244, 250, 88, 196, 151, 136,
            48, 39, 198, 166, 86, 29, 151, 13, 81, 69, 198, 40, 148, 134, 126, 7, 202, 1, 56, 174,
            43, 89, 28, 242, 194, 4, 214,
        ]);
        assert!(sig.is_eligible(0.5_f64));

        // ineligible signature
        let sig = Signature::from_slice_unchecked(&[
            119, 2, 197, 174, 52, 165, 229, 22, 218, 210, 240, 188, 220, 232, 149, 129, 211, 13,
            61, 217, 186, 79, 102, 15, 109, 237, 83, 193, 12, 117, 210, 66, 99, 230, 30, 131, 63,
            108, 28, 222, 48, 92, 153, 71, 159, 220, 115, 181, 183, 155, 146, 182, 205, 89, 140,
            234, 100, 40, 199, 248, 23, 147, 172, 248,
        ]);
        assert!(!sig.is_eligible(0.5_f64));
    }
}