Skip to content
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
41 changes: 41 additions & 0 deletions bindings/napi/pubkeys.zig
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const napi_io = @import("./io.zig");
const allocator = std.heap.page_allocator;

const default_initial_capacity: u32 = 0;
const max_stack_aggregate_pubkeys = 512;

pub const State = struct {
pubkey2index: PubkeyIndexMap = undefined,
Expand Down Expand Up @@ -175,6 +176,46 @@ pub fn get(index: js.Number) !?blst_bindings.PublicKey {
return .{ .raw = state.index2pubkey.items[@intCast(idx)] };
}

/// Aggregate multiple `PublicKey`s by the given
/// validator `indices` into one.
///
/// Validation is not required here since it is done upon
/// processing validator deposits.
///
/// JS: pubkeys.aggregate(indices) → PublicKey
pub fn aggregate(indices: js.Array) !blst_bindings.PublicKey {
if (!state.initialized) return error.PubkeyIndexNotInitialized;

const len = try indices.length();
if (len == 0) return error.EmptyPublicKeyArray;

if (len == 1) {
const idx = try (try indices.getNumber(0)).toU32();
if (idx >= state.index2pubkey.items.len) return error.PubkeyIndexNotFound;
return .{ .raw = state.index2pubkey.items[@intCast(idx)] };
}

var pks_stack: [max_stack_aggregate_pubkeys]bls.PublicKey = undefined;
const pks = if (len <= pks_stack.len)
pks_stack[0..len]
else blk: {
const buf = try allocator.alloc(bls.PublicKey, len);
break :blk buf;
};
defer if (len > pks_stack.len) allocator.free(pks);

for (0..len) |i| {
const idx = try (try indices.getNumber(@intCast(i))).toU32();
if (idx >= state.index2pubkey.items.len) return error.PubkeyIndexNotFound;
pks[i] = state.index2pubkey.items[@intCast(idx)];
}

const agg_pk = bls.AggregatePublicKey.aggregate(pks, false) catch
return error.AggregationFailed;

return .{ .raw = agg_pk.toPublicKey() };
}

/// JS: pubkeys.set(index, pubkeyBytes)
pub fn set(index: js.Number, pubkey: js.Uint8Array) !void {
if (!state.initialized) return error.PubkeyIndexNotInitialized;
Expand Down
2 changes: 2 additions & 0 deletions bindings/src/pubkeys.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ export interface PubkeyCache {
get(index: number): PublicKey | undefined;
/** Same as get(), but throws if the index is not in the cache */
getOrThrow(index: number): PublicKey;
/** Aggregate cached public keys by validator index */
aggregate(indices: number[]): PublicKey;
/** Get validator index by pubkey bytes */
getIndex(pubkey: Uint8Array): number | null;
/** Set both directions atomically — impl owns the PublicKey.fromBytes() deserialization */
Expand Down
5 changes: 5 additions & 0 deletions bindings/src/pubkeys.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ export const pubkeyCache = {
return pk;
},

aggregate(indices) {
if (indices.length === 1) return pubkeyCache.getOrThrow(indices[0]);
return native.aggregate(indices);
},

getIndex(pubkey) {
return native.getIndex(pubkey);
},
Expand Down
12 changes: 11 additions & 1 deletion bindings/test/pubkeys.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {afterAll, beforeAll, describe, expect, it} from "vitest";
import {SecretKey} from "../src/blst.js";
import {SecretKey, aggregatePublicKeys} from "../src/blst.js";
import {pubkeyCache} from "../src/pubkeys.js";

// Generate deterministic valid BLS keypairs for testing
Expand Down Expand Up @@ -43,6 +43,16 @@ describe("pubkeys", () => {
expect(pk1).toBe(pk2);
});

it("aggregates cached pubkeys by index", () => {
const indices = [0, 1, 2];
const expected = aggregatePublicKeys(indices.map((index) => pubkeyCache.getOrThrow(index)));
expect(pubkeyCache.aggregate(indices).toBytes()).toEqual(expected.toBytes());
});

it("returns the cached pubkey for a single-key aggregate", () => {
expect(pubkeyCache.aggregate([1]).toBytes()).toEqual(pubkeyCache.getOrThrow(1).toBytes());
});

it("get returns undefined for out-of-range index", () => {
expect(pubkeyCache.get(0xffffffff)).toBeUndefined();
});
Expand Down
Loading