ziskos 1.1.0-alpha

Guest runtime and entrypoint for programs targeting the ZisK zkVM
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
//! Operations on the BLS12-381 curve E: y² = x³ + 4

#[cfg(zisk_guest)]
use crate::alloc_extern::vec::Vec;

use crate::{
    syscalls::{
        syscall_bls12_381_curve_add, syscall_bls12_381_curve_dbl, SyscallBls12_381CurveAddParams,
        SyscallPoint384,
    },
    zisklib::{eq, fcall_msb_pos_256, is_one, is_two, is_zero, lt},
};

use super::{
    constants::{E_B, G1_IDENTITY, GAMMA, P, X2DIV3_BIN_BE},
    fp::{
        add_fp_bls12_381, mul_fp_bls12_381, neg_fp_bls12_381, sqrt_fp_bls12_381,
        square_fp_bls12_381,
    },
    fr::{reduce_fr_bls12_381, scalar_bytes_be_to_u64_le_bls12_381},
};

/// G1 add result codes
#[allow(dead_code)]
pub(crate) const G1_ADD_SUCCESS: u8 = 0;
#[allow(dead_code)]
pub(crate) const G1_ADD_SUCCESS_INFINITY: u8 = 1;
const G1_ADD_ERR_NOT_IN_FIELD: u8 = 2;
const G1_ADD_ERR_NOT_ON_CURVE: u8 = 3;

/// G1 MSM result codes
#[allow(dead_code)]
pub(crate) const G1_MSM_SUCCESS: u8 = 0;
#[allow(dead_code)]
pub(crate) const G1_MSM_SUCCESS_INFINITY: u8 = 1;
const G1_MSM_ERR_NOT_IN_FIELD: u8 = 2;
const G1_MSM_ERR_NOT_ON_CURVE: u8 = 3;
const G1_MSM_ERR_NOT_IN_SUBGROUP: u8 = 4;

/// Decompresses a point on the BLS12-381 curve from 48 bytes
///
/// Format: Big-endian x-coordinate with flag bits in the top 3 bits of the first byte:
/// - Bit 7 (0x80): Compression flag (must be 1 for compressed)
/// - Bit 6 (0x40): Infinity flag (1 = point at infinity)
/// - Bit 5 (0x20): Sign flag (1 = y is lexicographically largest)
pub fn decompress_bls12_381(
    input: &[u8; 48],
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> Result<([u64; 12], bool), &'static str> {
    let flags = input[0];

    // Check compression bit
    if (flags & 0x80) == 0 {
        return Err("Expected compressed point");
    }

    // Check infinity bit
    if (flags & 0x40) != 0 {
        // Verify rest is zero
        if (flags & 0x3f) != 0 {
            return Err("Invalid infinity encoding");
        }
        for input in input.iter().skip(1) {
            if *input != 0 {
                return Err("Invalid infinity encoding");
            }
        }
        return Ok((G1_IDENTITY, true));
    }

    // Extract sign bit
    let y_sign = (flags & 0x20) != 0;

    // Extract x-coordinate (big-endian), masking off flag bits
    let mut x = [0u64; 6];
    let mut bytes = [0u8; 48];
    bytes.copy_from_slice(input);
    bytes[0] &= 0x1f; // Clear flag bits

    // Convert from big-endian bytes to little-endian u64 limbs
    for i in 0..6 {
        for j in 0..8 {
            x[5 - i] |= (bytes[i * 8 + j] as u64) << (8 * (7 - j));
        }
    }

    // Verify x < p
    if !lt(&x, &P) {
        return Err("x coordinate >= field modulus");
    }

    // Calculate the y-coordinate of the point: y = sqrt(x³ + 4)
    let x_sq = square_fp_bls12_381(
        &x,
        #[cfg(feature = "hints")]
        hints,
    );
    let x_cb = mul_fp_bls12_381(
        &x_sq,
        &x,
        #[cfg(feature = "hints")]
        hints,
    );
    let y_sq = add_fp_bls12_381(
        &x_cb,
        &E_B,
        #[cfg(feature = "hints")]
        hints,
    );

    let (y, has_sqrt) = sqrt_fp_bls12_381(
        &y_sq,
        #[cfg(feature = "hints")]
        hints,
    );
    if !has_sqrt {
        return Err("No square root exists - point not on curve");
    }

    // Determine the sign of y, which is (lexicographically) done by checking if y > -y
    let y_neg = neg_fp_bls12_381(
        &y,
        #[cfg(feature = "hints")]
        hints,
    );
    let y_is_larger = lt(&y_neg, &y);

    // Select the correct y based on sign bit
    let final_y = if y_is_larger == y_sign { y } else { y_neg };

    // Return the point (x, final_y)
    let mut result = [0u64; 12];
    result[0..6].copy_from_slice(&x);
    result[6..12].copy_from_slice(&final_y);
    Ok((result, false))
}

/// Check if a point `p` is on the BLS12-381 curve
pub fn is_on_curve_bls12_381(
    p: &[u64; 12],
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> bool {
    let x: [u64; 6] = p[0..6].try_into().unwrap();
    let y: [u64; 6] = p[6..12].try_into().unwrap();

    // p in E iff y² == x³ + 4 or p == 𝒪
    let lhs = square_fp_bls12_381(
        &y,
        #[cfg(feature = "hints")]
        hints,
    );
    let mut rhs = square_fp_bls12_381(
        &x,
        #[cfg(feature = "hints")]
        hints,
    );
    rhs = mul_fp_bls12_381(
        &rhs,
        &x,
        #[cfg(feature = "hints")]
        hints,
    );
    rhs = add_fp_bls12_381(
        &rhs,
        &E_B,
        #[cfg(feature = "hints")]
        hints,
    );

    eq(&lhs, &rhs) || eq(p, &G1_IDENTITY)
}

/// Check if a point `p` is on the BLS12-381 subgroup
///
/// # Soundness
/// The point must be on-curve and have **canonical** coordinates (`x, y < p`).
pub fn is_on_subgroup_bls12_381(
    p: &[u64; 12],
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> bool {
    // p in subgroup iff:
    //          ((x²-1)/3)(2·σ(P) - P - σ²(P)) == σ²(P)
    // where σ(x,y) = (ɣ·x,y)
    //
    // Notice that the σ-fixed points are those with the
    // x-coordinate equal to 0, e.g. P = (0, 2) or P = 𝒪
    // In such case, (2·σ(P) - P - σ²(P)) = 𝒪

    // Compute σ(P), σ²(P)
    let sigma1 = sigma_endomorphism_bls12_381(
        p,
        #[cfg(feature = "hints")]
        hints,
    );
    let rhs = sigma_endomorphism_bls12_381(
        &sigma1,
        #[cfg(feature = "hints")]
        hints,
    );

    // Compute lhs = ((x²-1)/3)(2·σ(P) - P - σ²(P))
    let mut lhs = dbl_complete_bls12_381(
        &sigma1,
        #[cfg(feature = "hints")]
        hints,
    );
    lhs = sub_complete_bls12_381(
        &lhs,
        p,
        #[cfg(feature = "hints")]
        hints,
    );
    lhs = sub_complete_bls12_381(
        &lhs,
        &rhs,
        #[cfg(feature = "hints")]
        hints,
    );
    lhs = scalar_mul_by_x2div3_complete_bls12_381(
        &lhs,
        #[cfg(feature = "hints")]
        hints,
    );

    eq(&lhs, &rhs)
}

/// Compute the sigma endomorphism σ of a non-zero point `p`, defined as:
///              σ : E(Fp)  ->  E(Fp)
///                  (x,y) |-> (ɣ·x,y)
pub fn sigma_endomorphism_bls12_381(
    p: &[u64; 12],
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> [u64; 12] {
    let mut x: [u64; 6] = p[0..6].try_into().unwrap();
    let y: [u64; 6] = p[6..12].try_into().unwrap();

    x = mul_fp_bls12_381(
        &x,
        &GAMMA,
        #[cfg(feature = "hints")]
        hints,
    );
    let mut result = [0u64; 12];
    result[0..6].copy_from_slice(&x);
    result[6..12].copy_from_slice(&y);
    result
}

/// Adds two points `p1` and `p2` on the BLS12-381 curve
///
/// # Soundness
/// Both points must be on-curve and have **canonical** coordinates (`x, y < p`).
pub fn add_complete_bls12_381(
    p1: &[u64; 12],
    p2: &[u64; 12],
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> [u64; 12] {
    if eq(p1, &G1_IDENTITY) {
        return *p2;
    } else if eq(p2, &G1_IDENTITY) {
        return *p1;
    }

    add_bls12_381(
        p1,
        p2,
        #[cfg(feature = "hints")]
        hints,
    )
}

/// Adds two non-zero points `p1` and `p2` on the BLS12-381 curve
///
/// # Soundness
/// Both points must be on-curve, non-identity, and have **canonical** coordinates
/// (`x, y < p`).
pub(crate) fn add_bls12_381(
    p1: &[u64; 12],
    p2: &[u64; 12],
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> [u64; 12] {
    let x1: [u64; 6] = p1[0..6].try_into().unwrap();
    let y1: [u64; 6] = p1[6..12].try_into().unwrap();
    let x2: [u64; 6] = p2[0..6].try_into().unwrap();
    let y2: [u64; 6] = p2[6..12].try_into().unwrap();

    // Is x1 == x2?
    if eq(&x1, &x2) {
        // Is y1 == y2?
        if eq(&y1, &y2) {
            // Compute the doubling
            return dbl_bls12_381(
                p1,
                #[cfg(feature = "hints")]
                hints,
            );
        } else {
            // Return 𝒪
            return G1_IDENTITY;
        }
    }

    // Compute the addition
    let mut p1 = SyscallPoint384 { x: x1, y: y1 };
    let p2 = SyscallPoint384 { x: x2, y: y2 };
    let mut params = SyscallBls12_381CurveAddParams { p1: &mut p1, p2: &p2 };
    syscall_bls12_381_curve_add(
        &mut params,
        #[cfg(feature = "hints")]
        hints,
    );

    let mut result = [0u64; 12];
    result[0..6].copy_from_slice(&p1.x);
    result[6..12].copy_from_slice(&p1.y);
    result
}

/// Complete and safe addition of two points `p1` and `p2` on the BLS12-381 curve
pub fn add_complete_safe_bls12_381(
    p1: &[u64; 12],
    p2: &[u64; 12],
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> Result<[u64; 12], u8> {
    let p1_is_inf = *p1 == G1_IDENTITY;
    let p2_is_inf = *p2 == G1_IDENTITY;

    // Handle identity cases
    if p1_is_inf && p2_is_inf {
        return Ok(G1_IDENTITY);
    }
    if p1_is_inf {
        // Validate p2 field elements and curve membership
        let x2: [u64; 6] = p2[0..6].try_into().unwrap();
        let y2: [u64; 6] = p2[6..12].try_into().unwrap();
        if !lt(&x2, &P) || !lt(&y2, &P) {
            return Err(G1_ADD_ERR_NOT_IN_FIELD);
        }
        if !is_on_curve_bls12_381(
            p2,
            #[cfg(feature = "hints")]
            hints,
        ) {
            return Err(G1_ADD_ERR_NOT_ON_CURVE);
        }
        return Ok(*p2);
    }

    if p2_is_inf {
        // Validate p1 field elements and curve membership
        let x1: [u64; 6] = p1[0..6].try_into().unwrap();
        let y1: [u64; 6] = p1[6..12].try_into().unwrap();
        if !lt(&x1, &P) || !lt(&y1, &P) {
            return Err(G1_ADD_ERR_NOT_IN_FIELD);
        }
        if !is_on_curve_bls12_381(
            p1,
            #[cfg(feature = "hints")]
            hints,
        ) {
            return Err(G1_ADD_ERR_NOT_ON_CURVE);
        }
        return Ok(*p1);
    }

    // Both points are non-identity, validate both
    let x1: [u64; 6] = p1[0..6].try_into().unwrap();
    let y1: [u64; 6] = p1[6..12].try_into().unwrap();
    if !lt(&x1, &P) || !lt(&y1, &P) {
        return Err(G1_ADD_ERR_NOT_IN_FIELD);
    }
    if !is_on_curve_bls12_381(
        p1,
        #[cfg(feature = "hints")]
        hints,
    ) {
        return Err(G1_ADD_ERR_NOT_ON_CURVE);
    }

    // Validate p2 field elements and curve membership
    let x2: [u64; 6] = p2[0..6].try_into().unwrap();
    let y2: [u64; 6] = p2[6..12].try_into().unwrap();
    if !lt(&x2, &P) || !lt(&y2, &P) {
        return Err(G1_ADD_ERR_NOT_IN_FIELD);
    }
    if !is_on_curve_bls12_381(
        p2,
        #[cfg(feature = "hints")]
        hints,
    ) {
        return Err(G1_ADD_ERR_NOT_ON_CURVE);
    }

    // Otherwise, perform regular addition
    Ok(add_bls12_381(
        p1,
        p2,
        #[cfg(feature = "hints")]
        hints,
    ))
}

/// Negation of a point `p` on the BLS12-381 curve
pub fn neg_bls12_381(p: &[u64; 12], #[cfg(feature = "hints")] hints: &mut Vec<u64>) -> [u64; 12] {
    let x: [u64; 6] = p[0..6].try_into().unwrap();
    let y: [u64; 6] = p[6..12].try_into().unwrap();

    let y_neg = neg_fp_bls12_381(
        &y,
        #[cfg(feature = "hints")]
        hints,
    );
    let mut result = [0u64; 12];
    result[0..6].copy_from_slice(&x);
    result[6..12].copy_from_slice(&y_neg);
    result
}

/// Doubling of a point `p` on the BLS12-381 curve
///
/// # Soundness
/// The point must be on-curve and have **canonical** coordinates (`x, y < p`).
pub fn dbl_complete_bls12_381(
    p: &[u64; 12],
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> [u64; 12] {
    // Handle identity case
    if eq(p, &G1_IDENTITY) {
        return G1_IDENTITY;
    }

    dbl_bls12_381(
        p,
        #[cfg(feature = "hints")]
        hints,
    )
}

/// Doubling of a non-zero point `p` on the BLS12-381 curve
///
/// # Soundness
/// The point must be on-curve, non-identity, and have **canonical** coordinates
/// (`x, y < p`).
pub(crate) fn dbl_bls12_381(
    p: &[u64; 12],
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> [u64; 12] {
    let mut p = SyscallPoint384 { x: p[0..6].try_into().unwrap(), y: p[6..12].try_into().unwrap() };
    syscall_bls12_381_curve_dbl(
        &mut p,
        #[cfg(feature = "hints")]
        hints,
    );

    let mut result = [0u64; 12];
    result[0..6].copy_from_slice(&p.x);
    result[6..12].copy_from_slice(&p.y);
    result
}

/// Subtraction of two points `p1` and `p2` on the BLS12-381 curve
///
/// # Soundness
/// Both points must be on-curve and have **canonical** coordinates (`x, y < p`).
pub fn sub_complete_bls12_381(
    p1: &[u64; 12],
    p2: &[u64; 12],
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> [u64; 12] {
    // Handle identity cases
    if eq(p1, &G1_IDENTITY) {
        return neg_bls12_381(
            p2,
            #[cfg(feature = "hints")]
            hints,
        );
    } else if eq(p2, &G1_IDENTITY) {
        return *p1;
    }

    sub_bls12_381(
        p1,
        p2,
        #[cfg(feature = "hints")]
        hints,
    )
}

/// Subtraction of two non-zero points `p1` and `p2` on the BLS12-381 curve
///
/// # Soundness
/// Both points must be on-curve, non-identity, and have **canonical** coordinates
/// (`x, y < p`).
pub fn sub_bls12_381(
    p1: &[u64; 12],
    p2: &[u64; 12],
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> [u64; 12] {
    let x2: [u64; 6] = p2[0..6].try_into().unwrap();
    let y2: [u64; 6] = p2[6..12].try_into().unwrap();

    // P1 - P2 = P1 + (-P2)
    let y2_neg = neg_fp_bls12_381(
        &y2,
        #[cfg(feature = "hints")]
        hints,
    );

    let mut p2_neg = [0u64; 12];
    p2_neg[0..6].copy_from_slice(&x2);
    p2_neg[6..12].copy_from_slice(&y2_neg);

    add_bls12_381(
        p1,
        &p2_neg,
        #[cfg(feature = "hints")]
        hints,
    )
}

/// Multiplies a point `p` on the BLS12-381 curve by a scalar `k` on the BLS12-381 scalar field
///
/// # Soundness
/// The point must be on-curve and have **canonical** coordinates (`x, y < p`).
pub fn scalar_mul_complete_bls12_381(
    p: &[u64; 12],
    k: &[u64; 4],
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> [u64; 12] {
    // Handle identity case
    if eq(p, &G1_IDENTITY) {
        return G1_IDENTITY;
    }

    // Reduce the scalar
    let k = reduce_fr_bls12_381(
        k,
        #[cfg(feature = "hints")]
        hints,
    );

    // Direct cases: k = 0, k = 1, k = 2
    if is_zero(&k) {
        // Return 𝒪
        return G1_IDENTITY;
    } else if is_one(&k) {
        // Return p
        return *p;
    } else if is_two(&k) {
        // Return 2p
        return dbl_bls12_381(
            p,
            #[cfg(feature = "hints")]
            hints,
        );
    }

    // We can assume k > 2 from now on
    // Hint the length the binary representations of k
    // We will verify the output by recomposing k
    // Moreover, we should check that the first received bit is 1
    let (max_limb, max_bit) = fcall_msb_pos_256(
        &k,
        #[cfg(feature = "hints")]
        hints,
    );

    // Bound before use as index/shift
    assert!(max_limb < 4 && max_bit < 64, "msb_pos hint out of range");

    // Perform the loop, based on the binary representation of k

    // We do the first iteration separately
    let max_limb = max_limb as usize;
    let max_bit = max_bit as usize;

    // The first received bit should be 1
    assert_eq!((k[max_limb] >> max_bit) & 1, 1, "The most significant bit of the scalar must be 1");

    // Start at P
    let mut k_rec = [0u64; 4];
    k_rec[max_limb] |= 1 << max_bit;

    // Determine starting limb/bit for the loop
    let mut limb = max_limb;
    let mut bit = if max_bit == 0 {
        // If max_bit is 0 then limb > 0; otherwise k = 1, which is excluded here
        limb -= 1;
        63
    } else {
        max_bit - 1
    };

    // Perform the rest of the loop
    let mut q: [u64; 12] = *p;
    for i in (0..=limb).rev() {
        for j in (0..=bit).rev() {
            // Always double
            q = dbl_complete_bls12_381(
                &q,
                #[cfg(feature = "hints")]
                hints,
            );

            // Get the next bit b of k.
            // If b == 1, we should add P to Q, otherwise start the next iteration
            if ((k[i] >> j) & 1) == 1 {
                q = add_complete_bls12_381(
                    &q,
                    p,
                    #[cfg(feature = "hints")]
                    hints,
                );

                // Reconstruct k
                k_rec[i] |= 1 << j;
            }
        }
        bit = 63;
    }

    // Check that the reconstructed k is equal to the input k
    assert!(eq(&k, &k_rec), "Reconstructed scalar does not match input scalar");

    q
}

/// Multiplies a non-zero point `p` on the BLS12-381 curve by a scalar `k` on the BLS12-381 scalar field
///
/// # Soundness
/// The point must be on-curve, non-identity, and have **canonical** coordinates
/// (`x, y < p`).
pub fn scalar_mul_bls12_381(
    p: &[u64; 12],
    k: &[u64; 4],
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> [u64; 12] {
    // Reduce the scalar
    let k = reduce_fr_bls12_381(
        k,
        #[cfg(feature = "hints")]
        hints,
    );

    // Direct cases: k = 0, k = 1, k = 2
    if is_zero(&k) {
        // Return 𝒪
        return G1_IDENTITY;
    } else if is_one(&k) {
        // Return p
        return *p;
    } else if is_two(&k) {
        // Return 2p
        return dbl_bls12_381(
            p,
            #[cfg(feature = "hints")]
            hints,
        );
    }

    // We can assume k > 2 from now on
    // Hint the length the binary representations of k
    // We will verify the output by recomposing k
    // Moreover, we should check that the first received bit is 1
    let (max_limb, max_bit) = fcall_msb_pos_256(
        &k,
        #[cfg(feature = "hints")]
        hints,
    );

    // Bound before use as index/shift
    assert!(max_limb < 4 && max_bit < 64, "msb_pos hint out of range");

    // Perform the loop, based on the binary representation of k

    // We do the first iteration separately
    let max_limb = max_limb as usize;
    let max_bit = max_bit as usize;

    // The first received bit should be 1
    assert_eq!((k[max_limb] >> max_bit) & 1, 1, "The most significant bit of the scalar must be 1");

    // Start at P
    let x1: [u64; 6] = p[0..6].try_into().unwrap();
    let y1: [u64; 6] = p[6..12].try_into().unwrap();
    let mut q = SyscallPoint384 { x: x1, y: y1 };
    let mut k_rec = [0u64; 4];
    k_rec[max_limb] |= 1 << max_bit;

    // Determine starting limb/bit for the loop
    let mut limb = max_limb;
    let mut bit = if max_bit == 0 {
        // If max_bit is 0 then limb > 0; otherwise k = 1, which is excluded here
        limb -= 1;
        63
    } else {
        max_bit - 1
    };

    // Perform the rest of the loop
    let p = SyscallPoint384 { x: x1, y: y1 };
    for i in (0..=limb).rev() {
        for j in (0..=bit).rev() {
            // Always double
            syscall_bls12_381_curve_dbl(
                &mut q,
                #[cfg(feature = "hints")]
                hints,
            );

            // Get the next bit b of k.
            // If b == 1, we should add P to Q, otherwise start the next iteration
            if ((k[i] >> j) & 1) == 1 {
                let mut params = SyscallBls12_381CurveAddParams { p1: &mut q, p2: &p };
                syscall_bls12_381_curve_add(
                    &mut params,
                    #[cfg(feature = "hints")]
                    hints,
                );

                // Reconstruct k
                k_rec[i] |= 1 << j;
            }
        }
        bit = 63;
    }

    // Check that the reconstructed k is equal to the input k
    assert!(eq(&k, &k_rec), "Reconstructed scalar does not match input scalar");

    // Convert the result back to a single array
    let mut result = [0u64; 12];
    result[0..6].copy_from_slice(&q.x);
    result[6..12].copy_from_slice(&q.y);
    result
}

/// Scalar multiplication of a point by (x²-1)/3
///
/// # Soundness
/// The point must be on-curve and have **canonical** coordinates (`x, y < p`).
pub fn scalar_mul_by_x2div3_complete_bls12_381(
    p: &[u64; 12],
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> [u64; 12] {
    // Handle identity case
    if eq(p, &G1_IDENTITY) {
        return G1_IDENTITY;
    }

    // Start at p
    let mut r = *p;
    for &bit in X2DIV3_BIN_BE.iter().skip(1) {
        r = dbl_complete_bls12_381(
            &r,
            #[cfg(feature = "hints")]
            hints,
        );
        if bit == 1 {
            r = add_complete_bls12_381(
                &r,
                p,
                #[cfg(feature = "hints")]
                hints,
            );
        }
    }
    r
}

/// Multi-Scalar Multiplication (MSM) for BLS12-381 G1 points
/// It computes k1·P1 + k2·P2 + ... + kn·Pn
// TODO: This is a naive implementation, one can improve it by using, e.g., a windowed strategies!
pub fn msm_complete_safe_bls12_381(
    points: &[[u64; 12]],
    scalars: &[[u64; 4]],
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> Result<[u64; 12], u8> {
    assert_eq!(points.len(), scalars.len(), "Points and scalars must have the same length");

    let mut acc = G1_IDENTITY;
    let mut acc_is_inf = true;
    for (point, scalar) in points.iter().zip(scalars.iter()) {
        // Skip infinity points
        if *point == G1_IDENTITY {
            continue;
        }

        // NOTE: Validation must precede the scalar-zero skip below, since we should reject an
        // invalid input point regardless of its scalar.

        // Verify point coordinates are in the field
        let x: [u64; 6] = point[0..6].try_into().unwrap();
        let y: [u64; 6] = point[6..12].try_into().unwrap();
        if !lt(&x, &P) || !lt(&y, &P) {
            return Err(G1_MSM_ERR_NOT_IN_FIELD);
        }

        // Verify point is on curve
        if !is_on_curve_bls12_381(
            point,
            #[cfg(feature = "hints")]
            hints,
        ) {
            return Err(G1_MSM_ERR_NOT_ON_CURVE);
        }

        // Verify point is in subgroup
        if !is_on_subgroup_bls12_381(
            point,
            #[cfg(feature = "hints")]
            hints,
        ) {
            return Err(G1_MSM_ERR_NOT_IN_SUBGROUP);
        }

        // Reduce the scalar modulo the group order, and skip if the result is zero
        let scalar = reduce_fr_bls12_381(
            scalar,
            #[cfg(feature = "hints")]
            hints,
        );
        if is_zero(&scalar) {
            continue;
        }

        // Compute P * k
        let product = scalar_mul_bls12_381(
            point,
            &scalar,
            #[cfg(feature = "hints")]
            hints,
        );

        // Skip if product is infinity
        if product == G1_IDENTITY {
            continue;
        }

        // Add to accumulator
        if acc_is_inf {
            acc = product;
            acc_is_inf = false;
        } else {
            acc = add_bls12_381(
                &acc,
                &product,
                #[cfg(feature = "hints")]
                hints,
            );
            acc_is_inf = acc == G1_IDENTITY;
        }
    }

    Ok(acc)
}

// ==================== C FFI Functions ====================

/// Decompresses a compressed BLS12-381 G1 point (48 bytes) to affine coordinates.
/// Returns 0 on success (result written to `result_ptr`), 1 if decompression fails.
///
/// # Safety
/// - `input_ptr` must point to a valid `[u8; 48]` compressed point
/// - `result_ptr` must point to a writable `[u64; 12]` array
#[cfg_attr(not(feature = "hints"), no_mangle)]
#[cfg_attr(feature = "hints", export_name = "hints_decompress_bls12_381_c")]
pub unsafe extern "C" fn decompress_bls12_381_c(
    input_ptr: *const u8,
    result_ptr: *mut u64,
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> u8 {
    let input = &*(input_ptr as *const [u8; 48]);
    match decompress_bls12_381(
        input,
        #[cfg(feature = "hints")]
        hints,
    ) {
        Ok((p, is_infinity)) => {
            let result = &mut *(result_ptr as *mut [u64; 12]);
            *result = p;
            if is_infinity {
                1
            } else {
                0
            }
        }
        Err(_) => 2,
    }
}

/// Curve membership check for a BLS12-381 G1 point.
/// Returns 1 if the point is on the curve, 0 otherwise.
///
/// # Safety
/// - `p_ptr` must point to a valid `[u64; 12]` array (affine coordinates x ‖ y, little-endian limbs)
#[cfg_attr(not(feature = "hints"), no_mangle)]
#[cfg_attr(feature = "hints", export_name = "hints_is_on_curve_bls12_381_c")]
pub unsafe extern "C" fn is_on_curve_bls12_381_c(
    p_ptr: *const u64,
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> u8 {
    let p = &*(p_ptr as *const [u64; 12]);
    is_on_curve_bls12_381(
        p,
        #[cfg(feature = "hints")]
        hints,
    ) as u8
}

/// Subgroup membership check for a BLS12-381 G1 point.
/// Returns 1 if the point is in the G1 subgroup, 0 otherwise.
///
/// # Safety
/// - `p_ptr` must point to a valid `[u64; 12]` array (affine coordinates x ‖ y, little-endian limbs)
///
/// # Soundness
/// The point must be on-curve, non-identity, and have **canonical** coordinates
/// (`x, y < p`).
#[cfg_attr(not(feature = "hints"), no_mangle)]
#[cfg_attr(feature = "hints", export_name = "hints_is_on_subgroup_bls12_381_c")]
pub unsafe extern "C" fn is_on_subgroup_bls12_381_c(
    p_ptr: *const u64,
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> u8 {
    let p = &*(p_ptr as *const [u64; 12]);
    is_on_subgroup_bls12_381(
        p,
        #[cfg(feature = "hints")]
        hints,
    ) as u8
}

/// Addition of two BLS12-381 G1 points (raw, UNVALIDATED — caller pre-validates).
/// Returns 0 on success (result written to `result_ptr`), or 1 if the result is the
/// point at infinity.
///
/// # Safety
/// - `p1_ptr` must point to a valid `[u64; 12]` array (affine coordinates x ‖ y, little-endian limbs)
/// - `p2_ptr` must point to a valid `[u64; 12]` array (affine coordinates x ‖ y, little-endian limbs)
/// - `result_ptr` must point to a writable `[u64; 12]` array
///
/// # Soundness
/// Both points must be on-curve, non-identity, and have **canonical** coordinates
/// (`x, y < p`).
#[cfg_attr(not(feature = "hints"), no_mangle)]
#[cfg_attr(feature = "hints", export_name = "hints_add_bls12_381_c")]
pub unsafe extern "C" fn add_bls12_381_c(
    p1_ptr: *const u64,
    p2_ptr: *const u64,
    result_ptr: *mut u64,
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> u8 {
    let p1 = &*(p1_ptr as *const [u64; 12]);
    let p2 = &*(p2_ptr as *const [u64; 12]);
    let result = &mut *(result_ptr as *mut [u64; 12]);
    *result = add_bls12_381(
        p1,
        p2,
        #[cfg(feature = "hints")]
        hints,
    );

    if eq(result, &G1_IDENTITY) {
        1
    } else {
        0
    }
}

/// G1 point addition for uncompressed 96-byte points
///
/// Input format: 96 bytes per point = 48 bytes x-coordinate + 48 bytes y-coordinate (big-endian)
/// Output format: Same as input
///
/// ### Safety
/// - `a` must point to a valid `[u8; 96]` for the first input point
/// - `b` must point to a valid `[u8; 96]` for the second input point
/// - `ret` must point to a valid `[u8; 96]` for the output
///
/// Returns:
/// - [G1_ADD_SUCCESS] = success (result is valid and not infinity)
/// - [G1_ADD_SUCCESS_INFINITY] = success (result is infinity)
/// - [G1_ADD_ERR_NOT_IN_FIELD] = error (one of the input points has coordinates not in the field)
/// - [G1_ADD_ERR_NOT_ON_CURVE] = error (one of the input points is not on the curve)
#[allow(dead_code)]
#[inline]
pub(crate) unsafe fn add_safe_bls12_381_c(
    ret: *mut u8,
    a: *const u8,
    b: *const u8,
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> u8 {
    let a_bytes: &[u8; 96] = &*(a as *const [u8; 96]);
    let b_bytes: &[u8; 96] = &*(b as *const [u8; 96]);
    let ret_bytes: &mut [u8; 96] = &mut *(ret as *mut [u8; 96]);

    // Parse points
    let a_u64 = g1_bytes_be_to_u64_le_bls12_381(a_bytes);
    let b_u64 = g1_bytes_be_to_u64_le_bls12_381(b_bytes);

    // Perform addition
    let result = match add_complete_safe_bls12_381(
        &a_u64,
        &b_u64,
        #[cfg(feature = "hints")]
        hints,
    ) {
        Ok(r) => r,
        Err(code) => return code,
    };

    // Encode result
    g1_u64_le_to_bytes_be_bls12_381(&result, ret_bytes);
    if result == G1_IDENTITY {
        G1_ADD_SUCCESS_INFINITY
    } else {
        G1_ADD_SUCCESS
    }
}

/// Scalar multiplication of a non-zero BLS12-381 G1 point by a scalar.
///
/// # Safety
/// - `p_ptr` must point to a valid `[u64; 12]` array (affine coordinates x ‖ y, little-endian limbs)
/// - `k_ptr` must point to a valid `[u64; 4]` array (scalar, little-endian limbs)
/// - `result_ptr` must point to a writable `[u64; 12]` array
///
/// # Soundness
/// The point must be on-curve, non-identity, and have **canonical** coordinates
/// (`x, y < p`).
#[cfg_attr(not(feature = "hints"), no_mangle)]
#[cfg_attr(feature = "hints", export_name = "hints_scalar_mul_bls12_381_c")]
pub unsafe extern "C" fn scalar_mul_bls12_381_c(
    p_ptr: *const u64,
    k_ptr: *const u64,
    result_ptr: *mut u64,
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> u8 {
    let p = &*(p_ptr as *const [u64; 12]);
    let k = &*(k_ptr as *const [u64; 4]);
    let result = &mut *(result_ptr as *mut [u64; 12]);
    *result = scalar_mul_bls12_381(
        p,
        k,
        #[cfg(feature = "hints")]
        hints,
    );

    if eq(result, &G1_IDENTITY) {
        1
    } else {
        0
    }
}

/// G1 Multi-Scalar Multiplication (MSM) for uncompressed points
///
/// Input format per pair: 128 bytes = 96 bytes G1 point (x || y big-endian) + 32 bytes scalar (big-endian)
/// Output format: 96 bytes G1 point (x || y big-endian)
///
/// ### Safety
/// - `pairs` must point to an array of `num_pairs * 128` bytes
/// - `ret` must point to a valid `[u8; 96]` for the output
///
/// Returns:
/// - [G1_MSM_SUCCESS] = success (result is valid and not infinity)
/// - [G1_MSM_SUCCESS_INFINITY] = success (result is infinity)
/// - [G1_MSM_ERR_NOT_IN_FIELD] = error (one of the input points has coordinates not in the field)
/// - [G1_MSM_ERR_NOT_ON_CURVE] = error (one of the input points is not on the curve)
/// - [G1_MSM_ERR_NOT_IN_SUBGROUP] = error (one of the input points is not in the subgroup)
#[allow(dead_code)]
#[inline]
pub(crate) unsafe fn msm_safe_bls12_381_c(
    ret: *mut u8,
    pairs: *const u8,
    num_pairs: usize,
    #[cfg(feature = "hints")] hints: &mut Vec<u64>,
) -> u8 {
    let ret_bytes: &mut [u8; 96] = &mut *(ret as *mut [u8; 96]);

    // Parse all pairs
    let mut points = Vec::with_capacity(num_pairs);
    let mut scalars = Vec::with_capacity(num_pairs);
    for i in 0..num_pairs {
        let pair_ptr = pairs.add(i * 128);
        let point_bytes: &[u8; 96] = &*(pair_ptr as *const [u8; 96]);
        let scalar_bytes: &[u8; 32] = &*(pair_ptr.add(96) as *const [u8; 32]);

        // Parse point and scalar
        let point_u64 = g1_bytes_be_to_u64_le_bls12_381(point_bytes);
        let scalar_u64 = scalar_bytes_be_to_u64_le_bls12_381(scalar_bytes);

        points.push(point_u64);
        scalars.push(scalar_u64);
    }

    // Perform MSM with validation
    let result = match msm_complete_safe_bls12_381(
        &points,
        &scalars,
        #[cfg(feature = "hints")]
        hints,
    ) {
        Ok(r) => r,
        Err(code) => return code,
    };

    // Encode result
    g1_u64_le_to_bytes_be_bls12_381(&result, ret_bytes);
    if result == G1_IDENTITY {
        G1_MSM_SUCCESS_INFINITY
    } else {
        G1_MSM_SUCCESS
    }
}

/// Convert 96-byte big-endian G1 point to [u64; 12] little-endian
pub fn g1_bytes_be_to_u64_le_bls12_381(bytes: &[u8; 96]) -> [u64; 12] {
    let mut result = [0u64; 12];

    // x-coordinate (first 48 bytes)
    for i in 0..6 {
        for j in 0..8 {
            result[5 - i] |= (bytes[i * 8 + j] as u64) << (8 * (7 - j));
        }
    }

    // y-coordinate (next 48 bytes)
    for i in 0..6 {
        for j in 0..8 {
            result[11 - i] |= (bytes[48 + i * 8 + j] as u64) << (8 * (7 - j));
        }
    }

    result
}

/// Convert [u64; 12] little-endian G1 point to 96-byte big-endian
pub fn g1_u64_le_to_bytes_be_bls12_381(limbs: &[u64; 12], bytes: &mut [u8; 96]) {
    // x-coordinate (first 48 bytes)
    for i in 0..6 {
        let limb = limbs[5 - i];
        for j in 0..8 {
            bytes[i * 8 + j] = ((limb >> (8 * (7 - j))) & 0xFF) as u8;
        }
    }

    // y-coordinate (next 48 bytes)
    for i in 0..6 {
        let limb = limbs[11 - i];
        for j in 0..8 {
            bytes[48 + i * 8 + j] = ((limb >> (8 * (7 - j))) & 0xFF) as u8;
        }
    }
}