Skip to content

Commit

Permalink
Merge pull request #234 from chainbound/naman/chore/update-constraint…
Browse files Browse the repository at this point in the history
…s-api

chore(sidecar): use validator pubkey instead of index
  • Loading branch information
thedevbirb authored Sep 23, 2024
2 parents aa3c94d + a7f022e commit 5cbf944
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 39 deletions.
4 changes: 2 additions & 2 deletions bolt-sidecar/src/crypto/bls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ pub trait SignableBLS {
///
/// Note: The default implementation should be used where possible.
fn verify(&self, signature: &Signature, pubkey: &BlsPublicKey) -> bool {
signature.verify(false, &self.digest(), BLS_DST_PREFIX, &[], pubkey, true)
== BLST_ERROR::BLST_SUCCESS
signature.verify(false, &self.digest(), BLS_DST_PREFIX, &[], pubkey, true) ==
BLST_ERROR::BLST_SUCCESS
}
}

Expand Down
4 changes: 2 additions & 2 deletions bolt-sidecar/src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ impl<C: StateFetcher, BLS: SignerBLS, ECDSA: SignerECDSA> SidecarDriver<C, BLS,

let start = Instant::now();

let validator_index = match self.consensus.validate_request(&request) {
let validator_pubkey = match self.consensus.validate_request(&request) {
Ok(index) => index,
Err(err) => {
error!(?err, "Consensus: failed to validate request");
Expand Down Expand Up @@ -220,7 +220,7 @@ impl<C: StateFetcher, BLS: SignerBLS, ECDSA: SignerECDSA> SidecarDriver<C, BLS,

// parse the request into constraints and sign them
let slot = inclusion_request.slot;
let message = ConstraintsMessage::build(validator_index, inclusion_request);
let message = ConstraintsMessage::build(validator_pubkey, inclusion_request);
let signed_constraints = match self.constraint_signer.sign(&message.digest()).await {
Ok(signature) => SignedConstraints { message, signature },
Err(err) => {
Expand Down
28 changes: 12 additions & 16 deletions bolt-sidecar/src/primitives/constraint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use alloy::{
primitives::keccak256,
signers::k256::sha2::{Digest, Sha256},
};
use ethereum_consensus::crypto::PublicKey as BlsPublicKey;
use secp256k1::Message;
use serde::{Deserialize, Serialize};

Expand All @@ -16,7 +17,7 @@ use super::{FullTransaction, InclusionRequest};
impl SignableECDSA for ConstraintsMessage {
fn digest(&self) -> Message {
let mut data = Vec::new();
data.extend_from_slice(&self.validator_index.to_le_bytes());
data.extend_from_slice(&self.pubkey.to_vec());
data.extend_from_slice(&self.slot.to_le_bytes());

let mut constraint_bytes = Vec::new();
Expand Down Expand Up @@ -50,8 +51,8 @@ pub struct SignedConstraints {
/// Reference: https://chainbound.github.io/bolt-docs/api/builder#constraints
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
pub struct ConstraintsMessage {
/// The validator index of the proposer sidecar.
pub validator_index: u64,
/// The validator pubkey of the proposer sidecar.
pub pubkey: BlsPublicKey,
/// The consensus slot at which the constraints are valid
pub slot: u64,
/// Indicates whether these constraints are only valid on the top of the block.
Expand All @@ -64,17 +65,17 @@ pub struct ConstraintsMessage {

impl ConstraintsMessage {
/// Builds a constraints message from an inclusion request and metadata
pub fn build(validator_index: u64, request: InclusionRequest) -> Self {
pub fn build(pubkey: BlsPublicKey, request: InclusionRequest) -> Self {
let constraints = request.txs;

Self { validator_index, slot: request.slot, top: false, constraints }
Self { pubkey, slot: request.slot, top: false, constraints }
}
}

impl SignableBLS for ConstraintsMessage {
fn digest(&self) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(self.validator_index.to_le_bytes());
hasher.update(self.pubkey.to_vec());
hasher.update(self.slot.to_le_bytes());
hasher.update((self.top as u8).to_le_bytes());

Expand Down Expand Up @@ -109,19 +110,14 @@ mod tests {

#[test]
fn test_bls_digest() {
let mut rng = rand::thread_rng();

// Generate random values for the `ConstraintsMessage` fields
let validator_index = random_u64(&mut rng);
let slot = random_u64(&mut rng);
let pubkey = BlsPublicKey::default();
let slot = 0;
let top = false;
let constraints = random_constraints(1); // Generate 'n' random constraints

// Create a random `ConstraintsMessage`
let mut message = ConstraintsMessage { validator_index, slot, top, constraints };
message.validator_index = 0;
message.slot = 0;
message.top = false;
let message = ConstraintsMessage { pubkey, slot, top, constraints };

// Compute tree hash root
let digest = SignableBLS::digest(&message);
Expand All @@ -135,13 +131,13 @@ mod tests {
let mut rng = rand::thread_rng();

// Generate random values for the `ConstraintsMessage` fields
let validator_index = random_u64(&mut rng);
let pubkey = BlsPublicKey::default();
let slot = random_u64(&mut rng);
let top = false;
let constraints = random_constraints(2); // Generate 'n' random constraints

// Create a random `ConstraintsMessage`
let message = ConstraintsMessage { validator_index, slot, top, constraints };
let message = ConstraintsMessage { pubkey, slot, top, constraints };

// Serialize the `ConstraintsMessage` to JSON
let json = serde_json::to_string(&message).unwrap();
Expand Down
8 changes: 4 additions & 4 deletions bolt-sidecar/src/primitives/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -426,8 +426,8 @@ pub struct SignedDelegation {

#[derive(Debug, Clone, Serialize)]
pub struct DelegationMessage {
pub validator_index: u64,
pub pubkey: BlsPublicKey,
pub validator_pubkey: BlsPublicKey,
pub delegatee_pubkey: BlsPublicKey,
}

#[derive(Debug, Clone, Serialize)]
Expand All @@ -438,6 +438,6 @@ pub struct SignedRevocation {

#[derive(Debug, Clone, Serialize)]
pub struct RevocationMessage {
pub validator_index: u64,
pub pubkey: BlsPublicKey,
pub validator_pubkey: BlsPublicKey,
pub delegatee_pubkey: BlsPublicKey,
}
25 changes: 14 additions & 11 deletions bolt-sidecar/src/state/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::{
};

use beacon_api_client::{mainnet::Client, ProposerDuty};
use ethereum_consensus::phase0::mainnet::SLOTS_PER_EPOCH;
use ethereum_consensus::{crypto::PublicKey as BlsPublicKey, phase0::mainnet::SLOTS_PER_EPOCH};
use tracing::debug;

use super::CommitmentDeadline;
Expand Down Expand Up @@ -93,8 +93,12 @@ impl ConsensusState {
/// 1. The target slot is one of our proposer slots. (TODO)
/// 2. The request hasn't passed the slot deadline.
///
/// If the request is valid, it returns the validator public key for the slot.
/// TODO: Integrate with the registry to check if we are registered.
pub fn validate_request(&self, request: &CommitmentRequest) -> Result<u64, ConsensusError> {
pub fn validate_request(
&self,
request: &CommitmentRequest,
) -> Result<BlsPublicKey, ConsensusError> {
let CommitmentRequest::Inclusion(req) = request;

// Check if the slot is in the current epoch
Expand All @@ -110,9 +114,9 @@ impl ConsensusState {
}

// Find the validator index for the given slot
let validator_index = self.find_validator_index_for_slot(req.slot)?;
let validator_pubkey = self.find_validator_pubkey_for_slot(req.slot)?;

Ok(validator_index)
Ok(validator_pubkey)
}

/// Update the latest head and fetch the relevant data from the beacon chain.
Expand Down Expand Up @@ -155,16 +159,15 @@ impl ConsensusState {
Ok(())
}

/// Filters the proposer duties and returns the validator index for a given slot
/// if it doesn't exists then returns error.
fn find_validator_index_for_slot(&self, slot: u64) -> Result<u64, ConsensusError> {
/// Finds the validator public key for the given slot from the proposer duties.
fn find_validator_pubkey_for_slot(&self, slot: u64) -> Result<BlsPublicKey, ConsensusError> {
self.epoch
.proposer_duties
.iter()
.find(|&duty| {
duty.slot == slot && self.validator_indexes.contains(duty.validator_index as u64)
})
.map(|duty| duty.validator_index as u64)
.map(|duty| duty.public_key.clone())
.ok_or(ConsensusError::ValidatorNotFound)
}
}
Expand Down Expand Up @@ -202,12 +205,12 @@ mod tests {
};

// Test finding a valid slot
assert_eq!(state.find_validator_index_for_slot(1).unwrap(), 100);
assert_eq!(state.find_validator_index_for_slot(3).unwrap(), 102);
assert_eq!(state.find_validator_pubkey_for_slot(1).unwrap(), Default::default());
assert_eq!(state.find_validator_pubkey_for_slot(3).unwrap(), Default::default());

// Test finding an invalid slot (not in proposer duties)
assert!(matches!(
state.find_validator_index_for_slot(4),
state.find_validator_pubkey_for_slot(4),
Err(ConsensusError::ValidatorNotFound)
));
}
Expand Down
11 changes: 7 additions & 4 deletions bolt-sidecar/src/state/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -723,7 +723,10 @@ mod tests {

assert!(state.validate_request(&mut request).await.is_ok());

let message = ConstraintsMessage::build(0, request.as_inclusion_request().unwrap().clone());
let message = ConstraintsMessage::build(
Default::default(),
request.as_inclusion_request().unwrap().clone(),
);
let signature = signer.sign(&message.digest()).await?;
let signed_constraints = SignedConstraints { message, signature };
state.add_constraint(10, signed_constraints);
Expand Down Expand Up @@ -838,7 +841,7 @@ mod tests {
assert!(state.validate_request(&mut request).await.is_ok());

let bls_signer = Signer::random();
let message = ConstraintsMessage::build(0, inclusion_request);
let message = ConstraintsMessage::build(Default::default(), inclusion_request);
let signature = bls_signer.sign(&message.digest()).await.unwrap();
let signed_constraints = SignedConstraints { message, signature };

Expand Down Expand Up @@ -886,7 +889,7 @@ mod tests {
assert!(state.validate_request(&mut request).await.is_ok());

let bls_signer = Signer::random();
let message = ConstraintsMessage::build(0, inclusion_request);
let message = ConstraintsMessage::build(Default::default(), inclusion_request);
let signature = bls_signer.sign(&message.digest()).await.unwrap();
let signed_constraints = SignedConstraints { message, signature };

Expand Down Expand Up @@ -932,7 +935,7 @@ mod tests {
assert!(state.validate_request(&mut request).await.is_ok());

let bls_signer = Signer::random();
let message = ConstraintsMessage::build(0, inclusion_request);
let message = ConstraintsMessage::build(Default::default(), inclusion_request);
let signature = bls_signer.sign(&message.digest()).await.unwrap();
let signed_constraints = SignedConstraints { message, signature };

Expand Down

0 comments on commit 5cbf944

Please sign in to comment.