hekate_math/algebra.rs
1// SPDX-License-Identifier: Apache-2.0
2// This file is part of the hekate-math project.
3// Copyright (C) 2026 Andrei Kochergin <andrei@oumuamua.dev>
4// Copyright (C) 2026 Oumuamua Labs <info@oumuamua.dev>.
5//
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Binary-field algebraic extras.
19
20use crate::{Bit, TowerField};
21
22/// Binary-field operations beyond core `TowerField`:
23/// Frobenius, absolute trace, and the Artin-Schreier
24/// solver underpinning the Cantor/FFT substrate.
25pub trait BinaryFieldExtras: TowerField {
26 fn square(&self) -> Self {
27 *self * *self
28 }
29
30 /// `x^(2^k)`. `k` is taken mod the field degree
31 /// (`x^(2^BITS) = x`), so any `k` is valid.
32 fn frobenius(&self, k: u32) -> Self {
33 let reps = (k % Self::BITS as u32) as usize;
34
35 let mut acc = *self;
36 for _ in 0..reps {
37 acc = acc.square();
38 }
39
40 acc
41 }
42
43 /// Absolute trace `Tr_{F/GF(2)}(x) = Σ x^(2^i)`,
44 /// always 0 or 1.
45 fn trace(&self) -> Bit {
46 let mut acc = Self::ZERO;
47 let mut p = *self;
48
49 for _ in 0..Self::BITS {
50 acc += p;
51 p = p.square();
52 }
53
54 Bit::new((acc == Self::ONE) as u8)
55 }
56
57 /// A root of `x^2 + x = c`, or `None` iff
58 /// `Tr(c) != 0` (then it has no solution).
59 /// When solvable, the roots are the result and
60 /// `result + ONE`. The value path is constant-time;
61 /// only the `Some`/`None` choice reveals `Tr(c)`.
62 fn solve_quadratic(c: Self) -> Option<Self>;
63}
64
65macro_rules! impl_binary_field_extras {
66 ($block:ty, $sub:ty, $map_ct:ident, $trace_mask:ident, $solve_basis:ident) => {
67 impl BinaryFieldExtras for $block {
68 #[inline(always)]
69 fn square(&self) -> Self {
70 // char 2:
71 // (lo + hi·X)^2 = lo^2 + hi^2·X^2,
72 // no cross term.
73 let (lo, hi) = self.split();
74 let hi2 = hi.square();
75
76 Self::new(lo.square() + hi2 * <$sub>::EXTENSION_TAU, hi2)
77 }
78
79 #[inline(always)]
80 fn trace(&self) -> Bit {
81 Bit::new(((self.0 & constants::$trace_mask).count_ones() & 1) as u8)
82 }
83
84 #[inline(always)]
85 fn solve_quadratic(c: Self) -> Option<Self> {
86 if c.trace() != Bit::ZERO {
87 return None;
88 }
89
90 Some(Self($map_ct(c.0, &constants::$solve_basis)))
91 }
92 }
93 };
94}
95
96pub(crate) use impl_binary_field_extras;