RustCrypto / RustCrypto/crypto-bigint

Better newtype invariant handling

Open
#1,144 2 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

Right now several newtypes that enforce invariants like NonZero and Odd (or should, see #1127 for UintRef) are marked as pub(crate) and constructed outside the modules they're defined in. This has lead to bugs where the invariants aren't being respected. We also use typecasting in several places, sometimes to promote a reference to a type to a newtype wrapper.

I think it might make sense to remove the pub(crate) from such types and try to use a standard internal protocol for them which still allows code outside the module to promote the inner type to the newtype, but in a way that invariants at least get checked by debug_assert!, something like:

pub struct NewType<T>(T);

impl<T> NewType<T> {
    pub(crate) const fn construct(inner: T) {
        Self::check_invariants(&T);
        Self(inner)
    }

    pub(crate) const fn check_invariants(inner: &T) {
        debug_assert!(...);
    }
}

(it would need more trait bounds to actually work, but hopefully you get the idea)

I think an approach like this could catch some of the bugs we've seen where invalid newtypes were being constructed (which were my fault).

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 by tracing the NonZero and Odd newtypes, their construction sites, and the UintRef context in #1127. Determine a consistent internal construction protocol that checks invariants during promotion, then verify that existing constructions no longer permit invalid values.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
cryptography
Issue type
Refactor
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.