Add syncstatus command

This commit is contained in:
Aditya Kulkarni 2019-10-24 18:26:25 -07:00
parent 17bbb71a69
commit 865a72442d
3 changed files with 66 additions and 43 deletions

View File

@ -221,7 +221,12 @@ fn startup(server: http::Uri, dangerous: bool, seed: Option<String>, birthday: u
if first_sync { if first_sync {
let update = lightclient.do_sync(true); let update = lightclient.do_sync(true);
if print_updates { if print_updates {
println!("{}", update); match update {
Ok(j) => {
println!("{}", j.pretty(2));
},
Err(e) => println!("{}", e)
}
} }
} }
@ -329,7 +334,11 @@ fn command_loop(lightclient: Arc<LightClient>) -> (Sender<(String, Vec<String>)>
Err(_) => { Err(_) => {
// Timeout. Do a sync to keep the wallet up-to-date. False to whether to print updates on the console // Timeout. Do a sync to keep the wallet up-to-date. False to whether to print updates on the console
info!("Timeout, doing a sync"); info!("Timeout, doing a sync");
lc.do_sync(false); match lc.do_sync(false) {
Ok(_) => {},
Err(e) => {error!("{}", e)}
}
} }
} }
} }

View File

@ -28,7 +28,10 @@ impl Command for SyncCommand {
} }
fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String { fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String {
lightclient.do_sync(true) match lightclient.do_sync(true) {
Ok(j) => j.pretty(2),
Err(e) => e
}
} }
} }
@ -79,7 +82,10 @@ impl Command for RescanCommand {
} }
fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String { fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String {
lightclient.do_rescan() match lightclient.do_rescan() {
Ok(j) => j.pretty(2),
Err(e) => e
}
} }
} }
@ -145,8 +151,6 @@ impl Command for InfoCommand {
} }
fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String { fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String {
lightclient.do_sync(true);
lightclient.do_info() lightclient.do_info()
} }
} }
@ -169,9 +173,10 @@ impl Command for BalanceCommand {
} }
fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String { fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String {
lightclient.do_sync(true); match lightclient.do_sync(true) {
Ok(_) => format!("{}", lightclient.do_balance().pretty(2)),
format!("{}", lightclient.do_balance().pretty(2)) Err(e) => e
}
} }
} }
@ -434,7 +439,7 @@ impl Command for SendCommand {
} }
// Check for a single argument that can be parsed as JSON // Check for a single argument that can be parsed as JSON
if args.len() == 1 { let send_args = if args.len() == 1 {
// Sometimes on the command line, people use "'" for the quotes, which json::parse doesn't // Sometimes on the command line, people use "'" for the quotes, which json::parse doesn't
// understand. So replace it with double-quotes // understand. So replace it with double-quotes
let arg_list = args[0].replace("'", "\""); let arg_list = args[0].replace("'", "\"");
@ -455,20 +460,14 @@ impl Command for SendCommand {
if !j.has_key("address") || !j.has_key("amount") { if !j.has_key("address") || !j.has_key("amount") {
Err(format!("Need 'address' and 'amount'\n")) Err(format!("Need 'address' and 'amount'\n"))
} else { } else {
Ok((j["address"].as_str().unwrap(), j["amount"].as_u64().unwrap(), j["memo"].as_str().map(|s| s.to_string()))) Ok((j["address"].as_str().unwrap().to_string().clone(), j["amount"].as_u64().unwrap(), j["memo"].as_str().map(|s| s.to_string().clone())))
} }
}).collect::<Result<Vec<(&str, u64, Option<String>)>, String>>(); }).collect::<Result<Vec<(String, u64, Option<String>)>, String>>();
let send_args = match maybe_send_args { match maybe_send_args {
Ok(a) => a, Ok(a) => a.clone(),
Err(s) => { return format!("Error: {}\n{}", s, self.help()); } Err(s) => { return format!("Error: {}\n{}", s, self.help()); }
}; }
lightclient.do_sync(true);
match lightclient.do_send(send_args) {
Ok(txid) => { object!{ "txid" => txid } },
Err(e) => { object!{ "error" => e } }
}.pretty(2)
} else if args.len() == 2 || args.len() == 3 { } else if args.len() == 2 || args.len() == 3 {
// Make sure we can parse the amount // Make sure we can parse the amount
let value = match args[1].parse::<u64>() { let value = match args[1].parse::<u64>() {
@ -480,13 +479,21 @@ impl Command for SendCommand {
let memo = if args.len() == 3 { Some(args[2].to_string()) } else {None}; let memo = if args.len() == 3 { Some(args[2].to_string()) } else {None};
lightclient.do_sync(true); vec![(args[0].to_string(), value, memo)]
match lightclient.do_send(vec!((args[0], value, memo))) { } else {
return self.help()
};
match lightclient.do_sync(true) {
Ok(_) => {
// Convert to the right format. String -> &str.
let tos = send_args.iter().map(|(a, v, m)| (a.as_str(), *v, m.clone()) ).collect::<Vec<_>>();
match lightclient.do_send(tos) {
Ok(txid) => { object!{ "txid" => txid } }, Ok(txid) => { object!{ "txid" => txid } },
Err(e) => { object!{ "error" => e } } Err(e) => { object!{ "error" => e } }
}.pretty(2) }.pretty(2)
} else { },
self.help() Err(e) => e
} }
} }
} }
@ -568,9 +575,12 @@ impl Command for TransactionsCommand {
} }
fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String { fn exec(&self, _args: &[&str], lightclient: &LightClient) -> String {
lightclient.do_sync(true); match lightclient.do_sync(true) {
Ok(_) => {
format!("{}", lightclient.do_list_transactions().pretty(2)) format!("{}", lightclient.do_list_transactions().pretty(2))
},
Err(e) => e
}
} }
} }
@ -662,9 +672,12 @@ impl Command for NotesCommand {
false false
}; };
lightclient.do_sync(true); match lightclient.do_sync(true) {
Ok(_) => {
format!("{}", lightclient.do_list_notes(all_notes).pretty(2)) format!("{}", lightclient.do_list_notes(all_notes).pretty(2))
},
Err(e) => e
}
} }
} }

View File

@ -741,7 +741,7 @@ impl LightClient {
Ok(array![new_address]) Ok(array![new_address])
} }
pub fn do_rescan(&self) -> String { pub fn do_rescan(&self) -> Result<JsonValue, String> {
info!("Rescan starting"); info!("Rescan starting");
// First, clear the state from the wallet // First, clear the state from the wallet
self.wallet.read().unwrap().clear_blocks(); self.wallet.read().unwrap().clear_blocks();
@ -761,7 +761,7 @@ impl LightClient {
self.sync_status.read().unwrap().clone() self.sync_status.read().unwrap().clone()
} }
pub fn do_sync(&self, print_updates: bool) -> String { pub fn do_sync(&self, print_updates: bool) -> Result<JsonValue, String> {
// We can only do one sync at a time because we sync blocks in serial order // We can only do one sync at a time because we sync blocks in serial order
// If we allow multiple syncs, they'll all get jumbled up. // If we allow multiple syncs, they'll all get jumbled up.
let _lock = self.sync_lock.lock().unwrap(); let _lock = self.sync_lock.lock().unwrap();
@ -786,7 +786,7 @@ impl LightClient {
if latest_block < last_scanned_height { if latest_block < last_scanned_height {
let w = format!("Server's latest block({}) is behind ours({})", latest_block, last_scanned_height); let w = format!("Server's latest block({}) is behind ours({})", latest_block, last_scanned_height);
warn!("{}", w); warn!("{}", w);
return w; return Err(w);
} }
info!("Latest block is {}", latest_block); info!("Latest block is {}", latest_block);
@ -797,7 +797,7 @@ impl LightClient {
// If there's nothing to scan, just return // If there's nothing to scan, just return
if last_scanned_height == latest_block { if last_scanned_height == latest_block {
info!("Nothing to sync, returning"); info!("Nothing to sync, returning");
return "".to_string(); return Ok(object!{ "result" => "success" })
} }
{ {
@ -893,7 +893,7 @@ impl LightClient {
// Make sure we're not re-orging too much! // Make sure we're not re-orging too much!
if total_reorg > (crate::lightwallet::MAX_REORG - 1) as u64 { if total_reorg > (crate::lightwallet::MAX_REORG - 1) as u64 {
error!("Reorg has now exceeded {} blocks!", crate::lightwallet::MAX_REORG); error!("Reorg has now exceeded {} blocks!", crate::lightwallet::MAX_REORG);
return format!("Reorg has exceeded {} blocks. Aborting.", crate::lightwallet::MAX_REORG); return Err(format!("Reorg has exceeded {} blocks. Aborting.", crate::lightwallet::MAX_REORG));
} }
if invalid_height > 0 { if invalid_height > 0 {
@ -947,10 +947,7 @@ impl LightClient {
println!(""); // New line to finish up the updates println!(""); // New line to finish up the updates
} }
let mut responses = vec![];
info!("Synced to {}, Downloaded {} kB", latest_block, bytes_downloaded.load(Ordering::SeqCst) / 1024); info!("Synced to {}, Downloaded {} kB", latest_block, bytes_downloaded.load(Ordering::SeqCst) / 1024);
responses.push(format!("Synced to {}, Downloaded {} kB", latest_block, bytes_downloaded.load(Ordering::SeqCst) / 1024));
{ {
let mut status = self.sync_status.write().unwrap(); let mut status = self.sync_status.write().unwrap();
status.is_syncing = false; status.is_syncing = false;
@ -988,7 +985,11 @@ impl LightClient {
}); });
}; };
responses.join("\n") Ok(object!{
"result" => "success",
"latest_block" => latest_block,
"downloaded_bytes" => bytes_downloaded.load(Ordering::SeqCst)
})
} }
pub fn do_send(&self, addrs: Vec<(&str, u64, Option<String>)>) -> Result<String, String> { pub fn do_send(&self, addrs: Vec<(&str, u64, Option<String>)>) -> Result<String, String> {