1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
// This file is part of Gear.
// Copyright (C) 2021-2024 Gear Technologies Inc.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! Gas module.
use crate::{costs::CostToken, reservation::UnreservedReimbursement};
use enum_iterator::Sequence;
use scale_info::{
scale::{Decode, Encode},
TypeInfo,
};
/// The id of the gas lock.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Sequence)]
#[repr(u8)]
pub enum LockId {
/// The gas lock is provided by the mailbox.
Mailbox,
/// The gas lock is provided by the waitlist.
Waitlist,
/// The gas lock is provided by reservation.
Reservation,
/// The gas lock is provided by dispatch stash.
DispatchStash,
}
/// The result of charging gas.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChargeResult {
/// There was enough gas and it has been charged.
Enough,
/// There was not enough gas and it hasn't been charged.
NotEnough,
}
/// Gas counter with some predefined maximum gas.
///
/// `Copy` and `Clone` traits aren't implemented for the type (however could be)
/// in order to make the data only moveable, preventing explicit and implicit copying.
#[derive(Debug)]
pub struct GasCounter {
left: u64,
burned: u64,
}
impl GasCounter {
/// New limited gas counter with initial gas to spend.
pub fn new(initial_amount: u64) -> Self {
Self {
left: initial_amount,
burned: 0,
}
}
/// Account for used gas.
///
/// If there is no enough gas, then makes saturating charge and returns `NotEnough`.
/// Else charges gas and returns `Enough`.
pub fn charge<T: Into<u64> + Copy>(&mut self, amount: T) -> ChargeResult {
if let Some(new_left) = self.left.checked_sub(amount.into()) {
self.left = new_left;
self.burned += amount.into();
ChargeResult::Enough
} else {
self.burned += self.left;
self.left = 0;
ChargeResult::NotEnough
}
}
/// Account for used gas.
///
/// If there is no enough gas, then does nothing and returns `ChargeResult::NotEnough`.
/// Else charges gas and returns `ChargeResult::Enough`.
pub fn charge_if_enough<T: Into<u64> + Copy>(&mut self, amount: T) -> ChargeResult {
match self.left.checked_sub(amount.into()) {
None => ChargeResult::NotEnough,
Some(new_left) => {
self.left = new_left;
self.burned += amount.into();
ChargeResult::Enough
}
}
}
/// Increase left gas by `amount`.
///
/// Called when gas unreservation is occurred.
/// We don't decrease `burn` counter because `GasTree` manipulation is handled by separated function
pub fn increase(&mut self, amount: u64, _token: UnreservedReimbursement) -> bool {
match self.left.checked_add(amount) {
None => false,
Some(new_left) => {
self.left = new_left;
true
}
}
}
/// Reduce gas by `amount`.
///
/// Called when message is sent to another program, so the gas `amount` is sent to
/// receiving program.
/// Or called when gas reservation is occurred.
///
/// In case of gas reservation:
/// We don't increase `burn` counter because `GasTree` manipulation is handled by separated function
pub fn reduce(&mut self, amount: u64) -> ChargeResult {
match self.left.checked_sub(amount) {
None => ChargeResult::NotEnough,
Some(new_left) => {
self.left = new_left;
ChargeResult::Enough
}
}
}
/// Report how much gas is left.
pub fn left(&self) -> u64 {
self.left
}
/// Report how much gas is burned.
pub fn burned(&self) -> u64 {
self.burned
}
/// Get gas amount.
pub fn to_amount(&self) -> GasAmount {
GasAmount {
left: self.left,
burned: self.burned,
}
}
/// Clone the counter
///
/// # Safety
///
/// Use only when it's absolutely necessary to clone the counter i.e atomic implementation of `Ext`.
pub unsafe fn clone(&self) -> Self {
Self {
left: self.left,
burned: self.burned,
}
}
}
/// Read-only representation of consumed `GasCounter`.
///
/// `Copy` trait isn't implemented for the type (however could be)
/// in order to make the data only moveable, preventing implicit/explicit copying.
#[derive(Debug, Clone)]
pub struct GasAmount {
left: u64,
burned: u64,
}
impl GasAmount {
/// Report how much gas were left.
pub fn left(&self) -> u64 {
self.left
}
/// Report how much gas were burned.
pub fn burned(&self) -> u64 {
self.burned
}
}
/// Value counter with some predefined maximum value.
#[derive(Debug)]
pub struct ValueCounter(u128);
impl ValueCounter {
/// New limited value counter with initial value to spend.
pub fn new(initial_amount: u128) -> Self {
Self(initial_amount)
}
/// Reduce value by `amount`.
///
/// Called when message is sent to another program, so the value `amount` is sent to
/// receiving program.
pub fn reduce(&mut self, amount: u128) -> ChargeResult {
match self.0.checked_sub(amount) {
None => ChargeResult::NotEnough,
Some(new_left) => {
self.0 = new_left;
ChargeResult::Enough
}
}
}
/// Report how much value is left.
pub fn left(&self) -> u128 {
self.0
}
/// Clone the counter
///
/// # Safety
///
/// Use only when it's absolutely necessary to clone the counter i.e atomic implementation of `Ext`.
pub unsafe fn clone(&self) -> Self {
Self(self.0)
}
}
/// Gas allowance counter with some predefined maximum value.
#[derive(Clone, Debug)]
pub struct GasAllowanceCounter(u128);
impl GasAllowanceCounter {
/// New limited gas allowance counter with initial value to spend.
pub fn new(initial_amount: u64) -> Self {
Self(initial_amount as u128)
}
/// Report how much gas allowance is left.
pub fn left(&self) -> u64 {
self.0 as u64
}
/// Account for used gas allowance.
///
/// If there is no enough gas, then makes saturating charge and returns `NotEnough`.
/// Else charges gas and returns `Enough`.
pub fn charge<T: Into<u64>>(&mut self, amount: T) -> ChargeResult {
if let Some(new_left) = self.0.checked_sub(Into::<u64>::into(amount) as u128) {
self.0 = new_left;
ChargeResult::Enough
} else {
self.0 = 0;
ChargeResult::NotEnough
}
}
/// Account for used gas allowance.
///
/// If there is no enough gas, then does nothing and returns `ChargeResult::NotEnough`.
/// Else charges gas and returns `ChargeResult::Enough`.
pub fn charge_if_enough<T: Into<u64>>(&mut self, amount: T) -> ChargeResult {
if let Some(new_left) = self.0.checked_sub(Into::<u64>::into(amount) as u128) {
self.0 = new_left;
ChargeResult::Enough
} else {
ChargeResult::NotEnough
}
}
/// Clone the counter
///
/// # Safety
///
/// Use only when it's absolutely necessary to clone the counter i.e atomic implementation of `Ext`.
pub unsafe fn clone(&self) -> Self {
Self(self.0)
}
}
/// Charging error
#[derive(Debug, Clone, Eq, PartialEq, derive_more::Display)]
pub enum ChargeError {
/// An error occurs in attempt to charge more gas than available during execution.
#[display(fmt = "Not enough gas to continue execution")]
GasLimitExceeded,
/// Gas allowance exceeded
#[display(fmt = "Gas allowance exceeded")]
GasAllowanceExceeded,
}
/// Counters owner can change gas limit and allowance counters.
pub trait CountersOwner {
/// Charge for runtime api call.
fn charge_gas_for_token(&mut self, token: CostToken) -> Result<(), ChargeError>;
/// Charge gas if enough, else just returns error.
fn charge_gas_if_enough(&mut self, amount: u64) -> Result<(), ChargeError>;
/// Returns gas limit and gas allowance left.
fn gas_left(&self) -> GasLeft;
/// Currently set gas counter type.
fn current_counter_type(&self) -> CounterType;
/// Decreases gas left by fetched single numeric of actual counter.
fn decrease_current_counter_to(&mut self, amount: u64);
/// Returns minimal amount of gas counters and set the type of current counter.
fn define_current_counter(&mut self) -> u64;
/// Returns value of gas counter currently set.
fn current_counter_value(&self) -> u64 {
let GasLeft { gas, allowance } = self.gas_left();
match self.current_counter_type() {
CounterType::GasLimit => gas,
CounterType::GasAllowance => allowance,
}
}
}
/// Enum representing current type of gas counter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)]
pub enum CounterType {
/// Gas limit counter.
GasLimit,
/// Gas allowance counter.
GasAllowance,
}
/// Gas limit and gas allowance left.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)]
pub struct GasLeft {
/// Left gas from gas counter.
pub gas: u64,
/// Left gas from allowance counter.
pub allowance: u64,
}
impl From<(u64, u64)> for GasLeft {
fn from((gas, allowance): (u64, u64)) -> Self {
Self { gas, allowance }
}
}
impl From<(i64, i64)> for GasLeft {
fn from((gas, allowance): (i64, i64)) -> Self {
(gas as u64, allowance as u64).into()
}
}
/// The struct contains results of gas calculation required to process
/// a message.
#[derive(Clone, Debug, Decode, Default, Encode, PartialEq, Eq, TypeInfo)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub struct GasInfo {
/// Represents minimum gas limit required for execution.
pub min_limit: u64,
/// Gas amount that we reserve for some other on-chain interactions.
pub reserved: u64,
/// Contains number of gas burned during message processing.
pub burned: u64,
/// The value may be returned if a program happens to be executed
/// the second or next time in a block.
pub may_be_returned: u64,
/// Was the message placed into waitlist at the end of calculating.
///
/// This flag shows, that `min_limit` makes sense and have some guarantees
/// only before insertion into waitlist.
pub waited: bool,
}
#[cfg(test)]
mod tests {
use super::{ChargeResult, GasCounter};
use crate::gas::GasAllowanceCounter;
#[test]
/// Test that `GasCounter` object returns `Enough` and decreases the remaining count
/// on calling `charge(...)` when the remaining gas exceeds the required value,
/// otherwise returns NotEnough
fn limited_gas_counter_charging() {
let mut counter = GasCounter::new(200);
let result = counter.charge_if_enough(100u64);
assert_eq!(result, ChargeResult::Enough);
assert_eq!(counter.left(), 100);
let result = counter.charge_if_enough(101u64);
assert_eq!(result, ChargeResult::NotEnough);
assert_eq!(counter.left(), 100);
}
#[test]
fn charge_fails() {
let mut counter = GasCounter::new(100);
assert_eq!(counter.charge_if_enough(200u64), ChargeResult::NotEnough);
}
#[test]
fn charge_token_fails() {
let mut counter = GasCounter::new(10);
assert_eq!(counter.charge(1000u64), ChargeResult::NotEnough);
}
#[test]
fn charge_allowance_token_fails() {
let mut counter = GasAllowanceCounter::new(10);
assert_eq!(counter.charge(1000u64), ChargeResult::NotEnough);
}
}