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)]
17pub enum Base58Error {
18 #[error("base58btc output buffer too small")]
20 BufferTooSmall,
21 #[error("base58btc decode failed")]
23 DecodeFailed,
24 #[error("invalid base58btc character")]
26 InvalidCharacter,
27 #[error("non-ascii base58btc character")]
29 NonAsciiCharacter,
30 #[error("base58btc input too large")]
32 InputTooLarge,
33}
34
35impl From<Bs58DecodeError> for Base58Error {
36 fn from(value: Bs58DecodeError) -> Self {
37 match value {
38 Bs58DecodeError::BufferTooSmall => Self::BufferTooSmall,
39 Bs58DecodeError::InvalidCharacter { .. } => Self::InvalidCharacter,
40 Bs58DecodeError::NonAsciiCharacter { .. } => Self::NonAsciiCharacter,
41 _ => Self::DecodeFailed,
42 }
43 }
44}
45
46pub fn base58btc_encode(bytes: &[u8]) -> Result<String, Base58Error> {
48 if bytes.len() > MAX_BASE58BTC_INPUT_LEN {
49 return Err(Base58Error::InputTooLarge);
50 }
51 Ok(bs58::encode(bytes).into_string())
52}
53
54pub fn base58btc_decode(s: &str) -> Result<Vec<u8>, Base58Error> {
58 if s.len() > MAX_BASE58BTC_INPUT_LEN {
59 return Err(Base58Error::InputTooLarge);
60 }
61 bs58::decode(s).into_vec().map_err(Base58Error::from)
62}