Skip to main content

cosmic_applet_avestruz/nostr/
zap.rs

1// SPDX-License-Identifier: MIT
2
3//! Zapping a note (NIP-57): asking its author's Lightning address for an
4//! invoice that, once paid, their wallet service announces as a zap.
5//!
6//! It takes two requests over `https` (LNURL-pay, LUD-06 and LUD-16). The
7//! first asks the address what it accepts: how little, how much, and
8//! whether it knows about zaps. The second asks for an invoice of an amount,
9//! and carries a signed *zap request* naming the note and the relays the
10//! receipt should go to. Paying the invoice is left to a wallet: the invoice
11//! is all this client produces.
12//!
13//! Everything the address answers is somebody else's word. The invoice is
14//! only shown if it asks for the amount that was chosen.
15
16use nostr_sdk::prelude::{
17    Event, EventBuilder, EventId, FinalizeEvent, IntoEventBuilder, Keys, PublicKey, RelayUrl, Url, ZapRequestData,
18};
19
20use crate::http;
21use crate::nostr::account::{SignError, Signer};
22
23/// How long what a Lightning address answers may be. Real answers are a few
24/// hundred bytes, and an invoice a few hundred more.
25const MAX_ANSWER_BYTES: usize = 64 * 1024;
26
27/// Why there is no invoice.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub enum ZapError {
30    /// What the profile gives as a Lightning address is not one.
31    BadAddress,
32    /// The address did not answer, or not with what LNURL-pay says it should.
33    Unreachable(String),
34    /// The address answered that it won't, and why.
35    Refused(String),
36    /// The amount is outside what the address accepts, in sats.
37    OutOfRange { min: u64, max: u64 },
38    /// The invoice that came back is not for the amount asked.
39    WrongAmount,
40    /// The zap request could not be signed.
41    Sign(SignError),
42}
43
44/// What a Lightning address accepts.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct PayInfo {
47    /// Where an invoice is asked for.
48    callback: Url,
49    /// The least and the most it takes at once, in millisats.
50    min_millisats: u64,
51    max_millisats: u64,
52    /// The key its receipts are signed with, if it does zaps at all.
53    zapper: Option<PublicKey>,
54    /// How long a comment sent with a plain payment may be, in characters.
55    comment_chars: usize,
56}
57
58/// An invoice to pay.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct Invoice {
61    /// The invoice itself (BOLT 11).
62    pub bolt11: String,
63    /// What it asks for, in sats.
64    pub sats: u64,
65    /// Whether paying it is a zap: announced by the wallet service, and
66    /// counted under the note. If not, it is a payment and nothing more.
67    pub is_zap: bool,
68}
69
70/// Who a zap is from.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum Zapper {
73    /// The account, which signs the request.
74    Account(PublicKey),
75    /// Nobody in particular: the request is signed with a key made for it
76    /// and thrown away.
77    Anonymous,
78}
79
80/// What a Lightning invoice asks for, in millisats, read from the amount
81/// in its human-readable part: `lnbc2500u1…` is 2500 micro-bitcoin. `None`
82/// for an invoice that names no amount, or isn't one.
83pub(crate) fn invoice_millisats(invoice: &str) -> Option<u64> {
84    let invoice = invoice.to_ascii_lowercase();
85    // The data part has no `1` in it, so the last one ends the first part.
86    let (readable, _) = invoice.rsplit_once('1')?;
87    let amount = readable.strip_prefix("ln")?.trim_start_matches(|c: char| c.is_ascii_alphabetic());
88    let (digits, unit) = match amount.char_indices().find(|(_, c)| !c.is_ascii_digit()) {
89        Some((at, _)) => amount.split_at(at),
90        None => (amount, ""),
91    };
92    let value: u64 = digits.parse().ok()?;
93    // One bitcoin is 10^11 millisats.
94    match unit {
95        "" => value.checked_mul(100_000_000_000),
96        "m" => value.checked_mul(100_000_000),
97        "u" => value.checked_mul(100_000),
98        "n" => value.checked_mul(100),
99        "p" => Some(value / 10),
100        _ => None,
101    }
102}
103
104/// Where the Lightning address `name@domain` is asked what it accepts
105/// (LUD-16). `None` if it isn't an address.
106fn pay_info_url(address: &str) -> Option<Url> {
107    let (name, domain) = address.trim().split_once('@')?;
108    let name = name.to_ascii_lowercase();
109    let is_name = !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || "-_.+".contains(c));
110    let path = format!("/.well-known/lnurlp/{name}");
111    let url = Url::parse(&format!("https://{domain}{path}")).ok()?;
112    // Whatever stood for the domain was only a domain: nothing in it went
113    // into the path, the query, or before an `@` of its own.
114    let only_a_domain = url.path() == path && url.query().is_none() && url.fragment().is_none() && url.username().is_empty();
115    (is_name && only_a_domain).then_some(url)
116}
117
118/// The JSON object in `answer`, unless it is LNURL's way of saying no:
119/// `{"status": "ERROR", "reason": "…"}`.
120fn parse_answer(answer: &[u8]) -> Result<serde_json::Value, ZapError> {
121    let value: serde_json::Value = serde_json::from_slice(answer).map_err(|e| ZapError::Unreachable(e.to_string()))?;
122    if value.get("status").and_then(serde_json::Value::as_str).is_some_and(|status| status.eq_ignore_ascii_case("error")) {
123        let reason = value.get("reason").and_then(serde_json::Value::as_str).unwrap_or_default();
124        return Err(ZapError::Refused(reason.to_string()));
125    }
126    Ok(value)
127}
128
129/// What a Lightning address accepts, by its answer to the first request.
130fn parse_pay_info(answer: &[u8]) -> Result<PayInfo, ZapError> {
131    let value = parse_answer(answer)?;
132    let missing = |what: &str| ZapError::Unreachable(format!("the answer has no usable `{what}`"));
133    let text = |field: &str| value.get(field).and_then(serde_json::Value::as_str);
134    let number = |field: &str| value.get(field).and_then(serde_json::Value::as_u64);
135
136    if text("tag") != Some("payRequest") {
137        return Err(missing("tag"));
138    }
139    let callback = text("callback")
140        .and_then(|callback| Url::parse(callback).ok())
141        .filter(|url| url.scheme() == "https")
142        .ok_or(missing("callback"))?;
143    let (min_millisats, max_millisats) =
144        (number("minSendable").ok_or(missing("minSendable"))?, number("maxSendable").ok_or(missing("maxSendable"))?);
145    let allows_nostr = value.get("allowsNostr").and_then(serde_json::Value::as_bool).unwrap_or(false);
146    let zapper = text("nostrPubkey").filter(|_| allows_nostr).and_then(|key| PublicKey::from_hex(key).ok());
147    let comment_chars = number("commentAllowed").map_or(0, |chars| usize::try_from(chars).unwrap_or(usize::MAX));
148    Ok(PayInfo { callback, min_millisats, max_millisats, zapper, comment_chars })
149}
150
151/// The zap request for `millisats` to the author of `note`, yet to be
152/// signed: what the wallet service copies into its receipt, which is to go
153/// to `relays`.
154fn zap_request(recipient: PublicKey, note: EventId, millisats: u64, comment: &str, relays: Vec<RelayUrl>) -> EventBuilder {
155    ZapRequestData::new(recipient, relays).amount(millisats).event_id(note).message(comment).into_event_builder()
156}
157
158/// Where an invoice for `millisats` is asked for: `pay_info`'s callback,
159/// with the amount and, for a zap, the signed request. A plain payment
160/// carries the comment instead, if the address takes one that long.
161fn invoice_url(pay_info: &PayInfo, millisats: u64, request: Option<&Event>, comment: &str) -> Url {
162    let mut url = pay_info.callback.clone();
163    {
164        let mut query = url.query_pairs_mut();
165        query.append_pair("amount", &millisats.to_string());
166        match request {
167            Some(request) => {
168                query.append_pair("nostr", &request.as_json());
169            }
170            None if !comment.is_empty() && comment.chars().count() <= pay_info.comment_chars => {
171                query.append_pair("comment", comment);
172            }
173            None => {}
174        }
175    }
176    url
177}
178
179/// The invoice in the answer to the second request, if it is one for
180/// `millisats`.
181fn parse_invoice(answer: &[u8], millisats: u64) -> Result<String, ZapError> {
182    let value = parse_answer(answer)?;
183    let invoice = value
184        .get("pr")
185        .and_then(serde_json::Value::as_str)
186        .ok_or_else(|| ZapError::Unreachable("the answer has no invoice".to_string()))?;
187    if invoice_millisats(invoice) != Some(millisats) {
188        return Err(ZapError::WrongAmount);
189    }
190    Ok(invoice.to_string())
191}
192
193/// A zap to ask an invoice for.
194#[derive(Debug, Clone, PartialEq, Eq)]
195pub struct ZapOrder {
196    /// The Lightning address of the one zapped, from their profile.
197    pub address: String,
198    /// The one zapped: the author of the note.
199    pub recipient: PublicKey,
200    /// The note zapped.
201    pub note: EventId,
202    /// How much, in sats.
203    pub sats: u64,
204    /// What is said with it. May be empty.
205    pub comment: String,
206    /// Where the receipt is asked to be sent.
207    pub relays: Vec<RelayUrl>,
208    /// Who it is from.
209    pub zapper: Zapper,
210}
211
212/// The key the wallet service behind the Lightning address `address`
213/// signs its zap receipts with, as it says itself: none, of one that
214/// doesn't do zaps. A receipt for a zap to that address counts when this
215/// key signed it (NIP-57).
216pub async fn zapper_key(http: reqwest::Client, address: &str) -> Result<Option<PublicKey>, ZapError> {
217    let url = pay_info_url(address).ok_or(ZapError::BadAddress)?;
218    let answer = http::get(&http, url.as_str(), MAX_ANSWER_BYTES).await.map_err(ZapError::Unreachable)?;
219    Ok(parse_pay_info(&answer)?.zapper)
220}
221
222/// Ask a Lightning address for the invoice of `order`, with `signer`
223/// signing for an account that zaps.
224///
225/// An address that doesn't do zaps is asked for a plain invoice instead:
226/// the money arrives all the same, and the result says which it is.
227pub async fn request_invoice(http: reqwest::Client, signer: Signer, order: ZapOrder) -> Result<Invoice, ZapError> {
228    let ZapOrder { address, recipient, note, sats, comment, relays, zapper } = order;
229    let get = |url: Url| {
230        let http = http.clone();
231        async move { http::get(&http, url.as_str(), MAX_ANSWER_BYTES).await.map_err(ZapError::Unreachable) }
232    };
233    let pay_info = parse_pay_info(&get(pay_info_url(&address).ok_or(ZapError::BadAddress)?).await?)?;
234
235    let millisats = sats.saturating_mul(1000);
236    if !(pay_info.min_millisats..=pay_info.max_millisats).contains(&millisats) {
237        // Rounded inwards: what is shown as the range is inside it.
238        return Err(ZapError::OutOfRange { min: pay_info.min_millisats.div_ceil(1000), max: pay_info.max_millisats / 1000 });
239    }
240
241    let request = match pay_info.zapper {
242        Some(_) => {
243            let unsigned = zap_request(recipient, note, millisats, &comment, relays);
244            Some(match zapper {
245                Zapper::Account(account) => signer.sign(account, unsigned).await.map_err(ZapError::Sign)?,
246                Zapper::Anonymous => {
247                    unsigned.finalize(&Keys::generate()).map_err(|e| ZapError::Sign(SignError::Keyring(e.to_string())))?
248                }
249            })
250        }
251        None => None,
252    };
253    let answer = get(invoice_url(&pay_info, millisats, request.as_ref(), &comment)).await?;
254    let bolt11 = parse_invoice(&answer, millisats)?;
255    Ok(Invoice { bolt11, sats, is_zap: request.is_some() })
256}
257
258#[cfg(test)]
259mod tests {
260    use super::{PayInfo, ZapError, invoice_millisats, invoice_url, parse_invoice, parse_pay_info, pay_info_url, zap_request};
261    use nostr_sdk::prelude::{Event, EventId, FinalizeEvent, Keys, Kind, RelayUrl, Url};
262
263    #[test]
264    fn an_invoice_says_what_it_asks_for() {
265        assert_eq!(invoice_millisats("lnbc2500u1pvjluezsp5zyg3zyg3"), Some(250_000_000));
266        assert_eq!(invoice_millisats("lnbc210n1pjq9xyz"), Some(21_000), "21 sats");
267        assert_eq!(invoice_millisats("lnbc1m1pabc"), Some(100_000_000));
268        assert_eq!(invoice_millisats("lnbc20p1pabc"), Some(2));
269        assert_eq!(invoice_millisats("LNBC210N1PJQ9XYZ"), Some(21_000), "in capitals, as in a QR code");
270        assert_eq!(invoice_millisats("lntb100u1pabc"), Some(10_000_000), "another network");
271        assert_eq!(invoice_millisats("lnbc1pvjluezpp5"), None, "no amount named");
272        assert_eq!(invoice_millisats("not an invoice"), None);
273        assert_eq!(invoice_millisats(""), None);
274    }
275
276    #[test]
277    fn a_lightning_address_is_asked_at_its_domain_over_https() {
278        let url = |address: &str| pay_info_url(address).map(|url| url.to_string());
279        assert_eq!(url("ana@example.com").as_deref(), Some("https://example.com/.well-known/lnurlp/ana"));
280        assert_eq!(url(" Ana.B+tips@Example.com ").as_deref(), Some("https://example.com/.well-known/lnurlp/ana.b+tips"));
281        assert_eq!(url("ana@example.com:8443").as_deref(), Some("https://example.com:8443/.well-known/lnurlp/ana"));
282
283        assert_eq!(url("example.com"), None, "no name");
284        assert_eq!(url("@example.com"), None);
285        assert_eq!(url("ana@"), None);
286        assert_eq!(url("a/../b@example.com"), None, "a name is not a path");
287        assert_eq!(url("ana@example.com/elsewhere?x="), None, "a domain is not a path");
288        assert_eq!(url("ana@user@example.com"), None, "nor someone at a domain");
289        assert_eq!(url("ana@exa mple.com"), None);
290    }
291
292    const PAY_INFO: &str = r#"{
293        "callback": "https://example.com/lnurlp/ana/callback",
294        "minSendable": 1000, "maxSendable": 100000000,
295        "metadata": "[[\"text/plain\",\"Sats for Ana\"]]", "tag": "payRequest",
296        "allowsNostr": true,
297        "nostrPubkey": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
298        "commentAllowed": 20
299    }"#;
300
301    fn pay_info(json: &str) -> Result<PayInfo, ZapError> {
302        parse_pay_info(json.as_bytes())
303    }
304
305    #[test]
306    fn an_address_says_what_it_accepts_and_whether_it_does_zaps() {
307        let info = pay_info(PAY_INFO).unwrap();
308        assert_eq!(info.callback.as_str(), "https://example.com/lnurlp/ana/callback");
309        assert_eq!((info.min_millisats, info.max_millisats, info.comment_chars), (1000, 100_000_000, 20));
310        assert!(info.zapper.is_some());
311
312        // A key and no word that zaps are allowed is not an address that does them.
313        let quiet = pay_info(&PAY_INFO.replace(r#""allowsNostr": true,"#, "")).unwrap();
314        assert_eq!(quiet.zapper, None);
315        let no_key = pay_info(&PAY_INFO.replace("79be667e", "nonsense")).unwrap();
316        assert_eq!(no_key.zapper, None);
317    }
318
319    #[test]
320    fn an_answer_that_is_not_lnurl_pay_is_no_answer() {
321        let unusable = |json: &str| matches!(pay_info(json), Err(ZapError::Unreachable(_)));
322        assert!(unusable("<html>not found</html>"));
323        assert!(unusable("{}"));
324        assert!(unusable(&PAY_INFO.replace("payRequest", "withdrawRequest")));
325        assert!(unusable(&PAY_INFO.replace("https://example.com/lnurlp", "http://example.com/lnurlp")), "not https");
326        assert!(unusable(&PAY_INFO.replace(r#""minSendable": 1000,"#, "")));
327
328        assert_eq!(
329            pay_info(r#"{"status":"ERROR","reason":"no such user"}"#),
330            Err(ZapError::Refused("no such user".into())),
331            "LNURL's own way of saying no"
332        );
333    }
334
335    fn signed_request(comment: &str) -> Event {
336        let (me, them) = (Keys::generate(), Keys::generate());
337        let relay = RelayUrl::parse("wss://relay.example.com").unwrap();
338        zap_request(them.public_key(), EventId::from_byte_array([7; 32]), 21_000, comment, vec![relay]).finalize(&me).unwrap()
339    }
340
341    #[test]
342    fn a_zap_request_names_the_note_its_author_the_amount_and_where_the_receipt_goes() {
343        let request = signed_request("great note");
344        let tag = |kind: &str| request.tags.iter().find(|tag| tag.kind() == kind).map(|tag| tag.as_slice().to_vec());
345
346        assert_eq!(request.kind, Kind::ZapRequest);
347        assert_eq!(request.content, "great note");
348        assert_eq!(request.tags.event_ids().collect::<Vec<_>>(), [EventId::from_byte_array([7; 32])]);
349        assert_eq!(request.tags.public_keys().count(), 1);
350        assert_eq!(tag("amount"), Some(vec!["amount".to_string(), "21000".to_string()]));
351        assert_eq!(tag("relays"), Some(vec!["relays".to_string(), "wss://relay.example.com".to_string()]));
352    }
353
354    /// The query of `url`, as pairs.
355    fn query(url: &Url) -> Vec<(String, String)> {
356        url.query_pairs().map(|(key, value)| (key.into_owned(), value.into_owned())).collect()
357    }
358
359    #[test]
360    fn an_invoice_is_asked_for_with_the_amount_and_the_signed_request() {
361        let info = pay_info(PAY_INFO).unwrap();
362        let request = signed_request("great note & more");
363        let url = invoice_url(&info, 21_000, Some(&request), "great note & more");
364
365        assert_eq!(url.path(), "/lnurlp/ana/callback");
366        assert_eq!(query(&url), [("amount".to_string(), "21000".to_string()), ("nostr".to_string(), request.as_json())]);
367        // What arrives is the request itself, whatever was in it.
368        let arrived = Event::from_json(&query(&url)[1].1).unwrap();
369        assert_eq!(arrived, request);
370        assert!(arrived.verify().is_ok());
371    }
372
373    #[test]
374    fn a_plain_payment_carries_its_comment_only_if_the_address_takes_it() {
375        let mut info = pay_info(PAY_INFO).unwrap();
376        // A callback that has a query of its own keeps it.
377        info.callback = Url::parse("https://example.com/pay?user=ana").unwrap();
378        let pair = |key: &str, value: &str| (key.to_string(), value.to_string());
379
380        assert_eq!(
381            query(&invoice_url(&info, 5_000, None, "thanks")),
382            [pair("user", "ana"), pair("amount", "5000"), pair("comment", "thanks")]
383        );
384        let long = "a comment longer than the twenty characters it takes";
385        assert_eq!(query(&invoice_url(&info, 5_000, None, long)), [pair("user", "ana"), pair("amount", "5000")]);
386        assert_eq!(query(&invoice_url(&info, 5_000, None, "")), [pair("user", "ana"), pair("amount", "5000")]);
387    }
388
389    #[test]
390    fn an_invoice_is_only_taken_if_it_asks_for_what_was_chosen() {
391        let answer = |invoice: &str| format!(r#"{{"pr":"{invoice}","routes":[]}}"#);
392        assert_eq!(parse_invoice(answer("lnbc210n1pjq9xyz").as_bytes(), 21_000).as_deref(), Ok("lnbc210n1pjq9xyz"));
393        assert_eq!(parse_invoice(answer("lnbc10u1pjq9xyz").as_bytes(), 21_000), Err(ZapError::WrongAmount), "for more");
394        assert_eq!(parse_invoice(answer("lnbc1pjq9xyz").as_bytes(), 21_000), Err(ZapError::WrongAmount), "for any amount");
395        assert!(matches!(parse_invoice(b"{}", 21_000), Err(ZapError::Unreachable(_))));
396        assert_eq!(
397            parse_invoice(br#"{"status":"ERROR","reason":"amount too small"}"#, 21_000),
398            Err(ZapError::Refused("amount too small".into()))
399        );
400    }
401}