1use std::cmp;
2use std::collections::BTreeSet;
3use std::convert::Infallible;
4use std::time::{Duration, SystemTime};
5
6use bitcoin::ScriptBuf;
7use fedimint_api_client::api::{DynModuleApi, FederationError};
8use fedimint_bitcoind::{BitcoinRpcError, DynBitcoindRpc};
9use fedimint_client_module::module::{ClientContext, OutPointRange};
10use fedimint_client_module::transaction::{ClientInput, ClientInputBundle};
11use fedimint_core::core::OperationId;
12use fedimint_core::db::{
13 AutocommitError, Database, DatabaseError, DatabaseTransaction,
14 IDatabaseTransactionOpsCoreTyped as _,
15};
16use fedimint_core::envs::is_running_in_test_env;
17use fedimint_core::module::Amounts;
18use fedimint_core::task::sleep;
19use fedimint_core::txoproof::TxOutProof;
20use fedimint_core::util::FmtCompact as _;
21use fedimint_core::{BitcoinHash, TransactionId, secp256k1, time};
22use fedimint_logging::LOG_CLIENT_MODULE_WALLET;
23use fedimint_wallet_common::WalletInput;
24use fedimint_wallet_common::txoproof::{PegInProof, PegInProofError};
25use futures::StreamExt as _;
26use secp256k1::Keypair;
27use tokio::sync::watch;
28use tracing::{debug, instrument, trace, warn};
29
30use crate::api::WalletFederationApi as _;
31use crate::client_db::{
32 ClaimedPegInData, ClaimedPegInKey, PegInTweakIndexData, PegInTweakIndexKey,
33 PegInTweakIndexPrefix, TweakIdx,
34};
35use crate::error::DepositProgressError;
36use crate::events::{DepositConfirmed, ReceivePaymentEvent};
37use crate::{DepositProgress, WalletClientModule, WalletClientModuleData};
38
39#[derive(Debug, Clone)]
42struct NextActions {
43 now: SystemTime,
45 due: Vec<(PegInTweakIndexKey, PegInTweakIndexData)>,
47 next: Option<SystemTime>,
49}
50
51impl NextActions {
52 pub fn new() -> Self {
53 Self {
54 now: time::now(),
55 due: vec![],
56 next: None,
57 }
58 }
59}
60
61impl NextActions {
62 async fn from_db_state(db: &Database) -> Self {
64 db.begin_transaction_nc()
65 .await
66 .find_by_prefix(&PegInTweakIndexPrefix)
67 .await
68 .fold(NextActions::new(), |state, (key, val)| async {
69 state.fold(key, val)
70 })
71 .await
72 }
73
74 pub fn fold(mut self, key: PegInTweakIndexKey, val: PegInTweakIndexData) -> Self {
76 if let Some(next_check_time) = val.next_check_time {
77 if next_check_time < self.now {
78 self.due.push((key, val));
79 }
80
81 self.next = match self.next {
82 Some(existing) => Some(existing.min(next_check_time)),
83 None => Some(next_check_time),
84 };
85 }
86 self
87 }
88}
89
90#[allow(clippy::too_many_lines)]
95pub(crate) async fn run_peg_in_monitor(
96 client_ctx: ClientContext<WalletClientModule>,
97 db: Database,
98 btc_rpc: DynBitcoindRpc,
99 module_api: DynModuleApi,
100 data: WalletClientModuleData,
101 pegin_claimed_sender: watch::Sender<()>,
102 mut wakeup_receiver: watch::Receiver<()>,
103) {
104 let min_sleep: Duration = if is_running_in_test_env!() {
105 Duration::from_millis(100)
106 } else {
107 Duration::from_secs(30)
108 };
109
110 let mut next_wakeup_duration = Duration::ZERO;
115
116 loop {
117 debug!(target: LOG_CLIENT_MODULE_WALLET, sleep_msecs=%next_wakeup_duration.as_millis(), "Sleeping before next check");
118 let woke_via_signal = tokio::select! {
119 () = sleep(next_wakeup_duration) => {
120 debug!(target: LOG_CLIENT_MODULE_WALLET, "Woken up by a scheduled wakeup");
121 false
122 },
123 res = wakeup_receiver.changed() => {
124 debug!(target: LOG_CLIENT_MODULE_WALLET, "Woken up by a signal");
125 if res.is_err() {
126 debug!(target: LOG_CLIENT_MODULE_WALLET, "Terminating peg-in monitor");
127 return;
128 }
129 true
130 }
131 };
132
133 check_for_deposits(
134 &db,
135 &data,
136 &btc_rpc,
137 &module_api,
138 &client_ctx,
139 &pegin_claimed_sender,
140 )
141 .await;
142
143 let now = time::now();
144 let next_wakeup = NextActions::from_db_state(&db).await.next.unwrap_or_else(||
145 now + Duration::from_hours(1));
147 let effective_min_sleep = if woke_via_signal {
153 Duration::ZERO
154 } else {
155 min_sleep
156 };
157 next_wakeup_duration = next_wakeup
158 .duration_since(now)
159 .unwrap_or_default()
160 .max(effective_min_sleep);
161 }
162}
163
164async fn check_for_deposits(
165 db: &Database,
166 data: &WalletClientModuleData,
167 btc_rpc: &DynBitcoindRpc,
168 module_api: &DynModuleApi,
169 client_ctx: &ClientContext<WalletClientModule>,
170 pengin_claimed_sender: &watch::Sender<()>,
171) {
172 let due = NextActions::from_db_state(db).await.due;
173 trace!(target: LOG_CLIENT_MODULE_WALLET, ?due, "Checking for deposists");
174 for (due_key, due_val) in due {
175 check_and_claim_idx_pegins(
176 data,
177 due_key,
178 btc_rpc,
179 module_api,
180 db,
181 client_ctx,
182 due_val,
183 pengin_claimed_sender,
184 )
185 .await;
186 }
187}
188
189#[allow(clippy::too_many_arguments)]
190async fn check_and_claim_idx_pegins(
191 data: &WalletClientModuleData,
192 due_key: PegInTweakIndexKey,
193 btc_rpc: &DynBitcoindRpc,
194 module_api: &DynModuleApi,
195 db: &Database,
196 client_ctx: &ClientContext<WalletClientModule>,
197 due_val: PegInTweakIndexData,
198 pengin_claimed_sender: &watch::Sender<()>,
199) {
200 let now = time::now();
201 match check_idx_pegins(data, due_key.0, btc_rpc, module_api, db, client_ctx).await {
202 Ok(outcomes) => {
203 let next_check_time = CheckOutcome::retry_delay_vec(&outcomes, due_val.creation_time)
204 .map(|duration| now + duration);
205 db
206 .autocommit(
207 |dbtx, _| {
208 Box::pin(async {
209 let current = dbtx
216 .get_value(&due_key)
217 .await
218 .expect("Peg-in entries are never deleted");
219
220 let merged_next_check_time = if current.next_check_time
224 == due_val.next_check_time
225 {
226 next_check_time
227 } else {
228 match (current.next_check_time, next_check_time) {
229 (Some(a), Some(b)) => Some(a.min(b)),
230 (a, None) => a,
231 (None, b) => b,
232 }
233 };
234
235 let claimed_now = CheckOutcome::get_claimed_now_outpoints(&outcomes);
236
237 let claimed_sender = pengin_claimed_sender.clone();
238 dbtx.on_commit(move || {
239 claimed_sender.send_replace(());
240 });
241
242 let peg_in_tweak_index_data = PegInTweakIndexData {
243 next_check_time: merged_next_check_time,
244 last_check_time: Some(now),
245 claimed: [current.claimed.clone(), claimed_now].concat(),
246 ..current
247 };
248 trace!(
249 target: LOG_CLIENT_MODULE_WALLET,
250 tweak_idx=%due_key.0,
251 due_in_secs=?merged_next_check_time.map(|next_check_time| next_check_time.duration_since(now).unwrap_or_default().as_secs()),
252 data=?peg_in_tweak_index_data,
253 "Updating"
254 );
255 dbtx
256 .insert_entry(&due_key, &peg_in_tweak_index_data)
257 .await;
258
259 Ok::<_, Infallible>(())
260 })
261 },
262 None,
263 )
264 .await
265 .expect("Autocommit retries forever and the closure cannot fail");
266 }
267 Err(err) => {
268 debug!(
269 target: LOG_CLIENT_MODULE_WALLET,
270 err = %err.fmt_compact(),
271 tweak_idx = %due_key.0,
272 "Error checking tweak_idx"
273 );
274 }
275 }
276}
277
278#[derive(Copy, Clone, Debug)]
282enum CheckOutcome {
283 Pending { num_blocks_needed: u64 },
285 Claimed { outpoint: bitcoin::OutPoint },
287
288 AlreadyClaimed,
291}
292
293impl CheckOutcome {
294 fn retry_delay(self) -> Option<Duration> {
298 match self {
299 CheckOutcome::Pending { num_blocks_needed } => {
301 if is_running_in_test_env!() {
302 Some(Duration::from_millis(1))
304 } else {
305 Some(Duration::from_secs(60 * num_blocks_needed))
306 }
307 }
308 CheckOutcome::Claimed { .. } | CheckOutcome::AlreadyClaimed => None,
313 }
314 }
315
316 fn retry_delay_vec(outcomes: &[CheckOutcome], creation_time: SystemTime) -> Option<Duration> {
322 if outcomes.is_empty() {
326 if is_running_in_test_env!() {
327 return Some(Duration::from_millis(100));
329 }
330 let now = time::now();
331 let age = now.duration_since(creation_time).unwrap_or_default();
332 return Some(age / 10);
333 }
334
335 let mut min = None;
337
338 for outcome in outcomes {
339 min = match (min, outcome.retry_delay()) {
340 (None, time) => time,
341 (Some(min), None) => Some(min),
342 (Some(min), Some(time)) => Some(cmp::min(min, time)),
343 };
344 }
345
346 min
347 }
348
349 fn get_claimed_now_outpoints(outcomes: &[CheckOutcome]) -> Vec<bitcoin::OutPoint> {
350 let mut res = vec![];
351 for outcome in outcomes {
352 if let CheckOutcome::Claimed { outpoint } = outcome {
353 res.push(*outpoint);
354 }
355 }
356
357 res
358 }
359}
360
361fn blocks_until_claimable(tx_block_count: u64, consensus_block_count: u64) -> u64 {
363 tx_block_count.saturating_sub(consensus_block_count)
364}
365
366pub(crate) fn required_confirmations(finality_delay: u32) -> u64 {
369 u64::from(finality_delay) + 1
370}
371
372fn deposit_confirmations(
376 tx_block_count: u64,
377 consensus_block_count: u64,
378 finality_delay: u32,
379) -> u64 {
380 required_confirmations(finality_delay).saturating_sub(blocks_until_claimable(
381 tx_block_count,
382 consensus_block_count,
383 ))
384}
385
386pub(crate) async fn deposit_progress(
389 data: &WalletClientModuleData,
390 tweak_idx: TweakIdx,
391 btc_rpc: &DynBitcoindRpc,
392 module_rpc: &DynModuleApi,
393 db: &Database,
394) -> Result<Vec<DepositProgress>, DepositProgressError> {
395 let consensus_block_count = module_rpc.fetch_consensus_block_count().await?;
396 let (script, ..) = data.derive_peg_in_script(tweak_idx);
397 let history = btc_rpc.get_script_history(&script).await?;
398
399 let mut deposits = vec![];
400 for (transaction, outpoint) in unique_deposit_outputs(history, &script) {
401 let claimed_peg_in_key = ClaimedPegInKey {
402 peg_in_index: tweak_idx,
403 btc_out_point: outpoint,
404 };
405 if db
406 .begin_transaction_nc()
407 .await
408 .get_value(&claimed_peg_in_key)
409 .await
410 .is_some()
411 {
412 continue;
413 }
414
415 let confirmations = match btc_rpc.get_tx_block_height(&outpoint.txid).await? {
416 Some(tx_block_height) => deposit_confirmations(
417 tx_block_height.saturating_add(1),
418 consensus_block_count,
419 data.cfg.finality_delay,
420 ),
421 None => 0,
422 };
423
424 deposits.push(DepositProgress {
425 outpoint,
426 value: transaction.output[outpoint.vout as usize].value,
427 confirmations,
428 required: required_confirmations(data.cfg.finality_delay),
429 });
430 }
431 Ok(deposits)
432}
433
434fn unique_deposit_outputs(
437 history: Vec<bitcoin::Transaction>,
438 script: &ScriptBuf,
439) -> Vec<(bitcoin::Transaction, bitcoin::OutPoint)> {
440 let mut seen = BTreeSet::new();
441 filter_onchain_deposit_outputs(history.into_iter(), script)
442 .map(|(transaction, out_idx)| {
443 let outpoint = bitcoin::OutPoint {
444 txid: transaction.compute_txid(),
445 vout: out_idx,
446 };
447 (transaction, outpoint)
448 })
449 .filter(|(_, outpoint)| seen.insert(*outpoint))
450 .collect()
451}
452
453#[instrument(target = LOG_CLIENT_MODULE_WALLET, skip_all, fields(tweak_idx))]
458async fn check_idx_pegins(
459 data: &WalletClientModuleData,
460 tweak_idx: TweakIdx,
461 btc_rpc: &DynBitcoindRpc,
462 module_rpc: &DynModuleApi,
463 db: &Database,
464 client_ctx: &ClientContext<WalletClientModule>,
465) -> Result<Vec<CheckOutcome>, CheckPegInsError> {
466 let current_consensus_block_count = module_rpc.fetch_consensus_block_count().await?;
467 let (script, address, tweak_key, operation_id) = data.derive_peg_in_script(tweak_idx);
468 btc_rpc.watch_script_history(&script).await?;
469
470 let history = btc_rpc.get_script_history(&script).await?;
471
472 debug!(target: LOG_CLIENT_MODULE_WALLET, %address, num_txes=history.len(), "Got history of a peg-in address");
473
474 let mut outcomes = vec![];
475
476 for (transaction, out_idx) in filter_onchain_deposit_outputs(history.into_iter(), &script) {
477 let txid = transaction.compute_txid();
478 let outpoint = bitcoin::OutPoint {
479 txid,
480 vout: out_idx,
481 };
482
483 let claimed_peg_in_key = ClaimedPegInKey {
484 peg_in_index: tweak_idx,
485 btc_out_point: outpoint,
486 };
487
488 if db
489 .begin_transaction_nc()
490 .await
491 .get_value(&claimed_peg_in_key)
492 .await
493 .is_some()
494 {
495 debug!(target: LOG_CLIENT_MODULE_WALLET, %txid, %out_idx, "Already claimed");
496 outcomes.push(CheckOutcome::AlreadyClaimed);
497 continue;
498 }
499 let finality_delay = u64::from(data.cfg.finality_delay);
500
501 let tx_block_count =
502 if let Some(tx_block_height) = btc_rpc.get_tx_block_height(&txid).await? {
503 tx_block_height.saturating_add(1)
504 } else {
505 outcomes.push(CheckOutcome::Pending {
506 num_blocks_needed: finality_delay,
507 });
508 debug!(target:LOG_CLIENT_MODULE_WALLET, %txid, %out_idx,"In the mempool");
509 continue;
510 };
511
512 let num_blocks_needed =
513 blocks_until_claimable(tx_block_count, current_consensus_block_count);
514
515 if 0 < num_blocks_needed {
516 outcomes.push(CheckOutcome::Pending { num_blocks_needed });
517 debug!(target: LOG_CLIENT_MODULE_WALLET, %txid, %out_idx, %num_blocks_needed, %finality_delay, %tx_block_count, %current_consensus_block_count, "Needs more confirmations");
518 continue;
519 }
520
521 debug!(target: LOG_CLIENT_MODULE_WALLET, %txid, %out_idx, %finality_delay, %tx_block_count, %current_consensus_block_count, "Ready to claim");
522
523 let tx_out_proof = btc_rpc.get_txout_proof(txid).await?;
524 let federation_knows_utxo = module_rpc.is_utxo_confirmed(outpoint).await?;
525
526 claim_peg_in(
527 client_ctx,
528 tweak_idx,
529 tweak_key,
530 &transaction,
531 operation_id,
532 outpoint,
533 tx_out_proof,
534 federation_knows_utxo,
535 )
536 .await?;
537 outcomes.push(CheckOutcome::Claimed { outpoint });
538 }
539 Ok(outcomes)
540}
541
542#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
543async fn claim_peg_in(
544 client_ctx: &ClientContext<WalletClientModule>,
545 tweak_idx: TweakIdx,
546 tweak_key: Keypair,
547 transaction: &bitcoin::Transaction,
548 operation_id: OperationId,
549 out_point: bitcoin::OutPoint,
550 tx_out_proof: TxOutProof,
551 federation_knows_utxo: bool,
552) -> Result<(), CheckPegInsError> {
553 async fn claim_peg_in_inner(
556 client_ctx: &ClientContext<WalletClientModule>,
557 dbtx: &mut DatabaseTransaction<'_>,
558 btc_transaction: &bitcoin::Transaction,
559 out_idx: u32,
560 tweak_key: Keypair,
561 txout_proof: TxOutProof,
562 operation_id: OperationId,
563 federation_knows_utxo: bool,
564 ) -> Result<Option<OutPointRange>, CheckPegInsError> {
565 let pegin_proof = PegInProof::new(
572 txout_proof,
573 btc_transaction.clone(),
574 out_idx,
575 tweak_key.public_key(),
576 )
577 .inspect_err(|error| {
578 warn!(
579 target: LOG_CLIENT_MODULE_WALLET,
580 error = %error.fmt_compact(),
581 txid = %btc_transaction.compute_txid(),
582 %out_idx,
583 "Bitcoin backend returned a proof that does not cover this deposit; leaving it unclaimed so it is retried"
584 );
585 })
586 .map_err(CheckPegInsError::FaultyProof)?;
587
588 let amount = pegin_proof.tx_output().value.into();
589 let wallet_input = if federation_knows_utxo {
590 WalletInput::new_v1(&pegin_proof)
591 } else {
592 WalletInput::new_v0(pegin_proof)
593 };
594
595 let client_input = ClientInput::<WalletInput> {
596 input: wallet_input,
597 keys: vec![tweak_key],
598 amounts: Amounts::new_bitcoin(amount),
599 };
600
601 if amount <= client_ctx.self_ref().cfg().fee_consensus.peg_in_abs {
602 warn!(target: LOG_CLIENT_MODULE_WALLET, "We won't claim a deposit lower than the deposit fee");
603 return Ok(None);
604 }
605
606 let txid = btc_transaction.compute_txid();
607
608 client_ctx
609 .log_event(
610 dbtx,
611 DepositConfirmed {
612 txid,
613 out_idx,
614 amount,
615 },
616 )
617 .await;
618
619 client_ctx
620 .log_event(
621 dbtx,
622 ReceivePaymentEvent {
623 operation_id,
624 amount,
625 txid,
626 },
627 )
628 .await;
629
630 Ok(Some(
631 client_ctx
632 .claim_inputs(
633 dbtx,
634 ClientInputBundle::new_no_sm(vec![client_input]),
635 operation_id,
636 )
637 .await
638 .expect("Cannot claim input, additional funding needed"),
639 ))
640 }
641
642 let tx_out_proof = &tx_out_proof;
643
644 debug!(target: LOG_CLIENT_MODULE_WALLET, %out_point, "Claiming a peg-in");
645
646 client_ctx
647 .module_db()
648 .autocommit(
649 |dbtx, _| {
650 Box::pin(async {
651 let maybe_change_range = claim_peg_in_inner(
652 client_ctx,
653 dbtx,
654 transaction,
655 out_point.vout,
656 tweak_key,
657 tx_out_proof.clone(),
658 operation_id,
659 federation_knows_utxo,
660 )
661 .await?;
662
663 let claimed_pegin_data = if let Some(change_range) = maybe_change_range {
664 ClaimedPegInData {
665 claim_txid: change_range.txid(),
666 change: change_range.into_iter().collect(),
667 }
668 } else {
669 ClaimedPegInData {
670 claim_txid: TransactionId::from_byte_array([0; 32]),
671 change: vec![],
672 }
673 };
674
675 dbtx.insert_entry(
676 &ClaimedPegInKey {
677 peg_in_index: tweak_idx,
678 btc_out_point: out_point,
679 },
680 &claimed_pegin_data,
681 )
682 .await;
683
684 Ok::<_, CheckPegInsError>(())
685 })
686 },
687 Some(100),
688 )
689 .await
690 .map_err(|e| match e {
691 AutocommitError::CommitFailed {
692 last_error,
693 attempts,
694 } => CheckPegInsError::ClaimCommit {
695 attempts,
696 source: last_error,
697 },
698 AutocommitError::ClosureError { error, .. } => error,
699 })?;
700
701 Ok(())
702}
703
704pub(crate) fn filter_onchain_deposit_outputs<'a>(
705 tx_iter: impl Iterator<Item = bitcoin::Transaction> + 'a,
706 out_script: &'a ScriptBuf,
707) -> impl Iterator<Item = (bitcoin::Transaction, u32)> + 'a {
708 tx_iter.flat_map(move |tx| {
709 tx.output
710 .clone()
711 .into_iter()
712 .enumerate()
713 .filter_map(move |(out_idx, tx_out)| {
714 if &tx_out.script_pubkey == out_script {
715 Some((tx.clone(), out_idx as u32))
716 } else {
717 None
718 }
719 })
720 })
721}
722
723#[derive(Debug, thiserror::Error)]
725enum CheckPegInsError {
726 #[error(transparent)]
729 Federation(#[from] FederationError),
730
731 #[error(transparent)]
734 BitcoinRpc(#[from] BitcoinRpcError),
735
736 #[error("Bitcoin backend returned a proof that does not cover the deposit")]
740 FaultyProof(#[source] PegInProofError),
741
742 #[error("Failed to commit after {attempts} attempts")]
744 ClaimCommit {
745 attempts: usize,
746 #[source]
747 source: DatabaseError,
748 },
749}
750
751#[cfg(test)]
752mod tests;