witnet / vrf-rs

Verifiable Random Function (VRF) library written in Rust
MIT License
90 stars 37 forks source link

On RaspberryPi ARM32v7 thread 'main' panicked at 'attempt to shift right with overflow', /home/pi/.cargo/registry/src/github.com-1ecc6299db9ec823/hmac-sha256-0.1.1/src/lib.rs:261:33 #15

Closed kevingzhang closed 4 years ago

kevingzhang commented 4 years ago

I checked the source code.

/// Compute SHA256(absorbed content)
pub fn finalize(mut self) -> [u8; 32] {
let mut padded = [0u8; 128];
padded[..self.r].copy_from_slice(&self.w[..self.r]);
padded[self.r] = 0x80;
let r = if self.r < 56 { 64 } else { 128 };
let bits = self.len * 8;
for i in 0..8 {
padded[r - 8 + i] = (bits >> (56 - i * 8)) as u8;
}
self.state.blocks(&padded[..r]);
let mut out = [0u8; 32];
self.state.store(&mut out);
out
}

The bit shift cause problem on ARM CPU, but won't cause any problem on X86 ( I cannot reproduce this bug on my Mac).

I found some others have fix like this: https://github.com/sile/libflate/commit/337eb3c11d33721879754eb282d7bfc4714de042

From

let bits = (self.last_read >> self.offset) as u16;

to

debug_assert!(self.offset < 32 || bitwidth == 0);
let bits = self.last_read.wrapping_shr(self.offset as u32) as u16;

I have not tried this in VRF code, but I would like to ask first

Thanks

kevingzhang commented 4 years ago

I fixed this on my own rust-hmac-sha256 fork and send a pull request

https://github.com/jedisct1/rust-hmac-sha256/pull/1/commits/76fd9d343fff970383ea0f640108a15b8b48fea7

I updated hmac-sha256 on my own fork of vrf-rs and it works well on RaspberryPi. Just online change to use my own hmac-sha256 here https://github.com/kevingzhang/vrf-rs/commit/37ae0e0688c0ae755ad7147e91eaf3b48068163c

Once the owner of hmac-sha256 accepted my PR, and update newer version, I would suggest you to update yours in Cargo.toml too , so that other ARM developers can benefit from my fix.

BTW, your VRF did great job. I am wondering if you plan to write a sortition function based on existing VRF as well?

mariocao commented 4 years ago

Good catch! Thanks for creating the issue and finding the bug. We just published a new release 0.2.2 with the updated version of hmac-sha256.

girazoki commented 4 years ago

That is precisely our main use case, in which the VRF is utilized for selecting comittees to perform certain tasks. In our case, if the VRF output falls below a given target, the peer is eligible to perform the task.

Here you can find the code in which this verification is made:

Sorry that we point out to a different repo but it was important for us to release the VRF as an independent library.