#![no_std]
#![cfg_attr(bench, feature(test))]
#![warn(missing_docs)]
#![warn(deprecated_in_future)]
#![doc(test(attr(warn(unused))))]
#![cfg_attr(fuzzing, allow(dead_code, unused_imports))]
#![cfg_attr(bench, allow(dead_code, unused_imports))]
#![allow(clippy::incompatible_msrv)]
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(bench)]
extern crate test;
#[cfg(feature = "std")]
extern crate std;
static BASE58_CHARS: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
pub mod error;
#[cfg(feature = "alloc")]
#[cfg(not(feature = "std"))]
pub use alloc::{string::String, vec::Vec};
#[cfg(feature = "alloc")]
use core::convert::Infallible;
use core::fmt;
#[cfg(feature = "std")]
pub use std::{string::String, vec::Vec};
use hashes::sha256d;
use internals::array::ArrayExt;
use internals::array_vec::ArrayVec;
#[allow(unused)] use internals::slice::SliceExt;
use crate::error::{
Base256Error, DecodeCheckArrayErrorInner, IncorrectChecksumError, TooShortError,
UnexpectedLengthError,
};
#[cfg(not(feature = "alloc"))]
use crate::error::{DecodeCheckError, InputTooLongErrorInner, InvalidCharacterError};
#[rustfmt::skip] #[cfg(feature = "alloc")]
#[doc(no_inline)]
pub use self::error::{DecodeCheckError, InvalidCharacterError};
#[doc(no_inline)]
pub use self::error::{DecodeCheckArrayError, InputTooLongError};
#[rustfmt::skip]
static BASE58_DIGITS: [Option<u8>; 128] = [
None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, Some(0), Some(1), Some(2), Some(3), Some(4), Some(5), Some(6), Some(7), Some(8), None, None, None, None, None, None, None, Some(9), Some(10), Some(11), Some(12), Some(13), Some(14), Some(15), Some(16), None, Some(17), Some(18), Some(19), Some(20), Some(21), None, Some(22), Some(23), Some(24), Some(25), Some(26), Some(27), Some(28), Some(29), Some(30), Some(31), Some(32), None, None, None, None, None, None, Some(33), Some(34), Some(35), Some(36), Some(37), Some(38), Some(39), Some(40), Some(41), Some(42), Some(43), None, Some(44), Some(45), Some(46), Some(47), Some(48), Some(49), Some(50), Some(51), Some(52), Some(53), Some(54), Some(55), Some(56), Some(57), None, None, None, None, None, ];
fn build_base256<T: Buffer>(data: &str, scratch: &mut T) -> Result<(), Base256Error<T::Err>> {
for d58 in data.bytes() {
if usize::from(d58) >= BASE58_DIGITS.len() {
return Err(Base256Error::InvalidChar(InvalidCharacterError::new(d58)));
}
let mut carry = match BASE58_DIGITS[usize::from(d58)] {
Some(d58) => u32::from(d58),
None => {
return Err(Base256Error::InvalidChar(InvalidCharacterError::new(d58)));
}
};
for d256 in scratch.slice_mut() {
carry += u32::from(*d256) * 58;
*d256 = carry as u8; carry /= 256;
}
while carry > 0 {
scratch.try_push(carry as u8).map_err(Base256Error::Buffer)?; carry /= 256;
}
}
Ok(())
}
#[cfg(feature = "alloc")]
pub fn decode(data: &str) -> Result<Vec<u8>, InvalidCharacterError> {
let mut scratch = Vec::with_capacity(1 + data.len() * 11 / 15);
build_base256(data, &mut scratch).map_err(|e| match e {
Base256Error::Buffer(_) => unreachable!("Vec cannot fail try_push"),
Base256Error::InvalidChar(err) => err,
})?;
let mut ret: Vec<u8> = data.bytes().take_while(|&x| x == BASE58_CHARS[0]).map(|_| 0).collect();
ret.extend(scratch.into_iter().rev());
Ok(ret)
}
#[cfg(feature = "alloc")]
pub fn decode_check(data: &str) -> Result<Vec<u8>, DecodeCheckError> {
let mut ret: Vec<u8> = decode(data)?;
let (remaining, &data_check) =
ret.split_last_chunk::<4>().ok_or(TooShortError { length: ret.len() })?;
let hash_check = *sha256d::Hash::hash(remaining).as_byte_array().sub_array::<0, 4>();
let expected = u32::from_le_bytes(hash_check);
let actual = u32::from_le_bytes(data_check);
if actual != expected {
return Err(IncorrectChecksumError { incorrect: actual, expected }.into());
}
ret.truncate(remaining.len());
Ok(ret)
}
#[allow(clippy::missing_panics_doc)] pub fn decode_check_to_array<const N: usize>(data: &str) -> Result<[u8; N], DecodeCheckArrayError> {
let mut scratch = ArrayVec::<u8, SHORT_OPT_BUFFER_LEN>::new();
build_base256(data, &mut scratch)
.map_err(|e| match e {
Base256Error::Buffer(_) =>
DecodeCheckArrayErrorInner::UnexpectedLength(UnexpectedLengthError {
expected: N,
actual: data.len() * 11 / 15,
}),
Base256Error::InvalidChar(err) =>
DecodeCheckArrayErrorInner::Decode(DecodeCheckError::from(err)),
})
.map_err(DecodeCheckArrayError)?;
let leading_zeros = data.bytes().take_while(|&x| x == BASE58_CHARS[0]).count();
let decoded_len = leading_zeros + scratch.len();
let mut decoded = [0u8; SHORT_OPT_BUFFER_LEN];
scratch.as_mut_slice().reverse();
let write_slice = decoded
.get_mut(leading_zeros..decoded_len)
.ok_or(UnexpectedLengthError { expected: N, actual: data.len() * 11 / 15 })
.map_err(DecodeCheckArrayErrorInner::UnexpectedLength)
.map_err(DecodeCheckArrayError)?;
write_slice.copy_from_slice(&scratch);
let decoded = &decoded[..decoded_len];
let (payload, &data_check) = decoded.split_last_chunk::<4>().ok_or_else(|| {
DecodeCheckArrayError(DecodeCheckArrayErrorInner::Decode(DecodeCheckError::from(
TooShortError { length: decoded_len },
)))
})?;
if payload.len() != N {
return Err(DecodeCheckArrayError(DecodeCheckArrayErrorInner::UnexpectedLength(
UnexpectedLengthError { expected: N, actual: payload.len() },
)));
}
let hash_check = *sha256d::Hash::hash(payload).as_byte_array().sub_array::<0, 4>();
let expected = u32::from_le_bytes(hash_check);
let actual = u32::from_le_bytes(data_check);
if actual != expected {
return Err(DecodeCheckArrayError(DecodeCheckArrayErrorInner::Decode(
DecodeCheckError::from(IncorrectChecksumError { incorrect: actual, expected }),
)));
}
Ok(payload.try_into().expect("payload length checked to equal N"))
}
const SHORT_OPT_BUFFER_LEN: usize = 128;
#[derive(Clone, Hash, PartialEq, Eq)]
pub struct Base58CkString(Base58CkInner);
#[derive(Clone, Hash, PartialEq, Eq)]
enum Base58CkInner {
Small(ArrayVec<u8, SHORT_OPT_BUFFER_LEN>),
#[cfg(feature = "alloc")]
Large(Vec<u8>),
}
impl Base58CkString {
pub fn encode(data: &[u8]) -> Result<Self, InputTooLongError> {
#[cfg(feature = "alloc")]
{
Ok(Self::encode_unbounded(data))
}
#[cfg(not(feature = "alloc"))]
{
let mut buf = ArrayVec::<u8, SHORT_OPT_BUFFER_LEN>::new();
let checksum = sha256d::Hash::hash(data);
let iter = data.iter().copied().chain(checksum.as_byte_array()[0..4].iter().copied());
encode_to_buffer(iter, &mut buf)
.map(|()| Self(Base58CkInner::Small(buf)))
.map_err(|_| InputTooLongError(InputTooLongErrorInner { input_len: data.len() }))
}
}
#[allow(clippy::missing_panics_doc)] #[cfg(feature = "alloc")]
pub fn encode_unbounded(data: &[u8]) -> Self {
let checksum = sha256d::Hash::hash(data);
let iter = data.iter().copied().chain(checksum.as_byte_array()[0..4].iter().copied());
let reserve_len = encoded_check_reserve_len(data.len());
if reserve_len <= SHORT_OPT_BUFFER_LEN {
let mut buf = ArrayVec::<u8, SHORT_OPT_BUFFER_LEN>::new();
encode_to_buffer(iter, &mut buf)
.expect("encode_to_buffer is infallible with well-sized ArrayVec buf");
Self(Base58CkInner::Small(buf))
} else {
let mut buf = Vec::with_capacity(reserve_len);
encode_to_buffer(iter, &mut buf).expect("encode_to_buffer is infallible with Vec buf");
Self(Base58CkInner::Large(buf))
}
}
#[allow(clippy::missing_panics_doc)] pub fn as_str(&self) -> &str {
core::str::from_utf8(self.as_bytes()).expect("base58 characters are valid ASCII")
}
pub fn as_bytes(&self) -> &[u8] {
match self.0 {
Base58CkInner::Small(ref data) => data.slice(),
#[cfg(feature = "alloc")]
Base58CkInner::Large(ref data) => data.slice(),
}
}
pub fn len(&self) -> usize { self.as_bytes().len() }
pub fn is_empty(&self) -> bool { self.len() == 0 }
}
impl AsRef<str> for Base58CkString {
fn as_ref(&self) -> &str { self.as_str() }
}
impl AsRef<[u8]> for Base58CkString {
fn as_ref(&self) -> &[u8] { self.as_bytes() }
}
impl fmt::Display for Base58CkString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.as_str().fmt(f) }
}
impl fmt::Debug for Base58CkString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("Base58CkString").field(&self.as_str()).finish()
}
}
#[cfg(feature = "alloc")]
const fn encoded_reserve_len(unencoded_len: usize) -> usize {
unencoded_len * 137 / 100
}
#[cfg(feature = "alloc")]
const fn encoded_check_reserve_len(unencoded_len: usize) -> usize {
encoded_reserve_len(unencoded_len + 4)
}
trait Buffer: Sized {
type Err: fmt::Debug;
fn try_push(&mut self, val: u8) -> Result<(), Self::Err>;
fn slice(&self) -> &[u8];
fn slice_mut(&mut self) -> &mut [u8];
}
#[cfg(feature = "alloc")]
impl Buffer for Vec<u8> {
type Err = Infallible;
fn try_push(&mut self, val: u8) -> Result<(), Self::Err> {
self.push(val);
Ok(())
}
fn slice(&self) -> &[u8] { self }
fn slice_mut(&mut self) -> &mut [u8] { self }
}
impl<const N: usize> Buffer for ArrayVec<u8, N> {
type Err = internals::array_vec::error::Error;
fn try_push(&mut self, val: u8) -> Result<(), Self::Err> { self.try_push(val) }
fn slice(&self) -> &[u8] { self.as_slice() }
fn slice_mut(&mut self) -> &mut [u8] { self.as_mut_slice() }
}
fn encode_to_buffer<I: Iterator<Item = u8>, T: Buffer>(data: I, buf: &mut T) -> Result<(), T::Err> {
let mut leading_zero_count = 0;
let mut leading_zeroes = true;
for d256 in data {
let mut carry = u32::from(d256);
if leading_zeroes && carry == 0 {
leading_zero_count += 1;
} else {
leading_zeroes = false;
}
for ch in buf.slice_mut() {
let new_ch = u32::from(*ch) * 256 + carry;
*ch = (new_ch % 58) as u8; carry = new_ch / 58;
}
while carry > 0 {
buf.try_push((carry % 58) as u8)?; carry /= 58;
}
}
for _ in 0..leading_zero_count {
buf.try_push(0)?;
}
buf.slice_mut().reverse();
for ch in buf.slice_mut() {
*ch = BASE58_CHARS[usize::from(*ch)];
}
Ok(())
}
#[cfg(test)]
mod tests {
#[cfg(feature = "alloc")]
use alloc::vec;
use hex::hex;
use super::*;
#[test]
#[cfg(feature = "alloc")]
fn base58_encode() {
assert_eq!(Base58CkString::encode_unbounded(&[13, 36][..]).as_str(), "7YY3x3vS");
assert_eq!(Base58CkString::encode_unbounded(&[0, 13, 36][..]).as_str(), "17YZPJu4L");
assert_eq!(
Base58CkString::encode_unbounded(&[0, 0, 0, 0, 13, 36][..]).as_str(),
"11117YaXDHva"
);
let res = Base58CkString::encode_unbounded(
"BitcoinBitcoinBitcoinBitcoinBitcoinBitcoinBitcoinBitcoinBitcoinBit\
coinBitcoinBitcoinBitcoinBitcoinBitcoinBitcoinBitcoinBitcoinBitcoinBitcoin"
.as_bytes(),
);
let exp =
"4hqMa7U6Kxg4YstWo7KztyYAAkTuhuLWTvrHia8nrgx5eb2E8cf79wD9dBjd4c9STsTTXWZT5pp985vP\
nL4MVTQrt4EW5jgAk5Fh81PoF6jjhCyUZY2kZ8iYaM5XpfPkZ6aki57S6oiuVv4cmJz2ou8ssxEKNRJMWjSFL5izLbe\
s9rugAdBdrboyHMSAtSNY1Nrb4";
assert_eq!(res.as_str(), exp);
let addr = hex!("00f8917303bfa8ef24f292e8fa1419b20460ba064d");
assert_eq!(
Base58CkString::encode_unbounded(&addr[..]).as_str(),
"1PfJpZsjreyVrqeoAfabrRwwjQyoSQMmHH"
);
}
#[test]
#[cfg(feature = "alloc")]
fn base58_decode() {
assert_eq!(decode("1").ok(), Some(vec![0u8]));
assert_eq!(decode("2").ok(), Some(vec![1u8]));
assert_eq!(decode("21").ok(), Some(vec![58u8]));
assert_eq!(decode("211").ok(), Some(vec![13u8, 36]));
assert_eq!(decode("1211").ok(), Some(vec![0u8, 13, 36]));
assert_eq!(decode("111211").ok(), Some(vec![0u8, 0, 0, 13, 36]));
assert_eq!(
decode_check("1PfJpZsjreyVrqeoAfabrRwwjQyoSQMmHH").ok().unwrap().as_slice(),
hex!("00f8917303bfa8ef24f292e8fa1419b20460ba064d")
);
assert_eq!(decode("ยข").unwrap_err(), InvalidCharacterError::new(194));
}
#[test]
fn decode_check_to_array_roundtrip() {
let addr = hex!("00f8917303bfa8ef24f292e8fa1419b20460ba064d");
let encoded = Base58CkString::encode(&addr).unwrap();
let decoded = decode_check_to_array::<21>(encoded.as_str()).unwrap();
assert_eq!(decoded, addr);
#[cfg(feature = "alloc")]
assert_eq!(decoded.as_slice(), decode_check(encoded.as_str()).unwrap().as_slice());
}
#[test]
fn decode_check_to_array_errors() {
use crate::error::DecodeCheckArrayErrorInner;
const STRING_LEN: usize = SHORT_OPT_BUFFER_LEN + 1;
const APPROX_LEN: usize = STRING_LEN * 11 / 15;
let encoded = "1PfJpZsjreyVrqeoAfabrRwwjQyoSQMmHH";
let err = decode_check_to_array::<20>(encoded).unwrap_err();
assert_eq!(
err,
DecodeCheckArrayError(DecodeCheckArrayErrorInner::UnexpectedLength(
crate::error::UnexpectedLengthError { expected: 20, actual: 21 }
))
);
assert!(matches!(
decode_check_to_array::<21>("ยข").unwrap_err(),
DecodeCheckArrayError(DecodeCheckArrayErrorInner::Decode(_))
));
assert!(matches!(
decode_check_to_array::<21>("1PfJpZsjreyVrqeoAfabrRwwjQyoSQMmHG").unwrap_err(),
DecodeCheckArrayError(DecodeCheckArrayErrorInner::Decode(_))
));
let long = "1".repeat(STRING_LEN);
assert!(matches!(
decode_check_to_array::<21>(&long).unwrap_err(),
DecodeCheckArrayError(DecodeCheckArrayErrorInner::UnexpectedLength(
crate::UnexpectedLengthError { expected: 21, actual: APPROX_LEN }
))
));
}
#[test]
fn decode_check_to_array_at_input_length_limit() {
let encoded = "22UzJUbV3TnAhvzqfW411nkMuSfpgxfYfuuCyNPtrA9EQTViEdsmiBAqEyGP4EGFHb1c7XKWFmjWj9uzBdg8kpCVXAaWVGQmovSTnFjSjEEa9sAZqKUYrvnvgVtPVTuj";
let want = [0xFFu8; 89];
assert_eq!(encoded.len(), SHORT_OPT_BUFFER_LEN);
assert_eq!(decode_check_to_array::<89>(encoded).unwrap(), want);
let encoded = "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111DH4Svg";
let mut want = [0u8; 123];
want[122] = 0x01;
assert_eq!(encoded.len(), SHORT_OPT_BUFFER_LEN);
assert_eq!(decode_check_to_array::<123>(encoded).unwrap(), want);
}
#[test]
fn decode_check_to_array_leading_zeros() {
let data = [0u8, 0, 1, 2, 3];
let encoded = Base58CkString::encode(&data).unwrap();
assert_eq!(decode_check_to_array::<5>(encoded.as_str()).unwrap(), data);
}
#[test]
#[cfg(feature = "alloc")]
fn base58_roundtrip() {
let s = "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs";
let v: Vec<u8> = decode_check(s).unwrap();
assert_eq!(Base58CkString::encode_unbounded(&v[..]).as_str(), s);
assert_eq!(decode_check(Base58CkString::encode_unbounded(&v[..]).as_str()).ok(), Some(v));
assert_eq!(decode_check(Base58CkString::encode_unbounded(&[]).as_str()), Ok(vec![]));
assert_eq!(decode_check("Ldp"), Err(TooShortError { length: 3 }.into()));
}
}
#[cfg(bench)]
mod benches {
use test::{black_box, Bencher};
#[bench]
pub fn bench_encode_check_50(bh: &mut Bencher) {
let data: alloc::vec::Vec<_> = (0u8..50).collect();
bh.iter(|| {
let r = super::Base58CkString::encode_unbounded(&data);
black_box(r.as_str());
});
}
#[bench]
pub fn bench_encode_check_xpub(bh: &mut Bencher) {
let data: alloc::vec::Vec<_> = (0u8..78).collect();
bh.iter(|| {
let r = super::Base58CkString::encode_unbounded(&data);
black_box(r.as_str());
});
}
}