Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

signature-crate: Replace DigestSignature with derive attr #27

Merged
merged 1 commit into from
Oct 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 62 additions & 56 deletions signature-crate/signature_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,96 +12,102 @@ extern crate proc_macro;

use proc_macro2::TokenStream;
use quote::quote;
use syn::{Attribute, Meta, NestedMeta};
use synstructure::{decl_derive, AddBounds};

/// Name of the digest attribute
const DIGEST_ATTRIBUTE_NAME: &str = "digest";

/// Derive the `Signer` trait for `DigestSigner` types
fn derive_signer(mut s: synstructure::Structure) -> TokenStream {
let digest_path = DigestAttribute::parse(&s).into_meta("Signer");

s.add_bounds(AddBounds::None);
s.gen_impl(quote! {
gen impl<S> signature::Signer<S> for @Self
where
S: signature::DigestSignature,
Self: signature::DigestSigner<S::Digest, S>
S: Signature,
Self: signature::DigestSigner<#digest_path, S>
{
fn try_sign(&self, msg: &[u8]) -> Result<S, signature::Error> {
self.try_sign_digest(S::Digest::new().chain(msg))
self.try_sign_digest(#digest_path::new().chain(msg))
}
}
})
}
decl_derive!([Signer] => derive_signer);
decl_derive!([Signer, attributes(digest)] => derive_signer);

/// Derive the `Verifier` trait for `DigestVerifier` types
fn derive_verifier(mut s: synstructure::Structure) -> TokenStream {
let digest_path = DigestAttribute::parse(&s).into_meta("Verifier");

s.add_bounds(AddBounds::None);
s.gen_impl(quote! {
gen impl<S> signature::Verifier<S> for @Self
where
S: signature::DigestSignature,
Self: signature::DigestVerifier<S::Digest, S>
S: Signature,
Self: signature::DigestVerifier<#digest_path, S>
{
fn verify(&self, msg: &[u8], signature: &S) -> Result<(), signature::Error> {
self.verify_digest(S::Digest::new().chain(msg), signature)
self.verify_digest(#digest_path::new().chain(msg), signature)
}
}
})
}
decl_derive!([Verifier] => derive_verifier);

#[cfg(test)]
mod tests {
use super::*;
use synstructure::test_derive;

#[test]
fn signer() {
test_derive! {
derive_signer {
struct MySigner<C: EllipticCurve> {
scalar: Scalar<C::ScalarSize>
}
}
expands to {
#[allow(non_upper_case_globals)]
const _DERIVE_signature_Signer_S_FOR_MySigner: () = {
impl<S, C: EllipticCurve> signature::Signer<S> for MySigner<C>
where
S: signature::DigestSignature,
Self: signature::DigestSigner<S::Digest, S>
{
fn try_sign(&self, msg: &[u8]) -> Result <S, signature::Error> {
self.try_sign_digest(S::Digest::new().chain(msg))
}
}
};
decl_derive!([Verifier, attributes(digest)] => derive_verifier);

/// The `#[digest(...)]` attribute passed to the proc macro
#[derive(Default)]
struct DigestAttribute {
digest: Option<Meta>,
}

impl DigestAttribute {
/// Parse attributes from the incoming AST
fn parse(s: &synstructure::Structure<'_>) -> Self {
let mut result = Self::default();

for v in s.variants().iter() {
for attr in v.ast().attrs.iter() {
result.parse_attr(attr);
}
no_build // tests in `signature-crate/tests`
}

result
}

#[test]
fn verifier() {
test_derive! {
derive_verifier {
struct MyVerifier<C: EllipticCurve> {
point: UncompressedPoint<C>
}
/// Parse attribute and handle `#[digest(...)]` attribute
fn parse_attr(&mut self, attr: &Attribute) {
let meta = attr
.parse_meta()
.unwrap_or_else(|e| panic!("error parsing digest attribute: {:?} ({})", attr, e));

if let Meta::List(list) = meta {
if !list.path.is_ident(DIGEST_ATTRIBUTE_NAME) {
return;
}
expands to {
#[allow(non_upper_case_globals)]
const _DERIVE_signature_Verifier_S_FOR_MyVerifier: () = {
impl<S, C: EllipticCurve> signature::Verifier<S> for MyVerifier<C>
where
S: signature::DigestSignature,
Self: signature::DigestVerifier<S::Digest, S>
{
fn verify(&self, msg: &[u8], signature: &S) -> Result<(), signature::Error> {
self.verify_digest(S::Digest::new().chain(msg), signature)
}

for nested_meta in &list.nested {
if let NestedMeta::Meta(meta) = nested_meta {
if self.digest.is_none() {
self.digest = Some(meta.to_owned());
} else {
panic!("multiple digest attributes in custom derive");
}
};
} else {
panic!("malformed digest attribute: {:?}", nested_meta);
}
}
no_build // tests in `signature-crate/tests`
}
}

/// Convert parsed attributes into the recovered `Meta`
fn into_meta(self, trait_name: &str) -> Meta {
self.digest.unwrap_or_else(|| {
panic!(
"#[digest(...)] attribute is mandatory when deriving {}",
trait_name
)
})
}
}
16 changes: 0 additions & 16 deletions signature-crate/src/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,3 @@ pub trait Signature: AsRef<[u8]> + Debug + Sized {
self.as_slice().into()
}
}

/// Marker trait for `Signature` types computable as `S(H(m))`
///
/// - `S`: signature algorithm
/// - `H`: hash (a.k.a. digest) function
/// - `m`: message
///
/// For signature types that implement this trait, a blanket impl of
/// `Signer` will be provided for all types that `impl DigestSigner`
/// along with a corresponding impl of `Verifier` for all types that
/// `impl DigestVerifier`.
#[cfg(feature = "digest")]
pub trait DigestSignature: Signature {
/// Preferred `Digest` algorithm to use when computing this signature type.
type Digest: digest::Digest;
}
10 changes: 3 additions & 7 deletions signature-crate/tests/signature_derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ mod tests {
use digest::{generic_array::GenericArray, Digest};
use hex_literal::hex;
use sha2::Sha256;
use signature::{
DigestSignature, DigestSigner, DigestVerifier, Error, Signature, Signer, Verifier,
};
use signature::{DigestSigner, DigestVerifier, Error, Signature, Signer, Verifier};

/// Test vector to compute SHA-256 digest of
const INPUT_STRING: &[u8] = b"abc";
Expand All @@ -33,12 +31,9 @@ mod tests {
}
}

impl DigestSignature for DummySignature {
type Digest = Sha256;
}

/// Dummy signer which just returns the message digest as a `DummySignature`
#[derive(Signer, Default)]
#[digest(Sha256)]
struct DummySigner {}

impl DigestSigner<Sha256, DummySignature> for DummySigner {
Expand All @@ -52,6 +47,7 @@ mod tests {
///
/// Panics (via `assert_eq!`) if the value is not what is expected.
#[derive(Verifier, Default)]
#[digest(Sha256)]
struct DummyVerifier {}

impl DigestVerifier<Sha256, DummySignature> for DummyVerifier {
Expand Down