moonproof-wallet 0.2.1

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! Cross-cutting abstractions shared by the sub-wallets.
//!
//! Port of `@midnight-ntwrk/wallet-sdk-abstractions`. Keeps the surface small:
//! just the types that actually show up on wallet APIs (network id, protocol
//! version range, sync progress, wallet seed newtype). TS-specific plumbing
//! (effect/Brand, effect/Schema, RxJS-style observables) is either replaced
//! with native Rust idioms or omitted.

use std::fmt;

use serde::{Deserialize, Serialize};
use zeroize::{Zeroize, ZeroizeOnDrop};

// --- NetworkId ------------------------------------------------------------

/// Named Midnight networks plus the "custom" escape hatch for local / test
/// deployments.
///
/// Matches the TS `NetworkId` constants exactly; serialization goes
/// through the string form (`"mainnet"`, `"testnet"`, …), so values round-trip
/// across the FFI boundary with `midnight-js`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(from = "String", into = "String")]
pub enum NetworkId {
    MainNet,
    TestNet,
    DevNet,
    QaNet,
    Undeployed,
    Preview,
    PreProd,
    /// Any other network identifier — keeps the surface open-ended so
    /// local deployments don't have to fork this enum.
    Custom(String),
}

impl NetworkId {
    /// Canonical string form (what the indexer / node expects on the wire).
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            Self::MainNet => "mainnet",
            Self::TestNet => "testnet",
            Self::DevNet => "devnet",
            Self::QaNet => "qanet",
            Self::Undeployed => "undeployed",
            Self::Preview => "preview",
            Self::PreProd => "preprod",
            Self::Custom(s) => s,
        }
    }

    /// Parse from the canonical string form. Unknown labels round-trip through
    /// [`NetworkId::Custom`] rather than failing — matches the TS SDK.
    #[must_use]
    pub fn from_label(s: &str) -> Self {
        match s {
            "mainnet" => Self::MainNet,
            "testnet" => Self::TestNet,
            "devnet" => Self::DevNet,
            "qanet" => Self::QaNet,
            "undeployed" => Self::Undeployed,
            "preview" => Self::Preview,
            "preprod" => Self::PreProd,
            other => Self::Custom(other.to_owned()),
        }
    }
}

impl fmt::Display for NetworkId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl From<String> for NetworkId {
    fn from(s: String) -> Self {
        Self::from_label(&s)
    }
}

impl From<&str> for NetworkId {
    fn from(s: &str) -> Self {
        Self::from_label(s)
    }
}

impl From<NetworkId> for String {
    fn from(n: NetworkId) -> Self {
        n.as_str().to_owned()
    }
}

// --- ProtocolVersion ------------------------------------------------------

/// Midnight protocol version. The TS reference brands this over a `bigint`;
/// we use `u64` because no deployed protocol version gets near that ceiling
/// and stack values are cheaper than arbitrary-precision integers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ProtocolVersion(pub u64);

impl ProtocolVersion {
    pub const MIN_SUPPORTED: Self = Self(0);
    pub const MAX_SUPPORTED: Self = Self(u64::MAX);
}

impl fmt::Display for ProtocolVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "v{}", self.0)
    }
}

/// Half-open protocol version range: `[start, end)`. Matches the TS
/// `ProtocolVersion.Range` shape where `end - start >= 1`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProtocolVersionRange {
    pub start: ProtocolVersion,
    pub end: ProtocolVersion,
}

impl ProtocolVersionRange {
    /// Construct a range; returns `None` if `end <= start`.
    #[must_use]
    pub fn new(start: ProtocolVersion, end: ProtocolVersion) -> Option<Self> {
        if end.0 <= start.0 {
            None
        } else {
            Some(Self { start, end })
        }
    }

    /// Half-open containment check.
    #[inline]
    #[must_use]
    pub fn contains(&self, version: ProtocolVersion) -> bool {
        version >= self.start && version < self.end
    }
}

// --- SyncProgress ---------------------------------------------------------

/// Progress snapshot of a wallet's chain-sync loop.
///
/// Matches `SyncProgressData` from the TS reference. `isCompleteWithin` /
/// `isStrictlyComplete` become methods here; the default max-gap is 50 (as
/// in the TS reference).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SyncProgress {
    pub applied_index: u64,
    pub highest_relevant_wallet_index: u64,
    pub highest_index: u64,
    pub highest_relevant_index: u64,
    pub is_connected: bool,
}

impl SyncProgress {
    /// Default max-gap (matching the TS reference's `50n`).
    pub const DEFAULT_MAX_GAP: u64 = 50;

    /// Sync is complete within `max_gap` of the highest relevant index AND
    /// the connection is live.
    #[must_use]
    pub fn is_complete_within(&self, max_gap: u64) -> bool {
        if !self.is_connected {
            return false;
        }
        let lag = self
            .highest_relevant_wallet_index
            .abs_diff(self.applied_index);
        lag <= max_gap
    }

    /// Applied index has reached the highest relevant index exactly.
    #[inline]
    #[must_use]
    pub fn is_strictly_complete(&self) -> bool {
        self.is_complete_within(0)
    }

    /// Convenience: complete within the default gap.
    #[inline]
    #[must_use]
    pub fn is_complete(&self) -> bool {
        self.is_complete_within(Self::DEFAULT_MAX_GAP)
    }
}

// --- WalletSeed -----------------------------------------------------------

/// A BIP32-compatible seed (typically 64 bytes but BIP32 accepts 16..=64).
///
/// Zeroized on drop. Use [`WalletSeed::from_hex`] or [`WalletSeed::from_bytes`]
/// to construct one; feed it into [`crate::HDWallet::from_seed`] to derive
/// keys.
#[derive(Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
pub struct WalletSeed(Vec<u8>);

impl WalletSeed {
    /// Build from raw seed bytes. Does not validate length — BIP32 itself will
    /// reject seeds shorter than 16 or longer than 64 bytes.
    #[inline]
    #[must_use]
    pub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Self {
        Self(bytes.into())
    }

    /// Build from a hex string. Returns an error if the string isn't valid hex.
    pub fn from_hex(s: &str) -> Result<Self, hex::FromHexError> {
        Ok(Self(hex::decode(s)?))
    }

    #[inline]
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }
}

impl fmt::Debug for WalletSeed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("WalletSeed").field(&"[redacted]").finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn network_id_label_round_trip() {
        for id in [
            NetworkId::MainNet,
            NetworkId::TestNet,
            NetworkId::DevNet,
            NetworkId::QaNet,
            NetworkId::Undeployed,
            NetworkId::Preview,
            NetworkId::PreProd,
        ] {
            assert_eq!(NetworkId::from_label(id.as_str()), id);
        }
    }

    #[test]
    fn unknown_network_label_becomes_custom() {
        assert_eq!(
            NetworkId::from_label("localnet"),
            NetworkId::Custom("localnet".to_owned())
        );
    }

    #[test]
    fn protocol_version_range_rejects_empty() {
        assert!(ProtocolVersionRange::new(ProtocolVersion(5), ProtocolVersion(5)).is_none());
        assert!(ProtocolVersionRange::new(ProtocolVersion(5), ProtocolVersion(4)).is_none());
    }

    #[test]
    fn protocol_version_range_half_open_containment() {
        let r = ProtocolVersionRange::new(ProtocolVersion(1), ProtocolVersion(5)).unwrap();
        assert!(r.contains(ProtocolVersion(1)));
        assert!(r.contains(ProtocolVersion(4)));
        assert!(!r.contains(ProtocolVersion(5)), "upper bound is exclusive");
        assert!(!r.contains(ProtocolVersion(0)));
    }

    #[test]
    fn sync_progress_incomplete_when_disconnected() {
        let p = SyncProgress {
            is_connected: false,
            ..Default::default()
        };
        assert!(!p.is_complete_within(10));
        assert!(!p.is_strictly_complete());
    }

    #[test]
    fn sync_progress_strict_completion() {
        let p = SyncProgress {
            applied_index: 100,
            highest_relevant_wallet_index: 100,
            is_connected: true,
            ..Default::default()
        };
        assert!(p.is_strictly_complete());
    }

    #[test]
    fn sync_progress_within_gap() {
        let p = SyncProgress {
            applied_index: 100,
            highest_relevant_wallet_index: 105,
            is_connected: true,
            ..Default::default()
        };
        assert!(!p.is_strictly_complete());
        assert!(p.is_complete_within(5));
        assert!(p.is_complete_within(SyncProgress::DEFAULT_MAX_GAP));
    }

    #[test]
    fn wallet_seed_debug_is_redacted() {
        let s = WalletSeed::from_bytes(vec![0xDEu8; 32]);
        let dbg = format!("{s:?}");
        assert!(!dbg.contains("DEDE"));
        assert!(dbg.contains("redacted"));
    }

    #[test]
    fn wallet_seed_hex_round_trip() {
        let s = WalletSeed::from_hex("deadbeef").unwrap();
        assert_eq!(s.as_bytes(), &[0xDE, 0xAD, 0xBE, 0xEF]);
    }
}