Skip to main content

m10_signing/
lib.rs

1//! M10's helper library for signing messages with ED25519 or P256 elliptic-curve signatures
2//!
3//! This library contains a set of wrappers and traits that allow users to easily sign and verify
4//! signatures
5use async_trait::async_trait;
6use core::str::FromStr;
7use m10_protos::{prost::Message, sdk};
8use std::fmt;
9use std::sync::Arc;
10
11pub use ed25519::Ed25519;
12pub use p256::P256;
13pub use vault::VaultTransit;
14
15mod ed25519;
16mod p256;
17mod vault;
18pub use crate::vault::extract_public_key;
19
20pub fn verify_ed25519ph(
21    public_key: &[u8],
22    message: &[u8],
23    signature: &[u8],
24) -> Result<(), SigningError> {
25    use sha2::Digest as _;
26    let pk_bytes: &[u8; 32] = public_key
27        .try_into()
28        .map_err(|e| internal_error(e, "verify_ed25519ph: invalid public key length"))?;
29    let vk = ed25519_dalek::VerifyingKey::from_bytes(pk_bytes)
30        .map_err(|e| internal_error(e, "verify_ed25519ph: invalid public key"))?;
31    let sig = ed25519_dalek::Signature::from_slice(signature)
32        .map_err(|e| internal_error(e, "verify_ed25519ph: invalid signature bytes"))?;
33    vk.verify_prehashed_strict(
34        sha2::Sha512::new_with_prefix(sha2::Sha512::digest(message)),
35        None,
36        &sig,
37    )
38    .map_err(|e| internal_error(e, "verify_ed25519ph: signature verification failed"))
39}
40
41/// A signed request containing both the serialized and signed payload; and the original message
42#[derive(Default, Clone)]
43pub struct SignedRequest<P: Message> {
44    pub request_envelope: sdk::RequestEnvelope,
45    pub data: P,
46}
47
48impl<P: Message> From<SignedRequest<P>> for sdk::RequestEnvelope {
49    fn from(signed_request: SignedRequest<P>) -> Self {
50        signed_request.request_envelope
51    }
52}
53
54impl<P: Message> AsRef<P> for SignedRequest<P> {
55    fn as_ref(&self) -> &P {
56        &self.data
57    }
58}
59
60/// Algorithm-bound pre-computed digest of a transaction payload
61#[derive(Debug, PartialEq)]
62pub enum PreparedDigest {
63    P256Sha256([u8; 32]),
64    Ed25519PhSha512([u8; 64]),
65}
66
67impl PreparedDigest {
68    pub fn as_bytes(&self) -> &[u8] {
69        match self {
70            PreparedDigest::P256Sha256(d) => d,
71            PreparedDigest::Ed25519PhSha512(d) => d,
72        }
73    }
74}
75
76/// A transaction payload with its pre-computed algorithm-bound digest
77#[derive(Debug)]
78pub struct PreparedTransaction {
79    pub payload: Vec<u8>,
80    pub algorithm: sdk::signature::Algorithm,
81    pub digest: PreparedDigest,
82}
83
84impl PreparedTransaction {
85    /// Creates a new prepared transaction, computing the digest for the given algorithm
86    pub fn new(
87        payload: Vec<u8>,
88        algorithm: sdk::signature::Algorithm,
89    ) -> Result<Self, SigningError> {
90        use sha2::Digest as _;
91        let digest = match algorithm {
92            sdk::signature::Algorithm::P256Sha256Asn1 => {
93                PreparedDigest::P256Sha256(sha2::Sha256::digest(&payload).into())
94            }
95            sdk::signature::Algorithm::Ed25519PhSha512 => {
96                PreparedDigest::Ed25519PhSha512(sha2::Sha512::digest(&payload).into())
97            }
98            sdk::signature::Algorithm::Ed25519 => {
99                return Err(SigningError::KeyInvalid(
100                    "ED25519 does not support digest signing".to_string(),
101                ))
102            }
103        };
104        Ok(Self {
105            payload,
106            algorithm,
107            digest,
108        })
109    }
110
111    /// Verifies that the stored digest matches a fresh recomputation from the payload
112    pub fn verify_integrity(&self) -> Result<(), SigningError> {
113        use sha2::Digest as _;
114        let valid = match &self.digest {
115            PreparedDigest::P256Sha256(stored) => {
116                &sha2::Sha256::digest(&self.payload)[..] == stored
117            }
118            PreparedDigest::Ed25519PhSha512(stored) => {
119                &sha2::Sha512::digest(&self.payload)[..] == stored
120            }
121        };
122        if !valid {
123            return Err(internal_error(
124                "transaction digest mismatch",
125                "PreparedTransaction::verify_integrity",
126            ));
127        }
128        Ok(())
129    }
130}
131
132#[derive(thiserror::Error, Debug)]
133pub enum SigningError {
134    #[error("internal")]
135    Internal,
136    #[error("malformed signature")]
137    MalFormedSignature,
138    #[error("io error: {0}")]
139    Io(#[from] std::io::Error),
140    #[error("key invalid: {0}")]
141    KeyInvalid(String),
142}
143
144/// Internal helper for mapping lower-level errors to SigningError::Internal.
145/// When the "verbose_errors" feature flag is enabled, the helper logs the
146/// underlying error details with the provided context.
147#[inline]
148#[allow(unused_variables)]
149fn internal_error<E: std::fmt::Debug>(err: E, context: &'static str) -> SigningError {
150    #[cfg(feature = "verbose_errors")]
151    {
152        log::error!("{}: {:?}", context, err);
153    }
154    SigningError::Internal
155}
156
157#[macro_export]
158macro_rules! debug_verbose {
159    ($($arg:tt)*) => {
160        #[cfg(feature = "verbose_errors")]
161        {
162            log::debug!($($arg)*);
163        }
164    };
165}
166
167/// A trait repersenting a service or key that can sign a message
168///
169/// Typically this trait would be implemented by a key pair (like in [`KeyPair`]), an HSM, or some secure service like Vault
170#[async_trait::async_trait]
171pub trait Signer: Send + Sync {
172    /// Signs the passed message, and returns the signature.
173    async fn sign(&self, msg: &[u8]) -> Result<Vec<u8>, SigningError>;
174
175    /// Returns the public key associated with the signer
176    fn public_key(&self) -> &[u8];
177
178    /// Returns the signing algorithm used by the signer
179    fn algorithm(&self) -> sdk::signature::Algorithm;
180
181    /// Signs the payload, and returns a signature structure containing the algorithm, public-key, and signature
182    async fn sign_payload(&self, payload: &[u8]) -> Result<sdk::Signature, SigningError> {
183        Ok(sdk::Signature {
184            algorithm: self.algorithm().into(),
185            public_key: self.public_key().into(),
186            signature: self.sign(payload).await?,
187        })
188    }
189
190    /// Signs a [`Message`] and returns a [`SignedRequest`]
191    async fn sign_request<P: Message>(&self, data: P) -> Result<SignedRequest<P>, SigningError> {
192        let payload = data.encode_to_vec();
193        match self.algorithm() {
194            sdk::signature::Algorithm::Ed25519 => {
195                let signature = self.sign_payload(&payload).await?;
196                Ok(SignedRequest {
197                    request_envelope: sdk::RequestEnvelope {
198                        payload,
199                        signature: Some(signature),
200                    },
201                    data,
202                })
203            }
204            algorithm => {
205                let prepared = PreparedTransaction::new(payload, algorithm)?;
206                prepared.verify_integrity()?;
207                let sig_bytes = self.sign_prepared_transaction(&prepared).await?;
208                let signature = sdk::Signature {
209                    algorithm: algorithm.into(),
210                    public_key: self.public_key().to_vec(),
211                    signature: sig_bytes,
212                };
213                Ok(SignedRequest {
214                    request_envelope: sdk::RequestEnvelope {
215                        payload: prepared.payload,
216                        signature: Some(signature),
217                    },
218                    data,
219                })
220            }
221        }
222    }
223
224    /// Signs a pre-computed transaction digest
225    async fn sign_prepared_transaction(
226        &self,
227        _prepared: &PreparedTransaction,
228    ) -> Result<Vec<u8>, SigningError> {
229        Err(SigningError::Internal)
230    }
231
232    /// Adds an endorsement signatured to a [`sdk::Contract`]
233    /// TODO: endorse with the digest-signing path is not supported
234    /// Ed25519PhSha512-mode keys cannot use this method
235    async fn endorse(
236        &self,
237        contract: &mut sdk::Contract,
238        ledger_id: String,
239    ) -> Result<(), SigningError> {
240        let public_key = self.public_key();
241        let already_signed = contract
242            .endorsements
243            .iter()
244            .filter_map(|endorsement| endorsement.signature.as_ref())
245            .any(|signature| signature.public_key == public_key);
246        if !already_signed {
247            contract.endorsements.push(sdk::Endorsement {
248                ledger_id,
249                signature: Some(self.sign_payload(&contract.transactions).await?),
250            })
251        }
252        Ok(())
253    }
254}
255
256/// A P256 or ED25519 key pair
257#[derive(serde::Deserialize)]
258#[serde(try_from = "String", into = "String")]
259pub enum KeyPair {
260    P256(P256),
261    Ed25519(Ed25519),
262}
263
264#[async_trait::async_trait]
265impl Signer for KeyPair {
266    async fn sign(&self, msg: &[u8]) -> Result<Vec<u8>, SigningError> {
267        match self {
268            KeyPair::P256(key_pair) => Signer::sign(key_pair, msg).await,
269            KeyPair::Ed25519(key_pair) => Signer::sign(key_pair, msg).await,
270        }
271    }
272
273    fn public_key(&self) -> &[u8] {
274        match self {
275            KeyPair::P256(key_pair) => Signer::public_key(key_pair),
276            KeyPair::Ed25519(key_pair) => Signer::public_key(key_pair),
277        }
278    }
279
280    fn algorithm(&self) -> sdk::signature::Algorithm {
281        match self {
282            KeyPair::P256(key_pair) => Signer::algorithm(key_pair),
283            KeyPair::Ed25519(key_pair) => Signer::algorithm(key_pair),
284        }
285    }
286
287    async fn sign_prepared_transaction(
288        &self,
289        prepared: &PreparedTransaction,
290    ) -> Result<Vec<u8>, SigningError> {
291        match self {
292            KeyPair::P256(key_pair) => Signer::sign_prepared_transaction(key_pair, prepared).await,
293            KeyPair::Ed25519(key_pair) => {
294                Signer::sign_prepared_transaction(key_pair, prepared).await
295            }
296        }
297    }
298}
299
300impl FromStr for KeyPair {
301    type Err = SigningError;
302    fn from_str(key_pair_enc: &str) -> Result<Self, Self::Err> {
303        Ed25519::from_str(key_pair_enc)
304            .map(KeyPair::Ed25519)
305            .or_else(|_| P256::from_str(key_pair_enc).map(KeyPair::P256))
306    }
307}
308
309impl TryFrom<String> for KeyPair {
310    type Error = SigningError;
311    fn try_from(key_pair: String) -> Result<Self, Self::Error> {
312        key_pair.parse()
313    }
314}
315
316impl fmt::Debug for KeyPair {
317    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318        match self {
319            KeyPair::P256(key_pair) => write!(f, "P256({:?})", Signer::public_key(key_pair)),
320            KeyPair::Ed25519(key_pair) => {
321                write!(f, "Ed25519({:?})", Signer::public_key(key_pair))
322            }
323        }
324    }
325}
326
327#[derive(Clone, Debug)]
328pub struct ArcKeyPair(pub Arc<KeyPair>);
329
330impl<'de> serde::Deserialize<'de> for ArcKeyPair {
331    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
332    where
333        D: serde::Deserializer<'de>,
334    {
335        let encoded = String::deserialize(deserializer)?;
336        let keypair = Ed25519::from_keypair(&encoded)
337            .map(KeyPair::Ed25519)
338            .map_err(serde::de::Error::custom)?;
339        Ok(Self(Arc::new(keypair)))
340    }
341}
342
343impl std::ops::Deref for ArcKeyPair {
344    type Target = Arc<KeyPair>;
345    fn deref(&self) -> &Self::Target {
346        &self.0
347    }
348}
349
350#[async_trait]
351pub trait DynSigner: Send + Sync {
352    async fn sign(&self, msg: &[u8]) -> Result<Vec<u8>, SigningError>;
353
354    fn public_key(&self) -> &[u8];
355
356    fn algorithm(&self) -> sdk::signature::Algorithm;
357
358    async fn sign_prepared_transaction(
359        &self,
360        prepared: &PreparedTransaction,
361    ) -> Result<Vec<u8>, SigningError>;
362}
363
364#[async_trait]
365impl<T: Signer> DynSigner for T {
366    async fn sign(&self, msg: &[u8]) -> Result<Vec<u8>, SigningError> {
367        Signer::sign(self, msg).await
368    }
369
370    fn public_key(&self) -> &[u8] {
371        Signer::public_key(self)
372    }
373
374    fn algorithm(&self) -> sdk::signature::Algorithm {
375        Signer::algorithm(self)
376    }
377
378    async fn sign_prepared_transaction(
379        &self,
380        prepared: &PreparedTransaction,
381    ) -> Result<Vec<u8>, SigningError> {
382        Signer::sign_prepared_transaction(self, prepared).await
383    }
384}
385
386#[derive(Clone)]
387pub struct DynSignerWrapper(pub Arc<dyn DynSigner>);
388
389impl DynSignerWrapper {
390    pub fn new(signer: Arc<dyn DynSigner>) -> Self {
391        Self(signer)
392    }
393}
394
395#[async_trait]
396impl Signer for DynSignerWrapper {
397    async fn sign(&self, msg: &[u8]) -> Result<Vec<u8>, SigningError> {
398        self.0.sign(msg).await
399    }
400
401    fn public_key(&self) -> &[u8] {
402        self.0.public_key()
403    }
404
405    fn algorithm(&self) -> sdk::signature::Algorithm {
406        self.0.algorithm()
407    }
408
409    async fn sign_payload(&self, payload: &[u8]) -> Result<sdk::Signature, SigningError> {
410        let sig = self.0.sign(payload).await?;
411        Ok(sdk::Signature {
412            algorithm: self.0.algorithm().into(),
413            public_key: self.0.public_key().into(),
414            signature: sig,
415        })
416    }
417
418    async fn sign_prepared_transaction(
419        &self,
420        prepared: &PreparedTransaction,
421    ) -> Result<Vec<u8>, SigningError> {
422        self.0.sign_prepared_transaction(prepared).await
423    }
424
425    async fn endorse(
426        &self,
427        contract: &mut sdk::Contract,
428        ledger_id: String,
429    ) -> Result<(), SigningError> {
430        let public_key = self.0.public_key();
431        let already_signed = contract
432            .endorsements
433            .iter()
434            .filter_map(|e| e.signature.as_ref())
435            .any(|s| s.public_key == public_key);
436        if !already_signed {
437            let sig = self.sign_payload(&contract.transactions).await?;
438            contract.endorsements.push(sdk::Endorsement {
439                ledger_id,
440                signature: Some(sig),
441            });
442        }
443        Ok(())
444    }
445}
446
447#[cfg(test)]
448mod tests;