codec_multibase/
base58btc.rs1use bs58::decode::Error as Bs58DecodeError;
6use thiserror::Error;
7
8pub const MAX_BASE58BTC_INPUT_LEN: usize = 8 * 1024;
14
15#[derive(Debug, Error)]
17#[non_exhaustive]
18pub enum Base58Error {
19 #[error("base58btc output buffer too small")]
21 BufferTooSmall,
22 #[error("base58btc decode failed")]
24 DecodeFailed,
25 #[error("invalid base58btc character")]
27 InvalidCharacter,
28 #[error("non-ascii base58btc character")]
30 NonAsciiCharacter,
31 #[error("base58btc input too large")]
33 InputTooLarge,
34}
35
36impl From<Bs58DecodeError> for Base58Error {
37 fn from(value: Bs58DecodeError) -> Self {
38 match value {
39 Bs58DecodeError::BufferTooSmall => Self::BufferTooSmall,
40 Bs58DecodeError::InvalidCharacter { .. } => Self::InvalidCharacter,
41 Bs58DecodeError::NonAsciiCharacter { .. } => Self::NonAsciiCharacter,
42 _ => Self::DecodeFailed,
43 }
44 }
45}
46
47pub fn base58btc_encode(bytes: &[u8]) -> Result<String, Base58Error> {
49 if bytes.len() > MAX_BASE58BTC_INPUT_LEN {
50 return Err(Base58Error::InputTooLarge);
51 }
52 Ok(bs58::encode(bytes).into_string())
53}
54
55pub fn base58btc_decode(s: &str) -> Result<Vec<u8>, Base58Error> {
59 if s.len() > MAX_BASE58BTC_INPUT_LEN {
60 return Err(Base58Error::InputTooLarge);
61 }
62 bs58::decode(s).into_vec().map_err(Base58Error::from)
63}