rusk-wallet 0.3.0

A library providing functionalities to create wallets compatible with Dusk
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) DUSK NETWORK. All rights reserved.

mod sync;

use std::path::Path;
use std::sync::{Arc, Mutex};

use rkyv::Deserialize;

use dusk_bytes::Serializable;
use dusk_core::BlsScalar;
use dusk_core::Error as ExecutionCoreError;
use dusk_core::signatures::bls::PublicKey as BlsPublicKey;
use dusk_core::stake::{StakeData, StakeFundOwner, StakeKeys};
use dusk_core::transfer::Transaction;
use dusk_core::transfer::moonlight::AccountData;
use dusk_core::transfer::phoenix::{
    ArchivedNoteLeaf, Note, NoteLeaf, NoteOpening, Prove,
    PublicKey as PhoenixPublicKey,
};
use flume::Receiver;
use futures::executor::block_on;
use tokio::sync::Notify;
use tokio::task::JoinHandle;
use tokio::time::{Duration, sleep};
use wallet_core::keys::{
    derive_phoenix_pk, derive_phoenix_sk, derive_phoenix_vk,
};
use wallet_core::pick_notes;
use zeroize::Zeroize;

use self::sync::sync_db;
use super::cache::Cache;
use crate::rues::HttpClient as RuesHttpClient;
use crate::store::LocalStore;
use crate::{Address, Error, MAX_PROFILES};

const TRANSFER_CONTRACT: &str =
    "0100000000000000000000000000000000000000000000000000000000000000";

const STAKE_CONTRACT: &str =
    "0200000000000000000000000000000000000000000000000000000000000000";

// Sync every 3 seconds for now
const SYNC_INTERVAL_SECONDS: u64 = 3;

/// SIZE of the tree leaf
pub const TREE_LEAF: usize = std::mem::size_of::<ArchivedNoteLeaf>();

/// A prover struct that has the `Prove` trait from executio-core implemented.
/// It currently uses a hardcoded prover which delegates the proving to the
/// `prove_execute`
pub struct Prover;

impl Prove for Prover {
    fn prove(
        &self,
        tx_circuit_vec_bytes: &[u8],
    ) -> Result<Vec<u8>, ExecutionCoreError> {
        Ok(tx_circuit_vec_bytes.to_vec())
    }
}

/// The state struct is responsible for managing the state of the wallet
pub struct State {
    cache: Mutex<Arc<Cache>>,
    status: fn(&str),
    client: RuesHttpClient,
    prover: RuesHttpClient,
    store: LocalStore,
    pub sync_rx: Option<Receiver<String>>,
    sync_shutdown: Option<(Arc<Notify>, JoinHandle<()>)>,
}

impl State {
    /// Creates a new state instance. Should only be called once.
    pub(crate) fn new(
        data_dir: &Path,
        status: fn(&str),
        client: RuesHttpClient,
        prover: RuesHttpClient,
        store: LocalStore,
    ) -> Result<Self, Error> {
        let cfs = (0..MAX_PROFILES)
            .flat_map(|i| {
                // we know that `i < MAX_PROFILES <= u8::MAX`, so casting to u8
                // is safe here
                #[allow(clippy::cast_possible_truncation)]
                let pk: PhoenixPublicKey =
                    derive_phoenix_pk(store.get_seed(), i as u8);

                let pk = bs58::encode(pk.to_bytes()).into_string();

                [pk.clone(), format!("spent_{pk}")]
            })
            .collect();

        let cache = Mutex::new(Arc::new(Cache::new(data_dir, cfs, status)?));

        Ok(Self {
            cache,
            sync_rx: None,
            store,
            prover,
            status,
            client,
            sync_shutdown: None,
        })
    }

    /// Returns the reference to the client
    pub fn client(&self) -> &RuesHttpClient {
        &self.client
    }

    pub async fn check_connection(&self) -> bool {
        self.client.check_connection().await.is_ok()
    }

    pub(crate) fn cache(&self) -> Arc<Cache> {
        let state = self.cache.lock();

        // We can get an error if the thread holding the lock panicked while
        // holding the lock. In this case, we can recover the guard from the
        // poison error and return the guard to the caller.
        match state {
            Ok(guard) => Arc::clone(&guard),
            Err(poisoned) => Arc::clone(&poisoned.into_inner()),
        }
    }

    pub fn register_sync(&mut self) {
        let (sync_tx, sync_rx) = flume::unbounded::<String>();

        self.sync_rx = Some(sync_rx);

        let cache = self.cache();
        let client = self.client.clone();
        let mut store = self.store.clone();
        let shutdown = Arc::new(Notify::new());
        let shutdown_signal = shutdown.clone();

        let handle = tokio::spawn(async move {
            tracing::debug!("Starting background sync loop");
            loop {
                tokio::select! {
                    biased;
                    () = shutdown_signal.notified() => break,
                    () = sleep(Duration::from_secs(SYNC_INTERVAL_SECONDS)) => {
                        let _ = sync_tx.send("Syncing..".to_string());

                        let _ = match sync_db(&client, &cache, &store, |_| {}).await {
                            Ok(()) => sync_tx.send("Syncing Complete".to_string()),
                            Err(e) => sync_tx.send(format!("Error during sync:.. {e}")),
                        };
                    }
                }
            }
            store.inner_mut().zeroize();
            tracing::debug!("Background sync loop stopped");
        });

        self.sync_shutdown = Some((shutdown, handle));
    }

    pub async fn sync(&self) -> Result<(), Error> {
        sync_db(&self.client, &self.cache(), &self.store, self.status).await
    }

    /// Requests that a node prove the given shielded transaction.
    /// Returns the transaction unchanged for unshielded transaction.
    pub async fn prove(&self, tx: Transaction) -> Result<Transaction, Error> {
        let prover = &self.prover;
        let mut tx = tx;

        if let Transaction::Phoenix(utx) = &mut tx {
            let status = self.status;
            let proof = utx.proof();

            status("Attempt to prove tx...");

            let proof =
                prover.call("prover", None, "prove", proof).await.map_err(
                    |e| ExecutionCoreError::PhoenixCircuit(e.to_string()),
                )?;

            utx.set_proof(proof);

            status("Proving sucesss!");
        }

        Ok(tx)
    }

    /// Propagate a transaction to a node.
    pub async fn propagate(
        &self,
        tx: Transaction,
    ) -> Result<Transaction, Error> {
        let status = self.status;
        let tx_bytes = tx.to_var_bytes();

        status("Attempt to preverify tx...");
        let _ = self
            .client
            .call("transactions", None, "preverify", &tx_bytes)
            .await?;
        status("Preverify success!");

        status("Propagating tx...");
        let _ = self
            .client
            .call("transactions", None, "propagate", &tx_bytes)
            .await?;
        status("Transaction propagated!");

        Ok(tx)
    }

    /// Selects up to `MAX_INPUT_NOTES` unspent input notes from the cache. The
    /// value of the input notes need to cover the cost of the transaction.
    pub(crate) async fn tx_input_notes(
        &self,
        index: u8,
        tx_cost: u64,
    ) -> Result<Vec<(Note, NoteOpening, BlsScalar)>, Error> {
        let vk = derive_phoenix_vk(self.store().get_seed(), index);
        let mut sk = derive_phoenix_sk(self.store().get_seed(), index);
        let pk = derive_phoenix_pk(self.store().get_seed(), index);

        // fetch the cached unspent notes
        let cached_notes: Vec<_> = self
            .cache()
            .notes(&pk)
            .inspect_err(|_| sk.zeroize())?
            .into_iter()
            .map(|note_leaf| {
                let nullifier = note_leaf.note.gen_nullifier(&sk);
                (nullifier, note_leaf)
            })
            .collect();

        sk.zeroize();

        // pick up to MAX_INPUT_NOTES input-notes that cover the tx-cost
        let tx_input_notes = pick_notes(&vk, cached_notes.into(), tx_cost);
        if tx_input_notes.is_empty() {
            return Err(Error::NotEnoughBalance);
        }

        // construct the transaction input
        let mut tx_input = Vec::<(Note, NoteOpening, BlsScalar)>::new();
        for (nullifier, note_leaf) in &tx_input_notes {
            // fetch the openings for the input-notes
            let opening = self.fetch_opening(note_leaf.as_ref()).await?;

            tx_input.push((note_leaf.note.clone(), opening, *nullifier));
        }

        Ok(tx_input)
    }

    pub(crate) async fn fetch_account(
        &self,
        pk: &BlsPublicKey,
    ) -> Result<AccountData, Error> {
        let status = self.status;
        status("Fetching account-data...");

        // the target type of the deserialization has to match the return type
        // of the contract-query
        let bytes = self
            .client
            .contract_query::<_, _, 1024>(TRANSFER_CONTRACT, "account", pk)
            .await?;
        let account: AccountData =
            rkyv::check_archived_root::<AccountData>(&bytes)
                .map_err(|_| Error::Rkyv)?
                .deserialize(&mut rkyv::Infallible)
                .unwrap();

        status("account-data received!");

        Ok(account)
    }

    pub(crate) fn fetch_notes(
        &self,
        pk: &PhoenixPublicKey,
    ) -> Result<Vec<NoteLeaf>, Error> {
        self.cache().notes(pk).map(|set| set.into_iter().collect())
    }

    /// Fetch the current root of the state.
    pub(crate) async fn fetch_root(&self) -> Result<BlsScalar, Error> {
        let status = self.status;
        status("Fetching root...");

        // the target type of the deserialization has to match the return type
        // of the contract-query
        let bytes = self
            .client
            .contract_query::<(), _, 0>(TRANSFER_CONTRACT, "root", &())
            .await?;
        let root: BlsScalar = rkyv::check_archived_root::<BlsScalar>(&bytes)
            .map_err(|_| Error::Rkyv)?
            .deserialize(&mut rkyv::Infallible)
            .unwrap();

        status("root received!");

        Ok(root)
    }

    /// Queries the node for the amount staked by a key.
    pub(crate) async fn fetch_stake(
        &self,
        pk: &BlsPublicKey,
    ) -> Result<Option<StakeData>, Error> {
        let status = self.status;
        status("Fetching stake...");

        // the target type of the deserialization has to match the return type
        // of the contract-query
        let bytes = self
            .client
            .contract_query::<_, _, 1024>(STAKE_CONTRACT, "get_stake", pk)
            .await?;
        let stake_data: Option<StakeData> =
            rkyv::check_archived_root::<Option<StakeData>>(&bytes)
                .map_err(|_| Error::Rkyv)?
                .deserialize(&mut rkyv::Infallible)
                .unwrap();

        status("Stake received!");

        println!("Staking address: {}", Address::Public(*pk));

        Ok(stake_data)
    }

    /// Get the stake owner of a given stake account.
    pub(crate) async fn fetch_stake_owner(
        &self,
        pk: &BlsPublicKey,
    ) -> Result<Option<StakeFundOwner>, Error> {
        let status = self.status;
        status("Fetching stake owner...");

        // the target type of the deserialization has to match the return type
        // of the contract-query
        let bytes = self
            .client
            .contract_query::<_, _, 1024>(STAKE_CONTRACT, "get_stake_keys", pk)
            .await?;
        let stake_keys: Option<StakeKeys> =
            rkyv::check_archived_root::<Option<StakeKeys>>(&bytes)
                .map_err(|_| Error::Rkyv)?
                .deserialize(&mut rkyv::Infallible)
                .unwrap();

        let stake_owner = stake_keys.map(|keys| keys.owner);

        Ok(stake_owner)
    }

    pub(crate) fn store(&self) -> &LocalStore {
        &self.store
    }

    pub(crate) async fn fetch_chain_id(&self) -> Result<u8, Error> {
        let status = self.status;
        status("Fetching chain_id...");

        // the target type of the deserialization has to match the return type
        // of the contract-query
        let bytes = self
            .client
            .contract_query::<_, _, { u8::SIZE }>(
                TRANSFER_CONTRACT,
                "chain_id",
                &(),
            )
            .await?;
        let chain_id: u8 = rkyv::check_archived_root::<u8>(&bytes)
            .map_err(|_| Error::Rkyv)?
            .deserialize(&mut rkyv::Infallible)
            .unwrap();

        status("Chain id received!");

        Ok(chain_id)
    }

    /// Queries the node to find the merkle-tree opening for a specific note.
    async fn fetch_opening(&self, note: &Note) -> Result<NoteOpening, Error> {
        let status = self.status;
        status("Fetching note opening...");

        // the target type of the deserialization has to match the return type
        // of the contract-query
        let bytes = self
            .client
            .contract_query::<_, _, 1024>(
                TRANSFER_CONTRACT,
                "opening",
                note.pos(),
            )
            .await?;
        let opening: Option<NoteOpening> =
            rkyv::check_archived_root::<Option<NoteOpening>>(&bytes)
                .map_err(|_| Error::Rkyv)?
                .deserialize(&mut rkyv::Infallible)
                .unwrap();

        // return an error here if the note opening couldn't be fetched
        let opening = opening.ok_or(Error::NoteNotFound)?;

        status("Note opening received!");

        Ok(opening)
    }

    /// Queries the transfer contract for the number of notes.
    pub async fn fetch_num_notes(&self) -> Result<u64, Error> {
        let status = self.status;
        status("Fetching note count...");

        // the target type of the deserialization has to match the return type
        // of the contract-query
        let bytes = self
            .client
            .contract_query::<_, _, { u64::SIZE }>(
                TRANSFER_CONTRACT,
                "num_notes",
                &(),
            )
            .await?;
        let note_count: u64 = rkyv::check_archived_root::<u64>(&bytes)
            .map_err(|_| Error::Rkyv)?
            .deserialize(&mut rkyv::Infallible)
            .unwrap();

        status("Latest note count received!");

        Ok(note_count)
    }

    pub fn close(&mut self) {
        self.cache().close();
        let store = &mut self.store;

        // if there's sync handle we abort it
        if let Some((shutdown, handle)) = self.sync_shutdown.take() {
            shutdown.notify_one();
            if let Err(e) = block_on(handle) {
                eprintln!("Error while closing sync handle: {e}");
            }
        }

        store.inner_mut().zeroize();
    }
}