Skip to main content

moonproof_wallet/
address.rs

1//! Midnight address formats — Bech32m with a `mn` HRP.
2//!
3//! Port of `@midnight-ntwrk/wallet-sdk-address-format`. Matches the TS
4//! reference byte-for-byte:
5//!
6//! - Human-readable part: `mn_<type>[_<network>]`. `network` is omitted on
7//!   mainnet (so `mn_shield-addr` is implicitly mainnet).
8//! - `shield-addr` — shielded address (64 bytes: coin PK || encryption PK)
9//! - `shield-cpk` — shielded coin public key (32 bytes)
10//! - `shield-epk` — shielded encryption public key (32 bytes)
11//! - `addr` — unshielded address (32 bytes)
12//! - `dust` — dust public key, SCALE-compact-encoded big integer (≤ BLS
13//!   scalar modulus)
14//!
15//! Segment character set: `[A-Za-z1-9-]` per the TS reference.
16
17use std::fmt;
18
19use bech32::{primitives::decode::CheckedHrpstring, Bech32m, Hrp};
20use num_bigint::BigUint;
21use num_traits::{Num, Zero};
22use serde::{Deserialize, Serialize};
23
24use crate::abstractions::NetworkId;
25use crate::error::{Result, WalletError};
26
27/// HRP prefix for all Midnight Bech32m addresses.
28pub const HRP_PREFIX: &str = "mn";
29
30/// BLS12-381 scalar modulus (base of `midnight-curves::Fr`). A `DustAddress`
31/// must be `< modulus`; the BLS scalar field has ~254 bits.
32#[must_use]
33pub fn bls_scalar_modulus() -> BigUint {
34    // 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001
35    BigUint::from_str_radix(
36        "73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001",
37        16,
38    )
39    .expect("hard-coded BLS12-381 scalar modulus is valid hex")
40}
41
42/// Validate a Bech32m segment (type / network) — same regex as the TS
43/// reference: `[A-Za-z1-9-]+`.
44fn validate_segment(label: &'static str, s: &str) -> Result<()> {
45    if s.is_empty() {
46        return Err(WalletError::Bech32(format!("empty {label} segment")));
47    }
48    for ch in s.chars() {
49        if !(ch.is_ascii_alphabetic() || ch.is_ascii_digit() && ch != '0' || ch == '-') {
50            return Err(WalletError::Bech32(format!(
51                "{label} segment `{s}` contains disallowed character `{ch}`: \
52                 allowed set is A-Z a-z 1-9 -"
53            )));
54        }
55    }
56    Ok(())
57}
58
59fn build_hrp_string(type_tag: &str, network: &NetworkId) -> Result<String> {
60    validate_segment("type", type_tag)?;
61    let hrp = if matches!(network, NetworkId::MainNet) {
62        format!("{HRP_PREFIX}_{type_tag}")
63    } else {
64        validate_segment("network", network.as_str())?;
65        format!("{HRP_PREFIX}_{type_tag}_{}", network.as_str())
66    };
67    Ok(hrp)
68}
69
70/// A parsed Midnight Bech32m representation: prefix + type + optional
71/// network + payload bytes.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct MidnightBech32m {
74    pub type_tag: String,
75    pub network: NetworkId,
76    pub data: Vec<u8>,
77}
78
79impl MidnightBech32m {
80    /// Construct directly. Segments are validated; bytes are taken as-is.
81    pub fn new(
82        type_tag: impl Into<String>,
83        network: NetworkId,
84        data: impl Into<Vec<u8>>,
85    ) -> Result<Self> {
86        let type_tag = type_tag.into();
87        validate_segment("type", &type_tag)?;
88        if !matches!(network, NetworkId::MainNet) {
89            validate_segment("network", network.as_str())?;
90        }
91        Ok(Self {
92            type_tag,
93            network,
94            data: data.into(),
95        })
96    }
97
98    /// Encode to the canonical Bech32m string form.
99    pub fn to_string(&self) -> Result<String> {
100        let hrp_str = build_hrp_string(&self.type_tag, &self.network)?;
101        let hrp = Hrp::parse(&hrp_str)
102            .map_err(|e| WalletError::Bech32(format!("invalid hrp `{hrp_str}`: {e}")))?;
103        bech32::encode::<Bech32m>(hrp, &self.data)
104            .map_err(|e| WalletError::Bech32(format!("bech32m encode failed: {e}")))
105    }
106
107    /// Parse a Bech32m-encoded string back into prefix/type/network/data.
108    pub fn parse(s: &str) -> Result<Self> {
109        let parsed = CheckedHrpstring::new::<Bech32m>(s)
110            .map_err(|e| WalletError::Bech32(format!("bech32m decode failed: {e}")))?;
111        let hrp = parsed.hrp();
112        let data: Vec<u8> = parsed.byte_iter().collect();
113
114        let hrp_str = hrp.as_str();
115        let parts: Vec<&str> = hrp_str.split('_').collect();
116        let (prefix, type_tag, network) = match parts.as_slice() {
117            [prefix, type_tag] => (*prefix, *type_tag, NetworkId::MainNet),
118            [prefix, type_tag, net] => (*prefix, *type_tag, NetworkId::from_label(net)),
119            _ => {
120                return Err(WalletError::Bech32(format!(
121                    "expected hrp `mn_<type>[_<network>]`, got `{hrp_str}`"
122                )));
123            }
124        };
125        if prefix != HRP_PREFIX {
126            return Err(WalletError::Bech32(format!(
127                "expected prefix `{HRP_PREFIX}`, got `{prefix}`"
128            )));
129        }
130        validate_segment("type", type_tag)?;
131        if !matches!(network, NetworkId::MainNet) {
132            validate_segment("network", network.as_str())?;
133        }
134
135        Ok(Self {
136            type_tag: type_tag.to_owned(),
137            network,
138            data,
139        })
140    }
141}
142
143impl fmt::Display for MidnightBech32m {
144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145        match self.to_string() {
146            Ok(s) => f.write_str(&s),
147            Err(_) => Err(fmt::Error),
148        }
149    }
150}
151
152// --- Shielded types -------------------------------------------------------
153
154const SHIELDED_KEY_LEN: usize = 32;
155const TYPE_SHIELD_ADDR: &str = "shield-addr";
156const TYPE_SHIELD_CPK: &str = "shield-cpk";
157const TYPE_SHIELD_EPK: &str = "shield-epk";
158const TYPE_SHIELD_ESK: &str = "shield-esk";
159const TYPE_UNSHIELDED: &str = "addr";
160const TYPE_DUST: &str = "dust";
161
162/// A shielded encryption **secret** key, serialized as 32 bytes. Bech32m
163/// HRP is `mn_shield-esk_<network>`. This is the payload the indexer's
164/// `connect(viewingKey)` mutation accepts — the indexer uses it to
165/// attempt decryption of each zswap output's ciphertext during the
166/// relevance check.
167///
168/// **Handle with care.** Holding a `ShieldedEncryptionSecretKey` gives
169/// the holder view-only access to every shielded coin encrypted to the
170/// corresponding public key. The inner bytes are zeroized on drop.
171#[derive(
172    Clone, PartialEq, Eq, Hash, Serialize, Deserialize, zeroize::Zeroize, zeroize::ZeroizeOnDrop,
173)]
174pub struct ShieldedEncryptionSecretKey(pub [u8; SHIELDED_KEY_LEN]);
175
176impl fmt::Debug for ShieldedEncryptionSecretKey {
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        f.write_str("<shielded-esk>")
179    }
180}
181
182impl ShieldedEncryptionSecretKey {
183    /// Wrap an already-serialized 32-byte representation. The bytes must
184    /// be what `encryption::SecretKey::repr()` would produce.
185    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
186        if bytes.len() != SHIELDED_KEY_LEN {
187            return Err(WalletError::Bech32(format!(
188                "shielded encryption secret key must be {SHIELDED_KEY_LEN} bytes, got {}",
189                bytes.len()
190            )));
191        }
192        let mut out = [0u8; SHIELDED_KEY_LEN];
193        out.copy_from_slice(bytes);
194        Ok(Self(out))
195    }
196
197    pub fn encode(&self, network: &NetworkId) -> Result<MidnightBech32m> {
198        MidnightBech32m::new(TYPE_SHIELD_ESK, network.clone(), self.0.to_vec())
199    }
200
201    pub fn decode(repr: &MidnightBech32m) -> Result<Self> {
202        if repr.type_tag != TYPE_SHIELD_ESK {
203            return Err(WalletError::Bech32(format!(
204                "expected type `{TYPE_SHIELD_ESK}`, got `{}`",
205                repr.type_tag
206            )));
207        }
208        Self::from_bytes(&repr.data)
209    }
210
211    pub fn parse(s: &str) -> Result<Self> {
212        Self::decode(&MidnightBech32m::parse(s)?)
213    }
214}
215
216#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
217pub struct ShieldedCoinPublicKey(pub [u8; SHIELDED_KEY_LEN]);
218
219impl ShieldedCoinPublicKey {
220    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
221        if bytes.len() != SHIELDED_KEY_LEN {
222            return Err(WalletError::Bech32(format!(
223                "shielded coin public key must be {SHIELDED_KEY_LEN} bytes, got {}",
224                bytes.len()
225            )));
226        }
227        let mut out = [0u8; SHIELDED_KEY_LEN];
228        out.copy_from_slice(bytes);
229        Ok(Self(out))
230    }
231
232    pub fn from_hex(s: &str) -> Result<Self> {
233        let bytes = hex::decode(s).map_err(|e| WalletError::Bech32(e.to_string()))?;
234        Self::from_bytes(&bytes)
235    }
236
237    #[must_use]
238    pub fn to_hex(&self) -> String {
239        hex::encode(self.0)
240    }
241
242    pub fn encode(&self, network: &NetworkId) -> Result<MidnightBech32m> {
243        MidnightBech32m::new(TYPE_SHIELD_CPK, network.clone(), self.0.to_vec())
244    }
245
246    pub fn decode(repr: &MidnightBech32m) -> Result<Self> {
247        if repr.type_tag != TYPE_SHIELD_CPK {
248            return Err(WalletError::Bech32(format!(
249                "expected type `{TYPE_SHIELD_CPK}`, got `{}`",
250                repr.type_tag
251            )));
252        }
253        Self::from_bytes(&repr.data)
254    }
255}
256
257#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
258pub struct ShieldedEncryptionPublicKey(pub [u8; SHIELDED_KEY_LEN]);
259
260impl ShieldedEncryptionPublicKey {
261    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
262        if bytes.len() != SHIELDED_KEY_LEN {
263            return Err(WalletError::Bech32(format!(
264                "shielded encryption public key must be {SHIELDED_KEY_LEN} bytes, got {}",
265                bytes.len()
266            )));
267        }
268        let mut out = [0u8; SHIELDED_KEY_LEN];
269        out.copy_from_slice(bytes);
270        Ok(Self(out))
271    }
272
273    pub fn from_hex(s: &str) -> Result<Self> {
274        let bytes = hex::decode(s).map_err(|e| WalletError::Bech32(e.to_string()))?;
275        Self::from_bytes(&bytes)
276    }
277
278    #[must_use]
279    pub fn to_hex(&self) -> String {
280        hex::encode(self.0)
281    }
282
283    pub fn encode(&self, network: &NetworkId) -> Result<MidnightBech32m> {
284        MidnightBech32m::new(TYPE_SHIELD_EPK, network.clone(), self.0.to_vec())
285    }
286
287    pub fn decode(repr: &MidnightBech32m) -> Result<Self> {
288        if repr.type_tag != TYPE_SHIELD_EPK {
289            return Err(WalletError::Bech32(format!(
290                "expected type `{TYPE_SHIELD_EPK}`, got `{}`",
291                repr.type_tag
292            )));
293        }
294        Self::from_bytes(&repr.data)
295    }
296}
297
298/// Full shielded address = coin public key (32) concatenated with
299/// encryption public key (32).
300#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
301pub struct ShieldedAddress {
302    pub coin_public_key: ShieldedCoinPublicKey,
303    pub encryption_public_key: ShieldedEncryptionPublicKey,
304}
305
306impl ShieldedAddress {
307    #[must_use]
308    pub fn new(
309        coin_public_key: ShieldedCoinPublicKey,
310        encryption_public_key: ShieldedEncryptionPublicKey,
311    ) -> Self {
312        Self {
313            coin_public_key,
314            encryption_public_key,
315        }
316    }
317
318    pub fn encode(&self, network: &NetworkId) -> Result<MidnightBech32m> {
319        let mut bytes = Vec::with_capacity(SHIELDED_KEY_LEN * 2);
320        bytes.extend_from_slice(&self.coin_public_key.0);
321        bytes.extend_from_slice(&self.encryption_public_key.0);
322        MidnightBech32m::new(TYPE_SHIELD_ADDR, network.clone(), bytes)
323    }
324
325    pub fn decode(repr: &MidnightBech32m) -> Result<Self> {
326        if repr.type_tag != TYPE_SHIELD_ADDR {
327            return Err(WalletError::Bech32(format!(
328                "expected type `{TYPE_SHIELD_ADDR}`, got `{}`",
329                repr.type_tag
330            )));
331        }
332        if repr.data.len() != SHIELDED_KEY_LEN * 2 {
333            return Err(WalletError::Bech32(format!(
334                "shielded address must be {} bytes, got {}",
335                SHIELDED_KEY_LEN * 2,
336                repr.data.len()
337            )));
338        }
339        let (cpk_bytes, epk_bytes) = repr.data.split_at(SHIELDED_KEY_LEN);
340        Ok(Self {
341            coin_public_key: ShieldedCoinPublicKey::from_bytes(cpk_bytes)?,
342            encryption_public_key: ShieldedEncryptionPublicKey::from_bytes(epk_bytes)?,
343        })
344    }
345
346    /// Parse a canonical Bech32m-encoded shielded address string.
347    pub fn parse(s: &str) -> Result<Self> {
348        Self::decode(&MidnightBech32m::parse(s)?)
349    }
350}
351
352// --- Unshielded address ---------------------------------------------------
353
354#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
355pub struct UnshieldedAddress(pub [u8; SHIELDED_KEY_LEN]);
356
357impl UnshieldedAddress {
358    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
359        if bytes.len() != SHIELDED_KEY_LEN {
360            return Err(WalletError::Bech32(format!(
361                "unshielded address must be {SHIELDED_KEY_LEN} bytes, got {}",
362                bytes.len()
363            )));
364        }
365        let mut out = [0u8; SHIELDED_KEY_LEN];
366        out.copy_from_slice(bytes);
367        Ok(Self(out))
368    }
369
370    pub fn from_hex(s: &str) -> Result<Self> {
371        let bytes = hex::decode(s).map_err(|e| WalletError::Bech32(e.to_string()))?;
372        Self::from_bytes(&bytes)
373    }
374
375    #[must_use]
376    pub fn to_hex(&self) -> String {
377        hex::encode(self.0)
378    }
379
380    pub fn encode(&self, network: &NetworkId) -> Result<MidnightBech32m> {
381        MidnightBech32m::new(TYPE_UNSHIELDED, network.clone(), self.0.to_vec())
382    }
383
384    pub fn decode(repr: &MidnightBech32m) -> Result<Self> {
385        if repr.type_tag != TYPE_UNSHIELDED {
386            return Err(WalletError::Bech32(format!(
387                "expected type `{TYPE_UNSHIELDED}`, got `{}`",
388                repr.type_tag
389            )));
390        }
391        Self::from_bytes(&repr.data)
392    }
393
394    pub fn parse(s: &str) -> Result<Self> {
395        Self::decode(&MidnightBech32m::parse(s)?)
396    }
397}
398
399// --- DustAddress (SCALE-compact-encoded big integer) ----------------------
400
401/// Encode an unsigned big integer using SCALE compact-integer encoding.
402///
403/// SCALE spec cases for unsigned integers:
404/// - `x < 64` (6 bits): 1 byte `(x << 2) | 0b00`
405/// - `x < 16_384` (14 bits): 2 LE bytes `(x << 2) | 0b01`
406/// - `x < 2^30` (30 bits): 4 LE bytes `(x << 2) | 0b10`
407/// - else: header `((n-4) << 2) | 0b11` + `n` LE bytes (min-length encoded),
408///   where `n` is `max(4, ceil(bit_len / 8))` and the value must fit into
409///   `n` bytes with at most 67 total encoded bytes (n ≤ 67).
410#[allow(clippy::cast_possible_truncation)] // each arm checks the upper bound before casting.
411fn scale_compact_encode(x: &BigUint) -> Vec<u8> {
412    if x < &BigUint::from(64u64) {
413        // 1 byte, low 2 bits = 00. Value fits in 6 bits by the guard above.
414        let v = x.to_u64_digits().first().copied().unwrap_or(0);
415        return vec![(v as u8) << 2];
416    }
417    if x < &BigUint::from(16_384u64) {
418        let v = x.to_u64_digits().first().copied().unwrap_or(0);
419        let shifted = (v << 2) | 0b01;
420        return (shifted as u16).to_le_bytes().to_vec();
421    }
422    if x < &(BigUint::from(1u64) << 30) {
423        let v = x.to_u64_digits().first().copied().unwrap_or(0);
424        let shifted = (v << 2) | 0b10;
425        return (shifted as u32).to_le_bytes().to_vec();
426    }
427    // Big-integer mode.
428    let mut le = x.to_bytes_le();
429    // Strip trailing zeros from the LE representation (min-length encoding).
430    while le.last().copied() == Some(0) && le.len() > 1 {
431        le.pop();
432    }
433    let n = le.len();
434    assert!(
435        (4..=67).contains(&n),
436        "SCALE compact big-integer length out of range: {n}"
437    );
438    let header = (((n as u8) - 4) << 2) | 0b11;
439    let mut out = Vec::with_capacity(1 + n);
440    out.push(header);
441    out.extend_from_slice(&le);
442    out
443}
444
445/// Decode a SCALE-compact-encoded unsigned integer. Returns the value and
446/// the number of input bytes consumed.
447fn scale_compact_decode(input: &[u8]) -> Result<(BigUint, usize)> {
448    let first = *input
449        .first()
450        .ok_or_else(|| WalletError::Bech32("SCALE compact: empty input".to_owned()))?;
451    let mode = first & 0b11;
452    match mode {
453        0b00 => Ok((BigUint::from(first >> 2), 1)),
454        0b01 => {
455            if input.len() < 2 {
456                return Err(WalletError::Bech32(
457                    "SCALE compact: truncated 2-byte value".to_owned(),
458                ));
459            }
460            let v = u16::from_le_bytes([input[0], input[1]]) >> 2;
461            Ok((BigUint::from(v), 2))
462        }
463        0b10 => {
464            if input.len() < 4 {
465                return Err(WalletError::Bech32(
466                    "SCALE compact: truncated 4-byte value".to_owned(),
467                ));
468            }
469            let v = u32::from_le_bytes([input[0], input[1], input[2], input[3]]) >> 2;
470            Ok((BigUint::from(v), 4))
471        }
472        0b11 => {
473            let n = ((first >> 2) as usize) + 4;
474            if input.len() < 1 + n {
475                return Err(WalletError::Bech32(
476                    "SCALE compact: truncated big-integer value".to_owned(),
477                ));
478            }
479            let bytes = &input[1..=n];
480            Ok((BigUint::from_bytes_le(bytes), 1 + n))
481        }
482        _ => unreachable!(),
483    }
484}
485
486/// A Midnight dust address: an unsigned big integer strictly less than the
487/// BLS12-381 scalar modulus.
488#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
489pub struct DustAddress {
490    pub data: BigUint,
491}
492
493impl DustAddress {
494    /// Construct from a raw big-integer key, validating that it's below the
495    /// BLS scalar modulus.
496    pub fn new(data: BigUint) -> Result<Self> {
497        if data.is_zero() {
498            return Ok(Self { data });
499        }
500        if data >= bls_scalar_modulus() {
501            return Err(WalletError::Bech32(
502                "dust address is too large for BLS12-381 scalar field".to_owned(),
503            ));
504        }
505        Ok(Self { data })
506    }
507
508    /// SCALE-compact-encoded bytes (the canonical on-wire form within the
509    /// Bech32m data segment).
510    #[must_use]
511    pub fn serialize(&self) -> Vec<u8> {
512        scale_compact_encode(&self.data)
513    }
514
515    /// Reverse of [`Self::serialize`].
516    pub fn deserialize(bytes: &[u8]) -> Result<Self> {
517        let (data, consumed) = scale_compact_decode(bytes)?;
518        if consumed != bytes.len() {
519            return Err(WalletError::Bech32(format!(
520                "SCALE compact: {} trailing bytes after dust address",
521                bytes.len() - consumed
522            )));
523        }
524        Self::new(data)
525    }
526
527    pub fn encode(&self, network: &NetworkId) -> Result<MidnightBech32m> {
528        MidnightBech32m::new(TYPE_DUST, network.clone(), self.serialize())
529    }
530
531    pub fn decode(repr: &MidnightBech32m) -> Result<Self> {
532        if repr.type_tag != TYPE_DUST {
533            return Err(WalletError::Bech32(format!(
534                "expected type `{TYPE_DUST}`, got `{}`",
535                repr.type_tag
536            )));
537        }
538        Self::deserialize(&repr.data)
539    }
540
541    pub fn parse(s: &str) -> Result<Self> {
542        Self::decode(&MidnightBech32m::parse(s)?)
543    }
544}
545
546#[cfg(test)]
547mod tests {
548    use super::*;
549
550    fn cpk(seed: u8) -> ShieldedCoinPublicKey {
551        ShieldedCoinPublicKey([seed; SHIELDED_KEY_LEN])
552    }
553    fn epk(seed: u8) -> ShieldedEncryptionPublicKey {
554        ShieldedEncryptionPublicKey([seed; SHIELDED_KEY_LEN])
555    }
556
557    #[test]
558    fn mainnet_hrp_omits_network_segment() {
559        let addr = cpk(0x01).encode(&NetworkId::MainNet).unwrap();
560        let s = addr.to_string().unwrap();
561        assert!(
562            s.starts_with("mn_shield-cpk1"),
563            "mainnet cpk should start with `mn_shield-cpk` then Bech32m separator `1`; got `{s}`"
564        );
565    }
566
567    #[test]
568    fn testnet_hrp_includes_network_segment() {
569        let addr = cpk(0x02).encode(&NetworkId::TestNet).unwrap();
570        let s = addr.to_string().unwrap();
571        assert!(
572            s.starts_with("mn_shield-cpk_testnet1"),
573            "testnet cpk should start with `mn_shield-cpk_testnet`; got `{s}`"
574        );
575    }
576
577    #[test]
578    fn shielded_coin_pk_round_trips() {
579        let orig = cpk(0x7F);
580        let encoded = orig.encode(&NetworkId::DevNet).unwrap();
581        let s = encoded.to_string().unwrap();
582        let parsed = MidnightBech32m::parse(&s).unwrap();
583        let back = ShieldedCoinPublicKey::decode(&parsed).unwrap();
584        assert_eq!(orig, back);
585        assert_eq!(parsed.network, NetworkId::DevNet);
586    }
587
588    #[test]
589    fn shielded_address_round_trips_on_mainnet() {
590        let orig = ShieldedAddress::new(cpk(0x11), epk(0x22));
591        let s = orig
592            .encode(&NetworkId::MainNet)
593            .unwrap()
594            .to_string()
595            .unwrap();
596        let back = ShieldedAddress::parse(&s).unwrap();
597        assert_eq!(orig, back);
598    }
599
600    #[test]
601    fn unshielded_address_round_trips() {
602        let orig = UnshieldedAddress([0xAB; SHIELDED_KEY_LEN]);
603        let s = orig
604            .encode(&NetworkId::TestNet)
605            .unwrap()
606            .to_string()
607            .unwrap();
608        let back = UnshieldedAddress::parse(&s).unwrap();
609        assert_eq!(orig, back);
610    }
611
612    #[test]
613    fn custom_network_round_trips() {
614        let orig = cpk(0x55);
615        let s = orig
616            .encode(&NetworkId::Custom("local42".into()))
617            .unwrap()
618            .to_string()
619            .unwrap();
620        let parsed = MidnightBech32m::parse(&s).unwrap();
621        assert_eq!(parsed.network, NetworkId::Custom("local42".into()));
622    }
623
624    #[test]
625    fn wrong_type_is_rejected_on_decode() {
626        let s = cpk(0x01)
627            .encode(&NetworkId::MainNet)
628            .unwrap()
629            .to_string()
630            .unwrap();
631        let parsed = MidnightBech32m::parse(&s).unwrap();
632        let err = UnshieldedAddress::decode(&parsed).unwrap_err();
633        assert!(matches!(err, WalletError::Bech32(_)));
634    }
635
636    #[test]
637    fn invalid_segment_characters_rejected() {
638        let err = MidnightBech32m::new("bad type", NetworkId::MainNet, vec![]).unwrap_err();
639        assert!(matches!(err, WalletError::Bech32(_)));
640    }
641
642    #[test]
643    fn dust_address_rejects_values_above_bls_modulus() {
644        let over = bls_scalar_modulus() + BigUint::from(1u8);
645        assert!(DustAddress::new(over).is_err());
646        // The modulus itself is also rejected (strict less-than).
647        assert!(DustAddress::new(bls_scalar_modulus()).is_err());
648    }
649
650    #[test]
651    fn dust_address_round_trips_small_and_large() {
652        for hex_val in [
653            "0",
654            "1",
655            "3f",       // fits in 1-byte mode
656            "40",       // smallest 2-byte mode
657            "3fff",     // largest 2-byte mode
658            "4000",     // smallest 4-byte mode
659            "3fffffff", // largest 4-byte mode
660            "40000000", // smallest bigint mode
661            // Near-max BLS scalar (well below modulus).
662            "73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000",
663        ] {
664            let n = BigUint::from_str_radix(hex_val, 16).unwrap();
665            let orig = DustAddress::new(n).unwrap();
666            let s = orig
667                .encode(&NetworkId::MainNet)
668                .unwrap()
669                .to_string()
670                .unwrap();
671            let back = DustAddress::parse(&s).unwrap();
672            assert_eq!(orig, back, "round-trip failed for hex_val = `{hex_val}`");
673        }
674    }
675
676    #[test]
677    fn scale_compact_encoding_boundaries() {
678        // 1-byte mode
679        assert_eq!(scale_compact_encode(&BigUint::from(0u8)), vec![0b0000_0000]);
680        assert_eq!(
681            scale_compact_encode(&BigUint::from(63u8)),
682            vec![0b1111_1100]
683        );
684        // 2-byte mode
685        assert_eq!(
686            scale_compact_encode(&BigUint::from(64u16)),
687            vec![0b0000_0001, 0b0000_0001]
688        );
689        assert_eq!(
690            scale_compact_encode(&BigUint::from(16_383u16)),
691            vec![0b1111_1101, 0b1111_1111]
692        );
693        // 4-byte mode lower bound
694        let mut lb_4 = scale_compact_encode(&BigUint::from(16_384u32));
695        assert_eq!(lb_4.len(), 4);
696        assert_eq!(lb_4[0] & 0b11, 0b10);
697        lb_4.clear();
698
699        // Round-trip sanity at each boundary.
700        for v in [
701            0u128,
702            63,
703            64,
704            16_383,
705            16_384,
706            (1u128 << 30) - 1,
707            1u128 << 30,
708        ] {
709            let x = BigUint::from(v);
710            let enc = scale_compact_encode(&x);
711            let (dec, n) = scale_compact_decode(&enc).unwrap();
712            assert_eq!(x, dec);
713            assert_eq!(n, enc.len());
714        }
715    }
716}