mirror of
https://github.com/sigp/lighthouse.git
synced 2026-03-19 04:42:34 +00:00
* Start updating types * WIP * Signature hacking * Existing EF tests passing with fake_crypto * Updates * Delete outdated API spec * The refactor continues * It compiles * WIP test fixes * All release tests passing bar genesis state parsing * Update and test YamlConfig * Update to spec v0.10 compatible BLS * Updates to BLS EF tests * Add EF test for AggregateVerify And delete unused hash2curve tests for uncompressed points * Update EF tests to v0.10.1 * Use optional block root correctly in block proc * Use genesis fork in deposit domain. All tests pass * Cargo fmt * Fast aggregate verify test * Update REST API docs * Cargo fmt * Fix unused import * Bump spec tags to v0.10.1 * Add `seconds_per_eth1_block` to chainspec * Update to timestamp based eth1 voting scheme * Return None from `get_votes_to_consider` if block cache is empty * Handle overflows in `is_candidate_block` * Revert to failing tests * Fix eth1 data sets test * Choose default vote according to spec * Fix collect_valid_votes tests * Fix `get_votes_to_consider` to choose all eligible blocks * Uncomment winning_vote tests * Add comments; remove unused code * Reduce seconds_per_eth1_block for simulation * Addressed review comments * Add test for default vote case * Fix logs * Remove unused functions * Meter default eth1 votes * Fix comments * Address review comments; remove unused dependency * Add first attempt at attestation proc. re-write * Add version 2 of attestation processing * Minor fixes * Add validator pubkey cache * Make get_indexed_attestation take a committee * Link signature processing into new attn verification * First working version * Ensure pubkey cache is updated * Add more metrics, slight optimizations * Clone committee cache during attestation processing * Update shuffling cache during block processing * Remove old commented-out code * Fix shuffling cache insert bug * Used indexed attestation in fork choice * Restructure attn processing, add metrics * Add more detailed metrics * Tidy, fix failing tests * Fix failing tests, tidy * Disable/delete two outdated tests * Add new Pubkeys struct to signature_sets * Refactor with functional approach * Update beacon chain * Remove decompressed member from pubkey bytes * Add hashmap for indices lookup * Change `get_attesting_indices` to use Vec * Fix failing test * Tidy * Add pubkey cache persistence file * Add more comments * Integrate persistence file into builder * Add pubkey cache tests * Add data_dir to beacon chain builder * Remove Option in pubkey cache persistence file * Ensure consistency between datadir/data_dir * Fix failing network test * Tidy * Fix todos * Improve tests * Split up block processing metrics * Tidy * Refactor get_pubkey_from_state * Remove commented-out code * Add BeaconChain::validator_pubkey * Use Option::filter * Remove Box * Comment out tests that fail due to hard-coded Co-authored-by: Michael Sproul <michael@sigmaprime.io> Co-authored-by: Michael Sproul <micsproul@gmail.com> Co-authored-by: pawan <pawandhananjay@gmail.com>
173 lines
5.0 KiB
Rust
173 lines
5.0 KiB
Rust
use super::{SecretKey, BLS_PUBLIC_KEY_BYTE_SIZE};
|
|
use milagro_bls::{G1Point, 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
|
|
}
|
|
|
|
/// Consumes self and returns the underlying signature.
|
|
pub fn as_point(&self) -> &G1Point {
|
|
&self.0.point
|
|
}
|
|
|
|
/// Consumes self and returns the underlying signature.
|
|
pub fn into_point(self) -> G1Point {
|
|
self.0.point
|
|
}
|
|
|
|
/// Returns the underlying point as compressed bytes.
|
|
///
|
|
/// Identical to `self.as_uncompressed_bytes()`.
|
|
pub fn as_bytes(&self) -> Vec<u8> {
|
|
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) -> Vec<u8> {
|
|
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_raw().as_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(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);
|
|
}
|
|
}
|