Skip to content

[BUG]: Expected Behavior of FieldImpl::from_bytes_le() #997

@PengyuanYan

Description

@PengyuanYan

Description

When converting random bytes into a field element using FieldImpl::from_bytes_le(), the resulting field element sometimes behaves incorrectly in arithmetic and polynomial evaluation. It appears that the bytes are not properly reduced modulo the field's modulus.

Reproduce

use merlin::Transcript as Tr;
use icicle_bn254::curve::CurveCfg as Bn254CurveCfg;
use icicle_bn254::curve::ScalarField as Bn254ScalarField;
use icicle_core::traits::FieldImpl;
use icicle_core::curve::Curve;
use std::sync::Mutex;
use icicle_bn254::polynomials::DensePolynomial as Bn254DensePolynomial;
use icicle_core::polynomials::UnivariatePolynomial;
use icicle_runtime::memory::HostSlice;

#[test]
fn test_from_bytes_le() {
    let transcript = Tr::new(b"acc-transcript");
    let challenge_size = Bn254ScalarField::zero().to_bytes_le().len();
    let challenge_buffer = vec![0u8; challenge_size];

    let tr = Mutex::new(transcript);
    let challenge_buffer = Mutex::new(challenge_buffer);

    let mut ch_buffer = challenge_buffer.lock().unwrap();
    tr.lock().unwrap().challenge_bytes(b"acc-transcript", &mut ch_buffer);

    let beta = Bn254ScalarField::from_bytes_le(&ch_buffer);

    let beta_1 = beta + <Bn254CurveCfg as Curve>::ScalarField::zero();
    let beta_2 = beta_1 + <Bn254CurveCfg as Curve>::ScalarField::zero();

    println!("{}",beta_1 == beta_2);

    let test_coeffs = [<Bn254CurveCfg as Curve>::ScalarField::zero() - beta, <Bn254CurveCfg as Curve>::ScalarField::one()];
    let test_poly = Bn254DensePolynomial::from_coeffs(HostSlice::from_slice(&test_coeffs), 2);
    let x = test_poly.eval(&beta);

    println!("{}",x);
}

Expected Behavior

I expect the first println will print true and the second println will print a zero looks like 0x00000000000000000000000000.

Environment

Please complete the following information:

OS + Version: MacOS with Apple M1 Pro

Cargo Version: the current one

GPU type: N/A

Additional context

Please provide any additional context that may be helpful in confirming and resolving this issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    type:bugSomething isn't working

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions