use super::*;
impl<N: Network> Record<N, Plaintext<N>> {
pub fn encrypt(&self, randomizer: Scalar<N>) -> Result<Record<N, Ciphertext<N>>> {
if self.nonce == N::g_scalar_multiply(&randomizer) {
let record_view_key = (**self.owner * randomizer).to_x_coordinate();
self.encrypt_symmetric_unchecked(&record_view_key)
} else {
bail!("Illegal operation: Record::encrypt() randomizer does not correspond to the record nonce.")
}
}
pub fn encrypt_symmetric_unchecked(&self, record_view_key: &Field<N>) -> Result<Record<N, Ciphertext<N>>> {
let num_randomizers = self.num_randomizers()?;
let randomizers = N::hash_many_psd8(&[N::encryption_domain(), *record_view_key], num_randomizers);
self.encrypt_with_randomizers(&randomizers)
}
fn encrypt_with_randomizers(&self, randomizers: &[Field<N>]) -> Result<Record<N, Ciphertext<N>>> {
let mut index: usize = 0;
let owner = match self.owner.is_public() {
true => self.owner.encrypt_with_randomizer(&[])?,
false => self.owner.encrypt_with_randomizer(&[randomizers[index]])?,
};
if owner.is_private() {
index += 1;
}
let mut encrypted_data = IndexMap::with_capacity(self.data.len());
for (id, entry, num_randomizers) in self.data.iter().map(|(id, entry)| (id, entry, entry.num_randomizers())) {
let num_randomizers = num_randomizers? as usize;
let randomizers = &randomizers[index..index + num_randomizers];
let entry = match entry {
Entry::Constant(plaintext) => Entry::Constant(plaintext.clone()),
Entry::Public(plaintext) => Entry::Public(plaintext.clone()),
Entry::Private(private) => Entry::Private(Ciphertext::try_from(
private
.to_fields()?
.iter()
.zip_eq(randomizers)
.map(|(plaintext, randomizer)| *plaintext + randomizer)
.collect::<Vec<_>>(),
)?),
};
if encrypted_data.insert(*id, entry).is_some() {
bail!("Duplicate identifier in record: {}", id);
}
index += num_randomizers;
}
Self::from_ciphertext(owner, encrypted_data, self.nonce)
}
}