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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
use crate::amount::AsSats;
use crate::analytics::{derive_analytics_keys, AnalyticsInterceptor};
use crate::async_runtime::AsyncRuntime;
use crate::auth::{build_async_auth, build_auth};
use crate::data_store::DataStore;
use crate::errors::{NotificationHandlingErrorCode, NotificationHandlingResult};
use crate::event::report_event_for_analytics;
use crate::exchange_rate_provider::{ExchangeRateProvider, ExchangeRateProviderImpl};
use crate::logger::init_logger_once;
use crate::util::LogIgnoreError;
use crate::{
    enable_backtrace, register_webhook_url, sanitize_input, start_sdk, Config, EnableStatus,
    RuntimeErrorCode, UserPreferences, DB_FILENAME, LOGS_DIR,
};
use breez_sdk_core::{
    BreezEvent, BreezServices, EventListener, InvoicePaidDetails, OpenChannelFeeRequest, Payment,
    PaymentStatus, ReceivePaymentRequest,
};
use log::{debug, Level};
use parrot::AnalyticsClient;
use perro::{
    ensure, invalid_input, permanent_failure, runtime_error, MapToError, OptionToError, ResultTrait,
};
use pigeon::submit_lnurl_pay_invoice;
use serde::Deserialize;
use std::path::Path;
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender};
use std::sync::{mpsc, Arc, Mutex};
use std::time::{Duration, Instant};

/// A notification to be displayed to the user.
#[derive(Debug)]
pub enum Notification {
    /// The notification that a previously issued bolt11 invoice was paid.
    /// The `amount_sat` of the payment is provided.
    ///
    /// The `payment_hash` can be used to directly open the associated [`IncomingPaymentInfo`](crate::IncomingPaymentInfo) or
    /// [`OutgoingPaymentInfo`](crate::OutgoingPaymentInfo) using
    /// [`LightningNode::get_incoming_payment`](crate::LightningNode::get_incoming_payment) or
    /// [`LightningNode::get_outgoing_payment`](crate::LightningNode::get_outgoing_payment).
    Bolt11PaymentReceived {
        amount_sat: u64,
        payment_hash: String,
    },
    /// The notification that an onchain receive has completed successfully.
    /// The `amount_sat` of the payment is provided.
    ///
    /// The `payment_hash` can be used to directly open the associated
    /// [`Activity`](crate::Activity) using
    /// [`LightningNode::get_activity`](crate::LightningNode::get_activity).
    OnchainPaymentSwappedIn {
        amount_sat: u64,
        payment_hash: String,
    },
    /// The notification that an invoice was created and submitted for payment as part of an
    /// incoming LNURL payment.
    /// The `amount_sat` of the created invoice is provided.
    LnurlInvoiceCreated { amount_sat: u64 },
}

/// A configuration struct used to enable/disable processing of different payloads in [`handle_notification`].
pub struct NotificationToggles {
    pub payment_received_is_enabled: bool,
    pub address_txs_confirmed_is_enabled: bool,
    pub lnurl_pay_request_is_enabled: bool,
}

/// Handles a notification.
///
/// Notifications are used to wake up the node in order to process some request. Currently supported
/// requests are:
/// * Receive a payment from a previously issued bolt11 invoice.
/// * Receive a payment from a confirmed swap.
/// * Issue an invoice in order to receive an LNURL payment.
///
/// Requires network: **yes**
pub fn handle_notification(
    config: Config,
    notification_payload: String,
    notification_toggles: NotificationToggles,
    timeout: Duration,
) -> NotificationHandlingResult<Notification> {
    enable_backtrace();
    if let Some(level) = config.file_logging_level {
        init_logger_once(
            level,
            &Path::new(&config.local_persistence_path).join(LOGS_DIR),
        )
        .map_runtime_error_using(NotificationHandlingErrorCode::from_runtime_error)?;
    }
    debug!("Started handling a notification with payload: {notification_payload}");

    let timeout_instant = Instant::now() + timeout;

    let payload = match serde_json::from_str::<Payload>(&notification_payload) {
        Ok(p) => p,
        Err(e) => {
            invalid_input!("The provided payload was not recognized. Error: {e} - JSON Payload: {notification_payload}")
        }
    };

    match payload {
        Payload::PaymentReceived { .. } => ensure!(
            notification_toggles.payment_received_is_enabled,
            runtime_error(
                NotificationHandlingErrorCode::NotificationDisabledInNotificationToggles,
                "PaymentReceived notification dismissed due to disabled setting in NotificationToggles"
            )
        ),
        Payload::AddressTxsConfirmed { .. } => ensure!(
            notification_toggles.address_txs_confirmed_is_enabled,
            runtime_error(
                NotificationHandlingErrorCode::NotificationDisabledInNotificationToggles,
                "AddressTxsConfirmed notification dismissed due to disabled setting in NotificationToggles"
            )
        ),
        Payload::LnurlPayRequest { .. } => ensure!(
            notification_toggles.lnurl_pay_request_is_enabled,
            runtime_error(
                NotificationHandlingErrorCode::NotificationDisabledInNotificationToggles,
                "LnurlPayRequest notification dismissed due to disabled setting in NotificationToggles"
            )
        ),
    }

    let rt = AsyncRuntime::new()
        .map_runtime_error_using(NotificationHandlingErrorCode::from_runtime_error)?;

    let (tx, rx) = mpsc::channel();
    let analytics_interceptor = build_analytics_interceptor(&config, &rt)?;
    let event_listener = Box::new(NotificationHandlerEventListener::new(
        tx,
        analytics_interceptor,
    ));
    let sdk = rt
        .handle()
        .block_on(start_sdk(&config, event_listener))
        .map_runtime_error_using(NotificationHandlingErrorCode::from_runtime_error)?;

    match payload {
        Payload::PaymentReceived { payment_hash } => {
            handle_payment_received_notification(rt, sdk, rx, payment_hash, timeout_instant)
        }
        Payload::AddressTxsConfirmed { address } => {
            handle_address_txs_confirmed_notification(rt, sdk, rx, address, timeout_instant)
        }
        Payload::LnurlPayRequest { data } => {
            handle_lnurl_pay_request_notification(rt, sdk, config, data)
        }
    }
}

fn build_analytics_interceptor(
    config: &Config,
    rt: &AsyncRuntime,
) -> NotificationHandlingResult<AnalyticsInterceptor> {
    let user_preferences = Arc::new(Mutex::new(UserPreferences {
        fiat_currency: config.fiat_currency.clone(),
        timezone_config: config.timezone_config.clone(),
    }));

    let strong_typed_seed = get_strong_typed_seed(config)?;
    let async_auth = Arc::new(
        build_async_auth(
            &strong_typed_seed,
            &config.remote_services_config.backend_url,
        )
        .map_runtime_error_using(NotificationHandlingErrorCode::from_runtime_error)?,
    );

    let analytics_client = AnalyticsClient::new(
        config.remote_services_config.backend_url.clone(),
        derive_analytics_keys(&strong_typed_seed)
            .map_runtime_error_using(NotificationHandlingErrorCode::from_runtime_error)?,
        Arc::clone(&async_auth),
    );

    let db_path = format!("{}/{DB_FILENAME}", config.local_persistence_path);
    let data_store = DataStore::new(&db_path)
        .map_runtime_error_using(NotificationHandlingErrorCode::from_runtime_error)?;
    let analytics_config = data_store
        .retrieve_analytics_config()
        .map_runtime_error_using(NotificationHandlingErrorCode::from_runtime_error)?;
    Ok(AnalyticsInterceptor::new(
        analytics_client,
        Arc::clone(&user_preferences),
        rt.handle(),
        analytics_config,
    ))
}

fn handle_payment_received_notification(
    rt: AsyncRuntime,
    sdk: Arc<BreezServices>,
    event_receiver: Receiver<BreezEvent>,
    payment_hash: String,
    timeout_instant: Instant,
) -> NotificationHandlingResult<Notification> {
    // Check if the payment was already received
    if let Some(payment) = get_confirmed_payment(&rt, &sdk, &payment_hash)? {
        return Ok(Notification::Bolt11PaymentReceived {
            amount_sat: payment.amount_msat / 1000,
            payment_hash,
        });
    }

    // Wait for payment to be received
    if let Some(details) =
        wait_for_payment_with_timeout(&event_receiver, &payment_hash, timeout_instant)?
    {
        // We want to wait as long as possible to decrease the likelihood of the signer being shut down
        //  while HTLCs are still in-flight.
        wait_for_synced_event(&event_receiver)?;
        return Ok(Notification::Bolt11PaymentReceived {
            amount_sat: details.payment.map(|p| p.amount_msat).unwrap_or(0) / 1000, // payment will only be None for corrupted GL payments. This is unlikely, so giving an optional amount seems overkill.
            payment_hash,
        });
    }

    runtime_error!(
        NotificationHandlingErrorCode::ExpectedPaymentNotReceived,
        "Expected incoming payment with hash {payment_hash} but it was not received"
    )
}

fn handle_address_txs_confirmed_notification(
    rt: AsyncRuntime,
    sdk: Arc<BreezServices>,
    event_receiver: Receiver<BreezEvent>,
    address: String,
    timeout_instant: Instant,
) -> NotificationHandlingResult<Notification> {
    let in_progress_swap = rt
        .handle()
        .block_on(sdk.in_progress_swap())
        .map_to_runtime_error(
            RuntimeErrorCode::NodeUnavailable,
            "Failed to get in-progress swap",
        )
        .map_runtime_error_using(NotificationHandlingErrorCode::from_runtime_error)?
        .ok_or_runtime_error(
            NotificationHandlingErrorCode::InProgressSwapNotFound,
            "Received an address_txs_confirmed event when no swap is in progress",
        )?;

    ensure!(
        in_progress_swap.bitcoin_address == address,
        runtime_error(
            NotificationHandlingErrorCode::InProgressSwapNotFound,
            "Received an address_txs_confirmed event for an address different from the \
            current in-progress swap address"
        )
    );

    rt.handle()
        .block_on(sdk.redeem_swap(address.clone()))
        .map_to_runtime_error(
            NotificationHandlingErrorCode::NodeUnavailable,
            "Failed to start a swap redeem",
        )?;

    // Check if the payment was already received
    let payment_hash = hex::encode(in_progress_swap.payment_hash);
    if let Some(payment) = get_confirmed_payment(&rt, &sdk, &payment_hash)? {
        return Ok(Notification::OnchainPaymentSwappedIn {
            amount_sat: payment.amount_msat / 1000,
            payment_hash,
        });
    }

    // Wait for payment to arrive
    if let Some(details) =
        wait_for_payment_with_timeout(&event_receiver, &payment_hash, timeout_instant)?
    {
        // We want to wait as long as possible to decrease the likelihood of the signer being shut down
        //  while HTLCs are still in-flight.
        wait_for_synced_event(&event_receiver)?;
        return Ok(Notification::OnchainPaymentSwappedIn {
            amount_sat: details.payment.map(|p| p.amount_msat).unwrap_or(0) / 1000, // payment will only be None for corrupted GL payments. This is unlikely, so giving an optional amount seems overkill.
            payment_hash,
        });
    }

    runtime_error!(
        NotificationHandlingErrorCode::ExpectedPaymentNotReceived,
        "Expected incoming payment with hash {payment_hash} but it was not received"
    )
}

fn handle_lnurl_pay_request_notification(
    rt: AsyncRuntime,
    sdk: Arc<BreezServices>,
    config: Config,
    data: LnurlPayRequestData,
) -> NotificationHandlingResult<Notification> {
    // Prevent payments that need a new channel from being received
    let open_channel_fee_response = rt
        .handle()
        .block_on(sdk.open_channel_fee(OpenChannelFeeRequest {
            amount_msat: Some(data.amount_msat),
            expiry: None,
        }))
        .map_to_runtime_error(
            NotificationHandlingErrorCode::NodeUnavailable,
            "Failed to query open channel fees",
        )?;

    // Prevent payments sent to disabled address from being received
    let db_path = format!("{}/{DB_FILENAME}", config.local_persistence_path);
    let mut data_store = DataStore::new(&db_path)
        .map_runtime_error_using(NotificationHandlingErrorCode::from_runtime_error)?;
    match data_store
        .retrieve_lightning_addresses()
        .map_runtime_error_using(NotificationHandlingErrorCode::from_runtime_error)?
        .iter()
        .find(|(a, _)| data.recipient == *a)
    {
        None => {
            permanent_failure!(
                "Received LNURL Pay request notification for unrecognized address/phone number"
            )
        }
        Some((_, EnableStatus::FeatureDisabled)) => {
            permanent_failure!(
                "Received LNURL Pay request notification for disabled address/phone number feature"
            )
        }
        Some((_, EnableStatus::Enabled)) => {}
    }

    let strong_typed_seed = get_strong_typed_seed(&config)?;

    if let Some(fee_msat) = open_channel_fee_response.fee_msat {
        if fee_msat > 0 {
            report_insuficcient_inbound_liquidity(
                rt,
                &config.remote_services_config.backend_url,
                &strong_typed_seed,
                &data.id,
            )?;
            runtime_error!(
                NotificationHandlingErrorCode::InsufficientInboundLiquidity,
                "Rejecting an inbound LNURL-pay payment because of insufficient inbound liquidity"
            );
        }
    }

    let auth = build_auth(
        &strong_typed_seed,
        &config.remote_services_config.backend_url,
    )
    .map_to_runtime_error(
        NotificationHandlingErrorCode::LipaServiceUnavailable,
        "Failed to authenticate against backend",
    )?;

    // Register webhook in case user hasn't started the wallet for a long time
    //  (Breez expires webhook registrations)
    register_webhook_url(&rt, &sdk, &auth, &config)
        .map_runtime_error_to(NotificationHandlingErrorCode::NodeUnavailable)?;

    // Create invoice
    let receive_payment_result = rt
        .handle()
        .block_on(sdk.receive_payment(ReceivePaymentRequest {
            amount_msat: data.amount_msat,
            description: String::new(),
            preimage: None,
            opening_fee_params: None,
            use_description_hash: None,
            expiry: None,
            cltv: None,
        }))
        .map_to_runtime_error(
            NotificationHandlingErrorCode::NodeUnavailable,
            "Failed to create invoice",
        )?;
    if receive_payment_result.opening_fee_msat.is_some() {
        report_insuficcient_inbound_liquidity(
            rt,
            &config.remote_services_config.backend_url,
            &strong_typed_seed,
            &data.id,
        )?;
        runtime_error!(
            NotificationHandlingErrorCode::InsufficientInboundLiquidity,
            "Rejecting an inbound LNURL-pay payment because of insufficient inbound liquidity"
        )
    }

    // Invoice is not persisted in invoices table because we are not interested in unpaid invoices
    // resulting from incoming LNURL payments

    // Store payment info (exchange rates, user preferences, etc...)
    let user_preferences = UserPreferences {
        fiat_currency: config.fiat_currency.clone(),
        timezone_config: config.timezone_config.clone(),
    };
    let exchange_rate_provider = ExchangeRateProviderImpl::new(
        config.remote_services_config.backend_url.clone(),
        Arc::new(auth),
    );
    let exchange_rates = exchange_rate_provider
        .query_all_exchange_rates()
        .map_to_runtime_error(
            NotificationHandlingErrorCode::LipaServiceUnavailable,
            "Failed to get exchange rates",
        )?;

    data_store
        .store_payment_info(
            &receive_payment_result.ln_invoice.payment_hash,
            user_preferences,
            exchange_rates,
            None,
            Some(data.recipient),
            data.payer_comment,
        )
        .log_ignore_error(Level::Error, "Failed to persist payment info");

    // Submit created invoice to backend
    let async_auth = build_async_auth(
        &strong_typed_seed,
        &config.remote_services_config.backend_url,
    )
    .map_to_runtime_error(
        NotificationHandlingErrorCode::LipaServiceUnavailable,
        "Failed to authenticate against backend",
    )?;
    rt.handle()
        .block_on(submit_lnurl_pay_invoice(
            &config.remote_services_config.backend_url,
            &async_auth,
            data.id,
            Some(receive_payment_result.ln_invoice.bolt11),
        ))
        .map_runtime_error_to(NotificationHandlingErrorCode::LipaServiceUnavailable)?;

    Ok(Notification::LnurlInvoiceCreated {
        amount_sat: data.amount_msat.as_msats().sats_round_down().sats,
    })
}

fn report_insuficcient_inbound_liquidity(
    rt: AsyncRuntime,
    backend_url: &str,
    strong_typed_seed: &[u8; 64],
    id: &str,
) -> NotificationHandlingResult<()> {
    let async_auth = build_async_auth(strong_typed_seed, backend_url).map_to_runtime_error(
        NotificationHandlingErrorCode::LipaServiceUnavailable,
        "Failed to authenticate against backend",
    )?;
    rt.handle()
        .block_on(submit_lnurl_pay_invoice(
            backend_url,
            &async_auth,
            id.to_string(),
            None,
        ))
        .map_runtime_error_to(NotificationHandlingErrorCode::LipaServiceUnavailable)
}

fn get_confirmed_payment(
    rt: &AsyncRuntime,
    sdk: &Arc<BreezServices>,
    payment_hash: &str,
) -> NotificationHandlingResult<Option<Payment>> {
    let payment = rt
        .handle()
        .block_on(sdk.payment_by_hash(payment_hash.to_string()))
        .map_to_runtime_error(
            RuntimeErrorCode::NodeUnavailable,
            "Failed to get payment by hash",
        )
        .map_runtime_error_using(NotificationHandlingErrorCode::from_runtime_error)?;
    if let Some(payment) = payment {
        if payment.status == PaymentStatus::Complete {
            return Ok(Some(payment));
        }
    }
    Ok(None)
}

fn wait_for_payment_with_timeout(
    event_receiver: &Receiver<BreezEvent>,
    payment_hash: &str,
    timeout_instant: Instant,
) -> NotificationHandlingResult<Option<InvoicePaidDetails>> {
    while Instant::now() < timeout_instant {
        match event_receiver.recv_timeout(Duration::from_secs(1)) {
            Ok(BreezEvent::InvoicePaid { details }) if details.payment_hash == payment_hash => {
                return Ok(Some(details))
            }
            Ok(_) => continue,
            Err(RecvTimeoutError::Timeout) => continue,
            Err(RecvTimeoutError::Disconnected) => {
                permanent_failure!("The SDK stopped running unexpectedly");
            }
        }
    }
    Ok(None)
}

/// Wait for synced event without timeout.
fn wait_for_synced_event(event_receiver: &Receiver<BreezEvent>) -> NotificationHandlingResult<()> {
    loop {
        match event_receiver.recv_timeout(Duration::from_secs(1)) {
            Ok(BreezEvent::Synced) => return Ok(()),
            Ok(_) => continue,
            Err(RecvTimeoutError::Timeout) => continue,
            Err(RecvTimeoutError::Disconnected) => {
                permanent_failure!("The SDK stopped running unexpectedly");
            }
        }
    }
}

fn get_strong_typed_seed(config: &Config) -> NotificationHandlingResult<[u8; 64]> {
    sanitize_input::strong_type_seed(&config.seed)
        .map_runtime_error_using(NotificationHandlingErrorCode::from_runtime_error)
}

#[derive(Deserialize)]
#[serde(tag = "template", content = "data")]
#[serde(rename_all = "snake_case")]
enum Payload {
    PaymentReceived {
        payment_hash: String,
    },
    AddressTxsConfirmed {
        address: String,
    },
    LnurlPayRequest {
        #[serde(flatten)]
        data: LnurlPayRequestData,
    },
}

#[derive(Deserialize)]
struct LnurlPayRequestData {
    amount_msat: u64,
    recipient: String,
    payer_comment: Option<String>,
    id: String,
}

struct NotificationHandlerEventListener {
    event_sender: Sender<BreezEvent>,
    analytics_interceptor: AnalyticsInterceptor,
}

impl NotificationHandlerEventListener {
    fn new(event_sender: Sender<BreezEvent>, analytics_interceptor: AnalyticsInterceptor) -> Self {
        NotificationHandlerEventListener {
            event_sender,
            analytics_interceptor,
        }
    }
}

impl EventListener for NotificationHandlerEventListener {
    fn on_event(&self, e: BreezEvent) {
        report_event_for_analytics(&e, &self.analytics_interceptor);
        let _ = self.event_sender.send(e);
    }
}

#[cfg(test)]
mod tests {
    use crate::notification_handling::Payload;

    const PAYMENT_RECEIVED_PAYLOAD_JSON: &str = r#"{
                                                 "template": "payment_received",
                                                 "data": {
                                                  "payment_hash": "hash"
                                                 }
                                                }"#;

    const ADDRESS_TXS_CONFIRMED_PAYLOAD_JSON: &str = r#"{
                                                 "template": "address_txs_confirmed",
                                                 "data": {
                                                  "address": "address"
                                                 }
                                                }"#;

    const LNURL_PAY_REQUEST_PAYLOAD_JSON: &str = r#"{
                                                 "template": "lnurl_pay_request",
                                                 "data": {
                                                  "amount_msat": 12345,
                                                  "recipient": "recipient",
                                                  "payer_comment": "payer_comment",
                                                  "id": "id"
                                                 }
                                                }"#;

    const LNURL_PAY_REQUEST_WITHOUT_COMMENT_PAYLOAD_JSON: &str = r#"{
                                                 "template": "lnurl_pay_request",
                                                 "data": {
                                                  "amount_msat": 12345,
                                                  "recipient": "recipient",
                                                  "payer_comment": null,
                                                  "id": "id"
                                                 }
                                                }"#;

    #[test]
    fn test_payload_deserialize() {
        let payment_received_payload: Payload =
            serde_json::from_str(PAYMENT_RECEIVED_PAYLOAD_JSON).unwrap();
        assert!(matches!(
            payment_received_payload,
            Payload::PaymentReceived {
                payment_hash
            } if payment_hash == "hash"
        ));

        let address_txs_confirmed_payload: Payload =
            serde_json::from_str(ADDRESS_TXS_CONFIRMED_PAYLOAD_JSON).unwrap();
        assert!(matches!(
            address_txs_confirmed_payload,
            Payload::AddressTxsConfirmed {
                address
            } if address == "address"
        ));

        let lnurl_pay_request_payload: Payload =
            serde_json::from_str(LNURL_PAY_REQUEST_PAYLOAD_JSON).unwrap();
        assert!(matches!(
            lnurl_pay_request_payload,
            Payload::LnurlPayRequest {
                data
            } if data.amount_msat == 12345 && data.recipient == "recipient" && data.payer_comment == Some("payer_comment".to_string()) && data.id == "id"
        ));

        let lnurl_pay_request_without_comment_payload: Payload =
            serde_json::from_str(LNURL_PAY_REQUEST_WITHOUT_COMMENT_PAYLOAD_JSON).unwrap();
        assert!(matches!(
            lnurl_pay_request_without_comment_payload,
            Payload::LnurlPayRequest {
                data
            } if data.amount_msat == 12345 && data.recipient == "recipient" && data.payer_comment.is_none() && data.id == "id"
        ));
    }
}