-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathblst.zig
More file actions
1032 lines (839 loc) · 34.3 KB
/
blst.zig
File metadata and controls
1032 lines (839 loc) · 34.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Contains the necessary bindings for blst operations in lodestar-ts.
const std = @import("std");
const napi = @import("zapi:zapi");
const bls = @import("bls");
const builtin = @import("builtin");
const getter = @import("napi_property_descriptor.zig").getter;
const method = @import("napi_property_descriptor.zig").method;
const PublicKey = bls.PublicKey;
const Signature = bls.Signature;
const SecretKey = bls.SecretKey;
const Pairing = bls.Pairing;
const AggregatePublicKey = bls.AggregatePublicKey;
const AggregateSignature = bls.AggregateSignature;
const DST = bls.DST;
var gpa: std.heap.DebugAllocator(.{}) = .init;
const allocator = if (builtin.mode == .Debug)
gpa.allocator()
else
std.heap.c_allocator;
/// Per-context (per-thread) instance data for constructor references
const InstanceData = struct {
public_key_ctor_ref: ?napi.c.napi_ref = null,
signature_ctor_ref: ?napi.c.napi_ref = null,
fn init(env: napi.Env) !*InstanceData {
const self = try allocator.create(InstanceData);
errdefer allocator.destroy(self);
self.* = .{};
try napi.status.check(napi.c.napi_set_instance_data(
env.env,
@ptrCast(self),
InstanceData.finalize,
null,
));
return self;
}
fn finalize(env: napi.c.napi_env, data: ?*anyopaque, _: ?*anyopaque) callconv(.C) void {
const self: *InstanceData = @ptrCast(@alignCast(data orelse return));
self.clearRefs(env);
allocator.destroy(self);
}
fn get(env: napi.Env) !*InstanceData {
var raw: ?*anyopaque = null;
try napi.status.check(napi.c.napi_get_instance_data(env.env, &raw));
return @ptrCast(@alignCast(raw orelse return error.InstanceDataNotInitialized));
}
fn clearRefs(self: *InstanceData, env: napi.c.napi_env) void {
if (self.public_key_ctor_ref) |ref| {
napi.status.check(napi.c.napi_delete_reference(env, ref)) catch {};
self.public_key_ctor_ref = null;
}
if (self.signature_ctor_ref) |ref| {
napi.status.check(napi.c.napi_delete_reference(env, ref)) catch {};
self.signature_ctor_ref = null;
}
}
};
fn setRef(env: napi.Env, ctor: napi.Value, slot: *?napi.c.napi_ref) !void {
if (slot.*) |ref| {
try napi.status.check(napi.c.napi_delete_reference(env.env, ref));
}
var ref: napi.c.napi_ref = undefined;
try napi.status.check(napi.c.napi_create_reference(env.env, ctor.value, 1, &ref));
slot.* = ref;
}
fn getFromRef(env: napi.Env, slot: ?napi.c.napi_ref) !napi.Value {
const ref_ = slot orelse return error.RefNotInitialized;
var value: napi.c.napi_value = undefined;
try napi.status.check(napi.c.napi_get_reference_value(env.env, ref_, &value));
return .{
.env = env.env,
.value = value,
};
}
pub fn newPublicKeyInstance(env: napi.Env) !napi.Value {
const state = try InstanceData.get(env);
const ctor = try getFromRef(env, state.public_key_ctor_ref);
return try env.newInstance(ctor, .{});
}
pub fn newSignatureInstance(env: napi.Env) !napi.Value {
const state = try InstanceData.get(env);
const ctor = try getFromRef(env, state.signature_ctor_ref);
return try env.newInstance(ctor, .{});
}
fn coerceToBool(boolish: napi.Value) napi.status.NapiError!bool {
const b = try boolish.coerceToBool();
return b.getValueBool();
}
pub fn PublicKey_finalize(_: napi.Env, pk: *PublicKey, _: ?*anyopaque) void {
allocator.destroy(pk);
}
pub fn PublicKey_ctor(env: napi.Env, cb: napi.CallbackInfo(0)) !napi.Value {
const pk = try allocator.create(PublicKey);
errdefer allocator.destroy(pk);
_ = try env.wrap(cb.this(), PublicKey, pk, PublicKey_finalize, null, null);
return cb.this();
}
/// Converts given array of bytes to a `PublicKey`.
/// 1) bytes: Uint8Array
/// 2) pk_validate: ?bool
pub fn PublicKey_fromBytes(env: napi.Env, cb: napi.CallbackInfo(2)) !napi.Value {
const ctor = cb.this();
const bytes_info = try cb.arg(0).getTypedarrayInfo();
const pk_validate: bool = if (cb.getArg(1)) |sgc|
try coerceToBool(sgc)
else
false;
const pk_value = try env.newInstance(ctor, .{});
const pk = try env.unwrap(PublicKey, pk_value);
pk.* = try PublicKey.deserialize(bytes_info.data[0..]);
if (pk_validate) {
try pk.validate();
}
return pk_value;
}
/// Converts given hex string to a `PublicKey`.
///
/// 1) bytes: Uint8Array
/// 2) pk_validate: ?bool
pub fn PublicKey_fromHex(env: napi.Env, cb: napi.CallbackInfo(2)) !napi.Value {
const ctor = cb.this();
var hex_buf: [PublicKey.SERIALIZE_SIZE * 2 + 2]u8 = undefined;
const hex = try hexFromValue(cb.arg(0), &hex_buf);
const pk_validate: bool = if (cb.getArg(1)) |sgc|
try coerceToBool(sgc)
else
false;
const pk_value = try env.newInstance(ctor, .{});
const pk = try env.unwrap(PublicKey, pk_value);
var buf: [PublicKey.SERIALIZE_SIZE]u8 = undefined;
const bytes = try std.fmt.hexToBytes(&buf, hex);
pk.* = try PublicKey.deserialize(bytes);
if (pk_validate) try pk.validate();
return pk_value;
}
/// Converts given array of bytes to a `PublicKey`.
pub fn PublicKey_validate(env: napi.Env, cb: napi.CallbackInfo(0)) !napi.Value {
const pk = try env.unwrap(PublicKey, cb.this());
try pk.validate();
return try env.getUndefined();
}
/// Serializes this public key to bytes.
pub fn PublicKey_toBytes(env: napi.Env, cb: napi.CallbackInfo(1)) !napi.Value {
const pk = try env.unwrap(PublicKey, cb.this());
const compress = try if (cb.getArg(0)) |c| coerceToBool(c) else true;
if (compress) {
const bytes = pk.compress();
var arraybuffer_bytes: [*]u8 = undefined;
const arraybuffer = try env.createArrayBuffer(PublicKey.COMPRESS_SIZE, &arraybuffer_bytes);
@memcpy(arraybuffer_bytes[0..PublicKey.COMPRESS_SIZE], &bytes);
return try env.createTypedarray(.uint8, PublicKey.COMPRESS_SIZE, arraybuffer, 0);
} else {
const bytes = pk.serialize();
var arraybuffer_bytes: [*]u8 = undefined;
const arraybuffer = try env.createArrayBuffer(PublicKey.SERIALIZE_SIZE, &arraybuffer_bytes);
@memcpy(arraybuffer_bytes[0..PublicKey.SERIALIZE_SIZE], &bytes);
return try env.createTypedarray(.uint8, PublicKey.SERIALIZE_SIZE, arraybuffer, 0);
}
}
pub fn PublicKey_toHex(env: napi.Env, cb: napi.CallbackInfo(1)) !napi.Value {
const pk = try env.unwrap(PublicKey, cb.this());
const compress = try if (cb.getArg(0)) |c| coerceToBool(c) else true;
if (compress) {
const bytes = pk.compress();
const hex = try std.fmt.allocPrint(allocator, "0x{x}", .{std.fmt.fmtSliceHexLower(&bytes)});
defer allocator.free(hex);
return try env.createStringUtf8(hex);
} else {
const bytes = pk.serialize();
const hex = try std.fmt.allocPrint(allocator, "0x{x}", .{std.fmt.fmtSliceHexLower(&bytes)});
defer allocator.free(hex);
return try env.createStringUtf8(hex);
}
}
pub fn Signature_finalize(_: napi.Env, sig: *Signature, _: ?*anyopaque) void {
allocator.destroy(sig);
}
pub fn Signature_ctor(env: napi.Env, cb: napi.CallbackInfo(0)) !napi.Value {
const sig = try allocator.create(Signature);
errdefer allocator.destroy(sig);
_ = try env.wrap(cb.this(), Signature, sig, Signature_finalize, null, null);
return cb.this();
}
/// Converts given array of bytes to a `Signature`.
pub fn Signature_fromBytes(env: napi.Env, cb: napi.CallbackInfo(3)) !napi.Value {
const ctor = cb.this();
const bytes_info = try cb.arg(0).getTypedarrayInfo();
const sig_validate: bool = if (cb.getArg(1)) |sgc|
try coerceToBool(sgc)
else
false;
const sig_infcheck: bool = if (cb.getArg(2)) |v|
try coerceToBool(v)
else
false;
const sig_value = try env.newInstance(ctor, .{});
const sig = try env.unwrap(Signature, sig_value);
sig.* = Signature.deserialize(bytes_info.data[0..]) catch return error.DeserializationFailed;
if (sig_validate) {
try sig.validate(sig_infcheck);
}
return sig_value;
}
/// Converts given hex string to a `Signature`.
///
/// If `sig_validate` is `true`, the public key will be infinity and group checked.
/// If `sig_infcheck` is `false`, the infinity check will be skipped.
pub fn Signature_fromHex(env: napi.Env, cb: napi.CallbackInfo(3)) !napi.Value {
const ctor = cb.this();
var hex_buf: [Signature.SERIALIZE_SIZE * 2 + 2]u8 = undefined;
const hex = try hexFromValue(cb.arg(0), &hex_buf);
const sig_validate: bool = if (cb.getArg(1)) |sgc|
try coerceToBool(sgc)
else
false;
const sig_infcheck: bool = if (cb.getArg(2)) |v|
try coerceToBool(v)
else
false;
const sig_value = try env.newInstance(ctor, .{});
const sig = try env.unwrap(Signature, sig_value);
var buf: [Signature.SERIALIZE_SIZE]u8 = undefined;
const bytes = try std.fmt.hexToBytes(&buf, hex);
sig.* = Signature.deserialize(bytes) catch return error.DeserializationFailed;
if (sig_validate) try sig.validate(sig_infcheck);
return sig_value;
}
/// Serializes this signature to bytes.
pub fn Signature_toBytes(env: napi.Env, cb: napi.CallbackInfo(1)) !napi.Value {
const sig = try env.unwrap(Signature, cb.this());
const compress = try if (cb.getArg(0)) |c| coerceToBool(c) else true;
if (compress) {
const bytes = sig.compress();
var arraybuffer_bytes: [*]u8 = undefined;
const arraybuffer = try env.createArrayBuffer(Signature.COMPRESS_SIZE, &arraybuffer_bytes);
@memcpy(arraybuffer_bytes[0..Signature.COMPRESS_SIZE], &bytes);
return try env.createTypedarray(.uint8, Signature.COMPRESS_SIZE, arraybuffer, 0);
} else {
const bytes = sig.serialize();
var arraybuffer_bytes: [*]u8 = undefined;
const arraybuffer = try env.createArrayBuffer(Signature.SERIALIZE_SIZE, &arraybuffer_bytes);
@memcpy(arraybuffer_bytes[0..Signature.SERIALIZE_SIZE], &bytes);
return try env.createTypedarray(.uint8, Signature.SERIALIZE_SIZE, arraybuffer, 0);
}
}
pub fn Signature_toHex(env: napi.Env, cb: napi.CallbackInfo(1)) !napi.Value {
const sig = try env.unwrap(Signature, cb.this());
const compress = try if (cb.getArg(0)) |c| coerceToBool(c) else true;
if (compress) {
const bytes = sig.compress();
const hex = try std.fmt.allocPrint(allocator, "0x{x}", .{std.fmt.fmtSliceHexLower(&bytes)});
defer allocator.free(hex);
return try env.createStringUtf8(hex);
} else {
const bytes = sig.serialize();
const hex = try std.fmt.allocPrint(allocator, "0x{x}", .{std.fmt.fmtSliceHexLower(&bytes)});
defer allocator.free(hex);
return try env.createStringUtf8(hex);
}
}
pub fn SecretKey_finalize(_: napi.Env, sk: *SecretKey, _: ?*anyopaque) void {
allocator.destroy(sk);
}
pub fn SecretKey_ctor(env: napi.Env, cb: napi.CallbackInfo(0)) !napi.Value {
const sk = try allocator.create(SecretKey);
errdefer allocator.destroy(sk);
_ = try env.wrap(cb.this(), SecretKey, sk, SecretKey_finalize, null, null);
return cb.this();
}
/// Creates a `SecretKey` from raw bytes.
pub fn SecretKey_fromBytes(env: napi.Env, cb: napi.CallbackInfo(1)) !napi.Value {
const ctor = cb.this();
const bytes_info = try cb.arg(0).getTypedarrayInfo();
if (bytes_info.data.len != SecretKey.serialize_size) {
return error.InvalidSecretKeyLength;
}
const sk_value = try env.newInstance(ctor, .{});
const sk = try env.unwrap(SecretKey, sk_value);
sk.* = SecretKey.deserialize(bytes_info.data[0..SecretKey.serialize_size]) catch return error.DeserializationFailed;
return sk_value;
}
/// Creates a `SecretKey` from a hex string.
pub fn SecretKey_fromHex(env: napi.Env, cb: napi.CallbackInfo(1)) !napi.Value {
const ctor = cb.this();
var hex_buf: [SecretKey.serialize_size * 2 + 3]u8 = undefined;
const hex = try hexFromValue(cb.arg(0), &hex_buf);
const sk_value = try env.newInstance(ctor, .{});
const sk = try env.unwrap(SecretKey, sk_value);
var buf: [SecretKey.serialize_size]u8 = undefined;
const bytes = try std.fmt.hexToBytes(&buf, hex);
sk.* = SecretKey.deserialize(bytes[0..SecretKey.serialize_size]) catch return error.DeserializationFailed;
return sk_value;
}
pub fn SecretKey_toHex(env: napi.Env, cb: napi.CallbackInfo(0)) !napi.Value {
const sk = try env.unwrap(SecretKey, cb.this());
const bytes = sk.serialize();
const hex = try std.fmt.allocPrint(allocator, "0x{x}", .{std.fmt.fmtSliceHexLower(&bytes)});
defer allocator.free(hex);
return try env.createStringUtf8(hex);
}
/// Generates a `SecretKey` from a seed (IKM) using key derivation.
///
/// Seed must be at least 32 bytes.
pub fn SecretKey_fromKeygen(env: napi.Env, cb: napi.CallbackInfo(2)) !napi.Value {
const ctor = cb.this();
const bytes_info = try cb.arg(0).getTypedarrayInfo();
const key_info_data: ?[]const u8 = if (cb.getArg(1)) |ki| blk: {
const typeof = try ki.typeof();
if (typeof == .undefined or typeof == .null) break :blk null;
const info = try ki.getTypedarrayInfo();
if (info.array_type != .uint8) return error.InvalidArgument;
break :blk info.data;
} else null;
if (bytes_info.data.len < 32) return error.InvalidSeedLength;
const sk_value = try env.newInstance(ctor, .{});
const sk = try env.unwrap(SecretKey, sk_value);
sk.* = SecretKey.keyGen(bytes_info.data, key_info_data) catch return error.KeyGenFailed;
return sk_value;
}
/// Signs a message with this `SecretKey`, returns a `Signature`.
pub fn SecretKey_sign(env: napi.Env, cb: napi.CallbackInfo(1)) !napi.Value {
const sk = try env.unwrap(SecretKey, cb.this());
const msg = try cb.arg(0).getTypedarrayInfo();
const sig_value = try newSignatureInstance(env);
const sig = try env.unwrap(Signature, sig_value);
sig.* = sk.sign(msg.data, DST, null);
return sig_value;
}
/// Derives the PublicKey from this SecretKey.
pub fn SecretKey_toPublicKey(env: napi.Env, cb: napi.CallbackInfo(0)) !napi.Value {
const sk = try env.unwrap(SecretKey, cb.this());
const pk_value = try newPublicKeyInstance(env);
const pk = try env.unwrap(PublicKey, pk_value);
pk.* = sk.toPublicKey();
return pk_value;
}
/// Serializes the SecretKey to bytes (32 bytes).
pub fn SecretKey_toBytes(env: napi.Env, cb: napi.CallbackInfo(0)) !napi.Value {
const sk = try env.unwrap(SecretKey, cb.this());
const bytes = sk.serialize();
var arraybuffer_bytes: [*]u8 = undefined;
const arraybuffer = try env.createArrayBuffer(SecretKey.serialize_size, &arraybuffer_bytes);
@memcpy(arraybuffer_bytes[0..SecretKey.serialize_size], &bytes);
return try env.createTypedarray(.uint8, SecretKey.serialize_size, arraybuffer, 0);
}
/// Aggregates multiple Signature objects into one.
///
/// 1) sigs_array: []Signature
/// 2) sigs_groupcheck: bool
pub fn Signature_aggregate(env: napi.Env, cb: napi.CallbackInfo(2)) !napi.Value {
const ctor = cb.this();
const sigs_array = cb.arg(0);
const sigs_groupcheck = try coerceToBool(cb.arg(1));
const sigs_len = try sigs_array.getArrayLength();
if (sigs_len == 0) return error.EmptySignatureArray;
const sigs = try allocator.alloc(Signature, sigs_len);
defer allocator.free(sigs);
for (0..sigs_len) |i| {
const sig_value = try sigs_array.getElement(@intCast(i));
const sig = try env.unwrap(Signature, sig_value);
sigs[i] = sig.*;
}
const agg_sig = AggregateSignature.aggregate(sigs, sigs_groupcheck) catch return error.AggregationFailed;
const sig_value = try env.newInstance(ctor, .{});
const sig = try env.unwrap(Signature, sig_value);
sig.* = agg_sig.toSignature();
return sig_value;
}
/// Validates the signature.
/// Throws an error if the signature is invalid.
pub fn Signature_validate(env: napi.Env, cb: napi.CallbackInfo(1)) !napi.Value {
const sig = try env.unwrap(Signature, cb.this());
const sig_infcheck = try coerceToBool(cb.arg(0));
sig.validate(sig_infcheck) catch return error.InvalidSignature;
return try env.getUndefined();
}
/// Verifies a given `msg` against a `Signature` and a `PublicKey`.
///
/// Returns `true` if signature is valid, `false` otherwise.
///
/// Arguments:
/// 1) msg: Uint8Array
/// 2) pk: PublicKey
/// 3) sig: Signature
/// 4) pk_validate: ?bool
/// 5) sig_groupcheck: ?bool
pub fn blst_verify(env: napi.Env, cb: napi.CallbackInfo(5)) !napi.Value {
const msg_info = try cb.arg(0).getTypedarrayInfo();
const pk = try env.unwrap(PublicKey, cb.arg(1));
const sig = try env.unwrap(Signature, cb.arg(2));
const pk_validate: bool = if (cb.getArg(3)) |sgc|
try coerceToBool(sgc)
else
false;
const sig_groupcheck: bool = if (cb.getArg(4)) |v|
try coerceToBool(v)
else
false;
sig.verify(sig_groupcheck, msg_info.data, DST, null, pk, pk_validate) catch {
return try env.getBoolean(false);
};
return try env.getBoolean(true);
}
/// Verify an aggregated signature against multiple messages and multiple public keys.
/// 1) msgs: Uint8Array[]
/// 2) pks: PublicKey[]
/// 3) sig: Signature
/// 4) pks_validate: ?bool
/// 5) sig_groupcheck: ?bool
pub fn blst_aggregateVerify(
env: napi.Env,
cb: napi.CallbackInfo(5),
) !napi.Value {
const msgs_array = cb.arg(0);
const pks_array = cb.arg(1);
const sig = try env.unwrap(Signature, cb.arg(2));
const pks_validate: bool = if (cb.getArg(3)) |sgc|
try coerceToBool(sgc)
else
false;
const sig_groupcheck: bool = if (cb.getArg(4)) |v|
try coerceToBool(v)
else
false;
const msgs_len = try msgs_array.getArrayLength();
const pks_len = try pks_array.getArrayLength();
if (msgs_len == 0 or pks_len == 0 or msgs_len != pks_len) {
return error.InvalidAggregateVerifyInput;
}
const msgs = try allocator.alloc([32]u8, msgs_len);
defer allocator.free(msgs);
const pks = try allocator.alloc(PublicKey, pks_len);
defer allocator.free(pks);
for (0..msgs_len) |i| {
const msg_value = try msgs_array.getElement(@intCast(i));
const msg_info = try msg_value.getTypedarrayInfo();
if (msg_info.data.len != 32) return error.InvalidMessageLength;
@memcpy(&msgs[i], msg_info.data[0..32]);
const pk_value = try pks_array.getElement(@intCast(i));
const pk = try env.unwrap(PublicKey, pk_value);
pks[i] = pk.*;
}
var pairing_buf: [Pairing.sizeOf()]u8 align(Pairing.buf_align) = undefined;
const result = sig.aggregateVerify(
sig_groupcheck,
&pairing_buf,
msgs,
DST,
pks,
pks_validate,
) catch {
return try env.getBoolean(false);
};
return try env.getBoolean(result);
}
/// Aggregate and verify an array of `PublicKey`s. Returns `false` if pks array is empty or if signature is invalid.
///
/// `msg` (signing root) must be exactly 32 bytes.
///
/// Arguments:
/// 1) msg: Uint8Array
/// 2) pks: PublicKey[]
/// 3) sig: Signature
/// 4) sigs_groupcheck: ?bool
pub fn blst_fastAggregateVerify(env: napi.Env, cb: napi.CallbackInfo(4)) !napi.Value {
const msg_info = try cb.arg(0).getTypedarrayInfo();
if (msg_info.data.len != 32) return error.InvalidMessageLength;
const pks_array = cb.arg(1);
const sig = try env.unwrap(Signature, cb.arg(2));
const sigs_groupcheck = if (cb.getArg(3)) |sgc|
try coerceToBool(sgc)
else
false;
const pks_len = try pks_array.getArrayLength();
if (pks_len == 0) {
return try env.getBoolean(false);
}
const pks = try allocator.alloc(PublicKey, pks_len);
defer allocator.free(pks);
for (0..pks_len) |i| {
const pk_value = try pks_array.getElement(@intCast(i));
const pk = try env.unwrap(PublicKey, pk_value);
pks[i] = pk.*;
}
var pairing_buf: [Pairing.sizeOf()]u8 align(Pairing.buf_align) = undefined;
// `pks_validate` is always false here since we assume proof of possession for public keys.
const result = sig.fastAggregateVerify(sigs_groupcheck, &pairing_buf, msg_info.data[0..32], DST, pks, false) catch {
return try env.getBoolean(false);
};
return try env.getBoolean(result);
}
/// Batch verify multiple signature sets.
/// Returns `false` if verification fails.
///
/// Arguments:
/// 1) sets: Array of { msg: Uint8Array, pk: PublicKey, sig: Signature }
/// 2) pks_validate: ?bool
/// 3) sigs_groupcheck: ?bool
pub fn blst_verifyMultipleAggregateSignatures(env: napi.Env, cb: napi.CallbackInfo(3)) !napi.Value {
const sets = cb.arg(0);
const n_elems = try sets.getArrayLength();
const pks_validate: bool = if (cb.getArg(1)) |v|
try coerceToBool(v)
else
false;
const sigs_groupcheck: bool = if (cb.getArg(2)) |sgc|
try coerceToBool(sgc)
else
false;
if (n_elems == 0) {
return try env.getBoolean(false);
}
const msgs = try allocator.alloc([32]u8, n_elems);
defer allocator.free(msgs);
const pks = try allocator.alloc(*PublicKey, n_elems);
defer allocator.free(pks);
const sigs = try allocator.alloc(*Signature, n_elems);
defer allocator.free(sigs);
const rands = try allocator.alloc([32]u8, n_elems);
defer allocator.free(rands);
var prng = std.Random.DefaultPrng.init(std.crypto.random.int(u64));
const rand = prng.random();
for (0..n_elems) |i| {
const set_value = try sets.getElement(@intCast(i));
const msg_value = try set_value.getNamedProperty("msg");
const msg = try msg_value.getTypedarrayInfo();
if (msg.data.len != 32) return error.InvalidMessageLength;
@memcpy(&msgs[i], msg.data[0..32]);
// Use unwrapped pointers directly - no copy needed
const pk_value = try set_value.getNamedProperty("pk");
pks[i] = try env.unwrap(PublicKey, pk_value);
const sig_value = try set_value.getNamedProperty("sig");
sigs[i] = try env.unwrap(Signature, sig_value);
rand.bytes(&rands[i]);
}
var pairing_buf: [Pairing.sizeOf()]u8 align(Pairing.buf_align) = undefined;
const result = bls.verifyMultipleAggregateSignatures(
&pairing_buf,
n_elems,
msgs,
DST,
pks,
pks_validate,
sigs,
sigs_groupcheck,
rands,
) catch {
return try env.getBoolean(false);
};
return try env.getBoolean(result);
}
/// Aggregate multiple Signature objects into one.
/// Validates each signature if `sigs_groupcheck` is true.
///
/// Arguments:
/// 1) signatures: Signature[]
/// 2) sigs_groupcheck: ?bool
pub fn blst_aggregateSignatures(env: napi.Env, cb: napi.CallbackInfo(2)) !napi.Value {
const sigs_array = cb.arg(0);
const sigs_groupcheck: bool = if (cb.getArg(1)) |sgc|
try coerceToBool(sgc)
else
false;
const sigs_len = try sigs_array.getArrayLength();
if (sigs_len == 0) return error.EmptySignatureArray;
const sigs = try allocator.alloc(Signature, sigs_len);
defer allocator.free(sigs);
for (0..sigs_len) |i| {
const sig_value = try sigs_array.getElement(@intCast(i));
const sig = try env.unwrap(Signature, sig_value);
sigs[i] = sig.*;
}
const agg_sig = AggregateSignature.aggregate(sigs, sigs_groupcheck) catch return error.AggregationFailed;
const result_sig = agg_sig.toSignature();
const sig_value = try newSignatureInstance(env);
const sig = try env.unwrap(Signature, sig_value);
sig.* = result_sig;
return sig_value;
}
/// Aggregate multiple `PublicKey` objects into one.
///
/// Arguments:
/// 1) pks: PublicKey[]
/// 2) pks_validate: ?bool
pub fn blst_aggregatePublicKeys(env: napi.Env, cb: napi.CallbackInfo(2)) !napi.Value {
const pks_array = cb.arg(0);
const pks_len = try pks_array.getArrayLength();
const pks_validate: bool = if (cb.getArg(1)) |v|
try coerceToBool(v)
else
false;
if (pks_len == 0) {
return error.EmptyPublicKeyArray;
}
const pks = try allocator.alloc(PublicKey, pks_len);
defer allocator.free(pks);
for (0..pks_len) |i| {
const pk_value = try pks_array.getElement(@intCast(i));
const pk = try env.unwrap(PublicKey, pk_value);
pks[i] = pk.*;
}
const agg_pk = AggregatePublicKey.aggregate(pks, pks_validate) catch return error.AggregationFailed;
const result_pk = agg_pk.toPublicKey();
const pk_value = try newPublicKeyInstance(env);
const pk = try env.unwrap(PublicKey, pk_value);
pk.* = result_pk;
return pk_value;
}
/// Aggregate public keys from serialized bytes.
///
/// Arguments:
/// 1) serializedPublicKeys: Uint8Array[] - array of serialized (96-bytes each) `PublicKey`s.
pub fn blst_aggregateSerializedPublicKeys(env: napi.Env, cb: napi.CallbackInfo(2)) !napi.Value {
const pks_array = cb.arg(0);
const pks_len = try pks_array.getArrayLength();
const pks_validate: bool = if (cb.getArg(1)) |v|
try coerceToBool(v)
else
false;
if (pks_len == 0) return error.EmptyPublicKeyArray;
const pks = try allocator.alloc(PublicKey, pks_len);
defer allocator.free(pks);
for (0..pks_len) |i| {
const pk_bytes_value = try pks_array.getElement(@intCast(i));
const bytes_info = try pk_bytes_value.getTypedarrayInfo();
pks[i] = PublicKey.deserialize(bytes_info.data) catch
return error.DeserializationFailed;
}
const agg_pk = AggregatePublicKey.aggregate(pks, pks_validate) catch return error.AggregationFailed;
const result_pk = agg_pk.toPublicKey();
const pk_value = try newPublicKeyInstance(env);
const pk = try env.unwrap(PublicKey, pk_value);
pk.* = result_pk;
return pk_value;
}
/// Unpacks a hex string from a `napi.Value`. Returns the slice representing the hex string.
fn hexFromValue(value: napi.Value, buf: []u8) ![]const u8 {
const hex_str = try value.getValueStringUtf8(buf);
const hex = if (hex_str.len >= 2 and hex_str[0] == '0' and hex_str[1] == 'x') hex_str[2..] else hex_str;
return hex;
}
const MAX_AGGREGATE_PER_JOB = bls.MAX_AGGREGATE_PER_JOB;
const AsyncAggregateData = struct {
// Inputs (copied on main thread, freed in complete)
pks: []PublicKey,
sigs: []Signature,
n: usize,
// Outputs (set in execute)
result_pk: PublicKey = .{},
result_sig: Signature = .{},
err: bool = false,
// NAPI handles
deferred: napi.Deferred,
work: napi.AsyncWork(AsyncAggregateData) = undefined,
};
fn asyncAggregateExecute(_: napi.Env, data: *AsyncAggregateData) void {
const n = data.n;
// Generate 32 bytes of randomness per element, 64 meaningful bits (nbits=64)
var rands: [32 * MAX_AGGREGATE_PER_JOB]u8 = undefined;
std.crypto.random.bytes(rands[0 .. n * 32]);
// Build pointer arrays (stack-allocated, MAX_AGGREGATE_PER_JOB is 128)
var pk_refs: [MAX_AGGREGATE_PER_JOB]*const PublicKey = undefined;
var sig_refs: [MAX_AGGREGATE_PER_JOB]*const Signature = undefined;
for (0..n) |i| {
pk_refs[i] = &data.pks[i];
sig_refs[i] = &data.sigs[i];
}
// Per-call scratch allocation (safe for worker threads)
const p1_scratch_size = bls.c.blst_p1s_mult_pippenger_scratch_sizeof(n);
const p2_scratch_size = bls.c.blst_p2s_mult_pippenger_scratch_sizeof(n);
const scratch_size = @max(p1_scratch_size, p2_scratch_size);
const scratch = allocator.alloc(u64, scratch_size) catch {
data.err = true;
return;
};
defer allocator.free(scratch);
// Pippenger multi-scalar multiplication on G1 (pubkeys)
const agg_pk = AggregatePublicKey.aggregateWithRandomness(
pk_refs[0..n],
rands[0 .. n * 32],
false, // already validated
scratch,
) catch {
data.err = true;
return;
};
// Pippenger multi-scalar multiplication on G2 (signatures)
const agg_sig = AggregateSignature.aggregateWithRandomness(
sig_refs[0..n],
rands[0 .. n * 32],
false, // already validated during deserialization
scratch,
) catch {
data.err = true;
return;
};
data.result_pk = agg_pk.toPublicKey();
data.result_sig = agg_sig.toSignature();
}
fn asyncAggregateComplete(env: napi.Env, _: napi.status.Status, data: *AsyncAggregateData) void {
defer {
data.work.delete() catch {};
allocator.free(data.pks);
allocator.free(data.sigs);
allocator.destroy(data);
}
if (data.err) {
const msg = env.createStringUtf8("BLST_ERROR: Aggregation failed") catch return;
data.deferred.reject(msg) catch return;
return;
}
// Wrap results as NAPI PublicKey/Signature instances
const pk_value = newPublicKeyInstance(env) catch return;
const pk = env.unwrap(PublicKey, pk_value) catch return;
pk.* = data.result_pk;
const sig_value = newSignatureInstance(env) catch return;
const sig = env.unwrap(Signature, sig_value) catch return;
sig.* = data.result_sig;
// Create {pk, sig} JS object and resolve promise
const result = env.createObject() catch return;
result.setNamedProperty("pk", pk_value) catch return;
result.setNamedProperty("sig", sig_value) catch return;
data.deferred.resolve(result) catch return;
}
/// Asynchronously aggregates public keys and signatures with randomness using
/// Pippenger multi-scalar multiplication. Heavy math runs on the libuv thread pool.
///
/// Arguments:
/// 1) sets: Array of {pk: PublicKey, sig: Uint8Array}
///
/// Returns: Promise<{pk: PublicKey, sig: Signature}>
pub fn blst_asyncAggregateWithRandomness(env: napi.Env, cb: napi.CallbackInfo(1)) !napi.Value {
const sets = cb.arg(0);
const n = try sets.getArrayLength();
if (n == 0) return error.EmptyArray;
// Max set size enforced at MAX_AGGREGATE_PER_JOB (128) to match blst-z internal limits
if (n > MAX_AGGREGATE_PER_JOB) return error.TooManySets;
const pks = try allocator.alloc(PublicKey, n);
errdefer allocator.free(pks);
const sigs = try allocator.alloc(Signature, n);
errdefer allocator.free(sigs);
for (0..n) |i| {
const set_value = try sets.getElement(@intCast(i));
// Unwrap PublicKey (already validated when created via fromBytes)
const pk_value = try set_value.getNamedProperty("pk");
const unwrapped_pk = try env.unwrap(PublicKey, pk_value);
pks[i] = unwrapped_pk.*;
// Deserialize signature from Uint8Array with validation (infinity + group check),
// matching blst-ts Rust behavior
const sig_value = try set_value.getNamedProperty("sig");
const sig_bytes = try sig_value.getTypedarrayInfo();
sigs[i] = Signature.deserialize(sig_bytes.data[0..]) catch return error.DeserializationFailed;
sigs[i].validate(true) catch return error.InvalidSignature;
}
const data = try allocator.create(AsyncAggregateData);
errdefer allocator.destroy(data);
data.* = .{
.pks = pks,
.sigs = sigs,
.n = n,
.deferred = try napi.Deferred.create(env.env),
};
const resource_name = try env.createStringUtf8("asyncAggregateWithRandomness");
data.work = try napi.AsyncWork(AsyncAggregateData).create(
env,
null,
resource_name,
asyncAggregateExecute,
asyncAggregateComplete,
data,
);
try data.work.queue();
return data.deferred.getPromise();
}
pub fn register(env: napi.Env, exports: napi.Value) !void {
const blst_obj = try env.createObject();
const sk_ctor = try env.defineClass(
"SecretKey",
0,
SecretKey_ctor,
null,
&[_]napi.c.napi_property_descriptor{
method(1, SecretKey_sign),
method(0, SecretKey_toPublicKey),
method(0, SecretKey_toBytes),
method(0, SecretKey_toHex),
},
);
try sk_ctor.defineProperties(&[_]napi.c.napi_property_descriptor{
method(1, SecretKey_fromBytes),
method(1, SecretKey_fromHex),
method(2, SecretKey_fromKeygen),
});
const pk_ctor = try env.defineClass(
"PublicKey",
0,
PublicKey_ctor,
null,
&[_]napi.c.napi_property_descriptor{
method(1, PublicKey_toBytes),
method(1, PublicKey_toHex),
method(0, PublicKey_validate),
},
);
try pk_ctor.defineProperties(&[_]napi.c.napi_property_descriptor{
method(2, PublicKey_fromBytes),
method(2, PublicKey_fromHex),
});
const sig_ctor = try env.defineClass(
"Signature",
0,
Signature_ctor,