RustCrypto / RustCrypto/crypto-bigint

Uint::sub_mod weird behavior (bug?)

Open
#771 10 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Rust
Stars
309
Forks
95
Avg merge
1d 14h
Merged PRs (30d)
3

Description

I might be wrong but I would expect that any _mod(...) operation would return the Uint in the range of [0, m) (or maybe [-m/2, m/2] for Int) , where m is the modulus.
However this is not the case for sub_mod where the resulting value is way off that range when rhs operand is not in the range.
Not sure is this is expected behavior (if it's not than fixing it would be breaking change), if it is, IMHO it should be documented that arguments must be reduced beforehand.
See example below:

    #[test]
    fn test_sub_mod() {
        let x = U128::from_u128(1);
        let y = U128::from_u128(40);
        let m = U128::from_u128(35);
        let z = x.sub_mod(&y, &m);
        println!("z: {}", u128::from(z));
        // prints  z: 340282366920938463463374607431768211452
    }

for comparison this is how sagemath compute this:

> (1 - 40) % 35
31

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Uint::sub_mod entry point and the test_sub_mod example in the issue. Compare its behavior with the documented modular arithmetic expectations and determine whether unreduced operands are supported; done means the behavior is resolved with a documented contract and an appropriate regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
cryptography
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.