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
use std::collections::HashSet;

use super::{errors::ProtocolErrors, models::HashId};
use crate::commons::{
    crypto::{KeyMaterial, KeyPair},
    identifier::{derive::digest::DigestDerivator, KeyIdentifier},
    models::signature::Signature,
    settings::Settings,
};

pub trait SelfSignatureInterface {
    fn change_settings(&mut self, settings: &Settings);
    fn get_own_identifier(&self) -> KeyIdentifier;
    fn sign<T: HashId>(&self, content: &T) -> Result<Signature, ProtocolErrors>;
    fn check_if_signature_present(&self, signers: &HashSet<KeyIdentifier>) -> bool;
}

#[derive(Clone, Debug)]
pub struct SelfSignatureManager {
    pub keys: KeyPair,
    pub identifier: KeyIdentifier,
    pub digest_derivator: DigestDerivator,
}

impl SelfSignatureManager {
    pub fn new(keys: KeyPair, settings: &Settings) -> Self {
        let identifier = KeyIdentifier::new(keys.get_key_derivator(), &keys.public_key_bytes());
        Self {
            keys,
            identifier,
            digest_derivator: settings.node.digest_derivator.clone(),
        }
    }
}

impl SelfSignatureInterface for SelfSignatureManager {
    fn change_settings(&mut self, settings: &Settings) {
        self.digest_derivator = settings.node.digest_derivator.clone();
    }

    fn get_own_identifier(&self) -> KeyIdentifier {
        self.identifier.clone()
    }

    fn sign<T: HashId>(&self, content: &T) -> Result<Signature, ProtocolErrors> {
        Ok(Signature::new(content, &self.keys).map_err(|_| ProtocolErrors::SignatureError)?)
    }

    fn check_if_signature_present(&self, signers: &HashSet<KeyIdentifier>) -> bool {
        signers.contains(&self.identifier)
    }
}