moonproof-wallet 0.2.2

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! Seed-to-public-address derivation. Takes a 64-byte BIP39 seed plus
//! a network ID and produces the [`KeystoreAddresses`] bundle stored
//! alongside the encrypted seed in the on-disk envelope.
//!
//! Lives in `moonproof-wallet` because (1) only the wallet crate knows
//! how to walk a seed through the BIP44 / Midnight role scheme into
//! coin + encryption + bech32 keys, and (2) consolidating the
//! producer + on-disk type lets every host (CLI, Flutter SDK, future
//! `UniFFI` bindings) reuse a single derivation path.

use anyhow::{Context, Result};
use moonproof_keystore::format::KeystoreAddresses;

use crate::abstractions::NetworkId;
use crate::address::{ShieldedAddress, ShieldedCoinPublicKey, ShieldedEncryptionPublicKey};
use crate::testing::Wallet;

/// Derive the address bundle for a seed. `seed` is the 64-byte BIP39
/// seed; the BIP44 derivation uses `account=0, index=0` for every
/// role (the same scheme `Wallet` uses).
pub fn derive_addresses(seed: &[u8], network: &NetworkId) -> Result<KeystoreAddresses> {
    let wallet = Wallet::from_seed(seed, network.clone())
        .map_err(|e| anyhow::anyhow!("deriving wallet from seed: {e}"))?;

    let zswap_keys = wallet.zswap_secret_keys();

    let coin_pk_bytes = zswap_keys.coin_secret_key.public_key().0 .0;
    let coin_pk_hex = hex::encode(coin_pk_bytes);

    let enc_pk = zswap_keys.encryption_secret_key.public_key();
    let enc_pk_bytes =
        encode_encryption_public_key(&enc_pk).context("serializing encryption public key")?;
    let enc_pk_hex = hex::encode(enc_pk_bytes);

    let shielded_addr = ShieldedAddress::new(
        ShieldedCoinPublicKey(coin_pk_bytes),
        ShieldedEncryptionPublicKey(enc_pk_bytes),
    );
    let shielded_bech32 = shielded_addr
        .encode(network)
        .and_then(|enc| enc.to_string())
        .context("bech32-encoding shielded address")?;

    Ok(KeystoreAddresses {
        network: network.to_string(),
        night_bech32: Some(wallet.bech32_address.clone()),
        dust_bech32: None,
        shielded_bech32: Some(shielded_bech32),
        coin_pk_hex,
        enc_pk_hex,
    })
}

fn encode_encryption_public_key(
    pk: &moonproof_ledger::transient_crypto::encryption::PublicKey,
) -> Result<[u8; 32]> {
    use moonproof_ledger::serialize::Serializable;
    let mut buf = Vec::with_capacity(32);
    pk.serialize(&mut buf)?;
    if buf.len() != 32 {
        anyhow::bail!(
            "expected encryption public key to serialize to 32 bytes, got {}",
            buf.len()
        );
    }
    let mut out = [0u8; 32];
    out.copy_from_slice(&buf);
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use moonproof_keystore::seed::{self, Seed};
    use rand::SeedableRng;

    fn fixture_seed() -> Seed {
        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
        seed::generate(&mut rng, 24).unwrap().1
    }

    #[test]
    fn deterministic_derivation_yields_identical_bundles() {
        let s = fixture_seed();
        let a = s
            .expose(|b| derive_addresses(&b.0, &NetworkId::Undeployed))
            .unwrap();
        let b = s
            .expose(|b| derive_addresses(&b.0, &NetworkId::Undeployed))
            .unwrap();
        assert_eq!(a, b);
    }

    #[test]
    fn populates_network_pubkeys_and_bech32_strings() {
        let s = fixture_seed();
        let bundle = s
            .expose(|b| derive_addresses(&b.0, &NetworkId::Undeployed))
            .unwrap();
        assert_eq!(bundle.network, "undeployed");
        assert!(bundle.night_bech32.is_some());
        assert!(bundle.shielded_bech32.is_some());
        assert_eq!(bundle.coin_pk_hex.len(), 64);
        assert_eq!(bundle.enc_pk_hex.len(), 64);
        assert!(bundle.dust_bech32.is_none());
    }

    #[test]
    fn different_networks_share_pubkey_hex_but_differ_in_bech32() {
        let s = fixture_seed();
        let undeployed = s
            .expose(|b| derive_addresses(&b.0, &NetworkId::Undeployed))
            .unwrap();
        let testnet = s
            .expose(|b| derive_addresses(&b.0, &NetworkId::TestNet))
            .unwrap();
        assert_ne!(undeployed.night_bech32, testnet.night_bech32);
        assert_ne!(undeployed.shielded_bech32, testnet.shielded_bech32);
        assert_eq!(undeployed.coin_pk_hex, testnet.coin_pk_hex);
        assert_eq!(undeployed.enc_pk_hex, testnet.enc_pk_hex);
    }
}