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 => {
106                unreachable!("the NewLocal variant shouldn't use RemoteRunningCluster")
107            }
108        };
109
110        // TODO: test connectivity before proceeding?
111
112        Ok(Self {
113            fullnode_url,
114            faucet_url,
115            config_directory: tempfile::tempdir()?,
116        })
117    }
118
119    fn fullnode_url(&self) -> &str {
120        &self.fullnode_url
121    }
122
123    fn indexer_url(&self) -> &Option<String> {
124        &None
125    }
126
127    fn user_key(&self) -> AccountKeyPair {
128        get_key_pair().1
129    }
130
131    fn remote_faucet_url(&self) -> Option<&str> {
132        Some(&self.faucet_url)
133    }
134
135    fn local_faucet_key(&self) -> Option<&AccountKeyPair> {
136        None
137    }
138
139    fn config_directory(&self) -> &Path {
140        self.config_directory.path()
141    }
142}
143
144/// Represents a local Cluster which starts per cluster test run.
145pub struct LocalNewCluster {
146    test_cluster: TestCluster,
147    fullnode_url: String,
148    indexer_url: Option<String>,
149    faucet_key: AccountKeyPair,
150    config_directory: tempfile::TempDir,
151}
152
153impl LocalNewCluster {
154    #[allow(unused)]
155    pub fn swarm(&self) -> &Swarm {
156        &self.test_cluster.swarm
157    }
158}
159
160#[async_trait]
161impl Cluster for LocalNewCluster {
162    async fn start(options: &ClusterTestOpt) -> Result<Self, anyhow::Error> {
163        let data_ingestion_path = tempdir()?.keep();
164        // TODO: options should contain port instead of address
165        let fullnode_rpc_addr = options.fullnode_address.as_ref().map(|addr| {
166            addr.parse::<SocketAddr>()
167                .expect("unable to parse fullnode address")
168        });
169
170        let indexer_address = options.indexer_address.as_ref().map(|addr| {
171            addr.parse::<SocketAddr>()
172                .expect("unable to parse indexer address")
173        });
174
175        let mut cluster_builder = TestClusterBuilder::new()
176            .enable_fullnode_events()
177            .with_data_ingestion_dir(data_ingestion_path.clone());
178
179        // Check if we already have a config directory that is passed
180        if let Some(config_dir) = options.config_dir.clone() {
181            assert!(options.epoch_duration_ms.is_none());
182            // Load the config of the IOTA authority.
183            let network_config_path = config_dir.join(IOTA_NETWORK_CONFIG);
184            let NetworkConfigLight {
185                validator_configs,
186                account_keys,
187                committee_with_network: _,
188            } = PersistedConfig::read(&network_config_path).map_err(|err| {
189                err.context(format!(
190                    "cannot open IOTA network config file at {network_config_path:?}"
191                ))
192            })?;
193
194            // Add genesis objects
195            let genesis_path = config_dir.join(IOTA_GENESIS_FILENAME);
196            let genesis = Genesis::load(genesis_path)?;
197            let network_config = NetworkConfig {
198                validator_configs,
199                account_keys,
200                genesis,
201            };
202            cluster_builder = cluster_builder.set_network_config(network_config);
203
204            cluster_builder = cluster_builder.with_config_dir(config_dir);
205        } else {
206            // Let the faucet account hold 1000 gas objects on genesis
207            let mut genesis_config = GenesisConfig::custom_genesis(1, 100);
208            // Add any migration sources
209            let local_snapshots = options
210                .local_migration_snapshots
211                .iter()
212                .cloned()
213                .map(SnapshotSource::Local);
214            let remote_snapshots = options
215                .remote_migration_snapshots
216                .iter()
217                .cloned()
218                .map(SnapshotSource::S3);
219            genesis_config.migration_sources = local_snapshots.chain(remote_snapshots).collect();
220            // Custom genesis should be build here where we add the extra accounts
221            cluster_builder = cluster_builder.set_genesis_config(genesis_config);
222
223            if let Some(epoch_duration_ms) = options.epoch_duration_ms {
224                cluster_builder = cluster_builder.with_epoch_duration_ms(epoch_duration_ms);
225            }
226        }
227
228        if let Some(fullnode_rpc_addr) = fullnode_rpc_addr {
229            cluster_builder = cluster_builder.with_fullnode_rpc_addr(fullnode_rpc_addr);
230        }
231
232        let mut test_cluster = cluster_builder.build().await;
233
234        // Use the wealthy account for faucet
235        let faucet_key = test_cluster.swarm.config_mut().account_keys.swap_remove(0);
236        let faucet_address = IotaAddress::from(faucet_key.public());
237        info!(?faucet_address, "faucet_address");
238
239        // This cluster has fullnode handle, safe to unwrap
240        let fullnode_url = test_cluster.fullnode_handle.rpc_url.clone();
241
242        if let (Some(pg_address), Some(indexer_address)) =
243            (options.pg_address.clone(), indexer_address)
244        {
245            // Start in writer mode
246            start_test_indexer(
247                pg_address.clone(),
248                // reset the existing db
249                true,
250                None,
251                fullnode_url.clone(),
252                IndexerTypeConfig::writer_mode(None, None),
253                Some(data_ingestion_path.clone()),
254            )
255            .await;
256
257            // Start in reader mode
258            start_test_indexer(
259                pg_address,
260                false,
261                None,
262                fullnode_url.clone(),
263                IndexerTypeConfig::reader_mode(indexer_address.to_string()),
264                Some(data_ingestion_path),
265            )
266            .await;
267        }
268
269        if let Some(graphql_address) = &options.graphql_address {
270            let graphql_address = graphql_address.parse::<SocketAddr>()?;
271            let graphql_connection_config = ConnectionConfig::new(
272                Some(graphql_address.port()),
273                Some(graphql_address.ip().to_string()),
274                options.pg_address.clone(),
275                None,
276                None,
277                None,
278                None,
279            );
280
281            start_graphql_server_with_fn_rpc(
282                graphql_connection_config.clone(),
283                Some(fullnode_url.clone()),
284                // resolves to default cancellation_token
285                None,
286                // resolves to default service config
287                None,
288            )
289            .await;
290        }
291
292        // Let nodes connect to one another
293        tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
294
295        // TODO: test connectivity before proceeding?
296        Ok(Self {
297            test_cluster,
298            fullnode_url,
299            faucet_key,
300            config_directory: tempfile::tempdir()?,
301            indexer_url: options.indexer_address.clone(),
302        })
303    }
304
305    fn fullnode_url(&self) -> &str {
306        &self.fullnode_url
307    }
308
309    fn indexer_url(&self) -> &Option<String> {
310        &self.indexer_url
311    }
312
313    fn user_key(&self) -> AccountKeyPair {
314        get_key_pair().1
315    }
316
317    fn remote_faucet_url(&self) -> Option<&str> {
318        None
319    }
320
321    fn local_faucet_key(&self) -> Option<&AccountKeyPair> {
322        Some(&self.faucet_key)
323    }
324
325    fn config_directory(&self) -> &Path {
326        self.config_directory.path()
327    }
328}
329
330// Make linter happy
331#[async_trait]
332impl Cluster for Box<dyn Cluster + Send + Sync> {
333    async fn start(_options: &ClusterTestOpt) -> Result<Self, anyhow::Error> {
334        unreachable!(
335            "if we already have a boxed Cluster trait object we wouldn't have to call this function"
336        );
337    }
338    fn fullnode_url(&self) -> &str {
339        (**self).fullnode_url()
340    }
341    fn indexer_url(&self) -> &Option<String> {
342        (**self).indexer_url()
343    }
344
345    fn user_key(&self) -> AccountKeyPair {
346        (**self).user_key()
347    }
348
349    fn remote_faucet_url(&self) -> Option<&str> {
350        (**self).remote_faucet_url()
351    }
352
353    fn local_faucet_key(&self) -> Option<&AccountKeyPair> {
354        (**self).local_faucet_key()
355    }
356
357    fn config_directory(&self) -> &Path {
358        (**self).config_directory()
359    }
360}
361
362pub fn new_wallet_context_from_cluster(
363    cluster: &(dyn Cluster + Sync + Send),
364    key_pair: AccountKeyPair,
365) -> WalletContext {
366    let config_dir = cluster.config_directory();
367    let wallet_config_path = config_dir.join("client.yaml");
368    let fullnode_url = cluster.fullnode_url();
369    info!("Use RPC: {fullnode_url}");
370    let keystore_path = config_dir.join(IOTA_KEYSTORE_FILENAME);
371    let mut keystore = Keystore::from(FileBasedKeystore::new(&keystore_path).unwrap());
372    let address: IotaAddress = key_pair.public().into();
373    keystore
374        .add_key(None, IotaKeyPair::Ed25519(key_pair))
375        .unwrap();
376    IotaClientConfig::new(keystore)
377        .with_envs([IotaEnv::new("localnet", fullnode_url)])
378        .with_active_address(address)
379        .with_active_env("localnet".to_string())
380        .persisted(&wallet_config_path)
381        .save()
382        .unwrap();
383
384    info!(
385        "Initialize wallet from config path: {:?}",
386        wallet_config_path
387    );
388
389    WalletContext::new(&wallet_config_path, None, None).unwrap_or_else(|e| {
390        panic!("failed to init wallet context from path {wallet_config_path:?}, error: {e}")
391    })
392}