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

use borsh::{BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Serialize};
use std::str::FromStr;

use super::{Derivator, SignatureDerivator};
use crate::identifier::{error::Error, key_identifier::KeyIdentifier};

/// An enumeration of key derivator types.
#[derive(
    Debug,
    PartialEq,
    Clone,
    Copy,
    Serialize,
    Deserialize,
    Eq,
    Hash,
    BorshSerialize,
    BorshDeserialize,
    PartialOrd,
)]
pub enum KeyDerivator {
    /// The Ed25519 key derivator.
    Ed25519,
    /// The Secp256k1 key derivator.
    Secp256k1,
}

impl KeyDerivator {
    pub fn derive(&self, public_key: &[u8]) -> KeyIdentifier {
        KeyIdentifier::new(*self, public_key)
    }

    pub fn to_signature_derivator(&self) -> SignatureDerivator {
        match self {
            KeyDerivator::Ed25519 => SignatureDerivator::Ed25519Sha512,
            KeyDerivator::Secp256k1 => SignatureDerivator::ECDSAsecp256k1,
        }
    }
}

impl Derivator for KeyDerivator {
    fn code_len(&self) -> usize {
        match self {
            Self::Ed25519 | Self::Secp256k1 => 1,
        }
    }

    fn derivative_len(&self) -> usize {
        match self {
            Self::Ed25519 => 43,
            Self::Secp256k1 => 87,
        }
    }

    fn to_str(&self) -> String {
        match self {
            Self::Ed25519 => "E",
            Self::Secp256k1 => "S",
        }
        .into()
    }
}

impl FromStr for KeyDerivator {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.len() == 0 {
            return Err(Error::DeserializationError);
        }
        match &s[..1] {
            "E" => Ok(Self::Ed25519),
            "S" => Ok(Self::Secp256k1),
            _ => Err(Error::DeserializationError),
        }
    }
}

impl From<KeyDerivator> for config::Value {
    fn from(data: KeyDerivator) -> Self {
        match data {
            KeyDerivator::Ed25519 => {
                Self::new(None, config::ValueKind::String("Ed25519".to_owned()))
            }
            KeyDerivator::Secp256k1 => {
                Self::new(None, config::ValueKind::String("Secp256k1".to_owned()))
            }
        }
    }
}