Add explicit type check

This commit is contained in:
Justin Traglia 2023-02-22 09:10:09 -06:00
parent d5bd326877
commit 4a77aeff26
2 changed files with 25 additions and 12 deletions

View File

@ -82,10 +82,11 @@ function requireSetupHandle(): SetupHandle {
}
function checkBlob(blob: Blob) {
if (!(blob instanceof Uint8Array)) {
throw new Error("Expected blob to be a UInt8Array.");
}
if (blob.length != BYTES_PER_BLOB) {
throw new Error(
`Expected blob to be UInt8Array of ${BYTES_PER_BLOB} bytes.`,
);
throw new Error(`Expected blob to be ${BYTES_PER_BLOB} bytes.`);
}
}
@ -96,10 +97,11 @@ function checkBlobs(blobs: Blob[]) {
}
function checkCommitment(commitment: KZGCommitment) {
if (!(commitment instanceof Uint8Array)) {
throw new Error("Expected commitment to be a UInt8Array.");
}
if (commitment.length != BYTES_PER_COMMITMENT) {
throw new Error(
`Expected commitment to be UInt8Array of ${BYTES_PER_COMMITMENT} bytes.`,
);
throw new Error(`Expected commitment to be ${BYTES_PER_COMMITMENT} bytes.`);
}
}
@ -110,10 +112,11 @@ function checkCommitments(commitments: KZGCommitment[]) {
}
function checkProof(proof: KZGProof) {
if (!(proof instanceof Uint8Array)) {
throw new Error("Expected proof to be a UInt8Array.");
}
if (proof.length != BYTES_PER_PROOF) {
throw new Error(
`Expected proof to be UInt8Array of ${BYTES_PER_PROOF} bytes.`,
);
throw new Error(`Expected proof to be ${BYTES_PER_PROOF} bytes.`);
}
}
@ -124,9 +127,12 @@ function checkProofs(proofs: KZGProof[]) {
}
function checkFieldElement(field: Bytes32) {
if (!(field instanceof Uint8Array)) {
throw new Error("Expected field element to be a UInt8Array.");
}
if (field.length != BYTES_PER_FIELD_ELEMENT) {
throw new Error(
`Expected field element to be UInt8Array of ${BYTES_PER_FIELD_ELEMENT} bytes.`,
`Expected field element to be ${BYTES_PER_FIELD_ELEMENT} bytes.`,
);
}
}

View File

@ -205,14 +205,14 @@ describe("C-KZG", () => {
it("throws as expected when given an argument of invalid type", () => {
// @ts-expect-error
expect(() => blobToKzgCommitment("wrong type")).toThrowError(
"Expected blob to be UInt8Array of 131072 bytes",
"Expected blob to be a UInt8Array",
);
});
it("throws as expected when given an argument of invalid length", () => {
expect(() =>
blobToKzgCommitment(randomBytes(BYTES_PER_BLOB - 1)),
).toThrowError("Expected blob to be UInt8Array of 131072 bytes");
).toThrowError("Expected blob to be 131072 bytes");
});
});
@ -281,6 +281,13 @@ describe("C-KZG", () => {
});
describe("edge cases for verifyBlobKzgProofBatch", () => {
it("should reject non-bytearray blob", () => {
expect(() =>
// @ts-expect-error
verifyBlobKzgProofBatch(["foo", "bar"], [], []),
).toThrowError("Expected blob to be a UInt8Array");
});
it("zero blobs/commitments/proofs should verify as true", () => {
expect(verifyBlobKzgProofBatch([], [], [])).toBe(true);
});