Contractless/src/bin/lookup_difficulty.rs

68 lines
2.3 KiB
Rust

use blockchain::common::cli_prompts::{prompt_hidden_nonempty, prompt_wallet_path};
use blockchain::common::network_startup::get_connections;
use blockchain::env;
use blockchain::records::memory::response_channels::generate_uid;
use blockchain::standalone_tools::connections::handshake;
#[tokio::main]
async fn main() {
// Command 5 asks a peer for the current network difficulty.
let hashmap_key = generate_uid();
let _args: Vec<String> = env::args().collect();
let wallet_path = prompt_wallet_path().await;
let encryption_key = prompt_hidden_nonempty(
"What is your wallet decryption key? ",
"Wallet key cannot be empty. Please try again.",
)
.await;
let rpc_command = 5;
let json = "".to_string();
// Try each configured peer until one returns difficulty or text error.
let connections = get_connections().await;
let mut connected: bool = false;
for conn in connections {
if connected {
break;
}
let socket_address = conn.parse().expect("Failed to parse the socket address");
let result = handshake::connect_and_handshake(
socket_address,
json.clone(),
rpc_command,
handshake::HandshakeWallet::WalletKey {
encryption_key: encryption_key.clone(),
wallet_path: wallet_path.clone(),
},
hashmap_key,
)
.await;
match result {
Ok(response) => {
// The difficulty reply carries 4 bytes of header plus an 8-byte u64 difficulty.
if response.len() == 12 {
let difficulty = u64::from_le_bytes(response[4..12].try_into().unwrap());
println!("{difficulty}");
connected = true;
} else {
let response_text = String::from_utf8_lossy(&response);
let trimmed = response_text.trim();
if !trimmed.is_empty() {
println!("{trimmed}");
connected = true;
}
}
}
Err(_) => {
connected = false;
}
}
}
if !connected {
eprintln!("failed to connect");
}
}