Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement spec tests #5

Merged
merged 8 commits into from
Feb 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,9 @@ jobs:
run: bun install

# Run unit tests using "bun test:unit"
- name: Run Unit Tests
run: bun test:unit
- name: Unit Tests
run: bun test:unit
- name: Download spec tests
run: bun download-spec-tests
- name: Spec tests
run: bun test:spec
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -178,4 +178,8 @@ dist
bun.lockb

# prebuild
prebuild
prebuild

# Eth2.0 spec tests data
spec-tests
spec-tests-bls
9 changes: 7 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,18 @@
"module": "src/index.ts",
"type": "module",
"devDependencies": {
"@types/bun": "latest"
"@types/bun": "latest",
"@types/js-yaml": "^4.0.9",
"tar": "^7.4.0",
"js-yaml": "^4.1.0"
},
"peerDependencies": {
"typescript": "^5.0.0"
},
"scripts": {
"test:unit": "bun test test/unit",
"postinstall": "bun scripts/install.ts"
"test:spec": "bun test test/spec/*.test.ts",
"postinstall": "bun scripts/install.ts",
"download-spec-tests": "bun test/spec/downloadTests.ts"
}
}
2 changes: 1 addition & 1 deletion scripts/install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {ReadableStream} from "stream/web";
import {createWriteStream, existsSync, mkdirSync} from "fs";
import {PREBUILD_DIR, getBinaryName, getPrebuiltBinaryPath} from "../utils";

const VERSION = "0.1.0-rc.1";
const VERSION = "0.1.0-rc.3";

// CLI runner and entrance for this file when called by npm/yarn
install().then(
Expand Down
4 changes: 2 additions & 2 deletions src/secretKey.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { binding } from "./binding";
import { BLST_SUCCESS, PUBLIC_KEY_LENGTH_UNCOMPRESSED, SECRET_KEY_LENGTH } from "./const";
import { BLST_SUCCESS, SECRET_KEY_LENGTH } from "./const";
import { PublicKey } from "./publicKey";
import { Signature } from "./signature";
import { blstErrorToReason, fromHex, toError, toHex } from "./util";
import { fromHex, toError, toHex } from "./util";

export class SecretKey {
private blst_point: Uint8Array;
Expand Down
6 changes: 3 additions & 3 deletions src/signature.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { binding, writeReference } from "./binding";
import { BLST_SUCCESS, SIGNATURE_LENGTH_COMPRESSED, SIGNATURE_LENGTH_UNCOMPRESSED } from "./const";
import { blstErrorToReason, fromHex, toHex } from "./util";
import { fromHex, toError, toHex } from "./util";

export class Signature {
// this is mapped directly to `*const SignatureType` in Zig
Expand Down Expand Up @@ -43,7 +43,7 @@ export class Signature {
}

if (res !== BLST_SUCCESS) {
throw new Error(blstErrorToReason(res));
throw toError(res);
}

return new Signature(buffer);
Expand Down Expand Up @@ -90,7 +90,7 @@ export class Signature {
public sigValidate(sigInfcheck?: boolean | undefined | null): void {
const res = binding.validateSignature(this.blst_point, sigInfcheck ?? true);
if (res !== BLST_SUCCESS) {
throw new Error(blstErrorToReason(res));
throw toError(res);
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@ export function fromHex(hex: string): Uint8Array {
export function toError(blstErrorCode: number): Error {
const message = blstErrorToReason(blstErrorCode);
const error = new Error(message);
// this make it compliant to napi-rs binding
(error as unknown as {code: string}).code = blstErrorToCode(blstErrorCode);
return error;
}

export function blstErrorToReason(blstErrorCode: number): string {
function blstErrorToReason(blstErrorCode: number): string {
switch (blstErrorCode) {
case 0:
return "BLST_SUCCESS";
Expand Down
3 changes: 2 additions & 1 deletion src/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ export function verify(msg: Uint8Array, pk: PublicKey, sig: Signature, pkValidat
*/
export function aggregateVerify(msgs: Array<Uint8Array>, pks: Array<PublicKey>, sig: Signature, pkValidate?: boolean | undefined | null, sigsGroupcheck?: boolean | undefined | null): boolean {
if (msgs.length < 1) {
throw new Error("At least one message is required");
// this is the same to the original napi-rs blst-ts
return false;
}
if (msgs.length !== pks.length) {
throw new Error("Number of messages must be equal to the number of public keys");
Expand Down
5 changes: 5 additions & 0 deletions src/verifyMultipleAggregateSignatures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ export function verifyMultipleAggregateSignatures(sets: SignatureSet[], pksValid

writeSignatureSetsReference(sets, signature_sets_ref.subarray(0, sets.length * 2));
const msgLength = 32;
for (const set of sets) {
if (set.msg.length !== msgLength) {
throw new Error("All messages must be 32 bytes");
}
}
const res = binding.verifyMultipleAggregateSignatures(signature_sets_ref, sets.length, msgLength, pksValidate ?? false, sigsGroupcheck ?? false, pairing, pairing.length);
return res === 0;
}
Expand Down
11 changes: 11 additions & 0 deletions test/spec/downloadTests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import {downloadTests} from "./utils";
import {ethereumConsensusSpecsTests, blsSpecTests} from "./specTestVersioning";

/* eslint-disable no-console */

for (const downloadTestOpts of [ethereumConsensusSpecsTests, blsSpecTests]) {
downloadTests(downloadTestOpts, console.log).catch((e: Error) => {
console.error(e);
process.exit(1);
});
}
213 changes: 213 additions & 0 deletions test/spec/functions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
import {
SecretKey,
PublicKey,
Signature,
aggregatePublicKeys,
aggregateSignatures,
verify as VERIFY,
aggregateVerify,
fastAggregateVerify,
verifyMultipleAggregateSignatures,
type SignatureSet,
} from "../../src/index.ts";
import {type CodeError, fromHex} from "../utils";
import {G2_POINT_AT_INFINITY} from "./utils";

export const testFnByName: Record<string, (data: any) => any> = {
sign,
eth_aggregate_pubkeys,
aggregate,
verify,
aggregate_verify,
fast_aggregate_verify,
eth_fast_aggregate_verify,
batch_verify,
deserialization_G1,
deserialization_G2,
};

function catchBLSTError(e: unknown): boolean {
if ((e as CodeError).code?.startsWith("BLST")) return false;
throw e;
}

/**
* ```
* input: List[BLS Signature] -- list of input BLS signatures
* output: BLS Signature -- expected output, single BLS signature or empty.
* ```
*/
function aggregate(input: string[]): string | null {
return aggregateSignatures(input.map((hex) => Signature.fromHex(hex))).toHex();
}

/**
* ```
* input:
* pubkeys: List[BLS Pubkey] -- the pubkeys
* messages: List[bytes32] -- the messages
* signature: BLS Signature -- the signature to verify against pubkeys and messages
* output: bool -- true (VALID) or false (INVALID)
* ```
*/
function aggregate_verify(input: {pubkeys: string[]; messages: string[]; signature: string}): boolean {
const {pubkeys, messages, signature} = input;
try {
return aggregateVerify(
messages.map(fromHex),
pubkeys.map((hex) => PublicKey.fromHex(hex)),
Signature.fromHex(signature)
);
} catch (e) {
return catchBLSTError(e);
}
}

/**
* ```
* input: List[BLS Signature] -- list of input BLS signatures
* output: BLS Signature -- expected output, single BLS signature or empty.
* ```
*/
function eth_aggregate_pubkeys(input: string[]): string | null {
return aggregatePublicKeys(input.map((hex) => PublicKey.fromHex(hex, true))).toHex();
}

/**
* ```
* input:
* pubkeys: List[BLS Pubkey] -- list of input BLS pubkeys
* message: bytes32 -- the message
* signature: BLS Signature -- the signature to verify against pubkeys and message
* output: bool -- true (VALID) or false (INVALID)
* ```
*/
function eth_fast_aggregate_verify(input: {pubkeys: string[]; message: string; signature: string}): boolean {
const {pubkeys, message, signature} = input;

if (pubkeys.length === 0 && signature === G2_POINT_AT_INFINITY) {
return true;
}

try {
return fastAggregateVerify(
fromHex(message),
pubkeys.map((hex) => PublicKey.fromHex(hex, true)),
Signature.fromHex(signature)
);
} catch (e) {
return catchBLSTError(e);
}
}

/**
* ```
* input:
* pubkeys: List[BLS Pubkey] -- list of input BLS pubkeys
* message: bytes32 -- the message
* signature: BLS Signature -- the signature to verify against pubkeys and message
* output: bool -- true (VALID) or false (INVALID)
* ```
*/
function fast_aggregate_verify(input: {pubkeys: string[]; message: string; signature: string}): boolean {
const {pubkeys, message, signature} = input;

try {
return fastAggregateVerify(
fromHex(message),
pubkeys.map((hex) => PublicKey.fromHex(hex, true)),
Signature.fromHex(signature)
);
} catch (e) {
return catchBLSTError(e);
}
}

/**
* input:
* privkey: bytes32 -- the private key used for signing
* message: bytes32 -- input message to sign (a hash)
* output: BLS Signature -- expected output, single BLS signature or empty.
*/
function sign(input: {privkey: string; message: string}): string | null {
const {privkey, message} = input;
return SecretKey.fromHex(privkey).sign(fromHex(message)).toHex();
}

/**
* input:
* pubkey: bytes48 -- the pubkey
* message: bytes32 -- the message
* signature: bytes96 -- the signature to verify against pubkey and message
* output: bool -- VALID or INVALID
*/
function verify(input: {pubkey: string; message: string; signature: string}): boolean {
const {pubkey, message, signature} = input;
try {
return VERIFY(fromHex(message), PublicKey.fromHex(pubkey), Signature.fromHex(signature));
} catch (e) {
return catchBLSTError(e);
}
}

/**
* ```
* input:
* pubkeys: List[bytes48] -- the pubkeys
* messages: List[bytes32] -- the messages
* signatures: List[bytes96] -- the signatures to verify against pubkeys and messages
* output: bool -- VALID or INVALID
* ```
* https://github.com/ethereum/bls12-381-tests/blob/master/formats/batch_verify.md
*/
function batch_verify(input: {pubkeys: string[]; messages: string[]; signatures: string[]}): boolean | null {
const length = input.pubkeys.length;
if (input.messages.length !== length && input.signatures.length !== length) {
throw new Error("Invalid spec test. Must have same number in each array. Check spec yaml file");
}
const sets: SignatureSet[] = [];
try {
for (let i = 0; i < length; i++) {
sets.push({
msg: fromHex(input.messages[i]),
pk: PublicKey.fromHex(input.pubkeys[i]),
sig: Signature.fromHex(input.signatures[i]),
});
}
return verifyMultipleAggregateSignatures(sets);
} catch (e) {
return catchBLSTError(e);
}
}

/**
* ```
* input: pubkey: bytes48 -- the pubkey
* output: bool -- VALID or INVALID
* ```
* https://github.com/ethereum/bls12-381-tests/blob/master/formats/deserialization_G1.md
*/
function deserialization_G1(input: {pubkey: string}): boolean {
try {
PublicKey.fromHex(input.pubkey, true);
return true;
} catch (e) {
return catchBLSTError(e);
}
}

/**
* ```
* input: signature: bytes92 -- the signature
* output: bool -- VALID or INVALID
* ```
* https://github.com/ethereum/bls12-381-tests/blob/master/formats/deserialization_G2.md
*/
function deserialization_G2(input: {signature: string}): boolean {
try {
Signature.fromHex(input.signature, true);
return true;
} catch (e) {
return catchBLSTError(e);
}
}
Loading