├── .gitignore ├── rustfmt.toml ├── rust-toolchain.toml ├── README.md ├── Makefile ├── src ├── bin │ ├── io.rs │ ├── io │ │ ├── status.rs │ │ ├── args.rs │ │ ├── gql.rs │ │ └── prompt.rs │ ├── config.rs │ ├── menu.rs │ ├── README.md │ ├── command │ │ └── history.rs │ ├── settings.rs │ ├── main.rs │ ├── command.rs │ └── interactive.rs ├── block.rs ├── store.rs ├── lib.rs ├── wallet │ ├── gas.rs │ ├── file.rs │ └── address.rs ├── crypto.rs ├── rusk.rs ├── clients │ └── sync.rs ├── error.rs ├── currency.rs ├── dat.rs ├── cache.rs └── clients.rs ├── default.config.toml ├── .github └── workflows │ ├── wallet_ci.yml │ └── wallet_build.yml ├── Cargo.toml ├── LICENSE └── CHANGELOG.md /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width = 80 2 | wrap_comments = true 3 | 4 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "nightly-2024-02-18" 3 | components = ["rustfmt", "cargo", "clippy"] -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ⛔ [DEPRECATED] Dusk Wallet 2 | 3 | This repository has been archived and is no longer actively maintained. 4 | 5 | The development of the Rusk CLI Wallet has been moved to the [Rusk Monorepo](https://github.com/dusk-network/rusk/tree/master/rusk-wallet). Please refer to that repository for the latest code, updates, and contributions. 6 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | help: ## Display this help screen 2 | @grep -h -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-15s\033[0m %s\n", $$1, $$2}' 3 | 4 | build: ## Build the wallet 5 | cargo b --release 6 | 7 | install: build 8 | cargo install --path . 9 | 10 | test: build ## Run wallet tests 11 | cargo test --release 12 | 13 | .PHONY: build test help 14 | -------------------------------------------------------------------------------- /src/bin/io.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | mod args; 8 | mod gql; 9 | 10 | pub(crate) mod prompt; 11 | pub(crate) mod status; 12 | 13 | pub(crate) use args::WalletArgs; 14 | pub(crate) use gql::GraphQL; 15 | -------------------------------------------------------------------------------- /default.config.toml: -------------------------------------------------------------------------------- 1 | state = "https://nodes.dusk.network" 2 | prover = "https://provers.dusk.network" 3 | explorer = "https://explorer.dusk.network/transactions/transaction/?id=" 4 | 5 | [network.devnet] 6 | state = "https://devnet.nodes.dusk.network" 7 | prover = "https://devnet.provers.dusk.network" 8 | explorer = "https://explorer.dusk.network/transactions/transaction/?id=" 9 | 10 | [network.local] 11 | state = "http://127.0.0.1:8080" 12 | prover = "http://127.0.0.1:8080" 13 | -------------------------------------------------------------------------------- /src/block.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use tokio::runtime::Handle; 8 | use tokio::task::block_in_place; 9 | 10 | pub(crate) trait Block { 11 | fn wait(self) -> ::Output 12 | where 13 | Self: Sized, 14 | Self: futures::Future, 15 | { 16 | block_in_place(move || Handle::current().block_on(self)) 17 | } 18 | } 19 | 20 | impl Block for F where F: futures::Future {} 21 | -------------------------------------------------------------------------------- /src/bin/io/status.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use std::io::{stdout, Write}; 8 | use std::thread; 9 | use std::time::Duration; 10 | 11 | use tracing::info; 12 | 13 | /// Prints an interactive status message 14 | pub(crate) fn interactive(status: &str) { 15 | print!("\r{status: <50}\r"); 16 | let mut stdout = stdout(); 17 | stdout.flush().unwrap(); 18 | thread::sleep(Duration::from_millis(85)); 19 | } 20 | 21 | /// Logs the status message at info level 22 | pub(crate) fn headless(status: &str) { 23 | info!(status); 24 | } 25 | -------------------------------------------------------------------------------- /src/store.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use crate::clients::StateStore; 8 | use crate::Error; 9 | 10 | use dusk_bytes::{Error as BytesError, Serializable}; 11 | use dusk_wallet_core::Store; 12 | 13 | #[derive(Clone)] 14 | pub struct Seed([u8; 64]); 15 | 16 | impl Default for Seed { 17 | fn default() -> Self { 18 | Self([0u8; 64]) 19 | } 20 | } 21 | 22 | impl Serializable<64> for Seed { 23 | type Error = BytesError; 24 | 25 | fn from_bytes(buff: &[u8; Seed::SIZE]) -> Result { 26 | Ok(Self(*buff)) 27 | } 28 | fn to_bytes(&self) -> [u8; Seed::SIZE] { 29 | self.0 30 | } 31 | } 32 | 33 | /// Provides a valid wallet seed to dusk_wallet_core 34 | #[derive(Clone)] 35 | pub(crate) struct LocalStore { 36 | seed: Seed, 37 | } 38 | 39 | impl Store for LocalStore { 40 | type Error = Error; 41 | 42 | /// Retrieves the seed used to derive keys. 43 | fn get_seed(&self) -> Result<[u8; Seed::SIZE], Self::Error> { 44 | Ok(self.seed.to_bytes()) 45 | } 46 | } 47 | 48 | impl Store for StateStore { 49 | type Error = Error; 50 | 51 | /// Retrieves the seed used to derive keys. 52 | fn get_seed(&self) -> Result<[u8; Seed::SIZE], Self::Error> { 53 | Ok(self.store.seed.to_bytes()) 54 | } 55 | } 56 | 57 | impl LocalStore { 58 | /// Creates a new store from a known seed 59 | pub(crate) fn new(seed: Seed) -> Self { 60 | LocalStore { seed } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/bin/io/args.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use crate::settings::{LogFormat, LogLevel}; 8 | use crate::Command; 9 | use clap::{AppSettings, Parser}; 10 | use std::path::PathBuf; 11 | 12 | #[derive(Parser, Debug)] 13 | #[clap(version)] 14 | #[clap(name = "Dusk Wallet CLI")] 15 | #[clap(author = "Dusk Network B.V.")] 16 | #[clap(about = "A user-friendly, reliable command line interface to the Dusk wallet!", long_about = None)] 17 | #[clap(global_setting(AppSettings::DeriveDisplayOrder))] 18 | pub(crate) struct WalletArgs { 19 | /// Directory to store user data [default: `$HOME/.dusk/rusk-wallet`] 20 | #[clap(short, long)] 21 | pub profile: Option, 22 | 23 | /// Network to connect to 24 | #[clap(short, long)] 25 | pub network: Option, 26 | 27 | /// Set the password for wallet's creation 28 | #[clap(long, env = "RUSK_WALLET_PWD")] 29 | pub password: Option, 30 | 31 | /// The state server fully qualified URL 32 | #[clap(long)] 33 | pub state: Option, 34 | 35 | /// The prover server fully qualified URL 36 | #[clap(long)] 37 | pub prover: Option, 38 | 39 | /// Output log level 40 | #[clap(long, value_enum, default_value_t = LogLevel::Info)] 41 | pub log_level: LogLevel, 42 | 43 | /// Logging output type 44 | #[clap(long, value_enum, default_value_t = LogFormat::Coloured)] 45 | pub log_type: LogFormat, 46 | 47 | /// Command 48 | #[clap(subcommand)] 49 | pub command: Option, 50 | } 51 | -------------------------------------------------------------------------------- /src/bin/config.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use serde::Deserialize; 8 | use std::collections::HashMap; 9 | use std::path::Path; 10 | use url::Url; 11 | 12 | #[derive(Debug, Deserialize, Clone)] 13 | #[allow(dead_code)] 14 | pub(crate) struct Network { 15 | pub(crate) state: Url, 16 | pub(crate) prover: Url, 17 | pub(crate) explorer: Option, 18 | pub(crate) network: Option>, 19 | } 20 | 21 | use std::{fs, io}; 22 | 23 | /// Config holds the settings for the CLI wallet 24 | #[derive(Debug)] 25 | pub struct Config { 26 | /// Network configuration 27 | pub(crate) network: Network, 28 | } 29 | 30 | fn read_to_string>(path: P) -> io::Result> { 31 | fs::read_to_string(&path) 32 | .map(Some) 33 | .or_else(|e| match e.kind() { 34 | io::ErrorKind::NotFound => Ok(None), 35 | _ => Err(e), 36 | }) 37 | } 38 | 39 | impl Config { 40 | /// Attempt to load configuration from file 41 | pub fn load(profile: &Path) -> anyhow::Result { 42 | let profile = profile.join("config.toml"); 43 | 44 | let mut global_config = dirs::home_dir().expect("OS not supported"); 45 | global_config.push(".config"); 46 | global_config.push(env!("CARGO_BIN_NAME")); 47 | global_config.push("config.toml"); 48 | 49 | let contents = read_to_string(profile)? 50 | .or(read_to_string(&global_config)?) 51 | .unwrap_or_else(|| { 52 | include_str!("../../default.config.toml").to_string() 53 | }); 54 | 55 | let network: Network = toml::from_str(&contents)?; 56 | 57 | Ok(Config { network }) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /.github/workflows/wallet_ci.yml: -------------------------------------------------------------------------------- 1 | on: [pull_request, workflow_dispatch] 2 | 3 | name: Continuous integration 4 | 5 | jobs: 6 | fmt: 7 | name: Rustfmt 8 | runs-on: core 9 | steps: 10 | - uses: actions/checkout@v4 11 | - uses: dsherret/rust-toolchain-file@v1 12 | - run: cargo fmt --all -- --check 13 | 14 | analyze: 15 | name: Dusk Analyzer 16 | runs-on: core 17 | steps: 18 | - uses: actions/checkout@v4 19 | - uses: dsherret/rust-toolchain-file@v1 20 | - run: cargo install --git https://github.com/dusk-network/cargo-dusk-analyzer 21 | - run: cargo dusk-analyzer 22 | 23 | test_nightly-linux: 24 | name: "[Linux] Nightly tests" 25 | runs-on: core 26 | steps: 27 | - uses: actions/checkout@v4 28 | - uses: dsherret/rust-toolchain-file@v1 29 | - run: cargo test --release 30 | - run: cargo clippy --all-features --release -- -D warnings 31 | 32 | test_nightly-macintel: 33 | name: "[Mac Intel] Nightly tests" 34 | runs-on: macos-latest 35 | steps: 36 | - uses: actions/checkout@v4 37 | - uses: dsherret/rust-toolchain-file@v1 38 | 39 | - name: Add arm target for Apple Silicon build 40 | run: rustup target add aarch64-apple-darwin 41 | 42 | - run: cargo test 43 | 44 | test_nightly-macm1: 45 | name: "[Mac arm64] Nightly checks" 46 | runs-on: macos-latest 47 | steps: 48 | - uses: actions/checkout@v4 49 | - uses: dsherret/rust-toolchain-file@v1 50 | 51 | - name: Add arm target for Apple Silicon build 52 | run: rustup target add aarch64-apple-darwin 53 | 54 | - run: cargo check --target=aarch64-apple-darwin 55 | 56 | test_nightly-win: 57 | name: "[Windows] Nightly tests" 58 | runs-on: windows-latest 59 | steps: 60 | - uses: actions/checkout@v4 61 | - uses: dsherret/rust-toolchain-file@v1 62 | 63 | - run: cargo test 64 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | //! # Dusk Wallet Lib 8 | //! 9 | //! The `dusk_wallet` library aims to provide an easy and convenient way of 10 | //! interfacing with the Dusk Network. 11 | //! 12 | //! Clients can use `Wallet` to create their Dusk wallet, send transactions 13 | //! through the network of their choice, stake and withdraw rewards, etc. 14 | 15 | #![deny(missing_docs)] 16 | 17 | mod block; 18 | mod cache; 19 | mod clients; 20 | mod crypto; 21 | 22 | mod currency; 23 | mod error; 24 | mod rusk; 25 | mod store; 26 | mod wallet; 27 | 28 | /// Methods for parsing/checking the DAT wallet file 29 | pub mod dat; 30 | 31 | pub use rusk::{RuskHttpClient, RuskRequest}; 32 | 33 | pub use currency::{Dusk, Lux}; 34 | pub use error::Error; 35 | pub use wallet::gas; 36 | pub use wallet::{Address, DecodedNote, SecureWalletFile, Wallet, WalletPath}; 37 | 38 | /// The largest amount of Dusk that is possible to convert 39 | pub const MAX_CONVERTIBLE: Dusk = Dusk::MAX; 40 | /// The smallest amount of Dusk that is possible to convert 41 | pub const MIN_CONVERTIBLE: Dusk = Dusk::new(1); 42 | /// The length of an epoch in blocks 43 | pub const EPOCH: u64 = 2160; 44 | /// Max addresses the wallet can store 45 | pub const MAX_ADDRESSES: usize = get_max_addresses(); 46 | 47 | const DEFAULT_MAX_ADDRESSES: usize = 25; 48 | 49 | const fn get_max_addresses() -> usize { 50 | match option_env!("WALLET_MAX_ADDR") { 51 | Some(v) => match konst::primitive::parse_usize(v) { 52 | Ok(e) if e > 255 => { 53 | panic!("WALLET_MAX_ADDR must be lower or equal to 255") 54 | } 55 | Ok(e) if e > 0 => e, 56 | _ => panic!("Invalid WALLET_MAX_ADDR"), 57 | }, 58 | None => DEFAULT_MAX_ADDRESSES, 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/wallet/gas.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | //! This library contains the primitive related to the gas used for transaction 8 | //! in the Dusk Network. 9 | 10 | use crate::currency::Lux; 11 | 12 | /// The minimum gas limit 13 | pub const MIN_LIMIT: u64 = 350_000_000; 14 | 15 | /// The default gas limit 16 | pub const DEFAULT_LIMIT: u64 = 500_000_000; 17 | 18 | /// The default gas price 19 | pub const DEFAULT_PRICE: Lux = 1; 20 | 21 | #[derive(Debug)] 22 | /// Gas price and limit for any transaction 23 | pub struct Gas { 24 | /// The gas price in [Lux] 25 | pub price: Lux, 26 | /// The gas limit 27 | pub limit: u64, 28 | } 29 | 30 | impl Gas { 31 | /// Default gas price and limit 32 | pub fn new(limit: u64) -> Self { 33 | Gas { 34 | price: DEFAULT_PRICE, 35 | limit, 36 | } 37 | } 38 | 39 | /// Returns `true` if the gas is equal or greater than the minimum limit 40 | pub fn is_enough(&self) -> bool { 41 | self.limit >= MIN_LIMIT 42 | } 43 | 44 | /// Set the price 45 | pub fn set_price(&mut self, price: T) 46 | where 47 | T: Into>, 48 | { 49 | self.price = price.into().unwrap_or(DEFAULT_PRICE); 50 | } 51 | 52 | /// Set the price and return the Gas 53 | pub fn with_price(mut self, price: T) -> Self 54 | where 55 | T: Into, 56 | { 57 | self.price = price.into(); 58 | self 59 | } 60 | 61 | /// Set the limit 62 | pub fn set_limit(&mut self, limit: T) 63 | where 64 | T: Into>, 65 | { 66 | if let Some(limit) = limit.into() { 67 | self.limit = limit; 68 | } 69 | } 70 | } 71 | 72 | impl Default for Gas { 73 | fn default() -> Self { 74 | Self::new(DEFAULT_LIMIT) 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/crypto.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use aes::Aes256; 8 | use block_modes::block_padding::Pkcs7; 9 | use block_modes::{BlockMode, Cbc}; 10 | use rand::rngs::OsRng; 11 | use rand::RngCore; 12 | 13 | use crate::Error; 14 | 15 | type Aes256Cbc = Cbc; 16 | 17 | /// Encrypts data using a password. 18 | pub(crate) fn encrypt(plaintext: &[u8], pwd: &[u8]) -> Result, Error> { 19 | let mut iv = vec![0; 16]; 20 | let mut rng = OsRng; 21 | rng.fill_bytes(&mut iv); 22 | 23 | let cipher = Aes256Cbc::new_from_slices(pwd, &iv)?; 24 | let enc = cipher.encrypt_vec(plaintext); 25 | 26 | let ciphertext = iv.into_iter().chain(enc).collect(); 27 | Ok(ciphertext) 28 | } 29 | 30 | /// Decrypts data encrypted with `encrypt`. 31 | pub(crate) fn decrypt(ciphertext: &[u8], pwd: &[u8]) -> Result, Error> { 32 | let iv = &ciphertext[..16]; 33 | let enc = &ciphertext[16..]; 34 | 35 | let cipher = Aes256Cbc::new_from_slices(pwd, iv)?; 36 | let plaintext = cipher.decrypt_vec(enc)?; 37 | 38 | Ok(plaintext) 39 | } 40 | 41 | #[cfg(test)] 42 | mod tests { 43 | use super::*; 44 | 45 | #[test] 46 | fn encrypt_and_decrypt() { 47 | let seed = 48 | b"0001020304050607000102030405060700010203040506070001020304050607"; 49 | let pwd = blake3::hash("greatpassword".as_bytes()); 50 | let pwd = pwd.as_bytes(); 51 | 52 | let enc_seed = encrypt(seed, pwd).expect("seed to encrypt ok"); 53 | let enc_seed_t = encrypt(seed, pwd).expect("seed to encrypt ok"); 54 | 55 | // check that random IV is correctly applied 56 | assert_ne!(enc_seed, enc_seed_t); 57 | 58 | let dec_seed = decrypt(&enc_seed, pwd).expect("seed to decrypt ok"); 59 | 60 | // check that decryption matches original seed 61 | assert_eq!(dec_seed, seed); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "dusk-wallet" 3 | version = "0.22.1" 4 | edition = "2021" 5 | autobins = false 6 | description = "A library providing functionalities to create wallets compatible with Dusk Network" 7 | categories = ["cryptography", "cryptography::cryptocurrencies"] 8 | keywords = ["wallet", "dusk", "cryptocurrency", "blockchain"] 9 | repository = "https://github.com/dusk-network/wallet-cli" 10 | license = "MPL-2.0" 11 | exclude = [".github/*", ".gitignore"] 12 | 13 | [[bin]] 14 | name = "rusk-wallet" 15 | path = "src/bin/main.rs" 16 | 17 | [dependencies] 18 | clap = { version = "3.1", features = ["derive", "env"] } 19 | thiserror = "1.0" 20 | anyhow = "1.0" 21 | tokio = { version = "1.15", features = ["full"] } 22 | serde = { version = "1.0", features = ["derive"] } 23 | url = { version = "2", features = ["serde"] } 24 | async-trait = "0.1" 25 | block-modes = "0.8" 26 | serde_json = "1.0" 27 | hex = "0.4" 28 | tiny-bip39 = "0.8" 29 | crossterm = "0.23" 30 | rand_core = "0.6" 31 | requestty = "0.5.0" 32 | futures = "0.3" 33 | base64 = "0.13" 34 | crypto = "0.3" 35 | whoami = "1.2" 36 | blake3 = "1.3" 37 | sha2 = "0.10.7" 38 | toml = "0.5" 39 | open = "2.1" 40 | dirs = "4.0" 41 | bs58 = "0.4" 42 | rand = "0.8" 43 | aes = "0.7" 44 | rocksdb = "0.21" 45 | flume = "0.10.14" 46 | reqwest = { version = "0.11", features = ["stream"] } 47 | 48 | dusk-wallet-core = "0.24.0-plonk.0.16-rc.2" 49 | dusk-bytes = "0.1" 50 | dusk-pki = "0.13" 51 | rusk-abi = { version = "0.12.0-rc", default-features = false } 52 | phoenix-core = { version = "0.21", features = ["alloc"] } 53 | dusk-schnorr = { version = "0.14", default-features = false } 54 | dusk-poseidon = "0.31" 55 | dusk-plonk = "0.16" 56 | dusk-bls12_381-sign = { version = "0.5", default-features = false } 57 | ff = { version = "0.13", default-features = false } 58 | poseidon-merkle = "0.3" 59 | 60 | tracing = "0.1" 61 | tracing-subscriber = { version = "0.3.0", features = [ 62 | "fmt", 63 | "env-filter", 64 | "json", 65 | ] } 66 | 67 | rkyv = { version = "=0.7.39", default-features = false } 68 | 69 | konst = "0.3" 70 | 71 | [dev-dependencies] 72 | tempfile = "3.2" 73 | 74 | [profile.release] 75 | overflow-checks = true 76 | -------------------------------------------------------------------------------- /src/bin/menu.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use core::fmt::Debug; 8 | use std::collections::HashMap; 9 | use std::hash::Hash; 10 | 11 | use requestty::question::Choice; 12 | use requestty::{Answer, DefaultSeparator, Separator}; 13 | 14 | #[derive(Clone, Debug)] 15 | pub struct Menu { 16 | items: Vec>, 17 | keys: HashMap, 18 | } 19 | 20 | impl Default for Menu 21 | where 22 | K: Eq + Hash + Debug, 23 | { 24 | fn default() -> Self { 25 | Self::new() 26 | } 27 | } 28 | 29 | impl Menu 30 | where 31 | K: Eq + Hash + Debug, 32 | { 33 | pub fn new() -> Self { 34 | Self { 35 | items: vec![], 36 | keys: HashMap::new(), 37 | } 38 | } 39 | 40 | pub fn title(title: T) -> Self 41 | where 42 | T: Into, 43 | { 44 | let title = format!("─ {:─<12}", format!("{} ", title.into())); 45 | let title = Separator(title); 46 | let items = vec![title]; 47 | let keys = HashMap::new(); 48 | 49 | Self { items, keys } 50 | } 51 | 52 | pub fn add(mut self, key: K, item: V) -> Self 53 | where 54 | V: Into>, 55 | { 56 | self.items.push(item.into()); 57 | self.keys.insert(self.items.len() - 1, key); 58 | self 59 | } 60 | 61 | pub fn separator(mut self) -> Self { 62 | self.items.push(DefaultSeparator); 63 | self 64 | } 65 | 66 | pub fn separator_msg(mut self, msg: String) -> Self { 67 | self.items.push(Separator(msg)); 68 | self 69 | } 70 | 71 | pub fn answer(&self, answer: &Answer) -> &K { 72 | let index = answer.as_list_item().unwrap().index; 73 | let key = self.keys.get(&index); 74 | key.unwrap() 75 | } 76 | 77 | pub fn extend(mut self, other: Self) -> Self { 78 | let len = self.items.len(); 79 | 80 | self.items.extend(other.items); 81 | 82 | for (key, val) in other.keys.into_iter() { 83 | self.keys.insert(key + len, val); 84 | } 85 | 86 | self 87 | } 88 | } 89 | 90 | impl IntoIterator for Menu { 91 | type Item = Choice; 92 | type IntoIter = std::vec::IntoIter>; 93 | fn into_iter(self) -> Self::IntoIter { 94 | self.items.into_iter() 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /.github/workflows/wallet_build.yml: -------------------------------------------------------------------------------- 1 | name: Compile CLI wallet binaries 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | dusk_blockchain_ref: 7 | description: "GIT branch, ref, or SHA to checkout" 8 | required: true 9 | default: "main" 10 | 11 | defaults: 12 | run: 13 | shell: bash 14 | 15 | jobs: 16 | build_and_publish: 17 | name: Build rusk-wallet binaries for ${{ matrix.os }} with ${{ matrix.compiler }}. 18 | runs-on: ${{ matrix.os }} 19 | strategy: 20 | matrix: 21 | os: [ubuntu-20.04, ubuntu-22.04, macos-latest, macos-11, windows-latest] 22 | compiler: [cargo] 23 | include: 24 | - os: ubuntu-20.04 25 | compiler: cargo 26 | target: linux-x64 27 | 28 | - os: ubuntu-22.04 29 | compiler: cargo 30 | target: linux-x64-libssl3 31 | 32 | - os: macos-latest 33 | compiler: cargo 34 | target: macos-intel 35 | 36 | - os: macos-11 37 | compiler: cargo 38 | target: macos-arm64 39 | flags: --target=aarch64-apple-darwin 40 | platform: aarch64-apple-darwin 41 | 42 | - os: windows-latest 43 | compiler: cargo 44 | target: windows-x64 45 | 46 | steps: 47 | 48 | - name: Checkout Repository 49 | uses: actions/checkout@v4 50 | with: 51 | ref: ${{ github.event.inputs.dusk_blockchain_ref }} 52 | 53 | - name: Install dependencies 54 | uses: dsherret/rust-toolchain-file@v1 55 | 56 | - name: Add arm target for Apple Silicon build 57 | run: rustup target add aarch64-apple-darwin 58 | if: ${{ matrix.os == 'macos-11' }} 59 | 60 | - name: Build Wallet 61 | shell: bash 62 | working-directory: ./ 63 | run: ${{matrix.compiler}} b --release --verbose ${{matrix.flags}} 64 | 65 | - name: Get semver from wallet binary 66 | run: | 67 | ls -la target/release 68 | export SEMVER=$(cargo pkgid | perl -lpe 's/.*\@(.*)/$1/') 69 | echo "SEMVER=$SEMVER" >> $GITHUB_ENV 70 | 71 | - name: "Pack binaries" 72 | run: | 73 | mkdir rusk-wallet${{env.SEMVER}}-${{matrix.target}} 74 | echo "Fetching changelog and readme files..." 75 | mv target/${{matrix.platform}}/release/rusk-wallet rusk-wallet${{env.SEMVER}}-${{matrix.target}} 76 | cp CHANGELOG.md rusk-wallet${{env.SEMVER}}-${{matrix.target}} 77 | cp README.md rusk-wallet${{env.SEMVER}}-${{matrix.target}} 78 | tar -czvf ruskwallet${{env.SEMVER}}-${{matrix.target}}.tar.gz rusk-wallet${{env.SEMVER}}-${{matrix.target}} 79 | ls -la *.gz 80 | 81 | - name: "Upload Wallet Artifacts" 82 | uses: actions/upload-artifact@v3 83 | with: 84 | name: wallet-binaries-${{env.SEMVER}} 85 | path: | 86 | ./*.gz 87 | retention-days: 5 -------------------------------------------------------------------------------- /src/wallet/file.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use std::fmt; 8 | use std::path::{Path, PathBuf}; 9 | use std::str::FromStr; 10 | 11 | /// Provides access to a secure wallet file 12 | pub trait SecureWalletFile { 13 | /// Returns the path 14 | fn path(&self) -> &WalletPath; 15 | /// Returns the hashed password 16 | fn pwd(&self) -> &[u8]; 17 | } 18 | 19 | /// Wrapper around `PathBuf` for wallet paths 20 | #[derive(PartialEq, Eq, Hash, Debug, Clone)] 21 | pub struct WalletPath { 22 | /// Path of the wallet file 23 | pub wallet: PathBuf, 24 | /// Directory of the profile 25 | pub profile_dir: PathBuf, 26 | /// Name of the network 27 | pub network: Option, 28 | } 29 | 30 | impl WalletPath { 31 | /// Create wallet path from the path of "wallet.dat" file. The wallet.dat 32 | /// file should be located in the profile folder, this function also 33 | /// generates the profile folder from the passed argument 34 | pub fn new(wallet: &Path) -> Self { 35 | let wallet = wallet.to_path_buf(); 36 | // The wallet should be in the profile folder 37 | let mut profile_dir = wallet.clone(); 38 | 39 | profile_dir.pop(); 40 | 41 | Self { 42 | wallet, 43 | profile_dir, 44 | network: None, 45 | } 46 | } 47 | 48 | /// Returns the filename of this path 49 | pub fn name(&self) -> Option { 50 | // extract the name 51 | let name = self.wallet.file_stem()?.to_str()?; 52 | Some(String::from(name)) 53 | } 54 | 55 | /// Returns current directory for this path 56 | pub fn dir(&self) -> Option { 57 | self.wallet.parent().map(PathBuf::from) 58 | } 59 | 60 | /// Returns a reference to the `PathBuf` holding the path 61 | pub fn inner(&self) -> &PathBuf { 62 | &self.wallet 63 | } 64 | 65 | /// Sets the network name for different cache locations. 66 | /// e.g, devnet, testnet, etc. 67 | pub fn set_network_name(&mut self, network: Option) { 68 | self.network = network; 69 | } 70 | 71 | /// Generates dir for cache based on network specified 72 | pub fn cache_dir(&self) -> PathBuf { 73 | let mut cache = self.profile_dir.clone(); 74 | 75 | if let Some(network) = &self.network { 76 | cache.push(format!("cache_{network}")); 77 | } else { 78 | cache.push("cache"); 79 | } 80 | 81 | cache 82 | } 83 | } 84 | 85 | impl FromStr for WalletPath { 86 | type Err = crate::Error; 87 | 88 | fn from_str(s: &str) -> Result { 89 | let p = Path::new(s); 90 | 91 | Ok(Self::new(p)) 92 | } 93 | } 94 | 95 | impl From for WalletPath { 96 | fn from(p: PathBuf) -> Self { 97 | Self::new(&p) 98 | } 99 | } 100 | 101 | impl From<&Path> for WalletPath { 102 | fn from(p: &Path) -> Self { 103 | Self::new(p) 104 | } 105 | } 106 | 107 | impl fmt::Display for WalletPath { 108 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 109 | write!( 110 | f, 111 | "wallet path: {}\n\rprofile dir: {}\n\rnetwork: {}", 112 | self.wallet.display(), 113 | self.profile_dir.display(), 114 | self.network.as_ref().unwrap_or(&"default".to_string()) 115 | ) 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/rusk.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use std::io::{self, Write}; 8 | 9 | use reqwest::{Body, Response}; 10 | use rkyv::Archive; 11 | 12 | use crate::Error; 13 | 14 | /// Supported Rusk version 15 | const REQUIRED_RUSK_VERSION: &str = "0.7.0"; 16 | 17 | #[derive(Debug)] 18 | /// RuskRequesst according to the rusk event system 19 | pub struct RuskRequest { 20 | topic: String, 21 | data: Vec, 22 | } 23 | 24 | impl RuskRequest { 25 | /// New RuskRequesst from topic and data 26 | pub fn new(topic: &str, data: Vec) -> Self { 27 | let topic = topic.to_string(); 28 | Self { data, topic } 29 | } 30 | 31 | /// Return the binary representation of the RuskRequesst 32 | pub fn to_bytes(&self) -> io::Result> { 33 | let mut buffer = vec![]; 34 | buffer.write_all(&(self.topic.len() as u32).to_le_bytes())?; 35 | buffer.write_all(self.topic.as_bytes())?; 36 | buffer.write_all(&self.data)?; 37 | 38 | Ok(buffer) 39 | } 40 | } 41 | #[derive(Clone)] 42 | /// Rusk HTTP Binary Client 43 | pub struct RuskHttpClient { 44 | uri: String, 45 | } 46 | 47 | impl RuskHttpClient { 48 | /// Create a new HTTP Client 49 | pub fn new(uri: String) -> Self { 50 | Self { uri } 51 | } 52 | 53 | /// Utility for querying the rusk VM 54 | pub async fn contract_query( 55 | &self, 56 | contract: &str, 57 | method: &str, 58 | value: &I, 59 | ) -> Result, Error> 60 | where 61 | I: Archive, 62 | I: rkyv::Serialize>, 63 | { 64 | let data = rkyv::to_bytes(value).map_err(|_| Error::Rkyv)?.to_vec(); 65 | let request = RuskRequest::new(method, data); 66 | 67 | let response = self.call_raw(1, contract, &request, false).await?; 68 | 69 | Ok(response.bytes().await?.to_vec()) 70 | } 71 | 72 | /// Check rusk connection 73 | pub async fn check_connection(&self) -> Result<(), reqwest::Error> { 74 | reqwest::Client::new().post(&self.uri).send().await?; 75 | Ok(()) 76 | } 77 | 78 | /// Send a RuskRequest to a specific target. 79 | /// 80 | /// The response is interpreted as Binary 81 | pub async fn call( 82 | &self, 83 | target_type: u8, 84 | target: &str, 85 | request: &RuskRequest, 86 | ) -> Result, Error> { 87 | let response = 88 | self.call_raw(target_type, target, request, false).await?; 89 | let data = response.bytes().await?; 90 | Ok(data.to_vec()) 91 | } 92 | /// Send a RuskRequest to a specific target without parsing the response 93 | pub async fn call_raw( 94 | &self, 95 | target_type: u8, 96 | target: &str, 97 | request: &RuskRequest, 98 | feed: bool, 99 | ) -> Result { 100 | let uri = &self.uri; 101 | let client = reqwest::Client::new(); 102 | let mut request = client 103 | .post(format!("{uri}/{target_type}/{target}")) 104 | .body(Body::from(request.to_bytes()?)) 105 | .header("Content-Type", "application/octet-stream") 106 | .header("rusk-version", REQUIRED_RUSK_VERSION); 107 | 108 | if feed { 109 | request = request.header("Rusk-Feeder", "1"); 110 | } 111 | let response = request.send().await?; 112 | 113 | let status = response.status(); 114 | if status.is_client_error() || status.is_server_error() { 115 | let error = &response.bytes().await?; 116 | 117 | let error = String::from_utf8(error.to_vec()) 118 | .unwrap_or("unparsable error".into()); 119 | 120 | let msg = format!("{status}: {error}"); 121 | 122 | Err(Error::Rusk(msg)) 123 | } else { 124 | Ok(response) 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/wallet/address.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use crate::Error; 8 | use dusk_bytes::{DeserializableSlice, Error as BytesError, Serializable}; 9 | use dusk_pki::PublicSpendKey; 10 | use std::fmt; 11 | use std::hash::Hasher; 12 | use std::str::FromStr; 13 | 14 | #[derive(Clone, Eq)] 15 | /// A public address within the Dusk Network 16 | pub struct Address { 17 | pub(crate) index: Option, 18 | pub(crate) psk: PublicSpendKey, 19 | } 20 | 21 | impl Address { 22 | pub(crate) fn new(index: u8, psk: PublicSpendKey) -> Self { 23 | Self { 24 | index: Some(index), 25 | psk, 26 | } 27 | } 28 | 29 | /// Returns true if the current user owns this address 30 | pub fn is_owned(&self) -> bool { 31 | self.index.is_some() 32 | } 33 | 34 | pub(crate) fn psk(&self) -> &PublicSpendKey { 35 | &self.psk 36 | } 37 | 38 | pub(crate) fn index(&self) -> Result { 39 | self.index.ok_or(Error::AddressNotOwned) 40 | } 41 | 42 | /// A trimmed version of the address to display as preview 43 | pub fn preview(&self) -> String { 44 | let addr = bs58::encode(self.psk.to_bytes()).into_string(); 45 | format!("{}...{}", &addr[..7], &addr[addr.len() - 7..]) 46 | } 47 | } 48 | 49 | impl FromStr for Address { 50 | type Err = Error; 51 | 52 | fn from_str(s: &str) -> Result { 53 | let bytes = bs58::decode(s).into_vec()?; 54 | 55 | let psk = PublicSpendKey::from_reader(&mut &bytes[..]) 56 | .map_err(|_| Error::BadAddress)?; 57 | 58 | let addr = Address { index: None, psk }; 59 | 60 | Ok(addr) 61 | } 62 | } 63 | 64 | impl TryFrom for Address { 65 | type Error = Error; 66 | 67 | fn try_from(s: String) -> Result { 68 | Address::from_str(s.as_str()) 69 | } 70 | } 71 | 72 | impl TryFrom<&[u8; PublicSpendKey::SIZE]> for Address { 73 | type Error = Error; 74 | 75 | fn try_from( 76 | bytes: &[u8; PublicSpendKey::SIZE], 77 | ) -> Result { 78 | let addr = Address { 79 | index: None, 80 | psk: dusk_pki::PublicSpendKey::from_bytes(bytes)?, 81 | }; 82 | Ok(addr) 83 | } 84 | } 85 | 86 | impl PartialEq for Address { 87 | fn eq(&self, other: &Self) -> bool { 88 | self.index == other.index && self.psk == other.psk 89 | } 90 | } 91 | 92 | impl std::hash::Hash for Address { 93 | fn hash(&self, state: &mut H) { 94 | self.index.hash(state); 95 | self.psk.to_bytes().hash(state); 96 | } 97 | } 98 | 99 | impl fmt::Display for Address { 100 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 101 | write!(f, "{}", bs58::encode(self.psk.to_bytes()).into_string()) 102 | } 103 | } 104 | 105 | impl fmt::Debug for Address { 106 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 107 | write!(f, "{}", bs58::encode(self.psk.to_bytes()).into_string()) 108 | } 109 | } 110 | 111 | /// Addresses holds address-related metadata that needs to be 112 | /// persisted in the wallet file. 113 | pub(crate) struct Addresses { 114 | pub(crate) count: u8, 115 | } 116 | 117 | impl Default for Addresses { 118 | fn default() -> Self { 119 | Self { count: 1 } 120 | } 121 | } 122 | 123 | impl Serializable<1> for Addresses { 124 | type Error = BytesError; 125 | 126 | fn from_bytes(buf: &[u8; Addresses::SIZE]) -> Result 127 | where 128 | Self: Sized, 129 | { 130 | Ok(Self { count: buf[0] }) 131 | } 132 | 133 | fn to_bytes(&self) -> [u8; Addresses::SIZE] { 134 | [self.count] 135 | } 136 | } 137 | 138 | #[test] 139 | fn addresses_serde() -> Result<(), Box> { 140 | let addrs = Addresses { count: 6 }; 141 | let read = Addresses::from_bytes(&addrs.to_bytes()) 142 | .map_err(|_| Error::WalletFileCorrupted)?; 143 | assert!(read.count == addrs.count); 144 | Ok(()) 145 | } 146 | -------------------------------------------------------------------------------- /src/clients/sync.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use std::mem::size_of; 8 | 9 | use dusk_plonk::prelude::BlsScalar; 10 | use dusk_wallet_core::Store; 11 | use futures::StreamExt; 12 | use phoenix_core::transaction::{ArchivedTreeLeaf, TreeLeaf}; 13 | 14 | use crate::block::Block; 15 | use crate::clients::{Cache, TRANSFER_CONTRACT}; 16 | use crate::rusk::RuskHttpClient; 17 | use crate::store::LocalStore; 18 | use crate::{Error, RuskRequest, MAX_ADDRESSES}; 19 | 20 | const RKYV_TREE_LEAF_SIZE: usize = size_of::(); 21 | 22 | pub(crate) async fn sync_db( 23 | client: &RuskHttpClient, 24 | store: &LocalStore, 25 | cache: &Cache, 26 | status: F, 27 | ) -> Result<(), Error> { 28 | let addresses: Vec<_> = (0..MAX_ADDRESSES) 29 | .flat_map(|i| store.retrieve_ssk(i as u64)) 30 | .map(|ssk| { 31 | let vk = ssk.view_key(); 32 | let psk = vk.public_spend_key(); 33 | (ssk, vk, psk) 34 | }) 35 | .collect(); 36 | 37 | status("Getting cached note position..."); 38 | 39 | let last_pos = cache.last_pos()?; 40 | let pos_to_search = last_pos.map(|p| p + 1).unwrap_or_default(); 41 | let mut last_pos = last_pos.unwrap_or_default(); 42 | 43 | status("Fetching fresh notes..."); 44 | 45 | let req = rkyv::to_bytes::<_, 8>(&(pos_to_search)) 46 | .map_err(|_| Error::Rkyv)? 47 | .to_vec(); 48 | 49 | let mut stream = client 50 | .call_raw( 51 | 1, 52 | TRANSFER_CONTRACT, 53 | &RuskRequest::new("leaves_from_pos", req), 54 | true, 55 | ) 56 | .await? 57 | .bytes_stream(); 58 | 59 | status("Connection established..."); 60 | 61 | status("Streaming notes..."); 62 | 63 | // This buffer is needed because `.bytes_stream();` introduce additional 64 | // spliting of chunks according to it's own buffer 65 | let mut buffer = vec![]; 66 | 67 | while let Some(http_chunk) = stream.next().await { 68 | buffer.extend_from_slice(&http_chunk?); 69 | 70 | let mut leaf_chunk = buffer.chunks_exact(RKYV_TREE_LEAF_SIZE); 71 | 72 | for leaf_bytes in leaf_chunk.by_ref() { 73 | let TreeLeaf { block_height, note } = 74 | rkyv::from_bytes(leaf_bytes).map_err(|_| Error::Rkyv)?; 75 | 76 | last_pos = std::cmp::max(last_pos, *note.pos()); 77 | 78 | for (ssk, vk, psk) in addresses.iter() { 79 | if vk.owns(¬e) { 80 | let nullifier = note.gen_nullifier(ssk); 81 | let spent = 82 | fetch_existing_nullifiers_remote(client, &[nullifier]) 83 | .wait()? 84 | .first() 85 | .is_some(); 86 | let note = (note, nullifier); 87 | match spent { 88 | true => cache.insert_spent(psk, block_height, note), 89 | false => cache.insert(psk, block_height, note), 90 | }?; 91 | 92 | break; 93 | } 94 | } 95 | cache.insert_last_pos(last_pos)?; 96 | } 97 | 98 | buffer = leaf_chunk.remainder().to_vec(); 99 | } 100 | 101 | // Remove spent nullifiers from live notes 102 | for (_, _, psk) in addresses { 103 | let nullifiers = cache.unspent_notes_id(&psk)?; 104 | 105 | if !nullifiers.is_empty() { 106 | let existing = 107 | fetch_existing_nullifiers_remote(client, &nullifiers).wait()?; 108 | cache.spend_notes(&psk, &existing)?; 109 | } 110 | } 111 | Ok(()) 112 | } 113 | 114 | /// Asks the node to return the nullifiers that already exist from the given 115 | /// nullifiers. 116 | pub(crate) async fn fetch_existing_nullifiers_remote( 117 | client: &RuskHttpClient, 118 | nullifiers: &[BlsScalar], 119 | ) -> Result, Error> { 120 | if nullifiers.is_empty() { 121 | return Ok(vec![]); 122 | } 123 | let nullifiers = nullifiers.to_vec(); 124 | let data = client 125 | .contract_query::<_, 1024>( 126 | TRANSFER_CONTRACT, 127 | "existing_nullifiers", 128 | &nullifiers, 129 | ) 130 | .await?; 131 | 132 | let nullifiers = rkyv::from_bytes(&data).map_err(|_| Error::Rkyv)?; 133 | 134 | Ok(nullifiers) 135 | } 136 | -------------------------------------------------------------------------------- /src/bin/README.md: -------------------------------------------------------------------------------- 1 | # Dusk Wallet CLI 2 | 3 | A user-friendly, reliable command line interface to the Dusk wallet! 4 | 5 | ``` 6 | USAGE: 7 | rusk-wallet [OPTIONS] [SUBCOMMAND] 8 | 9 | OPTIONS: 10 | -p, --profile Directory to store user data [default: `$HOME/.dusk/rusk-wallet`] 11 | -n, --network Network to connect to 12 | --password Set the password for wallet's creation [env: 13 | RUSK_WALLET_PWD=password] 14 | --state The state server fully qualified URL 15 | --prover The prover server fully qualified URL 16 | --log-level Output log level [default: info] [possible values: trace, debug, 17 | info, warn, error] 18 | --log-type Logging output type [default: coloured] [possible values: json, 19 | plain, coloured] 20 | -h, --help Print help information 21 | -V, --version Print version information 22 | 23 | SUBCOMMANDS: 24 | create Create a new wallet 25 | restore Restore a lost wallet 26 | balance Check your current balance 27 | addresses List your existing addresses and generate new ones 28 | history Show address transaction history 29 | transfer Send DUSK through the network 30 | stake Start staking DUSK 31 | stake-info Check your stake information 32 | unstake Unstake a key's stake 33 | withdraw Withdraw accumulated reward for a stake key 34 | export Export BLS provisioner key pair 35 | settings Show current settings 36 | help Print this message or the help of the given subcommand(s) 37 | ``` 38 | 39 | ## Good to know 40 | 41 | Some commands can be run in standalone (offline) operation: 42 | 43 | - `create`: Create a new wallet 44 | - `restore`: Access (and restore) a lost wallet 45 | - `addresses`: Retrieve your addresses 46 | - `export`: Export BLS provisioner key pair 47 | 48 | All other commands involve transactions, and thus require an active connection to [**Rusk**](https://github.com/dusk-network/rusk). 49 | 50 | ## Installation 51 | 52 | [Install rust](https://www.rust-lang.org/tools/install) and then: 53 | 54 | ``` 55 | git clone git@github.com:dusk-network/wallet-cli.git 56 | cd wallet-cli 57 | make install 58 | ``` 59 | 60 | ## Configuring the CLI Wallet 61 | 62 | You will need to connect to a running [**Rusk**](https://github.com/dusk-network/rusk) instance for full wallet capabilities. 63 | 64 | The default settings can be seen [here](https://github.com/dusk-network/wallet-cli/blob/main/default.config.toml). 65 | 66 | It's possible to override those settings by create a `config.toml` file with the same structure, in one of the following 67 | directory: 68 | 69 | - The profile folder (provided via the `--profile` argument, defaults to `$HOME/.dusk/rusk-wallet/`) 70 | - The global configuration folder (`$HOME/.config/rusk-wallet/`) 71 | 72 | Having the `config.toml` in the global configuration folder is useful in case of multiple wallets (each one with its own profile folder) that shares the same settings. 73 | 74 | If a `config.toml` exists in both locations, the one found in the profile folder will be used. 75 | 76 | The CLI arguments takes precedence and overrides any configuration present in the configuration file. 77 | 78 | **Note:** When using Windows, connection will default to TCP/IP even if UDS is explicitly specified. 79 | 80 | ## Running the CLI Wallet 81 | 82 | ### Interactive mode 83 | 84 | By default, the CLI runs in interactive mode when no arguments are provided. 85 | 86 | ``` 87 | rusk-wallet 88 | ``` 89 | 90 | ### Headless mode 91 | 92 | Wallet can be run in headless mode by providing all the options required for a given subcommand. It is usually convenient to have a config file with the wallet settings, and then call the wallet with the desired subcommand and its options. 93 | 94 | To explore available options and commands, use the `help` command: 95 | 96 | ``` 97 | rusk-wallet help 98 | ``` 99 | 100 | To further explore any specific command you can use `--help` on the command itself. For example, the following command will print all the information about the `stake` subcommand: 101 | 102 | ``` 103 | rusk-wallet stake --help 104 | ``` 105 | 106 | By default, you will always be prompted to enter the wallet password. To prevent this behavior, you can provide the password using the `RUSK_WALLET_PWD` environment variable. This is useful in CI or any other headless environment. 107 | 108 | Please note that `RUSK_WALLET_PWD` is effectively used for: 109 | 110 | - Wallet decryption (in all commands that use a wallet) 111 | - Wallet encryption (in `create`) 112 | - BLS key encryption (in `export`) 113 | -------------------------------------------------------------------------------- /src/bin/command/history.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use std::collections::hash_map::Entry; 8 | use std::collections::HashMap; 9 | use std::fmt::{self, Display}; 10 | 11 | use dusk_wallet::DecodedNote; 12 | use dusk_wallet_core::Transaction; 13 | use rusk_abi::dusk; 14 | 15 | use crate::io::{self, GraphQL}; 16 | use crate::settings::Settings; 17 | 18 | pub struct TransactionHistory { 19 | direction: TransactionDirection, 20 | height: u64, 21 | amount: f64, 22 | fee: u64, 23 | pub tx: Transaction, 24 | id: String, 25 | } 26 | 27 | impl TransactionHistory { 28 | pub fn header() -> String { 29 | format!( 30 | "{: ^9} | {: ^64} | {: ^8} | {: ^17} | {: ^12}", 31 | "BLOCK", "TX_ID", "METHOD", "AMOUNT", "FEE" 32 | ) 33 | } 34 | } 35 | 36 | impl Display for TransactionHistory { 37 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 38 | let dusk = self.amount / dusk::dusk(1.0) as f64; 39 | let contract = match self.tx.call() { 40 | None => "transfer", 41 | Some((_, method, _)) => method, 42 | }; 43 | 44 | let fee = match self.direction { 45 | TransactionDirection::In => "".into(), 46 | TransactionDirection::Out => { 47 | let fee = self.fee; 48 | let fee = dusk::from_dusk(fee); 49 | format!("{: >12.9}", fee) 50 | } 51 | }; 52 | 53 | let tx_id = &self.id; 54 | let heigth = self.height; 55 | 56 | write!( 57 | f, 58 | "{heigth: >9} | {tx_id} | {contract: ^8} | {dusk: >+17.9} | {fee}", 59 | ) 60 | } 61 | } 62 | 63 | pub(crate) async fn transaction_from_notes( 64 | settings: &Settings, 65 | mut notes: Vec, 66 | ) -> anyhow::Result> { 67 | notes.sort_by(|a, b| a.note.pos().cmp(b.note.pos())); 68 | let mut ret: Vec = vec![]; 69 | let gql = GraphQL::new(settings.state.to_string(), io::status::interactive); 70 | 71 | let nullifiers = notes 72 | .iter() 73 | .flat_map(|note| { 74 | note.nullified_by.map(|nullifier| (nullifier, note.amount)) 75 | }) 76 | .collect::>(); 77 | 78 | let mut block_txs = HashMap::new(); 79 | 80 | for mut decoded_note in notes { 81 | // Set the position to max, in order to match the note with the one 82 | // in the tx 83 | decoded_note.note.set_pos(u64::MAX); 84 | 85 | let note_amount = decoded_note.amount as f64; 86 | 87 | let txs = match block_txs.entry(decoded_note.block_height) { 88 | Entry::Occupied(o) => o.into_mut(), 89 | Entry::Vacant(v) => { 90 | let txs = gql.txs_for_block(decoded_note.block_height).await?; 91 | v.insert(txs) 92 | } 93 | }; 94 | 95 | let note_hash = decoded_note.note.hash(); 96 | // Looking for the transaction which created the note 97 | let note_creator = txs.iter().find(|(t, _, _)| { 98 | t.outputs().iter().any(|&n| n.hash().eq(¬e_hash)) 99 | || t.nullifiers 100 | .iter() 101 | .any(|tx_null| nullifiers.iter().any(|(n, _)| n == tx_null)) 102 | }); 103 | 104 | if let Some((t, tx_id, gas_spent)) = note_creator { 105 | let inputs_amount: f64 = t 106 | .nullifiers() 107 | .iter() 108 | .filter_map(|input| { 109 | nullifiers.iter().find_map(|n| n.0.eq(input).then_some(n.1)) 110 | }) 111 | .sum::() as f64; 112 | 113 | let direction = match inputs_amount > 0f64 { 114 | true => TransactionDirection::Out, 115 | false => TransactionDirection::In, 116 | }; 117 | match ret.iter_mut().find(|th| &th.id == tx_id) { 118 | Some(tx) => tx.amount += note_amount, 119 | None => ret.push(TransactionHistory { 120 | direction, 121 | height: decoded_note.block_height, 122 | amount: note_amount - inputs_amount, 123 | fee: gas_spent * t.fee().gas_price, 124 | tx: t.clone(), 125 | id: tx_id.clone(), 126 | }), 127 | } 128 | } else { 129 | let outgoing_tx = ret.iter_mut().find(|th| { 130 | th.direction == TransactionDirection::Out 131 | && th.height == decoded_note.block_height 132 | }); 133 | 134 | match outgoing_tx { 135 | // Outgoing txs found, this should be the change or any 136 | // other output created by the tx result 137 | // (like withdraw or unstake) 138 | Some(th) => th.amount += note_amount, 139 | 140 | // No outgoing txs found, this note should belong to a 141 | // preconfigured genesis state 142 | None => println!("??? val {}", note_amount), 143 | } 144 | } 145 | } 146 | ret.sort_by(|a, b| a.height.cmp(&b.height)); 147 | Ok(ret) 148 | } 149 | 150 | #[derive(PartialEq)] 151 | enum TransactionDirection { 152 | In, 153 | Out, 154 | } 155 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use crate::clients::StateStore; 8 | use crate::store::LocalStore; 9 | use phoenix_core::Error as PhoenixError; 10 | use rand_core::Error as RngError; 11 | use std::io; 12 | use std::str::Utf8Error; 13 | 14 | use super::clients; 15 | /// Wallet core error 16 | pub(crate) type CoreError = 17 | dusk_wallet_core::Error; 18 | 19 | /// Errors returned by this library 20 | #[derive(Debug, thiserror::Error)] 21 | pub enum Error { 22 | /// Command not available in offline mode 23 | #[error("This command cannot be performed while offline")] 24 | Offline, 25 | /// Unauthorized access to this address 26 | #[error("Unauthorized access to this address")] 27 | Unauthorized, 28 | /// Rusk error 29 | #[error("Rusk error occurred: {0}")] 30 | Rusk(String), 31 | /// Filesystem errors 32 | #[error(transparent)] 33 | IO(#[from] io::Error), 34 | /// JSON serialization errors 35 | #[error(transparent)] 36 | Json(#[from] serde_json::Error), 37 | /// Bytes encoding errors 38 | #[error("A serialization error occurred: {0:?}")] 39 | Bytes(dusk_bytes::Error), 40 | /// Base58 errors 41 | #[error(transparent)] 42 | Base58(#[from] bs58::decode::Error), 43 | /// Rkyv errors 44 | #[error("A serialization error occurred.")] 45 | Rkyv, 46 | /// Reqwest errors 47 | #[error("A request error occurred: {0}")] 48 | Reqwest(#[from] reqwest::Error), 49 | /// Utf8 errors 50 | #[error("Utf8 error: {0:?}")] 51 | Utf8(Utf8Error), 52 | /// Random number generator errors 53 | #[error(transparent)] 54 | Rng(#[from] RngError), 55 | /// Transaction model errors 56 | #[error("An error occurred in Phoenix: {0:?}")] 57 | Phoenix(PhoenixError), 58 | /// Not enough balance to perform transaction 59 | #[error("Insufficient balance to perform this operation")] 60 | NotEnoughBalance, 61 | /// Amount to transfer/stake cannot be zero 62 | #[error("Amount to transfer/stake cannot be zero")] 63 | AmountIsZero, 64 | /// Note combination for the given value is impossible given the maximum 65 | /// amount of inputs in a transaction 66 | #[error("Impossible notes' combination for the given value is")] 67 | NoteCombinationProblem, 68 | /// Not enough gas to perform this transaction 69 | #[error("Not enough gas to perform this transaction")] 70 | NotEnoughGas, 71 | /// A stake already exists for this key 72 | #[error("A stake already exists for this key")] 73 | AlreadyStaked, 74 | /// A stake does not exist for this key 75 | #[error("A stake does not exist for this key")] 76 | NotStaked, 77 | /// No reward available for this key 78 | #[error("No reward available for this key")] 79 | NoReward, 80 | /// Invalid address 81 | #[error("Invalid address")] 82 | BadAddress, 83 | /// Address does not belong to this wallet 84 | #[error("Address does not belong to this wallet")] 85 | AddressNotOwned, 86 | /// Recovery phrase is not valid 87 | #[error("Invalid recovery phrase")] 88 | InvalidMnemonicPhrase, 89 | /// Path provided is not a directory 90 | #[error("Path provided is not a directory")] 91 | NotDirectory, 92 | /// Wallet file content is not valid 93 | #[error("Wallet file content is not valid")] 94 | WalletFileCorrupted, 95 | /// File version not recognized 96 | #[error("File version {0}.{1} not recognized")] 97 | UnknownFileVersion(u8, u8), 98 | /// A wallet file with this name already exists 99 | #[error("A wallet file with this name already exists")] 100 | WalletFileExists, 101 | /// Wallet file is missing 102 | #[error("Wallet file is missing")] 103 | WalletFileMissing, 104 | /// Wrong wallet password 105 | #[error("Invalid password")] 106 | BlockMode(#[from] block_modes::BlockModeError), 107 | /// Reached the maximum number of attempts 108 | #[error("Reached the maximum number of attempts")] 109 | AttemptsExhausted, 110 | /// Status callback needs to be set before connecting 111 | #[error("Status callback needs to be set before connecting")] 112 | StatusWalletConnected, 113 | /// Transaction error 114 | #[error("Transaction error: {0}")] 115 | Transaction(String), 116 | /// Rocksdb cache database error 117 | #[error("Rocks cache database error: {0}")] 118 | RocksDB(rocksdb::Error), 119 | /// Provided Network not found 120 | #[error( 121 | "Network not found, check config.toml, specify network with -n flag" 122 | )] 123 | NetworkNotFound, 124 | /// The cache database couldn't find column family required 125 | #[error("Cache database corrupted")] 126 | CacheDatabaseCorrupted, 127 | } 128 | 129 | impl From for Error { 130 | fn from(e: dusk_bytes::Error) -> Self { 131 | Self::Bytes(e) 132 | } 133 | } 134 | 135 | impl From for Error { 136 | fn from(_: block_modes::InvalidKeyIvLength) -> Self { 137 | Self::WalletFileCorrupted 138 | } 139 | } 140 | 141 | impl From for Error { 142 | fn from(e: CoreError) -> Self { 143 | use dusk_wallet_core::Error::*; 144 | match e { 145 | Store(err) | State(err) | Prover(err) => err, 146 | Rkyv => Self::Rkyv, 147 | Rng(err) => Self::Rng(err), 148 | Bytes(err) => Self::Bytes(err), 149 | Phoenix(err) => Self::Phoenix(err), 150 | NotEnoughBalance => Self::NotEnoughBalance, 151 | NoteCombinationProblem => Self::NoteCombinationProblem, 152 | AlreadyStaked { .. } => Self::AlreadyStaked, 153 | NotStaked { .. } => Self::NotStaked, 154 | NoReward { .. } => Self::NoReward, 155 | Utf8(err) => Self::Utf8(err.utf8_error()), 156 | } 157 | } 158 | } 159 | 160 | impl From for Error { 161 | fn from(e: rocksdb::Error) -> Self { 162 | Self::RocksDB(e) 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /src/bin/settings.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use crate::config::Network; 8 | use crate::io::WalletArgs; 9 | 10 | use dusk_wallet::Error; 11 | use std::fmt; 12 | use std::path::PathBuf; 13 | 14 | use tracing::Level; 15 | use url::Url; 16 | 17 | #[derive(clap::ValueEnum, Debug, Clone)] 18 | pub(crate) enum LogFormat { 19 | Json, 20 | Plain, 21 | Coloured, 22 | } 23 | 24 | #[derive(clap::ValueEnum, Debug, Clone)] 25 | pub(crate) enum LogLevel { 26 | /// Designates very low priority, often extremely verbose, information. 27 | Trace, 28 | /// Designates lower priority information. 29 | Debug, 30 | /// Designates useful information. 31 | Info, 32 | /// Designates hazardous situations. 33 | Warn, 34 | /// Designates very serious errors. 35 | Error, 36 | } 37 | 38 | #[derive(Debug)] 39 | pub(crate) struct Logging { 40 | /// Max log level 41 | pub level: LogLevel, 42 | /// Log format 43 | pub format: LogFormat, 44 | } 45 | 46 | #[allow(dead_code)] 47 | #[derive(Debug)] 48 | pub(crate) struct Settings { 49 | pub(crate) state: Url, 50 | pub(crate) prover: Url, 51 | pub(crate) explorer: Option, 52 | 53 | pub(crate) logging: Logging, 54 | 55 | pub(crate) profile: PathBuf, 56 | pub(crate) password: Option, 57 | } 58 | 59 | pub(crate) struct SettingsBuilder { 60 | profile: PathBuf, 61 | pub(crate) args: WalletArgs, 62 | } 63 | 64 | impl SettingsBuilder { 65 | pub fn profile(&self) -> &PathBuf { 66 | &self.profile 67 | } 68 | 69 | pub fn network(self, network: Network) -> Result { 70 | let args = self.args; 71 | 72 | let network = match (args.network, network.clone().network) { 73 | (Some(label), Some(mut networks)) => { 74 | let r = networks.remove(&label); 75 | // err if specified network is not in the list 76 | if r.is_none() { 77 | return Err(Error::BadAddress); 78 | } 79 | 80 | r 81 | } 82 | // err if no networks are specified but argument is 83 | (Some(_), None) => { 84 | return Err(Error::BadAddress); 85 | } 86 | (_, _) => None, 87 | } 88 | .unwrap_or(network); 89 | 90 | let state = args 91 | .state 92 | .as_ref() 93 | .and_then(|value| Url::parse(value).ok()) 94 | .unwrap_or(network.state); 95 | 96 | let prover = args 97 | .prover 98 | .as_ref() 99 | .and_then(|value| Url::parse(value).ok()) 100 | .unwrap_or(network.prover); 101 | 102 | let explorer = network.explorer; 103 | 104 | let profile = args.profile.as_ref().cloned().unwrap_or(self.profile); 105 | 106 | let password = args.password; 107 | 108 | let logging = Logging { 109 | level: args.log_level, 110 | format: args.log_type, 111 | }; 112 | 113 | Ok(Settings { 114 | state, 115 | prover, 116 | explorer, 117 | logging, 118 | profile, 119 | password, 120 | }) 121 | } 122 | } 123 | 124 | impl Settings { 125 | pub fn args(args: WalletArgs) -> SettingsBuilder { 126 | let profile = if let Some(path) = &args.profile { 127 | path.clone() 128 | } else { 129 | let mut path = dirs::home_dir().expect("OS not supported"); 130 | path.push(".dusk"); 131 | path.push(env!("CARGO_BIN_NAME")); 132 | path 133 | }; 134 | 135 | SettingsBuilder { profile, args } 136 | } 137 | } 138 | 139 | impl From<&LogLevel> for Level { 140 | fn from(level: &LogLevel) -> Level { 141 | match level { 142 | LogLevel::Trace => Level::TRACE, 143 | LogLevel::Debug => Level::DEBUG, 144 | LogLevel::Info => Level::INFO, 145 | LogLevel::Warn => Level::WARN, 146 | LogLevel::Error => Level::ERROR, 147 | } 148 | } 149 | } 150 | 151 | impl fmt::Display for LogFormat { 152 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 153 | write!( 154 | f, 155 | "{}", 156 | match self { 157 | Self::Json => "json", 158 | Self::Plain => "plain", 159 | Self::Coloured => "coloured", 160 | } 161 | ) 162 | } 163 | } 164 | 165 | impl fmt::Display for LogLevel { 166 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 167 | write!( 168 | f, 169 | "{}", 170 | match self { 171 | Self::Trace => "trace", 172 | Self::Debug => "debug", 173 | Self::Info => "info", 174 | Self::Warn => "warn", 175 | Self::Error => "error", 176 | } 177 | ) 178 | } 179 | } 180 | 181 | impl fmt::Display for Logging { 182 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 183 | write!(f, "Logging: [{}] ({})", self.level, self.format) 184 | } 185 | } 186 | 187 | impl fmt::Display for Settings { 188 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 189 | let separator = "─".repeat(14); 190 | writeln!(f, "{separator}")?; 191 | writeln!(f, "Settings")?; 192 | writeln!(f, "{separator}")?; 193 | writeln!(f, "Profile: {}", self.profile.display())?; 194 | writeln!( 195 | f, 196 | "Password: {}", 197 | if self.password.is_some() { 198 | "[Set]" 199 | } else { 200 | "[Not set]" 201 | } 202 | )?; 203 | writeln!(f, "{}", separator)?; 204 | writeln!(f, "state: {}", self.state)?; 205 | writeln!(f, "prover: {}", self.prover)?; 206 | 207 | if let Some(explorer) = &self.explorer { 208 | writeln!(f, "explorer: {explorer}")?; 209 | } 210 | 211 | writeln!(f, "{separator}")?; 212 | writeln!(f, "{}", self.logging) 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /src/bin/io/gql.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use dusk_wallet_core::Transaction; 8 | use tokio::time::{sleep, Duration}; 9 | 10 | use dusk_wallet::{Error, RuskHttpClient, RuskRequest}; 11 | use serde::Deserialize; 12 | 13 | /// GraphQL is a helper struct that aggregates all queries done 14 | /// to the Dusk GraphQL database. 15 | /// This helps avoid having helper structs and boilerplate code 16 | /// mixed with the wallet logic. 17 | #[derive(Clone)] 18 | pub struct GraphQL { 19 | client: RuskHttpClient, 20 | status: fn(&str), 21 | } 22 | 23 | #[derive(Deserialize)] 24 | struct SpentTx { 25 | pub id: String, 26 | #[serde(default)] 27 | pub raw: String, 28 | pub err: Option, 29 | #[serde(alias = "gasSpent", default)] 30 | pub gas_spent: f64, 31 | } 32 | #[derive(Deserialize)] 33 | struct Block { 34 | pub transactions: Vec, 35 | } 36 | 37 | #[derive(Deserialize)] 38 | struct BlockResponse { 39 | pub block: Option, 40 | } 41 | 42 | #[derive(Deserialize)] 43 | struct SpentTxResponse { 44 | pub tx: Option, 45 | } 46 | 47 | /// Transaction status 48 | #[derive(Debug)] 49 | pub enum TxStatus { 50 | Ok, 51 | NotFound, 52 | Error(String), 53 | } 54 | 55 | impl GraphQL { 56 | /// Create a new GraphQL wallet client 57 | pub fn new(url: S, status: fn(&str)) -> Self 58 | where 59 | S: Into, 60 | { 61 | Self { 62 | client: RuskHttpClient::new(url.into()), 63 | status, 64 | } 65 | } 66 | 67 | /// Wait for a transaction to be confirmed (included in a block) 68 | pub async fn wait_for(&self, tx_id: &str) -> anyhow::Result<()> { 69 | loop { 70 | let status = self.tx_status(tx_id).await?; 71 | 72 | match status { 73 | TxStatus::Ok => break, 74 | TxStatus::Error(err) => return Err(Error::Transaction(err))?, 75 | TxStatus::NotFound => { 76 | (self.status)( 77 | "Waiting for tx to be included into a block...", 78 | ); 79 | sleep(Duration::from_millis(1000)).await; 80 | } 81 | } 82 | } 83 | Ok(()) 84 | } 85 | 86 | /// Obtain transaction status 87 | async fn tx_status( 88 | &self, 89 | tx_id: &str, 90 | ) -> anyhow::Result { 91 | let query = 92 | "query { tx(hash: \"####\") { id, err }}".replace("####", tx_id); 93 | let response = self.query(&query).await?; 94 | let response = serde_json::from_slice::(&response)?.tx; 95 | 96 | match response { 97 | Some(SpentTx { err: Some(err), .. }) => Ok(TxStatus::Error(err)), 98 | Some(_) => Ok(TxStatus::Ok), 99 | None => Ok(TxStatus::NotFound), 100 | } 101 | } 102 | 103 | /// Obtain transactions inside a block 104 | pub async fn txs_for_block( 105 | &self, 106 | block_height: u64, 107 | ) -> anyhow::Result, GraphQLError> { 108 | let query = "query { block(height: ####) { transactions {id, raw, gasSpent, err}}}" 109 | .replace("####", block_height.to_string().as_str()); 110 | 111 | let response = self.query(&query).await?; 112 | let response = 113 | serde_json::from_slice::(&response)?.block; 114 | let block = response.ok_or(GraphQLError::BlockInfo)?; 115 | let mut ret = vec![]; 116 | 117 | for spent_tx in block.transactions { 118 | let tx_raw = hex::decode(&spent_tx.raw) 119 | .map_err(|_| GraphQLError::TxStatus)?; 120 | let ph_tx = Transaction::from_slice(&tx_raw).unwrap(); 121 | ret.push((ph_tx, spent_tx.id, spent_tx.gas_spent as u64)); 122 | } 123 | Ok(ret) 124 | } 125 | } 126 | 127 | /// Errors generated from GraphQL 128 | #[derive(Debug, thiserror::Error)] 129 | pub enum GraphQLError { 130 | /// Generic errors 131 | #[error("Error fetching data from the node: {0}")] 132 | Generic(dusk_wallet::Error), 133 | /// Failed to fetch transaction status 134 | #[error("Failed to obtain transaction status")] 135 | TxStatus, 136 | #[error("Failed to obtain block info")] 137 | BlockInfo, 138 | } 139 | 140 | impl From for GraphQLError { 141 | fn from(e: dusk_wallet::Error) -> Self { 142 | Self::Generic(e) 143 | } 144 | } 145 | 146 | impl From for GraphQLError { 147 | fn from(e: serde_json::Error) -> Self { 148 | Self::Generic(e.into()) 149 | } 150 | } 151 | 152 | impl GraphQL { 153 | pub async fn query( 154 | &self, 155 | query: &str, 156 | ) -> Result, dusk_wallet::Error> { 157 | let request = RuskRequest::new("gql", query.as_bytes().to_vec()); 158 | self.client.call(2, "Chain", &request).await 159 | } 160 | } 161 | 162 | #[ignore = "Leave it here just for manual tests"] 163 | #[tokio::test] 164 | async fn test() -> Result<(), Box> { 165 | let gql = GraphQL { 166 | status: |s| { 167 | println!("{s}"); 168 | }, 169 | client: RuskHttpClient::new( 170 | "http://nodes.dusk.network:9500/graphql".to_string(), 171 | ), 172 | }; 173 | let _ = gql 174 | .tx_status( 175 | "dbc5a2c949516ecfb418406909d195c3cc267b46bd966a3ca9d66d2e13c47003", 176 | ) 177 | .await?; 178 | let block_txs = gql.txs_for_block(90).await?; 179 | block_txs.into_iter().for_each(|(t, chain_txid, _)| { 180 | let hash = rusk_abi::hash::Hasher::digest(t.to_hash_input_bytes()); 181 | let tx_id = hex::encode(hash.to_bytes()); 182 | assert_eq!(chain_txid, tx_id); 183 | println!("txid: {tx_id}"); 184 | }); 185 | Ok(()) 186 | } 187 | 188 | #[tokio::test] 189 | async fn deser() -> Result<(), Box> { 190 | let block_not_found = r#"{"block":null}"#; 191 | serde_json::from_str::(block_not_found).unwrap(); 192 | 193 | let block_without_tx = r#"{"block":{"transactions":[]}}"#; 194 | serde_json::from_str::(block_without_tx).unwrap(); 195 | 196 | let block_with_tx = r#"{"block":{"transactions":[{"id":"88e6804989cc2f3fd5bf94dcd39a4e7b7da9a1114d9b8bf4e0515264bc81c50f"}]}}"#; 197 | serde_json::from_str::(block_with_tx).unwrap(); 198 | 199 | Ok(()) 200 | } 201 | -------------------------------------------------------------------------------- /src/currency.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use core::cmp::Ordering; 8 | use std::fmt; 9 | use std::hash::{Hash, Hasher}; 10 | use std::num::ParseFloatError; 11 | use std::ops::{Add, Deref, Div, Mul, Sub}; 12 | use std::str::FromStr; 13 | 14 | use rusk_abi::dusk; 15 | 16 | /// The underlying unit of Dusk 17 | pub type Lux = u64; 18 | 19 | /// Denomination for DUSK 20 | #[derive(Copy, Clone, Debug, Eq)] 21 | pub struct Dusk(Lux); 22 | 23 | impl Dusk { 24 | /// The smallest value that can be represented by Dusk currency 25 | pub const MIN: Dusk = Dusk(0); 26 | /// The largest value that can be represented by Dusk currency 27 | pub const MAX: Dusk = Dusk(dusk::dusk(f64::MAX / dusk::dusk(1.0) as f64)); 28 | 29 | /// Returns a new Dusk based on the [Lux] given 30 | pub const fn new(lux: Lux) -> Dusk { 31 | Self(lux) 32 | } 33 | } 34 | 35 | /// Core ops 36 | /// Implementations of Addition, Subtraction, Multiplication, 37 | /// Division, and Comparison operators for Dusk 38 | 39 | /// Addition 40 | impl Add for Dusk { 41 | type Output = Self; 42 | fn add(self, other: Self) -> Self { 43 | Self(self.0 + other.0) 44 | } 45 | } 46 | 47 | impl Add for Dusk { 48 | type Output = Self; 49 | fn add(self, other: Lux) -> Self { 50 | Self(self.0 + other) 51 | } 52 | } 53 | 54 | /// Subtraction 55 | impl Sub for Dusk { 56 | type Output = Self; 57 | fn sub(self, other: Self) -> Self { 58 | Self(self.0 - other.0) 59 | } 60 | } 61 | 62 | impl Sub for Dusk { 63 | type Output = Self; 64 | fn sub(self, other: Lux) -> Self { 65 | Self(self.0 - other) 66 | } 67 | } 68 | 69 | /// Multiplication 70 | impl Mul for Dusk { 71 | type Output = Self; 72 | fn mul(self, other: Self) -> Self { 73 | let a = dusk::from_dusk(self.0); 74 | let b = dusk::from_dusk(other.0); 75 | Self(dusk::dusk(a * b)) 76 | } 77 | } 78 | 79 | impl Mul for Dusk { 80 | type Output = Self; 81 | fn mul(self, other: Lux) -> Self { 82 | let a = dusk::from_dusk(self.0); 83 | let b = dusk::from_dusk(other); 84 | Self(dusk::dusk(a * b)) 85 | } 86 | } 87 | 88 | /// Division 89 | impl Div for Dusk { 90 | type Output = Self; 91 | fn div(self, other: Self) -> Self { 92 | Self(dusk::dusk(self.0 as f64 / other.0 as f64)) 93 | } 94 | } 95 | 96 | impl Div for Dusk { 97 | type Output = Self; 98 | fn div(self, other: Lux) -> Self { 99 | Self(dusk::dusk(self.0 as f64 / other as f64)) 100 | } 101 | } 102 | 103 | /// Equality 104 | impl Hash for Dusk { 105 | fn hash(&self, state: &mut H) { 106 | self.0.hash(state); 107 | } 108 | } 109 | impl PartialEq for Dusk { 110 | fn eq(&self, other: &Self) -> bool { 111 | self.0 == other.0 112 | } 113 | } 114 | impl PartialEq for Dusk { 115 | fn eq(&self, other: &Lux) -> bool { 116 | self.0 == *other 117 | } 118 | } 119 | impl PartialEq for Dusk { 120 | fn eq(&self, other: &f64) -> bool { 121 | self.0 == dusk::dusk(*other) 122 | } 123 | } 124 | 125 | /// Comparison 126 | impl Ord for Dusk { 127 | fn cmp(&self, other: &Self) -> Ordering { 128 | self.0.cmp(other) 129 | } 130 | } 131 | 132 | impl PartialOrd for Dusk { 133 | fn partial_cmp(&self, other: &Self) -> Option { 134 | Some(self.cmp(other)) 135 | } 136 | } 137 | impl PartialOrd for Dusk { 138 | fn partial_cmp(&self, other: &Lux) -> Option { 139 | self.0.partial_cmp(other) 140 | } 141 | } 142 | impl PartialOrd for Dusk { 143 | fn partial_cmp(&self, other: &f64) -> Option { 144 | self.0.partial_cmp(&dusk::dusk(*other)) 145 | } 146 | } 147 | 148 | /// Conversion ops 149 | /// Convenient conversion of primitives to and from Dusk 150 | 151 | /// Floats are used directly as Dusk value 152 | impl From for Dusk { 153 | fn from(val: f64) -> Self { 154 | if val < 0.0 { 155 | panic!("Dusk type does not support negative values"); 156 | } 157 | Self(dusk::dusk(val)) 158 | } 159 | } 160 | 161 | impl From for f64 { 162 | fn from(val: Dusk) -> f64 { 163 | dusk::from_dusk(*val) 164 | } 165 | } 166 | 167 | impl From<&Dusk> for f64 { 168 | fn from(val: &Dusk) -> f64 { 169 | (*val).into() 170 | } 171 | } 172 | 173 | /// Lux represent Dusk in their underlying unit type 174 | impl From for Dusk { 175 | fn from(lux: Lux) -> Self { 176 | Self(lux) 177 | } 178 | } 179 | 180 | /// Strings are parsed as Dusk values (floats) 181 | impl FromStr for Dusk { 182 | type Err = ParseFloatError; 183 | 184 | fn from_str(s: &str) -> Result { 185 | f64::from_str(s).map(Dusk::from) 186 | } 187 | } 188 | 189 | /// Dusk derefs into its underlying Lux amount 190 | impl Deref for Dusk { 191 | type Target = Lux; 192 | fn deref(&self) -> &Self::Target { 193 | &self.0 194 | } 195 | } 196 | 197 | /// Display 198 | /// Let the user print stuff 199 | impl fmt::Display for Dusk { 200 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 201 | let v: f64 = self.into(); 202 | f64::fmt(&v, f) 203 | } 204 | } 205 | 206 | #[cfg(test)] 207 | mod tests { 208 | use super::*; 209 | 210 | #[test] 211 | fn basics() { 212 | let one = Dusk::from(1.0); 213 | let dec = Dusk::from(2.25); 214 | assert_eq!(one, 1.0); 215 | assert_eq!(dec, 2.25); 216 | assert_eq!(Dusk::MIN, 0); 217 | assert_eq!(Dusk::MIN, Dusk::from(0.0)); 218 | } 219 | 220 | #[test] 221 | fn compare_dusk() { 222 | let one = Dusk::from(1.0); 223 | let two = Dusk::from(2.0); 224 | let dec_a = Dusk::from(0.00025); 225 | let dec_b = Dusk::from(0.00190); 226 | assert!(one == one); 227 | assert!(one != two); 228 | assert!(one < two); 229 | assert!(one <= two); 230 | assert!(one >= one); 231 | assert!(dec_a < dec_b); 232 | assert!(one > dec_b); 233 | } 234 | 235 | #[test] 236 | fn ops_dusk_dusk() { 237 | let one = Dusk::from(1.0); 238 | let two = Dusk::from(2.0); 239 | let three = Dusk::from(3.0); 240 | assert_eq!(one + two, three); 241 | assert_eq!(three - two, one); 242 | assert_eq!(one * one, one); 243 | assert_eq!(two * one, two); 244 | assert_eq!(two / one, two); 245 | let point_five = Dusk::from(0.5); 246 | assert_eq!(one / two, point_five); 247 | assert_eq!(point_five * point_five, Dusk::from(0.25)) 248 | } 249 | 250 | #[test] 251 | fn ops_dusk_lux() { 252 | let one = Dusk::from(1.0); 253 | let one_dusk = 1000000000; 254 | assert_eq!(one + one_dusk, 2.0); 255 | assert_eq!(one - one_dusk, 0.0); 256 | assert_eq!(one * one_dusk, 1.0); 257 | assert_eq!(one / one_dusk, 1.0); 258 | } 259 | 260 | #[test] 261 | fn conversions() { 262 | let my_float = 35.049; 263 | let dusk: Dusk = my_float.into(); 264 | assert_eq!(dusk, my_float); 265 | let one_dusk = 1_000_000_000u64; 266 | let dusk: Dusk = one_dusk.into(); 267 | assert_eq!(dusk, 1.0); 268 | assert_eq!(*dusk, one_dusk); 269 | let dusk = Dusk::from_str("69.420").unwrap(); 270 | assert_eq!(dusk, 69.420); 271 | let float: f64 = dusk.into(); 272 | assert_eq!(float, 69.420); 273 | let borrowed = &Dusk(one_dusk); 274 | let float: f64 = borrowed.into(); 275 | assert_eq!(float, 1.0); 276 | let zero = 0; 277 | assert_eq!(Dusk::from(zero), 0); 278 | let zero = 0.0; 279 | assert_eq!(Dusk::from(zero), 0.0); 280 | } 281 | 282 | #[test] 283 | #[should_panic] 284 | fn overflow() { 285 | let ten = Dusk::from(10.0); 286 | let _ = Dusk::MAX + ten; 287 | } 288 | 289 | #[test] 290 | #[should_panic] 291 | fn negative_dusk() { 292 | let _ = Dusk::from(-1.0); 293 | } 294 | 295 | #[test] 296 | #[should_panic] 297 | fn negative_result() { 298 | let one = Dusk::from(1.0); 299 | let two = Dusk::from(2.0); 300 | let _ = one - two; 301 | } 302 | } 303 | -------------------------------------------------------------------------------- /src/dat.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use dusk_bytes::DeserializableSlice; 8 | 9 | use std::fs; 10 | use std::io::Read; 11 | 12 | use crate::crypto::decrypt; 13 | use crate::store; 14 | use crate::Error; 15 | use crate::WalletPath; 16 | 17 | /// Binary prefix for old Dusk wallet files 18 | pub const OLD_MAGIC: u32 = 0x1d0c15; 19 | /// Binary prefix for new binary file format 20 | pub const MAGIC: u32 = 0x72736b; 21 | /// The latest version of the rusk binary format for wallet dat file 22 | pub const LATEST_VERSION: Version = (0, 0, 1, 0, false); 23 | /// The type info of the dat file we'll save 24 | pub const FILE_TYPE: u16 = 0x0200; 25 | /// Reserved for futures use, 0 for now 26 | pub const RESERVED: u16 = 0x0000; 27 | /// (Major, Minor, Patch, Pre, Pre-Higher) 28 | type Version = (u8, u8, u8, u8, bool); 29 | 30 | /// Versions of the potential wallet DAT files we read 31 | #[derive(Copy, Clone, Debug, PartialEq)] 32 | pub enum DatFileVersion { 33 | /// Legacy the oldest format 34 | Legacy, 35 | /// Preciding legacy, we have the old one 36 | OldWalletCli(Version), 37 | /// The newest one. All new saves are saved in this file format 38 | RuskBinaryFileFormat(Version), 39 | } 40 | 41 | impl DatFileVersion { 42 | /// Checks if the file version is older than the latest Rust Binary file 43 | /// format 44 | pub fn is_old(&self) -> bool { 45 | matches!(self, Self::Legacy | Self::OldWalletCli(_)) 46 | } 47 | } 48 | 49 | /// Make sense of the payload and return it 50 | pub(crate) fn get_seed_and_address( 51 | file: DatFileVersion, 52 | mut bytes: Vec, 53 | pwd: &[u8], 54 | ) -> Result<(store::Seed, u8), Error> { 55 | match file { 56 | DatFileVersion::Legacy => { 57 | if bytes[1] == 0 && bytes[2] == 0 { 58 | bytes.drain(..3); 59 | } 60 | 61 | bytes = decrypt(&bytes, pwd)?; 62 | 63 | // get our seed 64 | let seed = store::Seed::from_reader(&mut &bytes[..]) 65 | .map_err(|_| Error::WalletFileCorrupted)?; 66 | 67 | Ok((seed, 1)) 68 | } 69 | DatFileVersion::OldWalletCli((major, minor, _, _, _)) => { 70 | bytes.drain(..5); 71 | 72 | let result: Result<(store::Seed, u8), Error> = match (major, minor) 73 | { 74 | (1, 0) => { 75 | let content = decrypt(&bytes, pwd)?; 76 | let mut buff = &content[..]; 77 | 78 | let seed = store::Seed::from_reader(&mut buff) 79 | .map_err(|_| Error::WalletFileCorrupted)?; 80 | 81 | Ok((seed, 1)) 82 | } 83 | (2, 0) => { 84 | let content = decrypt(&bytes, pwd)?; 85 | let mut buff = &content[..]; 86 | 87 | // extract seed 88 | let seed = store::Seed::from_reader(&mut buff) 89 | .map_err(|_| Error::WalletFileCorrupted)?; 90 | 91 | // extract addresses count 92 | Ok((seed, buff[0])) 93 | } 94 | _ => Err(Error::UnknownFileVersion(major, minor)), 95 | }; 96 | 97 | result 98 | } 99 | DatFileVersion::RuskBinaryFileFormat(_) => { 100 | let rest = bytes.get(12..(12 + 96)); 101 | if let Some(rest) = rest { 102 | let content = decrypt(rest, pwd)?; 103 | 104 | if let Some(seed_buff) = content.get(0..65) { 105 | let seed = store::Seed::from_reader(&mut &seed_buff[0..64]) 106 | .map_err(|_| Error::WalletFileCorrupted)?; 107 | 108 | let count = &seed_buff[64..65]; 109 | 110 | Ok((seed, count[0])) 111 | } else { 112 | Err(Error::WalletFileCorrupted) 113 | } 114 | } else { 115 | Err(Error::WalletFileCorrupted) 116 | } 117 | } 118 | } 119 | } 120 | 121 | /// From the first 12 bytes of the file (header), we check version 122 | /// 123 | /// https://github.com/dusk-network/rusk/wiki/Binary-File-Format/#header 124 | pub(crate) fn check_version( 125 | bytes: Option<&[u8]>, 126 | ) -> Result { 127 | match bytes { 128 | Some(bytes) => { 129 | let header_bytes: [u8; 4] = bytes[0..4] 130 | .try_into() 131 | .map_err(|_| Error::WalletFileCorrupted)?; 132 | 133 | let magic = u32::from_le_bytes(header_bytes) & 0x00ffffff; 134 | 135 | if magic == OLD_MAGIC { 136 | // check for version information 137 | let (major, minor) = (bytes[3], bytes[4]); 138 | 139 | Ok(DatFileVersion::OldWalletCli((major, minor, 0, 0, false))) 140 | } else { 141 | let header_bytes = bytes[0..8] 142 | .try_into() 143 | .map_err(|_| Error::WalletFileCorrupted)?; 144 | 145 | let number = u64::from_be_bytes(header_bytes); 146 | 147 | let magic_num = (number & 0xFFFFFF00000000) >> 32; 148 | 149 | if (magic_num as u32) != MAGIC { 150 | return Ok(DatFileVersion::Legacy); 151 | } 152 | 153 | let file_type = (number & 0x000000FFFF0000) >> 16; 154 | let reserved = number & 0x0000000000FFFF; 155 | 156 | if file_type != FILE_TYPE as u64 { 157 | return Err(Error::WalletFileCorrupted); 158 | }; 159 | 160 | if reserved != RESERVED as u64 { 161 | return Err(Error::WalletFileCorrupted); 162 | }; 163 | 164 | let version_bytes = bytes[8..12] 165 | .try_into() 166 | .map_err(|_| Error::WalletFileCorrupted)?; 167 | 168 | let version = u32::from_be_bytes(version_bytes); 169 | 170 | let major = (version & 0xff000000) >> 24; 171 | let minor = (version & 0x00ff0000) >> 16; 172 | let patch = (version & 0x0000ff00) >> 8; 173 | let pre = (version & 0x000000f0) >> 4; 174 | let higher = version & 0x0000000f; 175 | 176 | let pre_higher = matches!(higher, 1); 177 | 178 | Ok(DatFileVersion::RuskBinaryFileFormat(( 179 | major as u8, 180 | minor as u8, 181 | patch as u8, 182 | pre as u8, 183 | pre_higher, 184 | ))) 185 | } 186 | } 187 | None => Err(Error::WalletFileCorrupted), 188 | } 189 | } 190 | 191 | /// Read the first 12 bytes of the dat file and get the file version from 192 | /// there 193 | pub fn read_file_version(file: &WalletPath) -> Result { 194 | let path = &file.wallet; 195 | 196 | // make sure file exists 197 | if !path.is_file() { 198 | return Err(Error::WalletFileMissing); 199 | } 200 | 201 | let mut fs = fs::File::open(path)?; 202 | 203 | let mut header_buf = [0; 12]; 204 | 205 | fs.read_exact(&mut header_buf)?; 206 | 207 | check_version(Some(&header_buf)) 208 | } 209 | 210 | pub(crate) fn version_bytes(version: Version) -> [u8; 4] { 211 | u32::from_be_bytes([version.0, version.1, version.2, version.3]) 212 | .to_be_bytes() 213 | } 214 | 215 | #[cfg(test)] 216 | mod tests { 217 | use super::*; 218 | 219 | #[test] 220 | fn distiction_between_versions() { 221 | // with magic number 222 | let old_wallet_file = vec![0x15, 0x0c, 0x1d, 0x02, 0x00]; 223 | // no magic number just nonsense bytes 224 | let legacy_file = vec![ 225 | 0xab, 0x38, 0x81, 0x3b, 0xfc, 0x79, 0x11, 0xf9, 0x86, 0xd6, 0xd0, 226 | ]; 227 | // new header 228 | let new_file = vec![ 229 | 0x00, 0x72, 0x73, 0x6b, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 230 | 0x00, 231 | ]; 232 | 233 | assert_eq!( 234 | check_version(Some(&old_wallet_file)).unwrap(), 235 | DatFileVersion::OldWalletCli((2, 0, 0, 0, false)) 236 | ); 237 | 238 | assert_eq!( 239 | check_version(Some(&legacy_file)).unwrap(), 240 | DatFileVersion::Legacy 241 | ); 242 | 243 | assert_eq!( 244 | check_version(Some(&new_file)).unwrap(), 245 | DatFileVersion::RuskBinaryFileFormat((0, 0, 1, 0, false)) 246 | ); 247 | } 248 | } 249 | -------------------------------------------------------------------------------- /src/cache.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use std::cmp::Ordering; 8 | use std::collections::BTreeSet; 9 | use std::path::Path; 10 | 11 | use dusk_bytes::{DeserializableSlice, Serializable}; 12 | use dusk_pki::PublicSpendKey; 13 | use dusk_plonk::prelude::BlsScalar; 14 | use dusk_wallet_core::Store; 15 | use phoenix_core::Note; 16 | use rocksdb::{DBWithThreadMode, MultiThreaded, Options}; 17 | 18 | use crate::{error::Error, store::LocalStore, MAX_ADDRESSES}; 19 | 20 | type DB = DBWithThreadMode; 21 | 22 | /// A cache of notes received from Rusk. 23 | /// 24 | /// path is the path of the rocks db database 25 | pub(crate) struct Cache { 26 | db: DB, 27 | } 28 | 29 | impl Cache { 30 | /// Returns a new cache instance. 31 | pub(crate) fn new>( 32 | path: T, 33 | store: &LocalStore, 34 | status: fn(&str), 35 | ) -> Result { 36 | let cfs: Vec<_> = (0..MAX_ADDRESSES) 37 | .flat_map(|i| { 38 | let ssk = 39 | store.retrieve_ssk(i as u64).expect("ssk to be available"); 40 | let psk = ssk.public_spend_key(); 41 | 42 | let live = format!("{:?}", psk); 43 | let spent = format!("spent_{:?}", psk); 44 | [live, spent] 45 | }) 46 | .collect(); 47 | 48 | status("Opening notes database"); 49 | 50 | let mut opts = Options::default(); 51 | opts.create_if_missing(true); 52 | opts.create_missing_column_families(true); 53 | // After 10 million bytes, sort the cache file and create new one 54 | opts.set_write_buffer_size(10_000_000); 55 | 56 | // create all CF(s) on startup if we don't have them 57 | let db = DB::open_cf(&opts, path, cfs)?; 58 | 59 | Ok(Self { db }) 60 | } 61 | 62 | // We store a column family named by hex representation of the psk. 63 | // We store the nullifier of the note as key and the value is the bytes 64 | // representation of the tuple (NoteHeight, Note) 65 | pub(crate) fn insert( 66 | &self, 67 | psk: &PublicSpendKey, 68 | height: u64, 69 | note_data: (Note, BlsScalar), 70 | ) -> Result<(), Error> { 71 | let cf_name = format!("{:?}", psk); 72 | 73 | let cf = self 74 | .db 75 | .cf_handle(&cf_name) 76 | .ok_or(Error::CacheDatabaseCorrupted)?; 77 | 78 | let (note, nullifier) = note_data; 79 | 80 | let data = NoteData { height, note }; 81 | let key = nullifier.to_bytes(); 82 | 83 | self.db.put_cf(&cf, key, data.to_bytes())?; 84 | 85 | Ok(()) 86 | } 87 | 88 | // We store a column family named by hex representation of the psk. 89 | // We store the nullifier of the note as key and the value is the bytes 90 | // representation of the tuple (NoteHeight, Note) 91 | pub(crate) fn insert_spent( 92 | &self, 93 | psk: &PublicSpendKey, 94 | height: u64, 95 | note_data: (Note, BlsScalar), 96 | ) -> Result<(), Error> { 97 | let cf_name = format!("spent_{:?}", psk); 98 | 99 | let cf = self 100 | .db 101 | .cf_handle(&cf_name) 102 | .ok_or(Error::CacheDatabaseCorrupted)?; 103 | 104 | let (note, nullifier) = note_data; 105 | 106 | let data = NoteData { height, note }; 107 | let key = nullifier.to_bytes(); 108 | 109 | self.db.put_cf(&cf, key, data.to_bytes())?; 110 | 111 | Ok(()) 112 | } 113 | 114 | pub(crate) fn spend_notes( 115 | &self, 116 | psk: &PublicSpendKey, 117 | nullifiers: &[BlsScalar], 118 | ) -> Result<(), Error> { 119 | if nullifiers.is_empty() { 120 | return Ok(()); 121 | } 122 | let cf_name = format!("{:?}", psk); 123 | let spent_cf_name = format!("spent_{:?}", psk); 124 | 125 | let cf = self 126 | .db 127 | .cf_handle(&cf_name) 128 | .ok_or(Error::CacheDatabaseCorrupted)?; 129 | let spent_cf = self 130 | .db 131 | .cf_handle(&spent_cf_name) 132 | .ok_or(Error::CacheDatabaseCorrupted)?; 133 | 134 | for n in nullifiers { 135 | let key = n.to_bytes(); 136 | let to_move = self 137 | .db 138 | .get_cf(&cf, key)? 139 | .expect("Note must exists to be moved"); 140 | self.db.put_cf(&spent_cf, key, to_move)?; 141 | self.db.delete_cf(&cf, n.to_bytes())?; 142 | } 143 | 144 | Ok(()) 145 | } 146 | 147 | pub(crate) fn insert_last_pos(&self, last_pos: u64) -> Result<(), Error> { 148 | self.db.put(b"last_pos", last_pos.to_be_bytes())?; 149 | 150 | Ok(()) 151 | } 152 | 153 | /// Returns the last position of inserted notes. If no note has ever been 154 | /// inserted it returns None. 155 | pub(crate) fn last_pos(&self) -> Result, Error> { 156 | Ok(self.db.get(b"last_pos")?.map(|x| { 157 | let buff: [u8; 8] = x.try_into().expect("Invalid u64 in cache db"); 158 | 159 | u64::from_be_bytes(buff) 160 | })) 161 | } 162 | 163 | /// Returns an iterator over all unspent notes nullifier for the given PSK. 164 | pub(crate) fn unspent_notes_id( 165 | &self, 166 | psk: &PublicSpendKey, 167 | ) -> Result, Error> { 168 | let cf_name = format!("{:?}", psk); 169 | let mut notes = vec![]; 170 | 171 | if let Some(cf) = self.db.cf_handle(&cf_name) { 172 | let iterator = 173 | self.db.iterator_cf(&cf, rocksdb::IteratorMode::Start); 174 | 175 | for i in iterator { 176 | let (id, _) = i?; 177 | 178 | let id = BlsScalar::from_slice(&id)?; 179 | notes.push(id); 180 | } 181 | }; 182 | 183 | Ok(notes) 184 | } 185 | 186 | /// Returns an iterator over all unspent notes inserted for the given PSK, 187 | /// in order of note position. 188 | pub(crate) fn notes( 189 | &self, 190 | psk: &PublicSpendKey, 191 | ) -> Result, Error> { 192 | let cf_name = format!("{:?}", psk); 193 | let mut notes = BTreeSet::::new(); 194 | 195 | if let Some(cf) = self.db.cf_handle(&cf_name) { 196 | let iterator = 197 | self.db.iterator_cf(&cf, rocksdb::IteratorMode::Start); 198 | 199 | for i in iterator { 200 | let (_, note_data) = i?; 201 | 202 | let note = NoteData::from_slice(¬e_data)?; 203 | 204 | notes.insert(note); 205 | } 206 | }; 207 | 208 | Ok(notes) 209 | } 210 | 211 | /// Returns an iterator over all notes inserted for the given PSK, in order 212 | /// of block height. 213 | pub(crate) fn spent_notes( 214 | &self, 215 | psk: &PublicSpendKey, 216 | ) -> Result, Error> { 217 | let cf_name = format!("spent_{:?}", psk); 218 | let mut notes = vec![]; 219 | 220 | if let Some(cf) = self.db.cf_handle(&cf_name) { 221 | let iterator = 222 | self.db.iterator_cf(&cf, rocksdb::IteratorMode::Start); 223 | 224 | for i in iterator { 225 | let (key, note_data) = i?; 226 | 227 | let note = NoteData::from_slice(¬e_data)?; 228 | let key = BlsScalar::from_slice(&key)?; 229 | 230 | notes.push((key, note)); 231 | } 232 | }; 233 | 234 | Ok(notes) 235 | } 236 | } 237 | 238 | /// Data kept about each note. 239 | #[derive(Debug, Clone, PartialEq, Eq)] 240 | pub(crate) struct NoteData { 241 | pub height: u64, 242 | pub note: Note, 243 | } 244 | 245 | impl PartialOrd for NoteData { 246 | fn partial_cmp(&self, other: &Self) -> Option { 247 | Some(self.cmp(other)) 248 | } 249 | } 250 | 251 | impl Ord for NoteData { 252 | fn cmp(&self, other: &Self) -> Ordering { 253 | self.note.pos().cmp(other.note.pos()) 254 | } 255 | } 256 | 257 | impl Serializable<{ u64::SIZE + Note::SIZE }> for NoteData { 258 | type Error = dusk_bytes::Error; 259 | /// Converts a Note into a byte representation 260 | 261 | fn to_bytes(&self) -> [u8; Self::SIZE] { 262 | let mut buf = [0u8; Self::SIZE]; 263 | 264 | buf[0..8].copy_from_slice(&self.height.to_bytes()); 265 | 266 | buf[8..].copy_from_slice(&self.note.to_bytes()); 267 | 268 | buf 269 | } 270 | 271 | /// Attempts to convert a byte representation of a note into a `Note`, 272 | /// failing if the input is invalid 273 | fn from_bytes(bytes: &[u8; Self::SIZE]) -> Result { 274 | let mut one_u64 = [0u8; 8]; 275 | one_u64.copy_from_slice(&bytes[0..8]); 276 | let height = u64::from_bytes(&one_u64)?; 277 | 278 | let note = Note::from_slice(&bytes[8..])?; 279 | Ok(Self { height, note }) 280 | } 281 | } 282 | -------------------------------------------------------------------------------- /src/bin/io/prompt.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use std::path::PathBuf; 8 | use std::str::FromStr; 9 | use std::{io::stdout, println}; 10 | 11 | use crossterm::{ 12 | cursor::{Hide, Show}, 13 | ExecutableCommand, 14 | }; 15 | 16 | use anyhow::Result; 17 | use bip39::{ErrorKind, Language, Mnemonic}; 18 | use dusk_wallet::{dat::DatFileVersion, Error}; 19 | use requestty::Question; 20 | 21 | use dusk_wallet::{Address, Dusk, Lux}; 22 | 23 | use dusk_wallet::gas; 24 | use dusk_wallet::{MAX_CONVERTIBLE, MIN_CONVERTIBLE}; 25 | use sha2::{Digest, Sha256}; 26 | 27 | /// Request the user to authenticate with a password 28 | pub(crate) fn request_auth( 29 | msg: &str, 30 | password: &Option, 31 | file_version: DatFileVersion, 32 | ) -> anyhow::Result> { 33 | let pwd = match password.as_ref() { 34 | Some(p) => p.to_string(), 35 | 36 | None => { 37 | let q = Question::password("password") 38 | .message(format!("{}:", msg)) 39 | .mask('*') 40 | .build(); 41 | 42 | let a = requestty::prompt_one(q)?; 43 | a.as_string().expect("answer to be a string").into() 44 | } 45 | }; 46 | 47 | Ok(hash(file_version, &pwd)) 48 | } 49 | 50 | /// Request the user to create a wallet password 51 | pub(crate) fn create_password( 52 | password: &Option, 53 | file_version: DatFileVersion, 54 | ) -> anyhow::Result> { 55 | let pwd = match password.as_ref() { 56 | Some(p) => p.to_string(), 57 | None => { 58 | let mut pwd = String::from(""); 59 | 60 | let mut pwds_match = false; 61 | while !pwds_match { 62 | // enter password 63 | let q = Question::password("password") 64 | .message("Enter the password for the wallet:") 65 | .mask('*') 66 | .build(); 67 | let a = requestty::prompt_one(q)?; 68 | let pwd1 = a.as_string().expect("answer to be a string"); 69 | 70 | // confirm password 71 | let q = Question::password("password") 72 | .message("Please confirm the password:") 73 | .mask('*') 74 | .build(); 75 | let a = requestty::prompt_one(q)?; 76 | let pwd2 = a.as_string().expect("answer to be a string"); 77 | 78 | // check match 79 | pwds_match = pwd1 == pwd2; 80 | if pwds_match { 81 | pwd = pwd1.to_string() 82 | } else { 83 | println!("Passwords don't match, please try again."); 84 | } 85 | } 86 | pwd 87 | } 88 | }; 89 | 90 | Ok(hash(file_version, &pwd)) 91 | } 92 | 93 | /// Display the recovery phrase to the user and ask for confirmation 94 | pub(crate) fn confirm_recovery_phrase(phrase: &S) -> anyhow::Result<()> 95 | where 96 | S: std::fmt::Display, 97 | { 98 | // inform the user about the mnemonic phrase 99 | println!("The following phrase is essential for you to regain access to your wallet\nin case you lose access to this computer."); 100 | println!("Please print it or write it down and store it somewhere safe:"); 101 | println!(); 102 | println!("> {}", phrase); 103 | println!(); 104 | 105 | // let the user confirm they have backed up their phrase 106 | loop { 107 | let q = requestty::Question::confirm("proceed") 108 | .message("Have you backed up your recovery phrase?") 109 | .build(); 110 | 111 | let a = requestty::prompt_one(q)?; 112 | if a.as_bool().expect("answer to be a bool") { 113 | return Ok(()); 114 | } 115 | } 116 | } 117 | 118 | /// Request the user to input the recovery phrase 119 | pub(crate) fn request_recovery_phrase() -> anyhow::Result { 120 | // let the user input the recovery phrase 121 | let mut attempt = 1; 122 | loop { 123 | let q = Question::input("phrase") 124 | .message("Please enter the recovery phrase:") 125 | .build(); 126 | 127 | let a = requestty::prompt_one(q)?; 128 | let phrase = a.as_string().expect("answer to be a string"); 129 | 130 | match Mnemonic::from_phrase(phrase, Language::English) { 131 | Ok(phrase) => break Ok(phrase.to_string()), 132 | 133 | Err(err) if attempt > 2 => match err.downcast_ref::() { 134 | Some(ErrorKind::InvalidWord) => { 135 | return Err(Error::AttemptsExhausted)? 136 | } 137 | _ => return Err(err), 138 | }, 139 | Err(_) => { 140 | println!("Invalid recovery phrase, please try again"); 141 | attempt += 1; 142 | } 143 | } 144 | } 145 | } 146 | 147 | fn is_valid_dir(dir: &str) -> bool { 148 | let mut p = std::path::PathBuf::new(); 149 | p.push(dir); 150 | p.is_dir() 151 | } 152 | 153 | /// Use sha256 for Rusk Binary Format, and blake for the rest 154 | fn hash(file_version: DatFileVersion, pwd: &str) -> Vec { 155 | match file_version { 156 | DatFileVersion::RuskBinaryFileFormat(_) => { 157 | let mut hasher = Sha256::new(); 158 | 159 | hasher.update(pwd.as_bytes()); 160 | 161 | hasher.finalize().to_vec() 162 | } 163 | _ => blake3::hash(pwd.as_bytes()).as_bytes().to_vec(), 164 | } 165 | } 166 | 167 | /// Request a directory 168 | pub(crate) fn request_dir( 169 | what_for: &str, 170 | profile: PathBuf, 171 | ) -> Result { 172 | let q = Question::input("name") 173 | .message(format!("Please enter a directory to {}:", what_for)) 174 | .default(profile.as_os_str().to_str().expect("default dir")) 175 | .validate_on_key(|dir, _| is_valid_dir(dir)) 176 | .validate(|dir, _| { 177 | if is_valid_dir(dir) { 178 | Ok(()) 179 | } else { 180 | Err("Not a valid directory".to_string()) 181 | } 182 | }) 183 | .build(); 184 | 185 | let a = requestty::prompt_one(q)?; 186 | let mut p = std::path::PathBuf::new(); 187 | p.push(a.as_string().expect("answer to be a string")); 188 | Ok(p) 189 | } 190 | 191 | /// Asks the user for confirmation 192 | pub(crate) fn ask_confirm() -> anyhow::Result { 193 | let q = requestty::Question::confirm("confirm") 194 | .message("Transaction ready. Proceed?") 195 | .build(); 196 | let a = requestty::prompt_one(q)?; 197 | Ok(a.as_bool().expect("answer to be a bool")) 198 | } 199 | 200 | /// Request a receiver address 201 | pub(crate) fn request_rcvr_addr(addr_for: &str) -> anyhow::Result
{ 202 | // let the user input the receiver address 203 | let q = Question::input("addr") 204 | .message(format!("Please enter the {} address:", addr_for)) 205 | .validate_on_key(|addr, _| Address::from_str(addr).is_ok()) 206 | .validate(|addr, _| { 207 | if Address::from_str(addr).is_ok() { 208 | Ok(()) 209 | } else { 210 | Err("Please introduce a valid DUSK address".to_string()) 211 | } 212 | }) 213 | .build(); 214 | 215 | let a = requestty::prompt_one(q)?; 216 | Ok(Address::from_str( 217 | a.as_string().expect("answer to be a string"), 218 | )?) 219 | } 220 | 221 | /// Checks for a valid DUSK denomination 222 | fn check_valid_denom(value: f64, balance: Dusk) -> Result<(), String> { 223 | let value = Dusk::from(value); 224 | let min = MIN_CONVERTIBLE; 225 | let max = std::cmp::min(balance, MAX_CONVERTIBLE); 226 | match (min..=max).contains(&value) { 227 | true => Ok(()), 228 | false => { 229 | Err(format!("The amount has to be between {} and {}", min, max)) 230 | } 231 | } 232 | } 233 | 234 | /// Request amount of tokens 235 | pub(crate) fn request_token_amt( 236 | action: &str, 237 | balance: Dusk, 238 | ) -> anyhow::Result { 239 | let question = requestty::Question::float("amt") 240 | .message(format!("Introduce the amount of DUSK to {}:", action)) 241 | .default(MIN_CONVERTIBLE.into()) 242 | .validate_on_key(|f, _| check_valid_denom(f, balance).is_ok()) 243 | .validate(|f, _| check_valid_denom(f, balance)) 244 | .build(); 245 | 246 | let a = requestty::prompt_one(question)?; 247 | Ok(a.as_float().expect("answer to be a float").into()) 248 | } 249 | 250 | /// Request gas limit 251 | pub(crate) fn request_gas_limit(default_gas_limit: u64) -> anyhow::Result { 252 | let question = requestty::Question::int("amt") 253 | .message("Introduce the gas limit for this transaction:") 254 | .default(default_gas_limit as i64) 255 | .validate_on_key(|n, _| n > (gas::MIN_LIMIT as i64)) 256 | .validate(|n, _| { 257 | if n < gas::MIN_LIMIT as i64 { 258 | Err("Gas limit too low".to_owned()) 259 | } else { 260 | Ok(()) 261 | } 262 | }) 263 | .build(); 264 | 265 | let a = requestty::prompt_one(question)?; 266 | Ok(a.as_int().expect("answer to be an int") as u64) 267 | } 268 | 269 | /// Request gas price 270 | pub(crate) fn request_gas_price() -> anyhow::Result { 271 | let question = requestty::Question::float("amt") 272 | .message("Introduce the gas price for this transaction:") 273 | .default(Dusk::from(gas::DEFAULT_PRICE).into()) 274 | .validate_on_key(|f, _| check_valid_denom(f, MAX_CONVERTIBLE).is_ok()) 275 | .validate(|f, _| check_valid_denom(f, MAX_CONVERTIBLE)) 276 | .build(); 277 | 278 | let a = requestty::prompt_one(question)?; 279 | let price = Dusk::from(a.as_float().expect("answer to be a float")); 280 | Ok(*price) 281 | } 282 | 283 | /// Request Dusk block explorer to be opened 284 | pub(crate) fn launch_explorer(url: String) -> Result<()> { 285 | let q = requestty::Question::confirm("launch") 286 | .message("Launch block explorer?") 287 | .build(); 288 | 289 | let a = requestty::prompt_one(q)?; 290 | let open = a.as_bool().expect("answer to be a bool"); 291 | if open { 292 | open::that(url)?; 293 | } 294 | Ok(()) 295 | } 296 | 297 | /// Shows the terminal cursor 298 | pub(crate) fn show_cursor() -> anyhow::Result<()> { 299 | let mut stdout = stdout(); 300 | stdout.execute(Show)?; 301 | Ok(()) 302 | } 303 | 304 | /// Hides the terminal cursor 305 | pub(crate) fn hide_cursor() -> anyhow::Result<()> { 306 | let mut stdout = stdout(); 307 | stdout.execute(Hide)?; 308 | Ok(()) 309 | } 310 | -------------------------------------------------------------------------------- /src/bin/main.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | mod command; 8 | mod config; 9 | mod interactive; 10 | mod io; 11 | mod menu; 12 | mod settings; 13 | 14 | pub(crate) use command::{Command, RunResult}; 15 | use dusk_wallet::dat::LATEST_VERSION; 16 | pub(crate) use menu::Menu; 17 | 18 | use clap::Parser; 19 | use std::fs::{self, File}; 20 | use std::io::Write; 21 | use tracing::{warn, Level}; 22 | 23 | use bip39::{Language, Mnemonic, MnemonicType}; 24 | 25 | use crate::command::TransactionHistory; 26 | use crate::settings::{LogFormat, Settings}; 27 | 28 | use dusk_wallet::{dat, Error}; 29 | use dusk_wallet::{Dusk, SecureWalletFile, Wallet, WalletPath}; 30 | 31 | use config::Config; 32 | use io::{prompt, status}; 33 | use io::{GraphQL, WalletArgs}; 34 | 35 | #[derive(Debug, Clone)] 36 | pub(crate) struct WalletFile { 37 | path: WalletPath, 38 | pwd: Vec, 39 | } 40 | 41 | impl SecureWalletFile for WalletFile { 42 | fn path(&self) -> &WalletPath { 43 | &self.path 44 | } 45 | 46 | fn pwd(&self) -> &[u8] { 47 | &self.pwd 48 | } 49 | } 50 | 51 | #[tokio::main(flavor = "multi_thread")] 52 | async fn main() -> anyhow::Result<()> { 53 | if let Err(err) = exec().await { 54 | // display the error message (if any) 55 | match err.downcast_ref::() { 56 | Some(requestty::ErrorKind::Interrupted) => { 57 | // TODO: Handle this error properly 58 | // See also https://github.com/dusk-network/wallet-cli/issues/104 59 | } 60 | _ => eprintln!("{err}"), 61 | }; 62 | // give cursor back to the user 63 | io::prompt::show_cursor()?; 64 | } 65 | Ok(()) 66 | } 67 | 68 | async fn connect( 69 | mut wallet: Wallet, 70 | settings: &Settings, 71 | status: fn(&str), 72 | ) -> Wallet 73 | where 74 | F: SecureWalletFile + std::fmt::Debug, 75 | { 76 | let con = wallet 77 | .connect_with_status( 78 | &settings.state.to_string(), 79 | &settings.prover.to_string(), 80 | status, 81 | ) 82 | .await; 83 | 84 | // check for connection errors 85 | match con { 86 | Err(Error::RocksDB(e)) => panic!{"Invalid cache {e}"}, 87 | Err(e) => warn!("[OFFLINE MODE]: Unable to connect to Rusk, limited functionality available: {e}"), 88 | _ => {} 89 | } 90 | 91 | wallet 92 | } 93 | 94 | async fn exec() -> anyhow::Result<()> { 95 | // parse user args 96 | let args = WalletArgs::parse(); 97 | // get the subcommand, if any 98 | let cmd = args.command.clone(); 99 | 100 | // set symbols to ASCII for Windows terminal compatibility 101 | #[cfg(windows)] 102 | requestty::symbols::set(requestty::symbols::ASCII); 103 | 104 | // Get the initial settings from the args 105 | let settings_builder = Settings::args(args); 106 | 107 | // Obtain the profile dir from the settings 108 | let profile_folder = settings_builder.profile().clone(); 109 | 110 | fs::create_dir_all(profile_folder.as_path())?; 111 | 112 | // prepare wallet path 113 | let mut wallet_path = 114 | WalletPath::from(profile_folder.as_path().join("wallet.dat")); 115 | 116 | // load configuration (or use default) 117 | let cfg = Config::load(&profile_folder)?; 118 | 119 | wallet_path.set_network_name(settings_builder.args.network.clone()); 120 | 121 | // Finally complete the settings by setting the network 122 | let settings = settings_builder 123 | .network(cfg.network) 124 | .map_err(|_| dusk_wallet::Error::NetworkNotFound)?; 125 | 126 | // generate a subscriber with the desired log level 127 | // 128 | // TODO: we should have the logger instantiate sooner, otherwise we cannot 129 | // catch errors that are happened before its instantiation. 130 | // 131 | // Therefore, the logger details such as `type` and `level` cannot be part 132 | // of the configuration, since it won't catch any configuration error 133 | // otherwise. 134 | // 135 | // See: 136 | // 137 | let level = &settings.logging.level; 138 | let level: Level = level.into(); 139 | let subscriber = tracing_subscriber::fmt::Subscriber::builder() 140 | .with_max_level(level) 141 | .with_writer(std::io::stderr); 142 | 143 | // set the subscriber as global 144 | match settings.logging.format { 145 | LogFormat::Json => { 146 | let subscriber = subscriber.json().flatten_event(true).finish(); 147 | tracing::subscriber::set_global_default(subscriber)?; 148 | } 149 | LogFormat::Plain => { 150 | let subscriber = subscriber.with_ansi(false).finish(); 151 | tracing::subscriber::set_global_default(subscriber)?; 152 | } 153 | LogFormat::Coloured => { 154 | let subscriber = subscriber.finish(); 155 | tracing::subscriber::set_global_default(subscriber)?; 156 | } 157 | }; 158 | 159 | let is_headless = cmd.is_some(); 160 | 161 | let password = &settings.password; 162 | 163 | if let Some(Command::Settings) = cmd { 164 | println!("{}", &settings); 165 | return Ok(()); 166 | }; 167 | 168 | let file_version = dat::read_file_version(&wallet_path); 169 | 170 | // get our wallet ready 171 | let mut wallet: Wallet = match cmd { 172 | Some(ref cmd) => match cmd { 173 | Command::Create { 174 | skip_recovery, 175 | seed_file, 176 | } => { 177 | // create a new randomly generated mnemonic phrase 178 | let mnemonic = 179 | Mnemonic::new(MnemonicType::Words12, Language::English); 180 | // ask user for a password to secure the wallet 181 | // latest version is used for dat file 182 | let pwd = prompt::create_password( 183 | password, 184 | dat::DatFileVersion::RuskBinaryFileFormat(LATEST_VERSION), 185 | )?; 186 | 187 | match (skip_recovery, seed_file) { 188 | (_, Some(file)) => { 189 | let mut file = File::create(file)?; 190 | file.write_all(mnemonic.phrase().as_bytes())? 191 | } 192 | // skip phrase confirmation if explicitly 193 | (false, _) => prompt::confirm_recovery_phrase(&mnemonic)?, 194 | _ => {} 195 | } 196 | 197 | // create wallet 198 | let mut w = Wallet::new(mnemonic)?; 199 | 200 | w.save_to(WalletFile { 201 | path: wallet_path, 202 | pwd, 203 | })?; 204 | 205 | w 206 | } 207 | Command::Restore { file } => { 208 | let (mut w, pwd) = match file { 209 | Some(file) => { 210 | // if we restore and old version file make sure we 211 | // know the corrrect version before asking for the 212 | // password 213 | let file_version = dat::read_file_version(file)?; 214 | 215 | let pwd = prompt::request_auth( 216 | "Please enter wallet password", 217 | password, 218 | file_version, 219 | )?; 220 | 221 | let w = Wallet::from_file(WalletFile { 222 | path: file.clone(), 223 | pwd: pwd.clone(), 224 | })?; 225 | 226 | (w, pwd) 227 | } 228 | // Use the latest dat file version when there's no dat file 229 | // provided when restoring the wallet 230 | None => { 231 | // ask user for 12-word recovery phrase 232 | let phrase = prompt::request_recovery_phrase()?; 233 | // ask user for a password to secure the wallet 234 | let pwd = prompt::create_password( 235 | password, 236 | dat::DatFileVersion::RuskBinaryFileFormat( 237 | LATEST_VERSION, 238 | ), 239 | )?; 240 | // create wallet 241 | let w = Wallet::new(phrase)?; 242 | 243 | (w, pwd) 244 | } 245 | }; 246 | 247 | w.save_to(WalletFile { 248 | path: wallet_path, 249 | pwd, 250 | })?; 251 | 252 | w 253 | } 254 | 255 | _ => { 256 | // Grab the file version for a random command 257 | let file_version = file_version?; 258 | // load wallet from file 259 | let pwd = prompt::request_auth( 260 | "Please enter wallet password", 261 | password, 262 | file_version, 263 | )?; 264 | 265 | Wallet::from_file(WalletFile { 266 | path: wallet_path, 267 | pwd, 268 | })? 269 | } 270 | }, 271 | None => { 272 | // load a wallet in interactive mode 273 | interactive::load_wallet(&wallet_path, &settings, file_version)? 274 | } 275 | }; 276 | 277 | // set our status callback 278 | let status_cb = match is_headless { 279 | true => status::headless, 280 | false => status::interactive, 281 | }; 282 | 283 | wallet = connect(wallet, &settings, status_cb).await; 284 | 285 | // run command 286 | match cmd { 287 | Some(cmd) => match cmd.run(&mut wallet, &settings).await? { 288 | RunResult::Balance(balance, spendable) => { 289 | if spendable { 290 | println!("{}", Dusk::from(balance.spendable)); 291 | } else { 292 | println!("{}", Dusk::from(balance.value)); 293 | } 294 | } 295 | RunResult::Address(addr) => { 296 | println!("{addr}"); 297 | } 298 | RunResult::Addresses(addrs) => { 299 | for a in addrs { 300 | println!("{a}"); 301 | } 302 | } 303 | RunResult::Tx(hash) => { 304 | let tx_id = hex::encode(hash.to_bytes()); 305 | 306 | // Wait for transaction confirmation from network 307 | let gql = GraphQL::new(settings.state, status::headless); 308 | gql.wait_for(&tx_id).await?; 309 | 310 | println!("{tx_id}"); 311 | } 312 | RunResult::StakeInfo(info, reward) => { 313 | if reward { 314 | println!("{}", Dusk::from(info.reward)); 315 | } else { 316 | let staked_amount = match info.amount { 317 | Some((staked, ..)) => staked, 318 | None => 0, 319 | }; 320 | println!("{}", Dusk::from(staked_amount)); 321 | } 322 | } 323 | RunResult::ExportedKeys(pub_key, key_pair) => { 324 | println!("{},{}", pub_key.display(), key_pair.display()) 325 | } 326 | RunResult::History(transactions) => { 327 | println!("{}", TransactionHistory::header()); 328 | for th in transactions { 329 | println!("{th}"); 330 | } 331 | } 332 | RunResult::Settings() => {} 333 | RunResult::Create() | RunResult::Restore() => {} 334 | }, 335 | None => { 336 | wallet.register_sync().await?; 337 | interactive::run_loop(&mut wallet, &settings).await?; 338 | } 339 | } 340 | 341 | Ok(()) 342 | } 343 | -------------------------------------------------------------------------------- /src/clients.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | mod sync; 8 | 9 | use dusk_bls12_381_sign::PublicKey; 10 | use dusk_bytes::{DeserializableSlice, Serializable, Write}; 11 | use dusk_pki::ViewKey; 12 | use dusk_plonk::prelude::*; 13 | use dusk_plonk::proof_system::Proof; 14 | use dusk_schnorr::Signature; 15 | use dusk_wallet_core::{ 16 | EnrichedNote, ProverClient, StakeInfo, StateClient, Transaction, 17 | UnprovenTransaction, POSEIDON_TREE_DEPTH, 18 | }; 19 | use flume::Sender; 20 | use phoenix_core::transaction::StakeData; 21 | use phoenix_core::{Crossover, Fee, Note}; 22 | use poseidon_merkle::Opening as PoseidonOpening; 23 | use tokio::time::{sleep, Duration}; 24 | 25 | use std::path::Path; 26 | use std::sync::{Arc, Mutex}; 27 | 28 | use self::sync::sync_db; 29 | 30 | use super::block::Block; 31 | use super::cache::Cache; 32 | 33 | use crate::rusk::{RuskHttpClient, RuskRequest}; 34 | use crate::store::LocalStore; 35 | use crate::Error; 36 | 37 | const STCT_INPUT_SIZE: usize = Fee::SIZE 38 | + Crossover::SIZE 39 | + u64::SIZE 40 | + JubJubScalar::SIZE 41 | + BlsScalar::SIZE 42 | + Signature::SIZE; 43 | 44 | const WFCT_INPUT_SIZE: usize = 45 | JubJubAffine::SIZE + u64::SIZE + JubJubScalar::SIZE; 46 | 47 | const TRANSFER_CONTRACT: &str = 48 | "0100000000000000000000000000000000000000000000000000000000000000"; 49 | 50 | const STAKE_CONTRACT: &str = 51 | "0200000000000000000000000000000000000000000000000000000000000000"; 52 | 53 | // Sync every 3 seconds for now 54 | const SYNC_INTERVAL_SECONDS: u64 = 3; 55 | 56 | /// Implementation of the ProverClient trait from wallet-core 57 | pub struct Prover { 58 | state: RuskHttpClient, 59 | prover: RuskHttpClient, 60 | status: fn(status: &str), 61 | } 62 | 63 | impl Prover { 64 | pub fn new(state: RuskHttpClient, prover: RuskHttpClient) -> Self { 65 | Prover { 66 | state, 67 | prover, 68 | status: |_| {}, 69 | } 70 | } 71 | 72 | /// Sets the callback method to send status updates 73 | pub fn set_status_callback(&mut self, status: fn(&str)) { 74 | self.status = status; 75 | } 76 | 77 | pub async fn check_connection(&self) -> Result<(), reqwest::Error> { 78 | self.state.check_connection().await?; 79 | self.prover.check_connection().await 80 | } 81 | } 82 | 83 | impl ProverClient for Prover { 84 | /// Error returned by the prover client. 85 | type Error = Error; 86 | 87 | /// Requests that a node prove the given transaction and later propagates it 88 | fn compute_proof_and_propagate( 89 | &self, 90 | utx: &UnprovenTransaction, 91 | ) -> Result { 92 | self.status("Proving tx, please wait..."); 93 | let utx_bytes = utx.to_var_bytes(); 94 | let prove_req = RuskRequest::new("prove_execute", utx_bytes); 95 | let proof_bytes = self.prover.call(2, "rusk", &prove_req).wait()?; 96 | self.status("Proof success!"); 97 | let proof = Proof::from_slice(&proof_bytes).map_err(Error::Bytes)?; 98 | let tx = utx.clone().prove(proof); 99 | let tx_bytes = tx.to_var_bytes(); 100 | 101 | self.status("Attempt to preverify tx..."); 102 | let preverify_req = RuskRequest::new("preverify", tx_bytes.clone()); 103 | let _ = self.state.call(2, "rusk", &preverify_req).wait()?; 104 | self.status("Preverify success!"); 105 | 106 | self.status("Propagating tx..."); 107 | let propagate_req = RuskRequest::new("propagate_tx", tx_bytes); 108 | let _ = self.state.call(2, "Chain", &propagate_req).wait()?; 109 | self.status("Transaction propagated!"); 110 | 111 | Ok(tx) 112 | } 113 | 114 | /// Requests an STCT proof. 115 | fn request_stct_proof( 116 | &self, 117 | fee: &Fee, 118 | crossover: &Crossover, 119 | value: u64, 120 | blinder: JubJubScalar, 121 | address: BlsScalar, 122 | signature: Signature, 123 | ) -> Result { 124 | let mut buf = [0; STCT_INPUT_SIZE]; 125 | let mut writer = &mut buf[..]; 126 | writer.write(&fee.to_bytes())?; 127 | writer.write(&crossover.to_bytes())?; 128 | writer.write(&value.to_bytes())?; 129 | writer.write(&blinder.to_bytes())?; 130 | writer.write(&address.to_bytes())?; 131 | writer.write(&signature.to_bytes())?; 132 | 133 | self.status("Requesting stct proof..."); 134 | 135 | let prove_req = RuskRequest::new("prove_stct", buf.to_vec()); 136 | let res = self.prover.call(2, "rusk", &prove_req).wait()?; 137 | 138 | self.status("Stct proof success!"); 139 | 140 | let mut proof_bytes = [0u8; Proof::SIZE]; 141 | proof_bytes.copy_from_slice(&res); 142 | 143 | let proof = Proof::from_bytes(&proof_bytes)?; 144 | Ok(proof) 145 | } 146 | 147 | /// Request a WFCT proof. 148 | fn request_wfct_proof( 149 | &self, 150 | commitment: JubJubAffine, 151 | value: u64, 152 | blinder: JubJubScalar, 153 | ) -> Result { 154 | let mut buf = [0; WFCT_INPUT_SIZE]; 155 | let mut writer = &mut buf[..]; 156 | writer.write(&commitment.to_bytes())?; 157 | writer.write(&value.to_bytes())?; 158 | writer.write(&blinder.to_bytes())?; 159 | 160 | self.status("Requesting wfct proof..."); 161 | let prove_req = RuskRequest::new("prove_wfct", buf.to_vec()); 162 | let res = self.prover.call(2, "rusk", &prove_req).wait()?; 163 | self.status("Wfct proof success!"); 164 | 165 | let mut proof_bytes = [0u8; Proof::SIZE]; 166 | proof_bytes.copy_from_slice(&res); 167 | 168 | let proof = Proof::from_bytes(&proof_bytes)?; 169 | Ok(proof) 170 | } 171 | } 172 | 173 | impl Prover { 174 | fn status(&self, text: &str) { 175 | (self.status)(text) 176 | } 177 | } 178 | 179 | /// Implementation of the StateClient trait from wallet-core 180 | /// inner is an option because we don't want to open the db twice and lock it 181 | /// We construct StateStore twice 182 | pub struct StateStore { 183 | inner: Mutex, 184 | status: fn(&str), 185 | pub(crate) store: LocalStore, 186 | } 187 | 188 | struct InnerState { 189 | client: RuskHttpClient, 190 | cache: Arc, 191 | } 192 | 193 | impl StateStore { 194 | /// Creates a new state instance. Should only be called once. 195 | pub(crate) fn new( 196 | client: RuskHttpClient, 197 | data_dir: &Path, 198 | store: LocalStore, 199 | status: fn(&str), 200 | ) -> Result { 201 | let cache = Arc::new(Cache::new(data_dir, &store, status)?); 202 | let inner = Mutex::new(InnerState { client, cache }); 203 | 204 | Ok(Self { 205 | inner, 206 | status, 207 | store, 208 | }) 209 | } 210 | 211 | pub async fn check_connection(&self) -> Result<(), reqwest::Error> { 212 | let client = { self.inner.lock().unwrap().client.clone() }; 213 | 214 | client.check_connection().await 215 | } 216 | 217 | pub async fn register_sync( 218 | &self, 219 | sync_tx: Sender, 220 | ) -> Result<(), Error> { 221 | let state = self.inner.lock().unwrap(); 222 | let status = self.status; 223 | let store = self.store.clone(); 224 | let client = state.client.clone(); 225 | let cache = Arc::clone(&state.cache); 226 | let sender = Arc::new(sync_tx); 227 | 228 | status("Starting Sync.."); 229 | 230 | tokio::spawn(async move { 231 | loop { 232 | let status = |_: &_| {}; 233 | let sender = Arc::clone(&sender); 234 | let _ = sender.send("Syncing..".to_string()); 235 | 236 | let sync_status = 237 | sync_db(&client, &store, &cache, status).await; 238 | let _ = match sync_status { 239 | Ok(_) => sender.send("Syncing Complete".to_string()), 240 | Err(e) => sender.send(format!("Error during sync:.. {e}")), 241 | }; 242 | 243 | sleep(Duration::from_secs(SYNC_INTERVAL_SECONDS)).await; 244 | } 245 | }); 246 | 247 | Ok(()) 248 | } 249 | 250 | pub async fn sync(&self) -> Result<(), Error> { 251 | let store = self.store.clone(); 252 | let status = self.status; 253 | let (cache, client) = { 254 | let state = self.inner.lock().unwrap(); 255 | 256 | let cache = state.cache.clone(); 257 | let client = state.client.clone(); 258 | (cache, client) 259 | }; 260 | 261 | sync_db(&client, &store, cache.as_ref(), status).await 262 | } 263 | 264 | pub(crate) fn cache(&self) -> Arc { 265 | let state = self.inner.lock().unwrap(); 266 | Arc::clone(&state.cache) 267 | } 268 | } 269 | 270 | /// Types that are clients of the state API. 271 | impl StateClient for StateStore { 272 | /// Error returned by the node client. 273 | type Error = Error; 274 | 275 | /// Find notes for a view key, starting from the given block height. 276 | fn fetch_notes( 277 | &self, 278 | vk: &ViewKey, 279 | ) -> Result, Self::Error> { 280 | let psk = vk.public_spend_key(); 281 | let state = self.inner.lock().unwrap(); 282 | 283 | Ok(state 284 | .cache 285 | .notes(&psk)? 286 | .into_iter() 287 | .map(|data| (data.note, data.height)) 288 | .collect()) 289 | } 290 | 291 | /// Fetch the current anchor of the state. 292 | fn fetch_anchor(&self) -> Result { 293 | let state = self.inner.lock().unwrap(); 294 | 295 | self.status("Fetching anchor..."); 296 | 297 | let anchor = state 298 | .client 299 | .contract_query::<(), 0>(TRANSFER_CONTRACT, "root", &()) 300 | .wait()?; 301 | self.status("Anchor received!"); 302 | let anchor = rkyv::from_bytes(&anchor).map_err(|_| Error::Rkyv)?; 303 | Ok(anchor) 304 | } 305 | 306 | /// Asks the node to return the nullifiers that already exist from the given 307 | /// nullifiers. 308 | fn fetch_existing_nullifiers( 309 | &self, 310 | _nullifiers: &[BlsScalar], 311 | ) -> Result, Self::Error> { 312 | Ok(vec![]) 313 | } 314 | 315 | /// Queries the node to find the opening for a specific note. 316 | fn fetch_opening( 317 | &self, 318 | note: &Note, 319 | ) -> Result, Self::Error> { 320 | let state = self.inner.lock().unwrap(); 321 | 322 | self.status("Fetching opening notes..."); 323 | 324 | let data = state 325 | .client 326 | .contract_query::<_, 1024>(TRANSFER_CONTRACT, "opening", note.pos()) 327 | .wait()?; 328 | 329 | self.status("Opening notes received!"); 330 | 331 | let branch = rkyv::from_bytes(&data).map_err(|_| Error::Rkyv)?; 332 | Ok(branch) 333 | } 334 | 335 | /// Queries the node for the amount staked by a key. 336 | fn fetch_stake(&self, pk: &PublicKey) -> Result { 337 | let state = self.inner.lock().unwrap(); 338 | 339 | self.status("Fetching stake..."); 340 | 341 | let data = state 342 | .client 343 | .contract_query::<_, 1024>(STAKE_CONTRACT, "get_stake", pk) 344 | .wait()?; 345 | 346 | let res: Option = 347 | rkyv::from_bytes(&data).map_err(|_| Error::Rkyv)?; 348 | self.status("Stake received!"); 349 | 350 | let staking_address = pk.to_bytes().to_vec(); 351 | let staking_address = bs58::encode(staking_address).into_string(); 352 | println!("Staking address: {}", staking_address); 353 | 354 | // FIX_ME: proper solution should to return an Option 355 | // changing the trait implementation. That would reflect the state of 356 | // the stake contract. It would be up to the consumer to decide what to 357 | // do with a None 358 | let stake = res 359 | .map( 360 | |StakeData { 361 | amount, 362 | reward, 363 | counter, 364 | }| StakeInfo { 365 | amount, 366 | reward, 367 | counter, 368 | }, 369 | ) 370 | .unwrap_or_default(); 371 | 372 | Ok(stake) 373 | } 374 | } 375 | 376 | impl StateStore { 377 | fn status(&self, text: &str) { 378 | (self.status)(text) 379 | } 380 | } 381 | -------------------------------------------------------------------------------- /src/bin/command.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | mod history; 8 | 9 | use clap::Subcommand; 10 | use dusk_plonk::prelude::BlsScalar; 11 | use rusk_abi::hash::Hasher; 12 | use std::{fmt, path::PathBuf}; 13 | 14 | use crate::io::prompt; 15 | use crate::settings::Settings; 16 | use crate::{WalletFile, WalletPath}; 17 | 18 | use dusk_wallet::gas::{Gas, DEFAULT_LIMIT, DEFAULT_PRICE}; 19 | use dusk_wallet::{Address, Dusk, Lux, Wallet, EPOCH, MAX_ADDRESSES}; 20 | use dusk_wallet_core::{BalanceInfo, StakeInfo}; 21 | 22 | pub use history::TransactionHistory; 23 | 24 | /// The default stake gas limit 25 | pub const DEFAULT_STAKE_GAS_LIMIT: u64 = 2_900_000_000; 26 | 27 | /// Commands that can be run against the Dusk wallet 28 | #[allow(clippy::large_enum_variant)] 29 | #[derive(PartialEq, Eq, Hash, Clone, Subcommand, Debug)] 30 | pub(crate) enum Command { 31 | /// Create a new wallet 32 | Create { 33 | /// Skip wallet recovery phrase (useful for headless wallet creation) 34 | #[clap(long, action)] 35 | skip_recovery: bool, 36 | 37 | /// Save recovery phrase to file (useful for headless wallet creation) 38 | #[clap(long)] 39 | seed_file: Option, 40 | }, 41 | 42 | /// Restore a lost wallet 43 | Restore { 44 | /// Set the wallet .dat file to restore from 45 | #[clap(short, long)] 46 | file: Option, 47 | }, 48 | 49 | /// Check your current balance 50 | Balance { 51 | /// Address 52 | #[clap(short, long)] 53 | addr: Option
, 54 | 55 | /// Check maximum spendable balance 56 | #[clap(long)] 57 | spendable: bool, 58 | }, 59 | 60 | /// List your existing addresses and generate new ones 61 | Addresses { 62 | /// Create new address 63 | #[clap(short, long, action)] 64 | new: bool, 65 | }, 66 | 67 | /// Show address transaction history 68 | History { 69 | /// Address for which you want to see the history 70 | #[clap(short, long)] 71 | addr: Option
, 72 | }, 73 | 74 | /// Send DUSK through the network 75 | Transfer { 76 | /// Address from which to send DUSK [default: first address] 77 | #[clap(short, long)] 78 | sndr: Option
, 79 | 80 | /// Receiver address 81 | #[clap(short, long)] 82 | rcvr: Address, 83 | 84 | /// Amount of DUSK to send 85 | #[clap(short, long)] 86 | amt: Dusk, 87 | 88 | /// Max amt of gas for this transaction 89 | #[clap(short = 'l', long, default_value_t= DEFAULT_LIMIT)] 90 | gas_limit: u64, 91 | 92 | /// Price you're going to pay for each gas unit (in LUX) 93 | #[clap(short = 'p', long, default_value_t= DEFAULT_PRICE)] 94 | gas_price: Lux, 95 | }, 96 | 97 | /// Start staking DUSK 98 | Stake { 99 | /// Address from which to stake DUSK [default: first address] 100 | #[clap(short = 's', long)] 101 | addr: Option
, 102 | 103 | /// Amount of DUSK to stake 104 | #[clap(short, long)] 105 | amt: Dusk, 106 | 107 | /// Max amt of gas for this transaction 108 | #[clap(short = 'l', long, default_value_t= DEFAULT_STAKE_GAS_LIMIT)] 109 | gas_limit: u64, 110 | 111 | /// Price you're going to pay for each gas unit (in LUX) 112 | #[clap(short = 'p', long, default_value_t= DEFAULT_PRICE)] 113 | gas_price: Lux, 114 | }, 115 | 116 | /// Check your stake information 117 | StakeInfo { 118 | /// Address used to stake [default: first address] 119 | #[clap(short, long)] 120 | addr: Option
, 121 | 122 | /// Check accumulated reward 123 | #[clap(long, action)] 124 | reward: bool, 125 | }, 126 | 127 | /// Unstake a key's stake 128 | Unstake { 129 | /// Address from which your DUSK was staked [default: first address] 130 | #[clap(short, long)] 131 | addr: Option
, 132 | 133 | /// Max amt of gas for this transaction 134 | #[clap(short = 'l', long, default_value_t= DEFAULT_STAKE_GAS_LIMIT)] 135 | gas_limit: u64, 136 | 137 | /// Price you're going to pay for each gas unit (in LUX) 138 | #[clap(short = 'p', long, default_value_t= DEFAULT_PRICE)] 139 | gas_price: Lux, 140 | }, 141 | 142 | /// Withdraw accumulated reward for a stake key 143 | Withdraw { 144 | /// Address from which your DUSK was staked [default: first address] 145 | #[clap(short, long)] 146 | addr: Option
, 147 | 148 | /// Max amt of gas for this transaction 149 | #[clap(short = 'l', long, default_value_t= DEFAULT_STAKE_GAS_LIMIT)] 150 | gas_limit: u64, 151 | 152 | /// Price you're going to pay for each gas unit (in LUX) 153 | #[clap(short = 'p', long, default_value_t= DEFAULT_PRICE)] 154 | gas_price: Lux, 155 | }, 156 | 157 | /// Export BLS provisioner key pair 158 | Export { 159 | /// Address for which you want the exported keys [default: first 160 | /// address] 161 | #[clap(short, long)] 162 | addr: Option
, 163 | 164 | /// Output directory for the exported keys 165 | #[clap(short, long)] 166 | dir: PathBuf, 167 | 168 | /// Name of the files exported [default: staking-address] 169 | #[clap(short, long)] 170 | name: Option, 171 | }, 172 | 173 | /// Show current settings 174 | Settings, 175 | } 176 | 177 | impl Command { 178 | /// Runs the command with the provided wallet 179 | pub async fn run( 180 | self, 181 | wallet: &mut Wallet, 182 | settings: &Settings, 183 | ) -> anyhow::Result { 184 | match self { 185 | Command::Balance { addr, spendable } => { 186 | let sync_result = wallet.sync().await; 187 | if let Err(e) = sync_result { 188 | // Sync error should be reported only if wallet is online 189 | if wallet.is_online().await { 190 | tracing::error!("Unable to update the balance {e:?}") 191 | } 192 | } 193 | 194 | let addr = match addr { 195 | Some(addr) => wallet.claim_as_address(addr)?, 196 | None => wallet.default_address(), 197 | }; 198 | 199 | let balance = wallet.get_balance(addr).await?; 200 | Ok(RunResult::Balance(balance, spendable)) 201 | } 202 | Command::Addresses { new } => { 203 | if new { 204 | if wallet.addresses().len() >= MAX_ADDRESSES { 205 | println!( 206 | "Cannot create more addresses, this wallet only supports up to {MAX_ADDRESSES} addresses. You have {} addresses already.", wallet.addresses().len() 207 | ); 208 | std::process::exit(0); 209 | } 210 | 211 | let addr = wallet.new_address().clone(); 212 | wallet.save()?; 213 | Ok(RunResult::Address(Box::new(addr))) 214 | } else { 215 | Ok(RunResult::Addresses(wallet.addresses().clone())) 216 | } 217 | } 218 | Command::Transfer { 219 | sndr, 220 | rcvr, 221 | amt, 222 | gas_limit, 223 | gas_price, 224 | } => { 225 | wallet.sync().await?; 226 | let sender = match sndr { 227 | Some(addr) => wallet.claim_as_address(addr)?, 228 | None => wallet.default_address(), 229 | }; 230 | let gas = Gas::new(gas_limit).with_price(gas_price); 231 | 232 | let tx = wallet.transfer(sender, &rcvr, amt, gas).await?; 233 | Ok(RunResult::Tx(Hasher::digest(tx.to_hash_input_bytes()))) 234 | } 235 | Command::Stake { 236 | addr, 237 | amt, 238 | gas_limit, 239 | gas_price, 240 | } => { 241 | wallet.sync().await?; 242 | let addr = match addr { 243 | Some(addr) => wallet.claim_as_address(addr)?, 244 | None => wallet.default_address(), 245 | }; 246 | let gas = Gas::new(gas_limit).with_price(gas_price); 247 | 248 | let tx = wallet.stake(addr, amt, gas).await?; 249 | Ok(RunResult::Tx(Hasher::digest(tx.to_hash_input_bytes()))) 250 | } 251 | Command::StakeInfo { addr, reward } => { 252 | let addr = match addr { 253 | Some(addr) => wallet.claim_as_address(addr)?, 254 | None => wallet.default_address(), 255 | }; 256 | let si = wallet.stake_info(addr).await?; 257 | Ok(RunResult::StakeInfo(si, reward)) 258 | } 259 | Command::Unstake { 260 | addr, 261 | gas_limit, 262 | gas_price, 263 | } => { 264 | wallet.sync().await?; 265 | let addr = match addr { 266 | Some(addr) => wallet.claim_as_address(addr)?, 267 | None => wallet.default_address(), 268 | }; 269 | 270 | let gas = Gas::new(gas_limit).with_price(gas_price); 271 | 272 | let tx = wallet.unstake(addr, gas).await?; 273 | Ok(RunResult::Tx(Hasher::digest(tx.to_hash_input_bytes()))) 274 | } 275 | Command::Withdraw { 276 | addr, 277 | gas_limit, 278 | gas_price, 279 | } => { 280 | wallet.sync().await?; 281 | let addr = match addr { 282 | Some(addr) => wallet.claim_as_address(addr)?, 283 | None => wallet.default_address(), 284 | }; 285 | 286 | let gas = Gas::new(gas_limit).with_price(gas_price); 287 | 288 | let tx = wallet.withdraw_reward(addr, gas).await?; 289 | Ok(RunResult::Tx(Hasher::digest(tx.to_hash_input_bytes()))) 290 | } 291 | Command::Export { addr, dir, name } => { 292 | let addr = match addr { 293 | Some(addr) => wallet.claim_as_address(addr)?, 294 | None => wallet.default_address(), 295 | }; 296 | 297 | let pwd = prompt::request_auth( 298 | "Provide a password for your provisioner keys", 299 | &settings.password, 300 | wallet.get_file_version()?, 301 | )?; 302 | 303 | let (pub_key, key_pair) = 304 | wallet.export_keys(addr, &dir, name, &pwd)?; 305 | 306 | Ok(RunResult::ExportedKeys(pub_key, key_pair)) 307 | } 308 | Command::History { addr } => { 309 | wallet.sync().await?; 310 | let addr = match addr { 311 | Some(addr) => wallet.claim_as_address(addr)?, 312 | None => wallet.default_address(), 313 | }; 314 | let notes = wallet.get_all_notes(addr).await?; 315 | 316 | let transactions = 317 | history::transaction_from_notes(settings, notes).await?; 318 | 319 | Ok(RunResult::History(transactions)) 320 | } 321 | Command::Create { .. } => Ok(RunResult::Create()), 322 | Command::Restore { .. } => Ok(RunResult::Restore()), 323 | Command::Settings => Ok(RunResult::Settings()), 324 | } 325 | } 326 | } 327 | 328 | /// Possible results of running a command in interactive mode 329 | pub enum RunResult { 330 | Tx(BlsScalar), 331 | Balance(BalanceInfo, bool), 332 | StakeInfo(StakeInfo, bool), 333 | Address(Box
), 334 | Addresses(Vec
), 335 | ExportedKeys(PathBuf, PathBuf), 336 | Create(), 337 | Restore(), 338 | Settings(), 339 | History(Vec), 340 | } 341 | 342 | impl fmt::Display for RunResult { 343 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 344 | use RunResult::*; 345 | match self { 346 | Balance(balance, _) => { 347 | write!( 348 | f, 349 | "> Total balance is: {} DUSK\n> Maximum spendable per TX is: {} DUSK", 350 | Dusk::from(balance.value), 351 | Dusk::from(balance.spendable) 352 | ) 353 | } 354 | Address(addr) => { 355 | write!(f, "> {}", addr) 356 | } 357 | Addresses(addrs) => { 358 | let str_addrs = addrs 359 | .iter() 360 | .map(|a| format!("{}", a)) 361 | .collect::>() 362 | .join("\n>"); 363 | write!(f, "> {}", str_addrs) 364 | } 365 | Tx(hash) => { 366 | let hash = hex::encode(hash.to_bytes()); 367 | write!(f, "> Transaction sent: {hash}",) 368 | } 369 | StakeInfo(si, _) => { 370 | let stake_str = match si.amount { 371 | Some((value, eligibility)) => format!( 372 | "Current stake amount is: {} DUSK\n> Stake eligibility from block #{} (Epoch {})", 373 | Dusk::from(value), 374 | eligibility, 375 | eligibility / EPOCH 376 | ), 377 | None => "No active stake found for this key".to_string(), 378 | }; 379 | write!( 380 | f, 381 | "> {}\n> Accumulated reward is: {} DUSK", 382 | stake_str, 383 | Dusk::from(si.reward) 384 | ) 385 | } 386 | ExportedKeys(pk, kp) => { 387 | write!( 388 | f, 389 | "> Public key exported to: {}\n> Key pair exported to: {}", 390 | pk.display(), 391 | kp.display() 392 | ) 393 | } 394 | History(transactions) => { 395 | writeln!(f, "{}", TransactionHistory::header())?; 396 | for th in transactions { 397 | writeln!(f, "{th}")?; 398 | } 399 | Ok(()) 400 | } 401 | Create() | Restore() | Settings() => unreachable!(), 402 | } 403 | } 404 | } 405 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /src/bin/interactive.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | // 5 | // Copyright (c) DUSK NETWORK. All rights reserved. 6 | 7 | use bip39::{Language, Mnemonic, MnemonicType}; 8 | use dusk_wallet::dat::{DatFileVersion, LATEST_VERSION}; 9 | use dusk_wallet::gas; 10 | use dusk_wallet::{Address, Dusk, Error, Wallet, WalletPath, MAX_ADDRESSES}; 11 | use requestty::Question; 12 | 13 | use crate::command::DEFAULT_STAKE_GAS_LIMIT; 14 | use crate::io; 15 | use crate::io::prompt::request_auth; 16 | use crate::io::GraphQL; 17 | use crate::prompt; 18 | use crate::settings::Settings; 19 | use crate::Menu; 20 | use crate::WalletFile; 21 | use crate::{Command, RunResult}; 22 | 23 | /// Run the interactive UX loop with a loaded wallet 24 | pub(crate) async fn run_loop( 25 | wallet: &mut Wallet, 26 | settings: &Settings, 27 | ) -> anyhow::Result<()> { 28 | loop { 29 | // let the user choose (or create) an address 30 | let addr = match menu_addr(wallet)? { 31 | AddrSelect::Address(addr) => *addr, 32 | AddrSelect::NewAddress => { 33 | if wallet.addresses().len() >= MAX_ADDRESSES { 34 | println!( 35 | "Cannot create more addresses, this wallet only supports up to {MAX_ADDRESSES} addresses" 36 | ); 37 | std::process::exit(0); 38 | } 39 | 40 | let addr = wallet.new_address().clone(); 41 | let file_version = wallet.get_file_version()?; 42 | 43 | let password = &settings.password; 44 | // if the version file is old, ask for password and save as 45 | // latest dat file 46 | if file_version.is_old() { 47 | let pwd = request_auth( 48 | "Updating your wallet data file, please enter your wallet password ", 49 | password, 50 | DatFileVersion::RuskBinaryFileFormat(LATEST_VERSION), 51 | )?; 52 | 53 | wallet.save_to(WalletFile { 54 | path: wallet.file().clone().unwrap().path, 55 | pwd, 56 | })?; 57 | } else { 58 | // else just save 59 | wallet.save()?; 60 | } 61 | 62 | addr 63 | } 64 | AddrSelect::Exit => std::process::exit(0), 65 | }; 66 | 67 | loop { 68 | // get balance for this address 69 | prompt::hide_cursor()?; 70 | let balance = wallet.get_balance(&addr).await?; 71 | let spendable: Dusk = balance.spendable.into(); 72 | let total: Dusk = balance.value.into(); 73 | prompt::hide_cursor()?; 74 | 75 | // display address information 76 | println!(); 77 | println!("Address: {addr}"); 78 | println!("Balance:"); 79 | println!(" - Spendable: {spendable}"); 80 | println!(" - Total: {total}"); 81 | 82 | // request operation to perform 83 | let op = match wallet.is_online().await { 84 | true => menu_op(addr.clone(), spendable, settings), 85 | false => menu_op_offline(addr.clone(), settings), 86 | }; 87 | 88 | // perform operations with this address 89 | match op? { 90 | AddrOp::Run(cmd) => { 91 | // request confirmation before running 92 | if confirm(&cmd)? { 93 | // run command 94 | prompt::hide_cursor()?; 95 | let result = cmd.run(wallet, settings).await; 96 | prompt::show_cursor()?; 97 | // output results 98 | match result { 99 | Ok(res) => { 100 | println!("\r{}", res); 101 | if let RunResult::Tx(hash) = res { 102 | let tx_id = hex::encode(hash.to_bytes()); 103 | 104 | // Wait for transaction confirmation from 105 | // network 106 | let gql = GraphQL::new( 107 | &settings.state.to_string(), 108 | io::status::interactive, 109 | ); 110 | gql.wait_for(&tx_id).await?; 111 | 112 | if let Some(explorer) = &settings.explorer { 113 | let url = format!("{explorer}{tx_id}"); 114 | println!("> URL: {url}"); 115 | prompt::launch_explorer(url)?; 116 | } 117 | } 118 | } 119 | 120 | Err(err) => println!("{err}"), 121 | } 122 | } 123 | } 124 | AddrOp::Back => break, 125 | } 126 | } 127 | } 128 | } 129 | 130 | #[derive(PartialEq, Eq, Hash, Debug, Clone)] 131 | enum AddrSelect { 132 | Address(Box
), 133 | NewAddress, 134 | Exit, 135 | } 136 | 137 | /// Allows the user to choose an address from the selected wallet 138 | /// to start performing operations. 139 | fn menu_addr(wallet: &Wallet) -> anyhow::Result { 140 | let mut address_menu = Menu::title("Addresses"); 141 | for addr in wallet.addresses() { 142 | let preview = addr.preview(); 143 | address_menu = address_menu 144 | .add(AddrSelect::Address(Box::new(addr.clone())), preview); 145 | } 146 | 147 | let remaining_addresses = 148 | MAX_ADDRESSES.saturating_sub(wallet.addresses().len()); 149 | let mut action_menu = Menu::new() 150 | .separator() 151 | .add(AddrSelect::NewAddress, "New address"); 152 | 153 | // show warning if less than 154 | if remaining_addresses < 5 { 155 | action_menu = action_menu.separator().separator_msg(format!( 156 | "\x1b[93m{}\x1b[0m This wallet only supports up to {MAX_ADDRESSES} addresses, you have {} addresses ", 157 | "Warning:", 158 | wallet.addresses().len() 159 | )); 160 | } 161 | 162 | if let Some(rx) = &wallet.sync_rx { 163 | if let Ok(status) = rx.try_recv() { 164 | action_menu = action_menu 165 | .separator() 166 | .separator_msg(format!("Sync Status: {}", status)); 167 | } else { 168 | action_menu = action_menu 169 | .separator() 170 | .separator_msg("Waiting for Sync to complete..".to_string()); 171 | } 172 | } 173 | 174 | action_menu = action_menu.separator().add(AddrSelect::Exit, "Exit"); 175 | 176 | let menu = address_menu.extend(action_menu); 177 | let questions = Question::select("theme") 178 | .message("Please select an address") 179 | .choices(menu.clone()) 180 | .build(); 181 | 182 | let answer = requestty::prompt_one(questions)?; 183 | Ok(menu.answer(&answer).to_owned()) 184 | } 185 | 186 | #[derive(PartialEq, Eq, Hash, Debug, Clone)] 187 | enum AddrOp { 188 | Run(Box), 189 | Back, 190 | } 191 | 192 | #[derive(PartialEq, Eq, Hash, Clone, Debug)] 193 | enum CommandMenuItem { 194 | History, 195 | Transfer, 196 | Stake, 197 | StakeInfo, 198 | Unstake, 199 | Withdraw, 200 | Export, 201 | Back, 202 | } 203 | 204 | /// Allows the user to choose the operation to perform for the 205 | /// selected address 206 | fn menu_op( 207 | addr: Address, 208 | balance: Dusk, 209 | settings: &Settings, 210 | ) -> anyhow::Result { 211 | use CommandMenuItem as CMI; 212 | 213 | let cmd_menu = Menu::new() 214 | .add(CMI::History, "Transaction History") 215 | .add(CMI::Transfer, "Transfer Dusk") 216 | .add(CMI::Stake, "Stake Dusk") 217 | .add(CMI::StakeInfo, "Check existing stake") 218 | .add(CMI::Unstake, "Unstake Dusk") 219 | .add(CMI::Withdraw, "Withdraw staking reward") 220 | .add(CMI::Export, "Export provisioner key-pair") 221 | .separator() 222 | .add(CMI::Back, "Back"); 223 | 224 | let q = Question::select("theme") 225 | .message("What would you like to do?") 226 | .choices(cmd_menu.clone()) 227 | .build(); 228 | 229 | let answer = requestty::prompt_one(q)?; 230 | let cmd = cmd_menu.answer(&answer).to_owned(); 231 | 232 | let res = match cmd { 233 | CMI::History => { 234 | AddrOp::Run(Box::new(Command::History { addr: Some(addr) })) 235 | } 236 | CMI::Transfer => AddrOp::Run(Box::new(Command::Transfer { 237 | sndr: Some(addr), 238 | rcvr: prompt::request_rcvr_addr("recipient")?, 239 | amt: prompt::request_token_amt("transfer", balance)?, 240 | gas_limit: prompt::request_gas_limit(gas::DEFAULT_LIMIT)?, 241 | gas_price: prompt::request_gas_price()?, 242 | })), 243 | CMI::Stake => AddrOp::Run(Box::new(Command::Stake { 244 | addr: Some(addr), 245 | amt: prompt::request_token_amt("stake", balance)?, 246 | gas_limit: prompt::request_gas_limit(DEFAULT_STAKE_GAS_LIMIT)?, 247 | gas_price: prompt::request_gas_price()?, 248 | })), 249 | CMI::StakeInfo => AddrOp::Run(Box::new(Command::StakeInfo { 250 | addr: Some(addr), 251 | reward: false, 252 | })), 253 | CMI::Unstake => AddrOp::Run(Box::new(Command::Unstake { 254 | addr: Some(addr), 255 | gas_limit: prompt::request_gas_limit(DEFAULT_STAKE_GAS_LIMIT)?, 256 | gas_price: prompt::request_gas_price()?, 257 | })), 258 | CMI::Withdraw => AddrOp::Run(Box::new(Command::Withdraw { 259 | addr: Some(addr), 260 | gas_limit: prompt::request_gas_limit(DEFAULT_STAKE_GAS_LIMIT)?, 261 | gas_price: prompt::request_gas_price()?, 262 | })), 263 | CMI::Export => AddrOp::Run(Box::new(Command::Export { 264 | addr: Some(addr), 265 | name: None, 266 | dir: prompt::request_dir("export keys", settings.profile.clone())?, 267 | })), 268 | CMI::Back => AddrOp::Back, 269 | }; 270 | Ok(res) 271 | } 272 | 273 | /// Allows the user to choose the operation to perform for the 274 | /// selected address while in offline mode 275 | fn menu_op_offline( 276 | addr: Address, 277 | settings: &Settings, 278 | ) -> anyhow::Result { 279 | use CommandMenuItem as CMI; 280 | 281 | let cmd_menu = Menu::new() 282 | .separator() 283 | .add(CMI::Export, "Export provisioner key-pair") 284 | .separator() 285 | .add(CMI::Back, "Back"); 286 | 287 | let q = Question::select("theme") 288 | .message("[OFFLINE] What would you like to do?") 289 | .choices(cmd_menu.clone()) 290 | .build(); 291 | 292 | let answer = requestty::prompt_one(q)?; 293 | let cmd = cmd_menu.answer(&answer).to_owned(); 294 | 295 | let res = match cmd { 296 | CMI::Export => AddrOp::Run(Box::new(Command::Export { 297 | addr: Some(addr), 298 | name: None, 299 | dir: prompt::request_dir("export keys", settings.profile.clone())?, 300 | })), 301 | CMI::Back => AddrOp::Back, 302 | _ => unreachable!(), 303 | }; 304 | Ok(res) 305 | } 306 | 307 | /// Allows the user to load a wallet interactively 308 | pub(crate) fn load_wallet( 309 | wallet_path: &WalletPath, 310 | settings: &Settings, 311 | file_version: Result, 312 | ) -> anyhow::Result> { 313 | let wallet_found = 314 | wallet_path.inner().exists().then(|| wallet_path.clone()); 315 | 316 | let password = &settings.password; 317 | 318 | // display main menu 319 | let wallet = match menu_wallet(wallet_found)? { 320 | MainMenu::Load(path) => { 321 | let file_version = file_version?; 322 | let mut attempt = 1; 323 | loop { 324 | let pwd = prompt::request_auth( 325 | "Please enter your wallet password", 326 | password, 327 | file_version, 328 | )?; 329 | match Wallet::from_file(WalletFile { 330 | path: path.clone(), 331 | pwd, 332 | }) { 333 | Ok(wallet) => break wallet, 334 | Err(_) if attempt > 2 => { 335 | Err(Error::AttemptsExhausted)?; 336 | } 337 | Err(_) => { 338 | println!("Invalid password, please try again"); 339 | attempt += 1; 340 | } 341 | } 342 | } 343 | } 344 | // Use the latest binary format when creating a wallet 345 | MainMenu::Create => { 346 | // create a new randomly generated mnemonic phrase 347 | let mnemonic = 348 | Mnemonic::new(MnemonicType::Words12, Language::English); 349 | // ask user for a password to secure the wallet 350 | let pwd = prompt::create_password( 351 | password, 352 | DatFileVersion::RuskBinaryFileFormat(LATEST_VERSION), 353 | )?; 354 | // display the recovery phrase 355 | prompt::confirm_recovery_phrase(&mnemonic)?; 356 | // create and store the wallet 357 | let mut w = Wallet::new(mnemonic)?; 358 | let path = wallet_path.clone(); 359 | w.save_to(WalletFile { path, pwd })?; 360 | w 361 | } 362 | MainMenu::Recover => { 363 | // ask user for 12-word recovery phrase 364 | let phrase = prompt::request_recovery_phrase()?; 365 | // ask user for a password to secure the wallet, create the latest 366 | // wallet file from the seed 367 | let pwd = prompt::create_password( 368 | &None, 369 | DatFileVersion::RuskBinaryFileFormat(LATEST_VERSION), 370 | )?; 371 | // create and store the recovered wallet 372 | let mut w = Wallet::new(phrase)?; 373 | let path = wallet_path.clone(); 374 | w.save_to(WalletFile { path, pwd })?; 375 | w 376 | } 377 | MainMenu::Exit => std::process::exit(0), 378 | }; 379 | 380 | Ok(wallet) 381 | } 382 | 383 | #[derive(PartialEq, Eq, Hash, Debug, Clone)] 384 | enum MainMenu { 385 | Load(WalletPath), 386 | Create, 387 | Recover, 388 | Exit, 389 | } 390 | 391 | /// Allows the user to load an existing wallet, recover a lost one 392 | /// or create a new one. 393 | fn menu_wallet(wallet_found: Option) -> anyhow::Result { 394 | // create the wallet menu 395 | let mut menu = Menu::new(); 396 | 397 | if let Some(wallet_path) = wallet_found { 398 | menu = menu 399 | .separator() 400 | .add(MainMenu::Load(wallet_path), "Access your wallet") 401 | .separator() 402 | .add(MainMenu::Create, "Replace your wallet with a new one") 403 | .add( 404 | MainMenu::Recover, 405 | "Replace your wallet with a lost one using the recovery phrase", 406 | ) 407 | } else { 408 | menu = menu.add(MainMenu::Create, "Create a new wallet").add( 409 | MainMenu::Recover, 410 | "Access a lost wallet using the recovery phrase", 411 | ) 412 | } 413 | 414 | // create the action menu 415 | menu = menu.separator().add(MainMenu::Exit, "Exit"); 416 | 417 | // let the user choose an option 418 | let questions = Question::select("theme") 419 | .message("What would you like to do?") 420 | .choices(menu.clone()) 421 | .build(); 422 | 423 | let answer = requestty::prompt_one(questions)?; 424 | Ok(menu.answer(&answer).to_owned()) 425 | } 426 | 427 | /// Request user confirmation for a transfer transaction 428 | fn confirm(cmd: &Command) -> anyhow::Result { 429 | match cmd { 430 | Command::Transfer { 431 | sndr, 432 | rcvr, 433 | amt, 434 | gas_limit, 435 | gas_price, 436 | } => { 437 | let sndr = sndr.as_ref().expect("sender to be a valid address"); 438 | let max_fee = gas_limit * gas_price; 439 | println!(" > Send from = {}", sndr.preview()); 440 | println!(" > Recipient = {}", rcvr.preview()); 441 | println!(" > Amount to transfer = {} DUSK", amt); 442 | println!(" > Max fee = {} DUSK", Dusk::from(max_fee)); 443 | prompt::ask_confirm() 444 | } 445 | Command::Stake { 446 | addr, 447 | amt, 448 | gas_limit, 449 | gas_price, 450 | } => { 451 | let addr = addr.as_ref().expect("address to be valid"); 452 | let max_fee = gas_limit * gas_price; 453 | println!(" > Stake from {}", addr.preview()); 454 | println!(" > Amount to stake = {} DUSK", amt); 455 | println!(" > Max fee = {} DUSK", Dusk::from(max_fee)); 456 | prompt::ask_confirm() 457 | } 458 | Command::Unstake { 459 | addr, 460 | gas_limit, 461 | gas_price, 462 | } => { 463 | let addr = addr.as_ref().expect("address to be valid"); 464 | let max_fee = gas_limit * gas_price; 465 | println!(" > Unstake from {}", addr.preview()); 466 | println!(" > Max fee = {} DUSK", Dusk::from(max_fee)); 467 | prompt::ask_confirm() 468 | } 469 | Command::Withdraw { 470 | addr, 471 | gas_limit, 472 | gas_price, 473 | } => { 474 | let addr = addr.as_ref().expect("address to be valid"); 475 | let max_fee = gas_limit * gas_price; 476 | println!(" > Reward from {}", addr.preview()); 477 | println!(" > Max fee = {} DUSK", Dusk::from(max_fee)); 478 | prompt::ask_confirm() 479 | } 480 | _ => Ok(true), 481 | } 482 | } 483 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [Unreleased] 9 | 10 | ### Fixed 11 | 12 | - Fix tx history to show tx created with "MAX" amount [#248] 13 | 14 | ## [0.22.1] - 2024-3-27 15 | 16 | ### Added 17 | 18 | - Add support for `WALLET_MAX_ADDR` lower than `6` [#244] 19 | 20 | ### Changed 21 | 22 | - Change rusk-wallet to wait for tx to be included 23 | 24 | ### Fixed 25 | 26 | - Fix tx history to avoid useless calls [#243] 27 | 28 | ## [0.22.0] - 2024-2-28 29 | 30 | ### Changed 31 | 32 | - Change `REQUIRED_RUSK_VERSION` to `0.7.0` 33 | - Update unclear error message [#235] 34 | - Change provisioner key password prompt message [#238] 35 | 36 | ### Removed 37 | 38 | - Remove `stake_allow` command 39 | 40 | ## [0.21.0] - 2023-12-30 41 | 42 | ### Added 43 | 44 | - Add `seed-file` to `create` command [#226] 45 | - Add `name` to `export` command 46 | 47 | ### Fixed 48 | 49 | - Fix `stake_allow` command [#222] 50 | 51 | ### Changed 52 | 53 | - Change `dusk-wallet-core` to `0.24.0-plonk.0.16-rc.2` 54 | - Change `DEFAULT_MAX_ADDRESSES` from 255 to 25 55 | - Update `requestty` from `0.4.1` to `0.5.0` [#231] 56 | 57 | ## [0.20.1] - 2023-11-22 58 | 59 | ### Added 60 | 61 | - Add `spending_keys` to wallet impl [#218] 62 | 63 | ## [0.20.0] - 2023-11-01 64 | 65 | ### Changed 66 | 67 | - Change `REQUIRED_RUSK_VERSION` to `0.7.0-rc` 68 | - Change the Staking Address generation. [#214] 69 | - Change `dusk-wallet-core` to `0.22.0-plonk.0.16` [#214] 70 | 71 | ## [0.19.1] - 2023-10-11 72 | 73 | ### Added 74 | - Add interactive stake allow [#98] 75 | - Add optional `WALLET_MAX_ADDR` compile time env [#210] 76 | 77 | ### Fixed 78 | 79 | - Fix staking address display [#204] 80 | - Fix status overlap [#179] 81 | 82 | ## [0.19.0] - 2023-09-20 83 | 84 | ### Added 85 | 86 | - Add balance display when offline 87 | - Add `Wallet::sync` method for sync cache update 88 | - Add `Wallet::register_sync` method for async cache update 89 | 90 | ### Changed 91 | 92 | - Change wallet to not sync automatically 93 | - Change spent notes to be in a different ColumnFamily 94 | - Change `StateClient::fetch_existing_nullifiers` to return empty data. 95 | - Change `fetch_notes` to use note's position instead of height [#190] 96 | 97 | ### Removed 98 | 99 | - Remove cache sync from `StateClient::fetch_notes` 100 | - Remove `RuskClient` struct 101 | 102 | ### Fixed 103 | 104 | - Fix bug where we return early when there's no wallet file in interactive [#182] 105 | - Fix bug where wallet file got corrupted when loading a old version and creating a new address [#198] 106 | 107 | ## [0.18.2] - 2023-09-05 108 | 109 | ## [0.18.1] - 2023-09-01 110 | 111 | ### Fixed 112 | 113 | - Fix fetch_notes buffer [#176] 114 | 115 | ## [0.18.0] - 2023-08-09 116 | 117 | ### Added 118 | 119 | - Add support for rusk HTTP request [#173] 120 | - Add `local` network to default.config.toml [#173] 121 | 122 | ### Changed 123 | 124 | - Change `config.toml` to use `http` instead of `grpc` endpoints [#173] 125 | - Save the wallet.dat file with the new Rusk Binary Format [#165] 126 | - Change blake3 with sha256 for password hashing for new Rusk Binary Format, 127 | keep using blake3 for old dat file formats [#162] 128 | 129 | ### Removed 130 | 131 | - Remove `grpc` support [#173] 132 | - Remove `gql` support [#173] 133 | 134 | ## [0.17.0] - 2023-07-19 135 | 136 | ### Added 137 | 138 | - Add `rkyv` dependency [#151] 139 | - Add `dusk-merkle` dependency [#151] 140 | - Add `Error::Utf8` variant [#151] 141 | - Add `devnet` network to default config [#151] 142 | 143 | ### Changed 144 | 145 | - Change `rust-toolchain` to `nightly-2023-05-22` [#151] 146 | - Change `REQUIRED_RUSK_VERSION` to `0.6.0` [#151] 147 | - Change `Error::Canon` variant to `Error::Rkyv` [#151] 148 | - Populate cache database with psk(s) on state init [#158] 149 | - Change `dusk-plonk` to `0.14.0` [#169] 150 | 151 | ### Fixed 152 | - Fix cache resolution for alternative networks [#151] 153 | - Fix cache error detection [#163] 154 | 155 | ### Removed 156 | 157 | - Remove `canonical` dependency [#151] 158 | 159 | ## [0.16.0] - 2023-06-28 160 | 161 | ### Changed 162 | 163 | - Change cached Note's key to be the nullifier instead of hash [#144] 164 | - Update cache for all the possible addresses at the same time [#144] 165 | 166 | ## [0.15.0] - 2023-06-07 167 | 168 | ### Changed 169 | 170 | - Cache implementation now uses rocksdb instead of microkelvin [#56] 171 | 172 | ### Fixed 173 | 174 | - Throw an error there when specifying a network that does not exist [#143] 175 | 176 | ## [0.14.1] - 2023-05-17 177 | 178 | ### Fixed 179 | 180 | - Add overflow-checks to release mode [#132] 181 | 182 | ## [0.14.0] - 2023-01-12 183 | 184 | ### Added 185 | 186 | - Add `execute` to create transaction for generic contract calls [#133] 187 | - Add transaction history [#12] 188 | - Add stake maturity epoch [#128] 189 | - Add staking address display [#105] 190 | - Add stake eligibility info [#124] 191 | 192 | ### Fixed 193 | 194 | - Fix headless balance display [#123] 195 | 196 | ## [0.13.0] - 2022-11-30 197 | 198 | ### Changed 199 | 200 | - Changed fn signature in `gas::new` to include the gas limit [#116] 201 | - Change `request_gas_limit` fn signature to accept a gas limit option [#116] 202 | - Change (un)stake, allow stake and withdraw default gas limits to sane defaults [#116] 203 | - Change exported consensus keys extension to `.keys` [#114] 204 | 205 | ## [0.12.0] - 2022-10-19 206 | 207 | ### Added 208 | 209 | - Add `default.config.toml` for the default configuration settings [#57] 210 | - Add `settings` subcommand to show the current settings [#57] 211 | - Add `--password` as global argument [#57] 212 | - Add `--skip-recovery` to `create` subcommand [#57] 213 | - Add `--file` to `restore` subcommand [#57] 214 | - Add `Settings` type to merge `Config` (from toml) and `WalletArgs` (from CLI) [#57] 215 | - Add `address` module 216 | - Add `gas` module 217 | - Add `settings` module [#57] 218 | - Add `is_enough` method to `Gas` 219 | - Add `Create`, `Restore` and `Settings` for both `Command` and `RunResult` enums [#72] 220 | - Add `LogFormat` and `LogLevel` enums to enforce the set of value from args [#57] 221 | - Add `From block` and `Last block` during fetching 222 | - Add missing documentations 223 | - Add `Seed` type in `store` module 224 | - Add `stake-allow` command [#83] 225 | 226 | ### Changed 227 | 228 | - Change program behavior to quit if wrong seed phrase is given [#49] 229 | - Change program behavior to have three attempts for entering a password [#46] 230 | - Change error handling to use the `anyhow` crate in `bin`[#87] 231 | - Change error handling to use the `thiserror` crate in `lib`[#87] 232 | - Change `config.toml` format [#57] 233 | - Change from multiple wallets to one wallet for a single profile dir [#72] 234 | - Rename `dusk` module to `currency` module 235 | - Rename `address` subcommand to `addresses` 236 | - Change `set_price` and `set_limit` for `Gas` to works with `Option` 237 | - Change part of the functions to either receive the `password` or the `settings` [#57] 238 | - Move `config` module outside `io` [#57] 239 | - Change few UI strings 240 | - Update rust-toolchain from `nightly-2022-02-19` to `nightly-2022-08-28` 241 | 242 | ### Removed 243 | 244 | - Rename `--data-dir` argument option to `--profile` [#57] 245 | - Remove `--wallet-name` argument option [#72] 246 | - Remove `--network` argument option to choose the network to connect with [#57] 247 | - Remove `interactive` subcommand [#57] 248 | - Remove `--skip-recovery` as global argument [#57] 249 | - Remove `--wait-for-tx` (now all the transaction wait by default) [#57] 250 | - Remove `merge` method from `Config` in favour of `Settings` type [#57] 251 | - Remove `Command::NotSupported` [#57] 252 | - Rename `DEFAULT_GAS_LIMIT`, `DEFAULT_GAS_PRICE`, `MIN_GAS_LIMIT` 253 | - Remove `Addresses` type in favour of `Vec
` 254 | - Remove `refund-addr` arg in `withdraw` command [#86] 255 | 256 | ### Fixed 257 | 258 | - Fix wrong condition involved `gas.is_enough()`[#91] 259 | - Fix `balance` subcommand: it didn't work because the address given wasn't claimed 260 | - Fix BLS keys exported with wrong extensions [#84] 261 | 262 | ## [0.11.1] - 2022-08-24 263 | 264 | ### Added 265 | 266 | - Add prompt confirm_recovery_phrase to display the recovery phrase [#70] 267 | - Add Windows terminal compatibility [#68] 268 | 269 | ### Changed 270 | 271 | - Change `LoggingConfig` to be optional [#73] 272 | - Replace `error!` macro with `eprintln!` macro [#73] 273 | - Change `Return` to `Back` in the menu 274 | 275 | ## [0.11.0] - 2022-08-17 276 | 277 | ### Added 278 | 279 | - New public `Wallet` struct exposing all wallet operations as library [#54] 280 | - New `Address` type to identify and work with addresses [#54] 281 | - Logging capabilities with customizable `log_level` and `log_type` [#11] 282 | 283 | ### Changed 284 | 285 | - Project is now a public facing library [#54] 286 | - Our reference implementation is included under `src/bin` [#54] 287 | - UX flow is now address-based to match that of the web wallet [#59] 288 | - Anything that's not strictly program output is redirected to stderr [#11] 289 | 290 | ## [0.10.0] - 2022-07-06 291 | 292 | ### Added 293 | 294 | - Add `src/bin` to gather the module related to the I/O ops [#51] 295 | - Add `autobins` to Cargo.toml to prevent bins auto discovery [#51] 296 | - Add `[lib]` and `[[bin]]` sections to Cargo.toml to decouple bin and lib [#51] 297 | - Add `src/bin/io` to gather all modules related to I/O [#51] 298 | - Add `status` mod as temp workaround to make the lib compile [#51] 299 | - Add `actions` mod with all the actions previously in `main` [#51] 300 | 301 | ### Changed 302 | 303 | - Rename `src/mod.rs` to `src/lib.rs` to be compliant with 2018 edition [#51] 304 | - Refactor `main` to be more readable [#51] 305 | - Update imports in the code to reflect the new files structure [#51] 306 | 307 | ## [0.9.0] - 2022-05-25 308 | 309 | ### Added 310 | 311 | - Flag `--spendable` to `Balance` command [#40] 312 | - Flag `--reward` to `StakeInfo` command [#40] 313 | 314 | ### Changed 315 | 316 | - Commands run in headless mode do not provide dynamic status updates [#40] 317 | 318 | ## [0.8.0] - 2022-05-04 319 | 320 | ### Added 321 | 322 | - Block trait for easier blocking on futures [#32] 323 | - Withdraw reward command [#26] 324 | 325 | ### Changed 326 | 327 | - Upgraded cache implementation to use `microkelvin` instead of `rusqlite` [#32] 328 | - Use streaming `GetNotes` call instead of `GetNotesOwnedBy` [#32] 329 | - Enhance address validity checks on interactive mode [#28] 330 | - Prevent exit on prepare command errors [#27] 331 | - Adapt balance to the new State [#24] 332 | - Rename `withdraw-stake` to `unstake` [#26] 333 | - Introduce Dusk type for currency management [#4] 334 | 335 | ### Fixed 336 | 337 | - Fix cache bug preventing adding all notes to it [#35] 338 | - Fix address validation by parsing address first [#35] 339 | 340 | ## [0.7.0] - 2022-04-13 341 | 342 | ### Added 343 | 344 | - Notes cache [#650] 345 | - Settings can be loaded from a config file [#637] 346 | - Create config file if not exists [#647] 347 | - Notify user when defaulting configuration [#655] 348 | - Implementation for `State`'s `fetch_block_height` [#651] 349 | - Option to wait for transaction confirmation [#680] 350 | - Default to TCP/IP on Windows [#6] 351 | 352 | ### Changed 353 | 354 | - Export consensus public key as binary 355 | - Interactive mode allows for directory and wallet file overriding [#630] 356 | - Client errors implemented, Rusk error messages displayed without metadata [#629] 357 | - Transactions from wallets with no balance are halted immediately [#631] 358 | - Rusk and prover connections decoupled [#659] 359 | - Use upper-case DUSK for units of measure [#672] 360 | - Use DUSK as unit for stake and transfer [#668] 361 | 362 | ### Fixed 363 | 364 | - `data_dir` can be properly overriden [#656] 365 | - Invalid configuration should not fallback into default [#670] 366 | - Prevent interactive process from quitting on wallet execution errors [#18] 367 | 368 | ## [0.5.2] - 2022-03-01 369 | 370 | ### Added 371 | 372 | - Optional configuration item to specify the prover URL [#612] 373 | - Get Stake information subcommand [#619] 374 | 375 | ## [0.5.1] - 2022-02-26 376 | 377 | ### Added 378 | 379 | - Display progress info about transaction preparation [#600] 380 | - Display confirmation before sending a transaction [#602] 381 | 382 | ### Changed 383 | 384 | - Use hex-encoded tx hashes on user-facing messages [#597] 385 | - Open or display explorer URL on succesful transactions [#598] 386 | 387 | ## [0.5.0] - 2022-02-26 388 | 389 | ### Changed 390 | 391 | - Update `canonical` across the entire Rusk stack [#606] 392 | 393 | ## [0.4.0] - 2022-02-17 394 | 395 | ### Changed 396 | 397 | - Use the Dusk denomination from `rusk-abi` [#582] 398 | 399 | ## [0.3.1] - 2022-02-17 400 | 401 | ### Changed 402 | 403 | - Default to current wallet directory for exported keys [#574] 404 | - Add an additional plain text file with the base58-encoded public key [#574] 405 | 406 | ## [0.3.0] - 2022-02-17 407 | 408 | ### Removed 409 | 410 | - Stake expiration [#566] 411 | 412 | ## [0.2.4] - 2022-02-15 413 | 414 | ### Added 415 | 416 | - Allow for headless wallet creation [#569] 417 | 418 | ### Changed 419 | 420 | - TX output in wallet instead of within client impl 421 | 422 | ## [0.2.3] - 2022-02-10 423 | 424 | ### Added 425 | 426 | - Pretty print wallet-core errors [#554] 427 | 428 | ## [0.2.2] - 2022-02-10 429 | 430 | ### Changed 431 | 432 | - Interactive mode prevents sending txs with insufficient balance [#547] 433 | 434 | ### Fixed 435 | 436 | - Panic when UDS socket is not available 437 | 438 | ## [0.2.1] - 2022-02-09 439 | 440 | ### Changed 441 | 442 | - Default `gas_price` from 0 to 0.001 Dusk [#539] 443 | 444 | ## [0.2.0] - 2022-02-04 445 | 446 | ### Added 447 | 448 | - Wallet file encoding version [#524] 449 | 450 | ### Changed 451 | 452 | - Default to UDS transport [#520] 453 | 454 | ## [0.1.3] - 2022-02-01 455 | 456 | ### Added 457 | 458 | - Offline mode [#499] [#507] 459 | - Live validation to user interactive input 460 | - Improved navigation through interactive menus 461 | - "Pause" after command outputs for better readability 462 | 463 | ### Fixed 464 | 465 | - Bad UX when creating an already existing wallet with default name 466 | 467 | ## [0.1.2] - 2022-01-31 468 | 469 | ### Added 470 | 471 | - Enable headless mode [#495] 472 | - Introduce interactive mode by default [#492] 473 | - Add Export command for BLS PubKeys [#505] 474 | 475 | ## [0.1.1] - 2022-01-27 476 | 477 | ### Added 478 | 479 | - Wallet file encryption using AES [#482] 480 | 481 | ### Changed 482 | 483 | - Common `Error` struct for this crate [#479] 484 | - Password hashing using blake3 485 | 486 | ### Removed 487 | 488 | - Recovery password 489 | 490 | ## [0.1.0] - 2022-01-25 491 | 492 | ### Added 493 | 494 | - `rusk-wallet` crate to workspace 495 | - Argument and command parsing, with help output 496 | - Interactive prompts for authentication 497 | - BIP39 mnemonic support for recovery phrase 498 | - Implementation of `Store` trait from `wallet-core` 499 | - Implementation of `State` and `Prover` traits from `wallet-core` 500 | 501 | [#248]: https://github.com/dusk-network/wallet-cli/issues/248 502 | [#244]: https://github.com/dusk-network/wallet-cli/issues/244 503 | [#243]: https://github.com/dusk-network/wallet-cli/issues/243 504 | [#238]: https://github.com/dusk-network/wallet-cli/issues/238 505 | [#235]: https://github.com/dusk-network/wallet-cli/issues/235 506 | [#231]: https://github.com/dusk-network/wallet-cli/issues/231 507 | [#226]: https://github.com/dusk-network/wallet-cli/issues/226 508 | [#222]: https://github.com/dusk-network/wallet-cli/issues/222 509 | [#218]: https://github.com/dusk-network/wallet-cli/issues/218 510 | [#214]: https://github.com/dusk-network/wallet-cli/issues/214 511 | [#210]: https://github.com/dusk-network/wallet-cli/issues/210 512 | [#98]: https://github.com/dusk-network/wallet-cli/issues/98 513 | [#179]: https://github.com/dusk-network/wallet-cli/issues/179 514 | [#204]: https://github.com/dusk-network/wallet-cli/issues/204 515 | [#182]: https://github.com/dusk-network/wallet-cli/issues/182 516 | [#198]: https://github.com/dusk-network/wallet-cli/issues/198 517 | [#176]: https://github.com/dusk-network/wallet-cli/issues/176 518 | [#162]: https://github.com/dusk-network/wallet-cli/issues/162 519 | [#163]: https://github.com/dusk-network/wallet-cli/issues/163 520 | [#151]: https://github.com/dusk-network/wallet-cli/issues/151 521 | [#144]: https://github.com/dusk-network/wallet-cli/issues/144 522 | [#133]: https://github.com/dusk-network/wallet-cli/issues/133 523 | [#132]: https://github.com/dusk-network/wallet-cli/issues/132 524 | [#128]: https://github.com/dusk-network/wallet-cli/issues/128 525 | [#105]: https://github.com/dusk-network/wallet-cli/issues/105 526 | [#124]: https://github.com/dusk-network/wallet-cli/issues/124 527 | [#123]: https://github.com/dusk-network/wallet-cli/issues/123 528 | [#116]: https://github.com/dusk-network/wallet-cli/issues/116 529 | [#114]: https://github.com/dusk-network/wallet-cli/issues/114 530 | [#165]: https://github.com/dusk-network/wallet-cli/issues/165 531 | [#49]: https://github.com/dusk-network/wallet-cli/issues/49 532 | [#46]: https://github.com/dusk-network/wallet-cli/issues/46 533 | [#87]: https://github.com/dusk-network/wallet-cli/issues/87 534 | [#86]: https://github.com/dusk-network/wallet-cli/issues/86 535 | [#83]: https://github.com/dusk-network/wallet-cli/issues/83 536 | [#84]: https://github.com/dusk-network/wallet-cli/issues/84 537 | [#72]: https://github.com/dusk-network/wallet-cli/issues/72 538 | [#57]: https://github.com/dusk-network/wallet-cli/issues/57 539 | [#70]: https://github.com/dusk-network/wallet-cli/issues/70 540 | [#73]: https://github.com/dusk-network/wallet-cli/issues/73 541 | [#68]: https://github.com/dusk-network/wallet-cli/issues/68 542 | [#11]: https://github.com/dusk-network/wallet-cli/issues/11 543 | [#59]: https://github.com/dusk-network/wallet-cli/issues/59 544 | [#54]: https://github.com/dusk-network/wallet-cli/issues/54 545 | [#51]: https://github.com/dusk-network/wallet-cli/issues/51 546 | [#40]: https://github.com/dusk-network/wallet-cli/issues/40 547 | [#35]: https://github.com/dusk-network/wallet-cli/issues/35 548 | [#32]: https://github.com/dusk-network/wallet-cli/issues/32 549 | [#28]: https://github.com/dusk-network/wallet-cli/issues/28 550 | [#27]: https://github.com/dusk-network/wallet-cli/issues/27 551 | [#26]: https://github.com/dusk-network/wallet-cli/issues/26 552 | [#24]: https://github.com/dusk-network/wallet-cli/issues/24 553 | [#18]: https://github.com/dusk-network/wallet-cli/issues/18 554 | [#12]: https://github.com/dusk-network/wallet-cli/issues/12 555 | [#6]: https://github.com/dusk-network/wallet-cli/issues/6 556 | [#56]: https://github.com/dusk-network/wallet-cli/issues/56 557 | [#143]: https://github.com/dusk-network/wallet-cli/issues/143 558 | [#4]: https://github.com/dusk-network/wallet-cli/issues/4 559 | [#680]: https://github.com/dusk-network/rusk/issues/680 560 | [#672]: https://github.com/dusk-network/rusk/issues/672 561 | [#670]: https://github.com/dusk-network/rusk/issues/670 562 | [#668]: https://github.com/dusk-network/rusk/issues/668 563 | [#659]: https://github.com/dusk-network/rusk/issues/659 564 | [#656]: https://github.com/dusk-network/rusk/issues/656 565 | [#655]: https://github.com/dusk-network/rusk/issues/655 566 | [#651]: https://github.com/dusk-network/rusk/issues/651 567 | [#650]: https://github.com/dusk-network/rusk/issues/650 568 | [#647]: https://github.com/dusk-network/rusk/issues/647 569 | [#637]: https://github.com/dusk-network/rusk/issues/637 570 | [#631]: https://github.com/dusk-network/rusk/issues/631 571 | [#630]: https://github.com/dusk-network/rusk/issues/630 572 | [#629]: https://github.com/dusk-network/rusk/issues/629 573 | [#619]: https://github.com/dusk-network/rusk/issues/619 574 | [#612]: https://github.com/dusk-network/rusk/issues/612 575 | [#606]: https://github.com/dusk-network/rusk/issues/606 576 | [#602]: https://github.com/dusk-network/rusk/issues/602 577 | [#600]: https://github.com/dusk-network/rusk/issues/600 578 | [#598]: https://github.com/dusk-network/rusk/issues/598 579 | [#597]: https://github.com/dusk-network/rusk/issues/597 580 | [#582]: https://github.com/dusk-network/rusk/issues/582 581 | [#574]: https://github.com/dusk-network/rusk/issues/574 582 | [#569]: https://github.com/dusk-network/rusk/issues/569 583 | [#566]: https://github.com/dusk-network/rusk/issues/566 584 | [#554]: https://github.com/dusk-network/rusk/issues/554 585 | [#547]: https://github.com/dusk-network/rusk/issues/547 586 | [#539]: https://github.com/dusk-network/rusk/issues/539 587 | [#520]: https://github.com/dusk-network/rusk/issues/520 588 | [#507]: https://github.com/dusk-network/rusk/issues/507 589 | [#505]: https://github.com/dusk-network/rusk/issues/505 590 | [#499]: https://github.com/dusk-network/rusk/issues/499 591 | [#495]: https://github.com/dusk-network/rusk/issues/495 592 | [#492]: https://github.com/dusk-network/rusk/issues/492 593 | [#482]: https://github.com/dusk-network/rusk/issues/482 594 | [#479]: https://github.com/dusk-network/rusk/issues/479 595 | [#158]: https://github.com/dusk-network/wallet-cli/pull/158 596 | [#169]: https://github.com/dusk-network/wallet-cli/pull/169 597 | [#173]: https://github.com/dusk-network/wallet-cli/pull/173 598 | [#173]: https://github.com/dusk-network/wallet-cli/pull/190 599 | 600 | 601 | 602 | [unreleased]: https://github.com/dusk-network/wallet-cli/compare/v0.22.1...HEAD 603 | [0.22.1]: https://github.com/dusk-network/wallet-cli/compare/v0.22.0...v0.22.1 604 | [0.22.0]: https://github.com/dusk-network/wallet-cli/compare/v0.21.0...v0.22.0 605 | [0.21.0]: https://github.com/dusk-network/wallet-cli/compare/v0.20.1...v0.21.0 606 | [0.20.1]: https://github.com/dusk-network/wallet-cli/compare/v0.20.0...v0.20.1 607 | [0.20.0]: https://github.com/dusk-network/wallet-cli/compare/v0.19.1...v0.20.0 608 | [0.19.1]: https://github.com/dusk-network/wallet-cli/compare/v0.19.0...v0.19.1 609 | [0.19.0]: https://github.com/dusk-network/wallet-cli/compare/v0.18.2...v0.19.0 610 | [0.18.2]: https://github.com/dusk-network/wallet-cli/compare/v0.18.1...v0.18.2 611 | [0.18.1]: https://github.com/dusk-network/wallet-cli/compare/v0.18.0...v0.18.1 612 | [0.18.0]: https://github.com/dusk-network/wallet-cli/compare/v0.17.0...v0.18.0 613 | [0.17.0]: https://github.com/dusk-network/wallet-cli/compare/v0.16.0...v0.17.0 614 | [0.16.0]: https://github.com/dusk-network/wallet-cli/compare/v0.15.0...v0.16.0 615 | [0.15.0]: https://github.com/dusk-network/wallet-cli/compare/v0.14.1...v0.15.0 616 | [0.14.1]: https://github.com/dusk-network/wallet-cli/compare/v0.14.0...v0.14.1 617 | [0.14.0]: https://github.com/dusk-network/wallet-cli/compare/v0.13.0...v0.14.0 618 | [0.13.0]: https://github.com/dusk-network/wallet-cli/compare/v0.12.0...v0.13.0 619 | [0.12.0]: https://github.com/dusk-network/wallet-cli/compare/v0.11.1...v0.12.0 620 | [0.11.1]: https://github.com/dusk-network/wallet-cli/compare/v0.11.0...v0.11.1 621 | [0.11.0]: https://github.com/dusk-network/wallet-cli/compare/v0.10.0...v0.11.0 622 | [0.10.0]: https://github.com/dusk-network/wallet-cli/compare/v0.9.0...v0.10.0 623 | [0.9.0]: https://github.com/dusk-network/wallet-cli/compare/v0.8.0...v0.9.0 624 | [0.8.0]: https://github.com/dusk-network/wallet-cli/compare/v0.7.0...v0.8.0 625 | [0.7.0]: https://github.com/dusk-network/wallet-cli/compare/v0.5.2...v0.7.0 626 | [0.5.2]: https://github.com/dusk-network/wallet-cli/compare/v0.5.1...v0.5.2 627 | [0.5.1]: https://github.com/dusk-network/wallet-cli/compare/v0.5.0...v0.5.1 628 | [0.5.0]: https://github.com/dusk-network/wallet-cli/compare/v0.4.0...v0.5.0 629 | [0.4.0]: https://github.com/dusk-network/wallet-cli/compare/v0.3.1...v0.4.0 630 | [0.3.1]: https://github.com/dusk-network/wallet-cli/compare/v0.3.0...v0.3.1 631 | [0.3.0]: https://github.com/dusk-network/wallet-cli/compare/v0.2.5...v0.3.0 632 | [0.2.5]: https://github.com/dusk-network/wallet-cli/compare/v0.2.4...v0.2.5 633 | [0.2.4]: https://github.com/dusk-network/wallet-cli/compare/v0.2.3...v0.2.4 634 | [0.2.3]: https://github.com/dusk-network/wallet-cli/compare/v0.2.2...v0.2.3 635 | [0.2.2]: https://github.com/dusk-network/wallet-cli/compare/v0.2.1...v0.2.2 636 | [0.2.1]: https://github.com/dusk-network/wallet-cli/compare/v0.2.0...v0.2.1 637 | [0.2.0]: https://github.com/dusk-network/wallet-cli/compare/v0.1.3...v0.2.0 638 | [0.1.3]: https://github.com/dusk-network/wallet-cli/compare/v0.1.2...v0.1.3 639 | [0.1.2]: https://github.com/dusk-network/wallet-cli/compare/v0.1.1...v0.1.2 640 | [0.1.1]: https://github.com/dusk-network/wallet-cli/compare/v0.1.0...v0.1.1 641 | [0.1.0]: https://github.com/dusk-network/wallet-cli/releases/tag/v0.1.0 642 | --------------------------------------------------------------------------------