Skip to main content

sui_types/gas_model/
gas_v2.rs

1// Copyright (c) 2021, Facebook, Inc. and its affiliates
2// Copyright (c) Mysten Labs, Inc.
3// SPDX-License-Identifier: Apache-2.0
4
5pub use checked::*;
6
7#[sui_macros::with_checked_arithmetic]
8mod checked {
9    use crate::gas::{GasCostSummary, GasUsageReport, SuiGasStatusAPI};
10    pub use crate::gas_model::gas_common::PerObjectStorage;
11    use crate::gas_model::gas_common::{StorageGas, half_digits_rounding, sender_rebate};
12    use crate::gas_model::gas_predicates::cost_table_for_version;
13    use crate::gas_model::units_types::CostTable;
14    use crate::{
15        ObjectID,
16        error::ExecutionError,
17        execution_status::ExecutionErrorKind,
18        gas_model::tables::{GasStatus, ZERO_COST_SCHEDULE},
19    };
20    use move_core_types::vm_status::StatusCode;
21    use sui_protocol_config::*;
22
23    /// A bucket defines a range of units that will be priced the same.
24    /// After execution a call to `GasStatus::bucketize` will round the computation
25    /// cost to `cost` for the bucket ([`min`, `max`]) the gas used falls into.
26    #[allow(dead_code)]
27    pub(crate) struct ComputationBucket {
28        min: u64,
29        max: u64,
30        cost: u64,
31    }
32
33    impl ComputationBucket {
34        fn new(min: u64, max: u64, cost: u64) -> Self {
35            ComputationBucket { min, max, cost }
36        }
37
38        fn simple(min: u64, max: u64) -> Self {
39            Self::new(min, max, max)
40        }
41    }
42
43    fn get_bucket_cost(table: &[ComputationBucket], computation_cost: u64) -> u64 {
44        for bucket in table {
45            if bucket.max >= computation_cost {
46                return bucket.cost;
47            }
48        }
49        match table.last() {
50            // maybe not a literal here could be better?
51            None => 5_000_000,
52            Some(bucket) => bucket.cost,
53        }
54    }
55
56    // define the bucket table for computation charging
57    // If versioning defines multiple functions and
58    fn computation_bucket(max_bucket_cost: u64) -> Vec<ComputationBucket> {
59        assert!(max_bucket_cost >= 5_000_000);
60        vec![
61            ComputationBucket::simple(0, 1_000),
62            ComputationBucket::simple(1_000, 5_000),
63            ComputationBucket::simple(5_000, 10_000),
64            ComputationBucket::simple(10_000, 20_000),
65            ComputationBucket::simple(20_000, 50_000),
66            ComputationBucket::simple(50_000, 200_000),
67            ComputationBucket::simple(200_000, 1_000_000),
68            ComputationBucket::simple(1_000_000, max_bucket_cost),
69        ]
70    }
71
72    /// A list of constant costs of various operations in Sui.
73    pub struct SuiCostTable {
74        /// Computation cost per byte charged for package publish. This cost is primarily
75        /// determined by the cost to verify and link a package. Note that this does not
76        /// include the cost of writing the package to the store.
77        package_publish_per_byte_cost: u64,
78        /// Per byte cost to read objects from the store. This is computation cost instead of
79        /// storage cost because it does not change the amount of data stored on the db.
80        object_read_per_byte_cost: u64,
81        /// Unit cost of a byte in the storage. This will be used both for charging for
82        /// new storage as well as rebating for deleting storage. That is, we expect users to
83        /// get full refund on the object storage when it's deleted.
84        storage_per_byte_cost: u64,
85        /// Execution cost table to be used.
86        pub execution_cost_table: CostTable,
87        /// Computation buckets to cost transaction in price groups
88        computation_bucket: Vec<ComputationBucket>,
89        /// Max gas price for aborted transactions.
90        max_gas_price_rgp_factor_for_aborted_transactions: Option<u64>,
91    }
92
93    impl std::fmt::Debug for SuiCostTable {
94        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95            // TODO: dump the fields.
96            write!(f, "SuiCostTable(...)")
97        }
98    }
99
100    impl SuiCostTable {
101        pub(crate) fn new(c: &ProtocolConfig) -> Self {
102            Self {
103                package_publish_per_byte_cost: c.package_publish_cost_per_byte(),
104                object_read_per_byte_cost: c.obj_access_cost_read_per_byte(),
105                storage_per_byte_cost: c.obj_data_cost_refundable(),
106                execution_cost_table: cost_table_for_version(c.gas_model_version()),
107                computation_bucket: computation_bucket(c.max_gas_computation_bucket()),
108                max_gas_price_rgp_factor_for_aborted_transactions: c
109                    .max_gas_price_rgp_factor_for_aborted_transactions_as_option(),
110            }
111        }
112
113        pub(crate) fn unmetered() -> Self {
114            Self {
115                package_publish_per_byte_cost: 0,
116                object_read_per_byte_cost: 0,
117                storage_per_byte_cost: 0,
118                execution_cost_table: ZERO_COST_SCHEDULE.clone(),
119                // should not matter
120                computation_bucket: computation_bucket(5_000_000),
121                max_gas_price_rgp_factor_for_aborted_transactions: None,
122            }
123        }
124    }
125
126    #[derive(Debug, Clone, Copy)]
127    enum GasRoundingMode {
128        /// Bucketize the computation cost according to predefined buckets.
129        Bucketize,
130        /// Rounding value to round up gas charges.
131        Stepped(u64),
132        /// Round by keeping just over half digits
133        KeepHalfDigits,
134    }
135
136    #[allow(dead_code)]
137    #[derive(Debug)]
138    pub struct SuiGasStatus {
139        // GasStatus as used by the VM, that is all the VM sees
140        pub gas_status: GasStatus,
141        // Cost table contains a set of constant/config for the gas model/charging
142        cost_table: SuiCostTable,
143        // Gas budget for this gas status instance.
144        // Typically the gas budget as defined in the `TransactionData::GasData`
145        gas_budget: u64,
146        // Computation cost after execution. This is the result of the gas used by the `GasStatus`
147        // properly bucketized.
148        // Starts at 0 and it is assigned in `bucketize_computation`.
149        computation_cost: u64,
150        // Whether to charge or go unmetered
151        charge: bool,
152        // Gas price for computation.
153        // This is a multiplier on the final charge as related to the RGP (reference gas price).
154        // Checked at signing: `gas_price >= reference_gas_price`
155        // and then conceptually
156        // `final_computation_cost = total_computation_cost * gas_price / reference_gas_price`
157        gas_price: u64,
158        // RGP as defined in the protocol config.
159        reference_gas_price: u64,
160        // storage rebate rate as defined in the ProtocolConfig
161        rebate_rate: u64,
162        /// Per-object storage accounting (accumulated costs/rebates + the storage config it needs),
163        /// shared with gas_v3 via `gas_common::StorageGas`.
164        storage: StorageGas,
165        /// Rounding mode for gas charges.
166        gas_rounding_mode: GasRoundingMode,
167    }
168
169    impl SuiGasStatus {
170        fn new(
171            move_gas_status: GasStatus,
172            gas_budget: u64,
173            charge: bool,
174            gas_price: u64,
175            reference_gas_price: u64,
176            storage_gas_price: u64,
177            rebate_rate: u64,
178            gas_rounding_mode: GasRoundingMode,
179            cost_table: SuiCostTable,
180        ) -> SuiGasStatus {
181            let gas_rounding_mode = match gas_rounding_mode {
182                GasRoundingMode::Bucketize => GasRoundingMode::Bucketize,
183                GasRoundingMode::Stepped(val) => GasRoundingMode::Stepped(val.max(1)),
184                GasRoundingMode::KeepHalfDigits => GasRoundingMode::KeepHalfDigits,
185            };
186            SuiGasStatus {
187                gas_status: move_gas_status,
188                gas_budget,
189                charge,
190                computation_cost: 0,
191                gas_price,
192                reference_gas_price,
193                rebate_rate,
194                storage: StorageGas::new(storage_gas_price, cost_table.storage_per_byte_cost),
195                gas_rounding_mode,
196                cost_table,
197            }
198        }
199
200        pub(crate) fn new_with_budget(
201            gas_budget: u64,
202            gas_price: u64,
203            reference_gas_price: u64,
204            config: &ProtocolConfig,
205        ) -> SuiGasStatus {
206            let storage_gas_price = config.storage_gas_price();
207            let max_computation_budget = config.max_gas_computation_bucket() * gas_price;
208            let computation_budget = if gas_budget > max_computation_budget {
209                max_computation_budget
210            } else {
211                gas_budget
212            };
213            let sui_cost_table = SuiCostTable::new(config);
214            let gas_rounding_mode = if config.gas_rounding_halve_digits() {
215                GasRoundingMode::KeepHalfDigits
216            } else if let Some(step) = config.gas_rounding_step_as_option() {
217                GasRoundingMode::Stepped(step)
218            } else {
219                GasRoundingMode::Bucketize
220            };
221            Self::new(
222                GasStatus::new(
223                    sui_cost_table.execution_cost_table.clone(),
224                    computation_budget,
225                    gas_price,
226                    config.gas_model_version(),
227                ),
228                gas_budget,
229                true,
230                gas_price,
231                reference_gas_price,
232                storage_gas_price,
233                config.storage_rebate_rate(),
234                gas_rounding_mode,
235                sui_cost_table,
236            )
237        }
238
239        pub fn new_unmetered() -> SuiGasStatus {
240            Self::new(
241                GasStatus::new_unmetered(),
242                0,
243                false,
244                0,
245                0,
246                0,
247                0,
248                GasRoundingMode::Bucketize,
249                SuiCostTable::unmetered(),
250            )
251        }
252
253        pub fn reference_gas_price(&self) -> u64 {
254            self.reference_gas_price
255        }
256
257        fn storage_cost(&self) -> u64 {
258            self.storage_gas_units()
259        }
260    }
261
262    impl SuiGasStatusAPI for SuiGasStatus {
263        fn is_unmetered(&self) -> bool {
264            !self.charge
265        }
266
267        fn move_gas_status(&self) -> &GasStatus {
268            &self.gas_status
269        }
270
271        fn move_gas_status_mut(&mut self) -> &mut GasStatus {
272            &mut self.gas_status
273        }
274
275        fn bucketize_computation(&mut self, aborted: Option<bool>) -> Result<(), ExecutionError> {
276            let gas_used = self.gas_status.gas_used_pre_gas_price();
277            let effective_gas_price = if let Some(max_gas_price_rgp_factor_for_aborted_transactions) =
278                self.cost_table
279                    .max_gas_price_rgp_factor_for_aborted_transactions
280                && aborted.unwrap_or(false)
281            {
282                // For aborts, cap at max but don't exceed user's price
283                // This minimizes the risk of competing for priority execution in the case that the txn may be aborted.
284                let max_gas_price_for_aborted_txns =
285                    max_gas_price_rgp_factor_for_aborted_transactions * self.reference_gas_price;
286                self.gas_price.min(max_gas_price_for_aborted_txns)
287            } else {
288                // For all other cases, use the user's gas price
289                self.gas_price
290            };
291            let gas_used = match self.gas_rounding_mode {
292                GasRoundingMode::KeepHalfDigits => {
293                    half_digits_rounding(gas_used) * effective_gas_price
294                }
295                GasRoundingMode::Stepped(gas_rounding) => {
296                    if gas_used > 0 && gas_used % gas_rounding == 0 {
297                        gas_used * effective_gas_price
298                    } else {
299                        ((gas_used / gas_rounding) + 1) * gas_rounding * effective_gas_price
300                    }
301                }
302                GasRoundingMode::Bucketize => {
303                    let bucket_cost =
304                        get_bucket_cost(&self.cost_table.computation_bucket, gas_used);
305                    // charge extra on top of `computation_cost` to make the total computation
306                    // cost a bucket value
307                    bucket_cost * effective_gas_price
308                }
309            };
310            if self.gas_budget <= gas_used {
311                self.computation_cost = self.gas_budget;
312                Err(ExecutionErrorKind::InsufficientGas.into())
313            } else {
314                self.computation_cost = gas_used;
315                Ok(())
316            }
317        }
318
319        /// Returns the final (computation cost, storage cost, storage rebate) of the gas meter.
320        /// We use initial budget, combined with remaining gas and storage cost to derive
321        /// computation cost.
322        fn summary(&self) -> GasCostSummary {
323            // compute storage rebate, both rebate and non refundable fee
324            let storage_rebate = self.storage_rebate();
325            let sender_rebate = sender_rebate(storage_rebate, self.rebate_rate);
326            assert!(sender_rebate <= storage_rebate);
327            let non_refundable_storage_fee = storage_rebate - sender_rebate;
328            GasCostSummary {
329                computation_cost: self.computation_cost,
330                storage_cost: self.storage_cost(),
331                storage_rebate: sender_rebate,
332                non_refundable_storage_fee,
333            }
334        }
335
336        fn gas_budget(&self) -> u64 {
337            self.gas_budget
338        }
339
340        fn gas_price(&self) -> u64 {
341            self.gas_price
342        }
343
344        fn reference_gas_price(&self) -> u64 {
345            self.reference_gas_price
346        }
347
348        fn storage_gas_units(&self) -> u64 {
349            self.storage.storage_gas_units()
350        }
351
352        fn storage_rebate(&self) -> u64 {
353            self.storage.storage_rebate()
354        }
355
356        fn unmetered_storage_rebate(&self) -> u64 {
357            self.storage.unmetered_storage_rebate()
358        }
359
360        fn gas_used(&self) -> u64 {
361            self.gas_status.gas_used_pre_gas_price()
362        }
363
364        fn reset_storage_cost_and_rebate(&mut self) {
365            self.storage.reset();
366        }
367
368        fn charge_storage_read(&mut self, size: usize) -> Result<(), ExecutionError> {
369            self.gas_status
370                .charge_bytes(size, self.cost_table.object_read_per_byte_cost)
371                .map_err(|e| {
372                    debug_assert_eq!(e.major_status(), StatusCode::OUT_OF_GAS);
373                    ExecutionErrorKind::InsufficientGas.into()
374                })
375        }
376
377        fn charge_publish_package(&mut self, size: usize) -> Result<(), ExecutionError> {
378            self.gas_status
379                .charge_bytes(size, self.cost_table.package_publish_per_byte_cost)
380                .map_err(|e| {
381                    debug_assert_eq!(e.major_status(), StatusCode::OUT_OF_GAS);
382                    ExecutionErrorKind::InsufficientGas.into()
383                })
384        }
385
386        /// Update `storage_rebate` and `storage_gas_units` for each object in the transaction.
387        /// There is no charge in this function. Charges will all be applied together at the end
388        /// (`track_storage_mutation`).
389        /// Return the new storage rebate (cost of object storage) according to `new_size`.
390        fn track_storage_mutation(
391            &mut self,
392            object_id: ObjectID,
393            new_size: usize,
394            storage_rebate: u64,
395        ) -> Option<u64> {
396            let unmetered = self.is_unmetered();
397            self.storage
398                .track_mutation(object_id, new_size, storage_rebate, unmetered)
399        }
400
401        fn charge_storage_and_rebate(&mut self) -> Result<(), ExecutionError> {
402            let storage_rebate = self.storage_rebate();
403            let storage_cost = self.storage_cost();
404            let sender_rebate = sender_rebate(storage_rebate, self.rebate_rate);
405            assert!(sender_rebate <= storage_rebate);
406            if sender_rebate >= storage_cost {
407                // there is more rebate than cost, when deducting gas we are adding
408                // to whatever is the current amount charged so we are `Ok`
409                Ok(())
410            } else {
411                let gas_left = self.gas_budget - self.computation_cost;
412                // we have to charge for storage and may go out of gas, check
413                if gas_left < storage_cost - sender_rebate {
414                    // Running out of gas would cause the temporary store to reset
415                    // and zero storage and rebate.
416                    // The remaining_gas will be 0 and we will charge all in computation
417                    Err(ExecutionErrorKind::InsufficientGas.into())
418                } else {
419                    Ok(())
420                }
421            }
422        }
423
424        fn adjust_computation_on_out_of_gas(&mut self) {
425            self.storage.reset();
426            self.computation_cost = self.gas_budget;
427        }
428
429        fn gas_usage_report(&self) -> GasUsageReport {
430            GasUsageReport {
431                cost_summary: self.summary(),
432                gas_used: self.gas_used(),
433                gas_price: self.gas_price(),
434                reference_gas_price: self.reference_gas_price(),
435                per_object_storage: self.per_object_storage().clone(),
436                gas_budget: self.gas_budget(),
437                storage_gas_price: self.storage.storage_gas_price,
438                rebate_rate: self.rebate_rate,
439            }
440        }
441
442        fn per_object_storage(&self) -> &Vec<(ObjectID, PerObjectStorage)> {
443            self.storage.per_object_storage()
444        }
445    }
446}