moonproof-wallet 0.2.2

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
//! Midnight address formats — Bech32m with a `mn` HRP.
//!
//! Port of `@midnight-ntwrk/wallet-sdk-address-format`. Matches the TS
//! reference byte-for-byte:
//!
//! - Human-readable part: `mn_<type>[_<network>]`. `network` is omitted on
//!   mainnet (so `mn_shield-addr` is implicitly mainnet).
//! - `shield-addr` — shielded address (64 bytes: coin PK || encryption PK)
//! - `shield-cpk` — shielded coin public key (32 bytes)
//! - `shield-epk` — shielded encryption public key (32 bytes)
//! - `addr` — unshielded address (32 bytes)
//! - `dust` — dust public key, SCALE-compact-encoded big integer (≤ BLS
//!   scalar modulus)
//!
//! Segment character set: `[A-Za-z1-9-]` per the TS reference.

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};

/// HRP prefix for all Midnight Bech32m addresses.
pub const HRP_PREFIX: &str = "mn";

/// BLS12-381 scalar modulus (base of `midnight-curves::Fr`). A `DustAddress`
/// must be `< modulus`; the BLS scalar field has ~254 bits.
#[must_use]
pub fn bls_scalar_modulus() -> BigUint {
    // 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001
    BigUint::from_str_radix(
        "73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001",
        16,
    )
    .expect("hard-coded BLS12-381 scalar modulus is valid hex")
}

/// Validate a Bech32m segment (type / network) — same regex as the TS
/// reference: `[A-Za-z1-9-]+`.
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)
}

/// A parsed Midnight Bech32m representation: prefix + type + optional
/// network + payload bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MidnightBech32m {
    pub type_tag: String,
    pub network: NetworkId,
    pub data: Vec<u8>,
}

impl MidnightBech32m {
    /// Construct directly. Segments are validated; bytes are taken as-is.
    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(),
        })
    }

    /// Encode to the canonical Bech32m string form.
    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}")))
    }

    /// Parse a Bech32m-encoded string back into prefix/type/network/data.
    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),
        }
    }
}

// --- Shielded types -------------------------------------------------------

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";

/// A shielded encryption **secret** key, serialized as 32 bytes. Bech32m
/// HRP is `mn_shield-esk_<network>`. This is the payload the indexer's
/// `connect(viewingKey)` mutation accepts — the indexer uses it to
/// attempt decryption of each zswap output's ciphertext during the
/// relevance check.
///
/// **Handle with care.** Holding a `ShieldedEncryptionSecretKey` gives
/// the holder view-only access to every shielded coin encrypted to the
/// corresponding public key. The inner bytes are zeroized on drop.
#[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 {
    /// Wrap an already-serialized 32-byte representation. The bytes must
    /// be what `encryption::SecretKey::repr()` would produce.
    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)
    }
}

/// Full shielded address = coin public key (32) concatenated with
/// encryption public key (32).
#[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)?,
        })
    }

    /// Parse a canonical Bech32m-encoded shielded address string.
    pub fn parse(s: &str) -> Result<Self> {
        Self::decode(&MidnightBech32m::parse(s)?)
    }
}

// --- Unshielded address ---------------------------------------------------

#[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)?)
    }
}

// --- DustAddress (SCALE-compact-encoded big integer) ----------------------

/// Encode an unsigned big integer using SCALE compact-integer encoding.
///
/// SCALE spec cases for unsigned integers:
/// - `x < 64` (6 bits): 1 byte `(x << 2) | 0b00`
/// - `x < 16_384` (14 bits): 2 LE bytes `(x << 2) | 0b01`
/// - `x < 2^30` (30 bits): 4 LE bytes `(x << 2) | 0b10`
/// - else: header `((n-4) << 2) | 0b11` + `n` LE bytes (min-length encoded),
///   where `n` is `max(4, ceil(bit_len / 8))` and the value must fit into
///   `n` bytes with at most 67 total encoded bytes (n ≤ 67).
#[allow(clippy::cast_possible_truncation)] // each arm checks the upper bound before casting.
fn scale_compact_encode(x: &BigUint) -> Vec<u8> {
    if x < &BigUint::from(64u64) {
        // 1 byte, low 2 bits = 00. Value fits in 6 bits by the guard above.
        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();
    }
    // Big-integer mode.
    let mut le = x.to_bytes_le();
    // Strip trailing zeros from the LE representation (min-length encoding).
    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
}

/// Decode a SCALE-compact-encoded unsigned integer. Returns the value and
/// the number of input bytes consumed.
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!(),
    }
}

/// A Midnight dust address: an unsigned big integer strictly less than the
/// BLS12-381 scalar modulus.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct DustAddress {
    pub data: BigUint,
}

impl DustAddress {
    /// Construct from a raw big-integer key, validating that it's below the
    /// BLS scalar modulus.
    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 })
    }

    /// SCALE-compact-encoded bytes (the canonical on-wire form within the
    /// Bech32m data segment).
    #[must_use]
    pub fn serialize(&self) -> Vec<u8> {
        scale_compact_encode(&self.data)
    }

    /// Reverse of [`Self::serialize`].
    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());
        // The modulus itself is also rejected (strict less-than).
        assert!(DustAddress::new(bls_scalar_modulus()).is_err());
    }

    #[test]
    fn dust_address_round_trips_small_and_large() {
        for hex_val in [
            "0",
            "1",
            "3f",       // fits in 1-byte mode
            "40",       // smallest 2-byte mode
            "3fff",     // largest 2-byte mode
            "4000",     // smallest 4-byte mode
            "3fffffff", // largest 4-byte mode
            "40000000", // smallest bigint mode
            // Near-max BLS scalar (well below modulus).
            "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() {
        // 1-byte mode
        assert_eq!(scale_compact_encode(&BigUint::from(0u8)), vec![0b0000_0000]);
        assert_eq!(
            scale_compact_encode(&BigUint::from(63u8)),
            vec![0b1111_1100]
        );
        // 2-byte mode
        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]
        );
        // 4-byte mode lower bound
        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();

        // Round-trip sanity at each boundary.
        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());
        }
    }
}