snarkvm_console_types_group/from_fields.rs
1// Copyright (c) 2019-2026 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> FromFields for Group<E> {
19 type Field = Field<E>;
20
21 /// Initializes a new group by recovering the **x-coordinate** of an affine group from a field element.
22 fn from_fields(fields: &[Self::Field]) -> Result<Self> {
23 // Ensure there is exactly one field element in the vector.
24 ensure!(fields.len() == 1, "Group must be recovered from a single field element");
25 // Recover the group from the field element.
26 Self::from_field(&fields[0])
27 }
28}
29
30#[cfg(test)]
31mod tests {
32 use super::*;
33 use snarkvm_console_network_environment::Console;
34
35 type CurrentEnvironment = Console;
36
37 const ITERATIONS: u64 = 10_000;
38
39 fn check_from_fields() -> Result<()> {
40 let mut rng = TestRng::default();
41
42 for _ in 0..ITERATIONS {
43 // Sample a random value.
44 let expected = Group::<CurrentEnvironment>::new(Uniform::rand(&mut rng));
45 let candidate = Group::<CurrentEnvironment>::from_fields(&expected.to_fields()?)?;
46 assert_eq!(expected, candidate);
47 }
48 Ok(())
49 }
50
51 #[test]
52 fn test_from_fields() -> Result<()> {
53 check_from_fields()
54 }
55}