Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ members = [
"modules/consensus/tendermint/prover",
"modules/consensus/tendermint/primitives",
"modules/consensus/tendermint/ics23-primitives",
"modules/consensus/beacon-kit-verifier",
"modules/trees/ethereum",
"modules/pallets/mmr",
"modules/pallets/mmr/primitives",
Expand Down Expand Up @@ -258,6 +259,7 @@ tendermint-verifier = { path = "./modules/consensus/tendermint/verifier", defaul
tendermint-primitives = { path = "./modules/consensus/tendermint/primitives", default-features = false }
tendermint-prover = { path = "./modules/consensus/tendermint/prover", default-features = false }
tendermint-ics23-primitives = { path = "./modules/consensus/tendermint/ics23-primitives", default-features = false }
beacon-kit-verifier = { path = "./modules/consensus/beacon-kit-verifier", default-features = false }

# consensus clients
ismp-bsc = { path = "./modules/ismp/clients/bsc", default-features = false }
Expand Down
36 changes: 36 additions & 0 deletions modules/consensus/beacon-kit-verifier/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
[package]
name = "beacon-kit-verifier"
version = "0.1.1"
edition = "2021"
authors = ["Polytope Labs"]
publish = false

[dependencies]
hex-literal = { workspace = true }
sync-committee-primitives = { workspace = true, default-features = false }
bsc-verifier = { workspace = true, default-features = false }
log = { workspace = true, default-features = false }
ssz-rs = { git = "https://github.com/polytope-labs/ssz-rs", branch = "main", default-features = false }
bls = { workspace = true }
codec = { workspace = true, features = ["derive"] }
primitive-types = { workspace = true, features = [
"serde_no_std",
"impl-codec",
] }
thiserror = { workspace = true}

[features]
default = ["std"]
std = [
"ssz-rs/std",
"ssz-rs/default",
"ssz-rs/serde",
'codec/std',
"log/std",
"primitive-types/std",
"sync-committee-primitives/std",
"log/std",
"bls/std",
"bsc-verifier/std"
]

29 changes: 29 additions & 0 deletions modules/consensus/beacon-kit-verifier/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#![cfg_attr(not(feature = "std"), no_std)]

use thiserror::Error;

#[derive(Debug, Error)]
pub enum BeaconKitError {
#[error("Not enough signers to meet consensus threshold")]
InsufficientSigners,
#[error("Update contains a signer not present in the trusted validator set")]
UnknownSigner,
#[error("Failed to compute domain")]
DomainComputationFailed,
#[error("Failed to compute signing root")]
SigningRootComputationFailed,
#[error("Failed to verify aggregate BLS signature")]
SignatureVerificationFailed,
#[error("Failed to hash execution payload")]
ExecutionPayloadHashFailed,
#[error("Invalid Execution Payload Merkle Proof")]
InvalidExecutionPayloadProof,
#[error("Failed to hash validator set")]
ValidatorSetHashFailed,
#[error("Invalid Validator Set Merkle Proof")]
InvalidValidatorSetProof,
#[error("Failed to create SSZ List from validators")]
SszListCreationFailure,
#[error("Invalid public key provided")]
InvalidPublicKey,
}
136 changes: 136 additions & 0 deletions modules/consensus/beacon-kit-verifier/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
// Copyright (C) 2022 Polytope Labs.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
extern crate core;

mod error;
pub mod primitives;

use crate::error::BeaconKitError;
use alloc::vec::Vec;
use bsc_verifier::aggregate_public_keys;
use primitive_types::H256;
use primitives::{BeaconKitUpdate, Config, VerificationResult};
use ssz_rs::{prelude::*, Merkleized};
use sync_committee_primitives::{
constants::{BlsPublicKey, Root, VALIDATOR_REGISTRY_LIMIT},
domains::DomainType,
util::{compute_domain, compute_signing_root},
};

/// Verifies a Beacon Kit light client update
pub fn verify_beacon_kit_header<C: Config>(
current_validators: &Vec<BlsPublicKey>,
mut update: BeaconKitUpdate,
) -> Result<VerificationResult, BeaconKitError> {
let signers_set_len = update.signers.len();
let total_validators = current_validators.len();
let threshold = (2 * total_validators / 3) + 1;

if signers_set_len < threshold {
return Err(BeaconKitError::InsufficientSigners);
}

if update.signers.iter().any(|signer| !current_validators.contains(signer)) {
return Err(BeaconKitError::UnknownSigner);
}

let domain = compute_domain(
DomainType::BeaconProposer,
Some(C::BEACON_KIT_FORK_VERSION),
Some(Root::from_bytes(C::GENESIS_VALIDATORS_ROOT)),
C::GENESIS_FORK_VERSION,
)
.map_err(|_| BeaconKitError::DomainComputationFailed)?;

let mut header = update.beacon_header.clone();
let signing_root = compute_signing_root(&mut header, domain)
.map_err(|_| BeaconKitError::SigningRootComputationFailed)?;

let aggregate_pubkey = aggregate_public_keys(&update.signers);

let verify_sig = bls::verify(
&aggregate_pubkey,
&signing_root.as_bytes().to_vec(),
&update.signature.to_vec(),
&bls::DST_ETHEREUM.as_bytes().to_vec(),
);

if !verify_sig {
return Err(BeaconKitError::SignatureVerificationFailed)?
}

let execution_payload_root = update
.execution_payload
.hash_tree_root()
.map_err(|_| BeaconKitError::ExecutionPayloadHashFailed)?;
let execution_payload_proof_nodes: Vec<Node> = update
.execution_payload_proof
.iter()
.map(|byte| Node::from_bytes(byte.as_ref().try_into().expect("Infallible")))
.collect();

let is_payload_valid = is_valid_merkle_branch(
&execution_payload_root,
execution_payload_proof_nodes.iter(),
C::EXECTION_PAYLOAD_INDEX_LOG2,
C::EXECUTION_PAYLOAD_INDEX,
&update.beacon_header.state_root,
);

if !is_payload_valid {
return Err(BeaconKitError::InvalidExecutionPayloadProof)?
}

let next_validators = if let Some(validator_proof) = update.validator_set_proof {
let mut validators_list = List::<BlsPublicKey, VALIDATOR_REGISTRY_LIMIT>::try_from(
validator_proof.validators.clone(),
)
.map_err(|_| BeaconKitError::SszListCreationFailure)?;

let validators_root = validators_list
.hash_tree_root()
.map_err(|_| BeaconKitError::ValidatorSetHashFailed)?;
let validator_proof_nodes: Vec<Node> = validator_proof
.proof
.iter()
.map(|byte| Node::from_bytes(byte.as_ref().try_into().expect("Infallible")))
.collect();

let is_validator_proof_valid = is_valid_merkle_branch(
&validators_root,
validator_proof_nodes.iter(),
C::VALIDATOR_REGISTRY_INDEX_LOG2,
C::VALIDATOR_REGSITRY_INDEX,
&update.beacon_header.state_root,
);

if !is_validator_proof_valid {
return Err(BeaconKitError::InvalidValidatorSetProof)?;
}

Some(validator_proof.validators)
} else {
None
};

Ok(VerificationResult {
hash: H256::from_slice(signing_root.as_bytes()),
finalized_header: update.beacon_header,
next_validators,
})
}
105 changes: 105 additions & 0 deletions modules/consensus/beacon-kit-verifier/src/primitives.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// Copyright (C) 2022 Polytope Labs.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![cfg_attr(not(feature = "std"), no_std)]

use alloc::vec::Vec;
use codec::{Decode, Encode};
use hex_literal::hex;
use primitive_types::H256;
use ssz_rs::prelude::*;
use sync_committee_primitives::{
consensus_types::{BeaconBlockHeader, ExecutionPayloadHeader},
constants::{BlsPublicKey, BlsSignature},
};

const BYTES_PER_LOGS_BLOOM: usize = 256;
const MAX_EXTRA_DATA_BYTES: usize = 32;

pub trait Config: Clone + Send + Sync {
const EXECUTION_PAYLOAD_INDEX: usize;
const EXECTION_PAYLOAD_INDEX_LOG2: usize;
const VALIDATOR_REGSITRY_INDEX: usize;
const VALIDATOR_REGISTRY_INDEX_LOG2: usize;
const GENESIS_VALIDATORS_ROOT: [u8; 32];
const GENESIS_FORK_VERSION: [u8; 4];
const BEACON_KIT_FORK_VERSION: [u8; 4];
}

/// Config for the Berachain Bepolia Testnet
#[derive(Clone, Default)]
pub struct BepoliaConfig;

impl Config for BepoliaConfig {
const EXECUTION_PAYLOAD_INDEX: usize = 25;
const EXECTION_PAYLOAD_INDEX_LOG2: usize = 5;
const VALIDATOR_REGSITRY_INDEX: usize = 11;
const VALIDATOR_REGISTRY_INDEX_LOG2: usize = 5;
const GENESIS_VALIDATORS_ROOT: [u8; 32] =
hex!("3cbcf75b02fe4750c592f1c1ff8b5500a74406f80f038e9ff250e2e294c5615e");
const GENESIS_FORK_VERSION: [u8; 4] = hex!("04000000");
const BEACON_KIT_FORK_VERSION: [u8; 4] = hex!("05010000");
}

/// Config for the Berachain mainnet
#[derive(Clone, Default)]
pub struct BerachainConfig;

impl Config for BerachainConfig {
const EXECUTION_PAYLOAD_INDEX: usize = 25;
const EXECTION_PAYLOAD_INDEX_LOG2: usize = 5;
const VALIDATOR_REGSITRY_INDEX: usize = 11;
const VALIDATOR_REGISTRY_INDEX_LOG2: usize = 5;
const GENESIS_VALIDATORS_ROOT: [u8; 32] =
hex!("df609e3b062842c6425ff716aec2d2092c46455d9b2e1a2c9e32c6ba63ff0bda");
const GENESIS_FORK_VERSION: [u8; 4] = hex!("04000000");
const BEACON_KIT_FORK_VERSION: [u8; 4] = hex!("05010000");
}

/// Represents a light client update for Beacon Kit consensus
#[derive(Debug, Clone, Encode, Decode)]
pub struct BeaconKitUpdate {
/// The header of the Beacon Block being verified
pub beacon_header: BeaconBlockHeader,
/// The aggregate BLS signature covering the header
pub signature: BlsSignature,
/// The public keys of the validators that signed this update
pub signers: Vec<BlsPublicKey>,
/// The execution payload header to be verified against the Beacon state
pub execution_payload: ExecutionPayloadHeader<BYTES_PER_LOGS_BLOOM, MAX_EXTRA_DATA_BYTES>,
/// The SSZ Merkle proof of the execution payload
pub execution_payload_proof: Vec<H256>,
/// Optional proof for the validator set, for auhtority set rotation
pub validator_set_proof: Option<ValidatorSetProof>,
}

/// Proof data for verifying the next validator set
#[derive(Debug, Clone, Encode, Decode)]
pub struct ValidatorSetProof {
/// The list of validators in the new set
pub validators: Vec<BlsPublicKey>,
/// The SSZ Merkle proof of the validator registry
pub proof: Vec<H256>,
}

/// The result of a successful light client verification
#[derive(Debug, Clone, Encode, Decode)]
pub struct VerificationResult {
/// The hash of the verified block (signing root)
pub hash: H256,
/// The verified beacon block header
pub finalized_header: BeaconBlockHeader,
/// The next authority set for a verified rotation
pub next_validators: Option<Vec<BlsPublicKey>>,
}
Loading