penumbra_sdk_dex/swap/
ciphertext.rs

1use anyhow::Result;
2
3use penumbra_sdk_keys::{keys::OutgoingViewingKey, PayloadKey};
4use penumbra_sdk_shielded_pool::note;
5
6use super::{SwapPlaintext, SWAP_CIPHERTEXT_BYTES, SWAP_LEN_BYTES};
7
8#[derive(Debug, Clone)]
9pub struct SwapCiphertext(pub [u8; SWAP_CIPHERTEXT_BYTES]);
10
11impl SwapCiphertext {
12    pub fn decrypt(
13        &self,
14        ovk: &OutgoingViewingKey,
15        commitment: note::StateCommitment,
16    ) -> Result<SwapPlaintext> {
17        let payload_key = PayloadKey::derive_swap(ovk, commitment);
18        self.decrypt_with_payload_key(&payload_key)
19    }
20
21    pub fn decrypt_with_payload_key(&self, payload_key: &PayloadKey) -> Result<SwapPlaintext> {
22        let swap_ciphertext = self.0;
23        let decryption_result = payload_key
24            .decrypt_swap(swap_ciphertext.to_vec())
25            .map_err(|_| anyhow::anyhow!("unable to decrypt swap ciphertext"))?;
26
27        // TODO: encapsulate plaintext encoding by making this a
28        // pub(super) parse_decryption method on SwapPlaintext
29        // and removing the TryFrom impls
30        let plaintext: [u8; SWAP_LEN_BYTES] = decryption_result
31            .try_into()
32            .map_err(|_| anyhow::anyhow!("swap decryption result did not fit in plaintext len"))?;
33
34        plaintext.try_into().map_err(|_| {
35            anyhow::anyhow!("unable to convert swap plaintext bytes into SwapPlaintext")
36        })
37    }
38}
39
40impl TryFrom<[u8; SWAP_CIPHERTEXT_BYTES]> for SwapCiphertext {
41    type Error = anyhow::Error;
42
43    fn try_from(bytes: [u8; SWAP_CIPHERTEXT_BYTES]) -> Result<SwapCiphertext, Self::Error> {
44        Ok(SwapCiphertext(bytes))
45    }
46}
47
48impl TryFrom<&[u8]> for SwapCiphertext {
49    type Error = anyhow::Error;
50
51    fn try_from(slice: &[u8]) -> Result<SwapCiphertext, Self::Error> {
52        Ok(SwapCiphertext(slice[..].try_into()?))
53    }
54}