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
use crate::nonnative::{AllocatedNonNativeFieldMulResultVar, NonNativeFieldVar};
use snarkvm_fields::PrimeField;
use snarkvm_r1cs::{errors::SynthesisError, ConstraintSystem};
#[derive(Debug)]
pub enum NonNativeFieldMulResultVar<TargetField: PrimeField, BaseField: PrimeField> {
Constant(TargetField),
Variable(AllocatedNonNativeFieldMulResultVar<TargetField, BaseField>),
}
impl<TargetField: PrimeField, BaseField: PrimeField> NonNativeFieldMulResultVar<TargetField, BaseField> {
pub fn zero() -> Self {
Self::Constant(TargetField::zero())
}
pub fn constant(v: TargetField) -> Self {
Self::Constant(v)
}
pub fn reduce<CS: ConstraintSystem<BaseField>>(
&self,
cs: &mut CS,
) -> Result<NonNativeFieldVar<TargetField, BaseField>, SynthesisError> {
match self {
Self::Constant(c) => Ok(NonNativeFieldVar::Constant(*c)),
Self::Variable(v) => Ok(NonNativeFieldVar::Var(v.reduce(cs)?)),
}
}
pub fn from_nonnative_field_gadget<CS: ConstraintSystem<BaseField>>(
cs: &mut CS,
src: &NonNativeFieldVar<TargetField, BaseField>,
) -> Result<Self, SynthesisError> {
match src {
NonNativeFieldVar::Constant(c) => Ok(NonNativeFieldMulResultVar::Constant(*c)),
NonNativeFieldVar::Var(v) => Ok(NonNativeFieldMulResultVar::Variable(
AllocatedNonNativeFieldMulResultVar::<TargetField, BaseField>::from_allocated_nonnative_field_gadget(
cs, v,
)?,
)),
}
}
pub fn add<CS: ConstraintSystem<BaseField>>(&self, cs: &mut CS, other: &Self) -> Result<Self, SynthesisError> {
match (self, other) {
(Self::Constant(c1), Self::Constant(c2)) => Ok(Self::Constant(*c1 + c2)),
(Self::Constant(c), Self::Variable(v)) | (Self::Variable(v), Self::Constant(c)) => {
Ok(Self::Variable(v.add_constant(cs, &c)?))
}
(Self::Variable(v1), Self::Variable(v2)) => Ok(Self::Variable(v1.add(cs, &v2)?)),
}
}
}