Skip to main content

elements/confidential/
nonce.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Confiential Nonces
4
5use core::fmt;
6use std::io;
7
8use secp256k1_zkp::rand::{CryptoRng, RngCore};
9use secp256k1_zkp::{self, PublicKey, Secp256k1, SecretKey, Signing};
10#[cfg(feature = "serde")]
11use serde::{Deserialize, Deserializer, Serialize, Serializer};
12
13use super::CommitmentEncoder;
14use crate::encode::{self, Decodable, Encodable};
15use crate::encoding;
16use crate::hashes::sha256d;
17
18type ExplicitInner = [u8; 32];
19type ConfInner = PublicKey;
20
21const EXPLICIT_LEN: usize = 32;
22const CONFIDENTIAL_LEN: usize = 33;
23const CONFIDENTIAL_LEN_LESS_PREFIX: usize = CONFIDENTIAL_LEN - 1;
24const CONF_PREFIX_1: u8 = 0x02;
25const CONF_PREFIX_2: u8 = 0x03;
26
27/// A CT commitment to an output nonce (i.e. a public key)
28#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
29pub enum Nonce {
30    /// No value
31    #[default]
32    Null,
33    /// There should be no such thing as an "explicit nonce", but Elements will deserialize
34    /// such a thing (and insists that its size be 32 bytes). So we stick a 32-byte type here
35    /// that implements all the traits we need.
36    Explicit(ExplicitInner),
37    /// Nonce is committed
38    Confidential(ConfInner),
39}
40
41impl Nonce {
42    /// Create nonce commitment.
43    pub fn new_confidential<R: RngCore + CryptoRng, C: Signing>(
44        rng: &mut R,
45        secp: &Secp256k1<C>,
46        receiver_blinding_pk: &ConfInner,
47    ) -> (Self, SecretKey) {
48        let ephemeral_sk = SecretKey::new(rng);
49        Self::with_ephemeral_sk(secp, ephemeral_sk, receiver_blinding_pk)
50    }
51
52    /// Similar to [`Self::new_confidential`], but with a given `ephemeral_sk`
53    /// instead of sampling it from rng.
54    pub fn with_ephemeral_sk<C: Signing>(
55        secp: &Secp256k1<C>,
56        ephemeral_sk: SecretKey,
57        receiver_blinding_pk: &ConfInner,
58    ) -> (Self, SecretKey) {
59        let sender_pk = ConfInner::from_secret_key(secp, &ephemeral_sk);
60        let shared_secret = Self::make_shared_secret(receiver_blinding_pk, &ephemeral_sk);
61        (Self::Confidential(sender_pk), shared_secret)
62    }
63
64    /// Calculate the shared secret.
65    pub fn shared_secret(&self, receiver_blinding_sk: &SecretKey) -> Option<SecretKey> {
66        match self {
67            Self::Confidential(sender_pk) =>
68                Some(Self::make_shared_secret(sender_pk, receiver_blinding_sk)),
69            _ => None,
70        }
71    }
72
73    /// Create the shared secret.
74    fn make_shared_secret(pk: &ConfInner, sk: &SecretKey) -> SecretKey {
75        let xy = secp256k1_zkp::ecdh::shared_secret_point(pk, sk);
76        let shared_secret = {
77            // Yes, what follows is the compressed representation of a Bitcoin public key.
78            // However, this is more by accident then by design, see here: https://github.com/rust-bitcoin/rust-secp256k1/pull/255#issuecomment-744146282
79
80            let mut dh_secret = [0u8; CONFIDENTIAL_LEN];
81            dh_secret[0] = if xy.last().unwrap() % 2 == 0 { CONF_PREFIX_1 } else { CONF_PREFIX_2 };
82            dh_secret[1..].copy_from_slice(&xy[0..32]);
83
84            sha256d::Hash::hash(&dh_secret).to_byte_array()
85        };
86
87        SecretKey::from_slice(&shared_secret[..32]).expect("always has exactly 32 bytes")
88    }
89
90    /// Serialized length, in bytes
91    pub fn encoded_length(&self) -> usize {
92        match *self {
93            Self::Null => 1,
94            Self::Explicit(..) => 1 + EXPLICIT_LEN,
95            Self::Confidential(..) => CONFIDENTIAL_LEN,
96        }
97    }
98
99    /// Create from commitment.
100    pub fn from_commitment(bytes: &[u8]) -> Result<Self, encode::Error> {
101        Ok(Self::Confidential(
102            ConfInner::from_slice(bytes).map_err(secp256k1_zkp::Error::Upstream)?,
103        ))
104    }
105
106    /// Check if the object is null.
107    pub fn is_null(&self) -> bool { matches!(*self, Self::Null) }
108
109    /// Check if the object is explicit.
110    pub fn is_explicit(&self) -> bool { matches!(*self, Self::Explicit(_)) }
111
112    /// Check if the object is confidential.
113    pub fn is_confidential(&self) -> bool { matches!(*self, Self::Confidential(_)) }
114
115    /// Returns the explicit inner value.
116    /// Returns [None] if [`Self::is_explicit`] returns false.
117    pub fn explicit(&self) -> Option<ExplicitInner> {
118        match *self {
119            Self::Explicit(i) => Some(i),
120            _ => None,
121        }
122    }
123
124    /// Returns the confidential commitment in case of a confidential value.
125    /// Returns [None] if [`Self::is_confidential`] returns false.
126    pub fn commitment(&self) -> Option<ConfInner> {
127        match *self {
128            Self::Confidential(i) => Some(i),
129            _ => None,
130        }
131    }
132}
133
134impl From<ConfInner> for Nonce {
135    fn from(from: ConfInner) -> Self { Self::Confidential(from) }
136}
137
138impl fmt::Display for Nonce {
139    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
140        match *self {
141            Self::Null => f.write_str("null"),
142            Self::Explicit(n) => {
143                for b in &n {
144                    write!(f, "{:02x}", b)?;
145                }
146                Ok(())
147            }
148            Self::Confidential(pk) => write!(f, "{:02x}", pk),
149        }
150    }
151}
152
153impl Encodable for Nonce {
154    fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {
155        match *self {
156            Self::Null => {
157                s.write_all(&[0u8])?;
158                Ok(1)
159            }
160            Self::Explicit(n) => {
161                s.write_all(&[1u8])?;
162                s.write_all(&n)?;
163                Ok(1 + EXPLICIT_LEN)
164            }
165            Self::Confidential(commitment) => {
166                s.write_all(&commitment.serialize())?;
167                Ok(CONFIDENTIAL_LEN)
168            }
169        }
170    }
171}
172
173impl Decodable for Nonce {
174    fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, encode::Error> {
175        let mut buf = [0u8; CONFIDENTIAL_LEN];
176        d.read_exact(&mut buf[0..1])?;
177
178        match buf[0] {
179            0 => Ok(Self::Null),
180            1 => {
181                let mut buf = [0; EXPLICIT_LEN];
182                d.read_exact(&mut buf)?;
183                Ok(Self::Explicit(buf))
184            }
185            p if p == CONF_PREFIX_1 || p == CONF_PREFIX_2 => {
186                d.read_exact(&mut buf[1..])?;
187                Ok(Self::Confidential(ConfInner::from_slice(&buf)?))
188            }
189            p => Err(encode::Error::InvalidConfidentialPrefix(p)),
190        }
191    }
192}
193
194#[cfg(feature = "serde")]
195impl Serialize for Nonce {
196    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
197        use serde::ser::SerializeSeq;
198
199        let seq_len = match *self {
200            Self::Null => 1,
201            Self::Explicit(_) | Self::Confidential(_) => 2,
202        };
203        let mut seq = s.serialize_seq(Some(seq_len))?;
204
205        match *self {
206            Self::Null => seq.serialize_element(&0u8)?,
207            Self::Explicit(n) => {
208                seq.serialize_element(&1u8)?;
209                seq.serialize_element(&n)?;
210            }
211            Self::Confidential(commitment) => {
212                seq.serialize_element(&2u8)?;
213                seq.serialize_element(&commitment)?;
214            }
215        }
216        seq.end()
217    }
218}
219
220#[cfg(feature = "serde")]
221impl<'de> Deserialize<'de> for Nonce {
222    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
223        use serde::de::{Error, SeqAccess, Visitor};
224        struct CommitVisitor;
225
226        impl<'de> Visitor<'de> for CommitVisitor {
227            type Value = Nonce;
228
229            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
230                f.write_str("a committed value")
231            }
232
233            fn visit_seq<A: SeqAccess<'de>>(self, mut access: A) -> Result<Nonce, A::Error> {
234                let prefix = access.next_element::<u8>()?;
235                match prefix {
236                    Some(0) => Ok(Self::Value::Null),
237                    Some(1) => match access.next_element()? {
238                        Some(x) => Ok(Self::Value::Explicit(x)),
239                        None => Err(A::Error::custom("missing explicit nonce")),
240                    },
241                    Some(2) => match access.next_element()? {
242                        Some(x) => Ok(Self::Value::Confidential(x)),
243                        None => Err(A::Error::custom("missing nonce")),
244                    },
245                    _ => Err(A::Error::custom("wrong or missing prefix")),
246                }
247            }
248        }
249
250        d.deserialize_seq(CommitVisitor)
251    }
252}
253
254encoding::encoder_newtype_exact! {
255    /// Encoder for the [`Nonce`] type.
256    #[derive(Clone, Debug)]
257    pub struct Encoder<'e>(CommitmentEncoder<'e>);
258}
259
260impl encoding::Encode for Nonce {
261    type Encoder<'e> = Encoder<'e>;
262
263    fn encoder(&self) -> Self::Encoder<'_> {
264        Encoder::new(match *self {
265            Self::Null => CommitmentEncoder::Null(0),
266            Self::Explicit(ref id) => CommitmentEncoder::Explicit32(Some(1), id),
267            Self::Confidential(ref gen) => CommitmentEncoder::Explicit33(gen.serialize()),
268        })
269    }
270}
271
272decoder_state_machine! {
273    /// A decoder for the [`Nonce`] type.
274    pub struct Decoder(enum DecoderInner {
275        Done(Nonce),
276        Errored,
277        DecodePrefix {
278            decoder: encoding::ArrayDecoder<1>,
279            => transition_decode_prefix(prefix, ...) -> Result {
280                match prefix {
281                    [0] => Ok(DecoderInner::Done(Nonce::Null)),
282                    [1] => {
283                        Ok(DecoderInner::DecodeExplicit { decoder: encoding::ArrayDecoder::default() })
284                    },
285                    [prefix @ (CONF_PREFIX_1 | CONF_PREFIX_2)] => {
286                        Ok(DecoderInner::DecodeConfidential { decoder: encoding::ArrayDecoder::default(), prefix })
287                    },
288                    [prefix] => Err(DecoderErrorInner::InvalidConfidentialPrefix { prefix })
289                }
290            }
291        },
292        DecodeExplicit {
293            decoder: encoding::ArrayDecoder<EXPLICIT_LEN>
294            => transition_decode_explicit(bytes, ...) -> Result {
295                Ok(DecoderInner::Done(Nonce::Explicit(bytes)))
296            }
297        },
298        DecodeConfidential {
299            decoder: encoding::ArrayDecoder<CONFIDENTIAL_LEN_LESS_PREFIX>,
300            prefix: u8
301            => transition_decode_confidential(x_coord, ...) -> Result {
302                let mut bytes = [0; CONFIDENTIAL_LEN];
303                bytes[0] = prefix;
304                bytes[1..].copy_from_slice(&x_coord);
305                let gen = ConfInner::from_slice(&bytes)
306                    .map_err(DecoderErrorInner::InvalidCommitment)?;
307                Ok(DecoderInner::Done(Nonce::Confidential(gen)))
308            }
309        },
310    });
311
312    /// A decoder error for the [`Nonce`] type.
313    #[derive(Clone, PartialEq, Eq, Debug)]
314    pub struct DecoderError(enum DecoderErrorInner {
315        [macro-inserted decoder variants]
316        /// Confidential prefix was not one of the two allowable values.
317        InvalidConfidentialPrefix {
318            prefix: u8,
319        },
320        /// Malformed confidential commitment.
321        InvalidCommitment(bitcoin::secp256k1::Error),
322    });
323}
324
325impl fmt::Display for DecoderError {
326    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
327        use DecoderErrorInner as Inner;
328        match self.0 {
329            Inner::DecodePrefix(_) => f.write_str("failed to decode prefix"),
330            Inner::DecodeExplicit(_) => f.write_str("failed to decode explicit value"),
331            Inner::DecodeConfidential(_) => f.write_str("failed to decode confidential value"),
332            Inner::InvalidConfidentialPrefix { prefix, .. } => {
333                write!(
334                    f,
335                    "confidential prefix 0x{:02x} was not one of 0, 1, 0x{:02x} or 0x{:02x}",
336                    prefix, CONF_PREFIX_1, CONF_PREFIX_2,
337                )
338            }
339            Inner::InvalidCommitment(_) => f.write_str("failed to parse confidential commitment"),
340        }
341    }
342}
343
344impl std::error::Error for DecoderError {
345    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
346        use DecoderErrorInner as Inner;
347        match self.0 {
348            Inner::DecodePrefix(ref e) => Some(e),
349            Inner::DecodeExplicit(ref e) => Some(e),
350            Inner::DecodeConfidential(ref e) => Some(e),
351            Inner::InvalidConfidentialPrefix { .. } => None,
352            Inner::InvalidCommitment(ref e) => Some(e),
353        }
354    }
355}
356
357impl Default for Decoder {
358    fn default() -> Self {
359        Self(DecoderInner::DecodePrefix { decoder: encoding::ArrayDecoder::default() })
360    }
361}