1use std::collections::BTreeMap;
2use std::time::Duration;
3use std::{cmp, ops};
4
5use bitcoin::secp256k1::PublicKey;
6use fedimint_api_client::api::{
7 DynGlobalApi, VERSION_THAT_INTRODUCED_GET_SESSION_STATUS,
8 VERSION_THAT_INTRODUCED_GET_SESSION_STATUS_V2,
9};
10use fedimint_core::db::DatabaseTransaction;
11use fedimint_core::encoding::{Decodable, Encodable};
12use fedimint_core::epoch::ConsensusItem;
13use fedimint_core::module::registry::ModuleDecoderRegistry;
14use fedimint_core::module::{ApiVersion, ModuleCommon};
15use fedimint_core::session_outcome::{AcceptedItem, SessionStatus};
16use fedimint_core::task::{MaybeSend, MaybeSync, ShuttingDownError, TaskGroup};
17use fedimint_core::transaction::Transaction;
18use fedimint_core::util::FmtCompactAnyhow as _;
19use fedimint_core::{Amount, OutPoint, PeerId, apply, async_trait_maybe_send};
20use fedimint_logging::LOG_CLIENT_RECOVERY;
21use futures::{Stream, StreamExt as _};
22use rand::{Rng as _, thread_rng};
23use serde::{Deserialize, Serialize};
24use tracing::{debug, trace, warn};
25
26use super::{ClientModuleInit, ClientModuleRecoverArgs};
27use crate::module::recovery::RecoveryProgress;
28use crate::module::{ClientContext, ClientModule};
29
30#[allow(clippy::struct_field_names)]
31#[derive(Debug, Clone, Eq, PartialEq, Encodable, Decodable, Serialize, Deserialize)]
32pub struct RecoveryFromHistoryCommon {
34 start_session: u64,
35 next_session: u64,
36 end_session: u64,
37}
38
39impl RecoveryFromHistoryCommon {
40 pub fn new(start_session: u64, next_session: u64, end_session: u64) -> Self {
41 Self {
42 start_session,
43 next_session,
44 end_session,
45 }
46 }
47}
48
49#[apply(async_trait_maybe_send!)]
53pub trait RecoveryFromHistory: std::fmt::Debug + MaybeSend + MaybeSync + Clone {
54 type Init: ClientModuleInit;
56
57 async fn new(
59 init: &Self::Init,
60 args: &ClientModuleRecoverArgs<Self::Init>,
61 snapshot: Option<&<<Self::Init as ClientModuleInit>::Module as ClientModule>::Backup>,
62 ) -> anyhow::Result<(Self, u64)>;
63
64 async fn load_dbtx(
70 init: &Self::Init,
71 dbtx: &mut DatabaseTransaction<'_>,
72 args: &ClientModuleRecoverArgs<Self::Init>,
73 ) -> anyhow::Result<Option<(Self, RecoveryFromHistoryCommon)>>;
74
75 async fn store_dbtx(
79 &self,
80 dbtx: &mut DatabaseTransaction<'_>,
81 common: &RecoveryFromHistoryCommon,
82 );
83
84 async fn delete_dbtx(&self, dbtx: &mut DatabaseTransaction<'_>);
88
89 async fn load_finalized(dbtx: &mut DatabaseTransaction<'_>) -> Option<bool>;
93
94 async fn store_finalized(dbtx: &mut DatabaseTransaction<'_>, state: bool);
98
99 async fn handle_session(
109 &mut self,
110 client_ctx: &ClientContext<<Self::Init as ClientModuleInit>::Module>,
111 session_idx: u64,
112 session_items: &Vec<AcceptedItem>,
113 ) -> anyhow::Result<()> {
114 for accepted_item in session_items {
115 if let ConsensusItem::Transaction(ref transaction) = accepted_item.item {
116 self.handle_transaction(client_ctx, transaction, session_idx)
117 .await?;
118 }
119 }
120 Ok(())
121 }
122
123 async fn handle_transaction(
134 &mut self,
135 client_ctx: &ClientContext<<Self::Init as ClientModuleInit>::Module>,
136 transaction: &Transaction,
137 session_idx: u64,
138 ) -> anyhow::Result<()> {
139 trace!(
140 target: LOG_CLIENT_RECOVERY,
141 tx_hash = %transaction.tx_hash(),
142 input_num = transaction.inputs.len(),
143 output_num = transaction.outputs.len(),
144 "processing transaction"
145 );
146
147 for (idx, input) in transaction.inputs.iter().enumerate() {
148 trace!(
149 target: LOG_CLIENT_RECOVERY,
150 tx_hash = %transaction.tx_hash(),
151 idx,
152 module_id = input.module_instance_id(),
153 "found transaction input"
154 );
155
156 if let Some(own_input) = client_ctx.input_from_dyn(input) {
157 self.handle_input(client_ctx, idx, own_input, session_idx)
158 .await?;
159 }
160 }
161
162 for (out_idx, output) in transaction.outputs.iter().enumerate() {
163 trace!(
164 target: LOG_CLIENT_RECOVERY,
165 tx_hash = %transaction.tx_hash(),
166 idx = out_idx,
167 module_id = output.module_instance_id(),
168 "found transaction output"
169 );
170
171 if let Some(own_output) = client_ctx.output_from_dyn(output) {
172 let out_point = OutPoint {
173 txid: transaction.tx_hash(),
174 out_idx: out_idx as u64,
175 };
176
177 self.handle_output(client_ctx, out_point, own_output, session_idx)
178 .await?;
179 }
180 }
181
182 Ok(())
183 }
184
185 async fn handle_input(
189 &mut self,
190 _client_ctx: &ClientContext<<Self::Init as ClientModuleInit>::Module>,
191 _idx: usize,
192 _input: &<<<Self::Init as ClientModuleInit>::Module as ClientModule>::Common as ModuleCommon>::Input,
193 _session_idx: u64,
194 ) -> anyhow::Result<()> {
195 Ok(())
196 }
197
198 async fn handle_output(
202 &mut self,
203 _client_ctx: &ClientContext<<Self::Init as ClientModuleInit>::Module>,
204 _out_point: OutPoint,
205 _output: &<<<Self::Init as ClientModuleInit>::Module as ClientModule>::Common as ModuleCommon>::Output,
206 _session_idx: u64,
207 ) -> anyhow::Result<()> {
208 Ok(())
209 }
210
211 async fn pre_finalize(&mut self) -> anyhow::Result<()> {
214 Ok(())
215 }
216
217 async fn finalize_dbtx(
230 &self,
231 dbtx: &mut DatabaseTransaction<'_>,
232 ) -> anyhow::Result<Option<Amount>>;
233}
234
235impl<Init> ClientModuleRecoverArgs<Init>
236where
237 Init: ClientModuleInit,
238{
239 pub async fn recover_from_history<Recovery>(
247 &self,
248 init: &Init,
249 snapshot: Option<&<<Init as ClientModuleInit>::Module as ClientModule>::Backup>,
250 ) -> anyhow::Result<Option<Amount>>
251 where
252 Recovery: RecoveryFromHistory<Init = Init> + std::fmt::Debug,
253 {
254 fn fetch_block_stream<'a>(
259 api: DynGlobalApi,
260 core_api_version: ApiVersion,
261 decoders: ModuleDecoderRegistry,
262 epoch_range: ops::Range<u64>,
263 broadcast_public_keys: Option<BTreeMap<PeerId, PublicKey>>,
264 task_group: TaskGroup,
265 ) -> impl futures::Stream<Item = Result<(u64, Vec<AcceptedItem>), ShuttingDownError>> + 'a
266 {
267 let parallelism_level =
269 if core_api_version < VERSION_THAT_INTRODUCED_GET_SESSION_STATUS_V2 {
270 64
271 } else {
272 128
273 };
274
275 futures::stream::iter(epoch_range.clone())
276 .map(move |session_idx| {
277 let api = api.clone();
278 let decoders = decoders.clone().with_fallback();
281 let task_group = task_group.clone();
282 let broadcast_public_keys = broadcast_public_keys.clone();
283
284 Box::pin(async move {
285 task_group.spawn_cancellable("recovery fetch block", async move {
289
290 let mut retry_sleep = Duration::from_millis(10);
291 let block = loop {
292 trace!(target: LOG_CLIENT_RECOVERY, session_idx, "Awaiting signed block");
293
294 let items_res = if core_api_version < VERSION_THAT_INTRODUCED_GET_SESSION_STATUS {
295 api.await_block(session_idx, &decoders).await.map(|s| s.items)
296 } else {
297 api.get_session_status(session_idx, &decoders, core_api_version, broadcast_public_keys.as_ref()).await.map(|s| match s {
298 SessionStatus::Initial => panic!("Federation missing session that existed when we started recovery"),
299 SessionStatus::Pending(items) => items,
300 SessionStatus::Complete(s) => s.items,
301 })
302 };
303
304 match items_res {
305 Ok(block) => {
306 trace!(target: LOG_CLIENT_RECOVERY, session_idx, "Got signed session");
307 break block
308 },
309 Err(err) => {
310 const MAX_SLEEP: Duration = Duration::from_mins(2);
311
312 warn!(target: LOG_CLIENT_RECOVERY, err = %err.fmt_compact_anyhow(), session_idx, "Error trying to fetch signed block");
313 if retry_sleep <= MAX_SLEEP {
316 retry_sleep = retry_sleep
317 + thread_rng().gen_range(Duration::ZERO..=retry_sleep);
318 }
319 fedimint_core::runtime::sleep(cmp::min(retry_sleep, MAX_SLEEP))
320 .await;
321 }
322 }
323 };
324
325 (session_idx, block)
326 }).await.expect("Can't fail")
327 })
328 })
329 .buffered(parallelism_level)
330 }
331
332 async fn make_progress<Init, Recovery: RecoveryFromHistory<Init = Init>>(
334 client_ctx: &ClientContext<<Init as ClientModuleInit>::Module>,
335 common_state: &mut RecoveryFromHistoryCommon,
336 state: &mut Recovery,
337 block_stream: &mut (
338 impl Stream<Item = Result<(u64, Vec<AcceptedItem>), ShuttingDownError>> + Unpin
339 ),
340 ) -> anyhow::Result<()>
341 where
342 Init: ClientModuleInit,
343 {
344 const PROGRESS_SNAPSHOT_BLOCKS: u64 = 5000;
349
350 let start = fedimint_core::time::now();
351
352 let block_range = common_state.next_session
353 ..cmp::min(
354 common_state
355 .next_session
356 .wrapping_add(PROGRESS_SNAPSHOT_BLOCKS),
357 common_state.end_session,
358 );
359
360 for _ in block_range {
361 let Some(res) = block_stream.next().await else {
362 break;
363 };
364
365 let (session_idx, accepted_items) = res?;
366
367 assert_eq!(common_state.next_session, session_idx);
368 state
369 .handle_session(client_ctx, session_idx, &accepted_items)
370 .await?;
371
372 common_state.next_session += 1;
373
374 if Duration::from_secs(10)
375 < fedimint_core::time::now()
376 .duration_since(start)
377 .unwrap_or_default()
378 {
379 break;
380 }
381 }
382
383 Ok(())
384 }
385
386 let db = self.db();
387 let client_ctx = self.context();
388
389 if Recovery::load_finalized(&mut db.begin_transaction_nc().await)
390 .await
391 .unwrap_or_default()
392 {
393 warn!(
414 target: LOG_CLIENT_RECOVERY,
415 "Previously finalized, exiting"
416 );
417 return Ok(None);
418 }
419 let current_session_count = client_ctx.global_api().session_count().await?;
420 debug!(target: LOG_CLIENT_RECOVERY, session_count = current_session_count, "Current session count");
421
422 let (mut state, mut common_state) =
423 if let Some((state, common_state)) = Recovery::load_dbtx(init, &mut db.begin_transaction_nc().await, self).await? {
426 (state, common_state)
427 } else {
428 let (state, start_session) = Recovery::new(init, self, snapshot).await?;
429
430 debug!(target: LOG_CLIENT_RECOVERY, start_session, "Recovery start session");
431 (state,
432 RecoveryFromHistoryCommon {
433 start_session,
434 next_session: start_session,
435 end_session: current_session_count + 1,
436 })
437 };
438
439 let block_stream_session_range = common_state.next_session..common_state.end_session;
440 debug!(target: LOG_CLIENT_RECOVERY, range = ?block_stream_session_range, "Starting block streaming");
441
442 let mut block_stream = fetch_block_stream(
443 self.api().clone(),
444 *self.core_api_version(),
445 client_ctx.decoders(),
446 block_stream_session_range,
447 client_ctx
448 .get_config()
449 .await
450 .global
451 .broadcast_public_keys
452 .clone(),
453 self.task_group().clone(),
454 );
455 let client_ctx = self.context();
456
457 while common_state.next_session < common_state.end_session {
458 make_progress(
459 &client_ctx,
460 &mut common_state,
461 &mut state,
462 &mut block_stream,
463 )
464 .await?;
465
466 let mut dbtx = db.begin_transaction().await;
467 state.store_dbtx(&mut dbtx.to_ref_nc(), &common_state).await;
468 dbtx.commit_tx().await;
469
470 self.update_recovery_progress(RecoveryProgress {
471 complete: (common_state.next_session - common_state.start_session)
472 .try_into()
473 .unwrap_or(u32::MAX),
474 total: (common_state.end_session - common_state.start_session)
475 .try_into()
476 .unwrap_or(u32::MAX),
477 });
478 }
479
480 state.pre_finalize().await?;
481
482 let mut dbtx = db.begin_transaction().await;
483 state.store_dbtx(&mut dbtx.to_ref_nc(), &common_state).await;
484 dbtx.commit_tx().await;
485
486 debug!(
487 target: LOG_CLIENT_RECOVERY,
488 ?state,
489 "Finalizing restore"
490 );
491
492 let recovered_amount = db
493 .autocommit(
494 |dbtx, _| {
495 let state = state.clone();
496 {
497 Box::pin(async move {
498 state.delete_dbtx(dbtx).await;
499 let recovered_amount = state.finalize_dbtx(dbtx).await?;
500 Recovery::store_finalized(dbtx, true).await;
501
502 Ok::<_, anyhow::Error>(recovered_amount)
503 })
504 }
505 },
506 None,
507 )
508 .await?;
509
510 Ok(recovered_amount)
511 }
512}