Skip to content

Commit

Permalink
cache tip
Browse files Browse the repository at this point in the history
  • Loading branch information
roeierez committed Feb 4, 2025
1 parent 0c9d2b8 commit ee0924c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
18 changes: 15 additions & 3 deletions lib/core/src/chain/bitcoin.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -77,12 +80,14 @@ pub trait BitcoinChainService: Send + Sync {
pub(crate) struct HybridBitcoinChainService {
client: OnceLock<Client>,
config: Config,
last_known_tip: Mutex<Option<HeaderNotification>>,
}
impl HybridBitcoinChainService {
pub fn new(config: Config) -> Result<Self, Error> {
Ok(Self {
config,
client: OnceLock::new(),
last_known_tip: Mutex::new(None),
})
}

Expand All @@ -107,7 +112,7 @@ impl BitcoinChainService for HybridBitcoinChainService {
maybe_popped_header = Some(header)
}

let new_tip = match maybe_popped_header {
let new_tip: Option<HeaderNotification> = match maybe_popped_header {
Some(popped_header) => Some(popped_header.try_into()?),
None => {
// https://github.com/bitcoindevkit/rust-electrum-client/issues/124
Expand All @@ -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<Txid> {
Expand Down
14 changes: 12 additions & 2 deletions lib/core/src/chain/liquid.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::sync::OnceLock;
use std::sync::{Mutex, OnceLock};
use std::time::Duration;

use anyhow::{anyhow, Result};
Expand Down Expand Up @@ -63,13 +63,15 @@ pub trait LiquidChainService: Send + Sync {
pub(crate) struct HybridLiquidChainService {
client: OnceLock<Client>,
config: Config,
last_known_tip: Mutex<Option<u32>>,
}

impl HybridLiquidChainService {
pub(crate) fn new(config: Config) -> Result<Self> {
Ok(Self {
config,
client: OnceLock::new(),
last_known_tip: Mutex::new(None),
})
}

Expand Down Expand Up @@ -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<u32>> =
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<Txid> {
Expand Down

0 comments on commit ee0924c

Please sign in to comment.