Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
62 changes: 29 additions & 33 deletions bindings/napi/blst.zig
Original file line number Diff line number Diff line change
Expand Up @@ -660,13 +660,13 @@ pub fn aggregateWithRandomness(sets: js.Array) !js.Value {
/// All input data should be copied into this struct so the worker thread doesn't depend on
/// any JS-managed memory staying alive.
const AsyncAggRandData = struct {
pks: []PublicKey,
sigs: []Signature,
pk_ptrs: []*const PublicKey,
sig_ptrs: []*const Signature,
pks: []NativePublicKey,
sigs: []NativeSignature,
pk_ptrs: []*const NativePublicKey,
sig_ptrs: []*const NativeSignature,
randomness: []u8,
pk_out: PublicKey,
sig_out: Signature,
pk_out: NativePublicKey,
sig_out: NativeSignature,
err: ?anyerror,
deferred: napi.Deferred,
work: napi.c.napi_async_work,
Expand Down Expand Up @@ -710,23 +710,23 @@ fn asyncAggRand_execute(_: napi.Env, data: *AsyncAggRandData) void {
/// Ran on the JS thread once the worker has finished. Always settles the
/// promise — `settle` does the resolve/reject; if it errors we fall back to a
/// bare reject so callers never see a dangling Promise.
fn asyncAggRand_complete(env: napi.Env, status: napi.status.Status, data: *AsyncAggRandData) void {
fn asyncAggRand_complete(env: napi.Env, stat: napi.status.Status, data: *AsyncAggRandData) void {
defer {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The variable name stat is an abbreviation of status, which violates the repository style guide (Rule 221). Additionally, the function name asyncAggRand_complete uses an underscore, violating the camelCase requirement for function names (Rule 216). Finally, per Rule 51, function arguments should be asserted to ensure they are valid before use.

fn asyncAggRand_complete(env: napi.Env, status: napi.status.Status, data: *AsyncAggRandData) void {
    std.debug.assert(env.env != null);
    std.debug.assert(data.work != null);
    defer {
References
  1. Do not abbreviate variable names. (link)
  2. Use camelCase for function names. (link)
  3. Assert all function arguments and return values. The assertion density of the code must average a minimum of two assertions per function. (link)

napi.status.check(napi.c.napi_delete_async_work(env.env, data.work)) catch {};
data.destroy();
}

settle(env, status, data) catch {
settle(env, stat, data) catch {
// Catch all rejection: if we reach this point we might want
// better errors upstream
rejectWithError(env, data.deferred, "asyncAggregateWithRandomness", "InternalError") catch {};
};
}

fn settle(env: napi.Env, status: napi.status.Status, data: *AsyncAggRandData) !void {
if (status != .ok) {
fn settle(env: napi.Env, stat: napi.status.Status, data: *AsyncAggRandData) !void {
if (stat != .ok) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The variable name stat is an abbreviation of status (Rule 221). Please also add assertions for the function arguments to comply with the repository's assertion density requirements (Rule 51).

fn settle(env: napi.Env, status: napi.status.Status, data: *AsyncAggRandData) !void {
    std.debug.assert(env.env != null);
    std.debug.assert(data.pks.ptr != null);
    if (status != .ok) {
References
  1. Do not abbreviate variable names. (link)
  2. Assert all function arguments and return values. (link)

// libuv's async work itself failed (e.g. cancelled), not crypto.
return rejectWithError(env, data.deferred, "asyncAggregateWithRandomness/asyncWork", @tagName(status));
return rejectWithError(env, data.deferred, "asyncAggregateWithRandomness/asyncWork", @tagName(stat));
}
if (data.err) |err| {
// Worker captured a Zig error — surface its name as the JS Error.code
Expand All @@ -735,13 +735,8 @@ fn settle(env: napi.Env, status: napi.status.Status, data: *AsyncAggRandData) !v
return rejectWithError(env, data.deferred, "asyncAggregateWithRandomness", @errorName(err));
}

const pk_value: NativePublicKey = .{};
const pk_unwrapped = try env.unwrap(PublicKey, pk_value);
pk_unwrapped.* = data.pk_out;

const sig_value: NativeSignature = .{};
const sig_unwrapped = try env.unwrap(Signature, sig_value);
sig_unwrapped.* = data.sig_out;
const pk_value = napi.Value{ .env = env.env, .value = js.convertReturn(PublicKey, .{ .raw = data.pk_out }, env.env) };
const sig_value = napi.Value{ .env = env.env, .value = js.convertReturn(Signature, .{ .raw = data.sig_out }, env.env) };

const result = try env.createObject();
try result.setNamedProperty("pk", pk_value);
Expand Down Expand Up @@ -777,24 +772,25 @@ fn rejectWithError(env: napi.Env, deferred: napi.Deferred, where: []const u8, co
/// 1) sets: Array of {pk: PublicKey, sig: Uint8Array}
///
/// Returns: Promise<{pk: PublicKey, sig: Signature}>
pub fn asyncAggregateWithRandomness(env: napi.Env, cb: napi.CallbackInfo(1)) !napi.Value {
const sets = cb.arg(0);
const n = try sets.getArrayLength();
pub fn asyncAggregateWithRandomness(sets: js.Array) !js.Value {
const n = try sets.length();
Comment on lines +775 to +776

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Per Rule 51 of the repository style guide, all function arguments must be asserted. Please add an assertion for the sets argument.

pub fn asyncAggregateWithRandomness(sets: js.Array) !js.Value {
    std.debug.assert(sets.val != null);
    const n = try sets.length();
References
  1. Assert all function arguments and return values. (link)


if (n == 0) return error.EmptyArray;
if (n > MAX_AGGREGATE_PER_JOB) return error.TooManySets;
if (thread_pool == null) return error.PoolNotInitialized;

const env = js.env();

const data = try allocator.create(AsyncAggRandData);
errdefer allocator.destroy(data);

data.pks = try allocator.alloc(PublicKey, n);
data.pks = try allocator.alloc(NativePublicKey, n);
errdefer allocator.free(data.pks);
data.sigs = try allocator.alloc(Signature, n);
data.sigs = try allocator.alloc(NativeSignature, n);
errdefer allocator.free(data.sigs);
data.pk_ptrs = try allocator.alloc(*const PublicKey, n);
data.pk_ptrs = try allocator.alloc(*const NativePublicKey, n);
errdefer allocator.free(data.pk_ptrs);
data.sig_ptrs = try allocator.alloc(*const Signature, n);
data.sig_ptrs = try allocator.alloc(*const NativeSignature, n);
errdefer allocator.free(data.sig_ptrs);
data.randomness = try allocator.alloc(u8, n * 32);
errdefer allocator.free(data.randomness);
Expand All @@ -807,16 +803,16 @@ pub fn asyncAggregateWithRandomness(env: napi.Env, cb: napi.CallbackInfo(1)) !na
napi_io.get().random(data.randomness);

for (0..n) |i| {
const set_value = try sets.getElement(@intCast(i));
const set = (try sets.get(@intCast(i))).toValue();

const pk_value = try set_value.getNamedProperty("pk");
const unwrapped_pk = try env.unwrap(PublicKey, pk_value);
data.pks[i] = unwrapped_pk.*;
const pk_napi = try set.getNamedProperty("pk");
const wrapped_pk = try env.unwrap(PublicKey, pk_napi);
data.pks[i] = wrapped_pk.raw;
data.pk_ptrs[i] = &data.pks[i];

const sig_value = try set_value.getNamedProperty("sig");
const sig_bytes = try sig_value.getTypedarrayInfo();
data.sigs[i] = Signature.deserialize(sig_bytes.data[0..]) catch return error.DeserializationFailed;
const sig_napi = try set.getNamedProperty("sig");
const sig_bytes = try uint8SliceFromValue(.{ .val = sig_napi });
data.sigs[i] = NativeSignature.deserialize(sig_bytes[0..]) catch return error.DeserializationFailed;
data.sig_ptrs[i] = &data.sigs[i];
}

Expand All @@ -835,5 +831,5 @@ pub fn asyncAggregateWithRandomness(env: napi.Env, cb: napi.CallbackInfo(1)) !na

try work.queue();

return data.deferred.getPromise();
return .{ .val = data.deferred.getPromise() };
}
82 changes: 82 additions & 0 deletions bindings/test/blst.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
aggregateSerializedPublicKeys,
aggregateVerify,
aggregateWithRandomness,
asyncAggregateWithRandomness,
fastAggregateVerify,
verify,
verifyMultipleAggregateSignatures,
Expand Down Expand Up @@ -357,6 +358,87 @@ describe("blst", () => {
expect(() => aggregateWithRandomness(input)).toThrow();
});
});

describe("asyncAggregateWithRandomness", () => {
it("should be exported as a function", () => {
expect(typeof asyncAggregateWithRandomness).toBe("function");
});

it("should return a Promise", () => {
const {sets} = getTestSetsSameMessage(2);
const input = sets.map((s) => ({pk: s.pk, sig: s.sig.toBytes()}));
const result = asyncAggregateWithRandomness(input);
expect(result).toBeInstanceOf(Promise);
return result;
});

it("should resolve with aggregated pk and sig instances", async () => {
const {sets} = getTestSetsSameMessage(8);
const input = sets.map((s) => ({pk: s.pk, sig: s.sig.toBytes()}));
const result = await asyncAggregateWithRandomness(input);
expect(result).toHaveProperty("pk");
expect(result).toHaveProperty("sig");
expect(result.pk).toBeInstanceOf(PublicKey);
expect(result.sig).toBeInstanceOf(Signature);
});

it("should produce a valid aggregated signature", async () => {
const {msg, sets} = getTestSetsSameMessage(8);
const input = sets.map((s) => ({pk: s.pk, sig: s.sig.toBytes()}));
const {pk, sig} = await asyncAggregateWithRandomness(input);
expect(verify(msg, pk, sig, false, false)).toBe(true);
});

it("should work with a single set", async () => {
const {msg, sets} = getTestSetsSameMessage(1);
const input = sets.map((s) => ({pk: s.pk, sig: s.sig.toBytes()}));
const {pk, sig} = await asyncAggregateWithRandomness(input);
expect(verify(msg, pk, sig, false, false)).toBe(true);
});

it("should fail verification against a different message", async () => {
const {sets} = getTestSetsSameMessage(4);
const input = sets.map((s) => ({pk: s.pk, sig: s.sig.toBytes()}));
const {pk, sig} = await asyncAggregateWithRandomness(input);
const wrongMessage = new Uint8Array(32).fill(0);
expect(verify(wrongMessage, pk, sig, false, false)).toBe(false);
});

it("should match the synchronous aggregateWithRandomness verification result", async () => {
const {msg, sets} = getTestSetsSameMessage(6);
const input = sets.map((s) => ({pk: s.pk, sig: s.sig.toBytes()}));
const syncResult = aggregateWithRandomness(input);
const asyncResult = await asyncAggregateWithRandomness(input);
// Randomness differs between calls so signatures aren't byte-equal,
// but both must verify against the shared message.
expect(verify(msg, syncResult.pk, syncResult.sig, false, false)).toBe(true);
expect(verify(msg, asyncResult.pk, asyncResult.sig, false, false)).toBe(true);
});

it("should reject on empty input", async () => {
await expect(Promise.resolve().then(() => asyncAggregateWithRandomness([]))).rejects.toThrow();
});

it("should reject on invalid signature bytes", async () => {
const {sets} = getTestSetsSameMessage(4);
const input = sets.map((s) => ({pk: s.pk, sig: s.sig.toBytes()}));
input[2].sig = new Uint8Array(96).fill(0xff);
await expect(Promise.resolve().then(() => asyncAggregateWithRandomness(input))).rejects.toThrow();
});

it("should resolve concurrent invocations correctly", async () => {
const {msg, sets} = getTestSetsSameMessage(8);
const input = sets.map((s) => ({pk: s.pk, sig: s.sig.toBytes()}));
const results = await Promise.all([
asyncAggregateWithRandomness(input),
asyncAggregateWithRandomness(input),
asyncAggregateWithRandomness(input),
]);
for (const {pk, sig} of results) {
expect(verify(msg, pk, sig, false, false)).toBe(true);
}
});
});
});

const DEFAULT_TEST_MESSAGE = Uint8Array.from(Buffer.from("lodestarlodestarlodestarlodestar"));
Expand Down
Loading