// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see .
//! API implementation for broadcasting transactions.
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;
/// An API for transaction RPC calls.
pub struct TransactionBroadcast {
/// Substrate client.
client: Arc,
/// Transactions pool.
pool: Arc,
/// Executor to spawn subscriptions.
executor: SubscriptionTaskExecutor,
/// The broadcast operation IDs.
broadcast_ids: Arc>>>,
/// Keep track of how many concurrent operations are active for each connection.
rpc_connections: RpcConnections,
}
/// The state of a broadcast operation.
struct BroadcastState {
/// Handle to abort the running future that broadcasts the transaction.
handle: AbortHandle,
/// Associated tx hash.
tx_hash: ::Hash,
}
impl TransactionBroadcast {
/// Creates a new [`TransactionBroadcast`].
pub fn new(
client: Arc,
pool: Arc,
executor: SubscriptionTaskExecutor,
max_transactions_per_connection: usize,
) -> Self {
TransactionBroadcast {
client,
pool,
executor,
broadcast_ids: Default::default(),
rpc_connections: RpcConnections::new(max_transactions_per_connection),
}
}
/// Generate an unique operation ID for the `transaction_broadcast` RPC method.
pub fn generate_unique_id(&self) -> String {
let generate_operation_id = || {
// The length of the operation ID.
const OPERATION_ID_LEN: usize = 16;
rand::thread_rng()
.sample_iter(Alphanumeric)
.take(OPERATION_ID_LEN)
.map(char::from)
.collect::()
};
let mut id = generate_operation_id();
let broadcast_ids = self.broadcast_ids.read();
while broadcast_ids.contains_key(&id) {
id = generate_operation_id();
}
id
}
}
/// Currently we treat all RPC transactions as externals.
///
/// Possibly in the future we could allow opt-in for special treatment
/// of such transactions, so that the block authors can inject
/// some unique transactions via RPC and have them included in the pool.
const TX_SOURCE: TransactionSource = TransactionSource::External;
#[async_trait]
impl TransactionBroadcastApiServer for TransactionBroadcast
where
Pool: TransactionPool + Sync + Send + 'static,
Pool::Error: IntoPoolError,
::Hash: Unpin,
Client: HeaderBackend + BlockchainEvents + Send + Sync + 'static,
{
async fn broadcast(&self, ext: &Extensions, bytes: Bytes) -> RpcResult