note.rs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. use chacha20poly1305::{AeadInPlace, ChaCha20Poly1305, KeyInit};
  2. use rand::rngs::OsRng;
  3. use darkfi::{
  4. crypto::{
  5. diffie_hellman::{kdf_sapling, sapling_ka_agree},
  6. keypair::{PublicKey, SecretKey},
  7. },
  8. Error, Result,
  9. };
  10. use darkfi_serial::{Decodable, Encodable, SerialDecodable, SerialEncodable};
  11. pub const AEAD_TAG_SIZE: usize = 16;
  12. pub fn encrypt<T: Encodable>(note: &T, public: &PublicKey) -> Result<EncryptedNote2> {
  13. let ephem_secret = SecretKey::random(&mut OsRng);
  14. let ephem_public = PublicKey::from_secret(ephem_secret);
  15. let shared_secret = sapling_ka_agree(&ephem_secret, public);
  16. let key = kdf_sapling(&shared_secret, &ephem_public);
  17. let mut input = Vec::new();
  18. note.encode(&mut input)?;
  19. let input_len = input.len();
  20. let mut ciphertext = vec![0_u8; input_len + AEAD_TAG_SIZE];
  21. ciphertext[..input_len].copy_from_slice(&input);
  22. ChaCha20Poly1305::new(key.as_ref().into())
  23. .encrypt_in_place([0u8; 12][..].into(), &[], &mut ciphertext)
  24. .unwrap();
  25. Ok(EncryptedNote2 { ciphertext, ephem_public })
  26. }
  27. #[derive(Debug, Clone, PartialEq, Eq, SerialEncodable, SerialDecodable)]
  28. pub struct EncryptedNote2 {
  29. ciphertext: Vec<u8>,
  30. ephem_public: PublicKey,
  31. }
  32. impl EncryptedNote2 {
  33. pub fn decrypt<T: Decodable>(&self, secret: &SecretKey) -> Result<T> {
  34. let shared_secret = sapling_ka_agree(secret, &self.ephem_public);
  35. let key = kdf_sapling(&shared_secret, &self.ephem_public);
  36. let ciphertext_len = self.ciphertext.len();
  37. let mut plaintext = vec![0_u8; ciphertext_len];
  38. plaintext.copy_from_slice(&self.ciphertext);
  39. match ChaCha20Poly1305::new(key.as_ref().into()).decrypt_in_place(
  40. [0u8; 12][..].into(),
  41. &[],
  42. &mut plaintext,
  43. ) {
  44. Ok(()) => {
  45. Ok(T::decode(&plaintext[..ciphertext_len - AEAD_TAG_SIZE]).map_err(Error::from)?)
  46. }
  47. Err(e) => Err(Error::NoteDecryptionFailed(e.to_string())),
  48. }
  49. }
  50. }
  51. #[cfg(test)]
  52. mod tests {
  53. use super::*;
  54. use darkfi::crypto::{
  55. keypair::Keypair,
  56. types::{DrkCoinBlind, DrkSerial, DrkTokenId, DrkValueBlind},
  57. };
  58. use group::ff::Field;
  59. #[test]
  60. fn test_note_encdec() {
  61. #[derive(SerialEncodable, SerialDecodable)]
  62. struct MyNote {
  63. serial: DrkSerial,
  64. value: u64,
  65. token_id: DrkTokenId,
  66. coin_blind: DrkCoinBlind,
  67. value_blind: DrkValueBlind,
  68. token_blind: DrkValueBlind,
  69. memo: Vec<u8>,
  70. }
  71. let note = MyNote {
  72. serial: DrkSerial::random(&mut OsRng),
  73. value: 110,
  74. token_id: DrkTokenId::random(&mut OsRng),
  75. coin_blind: DrkCoinBlind::random(&mut OsRng),
  76. value_blind: DrkValueBlind::random(&mut OsRng),
  77. token_blind: DrkValueBlind::random(&mut OsRng),
  78. memo: vec![32, 223, 231, 3, 1, 1],
  79. };
  80. let keypair = Keypair::random(&mut OsRng);
  81. let encrypted_note = encrypt(&note, &keypair.public).unwrap();
  82. let note2: MyNote = encrypted_note.decrypt(&keypair.secret).unwrap();
  83. assert_eq!(note.value, note2.value);
  84. assert_eq!(note.token_id, note2.token_id);
  85. assert_eq!(note.token_blind, note2.token_blind);
  86. assert_eq!(note.memo, note2.memo);
  87. }
  88. }