moonproof-wallet 0.2.1

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! Standalone signing primitives matching the dApp-connector-api
//! `signData` surface.
//!
//! Mirrors `@midnight-ntwrk/ledger-v8`'s `signData(secretKeyHex,
//! data) -> signatureHex` byte-for-byte: takes a secret key + raw
//! bytes, signs via `SigningKey::sign`, returns the wire-encoded
//! signature alongside the verifying key the dApp needs to verify.
//!
//! Encoding helpers parse the dApp's `data` parameter according to
//! the `encoding` option (`"hex"` / `"base64"` / `"text"`) before
//! signing, matching the connector API's contract.

use base64::engine::general_purpose::STANDARD as BASE64_STD;
use base64::Engine as _;
use moonproof_ledger::serialize::Serializable;
use moonproof_ledger::signatures::{Signature, SignatureScheme, SigningKey};
use rand::rngs::OsRng;
use rand::{CryptoRng, Rng};

use crate::error::{Result, WalletError};

/// Encoding label used by the dApp-connector-api `signData` options.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DataEncoding {
    Hex,
    Base64,
    Text,
}

impl DataEncoding {
    /// Parse the wire string. Defaults to `Text` for unknown values
    /// so dApps that omit the option get a working signature
    /// against UTF-8 bytes.
    #[must_use]
    pub fn from_label(s: &str) -> Self {
        match s {
            "hex" => Self::Hex,
            "base64" => Self::Base64,
            _ => Self::Text,
        }
    }

    /// Decode the dApp-supplied `data` string into the byte payload
    /// the wallet will sign.
    pub fn decode(self, data: &str) -> Result<Vec<u8>> {
        match self {
            Self::Hex => moonproof_utils::parse_hex(data).map_err(|e| {
                WalletError::SigningFailed(format!("hex-decode signData payload: {e}"))
            }),
            Self::Base64 => BASE64_STD.decode(data).map_err(|e| {
                WalletError::SigningFailed(format!("base64-decode signData payload: {e}"))
            }),
            Self::Text => Ok(data.as_bytes().to_vec()),
        }
    }
}

/// Output of [`sign_data`] — the dApp-connector-api `Signature` shape
/// (`{ data, signature, verifyingKey, scheme }`), hex-encoded.
#[derive(Debug, Clone)]
pub struct SignedDataOutput {
    /// Hex of the bytes that were signed (post-decoding). The dApp
    /// receives this verbatim so it can re-verify.
    pub data_hex: String,
    /// Hex of the 64-byte `r || s` signature.
    pub signature_hex: String,
    /// Hex of the verifying key: 32 bytes x-only for `schnorr_bip340`,
    /// 33 bytes SEC1-compressed for `ecdsa_secp256k1_sha256`.
    pub verifying_key_hex: String,
    /// `schnorr_bip340` or `ecdsa_secp256k1_sha256` (connector API 4.1).
    pub scheme: &'static str,
}

/// The bytes a `signData` signature covers: the dApp connector
/// specification's `midnight_signed_message:<data_size>:` prefix, then
/// the data. The prefix keeps a signed message from ever being valid as
/// a transaction signature.
#[must_use]
pub fn signed_message(data: &[u8]) -> Vec<u8> {
    let mut message = format!("midnight_signed_message:{}:", data.len()).into_bytes();
    message.extend_from_slice(data);
    message
}

/// Sign `decoded_bytes` as the dApp connector's `signData`: the
/// signature covers [`signed_message`] of the data.
pub fn sign_data(signing_key: &SigningKey, decoded_bytes: &[u8]) -> Result<SignedDataOutput> {
    let raw = moonproof_ledger::signatures::sign_raw(
        signing_key,
        &mut OsRng,
        &signed_message(decoded_bytes),
    )
    .map_err(|e| WalletError::SigningFailed(format!("serialize signData output: {e}")))?;
    Ok(SignedDataOutput {
        data_hex: hex::encode(decoded_bytes),
        signature_hex: hex::encode(raw.signature),
        verifying_key_hex: hex::encode(raw.verifying_key),
        scheme: raw.scheme.as_str(),
    })
}

/// Generic sign-callback the wallet can hand to recipe signers so
/// dApps can plug in their own multi-key signers (hardware wallets,
/// HSM signers, multi-account flows). Mirrors midnight-wallet's
/// `signFn: (payload: Uint8Array) => Signature` shape.
///
/// The callback signs the supplied byte payload using whatever
/// strategy the dApp picks. Returns the wire-encoded `Signature`
/// bytes (the same format `Signature::serialize` produces).
pub trait SignCallback: Send + Sync {
    fn sign(&self, payload: &[u8]) -> Result<Vec<u8>>;
}

/// Trivial in-process callback that signs every payload with one
/// `SigningKey`. The default the wallet uses when no external
/// signer is configured.
pub struct InProcessSigner<'a> {
    pub key: &'a SigningKey,
}

impl<'a> InProcessSigner<'a> {
    pub fn new(key: &'a SigningKey) -> Self {
        Self { key }
    }
}

impl SignCallback for InProcessSigner<'_> {
    fn sign(&self, payload: &[u8]) -> Result<Vec<u8>> {
        let signature = self.key.sign(&mut OsRng, payload);
        let mut buf = Vec::new();
        signature.serialize(&mut buf).map_err(|e| {
            WalletError::SigningFailed(format!("serialize callback signature: {e}"))
        })?;
        Ok(buf)
    }
}

/// Sign a raw `payload` and return the **deserialized**
/// [`Signature`]. Useful when the caller wants to verify or compare
/// signatures by struct rather than by wire bytes.
///
/// `R` is the RNG; passing `&mut OsRng` matches the `signData`
/// primitive's behavior verbatim.
pub fn sign_raw<R>(signing_key: &SigningKey, payload: &[u8], rng: &mut R) -> Signature
where
    R: Rng + CryptoRng,
{
    signing_key.sign(rng, payload)
}

/// Derive the wallet's primary signing key from a BIP32 master seed.
///
/// Mirrors the path the runtime wallet uses for sealing inputs:
/// `m/account'/Role::NightExternal/index`. Defaults to
/// `(account=0, index=0)`. The resulting key is what every
/// `sign-message` flow against the keystore should use.
pub fn signing_key_from_seed(seed: &[u8], account: u32, index: u32) -> Result<SigningKey> {
    let hd = crate::hd::HDWallet::from_seed(seed)
        .map_err(|e| WalletError::SigningFailed(format!("derive HD wallet from seed: {e}")))?;
    let secret = hd
        .account(account)
        .role(crate::hd::Role::NightExternal)
        .derive(index)
        .map_err(|e| {
            WalletError::SigningFailed(format!("derive NightExternal[{account}/{index}]: {e}"))
        })?;
    crate::unshielded::ledger_adapter::signing_key_from_bytes(secret.as_bytes())
}

/// Verify a [`sign_data`] signature over `payload` (the data before
/// the [`signed_message`] prefix), in the encodings it returns.
/// `scheme` is the connector API's `Signature.scheme`; absent means
/// `schnorr_bip340`, as the API specifies.
pub fn verify_data(
    verifying_key_hex: &str,
    payload: &[u8],
    signature_hex: &str,
    scheme: Option<&str>,
) -> Result<bool> {
    let scheme = match scheme {
        None => SignatureScheme::SchnorrBip340,
        Some(name) => SignatureScheme::parse(name).ok_or_else(|| {
            WalletError::SigningFailed(format!("unknown signature scheme `{name}`"))
        })?,
    };
    let vk_bytes = moonproof_utils::parse_hex(verifying_key_hex)
        .map_err(|e| WalletError::SigningFailed(format!("hex verify_data vk: {e}")))?;
    let sig_bytes = moonproof_utils::parse_hex(signature_hex)
        .map_err(|e| WalletError::SigningFailed(format!("hex verify_data sig: {e}")))?;
    moonproof_ledger::signatures::verify_raw(
        scheme,
        &vk_bytes,
        &signed_message(payload),
        &sig_bytes,
    )
    .map_err(|e| WalletError::SigningFailed(format!("decode signature or key: {e}")))
}

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

    #[test]
    fn the_signature_covers_the_connector_prefix() {
        let sk = crate::unshielded::ledger_adapter::signing_key_from_bytes(&[0x11; 32]).unwrap();
        let out = sign_data(&sk, b"hello").unwrap();
        assert_eq!(signed_message(b"hello"), b"midnight_signed_message:5:hello");
        assert!(verify_data(
            &out.verifying_key_hex,
            b"hello",
            &out.signature_hex,
            Some(out.scheme)
        )
        .unwrap());
        let vk = hex::decode(&out.verifying_key_hex).unwrap();
        let sig = hex::decode(&out.signature_hex).unwrap();
        let scheme = SignatureScheme::parse(out.scheme).unwrap();
        assert!(
            !moonproof_ledger::signatures::verify_raw(scheme, &vk, b"hello", &sig).unwrap(),
            "a signData signature must not verify over the bare data"
        );
        assert_eq!(out.data_hex, hex::encode(b"hello"));
    }
    use rand::rngs::OsRng;

    #[test]
    fn round_trip_text_encoding() {
        let key = moonproof_ledger::signatures::sample_signing_key(OsRng);
        let payload = b"hello midnight";
        let out = sign_data(&key, payload).unwrap();
        assert_eq!(out.data_hex, hex::encode(payload));
        assert_eq!(out.scheme, "schnorr_bip340");
        assert_eq!(out.signature_hex.len(), 128, "64-byte r || s");
        assert_eq!(out.verifying_key_hex.len(), 64, "32-byte x-only key");
        let verified = verify_data(
            &out.verifying_key_hex,
            payload,
            &out.signature_hex,
            Some(out.scheme),
        )
        .unwrap();
        assert!(verified);
        assert!(!verify_data(&out.verifying_key_hex, b"other", &out.signature_hex, None).unwrap());
    }

    #[test]
    fn decoding_handles_each_encoding() {
        let raw = b"\x01\x02\x03\x04";
        // hex
        assert_eq!(DataEncoding::Hex.decode("01020304").unwrap(), raw.to_vec());
        assert_eq!(
            DataEncoding::Hex.decode("0x01020304").unwrap(),
            raw.to_vec()
        );
        // base64
        assert_eq!(
            DataEncoding::Base64
                .decode(&BASE64_STD.encode(raw))
                .unwrap(),
            raw.to_vec()
        );
        // text
        assert_eq!(DataEncoding::Text.decode("abc").unwrap(), b"abc".to_vec());
    }

    #[test]
    fn from_label_defaults_to_text() {
        assert_eq!(DataEncoding::from_label("hex"), DataEncoding::Hex);
        assert_eq!(DataEncoding::from_label("base64"), DataEncoding::Base64);
        assert_eq!(DataEncoding::from_label("text"), DataEncoding::Text);
        assert_eq!(DataEncoding::from_label("unknown"), DataEncoding::Text);
    }
}