diff --git a/src/api.rs b/src/api.rs index 886a13c..a3b65e1 100644 --- a/src/api.rs +++ b/src/api.rs @@ -850,8 +850,9 @@ fn send_data(prd: &Prd, shared_secret: &AnkSharedSecretHash) -> AnyhowResult> ) -> anyhow::Result, AnkSharedSecretHash)>> { - let mut messages = lock_messages()?; + debug!("cached messages: {:#?}", messages); let nonce = Nonce::from_slice(&cipher[..12]); @@ -904,11 +905,7 @@ fn decrypt_with_cached_messages( Ok(None) } -fn decrypt_with_known_processes(cipher: &[u8]) -> anyhow::Result, OutPoint)>> { - let processes = lock_processes()?; - - debug!("Known processes: {:#?}", processes); - +fn decrypt_with_known_processes(cipher: &[u8], processes: MutexGuard>) -> anyhow::Result, OutPoint)>> { let nonce = Nonce::from_slice(&cipher[..12]); for (outpoint, process) in processes.iter() { @@ -1092,6 +1089,10 @@ fn handle_decrypted_message( #[wasm_bindgen] pub fn parse_cipher(cipher_msg: String) -> ApiResult { + // We lock message cache and processes to prevent race conditions + let mut messages = lock_messages()?; + let processes = lock_processes()?; + // Check that the cipher is not empty or too long if cipher_msg.is_empty() || cipher_msg.len() > MAX_PRD_PAYLOAD_SIZE { return Err(ApiError::new( @@ -1102,13 +1103,13 @@ pub fn parse_cipher(cipher_msg: String) -> ApiResult { let cipher = Vec::from_hex(cipher_msg.trim_matches('"'))?; // Try decrypting with cached messages first - if let Ok(Some((plain, shared_secret))) = decrypt_with_cached_messages(&cipher) { + if let Ok(Some((plain, shared_secret))) = decrypt_with_cached_messages(&cipher, &mut messages) { return handle_decrypted_message(plain, Some(shared_secret), None) .map_err(|e| ApiError::new(format!("Failed to handle decrypted message: {}", e))); } // If that fails, try decrypting with known processes - if let Ok(Some((plain, root_commitment))) = decrypt_with_known_processes(&cipher) { + if let Ok(Some((plain, root_commitment))) = decrypt_with_known_processes(&cipher, processes) { return handle_decrypted_message(plain, None, Some(root_commitment)) .map_err(|e| ApiError::new(format!("Failed to handle decrypted message: {}", e))); } @@ -1118,8 +1119,7 @@ pub fn parse_cipher(cipher_msg: String) -> ApiResult { return_msg.cipher = vec![cipher_msg]; return_msg.status = CachedMessageStatus::CipherWaitingTx; - let mut messages_cache = lock_messages()?; - messages_cache.push(return_msg.clone()); + messages.push(return_msg.clone()); Ok(ApiReturn { updated_cached_msg: vec![return_msg],