Implement batch call for script subscribe

This commit is contained in:
Riccardo Casatta 2023-03-21 13:19:21 +01:00
parent 84d6860144
commit 156e6fc839
No known key found for this signature in database
GPG Key ID: FD986A969E450397
4 changed files with 40 additions and 0 deletions

View File

@ -106,6 +106,13 @@ pub trait ElectrumApi {
/// already subscribed to the script.
fn script_subscribe(&self, script: &Script) -> Result<Option<ScriptStatus>, Error>;
/// Batch version of [`script_subscribe`](#method.script_subscribe).
///
/// Takes a list of scripts and returns a list of script status responses.
fn batch_script_subscribe<'s, I>(&self, scripts: I) -> Result<Vec<Option<ScriptStatus>>, Error>
where
I: IntoIterator<Item = &'s Script> + Clone;
/// Subscribes to notifications for activity on a specific *scriptPubKey*.
///
/// Returns a `bool` with the server response when successful.

View File

@ -43,6 +43,13 @@ impl Batch {
.push((String::from("blockchain.scripthash.get_balance"), params));
}
/// Add one `blockchain.scripthash.listunspent` request to the batch queue
pub fn script_subscribe(&mut self, script: &Script) {
let params = vec![Param::String(script.to_electrum_scripthash().to_hex())];
self.calls
.push((String::from("blockchain.scripthash.subscribe"), params));
}
/// Add one `blockchain.transaction.get` request to the batch queue
pub fn transaction_get(&mut self, tx_hash: &Txid) {
let params = vec![Param::String(tx_hash.to_hex())];

View File

@ -222,6 +222,14 @@ impl ElectrumApi for Client {
impl_inner_call!(self, script_subscribe, script)
}
#[inline]
fn batch_script_subscribe<'s, I>(&self, scripts: I) -> Result<Vec<Option<ScriptStatus>>, Error>
where
I: IntoIterator<Item = &'s Script> + Clone,
{
impl_inner_call!(self, batch_script_subscribe, scripts.clone())
}
#[inline]
fn script_unsubscribe(&self, script: &Script) -> Result<bool, Error> {
impl_inner_call!(self, script_unsubscribe, script)

View File

@ -848,6 +848,24 @@ impl<T: Read + Write> ElectrumApi for RawClient<T> {
Ok(serde_json::from_value(value)?)
}
fn batch_script_subscribe<'s, I>(&self, scripts: I) -> Result<Vec<Option<ScriptStatus>>, Error>
where
I: IntoIterator<Item = &'s Script> + Clone,
{
{
let mut script_notifications = self.script_notifications.lock()?;
for script in scripts.clone().into_iter() {
let script_hash = script.to_electrum_scripthash();
if script_notifications.contains_key(&script_hash) {
return Err(Error::AlreadySubscribed(script_hash));
}
script_notifications.insert(script_hash, VecDeque::new());
}
}
impl_batch_call!(self, scripts, script_subscribe)
}
fn script_unsubscribe(&self, script: &Script) -> Result<bool, Error> {
let script_hash = script.to_electrum_scripthash();
let mut script_notifications = self.script_notifications.lock()?;