linera_client/
benchmark.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::{collections::HashMap, iter, sync::Arc};

use linera_base::{
    crypto::{AccountPublicKey, AccountSecretKey},
    data_types::{Amount, Epoch, Timestamp},
    identifiers::{AccountOwner, ApplicationId, ChainId},
    listen_for_shutdown_signals,
    time::Instant,
};
use linera_chain::{
    data_types::{BlockProposal, ProposedBlock},
    types::ConfirmedBlock,
};
use linera_core::{client::ChainClient, local_node::LocalNodeClient};
use linera_execution::{
    committee::Committee,
    system::{Recipient, SystemOperation},
    Operation,
};
use linera_rpc::node_provider::NodeProvider;
use linera_sdk::abis::fungible;
use linera_storage::Storage;
use num_format::{Locale, ToFormattedString};
use prometheus_parse::{HistogramCount, Scrape, Value};
use tokio::{
    runtime::Handle,
    sync::{mpsc, Barrier},
    task, time,
};
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, warn, Instrument as _};

const PROXY_LATENCY_P99_THRESHOLD: f64 = 400.0;
const LATENCY_METRIC_PREFIX: &str = "linera_proxy_request_latency";

#[derive(Debug, thiserror::Error)]
pub enum BenchmarkError {
    #[error("Proxy of validator {0} unhealthy! Latency p99 is too high: {1} ms")]
    ProxyUnhealthy(String, f64),
    #[error("Failed to send message: {0}")]
    CrossbeamSendError(#[from] crossbeam_channel::SendError<()>),
    #[error("Failed to join task: {0}")]
    JoinError(#[from] task::JoinError),
    #[error("Failed to parse validator metrics port: {0}")]
    ParseValidatorMetricsPort(#[from] std::num::ParseIntError),
    #[error("Failed to parse validator metrics address: {0}")]
    ParseValidatorMetricsAddress(String),
    #[error("Local node error: {0}")]
    LocalNode(#[from] linera_core::local_node::LocalNodeError),
    #[error("Chain client error: {0}")]
    ChainClient(#[from] linera_core::client::ChainClientError),
    #[error("Current histogram count is less than previous histogram count")]
    HistogramCountMismatch,
    #[error("Expected histogram value, got {0:?}")]
    ExpectedHistogramValue(Value),
    #[error("Expected untyped value, got {0:?}")]
    ExpectedUntypedValue(Value),
    #[error("Incomplete histogram data")]
    IncompleteHistogramData,
    #[error("Could not compute quantile")]
    CouldNotComputeQuantile,
    #[error("Bucket count is 0")]
    BucketCountIsZero,
    #[error("Bucket boundaries do not match: {0} vs {1}")]
    BucketBoundariesDoNotMatch(f64, f64),
    #[error("Reqwest error: {0}")]
    Reqwest(#[from] reqwest::Error),
    #[error("Io error: {0}")]
    IoError(#[from] std::io::Error),
    #[error("Previous histogram snapshot does not exist: {0}")]
    PreviousHistogramSnapshotDoesNotExist(String),
    #[error("No data available yet to calculate p99")]
    NoDataYetForP99Calculation,
    #[error("Unexpected empty bucket")]
    UnexpectedEmptyBucket,
    #[error("Failed to send message: {0}")]
    TokioSendError(#[from] mpsc::error::SendError<()>),
}

#[derive(Debug)]
struct HistogramSnapshot {
    buckets: Vec<HistogramCount>,
    count: f64,
    sum: f64,
}

pub struct Benchmark<Storage>
where
    Storage: linera_storage::Storage,
{
    _phantom: std::marker::PhantomData<Storage>,
}

impl<S> Benchmark<S>
where
    S: Storage + Clone + Send + Sync + 'static,
{
    #[expect(clippy::too_many_arguments)]
    pub async fn run_benchmark(
        num_chains: usize,
        transactions_per_block: usize,
        bps: Option<usize>,
        chain_clients: HashMap<ChainId, ChainClient<NodeProvider, S>>,
        epoch: Epoch,
        blocks_infos: Vec<(ChainId, Vec<Operation>, AccountSecretKey)>,
        committee: Committee,
        local_node: LocalNodeClient<S>,
        health_check_endpoints: Option<String>,
    ) -> Result<(), BenchmarkError> {
        let shutdown_notifier = CancellationToken::new();
        tokio::spawn(listen_for_shutdown_signals(shutdown_notifier.clone()));

        let handle = Handle::current();
        // The bps control task will control the BPS from the threads. `crossbeam_channel` is used
        // for two reasons:
        // 1. it allows bounded channels with zero sized buffers.
        // 2. it blocks the current thread if the message can't be sent, which is exactly
        //    what we want to happen here. `tokio::sync::mpsc` doesn't do that. `std::sync::mpsc`
        //    does, but it is slower than `crossbeam_channel`.
        // Number 1 is the main reason. `tokio::sync::mpsc` doesn't allow 0 sized buffers.
        // With a channel with a buffer of size 1 or larger, even if we have already reached
        // the desired BPS, the tasks would continue sending block proposals until the channel's
        // buffer is filled, which would cause us to not properly control the BPS rate.
        let (sender, receiver) = crossbeam_channel::bounded(0);
        let bps_control_task = task::spawn_blocking(move || {
            handle.block_on(async move {
                let mut recv_count = 0;
                let mut start = time::Instant::now();
                while let Ok(()) = receiver.recv() {
                    recv_count += 1;
                    if recv_count == num_chains {
                        let elapsed = start.elapsed();
                        if let Some(bps) = bps {
                            let tps =
                                (bps * transactions_per_block).to_formatted_string(&Locale::en);
                            let bps = bps.to_formatted_string(&Locale::en);
                            if elapsed > time::Duration::from_secs(1) {
                                warn!(
                                    "Failed to achieve {} BPS/{} TPS in {} ms",
                                    bps,
                                    tps,
                                    elapsed.as_millis(),
                                );
                            } else {
                                time::sleep(time::Duration::from_secs(1) - elapsed).await;
                                info!(
                                    "Achieved {} BPS/{} TPS in {} ms",
                                    bps,
                                    tps,
                                    elapsed.as_millis(),
                                );
                            }
                        } else {
                            let achieved_bps = num_chains as f64 / elapsed.as_secs_f64();
                            info!(
                                "Achieved {} BPS/{} TPS in {} ms",
                                achieved_bps,
                                achieved_bps * transactions_per_block as f64,
                                elapsed.as_millis(),
                            );
                        }

                        recv_count = 0;
                        start = time::Instant::now();
                    }
                }

                info!("Exiting logging task...");
            })
        });

        let (bps_tasks_logger_sender, mut bps_tasks_logger_receiver) = mpsc::channel(num_chains);
        let bps_tasks_logger_task = task::spawn(async move {
            let mut tasks_running = 0;
            while let Some(()) = bps_tasks_logger_receiver.recv().await {
                tasks_running += 1;
                info!("{}/{} tasks ready to start", tasks_running, num_chains);
                if tasks_running == num_chains {
                    info!("All tasks are ready to start");
                    break;
                }
            }
        });

        let mut bps_remainder = bps.unwrap_or_default() % num_chains;
        let bps_share = bps.map(|bps| bps / num_chains);

        let barrier = Arc::new(Barrier::new(num_chains));
        let mut join_set = task::JoinSet::<Result<(), BenchmarkError>>::new();
        for (chain_id, operations, key_pair) in blocks_infos {
            let bps_share = if bps_remainder > 0 {
                bps_remainder -= 1;
                bps_share.map(|share| share + 1)
            } else {
                bps_share
            };

            let shutdown_notifier = shutdown_notifier.clone();
            let sender = sender.clone();
            let handle = Handle::current();
            let committee = committee.clone();
            let local_node = local_node.clone();
            let chain_client = chain_clients[&chain_id].clone();
            let bps_tasks_logger_sender = bps_tasks_logger_sender.clone();
            let inner_barrier = barrier.clone();
            chain_client.process_inbox().await?;
            join_set.spawn_blocking(move || {
                handle.block_on(
                    async move {
                        Box::pin(Self::run_benchmark_internal(
                            bps_share,
                            operations,
                            key_pair,
                            epoch,
                            chain_client,
                            shutdown_notifier,
                            sender,
                            committee,
                            local_node,
                            bps_tasks_logger_sender,
                            inner_barrier,
                        ))
                        .await?;

                        Ok(())
                    }
                    .instrument(tracing::info_span!(
                        "benchmark_chain_id",
                        chain_id = format!("{:?}", chain_id)
                    )),
                )
            });
        }

        let metrics_watcher =
            Self::create_metrics_watcher(health_check_endpoints, shutdown_notifier.clone()).await?;
        join_set
            .join_all()
            .await
            .into_iter()
            .collect::<Result<Vec<_>, _>>()?;
        drop(sender);
        info!("All benchmark tasks completed");
        bps_control_task.await?;
        if let Some(metrics_watcher) = metrics_watcher {
            metrics_watcher.await??;
        }
        bps_tasks_logger_task.await?;

        Ok(())
    }

    async fn create_metrics_watcher(
        health_check_endpoints: Option<String>,
        shutdown_notifier: CancellationToken,
    ) -> Result<Option<task::JoinHandle<Result<(), BenchmarkError>>>, BenchmarkError> {
        if let Some(health_check_endpoints) = health_check_endpoints {
            let metrics_addresses = health_check_endpoints
                .split(',')
                .map(|address| format!("http://{}/metrics", address.trim()))
                .collect::<Vec<_>>();

            let mut previous_histogram_snapshots: HashMap<String, HistogramSnapshot> =
                HashMap::new();
            let scrapes = Self::get_scrapes(&metrics_addresses).await?;
            for (metrics_address, scrape) in scrapes {
                previous_histogram_snapshots.insert(
                    metrics_address,
                    Self::parse_histogram(&scrape, LATENCY_METRIC_PREFIX)?,
                );
            }

            let metrics_watcher: task::JoinHandle<Result<(), BenchmarkError>> = tokio::spawn(
                async move {
                    let mut health_interval = time::interval(time::Duration::from_secs(5));
                    let mut shutdown_interval = time::interval(time::Duration::from_secs(1));
                    loop {
                        tokio::select! {
                            biased;
                            _ = health_interval.tick() => {
                                let result = Self::validators_healthy(&metrics_addresses, &mut previous_histogram_snapshots).await;
                                if let Err(ref err) = result {
                                    info!("Shutting down benchmark due to error: {}", err);
                                    shutdown_notifier.cancel();
                                    break;
                                } else if !result? {
                                    info!("Shutting down benchmark due to unhealthy validators");
                                    shutdown_notifier.cancel();
                                    break;
                                }
                            }
                            _ = shutdown_interval.tick() => {
                                if shutdown_notifier.is_cancelled() {
                                    info!("Shutdown signal received, stopping metrics watcher");
                                    break;
                                }
                            }
                        }
                    }

                    Ok(())
                },
            );

            Ok(Some(metrics_watcher))
        } else {
            Ok(None)
        }
    }

    async fn validators_healthy(
        metrics_addresses: &[String],
        previous_histogram_snapshots: &mut HashMap<String, HistogramSnapshot>,
    ) -> Result<bool, BenchmarkError> {
        let scrapes = Self::get_scrapes(metrics_addresses).await?;
        for (metrics_address, scrape) in scrapes {
            let histogram = Self::parse_histogram(&scrape, LATENCY_METRIC_PREFIX)?;
            let diff = Self::diff_histograms(
                previous_histogram_snapshots.get(&metrics_address).ok_or(
                    BenchmarkError::PreviousHistogramSnapshotDoesNotExist(metrics_address.clone()),
                )?,
                &histogram,
            )?;
            let p99 = match Self::compute_quantile(&diff.buckets, diff.count, 0.99) {
                Ok(p99) => p99,
                Err(BenchmarkError::NoDataYetForP99Calculation) => {
                    info!(
                        "No data available yet to calculate p99 for {}",
                        metrics_address
                    );
                    continue;
                }
                Err(e) => {
                    error!("Error computing p99 for {}: {}", metrics_address, e);
                    return Err(e);
                }
            };

            let last_bucket_boundary = diff.buckets[diff.buckets.len() - 2].less_than;
            if p99 == f64::INFINITY {
                info!(
                    "{} -> Estimated p99 for {} is higher than the last bucket boundary of {:?} ms",
                    metrics_address, LATENCY_METRIC_PREFIX, last_bucket_boundary
                );
            } else {
                info!(
                    "{} -> Estimated p99 for {}: {:.2} ms",
                    metrics_address, LATENCY_METRIC_PREFIX, p99
                );
            }
            if p99 > PROXY_LATENCY_P99_THRESHOLD {
                if p99 == f64::INFINITY {
                    error!(
                        "Proxy of validator {} unhealthy! Latency p99 is too high, it is higher than \
                        the last bucket boundary of {:.2} ms",
                        metrics_address, last_bucket_boundary
                    );
                } else {
                    error!(
                        "Proxy of validator {} unhealthy! Latency p99 is too high: {:.2} ms",
                        metrics_address, p99
                    );
                }
                return Ok(false);
            }
            previous_histogram_snapshots.insert(metrics_address.clone(), histogram);
        }

        Ok(true)
    }

    fn diff_histograms(
        previous: &HistogramSnapshot,
        current: &HistogramSnapshot,
    ) -> Result<HistogramSnapshot, BenchmarkError> {
        if current.count < previous.count {
            return Err(BenchmarkError::HistogramCountMismatch);
        }
        let total_diff = current.count - previous.count;
        let mut buckets_diff: Vec<HistogramCount> = Vec::new();
        for (before, after) in previous.buckets.iter().zip(current.buckets.iter()) {
            let bound_before = before.less_than;
            let bound_after = after.less_than;
            let cumulative_before = before.count;
            let cumulative_after = after.count;
            if (bound_before - bound_after).abs() > f64::EPSILON {
                return Err(BenchmarkError::BucketBoundariesDoNotMatch(
                    bound_before,
                    bound_after,
                ));
            }
            let diff = (cumulative_after - cumulative_before).max(0.0);
            buckets_diff.push(HistogramCount {
                less_than: bound_after,
                count: diff,
            });
        }
        Ok(HistogramSnapshot {
            buckets: buckets_diff,
            count: total_diff,
            sum: current.sum - previous.sum,
        })
    }

    async fn get_scrapes(
        metrics_addresses: &[String],
    ) -> Result<Vec<(String, Scrape)>, BenchmarkError> {
        let mut scrapes = Vec::new();
        for metrics_address in metrics_addresses {
            let response = reqwest::get(metrics_address)
                .await
                .map_err(BenchmarkError::Reqwest)?;
            let metrics = response.text().await.map_err(BenchmarkError::Reqwest)?;
            let scrape = Scrape::parse(metrics.lines().map(|line| Ok(line.to_owned())))
                .map_err(BenchmarkError::IoError)?;
            scrapes.push((metrics_address.clone(), scrape));
        }
        Ok(scrapes)
    }

    fn parse_histogram(
        scrape: &Scrape,
        metric_prefix: &str,
    ) -> Result<HistogramSnapshot, BenchmarkError> {
        let mut buckets: Vec<HistogramCount> = Vec::new();
        let mut total_count: Option<f64> = None;
        let mut total_sum: Option<f64> = None;

        // Iterate over each metric in the scrape.
        for sample in &scrape.samples {
            if sample.metric == metric_prefix {
                if let Value::Histogram(histogram) = &sample.value {
                    buckets.extend(histogram.iter().cloned());
                } else {
                    return Err(BenchmarkError::ExpectedHistogramValue(sample.value.clone()));
                }
            } else if sample.metric == format!("{}_count", metric_prefix) {
                if let Value::Untyped(count) = sample.value {
                    total_count = Some(count);
                } else {
                    return Err(BenchmarkError::ExpectedUntypedValue(sample.value.clone()));
                }
            } else if sample.metric == format!("{}_sum", metric_prefix) {
                if let Value::Untyped(sum) = sample.value {
                    total_sum = Some(sum);
                } else {
                    return Err(BenchmarkError::ExpectedUntypedValue(sample.value.clone()));
                }
            }
        }

        match (total_count, total_sum) {
            (Some(count), Some(sum)) if !buckets.is_empty() => {
                buckets.sort_by(|a, b| {
                    a.less_than
                        .partial_cmp(&b.less_than)
                        .expect("Comparison should not fail")
                });
                Ok(HistogramSnapshot {
                    buckets,
                    count,
                    sum,
                })
            }
            _ => Err(BenchmarkError::IncompleteHistogramData),
        }
    }

    fn compute_quantile(
        buckets: &[HistogramCount],
        total_count: f64,
        quantile: f64,
    ) -> Result<f64, BenchmarkError> {
        if total_count == 0.0 {
            // Had no samples in the last 5s.
            return Err(BenchmarkError::NoDataYetForP99Calculation);
        }
        // Compute the target cumulative count.
        let target = (quantile * total_count).ceil();
        let mut prev_cumulative = 0.0;
        let mut prev_bound = 0.0;
        for bucket in buckets {
            if bucket.count >= target {
                let bucket_count = bucket.count - prev_cumulative;
                if bucket_count == 0.0 {
                    // Bucket that is supposed to contain the target quantile is empty, unexpectedly.
                    return Err(BenchmarkError::UnexpectedEmptyBucket);
                }
                let fraction = (target - prev_cumulative) / bucket_count;
                return Ok(prev_bound + (bucket.less_than - prev_bound) * fraction);
            }
            prev_cumulative = bucket.count;
            prev_bound = bucket.less_than;
        }
        Err(BenchmarkError::CouldNotComputeQuantile)
    }

    #[expect(clippy::too_many_arguments)]
    async fn run_benchmark_internal(
        bps: Option<usize>,
        operations: Vec<Operation>,
        key_pair: AccountSecretKey,
        epoch: Epoch,
        chain_client: ChainClient<NodeProvider, S>,
        shutdown_notifier: CancellationToken,
        sender: crossbeam_channel::Sender<()>,
        committee: Committee,
        local_node: LocalNodeClient<S>,
        bps_tasks_logger_sender: mpsc::Sender<()>,
        barrier: Arc<Barrier>,
    ) -> Result<(), BenchmarkError> {
        let chain_id = chain_client.chain_id();
        bps_tasks_logger_sender.send(()).await?;
        barrier.wait().await;
        info!(
            "Starting benchmark at target BPS of {:?}, for chain {:?}",
            bps, chain_id
        );
        let cross_chain_message_delivery = chain_client.options().cross_chain_message_delivery;
        let mut num_sent_proposals = 0;
        let authenticated_signer = Some(AccountOwner::from(key_pair.public()));
        loop {
            if shutdown_notifier.is_cancelled() {
                info!("Shutdown signal received, stopping benchmark");
                break;
            }
            let proposed_block = ProposedBlock {
                epoch,
                chain_id,
                incoming_bundles: Vec::new(),
                operations: operations.clone(),
                previous_block_hash: chain_client.block_hash(),
                height: chain_client.next_block_height(),
                authenticated_signer,
                timestamp: chain_client.timestamp().max(Timestamp::now()),
            };
            let block = local_node
                .stage_block_execution(proposed_block.clone(), None, Vec::new())
                .await
                .map_err(BenchmarkError::LocalNode)?
                .0;

            let value = ConfirmedBlock::new(block);
            let proposal = BlockProposal::new_initial(
                linera_base::data_types::Round::Fast,
                proposed_block,
                &key_pair,
            );

            chain_client
                .submit_block_proposal(&committee, Box::new(proposal), value)
                .await
                .map_err(BenchmarkError::ChainClient)?;
            let next_block_height = chain_client.next_block_height();
            // We assume the committee will not change during the benchmark.
            chain_client
                .communicate_chain_updates(
                    &committee,
                    chain_id,
                    next_block_height,
                    cross_chain_message_delivery,
                )
                .await
                .map_err(BenchmarkError::ChainClient)?;

            num_sent_proposals += 1;
            if let Some(bps) = bps {
                if num_sent_proposals == bps {
                    sender.send(())?;
                    num_sent_proposals = 0;
                }
            } else {
                sender.send(())?;
                break;
            }
        }

        info!("Exiting task...");
        Ok(())
    }

    /// Closes the chain that was created for the benchmark.
    pub async fn close_benchmark_chain(
        chain_client: &ChainClient<NodeProvider, S>,
    ) -> Result<(), BenchmarkError> {
        let start = Instant::now();
        chain_client
            .execute_operation(Operation::system(SystemOperation::CloseChain))
            .await?
            .expect("Close chain operation should not fail!");

        debug!(
            "Closed chain {:?} in {} ms",
            chain_client.chain_id(),
            start.elapsed().as_millis()
        );

        Ok(())
    }

    /// Generates information related to one block per chain, up to `num_chains` blocks.
    pub fn make_benchmark_block_info(
        key_pairs: HashMap<ChainId, AccountSecretKey>,
        transactions_per_block: usize,
        fungible_application_id: Option<ApplicationId>,
    ) -> Vec<(ChainId, Vec<Operation>, AccountSecretKey)> {
        let mut blocks_infos = Vec::new();
        let mut previous_chain_id = *key_pairs
            .iter()
            .last()
            .expect("There should be a last element")
            .0;
        let amount = Amount::from(1);
        for (chain_id, key_pair) in key_pairs {
            let public_key = key_pair.public();
            let operation = match fungible_application_id {
                Some(application_id) => Self::fungible_transfer(
                    application_id,
                    previous_chain_id,
                    public_key,
                    public_key,
                    amount,
                ),
                None => Operation::system(SystemOperation::Transfer {
                    owner: AccountOwner::CHAIN,
                    recipient: Recipient::chain(previous_chain_id),
                    amount,
                }),
            };
            let operations = iter::repeat_n(operation, transactions_per_block).collect();
            blocks_infos.push((chain_id, operations, key_pair));
            previous_chain_id = chain_id;
        }
        blocks_infos
    }

    /// Creates a fungible token transfer operation.
    pub fn fungible_transfer(
        application_id: ApplicationId,
        chain_id: ChainId,
        sender: AccountPublicKey,
        receiver: AccountPublicKey,
        amount: Amount,
    ) -> Operation {
        let target_account = fungible::Account {
            chain_id,
            owner: AccountOwner::from(receiver),
        };
        let bytes = bcs::to_bytes(&fungible::Operation::Transfer {
            owner: AccountOwner::from(sender),
            amount,
            target_account,
        })
        .expect("should serialize fungible token operation");
        Operation::User {
            application_id,
            bytes,
        }
    }
}