From 74dea4ff6470cf5ce23db73040451aab1e540d2e Mon Sep 17 00:00:00 2001 From: Tom Grosso Date: Mon, 14 Oct 2024 16:28:19 -0300 Subject: [PATCH] Implement trailing zeros --- stwo_cairo_verifier/src/channel.cairo | 48 ++++++++++++++++++++++ stwo_cairo_verifier/src/pcs/verifier.cairo | 6 +++ 2 files changed, 54 insertions(+) diff --git a/stwo_cairo_verifier/src/channel.cairo b/stwo_cairo_verifier/src/channel.cairo index 408359b5..26840172 100644 --- a/stwo_cairo_verifier/src/channel.cairo +++ b/stwo_cairo_verifier/src/channel.cairo @@ -137,6 +137,27 @@ pub impl ChannelImpl of ChannelTrait { }; bytes } + + fn trailing_zeros(self: Channel) -> u32 { + let digest: felt252 = self.digest; + let mut digest_as_u256: u256 = digest.try_into().unwrap(); + + return Self::count_trailing_zeros(@digest_as_u256); + } + + fn count_trailing_zeros(n: @u256) -> u32 { + let mut count = 0; + let mut value = n.clone(); + while value > 0 { + if value & 1_u256 == 1 { + break; + } + count += 1; + value = value / 2; + }; + + return count; + } } #[inline] @@ -332,4 +353,31 @@ mod tests { let second_result = channel.draw_random_bytes(); assert_ne!(first_result, second_result); } + + #[test] + pub fn test_can_return_trailing_zeros_of_digest() { + let initial_digest = 0xcafecafe; + let mut channel = ChannelTrait::new(initial_digest); + let trailing_zeros: u32 = channel.trailing_zeros(); + assert_eq!(trailing_zeros, 1); + } + + #[test] + pub fn test_can_return_trailing_zeros_of_integer() { + let mut value = 1024_u256; + let mut tz = ChannelTrait::count_trailing_zeros(@value); + assert_eq!(tz, 10); + + value = 16; + let mut tz = ChannelTrait::count_trailing_zeros(@value); + assert_eq!(tz, 4); + + value = 3405695742; + let mut tz = ChannelTrait::count_trailing_zeros(@value); + assert_eq!(tz, 1); + + value = 11111; + let mut tz = ChannelTrait::count_trailing_zeros(@value); + assert_eq!(tz, 0); + } } diff --git a/stwo_cairo_verifier/src/pcs/verifier.cairo b/stwo_cairo_verifier/src/pcs/verifier.cairo index fac7ac77..7e314ac8 100644 --- a/stwo_cairo_verifier/src/pcs/verifier.cairo +++ b/stwo_cairo_verifier/src/pcs/verifier.cairo @@ -98,6 +98,12 @@ impl CommitmentSchemeVerifierImpl of CommitmentSchemeVerifierTrait { channel.mix_nonce(proof.proof_of_work); + // TODO: implement + // let proof_of_work_bits: u32 = *self.config.pow_bits; + // if channel.trailing_zeros() < proof_of_work_bits { + // return Result::Err(VerificationError::ProofOfWork); + // } + // Verify merkle decommitments. assert_eq!(self.trees.len(), proof.queried_values.len()); assert_eq!(self.trees.len(), proof.decommitments.len());