solana/src/thin_client.rs

467 lines
16 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 13:16:50 -08:00
use bincode::{deserialize, serialize};
use hash::Hash;
use request::{Request, Response};
use signature::{KeyPair, PublicKey, Signature};
use std::collections::HashMap;
use std::io;
2018-04-28 00:31:20 -07:00
use std::net::{SocketAddr, UdpSocket};
use std::thread::sleep;
use std::time::Duration;
2018-07-05 21:40:09 -07:00
use std::time::Instant;
use timing;
use transaction::Transaction;
2018-02-28 13:16:50 -08:00
2018-07-05 21:40:09 -07:00
use influx_db_client as influxdb;
use metrics;
2018-06-07 13:51:29 -07:00
/// An object for querying and sending transactions to the network.
pub struct ThinClient {
requests_addr: SocketAddr,
2018-07-02 13:43:33 -07:00
requests_socket: UdpSocket,
2018-05-25 14:51:41 -07:00
transactions_addr: SocketAddr,
transactions_socket: UdpSocket,
last_id: Option<Hash>,
transaction_count: u64,
balances: HashMap<PublicKey, i64>,
2018-06-28 17:59:02 -07:00
signature_status: bool,
2018-02-28 13:16:50 -08:00
}
impl ThinClient {
2018-05-12 09:53:25 -07:00
/// Create a new ThinClient that will interface with Rpu
2018-05-25 14:51:41 -07:00
/// over `requests_socket` and `transactions_socket`. To receive responses, the caller must bind `socket`
/// to a public address before invoking ThinClient methods.
pub fn new(
requests_addr: SocketAddr,
2018-07-02 13:43:33 -07:00
requests_socket: UdpSocket,
2018-05-25 14:51:41 -07:00
transactions_addr: SocketAddr,
transactions_socket: UdpSocket,
) -> Self {
2018-07-11 13:40:46 -07:00
ThinClient {
requests_addr,
2018-07-02 13:43:33 -07:00
requests_socket,
2018-05-25 14:51:41 -07:00
transactions_addr,
transactions_socket,
last_id: None,
transaction_count: 0,
balances: HashMap::new(),
2018-06-28 17:59:02 -07:00
signature_status: false,
2018-07-11 13:40:46 -07:00
}
}
pub fn recv_response(&self) -> io::Result<Response> {
let mut buf = vec![0u8; 1024];
2018-05-12 19:00:22 -07:00
trace!("start recv_from");
2018-07-02 13:43:33 -07:00
self.requests_socket.recv_from(&mut buf)?;
2018-05-12 19:00:22 -07:00
trace!("end recv_from");
deserialize(&buf).or_else(|_| Err(io::Error::new(io::ErrorKind::Other, "deserialize")))
}
2018-07-11 13:40:46 -07:00
pub fn process_response(&mut self, resp: &Response) {
match *resp {
Response::Balance { key, val } => {
2018-05-12 19:00:22 -07:00
trace!("Response balance {:?} {:?}", key, val);
self.balances.insert(key, val);
}
2018-05-14 08:35:10 -07:00
Response::LastId { id } => {
trace!("Response last_id {:?}", id);
2018-05-14 08:35:10 -07:00
self.last_id = Some(id);
}
Response::TransactionCount { transaction_count } => {
trace!("Response transaction count {:?}", transaction_count);
self.transaction_count = transaction_count;
}
Response::SignatureStatus { signature_status } => {
self.signature_status = signature_status;
2018-07-11 13:40:46 -07:00
if signature_status {
trace!("Response found signature");
} else {
trace!("Response signature not found");
}
}
2018-02-28 13:16:50 -08:00
}
}
2018-03-29 11:20:54 -07: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> {
2018-05-25 15:05:37 -07:00
let data = serialize(&tx).expect("serialize Transaction in pub fn transfer_signed");
2018-05-25 14:51:41 -07:00
self.transactions_socket
.send_to(&data, &self.transactions_addr)?;
Ok(tx.sig)
2018-02-28 13:16:50 -08:00
}
2018-03-29 11:20:54 -07:00
/// Creates, signs, and processes a Transaction. Useful for writing unit-tests.
2018-02-28 13:16:50 -08:00
pub fn transfer(
2018-03-05 10:11:00 -08:00
&self,
n: i64,
keypair: &KeyPair,
2018-02-28 13:16:50 -08:00
to: PublicKey,
last_id: &Hash,
) -> io::Result<Signature> {
2018-07-05 21:40:09 -07:00
let now = Instant::now();
2018-05-25 15:05:37 -07:00
let tx = Transaction::new(keypair, to, n, *last_id);
let result = self.transfer_signed(&tx);
2018-07-05 21:40:09 -07:00
metrics::submit(
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(),
);
result
2018-02-28 13:16:50 -08:00
}
2018-03-29 11:20:54 -07: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: &PublicKey) -> io::Result<i64> {
2018-05-12 19:00:22 -07:00
trace!("get_balance");
2018-02-28 13:16:50 -08:00
let req = Request::GetBalance { key: *pubkey };
2018-05-10 17:46:10 -07:00
let data = serialize(&req).expect("serialize GetBalance in pub fn get_balance");
2018-07-02 13:43:33 -07:00
self.requests_socket
.send_to(&data, &self.requests_addr)
2018-05-10 17:46:10 -07:00
.expect("buffer error in pub fn get_balance");
2018-04-17 15:41:58 -07:00
let mut done = false;
while !done {
let resp = self.recv_response()?;
2018-05-12 19:00:22 -07:00
trace!("recv_response {:?}", resp);
if let Response::Balance { key, .. } = &resp {
2018-04-17 15:41:58 -07:00
done = key == pubkey;
}
2018-07-11 13:40:46 -07:00
self.process_response(&resp);
2018-04-17 15:41:58 -07:00
}
self.balances
.get(pubkey)
2018-07-11 13:40:46 -07:00
.cloned()
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "nokey"))
}
/// Request the transaction count. If the response packet is dropped by the network,
/// this method will hang.
pub fn transaction_count(&mut self) -> u64 {
2018-07-22 16:20:07 -07:00
debug!("transaction_count");
let req = Request::GetTransactionCount;
let data =
serialize(&req).expect("serialize GetTransactionCount in pub fn transaction_count");
let mut done = false;
while !done {
2018-07-02 13:43:33 -07:00
self.requests_socket
.send_to(&data, &self.requests_addr)
.expect("buffer error in pub fn transaction_count");
if let Ok(resp) = self.recv_response() {
2018-07-22 16:20:07 -07:00
debug!("transaction_count recv_response: {:?}", resp);
2018-07-11 13:40:46 -07:00
if let Response::TransactionCount { .. } = resp {
done = true;
}
2018-07-11 13:40:46 -07:00
self.process_response(&resp);
}
}
self.transaction_count
}
2018-04-02 08:30:10 -07: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 {
trace!("get_last_id");
let req = Request::GetLastId;
let data = serialize(&req).expect("serialize GetLastId in pub fn get_last_id");
let mut done = false;
while !done {
2018-07-02 10:22:54 -07:00
debug!("get_last_id send_to {}", &self.requests_addr);
2018-07-02 13:43:33 -07:00
self.requests_socket
.send_to(&data, &self.requests_addr)
.expect("buffer error in pub fn get_last_id");
2018-06-28 15:23:53 -07:00
match self.recv_response() {
Ok(resp) => {
2018-07-11 13:40:46 -07:00
if let Response::LastId { .. } = resp {
2018-06-28 15:23:53 -07:00
done = true;
}
2018-07-11 13:40:46 -07:00
self.process_response(&resp);
2018-06-28 15:23:53 -07:00
}
Err(e) => {
debug!("thin_client get_last_id error: {}", e);
}
}
}
self.last_id.expect("some last_id")
}
2018-02-28 13:16:50 -08:00
pub fn poll_get_balance(&mut self, pubkey: &PublicKey) -> io::Result<i64> {
let mut balance_result;
let mut balance_value = -1;
let now = Instant::now();
loop {
balance_result = self.get_balance(pubkey);
if balance_result.is_ok() {
balance_value = *balance_result.as_ref().unwrap();
}
if balance_value > 0 || now.elapsed().as_secs() > 1 {
break;
}
sleep(Duration::from_millis(100));
}
2018-07-05 21:40:09 -07:00
metrics::submit(
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(&now.elapsed()) as i64),
)
.to_owned(),
);
if balance_value >= 0 {
Ok(balance_value)
} else {
assert!(balance_result.is_err());
balance_result
}
}
2018-07-20 16:05:39 -07:00
/// Poll the server to confirm a transaction.
pub fn poll_for_signature(&mut self, sig: &Signature) -> io::Result<()> {
let now = Instant::now();
while !self.check_signature(sig) {
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.
2018-06-28 17:59:02 -07:00
pub fn check_signature(&mut self, sig: &Signature) -> bool {
trace!("check_signature");
let req = Request::GetSignature { signature: *sig };
let data = serialize(&req).expect("serialize GetSignature in pub fn check_signature");
2018-07-05 21:40:09 -07:00
let now = Instant::now();
let mut done = false;
while !done {
2018-07-02 13:43:33 -07:00
self.requests_socket
.send_to(&data, &self.requests_addr)
.expect("buffer error in pub fn get_last_id");
if let Ok(resp) = self.recv_response() {
2018-07-11 13:40:46 -07:00
if let Response::SignatureStatus { .. } = resp {
done = true;
}
2018-07-11 13:40:46 -07:00
self.process_response(&resp);
}
}
2018-07-05 21:40:09 -07:00
metrics::submit(
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(),
);
self.signature_status
}
}
2018-07-05 21:40:09 -07:00
impl Drop for ThinClient {
fn drop(&mut self) {
metrics::flush();
}
}
2018-02-28 13:16:50 -08:00
#[cfg(test)]
mod tests {
use super::*;
2018-05-14 14:33:11 -07:00
use bank::Bank;
2018-05-29 12:28:07 -07:00
use budget::Budget;
use crdt::TestNode;
2018-07-02 15:24:40 -07:00
use fullnode::FullNode;
use ledger::LedgerWriter;
use logger;
use mint::Mint;
use service::Service;
use signature::{KeyPair, KeyPairUtil};
use std::fs::remove_dir_all;
use std::sync::atomic::{AtomicBool, Ordering};
2018-05-30 11:54:53 -07:00
use std::sync::Arc;
use transaction::{Instruction, Plan};
2018-02-28 13:16:50 -08:00
fn tmp_ledger(name: &str, mint: &Mint) -> String {
let keypair = KeyPair::new();
let path = format!("/tmp/tmp-ledger-{}-{}", name, keypair.pubkey());
let mut writer = LedgerWriter::new(&path, true).unwrap();
writer.write_entries(mint.create_entries()).unwrap();
path
}
2018-02-28 13:16:50 -08:00
#[test]
fn test_thin_client() {
logger::setup();
let leader_keypair = KeyPair::new();
let leader = TestNode::new_localhost_with_pubkey(leader_keypair.pubkey());
let leader_data = leader.data.clone();
2018-04-28 00:31:20 -07:00
let alice = Mint::new(10_000);
2018-05-14 14:33:11 -07:00
let bank = Bank::new(&alice);
let bob_pubkey = KeyPair::new().pubkey();
2018-03-22 13:05:23 -07:00
let exit = Arc::new(AtomicBool::new(false));
let ledger_path = tmp_ledger("thin_client", &alice);
2018-07-02 15:24:40 -07:00
let server = FullNode::new_leader(
leader_keypair,
bank,
2018-06-27 12:35:58 -07:00
0,
None,
Some(Duration::from_millis(30)),
leader,
exit.clone(),
&ledger_path,
false,
);
2018-05-13 20:33:41 -07:00
sleep(Duration::from_millis(900));
2018-02-28 13:16:50 -08:00
let requests_socket = UdpSocket::bind("0.0.0.0:0").unwrap();
2018-05-25 14:51:41 -07:00
let transactions_socket = UdpSocket::bind("0.0.0.0:0").unwrap();
2018-05-23 10:54:48 -07:00
let mut client = ThinClient::new(
2018-07-09 17:55:11 -07:00
leader_data.contact_info.rpu,
2018-05-23 10:54:48 -07:00
requests_socket,
2018-07-09 17:55:11 -07:00
leader_data.contact_info.tpu,
2018-05-25 14:51:41 -07:00
transactions_socket,
2018-05-23 10:54:48 -07:00
);
let last_id = client.get_last_id();
2018-07-20 16:05:39 -07:00
let sig = client
.transfer(500, &alice.keypair(), bob_pubkey, &last_id)
.unwrap();
2018-07-20 16:05:39 -07:00
client.poll_for_signature(&sig).unwrap();
let balance = client.get_balance(&bob_pubkey);
assert_eq!(balance.unwrap(), 500);
2018-03-22 13:05:23 -07:00
exit.store(true, Ordering::Relaxed);
server.join().unwrap();
2018-08-06 12:35:38 -07:00
remove_dir_all(ledger_path).unwrap();
2018-02-28 13:16:50 -08:00
}
// sleep(Duration::from_millis(300)); is unstable
2018-05-09 12:33:33 -07:00
#[test]
#[ignore]
2018-05-09 12:33:33 -07:00
fn test_bad_sig() {
logger::setup();
let leader_keypair = KeyPair::new();
let leader = TestNode::new_localhost_with_pubkey(leader_keypair.pubkey());
2018-05-09 12:33:33 -07:00
let alice = Mint::new(10_000);
2018-05-14 14:33:11 -07:00
let bank = Bank::new(&alice);
2018-05-09 12:33:33 -07:00
let bob_pubkey = KeyPair::new().pubkey();
let exit = Arc::new(AtomicBool::new(false));
let leader_data = leader.data.clone();
let ledger_path = tmp_ledger("bad_sig", &alice);
2018-07-02 15:24:40 -07:00
let server = FullNode::new_leader(
leader_keypair,
bank,
2018-06-27 12:35:58 -07:00
0,
None,
Some(Duration::from_millis(30)),
leader,
2018-05-09 12:33:33 -07:00
exit.clone(),
&ledger_path,
false,
);
//TODO: remove this sleep, or add a retry so CI is stable
2018-05-09 12:33:33 -07:00
sleep(Duration::from_millis(300));
2018-05-22 16:40:01 -07:00
let requests_socket = UdpSocket::bind("0.0.0.0:0").unwrap();
requests_socket
.set_read_timeout(Some(Duration::new(5, 0)))
.unwrap();
2018-05-25 14:51:41 -07:00
let transactions_socket = UdpSocket::bind("0.0.0.0:0").unwrap();
2018-05-23 10:54:48 -07:00
let mut client = ThinClient::new(
2018-07-09 17:55:11 -07:00
leader_data.contact_info.rpu,
2018-05-23 10:54:48 -07:00
requests_socket,
2018-07-09 17:55:11 -07:00
leader_data.contact_info.tpu,
2018-05-25 14:51:41 -07:00
transactions_socket,
2018-05-23 10:54:48 -07:00
);
let last_id = client.get_last_id();
2018-05-09 12:33:33 -07:00
2018-05-25 15:05:37 -07:00
let tx = Transaction::new(&alice.keypair(), bob_pubkey, 500, last_id);
2018-05-09 12:33:33 -07:00
2018-07-11 13:40:46 -07:00
let _sig = client.transfer_signed(&tx).unwrap();
2018-05-09 12:33:33 -07:00
let last_id = client.get_last_id();
2018-05-09 12:33:33 -07:00
let mut tr2 = Transaction::new(&alice.keypair(), bob_pubkey, 501, last_id);
2018-05-22 20:42:04 -07:00
if let Instruction::NewContract(contract) = &mut tr2.instruction {
contract.tokens = 502;
contract.plan = Plan::Budget(Budget::new_payment(502, bob_pubkey));
2018-05-22 20:42:04 -07:00
}
2018-07-20 16:05:39 -07:00
let sig = client.transfer_signed(&tr2).unwrap();
client.poll_for_signature(&sig).unwrap();
2018-05-09 12:33:33 -07:00
2018-07-20 16:05:39 -07:00
let balance = client.get_balance(&bob_pubkey);
assert_eq!(balance.unwrap(), 500);
2018-05-09 12:33:33 -07:00
exit.store(true, Ordering::Relaxed);
server.join().unwrap();
remove_dir_all(ledger_path).unwrap();
2018-02-28 13:16:50 -08:00
}
#[test]
fn test_client_check_signature() {
logger::setup();
let leader_keypair = KeyPair::new();
let leader = TestNode::new_localhost_with_pubkey(leader_keypair.pubkey());
let alice = Mint::new(10_000);
let bank = Bank::new(&alice);
let bob_pubkey = KeyPair::new().pubkey();
let exit = Arc::new(AtomicBool::new(false));
let leader_data = leader.data.clone();
let ledger_path = tmp_ledger("client_check_signature", &alice);
2018-07-02 15:24:40 -07:00
let server = FullNode::new_leader(
leader_keypair,
bank,
0,
None,
Some(Duration::from_millis(30)),
leader,
exit.clone(),
&ledger_path,
false,
);
sleep(Duration::from_millis(300));
let requests_socket = UdpSocket::bind("0.0.0.0:0").unwrap();
requests_socket
.set_read_timeout(Some(Duration::new(5, 0)))
.unwrap();
let transactions_socket = UdpSocket::bind("0.0.0.0:0").unwrap();
let mut client = ThinClient::new(
2018-07-09 17:55:11 -07:00
leader_data.contact_info.rpu,
requests_socket,
2018-07-09 17:55:11 -07:00
leader_data.contact_info.tpu,
transactions_socket,
);
let last_id = client.get_last_id();
let sig = client
.transfer(500, &alice.keypair(), bob_pubkey, &last_id)
.unwrap();
sleep(Duration::from_millis(100));
2018-06-28 17:59:02 -07:00
assert!(client.check_signature(&sig));
exit.store(true, Ordering::Relaxed);
server.join().unwrap();
remove_dir_all(ledger_path).unwrap();
}
}