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
use crate::revoke::RevokeError::IncorrectSignature;
use fluence_keypair::key_pair::KeyPair;
use fluence_keypair::public_key::PublicKey;
use fluence_keypair::signature::Signature;
use serde::{Deserialize, Serialize};
use sha2::Digest;
use std::time::Duration;
use thiserror::Error as ThisError;
#[derive(ThisError, Debug)]
pub enum RevokeError {
#[error("Signature is incorrect: {0}")]
IncorrectSignature(
#[from]
#[source]
fluence_keypair::error::VerificationError,
),
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Revocation {
pub pk: PublicKey,
pub revoked_at: Duration,
pub revoked_by: PublicKey,
pub signature: Signature,
}
impl Revocation {
pub fn new(
revoked_by: PublicKey,
pk: PublicKey,
revoked_at: Duration,
signature: Signature,
) -> Self {
Self {
pk,
revoked_at,
revoked_by,
signature,
}
}
pub fn create(revoker: &KeyPair, to_revoke: PublicKey, revoked_at: Duration) -> Self {
let msg = Revocation::signature_bytes(&to_revoke, revoked_at);
let signature = revoker.sign(&msg).unwrap();
Revocation::new(revoker.public(), to_revoke, revoked_at, signature)
}
pub fn signature_bytes(pk: &PublicKey, revoked_at: Duration) -> Vec<u8> {
let mut metadata = Vec::new();
let pk_bytes = &pk.encode();
metadata.push(pk_bytes.len() as u8);
metadata.extend(pk_bytes);
metadata.extend_from_slice(&(revoked_at.as_secs() as u64).to_le_bytes());
sha2::Sha256::digest(&metadata).to_vec()
}
pub fn verify(revoke: &Revocation) -> Result<(), RevokeError> {
let msg = Revocation::signature_bytes(&revoke.pk, revoke.revoked_at);
revoke
.revoked_by
.verify(msg.as_slice(), &revoke.signature)
.map_err(IncorrectSignature)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_gen_revoke_and_validate_ed25519() {
let revoker = KeyPair::generate_ed25519();
let to_revoke = KeyPair::generate_ed25519();
let duration = Duration::new(100, 0);
let revoke = Revocation::create(&revoker, to_revoke.public(), duration);
assert_eq!(Revocation::verify(&revoke).is_ok(), true);
}
#[test]
fn test_validate_corrupted_revoke_ed25519() {
let revoker = KeyPair::generate_ed25519();
let to_revoke = KeyPair::generate_ed25519();
let duration = Duration::new(100, 0);
let revoke = Revocation::create(&revoker, to_revoke.public(), duration);
let duration2 = Duration::new(95, 0);
let corrupted_revoke = Revocation::new(
revoker.public(),
to_revoke.public(),
duration2,
revoke.signature,
);
assert_eq!(Revocation::verify(&corrupted_revoke).is_ok(), false);
}
}