Skip to main content

fedimint_lnv2_client/
api.rs

1use std::collections::{BTreeMap, BTreeSet};
2
3use fedimint_api_client::api::{
4    FederationApiExt, FederationError, FederationResult, IModuleFederationApi, ServerResult,
5};
6#[cfg(feature = "cli")]
7use fedimint_core::module::ApiAuth;
8use fedimint_core::module::ApiRequestErased;
9use fedimint_core::runtime::{Duration, Instant, timeout};
10use fedimint_core::task::{MaybeSend, MaybeSync};
11use fedimint_core::util::SafeUrl;
12use fedimint_core::{NumPeersExt, OutPoint, PeerId, apply, async_trait_maybe_send};
13use fedimint_lnv2_common::ContractId;
14use fedimint_lnv2_common::contracts::IncomingContract;
15#[cfg(feature = "cli")]
16use fedimint_lnv2_common::endpoint_constants::{ADD_GATEWAY_ENDPOINT, REMOVE_GATEWAY_ENDPOINT};
17use fedimint_lnv2_common::endpoint_constants::{
18    AWAIT_INCOMING_CONTRACT_ENDPOINT, AWAIT_INCOMING_CONTRACTS_ENDPOINT, AWAIT_PREIMAGE_ENDPOINT,
19    CONSENSUS_BLOCK_COUNT_ENDPOINT, GATEWAYS_ENDPOINT, OUTGOING_CONTRACT_EXPIRATION_ENDPOINT,
20};
21use futures::StreamExt;
22use futures::stream::FuturesUnordered;
23use rand::seq::SliceRandom;
24
25#[cfg(test)]
26mod tests;
27
28/// How long [`LightningFederationApi::gateways`] keeps waiting for a threshold
29/// of guardians to answer once the first guardian has answered.
30///
31/// Waiting for more answers lets gateways listed by many guardians be ranked
32/// above a gateway listed only by the guardian that happened to answer first,
33/// while the bound keeps unreachable or failing guardians from stalling
34/// gateway selection.
35pub const GATEWAYS_GRACE_PERIOD: Duration = Duration::from_secs(5);
36
37#[apply(async_trait_maybe_send!)]
38pub trait LightningFederationApi {
39    async fn consensus_block_count(&self) -> FederationResult<u64>;
40
41    async fn await_incoming_contract(
42        &self,
43        contract_id: &ContractId,
44        expiration: u64,
45    ) -> Option<OutPoint>;
46
47    async fn await_preimage(&self, contract_id: OutPoint, expiration: u64) -> Option<[u8; 32]>;
48
49    async fn await_incoming_contracts(&self, start: u64, n: usize) -> (Vec<IncomingContract>, u64);
50
51    async fn outgoing_contract_expiration(
52        &self,
53        outpoint: OutPoint,
54    ) -> FederationResult<Option<(ContractId, u64)>>;
55
56    async fn gateways(&self) -> FederationResult<Vec<SafeUrl>>;
57
58    async fn gateways_from_peer(&self, peer: PeerId) -> ServerResult<Vec<SafeUrl>>;
59
60    #[cfg(feature = "cli")]
61    async fn add_gateway(&self, auth: ApiAuth, gateway: SafeUrl) -> FederationResult<bool>;
62
63    #[cfg(feature = "cli")]
64    async fn remove_gateway(&self, auth: ApiAuth, gateway: SafeUrl) -> FederationResult<bool>;
65}
66
67#[apply(async_trait_maybe_send!)]
68impl<T: ?Sized> LightningFederationApi for T
69where
70    T: IModuleFederationApi + MaybeSend + MaybeSync + 'static,
71{
72    async fn consensus_block_count(&self) -> FederationResult<u64> {
73        self.request_current_consensus(
74            CONSENSUS_BLOCK_COUNT_ENDPOINT.to_string(),
75            ApiRequestErased::new(()),
76        )
77        .await
78    }
79
80    async fn await_incoming_contract(
81        &self,
82        contract_id: &ContractId,
83        expiration: u64,
84    ) -> Option<OutPoint> {
85        self.request_current_consensus_retry::<Option<OutPoint>>(
86            AWAIT_INCOMING_CONTRACT_ENDPOINT.to_string(),
87            ApiRequestErased::new((contract_id, expiration)),
88        )
89        .await
90    }
91
92    async fn await_preimage(&self, outpoint: OutPoint, expiration: u64) -> Option<[u8; 32]> {
93        self.request_current_consensus_retry(
94            AWAIT_PREIMAGE_ENDPOINT.to_string(),
95            ApiRequestErased::new((outpoint, expiration)),
96        )
97        .await
98    }
99
100    async fn await_incoming_contracts(&self, start: u64, n: usize) -> (Vec<IncomingContract>, u64) {
101        self.request_current_consensus_retry(
102            AWAIT_INCOMING_CONTRACTS_ENDPOINT.to_string(),
103            ApiRequestErased::new((start, n)),
104        )
105        .await
106    }
107
108    async fn outgoing_contract_expiration(
109        &self,
110        outpoint: OutPoint,
111    ) -> FederationResult<Option<(ContractId, u64)>> {
112        self.request_current_consensus(
113            OUTGOING_CONTRACT_EXPIRATION_ENDPOINT.to_string(),
114            ApiRequestErased::new(outpoint),
115        )
116        .await
117    }
118
119    async fn gateways(&self) -> FederationResult<Vec<SafeUrl>> {
120        // Unlike `request_with_strategy` this does not give up once `f + 1`
121        // guardians have failed: any guardian's list is usable, so the query
122        // only fails if every guardian failed.
123        let mut requests = self
124            .all_peers()
125            .iter()
126            .map(|peer| async move {
127                let response = self
128                    .request_single_peer::<Vec<SafeUrl>>(
129                        GATEWAYS_ENDPOINT.to_string(),
130                        ApiRequestErased::default(),
131                        *peer,
132                    )
133                    .await;
134
135                (*peer, response)
136            })
137            .collect::<FuturesUnordered<_>>();
138
139        let threshold = self.all_peers().to_num_peers().threshold();
140        let mut gateways = BTreeMap::new();
141        let mut peer_errors = BTreeMap::new();
142        // Starts with the first answer; until then we wait for as long as
143        // some guardian may still answer.
144        let mut deadline = None;
145
146        while gateways.len() < threshold {
147            let next = match deadline {
148                Some(deadline) => {
149                    match timeout(
150                        Instant::saturating_duration_since(&deadline, Instant::now()),
151                        requests.next(),
152                    )
153                    .await
154                    {
155                        Ok(next) => next,
156                        Err(_elapsed) => break,
157                    }
158                }
159                None => requests.next().await,
160            };
161
162            let Some((peer, response)) = next else {
163                break;
164            };
165
166            match response {
167                Ok(response) => {
168                    gateways.insert(peer, response);
169
170                    deadline.get_or_insert_with(|| Instant::now() + GATEWAYS_GRACE_PERIOD);
171                }
172                Err(e) => {
173                    e.report_if_unusual(peer, "Gateways");
174
175                    peer_errors.insert(peer, e);
176                }
177            }
178        }
179
180        if gateways.is_empty() {
181            return Err(FederationError::peer_errors(
182                GATEWAYS_ENDPOINT,
183                (),
184                peer_errors,
185            ));
186        }
187
188        let mut union = gateways
189            .values()
190            .flatten()
191            .cloned()
192            .collect::<BTreeSet<SafeUrl>>()
193            .into_iter()
194            .collect::<Vec<SafeUrl>>();
195
196        // Shuffling the gateways ensures that payments are distributed over the
197        // gateways evenly.
198        union.shuffle(&mut rand::thread_rng());
199
200        // Gateways listed by more guardians come first, so a gateway listed by
201        // a single guardian does not take precedence over the ones the other
202        // guardians agree on.
203        union.sort_by_cached_key(|r| {
204            gateways
205                .values()
206                .filter(|response| !response.contains(r))
207                .count()
208        });
209
210        Ok(union)
211    }
212
213    async fn gateways_from_peer(&self, peer: PeerId) -> ServerResult<Vec<SafeUrl>> {
214        let gateways = self
215            .request_single_peer::<Vec<SafeUrl>>(
216                GATEWAYS_ENDPOINT.to_string(),
217                ApiRequestErased::default(),
218                peer,
219            )
220            .await?;
221
222        Ok(gateways)
223    }
224
225    #[cfg(feature = "cli")]
226    async fn add_gateway(&self, auth: ApiAuth, gateway: SafeUrl) -> FederationResult<bool> {
227        let is_new_entry: bool = self
228            .request_admin(ADD_GATEWAY_ENDPOINT, ApiRequestErased::new(gateway), auth)
229            .await?;
230
231        Ok(is_new_entry)
232    }
233
234    #[cfg(feature = "cli")]
235    async fn remove_gateway(&self, auth: ApiAuth, gateway: SafeUrl) -> FederationResult<bool> {
236        let entry_existed: bool = self
237            .request_admin(
238                REMOVE_GATEWAY_ENDPOINT,
239                ApiRequestErased::new(gateway),
240                auth,
241            )
242            .await?;
243
244        Ok(entry_existed)
245    }
246}