-
Notifications
You must be signed in to change notification settings - Fork 9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Remove electrum tip query on start #708
Merged
Merged
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
54d7e9a
remove electrum tip query on start
roeierez f0e2580
fix clippy
roeierez 262254f
simlify tip
roeierez a5cc34d
lazy initialization of electrum
roeierez e5d0e94
remove println statements
roeierez 41aca3c
fix comment
roeierez 24dac2e
Cleanup code
roeierez File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,18 @@ | ||
use std::sync::Mutex; | ||
use std::sync::OnceLock; | ||
use std::time::Duration; | ||
|
||
use anyhow::{anyhow, Result}; | ||
use async_trait::async_trait; | ||
use boltz_client::ToHex; | ||
use electrum_client::{Client, ElectrumApi}; | ||
use elements::encode::serialize as elements_serialize; | ||
use log::info; | ||
use lwk_wollet::clients::blocking::BlockchainBackend; | ||
use lwk_wollet::elements::hex::FromHex; | ||
use lwk_wollet::ElectrumOptions; | ||
use lwk_wollet::{bitcoin, elements, ElectrumOptions}; | ||
use lwk_wollet::{ | ||
elements::{Address, OutPoint, Script, Transaction, Txid}, | ||
hashes::{sha256, Hash}, | ||
ElectrumClient, ElectrumUrl, History, | ||
ElectrumUrl, History, | ||
}; | ||
|
||
use crate::prelude::Utxo; | ||
|
@@ -60,52 +61,112 @@ pub trait LiquidChainService: Send + Sync { | |
} | ||
|
||
pub(crate) struct HybridLiquidChainService { | ||
electrum_client: ElectrumClient, | ||
tip_client: Mutex<ElectrumClient>, | ||
client: OnceLock<Client>, | ||
config: Config, | ||
} | ||
|
||
impl HybridLiquidChainService { | ||
pub(crate) fn new(config: Config) -> Result<Self> { | ||
let electrum_url = ElectrumUrl::new(&config.liquid_electrum_url, true, true)?; | ||
let electrum_client = | ||
ElectrumClient::with_options(&electrum_url, ElectrumOptions { timeout: Some(3) })?; | ||
let tip_client = | ||
ElectrumClient::with_options(&electrum_url, ElectrumOptions { timeout: Some(3) })?; | ||
Ok(Self { | ||
electrum_client, | ||
tip_client: Mutex::new(tip_client), | ||
config, | ||
client: OnceLock::new(), | ||
}) | ||
} | ||
|
||
fn get_client(&self) -> Result<&Client> { | ||
if let Some(c) = self.client.get() { | ||
return Ok(c); | ||
} | ||
let electrum_url = ElectrumUrl::new(&self.config.liquid_electrum_url, true, true)?; | ||
let client = electrum_url.build_client(&ElectrumOptions { timeout: Some(3) })?; | ||
|
||
let client = self.client.get_or_init(|| client); | ||
Ok(client) | ||
} | ||
} | ||
|
||
#[async_trait] | ||
impl LiquidChainService for HybridLiquidChainService { | ||
async fn tip(&self) -> Result<u32> { | ||
Ok(self.tip_client.lock().unwrap().tip()?.height) | ||
let client = self.get_client()?; | ||
let mut maybe_popped_header = None; | ||
while let Some(header) = client.block_headers_pop_raw()? { | ||
maybe_popped_header = Some(header) | ||
} | ||
|
||
let new_tip: Option<u32> = match maybe_popped_header { | ||
Some(popped_header) => Some(popped_header.height.try_into()?), | ||
None => { | ||
// https://github.com/bitcoindevkit/rust-electrum-client/issues/124 | ||
// It might be that the client has reconnected and subscriptions don't persist | ||
// across connections. Calling `client.ping()` won't help here because the | ||
// successful retry will prevent us knowing about the reconnect. | ||
if let Ok(header) = client.block_headers_subscribe_raw() { | ||
Some(header.height.try_into()?) | ||
} else { | ||
None | ||
} | ||
} | ||
}; | ||
|
||
let tip: u32 = new_tip.ok_or_else(|| anyhow!("Failed to get tip"))?; | ||
Ok(tip) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit: Same as above. The name There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done |
||
} | ||
|
||
async fn broadcast(&self, tx: &Transaction) -> Result<Txid> { | ||
Ok(self.electrum_client.broadcast(tx)?) | ||
let txid = self | ||
.get_client()? | ||
.transaction_broadcast_raw(&elements_serialize(tx))?; | ||
Ok(Txid::from_raw_hash(txid.to_raw_hash())) | ||
} | ||
|
||
async fn get_transaction_hex(&self, txid: &Txid) -> Result<Option<Transaction>> { | ||
Ok(self.get_transactions(&[*txid]).await?.first().cloned()) | ||
} | ||
|
||
async fn get_transactions(&self, txids: &[Txid]) -> Result<Vec<Transaction>> { | ||
Ok(self.electrum_client.get_transactions(txids)?) | ||
let txids: Vec<bitcoin::Txid> = txids | ||
.iter() | ||
.map(|t| bitcoin::Txid::from_raw_hash(t.to_raw_hash())) | ||
.collect(); | ||
|
||
let mut result = vec![]; | ||
for tx in self.get_client()?.batch_transaction_get_raw(&txids)? { | ||
let tx: Transaction = elements::encode::deserialize(&tx)?; | ||
result.push(tx); | ||
} | ||
Ok(result) | ||
} | ||
|
||
async fn get_script_history(&self, script: &Script) -> Result<Vec<History>> { | ||
let mut history_vec = self.electrum_client.get_scripts_history(&[script])?; | ||
let scripts = &[script]; | ||
let scripts: Vec<&bitcoin::Script> = scripts | ||
.iter() | ||
.map(|t| bitcoin::Script::from_bytes(t.as_bytes())) | ||
.collect(); | ||
|
||
let mut history_vec: Vec<Vec<History>> = self | ||
.get_client()? | ||
.batch_script_get_history(&scripts)? | ||
.into_iter() | ||
.map(|e| e.into_iter().map(Into::into).collect()) | ||
.collect(); | ||
let h = history_vec.pop(); | ||
Ok(h.unwrap_or(vec![])) | ||
Ok(h.unwrap_or_default()) | ||
} | ||
|
||
async fn get_scripts_history(&self, scripts: &[&Script]) -> Result<Vec<Vec<History>>> { | ||
self.electrum_client | ||
.get_scripts_history(scripts) | ||
.map_err(Into::into) | ||
let scripts: Vec<&bitcoin::Script> = scripts | ||
.iter() | ||
.map(|t| bitcoin::Script::from_bytes(t.as_bytes())) | ||
.collect(); | ||
|
||
Ok(self | ||
.get_client()? | ||
.batch_script_get_history(&scripts)? | ||
.into_iter() | ||
.map(|e| e.into_iter().map(Into::into).collect()) | ||
.collect()) | ||
} | ||
|
||
async fn get_script_history_with_retry( | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nit: the
new_tip
name no longer makes sense. Maybe rename tomaybe_tip
? We can even get rid of it and return the tip directly within thematch
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done