bright_lightning/lnd/
rest_client.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
use std::io::Read;

use base64::prelude::*;

use crate::{
    lnd::{LndHodlInvoice, LndHodlInvoiceState, LndInfo, LndInvoice, LndInvoiceRequestBody},
    LndInvoiceList, LndWebsocket,
};
use reqwest::header::{HeaderMap, HeaderValue};

use super::{
    LndAddressProperty, LndListAddressesResponse, LndNewAddress, LndNextAddressRequest,
    LndPaymentInvoice, OnchainAddressType,
};

#[derive(Clone)]
pub struct LightningClient {
    url: &'static str,
    data_dir: &'static str,
    pub client: reqwest::Client,
}

impl LightningClient {
    pub async fn dud_server() -> anyhow::Result<Self> {
        let client = reqwest::Client::builder()
            .danger_accept_invalid_certs(true)
            .build()?;
        Ok(Self {
            url: "localhost:10009",
            client,
            data_dir: "",
        })
    }
    pub async fn new(url: &'static str, data_dir: &'static str) -> anyhow::Result<Self> {
        let mut default_header = HeaderMap::new();
        let macaroon = Self::macaroon(data_dir)?;
        let mut header_value = HeaderValue::from_str(&macaroon).unwrap();
        header_value.set_sensitive(true);
        default_header.insert("Grpc-Metadata-macaroon", header_value);
        default_header.insert("Accept", HeaderValue::from_static("application/json"));
        default_header.insert("Content-Type", HeaderValue::from_static("application/json"));
        let client = reqwest::Client::builder()
            .danger_accept_invalid_certs(true)
            .default_headers(default_header)
            .build()?;
        Ok(Self {
            url,
            client,
            data_dir,
        })
    }
    fn macaroon(data_dir: &'static str) -> anyhow::Result<String> {
        let mut macaroon = vec![];
        let mut file = std::fs::File::open(data_dir)?;
        file.read_to_end(&mut macaroon)?;
        Ok(macaroon.iter().map(|b| format!("{:02x}", b)).collect())
    }
    pub async fn get_info(&self) -> anyhow::Result<LndInfo> {
        let url = format!("https://{}/v1/getinfo", self.url);
        let response = self.client.get(&url).send().await?;
        let response = response.text().await?;
        LndInfo::try_from(response)
    }
    pub async fn channel_balance(&self) -> anyhow::Result<()> {
        let url = format!("https://{}/v1/balance/channels", self.url);
        let response = self.client.get(&url).send().await?;
        let _response = response.text().await?;
        Ok(())
    }
    pub async fn get_invoice(
        &self,
        form: LndInvoiceRequestBody,
    ) -> anyhow::Result<LndPaymentInvoice> {
        let url = format!("https://{}/v1/invoices", self.url);
        let response = self.client.post(&url).body(form.to_string());
        let response = response.send().await?;
        let response = response.json::<LndPaymentInvoice>().await?;
        Ok(response)
    }
    pub async fn list_invoices(&self) -> anyhow::Result<Vec<LndInvoice>> {
        let url = format!("https://{}/v1/invoices", self.url);
        let response = self.client.get(&url).send().await?;
        let response = response.json::<LndInvoiceList>().await?;
        Ok(response.invoices)
    }
    pub async fn new_onchain_address(
        &self,
        request: LndNextAddressRequest,
    ) -> anyhow::Result<LndNewAddress> {
        let url = format!("https://{}/v2/wallet/address/next", self.url);
        let request_str: String = request.into();
        let response = self.client.post(&url).body(request_str).send().await?;
        tracing::info!("{:?}", response);
        let response = response.json::<LndNewAddress>().await?;
        Ok(response)
    }
    pub async fn list_onchain_addresses(
        &self,
        account: &str,
        address_type: OnchainAddressType,
    ) -> anyhow::Result<Vec<LndAddressProperty>> {
        let url = format!("https://{}/v2/wallet/addresses", self.url);
        let response = self.client.get(&url).send().await?;
        let response = response
            .json::<LndListAddressesResponse>()
            .await?
            .find_addresses(account, address_type);
        Ok(response)
    }
    pub async fn invoice_channel(&self) -> anyhow::Result<LndWebsocket> {
        let url = format!("wss://{}/v2/router/send?method=POST", self.url);
        let lnd_ws =
            LndWebsocket::new(self.url.to_string(), Self::macaroon(self.data_dir)?, url).await?;
        Ok(lnd_ws)
    }
    pub async fn lookup_invoice(
        &self,
        r_hash_url_safe: String,
    ) -> anyhow::Result<LndHodlInvoiceState> {
        let query = format!(
            "https://{}/v2/invoices/lookup?payment_hash={}",
            self.url, r_hash_url_safe
        );
        let response = self.client.get(&query).send().await?;
        let response = response.json::<LndHodlInvoiceState>().await?;
        Ok(response)
    }
    pub async fn subscribe_to_invoice(
        &self,
        r_hash_url_safe: String,
    ) -> anyhow::Result<LndWebsocket> {
        let query = format!(
            "wss://{}/v2/invoices/subscribe/{}",
            self.url, r_hash_url_safe
        );
        let lnd_ws =
            LndWebsocket::new(self.url.to_string(), Self::macaroon(self.data_dir)?, query).await?;
        Ok(lnd_ws)
    }
    pub async fn get_hodl_invoice(
        &self,
        payment_hash: String,
        amount: u64,
    ) -> anyhow::Result<LndHodlInvoice> {
        let url = format!("https://{}/v2/invoices/hodl", self.url);

        let response = self
            .client
            .post(&url)
            .json(&serde_json::json!({ "value": amount, "hash": payment_hash }))
            .send()
            .await?;
        let response = response.text().await?;
        LndHodlInvoice::try_from(response)
    }
    pub async fn settle_htlc(&self, preimage: String) -> anyhow::Result<()> {
        let url = format!("https://{}/v2/invoices/settle", self.url);
        let hex_bytes = preimage.chars().collect::<Vec<char>>();
        let preimage = hex_bytes
            .chunks(2)
            .map(|chunk| {
                let s: String = chunk.iter().collect();
                u8::from_str_radix(&s, 16).unwrap()
            })
            .collect::<Vec<u8>>();
        let preimage = BASE64_URL_SAFE.encode(&preimage);
        let response = self
            .client
            .post(&url)
            .json(&serde_json::json!({ "preimage": preimage }))
            .send()
            .await?;
        let _test = response.text().await?;
        Ok(())
    }
    pub async fn cancel_htlc(&self, payment_hash: String) -> anyhow::Result<()> {
        let url = format!("https://{}/v2/invoices/cancel", self.url);
        let response = self
            .client
            .post(&url)
            .json(&serde_json::json!({ "payment_hash": payment_hash }))
            .send()
            .await?;
        response.text().await?;
        Ok(())
    }
}

#[cfg(test)]
mod test {

    use crate::{
        lnd::HodlState, InvoicePaymentState, LightningAddress, LndHodlInvoiceState, LndInvoice,
        LndInvoiceRequestBody, LndInvoiceState, LndNextAddressRequest, LndPaymentRequest,
        LndPaymentResponse, LndWebsocketMessage,
    };
    use futures_util::StreamExt;
    use tracing::{error, info};
    use tracing_test::traced_test;

    use super::LightningClient;
    #[tokio::test]
    #[traced_test]
    async fn next_onchain() -> anyhow::Result<()> {
        let client = LightningClient::new("lnd.illuminodes.com", "./admin.macaroon").await?;
        let invoices = client
            .new_onchain_address(LndNextAddressRequest::default())
            .await?;

        info!("{:?}", invoices);
        Ok(())
    }
    #[tokio::test]
    #[traced_test]
    async fn onchain_list() -> anyhow::Result<()> {
        let client = LightningClient::new("lnd.illuminodes.com", "./admin.macaroon").await?;
        let invoices = client
            .list_onchain_addresses("default", crate::OnchainAddressType::TaprootPubkey)
            .await?;
        info!("{:?}", invoices);
        Ok(())
    }

    #[tokio::test]
    #[traced_test]
    async fn test_invoice_list() -> anyhow::Result<()> {
        let client = LightningClient::new("lnd.illuminodes.com", "./admin.macaroon").await?;
        let invoices = client.list_invoices().await?;
        info!("{:?}", invoices);
        Ok(())
    }
    #[tokio::test]
    #[traced_test]
    async fn test_connection() -> anyhow::Result<()> {
        let client = LightningClient::new("lnd.illuminodes.com", "./admin.macaroon").await?;
        let invoice = client
            .get_invoice(LndInvoiceRequestBody {
                value: 1000.to_string(),
                memo: Some("Hello".to_string()),
                ..Default::default()
            })
            .await?;
        info!("{:?}", invoice);
        let mut subscription = client
            .subscribe_to_invoice(invoice.r_hash_url_safe())
            .await?;
        loop {
            match subscription.event_stream::<LndInvoice>().next().await {
                Some(LndWebsocketMessage::Response(state)) => {
                    info!("{:?}", state);
                    match state.state {
                        LndInvoiceState::Open => {
                            break;
                        }
                        LndInvoiceState::Canceled => {
                            break;
                        }
                        _ => {}
                    }
                }
                Some(LndWebsocketMessage::Error(e)) => {
                    tracing::error!("{}", e);
                    Err(anyhow::anyhow!("Error"))?;
                }
                Some(LndWebsocketMessage::Ping) => {
                    info!("Ping");
                }
                None => {
                    Err(anyhow::anyhow!("No state"))?;
                }
            }
        }
        Ok(())
    }
    #[tokio::test]
    #[traced_test]
    async fn get_hodl_invoice() -> anyhow::Result<()> {
        let client = LightningClient::new("lnd.illuminodes.com", "./admin.macaroon").await?;
        let ln_address = LightningAddress("42pupusas@blink.sv");
        let pay_request = ln_address.get_invoice(&client.client, 1000).await?;
        let _hodl_invoice = client.get_hodl_invoice(pay_request.r_hash()?, 100).await?;
        let mut states = client
            .subscribe_to_invoice(pay_request.r_hash_url_safe()?)
            .await?;
        let mut correct_state = false;
        while let Some(LndWebsocketMessage::Response(state)) =
            states.event_stream::<LndHodlInvoiceState>().next().await
        {
            info!("{:?}", state.state());
            match state.state() {
                HodlState::OPEN => {
                    client.cancel_htlc(pay_request.r_hash_url_safe()?).await?;
                }
                HodlState::CANCELED => {
                    correct_state = true;
                    break;
                }
                _ => {}
            }
        }
        assert!(correct_state);
        Ok(())
    }

    #[tokio::test]
    #[traced_test]
    async fn pay_invoice() -> anyhow::Result<()> {
        let client = LightningClient::new("lnd.illuminodes.com", "./admin.macaroon").await?;
        let ln_address = "42pupusas@blink.sv";
        let pay_request = LightningAddress(ln_address)
            .get_invoice(&client.client, 100000)
            .await?;
        let pr = LndPaymentRequest::new(pay_request.pr.clone(), 10, 10.to_string(), false);
        let mut lnd_ws = client.invoice_channel().await?;
        let mut receiver = lnd_ws.event_stream::<LndPaymentResponse>();
        lnd_ws.sender.send(pr.clone()).await.unwrap();
        while let Some(LndWebsocketMessage::Response(state)) = receiver.next().await {
            match state.status() {
                InvoicePaymentState::Initiaited => {
                    info!("Initiated");
                }
                InvoicePaymentState::InFlight => {
                    info!("InFlight");
                }
                InvoicePaymentState::Succeeded => {
                    info!("Succeeded");
                    break;
                }
                InvoicePaymentState::Failed => {
                    error!("Failed");
                    break;
                }
            }
        }
        Ok(())
    }
    #[tokio::test]
    #[traced_test]
    async fn settle_htlc() -> Result<(), anyhow::Error> {
        use std::sync::Arc;
        use tokio::sync::Mutex;
        let client = LightningClient::new("lnd.illuminodes.com", "./admin.macaroon").await?;
        let ln_address = "42pupusas@blink.sv";
        let pay_request = LightningAddress(ln_address)
            .get_invoice(&client.client, 100000)
            .await?;

        let hodl_invoice = client.get_hodl_invoice(pay_request.r_hash()?, 20).await?;
        info!("{:?}", hodl_invoice.payment_request());
        let correct_state = Arc::new(Mutex::new(false));
        let mut states = client
            .subscribe_to_invoice(hodl_invoice.r_hash_url_safe()?)
            .await?
            .event_stream::<LndHodlInvoiceState>();

        let pr = LndPaymentRequest::new(pay_request.pr.clone(), 1000, 10.to_string(), false);
        let mut lnd_ws = client.invoice_channel().await?;
        let mut receiver = lnd_ws.event_stream::<LndPaymentResponse>();
        tokio::spawn(async move {
            loop {
                match receiver.next().await {
                    Some(LndWebsocketMessage::Response(state)) => {
                        info!("Listening for payment state");
                        match state.status() {
                            InvoicePaymentState::Initiaited => {
                                info!("Initiated");
                            }
                            InvoicePaymentState::InFlight => {
                                info!("InFlight");
                            }
                            InvoicePaymentState::Succeeded => {
                                client.settle_htlc(state.preimage()).await.unwrap();
                                break;
                            }
                            InvoicePaymentState::Failed => {
                                error!("Failed");
                            }
                        }
                    }
                    others => {
                        info!("{:?}", others);
                    }
                }
            }
        });
        let correct_state_c = correct_state.clone();
        loop {
            info!("Waiting for state");
            match states.next().await {
                Some(LndWebsocketMessage::Response(state)) => match state.state() {
                    HodlState::OPEN => {
                        info!("Open");
                    }
                    HodlState::ACCEPTED => {
                        lnd_ws.sender.send(pr.clone()).await.unwrap();
                        info!("Sent payment");
                    }
                    HodlState::SETTLED => {
                        info!("REALLY Settled");
                        *correct_state_c.lock().await = true;
                        break;
                    }
                    _ => {}
                },
                _ => {}
            }
        }
        assert!(*correct_state.lock().await);
        Ok(())
    }
}