Move rust client directory
This commit is contained in:
50
src/address.rs
Normal file
50
src/address.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
//! Structs for handling supported address types.
|
||||
|
||||
use pairing::bls12_381::Bls12;
|
||||
use zcash_primitives::primitives::PaymentAddress;
|
||||
use zcash_client_backend::encoding::{decode_payment_address, decode_transparent_address};
|
||||
use zcash_primitives::legacy::TransparentAddress;
|
||||
|
||||
use zcash_client_backend::constants::testnet::{
|
||||
B58_PUBKEY_ADDRESS_PREFIX, B58_SCRIPT_ADDRESS_PREFIX, HRP_SAPLING_PAYMENT_ADDRESS,
|
||||
};
|
||||
|
||||
/// An address that funds can be sent to.
|
||||
pub enum RecipientAddress {
|
||||
Shielded(PaymentAddress<Bls12>),
|
||||
Transparent(TransparentAddress),
|
||||
}
|
||||
|
||||
impl From<PaymentAddress<Bls12>> for RecipientAddress {
|
||||
fn from(addr: PaymentAddress<Bls12>) -> Self {
|
||||
RecipientAddress::Shielded(addr)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TransparentAddress> for RecipientAddress {
|
||||
fn from(addr: TransparentAddress) -> Self {
|
||||
RecipientAddress::Transparent(addr)
|
||||
}
|
||||
}
|
||||
|
||||
impl RecipientAddress {
|
||||
pub fn from_str(s: &str) -> Option<Self> {
|
||||
// Try to match a sapling z address
|
||||
if let Some(pa) = match decode_payment_address(HRP_SAPLING_PAYMENT_ADDRESS, s) {
|
||||
Ok(ret) => ret,
|
||||
Err(_) => None
|
||||
}
|
||||
{
|
||||
Some(RecipientAddress::Shielded(pa)) // Matched a shielded address
|
||||
} else if let Some(addr) = match decode_transparent_address(
|
||||
&B58_PUBKEY_ADDRESS_PREFIX, &B58_SCRIPT_ADDRESS_PREFIX, s) {
|
||||
Ok(ret) => ret,
|
||||
Err(_) => None
|
||||
}
|
||||
{
|
||||
Some(RecipientAddress::Transparent(addr)) // Matched a transparent address
|
||||
} else {
|
||||
None // Didn't match anything
|
||||
}
|
||||
}
|
||||
}
|
||||
256
src/commands.rs
Normal file
256
src/commands.rs
Normal file
@@ -0,0 +1,256 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::LightClient;
|
||||
|
||||
pub trait Command {
|
||||
fn help(&self);
|
||||
|
||||
fn short_help(&self) -> String;
|
||||
|
||||
fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String;
|
||||
}
|
||||
|
||||
struct SyncCommand {}
|
||||
impl Command for SyncCommand {
|
||||
fn help(&self) {
|
||||
println!("Type sync for syncing");
|
||||
}
|
||||
|
||||
fn short_help(&self) -> String {
|
||||
"Download CompactBlocks and sync to the server".to_string()
|
||||
}
|
||||
|
||||
fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String {
|
||||
lightclient.do_sync()
|
||||
}
|
||||
}
|
||||
|
||||
struct RescanCommand {}
|
||||
impl Command for RescanCommand {
|
||||
fn help(&self) {
|
||||
println!("Rescan the wallet from it's initial state, rescanning and downloading all blocks and transactions.");
|
||||
}
|
||||
|
||||
fn short_help(&self) -> String {
|
||||
"Rescan the wallet, downloading and scanning all blocks and transactions".to_string()
|
||||
}
|
||||
|
||||
fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String {
|
||||
lightclient.do_rescan()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
struct HelpCommand {}
|
||||
impl Command for HelpCommand {
|
||||
fn help(&self) {
|
||||
println!("Lists all available commands");
|
||||
}
|
||||
|
||||
fn short_help(&self) -> String {
|
||||
"Lists all available commands".to_string()
|
||||
}
|
||||
|
||||
fn exec(&self, _args: &[&str], _: &LightClient) -> String {
|
||||
let mut responses = vec![];
|
||||
// Print a list of all commands
|
||||
responses.push(format!("Available commands:"));
|
||||
get_commands().iter().for_each(| (cmd, obj) | {
|
||||
responses.push(format!("{} - {}", cmd, obj.short_help()));
|
||||
});
|
||||
|
||||
responses.join("\n")
|
||||
}
|
||||
}
|
||||
|
||||
struct InfoCommand {}
|
||||
impl Command for InfoCommand {
|
||||
fn help(&self) {
|
||||
println!("Gets server info");
|
||||
}
|
||||
|
||||
fn short_help(&self) -> String {
|
||||
"Get the lightwalletd server's info".to_string()
|
||||
}
|
||||
|
||||
fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String {
|
||||
lightclient.do_sync();
|
||||
lightclient.do_info()
|
||||
}
|
||||
}
|
||||
|
||||
struct BalanceCommand {}
|
||||
impl Command for BalanceCommand {
|
||||
fn help(&self) {
|
||||
println!("Show my balance");
|
||||
}
|
||||
|
||||
fn short_help(&self) -> String {
|
||||
"Show the current ZEC balance in the wallet".to_string()
|
||||
}
|
||||
|
||||
fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String {
|
||||
lightclient.do_sync();
|
||||
|
||||
format!("{}", lightclient.do_address().pretty(2))
|
||||
}
|
||||
}
|
||||
|
||||
struct SendCommand {}
|
||||
impl Command for SendCommand {
|
||||
fn help(&self) {
|
||||
println!("Sends ZEC to an address");
|
||||
println!("Usage:");
|
||||
println!("send recipient_address value memo");
|
||||
}
|
||||
|
||||
fn short_help(&self) -> String {
|
||||
"Send ZEC to the given address".to_string()
|
||||
}
|
||||
|
||||
fn exec(&self, args: &[&str], lightclient: &LightClient) -> String {
|
||||
// Parse the args.
|
||||
// 1 - Destination address. T or Z address
|
||||
if args.len() < 2 || args.len() > 3 {
|
||||
return self.short_help();
|
||||
}
|
||||
|
||||
// Make sure we can parse the amount
|
||||
let value = match args[1].parse::<u64>() {
|
||||
Ok(amt) => amt,
|
||||
Err(e) => {
|
||||
return format!("Couldn't parse amount: {}", e);;
|
||||
}
|
||||
};
|
||||
|
||||
let memo = if args.len() == 3 { Some(args[2].to_string()) } else {None};
|
||||
|
||||
lightclient.do_sync();
|
||||
|
||||
lightclient.do_send(args[0], value, memo)
|
||||
}
|
||||
}
|
||||
|
||||
struct SaveCommand {}
|
||||
impl Command for SaveCommand {
|
||||
fn help(&self) {
|
||||
println!("Save wallet to disk");
|
||||
}
|
||||
|
||||
fn short_help(&self) -> String {
|
||||
"Save wallet file to disk".to_string()
|
||||
}
|
||||
|
||||
fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String {
|
||||
lightclient.do_save()
|
||||
}
|
||||
}
|
||||
|
||||
struct SeedCommand {}
|
||||
impl Command for SeedCommand {
|
||||
fn help(&self) {
|
||||
println!("Show the seed phrase for the wallet");
|
||||
}
|
||||
|
||||
fn short_help(&self) -> String {
|
||||
"Display the seed phrase".to_string()
|
||||
}
|
||||
|
||||
fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String {
|
||||
lightclient.do_seed_phrase()
|
||||
}
|
||||
}
|
||||
|
||||
struct TransactionsCommand {}
|
||||
impl Command for TransactionsCommand {
|
||||
fn help(&self) {
|
||||
println!("Show transactions");
|
||||
}
|
||||
|
||||
fn short_help(&self) -> String {
|
||||
"List all transactions in the wallet".to_string()
|
||||
}
|
||||
|
||||
fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String {
|
||||
lightclient.do_sync();
|
||||
|
||||
format!("{}", lightclient.do_list_transactions().pretty(2))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
struct NotesCommand {}
|
||||
impl Command for NotesCommand {
|
||||
fn help(&self) {
|
||||
println!("Show Notes");
|
||||
}
|
||||
|
||||
fn short_help(&self) -> String {
|
||||
"List all sapling notes in the wallet".to_string()
|
||||
}
|
||||
|
||||
fn exec(&self, args: &[&str], lightclient: &LightClient) -> String {
|
||||
// Parse the args.
|
||||
if args.len() > 1 {
|
||||
return self.short_help();
|
||||
}
|
||||
|
||||
// Make sure we can parse the amount
|
||||
let all_notes = if args.len() == 1 {
|
||||
match args[0] {
|
||||
"all" => true,
|
||||
_ => return "Invalid argument. Specify 'all' to include unspent notes".to_string()
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
lightclient.do_sync();
|
||||
|
||||
format!("{}", lightclient.do_list_notes(all_notes).pretty(2))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
struct QuitCommand {}
|
||||
impl Command for QuitCommand {
|
||||
fn help(&self) {
|
||||
println!("Quit");
|
||||
}
|
||||
|
||||
fn short_help(&self) -> String {
|
||||
"Quit the lightwallet, saving state to disk".to_string()
|
||||
}
|
||||
|
||||
fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String {
|
||||
lightclient.do_save()
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Add rescan command
|
||||
// TODO: Add consolidate command to consolidate t inputs
|
||||
|
||||
pub fn get_commands() -> Box<HashMap<String, Box<dyn Command>>> {
|
||||
let mut map: HashMap<String, Box<dyn Command>> = HashMap::new();
|
||||
|
||||
map.insert("sync".to_string(), Box::new(SyncCommand{}));
|
||||
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("info".to_string(), Box::new(InfoCommand{}));
|
||||
map.insert("send".to_string(), Box::new(SendCommand{}));
|
||||
map.insert("save".to_string(), Box::new(SaveCommand{}));
|
||||
map.insert("quit".to_string(), Box::new(QuitCommand{}));
|
||||
map.insert("list".to_string(), Box::new(TransactionsCommand{}));
|
||||
map.insert("notes".to_string(), Box::new(NotesCommand{}));
|
||||
map.insert("seed".to_string(), Box::new(SeedCommand{}));
|
||||
|
||||
Box::new(map)
|
||||
}
|
||||
|
||||
pub fn do_user_command(cmd: &str, args: &Vec<&str>, lightclient: &LightClient) -> String {
|
||||
match get_commands().get(cmd) {
|
||||
Some(cmd) => cmd.exec(args, lightclient),
|
||||
None => format!("Unknown command : {}. Type 'help' for a list of commands", cmd)
|
||||
}
|
||||
}
|
||||
911
src/lightclient.rs
Normal file
911
src/lightclient.rs
Normal file
@@ -0,0 +1,911 @@
|
||||
use crate::lightwallet::LightWallet;
|
||||
|
||||
use std::path::Path;
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::io::prelude::*;
|
||||
use std::io::{BufReader, BufWriter};
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
|
||||
use std::error::Error;
|
||||
|
||||
use json::{object, JsonValue};
|
||||
|
||||
use zcash_primitives::transaction::{TxId, Transaction};
|
||||
use zcash_primitives::note_encryption::Memo;
|
||||
use zcash_client_backend::{
|
||||
constants::testnet::HRP_SAPLING_PAYMENT_ADDRESS, encoding::encode_payment_address,
|
||||
};
|
||||
|
||||
use futures::Future;
|
||||
use hyper::client::connect::{Destination, HttpConnector};
|
||||
use tower_grpc::Request;
|
||||
use tower_hyper::{client, util};
|
||||
use tower_util::MakeService;
|
||||
use futures::stream::Stream;
|
||||
|
||||
use crate::grpc_client::{ChainSpec, BlockId, BlockRange, RawTransaction, TransparentAddress,
|
||||
TransparentAddressBlockFilter, TxFilter, Empty};
|
||||
use crate::grpc_client::client::CompactTxStreamer;
|
||||
|
||||
// Used below to return the grpc "Client" type to calling methods
|
||||
type Client = crate::grpc_client::client::CompactTxStreamer<tower_request_modifier::RequestModifier<tower_hyper::client::Connection<tower_grpc::BoxBody>, tower_grpc::BoxBody>>;
|
||||
|
||||
pub struct LightClient {
|
||||
pub wallet : Arc<LightWallet>,
|
||||
pub sapling_output : Vec<u8>,
|
||||
pub sapling_spend : Vec<u8>,
|
||||
}
|
||||
|
||||
impl LightClient {
|
||||
|
||||
pub fn set_wallet_initial_state(&self) {
|
||||
self.wallet.set_initial_block(500000,
|
||||
"004fada8d4dbc5e80b13522d2c6bd0116113c9b7197f0c6be69bc7a62f2824cd",
|
||||
"01b733e839b5f844287a6a491409a991ec70277f39a50c99163ed378d23a829a0700100001916db36dfb9a0cf26115ed050b264546c0fa23459433c31fd72f63d188202f2400011f5f4e3bd18da479f48d674dbab64454f6995b113fa21c9d8853a9e764fb3e1f01df9d2c233ca60360e3c2bb73caf5839a1be634c8b99aea22d02abda2e747d9100001970d41722c078288101acd0a75612acfb4c434f2a55aab09fb4e812accc2ba7301485150f0deac7774dcd0fe32043bde9ba2b6bbfff787ad074339af68e88ee70101601324f1421e00a43ef57f197faf385ee4cac65aab58048016ecbd94e022973701e1b17f4bd9d1b6ca1107f619ac6d27b53dd3350d5be09b08935923cbed97906c0000000000011f8322ef806eb2430dc4a7a41c1b344bea5be946efc7b4349c1c9edb14ff9d39");
|
||||
|
||||
}
|
||||
|
||||
pub fn new(seed_phrase: Option<String>) -> io::Result<Self> {
|
||||
let mut lc = if Path::new("wallet.dat").exists() {
|
||||
// Make sure that if a wallet exists, there is no seed phrase being attempted
|
||||
if !seed_phrase.is_none() {
|
||||
return Err(io::Error::new(io::ErrorKind::AlreadyExists,
|
||||
"Cannot create a new wallet from seed, because a wallet already exists"));
|
||||
}
|
||||
|
||||
let mut file_buffer = BufReader::new(File::open("wallet.dat")?);
|
||||
|
||||
let wallet = LightWallet::read(&mut file_buffer)?;
|
||||
LightClient {
|
||||
wallet : Arc::new(wallet),
|
||||
sapling_output : vec![],
|
||||
sapling_spend : vec![]
|
||||
}
|
||||
} else {
|
||||
let l = LightClient {
|
||||
wallet : Arc::new(LightWallet::new(seed_phrase)?),
|
||||
sapling_output : vec![],
|
||||
sapling_spend : vec![]
|
||||
};
|
||||
|
||||
l.set_wallet_initial_state();
|
||||
|
||||
l
|
||||
};
|
||||
|
||||
// Read Sapling Params
|
||||
let mut f = File::open("/home/adityapk/.zcash-params/sapling-output.params")?;
|
||||
f.read_to_end(&mut lc.sapling_output)?;
|
||||
let mut f = File::open("/home/adityapk/.zcash-params/sapling-spend.params")?;
|
||||
f.read_to_end(&mut lc.sapling_spend)?;
|
||||
|
||||
Ok(lc)
|
||||
}
|
||||
|
||||
pub fn last_scanned_height(&self) -> u64 {
|
||||
self.wallet.last_scanned_height() as u64
|
||||
}
|
||||
|
||||
pub fn do_address(&self) -> json::JsonValue {
|
||||
// Collect z addresses
|
||||
let z_addresses = self.wallet.address.iter().map( |ad| {
|
||||
let address = encode_payment_address(HRP_SAPLING_PAYMENT_ADDRESS, &ad);
|
||||
object!{
|
||||
"address" => address.clone(),
|
||||
"zbalance" => self.wallet.zbalance(Some(address.clone())),
|
||||
"verified_zbalance" => self.wallet.verified_zbalance(Some(address)),
|
||||
}
|
||||
}).collect::<Vec<JsonValue>>();
|
||||
|
||||
// Collect t addresses
|
||||
let t_addresses = self.wallet.tkeys.iter().map( |sk| {
|
||||
let address = LightWallet::address_from_sk(&sk);
|
||||
|
||||
// Get the balance for this address
|
||||
let balance = self.wallet.tbalance(Some(address.clone()));
|
||||
|
||||
object!{
|
||||
"address" => address,
|
||||
"balance" => balance,
|
||||
}
|
||||
}).collect::<Vec<JsonValue>>();
|
||||
|
||||
object!{
|
||||
"zbalance" => self.wallet.zbalance(None),
|
||||
"verified_zbalance" => self.wallet.verified_zbalance(None),
|
||||
"tbalance" => self.wallet.tbalance(None),
|
||||
"z_addresses" => z_addresses,
|
||||
"t_addresses" => t_addresses,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn do_save(&self) -> String {
|
||||
io::stdout().flush().ok().expect("Could not flush stdout");
|
||||
let mut file_buffer = BufWriter::with_capacity(
|
||||
1_000_000, // 1 MB write buffer
|
||||
File::create("wallet.dat").unwrap());
|
||||
|
||||
self.wallet.write(&mut file_buffer).unwrap();
|
||||
format!("Saved Wallet")
|
||||
}
|
||||
|
||||
|
||||
pub fn do_info(&self) -> String {
|
||||
use std::cell::RefCell;
|
||||
|
||||
let uri: http::Uri = format!("http://127.0.0.1:9067").parse().unwrap();
|
||||
let infostr = Arc::new(RefCell::<String>::default());
|
||||
|
||||
let infostrinner = infostr.clone();
|
||||
let say_hello = self.make_grpc_client(uri).unwrap()
|
||||
.and_then(move |mut client| {
|
||||
client.get_lightd_info(Request::new(Empty{}))
|
||||
})
|
||||
.and_then(move |response| {
|
||||
//let tx = Transaction::read(&response.into_inner().data[..]).unwrap();
|
||||
//println!("{:?}", response.into_inner());
|
||||
infostrinner.replace(format!("{:?}", response.into_inner()));
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|e| {
|
||||
println!("ERR = {:?}", e);
|
||||
});
|
||||
|
||||
tokio::runtime::current_thread::Runtime::new().unwrap().block_on(say_hello).unwrap();
|
||||
let ans = infostr.borrow().clone();
|
||||
|
||||
ans
|
||||
}
|
||||
|
||||
pub fn do_seed_phrase(&self) -> String {
|
||||
self.wallet.get_seed_phrase()
|
||||
}
|
||||
|
||||
// Return a list of all notes, spent and unspent
|
||||
pub fn do_list_notes(&self, all_notes: bool) -> JsonValue {
|
||||
let mut unspent_notes: Vec<JsonValue> = vec![];
|
||||
let mut spent_notes : Vec<JsonValue> = vec![];
|
||||
let mut pending_notes: Vec<JsonValue> = vec![];
|
||||
|
||||
// Collect Sapling notes
|
||||
self.wallet.txs.read().unwrap().iter()
|
||||
.flat_map( |(txid, wtx)| {
|
||||
wtx.notes.iter().filter_map(move |nd|
|
||||
if !all_notes && nd.spent.is_some() {
|
||||
None
|
||||
} else {
|
||||
Some(object!{
|
||||
"created_in_block" => wtx.block,
|
||||
"created_in_txid" => format!("{}", txid),
|
||||
"value" => nd.note.value,
|
||||
"is_change" => nd.is_change,
|
||||
"address" => LightWallet::address_from_extfvk(&nd.extfvk, nd.diversifier),
|
||||
"spent" => nd.spent.map(|spent_txid| format!("{}", spent_txid)),
|
||||
"unconfirmed_spent" => nd.unconfirmed_spent.map(|spent_txid| format!("{}", spent_txid)),
|
||||
})
|
||||
}
|
||||
)
|
||||
})
|
||||
.for_each( |note| {
|
||||
if note["spent"].is_null() && note["unconfirmed_spent"].is_null() {
|
||||
unspent_notes.push(note);
|
||||
} else if !note["spent"].is_null() {
|
||||
spent_notes.push(note);
|
||||
} else {
|
||||
pending_notes.push(note);
|
||||
}
|
||||
});
|
||||
|
||||
// Collect UTXOs
|
||||
let utxos = self.wallet.utxos.read().unwrap().iter()
|
||||
.map(|utxo| {
|
||||
object!{
|
||||
"created_in_block" => utxo.height,
|
||||
"created_in_txid" => format!("{}", utxo.txid),
|
||||
"value" => utxo.value,
|
||||
"scriptkey" => hex::encode(utxo.script.clone()),
|
||||
"is_change" => false, // TODO: Identify notes as change
|
||||
"address" => utxo.address.clone(),
|
||||
"spent" => utxo.spent.map(|spent_txid| format!("{}", spent_txid)),
|
||||
"unconfirmed_spent" => utxo.unconfirmed_spent.map(|spent_txid| format!("{}", spent_txid)),
|
||||
}
|
||||
})
|
||||
.collect::<Vec<JsonValue>>();
|
||||
|
||||
// Collect pending UTXOs
|
||||
let pending_utxos = self.wallet.txs.read().unwrap().iter()
|
||||
.flat_map( |(txid, wtx)| {
|
||||
wtx.utxos.iter().filter_map(move |utxo|
|
||||
if utxo.unconfirmed_spent.is_some() {
|
||||
Some(object!{
|
||||
"created_in_block" => wtx.block,
|
||||
"created_in_txid" => format!("{}", txid),
|
||||
"value" => utxo.value,
|
||||
"scriptkey" => hex::encode(utxo.script.clone()),
|
||||
"is_change" => false, // TODO: Identify notes as change
|
||||
"address" => utxo.address.clone(),
|
||||
"spent" => utxo.spent.map(|spent_txid| format!("{}", spent_txid)),
|
||||
"unconfirmed_spent" => utxo.unconfirmed_spent.map(|spent_txid| format!("{}", spent_txid)),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
)
|
||||
})
|
||||
.collect::<Vec<JsonValue>>();;
|
||||
|
||||
let mut res = object!{
|
||||
"unspent_notes" => unspent_notes,
|
||||
"pending_notes" => pending_notes,
|
||||
"utxos" => utxos,
|
||||
"pending_utxos" => pending_utxos,
|
||||
};
|
||||
|
||||
if all_notes {
|
||||
res["spent_notes"] = JsonValue::Array(spent_notes);
|
||||
}
|
||||
|
||||
// If all notes, also add historical utxos
|
||||
if all_notes {
|
||||
res["spent_utxos"] = JsonValue::Array(self.wallet.txs.read().unwrap().values()
|
||||
.flat_map(|wtx| {
|
||||
wtx.utxos.iter()
|
||||
.filter(|utxo| utxo.spent.is_some())
|
||||
.map(|utxo| {
|
||||
object!{
|
||||
"created_in_block" => wtx.block,
|
||||
"created_in_txid" => format!("{}", utxo.txid),
|
||||
"value" => utxo.value,
|
||||
"scriptkey" => hex::encode(utxo.script.clone()),
|
||||
"is_change" => false, // TODO: Identify notes as change
|
||||
"address" => utxo.address.clone(),
|
||||
"spent" => utxo.spent.map(|spent_txid| format!("{}", spent_txid)),
|
||||
"unconfirmed_spent" => utxo.unconfirmed_spent.map(|spent_txid| format!("{}", spent_txid)),
|
||||
}
|
||||
}).collect::<Vec<JsonValue>>()
|
||||
}).collect::<Vec<JsonValue>>()
|
||||
);
|
||||
}
|
||||
|
||||
res
|
||||
}
|
||||
|
||||
pub fn do_list_transactions(&self) -> JsonValue {
|
||||
// Create a list of TransactionItems
|
||||
let mut tx_list = self.wallet.txs.read().unwrap().iter()
|
||||
.flat_map(| (_k, v) | {
|
||||
let mut txns: Vec<JsonValue> = vec![];
|
||||
|
||||
if v.total_shielded_value_spent > 0 {
|
||||
// If money was spent, create a transaction. For this, we'll subtract
|
||||
// all the change notes. TODO: Add transparent change here to subtract it also
|
||||
let total_change: u64 = v.notes.iter()
|
||||
.filter( |nd| nd.is_change )
|
||||
.map( |nd| nd.note.value )
|
||||
.sum();
|
||||
|
||||
// TODO: What happens if change is > than sent ?
|
||||
|
||||
txns.push(object! {
|
||||
"block_height" => v.block,
|
||||
"txid" => format!("{}", v.txid),
|
||||
"amount" => total_change as i64
|
||||
- v.total_shielded_value_spent as i64
|
||||
- v.total_transparent_value_spent as i64,
|
||||
"address" => None::<String>, // TODO: For send, we don't have an address
|
||||
"memo" => None::<String>
|
||||
});
|
||||
}
|
||||
|
||||
// For each sapling note that is not a change, add a Tx.
|
||||
txns.extend(v.notes.iter()
|
||||
.filter( |nd| !nd.is_change )
|
||||
.map ( |nd|
|
||||
object! {
|
||||
"block_height" => v.block,
|
||||
"txid" => format!("{}", v.txid),
|
||||
"amount" => nd.note.value as i64,
|
||||
"address" => nd.note_address().unwrap(),
|
||||
"memo" => match &nd.memo {
|
||||
Some(memo) => {
|
||||
match memo.to_utf8() {
|
||||
Some(Ok(memo_str)) => Some(memo_str),
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
_ => None
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// Get the total transparent recieved
|
||||
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.
|
||||
txns.push(object!{
|
||||
"block_height" => v.block,
|
||||
"txid" => format!("{}", v.txid),
|
||||
"amount" => total_transparent_received as i64 - v.total_transparent_value_spent as i64,
|
||||
"address" => v.utxos.iter().map(|u| u.address.clone()).collect::<Vec<String>>().join(","),
|
||||
"memo" => None::<String>
|
||||
})
|
||||
}
|
||||
|
||||
txns
|
||||
})
|
||||
.collect::<Vec<JsonValue>>();
|
||||
|
||||
tx_list.sort_by( |a, b| if a["block_height"] == b["block_height"] {
|
||||
a["txid"].as_str().cmp(&b["txid"].as_str())
|
||||
} else {
|
||||
a["block_height"].as_i32().cmp(&b["block_height"].as_i32())
|
||||
}
|
||||
);
|
||||
|
||||
JsonValue::Array(tx_list)
|
||||
}
|
||||
|
||||
pub fn do_rescan(&self) -> String {
|
||||
// First, clear the state from the wallet
|
||||
self.wallet.clear_blocks();
|
||||
|
||||
// Then set the inital block
|
||||
self.set_wallet_initial_state();
|
||||
|
||||
// Then, do a sync, which will force a full rescan from the initial state
|
||||
self.do_sync()
|
||||
}
|
||||
|
||||
pub fn do_sync(&self) -> String {
|
||||
// Sync is 3 parts
|
||||
// 1. Get the latest block
|
||||
// 2. Get all the blocks that we don't have
|
||||
// 3. Find all new Txns that don't have the full Tx, and get them as full transactions
|
||||
// and scan them, mainly to get the memos
|
||||
let mut last_scanned_height = self.wallet.last_scanned_height() as u64;
|
||||
|
||||
// This will hold the latest block fetched from the RPC
|
||||
let latest_block_height = Arc::new(AtomicU64::new(0));
|
||||
let lbh = latest_block_height.clone();
|
||||
self.fetch_latest_block(move |block: BlockId| {
|
||||
lbh.store(block.height, Ordering::SeqCst);
|
||||
});
|
||||
let last_block = latest_block_height.load(Ordering::SeqCst);
|
||||
|
||||
// Get the end height to scan to.
|
||||
let mut end_height = std::cmp::min(last_scanned_height + 1000, last_block);
|
||||
|
||||
// Count how many bytes we've downloaded
|
||||
let bytes_downloaded = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
// Fetch CompactBlocks in increments
|
||||
loop {
|
||||
let local_light_wallet = self.wallet.clone();
|
||||
let local_bytes_downloaded = bytes_downloaded.clone();
|
||||
|
||||
// Show updates only if we're syncing a lot of blocks
|
||||
if end_height - last_scanned_height > 100 {
|
||||
print!("Syncing {}/{}\r", last_scanned_height, last_block);
|
||||
}
|
||||
|
||||
// Fetch compact blocks
|
||||
self.fetch_blocks(last_scanned_height, end_height,
|
||||
move |encoded_block: &[u8]| {
|
||||
local_light_wallet.scan_block(encoded_block);
|
||||
local_bytes_downloaded.fetch_add(encoded_block.len(), Ordering::SeqCst);
|
||||
});
|
||||
|
||||
// We'll also fetch all the txids that our transparent addresses are involved with
|
||||
// TODO: Use for all t addresses
|
||||
let address = LightWallet::address_from_sk(&self.wallet.tkeys[0]);
|
||||
let wallet = self.wallet.clone();
|
||||
self.fetch_transparent_txids(address, last_scanned_height, end_height,
|
||||
move |tx_bytes: &[u8], height: u64 | {
|
||||
let tx = Transaction::read(tx_bytes).unwrap();
|
||||
|
||||
// Scan this Tx for transparent inputs and outputs
|
||||
wallet.scan_full_tx(&tx, height as i32); // TODO: Add the height here!
|
||||
}
|
||||
);
|
||||
|
||||
last_scanned_height = end_height + 1;
|
||||
end_height = last_scanned_height + 1000 - 1;
|
||||
|
||||
if last_scanned_height > last_block {
|
||||
break;
|
||||
} else if end_height > last_block {
|
||||
end_height = last_block;
|
||||
}
|
||||
}
|
||||
println!(); // Print a new line, to finalize the syncing updates
|
||||
|
||||
let mut responses = vec![];
|
||||
responses.push(format!("Synced to {}, Downloaded {} kB", last_block, bytes_downloaded.load(Ordering::SeqCst) / 1024));
|
||||
|
||||
|
||||
// Get the Raw transaction for all the wallet transactions
|
||||
|
||||
// We need to first copy over the Txids from the wallet struct, because
|
||||
// we need to free the read lock from here (Because we'll self.wallet.txs later)
|
||||
let txids_to_fetch: Vec<(TxId, i32)>;
|
||||
{
|
||||
// First, build a list of all the TxIDs and Memos that we need
|
||||
// to fetch.
|
||||
// 1. Get all (txid, Option<Memo>)
|
||||
// 2. Filter out all txids where the Memo is None
|
||||
// (Which means that particular txid was never fetched. Remember
|
||||
// that when memos are fetched, if they are empty, they become
|
||||
// Some(f60000...)
|
||||
let txids_and_memos = self.wallet.txs.read().unwrap().iter()
|
||||
.flat_map( |(txid, wtx)| { // flat_map because we're collecting vector of vectors
|
||||
wtx.notes.iter()
|
||||
.filter( |nd| nd.memo.is_none()) // only get if memo is None (i.e., it has not been fetched)
|
||||
.map( |nd| (txid.clone(), nd.memo.clone(), wtx.block) ) // collect (txid, memo, height) Clone everything because we want copies, so we can release the read lock
|
||||
.collect::<Vec<(TxId, Option<Memo>, i32)>>() // convert to vector
|
||||
})
|
||||
.collect::<Vec<(TxId, Option<Memo>, i32)>>();
|
||||
|
||||
//println!("{:?}", txids_and_memos);
|
||||
// TODO: Assert that all the memos here are None
|
||||
|
||||
txids_to_fetch = txids_and_memos.iter()
|
||||
.map( | (txid, _, h) | (txid.clone(), *h) ) // We're only interested in the txids, so drop the Memo, which is None anyway
|
||||
.collect::<Vec<(TxId, i32)>>(); // and convert into Vec
|
||||
}
|
||||
|
||||
// And go and fetch the txids, getting the full transaction, so we can
|
||||
// read the memos
|
||||
for (txid, height) in txids_to_fetch {
|
||||
let light_wallet_clone = self.wallet.clone();
|
||||
responses.push(format!("Fetching full Tx: {}", txid));
|
||||
|
||||
self.fetch_full_tx(txid, move |tx_bytes: &[u8] | {
|
||||
let tx = Transaction::read(tx_bytes).unwrap();
|
||||
|
||||
light_wallet_clone.scan_full_tx(&tx, height);
|
||||
});
|
||||
};
|
||||
|
||||
// Finally, fetch the UTXOs
|
||||
|
||||
// Get all the UTXOs for our transparent addresses, clearing out the current list
|
||||
self.wallet.clear_utxos();
|
||||
// Fetch UTXOs
|
||||
self.wallet.tkeys.iter()
|
||||
.map( |sk| LightWallet::address_from_sk(&sk))
|
||||
.for_each( |taddr| {
|
||||
let wallet = self.wallet.clone();
|
||||
self.fetch_utxos(taddr, move |utxo| {
|
||||
wallet.add_utxo(&utxo);
|
||||
});
|
||||
});
|
||||
|
||||
responses.join("\n")
|
||||
}
|
||||
|
||||
pub fn do_send(&self, addr: &str, value: u64, memo: Option<String>) -> String {
|
||||
let rawtx = self.wallet.send_to_address(
|
||||
u32::from_str_radix("2bb40e60", 16).unwrap(), // Blossom ID
|
||||
&self.sapling_spend, &self.sapling_output,
|
||||
&addr, value, memo
|
||||
);
|
||||
|
||||
match rawtx {
|
||||
Some(txbytes) => self.broadcast_raw_tx(txbytes),
|
||||
None => format!("No Tx to broadcast")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fetch_blocks<F : 'static + std::marker::Send>(&self, start_height: u64, end_height: u64, c: F)
|
||||
where F : Fn(&[u8]) {
|
||||
// Fetch blocks
|
||||
let uri: http::Uri = format!("http://127.0.0.1:9067").parse().unwrap();
|
||||
|
||||
let dst = Destination::try_from_uri(uri.clone()).unwrap();
|
||||
let connector = util::Connector::new(HttpConnector::new(4));
|
||||
let settings = client::Builder::new().http2_only(true).clone();
|
||||
let mut make_client = client::Connect::with_builder(connector, settings);
|
||||
|
||||
let say_hello = make_client
|
||||
.make_service(dst)
|
||||
.map_err(|e| panic!("connect error: {:?}", e))
|
||||
.and_then(move |conn| {
|
||||
|
||||
let conn = tower_request_modifier::Builder::new()
|
||||
.set_origin(uri)
|
||||
.build(conn)
|
||||
.unwrap();
|
||||
|
||||
// Wait until the client is ready...
|
||||
CompactTxStreamer::new(conn)
|
||||
.ready()
|
||||
.map_err(|e| eprintln!("streaming error {:?}", e))
|
||||
})
|
||||
.and_then(move |mut client| {
|
||||
let bs = BlockId{ height: start_height, hash: vec!()};
|
||||
let be = BlockId{ height: end_height, hash: vec!()};
|
||||
|
||||
let br = Request::new(BlockRange{ start: Some(bs), end: Some(be)});
|
||||
client
|
||||
.get_block_range(br)
|
||||
.map_err(|e| {
|
||||
eprintln!("RouteChat request failed; err={:?}", e);
|
||||
})
|
||||
.and_then(move |response| {
|
||||
let inbound = response.into_inner();
|
||||
inbound.for_each(move |b| {
|
||||
use prost::Message;
|
||||
let mut encoded_buf = vec![];
|
||||
|
||||
b.encode(&mut encoded_buf).unwrap();
|
||||
c(&encoded_buf);
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|e| eprintln!("gRPC inbound stream error: {:?}", e))
|
||||
})
|
||||
});
|
||||
|
||||
tokio::runtime::current_thread::Runtime::new().unwrap().block_on(say_hello).unwrap();
|
||||
}
|
||||
|
||||
pub fn fetch_utxos<F : 'static + std::marker::Send>(&self, address: String, c: F)
|
||||
where F : Fn(crate::lightwallet::Utxo) {
|
||||
let uri: http::Uri = format!("http://127.0.0.1:9067").parse().unwrap();
|
||||
|
||||
let dst = Destination::try_from_uri(uri.clone()).unwrap();
|
||||
let connector = util::Connector::new(HttpConnector::new(4));
|
||||
let settings = client::Builder::new().http2_only(true).clone();
|
||||
let mut make_client = client::Connect::with_builder(connector, settings);
|
||||
|
||||
let say_hello = make_client
|
||||
.make_service(dst)
|
||||
.map_err(|e| panic!("connect error: {:?}", e))
|
||||
.and_then(move |conn| {
|
||||
|
||||
let conn = tower_request_modifier::Builder::new()
|
||||
.set_origin(uri)
|
||||
.build(conn)
|
||||
.unwrap();
|
||||
|
||||
// Wait until the client is ready...
|
||||
CompactTxStreamer::new(conn)
|
||||
.ready()
|
||||
.map_err(|e| eprintln!("streaming error {:?}", e))
|
||||
})
|
||||
.and_then(move |mut client| {
|
||||
|
||||
let br = Request::new(TransparentAddress{ address });
|
||||
client
|
||||
.get_utxos(br)
|
||||
.map_err(|e| {
|
||||
eprintln!("RouteChat request failed; err={:?}", e);
|
||||
})
|
||||
.and_then(move |response| {
|
||||
let inbound = response.into_inner();
|
||||
inbound.for_each(move |b| {
|
||||
let mut txid_bytes = [0u8; 32];
|
||||
txid_bytes.copy_from_slice(&b.txid);
|
||||
|
||||
let u = crate::lightwallet::Utxo {
|
||||
address: b.address.unwrap().address,
|
||||
txid: TxId {0: txid_bytes},
|
||||
output_index: b.output_index,
|
||||
script: b.script.to_vec(),
|
||||
height: b.height as i32,
|
||||
value: b.value,
|
||||
spent: None,
|
||||
unconfirmed_spent: None,
|
||||
};
|
||||
|
||||
c(u);
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|e| eprintln!("gRPC inbound stream error: {:?}", e))
|
||||
})
|
||||
});
|
||||
|
||||
tokio::runtime::current_thread::Runtime::new().unwrap().block_on(say_hello).unwrap();
|
||||
}
|
||||
|
||||
pub fn fetch_transparent_txids<F : 'static + std::marker::Send>(&self, address: String,
|
||||
start_height: u64, end_height: u64,c: F)
|
||||
where F : Fn(&[u8], u64) {
|
||||
let uri: http::Uri = format!("http://127.0.0.1:9067").parse().unwrap();
|
||||
|
||||
let dst = Destination::try_from_uri(uri.clone()).unwrap();
|
||||
let connector = util::Connector::new(HttpConnector::new(4));
|
||||
let settings = client::Builder::new().http2_only(true).clone();
|
||||
let mut make_client = client::Connect::with_builder(connector, settings);
|
||||
|
||||
let say_hello = make_client
|
||||
.make_service(dst)
|
||||
.map_err(|e| panic!("connect error: {:?}", e))
|
||||
.and_then(move |conn| {
|
||||
|
||||
let conn = tower_request_modifier::Builder::new()
|
||||
.set_origin(uri)
|
||||
.build(conn)
|
||||
.unwrap();
|
||||
|
||||
// Wait until the client is ready...
|
||||
CompactTxStreamer::new(conn)
|
||||
.ready()
|
||||
.map_err(|e| eprintln!("streaming error {:?}", e))
|
||||
})
|
||||
.and_then(move |mut client| {
|
||||
let start = Some(BlockId{ height: start_height, hash: vec!()});
|
||||
let end = Some(BlockId{ height: end_height, hash: vec!()});
|
||||
|
||||
let br = Request::new(TransparentAddressBlockFilter{ address, range: Some(BlockRange{start, end}) });
|
||||
|
||||
client
|
||||
.get_address_txids(br)
|
||||
.map_err(|e| {
|
||||
eprintln!("RouteChat request failed; err={:?}", e);
|
||||
})
|
||||
.and_then(move |response| {
|
||||
let inbound = response.into_inner();
|
||||
inbound.for_each(move |tx| {
|
||||
//let tx = Transaction::read(&tx.into_inner().data[..]).unwrap();
|
||||
c(&tx.data, tx.height);
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|e| eprintln!("gRPC inbound stream error: {:?}", e))
|
||||
})
|
||||
});
|
||||
|
||||
tokio::runtime::current_thread::Runtime::new().unwrap().block_on(say_hello).unwrap();
|
||||
}
|
||||
|
||||
pub fn fetch_full_tx<F : 'static + std::marker::Send>(&self, txid: TxId, c: F)
|
||||
where F : Fn(&[u8]) {
|
||||
let uri: http::Uri = format!("http://127.0.0.1:9067").parse().unwrap();
|
||||
|
||||
let say_hello = self.make_grpc_client(uri).unwrap()
|
||||
.and_then(move |mut client| {
|
||||
let txfilter = TxFilter { block: None, index: 0, hash: txid.0.to_vec() };
|
||||
client.get_transaction(Request::new(txfilter))
|
||||
})
|
||||
.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);
|
||||
});
|
||||
|
||||
tokio::runtime::current_thread::Runtime::new().unwrap().block_on(say_hello).unwrap();
|
||||
}
|
||||
|
||||
pub fn broadcast_raw_tx(&self, tx_bytes: Box<[u8]>) -> String {
|
||||
use std::cell::RefCell;
|
||||
|
||||
let uri: http::Uri = format!("http://127.0.0.1:9067").parse().unwrap();
|
||||
|
||||
let infostr = Arc::new(RefCell::<String>::default());
|
||||
let infostrinner = infostr.clone();
|
||||
|
||||
let say_hello = self.make_grpc_client(uri).unwrap()
|
||||
.and_then(move |mut client| {
|
||||
client.send_transaction(Request::new(RawTransaction {data: tx_bytes.to_vec(), height: 0}))
|
||||
})
|
||||
.and_then(move |response| {
|
||||
infostrinner.replace(format!("{:?}", response.into_inner()));
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|e| {
|
||||
println!("ERR = {:?}", e);
|
||||
});
|
||||
|
||||
tokio::runtime::current_thread::Runtime::new().unwrap().block_on(say_hello).unwrap();
|
||||
|
||||
let ans = infostr.borrow().clone();
|
||||
ans
|
||||
}
|
||||
|
||||
pub fn fetch_latest_block<F : 'static + std::marker::Send>(&self, mut c : F)
|
||||
where F : FnMut(BlockId) {
|
||||
let uri: http::Uri = format!("http://127.0.0.1:9067").parse().unwrap();
|
||||
|
||||
let say_hello = self.make_grpc_client(uri).unwrap()
|
||||
.and_then(|mut client| {
|
||||
client.get_latest_block(Request::new(ChainSpec {}))
|
||||
})
|
||||
.and_then(move |response| {
|
||||
c(response.into_inner());
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|e| {
|
||||
println!("ERR = {:?}", e);
|
||||
});
|
||||
|
||||
tokio::runtime::current_thread::Runtime::new().unwrap().block_on(say_hello).unwrap();
|
||||
}
|
||||
|
||||
fn make_grpc_client(&self, uri: http::Uri) -> Result<Box<dyn Future<Item=Client, Error=tower_grpc::Status> + Send>, Box<dyn Error>> {
|
||||
let dst = Destination::try_from_uri(uri.clone())?;
|
||||
let connector = util::Connector::new(HttpConnector::new(4));
|
||||
let settings = client::Builder::new().http2_only(true).clone();
|
||||
let mut make_client = client::Connect::with_builder(connector, settings);
|
||||
|
||||
let say_hello = make_client
|
||||
.make_service(dst)
|
||||
.map_err(|e| panic!("connect error: {:?}", e))
|
||||
.and_then(move |conn| {
|
||||
|
||||
let conn = tower_request_modifier::Builder::new()
|
||||
.set_origin(uri)
|
||||
.build(conn)
|
||||
.unwrap();
|
||||
|
||||
// Wait until the client is ready...
|
||||
CompactTxStreamer::new(conn).ready()
|
||||
});
|
||||
Ok(Box::new(say_hello))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/*
|
||||
TLS Example https://gist.github.com/kiratp/dfcbcf0aa713a277d5d53b06d9db9308
|
||||
|
||||
// [dependencies]
|
||||
// futures = "0.1.27"
|
||||
// http = "0.1.17"
|
||||
// tokio = "0.1.21"
|
||||
// tower-request-modifier = { git = "https://github.com/tower-rs/tower-http" }
|
||||
// tower-grpc = { version = "0.1.0", features = ["tower-hyper"] }
|
||||
// tower-service = "0.2"
|
||||
// tower-util = "0.1"
|
||||
// tokio-rustls = "0.10.0-alpha.3"
|
||||
// webpki = "0.19.1"
|
||||
// webpki-roots = "0.16.0"
|
||||
// tower-h2 = { git = "https://github.com/tower-rs/tower-h2" }
|
||||
// openssl = "*"
|
||||
// openssl-probe = "*"
|
||||
|
||||
use std::thread;
|
||||
use std::sync::{Arc};
|
||||
use futures::{future, Future};
|
||||
use tower_util::MakeService;
|
||||
|
||||
use tokio_rustls::client::TlsStream;
|
||||
use tokio_rustls::{rustls::ClientConfig, TlsConnector};
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use tokio::executor::DefaultExecutor;
|
||||
use tokio::net::tcp::TcpStream;
|
||||
use tower_h2;
|
||||
|
||||
use std::net::ToSocketAddrs;
|
||||
|
||||
|
||||
|
||||
struct Dst(SocketAddr);
|
||||
|
||||
|
||||
impl tower_service::Service<()> for Dst {
|
||||
type Response = TlsStream<TcpStream>;
|
||||
type Error = ::std::io::Error;
|
||||
type Future = Box<dyn Future<Item = TlsStream<TcpStream>, Error = ::std::io::Error> + Send>;
|
||||
|
||||
fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
|
||||
Ok(().into())
|
||||
}
|
||||
|
||||
fn call(&mut self, _: ()) -> Self::Future {
|
||||
println!("{:?}", self.0);
|
||||
let mut config = ClientConfig::new();
|
||||
|
||||
config.alpn_protocols.push(b"h2".to_vec());
|
||||
config.root_store.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
|
||||
let config = Arc::new(config);
|
||||
let tls_connector = TlsConnector::from(config);
|
||||
|
||||
let addr_string_local = "mydomain.com";
|
||||
|
||||
let domain = webpki::DNSNameRef::try_from_ascii_str(addr_string_local).unwrap();
|
||||
let domain_local = domain.to_owned();
|
||||
|
||||
let stream = TcpStream::connect(&self.0).and_then(move |sock| {
|
||||
sock.set_nodelay(true).unwrap();
|
||||
tls_connector.connect(domain_local.as_ref(), sock)
|
||||
})
|
||||
.map(move |tcp| tcp);
|
||||
|
||||
Box::new(stream)
|
||||
}
|
||||
}
|
||||
|
||||
// Same implementation but without TLS. Should make it straightforward to run without TLS
|
||||
// when testing on local machine
|
||||
|
||||
// impl tower_service::Service<()> for Dst {
|
||||
// type Response = TcpStream;
|
||||
// type Error = ::std::io::Error;
|
||||
// type Future = Box<dyn Future<Item = TcpStream, Error = ::std::io::Error> + Send>;
|
||||
|
||||
// fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
|
||||
// Ok(().into())
|
||||
// }
|
||||
|
||||
// fn call(&mut self, _: ()) -> Self::Future {
|
||||
// let mut config = ClientConfig::new();
|
||||
// config.alpn_protocols.push(b"h2".to_vec());
|
||||
// config.root_store.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
|
||||
|
||||
// let addr_string_local = "mydomain.com".to_string();
|
||||
// let addr = addr_string_local.as_str();
|
||||
|
||||
// let stream = TcpStream::connect(&self.0)
|
||||
// .and_then(move |sock| {
|
||||
// sock.set_nodelay(true).unwrap();
|
||||
// Ok(sock)
|
||||
// });
|
||||
// Box::new(stream)
|
||||
// }
|
||||
// }
|
||||
|
||||
|
||||
fn connect() {
|
||||
let keepalive = future::loop_fn((), move |_| {
|
||||
let uri: http::Uri = "https://mydomain.com".parse().unwrap();
|
||||
println!("Connecting to network at: {:?}", uri);
|
||||
|
||||
let addr = "https://mydomain.com:443"
|
||||
.to_socket_addrs()
|
||||
.unwrap()
|
||||
.next()
|
||||
.unwrap();
|
||||
|
||||
let h2_settings = Default::default();
|
||||
let mut make_client = tower_h2::client::Connect::new(Dst {0: addr}, h2_settings, DefaultExecutor::current());
|
||||
|
||||
make_client
|
||||
.make_service(())
|
||||
.map_err(|e| {
|
||||
eprintln!("HTTP/2 connection failed; err={:?}", e);
|
||||
})
|
||||
.and_then(move |conn| {
|
||||
let conn = tower_request_modifier::Builder::new()
|
||||
.set_origin(uri)
|
||||
.build(conn)
|
||||
.unwrap();
|
||||
|
||||
MyGrpcService::new(conn)
|
||||
// Wait until the client is ready...
|
||||
.ready()
|
||||
.map_err(|e| eprintln!("client closed: {:?}", e))
|
||||
})
|
||||
.and_then(move |mut client| {
|
||||
// do stuff
|
||||
})
|
||||
.then(|e| {
|
||||
eprintln!("Reopening client connection to network: {:?}", e);
|
||||
let retry_sleep = std::time::Duration::from_secs(1);
|
||||
|
||||
thread::sleep(retry_sleep);
|
||||
Ok(future::Loop::Continue(()))
|
||||
})
|
||||
});
|
||||
|
||||
thread::spawn(move || tokio::run(keepalive));
|
||||
}
|
||||
|
||||
pub fn main() {
|
||||
connect();
|
||||
}
|
||||
|
||||
*/
|
||||
1318
src/lightwallet.rs
Normal file
1318
src/lightwallet.rs
Normal file
File diff suppressed because it is too large
Load Diff
126
src/main.rs
Normal file
126
src/main.rs
Normal file
@@ -0,0 +1,126 @@
|
||||
mod lightclient;
|
||||
mod lightwallet;
|
||||
mod address;
|
||||
mod prover;
|
||||
mod commands;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use lightclient::LightClient;
|
||||
|
||||
use rustyline::error::ReadlineError;
|
||||
use rustyline::Editor;
|
||||
|
||||
pub mod grpc_client {
|
||||
include!(concat!(env!("OUT_DIR"), "/cash.z.wallet.sdk.rpc.rs"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
pub fn main() {
|
||||
use clap::{Arg, App};
|
||||
|
||||
let matches = App::new("Light Client")
|
||||
.version("1.0")
|
||||
.arg(Arg::with_name("seed")
|
||||
.short("s")
|
||||
.long("seed")
|
||||
.value_name("seed_phrase")
|
||||
.help("Create a new wallet with the given 24-word seed phrase. Will fail if wallet already exists")
|
||||
.takes_value(true))
|
||||
.get_matches();
|
||||
|
||||
let seed: Option<String> = matches.value_of("seed").map(|s| s.to_string());
|
||||
|
||||
println!("Creating Light Wallet");
|
||||
|
||||
let lightclient = match LightClient::new(seed) {
|
||||
Ok(lc) => Arc::new(lc),
|
||||
Err(e) => { eprintln!("Failed to start wallet. Error was:\n{}", e); return; }
|
||||
};
|
||||
|
||||
// At startup, run a sync
|
||||
let sync_update = lightclient.do_sync();
|
||||
println!("{}", sync_update);
|
||||
|
||||
let (command_tx, command_rx) = std::sync::mpsc::channel::<(String, Vec<String>)>();
|
||||
let (resp_tx, resp_rx) = std::sync::mpsc::channel::<String>();
|
||||
|
||||
let lc = lightclient.clone();
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
match command_rx.recv_timeout(Duration::from_secs(5 * 60)) {
|
||||
Ok((cmd, args)) => {
|
||||
let args = args.iter().map(|s| s.as_ref()).collect();
|
||||
let cmd_response = commands::do_user_command(&cmd, &args, &lc);
|
||||
resp_tx.send(cmd_response).unwrap();
|
||||
|
||||
if cmd == "quit" {
|
||||
break;
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
// Timeout. Do a sync to keep the wallet up-to-date
|
||||
lc.do_sync();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// `()` 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()));
|
||||
match readline {
|
||||
Ok(line) => {
|
||||
rl.add_history_entry(line.as_str());
|
||||
// Parse command line arguments
|
||||
let mut cmd_args = match shellwords::split(&line) {
|
||||
Ok(args) => args,
|
||||
Err(_) => {
|
||||
println!("Mismatched Quotes");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
if cmd_args.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let cmd = cmd_args.remove(0);
|
||||
let args: Vec<String> = cmd_args;
|
||||
command_tx.send((cmd, args)).unwrap();
|
||||
|
||||
// Wait for the response
|
||||
match resp_rx.recv() {
|
||||
Ok(response) => println!("{}", response),
|
||||
_ => { eprintln!("Error receiveing response");}
|
||||
}
|
||||
|
||||
// Special check for Quit command.
|
||||
if line == "quit" {
|
||||
break;
|
||||
}
|
||||
},
|
||||
Err(ReadlineError::Interrupted) => {
|
||||
println!("CTRL-C");
|
||||
println!("{}", lightclient.do_save());
|
||||
break
|
||||
},
|
||||
Err(ReadlineError::Eof) => {
|
||||
println!("CTRL-D");
|
||||
println!("{}", lightclient.do_save());
|
||||
break
|
||||
},
|
||||
Err(err) => {
|
||||
println!("Error: {:?}", err);
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
rl.save_history("history.txt").unwrap();
|
||||
}
|
||||
123
src/prover.rs
Normal file
123
src/prover.rs
Normal file
@@ -0,0 +1,123 @@
|
||||
//! Abstractions over the proving system and parameters for ease of use.
|
||||
|
||||
use bellman::groth16::{prepare_verifying_key, Parameters, PreparedVerifyingKey};
|
||||
use pairing::bls12_381::{Bls12, Fr};
|
||||
use zcash_primitives::{
|
||||
jubjub::{edwards, fs::Fs, Unknown},
|
||||
primitives::{Diversifier, PaymentAddress, ProofGenerationKey},
|
||||
redjubjub::{PublicKey, Signature},
|
||||
transaction::components::Amount
|
||||
};
|
||||
use zcash_primitives::{
|
||||
merkle_tree::CommitmentTreeWitness, prover::TxProver, sapling::Node,
|
||||
transaction::components::GROTH_PROOF_SIZE, JUBJUB,
|
||||
};
|
||||
use zcash_proofs::sapling::SaplingProvingContext;
|
||||
|
||||
/// An implementation of [`TxProver`] using Sapling Spend and Output parameters provided
|
||||
/// in-memory.
|
||||
pub struct InMemTxProver {
|
||||
spend_params: Parameters<Bls12>,
|
||||
spend_vk: PreparedVerifyingKey<Bls12>,
|
||||
output_params: Parameters<Bls12>,
|
||||
}
|
||||
|
||||
impl InMemTxProver {
|
||||
pub fn new(spend_params: &[u8], output_params: &[u8]) -> Self {
|
||||
// Deserialize params
|
||||
let spend_params = Parameters::<Bls12>::read(spend_params, false)
|
||||
.expect("couldn't deserialize Sapling spend parameters file");
|
||||
let output_params = Parameters::<Bls12>::read(output_params, false)
|
||||
.expect("couldn't deserialize Sapling spend parameters file");
|
||||
|
||||
// Prepare verifying keys
|
||||
let spend_vk = prepare_verifying_key(&spend_params.vk);
|
||||
|
||||
InMemTxProver {
|
||||
spend_params,
|
||||
spend_vk,
|
||||
output_params,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TxProver for InMemTxProver {
|
||||
type SaplingProvingContext = SaplingProvingContext;
|
||||
|
||||
fn new_sapling_proving_context(&self) -> Self::SaplingProvingContext {
|
||||
SaplingProvingContext::new()
|
||||
}
|
||||
|
||||
fn spend_proof(
|
||||
&self,
|
||||
ctx: &mut Self::SaplingProvingContext,
|
||||
proof_generation_key: ProofGenerationKey<Bls12>,
|
||||
diversifier: Diversifier,
|
||||
rcm: Fs,
|
||||
ar: Fs,
|
||||
value: u64,
|
||||
anchor: Fr,
|
||||
witness: CommitmentTreeWitness<Node>,
|
||||
) -> Result<
|
||||
(
|
||||
[u8; GROTH_PROOF_SIZE],
|
||||
edwards::Point<Bls12, Unknown>,
|
||||
PublicKey<Bls12>,
|
||||
),
|
||||
(),
|
||||
> {
|
||||
let (proof, cv, rk) = ctx.spend_proof(
|
||||
proof_generation_key,
|
||||
diversifier,
|
||||
rcm,
|
||||
ar,
|
||||
value,
|
||||
anchor,
|
||||
witness,
|
||||
&self.spend_params,
|
||||
&self.spend_vk,
|
||||
&JUBJUB,
|
||||
)?;
|
||||
|
||||
let mut zkproof = [0u8; GROTH_PROOF_SIZE];
|
||||
proof
|
||||
.write(&mut zkproof[..])
|
||||
.expect("should be able to serialize a proof");
|
||||
|
||||
Ok((zkproof, cv, rk))
|
||||
}
|
||||
|
||||
fn output_proof(
|
||||
&self,
|
||||
ctx: &mut Self::SaplingProvingContext,
|
||||
esk: Fs,
|
||||
payment_address: PaymentAddress<Bls12>,
|
||||
rcm: Fs,
|
||||
value: u64,
|
||||
) -> ([u8; GROTH_PROOF_SIZE], edwards::Point<Bls12, Unknown>) {
|
||||
let (proof, cv) = ctx.output_proof(
|
||||
esk,
|
||||
payment_address,
|
||||
rcm,
|
||||
value,
|
||||
&self.output_params,
|
||||
&JUBJUB,
|
||||
);
|
||||
|
||||
let mut zkproof = [0u8; GROTH_PROOF_SIZE];
|
||||
proof
|
||||
.write(&mut zkproof[..])
|
||||
.expect("should be able to serialize a proof");
|
||||
|
||||
(zkproof, cv)
|
||||
}
|
||||
|
||||
fn binding_sig(
|
||||
&self,
|
||||
ctx: &mut Self::SaplingProvingContext,
|
||||
value_balance: Amount,
|
||||
sighash: &[u8; 32],
|
||||
) -> Result<Signature, ()> {
|
||||
ctx.binding_sig(value_balance, sighash, &JUBJUB)
|
||||
}
|
||||
}
|
||||
10
src/utils.rs
Normal file
10
src/utils.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
pub fn set_panic_hook() {
|
||||
// When the `console_error_panic_hook` feature is enabled, we can call the
|
||||
// `set_panic_hook` function at least once during initialization, and then
|
||||
// we will get better error messages if our code ever panics.
|
||||
//
|
||||
// For more details see
|
||||
// https://github.com/rustwasm/console_error_panic_hook#readme
|
||||
#[cfg(feature = "console_error_panic_hook")]
|
||||
console_error_panic_hook::set_once();
|
||||
}
|
||||
Reference in New Issue
Block a user