Skip to main content

m10_signing/
ed25519.rs

1use crate::{internal_error, PreparedDigest, PreparedTransaction, Signer, SigningError};
2use core::convert::TryFrom;
3use core::str::FromStr;
4use ed25519_dalek::pkcs8::{DecodePrivateKey, EncodePrivateKey};
5use ed25519_dalek::{KEYPAIR_LENGTH, SECRET_KEY_LENGTH};
6use m10_protos::sdk::signature::Algorithm;
7use sha2::Digest as _;
8use std::fmt;
9use std::fs::File;
10use std::io::{Read, Write};
11
12/// An Ed25519 key-pair
13#[derive(serde::Deserialize)]
14#[serde(try_from = "String", into = "String")]
15pub struct Ed25519 {
16    #[serde(skip)]
17    key: ed25519_dalek::SigningKey,
18    public_key: [u8; ed25519_dalek::PUBLIC_KEY_LENGTH],
19    #[serde(skip)]
20    algorithm: Algorithm,
21}
22
23fn make_ed25519(key: ed25519_dalek::SigningKey) -> Ed25519 {
24    let public_key = *key.verifying_key().as_bytes();
25    Ed25519 {
26        key,
27        public_key,
28        algorithm: Algorithm::Ed25519,
29    }
30}
31
32impl Ed25519 {
33    /// Generates an ED25519 key-pair, and if the path is passed writes it to disk as a PKCS8 document
34    pub fn new_key_pair(path: Option<&str>) -> Result<Self, SigningError> {
35        let key = ed25519_dalek::SigningKey::generate(&mut rand_core::OsRng);
36        if let Some(p) = path {
37            let doc = key
38                .to_pkcs8_der()
39                .map_err(|e| internal_error(e, "Ed25519::new_key_pair: to_pkcs8_der"))?;
40            let mut key_file = File::create(p)?;
41            key_file.write_all(doc.as_bytes())?;
42        }
43        Ok(make_ed25519(key))
44    }
45
46    /// Loads an Ed25519 key-pair from a PKCS8 formatted file
47    pub fn load_key_pair(path: &str) -> Result<Self, SigningError> {
48        let mut key_file = File::open(path)?;
49        let mut pkcs8_bytes: Vec<u8> = Vec::new();
50        key_file.read_to_end(&mut pkcs8_bytes)?;
51        Ed25519::from_pkcs8(&pkcs8_bytes)
52    }
53
54    /// Generates a new key-pair, and returns both the key-pair and a PKCS8 document containing the key-pair
55    pub fn new_key_pair_exportable() -> Result<(Vec<u8>, Self), SigningError> {
56        let key = ed25519_dalek::SigningKey::generate(&mut rand_core::OsRng);
57        let doc = key
58            .to_pkcs8_der()
59            .map_err(|e| internal_error(e, "Ed25519::new_key_pair_exportable: to_pkcs8_der"))?;
60        let pkcs8_bytes = doc.as_bytes().to_vec();
61        Ok((pkcs8_bytes, make_ed25519(key)))
62    }
63
64    /// Returns a new [`Ed25519`] key-pair from a PKCS8 document
65    pub fn from_pkcs8(bytes: &[u8]) -> Result<Self, SigningError> {
66        let key = ed25519_dalek::SigningKey::from_pkcs8_der(bytes)
67            .map_err(|e| internal_error(e, "Ed25519::from_pkcs8"))?;
68        Ok(make_ed25519(key))
69    }
70
71    /// Parses Ed25519 key-pair from base64-encoded 64-byte raw key (32-byte private + 32-byte public)
72    pub fn from_keypair(b64: &str) -> Result<Self, SigningError> {
73        let bytes = base64::decode(b64).map_err(|_| {
74            SigningError::KeyInvalid("Failed to decode base64-encoded key".to_string())
75        })?;
76        if bytes.len() != KEYPAIR_LENGTH {
77            return Err(SigningError::KeyInvalid(format!(
78                "Invalid key length: expected {KEYPAIR_LENGTH} bytes, got {}",
79                bytes.len()
80            )));
81        }
82        let seed: &[u8; SECRET_KEY_LENGTH] = bytes[..SECRET_KEY_LENGTH]
83            .try_into()
84            .map_err(|_| SigningError::KeyInvalid("Invalid seed slice".to_string()))?;
85        let key = ed25519_dalek::SigningKey::from_bytes(seed);
86        Ok(make_ed25519(key))
87    }
88
89    pub fn new_key_pair_ph(path: Option<&str>) -> Result<Self, SigningError> {
90        Self::new_key_pair(path).map(|k| Self {
91            algorithm: Algorithm::Ed25519PhSha512,
92            ..k
93        })
94    }
95
96    pub fn load_key_pair_ph(path: &str) -> Result<Self, SigningError> {
97        Self::load_key_pair(path).map(|k| Self {
98            algorithm: Algorithm::Ed25519PhSha512,
99            ..k
100        })
101    }
102
103    pub fn from_pkcs8_ph(bytes: &[u8]) -> Result<Self, SigningError> {
104        Self::from_pkcs8(bytes).map(|k| Self {
105            algorithm: Algorithm::Ed25519PhSha512,
106            ..k
107        })
108    }
109}
110
111#[async_trait::async_trait]
112impl Signer for Ed25519 {
113    async fn sign(&self, msg: &[u8]) -> Result<Vec<u8>, super::SigningError> {
114        if self.algorithm == Algorithm::Ed25519PhSha512 {
115            return Err(SigningError::KeyInvalid(
116                "Ed25519Ph keys must use sign_prepared_transaction".into(),
117            ));
118        }
119        use ed25519_dalek::Signer as _;
120        Ok(self.key.sign(msg).to_bytes().to_vec())
121    }
122
123    fn public_key(&self) -> &[u8] {
124        &self.public_key
125    }
126
127    fn algorithm(&self) -> Algorithm {
128        self.algorithm
129    }
130
131    async fn sign_prepared_transaction(
132        &self,
133        prepared: &PreparedTransaction,
134    ) -> Result<Vec<u8>, super::SigningError> {
135        let hash = match (prepared.algorithm, &prepared.digest) {
136            (Algorithm::Ed25519PhSha512, PreparedDigest::Ed25519PhSha512(h)) => h,
137            _ => {
138                return Err(internal_error(
139                    "algorithm and digest type mismatch or unsupported",
140                    "Ed25519::sign_prepared_transaction",
141                ))
142            }
143        };
144
145        let sig = self
146            .key
147            .sign_prehashed(sha2::Sha512::new_with_prefix(hash), None)
148            .map_err(|e| internal_error(e, "Ed25519::sign_prepared_transaction: sign_prehashed"))?;
149
150        Ok(sig.to_bytes().to_vec())
151    }
152}
153
154impl fmt::Debug for Ed25519 {
155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        write!(f, "Ed25519({:?})", self.public_key())
157    }
158}
159
160impl FromStr for Ed25519 {
161    type Err = SigningError;
162    fn from_str(key_pair_enc: &str) -> Result<Self, Self::Err> {
163        let pkcs8_bytes = base64::decode(key_pair_enc).unwrap_or_default();
164        Ed25519::from_pkcs8(&pkcs8_bytes)
165    }
166}
167
168impl TryFrom<String> for Ed25519 {
169    type Error = SigningError;
170    fn try_from(key_pair: String) -> Result<Self, Self::Error> {
171        key_pair.parse()
172    }
173}