sui_bridge/
config.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::abi::EthBridgeConfig;
5use crate::crypto::BridgeAuthorityKeyPair;
6use crate::error::BridgeError;
7use crate::eth_client::EthClient;
8use crate::metered_eth_provider::MeteredEthHttpProvier;
9use crate::metered_eth_provider::new_metered_eth_provider;
10use crate::metrics::BridgeMetrics;
11use crate::sui_client::SuiClient;
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::apis::CoinReadApi;
29use sui_sdk::{SuiClient as SuiSdkClient, SuiClientBuilder};
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    /// Rpc url for Eth fullnode, used for query stuff.
45    pub eth_rpc_url: String,
46    /// The proxy address of SuiBridge
47    pub eth_bridge_proxy_address: String,
48    /// The expected BridgeChainId on Eth side.
49    pub eth_bridge_chain_id: u8,
50    /// The starting block for EthSyncer to monitor eth contracts.
51    /// It is required when `run_client` is true. Usually this is
52    /// the block number when the bridge contracts are deployed.
53    /// When BridgeNode starts, it reads the contract watermark from storage.
54    /// If the watermark is not found, it will start from this fallback block number.
55    /// If the watermark is found, it will start from the watermark.
56    /// this v.s.`eth_contracts_start_block_override`:
57    pub eth_contracts_start_block_fallback: Option<u64>,
58    /// The starting block for EthSyncer to monitor eth contracts. It overrides
59    /// the watermark in storage. This is useful when we want to reprocess the events
60    /// from a specific block number.
61    /// Note: this field has to be reset after starting the BridgeNode, otherwise it will
62    /// reprocess the events from this block number every time it starts.
63    #[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    /// Rpc url for Sui fullnode, used for query stuff and submit transactions.
72    pub sui_rpc_url: String,
73    /// The expected BridgeChainId on Sui side.
74    pub sui_bridge_chain_id: u8,
75    /// Path of the file where bridge client key (any SuiKeyPair) is stored.
76    /// If `run_client` is true, and this is None, then use `bridge_authority_key_path` as client key.
77    #[serde(skip_serializing_if = "Option::is_none")]
78    pub bridge_client_key_path: Option<PathBuf>,
79    /// The gas object to use for paying for gas fees for the client. It needs to
80    /// be owned by the address associated with bridge client key. If not set
81    /// and `run_client` is true, it will query and use the gas object with highest
82    /// amount for the account.
83    #[serde(skip_serializing_if = "Option::is_none")]
84    pub bridge_client_gas_object: Option<ObjectID>,
85    /// Override the last processed EventID for bridge module `bridge`.
86    /// When set, SuiSyncer will start from this cursor (exclusively) instead of the one in storage.
87    /// If the cursor is not found in storage or override, the query will start from genesis.
88    /// Key: sui module, Value: last processed EventID (tx_digest, event_seq).
89    /// Note 1: This field should be rarely used. Only use it when you understand how to follow up.
90    /// Note 2: the EventID needs to be valid, namely it must exist and matches the filter.
91    /// Otherwise, it will miss one event because of fullnode Event query semantics.
92    #[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    /// The port that the server listens on.
101    pub server_listen_port: u16,
102    /// The port that for metrics server.
103    pub metrics_port: u16,
104    /// Path of the file where bridge authority key (Secp256k1) is stored.
105    pub bridge_authority_key_path: PathBuf,
106    /// Whether to run client. If true, `sui.bridge_client_key_path`
107    /// and `db_path` needs to be provided.
108    pub run_client: bool,
109    /// Path of the client storage. Required when `run_client` is true.
110    #[serde(skip_serializing_if = "Option::is_none")]
111    pub db_path: Option<PathBuf>,
112    /// A list of approved governance actions. Action in this list will be signed when requested by client.
113    pub approved_governance_actions: Vec<BridgeAction>,
114    /// Sui configuration
115    pub sui: SuiConfig,
116    /// Eth configuration
117    pub eth: EthConfig,
118    /// Network key used for metrics pushing
119    #[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    /// Total supplies to watch on Sui. Mapping from coin name to coin type tag
144    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        // we do this check here instead of `prepare_for_sui` below because
172        // that is only called when `run_client` is true.
173        let sui_client =
174            Arc::new(SuiClient::<SuiSdkClient>::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        // Validate approved actions that must be governace actions
199        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], // the first contract is bridge proxy
213            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        // If client is enabled, prepare client config
223        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            // in `prepare_for_eth` we check if this is None when `run_client` is true. Safe to unwrap here.
241            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<MeteredEthHttpProvier>>, 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        // If bridge chain id is Eth Mainent or Sepolia, we expect to see chain
286        // identifier to match accordingly.
287        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::<MeteredEthHttpProvier>::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<SuiClient<SuiSdkClient>>,
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        // If bridge chain id is Sui Mainent or Testnet, we expect to see chain
349        // identifier to match accordingly.
350        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                    // Minimum balance for gas object is 10 SUI
388                    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<SuiClient<SuiSdkClient>>,
419    pub eth_client: Arc<EthClient<MeteredEthHttpProvier>>,
420    /// A list of approved governance actions. Action in this list will be signed when requested by client.
421    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<SuiClient<SuiSdkClient>>,
430    pub eth_client: Arc<EthClient<MeteredEthHttpProvier>>,
431    pub db_path: PathBuf,
432    pub eth_contracts: Vec<EthAddress>,
433    // See `BridgeNodeConfig` for the explanation of following two fields.
434    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    // Only look at SUI coins specifically
456    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        // Take the first coin with a sufficient balance
470        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        // Only check a small number of coins before giving up
479        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}