diff --git a/yarn-project/foundation/src/fields/fields.ts b/yarn-project/foundation/src/fields/fields.ts index a0233d91a99..a3d65d3f333 100644 --- a/yarn-project/foundation/src/fields/fields.ts +++ b/yarn-project/foundation/src/fields/fields.ts @@ -25,9 +25,6 @@ type DerivedField = { * Conversions from Buffer to BigInt and vice-versa are not cheap. * We allow construction with either form and lazily convert to other as needed. * We only check we are within the field modulus when initializing with bigint. - * If NODE_ENV === 'test', we will always initialize both types to check the modulus. - * This is also necessary in test environment as a lot of tests just use deep equality to check equality. - * WARNING: This could lead to a bugs in production that don't reveal in tests, but it's low risk. */ abstract class BaseField { static SIZE_IN_BYTES = 32; @@ -67,14 +64,6 @@ abstract class BaseField { } else { throw new Error(`Type '${typeof value}' with value '${value}' passed to BaseField ctor.`); } - - // Loads of our tests are just doing deep equality rather than calling e.g. toBigInt() first. - // This ensures the deep equality passes regardless of the internal representation. - // It also ensures the value range is checked even when initializing as a buffer. - if (process.env.NODE_ENV === 'test') { - this.toBuffer(); - this.toBigInt(); - } } protected abstract modulus(): bigint; @@ -405,3 +394,22 @@ export const GrumpkinScalar = Fq; export function reduceFn(fn: (input: TInput) => Buffer, field: DerivedField) { return (input: TInput) => fromBufferReduce(fn(input), field); } + +/** If we are in test mode, we register a special equality for fields. */ +if (process.env.NODE_ENV === 'test') { + const areFieldsEqual = (a: unknown, b: unknown): boolean | undefined => { + const isAField = a instanceof BaseField; + const isBField = b instanceof BaseField; + + if (isAField && isBField) { + return a.equals(b); + } else if (isAField === isBField) { + return undefined; + } else { + return false; + } + }; + + // `addEqualityTesters` doesn't seem to be in the types yet. + (expect as any).addEqualityTesters([areFieldsEqual]); +}