client.rs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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 client closed unexpectedly, we disconnect.
  155. if let Ok(0) = r {
  156. error!("[IRC CLIENT] Read failed for {}: Client disconnected", self.addr);
  157. self.incoming.unsubscribe().await;
  158. return Err(Error::ChannelStopped)
  159. }
  160. // If something failed during reading, we disconnect.
  161. if let Err(e) = r {
  162. error!("[IRC CLIENT] Read failed for {}: {e}", self.addr);
  163. self.incoming.unsubscribe().await;
  164. return Err(Error::ChannelStopped)
  165. }
  166. // If the penalty limit is reached, disconnect the client.
  167. if self.penalty.load(SeqCst) == PENALTY_LIMIT {
  168. self.incoming.unsubscribe().await;
  169. return Err(Error::ChannelStopped)
  170. }
  171. // We'll be strict here and disconnect the client
  172. // in case line processing failed in any way.
  173. match self.process_client_line(&line, &mut writer, &mut args_queue).await {
  174. // If we got an event back, we should broadcast it.
  175. // This means we add it to our DAG, and the DAG will
  176. // handle the rest of the propagation.
  177. Ok(Some(events)) => {
  178. for event in events {
  179. // Update the last sent event.
  180. let event_id = event.id();
  181. *self.last_sent.write().await = event_id;
  182. // If it fails for some reason, for now, we just note it and pass.
  183. if let Err(e) = self.server.darkirc.event_graph.dag_insert(&[event.clone()]).await {
  184. error!("[IRC CLIENT] Failed inserting new event to DAG: {e}");
  185. } else {
  186. // We sent this, so it should be considered seen.
  187. if let Err(e) = self.mark_seen(&event_id).await {
  188. error!("[IRC CLIENT] (multiplex_connection) self.mark_seen({event_id}) failed: {e}");
  189. return Err(e)
  190. }
  191. // If we have a RLN identity, now we'll build a ZK proof.
  192. // Also I really want GOTO in Rust... Fags.
  193. if let Some(mut rln_identity) = *self.server.rln_identity.write().await {
  194. // If the current epoch is different, we can reset the message counter
  195. if rln_identity.last_epoch != closest_epoch(event.timestamp) {
  196. rln_identity.last_epoch = closest_epoch(event.timestamp);
  197. rln_identity.message_id = 0;
  198. }
  199. rln_identity.message_id += 1;
  200. let (_proof, _public_inputs) = match self.create_rln_signal_proof(&rln_identity, &event).await {
  201. Ok(v) => v,
  202. Err(e) => {
  203. // TODO: Send a message to the IRC client telling that sending went wrong
  204. error!("[IRC CLIENT] Failed creating RLN signal proof: {e}");
  205. // Just use an empty "proof"
  206. (Proof::new(vec![]), vec![])
  207. }
  208. };
  209. self.server.darkirc.p2p.broadcast(&EventPut(event)).await;
  210. } else {
  211. // Broadcast it
  212. self.server.darkirc.p2p.broadcast(&EventPut(event)).await;
  213. }
  214. }
  215. }
  216. }
  217. // If we got nothing, we just pass.
  218. Ok(None) => {}
  219. // If we got an error, we disconnect the client.
  220. Err(e) => {
  221. self.incoming.unsubscribe().await;
  222. return Err(e)
  223. }
  224. }
  225. // Clear the line buffer
  226. line = String::new();
  227. }
  228. // Process message from the network. These should only be PRIVMSG.
  229. //
  230. // N.b. handling "historical messages", i.e. outstanding messages
  231. // which have occured when darkirc is offline are handled in
  232. // <file:./command.rs::async fn get_history(&self, channels: &HashSet<String>) -> Result<Vec<ReplyType>> {>
  233. // for which the logic for delivery should be kept in sync
  234. r = self.incoming.receive().fuse() => {
  235. // We will skip this if it's our own message.
  236. let event_id = r.id();
  237. if *self.last_sent.read().await == event_id {
  238. continue
  239. }
  240. // If this event was seen, skip it
  241. match self.is_seen(&event_id).await {
  242. Ok(true) => continue,
  243. Ok(false) => {},
  244. Err(e) => {
  245. error!("[IRC CLIENT] (multiplex_connection) self.is_seen({event_id}) failed: {e}");
  246. return Err(e)
  247. }
  248. }
  249. // If the Event contains an appended blob of data, try to check if it's
  250. // a RLN Signal proof and verify it.
  251. //if false {
  252. let mut verification_failed = false;
  253. #[allow(clippy::never_loop)]
  254. loop {
  255. let (event, blob) = (r.clone(), vec![0,1,2]);
  256. let (proof, public_inputs): (Proof, Vec<pallas::Base>) = match deserialize_async(&blob).await {
  257. Ok(v) => v,
  258. Err(_) => {
  259. // TODO: FIXME: This logic should be better written.
  260. // Right now we don't enforce RLN so we can just fall-through.
  261. //error!("[IRC CLIENT] Failed deserializing event ephemeral data: {e}");
  262. break
  263. }
  264. };
  265. if public_inputs.len() != 2 {
  266. error!("[IRC CLIENT] Received event has the wrong number of public inputs");
  267. verification_failed = true;
  268. break
  269. }
  270. info!("[IRC CLIENT] Verifying incoming Event RLN proof");
  271. if self.verify_rln_signal_proof(
  272. &event,
  273. proof,
  274. [public_inputs[0], public_inputs[1]],
  275. ).await.is_err() {
  276. verification_failed = true;
  277. break
  278. }
  279. // TODO: Store for secret shares recovery
  280. info!("[IRC CLIENT] RLN verification successful");
  281. break
  282. }
  283. if verification_failed {
  284. error!("[IRC CLIENT] Incoming Event proof verification failed");
  285. continue
  286. }
  287. // Try to deserialize the `Event`'s content into a `Privmsg`
  288. let mut privmsg = match Msg::deserialize(r.content()).await {
  289. Ok(Msg::V1(old_msg)) => old_msg.into_new(),
  290. Ok(Msg::V2(new_msg)) => new_msg,
  291. Err(e) => {
  292. error!("[IRC CLIENT] Failed deserializing incoming Privmsg event: {e}");
  293. continue
  294. }
  295. };
  296. // If successful, potentially decrypt it:
  297. self.server.try_decrypt(&mut privmsg, self.nickname.read().await.as_ref()).await;
  298. // We should skip any attempts to contact services from the network.
  299. if ["nickserv", "chanserv"].contains(&privmsg.nick.to_lowercase().as_str()) {
  300. continue
  301. }
  302. // If the privmsg is not intented for any of the given
  303. // channels or contacts, ignore it
  304. // otherwise add it as a reply and mark it as seen
  305. // in the seen_events tree.
  306. let channels = self.channels.read().await;
  307. let contacts = self.server.contacts.read().await;
  308. if !channels.contains(&privmsg.channel) &&
  309. !contacts.contains_key(&privmsg.channel)
  310. {
  311. continue
  312. }
  313. // Add the nickname to the list of nicks on the channel, if it's a channel.
  314. let mut chans_lock = self.server.channels.write().await;
  315. if let Some(chan) = chans_lock.get_mut(&privmsg.channel) {
  316. chan.nicks.insert(privmsg.nick.clone());
  317. }
  318. drop(chans_lock);
  319. // Handle message lines individually
  320. for line in privmsg.msg.lines() {
  321. // Skip empty lines
  322. if line.is_empty() {
  323. continue
  324. }
  325. // Format the message
  326. let msg = format!("PRIVMSG {} :{line}", privmsg.channel);
  327. // Send it to the client
  328. let reply = ReplyType::Client((privmsg.nick.clone(), msg));
  329. if let Err(e) = self.reply(&mut writer, &reply).await {
  330. error!("[IRC CLIENT] Failed writing PRIVMSG to client: {e}");
  331. continue
  332. }
  333. }
  334. // Mark the message as seen for this USER
  335. if let Err(e) = self.mark_seen(&event_id).await {
  336. error!("[IRC CLIENT] (multiplex_connection) self.mark_seen({event_id}) failed: {e}");
  337. return Err(e)
  338. }
  339. }
  340. }
  341. }
  342. }
  343. /// Send a reply to the IRC client. Matches on the reply type.
  344. async fn reply<W>(&self, writer: &mut W, reply: &ReplyType) -> Result<()>
  345. where
  346. W: AsyncWrite + Unpin,
  347. {
  348. let r = match reply {
  349. ReplyType::Server((rpl, msg)) => format!(":{SERVER_NAME} {rpl:03} {msg}"),
  350. ReplyType::Client((nick, msg)) => format!(":{nick}!~anon@darkirc {msg}"),
  351. ReplyType::Pong(origin) => format!(":{SERVER_NAME} PONG :{origin}"),
  352. ReplyType::Cap(msg) => format!(":{SERVER_NAME} {msg}"),
  353. ReplyType::Notice((src, dst, msg)) => {
  354. format!(":{src}!~anon@darkirc NOTICE {dst} :{msg}")
  355. }
  356. };
  357. debug!("[{}] <-- {r}", self.addr);
  358. writer.write(r.as_bytes()).await?;
  359. writer.write(b"\r\n").await?;
  360. writer.flush().await?;
  361. Ok(())
  362. }
  363. /// Handle the incoming line given sent by the IRC client
  364. async fn process_client_line<W>(
  365. &self,
  366. line: &str,
  367. writer: &mut W,
  368. args_queue: &mut VecDeque<OldPrivmsg>,
  369. ) -> Result<Option<Vec<Event>>>
  370. where
  371. W: AsyncWrite + Unpin,
  372. {
  373. if line.trim().is_empty() {
  374. // Silently ignore empty commands
  375. return Ok(None)
  376. }
  377. let mut line = line.to_string();
  378. // Remove CRLF
  379. if &line[(line.len() - 2)..] == "\r\n" {
  380. line.pop();
  381. line.pop();
  382. } else if &line[(line.len() - 1)..] == "\n" {
  383. line.pop();
  384. } else {
  385. return Err(Error::ParseFailed("Line doesn't end with CR/LF"))
  386. }
  387. // Prefix the message part of PRIVMSG with ':' if is not already.
  388. // Or realname part of USER command.
  389. if let Some(index) = match line.split_whitespace().next() {
  390. Some("PRIVMSG") => Some(2),
  391. Some("USER") => Some(4),
  392. _ => None,
  393. } {
  394. let mut words: Vec<String> =
  395. line.splitn(index + 1, char::is_whitespace).map(|s| s.to_string()).collect();
  396. if words.len() > index && !words[index].starts_with(':') {
  397. words[index] = format!(":{}", words[index]);
  398. }
  399. line = words.join(" ");
  400. }
  401. // Parse the line
  402. let mut tokens = line.split_ascii_whitespace();
  403. // Commands can begin with :garbage, but we will reject clients
  404. // doing that for now to keep the protocol simple and focused.
  405. let cmd = tokens.next().ok_or(Error::ParseFailed("Invalid command line"))?;
  406. let args = line.replacen(cmd, "", 1);
  407. let cmd = cmd.to_uppercase();
  408. debug!("[{}] --> {cmd}{args}", self.addr);
  409. // Handle the command. These implementations are in `command.rs`.
  410. let replies: Vec<ReplyType> = match cmd.as_str() {
  411. "ADMIN" => self.handle_cmd_admin(&args).await?,
  412. "CAP" => self.handle_cmd_cap(&args).await?,
  413. "INFO" => self.handle_cmd_info(&args).await?,
  414. "JOIN" => self.handle_cmd_join(&args, true).await?,
  415. "LIST" => self.handle_cmd_list(&args).await?,
  416. "MODE" => self.handle_cmd_mode(&args).await?,
  417. "MOTD" => self.handle_cmd_motd(&args).await?,
  418. "NAMES" => self.handle_cmd_names(&args).await?,
  419. "NICK" => self.handle_cmd_nick(&args).await?,
  420. "PART" => self.handle_cmd_part(&args).await?,
  421. "PASS" => self.handle_cmd_pass(&args).await?,
  422. "PING" => self.handle_cmd_ping(&args).await?,
  423. "PRIVMSG" => self.handle_cmd_privmsg(&args).await?,
  424. "REHASH" => self.handle_cmd_rehash(&args).await?,
  425. "TOPIC" => self.handle_cmd_topic(&args).await?,
  426. "USER" => self.handle_cmd_user(&args).await?,
  427. "VERSION" => self.handle_cmd_version(&args).await?,
  428. "QUIT" => return Err(Error::ChannelStopped),
  429. _ => {
  430. warn!("[IRC CLIENT] Unimplemented \"{cmd}\" command");
  431. vec![]
  432. }
  433. };
  434. // Depending on the reply type, we send according messages.
  435. for reply in replies.iter() {
  436. self.reply(writer, reply).await?;
  437. }
  438. // If the command was a PRIVMSG the client sent, we need to encrypt it and
  439. // create an Event to broadcast and return it from this function. So let's try.
  440. // We also do not allow sending unencrypted DMs. In that case, we send a notice
  441. // to the client to inform them that the feature is not enabled.
  442. // NOTE: This is not the most performant way to do this, probably not even
  443. // TODO: the best place to do it. Patches welcome. It's also a bit fragile
  444. // since we assume that `handle_cmd_privmsg()` won't return any replies.
  445. if cmd.as_str() == "PRIVMSG" && replies.is_empty() {
  446. // If the DAG is not synced yet, queue client lines
  447. // Once synced, send queued lines and continue as normal
  448. if !*self.server.darkirc.event_graph.synced.read().await {
  449. debug!("DAG is still syncing, queuing and skipping...");
  450. let privmsg = self.args_to_privmsg(args).await;
  451. args_queue.push_back(privmsg);
  452. return Ok(None)
  453. }
  454. // Check if we have queued PRIVMSGs, if we do send all of them first.
  455. let mut pending_events = vec![];
  456. if !args_queue.is_empty() {
  457. for _ in 0..args_queue.len() {
  458. let privmsg = args_queue.pop_front().unwrap();
  459. pending_events.push(self.privmsg_to_event(privmsg).await);
  460. }
  461. return Ok(Some(pending_events))
  462. }
  463. // If queue is empty, create an event and return it
  464. let privmsg = self.args_to_privmsg(args).await;
  465. let event = self.privmsg_to_event(privmsg).await;
  466. return Ok(Some(vec![event]))
  467. }
  468. Ok(None)
  469. }
  470. // Internal helper function that creates a PRIVMSG from IRC client arguments
  471. async fn args_to_privmsg(&self, args: String) -> OldPrivmsg {
  472. let nick = self.nickname.read().await.to_string();
  473. let channel = args.split_ascii_whitespace().next().unwrap().to_string();
  474. let msg_offset = args.find(':').unwrap() + 1;
  475. let (_, msg) = args.split_at(msg_offset);
  476. // Truncate messages longer than MAX_MSG_LEN
  477. let msg = if msg.len() > MAX_MSG_LEN { msg.split_at(MAX_MSG_LEN).0 } else { msg };
  478. OldPrivmsg { channel, nick, msg: msg.to_string() }
  479. }
  480. // Internal helper function that creates an Event from PRIVMSG arguments
  481. async fn privmsg_to_event(&self, mut privmsg: OldPrivmsg) -> Event {
  482. // Encrypt the Privmsg if an encryption method is available.
  483. self.server.try_encrypt(&mut privmsg).await;
  484. // Build a DAG event and return it.
  485. Event::new(serialize_async(&privmsg).await, &self.server.darkirc.event_graph).await
  486. }
  487. /// Atomically mark a message as seen for this client.
  488. pub async fn mark_seen(&self, event_id: &blake3::Hash) -> Result<()> {
  489. let db = self
  490. .seen
  491. .get_or_init(|| async {
  492. let u = self.username.read().await.to_string();
  493. self.server.darkirc.sled.open_tree(format!("darkirc_user_{u}")).unwrap()
  494. })
  495. .await;
  496. debug!("Marking event {event_id} as seen");
  497. let mut batch = sled::Batch::default();
  498. batch.insert(event_id.as_bytes(), &[]);
  499. Ok(db.apply_batch(batch)?)
  500. }
  501. /// Check if a message was already marked seen for this client.
  502. pub async fn is_seen(&self, event_id: &blake3::Hash) -> Result<bool> {
  503. let db = self
  504. .seen
  505. .get_or_init(|| async {
  506. let u = self.username.read().await.to_string();
  507. self.server.darkirc.sled.open_tree(format!("darkirc_user_{u}")).unwrap()
  508. })
  509. .await;
  510. Ok(db.contains_key(event_id.as_bytes())?)
  511. }
  512. /// Abstraction for RLN signal proof creation
  513. async fn create_rln_signal_proof(
  514. &self,
  515. rln_identity: &RlnIdentity,
  516. event: &Event,
  517. ) -> Result<(Proof, Vec<pallas::Base>)> {
  518. let identity_commitment = rln_identity.commitment();
  519. // Fetch the commitment's leaf position in the Merkle tree
  520. let Some(identity_pos) =
  521. self.server.rln_identity_store.get(identity_commitment.to_repr())?
  522. else {
  523. return Err(Error::DatabaseError(
  524. "Identity not found in commitment tree store".to_string(),
  525. ))
  526. };
  527. let identity_pos: Position = deserialize_async(&identity_pos).await?;
  528. // Fetch the latest commitment Merkle tree
  529. let Some(identity_tree) = self.server.server_store.get("rln_identity_tree")? else {
  530. return Err(Error::DatabaseError(
  531. "RLN Identity tree not found in server store".to_string(),
  532. ))
  533. };
  534. let identity_tree: MerkleTree = deserialize_async(&identity_tree).await?;
  535. // Retrieve the ZK proving key from the db
  536. let signal_zkbin = ZkBinary::decode(RLN2_SIGNAL_ZKBIN)?;
  537. let signal_circuit = ZkCircuit::new(empty_witnesses(&signal_zkbin)?, &signal_zkbin);
  538. let Some(proving_key) = self.server.server_store.get("rlnv2-diff-signal-pk")? else {
  539. return Err(Error::DatabaseError(
  540. "RLN signal proving key not found in server store".to_string(),
  541. ))
  542. };
  543. let mut reader = Cursor::new(proving_key);
  544. let proving_key = ProvingKey::read(&mut reader, signal_circuit)?;
  545. rln_identity.create_signal_proof(event, &identity_tree, identity_pos, &proving_key)
  546. }
  547. /// Abstraction for RLN signal proof verification
  548. async fn verify_rln_signal_proof(
  549. &self,
  550. event: &Event,
  551. proof: Proof,
  552. public_inputs: [pallas::Base; 2],
  553. ) -> Result<()> {
  554. let epoch = pallas::Base::from(closest_epoch(event.timestamp));
  555. let external_nullifier = poseidon_hash([epoch, RLN_APP_IDENTIFIER]);
  556. let x = hash_event(event);
  557. let y = public_inputs[0];
  558. let internal_nullifier = public_inputs[1];
  559. // Fetch the latest commitment Merkle tree
  560. let Some(identity_tree) = self.server.server_store.get("rln_identity_tree")? else {
  561. return Err(Error::DatabaseError(
  562. "RLN Identity tree not found in server store".to_string(),
  563. ))
  564. };
  565. let identity_tree: MerkleTree = deserialize_async(&identity_tree).await?;
  566. let identity_root = identity_tree.root(0).unwrap();
  567. let public_inputs =
  568. vec![epoch, external_nullifier, x, y, internal_nullifier, identity_root.inner()];
  569. Ok(proof.verify(&self.server.rln_signal_vk, &public_inputs)?)
  570. }
  571. }