diff --git a/crypto/finite_field.ts b/crypto/finite_field.ts index 8c5b24f9..15070503 100644 --- a/crypto/finite_field.ts +++ b/crypto/finite_field.ts @@ -214,6 +214,13 @@ function createField( } return BigInt('0b' + binary.reverse().join('')); }, + leftShift(x: bigint, bits: number, maxBitSize: number = 64) { + let shifted = x << BigInt(bits); + return shifted & ((1n << BigInt(maxBitSize)) - 1n); + }, + rightShift(x: bigint, bits: number) { + return x >> BigInt(bits); + }, }; } diff --git a/lib/encoding.ts b/lib/encoding.ts index 4ecc5861..9d647c24 100644 --- a/lib/encoding.ts +++ b/lib/encoding.ts @@ -123,7 +123,7 @@ const Bijective = { }; function toBytesBijective(fields: Field[], p: bigint) { - let fieldsBigInts = fields.map(fieldToBigInt); + let fieldsBigInts = fields.map((x) => x.toBigInt()); let bytesBig = changeBase(fieldsBigInts, p, bytesBase); let bytes = bigIntArrayToBytes(bytesBig, bytesPerBigInt); return bytes; @@ -132,26 +132,12 @@ function toBytesBijective(fields: Field[], p: bigint) { function toFieldsBijective(bytes: Uint8Array, p: bigint) { let bytesBig = bytesToBigIntArray(bytes, bytesPerBigInt); let fieldsBigInts = changeBase(bytesBig, bytesBase, p); - let fields = fieldsBigInts.map(bigIntToField); + let fields = fieldsBigInts.map(Field); return fields; } -// a constant field is internally represented as {value: [0, Uint8Array(32)]} function bytesOfConstantField(field: Field): Uint8Array { - let value = (field as any).value; - if (value[0] !== 0) throw Error('Field is not constant'); - return value[1]; -} - -function fieldToBigInt(field: Field) { - let bytes = bytesOfConstantField(field); - return bytesToBigInt(bytes); -} - -function bigIntToField(x: bigint) { - let field = Field(1); - (field as any).value = [0, bigIntToBytes(x, 32)]; - return field; + return Uint8Array.from(Field.toBytes(field)); } function bigIntToBytes(x: bigint, length: number) {