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 {:?}",
189                    network_config_path
190                ))
191            })?;
192
193            // Add genesis objects
194            let genesis_path = config_dir.join(IOTA_GENESIS_FILENAME);
195            let genesis = Genesis::load(genesis_path)?;
196            let network_config = NetworkConfig {
197                validator_configs,
198                account_keys,
199                genesis,
200            };
201            cluster_builder = cluster_builder.set_network_config(network_config);
202
203            cluster_builder = cluster_builder.with_config_dir(config_dir);
204        } else {
205            // Let the faucet account hold 1000 gas objects on genesis
206            let mut genesis_config = GenesisConfig::custom_genesis(1, 100);
207            // Add any migration sources
208            let local_snapshots = options
209                .local_migration_snapshots
210                .iter()
211                .cloned()
212                .map(SnapshotSource::Local);
213            let remote_snapshots = options
214                .remote_migration_snapshots
215                .iter()
216                .cloned()
217                .map(SnapshotSource::S3);
218            genesis_config.migration_sources = local_snapshots.chain(remote_snapshots).collect();
219            // Custom genesis should be build here where we add the extra accounts
220            cluster_builder = cluster_builder.set_genesis_config(genesis_config);
221
222            if let Some(epoch_duration_ms) = options.epoch_duration_ms {
223                cluster_builder = cluster_builder.with_epoch_duration_ms(epoch_duration_ms);
224            }
225        }
226
227        if let Some(fullnode_rpc_addr) = fullnode_rpc_addr {
228            cluster_builder = cluster_builder.with_fullnode_rpc_addr(fullnode_rpc_addr);
229        }
230
231        let mut test_cluster = cluster_builder.build().await;
232
233        // Use the wealthy account for faucet
234        let faucet_key = test_cluster.swarm.config_mut().account_keys.swap_remove(0);
235        let faucet_address = IotaAddress::from(faucet_key.public());
236        info!(?faucet_address, "faucet_address");
237
238        // This cluster has fullnode handle, safe to unwrap
239        let fullnode_url = test_cluster.fullnode_handle.rpc_url.clone();
240
241        if let (Some(pg_address), Some(indexer_address)) =
242            (options.pg_address.clone(), indexer_address)
243        {
244            // Start in writer mode
245            start_test_indexer(
246                pg_address.clone(),
247                // reset the existing db
248                true,
249                None,
250                fullnode_url.clone(),
251                IndexerTypeConfig::writer_mode(None, None),
252                Some(data_ingestion_path.clone()),
253            )
254            .await;
255
256            // Start in reader mode
257            start_test_indexer(
258                pg_address,
259                false,
260                None,
261                fullnode_url.clone(),
262                IndexerTypeConfig::reader_mode(indexer_address.to_string()),
263                Some(data_ingestion_path),
264            )
265            .await;
266        }
267
268        if let Some(graphql_address) = &options.graphql_address {
269            let graphql_address = graphql_address.parse::<SocketAddr>()?;
270            let graphql_connection_config = ConnectionConfig::new(
271                Some(graphql_address.port()),
272                Some(graphql_address.ip().to_string()),
273                options.pg_address.clone(),
274                None,
275                None,
276                None,
277            );
278
279            start_graphql_server_with_fn_rpc(
280                graphql_connection_config.clone(),
281                Some(fullnode_url.clone()),
282                // cancellation_token
283                None,
284            )
285            .await;
286        }
287
288        // Let nodes connect to one another
289        tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
290
291        // TODO: test connectivity before proceeding?
292        Ok(Self {
293            test_cluster,
294            fullnode_url,
295            faucet_key,
296            config_directory: tempfile::tempdir()?,
297            indexer_url: options.indexer_address.clone(),
298        })
299    }
300
301    fn fullnode_url(&self) -> &str {
302        &self.fullnode_url
303    }
304
305    fn indexer_url(&self) -> &Option<String> {
306        &self.indexer_url
307    }
308
309    fn user_key(&self) -> AccountKeyPair {
310        get_key_pair().1
311    }
312
313    fn remote_faucet_url(&self) -> Option<&str> {
314        None
315    }
316
317    fn local_faucet_key(&self) -> Option<&AccountKeyPair> {
318        Some(&self.faucet_key)
319    }
320
321    fn config_directory(&self) -> &Path {
322        self.config_directory.path()
323    }
324}
325
326// Make linter happy
327#[async_trait]
328impl Cluster for Box<dyn Cluster + Send + Sync> {
329    async fn start(_options: &ClusterTestOpt) -> Result<Self, anyhow::Error> {
330        unreachable!(
331            "If we already have a boxed Cluster trait object we wouldn't have to call this function"
332        );
333    }
334    fn fullnode_url(&self) -> &str {
335        (**self).fullnode_url()
336    }
337    fn indexer_url(&self) -> &Option<String> {
338        (**self).indexer_url()
339    }
340
341    fn user_key(&self) -> AccountKeyPair {
342        (**self).user_key()
343    }
344
345    fn remote_faucet_url(&self) -> Option<&str> {
346        (**self).remote_faucet_url()
347    }
348
349    fn local_faucet_key(&self) -> Option<&AccountKeyPair> {
350        (**self).local_faucet_key()
351    }
352
353    fn config_directory(&self) -> &Path {
354        (**self).config_directory()
355    }
356}
357
358pub fn new_wallet_context_from_cluster(
359    cluster: &(dyn Cluster + Sync + Send),
360    key_pair: AccountKeyPair,
361) -> WalletContext {
362    let config_dir = cluster.config_directory();
363    let wallet_config_path = config_dir.join("client.yaml");
364    let fullnode_url = cluster.fullnode_url();
365    info!("Use RPC: {}", &fullnode_url);
366    let keystore_path = config_dir.join(IOTA_KEYSTORE_FILENAME);
367    let mut keystore = Keystore::from(FileBasedKeystore::new(&keystore_path).unwrap());
368    let address: IotaAddress = key_pair.public().into();
369    keystore
370        .add_key(None, IotaKeyPair::Ed25519(key_pair))
371        .unwrap();
372    IotaClientConfig::new(keystore)
373        .with_envs([IotaEnv::new("localnet", fullnode_url)])
374        .with_active_address(address)
375        .with_active_env("localnet".to_string())
376        .persisted(&wallet_config_path)
377        .save()
378        .unwrap();
379
380    info!(
381        "Initialize wallet from config path: {:?}",
382        wallet_config_path
383    );
384
385    WalletContext::new(&wallet_config_path, None, None).unwrap_or_else(|e| {
386        panic!(
387            "Failed to init wallet context from path {:?}, error: {e}",
388            wallet_config_path
389        )
390    })
391}