|
| 1 | +use bip157::tokio; |
| 2 | +use bip157::tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 3 | +use bip157::tokio::sync::mpsc::UnboundedSender; |
| 4 | +use bitcoin::Txid; |
| 5 | +use bitcoin::secp256k1::{PublicKey, SecretKey}; |
| 6 | +use jsonrpc::simple_http::{self, SimpleHttpTransport}; |
| 7 | +use jsonrpc::Client; |
| 8 | +use serde::{Deserialize, Serialize}; |
| 9 | +use serde_json::value::to_raw_value; |
| 10 | +use serde_json::Value; |
| 11 | + |
| 12 | +#[derive(Debug)] |
| 13 | +pub enum FrigateError { |
| 14 | + JsonRpc(jsonrpc::Error), |
| 15 | + ParseUrl(url::ParseError), |
| 16 | + Serde(serde_json::Error), |
| 17 | +} |
| 18 | + |
| 19 | +impl From<serde_json::Error> for FrigateError { |
| 20 | + fn from(value: serde_json::Error) -> Self { |
| 21 | + FrigateError::Serde(value) |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +impl From<url::ParseError> for FrigateError { |
| 26 | + fn from(value: url::ParseError) -> Self { |
| 27 | + Self::ParseUrl(value) |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +impl From<jsonrpc::Error> for FrigateError { |
| 32 | + fn from(value: jsonrpc::Error) -> Self { |
| 33 | + Self::JsonRpc(value) |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +pub struct FrigateClient { |
| 38 | + pub host_url: String, |
| 39 | + client: Client, |
| 40 | +} |
| 41 | + |
| 42 | +#[derive(Serialize, Deserialize)] |
| 43 | +pub struct History { |
| 44 | + pub height: u32, |
| 45 | + pub tx_hash: Txid, |
| 46 | + pub tweak_key: PublicKey, |
| 47 | + pub progress: f32, |
| 48 | +} |
| 49 | + |
| 50 | +#[derive(Serialize, Deserialize)] |
| 51 | +pub struct NotifPayload { |
| 52 | + scan_private_key: SecretKey, |
| 53 | + spend_public_key: PublicKey, |
| 54 | + address: String, |
| 55 | + labels: Option<Vec<u32>>, |
| 56 | + start_height: u32, |
| 57 | + progress: f32, |
| 58 | + history: Vec<History>, |
| 59 | +} |
| 60 | + |
| 61 | +#[derive(Serialize, Deserialize)] |
| 62 | +pub struct SubscribeRequest { |
| 63 | + pub scan_priv_key: SecretKey, |
| 64 | + pub spend_pub_key: PublicKey, |
| 65 | + pub start_height: Option<u32>, |
| 66 | + pub labels: Option<Vec<u32>>, |
| 67 | +} |
| 68 | + |
| 69 | +#[derive(Serialize, Deserialize)] |
| 70 | +pub struct UnsubscribeRequest { |
| 71 | + pub scan_privkey: SecretKey, |
| 72 | + pub spend_pubkey: PublicKey, |
| 73 | +} |
| 74 | + |
| 75 | +#[derive(Serialize, Deserialize)] |
| 76 | +pub struct GetRequest { |
| 77 | + pub tx_hash: Txid, |
| 78 | +} |
| 79 | + |
| 80 | +const SUBSCRIBE_RPC_METHOD: &str = "blockchain.silentpayments.subscribe"; |
| 81 | +const UNSUBSCRIBE_RPC_METHOD: &str = "blockchain.silentpayments.unsubscribe"; |
| 82 | +const GET_RPC_METHOD: &str = "blockchain.transaction.get"; |
| 83 | +const SUBSCRIBE_OWNED_OUTPUTS: &str = "blockchain.scripthash.subscribe"; |
| 84 | + |
| 85 | +impl FrigateClient { |
| 86 | + pub fn new( |
| 87 | + host_url: &str, |
| 88 | + user: Option<&str>, |
| 89 | + password: Option<&str>, |
| 90 | + ) -> Result<Self, simple_http::Error> { |
| 91 | + let transport = SimpleHttpTransport::builder() |
| 92 | + .url(host_url)? |
| 93 | + .auth(user.unwrap_or(""), password) |
| 94 | + .build(); |
| 95 | + |
| 96 | + Ok(Self { |
| 97 | + host_url: host_url.to_string(), |
| 98 | + client: Client::with_transport(transport), |
| 99 | + }) |
| 100 | + } |
| 101 | + |
| 102 | + pub fn subscribe(&self, req: &SubscribeRequest) -> Result<String, FrigateError> { |
| 103 | + let params = to_raw_value(&serde_json::json!(req))?; |
| 104 | + let req = self |
| 105 | + .client |
| 106 | + .build_request(SUBSCRIBE_RPC_METHOD, Some(¶ms)); |
| 107 | + let res = self.client.send_request(req)?; |
| 108 | + Ok(res.result()?) |
| 109 | + } |
| 110 | + |
| 111 | + pub fn unsubscribe(&self, req: &UnsubscribeRequest) -> Result<String, FrigateError> { |
| 112 | + let params = to_raw_value(&serde_json::json!(req))?; |
| 113 | + let req = self |
| 114 | + .client |
| 115 | + .build_request(UNSUBSCRIBE_RPC_METHOD, Some(¶ms)); |
| 116 | + let res = self.client.send_request(req)?; |
| 117 | + Ok(res.result()?) |
| 118 | + } |
| 119 | + |
| 120 | + pub fn get(&self, req: &GetRequest) -> Result<String, FrigateError> { |
| 121 | + let params = to_raw_value(req)?; |
| 122 | + let req = self.client.build_request(GET_RPC_METHOD, Some(¶ms)); |
| 123 | + let response = self.client.send_request(req)?; |
| 124 | + Ok(response.result()?) |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +pub struct FrigateListener { |
| 129 | + pub frigate_client: FrigateClient, |
| 130 | + sender: UnboundedSender<(Vec<History>, f32)>, |
| 131 | +} |
| 132 | + |
| 133 | +impl FrigateListener { |
| 134 | + pub fn new(frigate_client: FrigateClient, sender: UnboundedSender<(Vec<History>, f32)>) -> Self { |
| 135 | + Self { |
| 136 | + frigate_client, |
| 137 | + sender, |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + pub async fn run(&self, params: SubscribeRequest) -> Result<(), FrigateError> { |
| 142 | + let raw_subscribe_params = serde_json::json!(params); |
| 143 | + let mut tcp_stream = tokio::net::TcpStream::connect(self.frigate_client.host_url.clone()) |
| 144 | + .await |
| 145 | + .map_err(|e| FrigateError::JsonRpc(jsonrpc::Error::Transport(Box::new(e))))?; |
| 146 | + let (mut reader, mut writer) = tcp_stream.split(); |
| 147 | + |
| 148 | + writer |
| 149 | + .write_all(raw_subscribe_params.to_string().as_bytes()) |
| 150 | + .await |
| 151 | + .map_err(|e| FrigateError::JsonRpc(jsonrpc::Error::Transport(Box::new(e))))?; |
| 152 | + |
| 153 | + loop { |
| 154 | + let mut buffer = vec![0; 1024]; |
| 155 | + let n = reader |
| 156 | + .read(&mut buffer) |
| 157 | + .await |
| 158 | + .map_err(|e| FrigateError::JsonRpc(jsonrpc::Error::Transport(Box::new(e))))?; |
| 159 | + if n == 0 { |
| 160 | + break; |
| 161 | + } |
| 162 | + let response_str = String::from_utf8_lossy(&buffer[..n]); |
| 163 | + let result: Value = serde_json::from_str(&response_str).map_err(FrigateError::Serde)?; |
| 164 | + |
| 165 | + if result["result"].is_string() { |
| 166 | + tracing::info!("Subscribed to silent payment address: {:?}", result); |
| 167 | + } else if result["params"].is_object() { |
| 168 | + let histories: Vec<History> = |
| 169 | + serde_json::from_value(result["params"]["history"].clone()) |
| 170 | + .map_err(FrigateError::Serde)?; |
| 171 | + |
| 172 | + let progress = result["params"]["progress"].as_f64().unwrap_or(0.0) as f32; |
| 173 | + |
| 174 | + self.sender |
| 175 | + .send((histories, progress)) |
| 176 | + .map_err(|e| FrigateError::JsonRpc(jsonrpc::Error::Transport(Box::new(e))))?; |
| 177 | + |
| 178 | + if progress >= 1.0 { |
| 179 | + tracing::info!("Scanning completed"); |
| 180 | + break; |
| 181 | + } |
| 182 | + } |
| 183 | + } |
| 184 | + Ok(()) |
| 185 | + } |
| 186 | +} |
0 commit comments