use std::fmt;
use bech32::{primitives::decode::CheckedHrpstring, Bech32m, Hrp};
use num_bigint::BigUint;
use num_traits::{Num, Zero};
use serde::{Deserialize, Serialize};
use crate::abstractions::NetworkId;
use crate::error::{Result, WalletError};
pub const HRP_PREFIX: &str = "mn";
#[must_use]
pub fn bls_scalar_modulus() -> BigUint {
BigUint::from_str_radix(
"73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001",
16,
)
.expect("hard-coded BLS12-381 scalar modulus is valid hex")
}
fn validate_segment(label: &'static str, s: &str) -> Result<()> {
if s.is_empty() {
return Err(WalletError::Bech32(format!("empty {label} segment")));
}
for ch in s.chars() {
if !(ch.is_ascii_alphabetic() || ch.is_ascii_digit() && ch != '0' || ch == '-') {
return Err(WalletError::Bech32(format!(
"{label} segment `{s}` contains disallowed character `{ch}`: \
allowed set is A-Z a-z 1-9 -"
)));
}
}
Ok(())
}
fn build_hrp_string(type_tag: &str, network: &NetworkId) -> Result<String> {
validate_segment("type", type_tag)?;
let hrp = if matches!(network, NetworkId::MainNet) {
format!("{HRP_PREFIX}_{type_tag}")
} else {
validate_segment("network", network.as_str())?;
format!("{HRP_PREFIX}_{type_tag}_{}", network.as_str())
};
Ok(hrp)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MidnightBech32m {
pub type_tag: String,
pub network: NetworkId,
pub data: Vec<u8>,
}
impl MidnightBech32m {
pub fn new(
type_tag: impl Into<String>,
network: NetworkId,
data: impl Into<Vec<u8>>,
) -> Result<Self> {
let type_tag = type_tag.into();
validate_segment("type", &type_tag)?;
if !matches!(network, NetworkId::MainNet) {
validate_segment("network", network.as_str())?;
}
Ok(Self {
type_tag,
network,
data: data.into(),
})
}
pub fn to_string(&self) -> Result<String> {
let hrp_str = build_hrp_string(&self.type_tag, &self.network)?;
let hrp = Hrp::parse(&hrp_str)
.map_err(|e| WalletError::Bech32(format!("invalid hrp `{hrp_str}`: {e}")))?;
bech32::encode::<Bech32m>(hrp, &self.data)
.map_err(|e| WalletError::Bech32(format!("bech32m encode failed: {e}")))
}
pub fn parse(s: &str) -> Result<Self> {
let parsed = CheckedHrpstring::new::<Bech32m>(s)
.map_err(|e| WalletError::Bech32(format!("bech32m decode failed: {e}")))?;
let hrp = parsed.hrp();
let data: Vec<u8> = parsed.byte_iter().collect();
let hrp_str = hrp.as_str();
let parts: Vec<&str> = hrp_str.split('_').collect();
let (prefix, type_tag, network) = match parts.as_slice() {
[prefix, type_tag] => (*prefix, *type_tag, NetworkId::MainNet),
[prefix, type_tag, net] => (*prefix, *type_tag, NetworkId::from_label(net)),
_ => {
return Err(WalletError::Bech32(format!(
"expected hrp `mn_<type>[_<network>]`, got `{hrp_str}`"
)));
}
};
if prefix != HRP_PREFIX {
return Err(WalletError::Bech32(format!(
"expected prefix `{HRP_PREFIX}`, got `{prefix}`"
)));
}
validate_segment("type", type_tag)?;
if !matches!(network, NetworkId::MainNet) {
validate_segment("network", network.as_str())?;
}
Ok(Self {
type_tag: type_tag.to_owned(),
network,
data,
})
}
}
impl fmt::Display for MidnightBech32m {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.to_string() {
Ok(s) => f.write_str(&s),
Err(_) => Err(fmt::Error),
}
}
}
const SHIELDED_KEY_LEN: usize = 32;
const TYPE_SHIELD_ADDR: &str = "shield-addr";
const TYPE_SHIELD_CPK: &str = "shield-cpk";
const TYPE_SHIELD_EPK: &str = "shield-epk";
const TYPE_SHIELD_ESK: &str = "shield-esk";
const TYPE_UNSHIELDED: &str = "addr";
const TYPE_DUST: &str = "dust";
#[derive(
Clone, PartialEq, Eq, Hash, Serialize, Deserialize, zeroize::Zeroize, zeroize::ZeroizeOnDrop,
)]
pub struct ShieldedEncryptionSecretKey(pub [u8; SHIELDED_KEY_LEN]);
impl fmt::Debug for ShieldedEncryptionSecretKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("<shielded-esk>")
}
}
impl ShieldedEncryptionSecretKey {
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
if bytes.len() != SHIELDED_KEY_LEN {
return Err(WalletError::Bech32(format!(
"shielded encryption secret key must be {SHIELDED_KEY_LEN} bytes, got {}",
bytes.len()
)));
}
let mut out = [0u8; SHIELDED_KEY_LEN];
out.copy_from_slice(bytes);
Ok(Self(out))
}
pub fn encode(&self, network: &NetworkId) -> Result<MidnightBech32m> {
MidnightBech32m::new(TYPE_SHIELD_ESK, network.clone(), self.0.to_vec())
}
pub fn decode(repr: &MidnightBech32m) -> Result<Self> {
if repr.type_tag != TYPE_SHIELD_ESK {
return Err(WalletError::Bech32(format!(
"expected type `{TYPE_SHIELD_ESK}`, got `{}`",
repr.type_tag
)));
}
Self::from_bytes(&repr.data)
}
pub fn parse(s: &str) -> Result<Self> {
Self::decode(&MidnightBech32m::parse(s)?)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ShieldedCoinPublicKey(pub [u8; SHIELDED_KEY_LEN]);
impl ShieldedCoinPublicKey {
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
if bytes.len() != SHIELDED_KEY_LEN {
return Err(WalletError::Bech32(format!(
"shielded coin public key must be {SHIELDED_KEY_LEN} bytes, got {}",
bytes.len()
)));
}
let mut out = [0u8; SHIELDED_KEY_LEN];
out.copy_from_slice(bytes);
Ok(Self(out))
}
pub fn from_hex(s: &str) -> Result<Self> {
let bytes = hex::decode(s).map_err(|e| WalletError::Bech32(e.to_string()))?;
Self::from_bytes(&bytes)
}
#[must_use]
pub fn to_hex(&self) -> String {
hex::encode(self.0)
}
pub fn encode(&self, network: &NetworkId) -> Result<MidnightBech32m> {
MidnightBech32m::new(TYPE_SHIELD_CPK, network.clone(), self.0.to_vec())
}
pub fn decode(repr: &MidnightBech32m) -> Result<Self> {
if repr.type_tag != TYPE_SHIELD_CPK {
return Err(WalletError::Bech32(format!(
"expected type `{TYPE_SHIELD_CPK}`, got `{}`",
repr.type_tag
)));
}
Self::from_bytes(&repr.data)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ShieldedEncryptionPublicKey(pub [u8; SHIELDED_KEY_LEN]);
impl ShieldedEncryptionPublicKey {
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
if bytes.len() != SHIELDED_KEY_LEN {
return Err(WalletError::Bech32(format!(
"shielded encryption public key must be {SHIELDED_KEY_LEN} bytes, got {}",
bytes.len()
)));
}
let mut out = [0u8; SHIELDED_KEY_LEN];
out.copy_from_slice(bytes);
Ok(Self(out))
}
pub fn from_hex(s: &str) -> Result<Self> {
let bytes = hex::decode(s).map_err(|e| WalletError::Bech32(e.to_string()))?;
Self::from_bytes(&bytes)
}
#[must_use]
pub fn to_hex(&self) -> String {
hex::encode(self.0)
}
pub fn encode(&self, network: &NetworkId) -> Result<MidnightBech32m> {
MidnightBech32m::new(TYPE_SHIELD_EPK, network.clone(), self.0.to_vec())
}
pub fn decode(repr: &MidnightBech32m) -> Result<Self> {
if repr.type_tag != TYPE_SHIELD_EPK {
return Err(WalletError::Bech32(format!(
"expected type `{TYPE_SHIELD_EPK}`, got `{}`",
repr.type_tag
)));
}
Self::from_bytes(&repr.data)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ShieldedAddress {
pub coin_public_key: ShieldedCoinPublicKey,
pub encryption_public_key: ShieldedEncryptionPublicKey,
}
impl ShieldedAddress {
#[must_use]
pub fn new(
coin_public_key: ShieldedCoinPublicKey,
encryption_public_key: ShieldedEncryptionPublicKey,
) -> Self {
Self {
coin_public_key,
encryption_public_key,
}
}
pub fn encode(&self, network: &NetworkId) -> Result<MidnightBech32m> {
let mut bytes = Vec::with_capacity(SHIELDED_KEY_LEN * 2);
bytes.extend_from_slice(&self.coin_public_key.0);
bytes.extend_from_slice(&self.encryption_public_key.0);
MidnightBech32m::new(TYPE_SHIELD_ADDR, network.clone(), bytes)
}
pub fn decode(repr: &MidnightBech32m) -> Result<Self> {
if repr.type_tag != TYPE_SHIELD_ADDR {
return Err(WalletError::Bech32(format!(
"expected type `{TYPE_SHIELD_ADDR}`, got `{}`",
repr.type_tag
)));
}
if repr.data.len() != SHIELDED_KEY_LEN * 2 {
return Err(WalletError::Bech32(format!(
"shielded address must be {} bytes, got {}",
SHIELDED_KEY_LEN * 2,
repr.data.len()
)));
}
let (cpk_bytes, epk_bytes) = repr.data.split_at(SHIELDED_KEY_LEN);
Ok(Self {
coin_public_key: ShieldedCoinPublicKey::from_bytes(cpk_bytes)?,
encryption_public_key: ShieldedEncryptionPublicKey::from_bytes(epk_bytes)?,
})
}
pub fn parse(s: &str) -> Result<Self> {
Self::decode(&MidnightBech32m::parse(s)?)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct UnshieldedAddress(pub [u8; SHIELDED_KEY_LEN]);
impl UnshieldedAddress {
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
if bytes.len() != SHIELDED_KEY_LEN {
return Err(WalletError::Bech32(format!(
"unshielded address must be {SHIELDED_KEY_LEN} bytes, got {}",
bytes.len()
)));
}
let mut out = [0u8; SHIELDED_KEY_LEN];
out.copy_from_slice(bytes);
Ok(Self(out))
}
pub fn from_hex(s: &str) -> Result<Self> {
let bytes = hex::decode(s).map_err(|e| WalletError::Bech32(e.to_string()))?;
Self::from_bytes(&bytes)
}
#[must_use]
pub fn to_hex(&self) -> String {
hex::encode(self.0)
}
pub fn encode(&self, network: &NetworkId) -> Result<MidnightBech32m> {
MidnightBech32m::new(TYPE_UNSHIELDED, network.clone(), self.0.to_vec())
}
pub fn decode(repr: &MidnightBech32m) -> Result<Self> {
if repr.type_tag != TYPE_UNSHIELDED {
return Err(WalletError::Bech32(format!(
"expected type `{TYPE_UNSHIELDED}`, got `{}`",
repr.type_tag
)));
}
Self::from_bytes(&repr.data)
}
pub fn parse(s: &str) -> Result<Self> {
Self::decode(&MidnightBech32m::parse(s)?)
}
}
#[allow(clippy::cast_possible_truncation)] fn scale_compact_encode(x: &BigUint) -> Vec<u8> {
if x < &BigUint::from(64u64) {
let v = x.to_u64_digits().first().copied().unwrap_or(0);
return vec![(v as u8) << 2];
}
if x < &BigUint::from(16_384u64) {
let v = x.to_u64_digits().first().copied().unwrap_or(0);
let shifted = (v << 2) | 0b01;
return (shifted as u16).to_le_bytes().to_vec();
}
if x < &(BigUint::from(1u64) << 30) {
let v = x.to_u64_digits().first().copied().unwrap_or(0);
let shifted = (v << 2) | 0b10;
return (shifted as u32).to_le_bytes().to_vec();
}
let mut le = x.to_bytes_le();
while le.last().copied() == Some(0) && le.len() > 1 {
le.pop();
}
let n = le.len();
assert!(
(4..=67).contains(&n),
"SCALE compact big-integer length out of range: {n}"
);
let header = (((n as u8) - 4) << 2) | 0b11;
let mut out = Vec::with_capacity(1 + n);
out.push(header);
out.extend_from_slice(&le);
out
}
fn scale_compact_decode(input: &[u8]) -> Result<(BigUint, usize)> {
let first = *input
.first()
.ok_or_else(|| WalletError::Bech32("SCALE compact: empty input".to_owned()))?;
let mode = first & 0b11;
match mode {
0b00 => Ok((BigUint::from(first >> 2), 1)),
0b01 => {
if input.len() < 2 {
return Err(WalletError::Bech32(
"SCALE compact: truncated 2-byte value".to_owned(),
));
}
let v = u16::from_le_bytes([input[0], input[1]]) >> 2;
Ok((BigUint::from(v), 2))
}
0b10 => {
if input.len() < 4 {
return Err(WalletError::Bech32(
"SCALE compact: truncated 4-byte value".to_owned(),
));
}
let v = u32::from_le_bytes([input[0], input[1], input[2], input[3]]) >> 2;
Ok((BigUint::from(v), 4))
}
0b11 => {
let n = ((first >> 2) as usize) + 4;
if input.len() < 1 + n {
return Err(WalletError::Bech32(
"SCALE compact: truncated big-integer value".to_owned(),
));
}
let bytes = &input[1..=n];
Ok((BigUint::from_bytes_le(bytes), 1 + n))
}
_ => unreachable!(),
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct DustAddress {
pub data: BigUint,
}
impl DustAddress {
pub fn new(data: BigUint) -> Result<Self> {
if data.is_zero() {
return Ok(Self { data });
}
if data >= bls_scalar_modulus() {
return Err(WalletError::Bech32(
"dust address is too large for BLS12-381 scalar field".to_owned(),
));
}
Ok(Self { data })
}
#[must_use]
pub fn serialize(&self) -> Vec<u8> {
scale_compact_encode(&self.data)
}
pub fn deserialize(bytes: &[u8]) -> Result<Self> {
let (data, consumed) = scale_compact_decode(bytes)?;
if consumed != bytes.len() {
return Err(WalletError::Bech32(format!(
"SCALE compact: {} trailing bytes after dust address",
bytes.len() - consumed
)));
}
Self::new(data)
}
pub fn encode(&self, network: &NetworkId) -> Result<MidnightBech32m> {
MidnightBech32m::new(TYPE_DUST, network.clone(), self.serialize())
}
pub fn decode(repr: &MidnightBech32m) -> Result<Self> {
if repr.type_tag != TYPE_DUST {
return Err(WalletError::Bech32(format!(
"expected type `{TYPE_DUST}`, got `{}`",
repr.type_tag
)));
}
Self::deserialize(&repr.data)
}
pub fn parse(s: &str) -> Result<Self> {
Self::decode(&MidnightBech32m::parse(s)?)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn cpk(seed: u8) -> ShieldedCoinPublicKey {
ShieldedCoinPublicKey([seed; SHIELDED_KEY_LEN])
}
fn epk(seed: u8) -> ShieldedEncryptionPublicKey {
ShieldedEncryptionPublicKey([seed; SHIELDED_KEY_LEN])
}
#[test]
fn mainnet_hrp_omits_network_segment() {
let addr = cpk(0x01).encode(&NetworkId::MainNet).unwrap();
let s = addr.to_string().unwrap();
assert!(
s.starts_with("mn_shield-cpk1"),
"mainnet cpk should start with `mn_shield-cpk` then Bech32m separator `1`; got `{s}`"
);
}
#[test]
fn testnet_hrp_includes_network_segment() {
let addr = cpk(0x02).encode(&NetworkId::TestNet).unwrap();
let s = addr.to_string().unwrap();
assert!(
s.starts_with("mn_shield-cpk_testnet1"),
"testnet cpk should start with `mn_shield-cpk_testnet`; got `{s}`"
);
}
#[test]
fn shielded_coin_pk_round_trips() {
let orig = cpk(0x7F);
let encoded = orig.encode(&NetworkId::DevNet).unwrap();
let s = encoded.to_string().unwrap();
let parsed = MidnightBech32m::parse(&s).unwrap();
let back = ShieldedCoinPublicKey::decode(&parsed).unwrap();
assert_eq!(orig, back);
assert_eq!(parsed.network, NetworkId::DevNet);
}
#[test]
fn shielded_address_round_trips_on_mainnet() {
let orig = ShieldedAddress::new(cpk(0x11), epk(0x22));
let s = orig
.encode(&NetworkId::MainNet)
.unwrap()
.to_string()
.unwrap();
let back = ShieldedAddress::parse(&s).unwrap();
assert_eq!(orig, back);
}
#[test]
fn unshielded_address_round_trips() {
let orig = UnshieldedAddress([0xAB; SHIELDED_KEY_LEN]);
let s = orig
.encode(&NetworkId::TestNet)
.unwrap()
.to_string()
.unwrap();
let back = UnshieldedAddress::parse(&s).unwrap();
assert_eq!(orig, back);
}
#[test]
fn custom_network_round_trips() {
let orig = cpk(0x55);
let s = orig
.encode(&NetworkId::Custom("local42".into()))
.unwrap()
.to_string()
.unwrap();
let parsed = MidnightBech32m::parse(&s).unwrap();
assert_eq!(parsed.network, NetworkId::Custom("local42".into()));
}
#[test]
fn wrong_type_is_rejected_on_decode() {
let s = cpk(0x01)
.encode(&NetworkId::MainNet)
.unwrap()
.to_string()
.unwrap();
let parsed = MidnightBech32m::parse(&s).unwrap();
let err = UnshieldedAddress::decode(&parsed).unwrap_err();
assert!(matches!(err, WalletError::Bech32(_)));
}
#[test]
fn invalid_segment_characters_rejected() {
let err = MidnightBech32m::new("bad type", NetworkId::MainNet, vec![]).unwrap_err();
assert!(matches!(err, WalletError::Bech32(_)));
}
#[test]
fn dust_address_rejects_values_above_bls_modulus() {
let over = bls_scalar_modulus() + BigUint::from(1u8);
assert!(DustAddress::new(over).is_err());
assert!(DustAddress::new(bls_scalar_modulus()).is_err());
}
#[test]
fn dust_address_round_trips_small_and_large() {
for hex_val in [
"0",
"1",
"3f", "40", "3fff", "4000", "3fffffff", "40000000", "73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000",
] {
let n = BigUint::from_str_radix(hex_val, 16).unwrap();
let orig = DustAddress::new(n).unwrap();
let s = orig
.encode(&NetworkId::MainNet)
.unwrap()
.to_string()
.unwrap();
let back = DustAddress::parse(&s).unwrap();
assert_eq!(orig, back, "round-trip failed for hex_val = `{hex_val}`");
}
}
#[test]
fn scale_compact_encoding_boundaries() {
assert_eq!(scale_compact_encode(&BigUint::from(0u8)), vec![0b0000_0000]);
assert_eq!(
scale_compact_encode(&BigUint::from(63u8)),
vec![0b1111_1100]
);
assert_eq!(
scale_compact_encode(&BigUint::from(64u16)),
vec![0b0000_0001, 0b0000_0001]
);
assert_eq!(
scale_compact_encode(&BigUint::from(16_383u16)),
vec![0b1111_1101, 0b1111_1111]
);
let mut lb_4 = scale_compact_encode(&BigUint::from(16_384u32));
assert_eq!(lb_4.len(), 4);
assert_eq!(lb_4[0] & 0b11, 0b10);
lb_4.clear();
for v in [
0u128,
63,
64,
16_383,
16_384,
(1u128 << 30) - 1,
1u128 << 30,
] {
let x = BigUint::from(v);
let enc = scale_compact_encode(&x);
let (dec, n) = scale_compact_decode(&enc).unwrap();
assert_eq!(x, dec);
assert_eq!(n, enc.len());
}
}
}