diff --git a/rusk-wallet/src/bin/command.rs b/rusk-wallet/src/bin/command.rs index 5c26127ec3..1c8e39d2d2 100644 --- a/rusk-wallet/src/bin/command.rs +++ b/rusk-wallet/src/bin/command.rs @@ -48,8 +48,8 @@ pub(crate) enum Command { file: Option, }, - /// Check your current balance - Balance { + /// Check your current phoenix balance + PhoenixBalance { /// Address #[clap(short, long)] addr: Option
, @@ -59,6 +59,13 @@ pub(crate) enum Command { spendable: bool, }, + /// Check your current moonlight balance + MoonlightBalance { + /// Address + #[clap(short, long)] + addr: Option
, + }, + /// List your existing addresses and generate new ones Addresses { /// Create new address @@ -67,19 +74,42 @@ pub(crate) enum Command { }, /// Show address transaction history - History { + PhoenixHistory { /// Address for which you want to see the history #[clap(short, long)] addr: Option
, }, - /// Send DUSK through the network - Transfer { - /// Address from which to send DUSK [default: first address] + /// Send DUSK privately through the network using Phoenix + PhoenixTransfer { + /// Phoenix Address from which to send DUSK [default: first address] + #[clap(short, long)] + sndr: Option
, + + /// Phoenix Receiver address + #[clap(short, long)] + rcvr: Address, + + /// Amount of DUSK to send + #[clap(short, long)] + amt: Dusk, + + /// Max amt of gas for this transaction + #[clap(short = 'l', long, default_value_t= DEFAULT_LIMIT)] + gas_limit: u64, + + /// Price you're going to pay for each gas unit (in LUX) + #[clap(short = 'p', long, default_value_t= DEFAULT_PRICE)] + gas_price: Lux, + }, + + /// Send DUSK through the network using moonlight + MoonlightTransfer { + /// Bls Address from which to send DUSK [default: first address] #[clap(short, long)] sndr: Option
, - /// Receiver address + /// Bls Receiver address #[clap(short, long)] rcvr: Address, @@ -96,9 +126,9 @@ pub(crate) enum Command { gas_price: Lux, }, - /// Start staking DUSK - Stake { - /// Address from which to stake DUSK [default: first address] + /// Start staking DUSK through phoenix + PhoenixStake { + /// Phoenix Address from which to stake DUSK [default: first address] #[clap(short = 's', long)] addr: Option
, @@ -126,9 +156,10 @@ pub(crate) enum Command { reward: bool, }, - /// Unstake a key's stake - Unstake { - /// Address from which your DUSK was staked [default: first address] + /// Phoeinx Unstake a key's stake + PhoenixUnstake { + /// Phoenix Address from which your DUSK was staked [default: first + /// address] #[clap(short, long)] addr: Option
, @@ -141,9 +172,10 @@ pub(crate) enum Command { gas_price: Lux, }, - /// Withdraw accumulated reward for a stake key - Withdraw { - /// Address from which your DUSK was staked [default: first address] + /// Phoenix Withdraw accumulated reward for a stake key + PhoenixWithdraw { + /// Phoenix Address from which your DUSK was staked [default: first + /// address] #[clap(short, long)] addr: Option
, @@ -184,7 +216,7 @@ impl Command { settings: &Settings, ) -> anyhow::Result { match self { - Command::Balance { addr, spendable } => { + Command::PhoenixBalance { addr, spendable } => { let sync_result = wallet.sync().await; if let Err(e) = sync_result { // Sync error should be reported only if wallet is online @@ -198,8 +230,18 @@ impl Command { None => wallet.default_address(), }; - let balance = wallet.get_balance(addr).await?; - Ok(RunResult::Balance(balance, spendable)) + let balance = wallet.get_phoenix_balance(addr).await?; + Ok(RunResult::PhoenixBalance(balance, spendable)) + } + Command::MoonlightBalance { addr } => { + let addr = match addr { + Some(addr) => wallet.claim_as_address(addr)?, + None => wallet.default_address(), + }; + + Ok(RunResult::MoonlightBalance( + wallet.get_moonlight_balance(addr)?, + )) } Command::Addresses { new } => { if new { @@ -217,7 +259,7 @@ impl Command { Ok(RunResult::Addresses(wallet.addresses().clone())) } } - Command::Transfer { + Command::PhoenixTransfer { sndr, rcvr, amt, @@ -235,18 +277,36 @@ impl Command { wallet.phoenix_transfer(sender, &rcvr, amt, gas).await?; Ok(RunResult::Tx(tx.hash())) } - Command::Stake { + Command::MoonlightTransfer { + sndr, + rcvr, + amt, + gas_limit, + gas_price, + } => { + let gas = Gas::new(gas_limit).with_price(gas_price); + let sender = match sndr { + Some(addr) => wallet.claim_as_address(addr)?, + None => wallet.default_address(), + }; + + let tx = + wallet.moonlight_transfer(sender, &rcvr, amt, gas).await?; + + Ok(RunResult::Tx(tx.hash())) + } + Command::PhoenixStake { addr, amt, gas_limit, gas_price, } => { wallet.sync().await?; + let gas = Gas::new(gas_limit).with_price(gas_price); let addr = match addr { Some(addr) => wallet.claim_as_address(addr)?, None => wallet.default_address(), }; - let gas = Gas::new(gas_limit).with_price(gas_price); let tx = wallet.phoenix_stake(addr, amt, gas).await?; Ok(RunResult::Tx(tx.hash())) @@ -257,13 +317,13 @@ impl Command { None => wallet.default_address(), }; let si = wallet - .stake_info(addr.index) + .stake_info(addr.index()?) .await? .ok_or(Error::NotStaked)?; Ok(RunResult::StakeInfo(si, reward)) } - Command::Unstake { + Command::PhoenixUnstake { addr, gas_limit, gas_price, @@ -279,7 +339,7 @@ impl Command { let tx = wallet.phoenix_unstake(addr, gas).await?; Ok(RunResult::Tx(tx.hash())) } - Command::Withdraw { + Command::PhoenixWithdraw { addr, gas_limit, gas_price, @@ -312,7 +372,7 @@ impl Command { Ok(RunResult::ExportedKeys(pub_key, key_pair)) } - Command::History { addr } => { + Command::PhoenixHistory { addr } => { wallet.sync().await?; let addr = match addr { Some(addr) => wallet.claim_as_address(addr)?, @@ -323,7 +383,7 @@ impl Command { let transactions = history::transaction_from_notes(settings, notes).await?; - Ok(RunResult::History(transactions)) + Ok(RunResult::PhoenixHistory(transactions)) } Command::Create { .. } => Ok(RunResult::Create()), Command::Restore { .. } => Ok(RunResult::Restore()), @@ -335,7 +395,8 @@ impl Command { /// Possible results of running a command in interactive mode pub enum RunResult { Tx(BlsScalar), - Balance(BalanceInfo, bool), + PhoenixBalance(BalanceInfo, bool), + MoonlightBalance(Dusk), StakeInfo(StakeData, bool), Address(Box
), Addresses(Vec
), @@ -343,21 +404,24 @@ pub enum RunResult { Create(), Restore(), Settings(), - History(Vec), + PhoenixHistory(Vec), } impl fmt::Display for RunResult { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use RunResult::*; match self { - Balance(balance, _) => { + PhoenixBalance(balance, _) => { write!( f, - "> Total balance is: {} DUSK\n> Maximum spendable per TX is: {} DUSK", + "> Total Phoenix balance is: {} DUSK\n> Maximum spendable per TX is: {} DUSK", Dusk::from(balance.value), Dusk::from(balance.spendable) ) } + MoonlightBalance(balance) => { + write!(f, "> Total Moonlight balance is: {} DUSK", balance) + } Address(addr) => { write!(f, "> {}", addr) } @@ -398,7 +462,7 @@ impl fmt::Display for RunResult { kp.display() ) } - History(transactions) => { + PhoenixHistory(transactions) => { writeln!(f, "{}", TransactionHistory::header())?; for th in transactions { writeln!(f, "{th}")?; diff --git a/rusk-wallet/src/bin/interactive.rs b/rusk-wallet/src/bin/interactive.rs index 07f35cea34..a6befe3ab0 100644 --- a/rusk-wallet/src/bin/interactive.rs +++ b/rusk-wallet/src/bin/interactive.rs @@ -66,17 +66,30 @@ pub(crate) async fn run_loop( AddrSelect::Exit => std::process::exit(0), }; + let index = addr.index()?; + + let moonlight = Address::Bls { + index: Some(index), + addr: wallet.bls_public_key(addr.index()?), + }; + loop { // get balance for this address prompt::hide_cursor()?; - let balance = wallet.get_balance(&addr).await?; - let spendable = balance.spendable.into(); - let total: Dusk = balance.value.into(); + let phoenix_bal = wallet.get_phoenix_balance(&addr).await?; + let moonlight_bal = wallet.get_moonlight_balance(&moonlight)?; + let spendable = phoenix_bal.spendable.into(); + let total: Dusk = phoenix_bal.value.into(); + prompt::hide_cursor()?; // display address information println!(); - println!("Address: {addr}"); + println!("Moonlight Address: {moonlight}"); + println!("Balance:"); + println!(" - Total: {moonlight_bal}"); + println!(); + println!("Phoenix Address: {addr}"); println!("Balance:"); println!(" - Spendable: {spendable}"); println!(" - Total: {total}"); @@ -193,12 +206,13 @@ enum AddrOp { #[derive(PartialEq, Eq, Hash, Clone, Debug)] enum CommandMenuItem { - History, - Transfer, - Stake, + PhoenixHistory, + PhoenixTransfer, + MoonlightTransfer, + PhoenixStake, StakeInfo, - Unstake, - Withdraw, + PhoenixUnstake, + PhoenixWithdraw, Export, Back, } @@ -213,12 +227,13 @@ fn menu_op( use CommandMenuItem as CMI; let cmd_menu = Menu::new() - .add(CMI::History, "Transaction History") - .add(CMI::Transfer, "Transfer Dusk") - .add(CMI::Stake, "Stake Dusk") + .add(CMI::PhoenixHistory, "Phoenix Transaction History") + .add(CMI::PhoenixTransfer, "Phoenix Transfer Dusk") + .add(CMI::MoonlightTransfer, "Moonlight Transfer Dusk") + .add(CMI::PhoenixStake, "Phoenix Stake Dusk") .add(CMI::StakeInfo, "Check existing stake") - .add(CMI::Unstake, "Unstake Dusk") - .add(CMI::Withdraw, "Withdraw staking reward") + .add(CMI::PhoenixUnstake, "Phoenix Unstake Dusk") + .add(CMI::PhoenixWithdraw, "Phoenix Withdraw staking reward") .add(CMI::Export, "Export provisioner key-pair") .separator() .add(CMI::Back, "Back"); @@ -232,17 +247,28 @@ fn menu_op( let cmd = cmd_menu.answer(&answer).to_owned(); let res = match cmd { - CMI::History => { - AddrOp::Run(Box::new(Command::History { addr: Some(addr) })) + CMI::PhoenixHistory => { + AddrOp::Run(Box::new(Command::PhoenixHistory { addr: Some(addr) })) } - CMI::Transfer => AddrOp::Run(Box::new(Command::Transfer { - sndr: Some(addr), - rcvr: prompt::request_rcvr_addr("recipient")?, - amt: prompt::request_token_amt("transfer", balance)?, - gas_limit: prompt::request_gas_limit(gas::DEFAULT_LIMIT)?, - gas_price: prompt::request_gas_price()?, - })), - CMI::Stake => AddrOp::Run(Box::new(Command::Stake { + CMI::PhoenixTransfer => { + AddrOp::Run(Box::new(Command::PhoenixTransfer { + sndr: Some(addr), + rcvr: prompt::request_rcvr_addr("recipient")?, + amt: prompt::request_token_amt("transfer", balance)?, + gas_limit: prompt::request_gas_limit(gas::DEFAULT_LIMIT)?, + gas_price: prompt::request_gas_price()?, + })) + } + CMI::MoonlightTransfer => { + AddrOp::Run(Box::new(Command::MoonlightTransfer { + sndr: Some(addr), + rcvr: prompt::request_rcvr_addr("recipient")?, + amt: prompt::request_token_amt("transfer", balance)?, + gas_limit: prompt::request_gas_limit(gas::DEFAULT_LIMIT)?, + gas_price: prompt::request_gas_price()?, + })) + } + CMI::PhoenixStake => AddrOp::Run(Box::new(Command::PhoenixStake { addr: Some(addr), amt: prompt::request_token_amt("stake", balance)?, gas_limit: prompt::request_gas_limit(DEFAULT_STAKE_GAS_LIMIT)?, @@ -252,16 +278,18 @@ fn menu_op( addr: Some(addr), reward: false, })), - CMI::Unstake => AddrOp::Run(Box::new(Command::Unstake { - addr: Some(addr), - gas_limit: prompt::request_gas_limit(DEFAULT_STAKE_GAS_LIMIT)?, - gas_price: prompt::request_gas_price()?, - })), - CMI::Withdraw => AddrOp::Run(Box::new(Command::Withdraw { + CMI::PhoenixUnstake => AddrOp::Run(Box::new(Command::PhoenixUnstake { addr: Some(addr), gas_limit: prompt::request_gas_limit(DEFAULT_STAKE_GAS_LIMIT)?, gas_price: prompt::request_gas_price()?, })), + CMI::PhoenixWithdraw => { + AddrOp::Run(Box::new(Command::PhoenixWithdraw { + addr: Some(addr), + gas_limit: prompt::request_gas_limit(DEFAULT_STAKE_GAS_LIMIT)?, + gas_price: prompt::request_gas_price()?, + })) + } CMI::Export => AddrOp::Run(Box::new(Command::Export { addr: Some(addr), name: None, @@ -429,7 +457,22 @@ fn menu_wallet(wallet_found: Option) -> anyhow::Result { /// Request user confirmation for a transfer transaction fn confirm(cmd: &Command) -> anyhow::Result { match cmd { - Command::Transfer { + Command::PhoenixTransfer { + sndr, + rcvr, + amt, + gas_limit, + gas_price, + } => { + let sndr = sndr.as_ref().expect("sender to be a valid address"); + let max_fee = gas_limit * gas_price; + println!(" > Send from = {}", sndr.preview()); + println!(" > Recipient = {}", rcvr.preview()); + println!(" > Amount to transfer = {} DUSK", amt); + println!(" > Max fee = {} DUSK", Dusk::from(max_fee)); + prompt::ask_confirm() + } + Command::MoonlightTransfer { sndr, rcvr, amt, @@ -442,9 +485,10 @@ fn confirm(cmd: &Command) -> anyhow::Result { println!(" > Recipient = {}", rcvr.preview()); println!(" > Amount to transfer = {} DUSK", amt); println!(" > Max fee = {} DUSK", Dusk::from(max_fee)); + println!(" > ALERT: THIS IS A PUBLIC TRANSACTION"); prompt::ask_confirm() } - Command::Stake { + Command::PhoenixStake { addr, amt, gas_limit, @@ -457,7 +501,7 @@ fn confirm(cmd: &Command) -> anyhow::Result { println!(" > Max fee = {} DUSK", Dusk::from(max_fee)); prompt::ask_confirm() } - Command::Unstake { + Command::PhoenixUnstake { addr, gas_limit, gas_price, @@ -468,7 +512,7 @@ fn confirm(cmd: &Command) -> anyhow::Result { println!(" > Max fee = {} DUSK", Dusk::from(max_fee)); prompt::ask_confirm() } - Command::Withdraw { + Command::PhoenixWithdraw { addr, gas_limit, gas_price, diff --git a/rusk-wallet/src/bin/main.rs b/rusk-wallet/src/bin/main.rs index 050c4d8742..2862bedc21 100644 --- a/rusk-wallet/src/bin/main.rs +++ b/rusk-wallet/src/bin/main.rs @@ -287,13 +287,16 @@ async fn exec() -> anyhow::Result<()> { // run command match cmd { Some(cmd) => match cmd.run(&mut wallet, &settings).await? { - RunResult::Balance(balance, spendable) => { + RunResult::PhoenixBalance(balance, spendable) => { if spendable { println!("{}", Dusk::from(balance.spendable)); } else { println!("{}", Dusk::from(balance.value)); } } + RunResult::MoonlightBalance(balance) => { + println!("Total: {}", balance); + } RunResult::Address(addr) => { println!("{addr}"); } @@ -325,7 +328,7 @@ async fn exec() -> anyhow::Result<()> { RunResult::ExportedKeys(pub_key, key_pair) => { println!("{},{}", pub_key.display(), key_pair.display()) } - RunResult::History(transactions) => { + RunResult::PhoenixHistory(transactions) => { println!("{}", TransactionHistory::header()); for th in transactions { println!("{th}"); diff --git a/rusk-wallet/src/clients.rs b/rusk-wallet/src/clients.rs index 53a456ea77..d6e50bdca8 100644 --- a/rusk-wallet/src/clients.rs +++ b/rusk-wallet/src/clients.rs @@ -230,10 +230,6 @@ impl State { let account = rkyv::from_bytes(&account).map_err(|_| Error::Rkyv)?; status("account-data received!"); - let account_address = pk.to_bytes().to_vec(); - let account_address = bs58::encode(account_address).into_string(); - println!("Account address: {}", account_address); - Ok(account) } diff --git a/rusk-wallet/src/error.rs b/rusk-wallet/src/error.rs index a5ee8670c7..260d0a69e2 100644 --- a/rusk-wallet/src/error.rs +++ b/rusk-wallet/src/error.rs @@ -119,6 +119,12 @@ pub enum Error { /// Memo provided is too large #[error("Memo too large {0}")] MemoTooLarge(usize), + /// Expected Bls Key + #[error("Expected Bls Public Key")] + ExpectedBlsPublicKey, + /// Expected Phoenix public key + #[error("Expected Phoenix public Key")] + ExpectedPhoenixPublicKey, } impl From for Error { diff --git a/rusk-wallet/src/lib.rs b/rusk-wallet/src/lib.rs index 5d0371c63b..d89b1902c1 100644 --- a/rusk-wallet/src/lib.rs +++ b/rusk-wallet/src/lib.rs @@ -58,7 +58,7 @@ pub const EPOCH: u64 = 2160; /// Max addresses the wallet can store pub const MAX_ADDRESSES: usize = get_max_addresses(); -const DEFAULT_MAX_ADDRESSES: usize = 1; +const DEFAULT_MAX_ADDRESSES: usize = 2; const fn get_max_addresses() -> usize { match option_env!("WALLET_MAX_ADDR") { diff --git a/rusk-wallet/src/rusk.rs b/rusk-wallet/src/rusk.rs index b1eb580f5b..2ab9312241 100644 --- a/rusk-wallet/src/rusk.rs +++ b/rusk-wallet/src/rusk.rs @@ -125,4 +125,5 @@ impl RuskHttpClient { Ok(response) } } + } diff --git a/rusk-wallet/src/wallet.rs b/rusk-wallet/src/wallet.rs index c8cacb0d8e..ae1cad2ff7 100644 --- a/rusk-wallet/src/wallet.rs +++ b/rusk-wallet/src/wallet.rs @@ -22,15 +22,13 @@ use std::fs; use std::path::{Path, PathBuf}; use wallet_core::{ + moonlight::{moonlight, moonlight_stake, moonlight_unstake}, + phoenix::{phoenix, phoenix_stake, phoenix_stake_reward, phoenix_unstake}, phoenix_balance, prelude::keys::{ derive_bls_pk, derive_bls_sk, derive_phoenix_pk, derive_phoenix_sk, derive_phoenix_vk, }, - transaction::{ - moonlight, phoenix, phoenix_stake, phoenix_stake_reward, - phoenix_unstake, - }, BalanceInfo, }; @@ -86,6 +84,11 @@ impl Wallet { } /// Returns phoenix key pair for a given address + /// + /// # Errors + /// + /// - If the Address provided is not a Phoenix address + /// - If the address is not owned pub fn phoenix_keys( &self, addr: &Address, @@ -99,7 +102,7 @@ impl Wallet { // retrieve keys let sk = self.phoenix_secret_key(index); - let pk = addr.pk(); + let pk = addr.pk()?; Ok((*pk, sk)) } @@ -123,7 +126,10 @@ impl Wallet { let bytes = seed.as_bytes().try_into().unwrap(); // Generate the default address - let address = Address::new(0, derive_phoenix_pk(&bytes, 0)); + let address = Address::Phoenix { + index: Some(0), + addr: derive_phoenix_pk(&bytes, 0), + }; // return new wallet instance Ok(Wallet { @@ -159,7 +165,10 @@ impl Wallet { // return early if its legacy if let DatFileVersion::Legacy = file_version { - let address = Address::new(0, derive_phoenix_pk(&seed, 0)); + let address = Address::Phoenix { + index: Some(0), + addr: derive_phoenix_pk(&seed, 0), + }; // return the store return Ok(Self { @@ -172,7 +181,10 @@ impl Wallet { } let addresses: Vec<_> = (0..address_count) - .map(|i| Address::new(i, derive_phoenix_pk(&seed, i))) + .map(|i| Address::Phoenix { + index: Some(i), + addr: derive_phoenix_pk(&seed, i), + }) .collect(); // create and return @@ -314,7 +326,7 @@ impl Wallet { let index = addr.index()?; let vk = derive_phoenix_vk(seed, index); - let pk = addr.pk(); + let pk = addr.pk()?; let live_notes = self.state()?.fetch_notes(pk)?; let spent_notes = self.state()?.cache().spent_notes(pk)?; @@ -344,7 +356,7 @@ impl Wallet { } /// Obtain balance information for a given address - pub async fn get_balance( + pub async fn get_phoenix_balance( &self, addr: &Address, ) -> Result { @@ -355,7 +367,7 @@ impl Wallet { } let index = addr.index()?; - let notes = state.fetch_notes(addr.pk())?; + let notes = state.fetch_notes(addr.pk()?)?; let seed = self.store.get_seed(); @@ -365,13 +377,25 @@ impl Wallet { )) } + /// Get moonlight account balance + pub fn get_moonlight_balance(&self, addr: &Address) -> Result { + let pk = addr.apk()?; + let state = self.state()?; + let account = state.fetch_account(pk)?; + + Ok(Dusk::from(account.balance)) + } + /// Creates a new public address. /// The addresses generated are deterministic across sessions. pub fn new_address(&mut self) -> &Address { let seed = self.store.get_seed(); let len = self.addresses.len(); let pk = derive_phoenix_pk(seed, len as u8); - let addr = Address::new(len as u8, pk); + let addr = Address::Phoenix { + index: Some(len as u8), + addr: pk, + }; self.addresses.push(addr); self.addresses.last().unwrap() @@ -390,25 +414,25 @@ impl Wallet { /// Returns the phoenix secret-key for a given index pub(crate) fn phoenix_secret_key(&self, index: u8) -> PhoenixSecretKey { let seed = self.store.get_seed(); - derive_phoenix_sk(&seed, index) + derive_phoenix_sk(seed, index) } /// Returns the phoenix public-key for a given index pub fn phoenix_public_key(&self, index: u8) -> PhoenixPublicKey { let seed = self.store.get_seed(); - derive_phoenix_pk(&seed, index) + derive_phoenix_pk(seed, index) } /// Returns the bls secret-key for a given index pub(crate) fn bls_secret_key(&self, index: u8) -> BlsSecretKey { let seed = self.store.get_seed(); - derive_bls_sk(&seed, index) + derive_bls_sk(seed, index) } /// Returns the bls public-key for a given index pub fn bls_public_key(&self, index: u8) -> BlsPublicKey { let seed = self.store.get_seed(); - derive_bls_pk(&seed, index) + derive_bls_pk(seed, index) } /// Creates a generic moonlight transaction. @@ -489,7 +513,7 @@ impl Wallet { let sender_index = sender.index()?; let mut sender_sk = self.phoenix_secret_key(sender_index); // in a contract execution, the sender and receiver are the same - let receiver_pk = sender.pk(); + let receiver_pk = sender.pk()?; let inputs = state .inputs(sender_index, deposit + gas.limit * gas.price)? @@ -503,7 +527,7 @@ impl Wallet { let tx = phoenix::<_, Prover>( &mut rng, &sender_sk, - sender.pk(), + sender.pk()?, receiver_pk, inputs, root, @@ -549,8 +573,8 @@ impl Wallet { let amt = *amt; let mut sender_sk = self.phoenix_secret_key(sender_index); - let change_pk = sender.pk(); - let reciever_pk = rcvr.pk(); + let change_pk = sender.pk()?; + let reciever_pk = rcvr.pk()?; let inputs = state .inputs(sender_index, amt + gas.limit * gas.price)? @@ -582,6 +606,52 @@ impl Wallet { state.prove_and_propagate(tx) } + /// Transfer through moonlight + pub async fn moonlight_transfer( + &self, + sender: &Address, + rcvr: &Address, + amt: Dusk, + gas: Gas, + ) -> Result { + // make sure we own the sender address + if !sender.is_owned() { + return Err(Error::Unauthorized); + } + // make sure amount is positive + if amt == 0 { + return Err(Error::AmountIsZero); + } + // check gas limits + if !gas.is_enough() { + return Err(Error::NotEnoughGas); + } + + let mut from_sk = self.bls_secret_key(sender.index()?); + let apk = rcvr.apk()?; + let amt = *amt; + + let state = self.state()?; + let account = state.fetch_account(apk)?; + let chain_id = state.fetch_chain_id()?; + + let tx = moonlight( + &from_sk, + Some(*apk), + amt, + 0, + gas.limit, + gas.price, + account.nonce, + chain_id, + None::, + )?; + + from_sk.zeroize(); + + state.prove_and_propagate(tx) + } + /// Stakes Dusk using phoenix notes pub async fn phoenix_stake( &self, @@ -635,6 +705,52 @@ impl Wallet { state.prove_and_propagate(stake) } + /// Stake via moonlight + pub fn moonlight_stake( + &self, + addr: &Address, + amt: Dusk, + gas: Gas, + ) -> Result { + // make sure we own the staking address + if !addr.is_owned() { + return Err(Error::Unauthorized); + } + // make sure amount is positive + if amt == 0 { + return Err(Error::AmountIsZero); + } + // check if the gas is enough + if !gas.is_enough() { + return Err(Error::NotEnoughGas); + } + + let state = self.state()?; + + let amt = *amt; + let sender_index = addr.index()?; + let mut stake_sk = self.bls_secret_key(sender_index); + let pk = AccountPublicKey::from(&stake_sk); + let account = state.fetch_account(&pk)?; + let chain_id = state.fetch_chain_id()?; + + let nonce = state.fetch_stake(&pk)?.map(|s| s.nonce).unwrap_or(0); + + let stake = moonlight_stake( + &stake_sk, + amt, + chain_id, + nonce, + account.nonce, + gas.limit, + gas.price, + )?; + + stake_sk.zeroize(); + + state.prove_and_propagate(stake) + } + /// Obtains stake information for a given address pub async fn stake_info( &self, @@ -691,11 +807,52 @@ impl Wallet { state.prove_and_propagate(unstake) } + /// Unstakes Dusk through moonlight + pub async fn moonlight_unstake( + &self, + addr: &Address, + gas: Gas, + ) -> Result { + // make sure we own the staking address + if !addr.is_owned() { + return Err(Error::Unauthorized); + } + + let mut rng = StdRng::from_entropy(); + let index = addr.index()?; + let state = self.state()?; + let mut stake_sk = self.bls_secret_key(index); + + let pk = AccountPublicKey::from(&stake_sk); + + let chain_id = state.fetch_chain_id()?; + let account = state.fetch_account(&pk)?; + + let unstake_value = state + .fetch_stake(&pk)? + .and_then(|s| s.amount) + .map(|s| s.value) + .unwrap_or(0); + + let unstake = moonlight_unstake( + &mut rng, + &stake_sk, + unstake_value, + chain_id, + account.nonce + 1, + gas.price, + gas.limit, + )?; + + stake_sk.zeroize(); + + state.prove_and_propagate(unstake) + } + /// Withdraw accumulated staking reward for a given address pub async fn phoenix_stake_withdraw( &self, sender_addr: &Address, - staker_index: u8, gas: Gas, ) -> Result { let state = self.state()?; @@ -708,7 +865,7 @@ impl Wallet { let sender_index = sender_addr.index()?; let mut sender_sk = self.phoenix_secret_key(sender_index); - let mut stake_sk = self.bls_secret_key(staker_index); + let mut stake_sk = self.bls_secret_key(sender_index); let inputs = state.inputs(sender_index, gas.limit * gas.price)?; @@ -800,7 +957,7 @@ impl Wallet { pub fn claim_as_address(&self, addr: Address) -> Result<&Address, Error> { self.addresses() .iter() - .find(|a| a.pk == addr.pk) + .find(|&a| a == &addr) .ok_or(Error::AddressNotOwned) } diff --git a/rusk-wallet/src/wallet/address.rs b/rusk-wallet/src/wallet/address.rs index dd3e19f094..ddd3ba3731 100644 --- a/rusk-wallet/src/wallet/address.rs +++ b/rusk-wallet/src/wallet/address.rs @@ -4,109 +4,174 @@ // // Copyright (c) DUSK NETWORK. All rights reserved. -use std::fmt; use std::hash::Hasher; -use std::str::FromStr; +use std::{fmt, str::FromStr}; use super::*; use crate::Error; use dusk_bytes::{DeserializableSlice, Error as BytesError, Serializable}; +/// Address for which to perform transactions with +/// it may be owned by the user or not, if the address is a reciever +/// then the index field will be none #[derive(Clone, Eq)] -/// A public address within the Dusk Network -pub struct Address { - pub(crate) index: Option, - pub(crate) pk: PhoenixPublicKey, +#[allow(missing_docs)] +pub enum Address { + /// A Phoenix address + Phoenix { + index: Option, + addr: PhoenixPublicKey, + }, + /// A BLS address for moonlight account + Bls { + index: Option, + addr: AccountPublicKey, + }, } +/// A public address within the Dusk Network impl Address { - pub(crate) fn new(index: u8, pk: PhoenixPublicKey) -> Self { - Self { - index: Some(index), - pk, + /// Returns true if the current user owns this address + pub fn is_owned(&self) -> bool { + self.index().is_ok() + } + + pub(crate) fn pk(&self) -> Result<&PhoenixPublicKey, Error> { + if let Self::Phoenix { addr, .. } = self { + Ok(addr) + } else { + Err(Error::ExpectedPhoenixPublicKey) } } - /// Returns true if the current user owns this address - pub fn is_owned(&self) -> bool { - self.index.is_some() + pub(crate) fn apk(&self) -> Result<&AccountPublicKey, Error> { + if let Self::Bls { addr, .. } = self { + Ok(addr) + } else { + Err(Error::ExpectedBlsPublicKey) + } } - pub(crate) fn pk(&self) -> &PhoenixPublicKey { - &self.pk + /// find index of the address + pub fn index(&self) -> Result { + match self { + Self::Phoenix { index, .. } => index, + Self::Bls { index, .. } => index, + } + .ok_or(Error::AddressNotOwned) } - pub(crate) fn index(&self) -> Result { - self.index.ok_or(Error::AddressNotOwned) + pub(crate) fn to_bytes(&self) -> Vec { + match self { + Self::Phoenix { addr, .. } => addr.to_bytes().to_vec(), + Self::Bls { addr, .. } => addr.to_bytes().to_vec(), + } } /// A trimmed version of the address to display as preview pub fn preview(&self) -> String { - let addr = bs58::encode(self.pk.to_bytes()).into_string(); + let bytes = self.to_bytes(); + let addr = bs58::encode(bytes).into_string(); format!("{}...{}", &addr[..7], &addr[addr.len() - 7..]) } -} -impl FromStr for Address { - type Err = Error; - - fn from_str(s: &str) -> Result { + /// try to create phoenix address from string + pub fn try_from_str_phoenix(s: &str) -> Result { let bytes = bs58::decode(s).into_vec()?; let pk = PhoenixPublicKey::from_reader(&mut &bytes[..]) .map_err(|_| Error::BadAddress)?; - let addr = Address { index: None, pk }; + let addr = Self::Phoenix { + index: None, + addr: pk, + }; Ok(addr) } -} -impl TryFrom for Address { - type Error = Error; + /// try to create moonlight address from string + pub fn try_from_str_bls(s: &str) -> Result { + let bytes = bs58::decode(s).into_vec()?; - fn try_from(s: String) -> Result { - Address::from_str(s.as_str()) - } -} + let apk = AccountPublicKey::from_reader(&mut &bytes[..]) + .map_err(|_| Error::BadAddress)?; -impl TryFrom<&[u8; PhoenixPublicKey::SIZE]> for Address { - type Error = Error; + let addr = Self::Bls { + index: None, + addr: apk, + }; + + Ok(addr) + } - fn try_from( + /// try to create phoenix public key from bytes + pub fn try_from_bytes_phoenix( bytes: &[u8; PhoenixPublicKey::SIZE], - ) -> Result { - let addr = Address { + ) -> Result { + let addr = Self::Phoenix { + index: None, + addr: PhoenixPublicKey::from_bytes(bytes)?, + }; + + Ok(addr) + } + + /// Create an address instance from `BlsPublicKey` bytes. + pub fn try_from_bytes_bls( + bytes: &[u8; AccountPublicKey::SIZE], + ) -> Result { + let addr = Self::Bls { index: None, - pk: PhoenixPublicKey::from_bytes(bytes)?, + addr: AccountPublicKey::from_bytes(bytes)?, }; + Ok(addr) } } +impl FromStr for Address { + type Err = Error; + + fn from_str(s: &str) -> Result { + let try_phoenix = Self::try_from_str_phoenix(s); + let try_bls = Self::try_from_str_bls(s); + + if let Ok(addr) = try_phoenix { + Ok(addr) + } else { + try_bls + } + } +} + impl PartialEq for Address { fn eq(&self, other: &Self) -> bool { - self.index == other.index && self.pk == other.pk + match (self.index(), other.index()) { + (Ok(x), Ok(y)) => x == y && self.preview() == other.preview(), + (_, _) => self.preview() == other.preview(), + } } } impl std::hash::Hash for Address { fn hash(&self, state: &mut H) { - self.index.hash(state); - self.pk.to_bytes().hash(state); + // we dont care about addresses we dont own + let _ = self.index().map(|f| f.hash(state)); + self.preview().hash(state); } } impl fmt::Display for Address { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", bs58::encode(self.pk.to_bytes()).into_string()) + write!(f, "{}", bs58::encode(self.to_bytes()).into_string()) } } impl fmt::Debug for Address { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", bs58::encode(self.pk.to_bytes()).into_string()) + write!(f, "{}", bs58::encode(self.to_bytes()).into_string()) } } diff --git a/test-wallet/src/imp.rs b/test-wallet/src/imp.rs index 34d917ec13..79e617bce6 100644 --- a/test-wallet/src/imp.rs +++ b/test-wallet/src/imp.rs @@ -36,12 +36,11 @@ use execution_core::{ use rusk_prover::LocalProver; use wallet_core::{ keys::{derive_bls_sk, derive_phoenix_sk}, - phoenix_balance, - transaction::{ + phoenix::{ phoenix as phoenix_transaction, phoenix_stake, phoenix_stake_reward, phoenix_unstake, }, - BalanceInfo, + phoenix_balance, BalanceInfo, }; const MAX_INPUT_NOTES: usize = 4; diff --git a/wallet-core/src/lib.rs b/wallet-core/src/lib.rs index 610e6db1db..cb822df86a 100644 --- a/wallet-core/src/lib.rs +++ b/wallet-core/src/lib.rs @@ -21,7 +21,8 @@ mod ffi; pub mod input; pub mod keys; -pub mod transaction; +pub mod moonlight; +pub mod phoenix; pub mod prelude { //! Re-export of the most commonly used types and traits. diff --git a/wallet-core/src/moonlight.rs b/wallet-core/src/moonlight.rs new file mode 100644 index 0000000000..f7e2e887b3 --- /dev/null +++ b/wallet-core/src/moonlight.rs @@ -0,0 +1,142 @@ +// 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. + +//! Implementations of basic wallet functionalities to create moonlight +//! transactions. + +#![allow(clippy::module_name_repetitions)] + +use execution_core::{ + signatures::bls::{PublicKey as BlsPublicKey, SecretKey as BlsSecretKey}, + stake::{Stake, Withdraw as StakeWithdraw, STAKE_CONTRACT}, + transfer::{ + data::{ContractCall, TransactionData}, + moonlight::Transaction as MoonlightTransaction, + withdraw::{Withdraw, WithdrawReceiver, WithdrawReplayToken}, + Transaction, + }, + Error, +}; + +use rand::{CryptoRng, RngCore}; + +/// Generate a moonlight transaction +/// +/// # Errors +/// - the transaction-data is incorrect +#[allow(clippy::too_many_arguments)] +pub fn moonlight( + from_sk: &BlsSecretKey, + to_account: Option, + value: u64, + deposit: u64, + gas_limit: u64, + gas_price: u64, + nonce: u64, + chain_id: u8, + data: Option>, +) -> Result { + Ok(MoonlightTransaction::new( + from_sk, + to_account, + value, + deposit, + gas_limit, + gas_price, + nonce + 1, + chain_id, + data, + )? + .into()) +} + +/// Stake through moonlight, the `stake_nonce` is the nonce of the stake +/// which is obtained via stake info query on the chain +/// +/// The `nonce` is the nonce of the moonlight transaction +/// +/// # Errors +/// +/// This function most likey not fail but if the `nonce` is incorrect +/// or the `stake_nonce` the node will error and not accept the transcation +pub fn moonlight_stake( + from_sk: &BlsSecretKey, + stake_value: u64, + chain_id: u8, + stake_nonce: u64, + nonce: u64, + gas_limit: u64, + gas_price: u64, +) -> Result { + let receiver_pk = BlsPublicKey::from(from_sk); + + let transfer_value = 0; + let deposit = stake_value; + + let stake = Stake::new(from_sk, stake_value, stake_nonce + 1, chain_id); + + let contract_call = ContractCall::new(STAKE_CONTRACT, "stake", &stake)?; + + Ok(MoonlightTransaction::new( + from_sk, + Some(receiver_pk), + transfer_value, + deposit, + gas_limit, + gas_price, + nonce + 1, + chain_id, + Some(contract_call), + )? + .into()) +} + +/// Unstake through moonlight +/// +/// # Errors +/// +/// This function most likey not fail but if the `nonce` is incorrect +/// or the `stake_nonce` the node will error and not accept the transcation +pub fn moonlight_unstake( + rng: &mut R, + from_sk: &BlsSecretKey, + unstake_value: u64, + chain_id: u8, + nonce: u64, + gas_limit: u64, + gas_price: u64, +) -> Result { + let receiver_pk = BlsPublicKey::from(from_sk); + + let transfer_value = 0; + let deposit = unstake_value; + + let withdraw = Withdraw::new( + rng, + from_sk, + STAKE_CONTRACT, + unstake_value, + WithdrawReceiver::Moonlight(receiver_pk), + WithdrawReplayToken::Moonlight(nonce), + ); + + let unstake = StakeWithdraw::new(from_sk, withdraw); + + let contract_call = ContractCall::new(STAKE_CONTRACT, "unstake", &unstake)?; + + Ok(MoonlightTransaction::new( + from_sk, + Some(receiver_pk), + transfer_value, + deposit, + gas_limit, + gas_price, + nonce + 1, + chain_id, + Some(contract_call), + )? + .into()) +} diff --git a/wallet-core/src/transaction.rs b/wallet-core/src/phoenix.rs similarity index 92% rename from wallet-core/src/transaction.rs rename to wallet-core/src/phoenix.rs index ee93bb6f10..f72aaa3777 100644 --- a/wallet-core/src/transaction.rs +++ b/wallet-core/src/phoenix.rs @@ -4,7 +4,10 @@ // // Copyright (c) DUSK NETWORK. All rights reserved. -//! Implementations of basic wallet functionalities to create transactions. +//! Implementations of basic wallet functionalities to create phoenix +//! transactions. + +#![allow(clippy::module_name_repetitions)] use alloc::vec::Vec; @@ -14,11 +17,10 @@ use ff::Field; use zeroize::Zeroize; use execution_core::{ - signatures::bls::{PublicKey as BlsPublicKey, SecretKey as BlsSecretKey}, + signatures::bls::SecretKey as BlsSecretKey, stake::{Stake, Withdraw as StakeWithdraw, STAKE_CONTRACT}, transfer::{ data::{ContractCall, TransactionData}, - moonlight::Transaction as MoonlightTransaction, phoenix::{ Note, NoteOpening, Prove, PublicKey as PhoenixPublicKey, SecretKey as PhoenixSecretKey, Transaction as PhoenixTransaction, @@ -73,29 +75,6 @@ pub fn phoenix( .into()) } -/// Generate a moonlight transaction -/// -/// # Errors -/// - the transaction-data is incorrect -#[allow(clippy::too_many_arguments)] -pub fn moonlight( - from_sk: &BlsSecretKey, - to_account: Option, - value: u64, - deposit: u64, - gas_limit: u64, - gas_price: u64, - nonce: u64, - chain_id: u8, - data: Option>, -) -> Result { - Ok(MoonlightTransaction::new( - from_sk, to_account, value, deposit, gas_limit, gas_price, nonce, - chain_id, data, - )? - .into()) -} - /// Create a [`Transaction`] to stake from phoenix-notes. /// /// # Errors