Skip to content

Commit acbeb46

Browse files
committed
Implement Bech32WithHrp trait for [u8]
1 parent 84cd45a commit acbeb46

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

common/src/hash.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -315,7 +315,7 @@ macro_rules! declare_hash_type_with_bech32 {
315315
use crate::serialization::Bech32WithHrp;
316316
use anyhow::Context;
317317

318-
self.to_vec().to_bech32_with_hrp($hrp).with_context(|| {
318+
self.as_ref().to_bech32_with_hrp($hrp).with_context(|| {
319319
format!(
320320
"Failed to encode {} to bech32 with HRP '{}'",
321321
stringify!($name),

common/src/serialization.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,23 @@ impl Bech32WithHrp for Vec<u8> {
115115
Ok(data.to_vec())
116116
}
117117
}
118+
119+
impl Bech32WithHrp for [u8] {
120+
fn to_bech32_with_hrp(&self, hrp: &str) -> Result<String, anyhow::Error> {
121+
let hrp = Hrp::parse(hrp).map_err(|e| anyhow!("Bech32 HRP parse error: {e}"))?;
122+
123+
bech32::encode::<Bech32>(hrp, self).map_err(|e| anyhow!("Bech32 encoding error: {e}"))
124+
}
125+
126+
fn from_bech32_with_hrp(s: &str, expected_hrp: &str) -> Result<Vec<u8>, anyhow::Error> {
127+
let (hrp, data) = bech32::decode(s).map_err(|e| anyhow!("Invalid Bech32 string: {e}"))?;
128+
129+
if hrp != Hrp::parse(expected_hrp)? {
130+
return Err(anyhow!(
131+
"Invalid HRP, expected '{expected_hrp}', got '{hrp}'"
132+
));
133+
}
134+
135+
Ok(data.to_vec())
136+
}
137+
}

0 commit comments

Comments
 (0)