vsss_rs_std/
polynomial.rs

1/*
2    Copyright Michael Lodder. All Rights Reserved.
3    SPDX-License-Identifier: Apache-2.0
4*/
5
6use elliptic_curve::ff::PrimeField;
7use rand_core::{CryptoRng, RngCore};
8
9/// The polynomial used for generating the shares
10pub struct Polynomial<F: PrimeField> {
11    pub(crate) coefficients: Vec<F>,
12}
13
14impl<F: PrimeField> Polynomial<F> {
15    /// Construct a random polynomial with `N` degree using the specified intercept
16    pub fn new(intercept: F, mut rng: impl RngCore + CryptoRng, length: usize) -> Self {
17        let mut coefficients = Vec::with_capacity(length);
18
19        // Ensure intercept is set
20        coefficients.push(intercept);
21
22        // Assign random coefficients to polynomial
23        // Start at 1 since 0 is the intercept and not chosen at random
24        for _ in 1..length {
25            coefficients.push(F::random(&mut rng));
26        }
27        Self { coefficients }
28    }
29
30    /// Compute the value of the polynomial for the given `x`
31    pub fn evaluate(&self, x: F, threshold: usize) -> F {
32        // Compute the polynomial value using Horner's Method
33        let degree = threshold - 1;
34        // b_n = a_n
35        let mut out = self.coefficients[degree];
36
37        for i in (0..degree).rev() {
38            // b_{n-1} = a_{n-1} + b_n*x
39            out *= x;
40            out += self.coefficients[i];
41        }
42        out
43    }
44}