1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
use async_trait::async_trait;
use cubist_config::{
    network::{CommonConfig, CredConfig, PolygonConfig},
    secret::SecretUrl,
};
use cubist_proxy::transformer::eth_creds::{build_wallets, EthProxyConfig};
use cubist_util::net::next_available_port;
use secrecy::ExposeSecret;
use std::net::SocketAddr;
use std::time::Duration;
use tempdir::TempDir;
use tracing::trace;

use crate::{
    config::Config,
    error::{Error, ProviderError, Result},
    proxy::Proxy,
    resource::{resource_for_current_machine, Downloadable},
};
use crate::{start_error, to_uri, UrlExt};

use tokio::process::{Child, Command};

use super::{eth_available, eth_fund_wallets, Provider, Server, WhileRunning};
use crate::tracing::{child_stdio, trace_stdout};

use ethers::prelude::*;
use ethers::providers;

const PROVIDER_NAME: &str = "polygon";
const BOR_DEFAULT_PORT: u16 = 9545;
const BOR_CHAIN_ID: u32 = 1337;

impl Config for PolygonConfig {
    fn name(&self) -> &str {
        PROVIDER_NAME
    }

    fn common(&self) -> CommonConfig {
        self.common.clone()
    }

    fn local_provider(&self) -> Result<Box<dyn Provider>> {
        assert!(
            self.common.url.is_loopback()?,
            "Cannot start node on remote machine."
        );
        let url = self.common.url.clone();
        let config = BorConfig {
            url,
            local_accounts: self.local_accounts.clone(),
        };
        let provider = BorProvider {
            exe: resource_for_current_machine("bor")?,
            config,
        };
        Ok(Box::new(provider))
    }
}

struct BorConfig {
    url: SecretUrl,
    local_accounts: Vec<CredConfig>,
}

pub struct BorProvider {
    exe: Downloadable,
    config: BorConfig,
}

struct BorServer {
    process: Child,
    bor_url: SecretUrl,
    data_dir: Option<TempDir>,
    proxy: Option<Proxy>,
    /// Accounts to fund when initializing the server.
    to_fund: Vec<H160>,
}

impl BorServer {
    /// Creates a provider for communicating with the server
    fn create_provider(&self) -> Result<providers::Provider<Http>> {
        let url = self.bor_url.load()?;
        let provider = providers::Provider::<Http>::try_from(url.expose_secret())
            .map_err(ProviderError::UrlParseError)?
            .interval(Duration::from_millis(10));
        Ok(provider)
    }

    /// Retrieves the developer account, i.e., an account that is pre-funded when the server is
    /// started
    async fn get_dev_account(&self, provider: &providers::Provider<Http>) -> Result<H160> {
        // The developer account is the only account that exists after starting the server
        let dev_account = provider.get_accounts().await?[0];
        let balance = provider.get_balance(dev_account, None).await.unwrap();
        tracing::debug!(
            "Dev account is {} with a balance of {}",
            dev_account,
            balance
        );
        Ok(dev_account)
    }
}

#[async_trait]
impl Server for BorServer {
    fn pid(&self) -> Option<u32> {
        self.process.id()
    }

    async fn kill(&mut self) -> Result<()> {
        let result = self.process.kill().await;
        trace!(
            "Killing bor server (pid = {:?}) returned {result:?}",
            self.process.id()
        );
        self.proxy.take();
        self.data_dir.take();
        Ok(())
    }

    async fn available(&mut self) -> Result<()> {
        let name = PROVIDER_NAME.to_string();
        self.process
            .while_running(eth_available(self.bor_url.clone(), name.clone()), name)
            .await??;
        Ok(())
    }

    async fn initialize(&mut self) -> Result<()> {
        let provider = self.create_provider()?;
        let dev_account = self.get_dev_account(&provider).await?;
        eth_fund_wallets(&provider, dev_account, &self.to_fund).await?;
        Ok(())
    }
}

impl Drop for BorServer {
    fn drop(&mut self) {
        let _ = self.kill();
    }
}

#[async_trait]
impl Provider for BorProvider {
    fn name(&self) -> &str {
        PROVIDER_NAME
    }

    fn bootstrap_eta(&self) -> Duration {
        Duration::from_secs(3)
    }

    fn url(&self) -> SecretUrl {
        self.config.url.clone()
    }

    fn preflight(&self) -> Result<Vec<&Downloadable>> {
        Ok(vec![&self.exe])
    }

    fn credentials(&self) -> Vec<CredConfig> {
        self.config.local_accounts.clone()
    }

    async fn start(&self) -> Result<Box<dyn Server>> {
        // setup before running
        let temp_dir = TempDir::new("bor-data")
            .map_err(|e| Error::FsError("Failed to create temp dir", "bor-data".into(), e))?;
        let data_dir = temp_dir.path();

        let proxy_port = self.config.url.port().unwrap_or(BOR_DEFAULT_PORT);
        let bor_port = next_available_port(proxy_port);

        let creds = self.credentials();
        let wallets: Vec<LocalWallet> = build_wallets(creds.iter())?;
        let to_fund: Vec<H160> = wallets.into_iter().map(|w| w.address()).collect();

        let mut child = Command::new(&self.exe.destination())
            .arg("--dev")
            .arg("--datadir")
            .arg(data_dir)
            .args([
                "--port",
                "30303",
                "--http",
                "--http.vhosts",
                "*",
                "--http.corsdomain",
                "*",
                "--http.port",
                &bor_port.to_string(),
            ])
            .args(["--http.api", "eth,net,web3,txpool"])
            .arg("--networkid")
            .arg(BOR_CHAIN_ID.to_string())
            .args(["--miner.gasprice", "0"])
            .args([
                "--metrics",
                "--pprof",
                "--pprof.port",
                "7071",
                "--nodiscover",
                "--maxpeers",
                "0",
            ])
            .stdout(child_stdio())
            .stderr(child_stdio())
            .kill_on_drop(true)
            .spawn()
            .map_err(|e| {
                start_error!(
                    "Unable to start bor server (at {}): {}",
                    &self.exe.destination().display(),
                    e
                )
            })?;

        trace_stdout("bor", &mut child).await;

        let bor_url_exposed = self
            .config
            .url
            .expose_url_and_update(None, Some(bor_port), None)?;
        Ok(Box::new(BorServer {
            process: child,
            data_dir: Some(temp_dir),
            proxy: Some(Proxy::new(
                SocketAddr::from(([127, 0, 0, 1], proxy_port)),
                &bor_url_exposed,
                EthProxyConfig {
                    onchain_uri: Some(to_uri(&bor_url_exposed)),
                    chain_id: BOR_CHAIN_ID,
                    creds,
                },
            )?),
            bor_url: bor_url_exposed.into(),
            to_fund,
        }))
    }
}

#[cfg(test)]
mod tests {
    use cubist_config::network::{MnemonicConfig, DEFAULT_ETH_DERIVATION_PATH_PREFIX};

    use super::*;

    #[test]
    pub fn test_proxy_creds() {
        let cred = CredConfig::Mnemonic(MnemonicConfig {
            seed: "test test test test test test test test test test test junk"
                .to_string()
                .into(),
            account_count: 5,
            derivation_path: DEFAULT_ETH_DERIVATION_PATH_PREFIX.to_string(),
        });
        let wallets = build_wallets([cred].iter()).unwrap();
        assert_eq!(5, wallets.len());
    }
}