Skip to content

Commit

Permalink
Merge pull request #2385 from dusk-network/rusk-wallet-rues
Browse files Browse the repository at this point in the history
  • Loading branch information
herr-seppia authored Sep 13, 2024
2 parents b104aeb + bcad8ce commit e95d7bf
Show file tree
Hide file tree
Showing 8 changed files with 157 additions and 27 deletions.
13 changes: 7 additions & 6 deletions rusk-wallet/src/bin/io/gql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use execution_core::transfer::Transaction;
use tokio::time::{sleep, Duration};

use rusk_wallet::{Error, RuskHttpClient, RuskRequest};
use rusk_wallet::{Error, RuesHttpClient};
use serde::Deserialize;

/// GraphQL is a helper struct that aggregates all queries done
Expand All @@ -16,7 +16,7 @@ use serde::Deserialize;
/// mixed with the wallet logic.
#[derive(Clone)]
pub struct GraphQL {
client: RuskHttpClient,
client: RuesHttpClient,
status: fn(&str),
}

Expand Down Expand Up @@ -59,7 +59,7 @@ impl GraphQL {
S: Into<String>,
{
Self {
client: RuskHttpClient::new(url.into()),
client: RuesHttpClient::new(url.into()),
status,
}
}
Expand Down Expand Up @@ -151,8 +151,9 @@ impl From<serde_json::Error> for GraphQLError {

impl GraphQL {
pub async fn query(&self, query: &str) -> Result<Vec<u8>, Error> {
let request = RuskRequest::new("gql", query.as_bytes().to_vec());
self.client.call(2, "Chain", &request).await
self.client
.call("graphql", None, "query", query.as_bytes())
.await
}
}

Expand All @@ -163,7 +164,7 @@ async fn test() -> Result<(), Box<dyn std::error::Error>> {
status: |s| {
println!("{s}");
},
client: RuskHttpClient::new(
client: RuesHttpClient::new(
"http://nodes.dusk.network:9500/graphql".to_string(),
),
};
Expand Down
31 changes: 20 additions & 11 deletions rusk-wallet/src/clients.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use execution_core::{
use execution_core::transfer::phoenix::{Note, NoteLeaf};

use flume::Receiver;
use rues::RuesHttpClient;
use tokio::time::{sleep, Duration};
use wallet_core::{
keys::{derive_phoenix_pk, derive_phoenix_sk, derive_phoenix_vk},
Expand Down Expand Up @@ -66,7 +67,7 @@ impl Prove for Prover {
pub struct State {
cache: Mutex<Arc<Cache>>,
status: fn(&str),
client: RuskHttpClient,
client: RuesHttpClient,
prover: RuskHttpClient,
store: LocalStore,
pub sync_rx: Option<Receiver<String>>,
Expand All @@ -77,7 +78,7 @@ impl State {
pub(crate) fn new(
data_dir: &Path,
status: fn(&str),
client: RuskHttpClient,
client: RuesHttpClient,
prover: RuskHttpClient,
store: LocalStore,
) -> Result<Self, Error> {
Expand Down Expand Up @@ -171,13 +172,17 @@ impl State {
let tx_bytes = tx.to_var_bytes();

status("Attempt to preverify tx...");
let preverify_req = RuskRequest::new("preverify", tx_bytes.clone());
let _ = self.client.call(2, "rusk", &preverify_req).wait()?;
let _ = self
.client
.call("transactions", None, "preverify", &tx_bytes)
.wait()?;
status("Preverify success!");

status("Propagating tx...");
let propagate_req = RuskRequest::new("propagate_tx", tx_bytes);
let _ = self.client.call(2, "Chain", &propagate_req).wait()?;
let _ = self
.client
.call("transactions", None, "propagate", &tx_bytes)
.wait()?;
status("Transaction propagated!");

Ok(tx)
Expand Down Expand Up @@ -229,7 +234,7 @@ impl State {

let account = self
.client
.contract_query::<_, 1024>(TRANSFER_CONTRACT, "account", pk)
.contract_query::<_, _, 1024>(TRANSFER_CONTRACT, "account", pk)
.wait()?;
let account = rkyv::from_bytes(&account).map_err(|_| Error::Rkyv)?;
status("account-data received!");
Expand Down Expand Up @@ -260,7 +265,7 @@ impl State {

let root = self
.client
.contract_query::<(), 0>(TRANSFER_CONTRACT, "root", &())
.contract_query::<(), _, 0>(TRANSFER_CONTRACT, "root", &())
.wait()?;
status("root received!");
let root = rkyv::from_bytes(&root).map_err(|_| Error::Rkyv)?;
Expand All @@ -277,7 +282,7 @@ impl State {

let data = self
.client
.contract_query::<_, 1024>(STAKE_CONTRACT, "get_stake", pk)
.contract_query::<_, _, 1024>(STAKE_CONTRACT, "get_stake", pk)
.wait()?;

let res: Option<StakeData> =
Expand All @@ -301,7 +306,7 @@ impl State {

let data = self
.client
.contract_query::<_, { u8::SIZE }>(
.contract_query::<_, _, { u8::SIZE }>(
TRANSFER_CONTRACT,
"chain_id",
&(),
Expand All @@ -321,7 +326,11 @@ impl State {

let data = self
.client
.contract_query::<_, 1024>(TRANSFER_CONTRACT, "opening", note.pos())
.contract_query::<_, _, 1024>(
TRANSFER_CONTRACT,
"opening",
note.pos(),
)
.wait()?;

status("Opening notes received!");
Expand Down
15 changes: 8 additions & 7 deletions rusk-wallet/src/clients/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,18 @@
use std::mem::size_of;

use futures::StreamExt;
use rues::CONTRACTS_TARGET;

use crate::block::Block;
use crate::clients::{Cache, TRANSFER_CONTRACT};
use crate::rusk::RuskHttpClient;
use crate::{Error, RuskRequest};
use crate::Error;

use super::*;

const TREE_LEAF: usize = size_of::<ArchivedNoteLeaf>();

pub(crate) async fn sync_db(
client: &RuskHttpClient,
client: &RuesHttpClient,
cache: &Cache,
store: &LocalStore,
status: fn(&str),
Expand Down Expand Up @@ -51,9 +51,10 @@ pub(crate) async fn sync_db(

let mut stream = client
.call_raw(
1,
CONTRACTS_TARGET,
TRANSFER_CONTRACT,
&RuskRequest::new("leaves_from_pos", req),
"leaves_from_pos",
&req,
true,
)
.await?
Expand Down Expand Up @@ -128,15 +129,15 @@ pub(crate) async fn sync_db(
/// Asks the node to return the nullifiers that already exist from the given
/// nullifiers.
pub(crate) async fn fetch_existing_nullifiers_remote(
client: &RuskHttpClient,
client: &RuesHttpClient,
nullifiers: &[BlsScalar],
) -> Result<Vec<BlsScalar>, Error> {
if nullifiers.is_empty() {
return Ok(vec![]);
}
let nullifiers = nullifiers.to_vec();
let data = client
.contract_query::<_, 1024>(
.contract_query::<_, _, 1024>(
TRANSFER_CONTRACT,
"existing_nullifiers",
&nullifiers,
Expand Down
2 changes: 2 additions & 0 deletions rusk-wallet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,15 @@ mod cache;
mod clients;
mod crypto;
mod error;
mod rues;
mod rusk;
mod store;
mod wallet;

/// Methods for parsing/checking the DAT wallet file
pub mod dat;

pub use rues::RuesHttpClient;
pub use rusk::{RuskHttpClient, RuskRequest};

pub use error::Error;
Expand Down
118 changes: 118 additions & 0 deletions rusk-wallet/src/rues.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
// 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.

use reqwest::{Body, Response};
use rkyv::Archive;

use crate::Error;

/// Supported Rusk version
const REQUIRED_RUSK_VERSION: &str = ">=0.8.0";

/// Target for contracts
pub const CONTRACTS_TARGET: &str = "contracts";

#[derive(Clone)]
/// Rusk HTTP Binary Client
pub struct RuesHttpClient {
uri: String,
}

impl RuesHttpClient {
/// Create a new HTTP Client
pub fn new(uri: String) -> Self {
Self { uri }
}

/// Utility for querying the rusk VM
pub async fn contract_query<I, C, const N: usize>(
&self,
contract: C,
method: &str,
value: &I,
) -> Result<Vec<u8>, Error>
where
I: Archive,
I: rkyv::Serialize<rkyv::ser::serializers::AllocSerializer<N>>,
C: Into<Option<&'static str>>,
{
let data = rkyv::to_bytes(value).map_err(|_| Error::Rkyv)?.to_vec();

let response = self
.call_raw(CONTRACTS_TARGET, contract.into(), method, &data, false)
.await?;

Ok(response.bytes().await?.to_vec())
}

/// Check rusk connection
pub async fn check_connection(&self) -> Result<(), reqwest::Error> {
reqwest::Client::new().post(&self.uri).send().await?;
Ok(())
}

/// Send a RuskRequest to a specific target.
///
/// The response is interpreted as Binary
pub async fn call<E>(
&self,
target: &str,
entity: E,
topic: &str,
request: &[u8],
) -> Result<Vec<u8>, Error>
where
E: Into<Option<&'static str>>,
{
let response =
self.call_raw(target, entity, topic, request, false).await?;
let data = response.bytes().await?;
Ok(data.to_vec())
}

/// Send a RuskRequest to a specific target without parsing the response
pub async fn call_raw<E>(
&self,
target: &str,
entity: E,
topic: &str,
data: &[u8],
feed: bool,
) -> Result<Response, Error>
where
E: Into<Option<&'static str>>,
{
let uri = &self.uri;
let client = reqwest::Client::new();
let entity = entity.into().map(|e| format!(":{e}")).unwrap_or_default();

let rues_prefix = if uri.ends_with('/') { "on" } else { "/on" };
let mut request = client
.post(format!("{uri}{rues_prefix}/{target}{entity}/{topic}"))
.body(Body::from(data.to_vec()))
.header("Content-Type", "application/octet-stream")
.header("rusk-version", REQUIRED_RUSK_VERSION);

if feed {
request = request.header("Rusk-Feeder", "1");
}
let response = request.send().await?;

let status = response.status();
if status.is_client_error() || status.is_server_error() {
let error = &response.bytes().await?;

let error = String::from_utf8(error.to_vec())
.unwrap_or("unparsable error".into());

let msg = format!("{status}: {error}");

Err(Error::Rusk(msg))
} else {
Ok(response)
}
}
}
1 change: 0 additions & 1 deletion rusk-wallet/src/rusk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,5 +125,4 @@ impl RuskHttpClient {
Ok(response)
}
}

}
3 changes: 2 additions & 1 deletion rusk-wallet/src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use dusk_bytes::Serializable;
use rand::rngs::StdRng;
use rand::SeedableRng;

use rues::RuesHttpClient;
use serde::Serialize;
use std::fmt::Debug;
use std::fs;
Expand Down Expand Up @@ -266,7 +267,7 @@ impl<F: SecureWalletFile + Debug> Wallet<F> {
S: Into<String>,
{
// attempt connection
let http_state = RuskHttpClient::new(rusk_addr.into());
let http_state = RuesHttpClient::new(rusk_addr.into());
let http_prover = RuskHttpClient::new(prov_addr.into());

let state_status = http_state.check_connection().await;
Expand Down
1 change: 0 additions & 1 deletion rusk/src/lib/http/rusk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ impl HandleRequest for Rusk {
&self,
request: &RuesDispatchEvent,
) -> anyhow::Result<ResponseData> {
info!("received event {request:?}");
match request.uri.inner() {
("contracts", Some(contract_id), method) => {
let feeder = request.header(RUSK_FEEDER_HEADER).is_some();
Expand Down

0 comments on commit e95d7bf

Please sign in to comment.