本文深入探讨了 Circom 中 if 语句的使用限制,明确指出信号不能用于改变 if 语句的行为,也不能在依赖于信号的 if 语句中赋值。
Circom 对 if 语句的使用非常严格。必须遵守以下规则:
下面的示例电路演示了这两种违规情况:
template Foo() {
signal input in;
signal input cond;
signal output out;
// if 语句不能依赖于
// 编译时未知的值
if (in == 3) {
// 在 if 语句内部赋值
// 其值在编译时未知
// 是不允许的
out <== 4;
}
}
如果 if 语句不受任何信号的影响,也不影响任何信号,那么它们是可以接受的。
实际上,它们不是底层 Rank 1 Constraint system (R1CS) 的一部分。
例如,如果我们想计算列表中的最大值(而不生成约束),我们可以使用以下典型解决方案,Circom 可以接受,因为不涉及任何信号:
var max;
for (var i = 0; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
此计算不会创建任何约束,它仅仅是为了方便。
可能看起来 Circom 无法进行条件分支,但事实并非如此。要在 Circom 中创建条件分支,必须执行语句的所有分支,将“不需要的”分支乘以零,将“正确的”分支乘以一。
假设我们正在对以下计算进行建模:
def foo(x):
if x == 5:
out = 14
elif x == 9:
out = 22
elif x == 10:
out = 23
else
out = 45
return out
由于 x
和 out
之间没有明确的数学联系,因此最好尽可能直接地对该条件进行建模。以下是我们如何用数学方式描述条件语句:
out=x\_eq\_5⋅14+x\_eq\_9⋅22+x\_eq\_10⋅23+otherwise⋅45
x
等于 5,则 x_eq_5
等于 1,否则等于零,这可以通过 IsEqual()([x, 5])
实现x
等于 9 时,x_eq_9
等于 1,否则等于零x
等于 10 时,x_eq_10
等于 1,否则等于零x_eq_5
、x_eq_9
、x_eq_10
)都为 0 时, otherwise
等于 1。我们可以使用 Circomlib 中的 IsEqual()
模板将值分配给信号 x_eq_5
、x_eq_9
、x_eq_10
和 otherwise
—— 这也将强制它们为 0 或 1。为了确保只有一个信号为 1,其余信号为零,我们使用以下约束:
1===x\_eq\_5+x\_eq\_9+x\_eq\_10+otherwise
一般来说,我们创建“二进制开关”,当特定分支处于活动状态时,该开关为 1,否则为 0。然后,我们将所有分支的评估结果相加,每个分支都乘以其开关。
由于只有一个 out = … 分支会处于活动状态,因此其余的评估结果都乘以 0,因此无关紧要。
以下是完整的电路:
include "./node_modules/circomlib/circuits/comparators.circom";
template MultiBranchConditional() {
signal input x;
signal output out;
signal x_eq_5;
signal x_eq_9;
signal x_eq_10;
signal otherwise;
x_eq_5 <== IsEqual()([x, 5]);
x_eq_9 <== IsEqual()([x, 9]);
x_eq_10 <== IsEqual()([x, 10]);
otherwise <== IsZero()(x_eq_5 + x_eq_9 + x_eq_10);
signal branches_5_9;
signal branches_10_otherwise;
branches_5_9 <== x_eq_5 * 14 + x_eq_9 * 22;
branches_10_otherwise <== x_eq_10 * 23 + otherwise * 45;
out <== branches_5_9 + branches_10_otherwise;
}
component main = MultiBranchConditional();
为了使我们的代码更简洁,最好将四向分支作为一个单独的组件——这样,我们可以重用分支模板。
include "./node_modules/circomlib/circuits/comparators.circom";
template Branch4(cond1, cond2, cond3, branch1, branch2, branch3, branch4) {
signal input x;
signal output out;
signal switch1;
signal switch2;
signal switch3;
signal otherwise;
switch1 <== IsEqual()([x, cond1]);
switch2 <== IsEqual()([x, cond2])...
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!