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/// Maximum accepted base58btc input length.
9///
10/// The underlying base58 conversion is not linear in input size. This cap keeps
11/// untrusted byte and text inputs bounded while leaving headroom above the
12/// largest currently supported multikey encodings.
13pub const MAX_BASE58BTC_INPUT_LEN: usize = 8 * 1024;
14
15/// Error returned when base58btc decoding fails.
16#[derive(Debug, Error)]
17pub enum Base58Error {
18    /// The output buffer was too small to hold the decoded bytes.
19    #[error("base58btc output buffer too small")]
20    BufferTooSmall,
21    /// Decoding failed for a reason not covered by the other variants.
22    #[error("base58btc decode failed")]
23    DecodeFailed,
24    /// The input contained a character outside the base58btc alphabet.
25    #[error("invalid base58btc character")]
26    InvalidCharacter,
27    /// The input contained a non-ASCII character.
28    #[error("non-ascii base58btc character")]
29    NonAsciiCharacter,
30    /// The input exceeded the accepted base58btc text length.
31    #[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
46/// Encodes bytes as a base58btc string.
47pub 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
54/// Decodes a base58btc string into bytes.
55///
56/// Fails closed: returns an error on any invalid or non-ASCII character.
57pub 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}