Skip to content

Commit

Permalink
chore: introduce endianness BytesBitIterator
Browse files Browse the repository at this point in the history
Signed-off-by: aeryz <[email protected]>
  • Loading branch information
aeryz committed Mar 1, 2025
1 parent 9d94515 commit 038393b
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 14 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

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

10 changes: 5 additions & 5 deletions lib/aptos-verifier/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use unionlabs::{
validator_verifier::ValidatorVerifier,
},
primitives::{encoding::HexPrefixed, H256, H384, H768},
BytesBitIterator,
BytesBitIteratorBE,
};

pub(crate) const MAX_ACCUMULATOR_PROOF_DEPTH: usize = 63;
Expand All @@ -41,9 +41,9 @@ pub trait BlsVerify {
///
/// * `current_validator_verifier`: The validator verifier for the current(trusted) epoch.
/// * `trusted_state`: Currently trusted `LedgerInfo`. Note that if there's any epoch change, it **MUST** start
/// from the current epoch + 1.
/// from the current epoch + 1.
/// * `state_proof`: Proof of state transition. Note that the function expects epoch changes to be in an ascending
/// order respective to the epoch number.
/// order respective to the epoch number.
/// * `bls_verifier`: BLS verifier
pub fn verify_state_proof<V: BlsVerify>(
current_validator_verifier: &ValidatorVerifier,
Expand Down Expand Up @@ -88,7 +88,7 @@ pub fn verify_ledger_info<V: BlsVerify>(
bls_verifier: &V,
) -> Result<(), Error> {
// Self::check_num_of_voters(self.len() as u16, multi_signature.get_signers_bitvec())?;
let (pub_keys, _) = BytesBitIterator::new(&ledger_info.signatures.validator_bitmask.inner)
let (pub_keys, _) = BytesBitIteratorBE::new(&ledger_info.signatures.validator_bitmask.inner)
.enumerate()
.filter(|(_, is_true)| *is_true)
.map(|(i, _)| {
Expand Down Expand Up @@ -214,7 +214,7 @@ pub fn verify_existence_proof(
.iter()
.rev()
.zip(
BytesBitIterator::new(&element_key)
BytesBitIteratorBE::new(&element_key)
.rev()
.skip(256 - proof.siblings.len()),
)
Expand Down
6 changes: 3 additions & 3 deletions lib/ethereum-sync-protocol/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use typenum::Unsigned;
use unionlabs::{
ensure,
primitives::{H256, H384, H768},
BytesBitIterator,
BytesBitIteratorLE,
};

use crate::{
Expand Down Expand Up @@ -73,7 +73,7 @@ pub fn validate_light_client_update<C: ChainSpec, V: BlsVerify>(
) -> Result<(), Error> {
// verify that the sync committee has sufficient participants
let sync_aggregate = &update.sync_aggregate;
let set_bits = BytesBitIterator::new(&sync_aggregate.sync_committee_bits)
let set_bits = BytesBitIteratorLE::new(&sync_aggregate.sync_committee_bits)
.filter(|included| *included)
.count();
ensure(
Expand Down Expand Up @@ -209,7 +209,7 @@ pub fn validate_light_client_update<C: ChainSpec, V: BlsVerify>(

// It's not mandatory for all of the members of the sync committee to participate. So we are extracting the
// public keys of the ones who participated.
let participant_pubkeys = BytesBitIterator::new(&sync_aggregate.sync_committee_bits)
let participant_pubkeys = BytesBitIteratorLE::new(&sync_aggregate.sync_committee_bits)
.zip(sync_committee.pubkeys.iter())
.filter_map(|(included, pubkey)| if included { Some(pubkey) } else { None })
.collect::<Vec<_>>();
Expand Down
2 changes: 2 additions & 0 deletions lib/unionlabs/src/aptos/ledger_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@ pub enum LedgerInfoWithSignatures {
}

impl LedgerInfoWithSignatures {
#[must_use]
pub fn ledger_info(&self) -> &LedgerInfo {
let Self::V0(ledger_info) = self;
&ledger_info.ledger_info
}

#[must_use]
pub fn signatures(&self) -> &AggregateSignature {
let Self::V0(ledger_info) = self;
&ledger_info.signatures
Expand Down
37 changes: 32 additions & 5 deletions lib/unionlabs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ extern crate alloc;
use core::{
fmt::{self, Debug, Display},
iter,
marker::PhantomData,
ptr::addr_of,
str::FromStr,
};
Expand Down Expand Up @@ -260,17 +261,43 @@ impl<T: core::error::Error> Display for ErrorReporter<T> {
}
}

pub trait BitIndex {
/// Get the 'i'th bit
fn index_of(i: usize) -> usize;
}

pub struct LittleEndianBitIndex;

impl BitIndex for LittleEndianBitIndex {
fn index_of(i: usize) -> usize {
i % 8
}
}

pub struct BigEndianBitIndex;

impl BitIndex for BigEndianBitIndex {
fn index_of(i: usize) -> usize {
7 - i % 8
}
}

pub type BytesBitIteratorLE<'a> = BytesBitIterator<'a, LittleEndianBitIndex>;
pub type BytesBitIteratorBE<'a> = BytesBitIterator<'a, BigEndianBitIndex>;

#[must_use = "constructing an iterator has no effect"]
pub struct BytesBitIterator<'a> {
pub struct BytesBitIterator<'a, E: BitIndex> {
bz: &'a [u8],
pos: core::ops::Range<usize>,
_marker: PhantomData<E>,
}

impl<'a> BytesBitIterator<'a> {
impl<'a, E: BitIndex> BytesBitIterator<'a, E> {
pub fn new(bz: &'a impl AsRef<[u8]>) -> Self {
BytesBitIterator {
bz: bz.as_ref(),
pos: (0..bz.as_ref().len() * 8),
_marker: PhantomData,
}
}

Expand All @@ -279,12 +306,12 @@ impl<'a> BytesBitIterator<'a> {
// debug_assert_eq!(self.hash_bytes.len(), Hash::LENGTH); // invariant
// debug_assert_lt!(index, Hash::LENGTH_IN_BITS); // assumed precondition
let pos = index / 8;
let bit = index % 8;
let bit = E::index_of(index);
(self.bz[pos] >> bit) & 1 != 0
}
}

impl core::iter::Iterator for BytesBitIterator<'_> {
impl<E: BitIndex> core::iter::Iterator for BytesBitIterator<'_, E> {
type Item = bool;

fn next(&mut self) -> Option<Self::Item> {
Expand All @@ -296,7 +323,7 @@ impl core::iter::Iterator for BytesBitIterator<'_> {
}
}

impl core::iter::DoubleEndedIterator for BytesBitIterator<'_> {
impl<E: BitIndex> core::iter::DoubleEndedIterator for BytesBitIterator<'_, E> {
fn next_back(&mut self) -> Option<Self::Item> {
self.pos.next_back().map(|x| self.get_bit(x))
}
Expand Down

0 comments on commit 038393b

Please sign in to comment.