Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Port rusk-wallet to new wallet-core #2219

Merged
merged 2 commits into from
Sep 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 9 additions & 17 deletions rusk-wallet/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "dusk-wallet"
version = "0.22.1"
name = "rusk-wallet"
version = "0.1.0"
edition = "2021"
autobins = false
description = "A library providing functionalities to create wallets compatible with Dusk Network"
Expand Down Expand Up @@ -32,7 +32,6 @@ requestty = "0.5.0"
futures = "0.3"
base64 = "0.13"
crypto = "0.3"
whoami = "1.2"
blake3 = "1.3"
sha2 = "0.10.7"
toml = "0.5"
Expand All @@ -44,24 +43,17 @@ aes = "0.7"
rocksdb = "0.22"
flume = "0.10.14"
reqwest = { version = "0.11", features = ["stream"] }

dusk-wallet-core = "0.24.0-plonk.0.16-rc.2"
dusk-bytes = "0.1"
dusk-pki = "0.13"
rusk-abi = { version = "0.12.0-rc", default-features = false }
phoenix-core = { version = "0.21", features = ["alloc"] }
dusk-schnorr = { version = "0.14", default-features = false }
dusk-poseidon = "0.31"
dusk-plonk = "0.16"
dusk-bls12_381-sign = { version = "0.5", default-features = false }
ff = { version = "0.13", default-features = false }
poseidon-merkle = "0.3"

zeroize = { version = "1", default-features = false, features = ["derive"] }
wallet-core = { path = "../wallet-core" }
execution-core = { path = "../execution-core" }

tracing = "0.1"
tracing-subscriber = { version = "0.3.0", features = [
"fmt",
"env-filter",
"json",
"fmt",
"env-filter",
"json",
] }

rkyv = { version = "=0.7.39", default-features = false }
Expand Down
40 changes: 22 additions & 18 deletions rusk-wallet/src/bin/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,19 @@
mod history;

use clap::Subcommand;
use dusk_plonk::prelude::BlsScalar;
use rusk_abi::hash::Hasher;
use std::{fmt, path::PathBuf};

use crate::io::prompt;
use crate::settings::Settings;
use crate::{WalletFile, WalletPath};

use dusk_wallet::gas::{Gas, DEFAULT_LIMIT, DEFAULT_PRICE};
use dusk_wallet::{Address, Dusk, Lux, Wallet, EPOCH, MAX_ADDRESSES};
use dusk_wallet_core::{BalanceInfo, StakeInfo};
use execution_core::{stake::StakeData, BlsScalar};
use rusk_wallet::{
currency::{Dusk, Lux},
gas::{Gas, DEFAULT_LIMIT, DEFAULT_PRICE},
Address, Error, Wallet, EPOCH, MAX_ADDRESSES,
};
use wallet_core::BalanceInfo;

pub use history::TransactionHistory;

Expand Down Expand Up @@ -230,7 +232,7 @@ impl Command {
let gas = Gas::new(gas_limit).with_price(gas_price);

let tx = wallet.transfer(sender, &rcvr, amt, gas).await?;
Ok(RunResult::Tx(Hasher::digest(tx.to_hash_input_bytes())))
Ok(RunResult::Tx(tx.hash()))
}
Command::Stake {
addr,
Expand All @@ -246,14 +248,16 @@ impl Command {
let gas = Gas::new(gas_limit).with_price(gas_price);

let tx = wallet.stake(addr, amt, gas).await?;
Ok(RunResult::Tx(Hasher::digest(tx.to_hash_input_bytes())))
Ok(RunResult::Tx(tx.hash()))
}
Command::StakeInfo { addr, reward } => {
let addr = match addr {
Some(addr) => wallet.claim_as_address(addr)?,
None => wallet.default_address(),
};
let si = wallet.stake_info(addr).await?;
let si =
wallet.stake_info(addr).await?.ok_or(Error::NotStaked)?;

Ok(RunResult::StakeInfo(si, reward))
}
Command::Unstake {
Expand All @@ -270,7 +274,7 @@ impl Command {
let gas = Gas::new(gas_limit).with_price(gas_price);

let tx = wallet.unstake(addr, gas).await?;
Ok(RunResult::Tx(Hasher::digest(tx.to_hash_input_bytes())))
Ok(RunResult::Tx(tx.hash()))
}
Command::Withdraw {
addr,
Expand All @@ -286,7 +290,7 @@ impl Command {
let gas = Gas::new(gas_limit).with_price(gas_price);

let tx = wallet.withdraw_reward(addr, gas).await?;
Ok(RunResult::Tx(Hasher::digest(tx.to_hash_input_bytes())))
Ok(RunResult::Tx(tx.hash()))
}
Command::Export { addr, dir, name } => {
let addr = match addr {
Expand Down Expand Up @@ -329,7 +333,7 @@ impl Command {
pub enum RunResult {
Tx(BlsScalar),
Balance(BalanceInfo, bool),
StakeInfo(StakeInfo, bool),
StakeInfo(StakeData, bool),
Address(Box<Address>),
Addresses(Vec<Address>),
ExportedKeys(PathBuf, PathBuf),
Expand Down Expand Up @@ -366,21 +370,21 @@ impl fmt::Display for RunResult {
let hash = hex::encode(hash.to_bytes());
write!(f, "> Transaction sent: {hash}",)
}
StakeInfo(si, _) => {
let stake_str = match si.amount {
Some((value, eligibility)) => format!(
StakeInfo(data, _) => {
let stake_str = match data.amount {
Some(amt) => format!(
"Current stake amount is: {} DUSK\n> Stake eligibility from block #{} (Epoch {})",
Dusk::from(value),
eligibility,
eligibility / EPOCH
Dusk::from(amt.value),
amt.eligibility,
amt.eligibility / EPOCH
),
None => "No active stake found for this key".to_string(),
};
write!(
f,
"> {}\n> Accumulated reward is: {} DUSK",
stake_str,
Dusk::from(si.reward)
Dusk::from(data.reward)
)
}
ExportedKeys(pk, kp) => {
Expand Down
19 changes: 10 additions & 9 deletions rusk-wallet/src/bin/command/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::fmt::{self, Display};

use dusk_wallet::DecodedNote;
use dusk_wallet_core::Transaction;
use rusk_abi::dusk;
use rusk_wallet::DecodedNote;

use execution_core::{dusk, from_dusk, transfer::Transaction};

use crate::io::{self, GraphQL};
use crate::settings::Settings;
Expand All @@ -35,17 +35,17 @@ impl TransactionHistory {

impl Display for TransactionHistory {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let dusk = self.amount / dusk::dusk(1.0) as f64;
let dusk = self.amount / dusk(1.0) as f64;
let contract = match self.tx.call() {
None => "transfer",
Some((_, method, _)) => method,
Some(call) => &call.fn_name,
};

let fee = match self.direction {
TransactionDirection::In => "".into(),
TransactionDirection::Out => {
let fee = self.fee;
let fee = dusk::from_dusk(fee);
let fee = from_dusk(fee);
format!("{: >12.9}", fee)
}
};
Expand Down Expand Up @@ -95,8 +95,8 @@ pub(crate) async fn transaction_from_notes(
let note_hash = decoded_note.note.hash();
// Looking for the transaction which created the note
let note_creator = txs.iter().find(|(t, _, _)| {
t.outputs().iter().any(|&n| n.hash().eq(&note_hash))
|| t.nullifiers
t.outputs().iter().any(|n| n.hash().eq(&note_hash))
|| t.nullifiers()
.iter()
.any(|tx_null| nullifiers.iter().any(|(n, _)| n == tx_null))
});
Expand All @@ -114,13 +114,14 @@ pub(crate) async fn transaction_from_notes(
true => TransactionDirection::Out,
false => TransactionDirection::In,
};

match ret.iter_mut().find(|th| &th.id == tx_id) {
Some(tx) => tx.amount += note_amount,
None => ret.push(TransactionHistory {
direction,
height: decoded_note.block_height,
amount: note_amount - inputs_amount,
fee: gas_spent * t.fee().gas_price,
fee: gas_spent * t.gas_price(),
tx: t.clone(),
id: tx_id.clone(),
}),
Expand Down
12 changes: 7 additions & 5 deletions rusk-wallet/src/bin/interactive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
// Copyright (c) DUSK NETWORK. All rights reserved.

use bip39::{Language, Mnemonic, MnemonicType};
use dusk_wallet::dat::{DatFileVersion, LATEST_VERSION};
use dusk_wallet::gas;
use dusk_wallet::{Address, Dusk, Error, Wallet, WalletPath, MAX_ADDRESSES};
use requestty::Question;
use rusk_wallet::{
currency::Dusk,
dat::{DatFileVersion, LATEST_VERSION},
gas, Address, Error, Wallet, WalletPath, MAX_ADDRESSES,
};

use crate::command::DEFAULT_STAKE_GAS_LIMIT;
use crate::io;
Expand Down Expand Up @@ -68,7 +70,7 @@ pub(crate) async fn run_loop(
// get balance for this address
prompt::hide_cursor()?;
let balance = wallet.get_balance(&addr).await?;
let spendable: Dusk = balance.spendable.into();
let spendable = balance.spendable.into();
let total: Dusk = balance.value.into();
prompt::hide_cursor()?;

Expand Down Expand Up @@ -159,7 +161,7 @@ fn menu_addr(wallet: &Wallet<WalletFile>) -> anyhow::Result<AddrSelect> {
));
}

if let Some(rx) = &wallet.sync_rx {
if let Some(rx) = &wallet.state()?.sync_rx {
if let Ok(status) = rx.try_recv() {
action_menu = action_menu
.separator()
Expand Down
17 changes: 7 additions & 10 deletions rusk-wallet/src/bin/io/gql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
//
// Copyright (c) DUSK NETWORK. All rights reserved.

use dusk_wallet_core::Transaction;
use execution_core::transfer::Transaction;
use tokio::time::{sleep, Duration};

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

/// GraphQL is a helper struct that aggregates all queries done
Expand Down Expand Up @@ -129,16 +129,16 @@ impl GraphQL {
pub enum GraphQLError {
/// Generic errors
#[error("Error fetching data from the node: {0}")]
Generic(dusk_wallet::Error),
Generic(Error),
/// Failed to fetch transaction status
#[error("Failed to obtain transaction status")]
TxStatus,
#[error("Failed to obtain block info")]
BlockInfo,
}

impl From<dusk_wallet::Error> for GraphQLError {
fn from(e: dusk_wallet::Error) -> Self {
impl From<Error> for GraphQLError {
fn from(e: Error) -> Self {
Self::Generic(e)
}
}
Expand All @@ -150,10 +150,7 @@ impl From<serde_json::Error> for GraphQLError {
}

impl GraphQL {
pub async fn query(
&self,
query: &str,
) -> Result<Vec<u8>, dusk_wallet::Error> {
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
}
Expand All @@ -177,7 +174,7 @@ async fn test() -> Result<(), Box<dyn std::error::Error>> {
.await?;
let block_txs = gql.txs_for_block(90).await?;
block_txs.into_iter().for_each(|(t, chain_txid, _)| {
let hash = rusk_abi::hash::Hasher::digest(t.to_hash_input_bytes());
let hash = t.hash();
let tx_id = hex::encode(hash.to_bytes());
assert_eq!(chain_txid, tx_id);
println!("txid: {tx_id}");
Expand Down
12 changes: 7 additions & 5 deletions rusk-wallet/src/bin/io/prompt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,14 @@ use crossterm::{

use anyhow::Result;
use bip39::{ErrorKind, Language, Mnemonic};
use dusk_wallet::{dat::DatFileVersion, Error};
use requestty::Question;

use dusk_wallet::{Address, Dusk, Lux};

use dusk_wallet::gas;
use dusk_wallet::{MAX_CONVERTIBLE, MIN_CONVERTIBLE};
use rusk_wallet::gas;
use rusk_wallet::{
currency::{Dusk, Lux},
dat::DatFileVersion,
Address, Error, MAX_CONVERTIBLE, MIN_CONVERTIBLE,
};
use sha2::{Digest, Sha256};

/// Request the user to authenticate with a password
Expand Down Expand Up @@ -244,6 +245,7 @@ pub(crate) fn request_token_amt(
.build();

let a = requestty::prompt_one(question)?;

Ok(a.as_float().expect("answer to be a float").into())
}

Expand Down
14 changes: 8 additions & 6 deletions rusk-wallet/src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ mod menu;
mod settings;

pub(crate) use command::{Command, RunResult};
use dusk_wallet::dat::LATEST_VERSION;
pub(crate) use menu::Menu;

use clap::Parser;
Expand All @@ -25,8 +24,11 @@ use bip39::{Language, Mnemonic, MnemonicType};
use crate::command::TransactionHistory;
use crate::settings::{LogFormat, Settings};

use dusk_wallet::{dat, Error};
use dusk_wallet::{Dusk, SecureWalletFile, Wallet, WalletPath};
use rusk_wallet::{currency::Dusk, SecureWalletFile, Wallet, WalletPath};
use rusk_wallet::{
dat::{self, LATEST_VERSION},
Error,
};

use config::Config;
use io::{prompt, status};
Expand Down Expand Up @@ -83,7 +85,7 @@ where

// check for connection errors
match con {
Err(Error::RocksDB(e)) => panic!{"Invalid cache {e}"},
Err(Error::RocksDB(e)) => panic!{"Please reset the cache! {e}"},
Err(e) => warn!("[OFFLINE MODE]: Unable to connect to Rusk, limited functionality available: {e}"),
_ => {}
}
Expand Down Expand Up @@ -121,7 +123,7 @@ async fn exec() -> anyhow::Result<()> {
// Finally complete the settings by setting the network
let settings = settings_builder
.network(cfg.network)
.map_err(|_| dusk_wallet::Error::NetworkNotFound)?;
.map_err(|_| rusk_wallet::Error::NetworkNotFound)?;

// generate a subscriber with the desired log level
//
Expand Down Expand Up @@ -314,7 +316,7 @@ async fn exec() -> anyhow::Result<()> {
println!("{}", Dusk::from(info.reward));
} else {
let staked_amount = match info.amount {
Some((staked, ..)) => staked,
Some(info) => info.value,
None => 0,
};
println!("{}", Dusk::from(staked_amount));
Expand Down
2 changes: 1 addition & 1 deletion rusk-wallet/src/bin/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use crate::config::Network;
use crate::io::WalletArgs;

use dusk_wallet::Error;
use rusk_wallet::Error;
use std::fmt;
use std::path::PathBuf;

Expand Down
Loading
Loading