Skip to main content

sui_types/gas_model/
gas_v3.rs

1// Copyright (c) 2021, Facebook, Inc. and its affiliates
2// Copyright (c) Mysten Labs, Inc.
3// SPDX-License-Identifier: Apache-2.0
4
5#![deny(clippy::arithmetic_side_effects)]
6#![deny(clippy::cast_possible_truncation)]
7#![deny(clippy::indexing_slicing)]
8#![deny(clippy::cast_possible_wrap)]
9#![deny(clippy::cast_sign_loss)]
10
11use crate::gas::{GasCostSummary, GasUsageReport, SuiGasStatusAPI};
12use crate::gas_model::gas_common::{
13    StorageGas, half_digits_rounding, package_read_internal_gas, sender_rebate,
14};
15use crate::gas_model::gas_predicates::cost_table_for_version;
16use crate::gas_model::units_types::CostTable;
17use crate::{
18    ObjectID,
19    error::ExecutionError,
20    execution_status::ExecutionErrorKind,
21    gas_model::tables::{GasStatus, ZERO_COST_SCHEDULE},
22};
23use move_core_types::gas_algebra::InternalGas;
24use move_core_types::vm_status::StatusCode;
25use sui_protocol_config::*;
26
27/// A list of constant costs of various operations in Sui.
28pub struct SuiCostTable {
29    /// Computation cost per byte charged for package publish.
30    package_publish_per_byte_cost: u64,
31    /// Per byte cost to read objects from the store.
32    object_read_per_byte_cost: u64,
33    /// Cost per KiB to read package inputs, or `None` to charge them the object rate.
34    package_read_per_kb_cost: Option<u64>,
35    /// Unit cost of a byte in the storage.
36    storage_per_byte_cost: u64,
37    /// Execution cost table to be used.
38    pub execution_cost_table: CostTable,
39    /// RGP-multiplier cap on the effective gas price for aborted transactions.
40    max_gas_price_rgp_factor_for_aborted_transactions: Option<u64>,
41}
42
43impl std::fmt::Debug for SuiCostTable {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        // TODO: dump the fields.
46        write!(f, "SuiCostTable(...)")
47    }
48}
49
50impl SuiCostTable {
51    pub(crate) fn new(c: &ProtocolConfig) -> Self {
52        Self {
53            package_publish_per_byte_cost: c.package_publish_cost_per_byte(),
54            object_read_per_byte_cost: c.obj_access_cost_read_per_byte(),
55            package_read_per_kb_cost: c.obj_access_cost_read_per_package_kb_as_option(),
56            storage_per_byte_cost: c.obj_data_cost_refundable(),
57            execution_cost_table: cost_table_for_version(c.gas_model_version()),
58            max_gas_price_rgp_factor_for_aborted_transactions: c
59                .max_gas_price_rgp_factor_for_aborted_transactions_as_option(),
60        }
61    }
62
63    pub(crate) fn unmetered() -> Self {
64        Self {
65            package_publish_per_byte_cost: 0,
66            object_read_per_byte_cost: 0,
67            package_read_per_kb_cost: None,
68            storage_per_byte_cost: 0,
69            execution_cost_table: ZERO_COST_SCHEDULE.clone(),
70            max_gas_price_rgp_factor_for_aborted_transactions: None,
71        }
72    }
73}
74
75pub use crate::gas_model::gas_common::PerObjectStorage;
76
77#[allow(dead_code)]
78#[derive(Debug)]
79pub struct SuiGasStatus {
80    // GasStatus as used by the VM, that is all the VM sees
81    pub gas_status: GasStatus,
82    // Cost table contains a set of constant/config for the gas model/charging
83    cost_table: SuiCostTable,
84    // Gas budget for this gas status instance.
85    gas_budget: u64,
86    // Whether to charge or go unmetered
87    charge: bool,
88    // Price used to convert gas units to MIST; starts at `user_gas_price`, lowered to the abort cap
89    // by `bucketize_computation` on a Move abort.
90    effective_gas_price: u64,
91    // The gas price the user signed for (>= reference_gas_price).
92    user_gas_price: u64,
93    // RGP as defined in the protocol config.
94    reference_gas_price: u64,
95    // storage rebate rate as defined in the ProtocolConfig
96    rebate_rate: u64,
97    /// Per-object storage accounting .
98    storage: StorageGas,
99    /// When set, computation cost is reported as exactly `gas_budget`.
100    force_computation_cost_to_budget: bool,
101}
102
103impl SuiGasStatus {
104    pub(crate) fn charge_package_object_read(&mut self, size: usize) -> Result<(), ExecutionError> {
105        if let Some(cost_per_kb) = self.cost_table.package_read_per_kb_cost {
106            self.gas_status
107                .deduct_gas(InternalGas::new(package_read_internal_gas(
108                    size,
109                    cost_per_kb,
110                )))
111                .map_err(|e| {
112                    debug_assert_eq!(e.major_status(), StatusCode::OUT_OF_GAS);
113                    ExecutionErrorKind::InsufficientGas.into()
114                })
115        } else {
116            // Without a package rate, packages are charged exactly as other input objects.
117            self.charge_storage_read(size)
118        }
119    }
120
121    fn new(
122        move_gas_status: GasStatus,
123        gas_budget: u64,
124        charge: bool,
125        user_gas_price: u64,
126        reference_gas_price: u64,
127        storage_gas_price: u64,
128        rebate_rate: u64,
129        cost_table: SuiCostTable,
130    ) -> SuiGasStatus {
131        SuiGasStatus {
132            gas_status: move_gas_status,
133            gas_budget,
134            charge,
135            effective_gas_price: user_gas_price,
136            user_gas_price,
137            reference_gas_price,
138            rebate_rate,
139            storage: StorageGas::new(storage_gas_price, cost_table.storage_per_byte_cost),
140            cost_table,
141            force_computation_cost_to_budget: false,
142        }
143    }
144
145    pub(crate) fn new_with_budget(
146        gas_budget: u64,
147        gas_price: u64,
148        reference_gas_price: u64,
149        config: &ProtocolConfig,
150    ) -> SuiGasStatus {
151        let storage_gas_price = config.storage_gas_price();
152        let max_computation_budget = config
153            .max_gas_computation_bucket()
154            .checked_mul(gas_price)
155            .expect("computation budget cannot overflow: gas_price is bounded by max_gas_price");
156        let computation_budget = if gas_budget > max_computation_budget {
157            max_computation_budget
158        } else {
159            gas_budget
160        };
161        let sui_cost_table = SuiCostTable::new(config);
162        Self::new(
163            GasStatus::new(
164                sui_cost_table.execution_cost_table.clone(),
165                computation_budget,
166                gas_price,
167                config.gas_model_version(),
168            ),
169            gas_budget,
170            true,
171            gas_price,
172            reference_gas_price,
173            storage_gas_price,
174            config.storage_rebate_rate(),
175            sui_cost_table,
176        )
177    }
178
179    pub fn new_unmetered() -> SuiGasStatus {
180        Self::new(
181            GasStatus::new_unmetered(),
182            0,
183            false,
184            0,
185            0,
186            0,
187            0,
188            SuiCostTable::unmetered(),
189        )
190    }
191
192    pub fn reference_gas_price(&self) -> u64 {
193        self.reference_gas_price
194    }
195
196    /// Meter-derived computation cost in MIST (bucketed units * effective_gas_price).
197    fn uncapped_computation_cost(&self) -> u64 {
198        if self.force_computation_cost_to_budget {
199            return self.gas_budget;
200        }
201        let raw_units = self.gas_status.gas_used_pre_gas_price();
202        let bucketed_units = half_digits_rounding(raw_units);
203        bucketed_units.saturating_mul(self.effective_gas_price)
204    }
205
206    /// Computation cost reported in `summary()`, capped so
207    /// `computation + storage_cost - sender_rebate <= gas_budget`
208    /// storage charges stick, computation absorbs whatever budget remains.
209    fn derived_computation_cost(&self) -> u64 {
210        let uncapped_cost = self.uncapped_computation_cost();
211        let storage_rebate = self.storage_rebate();
212        let sender_rebate = sender_rebate(storage_rebate, self.rebate_rate);
213        let net_storage = self.storage_cost().saturating_sub(sender_rebate);
214        let max_computation = self.gas_budget.saturating_sub(net_storage);
215        uncapped_cost.min(max_computation)
216    }
217
218    fn storage_cost(&self) -> u64 {
219        self.storage_gas_units()
220    }
221}
222
223impl SuiGasStatusAPI for SuiGasStatus {
224    fn is_unmetered(&self) -> bool {
225        !self.charge
226    }
227
228    fn move_gas_status(&self) -> &GasStatus {
229        &self.gas_status
230    }
231
232    fn move_gas_status_mut(&mut self) -> &mut GasStatus {
233        &mut self.gas_status
234    }
235
236    fn bucketize_computation(&mut self, aborted: Option<bool>) -> Result<(), ExecutionError> {
237        self.effective_gas_price = match self
238            .cost_table
239            .max_gas_price_rgp_factor_for_aborted_transactions
240        {
241            Some(factor) if aborted.unwrap_or(false) => {
242                let cap = factor
243                    .checked_mul(self.reference_gas_price)
244                    .ok_or_else(|| {
245                        ExecutionError::from_kind(ExecutionErrorKind::InvariantViolation)
246                    })?;
247                self.user_gas_price.min(cap)
248            }
249            _ => self.user_gas_price,
250        };
251        if self.uncapped_computation_cost() >= self.gas_budget {
252            return Err(ExecutionErrorKind::InsufficientGas.into());
253        }
254        Ok(())
255    }
256
257    /// Returns the gas cost summary for the transaction.
258    fn summary(&self) -> GasCostSummary {
259        let storage_rebate = self.storage_rebate();
260        let sender_rebate = sender_rebate(storage_rebate, self.rebate_rate);
261        let non_refundable_storage_fee = storage_rebate
262            .checked_sub(sender_rebate)
263            .expect("sender rebate must not exceed storage rebate");
264        GasCostSummary {
265            computation_cost: self.derived_computation_cost(),
266            storage_cost: self.storage_cost(),
267            storage_rebate: sender_rebate,
268            non_refundable_storage_fee,
269        }
270    }
271
272    fn gas_budget(&self) -> u64 {
273        self.gas_budget
274    }
275
276    fn gas_price(&self) -> u64 {
277        self.user_gas_price
278    }
279
280    fn reference_gas_price(&self) -> u64 {
281        self.reference_gas_price
282    }
283
284    fn storage_gas_units(&self) -> u64 {
285        self.storage.storage_gas_units()
286    }
287
288    fn storage_rebate(&self) -> u64 {
289        self.storage.storage_rebate()
290    }
291
292    fn unmetered_storage_rebate(&self) -> u64 {
293        self.storage.unmetered_storage_rebate()
294    }
295
296    fn gas_used(&self) -> u64 {
297        self.gas_status.gas_used_pre_gas_price()
298    }
299
300    fn reset_storage_cost_and_rebate(&mut self) {
301        self.storage.reset();
302    }
303
304    fn charge_storage_read(&mut self, size: usize) -> Result<(), ExecutionError> {
305        self.gas_status
306            .charge_bytes(size, self.cost_table.object_read_per_byte_cost)
307            .map_err(|e| {
308                debug_assert_eq!(e.major_status(), StatusCode::OUT_OF_GAS);
309                ExecutionErrorKind::InsufficientGas.into()
310            })
311    }
312
313    fn charge_publish_package(&mut self, size: usize) -> Result<(), ExecutionError> {
314        self.gas_status
315            .charge_bytes(size, self.cost_table.package_publish_per_byte_cost)
316            .map_err(|e| {
317                debug_assert_eq!(e.major_status(), StatusCode::OUT_OF_GAS);
318                ExecutionErrorKind::InsufficientGas.into()
319            })
320    }
321
322    /// Update `storage_rebate` and `storage_gas_units` for each object in the transaction.
323    /// Return the new storage rebate (cost of object storage) according to `new_size` or
324    /// `None` on arithmetic errors.
325    fn track_storage_mutation(
326        &mut self,
327        object_id: ObjectID,
328        new_size: usize,
329        storage_rebate: u64,
330    ) -> Option<u64> {
331        let unmetered = self.is_unmetered();
332        self.storage
333            .track_mutation(object_id, new_size, storage_rebate, unmetered)
334    }
335
336    fn charge_storage_and_rebate(&mut self) -> Result<(), ExecutionError> {
337        let storage_rebate = self.storage.storage_rebate();
338        let storage_cost = self.storage.storage_gas_units();
339        let sender_rebate = sender_rebate(storage_rebate, self.rebate_rate);
340        assert!(sender_rebate <= storage_rebate);
341        let net_storage_cost = storage_cost.saturating_sub(sender_rebate);
342        let gas_left = self
343            .gas_budget
344            .saturating_sub(self.uncapped_computation_cost());
345        if net_storage_cost > gas_left {
346            return Err(ExecutionErrorKind::InsufficientGas.into());
347        }
348        Ok(())
349    }
350
351    /// Drop accumulated storage and force `summary()` to report `computation_cost == gas_budget`
352    fn adjust_computation_on_out_of_gas(&mut self) {
353        self.storage.reset();
354        self.force_computation_cost_to_budget = true;
355    }
356
357    fn gas_usage_report(&self) -> GasUsageReport {
358        GasUsageReport {
359            cost_summary: self.summary(),
360            gas_used: self.gas_used(),
361            gas_price: self.gas_price(),
362            reference_gas_price: self.reference_gas_price(),
363            per_object_storage: self.per_object_storage().clone(),
364            gas_budget: self.gas_budget(),
365            storage_gas_price: self.storage.storage_gas_price,
366            rebate_rate: self.rebate_rate,
367        }
368    }
369
370    fn per_object_storage(&self) -> &Vec<(ObjectID, PerObjectStorage)> {
371        self.storage.per_object_storage()
372    }
373}