Skip to main content

acta_maker_sdk/
wire.rs

1use thiserror::Error;
2
3#[derive(Debug, Error)]
4pub enum WireError {
5    #[error("invalid hex: {0}")]
6    InvalidHex(String),
7    #[error("invalid base58: {0}")]
8    InvalidBase58(String),
9    #[error("invalid length: expected {expected}, got {actual}")]
10    InvalidLength { expected: usize, actual: usize },
11}
12
13pub fn decode_hex_32(hex_str: &str) -> Result<[u8; 32], WireError> {
14    let trimmed = hex_str.strip_prefix("0x").unwrap_or(hex_str);
15    let bytes = hex::decode(trimmed).map_err(|err| WireError::InvalidHex(err.to_string()))?;
16    if bytes.len() != 32 {
17        return Err(WireError::InvalidLength {
18            expected: 32,
19            actual: bytes.len(),
20        });
21    }
22    let mut out = [0u8; 32];
23    out.copy_from_slice(&bytes);
24    Ok(out)
25}
26
27pub fn decode_base58_32(value: &str) -> Result<[u8; 32], WireError> {
28    decode_base58_fixed::<32>(value)
29}
30
31pub fn decode_base58_64(value: &str) -> Result<[u8; 64], WireError> {
32    decode_base58_fixed::<64>(value)
33}
34
35pub fn encode_base58(bytes: &[u8]) -> String {
36    bs58::encode(bytes).into_string()
37}
38
39pub fn encode_hex(bytes: &[u8]) -> String {
40    hex::encode(bytes)
41}
42
43fn decode_base58_fixed<const N: usize>(value: &str) -> Result<[u8; N], WireError> {
44    let bytes = bs58::decode(value)
45        .into_vec()
46        .map_err(|err| WireError::InvalidBase58(err.to_string()))?;
47    if bytes.len() != N {
48        return Err(WireError::InvalidLength {
49            expected: N,
50            actual: bytes.len(),
51        });
52    }
53    let mut out = [0u8; N];
54    out.copy_from_slice(&bytes);
55    Ok(out)
56}