Merge branch 'master' of github.com:adityapk00/lightwalletclient

This commit is contained in:
Aditya Kulkarni
2019-09-30 21:12:26 -07:00
9 changed files with 121 additions and 134 deletions

View File

@@ -38,7 +38,7 @@ webpki-roots = "0.16.0"
tower-h2 = { git = "https://github.com/tower-rs/tower-h2" }
openssl = "*"
openssl-probe = "*"
rust-embed = "5.1.0"
[dependencies.bellman]
git = "https://github.com/adityapk00/librustzcash.git"
@@ -72,4 +72,4 @@ tower-grpc-build = { git = "https://github.com/tower-rs/tower-grpc", features =
rand_core = "0.5.1"
[profile.release]
debug = true
debug = false

View File

@@ -1,6 +1,6 @@
# Zeclite CLI - A command line ZecWallet light client.
`zeclite-cli` is a command line zecwallet light client. To use it, download the latest binary from the releases page and run `./zeclite-cli`
`zeclite-cli` is a command line ZecWallet light client. To use it, download the latest binary from the releases page and run `./zeclite-cli`
This will launch the interactive prompt. Type `help` to get a list of commands
@@ -14,10 +14,10 @@ This will launch the interactive prompt. Type `help` to get a list of commands
* The log file is in `~/.zcash/testnet3/zeclite.debug.log`
### Note Management
Zeclite does automatic note and utxo management, which means it doesn't allow you to manually select which address to send outgoing transactions from. It follows these priciples:
Zeclite does automatic note and utxo management, which means it doesn't allow you to manually select which address to send outgoing transactions from. It follows these principles:
* Defaults to sending shielded transactions, even if you're sending to a transparent address
* Can select funds from multiple shielded addresses in the same transaction
* Will automatically shield your transparent funds at the first oppurtunity
* Will automatically shield your transparent funds at the first opportunity
* When sending an outgoing transaction to a shielded address, Zeclite can decide to use the transaction to additionally shield your transparent funds (i.e., send your transparent funds to your own shielded address in the same transaction)
## Compiling from source

View File

@@ -383,7 +383,7 @@ pub fn get_commands() -> Box<HashMap<String, Box<dyn Command>>> {
map.insert("rescan".to_string(), Box::new(RescanCommand{}));
map.insert("help".to_string(), Box::new(HelpCommand{}));
map.insert("balance".to_string(), Box::new(BalanceCommand{}));
map.insert("address".to_string(), Box::new(AddressCommand{}));
map.insert("addresses".to_string(), Box::new(AddressCommand{}));
map.insert("export".to_string(), Box::new(ExportCommand{}));
map.insert("info".to_string(), Box::new(InfoCommand{}));
map.insert("send".to_string(), Box::new(SendCommand{}));

View File

@@ -37,14 +37,15 @@ use zcash_client_backend::{
use crate::grpc_client::{ChainSpec, BlockId, BlockRange, RawTransaction,
TransparentAddressBlockFilter, TxFilter, Empty, LightdInfo};
use crate::grpc_client::client::CompactTxStreamer;
use crate::SaplingParams;
// Used below to return the grpc "Client" type to calling methods
pub const DEFAULT_SERVER: &str = "https://lightd-test.zecwallet.co:443";
pub const DEFAULT_SERVER: &str = "https://lightd-main.zecwallet.co:443";
pub const WALLET_NAME: &str = "zeclite.wallet.dat";
pub const LOGFILE_NAME: &str = "zeclite.debug.log";
/// A Secure (https) grpc destination. If insecure=true, then it will not use TLS (eg. for local testing)
/// A Secure (https) grpc destination.
struct Dst {
addr: SocketAddr,
host: String,
@@ -112,7 +113,6 @@ impl tower_service::Service<()> for Dst {
// }
// }
macro_rules! make_grpc_client {
($protocol:expr, $host:expr, $port:expr) => {{
let uri: http::Uri = format!("{}://{}", $protocol, $host).parse().unwrap();
@@ -128,9 +128,7 @@ macro_rules! make_grpc_client {
make_client
.make_service(())
.map_err(|e| {
eprintln!("HTTP/2 connection failed; err={:?}", e);
})
.map_err(|e| { format!("HTTP/2 connection failed; err={:?}", e) })
.and_then(move |conn| {
let conn = tower_request_modifier::Builder::new()
.set_origin(uri)
@@ -140,12 +138,11 @@ macro_rules! make_grpc_client {
CompactTxStreamer::new(conn)
// Wait until the client is ready...
.ready()
.map_err(|e| eprintln!("client closed: {:?}", e))
.map_err(|e| { format!("client closed: {:?}", e) })
})
}};
}
#[derive(Clone, Debug)]
pub struct LightClientConfig {
pub server : http::Uri,
@@ -155,22 +152,6 @@ pub struct LightClientConfig {
}
impl LightClientConfig {
pub fn get_params_path(&self, name: &str) -> Box<Path> {
let mut params_location;
if cfg!(target_os="macos") || cfg!(target_os="windows") {
params_location = dirs::data_dir()
.expect("Couldn't determine app data directory!");
params_location.push("ZcashParams");
} else {
params_location = dirs::home_dir()
.expect("Couldn't determine home directory!");
params_location.push(".zcash-params");
};
params_location.push(name);
params_location.into_boxed_path()
}
pub fn get_zcash_data_path(&self) -> Box<Path> {
let mut zcash_data_location;
@@ -222,7 +203,14 @@ impl LightClientConfig {
pub fn get_server_or_default(server: Option<String>) -> http::Uri {
match server {
Some(s) => if s.starts_with("http") {s} else { "http://".to_string() + &s}
Some(s) => {
let mut s = if s.starts_with("http") {s} else { "http://".to_string() + &s};
let uri: http::Uri = s.parse().unwrap();
if uri.port_part().is_none() {
s = s + ":443";
}
s
}
None => DEFAULT_SERVER.to_string()
}.parse().unwrap()
}
@@ -330,19 +318,8 @@ impl LightClient {
info!("Read wallet with birthday {}", lc.wallet.get_first_tx_block());
// Read Sapling Params
let mut f = match File::open(config.get_params_path("sapling-output.params")) {
Ok(file) => file,
Err(_) => return Err(Error::new(ErrorKind::NotFound,
format!("Couldn't read {}", config.get_params_path("sapling-output.params").display())))
};
f.read_to_end(&mut lc.sapling_output)?;
let mut f = match File::open(config.get_params_path("sapling-spend.params")) {
Ok(file) => file,
Err(_) => return Err(Error::new(ErrorKind::NotFound,
format!("Couldn't read {}", config.get_params_path("sapling-spend.params").display())))
};
f.read_to_end(&mut lc.sapling_spend)?;
lc.sapling_output.extend_from_slice(SaplingParams::get("sapling-output.params").unwrap().as_ref());
lc.sapling_spend.extend_from_slice(SaplingParams::get("sapling-spend.params").unwrap().as_ref());
info!("Created LightClient to {}", &config.server);
println!("Lightclient connecting to {}", config.server);
@@ -454,31 +431,22 @@ impl LightClient {
self.config.server.clone()
}
pub fn get_info(uri: http::Uri) -> LightdInfo {
use std::cell::RefCell;
let info = Arc::new(RefCell::<LightdInfo>::default());
let info_inner = info.clone();
pub fn get_info(uri: http::Uri) -> Result<LightdInfo, String> {
let runner = make_grpc_client!(uri.scheme_str().unwrap(), uri.host().unwrap(), uri.port_part().unwrap())
.and_then(move |mut client| {
client.get_lightd_info(Request::new(Empty{}))
.map_err(|e| {
println!("ERR = {:?}", e);
format!("ERR = {:?}", e)
})
.and_then(move |response| {
info_inner.replace(response.into_inner());
Ok(())
Ok(response.into_inner())
})
.map_err(|e| {
println!("ERR = {:?}", e);
format!("ERR = {:?}", e)
})
});
tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner).unwrap();
let ans = info.borrow().clone();
ans
tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner)
}
pub fn do_info(uri: http::Uri) -> String {
@@ -646,10 +614,10 @@ impl LightClient {
})
);
// Get the total transparent recieved
// Get the total transparent received
let total_transparent_received = v.utxos.iter().map(|u| u.value).sum::<u64>();
if total_transparent_received > v.total_transparent_value_spent {
// Create a input transaction for the transparent value as well.
// Create an input transaction for the transparent value as well.
txns.push(object!{
"block_height" => v.block,
"txid" => format!("{}", v.txid),
@@ -678,7 +646,7 @@ impl LightClient {
// First, clear the state from the wallet
self.wallet.clear_blocks();
// Then set the inital block
// Then set the initial block
self.set_wallet_initial_state();
// Then, do a sync, which will force a full rescan from the initial state
@@ -851,7 +819,10 @@ impl LightClient {
);
match rawtx {
Some(txbytes) => self.broadcast_raw_tx(txbytes),
Some(txbytes) => match self.broadcast_raw_tx(txbytes) {
Ok(k) => k,
Err(e) => e,
},
None => format!("No Tx to broadcast")
}
}
@@ -860,7 +831,6 @@ impl LightClient {
// GRPC code
// ==============
pub fn fetch_blocks<F : 'static + std::marker::Send>(&self, start_height: u64, end_height: u64, c: F)
where F : Fn(&[u8]) {
let uri = self.get_server_uri();
@@ -873,7 +843,7 @@ impl LightClient {
client
.get_block_range(br)
.map_err(|e| {
eprintln!("RouteChat request failed; err={:?}", e);
format!("RouteChat request failed; err={:?}", e)
})
.and_then(move |response| {
let inbound = response.into_inner();
@@ -886,11 +856,17 @@ impl LightClient {
Ok(())
})
.map_err(|e| eprintln!("gRPC inbound stream error: {:?}", e))
.map_err(|e| format!("gRPC inbound stream error: {:?}", e))
})
});
tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner).unwrap();
match tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner) {
Ok(_) => {}, // The result is processed in callbacks, so nothing to do here
Err(e) => {
error!("Error while executing fetch_blocks: {}", e);
eprintln!("{}", e);
}
};
}
pub fn fetch_transparent_txids<F : 'static + std::marker::Send>(&self, address: String,
@@ -907,7 +883,7 @@ impl LightClient {
client
.get_address_txids(br)
.map_err(|e| {
eprintln!("RouteChat request failed; err={:?}", e);
format!("RouteChat request failed; err={:?}", e)
})
.and_then(move |response| {
let inbound = response.into_inner();
@@ -917,11 +893,17 @@ impl LightClient {
Ok(())
})
.map_err(|e| eprintln!("gRPC inbound stream error: {:?}", e))
.map_err(|e| format!("gRPC inbound stream error: {:?}", e))
})
});
tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner).unwrap();
match tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner) {
Ok(_) => {}, // The result is processed in callbacks, so nothing to do here
Err(e) => {
error!("Error while executing fetch_transparent_txids: {}", e);
eprintln!("{}", e);
}
};
}
pub fn fetch_full_tx<F : 'static + std::marker::Send>(&self, txid: TxId, c: F)
@@ -932,53 +914,45 @@ impl LightClient {
let txfilter = TxFilter { block: None, index: 0, hash: txid.0.to_vec() };
client.get_transaction(Request::new(txfilter))
.map_err(|e| {
eprintln!("RouteChat request failed; err={:?}", e);
format!("RouteChat request failed; err={:?}", e)
})
.and_then(move |response| {
//let tx = Transaction::read(&response.into_inner().data[..]).unwrap();
c(&response.into_inner().data);
Ok(())
})
.map_err(|e| {
println!("ERR = {:?}", e);
})
.map_err(|e| { format!("ERR = {:?}", e) })
});
tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner).unwrap();
match tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner) {
Ok(_) => {}, // The result is processed in callbacks, so nothing to do here
Err(e) => {
error!("Error while executing fetch_full_tx: {}", e);
eprintln!("{}", e);
}
};
}
pub fn broadcast_raw_tx(&self, tx_bytes: Box<[u8]>) -> String {
use std::cell::RefCell;
let infostr = Arc::new(RefCell::<String>::default());
let infostrinner = infostr.clone();
pub fn broadcast_raw_tx(&self, tx_bytes: Box<[u8]>) -> Result<String, String> {
let uri = self.get_server_uri();
let runner = make_grpc_client!(uri.scheme_str().unwrap(), uri.host().unwrap(), uri.port_part().unwrap())
.and_then(move |mut client| {
client.send_transaction(Request::new(RawTransaction {data: tx_bytes.to_vec(), height: 0}))
.map_err(|e| {
println!("ERR = {:?}", e);
format!("ERR = {:?}", e)
})
.and_then(move |response| {
let sendresponse = response.into_inner();
if sendresponse.error_code == 0 {
infostrinner.replace(format!("Successfully broadcast Tx: {}", sendresponse.error_message));
Ok(format!("Successfully broadcast Tx: {}", sendresponse.error_message))
} else {
infostrinner.replace(format!("Error: {:?}", sendresponse));
Err(format!("Error: {:?}", sendresponse))
}
Ok(())
})
.map_err(|e| {
println!("ERR = {:?}", e);
})
.map_err(|e| { format!("ERR = {:?}", e) })
});
tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner).unwrap();
let ans = infostr.borrow().clone();
ans
tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner)
}
pub fn fetch_latest_block<F : 'static + std::marker::Send>(&self, mut c : F)
@@ -987,19 +961,21 @@ impl LightClient {
let runner = make_grpc_client!(uri.scheme_str().unwrap(), uri.host().unwrap(), uri.port_part().unwrap())
.and_then(|mut client| {
client.get_latest_block(Request::new(ChainSpec {}))
.map_err(|e| {
println!("ERR = {:?}", e);
})
.map_err(|e| { format!("ERR = {:?}", e) })
.and_then(move |response| {
c(response.into_inner());
Ok(())
})
.map_err(|e| {
println!("ERR = {:?}", e);
})
.map_err(|e| { format!("ERR = {:?}", e) })
});
tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner).unwrap();
match tokio::runtime::current_thread::Runtime::new().unwrap().block_on(runner) {
Ok(_) => {}, // The result is processed in callbacks, so nothing to do here
Err(e) => {
error!("Error while executing fetch_latest_block: {}", e);
eprintln!("{}", e);
}
};
}
}

View File

@@ -363,14 +363,14 @@ impl OutgoingTxMetadata {
pub struct WalletTx {
pub block: i32,
// Txid of this transcation. It's duplicated here (It is also the Key in the HashMap that points to this
// Txid of this transaction. It's duplicated here (It is also the Key in the HashMap that points to this
// WalletTx in LightWallet::txs)
pub txid: TxId,
// List of all notes recieved in this tx. Some of these might be change notes.
// List of all notes received in this tx. Some of these might be change notes.
pub notes: Vec<SaplingNoteData>,
// List of all Utxos recieved in this Tx. Some of these might be change notes
// List of all Utxos received in this Tx. Some of these might be change notes
pub utxos: Vec<Utxo>,
// Total shielded value spent in this Tx. Note that this is the value of the wallet's notes spent.

View File

@@ -335,7 +335,7 @@ impl LightWallet {
}).collect::<Vec<(String, String)>>()
}
// Clears all the downloaded blocks and resets the state back to the inital block.
// Clears all the downloaded blocks and resets the state back to the initial block.
// After this, the wallet's initial state will need to be set
// and the wallet will need to be rescanned
pub fn clear_blocks(&self) {
@@ -1072,7 +1072,7 @@ impl LightWallet {
let mut builder = Builder::new(height);
// A note on t addresses
// Funds recieved by t-addresses can't be explicitly spent in ZecWallet.
// Funds received by t-addresses can't be explicitly spent in ZecWallet.
// ZecWallet will lazily consolidate all t address funds into your shielded addresses.
// Specifically, if you send an outgoing transaction that is sent to a shielded address,
// ZecWallet will add all your t-address funds into that transaction, and send them to your shielded
@@ -1197,8 +1197,7 @@ impl LightWallet {
#[cfg(test)]
pub mod tests {
use std::convert::TryInto;
use std::fs::File;
use std::io::{Read, Error, ErrorKind};
use std::io::{Error};
use ff::{Field, PrimeField, PrimeFieldRepr};
use pairing::bls12_381::Bls12;
use rand_core::{RngCore, OsRng};
@@ -1228,24 +1227,17 @@ pub mod tests {
use super::LightWallet;
use crate::LightClientConfig;
use secp256k1::{Secp256k1, key::PublicKey, key::SecretKey};
use crate::SaplingParams;
fn get_sapling_params(config: &LightClientConfig) -> Result<(Vec<u8>, Vec<u8>), Error> {
fn get_sapling_params() -> Result<(Vec<u8>, Vec<u8>), Error> {
// Read Sapling Params
let mut sapling_output = vec![];
let mut f = match File::open(config.get_params_path("sapling-output.params")) {
Ok(file) => file,
Err(_) => return Err(Error::new(ErrorKind::NotFound,
format!("Couldn't read {}", config.get_params_path("sapling-output.params").display())))
};
f.read_to_end(&mut sapling_output)?;
sapling_output.extend_from_slice(SaplingParams::get("sapling-output.params").unwrap().as_ref());
println!("Read output {}", sapling_output.len());
let mut sapling_spend = vec![];
let mut f = match File::open(config.get_params_path("sapling-spend.params")) {
Ok(file) => file,
Err(_) => return Err(Error::new(ErrorKind::NotFound,
format!("Couldn't read {}", config.get_params_path("sapling-spend.params").display())))
};
f.read_to_end(&mut sapling_spend)?;
sapling_spend.extend_from_slice(SaplingParams::get("sapling-spend.params").unwrap().as_ref());
println!("Read output {}", sapling_spend.len());
Ok((sapling_spend, sapling_output))
}
@@ -1832,7 +1824,7 @@ pub mod tests {
}
// Get a test wallet already setup with a single note
fn get_test_wallet(amount: u64) -> (LightWallet, LightClientConfig, TxId, BlockHash) {
fn get_test_wallet(amount: u64) -> (LightWallet, TxId, BlockHash) {
let config = get_test_config();
let wallet = LightWallet::new(None, &config, 0).unwrap();
@@ -1852,18 +1844,17 @@ pub mod tests {
assert_eq!(wallet.verified_zbalance(None), amount);
// Create a new block so that the note is now verified to be spent
let cb2 = FakeCompactBlock::new(1, cb1.hash());
wallet.scan_block(&cb2.as_bytes()).unwrap();
(wallet, config, txid1, cb2.hash())
(wallet, txid1, cb2.hash())
}
#[test]
fn test_z_spend() {
const AMOUNT1: u64 = 50000;
let (wallet, config, txid1, block_hash) = get_test_wallet(AMOUNT1);
let (wallet, txid1, block_hash) = get_test_wallet(AMOUNT1);
let fvk = ExtendedFullViewingKey::from(&ExtendedSpendingKey::master(&[1u8; 32]));
let ext_address = encode_payment_address(wallet.config.hrp_sapling_address(),
@@ -1875,7 +1866,7 @@ pub mod tests {
let fee: u64 = DEFAULT_FEE.try_into().unwrap();
let branch_id = u32::from_str_radix("2bb40e60", 16).unwrap();
let (ss, so) = get_sapling_params(&config).unwrap();
let (ss, so) =get_sapling_params().unwrap();
// Create a tx and send to address
let raw_tx = wallet.send_to_address(branch_id, &ss, &so,
@@ -1933,10 +1924,10 @@ pub mod tests {
#[test]
fn test_z_spend_to_taddr() {
const AMOUNT1: u64 = 50000;
let (wallet, config, txid1, block_hash) = get_test_wallet(AMOUNT1);
let (wallet, txid1, block_hash) = get_test_wallet(AMOUNT1);
let branch_id = u32::from_str_radix("2bb40e60", 16).unwrap();
let (ss, so) = get_sapling_params(&config).unwrap();
let (ss, so) =get_sapling_params().unwrap();
let taddr = wallet.address_from_sk(&SecretKey::from_slice(&[1u8; 32]).unwrap());
const AMOUNT_SENT: u64 = 30;
@@ -1998,7 +1989,7 @@ pub mod tests {
const AMOUNT_Z: u64 = 50000;
const AMOUNT_T: u64 = 40000;
let (wallet, config, txid1, block_hash) = get_test_wallet(AMOUNT_Z);
let (wallet, txid1, block_hash) = get_test_wallet(AMOUNT_Z);
let pk = PublicKey::from_secret_key(&secp, &wallet.tkeys[0]);
let taddr = wallet.address_from_sk(&wallet.tkeys[0]);
@@ -2031,7 +2022,7 @@ pub mod tests {
let fee: u64 = DEFAULT_FEE.try_into().unwrap();
let branch_id = u32::from_str_radix("2bb40e60", 16).unwrap();
let (ss, so) = get_sapling_params(&config).unwrap();
let (ss, so) =get_sapling_params().unwrap();
// Create a tx and send to address. This should consume both the UTXO and the note
let raw_tx = wallet.send_to_address(branch_id, &ss, &so,
@@ -2096,7 +2087,7 @@ pub mod tests {
#[test]
fn test_z_incoming_memo() {
const AMOUNT1: u64 = 50000;
let (wallet, config, _txid1, block_hash) = get_test_wallet(AMOUNT1);
let (wallet, _txid1, block_hash) = get_test_wallet(AMOUNT1);
let my_address = encode_payment_address(wallet.config.hrp_sapling_address(),
&wallet.extfvks[0].default_address().unwrap().1);
@@ -2105,7 +2096,7 @@ pub mod tests {
let fee: u64 = DEFAULT_FEE.try_into().unwrap();
let branch_id = u32::from_str_radix("2bb40e60", 16).unwrap();
let (ss, so) = get_sapling_params(&config).unwrap();
let (ss, so) =get_sapling_params().unwrap();
// Create a tx and send to address
let raw_tx = wallet.send_to_address(branch_id, &ss, &so,

View File

@@ -1,3 +1,6 @@
#[macro_use]
extern crate rust_embed;
mod lightclient;
mod lightwallet;
mod address;
@@ -24,6 +27,10 @@ pub mod grpc_client {
include!(concat!(env!("OUT_DIR"), "/cash.z.wallet.sdk.rpc.rs"));
}
#[derive(RustEmbed)]
#[folder = "zcash-params/"]
pub struct SaplingParams;
pub fn main() {
// Get command line arguments
let matches = App::new("ZecLite CLI")
@@ -47,8 +54,20 @@ pub fn main() {
let server = LightClientConfig::get_server_or_default(maybe_server);
// Test to make sure the server has all of scheme, host and port
if server.scheme_str().is_none() || server.host().is_none() || server.port_part().is_none() {
eprintln!("Please provide the --server parameter as [scheme]://[host]:[port].\nYou provided: {}", server);
return;
}
// Do a getinfo first, before opening the wallet
let info = LightClient::get_info(server.clone());
let info = match LightClient::get_info(server.clone()) {
Ok(ld) => ld,
Err(e) => {
eprintln!("Error:\n{}\nCouldn't get server info, quitting!", e);
return;
}
};
// Create a Light Client Config
let config = lightclient::LightClientConfig {
@@ -112,12 +131,13 @@ pub fn main() {
// `()` can be used when no completer is required
let mut rl = Editor::<()>::new();
let _ = rl.load_history("history.txt");
println!("Ready!");
loop {
let readline = rl.readline(&format!("Block:{} (type 'help') >> ", lightclient.last_scanned_height()));
let readline = rl.readline(&format!("({}) Block:{} (type 'help') >> ",
config.chain_name,
lightclient.last_scanned_height()));
match readline {
Ok(line) => {
rl.add_history_entry(line.as_str());
@@ -167,5 +187,5 @@ pub fn main() {
}
}
}
rl.save_history("history.txt").unwrap();
}

Binary file not shown.

Binary file not shown.