/ console / program / src / data / record / encrypt.rs
encrypt.rs
  1  // Copyright (c) 2019-2025 Alpha-Delta Network Inc.
  2  // This file is part of the alphavm library.
  3  
  4  // Licensed under the Apache License, Version 2.0 (the "License");
  5  // you may not use this file except in compliance with the License.
  6  // You may obtain a copy of the License at:
  7  
  8  // http://www.apache.org/licenses/LICENSE-2.0
  9  
 10  // Unless required by applicable law or agreed to in writing, software
 11  // distributed under the License is distributed on an "AS IS" BASIS,
 12  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  // See the License for the specific language governing permissions and
 14  // limitations under the License.
 15  
 16  use super::*;
 17  
 18  impl<N: Network> Record<N, Plaintext<N>> {
 19      /// Encrypts `self` for the record owner under the given randomizer.
 20      pub fn encrypt(&self, randomizer: Scalar<N>) -> Result<Record<N, Ciphertext<N>>> {
 21          // Output the encrypted record.
 22          self.encrypt_symmetric(randomizer).map(|(encrypted_record, _)| encrypted_record)
 23      }
 24  
 25      /// Encrypts `self` for the record owner under the given randomizer,
 26      /// and returns the encrypted record alongside the record view key.
 27      #[allow(clippy::type_complexity)]
 28      pub fn encrypt_symmetric(&self, randomizer: Scalar<N>) -> Result<(Record<N, Ciphertext<N>>, Field<N>)> {
 29          // Ensure the randomizer corresponds to the record nonce.
 30          if self.nonce == N::g_scalar_multiply(&randomizer) {
 31              // Compute the record view key.
 32              let record_view_key = (**self.owner * randomizer).to_x_coordinate();
 33              // Encrypt the record.
 34              let encrypted_record = self.encrypt_symmetric_unchecked(&record_view_key)?;
 35              // Return the encrypted record and the record view key.
 36              Ok((encrypted_record, record_view_key))
 37          } else {
 38              bail!("Illegal operation: Record::encrypt() randomizer does not correspond to the record nonce.")
 39          }
 40      }
 41  
 42      /// Encrypts `self` under the given record view key.
 43      /// Note: This method does not check that the record view key corresponds to the record owner.
 44      /// Use `Self::encrypt` for the checked variant.
 45      pub fn encrypt_symmetric_unchecked(&self, record_view_key: &Field<N>) -> Result<Record<N, Ciphertext<N>>> {
 46          // Determine the number of randomizers needed to encrypt the record.
 47          let num_randomizers = self.num_randomizers()?;
 48          // Prepare a randomizer for each field element.
 49          let randomizers = N::hash_many_psd8(&[N::encryption_domain(), *record_view_key], num_randomizers);
 50          // Encrypt the record.
 51          self.encrypt_with_randomizers(&randomizers)
 52      }
 53  
 54      /// Encrypts `self` under the given randomizers.
 55      fn encrypt_with_randomizers(&self, randomizers: &[Field<N>]) -> Result<Record<N, Ciphertext<N>>> {
 56          // Initialize an index to keep track of the randomizer index.
 57          let mut index: usize = 0;
 58  
 59          // Encrypt the owner.
 60          let owner = match self.owner.is_public() {
 61              true => self.owner.encrypt_with_randomizer(&[])?,
 62              false => self.owner.encrypt_with_randomizer(&[randomizers[index]])?,
 63          };
 64  
 65          // Increment the index if the owner is private.
 66          if owner.is_private() {
 67              index += 1;
 68          }
 69  
 70          // Encrypt the data.
 71          let mut encrypted_data = IndexMap::with_capacity(self.data.len());
 72          for (id, entry, num_randomizers) in self.data.iter().map(|(id, entry)| (id, entry, entry.num_randomizers())) {
 73              // Retrieve the result for `num_randomizers`.
 74              let num_randomizers = num_randomizers? as usize;
 75              // Retrieve the randomizers for this entry.
 76              let randomizers = &randomizers[index..index + num_randomizers];
 77              // Encrypt the entry.
 78              let entry = match entry {
 79                  // Constant entries do not need to be encrypted.
 80                  Entry::Constant(plaintext) => Entry::Constant(plaintext.clone()),
 81                  // Public entries do not need to be encrypted.
 82                  Entry::Public(plaintext) => Entry::Public(plaintext.clone()),
 83                  // Private entries are encrypted with the given randomizers.
 84                  Entry::Private(private) => Entry::Private(Ciphertext::try_from(
 85                      private
 86                          .to_fields()?
 87                          .iter()
 88                          .zip_eq(randomizers)
 89                          .map(|(plaintext, randomizer)| *plaintext + randomizer)
 90                          .collect::<Vec<_>>(),
 91                  )?),
 92              };
 93              // Insert the encrypted entry.
 94              if encrypted_data.insert(*id, entry).is_some() {
 95                  bail!("Duplicate identifier in record: {id}");
 96              }
 97              // Increment the index.
 98              index += num_randomizers;
 99          }
100  
101          // Return the encrypted record.
102          Self::from_ciphertext(owner, encrypted_data, self.nonce, self.version)
103      }
104  }