snarkvm_console_types_scalar/to_field.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> ToField for Scalar<E> {
19 type Field = Field<E>;
20
21 /// Returns the scalar as a field element.
22 fn to_field(&self) -> Result<Self::Field> {
23 // Note: We are reconstituting the scalar field into a base field.
24 // This is safe as the scalar field modulus is less than the base field modulus,
25 // and thus will always fit within a single base field element.
26 debug_assert!(Scalar::<E>::size_in_bits() < Field::<E>::size_in_bits());
27
28 Field::<E>::from_bits_le(&self.to_bits_le())
29 }
30}
31
32#[cfg(test)]
33mod tests {
34 use super::*;
35 use snarkvm_console_network_environment::Console;
36
37 type CurrentEnvironment = Console;
38
39 const ITERATIONS: u64 = 10_000;
40
41 #[test]
42 fn test_to_field() -> Result<()> {
43 let mut rng = TestRng::default();
44
45 for _ in 0..ITERATIONS {
46 // Sample a random value.
47 let scalar: Scalar<CurrentEnvironment> = Uniform::rand(&mut rng);
48
49 let candidate = scalar.to_field()?;
50
51 let expected = scalar.to_bits_le();
52 for (index, candidate_bit) in candidate.to_bits_le().iter().enumerate() {
53 match index < Scalar::<CurrentEnvironment>::size_in_bits() {
54 true => assert_eq!(expected[index], *candidate_bit),
55 false => assert!(!*candidate_bit),
56 }
57 }
58 }
59 Ok(())
60 }
61}