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/// Decodes input as base58 into array and checks for its length
15pub fn checked_base58_decode_array<const N: usize>(
16    input: impl AsRef<[u8]>,
17) -> Result<[u8; N], ParseCurveError> {
18    let mut output = [0u8; N];
19    let n = bs58::decode(input.as_ref())
20        // NOTE: `.into_array_const()` doesn't return an error on insufficient
21        // input length and pads the array with zeros
22        .onto(&mut output)?;
23    (n == N)
24        .then_some(output)
25        .ok_or(ParseCurveError::InvalidLength)
26}