Skip to main content

iota_types/
gas.rs

1// Copyright (c) 2021, Facebook, Inc. and its affiliates
2// Copyright (c) Mysten Labs, Inc.
3// Modifications Copyright (c) 2024 IOTA Stiftung
4// SPDX-License-Identifier: Apache-2.0
5
6pub use checked::*;
7
8#[iota_macros::with_checked_arithmetic]
9pub mod checked {
10
11    use std::collections::HashMap;
12
13    use enum_dispatch::enum_dispatch;
14    use iota_protocol_config::ProtocolConfig;
15    use iota_sdk_types::{GasCostSummary, GasPayment, ObjectReference, Transaction};
16
17    use crate::{
18        ObjectId,
19        error::{ExecutionError, IotaResult, UserInputError, UserInputResult},
20        gas_model::{
21            gas_v1::{IotaGasStatus as IotaGasStatusV1, min_transaction_cost},
22            tables::GasStatus,
23        },
24        object::{MoveStructExt, Object},
25        transaction::{InputObjects, ObjectReadResult, TransactionAPI},
26    };
27
28    #[enum_dispatch]
29    pub trait IotaGasStatusAPI {
30        fn is_unmetered(&self) -> bool;
31        fn move_gas_status(&self) -> &GasStatus;
32        fn move_gas_status_mut(&mut self) -> &mut GasStatus;
33        fn bucketize_computation(&mut self) -> Result<(), ExecutionError>;
34        fn summary(&self) -> GasCostSummary;
35        fn gas_budget(&self) -> u64;
36        fn gas_price(&self) -> u64;
37        fn reference_gas_price(&self) -> u64;
38        fn storage_gas_units(&self) -> u64;
39        fn storage_rebate(&self) -> u64;
40        fn unmetered_storage_rebate(&self) -> u64;
41        fn gas_used(&self) -> u64;
42        fn reset_storage_cost_and_rebate(&mut self);
43        fn charge_storage_read(&mut self, size: usize) -> Result<(), ExecutionError>;
44        fn charge_publish_package(&mut self, size: usize) -> Result<(), ExecutionError>;
45        fn track_storage_mutation(
46            &mut self,
47            object_id: ObjectId,
48            new_size: usize,
49            storage_rebate: u64,
50        ) -> u64;
51        fn charge_storage_and_rebate(&mut self) -> Result<(), ExecutionError>;
52        fn adjust_computation_on_out_of_gas(&mut self);
53    }
54
55    /// Version aware enum for gas status.
56    #[enum_dispatch(IotaGasStatusAPI)]
57    #[derive(Debug)]
58    pub enum IotaGasStatus {
59        V1(IotaGasStatusV1),
60    }
61
62    impl IotaGasStatus {
63        pub fn new(
64            gas_budget: u64,
65            gas_price: u64,
66            reference_gas_price: u64,
67            config: &ProtocolConfig,
68        ) -> IotaResult<Self> {
69            check_gas_price_bounds(gas_price, reference_gas_price, config)?;
70
71            Ok(Self::V1(IotaGasStatusV1::new_with_budget(
72                gas_budget,
73                gas_price,
74                reference_gas_price,
75                config,
76            )))
77        }
78
79        pub fn new_unmetered() -> Self {
80            // Always return V1 as unmetered gas status is identical from V1 to V2.
81            // This is only used for system transactions which do not pay gas.
82            Self::V1(IotaGasStatusV1::new_unmetered())
83        }
84
85        // This is the only public API on IotaGasStatus, all other gas related
86        // operations should go through `GasCharger`
87        //
88        // `bounded_budget` selects whether the budget itself must fall between the
89        // protocol minimum and maximum. The gas coins are required to be
90        // address-owned and to cover the budget either way.
91        pub fn check_gas_balance(
92            &self,
93            gas_objs: &[&ObjectReadResult],
94            gas_budget: u64,
95            bounded_budget: bool,
96        ) -> UserInputResult {
97            match self {
98                Self::V1(status) => status.check_gas_balance(gas_objs, gas_budget, bounded_budget),
99            }
100        }
101    }
102
103    /// Validates the transaction's declared gas price and budget against the
104    /// epoch reference gas price and the protocol config bounds.
105    ///
106    /// Payload-only: reads no objects and no frontier state, so it is safe to
107    /// run post-consensus before version assignment. Shares the price checks
108    /// with `IotaGasStatus::new` and the budget-bound checks with
109    /// `IotaGasStatusV1::check_gas_balance`, without touching gas coins.
110    pub fn check_gas_bounds(
111        config: &ProtocolConfig,
112        reference_gas_price: u64,
113        gas_price: u64,
114        gas_budget: u64,
115    ) -> UserInputResult<()> {
116        check_gas_price_bounds(gas_price, reference_gas_price, config)?;
117        check_gas_budget_bounds(
118            gas_budget,
119            min_transaction_cost(config, gas_price),
120            config.max_tx_gas(),
121        )
122    }
123
124    /// Checks the declared gas price against the epoch reference gas price and
125    /// the protocol config maximum.
126    pub(crate) fn check_gas_price_bounds(
127        gas_price: u64,
128        reference_gas_price: u64,
129        config: &ProtocolConfig,
130    ) -> UserInputResult<()> {
131        if gas_price < reference_gas_price {
132            return Err(UserInputError::GasPriceUnderRGP {
133                gas_price,
134                reference_gas_price,
135            });
136        }
137        if gas_price > config.max_gas_price() {
138            return Err(UserInputError::GasPriceTooHigh {
139                max_gas_price: config.max_gas_price(),
140            });
141        }
142        Ok(())
143    }
144
145    /// Checks the declared gas budget against the given bounds.
146    pub(crate) fn check_gas_budget_bounds(
147        gas_budget: u64,
148        min_budget: u64,
149        max_budget: u64,
150    ) -> UserInputResult<()> {
151        if gas_budget > max_budget {
152            return Err(UserInputError::GasBudgetTooHigh {
153                gas_budget,
154                max_budget,
155            });
156        }
157        if gas_budget < min_budget {
158            return Err(UserInputError::GasBudgetTooLow {
159                gas_budget,
160                min_budget,
161            });
162        }
163        Ok(())
164    }
165
166    // Helper functions to deal with gas coins operations.
167
168    pub fn deduct_gas(gas_object: &mut Object, charge_or_rebate: i64) {
169        // The object must be a gas coin as we have checked in transaction handle phase.
170        let gas_coin = gas_object.data.as_opt_mut_struct().unwrap();
171        let balance = gas_coin.get_coin_value_unchecked();
172        let new_balance = if charge_or_rebate < 0 {
173            balance + (-charge_or_rebate as u64)
174        } else {
175            assert!(balance >= charge_or_rebate as u64);
176            balance - charge_or_rebate as u64
177        };
178        gas_coin.set_coin_value_unchecked(new_balance)
179    }
180
181    pub fn get_gas_balance(gas_object: &Object) -> UserInputResult<u64> {
182        if let Some(move_obj) = gas_object.data.as_opt_struct() {
183            if !move_obj.struct_tag().is_gas_coin() {
184                return Err(UserInputError::InvalidGasObject {
185                    object_id: gas_object.id(),
186                });
187            }
188            Ok(move_obj.get_coin_value_unchecked())
189        } else {
190            Err(UserInputError::InvalidGasObject {
191                object_id: gas_object.id(),
192            })
193        }
194    }
195
196    /// Fills in the gas a simulated transaction leaves unset: a zero price
197    /// becomes `reference_gas_price`, and a zero budget as much as the gas
198    /// coins can back, up to the protocol maximum.
199    pub fn fill_in_unset_simulation_gas(
200        transaction: &mut Transaction,
201        input_objects: &InputObjects,
202        reference_gas_price: u64,
203        protocol_config: &ProtocolConfig,
204    ) {
205        if transaction.gas_price() == 0 {
206            transaction.gas_data_mut().price = reference_gas_price;
207        }
208        if transaction.gas_budget() == 0 {
209            let min_gas_budget = protocol_config
210                .base_tx_cost_fixed()
211                .saturating_mul(transaction.gas_price());
212
213            // The gas budget is capped at the gas coins' combined balance rather than left
214            // at the protocol maximum, so that coins holding less than `max_tx_gas`
215            // still produce an estimate instead of being rejected for not covering a
216            // budget the caller never asked for.
217            let gas_balance = gas_coins_balance(input_objects, transaction.gas());
218
219            // The cap is raised back to the minimum budget a transaction may declare
220            // when the balance falls below it, so a balance too small to transact at
221            // all is still reported against the balance by the gas checks, rather than
222            // against a budget the caller never set.
223            let budget = std::cmp::min(protocol_config.max_tx_gas() as u128, gas_balance)
224                .max(min_gas_budget as u128);
225
226            transaction.gas_data_mut().budget = budget as u64;
227        }
228    }
229
230    /// Sums the balance of the gas coins `gas` refers to among `input_objects`
231    /// and skips all non-gas coins.
232    fn gas_coins_balance(input_objects: &InputObjects, gas: &[ObjectReference]) -> u128 {
233        let objects: HashMap<_, _> = input_objects
234            .iter()
235            .map(|object| (object.id(), object))
236            .collect();
237
238        gas.iter()
239            .filter_map(|gas_ref| objects.get(&gas_ref.object_id)?.as_object())
240            .filter_map(|object| get_gas_balance(object).ok())
241            .map(u128::from)
242            .sum()
243    }
244
245    /// Reports the gas a simulation ran with in `reported`, in place of what
246    /// the caller left unset — the mirror of [`fill_in_unset_simulation_gas`],
247    /// for the response rather than the run.
248    ///
249    /// A zero budget asks what the transaction costs, so it comes back as
250    /// `gas_used` rather than as the caller's own zero, which would say
251    /// nothing.
252    ///
253    /// Note what that costs: `gas_used` is not the budget the run
254    /// metered against, so a transaction reported this way does not hash to the
255    /// digest the effects are keyed by.
256    pub fn report_simulation_gas(reported: &mut GasPayment, simulated: &GasPayment, gas_used: u64) {
257        let estimating = reported.budget == 0;
258        *reported = simulated.clone();
259        if estimating {
260            reported.budget = gas_used;
261        }
262    }
263}
264
265#[cfg(test)]
266#[path = "unit_tests/gas_tests.rs"]
267mod gas_tests;