Skip to content

Commit

Permalink
refactor: unify bls types (#357)
Browse files Browse the repository at this point in the history
* refactor: unify bls types

* ci

* remove clone
  • Loading branch information
ncitron authored Aug 26, 2024
1 parent b8cb0aa commit bb38e21
Show file tree
Hide file tree
Showing 7 changed files with 86 additions and 54 deletions.
33 changes: 15 additions & 18 deletions consensus-core/src/consensus_core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use std::cmp;

use alloy::primitives::B256;
use eyre::Result;
use milagro_bls::PublicKey;
use ssz_types::{BitVector, FixedVector};
use tracing::{info, warn};
use tree_hash::TreeHash;
Expand All @@ -11,13 +10,13 @@ use zduny_wasm_timer::{SystemTime, UNIX_EPOCH};
use common::config::types::Forks;

use crate::errors::ConsensusError;
use crate::types::bls::{PublicKey, Signature};
use crate::types::{
FinalityUpdate, GenericUpdate, Header, LightClientStore, OptimisticUpdate, SignatureBytes,
SyncCommittee, Update,
FinalityUpdate, GenericUpdate, Header, LightClientStore, OptimisticUpdate, SyncCommittee,
Update,
};
use crate::utils::{
calc_sync_period, compute_domain, compute_fork_data_root, compute_signing_root,
is_aggregate_valid, is_proof_valid,
calc_sync_period, compute_domain, compute_fork_data_root, compute_signing_root, is_proof_valid,
};

pub fn get_participating_keys(
Expand All @@ -28,8 +27,7 @@ pub fn get_participating_keys(

bitfield.iter().enumerate().for_each(|(i, bit)| {
if bit {
let pk = &committee.pubkeys[i];
let pk = PublicKey::from_bytes_unchecked(&pk.inner).unwrap();
let pk = committee.pubkeys[i].clone();
pks.push(pk);
}
});
Expand All @@ -43,15 +41,15 @@ pub fn get_bits(bitfield: &BitVector<typenum::U512>) -> u64 {

pub fn is_finality_proof_valid(
attested_header: &Header,
finality_header: &mut Header,
finality_header: &Header,
finality_branch: &[B256],
) -> bool {
is_proof_valid(attested_header, finality_header, finality_branch, 6, 41)
}

pub fn is_next_committee_proof_valid(
attested_header: &Header,
next_committee: &mut SyncCommittee,
next_committee: &SyncCommittee,
next_committee_branch: &[B256],
) -> bool {
is_proof_valid(
Expand All @@ -65,7 +63,7 @@ pub fn is_next_committee_proof_valid(

pub fn is_current_committee_proof_valid(
attested_header: &Header,
current_committee: &mut SyncCommittee,
current_committee: &SyncCommittee,
current_committee_branch: &[B256],
) -> bool {
is_proof_valid(
Expand Down Expand Up @@ -216,8 +214,8 @@ pub fn verify_generic_update(
if update.finalized_header.is_some() && update.finality_branch.is_some() {
let is_valid = is_finality_proof_valid(
&update.attested_header,
&mut update.finalized_header.clone().unwrap(),
&update.finality_branch.clone().unwrap(),
update.finalized_header.as_ref().unwrap(),
update.finality_branch.as_ref().unwrap(),
);

if !is_valid {
Expand All @@ -228,8 +226,8 @@ pub fn verify_generic_update(
if update.next_sync_committee.is_some() && update.next_sync_committee_branch.is_some() {
let is_valid = is_next_committee_proof_valid(
&update.attested_header,
&mut update.next_sync_committee.clone().unwrap(),
&update.next_sync_committee_branch.clone().unwrap(),
update.next_sync_committee.as_ref().unwrap(),
update.next_sync_committee_branch.as_ref().unwrap(),
);

if !is_valid {
Expand Down Expand Up @@ -316,13 +314,12 @@ pub fn expected_current_slot(now: SystemTime, genesis_time: u64) -> u64 {
pub fn verify_sync_committee_signture(
pks: &[PublicKey],
attested_header: &Header,
signature: &SignatureBytes,
signature: &Signature,
fork_data_root: B256,
) -> bool {
let pks: Vec<&PublicKey> = pks.iter().collect();
let header_root = attested_header.clone().tree_hash_root();
let header_root = attested_header.tree_hash_root();
let signing_root = compute_committee_sign_root(header_root, fork_data_root);
is_aggregate_valid(signature, signing_root.as_ref(), &pks)
signature.verify(signing_root.as_slice(), pks)
}

pub fn compute_committee_sign_root(header: B256, fork_data_root: B256) -> B256 {
Expand Down
2 changes: 1 addition & 1 deletion consensus-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ pub mod errors;
pub mod types;
pub mod utils;

pub mod consensus_core;
mod consensus_core;
pub use crate::consensus_core::*;
40 changes: 40 additions & 0 deletions consensus-core/src/types/bls.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use milagro_bls::{AggregateSignature, PublicKey as MilagroPK};
use serde::{Deserialize, Serialize};
use ssz_derive::{Decode, Encode};
use tree_hash_derive::TreeHash;

use super::bytes::ByteVector;

#[derive(Debug, Clone, Default, Serialize, Deserialize, Encode, Decode, TreeHash)]
#[ssz(struct_behaviour = "transparent")]
#[serde(transparent)]
pub struct PublicKey {
inner: ByteVector<typenum::U48>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, Encode, Decode, TreeHash)]
#[ssz(struct_behaviour = "transparent")]
#[serde(transparent)]
pub struct Signature {
inner: ByteVector<typenum::U96>,
}

impl Signature {
pub fn verify(&self, msg: &[u8], pks: &[PublicKey]) -> bool {
if let Ok(agg) = AggregateSignature::from_bytes(&self.inner.inner) {
let pks_res = pks
.iter()
.map(|pk| MilagroPK::from_bytes(&pk.inner.inner))
.collect::<Result<Vec<_>, _>>();

if let Ok(pks) = pks_res {
let pks = pks.iter().collect::<Vec<_>>();
agg.fast_aggregate_verify(msg, &pks)
} else {
false
}
} else {
false
}
}
}
File renamed without changes.
34 changes: 18 additions & 16 deletions consensus-core/src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,18 @@ use ssz_types::{serde_utils::quoted_u64_var_list, BitList, BitVector, FixedVecto
use superstruct::superstruct;
use tree_hash_derive::TreeHash;

use self::primitives::{ByteList, ByteVector};
use self::{
bls::{PublicKey, Signature},
bytes::{ByteList, ByteVector},
};

pub mod primitives;
pub mod bls;
pub mod bytes;
mod serde_utils;
mod utils;

pub type LogsBloom = ByteVector<typenum::U256>;
pub type BLSPubKey = ByteVector<typenum::U48>;
pub type KZGCommitment = ByteVector<typenum::U48>;
pub type SignatureBytes = ByteVector<typenum::U96>;
pub type Transaction = ByteList<typenum::U1073741824>;

#[derive(Debug, Default, Clone, Deserialize)]
Expand Down Expand Up @@ -51,7 +53,7 @@ pub struct BeaconBlock {
#[ssz(enum_behaviour = "transparent")]
#[tree_hash(enum_behaviour = "transparent")]
pub struct BeaconBlockBody {
randao_reveal: SignatureBytes,
randao_reveal: Signature,
eth1_data: Eth1Data,
graffiti: B256,
proposer_slashings: VariableList<ProposerSlashing, typenum::U16>,
Expand All @@ -76,14 +78,14 @@ impl Default for BeaconBlockBody {
#[derive(Default, Clone, Debug, Encode, TreeHash, Deserialize)]
pub struct SignedBlsToExecutionChange {
message: BlsToExecutionChange,
signature: SignatureBytes,
signature: Signature,
}

#[derive(Default, Clone, Debug, Encode, TreeHash, Deserialize)]
pub struct BlsToExecutionChange {
#[serde(with = "serde_utils::u64")]
validator_index: u64,
from_bls_pubkey: BLSPubKey,
from_bls_pubkey: PublicKey,
to_execution_address: Address,
}

Expand Down Expand Up @@ -154,7 +156,7 @@ pub struct ProposerSlashing {
#[derive(Deserialize, Debug, Default, Encode, TreeHash, Clone)]
struct SignedBeaconBlockHeader {
message: BeaconBlockHeader,
signature: SignatureBytes,
signature: Signature,
}

#[derive(Deserialize, Debug, Default, Encode, TreeHash, Clone)]
Expand All @@ -179,14 +181,14 @@ struct IndexedAttestation {
#[serde(with = "quoted_u64_var_list")]
attesting_indices: VariableList<u64, typenum::U2048>,
data: AttestationData,
signature: SignatureBytes,
signature: Signature,
}

#[derive(Deserialize, Debug, Encode, TreeHash, Clone)]
pub struct Attestation {
aggregation_bits: BitList<typenum::U2048>,
data: AttestationData,
signature: SignatureBytes,
signature: Signature,
}

#[derive(Deserialize, Debug, Default, Encode, TreeHash, Clone)]
Expand All @@ -210,7 +212,7 @@ struct Checkpoint {
#[derive(Deserialize, Debug, Default, Encode, TreeHash, Clone)]
pub struct SignedVoluntaryExit {
message: VoluntaryExit,
signature: SignatureBytes,
signature: Signature,
}

#[derive(Deserialize, Debug, Default, Encode, TreeHash, Clone)]
Expand All @@ -229,11 +231,11 @@ pub struct Deposit {

#[derive(Deserialize, Default, Debug, Encode, TreeHash, Clone)]
struct DepositData {
pubkey: BLSPubKey,
pubkey: PublicKey,
withdrawal_credentials: B256,
#[serde(with = "serde_utils::u64")]
amount: u64,
signature: SignatureBytes,
signature: Signature,
}

#[derive(Deserialize, Debug, Default, Encode, TreeHash, Clone)]
Expand Down Expand Up @@ -300,14 +302,14 @@ pub struct Header {

#[derive(Debug, Clone, Default, Encode, TreeHash, Serialize, Deserialize)]
pub struct SyncCommittee {
pub pubkeys: FixedVector<BLSPubKey, typenum::U512>,
pub aggregate_pubkey: BLSPubKey,
pub pubkeys: FixedVector<PublicKey, typenum::U512>,
pub aggregate_pubkey: PublicKey,
}

#[derive(Serialize, Deserialize, Debug, Clone, Default, Encode, TreeHash)]
pub struct SyncAggregate {
pub sync_committee_bits: BitVector<typenum::U512>,
pub sync_committee_signature: SignatureBytes,
pub sync_committee_signature: Signature,
}

pub struct GenericUpdate {
Expand Down
14 changes: 2 additions & 12 deletions consensus-core/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use alloy::primitives::B256;
use milagro_bls::{AggregateSignature, PublicKey};
use sha2::{Digest, Sha256};
use ssz_types::FixedVector;
use tree_hash::TreeHash;
use tree_hash_derive::TreeHash;

use crate::types::{Header, SignatureBytes};
use crate::types::Header;

pub fn calc_sync_period(slot: u64) -> u64 {
// 32 slots per epoch
Expand All @@ -14,18 +13,9 @@ pub fn calc_sync_period(slot: u64) -> u64 {
epoch / 256
}

pub fn is_aggregate_valid(sig_bytes: &SignatureBytes, msg: &[u8], pks: &[&PublicKey]) -> bool {
let sig_res = AggregateSignature::from_bytes(&sig_bytes.inner);

match sig_res {
Ok(sig) => sig.fast_aggregate_verify(msg, pks),
Err(_) => false,
}
}

pub fn is_proof_valid<L: TreeHash>(
attested_header: &Header,
leaf_object: &mut L,
leaf_object: &L,
branch: &[B256],
depth: usize,
index: usize,
Expand Down
17 changes: 10 additions & 7 deletions consensus/src/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ impl<R: ConsensusRpc> Inner<R> {
}

pub async fn bootstrap(&mut self, checkpoint: B256) -> Result<()> {
let mut bootstrap = self
let bootstrap = self
.rpc
.get_bootstrap(checkpoint)
.await
Expand All @@ -374,7 +374,7 @@ impl<R: ConsensusRpc> Inner<R> {

let committee_valid = is_current_committee_proof_valid(
&bootstrap.header,
&mut bootstrap.current_sync_committee,
&bootstrap.current_sync_committee,
&bootstrap.current_sync_committee_branch,
);

Expand Down Expand Up @@ -542,7 +542,10 @@ mod tests {
};
use alloy::primitives::b256;
use consensus_core::errors::ConsensusError;
use consensus_core::types::{BLSPubKey, Header, SignatureBytes};
use consensus_core::types::{
bls::{PublicKey, Signature},
Header,
};

use config::{networks, Config};
use tokio::sync::{mpsc::channel, watch};
Expand Down Expand Up @@ -606,7 +609,7 @@ mod tests {
.unwrap();

let mut update = updates[0].clone();
update.next_sync_committee.pubkeys[0] = BLSPubKey::default();
update.next_sync_committee.pubkeys[0] = PublicKey::default();

let err = client.verify_update(&update).err().unwrap();
assert_eq!(
Expand Down Expand Up @@ -646,7 +649,7 @@ mod tests {
.unwrap();

let mut update = updates[0].clone();
update.sync_aggregate.sync_committee_signature = SignatureBytes::default();
update.sync_aggregate.sync_committee_signature = Signature::default();

let err = client.verify_update(&update).err().unwrap();
assert_eq!(
Expand Down Expand Up @@ -683,7 +686,7 @@ mod tests {
let client = get_client(false, true).await;

let mut update = client.rpc.get_finality_update().await.unwrap();
update.sync_aggregate.sync_committee_signature = SignatureBytes::default();
update.sync_aggregate.sync_committee_signature = Signature::default();

let err = client.verify_finality_update(&update).err().unwrap();
assert_eq!(
Expand All @@ -705,7 +708,7 @@ mod tests {
let client = get_client(false, true).await;

let mut update = client.rpc.get_optimistic_update().await.unwrap();
update.sync_aggregate.sync_committee_signature = SignatureBytes::default();
update.sync_aggregate.sync_committee_signature = Signature::default();

let err = client.verify_optimistic_update(&update).err().unwrap();
assert_eq!(
Expand Down

0 comments on commit bb38e21

Please sign in to comment.