reddsa/src/verification_key.rs

203 lines
7.0 KiB
Rust
Raw Normal View History

// -*- mode: rust; -*-
//
2021-03-01 06:38:25 -08:00
// This file is part of reddsa.
// Copyright (c) 2019-2021 Zcash Foundation
// See LICENSE for licensing information.
//
// Authors:
// - Deirdre Connolly <deirdre@zfnd.org>
// - Henry de Valence <hdevalence@hdevalence.ca>
use std::{
convert::TryFrom,
hash::{Hash, Hasher},
marker::PhantomData,
};
2019-12-02 21:58:19 -08:00
2021-03-01 06:54:52 -08:00
use jubjub::Scalar;
use crate::{Error, Randomizer, SigType, Signature, SpendAuth};
2019-12-02 21:58:19 -08:00
2019-12-03 15:59:24 -08:00
/// A refinement type for `[u8; 32]` indicating that the bytes represent
/// an encoding of a RedJubJub verification key.
2019-12-03 15:59:24 -08:00
///
/// This is useful for representing a compressed verification key; the
/// [`VerificationKey`] type in this library holds other decompressed state
2019-12-03 15:59:24 -08:00
/// used in signature verification.
2019-12-02 21:58:19 -08:00
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct VerificationKeyBytes<T: SigType> {
2019-12-03 15:59:24 -08:00
pub(crate) bytes: [u8; 32],
pub(crate) _marker: PhantomData<T>,
}
2019-12-02 21:58:19 -08:00
impl<T: SigType> From<[u8; 32]> for VerificationKeyBytes<T> {
fn from(bytes: [u8; 32]) -> VerificationKeyBytes<T> {
VerificationKeyBytes {
2019-12-03 13:39:26 -08:00
bytes,
_marker: PhantomData,
}
2019-12-02 21:58:19 -08:00
}
}
impl<T: SigType> From<VerificationKeyBytes<T>> for [u8; 32] {
fn from(refined: VerificationKeyBytes<T>) -> [u8; 32] {
refined.bytes
2019-12-02 21:58:19 -08:00
}
}
impl<T: SigType> Hash for VerificationKeyBytes<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.bytes.hash(state);
self._marker.hash(state);
}
}
/// A valid RedJubJub verification key.
2019-12-04 17:36:01 -08:00
///
/// This type holds decompressed state used in signature verification; if the
/// verification key may not be used immediately, it is probably better to use
/// [`VerificationKeyBytes`], which is a refinement type for `[u8; 32]`.
///
/// ## Consensus properties
///
/// The `TryFrom<VerificationKeyBytes>` conversion performs the following Zcash
/// consensus rule checks:
///
/// 1. The check that the bytes are a canonical encoding of a verification key;
/// 2. The check that the verification key is not a point of small order.
Implement the messages spec (#114) * start messages and validation * add missing docs to constants * change validation to matches, fix constant doc Co-authored-by: teor <teor@riseup.net> * fix the build * validate share_commitment * add new constants and validations * fix validation * derive serde Serialize and Deserialize in all messages structs * update created structs Co-authored-by: teor <teor@riseup.net> * fix build * define and use a new MAX_SIGNERS constant * change group_public type * add some test cases * add validation and serialization tests for SigningCommitments * add validation and serialization test to SigningPackage * change some fields order matching the spec * fix field order in tests according to last updates to the spec * implement serialize and deserialize for ParticipantId * move serde-json to dev-dependencies section * change to pub(crate) * fix serialize of VerificationKey * add assert to serialize * add note, fix typo * improve some code in tests * test serialization of individual fields * start messages and validation * add missing docs to constants * change validation to matches, fix constant doc Co-authored-by: teor <teor@riseup.net> * fix the build * validate share_commitment * add new constants and validations * fix validation * define and use a new MAX_SIGNERS constant * change group_public type * change some fields order matching the spec * change message fields to new spec * remove some non needed conversions * use a BTreeMap to guarantee the order * remove some calls to `clone()` by implementing `Copy` * change message type in frost and add validate_signatureshare test * change `share_commitment` to BTreeMap * add `serialize_signatureshare` test * add aggregatesignature tests * add some test header messages utility functions * add a setup utility * move the general serialization checks into an utility function * fi some typos * add and use a `generate_share_commitment` utility * add create_signing_commitments utility function * improve the serialization tests * make room for prop tests * add arbitrary tests for serialization * remove allow dead code from messages * fix some imports * make signature module public only to the crate * simplify a bit the frost tests * improve the generated docs * add a `prop_filter` to Header arbitrary * (ab)use proptest_derive * improve validation for Message * improve some utility functions * change frost to serialization id conversion * add a quick btreemap test * change the `MsgType` to `u32` * add no leftover bytes checks * add a full_setup utility * add map len checks Co-authored-by: teor <teor@riseup.net>
2021-06-16 12:13:23 -07:00
#[derive(PartialEq, Copy, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "VerificationKeyBytes<T>"))]
#[cfg_attr(feature = "serde", serde(into = "VerificationKeyBytes<T>"))]
#[cfg_attr(feature = "serde", serde(bound = "T: SigType"))]
pub struct VerificationKey<T: SigType> {
2019-12-03 14:51:38 -08:00
// XXX-jubjub: this should just be Point
2019-12-03 15:01:54 -08:00
pub(crate) point: jubjub::ExtendedPoint,
pub(crate) bytes: VerificationKeyBytes<T>,
2019-12-02 21:58:19 -08:00
}
impl<T: SigType> From<VerificationKey<T>> for VerificationKeyBytes<T> {
fn from(pk: VerificationKey<T>) -> VerificationKeyBytes<T> {
2019-12-03 15:59:24 -08:00
pk.bytes
2019-12-02 21:58:19 -08:00
}
}
impl<T: SigType> From<VerificationKey<T>> for [u8; 32] {
fn from(pk: VerificationKey<T>) -> [u8; 32] {
2019-12-04 17:36:01 -08:00
pk.bytes.bytes
}
}
impl<T: SigType> TryFrom<VerificationKeyBytes<T>> for VerificationKey<T> {
2019-12-02 21:58:19 -08:00
type Error = Error;
fn try_from(bytes: VerificationKeyBytes<T>) -> Result<Self, Self::Error> {
2019-12-03 14:51:38 -08:00
// XXX-jubjub: this should not use CtOption
// XXX-jubjub: this takes ownership of bytes, while Fr doesn't.
// This checks that the encoding is canonical...
2019-12-03 14:51:38 -08:00
let maybe_point = jubjub::AffinePoint::from_bytes(bytes.bytes);
if maybe_point.is_some().into() {
let point: jubjub::ExtendedPoint = maybe_point.unwrap().into();
// Note that small-order verification keys (including the identity) are not
// rejected here. Previously they were rejected, but this was a bug as the
// RedDSA specification allows them. Zcash Sapling rejects small-order points
// for the RedJubjub spend authorization key rk; this now occurs separately.
// Meanwhile, Zcash Orchard uses a prime-order group, so the only small-order
// point would be the identity, which is allowed in Orchard.
Ok(VerificationKey { point, bytes })
2019-12-03 14:51:38 -08:00
} else {
Err(Error::MalformedVerificationKey)
2019-12-03 14:51:38 -08:00
}
2019-12-02 21:58:19 -08:00
}
}
2019-12-02 22:20:21 -08:00
impl<T: SigType> TryFrom<[u8; 32]> for VerificationKey<T> {
2019-12-04 17:36:01 -08:00
type Error = Error;
fn try_from(bytes: [u8; 32]) -> Result<Self, Self::Error> {
use std::convert::TryInto;
VerificationKeyBytes::from(bytes).try_into()
2019-12-04 17:36:01 -08:00
}
}
impl VerificationKey<SpendAuth> {
/// Randomize this verification key with the given `randomizer`.
2019-12-04 17:00:55 -08:00
///
/// Randomization is only supported for `SpendAuth` keys.
pub fn randomize(&self, randomizer: &Randomizer) -> VerificationKey<SpendAuth> {
2019-12-04 17:00:55 -08:00
use crate::private::Sealed;
let point = &self.point + &(&SpendAuth::basepoint() * randomizer);
let bytes = VerificationKeyBytes {
2019-12-04 17:00:55 -08:00
bytes: jubjub::AffinePoint::from(&point).to_bytes(),
_marker: PhantomData,
};
VerificationKey { bytes, point }
2019-12-04 17:00:55 -08:00
}
}
impl<T: SigType> VerificationKey<T> {
pub(crate) fn from(s: &Scalar) -> VerificationKey<T> {
let point = &T::basepoint() * s;
let bytes = VerificationKeyBytes {
bytes: jubjub::AffinePoint::from(&point).to_bytes(),
_marker: PhantomData,
};
VerificationKey { bytes, point }
}
/// Verify a purported `signature` over `msg` made by this verification key.
// This is similar to impl signature::Verifier but without boxed errors
2019-12-04 11:59:31 -08:00
pub fn verify(&self, msg: &[u8], signature: &Signature<T>) -> Result<(), Error> {
2019-12-03 22:32:30 -08:00
use crate::HStar;
let c = HStar::default()
.update(&signature.r_bytes[..])
.update(&self.bytes.bytes[..]) // XXX ugly
.update(msg)
.finalize();
self.verify_prehashed(signature, c)
}
2019-12-02 22:32:55 -08:00
/// Verify a purported `signature` with a prehashed challenge.
#[allow(non_snake_case)]
pub(crate) fn verify_prehashed(
&self,
signature: &Signature<T>,
c: Scalar,
) -> Result<(), Error> {
2019-12-03 22:32:30 -08:00
let r = {
// XXX-jubjub: should not use CtOption here
// XXX-jubjub: inconsistent ownership in from_bytes
let maybe_point = jubjub::AffinePoint::from_bytes(signature.r_bytes);
if maybe_point.is_some().into() {
jubjub::ExtendedPoint::from(maybe_point.unwrap())
} else {
return Err(Error::InvalidSignature);
}
};
let s = {
// XXX-jubjub: should not use CtOption here
let maybe_scalar = Scalar::from_bytes(&signature.s_bytes);
if maybe_scalar.is_some().into() {
maybe_scalar.unwrap()
} else {
return Err(Error::InvalidSignature);
}
};
// XXX rewrite as normal double scalar mul
// Verify check is h * ( - s * B + R + c * A) == 0
// h * ( s * B - c * A - R) == 0
let sB = &T::basepoint() * &s;
let cA = &self.point * &c;
let check = sB - cA - r;
if check.is_small_order().into() {
Ok(())
} else {
Err(Error::InvalidSignature)
}
2019-12-02 22:20:21 -08:00
}
}