linera_service/cli_wrappers/
wallet.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{
5    borrow::Cow,
6    collections::BTreeMap,
7    env,
8    marker::PhantomData,
9    mem,
10    path::{Path, PathBuf},
11    pin::Pin,
12    process::Stdio,
13    str::FromStr,
14    sync,
15    time::Duration,
16};
17
18use anyhow::{bail, ensure, Context, Result};
19use async_graphql::InputType;
20use async_tungstenite::tungstenite::{client::IntoClientRequest as _, http::HeaderValue};
21use futures::{SinkExt as _, Stream, StreamExt as _, TryStreamExt as _};
22use heck::ToKebabCase;
23use linera_base::{
24    abi::ContractAbi,
25    command::{resolve_binary, CommandExt},
26    crypto::{CryptoHash, InMemorySigner},
27    data_types::{Amount, BlockHeight, Bytecode, Epoch},
28    identifiers::{
29        Account, AccountOwner, ApplicationId, ChainId, IndexAndEvent, ModuleId, StreamId,
30    },
31    vm::VmRuntime,
32};
33use linera_client::client_options::ResourceControlPolicyConfig;
34use linera_core::worker::Notification;
35use linera_execution::committee::Committee;
36use linera_faucet_client::Faucet;
37use serde::{de::DeserializeOwned, ser::Serialize};
38use serde_command_opts::to_args;
39use serde_json::{json, Value};
40use tempfile::TempDir;
41use tokio::{
42    io::{AsyncBufReadExt, BufReader},
43    process::{Child, Command},
44    sync::oneshot,
45    task::JoinHandle,
46};
47#[cfg(with_testing)]
48use {
49    futures::FutureExt as _,
50    linera_core::worker::Reason,
51    std::{collections::BTreeSet, future::Future},
52};
53
54use crate::{
55    cli::command::BenchmarkCommand,
56    cli_wrappers::{
57        local_net::{PathProvider, ProcessInbox},
58        Network,
59    },
60    util::{self, ChildExt},
61    wallet::Wallet,
62};
63
64/// The name of the environment variable that allows specifying additional arguments to be passed
65/// to the node-service command of the client.
66const CLIENT_SERVICE_ENV: &str = "LINERA_CLIENT_SERVICE_PARAMS";
67
68fn reqwest_client() -> reqwest::Client {
69    reqwest::ClientBuilder::new()
70        .timeout(Duration::from_secs(30))
71        .build()
72        .unwrap()
73}
74
75/// Wrapper to run a Linera client command.
76pub struct ClientWrapper {
77    binary_path: sync::Mutex<Option<PathBuf>>,
78    testing_prng_seed: Option<u64>,
79    storage: String,
80    wallet: String,
81    keystore: String,
82    max_pending_message_bundles: usize,
83    network: Network,
84    pub path_provider: PathProvider,
85    on_drop: OnClientDrop,
86    extra_args: Vec<String>,
87}
88
89/// Action to perform when the [`ClientWrapper`] is dropped.
90#[derive(Clone, Copy, Debug, Eq, PartialEq)]
91pub enum OnClientDrop {
92    /// Close all the chains on the wallet.
93    CloseChains,
94    /// Do not close any chains, leaving them active.
95    LeakChains,
96}
97
98impl ClientWrapper {
99    pub fn new(
100        path_provider: PathProvider,
101        network: Network,
102        testing_prng_seed: Option<u64>,
103        id: usize,
104        on_drop: OnClientDrop,
105    ) -> Self {
106        Self::new_with_extra_args(
107            path_provider,
108            network,
109            testing_prng_seed,
110            id,
111            on_drop,
112            vec!["--wait-for-outgoing-messages".to_string()],
113        )
114    }
115
116    pub fn new_with_extra_args(
117        path_provider: PathProvider,
118        network: Network,
119        testing_prng_seed: Option<u64>,
120        id: usize,
121        on_drop: OnClientDrop,
122        extra_args: Vec<String>,
123    ) -> Self {
124        let storage = format!(
125            "rocksdb:{}/client_{}.db",
126            path_provider.path().display(),
127            id
128        );
129        let wallet = format!("wallet_{}.json", id);
130        let keystore = format!("keystore_{}.json", id);
131        Self {
132            binary_path: sync::Mutex::new(None),
133            testing_prng_seed,
134            storage,
135            wallet,
136            keystore,
137            max_pending_message_bundles: 10_000,
138            network,
139            path_provider,
140            on_drop,
141            extra_args,
142        }
143    }
144
145    /// Runs `linera project new`.
146    pub async fn project_new(&self, project_name: &str, linera_root: &Path) -> Result<TempDir> {
147        let tmp = TempDir::new()?;
148        let mut command = self.command().await?;
149        command
150            .current_dir(tmp.path())
151            .arg("project")
152            .arg("new")
153            .arg(project_name)
154            .arg("--linera-root")
155            .arg(linera_root)
156            .spawn_and_wait_for_stdout()
157            .await?;
158        Ok(tmp)
159    }
160
161    /// Runs `linera project publish`.
162    pub async fn project_publish<T: Serialize>(
163        &self,
164        path: PathBuf,
165        required_application_ids: Vec<String>,
166        publisher: impl Into<Option<ChainId>>,
167        argument: &T,
168    ) -> Result<String> {
169        let json_parameters = serde_json::to_string(&())?;
170        let json_argument = serde_json::to_string(argument)?;
171        let mut command = self.command().await?;
172        command
173            .arg("project")
174            .arg("publish-and-create")
175            .arg(path)
176            .args(publisher.into().iter().map(ChainId::to_string))
177            .args(["--json-parameters", &json_parameters])
178            .args(["--json-argument", &json_argument]);
179        if !required_application_ids.is_empty() {
180            command.arg("--required-application-ids");
181            command.args(required_application_ids);
182        }
183        let stdout = command.spawn_and_wait_for_stdout().await?;
184        Ok(stdout.trim().to_string())
185    }
186
187    /// Runs `linera project test`.
188    pub async fn project_test(&self, path: &Path) -> Result<()> {
189        self.command()
190            .await
191            .context("failed to create project test command")?
192            .current_dir(path)
193            .arg("project")
194            .arg("test")
195            .spawn_and_wait_for_stdout()
196            .await?;
197        Ok(())
198    }
199
200    async fn command_with_envs_and_arguments(
201        &self,
202        envs: &[(&str, &str)],
203        arguments: impl IntoIterator<Item = Cow<'_, str>>,
204    ) -> Result<Command> {
205        let mut command = self.command_binary().await?;
206        command.current_dir(self.path_provider.path());
207        for (key, value) in envs {
208            command.env(key, value);
209        }
210        for argument in arguments {
211            command.arg(&*argument);
212        }
213        Ok(command)
214    }
215
216    async fn command_with_envs(&self, envs: &[(&str, &str)]) -> Result<Command> {
217        self.command_with_envs_and_arguments(envs, self.command_arguments())
218            .await
219    }
220
221    async fn command_with_arguments(
222        &self,
223        arguments: impl IntoIterator<Item = Cow<'_, str>>,
224    ) -> Result<Command> {
225        self.command_with_envs_and_arguments(
226            &[(
227                "RUST_LOG",
228                &std::env::var("RUST_LOG").unwrap_or(String::from("linera=debug")),
229            )],
230            arguments,
231        )
232        .await
233    }
234
235    async fn command(&self) -> Result<Command> {
236        self.command_with_envs(&[(
237            "RUST_LOG",
238            &std::env::var("RUST_LOG").unwrap_or(String::from("linera=debug")),
239        )])
240        .await
241    }
242
243    fn required_command_arguments(&self) -> impl Iterator<Item = Cow<'_, str>> + '_ {
244        [
245            "--wallet".into(),
246            self.wallet.as_str().into(),
247            "--keystore".into(),
248            self.keystore.as_str().into(),
249            "--storage".into(),
250            self.storage.as_str().into(),
251            "--send-timeout-ms".into(),
252            "500000".into(),
253            "--recv-timeout-ms".into(),
254            "500000".into(),
255        ]
256        .into_iter()
257        .chain(self.extra_args.iter().map(|s| s.as_str().into()))
258    }
259
260    /// Returns an iterator over the arguments that should be added to all command invocations.
261    fn command_arguments(&self) -> impl Iterator<Item = Cow<'_, str>> + '_ {
262        self.required_command_arguments().chain([
263            "--max-pending-message-bundles".into(),
264            self.max_pending_message_bundles.to_string().into(),
265        ])
266    }
267
268    /// Returns the [`Command`] instance configured to run the appropriate binary.
269    ///
270    /// The path is resolved once and cached inside `self` for subsequent usages.
271    async fn command_binary(&self) -> Result<Command> {
272        match self.command_with_cached_binary_path() {
273            Some(command) => Ok(command),
274            None => {
275                let resolved_path = resolve_binary("linera", env!("CARGO_PKG_NAME")).await?;
276                let command = Command::new(&resolved_path);
277
278                self.set_cached_binary_path(resolved_path);
279
280                Ok(command)
281            }
282        }
283    }
284
285    /// Returns a [`Command`] instance configured with the cached `binary_path`, if available.
286    fn command_with_cached_binary_path(&self) -> Option<Command> {
287        let binary_path = self.binary_path.lock().unwrap();
288
289        binary_path.as_ref().map(Command::new)
290    }
291
292    /// Sets the cached `binary_path` with the `new_binary_path`.
293    ///
294    /// # Panics
295    ///
296    /// If the cache is already set to a different value. In theory the two threads calling
297    /// `command_binary` can race and resolve the binary path twice, but they should always be the
298    /// same path.
299    fn set_cached_binary_path(&self, new_binary_path: PathBuf) {
300        let mut binary_path = self.binary_path.lock().unwrap();
301
302        if binary_path.is_none() {
303            *binary_path = Some(new_binary_path);
304        } else {
305            assert_eq!(*binary_path, Some(new_binary_path));
306        }
307    }
308
309    /// Runs `linera create-genesis-config`.
310    pub async fn create_genesis_config(
311        &self,
312        num_other_initial_chains: u32,
313        initial_funding: Amount,
314        policy_config: ResourceControlPolicyConfig,
315        http_allow_list: Option<Vec<String>>,
316    ) -> Result<()> {
317        let mut command = self.command().await?;
318        command
319            .args([
320                "create-genesis-config",
321                &num_other_initial_chains.to_string(),
322            ])
323            .args(["--initial-funding", &initial_funding.to_string()])
324            .args(["--committee", "committee.json"])
325            .args(["--genesis", "genesis.json"])
326            .args([
327                "--policy-config",
328                &policy_config.to_string().to_kebab_case(),
329            ]);
330        if let Some(allow_list) = http_allow_list {
331            command
332                .arg("--http-request-allow-list")
333                .arg(allow_list.join(","));
334        }
335        if let Some(seed) = self.testing_prng_seed {
336            command.arg("--testing-prng-seed").arg(seed.to_string());
337        }
338        command.spawn_and_wait_for_stdout().await?;
339        Ok(())
340    }
341
342    /// Runs `linera wallet init`. The genesis config is read from `genesis.json`, or from the
343    /// faucet if provided.
344    pub async fn wallet_init(&self, faucet: Option<&'_ Faucet>) -> Result<()> {
345        let mut command = self.command().await?;
346        command.args(["wallet", "init"]);
347        match faucet {
348            None => command.args(["--genesis", "genesis.json"]),
349            Some(faucet) => command.args(["--faucet", faucet.url()]),
350        };
351        if let Some(seed) = self.testing_prng_seed {
352            command.arg("--testing-prng-seed").arg(seed.to_string());
353        }
354        command.spawn_and_wait_for_stdout().await?;
355        Ok(())
356    }
357
358    /// Runs `linera wallet request-chain`.
359    pub async fn request_chain(
360        &self,
361        faucet: &Faucet,
362        set_default: bool,
363    ) -> Result<(ChainId, AccountOwner)> {
364        let mut command = self.command().await?;
365        command.args(["wallet", "request-chain", "--faucet", faucet.url()]);
366        if set_default {
367            command.arg("--set-default");
368        }
369        let stdout = command.spawn_and_wait_for_stdout().await?;
370        let mut lines = stdout.split_whitespace();
371        let chain_id: ChainId = lines.next().context("missing chain ID")?.parse()?;
372        let owner = lines.next().context("missing chain owner")?.parse()?;
373        Ok((chain_id, owner))
374    }
375
376    /// Runs `linera wallet publish-and-create`.
377    #[expect(clippy::too_many_arguments)]
378    pub async fn publish_and_create<
379        A: ContractAbi,
380        Parameters: Serialize,
381        InstantiationArgument: Serialize,
382    >(
383        &self,
384        contract: PathBuf,
385        service: PathBuf,
386        vm_runtime: VmRuntime,
387        parameters: &Parameters,
388        argument: &InstantiationArgument,
389        required_application_ids: &[ApplicationId],
390        publisher: impl Into<Option<ChainId>>,
391    ) -> Result<ApplicationId<A>> {
392        let json_parameters = serde_json::to_string(parameters)?;
393        let json_argument = serde_json::to_string(argument)?;
394        let mut command = self.command().await?;
395        let vm_runtime = format!("{}", vm_runtime);
396        command
397            .arg("publish-and-create")
398            .args([contract, service])
399            .args(["--vm-runtime", &vm_runtime.to_lowercase()])
400            .args(publisher.into().iter().map(ChainId::to_string))
401            .args(["--json-parameters", &json_parameters])
402            .args(["--json-argument", &json_argument]);
403        if !required_application_ids.is_empty() {
404            command.arg("--required-application-ids");
405            command.args(
406                required_application_ids
407                    .iter()
408                    .map(ApplicationId::to_string),
409            );
410        }
411        let stdout = command.spawn_and_wait_for_stdout().await?;
412        Ok(stdout.trim().parse::<ApplicationId>()?.with_abi())
413    }
414
415    /// Runs `linera publish-module`.
416    pub async fn publish_module<Abi, Parameters, InstantiationArgument>(
417        &self,
418        contract: PathBuf,
419        service: PathBuf,
420        vm_runtime: VmRuntime,
421        publisher: impl Into<Option<ChainId>>,
422    ) -> Result<ModuleId<Abi, Parameters, InstantiationArgument>> {
423        let stdout = self
424            .command()
425            .await?
426            .arg("publish-module")
427            .args([contract, service])
428            .args(["--vm-runtime", &format!("{}", vm_runtime).to_lowercase()])
429            .args(publisher.into().iter().map(ChainId::to_string))
430            .spawn_and_wait_for_stdout()
431            .await?;
432        let module_id: ModuleId = stdout.trim().parse()?;
433        Ok(module_id.with_abi())
434    }
435
436    /// Runs `linera create-application`.
437    pub async fn create_application<
438        Abi: ContractAbi,
439        Parameters: Serialize,
440        InstantiationArgument: Serialize,
441    >(
442        &self,
443        module_id: &ModuleId<Abi, Parameters, InstantiationArgument>,
444        parameters: &Parameters,
445        argument: &InstantiationArgument,
446        required_application_ids: &[ApplicationId],
447        creator: impl Into<Option<ChainId>>,
448    ) -> Result<ApplicationId<Abi>> {
449        let json_parameters = serde_json::to_string(parameters)?;
450        let json_argument = serde_json::to_string(argument)?;
451        let mut command = self.command().await?;
452        command
453            .arg("create-application")
454            .arg(module_id.forget_abi().to_string())
455            .args(["--json-parameters", &json_parameters])
456            .args(["--json-argument", &json_argument])
457            .args(creator.into().iter().map(ChainId::to_string));
458        if !required_application_ids.is_empty() {
459            command.arg("--required-application-ids");
460            command.args(
461                required_application_ids
462                    .iter()
463                    .map(ApplicationId::to_string),
464            );
465        }
466        let stdout = command.spawn_and_wait_for_stdout().await?;
467        Ok(stdout.trim().parse::<ApplicationId>()?.with_abi())
468    }
469
470    /// Runs `linera service`.
471    pub async fn run_node_service(
472        &self,
473        port: impl Into<Option<u16>>,
474        process_inbox: ProcessInbox,
475    ) -> Result<NodeService> {
476        self.run_node_service_with_options(port, process_inbox, &[], &[], false)
477            .await
478    }
479
480    /// Runs `linera service` with optional task processor configuration.
481    pub async fn run_node_service_with_options(
482        &self,
483        port: impl Into<Option<u16>>,
484        process_inbox: ProcessInbox,
485        operator_application_ids: &[ApplicationId],
486        operators: &[(String, PathBuf)],
487        read_only: bool,
488    ) -> Result<NodeService> {
489        let port = port.into().unwrap_or(8080);
490        let mut command = self.command().await?;
491        command.arg("service");
492        if let ProcessInbox::Skip = process_inbox {
493            command.arg("--listener-skip-process-inbox");
494        }
495        if let Ok(var) = env::var(CLIENT_SERVICE_ENV) {
496            command.args(var.split_whitespace());
497        }
498        for app_id in operator_application_ids {
499            command.args(["--operator-application-ids", &app_id.to_string()]);
500        }
501        for (name, path) in operators {
502            command.args(["--operators", &format!("{}={}", name, path.display())]);
503        }
504        if read_only {
505            command.arg("--read-only");
506        }
507        let child = command
508            .args(["--port".to_string(), port.to_string()])
509            .spawn_into()?;
510        let client = reqwest_client();
511        for i in 0..10 {
512            linera_base::time::timer::sleep(Duration::from_secs(i)).await;
513            let request = client
514                .get(format!("http://localhost:{}/", port))
515                .send()
516                .await;
517            if request.is_ok() {
518                tracing::info!("Node service has started");
519                return Ok(NodeService::new(port, child));
520            } else {
521                tracing::warn!("Waiting for node service to start");
522            }
523        }
524        bail!("Failed to start node service");
525    }
526
527    /// Runs `linera validator query`
528    pub async fn query_validator(&self, address: &str) -> Result<CryptoHash> {
529        let mut command = self.command().await?;
530        command.arg("validator").arg("query").arg(address);
531        let stdout = command.spawn_and_wait_for_stdout().await?;
532
533        // Parse the genesis config hash from the output.
534        // It's on a line like "Genesis config hash: <hash>"
535        let hash = stdout
536            .lines()
537            .find_map(|line| {
538                line.strip_prefix("Genesis config hash: ")
539                    .and_then(|hash_str| hash_str.trim().parse().ok())
540            })
541            .context("error while parsing the result of `linera validator query`")?;
542        Ok(hash)
543    }
544
545    /// Runs `linera validator list`.
546    pub async fn query_validators(&self, chain_id: Option<ChainId>) -> Result<()> {
547        let mut command = self.command().await?;
548        command.arg("validator").arg("list");
549        if let Some(chain_id) = chain_id {
550            command.args(["--chain-id", &chain_id.to_string()]);
551        }
552        command.spawn_and_wait_for_stdout().await?;
553        Ok(())
554    }
555
556    /// Runs `linera sync-validator`.
557    pub async fn sync_validator(
558        &self,
559        chain_ids: impl IntoIterator<Item = &ChainId>,
560        validator_address: impl Into<String>,
561    ) -> Result<()> {
562        let mut command = self.command().await?;
563        command
564            .arg("validator")
565            .arg("sync")
566            .arg(validator_address.into());
567        let mut chain_ids = chain_ids.into_iter().peekable();
568        if chain_ids.peek().is_some() {
569            command
570                .arg("--chains")
571                .args(chain_ids.map(ChainId::to_string));
572        }
573        command.spawn_and_wait_for_stdout().await?;
574        Ok(())
575    }
576
577    /// Runs `linera faucet`.
578    pub async fn run_faucet(
579        &self,
580        port: impl Into<Option<u16>>,
581        chain_id: Option<ChainId>,
582        amount: Amount,
583    ) -> Result<FaucetService> {
584        let port = port.into().unwrap_or(8080);
585        let temp_dir = tempfile::tempdir()
586            .context("Failed to create temporary directory for faucet storage")?;
587        let storage_path = temp_dir.path().join("faucet_storage.sqlite");
588        let mut command = self.command().await?;
589        let command = command
590            .arg("faucet")
591            .args(["--port".to_string(), port.to_string()])
592            .args(["--amount".to_string(), amount.to_string()])
593            .args([
594                "--storage-path".to_string(),
595                storage_path.to_string_lossy().to_string(),
596            ]);
597        if let Some(chain_id) = chain_id {
598            command.arg(chain_id.to_string());
599        }
600        let child = command.spawn_into()?;
601        let client = reqwest_client();
602        for i in 0..10 {
603            linera_base::time::timer::sleep(Duration::from_secs(i)).await;
604            let request = client
605                .get(format!("http://localhost:{}/", port))
606                .send()
607                .await;
608            if request.is_ok() {
609                tracing::info!("Faucet has started");
610                return Ok(FaucetService::new(port, child, temp_dir));
611            } else {
612                tracing::debug!("Waiting for faucet to start");
613            }
614        }
615        bail!("Failed to start faucet");
616    }
617
618    /// Runs `linera local-balance`.
619    pub async fn local_balance(&self, account: Account) -> Result<Amount> {
620        let stdout = self
621            .command()
622            .await?
623            .arg("local-balance")
624            .arg(account.to_string())
625            .spawn_and_wait_for_stdout()
626            .await?;
627        let amount = stdout
628            .trim()
629            .parse()
630            .context("error while parsing the result of `linera local-balance`")?;
631        Ok(amount)
632    }
633
634    /// Runs `linera query-balance`.
635    pub async fn query_balance(&self, account: Account) -> Result<Amount> {
636        let stdout = self
637            .command()
638            .await?
639            .arg("query-balance")
640            .arg(account.to_string())
641            .spawn_and_wait_for_stdout()
642            .await?;
643        let amount = stdout
644            .trim()
645            .parse()
646            .context("error while parsing the result of `linera query-balance`")?;
647        Ok(amount)
648    }
649
650    /// Runs `linera sync`.
651    pub async fn sync(&self, chain_id: ChainId) -> Result<()> {
652        self.command()
653            .await?
654            .arg("sync")
655            .arg(chain_id.to_string())
656            .spawn_and_wait_for_stdout()
657            .await?;
658        Ok(())
659    }
660
661    /// Runs `linera process-inbox`.
662    pub async fn process_inbox(&self, chain_id: ChainId) -> Result<()> {
663        self.command()
664            .await?
665            .arg("process-inbox")
666            .arg(chain_id.to_string())
667            .spawn_and_wait_for_stdout()
668            .await?;
669        Ok(())
670    }
671
672    /// Runs `linera transfer`.
673    pub async fn transfer(&self, amount: Amount, from: ChainId, to: ChainId) -> Result<()> {
674        self.command()
675            .await?
676            .arg("transfer")
677            .arg(amount.to_string())
678            .args(["--from", &from.to_string()])
679            .args(["--to", &to.to_string()])
680            .spawn_and_wait_for_stdout()
681            .await?;
682        Ok(())
683    }
684
685    /// Runs `linera transfer` with no logging.
686    pub async fn transfer_with_silent_logs(
687        &self,
688        amount: Amount,
689        from: ChainId,
690        to: ChainId,
691    ) -> Result<()> {
692        self.command()
693            .await?
694            .env("RUST_LOG", "off")
695            .arg("transfer")
696            .arg(amount.to_string())
697            .args(["--from", &from.to_string()])
698            .args(["--to", &to.to_string()])
699            .spawn_and_wait_for_stdout()
700            .await?;
701        Ok(())
702    }
703
704    /// Runs `linera transfer` with owner accounts.
705    pub async fn transfer_with_accounts(
706        &self,
707        amount: Amount,
708        from: Account,
709        to: Account,
710    ) -> Result<()> {
711        self.command()
712            .await?
713            .arg("transfer")
714            .arg(amount.to_string())
715            .args(["--from", &from.to_string()])
716            .args(["--to", &to.to_string()])
717            .spawn_and_wait_for_stdout()
718            .await?;
719        Ok(())
720    }
721
722    fn benchmark_command_internal(command: &mut Command, args: BenchmarkCommand) -> Result<()> {
723        let mut formatted_args = to_args(&args)?;
724        let subcommand = formatted_args.remove(0);
725        // The subcommand is followed by the flattened options, which are preceded by "options".
726        // So remove that as well.
727        formatted_args.remove(0);
728        let options = formatted_args
729            .chunks_exact(2)
730            .flat_map(|pair| {
731                let option = format!("--{}", pair[0]);
732                match pair[1].as_str() {
733                    "true" => vec![option],
734                    "false" => vec![],
735                    _ => vec![option, pair[1].clone()],
736                }
737            })
738            .collect::<Vec<_>>();
739        command
740            .args([
741                "--max-pending-message-bundles",
742                &args.transactions_per_block().to_string(),
743            ])
744            .arg("benchmark")
745            .arg(subcommand)
746            .args(options);
747        Ok(())
748    }
749
750    async fn benchmark_command_with_envs(
751        &self,
752        args: BenchmarkCommand,
753        envs: &[(&str, &str)],
754    ) -> Result<Command> {
755        let mut command = self
756            .command_with_envs_and_arguments(envs, self.required_command_arguments())
757            .await?;
758        Self::benchmark_command_internal(&mut command, args)?;
759        Ok(command)
760    }
761
762    async fn benchmark_command(&self, args: BenchmarkCommand) -> Result<Command> {
763        let mut command = self
764            .command_with_arguments(self.required_command_arguments())
765            .await?;
766        Self::benchmark_command_internal(&mut command, args)?;
767        Ok(command)
768    }
769
770    /// Runs `linera benchmark`.
771    pub async fn benchmark(&self, args: BenchmarkCommand) -> Result<()> {
772        let mut command = self.benchmark_command(args).await?;
773        command.spawn_and_wait_for_stdout().await?;
774        Ok(())
775    }
776
777    /// Runs `linera benchmark`, but detached: don't wait for the command to finish, just spawn it
778    /// and return the child process, and the handles to the stdout and stderr.
779    pub async fn benchmark_detached(
780        &self,
781        args: BenchmarkCommand,
782        tx: oneshot::Sender<()>,
783    ) -> Result<(Child, JoinHandle<()>, JoinHandle<()>)> {
784        let mut child = self
785            .benchmark_command_with_envs(args, &[("RUST_LOG", "linera=info")])
786            .await?
787            .kill_on_drop(true)
788            .stdin(Stdio::piped())
789            .stdout(Stdio::piped())
790            .stderr(Stdio::piped())
791            .spawn()?;
792
793        let pid = child.id().expect("failed to get pid");
794        let stdout = child.stdout.take().expect("stdout not open");
795        let stdout_handle = tokio::spawn(async move {
796            let mut lines = BufReader::new(stdout).lines();
797            while let Ok(Some(line)) = lines.next_line().await {
798                println!("benchmark{{pid={pid}}} {line}");
799            }
800        });
801
802        let stderr = child.stderr.take().expect("stderr not open");
803        let stderr_handle = tokio::spawn(async move {
804            let mut lines = BufReader::new(stderr).lines();
805            let mut tx = Some(tx);
806            while let Ok(Some(line)) = lines.next_line().await {
807                if line.contains("Ready to start benchmark") {
808                    tx.take()
809                        .expect("Should only send signal once")
810                        .send(())
811                        .expect("failed to send ready signal to main thread");
812                } else {
813                    println!("benchmark{{pid={pid}}} {line}");
814                }
815            }
816        });
817        Ok((child, stdout_handle, stderr_handle))
818    }
819
820    async fn open_chain_internal(
821        &self,
822        from: ChainId,
823        owner: Option<AccountOwner>,
824        initial_balance: Amount,
825        super_owner: bool,
826    ) -> Result<(ChainId, AccountOwner)> {
827        let mut command = self.command().await?;
828        command
829            .arg("open-chain")
830            .args(["--from", &from.to_string()])
831            .args(["--initial-balance", &initial_balance.to_string()]);
832
833        if let Some(owner) = owner {
834            command.args(["--owner", &owner.to_string()]);
835        }
836
837        if super_owner {
838            command.arg("--super-owner");
839        }
840
841        let stdout = command.spawn_and_wait_for_stdout().await?;
842        let mut split = stdout.split('\n');
843        let chain_id = ChainId::from_str(split.next().context("no chain ID in output")?)?;
844        let new_owner = AccountOwner::from_str(split.next().context("no owner in output")?)?;
845        if let Some(owner) = owner {
846            assert_eq!(owner, new_owner);
847        }
848        Ok((chain_id, new_owner))
849    }
850
851    /// Runs `linera open-chain --super-owner`.
852    pub async fn open_chain_super_owner(
853        &self,
854        from: ChainId,
855        owner: Option<AccountOwner>,
856        initial_balance: Amount,
857    ) -> Result<(ChainId, AccountOwner)> {
858        self.open_chain_internal(from, owner, initial_balance, true)
859            .await
860    }
861
862    /// Runs `linera open-chain`.
863    pub async fn open_chain(
864        &self,
865        from: ChainId,
866        owner: Option<AccountOwner>,
867        initial_balance: Amount,
868    ) -> Result<(ChainId, AccountOwner)> {
869        self.open_chain_internal(from, owner, initial_balance, false)
870            .await
871    }
872
873    /// Runs `linera open-chain` then `linera assign`.
874    pub async fn open_and_assign(
875        &self,
876        client: &ClientWrapper,
877        initial_balance: Amount,
878    ) -> Result<ChainId> {
879        let our_chain = self
880            .load_wallet()?
881            .default_chain()
882            .context("no default chain found")?;
883        let owner = client.keygen().await?;
884        let (new_chain, _) = self
885            .open_chain(our_chain, Some(owner), initial_balance)
886            .await?;
887        client.assign(owner, new_chain).await?;
888        Ok(new_chain)
889    }
890
891    pub async fn open_multi_owner_chain(
892        &self,
893        from: ChainId,
894        owners: Vec<AccountOwner>,
895        weights: Vec<u64>,
896        multi_leader_rounds: u32,
897        balance: Amount,
898        base_timeout_ms: u64,
899    ) -> Result<ChainId> {
900        let mut command = self.command().await?;
901        command
902            .arg("open-multi-owner-chain")
903            .args(["--from", &from.to_string()])
904            .arg("--owners")
905            .args(owners.iter().map(AccountOwner::to_string))
906            .args(["--base-timeout-ms", &base_timeout_ms.to_string()]);
907        if !weights.is_empty() {
908            command
909                .arg("--owner-weights")
910                .args(weights.iter().map(u64::to_string));
911        };
912        command
913            .args(["--multi-leader-rounds", &multi_leader_rounds.to_string()])
914            .args(["--initial-balance", &balance.to_string()]);
915
916        let stdout = command.spawn_and_wait_for_stdout().await?;
917        let mut split = stdout.split('\n');
918        let chain_id = ChainId::from_str(split.next().context("no chain ID in output")?)?;
919
920        Ok(chain_id)
921    }
922
923    pub async fn change_ownership(
924        &self,
925        chain_id: ChainId,
926        super_owners: Vec<AccountOwner>,
927        owners: Vec<AccountOwner>,
928    ) -> Result<()> {
929        let mut command = self.command().await?;
930        command
931            .arg("change-ownership")
932            .args(["--chain-id", &chain_id.to_string()]);
933        if !super_owners.is_empty() {
934            command
935                .arg("--super-owners")
936                .args(super_owners.iter().map(AccountOwner::to_string));
937        }
938        if !owners.is_empty() {
939            command
940                .arg("--owners")
941                .args(owners.iter().map(AccountOwner::to_string));
942        }
943        command.spawn_and_wait_for_stdout().await?;
944        Ok(())
945    }
946
947    /// Runs `linera wallet follow-chain CHAIN_ID`.
948    pub async fn follow_chain(&self, chain_id: ChainId, sync: bool) -> Result<()> {
949        let mut command = self.command().await?;
950        command
951            .args(["wallet", "follow-chain"])
952            .arg(chain_id.to_string());
953        if sync {
954            command.arg("--sync");
955        }
956        command.spawn_and_wait_for_stdout().await?;
957        Ok(())
958    }
959
960    /// Runs `linera wallet forget-chain CHAIN_ID`.
961    pub async fn forget_chain(&self, chain_id: ChainId) -> Result<()> {
962        let mut command = self.command().await?;
963        command
964            .args(["wallet", "forget-chain"])
965            .arg(chain_id.to_string());
966        command.spawn_and_wait_for_stdout().await?;
967        Ok(())
968    }
969
970    /// Runs `linera wallet set-default CHAIN_ID`.
971    pub async fn set_default_chain(&self, chain_id: ChainId) -> Result<()> {
972        let mut command = self.command().await?;
973        command
974            .args(["wallet", "set-default"])
975            .arg(chain_id.to_string());
976        command.spawn_and_wait_for_stdout().await?;
977        Ok(())
978    }
979
980    pub async fn retry_pending_block(
981        &self,
982        chain_id: Option<ChainId>,
983    ) -> Result<Option<CryptoHash>> {
984        let mut command = self.command().await?;
985        command.arg("retry-pending-block");
986        if let Some(chain_id) = chain_id {
987            command.arg(chain_id.to_string());
988        }
989        let stdout = command.spawn_and_wait_for_stdout().await?;
990        let stdout = stdout.trim();
991        if stdout.is_empty() {
992            Ok(None)
993        } else {
994            Ok(Some(CryptoHash::from_str(stdout)?))
995        }
996    }
997
998    /// Runs `linera publish-data-blob`.
999    pub async fn publish_data_blob(
1000        &self,
1001        path: &Path,
1002        chain_id: Option<ChainId>,
1003    ) -> Result<CryptoHash> {
1004        let mut command = self.command().await?;
1005        command.arg("publish-data-blob").arg(path);
1006        if let Some(chain_id) = chain_id {
1007            command.arg(chain_id.to_string());
1008        }
1009        let stdout = command.spawn_and_wait_for_stdout().await?;
1010        let stdout = stdout.trim();
1011        Ok(CryptoHash::from_str(stdout)?)
1012    }
1013
1014    /// Runs `linera read-data-blob`.
1015    pub async fn read_data_blob(&self, hash: CryptoHash, chain_id: Option<ChainId>) -> Result<()> {
1016        let mut command = self.command().await?;
1017        command.arg("read-data-blob").arg(hash.to_string());
1018        if let Some(chain_id) = chain_id {
1019            command.arg(chain_id.to_string());
1020        }
1021        command.spawn_and_wait_for_stdout().await?;
1022        Ok(())
1023    }
1024
1025    pub fn load_wallet(&self) -> Result<Wallet> {
1026        Ok(Wallet::read(&self.wallet_path())?)
1027    }
1028
1029    pub fn load_keystore(&self) -> Result<InMemorySigner> {
1030        util::read_json(self.keystore_path())
1031    }
1032
1033    pub fn wallet_path(&self) -> PathBuf {
1034        self.path_provider.path().join(&self.wallet)
1035    }
1036
1037    pub fn keystore_path(&self) -> PathBuf {
1038        self.path_provider.path().join(&self.keystore)
1039    }
1040
1041    pub fn storage_path(&self) -> &str {
1042        &self.storage
1043    }
1044
1045    pub fn get_owner(&self) -> Option<AccountOwner> {
1046        let wallet = self.load_wallet().ok()?;
1047        wallet
1048            .get(wallet.default_chain()?)
1049            .expect("default chain must be in wallet")
1050            .owner
1051    }
1052
1053    pub fn is_chain_present_in_wallet(&self, chain: ChainId) -> bool {
1054        self.load_wallet()
1055            .ok()
1056            .is_some_and(|wallet| wallet.get(chain).is_some())
1057    }
1058
1059    pub async fn set_validator(
1060        &self,
1061        validator_key: &(String, String),
1062        port: usize,
1063        votes: usize,
1064    ) -> Result<()> {
1065        let address = format!("{}:127.0.0.1:{}", self.network.short(), port);
1066        self.command()
1067            .await?
1068            .arg("validator")
1069            .arg("add")
1070            .args(["--public-key", &validator_key.0])
1071            .args(["--account-key", &validator_key.1])
1072            .args(["--address", &address])
1073            .args(["--votes", &votes.to_string()])
1074            .spawn_and_wait_for_stdout()
1075            .await?;
1076        Ok(())
1077    }
1078
1079    pub async fn remove_validator(&self, validator_key: &str) -> Result<()> {
1080        self.command()
1081            .await?
1082            .arg("validator")
1083            .arg("remove")
1084            .args(["--public-key", validator_key])
1085            .spawn_and_wait_for_stdout()
1086            .await?;
1087        Ok(())
1088    }
1089
1090    pub async fn change_validators(
1091        &self,
1092        add_validators: &[(String, String, usize, usize)], // (public_key, account_key, port, votes)
1093        modify_validators: &[(String, String, usize, usize)], // (public_key, account_key, port, votes)
1094        remove_validators: &[String],
1095    ) -> Result<()> {
1096        use std::str::FromStr;
1097
1098        use linera_base::crypto::{AccountPublicKey, ValidatorPublicKey};
1099
1100        // Build a map that will be serialized to JSON
1101        // Use the exact types that deserialization expects
1102        let mut changes = std::collections::HashMap::new();
1103
1104        // Add/modify validators
1105        for (public_key_str, account_key_str, port, votes) in
1106            add_validators.iter().chain(modify_validators.iter())
1107        {
1108            let public_key = ValidatorPublicKey::from_str(public_key_str)
1109                .with_context(|| format!("Invalid validator public key: {}", public_key_str))?;
1110
1111            let account_key = AccountPublicKey::from_str(account_key_str)
1112                .with_context(|| format!("Invalid account public key: {}", account_key_str))?;
1113
1114            let address = format!("{}:127.0.0.1:{}", self.network.short(), port)
1115                .parse()
1116                .unwrap();
1117
1118            // Create ValidatorChange struct
1119            let change = crate::cli::validator::Change {
1120                account_key,
1121                address,
1122                votes: crate::cli::validator::Votes(
1123                    std::num::NonZero::new(*votes as u64).context("Votes must be non-zero")?,
1124                ),
1125            };
1126
1127            changes.insert(public_key, Some(change));
1128        }
1129
1130        // Remove validators (set to None)
1131        for validator_key_str in remove_validators {
1132            let public_key = ValidatorPublicKey::from_str(validator_key_str)
1133                .with_context(|| format!("Invalid validator public key: {}", validator_key_str))?;
1134            changes.insert(public_key, None);
1135        }
1136
1137        // Create temporary file with JSON
1138        let temp_file = tempfile::NamedTempFile::new()
1139            .context("Failed to create temporary file for validator changes")?;
1140        serde_json::to_writer(&temp_file, &changes)
1141            .context("Failed to write validator changes to file")?;
1142        let temp_path = temp_file.path();
1143
1144        self.command()
1145            .await?
1146            .arg("validator")
1147            .arg("update")
1148            .arg(temp_path)
1149            .arg("--yes") // Skip confirmation prompt
1150            .spawn_and_wait_for_stdout()
1151            .await?;
1152
1153        Ok(())
1154    }
1155
1156    pub async fn revoke_epochs(&self, epoch: Epoch) -> Result<()> {
1157        self.command()
1158            .await?
1159            .arg("revoke-epochs")
1160            .arg(epoch.to_string())
1161            .spawn_and_wait_for_stdout()
1162            .await?;
1163        Ok(())
1164    }
1165
1166    /// Runs `linera keygen`.
1167    pub async fn keygen(&self) -> Result<AccountOwner> {
1168        let stdout = self
1169            .command()
1170            .await?
1171            .arg("keygen")
1172            .spawn_and_wait_for_stdout()
1173            .await?;
1174        AccountOwner::from_str(stdout.as_str().trim())
1175    }
1176
1177    /// Returns the default chain.
1178    pub fn default_chain(&self) -> Option<ChainId> {
1179        self.load_wallet().ok()?.default_chain()
1180    }
1181
1182    /// Runs `linera assign`.
1183    pub async fn assign(&self, owner: AccountOwner, chain_id: ChainId) -> Result<()> {
1184        let _stdout = self
1185            .command()
1186            .await?
1187            .arg("assign")
1188            .args(["--owner", &owner.to_string()])
1189            .args(["--chain-id", &chain_id.to_string()])
1190            .spawn_and_wait_for_stdout()
1191            .await?;
1192        Ok(())
1193    }
1194
1195    /// Runs `linera set-preferred-owner` for `chain_id`.
1196    pub async fn set_preferred_owner(
1197        &self,
1198        chain_id: ChainId,
1199        owner: Option<AccountOwner>,
1200    ) -> Result<()> {
1201        let mut owner_arg = vec!["--owner".to_string()];
1202        if let Some(owner) = owner {
1203            owner_arg.push(owner.to_string());
1204        };
1205        self.command()
1206            .await?
1207            .arg("set-preferred-owner")
1208            .args(["--chain-id", &chain_id.to_string()])
1209            .args(owner_arg)
1210            .spawn_and_wait_for_stdout()
1211            .await?;
1212        Ok(())
1213    }
1214
1215    pub async fn build_application(
1216        &self,
1217        path: &Path,
1218        name: &str,
1219        is_workspace: bool,
1220    ) -> Result<(PathBuf, PathBuf)> {
1221        Command::new("cargo")
1222            .current_dir(self.path_provider.path())
1223            .arg("build")
1224            .arg("--release")
1225            .args(["--target", "wasm32-unknown-unknown"])
1226            .arg("--manifest-path")
1227            .arg(path.join("Cargo.toml"))
1228            .spawn_and_wait_for_stdout()
1229            .await?;
1230
1231        let release_dir = match is_workspace {
1232            true => path.join("../target/wasm32-unknown-unknown/release"),
1233            false => path.join("target/wasm32-unknown-unknown/release"),
1234        };
1235
1236        let contract = release_dir.join(format!("{}_contract.wasm", name.replace('-', "_")));
1237        let service = release_dir.join(format!("{}_service.wasm", name.replace('-', "_")));
1238
1239        let contract_size = fs_err::tokio::metadata(&contract).await?.len();
1240        let service_size = fs_err::tokio::metadata(&service).await?.len();
1241        tracing::info!("Done building application {name}: contract_size={contract_size}, service_size={service_size}");
1242
1243        Ok((contract, service))
1244    }
1245}
1246
1247impl Drop for ClientWrapper {
1248    fn drop(&mut self) {
1249        use std::process::Command as SyncCommand;
1250
1251        if self.on_drop != OnClientDrop::CloseChains {
1252            return;
1253        }
1254
1255        let Ok(binary_path) = self.binary_path.lock() else {
1256            tracing::error!(
1257                "Failed to close chains because a thread panicked with a lock to `binary_path`"
1258            );
1259            return;
1260        };
1261
1262        let Some(binary_path) = binary_path.as_ref() else {
1263            tracing::warn!(
1264                "Assuming no chains need to be closed, because the command binary was never \
1265                resolved and therefore presumably never called"
1266            );
1267            return;
1268        };
1269
1270        let working_directory = self.path_provider.path();
1271        let mut wallet_show_command = SyncCommand::new(binary_path);
1272
1273        for argument in self.command_arguments() {
1274            wallet_show_command.arg(&*argument);
1275        }
1276
1277        let Ok(wallet_show_output) = wallet_show_command
1278            .current_dir(working_directory)
1279            .args(["wallet", "show", "--short", "--owned"])
1280            .output()
1281        else {
1282            tracing::warn!("Failed to execute `wallet show --short` to list chains to close");
1283            return;
1284        };
1285
1286        if !wallet_show_output.status.success() {
1287            tracing::warn!("Failed to list chains in the wallet to close them");
1288            return;
1289        }
1290
1291        let Ok(chain_list_string) = String::from_utf8(wallet_show_output.stdout) else {
1292            tracing::warn!(
1293                "Failed to close chains because `linera wallet show --short` \
1294                returned a non-UTF-8 output"
1295            );
1296            return;
1297        };
1298
1299        let chain_ids = chain_list_string
1300            .split('\n')
1301            .map(|line| line.trim())
1302            .filter(|line| !line.is_empty());
1303
1304        for chain_id in chain_ids {
1305            let mut close_chain_command = SyncCommand::new(binary_path);
1306
1307            for argument in self.command_arguments() {
1308                close_chain_command.arg(&*argument);
1309            }
1310
1311            close_chain_command.current_dir(working_directory);
1312
1313            match close_chain_command.args(["close-chain", chain_id]).status() {
1314                Ok(status) if status.success() => (),
1315                Ok(failure) => tracing::warn!("Failed to close chain {chain_id}: {failure}"),
1316                Err(error) => tracing::warn!("Failed to close chain {chain_id}: {error}"),
1317            }
1318        }
1319    }
1320}
1321
1322#[cfg(with_testing)]
1323impl ClientWrapper {
1324    pub async fn build_example(&self, name: &str) -> Result<(PathBuf, PathBuf)> {
1325        self.build_application(Self::example_path(name)?.as_path(), name, true)
1326            .await
1327    }
1328
1329    pub fn example_path(name: &str) -> Result<PathBuf> {
1330        Ok(env::current_dir()?.join("../examples/").join(name))
1331    }
1332}
1333
1334fn truncate_query_output(input: &str) -> String {
1335    let max_len = 1000;
1336    if input.len() < max_len {
1337        input.to_string()
1338    } else {
1339        format!("{} ...", input.get(..max_len).unwrap())
1340    }
1341}
1342
1343fn truncate_query_output_serialize<T: Serialize>(query: T) -> String {
1344    let query = serde_json::to_string(&query).expect("Failed to serialize the failed query");
1345    let max_len = 200;
1346    if query.len() < max_len {
1347        query
1348    } else {
1349        format!("{} ...", query.get(..max_len).unwrap())
1350    }
1351}
1352
1353/// A running node service.
1354pub struct NodeService {
1355    port: u16,
1356    child: Child,
1357}
1358
1359impl NodeService {
1360    fn new(port: u16, child: Child) -> Self {
1361        Self { port, child }
1362    }
1363
1364    pub async fn terminate(mut self) -> Result<()> {
1365        self.child.kill().await.context("terminating node service")
1366    }
1367
1368    pub fn port(&self) -> u16 {
1369        self.port
1370    }
1371
1372    pub fn ensure_is_running(&mut self) -> Result<()> {
1373        self.child.ensure_is_running()
1374    }
1375
1376    pub async fn process_inbox(&self, chain_id: &ChainId) -> Result<Vec<CryptoHash>> {
1377        let query = format!("mutation {{ processInbox(chainId: \"{chain_id}\") }}");
1378        let mut data = self.query_node(query).await?;
1379        Ok(serde_json::from_value(data["processInbox"].take())?)
1380    }
1381
1382    pub async fn sync(&self, chain_id: &ChainId) -> Result<u64> {
1383        let query = format!("mutation {{ sync(chainId: \"{chain_id}\") }}");
1384        let mut data = self.query_node(query).await?;
1385        Ok(serde_json::from_value(data["sync"].take())?)
1386    }
1387
1388    pub async fn transfer(
1389        &self,
1390        chain_id: ChainId,
1391        owner: AccountOwner,
1392        recipient: Account,
1393        amount: Amount,
1394    ) -> Result<CryptoHash> {
1395        let json_owner = owner.to_value();
1396        let json_recipient = recipient.to_value();
1397        let query = format!(
1398            "mutation {{ transfer(\
1399                 chainId: \"{chain_id}\", \
1400                 owner: {json_owner}, \
1401                 recipient: {json_recipient}, \
1402                 amount: \"{amount}\") \
1403             }}"
1404        );
1405        let data = self.query_node(query).await?;
1406        serde_json::from_value(data["transfer"].clone())
1407            .context("missing transfer field in response")
1408    }
1409
1410    pub async fn balance(&self, account: &Account) -> Result<Amount> {
1411        let chain = account.chain_id;
1412        let owner = account.owner;
1413        if matches!(owner, AccountOwner::CHAIN) {
1414            let query = format!(
1415                "query {{ chain(chainId:\"{chain}\") {{
1416                    executionState {{ system {{ balance }} }}
1417                }} }}"
1418            );
1419            let response = self.query_node(query).await?;
1420            let balance = &response["chain"]["executionState"]["system"]["balance"]
1421                .as_str()
1422                .unwrap();
1423            return Ok(Amount::from_str(balance)?);
1424        }
1425        let query = format!(
1426            "query {{ chain(chainId:\"{chain}\") {{
1427                executionState {{ system {{ balances {{
1428                    entry(key:\"{owner}\") {{ value }}
1429                }} }} }}
1430            }} }}"
1431        );
1432        let response = self.query_node(query).await?;
1433        let balances = &response["chain"]["executionState"]["system"]["balances"];
1434        let balance = balances["entry"]["value"].as_str();
1435        match balance {
1436            None => Ok(Amount::ZERO),
1437            Some(amount) => Ok(Amount::from_str(amount)?),
1438        }
1439    }
1440
1441    pub fn make_application<A: ContractAbi>(
1442        &self,
1443        chain_id: &ChainId,
1444        application_id: &ApplicationId<A>,
1445    ) -> Result<ApplicationWrapper<A>> {
1446        let application_id = application_id.forget_abi().to_string();
1447        let link = format!(
1448            "http://localhost:{}/chains/{chain_id}/applications/{application_id}",
1449            self.port
1450        );
1451        Ok(ApplicationWrapper::from(link))
1452    }
1453
1454    pub async fn publish_data_blob(
1455        &self,
1456        chain_id: &ChainId,
1457        bytes: Vec<u8>,
1458    ) -> Result<CryptoHash> {
1459        let query = format!(
1460            "mutation {{ publishDataBlob(chainId: {}, bytes: {}) }}",
1461            chain_id.to_value(),
1462            bytes.to_value(),
1463        );
1464        let data = self.query_node(query).await?;
1465        serde_json::from_value(data["publishDataBlob"].clone())
1466            .context("missing publishDataBlob field in response")
1467    }
1468
1469    pub async fn publish_module<Abi, Parameters, InstantiationArgument>(
1470        &self,
1471        chain_id: &ChainId,
1472        contract: PathBuf,
1473        service: PathBuf,
1474        vm_runtime: VmRuntime,
1475    ) -> Result<ModuleId<Abi, Parameters, InstantiationArgument>> {
1476        let contract_code = Bytecode::load_from_file(&contract)?;
1477        let service_code = Bytecode::load_from_file(&service)?;
1478        let query = format!(
1479            "mutation {{ publishModule(chainId: {}, contract: {}, service: {}, vmRuntime: {}) }}",
1480            chain_id.to_value(),
1481            contract_code.to_value(),
1482            service_code.to_value(),
1483            vm_runtime.to_value(),
1484        );
1485        let data = self.query_node(query).await?;
1486        let module_str = data["publishModule"]
1487            .as_str()
1488            .context("module ID not found")?;
1489        let module_id: ModuleId = module_str.parse().context("could not parse module ID")?;
1490        Ok(module_id.with_abi())
1491    }
1492
1493    pub async fn query_committees(&self, chain_id: &ChainId) -> Result<BTreeMap<Epoch, Committee>> {
1494        let query = format!(
1495            "query {{ chain(chainId:\"{chain_id}\") {{
1496                executionState {{ system {{ committees }} }}
1497            }} }}"
1498        );
1499        let mut response = self.query_node(query).await?;
1500        let committees = response["chain"]["executionState"]["system"]["committees"].take();
1501        Ok(serde_json::from_value(committees)?)
1502    }
1503
1504    pub async fn events_from_index(
1505        &self,
1506        chain_id: &ChainId,
1507        stream_id: &StreamId,
1508        start_index: u32,
1509    ) -> Result<Vec<IndexAndEvent>> {
1510        let query = format!(
1511            "query {{
1512               eventsFromIndex(chainId: \"{chain_id}\", streamId: {}, startIndex: {start_index})
1513               {{ index event }}
1514             }}",
1515            stream_id.to_value()
1516        );
1517        let mut response = self.query_node(query).await?;
1518        let response = response["eventsFromIndex"].take();
1519        Ok(serde_json::from_value(response)?)
1520    }
1521
1522    pub async fn query_node(&self, query: impl AsRef<str>) -> Result<Value> {
1523        let n_try = 5;
1524        let query = query.as_ref();
1525        for i in 0..n_try {
1526            linera_base::time::timer::sleep(Duration::from_secs(i)).await;
1527            let url = format!("http://localhost:{}/", self.port);
1528            let client = reqwest_client();
1529            let result = client
1530                .post(url)
1531                .json(&json!({ "query": query }))
1532                .send()
1533                .await;
1534            if matches!(result, Err(ref error) if error.is_timeout()) {
1535                tracing::warn!(
1536                    "Timeout when sending query {} to the node service",
1537                    truncate_query_output(query)
1538                );
1539                continue;
1540            }
1541            let response = result.with_context(|| {
1542                format!(
1543                    "query_node: failed to post query={}",
1544                    truncate_query_output(query)
1545                )
1546            })?;
1547            ensure!(
1548                response.status().is_success(),
1549                "Query \"{}\" failed: {}",
1550                truncate_query_output(query),
1551                response
1552                    .text()
1553                    .await
1554                    .unwrap_or_else(|error| format!("Could not get response text: {error}"))
1555            );
1556            let value: Value = response.json().await.context("invalid JSON")?;
1557            if let Some(errors) = value.get("errors") {
1558                tracing::warn!(
1559                    "Query \"{}\" failed: {}",
1560                    truncate_query_output(query),
1561                    errors
1562                );
1563            } else {
1564                return Ok(value["data"].clone());
1565            }
1566        }
1567        bail!(
1568            "Query \"{}\" failed after {} retries.",
1569            truncate_query_output(query),
1570            n_try
1571        );
1572    }
1573
1574    pub async fn create_application<
1575        Abi: ContractAbi,
1576        Parameters: Serialize,
1577        InstantiationArgument: Serialize,
1578    >(
1579        &self,
1580        chain_id: &ChainId,
1581        module_id: &ModuleId<Abi, Parameters, InstantiationArgument>,
1582        parameters: &Parameters,
1583        argument: &InstantiationArgument,
1584        required_application_ids: &[ApplicationId],
1585    ) -> Result<ApplicationId<Abi>> {
1586        let module_id = module_id.forget_abi();
1587        let json_required_applications_ids = required_application_ids
1588            .iter()
1589            .map(ApplicationId::to_string)
1590            .collect::<Vec<_>>()
1591            .to_value();
1592        // Convert to `serde_json::Value` then `async_graphql::Value` via the trait `InputType`.
1593        let new_parameters = serde_json::to_value(parameters)
1594            .context("could not create parameters JSON")?
1595            .to_value();
1596        let new_argument = serde_json::to_value(argument)
1597            .context("could not create argument JSON")?
1598            .to_value();
1599        let query = format!(
1600            "mutation {{ createApplication(\
1601                 chainId: \"{chain_id}\",
1602                 moduleId: \"{module_id}\", \
1603                 parameters: {new_parameters}, \
1604                 instantiationArgument: {new_argument}, \
1605                 requiredApplicationIds: {json_required_applications_ids}) \
1606             }}"
1607        );
1608        let data = self.query_node(query).await?;
1609        let app_id_str = data["createApplication"]
1610            .as_str()
1611            .context("missing createApplication string in response")?
1612            .trim();
1613        Ok(app_id_str
1614            .parse::<ApplicationId>()
1615            .context("invalid application ID")?
1616            .with_abi())
1617    }
1618
1619    /// Obtains the hash and height of the `chain`'s tip block, as known by this node service.
1620    pub async fn chain_tip(&self, chain: ChainId) -> Result<Option<(CryptoHash, BlockHeight)>> {
1621        let query = format!(
1622            r#"query {{ block(chainId: "{chain}") {{
1623                hash
1624                block {{ header {{ height }} }}
1625            }} }}"#
1626        );
1627
1628        let mut response = self.query_node(&query).await?;
1629
1630        match (
1631            mem::take(&mut response["block"]["hash"]),
1632            mem::take(&mut response["block"]["block"]["header"]["height"]),
1633        ) {
1634            (Value::Null, Value::Null) => Ok(None),
1635            (Value::String(hash), Value::Number(height)) => Ok(Some((
1636                hash.parse()
1637                    .context("Received an invalid hash {hash:?} for chain tip")?,
1638                BlockHeight(height.as_u64().unwrap()),
1639            ))),
1640            invalid_data => bail!("Expected a tip hash string, but got {invalid_data:?} instead"),
1641        }
1642    }
1643
1644    /// Subscribes to the node service and returns a stream of notifications about a chain.
1645    pub async fn notifications(
1646        &self,
1647        chain_id: ChainId,
1648    ) -> Result<Pin<Box<impl Stream<Item = Result<Notification>>>>> {
1649        let query = format!("subscription {{ notifications(chainId: \"{chain_id}\") }}",);
1650        let url = format!("ws://localhost:{}/ws", self.port);
1651        let mut request = url.into_client_request()?;
1652        request.headers_mut().insert(
1653            "Sec-WebSocket-Protocol",
1654            HeaderValue::from_str("graphql-transport-ws")?,
1655        );
1656        let (mut websocket, _) = async_tungstenite::tokio::connect_async(request).await?;
1657        let init_json = json!({
1658          "type": "connection_init",
1659          "payload": {}
1660        });
1661        websocket.send(init_json.to_string().into()).await?;
1662        let text = websocket
1663            .next()
1664            .await
1665            .context("Failed to establish connection")??
1666            .into_text()?;
1667        ensure!(
1668            text == "{\"type\":\"connection_ack\"}",
1669            "Unexpected response: {text}"
1670        );
1671        let query_json = json!({
1672          "id": "1",
1673          "type": "start",
1674          "payload": {
1675            "query": query,
1676            "variables": {},
1677            "operationName": null
1678          }
1679        });
1680        websocket.send(query_json.to_string().into()).await?;
1681        Ok(Box::pin(websocket.map_err(anyhow::Error::from).and_then(
1682            |message| async {
1683                let text = message.into_text()?;
1684                let value: Value = serde_json::from_str(&text).context("invalid JSON")?;
1685                if let Some(errors) = value["payload"].get("errors") {
1686                    bail!("Notification subscription failed: {errors:?}");
1687                }
1688                serde_json::from_value(value["payload"]["data"]["notifications"].clone())
1689                    .context("Failed to deserialize notification")
1690            },
1691        )))
1692    }
1693}
1694
1695/// A running faucet service.
1696pub struct FaucetService {
1697    port: u16,
1698    child: Child,
1699    _temp_dir: tempfile::TempDir,
1700}
1701
1702impl FaucetService {
1703    fn new(port: u16, child: Child, temp_dir: tempfile::TempDir) -> Self {
1704        Self {
1705            port,
1706            child,
1707            _temp_dir: temp_dir,
1708        }
1709    }
1710
1711    pub async fn terminate(mut self) -> Result<()> {
1712        self.child
1713            .kill()
1714            .await
1715            .context("terminating faucet service")
1716    }
1717
1718    pub fn ensure_is_running(&mut self) -> Result<()> {
1719        self.child.ensure_is_running()
1720    }
1721
1722    pub fn instance(&self) -> Faucet {
1723        Faucet::new(format!("http://localhost:{}/", self.port))
1724    }
1725}
1726
1727/// A running `Application` to be queried in GraphQL.
1728pub struct ApplicationWrapper<A> {
1729    uri: String,
1730    _phantom: PhantomData<A>,
1731}
1732
1733impl<A> ApplicationWrapper<A> {
1734    pub async fn run_graphql_query(&self, query: impl AsRef<str>) -> Result<Value> {
1735        let query = query.as_ref();
1736        let value = self.run_json_query(json!({ "query": query })).await?;
1737        Ok(value["data"].clone())
1738    }
1739
1740    pub async fn run_json_query<T: Serialize>(&self, query: T) -> Result<Value> {
1741        const MAX_RETRIES: usize = 5;
1742
1743        for i in 0.. {
1744            let client = reqwest_client();
1745            let result = client.post(&self.uri).json(&query).send().await;
1746            let response = match result {
1747                Ok(response) => response,
1748                Err(error) if i < MAX_RETRIES => {
1749                    tracing::warn!(
1750                        "Failed to post query \"{}\": {error}; retrying",
1751                        truncate_query_output_serialize(&query),
1752                    );
1753                    continue;
1754                }
1755                Err(error) => {
1756                    let query = truncate_query_output_serialize(&query);
1757                    return Err(error)
1758                        .with_context(|| format!("run_json_query: failed to post query={query}"));
1759                }
1760            };
1761            ensure!(
1762                response.status().is_success(),
1763                "Query \"{}\" failed: {}",
1764                truncate_query_output_serialize(&query),
1765                response
1766                    .text()
1767                    .await
1768                    .unwrap_or_else(|error| format!("Could not get response text: {error}"))
1769            );
1770            let value: Value = response.json().await.context("invalid JSON")?;
1771            if let Some(errors) = value.get("errors") {
1772                bail!(
1773                    "Query \"{}\" failed: {}",
1774                    truncate_query_output_serialize(&query),
1775                    errors
1776                );
1777            }
1778            return Ok(value);
1779        }
1780        unreachable!()
1781    }
1782
1783    pub async fn query(&self, query: impl AsRef<str>) -> Result<Value> {
1784        let query = query.as_ref();
1785        self.run_graphql_query(&format!("query {{ {query} }}"))
1786            .await
1787    }
1788
1789    pub async fn query_json<T: DeserializeOwned>(&self, query: impl AsRef<str>) -> Result<T> {
1790        let query = query.as_ref().trim();
1791        let name = query
1792            .split_once(|ch: char| !ch.is_alphanumeric())
1793            .map_or(query, |(name, _)| name);
1794        let data = self.query(query).await?;
1795        serde_json::from_value(data[name].clone())
1796            .with_context(|| format!("{name} field missing in response"))
1797    }
1798
1799    pub async fn mutate(&self, mutation: impl AsRef<str>) -> Result<Value> {
1800        let mutation = mutation.as_ref();
1801        self.run_graphql_query(&format!("mutation {{ {mutation} }}"))
1802            .await
1803    }
1804
1805    pub async fn multiple_mutate(&self, mutations: &[String]) -> Result<Value> {
1806        let mut out = String::from("mutation {\n");
1807        for (index, mutation) in mutations.iter().enumerate() {
1808            out = format!("{}  u{}: {}\n", out, index, mutation);
1809        }
1810        out.push_str("}\n");
1811        self.run_graphql_query(&out).await
1812    }
1813}
1814
1815impl<A> From<String> for ApplicationWrapper<A> {
1816    fn from(uri: String) -> ApplicationWrapper<A> {
1817        ApplicationWrapper {
1818            uri,
1819            _phantom: PhantomData,
1820        }
1821    }
1822}
1823
1824/// Returns the timeout for tests that wait for notifications, either read from the env
1825/// variable `LINERA_TEST_NOTIFICATION_TIMEOUT_MS`, or the default value of 10 seconds.
1826#[cfg(with_testing)]
1827fn notification_timeout() -> Duration {
1828    const NOTIFICATION_TIMEOUT_MS_ENV: &str = "LINERA_TEST_NOTIFICATION_TIMEOUT_MS";
1829    const NOTIFICATION_TIMEOUT_MS_DEFAULT: u64 = 10_000;
1830
1831    match env::var(NOTIFICATION_TIMEOUT_MS_ENV) {
1832        Ok(var) => Duration::from_millis(var.parse().unwrap_or_else(|error| {
1833            panic!("{NOTIFICATION_TIMEOUT_MS_ENV} is not a valid number: {error}")
1834        })),
1835        Err(env::VarError::NotPresent) => Duration::from_millis(NOTIFICATION_TIMEOUT_MS_DEFAULT),
1836        Err(env::VarError::NotUnicode(_)) => {
1837            panic!("{NOTIFICATION_TIMEOUT_MS_ENV} must be valid Unicode")
1838        }
1839    }
1840}
1841
1842#[cfg(with_testing)]
1843pub trait NotificationsExt {
1844    /// Waits for a notification for which `f` returns `Some(t)`, and returns `t`.
1845    fn wait_for<T>(
1846        &mut self,
1847        f: impl FnMut(Notification) -> Option<T>,
1848    ) -> impl Future<Output = Result<T>>;
1849
1850    /// Waits for a `NewEvents` notification for the given block height. If no height is specified,
1851    /// any height is accepted.
1852    fn wait_for_events(
1853        &mut self,
1854        expected_height: impl Into<Option<BlockHeight>>,
1855    ) -> impl Future<Output = Result<BTreeSet<StreamId>>> {
1856        let expected_height = expected_height.into();
1857        self.wait_for(move |notification| {
1858            if let Reason::NewEvents {
1859                height,
1860                event_streams,
1861                ..
1862            } = notification.reason
1863            {
1864                if expected_height.is_none_or(|h| h == height) {
1865                    return Some(event_streams);
1866                }
1867            }
1868            None
1869        })
1870    }
1871
1872    /// Waits for a `NewBlock` notification for the given block height. If no height is specified,
1873    /// any height is accepted.
1874    fn wait_for_block(
1875        &mut self,
1876        expected_height: impl Into<Option<BlockHeight>>,
1877    ) -> impl Future<Output = Result<CryptoHash>> {
1878        let expected_height = expected_height.into();
1879        self.wait_for(move |notification| {
1880            if let Reason::NewBlock { height, hash, .. } = notification.reason {
1881                if expected_height.is_none_or(|h| h == height) {
1882                    return Some(hash);
1883                }
1884            }
1885            None
1886        })
1887    }
1888
1889    /// Waits for a `NewIncomingBundle` notification for the given sender chain and sender block
1890    /// height. If no height is specified, any height is accepted.
1891    fn wait_for_bundle(
1892        &mut self,
1893        expected_origin: ChainId,
1894        expected_height: impl Into<Option<BlockHeight>>,
1895    ) -> impl Future<Output = Result<()>> {
1896        let expected_height = expected_height.into();
1897        self.wait_for(move |notification| {
1898            if let Reason::NewIncomingBundle { height, origin } = notification.reason {
1899                if expected_height.is_none_or(|h| h == height) && origin == expected_origin {
1900                    return Some(());
1901                }
1902            }
1903            None
1904        })
1905    }
1906}
1907
1908#[cfg(with_testing)]
1909impl<S: Stream<Item = Result<Notification>>> NotificationsExt for Pin<Box<S>> {
1910    async fn wait_for<T>(&mut self, mut f: impl FnMut(Notification) -> Option<T>) -> Result<T> {
1911        let mut timeout = Box::pin(linera_base::time::timer::sleep(notification_timeout())).fuse();
1912        loop {
1913            let notification = futures::select! {
1914                () = timeout => bail!("Timeout waiting for notification"),
1915                notification = self.next().fuse() => notification.context("Stream closed")??,
1916            };
1917            if let Some(t) = f(notification) {
1918                return Ok(t);
1919            }
1920        }
1921    }
1922}