Skip to main content

miden_protocol/address/
type.rs

1use crate::errors::{AddressError, Bech32Error};
2
3/// The type of an [`Address`](super::Address) in Miden.
4///
5/// The byte values of this address type should be chosen as a multiple of 8. That way, the first
6/// character of the bech32 string after the `1` separator will be different for every address type.
7/// This makes the type of the address conveniently human-readable.
8///
9/// For instance, [`AddressType::AccountId`] is chosen as 232 which is 0b1110_1000 in binary. Base32
10/// encodes one character for every 5 bits and 0b11101 (= 29) translates to `a`. So, every account
11/// ID address will start with `mm1a`.
12///
13/// See the table in the [bech32 spec](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32)
14/// for a convenient overview.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
16#[repr(u8)]
17#[non_exhaustive]
18pub enum AddressType {
19    AccountId = Self::ACCOUNT_ID,
20}
21
22impl AddressType {
23    // Constants for internal use only.
24    const ACCOUNT_ID: u8 = 232;
25}
26
27impl TryFrom<u8> for AddressType {
28    type Error = AddressError;
29
30    /// Decodes an [`AddressType`] from its byte representation.
31    fn try_from(byte: u8) -> Result<Self, Self::Error> {
32        match byte {
33            Self::ACCOUNT_ID => Ok(Self::AccountId),
34            other => Err(AddressError::Bech32DecodeError(Bech32Error::UnknownAddressType(other))),
35        }
36    }
37}