snarkvm_console_program/data/record/encrypt.rs
1// Copyright 2024 Aleo Network Foundation
2// This file is part of the snarkVM 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
16use super::*;
17
18impl<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 // Ensure the randomizer corresponds to the record nonce.
22 if self.nonce == N::g_scalar_multiply(&randomizer) {
23 // Compute the record view key.
24 let record_view_key = (**self.owner * randomizer).to_x_coordinate();
25 // Encrypt the record.
26 self.encrypt_symmetric_unchecked(&record_view_key)
27 } else {
28 bail!("Illegal operation: Record::encrypt() randomizer does not correspond to the record nonce.")
29 }
30 }
31
32 /// Encrypts `self` under the given record view key.
33 /// Note: This method does not check that the record view key corresponds to the record owner.
34 /// Use `Self::encrypt` for the checked variant.
35 pub fn encrypt_symmetric_unchecked(&self, record_view_key: &Field<N>) -> Result<Record<N, Ciphertext<N>>> {
36 // Determine the number of randomizers needed to encrypt the record.
37 let num_randomizers = self.num_randomizers()?;
38 // Prepare a randomizer for each field element.
39 let randomizers = N::hash_many_psd8(&[N::encryption_domain(), *record_view_key], num_randomizers);
40 // Encrypt the record.
41 self.encrypt_with_randomizers(&randomizers)
42 }
43
44 /// Encrypts `self` under the given randomizers.
45 fn encrypt_with_randomizers(&self, randomizers: &[Field<N>]) -> Result<Record<N, Ciphertext<N>>> {
46 // Initialize an index to keep track of the randomizer index.
47 let mut index: usize = 0;
48
49 // Encrypt the owner.
50 let owner = match self.owner.is_public() {
51 true => self.owner.encrypt_with_randomizer(&[])?,
52 false => self.owner.encrypt_with_randomizer(&[randomizers[index]])?,
53 };
54
55 // Increment the index if the owner is private.
56 if owner.is_private() {
57 index += 1;
58 }
59
60 // Encrypt the data.
61 let mut encrypted_data = IndexMap::with_capacity(self.data.len());
62 for (id, entry, num_randomizers) in self.data.iter().map(|(id, entry)| (id, entry, entry.num_randomizers())) {
63 // Retrieve the result for `num_randomizers`.
64 let num_randomizers = num_randomizers? as usize;
65 // Retrieve the randomizers for this entry.
66 let randomizers = &randomizers[index..index + num_randomizers];
67 // Encrypt the entry.
68 let entry = match entry {
69 // Constant entries do not need to be encrypted.
70 Entry::Constant(plaintext) => Entry::Constant(plaintext.clone()),
71 // Public entries do not need to be encrypted.
72 Entry::Public(plaintext) => Entry::Public(plaintext.clone()),
73 // Private entries are encrypted with the given randomizers.
74 Entry::Private(private) => Entry::Private(Ciphertext::try_from(
75 private
76 .to_fields()?
77 .iter()
78 .zip_eq(randomizers)
79 .map(|(plaintext, randomizer)| *plaintext + randomizer)
80 .collect::<Vec<_>>(),
81 )?),
82 };
83 // Insert the encrypted entry.
84 if encrypted_data.insert(*id, entry).is_some() {
85 bail!("Duplicate identifier in record: {}", id);
86 }
87 // Increment the index.
88 index += num_randomizers;
89 }
90
91 // Return the encrypted record.
92 Self::from_ciphertext(owner, encrypted_data, self.nonce)
93 }
94}