use bs58::decode::Error as Bs58DecodeError;
use thiserror::Error;
pub const MAX_BASE58BTC_INPUT_LEN: usize = 8 * 1024;
#[derive(Debug, Error)]
pub enum Base58Error {
#[error("base58btc output buffer too small")]
BufferTooSmall,
#[error("base58btc decode failed")]
DecodeFailed,
#[error("invalid base58btc character")]
InvalidCharacter,
#[error("non-ascii base58btc character")]
NonAsciiCharacter,
#[error("base58btc input too large")]
InputTooLarge,
}
impl From<Bs58DecodeError> for Base58Error {
fn from(value: Bs58DecodeError) -> Self {
match value {
Bs58DecodeError::BufferTooSmall => Self::BufferTooSmall,
Bs58DecodeError::InvalidCharacter { .. } => Self::InvalidCharacter,
Bs58DecodeError::NonAsciiCharacter { .. } => Self::NonAsciiCharacter,
_ => Self::DecodeFailed,
}
}
}
pub fn base58btc_encode(bytes: &[u8]) -> Result<String, Base58Error> {
if bytes.len() > MAX_BASE58BTC_INPUT_LEN {
return Err(Base58Error::InputTooLarge);
}
Ok(bs58::encode(bytes).into_string())
}
pub fn base58btc_decode(s: &str) -> Result<Vec<u8>, Base58Error> {
if s.len() > MAX_BASE58BTC_INPUT_LEN {
return Err(Base58Error::InputTooLarge);
}
bs58::decode(s).into_vec().map_err(Base58Error::from)
}