linera-client 0.15.20

A library for writing Linera client applications.
Documentation
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::sync::Arc;

#[cfg(not(web))]
use futures::StreamExt as _;
use futures::{Future, TryStreamExt as _};
use linera_base::{
    crypto::{CryptoHash, ValidatorPublicKey},
    data_types::{ChainDescription, Epoch, Timestamp},
    identifiers::{Account, AccountOwner, ChainId},
    ownership::ChainOwnership,
    time::{Duration, Instant},
    util::future::FutureSyncExt as _,
};
use linera_chain::{manager::LockingBlock, types::ConfirmedBlockCertificate};
use linera_core::{
    client::{chain_client, ChainClient, Client, ListeningMode},
    data_types::{ChainInfo, ChainInfoQuery, ClientOutcome},
    join_set_ext::JoinSet,
    node::ValidatorNode,
    wallet, Environment, JoinSetExt as _, Wallet as _,
};
use linera_rpc::node_provider::{NodeOptions, NodeProvider};
use linera_storage::Storage as _;
use linera_version::VersionInfo;
use thiserror_context::Context;
use tracing::{debug, info, warn};
#[cfg(not(web))]
use {
    crate::{
        benchmark::{fungible_transfer, Benchmark, BenchmarkError},
        client_metrics::ClientMetrics,
    },
    futures::stream,
    linera_base::{
        crypto::AccountPublicKey,
        data_types::{Amount, BlockHeight},
        identifiers::{ApplicationId, BlobType},
    },
    linera_execution::{
        system::{OpenChainConfig, SystemOperation},
        Operation,
    },
    std::{collections::HashSet, path::Path},
    tokio::{sync::mpsc, task},
};
#[cfg(feature = "fs")]
use {
    linera_base::{
        data_types::{BlobContent, Bytecode},
        identifiers::ModuleId,
        vm::VmRuntime,
    },
    linera_core::client::create_bytecode_blobs,
    std::{fs, path::PathBuf},
};

use crate::{
    chain_listener::{self, ClientContext as _},
    client_options::{ChainOwnershipConfig, Options},
    config::GenesisConfig,
    error, util, Error,
};

/// Results from querying a validator about version, network description, and chain info.
pub struct ValidatorQueryResults {
    /// The validator's version information.
    pub version_info: Result<VersionInfo, Error>,
    /// The validator's genesis config hash.
    pub genesis_config_hash: Result<CryptoHash, Error>,
    /// The validator's chain info (if valid and signature check passed).
    pub chain_info: Result<ChainInfo, Error>,
}

impl ValidatorQueryResults {
    /// Returns a vector of references to all errors in the query results.
    pub fn errors(&self) -> Vec<&Error> {
        let mut errors = Vec::new();
        if let Err(e) = &self.version_info {
            errors.push(e);
        }
        if let Err(e) = &self.genesis_config_hash {
            errors.push(e);
        }
        if let Err(e) = &self.chain_info {
            errors.push(e);
        }
        errors
    }

    /// Prints validator information to stdout.
    ///
    /// Prints public key, address, and optionally weight, version info, and chain info.
    /// If `reference` is provided, only prints fields that differ from the reference.
    pub fn print(
        &self,
        public_key: Option<&ValidatorPublicKey>,
        address: Option<&str>,
        weight: Option<u64>,
        reference: Option<&ValidatorQueryResults>,
    ) {
        if let Some(key) = public_key {
            println!("Public key: {key}");
        }
        if let Some(address) = address {
            println!("Address: {address}");
        }
        if let Some(w) = weight {
            println!("Weight: {w}");
        }

        let ref_version = reference.and_then(|ref_results| ref_results.version_info.as_ref().ok());
        match &self.version_info {
            Ok(version_info) => {
                if ref_version.is_none_or(|ref_v| ref_v.crate_version != version_info.crate_version)
                {
                    println!("Linera protocol: v{}", version_info.crate_version);
                }
                if ref_version.is_none_or(|ref_v| ref_v.rpc_hash != version_info.rpc_hash) {
                    println!("RPC API hash: {}", version_info.rpc_hash);
                }
                if ref_version.is_none_or(|ref_v| ref_v.graphql_hash != version_info.graphql_hash) {
                    println!("GraphQL API hash: {}", version_info.graphql_hash);
                }
                if ref_version.is_none_or(|ref_v| ref_v.wit_hash != version_info.wit_hash) {
                    println!("WIT API hash: v{}", version_info.wit_hash);
                }
                if ref_version.is_none_or(|ref_v| {
                    (&ref_v.git_commit, ref_v.git_dirty)
                        != (&version_info.git_commit, version_info.git_dirty)
                }) {
                    println!(
                        "Source code: {}/tree/{}{}",
                        env!("CARGO_PKG_REPOSITORY"),
                        version_info.git_commit,
                        if version_info.git_dirty {
                            " (dirty)"
                        } else {
                            ""
                        }
                    );
                }
            }
            Err(err) => println!("Error getting version info: {err}"),
        }

        let ref_genesis_hash =
            reference.and_then(|ref_results| ref_results.genesis_config_hash.as_ref().ok());
        match &self.genesis_config_hash {
            Ok(hash) if ref_genesis_hash.is_some_and(|ref_hash| ref_hash == hash) => {}
            Ok(hash) => println!("Genesis config hash: {hash}"),
            Err(err) => println!("Error getting genesis config: {err}"),
        }

        let ref_info = reference.and_then(|ref_results| ref_results.chain_info.as_ref().ok());
        match &self.chain_info {
            Ok(info) => {
                if ref_info.is_none_or(|ref_info| info.block_hash != ref_info.block_hash) {
                    if let Some(hash) = info.block_hash {
                        println!("Block hash: {hash}");
                    } else {
                        println!("Block hash: None");
                    }
                }
                if ref_info
                    .is_none_or(|ref_info| info.next_block_height != ref_info.next_block_height)
                {
                    println!("Next height: {}", info.next_block_height);
                }
                if ref_info.is_none_or(|ref_info| info.timestamp != ref_info.timestamp) {
                    println!("Timestamp: {}", info.timestamp);
                }
                if ref_info.is_none_or(|ref_info| info.epoch != ref_info.epoch) {
                    println!("Epoch: {}", info.epoch);
                }
                if ref_info.is_none_or(|ref_info| {
                    info.manager.current_round != ref_info.manager.current_round
                }) {
                    println!("Round: {}", info.manager.current_round);
                }
                if let Some(leader) = info.manager.leader {
                    println!("Leader: {leader}");
                }
                if let Some(locking) = &info.manager.requested_locking {
                    match &**locking {
                        LockingBlock::Fast(proposal) => {
                            println!(
                                "Locking fast block from {}",
                                proposal.content.block.timestamp
                            );
                        }
                        LockingBlock::Regular(validated) => {
                            println!(
                                "Locking block {} in {} from {}",
                                validated.hash(),
                                validated.round,
                                validated.block().header.timestamp
                            );
                        }
                    }
                }
            }
            Err(err) => println!("Error getting chain info: {err}"),
        }
        println!();
    }
}

/// The state shared by the client commands: the core client, wallet configuration, and
/// network timeouts.
pub struct ClientContext<Env: Environment> {
    /// The core client used to interact with chains and validators.
    pub client: Arc<Client<Env>>,
    /// The genesis configuration of the network.
    // TODO(#5083): this doesn't really need to be stored
    pub genesis_config: crate::config::GenesisConfig,
    /// The timeout for sending requests to validators.
    pub send_timeout: Duration,
    /// The timeout for receiving responses from validators.
    pub recv_timeout: Duration,
    /// The delay before retrying a failed request to a validator.
    pub retry_delay: Duration,
    /// The maximum number of times to retry a failed request to a validator.
    pub max_retries: u32,
    /// The maximum backoff between retries of a failed request to a validator.
    pub max_backoff: Duration,
    /// The set of background tasks listening for chain notifications.
    pub chain_listeners: JoinSet,
    /// The default chain used when no chain is explicitly specified.
    // TODO(#5082): move this into the upstream UI layers (maybe just the CLI)
    pub default_chain: Option<ChainId>,
    /// The metrics collector, if metrics collection is enabled.
    #[cfg(not(web))]
    pub client_metrics: Option<ClientMetrics>,
}

impl<Env: Environment> chain_listener::ClientContext for ClientContext<Env> {
    type Environment = Env;

    fn wallet(&self) -> &Env::Wallet {
        self.client.wallet()
    }

    fn storage(&self) -> &Env::Storage {
        self.client.storage_client()
    }

    fn client(&self) -> &Arc<Client<Env>> {
        &self.client
    }

    #[cfg(not(web))]
    fn timing_sender(
        &self,
    ) -> Option<mpsc::UnboundedSender<(u64, linera_core::client::TimingType)>> {
        self.client_metrics
            .as_ref()
            .map(|metrics| metrics.timing_sender.clone())
    }

    async fn update_wallet_for_new_chain(
        &mut self,
        chain_id: ChainId,
        owner: Option<AccountOwner>,
        timestamp: Timestamp,
        epoch: Epoch,
    ) -> Result<(), Error> {
        self.update_wallet_for_new_chain(chain_id, owner, timestamp, epoch)
            .make_sync()
            .await
    }

    async fn update_wallet(&mut self, chain_client: &ChainClient<Env>) -> Result<(), Error> {
        self.update_wallet_from_client(chain_client)
            .make_sync()
            .await
    }
}

impl<S, Si, W> ClientContext<linera_core::environment::Impl<S, NodeProvider, Si, W>>
where
    S: linera_core::environment::Storage,
    Si: linera_core::environment::Signer,
    W: linera_core::environment::Wallet,
{
    // not worth refactoring this because
    // https://github.com/linera-io/linera-protocol/issues/5082
    // https://github.com/linera-io/linera-protocol/issues/5083
    /// Creates a new client context from the given storage, wallet, signer, and options.
    #[expect(clippy::too_many_arguments)]
    pub async fn new(
        storage: S,
        wallet: W,
        signer: Si,
        options: &Options,
        default_chain: Option<ChainId>,
        genesis_config: GenesisConfig,
        block_cache_size: usize,
        execution_state_cache_size: usize,
    ) -> Result<Self, Error> {
        #[cfg(not(web))]
        let timing_config = options.to_timing_config();
        let node_provider = NodeProvider::new(NodeOptions {
            send_timeout: options.send_timeout,
            recv_timeout: options.recv_timeout,
            retry_delay: options.retry_delay,
            max_retries: options.max_retries,
            max_backoff: options.max_backoff,
        });
        let chain_modes: Vec<_> = wallet
            .items()
            .map_ok(|(id, _chain)| (id, ListeningMode::FullChain))
            .try_collect()
            .await
            .map_err(error::Inner::wallet)?;
        let name = match chain_modes.len() {
            0 => "Client node".to_string(),
            1 => format!("Client node for {:.8}", chain_modes[0].0),
            n => format!(
                "Client node for {:.8} and {} others",
                chain_modes[0].0,
                n - 1
            ),
        };

        let client = Client::new(
            linera_core::environment::Impl {
                network: node_provider,
                storage,
                signer,
                wallet,
            },
            genesis_config.admin_chain_id(),
            options.long_lived_services,
            chain_modes,
            name,
            util::non_zero_duration(options.chain_worker_ttl),
            util::non_zero_duration(options.sender_chain_worker_ttl),
            options.cross_chain_batch_size_limit,
            options.to_chain_client_options(),
            &options.to_requests_scheduler_config(),
            block_cache_size,
            execution_state_cache_size,
        );

        #[cfg(not(web))]
        let client_metrics = if timing_config.enabled {
            Some(ClientMetrics::new(timing_config))
        } else {
            None
        };

        Ok(ClientContext {
            client: Arc::new(client),
            default_chain,
            genesis_config,
            send_timeout: options.send_timeout,
            recv_timeout: options.recv_timeout,
            retry_delay: options.retry_delay,
            max_retries: options.max_retries,
            max_backoff: options.max_backoff,
            chain_listeners: JoinSet::default(),
            #[cfg(not(web))]
            client_metrics,
        })
    }
}

impl<Env: Environment> ClientContext<Env> {
    // TODO(#5084) this (and other injected dependencies) should not be re-exposed by the
    // client interface
    /// Returns a reference to the wallet.
    pub fn wallet(&self) -> &Env::Wallet {
        self.client.wallet()
    }

    /// Returns the ID of the admin chain.
    pub fn admin_chain_id(&self) -> ChainId {
        self.client.admin_chain_id()
    }

    /// Retrieve the default account. Current this is the common account of the default
    /// chain.
    pub fn default_account(&self) -> Account {
        Account::chain(self.default_chain())
    }

    /// Retrieve the default chain.
    pub fn default_chain(&self) -> ChainId {
        self.default_chain
            .expect("default chain requested but none set")
    }

    /// Returns the lowest non-admin chain ID in the wallet.
    pub async fn first_non_admin_chain(&self) -> Result<ChainId, Error> {
        let admin_chain_id = self.admin_chain_id();
        let chain_ids = self
            .wallet()
            .chain_ids()
            .try_filter(|chain_id| futures::future::ready(*chain_id != admin_chain_id))
            .try_collect::<Vec<ChainId>>()
            .await
            .map_err(Error::wallet)?;
        Ok(chain_ids
            .into_iter()
            .min()
            .expect("No non-admin chain specified in wallet with no non-admin chain"))
    }

    /// Creates a node provider configured with this context's network options.
    // TODO(#5084) this should match the `NodeProvider` from the `Environment`
    pub fn make_node_provider(&self) -> NodeProvider {
        NodeProvider::new(self.make_node_options())
    }

    fn make_node_options(&self) -> NodeOptions {
        NodeOptions {
            send_timeout: self.send_timeout,
            recv_timeout: self.recv_timeout,
            retry_delay: self.retry_delay,
            max_retries: self.max_retries,
            max_backoff: self.max_backoff,
        }
    }

    /// Returns the client metrics, if metrics collection is enabled.
    #[cfg(not(web))]
    pub fn client_metrics(&self) -> Option<&ClientMetrics> {
        self.client_metrics.as_ref()
    }

    /// Updates the wallet entry for the client's chain from its current chain info.
    pub async fn update_wallet_from_client<Env_: Environment>(
        &self,
        chain_client: &ChainClient<Env_>,
    ) -> Result<(), Error> {
        let info = chain_client.chain_info().await?;
        let existing_owner = self
            .wallet()
            .get(info.chain_id)
            .await
            .map_err(error::Inner::wallet)?
            .and_then(|chain| chain.owner);

        // Only persist proposals that were made in the fast round: they need to be
        // remembered across sessions to make sure there are no conflicting fast proposals.
        let pending_proposal = chain_client
            .pending_proposal()
            .await
            .filter(|p| p.round.is_some_and(|r| r.is_fast()));
        self.wallet()
            .insert(
                info.chain_id,
                wallet::Chain {
                    pending_proposal,
                    owner: existing_owner,
                    ..info.as_ref().into()
                },
            )
            .await
            .map_err(error::Inner::wallet)?;

        Ok(())
    }

    /// Remembers the new chain and its owner (if any) in the wallet.
    pub async fn update_wallet_for_new_chain(
        &mut self,
        chain_id: ChainId,
        owner: Option<AccountOwner>,
        timestamp: Timestamp,
        epoch: Epoch,
    ) -> Result<(), Error> {
        self.wallet()
            .try_insert(
                chain_id,
                linera_core::wallet::Chain::new(owner, epoch, timestamp),
            )
            .await
            .map_err(error::Inner::wallet)?;
        Ok(())
    }

    /// Registers a chain from its description: initializes local storage, adds to
    /// wallet, and starts tracking it for cross-chain message delivery.
    pub async fn extend_with_chain(
        &mut self,
        description: ChainDescription,
        owner: Option<AccountOwner>,
    ) -> Result<(), Error> {
        let chain_id = description.id();
        self.client
            .storage_client()
            .create_chain(description.clone())
            .await?;
        self.wallet()
            .try_insert(
                chain_id,
                linera_core::wallet::Chain::new(
                    owner,
                    description.config().epoch,
                    description.timestamp(),
                ),
            )
            .await
            .map_err(error::Inner::wallet)?;
        self.client
            .extend_chain_mode(chain_id, ListeningMode::FullChain);
        Ok(())
    }

    /// Processes the chain's inbox, waiting for round timeouts, and updates the wallet.
    pub async fn process_inbox(
        &mut self,
        chain_client: &ChainClient<Env>,
    ) -> Result<Vec<ConfirmedBlockCertificate>, Error> {
        let mut certificates = Vec::new();
        // Try processing the inbox optimistically without waiting for validator notifications.
        let (new_certificates, maybe_timeout) = {
            chain_client.synchronize_from_validators().await?;
            let result = chain_client.process_inbox_without_prepare().await;
            self.update_wallet_from_client(chain_client).await?;
            result?
        };
        certificates.extend(new_certificates);
        if maybe_timeout.is_none() {
            return Ok(certificates);
        }

        // Start listening for notifications, so we learn about new rounds and blocks.
        let (listener, _listen_handle, mut notification_stream) = chain_client.listen().await?;
        self.chain_listeners.spawn_task(listener);

        loop {
            let (new_certificates, maybe_timeout) = {
                let result = chain_client.process_inbox().await;
                self.update_wallet_from_client(chain_client).await?;
                result?
            };
            certificates.extend(new_certificates);
            if let Some(timestamp) = maybe_timeout {
                util::wait_for_next_round(&mut notification_stream, timestamp).await
            } else {
                return Ok(certificates);
            }
        }
    }

    /// Assigns the given chain to the owner, tracking it and recording it in the wallet.
    pub async fn assign_new_chain_to_key(
        &mut self,
        chain_id: ChainId,
        owner: AccountOwner,
    ) -> Result<(), Error> {
        self.client
            .extend_chain_mode(chain_id, ListeningMode::FullChain);
        let chain_client = self.make_chain_client(chain_id).await?;

        // Ensure we have the chain description blob.
        chain_client.get_chain_description().await?;

        // Synchronize and get chain info.
        chain_client.synchronize_from_validators().await?;
        let info = chain_client.chain_info().await?;

        // Validate that the owner can propose on this chain (either as owner or via
        // open_multi_leader_rounds).
        if !info
            .manager
            .ownership
            .can_propose_in_multi_leader_round(&owner)
        {
            tracing::error!("Chain {chain_id} is not owned by {owner}.");
            return Err(error::Inner::ChainOwnership.into());
        }

        // Try to modify existing chain entry, setting the owner.
        let modified = self
            .wallet()
            .modify(chain_id, |chain| chain.owner = Some(owner))
            .await
            .map_err(error::Inner::wallet)?;
        // If the chain didn't exist, insert a new entry.
        if modified.is_none() {
            self.wallet()
                .insert(
                    chain_id,
                    wallet::Chain {
                        owner: Some(owner),
                        timestamp: info.timestamp,
                        epoch: Some(info.epoch),
                        ..Default::default()
                    },
                )
                .await
                .map_err(error::Inner::wallet)
                .context("assigning new chain")?;
        }
        Ok(())
    }

    /// Applies the given function to the chain client.
    ///
    /// Updates the wallet regardless of the outcome. As long as the function returns a round
    /// timeout, it will wait and retry.
    pub async fn apply_client_command<E, F, Fut, T>(
        &mut self,
        chain_client: &ChainClient<Env>,
        mut f: F,
    ) -> Result<T, Error>
    where
        F: FnMut(&ChainClient<Env>) -> Fut,
        Fut: Future<Output = Result<ClientOutcome<T>, E>>,
        Error: From<E>,
    {
        chain_client.prepare_chain().await?;
        // Try applying f optimistically without validator notifications. Return if committed.
        let result = f(chain_client).await;
        self.update_wallet_from_client(chain_client).await?;
        match result? {
            ClientOutcome::Committed(t) => return Ok(t),
            ClientOutcome::Conflict(certificate) => {
                return Err(chain_client::Error::Conflict(certificate.hash()).into());
            }
            ClientOutcome::WaitForTimeout(_) => {}
        }

        // Start listening for notifications, so we learn about new rounds and blocks.
        let (listener, _listen_handle, mut notification_stream) = chain_client.listen().await?;
        self.chain_listeners.spawn_task(listener);

        loop {
            // Try applying f. Return if committed.
            let result = f(chain_client).await;
            self.update_wallet_from_client(chain_client).await?;
            let timeout = match result? {
                ClientOutcome::Committed(t) => return Ok(t),
                ClientOutcome::Conflict(certificate) => {
                    return Err(chain_client::Error::Conflict(certificate.hash()).into());
                }
                ClientOutcome::WaitForTimeout(timeout) => timeout,
            };
            // Otherwise wait and try again in the next round.
            util::wait_for_next_round(&mut notification_stream, timeout).await;
        }
    }

    /// Returns the ownership configuration of the given chain.
    pub async fn ownership(&mut self, chain_id: Option<ChainId>) -> Result<ChainOwnership, Error> {
        let chain_id = chain_id.unwrap_or_else(|| self.default_chain());
        let chain_client = self.make_chain_client(chain_id).await?;
        let info = chain_client.chain_info().await?;
        Ok(info.manager.ownership)
    }

    /// Changes the ownership configuration of the given chain.
    pub async fn change_ownership(
        &mut self,
        chain_id: Option<ChainId>,
        ownership_config: ChainOwnershipConfig,
    ) -> Result<(), Error> {
        let chain_id = chain_id.unwrap_or_else(|| self.default_chain());
        let chain_client = self.make_chain_client(chain_id).await?;
        info!(
            ?ownership_config, %chain_id, preferred_owner=?chain_client.preferred_owner(),
            "Changing ownership of a chain"
        );
        let time_start = Instant::now();
        let mut ownership = chain_client.query_chain_ownership().await?;
        ownership_config.update(&mut ownership)?;

        if ownership.super_owners.is_empty() && ownership.owners.is_empty() {
            tracing::error!("At least one owner or super owner of the chain has to be set.");
            return Err(error::Inner::ChainOwnership.into());
        }

        let certificate = self
            .apply_client_command(&chain_client, |chain_client| {
                let ownership = ownership.clone();
                let chain_client = chain_client.clone();
                async move {
                    chain_client
                        .change_ownership(ownership)
                        .await
                        .map_err(Error::from)
                        .context("Failed to change ownership")
                }
            })
            .await?;
        let time_total = time_start.elapsed();
        info!("Operation confirmed after {} ms", time_total.as_millis());
        debug!("{:?}", certificate);
        Ok(())
    }

    /// Sets the preferred owner used to propose blocks on the given chain.
    pub async fn set_preferred_owner(
        &mut self,
        chain_id: Option<ChainId>,
        preferred_owner: AccountOwner,
    ) -> Result<(), Error> {
        let chain_id = chain_id.unwrap_or_else(|| self.default_chain());
        let mut chain_client = self.make_chain_client(chain_id).await?;
        let old_owner = chain_client.preferred_owner();
        info!(%chain_id, ?old_owner, %preferred_owner, "Changing preferred owner for chain");
        chain_client.set_preferred_owner(preferred_owner);
        self.update_wallet_from_client(&chain_client).await?;
        info!("New preferred owner set");
        Ok(())
    }

    /// Checks that the validator's version info is compatible with the local version.
    pub async fn check_compatible_version_info(
        &self,
        address: &str,
        node: &impl ValidatorNode,
    ) -> Result<VersionInfo, Error> {
        match node.get_version_info().await {
            Ok(version_info) if version_info.is_compatible_with(&linera_version::VERSION_INFO) => {
                debug!(
                    "Version information for validator {address}: {}",
                    version_info
                );
                Ok(version_info)
            }
            Ok(version_info) => Err(error::Inner::UnexpectedVersionInfo {
                remote: Box::new(version_info),
                local: Box::new(linera_version::VERSION_INFO.clone()),
            }
            .into()),
            Err(error) => Err(error::Inner::UnavailableVersionInfo {
                address: address.to_string(),
                error: Box::new(error),
            }
            .into()),
        }
    }

    /// Checks that the validator's network description matches the local genesis config.
    pub async fn check_matching_network_description(
        &self,
        address: &str,
        node: &impl ValidatorNode,
    ) -> Result<CryptoHash, Error> {
        let network_description = self.genesis_config.network_description();
        match node.get_network_description().await {
            Ok(description) => {
                if description == network_description {
                    Ok(description.genesis_config_hash)
                } else {
                    Err(error::Inner::UnexpectedNetworkDescription {
                        remote: Box::new(description),
                        local: Box::new(network_description),
                    }
                    .into())
                }
            }
            Err(error) => Err(error::Inner::UnavailableNetworkDescription {
                address: address.to_string(),
                error: Box::new(error),
            }
            .into()),
        }
    }

    /// Queries a validator for the given chain's info and verifies its signature.
    pub async fn check_validator_chain_info_response(
        &self,
        public_key: Option<&ValidatorPublicKey>,
        address: &str,
        node: &impl ValidatorNode,
        chain_id: ChainId,
    ) -> Result<ChainInfo, Error> {
        let query = ChainInfoQuery::new(chain_id).with_manager_values();
        match node.handle_chain_info_query(query).await {
            Ok(response) => {
                debug!(
                    "Validator {address} sees chain {chain_id} at block height {} and epoch {:?}",
                    response.info.next_block_height, response.info.epoch,
                );
                if let Some(public_key) = public_key {
                    if response.check(*public_key).is_ok() {
                        debug!("Signature for public key {public_key} is OK.");
                    } else {
                        return Err(error::Inner::InvalidSignature {
                            public_key: *public_key,
                        }
                        .into());
                    }
                } else {
                    warn!("Not checking signature as public key was not given");
                }
                Ok(*response.info)
            }
            Err(error) => Err(error::Inner::UnavailableChainInfo {
                address: address.to_string(),
                chain_id,
                error: Box::new(error),
            }
            .into()),
        }
    }

    /// Query a validator for version info, network description, and chain info.
    ///
    /// Returns a `ValidatorQueryResults` struct with the results of all three queries.
    pub async fn query_validator(
        &self,
        address: &str,
        node: &impl ValidatorNode,
        chain_id: ChainId,
        public_key: Option<&ValidatorPublicKey>,
    ) -> ValidatorQueryResults {
        let version_info = self.check_compatible_version_info(address, node).await;
        let genesis_config_hash = self.check_matching_network_description(address, node).await;
        let chain_info = self
            .check_validator_chain_info_response(public_key, address, node, chain_id)
            .await;

        ValidatorQueryResults {
            version_info,
            genesis_config_hash,
            chain_info,
        }
    }

    /// Query the local node for version info, network description, and chain info.
    ///
    /// Returns a `ValidatorQueryResults` struct with the local node's information.
    pub async fn query_local_node(
        &self,
        chain_id: ChainId,
    ) -> Result<ValidatorQueryResults, Error> {
        let version_info = Ok(linera_version::VERSION_INFO.clone());
        let genesis_config_hash = Ok(self
            .genesis_config
            .network_description()
            .genesis_config_hash);
        let chain_info = self
            .make_chain_client(chain_id)
            .await?
            .chain_info_with_manager_values()
            .await
            .map(|info| *info)
            .map_err(|e| e.into());

        Ok(ValidatorQueryResults {
            version_info,
            genesis_config_hash,
            chain_info,
        })
    }
}

#[cfg(feature = "fs")]
impl<Env: Environment> ClientContext<Env> {
    /// Publishes a module from its contract and service bytecode files.
    pub async fn publish_module(
        &mut self,
        chain_client: &ChainClient<Env>,
        contract: PathBuf,
        service: PathBuf,
        vm_runtime: VmRuntime,
    ) -> Result<ModuleId, Error> {
        let (blobs, module_id) = load_bytecode_blobs(&contract, &service, vm_runtime).await?;

        info!("Publishing module");
        let (module_id, _) = self
            .apply_client_command(chain_client, |chain_client| {
                let blobs = blobs.clone();
                let chain_client = chain_client.clone();
                async move {
                    chain_client
                        .publish_module_blobs(blobs, module_id)
                        .await
                        .context("Failed to publish module")
                }
            })
            .await?;

        info!("{}", "Module published successfully!");

        info!("Synchronizing client and processing inbox");
        self.process_inbox(chain_client).await?;
        Ok(module_id)
    }

    /// Publishes a data blob loaded from the given file.
    pub async fn publish_data_blob(
        &mut self,
        chain_client: &ChainClient<Env>,
        blob_path: PathBuf,
    ) -> Result<CryptoHash, Error> {
        info!("Loading data blob file");
        let blob_bytes = fs::read(&blob_path).map_err(|e| {
            std::io::Error::new(
                e.kind(),
                format!("failed to load data blob bytes from {blob_path:?}: {e}"),
            )
        })?;

        info!("Publishing data blob");
        self.apply_client_command(chain_client, |chain_client| {
            let blob_bytes = blob_bytes.clone();
            let chain_client = chain_client.clone();
            async move {
                chain_client
                    .publish_data_blob(blob_bytes)
                    .await
                    .context("Failed to publish data blob")
            }
        })
        .await?;

        info!("{}", "Data blob published successfully!");
        Ok(CryptoHash::new(&BlobContent::new_data(blob_bytes)))
    }

    // TODO(#2490): Consider removing or renaming this.
    /// Verifies that a data blob with the given hash is available.
    pub async fn read_data_blob(
        &mut self,
        chain_client: &ChainClient<Env>,
        hash: CryptoHash,
    ) -> Result<(), Error> {
        info!("Verifying data blob");
        self.apply_client_command(chain_client, |chain_client| {
            let chain_client = chain_client.clone();
            async move {
                chain_client
                    .read_data_blob(hash)
                    .await
                    .context("Failed to verify data blob")
            }
        })
        .await?;

        info!("{}", "Data blob verified successfully!");
        Ok(())
    }
}

#[cfg(all(feature = "fs", not(web)))]
impl<Env: Environment> ClientContext<Env> {
    /// Publishes a module along with the JSON-encoded `Formats` description loaded
    /// from `formats`. The module publication and the formats-registry write
    /// happen atomically in a single block.
    pub async fn publish_module_with_formats(
        &mut self,
        chain_client: &ChainClient<Env>,
        contract: PathBuf,
        service: PathBuf,
        vm_runtime: VmRuntime,
        formats: PathBuf,
        registry_application_id: ApplicationId,
    ) -> Result<ModuleId, Error> {
        let owner = chain_client
            .preferred_owner()
            .ok_or(error::Inner::ChainOwnership)?;
        let (blobs, formats_blob_bytes, module_id, registry_op_bytes) = self
            .prepare_bcs_publication(owner, &contract, &service, vm_runtime, &formats)
            .await?;

        // Publish the formats data blob in its own block first, so it is committed
        // before the registry `Write` operation asserts its existence.
        info!("Publishing the formats data blob");
        self.apply_client_command(chain_client, |chain_client| {
            let formats_blob_bytes = formats_blob_bytes.clone();
            let chain_client = chain_client.clone();
            async move {
                chain_client
                    .publish_data_blob(formats_blob_bytes)
                    .await
                    .context("Failed to publish the formats data blob")
            }
        })
        .await?;

        info!("Publishing module and registering its formats");
        self.apply_client_command(chain_client, |chain_client| {
            let blobs = blobs.clone();
            let registry_op_bytes = registry_op_bytes.clone();
            let chain_client = chain_client.clone();
            async move {
                chain_client
                    .execute_operations(
                        vec![
                            Operation::system(SystemOperation::PublishModule { module_id }),
                            Operation::User {
                                application_id: registry_application_id,
                                bytes: registry_op_bytes,
                            },
                        ],
                        blobs,
                    )
                    .await
                    .context("Failed to publish module and register formats")
            }
        })
        .await?;

        info!(
            "{}",
            "Module published and formats registered successfully!"
        );
        info!("Synchronizing client and processing inbox");
        self.process_inbox(chain_client).await?;
        Ok(module_id)
    }

    /// Publishes a module, registers its `Formats` description in the formats
    /// registry, and creates an application from that module — all atomically in
    /// a single block.
    #[allow(clippy::too_many_arguments)]
    pub async fn publish_bcs_application(
        &mut self,
        chain_client: &ChainClient<Env>,
        contract: PathBuf,
        service: PathBuf,
        vm_runtime: VmRuntime,
        formats: PathBuf,
        registry_application_id: ApplicationId,
        parameters: Vec<u8>,
        instantiation_argument: Vec<u8>,
        required_application_ids: Vec<ApplicationId>,
    ) -> Result<(ApplicationId, ModuleId), Error> {
        let owner = chain_client
            .preferred_owner()
            .ok_or(error::Inner::ChainOwnership)?;
        let (blobs, formats_blob_bytes, module_id, registry_op_bytes) = self
            .prepare_bcs_publication(owner, &contract, &service, vm_runtime, &formats)
            .await?;

        // Publish the formats data blob in its own block first, so it is committed
        // before the registry `Write` operation asserts its existence.
        info!("Publishing the formats data blob");
        self.apply_client_command(chain_client, |chain_client| {
            let formats_blob_bytes = formats_blob_bytes.clone();
            let chain_client = chain_client.clone();
            async move {
                chain_client
                    .publish_data_blob(formats_blob_bytes)
                    .await
                    .context("Failed to publish the formats data blob")
            }
        })
        .await?;

        info!("Publishing module, registering its formats and creating the application");
        let application_id = self
            .apply_client_command(chain_client, |chain_client| {
                let blobs = blobs.clone();
                let registry_op_bytes = registry_op_bytes.clone();
                let parameters = parameters.clone();
                let instantiation_argument = instantiation_argument.clone();
                let required_application_ids = required_application_ids.clone();
                let chain_client = chain_client.clone();
                async move {
                    let outcome: ClientOutcome<ConfirmedBlockCertificate> = chain_client
                        .execute_operations(
                            vec![
                                Operation::system(SystemOperation::PublishModule { module_id }),
                                Operation::User {
                                    application_id: registry_application_id,
                                    bytes: registry_op_bytes,
                                },
                                Operation::system(SystemOperation::CreateApplication {
                                    module_id,
                                    parameters,
                                    instantiation_argument,
                                    required_application_ids,
                                }),
                            ],
                            blobs,
                        )
                        .await?;
                    outcome.try_map(|certificate| {
                        let mut creation: Vec<_> = certificate
                            .block()
                            .created_blob_ids()
                            .into_iter()
                            .filter(|blob_id| blob_id.blob_type == BlobType::ApplicationDescription)
                            .collect();
                        if creation.len() != 1 {
                            return Err(chain_client::Error::InternalError(
                                "Unexpected number of application descriptions published",
                            ));
                        }
                        let blob_id = creation.pop().expect("checked length");
                        Ok(ApplicationId::new(blob_id.hash))
                    })
                }
            })
            .await?;

        info!(
            "{}",
            "Module published, formats registered and application created successfully!"
        );
        info!("Synchronizing client and processing inbox");
        self.process_inbox(chain_client).await?;
        Ok((application_id, module_id))
    }

    /// Loads the bytecode files and the SNAP file, building the bytecode blobs, the
    /// BCS-encoded formats data blob, and the formats-registry write operation
    /// authorized by `owner`. The formats blob is returned separately from the
    /// bytecode blobs because the caller publishes it in its own block first (so it
    /// is committed before the registry `Write` operation asserts its existence).
    async fn prepare_bcs_publication(
        &self,
        owner: AccountOwner,
        contract: &Path,
        service: &Path,
        vm_runtime: VmRuntime,
        formats: &Path,
    ) -> Result<
        (
            Vec<linera_base::data_types::Blob>,
            Vec<u8>,
            ModuleId,
            Vec<u8>,
        ),
        Error,
    > {
        let (blobs, module_id) = load_bytecode_blobs(contract, service, vm_runtime).await?;

        info!("Loading formats from {formats:?}");
        let parsed = read_formats_from_snap(formats)?;
        let formats_blob_bytes = bcs::to_bytes(&parsed)?;
        let formats_blob_hash = CryptoHash::new(&BlobContent::new_data(formats_blob_bytes.clone()));
        let registry_op = linera_sdk::abis::formats_registry::Operation::Write {
            owner,
            module_id,
            blob_hash: linera_base::identifiers::DataBlobHash(formats_blob_hash),
        };
        let registry_op_bytes = bcs::to_bytes(&registry_op)?;
        Ok((blobs, formats_blob_bytes, module_id, registry_op_bytes))
    }
}

/// Reads the contract and service Wasm bytecode files from disk and turns them
/// into the blobs needed for module publication. Shared between
/// [`ClientContext::publish_module`] and the formats-aware variants so the two
/// code paths can't drift on error messages or blob construction.
#[cfg(feature = "fs")]
async fn load_bytecode_blobs(
    contract: &Path,
    service: &Path,
    vm_runtime: VmRuntime,
) -> Result<(Vec<linera_base::data_types::Blob>, ModuleId), Error> {
    info!("Loading bytecode files");
    let contract_bytecode = Bytecode::load_from_file(contract).map_err(|e| {
        std::io::Error::new(
            e.kind(),
            format!("failed to load contract bytecode from {contract:?}: {e}"),
        )
    })?;
    let service_bytecode = Bytecode::load_from_file(service).map_err(|e| {
        std::io::Error::new(
            e.kind(),
            format!("failed to load service bytecode from {service:?}: {e}"),
        )
    })?;
    Ok(create_bytecode_blobs(contract_bytecode, service_bytecode, vm_runtime).await)
}

/// Parses the `Formats` description of an application from a SNAP file (the YAML
/// snapshot produced by the `format` test of the example applications). The body
/// between the `---` frontmatter delimiters is deserialized as
/// [`linera_sdk::formats::Formats`]. BCS-serializing the result yields the data-blob
/// payload the formats registry expects, so external tooling can produce a blob file
/// ready for `linera publish-data-blob` (see the `extract-formats` binary in the
/// `formats-registry` example).
#[cfg(all(feature = "fs", not(web)))]
pub fn read_formats_from_snap(path: &Path) -> Result<linera_sdk::formats::Formats, Error> {
    let content = fs::read_to_string(path).map_err(|e| {
        std::io::Error::new(e.kind(), format!("failed to read SNAP file {path:?}: {e}"))
    })?;
    let body = strip_snap_frontmatter(&content).ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("SNAP file {path:?} is missing the `---` frontmatter delimiters"),
        )
    })?;
    serde_yaml_08::from_str(body).map_err(|e| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("failed to parse SNAP body in {path:?} as Formats: {e}"),
        )
        .into()
    })
}

#[cfg(all(feature = "fs", not(web)))]
fn strip_snap_frontmatter(content: &str) -> Option<&str> {
    let rest = content.strip_prefix("---\n")?;
    let end = rest.find("\n---\n")?;
    Some(&rest[end + "\n---\n".len()..])
}

#[cfg(all(test, feature = "fs", not(web)))]
mod snap_loader_tests {
    use super::read_formats_from_snap;

    #[test]
    fn parses_fungible_snap() {
        let path = std::path::Path::new("../examples/fungible/tests/snapshots/format__format.snap");
        read_formats_from_snap(path).expect("fungible snap should parse");
    }

    #[test]
    fn parses_social_snap() {
        let path = std::path::Path::new("../examples/social/tests/snapshots/format__format.snap");
        read_formats_from_snap(path).expect("social snap should parse");
    }

    #[test]
    fn parses_counter_snap() {
        let path = std::path::Path::new("../examples/counter/tests/snapshots/format__format.snap");
        read_formats_from_snap(path).expect("counter snap should parse");
    }
}

#[cfg(not(web))]
impl<Env: Environment> ClientContext<Env> {
    /// Prepares the chains and fungible tokens needed to run a benchmark.
    pub async fn prepare_for_benchmark(
        &mut self,
        num_chains: usize,
        tokens_per_chain: Amount,
        fungible_application_id: Option<ApplicationId>,
        pub_keys: Vec<AccountPublicKey>,
        chains_config_path: Option<&Path>,
        close_chains: bool,
    ) -> Result<Vec<ChainClient<Env>>, Error> {
        let start = Instant::now();
        // Below all block proposals are supposed to succeed without retries, we
        // must make sure that all incoming payments have been accepted on-chain
        // and that no validator is missing user certificates.
        self.process_inboxes_and_force_validator_updates().await;
        info!(
            "Processed inboxes and forced validator updates in {} ms",
            start.elapsed().as_millis()
        );

        let start = Instant::now();
        let (benchmark_chains, chain_clients) = self
            .make_benchmark_chains(
                num_chains,
                tokens_per_chain,
                pub_keys,
                chains_config_path.is_some(),
                close_chains,
            )
            .await?;
        info!(
            "Got {} chains in {} ms",
            num_chains,
            start.elapsed().as_millis()
        );

        if let Some(id) = fungible_application_id {
            let start = Instant::now();
            self.supply_fungible_tokens(&benchmark_chains, id).await?;
            info!(
                "Supplied fungible tokens in {} ms",
                start.elapsed().as_millis()
            );
            // Need to process inboxes to make sure the chains receive the supplied tokens.
            let start = Instant::now();
            for chain_client in &chain_clients {
                chain_client.process_inbox().await?;
            }
            info!(
                "Processed inboxes after supplying fungible tokens in {} ms",
                start.elapsed().as_millis()
            );
        }

        let all_chains = Benchmark::<Env>::get_all_chains(chains_config_path, &benchmark_chains)?;
        let known_chain_ids: HashSet<_> = benchmark_chains.iter().map(|(id, _)| *id).collect();
        let unknown_chain_ids: Vec<_> = all_chains
            .iter()
            .filter(|id| !known_chain_ids.contains(id))
            .copied()
            .collect();
        if !unknown_chain_ids.is_empty() {
            // The current client won't have the blobs for the chains in the other wallets. Even
            // though it will eventually get those blobs, we're getting a head start here and
            // fetching those blobs in advance.
            for chain_id in &unknown_chain_ids {
                self.client.get_chain_description(*chain_id).await?;
            }
        }

        Ok(chain_clients)
    }

    /// Closes the benchmark chains, or processes their inboxes and updates the wallet.
    pub async fn wrap_up_benchmark(
        &mut self,
        chain_clients: Vec<ChainClient<Env>>,
        close_chains: bool,
        wrap_up_max_in_flight: usize,
    ) -> Result<(), Error> {
        if close_chains {
            info!("Closing chains...");
            let chain_ids: Vec<_> = chain_clients.iter().map(|c| c.chain_id()).collect();
            let stream = stream::iter(chain_clients)
                .map(|chain_client| async move {
                    Benchmark::<Env>::close_benchmark_chain(&chain_client).await?;
                    info!("Closed chain {:?}", chain_client.chain_id());
                    Ok::<(), BenchmarkError>(())
                })
                .buffer_unordered(wrap_up_max_in_flight);
            stream.try_collect::<Vec<_>>().await?;
            // Remove closed chains from wallet (the chain listener may have added them).
            for chain_id in chain_ids {
                if let Err(error) = self.wallet().remove(chain_id).await {
                    warn!(%chain_id, %error, "Failed to remove closed chain from wallet");
                }
            }
        } else {
            info!("Processing inbox for all chains...");
            let stream = stream::iter(chain_clients.clone())
                .map(|chain_client| async move {
                    chain_client.process_inbox().await?;
                    info!("Processed inbox for chain {:?}", chain_client.chain_id());
                    Ok::<(), chain_client::Error>(())
                })
                .buffer_unordered(wrap_up_max_in_flight);
            stream.try_collect::<Vec<_>>().await?;

            info!("Updating wallet from chain clients...");
            for chain_client in chain_clients {
                let info = chain_client.chain_info().await?;
                let client_owner = chain_client.preferred_owner();
                let pending_proposal = chain_client
                    .pending_proposal()
                    .await
                    .filter(|p| p.round.is_some_and(|r| r.is_fast()));
                self.wallet()
                    .insert(
                        info.chain_id,
                        wallet::Chain {
                            pending_proposal,
                            owner: client_owner,
                            ..info.as_ref().into()
                        },
                    )
                    .await
                    .map_err(error::Inner::wallet)?;
            }
        }

        Ok(())
    }

    async fn process_inboxes_and_force_validator_updates(&mut self) {
        let mut join_set = task::JoinSet::new();

        let chain_clients: Vec<_> = self
            .wallet()
            .owned_chain_ids()
            .map_err(|e| error::Inner::wallet(e).into())
            .and_then(|id| self.make_chain_client(id))
            .try_collect()
            .await
            .unwrap();

        for chain_client in chain_clients {
            join_set.spawn(async move {
                Self::process_inbox_without_updating_wallet(&chain_client)
                    .await
                    .expect("Processing inbox should not fail!");
                chain_client
            });
        }

        for chain_client in join_set.join_all().await {
            self.update_wallet_from_client(&chain_client).await.unwrap();
        }
    }

    async fn process_inbox_without_updating_wallet(
        chain_client: &ChainClient<Env>,
    ) -> Result<Vec<ConfirmedBlockCertificate>, Error> {
        // Try processing the inbox optimistically without waiting for validator notifications.
        chain_client.synchronize_from_validators().await?;
        let (certificates, maybe_timeout) = chain_client.process_inbox_without_prepare().await?;
        assert!(
            maybe_timeout.is_none(),
            "Should not timeout within benchmark!"
        );

        Ok(certificates)
    }

    /// Creates chains if necessary, and returns a map of exactly `num_chains` chain IDs
    /// with key pairs, as well as a map of the chain clients.
    ///
    /// If `close_chains` is true, chains are not looked up from or stored in the wallet,
    /// since they will be closed after the benchmark and shouldn't be reused.
    async fn make_benchmark_chains(
        &mut self,
        num_chains: usize,
        balance: Amount,
        pub_keys: Vec<AccountPublicKey>,
        wallet_only: bool,
        close_chains: bool,
    ) -> Result<(Vec<(ChainId, AccountOwner)>, Vec<ChainClient<Env>>), Error> {
        let mut chains_found_in_wallet = 0;
        let mut benchmark_chains = Vec::with_capacity(num_chains);
        let mut chain_clients = Vec::with_capacity(num_chains);
        let start = Instant::now();

        // When close_chains is true and we're creating our own chains (not wallet_only),
        // skip wallet lookup to avoid picking up existing chains that would then be closed.
        // When wallet_only is true, chains were pre-created by the parent process and must
        // be read from the wallet.
        if !close_chains || wallet_only {
            let mut owned_chain_ids = std::pin::pin!(self.wallet().owned_chain_ids());
            while let Some(chain_id) = owned_chain_ids.next().await {
                let chain_id = chain_id.map_err(error::Inner::wallet)?;
                if chains_found_in_wallet == num_chains {
                    break;
                }
                let chain_client = self.make_chain_client(chain_id).await?;
                let ownership = chain_client.chain_info().await?.manager.ownership;
                if !ownership.owners.is_empty() || ownership.super_owners.len() != 1 {
                    continue;
                }
                let owner = *ownership.super_owners.first().unwrap();
                chain_client.process_inbox().await?;
                benchmark_chains.push((chain_id, owner));
                chain_clients.push(chain_client);
                chains_found_in_wallet += 1;
            }
            info!(
                "Got {} chains from the wallet in {} ms",
                benchmark_chains.len(),
                start.elapsed().as_millis()
            );
        }

        let num_chains_to_create = num_chains - chains_found_in_wallet;

        let default_chain_client = self.make_chain_client(self.default_chain()).await?;

        if num_chains_to_create > 0 {
            if wallet_only {
                return Err(
                    error::Inner::Benchmark(BenchmarkError::NotEnoughChainsInWallet(
                        num_chains,
                        chains_found_in_wallet,
                    ))
                    .into(),
                );
            }
            let mut pub_keys_iter = pub_keys.into_iter().take(num_chains_to_create);
            let operations_per_block = 900; // Over this we seem to hit the block size limits.
            for i in (0..num_chains_to_create).step_by(operations_per_block) {
                let num_new_chains = operations_per_block.min(num_chains_to_create - i);
                // Each chain gets its own unique owner (previously all chains in a batch
                // shared one owner, which could cause conflicts during benchmarking).
                let owners: Vec<AccountOwner> = (&mut pub_keys_iter)
                    .take(num_new_chains)
                    .map(|pk| pk.into())
                    .collect();

                let certificate = Self::execute_open_chains_operations(
                    &default_chain_client,
                    balance,
                    owners.clone(),
                )
                .await?;
                info!("Block executed successfully");

                let block = certificate.block();
                for (i, owner) in owners.into_iter().enumerate() {
                    let chain_id = block.body.blobs[i]
                        .iter()
                        .find(|blob| blob.id().blob_type == BlobType::ChainDescription)
                        .map(|blob| ChainId(blob.id().hash))
                        .expect("failed to create a new chain");
                    self.client
                        .extend_chain_mode(chain_id, ListeningMode::FullChain);

                    let mut chain_client = self.client.create_chain_client(
                        chain_id,
                        None,
                        BlockHeight::ZERO,
                        &None,
                        Some(owner),
                        self.timing_sender(),
                    );
                    chain_client.set_preferred_owner(owner);
                    chain_client.process_inbox().await?;
                    benchmark_chains.push((chain_id, owner));
                    chain_clients.push(chain_client);
                }
            }

            info!(
                "Created {} chains in {} ms",
                num_chains_to_create,
                start.elapsed().as_millis()
            );
        }

        // Only update wallet if chains will be reused (not closed after benchmark)
        if !close_chains {
            info!("Updating wallet from client");
            self.update_wallet_from_client(&default_chain_client)
                .await?;
        }
        info!("Retrying pending outgoing messages");
        default_chain_client
            .retry_pending_outgoing_messages()
            .await
            .context("outgoing messages to create the new chains should be delivered")?;
        info!("Processing default chain inbox");
        default_chain_client.process_inbox().await?;

        Ok((benchmark_chains, chain_clients))
    }

    async fn execute_open_chains_operations(
        chain_client: &ChainClient<Env>,
        balance: Amount,
        owners: Vec<AccountOwner>,
    ) -> Result<ConfirmedBlockCertificate, Error> {
        let operations: Vec<_> = owners
            .iter()
            .map(|owner| {
                let config = OpenChainConfig {
                    ownership: ChainOwnership::single_super(*owner),
                    balance,
                    application_permissions: Default::default(),
                };
                Operation::system(SystemOperation::OpenChain(config))
            })
            .collect();
        info!("Executing {} OpenChain operations", operations.len());
        Ok(chain_client
            .execute_operations(operations, vec![])
            .await?
            .expect("should execute block with OpenChain operations"))
    }

    /// Supplies fungible tokens to the chains.
    async fn supply_fungible_tokens(
        &mut self,
        key_pairs: &[(ChainId, AccountOwner)],
        application_id: ApplicationId,
    ) -> Result<(), Error> {
        let default_chain_id = self.default_chain();
        let default_key = self
            .wallet()
            .get(default_chain_id)
            .await
            .unwrap()
            .unwrap()
            .owner
            .unwrap();
        // This should be enough to run the benchmark at 1M TPS for an hour.
        let amount = Amount::from_nanos(4);
        let operations: Vec<Operation> = key_pairs
            .iter()
            .map(|(chain_id, owner)| {
                fungible_transfer(application_id, *chain_id, default_key, *owner, amount)
            })
            .collect();
        let chain_client = self.make_chain_client(default_chain_id).await?;
        // Put at most 1000 fungible token operations in each block.
        for operation_chunk in operations.chunks(1000) {
            chain_client
                .execute_operations(operation_chunk.to_vec(), vec![])
                .await?
                .expect("should execute block with Transfer operations");
        }
        self.update_wallet_from_client(&chain_client).await?;

        Ok(())
    }
}