1use 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#[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 fn remote_faucet_url(&self) -> Option<&str>;
68
69 fn local_faucet_key(&self) -> Option<&AccountKeyPair>;
71
72 fn config_directory(&self) -> &Path;
74}
75
76pub 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 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
144pub 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 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 if let Some(config_dir) = options.config_dir.clone() {
181 assert!(options.epoch_duration_ms.is_none());
182 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 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 mut genesis_config = GenesisConfig::custom_genesis(1, 100);
208 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 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 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 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_test_indexer(
247 pg_address.clone(),
248 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_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 );
279
280 start_graphql_server_with_fn_rpc(
281 graphql_connection_config.clone(),
282 Some(fullnode_url.clone()),
283 None,
285 )
286 .await;
287 }
288
289 tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
291
292 Ok(Self {
294 test_cluster,
295 fullnode_url,
296 faucet_key,
297 config_directory: tempfile::tempdir()?,
298 indexer_url: options.indexer_address.clone(),
299 })
300 }
301
302 fn fullnode_url(&self) -> &str {
303 &self.fullnode_url
304 }
305
306 fn indexer_url(&self) -> &Option<String> {
307 &self.indexer_url
308 }
309
310 fn user_key(&self) -> AccountKeyPair {
311 get_key_pair().1
312 }
313
314 fn remote_faucet_url(&self) -> Option<&str> {
315 None
316 }
317
318 fn local_faucet_key(&self) -> Option<&AccountKeyPair> {
319 Some(&self.faucet_key)
320 }
321
322 fn config_directory(&self) -> &Path {
323 self.config_directory.path()
324 }
325}
326
327#[async_trait]
329impl Cluster for Box<dyn Cluster + Send + Sync> {
330 async fn start(_options: &ClusterTestOpt) -> Result<Self, anyhow::Error> {
331 unreachable!(
332 "if we already have a boxed Cluster trait object we wouldn't have to call this function"
333 );
334 }
335 fn fullnode_url(&self) -> &str {
336 (**self).fullnode_url()
337 }
338 fn indexer_url(&self) -> &Option<String> {
339 (**self).indexer_url()
340 }
341
342 fn user_key(&self) -> AccountKeyPair {
343 (**self).user_key()
344 }
345
346 fn remote_faucet_url(&self) -> Option<&str> {
347 (**self).remote_faucet_url()
348 }
349
350 fn local_faucet_key(&self) -> Option<&AccountKeyPair> {
351 (**self).local_faucet_key()
352 }
353
354 fn config_directory(&self) -> &Path {
355 (**self).config_directory()
356 }
357}
358
359pub fn new_wallet_context_from_cluster(
360 cluster: &(dyn Cluster + Sync + Send),
361 key_pair: AccountKeyPair,
362) -> WalletContext {
363 let config_dir = cluster.config_directory();
364 let wallet_config_path = config_dir.join("client.yaml");
365 let fullnode_url = cluster.fullnode_url();
366 info!("Use RPC: {fullnode_url}");
367 let keystore_path = config_dir.join(IOTA_KEYSTORE_FILENAME);
368 let mut keystore = Keystore::from(FileBasedKeystore::new(&keystore_path).unwrap());
369 let address: IotaAddress = key_pair.public().into();
370 keystore
371 .add_key(None, IotaKeyPair::Ed25519(key_pair))
372 .unwrap();
373 IotaClientConfig::new(keystore)
374 .with_envs([IotaEnv::new("localnet", fullnode_url)])
375 .with_active_address(address)
376 .with_active_env("localnet".to_string())
377 .persisted(&wallet_config_path)
378 .save()
379 .unwrap();
380
381 info!(
382 "Initialize wallet from config path: {:?}",
383 wallet_config_path
384 );
385
386 WalletContext::new(&wallet_config_path, None, None).unwrap_or_else(|e| {
387 panic!("failed to init wallet context from path {wallet_config_path:?}, error: {e}")
388 })
389}