snarkvm_circuit_program/data/literal/cast_lossy/
field.rs

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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// Copyright 2024 Aleo Network Foundation
// 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> CastLossy<Address<E>> for Field<E> {
    /// Casts a `Field` to an `Address`.
    ///
    /// This operation attempts to recover the group element from the given field,
    /// which is then used to construct the address. See the documentation of `Field::cast_lossy`
    /// on the `Group` type for more details.
    #[inline]
    fn cast_lossy(&self) -> Address<E> {
        // Perform a lossy cast to a group element.
        let group: Group<E> = self.cast_lossy();
        // Convert the group element to an address.
        Address::from_group(group)
    }
}

impl<E: Environment> CastLossy<Boolean<E>> for Field<E> {
    /// Casts a `Field` to a `Boolean`, with lossy truncation.
    /// This operation returns the least significant bit of the field.
    #[inline]
    fn cast_lossy(&self) -> Boolean<E> {
        let bits_le = self.to_bits_le();
        debug_assert!(!bits_le.is_empty(), "An integer must have at least one bit");
        bits_le[0].clone()
    }
}

impl<E: Environment> CastLossy<Field<E>> for Field<E> {
    /// Casts a `Field` to a `Field`.
    /// This is an identity cast, so it is **always** lossless.
    #[inline]
    fn cast_lossy(&self) -> Field<E> {
        self.clone()
    }
}

impl<E: Environment> CastLossy<Group<E>> for Field<E> {
    /// Casts a `Field` to a `Group`.
    ///
    /// This operation attempts to recover the group element from the given field.
    ///
    /// If the field is a valid x-coordinate, then the group element is returned.
    /// If the field is not a valid x-coordinate, then if the field is the one element,
    /// the generator of the prime-order subgroup is returned.
    /// Otherwise, Elligator-2 is applied to the field element to recover a group element.
    #[inline]
    fn cast_lossy(&self) -> Group<E> {
        // This method requires that an `x-coordinate` of 1 is an invalid group element.
        // This is used by the ternary below, which uses 'is_x_one' to determine whether to return the generator.
        debug_assert!(console::Group::from_x_coordinate(<console::Field<E::Network> as console::One>::one()).is_err());

        // Attempt to find a group element with self as the x-coordinate.
        let (point_with_x, x_is_not_in_group) = Group::from_x_coordinate_flagged(self.clone());

        // Determine if the field element is zero.
        let is_x_zero = self.is_zero();
        // Determine if the field element is one.
        let is_x_one = self.is_one();

        // Initialize the group generator.
        let generator = Group::generator();

        // Determine the input to Elligator-2, based on the x-coordinate.
        // If self is 0, we pass 1 to Elligator-2 instead.
        // Note that, in this case, we won't use the result of Elligator-2,
        // because the point (0, 1) is in the subgroup, and that is what we return.
        let elligator_input = Field::ternary(&is_x_zero, &Field::one(), self);
        // Perform Elligator-2 on the field element, to recover a group element.
        let elligator_point = Elligator2::encode(&elligator_input);

        // Select either the generator or the result of Elligator-2, depending on whether x is 1 or not.
        // This is only used when x is not in the group, see below.
        let generator_or_elligator_point = Group::ternary(&is_x_one, &generator, &elligator_point);

        // Select either the group point with x or the generator or the result of Elligator-2,
        // depending on whether x is in the group or not, and, if it is not, based on whether it is 1 or not.
        Group::ternary(&x_is_not_in_group, &generator_or_elligator_point, &point_with_x)
    }
}

impl<E: Environment, I: IntegerType> CastLossy<Integer<E, I>> for Field<E> {
    /// Casts a `Field` to an `Integer`, with lossy truncation.
    /// This operation truncates the field to an integer.
    #[inline]
    fn cast_lossy(&self) -> Integer<E, I> {
        Integer::from_field_lossy(self)
    }
}

impl<E: Environment> CastLossy<Scalar<E>> for Field<E> {
    /// Casts a `Field` to a `Scalar`, with lossy truncation.
    /// This operation truncates the field to a scalar.
    #[inline]
    fn cast_lossy(&self) -> Scalar<E> {
        Scalar::from_field_lossy(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use console::CastLossy as _;
    use console_root::{
        network::MainnetV0,
        prelude::{One, TestRng, Uniform, Zero},
    };
    use snarkvm_circuit_types::environment::{Circuit, Eject, Inject, Mode, UpdatableCount, count_is, count_less_than};

    use std::fmt::Debug;

    const ITERATIONS: usize = 100;

    fn sample_values(
        i: usize,
        mode: Mode,
        rng: &mut TestRng,
    ) -> (console_root::types::Field<MainnetV0>, Field<Circuit>) {
        let console_value = match i {
            0 => console_root::types::Field::<MainnetV0>::zero(),
            1 => console_root::types::Field::<MainnetV0>::one(),
            _ => Uniform::rand(rng),
        };
        let circuit_value = Field::<Circuit>::new(mode, console_value);
        (console_value, circuit_value)
    }

    check_cast_lossy!(cast_lossy, Field<Circuit>, console_root::types::Field::<MainnetV0>);

    #[test]
    fn test_field_to_address() {
        check_cast_lossy::<Address<Circuit>, console_root::types::Address<MainnetV0>>(
            Mode::Constant,
            count_less_than!(4303, 0, 0, 0),
        );
        check_cast_lossy::<Address<Circuit>, console_root::types::Address<MainnetV0>>(
            Mode::Public,
            count_is!(2029, 0, 6745, 6750),
        );
        check_cast_lossy::<Address<Circuit>, console_root::types::Address<MainnetV0>>(
            Mode::Private,
            count_is!(2029, 0, 6745, 6750),
        );
    }

    #[test]
    fn test_field_to_boolean() {
        check_cast_lossy::<Boolean<Circuit>, console_root::types::Boolean<MainnetV0>>(
            Mode::Constant,
            count_is!(253, 0, 0, 0),
        );
        check_cast_lossy::<Boolean<Circuit>, console_root::types::Boolean<MainnetV0>>(
            Mode::Public,
            count_is!(0, 0, 505, 507),
        );
        check_cast_lossy::<Boolean<Circuit>, console_root::types::Boolean<MainnetV0>>(
            Mode::Private,
            count_is!(0, 0, 505, 507),
        );
    }

    #[test]
    fn test_field_to_field() {
        check_cast_lossy::<Field<Circuit>, console_root::types::Field<MainnetV0>>(
            Mode::Constant,
            count_is!(0, 0, 0, 0),
        );
        check_cast_lossy::<Field<Circuit>, console_root::types::Field<MainnetV0>>(Mode::Public, count_is!(0, 0, 0, 0));
        check_cast_lossy::<Field<Circuit>, console_root::types::Field<MainnetV0>>(Mode::Private, count_is!(0, 0, 0, 0));
    }

    #[test]
    fn test_field_to_group() {
        check_cast_lossy::<Group<Circuit>, console_root::types::Group<MainnetV0>>(
            Mode::Constant,
            count_less_than!(4303, 0, 0, 0),
        );
        check_cast_lossy::<Group<Circuit>, console_root::types::Group<MainnetV0>>(
            Mode::Public,
            count_is!(2029, 0, 6745, 6750),
        );
        check_cast_lossy::<Group<Circuit>, console_root::types::Group<MainnetV0>>(
            Mode::Private,
            count_is!(2029, 0, 6745, 6750),
        );
    }

    #[test]
    fn test_field_to_i8() {
        check_cast_lossy::<I8<Circuit>, console_root::types::I8<MainnetV0>>(Mode::Constant, count_is!(253, 0, 0, 0));
        check_cast_lossy::<I8<Circuit>, console_root::types::I8<MainnetV0>>(Mode::Public, count_is!(0, 0, 505, 507));
        check_cast_lossy::<I8<Circuit>, console_root::types::I8<MainnetV0>>(Mode::Private, count_is!(0, 0, 505, 507));
    }

    #[test]
    fn test_field_to_i16() {
        check_cast_lossy::<I16<Circuit>, console_root::types::I16<MainnetV0>>(Mode::Constant, count_is!(253, 0, 0, 0));
        check_cast_lossy::<I16<Circuit>, console_root::types::I16<MainnetV0>>(Mode::Public, count_is!(0, 0, 505, 507));
        check_cast_lossy::<I16<Circuit>, console_root::types::I16<MainnetV0>>(Mode::Private, count_is!(0, 0, 505, 507));
    }

    #[test]
    fn test_field_to_i32() {
        check_cast_lossy::<I32<Circuit>, console_root::types::I32<MainnetV0>>(Mode::Constant, count_is!(253, 0, 0, 0));
        check_cast_lossy::<I32<Circuit>, console_root::types::I32<MainnetV0>>(Mode::Public, count_is!(0, 0, 505, 507));
        check_cast_lossy::<I32<Circuit>, console_root::types::I32<MainnetV0>>(Mode::Private, count_is!(0, 0, 505, 507));
    }

    #[test]
    fn test_field_to_i64() {
        check_cast_lossy::<I64<Circuit>, console_root::types::I64<MainnetV0>>(Mode::Constant, count_is!(253, 0, 0, 0));
        check_cast_lossy::<I64<Circuit>, console_root::types::I64<MainnetV0>>(Mode::Public, count_is!(0, 0, 505, 507));
        check_cast_lossy::<I64<Circuit>, console_root::types::I64<MainnetV0>>(Mode::Private, count_is!(0, 0, 505, 507));
    }

    #[test]
    fn test_field_to_i128() {
        check_cast_lossy::<I128<Circuit>, console_root::types::I128<MainnetV0>>(
            Mode::Constant,
            count_is!(253, 0, 0, 0),
        );
        check_cast_lossy::<I128<Circuit>, console_root::types::I128<MainnetV0>>(
            Mode::Public,
            count_is!(0, 0, 505, 507),
        );
        check_cast_lossy::<I128<Circuit>, console_root::types::I128<MainnetV0>>(
            Mode::Private,
            count_is!(0, 0, 505, 507),
        );
    }

    #[test]
    fn test_field_to_scalar() {
        check_cast_lossy::<Scalar<Circuit>, console_root::types::Scalar<MainnetV0>>(
            Mode::Constant,
            count_is!(253, 0, 0, 0),
        );
        check_cast_lossy::<Scalar<Circuit>, console_root::types::Scalar<MainnetV0>>(
            Mode::Public,
            count_is!(0, 0, 505, 507),
        );
        check_cast_lossy::<Scalar<Circuit>, console_root::types::Scalar<MainnetV0>>(
            Mode::Private,
            count_is!(0, 0, 505, 507),
        );
    }

    #[test]
    fn test_field_to_u8() {
        check_cast_lossy::<U8<Circuit>, console_root::types::U8<MainnetV0>>(Mode::Constant, count_is!(253, 0, 0, 0));
        check_cast_lossy::<U8<Circuit>, console_root::types::U8<MainnetV0>>(Mode::Public, count_is!(0, 0, 505, 507));
        check_cast_lossy::<U8<Circuit>, console_root::types::U8<MainnetV0>>(Mode::Private, count_is!(0, 0, 505, 507));
    }

    #[test]
    fn test_field_to_u16() {
        check_cast_lossy::<U16<Circuit>, console_root::types::U16<MainnetV0>>(Mode::Constant, count_is!(253, 0, 0, 0));
        check_cast_lossy::<U16<Circuit>, console_root::types::U16<MainnetV0>>(Mode::Public, count_is!(0, 0, 505, 507));
        check_cast_lossy::<U16<Circuit>, console_root::types::U16<MainnetV0>>(Mode::Private, count_is!(0, 0, 505, 507));
    }

    #[test]
    fn test_field_to_u32() {
        check_cast_lossy::<U32<Circuit>, console_root::types::U32<MainnetV0>>(Mode::Constant, count_is!(253, 0, 0, 0));
        check_cast_lossy::<U32<Circuit>, console_root::types::U32<MainnetV0>>(Mode::Public, count_is!(0, 0, 505, 507));
        check_cast_lossy::<U32<Circuit>, console_root::types::U32<MainnetV0>>(Mode::Private, count_is!(0, 0, 505, 507));
    }

    #[test]
    fn test_field_to_u64() {
        check_cast_lossy::<U64<Circuit>, console_root::types::U64<MainnetV0>>(Mode::Constant, count_is!(253, 0, 0, 0));
        check_cast_lossy::<U64<Circuit>, console_root::types::U64<MainnetV0>>(Mode::Public, count_is!(0, 0, 505, 507));
        check_cast_lossy::<U64<Circuit>, console_root::types::U64<MainnetV0>>(Mode::Private, count_is!(0, 0, 505, 507));
    }

    #[test]
    fn test_field_to_u128() {
        check_cast_lossy::<U128<Circuit>, console_root::types::U128<MainnetV0>>(
            Mode::Constant,
            count_is!(253, 0, 0, 0),
        );
        check_cast_lossy::<U128<Circuit>, console_root::types::U128<MainnetV0>>(
            Mode::Public,
            count_is!(0, 0, 505, 507),
        );
        check_cast_lossy::<U128<Circuit>, console_root::types::U128<MainnetV0>>(
            Mode::Private,
            count_is!(0, 0, 505, 507),
        );
    }
}