From ee0924c571930013ef1345f118af256f3a3840b2 Mon Sep 17 00:00:00 2001 From: Roei Erez Date: Tue, 4 Feb 2025 09:42:24 +0200 Subject: [PATCH] cache tip --- lib/core/src/chain/bitcoin.rs | 18 +++++++++++++++--- lib/core/src/chain/liquid.rs | 14 ++++++++++++-- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/lib/core/src/chain/bitcoin.rs b/lib/core/src/chain/bitcoin.rs index 96e53859d..75b6ad96a 100644 --- a/lib/core/src/chain/bitcoin.rs +++ b/lib/core/src/chain/bitcoin.rs @@ -1,4 +1,7 @@ -use std::{sync::OnceLock, time::Duration}; +use std::{ + sync::{Mutex, OnceLock}, + time::Duration, +}; use anyhow::{anyhow, Result}; use async_trait::async_trait; @@ -77,12 +80,14 @@ pub trait BitcoinChainService: Send + Sync { pub(crate) struct HybridBitcoinChainService { client: OnceLock, config: Config, + last_known_tip: Mutex>, } impl HybridBitcoinChainService { pub fn new(config: Config) -> Result { Ok(Self { config, client: OnceLock::new(), + last_known_tip: Mutex::new(None), }) } @@ -107,7 +112,7 @@ impl BitcoinChainService for HybridBitcoinChainService { maybe_popped_header = Some(header) } - let new_tip = match maybe_popped_header { + let new_tip: Option = match maybe_popped_header { Some(popped_header) => Some(popped_header.try_into()?), None => { // https://github.com/bitcoindevkit/rust-electrum-client/issues/124 @@ -122,7 +127,14 @@ impl BitcoinChainService for HybridBitcoinChainService { } }; - new_tip.ok_or_else(|| anyhow!("Failed to get tip")) + let mut last_tip = self.last_known_tip.lock().unwrap(); + match new_tip { + Some(header) => { + *last_tip = Some(header.clone()); + Ok(header) + } + None => last_tip.clone().ok_or_else(|| anyhow!("Failed to get tip")), + } } fn broadcast(&self, tx: &Transaction) -> Result { diff --git a/lib/core/src/chain/liquid.rs b/lib/core/src/chain/liquid.rs index 0a25a0a39..9b756e3f8 100644 --- a/lib/core/src/chain/liquid.rs +++ b/lib/core/src/chain/liquid.rs @@ -1,4 +1,4 @@ -use std::sync::OnceLock; +use std::sync::{Mutex, OnceLock}; use std::time::Duration; use anyhow::{anyhow, Result}; @@ -63,6 +63,7 @@ pub trait LiquidChainService: Send + Sync { pub(crate) struct HybridLiquidChainService { client: OnceLock, config: Config, + last_known_tip: Mutex>, } impl HybridLiquidChainService { @@ -70,6 +71,7 @@ impl HybridLiquidChainService { Ok(Self { config, client: OnceLock::new(), + last_known_tip: Mutex::new(None), }) } @@ -109,7 +111,15 @@ impl LiquidChainService for HybridLiquidChainService { } }; - new_tip.ok_or_else(|| anyhow!("Failed to get tip")) + let mut last_tip: std::sync::MutexGuard<'_, Option> = + self.last_known_tip.lock().unwrap(); + match new_tip { + Some(header) => { + *last_tip = Some(header); + Ok(header) + } + None => last_tip.ok_or_else(|| anyhow!("Failed to get tip")), + } } async fn broadcast(&self, tx: &Transaction) -> Result {