1use core::future::Future;
9use core::task::{Poll, Waker};
10use std::collections::VecDeque;
11use std::ops::Deref;
12use std::sync::{Arc, Mutex};
13
14use bitcoin::blockdata::locktime::absolute::LockTime;
15use bitcoin::secp256k1::PublicKey;
16use bitcoin::{Amount, OutPoint};
17use lightning::events::bump_transaction::BumpTransactionEvent;
18use lightning::events::{
19 ClosureReason, Event as LdkEvent, PaymentFailureReason, PaymentPurpose, ReplayEvent,
20};
21use lightning::impl_writeable_tlv_based_enum;
22use lightning::ln::channelmanager::{FailureCode, PaymentId};
23use lightning::ln::types::ChannelId;
24use lightning::routing::gossip::NodeId;
25use lightning::util::config::{
26 ChannelConfigOverrides, ChannelConfigUpdate, ChannelHandshakeConfigUpdate,
27};
28use lightning::util::errors::APIError;
29use lightning::util::persist::KVStore;
30use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
31use lightning_liquidity::lsps2::utils::compute_opening_fee;
32use lightning_types::payment::{PaymentHash, PaymentPreimage};
33use rand::{rng, Rng};
34
35use crate::config::{may_announce_channel, Config};
36use crate::connection::ConnectionManager;
37use crate::data_store::DataStoreUpdateResult;
38use crate::fee_estimator::ConfirmationTarget;
39use crate::io::{
40 EVENT_QUEUE_PERSISTENCE_KEY, EVENT_QUEUE_PERSISTENCE_PRIMARY_NAMESPACE,
41 EVENT_QUEUE_PERSISTENCE_SECONDARY_NAMESPACE,
42};
43use crate::liquidity::LiquiditySource;
44use crate::logger::{log_debug, log_error, log_info, log_trace, LdkLogger, Logger};
45use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
46use crate::payment::asynchronous::static_invoice_store::StaticInvoiceStore;
47use crate::payment::store::{
48 PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
49};
50use crate::runtime::Runtime;
51use crate::types::{CustomTlvRecord, DynStore, OnionMessenger, PaymentStore, Sweeper, Wallet};
52use crate::{
53 hex_utils, BumpTransactionEventHandler, ChannelManager, Error, Graph, PeerInfo, PeerStore,
54 UserChannelId,
55};
56
57#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum Event {
62 PaymentSuccessful {
64 payment_id: Option<PaymentId>,
68 payment_hash: PaymentHash,
70 payment_preimage: Option<PaymentPreimage>,
76 fee_paid_msat: Option<u64>,
78 },
79 PaymentFailed {
81 payment_id: Option<PaymentId>,
85 payment_hash: Option<PaymentHash>,
92 reason: Option<PaymentFailureReason>,
96 },
97 PaymentReceived {
99 payment_id: Option<PaymentId>,
103 payment_hash: PaymentHash,
105 amount_msat: u64,
107 custom_records: Vec<CustomTlvRecord>,
109 },
110 PaymentForwarded {
112 prev_channel_id: ChannelId,
114 next_channel_id: ChannelId,
116 prev_user_channel_id: Option<UserChannelId>,
120 next_user_channel_id: Option<UserChannelId>,
125 prev_node_id: Option<PublicKey>,
130 next_node_id: Option<PublicKey>,
135 total_fee_earned_msat: Option<u64>,
147 skimmed_fee_msat: Option<u64>,
156 claim_from_onchain_tx: bool,
159 outbound_amount_forwarded_msat: Option<u64>,
163 },
164 PaymentClaimable {
176 payment_id: PaymentId,
178 payment_hash: PaymentHash,
180 claimable_amount_msat: u64,
182 claim_deadline: Option<u32>,
185 custom_records: Vec<CustomTlvRecord>,
187 },
188 ChannelPending {
190 channel_id: ChannelId,
192 user_channel_id: UserChannelId,
194 former_temporary_channel_id: ChannelId,
196 counterparty_node_id: PublicKey,
198 funding_txo: OutPoint,
200 },
201 ChannelReady {
207 channel_id: ChannelId,
209 user_channel_id: UserChannelId,
211 counterparty_node_id: Option<PublicKey>,
215 funding_txo: Option<OutPoint>,
223 },
224 ChannelClosed {
226 channel_id: ChannelId,
228 user_channel_id: UserChannelId,
230 counterparty_node_id: Option<PublicKey>,
234 reason: Option<ClosureReason>,
236 },
237 SplicePending {
239 channel_id: ChannelId,
241 user_channel_id: UserChannelId,
243 counterparty_node_id: PublicKey,
245 new_funding_txo: OutPoint,
247 },
248 SpliceFailed {
250 channel_id: ChannelId,
252 user_channel_id: UserChannelId,
254 counterparty_node_id: PublicKey,
256 abandoned_funding_txo: Option<OutPoint>,
258 },
259}
260
261impl_writeable_tlv_based_enum!(Event,
262 (0, PaymentSuccessful) => {
263 (0, payment_hash, required),
264 (1, fee_paid_msat, option),
265 (3, payment_id, option),
266 (5, payment_preimage, option),
267 },
268 (1, PaymentFailed) => {
269 (0, payment_hash, option),
270 (1, reason, upgradable_option),
271 (3, payment_id, option),
272 },
273 (2, PaymentReceived) => {
274 (0, payment_hash, required),
275 (1, payment_id, option),
276 (2, amount_msat, required),
277 (3, custom_records, optional_vec),
278 },
279 (3, ChannelReady) => {
280 (0, channel_id, required),
281 (1, counterparty_node_id, option),
282 (2, user_channel_id, required),
283 (3, funding_txo, option),
284 },
285 (4, ChannelPending) => {
286 (0, channel_id, required),
287 (2, user_channel_id, required),
288 (4, former_temporary_channel_id, required),
289 (6, counterparty_node_id, required),
290 (8, funding_txo, required),
291 },
292 (5, ChannelClosed) => {
293 (0, channel_id, required),
294 (1, counterparty_node_id, option),
295 (2, user_channel_id, required),
296 (3, reason, upgradable_option),
297 },
298 (6, PaymentClaimable) => {
299 (0, payment_hash, required),
300 (2, payment_id, required),
301 (4, claimable_amount_msat, required),
302 (6, claim_deadline, option),
303 (7, custom_records, optional_vec),
304 },
305 (7, PaymentForwarded) => {
306 (0, prev_channel_id, required),
307 (1, prev_node_id, option),
308 (2, next_channel_id, required),
309 (3, next_node_id, option),
310 (4, prev_user_channel_id, option),
311 (6, next_user_channel_id, option),
312 (8, total_fee_earned_msat, option),
313 (10, skimmed_fee_msat, option),
314 (12, claim_from_onchain_tx, required),
315 (14, outbound_amount_forwarded_msat, option),
316 },
317 (8, SplicePending) => {
318 (1, channel_id, required),
319 (3, counterparty_node_id, required),
320 (5, user_channel_id, required),
321 (7, new_funding_txo, required),
322 },
323 (9, SpliceFailed) => {
324 (1, channel_id, required),
325 (3, counterparty_node_id, required),
326 (5, user_channel_id, required),
327 (7, abandoned_funding_txo, option),
328 },
329);
330
331pub struct EventQueue<L: Deref>
332where
333 L::Target: LdkLogger,
334{
335 queue: Arc<Mutex<VecDeque<Event>>>,
336 waker: Arc<Mutex<Option<Waker>>>,
337 kv_store: Arc<DynStore>,
338 logger: L,
339}
340
341impl<L: Deref> EventQueue<L>
342where
343 L::Target: LdkLogger,
344{
345 pub(crate) fn new(kv_store: Arc<DynStore>, logger: L) -> Self {
346 let queue = Arc::new(Mutex::new(VecDeque::new()));
347 let waker = Arc::new(Mutex::new(None));
348 Self { queue, waker, kv_store, logger }
349 }
350
351 pub(crate) async fn add_event(&self, event: Event) -> Result<(), Error> {
352 let data = {
353 let mut locked_queue = self.queue.lock().unwrap();
354 locked_queue.push_back(event);
355 EventQueueSerWrapper(&locked_queue).encode()
356 };
357
358 self.persist_queue(data).await?;
359
360 if let Some(waker) = self.waker.lock().unwrap().take() {
361 waker.wake();
362 }
363 Ok(())
364 }
365
366 pub(crate) fn next_event(&self) -> Option<Event> {
367 let locked_queue = self.queue.lock().unwrap();
368 locked_queue.front().cloned()
369 }
370
371 pub(crate) async fn next_event_async(&self) -> Event {
372 EventFuture { event_queue: Arc::clone(&self.queue), waker: Arc::clone(&self.waker) }.await
373 }
374
375 pub(crate) async fn event_handled(&self) -> Result<(), Error> {
376 let data = {
377 let mut locked_queue = self.queue.lock().unwrap();
378 locked_queue.pop_front();
379 EventQueueSerWrapper(&locked_queue).encode()
380 };
381
382 self.persist_queue(data).await?;
383
384 if let Some(waker) = self.waker.lock().unwrap().take() {
385 waker.wake();
386 }
387 Ok(())
388 }
389
390 async fn persist_queue(&self, encoded_queue: Vec<u8>) -> Result<(), Error> {
391 KVStore::write(
392 &*self.kv_store,
393 EVENT_QUEUE_PERSISTENCE_PRIMARY_NAMESPACE,
394 EVENT_QUEUE_PERSISTENCE_SECONDARY_NAMESPACE,
395 EVENT_QUEUE_PERSISTENCE_KEY,
396 encoded_queue,
397 )
398 .await
399 .map_err(|e| {
400 log_error!(
401 self.logger,
402 "Write for key {}/{}/{} failed due to: {}",
403 EVENT_QUEUE_PERSISTENCE_PRIMARY_NAMESPACE,
404 EVENT_QUEUE_PERSISTENCE_SECONDARY_NAMESPACE,
405 EVENT_QUEUE_PERSISTENCE_KEY,
406 e
407 );
408 Error::PersistenceFailed
409 })?;
410 Ok(())
411 }
412}
413
414impl<L: Deref> ReadableArgs<(Arc<DynStore>, L)> for EventQueue<L>
415where
416 L::Target: LdkLogger,
417{
418 #[inline]
419 fn read<R: lightning::io::Read>(
420 reader: &mut R, args: (Arc<DynStore>, L),
421 ) -> Result<Self, lightning::ln::msgs::DecodeError> {
422 let (kv_store, logger) = args;
423 let read_queue: EventQueueDeserWrapper = Readable::read(reader)?;
424 let queue = Arc::new(Mutex::new(read_queue.0));
425 let waker = Arc::new(Mutex::new(None));
426 Ok(Self { queue, waker, kv_store, logger })
427 }
428}
429
430struct EventQueueDeserWrapper(VecDeque<Event>);
431
432impl Readable for EventQueueDeserWrapper {
433 fn read<R: lightning::io::Read>(
434 reader: &mut R,
435 ) -> Result<Self, lightning::ln::msgs::DecodeError> {
436 let len: u16 = Readable::read(reader)?;
437 let mut queue = VecDeque::with_capacity(len as usize);
438 for _ in 0..len {
439 queue.push_back(Readable::read(reader)?);
440 }
441 Ok(Self(queue))
442 }
443}
444
445struct EventQueueSerWrapper<'a>(&'a VecDeque<Event>);
446
447impl Writeable for EventQueueSerWrapper<'_> {
448 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), lightning::io::Error> {
449 (self.0.len() as u16).write(writer)?;
450 for e in self.0.iter() {
451 e.write(writer)?;
452 }
453 Ok(())
454 }
455}
456
457struct EventFuture {
458 event_queue: Arc<Mutex<VecDeque<Event>>>,
459 waker: Arc<Mutex<Option<Waker>>>,
460}
461
462impl Future for EventFuture {
463 type Output = Event;
464
465 fn poll(
466 self: core::pin::Pin<&mut Self>, cx: &mut core::task::Context<'_>,
467 ) -> core::task::Poll<Self::Output> {
468 if let Some(event) = self.event_queue.lock().unwrap().front() {
469 Poll::Ready(event.clone())
470 } else {
471 *self.waker.lock().unwrap() = Some(cx.waker().clone());
472 Poll::Pending
473 }
474 }
475}
476
477pub(crate) struct EventHandler<L: Deref + Clone + Sync + Send + 'static>
478where
479 L::Target: LdkLogger,
480{
481 event_queue: Arc<EventQueue<L>>,
482 wallet: Arc<Wallet>,
483 bump_tx_event_handler: Arc<BumpTransactionEventHandler>,
484 channel_manager: Arc<ChannelManager>,
485 connection_manager: Arc<ConnectionManager<L>>,
486 output_sweeper: Arc<Sweeper>,
487 network_graph: Arc<Graph>,
488 liquidity_source: Option<Arc<LiquiditySource<Arc<Logger>>>>,
489 payment_store: Arc<PaymentStore>,
490 peer_store: Arc<PeerStore<L>>,
491 runtime: Arc<Runtime>,
492 logger: L,
493 config: Arc<Config>,
494 static_invoice_store: Option<StaticInvoiceStore>,
495 onion_messenger: Arc<OnionMessenger>,
496 om_mailbox: Option<Arc<OnionMessageMailbox>>,
497}
498
499impl<L: Deref + Clone + Sync + Send + 'static> EventHandler<L>
500where
501 L::Target: LdkLogger,
502{
503 pub fn new(
504 event_queue: Arc<EventQueue<L>>, wallet: Arc<Wallet>,
505 bump_tx_event_handler: Arc<BumpTransactionEventHandler>,
506 channel_manager: Arc<ChannelManager>, connection_manager: Arc<ConnectionManager<L>>,
507 output_sweeper: Arc<Sweeper>, network_graph: Arc<Graph>,
508 liquidity_source: Option<Arc<LiquiditySource<Arc<Logger>>>>,
509 payment_store: Arc<PaymentStore>, peer_store: Arc<PeerStore<L>>,
510 static_invoice_store: Option<StaticInvoiceStore>, onion_messenger: Arc<OnionMessenger>,
511 om_mailbox: Option<Arc<OnionMessageMailbox>>, runtime: Arc<Runtime>, logger: L,
512 config: Arc<Config>,
513 ) -> Self {
514 Self {
515 event_queue,
516 wallet,
517 bump_tx_event_handler,
518 channel_manager,
519 connection_manager,
520 output_sweeper,
521 network_graph,
522 liquidity_source,
523 payment_store,
524 peer_store,
525 logger,
526 runtime,
527 config,
528 static_invoice_store,
529 onion_messenger,
530 om_mailbox,
531 }
532 }
533
534 pub async fn handle_event(&self, event: LdkEvent) -> Result<(), ReplayEvent> {
535 match event {
536 LdkEvent::FundingGenerationReady {
537 temporary_channel_id,
538 counterparty_node_id,
539 channel_value_satoshis,
540 output_script,
541 user_channel_id,
542 } => {
543 let confirmation_target = ConfirmationTarget::ChannelFunding;
546
547 let cur_height = self.channel_manager.current_best_block().height;
549 let locktime = LockTime::from_height(cur_height).unwrap_or(LockTime::ZERO);
550
551 let channel_amount = Amount::from_sat(channel_value_satoshis);
553 match self.wallet.create_funding_transaction(
554 output_script,
555 channel_amount,
556 confirmation_target,
557 locktime,
558 ) {
559 Ok(final_tx) => {
560 let needs_manual_broadcast =
561 self.liquidity_source.as_ref().map_or(false, |ls| {
562 ls.as_ref().lsps2_channel_needs_manual_broadcast(
563 counterparty_node_id,
564 user_channel_id,
565 )
566 });
567
568 let result = if needs_manual_broadcast {
569 self.liquidity_source.as_ref().map(|ls| {
570 ls.lsps2_store_funding_transaction(
571 user_channel_id,
572 counterparty_node_id,
573 final_tx.clone(),
574 );
575 });
576 self.channel_manager.funding_transaction_generated_manual_broadcast(
577 temporary_channel_id,
578 counterparty_node_id,
579 final_tx,
580 )
581 } else {
582 self.channel_manager.funding_transaction_generated(
583 temporary_channel_id,
584 counterparty_node_id,
585 final_tx,
586 )
587 };
588
589 match result {
590 Ok(()) => {},
591 Err(APIError::APIMisuseError { err }) => {
592 log_error!(
593 self.logger,
594 "Encountered APIMisuseError, this should never happen: {}",
595 err
596 );
597 debug_assert!(false, "APIMisuseError: {}", err);
598 },
599 Err(APIError::ChannelUnavailable { err }) => {
600 log_error!(
601 self.logger,
602 "Failed to process funding transaction as channel went away before we could fund it: {}",
603 err
604 );
605 },
606 Err(err) => {
607 log_error!(
608 self.logger,
609 "Failed to process funding transaction: {:?}",
610 err
611 );
612 },
613 }
614 },
615 Err(err) => {
616 log_error!(self.logger, "Failed to create funding transaction: {}", err);
617 self.channel_manager
618 .force_close_broadcasting_latest_txn(
619 &temporary_channel_id,
620 &counterparty_node_id,
621 "Failed to create funding transaction".to_string(),
622 )
623 .unwrap_or_else(|e| {
624 log_error!(self.logger, "Failed to force close channel after funding generation failed: {:?}", e);
625 debug_assert!(false,
626 "Failed to force close channel after funding generation failed"
627 );
628 });
629 },
630 }
631 },
632 LdkEvent::FundingTxBroadcastSafe { user_channel_id, counterparty_node_id, .. } => {
633 self.liquidity_source.as_ref().map(|ls| {
634 ls.lsps2_funding_tx_broadcast_safe(user_channel_id, counterparty_node_id);
635 });
636 },
637 LdkEvent::PaymentClaimable {
638 payment_hash,
639 purpose,
640 amount_msat,
641 claim_deadline,
642 onion_fields,
643 counterparty_skimmed_fee_msat,
644 ..
645 } => {
646 let payment_id = PaymentId(payment_hash.0);
647
648 if let Some((tlv_type, _)) = onion_fields
649 .as_ref()
650 .and_then(|fields| fields.custom_tlvs().iter().find(|(id, _)| id % 2 == 0))
651 {
652 log_info!(
653 self.logger,
654 "Refusing inbound payment with hash {} as the sender included unknown required TLVs (incl {})",
655 hex_utils::to_string(&payment_hash.0),
656 tlv_type,
657 );
658 let error_code = FailureCode::InvalidOnionPayload(Some((*tlv_type, 0)));
659 self.channel_manager.fail_htlc_backwards_with_reason(&payment_hash, error_code);
660 return Ok(());
661 }
662
663 if let Some(info) = self.payment_store.get(&payment_id) {
664 if info.direction == PaymentDirection::Outbound {
665 log_info!(
666 self.logger,
667 "Refused inbound payment with ID {}: circular payments are unsupported.",
668 payment_id
669 );
670 self.channel_manager.fail_htlc_backwards(&payment_hash);
671 return Ok(());
672 }
673
674 if info.status == PaymentStatus::Succeeded
675 || matches!(info.kind, PaymentKind::Spontaneous { .. })
676 {
677 log_info!(
678 self.logger,
679 "Refused duplicate inbound payment from payment hash {} of {}msat",
680 hex_utils::to_string(&payment_hash.0),
681 amount_msat,
682 );
683 self.channel_manager.fail_htlc_backwards(&payment_hash);
684 return Ok(());
685 }
686
687 let max_total_opening_fee_msat = match info.kind {
688 PaymentKind::Bolt11Jit { lsp_fee_limits, .. } => {
689 lsp_fee_limits
690 .max_total_opening_fee_msat
691 .or_else(|| {
692 lsp_fee_limits.max_proportional_opening_fee_ppm_msat.and_then(
693 |max_prop_fee| {
694 compute_opening_fee(amount_msat, 0, max_prop_fee)
696 },
697 )
698 })
699 .unwrap_or(0)
700 },
701 _ => 0,
702 };
703
704 if counterparty_skimmed_fee_msat > max_total_opening_fee_msat {
705 log_info!(
706 self.logger,
707 "Refusing inbound payment with hash {} as the counterparty-withheld fee of {}msat exceeds our limit of {}msat",
708 hex_utils::to_string(&payment_hash.0),
709 counterparty_skimmed_fee_msat,
710 max_total_opening_fee_msat,
711 );
712 self.channel_manager.fail_htlc_backwards(&payment_hash);
713
714 let update = PaymentDetailsUpdate {
715 hash: Some(Some(payment_hash)),
716 status: Some(PaymentStatus::Failed),
717 ..PaymentDetailsUpdate::new(payment_id)
718 };
719 match self.payment_store.update(&update) {
720 Ok(_) => return Ok(()),
721 Err(e) => {
722 log_error!(self.logger, "Failed to access payment store: {}", e);
723 return Err(ReplayEvent());
724 },
725 };
726 }
727
728 if counterparty_skimmed_fee_msat > 0 {
730 match info.kind {
731 PaymentKind::Bolt11Jit { .. } => {
732 let update = PaymentDetailsUpdate {
733 counterparty_skimmed_fee_msat: Some(Some(counterparty_skimmed_fee_msat)),
734 ..PaymentDetailsUpdate::new(payment_id)
735 };
736 match self.payment_store.update(&update) {
737 Ok(_) => (),
738 Err(e) => {
739 log_error!(self.logger, "Failed to access payment store: {}", e);
740 return Err(ReplayEvent());
741 },
742 };
743 }
744 _ => debug_assert!(false, "We only expect the counterparty to get away with withholding fees for JIT payments."),
745 }
746 }
747
748 match info.kind {
752 PaymentKind::Bolt11 { preimage, .. }
753 | PaymentKind::Bolt11Jit { preimage, .. } => {
754 if purpose.preimage().is_none() {
755 debug_assert!(
756 preimage.is_none(),
757 "We would have registered the preimage if we knew"
758 );
759
760 let custom_records = onion_fields
761 .map(|cf| {
762 cf.custom_tlvs().into_iter().map(|tlv| tlv.into()).collect()
763 })
764 .unwrap_or_default();
765 let event = Event::PaymentClaimable {
766 payment_id,
767 payment_hash,
768 claimable_amount_msat: amount_msat,
769 claim_deadline,
770 custom_records,
771 };
772 match self.event_queue.add_event(event).await {
773 Ok(_) => return Ok(()),
774 Err(e) => {
775 log_error!(
776 self.logger,
777 "Failed to push to event queue: {}",
778 e
779 );
780 return Err(ReplayEvent());
781 },
782 };
783 }
784 },
785 _ => {},
786 }
787 } else if counterparty_skimmed_fee_msat > 0 {
788 log_info!(
792 self.logger,
793 "Refusing inbound payment with hash {} as the counterparty withheld {}msat without a corresponding JIT-channel payment authorizing it",
794 hex_utils::to_string(&payment_hash.0),
795 counterparty_skimmed_fee_msat,
796 );
797 self.channel_manager.fail_htlc_backwards(&payment_hash);
798 return Ok(());
799 }
800
801 log_info!(
802 self.logger,
803 "Received payment from payment hash {} of {}msat",
804 hex_utils::to_string(&payment_hash.0),
805 amount_msat,
806 );
807 let payment_preimage = match purpose {
808 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, .. } => {
809 payment_preimage
810 },
811 PaymentPurpose::Bolt12OfferPayment {
812 payment_preimage,
813 payment_secret,
814 payment_context,
815 ..
816 } => {
817 let payer_note = payment_context.invoice_request.payer_note_truncated;
818 let offer_id = payment_context.offer_id;
819 let quantity = payment_context.invoice_request.quantity;
820 let kind = PaymentKind::Bolt12Offer {
821 hash: Some(payment_hash),
822 preimage: payment_preimage,
823 secret: Some(payment_secret),
824 offer_id,
825 payer_note,
826 quantity,
827 };
828
829 let payment = PaymentDetails::new(
830 payment_id,
831 kind,
832 Some(amount_msat),
833 None,
834 PaymentDirection::Inbound,
835 PaymentStatus::Pending,
836 );
837
838 match self.payment_store.insert(payment) {
839 Ok(false) => (),
840 Ok(true) => {
841 log_error!(
842 self.logger,
843 "Bolt12OfferPayment with ID {} was previously known",
844 payment_id,
845 );
846 debug_assert!(false);
847 },
848 Err(e) => {
849 log_error!(
850 self.logger,
851 "Failed to insert payment with ID {}: {}",
852 payment_id,
853 e
854 );
855 debug_assert!(false);
856 },
857 }
858 payment_preimage
859 },
860 PaymentPurpose::Bolt12RefundPayment { payment_preimage, .. } => {
861 payment_preimage
862 },
863 PaymentPurpose::SpontaneousPayment(preimage) => {
864 let kind = PaymentKind::Spontaneous {
866 hash: payment_hash,
867 preimage: Some(preimage),
868 };
869
870 let payment = PaymentDetails::new(
871 payment_id,
872 kind,
873 Some(amount_msat),
874 None,
875 PaymentDirection::Inbound,
876 PaymentStatus::Pending,
877 );
878
879 match self.payment_store.insert(payment) {
880 Ok(false) => (),
881 Ok(true) => {
882 log_error!(
883 self.logger,
884 "Spontaneous payment with ID {} was previously known",
885 payment_id,
886 );
887 debug_assert!(false);
888 },
889 Err(e) => {
890 log_error!(
891 self.logger,
892 "Failed to insert payment with ID {}: {}",
893 payment_id,
894 e
895 );
896 debug_assert!(false);
897 },
898 }
899
900 Some(preimage)
901 },
902 };
903
904 if let Some(preimage) = payment_preimage {
905 self.channel_manager.claim_funds(preimage);
906 } else {
907 log_error!(
908 self.logger,
909 "Failed to claim payment with ID {}: preimage unknown.",
910 payment_id,
911 );
912 self.channel_manager.fail_htlc_backwards(&payment_hash);
913
914 let update = PaymentDetailsUpdate {
915 hash: Some(Some(payment_hash)),
916 status: Some(PaymentStatus::Failed),
917 ..PaymentDetailsUpdate::new(payment_id)
918 };
919 match self.payment_store.update(&update) {
920 Ok(_) => return Ok(()),
921 Err(e) => {
922 log_error!(self.logger, "Failed to access payment store: {}", e);
923 return Err(ReplayEvent());
924 },
925 };
926 }
927 },
928 LdkEvent::PaymentClaimed {
929 payment_hash,
930 purpose,
931 amount_msat,
932 receiver_node_id: _,
933 htlcs: _,
934 sender_intended_total_msat: _,
935 onion_fields,
936 payment_id: _,
937 } => {
938 let payment_id = PaymentId(payment_hash.0);
939 log_info!(
940 self.logger,
941 "Claimed payment with ID {} from payment hash {} of {}msat.",
942 payment_id,
943 hex_utils::to_string(&payment_hash.0),
944 amount_msat,
945 );
946
947 let update = match purpose {
948 PaymentPurpose::Bolt11InvoicePayment {
949 payment_preimage,
950 payment_secret,
951 ..
952 } => PaymentDetailsUpdate {
953 preimage: Some(payment_preimage),
954 secret: Some(Some(payment_secret)),
955 amount_msat: Some(Some(amount_msat)),
956 status: Some(PaymentStatus::Succeeded),
957 ..PaymentDetailsUpdate::new(payment_id)
958 },
959 PaymentPurpose::Bolt12OfferPayment {
960 payment_preimage, payment_secret, ..
961 } => PaymentDetailsUpdate {
962 preimage: Some(payment_preimage),
963 secret: Some(Some(payment_secret)),
964 amount_msat: Some(Some(amount_msat)),
965 status: Some(PaymentStatus::Succeeded),
966 ..PaymentDetailsUpdate::new(payment_id)
967 },
968 PaymentPurpose::Bolt12RefundPayment {
969 payment_preimage,
970 payment_secret,
971 ..
972 } => PaymentDetailsUpdate {
973 preimage: Some(payment_preimage),
974 secret: Some(Some(payment_secret)),
975 amount_msat: Some(Some(amount_msat)),
976 status: Some(PaymentStatus::Succeeded),
977 ..PaymentDetailsUpdate::new(payment_id)
978 },
979 PaymentPurpose::SpontaneousPayment(preimage) => PaymentDetailsUpdate {
980 preimage: Some(Some(preimage)),
981 amount_msat: Some(Some(amount_msat)),
982 status: Some(PaymentStatus::Succeeded),
983 ..PaymentDetailsUpdate::new(payment_id)
984 },
985 };
986
987 match self.payment_store.update(&update) {
988 Ok(DataStoreUpdateResult::Updated) | Ok(DataStoreUpdateResult::Unchanged) => (
989 ),
992 Ok(DataStoreUpdateResult::NotFound) => {
993 log_error!(
994 self.logger,
995 "Claimed payment with ID {} couldn't be found in store",
996 payment_id,
997 );
998 },
999 Err(e) => {
1000 log_error!(
1001 self.logger,
1002 "Failed to update payment with ID {}: {}",
1003 payment_id,
1004 e
1005 );
1006 return Err(ReplayEvent());
1007 },
1008 }
1009
1010 let event = Event::PaymentReceived {
1011 payment_id: Some(payment_id),
1012 payment_hash,
1013 amount_msat,
1014 custom_records: onion_fields
1015 .map(|cf| cf.custom_tlvs().into_iter().map(|tlv| tlv.into()).collect())
1016 .unwrap_or_default(),
1017 };
1018 match self.event_queue.add_event(event).await {
1019 Ok(_) => return Ok(()),
1020 Err(e) => {
1021 log_error!(self.logger, "Failed to push to event queue: {}", e);
1022 return Err(ReplayEvent());
1023 },
1024 };
1025 },
1026 LdkEvent::PaymentSent {
1027 payment_id,
1028 payment_preimage,
1029 payment_hash,
1030 fee_paid_msat,
1031 ..
1032 } => {
1033 let payment_id = if let Some(id) = payment_id {
1034 id
1035 } else {
1036 debug_assert!(false, "payment_id should always be set.");
1037 return Ok(());
1038 };
1039
1040 let update = PaymentDetailsUpdate {
1041 hash: Some(Some(payment_hash)),
1042 preimage: Some(Some(payment_preimage)),
1043 fee_paid_msat: Some(fee_paid_msat),
1044 status: Some(PaymentStatus::Succeeded),
1045 ..PaymentDetailsUpdate::new(payment_id)
1046 };
1047
1048 match self.payment_store.update(&update) {
1049 Ok(_) => {},
1050 Err(e) => {
1051 log_error!(self.logger, "Failed to access payment store: {}", e);
1052 return Err(ReplayEvent());
1053 },
1054 };
1055
1056 self.payment_store.get(&payment_id).map(|payment| {
1057 log_info!(
1058 self.logger,
1059 "Successfully sent payment of {}msat{} with payment hash {}",
1060 payment.amount_msat.unwrap(),
1061 if let Some(fee) = fee_paid_msat {
1062 format!(" (fee {} msat)", fee)
1063 } else {
1064 "".to_string()
1065 },
1066 hex_utils::to_string(&payment_hash.0),
1067 );
1068 });
1069 let event = Event::PaymentSuccessful {
1070 payment_id: Some(payment_id),
1071 payment_hash,
1072 payment_preimage: Some(payment_preimage),
1073 fee_paid_msat,
1074 };
1075
1076 match self.event_queue.add_event(event).await {
1077 Ok(_) => return Ok(()),
1078 Err(e) => {
1079 log_error!(self.logger, "Failed to push to event queue: {}", e);
1080 return Err(ReplayEvent());
1081 },
1082 };
1083 },
1084 LdkEvent::PaymentFailed { payment_id, payment_hash, reason, .. } => {
1085 if let Some(payment) = self.payment_store.get(&payment_id) {
1088 if payment.direction == PaymentDirection::Outbound
1089 && payment.kind.is_lightning_payment()
1090 && payment.status == PaymentStatus::Succeeded
1091 {
1092 log_info!(
1093 self.logger,
1094 "Ignoring late payment failure for already-succeeded payment with ID {}.",
1095 payment_id
1096 );
1097 return Ok(());
1098 }
1099 }
1100
1101 log_info!(
1102 self.logger,
1103 "Failed to send payment with ID {} due to {:?}.",
1104 payment_id,
1105 reason
1106 );
1107
1108 let update = PaymentDetailsUpdate {
1109 hash: Some(payment_hash),
1110 status: Some(PaymentStatus::Failed),
1111 ..PaymentDetailsUpdate::new(payment_id)
1112 };
1113 match self.payment_store.update(&update) {
1114 Ok(_) => {},
1115 Err(e) => {
1116 log_error!(self.logger, "Failed to access payment store: {}", e);
1117 return Err(ReplayEvent());
1118 },
1119 };
1120
1121 let event =
1122 Event::PaymentFailed { payment_id: Some(payment_id), payment_hash, reason };
1123 match self.event_queue.add_event(event).await {
1124 Ok(_) => return Ok(()),
1125 Err(e) => {
1126 log_error!(self.logger, "Failed to push to event queue: {}", e);
1127 return Err(ReplayEvent());
1128 },
1129 };
1130 },
1131
1132 LdkEvent::PaymentPathSuccessful { .. } => {},
1133 LdkEvent::PaymentPathFailed { .. } => {},
1134 LdkEvent::ProbeSuccessful { .. } => {},
1135 LdkEvent::ProbeFailed { .. } => {},
1136 LdkEvent::HTLCHandlingFailed { failure_type, .. } => {
1137 if let Some(liquidity_source) = self.liquidity_source.as_ref() {
1138 liquidity_source.handle_htlc_handling_failed(failure_type).await;
1139 }
1140 },
1141 LdkEvent::SpendableOutputs { outputs, channel_id } => {
1142 match self
1143 .output_sweeper
1144 .track_spendable_outputs(outputs, channel_id, true, None)
1145 .await
1146 {
1147 Ok(_) => return Ok(()),
1148 Err(_) => {
1149 log_error!(self.logger, "Failed to track spendable outputs");
1150 return Err(ReplayEvent());
1151 },
1152 };
1153 },
1154 LdkEvent::OpenChannelRequest {
1155 temporary_channel_id,
1156 counterparty_node_id,
1157 funding_satoshis,
1158 channel_type,
1159 channel_negotiation_type: _,
1160 is_announced,
1161 params: _,
1162 } => {
1163 if is_announced {
1164 if let Err(err) = may_announce_channel(&*self.config) {
1165 log_error!(self.logger, "Rejecting inbound announced channel from peer {} due to missing configuration: {}", counterparty_node_id, err);
1166
1167 self.channel_manager
1168 .force_close_broadcasting_latest_txn(
1169 &temporary_channel_id,
1170 &counterparty_node_id,
1171 "Channel request rejected".to_string(),
1172 )
1173 .unwrap_or_else(|e| {
1174 log_error!(self.logger, "Failed to reject channel: {:?}", e);
1175 });
1176 return Ok(());
1177 }
1178 }
1179
1180 let anchor_channel = channel_type.requires_anchors_zero_fee_htlc_tx();
1181 if anchor_channel {
1182 if let Some(anchor_channels_config) =
1183 self.config.anchor_channels_config.as_ref()
1184 {
1185 let cur_anchor_reserve_sats = crate::total_anchor_channels_reserve_sats(
1186 &self.channel_manager,
1187 &self.config,
1188 );
1189 let spendable_amount_sats = self
1190 .wallet
1191 .get_spendable_amount_sats(cur_anchor_reserve_sats)
1192 .unwrap_or(0);
1193
1194 let required_amount_sats = if anchor_channels_config
1195 .trusted_peers_no_reserve
1196 .contains(&counterparty_node_id)
1197 {
1198 0
1199 } else {
1200 anchor_channels_config.per_channel_reserve_sats
1201 };
1202
1203 if spendable_amount_sats < required_amount_sats {
1204 log_error!(
1205 self.logger,
1206 "Rejecting inbound Anchor channel from peer {} due to insufficient available on-chain reserves. Available: {}/{}sats",
1207 counterparty_node_id,
1208 spendable_amount_sats,
1209 required_amount_sats,
1210 );
1211 self.channel_manager
1212 .force_close_broadcasting_latest_txn(
1213 &temporary_channel_id,
1214 &counterparty_node_id,
1215 "Channel request rejected".to_string(),
1216 )
1217 .unwrap_or_else(|e| {
1218 log_error!(self.logger, "Failed to reject channel: {:?}", e);
1219 });
1220 return Ok(());
1221 }
1222 } else {
1223 log_error!(
1224 self.logger,
1225 "Rejecting inbound channel from peer {} due to Anchor channels being disabled.",
1226 counterparty_node_id,
1227 );
1228 self.channel_manager
1229 .force_close_broadcasting_latest_txn(
1230 &temporary_channel_id,
1231 &counterparty_node_id,
1232 "Channel request rejected".to_string(),
1233 )
1234 .unwrap_or_else(|e| {
1235 log_error!(self.logger, "Failed to reject channel: {:?}", e);
1236 });
1237 return Ok(());
1238 }
1239 }
1240
1241 let user_channel_id: u128 = rng().random();
1242 let allow_0conf = self.config.trusted_peers_0conf.contains(&counterparty_node_id);
1243 let mut channel_override_config = None;
1244 if let Some((lsp_node_id, _)) = self
1245 .liquidity_source
1246 .as_ref()
1247 .and_then(|ls| ls.as_ref().get_lsps2_lsp_details())
1248 {
1249 if lsp_node_id == counterparty_node_id {
1250 channel_override_config = Some(ChannelConfigOverrides {
1257 handshake_overrides: Some(ChannelHandshakeConfigUpdate {
1258 max_inbound_htlc_value_in_flight_percent_of_channel: Some(100),
1259 ..Default::default()
1260 }),
1261 update_overrides: Some(ChannelConfigUpdate {
1262 accept_underpaying_htlcs: Some(true),
1263 ..Default::default()
1264 }),
1265 });
1266 }
1267 }
1268 let res = if allow_0conf {
1269 self.channel_manager.accept_inbound_channel_from_trusted_peer_0conf(
1270 &temporary_channel_id,
1271 &counterparty_node_id,
1272 user_channel_id,
1273 channel_override_config,
1274 )
1275 } else {
1276 self.channel_manager.accept_inbound_channel(
1277 &temporary_channel_id,
1278 &counterparty_node_id,
1279 user_channel_id,
1280 channel_override_config,
1281 )
1282 };
1283
1284 match res {
1285 Ok(()) => {
1286 log_info!(
1287 self.logger,
1288 "Accepting inbound{}{} channel of {}sats from{} peer {}",
1289 if allow_0conf { " 0conf" } else { "" },
1290 if anchor_channel { " Anchor" } else { "" },
1291 funding_satoshis,
1292 if allow_0conf { " trusted" } else { "" },
1293 counterparty_node_id,
1294 );
1295 },
1296 Err(e) => {
1297 log_error!(
1298 self.logger,
1299 "Error while accepting inbound{}{} channel from{} peer {}: {:?}",
1300 if allow_0conf { " 0conf" } else { "" },
1301 if anchor_channel { " Anchor" } else { "" },
1302 counterparty_node_id,
1303 if allow_0conf { " trusted" } else { "" },
1304 e,
1305 );
1306 },
1307 }
1308 },
1309 LdkEvent::PaymentForwarded {
1310 prev_channel_id,
1311 next_channel_id,
1312 prev_user_channel_id,
1313 next_user_channel_id,
1314 prev_node_id,
1315 next_node_id,
1316 total_fee_earned_msat,
1317 skimmed_fee_msat,
1318 claim_from_onchain_tx,
1319 outbound_amount_forwarded_msat,
1320 } => {
1321 {
1322 let read_only_network_graph = self.network_graph.read_only();
1323 let nodes = read_only_network_graph.nodes();
1324 let channels = self.channel_manager.list_channels();
1325
1326 let node_str = |channel_id: &Option<ChannelId>| {
1327 channel_id
1328 .and_then(|channel_id| {
1329 channels.iter().find(|c| c.channel_id == channel_id)
1330 })
1331 .and_then(|channel| {
1332 nodes.get(&NodeId::from_pubkey(&channel.counterparty.node_id))
1333 })
1334 .map_or("private_node".to_string(), |node| {
1335 node.announcement_info
1336 .as_ref()
1337 .map_or("unnamed node".to_string(), |ann| {
1338 format!("node {}", ann.alias())
1339 })
1340 })
1341 };
1342 let channel_str = |channel_id: &Option<ChannelId>| {
1343 channel_id
1344 .map(|channel_id| format!(" with channel {}", channel_id))
1345 .unwrap_or_default()
1346 };
1347 let from_prev_str = format!(
1348 " from {}{}",
1349 node_str(&prev_channel_id),
1350 channel_str(&prev_channel_id)
1351 );
1352 let to_next_str = format!(
1353 " to {}{}",
1354 node_str(&next_channel_id),
1355 channel_str(&next_channel_id)
1356 );
1357
1358 let fee_earned = total_fee_earned_msat.unwrap_or(0);
1359 if claim_from_onchain_tx {
1360 log_info!(
1361 self.logger,
1362 "Forwarded payment{}{} of {}msat, earning {}msat in fees from claiming onchain.",
1363 from_prev_str,
1364 to_next_str,
1365 outbound_amount_forwarded_msat.unwrap_or(0),
1366 fee_earned,
1367 );
1368 } else {
1369 log_info!(
1370 self.logger,
1371 "Forwarded payment{}{} of {}msat, earning {}msat in fees.",
1372 from_prev_str,
1373 to_next_str,
1374 outbound_amount_forwarded_msat.unwrap_or(0),
1375 fee_earned,
1376 );
1377 }
1378 }
1379
1380 if let Some(liquidity_source) = self.liquidity_source.as_ref() {
1381 let skimmed_fee_msat = skimmed_fee_msat.unwrap_or(0);
1382 liquidity_source
1383 .handle_payment_forwarded(next_channel_id, skimmed_fee_msat)
1384 .await;
1385 }
1386
1387 let event = Event::PaymentForwarded {
1388 prev_channel_id: prev_channel_id.expect("prev_channel_id expected for events generated by LDK versions greater than 0.0.107."),
1389 next_channel_id: next_channel_id.expect("next_channel_id expected for events generated by LDK versions greater than 0.0.107."),
1390 prev_user_channel_id: prev_user_channel_id.map(UserChannelId),
1391 next_user_channel_id: next_user_channel_id.map(UserChannelId),
1392 prev_node_id,
1393 next_node_id,
1394 total_fee_earned_msat,
1395 skimmed_fee_msat,
1396 claim_from_onchain_tx,
1397 outbound_amount_forwarded_msat,
1398 };
1399 self.event_queue.add_event(event).await.map_err(|e| {
1400 log_error!(self.logger, "Failed to push to event queue: {}", e);
1401 ReplayEvent()
1402 })?;
1403 },
1404 LdkEvent::ChannelPending {
1405 channel_id,
1406 user_channel_id,
1407 former_temporary_channel_id,
1408 counterparty_node_id,
1409 funding_txo,
1410 ..
1411 } => {
1412 log_info!(
1413 self.logger,
1414 "New channel {} with counterparty {} has been created and is pending confirmation on chain.",
1415 channel_id,
1416 counterparty_node_id,
1417 );
1418
1419 let event = Event::ChannelPending {
1420 channel_id,
1421 user_channel_id: UserChannelId(user_channel_id),
1422 former_temporary_channel_id: former_temporary_channel_id.unwrap(),
1423 counterparty_node_id,
1424 funding_txo,
1425 };
1426 match self.event_queue.add_event(event).await {
1427 Ok(_) => {},
1428 Err(e) => {
1429 log_error!(self.logger, "Failed to push to event queue: {}", e);
1430 return Err(ReplayEvent());
1431 },
1432 };
1433
1434 let network_graph = self.network_graph.read_only();
1435 let channels =
1436 self.channel_manager.list_channels_with_counterparty(&counterparty_node_id);
1437 if let Some(pending_channel) =
1438 channels.into_iter().find(|c| c.channel_id == channel_id)
1439 {
1440 if !pending_channel.is_outbound
1441 && self.peer_store.get_peer(&counterparty_node_id).is_none()
1442 {
1443 if let Some(address) = network_graph
1444 .nodes()
1445 .get(&NodeId::from_pubkey(&counterparty_node_id))
1446 .and_then(|node_info| node_info.announcement_info.as_ref())
1447 .and_then(|ann_info| ann_info.addresses().first())
1448 {
1449 let peer = PeerInfo {
1450 node_id: counterparty_node_id,
1451 address: address.clone(),
1452 };
1453
1454 self.peer_store.add_peer(peer).unwrap_or_else(|e| {
1455 log_error!(
1456 self.logger,
1457 "Failed to add peer {} to peer store: {}",
1458 counterparty_node_id,
1459 e
1460 );
1461 });
1462 }
1463 }
1464 }
1465 },
1466 LdkEvent::ChannelReady {
1467 channel_id,
1468 user_channel_id,
1469 counterparty_node_id,
1470 funding_txo,
1471 ..
1472 } => {
1473 if let Some(funding_txo) = funding_txo {
1474 log_info!(
1475 self.logger,
1476 "Channel {} with counterparty {} ready to be used with funding_txo {}",
1477 channel_id,
1478 counterparty_node_id,
1479 funding_txo,
1480 );
1481 } else {
1482 log_info!(
1483 self.logger,
1484 "Channel {} with counterparty {} ready to be used",
1485 channel_id,
1486 counterparty_node_id,
1487 );
1488 }
1489
1490 if let Some(liquidity_source) = self.liquidity_source.as_ref() {
1491 liquidity_source
1492 .handle_channel_ready(user_channel_id, &channel_id, &counterparty_node_id)
1493 .await;
1494 }
1495
1496 let event = Event::ChannelReady {
1497 channel_id,
1498 user_channel_id: UserChannelId(user_channel_id),
1499 counterparty_node_id: Some(counterparty_node_id),
1500 funding_txo,
1501 };
1502 match self.event_queue.add_event(event).await {
1503 Ok(_) => {},
1504 Err(e) => {
1505 log_error!(self.logger, "Failed to push to event queue: {}", e);
1506 return Err(ReplayEvent());
1507 },
1508 };
1509 },
1510 LdkEvent::ChannelClosed {
1511 channel_id,
1512 reason,
1513 user_channel_id,
1514 counterparty_node_id,
1515 ..
1516 } => {
1517 log_info!(self.logger, "Channel {} closed due to: {}", channel_id, reason);
1518
1519 let event = Event::ChannelClosed {
1520 channel_id,
1521 user_channel_id: UserChannelId(user_channel_id),
1522 counterparty_node_id,
1523 reason: Some(reason),
1524 };
1525
1526 match self.event_queue.add_event(event).await {
1527 Ok(_) => {},
1528 Err(e) => {
1529 log_error!(self.logger, "Failed to push to event queue: {}", e);
1530 return Err(ReplayEvent());
1531 },
1532 };
1533 },
1534 LdkEvent::DiscardFunding { .. } => {},
1535 LdkEvent::HTLCIntercepted {
1536 requested_next_hop_scid,
1537 intercept_id,
1538 expected_outbound_amount_msat,
1539 payment_hash,
1540 ..
1541 } => {
1542 if let Some(liquidity_source) = self.liquidity_source.as_ref() {
1543 liquidity_source
1544 .handle_htlc_intercepted(
1545 requested_next_hop_scid,
1546 intercept_id,
1547 expected_outbound_amount_msat,
1548 payment_hash,
1549 )
1550 .await;
1551 }
1552 },
1553 LdkEvent::InvoiceReceived { .. } => {
1554 debug_assert!(false, "We currently don't handle BOLT12 invoices manually, so this event should never be emitted.");
1555 },
1556 LdkEvent::ConnectionNeeded { node_id, addresses } => {
1557 let spawn_logger = self.logger.clone();
1558 let spawn_cm = Arc::clone(&self.connection_manager);
1559 let future = async move {
1560 for addr in &addresses {
1561 match spawn_cm.connect_peer_if_necessary(node_id, addr.clone()).await {
1562 Ok(()) => {
1563 return;
1564 },
1565 Err(e) => {
1566 log_error!(
1567 spawn_logger,
1568 "Failed to establish connection to peer {}@{}: {}",
1569 node_id,
1570 addr,
1571 e
1572 );
1573 },
1574 }
1575 }
1576 };
1577 self.runtime.spawn_cancellable_background_task(future);
1578 },
1579 LdkEvent::BumpTransaction(bte) => {
1580 match bte {
1581 BumpTransactionEvent::ChannelClose {
1582 ref channel_id,
1583 ref counterparty_node_id,
1584 ..
1585 } => {
1586 if let Some(anchor_channels_config) =
1588 self.config.anchor_channels_config.as_ref()
1589 {
1590 if anchor_channels_config
1591 .trusted_peers_no_reserve
1592 .contains(counterparty_node_id)
1593 {
1594 log_debug!(self.logger,
1595 "Ignoring BumpTransactionEvent::ChannelClose for channel {} due to trusted counterparty {}",
1596 channel_id, counterparty_node_id
1597 );
1598 return Ok(());
1599 }
1600 }
1601 },
1602 BumpTransactionEvent::HTLCResolution { .. } => {},
1603 }
1604
1605 self.bump_tx_event_handler.handle_event(&bte).await;
1606 },
1607 LdkEvent::OnionMessageIntercepted { peer_node_id, message } => {
1608 if let Some(om_mailbox) = self.om_mailbox.as_ref() {
1609 om_mailbox.onion_message_intercepted(peer_node_id, message);
1610 } else {
1611 log_trace!(
1612 self.logger,
1613 "Onion message intercepted, but no onion message mailbox available"
1614 );
1615 }
1616 },
1617 LdkEvent::OnionMessagePeerConnected { peer_node_id } => {
1618 if let Some(om_mailbox) = self.om_mailbox.as_ref() {
1619 let messages = om_mailbox.onion_message_peer_connected(peer_node_id);
1620
1621 for message in messages {
1622 if let Err(e) =
1623 self.onion_messenger.forward_onion_message(message, &peer_node_id)
1624 {
1625 log_trace!(
1626 self.logger,
1627 "Failed to forward onion message to peer {}: {:?}",
1628 peer_node_id,
1629 e
1630 );
1631 }
1632 }
1633 }
1634 },
1635
1636 LdkEvent::PersistStaticInvoice {
1637 invoice,
1638 invoice_request_path,
1639 invoice_slot,
1640 recipient_id,
1641 invoice_persisted_path,
1642 } => {
1643 if let Some(store) = self.static_invoice_store.as_ref() {
1644 match store
1645 .handle_persist_static_invoice(
1646 invoice,
1647 invoice_request_path,
1648 invoice_slot,
1649 recipient_id,
1650 )
1651 .await
1652 {
1653 Ok(_) => {
1654 self.channel_manager.static_invoice_persisted(invoice_persisted_path);
1655 },
1656 Err(e) => {
1657 log_error!(self.logger, "Failed to persist static invoice: {}", e);
1658 return Err(ReplayEvent());
1659 },
1660 };
1661 }
1662 },
1663 LdkEvent::StaticInvoiceRequested {
1664 recipient_id,
1665 invoice_slot,
1666 reply_path,
1667 invoice_request,
1668 } => {
1669 if let Some(store) = self.static_invoice_store.as_ref() {
1670 let invoice =
1671 store.handle_static_invoice_requested(&recipient_id, invoice_slot).await;
1672
1673 match invoice {
1674 Ok(Some((invoice, invoice_request_path))) => {
1675 if let Err(e) = self.channel_manager.respond_to_static_invoice_request(
1676 invoice,
1677 reply_path,
1678 invoice_request,
1679 invoice_request_path,
1680 ) {
1681 log_error!(self.logger, "Failed to send static invoice: {:?}", e);
1682 }
1683 },
1684 Ok(None) => {
1685 log_trace!(
1686 self.logger,
1687 "No static invoice found for recipient {} and slot {}",
1688 hex_utils::to_string(&recipient_id),
1689 invoice_slot
1690 );
1691 },
1692 Err(e) => {
1693 log_error!(self.logger, "Failed to retrieve static invoice: {}", e);
1694 return Err(ReplayEvent());
1695 },
1696 }
1697 }
1698 },
1699 LdkEvent::FundingTransactionReadyForSigning {
1701 channel_id,
1702 counterparty_node_id,
1703 unsigned_transaction,
1704 ..
1705 } => match self.wallet.sign_owned_inputs(unsigned_transaction) {
1706 Ok(partially_signed_tx) => {
1707 match self.channel_manager.funding_transaction_signed(
1708 &channel_id,
1709 &counterparty_node_id,
1710 partially_signed_tx,
1711 ) {
1712 Ok(()) => {
1713 log_info!(
1714 self.logger,
1715 "Signed funding transaction for channel {} with counterparty {}",
1716 channel_id,
1717 counterparty_node_id
1718 );
1719 },
1720 Err(e) => {
1721 debug_assert!(false, "Failed signing funding transaction: {:?}", e);
1723 log_error!(self.logger, "Failed signing funding transaction: {:?}", e);
1724 },
1725 }
1726 },
1727 Err(()) => {
1728 log_error!(self.logger, "Failed signing funding transaction");
1729 },
1730 },
1731 LdkEvent::SplicePending {
1732 channel_id,
1733 user_channel_id,
1734 counterparty_node_id,
1735 new_funding_txo,
1736 ..
1737 } => {
1738 log_info!(
1739 self.logger,
1740 "Channel {} with counterparty {} pending splice with funding_txo {}",
1741 channel_id,
1742 counterparty_node_id,
1743 new_funding_txo,
1744 );
1745
1746 let event = Event::SplicePending {
1747 channel_id,
1748 user_channel_id: UserChannelId(user_channel_id),
1749 counterparty_node_id,
1750 new_funding_txo,
1751 };
1752
1753 match self.event_queue.add_event(event).await {
1754 Ok(_) => {},
1755 Err(e) => {
1756 log_error!(self.logger, "Failed to push to event queue: {}", e);
1757 return Err(ReplayEvent());
1758 },
1759 };
1760 },
1761 LdkEvent::SpliceFailed {
1762 channel_id,
1763 user_channel_id,
1764 counterparty_node_id,
1765 abandoned_funding_txo,
1766 contributed_outputs,
1767 ..
1768 } => {
1769 if let Some(funding_txo) = abandoned_funding_txo {
1770 log_info!(
1771 self.logger,
1772 "Channel {} with counterparty {} failed splice with funding_txo {}",
1773 channel_id,
1774 counterparty_node_id,
1775 funding_txo,
1776 );
1777 } else {
1778 log_info!(
1779 self.logger,
1780 "Channel {} with counterparty {} failed splice",
1781 channel_id,
1782 counterparty_node_id,
1783 );
1784 }
1785
1786 let tx = bitcoin::Transaction {
1787 version: bitcoin::transaction::Version::TWO,
1788 lock_time: bitcoin::absolute::LockTime::ZERO,
1789 input: vec![],
1790 output: contributed_outputs,
1791 };
1792 if let Err(e) = self.wallet.cancel_tx(&tx) {
1793 log_error!(self.logger, "Failed reclaiming unused addresses: {}", e);
1794 return Err(ReplayEvent());
1795 }
1796
1797 let event = Event::SpliceFailed {
1798 channel_id,
1799 user_channel_id: UserChannelId(user_channel_id),
1800 counterparty_node_id,
1801 abandoned_funding_txo,
1802 };
1803
1804 match self.event_queue.add_event(event).await {
1805 Ok(_) => {},
1806 Err(e) => {
1807 log_error!(self.logger, "Failed to push to event queue: {}", e);
1808 return Err(ReplayEvent());
1809 },
1810 };
1811 },
1812 }
1813 Ok(())
1814 }
1815}
1816
1817#[cfg(test)]
1818mod tests {
1819 use std::sync::atomic::{AtomicU16, Ordering};
1820 use std::time::Duration;
1821
1822 use lightning::util::test_utils::TestLogger;
1823
1824 use super::*;
1825 use crate::io::test_utils::InMemoryStore;
1826
1827 #[tokio::test]
1828 async fn event_queue_persistence() {
1829 let store: Arc<DynStore> = Arc::new(InMemoryStore::new());
1830 let logger = Arc::new(TestLogger::new());
1831 let event_queue = Arc::new(EventQueue::new(Arc::clone(&store), Arc::clone(&logger)));
1832 assert_eq!(event_queue.next_event(), None);
1833
1834 let expected_event = Event::ChannelReady {
1835 channel_id: ChannelId([23u8; 32]),
1836 user_channel_id: UserChannelId(2323),
1837 counterparty_node_id: None,
1838 funding_txo: None,
1839 };
1840 event_queue.add_event(expected_event.clone()).await.unwrap();
1841
1842 for _ in 0..5 {
1844 assert_eq!(event_queue.next_event_async().await, expected_event);
1845 assert_eq!(event_queue.next_event(), Some(expected_event.clone()));
1846 }
1847
1848 let persisted_bytes = KVStore::read(
1850 &*store,
1851 EVENT_QUEUE_PERSISTENCE_PRIMARY_NAMESPACE,
1852 EVENT_QUEUE_PERSISTENCE_SECONDARY_NAMESPACE,
1853 EVENT_QUEUE_PERSISTENCE_KEY,
1854 )
1855 .await
1856 .unwrap();
1857 let deser_event_queue =
1858 EventQueue::read(&mut &persisted_bytes[..], (Arc::clone(&store), logger)).unwrap();
1859 assert_eq!(deser_event_queue.next_event_async().await, expected_event);
1860
1861 event_queue.event_handled().await.unwrap();
1862 assert_eq!(event_queue.next_event(), None);
1863 }
1864
1865 #[tokio::test]
1866 async fn event_queue_concurrency() {
1867 let store: Arc<DynStore> = Arc::new(InMemoryStore::new());
1868 let logger = Arc::new(TestLogger::new());
1869 let event_queue = Arc::new(EventQueue::new(Arc::clone(&store), Arc::clone(&logger)));
1870 assert_eq!(event_queue.next_event(), None);
1871
1872 let expected_event = Event::ChannelReady {
1873 channel_id: ChannelId([23u8; 32]),
1874 user_channel_id: UserChannelId(2323),
1875 counterparty_node_id: None,
1876 funding_txo: None,
1877 };
1878
1879 tokio::select! {
1881 _ = tokio::time::sleep(Duration::from_secs(1)) => {
1882 }
1884 _ = event_queue.next_event_async() => {
1885 panic!();
1886 }
1887 }
1888
1889 assert_eq!(event_queue.next_event(), None);
1890 let enqueued_events = AtomicU16::new(0);
1892 let received_events = AtomicU16::new(0);
1893 let mut delayed_enqueue = false;
1894
1895 for _ in 0..25 {
1896 event_queue.add_event(expected_event.clone()).await.unwrap();
1897 enqueued_events.fetch_add(1, Ordering::SeqCst);
1898 }
1899
1900 loop {
1901 tokio::select! {
1902 _ = tokio::time::sleep(Duration::from_millis(10)), if !delayed_enqueue => {
1903 event_queue.add_event(expected_event.clone()).await.unwrap();
1904 enqueued_events.fetch_add(1, Ordering::SeqCst);
1905 delayed_enqueue = true;
1906 }
1907 e = event_queue.next_event_async() => {
1908 assert_eq!(e, expected_event);
1909 event_queue.event_handled().await.unwrap();
1910 received_events.fetch_add(1, Ordering::SeqCst);
1911
1912 event_queue.add_event(expected_event.clone()).await.unwrap();
1913 enqueued_events.fetch_add(1, Ordering::SeqCst);
1914 }
1915 e = event_queue.next_event_async() => {
1916 assert_eq!(e, expected_event);
1917 event_queue.event_handled().await.unwrap();
1918 received_events.fetch_add(1, Ordering::SeqCst);
1919 }
1920 }
1921
1922 if delayed_enqueue
1923 && received_events.load(Ordering::SeqCst) == enqueued_events.load(Ordering::SeqCst)
1924 {
1925 break;
1926 }
1927 }
1928 assert_eq!(event_queue.next_event(), None);
1929 }
1930}