Skip to content

Commit

Permalink
add spec and hrp
Browse files Browse the repository at this point in the history
  • Loading branch information
joyqvq committed Dec 19, 2023
1 parent de2d73a commit edeccf0
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions fastcrypto/src/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,12 @@ impl<'de, const N: usize> DeserializeAs<'de, [u8; N]> for Base58 {
pub struct Bech32(String);

impl Bech32 {
/// Decodes the Bech32 string to bytes, validating the given human readable part (hrp). See spec: https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki
/// # Example:
/// ```
/// let bytes = Bech32::decode("split1qqqqsk5gh5","split").unwrap();
/// assert_eq!(bytes, vec![0, 0]);
/// ```
pub fn decode(s: &str, hrp: &str) -> Result<Vec<u8>, eyre::Report> {
let (parsed, data, variant) = bech32::decode(s).map_err(|e| eyre::eyre!(e))?;
if parsed != hrp || variant != Variant::Bech32 {
Expand All @@ -281,6 +287,12 @@ impl Bech32 {
}
}

/// Encodes bytes into a Bech32 encoded string, with the given human readable part (hrp). See spec: https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki
/// # Example:
/// ```
/// let str = Bech32::encode(vec![0, 0],"split").unwrap();
/// assert_eq!(str, "split1qqqqsk5gh5".to_string());
/// ```
pub fn encode<T: AsRef<[u8]>>(data: T, hrp: &str) -> Result<String> {
use bech32::ToBase32;
bech32::encode(hrp, data.to_base32(), Variant::Bech32).map_err(|e| eyre::eyre!(e))
Expand Down

0 comments on commit edeccf0

Please sign in to comment.