sui_adapter_v1/
gas_charger.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]
8pub mod checked {
9
10    use crate::sui_types::gas::SuiGasStatusAPI;
11    use crate::temporary_store::TemporaryStore;
12    use sui_protocol_config::ProtocolConfig;
13    use sui_types::gas::{deduct_gas, GasCostSummary, SuiGasStatus};
14    use sui_types::gas_model::gas_predicates::{
15        charge_upgrades, dont_charge_budget_on_storage_oog,
16    };
17    use sui_types::{
18        base_types::{ObjectID, ObjectRef},
19        digests::TransactionDigest,
20        error::ExecutionError,
21        gas_model::tables::GasStatus,
22        is_system_package,
23        object::Data,
24    };
25    use tracing::trace;
26
27    /// Tracks all gas operations for a single transaction.
28    /// This is the main entry point for gas accounting.
29    /// All the information about gas is stored in this object.
30    /// The objective here is two-fold:
31    /// 1- Isolate al version info into a single entry point. This file and the other gas
32    ///    related files are the only one that check for gas version.
33    /// 2- Isolate all gas accounting into a single implementation. Gas objects are not
34    ///    passed around, and they are retrieved from this instance.
35    #[derive(Debug)]
36    pub struct GasCharger {
37        tx_digest: TransactionDigest,
38        gas_model_version: u64,
39        gas_coins: Vec<ObjectRef>,
40        // this is the first gas coin in `gas_coins` and the one that all others will
41        // be smashed into. It can be None for system transactions when `gas_coins` is empty.
42        smashed_gas_coin: Option<ObjectID>,
43        gas_status: SuiGasStatus,
44    }
45
46    impl GasCharger {
47        pub fn new(
48            tx_digest: TransactionDigest,
49            gas_coins: Vec<ObjectRef>,
50            gas_status: SuiGasStatus,
51            protocol_config: &ProtocolConfig,
52        ) -> Self {
53            let gas_model_version = protocol_config.gas_model_version();
54            Self {
55                tx_digest,
56                gas_model_version,
57                gas_coins,
58                smashed_gas_coin: None,
59                gas_status,
60            }
61        }
62
63        pub fn new_unmetered(tx_digest: TransactionDigest) -> Self {
64            Self {
65                tx_digest,
66                gas_model_version: 6, // pick any of the latest, it should not matter
67                gas_coins: vec![],
68                smashed_gas_coin: None,
69                gas_status: SuiGasStatus::new_unmetered(),
70            }
71        }
72
73        // TODO: there is only one caller to this function that should not exist otherwise.
74        //       Explore way to remove it.
75        pub(crate) fn gas_coins(&self) -> &[ObjectRef] {
76            &self.gas_coins
77        }
78
79        // Return the logical gas coin for this transactions or None if no gas coin was present
80        // (system transactions).
81        pub fn gas_coin(&self) -> Option<ObjectID> {
82            self.smashed_gas_coin
83        }
84
85        pub fn gas_budget(&self) -> u64 {
86            self.gas_status.gas_budget()
87        }
88
89        pub fn unmetered_storage_rebate(&self) -> u64 {
90            self.gas_status.unmetered_storage_rebate()
91        }
92
93        pub fn no_charges(&self) -> bool {
94            self.gas_status.gas_used() == 0
95                && self.gas_status.storage_rebate() == 0
96                && self.gas_status.storage_gas_units() == 0
97        }
98
99        pub fn is_unmetered(&self) -> bool {
100            self.gas_status.is_unmetered()
101        }
102
103        pub fn move_gas_status(&self) -> &GasStatus {
104            self.gas_status.move_gas_status()
105        }
106
107        pub fn move_gas_status_mut(&mut self) -> &mut GasStatus {
108            self.gas_status.move_gas_status_mut()
109        }
110
111        pub fn into_gas_status(self) -> SuiGasStatus {
112            self.gas_status
113        }
114
115        pub fn summary(&self) -> GasCostSummary {
116            self.gas_status.summary()
117        }
118
119        // This function is called when the transaction is about to be executed.
120        // It will smash all gas coins into a single one and set the logical gas coin
121        // to be the first one in the list.
122        // After this call, `gas_coin` will return it id of the gas coin.
123        // This function panics if errors are found while operation on the gas coins.
124        // Transaction and certificate input checks must have insured that all gas coins
125        // are correct.
126        pub fn smash_gas(&mut self, temporary_store: &mut TemporaryStore<'_>) {
127            let gas_coin_count = self.gas_coins.len();
128            if gas_coin_count == 0 || (gas_coin_count == 1 && self.gas_coins[0].0 == ObjectID::ZERO)
129            {
130                return; // self.smashed_gas_coin is None
131            }
132            // set the first coin to be the transaction only gas coin.
133            // All others will be smashed into this one.
134            let gas_coin_id = self.gas_coins[0].0;
135            self.smashed_gas_coin = Some(gas_coin_id);
136            if gas_coin_count == 1 {
137                return;
138            }
139            // sum the value of all gas coins
140            let new_balance = self
141                .gas_coins
142                .iter()
143                .map(|obj_ref| {
144                    let obj = temporary_store.objects().get(&obj_ref.0).unwrap();
145                    let Data::Move(move_obj) = &obj.data else {
146                        return Err(ExecutionError::invariant_violation(
147                            "Provided non-gas coin object as input for gas!",
148                        ));
149                    };
150                    if !move_obj.type_().is_gas_coin() {
151                        return Err(ExecutionError::invariant_violation(
152                            "Provided non-gas coin object as input for gas!",
153                        ));
154                    }
155                    Ok(move_obj.get_coin_value_unsafe())
156                })
157                .collect::<Result<Vec<u64>, ExecutionError>>()
158                // transaction and certificate input checks must have insured that all gas coins
159                // are valid
160                .unwrap_or_else(|_| {
161                    panic!(
162                        "Invariant violation: non-gas coin object as input for gas in txn {}",
163                        self.tx_digest
164                    )
165                })
166                .iter()
167                .sum();
168            let mut primary_gas_object = temporary_store
169                .objects()
170                .get(&gas_coin_id)
171                // unwrap should be safe because we checked that this exists in `self.objects()` above
172                .unwrap_or_else(|| {
173                    panic!(
174                        "Invariant violation: gas coin not found in store in txn {}",
175                        self.tx_digest
176                    )
177                })
178                .clone();
179            // delete all gas objects except the primary_gas_object
180            for (id, _version, _digest) in &self.gas_coins[1..] {
181                debug_assert_ne!(*id, primary_gas_object.id());
182                temporary_store.delete_input_object(id);
183            }
184            primary_gas_object
185                .data
186                .try_as_move_mut()
187                // unwrap should be safe because we checked that the primary gas object was a coin object above.
188                .unwrap_or_else(|| {
189                    panic!(
190                        "Invariant violation: invalid coin object in txn {}",
191                        self.tx_digest
192                    )
193                })
194                .set_coin_value_unsafe(new_balance);
195            temporary_store.mutate_input_object(primary_gas_object);
196        }
197
198        //
199        // Gas charging operations
200        //
201
202        pub fn track_storage_mutation(
203            &mut self,
204            object_id: ObjectID,
205            new_size: usize,
206            storage_rebate: u64,
207        ) -> u64 {
208            self.gas_status
209                .track_storage_mutation(object_id, new_size, storage_rebate)
210        }
211
212        pub fn reset_storage_cost_and_rebate(&mut self) {
213            self.gas_status.reset_storage_cost_and_rebate();
214        }
215
216        pub fn charge_publish_package(&mut self, size: usize) -> Result<(), ExecutionError> {
217            self.gas_status.charge_publish_package(size)
218        }
219
220        pub fn charge_upgrade_package(&mut self, size: usize) -> Result<(), ExecutionError> {
221            if charge_upgrades(self.gas_model_version) {
222                self.gas_status.charge_publish_package(size)
223            } else {
224                Ok(())
225            }
226        }
227
228        pub fn charge_input_objects(
229            &mut self,
230            temporary_store: &TemporaryStore<'_>,
231        ) -> Result<(), ExecutionError> {
232            let objects = temporary_store.objects();
233            // TODO: Charge input object count.
234            let _object_count = objects.len();
235            // Charge bytes read
236            let total_size = temporary_store
237                .objects()
238                .iter()
239                // don't charge for loading Sui Framework or Move stdlib
240                .filter(|(id, _)| !is_system_package(**id))
241                .map(|(_, obj)| obj.object_size_for_gas_metering())
242                .sum();
243            self.gas_status.charge_storage_read(total_size)
244        }
245
246        /// Resets any mutations, deletions, and events recorded in the store, as well as any storage costs and
247        /// rebates, then Re-runs gas smashing. Effects on store are now as if we were about to begin execution
248        pub fn reset(&mut self, temporary_store: &mut TemporaryStore<'_>) {
249            temporary_store.drop_writes();
250            self.gas_status.reset_storage_cost_and_rebate();
251            self.smash_gas(temporary_store);
252        }
253
254        /// Entry point for gas charging.
255        /// 1. Compute tx storage gas costs and tx storage rebates, update storage_rebate field of
256        /// mutated objects
257        /// 2. Deduct computation gas costs and storage costs, credit storage rebates.
258        /// The happy path of this function follows (1) + (2) and is fairly simple.
259        /// Most of the complexity is in the unhappy paths:
260        /// - if execution aborted before calling this function, we have to dump all writes +
261        ///   re-smash gas, then charge for storage
262        /// - if we run out of gas while charging for storage, we have to dump all writes +
263        ///   re-smash gas, then charge for storage again
264        pub fn charge_gas<T>(
265            &mut self,
266            temporary_store: &mut TemporaryStore<'_>,
267            execution_result: &mut Result<T, ExecutionError>,
268        ) -> GasCostSummary {
269            // at this point, we have done *all* charging for computation,
270            // but have not yet set the storage rebate or storage gas units
271            debug_assert!(self.gas_status.storage_rebate() == 0);
272            debug_assert!(self.gas_status.storage_gas_units() == 0);
273
274            if self.smashed_gas_coin.is_some() {
275                // bucketize computation cost
276                if let Err(err) = self.gas_status.bucketize_computation(None) {
277                    if execution_result.is_ok() {
278                        *execution_result = Err(err);
279                    }
280                }
281
282                // On error we need to dump writes, deletes, etc before charging storage gas
283                if execution_result.is_err() {
284                    self.reset(temporary_store);
285                }
286            }
287
288            // compute and collect storage charges
289            temporary_store.ensure_active_inputs_mutated();
290            temporary_store.collect_storage_and_rebate(self);
291
292            if self.smashed_gas_coin.is_some() {
293                #[skip_checked_arithmetic]
294                trace!(target: "replay_gas_info", "Gas smashing has occurred for this transaction");
295            }
296
297            // system transactions (None smashed_gas_coin)  do not have gas and so do not charge
298            // for storage, however they track storage values to check for conservation rules
299            if let Some(gas_object_id) = self.smashed_gas_coin {
300                if dont_charge_budget_on_storage_oog(self.gas_model_version) {
301                    self.handle_storage_and_rebate_v2(temporary_store, execution_result)
302                } else {
303                    self.handle_storage_and_rebate_v1(temporary_store, execution_result)
304                }
305
306                let cost_summary = self.gas_status.summary();
307                let gas_used = cost_summary.net_gas_usage();
308
309                let mut gas_object = temporary_store.read_object(&gas_object_id).unwrap().clone();
310                deduct_gas(&mut gas_object, gas_used);
311                #[skip_checked_arithmetic]
312                trace!(gas_used, gas_obj_id =? gas_object.id(), gas_obj_ver =? gas_object.version(), "Updated gas object");
313
314                temporary_store.mutate_input_object(gas_object);
315                cost_summary
316            } else {
317                GasCostSummary::default()
318            }
319        }
320
321        fn handle_storage_and_rebate_v1<T>(
322            &mut self,
323            temporary_store: &mut TemporaryStore<'_>,
324            execution_result: &mut Result<T, ExecutionError>,
325        ) {
326            if let Err(err) = self.gas_status.charge_storage_and_rebate() {
327                self.reset(temporary_store);
328                self.gas_status.adjust_computation_on_out_of_gas();
329                temporary_store.ensure_active_inputs_mutated();
330                temporary_store.collect_rebate(self);
331                if execution_result.is_ok() {
332                    *execution_result = Err(err);
333                }
334            }
335        }
336
337        fn handle_storage_and_rebate_v2<T>(
338            &mut self,
339            temporary_store: &mut TemporaryStore<'_>,
340            execution_result: &mut Result<T, ExecutionError>,
341        ) {
342            if let Err(err) = self.gas_status.charge_storage_and_rebate() {
343                // we run out of gas charging storage, reset and try charging for storage again.
344                // Input objects are touched and so they have a storage cost
345                self.reset(temporary_store);
346                temporary_store.ensure_active_inputs_mutated();
347                temporary_store.collect_storage_and_rebate(self);
348                if let Err(err) = self.gas_status.charge_storage_and_rebate() {
349                    // we run out of gas attempting to charge for the input objects exclusively,
350                    // deal with this edge case by not charging for storage
351                    self.reset(temporary_store);
352                    self.gas_status.adjust_computation_on_out_of_gas();
353                    temporary_store.ensure_active_inputs_mutated();
354                    temporary_store.collect_rebate(self);
355                    if execution_result.is_ok() {
356                        *execution_result = Err(err);
357                    }
358                } else if execution_result.is_ok() {
359                    *execution_result = Err(err);
360                }
361            }
362        }
363    }
364}