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
use std::io::Read;

use base64::prelude::*;

use crate::{
    lnd::{
        LndHodlInvoice, LndHodlInvoiceState, LndInfo, LndInvoice, LndInvoiceRequestBody,
        LndPaymentRequest, LndPaymentResponse,
    },
    LndWebsocket,
};
use reqwest::header::{HeaderMap, HeaderValue};
use tracing::info;

#[derive(Clone)]
pub struct LightningClient {
    url: &'static str,
    data_dir: &'static str,
    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?;
        info!("{}", response);
        Ok(())
    }
    pub async fn get_invoice(&self, amount: u64) -> anyhow::Result<LndInvoice> {
        let url = format!("https://{}/v1/invoices", self.url);
        let form = LndInvoiceRequestBody::new(amount.to_string());
        let response = self.client.post(&url).body(form.to_string());
        info!("{:?}", response);
        let response = response.send().await?;
        let response = response.json::<LndInvoice>().await?;
        Ok(response)
    }
    pub async fn invoice_channel(
        &self,
    ) -> anyhow::Result<LndWebsocket<LndPaymentResponse, LndPaymentRequest>> {
        let url = format!("wss://{}/v2/router/send?method=POST", self.url);
        let lnd_ws = LndWebsocket::<LndPaymentResponse, LndPaymentRequest>::new(
            self.url.to_string(),
            Self::macaroon(self.data_dir)?,
            url,
            10,
        )
        .await?;
        Ok(lnd_ws)
    }
    pub async fn subscribe_to_invoice(
        &self,
        r_hash_url_safe: String,
    ) -> anyhow::Result<LndWebsocket<LndHodlInvoiceState, String>> {
        let query = format!(
            "wss://{}/v2/invoices/subscribe/{}",
            self.url, r_hash_url_safe
        );
        let lnd_ws = LndWebsocket::<LndHodlInvoiceState, String>::new(
            self.url.to_string(),
            Self::macaroon(self.data_dir)?,
            query,
            3,
        )
        .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?;
        info!("{}", response);
        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?;
        info!("{}", _test);
        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, LightningAddress};
    use tracing::info;
    use tracing_test::traced_test;

    use super::LightningClient;
    #[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(100).await?;
        info!("{:?}", invoice);
        let mut subscription = client
            .subscribe_to_invoice(invoice.r_hash_url_safe())
            .await?;
        loop {
            match subscription.receiver.recv().await {
                Some(state) => {
                    info!("{:?}", state);
                    match state.state() {
                        HodlState::OPEN => {
                            client.cancel_htlc(invoice.r_hash_url_safe()).await?;
                        }
                        HodlState::CANCELED => {
                            break;
                        }
                        _ => {}
                    }
                }
                None => {
                    break;
                }
            }
        }
        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(state) = states.receiver.recv().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 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 = client
    //         .get_ln_url_invoice(10000, ln_address.to_string())
    //         .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 states = client
    //         .subscribe_to_invoice(pay_request.r_hash_url_safe()?)
    //         .await?;
    //     let pr = LndPaymentRequest::new(pay_request.pr.clone(), 10, 10.to_string(), false);
    //     let (pay_rx, pay_tx) = client.invoice_channel().await?;
    //     tokio::spawn(async move {
    //         info!("Sent payment request");
    //         loop {
    //             if pay_rx.is_closed() && pay_rx.is_empty() {
    //                 break;
    //             }
    //             info!("Waiting for pr state");
    //             match pay_rx.recv().await {
    //                 Ok(state) => {
    //                     match state.status() {
    //                         InvoicePaymentState::Succeeded => {
    //                             info!("Payment succeeded");
    //                             client.settle_htlc(state.preimage()).await.unwrap();
    //                             info!("Settled");
    //                         }
    //                         _ => {}
    //                     }
    //                 }
    //                 Err(e) => {
    //                     info!("{}", e);
    //                 }
    //             }
    //         }
    //     });
    //     let correct_state_c = correct_state.clone();
    //     loop {
    //         info!("Waiting for state");
    //         match states.recv().await {
    //             Ok(state) => {
    //                 info!("{:?}", state.state());
    //                 match state.state() {
    //                     HodlState::OPEN => {}
    //                     HodlState::ACCEPTED => {
    //                         pay_tx.send(pr.clone()).await.unwrap();
    //                         info!("Sent payment");
    //                     }
    //                     HodlState::SETTLED => {
    //                         info!("REALLY Settled");
    //                         *correct_state_c.lock().await = true;
    //                         break;
    //                     }
    //                     _ => {}
    //                 }
    //             }
    //             Err(e) => {
    //                 info!("{}", e);
    //                 break;
    //             }
    //         }
    //     }
    //     assert!(*correct_state.lock().await);
    //     Ok(())
    // }
}