Files
solana/src/thin_client.rs

662 lines
23 KiB
Rust
Raw Normal View History

//! The `thin_client` module is a client-side object that interfaces with
//! a server-side TPU. Client code should use this object instead of writing
//! messages to the network directly. The binary encoding of its messages are
//! unstable and may change in future releases.
2018-02-28 14:16:50 -07:00
2018-12-07 20:16:27 -07:00
use crate::bank::Bank;
use crate::cluster_info::{ClusterInfo, ClusterInfoError, NodeInfo};
use crate::fullnode::{Fullnode, FullnodeConfig};
2018-12-07 20:16:27 -07:00
use crate::gossip_service::GossipService;
use crate::packet::PACKET_DATA_SIZE;
use crate::result::{Error, Result};
use crate::rpc_request::{RpcClient, RpcRequest, RpcRequestHandler};
use bincode::serialize_into;
2018-11-05 10:50:58 -07:00
use bs58;
use hashbrown::HashMap;
use log::Level;
2018-11-05 10:50:58 -07:00
use serde_json;
2018-11-16 08:45:59 -08:00
use solana_metrics;
use solana_metrics::influxdb;
use solana_sdk::account::Account;
2018-11-16 08:04:46 -08:00
use solana_sdk::hash::Hash;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::signature::{Keypair, KeypairUtil, Signature};
2018-12-04 20:19:48 -08:00
use solana_sdk::system_transaction::SystemTransaction;
2018-11-16 08:45:59 -08:00
use solana_sdk::timing;
2018-11-29 16:18:47 -08:00
use solana_sdk::transaction::Transaction;
use std;
use std::io;
2018-04-28 00:31:20 -07:00
use std::net::{SocketAddr, UdpSocket};
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, RwLock};
use std::thread::sleep;
use std::time::Duration;
2018-07-05 21:40:09 -07:00
use std::time::Instant;
2018-02-28 14:16:50 -07:00
2018-06-07 14:51:29 -06:00
/// An object for querying and sending transactions to the network.
pub struct ThinClient {
2018-11-05 10:50:58 -07:00
rpc_addr: SocketAddr,
2018-05-25 15:51:41 -06:00
transactions_addr: SocketAddr,
transactions_socket: UdpSocket,
transaction_count: u64,
balances: HashMap<Pubkey, Account>,
2018-06-28 18:59:02 -06:00
signature_status: bool,
confirmation: Option<usize>,
rpc_client: RpcClient,
2018-02-28 14:16:50 -07:00
}
impl ThinClient {
2018-11-05 10:50:58 -07:00
/// Create a new ThinClient that will interface with the Rpc at `rpc_addr` using TCP
/// and the Tpu at `transactions_addr` over `transactions_socket` using UDP.
pub fn new(
2018-11-05 10:50:58 -07:00
rpc_addr: SocketAddr,
2018-05-25 15:51:41 -06:00
transactions_addr: SocketAddr,
transactions_socket: UdpSocket,
) -> Self {
Self::new_from_client(
rpc_addr,
transactions_addr,
transactions_socket,
RpcClient::new_from_socket(rpc_addr),
)
}
pub fn new_with_timeout(
rpc_addr: SocketAddr,
transactions_addr: SocketAddr,
transactions_socket: UdpSocket,
timeout: Duration,
) -> Self {
let rpc_client = RpcClient::new_with_timeout(rpc_addr, timeout);
Self::new_from_client(rpc_addr, transactions_addr, transactions_socket, rpc_client)
}
fn new_from_client(
rpc_addr: SocketAddr,
transactions_addr: SocketAddr,
transactions_socket: UdpSocket,
rpc_client: RpcClient,
) -> Self {
2018-07-11 14:40:46 -06:00
ThinClient {
rpc_client,
2018-11-05 10:50:58 -07:00
rpc_addr,
2018-05-25 15:51:41 -06:00
transactions_addr,
transactions_socket,
transaction_count: 0,
balances: HashMap::new(),
2018-06-28 18:59:02 -06:00
signature_status: false,
confirmation: None,
2018-07-11 14:40:46 -06:00
}
}
2018-03-29 12:20:54 -06:00
/// Send a signed Transaction to the server for processing. This method
/// does not wait for a response.
pub fn transfer_signed(&self, tx: &Transaction) -> io::Result<Signature> {
let mut buf = vec![0; tx.serialized_size().unwrap() as usize];
let mut wr = std::io::Cursor::new(&mut buf[..]);
serialize_into(&mut wr, &tx).expect("serialize Transaction in pub fn transfer_signed");
assert!(buf.len() < PACKET_DATA_SIZE);
2018-05-25 15:51:41 -06:00
self.transactions_socket
.send_to(&buf[..], &self.transactions_addr)?;
Ok(tx.signatures[0])
2018-02-28 14:16:50 -07:00
}
2018-08-26 15:58:22 -07:00
/// Retry a sending a signed Transaction to the server for processing.
pub fn retry_transfer(
2018-08-26 15:58:22 -07:00
&mut self,
keypair: &Keypair,
tx: &mut Transaction,
2018-08-26 15:58:22 -07:00
tries: usize,
) -> io::Result<Signature> {
for x in 0..tries {
tx.sign(&[keypair], self.get_last_id());
let mut buf = vec![0; tx.serialized_size().unwrap() as usize];
let mut wr = std::io::Cursor::new(&mut buf[..]);
serialize_into(&mut wr, &tx).expect("serialize Transaction in pub fn transfer_signed");
2018-08-26 15:58:22 -07:00
self.transactions_socket
.send_to(&buf[..], &self.transactions_addr)?;
if self.poll_for_signature(&tx.signatures[0]).is_ok() {
return Ok(tx.signatures[0]);
2018-08-26 15:58:22 -07:00
}
info!("{} tries failed transfer to {}", x, self.transactions_addr);
}
Err(io::Error::new(
io::ErrorKind::Other,
"retry_transfer failed",
2018-08-26 15:58:22 -07:00
))
}
2018-03-29 12:20:54 -06:00
/// Creates, signs, and processes a Transaction. Useful for writing unit-tests.
2018-02-28 14:16:50 -07:00
pub fn transfer(
2018-03-05 11:11:00 -07:00
&self,
n: u64,
2018-08-09 08:56:04 -06:00
keypair: &Keypair,
to: Pubkey,
last_id: &Hash,
) -> io::Result<Signature> {
debug!(
"transfer: n={} from={:?} to={:?} last_id={:?}",
n,
keypair.pubkey(),
to,
last_id
);
2018-07-05 21:40:09 -07:00
let now = Instant::now();
let tx = SystemTransaction::new_account(keypair, to, n, *last_id, 0);
let result = self.transfer_signed(&tx);
2018-11-16 08:45:59 -08:00
solana_metrics::submit(
2018-07-05 21:40:09 -07:00
influxdb::Point::new("thinclient")
.add_tag("op", influxdb::Value::String("transfer".to_string()))
.add_field(
"duration_ms",
influxdb::Value::Integer(timing::duration_as_ms(&now.elapsed()) as i64),
)
.to_owned(),
2018-07-05 21:40:09 -07:00
);
result
2018-02-28 14:16:50 -07:00
}
pub fn get_account_userdata(&mut self, pubkey: &Pubkey) -> io::Result<Option<Vec<u8>>> {
let params = json!([format!("{}", pubkey)]);
let resp = self
.rpc_client
.make_rpc_request(1, RpcRequest::GetAccountInfo, Some(params));
2018-11-05 10:50:58 -07:00
if let Ok(account_json) = resp {
let account: Account =
serde_json::from_value(account_json).expect("deserialize account");
return Ok(Some(account.userdata));
}
2018-11-05 10:50:58 -07:00
Err(io::Error::new(
io::ErrorKind::Other,
"get_account_userdata failed",
))
}
2018-03-29 12:20:54 -06:00
/// 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(&mut self, pubkey: &Pubkey) -> io::Result<u64> {
2018-11-05 10:50:58 -07:00
trace!("get_balance sending request to {}", self.rpc_addr);
let params = json!([format!("{}", pubkey)]);
let resp = self
.rpc_client
.make_rpc_request(1, RpcRequest::GetAccountInfo, Some(params));
2018-11-05 10:50:58 -07:00
if let Ok(account_json) = resp {
let account: Account =
serde_json::from_value(account_json).expect("deserialize account");
trace!("Response account {:?} {:?}", pubkey, account);
self.balances.insert(*pubkey, account.clone());
} else {
debug!("Response account {}: None ", pubkey);
self.balances.remove(&pubkey);
2018-04-17 18:41:58 -04:00
}
trace!("get_balance {:?}", self.balances.get(pubkey));
2018-09-09 07:07:38 -07:00
// TODO: This is a hard coded call to introspect the balance of a budget_dsl contract
// In the future custom contracts would need their own introspection
self.balances
.get(pubkey)
.map(Bank::read_balance)
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "AccountNotFound"))
}
/// Request the confirmation time from the leader node
pub fn get_confirmation_time(&mut self) -> usize {
trace!("get_confirmation_time");
let mut done = false;
while !done {
debug!("get_confirmation_time send_to {}", &self.rpc_addr);
let resp = self
.rpc_client
.make_rpc_request(1, RpcRequest::GetConfirmationTime, None);
2018-11-05 10:50:58 -07:00
if let Ok(value) = resp {
done = true;
let confirmation = value.as_u64().unwrap() as usize;
self.confirmation = Some(confirmation);
2018-11-05 10:50:58 -07:00
} else {
debug!("thin_client get_confirmation_time error: {:?}", resp);
}
}
self.confirmation.expect("some confirmation")
}
/// Request the transaction count. If the response packet is dropped by the network,
/// this method will try again 5 times.
pub fn transaction_count(&mut self) -> u64 {
2018-07-22 16:20:07 -07:00
debug!("transaction_count");
let mut tries_left = 5;
while tries_left > 0 {
let resp = self
.rpc_client
.make_rpc_request(1, RpcRequest::GetTransactionCount, None);
2018-11-05 10:50:58 -07:00
if let Ok(value) = resp {
debug!("transaction_count recv_response: {:?}", value);
tries_left = 0;
let transaction_count = value.as_u64().unwrap();
self.transaction_count = transaction_count;
} else {
tries_left -= 1;
}
}
self.transaction_count
}
2018-04-02 09:30:10 -06:00
/// Request the last Entry ID from the server. This method blocks
/// until the server sends a response.
pub fn get_last_id(&mut self) -> Hash {
2019-02-07 15:08:41 -08:00
loop {
trace!("get_last_id send_to {}", &self.rpc_addr);
let resp = self
.rpc_client
.make_rpc_request(1, RpcRequest::GetLastId, None);
2018-11-05 10:50:58 -07:00
if let Ok(value) = resp {
let last_id_str = value.as_str().unwrap();
let last_id_vec = bs58::decode(last_id_str).into_vec().unwrap();
2019-02-07 15:08:41 -08:00
return Hash::new(&last_id_vec);
2018-11-05 10:50:58 -07:00
} else {
debug!("thin_client get_last_id error: {:?}", resp);
}
}
}
2018-02-28 14:16:50 -07:00
pub fn submit_poll_balance_metrics(elapsed: &Duration) {
2018-11-16 08:45:59 -08:00
solana_metrics::submit(
2018-07-05 21:40:09 -07:00
influxdb::Point::new("thinclient")
.add_tag("op", influxdb::Value::String("get_balance".to_string()))
.add_field(
"duration_ms",
influxdb::Value::Integer(timing::duration_as_ms(elapsed) as i64),
)
.to_owned(),
2018-07-05 21:40:09 -07:00
);
}
pub fn poll_balance_with_timeout(
&mut self,
pubkey: &Pubkey,
polling_frequency: &Duration,
timeout: &Duration,
) -> io::Result<u64> {
let now = Instant::now();
loop {
match self.get_balance(&pubkey) {
Ok(bal) => {
ThinClient::submit_poll_balance_metrics(&now.elapsed());
return Ok(bal);
}
Err(e) => {
sleep(*polling_frequency);
if now.elapsed() > *timeout {
ThinClient::submit_poll_balance_metrics(&now.elapsed());
return Err(e);
}
}
};
}
}
pub fn poll_get_balance(&mut self, pubkey: &Pubkey) -> io::Result<u64> {
self.poll_balance_with_timeout(pubkey, &Duration::from_millis(100), &Duration::from_secs(1))
}
2018-07-20 19:05:39 -04:00
/// Poll the server to confirm a transaction.
pub fn poll_for_signature(&mut self, signature: &Signature) -> io::Result<()> {
2018-07-20 19:05:39 -04:00
let now = Instant::now();
while !self.check_signature(signature) {
2018-07-20 19:05:39 -04:00
if now.elapsed().as_secs() > 1 {
// TODO: Return a better error.
return Err(io::Error::new(io::ErrorKind::Other, "signature not found"));
}
sleep(Duration::from_millis(100));
}
Ok(())
}
/// Check a signature in the bank. This method blocks
/// until the server sends a response.
pub fn check_signature(&mut self, signature: &Signature) -> bool {
trace!("check_signature");
let params = json!([format!("{}", signature)]);
2018-07-05 21:40:09 -07:00
let now = Instant::now();
let mut done = false;
while !done {
let resp = self.rpc_client.make_rpc_request(
2018-11-05 10:50:58 -07:00
1,
RpcRequest::ConfirmTransaction,
2018-11-05 10:50:58 -07:00
Some(params.clone()),
);
if let Ok(confirmation) = resp {
done = true;
self.signature_status = confirmation.as_bool().unwrap();
if self.signature_status {
trace!("Response found signature");
} else {
trace!("Response signature not found");
}
}
}
2018-11-16 08:45:59 -08:00
solana_metrics::submit(
2018-07-05 21:40:09 -07:00
influxdb::Point::new("thinclient")
.add_tag("op", influxdb::Value::String("check_signature".to_string()))
.add_field(
"duration_ms",
influxdb::Value::Integer(timing::duration_as_ms(&now.elapsed()) as i64),
)
.to_owned(),
2018-07-05 21:40:09 -07:00
);
self.signature_status
}
}
2018-07-05 21:40:09 -07:00
impl Drop for ThinClient {
fn drop(&mut self) {
2018-11-16 08:45:59 -08:00
solana_metrics::flush();
2018-07-05 21:40:09 -07:00
}
}
pub fn poll_gossip_for_leader(leader_gossip: SocketAddr, timeout: Option<u64>) -> Result<NodeInfo> {
let exit = Arc::new(AtomicBool::new(false));
2018-10-08 20:55:54 -06:00
let (node, gossip_socket) = ClusterInfo::spy_node();
let my_addr = gossip_socket.local_addr().unwrap();
let cluster_info = Arc::new(RwLock::new(ClusterInfo::new(node)));
let gossip_service =
GossipService::new(&cluster_info.clone(), None, gossip_socket, exit.clone());
let leader_entry_point = NodeInfo::new_entry_point(&leader_gossip);
cluster_info
.write()
.unwrap()
.insert_info(leader_entry_point);
sleep(Duration::from_millis(100));
let deadline = match timeout {
Some(timeout) => Duration::new(timeout, 0),
None => Duration::new(std::u64::MAX, 0),
};
let now = Instant::now();
// Block until leader's correct contact info is received
let leader;
loop {
trace!("polling {:?} for leader from {:?}", leader_gossip, my_addr);
Leader scheduler plumbing (#1440) * Added LeaderScheduler module and tests * plumbing for LeaderScheduler in Fullnode + tests. Add vote processing for active set to ReplicateStage and WriteStage * Add LeaderScheduler plumbing for Tvu, window, and tests * Fix bank and switch tests to use new LeaderScheduler * move leader rotation check from window service to replicate stage * Add replicate_stage leader rotation exit test * removed leader scheduler from the window service and associated modules/tests * Corrected is_leader calculation in repair() function in window.rs * Integrate LeaderScheduler with write_stage for leader to validator transitions * Integrated LeaderScheduler with BroadcastStage * Removed gossip leader rotation from crdt * Add multi validator, leader test * Comments and cleanup * Remove unneeded checks from broadcast stage * Fix case where a validator/leader need to immediately transition on startup after reading ledger and seeing they are not in the correct role * Set new leader in validator -> validator transitions * Clean up for PR comments, refactor LeaderScheduler from process_entry/process_ledger_tail * Cleaned out LeaderScheduler options, implemented LeaderScheduler strategy that only picks the bootstrap leader to support existing tests, drone/airdrops * Ignore test_full_leader_validator_network test due to bug where the next leader in line fails to get the last entry before rotation (b/c it hasn't started up yet). Added a test test_dropped_handoff_recovery go track this bug
2018-10-10 16:49:41 -07:00
if let Some(l) = cluster_info.read().unwrap().get_gossip_top_leader() {
leader = Some(l.clone());
break;
}
if log_enabled!(Level::Trace) {
2018-10-08 20:55:54 -06:00
trace!("{}", cluster_info.read().unwrap().node_info_trace());
}
if now.elapsed() > deadline {
2018-10-08 20:55:54 -06:00
return Err(Error::ClusterInfoError(ClusterInfoError::NoLeader));
}
sleep(Duration::from_millis(100));
}
gossip_service.close()?;
if log_enabled!(Level::Trace) {
2018-10-08 20:55:54 -06:00
trace!("{}", cluster_info.read().unwrap().node_info_trace());
}
Ok(leader.unwrap().clone())
}
pub fn retry_get_balance(
client: &mut ThinClient,
bob_pubkey: &Pubkey,
expected_balance: Option<u64>,
) -> Option<u64> {
const LAST: usize = 30;
for run in 0..LAST {
let balance_result = client.poll_get_balance(bob_pubkey);
if expected_balance.is_none() {
return balance_result.ok();
}
trace!(
"retry_get_balance[{}] {:?} {:?}",
run,
balance_result,
expected_balance
);
if let (Some(expected_balance), Ok(balance_result)) = (expected_balance, balance_result) {
if expected_balance == balance_result {
return Some(balance_result);
}
}
}
None
}
pub fn new_fullnode(ledger_name: &'static str) -> (Fullnode, NodeInfo, Keypair, String) {
2018-12-07 20:16:27 -07:00
use crate::cluster_info::Node;
2019-01-30 10:18:33 -08:00
use crate::db_ledger::create_tmp_sample_ledger;
use crate::fullnode::Fullnode;
use crate::voting_keypair::VotingKeypair;
use solana_sdk::signature::KeypairUtil;
let node_keypair = Arc::new(Keypair::new());
let node = Node::new_localhost_with_pubkey(node_keypair.pubkey());
let node_info = node.info.clone();
let (mint_keypair, ledger_path, _, _) =
2019-01-30 10:18:33 -08:00
create_tmp_sample_ledger(ledger_name, 10_000, 0, node_info.id, 42);
let vote_account_keypair = Arc::new(Keypair::new());
let voting_keypair = VotingKeypair::new_local(&vote_account_keypair);
let node = Fullnode::new(
node,
&node_keypair,
&ledger_path,
voting_keypair,
None,
&FullnodeConfig::default(),
);
(node, node_info, mint_keypair, ledger_path)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::client::mk_client;
use bincode::{deserialize, serialize};
2018-12-03 10:26:28 -08:00
use solana_sdk::signature::{Keypair, KeypairUtil};
2018-11-16 08:04:46 -08:00
use solana_sdk::system_instruction::SystemInstruction;
2019-02-01 15:50:11 -07:00
use solana_sdk::vote_program::VoteState;
2018-12-04 15:05:41 -08:00
use solana_sdk::vote_transaction::VoteTransaction;
2018-12-04 20:19:48 -08:00
use std::fs::remove_dir_all;
2018-02-28 14:16:50 -07:00
#[test]
fn test_thin_client_basic() {
solana_logger::setup();
let (server, leader_data, alice, ledger_path) = new_fullnode("thin_client");
let server_exit = server.run(None);
2018-08-09 08:56:04 -06:00
let bob_pubkey = Keypair::new().pubkey();
info!(
"found leader: {:?}",
poll_gossip_for_leader(leader_data.gossip, Some(5)).unwrap()
);
2018-02-28 14:16:50 -07:00
let mut client = mk_client(&leader_data);
2018-11-05 10:50:58 -07:00
let transaction_count = client.transaction_count();
assert_eq!(transaction_count, 0);
let confirmation = client.get_confirmation_time();
assert_eq!(confirmation, 18446744073709551615);
let last_id = client.get_last_id();
info!("test_thin_client last_id: {:?}", last_id);
2019-01-24 12:04:04 -08:00
let signature = client.transfer(500, &alice, bob_pubkey, &last_id).unwrap();
info!("test_thin_client signature: {:?}", signature);
client.poll_for_signature(&signature).unwrap();
2018-07-20 19:05:39 -04:00
let balance = client.get_balance(&bob_pubkey);
assert_eq!(balance.unwrap(), 500);
2018-11-05 10:50:58 -07:00
let transaction_count = client.transaction_count();
assert_eq!(transaction_count, 1);
server_exit();
2018-08-06 12:35:38 -07:00
remove_dir_all(ledger_path).unwrap();
2018-02-28 14:16:50 -07:00
}
2018-05-09 13:33:33 -06:00
#[test]
#[ignore]
2018-05-09 13:33:33 -06:00
fn test_bad_sig() {
solana_logger::setup();
let (server, leader_data, alice, ledger_path) = new_fullnode("bad_sig");
let server_exit = server.run(None);
2018-08-09 08:56:04 -06:00
let bob_pubkey = Keypair::new().pubkey();
info!(
"found leader: {:?}",
poll_gossip_for_leader(leader_data.gossip, Some(5)).unwrap()
);
2018-05-09 13:33:33 -06:00
let mut client = mk_client(&leader_data);
let last_id = client.get_last_id();
2018-05-09 13:33:33 -06:00
let tx = SystemTransaction::new_account(&alice, bob_pubkey, 500, last_id, 0);
2018-05-09 13:33:33 -06:00
2018-07-11 14:40:46 -06:00
let _sig = client.transfer_signed(&tx).unwrap();
2018-05-09 13:33:33 -06:00
let last_id = client.get_last_id();
2018-05-09 13:33:33 -06:00
let mut tr2 = SystemTransaction::new_account(&alice, bob_pubkey, 501, last_id, 0);
let mut instruction2 = deserialize(tr2.userdata(0)).unwrap();
2018-11-16 08:04:46 -08:00
if let SystemInstruction::Move { ref mut tokens } = instruction2 {
*tokens = 502;
2018-05-22 21:42:04 -06:00
}
tr2.instructions[0].userdata = serialize(&instruction2).unwrap();
let signature = client.transfer_signed(&tr2).unwrap();
client.poll_for_signature(&signature).unwrap();
2018-05-09 13:33:33 -06:00
2018-07-20 19:05:39 -04:00
let balance = client.get_balance(&bob_pubkey);
assert_eq!(balance.unwrap(), 1001);
server_exit();
remove_dir_all(ledger_path).unwrap();
}
#[test]
fn test_register_vote_account() {
solana_logger::setup();
let (server, leader_data, alice, ledger_path) = new_fullnode("thin_client");
let server_exit = server.run(None);
info!(
"found leader: {:?}",
poll_gossip_for_leader(leader_data.gossip, Some(5)).unwrap()
);
let mut client = mk_client(&leader_data);
// Create the validator account, transfer some tokens to that account
let validator_keypair = Keypair::new();
let last_id = client.get_last_id();
let signature = client
.transfer(500, &alice, validator_keypair.pubkey(), &last_id)
.unwrap();
client.poll_for_signature(&signature).unwrap();
// Create and register the vote account
let validator_vote_account_keypair = Keypair::new();
let vote_account_id = validator_vote_account_keypair.pubkey();
let last_id = client.get_last_id();
2018-11-15 17:05:31 -08:00
let transaction =
VoteTransaction::new_account(&validator_keypair, vote_account_id, last_id, 1, 1);
2018-11-15 17:05:31 -08:00
let signature = client.transfer_signed(&transaction).unwrap();
client.poll_for_signature(&signature).unwrap();
2018-11-15 17:05:31 -08:00
let balance = retry_get_balance(&mut client, &vote_account_id, Some(1))
.expect("Expected balance for new account to exist");
assert_eq!(balance, 1);
const LAST: usize = 30;
for run in 0..=LAST {
let account_user_data = client
.get_account_userdata(&vote_account_id)
.expect("Expected valid response for account userdata")
.expect("Expected valid account userdata to exist after account creation");
2019-02-01 15:50:11 -07:00
let vote_state = VoteState::deserialize(&account_user_data);
if vote_state.map(|vote_state| vote_state.node_id) == Ok(validator_keypair.pubkey()) {
break;
}
if run == LAST {
panic!("Expected successful vote account registration");
}
sleep(Duration::from_millis(900));
}
server_exit();
remove_dir_all(ledger_path).unwrap();
}
#[test]
fn test_transaction_count() {
// set a bogus address, see that we don't hang
solana_logger::setup();
let addr = "0.0.0.0:1234".parse().unwrap();
let transactions_socket = UdpSocket::bind("0.0.0.0:0").unwrap();
let mut client =
ThinClient::new_with_timeout(addr, addr, transactions_socket, Duration::from_secs(2));
assert_eq!(client.transaction_count(), 0);
}
#[test]
fn test_zero_balance_after_nonzero() {
solana_logger::setup();
let (server, leader_data, alice, ledger_path) = new_fullnode("thin_client");
let server_exit = server.run(None);
let bob_keypair = Keypair::new();
info!(
"found leader: {:?}",
poll_gossip_for_leader(leader_data.gossip, Some(5)).unwrap()
);
let mut client = mk_client(&leader_data);
let last_id = client.get_last_id();
let starting_balance = client.poll_get_balance(&alice.pubkey()).unwrap();
info!("Give Bob 500 tokens");
let signature = client
2019-01-24 12:04:04 -08:00
.transfer(500, &alice, bob_keypair.pubkey(), &last_id)
.unwrap();
client.poll_for_signature(&signature).unwrap();
let balance = client.poll_get_balance(&bob_keypair.pubkey());
assert_eq!(balance.unwrap(), 500);
info!("Take Bob's 500 tokens away");
let signature = client
2019-01-24 12:04:04 -08:00
.transfer(500, &bob_keypair, alice.pubkey(), &last_id)
.unwrap();
client.poll_for_signature(&signature).unwrap();
let balance = client.poll_get_balance(&alice.pubkey()).unwrap();
assert_eq!(balance, starting_balance);
info!("Should get an error when Bob's balance hits zero and is purged");
let balance = client.poll_get_balance(&bob_keypair.pubkey());
assert!(balance.is_err());
server_exit();
remove_dir_all(ledger_path).unwrap();
}
}