diff --git a/packages/eddsa-poseidon/src/utils.ts b/packages/eddsa-poseidon/src/utils.ts index 7ffc3dea..b20df6bc 100644 --- a/packages/eddsa-poseidon/src/utils.ts +++ b/packages/eddsa-poseidon/src/utils.ts @@ -59,18 +59,21 @@ export function checkPrivateKey(privateKey: Buffer | Uint8Array | string): Buffe } /** - * Validates and converts a BigNumberish message to a bigint. + * Validates and converts a BigNumberish message to a bigint. Ensures the message size does not exceed 32 bytes. * @param message The message to check and convert. * @returns The message as a bigint. */ export function checkMessage(message: BigNumberish): bigint { requireTypes(message, "message", ["bignumberish", "string"]) - if (isBigNumberish(message)) { - return bigNumberishToBigInt(message) - } + const bigIntMessage = isBigNumberish(message) + ? bigNumberishToBigInt(message) + : bufferToBigInt(Buffer.from(message as string)) - return bufferToBigInt(Buffer.from(message as string)) + const maxLength = 2n ** 256n / 2n + if (bigIntMessage < maxLength * -1n || bigIntMessage >= maxLength) + throw new Error(`Message length is larger than 32 bytes`) + return bigIntMessage } /** diff --git a/packages/eddsa-poseidon/tests/eddsa-poseidon-blake1.test.ts b/packages/eddsa-poseidon/tests/eddsa-poseidon-blake1.test.ts index f0f13c81..b42d87cf 100644 --- a/packages/eddsa-poseidon/tests/eddsa-poseidon-blake1.test.ts +++ b/packages/eddsa-poseidon/tests/eddsa-poseidon-blake1.test.ts @@ -138,6 +138,30 @@ describe("EdDSAPoseidon", () => { expect(fun).toThrow(`Parameter 'message' is none of the following types: bignumberish, string`) }) + it("Should throw an error if the message is larger than 32 Bytes [string]", async () => { + const message = "abcdefghijklmnopqrstuvwxyz1234567" + + const fun = () => signMessage(privateKey, message) + + expect(fun).toThrow(`Message length is larger than 32 bytes`) + }) + + it("Should throw an error if the message is larger than 32 Bytes [number]", async () => { + const message = 2 ** 255 + + const fun = () => signMessage(privateKey, message) + + expect(fun).toThrow(`Message length is larger than 32 bytes`) + }) + + it("Should throw an error if the message is larger than 32 Bytes [-number]", async () => { + const message = -(2n ** 255n + 1n) + + const fun = () => signMessage(privateKey, message) + + expect(fun).toThrow(`Message length is larger than 32 bytes`) + }) + it("Should verify a signature (numeric)", async () => { const publicKey = derivePublicKey(privateKey) const signature = signMessage(privateKey, message)