use bech32::primitives::decode::{
CheckedHrpstring, CheckedHrpstringError, ChecksumError, PaddingError,
};
const PQ_HRP: &str = "age1pq";
const CLASSICAL_HRP: &str = "age";
pub(crate) const PQ_KEY_BYTES: usize = 1216;
const CLASSICAL_KEY_BYTES: usize = 32;
enum Bech32Long {}
impl bech32::Checksum for Bech32Long {
type MidstateRepr = u32;
type CorrectionField = <bech32::Bech32 as bech32::Checksum>::CorrectionField;
const ROOT_GENERATOR: Self::CorrectionField = bech32::Bech32::ROOT_GENERATOR;
const ROOT_EXPONENTS: core::ops::RangeInclusive<usize> = bech32::Bech32::ROOT_EXPONENTS;
const CODE_LENGTH: usize = usize::MAX;
const CHECKSUM_LENGTH: usize = bech32::Bech32::CHECKSUM_LENGTH;
const GENERATOR_SH: [u32; 5] = bech32::Bech32::GENERATOR_SH;
const TARGET_RESIDUE: u32 = bech32::Bech32::TARGET_RESIDUE;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RecipientError {
Classical,
NotPostQuantum,
NotLowercase,
Encoding,
Checksum,
Padding,
Length,
}
impl RecipientError {
pub(crate) fn message(self) -> String {
match self {
Self::Classical => format!(
"is a classical age recipient; a post-quantum recipient beginning with \"{PQ_HRP}1\" is required"
),
Self::NotPostQuantum => {
format!("must be a post-quantum age recipient beginning with \"{PQ_HRP}1\"")
}
Self::NotLowercase => "must be lowercase".to_owned(),
Self::Encoding => {
"is not a valid post-quantum age recipient: invalid bech32 encoding".to_owned()
}
Self::Checksum => {
"is not a valid post-quantum age recipient: bad bech32 checksum".to_owned()
}
Self::Padding => {
"is not a valid post-quantum age recipient: non-zero padding bits".to_owned()
}
Self::Length => format!(
"is not a valid post-quantum age recipient: key must be {PQ_KEY_BYTES} bytes"
),
}
}
}
pub(crate) fn check_post_quantum(s: &str) -> Result<(), RecipientError> {
let Some((hrp, _)) = s.rsplit_once('1') else {
return Err(RecipientError::NotPostQuantum);
};
if hrp.eq_ignore_ascii_case(CLASSICAL_HRP) {
return Err(if decode(s, CLASSICAL_KEY_BYTES).is_ok() {
RecipientError::Classical
} else {
RecipientError::NotPostQuantum
});
}
if !hrp.eq_ignore_ascii_case(PQ_HRP) {
return Err(RecipientError::NotPostQuantum);
}
if s.bytes().any(|b| b.is_ascii_uppercase()) {
return Err(RecipientError::NotLowercase);
}
decode(s, PQ_KEY_BYTES)
}
fn decode(s: &str, key_bytes: usize) -> Result<(), RecipientError> {
let parsed = CheckedHrpstring::new::<Bech32Long>(s).map_err(|e| match e {
CheckedHrpstringError::Checksum(ChecksumError::InvalidResidue(_)) => {
RecipientError::Checksum
}
_ => RecipientError::Encoding,
})?;
parsed.validate_segwit_padding().map_err(|e| match e {
PaddingError::NonZero => RecipientError::Padding,
_ => RecipientError::Length,
})?;
if parsed.byte_iter().len() == key_bytes {
Ok(())
} else {
Err(RecipientError::Length)
}
}