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
//! Payment Stream
//!
//! This future Stream will wait events for a Mint Quote be paid. If it is for a Bolt12 it will not stop
//! but it will eventually error on a Timeout.
//!
//! Bolt11 will emit a single event.
use std::sync::Arc;
use std::task::Poll;
use cdk_common::{Amount, Error, MeltQuoteState, MintQuoteState, NotificationPayload};
use futures::future::join_all;
use futures::stream::FuturesUnordered;
use futures::{FutureExt, Stream, StreamExt};
use tokio_util::sync::CancellationToken;
use super::RecvFuture;
use crate::event::MintEvent;
use crate::wallet::subscription::ActiveSubscription;
use crate::{Wallet, WalletSubscription};
type SubscribeReceived = (Option<MintEvent<String>>, Vec<ActiveSubscription>);
type PaymentValue = (String, Option<Amount>);
/// PaymentWaiter
#[allow(missing_debug_implementations)]
pub struct PaymentStream<'a> {
wallet: &'a Wallet,
filters: Option<Vec<WalletSubscription>>,
is_finalized: bool,
active_subscription: Option<Vec<ActiveSubscription>>,
cancel_token: CancellationToken,
// Future events
subscriber_future: Option<RecvFuture<'a, Vec<ActiveSubscription>>>,
subscription_receiver_future: Option<RecvFuture<'static, SubscribeReceived>>,
cancellation_future: Option<RecvFuture<'a, ()>>,
}
impl<'a> PaymentStream<'a> {
/// Creates a new instance of the
pub fn new(wallet: &'a Wallet, filters: Vec<WalletSubscription>) -> Self {
Self {
wallet,
filters: Some(filters),
is_finalized: false,
active_subscription: None,
cancel_token: Default::default(),
subscriber_future: None,
subscription_receiver_future: None,
cancellation_future: None,
}
}
/// Get cancellation token
pub fn get_cancel_token(&self) -> CancellationToken {
self.cancel_token.clone()
}
/// Creating a wallet subscription is an async event, this may change in the future, but for now,
/// creating a new Subscription should be polled, as any other async event. This function will
/// return None if the subscription is already active, Some(()) otherwise
fn poll_init_subscription(&mut self, cx: &mut std::task::Context<'_>) -> Option<()> {
if let Some(filters) = self.filters.take() {
let wallet = self.wallet;
self.subscriber_future = Some(Box::pin(async move {
let results = join_all(filters.into_iter().map(|w| wallet.subscribe(w))).await;
// Collect successful subscriptions, log errors
results
.into_iter()
.filter_map(|r| match r {
Ok(sub) => Some(sub),
Err(e) => {
tracing::warn!("Failed to create subscription: {}", e);
None
}
})
.collect::<Vec<_>>()
}));
}
let mut subscriber_future = self.subscriber_future.take()?;
match subscriber_future.poll_unpin(cx) {
Poll::Pending => {
self.subscriber_future = Some(subscriber_future);
Some(())
}
Poll::Ready(active_subscription) => {
self.active_subscription = Some(active_subscription);
None
}
}
}
/// Checks if the stream has been externally cancelled
fn poll_cancel(&mut self, cx: &mut std::task::Context<'_>) -> bool {
let mut cancellation_future = self.cancellation_future.take().unwrap_or_else(|| {
let cancel_token = self.cancel_token.clone();
Box::pin(async move { cancel_token.cancelled().await })
});
if cancellation_future.poll_unpin(cx).is_ready() {
self.subscription_receiver_future = None;
true
} else {
self.cancellation_future = Some(cancellation_future);
false
}
}
/// Polls the subscription for any new event
fn poll_event(
&mut self,
cx: &mut std::task::Context<'_>,
) -> Poll<Option<Result<PaymentValue, Error>>> {
let (subscription_receiver_future, active_subscription) = (
self.subscription_receiver_future.take(),
self.active_subscription.take(),
);
if subscription_receiver_future.is_none() && active_subscription.is_none() {
// Unexpected state, we should have an in-flight future or the active_subscription to
// create the future to read an event
return Poll::Ready(Some(Err(Error::Internal)));
}
let localstore = Arc::clone(&self.wallet.localstore);
let mut receiver = subscription_receiver_future.unwrap_or_else(|| {
let mut subscription_receiver =
active_subscription.expect("active subscription object");
Box::pin(async move {
let mut futures: FuturesUnordered<_> = subscription_receiver
.iter_mut()
.map(|sub| sub.recv())
.collect();
if let Some(res) = futures.next().await {
drop(futures);
if let Some(event) = &res {
match event.inner() {
NotificationPayload::MintQuoteBolt11Response(info) => {
let quote_id = info.quote.clone();
if let Ok(Some(mut quote)) =
localstore.get_mint_quote("e_id).await
{
quote.state = info.state;
quote.amount_paid = info.amount.unwrap_or(Amount::ZERO);
if let Err(e) = localstore.add_mint_quote(quote).await {
tracing::warn!("Failed to update quote state: {}", e);
}
}
}
NotificationPayload::MintQuoteBolt12Response(info) => {
let quote_id = info.quote.clone();
if let Ok(Some(mut quote)) =
localstore.get_mint_quote("e_id).await
{
quote.amount_paid = info.amount_paid;
quote.amount_issued = info.amount_issued;
if let Err(e) = localstore.add_mint_quote(quote).await {
tracing::warn!("Failed to update quote state: {}", e);
}
}
}
NotificationPayload::MintQuoteOnchainResponse(info) => {
let quote_id = info.quote.clone();
if let Ok(Some(mut quote)) =
localstore.get_mint_quote("e_id).await
{
quote.amount_paid = info.amount_paid;
quote.amount_issued = info.amount_issued;
if let Err(e) = localstore.add_mint_quote(quote).await {
tracing::warn!("Failed to update quote state: {}", e);
}
}
}
NotificationPayload::CustomMintQuoteResponse(_, info) => {
let quote_id = info.quote.clone();
if let Ok(Some(mut quote)) =
localstore.get_mint_quote("e_id).await
{
quote.amount_paid = info.amount_paid;
quote.amount_issued = info.amount_issued;
if let Err(e) = localstore.add_mint_quote(quote).await {
tracing::warn!("Failed to update quote state: {}", e);
}
}
}
_ => (),
}
}
return (res, subscription_receiver);
}
drop(futures);
(None, subscription_receiver)
})
});
match receiver.poll_unpin(cx) {
Poll::Pending => {
self.subscription_receiver_future = Some(receiver);
Poll::Pending
}
Poll::Ready((notification, subscription)) => {
tracing::debug!("Receive payment notification {:?}", notification);
// This future is now fulfilled, put the active_subscription again back to object. Next time next().await is called,
// the future will be created in subscription_receiver_future.
self.active_subscription = Some(subscription);
self.cancellation_future = None; // resets timeout
match notification {
None => {
self.is_finalized = true;
Poll::Ready(None)
}
Some(info) => {
match info.into_inner() {
NotificationPayload::MintQuoteBolt11Response(info)
if info.state == MintQuoteState::Paid =>
{
self.is_finalized = true;
return Poll::Ready(Some(Ok((info.quote, None))));
}
NotificationPayload::MintQuoteBolt12Response(info) => {
let to_be_issued = info.amount_paid - info.amount_issued;
if to_be_issued > Amount::ZERO {
return Poll::Ready(Some(Ok((info.quote, Some(to_be_issued)))));
}
}
NotificationPayload::MintQuoteOnchainResponse(info) => {
let to_be_issued = info.amount_paid - info.amount_issued;
if to_be_issued > Amount::ZERO {
return Poll::Ready(Some(Ok((info.quote, Some(to_be_issued)))));
}
}
NotificationPayload::CustomMintQuoteResponse(_, info) => {
let to_be_issued = info.amount_paid - info.amount_issued;
if to_be_issued > Amount::ZERO {
return Poll::Ready(Some(Ok((info.quote, Some(to_be_issued)))));
}
}
NotificationPayload::MeltQuoteBolt11Response(info)
if info.state == MeltQuoteState::Paid =>
{
self.is_finalized = true;
return Poll::Ready(Some(Ok((info.quote, None))));
}
NotificationPayload::MeltQuoteOnchainResponse(info)
if info.state == MeltQuoteState::Paid =>
{
self.is_finalized = true;
return Poll::Ready(Some(Ok((info.quote, None))));
}
_ => {}
}
// We got an event but it is not what was expected, we need to call `recv`
// again, and to copy-paste this is a recursive call that should be resolved
// to a Poll::Pending *but* will trigger the future execution
self.poll_event(cx)
}
}
}
}
}
}
impl Stream for PaymentStream<'_> {
type Item = Result<PaymentValue, Error>;
fn poll_next(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
let this = self.get_mut();
if this.is_finalized {
// end of stream
return Poll::Ready(None);
}
if this.poll_cancel(cx) {
return Poll::Ready(None);
}
if this.poll_init_subscription(cx).is_some() {
return Poll::Pending;
}
this.poll_event(cx)
}
}