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
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the snarkVM library.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::*;
impl<E: Environment> FromBits for Field<E> {
type Boolean = Boolean<E>;
/// Initializes a new base field element from a list of **little-endian** bits.
/// - If `bits_le` is longer than `E::BaseField::size_in_bits()`, the excess bits are enforced to be `0`s.
/// - If `bits_le` is shorter than `E::BaseField::size_in_bits()`, it is padded with `0`s up to base field size.
fn from_bits_le(bits_le: &[Self::Boolean]) -> Self {
// Retrieve the data and base field size.
let size_in_data_bits = E::BaseField::size_in_data_bits();
let size_in_bits = E::BaseField::size_in_bits();
// Ensure the list of booleans is within the allowed size in bits.
let num_bits = bits_le.len();
if num_bits > size_in_bits {
// Check if all excess bits are zero.
for bit in bits_le[size_in_bits..].iter() {
E::assert_eq(E::zero(), bit);
}
}
// If `num_bits` is greater than `size_in_data_bits`, check it is less than `BaseField::MODULUS`.
if num_bits > size_in_data_bits {
// Retrieve the modulus & subtract by 1 as we'll check `bits_le` is less than or *equal* to this value.
// (For advanced users) BaseField::MODULUS - 1 is equivalent to -1 in the field.
let modulus_minus_one = -E::BaseField::one();
// As `bits_le[size_in_bits..]` is guaranteed to be zero from the above logic,
// and `bits_le` is greater than `size_in_data_bits`, it is safe to truncate `bits_le` to `size_in_bits`.
let bits_le = &bits_le[..size_in_bits];
// Assert `bits_le <= (BaseField::MODULUS - 1)`, which is equivalent to `bits_le < BaseField::MODULUS`.
Boolean::assert_less_than_or_equal_constant(bits_le, &modulus_minus_one.to_bits_le());
}
// Reconstruct the bits as a linear combination representing the original field value.
// `output` := (2^i * b_i + ... + 2^0 * b_0)
let mut output = Field::zero();
let mut coefficient = Field::one();
for bit in bits_le.iter().take(size_in_bits) {
output += Field::from_boolean(bit) * &coefficient;
coefficient = coefficient.double();
}
// Construct the sanitized list of bits, resizing up if necessary.
let mut bits_le = bits_le.iter().take(size_in_bits).cloned().collect::<Vec<_>>();
bits_le.resize(size_in_bits, Boolean::constant(false));
// Store the little-endian bits in the output.
if output.bits_le.set(bits_le).is_err() {
E::halt("Detected corrupt internal state for the bits of a field element")
}
output
}
/// Initializes a new base field element from a list of big-endian bits *without* leading zeros.
fn from_bits_be(bits_be: &[Self::Boolean]) -> Self {
// Reverse the given bits from big-endian into little-endian.
// Note: This is safe as the bit representation is consistent (there are no leading zeros).
let mut bits_le = bits_be.to_vec();
bits_le.reverse();
Self::from_bits_le(&bits_le)
}
}
impl<E: Environment> Metrics<dyn FromBits<Boolean = Boolean<E>>> for Field<E> {
type Case = Vec<Mode>;
fn count(_modes: &Self::Case) -> Count {
todo!()
}
}
impl<E: Environment> OutputMode<dyn FromBits<Boolean = Boolean<E>>> for Field<E> {
type Case = Vec<Mode>;
fn output_mode(case: &Self::Case) -> Mode {
match case.iter().all(|mode| mode.is_constant()) {
true => Mode::Constant,
false => Mode::Private,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use snarkvm_circuit_environment::Circuit;
const ITERATIONS: u64 = 100;
fn check_from_bits_le(mode: Mode, num_constants: u64, num_public: u64, num_private: u64, num_constraints: u64) {
let mut rng = TestRng::default();
for i in 0..ITERATIONS {
// Sample a random element.
let expected = Uniform::rand(&mut rng);
let given_bits = Field::<Circuit>::new(mode, expected).to_bits_le();
let expected_size_in_bits = given_bits.len();
Circuit::scope(format!("{mode} {i}"), || {
let candidate = Field::<Circuit>::from_bits_le(&given_bits);
assert_eq!(expected, candidate.eject_value());
assert_eq!(expected_size_in_bits, candidate.bits_le.get().expect("Caching failed").len());
assert_scope!(num_constants, num_public, num_private, num_constraints);
// Ensure a subsequent call to `to_bits_le` does not incur additional costs.
let candidate_bits = candidate.to_bits_le();
assert_eq!(expected_size_in_bits, candidate_bits.len());
assert_scope!(num_constants, num_public, num_private, num_constraints);
});
// Add excess zero bits.
let candidate = vec![given_bits, vec![Boolean::new(mode, false); i as usize]].concat();
Circuit::scope(&format!("Excess {mode} {i}"), || {
let candidate = Field::<Circuit>::from_bits_le(&candidate);
assert_eq!(expected, candidate.eject_value());
assert_eq!(expected_size_in_bits, candidate.bits_le.get().expect("Caching failed").len());
match mode.is_constant() {
true => assert_scope!(num_constants, num_public, num_private, num_constraints),
// `num_private` gets 1 free excess bit, then is incremented by one for each excess bit.
// `num_constraints` is incremented by one for each excess bit.
false => {
assert_scope!(num_constants, num_public, num_private, num_constraints + i)
}
};
});
}
}
fn check_from_bits_be(mode: Mode, num_constants: u64, num_public: u64, num_private: u64, num_constraints: u64) {
let mut rng = TestRng::default();
for i in 0..ITERATIONS {
// Sample a random element.
let expected = Uniform::rand(&mut rng);
let given_bits = Field::<Circuit>::new(mode, expected).to_bits_be();
let expected_size_in_bits = given_bits.len();
Circuit::scope(format!("{mode} {i}"), || {
let candidate = Field::<Circuit>::from_bits_be(&given_bits);
assert_eq!(expected, candidate.eject_value());
assert_eq!(expected_size_in_bits, candidate.bits_le.get().expect("Caching failed").len());
assert_scope!(num_constants, num_public, num_private, num_constraints);
// Ensure a subsequent call to `to_bits_be` does not incur additional costs.
let candidate_bits = candidate.to_bits_be();
assert_eq!(expected_size_in_bits, candidate_bits.len());
assert_scope!(num_constants, num_public, num_private, num_constraints);
});
// Add excess zero bits.
let candidate = vec![vec![Boolean::new(mode, false); i as usize], given_bits].concat();
Circuit::scope(&format!("Excess {mode} {i}"), || {
let candidate = Field::<Circuit>::from_bits_be(&candidate);
assert_eq!(expected, candidate.eject_value());
assert_eq!(expected_size_in_bits, candidate.bits_le.get().expect("Caching failed").len());
match mode.is_constant() {
true => assert_scope!(num_constants, num_public, num_private, num_constraints),
// `num_private` gets 1 free excess bit, then is incremented by one for each excess bit.
// `num_constraints` is incremented by one for each excess bit.
false => {
assert_scope!(num_constants, num_public, num_private, num_constraints + i)
}
};
});
}
}
#[test]
fn test_from_bits_le_constant() {
check_from_bits_le(Mode::Constant, 0, 0, 0, 0);
}
#[test]
fn test_from_bits_le_public() {
check_from_bits_le(Mode::Public, 0, 0, 252, 253);
}
#[test]
fn test_from_bits_le_private() {
check_from_bits_le(Mode::Private, 0, 0, 252, 253);
}
#[test]
fn test_from_bits_be_constant() {
check_from_bits_be(Mode::Constant, 0, 0, 0, 0);
}
#[test]
fn test_from_bits_be_public() {
check_from_bits_be(Mode::Public, 0, 0, 252, 253);
}
#[test]
fn test_from_bits_be_private() {
check_from_bits_be(Mode::Private, 0, 0, 252, 253);
}
}