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
// 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.

//! The graphql endpoint can be queried with this helper struct.
//! The <node-url>/on/gaphql/query if queried with empty bytes returns the
//! graphql schema

use dusk_core::abi::ContractId;
use dusk_core::stake::StakeEvent;
use dusk_core::transfer::phoenix::StealthAddress;
use dusk_core::transfer::{
    ConvertEvent, DepositEvent, MoonlightTransactionEvent, Transaction,
    WithdrawEvent,
};
use serde::Deserialize;
use serde_json::Value;
use serde_with::hex::Hex;
use serde_with::{As, DisplayFromStr};
use tokio::time::{Duration, sleep};

use crate::rues::HttpClient as RuesHttpClient;
use crate::{Address, Error};

/// GraphQL is a helper struct that aggregates all queries done
/// to the Dusk GraphQL database.
/// This helps avoid having helper structs and boilerplate code
/// mixed with the wallet logic.
#[derive(Clone)]
pub struct GraphQL {
    state_client: RuesHttpClient,
    archiver_client: RuesHttpClient,
    status: fn(&str),
}

/// The `tx_for_block` returns a Vec<BlockTransaction> which contains
/// the dusk-core transaction, its id hash and gas spent
pub struct BlockTransaction {
    /// The dusk-core transaction struct obtained from GraphQL endpoint
    pub tx: Transaction,
    /// The hash of the transaction or the id of the transaction in string utf8
    pub id: String,
    /// Gas amount spent for the transaction
    pub gas_spent: u64,
}

#[derive(Deserialize)]
struct SpentTx {
    pub id: String,
    #[serde(default)]
    pub raw: String,
    pub err: Option<String>,
    #[serde(alias = "gasSpent", default)]
    pub gas_spent: u64,
}

#[derive(Deserialize)]
struct Block {
    pub transactions: Vec<SpentTx>,
}

#[derive(Deserialize)]
struct BlockResponse {
    pub block: Option<Block>,
}

// See `PhoenixTransactionEventSubset` for the reason for this struct
// and allowing dead code here.
#[derive(Deserialize, Debug, Clone)]
#[allow(dead_code)]
struct NoteAddress {
    stealth_address: StealthAddress,
}

// This struct is used instead of the one in `dusk_core::transfer`
// because of the order-dependent deserialization bug in
// the `dusk_core::transfer::phoenix::Note` https://github.com/dusk-network/phoenix/issues/274.
// Dead code is allowed to avoid catch-alls, so that the case in which an
// unexpected event is received, an appropriate error will be thrown.
#[derive(serde::Deserialize, Debug)]
#[allow(dead_code)]
pub struct PhoenixTransactionEventSubset {
    /// Notes produced during the transaction.
    #[serde(rename(deserialize = "notes"))]
    note_addresses: Vec<NoteAddress>,
    /// The memo included in the transaction.
    #[serde(with = "As::<Hex>")]
    memo: Vec<u8>,
    /// Gas spent by the transaction.
    #[serde(with = "As::<DisplayFromStr>")]
    gas_spent: u64,
    /// Optional gas-refund note if the refund is positive.
    #[serde(rename(deserialize = "refund_note"))]
    refund_note_address: Option<NoteAddress>,
}

/// Deserialized block data in the full moonlight history.
#[derive(Deserialize, Debug)]
#[serde(untagged)]
#[allow(clippy::large_enum_variant)]
pub enum BlockData {
    /// For the moonlight transaction event.
    MoonlightTransactionEvent(MoonlightTransactionEvent),
    /// For the `PhoenixTransactionEvent`.
    /// In the case where a conversion is made from phoenix to
    /// moonlight, this appears.
    PhoenixTransactionEvent(PhoenixTransactionEventSubset),
    /// For the convert event.
    ConvertEvent(ConvertEvent),
    /// For the stake event.
    StakeEvent(StakeEvent),
    /// For the deposit event.
    DepositEvent(DepositEvent),
    /// For the withdraw event.
    WithdrawEvent(WithdrawEvent),
}

#[derive(Deserialize, Debug)]
pub struct BlockEvents {
    pub data: BlockData,
    pub target: ContractId,
}

#[derive(Deserialize, Debug)]
pub struct MoonlightHistory {
    pub block_height: u64,
    pub origin: String,
    pub events: Vec<BlockEvents>,
}

#[derive(Deserialize, Debug)]
pub struct MoonlightHistoryJson {
    pub json: Vec<MoonlightHistory>,
}

#[derive(Deserialize, Debug)]
pub struct FullMoonlightHistory {
    #[serde(rename(deserialize = "fullMoonlightHistory"))]
    pub full_moonlight_history: Option<MoonlightHistoryJson>,
}

#[derive(Deserialize)]
struct SpentTxResponse {
    pub tx: Option<SpentTx>,
}

/// Transaction status
#[derive(Debug)]
pub enum TxStatus {
    Ok,
    NotFound,
    Error(String),
}

impl GraphQL {
    /// Create a new GraphQL wallet client
    ///
    /// # Errors
    /// This method errors if a TLS backend cannot be initialized, or the
    /// resolver cannot load the system configuration.
    pub fn new<S: Into<String>>(
        state_url: S,
        archiver_url: S,
        status: fn(&str),
    ) -> Result<Self, Error> {
        Ok(Self {
            state_client: RuesHttpClient::new(state_url)?,
            archiver_client: RuesHttpClient::new(archiver_url)?,
            status,
        })
    }

    /// Wait for a transaction to be confirmed (included in a block)
    ///
    /// # Errors
    /// This method errors if there was an error while sending the query,
    /// or if the response body is not in JSON format or encoded correctly.
    pub async fn wait_for(&self, tx_id: &str) -> anyhow::Result<()> {
        loop {
            let status = self.tx_status(tx_id).await?;

            match status {
                TxStatus::Ok => break,
                TxStatus::Error(err) => return Err(Error::Transaction(err))?,
                TxStatus::NotFound => {
                    (self.status)(
                        "Waiting for tx to be included into a block...",
                    );
                    sleep(Duration::from_millis(1000)).await;
                }
            }
        }
        Ok(())
    }

    /// Obtain transaction status
    ///
    /// # Errors
    /// This method errors if there was an error while sending the query,
    /// if the response body is not in JSON format or encoded correctly or if
    /// the transaction couldn't be found.
    async fn tx_status(&self, tx_id: &str) -> Result<TxStatus, Error> {
        let query =
            "query { tx(hash: \"####\") { id, err }}".replace("####", tx_id);
        let response = self.query_state(&query).await?;
        let response = serde_json::from_slice::<SpentTxResponse>(&response)?.tx;

        match response {
            Some(SpentTx { err: Some(err), .. }) => Ok(TxStatus::Error(err)),
            Some(_) => Ok(TxStatus::Ok),
            None => Ok(TxStatus::NotFound),
        }
    }

    /// Obtain transactions inside a block
    ///
    /// # Errors
    /// This method errors if there was an error while sending the query,
    /// or if the response body is not in JSON format or encoded correctly.
    pub async fn txs_for_block(
        &self,
        block_height: u64,
    ) -> Result<Vec<BlockTransaction>, Error> {
        let query = "query { block(height: ####) { transactions {id, raw, gasSpent, err}}}"
            .replace("####", block_height.to_string().as_str());

        let response = self.query_state(&query).await?;
        let response =
            serde_json::from_slice::<BlockResponse>(&response)?.block;
        let block = response.ok_or(GraphQLError::BlockInfo)?;
        let mut ret = vec![];

        for spent_tx in block.transactions {
            let tx_raw = hex::decode(&spent_tx.raw)
                .map_err(|_| GraphQLError::TxStatus)?;
            let ph_tx = Transaction::from_slice(&tx_raw)
                .map_err(|_| GraphQLError::BytesError)?;
            ret.push(BlockTransaction {
                tx: ph_tx,
                id: spent_tx.id,
                gas_spent: spent_tx.gas_spent,
            });
        }

        Ok(ret)
    }

    /// Sends an empty body to url to check if its available
    ///
    /// # Errors
    /// This method errors if there was an error while sending the query.
    pub async fn check_connection(&self) -> Result<(), Error> {
        match (self.query_state("").await, self.query_archiver("").await) {
            (Ok(_), Ok(_)) => Ok(()),
            (Err(e), _) | (_, Err(e)) => Err(e),
        }
    }

    /// Query the archival node for moonlight transactions given the
    /// `BlsPublicKey`
    ///
    /// # Errors
    /// This method errors if there was an error while sending the query,
    /// or if the response body is not in JSON format or encoded correctly.
    pub async fn moonlight_history(
        &self,
        public_address: Address,
    ) -> Result<FullMoonlightHistory, Error> {
        let query = format!(
            r#"query {{ fullMoonlightHistory(address: "{public_address}") {{ json }} }}"#
        );

        let response = self
            .query_archiver(&query)
            .await
            .map_err(|err| Error::ArchiveJsonError(err.to_string()))?;

        let response =
            serde_json::from_slice::<FullMoonlightHistory>(&response)
                .map_err(|err| Error::ArchiveJsonError(err.to_string()))?;

        Ok(response)
    }

    /// Query the archival node for moonlight transactions of `public_address`
    /// in the given `block`.
    ///
    /// # Errors
    /// This method errors if there was an error while sending the query,
    /// or if the response body is not in JSON format or encoded correctly.
    pub async fn moonlight_history_at_block(
        &self,
        public_address: &Address,
        block: u64,
    ) -> Result<FullMoonlightHistory, Error> {
        let query = format!(
            r#"query {{ fullMoonlightHistory(address: "{public_address}", fromBlock: {block}, toBlock: {block}) {{ json }} }}"#
        );

        let response = self
            .query_archiver(&query)
            .await
            .map_err(|err| Error::ArchiveJsonError(err.to_string()))?;

        let response =
            serde_json::from_slice::<FullMoonlightHistory>(&response)
                .map_err(|err| Error::ArchiveJsonError(err.to_string()))?;

        Ok(response)
    }

    /// Fetch the spent transaction given moonlight tx hash
    ///
    /// # Errors
    /// This method errors if there was an error while sending the query,
    /// or if the response body is not in JSON format or encoded correctly.
    pub async fn moonlight_tx(
        &self,
        origin: &str,
    ) -> Result<Transaction, Error> {
        let query =
            format!(r#"query {{ tx(hash: "{origin}") {{ tx {{ raw }} }} }}"#);

        let response = self.query_state(&query).await?;
        let json: Value = serde_json::from_slice(&response)?;

        let tx = json
            .get("tx")
            .and_then(|val| val.get("tx").and_then(|val| val.get("raw")))
            .and_then(|val| val.as_str());

        if let Some(tx) = tx {
            let hex = hex::decode(tx).map_err(|_| GraphQLError::TxStatus)?;
            let tx: Transaction = Transaction::from_slice(&hex)?;
            Ok(tx)
        } else {
            Err(Error::GraphQLError(GraphQLError::TxStatus))
        }
    }
}

/// Errors generated from GraphQL
#[derive(Debug, thiserror::Error)]
pub enum GraphQLError {
    /// Generic errors
    #[error("Error fetching data from the node: {0}")]
    Generic(serde_json::Error),
    /// Failed to fetch transaction status
    #[error("Failed to obtain transaction status")]
    TxStatus,
    #[error("Failed to obtain block info")]
    /// Failed to obtain block info
    BlockInfo,
    /// Bytes decoding errors
    #[error("A deserialization error occurred")]
    BytesError,
}

impl From<serde_json::Error> for GraphQLError {
    fn from(e: serde_json::Error) -> Self {
        Self::Generic(e)
    }
}

impl GraphQL {
    /// Call the graphql endpoint of a state node
    ///
    /// # Errors
    /// This method errors if there was an error while sending the query,
    /// or if the response body is not in JSON format.
    pub async fn query_state(&self, query: &str) -> Result<Vec<u8>, Error> {
        self.query(&self.state_client, query).await
    }

    /// Call the graphql endpoint of an archiver node
    ///
    /// # Errors
    /// This method errors if there was an error while sending the query,
    /// or if the response body is not in JSON format.
    pub async fn query_archiver(&self, query: &str) -> Result<Vec<u8>, Error> {
        self.query(&self.archiver_client, query).await
    }

    async fn query(
        &self,
        client: &RuesHttpClient,
        query: &str,
    ) -> Result<Vec<u8>, Error> {
        client
            .call("graphql", None, "query", query.as_bytes())
            .await
    }
}

#[ignore = "Leave it here just for manual tests"]
#[tokio::test]
async fn test() -> Result<(), Error> {
    let gql = GraphQL {
        status: |s| {
            println!("{s}");
        },
        state_client: RuesHttpClient::new(
            "http://testnet.nodes.dusk.network:9500/graphql",
        )?,
        archiver_client: RuesHttpClient::new(
            "http://testnet.nodes.dusk.network:9500/graphql",
        )?,
    };
    let _ = gql
        .tx_status(
            "dbc5a2c949516ecfb418406909d195c3cc267b46bd966a3ca9d66d2e13c47003",
        )
        .await?;
    let block_txs = gql.txs_for_block(90).await?;
    block_txs.into_iter().for_each(|tx_block| {
        let tx = tx_block.tx;
        let chain_txid = tx_block.id;
        let hash = tx.hash();
        let tx_id = hex::encode(hash.to_bytes());
        assert_eq!(chain_txid, tx_id);
        println!("txid: {tx_id}");
    });
    Ok(())
}

#[tokio::test]
async fn deser() -> Result<(), Box<dyn std::error::Error>> {
    let block_not_found = r#"{"block":null}"#;
    serde_json::from_str::<BlockResponse>(block_not_found).unwrap();

    let block_without_tx = r#"{"block":{"transactions":[]}}"#;
    serde_json::from_str::<BlockResponse>(block_without_tx).unwrap();

    let block_with_tx = r#"{"block":{"transactions":[{"id":"88e6804989cc2f3fd5bf94dcd39a4e7b7da9a1114d9b8bf4e0515264bc81c50f"}]}}"#;
    serde_json::from_str::<BlockResponse>(block_with_tx).unwrap();

    let empty_full_moonlight_history = r#"{"fullMoonlightHistory":null}"#;
    serde_json::from_str::<FullMoonlightHistory>(empty_full_moonlight_history)
        .unwrap();

    let full_moonlight_history =
        include_str!("./gql/tests/assets/full_moonlight_history.json");
    serde_json::from_str::<FullMoonlightHistory>(full_moonlight_history)
        .unwrap();

    Ok(())
}