Support multiple BLS implementations (#1335)

## Issue Addressed

NA

## Proposed Changes

- Refactor the `bls` crate to support multiple BLS "backends" (e.g., milagro, blst, etc).
- Removes some duplicate, unused code in `common/rest_types/src/validator.rs`.
- Removes the old "upgrade legacy keypairs" functionality (these were unencrypted keys that haven't been supported for a few testnets, no one should be using them anymore).

## Additional Info

Most of the files changed are just inconsequential changes to function names.

## TODO

- [x] Optimization levels
- [x] Infinity point: https://github.com/supranational/blst/issues/11
- [x] Ensure milagro *and* blst are tested via CI
- [x] What to do with unsafe code?
- [x] Test infinity point in signature sets
This commit is contained in:
Paul Hauner
2020-07-25 02:03:18 +00:00
parent 21bcc8848d
commit b73c497be2
117 changed files with 3009 additions and 2463 deletions

View File

@@ -1,99 +0,0 @@
use super::{PublicKey, BLS_PUBLIC_KEY_BYTE_SIZE};
use milagro_bls::AggregatePublicKey as RawAggregatePublicKey;
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use serde_hex::{encode as hex_encode, PrefixedHexVisitor};
use ssz::{Decode, DecodeError, Encode};
/// A BLS aggregate public key.
///
/// This struct is a wrapper upon a base type and provides helper functions (e.g., SSZ
/// serialization).
#[derive(Debug, Clone, Default)]
pub struct AggregatePublicKey(RawAggregatePublicKey);
impl AggregatePublicKey {
pub fn new() -> Self {
AggregatePublicKey(RawAggregatePublicKey::new())
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
let pubkey = RawAggregatePublicKey::from_bytes(&bytes).map_err(|_| {
DecodeError::BytesInvalid(format!("Invalid AggregatePublicKey bytes: {:?}", bytes))
})?;
Ok(AggregatePublicKey(pubkey))
}
pub fn add_without_affine(&mut self, public_key: &PublicKey) {
self.0.point.add(&public_key.as_raw().point)
}
pub fn affine(&mut self) {
self.0.point.affine()
}
pub fn add(&mut self, public_key: &PublicKey) {
self.0.add(public_key.as_raw())
}
/// Returns the underlying public key.
pub fn as_raw(&self) -> &RawAggregatePublicKey {
&self.0
}
/// Returns the underlying point as compressed bytes.
pub fn as_bytes(&self) -> [u8; BLS_PUBLIC_KEY_BYTE_SIZE] {
self.as_raw().as_bytes()
}
pub fn into_raw(self) -> RawAggregatePublicKey {
self.0
}
/// Return a hex string representation of this key's bytes.
#[cfg(test)]
pub fn as_hex_string(&self) -> String {
serde_hex::encode(self.as_ssz_bytes())
}
}
impl_ssz!(
AggregatePublicKey,
BLS_PUBLIC_KEY_BYTE_SIZE,
"AggregatePublicKey"
);
impl_tree_hash!(AggregatePublicKey, BLS_PUBLIC_KEY_BYTE_SIZE);
impl Serialize for AggregatePublicKey {
/// Serde serialization is compliant the Ethereum YAML test format.
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&hex_encode(self.as_ssz_bytes()))
}
}
impl<'de> Deserialize<'de> for AggregatePublicKey {
/// Serde serialization is compliant the Ethereum YAML test format.
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let bytes = deserializer.deserialize_str(PrefixedHexVisitor)?;
let agg_sig = AggregatePublicKey::from_ssz_bytes(&bytes)
.map_err(|e| serde::de::Error::custom(format!("invalid ssz ({:?})", e)))?;
Ok(agg_sig)
}
}
#[cfg(feature = "arbitrary")]
impl arbitrary::Arbitrary for AggregatePublicKey {
fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
let mut bytes = [0u8; BLS_PUBLIC_KEY_BYTE_SIZE];
u.fill_buffer(&mut bytes)?;
Self::from_bytes(&bytes).map_err(|_| arbitrary::Error::IncorrectFormat)
}
}

View File

@@ -1,201 +0,0 @@
use super::*;
use milagro_bls::AggregateSignature as RawAggregateSignature;
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use serde_hex::{encode as hex_encode, PrefixedHexVisitor};
use ssz::{Decode, DecodeError, Encode};
/// A BLS aggregate signature.
///
/// This struct is a wrapper upon a base type and provides helper functions (e.g., SSZ
/// serialization).
#[derive(Debug, PartialEq, Clone, Default, Eq)]
pub struct AggregateSignature {
aggregate_signature: RawAggregateSignature,
is_empty: bool,
}
impl AggregateSignature {
/// Instantiate a new AggregateSignature.
///
/// is_empty is false
/// AggregateSignature is point at infinity
pub fn new() -> Self {
Self {
aggregate_signature: RawAggregateSignature::new(),
is_empty: false,
}
}
/// Add (aggregate) a signature to the `AggregateSignature`.
pub fn add(&mut self, signature: &Signature) {
// Only empty if both are empty
self.is_empty = self.is_empty && signature.is_empty();
// Note: empty signatures will have point at infinity which is equivalent of adding 0.
self.aggregate_signature.add(signature.as_raw())
}
/// Add (aggregate) another `AggregateSignature`.
pub fn add_aggregate(&mut self, agg_signature: &AggregateSignature) {
// Only empty if both are empty
self.is_empty = self.is_empty && agg_signature.is_empty();
// Note: empty signatures will have point at infinity which is equivalent of adding 0.
self.aggregate_signature
.add_aggregate(&agg_signature.aggregate_signature)
}
/// Verify the `AggregateSignature` against an `AggregatePublicKey`.
///
/// Only returns `true` if the set of keys in the `AggregatePublicKey` match the set of keys
/// that signed the `AggregateSignature`.
pub fn verify(&self, msg: &[u8], aggregate_public_key: &AggregatePublicKey) -> bool {
if self.is_empty {
return false;
}
self.aggregate_signature
.fast_aggregate_verify_pre_aggregated(msg, aggregate_public_key.as_raw())
}
/// Verify the `AggregateSignature` against an `AggregatePublicKey`.
///
/// Only returns `true` if the set of keys in the `AggregatePublicKey` match the set of keys
/// that signed the `AggregateSignature`.
pub fn verify_unaggregated(&self, msg: &[u8], public_keys: &[&PublicKey]) -> bool {
if self.is_empty {
return false;
}
let public_key_refs: Vec<_> = public_keys.iter().map(|pk| pk.as_raw()).collect();
self.aggregate_signature
.fast_aggregate_verify(msg, &public_key_refs)
}
/// Verify this AggregateSignature against multiple AggregatePublickeys and Messages.
///
/// Each AggregatePublicKey has a 1:1 ratio with a 32 byte Message.
pub fn verify_multiple(&self, messages: &[&[u8]], public_keys: &[&PublicKey]) -> bool {
if self.is_empty {
return false;
}
let public_keys_refs: Vec<_> = public_keys.iter().map(|pk| pk.as_raw()).collect();
self.aggregate_signature
.aggregate_verify(&messages, &public_keys_refs)
}
/// Return AggregateSignature as bytes
pub fn as_bytes(&self) -> [u8; BLS_AGG_SIG_BYTE_SIZE] {
if self.is_empty {
return [0; BLS_AGG_SIG_BYTE_SIZE];
}
self.aggregate_signature.as_bytes()
}
/// Convert bytes to AggregateSignature
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
for byte in bytes {
if *byte != 0 {
let sig = RawAggregateSignature::from_bytes(&bytes).map_err(|_| {
DecodeError::BytesInvalid(format!(
"Invalid AggregateSignature bytes: {:?}",
bytes
))
})?;
return Ok(Self {
aggregate_signature: sig,
is_empty: false,
});
}
}
Ok(Self::empty_signature())
}
/// Returns the underlying signature.
pub fn as_raw(&self) -> &RawAggregateSignature {
&self.aggregate_signature
}
/// Returns if the AggregateSignature `is_empty`
pub fn is_empty(&self) -> bool {
self.is_empty
}
/// Creates a new AggregateSignature
///
/// aggregate_signature set to the point infinity
/// is_empty set to true
pub fn empty_signature() -> Self {
Self {
aggregate_signature: RawAggregateSignature::new(),
is_empty: true,
}
}
/// Return a hex string representation of the bytes of this signature.
#[cfg(test)]
pub fn as_hex_string(&self) -> String {
hex_encode(self.as_ssz_bytes())
}
}
impl_ssz!(
AggregateSignature,
BLS_AGG_SIG_BYTE_SIZE,
"AggregateSignature"
);
impl_tree_hash!(AggregateSignature, BLS_AGG_SIG_BYTE_SIZE);
impl Serialize for AggregateSignature {
/// Serde serialization is compliant the Ethereum YAML test format.
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&hex_encode(self.as_ssz_bytes()))
}
}
impl<'de> Deserialize<'de> for AggregateSignature {
/// Serde serialization is compliant the Ethereum YAML test format.
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let bytes = deserializer.deserialize_str(PrefixedHexVisitor)?;
let agg_sig = AggregateSignature::from_ssz_bytes(&bytes)
.map_err(|e| serde::de::Error::custom(format!("invalid ssz ({:?})", e)))?;
Ok(agg_sig)
}
}
#[cfg(feature = "arbitrary")]
impl arbitrary::Arbitrary for AggregateSignature {
fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
let mut bytes = [0u8; BLS_AGG_SIG_BYTE_SIZE];
u.fill_buffer(&mut bytes)?;
Self::from_bytes(&bytes).map_err(|_| arbitrary::Error::IncorrectFormat)
}
}
#[cfg(test)]
mod tests {
use super::super::{Keypair, Signature};
use super::*;
use ssz::Encode;
#[test]
pub fn test_ssz_round_trip() {
let keypair = Keypair::random();
let mut original = AggregateSignature::new();
original.add(&Signature::new(&[42, 42], &keypair.sk));
let bytes = original.as_ssz_bytes();
let decoded = AggregateSignature::from_ssz_bytes(&bytes).unwrap();
assert_eq!(original, decoded);
}
}

View File

@@ -1,132 +0,0 @@
use super::{PublicKey, BLS_PUBLIC_KEY_BYTE_SIZE};
use hex::encode as hex_encode;
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use serde_hex::PrefixedHexVisitor;
use ssz::{ssz_encode, Decode, DecodeError, Encode};
use std::fmt;
/// A BLS aggregate public key.
///
/// This struct is a wrapper upon a base type and provides helper functions (e.g., SSZ
/// serialization).
#[derive(Clone)]
pub struct FakeAggregatePublicKey {
bytes: [u8; BLS_PUBLIC_KEY_BYTE_SIZE],
}
impl FakeAggregatePublicKey {
pub fn new() -> Self {
Self::zero()
}
pub fn empty_signature() -> Self {
Self {
bytes: [0; BLS_PUBLIC_KEY_BYTE_SIZE],
}
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
if bytes.len() != BLS_PUBLIC_KEY_BYTE_SIZE {
Err(DecodeError::InvalidByteLength {
len: bytes.len(),
expected: BLS_PUBLIC_KEY_BYTE_SIZE,
})
} else {
let mut array = [0; BLS_PUBLIC_KEY_BYTE_SIZE];
array.copy_from_slice(&bytes);
Ok(Self { bytes: array })
}
}
pub fn add_without_affine(&mut self, _public_key: &PublicKey) {
// No nothing.
}
pub fn affine(&mut self) {
// No nothing.
}
/// Creates a new all-zero's aggregate public key
pub fn zero() -> Self {
Self {
bytes: [0; BLS_PUBLIC_KEY_BYTE_SIZE],
}
}
pub fn add(&mut self, _public_key: &PublicKey) {
// No nothing.
}
pub fn aggregate(_pks: &[&PublicKey]) -> Self {
Self::new()
}
pub fn from_public_key(public_key: &PublicKey) -> Self {
Self {
bytes: public_key.as_bytes(),
}
}
pub fn as_raw(&self) -> &Self {
&self
}
pub fn into_raw(self) -> Self {
self
}
pub fn as_bytes(&self) -> [u8; BLS_PUBLIC_KEY_BYTE_SIZE] {
self.bytes.clone()
}
}
impl_ssz!(
FakeAggregatePublicKey,
BLS_PUBLIC_KEY_BYTE_SIZE,
"FakeAggregatePublicKey"
);
impl_tree_hash!(FakeAggregatePublicKey, BLS_PUBLIC_KEY_BYTE_SIZE);
impl Serialize for FakeAggregatePublicKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&hex_encode(ssz_encode(self)))
}
}
impl<'de> Deserialize<'de> for FakeAggregatePublicKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let bytes = deserializer.deserialize_str(PrefixedHexVisitor)?;
let pubkey = <_>::from_ssz_bytes(&bytes[..])
.map_err(|e| serde::de::Error::custom(format!("invalid ssz ({:?})", e)))?;
Ok(pubkey)
}
}
impl Default for FakeAggregatePublicKey {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for FakeAggregatePublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!("{:?}", self.bytes.to_vec()))
}
}
#[cfg(feature = "arbitrary")]
impl arbitrary::Arbitrary for FakeAggregatePublicKey {
fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
let mut bytes = [0u8; BLS_PUBLIC_KEY_BYTE_SIZE];
u.fill_buffer(&mut bytes)?;
Self::from_bytes(&bytes).map_err(|_| arbitrary::Error::IncorrectFormat)
}
}

View File

@@ -1,184 +0,0 @@
use super::{
fake_aggregate_public_key::FakeAggregatePublicKey, fake_public_key::FakePublicKey,
fake_signature::FakeSignature, BLS_AGG_SIG_BYTE_SIZE,
};
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use serde_hex::{encode as hex_encode, PrefixedHexVisitor};
use ssz::{ssz_encode, Decode, DecodeError, Encode};
use std::fmt;
/// A BLS aggregate signature.
///
/// This struct is a wrapper upon a base type and provides helper functions (e.g., SSZ
/// serialization).
#[derive(Clone)]
pub struct FakeAggregateSignature {
bytes: [u8; BLS_AGG_SIG_BYTE_SIZE],
}
impl FakeAggregateSignature {
/// Creates a new all-zero's signature
pub fn new() -> Self {
Self::zero()
}
/// Creates a new all-zero's signature
pub fn zero() -> Self {
Self {
bytes: [0; BLS_AGG_SIG_BYTE_SIZE],
}
}
pub fn as_raw(&self) -> &Self {
&self
}
/// Does glorious nothing.
pub fn add(&mut self, _signature: &FakeSignature) {
// Do nothing.
}
/// Does glorious nothing.
pub fn add_aggregate(&mut self, _agg_sig: &FakeAggregateSignature) {
// Do nothing.
}
/// Does glorious nothing.
pub fn aggregate(&mut self, _agg_sig: &FakeAggregateSignature) {
// Do nothing.
}
/// _Always_ returns `true`.
pub fn verify(&self, _msg: &[u8], _aggregate_public_key: &FakeAggregatePublicKey) -> bool {
true
}
/// _Always_ returns `true`.
pub fn verify_multiple(
&self,
_messages: &[&[u8]],
_aggregate_public_keys: &[&FakePublicKey],
) -> bool {
true
}
/// _Always_ returns `true`.
pub fn fast_aggregate_verify_pre_aggregated(
&self,
_messages: &[u8],
_aggregate_public_keys: &FakeAggregatePublicKey,
) -> bool {
true
}
/// _Always_ returns `true`.
pub fn from_signature(signature: &FakeSignature) -> Self {
Self {
bytes: signature.as_bytes(),
}
}
/// Creates a new empty FakeAggregateSignature
pub fn empty_signature() -> Self {
Self {
bytes: [0u8; BLS_AGG_SIG_BYTE_SIZE],
}
}
/// Convert bytes to fake BLS aggregate signature
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
if bytes.len() != BLS_AGG_SIG_BYTE_SIZE {
Err(DecodeError::InvalidByteLength {
len: bytes.len(),
expected: BLS_AGG_SIG_BYTE_SIZE,
})
} else {
let mut array = [0u8; BLS_AGG_SIG_BYTE_SIZE];
array.copy_from_slice(bytes);
Ok(Self { bytes: array })
}
}
pub fn as_bytes(&self) -> [u8; BLS_AGG_SIG_BYTE_SIZE] {
self.bytes.clone()
}
}
impl_ssz!(
FakeAggregateSignature,
BLS_AGG_SIG_BYTE_SIZE,
"FakeAggregateSignature"
);
impl_tree_hash!(FakeAggregateSignature, BLS_AGG_SIG_BYTE_SIZE);
impl Serialize for FakeAggregateSignature {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&hex_encode(ssz_encode(self)))
}
}
impl<'de> Deserialize<'de> for FakeAggregateSignature {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let bytes = deserializer.deserialize_str(PrefixedHexVisitor)?;
let obj = <_>::from_ssz_bytes(&bytes[..])
.map_err(|e| serde::de::Error::custom(format!("invalid ssz ({:?})", e)))?;
Ok(obj)
}
}
impl fmt::Debug for FakeAggregateSignature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!("{:?}", self.bytes.to_vec()))
}
}
impl PartialEq for FakeAggregateSignature {
fn eq(&self, other: &FakeAggregateSignature) -> bool {
ssz_encode(self) == ssz_encode(other)
}
}
impl Eq for FakeAggregateSignature {}
impl Default for FakeAggregateSignature {
fn default() -> Self {
Self::zero()
}
}
#[cfg(feature = "arbitrary")]
impl arbitrary::Arbitrary for FakeAggregateSignature {
fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
let mut bytes = [0u8; BLS_AGG_SIG_BYTE_SIZE];
u.fill_buffer(&mut bytes)?;
Self::from_bytes(&bytes).map_err(|_| arbitrary::Error::IncorrectFormat)
}
}
#[cfg(test)]
mod tests {
use super::super::{Keypair, Signature};
use super::*;
use ssz::ssz_encode;
#[test]
pub fn test_ssz_round_trip() {
let keypair = Keypair::random();
let mut original = FakeAggregateSignature::new();
original.add(&Signature::new(&[42, 42], &keypair.sk));
let bytes = ssz_encode(&original);
let decoded = FakeAggregateSignature::from_ssz_bytes(&bytes).unwrap();
assert_eq!(original, decoded);
}
}

View File

@@ -1,186 +0,0 @@
use super::{SecretKey, BLS_PUBLIC_KEY_BYTE_SIZE};
use milagro_bls::PublicKey as RawPublicKey;
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use serde_hex::{encode as hex_encode, PrefixedHexVisitor};
use ssz::{ssz_encode, Decode, DecodeError, Encode};
use std::default;
use std::fmt;
use std::hash::{Hash, Hasher};
/// A single BLS signature.
///
/// This struct is a wrapper upon a base type and provides helper functions (e.g., SSZ
/// serialization).
#[derive(Clone)]
pub struct FakePublicKey {
bytes: [u8; BLS_PUBLIC_KEY_BYTE_SIZE],
}
impl FakePublicKey {
pub fn from_secret_key(_secret_key: &SecretKey) -> Self {
Self::zero()
}
pub fn from_raw(raw: RawPublicKey) -> Self {
Self {
bytes: raw.clone().as_bytes(),
}
}
/// Creates a new all-zero's public key
pub fn zero() -> Self {
Self {
bytes: [0; BLS_PUBLIC_KEY_BYTE_SIZE],
}
}
/// Returns the underlying point as compressed bytes.
pub fn as_bytes(&self) -> [u8; BLS_PUBLIC_KEY_BYTE_SIZE] {
self.bytes.clone()
}
/// Converts compressed bytes to FakePublicKey
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
if bytes.len() != BLS_PUBLIC_KEY_BYTE_SIZE {
Err(DecodeError::InvalidByteLength {
len: bytes.len(),
expected: BLS_PUBLIC_KEY_BYTE_SIZE,
})
} else {
let mut array = [0u8; BLS_PUBLIC_KEY_BYTE_SIZE];
array.copy_from_slice(bytes);
Ok(Self { bytes: array })
}
}
/// Returns the FakePublicKey as (x, y) bytes
pub fn as_uncompressed_bytes(&self) -> [u8; BLS_PUBLIC_KEY_BYTE_SIZE * 2] {
[0u8; BLS_PUBLIC_KEY_BYTE_SIZE * 2]
}
/// Converts (x, y) bytes to FakePublicKey
pub fn from_uncompressed_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
if bytes.len() != BLS_PUBLIC_KEY_BYTE_SIZE * 2 {
Err(DecodeError::InvalidByteLength {
len: bytes.len(),
expected: BLS_PUBLIC_KEY_BYTE_SIZE * 2,
})
} else {
let mut array = [0u8; BLS_PUBLIC_KEY_BYTE_SIZE];
array.copy_from_slice(bytes);
Ok(Self { bytes: array })
}
}
/// Returns the last 6 bytes of the SSZ encoding of the public key, as a hex string.
///
/// Useful for providing a short identifier to the user.
pub fn concatenated_hex_id(&self) -> String {
let bytes = ssz_encode(self);
let end_bytes = &bytes[bytes.len().saturating_sub(6)..bytes.len()];
hex_encode(end_bytes)
}
/// Returns the point as a hex string of the SSZ encoding.
///
/// Note: the string is prefixed with `0x`.
pub fn as_hex_string(&self) -> String {
hex_encode(self.as_ssz_bytes())
}
// Returns itself
pub fn as_raw(&self) -> &Self {
self
}
}
impl fmt::Display for FakePublicKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.concatenated_hex_id())
}
}
impl fmt::Debug for FakePublicKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "0x{}", self.as_hex_string())
}
}
impl default::Default for FakePublicKey {
fn default() -> Self {
let secret_key = SecretKey::random();
FakePublicKey::from_secret_key(&secret_key)
}
}
impl_ssz!(FakePublicKey, BLS_PUBLIC_KEY_BYTE_SIZE, "FakePublicKey");
impl_tree_hash!(FakePublicKey, BLS_PUBLIC_KEY_BYTE_SIZE);
impl Serialize for FakePublicKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&hex_encode(self.as_ssz_bytes()))
}
}
impl<'de> Deserialize<'de> for FakePublicKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let bytes = deserializer.deserialize_str(PrefixedHexVisitor)?;
let pubkey = Self::from_ssz_bytes(&bytes[..])
.map_err(|e| serde::de::Error::custom(format!("invalid pubkey ({:?})", e)))?;
Ok(pubkey)
}
}
impl PartialEq for FakePublicKey {
fn eq(&self, other: &FakePublicKey) -> bool {
ssz_encode(self) == ssz_encode(other)
}
}
impl Eq for FakePublicKey {}
impl Hash for FakePublicKey {
/// Note: this is distinct from consensus serialization, it will produce a different hash.
///
/// This method uses the uncompressed bytes, which are much faster to obtain than the
/// compressed bytes required for consensus serialization.
///
/// Use `ssz::Encode` to obtain the bytes required for consensus hashing.
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_uncompressed_bytes().hash(state)
}
}
#[cfg(feature = "arbitrary")]
impl arbitrary::Arbitrary for FakePublicKey {
fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
let mut bytes = [0u8; BLS_PUBLIC_KEY_BYTE_SIZE];
u.fill_buffer(&mut bytes)?;
Self::from_bytes(&bytes).map_err(|_| arbitrary::Error::IncorrectFormat)
}
}
#[cfg(test)]
mod tests {
use super::*;
use ssz::ssz_encode;
#[test]
pub fn test_ssz_round_trip() {
let sk = SecretKey::random();
let original = FakePublicKey::from_secret_key(&sk);
let bytes = ssz_encode(&original);
let decoded = FakePublicKey::from_ssz_bytes(&bytes).unwrap();
assert_eq!(original, decoded);
}
}

View File

@@ -1,159 +0,0 @@
use super::{PublicKey, SecretKey, BLS_SIG_BYTE_SIZE};
use hex::encode as hex_encode;
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use serde_hex::PrefixedHexVisitor;
use ssz::{ssz_encode, Decode, DecodeError, Encode};
use std::fmt;
/// A single BLS signature.
///
/// This struct is a wrapper upon a base type and provides helper functions (e.g., SSZ
/// serialization).
#[derive(Clone)]
pub struct FakeSignature {
bytes: [u8; BLS_SIG_BYTE_SIZE],
is_empty: bool,
}
impl FakeSignature {
/// Creates a new all-zero's signature
pub fn new(_msg: &[u8], _sk: &SecretKey) -> Self {
FakeSignature::zero()
}
/// Creates a new all-zero's signature
pub fn zero() -> Self {
Self {
bytes: [0; BLS_SIG_BYTE_SIZE],
is_empty: true,
}
}
/// Creates a new all-zero's signature
pub fn new_hashed(_x_real_hashed: &[u8], _x_imaginary_hashed: &[u8], _sk: &SecretKey) -> Self {
FakeSignature::zero()
}
/// _Always_ returns `true`.
pub fn verify(&self, _msg: &[u8], _pk: &PublicKey) -> bool {
true
}
pub fn as_raw(&self) -> &Self {
&self
}
/// _Always_ returns true.
pub fn verify_hashed(
&self,
_x_real_hashed: &[u8],
_x_imaginary_hashed: &[u8],
_pk: &PublicKey,
) -> bool {
true
}
/// Convert bytes to fake BLS Signature
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
if bytes.len() != BLS_SIG_BYTE_SIZE {
Err(DecodeError::InvalidByteLength {
len: bytes.len(),
expected: BLS_SIG_BYTE_SIZE,
})
} else {
let is_empty = bytes.iter().all(|x| *x == 0);
let mut array = [0u8; BLS_SIG_BYTE_SIZE];
array.copy_from_slice(bytes);
Ok(Self {
bytes: array,
is_empty,
})
}
}
pub fn as_bytes(&self) -> [u8; BLS_SIG_BYTE_SIZE] {
self.bytes.clone()
}
/// Returns a new empty signature.
pub fn empty_signature() -> Self {
FakeSignature::zero()
}
// Check for empty Signature
pub fn is_empty(&self) -> bool {
self.is_empty
}
}
impl_ssz!(FakeSignature, BLS_SIG_BYTE_SIZE, "FakeSignature");
impl_tree_hash!(FakeSignature, BLS_SIG_BYTE_SIZE);
impl fmt::Debug for FakeSignature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!(
"{:?}, {:?}",
self.bytes.to_vec(),
self.is_empty()
))
}
}
impl PartialEq for FakeSignature {
fn eq(&self, other: &FakeSignature) -> bool {
self.bytes.to_vec() == other.bytes.to_vec()
}
}
impl Eq for FakeSignature {}
impl Serialize for FakeSignature {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&hex_encode(ssz_encode(self)))
}
}
impl<'de> Deserialize<'de> for FakeSignature {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let bytes = deserializer.deserialize_str(PrefixedHexVisitor)?;
let pubkey = <_>::from_ssz_bytes(&bytes[..])
.map_err(|e| serde::de::Error::custom(format!("invalid ssz ({:?})", e)))?;
Ok(pubkey)
}
}
#[cfg(feature = "arbitrary")]
impl arbitrary::Arbitrary for FakeSignature {
fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
let mut bytes = [0u8; BLS_SIG_BYTE_SIZE];
u.fill_buffer(&mut bytes)?;
Self::from_bytes(&bytes).map_err(|_| arbitrary::Error::IncorrectFormat)
}
}
#[cfg(test)]
mod tests {
use super::super::Keypair;
use super::*;
use ssz::ssz_encode;
#[test]
pub fn test_ssz_round_trip() {
let keypair = Keypair::random();
let original = FakeSignature::new(&[42, 42], &keypair.sk);
let bytes = ssz_encode(&original);
let decoded = FakeSignature::from_ssz_bytes(&bytes).unwrap();
assert_eq!(original, decoded);
}
}

View File

@@ -0,0 +1,18 @@
use crate::{Error, PUBLIC_KEY_BYTES_LEN};
/// Implemented on some struct from a BLS library so it may be used internally in this crate.
pub trait TAggregatePublicKey: Sized + Clone {
/// Initialize `Self` to the infinity value which can then have other public keys aggregated
/// upon it.
fn infinity() -> Self;
/// Serialize `self` as compressed bytes.
fn serialize(&self) -> [u8; PUBLIC_KEY_BYTES_LEN];
/// Deserialize `self` from compressed bytes.
fn deserialize(bytes: &[u8]) -> Result<Self, Error>;
}
/*
* Note: there is no immediate need for a `GenericAggregatePublicKey` struct.
*/

View File

@@ -0,0 +1,283 @@
use crate::{
generic_aggregate_public_key::TAggregatePublicKey,
generic_public_key::{GenericPublicKey, TPublicKey},
generic_signature::{GenericSignature, TSignature},
Error, Hash256, INFINITY_SIGNATURE, SIGNATURE_BYTES_LEN,
};
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use serde_hex::{encode as hex_encode, PrefixedHexVisitor};
use ssz::{Decode, Encode};
use std::fmt;
use std::marker::PhantomData;
use tree_hash::TreeHash;
/// The compressed bytes used to represent `GenericAggregateSignature::empty()`.
pub const EMPTY_SIGNATURE_SERIALIZATION: [u8; SIGNATURE_BYTES_LEN] = [0; SIGNATURE_BYTES_LEN];
/// Implemented on some struct from a BLS library so it may be used as the `point` in an
/// `GenericAggregateSignature`.
pub trait TAggregateSignature<Pub, AggPub, Sig>: Sized + Clone {
/// Initialize `Self` to the infinity value which can then have other signatures aggregated
/// upon it.
fn infinity() -> Self;
/// Aggregates a signature onto `self`.
fn add_assign(&mut self, other: &Sig);
/// Aggregates an aggregate signature onto `self`.
fn add_assign_aggregate(&mut self, other: &Self);
/// Serialize `self` as compressed bytes.
fn serialize(&self) -> [u8; SIGNATURE_BYTES_LEN];
/// Deserialize `self` from compressed bytes.
fn deserialize(bytes: &[u8]) -> Result<Self, Error>;
/// Verify that `self` represents an aggregate signature where all `pubkeys` have signed `msg`.
fn fast_aggregate_verify(&self, msg: Hash256, pubkeys: &[&GenericPublicKey<Pub>]) -> bool;
/// Verify that `self` represents an aggregate signature where all `pubkeys` have signed their
/// corresponding message in `msgs`.
///
/// ## Notes
///
/// This function only exists for EF tests, it's presently not used in production.
fn aggregate_verify(&self, msgs: &[Hash256], pubkeys: &[&GenericPublicKey<Pub>]) -> bool;
}
/// A BLS aggregate signature that is generic across:
///
/// - `Pub`: A BLS public key.
/// - `AggPub`: A BLS aggregate public key.
/// - `Sig`: A BLS signature.
/// - `AggSig`: A BLS aggregate signature.
///
/// Provides generic functionality whilst deferring all serious cryptographic operations to the
/// generics.
#[derive(Clone, PartialEq)]
pub struct GenericAggregateSignature<Pub, AggPub, Sig, AggSig> {
/// The underlying point which performs *actual* cryptographic operations.
point: Option<AggSig>,
/// True if this point is equal to the `INFINITY_SIGNATURE`.
pub(crate) is_infinity: bool,
_phantom_pub: PhantomData<Pub>,
_phantom_agg_pub: PhantomData<AggPub>,
_phantom_sig: PhantomData<Sig>,
}
impl<Pub, AggPub, Sig, AggSig> GenericAggregateSignature<Pub, AggPub, Sig, AggSig>
where
Sig: TSignature<Pub>,
AggSig: TAggregateSignature<Pub, AggPub, Sig>,
{
/// Initialize `Self` to the infinity value which can then have other signatures aggregated
/// upon it.
pub fn infinity() -> Self {
Self {
point: Some(AggSig::infinity()),
is_infinity: true,
_phantom_pub: PhantomData,
_phantom_agg_pub: PhantomData,
_phantom_sig: PhantomData,
}
}
/// Initialize self to the "empty" value. This value is serialized as all-zeros.
///
/// This value can have another signature aggregated atop of it. When this happens, `self` is
/// simply set to infinity before having the other signature aggregated onto it.
///
/// ## Notes
///
/// This function is not necessarily useful from a BLS cryptography perspective, it mostly
/// exists to satisfy the Eth2 specification which expects the all-zeros serialization to be
/// meaningful.
pub fn empty() -> Self {
Self {
point: None,
is_infinity: false,
_phantom_pub: PhantomData,
_phantom_agg_pub: PhantomData,
_phantom_sig: PhantomData,
}
}
/// Returns `true` if `self` is equal to the "empty" value.
///
/// E.g., `Self::empty().is_empty() == true`
pub fn is_empty(&self) -> bool {
self.point.is_none()
}
/// Returns a reference to the underlying BLS point.
pub(crate) fn point(&self) -> Option<&AggSig> {
self.point.as_ref()
}
/// Aggregates a signature onto `self`.
pub fn add_assign(&mut self, other: &GenericSignature<Pub, Sig>) {
if let Some(other_point) = other.point() {
self.is_infinity = self.is_infinity && other.is_infinity;
if let Some(self_point) = &mut self.point {
self_point.add_assign(other_point)
} else {
let mut self_point = AggSig::infinity();
self_point.add_assign(other_point);
self.point = Some(self_point)
}
}
}
/// Aggregates an aggregate signature onto `self`.
pub fn add_assign_aggregate(&mut self, other: &Self) {
if let Some(other_point) = other.point() {
self.is_infinity = self.is_infinity && other.is_infinity;
if let Some(self_point) = &mut self.point {
self_point.add_assign_aggregate(other_point)
} else {
let mut self_point = AggSig::infinity();
self_point.add_assign_aggregate(other_point);
self.point = Some(self_point)
}
}
}
/// Serialize `self` as compressed bytes.
pub fn serialize(&self) -> [u8; SIGNATURE_BYTES_LEN] {
if let Some(point) = &self.point {
point.serialize()
} else {
EMPTY_SIGNATURE_SERIALIZATION
}
}
/// Deserialize `self` from compressed bytes.
pub fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
let point = if bytes == &EMPTY_SIGNATURE_SERIALIZATION[..] {
None
} else {
Some(AggSig::deserialize(bytes)?)
};
Ok(Self {
point,
is_infinity: bytes == &INFINITY_SIGNATURE[..],
_phantom_pub: PhantomData,
_phantom_agg_pub: PhantomData,
_phantom_sig: PhantomData,
})
}
}
impl<Pub, AggPub, Sig, AggSig> GenericAggregateSignature<Pub, AggPub, Sig, AggSig>
where
Pub: TPublicKey + Clone,
AggPub: TAggregatePublicKey + Clone,
Sig: TSignature<Pub>,
AggSig: TAggregateSignature<Pub, AggPub, Sig>,
{
/// Verify that `self` represents an aggregate signature where all `pubkeys` have signed `msg`.
pub fn fast_aggregate_verify(&self, msg: Hash256, pubkeys: &[&GenericPublicKey<Pub>]) -> bool {
if pubkeys.is_empty() {
return false;
}
if self.is_infinity
&& pubkeys.len() == 1
&& pubkeys.first().map_or(false, |pk| pk.is_infinity)
{
return true;
}
match self.point.as_ref() {
Some(point) => point.fast_aggregate_verify(msg, pubkeys),
None => false,
}
}
/// Verify that `self` represents an aggregate signature where all `pubkeys` have signed their
/// corresponding message in `msgs`.
///
/// ## Notes
///
/// This function only exists for EF tests, it's presently not used in production.
pub fn aggregate_verify(&self, msgs: &[Hash256], pubkeys: &[&GenericPublicKey<Pub>]) -> bool {
if msgs.is_empty() || msgs.len() != pubkeys.len() {
return false;
}
if self.is_infinity
&& pubkeys.len() == 1
&& pubkeys.first().map_or(false, |pk| pk.is_infinity)
{
return true;
}
match self.point.as_ref() {
Some(point) => point.aggregate_verify(msgs, pubkeys),
None => false,
}
}
}
impl<Pub, AggPub, Sig, AggSig> Encode for GenericAggregateSignature<Pub, AggPub, Sig, AggSig>
where
Sig: TSignature<Pub>,
AggSig: TAggregateSignature<Pub, AggPub, Sig>,
{
impl_ssz_encode!(SIGNATURE_BYTES_LEN);
}
impl<Pub, AggPub, Sig, AggSig> Decode for GenericAggregateSignature<Pub, AggPub, Sig, AggSig>
where
Sig: TSignature<Pub>,
AggSig: TAggregateSignature<Pub, AggPub, Sig>,
{
impl_ssz_decode!(SIGNATURE_BYTES_LEN);
}
impl<Pub, AggPub, Sig, AggSig> TreeHash for GenericAggregateSignature<Pub, AggPub, Sig, AggSig>
where
Sig: TSignature<Pub>,
AggSig: TAggregateSignature<Pub, AggPub, Sig>,
{
impl_tree_hash!(SIGNATURE_BYTES_LEN);
}
impl<Pub, AggPub, Sig, AggSig> Serialize for GenericAggregateSignature<Pub, AggPub, Sig, AggSig>
where
Sig: TSignature<Pub>,
AggSig: TAggregateSignature<Pub, AggPub, Sig>,
{
impl_serde_serialize!();
}
impl<'de, Pub, AggPub, Sig, AggSig> Deserialize<'de>
for GenericAggregateSignature<Pub, AggPub, Sig, AggSig>
where
Sig: TSignature<Pub>,
AggSig: TAggregateSignature<Pub, AggPub, Sig>,
{
impl_serde_deserialize!();
}
impl<Pub, AggPub, Sig, AggSig> fmt::Debug for GenericAggregateSignature<Pub, AggPub, Sig, AggSig>
where
Sig: TSignature<Pub>,
AggSig: TAggregateSignature<Pub, AggPub, Sig>,
{
impl_debug!();
}
#[cfg(feature = "arbitrary")]
impl<Pub, AggPub, Sig, AggSig> arbitrary::Arbitrary
for GenericAggregateSignature<Pub, AggPub, Sig, AggSig>
where
Pub: 'static,
AggPub: 'static,
Sig: TSignature<Pub> + 'static,
AggSig: TAggregateSignature<Pub, AggPub, Sig> + 'static,
{
impl_arbitrary!(SIGNATURE_BYTES_LEN);
}

View File

@@ -0,0 +1,54 @@
use crate::{
generic_public_key::{GenericPublicKey, TPublicKey},
generic_secret_key::{GenericSecretKey, TSecretKey},
generic_signature::TSignature,
};
use std::fmt;
use std::marker::PhantomData;
/// A simple wrapper around `PublicKey` and `GenericSecretKey`.
#[derive(Clone)]
pub struct GenericKeypair<Pub, Sec, Sig> {
pub pk: GenericPublicKey<Pub>,
pub sk: GenericSecretKey<Sig, Pub, Sec>,
_phantom: PhantomData<Sig>,
}
impl<Pub, Sec, Sig> GenericKeypair<Pub, Sec, Sig>
where
Pub: TPublicKey,
Sec: TSecretKey<Sig, Pub>,
Sig: TSignature<Pub>,
{
/// Instantiate `Self` from a public and secret key.
///
/// This function does not check to ensure that `pk` is derived from `sk`. It would be a logic
/// error to supply such a `pk`.
pub fn from_components(pk: GenericPublicKey<Pub>, sk: GenericSecretKey<Sig, Pub, Sec>) -> Self {
Self {
pk,
sk,
_phantom: PhantomData,
}
}
/// Instantiates `Self` from a randomly generated secret key.
pub fn random() -> Self {
let sk = GenericSecretKey::random();
Self {
pk: sk.public_key(),
sk,
_phantom: PhantomData,
}
}
}
impl<Pub, Sec, Sig> fmt::Debug for GenericKeypair<Pub, Sec, Sig>
where
Pub: TPublicKey,
{
/// Defers to `self.pk` to avoid leaking the secret key.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.pk.fmt(f)
}
}

View File

@@ -0,0 +1,115 @@
use crate::Error;
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use serde_hex::{encode as hex_encode, PrefixedHexVisitor};
use ssz::{Decode, Encode};
use std::fmt;
use std::hash::{Hash, Hasher};
use tree_hash::TreeHash;
/// The byte-length of a BLS public key when serialized in compressed form.
pub const PUBLIC_KEY_BYTES_LEN: usize = 48;
/// Represents the public key at infinity.
pub const INFINITY_PUBLIC_KEY: [u8; PUBLIC_KEY_BYTES_LEN] = [
0xc0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
/// Implemented on some struct from a BLS library so it may be used as the `point` in a
/// `GenericPublicKey`.
pub trait TPublicKey: Sized + Clone {
/// Serialize `self` as compressed bytes.
fn serialize(&self) -> [u8; PUBLIC_KEY_BYTES_LEN];
/// Deserialize `self` from compressed bytes.
fn deserialize(bytes: &[u8]) -> Result<Self, Error>;
}
/// A BLS aggregate public key that is generic across some BLS point (`Pub`).
///
/// Provides generic functionality whilst deferring all serious cryptographic operations to `Pub`.
#[derive(Clone)]
pub struct GenericPublicKey<Pub> {
/// The underlying point which performs *actual* cryptographic operations.
point: Pub,
/// True if this point is equal to the `INFINITY_PUBLIC_KEY`.
pub(crate) is_infinity: bool,
}
impl<Pub> GenericPublicKey<Pub>
where
Pub: TPublicKey,
{
/// Instantiates `Self` from a `point`.
pub(crate) fn from_point(point: Pub, is_infinity: bool) -> Self {
Self { point, is_infinity }
}
/// Returns a reference to the underlying BLS point.
pub(crate) fn point(&self) -> &Pub {
&self.point
}
/// Returns `self.serialize()` as a `0x`-prefixed hex string.
pub fn to_hex_string(&self) -> String {
format!("{:?}", self)
}
/// Serialize `self` as compressed bytes.
pub fn serialize(&self) -> [u8; PUBLIC_KEY_BYTES_LEN] {
self.point.serialize()
}
/// Deserialize `self` from compressed bytes.
pub fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
Ok(Self {
point: Pub::deserialize(bytes)?,
is_infinity: bytes == &INFINITY_PUBLIC_KEY[..],
})
}
}
impl<Pub: TPublicKey> Eq for GenericPublicKey<Pub> {}
impl<Pub: TPublicKey> PartialEq for GenericPublicKey<Pub> {
fn eq(&self, other: &Self) -> bool {
self.serialize()[..] == other.serialize()[..]
}
}
/// Hashes the `self.serialize()` bytes.
impl<Pub: TPublicKey> Hash for GenericPublicKey<Pub> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.serialize()[..].hash(state);
}
}
impl<Pub: TPublicKey> Encode for GenericPublicKey<Pub> {
impl_ssz_encode!(PUBLIC_KEY_BYTES_LEN);
}
impl<Pub: TPublicKey> Decode for GenericPublicKey<Pub> {
impl_ssz_decode!(PUBLIC_KEY_BYTES_LEN);
}
impl<Pub: TPublicKey> TreeHash for GenericPublicKey<Pub> {
impl_tree_hash!(PUBLIC_KEY_BYTES_LEN);
}
impl<Pub: TPublicKey> Serialize for GenericPublicKey<Pub> {
impl_serde_serialize!();
}
impl<'de, Pub: TPublicKey> Deserialize<'de> for GenericPublicKey<Pub> {
impl_serde_deserialize!();
}
impl<Pub: TPublicKey> fmt::Debug for GenericPublicKey<Pub> {
impl_debug!();
}
#[cfg(feature = "arbitrary")]
impl<Pub: TPublicKey + 'static> arbitrary::Arbitrary for GenericPublicKey<Pub> {
impl_arbitrary!(PUBLIC_KEY_BYTES_LEN);
}

View File

@@ -0,0 +1,150 @@
use crate::{
generic_public_key::{GenericPublicKey, TPublicKey},
Error, INFINITY_PUBLIC_KEY, PUBLIC_KEY_BYTES_LEN,
};
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use serde_hex::{encode as hex_encode, PrefixedHexVisitor};
use ssz::{Decode, Encode};
use std::convert::TryInto;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use tree_hash::TreeHash;
/// A wrapper around some bytes that may or may not be a `PublicKey` in compressed form.
///
/// This struct is useful for two things:
///
/// - Lazily verifying a serialized public key.
/// - Storing some bytes that are actually invalid (required in the case of a `Deposit` message).
#[derive(Clone)]
pub struct GenericPublicKeyBytes<Pub> {
bytes: [u8; PUBLIC_KEY_BYTES_LEN],
_phantom: PhantomData<Pub>,
}
impl<Pub> GenericPublicKeyBytes<Pub>
where
Pub: TPublicKey,
{
/// Decompress and deserialize the bytes in `self` into an actual public key.
///
/// May fail if the bytes are invalid.
pub fn decompress(&self) -> Result<GenericPublicKey<Pub>, Error> {
let is_infinity = self.bytes[..] == INFINITY_PUBLIC_KEY[..];
Pub::deserialize(&self.bytes).map(|point| GenericPublicKey::from_point(point, is_infinity))
}
}
impl<Pub> GenericPublicKeyBytes<Pub> {
/// Instantiates `Self` with all-zeros.
pub fn empty() -> Self {
Self {
bytes: [0; PUBLIC_KEY_BYTES_LEN],
_phantom: PhantomData,
}
}
/// Returns a slice of the bytes contained in `self`.
///
/// The bytes are not verified (i.e., they may not represent a valid BLS point).
pub fn as_serialized(&self) -> &[u8] {
&self.bytes
}
/// Clones the bytes in `self`.
///
/// The bytes are not verified (i.e., they may not represent a valid BLS point).
pub fn serialize(&self) -> [u8; PUBLIC_KEY_BYTES_LEN] {
self.bytes
}
/// Instantiates `Self` from bytes.
///
/// The bytes are not fully verified (i.e., they may not represent a valid BLS point). Only the
/// byte-length is checked.
pub fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
if bytes.len() == PUBLIC_KEY_BYTES_LEN {
let mut pk_bytes = [0; PUBLIC_KEY_BYTES_LEN];
pk_bytes[..].copy_from_slice(bytes);
Ok(Self {
bytes: pk_bytes,
_phantom: PhantomData,
})
} else {
Err(Error::InvalidByteLength {
got: bytes.len(),
expected: PUBLIC_KEY_BYTES_LEN,
})
}
}
}
impl<Pub> Eq for GenericPublicKeyBytes<Pub> {}
impl<Pub> PartialEq for GenericPublicKeyBytes<Pub> {
fn eq(&self, other: &Self) -> bool {
self.bytes[..] == other.bytes[..]
}
}
impl<Pub> Hash for GenericPublicKeyBytes<Pub> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.bytes[..].hash(state);
}
}
/// Serializes the `PublicKey` in compressed form, storing the bytes in the newly created `Self`.
impl<Pub> From<GenericPublicKey<Pub>> for GenericPublicKeyBytes<Pub>
where
Pub: TPublicKey,
{
fn from(pk: GenericPublicKey<Pub>) -> Self {
Self {
bytes: pk.serialize(),
_phantom: PhantomData,
}
}
}
/// Alias to `self.decompress()`.
impl<Pub> TryInto<GenericPublicKey<Pub>> for &GenericPublicKeyBytes<Pub>
where
Pub: TPublicKey,
{
type Error = Error;
fn try_into(self) -> Result<GenericPublicKey<Pub>, Self::Error> {
self.decompress()
}
}
impl<Pub> Encode for GenericPublicKeyBytes<Pub> {
impl_ssz_encode!(PUBLIC_KEY_BYTES_LEN);
}
impl<Pub> Decode for GenericPublicKeyBytes<Pub> {
impl_ssz_decode!(PUBLIC_KEY_BYTES_LEN);
}
impl<Pub> TreeHash for GenericPublicKeyBytes<Pub> {
impl_tree_hash!(PUBLIC_KEY_BYTES_LEN);
}
impl<Pub> Serialize for GenericPublicKeyBytes<Pub> {
impl_serde_serialize!();
}
impl<'de, Pub> Deserialize<'de> for GenericPublicKeyBytes<Pub> {
impl_serde_deserialize!();
}
impl<Pub> fmt::Debug for GenericPublicKeyBytes<Pub> {
impl_debug!();
}
#[cfg(feature = "arbitrary")]
impl<Pub: 'static> arbitrary::Arbitrary for GenericPublicKeyBytes<Pub> {
impl_arbitrary!(PUBLIC_KEY_BYTES_LEN);
}

View File

@@ -0,0 +1,90 @@
use crate::{
generic_public_key::{GenericPublicKey, TPublicKey},
generic_signature::{GenericSignature, TSignature},
Error, Hash256, ZeroizeHash,
};
use std::marker::PhantomData;
/// The byte-length of a BLS secret key.
pub const SECRET_KEY_BYTES_LEN: usize = 32;
/// Implemented on some struct from a BLS library so it may be used as the `point` in a
/// `GenericSecretKey`.
pub trait TSecretKey<SignaturePoint, PublicKeyPoint>: Sized {
/// Instantiate `Self` from some secure source of entropy.
fn random() -> Self;
/// Signs `msg`.
fn sign(&self, msg: Hash256) -> SignaturePoint;
/// Returns the public key that corresponds to self.
fn public_key(&self) -> PublicKeyPoint;
/// Serialize `self` as compressed bytes.
fn serialize(&self) -> ZeroizeHash;
/// Deserialize `self` from compressed bytes.
fn deserialize(bytes: &[u8]) -> Result<Self, Error>;
}
#[derive(Clone)]
pub struct GenericSecretKey<Sig, Pub, Sec> {
/// The underlying point which performs *actual* cryptographic operations.
point: Sec,
_phantom_signature: PhantomData<Sig>,
_phantom_public_key: PhantomData<Pub>,
}
impl<Sig, Pub, Sec> GenericSecretKey<Sig, Pub, Sec>
where
Sig: TSignature<Pub>,
Pub: TPublicKey,
Sec: TSecretKey<Sig, Pub>,
{
/// Instantiate `Self` from some secure source of entropy.
pub fn random() -> Self {
Self {
point: Sec::random(),
_phantom_signature: PhantomData,
_phantom_public_key: PhantomData,
}
}
/// Signs `msg`.
pub fn sign(&self, msg: Hash256) -> GenericSignature<Pub, Sig> {
let is_infinity = false;
GenericSignature::from_point(self.point.sign(msg), is_infinity)
}
/// Returns the public key that corresponds to self.
pub fn public_key(&self) -> GenericPublicKey<Pub> {
let is_infinity = false;
GenericPublicKey::from_point(self.point.public_key(), is_infinity)
}
/// Serialize `self` as compressed bytes.
///
/// ## Note
///
/// The bytes that are returned are the unencrypted secret key. This is sensitive cryptographic
/// material.
pub fn serialize(&self) -> ZeroizeHash {
self.point.serialize()
}
/// Deserialize `self` from compressed bytes.
pub fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
if bytes.len() != SECRET_KEY_BYTES_LEN {
Err(Error::InvalidSecretKeyLength {
got: bytes.len(),
expected: SECRET_KEY_BYTES_LEN,
})
} else {
Ok(Self {
point: Sec::deserialize(bytes)?,
_phantom_signature: PhantomData,
_phantom_public_key: PhantomData,
})
}
}
}

View File

@@ -0,0 +1,169 @@
use crate::{
generic_public_key::{GenericPublicKey, TPublicKey},
Error, Hash256,
};
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use serde_hex::{encode as hex_encode, PrefixedHexVisitor};
use ssz::{Decode, Encode};
use std::fmt;
use std::marker::PhantomData;
use tree_hash::TreeHash;
/// The byte-length of a BLS signature when serialized in compressed form.
pub const SIGNATURE_BYTES_LEN: usize = 96;
/// Represents the signature at infinity.
pub const INFINITY_SIGNATURE: [u8; SIGNATURE_BYTES_LEN] = [
0xc0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0,
];
/// The compressed bytes used to represent `GenericSignature::empty()`.
pub const NONE_SIGNATURE: [u8; SIGNATURE_BYTES_LEN] = [0; SIGNATURE_BYTES_LEN];
/// Implemented on some struct from a BLS library so it may be used as the `point` in an
/// `GenericSignature`.
pub trait TSignature<GenericPublicKey>: Sized + Clone {
/// Serialize `self` as compressed bytes.
fn serialize(&self) -> [u8; SIGNATURE_BYTES_LEN];
/// Deserialize `self` from compressed bytes.
fn deserialize(bytes: &[u8]) -> Result<Self, Error>;
/// Returns `true` if `self` is a signature across `msg` by `pubkey`.
fn verify(&self, pubkey: &GenericPublicKey, msg: Hash256) -> bool;
}
/// A BLS signature that is generic across:
///
/// - `Pub`: A BLS public key.
/// - `Sig`: A BLS signature.
///
/// Provides generic functionality whilst deferring all serious cryptographic operations to the
/// generics.
#[derive(Clone, PartialEq)]
pub struct GenericSignature<Pub, Sig> {
/// The underlying point which performs *actual* cryptographic operations.
point: Option<Sig>,
/// True if this point is equal to the `INFINITY_SIGNATURE`.
pub(crate) is_infinity: bool,
_phantom: PhantomData<Pub>,
}
impl<Pub, Sig> GenericSignature<Pub, Sig>
where
Sig: TSignature<Pub>,
{
/// Initialize self to the "empty" value. This value is serialized as all-zeros.
///
/// ## Notes
///
/// This function is not necessarily useful from a BLS cryptography perspective, it mostly
/// exists to satisfy the Eth2 specification which expects the all-zeros serialization to be
/// meaningful.
pub fn empty() -> Self {
Self {
point: None,
is_infinity: false,
_phantom: PhantomData,
}
}
/// Returns `true` if `self` is equal to the "empty" value.
///
/// E.g., `Self::empty().is_empty() == true`
pub fn is_empty(&self) -> bool {
self.point.is_none()
}
/// Returns a reference to the underlying BLS point.
pub(crate) fn point(&self) -> Option<&Sig> {
self.point.as_ref()
}
/// Instantiates `Self` from a `point`.
pub(crate) fn from_point(point: Sig, is_infinity: bool) -> Self {
Self {
point: Some(point),
is_infinity,
_phantom: PhantomData,
}
}
/// Serialize `self` as compressed bytes.
pub fn serialize(&self) -> [u8; SIGNATURE_BYTES_LEN] {
if let Some(point) = &self.point {
point.serialize()
} else {
NONE_SIGNATURE
}
}
/// Deserialize `self` from compressed bytes.
pub fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
let point = if bytes == &NONE_SIGNATURE[..] {
None
} else {
Some(Sig::deserialize(bytes)?)
};
Ok(Self {
point,
is_infinity: bytes == &INFINITY_SIGNATURE[..],
_phantom: PhantomData,
})
}
}
impl<Pub, Sig> GenericSignature<Pub, Sig>
where
Sig: TSignature<Pub>,
Pub: TPublicKey + Clone,
{
/// Returns `true` if `self` is a signature across `msg` by `pubkey`.
pub fn verify(&self, pubkey: &GenericPublicKey<Pub>, msg: Hash256) -> bool {
if self.is_infinity && pubkey.is_infinity {
return true;
}
if let Some(point) = &self.point {
point.verify(pubkey.point(), msg)
} else {
false
}
}
}
impl<PublicKey, T: TSignature<PublicKey>> Encode for GenericSignature<PublicKey, T> {
impl_ssz_encode!(SIGNATURE_BYTES_LEN);
}
impl<PublicKey, T: TSignature<PublicKey>> Decode for GenericSignature<PublicKey, T> {
impl_ssz_decode!(SIGNATURE_BYTES_LEN);
}
impl<PublicKey, T: TSignature<PublicKey>> TreeHash for GenericSignature<PublicKey, T> {
impl_tree_hash!(SIGNATURE_BYTES_LEN);
}
impl<PublicKey, T: TSignature<PublicKey>> Serialize for GenericSignature<PublicKey, T> {
impl_serde_serialize!();
}
impl<'de, PublicKey, T: TSignature<PublicKey>> Deserialize<'de> for GenericSignature<PublicKey, T> {
impl_serde_deserialize!();
}
impl<PublicKey, T: TSignature<PublicKey>> fmt::Debug for GenericSignature<PublicKey, T> {
impl_debug!();
}
#[cfg(feature = "arbitrary")]
impl<PublicKey: 'static, T: TSignature<PublicKey> + 'static> arbitrary::Arbitrary
for GenericSignature<PublicKey, T>
{
impl_arbitrary!(SIGNATURE_BYTES_LEN);
}

View File

@@ -0,0 +1,142 @@
use crate::{
generic_public_key::TPublicKey,
generic_signature::{GenericSignature, TSignature},
Error, INFINITY_SIGNATURE, SIGNATURE_BYTES_LEN,
};
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use serde_hex::{encode as hex_encode, PrefixedHexVisitor};
use ssz::{Decode, Encode};
use std::convert::TryInto;
use std::fmt;
use std::marker::PhantomData;
use tree_hash::TreeHash;
/// A wrapper around some bytes that may or may not be a `GenericSignature` in compressed form.
///
/// This struct is useful for two things:
///
/// - Lazily verifying a serialized signature.
/// - Storing some bytes that are actually invalid (required in the case of a `Deposit` message).
#[derive(Clone)]
pub struct GenericSignatureBytes<Pub, Sig> {
bytes: [u8; SIGNATURE_BYTES_LEN],
_phantom_public_key: PhantomData<Pub>,
_phantom_signature: PhantomData<Sig>,
}
impl<Pub, Sig> GenericSignatureBytes<Pub, Sig>
where
Sig: TSignature<Pub>,
Pub: TPublicKey,
{
/// Decompress and deserialize the bytes in `self` into an actual signature.
///
/// May fail if the bytes are invalid.
pub fn decompress(&self) -> Result<GenericSignature<Pub, Sig>, Error> {
let is_infinity = self.bytes[..] == INFINITY_SIGNATURE[..];
Sig::deserialize(&self.bytes).map(|point| GenericSignature::from_point(point, is_infinity))
}
}
impl<Pub, Sig> GenericSignatureBytes<Pub, Sig> {
/// Instantiates `Self` with all-zeros.
pub fn empty() -> Self {
Self {
bytes: [0; SIGNATURE_BYTES_LEN],
_phantom_signature: PhantomData,
_phantom_public_key: PhantomData,
}
}
/// Clones the bytes in `self`.
///
/// The bytes are not verified (i.e., they may not represent a valid BLS point).
pub fn serialize(&self) -> [u8; SIGNATURE_BYTES_LEN] {
self.bytes
}
/// Instantiates `Self` from bytes.
///
/// The bytes are not fully verified (i.e., they may not represent a valid BLS point). Only the
/// byte-length is checked.
pub fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
if bytes.len() == SIGNATURE_BYTES_LEN {
let mut pk_bytes = [0; SIGNATURE_BYTES_LEN];
pk_bytes[..].copy_from_slice(bytes);
Ok(Self {
bytes: pk_bytes,
_phantom_signature: PhantomData,
_phantom_public_key: PhantomData,
})
} else {
Err(Error::InvalidByteLength {
got: bytes.len(),
expected: SIGNATURE_BYTES_LEN,
})
}
}
}
impl<Pub, Sig> PartialEq for GenericSignatureBytes<Pub, Sig> {
fn eq(&self, other: &Self) -> bool {
self.bytes[..] == other.bytes[..]
}
}
/// Serializes the `GenericSignature` in compressed form, storing the bytes in the newly created `Self`.
impl<Pub, Sig> From<GenericSignature<Pub, Sig>> for GenericSignatureBytes<Pub, Sig>
where
Pub: TPublicKey,
Sig: TSignature<Pub>,
{
fn from(sig: GenericSignature<Pub, Sig>) -> Self {
Self {
bytes: sig.serialize(),
_phantom_signature: PhantomData,
_phantom_public_key: PhantomData,
}
}
}
/// Alias to `self.decompress()`.
impl<Pub, Sig> TryInto<GenericSignature<Pub, Sig>> for &GenericSignatureBytes<Pub, Sig>
where
Pub: TPublicKey,
Sig: TSignature<Pub>,
{
type Error = Error;
fn try_into(self) -> Result<GenericSignature<Pub, Sig>, Error> {
self.decompress()
}
}
impl<Pub, Sig> Encode for GenericSignatureBytes<Pub, Sig> {
impl_ssz_encode!(SIGNATURE_BYTES_LEN);
}
impl<Pub, Sig> Decode for GenericSignatureBytes<Pub, Sig> {
impl_ssz_decode!(SIGNATURE_BYTES_LEN);
}
impl<Pub, Sig> TreeHash for GenericSignatureBytes<Pub, Sig> {
impl_tree_hash!(SIGNATURE_BYTES_LEN);
}
impl<Pub, Sig> Serialize for GenericSignatureBytes<Pub, Sig> {
impl_serde_serialize!();
}
impl<'de, Pub, Sig> Deserialize<'de> for GenericSignatureBytes<Pub, Sig> {
impl_serde_deserialize!();
}
impl<Pub, Sig> fmt::Debug for GenericSignatureBytes<Pub, Sig> {
impl_debug!();
}
#[cfg(feature = "arbitrary")]
impl<Pub: 'static, Sig: 'static> arbitrary::Arbitrary for GenericSignatureBytes<Pub, Sig> {
impl_arbitrary!(SIGNATURE_BYTES_LEN);
}

View File

@@ -0,0 +1,121 @@
use crate::{
generic_aggregate_public_key::TAggregatePublicKey,
generic_aggregate_signature::{GenericAggregateSignature, TAggregateSignature},
generic_public_key::{GenericPublicKey, TPublicKey},
generic_signature::{GenericSignature, TSignature},
Hash256,
};
use std::borrow::Cow;
use std::marker::PhantomData;
/// A generic way to represent a `GenericSignature` or `GenericAggregateSignature`.
pub struct WrappedSignature<'a, Pub, AggPub, Sig, AggSig>
where
Pub: TPublicKey + Clone,
AggPub: Clone,
Sig: Clone,
AggSig: Clone,
{
aggregate: Cow<'a, GenericAggregateSignature<Pub, AggPub, Sig, AggSig>>,
}
impl<'a, Pub, AggPub, Sig, AggSig> Into<WrappedSignature<'a, Pub, AggPub, Sig, AggSig>>
for &'a GenericSignature<Pub, Sig>
where
Pub: TPublicKey + Clone,
AggPub: Clone,
Sig: TSignature<Pub> + Clone,
AggSig: TAggregateSignature<Pub, AggPub, Sig> + Clone,
{
fn into(self) -> WrappedSignature<'a, Pub, AggPub, Sig, AggSig> {
let mut aggregate: GenericAggregateSignature<Pub, AggPub, Sig, AggSig> =
GenericAggregateSignature::infinity();
aggregate.add_assign(self);
WrappedSignature {
aggregate: Cow::Owned(aggregate),
}
}
}
impl<'a, Pub, AggPub, Sig, AggSig> Into<WrappedSignature<'a, Pub, AggPub, Sig, AggSig>>
for &'a GenericAggregateSignature<Pub, AggPub, Sig, AggSig>
where
Pub: TPublicKey + Clone,
AggPub: Clone,
Sig: Clone,
AggSig: Clone,
{
fn into(self) -> WrappedSignature<'a, Pub, AggPub, Sig, AggSig> {
WrappedSignature {
aggregate: Cow::Borrowed(self),
}
}
}
/// A generic way to represent a signature across a message by multiple public keys.
///
/// This struct is primarily useful in a collection (e.g., `Vec<GenericSignatureSet>`) so we can perform
/// multiple-signature verification which is much faster than verifying each signature
/// individually.
#[derive(Clone)]
pub struct GenericSignatureSet<'a, Pub, AggPub, Sig, AggSig>
where
Pub: TPublicKey + Clone,
AggPub: Clone,
Sig: Clone,
AggSig: Clone,
{
pub signature: Cow<'a, GenericAggregateSignature<Pub, AggPub, Sig, AggSig>>,
pub(crate) signing_keys: Vec<Cow<'a, GenericPublicKey<Pub>>>,
pub(crate) message: Hash256,
_phantom: PhantomData<Sig>,
}
impl<'a, Pub, AggPub, Sig, AggSig> GenericSignatureSet<'a, Pub, AggPub, Sig, AggSig>
where
Pub: TPublicKey + Clone,
AggPub: TAggregatePublicKey + Clone,
Sig: TSignature<Pub> + Clone,
AggSig: TAggregateSignature<Pub, AggPub, Sig> + Clone,
{
/// Instantiate self where `signature` is only signed by a single public key.
pub fn single_pubkey(
signature: impl Into<WrappedSignature<'a, Pub, AggPub, Sig, AggSig>>,
signing_key: Cow<'a, GenericPublicKey<Pub>>,
message: Hash256,
) -> Self {
Self {
signature: signature.into().aggregate,
signing_keys: vec![signing_key],
message,
_phantom: PhantomData,
}
}
/// Instantiate self where `signature` is signed by multiple public keys.
pub fn multiple_pubkeys(
signature: impl Into<WrappedSignature<'a, Pub, AggPub, Sig, AggSig>>,
signing_keys: Vec<Cow<'a, GenericPublicKey<Pub>>>,
message: Hash256,
) -> Self {
Self {
signature: signature.into().aggregate,
signing_keys,
message,
_phantom: PhantomData,
}
}
/// Returns `true` if `self.signature` is a signature across `self.message` by
/// `self.signing_keys`.
pub fn verify(self) -> bool {
let pubkeys = self
.signing_keys
.iter()
.map(|pk| pk.as_ref())
.collect::<Vec<_>>();
self.signature
.fast_aggregate_verify(self.message, &pubkeys[..])
}
}

View File

@@ -0,0 +1,14 @@
use crate::PublicKey;
use eth2_hashing::hash;
use ssz::Encode;
/// Returns the withdrawal credentials for a given public key.
///
/// Used for submitting deposits to the Eth1 deposit contract.
pub fn get_withdrawal_credentials(pubkey: &PublicKey, prefix_byte: u8) -> Vec<u8> {
let hashed = hash(&pubkey.as_ssz_bytes());
let mut prefixed = vec![prefix_byte];
prefixed.extend_from_slice(&hashed[1..]);
prefixed
}

View File

@@ -0,0 +1,273 @@
use crate::{
generic_aggregate_public_key::TAggregatePublicKey,
generic_aggregate_signature::TAggregateSignature,
generic_public_key::{GenericPublicKey, TPublicKey, PUBLIC_KEY_BYTES_LEN},
generic_secret_key::TSecretKey,
generic_signature::{TSignature, SIGNATURE_BYTES_LEN},
Error, Hash256, ZeroizeHash, INFINITY_PUBLIC_KEY, INFINITY_SIGNATURE,
};
pub use blst::min_pk as blst_core;
use blst::{blst_scalar, BLST_ERROR};
use rand::Rng;
use std::iter::ExactSizeIterator;
pub const DST: &[u8] = b"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_";
pub const RAND_BITS: usize = 64;
/// Provides the externally-facing, core BLS types.
pub mod types {
pub use super::blst_core::PublicKey;
pub use super::blst_core::SecretKey;
pub use super::blst_core::Signature;
pub use super::verify_signature_sets;
pub use super::BlstAggregatePublicKey as AggregatePublicKey;
pub use super::BlstAggregateSignature as AggregateSignature;
pub use super::SignatureSet;
}
pub type SignatureSet<'a> = crate::generic_signature_set::GenericSignatureSet<
'a,
blst_core::PublicKey,
BlstAggregatePublicKey,
blst_core::Signature,
BlstAggregateSignature,
>;
pub fn verify_signature_sets<'a>(
signature_sets: impl ExactSizeIterator<Item = &'a SignatureSet<'a>>,
) -> bool {
let sets = signature_sets.collect::<Vec<_>>();
if sets.is_empty() {
return false;
}
let rng = &mut rand::thread_rng();
let mut rands: Vec<blst_scalar> = Vec::with_capacity(sets.len());
let mut msgs_refs = Vec::with_capacity(sets.len());
let mut sigs = Vec::with_capacity(sets.len());
let mut pks = Vec::with_capacity(sets.len());
for set in &sets {
// If this set is simply an infinity signature and infinity pubkey then skip verification.
// This has the effect of always declaring that this sig/pubkey combination is valid.
if set.signature.is_infinity
&& set.signing_keys.len() == 1
&& set.signing_keys.first().map_or(false, |pk| pk.is_infinity)
{
continue;
}
// Generate random scalars.
let mut vals = [0u64; 4];
vals[0] = rng.gen();
let mut rand_i = std::mem::MaybeUninit::<blst_scalar>::uninit();
// TODO: remove this `unsafe` code-block once we get a safe option from `blst`.
//
// See https://github.com/supranational/blst/issues/13
unsafe {
blst::blst_scalar_from_uint64(rand_i.as_mut_ptr(), vals.as_ptr());
rands.push(rand_i.assume_init());
}
// Grab a slice of the message, to satisfy the blst API.
msgs_refs.push(set.message.as_bytes());
// Convert the aggregate signature into a signature.
if let Some(point) = set.signature.point() {
sigs.push(point.0.to_signature())
} else {
// Any "empty" signature should cause a signature failure.
return false;
}
// Sanity check.
if set.signing_keys.is_empty() {
// A signature that has no signing keys is invalid.
return false;
}
// Collect all the public keys into a point, to satisfy the blst API.
//
// Note: we could potentially have the `SignatureSet` take a pubkey point instead of a
// `GenericPublicKey` and avoid this allocation.
let signing_keys = set
.signing_keys
.iter()
.map(|pk| pk.point())
.collect::<Vec<_>>();
// Aggregate all the public keys.
pks.push(blst_core::AggregatePublicKey::aggregate(&signing_keys).to_public_key());
}
// Due to an earlier check, the only case this can be empty is if all the sets consisted of
// infinity pubkeys/sigs. In such a case we wish to return `true`.
if msgs_refs.is_empty() {
return true;
}
let (sig_refs, pks_refs): (Vec<_>, Vec<_>) = sigs.iter().zip(pks.iter()).unzip();
let err = blst_core::Signature::verify_multiple_aggregate_signatures(
&msgs_refs, DST, &pks_refs, &sig_refs, &rands, RAND_BITS,
);
err == blst::BLST_ERROR::BLST_SUCCESS
}
impl TPublicKey for blst_core::PublicKey {
fn serialize(&self) -> [u8; PUBLIC_KEY_BYTES_LEN] {
self.compress()
}
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
Self::uncompress(&bytes).map_err(Into::into)
}
}
/// A wrapper that allows for `PartialEq` and `Clone` impls.
pub struct BlstAggregatePublicKey(blst_core::AggregatePublicKey);
impl Clone for BlstAggregatePublicKey {
fn clone(&self) -> Self {
Self(blst_core::AggregatePublicKey::from_public_key(
&self.0.to_public_key(),
))
}
}
impl PartialEq for BlstAggregatePublicKey {
fn eq(&self, other: &Self) -> bool {
self.0.to_public_key() == other.0.to_public_key()
}
}
impl TAggregatePublicKey for BlstAggregatePublicKey {
fn infinity() -> Self {
blst_core::PublicKey::from_bytes(&INFINITY_PUBLIC_KEY)
.map(|pk| blst_core::AggregatePublicKey::from_public_key(&pk))
.map(Self)
.expect("should decode infinity public key")
}
fn serialize(&self) -> [u8; PUBLIC_KEY_BYTES_LEN] {
self.0.to_public_key().compress()
}
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
blst_core::PublicKey::from_bytes(&bytes)
.map_err(Into::into)
.map(|pk| blst_core::AggregatePublicKey::from_public_key(&pk))
.map(Self)
}
}
impl TSignature<blst_core::PublicKey> for blst_core::Signature {
fn serialize(&self) -> [u8; SIGNATURE_BYTES_LEN] {
self.to_bytes()
}
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
Self::from_bytes(bytes).map_err(Into::into)
}
fn verify(&self, pubkey: &blst_core::PublicKey, msg: Hash256) -> bool {
self.verify(msg.as_bytes(), DST, &[], pubkey) == BLST_ERROR::BLST_SUCCESS
}
}
/// A wrapper that allows for `PartialEq` and `Clone` impls.
pub struct BlstAggregateSignature(blst_core::AggregateSignature);
impl Clone for BlstAggregateSignature {
fn clone(&self) -> Self {
Self(blst_core::AggregateSignature::from_signature(
&self.0.to_signature(),
))
}
}
impl PartialEq for BlstAggregateSignature {
fn eq(&self, other: &Self) -> bool {
self.0.to_signature() == other.0.to_signature()
}
}
impl TAggregateSignature<blst_core::PublicKey, BlstAggregatePublicKey, blst_core::Signature>
for BlstAggregateSignature
{
fn infinity() -> Self {
blst_core::Signature::from_bytes(&INFINITY_SIGNATURE)
.map(|sig| blst_core::AggregateSignature::from_signature(&sig))
.map(Self)
.expect("should decode infinity signature")
}
fn add_assign(&mut self, other: &blst_core::Signature) {
self.0.add_signature(other)
}
fn add_assign_aggregate(&mut self, other: &Self) {
self.0.add_aggregate(&other.0)
}
fn serialize(&self) -> [u8; SIGNATURE_BYTES_LEN] {
self.0.to_signature().to_bytes()
}
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
blst_core::Signature::from_bytes(bytes)
.map_err(Into::into)
.map(|sig| blst_core::AggregateSignature::from_signature(&sig))
.map(Self)
}
fn fast_aggregate_verify(
&self,
msg: Hash256,
pubkeys: &[&GenericPublicKey<blst_core::PublicKey>],
) -> bool {
let pubkeys = pubkeys.iter().map(|pk| pk.point()).collect::<Vec<_>>();
let signature = self.0.clone().to_signature();
signature.fast_aggregate_verify(msg.as_bytes(), DST, &pubkeys) == BLST_ERROR::BLST_SUCCESS
}
fn aggregate_verify(
&self,
msgs: &[Hash256],
pubkeys: &[&GenericPublicKey<blst_core::PublicKey>],
) -> bool {
let pubkeys = pubkeys.iter().map(|pk| pk.point()).collect::<Vec<_>>();
let msgs = msgs.iter().map(|hash| hash.as_bytes()).collect::<Vec<_>>();
let signature = self.0.clone().to_signature();
signature.aggregate_verify(&msgs, DST, &pubkeys) == BLST_ERROR::BLST_SUCCESS
}
}
impl TSecretKey<blst_core::Signature, blst_core::PublicKey> for blst_core::SecretKey {
fn random() -> Self {
let rng = &mut rand::thread_rng();
let ikm: [u8; 32] = rng.gen();
Self::key_gen(&ikm, &[]).unwrap()
}
fn public_key(&self) -> blst_core::PublicKey {
self.sk_to_pk()
}
fn sign(&self, msg: Hash256) -> blst_core::Signature {
self.sign(msg.as_bytes(), DST, &[])
}
fn serialize(&self) -> ZeroizeHash {
self.to_bytes().into()
}
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
Self::from_bytes(&bytes).map_err(Into::into)
}
}

View File

@@ -0,0 +1,215 @@
use crate::{
generic_aggregate_public_key::TAggregatePublicKey,
generic_aggregate_signature::TAggregateSignature,
generic_public_key::{GenericPublicKey, TPublicKey, PUBLIC_KEY_BYTES_LEN},
generic_secret_key::{TSecretKey, SECRET_KEY_BYTES_LEN},
generic_signature::{TSignature, SIGNATURE_BYTES_LEN},
Error, Hash256, ZeroizeHash, INFINITY_PUBLIC_KEY, INFINITY_SIGNATURE,
};
/// Provides the externally-facing, core BLS types.
pub mod types {
pub use super::verify_signature_sets;
pub use super::AggregatePublicKey;
pub use super::AggregateSignature;
pub use super::PublicKey;
pub use super::SecretKey;
pub use super::Signature;
pub use super::SignatureSet;
}
pub type SignatureSet<'a> = crate::generic_signature_set::GenericSignatureSet<
'a,
PublicKey,
AggregatePublicKey,
Signature,
AggregateSignature,
>;
pub fn verify_signature_sets<'a>(
_signature_sets: impl ExactSizeIterator<Item = &'a SignatureSet<'a>>,
) -> bool {
true
}
#[derive(Clone)]
pub struct PublicKey([u8; PUBLIC_KEY_BYTES_LEN]);
impl PublicKey {
fn infinity() -> Self {
Self(INFINITY_PUBLIC_KEY)
}
}
impl TPublicKey for PublicKey {
fn serialize(&self) -> [u8; PUBLIC_KEY_BYTES_LEN] {
self.0
}
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
let mut pubkey = Self::infinity();
pubkey.0[..].copy_from_slice(&bytes[0..PUBLIC_KEY_BYTES_LEN]);
Ok(pubkey)
}
}
impl Eq for PublicKey {}
impl PartialEq for PublicKey {
fn eq(&self, other: &Self) -> bool {
self.0[..] == other.0[..]
}
}
#[derive(Clone)]
pub struct AggregatePublicKey([u8; PUBLIC_KEY_BYTES_LEN]);
impl TAggregatePublicKey for AggregatePublicKey {
fn infinity() -> Self {
Self([0; PUBLIC_KEY_BYTES_LEN])
}
fn serialize(&self) -> [u8; PUBLIC_KEY_BYTES_LEN] {
let mut bytes = [0; PUBLIC_KEY_BYTES_LEN];
bytes[..].copy_from_slice(&self.0);
bytes
}
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
let mut key = [0; PUBLIC_KEY_BYTES_LEN];
key[..].copy_from_slice(&bytes);
Ok(Self(key))
}
}
impl Eq for AggregatePublicKey {}
impl PartialEq for AggregatePublicKey {
fn eq(&self, other: &Self) -> bool {
self.0[..] == other.0[..]
}
}
#[derive(Clone)]
pub struct Signature([u8; SIGNATURE_BYTES_LEN]);
impl Signature {
fn infinity() -> Self {
Self([0; SIGNATURE_BYTES_LEN])
}
}
impl TSignature<PublicKey> for Signature {
fn serialize(&self) -> [u8; SIGNATURE_BYTES_LEN] {
self.0
}
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
let mut signature = Self::infinity();
signature.0[..].copy_from_slice(&bytes[0..SIGNATURE_BYTES_LEN]);
Ok(signature)
}
fn verify(&self, _pubkey: &PublicKey, _msg: Hash256) -> bool {
true
}
}
impl PartialEq for Signature {
fn eq(&self, other: &Self) -> bool {
self.0[..] == other.0[..]
}
}
#[derive(Clone)]
pub struct AggregateSignature([u8; SIGNATURE_BYTES_LEN]);
impl AggregateSignature {
fn infinity() -> Self {
Self(INFINITY_SIGNATURE)
}
}
impl TAggregateSignature<PublicKey, AggregatePublicKey, Signature> for AggregateSignature {
fn infinity() -> Self {
Self::infinity()
}
fn add_assign(&mut self, _other: &Signature) {
// Do nothing.
}
fn add_assign_aggregate(&mut self, _other: &Self) {
// Do nothing.
}
fn serialize(&self) -> [u8; SIGNATURE_BYTES_LEN] {
let mut bytes = [0; SIGNATURE_BYTES_LEN];
bytes[..].copy_from_slice(&self.0);
bytes
}
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
let mut key = [0; SIGNATURE_BYTES_LEN];
key[..].copy_from_slice(&bytes);
Ok(Self(key))
}
fn fast_aggregate_verify(
&self,
_msg: Hash256,
_pubkeys: &[&GenericPublicKey<PublicKey>],
) -> bool {
true
}
fn aggregate_verify(
&self,
_msgs: &[Hash256],
_pubkeys: &[&GenericPublicKey<PublicKey>],
) -> bool {
true
}
}
impl Eq for AggregateSignature {}
impl PartialEq for AggregateSignature {
fn eq(&self, other: &Self) -> bool {
self.0[..] == other.0[..]
}
}
#[derive(Clone)]
pub struct SecretKey([u8; SECRET_KEY_BYTES_LEN]);
impl TSecretKey<Signature, PublicKey> for SecretKey {
fn random() -> Self {
Self([0; SECRET_KEY_BYTES_LEN])
}
fn public_key(&self) -> PublicKey {
PublicKey::infinity()
}
fn sign(&self, _msg: Hash256) -> Signature {
Signature::infinity()
}
fn serialize(&self) -> ZeroizeHash {
let mut bytes = [0; SECRET_KEY_BYTES_LEN];
bytes[..].copy_from_slice(&self.0[..]);
bytes.into()
}
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
let mut sk = Self::random();
sk.0[..].copy_from_slice(&bytes[0..SECRET_KEY_BYTES_LEN]);
Ok(sk)
}
}

View File

@@ -0,0 +1,197 @@
use crate::{
generic_aggregate_public_key::TAggregatePublicKey,
generic_aggregate_signature::TAggregateSignature,
generic_public_key::{GenericPublicKey, TPublicKey, PUBLIC_KEY_BYTES_LEN},
generic_secret_key::{TSecretKey, SECRET_KEY_BYTES_LEN},
generic_signature::{TSignature, SIGNATURE_BYTES_LEN},
Error, Hash256, ZeroizeHash, INFINITY_PUBLIC_KEY,
};
pub use milagro_bls as milagro;
use rand::thread_rng;
use std::iter::ExactSizeIterator;
/// Provides the externally-facing, core BLS types.
pub mod types {
pub use super::milagro::AggregatePublicKey;
pub use super::milagro::AggregateSignature;
pub use super::milagro::PublicKey;
pub use super::milagro::SecretKey;
pub use super::milagro::Signature;
pub use super::verify_signature_sets;
pub use super::SignatureSet;
}
pub type SignatureSet<'a> = crate::generic_signature_set::GenericSignatureSet<
'a,
milagro::PublicKey,
milagro::AggregatePublicKey,
milagro::Signature,
milagro::AggregateSignature,
>;
pub fn verify_signature_sets<'a>(
signature_sets: impl ExactSizeIterator<Item = &'a SignatureSet<'a>>,
) -> bool {
if signature_sets.len() == 0 {
return false;
}
signature_sets
.map(|signature_set| {
let mut aggregate = milagro::AggregatePublicKey::from_public_key(
signature_set.signing_keys.first().ok_or(())?.point(),
);
for signing_key in signature_set.signing_keys.iter().skip(1) {
aggregate.add(signing_key.point())
}
if signature_set.signature.point().is_none() {
return Err(());
}
Ok((
signature_set.signature.as_ref(),
aggregate,
signature_set.message,
))
})
.collect::<Result<Vec<_>, ()>>()
.map(|aggregates| {
milagro::AggregateSignature::verify_multiple_aggregate_signatures(
&mut rand::thread_rng(),
aggregates.iter().map(|(signature, aggregate, message)| {
(
signature
.point()
.expect("guarded against none by previous check"),
aggregate,
message.as_bytes(),
)
}),
)
})
.unwrap_or(false)
}
impl TPublicKey for milagro::PublicKey {
fn serialize(&self) -> [u8; PUBLIC_KEY_BYTES_LEN] {
let mut bytes = [0; PUBLIC_KEY_BYTES_LEN];
bytes[..].copy_from_slice(&self.as_bytes());
bytes
}
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
Self::from_bytes(&bytes).map_err(Into::into)
}
}
impl TAggregatePublicKey for milagro::AggregatePublicKey {
fn infinity() -> Self {
Self::from_bytes(&INFINITY_PUBLIC_KEY).expect("should decode infinity public key")
}
fn serialize(&self) -> [u8; PUBLIC_KEY_BYTES_LEN] {
let mut bytes = [0; PUBLIC_KEY_BYTES_LEN];
bytes[..].copy_from_slice(&self.as_bytes());
bytes
}
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
Self::from_bytes(&bytes).map_err(Into::into)
}
}
impl TSignature<milagro::PublicKey> for milagro::Signature {
fn serialize(&self) -> [u8; SIGNATURE_BYTES_LEN] {
let mut bytes = [0; SIGNATURE_BYTES_LEN];
bytes[..].copy_from_slice(&self.as_bytes());
bytes
}
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
milagro::Signature::from_bytes(&bytes).map_err(Error::MilagroError)
}
fn verify(&self, pubkey: &milagro::PublicKey, msg: Hash256) -> bool {
self.verify(msg.as_bytes(), pubkey)
}
}
impl TAggregateSignature<milagro::PublicKey, milagro::AggregatePublicKey, milagro::Signature>
for milagro::AggregateSignature
{
fn infinity() -> Self {
milagro::AggregateSignature::new()
}
fn add_assign(&mut self, other: &milagro::Signature) {
self.add(other)
}
fn add_assign_aggregate(&mut self, other: &Self) {
self.add_aggregate(other)
}
fn serialize(&self) -> [u8; SIGNATURE_BYTES_LEN] {
let mut bytes = [0; SIGNATURE_BYTES_LEN];
bytes[..].copy_from_slice(&self.as_bytes());
bytes
}
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
milagro::AggregateSignature::from_bytes(&bytes).map_err(Error::MilagroError)
}
fn fast_aggregate_verify(
&self,
msg: Hash256,
pubkeys: &[&GenericPublicKey<milagro::PublicKey>],
) -> bool {
let pubkeys = pubkeys.iter().map(|pk| pk.point()).collect::<Vec<_>>();
self.fast_aggregate_verify(msg.as_bytes(), &pubkeys)
}
fn aggregate_verify(
&self,
msgs: &[Hash256],
pubkeys: &[&GenericPublicKey<milagro::PublicKey>],
) -> bool {
let pubkeys = pubkeys.iter().map(|pk| pk.point()).collect::<Vec<_>>();
let msgs = msgs.iter().map(|hash| hash.as_bytes()).collect::<Vec<_>>();
self.aggregate_verify(&msgs, &pubkeys)
}
}
impl TSecretKey<milagro::Signature, milagro::PublicKey> for milagro::SecretKey {
fn random() -> Self {
Self::random(&mut thread_rng())
}
fn public_key(&self) -> milagro::PublicKey {
let point = milagro::PublicKey::from_secret_key(self).point;
milagro::PublicKey { point }
}
fn sign(&self, msg: Hash256) -> milagro::Signature {
let point = milagro::Signature::new(msg.as_bytes(), self).point;
milagro::Signature { point }
}
fn serialize(&self) -> ZeroizeHash {
let mut bytes = [0; SECRET_KEY_BYTES_LEN];
// Takes the right-hand 32 bytes from the secret key.
bytes[..].copy_from_slice(&self.as_bytes());
bytes.into()
}
fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
Self::from_bytes(&bytes).map_err(Into::into)
}
}

View File

@@ -0,0 +1,3 @@
pub mod blst;
pub mod fake_crypto;
pub mod milagro;

View File

@@ -1,41 +0,0 @@
use super::{PublicKey, SecretKey};
use std::fmt;
use std::hash::{Hash, Hasher};
#[derive(Clone)]
pub struct Keypair {
pub sk: SecretKey,
pub pk: PublicKey,
}
impl Keypair {
/// Instantiate a Keypair using SecretKey::random().
pub fn random() -> Self {
let sk = SecretKey::random();
let pk = PublicKey::from_secret_key(&sk);
Keypair { sk, pk }
}
pub fn identifier(&self) -> String {
self.pk.concatenated_hex_id()
}
}
#[allow(clippy::derive_hash_xor_eq)]
impl Hash for Keypair {
/// Note: this is distinct from consensus serialization, it will produce a different hash.
///
/// This method uses the uncompressed bytes, which are much faster to obtain than the
/// compressed bytes required for consensus serialization.
///
/// Use `ssz::Encode` to obtain the bytes required for consensus hashing.
fn hash<H: Hasher>(&self, state: &mut H) {
self.pk.as_uncompressed_bytes().hash(state)
}
}
impl fmt::Display for Keypair {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.pk)
}
}

View File

@@ -1,84 +1,140 @@
extern crate milagro_bls;
extern crate ssz;
//! This library provides a wrapper around several BLS implementations to provide
//! Lighthouse-specific functionality.
//!
//! This crate should not perform direct cryptographic operations, instead it should do these via
//! external libraries. However, seeing as it is an interface to a real cryptographic library, it
//! may contain logic that affects the outcomes of cryptographic operations.
//!
//! A source of complexity in this crate is that *multiple* BLS implementations (a.k.a. "backends")
//! are supported via compile-time flags. There are three backends supported via features:
//!
//! - `supranational`: the pure-assembly, highly optimized version from the `blst` crate.
//! - `milagro`: the classic pure-Rust `milagro_bls` crate.
//! - `fake_crypto`: an always-returns-valid implementation that is only useful for testing
//! scenarios which intend to *ignore* real cryptography.
//!
//! This crate uses traits to reduce code-duplication between the two implementations. For example,
//! the `GenericPublicKey` struct exported from this crate is generic across the `TPublicKey` trait
//! (i.e., `PublicKey<TPublicKey>`). `TPublicKey` is implemented by all three backends (see the
//! `impls.rs` module). When compiling with the `milagro` feature, we export
//! `type PublicKey = GenericPublicKey<milagro::PublicKey>`.
#[macro_use]
mod macros;
mod keypair;
mod public_key_bytes;
mod secret_hash;
mod secret_key;
mod signature_bytes;
mod signature_set;
mod generic_aggregate_public_key;
mod generic_aggregate_signature;
mod generic_keypair;
mod generic_public_key;
mod generic_public_key_bytes;
mod generic_secret_key;
mod generic_signature;
mod generic_signature_bytes;
mod generic_signature_set;
mod get_withdrawal_credentials;
mod zeroize_hash;
pub use crate::keypair::Keypair;
pub use crate::public_key_bytes::PublicKeyBytes;
pub use crate::secret_key::SecretKey;
pub use crate::signature_bytes::SignatureBytes;
pub use secret_hash::SecretHash;
pub use signature_set::{verify_signature_sets, SignatureSet};
pub mod impls;
#[cfg(feature = "arbitrary")]
pub use arbitrary;
pub use generic_public_key::{INFINITY_PUBLIC_KEY, PUBLIC_KEY_BYTES_LEN};
pub use generic_secret_key::SECRET_KEY_BYTES_LEN;
pub use generic_signature::{INFINITY_SIGNATURE, SIGNATURE_BYTES_LEN};
pub use get_withdrawal_credentials::get_withdrawal_credentials;
pub use zeroize_hash::ZeroizeHash;
#[cfg(feature = "fake_crypto")]
mod fake_aggregate_public_key;
#[cfg(feature = "fake_crypto")]
mod fake_aggregate_signature;
#[cfg(feature = "fake_crypto")]
mod fake_public_key;
#[cfg(feature = "fake_crypto")]
mod fake_signature;
use blst::BLST_ERROR as BlstError;
use milagro_bls::AmclError;
#[cfg(not(feature = "fake_crypto"))]
mod aggregate_public_key;
#[cfg(not(feature = "fake_crypto"))]
mod aggregate_signature;
#[cfg(not(feature = "fake_crypto"))]
mod public_key;
#[cfg(not(feature = "fake_crypto"))]
mod signature;
pub type Hash256 = ethereum_types::H256;
#[cfg(feature = "fake_crypto")]
pub use fakes::*;
#[cfg(feature = "fake_crypto")]
mod fakes {
pub use crate::fake_aggregate_public_key::FakeAggregatePublicKey as AggregatePublicKey;
pub use crate::fake_aggregate_signature::FakeAggregateSignature as AggregateSignature;
pub use crate::fake_public_key::FakePublicKey as PublicKey;
pub use crate::fake_signature::FakeSignature as Signature;
#[derive(Clone, Debug, PartialEq)]
pub enum Error {
/// An error was raised from the Milagro BLS library.
MilagroError(AmclError),
/// An error was raised from the Supranational BLST BLS library.
BlstError(BlstError),
/// The provided bytes were an incorrect length.
InvalidByteLength { got: usize, expected: usize },
/// The provided secret key bytes were an incorrect length.
InvalidSecretKeyLength { got: usize, expected: usize },
}
#[cfg(not(feature = "fake_crypto"))]
pub use reals::*;
#[cfg(not(feature = "fake_crypto"))]
mod reals {
pub use crate::aggregate_public_key::AggregatePublicKey;
pub use crate::aggregate_signature::AggregateSignature;
pub use crate::public_key::PublicKey;
pub use crate::signature::Signature;
impl From<AmclError> for Error {
fn from(e: AmclError) -> Error {
Error::MilagroError(e)
}
}
pub const BLS_AGG_SIG_BYTE_SIZE: usize = 96;
pub const BLS_SIG_BYTE_SIZE: usize = 96;
pub const BLS_SECRET_KEY_BYTE_SIZE: usize = 32;
pub const BLS_PUBLIC_KEY_BYTE_SIZE: usize = 48;
use eth2_hashing::hash;
use ssz::ssz_encode;
/// Returns the withdrawal credentials for a given public key.
pub fn get_withdrawal_credentials(pubkey: &PublicKey, prefix_byte: u8) -> Vec<u8> {
let hashed = hash(&ssz_encode(pubkey));
let mut prefixed = vec![prefix_byte];
prefixed.extend_from_slice(&hashed[1..]);
prefixed
impl From<BlstError> for Error {
fn from(e: BlstError) -> Error {
Error::BlstError(e)
}
}
pub fn bls_verify_aggregate(
pubkey: &AggregatePublicKey,
message: &[u8],
signature: &AggregateSignature,
) -> bool {
signature.verify(message, pubkey)
/// Generic implementations which are only generally useful for docs.
pub mod generics {
pub use crate::generic_aggregate_signature::GenericAggregateSignature;
pub use crate::generic_keypair::GenericKeypair;
pub use crate::generic_public_key::GenericPublicKey;
pub use crate::generic_public_key_bytes::GenericPublicKeyBytes;
pub use crate::generic_secret_key::GenericSecretKey;
pub use crate::generic_signature::GenericSignature;
pub use crate::generic_signature_bytes::GenericSignatureBytes;
}
/// Defines all the fundamental BLS points which should be exported by this crate by making
/// concrete the generic type parameters using the points from some external BLS library (e.g.,
/// Milagro, BLST).
macro_rules! define_mod {
($name: ident, $mod: path) => {
pub mod $name {
use $mod as bls_variant;
use crate::generics::*;
pub use bls_variant::{verify_signature_sets, SignatureSet};
pub type PublicKey = GenericPublicKey<bls_variant::PublicKey>;
pub type PublicKeyBytes = GenericPublicKeyBytes<bls_variant::PublicKey>;
pub type Signature = GenericSignature<bls_variant::PublicKey, bls_variant::Signature>;
pub type AggregateSignature = GenericAggregateSignature<
bls_variant::PublicKey,
bls_variant::AggregatePublicKey,
bls_variant::Signature,
bls_variant::AggregateSignature,
>;
pub type SignatureBytes =
GenericSignatureBytes<bls_variant::PublicKey, bls_variant::Signature>;
pub type SecretKey = GenericSecretKey<
bls_variant::Signature,
bls_variant::PublicKey,
bls_variant::SecretKey,
>;
pub type Keypair = GenericKeypair<
bls_variant::PublicKey,
bls_variant::SecretKey,
bls_variant::Signature,
>;
}
};
}
define_mod!(milagro_implementations, crate::impls::milagro::types);
define_mod!(blst_implementations, crate::impls::blst::types);
#[cfg(feature = "fake_crypto")]
define_mod!(
fake_crypto_implementations,
crate::impls::fake_crypto::types
);
#[cfg(all(feature = "milagro", not(feature = "fake_crypto"),))]
pub use milagro_implementations::*;
#[cfg(all(
feature = "supranational",
not(feature = "fake_crypto"),
not(feature = "milagro")
))]
pub use blst_implementations::*;
#[cfg(feature = "fake_crypto")]
pub use fake_crypto_implementations::*;

View File

@@ -1,265 +1,132 @@
macro_rules! impl_ssz {
($type: ident, $byte_size: expr, $item_str: expr) => {
impl ssz::Encode for $type {
fn is_ssz_fixed_len() -> bool {
true
}
fn ssz_fixed_len() -> usize {
$byte_size
}
fn ssz_bytes_len(&self) -> usize {
$byte_size
}
fn ssz_append(&self, buf: &mut Vec<u8>) {
buf.extend_from_slice(&self.as_bytes())
}
}
impl ssz::Decode for $type {
fn is_ssz_fixed_len() -> bool {
true
}
fn ssz_fixed_len() -> usize {
$byte_size
}
fn from_ssz_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
let len = bytes.len();
let expected = <Self as ssz::Decode>::ssz_fixed_len();
if len != expected {
Err(ssz::DecodeError::InvalidByteLength { len, expected })
} else {
$type::from_bytes(bytes)
}
}
}
};
}
/// Contains the functions required for a `TreeHash` implementation.
///
/// Does not include the `Impl` section since it gets very complicated when it comes to generics.
macro_rules! impl_tree_hash {
($type: ty, $byte_size: expr) => {
impl tree_hash::TreeHash for $type {
fn tree_hash_type() -> tree_hash::TreeHashType {
tree_hash::TreeHashType::Vector
}
($byte_size: expr) => {
fn tree_hash_type() -> tree_hash::TreeHashType {
tree_hash::TreeHashType::Vector
}
fn tree_hash_packed_encoding(&self) -> Vec<u8> {
unreachable!("Vector should never be packed.")
}
fn tree_hash_packed_encoding(&self) -> Vec<u8> {
unreachable!("Vector should never be packed.")
}
fn tree_hash_packing_factor() -> usize {
unreachable!("Vector should never be packed.")
}
fn tree_hash_packing_factor() -> usize {
unreachable!("Vector should never be packed.")
}
fn tree_hash_root(&self) -> tree_hash::Hash256 {
// We could use the tree hash implementation for `FixedVec<u8, $byte_size>`,
// but benchmarks have show that to be at least 15% slower because of the
// unnecessary copying and allocation (one Vec per byte)
let values_per_chunk = tree_hash::BYTES_PER_CHUNK;
let minimum_chunk_count = ($byte_size + values_per_chunk - 1) / values_per_chunk;
fn tree_hash_root(&self) -> tree_hash::Hash256 {
// We could use the tree hash implementation for `FixedVec<u8, $byte_size>`,
// but benchmarks have show that to be at least 15% slower because of the
// unnecessary copying and allocation (one Vec per byte)
let values_per_chunk = tree_hash::BYTES_PER_CHUNK;
let minimum_chunk_count = ($byte_size + values_per_chunk - 1) / values_per_chunk;
tree_hash::merkle_root(&self.serialize(), minimum_chunk_count)
}
};
}
let mut hasher = tree_hash::MerkleHasher::with_leaves(minimum_chunk_count);
hasher
.write(&self.as_ssz_bytes())
.expect("bls should not exceed leaf count");
hasher
.finish()
.expect("bls should not exceed leaf count from buffer")
/// Contains the functions required for a `ssz::Encode` implementation.
///
/// Does not include the `Impl` section since it gets very complicated when it comes to generics.
macro_rules! impl_ssz_encode {
($byte_size: expr) => {
fn is_ssz_fixed_len() -> bool {
true
}
fn ssz_fixed_len() -> usize {
$byte_size
}
fn ssz_bytes_len(&self) -> usize {
$byte_size
}
fn ssz_append(&self, buf: &mut Vec<u8>) {
buf.extend_from_slice(&self.serialize())
}
};
}
/// Contains the functions required for a `ssz::Decode` implementation.
///
/// Does not include the `Impl` section since it gets very complicated when it comes to generics.
macro_rules! impl_ssz_decode {
($byte_size: expr) => {
fn is_ssz_fixed_len() -> bool {
true
}
fn ssz_fixed_len() -> usize {
$byte_size
}
fn from_ssz_bytes(bytes: &[u8]) -> Result<Self, ssz::DecodeError> {
let len = bytes.len();
let expected = <Self as ssz::Decode>::ssz_fixed_len();
if len != expected {
Err(ssz::DecodeError::InvalidByteLength { len, expected })
} else {
Self::deserialize(bytes)
.map_err(|e| ssz::DecodeError::BytesInvalid(format!("{:?}", e)))
}
}
};
}
macro_rules! bytes_struct {
($name: ident, $type: ty, $byte_size: expr, $small_name: expr,
$type_str: expr, $byte_size_str: expr) => {
#[doc = "Stores `"]
#[doc = $byte_size_str]
#[doc = "` bytes which may or may not represent a valid BLS "]
#[doc = $small_name]
#[doc = ".\n\nThe `"]
#[doc = $type_str]
#[doc = "` struct performs validation when it is instantiated, where as this struct does \
not. This struct is suitable where we may wish to store bytes that are \
potentially not a valid "]
#[doc = $small_name]
#[doc = " (e.g., from the deposit contract)."]
#[derive(Clone)]
pub struct $name {
bytes: [u8; $byte_size],
/// Contains the functions required for a `serde::Serialize` implementation.
///
/// Does not include the `Impl` section since it gets very complicated when it comes to generics.
macro_rules! impl_serde_serialize {
() => {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&hex_encode(self.serialize().to_vec()))
}
};
}
/// Contains the functions required for a `serde::Deserialize` implementation.
///
/// Does not include the `Impl` section since it gets very complicated when it comes to generics.
macro_rules! impl_serde_deserialize {
() => {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let bytes = deserializer.deserialize_str(PrefixedHexVisitor)?;
Self::deserialize(&bytes[..])
.map_err(|e| serde::de::Error::custom(format!("invalid pubkey ({:?})", e)))
}
};
}
/// Contains the functions required for a `Debug` implementation.
///
/// Does not include the `Impl` section since it gets very complicated when it comes to generics.
macro_rules! impl_debug {
() => {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", hex_encode(&self.serialize().to_vec()))
}
};
}
/// Contains the functions required for an `Arbitrary` implementation.
///
/// Does not include the `Impl` section since it gets very complicated when it comes to generics.
#[cfg(feature = "arbitrary")]
macro_rules! impl_arbitrary {
($byte_size: expr) => {
fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
let mut bytes = [0u8; $byte_size];
u.fill_buffer(&mut bytes)?;
Self::deserialize(&bytes).map_err(|_| arbitrary::Error::IncorrectFormat)
}
};
($name: ident, $type: ty, $byte_size: expr, $small_name: expr) => {
bytes_struct!($name, $type, $byte_size, $small_name, stringify!($type),
stringify!($byte_size));
impl $name {
pub fn from_bytes(bytes: &[u8]) -> Result<Self, ssz::DecodeError> {
Ok(Self {
bytes: Self::get_bytes(bytes)?,
})
}
pub fn empty() -> Self {
Self {
bytes: [0; $byte_size],
}
}
pub fn as_bytes(&self) -> Vec<u8> {
self.bytes.to_vec()
}
pub fn as_slice(&self) -> &[u8] {
&self.bytes
}
fn get_bytes(bytes: &[u8]) -> Result<[u8; $byte_size], ssz::DecodeError> {
let mut result = [0; $byte_size];
if bytes.len() != $byte_size {
Err(ssz::DecodeError::InvalidByteLength {
len: bytes.len(),
expected: $byte_size,
})
} else {
result[..].copy_from_slice(bytes);
Ok(result)
}
}
}
impl std::fmt::Debug for $name {
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
self.bytes[..].fmt(formatter)
}
}
impl PartialEq for $name {
fn eq(&self, other: &Self) -> bool {
&self.bytes[..] == &other.bytes[..]
}
}
impl std::hash::Hash for $name {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.bytes.hash(state)
}
}
impl Eq for $name {}
impl std::convert::TryInto<$type> for &$name {
type Error = ssz::DecodeError;
fn try_into(self) -> Result<$type, Self::Error> {
<$type>::from_bytes(&self.bytes[..])
}
}
impl std::convert::From<$type> for $name {
fn from(obj: $type) -> Self {
// We know that obj.as_bytes() always has exactly $byte_size many bytes.
Self::from_bytes(obj.as_ssz_bytes().as_slice()).unwrap()
}
}
impl ssz::Encode for $name {
fn is_ssz_fixed_len() -> bool {
true
}
fn ssz_fixed_len() -> usize {
$byte_size
}
fn ssz_bytes_len(&self) -> usize {
$byte_size
}
fn ssz_append(&self, buf: &mut Vec<u8>) {
buf.extend_from_slice(&self.bytes)
}
}
impl ssz::Decode for $name {
fn is_ssz_fixed_len() -> bool {
true
}
fn ssz_fixed_len() -> usize {
$byte_size
}
fn from_ssz_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
let len = bytes.len();
let expected = <Self as ssz::Decode>::ssz_fixed_len();
if len != expected {
Err(ssz::DecodeError::InvalidByteLength { len, expected })
} else {
Self::from_bytes(bytes)
}
}
}
impl tree_hash::TreeHash for $name {
fn tree_hash_type() -> tree_hash::TreeHashType {
tree_hash::TreeHashType::Vector
}
fn tree_hash_packed_encoding(&self) -> Vec<u8> {
unreachable!("Vector should never be packed.")
}
fn tree_hash_packing_factor() -> usize {
unreachable!("Vector should never be packed.")
}
fn tree_hash_root(&self) -> tree_hash::Hash256 {
let values_per_chunk = tree_hash::BYTES_PER_CHUNK;
let minimum_chunk_count = ($byte_size + values_per_chunk - 1) / values_per_chunk;
let mut hasher = tree_hash::MerkleHasher::with_leaves(minimum_chunk_count);
hasher.write(&self.bytes).expect("bls should not exceed leaf count");
hasher.finish().expect("bls should not exceed leaf count from buffer")
}
}
impl serde::ser::Serialize for $name {
/// Serde serialization is compliant the Ethereum YAML test format.
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
serializer.serialize_str(&serde_hex::encode(ssz::ssz_encode(self)))
}
}
impl<'de> serde::de::Deserialize<'de> for $name {
/// Serde serialization is compliant the Ethereum YAML test format.
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
let bytes = deserializer.deserialize_str(serde_hex::PrefixedHexVisitor)?;
let signature = Self::from_ssz_bytes(&bytes[..])
.map_err(|e| serde::de::Error::custom(format!("invalid ssz ({:?})", e)))?;
Ok(signature)
}
}
#[cfg(feature = "arbitrary")]
impl $crate::arbitrary::Arbitrary for $name {
fn arbitrary(u: &mut $crate::arbitrary::Unstructured<'_>) -> $crate::arbitrary::Result<Self> {
let mut bytes = [0u8; $byte_size];
u.fill_buffer(&mut bytes)?;
Self::from_bytes(&bytes).map_err(|_| $crate::arbitrary::Error::IncorrectFormat)
}
}
};
}

View File

@@ -1,169 +0,0 @@
use super::{SecretKey, BLS_PUBLIC_KEY_BYTE_SIZE};
use milagro_bls::PublicKey as RawPublicKey;
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use serde_hex::{encode as hex_encode, PrefixedHexVisitor};
use ssz::{Decode, DecodeError, Encode};
use std::default;
use std::fmt;
use std::hash::{Hash, Hasher};
/// A single BLS signature.
///
/// This struct is a wrapper upon a base type and provides helper functions (e.g., SSZ
/// serialization).
#[derive(Clone, Eq)]
pub struct PublicKey(RawPublicKey);
impl PublicKey {
pub fn from_secret_key(secret_key: &SecretKey) -> Self {
PublicKey(RawPublicKey::from_secret_key(secret_key.as_raw()))
}
pub fn from_raw(raw: RawPublicKey) -> Self {
Self(raw)
}
/// Returns a reference to the underlying signature.
pub fn as_raw(&self) -> &RawPublicKey {
&self.0
}
/// Returns the underlying point as compressed bytes.
pub fn as_bytes(&self) -> [u8; BLS_PUBLIC_KEY_BYTE_SIZE] {
self.as_raw().as_bytes()
}
/// Converts compressed bytes to PublicKey
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
let pubkey = RawPublicKey::from_bytes(&bytes).map_err(|_| {
DecodeError::BytesInvalid(format!("Invalid PublicKey bytes: {:?}", bytes))
})?;
Ok(PublicKey(pubkey))
}
/// Returns the PublicKey as (x, y) bytes
pub fn as_uncompressed_bytes(&self) -> [u8; BLS_PUBLIC_KEY_BYTE_SIZE * 2] {
RawPublicKey::as_uncompressed_bytes(&mut self.0.clone())
}
/// Converts (x, y) bytes to PublicKey
pub fn from_uncompressed_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
let pubkey = RawPublicKey::from_uncompressed_bytes(&bytes).map_err(|_| {
DecodeError::BytesInvalid("Invalid PublicKey uncompressed bytes.".to_string())
})?;
Ok(PublicKey(pubkey))
}
/// Returns the last 6 bytes of the SSZ encoding of the public key, as a hex string.
///
/// Useful for providing a short identifier to the user.
pub fn concatenated_hex_id(&self) -> String {
self.as_hex_string()[0..6].to_string()
}
/// Returns the point as a hex string of the SSZ encoding.
///
/// Note: the string is prefixed with `0x`.
pub fn as_hex_string(&self) -> String {
hex_encode(self.as_ssz_bytes())
}
}
impl fmt::Display for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.concatenated_hex_id())
}
}
impl fmt::Debug for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_hex_string())
}
}
impl default::Default for PublicKey {
fn default() -> Self {
let secret_key = SecretKey::random();
PublicKey::from_secret_key(&secret_key)
}
}
impl_ssz!(PublicKey, BLS_PUBLIC_KEY_BYTE_SIZE, "PublicKey");
impl_tree_hash!(PublicKey, BLS_PUBLIC_KEY_BYTE_SIZE);
impl Serialize for PublicKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&hex_encode(self.as_ssz_bytes()))
}
}
impl<'de> Deserialize<'de> for PublicKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let bytes = deserializer.deserialize_str(PrefixedHexVisitor)?;
let pubkey = Self::from_ssz_bytes(&bytes[..])
.map_err(|e| serde::de::Error::custom(format!("invalid pubkey ({:?})", e)))?;
Ok(pubkey)
}
}
impl PartialEq for PublicKey {
fn eq(&self, other: &PublicKey) -> bool {
self.as_ssz_bytes() == other.as_ssz_bytes()
}
}
impl Hash for PublicKey {
/// Note: this is distinct from consensus serialization, it will produce a different hash.
///
/// This method uses the uncompressed bytes, which are much faster to obtain than the
/// compressed bytes required for consensus serialization.
///
/// Use `ssz::Encode` to obtain the bytes required for consensus hashing.
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_uncompressed_bytes().hash(state)
}
}
#[cfg(feature = "arbitrary")]
impl arbitrary::Arbitrary for PublicKey {
fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
let mut bytes = [0u8; BLS_PUBLIC_KEY_BYTE_SIZE];
u.fill_buffer(&mut bytes)?;
Self::from_bytes(&bytes).map_err(|_| arbitrary::Error::IncorrectFormat)
}
}
#[cfg(test)]
mod tests {
use super::*;
use ssz::ssz_encode;
#[test]
pub fn test_ssz_round_trip() {
let sk = SecretKey::random();
let original = PublicKey::from_secret_key(&sk);
let bytes = ssz_encode(&original);
let decoded = PublicKey::from_ssz_bytes(&bytes).unwrap();
assert_eq!(original, decoded);
}
#[test]
pub fn test_byte_size() {
let sk = SecretKey::random();
let original = PublicKey::from_secret_key(&sk);
let bytes = ssz_encode(&original);
assert_eq!(bytes.len(), BLS_PUBLIC_KEY_BYTE_SIZE);
}
}

View File

@@ -1,43 +0,0 @@
use ssz::{Decode, DecodeError, Encode};
use super::{PublicKey, BLS_PUBLIC_KEY_BYTE_SIZE};
bytes_struct!(
PublicKeyBytes,
PublicKey,
BLS_PUBLIC_KEY_BYTE_SIZE,
"public key"
);
#[cfg(test)]
mod tests {
use std::convert::TryInto;
use ssz::ssz_encode;
use super::super::Keypair;
use super::*;
#[test]
pub fn test_valid_public_key() {
let keypair = Keypair::random();
let bytes = ssz_encode(&keypair.pk);
let public_key_bytes = PublicKeyBytes::from_bytes(&bytes).unwrap();
let public_key: Result<PublicKey, _> = (&public_key_bytes).try_into();
assert!(public_key.is_ok());
assert_eq!(keypair.pk, public_key.unwrap());
}
#[test]
#[cfg(not(feature = "fake_crypto"))]
pub fn test_invalid_public_key() {
let mut public_key_bytes = [0; BLS_PUBLIC_KEY_BYTE_SIZE];
public_key_bytes[0] = 255; //a_flag1 == b_flag1 == c_flag1 == 1 and x1 = 0 shouldn't be allowed
let public_key_bytes = PublicKeyBytes::from_bytes(&public_key_bytes[..]);
assert!(public_key_bytes.is_ok());
let public_key: Result<PublicKey, _> = public_key_bytes.as_ref().unwrap().try_into();
assert!(public_key.is_err());
}
}

View File

@@ -1,68 +0,0 @@
extern crate rand;
use crate::SecretHash;
use milagro_bls::SecretKey as RawSecretKey;
use ssz::DecodeError;
/// A single BLS signature.
///
/// This struct is a wrapper upon a base type and provides helper functions (e.g., SSZ
/// serialization).
#[derive(Clone)]
pub struct SecretKey(RawSecretKey);
impl SecretKey {
/// Generate a new `Self` using `rand::thread_rng`.
pub fn random() -> Self {
SecretKey(RawSecretKey::random(&mut rand::thread_rng()))
}
pub fn from_raw(raw: RawSecretKey) -> Self {
Self(raw)
}
/// Returns the secret key as a byte array (wrapped in `SecretHash` wrapper so it is zeroized on
/// `Drop`).
///
/// Extreme care should be taken not to leak these bytes as they are the unencrypted secret
/// key.
pub fn as_bytes(&self) -> SecretHash {
self.as_raw().as_bytes().into()
}
/// Instantiate a SecretKey from existing bytes.
///
/// Note: this is _not_ SSZ decoding.
pub fn from_bytes(bytes: &[u8]) -> Result<SecretKey, DecodeError> {
Ok(SecretKey(RawSecretKey::from_bytes(bytes).map_err(|e| {
DecodeError::BytesInvalid(format!(
"Invalid SecretKey bytes: {:?} Error: {:?}",
bytes, e
))
})?))
}
/// Returns the underlying secret key.
pub(crate) fn as_raw(&self) -> &RawSecretKey {
&self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
pub fn test_ssz_round_trip() {
let byte_key = [
3, 211, 210, 129, 231, 69, 162, 234, 16, 15, 244, 214, 126, 201, 0, 85, 28, 239, 82,
121, 208, 190, 223, 6, 169, 202, 86, 236, 197, 218, 3, 69,
];
let original = SecretKey::from_bytes(&byte_key).unwrap();
let bytes = original.as_bytes();
let decoded = SecretKey::from_bytes(bytes.as_ref()).unwrap();
assert!(original.as_bytes().as_ref().to_vec() == decoded.as_bytes().as_ref().to_vec());
}
}

View File

@@ -1,174 +0,0 @@
use super::{PublicKey, SecretKey, BLS_SIG_BYTE_SIZE};
use milagro_bls::Signature as RawSignature;
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use serde_hex::{encode as hex_encode, PrefixedHexVisitor};
use ssz::{ssz_encode, Decode, DecodeError, Encode};
/// A single BLS signature.
///
/// This struct is a wrapper upon a base type and provides helper functions (e.g., SSZ
/// serialization).
#[derive(Debug, PartialEq, Clone, Eq)]
pub struct Signature {
signature: RawSignature,
is_empty: bool,
}
impl Signature {
/// Instantiate a new Signature from a message and a SecretKey.
pub fn new(msg: &[u8], sk: &SecretKey) -> Self {
Signature {
signature: RawSignature::new(msg, sk.as_raw()),
is_empty: false,
}
}
/// Verify the Signature against a PublicKey.
pub fn verify(&self, msg: &[u8], pk: &PublicKey) -> bool {
if self.is_empty {
return false;
}
self.signature.verify(msg, pk.as_raw())
}
/// Returns the underlying signature.
pub fn as_raw(&self) -> &RawSignature {
&self.signature
}
/// Returns a new empty signature.
pub fn empty_signature() -> Self {
// Set RawSignature = infinity
let mut empty = [0u8; BLS_SIG_BYTE_SIZE];
empty[0] += u8::pow(2, 6) + u8::pow(2, 7);
Signature {
signature: RawSignature::from_bytes(&empty).unwrap(),
is_empty: true,
}
}
// Converts a BLS Signature to bytes
pub fn as_bytes(&self) -> [u8; BLS_SIG_BYTE_SIZE] {
if self.is_empty {
return [0u8; BLS_SIG_BYTE_SIZE];
}
self.signature.as_bytes()
}
// Convert bytes to BLS Signature
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
for byte in bytes {
if *byte != 0 {
let raw_signature = RawSignature::from_bytes(&bytes).map_err(|_| {
DecodeError::BytesInvalid(format!("Invalid Signature bytes: {:?}", bytes))
})?;
return Ok(Signature {
signature: raw_signature,
is_empty: false,
});
}
}
Ok(Signature::empty_signature())
}
// Check for empty Signature
pub fn is_empty(&self) -> bool {
self.is_empty
}
/// Display a signature as a hex string of its bytes.
#[cfg(test)]
pub fn as_hex_string(&self) -> String {
hex_encode(self.as_ssz_bytes())
}
}
impl_ssz!(Signature, BLS_SIG_BYTE_SIZE, "Signature");
impl_tree_hash!(Signature, BLS_SIG_BYTE_SIZE);
impl Serialize for Signature {
/// Serde serialization is compliant the Ethereum YAML test format.
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&hex_encode(ssz_encode(self)))
}
}
impl<'de> Deserialize<'de> for Signature {
/// Serde serialization is compliant the Ethereum YAML test format.
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let bytes = deserializer.deserialize_str(PrefixedHexVisitor)?;
let signature = Self::from_ssz_bytes(&bytes[..])
.map_err(|e| serde::de::Error::custom(format!("invalid ssz ({:?})", e)))?;
Ok(signature)
}
}
#[cfg(feature = "arbitrary")]
impl arbitrary::Arbitrary for Signature {
fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
let mut bytes = [0u8; BLS_SIG_BYTE_SIZE];
u.fill_buffer(&mut bytes)?;
Self::from_bytes(&bytes).map_err(|_| arbitrary::Error::IncorrectFormat)
}
}
#[cfg(test)]
mod tests {
use super::super::Keypair;
use super::*;
use ssz::ssz_encode;
#[test]
pub fn test_ssz_round_trip() {
let keypair = Keypair::random();
let original = Signature::new(&[42, 42], &keypair.sk);
let bytes = ssz_encode(&original);
let decoded = Signature::from_ssz_bytes(&bytes).unwrap();
assert_eq!(original, decoded);
}
#[test]
pub fn test_byte_size() {
let keypair = Keypair::random();
let signature = Signature::new(&[42, 42], &keypair.sk);
let bytes = ssz_encode(&signature);
assert_eq!(bytes.len(), BLS_SIG_BYTE_SIZE);
}
#[test]
pub fn test_infinity_signature() {
let sig = Signature::empty_signature();
let sig_as_bytes = sig.as_raw().as_bytes();
assert_eq!(sig_as_bytes.len(), BLS_SIG_BYTE_SIZE);
for (i, one_byte) in sig_as_bytes.iter().enumerate() {
if i == 0 {
assert_eq!(*one_byte, u8::pow(2, 6) + u8::pow(2, 7));
} else {
assert_eq!(*one_byte, 0);
}
}
}
#[test]
pub fn test_empty_signature() {
let sig = Signature::empty_signature();
let sig_as_bytes = sig.as_bytes().to_vec();
assert_eq!(sig_as_bytes, vec![0u8; BLS_SIG_BYTE_SIZE]);
}
}

View File

@@ -1,39 +0,0 @@
use ssz::{Decode, DecodeError, Encode};
use super::{Signature, BLS_SIG_BYTE_SIZE};
bytes_struct!(SignatureBytes, Signature, BLS_SIG_BYTE_SIZE, "signature");
#[cfg(test)]
mod tests {
use std::convert::TryInto;
use ssz::ssz_encode;
use super::super::Keypair;
use super::*;
#[test]
pub fn test_valid_signature() {
let keypair = Keypair::random();
let original = Signature::new(&[42, 42], &keypair.sk);
let bytes = ssz_encode(&original);
let signature_bytes = SignatureBytes::from_bytes(&bytes).unwrap();
let signature: Result<Signature, _> = (&signature_bytes).try_into();
assert!(signature.is_ok());
assert_eq!(original, signature.unwrap());
}
#[test]
#[cfg(not(feature = "fake_crypto"))]
pub fn test_invalid_signature() {
let mut signature_bytes = [0; BLS_SIG_BYTE_SIZE];
signature_bytes[0] = 255; //a_flag1 == b_flag1 == c_flag1 == 1 and x1 = 0 shouldn't be allowed
let signature_bytes = SignatureBytes::from_bytes(&signature_bytes[..]);
assert!(signature_bytes.is_ok());
let signature: Result<Signature, _> = signature_bytes.as_ref().unwrap().try_into();
assert!(signature.is_err());
}
}

View File

@@ -1,75 +0,0 @@
use crate::{AggregateSignature, PublicKey, Signature};
use std::borrow::Cow;
#[cfg(not(feature = "fake_crypto"))]
use milagro_bls::{
AggregatePublicKey as RawAggregatePublicKey, AggregateSignature as RawAggregateSignature,
PublicKey as RawPublicKey,
};
#[cfg(feature = "fake_crypto")]
use crate::fakes::{
AggregatePublicKey as RawAggregatePublicKey, AggregateSignature as RawAggregateSignature,
PublicKey as RawPublicKey,
};
type Message = Vec<u8>;
#[derive(Clone, Debug)]
pub struct SignatureSet {
pub signature: RawAggregateSignature,
signing_keys: RawAggregatePublicKey,
message: Message,
}
impl SignatureSet {
pub fn single(signature: &Signature, signing_key: Cow<PublicKey>, message: Message) -> Self {
Self {
signature: RawAggregateSignature::from_signature(signature.as_raw()),
signing_keys: RawAggregatePublicKey::from_public_key(signing_key.as_raw()),
message,
}
}
pub fn new(
signature: &AggregateSignature,
signing_keys: Vec<Cow<PublicKey>>,
message: Message,
) -> Self
where {
let signing_keys_refs: Vec<&RawPublicKey> =
signing_keys.iter().map(|pk| pk.as_raw()).collect();
Self {
signature: signature.as_raw().clone(),
signing_keys: RawAggregatePublicKey::aggregate(&signing_keys_refs),
message,
}
}
pub fn is_valid(&self) -> bool {
self.signature
.fast_aggregate_verify_pre_aggregated(&self.message, &self.signing_keys)
}
}
#[cfg(not(feature = "fake_crypto"))]
type VerifySet<'a> = (
&'a RawAggregateSignature,
&'a RawAggregatePublicKey,
&'a [u8],
);
#[cfg(not(feature = "fake_crypto"))]
pub fn verify_signature_sets(sets: Vec<SignatureSet>) -> bool {
let rng = &mut rand::thread_rng();
let verify_set: Vec<VerifySet> = sets
.iter()
.map(|ss| (&ss.signature, &ss.signing_keys, ss.message.as_slice()))
.collect();
RawAggregateSignature::verify_multiple_aggregate_signatures(rng, verify_set.into_iter())
}
#[cfg(feature = "fake_crypto")]
pub fn verify_signature_sets<'a>(_: Vec<SignatureSet>) -> bool {
true
}

View File

@@ -1,15 +1,15 @@
use super::BLS_SECRET_KEY_BYTE_SIZE;
use super::SECRET_KEY_BYTES_LEN;
use zeroize::Zeroize;
/// Provides a wrapper around a `[u8; HASH_SIZE]` that implements `Zeroize` on `Drop`.
/// Provides a wrapper around a `[u8; SECRET_KEY_BYTES_LEN]` that implements `Zeroize` on `Drop`.
#[derive(Zeroize)]
#[zeroize(drop)]
pub struct SecretHash([u8; BLS_SECRET_KEY_BYTE_SIZE]);
pub struct ZeroizeHash([u8; SECRET_KEY_BYTES_LEN]);
impl SecretHash {
impl ZeroizeHash {
/// Instantiates `Self` with all zeros.
pub fn zero() -> Self {
Self([0; BLS_SECRET_KEY_BYTE_SIZE])
Self([0; SECRET_KEY_BYTES_LEN])
}
/// Returns a reference to the underlying bytes.
@@ -23,13 +23,13 @@ impl SecretHash {
}
}
impl From<[u8; BLS_SECRET_KEY_BYTE_SIZE]> for SecretHash {
fn from(array: [u8; BLS_SECRET_KEY_BYTE_SIZE]) -> Self {
impl From<[u8; SECRET_KEY_BYTES_LEN]> for ZeroizeHash {
fn from(array: [u8; SECRET_KEY_BYTES_LEN]) -> Self {
Self(array)
}
}
impl AsRef<[u8]> for SecretHash {
impl AsRef<[u8]> for ZeroizeHash {
fn as_ref(&self) -> &[u8] {
&self.0
}