Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add proper felt division #50

Merged
merged 2 commits into from
Apr 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 8 additions & 13 deletions src/primitives/felt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,19 +107,14 @@ describe('Felt', () => {
});

describe('div', () => {
test('should divide two felts properly', () => {
const a = new Felt(10n);
const b = new Felt(2n);
const result = a.div(b);
const expected = new Felt(5n);
expect(result.eq(expected)).toBeTrue();
});
test('should go to 0 if a < b in a/b', () => {
const a = new Felt(5n);
const b = new Felt(10n);
const result = a.div(b);
const expected = new Felt(0n);
expect(result.eq(expected)).toBeTrue();
test.each([
[new Felt(10n), new Felt(2n)],
[new Felt(5n), new Felt(10n)],
[new Felt(Felt.PRIME - 10n), new Felt(10n)],
[new Felt(10n), new Felt(Felt.PRIME - 10n)],
])('should divide two felts properly', (a: Felt, b: Felt) => {
const result = a.div(b).mul(b);
expect(result).toStrictEqual(a);
});
});
});
27 changes: 26 additions & 1 deletion src/primitives/felt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ export class Felt {
if (!isFelt(other) || other.inner === 0n) {
throw new ForbiddenOperation();
}
return new Felt(this.inner / other.inner);

return this.mul(other.inv());
}

eq(other: MaybeRelocatable): boolean {
Expand All @@ -60,4 +61,28 @@ export class Felt {
toHexString(): string {
return this.inner.toString(16);
}

/**
* @dev Compute modular multiplicative inverse with
* Euler totient's function and Fermat's little theorem
*/
private inv(): Felt {
return this.pow(Felt.PRIME - 2n);
}

/** @dev Binary Exponentiation - Iterative version */
private pow(exp: bigint): Felt {
if (exp === 0n) return new Felt(1n);
if (exp === 1n) return this;
let res = 1n;
let inner = this.inner;
while (exp !== 0n) {
if (exp & 1n) {
res = (res * inner) % Felt.PRIME;
}
inner = (inner * inner) % Felt.PRIME;
exp >>= 1n;
}
return new Felt(res);
}
}
2 changes: 1 addition & 1 deletion src/vm/virtualMachine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ describe('VirtualMachine', () => {
test('should deduce op1 for assert eq res logic add', () => {
const instruction = getInstructionWithOpcodeAndOpLogic(
'assert_eq',
'op0 * op1'
'op0 + op1'
);
const vm = new VirtualMachine();
const dst = new Felt(3n);
Expand Down
Loading