Skip to content

feat(field): add KoalaBear prime field and degree 4 extension - #1136

Merged
diegokingston merged 5 commits into
mainfrom
feat/koalabear-field
Feb 5, 2026
Merged

feat(field): add KoalaBear prime field and degree 4 extension#1136
diegokingston merged 5 commits into
mainfrom
feat/koalabear-field

Conversation

@diegokingston

Copy link
Copy Markdown
Collaborator

Add KoalaBear field (p = 2^31 - 2^24 + 1 = 2130706433) following Plonky3's implementation. Includes:

  • Base field with TWO_ADICITY=24 and full FFT support
  • Degree 4 extension using irreducible polynomial x^4 - 3
  • Optimized mul_by_beta using additions (3x = x.double() + x)
  • Generic inversion algorithm in U32MontgomeryBackendPrimeField

BETA = 3 is both a quadratic and quartic non-residue, making it the correct choice for the extension field (matching Plonky3's W=3).

The extension field supports basic arithmetic (add, mul, inv) but not FFT operations, as computing the primitive 2^26-th root of unity in F_{p^4} requires finding a multiplicative generator.

Acknowledgments: Plonky3 (Polygon) for field definition, RISC Zero for degree 4 inversion algorithm, lambdaworks BabyBear for implementation patterns.

Add KoalaBear field (p = 2^31 - 2^24 + 1 = 2130706433) following Plonky3's
implementation. Includes:

- Base field with TWO_ADICITY=24 and full FFT support
- Degree 4 extension using irreducible polynomial x^4 - 3
- Optimized mul_by_beta using additions (3x = x.double() + x)
- Generic inversion algorithm in U32MontgomeryBackendPrimeField

BETA = 3 is both a quadratic and quartic non-residue, making it the correct
choice for the extension field (matching Plonky3's W=3).

The extension field supports basic arithmetic (add, mul, inv) but not FFT
operations, as computing the primitive 2^26-th root of unity in F_{p^4}
requires finding a multiplicative generator.

Acknowledgments: Plonky3 (Polygon) for field definition, RISC Zero for
degree 4 inversion algorithm, lambdaworks BabyBear for implementation patterns.
@diegokingston
diegokingston requested a review from a team as a code owner February 5, 2026 13:03
@github-actions

github-actions Bot commented Feb 5, 2026

Copy link
Copy Markdown

Kimi AI Review

Review Feedback

koalabear.rs

File: koalabear.rs

  1. Line 19: The comment states that p - 1 = 2^24 × 127, but the actual calculation is 2130706433 - 1 = 2130706432, which is indeed 2^24 × 127. This is a correct statement, but it might be confusing for readers. Consider clarifying the comment to explicitly state the calculation: p - 1 = 2^24 * 127 = 2130706432.

  2. Line 35-36: The IsFFTField implementation for Koalabear31PrimeField includes a TWO_ADIC_PRIMITVE_ROOT_OF_UNITY constant. The comment states that (3^127)^(2^24) ≡ 1 mod 2130706433 and (3^127)^(2^23) ≡ -1 mod 2130706433. These statements are crucial for verifying the correctness of the primitive root of unity. Consider adding a test case to explicitly verify these properties to ensure the correctness of the TWO_ADIC_PRIMITVE_ROOT_OF_UNITY value.

  3. Line 204: The test test_two_adic_primitive_root_of_unity verifies that 3^(2^24) = 1 mod p. This is correct and necessary. However, the test test_two_adic_primitive_root_is_primitive checks that 3^(2^23) != 1 mod p, which is not sufficient to prove primitivity. A more robust test should check that no smaller power of 3^127 equals 1 mod p, except for the full order. Consider enhancing this test to ensure the full primitivity of the root.

  4. Line 300-301: The property-based tests for FFT evaluations and interpolations are thorough. However, the tests assume that the FFT implementation is correct and focus on comparing it with naive polynomial evaluations. Consider adding tests that verify the correctness of the FFT implementation itself, especially for edge cases and large inputs.

  5. Overall: The implementation and tests for the Koalabear31PrimeField are comprehensive. However, there is a lack of documentation on the overall design and usage of the field. Consider adding more detailed documentation on the module's purpose, the choice of the prime field, and its properties.

quartic_koalabear.rs

File: quartic_koalabear.rs

  1. Line 17: The calculation of BETA is based on the Montgomery form of 3. Ensure that the calculation is correct and consider adding a comment explaining the Montgomery form and why BETA is calculated this way.

  2. Line 44: The mul_by_beta function is implemented as x.double() + x. This is correct for multiplying by 3 in a field where x^4 = 3. However, consider adding a comment explaining why this works and the relationship to the field's defining equation.

  3. Line 124-125: The inv function for the degree four extension field is implemented using an adapted algorithm from RISC Zero. Consider adding a comment explaining the algorithm's steps and why it works for the specific case of x^4 - 3.

  4. Line 196: The from_base_type function is implemented as the identity function. Consider adding a comment explaining why this is the case and the relationship between the base type and the field elements.

  5. Line 226: The HasDefaultTranscript implementation uses a mask to ensure the generated random numbers are within the field's bounds. This is a good practice for ensuring the correctness of random field elements. However, consider adding a comment explaining the mask's purpose and why it is necessary.

  6. Overall: The implementation of the quartic extension field is thorough and includes detailed tests. However, there is a lack of documentation on the overall design and usage of the field extension. Consider adding more detailed documentation on the module's purpose, the choice of the irreducible polynomial, and its properties.

u32_montgomery_backend_prime_field.rs

File: u32_montgomery_backend_prime_field.rs

  1. Line 126-151: The inv function has been updated to use a generic square-and-multiply algorithm. This is a correct approach for computing the multiplicative inverse in any prime field. However, consider adding comments explaining the algorithm's steps and why it works for prime fields.

  2. Overall: The implementation of the `U32MontgomeryBackendPrime

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review by ChatGPT

}
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness

  • The implementation appears mostly correct; however, thorough checks on the underlying U32MontgomeryBackendPrimeField class would be needed to ensure proper modular arithmetic operations, especially given the emphasis on FFT operations, which are very sensitive to arithmetic correctness.

Security

  • Timing Side-Channels: Ensure all arithmetic operations involving field elements, particularly inversions, are constant time to prevent timing attacks. The code currently does not specify if the operations provided by U32MontgomeryBackendPrimeField handle this.
  • Hash Function Domain Separation: No evidence of domain separation in hashing is evident, though it's likely not in the reviewed snippet. Check elsewhere if the code interacts with hash functions.
  • Proper Zeroization: The code does not show explicit zeroization of sensitive data. Consider using libraries or mechanisms to zeroize secret data properly after use to prevent data leaks.

Performance

  • Unnecessary Allocations: The function get_powers_of_primitive_root might be generating temporary vectors that could be eliminated or reduced.
  • Redundant Field Inversions: Field inversions may already be optimized by the library; it's essential to verify that they aren't called unnecessarily since they are expensive operations.

Bugs & Errors

  • Panics or Unwraps: expect on unwrap/expect usage exists in tests, though it's acceptable here, it might be risky if similar patterns exist in production code.
  • Integer Overflow/Underflow: There is a theoretical risk of implicit overflows in arithmetic operations; a dense test around these operations should include checks for overflows.

Code Simplicity

  • The code currently seems complex with a significant amount of test boilerplate. Abstractions for repetitive test patterns could improve test maintainability and readability.
  • Could consider reducing complexity by modularizing test functions where repetitive logic patterns (e.g., FFT evaluations, or different interpolation methods).

Overall, while the changes seem promising, ensure comprehensive correctness validation, constant-time assurance, and avoidance of any risk of timing side-channels before merging.

pub mod quartic_koalabear;
/// Implementation of the prime field used in [Stark101](https://starkware.co/stark-101/) tutorial, p = 3 * 2^30 + 1
pub mod stark_101_prime_field;
/// Implementation of two-adic prime field over 256 bit unsigned integers.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness

  • Edge Cases: Ensure the new KoalaBear prime field correctly handles all edge cases, similar to Babybear, especially for zero-initialization and identity elements.
  • Modular Arithmetic: Double-check the arithmetic operations for the KoalaBear prime field to verify correct modular reduction with the specified prime.

Security

  • Timing Side-Channels: It is crucial that all field operations and sensitive procedures in both Babybear and KoalaBear implementations are conducted in constant-time to prevent timing attacks.
  • Cryptographically Secure Randomness: When generating elements from these fields, ensure that randomness is generated using a cryptographically secure RNG where applicable.
  • Zeroization: Any sensitive data should be zeroized appropriately after its use, especially in extended field operations.

Performance

  • Redundant Field Inversions: Review the code for any unnecessary field inversions in both Babybear and KoalaBear that could be avoided through alternative algorithms.
  • MSM and FFT Efficiency: If MSM or FFT are implemented within these modules, profile and optimize for performance, focusing on avoiding unnecessary data allocations.

Bugs & Errors

  • Potential Panics or Unwraps: Ensure no operations in these modules use unwrap() or could lead to a panic under legitimate inputs. Consider returning Result types where failures are possible.
  • Memory Safety: Validate that all memory operations are safe and free from potential overflows or unchecked indexing.

Code Simplicity

  • Duplicated Code: If KoalaBear shares much logic with Babybear, consider abstracting common operations to avoid code duplication and improve maintainability.

Overall, thorough testing is recommended, both unit tests and property-based tests, to ensure the operations adhere to expected behaviors across these critical cryptographic modules.

assert_eq!(Fp4E::from_bytes_le(&bytes).expect("valid bytes").to_bytes_le(), bytes);
}

}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness

  • Polynomial Arithmetic: The code for polynomials modulo x^4 - 3 appears mathematically sound, and tests are provided to back operations.
  • Inversion Logic: The inversion algorithm looks properly implemented for the irreducible polynomial x^4 - 3.
  • Edge Cases: There are tests for zero and identity elements but ensure thorough edge cases like the inverse of zero are checked.

Security

  • Timing Side-channels: There are no evident constant-time guarantees, especially in arithmetic operations like inv. Consider using a constant-time algorithm for inversion, especially when handling sensitive data.
  • Zeroization: Sensitive data zeroization is not evident, which is important for security in cryptographic operations.
  • Branching: Ensure no secret-dependent branching is happening unintentionally.
  • Randomness: get_random_field_element_from_rng uses rejection sampling correctly, but ensure the RNG is cryptographically secure.
  • Hash Function Domain Separation: Not evaluated in the provided code. Ensure domain separation in associated cryptographic hash function use.

Performance

  • Redundant Operation Checks: double calls add, which may induce unnecessary overhead. Direct implementation might be optimized.
  • FFT & MSM: Since FFT support isn't implemented yet for this degree 4 field, this limits potential use cases for optimization discussions.
  • Unnecessary Allocations: The to_bytes_be and to_bytes_le could aggregate bytes without extending them repeatedly, thus reducing allocation overhead.

Bugs & Errors

  • Memory Safety: No memory safety issues identified in provided code, but it heavily depends on proper handling in called methods.
  • Panics or Unwraps: Some unwraps in tests must ensure no panics on valid field operations.
  • Integer Overflow/Underflow: Rust's FieldElement likely provides safety against integer overflows, but double-check any unchecked regions missing exploits.
  • Off-by-One Errors: None detected in this code review.

Code Simplicity

  • Complexity: The inv method's complex nature could be a candidate for refactoring into simpler components or utilizing more comments.
  • Duplicated Code: Byte conversion methods present similar patterns. Consider refactoring for less duplication.
  • Poor Abstractions: The library efficiently defines IsField and IsSubFieldOf traits to handle field extensions, enhancing code maintainability.

Ok(result)
}

#[inline(always)]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness

  • Mathematical Operations: The use of a generic square-and-multiply algorithm for computing the multiplicative inverse via Fermat's Little Theorem is correct theoretically, but it's crucial to ensure that this algorithm operates correctly for all valid inputs. Specifically, ensure that MODULUS is indeed a prime as assumed.

Security

  • Timing Side-Channels: The new implementation employs a basic square-and-multiply algorithm, which may not be constant-time due to the secret-dependent loop based on the exponent bits. This could lead to timing side-channel vulnerabilities when operating on secret data. Consider using a constant-time algorithm like Montgomery ladder for more secure exponentiation.
  • Zeroization of Sensitive Data: There is no explicit mention of any zeroization of the variables used in this computation (e.g., result, base). While they are on the stack, ensure zeroization of sensitive data when feasible.

Bugs & Errors

  • Potential Panics: Ensure that the subtraction MODULUS - 2 does not panic due to potential underflows. Although MODULUS should be greater than 2 for primes, handling edge cases or verifying constraints is crucial.

Performance

  • Efficiency: The new algorithm is likely to be more efficient than the previous unrolled method, especially for large MODULUS, due to its reduced complexity dependency on the modulus size.

Code Simplicity

  • Complexity: The current implementation is significantly simpler and more maintainable than the previous, albeit needing attention on the timing side-channel front.

Recommendations

  • Implement constant-time exponentiation for secure computations.
  • Add checks or assertions to ensure that MODULUS meets the required properties (i.e., being a prime greater than 2).
  • Consider adding test cases for edge cases such as minimal non-zero values and maximal values just below MODULUS.

@greptile-apps

greptile-apps Bot commented Feb 5, 2026

Copy link
Copy Markdown

Greptile Overview

Greptile Summary

This PR adds the KoalaBear prime field (p = 2^31 - 2^24 + 1) and its degree-4 extension, following Plonky3's implementation. The implementation includes:

  • Base field with TWO_ADICITY=24 and comprehensive FFT support
  • Degree-4 extension using irreducible polynomial x^4 - 3 with BETA=3
  • Optimized mul_by_beta function using additions (3x = x.double() + x)
  • Generic inversion algorithm in U32MontgomeryBackendPrimeField using Fermat's Little Theorem
  • Extensive test coverage including property-based tests for FFT operations

The PR correctly sets BYTES_PER_FIELD = 4 throughout (as noted in previous review threads). All field parameters match Plonky3's specification, and the mathematical formulas for the extension field operations are correctly adapted for x^4 - 3 (using + for BETA terms instead of - as in BabyBear's x^4 + 11).

Confidence Score: 5/5

  • Safe to merge - well-tested implementation following established patterns
  • All mathematical formulas verified correct, comprehensive test coverage, follows existing codebase patterns, proper documentation
  • No files require special attention

Important Files Changed

Filename Overview
crates/math/src/field/fields/fft_friendly/koalabear.rs New KoalaBear prime field implementation with comprehensive tests and FFT support
crates/math/src/field/fields/fft_friendly/quartic_koalabear.rs Degree-4 extension field using x^4 - 3 with optimized mul_by_beta and comprehensive tests (BYTES_PER_FIELD correctly set to 4)
crates/math/src/field/fields/u32_montgomery_backend_prime_field.rs Refactored inv() to use generic Fermat's Little Theorem instead of BabyBear-specific optimization
crates/math/src/field/fields/fft_friendly/mod.rs Module registration for koalabear and quartic_koalabear modules

Sequence Diagram

sequenceDiagram
    participant User
    participant KoalaBear as Koalabear31PrimeField
    participant Quartic as Degree4KoalaBearExtensionField
    participant Montgomery as U32MontgomeryBackendPrimeField
    participant FFT as FFT Operations

    Note over KoalaBear: Base Field (p = 2^31 - 2^24 + 1)
    User->>KoalaBear: Create field element
    KoalaBear->>Montgomery: Use Montgomery backend
    Montgomery-->>KoalaBear: Element in Montgomery form
    
    User->>KoalaBear: Field operations (add, mul, inv)
    KoalaBear->>Montgomery: Generic Fermat's Little Theorem inv()
    Montgomery-->>KoalaBear: Result
    
    User->>KoalaBear: FFT operations
    KoalaBear->>FFT: Use TWO_ADICITY=24, root=1791270792
    FFT-->>User: FFT result
    
    Note over Quartic: Extension Field (x^4 - 3)
    User->>Quartic: Create extension element [a0,a1,a2,a3]
    Quartic->>Quartic: mul_by_beta(x) optimized as x.double() + x
    
    User->>Quartic: Extension operations (mul, inv)
    Quartic->>Quartic: Adapted RISC Zero algorithm for x^4 - β
    Quartic->>KoalaBear: Base field operations
    KoalaBear-->>Quartic: Base field results
    Quartic-->>User: Extension result
Loading

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

4 files reviewed, 2 comments

Edit Code Review Agent Settings | Greptile

where
Self: Sized,
{
const BYTES_PER_FIELD: usize = 32;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BYTES_PER_FIELD should be 4, not 32. KoalaBear is a u32 field, so each element is 4 bytes.

Suggested change
const BYTES_PER_FIELD: usize = 32;
const BYTES_PER_FIELD: usize = 4;
Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/math/src/field/fields/fft_friendly/quartic_koalabear.rs
Line: 273:273

Comment:
`BYTES_PER_FIELD` should be 4, not 32. KoalaBear is a u32 field, so each element is 4 bytes.

```suggestion
        const BYTES_PER_FIELD: usize = 4;
```

How can I resolve this? If you propose a fix, please make it concise.

where
Self: Sized,
{
const BYTES_PER_FIELD: usize = 32;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BYTES_PER_FIELD should be 4, not 32. KoalaBear is a u32 field, so each element is 4 bytes.

Suggested change
const BYTES_PER_FIELD: usize = 32;
const BYTES_PER_FIELD: usize = 4;
Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/math/src/field/fields/fft_friendly/quartic_koalabear.rs
Line: 287:287

Comment:
`BYTES_PER_FIELD` should be 4, not 32. KoalaBear is a u32 field, so each element is 4 bytes.

```suggestion
        const BYTES_PER_FIELD: usize = 4;
```

How can I resolve this? If you propose a fix, please make it concise.

@codecov-commenter

codecov-commenter commented Feb 5, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.68966% with 112 lines in your changes missing coverage. Please review.
✅ Project coverage is 72.45%. Comparing base (841c221) to head (49209be).

Files with missing lines Patch % Lines
...src/field/fields/fft_friendly/quartic_koalabear.rs 68.42% 108 Missing ⚠️
...es/math/src/field/fields/fft_friendly/koalabear.rs 98.23% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1136      +/-   ##
==========================================
+ Coverage   72.35%   72.45%   +0.10%     
==========================================
  Files         167      169       +2     
  Lines       37498    38052     +554     
==========================================
+ Hits        27130    27569     +439     
- Misses      10368    10483     +115     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

…rsion

KoalaBear uses u32 (4 bytes), not 32 bytes per field element.
Fixed the ByteConversion impl for [FieldElement<Koalabear31PrimeField>; 4].

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review by ChatGPT

/// BETA = 3 is the non-residue (both quadratic and quartic non-residue in KoalaBear).
/// Since `const_from_raw()` doesn't make the montgomery conversion, we calculated it.
/// The montgomery form of a number "a" is a * R mod p.
/// In KoalaBear field, R = 2^32 and p = 2130706433.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness

  • Error in ByteConversion: The size change in BYTES_PER_FIELD from 32 to 4 bytes suggests that each field element in Koalabear31PrimeField is being represented as a 32-bit value rather than a 256-bit value. This discrepancy affects the deserialization of field elements, potentially leading to incorrect mathematical results throughout operations dealing with these elements.

Security

  • No immediate issues found given the context of the changes. Ensure any arithmetic or comparison involving sensitive data remains constant-time, although this snippet doesn't directly touch on such concerns.

Performance

  • Potential Performance Impact: The assumption that fields are 32-bits rather than 256 might indicate optimization issues elsewhere if 256-bit arithmetic is expected within the library.

Bugs & Errors

  • Potential Deserialization Bugs: If the assumption that each element is 32 bits is incorrect, slicing the bytes in 4-byte increments will lead to incorrect initialization of FieldElement values, leading to faulty operations or panics if bounds checks on the 'from_bytes' function are not comprehensive.

Code Simplicity

  • Ambiguity in Field Size Constants: Ensure that the code clearly communicates why a 4-byte representation is appropriate and whether this aligns with expectations of other code portions relying on Koalabear31PrimeField.

Summary

  • The change in BYTES_PER_FIELD requires a thorough review of how field elements are expected to be represented throughout the library. This affects deserialization and potentially invalidates the correctness of the operations. It's crucial to validate whether Koalabear31PrimeField genuinely uses u32 representation and if not, revert or adjust operations accordingly. Further inspection on potential impacts on cryptographic operations and alignment with the library's overall representation logic is needed before merging.

@github-actions

github-actions Bot commented Feb 5, 2026

Copy link
Copy Markdown

Kimi AI Review

The PR introduces new implementations for the KoalaBear prime field and its degree 4 extension. Here are my comments and concerns:

  1. Correctness of Two-Adic Primitive Root of Unity (koalabear.rs:12-13)

    • The claim that 3^127 = 1791270792 is a two-adic primitive root of unity for the KoalaBear field needs verification. The primitive root of unity should satisfy (root^(2^24)) % p == 1 and (root^(2^23)) % p != 1. Please provide a reference or proof for this claim.
  2. Security Implications of Inversion Algorithm (u32_montgomery_backend_prime_field.rs:126-)

    • The inversion algorithm has been changed from a hardcoded, potentially optimized version to a generic square-and-multiply approach. This change might have security implications if the previous algorithm was designed to be constant-time. Please review the new algorithm for constant-time properties, especially if it's used in cryptographic protocols.
  3. Performance of Degree 4 Extension Field Operations (quartic_koalabear.rs:39-)

    • The custom implementation of the degree 4 extension field operations seems to be optimized for performance. However, the lack of comments and documentation makes it hard to understand the reasoning behind certain choices, such as the use of mul_by_beta. Adding comments explaining the optimizations and the mathematical basis for these operations would improve maintainability.
  4. Lack of FFT Support for Degree 4 Extension (quartic_koalabear.rs:26)

    • The comment notes that FFT support for the degree 4 extension is not yet implemented. This is a significant limitation if the field is intended for use in algorithms that rely on FFTs, such as certain zero-knowledge proofs. Please provide an estimate of when this feature might be implemented or if there are plans to use a different approach.
  5. Error Handling in Field Operations (quartic_koalabear.rs:168-)

    • The inv function in the degree 4 extension field returns a FieldError if the input is zero. However, the error message is not very informative. Consider using a more specific error variant, such as FieldError::InvZeroError, to improve error handling in the caller code.
  6. Test Coverage (koalabear.rs: tests module)

    • The test module includes a comprehensive set of tests for the KoalaBear field operations. However, there are no tests for the two-adic primitive root of unity. Adding tests to verify the correctness of this value would increase confidence in the implementation.

Overall, the PR makes significant changes to the field implementations. While the optimizations and custom operations seem to improve performance, there are concerns about the correctness of the two-adic primitive root of unity and the security implications of the new inversion algorithm. Additionally, the lack of FFT support and the need for better documentation and error handling should be addressed.

@github-actions

github-actions Bot commented Feb 5, 2026

Copy link
Copy Markdown

Kimi AI Review

Review Feedback

File: koalabear.rs

  1. Correctness of Two-Adic Primitive Root of Unity Calculation:

    • In koalabear.rs, the two-adic primitive root of unity is calculated as 3^127 = 1791270792. This calculation should be verified for correctness, especially the exponentiation process, to ensure it adheres to the field's properties.

    • Line 22: The calculation of TWO_ADIC_PRIMITVE_ROOT_OF_UNITY should be reviewed to ensure that 3^127 indeed equals 1791270792 modulo 2130706433. This is crucial for the field's structure and subsequent FFT operations.

  2. Tests for Field Operations:

    • The test module test_koalabear_31_ops contains various tests for field operations. It's important to ensure that these tests cover all edge cases and potential overflows, especially for operations like subtraction and addition near the modulus boundary.

    • Line 45-47: The test two_plus_one_is_three is straightforward but should be expanded to include tests for subtraction and addition that could potentially wrap around the modulus.

  3. Performance Considerations:

    • The implementation of field operations should be reviewed for performance optimizations, especially in how multiplication and exponentiation are handled.

    • Line 34-35: The use of double() in the doubling test could be optimized by directly using addition, as a + a is equivalent to 2a in field arithmetic.

  4. Cryptographic Security:

    • While the code does not directly handle cryptographic operations, the correctness of the field operations is paramount for any cryptographic application that might use this field.

    • Line 22: The choice of the two-adic primitive root of unity should be reviewed for its cryptographic implications, especially in the context of side-channel attacks.

File: u32_montgomery_backend_prime_field.rs

  1. Optimization of Inversion Algorithm:

    • The inversion algorithm has been updated to use a generic square-and-multiply approach. This is a significant improvement over the previous hardcoded approach, as it makes the code more flexible and applicable to different moduli.

    • Line 126-150: The new inversion algorithm should be thoroughly tested to ensure it produces the correct results for all non-zero elements in the field.

  2. Documentation and Comments:

    • The code could benefit from more detailed comments, especially explaining the reasoning behind choosing the square-and-multiply algorithm for inversion and how it applies to Montgomery form arithmetic.

    • Line 126: A comment explaining the square-and-multiply algorithm and its application in the context of this field would be beneficial.

Summary

The changes in the PR address several important aspects of the field implementation, including the addition of a new prime field and optimizations to the inversion algorithm. However, it is crucial to ensure that the mathematical correctness of the new field's properties, such as the two-adic primitive root of unity, is verified. Additionally, the performance and security implications of these changes should be carefully considered and tested.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review by ChatGPT

}

#[test]
fn mul_2_3_is_6() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here are the issues identified in the code changes:

Correctness:

  1. The functions in test cases, such as to_bytes_from_bytes_be_is_the_identity, rely on hexadecimal and byte conversions but do not cover edge cases such as zero or the maximum field element value.

  2. Check if Polynomial::evaluate_fft and Polynomial::interpolate_fft handle edge cases like polynomials of zero length or constant polynomials correctly.

Security:

  1. Ensure that all operations, especially those involving the FE::from_bytes_be and FE::from_bytes_le, are implemented in constant time to avoid timing side channels.

  2. There is no indication of proper zeroization of sensitive data, such as intermediate calculations or results, which might be necessary depending on their usage.

  3. Verify that cryptographically secure randomness (e.g., for nonce generation) is used where needed, such as in generating primitive roots or offsets.

Performance:

  1. Consider adding tests for performance-critical paths, especially FFT-related computations, to ensure efficient execution.

  2. Ensure no redundant memory allocations occur in loop constructs, particularly inside FFT and polynomial evaluations. Allocation, especially in a loop, can degrade performance.

Bugs & Errors:

  1. Functions use .expect() calls which may panic. Consider handling these situations gracefully or ensuring they will not fail in production.

  2. Since the fft and interpolation methods often involve indices and length calculations, make sure these calculations do not lead to off-by-one errors or overflows. Consider wrapping with a checked arithmetic if necessary.

Code Simplicity:

  1. Verifying duplicate logic in the test cases might help to simplify them. For example, similar logic is used in conversions (to_bytes_le and to_bytes_be). Abstracting this functionality could reduce duplication.

Please address these issues to ensure that the code is correct and secure before merging.

fn sub(a: &Self::BaseType, b: &Self::BaseType) -> Self::BaseType {
[a[0] - b[0], a[1] - b[1], a[2] - b[2], a[3] - b[3]]
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness

  • The function mul_by_beta uses a simple and correct optimization for multiplying by the constant BETA, which is 3 in this context. It should be verified that the .double() method is correctly implemented for arithmetic within the Koalabear31PrimeField.
  • No code provided that involves handling of edge cases such as zero or infinity points for elliptic curves. Ensure that these are correctly handled elsewhere in the library.

Security

  • There are no observed changes addressing timing side-channels or constant-time operations. Ensure that all sensitive field operations (such as multiplications or inversions involving secret data) are performed in constant time.
  • No evidence of zeroization for sensitive data, for example in temporary variables used in field operations, exposing risk if these variables leak from memory in other parts of the code.
  • Verify cryptographically secure randomness if used elsewhere; not enough context provided here.
  • Ensure hash function usages are correctly domain-separated if hashes are used in proofs or random oracles.

Performance

  • The current change focuses mainly on format adjustments and test cases.
  • Test cases are invoking .expect(), which can panic, consider handling errors gracefully in non-test code paths.

Bugs & Errors

  • The use of .expect() in test cases should be safe given the provided context; however, ensure that production code handles potential errors gracefully without panic.

Code Simplicity

  • No complex logic changes in the provided diff.
  • Avoid unnecessary line breaks in expressions for readability in functions and structs, unless naturally complex.

General Comments

The provided code is related to tests and minor format changes. Assuming the core implementation is elsewhere, verify that any underlying field and arithmetic operations are correctly implemented and constant-time as there are no direct algorithmic changes in the provided diff. Ensure that sensitive operations are secure and efficiencies like FFT and MSMs are maintained in other parts of the code.

…ar tests

Tests using from_hex, to_bytes_*, ByteConversion, and CreationError
require alloc feature. Added conditional compilation attributes to:
- Import statements (CreationError, ByteConversion)
- Test functions (byte_serialization_and_deserialization_works_*)

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review by ChatGPT

}

#[cfg(test)]
mod tests {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness:

  • Ensure that all mathematical operations involving FE (FieldElements) are consistent with the field arithmetic specifications, especially handling edge cases like zero and one. In this diff, there are no seen issues with the operations themselves, but it is crucial the library indeed implements such checks.

Security:

  • Constant-Time Operations: Ensure back-end implementations for arithmetic within FieldElement, such as to_bytes_le and to_bytes_be, are constant-time because they manage potentially sensitive cryptographic elements.

  • Zeroization: After operations, or when memory deallocation happens, confirm that any sensitive data (like field elements) is properly zeroed from memory.

  • Feature Guards: The use of #[cfg(feature = "alloc")] suggests conditional compilation. Ensure that when alloc isn't enabled, the absence of these features doesn’t introduce vulnerabilities elsewhere in the compiled code.

Performance:

  • No performance issues visible in the provided code chunk, but inside field operations, excessive use of allocations could be a concern when the alloc feature is enabled.

Bugs & Errors:

  • Panics/Unwraps: Using expect("valid hex") can cause a panic if the assumption isn’t guaranteed. It’s better to handle this with error management or ensure through other checks that input can never be invalid.

Code Simplicity:

  • Consider whether the conditional feature checks in imports (#[cfg(feature = "alloc")]) may lead to duplicated logic, especially if different parts of the module have similar dependencies with differing feature requirements.

Overall:

  • Address the panic/unwrap risk by implementing a more robust error-handling approach for hexadecimal parsing (e.g., propagating errors). Ensure field operations and conditional feature allocations do not open timing or zeroing vulnerabilities in cryptographic contexts. The absence of complete logic for operations makes a thorough assessment difficult, recommending further review focused on details of those methods/traits used extensively in the diff.

@github-actions

github-actions Bot commented Feb 5, 2026

Copy link
Copy Markdown

Kimi AI Review

Review Feedback

koalabear.rs

  1. Correctness of Two-Adic Primitive Root of Unity Calculation:

    • In koalabear.rs, the two-adic primitive root of unity is calculated as 3^127. Ensure that this calculation is correct and that 3 is indeed a primitive root modulo 2130706433. The verification tests test_two_adic_primitive_root_of_unity and test_two_adic_primitive_root_is_primitive are good, but double-check the mathematical correctness of the constants used.
  2. Performance of Field Operations:

    • The implementation of field operations like add, sub, mul, and inv should be reviewed for performance optimizations. Using u32 for backend operations can be efficient, but ensure that there are no unnecessary computations or conversions that could be optimized.
  3. Cryptographic Security:

    • Review the constant-time nature of the field operations, especially inv. The current implementation uses a square-and-multiply approach, which is generally constant-time. However, ensure that all multiplications and squarings are performed in a constant-time manner to avoid timing side-channels.
  4. Code Simplicity and Maintainability:

    • The code is relatively straightforward, but the use of const_from_raw and manual calculations for constants like BETA can be error-prone. Consider using a more automated approach or library functions to generate these constants to reduce the risk of human error.

quartic_koalabear.rs

  1. Correctness of Extension Field Operations:

    • The implementation of the quartic extension field using the irreducible polynomial x^4 - 3 is complex. Ensure that all operations, especially multiplication and inversion, are correctly implemented according to the field's definition. The tests provided are a good start, but additional properties and edge cases should be tested.
  2. Performance of Extension Field Operations:

    • Similar to the base field, review the performance of operations in the extension field. The multiplication and inversion algorithms are critical and should be optimized for performance.
  3. Cryptographic Security:

    • As with the base field, ensure that all operations in the extension field are constant-time to prevent timing side-channels.
  4. Code Simplicity and Maintainability:

    • The code for the extension field is more complex due to the nature of the operations. Consider refactoring or using more abstracted approaches to make the code more maintainable and readable.

u32_montgomery_backend_prime_field.rs

  1. Correctness of Inverse Calculation:

    • The new implementation of inv using a generic square-and-multiply algorithm is a good change for maintainability. However, ensure that it is correctly implemented and tested for all edge cases, especially for large exponents.
  2. Performance of Inverse Calculation:

    • Review the performance of the new inv implementation. The square-and-multiply approach is generally efficient, but benchmark it against the previous approach to ensure there is no performance regression.

Overall, the changes seem to be moving towards a more standardized and maintainable implementation. However, thorough testing, especially for edge cases and performance, is crucial to ensure the library remains robust and efficient.

@github-actions

github-actions Bot commented Feb 5, 2026

Copy link
Copy Markdown

Kimi AI Review

Here are my specific comments on the provided PR diff:

  1. koalabear.rs:

    • The implementation of the KoalaBear31PrimeField seems correct. The prime modulus and the two-adic properties are correctly specified.
    • The IsFFTField trait implementation looks good, with the correct two-adicity and primitive root of unity.
    • The test cases cover a wide range of field operations and edge cases. They seem comprehensive and correct.
  2. mod.rs:

    • Adding the koalabear and quartic_koalabear modules looks correct and follows the existing pattern.
  3. quartic_koalabear.rs:

    • The implementation of the degree 4 extension field using the irreducible polynomial x^4 - 3 is correct.
    • The BETA constant is correctly calculated as the Montgomery form of 3.
    • The field operations (add, mul, inv) are correctly implemented using the irreducible polynomial relation.
    • The IsSubFieldOf trait implementation for KoalaBear31PrimeField within the extension field is correct.
    • The test cases cover the essential operations and edge cases, and they seem comprehensive.
  4. u32_montgomery_backend_prime_field.rs:

    • The updated inv implementation using a generic square-and-multiply algorithm is correct and more maintainable than the previous hardcoded steps.
    • This change will make it easier to adapt the code for different prime moduli in the future.

Overall, the changes look good, and I don't see any immediate issues. The code is well-structured, follows the existing patterns, and includes comprehensive test cases. The update to the inv implementation is an improvement in terms of maintainability and adaptability.

One minor suggestion: consider adding a comment explaining the change in the u32_montgomery_backend_prime_field.rs file, mentioning that the new generic square-and-multiply algorithm replaces the hardcoded steps.

Let me know if you have any specific questions or need further clarification. I'm happy to help!

@jotabulacios

Copy link
Copy Markdown
Contributor

@greptile

@diegokingston
diegokingston merged commit 3d80597 into main Feb 5, 2026
12 checks passed
@diegokingston
diegokingston deleted the feat/koalabear-field branch February 5, 2026 16:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants