linera-client 0.15.21

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
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::{
    collections::{BTreeMap, HashSet},
    fmt,
};

use linera_base::{
    data_types::{ApplicationPermissions, BlanketMessagePolicy, MessagePolicy, TimeDelta},
    identifiers::{AccountOwner, ApplicationId, ChainId, GenericApplicationId},
    ownership::ChainOwnership,
    time::Duration,
};
use linera_core::{
    client::{
        chain_client, DEFAULT_CERTIFICATE_DOWNLOAD_BATCH_SIZE,
        DEFAULT_CERTIFICATE_UPLOAD_BATCH_SIZE, DEFAULT_MAX_CONCURRENT_BATCH_DOWNLOADS,
        DEFAULT_MAX_EVENT_STREAM_QUERIES, DEFAULT_SENDER_CERTIFICATE_DOWNLOAD_BATCH_SIZE,
    },
    node::CrossChainMessageDelivery,
    DEFAULT_QUORUM_GRACE_PERIOD,
};
use linera_execution::ResourceControlPolicy;

#[cfg(not(web))]
use crate::client_metrics::TimingConfig;
use crate::util;

#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum Error {
    #[error("I/O error: {0}")]
    IoError(#[from] std::io::Error),
    #[error("there are {public_keys} public keys but {weights} weights")]
    MisalignedWeights { public_keys: usize, weights: usize },
    #[error("config error: {0}")]
    Config(#[from] crate::config::GenesisConfigError),
}

util::impl_from_infallible!(Error);

/// Command-line options controlling the behavior of the chain client.
#[derive(Clone, clap::Parser, serde::Deserialize, tsify::Tsify)]
#[tsify(from_wasm_abi)]
#[group(skip)]
#[serde(default, rename_all = "camelCase")]
pub struct Options {
    /// Timeout for sending queries (milliseconds)
    #[arg(long = "send-timeout-ms", default_value = "4000", value_parser = util::parse_millis)]
    pub send_timeout: Duration,

    /// Timeout for receiving responses (milliseconds)
    #[arg(long = "recv-timeout-ms", default_value = "4000", value_parser = util::parse_millis)]
    pub recv_timeout: Duration,

    /// The maximum number of incoming message bundles to include in a block proposal.
    #[arg(long, default_value = "300")]
    pub max_pending_message_bundles: usize,

    /// Maximum number of message bundles to discard from a block proposal due to block limit
    /// errors before discarding all remaining bundles.
    ///
    /// Discarded bundles can be retried in the next block.
    #[arg(long, default_value = "3")]
    pub max_block_limit_errors: u32,

    /// The maximum number of new stream events to include in a block proposal.
    #[arg(long, default_value = "10")]
    pub max_new_events_per_block: usize,

    /// Time budget for staging message bundles in milliseconds. When set, limits bundle
    /// execution by wall-clock time, in addition to the count limit from
    /// `max_pending_message_bundles`.
    #[arg(long = "staging-bundles-time-budget-ms", value_parser = util::parse_millis)]
    pub staging_bundles_time_budget: Option<Duration>,

    /// Comma-separated list of chain IDs whose incoming bundles should be processed first.
    #[arg(long, value_parser = util::parse_chain_set)]
    pub prioritize_bundles_from: Option<HashSet<ChainId>>,

    /// Comma-separated list of chain IDs whose incoming bundles should be ignored.
    #[arg(long, value_parser = util::parse_chain_set)]
    pub ignore_bundles_from: Option<HashSet<ChainId>>,

    /// The duration in milliseconds after which an idle chain worker will free its memory.
    #[arg(
        long = "chain-worker-ttl-ms",
        default_value = "30000",
        env = "LINERA_CHAIN_WORKER_TTL_MS",
        value_parser = util::parse_millis,
    )]
    pub chain_worker_ttl: Duration,

    /// The duration, in milliseconds, after which an idle sender chain worker will
    /// free its memory.
    #[arg(
        long = "sender-chain-worker-ttl-ms",
        default_value = "1000",
        env = "LINERA_SENDER_CHAIN_WORKER_TTL_MS",
        value_parser = util::parse_millis
    )]
    pub sender_chain_worker_ttl: Duration,

    /// Maximum number of cross-chain requests coalesced into a single batch by the
    /// per-chain driver. Bounds the worst-case write-lock hold time.
    #[arg(long, default_value_t = 1000)]
    pub cross_chain_batch_size_limit: usize,

    /// Delay increment for retrying to connect to a validator.
    #[arg(
        long = "retry-delay-ms",
        default_value = "1000",
        value_parser = util::parse_millis
    )]
    pub retry_delay: Duration,

    /// Number of times to retry connecting to a validator.
    #[arg(long, default_value = "10")]
    pub max_retries: u32,

    /// Maximum backoff delay for retrying to connect to a validator.
    #[arg(
        long = "max-backoff-ms",
        default_value = "30000",
        value_parser = util::parse_millis
    )]
    pub max_backoff: Duration,

    /// Initial probe interval (ms) for the notification circuit breaker. When a validator's
    /// notification stream exhausts retries, the circuit breaker waits this long before
    /// probing again. Doubles on each failed probe.
    #[arg(
        long = "notification-circuit-breaker-initial-probe-interval-ms",
        default_value = "300000",
        value_parser = util::parse_millis
    )]
    pub notification_circuit_breaker_initial_probe_interval: Duration,

    /// Maximum probe interval (ms) for the notification circuit breaker. The probe interval
    /// doubles on each failure but is capped at this value.
    #[arg(
        long = "notification-circuit-breaker-max-probe-interval-ms",
        default_value = "3600000",
        value_parser = util::parse_millis
    )]
    pub notification_circuit_breaker_max_probe_interval: Duration,

    /// Whether to wait until a quorum of validators has confirmed that all sent cross-chain
    /// messages have been delivered.
    #[arg(long)]
    pub wait_for_outgoing_messages: bool,

    /// Whether to allow creating blocks in the fast round. Fast blocks have lower latency but
    /// must be used carefully so that there are never any conflicting fast block proposals.
    #[arg(long)]
    pub allow_fast_blocks: bool,

    /// (EXPERIMENTAL) Whether application services can persist in some cases between queries.
    #[arg(long)]
    pub long_lived_services: bool,

    /// The policy for handling incoming messages.
    #[arg(long, default_value_t, value_enum)]
    pub blanket_message_policy: BlanketMessagePolicy,

    /// A set of chains to restrict incoming messages and events from. By default, messages and
    /// events from all chains are accepted. To reject all of them, specify an empty string. The
    /// admin chain's event stream is always followed regardless of this setting.
    #[arg(long, value_parser = util::parse_chain_set)]
    pub restrict_chain_ids_to: Option<HashSet<ChainId>>,

    /// A set of application IDs. If specified, only bundles with at least one message from one of
    /// these applications will be accepted.
    #[arg(long, value_parser = util::parse_app_set)]
    pub reject_message_bundles_without_application_ids: Option<HashSet<GenericApplicationId>>,

    /// A set of application IDs. If specified, only bundles where all messages are from one of
    /// these applications will be accepted.
    #[arg(long, value_parser = util::parse_app_set)]
    pub reject_message_bundles_with_other_application_ids: Option<HashSet<GenericApplicationId>>,

    /// A set of application IDs. If specified, only event streams created by applications from
    /// this set are processed and followed. The admin chain's event stream is always followed.
    #[arg(long, value_parser = util::parse_app_set)]
    pub process_events_from_application_ids: Option<HashSet<GenericApplicationId>>,

    /// A set of application IDs whose messages must never be rejected. Bundles whose messages
    /// are all from one of these applications bypass the other rejection rules (except
    /// `--restrict-chain-ids-to`), and on execution failure they (and subsequent bundles from
    /// the same sender) are removed from the block for later retry instead of being rejected,
    /// with a warning logged. Bundles that contain any message from an application not on this
    /// list can be rejected.
    #[arg(long, value_parser = util::parse_app_set)]
    pub never_reject_application_ids: Option<HashSet<GenericApplicationId>>,

    /// Enable timing reports during operations
    #[cfg(not(web))]
    #[arg(long)]
    pub timings: bool,

    /// Interval in seconds between timing reports (defaults to 5)
    #[cfg(not(web))]
    #[arg(long, default_value = "5")]
    pub timing_interval: u64,

    /// An additional delay, after reaching a quorum, to wait for additional validator signatures,
    /// as a fraction of time taken to reach quorum.
    #[arg(long, default_value_t = DEFAULT_QUORUM_GRACE_PERIOD)]
    pub quorum_grace_period: f64,

    /// The delay when downloading a blob, after which we try a second validator, in milliseconds.
    #[arg(
        long = "blob-download-hedge-delay-ms",
        default_value = "1000",
        value_parser = util::parse_millis,
    )]
    pub blob_download_hedge_delay: Duration,

    /// The delay when downloading a batch of certificates, after which we try a second validator,
    /// in milliseconds.
    #[arg(
        long = "cert-batch-download-hedge-delay-ms",
        default_value = "1000",
        value_parser = util::parse_millis
    )]
    pub certificate_batch_download_hedge_delay: Duration,

    /// Maximum number of certificates that we download at a time from one validator when
    /// synchronizing one of our chains.
    #[arg(
        long,
        default_value_t = DEFAULT_CERTIFICATE_DOWNLOAD_BATCH_SIZE,
    )]
    pub certificate_download_batch_size: u64,

    /// Maximum number of certificates read from local storage and uploaded to a validator
    /// at a time when synchronizing a chain.
    #[arg(
        long,
        default_value_t = DEFAULT_CERTIFICATE_UPLOAD_BATCH_SIZE,
    )]
    pub certificate_upload_batch_size: u64,

    /// Maximum number of sender certificates we try to download and receive in one go
    /// when syncing sender chains.
    #[arg(
        long,
        default_value_t = DEFAULT_SENDER_CERTIFICATE_DOWNLOAD_BATCH_SIZE,
    )]
    pub sender_certificate_download_batch_size: usize,

    /// Maximum number of certificate batches downloaded concurrently during chain sync.
    #[arg(long, default_value_t = DEFAULT_MAX_CONCURRENT_BATCH_DOWNLOADS)]
    pub max_concurrent_batch_downloads: usize,

    /// Maximum number of tasks that can are joined concurrently in the client.
    #[arg(long, default_value = "100")]
    pub max_joined_tasks: usize,

    /// Maximum number of event stream IDs to include in a single `PreviousEventBlocks`
    /// request. Larger sets are split into multiple requests.
    #[arg(long, default_value_t = DEFAULT_MAX_EVENT_STREAM_QUERIES)]
    pub max_event_stream_queries: usize,

    /// Maximum expected latency in milliseconds for score normalization.
    #[arg(
        long,
        default_value_t = linera_core::client::requests_scheduler::MAX_ACCEPTED_LATENCY_MS,
        env = "LINERA_REQUESTS_SCHEDULER_MAX_ACCEPTED_LATENCY_MS"
    )]
    pub max_accepted_latency_ms: f64,

    /// Time-to-live for cached responses in milliseconds.
    #[arg(
        long,
        default_value_t = linera_core::client::requests_scheduler::CACHE_TTL_MS,
        env = "LINERA_REQUESTS_SCHEDULER_CACHE_TTL_MS"
    )]
    pub cache_ttl_ms: u64,

    /// Maximum number of entries in the cache.
    #[arg(
        long,
        default_value_t = linera_core::client::requests_scheduler::CACHE_MAX_SIZE,
        env = "LINERA_REQUESTS_SCHEDULER_CACHE_MAX_SIZE"
    )]
    pub cache_max_size: usize,

    /// Maximum latency for an in-flight request before we stop deduplicating it (in milliseconds).
    #[arg(
        long,
        default_value_t = linera_core::client::requests_scheduler::MAX_REQUEST_TTL_MS,
        env = "LINERA_REQUESTS_SCHEDULER_MAX_REQUEST_TTL_MS"
    )]
    pub max_request_ttl_ms: u64,

    /// Smoothing factor for Exponential Moving Averages (0 < alpha < 1).
    /// Higher values give more weight to recent observations.
    /// Typical values are between 0.01 and 0.5.
    /// A value of 0.1 means that 10% of the new observation is considered
    /// and 90% of the previous average is retained.
    #[arg(
        long,
        default_value_t = linera_core::client::requests_scheduler::ALPHA_SMOOTHING_FACTOR,
        env = "LINERA_REQUESTS_SCHEDULER_ALPHA"
    )]
    pub alpha: f64,

    /// Delay in milliseconds between starting requests to different peers.
    /// This helps to stagger requests and avoid overwhelming the network.
    #[arg(
        long,
        default_value_t = linera_core::client::requests_scheduler::STAGGERED_DELAY_MS,
        env = "LINERA_REQUESTS_SCHEDULER_ALTERNATIVE_PEERS_RETRY_DELAY_MS"
    )]
    pub alternative_peers_retry_delay_ms: u64,

    /// Configuration for the chain listener.
    #[serde(flatten)]
    #[clap(flatten)]
    pub chain_listener_config: crate::chain_listener::ChainListenerConfig,
}

impl Default for Options {
    fn default() -> Self {
        use clap::Parser;

        #[derive(Parser)]
        struct OptionsParser {
            #[clap(flatten)]
            options: Options,
        }

        OptionsParser::try_parse_from(std::iter::empty::<std::ffi::OsString>())
            .expect("Options has no required arguments")
            .options
    }
}

impl Options {
    /// Creates [`chain_client::Options`] with the corresponding values.
    pub(crate) fn to_chain_client_options(&self) -> chain_client::Options {
        let message_policy = MessagePolicy {
            blanket: self.blanket_message_policy,
            restrict_chain_ids_to: self.restrict_chain_ids_to.clone(),
            ignore_chain_ids: self.ignore_bundles_from.clone().unwrap_or_default(),
            reject_message_bundles_without_application_ids: self
                .reject_message_bundles_without_application_ids
                .clone(),
            reject_message_bundles_with_other_application_ids: self
                .reject_message_bundles_with_other_application_ids
                .clone(),
            process_events_from_application_ids: self.process_events_from_application_ids.clone(),
            never_reject_application_ids: self
                .never_reject_application_ids
                .clone()
                .unwrap_or_default(),
        };
        let cross_chain_message_delivery =
            CrossChainMessageDelivery::new(self.wait_for_outgoing_messages);
        chain_client::Options {
            max_pending_message_bundles: self.max_pending_message_bundles,
            max_block_limit_errors: self.max_block_limit_errors,
            max_new_events_per_block: self.max_new_events_per_block,
            staging_bundles_time_budget: self.staging_bundles_time_budget,
            priority_bundle_origins: self.prioritize_bundles_from.clone().unwrap_or_default(),
            message_policy,
            cross_chain_message_delivery,
            quorum_grace_period: self.quorum_grace_period,
            blob_download_hedge_delay: self.blob_download_hedge_delay,
            certificate_batch_download_hedge_delay: self.certificate_batch_download_hedge_delay,
            certificate_download_batch_size: self.certificate_download_batch_size,
            certificate_upload_batch_size: self.certificate_upload_batch_size,
            sender_certificate_download_batch_size: self.sender_certificate_download_batch_size,
            max_concurrent_batch_downloads: self.max_concurrent_batch_downloads,
            max_joined_tasks: self.max_joined_tasks,
            allow_fast_blocks: self.allow_fast_blocks,
            notification_circuit_breaker_initial_probe_interval: self
                .notification_circuit_breaker_initial_probe_interval,
            notification_circuit_breaker_max_probe_interval: self
                .notification_circuit_breaker_max_probe_interval,
            max_event_stream_queries: self.max_event_stream_queries,
        }
    }

    /// Creates [`TimingConfig`] with the corresponding values.
    #[cfg(not(web))]
    pub(crate) fn to_timing_config(&self) -> TimingConfig {
        TimingConfig {
            enabled: self.timings,
            report_interval_secs: self.timing_interval,
        }
    }

    /// Creates [`RequestsSchedulerConfig`] with the corresponding values.
    pub(crate) fn to_requests_scheduler_config(
        &self,
    ) -> linera_core::client::RequestsSchedulerConfig {
        linera_core::client::RequestsSchedulerConfig {
            max_accepted_latency_ms: self.max_accepted_latency_ms,
            cache_ttl_ms: self.cache_ttl_ms,
            cache_max_size: self.cache_max_size,
            max_request_ttl_ms: self.max_request_ttl_ms,
            alpha: self.alpha,
            retry_delay_ms: self.alternative_peers_retry_delay_ms,
        }
    }
}

/// Command-line options for configuring the ownership of a chain.
#[derive(Debug, Clone, clap::Args)]
pub struct ChainOwnershipConfig {
    /// A JSON list of the new super owners. Absence of the option leaves the current
    /// set of super owners unchanged.
    // NOTE (applies to all fields): we need the std::option:: and std::vec:: qualifiers in order
    // to throw off the #[derive(Args)] macro's automatic inference of the type it should expect
    // from the parser. Without it, it infers the inner type (so either ApplicationId or
    // Vec<ApplicationId>), which is not what we want here - we want the parsers to return the full
    // expected types.
    #[arg(long, value_parser = util::parse_json::<Vec<AccountOwner>>)]
    pub super_owners: Option<std::vec::Vec<AccountOwner>>,

    /// A JSON map of the new owners to their weights. Absence of the option leaves the current
    /// set of owners unchanged.
    #[arg(long, value_parser = util::parse_json::<BTreeMap<AccountOwner, u64>>)]
    pub owners: Option<BTreeMap<AccountOwner, u64>>,

    /// The number of rounds in which every owner can propose blocks, i.e. the first round
    /// number in which only a single designated leader is allowed to propose blocks. "null" is
    /// equivalent to 2^32 - 1. Absence of the option leaves the current setting unchanged.
    #[arg(long, value_parser = util::parse_json::<Option<u32>>)]
    pub multi_leader_rounds: Option<std::option::Option<u32>>,

    /// Whether the multi-leader rounds are unrestricted, i.e. not limited to chain owners.
    /// This should only be `true` on chains with restrictive application permissions and an
    /// application-based mechanism to select block proposers.
    #[arg(long)]
    pub open_multi_leader_rounds: bool,

    /// The duration of the fast round, in milliseconds. "null" means the fast round will
    /// not time out. Absence of the option leaves the current setting unchanged.
    #[arg(long = "fast-round-ms", value_parser = util::parse_json_optional_millis_delta)]
    pub fast_round_duration: Option<std::option::Option<TimeDelta>>,

    /// The duration of the first single-leader and all multi-leader rounds. Absence of
    /// the option leaves the current setting unchanged.
    #[arg(
        long = "base-timeout-ms",
        value_parser = util::parse_millis_delta
    )]
    pub base_timeout: Option<TimeDelta>,

    /// The number of milliseconds by which the timeout increases after each
    /// single-leader round. Absence of the option leaves the current setting unchanged.
    #[arg(
        long = "timeout-increment-ms",
        value_parser = util::parse_millis_delta
    )]
    pub timeout_increment: Option<TimeDelta>,

    /// The age of an incoming tracked or protected message after which the validators start
    /// transitioning the chain to fallback mode, in milliseconds. Absence of the option
    /// leaves the current setting unchanged.
    #[arg(
        long = "fallback-duration-ms",
        value_parser = util::parse_millis_delta
    )]
    pub fallback_duration: Option<TimeDelta>,
}

impl ChainOwnershipConfig {
    /// Applies the configured ownership overrides to the given chain ownership.
    pub fn update(self, chain_ownership: &mut ChainOwnership) -> Result<(), Error> {
        let ChainOwnershipConfig {
            super_owners,
            owners,
            multi_leader_rounds,
            fast_round_duration,
            open_multi_leader_rounds,
            base_timeout,
            timeout_increment,
            fallback_duration,
        } = self;

        if let Some(owners) = owners {
            chain_ownership.owners = owners;
        }

        if let Some(super_owners) = super_owners {
            chain_ownership.super_owners = super_owners.into_iter().collect();
        }

        if let Some(multi_leader_rounds) = multi_leader_rounds {
            chain_ownership.multi_leader_rounds = multi_leader_rounds.unwrap_or(u32::MAX);
        }

        chain_ownership.open_multi_leader_rounds = open_multi_leader_rounds;

        if let Some(fast_round_duration) = fast_round_duration {
            chain_ownership.timeout_config.fast_round_duration = fast_round_duration;
        }
        if let Some(base_timeout) = base_timeout {
            chain_ownership.timeout_config.base_timeout = base_timeout;
        }
        if let Some(timeout_increment) = timeout_increment {
            chain_ownership.timeout_config.timeout_increment = timeout_increment;
        }
        if let Some(fallback_duration) = fallback_duration {
            chain_ownership.timeout_config.fallback_duration = fallback_duration;
        }

        Ok(())
    }
}

impl TryFrom<ChainOwnershipConfig> for ChainOwnership {
    type Error = Error;

    fn try_from(config: ChainOwnershipConfig) -> Result<ChainOwnership, Error> {
        let mut chain_ownership = ChainOwnership::default();
        config.update(&mut chain_ownership)?;
        Ok(chain_ownership)
    }
}

/// Command-line options for configuring application permissions on a chain.
#[derive(Debug, Clone, clap::Args)]
pub struct ApplicationPermissionsConfig {
    /// A JSON list of applications allowed to execute operations on this chain. If set to null, all
    /// operations will be allowed. Otherwise, only operations from the specified applications are
    /// allowed, and no system operations. Absence of the option leaves current permissions
    /// unchanged.
    // NOTE (applies to all fields): we need the std::option:: and std::vec:: qualifiers in order
    // to throw off the #[derive(Args)] macro's automatic inference of the type it should expect
    // from the parser. Without it, it infers the inner type (so either ApplicationId or
    // Vec<ApplicationId>), which is not what we want here - we want the parsers to return the full
    // expected types.
    #[arg(long, value_parser = util::parse_json::<Option<Vec<ApplicationId>>>)]
    pub execute_operations: Option<std::option::Option<Vec<ApplicationId>>>,
    /// A JSON list of applications, such that at least one operation or incoming message from each
    /// of these applications must occur in every block. Absence of the option leaves
    /// current mandatory applications unchanged.
    #[arg(long, value_parser = util::parse_json::<Vec<ApplicationId>>)]
    pub mandatory_applications: Option<std::vec::Vec<ApplicationId>>,
    /// A JSON list of applications allowed to close the chain. Absence of the option leaves
    /// the current list unchanged.
    #[arg(long, value_parser = util::parse_json::<Vec<ApplicationId>>)]
    pub close_chain: Option<std::vec::Vec<ApplicationId>>,
    /// A JSON list of applications allowed to change the application permissions on the current
    /// chain using the system API. Absence of the option leaves the current list unchanged.
    #[arg(long, value_parser = util::parse_json::<Vec<ApplicationId>>)]
    pub change_application_permissions: Option<std::vec::Vec<ApplicationId>>,
    /// A JSON list of applications that are allowed to call services as oracles on the current
    /// chain using the system API. If set to null, all applications will be able to do
    /// so. Absence of the option leaves the current value of the setting unchanged.
    #[arg(long, value_parser = util::parse_json::<Option<Vec<ApplicationId>>>)]
    pub call_service_as_oracle: Option<std::option::Option<Vec<ApplicationId>>>,
    /// A JSON list of applications that are allowed to make HTTP requests on the current chain
    /// using the system API. If set to null, all applications will be able to do so.
    /// Absence of the option leaves the current value of the setting unchanged.
    #[arg(long, value_parser = util::parse_json::<Option<Vec<ApplicationId>>>)]
    pub make_http_requests: Option<std::option::Option<Vec<ApplicationId>>>,
}

impl ApplicationPermissionsConfig {
    /// Applies the configured permission overrides to the given application permissions.
    pub fn update(self, application_permissions: &mut ApplicationPermissions) {
        if let Some(execute_operations) = self.execute_operations {
            application_permissions.execute_operations = execute_operations;
        }
        if let Some(mandatory_applications) = self.mandatory_applications {
            application_permissions.mandatory_applications = mandatory_applications;
        }
        if let Some(close_chain) = self.close_chain {
            application_permissions.close_chain = close_chain;
        }
        if let Some(change_application_permissions) = self.change_application_permissions {
            application_permissions.change_application_permissions = change_application_permissions;
        }
        if let Some(call_service_as_oracle) = self.call_service_as_oracle {
            application_permissions.call_service_as_oracle = call_service_as_oracle;
        }
        if let Some(make_http_requests) = self.make_http_requests {
            application_permissions.make_http_requests = make_http_requests;
        }
    }
}

/// A named preset selecting which resource control policy the chain should use.
#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResourceControlPolicyConfig {
    /// Charges nothing for any resource, with no usage limits.
    NoFees,
    /// Uses the fees and limits that match the public Testnet.
    Testnet,
    /// Charges only for fuel, leaving all other resources free (for testing).
    #[cfg(with_testing)]
    OnlyFuel,
    /// Charges a small non-zero amount in every fee category (for testing).
    #[cfg(with_testing)]
    AllCategories,
}

impl ResourceControlPolicyConfig {
    /// Converts this config into the corresponding resource control policy.
    pub fn into_policy(self) -> ResourceControlPolicy {
        match self {
            ResourceControlPolicyConfig::NoFees => ResourceControlPolicy::no_fees(),
            ResourceControlPolicyConfig::Testnet => ResourceControlPolicy::testnet(),
            #[cfg(with_testing)]
            ResourceControlPolicyConfig::OnlyFuel => ResourceControlPolicy::only_fuel(),
            #[cfg(with_testing)]
            ResourceControlPolicyConfig::AllCategories => ResourceControlPolicy::all_categories(),
        }
    }
}

impl std::str::FromStr for ResourceControlPolicyConfig {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        clap::ValueEnum::from_str(s, true)
    }
}

impl fmt::Display for ResourceControlPolicyConfig {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{self:?}")
    }
}