snarkvm_ledger_puzzle/solution_id/
string.rsuse super::*;
pub static SOLUTION_ID_PREFIX: &str = "solution";
impl<N: Network> FromStr for SolutionID<N> {
type Err = Error;
fn from_str(solution_id: &str) -> Result<Self, Self::Err> {
let (hrp, data, variant) = bech32::decode(solution_id)?;
if hrp != SOLUTION_ID_PREFIX {
bail!("Failed to decode solution ID: '{hrp}' is an invalid prefix")
} else if data.is_empty() {
bail!("Failed to decode solution ID: data field is empty")
} else if variant != bech32::Variant::Bech32m {
bail!("Found a solution ID that is not bech32m encoded: {solution_id}");
}
Ok(Self::read_le(&Vec::from_base32(&data)?[..])?)
}
}
impl<N: Network> Debug for SolutionID<N> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Display::fmt(self, f)
}
}
impl<N: Network> Display for SolutionID<N> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let bytes = self.to_bytes_le().map_err(|_| fmt::Error)?;
let string =
bech32::encode(SOLUTION_ID_PREFIX, bytes.to_base32(), bech32::Variant::Bech32m).map_err(|_| fmt::Error)?;
Display::fmt(&string, f)
}
}
#[cfg(test)]
mod tests {
use super::*;
use console::network::MainnetV0;
type CurrentNetwork = MainnetV0;
const ITERATIONS: u64 = 1_000;
#[test]
fn test_string() -> Result<()> {
assert!(SolutionID::<CurrentNetwork>::from_str(&format!("{SOLUTION_ID_PREFIX}1")).is_err());
assert!(SolutionID::<CurrentNetwork>::from_str("").is_err());
let mut rng = TestRng::default();
for _ in 0..ITERATIONS {
let expected = SolutionID::<CurrentNetwork>::from(rng.gen::<u64>());
let candidate = format!("{expected}");
assert_eq!(expected, SolutionID::from_str(&candidate)?);
assert_eq!(SOLUTION_ID_PREFIX, candidate.split('1').next().unwrap());
}
Ok(())
}
#[test]
fn test_display() -> Result<()> {
let mut rng = TestRng::default();
for _ in 0..ITERATIONS {
let expected = SolutionID::<CurrentNetwork>::from(rng.gen::<u64>());
let candidate = expected.to_string();
assert_eq!(format!("{expected}"), candidate);
assert_eq!(SOLUTION_ID_PREFIX, candidate.split('1').next().unwrap());
let candidate_recovered = SolutionID::<CurrentNetwork>::from_str(&candidate.to_string())?;
assert_eq!(expected, candidate_recovered);
}
Ok(())
}
}