pub fn base64_decode(input: &str) -> Option<Vec<u8>> {
fn sextet(c: u8) -> Option<u32> {
Some(match c {
b'A'..=b'Z' => u32::from(c - b'A'),
b'a'..=b'z' => u32::from(c - b'a' + 26),
b'0'..=b'9' => u32::from(c - b'0' + 52),
b'+' | b'-' => 62,
b'/' | b'_' => 63,
_ => return None,
})
}
let bytes = input.as_bytes();
if bytes.len() % 4 != 0 {
return None;
}
let padding = bytes.iter().rev().take_while(|&&c| c == b'=').count();
let body = bytes.get(..bytes.len() - padding)?;
if padding > 2 || body.contains(&b'=') {
return None;
}
let mut out = Vec::with_capacity(bytes.len() * 3 / 4);
let mut acc = 0u32;
let mut bits = 0u32;
for &c in body {
acc = (acc << 6) | sextet(c)?;
bits += 6;
if bits >= 8 {
bits -= 8;
#[allow(
clippy::cast_possible_truncation,
reason = "bits was just reduced below 8, so acc >> bits carries exactly the newly completed byte in its low 8 bits; anything the cast drops above that is a sextet already pushed in an earlier iteration"
)]
out.push((acc >> bits) as u8);
}
}
if acc & ((1 << bits) - 1) != 0 {
return None;
}
Some(out)
}
pub fn crc16(data: &[u8]) -> u16 {
let mut crc: u16 = 0;
for &byte in data {
crc ^= u16::from(byte) << 8;
for _ in 0..8 {
crc = if crc & 0x8000 != 0 {
(crc << 1) ^ 0x1021
} else {
crc << 1
};
}
}
crc
}
pub fn decode_hex(input: &str) -> Option<Vec<u8>> {
ton_net_cell::hex_decode(input).ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn hex(bytes: &[u8]) -> String {
use std::fmt::Write as _;
bytes.iter().fold(String::new(), |mut hex, b| {
let _ = write!(hex, "{b:02x}");
hex
})
}
#[test]
fn base64_decodes_a_config_key() {
let key = base64_decode("n4VDnSCUuSpjnCyUk9e3QOOd6o0ItSWYbTnW3Wnn8wk=").unwrap();
assert_eq!(
hex(&key),
"9f85439d2094b92a639c2c9493d7b740e39dea8d08b525986d39d6dd69e7f309"
);
}
#[test]
fn base64_decodes_the_url_safe_alphabet() {
assert_eq!(base64_decode("-_8=").unwrap(), vec![0xfb, 0xff]);
}
#[test]
fn base64_rejects_an_invalid_character() {
assert!(base64_decode("****").is_none());
}
#[test]
fn both_alphabets_spell_one_value() {
const TAKEN: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/-_";
let mut spellings = Vec::new();
for &high in TAKEN {
for &middle in TAKEN {
for &low in TAKEN {
let text = String::from_utf8(vec![high, middle, low, b'='])
.expect("the alphabet is ascii");
if base64_decode(&text).as_deref() == Some(&[0xfb, 0xff][..]) {
spellings.push(text);
}
}
}
}
assert_eq!(spellings, ["+/8=", "+_8=", "-/8=", "-_8="]);
}
#[test]
fn both_alphabets_spell_one_address() {
let url_safe = "EQD8uRo6OBbQ97jCx2EIuKm8Wmt6Vb15-KsQHFLbKSMiYM0w";
let standard = "EQD8uRo6OBbQ97jCx2EIuKm8Wmt6Vb15+KsQHFLbKSMiYM0w";
assert_ne!(url_safe, standard, "two strings, not one");
assert_eq!(
base64_decode(url_safe).unwrap(),
base64_decode(standard).unwrap()
);
assert_eq!(
crate::Address::parse(url_safe).unwrap(),
crate::Address::parse(standard).unwrap()
);
}
#[test]
fn crc16_matches_the_reference() {
let mut preimage = vec![0x11, 0xff];
preimage.extend_from_slice(&[0x33; 32]);
assert_eq!(crc16(&preimage), 0x4bc5);
}
#[test]
fn decode_hex_round_trips() {
assert_eq!(decode_hex("00ff10").unwrap(), vec![0x00, 0xff, 0x10]);
assert!(decode_hex("0").is_none());
assert!(decode_hex("zz").is_none());
}
#[test]
fn decode_hex_refuses_a_leading_sign() {
assert_eq!(decode_hex("0f").unwrap(), vec![0x0f]);
assert!(decode_hex("+f").is_none());
assert!(decode_hex("+f+f").is_none());
}
}