clock-curve-math 1.1.3

High-performance, constant-time, cryptography-grade number theory library for ClockCurve ecosystem
Documentation
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
//! Comprehensive tests for API extensions.
//!
//! This module tests the advanced API patterns, builders, and extension traits
//! provided by the api_extensions module.

use clock_curve_math::{BigInt, FieldElement, FieldOps, api_extensions::*};

#[test]
fn test_field_extensions_try_sqrt() {
    let zero = FieldElement::from_u64(0);
    let one = FieldElement::from_u64(1);
    let four = FieldElement::from_u64(4);

    // Test sqrt of 0
    let sqrt_zero = zero.try_sqrt();
    assert!(sqrt_zero.is_some());
    assert_eq!(sqrt_zero.unwrap(), zero);

    // Test sqrt of 1
    let sqrt_one = one.try_sqrt();
    assert!(sqrt_one.is_some());
    assert_eq!(sqrt_one.unwrap(), one);

    // Test sqrt of 4
    let sqrt_four = four.try_sqrt();
    assert!(sqrt_four.is_some());
    let sqrt_val = sqrt_four.unwrap();
    assert_eq!(sqrt_val.square(), four);
}

#[test]
fn test_field_extensions_legendre() {
    let zero = FieldElement::from_u64(0);
    let one = FieldElement::from_u64(1);
    let quadratic_residue = FieldElement::from_u64(4); // 4 is a quadratic residue

    // Legendre symbol of 0 should be 0
    assert_eq!(zero.legendre(), 0);

    // Legendre symbol of 1 should be 1 (1 is always a quadratic residue)
    assert_eq!(one.legendre(), 1);

    // Test that legendre matches is_quadratic_residue
    assert_eq!(
        quadratic_residue.is_quadratic_residue(),
        quadratic_residue.legendre() == 1
    );
}

#[test]
fn test_field_extensions_order() {
    let one = FieldElement::from_u64(1);
    let minus_one = FieldElement::from_u64(1).neg();

    // Order of 1 should be 1 (1^1 = 1)
    let order_one = one.order();
    assert!(order_one.is_some());
    assert_eq!(order_one.unwrap(), BigInt::from_u64(1));

    // Order of -1 should be 2 ((-1)^2 = 1)
    let order_minus_one = minus_one.order();
    assert!(order_minus_one.is_some());
    assert_eq!(order_minus_one.unwrap(), BigInt::from_u64(2));
}

#[test]
fn test_exponentiation_builder_basic() {
    let base = FieldElement::from_u64(2);
    let exp = BigInt::from_u64(10);

    // Test basic exponentiation
    let result = ExponentiationBuilder::new(&base, &exp).build().compute();
    assert_eq!(result, base.pow(&exp));

    // Test that 2^10 = 1024
    assert_eq!(result, FieldElement::from_u64(1024));
}

#[test]
fn test_exponentiation_builder_with_algorithm() {
    let base = FieldElement::from_u64(3);
    let exp = BigInt::from_u64(5);

    // Test different algorithms produce same result
    let binary_result = ExponentiationBuilder::new(&base, &exp)
        .algorithm(Algorithm::Binary)
        .build()
        .compute();

    let sliding_result = ExponentiationBuilder::new(&base, &exp)
        .algorithm(Algorithm::SlidingWindow(4))
        .build()
        .compute();

    let expected = base.pow(&exp); // 3^5 = 243

    assert_eq!(binary_result, expected);
    assert_eq!(sliding_result, expected);
    assert_eq!(binary_result, sliding_result);
}

#[test]
fn test_exponentiation_builder_fixed_window() {
    let base = FieldElement::from_u64(2);

    // Test 2^1 = 2
    let exp1 = BigInt::from_u64(1);
    let result1 = ExponentiationBuilder::new(&base, &exp1)
        .algorithm(Algorithm::FixedWindow(3))
        .build()
        .compute();
    assert_eq!(result1, FieldElement::from_u64(2));

    // Test 2^2 = 4
    let exp2 = BigInt::from_u64(2);
    let result2 = ExponentiationBuilder::new(&base, &exp2)
        .algorithm(Algorithm::FixedWindow(3))
        .build()
        .compute();
    assert_eq!(result2, FieldElement::from_u64(4));

    // Test 2^7 = 128
    let exp7 = BigInt::from_u64(7);
    let result7 = ExponentiationBuilder::new(&base, &exp7)
        .algorithm(Algorithm::FixedWindow(3))
        .build()
        .compute();
    assert_eq!(result7, FieldElement::from_u64(128));
}

#[test]
fn test_exponentiation_builder_adaptive() {
    let base = FieldElement::from_u64(2);

    // Small exponent should work
    let small_exp = BigInt::from_u64(5);
    let small_result = ExponentiationBuilder::new(&base, &small_exp)
        .algorithm(Algorithm::Adaptive)
        .build()
        .compute();
    assert_eq!(small_result, FieldElement::from_u64(32));

    // Large exponent should work
    let large_exp = BigInt::from_u64(100);
    let large_result = ExponentiationBuilder::new(&base, &large_exp)
        .algorithm(Algorithm::Adaptive)
        .build()
        .compute();
    // Verify the computation completes and returns a valid field element
    assert!(large_result.is_valid());
}

#[test]
fn test_exponentiation_config_default() {
    let config = ExponentiationConfig::default();
    assert_eq!(config.algorithm, Algorithm::Adaptive);
    assert_eq!(config.max_bits, None);
    assert_eq!(config.constant_time, true);
}

#[test]
fn test_exponentiation_builder_config_methods() {
    let base = FieldElement::from_u64(2);
    let exp = BigInt::from_u64(3);

    let builder = ExponentiationBuilder::new(&base, &exp)
        .algorithm(Algorithm::SlidingWindow(4))
        .max_bits(64)
        .constant_time(false);

    let configured = builder.build();
    assert_eq!(configured.get_algorithm(), Algorithm::SlidingWindow(4));
    assert_eq!(configured.get_max_bits(), Some(64));
    assert_eq!(configured.get_constant_time(), false);
}

#[test]
fn test_multiplication_config_default() {
    let config = MultiplicationConfig::default();
    assert_eq!(config.algorithm, MultiplicationAlgorithm::Standard);
    assert_eq!(config.optimize_squaring, true);
}

#[test]
fn test_configurable_arithmetic_field_element() {
    let a = FieldElement::from_u64(6);
    let b = FieldElement::from_u64(7);

    // Test standard multiplication
    let config = MultiplicationConfig {
        algorithm: MultiplicationAlgorithm::Standard,
        optimize_squaring: true,
    };
    let result_standard = a.mul_with_config(&b, &config);
    assert_eq!(result_standard, a.mul(&b));

    // Test with different algorithms (should still work for small numbers)
    let config_karatsuba = MultiplicationConfig {
        algorithm: MultiplicationAlgorithm::Karatsuba,
        optimize_squaring: true,
    };
    let result_karatsuba = a.mul_with_config(&b, &config_karatsuba);
    assert_eq!(result_karatsuba, a.mul(&b));
}

#[test]
fn test_configurable_arithmetic_bigint() {
    let a = BigInt::from_u64(12);
    let b = BigInt::from_u64(8);

    // Test standard multiplication
    let config = MultiplicationConfig {
        algorithm: MultiplicationAlgorithm::Standard,
        optimize_squaring: true,
    };
    let result_standard = a.mul_with_config(&b, &config);
    assert_eq!(result_standard, a.mul(&b));

    // Test Karatsuba (should work for small numbers too)
    let config_karatsuba = MultiplicationConfig {
        algorithm: MultiplicationAlgorithm::Karatsuba,
        optimize_squaring: true,
    };
    let result_karatsuba = a.mul_with_config(&b, &config_karatsuba);
    assert_eq!(result_karatsuba, a.mul(&b));
}

#[test]
fn test_configurable_arithmetic_exponentiation() {
    let base = FieldElement::from_u64(2);
    let exp = BigInt::from_u64(8);

    let config = ExponentiationConfig {
        algorithm: Algorithm::Binary,
        max_bits: Some(32),
        constant_time: true,
    };

    let result = base.pow_with_config(&exp, &config);
    assert_eq!(result, FieldElement::from_u64(256)); // 2^8 = 256
}

#[test]
fn test_bigint_configurable_exponentiation() {
    let base = BigInt::from_u64(3);
    let exp = BigInt::from_u64(4);

    let config = ExponentiationConfig::default();
    let result = base.pow_with_config(&exp, &config);
    assert_eq!(result, BigInt::from_u64(81)); // 3^4 = 81
}

#[cfg(feature = "alloc")]
mod batch_tests {
    use super::*;

    #[test]
    fn test_batch_config_default() {
        let config = BatchConfig::default();
        assert_eq!(config.max_batch_size, 1000);
        assert_eq!(config.parallel, false);
        assert_eq!(config.allocation_strategy, AllocationStrategy::Preallocate);
    }

    #[test]
    fn test_batch_inverse_builder_basic() {
        let elements = vec![
            FieldElement::from_u64(1),
            FieldElement::from_u64(2),
            FieldElement::from_u64(3),
        ];

        let builder = BatchInverseBuilder::new(&elements);
        let result = builder.compute().unwrap();

        assert_eq!(result.inverses.len(), 3);
        for (i, inv) in result.inverses.iter().enumerate() {
            assert_eq!(elements[i].mul(inv), FieldElement::from_u64(1));
        }
    }

    #[test]
    fn test_batch_inverse_builder_with_config() {
        let elements = vec![FieldElement::from_u64(5), FieldElement::from_u64(7)];

        let result = BatchInverseBuilder::new(&elements)
            .max_batch_size(10)
            .parallel(false)
            .allocation_strategy(AllocationStrategy::OnDemand)
            .compute()
            .unwrap();

        assert_eq!(result.inverses.len(), 2);
        for (i, inv) in result.inverses.iter().enumerate() {
            assert_eq!(elements[i].mul(inv), FieldElement::from_u64(1));
        }
    }

    #[test]
    fn test_batch_inverse_builder_empty() {
        let elements: Vec<FieldElement> = vec![];
        let result = BatchInverseBuilder::new(&elements).compute().unwrap();
        assert_eq!(result.inverses.len(), 0);
    }

    #[test]
    fn test_batch_inverse_builder_single_element() {
        let elements = vec![FieldElement::from_u64(42)];
        let result = BatchInverseBuilder::new(&elements).compute().unwrap();

        assert_eq!(result.inverses.len(), 1);
        assert_eq!(
            elements[0].mul(&result.inverses[0]),
            FieldElement::from_u64(1)
        );
    }

    #[test]
    fn test_batch_inverse_result_access() {
        let elements = vec![FieldElement::from_u64(2), FieldElement::from_u64(3)];

        let result = BatchInverseBuilder::new(&elements).compute().unwrap();

        // Test individual access via indexing
        assert_eq!(
            elements[0].mul(&result.inverses[0]),
            FieldElement::from_u64(1)
        );
        assert_eq!(
            elements[1].mul(&result.inverses[1]),
            FieldElement::from_u64(1)
        );
    }
}

#[test]
fn test_algorithm_enum_variants() {
    // Test all Algorithm variants
    assert_eq!(Algorithm::Binary, Algorithm::Binary);
    assert_eq!(Algorithm::SlidingWindow(4), Algorithm::SlidingWindow(4));
    assert_eq!(Algorithm::MontgomeryLadder, Algorithm::MontgomeryLadder);
    assert_eq!(Algorithm::FixedWindow(5), Algorithm::FixedWindow(5));
    assert_eq!(Algorithm::Adaptive, Algorithm::Adaptive);

    // Test inequality
    assert_ne!(Algorithm::Binary, Algorithm::Adaptive);
    assert_ne!(Algorithm::SlidingWindow(3), Algorithm::SlidingWindow(4));
}

#[test]
fn test_multiplication_algorithm_enum() {
    // Test all MultiplicationAlgorithm variants
    assert_eq!(
        MultiplicationAlgorithm::Standard,
        MultiplicationAlgorithm::Standard
    );
    assert_eq!(
        MultiplicationAlgorithm::Schoolbook,
        MultiplicationAlgorithm::Schoolbook
    );
    assert_eq!(
        MultiplicationAlgorithm::Karatsuba,
        MultiplicationAlgorithm::Karatsuba
    );
    assert_eq!(
        MultiplicationAlgorithm::ToomCook,
        MultiplicationAlgorithm::ToomCook
    );
    assert_eq!(MultiplicationAlgorithm::FFT, MultiplicationAlgorithm::FFT);

    // Test that Standard and Schoolbook are different variants (Schoolbook is an alias but separate variant)
    assert_ne!(
        MultiplicationAlgorithm::Standard,
        MultiplicationAlgorithm::Schoolbook
    );
}

#[test]
fn test_allocation_strategy_enum() {
    // Test all AllocationStrategy variants
    assert_eq!(
        AllocationStrategy::Preallocate,
        AllocationStrategy::Preallocate
    );
    assert_eq!(AllocationStrategy::OnDemand, AllocationStrategy::OnDemand);
    assert_eq!(AllocationStrategy::Reuse, AllocationStrategy::Reuse);

    // Test default
    assert_eq!(
        AllocationStrategy::default(),
        AllocationStrategy::Preallocate
    );
}

#[test]
fn test_exponentiation_edge_cases() {
    let base = FieldElement::from_u64(5);

    // Test exponent = 0 (any number to the power of 0 is 1)
    let exp_zero = BigInt::from_u64(0);
    let result_zero = ExponentiationBuilder::new(&base, &exp_zero)
        .build()
        .compute();
    assert_eq!(result_zero, FieldElement::from_u64(1));

    // Test exponent = 1 (any number to the power of 1 is itself)
    let exp_one = BigInt::from_u64(1);
    let result_one = ExponentiationBuilder::new(&base, &exp_one)
        .build()
        .compute();
    assert_eq!(result_one, base);
}

#[test]
fn test_multiplication_algorithms_consistency() {
    let a = BigInt::from_u64(25);
    let b = BigInt::from_u64(30);

    let expected = a.mul(&b);

    // Test that all algorithms produce the same result for small numbers
    let algorithms = vec![
        MultiplicationAlgorithm::Standard,
        MultiplicationAlgorithm::Schoolbook,
        MultiplicationAlgorithm::Karatsuba,
        MultiplicationAlgorithm::ToomCook,
        MultiplicationAlgorithm::FFT,
    ];

    for algorithm in algorithms {
        let config = MultiplicationConfig {
            algorithm,
            optimize_squaring: true,
        };
        let result = a.mul_with_config(&b, &config);
        assert_eq!(result, expected, "Algorithm {:?} failed", algorithm);
    }
}

#[test]
fn test_algorithm_display_and_debug() {
    // Test that algorithms implement Debug and can be printed
    let algo = Algorithm::SlidingWindow(4);
    let debug_str = format!("{:?}", algo);
    assert!(debug_str.contains("SlidingWindow"));
    assert!(debug_str.contains("4"));
}

#[cfg(feature = "alloc")]
#[test]
fn test_batch_builder_config_methods() {
    let elements = vec![FieldElement::from_u64(1)];

    let builder = BatchInverseBuilder::new(&elements)
        .max_batch_size(500)
        .parallel(true);

    // Verify the config is set correctly
    assert_eq!(builder.get_max_batch_size(), 500);
    assert_eq!(builder.get_parallel(), true);
}