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
//! Self Signing derivation module
//!

use std::str::FromStr;

use borsh::{BorshDeserialize, BorshSerialize};

use super::Derivator;
use crate::identifier::{error::Error, signature_identifier::SignatureIdentifier};

/// Enumeration with signature derivator types
#[derive(Debug, PartialEq, Clone, Copy, Eq, Hash, BorshSerialize, BorshDeserialize, PartialOrd)]
pub enum SignatureDerivator {
    Ed25519Sha512,
    ECDSAsecp256k1,
}

impl SignatureDerivator {
    pub fn derive(&self, sign: &[u8]) -> SignatureIdentifier {
        SignatureIdentifier::new(*self, sign)
    }
}

impl Derivator for SignatureDerivator {
    fn code_len(&self) -> usize {
        match self {
            Self::Ed25519Sha512 | Self::ECDSAsecp256k1 => 2,
        }
    }

    fn derivative_len(&self) -> usize {
        match self {
            Self::Ed25519Sha512 | Self::ECDSAsecp256k1 => 86,
        }
    }

    fn to_str(&self) -> String {
        match self {
            Self::Ed25519Sha512 => "SE",
            Self::ECDSAsecp256k1 => "SS",
        }
        .into()
    }
}

impl FromStr for SignatureDerivator {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match &s[..1] {
            "S" => match &s[1..2] {
                "E" => Ok(Self::Ed25519Sha512),
                "S" => Ok(Self::ECDSAsecp256k1),
                _ => Err(Error::DeserializationError),
            },
            _ => Err(Error::DeserializationError),
        }
    }
}