From fde25c25266cc9870c18f550e51141252cdbf0cc Mon Sep 17 00:00:00 2001 From: Sonkeng Maldini Date: Wed, 30 Sep 2026 15:34:32 +0100 Subject: [PATCH 1/4] feat(scanner): add frigate scanner layouts --- Cargo.toml | 4 +- scanners/remote/frigate/.gitignore | 1 + scanners/remote/frigate/Cargo.toml | 22 +++ scanners/remote/frigate/src/client.rs | 183 +++++++++++++++++++++++++ scanners/remote/frigate/src/lib.rs | 2 + scanners/remote/frigate/src/scanner.rs | 120 ++++++++++++++++ 6 files changed, 331 insertions(+), 1 deletion(-) create mode 100644 scanners/remote/frigate/.gitignore create mode 100644 scanners/remote/frigate/Cargo.toml create mode 100644 scanners/remote/frigate/src/client.rs create mode 100644 scanners/remote/frigate/src/lib.rs create mode 100644 scanners/remote/frigate/src/scanner.rs diff --git a/Cargo.toml b/Cargo.toml index e40832a3..f684c210 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,8 @@ members = [ "backends/blindbit-v1", "spdk-wallet", "silentpayments", - "scanners/local", + "scanners/local", + "scanners/remote/frigate", ] resolver = "3" @@ -36,6 +37,7 @@ reqwest = { version = "0.12.4", features = [ "gzip", ], default-features = false } secp256k1 = { version = "0.29.0" } +electrum_streaming_client = { git = "https://github.com/bitcoindevkit/electrum_streaming_client", rev = "01a6d42aac33f86b2bc647e7fc702067be99c9c7", features = ["frigate"]} [workspace.package] edition = "2024" diff --git a/scanners/remote/frigate/.gitignore b/scanners/remote/frigate/.gitignore new file mode 100644 index 00000000..ea8c4bf7 --- /dev/null +++ b/scanners/remote/frigate/.gitignore @@ -0,0 +1 @@ +/target diff --git a/scanners/remote/frigate/Cargo.toml b/scanners/remote/frigate/Cargo.toml new file mode 100644 index 00000000..0c9120f6 --- /dev/null +++ b/scanners/remote/frigate/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "frigate" +version = "0.1.0" +edition.workspace = true +repository.workspace = true +authors.workspace = true +license.workspace = true + +[dependencies] +electrum_streaming_client.workspace = true +spdk-core.workspace = true +silentpayments.workspace = true + +bitcoin.workspace = true +futures.workspace = true +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } +log.workspace = true +async-trait.workspace = true +anyhow.workspace = true + +[lints] +workspace = true diff --git a/scanners/remote/frigate/src/client.rs b/scanners/remote/frigate/src/client.rs new file mode 100644 index 00000000..fe427244 --- /dev/null +++ b/scanners/remote/frigate/src/client.rs @@ -0,0 +1,183 @@ +use std::{collections::HashSet, ops::RangeInclusive, pin::Pin, time::Duration}; + +use bitcoin::{ + Amount, BlockHash, OutPoint, Txid, absolute::Height, +}; +use async_trait::async_trait; +use electrum_streaming_client::{AsyncClient, Event, request, response::{FullTx, HeaderResp}}; +use futures::{Stream, channel::mpsc::UnboundedReceiver}; + +use spdk_core::chain::{BoxedBlockData, ChainBackend, UtxoData}; +use tokio::{net::TcpStream, task::JoinHandle, time::timeout}; + +#[derive(Debug)] +pub struct FrigateClient { + pub host_url: String, + pub client: AsyncClient, + pub events: UnboundedReceiver, + pub worker: JoinHandle>, + pub request_timeout: Duration, +} + + +#[derive(Debug)] +pub enum FrigateError { + Connection(String), + Timeout(String), + Request(String), + Io(String), +} + +type Result = std::result::Result; + +impl std::fmt::Display for FrigateError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Connection(msg) => write!(f, "connection error: {msg}"), + Self::Timeout(msg) => write!(f, "request timeout: {msg}"), + Self::Request(msg) => write!(f, "request error: {msg}"), + Self::Io(msg) => write!(f, "I/O error: {msg}"), + } + } +} + +impl std::error::Error for FrigateError {} + +impl FrigateClient { + + pub async fn connect(host_url: &str) -> Result { + let stream = TcpStream::connect(host_url).await.map_err(|err| { + FrigateError::Connection(format!("can't connect to socket '{host_url}': {err}")) + })?; + + let (reader, writer) = stream.into_split(); + let (client, events, worker) = AsyncClient::new_tokio(reader, writer); + + let worker = tokio::spawn(async move { + match worker.await { + Ok(()) => { + Ok(()) + } + Err(e) => { + Err(e) + } + } + }); + + Ok(Self { + host_url: host_url.to_owned(), + client, + events, + worker, + request_timeout: Duration::from_secs(10), + }) + } + + /// Sets a custom request timeout for this client. + #[must_use] + pub const fn with_timeout(mut self, timeout: Duration) -> Self { + self.request_timeout = timeout; + self + } + + pub async fn get_block_header(&mut self, height: u32) -> Result { + let res = timeout( + self.request_timeout, + self.client.send_request(request::Header { height }), + ) + .await + .map_err(|_| FrigateError::Timeout("Header request timed out".to_owned()))? + .map_err(|e| FrigateError::Request(format!("Header request failed: {e}")))?; + Ok(res) + } + + pub async fn get_transaction(&mut self, txid: Txid) -> Result { + let res = timeout( + self.request_timeout, + self.client.send_request(request::GetTx { txid }), + ) + .await + .map_err(|_| FrigateError::Timeout("GetTx request timed out".to_owned()))? + .map_err(|e| FrigateError::Request(format!("GetTx request failed: {e}")))?; + Ok(res) + } + + /// Send a request to the Frigate electrum server for version negotiation + /// This is the first request that should be sent before subsequent one. + pub async fn version(&mut self) -> Result { + let res = timeout( + self.request_timeout, + self.client.send_request(request::ServerVersion { + client_name: "bdk-sp".into(), + protocol_version: request::SupportedVersion::Range([ + "1.3.2".into(), + "1.4.1".into(), + ]), + }), + ) + .await + .map_err(|_| FrigateError::Timeout("Version request timed out".to_owned()))? + .map_err(|e| FrigateError::Request(format!("Version request failed: {e}")))?; + Ok(res.protocol_version) + } + + /// Make a request to the Frigate electrum server to subscribe to the outputs beloging to the given silent payment address + /// Once the server receives the request notification will be sent to the client everytime an ouput is found. + /// + /// See: + pub async fn subscribe( + &mut self, + subscribe_req: request::SpSubscribe, + ) -> Result { + log::debug!("Sending subscribe event request..."); + + let res = timeout( + self.request_timeout, + self.client.send_request(subscribe_req), + ) + .await + .map_err(|_| FrigateError::Timeout("Subscribe request timed out".to_owned()))? + .map_err(|e| FrigateError::Request(format!("Subscribe request failed: {e}")))?; + + log::info!("Subscribed to silent payment address: {res}"); + Ok(res) + } + + pub async fn unsubscribe( + &mut self, + unsub_req: request::SpUnsubscribe, + ) -> Result<()> { + let res = timeout(self.request_timeout, self.client.send_request(unsub_req)) + .await + .map_err(|_| FrigateError::Timeout("Unsubscribe request timed out".to_owned()))? + .map_err(|e| FrigateError::Request(format!("Unsubscribe request failed: {e}")))?; + + log::info!("Unsubscribed to silent payment address: {res:?}"); + Ok(()) + } +} + +#[async_trait] +impl ChainBackend for FrigateClient { + fn get_block_data_for_range( + &self, + _range: RangeInclusive, + _dust_limit: Amount, + _with_cutthrough: bool, + ) -> Pin> + Send>> { + unimplemented!("Not needed for frigate implementation") + } + + async fn detect_spent_outpoints( + &self, + _block_height: Height, + _block_hash: BlockHash, + _outpoints: HashSet, + ) -> anyhow::Result> { + unimplemented!("Not needed for frigate implementation") + } + + async fn utxos(&self, _block_height: Height) -> anyhow::Result> { + unimplemented!("Not needed for frigate implementation") + } +} \ No newline at end of file diff --git a/scanners/remote/frigate/src/lib.rs b/scanners/remote/frigate/src/lib.rs new file mode 100644 index 00000000..2f91c788 --- /dev/null +++ b/scanners/remote/frigate/src/lib.rs @@ -0,0 +1,2 @@ +pub mod scanner; +pub mod client; \ No newline at end of file diff --git a/scanners/remote/frigate/src/scanner.rs b/scanners/remote/frigate/src/scanner.rs new file mode 100644 index 00000000..cf9145b3 --- /dev/null +++ b/scanners/remote/frigate/src/scanner.rs @@ -0,0 +1,120 @@ +use std::collections::{HashMap, HashSet}; + +use bitcoin::{OutPoint, Txid, absolute::Height, secp256k1::{PublicKey, SecretKey}}; +use electrum_streaming_client::{Event, notification::Notification, request, response::TxTweak}; +use futures::{SinkExt as _, StreamExt as _, channel::mpsc::{Receiver, channel}}; +use log::{debug, info}; +use spdk_core::scanner::{DiscoveredOutput, ScanResult, Scanner}; +use silentpayments::receiving::Receiver as SpReceiver; + +use crate::client::FrigateClient; + +pub struct FrigateScanner { + client: FrigateClient, + b_scan: SecretKey, + sp_receiver: SpReceiver, + labels: Option> +} + +impl FrigateScanner { + pub const fn new( + client: FrigateClient, + b_scan: SecretKey, + sp_receiver: SpReceiver, + labels: Option> + ) -> Self { + Self { + client, + b_scan, + sp_receiver, + labels, + } + } +} + +impl Scanner for FrigateScanner { + fn scan_blocks(mut self, range: std::ops::RangeInclusive) -> Receiver { + let subscribe_params = request::SpSubscribe { + scan_priv_key: self.b_scan, + spend_pub_key: self.sp_receiver.receiving_code().m_pubkey(), + start_height: Some(range.start().to_consensus_u32()), + labels: self.labels + }; + + info!( + "start: {} end: {}", + range.start().to_consensus_u32(), + range.end().to_consensus_u32(), + ); + + let (mut tx, rx) = channel(100_000); + + tokio::spawn( async move { + + if let Ok(sp_address) = self.client.subscribe(subscribe_params).await { + info!("Subscribed to silent payments address {sp_address}"); + } else { + log::error!("Unable to subscribe"); + } + + while let Some(event) = self.client.events.next().await { + if let Event::Notification(notification) = event { + match notification { + Notification::SpSubscribe(sp_subscribe_notification) => { + let histories = sp_subscribe_notification.history.clone(); + let progress = sp_subscribe_notification.progress; + + let mut secrets_by_height: HashMap> = HashMap::new(); + + debug!("Received history {histories:#?}"); + info!("Found a total of {} output(s)", histories.len()); + + for h in &histories { + secrets_by_height + .entry(h.height) + .and_modify(|v| { + v.insert(h.tx_hash, h.tweak_key); + }) + .or_insert(HashMap::from([(h.tx_hash, h.tweak_key)])); + } + + for history in secrets_by_height { + let discovered_inputs = HashSet::::new(); + let discovered_outputs = HashMap::::new(); + + let blk_header = self.client.get_block_header(history.0).await.unwrap(); + + let scan_res = ScanResult { + blkheight: Height::from_consensus(history.0).unwrap(), + blkhash: blk_header.header.block_hash(), + discovered_inputs, + discovered_outputs, + }; + + match tx.send(scan_res).await { + Ok(()) => info!("Scan result sent!"), + Err(e) => log::error!("Unable to send scan result: {e}") + } + } + + if progress >= 1.0f32 { + info!("Scanning completed!"); + break; + } + + subscribe_to_owned_outpouts(&self.client, histories).await; + } + Notification::ScriptHash(_script_hash_notification) => todo!(), + _ => info!("Notification event not supported.") + } + } + } + }); + + rx + } +} + +async fn subscribe_to_owned_outpouts(_client: &FrigateClient, _tx_hash: Vec) {} + + From 89c80483e0c29598b79978d058fcf6d1126e8112 Mon Sep 17 00:00:00 2001 From: Sonkeng Maldini Date: Wed, 7 Oct 2026 22:39:22 +0100 Subject: [PATCH 2/4] scanner: implement scan_blocks for frigate with additional helpers --- scanners/remote/frigate/Cargo.toml | 6 +- .../frigate/examples/frigate_scanner.rs | 57 ++++ scanners/remote/frigate/src/client.rs | 80 +++--- scanners/remote/frigate/src/lib.rs | 2 +- scanners/remote/frigate/src/scanner.rs | 253 +++++++++++++++--- 5 files changed, 320 insertions(+), 78 deletions(-) create mode 100644 scanners/remote/frigate/examples/frigate_scanner.rs diff --git a/scanners/remote/frigate/Cargo.toml b/scanners/remote/frigate/Cargo.toml index 0c9120f6..60d2c23e 100644 --- a/scanners/remote/frigate/Cargo.toml +++ b/scanners/remote/frigate/Cargo.toml @@ -13,10 +13,14 @@ silentpayments.workspace = true bitcoin.workspace = true futures.workspace = true -tokio = { version = "1", features = ["macros", "rt-multi-thread"] } +tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "time"] } log.workspace = true async-trait.workspace = true anyhow.workspace = true +[dev-dependencies] +spdk-wallet.workspace = true +env_logger = "0.11" + [lints] workspace = true diff --git a/scanners/remote/frigate/examples/frigate_scanner.rs b/scanners/remote/frigate/examples/frigate_scanner.rs new file mode 100644 index 00000000..66519c29 --- /dev/null +++ b/scanners/remote/frigate/examples/frigate_scanner.rs @@ -0,0 +1,57 @@ +use std::collections::{HashMap, HashSet}; + +use bitcoin::absolute::Height; +use bitcoin::secp256k1::SecretKey; +use bitcoin::{BlockHash, Network, OutPoint}; +use frigate::client::FrigateClient; +use frigate::scanner::FrigateScanner; +use spdk_core::scanner::{DiscoveredOutput, Scanner as _}; +use spdk_wallet::client::{SpClient, SpendKey}; + +const NETWORK: Network = Network::Signet; +const FRIGATE_BACKEND_URL: &str = "100.81.213.115:50102"; +// scan range settings +const SCAN_START_HEIGHT: u32 = 326_000; +const SCAN_END_HEIGHT: u32 = 326_595; + +// scan & spend key bytes, these should be randomly generated, +// but for this example we use simple byte arrays +const SCAN_SK_BYTES: [u8; 32] = [0x01; 32]; +const SPEND_SK_BYTES: [u8; 32] = [0x02; 32]; + +#[derive(Debug)] +pub struct UpdateResult { + pub blkheight: Height, + pub blkhash: BlockHash, + pub discovered_inputs: HashSet, + pub discovered_outputs: HashMap, +} + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + env_logger::init(); + let scan_sk = SecretKey::from_slice(&SCAN_SK_BYTES)?; + let spend_sk = SecretKey::from_slice(&SPEND_SK_BYTES)?; + + let frigate_client = FrigateClient::connect(FRIGATE_BACKEND_URL).await?; + + let sp_client = SpClient::new(scan_sk, SpendKey::Secret(spend_sk), NETWORK)?; + let sp_receiver = sp_client.receiver(); + + let frigate_scanner = FrigateScanner::new(frigate_client, scan_sk, sp_receiver, None); + + println!("Receiving code for this key pair + network:"); + println!("{}", sp_client.receiving_code()); + + let start = Height::from_consensus(SCAN_START_HEIGHT)?; + let end = Height::from_consensus(SCAN_END_HEIGHT)?; + + let mut rx = frigate_scanner.scan_blocks(start..=end); + + while let Ok(update) = rx.recv().await { + // print all received updates + println!("{update:#?}"); + } + + Ok(()) +} diff --git a/scanners/remote/frigate/src/client.rs b/scanners/remote/frigate/src/client.rs index fe427244..4b5f791e 100644 --- a/scanners/remote/frigate/src/client.rs +++ b/scanners/remote/frigate/src/client.rs @@ -1,14 +1,20 @@ -use std::{collections::HashSet, ops::RangeInclusive, pin::Pin, time::Duration}; +use std::collections::HashSet; +use std::ops::RangeInclusive; +use std::pin::Pin; +use std::time::Duration; -use bitcoin::{ - Amount, BlockHash, OutPoint, Txid, absolute::Height, -}; use async_trait::async_trait; -use electrum_streaming_client::{AsyncClient, Event, request, response::{FullTx, HeaderResp}}; -use futures::{Stream, channel::mpsc::UnboundedReceiver}; - +use bitcoin::absolute::Height; +use bitcoin::{Amount, BlockHash, OutPoint, Txid}; +use electrum_streaming_client::response::{FullTx, HeaderResp}; +use electrum_streaming_client::{AsyncClient, Event, request}; +use futures::Stream; +use futures::channel::mpsc::UnboundedReceiver; +use log::{debug, info}; use spdk_core::chain::{BoxedBlockData, ChainBackend, UtxoData}; -use tokio::{net::TcpStream, task::JoinHandle, time::timeout}; +use tokio::net::TcpStream; +use tokio::task::JoinHandle; +use tokio::time::timeout; #[derive(Debug)] pub struct FrigateClient { @@ -17,9 +23,9 @@ pub struct FrigateClient { pub events: UnboundedReceiver, pub worker: JoinHandle>, pub request_timeout: Duration, + protocol_version: Option, } - #[derive(Debug)] pub enum FrigateError { Connection(String), @@ -44,7 +50,6 @@ impl std::fmt::Display for FrigateError { impl std::error::Error for FrigateError {} impl FrigateClient { - pub async fn connect(host_url: &str) -> Result { let stream = TcpStream::connect(host_url).await.map_err(|err| { FrigateError::Connection(format!("can't connect to socket '{host_url}': {err}")) @@ -55,12 +60,8 @@ impl FrigateClient { let worker = tokio::spawn(async move { match worker.await { - Ok(()) => { - Ok(()) - } - Err(e) => { - Err(e) - } + Ok(()) => Ok(()), + Err(e) => Err(e), } }); @@ -70,6 +71,7 @@ impl FrigateClient { events, worker, request_timeout: Duration::from_secs(10), + protocol_version: None, }) } @@ -81,6 +83,8 @@ impl FrigateClient { } pub async fn get_block_header(&mut self, height: u32) -> Result { + self.version().await?; + let res = timeout( self.request_timeout, self.client.send_request(request::Header { height }), @@ -92,6 +96,8 @@ impl FrigateClient { } pub async fn get_transaction(&mut self, txid: Txid) -> Result { + self.version().await?; + let res = timeout( self.request_timeout, self.client.send_request(request::GetTx { txid }), @@ -102,13 +108,20 @@ impl FrigateClient { Ok(res) } - /// Send a request to the Frigate electrum server for version negotiation - /// This is the first request that should be sent before subsequent one. + /// Negotiate the Frigate protocol version once and cache the result. + /// + /// The negotiation is sent as the first request on the connection. Later calls return the + /// cached version without sending another request. pub async fn version(&mut self) -> Result { + if let Some(protocol_version) = &self.protocol_version { + return Ok(protocol_version.clone()); + } + + debug!("Sending version request to Frigate server..."); let res = timeout( self.request_timeout, self.client.send_request(request::ServerVersion { - client_name: "bdk-sp".into(), + client_name: "spdk".into(), protocol_version: request::SupportedVersion::Range([ "1.3.2".into(), "1.4.1".into(), @@ -118,19 +131,19 @@ impl FrigateClient { .await .map_err(|_| FrigateError::Timeout("Version request timed out".to_owned()))? .map_err(|e| FrigateError::Request(format!("Version request failed: {e}")))?; + self.protocol_version = Some(res.protocol_version.clone()); Ok(res.protocol_version) } - /// Make a request to the Frigate electrum server to subscribe to the outputs beloging to the given silent payment address - /// Once the server receives the request notification will be sent to the client everytime an ouput is found. + /// Make a request to the Frigate electrum server to subscribe to the outputs beloging to the + /// given silent payment address Once the server receives the request notification will be + /// sent to the client everytime an ouput is found. /// /// See: - pub async fn subscribe( - &mut self, - subscribe_req: request::SpSubscribe, - ) -> Result { - log::debug!("Sending subscribe event request..."); - + pub async fn subscribe(&mut self, subscribe_req: request::SpSubscribe) -> Result { + self.version().await?; + debug!("Sending subscribe event request..."); + let res = timeout( self.request_timeout, self.client.send_request(subscribe_req), @@ -139,20 +152,19 @@ impl FrigateClient { .map_err(|_| FrigateError::Timeout("Subscribe request timed out".to_owned()))? .map_err(|e| FrigateError::Request(format!("Subscribe request failed: {e}")))?; - log::info!("Subscribed to silent payment address: {res}"); + info!("Subscribed to silent payment address: {res}"); Ok(res) } - pub async fn unsubscribe( - &mut self, - unsub_req: request::SpUnsubscribe, - ) -> Result<()> { + pub async fn unsubscribe(&mut self, unsub_req: request::SpUnsubscribe) -> Result<()> { + self.version().await?; + let res = timeout(self.request_timeout, self.client.send_request(unsub_req)) .await .map_err(|_| FrigateError::Timeout("Unsubscribe request timed out".to_owned()))? .map_err(|e| FrigateError::Request(format!("Unsubscribe request failed: {e}")))?; - log::info!("Unsubscribed to silent payment address: {res:?}"); + info!("Unsubscribed to silent payment address: {res:?}"); Ok(()) } } @@ -180,4 +192,4 @@ impl ChainBackend for FrigateClient { async fn utxos(&self, _block_height: Height) -> anyhow::Result> { unimplemented!("Not needed for frigate implementation") } -} \ No newline at end of file +} diff --git a/scanners/remote/frigate/src/lib.rs b/scanners/remote/frigate/src/lib.rs index 2f91c788..78619406 100644 --- a/scanners/remote/frigate/src/lib.rs +++ b/scanners/remote/frigate/src/lib.rs @@ -1,2 +1,2 @@ +pub mod client; pub mod scanner; -pub mod client; \ No newline at end of file diff --git a/scanners/remote/frigate/src/scanner.rs b/scanners/remote/frigate/src/scanner.rs index cf9145b3..28492311 100644 --- a/scanners/remote/frigate/src/scanner.rs +++ b/scanners/remote/frigate/src/scanner.rs @@ -1,11 +1,20 @@ -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; -use bitcoin::{OutPoint, Txid, absolute::Height, secp256k1::{PublicKey, SecretKey}}; -use electrum_streaming_client::{Event, notification::Notification, request, response::TxTweak}; -use futures::{SinkExt as _, StreamExt as _, channel::mpsc::{Receiver, channel}}; -use log::{debug, info}; +use bitcoin::absolute::Height; +use bitcoin::secp256k1::{PublicKey, Scalar, SecretKey}; +use bitcoin::{OutPoint, ScriptBuf, Transaction, TxOut, Txid, XOnlyPublicKey}; +use electrum_streaming_client::notification::Notification; +use electrum_streaming_client::{Event, request}; +use futures::channel::mpsc::{Receiver, channel}; +use futures::{SinkExt as _, StreamExt as _}; +use log::{debug, error, info}; +use silentpayments::SharedSecret; +use silentpayments::receiving::{Label, Receiver as SpReceiver}; +use silentpayments::utils::receiving::{ + calculate_ecdh_shared_secret, generate_script_pubkey_from_output_key, +}; +use spdk_core::chain::UtxoData; use spdk_core::scanner::{DiscoveredOutput, ScanResult, Scanner}; -use silentpayments::receiving::Receiver as SpReceiver; use crate::client::FrigateClient; @@ -13,7 +22,7 @@ pub struct FrigateScanner { client: FrigateClient, b_scan: SecretKey, sp_receiver: SpReceiver, - labels: Option> + labels: Option>, } impl FrigateScanner { @@ -21,40 +30,44 @@ impl FrigateScanner { client: FrigateClient, b_scan: SecretKey, sp_receiver: SpReceiver, - labels: Option> + labels: Option>, ) -> Self { - Self { - client, - b_scan, - sp_receiver, - labels, - } + Self { + client, + b_scan, + sp_receiver, + labels, } + } } impl Scanner for FrigateScanner { + #[expect(clippy::too_many_lines, reason = "will be refactored once needed")] fn scan_blocks(mut self, range: std::ops::RangeInclusive) -> Receiver { let subscribe_params = request::SpSubscribe { scan_priv_key: self.b_scan, spend_pub_key: self.sp_receiver.receiving_code().m_pubkey(), start_height: Some(range.start().to_consensus_u32()), - labels: self.labels + labels: self.labels, }; info!( "start: {} end: {}", range.start().to_consensus_u32(), range.end().to_consensus_u32(), - ); + ); let (mut tx, rx) = channel(100_000); - tokio::spawn( async move { - - if let Ok(sp_address) = self.client.subscribe(subscribe_params).await { - info!("Subscribed to silent payments address {sp_address}"); - } else { - log::error!("Unable to subscribe"); + tokio::spawn(async move { + // Maybe later check if there's any current subscription and skip, just listen to + // events. + match self.client.subscribe(subscribe_params).await { + Ok(sp_address) => info!("Subscribed to silent payments address {sp_address}"), + Err(e) => { + error!("Unable to subscribe to silent payments: {e}"); + return; + } } while let Some(event) = self.client.events.next().await { @@ -64,12 +77,18 @@ impl Scanner for FrigateScanner { let histories = sp_subscribe_notification.history.clone(); let progress = sp_subscribe_notification.progress; - let mut secrets_by_height: HashMap> = HashMap::new(); + let mut secrets_by_height: BTreeMap> = + BTreeMap::new(); debug!("Received history {histories:#?}"); info!("Found a total of {} output(s)", histories.len()); - for h in &histories { + for h in &histories { + if h.height == 0 { + debug!("Skipping mempool transaction {}", h.tx_hash); + continue; + } + secrets_by_height .entry(h.height) .and_modify(|v| { @@ -79,21 +98,73 @@ impl Scanner for FrigateScanner { } for history in secrets_by_height { - let discovered_inputs = HashSet::::new(); - let discovered_outputs = HashMap::::new(); - - let blk_header = self.client.get_block_header(history.0).await.unwrap(); - - let scan_res = ScanResult { - blkheight: Height::from_consensus(history.0).unwrap(), - blkhash: blk_header.header.block_hash(), - discovered_inputs, - discovered_outputs, + let blk_header = match self.client.get_block_header(history.0).await + { + Ok(header) => header, + Err(e) => { + error!( + "Unable to fetch block header at height {}: {e}", + history.0 + ); + return; + } }; + let blkheight = match Height::from_consensus(history.0) { + Ok(height) => height, + Err(e) => { + error!( + "Invalid block height {} received from Frigate: {e}", + history.0 + ); + return; + } + }; + + // Get now the outputs from the transaction belonging to the key + // we're scanning for. + // Once done just return the scan result + + for tx_tweak in history.1 { + let discovered_inputs = HashSet::::new(); + let full_tx = + match self.client.get_transaction(tx_tweak.0).await { + Ok(full_tx) => full_tx, + Err(e) => { + error!( + "Unable to fetch transaction {}: {e}", + tx_tweak.0 + ); + return; + } + }; + let discovered_outputs = match process_outputs( + &full_tx.tx, + &self.b_scan, + &self.sp_receiver, + &[tx_tweak.1], + ) { + Ok(outputs) => outputs, + Err(e) => { + error!( + "Unable to process transaction {}: {e}", + tx_tweak.0 + ); + return; + } + }; + + let scan_res = ScanResult { + blkheight, + blkhash: blk_header.header.block_hash(), + discovered_inputs, + discovered_outputs, + }; - match tx.send(scan_res).await { - Ok(()) => info!("Scan result sent!"), - Err(e) => log::error!("Unable to send scan result: {e}") + if let Err(e) = tx.send(scan_res).await { + error!("Unable to send scan result: {e}; stopping scan"); + return; + } + info!("Scan result sent!"); } } @@ -101,11 +172,8 @@ impl Scanner for FrigateScanner { info!("Scanning completed!"); break; } - - subscribe_to_owned_outpouts(&self.client, histories).await; } - Notification::ScriptHash(_script_hash_notification) => todo!(), - _ => info!("Notification event not supported.") + _ => error!("Notification event not supported."), } } } @@ -115,6 +183,107 @@ impl Scanner for FrigateScanner { } } -async fn subscribe_to_owned_outpouts(_client: &FrigateClient, _tx_hash: Vec) {} +fn process_outputs( + tx: &Transaction, + b_scan: &SecretKey, + sp_receiver: &SpReceiver, + tweaks: &[PublicKey], +) -> anyhow::Result> { + let secret_map = output_key_to_secret_map(b_scan, sp_receiver, tweaks.to_owned())?; + let txid: Txid = tx.compute_txid(); + let outputs_to_check = tx + .output + .iter() + .enumerate() + .filter(|(_idx, x)| x.script_pubkey.is_p2tr()) + .map(|(idx, txout)| { + let output_key = XOnlyPublicKey::from_slice(&txout.script_pubkey.as_bytes()[2..]) + .map_err(|e| anyhow::anyhow!("invalid Taproot output key at index {idx}: {e}"))?; + let vout = u32::try_from(idx) + .map_err(|e| anyhow::anyhow!("output index {idx} does not fit in u32: {e}"))?; + Ok(UtxoData { + txid, + vout, + value: txout.value, + output_key, + spent: false, + }) + }) + .collect::>>()?; + + let output_keys: Vec = outputs_to_check + .iter() + .map(|utxo| utxo.output_key) + .collect(); + + let mut scan_res: Vec<(Option