iota_types/gas_model/gas_v1.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]
9mod checked {
10 use iota_protocol_config::*;
11 use iota_sdk_types::GasCostSummary;
12 use move_core_types::vm_status::StatusCode;
13
14 use crate::{
15 ObjectId,
16 error::{ExecutionError, ExecutionErrorKind, UserInputError, UserInputResult},
17 gas::{self, IotaGasStatusAPI},
18 gas_model::{
19 gas_predicates::cost_table_for_version,
20 tables::{GasStatus, ZERO_COST_SCHEDULE},
21 units_types::CostTable,
22 },
23 transaction::ObjectReadResult,
24 };
25
26 /// A bucket defines a range of units that will be priced the same.
27 /// After execution a call to `GasStatus::bucketize` will round the
28 /// computation cost to `cost` for the bucket ([`min`, `max`]) the gas
29 /// used falls into.
30 #[expect(dead_code)]
31 pub(crate) struct ComputationBucket {
32 min: u64,
33 max: u64,
34 cost: u64,
35 }
36
37 impl ComputationBucket {
38 fn new(min: u64, max: u64, cost: u64) -> Self {
39 ComputationBucket { min, max, cost }
40 }
41
42 fn simple(min: u64, max: u64) -> Self {
43 Self::new(min, max, max)
44 }
45 }
46
47 fn get_bucket_cost(table: &[ComputationBucket], computation_cost: u64) -> u64 {
48 for bucket in table {
49 if bucket.max >= computation_cost {
50 return bucket.cost;
51 }
52 }
53 match table.last() {
54 // maybe not a literal here could be better?
55 None => 5_000_000,
56 Some(bucket) => bucket.cost,
57 }
58 }
59
60 // define the bucket table for computation charging
61 // If versioning defines multiple functions and
62 fn computation_bucket(max_bucket_cost: u64) -> Vec<ComputationBucket> {
63 assert!(max_bucket_cost >= 5_000_000);
64 vec![
65 ComputationBucket::simple(0, 1_000),
66 ComputationBucket::simple(1_000, 5_000),
67 ComputationBucket::simple(5_000, 10_000),
68 ComputationBucket::simple(10_000, 20_000),
69 ComputationBucket::simple(20_000, 50_000),
70 ComputationBucket::simple(50_000, 200_000),
71 ComputationBucket::simple(200_000, 1_000_000),
72 ComputationBucket::simple(1_000_000, max_bucket_cost),
73 ]
74 }
75
76 /// Portion of the storage rebate that gets passed on to the transaction
77 /// sender. The remainder will be burned, then re-minted + added to the
78 /// storage fund at the next epoch change
79 fn sender_rebate(storage_rebate: u64, storage_rebate_rate: u64) -> u64 {
80 // we round storage rebate such that `>= x.5` goes to x+1 (rounds up) and
81 // `< x.5` goes to x (truncates). We replicate `f32/64::round()`
82 const BASIS_POINTS: u128 = 10000;
83 (((storage_rebate as u128 * storage_rebate_rate as u128)
84 + (BASIS_POINTS / 2)) // integer rounding adds half of the BASIS_POINTS (denominator)
85 / BASIS_POINTS) as u64
86 }
87
88 /// A list of constant costs of various operations in IOTA.
89 pub struct IotaCostTable {
90 /// A flat fee charged for every transaction. This is also the minimum
91 /// amount of gas charged for a transaction.
92 pub(crate) min_transaction_cost: u64,
93 /// Maximum allowable budget for a transaction.
94 pub(crate) max_gas_budget: u64,
95 /// Computation cost per byte charged for package publish. This cost is
96 /// primarily determined by the cost to verify and link a
97 /// package. Note that this does not include the cost of writing
98 /// the package to the store.
99 package_publish_per_byte_cost: u64,
100 /// Per byte cost to read objects from the store. This is computation
101 /// cost instead of storage cost because it does not change the
102 /// amount of data stored on the db.
103 object_read_per_byte_cost: u64,
104 /// Unit cost of a byte in the storage. This will be used both for
105 /// charging for new storage as well as rebating for deleting
106 /// storage. That is, we expect users to get full refund on the
107 /// object storage when it's deleted.
108 storage_per_byte_cost: u64,
109 /// Execution cost table to be used.
110 pub execution_cost_table: CostTable,
111 /// Computation buckets to cost transaction in price groups
112 computation_bucket: Vec<ComputationBucket>,
113 }
114
115 impl std::fmt::Debug for IotaCostTable {
116 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117 // TODO: dump the fields.
118 write!(f, "IotaCostTable(...)")
119 }
120 }
121
122 /// The flat fee charged for every transaction.
123 pub(crate) fn min_transaction_cost(config: &ProtocolConfig, gas_price: u64) -> u64 {
124 config.base_tx_cost_fixed() * gas_price
125 }
126
127 impl IotaCostTable {
128 pub(crate) fn new(c: &ProtocolConfig, gas_price: u64) -> Self {
129 Self {
130 min_transaction_cost: min_transaction_cost(c, gas_price),
131 max_gas_budget: c.max_tx_gas(),
132 package_publish_per_byte_cost: c.package_publish_cost_per_byte(),
133 object_read_per_byte_cost: c.obj_access_cost_read_per_byte(),
134 storage_per_byte_cost: c.obj_data_cost_refundable(),
135 execution_cost_table: cost_table_for_version(c.gas_model_version()),
136 computation_bucket: computation_bucket(c.max_gas_computation_bucket()),
137 }
138 }
139
140 pub(crate) fn unmetered() -> Self {
141 Self {
142 min_transaction_cost: 0,
143 max_gas_budget: u64::MAX,
144 package_publish_per_byte_cost: 0,
145 object_read_per_byte_cost: 0,
146 storage_per_byte_cost: 0,
147 execution_cost_table: ZERO_COST_SCHEDULE.clone(),
148 // should not matter
149 computation_bucket: computation_bucket(5_000_000),
150 }
151 }
152 }
153
154 #[derive(Debug)]
155 pub struct PerObjectStorage {
156 /// storage_cost is the total storage gas to charge. This is computed
157 /// at the end of execution while determining storage charges.
158 /// It tracks `storage_bytes * obj_data_cost_refundable` as
159 /// described in `storage_gas_price`
160 /// It has been multiplied by the storage gas price. This is the new
161 /// storage rebate.
162 pub storage_cost: u64,
163 /// storage_rebate is the storage rebate (in IOTA) for in this object.
164 /// This is computed at the end of execution while determining storage
165 /// charges. The value is in IOTA.
166 pub storage_rebate: u64,
167 /// The object size post-transaction in bytes
168 pub new_size: u64,
169 }
170
171 #[derive(Debug)]
172 pub struct IotaGasStatus {
173 /// GasStatus as used by the VM, that is all the VM sees
174 pub gas_status: GasStatus,
175 /// Cost table contains a set of constant/config for the gas
176 /// model/charging
177 cost_table: IotaCostTable,
178 /// Gas budget for this gas status instance.
179 /// Typically the gas budget as defined in the
180 /// `Transaction::GasPayment`
181 gas_budget: u64,
182 /// Computation cost after execution. This is the result of the gas used
183 /// by the `GasStatus` properly bucketized.
184 /// Starts at 0 and it is assigned in `bucketize_computation`.
185 computation_cost: u64,
186 /// Whether to charge or go unmetered
187 charge: bool,
188 /// Gas price for computation.
189 /// This is a multiplier on the final charge as related to the RGP
190 /// (reference gas price). Checked at signing: `gas_price >=
191 /// reference_gas_price` and then conceptually
192 /// `final_computation_cost = total_computation_cost * gas_price /
193 /// reference_gas_price`
194 gas_price: u64,
195 // Reference gas price as defined in protocol config.
196 // If `protocol_defined_base_fee' is enabled, this is a mandatory base fee paid to the
197 // protocol.
198 reference_gas_price: u64,
199 /// Gas price for storage. This is a multiplier on the final charge
200 /// as related to the storage gas price defined in the system
201 /// (`ProtocolConfig::storage_gas_price`).
202 /// Conceptually, given a constant `obj_data_cost_refundable`
203 /// (defined in `ProtocolConfig::obj_data_cost_refundable`)
204 /// `total_storage_cost = storage_bytes * obj_data_cost_refundable`
205 /// `final_storage_cost = total_storage_cost * storage_gas_price`
206 storage_gas_price: u64,
207 /// Per Object Storage Cost and Storage Rebate, used to get accumulated
208 /// values at the end of execution to determine storage charges
209 /// and rebates.
210 per_object_storage: Vec<(ObjectId, PerObjectStorage)>,
211 // storage rebate rate as defined in the ProtocolConfig
212 rebate_rate: u64,
213 /// Amount of storage rebate accumulated when we are running in
214 /// unmetered mode (i.e. system transaction). This allows us to
215 /// track how much storage rebate we need to retain in system
216 /// transactions.
217 unmetered_storage_rebate: u64,
218 /// Rounding value to round up gas charges.
219 gas_rounding_step: Option<u64>,
220 /// Flag to indicate whether the protocol-defined base fee is enabled,
221 /// in which case the reference gas price is burned.
222 protocol_defined_base_fee: bool,
223 }
224
225 impl IotaGasStatus {
226 fn new(
227 move_gas_status: GasStatus,
228 gas_budget: u64,
229 charge: bool,
230 gas_price: u64,
231 reference_gas_price: u64,
232 storage_gas_price: u64,
233 rebate_rate: u64,
234 gas_rounding_step: Option<u64>,
235 cost_table: IotaCostTable,
236 protocol_defined_base_fee: bool,
237 ) -> IotaGasStatus {
238 let gas_rounding_step = gas_rounding_step.map(|val| val.max(1));
239 IotaGasStatus {
240 gas_status: move_gas_status,
241 gas_budget,
242 charge,
243 computation_cost: 0,
244 gas_price,
245 reference_gas_price,
246 storage_gas_price,
247 per_object_storage: Vec::new(),
248 rebate_rate,
249 unmetered_storage_rebate: 0,
250 gas_rounding_step,
251 cost_table,
252 protocol_defined_base_fee,
253 }
254 }
255
256 pub(crate) fn new_with_budget(
257 gas_budget: u64,
258 gas_price: u64,
259 reference_gas_price: u64,
260 config: &ProtocolConfig,
261 ) -> IotaGasStatus {
262 let storage_gas_price = config.storage_gas_price();
263 let computation_budget = computation_budget(gas_budget, gas_price, config);
264 let iota_cost_table = IotaCostTable::new(config, gas_price);
265 let gas_rounding_step = config.gas_rounding_step_as_option();
266 Self::new(
267 GasStatus::new(
268 iota_cost_table.execution_cost_table.clone(),
269 computation_budget,
270 gas_price,
271 config.gas_model_version(),
272 ),
273 gas_budget,
274 true,
275 gas_price,
276 reference_gas_price,
277 storage_gas_price,
278 config.storage_rebate_rate(),
279 gas_rounding_step,
280 iota_cost_table,
281 config.protocol_defined_base_fee(),
282 )
283 }
284
285 pub fn new_unmetered() -> IotaGasStatus {
286 Self::new(
287 GasStatus::new_unmetered(),
288 0,
289 false,
290 0,
291 0,
292 0,
293 0,
294 None,
295 IotaCostTable::unmetered(),
296 false,
297 )
298 }
299
300 pub fn reference_gas_price(&self) -> u64 {
301 self.reference_gas_price
302 }
303
304 // Check whether gas arguments are legit:
305 // 1. Gas object has an address owner.
306 // 2. Gas budget is between min and max budget allowed, when `bounded_budget` is set.
307 // 3. Gas balance (all gas coins together) is bigger or equal to budget
308 //
309 // Keep the three checks together: it is only sound because step 1 has already
310 // rejected every gas object that `as_object` returns `None` for.
311 //
312 // Step 3 sums the balances of `gas_objs` as given, so an object listed twice
313 // is counted twice and the balance it reports is too high. Nothing here
314 // rejects that; `check_transaction_input` rejects it afterwards, in
315 // `check_objects`, as `MutableObjectUsedMoreThanOnce`. So an inflated
316 // balance can pass this function but not the call it is part of. A caller
317 // reaching this directly has to reject duplicate gas references itself.
318 pub(crate) fn check_gas_balance(
319 &self,
320 gas_objs: &[&ObjectReadResult],
321 gas_budget: u64,
322 bounded_budget: bool,
323 ) -> UserInputResult {
324 // 1. All gas objects have an address owner
325 for gas_object in gas_objs {
326 // if as_object() returns None, it means the object has been deleted (and
327 // therefore must be a shared object).
328 if let Some(obj) = gas_object.as_object() {
329 if !obj.is_address_owned() {
330 return Err(UserInputError::GasObjectNotOwnedObject { owner: obj.owner });
331 }
332 } else {
333 // This case should never happen (because gas can't be a shared object), but we
334 // handle this case for future-proofing
335 return Err(UserInputError::MissingGasPayment);
336 }
337 }
338
339 if bounded_budget {
340 // 2. Gas budget is between min and max budget allowed
341 gas::check_gas_budget_bounds(
342 gas_budget,
343 self.cost_table.min_transaction_cost,
344 self.cost_table.max_gas_budget,
345 )?;
346 }
347
348 // 3. Gas balance (all gas coins together) is bigger or equal to budget
349 let mut gas_balance = 0u128;
350 for gas_obj in gas_objs {
351 // expect is safe because we already checked that all gas objects have an
352 // address owner
353 gas_balance +=
354 gas::get_gas_balance(gas_obj.as_object().expect("object must be owned"))?
355 as u128;
356 }
357 if gas_balance < gas_budget as u128 {
358 Err(UserInputError::GasBalanceTooLow {
359 gas_balance,
360 needed_gas_amount: gas_budget as u128,
361 })
362 } else {
363 Ok(())
364 }
365 }
366
367 fn storage_cost(&self) -> u64 {
368 self.storage_gas_units()
369 }
370
371 pub fn per_object_storage(&self) -> &Vec<(ObjectId, PerObjectStorage)> {
372 &self.per_object_storage
373 }
374 }
375
376 impl IotaGasStatusAPI for IotaGasStatus {
377 fn is_unmetered(&self) -> bool {
378 !self.charge
379 }
380
381 fn move_gas_status(&self) -> &GasStatus {
382 &self.gas_status
383 }
384
385 fn move_gas_status_mut(&mut self) -> &mut GasStatus {
386 &mut self.gas_status
387 }
388
389 fn bucketize_computation(&mut self) -> Result<(), ExecutionError> {
390 let mut computation_units = self.gas_status.gas_used_pre_gas_price();
391 if let Some(gas_rounding) = self.gas_rounding_step {
392 if gas_rounding > 0
393 && (computation_units == 0 || computation_units % gas_rounding > 0)
394 {
395 computation_units = ((computation_units / gas_rounding) + 1) * gas_rounding;
396 }
397 } else {
398 // use the max value of the bucket that the computation_units falls into.
399 computation_units =
400 get_bucket_cost(&self.cost_table.computation_bucket, computation_units);
401 };
402 let computation_cost = computation_units * self.gas_price;
403 if self.gas_budget <= computation_cost {
404 self.computation_cost = self.gas_budget;
405 Err(ExecutionErrorKind::InsufficientGas.into())
406 } else {
407 self.computation_cost = computation_cost;
408 Ok(())
409 }
410 }
411
412 /// Returns the final (computation cost, storage cost, storage rebate)
413 /// of the gas meter. We use initial budget, combined with
414 /// remaining gas and storage cost to derive computation cost.
415 fn summary(&self) -> GasCostSummary {
416 // compute computation cost burned and storage rebate, both rebate and non
417 // refundable fee
418 let computation_cost_burned = if self.protocol_defined_base_fee {
419 // when protocol_defined_base_fee is enabled, the computation cost burned is
420 // computed as follows:
421 // computation_cost_burned = computation_units * reference_gas_price.
422 // = (computation_cost / gas_price) * reference_gas_price
423 self.computation_cost * self.reference_gas_price / self.gas_price
424 } else {
425 // when protocol_defined_base_fee is disabled, the entire computation cost is
426 // burned.
427 self.computation_cost
428 };
429 let storage_rebate = self.storage_rebate();
430 let sender_rebate = sender_rebate(storage_rebate, self.rebate_rate);
431 assert!(sender_rebate <= storage_rebate);
432 let non_refundable_storage_fee = storage_rebate - sender_rebate;
433 GasCostSummary {
434 computation_cost: self.computation_cost,
435 computation_cost_burned,
436 storage_cost: self.storage_cost(),
437 storage_rebate: sender_rebate,
438 non_refundable_storage_fee,
439 }
440 }
441
442 fn gas_budget(&self) -> u64 {
443 self.gas_budget
444 }
445
446 fn gas_price(&self) -> u64 {
447 self.gas_price
448 }
449
450 fn reference_gas_price(&self) -> u64 {
451 self.reference_gas_price
452 }
453
454 fn storage_gas_units(&self) -> u64 {
455 self.per_object_storage
456 .iter()
457 .map(|(_, per_object)| per_object.storage_cost)
458 .sum()
459 }
460
461 fn storage_rebate(&self) -> u64 {
462 self.per_object_storage
463 .iter()
464 .map(|(_, per_object)| per_object.storage_rebate)
465 .sum()
466 }
467
468 fn unmetered_storage_rebate(&self) -> u64 {
469 self.unmetered_storage_rebate
470 }
471
472 fn gas_used(&self) -> u64 {
473 self.gas_status.gas_used_pre_gas_price()
474 }
475
476 fn reset_storage_cost_and_rebate(&mut self) {
477 self.per_object_storage = Vec::new();
478 self.unmetered_storage_rebate = 0;
479 }
480
481 fn charge_storage_read(&mut self, size: usize) -> Result<(), ExecutionError> {
482 self.gas_status
483 .charge_bytes(size, self.cost_table.object_read_per_byte_cost)
484 .map_err(|e| {
485 debug_assert_eq!(e.major_status(), StatusCode::OUT_OF_GAS);
486 ExecutionErrorKind::InsufficientGas.into()
487 })
488 }
489
490 fn charge_publish_package(&mut self, size: usize) -> Result<(), ExecutionError> {
491 self.gas_status
492 .charge_bytes(size, self.cost_table.package_publish_per_byte_cost)
493 .map_err(|e| {
494 debug_assert_eq!(e.major_status(), StatusCode::OUT_OF_GAS);
495 ExecutionErrorKind::InsufficientGas.into()
496 })
497 }
498
499 /// Update `storage_rebate` and `storage_gas_units` for each object in
500 /// the transaction. There is no charge in this function.
501 /// Charges will all be applied together at the end
502 /// (`track_storage_mutation`).
503 /// Return the new storage rebate (cost of object storage) according to
504 /// `new_size`.
505 fn track_storage_mutation(
506 &mut self,
507 object_id: ObjectId,
508 new_size: usize,
509 storage_rebate: u64,
510 ) -> u64 {
511 if self.is_unmetered() {
512 self.unmetered_storage_rebate += storage_rebate;
513 return 0;
514 }
515
516 // compute and track cost (based on size)
517 let new_size = new_size as u64;
518 let storage_cost =
519 new_size * self.cost_table.storage_per_byte_cost * self.storage_gas_price;
520 // track rebate
521
522 self.per_object_storage.push((
523 object_id,
524 PerObjectStorage {
525 storage_cost,
526 storage_rebate,
527 new_size,
528 },
529 ));
530 // return the new object rebate (object storage cost)
531 storage_cost
532 }
533
534 fn charge_storage_and_rebate(&mut self) -> Result<(), ExecutionError> {
535 let storage_rebate = self.storage_rebate();
536 let storage_cost = self.storage_cost();
537 let sender_rebate = sender_rebate(storage_rebate, self.rebate_rate);
538 assert!(sender_rebate <= storage_rebate);
539 if sender_rebate >= storage_cost {
540 // there is more rebate than cost, when deducting gas we are adding
541 // to whatever is the current amount charged so we are `Ok`
542 Ok(())
543 } else {
544 let gas_left = self.gas_budget - self.computation_cost;
545 // we have to charge for storage and may go out of gas, check
546 if gas_left < storage_cost - sender_rebate {
547 // Running out of gas would cause the temporary store to reset
548 // and zero storage and rebate.
549 // The remaining_gas will be 0 and we will charge all in computation
550 Err(ExecutionErrorKind::InsufficientGas.into())
551 } else {
552 Ok(())
553 }
554 }
555 }
556
557 fn adjust_computation_on_out_of_gas(&mut self) {
558 self.per_object_storage = Vec::new();
559 self.computation_cost = self.gas_budget;
560 }
561 }
562
563 pub fn computation_budget(gas_budget: u64, gas_price: u64, config: &ProtocolConfig) -> u64 {
564 let max_computation_budget = config.max_gas_computation_bucket() * gas_price;
565
566 if gas_budget > max_computation_budget {
567 max_computation_budget
568 } else {
569 gas_budget
570 }
571 }
572}