cairo-native 0.9.0-rc.7

A compiler to convert Cairo's IR Sierra code to MLIR and execute it.
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
//! # Elliptic curve libfuncs

use super::LibfuncHelper;
use crate::{
    error::{Error, Result},
    execution_result::EC_OP_BUILTIN_SIZE,
    libfuncs::increment_builtin_counter_conditionally_by,
    metadata::{runtime_bindings::RuntimeBindingsMeta, MetadataStorage},
    utils::{get_integer_layout, ProgramRegistryExt, PRIME},
};
use cairo_lang_sierra::{
    extensions::{
        core::{CoreLibfunc, CoreType},
        ec::EcConcreteLibfunc,
        lib_func::SignatureOnlyConcreteLibfunc,
        ConcreteLibfunc,
    },
    program_registry::ProgramRegistry,
};
use melior::{
    dialect::{
        arith::{self, CmpiPredicate},
        llvm,
    },
    helpers::{ArithBlockExt, BuiltinBlockExt, LlvmBlockExt},
    ir::{operation::OperationBuilder, r#type::IntegerType, Block, Location},
    Context,
};

/// Select and call the correct libfunc builder function from the selector.
pub fn build<'ctx, 'this>(
    context: &'ctx Context,
    registry: &ProgramRegistry<CoreType, CoreLibfunc>,
    entry: &'this Block<'ctx>,
    location: Location<'ctx>,
    helper: &LibfuncHelper<'ctx, 'this>,
    metadata: &mut MetadataStorage,
    selector: &EcConcreteLibfunc,
) -> Result<()> {
    match selector {
        EcConcreteLibfunc::IsZero(info) => {
            build_is_zero(context, registry, entry, location, helper, metadata, info)
        }
        EcConcreteLibfunc::Neg(info) => {
            build_neg(context, registry, entry, location, helper, metadata, info)
        }
        EcConcreteLibfunc::PointFromX(info) => {
            build_point_from_x(context, registry, entry, location, helper, metadata, info)
        }
        EcConcreteLibfunc::StateAdd(info) => {
            build_state_add(context, registry, entry, location, helper, metadata, info)
        }
        EcConcreteLibfunc::StateAddMul(info) => {
            build_state_add_mul(context, registry, entry, location, helper, metadata, info)
        }
        EcConcreteLibfunc::StateFinalize(info) => {
            build_state_finalize(context, registry, entry, location, helper, metadata, info)
        }
        EcConcreteLibfunc::StateInit(info) => {
            build_state_init(context, registry, entry, location, helper, metadata, info)
        }
        EcConcreteLibfunc::TryNew(info) => {
            build_try_new(context, registry, entry, location, helper, metadata, info)
        }
        EcConcreteLibfunc::UnwrapPoint(info) => {
            build_unwrap_point(context, registry, entry, location, helper, metadata, info)
        }
        EcConcreteLibfunc::Zero(info) => {
            build_zero(context, registry, entry, location, helper, metadata, info)
        }
        EcConcreteLibfunc::NegNz(info) => {
            build_neg_nz(context, registry, entry, location, helper, metadata, info)
        }
    }
}

/// Generate MLIR operations for the `ec_point_is_zero` libfunc.
pub fn build_is_zero<'ctx, 'this>(
    context: &'ctx Context,
    _registry: &ProgramRegistry<CoreType, CoreLibfunc>,
    entry: &'this Block<'ctx>,
    location: Location<'ctx>,
    helper: &LibfuncHelper<'ctx, 'this>,
    _metadata: &mut MetadataStorage,
    _info: &SignatureOnlyConcreteLibfunc,
) -> Result<()> {
    // To check whether `(x, y) = (0, 0)` (the zero point), it is enough to check
    // whether `y = 0`, since there is no point on the curve with y = 0.
    let y = entry.extract_value(
        context,
        location,
        entry.arg(0)?,
        IntegerType::new(context, 252).into(),
        1,
    )?;

    let k0 = entry.const_int(context, location, 0, 252)?;
    let y_is_zero = entry.cmpi(context, CmpiPredicate::Eq, y, k0, location)?;

    helper.cond_br(
        context,
        entry,
        y_is_zero,
        [0, 1],
        [&[], &[entry.arg(0)?]],
        location,
    )
}

/// Generate MLIR operations for the `ec_neg` libfunc.
pub fn build_neg<'ctx, 'this>(
    context: &'ctx Context,
    _registry: &ProgramRegistry<CoreType, CoreLibfunc>,
    entry: &'this Block<'ctx>,
    location: Location<'ctx>,
    helper: &LibfuncHelper<'ctx, 'this>,
    _metadata: &mut MetadataStorage,
    _info: &SignatureOnlyConcreteLibfunc,
) -> Result<()> {
    let y = entry.extract_value(
        context,
        location,
        entry.arg(0)?,
        IntegerType::new(context, 252).into(),
        1,
    )?;

    let k_prime = entry.const_int(context, location, PRIME.clone(), 252)?;
    let k0 = entry.const_int(context, location, 0, 252)?;

    let y_is_zero = entry.cmpi(context, CmpiPredicate::Eq, y, k0, location)?;

    let y_neg = entry.append_op_result(arith::subi(k_prime, y, location))?;
    let y_neg = entry.append_op_result(
        OperationBuilder::new("arith.select", location)
            .add_operands(&[y_is_zero, k0, y_neg])
            .add_results(&[IntegerType::new(context, 252).into()])
            .build()?,
    )?;

    let result = entry.insert_value(context, location, entry.arg(0)?, y_neg, 1)?;

    helper.br(entry, 0, &[result], location)
}

/// Generate MLIR operations for the `ec_neg_nz` libfunc.
pub fn build_neg_nz<'ctx, 'this>(
    context: &'ctx Context,
    _registry: &ProgramRegistry<CoreType, CoreLibfunc>,
    entry: &'this Block<'ctx>,
    location: Location<'ctx>,
    helper: &LibfuncHelper<'ctx, 'this>,
    _metadata: &mut MetadataStorage,
    _info: &SignatureOnlyConcreteLibfunc,
) -> Result<()> {
    let y = entry.extract_value(
        context,
        location,
        entry.arg(0)?,
        IntegerType::new(context, 252).into(),
        1,
    )?;

    let k_prime = entry.const_int(context, location, PRIME.clone(), 252)?;
    let y_neg = entry.append_op_result(arith::subi(k_prime, y, location))?;
    let result = entry.insert_value(context, location, entry.arg(0)?, y_neg, 1)?;

    helper.br(entry, 0, &[result], location)
}

/// Generate MLIR operations for the `ec_point_from_x_nz` libfunc.
pub fn build_point_from_x<'ctx, 'this>(
    context: &'ctx Context,
    _registry: &ProgramRegistry<CoreType, CoreLibfunc>,
    entry: &'this Block<'ctx>,
    location: Location<'ctx>,
    helper: &LibfuncHelper<'ctx, 'this>,
    metadata: &mut MetadataStorage,
    _info: &SignatureOnlyConcreteLibfunc,
) -> Result<()> {
    let ec_point_ty = llvm::r#type::r#struct(
        context,
        &[
            IntegerType::new(context, 252).into(),
            IntegerType::new(context, 252).into(),
        ],
        false,
    );

    let point_ptr = helper.init_block().alloca1(
        context,
        location,
        ec_point_ty,
        get_integer_layout(252).align(),
    )?;

    let point = entry.append_op_result(llvm::undef(ec_point_ty, location))?;
    let point = entry.insert_value(context, location, point, entry.arg(1)?, 0)?;

    entry.store(context, location, point_ptr, point)?;
    let is_on_curve = metadata
        .get_mut::<RuntimeBindingsMeta>()
        .ok_or(Error::MissingMetadata)?
        .libfunc_ec_point_from_x_nz(context, helper, entry, point_ptr, location)?
        .result(0)?
        .into();

    let point = entry.load(context, location, point_ptr, ec_point_ty)?;

    // The sierra-to-casm compiler uses the range check builtin a total of 3 times if the
    // point is on the curve. Otherwise it is not used.
    // https://github.com/starkware-libs/cairo/blob/v2.12.0-dev.1/crates/cairo-lang-sierra-to-casm/src/invocations/ec.rs#L167
    let range_check = increment_builtin_counter_conditionally_by(
        context,
        entry,
        location,
        entry.arg(0)?,
        3,
        0,
        is_on_curve,
    )?;

    helper.cond_br(
        context,
        entry,
        is_on_curve,
        [0, 1],
        [&[range_check, point], &[range_check]],
        location,
    )
}

/// Generate MLIR operations for the `ec_state_add` libfunc.
pub fn build_state_add<'ctx, 'this>(
    context: &'ctx Context,
    _registry: &ProgramRegistry<CoreType, CoreLibfunc>,
    entry: &'this Block<'ctx>,
    location: Location<'ctx>,
    helper: &LibfuncHelper<'ctx, 'this>,
    metadata: &mut MetadataStorage,
    _info: &SignatureOnlyConcreteLibfunc,
) -> Result<()> {
    let ec_state_ty = llvm::r#type::r#struct(
        context,
        &[
            IntegerType::new(context, 252).into(),
            IntegerType::new(context, 252).into(),
            IntegerType::new(context, 252).into(),
            IntegerType::new(context, 252).into(),
        ],
        false,
    );

    let state_ptr = helper.init_block().alloca1(
        context,
        location,
        ec_state_ty,
        get_integer_layout(252).align(),
    )?;
    let point_ptr = helper.init_block().alloca1(
        context,
        location,
        ec_state_ty,
        get_integer_layout(252).align(),
    )?;

    entry.store(context, location, state_ptr, entry.arg(0)?)?;
    entry.store(context, location, point_ptr, entry.arg(1)?)?;

    metadata
        .get_mut::<RuntimeBindingsMeta>()
        .ok_or(Error::MissingMetadata)?
        .libfunc_ec_state_add(context, helper, entry, state_ptr, point_ptr, location)?;

    let state = entry.load(context, location, state_ptr, ec_state_ty)?;

    helper.br(entry, 0, &[state], location)
}

/// Generate MLIR operations for the `ec_state_add_mul` libfunc.
pub fn build_state_add_mul<'ctx, 'this>(
    context: &'ctx Context,
    _registry: &ProgramRegistry<CoreType, CoreLibfunc>,
    entry: &'this Block<'ctx>,
    location: Location<'ctx>,
    helper: &LibfuncHelper<'ctx, 'this>,
    metadata: &mut MetadataStorage,
    _info: &SignatureOnlyConcreteLibfunc,
) -> Result<()> {
    // The sierra-to-casm compiler uses the ec op builtin 1 time.
    // https://github.com/starkware-libs/cairo/blob/v2.12.0-dev.1/crates/cairo-lang-sierra-to-casm/src/invocations/ec.rs#L439
    let ec_op = super::increment_builtin_counter_by(
        context,
        entry,
        location,
        entry.arg(0)?,
        EC_OP_BUILTIN_SIZE,
    )?;

    let felt252_ty = IntegerType::new(context, 252).into();
    let ec_state_ty = llvm::r#type::r#struct(
        context,
        &[felt252_ty, felt252_ty, felt252_ty, felt252_ty],
        false,
    );
    let ec_point_ty = llvm::r#type::r#struct(context, &[felt252_ty, felt252_ty], false);

    let state_ptr = helper.init_block().alloca1(
        context,
        location,
        ec_state_ty,
        get_integer_layout(252).align(),
    )?;
    let scalar_ptr = helper.init_block().alloca1(
        context,
        location,
        felt252_ty,
        get_integer_layout(252).align(),
    )?;
    let point_ptr = helper.init_block().alloca1(
        context,
        location,
        ec_point_ty,
        get_integer_layout(252).align(),
    )?;

    entry.store(context, location, state_ptr, entry.arg(1)?)?;
    entry.store(context, location, scalar_ptr, entry.arg(2)?)?;
    entry.store(context, location, point_ptr, entry.arg(3)?)?;

    metadata
        .get_mut::<RuntimeBindingsMeta>()
        .ok_or(Error::MissingMetadata)?
        .libfunc_ec_state_add_mul(
            context, helper, entry, state_ptr, scalar_ptr, point_ptr, location,
        )?;

    let state = entry.load(context, location, state_ptr, ec_state_ty)?;

    helper.br(entry, 0, &[ec_op, state], location)
}

/// Generate MLIR operations for the `ec_state_try_finalize_nz` libfunc.
pub fn build_state_finalize<'ctx, 'this>(
    context: &'ctx Context,
    _registry: &ProgramRegistry<CoreType, CoreLibfunc>,
    entry: &'this Block<'ctx>,
    location: Location<'ctx>,
    helper: &LibfuncHelper<'ctx, 'this>,
    metadata: &mut MetadataStorage,
    _info: &SignatureOnlyConcreteLibfunc,
) -> Result<()> {
    let felt252_ty = IntegerType::new(context, 252).into();
    let ec_state_ty = llvm::r#type::r#struct(
        context,
        &[felt252_ty, felt252_ty, felt252_ty, felt252_ty],
        false,
    );
    let ec_point_ty = llvm::r#type::r#struct(context, &[felt252_ty, felt252_ty], false);

    let point_ptr = helper.init_block().alloca1(
        context,
        location,
        ec_point_ty,
        get_integer_layout(252).align(),
    )?;
    let state_ptr = helper.init_block().alloca1(
        context,
        location,
        ec_state_ty,
        get_integer_layout(252).align(),
    )?;

    entry.store(context, location, state_ptr, entry.arg(0)?)?;

    let is_zero = metadata
        .get_mut::<RuntimeBindingsMeta>()
        .ok_or(Error::MissingMetadata)?
        .libfunc_ec_state_try_finalize_nz(context, helper, entry, point_ptr, state_ptr, location)?
        .result(0)?
        .into();

    let point = entry.load(context, location, point_ptr, ec_point_ty)?;

    helper.cond_br(context, entry, is_zero, [0, 1], [&[point], &[]], location)
}

/// Generate MLIR operations for the `ec_state_init` libfunc.
pub fn build_state_init<'ctx, 'this>(
    context: &'ctx Context,
    _registry: &ProgramRegistry<CoreType, CoreLibfunc>,
    entry: &'this Block<'ctx>,
    location: Location<'ctx>,
    helper: &LibfuncHelper<'ctx, 'this>,
    metadata: &mut MetadataStorage,
    _info: &SignatureOnlyConcreteLibfunc,
) -> Result<()> {
    let ec_state_ty = llvm::r#type::r#struct(
        context,
        &[
            IntegerType::new(context, 252).into(),
            IntegerType::new(context, 252).into(),
            IntegerType::new(context, 252).into(),
            IntegerType::new(context, 252).into(),
        ],
        false,
    );

    let state_ptr = helper.init_block().alloca1(
        context,
        location,
        ec_state_ty,
        get_integer_layout(252).align(),
    )?;

    metadata
        .get_mut::<RuntimeBindingsMeta>()
        .ok_or(Error::MissingMetadata)?
        .libfunc_ec_state_init(context, helper, entry, state_ptr, location)?;

    let state = entry.load(context, location, state_ptr, ec_state_ty)?;

    helper.br(entry, 0, &[state], location)
}

/// Generate MLIR operations for the `ec_point_try_new_nz` libfunc.
pub fn build_try_new<'ctx, 'this>(
    context: &'ctx Context,
    _registry: &ProgramRegistry<CoreType, CoreLibfunc>,
    entry: &'this Block<'ctx>,
    location: Location<'ctx>,
    helper: &LibfuncHelper<'ctx, 'this>,
    metadata: &mut MetadataStorage,
    _info: &SignatureOnlyConcreteLibfunc,
) -> Result<()> {
    let ec_point_ty = llvm::r#type::r#struct(
        context,
        &[
            IntegerType::new(context, 252).into(),
            IntegerType::new(context, 252).into(),
        ],
        false,
    );

    let point_ptr = helper.init_block().alloca1(
        context,
        location,
        ec_point_ty,
        get_integer_layout(252).align(),
    )?;

    let point = entry.append_op_result(llvm::undef(ec_point_ty, location))?;
    let point = entry.insert_value(context, location, point, entry.arg(0)?, 0)?;
    let point = entry.insert_value(context, location, point, entry.arg(1)?, 1)?;

    entry.store(context, location, point_ptr, point)?;

    let result = metadata
        .get_mut::<RuntimeBindingsMeta>()
        .ok_or(Error::MissingMetadata)?
        .libfunc_ec_point_try_new_nz(context, helper, entry, point_ptr, location)?
        .result(0)?
        .into();

    helper.cond_br(context, entry, result, [0, 1], [&[point], &[]], location)
}

/// Generate MLIR operations for the `ec_point_unwrap` libfunc.
pub fn build_unwrap_point<'ctx, 'this>(
    context: &'ctx Context,
    registry: &ProgramRegistry<CoreType, CoreLibfunc>,
    entry: &'this Block<'ctx>,
    location: Location<'ctx>,
    helper: &LibfuncHelper<'ctx, 'this>,
    metadata: &mut MetadataStorage,
    info: &SignatureOnlyConcreteLibfunc,
) -> Result<()> {
    let x = entry.extract_value(
        context,
        location,
        entry.arg(0)?,
        registry.build_type(
            context,
            helper,
            metadata,
            &info.branch_signatures()[0].vars[0].ty,
        )?,
        0,
    )?;

    let y = entry.extract_value(
        context,
        location,
        entry.arg(0)?,
        registry.build_type(
            context,
            helper,
            metadata,
            &info.branch_signatures()[0].vars[1].ty,
        )?,
        1,
    )?;

    helper.br(entry, 0, &[x, y], location)
}

/// Generate MLIR operations for the `ec_point_zero` libfunc.
pub fn build_zero<'ctx, 'this>(
    context: &'ctx Context,
    registry: &ProgramRegistry<CoreType, CoreLibfunc>,
    entry: &'this Block<'ctx>,
    location: Location<'ctx>,
    helper: &LibfuncHelper<'ctx, 'this>,
    metadata: &mut MetadataStorage,
    info: &SignatureOnlyConcreteLibfunc,
) -> Result<()> {
    let ec_point_ty = registry.build_type(
        context,
        helper,
        metadata,
        &info.branch_signatures()[0].vars[0].ty,
    )?;

    let point = entry.append_op_result(llvm::undef(ec_point_ty, location))?;

    let k0 = entry.const_int(context, location, 0, 252)?;

    let point = entry.insert_value(context, location, point, k0, 0)?;

    let point = entry.insert_value(context, location, point, k0, 1)?;

    helper.br(entry, 0, &[point], location)
}

#[cfg(test)]
mod test {
    use crate::{
        jit_enum, jit_struct,
        utils::{
            testing::{get_compiled_program, run_program, run_program_assert_output},
            PRIME,
        },
        values::Value,
    };
    use starknet_types_core::felt::Felt;
    use std::ops::Neg;

    #[test]
    fn ec_point_is_zero() {
        let program =
            get_compiled_program("test_data_artifacts/programs/libfuncs/ec_point_is_zero");
        let r = |x, y| run_program(&program, "run_test", &[Value::EcPoint(x, y)]).return_value;

        assert_eq!(r(0.into(), 0.into()), jit_enum!(0, jit_struct!()));
        assert_eq!(
            r(0.into(), 1.into()),
            jit_enum!(1, Value::EcPoint(0.into(), 1.into()))
        );
        assert_eq!(r(1.into(), 0.into()), jit_enum!(0, jit_struct!()));
        assert_eq!(
            r(1.into(), 1.into()),
            jit_enum!(1, Value::EcPoint(1.into(), 1.into()))
        );
    }

    #[test]
    fn ec_neg() {
        let program = get_compiled_program("test_data_artifacts/programs/libfuncs/ec_neg");
        let r = |x, y| run_program(&program, "run_test", &[Value::EcPoint(x, y)]).return_value;

        assert_eq!(r(0.into(), 0.into()), Value::EcPoint(0.into(), 0.into()));
        assert_eq!(
            r(0.into(), 1.into()),
            Value::EcPoint(0.into(), Felt::from(-1))
        );
        assert_eq!(r(1.into(), 0.into()), Value::EcPoint(1.into(), 0.into()));
        assert_eq!(
            r(1.into(), 1.into()),
            Value::EcPoint(1.into(), Felt::from(-1))
        );
    }

    #[test]
    fn ec_neg_nz() {
        let program = get_compiled_program("test_data_artifacts/programs/libfuncs/ec_neg_nz");
        let r = |x, y| run_program(&program, "run_test", &[Value::EcPoint(x, y)]).return_value;

        assert_eq!(
            r(0.into(), 1.into()),
            Value::EcPoint(0.into(), Felt::from(-1))
        );
        assert_eq!(
            r(1.into(), 1.into()),
            Value::EcPoint(1.into(), Felt::from(-1))
        );
        assert_eq!(
            r(1.into(), Felt::from(-1)),
            Value::EcPoint(1.into(), Felt::from(1))
        );
        assert_eq!(
            r(Felt::from(-1), Felt::from(-1)),
            Value::EcPoint(Felt::from(-1), Felt::from(1))
        );
        assert_eq!(
            r(1.into(), Felt::from(PRIME.clone())),
            Value::EcPoint(1.into(), -Felt::from(PRIME.clone()))
        );
        assert_eq!(
            r(1.into(), -Felt::from(PRIME.clone())),
            Value::EcPoint(1.into(), Felt::from(PRIME.clone()))
        );
    }

    #[test]
    fn ec_point_from_x() {
        let program =
            get_compiled_program("test_data_artifacts/programs/libfuncs/ec_point_from_x_nz");
        let r = |x| run_program(&program, "run_test", &[Value::Felt252(x)]).return_value;

        assert_eq!(r(0.into()), jit_enum!(1, jit_struct!()));
        assert_eq!(r(1234.into()), jit_enum!(0, Value::EcPoint(
            Felt::from(1234),
            Felt::from_dec_str("1301976514684871091717790968549291947487646995000837413367950573852273027507").unwrap()
        )));
    }

    #[test]
    fn ec_state_add() {
        let program = get_compiled_program("test_data_artifacts/programs/libfuncs/ec_state_add");
        run_program_assert_output(&program, "run_test", &[
            Value::EcState(
                Felt::from_dec_str("3151312365169595090315724863753927489909436624354740709748557281394568342450").unwrap(),
                Felt::from_dec_str("2835232394579952276045648147338966184268723952674536708929458753792035266179").unwrap(),
                Felt::from_dec_str("3151312365169595090315724863753927489909436624354740709748557281394568342450").unwrap(),
                Felt::from_dec_str("2835232394579952276045648147338966184268723952674536708929458753792035266179").unwrap()
            ),
            Value::EcPoint(
                Felt::from_dec_str("1234").unwrap(),
                Felt::from_dec_str("1301976514684871091717790968549291947487646995000837413367950573852273027507").unwrap()
            )
        ],
        Value::EcState(
            Felt::from_dec_str("763975897824944497806946001227010133599886598340174017198031710397718335159").unwrap(),
            Felt::from_dec_str("2805180267536471620369715068237762638204710971142209985448115065526708105983").unwrap(),
            Felt::from_dec_str("3151312365169595090315724863753927489909436624354740709748557281394568342450").unwrap(),
            Felt::from_dec_str("2835232394579952276045648147338966184268723952674536708929458753792035266179").unwrap()
        ));
    }

    #[test]
    fn ec_state_add_mul() {
        let program =
            get_compiled_program("test_data_artifacts/programs/libfuncs/ec_state_add_mul");
        run_program_assert_output(&program, "run_test", &[
            Value::EcState(
                Felt::from_dec_str("3151312365169595090315724863753927489909436624354740709748557281394568342450").unwrap(),
                Felt::from_dec_str("2835232394579952276045648147338966184268723952674536708929458753792035266179").unwrap(),
                Felt::from_dec_str("3151312365169595090315724863753927489909436624354740709748557281394568342450").unwrap(),
                Felt::from_dec_str("2835232394579952276045648147338966184268723952674536708929458753792035266179").unwrap()
            ),
            Felt::ONE.into(), // scalar
            Value::EcPoint(
                Felt::from_dec_str("1234").unwrap(),
                Felt::from_dec_str("1301976514684871091717790968549291947487646995000837413367950573852273027507").unwrap()
            )
        ],
            Value::EcState(
                Felt::from_dec_str("763975897824944497806946001227010133599886598340174017198031710397718335159").unwrap(),
                Felt::from_dec_str("2805180267536471620369715068237762638204710971142209985448115065526708105983").unwrap(),
                Felt::from_dec_str("3151312365169595090315724863753927489909436624354740709748557281394568342450").unwrap(),
                Felt::from_dec_str("2835232394579952276045648147338966184268723952674536708929458753792035266179").unwrap()
            )
        );

        run_program_assert_output(&program, "run_test", &[
            Value::EcState(
                Felt::from_dec_str("3151312365169595090315724863753927489909436624354740709748557281394568342450").unwrap(),
                Felt::from_dec_str("2835232394579952276045648147338966184268723952674536708929458753792035266179").unwrap(),
                Felt::from_dec_str("3151312365169595090315724863753927489909436624354740709748557281394568342450").unwrap(),
                Felt::from_dec_str("2835232394579952276045648147338966184268723952674536708929458753792035266179").unwrap()
            ),
            Felt::from(2).into(), // scalar
            Value::EcPoint(
                Felt::from_dec_str("1234").unwrap(),
                Felt::from_dec_str("1301976514684871091717790968549291947487646995000837413367950573852273027507").unwrap()
            )
        ],
            Value::EcState(
                Felt::from_dec_str("3016674370847061744386893405108272070153695046160622325692702034987910716850").unwrap(),
                Felt::from_dec_str("898133181809473419542838028331350248951548889944002871647069130998202992502").unwrap(),
                Felt::from_dec_str("3151312365169595090315724863753927489909436624354740709748557281394568342450").unwrap(),
                Felt::from_dec_str("2835232394579952276045648147338966184268723952674536708929458753792035266179").unwrap()
            )
        );
    }

    #[test]
    fn ec_state_finalize() {
        let program =
            get_compiled_program("test_data_artifacts/programs/libfuncs/ec_state_finalize");
        run_program_assert_output(
            &program,
            "run_test",
            &[Value::EcState(
                Felt::from_dec_str(
                    "3151312365169595090315724863753927489909436624354740709748557281394568342450",
                )
                .unwrap(),
                Felt::from_dec_str(
                    "2835232394579952276045648147338966184268723952674536708929458753792035266179",
                )
                .unwrap(),
                Felt::from_dec_str(
                    "3151312365169595090315724863753927489909436624354740709748557281394568342450",
                )
                .unwrap(),
                Felt::from_dec_str(
                    "2835232394579952276045648147338966184268723952674536708929458753792035266179",
                )
                .unwrap(),
            )],
            jit_enum!(1, jit_struct!()),
        );
        run_program_assert_output(&program, "run_test", &[
            Value::EcState(
                Felt::from_dec_str("763975897824944497806946001227010133599886598340174017198031710397718335159").unwrap(),
                Felt::from_dec_str("2805180267536471620369715068237762638204710971142209985448115065526708105983").unwrap(),
                Felt::from_dec_str("3151312365169595090315724863753927489909436624354740709748557281394568342450").unwrap(),
                Felt::from_dec_str("2835232394579952276045648147338966184268723952674536708929458753792035266179").unwrap()
            ),
        ],
            jit_enum!(0, Value::EcPoint(
                    Felt::from(1234),
                    Felt::from_dec_str("1301976514684871091717790968549291947487646995000837413367950573852273027507").unwrap()
                )
            )
        );
    }

    #[test]
    fn ec_state_init() {
        let program = get_compiled_program("test_data_artifacts/programs/libfuncs/ec_state_init");
        let result = run_program(&program, "run_test", &[]);
        // cant match the values because the state init is a random point
        assert!(matches!(result.return_value, Value::EcState(_, _, _, _)));
    }

    #[test]
    fn ec_point_try_new_nz() {
        let program =
            get_compiled_program("test_data_artifacts/programs/libfuncs/ec_point_try_new_nz");
        run_program_assert_output(
            &program,
            "run_test",
            &[
                Felt::from_dec_str("0").unwrap().into(),
                Felt::from_dec_str("0").unwrap().into(),
            ],
            jit_enum!(1, jit_struct!()),
        );
        run_program_assert_output(
            &program,
            "run_test",
            &[
                Felt::from_dec_str("1234").unwrap().into(),
                Felt::from_dec_str("1301976514684871091717790968549291947487646995000837413367950573852273027507").unwrap().into()
            ],
                jit_enum!(0, Value::EcPoint(
                    Felt::from_dec_str("1234").unwrap(),
                    Felt::from_dec_str("1301976514684871091717790968549291947487646995000837413367950573852273027507").unwrap()
                ))
            ,
        );
        run_program_assert_output(
            &program,
            "run_test",
            &[  Felt::from_dec_str("1234").unwrap().into(),
                Felt::from_dec_str("1301976514684871091717790968549291947487646995000837413367950573852273027507").unwrap().neg().into()
                ],
                jit_enum!(0, Value::EcPoint(
                    Felt::from_dec_str("1234").unwrap(),
                    Felt::from_dec_str("1301976514684871091717790968549291947487646995000837413367950573852273027507").unwrap().neg()
                ))
                ,
        );
    }

    #[test]
    fn ec_point_unwrap() {
        fn parse(x: &str) -> Felt {
            if let Some(x) = x.strip_prefix('-') {
                Felt::from_dec_str(x).unwrap().neg()
            } else {
                Felt::from_dec_str(x).unwrap()
            }
        }

        #[track_caller]
        fn run(a: &str, b: &str, ea: &str, eb: &str) {
            let program =
                get_compiled_program("test_data_artifacts/programs/libfuncs/ec_point_unwrap");
            run_program_assert_output(
                &program,
                "run_test",
                &[Value::EcPoint(parse(a), parse(b))],
                jit_struct!(parse(ea).into(), parse(eb).into()),
            );
        }

        run("0", "0", "0", "0");
        run("0", "1", "0", "1");
        run("0", "-1", "0", "-1");
        run("1", "0", "1", "0");
        run("1", "1", "1", "1");
        run("1", "-1", "1", "-1");
        run("-1", "0", "-1", "0");
        run("-1", "1", "-1", "1");
        run("-1", "-1", "-1", "-1");
    }

    #[test]
    fn ec_point_zero() {
        let program = get_compiled_program("test_data_artifacts/programs/libfuncs/ec_point_zero");
        run_program_assert_output(
            &program,
            "run_test",
            &[],
            Value::EcPoint(
                Felt::from_dec_str("0").unwrap(),
                Felt::from_dec_str("0").unwrap().neg(),
            ),
        );
    }
}