1use crate::abi::EthBridgeConfig;
5use crate::crypto::BridgeAuthorityKeyPair;
6use crate::error::BridgeError;
7use crate::eth_client::EthClient;
8use crate::metered_eth_provider::MeteredEthHttpProvider;
9use crate::metered_eth_provider::new_metered_eth_provider;
10use crate::metrics::BridgeMetrics;
11use crate::sui_client::SuiBridgeClient;
12use crate::types::{BridgeAction, is_route_valid};
13use crate::utils::get_eth_contract_addresses;
14use anyhow::anyhow;
15use ethers::providers::Middleware;
16use ethers::types::Address as EthAddress;
17use futures::StreamExt;
18use serde::{Deserialize, Serialize};
19use serde_with::serde_as;
20use std::collections::BTreeMap;
21use std::collections::HashSet;
22use std::path::PathBuf;
23use std::str::FromStr;
24use std::sync::Arc;
25use sui_config::Config;
26use sui_json_rpc_types::Coin;
27use sui_keys::keypair_file::read_key;
28use sui_sdk::SuiClientBuilder;
29use sui_sdk::apis::CoinReadApi;
30use sui_types::base_types::ObjectRef;
31use sui_types::base_types::{ObjectID, SuiAddress};
32use sui_types::bridge::BridgeChainId;
33use sui_types::crypto::KeypairTraits;
34use sui_types::crypto::{NetworkKeyPair, SuiKeyPair, get_key_pair_from_rng};
35use sui_types::digests::{get_mainnet_chain_identifier, get_testnet_chain_identifier};
36use sui_types::event::EventID;
37use sui_types::object::Owner;
38use tracing::info;
39
40#[serde_as]
41#[derive(Clone, Debug, Deserialize, Serialize)]
42#[serde(rename_all = "kebab-case")]
43pub struct EthConfig {
44 pub eth_rpc_url: String,
46 pub eth_bridge_proxy_address: String,
48 pub eth_bridge_chain_id: u8,
50 pub eth_contracts_start_block_fallback: Option<u64>,
58 #[serde(skip_serializing_if = "Option::is_none")]
64 pub eth_contracts_start_block_override: Option<u64>,
65}
66
67#[serde_as]
68#[derive(Clone, Debug, Deserialize, Serialize)]
69#[serde(rename_all = "kebab-case")]
70pub struct SuiConfig {
71 pub sui_rpc_url: String,
73 pub sui_bridge_chain_id: u8,
75 #[serde(skip_serializing_if = "Option::is_none")]
78 pub bridge_client_key_path: Option<PathBuf>,
79 #[serde(skip_serializing_if = "Option::is_none")]
84 pub bridge_client_gas_object: Option<ObjectID>,
85 #[serde(skip_serializing_if = "Option::is_none")]
93 pub sui_bridge_module_last_processed_event_id_override: Option<EventID>,
94}
95
96#[serde_as]
97#[derive(Debug, Deserialize, Serialize)]
98#[serde(rename_all = "kebab-case")]
99pub struct BridgeNodeConfig {
100 pub server_listen_port: u16,
102 pub metrics_port: u16,
104 pub bridge_authority_key_path: PathBuf,
106 pub run_client: bool,
109 #[serde(skip_serializing_if = "Option::is_none")]
111 pub db_path: Option<PathBuf>,
112 pub approved_governance_actions: Vec<BridgeAction>,
114 pub sui: SuiConfig,
116 pub eth: EthConfig,
118 #[serde(default = "default_ed25519_key_pair")]
120 pub metrics_key_pair: NetworkKeyPair,
121 #[serde(skip_serializing_if = "Option::is_none")]
122 pub metrics: Option<MetricsConfig>,
123
124 #[serde(skip_serializing_if = "Option::is_none")]
125 pub watchdog_config: Option<WatchdogConfig>,
126}
127
128pub fn default_ed25519_key_pair() -> NetworkKeyPair {
129 get_key_pair_from_rng(&mut rand::rngs::OsRng).1
130}
131
132#[derive(Debug, Clone, Deserialize, Serialize)]
133#[serde(rename_all = "kebab-case")]
134pub struct MetricsConfig {
135 #[serde(skip_serializing_if = "Option::is_none")]
136 pub push_interval_seconds: Option<u64>,
137 pub push_url: String,
138}
139
140#[derive(Debug, Clone, Deserialize, Serialize)]
141#[serde(rename_all = "kebab-case")]
142pub struct WatchdogConfig {
143 pub total_supplies: BTreeMap<String, String>,
145}
146
147impl Config for BridgeNodeConfig {}
148
149impl BridgeNodeConfig {
150 pub async fn validate(
151 &self,
152 metrics: Arc<BridgeMetrics>,
153 ) -> anyhow::Result<(BridgeServerConfig, Option<BridgeClientConfig>)> {
154 info!("Starting config validation");
155 if !is_route_valid(
156 BridgeChainId::try_from(self.sui.sui_bridge_chain_id)?,
157 BridgeChainId::try_from(self.eth.eth_bridge_chain_id)?,
158 ) {
159 return Err(anyhow!(
160 "Route between Sui chain id {} and Eth chain id {} is not valid",
161 self.sui.sui_bridge_chain_id,
162 self.eth.eth_bridge_chain_id,
163 ));
164 };
165
166 let bridge_authority_key = match read_key(&self.bridge_authority_key_path, true)? {
167 SuiKeyPair::Secp256k1(key) => key,
168 _ => unreachable!("we required secp256k1 key in `read_key`"),
169 };
170
171 let sui_client =
174 Arc::new(SuiBridgeClient::new(&self.sui.sui_rpc_url, metrics.clone()).await?);
175 let bridge_committee = sui_client
176 .get_bridge_committee()
177 .await
178 .map_err(|e| anyhow!("Error getting bridge committee: {:?}", e))?;
179 if !bridge_committee.is_active_member(&bridge_authority_key.public().into()) {
180 return Err(anyhow!(
181 "Bridge authority key is not part of bridge committee"
182 ));
183 }
184
185 let (eth_client, eth_contracts) = self.prepare_for_eth(metrics.clone()).await?;
186 let bridge_summary = sui_client
187 .get_bridge_summary()
188 .await
189 .map_err(|e| anyhow!("Error getting bridge summary: {:?}", e))?;
190 if bridge_summary.chain_id != self.sui.sui_bridge_chain_id {
191 anyhow::bail!(
192 "Bridge chain id mismatch: expected {}, but connected to {}",
193 self.sui.sui_bridge_chain_id,
194 bridge_summary.chain_id
195 );
196 }
197
198 for action in &self.approved_governance_actions {
200 if !action.is_governace_action() {
201 anyhow::bail!(format!(
202 "{:?}",
203 BridgeError::ActionIsNotGovernanceAction(action.clone())
204 ));
205 }
206 }
207 let approved_governance_actions = self.approved_governance_actions.clone();
208
209 let bridge_server_config = BridgeServerConfig {
210 key: bridge_authority_key,
211 metrics_port: self.metrics_port,
212 eth_bridge_proxy_address: eth_contracts[0], server_listen_port: self.server_listen_port,
214 sui_client: sui_client.clone(),
215 eth_client: eth_client.clone(),
216 approved_governance_actions,
217 };
218 if !self.run_client {
219 return Ok((bridge_server_config, None));
220 }
221
222 let (bridge_client_key, client_sui_address, gas_object_ref) =
224 self.prepare_for_sui(sui_client.clone(), metrics).await?;
225
226 let db_path = self
227 .db_path
228 .clone()
229 .ok_or(anyhow!("`db_path` is required when `run_client` is true"))?;
230
231 let bridge_client_config = BridgeClientConfig {
232 sui_address: client_sui_address,
233 key: bridge_client_key,
234 gas_object_ref,
235 metrics_port: self.metrics_port,
236 sui_client: sui_client.clone(),
237 eth_client: eth_client.clone(),
238 db_path,
239 eth_contracts,
240 eth_contracts_start_block_fallback: self
242 .eth
243 .eth_contracts_start_block_fallback
244 .unwrap(),
245 eth_contracts_start_block_override: self.eth.eth_contracts_start_block_override,
246 sui_bridge_module_last_processed_event_id_override: self
247 .sui
248 .sui_bridge_module_last_processed_event_id_override,
249 };
250
251 info!("Config validation complete");
252 Ok((bridge_server_config, Some(bridge_client_config)))
253 }
254
255 async fn prepare_for_eth(
256 &self,
257 metrics: Arc<BridgeMetrics>,
258 ) -> anyhow::Result<(Arc<EthClient<MeteredEthHttpProvider>>, Vec<EthAddress>)> {
259 info!("Creating Ethereum client provider");
260 let bridge_proxy_address = EthAddress::from_str(&self.eth.eth_bridge_proxy_address)?;
261 let provider = Arc::new(
262 new_metered_eth_provider(&self.eth.eth_rpc_url, metrics.clone())
263 .unwrap()
264 .interval(std::time::Duration::from_millis(2000)),
265 );
266 let chain_id = provider.get_chainid().await?;
267 let (
268 committee_address,
269 limiter_address,
270 vault_address,
271 config_address,
272 _weth_address,
273 _usdt_address,
274 _wbtc_address,
275 _lbtc_address,
276 ) = get_eth_contract_addresses(bridge_proxy_address, &provider).await?;
277 let config = EthBridgeConfig::new(config_address, provider.clone());
278
279 if self.run_client && self.eth.eth_contracts_start_block_fallback.is_none() {
280 return Err(anyhow!(
281 "eth_contracts_start_block_fallback is required when run_client is true"
282 ));
283 }
284
285 let bridge_chain_id: u8 = config.chain_id().call().await?;
288 if self.eth.eth_bridge_chain_id != bridge_chain_id {
289 return Err(anyhow!(
290 "Bridge chain id mismatch: expected {}, but connected to {}",
291 self.eth.eth_bridge_chain_id,
292 bridge_chain_id
293 ));
294 }
295 if bridge_chain_id == BridgeChainId::EthMainnet as u8 && chain_id.as_u64() != 1 {
296 anyhow::bail!(
297 "Expected Eth chain id 1, but connected to {}",
298 chain_id.as_u64()
299 );
300 }
301 if bridge_chain_id == BridgeChainId::EthSepolia as u8 && chain_id.as_u64() != 11155111 {
302 anyhow::bail!(
303 "Expected Eth chain id 11155111, but connected to {}",
304 chain_id.as_u64()
305 );
306 }
307 info!(
308 "Connected to Eth chain: {}, Bridge chain id: {}",
309 chain_id.as_u64(),
310 bridge_chain_id,
311 );
312
313 let eth_client = Arc::new(
314 EthClient::<MeteredEthHttpProvider>::new(
315 &self.eth.eth_rpc_url,
316 HashSet::from_iter(vec![
317 bridge_proxy_address,
318 committee_address,
319 config_address,
320 limiter_address,
321 vault_address,
322 ]),
323 metrics,
324 )
325 .await?,
326 );
327 let contract_addresses = vec![
328 bridge_proxy_address,
329 committee_address,
330 config_address,
331 limiter_address,
332 vault_address,
333 ];
334 info!("Ethereum client setup complete");
335 Ok((eth_client, contract_addresses))
336 }
337
338 async fn prepare_for_sui(
339 &self,
340 sui_client: Arc<SuiBridgeClient>,
341 metrics: Arc<BridgeMetrics>,
342 ) -> anyhow::Result<(SuiKeyPair, SuiAddress, ObjectRef)> {
343 let bridge_client_key = match &self.sui.bridge_client_key_path {
344 None => read_key(&self.bridge_authority_key_path, true),
345 Some(path) => read_key(path, false),
346 }?;
347
348 let sui_identifier = sui_client
351 .get_chain_identifier()
352 .await
353 .map_err(|e| anyhow!("Error getting chain identifier from Sui: {:?}", e))?;
354 if self.sui.sui_bridge_chain_id == BridgeChainId::SuiMainnet as u8
355 && sui_identifier != get_mainnet_chain_identifier().to_string()
356 {
357 anyhow::bail!(
358 "Expected sui chain identifier {}, but connected to {}",
359 self.sui.sui_bridge_chain_id,
360 sui_identifier
361 );
362 }
363 if self.sui.sui_bridge_chain_id == BridgeChainId::SuiTestnet as u8
364 && sui_identifier != get_testnet_chain_identifier().to_string()
365 {
366 anyhow::bail!(
367 "Expected sui chain identifier {}, but connected to {}",
368 self.sui.sui_bridge_chain_id,
369 sui_identifier
370 );
371 }
372 info!(
373 "Connected to Sui chain: {}, Bridge chain id: {}",
374 sui_identifier, self.sui.sui_bridge_chain_id,
375 );
376
377 let client_sui_address = SuiAddress::from(&bridge_client_key.public());
378
379 let gas_object_id = match self.sui.bridge_client_gas_object {
380 Some(id) => id,
381 None => {
382 info!("No gas object configured, finding gas object with highest balance");
383 let sui_client = SuiClientBuilder::default()
384 .build(&self.sui.sui_rpc_url)
385 .await?;
386 let coin =
387 pick_highest_balance_coin(sui_client.coin_read_api(), client_sui_address, 10_000_000_000)
389 .await?;
390 coin.coin_object_id
391 }
392 };
393 let (gas_coin, gas_object_ref, owner) = sui_client
394 .get_gas_data_panic_if_not_gas(gas_object_id)
395 .await;
396 if owner != Owner::AddressOwner(client_sui_address) {
397 return Err(anyhow!(
398 "Gas object {:?} is not owned by bridge client key's associated sui address {:?}, but {:?}",
399 gas_object_id,
400 client_sui_address,
401 owner
402 ));
403 }
404 let balance = gas_coin.value();
405 info!("Gas object balance: {}", balance);
406 metrics.gas_coin_balance.set(balance as i64);
407
408 info!("Sui client setup complete");
409 Ok((bridge_client_key, client_sui_address, gas_object_ref))
410 }
411}
412
413pub struct BridgeServerConfig {
414 pub key: BridgeAuthorityKeyPair,
415 pub server_listen_port: u16,
416 pub eth_bridge_proxy_address: EthAddress,
417 pub metrics_port: u16,
418 pub sui_client: Arc<SuiBridgeClient>,
419 pub eth_client: Arc<EthClient<MeteredEthHttpProvider>>,
420 pub approved_governance_actions: Vec<BridgeAction>,
422}
423
424pub struct BridgeClientConfig {
425 pub sui_address: SuiAddress,
426 pub key: SuiKeyPair,
427 pub gas_object_ref: ObjectRef,
428 pub metrics_port: u16,
429 pub sui_client: Arc<SuiBridgeClient>,
430 pub eth_client: Arc<EthClient<MeteredEthHttpProvider>>,
431 pub db_path: PathBuf,
432 pub eth_contracts: Vec<EthAddress>,
433 pub eth_contracts_start_block_fallback: u64,
435 pub eth_contracts_start_block_override: Option<u64>,
436 pub sui_bridge_module_last_processed_event_id_override: Option<EventID>,
437}
438
439#[serde_as]
440#[derive(Clone, Debug, Deserialize, Serialize)]
441#[serde(rename_all = "kebab-case")]
442pub struct BridgeCommitteeConfig {
443 pub bridge_authority_port_and_key_path: Vec<(u64, PathBuf)>,
444}
445
446impl Config for BridgeCommitteeConfig {}
447
448pub async fn pick_highest_balance_coin(
449 coin_read_api: &CoinReadApi,
450 address: SuiAddress,
451 minimal_amount: u64,
452) -> anyhow::Result<Coin> {
453 info!("Looking for a suitable gas coin for address {:?}", address);
454
455 let mut stream = coin_read_api
457 .get_coins_stream(address, Some("0x2::sui::SUI".to_string()))
458 .boxed();
459
460 let mut coins_checked = 0;
461
462 while let Some(coin) = stream.next().await {
463 info!(
464 "Checking coin: {:?}, balance: {}",
465 coin.coin_object_id, coin.balance
466 );
467 coins_checked += 1;
468
469 if coin.balance >= minimal_amount {
471 info!(
472 "Found suitable gas coin with {} mist (object ID: {:?})",
473 coin.balance, coin.coin_object_id
474 );
475 return Ok(coin);
476 }
477
478 if coins_checked >= 1000 {
480 break;
481 }
482 }
483
484 Err(anyhow!(
485 "No suitable gas coin with >= {} mist found for address {:?} after checking {} coins",
486 minimal_amount,
487 address,
488 coins_checked
489 ))
490}
491
492#[derive(Debug, Eq, PartialEq, Clone)]
493pub struct EthContractAddresses {
494 pub sui_bridge: EthAddress,
495 pub bridge_committee: EthAddress,
496 pub bridge_config: EthAddress,
497 pub bridge_limiter: EthAddress,
498 pub bridge_vault: EthAddress,
499}