use crate::core::addresscodec::exceptions::XRPLAddressCodecException;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use bs58::Alphabet;
pub(crate) const FAMILY_SEED_PREFIX: [u8; 1] = [0x21];
pub(crate) const ED25519_SEED_PREFIX: [u8; 3] = [0x01, 0xE1, 0x4B];
pub(crate) const ADDRESS_PREFIX_BYTES_MAIN: [u8; 2] = [0x05, 0x44];
pub(crate) const ADDRESS_PREFIX_BYTES_TEST: [u8; 2] = [0x04, 0x93];
pub(crate) const CLASSIC_ADDRESS_ID_LENGTH: usize = 20;
pub(crate) const CLASSIC_ADDRESS_LENGTH: u8 = 20;
pub(crate) const CLASSIC_ADDRESS_PREFIX: [u8; 1] = [0x0];
pub(crate) const NODE_PUBLIC_KEY_PREFIX: [u8; 1] = [0x1C];
pub(crate) const NODE_PUBLIC_KEY_LENGTH: u8 = 33;
pub(crate) const ACCOUNT_PUBLIC_KEY_PREFIX: [u8; 1] = [0x23];
pub(crate) const ACCOUNT_PUBLIC_KEY_LENGTH: u8 = 33;
pub const XRPL_ALPHABET: Alphabet = *bs58::Alphabet::RIPPLE;
pub const SEED_LENGTH: usize = 16;
pub fn decode_base58(
b58_string: &str,
prefix: &[u8],
) -> Result<Vec<u8>, XRPLAddressCodecException> {
let prefix_len = prefix.len();
let decoded = bs58::decode(b58_string)
.with_alphabet(&XRPL_ALPHABET)
.with_check(None)
.into_vec()?;
if &decoded[..prefix_len] != prefix {
Err(XRPLAddressCodecException::InvalidEncodingPrefixLength)
} else {
Ok(decoded[prefix_len..].to_vec())
}
}
pub fn encode_base58(
bytestring: &[u8],
prefix: &[u8],
expected_length: Option<usize>,
) -> Result<String, XRPLAddressCodecException> {
if expected_length != Some(bytestring.len()) {
Err(XRPLAddressCodecException::UnexpectedPayloadLength {
expected: expected_length.expect(""),
found: bytestring.len(),
})
} else {
let mut payload = vec![];
payload.extend_from_slice(prefix);
payload.extend_from_slice(bytestring);
Ok(bs58::encode(payload)
.with_alphabet(&XRPL_ALPHABET)
.with_check()
.into_string())
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::alloc::string::ToString;
const ENCODED: &str = "r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59";
const DECODED: &[u8] = &[
94, 123, 17, 37, 35, 246, 141, 47, 94, 135, 157, 180, 234, 197, 28, 102, 152, 166, 147, 4,
];
#[test]
fn test_decode_base58() {
assert_eq!(decode_base58(ENCODED, &[0x0]), Ok(DECODED.to_vec()));
}
#[test]
fn test_encode_base58() {
assert_eq!(
encode_base58(DECODED, &[0x0], Some(20)),
Ok(ENCODED.to_string())
);
}
}