Move thin_client RPC requests into rpc_request; de-mut thin_client

This commit is contained in:
Michael Vines
2019-03-16 08:31:19 -07:00
parent bcc34b906c
commit 4b04bc8612
10 changed files with 285 additions and 275 deletions

@@ -1,15 +1,19 @@
use bs58;
use log::*;
use reqwest;
use reqwest::header::CONTENT_TYPE;
use serde_json::{json, Value};
use solana_sdk::account::Account;
use solana_sdk::hash::Hash;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::signature::Signature;
use solana_sdk::timing::{DEFAULT_TICKS_PER_SLOT, NUM_TICKS_PER_SECOND};
use std::io;
use std::net::SocketAddr;
use std::thread::sleep;
use std::time::Duration;
use std::time::{Duration, Instant};
use std::{error, fmt};
use solana_sdk::pubkey::Pubkey;
#[derive(Clone)]
pub struct RpcClient {
pub client: reqwest::Client,
@@ -49,6 +53,202 @@ impl RpcClient {
Ok(res)
}
pub fn get_account_data(&self, pubkey: &Pubkey) -> io::Result<Option<Vec<u8>>> {
let params = json!([format!("{}", pubkey)]);
let response = self.make_rpc_request(RpcRequest::GetAccountInfo, Some(params));
match response {
Ok(account_json) => {
let account: Account =
serde_json::from_value(account_json).expect("deserialize account");
Ok(Some(account.data))
}
Err(error) => {
debug!("get_account_data failed: {:?}", error);
Err(io::Error::new(
io::ErrorKind::Other,
"get_account_data failed",
))
}
}
}
/// Request the balance of the user holding `pubkey`. This method blocks
/// until the server sends a response. If the response packet is dropped
/// by the network, this method will hang indefinitely.
pub fn get_balance(&self, pubkey: &Pubkey) -> io::Result<u64> {
let params = json!([format!("{}", pubkey)]);
let response = self.make_rpc_request(RpcRequest::GetAccountInfo, Some(params));
response
.and_then(|account_json| {
let account: Account =
serde_json::from_value(account_json).expect("deserialize account");
trace!("Response account {:?} {:?}", pubkey, account);
trace!("get_balance {:?}", account.lamports);
Ok(account.lamports)
})
.map_err(|error| {
debug!("Response account {}: None (error: {:?})", pubkey, error);
io::Error::new(io::ErrorKind::Other, "AccountNotFound")
})
}
/// Request the transaction count. If the response packet is dropped by the network,
/// this method will try again 5 times.
pub fn transaction_count(&self) -> u64 {
debug!("transaction_count");
for _tries in 0..5 {
let response = self.make_rpc_request(RpcRequest::GetTransactionCount, None);
match response {
Ok(value) => {
debug!("transaction_count response: {:?}", value);
let transaction_count = value.as_u64().unwrap();
return transaction_count;
}
Err(error) => {
debug!("transaction_count failed: {:?}", error);
}
};
}
0
}
/// Request the last Entry ID from the server without blocking.
/// Returns the blockhash Hash or None if there was no response from the server.
pub fn try_get_recent_blockhash(&self, mut num_retries: u64) -> Option<Hash> {
loop {
let response = self.make_rpc_request(RpcRequest::GetRecentBlockhash, None);
match response {
Ok(value) => {
let blockhash_str = value.as_str().unwrap();
let blockhash_vec = bs58::decode(blockhash_str).into_vec().unwrap();
return Some(Hash::new(&blockhash_vec));
}
Err(error) => {
debug!("thin_client get_recent_blockhash error: {:?}", error);
num_retries -= 1;
if num_retries == 0 {
return None;
}
}
}
}
}
/// Request the last Entry ID from the server. This method blocks
/// until the server sends a response.
pub fn get_recent_blockhash(&self) -> Hash {
loop {
if let Some(hash) = self.try_get_recent_blockhash(10) {
return hash;
}
}
}
/// Request a new last Entry ID from the server. This method blocks
/// until the server sends a response.
pub fn get_next_blockhash(&self, previous_blockhash: &Hash) -> Hash {
self.get_next_blockhash_ext(previous_blockhash, &|| {
sleep(Duration::from_millis(100));
})
}
fn get_next_blockhash_ext(&self, previous_blockhash: &Hash, func: &Fn()) -> Hash {
loop {
let blockhash = self.get_recent_blockhash();
if blockhash != *previous_blockhash {
break blockhash;
}
debug!("Got same blockhash ({:?}), will retry...", blockhash);
func()
}
}
pub fn poll_balance_with_timeout(
&self,
pubkey: &Pubkey,
polling_frequency: &Duration,
timeout: &Duration,
) -> io::Result<u64> {
let now = Instant::now();
loop {
match self.get_balance(&pubkey) {
Ok(bal) => {
return Ok(bal);
}
Err(e) => {
sleep(*polling_frequency);
if now.elapsed() > *timeout {
return Err(e);
}
}
};
}
}
pub fn poll_get_balance(&self, pubkey: &Pubkey) -> io::Result<u64> {
self.poll_balance_with_timeout(pubkey, &Duration::from_millis(100), &Duration::from_secs(1))
}
/// Poll the server to confirm a transaction.
pub fn poll_for_signature(&self, signature: &Signature) -> io::Result<()> {
let now = Instant::now();
while !self.check_signature(signature) {
if now.elapsed().as_secs() > 15 {
// TODO: Return a better error.
return Err(io::Error::new(io::ErrorKind::Other, "signature not found"));
}
sleep(Duration::from_millis(250));
}
Ok(())
}
/// Check a signature in the bank. This method blocks
/// until the server sends a response.
pub fn check_signature(&self, signature: &Signature) -> bool {
trace!("check_signature: {:?}", signature);
let params = json!([format!("{}", signature)]);
loop {
let response =
self.make_rpc_request(RpcRequest::ConfirmTransaction, Some(params.clone()));
match response {
Ok(confirmation) => {
let signature_status = confirmation.as_bool().unwrap();
if signature_status {
trace!("Response found signature");
} else {
trace!("Response signature not found");
}
return signature_status;
}
Err(err) => {
debug!("check_signature request failed: {:?}", err);
}
};
}
}
pub fn fullnode_exit(&self) -> io::Result<bool> {
let response = self
.make_rpc_request(RpcRequest::FullnodeExit, None)
.map_err(|err| {
io::Error::new(
io::ErrorKind::Other,
format!("FullnodeExit request failure: {:?}", err),
)
})?;
serde_json::from_value(response).map_err(|err| {
io::Error::new(
io::ErrorKind::Other,
format!("FullnodeExit parse failure: {:?}", err),
)
})
}
pub fn retry_make_rpc_request(
&self,
request: &RpcRequest,