Skip to main content

sp1_core_machine/operations/
sub.rs

1use serde::{Deserialize, Serialize};
2use sp1_core_executor::events::ByteRecord;
3use sp1_hypercube::{air::SP1AirBuilder, Word};
4use sp1_primitives::consts::{u64_to_u16_limbs, WORD_SIZE};
5use struct_reflection::{StructReflection, StructReflectionHelper};
6
7use slop_air::AirBuilder;
8use slop_algebra::{AbstractField, Field};
9use sp1_derive::{AlignedBorrow, InputExpr, InputParams, IntoShape, SP1OperationBuilder};
10
11use crate::air::{SP1Operation, WordAirBuilder};
12
13/// A set of columns needed to compute the sub of two words.
14#[derive(
15    AlignedBorrow,
16    Default,
17    Debug,
18    Clone,
19    Copy,
20    Serialize,
21    Deserialize,
22    IntoShape,
23    SP1OperationBuilder,
24    StructReflection,
25)]
26#[repr(C)]
27pub struct SubOperation<T> {
28    /// The result of `a - b`.
29    pub value: Word<T>,
30}
31
32impl<F: Field> SubOperation<F> {
33    pub fn populate(&mut self, record: &mut impl ByteRecord, a_u64: u64, b_u64: u64) -> u64 {
34        let expected = a_u64.wrapping_sub(b_u64);
35        self.value = Word::from(expected);
36        // Range check
37        record.add_u16_range_checks(&u64_to_u16_limbs(expected));
38        expected
39    }
40
41    /// Evaluate the sub operation.
42    /// Assumes that `a`, `b` are valid `Word`s of u16 limbs.
43    /// Constrains that `is_real` is boolean.
44    /// If `is_real` is true, the `value` is constrained to a valid `Word` representing `a - b`.
45    pub fn eval<AB: SP1AirBuilder>(
46        builder: &mut AB,
47        a: Word<AB::Var>,
48        b: Word<AB::Var>,
49        cols: SubOperation<AB::Var>,
50        is_real: AB::Expr,
51    ) {
52        builder.assert_bool(is_real.clone());
53
54        let base = AB::F::from_canonical_u32(1 << 16);
55        let mut builder_is_real = builder.when(is_real.clone());
56        let mut carry = AB::Expr::one();
57        let one = AB::Expr::one();
58
59        // Use the same logic as addition, for (a + (2^64 - b)).
60        // This by using `2^16 - 1 - b[i]` as the added limb, and initializing the carry to 1.
61        for i in 0..WORD_SIZE {
62            carry = (a[i] + base - one.clone() - b[i] - cols.value[i] + carry) * base.inverse();
63            builder_is_real.assert_bool(carry.clone());
64        }
65
66        // Range check each limb.
67        builder.slice_range_check_u16(&cols.value.0, is_real);
68    }
69}
70
71#[derive(Clone, InputExpr, InputParams)]
72pub struct SubOperationInput<AB: SP1AirBuilder> {
73    pub a: Word<AB::Var>,
74    pub b: Word<AB::Var>,
75    pub cols: SubOperation<AB::Var>,
76    pub is_real: AB::Expr,
77}
78
79impl<AB: SP1AirBuilder> SP1Operation<AB> for SubOperation<AB::F> {
80    type Input = SubOperationInput<AB>;
81    type Output = ();
82
83    fn lower(builder: &mut AB, input: Self::Input) -> Self::Output {
84        Self::eval(builder, input.a, input.b, input.cols, input.is_real);
85    }
86}