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
//! A synced wallet answering a dApp in-process: the dApp connector 4.1
//! surface over one [`WalletSession`]. Spends are booked against the
//! live facade under one lock, so concurrent builds never pick the same
//! coins, and every submission is followed to its outcome, which lands
//! in the wallet's history and releases what the chain did not spend.
//!
//! [`seal_unbound`] and [`pay_sealed`] are the two balancing operations
//! on their own, for hosts that keep their facade elsewhere.

use std::sync::Arc;
use std::time::Duration as StdDuration;

use anyhow::{anyhow, Context, Result};
use moonproof_indexer_client::HttpIndexerClient;
use moonproof_ledger::ledger::dust::DustSecretKey;
use moonproof_node_client::SubmissionStage;
use tokio::sync::{Mutex, RwLock};

use crate::connector::{
    self, Configuration, DesiredInput, DesiredOutput, DustBalance, HistoryEntry, MakeIntentOptions,
    SignDataOptions, WalletAddresses,
};
use crate::facade::{
    balance_sealed_recipe, balance_unbound_recipe, build_transfer_recipe, ended_transaction_result,
    init_swap, serialize_finalized, sign_recipe, FacadeState, FinalizedTransaction,
    FinalizedTransactionRecipe, ProvenTransaction, SubmissionEnd, SubmissionWatch, SwapOptions,
    TransferOptions, TransferSigningKeys, UnprovenTransaction, UnprovenTransactionRecipe,
};
use crate::pending_tx::{
    InMemoryPendingTransactionsStorage, PendingTransactionEntry, PendingTransactionResult,
    PendingTransactionStatus, PendingTransactionsStorage,
};
use crate::signing::SignedDataOutput;
use crate::tx_history::{
    InMemoryTransactionHistoryStorage, TransactionHistoryEntry, TransactionHistoryStatus,
    TransactionHistoryStorage,
};
use crate::{Wallet, WalletError};

use super::{
    drain_wallet_sync, finalize_with_backend, sync_wallet_fresh, ttl_from, ProvingBackend,
    WalletSession, TRANSACTION_TTL_SECS,
};

/// How long a submission is followed for its outcome: twice the TTL
/// wallet-built transactions carry, so the TTL passes first.
const FOLLOW_LIMIT: StdDuration = StdDuration::from_secs(2 * TRANSACTION_TTL_SECS);

/// `balanceUnsealedTransaction`: close the token imbalances of a
/// proven, unbound transaction from `wallet`'s coins, pay its fee in
/// Dust when `pay_fees` is set, and seal it. Returns the facade with
/// the spends booked, and the transaction ready to submit.
pub async fn seal_unbound(
    facade: FacadeState,
    base: ProvenTransaction,
    wallet: &Wallet,
    pay_fees: bool,
    backend: &ProvingBackend,
) -> Result<(FacadeState, FinalizedTransaction)> {
    let zswap = wallet.zswap_secret_keys();
    let dust = wallet.dust_secret_key();
    let options = balancing_options(&facade, pay_fees);
    let (recipe, booked) = balance_unbound_recipe(
        &mut rand::rngs::OsRng,
        facade,
        base,
        &signing_keys(wallet, &zswap, &dust),
        &options,
    )
    .map_err(anyhow::Error::new)?;
    let leg = prove_leg(recipe.balancing.clone(), backend).await?;
    let sealed = recipe.complete(leg).map_err(anyhow::Error::new)?;
    Ok((booked, sealed))
}

/// `balanceSealedTransaction`: merge into `original`, a sealed
/// transaction, a proven leg that closes its token imbalances from
/// `wallet`'s coins and, when `pay_fees` is set, pays its fee in Dust.
/// Returns the facade with the spends booked, and the transaction ready
/// to submit.
pub async fn pay_sealed(
    facade: FacadeState,
    original: FinalizedTransaction,
    wallet: &Wallet,
    pay_fees: bool,
    backend: &ProvingBackend,
) -> Result<(FacadeState, FinalizedTransaction)> {
    let zswap = wallet.zswap_secret_keys();
    let dust = wallet.dust_secret_key();
    let options = balancing_options(&facade, pay_fees);
    let (recipe, booked) = balance_sealed_recipe(
        &mut rand::rngs::OsRng,
        facade,
        original,
        &signing_keys(wallet, &zswap, &dust),
        &options,
    )
    .map_err(anyhow::Error::new)?;
    let leg = prove_leg(recipe.balancing.clone(), backend).await?;
    let paid = recipe.complete(leg).map_err(anyhow::Error::new)?;
    Ok((booked, paid))
}

fn balancing_options(facade: &FacadeState, pay_fees: bool) -> TransferOptions {
    let now = facade.chain_tip_ts();
    TransferOptions {
        ttl: ttl_from(now),
        current_time: now,
        pay_fees,
    }
}

fn signing_keys<'a>(
    wallet: &'a Wallet,
    zswap: &'a moonproof_ledger::zswap::keys::SecretKeys,
    dust: &'a DustSecretKey,
) -> TransferSigningKeys<'a> {
    TransferSigningKeys {
        shielded_secret_keys: zswap,
        dust_secret_key: dust,
        night_signing_key: &wallet.signing_key,
        night_verifying_key: &wallet.verifying_key,
        sender_owner: wallet.owner_bytes(),
    }
}

async fn prove_leg(
    leg: Option<UnprovenTransaction>,
    backend: &ProvingBackend,
) -> Result<Option<FinalizedTransaction>> {
    let Some(transaction) = leg else {
        return Ok(None);
    };
    let proven = finalize_with_backend(UnprovenTransactionRecipe { transaction }, backend)
        .await
        .context("prove the balancing leg")?;
    Ok(Some(proven.transaction))
}

/// Tagged wire bytes of a sealed transaction.
pub fn sealed_bytes(transaction: FinalizedTransaction) -> Result<Vec<u8>> {
    serialize_finalized(&FinalizedTransactionRecipe { transaction }).map_err(anyhow::Error::new)
}

/// A synced wallet serving the dApp connector surface in-process.
pub struct ConnectedWallet {
    session: WalletSession,
    backend: ProvingBackend,
    facade: RwLock<FacadeState>,
    /// Held from reading the facade for a build until the build's spends
    /// are booked, and around every fold, so neither can lose the other.
    spend: Mutex<()>,
    pending: InMemoryPendingTransactionsStorage,
    history: InMemoryTransactionHistoryStorage,
}

impl ConnectedWallet {
    /// Sync `session` from genesis and serve it, proving through
    /// `backend`.
    pub async fn open(session: WalletSession, backend: ProvingBackend) -> Result<Arc<Self>> {
        let facade = Box::pin(sync_wallet_fresh(&session)).await?;
        Ok(Arc::new(Self {
            session,
            backend,
            facade: RwLock::new(facade),
            spend: Mutex::new(()),
            pending: InMemoryPendingTransactionsStorage::new(),
            history: InMemoryTransactionHistoryStorage::new(),
        }))
    }

    /// Fold what the chain did since the last sync into the facade,
    /// keeping every booking made meanwhile.
    pub async fn sync(&self) -> Result<()> {
        let prior = self.facade.read().await.clone();
        let (_, drained) = Box::pin(drain_wallet_sync(&self.session, Some(prior))).await?;
        let _spend = self.spend.lock().await;
        let current = self.facade.read().await.clone();
        let folded = drained.fold_into(current, &self.session.wallet)?;
        *self.facade.write().await = folded;
        Ok(())
    }

    /// The synced facade.
    pub async fn facade(&self) -> FacadeState {
        self.facade.read().await.clone()
    }

    /// The underlying [`WalletSession`] (network, wallet keys, node client).
    #[must_use]
    pub const fn session(&self) -> &WalletSession {
        &self.session
    }

    /// `getConfiguration`.
    #[must_use]
    pub fn configuration(&self) -> Configuration {
        let prover = match &self.backend {
            ProvingBackend::InProcess => None,
            ProvingBackend::HttpServer { base_url } => Some(base_url.clone()),
        };
        Configuration::of(&self.session.network, prover)
    }

    /// `getShieldedAddresses`, `getUnshieldedAddress`, `getDustAddress`.
    pub fn addresses(&self) -> crate::Result<WalletAddresses> {
        connector::addresses(&self.session.wallet)
    }

    /// `getShieldedBalances`.
    pub async fn shielded_balances(&self) -> std::collections::BTreeMap<String, u128> {
        connector::shielded_balances(
            &*self.facade.read().await,
            &self.session.wallet.zswap_secret_keys(),
        )
    }

    /// `getUnshieldedBalances`.
    pub async fn unshielded_balances(
        &self,
    ) -> crate::Result<std::collections::BTreeMap<String, u128>> {
        connector::unshielded_balances(&*self.facade.read().await)
    }

    /// `getDustBalance`, at the synced chain time.
    pub async fn dust_balance(&self) -> DustBalance {
        let facade = self.facade.read().await;
        connector::dust_balance(&facade, facade.chain_tip_ts())
    }

    /// `getTxHistory(page, pageSize)`.
    pub async fn tx_history(&self, page: u32, page_size: u32) -> crate::Result<Vec<HistoryEntry>> {
        let pending = self.pending.get_all().await?;
        let history = self.history.get_all().await?;
        Ok(connector::history_page(&pending, &history, page, page_size))
    }

    /// `signData(data, options)`.
    pub fn sign_data(
        &self,
        data: &str,
        options: &SignDataOptions,
    ) -> crate::Result<SignedDataOutput> {
        connector::sign_data(&self.session.wallet.signing_key, data, options)
    }

    fn keys<'a>(
        &'a self,
        zswap: &'a moonproof_ledger::zswap::keys::SecretKeys,
        dust: &'a DustSecretKey,
    ) -> TransferSigningKeys<'a> {
        signing_keys(&self.session.wallet, zswap, dust)
    }

    /// Sign and prove `recipe`, then book `booked`. Call with `spend`
    /// held.
    async fn prove_and_book(
        &self,
        recipe: UnprovenTransactionRecipe,
        booked: FacadeState,
    ) -> Result<Vec<u8>> {
        let signed = sign_recipe(
            recipe,
            &self.session.wallet.signing_key,
            &mut rand::rngs::OsRng,
        )
        .map_err(anyhow::Error::new)?;
        let finalized = finalize_with_backend(signed, &self.backend).await?;
        let bytes = serialize_finalized(&finalized).map_err(anyhow::Error::new)?;
        *self.facade.write().await = booked;
        Ok(bytes)
    }

    /// `makeTransfer(desiredOutputs, { payFees })`: a proven transaction
    /// ready to submit.
    pub async fn make_transfer(
        &self,
        outputs: &[DesiredOutput],
        pay_fees: bool,
    ) -> Result<Vec<u8>> {
        if outputs.is_empty() {
            return Err(anyhow::Error::new(WalletError::InvalidAmount(
                "makeTransfer needs a desired output".to_owned(),
            )));
        }
        let transfers = connector::transfer_outputs(outputs, &self.session.network.network_id)?;
        // Refresh from the indexer before spending so confirmed change coins
        // and the latest chain tip timestamp are visible to coin selection.
        self.sync().await?;
        let _spend = self.spend.lock().await;
        let synced = self.facade.read().await.clone();
        let zswap = self.session.wallet.zswap_secret_keys();
        let dust = self.session.wallet.dust_secret_key();
        let now = synced.chain_tip_ts();
        let (recipe, booked) = build_transfer_recipe(
            &mut rand::rngs::OsRng,
            synced,
            &transfers,
            &self.keys(&zswap, &dust),
            &TransferOptions {
                ttl: ttl_from(now),
                current_time: now,
                pay_fees,
            },
        )?;
        self.prove_and_book(recipe, booked).await
    }

    /// `makeIntent(desiredInputs, desiredOutputs, options)`: this
    /// wallet's proven half of a swap.
    pub async fn make_intent(
        &self,
        inputs: &[DesiredInput],
        outputs: &[DesiredOutput],
        options: MakeIntentOptions,
    ) -> Result<Vec<u8>> {
        let inputs = connector::swap_inputs(inputs)?;
        let outputs = connector::transfer_outputs(outputs, &self.session.network.network_id)?;
        let segment = options.intent_id.resolve(&mut rand::rngs::OsRng);
        // Refresh from the indexer before spending so confirmed change coins
        // and the latest chain tip timestamp are visible to coin selection.
        self.sync().await?;
        let _spend = self.spend.lock().await;
        let synced = self.facade.read().await.clone();
        let zswap = self.session.wallet.zswap_secret_keys();
        let dust = self.session.wallet.dust_secret_key();
        let now = synced.chain_tip_ts();
        let (recipe, booked) = init_swap(
            &mut rand::rngs::OsRng,
            synced,
            &inputs,
            &outputs,
            &self.keys(&zswap, &dust),
            &SwapOptions {
                ttl: ttl_from(now),
                current_time: now,
                pay_fees: options.pay_fees,
            },
            segment,
        )?;
        self.prove_and_book(recipe, booked).await
    }

    /// `balanceUnsealedTransaction(tx, { payFees })`.
    pub async fn balance_unsealed(
        &self,
        base: ProvenTransaction,
        pay_fees: bool,
    ) -> Result<Vec<u8>> {
        // Refresh from the indexer before balancing so change coins from
        // prior transactions and a fresh chain tip timestamp are available.
        self.sync().await?;
        let _spend = self.spend.lock().await;
        let facade = self.facade.read().await.clone();
        let (booked, sealed) = Box::pin(seal_unbound(
            facade,
            base,
            &self.session.wallet,
            pay_fees,
            &self.backend,
        ))
        .await?;
        let bytes = sealed_bytes(sealed)?;
        *self.facade.write().await = booked;
        Ok(bytes)
    }

    /// `balanceSealedTransaction(tx, { payFees })`.
    pub async fn balance_sealed(
        &self,
        original: FinalizedTransaction,
        pay_fees: bool,
    ) -> Result<Vec<u8>> {
        // Refresh from the indexer before balancing so change coins from
        // prior transactions and a fresh chain tip timestamp are available.
        self.sync().await?;
        let _spend = self.spend.lock().await;
        let facade = self.facade.read().await.clone();
        let (booked, paid) = Box::pin(pay_sealed(
            facade,
            original,
            &self.session.wallet,
            pay_fees,
            &self.backend,
        ))
        .await?;
        let bytes = sealed_bytes(paid)?;
        *self.facade.write().await = booked;
        Ok(bytes)
    }

    /// `submitTransaction(tx)`: hand the sealed `bytes` to the node and
    /// return once it accepts them. The transaction is then followed in
    /// the background until its outcome is in the history.
    pub async fn submit_transaction(self: &Arc<Self>, bytes: Vec<u8>) -> Result<()> {
        let tx = moonproof_ledger::serialize::tagged_deserialize::<FinalizedTransaction>(
            bytes.as_slice(),
        )
        .map_err(|e| {
            anyhow::Error::new(WalletError::Serialization(format!("not a sealed tx: {e}")))
        })?;
        let mut watch = SubmissionWatch::submit(self.session.node.as_ref(), bytes.clone()).await;
        let submitted = watch.wait_for(SubmissionStage::Submitted).await;
        if watch.settled() == Some(SubmissionEnd::Excluded) {
            let _spend = self.spend.lock().await;
            let current = self.facade.read().await.clone();
            let released = current.revert_transaction(&tx);
            *self.facade.write().await = released;
            return submitted.map(|_| ()).map_err(anyhow::Error::new);
        }
        let event = submitted.map_err(anyhow::Error::new)?;
        let protocol_version = self.facade.read().await.protocol_version();
        let segment_ids = match &tx {
            moonproof_ledger::ledger::structure::Transaction::Standard(stx) => {
                let mut ids: Vec<u16> = stx.intents.keys().collect();
                ids.sort_unstable();
                ids
            }
            moonproof_ledger::ledger::structure::Transaction::ClaimRewards(_) => Vec::new(),
        };
        let submitted_at_ms = moonproof_utils::rt::SystemTime::now()
            .duration_since(moonproof_utils::rt::UNIX_EPOCH)
            .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX));
        let tx_hash = event.tx_hash().to_owned();
        self.pending
            .upsert(PendingTransactionEntry {
                hash: tx_hash.clone(),
                creation_time_ms: submitted_at_ms,
                segment_ids: segment_ids.clone(),
                ttl_secs: i64::try_from(TRANSACTION_TTL_SECS).ok(),
                raw_tx_hex: Some(hex::encode(&bytes)),
                result: None,
            })
            .await?;

        let wallet = Arc::downgrade(self);
        moonproof_utils::rt::spawn(async move {
            let end = watch.end().await;
            let Some(this) = wallet.upgrade() else {
                return;
            };
            let outcome = Submission {
                tx_hash,
                submitted_at_ms,
                segment_ids,
                protocol_version,
            };
            if let Err(e) = this.settle(&tx, end, outcome).await {
                tracing::warn!(error = %e, "following a dApp submission failed");
            }
        });
        Ok(())
    }

    /// Learn `tx`'s outcome, record it, and release what the chain did
    /// not spend.
    async fn settle(
        &self,
        tx: &FinalizedTransaction,
        end: SubmissionEnd,
        submission: Submission,
    ) -> Result<()> {
        let indexer = HttpIndexerClient::new(&self.session.network.indexer_http)
            .map_err(|e| anyhow!("indexer url: {e}"))?;
        let result = ended_transaction_result(&indexer, tx, end, FOLLOW_LIMIT)
            .await
            .ok_or_else(|| {
                anyhow!(
                    "no result for {} within the follow limit",
                    submission.tx_hash
                )
            })?;
        self.record_outcome(submission, &result).await?;
        if result.status != PendingTransactionStatus::Success {
            let _spend = self.spend.lock().await;
            let current = self.facade.read().await.clone();
            *self.facade.write().await = current.release_ended(tx, &result);
        }
        // Fold confirmed change and newly created coins into the facade so
        // balances and subsequent spends reflect the settled transaction.
        if let Err(e) = self.sync().await {
            tracing::warn!(error = %e, "post-settlement wallet sync failed");
        }
        Ok(())
    }

    async fn record_outcome(
        &self,
        submission: Submission,
        result: &PendingTransactionResult,
    ) -> Result<()> {
        let execution = connector::execution_status(&submission.segment_ids, result);
        self.history
            .upsert(TransactionHistoryEntry {
                hash: submission.tx_hash.clone(),
                protocol_version: submission.protocol_version,
                status: match result.status {
                    PendingTransactionStatus::Success => TransactionHistoryStatus::Success,
                    PendingTransactionStatus::PartialSuccess => {
                        TransactionHistoryStatus::PartialSuccess
                    }
                    PendingTransactionStatus::Failure => TransactionHistoryStatus::Failure,
                },
                identifiers: None,
                timestamp_ms: Some(submission.submitted_at_ms),
                fees: None,
                shielded: None,
                unshielded: None,
                dust: None,
                extra: serde_json::json!({ connector::EXECUTION_STATUS_KEY: execution }),
            })
            .await?;
        self.pending
            .mark_result(&submission.tx_hash, result.clone())
            .await?;
        Ok(())
    }
}

/// What a followed submission's history row needs besides its outcome.
struct Submission {
    tx_hash: String,
    submitted_at_ms: i64,
    segment_ids: Vec<u16>,
    protocol_version: crate::abstractions::ProtocolVersion,
}