lnurl/
blocking.rs

1//! LNURL by way of `ureq` HTTP client.
2#![allow(clippy::result_large_err)]
3
4use bitcoin::secp256k1::ecdsa::Signature;
5use bitcoin::secp256k1::PublicKey;
6use std::time::Duration;
7
8use ureq::{Agent, Proxy};
9
10use crate::channel::ChannelResponse;
11use crate::lnurl::LnUrl;
12use crate::pay::{LnURLPayInvoice, PayResponse};
13use crate::withdraw::WithdrawalResponse;
14use crate::{decode_ln_url_response_from_json, Builder, Error, LnUrlResponse, Response};
15
16#[derive(Debug, Clone)]
17pub struct BlockingClient {
18    agent: Agent,
19}
20
21impl BlockingClient {
22    /// build a blocking client from a [`Builder`]
23    pub fn from_builder(builder: Builder) -> Result<Self, Error> {
24        let mut agent_builder = ureq::AgentBuilder::new();
25
26        if let Some(timeout) = builder.timeout {
27            agent_builder = agent_builder.timeout(Duration::from_secs(timeout));
28        }
29
30        if let Some(proxy) = &builder.proxy {
31            agent_builder = agent_builder.proxy(Proxy::new(proxy).unwrap());
32        }
33
34        Ok(Self::from_agent(agent_builder.build()))
35    }
36
37    /// build a blocking client from an [`Agent`]
38    pub fn from_agent(agent: Agent) -> Self {
39        BlockingClient { agent }
40    }
41
42    pub fn make_request(&self, url: &str) -> Result<LnUrlResponse, Error> {
43        let resp = self.agent.get(url).call();
44
45        match resp {
46            Ok(resp) => {
47                let json: serde_json::Value = resp.into_json()?;
48                decode_ln_url_response_from_json(json)
49            }
50            Err(ureq::Error::Status(code, _)) => Err(Error::HttpResponse(code)),
51            Err(e) => Err(Error::Ureq(e)),
52        }
53    }
54
55    pub fn get_invoice(
56        &self,
57        pay: &PayResponse,
58        msats: u64,
59        zap_request: Option<String>,
60        comment: Option<&str>,
61    ) -> Result<LnURLPayInvoice, Error> {
62        // verify amount
63        if msats < pay.min_sendable || msats > pay.max_sendable {
64            return Err(Error::InvalidAmount);
65        }
66
67        // verify comment length
68        if let Some(comment) = comment {
69            if let Some(max_length) = pay.comment_allowed {
70                if comment.len() > max_length as usize {
71                    return Err(Error::InvalidComment);
72                }
73            }
74        }
75
76        let symbol = if pay.callback.contains('?') { "&" } else { "?" };
77
78        let url = match (zap_request, comment) {
79            (Some(_), Some(_)) => return Err(Error::InvalidComment),
80            (Some(zap_request), None) => format!(
81                "{}{}amount={}&nostr={}",
82                pay.callback, symbol, msats, zap_request
83            ),
84            (None, Some(comment)) => format!(
85                "{}{}amount={}&comment={}",
86                pay.callback, symbol, msats, comment
87            ),
88            (None, None) => format!("{}{}amount={}", pay.callback, symbol, msats),
89        };
90
91        let resp = self.agent.get(&url).call();
92
93        match resp {
94            Ok(resp) => {
95                let json: serde_json::Value = resp.into_json()?;
96                let result = serde_json::from_value::<LnURLPayInvoice>(json.clone());
97
98                match result {
99                    Ok(invoice) => Ok(invoice),
100                    Err(_) => {
101                        let response = serde_json::from_value::<Response>(json)?;
102                        match response {
103                            Response::Error { reason } => Err(Error::Other(reason)),
104                            Response::Ok { .. } => unreachable!("Ok response should be an invoice"),
105                        }
106                    }
107                }
108            }
109            Err(ureq::Error::Status(code, _)) => Err(Error::HttpResponse(code)),
110            Err(e) => Err(Error::Ureq(e)),
111        }
112    }
113
114    pub fn do_withdrawal(
115        &self,
116        withdrawal: &WithdrawalResponse,
117        invoice: &str,
118    ) -> Result<Response, Error> {
119        let symbol = if withdrawal.callback.contains('?') {
120            "&"
121        } else {
122            "?"
123        };
124
125        let url = format!(
126            "{}{}k1={}&pr={}",
127            withdrawal.callback, symbol, withdrawal.k1, invoice
128        );
129
130        let resp = self.agent.get(&url).call();
131
132        match resp {
133            Ok(resp) => Ok(resp.into_json()?),
134            Err(ureq::Error::Status(code, _)) => Err(Error::HttpResponse(code)),
135            Err(e) => Err(Error::Ureq(e)),
136        }
137    }
138
139    pub fn open_channel(
140        &self,
141        channel: &ChannelResponse,
142        node_pubkey: PublicKey,
143        private: bool,
144    ) -> Result<Response, Error> {
145        let symbol = if channel.callback.contains('?') {
146            "&"
147        } else {
148            "?"
149        };
150
151        let url = format!(
152            "{}{}k1={}&remoteid={}&private={}",
153            channel.callback,
154            symbol,
155            channel.k1,
156            node_pubkey,
157            private as i32 // 0 or 1
158        );
159
160        let resp = self.agent.get(&url).call();
161
162        match resp {
163            Ok(resp) => Ok(resp.into_json()?),
164            Err(ureq::Error::Status(code, _)) => Err(Error::HttpResponse(code)),
165            Err(e) => Err(Error::Ureq(e)),
166        }
167    }
168
169    pub fn lnurl_auth(
170        &self,
171        lnurl: LnUrl,
172        sig: Signature,
173        key: PublicKey,
174    ) -> Result<Response, Error> {
175        let url = format!("{}&sig={}&key={}", lnurl.url, sig, key);
176
177        let resp = self.agent.get(&url).call();
178
179        match resp {
180            Ok(resp) => Ok(resp.into_json()?),
181            Err(ureq::Error::Status(code, _)) => Err(Error::HttpResponse(code)),
182            Err(e) => Err(Error::Ureq(e)),
183        }
184    }
185}