cairo_lang_sierra/extensions/modules/
gas.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
use convert_case::Casing;
use itertools::chain;
use serde::{Deserialize, Serialize};

use super::int::unsigned128::Uint128Type;
// Module providing the gas related extensions.
use super::range_check::RangeCheckType;
use crate::define_libfunc_hierarchy;
use crate::extensions::lib_func::{
    BranchSignature, DeferredOutputKind, LibfuncSignature, OutputVarInfo, ParamSignature,
    SierraApChange, SignatureSpecializationContext,
};
use crate::extensions::{
    NamedType, NoGenericArgsGenericLibfunc, NoGenericArgsGenericType, OutputVarReferenceInfo,
    SpecializationError,
};
use crate::ids::GenericTypeId;

/// Type for gas actions.
#[derive(Default)]
pub struct GasBuiltinType {}
impl NoGenericArgsGenericType for GasBuiltinType {
    const ID: GenericTypeId = GenericTypeId::new_inline("GasBuiltin");
    const STORABLE: bool = true;
    const DUPLICATABLE: bool = false;
    const DROPPABLE: bool = false;
    const ZERO_SIZED: bool = false;
}

define_libfunc_hierarchy! {
    pub enum GasLibfunc {
        WithdrawGas(WithdrawGasLibfunc),
        RedepositGas(RedepositGasLibfunc),
        GetAvailableGas(GetAvailableGasLibfunc),
        BuiltinWithdrawGas(BuiltinCostWithdrawGasLibfunc),
        GetBuiltinCosts(BuiltinCostGetBuiltinCostsLibfunc),
    }, GasConcreteLibfunc
}

/// Libfunc for withdrawing gas.
#[derive(Default)]
pub struct WithdrawGasLibfunc {}
impl NoGenericArgsGenericLibfunc for WithdrawGasLibfunc {
    const STR_ID: &'static str = "withdraw_gas";

    fn specialize_signature(
        &self,
        context: &dyn SignatureSpecializationContext,
    ) -> Result<LibfuncSignature, SpecializationError> {
        let gas_builtin_type = context.get_concrete_type(GasBuiltinType::id(), &[])?;
        let range_check_type = context.get_concrete_type(RangeCheckType::id(), &[])?;
        let rc_output_info = OutputVarInfo::new_builtin(range_check_type.clone(), 0);
        Ok(LibfuncSignature {
            param_signatures: vec![
                ParamSignature::new(range_check_type).with_allow_add_const(),
                ParamSignature::new(gas_builtin_type.clone()),
            ],
            branch_signatures: vec![
                // Success:
                BranchSignature {
                    vars: vec![rc_output_info.clone(), OutputVarInfo {
                        ty: gas_builtin_type.clone(),
                        ref_info: OutputVarReferenceInfo::NewTempVar { idx: 0 },
                    }],
                    ap_change: SierraApChange::Known { new_vars_only: false },
                },
                // Failure:
                BranchSignature {
                    vars: vec![rc_output_info, OutputVarInfo {
                        ty: gas_builtin_type,
                        ref_info: OutputVarReferenceInfo::SameAsParam { param_idx: 1 },
                    }],
                    ap_change: SierraApChange::Known { new_vars_only: false },
                },
            ],
            fallthrough: Some(0),
        })
    }
}

/// Libfunc for returning unused gas.
#[derive(Default)]
pub struct RedepositGasLibfunc {}
impl NoGenericArgsGenericLibfunc for RedepositGasLibfunc {
    const STR_ID: &'static str = "redeposit_gas";

    fn specialize_signature(
        &self,
        context: &dyn SignatureSpecializationContext,
    ) -> Result<LibfuncSignature, SpecializationError> {
        let gas_builtin_type = context.get_concrete_type(GasBuiltinType::id(), &[])?;
        Ok(LibfuncSignature::new_non_branch(
            vec![gas_builtin_type.clone()],
            vec![OutputVarInfo {
                ty: gas_builtin_type,
                ref_info: OutputVarReferenceInfo::Deferred(DeferredOutputKind::Generic),
            }],
            SierraApChange::Known { new_vars_only: false },
        ))
    }
}

/// Libfunc for returning the amount of available gas.
#[derive(Default)]
pub struct GetAvailableGasLibfunc {}
impl NoGenericArgsGenericLibfunc for GetAvailableGasLibfunc {
    const STR_ID: &'static str = "get_available_gas";

    fn specialize_signature(
        &self,
        context: &dyn SignatureSpecializationContext,
    ) -> Result<LibfuncSignature, SpecializationError> {
        let gas_builtin_type = context.get_concrete_type(GasBuiltinType::id(), &[])?;
        Ok(LibfuncSignature::new_non_branch(
            vec![gas_builtin_type.clone()],
            vec![
                OutputVarInfo {
                    ty: gas_builtin_type,
                    ref_info: OutputVarReferenceInfo::SameAsParam { param_idx: 0 },
                },
                OutputVarInfo {
                    ty: context.get_concrete_type(Uint128Type::id(), &[])?,
                    ref_info: OutputVarReferenceInfo::SameAsParam { param_idx: 0 },
                },
            ],
            SierraApChange::Known { new_vars_only: true },
        ))
    }
}

/// Represents different type of costs.
/// Note that if you add a type here you should update 'iter_precost'
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub enum CostTokenType {
    /// A compile time known cost unit. This is a linear combination of the runtime tokens
    /// ([CostTokenType::Step], [CostTokenType::Hole], [CostTokenType::RangeCheck],
    /// [CostTokenType::RangeCheck96]).
    Const,

    // Runtime post-cost token types:
    /// The number of steps.
    Step,
    /// The number of memory holes (untouched memory addresses).
    Hole,
    /// The number of 128-bit range check builtins.
    RangeCheck,
    /// The number of 96-bit range check builtins.
    RangeCheck96,

    // Pre-cost token types (builtins):
    /// One invocation of the pedersen hash function.
    Pedersen,
    /// One invocation of the Poseidon hades permutation.
    Poseidon,
    /// One invocation of the bitwise builtin.
    Bitwise,
    /// One invocation of the EC op builtin.
    EcOp,
    // Add mod builtin.
    AddMod,
    // mul mod builtin.
    MulMod,
}
impl CostTokenType {
    /// Iterates over the pre-cost token types.
    pub fn iter_precost() -> std::slice::Iter<'static, Self> {
        [
            CostTokenType::Pedersen,
            CostTokenType::Poseidon,
            CostTokenType::Bitwise,
            CostTokenType::EcOp,
            CostTokenType::AddMod,
            CostTokenType::MulMod,
        ]
        .iter()
    }

    /// Iterates over the tokens that are used in the Sierra->Casm compilation (pre-cost token types
    /// and [CostTokenType::Const]).
    pub fn iter_casm_tokens()
    -> std::iter::Chain<std::slice::Iter<'static, Self>, std::slice::Iter<'static, Self>> {
        chain!(Self::iter_precost(), [CostTokenType::Const].iter())
    }

    /// Returns the name of the token type, in snake_case.
    pub fn name(&self) -> String {
        match self {
            CostTokenType::Const => "const",
            CostTokenType::Step => "step",
            CostTokenType::Hole => "hole",
            CostTokenType::RangeCheck => "range_check",
            CostTokenType::RangeCheck96 => "range_check96",
            CostTokenType::Pedersen => "pedersen",
            CostTokenType::Bitwise => "bitwise",
            CostTokenType::EcOp => "ec_op",
            CostTokenType::Poseidon => "poseidon",
            CostTokenType::AddMod => "add_mod",
            CostTokenType::MulMod => "mul_mod",
        }
        .into()
    }

    pub fn camel_case_name(&self) -> String {
        self.name().to_case(convert_case::Case::UpperCamel)
    }

    pub fn offset_in_builtin_costs(&self) -> i16 {
        match self {
            CostTokenType::Const
            | CostTokenType::Step
            | CostTokenType::Hole
            | CostTokenType::RangeCheck
            | CostTokenType::RangeCheck96 => {
                panic!("offset_in_builtin_costs is not supported for '{}'.", self.camel_case_name())
            }

            CostTokenType::Pedersen => 0,
            CostTokenType::Bitwise => 1,
            CostTokenType::EcOp => 2,
            CostTokenType::Poseidon => 3,
            // TODO(ilya): Update the actual table.
            CostTokenType::AddMod => 4,
            CostTokenType::MulMod => 5,
        }
    }
}

/// Represents a pointer to an array with the builtin costs.
/// Every element in the array is the cost of a single invocation of a builtin.
///
/// Offsets to the array are given by [CostTokenType::offset_in_builtin_costs].
#[derive(Default)]
pub struct BuiltinCostsType {}
impl NoGenericArgsGenericType for BuiltinCostsType {
    const ID: GenericTypeId = GenericTypeId::new_inline("BuiltinCosts");
    const STORABLE: bool = true;
    const DUPLICATABLE: bool = true;
    const DROPPABLE: bool = true;
    const ZERO_SIZED: bool = false;
}
impl BuiltinCostsType {
    /// Returns the number of steps required for the computation of the requested cost, given the
    /// number of requested token usages. The number of steps is also the change in `ap`.
    /// If `table_available` is false, the number of steps includes the cost of fetching the builtin
    /// cost table.
    pub fn cost_computation_steps<TokenUsages: Fn(CostTokenType) -> usize>(
        table_available: bool,
        token_usages: TokenUsages,
    ) -> usize {
        let calculation_steps = CostTokenType::iter_precost()
            .map(|token_type| match token_usages(*token_type) {
                0 => 0,
                1 => 2,
                _ => 3,
            })
            .sum();
        if calculation_steps > 0 && !table_available {
            calculation_steps + 4
        } else {
            calculation_steps
        }
    }
}

/// Libfunc for withdrawing gas to be used by a builtin.
#[derive(Default)]
pub struct BuiltinCostWithdrawGasLibfunc;
impl NoGenericArgsGenericLibfunc for BuiltinCostWithdrawGasLibfunc {
    const STR_ID: &'static str = "withdraw_gas_all";

    fn specialize_signature(
        &self,
        context: &dyn SignatureSpecializationContext,
    ) -> Result<LibfuncSignature, SpecializationError> {
        let gas_builtin_type = context.get_concrete_type(GasBuiltinType::id(), &[])?;
        let range_check_type = context.get_concrete_type(RangeCheckType::id(), &[])?;
        let builtin_costs_type = context.get_concrete_type(BuiltinCostsType::id(), &[])?;
        let rc_output_info = OutputVarInfo::new_builtin(range_check_type.clone(), 0);
        Ok(LibfuncSignature {
            param_signatures: vec![
                ParamSignature::new(range_check_type).with_allow_add_const(),
                ParamSignature::new(gas_builtin_type.clone()),
                ParamSignature::new(builtin_costs_type),
            ],
            branch_signatures: vec![
                // Success:
                BranchSignature {
                    vars: vec![rc_output_info.clone(), OutputVarInfo {
                        ty: gas_builtin_type.clone(),
                        ref_info: OutputVarReferenceInfo::NewTempVar { idx: 0 },
                    }],
                    ap_change: SierraApChange::Known { new_vars_only: false },
                },
                // Failure:
                BranchSignature {
                    vars: vec![rc_output_info, OutputVarInfo {
                        ty: gas_builtin_type,
                        ref_info: OutputVarReferenceInfo::SameAsParam { param_idx: 1 },
                    }],
                    ap_change: SierraApChange::Known { new_vars_only: false },
                },
            ],
            fallthrough: Some(0),
        })
    }
}

/// Libfunc for getting the pointer to the gas cost array.
/// See [BuiltinCostsType].
#[derive(Default)]
pub struct BuiltinCostGetBuiltinCostsLibfunc {}

impl NoGenericArgsGenericLibfunc for BuiltinCostGetBuiltinCostsLibfunc {
    const STR_ID: &'static str = "get_builtin_costs";

    fn specialize_signature(
        &self,
        context: &dyn SignatureSpecializationContext,
    ) -> Result<LibfuncSignature, SpecializationError> {
        let builtin_costs_type = context.get_concrete_type(BuiltinCostsType::id(), &[])?;
        Ok(LibfuncSignature::new_non_branch(
            vec![],
            vec![OutputVarInfo {
                ty: builtin_costs_type,
                ref_info: OutputVarReferenceInfo::Deferred(DeferredOutputKind::Generic),
            }],
            SierraApChange::Known { new_vars_only: false },
        ))
    }
}