Skip to content

Commit

Permalink
feat(perf): speed up construction of bbjs Frs
Browse files Browse the repository at this point in the history
  • Loading branch information
dbanks12 committed Feb 9, 2025
1 parent 4526059 commit 18151df
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 11 deletions.
24 changes: 16 additions & 8 deletions barretenberg/ts/src/bigint-array/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,20 @@ export function toBigIntBE(bytes: Uint8Array) {
return bigint;
}

export function toBufferBE(value: bigint, byteLength = 32) {
const bytes = new Uint8Array(byteLength);
const view = new DataView(bytes.buffer);
for (let i = 0; i < byteLength; i++) {
view.setUint8(byteLength - i - 1, Number(value & BigInt(0xff)));
value >>= BigInt(8);
}
return bytes;
export function bufToBigIntBE(buf: Buffer) {
return (
(buf.readBigInt64BE(0) << 192n) +
(buf.readBigInt64BE(8) << 128n) +
(buf.readBigInt64BE(16) << 64n) +
buf.readBigInt64BE(24)
);
}

export function toBufferBE(value: bigint, byteLength = 32): Buffer {
const buf = Buffer.alloc(byteLength);
buf.writeBigUInt64BE(value >> 192n, 0);
buf.writeBigUInt64BE((value >> 128n) & 0xffffffffffffffffn, 8);
buf.writeBigUInt64BE((value >> 64n) & 0xffffffffffffffffn, 16);
buf.writeBigUInt64BE(value & 0xffffffffffffffffn, 24);
return buf;
}
7 changes: 4 additions & 3 deletions barretenberg/ts/src/types/fields.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { randomBytes } from '../random/index.js';
import { toBigIntBE, toBufferBE } from '../bigint-array/index.js';
import { bufToBigIntBE, toBigIntBE, toBufferBE } from '../bigint-array/index.js';
import { BufferReader, uint8ArrayToHexString } from '../serialize/index.js';

// TODO(#4189): Replace with implementation in yarn-project/foundation/src/fields/fields.ts
Expand All @@ -15,9 +15,10 @@ export class Fr {
static SIZE_IN_BYTES = 32;
value: Uint8Array;

constructor(value: Uint8Array | bigint) {
constructor(value: Uint8Array | bigint | Buffer) {
// We convert buffer value to bigint to be able to check it fits within modulus
const valueBigInt = typeof value === 'bigint' ? value : toBigIntBE(value);
const valueBigInt =
typeof value === 'bigint' ? value : value instanceof Buffer ? bufToBigIntBE(value) : toBigIntBE(value);

if (valueBigInt > Fr.MAX_VALUE) {
throw new Error(`Value 0x${valueBigInt.toString(16)} is greater or equal to field modulus.`);
Expand Down

0 comments on commit 18151df

Please sign in to comment.