client.rs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. collections::{HashMap, HashSet, VecDeque},
  20. io::Cursor,
  21. sync::{
  22. atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
  23. Arc,
  24. },
  25. };
  26. use darkfi::{
  27. event_graph::{proto::EventPut, Event, NULL_ID},
  28. system::Subscription,
  29. zk::{empty_witnesses, Proof, ProvingKey, ZkCircuit},
  30. zkas::ZkBinary,
  31. Error, Result,
  32. };
  33. use darkfi_sdk::{
  34. bridgetree::Position,
  35. crypto::{pasta_prelude::PrimeField, poseidon_hash, MerkleTree},
  36. pasta::pallas,
  37. };
  38. use darkfi_serial::{deserialize_async, serialize_async};
  39. use futures::FutureExt;
  40. use log::{debug, error, info, warn};
  41. use sled_overlay::sled;
  42. use smol::{
  43. io::{self, AsyncBufReadExt, AsyncWriteExt, BufReader},
  44. lock::{OnceCell, RwLock},
  45. net::SocketAddr,
  46. prelude::{AsyncRead, AsyncWrite},
  47. };
  48. use super::{
  49. server::{IrcServer, MAX_MSG_LEN},
  50. Msg, NickServ, OldPrivmsg, SERVER_NAME,
  51. };
  52. use crate::crypto::rln::{
  53. closest_epoch, hash_event, RlnIdentity, RLN2_SIGNAL_ZKBIN, RLN_APP_IDENTIFIER,
  54. };
  55. const PENALTY_LIMIT: usize = 5;
  56. /// Reply types, we can either send server replies, or client replies.
  57. pub enum ReplyType {
  58. /// Server reply, we have to use numerics
  59. Server((u16, String)),
  60. /// Client reply, message from someone to some{one,where}
  61. Client((String, String)),
  62. /// Pong reply, we just use server origin
  63. Pong(String),
  64. /// CAP reply
  65. Cap(String),
  66. /// NOTICE reply (from, to, what)
  67. Notice((String, String, String)),
  68. }
  69. /// Stateful IRC client handler, used for each client connection
  70. pub struct Client {
  71. /// Pointer to parent `IrcServer`
  72. pub server: Arc<IrcServer>,
  73. /// Subscription for incoming events
  74. pub incoming: Subscription<Event>,
  75. /// Client socket addr
  76. pub addr: SocketAddr,
  77. /// ID of the last sent event
  78. pub last_sent: RwLock<blake3::Hash>,
  79. /// Active (joined) channels for this client
  80. pub channels: RwLock<HashSet<String>>,
  81. /// Penalty counter, when limit is reached, disconnect client
  82. pub penalty: AtomicUsize,
  83. /// Registration marker
  84. pub registered: AtomicBool,
  85. /// Registration pause marker
  86. pub reg_paused: AtomicBool,
  87. /// CAP END marker
  88. pub is_cap_end: AtomicBool,
  89. /// Password setup marker
  90. pub is_pass_set: AtomicBool,
  91. /// Client username
  92. pub username: Arc<RwLock<String>>,
  93. /// Client nickname
  94. pub nickname: Arc<RwLock<String>>,
  95. /// Client realname
  96. pub realname: RwLock<String>,
  97. /// Client caps
  98. pub caps: RwLock<HashMap<String, bool>>,
  99. /// Set of seen messages for the user
  100. /// TODO: It grows indefinitely, needs to be pruned.
  101. pub seen: OnceCell<sled::Tree>,
  102. /// NickServ instance
  103. pub nickserv: Arc<NickServ>,
  104. }
  105. impl Client {
  106. /// Instantiate a new Client.
  107. pub async fn new(
  108. server: Arc<IrcServer>,
  109. incoming: Subscription<Event>,
  110. addr: SocketAddr,
  111. ) -> Result<Self> {
  112. let caps =
  113. HashMap::from([("no-history".to_string(), false), ("no-autojoin".to_string(), false)]);
  114. let username = Arc::new(RwLock::new(String::from("*")));
  115. let nickname = Arc::new(RwLock::new(String::from("*")));
  116. Ok(Self {
  117. server: server.clone(),
  118. incoming,
  119. addr,
  120. last_sent: RwLock::new(NULL_ID),
  121. channels: RwLock::new(HashSet::new()),
  122. penalty: AtomicUsize::new(0),
  123. registered: AtomicBool::new(false),
  124. reg_paused: AtomicBool::new(false),
  125. is_cap_end: AtomicBool::new(false),
  126. is_pass_set: AtomicBool::new(false),
  127. username: username.clone(),
  128. nickname: nickname.clone(),
  129. realname: RwLock::new(String::from("*")),
  130. caps: RwLock::new(caps),
  131. seen: OnceCell::new(),
  132. nickserv: Arc::new(
  133. NickServ::new(username.clone(), nickname.clone(), server.clone()).await?,
  134. ),
  135. })
  136. }
  137. /// This function handles a single IRC client. We listen to messages from the
  138. /// IRC client and relay them to the network, and we also get notified of
  139. /// incoming messages and relay them to the IRC client. The notifications come
  140. /// from events being inserted into the Event Graph.
  141. pub async fn multiplex_connection<S>(&self, stream: S) -> Result<()>
  142. where
  143. S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
  144. {
  145. let (reader, mut writer) = io::split(stream);
  146. let mut reader = BufReader::new(reader);
  147. // Our buffer for the client line
  148. let mut line = String::new();
  149. let mut args_queue: VecDeque<_> = VecDeque::new();
  150. loop {
  151. futures::select! {
  152. // Process message from the IRC client
  153. r = reader.read_line(&mut line).fuse() => {
  154. // If something failed during reading, we disconnect.
  155. if let Err(e) = r {
  156. error!("[IRC CLIENT] Read failed for {}: {}", self.addr, e);
  157. self.incoming.unsubscribe().await;
  158. return Err(Error::ChannelStopped)
  159. }
  160. // If the penalty limit is reached, disconnect the client.
  161. if self.penalty.load(SeqCst) == PENALTY_LIMIT {
  162. self.incoming.unsubscribe().await;
  163. return Err(Error::ChannelStopped)
  164. }
  165. // We'll be strict here and disconnect the client
  166. // in case line processing failed in any way.
  167. match self.process_client_line(&line, &mut writer, &mut args_queue).await {
  168. // If we got an event back, we should broadcast it.
  169. // This means we add it to our DAG, and the DAG will
  170. // handle the rest of the propagation.
  171. Ok(Some(events)) => {
  172. for event in events {
  173. // Update the last sent event.
  174. let event_id = event.id();
  175. *self.last_sent.write().await = event_id;
  176. // If it fails for some reason, for now, we just note it and pass.
  177. if let Err(e) = self.server.darkirc.event_graph.dag_insert(&[event.clone()]).await {
  178. error!("[IRC CLIENT] Failed inserting new event to DAG: {}", e);
  179. } else {
  180. // We sent this, so it should be considered seen.
  181. if let Err(e) = self.mark_seen(&event_id).await {
  182. error!("[IRC CLIENT] (multiplex_connection) self.mark_seen({}) failed: {}", event_id, e);
  183. return Err(e)
  184. }
  185. // If we have a RLN identity, now we'll build a ZK proof.
  186. // Also I really want GOTO in Rust... Fags.
  187. if let Some(mut rln_identity) = *self.server.rln_identity.write().await {
  188. // If the current epoch is different, we can reset the message counter
  189. if rln_identity.last_epoch != closest_epoch(event.timestamp) {
  190. rln_identity.last_epoch = closest_epoch(event.timestamp);
  191. rln_identity.message_id = 0;
  192. }
  193. rln_identity.message_id += 1;
  194. let (_proof, _public_inputs) = match self.create_rln_signal_proof(&rln_identity, &event).await {
  195. Ok(v) => v,
  196. Err(e) => {
  197. // TODO: Send a message to the IRC client telling that sending went wrong
  198. error!("[IRC CLIENT] Failed creating RLN signal proof: {}", e);
  199. // Just use an empty "proof"
  200. (Proof::new(vec![]), vec![])
  201. }
  202. };
  203. self.server.darkirc.p2p.broadcast(&EventPut(event)).await;
  204. } else {
  205. // Broadcast it
  206. self.server.darkirc.p2p.broadcast(&EventPut(event)).await;
  207. }
  208. }
  209. }
  210. }
  211. // If we got nothing, we just pass.
  212. Ok(None) => {}
  213. // If we got an error, we disconnect the client.
  214. Err(e) => {
  215. self.incoming.unsubscribe().await;
  216. return Err(e)
  217. }
  218. }
  219. // Clear the line buffer
  220. line = String::new();
  221. }
  222. // Process message from the network. These should only be PRIVMSG.
  223. r = self.incoming.receive().fuse() => {
  224. // We will skip this if it's our own message.
  225. let event_id = r.id();
  226. if *self.last_sent.read().await == event_id {
  227. continue
  228. }
  229. // If this event was seen, skip it
  230. match self.is_seen(&event_id).await {
  231. Ok(true) => continue,
  232. Ok(false) => {},
  233. Err(e) => {
  234. error!("[IRC CLIENT] (multiplex_connection) self.is_seen({}) failed: {}", event_id, e);
  235. return Err(e)
  236. }
  237. }
  238. // If the Event contains an appended blob of data, try to check if it's
  239. // a RLN Signal proof and verify it.
  240. //if false {
  241. let mut verification_failed = false;
  242. #[allow(clippy::never_loop)]
  243. loop {
  244. let (event, blob) = (r.clone(), vec![0,1,2]);
  245. let (proof, public_inputs): (Proof, Vec<pallas::Base>) = match deserialize_async(&blob).await {
  246. Ok(v) => v,
  247. Err(e) => {
  248. // TODO: FIXME: This logic should be better written.
  249. // Right now we don't enforce RLN so we can just fall-through.
  250. //error!("[IRC CLIENT] Failed deserializing event ephemeral data: {}", e);
  251. break
  252. }
  253. };
  254. if public_inputs.len() != 2 {
  255. error!("[IRC CLIENT] Received event has the wrong number of public inputs");
  256. verification_failed = true;
  257. break
  258. }
  259. info!("[IRC CLIENT] Verifying incoming Event RLN proof");
  260. if self.verify_rln_signal_proof(
  261. &event,
  262. proof,
  263. [public_inputs[0], public_inputs[1]],
  264. ).await.is_err() {
  265. verification_failed = true;
  266. break
  267. }
  268. // TODO: Store for secret shares recovery
  269. info!("[IRC CLIENT] RLN verification successful");
  270. break
  271. }
  272. if verification_failed {
  273. error!("[IRC CLIENT] Incoming Event proof verification failed");
  274. continue
  275. }
  276. // Try to deserialize the `Event`'s content into a `Privmsg`
  277. let mut privmsg = match Msg::deserialize(r.content()).await {
  278. Ok(Msg::V1(old_msg)) => old_msg.into_new(),
  279. Ok(Msg::V2(new_msg)) => new_msg,
  280. Err(e) => {
  281. error!("[IRC CLIENT] Failed deserializing incoming Privmsg event: {}", e);
  282. continue
  283. }
  284. };
  285. // If successful, potentially decrypt it:
  286. self.server.try_decrypt(&mut privmsg, self.nickname.read().await.as_ref()).await;
  287. // We should skip any attempts to contact services from the network.
  288. if ["nickserv", "chanserv"].contains(&privmsg.nick.to_lowercase().as_str()) {
  289. continue
  290. }
  291. // If the privmsg is not intented for any of the given
  292. // channels or contacts, ignore it
  293. // otherwise add it as a reply and mark it as seen
  294. // in the seen_events tree.
  295. let channels = self.channels.read().await;
  296. let contacts = self.server.contacts.read().await;
  297. if !channels.contains(&privmsg.channel) &&
  298. !contacts.contains_key(&privmsg.channel)
  299. {
  300. continue
  301. }
  302. // Add the nickname to the list of nicks on the channel, if it's a channel.
  303. let mut chans_lock = self.server.channels.write().await;
  304. if let Some(chan) = chans_lock.get_mut(&privmsg.channel) {
  305. chan.nicks.insert(privmsg.nick.clone());
  306. }
  307. drop(chans_lock);
  308. // Handle message lines individually
  309. for line in privmsg.msg.lines() {
  310. // Skip empty lines
  311. if line.is_empty() {
  312. continue
  313. }
  314. // Format the message
  315. let msg = format!("PRIVMSG {} :{}", privmsg.channel, line);
  316. // Send it to the client
  317. let reply = ReplyType::Client((privmsg.nick.clone(), msg));
  318. if let Err(e) = self.reply(&mut writer, &reply).await {
  319. error!("[IRC CLIENT] Failed writing PRIVMSG to client: {}", e);
  320. continue
  321. }
  322. }
  323. // Mark the message as seen for this USER
  324. if let Err(e) = self.mark_seen(&event_id).await {
  325. error!("[IRC CLIENT] (multiplex_connection) self.mark_seen({}) failed: {}", event_id, e);
  326. return Err(e)
  327. }
  328. }
  329. }
  330. }
  331. }
  332. /// Send a reply to the IRC client. Matches on the reply type.
  333. async fn reply<W>(&self, writer: &mut W, reply: &ReplyType) -> Result<()>
  334. where
  335. W: AsyncWrite + Unpin,
  336. {
  337. let r = match reply {
  338. ReplyType::Server((rpl, msg)) => format!(":{} {:03} {}", SERVER_NAME, rpl, msg),
  339. ReplyType::Client((nick, msg)) => format!(":{}!~anon@darkirc {}", nick, msg),
  340. ReplyType::Pong(origin) => format!(":{} PONG :{}", SERVER_NAME, origin),
  341. ReplyType::Cap(msg) => format!(":{} {}", SERVER_NAME, msg),
  342. ReplyType::Notice((src, dst, msg)) => {
  343. format!(":{}!~anon@darkirc NOTICE {} :{}", src, dst, msg)
  344. }
  345. };
  346. debug!("[{}] <-- {}", self.addr, r);
  347. writer.write(r.as_bytes()).await?;
  348. writer.write(b"\r\n").await?;
  349. writer.flush().await?;
  350. Ok(())
  351. }
  352. /// Handle the incoming line given sent by the IRC client
  353. async fn process_client_line<W>(
  354. &self,
  355. line: &str,
  356. writer: &mut W,
  357. args_queue: &mut VecDeque<String>,
  358. ) -> Result<Option<Vec<Event>>>
  359. where
  360. W: AsyncWrite + Unpin,
  361. {
  362. if line.trim().is_empty() {
  363. // Silently ignore empty commands
  364. return Ok(None)
  365. }
  366. let mut line = line.to_string();
  367. // Remove CRLF
  368. if &line[(line.len() - 2)..] == "\r\n" {
  369. line.pop();
  370. line.pop();
  371. } else if &line[(line.len() - 1)..] == "\n" {
  372. line.pop();
  373. } else {
  374. return Err(Error::ParseFailed("Line doesn't end with CR/LF"))
  375. }
  376. // Prefix the message part of PRIVMSG with ':' if is not already.
  377. // Or realname part of USER command.
  378. let mut words: Vec<String> = line.split_whitespace().map(|s| s.to_string()).collect();
  379. if words[0].to_uppercase() == "PRIVMSG" {
  380. if words.len() > 1 && !words[2].starts_with(':') {
  381. words[2] = format!(":{}", words[2]);
  382. }
  383. line = words.join(" ");
  384. } else if words[0].to_uppercase() == "USER" {
  385. if words.len() > 1 && !words[4].starts_with(':') {
  386. words[4] = format!(":{}", words[4]);
  387. }
  388. line = words.join(" ");
  389. }
  390. // Parse the line
  391. let mut tokens = line.split_ascii_whitespace();
  392. // Commands can begin with :garbage, but we will reject clients
  393. // doing that for now to keep the protocol simple and focused.
  394. let cmd = tokens.next().ok_or(Error::ParseFailed("Invalid command line"))?;
  395. let args = line.replacen(cmd, "", 1);
  396. let cmd = cmd.to_uppercase();
  397. debug!("[{}] --> {}{}", self.addr, cmd, args);
  398. // Handle the command. These implementations are in `command.rs`.
  399. let replies: Vec<ReplyType> = match cmd.as_str() {
  400. "ADMIN" => self.handle_cmd_admin(&args).await?,
  401. "CAP" => self.handle_cmd_cap(&args).await?,
  402. "INFO" => self.handle_cmd_info(&args).await?,
  403. "JOIN" => self.handle_cmd_join(&args, true).await?,
  404. "LIST" => self.handle_cmd_list(&args).await?,
  405. "MODE" => self.handle_cmd_mode(&args).await?,
  406. "MOTD" => self.handle_cmd_motd(&args).await?,
  407. "NAMES" => self.handle_cmd_names(&args).await?,
  408. "NICK" => self.handle_cmd_nick(&args).await?,
  409. "PART" => self.handle_cmd_part(&args).await?,
  410. "PASS" => self.handle_cmd_pass(&args).await?,
  411. "PING" => self.handle_cmd_ping(&args).await?,
  412. "PRIVMSG" => self.handle_cmd_privmsg(&args).await?,
  413. "REHASH" => self.handle_cmd_rehash(&args).await?,
  414. "TOPIC" => self.handle_cmd_topic(&args).await?,
  415. "USER" => self.handle_cmd_user(&args).await?,
  416. "VERSION" => self.handle_cmd_version(&args).await?,
  417. "QUIT" => return Err(Error::ChannelStopped),
  418. _ => {
  419. warn!("[IRC CLIENT] Unimplemented \"{}\" command", cmd);
  420. vec![]
  421. }
  422. };
  423. // Depending on the reply type, we send according messages.
  424. for reply in replies.iter() {
  425. self.reply(writer, reply).await?;
  426. }
  427. // If the command was a PRIVMSG the client sent, we need to encrypt it and
  428. // create an Event to broadcast and return it from this function. So let's try.
  429. // We also do not allow sending unencrypted DMs. In that case, we send a notice
  430. // to the client to inform them that the feature is not enabled.
  431. // NOTE: This is not the most performant way to do this, probably not even
  432. // TODO: the best place to do it. Patches welcome. It's also a bit fragile
  433. // since we assume that `handle_cmd_privmsg()` won't return any replies.
  434. if cmd.as_str() == "PRIVMSG" && replies.is_empty() {
  435. // If the DAG is not synced yet, queue client lines
  436. // Once synced, send queued lines and continue as normal
  437. if !*self.server.darkirc.event_graph.synced.read().await {
  438. debug!("DAG is still syncing, queuing and skipping...");
  439. args_queue.push_back(args);
  440. return Ok(None)
  441. }
  442. // Check if we have queued PRIVMSGs, if we do send all of them first.
  443. let mut pending_events = vec![];
  444. if !args_queue.is_empty() {
  445. for _ in 0..args_queue.len() {
  446. let args = args_queue.pop_front().unwrap();
  447. pending_events.push(self.privmsg_to_event(args).await);
  448. }
  449. return Ok(Some(pending_events))
  450. }
  451. // If queue is empty, create an event and return it
  452. let event = self.privmsg_to_event(args).await;
  453. return Ok(Some(vec![event]))
  454. }
  455. Ok(None)
  456. }
  457. // Internal helper function that creates an Event from PRIVMSG arguments
  458. async fn privmsg_to_event(&self, args: String) -> Event {
  459. let channel = args.split_ascii_whitespace().next().unwrap().to_string();
  460. let msg_offset = args.find(':').unwrap() + 1;
  461. let (_, msg) = args.split_at(msg_offset);
  462. // Truncate messages longer than MAX_MSG_LEN
  463. let msg = if msg.len() > MAX_MSG_LEN { msg.split_at(MAX_MSG_LEN).0 } else { msg };
  464. // TODO: This is kept as old version of privmsg, since now we
  465. // can deserialize both old and new versions, after some time
  466. // this will be replaced with Privmsg (new version)
  467. let mut privmsg = OldPrivmsg {
  468. channel,
  469. nick: self.nickname.read().await.to_string(),
  470. msg: msg.to_string(),
  471. };
  472. // Encrypt the Privmsg if an encryption method is available.
  473. self.server.try_encrypt(&mut privmsg).await;
  474. // Build a DAG event and return it.
  475. Event::new(serialize_async(&privmsg).await, &self.server.darkirc.event_graph).await
  476. }
  477. /// Atomically mark a message as seen for this client.
  478. pub async fn mark_seen(&self, event_id: &blake3::Hash) -> Result<()> {
  479. let db = self
  480. .seen
  481. .get_or_init(|| async {
  482. let u = self.username.read().await.to_string();
  483. self.server.darkirc.sled.open_tree(format!("darkirc_user_{}", u)).unwrap()
  484. })
  485. .await;
  486. debug!("Marking event {} as seen", event_id);
  487. let mut batch = sled::Batch::default();
  488. batch.insert(event_id.as_bytes(), &[]);
  489. Ok(db.apply_batch(batch)?)
  490. }
  491. /// Check if a message was already marked seen for this client.
  492. pub async fn is_seen(&self, event_id: &blake3::Hash) -> Result<bool> {
  493. let db = self
  494. .seen
  495. .get_or_init(|| async {
  496. let u = self.username.read().await.to_string();
  497. self.server.darkirc.sled.open_tree(format!("darkirc_user_{}", u)).unwrap()
  498. })
  499. .await;
  500. Ok(db.contains_key(event_id.as_bytes())?)
  501. }
  502. /// Abstraction for RLN signal proof creation
  503. async fn create_rln_signal_proof(
  504. &self,
  505. rln_identity: &RlnIdentity,
  506. event: &Event,
  507. ) -> Result<(Proof, Vec<pallas::Base>)> {
  508. let identity_commitment = rln_identity.commitment();
  509. // Fetch the commitment's leaf position in the Merkle tree
  510. let Some(identity_pos) =
  511. self.server.rln_identity_store.get(identity_commitment.to_repr())?
  512. else {
  513. return Err(Error::DatabaseError(
  514. "Identity not found in commitment tree store".to_string(),
  515. ))
  516. };
  517. let identity_pos: Position = deserialize_async(&identity_pos).await?;
  518. // Fetch the latest commitment Merkle tree
  519. let Some(identity_tree) = self.server.server_store.get("rln_identity_tree")? else {
  520. return Err(Error::DatabaseError(
  521. "RLN Identity tree not found in server store".to_string(),
  522. ))
  523. };
  524. let identity_tree: MerkleTree = deserialize_async(&identity_tree).await?;
  525. // Retrieve the ZK proving key from the db
  526. let signal_zkbin = ZkBinary::decode(RLN2_SIGNAL_ZKBIN)?;
  527. let signal_circuit = ZkCircuit::new(empty_witnesses(&signal_zkbin)?, &signal_zkbin);
  528. let Some(proving_key) = self.server.server_store.get("rlnv2-diff-signal-pk")? else {
  529. return Err(Error::DatabaseError(
  530. "RLN signal proving key not found in server store".to_string(),
  531. ))
  532. };
  533. let mut reader = Cursor::new(proving_key);
  534. let proving_key = ProvingKey::read(&mut reader, signal_circuit)?;
  535. rln_identity.create_signal_proof(event, &identity_tree, identity_pos, &proving_key)
  536. }
  537. /// Abstraction for RLN signal proof verification
  538. async fn verify_rln_signal_proof(
  539. &self,
  540. event: &Event,
  541. proof: Proof,
  542. public_inputs: [pallas::Base; 2],
  543. ) -> Result<()> {
  544. let epoch = pallas::Base::from(closest_epoch(event.timestamp));
  545. let external_nullifier = poseidon_hash([epoch, RLN_APP_IDENTIFIER]);
  546. let x = hash_event(event);
  547. let y = public_inputs[0];
  548. let internal_nullifier = public_inputs[1];
  549. // Fetch the latest commitment Merkle tree
  550. let Some(identity_tree) = self.server.server_store.get("rln_identity_tree")? else {
  551. return Err(Error::DatabaseError(
  552. "RLN Identity tree not found in server store".to_string(),
  553. ))
  554. };
  555. let identity_tree: MerkleTree = deserialize_async(&identity_tree).await?;
  556. let identity_root = identity_tree.root(0).unwrap();
  557. let public_inputs =
  558. vec![epoch, external_nullifier, x, y, internal_nullifier, identity_root.inner()];
  559. Ok(proof.verify(&self.server.rln_signal_vk, &public_inputs)?)
  560. }
  561. }