moonproof-wallet 0.2.1

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
//! Adapter from a moonproof [`TransferRecipe`] to a `moonproof_ledger::ledger` `Intent`.
//!
//! This is the boundary where the wallet's domain types meet the
//! `midnight-ledger` Rust crate's transaction-construction API. Three steps:
//!
//! 1. [`build_intent`] — converts a recipe + spender's `VerifyingKey` + TTL
//!    into an Intent with empty signatures (the "unsigned" runtime state of
//!    [`UnshieldedIntent`]).
//! 2. [`sign_intent`] — signs the unshielded inputs with the spender's
//!    `SigningKey`s, producing an Intent of the same Rust type with the
//!    `signatures` array populated.
//! 3. [`build_transaction`] / [`serialize_transaction`] — wrap a signed
//!    Intent into a `Transaction` and serialize it for the Midnight node.
//!
//! Concrete `D = InMemoryDB` everywhere — moonproof has no need for a
//! persistent ledger DB, and matches what the prover crate already uses.
//!
//! ## Generic-parameter notes
//!
//! `Intent<S, P, B, D>` carries four type parameters; the unshielded path
//! uses `S = Signature`, `P = ProofPreimageMarker`, `B = PedersenRandomness`,
//! `D = InMemoryDB`. Critically, `Intent::sign` returns `Self` — the
//! `SignatureKind` does not change. The "signed" vs "unsigned" distinction
//! is purely about whether the `signatures` array inside the
//! `UnshieldedOffer` is empty or populated, not a separate type. We use the
//! same [`UnshieldedIntent`] alias for both.

use std::convert::TryFrom;

use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::coin_structure::coin::{UnshieldedTokenType, UserAddress, NIGHT};
use moonproof_ledger::ledger::error::TransactionProvingError;
use moonproof_ledger::ledger::structure::{
    Intent, IntentHash, ProofMarker, ProofPreimageMarker, Transaction, UnshieldedOffer, UtxoOutput,
    UtxoSpend,
};
use moonproof_ledger::onchain_runtime::cost_model::INITIAL_COST_MODEL;
use moonproof_ledger::serialize::tagged_serialize;
use moonproof_ledger::signatures::{Signature, SigningKey, VerifyingKey};
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
use moonproof_ledger::transient_crypto::commitment::{PedersenRandomness, PureGeneratorPedersen};
use moonproof_ledger::transient_crypto::hash::HashOutput;
use moonproof_ledger::transient_crypto::proofs::{Proof, ProofPreimage, ProvingProvider};
use rand::rngs::OsRng;
use rand::{CryptoRng, RngCore};

use crate::error::{Result, WalletError};
use crate::types::TokenType;
use crate::unshielded::state::UtxoWithMeta;
use crate::unshielded::transacting::{TransferRecipe, UnshieldedOutputSpec};

/// Concrete DB type used throughout moonproof — the in-memory variant is
/// sufficient for transaction construction and matches the prover crate.
pub type Db = InMemoryDB;

/// Intent shape used throughout the unshielded path. Has empty `signatures`
/// before [`sign_intent`] runs, populated `signatures` after.
pub type UnshieldedIntent = Intent<Signature, ProofPreimageMarker, PedersenRandomness, Db>;

/// Signed `Transaction` shape — output of [`build_transaction`]. This is
/// the pre-proof, pre-bind form: signatures populated, proof preimages not
/// yet upgraded to real proofs, binding commitment still in its randomness
/// form. Suitable as input to a proof server but NOT directly to the node.
pub type SignedTransaction = Transaction<Signature, ProofPreimageMarker, PedersenRandomness, Db>;

/// Wire-format `Transaction` shape — what the node's
/// `pallet_midnight.send_mn_transaction` expects. `ProofMarker` +
/// `PureGeneratorPedersen` means proofs have been upgraded (or a no-op cast
/// applied for unshielded-only txs) and the binding commitment is sealed.
/// Produced by [`finalize_unshielded_transaction`].
pub type FinalizedTransaction = Transaction<Signature, ProofMarker, PureGeneratorPedersen, Db>;

// --- No-op proving provider ----------------------------------------------

/// [`ProvingProvider`] that rejects any actual proof request.
///
/// Safe for **pure-unshielded** transactions only — these carry no
/// contract-call actions, no dust actions, no Zswap offers, so
/// `Transaction::prove` never invokes our `prove` / `check` methods. The
/// call is a type-parameter-upgrade: `ProofPreimageMarker → ProofMarker`
/// with no new artifacts.
///
/// Using this provider on a transaction that DOES contain proof-bearing
/// content errors out — matches `ledger::MockProver`'s "cannot mock prove
/// non-builtin circuit" behavior, so the error message is intelligible.
#[derive(Debug, Clone, Copy)]
pub struct NoopProvingProvider;

impl ProvingProvider for NoopProvingProvider {
    fn check(
        &self,
        _preimage: &ProofPreimage,
    ) -> impl std::future::Future<Output = std::result::Result<Vec<Option<usize>>, anyhow::Error>>
    {
        std::future::ready(Err(anyhow::anyhow!(
            "NoopProvingProvider: cannot check proof preimage — \
             this provider is only valid for unshielded-only transactions"
        )))
    }

    fn prove(
        self,
        _preimage: &ProofPreimage,
        _overwrite_binding_input: Option<moonproof_ledger::transient_crypto::curve::Fr>,
    ) -> impl std::future::Future<Output = std::result::Result<Proof, anyhow::Error>> {
        std::future::ready(Err(anyhow::anyhow!(
            "NoopProvingProvider: cannot produce a real proof — \
             this provider is only valid for unshielded-only transactions"
        )))
    }

    /// Ledger 9 asks a provider for the resolver behind it. This one
    /// never proves anything, so it hands back an empty resolver rather
    /// than pretending to have keys.
    #[cfg(not(feature = "ledger8"))]
    fn resolver(&self) -> &impl moonproof_prover::Resolver {
        static EMPTY: std::sync::OnceLock<moonproof_prover::ContractKeyResolver> =
            std::sync::OnceLock::new();
        EMPTY.get_or_init(moonproof_prover::ContractKeyResolver::default)
    }

    fn split(&mut self) -> Self {
        NoopProvingProvider
    }
}

// --- Token-type conversion -----------------------------------------------

/// Recognized aliases for the native NIGHT token.
const NATIVE_ALIASES: &[&str] = &["native", "night", "NIGHT", "Night", "NATIVE"];

/// Convert a wallet `TokenType` into a ledger `UnshieldedTokenType`.
///
/// - The aliases `"native" / "night" / "NIGHT" / "Night" / "NATIVE"` map to
///   [`NIGHT`] (the all-zero ledger constant).
/// - Anything else is parsed as a 64-character hex string and wrapped as an
///   `UnshieldedTokenType(HashOutput([u8; 32]))`.
pub fn to_ledger_token_type(token: &TokenType) -> Result<UnshieldedTokenType> {
    let s = token.as_str();
    if NATIVE_ALIASES.iter().any(|a| s.eq_ignore_ascii_case(a)) {
        return Ok(NIGHT);
    }
    let bytes = hex::decode(s).map_err(|e| {
        WalletError::InvalidTokenType(format!("token type `{s}` is not valid hex: {e}"))
    })?;
    let arr = <[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| {
        WalletError::InvalidTokenType(format!(
            "token type `{s}` decoded to {} bytes; expected 32",
            bytes.len()
        ))
    })?;
    Ok(UnshieldedTokenType(HashOutput(arr)))
}

/// Lift the wallet's `[u8; 32]` owner into a ledger `UserAddress`.
#[inline]
#[must_use]
pub fn to_ledger_user_address(owner: [u8; 32]) -> UserAddress {
    UserAddress(HashOutput(owner))
}

/// Lift the wallet's `[u8; 32]` intent hash into a ledger `IntentHash`.
#[inline]
#[must_use]
pub fn to_ledger_intent_hash(intent_hash: [u8; 32]) -> IntentHash {
    IntentHash(HashOutput(intent_hash))
}

/// Convert a wallet [`crate::SecretKey`] byte slice into a ledger
/// `SigningKey`. The slice must be exactly 32 bytes.
pub fn signing_key_from_bytes(bytes: &[u8]) -> Result<SigningKey> {
    moonproof_ledger::signatures::schnorr_signing_key(bytes)
        .map_err(|e| WalletError::SigningFailed(format!("invalid signing key bytes: {e}")))
}

/// Convert a `UtxoWithMeta` into a ledger `UtxoSpend` — needs the spender's
/// `VerifyingKey` (the on-chain `UtxoSpend.owner` is the verifying key used
/// to verify the input's signature, not the address that received it).
fn utxo_to_spend(utxo: &UtxoWithMeta, spender_verifying_key: &VerifyingKey) -> Result<UtxoSpend> {
    Ok(UtxoSpend {
        value: utxo.utxo.value,
        owner: spender_verifying_key.clone(),
        type_: to_ledger_token_type(&utxo.utxo.token_type)?,
        intent_hash: to_ledger_intent_hash(utxo.utxo.id.intent_hash),
        output_no: utxo.utxo.id.output_no,
    })
}

/// Convert an `UnshieldedOutputSpec` into a ledger `UtxoOutput`.
fn spec_to_output(spec: &UnshieldedOutputSpec) -> Result<UtxoOutput> {
    Ok(UtxoOutput {
        value: spec.value,
        owner: to_ledger_user_address(spec.owner),
        type_: to_ledger_token_type(&spec.token_type)?,
    })
}

// --- Intent construction --------------------------------------------------

/// Parameters for [`build_intent`] — bundled to keep the call site readable.
#[derive(Debug, Clone)]
pub struct IntentParams {
    /// `m/44'/2400'/account'/role/index`-derived verifying key whose UTXOs are
    /// being spent. Every input in the recipe must be owned by this key.
    pub spender_verifying_key: VerifyingKey,
    /// Time after which the chain rejects the transaction.
    pub ttl: Timestamp,
}

/// Convert a recipe into an Intent with empty signatures (ready for
/// [`sign_intent`]). Inputs become a single guaranteed `UnshieldedOffer`;
/// recipient + change outputs are concatenated in that order (matching
/// `TransferRecipe::all_outputs`); no fallible section, no contract calls,
/// no dust actions.
///
/// Returns `Ok(None)` if the recipe is empty (no inputs and no outputs) —
/// there's no transaction to build.
pub fn build_intent<R: RngCore + CryptoRng>(
    recipe: &TransferRecipe,
    params: &IntentParams,
    rng: &mut R,
) -> Result<Option<UnshieldedIntent>> {
    if recipe.inputs.is_empty()
        && recipe.recipient_outputs.is_empty()
        && recipe.change_outputs.is_empty()
    {
        return Ok(None);
    }

    let inputs: Vec<UtxoSpend> = recipe
        .inputs
        .iter()
        .map(|u| utxo_to_spend(u, &params.spender_verifying_key))
        .collect::<Result<_>>()?;

    let mut outputs: Vec<UtxoOutput> = Vec::with_capacity(recipe.total_output_count());
    for o in &recipe.recipient_outputs {
        outputs.push(spec_to_output(o)?);
    }
    for o in &recipe.change_outputs {
        outputs.push(spec_to_output(o)?);
    }

    // S = Signature throughout; we start with an empty signature array, which
    // `sign_intent` populates. This matches the test pattern in
    // midnight-ledger/ledger/tests/intent.rs:85 — `UnshieldedOffer<Signature, _>`
    // from the start, not `<(), _>`.
    let offer: UnshieldedOffer<Signature, Db> = UnshieldedOffer {
        inputs: inputs.into(),
        outputs: outputs.into(),
        signatures: Vec::<Signature>::new().into(),
    };

    let intent: UnshieldedIntent = Intent::new(
        rng,
        Some(offer),
        None,   // no fallible offer
        vec![], // no contract calls
        vec![], // no maintenance updates
        vec![], // no contract deploys
        None,   // no dust actions
        params.ttl,
    );

    Ok(Some(intent))
}

/// Fold `recipe`'s inputs (spent by `spender_verifying_key`) and outputs
/// into `existing`, an unsigned offer of someone else's intent, or into
/// a fresh offer when there is none. The ledger rejects an offer whose
/// inputs or outputs are out of order, so both are sorted after the
/// merge; the offer is left unsigned, for the intent it sits in to be
/// signed once it is complete.
///
/// # Errors
///
/// [`WalletError::SigningFailed`] when `existing` already carries
/// signatures: they cover the intent as it was, so extending it would
/// invalidate them.
pub fn merge_into_offer(
    existing: Option<&UnshieldedOffer<Signature, Db>>,
    recipe: &TransferRecipe,
    spender_verifying_key: &VerifyingKey,
) -> Result<UnshieldedOffer<Signature, Db>> {
    let (mut inputs, mut outputs): (Vec<UtxoSpend>, Vec<UtxoOutput>) = match existing {
        Some(offer) => {
            if !offer.signatures.is_empty() {
                return Err(WalletError::SigningFailed(
                    "cannot add inputs or outputs to an unshielded offer that is already signed"
                        .to_owned(),
                ));
            }
            (Vec::from(&offer.inputs), Vec::from(&offer.outputs))
        }
        None => (Vec::new(), Vec::new()),
    };
    for utxo in &recipe.inputs {
        inputs.push(utxo_to_spend(utxo, spender_verifying_key)?);
    }
    for spec in recipe.all_outputs() {
        outputs.push(spec_to_output(spec)?);
    }
    inputs.sort();
    outputs.sort();
    Ok(UnshieldedOffer {
        inputs: inputs.into(),
        outputs: outputs.into(),
        signatures: Vec::<Signature>::new().into(),
    })
}

// --- Signing --------------------------------------------------------------

/// Sign an Intent's guaranteed unshielded inputs in place. The number of
/// signing keys must equal the number of inputs (each input is signed by
/// the key that controls its UTXO).
///
/// `Intent::sign` returns `Self` — the type doesn't change; only the
/// `signatures` array inside the `UnshieldedOffer` becomes populated.
///
/// # Footgun protection
///
/// `moonproof_ledger::ledger::Intent::sign` internally uses `inputs.iter().zip(keys)`,
/// which silently truncates to the shorter side. Passing fewer keys than
/// inputs produces an Intent with under-signed inputs — `well_formed` will
/// reject it later, but at the wrong layer. We pre-validate here so callers
/// get an immediate error.
pub fn sign_intent<R: RngCore + CryptoRng>(
    intent: UnshieldedIntent,
    segment_id: u16,
    guaranteed_signing_keys: &[SigningKey],
    rng: &mut R,
) -> Result<UnshieldedIntent> {
    let input_count = intent
        .guaranteed_unshielded_offer
        .as_ref()
        .map_or(0, |offer| offer.inputs.len());

    if guaranteed_signing_keys.len() != input_count {
        return Err(WalletError::SigningFailed(format!(
            "guaranteed signing keys count ({}) does not match input count ({})",
            guaranteed_signing_keys.len(),
            input_count
        )));
    }

    intent
        .sign(rng, segment_id, guaranteed_signing_keys, &[], &[])
        .map_err(|e| WalletError::SigningFailed(format!("Intent::sign: {e:?}")))
}

// --- Transaction assembly -------------------------------------------------

/// Wrap a signed Intent into a `Transaction` ready for submission.
#[must_use]
pub fn build_transaction(
    intent: UnshieldedIntent,
    segment_id: u16,
    network_id: impl Into<String>,
) -> SignedTransaction {
    let mut intents: StorageHashMap<u16, UnshieldedIntent, Db> = StorageHashMap::new();
    intents = intents.insert(segment_id, intent);
    Transaction::from_intents(network_id, intents)
}

/// Serialize a `SignedTransaction` in the tagged form expected by a proof
/// server. NOT the form the node's submission endpoint accepts — for that,
/// finalize via [`finalize_unshielded_transaction`] and serialize the
/// result via [`serialize_finalized_transaction`].
pub fn serialize_transaction(tx: &SignedTransaction) -> Result<Vec<u8>> {
    let mut bytes = Vec::with_capacity(1024);
    tagged_serialize(tx, &mut bytes)
        .map_err(|e| WalletError::Serialization(format!("tagged_serialize: {e}")))?;
    Ok(bytes)
}

/// Upgrade a [`SignedTransaction`] (pre-proof, pre-bind) into a
/// [`FinalizedTransaction`] (post-proof, sealed binding) — the wire shape
/// the node accepts.
///
/// Internally calls `Transaction::prove(NoopProvingProvider, INITIAL_COST_MODEL)`
/// and then `.seal(OsRng)`. For **pure unshielded transactions only** —
/// the prove step does not invoke the proving provider (no actions/dust
/// actions/zswap offers to prove), it's a type-level cast from
/// `ProofPreimageMarker` to `ProofMarker`. The `seal` then uses `OsRng` to
/// derive the final `PureGeneratorPedersen` binding commitment from the
/// stored `PedersenRandomness`.
///
/// The resulting [`FinalizedTransaction`] serializes (via
/// [`serialize_finalized_transaction`]) to bytes the node can accept.
///
/// # Errors
///
/// Returns [`WalletError::Serialization`] if the transaction contains
/// proof-bearing content that the no-op prover can't handle. Callers
/// should use a real [`ProvingProvider`] (e.g. a proof-server client) for
/// those.
pub fn finalize_unshielded_transaction(tx: &SignedTransaction) -> Result<FinalizedTransaction> {
    // Prove (no-op cast for unshielded-only) → upgrade to ProofMarker while
    // keeping PedersenRandomness. We run this synchronously because
    // NoopProvingProvider's methods never suspend.
    let post_prove = futures::executor::block_on(tx.prove(NoopProvingProvider, &INITIAL_COST_MODEL))
        .map_err(|e: TransactionProvingError<Db>| {
            WalletError::Serialization(format!(
                "finalize_unshielded_transaction: prove step failed — transaction likely \
                 contains contract actions or Zswap offers that require a real proving provider: {e:?}"
            ))
        })?;

    // Seal: PedersenRandomness → PureGeneratorPedersen. Derives the final
    // binding commitment from the stored randomness. Uses OsRng because the
    // derivation needs secure randomness (the Schnorr signature inside
    // PureGeneratorPedersen::new_from).
    Ok(post_prove.seal(OsRng))
}

/// Serialize a [`FinalizedTransaction`] to the byte form the Midnight
/// node's `pallet_midnight.send_mn_transaction` expects (tagged form).
pub fn serialize_finalized_transaction(tx: &FinalizedTransaction) -> Result<Vec<u8>> {
    let mut bytes = Vec::with_capacity(1024);
    tagged_serialize(tx, &mut bytes)
        .map_err(|e| WalletError::Serialization(format!("tagged_serialize(finalized): {e}")))?;
    Ok(bytes)
}

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

    #[test]
    fn native_aliases_resolve_to_night() {
        for alias in NATIVE_ALIASES {
            let t = TokenType::new(*alias);
            let resolved = to_ledger_token_type(&t).expect("alias should resolve");
            assert_eq!(
                format!("{resolved:?}"),
                format!("{NIGHT:?}"),
                "alias `{alias}` did not resolve to NIGHT (got {resolved:?})"
            );
        }
    }

    #[test]
    fn hex_token_type_is_parsed_into_unshielded() {
        let bytes = [0xABu8; 32];
        let token = TokenType::new(hex::encode(bytes));
        let resolved = to_ledger_token_type(&token).expect("32-byte hex parses");
        assert_eq!(resolved.0 .0, bytes);
    }

    #[test]
    fn invalid_hex_token_type_errors() {
        let token = TokenType::new("not-hex!!");
        assert!(matches!(
            to_ledger_token_type(&token),
            Err(WalletError::InvalidTokenType(_))
        ));
    }

    #[test]
    fn wrong_length_hex_token_type_errors() {
        let token = TokenType::new(hex::encode([0xAA; 16])); // 16 bytes, not 32
        assert!(matches!(
            to_ledger_token_type(&token),
            Err(WalletError::InvalidTokenType(_))
        ));
    }

    #[test]
    fn user_address_round_trips_bytes() {
        let bytes = [0x55u8; 32];
        let addr = to_ledger_user_address(bytes);
        assert_eq!(addr.0 .0, bytes);
    }

    #[test]
    fn intent_hash_round_trips_bytes() {
        let bytes = [0x77u8; 32];
        let h = to_ledger_intent_hash(bytes);
        assert_eq!(h.0 .0, bytes);
    }
}