snarkvm_console_types_scalar/from_field_lossy.rs
1// Copyright (c) 2019-2025 Provable Inc.
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::*;
17
18impl<E: Environment> Scalar<E> {
19 /// Casts a scalar from a base field, with lossy truncation.
20 ///
21 /// This method is commonly used by hash-to-scalar algorithms,
22 /// where the hash output does not need to preserve the full base field.
23 pub fn from_field_lossy(field: &Field<E>) -> Self {
24 debug_assert!(Scalar::<E>::size_in_bits() < Field::<E>::size_in_bits());
25
26 // Truncate the field to the size in data bits (1 bit less than the MODULUS) of the scalar.
27 // Slicing here is safe as the base field is larger than the scalar field.
28 let result = Self::from_bits_le(&field.to_bits_le()[..Scalar::<E>::size_in_data_bits()]);
29 debug_assert!(result.is_ok(), "A lossy scalar should always be able to be constructed from field bits");
30 result.unwrap()
31 }
32}
33
34#[cfg(test)]
35mod tests {
36 use super::*;
37 use snarkvm_console_network_environment::Console;
38
39 type CurrentEnvironment = Console;
40
41 const ITERATIONS: u64 = 10_000;
42
43 #[test]
44 fn test_from_field() -> Result<()> {
45 let mut rng = TestRng::default();
46
47 for _ in 0..ITERATIONS {
48 // Sample a random scalar.
49 let size_in_data_bits = Scalar::<CurrentEnvironment>::size_in_data_bits();
50 let prepare = &Scalar::<CurrentEnvironment>::rand(&mut rng).to_bits_le()[0..size_in_data_bits];
51 let expected = Scalar::<CurrentEnvironment>::from_bits_le(prepare)?;
52 // Perform the operation.
53 let candidate = Scalar::from_field_lossy(&expected.to_field()?);
54 assert_eq!(expected, candidate);
55
56 // Sample a random field.
57 let expected = Field::<CurrentEnvironment>::rand(&mut rng);
58 // Perform the operation (should not fail).
59 let _result = Scalar::from_field_lossy(&expected);
60 }
61 Ok(())
62 }
63}