Skip to main content

iota_single_node_benchmark/
benchmark_context.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::{
6    collections::{BTreeMap, HashMap},
7    ops::Deref,
8    sync::Arc,
9};
10
11use futures::{StreamExt, stream::FuturesUnordered};
12use iota_config::node::RunWithRange;
13use iota_core::authority::shared_object_version_manager::AssignedTxAndVersions;
14use iota_sdk_types::{Address, ObjectId, ObjectReference, TransactionEffects, Version};
15use iota_test_transaction_builder::PublishData;
16use iota_types::{
17    effects::TransactionEffectsAPI,
18    messages_grpc::HandleTransactionResponse,
19    mock_checkpoint_builder::ValidatorKeypairProvider,
20    transaction::{
21        CertifiedTransaction, SenderSignedTransactionAPI, SignedTransaction, TransactionEnvelope,
22        VerifiedTransaction,
23    },
24};
25use tracing::{info, warn};
26
27use crate::{
28    command::Component,
29    mock_account::{Account, batch_create_account_and_gas},
30    mock_storage::InMemoryObjectStore,
31    single_node::SingleValidator,
32    tx_generator::{RootObjectCreateTxGenerator, SharedObjectCreateTxGenerator, TxGenerator},
33    workload::Workload,
34};
35
36pub struct BenchmarkContext {
37    validator: SingleValidator,
38    user_accounts: BTreeMap<Address, Account>,
39    admin_account: Account,
40    benchmark_component: Component,
41}
42
43impl BenchmarkContext {
44    pub(crate) async fn new(
45        workload: Workload,
46        benchmark_component: Component,
47        print_sample_tx: bool,
48    ) -> Self {
49        // Reserve 1 account for package publishing.
50        let mut num_accounts = workload.num_accounts() + 1;
51        if print_sample_tx {
52            // Reserver another one to generate a sample transaction.
53            num_accounts += 1;
54        }
55        let gas_object_num_per_account = workload.gas_object_num_per_account();
56        let total = num_accounts * gas_object_num_per_account;
57
58        info!(
59            "Creating {} accounts and {} gas objects",
60            num_accounts, total
61        );
62        let (mut user_accounts, genesis_gas_objects) =
63            batch_create_account_and_gas(num_accounts, gas_object_num_per_account).await;
64        assert_eq!(genesis_gas_objects.len() as u64, total);
65        let (_, admin_account) = user_accounts.pop_last().unwrap();
66
67        info!("Initializing validator");
68        let validator = SingleValidator::new(&genesis_gas_objects[..], benchmark_component).await;
69
70        Self {
71            validator,
72            user_accounts,
73            admin_account,
74            benchmark_component,
75        }
76    }
77
78    pub(crate) fn validator(&self) -> SingleValidator {
79        self.validator.clone()
80    }
81
82    pub(crate) async fn publish_package(&mut self, publish_data: PublishData) -> ObjectReference {
83        let mut gas_objects = self.admin_account.gas_objects.deref().clone();
84        let (package, updated_gas) = self
85            .validator
86            .publish_package(
87                publish_data,
88                self.admin_account.sender,
89                &self.admin_account.private_key,
90                gas_objects[0],
91            )
92            .await;
93        gas_objects[0] = updated_gas;
94        self.admin_account.gas_objects = Arc::new(gas_objects);
95        package
96    }
97
98    /// In order to benchmark transactions that can read dynamic fields, we must
99    /// first create a root object with dynamic fields for each account
100    /// address.
101    pub(crate) async fn preparing_dynamic_fields(
102        &mut self,
103        move_package: ObjectId,
104        num_dynamic_fields: u64,
105    ) -> HashMap<Address, ObjectReference> {
106        let mut root_objects = HashMap::new();
107
108        if num_dynamic_fields == 0 {
109            return root_objects;
110        }
111
112        info!("Preparing root object with dynamic fields");
113        let root_object_create_transactions = self
114            .generate_transactions(Arc::new(RootObjectCreateTxGenerator::new(
115                move_package,
116                num_dynamic_fields,
117            )))
118            .await;
119        let results = self
120            .execute_raw_transactions(root_object_create_transactions)
121            .await;
122        let mut new_gas_objects = HashMap::new();
123        let cache_commit = self.validator().get_validator().get_cache_commit().clone();
124        for effects in results {
125            let batch =
126                cache_commit.build_db_batch(effects.epoch(), 0, &[*effects.transaction_digest()]);
127
128            cache_commit.commit_transaction_outputs(
129                effects.epoch(),
130                batch,
131                &[*effects.transaction_digest()],
132            );
133
134            let (owner, root_object) = effects
135                .created()
136                .into_iter()
137                .filter_map(|created| {
138                    created
139                        .owner()
140                        .as_opt_address()
141                        .map(|owner| (*owner, *created.reference()))
142                })
143                .next()
144                .unwrap();
145            root_objects.insert(owner, root_object);
146            let gas_object = *effects.gas_object().reference();
147            new_gas_objects.insert(gas_object.object_id, gas_object);
148        }
149        self.refresh_gas_objects(new_gas_objects);
150        info!("Finished preparing root object with dynamic fields");
151        root_objects
152    }
153
154    pub(crate) async fn prepare_shared_objects(
155        &mut self,
156        move_package: ObjectId,
157        num_shared_objects: usize,
158    ) -> Vec<(ObjectId, Version)> {
159        let mut shared_objects = Vec::new();
160
161        if num_shared_objects == 0 {
162            return shared_objects;
163        }
164
165        if matches!(
166            self.benchmark_component,
167            Component::ValidatorWithoutConsensus
168        ) {
169            warn!(
170                "Ignoring num_shared_objects {} parameter for Component::ValidatorWithoutConsensus",
171                num_shared_objects
172            );
173            return shared_objects;
174        }
175
176        assert!(num_shared_objects <= self.user_accounts.len());
177
178        info!("Preparing shared objects");
179        let generator = SharedObjectCreateTxGenerator::new(move_package);
180        let shared_object_create_transactions: Vec<_> = self
181            .user_accounts
182            .values()
183            .take(num_shared_objects)
184            .map(|account| generator.generate_tx(account.clone()))
185            .collect();
186        let results = self
187            .execute_raw_transactions(shared_object_create_transactions)
188            .await;
189        let mut new_gas_objects = HashMap::new();
190        let cache_commit = self.validator.get_validator().get_cache_commit();
191        for effects in results {
192            let shared_object = effects
193                .created()
194                .into_iter()
195                .filter_map(|created| {
196                    let oref = created.reference();
197                    if created.owner().is_shared() {
198                        Some((oref.object_id, oref.version))
199                    } else {
200                        None
201                    }
202                })
203                .next()
204                .unwrap();
205            shared_objects.push(shared_object);
206            let gas_object = *effects.gas_object().reference();
207            new_gas_objects.insert(gas_object.object_id, gas_object);
208            // Make sure to commit them to DB. This is needed by both the execution-only
209            // mode and the checkpoint-executor mode. For execution-only mode,
210            // we iterate through all live objects to construct the in memory
211            // object store, hence requiring these objects committed to DB.
212            // For checkpoint executor, in order to commit a checkpoint it is required
213            // previous versions of objects are already committed.
214            let batch =
215                cache_commit.build_db_batch(effects.epoch(), 0, &[*effects.transaction_digest()]);
216            cache_commit.commit_transaction_outputs(
217                effects.epoch(),
218                batch,
219                &[*effects.transaction_digest()],
220            );
221        }
222        self.refresh_gas_objects(new_gas_objects);
223        info!("Finished preparing shared objects");
224        shared_objects
225    }
226
227    pub(crate) async fn generate_transactions(
228        &self,
229        tx_generator: Arc<dyn TxGenerator>,
230    ) -> Vec<TransactionEnvelope> {
231        info!(
232            "{}: Creating {} transactions",
233            tx_generator.name(),
234            self.user_accounts.len()
235        );
236        let tasks: FuturesUnordered<_> = self
237            .user_accounts
238            .values()
239            .map(|account| {
240                let account = account.clone();
241                let tx_generator = tx_generator.clone();
242                tokio::spawn(async move { tx_generator.generate_tx(account) })
243            })
244            .collect();
245        let results: Vec<_> = tasks.collect().await;
246        results.into_iter().map(|r| r.unwrap()).collect()
247    }
248
249    pub(crate) async fn certify_transactions(
250        &self,
251        transactions: Vec<TransactionEnvelope>,
252        skip_signing: bool,
253    ) -> Vec<CertifiedTransaction> {
254        info!("Creating transaction certificates");
255        let tasks: FuturesUnordered<_> = transactions
256            .into_iter()
257            .map(|tx| {
258                let validator = self.validator();
259                tokio::spawn(async move {
260                    let committee = validator.get_committee();
261                    let validator_state = validator.get_validator();
262                    let sig = if skip_signing {
263                        SignedTransaction::sign(
264                            0,
265                            &tx,
266                            &*validator_state.secret,
267                            validator_state.name,
268                        )
269                    } else {
270                        let verified_tx = VerifiedTransaction::new_unchecked(tx.clone());
271                        validator_state
272                            .handle_transaction(validator.get_epoch_store(), verified_tx)
273                            .await
274                            .unwrap()
275                            .status
276                            .into_signed_for_testing()
277                    };
278                    CertifiedTransaction::new(tx.into_data(), vec![sig], committee).unwrap()
279                })
280            })
281            .collect();
282        let results: Vec<_> = tasks.collect().await;
283        results.into_iter().map(|r| r.unwrap()).collect()
284    }
285
286    pub(crate) async fn benchmark_transaction_execution(
287        &self,
288        transactions: Vec<CertifiedTransaction>,
289        assigned_versions: AssignedTxAndVersions,
290        print_sample_tx: bool,
291    ) {
292        let assigned_versions = assigned_versions.into_map();
293        if print_sample_tx {
294            // We must use remove(0) in case there are shared objects and the transactions
295            // must be executed in order.
296            self.execute_sample_transaction(transactions[0].clone())
297                .await;
298        }
299
300        let tx_count = transactions.len();
301        let start_time = std::time::Instant::now();
302        info!(
303            "Started executing {} transactions. You can now attach a profiler",
304            transactions.len()
305        );
306
307        let has_shared_object = transactions.iter().any(|tx| tx.contains_shared_object());
308        if has_shared_object {
309            // With shared objects, we must execute each transaction in order.
310            for transaction in transactions {
311                let key = transaction.key();
312                self.validator
313                    .execute_certificate(
314                        transaction,
315                        assigned_versions.get(&key).unwrap(),
316                        self.benchmark_component,
317                    )
318                    .await;
319            }
320        } else {
321            let tasks: FuturesUnordered<_> = transactions
322                .into_iter()
323                .map(|tx| {
324                    let validator = self.validator();
325                    let component = self.benchmark_component;
326                    tokio::spawn(async move {
327                        validator.execute_certificate(tx, &vec![], component).await
328                    })
329                })
330                .collect();
331            let results: Vec<_> = tasks.collect().await;
332            results.into_iter().for_each(|r| {
333                r.unwrap();
334            });
335        }
336
337        let elapsed = start_time.elapsed().as_millis() as f64 / 1000f64;
338        info!(
339            "Execution finished in {}s, TPS={}",
340            elapsed,
341            tx_count as f64 / elapsed
342        );
343    }
344
345    pub(crate) async fn benchmark_transaction_execution_in_memory(
346        &self,
347        transactions: Vec<CertifiedTransaction>,
348        assigned_versions: AssignedTxAndVersions,
349        print_sample_tx: bool,
350    ) {
351        if print_sample_tx {
352            self.execute_sample_transaction(transactions[0].clone())
353                .await;
354        }
355
356        let tx_count = transactions.len();
357        let in_memory_store = self.validator.create_in_memory_store();
358        let start_time = std::time::Instant::now();
359        info!(
360            "Started executing {} transactions. You can now attach a profiler",
361            transactions.len()
362        );
363
364        self.execute_transactions_in_memory(
365            in_memory_store.clone(),
366            transactions,
367            assigned_versions,
368        )
369        .await;
370
371        let elapsed = start_time.elapsed().as_millis() as f64 / 1000f64;
372        info!(
373            "Execution finished in {}s, TPS={}, number of DB object reads per transaction: {}",
374            elapsed,
375            tx_count as f64 / elapsed,
376            in_memory_store.get_num_object_reads() as f64 / tx_count as f64
377        );
378    }
379
380    /// Print out a sample transaction and its effects so that we can get a
381    /// rough idea what we are measuring.
382    async fn execute_sample_transaction(&self, sample_transaction: CertifiedTransaction) {
383        info!(
384            "Sample transaction digest={:?}: {:?}",
385            sample_transaction.digest(),
386            sample_transaction.data()
387        );
388        let effects = self
389            .validator()
390            .execute_dry_run(sample_transaction.into_unsigned())
391            .await;
392        info!("Sample effects: {:?}\n\n", effects);
393        assert!(effects.status().is_success());
394    }
395
396    /// Benchmark parallel signing a vector of transactions and measure the TPS.
397    pub(crate) async fn benchmark_transaction_signing(
398        &self,
399        transactions: Vec<TransactionEnvelope>,
400        print_sample_tx: bool,
401    ) {
402        if print_sample_tx {
403            let sample_transaction = &transactions[0];
404            info!("Sample transaction: {:?}", sample_transaction.data());
405        }
406
407        let tx_count = transactions.len();
408        let start_time = std::time::Instant::now();
409        self.validator_sign_transactions(transactions).await;
410        let elapsed = start_time.elapsed().as_millis() as f64 / 1000f64;
411        info!(
412            "Transaction signing finished in {}s, TPS={}.",
413            elapsed,
414            tx_count as f64 / elapsed,
415        );
416    }
417
418    pub(crate) async fn benchmark_checkpoint_executor(
419        &self,
420        transactions: Vec<CertifiedTransaction>,
421        assigned_versions: AssignedTxAndVersions,
422        checkpoint_size: usize,
423    ) {
424        self.execute_sample_transaction(transactions[0].clone())
425            .await;
426
427        info!("Executing all transactions to generate effects");
428        let tx_count = transactions.len();
429        let in_memory_store = self.validator.create_in_memory_store();
430        let effects: BTreeMap<_, _> = self
431            .execute_transactions_in_memory(
432                in_memory_store.clone(),
433                transactions.clone(),
434                assigned_versions,
435            )
436            .await
437            .into_iter()
438            .map(|e| (*e.transaction_digest(), e))
439            .collect();
440
441        info!("Building checkpoints");
442        let validator = self.validator();
443        let checkpoints = validator
444            .build_checkpoints(transactions, effects, checkpoint_size)
445            .await;
446        info!("Built {} checkpoints", checkpoints.len());
447        let last_checkpoint_seq = checkpoints.last().unwrap().0.sequence_number();
448        let checkpoint_executor = validator.create_checkpoint_executor();
449        for (checkpoint, contents) in checkpoints {
450            let state = validator.get_validator();
451            state
452                .get_checkpoint_store()
453                .insert_verified_checkpoint(&checkpoint)
454                .unwrap();
455            state
456                .get_state_sync_store()
457                .multi_insert_transaction_and_effects(contents.transactions());
458            state
459                .get_checkpoint_store()
460                .insert_verified_checkpoint_contents(&checkpoint, contents)
461                .unwrap();
462            state
463                .get_checkpoint_store()
464                .update_highest_synced_checkpoint(&checkpoint)
465                .unwrap();
466        }
467        let start_time = std::time::Instant::now();
468        info!("Starting checkpoint execution. You can now attach a profiler");
469        checkpoint_executor
470            .run_epoch(Some(RunWithRange::Checkpoint(last_checkpoint_seq)))
471            .await;
472        let elapsed = start_time.elapsed().as_millis() as f64 / 1000f64;
473        info!(
474            "Checkpoint execution finished in {}s, TPS={}.",
475            elapsed,
476            tx_count as f64 / elapsed,
477        );
478    }
479
480    async fn execute_raw_transactions(
481        &self,
482        transactions: Vec<TransactionEnvelope>,
483    ) -> Vec<TransactionEffects> {
484        let tasks: FuturesUnordered<_> = transactions
485            .into_iter()
486            .map(|tx| {
487                let validator = self.validator();
488                tokio::spawn(async move { validator.execute_raw_transaction(tx).await })
489            })
490            .collect();
491        let results: Vec<_> = tasks.collect().await;
492        results.into_iter().map(|r| r.unwrap()).collect()
493    }
494
495    async fn execute_transactions_in_memory(
496        &self,
497        store: InMemoryObjectStore,
498        transactions: Vec<CertifiedTransaction>,
499        assigned_versions: AssignedTxAndVersions,
500    ) -> Vec<TransactionEffects> {
501        let has_shared_object = transactions.iter().any(|tx| tx.contains_shared_object());
502        let assigned_versions = assigned_versions.into_map();
503        if has_shared_object {
504            // With shared objects, we must execute each transaction in order.
505            let mut effects = Vec::new();
506            for transaction in transactions {
507                let assigned_versions = assigned_versions.get(&transaction.key()).unwrap();
508                effects.push(
509                    self.validator
510                        .execute_transaction_in_memory(
511                            store.clone(),
512                            transaction,
513                            assigned_versions,
514                        )
515                        .await,
516                );
517            }
518            effects
519        } else {
520            let tasks: FuturesUnordered<_> = transactions
521                .into_iter()
522                .map(|tx| {
523                    let store = store.clone();
524                    let validator = self.validator();
525                    tokio::spawn(async move {
526                        validator
527                            .execute_transaction_in_memory(store, tx, &vec![])
528                            .await
529                    })
530                })
531                .collect();
532            let results: Vec<_> = tasks.collect().await;
533            results.into_iter().map(|r| r.unwrap()).collect()
534        }
535    }
536
537    fn refresh_gas_objects(&mut self, mut new_gas_objects: HashMap<ObjectId, ObjectReference>) {
538        info!("Refreshing gas objects");
539        for account in self.user_accounts.values_mut() {
540            let refreshed_gas_objects: Vec<_> = account
541                .gas_objects
542                .iter()
543                .map(|oref| {
544                    if let Some(new_oref) = new_gas_objects.remove(&oref.object_id) {
545                        new_oref
546                    } else {
547                        *oref
548                    }
549                })
550                .collect();
551            account.gas_objects = Arc::new(refreshed_gas_objects);
552        }
553    }
554    pub(crate) async fn validator_sign_transactions(
555        &self,
556        transactions: Vec<TransactionEnvelope>,
557    ) -> Vec<HandleTransactionResponse> {
558        info!(
559            "Started signing {} transactions. You can now attach a profiler",
560            transactions.len(),
561        );
562        let tasks: FuturesUnordered<_> = transactions
563            .into_iter()
564            .map(|tx| {
565                let validator = self.validator();
566                tokio::spawn(async move { validator.sign_transaction(tx).await })
567            })
568            .collect();
569        let results: Vec<_> = tasks.collect().await;
570        results.into_iter().map(|r| r.unwrap()).collect()
571    }
572}