///|
/// Arithmetic in GF(2^8) with the AES polynomial 0x11B. Bytes are carried
/// as Int in 0..255. Subtraction is addition is XOR, which is what makes
/// the Lagrange interpolation in shamir.mbt lose its minus signs: the
/// weight of point i at zero is the product of x_j times the inverse of
/// x_i XOR x_j.
///|
/// Exponent and logarithm tables over generator 3, which has order 255
/// over 0x11B. Multiplication becomes an add of logarithms - the same
/// field through a different construction than shift-and-reduce, and the
/// two are held equal on every input pair by the exhaustive test below.
let gf_exp : FixedArray[Int32] = FixedArray::make(512, 0)
///|
let gf_log : FixedArray[Int32] = FixedArray::make(256, 0)
///|
fn init {
// Multiply by 3 is x XOR xtime(x), with xtime reducing past 0x100.
let mut x = 1
for i in 0..<255 {
gf_exp[i] = x
gf_log[x] = i
let doubled = x << 1
let reduced = if doubled >= 256 { doubled ^ 0x11B } else { doubled }
x = x ^ reduced
}
for i in 255..<512 {
gf_exp[i] = gf_exp[i - 255]
}
}
///|
/// Table multiplication: zero short-circuits because it has no logarithm.
fn gf_mul(left : Int32, right : Int32) -> Int32 {
if left == 0 || right == 0 {
0
} else {
gf_exp[gf_log[left] + gf_log[right]]
}
}
///|
/// The shift-and-reduce multiplier the tables were built against, kept as
/// the independent witness for the exhaustive equality test.
fn gf_mul_shift(left : Int32, right : Int32) -> Int32 {
let mut product = 0
let mut x = left
let mut y = right
while y > 0 {
if (y & 1) == 1 {
product = product ^ x
}
x = x << 1
if x >= 256 {
x = x ^ 0x11B
}
y = y >> 1
}
product
}
///|
fn gf_pow(base : Int32, exponent : Int32) -> Int32 {
let mut result = 1
let mut square = base
let mut n = exponent
while n > 0 {
if (n & 1) == 1 {
result = gf_mul(result, square)
}
square = gf_mul(square, square)
n = n >> 1
}
result
}
///|
/// The multiplicative inverse by Fermat: a^254, valid for every nonzero a.
fn gf_inv(value : Int32) -> Int32 {
gf_pow(value, 254)
}
///|
/// Horner evaluation of the coefficient list (constant term first) at x.
fn gf_eval(coefficients : Array[Int32], x : Int32) -> Int32 {
let mut acc = 0
for i in 0.. Int32 {
let mut acc = 0
for i in 0.. Int32 {
gf_interpolate_at(points, 0)
}
///|
/// The Lagrange weights of the points at `at`, computed once: weight_i =
/// product over j != i of (at XOR x_j) / (x_i XOR x_j). With the weights
/// in hand, interpolating any number of byte positions costs k multiplies
/// each instead of k^2 inversions each - the batch shape combine,
/// diagnose and reshare all want.
pub fn gf_lagrange_weights(
points : Array[(Int32, Int32)],
at : Int32,
) -> Array[Int32] {
let weights : Array[Int32] = []
for i in 0.. Int32 {
let mut acc = 0
for i in 0..