ln_gateway/gateway_module_v2/
events.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
use std::time::SystemTime;

use fedimint_core::config::FederationId;
use fedimint_core::core::ModuleKind;
use fedimint_core::Amount;
use fedimint_eventlog::{Event, EventKind, PersistedLogEntry};
use fedimint_lnv2_common::contracts::{Commitment, OutgoingContract, PaymentImage};
use serde::{Deserialize, Serialize};
use serde_millis;

use super::send_sm::Cancelled;
use crate::events::{filter_events, join_events, StructuredPaymentEvents};

/// Event that is emitted when an outgoing payment attempt is initiated.
#[derive(Serialize, Deserialize, Debug)]
pub struct OutgoingPaymentStarted {
    /// The timestamp that the operation begins, including the API calls to the
    /// federation to get the consensus block height.
    #[serde(with = "serde_millis")]
    pub operation_start: SystemTime,

    /// The outgoing contract for this payment.
    pub outgoing_contract: OutgoingContract,

    /// The minimum amount that must be escrowed for the payment (includes the
    /// gateway's fee)
    pub min_contract_amount: Amount,

    /// The amount requested in the invoice.
    pub invoice_amount: Amount,

    /// The max delay of the payment in blocks.
    pub max_delay: u64,
}

impl Event for OutgoingPaymentStarted {
    const MODULE: Option<ModuleKind> = Some(fedimint_lnv2_common::KIND);

    const KIND: EventKind = EventKind::from_static("outgoing-payment-started");
}

/// Event that is emitted when an outgoing payment attempt has succeeded.
#[derive(Serialize, Deserialize, Debug)]
pub struct OutgoingPaymentSucceeded {
    /// The payment image of the invoice that was paid.
    pub payment_image: PaymentImage,

    /// The target federation ID if a swap was performed, otherwise `None`.
    pub target_federation: Option<FederationId>,
}

impl Event for OutgoingPaymentSucceeded {
    const MODULE: Option<ModuleKind> = Some(fedimint_lnv2_common::KIND);

    const KIND: EventKind = EventKind::from_static("outgoing-payment-succeeded");
}

/// Event that is emitted when an outgoing payment attempt has failed.
#[derive(Serialize, Deserialize, Debug)]
pub struct OutgoingPaymentFailed {
    /// The payment image of the invoice that failed.
    pub payment_image: PaymentImage,

    /// The reason the outgoing payment was cancelled.
    pub error: Cancelled,
}

impl Event for OutgoingPaymentFailed {
    const MODULE: Option<ModuleKind> = Some(fedimint_lnv2_common::KIND);

    const KIND: EventKind = EventKind::from_static("outgoing-payment-failed");
}

/// Event that is emitted when an incoming payment attempt has started. Includes
/// both internal swaps and outside LN payments.
#[derive(Serialize, Deserialize, Debug)]
pub struct IncomingPaymentStarted {
    /// The timestamp that the operation begins, including any metadata checks
    /// before the state machine has spawned.
    #[serde(with = "serde_millis")]
    pub operation_start: SystemTime,

    /// The commitment for the incoming contract.
    pub incoming_contract_commitment: Commitment,

    /// The amount requested in the invoice.
    pub invoice_amount: Amount,
}

impl Event for IncomingPaymentStarted {
    const MODULE: Option<ModuleKind> = Some(fedimint_lnv2_common::KIND);

    const KIND: EventKind = EventKind::from_static("incoming-payment-started");
}

/// Event that is emitted when an incoming payment attempt has succeeded.
/// Includes both internal swaps and outside LN payments.
#[derive(Serialize, Deserialize, Debug)]
pub struct IncomingPaymentSucceeded {
    /// The payment image of the invoice that was paid.
    pub payment_image: PaymentImage,
}

impl Event for IncomingPaymentSucceeded {
    const MODULE: Option<ModuleKind> = Some(fedimint_lnv2_common::KIND);

    const KIND: EventKind = EventKind::from_static("incoming-payment-succeeded");
}

/// Event that is emitted when an incoming payment attempt has failed.
#[derive(Serialize, Deserialize, Debug)]
pub struct IncomingPaymentFailed {
    /// The payment image of the invoice that failed
    pub payment_image: PaymentImage,

    /// The reason the incoming payment failed
    pub error: String,
}

impl Event for IncomingPaymentFailed {
    const MODULE: Option<ModuleKind> = Some(fedimint_lnv2_common::KIND);

    const KIND: EventKind = EventKind::from_static("incoming-payment-failed");
}

/// Event that is emitted when a preimage is revealed to the Lightning network.
/// Only emitted for payments that are received from an external Lightning node,
/// not internal swaps.
#[derive(Serialize, Deserialize, Debug)]
pub struct CompleteLightningPaymentSucceeded {
    /// The payment image of the invoice that was paid.
    pub payment_image: PaymentImage,
}

impl Event for CompleteLightningPaymentSucceeded {
    const MODULE: Option<ModuleKind> = Some(fedimint_lnv2_common::KIND);

    const KIND: EventKind = EventKind::from_static("complete-lightning-payment-succeeded");
}

/// Computes the `StructurePaymentEvents` for all LNv2 payments.
///
/// Filters the event set for LNv2 events and joins them together.
pub fn compute_lnv2_stats(
    all_events: &[PersistedLogEntry],
) -> (StructuredPaymentEvents, StructuredPaymentEvents) {
    let outgoing_start_events = filter_events(
        all_events,
        OutgoingPaymentStarted::KIND,
        fedimint_lnv2_common::KIND,
    )
    .collect::<Vec<_>>();
    let outgoing_success_events = filter_events(
        all_events,
        OutgoingPaymentSucceeded::KIND,
        fedimint_lnv2_common::KIND,
    )
    .collect::<Vec<_>>();
    let outgoing_failure_events = filter_events(
        all_events,
        OutgoingPaymentFailed::KIND,
        fedimint_lnv2_common::KIND,
    )
    .collect::<Vec<_>>();

    let outgoing_success_stats =
        join_events::<OutgoingPaymentStarted, OutgoingPaymentSucceeded, (u64, Amount)>(
            &outgoing_start_events,
            &outgoing_success_events,
            |start_event, success_event, latency| {
                if start_event.outgoing_contract.payment_image == success_event.payment_image {
                    start_event
                        .min_contract_amount
                        .checked_sub(start_event.invoice_amount)
                        .map(|fee| (latency, fee))
                } else {
                    None
                }
            },
        )
        .collect::<Vec<_>>();

    let outgoing_failure_stats = join_events::<OutgoingPaymentStarted, OutgoingPaymentFailed, u64>(
        &outgoing_start_events,
        &outgoing_failure_events,
        |start_event, fail_event, latency| {
            if start_event.outgoing_contract.payment_image == fail_event.payment_image {
                Some(latency)
            } else {
                None
            }
        },
    )
    .collect::<Vec<_>>();

    let incoming_start_events = filter_events(
        all_events,
        IncomingPaymentStarted::KIND,
        fedimint_lnv2_common::KIND,
    )
    .collect::<Vec<_>>();
    let incoming_success_events = filter_events(
        all_events,
        IncomingPaymentSucceeded::KIND,
        fedimint_lnv2_common::KIND,
    )
    .collect::<Vec<_>>();
    let incoming_failure_events = filter_events(
        all_events,
        IncomingPaymentFailed::KIND,
        fedimint_lnv2_common::KIND,
    )
    .collect::<Vec<_>>();

    let incoming_success_stats =
        join_events::<IncomingPaymentStarted, IncomingPaymentSucceeded, (u64, Amount)>(
            &incoming_start_events,
            &incoming_success_events,
            |start_event, success_event, latency| {
                if start_event.incoming_contract_commitment.payment_image
                    == success_event.payment_image
                {
                    start_event
                        .invoice_amount
                        .checked_sub(start_event.incoming_contract_commitment.amount)
                        .map(|fee| (latency, fee))
                } else {
                    None
                }
            },
        )
        .collect::<Vec<_>>();

    let incoming_failure_stats = join_events::<IncomingPaymentStarted, IncomingPaymentFailed, u64>(
        &incoming_start_events,
        &incoming_failure_events,
        |start_event, fail_event, latency| {
            if start_event.incoming_contract_commitment.payment_image == fail_event.payment_image {
                Some(latency)
            } else {
                None
            }
        },
    )
    .collect::<Vec<_>>();

    let outgoing = StructuredPaymentEvents::new(&outgoing_success_stats, outgoing_failure_stats);
    let incoming = StructuredPaymentEvents::new(&incoming_success_stats, incoming_failure_stats);
    (outgoing, incoming)
}