use crate::{
common::connections::RpcConnections, transaction::api::TransactionBroadcastApiServer,
SubscriptionTaskExecutor,
};
use codec::Decode;
use futures::{FutureExt, Stream, StreamExt};
use futures_util::stream::AbortHandle;
use jsonrpsee::{
core::{async_trait, RpcResult},
ConnectionId, Extensions,
};
use parking_lot::RwLock;
use rand::{distributions::Alphanumeric, Rng};
use sc_client_api::BlockchainEvents;
use sc_transaction_pool_api::{
error::IntoPoolError, TransactionFor, TransactionPool, TransactionSource,
};
use sp_blockchain::HeaderBackend;
use sp_core::Bytes;
use sp_runtime::traits::Block as BlockT;
use std::{collections::HashMap, sync::Arc};
use super::error::ErrorBroadcast;
pub struct TransactionBroadcast<Pool: TransactionPool, Client> {
client: Arc<Client>,
pool: Arc<Pool>,
executor: SubscriptionTaskExecutor,
broadcast_ids: Arc<RwLock<HashMap<String, BroadcastState<Pool>>>>,
rpc_connections: RpcConnections,
}
struct BroadcastState<Pool: TransactionPool> {
handle: AbortHandle,
tx_hash: <Pool as TransactionPool>::Hash,
}
impl<Pool: TransactionPool, Client> TransactionBroadcast<Pool, Client> {
pub fn new(
client: Arc<Client>,
pool: Arc<Pool>,
executor: SubscriptionTaskExecutor,
max_transactions_per_connection: usize,
) -> Self {
TransactionBroadcast {
client,
pool,
executor,
broadcast_ids: Default::default(),
rpc_connections: RpcConnections::new(max_transactions_per_connection),
}
}
pub fn generate_unique_id(&self) -> String {
let generate_operation_id = || {
const OPERATION_ID_LEN: usize = 16;
rand::thread_rng()
.sample_iter(Alphanumeric)
.take(OPERATION_ID_LEN)
.map(char::from)
.collect::<String>()
};
let mut id = generate_operation_id();
let broadcast_ids = self.broadcast_ids.read();
while broadcast_ids.contains_key(&id) {
id = generate_operation_id();
}
id
}
}
const TX_SOURCE: TransactionSource = TransactionSource::External;
#[async_trait]
impl<Pool, Client> TransactionBroadcastApiServer for TransactionBroadcast<Pool, Client>
where
Pool: TransactionPool + Sync + Send + 'static,
Pool::Error: IntoPoolError,
<Pool::Block as BlockT>::Hash: Unpin,
Client: HeaderBackend<Pool::Block> + BlockchainEvents<Pool::Block> + Send + Sync + 'static,
{
async fn broadcast(&self, ext: &Extensions, bytes: Bytes) -> RpcResult<Option<String>> {
let pool = self.pool.clone();
let conn_id = ext
.get::<ConnectionId>()
.copied()
.expect("ConnectionId is always set by jsonrpsee; qed");
let id = self.generate_unique_id();
let Some(reserved_connection) = self.rpc_connections.reserve_space(conn_id) else {
return Ok(None)
};
let Some(reserved_identifier) = reserved_connection.register(id.clone()) else {
return Ok(None)
};
let Ok(decoded_extrinsic) = TransactionFor::<Pool>::decode(&mut &bytes[..]) else {
return Ok(Some(id));
};
let tx_hash = pool.hash_of(&decoded_extrinsic);
let mut best_block_import_stream: std::pin::Pin<
Box<dyn Stream<Item = <Pool::Block as BlockT>::Hash> + Send>,
> =
Box::pin(self.client.import_notification_stream().filter_map(
|notification| async move { notification.is_new_best.then_some(notification.hash) },
));
let broadcast_transaction_fut = async move {
let mut is_done = false;
while !is_done {
let Some(best_block_hash) =
last_stream_element(&mut best_block_import_stream).await
else {
return;
};
let mut stream = match pool
.submit_and_watch(best_block_hash, TX_SOURCE, decoded_extrinsic.clone())
.await
{
Ok(stream) => stream,
Err(e) => {
let Ok(pool_err) = e.into_pool_error() else { return };
if pool_err.is_retriable() {
continue
} else {
return;
}
},
};
while let Some(event) = stream.next().await {
if event.is_retriable() {
break;
}
if event.is_final() {
is_done = true;
break;
}
}
}
};
let (fut, handle) = futures::future::abortable(broadcast_transaction_fut);
let broadcast_ids = self.broadcast_ids.clone();
let drop_id = id.clone();
let pool = self.pool.clone();
let fut = fut.map(move |result| {
drop(reserved_identifier);
let Some(broadcast_state) = broadcast_ids.write().remove(&drop_id) else { return };
if result.is_ok() {
return
}
pool.remove_invalid(&[broadcast_state.tx_hash]);
});
{
let mut broadcast_ids = self.broadcast_ids.write();
broadcast_ids.insert(id.clone(), BroadcastState { handle, tx_hash });
}
sc_rpc::utils::spawn_subscription_task(&self.executor, fut);
Ok(Some(id))
}
async fn stop_broadcast(
&self,
ext: &Extensions,
operation_id: String,
) -> Result<(), ErrorBroadcast> {
let conn_id = ext
.get::<ConnectionId>()
.copied()
.expect("ConnectionId is always set by jsonrpsee; qed");
if !self.rpc_connections.contains_identifier(conn_id, &operation_id) {
return Err(ErrorBroadcast::InvalidOperationID)
}
let mut broadcast_ids = self.broadcast_ids.write();
let Some(broadcast_state) = broadcast_ids.remove(&operation_id) else {
return Err(ErrorBroadcast::InvalidOperationID)
};
broadcast_state.handle.abort();
Ok(())
}
}
async fn last_stream_element<S>(stream: &mut S) -> Option<S::Item>
where
S: Stream + Unpin,
{
let Some(mut element) = stream.next().await else { return None };
while let Some(next) = stream.next().now_or_never() {
let Some(next) = next else {
return None
};
element = next;
}
Some(element)
}
#[cfg(test)]
mod tests {
use super::*;
use tokio_stream::wrappers::ReceiverStream;
#[tokio::test]
async fn check_last_stream_element() {
let (tx, rx) = tokio::sync::mpsc::channel(16);
let mut stream = ReceiverStream::new(rx);
tx.send(1).await.unwrap();
assert_eq!(last_stream_element(&mut stream).await, Some(1));
tx.send(1).await.unwrap();
tx.send(2).await.unwrap();
tx.send(3).await.unwrap();
assert_eq!(last_stream_element(&mut stream).await, Some(3));
tx.send(1).await.unwrap();
tx.send(2).await.unwrap();
drop(tx);
assert_eq!(last_stream_element(&mut stream).await, None);
}
}