phoenix_core/
stealth_address.rs1use dusk_bytes::{DeserializableSlice, Error, Serializable};
8use dusk_jubjub::{JubJubAffine, JubJubExtended};
9use jubjub_schnorr::PublicKey as NotePublicKey;
10#[cfg(feature = "rkyv-impl")]
11use rkyv::{Archive, Deserialize, Serialize};
12use subtle::{Choice, ConstantTimeEq};
13
14#[derive(Default, Debug, Clone, Copy, Eq)]
19#[cfg_attr(
20 feature = "rkyv-impl",
21 derive(Archive, Serialize, Deserialize),
22 archive_attr(derive(bytecheck::CheckBytes))
23)]
24pub struct StealthAddress {
25 pub(crate) R: JubJubExtended,
26 pub(crate) note_pk: NotePublicKey,
27}
28
29impl StealthAddress {
30 pub const fn from_raw_unchecked(
40 R: JubJubExtended,
41 note_pk: NotePublicKey,
42 ) -> Self {
43 Self { R, note_pk }
44 }
45
46 pub const fn R(&self) -> &JubJubExtended {
48 &self.R
49 }
50
51 pub const fn note_pk(&self) -> &NotePublicKey {
53 &self.note_pk
54 }
55
56 pub fn from_bytes_legacy_compat(
59 bytes: &[u8; Self::SIZE],
60 ) -> Result<Self, Error> {
61 let r_affine = affine_from_slice_legacy_compat(&bytes[..32])?;
62 let note_pk_affine = affine_from_slice_legacy_compat(&bytes[32..])?;
63
64 Ok(Self {
65 R: JubJubExtended::from(r_affine),
66 note_pk: NotePublicKey::from_raw_unchecked(JubJubExtended::from(
67 note_pk_affine,
68 )),
69 })
70 }
71}
72
73impl ConstantTimeEq for StealthAddress {
74 fn ct_eq(&self, other: &Self) -> Choice {
75 self.note_pk().as_ref().ct_eq(other.note_pk().as_ref())
76 & self.R.ct_eq(&other.R)
77 }
78}
79
80impl PartialEq for StealthAddress {
81 fn eq(&self, other: &Self) -> bool {
82 self.ct_eq(other).into()
83 }
84}
85
86impl Serializable<64> for StealthAddress {
87 type Error = Error;
88 fn to_bytes(&self) -> [u8; Self::SIZE] {
90 let mut bytes = [0u8; Self::SIZE];
91 bytes[..32].copy_from_slice(&JubJubAffine::from(self.R).to_bytes());
92 bytes[32..].copy_from_slice(
93 &JubJubAffine::from(self.note_pk().as_ref()).to_bytes(),
94 );
95 bytes
96 }
97
98 fn from_bytes(bytes: &[u8; Self::SIZE]) -> Result<Self, Error> {
100 let R = JubJubExtended::from(JubJubAffine::from_slice(&bytes[..32])?);
101 let note_pk =
102 JubJubExtended::from(JubJubAffine::from_slice(&bytes[32..])?);
103 let note_pk = NotePublicKey::from_raw_unchecked(note_pk);
104
105 Ok(StealthAddress { R, note_pk })
106 }
107}
108
109pub(crate) fn affine_from_slice_legacy_compat(
110 bytes: &[u8],
111) -> Result<JubJubAffine, Error> {
112 let mut point = [0u8; JubJubAffine::SIZE];
113 point.copy_from_slice(bytes);
114 Option::<JubJubAffine>::from(JubJubAffine::from_bytes(point))
115 .ok_or(Error::InvalidData)
116}