use crate::{StealthAddress, keys::hash};
use dusk_jubjub::{GENERATOR_EXTENDED, JubJubScalar};
use ff::Field;
use jubjub_schnorr::SecretKey as NoteSecretKey;
use zeroize::Zeroize;
#[cfg(feature = "rkyv-impl")]
use rkyv::{Archive, Deserialize, Serialize};
use dusk_bytes::{DeserializableSlice, Error, Serializable};
use rand::{CryptoRng, RngCore};
use subtle::{Choice, ConstantTimeEq};
#[derive(Clone, Eq, Debug, Zeroize)]
#[cfg_attr(
feature = "rkyv-impl",
derive(Archive, Serialize, Deserialize),
archive_attr(derive(bytecheck::CheckBytes))
)]
pub struct SecretKey {
a: JubJubScalar,
b: JubJubScalar,
}
impl SecretKey {
pub fn new(a: JubJubScalar, b: JubJubScalar) -> Self {
Self { a, b }
}
pub fn a(&self) -> &JubJubScalar {
&self.a
}
pub fn b(&self) -> &JubJubScalar {
&self.b
}
pub fn random<R: RngCore + CryptoRng>(rng: &mut R) -> Self {
let a = JubJubScalar::random(&mut *rng);
let b = JubJubScalar::random(&mut *rng);
SecretKey::new(a, b)
}
pub fn gen_note_sk(&self, stealth: &StealthAddress) -> NoteSecretKey {
let aR = stealth.R() * self.a;
NoteSecretKey::from(hash(&aR) + self.b)
}
pub fn owns(&self, stealth_address: &StealthAddress) -> bool {
let note_sk = self.gen_note_sk(stealth_address);
let note_pk = GENERATOR_EXTENDED * note_sk.as_ref();
stealth_address.note_pk().as_ref() == ¬e_pk
}
}
impl ConstantTimeEq for SecretKey {
fn ct_eq(&self, other: &Self) -> Choice {
self.a.ct_eq(&other.a) & self.b.ct_eq(&other.b)
}
}
impl PartialEq for SecretKey {
fn eq(&self, other: &Self) -> bool {
self.ct_eq(other).into()
}
}
impl Serializable<64> for SecretKey {
type Error = Error;
fn to_bytes(&self) -> [u8; 64] {
let mut bytes = [0u8; 64];
bytes[..32].copy_from_slice(&self.a.to_bytes());
bytes[32..].copy_from_slice(&self.b.to_bytes());
bytes
}
fn from_bytes(buf: &[u8; 64]) -> Result<Self, Self::Error> {
let a = JubJubScalar::from_slice(&buf[..32])?;
let b = JubJubScalar::from_slice(&buf[32..])?;
Ok(Self { a, b })
}
}