Skip to main content

codec_multibase/
base58btc.rs

1// SPDX-FileCopyrightText: Copyright © 2026 ReallyMe LLC. All rights reserved
2//
3// SPDX-License-Identifier: Apache-2.0
4
5use bs58::decode::Error as Bs58DecodeError;
6use thiserror::Error;
7
8/// Error returned when base58btc decoding fails.
9#[derive(Debug, Error)]
10pub enum Base58Error {
11    /// The output buffer was too small to hold the decoded bytes.
12    #[error("base58btc output buffer too small")]
13    BufferTooSmall,
14    /// Decoding failed for a reason not covered by the other variants.
15    #[error("base58btc decode failed")]
16    DecodeFailed,
17    /// The input contained a character outside the base58btc alphabet.
18    #[error("invalid base58btc character")]
19    InvalidCharacter,
20    /// The input contained a non-ASCII character.
21    #[error("non-ascii base58btc character")]
22    NonAsciiCharacter,
23}
24
25impl From<Bs58DecodeError> for Base58Error {
26    fn from(value: Bs58DecodeError) -> Self {
27        match value {
28            Bs58DecodeError::BufferTooSmall => Self::BufferTooSmall,
29            Bs58DecodeError::InvalidCharacter { .. } => Self::InvalidCharacter,
30            Bs58DecodeError::NonAsciiCharacter { .. } => Self::NonAsciiCharacter,
31            _ => Self::DecodeFailed,
32        }
33    }
34}
35
36/// Encodes bytes as a base58btc string.
37pub fn base58btc_encode(bytes: &[u8]) -> String {
38    bs58::encode(bytes).into_string()
39}
40
41/// Decodes a base58btc string into bytes.
42///
43/// Fails closed: returns an error on any invalid or non-ASCII character.
44pub fn base58btc_decode(s: &str) -> Result<Vec<u8>, Base58Error> {
45    bs58::decode(s).into_vec().map_err(Base58Error::from)
46}