defuse_crypto/
parse.rs

1use near_sdk::bs58;
2use thiserror::Error as ThisError;
3
4#[derive(Debug, ThisError, PartialEq, Eq)]
5pub enum ParseCurveError {
6    #[error("wrong curve type")]
7    WrongCurveType,
8    #[error("base58: {0}")]
9    Base58(#[from] bs58::decode::Error),
10    #[error("invalid length")]
11    InvalidLength,
12}
13
14#[cfg(any(feature = "ed25519", feature = "secp256k1", feature = "p256"))]
15/// Decodes input as base58 into array and checks for its length
16pub fn checked_base58_decode_array<const N: usize>(
17    input: impl AsRef<[u8]>,
18) -> Result<[u8; N], ParseCurveError> {
19    let mut output = [0u8; N];
20    let n = bs58::decode(input.as_ref())
21        // NOTE: `.into_array_const()` doesn't return an error on insufficient
22        // input length and pads the array with zeros
23        .onto(&mut output)?;
24    (n == N)
25        .then_some(output)
26        .ok_or(ParseCurveError::InvalidLength)
27}