|
| 1 | +//! Conversion functions |
| 2 | +
|
| 3 | +use displaydoc::Display; |
| 4 | +use thiserror::Error; |
| 5 | + |
| 6 | +/// Errors that can occur when converting bytes to an Ed25519 verifying key. |
| 7 | +#[derive(Display, Debug, Error)] |
| 8 | +pub enum VKeyFromBytesError { |
| 9 | + /// Invalid byte length: expected {expected} bytes, got {actual} |
| 10 | + InvalidLength { |
| 11 | + /// The expected number of bytes (must be 32). |
| 12 | + expected: usize, |
| 13 | + /// The actual number of bytes in the provided input. |
| 14 | + actual: usize, |
| 15 | + }, |
| 16 | + /// Failed to parse Ed25519 public key: {source} |
| 17 | + ParseError { |
| 18 | + /// The underlying error from `ed25519_dalek`. |
| 19 | + #[from] |
| 20 | + source: ed25519_dalek::SignatureError, |
| 21 | + }, |
| 22 | +} |
| 23 | + |
| 24 | +/// Convert an `<T>` to `<R>` (saturate if out of range). |
| 25 | +/// Note can convert any int to float, or f32 to f64 as well. |
| 26 | +/// can not convert from float to int, or f64 to f32. |
| 27 | +pub fn from_saturating< |
| 28 | + R: Copy + num_traits::identities::Zero + num_traits::Bounded, |
| 29 | + T: Copy |
| 30 | + + TryInto<R> |
| 31 | + + std::ops::Sub<Output = T> |
| 32 | + + std::cmp::PartialOrd<T> |
| 33 | + + num_traits::identities::Zero, |
| 34 | +>( |
| 35 | + value: T, |
| 36 | +) -> R { |
| 37 | + match value.try_into() { |
| 38 | + Ok(value) => value, |
| 39 | + Err(_) => { |
| 40 | + // If we couldn't convert, its out of range for the destination type. |
| 41 | + if value > T::zero() { |
| 42 | + // If the number is positive, its out of range in the positive direction. |
| 43 | + R::max_value() |
| 44 | + } else { |
| 45 | + // Otherwise its out of range in the negative direction. |
| 46 | + R::min_value() |
| 47 | + } |
| 48 | + }, |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +/// Try and convert a byte array into an Ed25519 verifying key. |
| 53 | +/// |
| 54 | +/// # Errors |
| 55 | +/// |
| 56 | +/// Fails if the bytes are not a valid ED25519 Public Key |
| 57 | +pub fn vkey_from_bytes(bytes: &[u8]) -> Result<ed25519_dalek::VerifyingKey, VKeyFromBytesError> { |
| 58 | + if bytes.len() != ed25519_dalek::PUBLIC_KEY_LENGTH { |
| 59 | + return Err(VKeyFromBytesError::InvalidLength { |
| 60 | + expected: ed25519_dalek::PUBLIC_KEY_LENGTH, |
| 61 | + actual: bytes.len(), |
| 62 | + }); |
| 63 | + } |
| 64 | + |
| 65 | + let mut ed25519 = [0u8; ed25519_dalek::PUBLIC_KEY_LENGTH]; |
| 66 | + ed25519.copy_from_slice(bytes); // Can't panic because we already validated its size. |
| 67 | + |
| 68 | + ed25519_dalek::VerifyingKey::from_bytes(&ed25519) |
| 69 | + .map_err(|source| VKeyFromBytesError::ParseError { source }) |
| 70 | +} |
0 commit comments