1use std::{borrow::Cow, collections::HashMap, pin::Pin, sync::Arc};
28
29use async_trait::async_trait;
30use node_primitives::Block;
31use node_testing::bench::{BenchDb, BlockType, DatabaseType, KeyTypes};
32use sc_transaction_pool_api::{
33 ImportNotificationStream, PoolStatus, ReadyTransactions, TransactionFor, TransactionSource,
34 TransactionStatusStreamFor, TxHash, TxInvalidityReportMap,
35};
36use sp_consensus::{Environment, ProposeArgs, Proposer};
37use sp_inherents::InherentDataProvider;
38use sp_runtime::OpaqueExtrinsic;
39
40use crate::{
41 common::SizeType,
42 core::{self, Mode, Path},
43};
44
45pub struct ConstructionBenchmarkDescription {
46 pub key_types: KeyTypes,
47 pub block_type: BlockType,
48 pub size: SizeType,
49 pub database_type: DatabaseType,
50}
51
52pub struct ConstructionBenchmark {
53 database: BenchDb,
54 transactions: Transactions,
55}
56
57impl core::BenchmarkDescription for ConstructionBenchmarkDescription {
58 fn path(&self) -> Path {
59 let mut path = Path::new(&["node", "proposer"]);
60
61 match self.key_types {
62 KeyTypes::Sr25519 => path.push("sr25519"),
63 KeyTypes::Ed25519 => path.push("ed25519"),
64 }
65
66 match self.block_type {
67 BlockType::RandomTransfersKeepAlive => path.push("transfer"),
68 BlockType::RandomTransfersReaping => path.push("transfer_reaping"),
69 BlockType::Noop => path.push("noop"),
70 }
71
72 match self.database_type {
73 DatabaseType::RocksDb => path.push("rocksdb"),
74 DatabaseType::ParityDb => path.push("paritydb"),
75 }
76
77 path.push(&format!("{}", self.size));
78
79 path
80 }
81
82 fn setup(self: Box<Self>) -> Box<dyn core::Benchmark> {
83 let mut extrinsics: Vec<Arc<PoolTransaction>> = Vec::new();
84
85 let mut bench_db = BenchDb::with_key_types(self.database_type, 50_000, self.key_types);
86
87 let client = bench_db.client();
88
89 let content_type = self.block_type.to_content(self.size.transactions());
90 for transaction in bench_db.block_content(content_type, &client) {
91 extrinsics.push(Arc::new(transaction.into()));
92 }
93
94 Box::new(ConstructionBenchmark {
95 database: bench_db,
96 transactions: Transactions(extrinsics),
97 })
98 }
99
100 fn name(&self) -> Cow<'static, str> {
101 format!(
102 "Block construction ({:?}/{}, {:?} backend)",
103 self.block_type, self.size, self.database_type,
104 )
105 .into()
106 }
107}
108
109impl core::Benchmark for ConstructionBenchmark {
110 fn run(&mut self, mode: Mode) -> std::time::Duration {
111 let context = self.database.create_context();
112
113 let _ = context
114 .client
115 .runtime_version_at(context.client.chain_info().genesis_hash)
116 .expect("Failed to get runtime version")
117 .spec_version;
118
119 if mode == Mode::Profile {
120 std::thread::park_timeout(std::time::Duration::from_secs(3));
121 }
122
123 let mut proposer_factory = sc_basic_authorship::ProposerFactory::new(
124 context.spawn_handle.clone(),
125 context.client.clone(),
126 self.transactions.clone().into(),
127 None,
128 None,
129 );
130 let timestamp_provider = sp_timestamp::InherentDataProvider::from_system_time();
131
132 let start = std::time::Instant::now();
133
134 let proposer = futures::executor::block_on(
135 proposer_factory.init(
136 &context
137 .client
138 .header(context.client.chain_info().genesis_hash)
139 .expect("Database error querying block #0")
140 .expect("Block #0 should exist"),
141 ),
142 )
143 .expect("Proposer initialization failed");
144
145 let inherent_data = futures::executor::block_on(timestamp_provider.create_inherent_data())
146 .expect("Create inherent data failed");
147 let _block = futures::executor::block_on(Proposer::propose(
148 proposer,
149 ProposeArgs {
150 inherent_data,
151 inherent_digests: Default::default(),
152 max_duration: std::time::Duration::from_secs(20),
153 ..Default::default()
154 },
155 ))
156 .map(|r| r.block)
157 .expect("Proposing failed");
158
159 let elapsed = start.elapsed();
160
161 if mode == Mode::Profile {
162 std::thread::park_timeout(std::time::Duration::from_secs(1));
163 }
164
165 elapsed
166 }
167}
168
169#[derive(Clone, Debug)]
170pub struct PoolTransaction {
171 data: Arc<OpaqueExtrinsic>,
172 hash: node_primitives::Hash,
173}
174
175impl From<OpaqueExtrinsic> for PoolTransaction {
176 fn from(e: OpaqueExtrinsic) -> Self {
177 PoolTransaction { data: Arc::from(e), hash: node_primitives::Hash::zero() }
178 }
179}
180
181impl sc_transaction_pool_api::InPoolTransaction for PoolTransaction {
182 type Transaction = Arc<OpaqueExtrinsic>;
183 type Hash = node_primitives::Hash;
184
185 fn data(&self) -> &Self::Transaction {
186 &self.data
187 }
188
189 fn hash(&self) -> &Self::Hash {
190 &self.hash
191 }
192
193 fn priority(&self) -> &u64 {
194 unimplemented!()
195 }
196
197 fn longevity(&self) -> &u64 {
198 unimplemented!()
199 }
200
201 fn requires(&self) -> &[Vec<u8>] {
202 unimplemented!()
203 }
204
205 fn provides(&self) -> &[Vec<u8>] {
206 unimplemented!()
207 }
208
209 fn is_propagable(&self) -> bool {
210 unimplemented!()
211 }
212}
213
214#[derive(Clone, Debug)]
215pub struct Transactions(Vec<Arc<PoolTransaction>>);
216pub struct TransactionsIterator(std::vec::IntoIter<Arc<PoolTransaction>>);
217
218impl Iterator for TransactionsIterator {
219 type Item = Arc<PoolTransaction>;
220
221 fn next(&mut self) -> Option<Self::Item> {
222 self.0.next()
223 }
224}
225
226impl ReadyTransactions for TransactionsIterator {
227 fn report_invalid(&mut self, _tx: &Self::Item) {}
228}
229
230#[async_trait]
231impl sc_transaction_pool_api::TransactionPool for Transactions {
232 type Block = Block;
233 type Hash = node_primitives::Hash;
234 type InPoolTransaction = PoolTransaction;
235 type Error = sc_transaction_pool_api::error::Error;
236
237 async fn submit_at(
239 &self,
240 _at: Self::Hash,
241 _source: TransactionSource,
242 _xts: Vec<TransactionFor<Self>>,
243 ) -> Result<Vec<Result<node_primitives::Hash, Self::Error>>, Self::Error> {
244 unimplemented!()
245 }
246
247 async fn submit_one(
249 &self,
250 _at: Self::Hash,
251 _source: TransactionSource,
252 _xt: TransactionFor<Self>,
253 ) -> Result<TxHash<Self>, Self::Error> {
254 unimplemented!()
255 }
256
257 async fn submit_and_watch(
258 &self,
259 _at: Self::Hash,
260 _source: TransactionSource,
261 _xt: TransactionFor<Self>,
262 ) -> Result<Pin<Box<TransactionStatusStreamFor<Self>>>, Self::Error> {
263 unimplemented!()
264 }
265
266 async fn ready_at(
267 &self,
268 _at: Self::Hash,
269 ) -> Box<dyn ReadyTransactions<Item = Arc<Self::InPoolTransaction>> + Send> {
270 Box::new(TransactionsIterator(self.0.clone().into_iter()))
271 }
272
273 fn ready(&self) -> Box<dyn ReadyTransactions<Item = Arc<Self::InPoolTransaction>> + Send> {
274 unimplemented!()
275 }
276
277 async fn report_invalid(
278 &self,
279 _at: Option<Self::Hash>,
280 _invalid_tx_errors: TxInvalidityReportMap<TxHash<Self>>,
281 ) -> Vec<Arc<Self::InPoolTransaction>> {
282 Default::default()
283 }
284
285 fn futures(&self) -> Vec<Self::InPoolTransaction> {
286 unimplemented!()
287 }
288
289 fn status(&self) -> PoolStatus {
290 unimplemented!()
291 }
292
293 fn import_notification_stream(&self) -> ImportNotificationStream<TxHash<Self>> {
294 unimplemented!()
295 }
296
297 fn on_broadcasted(&self, _propagations: HashMap<TxHash<Self>, Vec<String>>) {
298 unimplemented!()
299 }
300
301 fn hash_of(&self, _xt: &TransactionFor<Self>) -> TxHash<Self> {
302 unimplemented!()
303 }
304
305 fn ready_transaction(&self, _hash: &TxHash<Self>) -> Option<Arc<Self::InPoolTransaction>> {
306 unimplemented!()
307 }
308
309 async fn ready_at_with_timeout(
310 &self,
311 _at: Self::Hash,
312 _timeout: std::time::Duration,
313 ) -> Box<dyn ReadyTransactions<Item = Arc<Self::InPoolTransaction>> + Send> {
314 unimplemented!()
315 }
316}