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

Add support for cold wallet #1497

Merged
merged 4 commits into from
Jan 25, 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
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 2 additions & 3 deletions test/functional/wallet_decommission_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ async def async_test(self):
node = self.nodes[0]
decommission_address = ""

async with WalletCliController(node, self.config, self.log, chain_config_args=["--chain-pos-netupgrades", "true"]) as wallet:
async with WalletCliController(node, self.config, self.log, chain_config_args=["--chain-pos-netupgrades", "true", "--cold-wallet"]) as wallet:
# new cold wallet
await wallet.create_wallet("cold_wallet")

Expand Down Expand Up @@ -299,10 +299,9 @@ async def async_test(self):

decommission_signed_tx = ""

async with WalletCliController(node, self.config, self.log, chain_config_args=["--chain-pos-netupgrades", "true"]) as wallet:
async with WalletCliController(node, self.config, self.log, chain_config_args=["--chain-pos-netupgrades", "true", "--cold-wallet"]) as wallet:
# open cold wallet
await wallet.open_wallet("cold_wallet")
assert_in("Success", await wallet.sync())

# sign decommission request
decommission_signed_tx_output = await wallet.sign_raw_transaction(decommission_req)
Expand Down
4 changes: 2 additions & 2 deletions test/src/bin/test_wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
use clap::Parser;
use wallet_cli_lib::{
config::WalletCliArgs,
console::{ConsoleOutput, StdioInputConsole, StdioOutputConsole},
console::{StdioInputConsole, StdioOutputConsole},
};

#[tokio::main]
Expand All @@ -31,7 +31,7 @@ async fn main() {
wallet_cli_lib::run(StdioInputConsole, StdioOutputConsole, args, None)
.await
.unwrap_or_else(|err| {
StdioOutputConsole.print_error(err);
eprintln!("{err}");
std::process::exit(1);
})
}
2 changes: 2 additions & 0 deletions wallet/wallet-cli-lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ crypto = { path = "../../crypto" }
logging = { path = "../../logging" }
mempool = { path = "../../mempool" }
p2p-types = { path = "../../p2p/types" }
node-comm = { path = "../wallet-node-client" }
rpc = { path = "../../rpc" }
serialization = { path = "../../serialization" }
utils = { path = "../../utils" }
Expand All @@ -33,6 +34,7 @@ serde_json.workspace = true
shlex.workspace = true
thiserror.workspace = true
tokio = { workspace = true, default-features = false, features = ["io-util", "macros", "net", "rt", "sync"] }
futures.workspace = true

prettytable-rs = "0.10"

Expand Down
19 changes: 8 additions & 11 deletions wallet/wallet-cli-lib/src/cli_event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,35 +16,32 @@
use std::sync::Arc;

use common::chain::ChainConfig;
use rpc::RpcAuthData;
use tokio::sync::{mpsc, oneshot};
use wallet_controller::ControllerConfig;
use wallet_controller::{ControllerConfig, NodeInterface};

use crate::{
commands::{CommandHandler, ConsoleCommand, WalletCommand},
errors::WalletCliError,
};

#[derive(Debug)]
pub enum Event {
pub enum Event<N: NodeInterface> {
HandleCommand {
command: WalletCommand,
res_tx: oneshot::Sender<Result<ConsoleCommand, WalletCliError>>,
res_tx: oneshot::Sender<Result<ConsoleCommand, WalletCliError<N>>>,
},
}

pub async fn run(
pub async fn run<N: NodeInterface + Clone + Send + Sync + 'static>(
chain_config: &Arc<ChainConfig>,
mut event_rx: mpsc::UnboundedReceiver<Event>,
mut event_rx: mpsc::UnboundedReceiver<Event<N>>,
in_top_x_mb: usize,
node_rpc_address: Option<String>,
node_credentials: RpcAuthData,
) -> Result<(), WalletCliError> {
node_rpc: N,
) -> Result<(), WalletCliError<N>> {
let mut command_handler = CommandHandler::new(
ControllerConfig { in_top_x_mb },
chain_config.clone(),
node_rpc_address,
node_credentials,
node_rpc,
)
.await?;

Expand Down
45 changes: 26 additions & 19 deletions wallet/wallet-cli-lib/src/commands/helper_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
use std::{fmt::Display, str::FromStr};

use clap::ValueEnum;
use wallet_controller::{UtxoState, UtxoStates, UtxoType, UtxoTypes};
use wallet_controller::{NodeInterface, UtxoState, UtxoStates, UtxoType, UtxoTypes};

use common::{
chain::{
Expand Down Expand Up @@ -151,31 +151,37 @@ impl CliStoreSeedPhrase {
///
/// e.g tx(000000000000000000059fa50103b9683e51e5aba83b8a34c9b98ce67d66136c,1)
/// e.g block(000000000000000000059fa50103b9683e51e5aba83b8a34c9b98ce67d66136c,2)
pub fn parse_utxo_outpoint(mut input: String) -> Result<UtxoOutPoint, WalletCliError> {
pub fn parse_utxo_outpoint<N: NodeInterface>(
mut input: String,
) -> Result<UtxoOutPoint, WalletCliError<N>> {
if !input.ends_with(')') {
return Err(WalletCliError::InvalidInput("Invalid input format".into()));
return Err(WalletCliError::<N>::InvalidInput(
"Invalid input format".into(),
));
}
input.pop();

let mut parts: Vec<&str> = input.split('(').collect();
let last = parts.pop().ok_or(WalletCliError::InvalidInput(
let last = parts.pop().ok_or(WalletCliError::<N>::InvalidInput(
"Invalid input format".to_owned(),
))?;
parts.extend(last.split(','));

if parts.len() != 3 {
return Err(WalletCliError::InvalidInput("Invalid input format".into()));
return Err(WalletCliError::<N>::InvalidInput(
"Invalid input format".into(),
));
}

let h256 =
H256::from_str(parts[1]).map_err(|err| WalletCliError::InvalidInput(err.to_string()))?;
let output_index =
u32::from_str(parts[2]).map_err(|err| WalletCliError::InvalidInput(err.to_string()))?;
let h256 = H256::from_str(parts[1])
.map_err(|err| WalletCliError::<N>::InvalidInput(err.to_string()))?;
let output_index = u32::from_str(parts[2])
.map_err(|err| WalletCliError::<N>::InvalidInput(err.to_string()))?;
let source_id = match parts[0] {
"tx" => OutPointSourceId::Transaction(Id::new(h256)),
"block" => OutPointSourceId::BlockReward(Id::new(h256)),
_ => {
return Err(WalletCliError::InvalidInput(
return Err(WalletCliError::<N>::InvalidInput(
"Invalid input: unknown ID type".into(),
));
}
Expand All @@ -186,10 +192,10 @@ pub fn parse_utxo_outpoint(mut input: String) -> Result<UtxoOutPoint, WalletCliE

/// Try to parse a total token supply from a string
/// Valid values are "unlimited", "lockable" and "fixed(Amount)"
pub fn parse_token_supply(
pub fn parse_token_supply<N: NodeInterface>(
input: &str,
token_number_of_decimals: u8,
) -> Result<TokenTotalSupply, WalletCliError> {
) -> Result<TokenTotalSupply, WalletCliError<N>> {
match input {
"unlimited" => Ok(TokenTotalSupply::Unlimited),
"lockable" => Ok(TokenTotalSupply::Lockable),
Expand All @@ -198,32 +204,33 @@ pub fn parse_token_supply(
}

/// Try to parse a fixed total token supply in the format of "fixed(Amount)"
fn parse_fixed_token_supply(
fn parse_fixed_token_supply<N: NodeInterface>(
input: &str,
token_number_of_decimals: u8,
) -> Result<TokenTotalSupply, WalletCliError> {
) -> Result<TokenTotalSupply, WalletCliError<N>> {
if let Some(inner) = input.strip_prefix("fixed(").and_then(|str| str.strip_suffix(')')) {
Ok(TokenTotalSupply::Fixed(parse_token_amount(
token_number_of_decimals,
inner,
)?))
} else {
Err(WalletCliError::InvalidInput(format!(
Err(WalletCliError::<N>::InvalidInput(format!(
"Failed to parse token supply from {input}"
)))
}
}

pub fn parse_token_amount(
pub fn parse_token_amount<N: NodeInterface>(
token_number_of_decimals: u8,
value: &str,
) -> Result<Amount, WalletCliError> {
) -> Result<Amount, WalletCliError<N>> {
Amount::from_fixedpoint_str(value, token_number_of_decimals)
.ok_or_else(|| WalletCliError::InvalidInput(value.to_owned()))
.ok_or_else(|| WalletCliError::<N>::InvalidInput(value.to_owned()))
}

#[cfg(test)]
mod tests {
use node_comm::rpc_client::ColdWalletClient;
use rstest::rstest;
use test_utils::random::{make_seedable_rng, Seed};

Expand All @@ -235,7 +242,7 @@ mod tests {
#[case(Seed::from_entropy())]
fn test_parse_utxo_outpoint(#[case] seed: Seed) {
fn check(input: String, is_tx: bool, idx: u32, hash: H256) {
let utxo_outpoint = parse_utxo_outpoint(input).unwrap();
let utxo_outpoint = parse_utxo_outpoint::<ColdWalletClient>(input).unwrap();

match utxo_outpoint.source_id() {
OutPointSourceId::Transaction(id) => {
Expand Down
Loading
Loading