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, 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 inherent_data,
150 Default::default(),
151 std::time::Duration::from_secs(20),
152 None,
153 ))
154 .map(|r| r.block)
155 .expect("Proposing failed");
156
157 let elapsed = start.elapsed();
158
159 if mode == Mode::Profile {
160 std::thread::park_timeout(std::time::Duration::from_secs(1));
161 }
162
163 elapsed
164 }
165}
166
167#[derive(Clone, Debug)]
168pub struct PoolTransaction {
169 data: Arc<OpaqueExtrinsic>,
170 hash: node_primitives::Hash,
171}
172
173impl From<OpaqueExtrinsic> for PoolTransaction {
174 fn from(e: OpaqueExtrinsic) -> Self {
175 PoolTransaction { data: Arc::from(e), hash: node_primitives::Hash::zero() }
176 }
177}
178
179impl sc_transaction_pool_api::InPoolTransaction for PoolTransaction {
180 type Transaction = Arc<OpaqueExtrinsic>;
181 type Hash = node_primitives::Hash;
182
183 fn data(&self) -> &Self::Transaction {
184 &self.data
185 }
186
187 fn hash(&self) -> &Self::Hash {
188 &self.hash
189 }
190
191 fn priority(&self) -> &u64 {
192 unimplemented!()
193 }
194
195 fn longevity(&self) -> &u64 {
196 unimplemented!()
197 }
198
199 fn requires(&self) -> &[Vec<u8>] {
200 unimplemented!()
201 }
202
203 fn provides(&self) -> &[Vec<u8>] {
204 unimplemented!()
205 }
206
207 fn is_propagable(&self) -> bool {
208 unimplemented!()
209 }
210}
211
212#[derive(Clone, Debug)]
213pub struct Transactions(Vec<Arc<PoolTransaction>>);
214pub struct TransactionsIterator(std::vec::IntoIter<Arc<PoolTransaction>>);
215
216impl Iterator for TransactionsIterator {
217 type Item = Arc<PoolTransaction>;
218
219 fn next(&mut self) -> Option<Self::Item> {
220 self.0.next()
221 }
222}
223
224impl ReadyTransactions for TransactionsIterator {
225 fn report_invalid(&mut self, _tx: &Self::Item) {}
226}
227
228#[async_trait]
229impl sc_transaction_pool_api::TransactionPool for Transactions {
230 type Block = Block;
231 type Hash = node_primitives::Hash;
232 type InPoolTransaction = PoolTransaction;
233 type Error = sc_transaction_pool_api::error::Error;
234
235 async fn submit_at(
237 &self,
238 _at: Self::Hash,
239 _source: TransactionSource,
240 _xts: Vec<TransactionFor<Self>>,
241 ) -> Result<Vec<Result<node_primitives::Hash, Self::Error>>, Self::Error> {
242 unimplemented!()
243 }
244
245 async fn submit_one(
247 &self,
248 _at: Self::Hash,
249 _source: TransactionSource,
250 _xt: TransactionFor<Self>,
251 ) -> Result<TxHash<Self>, Self::Error> {
252 unimplemented!()
253 }
254
255 async fn submit_and_watch(
256 &self,
257 _at: Self::Hash,
258 _source: TransactionSource,
259 _xt: TransactionFor<Self>,
260 ) -> Result<Pin<Box<TransactionStatusStreamFor<Self>>>, Self::Error> {
261 unimplemented!()
262 }
263
264 async fn ready_at(
265 &self,
266 _at: Self::Hash,
267 ) -> Box<dyn ReadyTransactions<Item = Arc<Self::InPoolTransaction>> + Send> {
268 Box::new(TransactionsIterator(self.0.clone().into_iter()))
269 }
270
271 fn ready(&self) -> Box<dyn ReadyTransactions<Item = Arc<Self::InPoolTransaction>> + Send> {
272 unimplemented!()
273 }
274
275 async fn report_invalid(
276 &self,
277 _at: Option<Self::Hash>,
278 _invalid_tx_errors: TxInvalidityReportMap<TxHash<Self>>,
279 ) -> Vec<Arc<Self::InPoolTransaction>> {
280 Default::default()
281 }
282
283 fn futures(&self) -> Vec<Self::InPoolTransaction> {
284 unimplemented!()
285 }
286
287 fn status(&self) -> PoolStatus {
288 unimplemented!()
289 }
290
291 fn import_notification_stream(&self) -> ImportNotificationStream<TxHash<Self>> {
292 unimplemented!()
293 }
294
295 fn on_broadcasted(&self, _propagations: HashMap<TxHash<Self>, Vec<String>>) {
296 unimplemented!()
297 }
298
299 fn hash_of(&self, _xt: &TransactionFor<Self>) -> TxHash<Self> {
300 unimplemented!()
301 }
302
303 fn ready_transaction(&self, _hash: &TxHash<Self>) -> Option<Arc<Self::InPoolTransaction>> {
304 unimplemented!()
305 }
306
307 async fn ready_at_with_timeout(
308 &self,
309 _at: Self::Hash,
310 _timeout: std::time::Duration,
311 ) -> Box<dyn ReadyTransactions<Item = Arc<Self::InPoolTransaction>> + Send> {
312 unimplemented!()
313 }
314}