iota_cluster_test/
cluster.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::{net::SocketAddr, path::Path};
6
7use async_trait::async_trait;
8use iota_config::{
9    Config, IOTA_GENESIS_FILENAME, IOTA_KEYSTORE_FILENAME, IOTA_NETWORK_CONFIG, PersistedConfig,
10    genesis::Genesis,
11};
12use iota_genesis_builder::SnapshotSource;
13use iota_graphql_rpc::{
14    config::ConnectionConfig, test_infra::cluster::start_graphql_server_with_fn_rpc,
15};
16use iota_indexer::test_utils::{IndexerTypeConfig, start_test_indexer};
17use iota_keys::keystore::{AccountKeystore, FileBasedKeystore, Keystore};
18use iota_sdk::{
19    iota_client_config::{IotaClientConfig, IotaEnv},
20    wallet_context::WalletContext,
21};
22use iota_swarm::memory::Swarm;
23use iota_swarm_config::{
24    genesis_config::GenesisConfig,
25    network_config::{NetworkConfig, NetworkConfigLight},
26};
27use iota_types::{
28    base_types::IotaAddress,
29    crypto::{AccountKeyPair, IotaKeyPair, KeypairTraits, get_key_pair},
30};
31use tempfile::tempdir;
32use test_cluster::{TestCluster, TestClusterBuilder};
33use tracing::info;
34
35use super::config::{ClusterTestOpt, Env};
36
37const DEVNET_FAUCET_ADDR: &str = "https://faucet.devnet.iota.cafe:443";
38const TESTNET_FAUCET_ADDR: &str = "https://faucet.testnet.iota.cafe:443";
39const DEVNET_FULLNODE_ADDR: &str = "https://api.devnet.iota.cafe:443";
40const TESTNET_FULLNODE_ADDR: &str = "https://api.testnet.iota.cafe:443";
41
42pub struct ClusterFactory;
43
44impl ClusterFactory {
45    pub async fn start(
46        options: &ClusterTestOpt,
47    ) -> Result<Box<dyn Cluster + Sync + Send>, anyhow::Error> {
48        Ok(match &options.env {
49            Env::NewLocal => Box::new(LocalNewCluster::start(options).await?),
50            _ => Box::new(RemoteRunningCluster::start(options).await?),
51        })
52    }
53}
54
55/// Cluster Abstraction
56#[async_trait]
57pub trait Cluster {
58    async fn start(options: &ClusterTestOpt) -> Result<Self, anyhow::Error>
59    where
60        Self: Sized;
61
62    fn fullnode_url(&self) -> &str;
63    fn user_key(&self) -> AccountKeyPair;
64    fn indexer_url(&self) -> &Option<String>;
65
66    /// Returns faucet url in a remote cluster.
67    fn remote_faucet_url(&self) -> Option<&str>;
68
69    /// Returns faucet key in a local cluster.
70    fn local_faucet_key(&self) -> Option<&AccountKeyPair>;
71
72    /// Place to put config for the wallet, and any locally running services.
73    fn config_directory(&self) -> &Path;
74}
75
76/// Represents an up and running cluster deployed remotely.
77pub struct RemoteRunningCluster {
78    fullnode_url: String,
79    faucet_url: String,
80    config_directory: tempfile::TempDir,
81}
82
83#[async_trait]
84impl Cluster for RemoteRunningCluster {
85    async fn start(options: &ClusterTestOpt) -> Result<Self, anyhow::Error> {
86        let (fullnode_url, faucet_url) = match options.env {
87            Env::Devnet => (
88                String::from(DEVNET_FULLNODE_ADDR),
89                String::from(DEVNET_FAUCET_ADDR),
90            ),
91            Env::Testnet => (
92                String::from(TESTNET_FULLNODE_ADDR),
93                String::from(TESTNET_FAUCET_ADDR),
94            ),
95            Env::CustomRemote => (
96                options
97                    .fullnode_address
98                    .clone()
99                    .expect("Expect 'fullnode_address' for Env::Custom"),
100                options
101                    .faucet_address
102                    .clone()
103                    .expect("Expect 'faucet_address' for Env::Custom"),
104            ),
105            Env::NewLocal => unreachable!("NewLocal shouldn't use RemoteRunningCluster"),
106        };
107
108        // TODO: test connectivity before proceeding?
109
110        Ok(Self {
111            fullnode_url,
112            faucet_url,
113            config_directory: tempfile::tempdir()?,
114        })
115    }
116
117    fn fullnode_url(&self) -> &str {
118        &self.fullnode_url
119    }
120
121    fn indexer_url(&self) -> &Option<String> {
122        &None
123    }
124
125    fn user_key(&self) -> AccountKeyPair {
126        get_key_pair().1
127    }
128
129    fn remote_faucet_url(&self) -> Option<&str> {
130        Some(&self.faucet_url)
131    }
132
133    fn local_faucet_key(&self) -> Option<&AccountKeyPair> {
134        None
135    }
136
137    fn config_directory(&self) -> &Path {
138        self.config_directory.path()
139    }
140}
141
142/// Represents a local Cluster which starts per cluster test run.
143pub struct LocalNewCluster {
144    test_cluster: TestCluster,
145    fullnode_url: String,
146    indexer_url: Option<String>,
147    faucet_key: AccountKeyPair,
148    config_directory: tempfile::TempDir,
149}
150
151impl LocalNewCluster {
152    #[allow(unused)]
153    pub fn swarm(&self) -> &Swarm {
154        &self.test_cluster.swarm
155    }
156}
157
158#[async_trait]
159impl Cluster for LocalNewCluster {
160    async fn start(options: &ClusterTestOpt) -> Result<Self, anyhow::Error> {
161        let data_ingestion_path = tempdir()?.into_path();
162        // TODO: options should contain port instead of address
163        let fullnode_rpc_addr = options.fullnode_address.as_ref().map(|addr| {
164            addr.parse::<SocketAddr>()
165                .expect("Unable to parse fullnode address")
166        });
167
168        let indexer_address = options.indexer_address.as_ref().map(|addr| {
169            addr.parse::<SocketAddr>()
170                .expect("Unable to parse indexer address")
171        });
172
173        let mut cluster_builder = TestClusterBuilder::new()
174            .enable_fullnode_events()
175            .with_data_ingestion_dir(data_ingestion_path.clone());
176
177        // Check if we already have a config directory that is passed
178        if let Some(config_dir) = options.config_dir.clone() {
179            assert!(options.epoch_duration_ms.is_none());
180            // Load the config of the IOTA authority.
181            let network_config_path = config_dir.join(IOTA_NETWORK_CONFIG);
182            let NetworkConfigLight {
183                validator_configs,
184                account_keys,
185                committee_with_network: _,
186            } = PersistedConfig::read(&network_config_path).map_err(|err| {
187                err.context(format!(
188                    "Cannot open IOTA network config file at {network_config_path:?}"
189                ))
190            })?;
191
192            // Add genesis objects
193            let genesis_path = config_dir.join(IOTA_GENESIS_FILENAME);
194            let genesis = Genesis::load(genesis_path)?;
195            let network_config = NetworkConfig {
196                validator_configs,
197                account_keys,
198                genesis,
199            };
200            cluster_builder = cluster_builder.set_network_config(network_config);
201
202            cluster_builder = cluster_builder.with_config_dir(config_dir);
203        } else {
204            // Let the faucet account hold 1000 gas objects on genesis
205            let mut genesis_config = GenesisConfig::custom_genesis(1, 100);
206            // Add any migration sources
207            let local_snapshots = options
208                .local_migration_snapshots
209                .iter()
210                .cloned()
211                .map(SnapshotSource::Local);
212            let remote_snapshots = options
213                .remote_migration_snapshots
214                .iter()
215                .cloned()
216                .map(SnapshotSource::S3);
217            genesis_config.migration_sources = local_snapshots.chain(remote_snapshots).collect();
218            // Custom genesis should be build here where we add the extra accounts
219            cluster_builder = cluster_builder.set_genesis_config(genesis_config);
220
221            if let Some(epoch_duration_ms) = options.epoch_duration_ms {
222                cluster_builder = cluster_builder.with_epoch_duration_ms(epoch_duration_ms);
223            }
224        }
225
226        if let Some(fullnode_rpc_addr) = fullnode_rpc_addr {
227            cluster_builder = cluster_builder.with_fullnode_rpc_addr(fullnode_rpc_addr);
228        }
229
230        let mut test_cluster = cluster_builder.build().await;
231
232        // Use the wealthy account for faucet
233        let faucet_key = test_cluster.swarm.config_mut().account_keys.swap_remove(0);
234        let faucet_address = IotaAddress::from(faucet_key.public());
235        info!(?faucet_address, "faucet_address");
236
237        // This cluster has fullnode handle, safe to unwrap
238        let fullnode_url = test_cluster.fullnode_handle.rpc_url.clone();
239
240        if let (Some(pg_address), Some(indexer_address)) =
241            (options.pg_address.clone(), indexer_address)
242        {
243            // Start in writer mode
244            start_test_indexer(
245                pg_address.clone(),
246                // reset the existing db
247                true,
248                None,
249                fullnode_url.clone(),
250                IndexerTypeConfig::writer_mode(None, None),
251                Some(data_ingestion_path.clone()),
252            )
253            .await;
254
255            // Start in reader mode
256            start_test_indexer(
257                pg_address,
258                false,
259                None,
260                fullnode_url.clone(),
261                IndexerTypeConfig::reader_mode(indexer_address.to_string()),
262                Some(data_ingestion_path),
263            )
264            .await;
265        }
266
267        if let Some(graphql_address) = &options.graphql_address {
268            let graphql_address = graphql_address.parse::<SocketAddr>()?;
269            let graphql_connection_config = ConnectionConfig::new(
270                Some(graphql_address.port()),
271                Some(graphql_address.ip().to_string()),
272                options.pg_address.clone(),
273                None,
274                None,
275                None,
276            );
277
278            start_graphql_server_with_fn_rpc(
279                graphql_connection_config.clone(),
280                Some(fullnode_url.clone()),
281                // cancellation_token
282                None,
283            )
284            .await;
285        }
286
287        // Let nodes connect to one another
288        tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
289
290        // TODO: test connectivity before proceeding?
291        Ok(Self {
292            test_cluster,
293            fullnode_url,
294            faucet_key,
295            config_directory: tempfile::tempdir()?,
296            indexer_url: options.indexer_address.clone(),
297        })
298    }
299
300    fn fullnode_url(&self) -> &str {
301        &self.fullnode_url
302    }
303
304    fn indexer_url(&self) -> &Option<String> {
305        &self.indexer_url
306    }
307
308    fn user_key(&self) -> AccountKeyPair {
309        get_key_pair().1
310    }
311
312    fn remote_faucet_url(&self) -> Option<&str> {
313        None
314    }
315
316    fn local_faucet_key(&self) -> Option<&AccountKeyPair> {
317        Some(&self.faucet_key)
318    }
319
320    fn config_directory(&self) -> &Path {
321        self.config_directory.path()
322    }
323}
324
325// Make linter happy
326#[async_trait]
327impl Cluster for Box<dyn Cluster + Send + Sync> {
328    async fn start(_options: &ClusterTestOpt) -> Result<Self, anyhow::Error> {
329        unreachable!(
330            "If we already have a boxed Cluster trait object we wouldn't have to call this function"
331        );
332    }
333    fn fullnode_url(&self) -> &str {
334        (**self).fullnode_url()
335    }
336    fn indexer_url(&self) -> &Option<String> {
337        (**self).indexer_url()
338    }
339
340    fn user_key(&self) -> AccountKeyPair {
341        (**self).user_key()
342    }
343
344    fn remote_faucet_url(&self) -> Option<&str> {
345        (**self).remote_faucet_url()
346    }
347
348    fn local_faucet_key(&self) -> Option<&AccountKeyPair> {
349        (**self).local_faucet_key()
350    }
351
352    fn config_directory(&self) -> &Path {
353        (**self).config_directory()
354    }
355}
356
357pub fn new_wallet_context_from_cluster(
358    cluster: &(dyn Cluster + Sync + Send),
359    key_pair: AccountKeyPair,
360) -> WalletContext {
361    let config_dir = cluster.config_directory();
362    let wallet_config_path = config_dir.join("client.yaml");
363    let fullnode_url = cluster.fullnode_url();
364    info!("Use RPC: {}", &fullnode_url);
365    let keystore_path = config_dir.join(IOTA_KEYSTORE_FILENAME);
366    let mut keystore = Keystore::from(FileBasedKeystore::new(&keystore_path).unwrap());
367    let address: IotaAddress = key_pair.public().into();
368    keystore
369        .add_key(None, IotaKeyPair::Ed25519(key_pair))
370        .unwrap();
371    IotaClientConfig::new(keystore)
372        .with_envs([IotaEnv::new("localnet", fullnode_url)])
373        .with_active_address(address)
374        .with_active_env("localnet".to_string())
375        .persisted(&wallet_config_path)
376        .save()
377        .unwrap();
378
379    info!(
380        "Initialize wallet from config path: {:?}",
381        wallet_config_path
382    );
383
384    WalletContext::new(&wallet_config_path, None, None).unwrap_or_else(|e| {
385        panic!("Failed to init wallet context from path {wallet_config_path:?}, error: {e}")
386    })
387}