solana/src/thin_client.rs

297 lines
10 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 futures::future::{ok, FutureResult};
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 transaction::Transaction;
2018-02-28 13:16:50 -08:00
pub struct ThinClient {
requests_addr: SocketAddr,
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, Option<i64>>,
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,
requests_socket: UdpSocket,
2018-05-25 14:51:41 -07:00
transactions_addr: SocketAddr,
transactions_socket: UdpSocket,
) -> Self {
let client = ThinClient {
requests_addr,
requests_socket,
2018-05-25 14:51:41 -07:00
transactions_addr,
transactions_socket,
last_id: None,
transaction_count: 0,
balances: HashMap::new(),
2018-04-17 15:41:58 -07:00
};
client
}
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");
self.requests_socket.recv_from(&mut buf)?;
2018-05-12 19:00:22 -07:00
trace!("end recv_from");
2018-05-10 17:46:10 -07:00
let resp = deserialize(&buf).expect("deserialize balance in thin_client");
Ok(resp)
}
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 } => {
info!("Response last_id {:?}", id);
self.last_id = Some(id);
}
Response::TransactionCount { transaction_count } => {
info!("Response transaction count {:?}", transaction_count);
self.transaction_count = transaction_count;
}
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.
2018-05-25 15:05:37 -07:00
pub fn transfer_signed(&self, tx: Transaction) -> io::Result<usize> {
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)
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-05-25 15:05:37 -07:00
let tx = Transaction::new(keypair, to, n, *last_id);
let sig = tx.sig;
self.transfer_signed(tx).map(|_| sig)
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");
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);
2018-04-17 15:41:58 -07:00
if let &Response::Balance { ref key, .. } = &resp {
done = key == pubkey;
}
self.process_response(resp);
}
self.balances[pubkey].ok_or(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 {
info!("transaction_count");
let req = Request::GetTransactionCount;
let data =
serialize(&req).expect("serialize GetTransactionCount in pub fn transaction_count");
self.requests_socket
.send_to(&data, &self.requests_addr)
.expect("buffer error in pub fn transaction_count");
let mut done = false;
while !done {
let resp = self.recv_response().expect("transaction count dropped");
info!("recv_response {:?}", resp);
if let &Response::TransactionCount { .. } = &resp {
done = true;
}
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) -> FutureResult<Hash, ()> {
info!("get_last_id");
let req = Request::GetLastId;
let data = serialize(&req).expect("serialize GetLastId in pub fn get_last_id");
self.requests_socket
.send_to(&data, &self.requests_addr)
.expect("buffer error in pub fn get_last_id");
let mut done = false;
while !done {
let resp = self.recv_response().expect("get_last_id response");
if let &Response::LastId { .. } = &resp {
done = true;
}
self.process_response(resp);
}
ok(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> {
use std::time::Instant;
let mut balance;
let now = Instant::now();
loop {
balance = self.get_balance(pubkey);
if balance.is_ok() || now.elapsed().as_secs() > 1 {
break;
}
}
balance
}
}
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;
use futures::Future;
use logger;
use mint::Mint;
use plan::Budget;
2018-05-15 10:00:01 -07:00
use server::Server;
use signature::{KeyPair, KeyPairUtil};
2018-03-26 11:17:19 -07:00
use std::io::sink;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::sleep;
use std::time::Duration;
2018-05-22 20:42:04 -07:00
use transaction::Instruction;
use tvu::TestNode;
2018-02-28 13:16:50 -08:00
#[test]
fn test_thin_client() {
logger::setup();
2018-05-23 10:49:48 -07:00
let leader = TestNode::new();
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));
2018-05-23 11:06:18 -07:00
let server = Server::new_leader(
bank,
alice.last_id(),
Some(Duration::from_millis(30)),
2018-05-23 10:52:47 -07:00
leader.data.clone(),
2018-05-23 11:06:18 -07:00
leader.sockets.requests,
2018-05-25 14:51:41 -07:00
leader.sockets.transaction,
2018-05-23 11:06:18 -07:00
leader.sockets.broadcast,
leader.sockets.respond,
leader.sockets.gossip,
exit.clone(),
sink(),
);
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(
leader.data.requests_addr,
requests_socket,
2018-05-25 14:51:41 -07:00
leader.data.transactions_addr,
transactions_socket,
2018-05-23 10:54:48 -07:00
);
2018-05-11 15:15:14 -07:00
let last_id = client.get_last_id().wait().unwrap();
let _sig = client
.transfer(500, &alice.keypair(), bob_pubkey, &last_id)
.unwrap();
let balance = client.poll_get_balance(&bob_pubkey);
assert_eq!(balance.unwrap(), 500);
2018-03-22 13:05:23 -07:00
exit.store(true, Ordering::Relaxed);
2018-05-15 10:00:01 -07:00
for t in server.thread_hdls {
2018-04-28 00:31:20 -07:00
t.join().unwrap();
}
2018-02-28 13:16:50 -08:00
}
2018-05-09 12:33:33 -07:00
#[test]
fn test_bad_sig() {
logger::setup();
2018-05-23 08:29:24 -07:00
let leader = TestNode::new();
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));
2018-05-23 11:06:18 -07:00
let server = Server::new_leader(
bank,
alice.last_id(),
Some(Duration::from_millis(30)),
2018-05-23 10:52:47 -07:00
leader.data.clone(),
2018-05-23 11:06:18 -07:00
leader.sockets.requests,
2018-05-25 14:51:41 -07:00
leader.sockets.transaction,
2018-05-23 11:06:18 -07:00
leader.sockets.broadcast,
leader.sockets.respond,
leader.sockets.gossip,
2018-05-09 12:33:33 -07:00
exit.clone(),
sink(),
);
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(
leader.data.requests_addr,
requests_socket,
2018-05-25 14:51:41 -07:00
leader.data.transactions_addr,
transactions_socket,
2018-05-23 10:54:48 -07:00
);
2018-05-09 12:33:33 -07:00
let last_id = client.get_last_id().wait().unwrap();
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-05-25 15:05:37 -07:00
let _sig = client.transfer_signed(tx).unwrap();
2018-05-09 12:33:33 -07:00
let last_id = client.get_last_id().wait().unwrap();
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 = Budget::new_payment(502, bob_pubkey);
2018-05-22 20:42:04 -07:00
}
2018-05-09 12:33:33 -07:00
let _sig = client.transfer_signed(tr2).unwrap();
let balance = client.poll_get_balance(&bob_pubkey);
assert_eq!(balance.unwrap(), 500);
2018-05-09 12:33:33 -07:00
exit.store(true, Ordering::Relaxed);
2018-05-15 10:00:01 -07:00
for t in server.thread_hdls {
2018-05-09 12:33:33 -07:00
t.join().unwrap();
}
2018-02-28 13:16:50 -08:00
}
}