pub use crate::nonblocking::tpu_client::TpuSenderError;
use {
crate::nonblocking::tpu_client::TpuClient as NonblockingTpuClient,
rayon::iter::{IntoParallelIterator, ParallelIterator},
solana_connection_cache::connection_cache::{
ConnectionCache, ConnectionManager, ConnectionPool, NewConnectionConfig,
},
solana_rpc_client::rpc_client::RpcClient,
solana_sdk::{clock::Slot, transaction::Transaction, transport::Result as TransportResult},
std::{
collections::VecDeque,
net::UdpSocket,
sync::{Arc, RwLock},
},
};
#[cfg(feature = "spinner")]
use {
solana_sdk::{message::Message, signers::Signers, transaction::TransactionError},
tokio::time::Duration,
};
pub const DEFAULT_TPU_ENABLE_UDP: bool = false;
pub const DEFAULT_TPU_USE_QUIC: bool = true;
pub const DEFAULT_TPU_CONNECTION_POOL_SIZE: usize = 1;
pub type Result<T> = std::result::Result<T, TpuSenderError>;
#[cfg(feature = "spinner")]
pub(crate) const SEND_TRANSACTION_INTERVAL: Duration = Duration::from_millis(10);
#[cfg(feature = "spinner")]
pub(crate) const TRANSACTION_RESEND_INTERVAL: Duration = Duration::from_secs(4);
pub const DEFAULT_FANOUT_SLOTS: u64 = 12;
pub const MAX_FANOUT_SLOTS: u64 = 100;
#[derive(Clone, Debug)]
pub struct TpuClientConfig {
pub fanout_slots: u64,
}
impl Default for TpuClientConfig {
fn default() -> Self {
Self {
fanout_slots: DEFAULT_FANOUT_SLOTS,
}
}
}
pub struct TpuClient<
P, M, C, > {
_deprecated: UdpSocket, rpc_client: Arc<RpcClient>,
tpu_client: Arc<NonblockingTpuClient<P, M, C>>,
}
impl<P, M, C> TpuClient<P, M, C>
where
P: ConnectionPool<NewConnectionConfig = C>,
M: ConnectionManager<ConnectionPool = P, NewConnectionConfig = C>,
C: NewConnectionConfig,
{
pub fn send_transaction(&self, transaction: &Transaction) -> bool {
self.invoke(self.tpu_client.send_transaction(transaction))
}
pub fn send_wire_transaction(&self, wire_transaction: Vec<u8>) -> bool {
self.invoke(self.tpu_client.send_wire_transaction(wire_transaction))
}
pub fn try_send_transaction(&self, transaction: &Transaction) -> TransportResult<()> {
self.invoke(self.tpu_client.try_send_transaction(transaction))
}
pub fn try_send_transaction_batch(&self, transactions: &[Transaction]) -> TransportResult<()> {
let wire_transactions = transactions
.into_par_iter()
.map(|tx| bincode::serialize(&tx).expect("serialize Transaction in send_batch"))
.collect::<Vec<_>>();
self.invoke(
self.tpu_client
.try_send_wire_transaction_batch(wire_transactions),
)
}
pub fn try_send_wire_transaction(&self, wire_transaction: Vec<u8>) -> TransportResult<()> {
self.invoke(self.tpu_client.try_send_wire_transaction(wire_transaction))
}
pub fn new(
name: &'static str,
rpc_client: Arc<RpcClient>,
websocket_url: &str,
config: TpuClientConfig,
connection_manager: M,
) -> Result<Self> {
let create_tpu_client = NonblockingTpuClient::new(
name,
rpc_client.get_inner_client().clone(),
websocket_url,
config,
connection_manager,
);
let tpu_client =
tokio::task::block_in_place(|| rpc_client.runtime().block_on(create_tpu_client))?;
Ok(Self {
_deprecated: UdpSocket::bind("0.0.0.0:0").unwrap(),
rpc_client,
tpu_client: Arc::new(tpu_client),
})
}
pub fn new_with_connection_cache(
rpc_client: Arc<RpcClient>,
websocket_url: &str,
config: TpuClientConfig,
connection_cache: Arc<ConnectionCache<P, M, C>>,
) -> Result<Self> {
let create_tpu_client = NonblockingTpuClient::new_with_connection_cache(
rpc_client.get_inner_client().clone(),
websocket_url,
config,
connection_cache,
);
let tpu_client =
tokio::task::block_in_place(|| rpc_client.runtime().block_on(create_tpu_client))?;
Ok(Self {
_deprecated: UdpSocket::bind("0.0.0.0:0").unwrap(),
rpc_client,
tpu_client: Arc::new(tpu_client),
})
}
#[cfg(feature = "spinner")]
pub fn send_and_confirm_messages_with_spinner<T: Signers + ?Sized>(
&self,
messages: &[Message],
signers: &T,
) -> Result<Vec<Option<TransactionError>>> {
self.invoke(
self.tpu_client
.send_and_confirm_messages_with_spinner(messages, signers),
)
}
pub fn rpc_client(&self) -> &RpcClient {
&self.rpc_client
}
fn invoke<T, F: std::future::Future<Output = T>>(&self, f: F) -> T {
tokio::task::block_in_place(move || self.rpc_client.runtime().block_on(f))
}
}
const MAX_SLOT_SKIP_DISTANCE: u64 = 48;
#[derive(Clone, Debug)]
pub(crate) struct RecentLeaderSlots(Arc<RwLock<VecDeque<Slot>>>);
impl RecentLeaderSlots {
pub(crate) fn new(current_slot: Slot) -> Self {
let mut recent_slots = VecDeque::new();
recent_slots.push_back(current_slot);
Self(Arc::new(RwLock::new(recent_slots)))
}
pub(crate) fn record_slot(&self, current_slot: Slot) {
let mut recent_slots = self.0.write().unwrap();
recent_slots.push_back(current_slot);
while recent_slots.len() > 12 {
recent_slots.pop_front();
}
}
pub(crate) fn estimated_current_slot(&self) -> Slot {
let mut recent_slots: Vec<Slot> = self.0.read().unwrap().iter().cloned().collect();
assert!(!recent_slots.is_empty());
recent_slots.sort_unstable();
let max_index = recent_slots.len() - 1;
let median_index = max_index / 2;
let median_recent_slot = recent_slots[median_index];
let expected_current_slot = median_recent_slot + (max_index - median_index) as u64;
let max_reasonable_current_slot = expected_current_slot + MAX_SLOT_SKIP_DISTANCE;
recent_slots
.into_iter()
.rev()
.find(|slot| *slot <= max_reasonable_current_slot)
.unwrap()
}
}
#[cfg(test)]
impl From<Vec<Slot>> for RecentLeaderSlots {
fn from(recent_slots: Vec<Slot>) -> Self {
assert!(!recent_slots.is_empty());
Self(Arc::new(RwLock::new(recent_slots.into_iter().collect())))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn assert_slot(recent_slots: RecentLeaderSlots, expected_slot: Slot) {
assert_eq!(recent_slots.estimated_current_slot(), expected_slot);
}
#[test]
fn test_recent_leader_slots() {
assert_slot(RecentLeaderSlots::new(0), 0);
let mut recent_slots: Vec<Slot> = (1..=12).collect();
assert_slot(RecentLeaderSlots::from(recent_slots.clone()), 12);
recent_slots.reverse();
assert_slot(RecentLeaderSlots::from(recent_slots), 12);
assert_slot(
RecentLeaderSlots::from(vec![0, 1 + MAX_SLOT_SKIP_DISTANCE]),
1 + MAX_SLOT_SKIP_DISTANCE,
);
assert_slot(
RecentLeaderSlots::from(vec![0, 2 + MAX_SLOT_SKIP_DISTANCE]),
0,
);
assert_slot(RecentLeaderSlots::from(vec![1]), 1);
assert_slot(RecentLeaderSlots::from(vec![1, 100]), 1);
assert_slot(RecentLeaderSlots::from(vec![1, 2, 100]), 2);
assert_slot(RecentLeaderSlots::from(vec![1, 2, 3, 100]), 3);
assert_slot(RecentLeaderSlots::from(vec![1, 2, 3, 99, 100]), 3);
}
}