Skip to content
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
69 commits
Select commit Hold shift + click to select a range
7ee1652
tokio rwlock + sync code bridge
michalkucharczyk May 14, 2025
2153a5d
wip: new async trackedmap
michalkucharczyk May 15, 2025
32caa5e
report_invalid is async now
michalkucharczyk May 16, 2025
2650303
clean-up + HRTB fun
michalkucharczyk May 16, 2025
b2f6764
debug_assert enabled
michalkucharczyk May 19, 2025
d6418fb
sync <> async bridghe + todos cleanup
michalkucharczyk May 19, 2025
d4275bf
rename
michalkucharczyk May 19, 2025
d0e28a3
tracked_map: removed unused methods
michalkucharczyk May 19, 2025
6d5c3e9
transaction-network: consts updated
michalkucharczyk Mar 4, 2025
a507ff8
FullChainApi: async_trait used, tokio locking primitives
michalkucharczyk May 21, 2025
8c71aaf
ChainAPi: async_trait + fixes
michalkucharczyk May 21, 2025
f3292bb
tx_mem_pool: limit adjusted to x2
michalkucharczyk May 21, 2025
7c57cd8
view_store: most_recent_view is a ref to view now
michalkucharczyk May 21, 2025
d563da9
view_store: apply_pending_tx_replacements bug fix
michalkucharczyk May 21, 2025
9ead46d
debug levels adjusted
michalkucharczyk May 21, 2025
74dafae
fatp: most_recent_view is a view ref
michalkucharczyk May 21, 2025
9cbffa2
VadlidationFuture removed
michalkucharczyk May 21, 2025
c1570e3
fatp: self review cleanup
michalkucharczyk May 21, 2025
4870135
tests: blocking tasks spawned
michalkucharczyk May 21, 2025
1cf3616
view_store: doc
michalkucharczyk May 21, 2025
6caa9d8
sliding_stat helper added
michalkucharczyk May 23, 2025
cf1f050
fatp: stats added
michalkucharczyk May 23, 2025
1b71082
fatp: attempt_transaction_replacement_inner_inner -> post_attempt_tra…
michalkucharczyk May 23, 2025
e8ac935
submit_and_watch + submit_at -> inner versions
michalkucharczyk May 23, 2025
addf0de
dropped stats
michalkucharczyk May 26, 2025
b025e5c
common: validate tx api stats
michalkucharczyk May 27, 2025
35d1097
more stats added
michalkucharczyk May 27, 2025
4d66dfc
fix
michalkucharczyk May 27, 2025
69dfbc3
instrument macro added
michalkucharczyk May 27, 2025
48fa685
debugs
michalkucharczyk May 27, 2025
0f29287
ChainApi: ValidateTransactionPriority added
michalkucharczyk May 29, 2025
ac8feb3
transaction-network: consts updated - 2
michalkucharczyk May 30, 2025
860ed1f
tx_mem_pool: limit multiplier removed
michalkucharczyk May 30, 2025
5ebd88f
doc fix
michalkucharczyk May 30, 2025
2c6e0c5
Revert "transaction-network: consts updated - 2"
michalkucharczyk May 30, 2025
045bc6d
Revert "transaction-network: consts updated"
michalkucharczyk May 30, 2025
1387f9f
Merge remote-tracking branch 'origin/master' into mku-txpool-limits-fix
michalkucharczyk Jun 2, 2025
113bf22
post merge fix
michalkucharczyk Jun 2, 2025
e963dba
Cargo.lock
michalkucharczyk Jun 2, 2025
abd9a58
fatp: ready_at_light: better debug
michalkucharczyk Jun 3, 2025
0bf0b96
txpoolstat target added
michalkucharczyk Jun 6, 2025
1e7cbb3
mempool: send to view is now throttled
michalkucharczyk Jun 12, 2025
5f1bacc
maintain queue is used for revalidation / pending replacements
michalkucharczyk Jun 12, 2025
a25d50b
revalidation: debugs
michalkucharczyk Jun 12, 2025
030a857
Apply suggestions from code review
michalkucharczyk Jun 12, 2025
b11cf8e
Merge remote-tracking branch 'origin/master' into mku-txpool-limits-fix
michalkucharczyk Jun 12, 2025
90c54c2
Revert "report_invalid is async now"
michalkucharczyk Jun 12, 2025
a7e70e0
Update from github-actions[bot] running command 'prdoc --bump minor -…
github-actions[bot] Jun 12, 2025
2ef575d
Update prdoc/pr_8596.prdoc
michalkucharczyk Jun 12, 2025
0714273
Update prdoc/pr_8596.prdoc
michalkucharczyk Jun 12, 2025
71c5ce7
Update from github-actions[bot] running command 'fmt'
github-actions[bot] Jun 12, 2025
48eed5f
fix
michalkucharczyk Jun 12, 2025
86be44a
clippy happy now
michalkucharczyk Jun 12, 2025
2b36584
Revert "TransactionPool::ChainApi is now async"
michalkucharczyk Jun 17, 2025
ad943a8
format
michalkucharczyk Jun 17, 2025
5eb0413
ValidateTransactionPriority: doc
michalkucharczyk Jun 18, 2025
8201098
tx_mem_pool_map: naming fixed
michalkucharczyk Jun 18, 2025
870147a
fixing ChainApi revert
michalkucharczyk Jun 18, 2025
be46fff
tx_mem_pool_map: derive(Ord,PartialOrd)
michalkucharczyk Jun 18, 2025
67ee638
spelling
michalkucharczyk Jun 18, 2025
0dcb0ac
fmt
michalkucharczyk Jun 24, 2025
dab9113
comment added: 8912
michalkucharczyk Jun 24, 2025
ad3c17e
todo comment removed
michalkucharczyk Jun 24, 2025
9da6712
Merge branch 'master' into mku-txpool-limits-fix
michalkucharczyk Jun 24, 2025
13c7cc6
txmempool: sync bridge note added
michalkucharczyk Jun 24, 2025
a069036
rust doc
michalkucharczyk Jun 24, 2025
2aa0670
Merge remote-tracking branch 'origin/master' into mku-txpool-limits-fix
michalkucharczyk Jun 24, 2025
1bd13ed
random md fixed
michalkucharczyk Jun 24, 2025
4fc51f5
Merge branch 'master' into mku-txpool-limits-fix
michalkucharczyk Jun 24, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion substrate/client/basic-authorship/src/basic_authorship.rs
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,9 @@ where
);
}

self.transaction_pool.report_invalid(Some(self.parent_hash), unqueue_invalid);
self.transaction_pool
.report_invalid(Some(self.parent_hash), unqueue_invalid)
.await;
Ok(end_reason)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ impl NotificationProtocolConfig {
.with_handshake(handshake.map_or(vec![1], |handshake| (*handshake).to_vec()))
.with_max_size(max_notification_size as usize)
.with_auto_accept_inbound(true)
.with_sync_channel_size(20 * 2048)
Comment thread
michalkucharczyk marked this conversation as resolved.
Outdated
.with_fallback_names(fallback_names.into_iter().map(From::from).collect())
.build();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ const LOG_TARGET: &str = "sub-libp2p::notification::handler";
pub(crate) const ASYNC_NOTIFICATIONS_BUFFER_SIZE: usize = 8;

/// Number of pending notifications in synchronous contexts.
const SYNC_NOTIFICATIONS_BUFFER_SIZE: usize = 2048;
const SYNC_NOTIFICATIONS_BUFFER_SIZE: usize = 20 * 2048;
Comment thread
michalkucharczyk marked this conversation as resolved.
Outdated

/// Maximum duration to open a substream and receive the handshake message. After that, we
/// consider that we failed to open the substream.
Expand Down
4 changes: 2 additions & 2 deletions substrate/client/network/transactions/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@ pub(crate) const PROPAGATE_TIMEOUT: time::Duration = time::Duration::from_millis
/// Maximum number of known transaction hashes to keep for a peer.
///
/// This should be approx. 2 blocks full of transactions for the network to function properly.
pub(crate) const MAX_KNOWN_TRANSACTIONS: usize = 10240; // ~300kb per peer + overhead.
pub(crate) const MAX_KNOWN_TRANSACTIONS: usize = 8 * 10240; // ~300kb per peer + overhead.

/// Maximum allowed size for a transactions notification.
pub(crate) const MAX_TRANSACTIONS_SIZE: u64 = MAX_RESPONSE_SIZE;

/// Maximum number of transaction validation request we keep at any moment.
pub(crate) const MAX_PENDING_TRANSACTIONS: usize = 8192;
pub(crate) const MAX_PENDING_TRANSACTIONS: usize = 8 * 8192;
Comment thread
michalkucharczyk marked this conversation as resolved.
Outdated

/// Result of the transaction import.
#[derive(Clone, Copy, Debug)]
Expand Down
2 changes: 1 addition & 1 deletion substrate/client/rpc-api/src/author/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ pub trait AuthorApi<Hash, BlockHash> {

/// Remove given extrinsic from the pool and temporarily ban it to prevent reimporting.
#[method(name = "author_removeExtrinsic", with_extensions)]
fn remove_extrinsic(
async fn remove_extrinsic(
&self,
bytes_or_hash: Vec<hash::ExtrinsicOrHash<Hash>>,
) -> Result<Vec<Hash>, Error>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,20 +226,22 @@ where
let pool = self.pool.clone();
// The future expected by the executor must be `Future<Output = ()>` instead of
// `Future<Output = Result<(), Aborted>>`.
let fut = fut.map(move |result| {
// Connection space is cleaned when this object is dropped.
drop(reserved_identifier);
let fut = fut.then(move |result| {
async move {
// Connection space is cleaned when this object is dropped.
drop(reserved_identifier);

// Remove the entry from the broadcast IDs map.
let Some(broadcast_state) = broadcast_ids.write().remove(&drop_id) else { return };
// Remove the entry from the broadcast IDs map.
let Some(broadcast_state) = broadcast_ids.write().remove(&drop_id) else { return };

// The broadcast was not stopped.
if result.is_ok() {
return
}
// The broadcast was not stopped.
if result.is_ok() {
return
}

// Best effort pool removal (tx can already be finalized).
pool.report_invalid(None, [(broadcast_state.tx_hash, None)].into());
// Best effort pool removal (tx can already be finalized).
pool.report_invalid(None, [(broadcast_state.tx_hash, None)].into()).await;
}
});

// Keep track of this entry and the abortable handle.
Expand Down
3 changes: 2 additions & 1 deletion substrate/client/rpc/src/author/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ where
Ok(self.pool.ready().map(|tx| tx.data().encode().into()).collect())
}

fn remove_extrinsic(
async fn remove_extrinsic(
&self,
ext: &Extensions,
bytes_or_hash: Vec<hash::ExtrinsicOrHash<TxHash<P>>>,
Expand All @@ -173,6 +173,7 @@ where
Ok(self
.pool
.report_invalid(None, hashes)
.await
.into_iter()
.map(|tx| tx.hash().clone())
.collect())
Expand Down
1 change: 1 addition & 0 deletions substrate/client/transaction-pool/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ sp-crypto-hashing = { workspace = true, default-features = true }
sp-runtime = { workspace = true, default-features = true }
sp-tracing = { workspace = true, default-features = true }
sp-transaction-pool = { workspace = true, default-features = true }
test-case = "3.3.1"
Comment thread
michalkucharczyk marked this conversation as resolved.
Outdated
thiserror = { workspace = true }
tokio = { workspace = true, default-features = true, features = ["macros", "time"] }
tokio-stream = { workspace = true }
Expand Down
2 changes: 1 addition & 1 deletion substrate/client/transaction-pool/api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ pub trait TransactionPool: Send + Sync {
/// occurred.
///
/// Function returns the transactions actually removed from the pool.
fn report_invalid(
async fn report_invalid(
&self,
at: Option<<Self::Block as BlockT>::Hash>,
invalid_tx_errors: TxInvalidityReportMap<TxHash<Self>>,
Expand Down
63 changes: 29 additions & 34 deletions substrate/client/transaction-pool/src/common/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,9 @@
//! Chain api required for the transaction pool.

use crate::LOG_TARGET;
use async_trait::async_trait;
use codec::Encode;
use futures::{
channel::{mpsc, oneshot},
future::{ready, Future, FutureExt, Ready},
lock::Mutex,
SinkExt, StreamExt,
};
use std::{marker::PhantomData, pin::Pin, sync::Arc};

use futures::future::{ready, Future, FutureExt, Ready};
use prometheus_endpoint::Registry as PrometheusRegistry;
use sc_client_api::{blockchain::HeaderBackend, BlockBackend};
use sp_api::{ApiExt, ProvideRuntimeApi};
Expand All @@ -39,13 +33,15 @@ use sp_runtime::{
transaction_validity::{TransactionSource, TransactionValidity},
};
use sp_transaction_pool::runtime_api::TaggedTransactionQueue;
use std::{marker::PhantomData, pin::Pin, sync::Arc, time::Instant};
use tokio::sync::{mpsc, oneshot, Mutex};

use super::{
error::{self, Error},
metrics::{ApiMetrics, ApiMetricsExt},
};
use crate::graph;
use tracing::{trace, warn};
use tracing::{instrument, trace, warn, Level};

/// The transaction pool logic for full client.
pub struct FullChainApi<Client, Block> {
Expand All @@ -66,7 +62,7 @@ fn spawn_validation_pool_task(
Some("transaction-pool"),
async move {
loop {
let task = receiver.lock().await.next().await;
let task = receiver.lock().await.recv().await;
match task {
None => return,
Some(task) => task.await,
Expand Down Expand Up @@ -96,7 +92,7 @@ impl<Client, Block> FullChainApi<Client, Block> {
Ok(api) => Some(Arc::new(api)),
});

let (sender, receiver) = mpsc::channel(0);
let (sender, receiver) = mpsc::channel(1);

let receiver = Arc::new(Mutex::new(receiver));
spawn_validation_pool_task("transaction-pool-task-0", receiver.clone(), spawner);
Expand All @@ -106,6 +102,7 @@ impl<Client, Block> FullChainApi<Client, Block> {
}
}

#[async_trait]
impl<Client, Block> graph::ChainApi for FullChainApi<Client, Block>
where
Block: BlockT,
Expand All @@ -127,40 +124,38 @@ where
ready(self.client.block_body(hash).map_err(error::Error::from))
}

fn validate_transaction(
#[instrument(level = Level::TRACE, skip_all, target = "txpool", name = "api::validate_transaction")]
async fn validate_transaction(
&self,
at: <Self::Block as BlockT>::Hash,
source: TransactionSource,
uxt: graph::ExtrinsicFor<Self>,
) -> Self::ValidationFuture {
) -> Result<TransactionValidity, Self::Error> {
let (tx, rx) = oneshot::channel();
let client = self.client.clone();
let mut validation_pool = self.validation_pool.clone();
let validation_pool = self.validation_pool.clone();
let metrics = self.metrics.clone();

async move {
metrics.report(|m| m.validations_scheduled.inc());
metrics.report(|m| m.validations_scheduled.inc());

{
validation_pool
.send(
async move {
let res = validate_transaction_blocking(&*client, at, source, uxt);
let _ = tx.send(res);
metrics.report(|m| m.validations_finished.inc());
}
.boxed(),
)
.await
.map_err(|e| Error::RuntimeApi(format!("Validation pool down: {:?}", e)))?;
}
{
validation_pool
.send(
async move {
let res = validate_transaction_blocking(&*client, at, source, uxt);
let _ = tx.send(res);
metrics.report(|m| m.validations_finished.inc());
}
.boxed(),
)
.await
.map_err(|e| Error::RuntimeApi(format!("Validation pool down: {:?}", e)))?;
}

match rx.await {
Ok(r) => r,
Err(_) => Err(Error::RuntimeApi("Validation was canceled".into())),
}
match rx.await {
Ok(r) => r,
Err(_) => Err(Error::RuntimeApi("Validation was canceled".into())),
}
.boxed()
}

/// Validates a transaction by calling into the runtime.
Expand Down
8 changes: 5 additions & 3 deletions substrate/client/transaction-pool/src/common/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
//! Testing related primitives for internal usage in this crate.

use crate::graph::{BlockHash, ChainApi, ExtrinsicFor, NumberFor, RawExtrinsicFor};
use async_trait::async_trait;
use codec::Encode;
use parking_lot::Mutex;
use sc_transaction_pool_api::error;
Expand Down Expand Up @@ -66,19 +67,20 @@ impl TestApi {
}
}

#[async_trait]
impl ChainApi for TestApi {
type Block = Block;
type Error = error::Error;
type ValidationFuture = futures::future::Ready<error::Result<TransactionValidity>>;
type BodyFuture = futures::future::Ready<error::Result<Option<Vec<Extrinsic>>>>;

/// Verify extrinsic at given block.
fn validate_transaction(
async fn validate_transaction(
&self,
at: <Self::Block as BlockT>::Hash,
_source: TransactionSource,
uxt: ExtrinsicFor<Self>,
) -> Self::ValidationFuture {
) -> Result<TransactionValidity, error::Error> {
let uxt = (*uxt).clone();
self.validation_requests.lock().push(uxt.clone());
let hash = self.hash_and_length(&uxt).0;
Expand Down Expand Up @@ -155,7 +157,7 @@ impl ChainApi for TestApi {
_ => unimplemented!(),
};

futures::future::ready(Ok(res))
Ok(res)
}

fn validate_transaction_blocking(
Expand Down
Loading