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
use blsttc::{serde_impl::SerdeSecret, SecretKeyShare};
use rand::{CryptoRng, Rng};
use serde::{Deserialize, Serialize};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error("Invalid Signature")]
InvalidSignature,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct PublicKey(blsttc::PublicKeyShare);
impl PublicKey {
pub fn random(rng: impl Rng + CryptoRng) -> Self {
SecretKey::random(rng).public_key()
}
pub fn verify(&self, msg: &[u8], signature: &Signature) -> Result<(), Error> {
if self.0.verify(&signature.0, msg) {
Ok(())
} else {
Err(Error::InvalidSignature)
}
}
}
impl core::fmt::Display for PublicKey {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let bytes = self.0.to_bytes();
write!(f, "i:{}", hex::encode(&bytes[..3]))
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SecretKey(SerdeSecret<SecretKeyShare>);
impl SecretKey {
pub fn random(mut rng: impl Rng + CryptoRng) -> Self {
Self(SerdeSecret(rng.gen()))
}
pub fn public_key(&self) -> PublicKey {
PublicKey(self.0 .0.public_key_share())
}
pub fn sign(&self, msg: &[u8]) -> Signature {
Signature(self.0.sign(msg))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Signature(blsttc::SignatureShare);
impl PartialOrd for PublicKey {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for PublicKey {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.0.to_bytes().cmp(&other.0.to_bytes())
}
}
impl PartialOrd for Signature {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Signature {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.0.to_bytes().cmp(&other.0.to_bytes())
}
}