devimint/
gatewayd.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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
use std::collections::HashMap;
use std::ops::ControlFlow;
use std::path::PathBuf;
use std::str::FromStr;

use anyhow::{anyhow, Context, Result};
use esplora_client::Txid;
use fedimint_core::config::FederationId;
use fedimint_core::envs::{is_env_var_set, FM_DEVIMINT_DISABLE_MODULE_LNV2_ENV};
use fedimint_core::secp256k1::PublicKey;
use fedimint_core::util::{backoff_util, retry};
use fedimint_core::{Amount, BitcoinAmountOrAll};
use fedimint_ln_server::common::lightning_invoice::Bolt11Invoice;
use fedimint_lnv2_common::gateway_api::PaymentFee;
use fedimint_testing::gateway::LightningNodeType;
use ln_gateway::envs::FM_GATEWAY_LIGHTNING_MODULE_MODE_ENV;
use ln_gateway::lightning::ChannelInfo;
use ln_gateway::rpc::{GatewayBalances, MnemonicResponse, V1_API_ENDPOINT};
use tracing::info;

use crate::cmd;
use crate::envs::{FM_GATEWAY_API_ADDR_ENV, FM_GATEWAY_DATA_DIR_ENV, FM_GATEWAY_LISTEN_ADDR_ENV};
use crate::external::{Bitcoind, LightningNode};
use crate::federation::Federation;
use crate::util::{poll, Command, ProcessHandle, ProcessManager};
use crate::vars::utf8;
use crate::version_constants::{VERSION_0_4_0_ALPHA, VERSION_0_5_0_ALPHA, VERSION_0_6_0_ALPHA};

#[derive(Clone)]
pub struct Gatewayd {
    pub(crate) process: ProcessHandle,
    pub ln: Option<LightningNode>,
    pub addr: String,
    pub(crate) lightning_node_addr: String,
}

impl Gatewayd {
    pub async fn new(process_mgr: &ProcessManager, ln: LightningNode) -> Result<Self> {
        let ln_name = ln.name();
        let test_dir = &process_mgr.globals.FM_TEST_DIR;

        let port = match ln {
            LightningNode::Lnd(_) => process_mgr.globals.FM_PORT_GW_LND,
            LightningNode::Ldk => process_mgr.globals.FM_PORT_GW_LDK,
        };
        let addr = format!("http://127.0.0.1:{port}/{V1_API_ENDPOINT}");

        let lightning_node_port = match ln {
            LightningNode::Lnd(_) => process_mgr.globals.FM_PORT_LND_LISTEN,
            LightningNode::Ldk => process_mgr.globals.FM_PORT_LDK,
        };
        let lightning_node_addr = format!("127.0.0.1:{lightning_node_port}");

        let mut gateway_env: HashMap<String, String> = HashMap::from_iter([
            (
                FM_GATEWAY_DATA_DIR_ENV.to_owned(),
                format!("{}/{ln_name}", utf8(test_dir)),
            ),
            (
                FM_GATEWAY_LISTEN_ADDR_ENV.to_owned(),
                format!("127.0.0.1:{port}"),
            ),
            (FM_GATEWAY_API_ADDR_ENV.to_owned(), addr.clone()),
        ]);
        // TODO(support:v0.4.0): Run the gateway in LNv1 mode only before v0.5.0 because
        // that is the only module it supported.
        let fedimintd_version = crate::util::FedimintdCmd::version_or_default().await;
        if fedimintd_version < *VERSION_0_5_0_ALPHA
            || is_env_var_set(FM_DEVIMINT_DISABLE_MODULE_LNV2_ENV)
        {
            gateway_env.insert(
                FM_GATEWAY_LIGHTNING_MODULE_MODE_ENV.to_owned(),
                "LNv1".to_string(),
            );
        }
        let process = process_mgr
            .spawn_daemon(
                &format!("gatewayd-{ln_name}"),
                cmd!(crate::util::Gatewayd, ln_name).envs(gateway_env),
            )
            .await?;

        let gatewayd = Self {
            ln: Some(ln),
            process,
            addr,
            lightning_node_addr,
        };
        poll(
            "waiting for gateway to be ready to respond to rpc",
            || async { gatewayd.gateway_id().await.map_err(ControlFlow::Continue) },
        )
        .await?;
        Ok(gatewayd)
    }

    pub fn ln_type(&self) -> LightningNodeType {
        self.ln
            .as_ref()
            .expect("Gatewayd has no lightning node type")
            .name()
    }

    pub async fn terminate(self) -> Result<()> {
        self.process.terminate().await
    }

    pub fn set_lightning_node(&mut self, ln_node: LightningNode) {
        self.ln = Some(ln_node);
    }

    pub async fn stop_lightning_node(&mut self) -> Result<()> {
        info!("Stopping lightning node");
        match self.ln.take() {
            Some(LightningNode::Lnd(lnd)) => lnd.terminate().await,
            Some(LightningNode::Ldk) => {
                // This is not implemented because the LDK node lives in
                // the gateway process and cannot be stopped independently.
                unimplemented!("LDK node termination not implemented")
            }
            None => Err(anyhow!("Cannot stop an already stopped Lightning Node")),
        }
    }

    /// Restarts the gateway using the provided `bin_path`, which is useful for
    /// testing upgrades.
    pub async fn restart_with_bin(
        &mut self,
        process_mgr: &ProcessManager,
        gatewayd_path: &PathBuf,
        gateway_cli_path: &PathBuf,
    ) -> Result<()> {
        let ln = self
            .ln
            .as_ref()
            .expect("Lightning Node should exist")
            .clone();

        self.process.terminate().await?;
        std::env::set_var("FM_GATEWAYD_BASE_EXECUTABLE", gatewayd_path);
        std::env::set_var("FM_GATEWAY_CLI_BASE_EXECUTABLE", gateway_cli_path);

        let new_ln = ln;
        let new_gw = Self::new(process_mgr, new_ln.clone()).await?;
        self.process = new_gw.process;
        self.set_lightning_node(new_ln);
        let gatewayd_version = crate::util::Gatewayd::version_or_default().await;
        let gateway_cli_version = crate::util::GatewayCli::version_or_default().await;
        info!(
            ?gatewayd_version,
            ?gateway_cli_version,
            "upgraded gatewayd and gateway-cli"
        );
        Ok(())
    }

    pub fn cmd(&self) -> Command {
        cmd!(
            crate::util::get_gateway_cli_path(),
            "--rpcpassword=theresnosecondbest",
            "-a",
            &self.addr
        )
    }

    pub async fn get_info(&self) -> Result<serde_json::Value> {
        retry(
            "Getting gateway info via gateway-cli info",
            backoff_util::aggressive_backoff(),
            || async { cmd!(self, "info").out_json().await },
        )
        .await
        .context("Getting gateway info via gateway-cli info")
    }

    pub async fn gateway_id(&self) -> Result<String> {
        let info = self.get_info().await?;
        let gateway_id = info["gateway_id"]
            .as_str()
            .context("gateway_id must be a string")?
            .to_owned();
        Ok(gateway_id)
    }

    pub async fn lightning_pubkey(&self) -> Result<PublicKey> {
        let info = self.get_info().await?;
        let lightning_pub_key = info["lightning_pub_key"]
            .as_str()
            .context("lightning_pub_key must be a string")?
            .to_owned();
        Ok(lightning_pub_key.parse()?)
    }

    pub async fn connect_fed(&self, fed: &Federation) -> Result<()> {
        let invite_code = fed.invite_code()?;
        poll("gateway connect-fed", || async {
            cmd!(self, "connect-fed", invite_code.clone())
                .run()
                .await
                .map_err(ControlFlow::Continue)?;
            Ok(())
        })
        .await?;
        Ok(())
    }

    pub async fn recover_fed(&self, fed: &Federation) -> Result<()> {
        let federation_id = fed.calculate_federation_id();
        let invite_code = fed.invite_code()?;
        info!("Recovering {federation_id}...");
        poll("gateway connect-fed --recover=true", || async {
            cmd!(self, "connect-fed", invite_code.clone(), "--recover=true")
                .run()
                .await
                .map_err(ControlFlow::Continue)?;
            Ok(())
        })
        .await?;
        Ok(())
    }

    pub async fn backup_to_fed(&self, fed: &Federation) -> Result<()> {
        let federation_id = fed.calculate_federation_id();
        cmd!(self, "ecash", "backup", "--federation-id", federation_id)
            .run()
            .await?;
        Ok(())
    }

    pub fn lightning_node_type(&self) -> LightningNodeType {
        self.ln
            .as_ref()
            .expect("Gateway has no lightning node")
            .name()
    }

    pub async fn get_pegin_addr(&self, fed_id: &str) -> Result<String> {
        let gateway_cli_version = crate::util::GatewayCli::version_or_default().await;

        // TODO(support:v0.4): `ecash pegin` was introduced in v0.5.0
        // see: https://github.com/fedimint/fedimint/pull/6270
        let address = if gateway_cli_version < *VERSION_0_5_0_ALPHA {
            cmd!(self, "address", "--federation-id={fed_id}")
                .out_json()
                .await?
                .as_str()
                .context("address must be a string")?
                .to_owned()
        } else {
            cmd!(self, "ecash", "pegin", "--federation-id={fed_id}")
                .out_json()
                .await?
                .as_str()
                .context("address must be a string")?
                .to_owned()
        };
        Ok(address)
    }

    pub async fn get_ln_onchain_address(&self) -> Result<String> {
        let gateway_cli_version = crate::util::GatewayCli::version_or_default().await;
        let address = if gateway_cli_version < *VERSION_0_5_0_ALPHA {
            cmd!(self, "lightning", "get-funding-address")
                .out_string()
                .await?
        } else {
            cmd!(self, "onchain", "address").out_string().await?
        };

        Ok(address)
    }

    pub async fn get_mnemonic(&self) -> Result<MnemonicResponse> {
        let value = retry(
            "Getting gateway mnemonic",
            backoff_util::aggressive_backoff(),
            || async { cmd!(self, "seed").out_json().await },
        )
        .await
        .context("Getting gateway mnemonic")?;

        Ok(serde_json::from_value(value)?)
    }

    pub async fn leave_federation(&self, federation_id: FederationId) -> Result<()> {
        cmd!(self, "leave-fed", "--federation-id", federation_id)
            .run()
            .await?;
        Ok(())
    }

    pub async fn create_invoice(&self, amount_msats: u64) -> Result<Bolt11Invoice> {
        Ok(Bolt11Invoice::from_str(
            &cmd!(self, "lightning", "create-invoice", amount_msats)
                .out_string()
                .await?,
        )?)
    }

    pub async fn pay_invoice(&self, invoice: Bolt11Invoice) -> Result<()> {
        cmd!(self, "lightning", "pay-invoice", invoice.to_string())
            .run()
            .await?;

        Ok(())
    }

    pub async fn send_ecash(&self, federation_id: String, amount_msats: u64) -> Result<String> {
        let value = cmd!(
            self,
            "ecash",
            "send",
            "--federation-id",
            federation_id,
            amount_msats
        )
        .out_json()
        .await?;
        let ecash: String = serde_json::from_value(
            value
                .get("notes")
                .expect("notes key does not exist")
                .clone(),
        )?;
        Ok(ecash)
    }

    pub async fn receive_ecash(&self, ecash: String) -> Result<()> {
        cmd!(self, "ecash", "receive", "--notes", ecash)
            .run()
            .await?;
        Ok(())
    }

    pub async fn get_balances(&self) -> Result<GatewayBalances> {
        let value = cmd!(self, "get-balances").out_json().await?;
        Ok(serde_json::from_value(value)?)
    }

    pub async fn ecash_balance(&self, federation_id: String) -> anyhow::Result<u64> {
        let federation_id = FederationId::from_str(&federation_id)?;
        let gateway_cli_version = crate::util::GatewayCli::version_or_default().await;
        // TODO(support:v0.4): `get_balances` was introduced in v0.5.0
        // see: https://github.com/fedimint/fedimint/pull/5823
        if gateway_cli_version < *VERSION_0_5_0_ALPHA {
            let ecash_balance = cmd!(self, "balance", "--federation-id={federation_id}",)
                .out_json()
                .await?
                .as_u64()
                .unwrap();
            Ok(ecash_balance)
        } else {
            let balances = self.get_balances().await?;
            let ecash_balance = balances
                .ecash_balances
                .into_iter()
                .find(|info| info.federation_id == federation_id)
                .ok_or(anyhow::anyhow!("Gateway is not joined to federation"))?
                .ecash_balance_msats
                .msats;
            Ok(ecash_balance)
        }
    }

    pub async fn send_onchain(
        &self,
        bitcoind: &Bitcoind,
        amount: BitcoinAmountOrAll,
        fee_rate: u64,
    ) -> Result<()> {
        let withdraw_address = bitcoind.get_new_address().await?;
        let value = cmd!(
            self,
            "onchain",
            "send",
            "--address",
            withdraw_address,
            "--amount",
            amount,
            "--fee-rate-sats-per-vbyte",
            fee_rate
        )
        .out_json()
        .await?;
        let txid: bitcoin::Txid = serde_json::from_value(value)?;
        bitcoind.mine_blocks(21).await?;
        let block_height = bitcoind.get_block_count().await? - 1;
        bitcoind.poll_get_transaction(txid).await?;
        self.wait_for_block_height(block_height).await?;
        Ok(())
    }

    pub async fn close_all_channels(&self, bitcoind: Bitcoind) -> Result<()> {
        let channels = self.list_active_channels().await?;
        for chan in channels {
            let remote_pubkey = chan.remote_pubkey;
            cmd!(
                self,
                "lightning",
                "close-channels-with-peer",
                "--pubkey",
                remote_pubkey
            )
            .run()
            .await?;
        }
        bitcoind.mine_blocks(50).await?;
        let block_height = bitcoind.get_block_count().await? - 1;
        self.wait_for_block_height(block_height).await?;

        Ok(())
    }

    /// Open a channel with the gateway's lightning node.
    /// Returns the txid of the funding transaction if the gateway is a new
    /// enough version to return it. Otherwise, returns `None`.
    ///
    /// TODO(support:v0.5): Remove the `Option<Txid>` return type and just
    /// return `Txid`.
    pub async fn open_channel(
        &self,
        gw: &Gatewayd,
        channel_size_sats: u64,
        push_amount_sats: Option<u64>,
    ) -> Result<Option<Txid>> {
        let pubkey = gw.lightning_pubkey().await?;

        let mut command = cmd!(
            self,
            "lightning",
            "open-channel",
            "--pubkey",
            pubkey,
            "--host",
            gw.lightning_node_addr,
            "--channel-size-sats",
            channel_size_sats,
            "--push-amount-sats",
            push_amount_sats.unwrap_or(0)
        );

        let gatewayd_version = crate::util::Gatewayd::version_or_default().await;
        if gatewayd_version < *VERSION_0_5_0_ALPHA {
            command.run().await?;

            Ok(None)
        } else {
            Ok(Some(Txid::from_str(&command.out_string().await?)?))
        }
    }

    pub async fn list_active_channels(&self) -> Result<Vec<ChannelInfo>> {
        let channels = cmd!(self, "lightning", "list-active-channels")
            .out_json()
            .await?;
        let channels = channels
            .as_array()
            .context("channels must be an array")?
            .iter()
            .map(|channel| {
                let remote_pubkey = channel["remote_pubkey"]
                    .as_str()
                    .context("remote_pubkey must be a string")?
                    .to_owned();
                let channel_size_sats = channel["channel_size_sats"]
                    .as_u64()
                    .context("channel_size_sats must be a u64")?;
                let outbound_liquidity_sats = channel["outbound_liquidity_sats"]
                    .as_u64()
                    .context("outbound_liquidity_sats must be a u64")?;
                let inbound_liquidity_sats = channel["inbound_liquidity_sats"]
                    .as_u64()
                    .context("inbound_liquidity_sats must be a u64")?;
                let short_channel_id = channel["short_channel_id"]
                    .as_u64()
                    .context("short_channel_id must be a u64")?;
                Ok(ChannelInfo {
                    remote_pubkey: remote_pubkey
                        .parse()
                        .expect("Lightning node returned invalid remote channel pubkey"),
                    channel_size_sats,
                    outbound_liquidity_sats,
                    inbound_liquidity_sats,
                    short_channel_id,
                })
            })
            .collect::<Result<Vec<ChannelInfo>>>()?;
        Ok(channels)
    }

    pub async fn wait_for_block_height(&self, target_block_height: u64) -> Result<()> {
        poll("waiting for block height", || async {
            let info = self.get_info().await.map_err(ControlFlow::Continue)?;
            let value = info.get("block_height");
            if let Some(height) = value {
                let block_height: Option<u32> = serde_json::from_value(height.clone())
                    .context("Could not parse block height")
                    .map_err(ControlFlow::Continue)?;
                let Some(block_height) = block_height else {
                    return Err(ControlFlow::Continue(anyhow!("Not synced any blocks yet")));
                };
                if block_height >= target_block_height as u32 {
                    return Ok(());
                }
            }
            Err(ControlFlow::Continue(anyhow!("Not synced to block")))
        })
        .await?;
        Ok(())
    }

    pub async fn get_lightning_fee(&self, fed_id: String) -> Result<PaymentFee> {
        let gatewayd_version = crate::util::Gatewayd::version_or_default().await;
        let (fee_key, base_key, ppm_key) = if gatewayd_version >= *VERSION_0_6_0_ALPHA {
            ("lightning_fee", "base", "parts_per_million")
        } else {
            ("routing_fees", "base_msat", "proportional_millionths")
        };

        let info_value = self.get_info().await?;
        let federations = info_value["federations"]
            .as_array()
            .expect("federations is an array");

        let fed = federations
            .iter()
            .find(|fed| {
                serde_json::from_value::<String>(fed["federation_id"].clone())
                    .expect("could not deserialize federation_id")
                    == fed_id
            })
            .ok_or_else(|| anyhow!("Federation not found"))?;

        let lightning_fee = if gatewayd_version >= *VERSION_0_6_0_ALPHA {
            fed["config"][fee_key].clone()
        } else {
            fed[fee_key].clone()
        };

        let base: Amount = serde_json::from_value(lightning_fee[base_key].clone())
            .map_err(|e| anyhow!("Couldnt parse base: {}", e))?;
        let parts_per_million: u64 = serde_json::from_value(lightning_fee[ppm_key].clone())
            .map_err(|e| anyhow!("Couldnt parse parts_per_million: {}", e))?;

        Ok(PaymentFee {
            base,
            parts_per_million,
        })
    }

    pub async fn set_federation_routing_fee(
        &self,
        fed_id: String,
        base: u64,
        ppm: u64,
    ) -> Result<()> {
        let gatewayd_version = crate::util::Gatewayd::version_or_default().await;
        if gatewayd_version < *VERSION_0_4_0_ALPHA {
            let fees = format!("{base},{ppm}");
            cmd!(self, "set-configuration", "--routing-fees", fees)
                .run()
                .await?;
        } else if gatewayd_version >= *VERSION_0_4_0_ALPHA
            && gatewayd_version < *VERSION_0_6_0_ALPHA
        {
            let new_fed_routing_fees = format!("{fed_id},{base},{ppm}");
            cmd!(
                self,
                "set-configuration",
                "--per-federation-routing-fees",
                new_fed_routing_fees
            )
            .run()
            .await?;
        } else {
            cmd!(
                self,
                "cfg",
                "set-fees",
                "--federation-id",
                fed_id,
                "--ln-base",
                base,
                "--ln-ppm",
                ppm
            )
            .run()
            .await?;
        }

        Ok(())
    }

    pub async fn set_federation_transaction_fee(
        &self,
        fed_id: String,
        base: u64,
        ppm: u64,
    ) -> Result<()> {
        let gatewayd_version = crate::util::Gatewayd::version_or_default().await;
        if gatewayd_version >= *VERSION_0_6_0_ALPHA {
            cmd!(
                self,
                "cfg",
                "set-fees",
                "--federation-id",
                fed_id,
                "--tx-base",
                base,
                "--tx-ppm",
                ppm
            )
            .run()
            .await?;
        }

        Ok(())
    }
}