devimint/
devfed.rs

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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use std::ops::Deref as _;
use std::sync::Arc;

use anyhow::Result;
use fedimint_core::envs::{is_env_var_set, FM_DEVIMINT_DISABLE_MODULE_LNV2_ENV};
use fedimint_core::runtime;
use fedimint_core::task::jit::{JitTry, JitTryAnyhow};
use fedimint_logging::LOG_DEVIMINT;
use tokio::join;
use tracing::debug;

use crate::external::{
    open_channel, open_channels_between_gateways, Bitcoind, Electrs, Esplora, Lightningd, Lnd,
    NamedGateway,
};
use crate::federation::{Client, Federation};
use crate::gatewayd::Gatewayd;
use crate::util::ProcessManager;
use crate::version_constants::{VERSION_0_4_0_ALPHA, VERSION_0_5_0_ALPHA};
use crate::LightningNode;

async fn spawn_drop<T>(t: T)
where
    T: Send + 'static,
{
    runtime::spawn("spawn_drop", async {
        drop(t);
    })
    .await
    .expect("drop panic");
}

#[derive(Clone)]
pub struct DevFed {
    pub bitcoind: Bitcoind,
    pub cln: Lightningd,
    pub lnd: Lnd,
    pub fed: Federation,
    pub gw_lnd: Gatewayd,
    pub gw_ldk: Option<Gatewayd>,
    pub electrs: Electrs,
    pub esplora: Esplora,
}

impl DevFed {
    pub async fn fast_terminate(self) {
        let Self {
            bitcoind,
            cln,
            lnd,
            fed,
            gw_lnd,
            gw_ldk,
            electrs,
            esplora,
        } = self;

        join!(
            spawn_drop(gw_lnd),
            spawn_drop(gw_ldk),
            spawn_drop(fed),
            spawn_drop(lnd),
            spawn_drop(cln),
            spawn_drop(esplora),
            spawn_drop(electrs),
            spawn_drop(bitcoind),
        );
    }
}
pub async fn dev_fed(process_mgr: &ProcessManager) -> Result<DevFed> {
    DevJitFed::new(process_mgr, false)?
        .to_dev_fed(process_mgr)
        .await
}

type JitArc<T> = JitTryAnyhow<Arc<T>>;

#[derive(Clone)]
pub struct DevJitFed {
    bitcoind: JitArc<Bitcoind>,
    cln: JitArc<Lightningd>,
    lnd: JitArc<Lnd>,
    fed: JitArc<Federation>,
    gw_lnd: JitArc<Gatewayd>,
    gw_ldk: JitArc<Option<Gatewayd>>,
    electrs: JitArc<Electrs>,
    esplora: JitArc<Esplora>,
    start_time: std::time::SystemTime,
    gw_lnd_registered: JitArc<()>,
    gw_ldk_connected: JitArc<()>,
    fed_epoch_generated: JitArc<()>,
    channel_opened: JitArc<()>,
}

impl DevJitFed {
    pub fn new(process_mgr: &ProcessManager, skip_setup: bool) -> Result<DevJitFed> {
        let fed_size = process_mgr.globals.FM_FED_SIZE;
        let offline_nodes = process_mgr.globals.FM_OFFLINE_NODES;
        anyhow::ensure!(
            fed_size > 3 * offline_nodes,
            "too many offline nodes ({offline_nodes}) to reach consensus"
        );
        let start_time = fedimint_core::time::now();

        debug!("Starting dev federation");

        let bitcoind = JitTry::new_try({
            let process_mgr = process_mgr.to_owned();
            move || async move { Ok(Arc::new(Bitcoind::new(&process_mgr, skip_setup).await?)) }
        });
        let cln = JitTry::new_try({
            let process_mgr = process_mgr.to_owned();
            let bitcoind = bitcoind.clone();
            || async move {
                Ok(Arc::new(
                    Lightningd::new(&process_mgr, bitcoind.get_try().await?.deref().clone())
                        .await?,
                ))
            }
        });
        let lnd = JitTry::new_try({
            let process_mgr = process_mgr.to_owned();
            let bitcoind = bitcoind.clone();
            || async move {
                Ok(Arc::new(
                    Lnd::new(&process_mgr, bitcoind.get_try().await?.deref().clone()).await?,
                ))
            }
        });
        let electrs = JitTryAnyhow::new_try({
            let process_mgr = process_mgr.to_owned();
            let bitcoind = bitcoind.clone();
            || async move {
                let bitcoind = bitcoind.get_try().await?.deref().clone();
                Ok(Arc::new(Electrs::new(&process_mgr, bitcoind).await?))
            }
        });
        let esplora = JitTryAnyhow::new_try({
            let process_mgr = process_mgr.to_owned();
            let bitcoind = bitcoind.clone();
            || async move {
                let bitcoind = bitcoind.get_try().await?.deref().clone();
                Ok(Arc::new(Esplora::new(&process_mgr, bitcoind).await?))
            }
        });

        let fed = JitTryAnyhow::new_try({
            let process_mgr = process_mgr.to_owned();
            let bitcoind = bitcoind.clone();
            move || async move {
                let bitcoind = bitcoind.get_try().await?.deref().clone();
                let mut fed = Federation::new(
                    &process_mgr,
                    bitcoind,
                    fed_size,
                    skip_setup,
                    "default".to_string(),
                )
                .await?;

                // Create a degraded federation if there are offline nodes
                fed.degrade_federation(&process_mgr).await?;

                Ok(Arc::new(fed))
            }
        });

        let gw_lnd = JitTryAnyhow::new_try({
            let process_mgr = process_mgr.to_owned();
            let lnd = lnd.clone();
            || async move {
                let lnd = lnd.get_try().await?.deref().clone();
                Ok(Arc::new(
                    Gatewayd::new(&process_mgr, LightningNode::Lnd(lnd)).await?,
                ))
            }
        });
        let gw_lnd_registered = JitTryAnyhow::new_try({
            let gw_lnd = gw_lnd.clone();
            let fed = fed.clone();
            move || async move {
                let gw_lnd = gw_lnd.get_try().await?.deref();
                let fed = fed.get_try().await?.deref();
                if !skip_setup {
                    gw_lnd.connect_fed(fed).await?;
                }
                Ok(Arc::new(()))
            }
        });
        let gw_ldk = JitTryAnyhow::new_try({
            let process_mgr = process_mgr.to_owned();
            move || async move {
                // TODO(support:v0.4.0): Only run LDK gateway when the federation supports LNv2
                let fedimintd_version = crate::util::FedimintdCmd::version_or_default().await;
                let gatewayd_version = crate::util::Gatewayd::version_or_default().await;
                if gatewayd_version >= *VERSION_0_5_0_ALPHA
                    && fedimintd_version >= *VERSION_0_5_0_ALPHA
                    // and lnv2 was not explicitly disabled
                    && !is_env_var_set(FM_DEVIMINT_DISABLE_MODULE_LNV2_ENV)
                {
                    Ok(Arc::new(Some(
                        Gatewayd::new(&process_mgr, LightningNode::Ldk).await?,
                    )))
                } else {
                    Ok(Arc::new(None))
                }
            }
        });
        let gw_ldk_connected = JitTryAnyhow::new_try({
            let gw_ldk = gw_ldk.clone();
            let fed = fed.clone();
            move || async move {
                let gw_ldk = gw_ldk.get_try().await?.deref();
                if let Some(gw_ldk) = gw_ldk {
                    let fed = fed.get_try().await?.deref();
                    if !skip_setup {
                        gw_ldk.connect_fed(fed).await?;
                    }
                }
                Ok(Arc::new(()))
            }
        });

        let channel_opened = JitTryAnyhow::new_try({
            let process_mgr = process_mgr.to_owned();
            let lnd = lnd.clone();
            let gw_lnd = gw_lnd.clone();
            let cln = cln.clone();
            let gw_ldk = gw_ldk.clone();
            let bitcoind = bitcoind.clone();
            || async move {
                // Note: We open new channel even if starting from existing state
                // as ports change on every start, and without this nodes will not find each
                // other.

                let gateway_cli_version = crate::util::GatewayCli::version_or_default().await;
                let gatewayd_version = crate::util::Gatewayd::version_or_default().await;
                let fedimintd_version = crate::util::FedimintdCmd::version_or_default().await;

                let bitcoind = bitcoind.get_try().await?.deref().clone();

                if gateway_cli_version <= *VERSION_0_4_0_ALPHA
                    || gatewayd_version <= *VERSION_0_4_0_ALPHA
                    || fedimintd_version <= *VERSION_0_4_0_ALPHA
                    || is_env_var_set(FM_DEVIMINT_DISABLE_MODULE_LNV2_ENV)
                {
                    let lnd = lnd.get_try().await?.deref().clone();
                    let cln = cln.get_try().await?.deref().clone();

                    open_channel(&process_mgr, &bitcoind, &cln, &lnd).await?;
                } else {
                    let gw_lnd = gw_lnd.get_try().await?.deref();
                    let gw_ldk = gw_ldk
                        .get_try()
                        .await?
                        .deref()
                        .as_ref()
                        .expect("GW LDK should be present");
                    let gateways: &[NamedGateway<'_>] = &[(gw_lnd, "LND"), (gw_ldk, "LDK")];
                    open_channels_between_gateways(&bitcoind, gateways).await?;

                    let lnd = lnd.get_try().await?.deref().clone();
                    let cln = cln.get_try().await?.deref().clone();
                    open_channel(&process_mgr, &bitcoind, &cln, &lnd).await?;
                }

                Ok(Arc::new(()))
            }
        });

        let fed_epoch_generated = JitTryAnyhow::new_try({
            let fed = fed.clone();
            move || async move {
                let fed = fed.get_try().await?.deref().clone();
                if !skip_setup {
                    fed.mine_then_wait_blocks_sync(10).await?;
                }
                Ok(Arc::new(()))
            }
        });

        Ok(DevJitFed {
            bitcoind,
            cln,
            lnd,
            fed,
            gw_lnd,
            gw_ldk,
            electrs,
            esplora,
            start_time,
            gw_lnd_registered,
            gw_ldk_connected,
            fed_epoch_generated,
            channel_opened,
        })
    }

    pub async fn electrs(&self) -> anyhow::Result<&Electrs> {
        Ok(self.electrs.get_try().await?.deref())
    }
    pub async fn esplora(&self) -> anyhow::Result<&Esplora> {
        Ok(self.esplora.get_try().await?.deref())
    }
    pub async fn cln(&self) -> anyhow::Result<&Lightningd> {
        Ok(self.cln.get_try().await?.deref())
    }
    pub async fn lnd(&self) -> anyhow::Result<&Lnd> {
        Ok(self.lnd.get_try().await?.deref())
    }
    pub async fn gw_lnd(&self) -> anyhow::Result<&Gatewayd> {
        Ok(self.gw_lnd.get_try().await?.deref())
    }
    pub async fn gw_lnd_registered(&self) -> anyhow::Result<&Gatewayd> {
        self.gw_lnd_registered.get_try().await?;
        Ok(self.gw_lnd.get_try().await?.deref())
    }
    pub async fn gw_ldk(&self) -> anyhow::Result<&Option<Gatewayd>> {
        Ok(self.gw_ldk.get_try().await?.deref())
    }
    pub async fn gw_ldk_connected(&self) -> anyhow::Result<&Option<Gatewayd>> {
        self.gw_ldk_connected.get_try().await?;
        Ok(self.gw_ldk.get_try().await?.deref())
    }
    pub async fn fed(&self) -> anyhow::Result<&Federation> {
        Ok(self.fed.get_try().await?.deref())
    }
    pub async fn bitcoind(&self) -> anyhow::Result<&Bitcoind> {
        Ok(self.bitcoind.get_try().await?.deref())
    }

    pub async fn internal_client(&self) -> anyhow::Result<Client> {
        Ok(self.fed().await?.internal_client().await?.clone())
    }

    /// Like [`Self::internal_client`] but will check and wait for a LN gateway
    /// to be registered
    pub async fn internal_client_gw_registered(&self) -> anyhow::Result<Client> {
        self.fed().await?.await_gateways_registered().await?;
        Ok(self.fed().await?.internal_client().await?.clone())
    }

    pub async fn finalize(&self, process_mgr: &ProcessManager) -> anyhow::Result<()> {
        let fed_size = process_mgr.globals.FM_FED_SIZE;
        let offline_nodes = process_mgr.globals.FM_OFFLINE_NODES;
        anyhow::ensure!(
            fed_size > 3 * offline_nodes,
            "too many offline nodes ({offline_nodes}) to reach consensus"
        );

        let _ = self.internal_client_gw_registered().await?;
        let _ = self.channel_opened.get_try().await?;
        let _ = self.gw_lnd_registered().await?;
        let _ = self.gw_ldk_connected().await?;
        let _ = self.cln().await?;
        let _ = self.lnd().await?;
        let _ = self.electrs().await?;
        let _ = self.esplora().await?;
        let _ = self.fed_epoch_generated.get_try().await?;

        debug!(
            target: LOG_DEVIMINT,
            fed_size,
            offline_nodes,
            elapsed_ms = %self.start_time.elapsed()?.as_millis(),
            "Dev federation ready",
        );
        Ok(())
    }

    pub async fn to_dev_fed(self, process_mgr: &ProcessManager) -> anyhow::Result<DevFed> {
        self.finalize(process_mgr).await?;
        Ok(DevFed {
            bitcoind: self.bitcoind().await?.to_owned(),
            cln: self.cln().await?.to_owned(),
            lnd: self.lnd().await?.to_owned(),
            fed: self.fed().await?.to_owned(),
            gw_lnd: self.gw_lnd().await?.to_owned(),
            gw_ldk: self.gw_ldk().await?.to_owned(),
            esplora: self.esplora().await?.to_owned(),
            electrs: self.electrs().await?.to_owned(),
        })
    }

    pub async fn fast_terminate(self) {
        let Self {
            bitcoind,
            cln,
            lnd,
            fed,
            gw_lnd,
            electrs,
            esplora,
            ..
        } = self;

        join!(
            spawn_drop(gw_lnd),
            spawn_drop(fed),
            spawn_drop(lnd),
            spawn_drop(cln),
            spawn_drop(esplora),
            spawn_drop(electrs),
            spawn_drop(bitcoind),
        );
    }
}