|
@@ -61,25 +61,16 @@ macro_rules! BinaryId {
|
|
|
impl TryFrom<&str> for $id {
|
|
|
type Error = Error;
|
|
|
fn try_from(value: &str) -> Result<Self, Self::Error> {
|
|
|
- if $suffix.len() + 64 != value.len() {
|
|
|
- return Err(Error::InvalidLength(
|
|
|
- stringify!($id).to_owned(),
|
|
|
- value.len(),
|
|
|
- $suffix.len() + 64,
|
|
|
- ));
|
|
|
- }
|
|
|
-
|
|
|
- if !value.starts_with($suffix) {
|
|
|
- return Err(Error::InvalidLength(
|
|
|
+ let (hrp, bytes) = bech32::decode(&value)?;
|
|
|
+ let hrp = hrp.to_string();
|
|
|
+ if hrp != $suffix {
|
|
|
+ return Err(Error::InvalidPrefix(
|
|
|
stringify!($id).to_owned(),
|
|
|
- value.len(),
|
|
|
- $suffix.len() + 64,
|
|
|
+ $suffix.to_owned(),
|
|
|
+ hrp,
|
|
|
));
|
|
|
}
|
|
|
|
|
|
- let bytes = hex::decode(&value[$suffix.len()..]).map_err(|_| {
|
|
|
- Error::InvalidLength(stringify!($id).to_owned(), value.len(), 32)
|
|
|
- })?;
|
|
|
bytes.try_into()
|
|
|
}
|
|
|
}
|
|
@@ -120,7 +111,13 @@ macro_rules! BinaryId {
|
|
|
|
|
|
impl Display for $id {
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
- write!(f, "{}{}", $suffix, hex::encode(self.bytes))
|
|
|
+ let hrp = bech32::Hrp::parse($suffix).map_err(|_| std::fmt::Error)?;
|
|
|
+ write!(
|
|
|
+ f,
|
|
|
+ "{}",
|
|
|
+ bech32::encode::<bech32::Bech32m>(hrp, &self.bytes)
|
|
|
+ .map_err(|_| std::fmt::Error)?
|
|
|
+ )
|
|
|
}
|
|
|
}
|
|
|
|