Skip to main content

zebra_chain/orchard/
keys.rs

1//! Orchard key types.
2//!
3//! Unused key types are not implemented, see PR #5476.
4//!
5//! <https://zips.z.cash/protocol/nu5.pdf#orchardkeycomponents>
6
7use std::{fmt, io};
8
9use group::{ff::PrimeField, CurveAffine as _, Group, GroupEncoding};
10use halo2::{
11    arithmetic::{Coordinates, CurveAffine},
12    pasta::pallas,
13};
14use rand_core::{CryptoRng, Rng};
15
16use crate::{
17    error::RandError,
18    serialization::{
19        serde_helpers, ReadZcashExt, SerializationError, ZcashDeserialize, ZcashSerialize,
20    },
21};
22
23/// A _diversifier_, as described in [protocol specification §4.2.3][ps].
24///
25/// [ps]: https://zips.z.cash/protocol/nu5.pdf#orchardkeycomponents
26#[derive(Copy, Clone, Eq, PartialEq)]
27#[cfg_attr(
28    any(test, feature = "proptest-impl"),
29    derive(proptest_derive::Arbitrary)
30)]
31pub struct Diversifier(pub(crate) [u8; 11]);
32
33impl fmt::Debug for Diversifier {
34    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
35        f.debug_tuple("Diversifier")
36            .field(&hex::encode(self.0))
37            .finish()
38    }
39}
40
41impl From<[u8; 11]> for Diversifier {
42    fn from(bytes: [u8; 11]) -> Self {
43        Self(bytes)
44    }
45}
46
47impl From<Diversifier> for [u8; 11] {
48    fn from(d: Diversifier) -> [u8; 11] {
49        d.0
50    }
51}
52
53impl PartialEq<[u8; 11]> for Diversifier {
54    fn eq(&self, other: &[u8; 11]) -> bool {
55        self.0 == *other
56    }
57}
58
59impl Diversifier {
60    /// Generate a new `Diversifier`.
61    ///
62    /// <https://zips.z.cash/protocol/nu5.pdf#orchardkeycomponents>
63    pub fn new<T>(csprng: &mut T) -> Result<Self, RandError>
64    where
65        T: Rng + CryptoRng,
66    {
67        let mut bytes = [0u8; 11];
68        csprng
69            .try_fill_bytes(&mut bytes)
70            .map_err(|_| RandError::FillBytes)?;
71
72        Ok(Self::from(bytes))
73    }
74}
75
76/// A (diversified) transmission Key
77///
78/// In Orchard, secrets need to be transmitted to a recipient of funds in order
79/// for them to be later spent. To transmit these secrets securely to a
80/// recipient without requiring an out-of-band communication channel, the
81/// transmission key is used to encrypt them.
82///
83/// Derived by multiplying a Pallas point [derived][concretediversifyhash] from
84/// a `Diversifier` by the `IncomingViewingKey` scalar.
85///
86/// [concretediversifyhash]: https://zips.z.cash/protocol/nu5.pdf#concretediversifyhash
87/// <https://zips.z.cash/protocol/nu5.pdf#orchardkeycomponents>
88#[derive(Copy, Clone, PartialEq)]
89pub struct TransmissionKey(pub(crate) pallas::Affine);
90
91impl fmt::Debug for TransmissionKey {
92    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
93        let mut d = f.debug_struct("TransmissionKey");
94
95        let option: Option<Coordinates<pallas::Affine>> = self.0.coordinates().into();
96
97        match option {
98            Some(coordinates) => d
99                .field("x", &hex::encode(coordinates.x().to_repr()))
100                .field("y", &hex::encode(coordinates.y().to_repr()))
101                .finish(),
102            None => d
103                .field("x", &hex::encode(pallas::Base::zero().to_repr()))
104                .field("y", &hex::encode(pallas::Base::zero().to_repr()))
105                .finish(),
106        }
107    }
108}
109
110impl Eq for TransmissionKey {}
111
112impl From<TransmissionKey> for [u8; 32] {
113    fn from(pk_d: TransmissionKey) -> [u8; 32] {
114        pk_d.0.to_bytes()
115    }
116}
117
118impl PartialEq<[u8; 32]> for TransmissionKey {
119    fn eq(&self, other: &[u8; 32]) -> bool {
120        &self.0.to_bytes() == other
121    }
122}
123
124/// An ephemeral public key for Orchard key agreement.
125///
126/// <https://zips.z.cash/protocol/nu5.pdf#concreteorchardkeyagreement>
127/// <https://zips.z.cash/protocol/nu5.pdf#saplingandorchardencrypt>
128#[derive(Copy, Clone, Deserialize, PartialEq, Eq, Serialize)]
129pub struct EphemeralPublicKey(#[serde(with = "serde_helpers::Affine")] pub(crate) pallas::Affine);
130
131impl fmt::Debug for EphemeralPublicKey {
132    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
133        let mut d = f.debug_struct("EphemeralPublicKey");
134
135        let option: Option<Coordinates<pallas::Affine>> = self.0.coordinates().into();
136
137        match option {
138            Some(coordinates) => d
139                .field("x", &hex::encode(coordinates.x().to_repr()))
140                .field("y", &hex::encode(coordinates.y().to_repr()))
141                .finish(),
142            None => d
143                .field("x", &hex::encode(pallas::Base::zero().to_repr()))
144                .field("y", &hex::encode(pallas::Base::zero().to_repr()))
145                .finish(),
146        }
147    }
148}
149
150impl From<EphemeralPublicKey> for [u8; 32] {
151    fn from(epk: EphemeralPublicKey) -> [u8; 32] {
152        epk.0.to_bytes()
153    }
154}
155
156impl From<&EphemeralPublicKey> for [u8; 32] {
157    fn from(epk: &EphemeralPublicKey) -> [u8; 32] {
158        epk.0.to_bytes()
159    }
160}
161
162impl PartialEq<[u8; 32]> for EphemeralPublicKey {
163    fn eq(&self, other: &[u8; 32]) -> bool {
164        &self.0.to_bytes() == other
165    }
166}
167
168impl TryFrom<[u8; 32]> for EphemeralPublicKey {
169    type Error = &'static str;
170
171    /// Convert an array into a [`EphemeralPublicKey`].
172    ///
173    /// Returns an error if the encoding is malformed or if [it encodes the
174    /// identity point][1].
175    ///
176    /// > epk cannot be 𝒪_P
177    ///
178    /// Note that this is [intrinsic to the EphemeralPublicKey][2] type and it is not
179    /// a separate consensus rule:
180    ///
181    /// > Define KA^{Orchard}.Public := P^*.
182    ///
183    /// [1]: https://zips.z.cash/protocol/protocol.pdf#actiondesc
184    /// [2]: https://zips.z.cash/protocol/protocol.pdf#concreteorchardkeyagreement
185    fn try_from(bytes: [u8; 32]) -> Result<Self, Self::Error> {
186        let possible_point = pallas::Affine::from_bytes(&bytes);
187
188        if possible_point.is_some().into() {
189            let point = possible_point.unwrap();
190            if point.to_curve().is_identity().into() {
191                Err("pallas::Affine value for Orchard EphemeralPublicKey is the identity")
192            } else {
193                Ok(Self(possible_point.unwrap()))
194            }
195        } else {
196            Err("Invalid pallas::Affine value for Orchard EphemeralPublicKey")
197        }
198    }
199}
200
201impl ZcashSerialize for EphemeralPublicKey {
202    fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
203        writer.write_all(&<[u8; 32]>::from(self)[..])?;
204        Ok(())
205    }
206}
207
208impl ZcashDeserialize for EphemeralPublicKey {
209    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
210        Self::try_from(reader.read_32_bytes()?).map_err(SerializationError::Parse)
211    }
212}