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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
// This file is part of Gear.

// Copyright (C) 2022-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 reservation structures.

use crate::{
    ids::{prelude::*, MessageId, ReservationId},
    message::IncomingDispatch,
};
use alloc::{collections::BTreeMap, format};
use gear_core_errors::ReservationError;
use scale_info::{
    scale::{Decode, Encode},
    TypeInfo,
};

/// An unchangeable wrapper over u64 value, which is required
/// to be used as a "view-only" reservations nonce in a message
/// execution context.
///
/// ### Note:
/// By contract, It must be instantiated only once, when message execution
/// context is created. Also the latter is required to be instantiated only
/// once, when incoming dispatch is created.
#[derive(
    Clone, Copy, Default, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Decode, Encode, TypeInfo,
)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
pub struct ReservationNonce(u64);

impl From<&InnerNonce> for ReservationNonce {
    fn from(nonce: &InnerNonce) -> Self {
        ReservationNonce(nonce.0)
    }
}

/// A changeable wrapper over u64 value, which is required
/// to be used as an "active" reservations nonce in a gas reserver.
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
struct InnerNonce(u64);

impl InnerNonce {
    /// Fetches current state of the nonce and
    /// updates its state by incrementing it.
    fn fetch_inc(&mut self) -> u64 {
        let current = self.0;
        self.0 = self.0.saturating_add(1);

        current
    }
}

impl From<ReservationNonce> for InnerNonce {
    fn from(frozen_nonce: ReservationNonce) -> Self {
        InnerNonce(frozen_nonce.0)
    }
}

/// Gas reserver.
///
/// Controls gas reservations states.
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
pub struct GasReserver {
    /// Message id within which reservations are created
    /// by the current instance of [`GasReserver`].
    message_id: MessageId,
    /// Nonce used to generate [`ReservationId`]s.
    ///
    /// It's really important that if gas reserver is created
    /// several times with the same `message_id`, value of this
    /// field is re-used. This property is guaranteed by instantiating
    /// gas reserver from the [`IncomingDispatch`].
    nonce: InnerNonce,
    /// Gas reservations states.
    states: GasReservationStates,
    /// Maximum allowed reservations to be stored in `states`.
    ///
    /// This field is used not only to control `states` during
    /// one execution, but also during several execution using
    /// gas reserver for the actor. To reach that `states` must
    /// be set with reservation from previous executions of the
    /// actor.
    max_reservations: u64,
}

impl GasReserver {
    /// Creates a new gas reserver.
    ///
    /// `map`, which is a [`BTreeMap`] of [`GasReservationSlot`]s,
    /// will be converted to the [`BTreeMap`] of [`GasReservationState`]s.
    pub fn new(
        incoming_dispatch: &IncomingDispatch,
        map: GasReservationMap,
        max_reservations: u64,
    ) -> Self {
        let message_id = incoming_dispatch.id();
        let nonce = incoming_dispatch
            .context()
            .as_ref()
            .map(|c| c.reservation_nonce())
            .unwrap_or_default()
            .into();
        Self {
            message_id,
            nonce,
            states: {
                let mut states = BTreeMap::new();
                states.extend(map.into_iter().map(|(id, slot)| (id, slot.into())));
                states
            },
            max_reservations,
        }
    }

    /// Returns bool defining if gas reserver is empty.
    pub fn is_empty(&self) -> bool {
        self.states.is_empty()
    }

    /// Checks that the number of existing and newly created reservations
    /// in the `states` is less than `max_reservations`. Removed reservations,
    /// which are stored with the [`GasReservationState::Removed`] state in the
    /// `states`, aren't excluded from the check.
    fn check_execution_limit(&self) -> Result<(), ReservationError> {
        // operation might very expensive in the future
        // so we will store 2 numerics to optimize it maybe
        let current_reservations = self
            .states
            .values()
            .map(|state| {
                matches!(
                    state,
                    GasReservationState::Exists { .. } | GasReservationState::Created { .. }
                ) as u64
            })
            .sum::<u64>();
        if current_reservations > self.max_reservations {
            Err(ReservationError::ReservationsLimitReached)
        } else {
            Ok(())
        }
    }

    /// Returns amount of gas in reservation, if exists.
    pub fn limit_of(&self, reservation_id: &ReservationId) -> Option<u64> {
        self.states.get(reservation_id).and_then(|v| match v {
            GasReservationState::Exists { amount, .. }
            | GasReservationState::Created { amount, .. } => Some(*amount),
            _ => None,
        })
    }

    /// Reserves gas.
    ///
    /// Creates a new reservation and returns its id.
    ///
    /// Returns an error if maximum limit of reservations is reached.
    pub fn reserve(
        &mut self,
        amount: u64,
        duration: u32,
    ) -> Result<ReservationId, ReservationError> {
        self.check_execution_limit()?;

        let id = ReservationId::generate(self.message_id, self.nonce.fetch_inc());

        let maybe_reservation = self.states.insert(
            id,
            GasReservationState::Created {
                amount,
                duration,
                used: false,
            },
        );

        if maybe_reservation.is_some() {
            let err_msg = format!(
                "GasReserver::reserve: created a duplicate reservation. \
                Message id  - {message_id}, nonce - {nonce}",
                message_id = self.message_id,
                nonce = self.nonce.0
            );

            log::error!("{err_msg}");
            unreachable!("{err_msg}");
        }

        Ok(id)
    }

    /// Unreserves gas reserved within `id` reservation.
    ///
    /// Return error if:
    /// 1. Reservation doesn't exist.
    /// 2. Reservation was "unreserved", so in [`GasReservationState::Removed`] state.
    /// 3. Reservation was marked used.
    pub fn unreserve(
        &mut self,
        id: ReservationId,
    ) -> Result<(u64, Option<UnreservedReimbursement>), ReservationError> {
        // Docs error case #1.
        let state = self
            .states
            .get(&id)
            .ok_or(ReservationError::InvalidReservationId)?;

        if matches!(
            state,
            // Docs error case #2.
            GasReservationState::Removed { .. } |
            // Docs error case #3.
            GasReservationState::Exists { used: true, .. } |
            GasReservationState::Created { used: true, .. }
        ) {
            return Err(ReservationError::InvalidReservationId);
        }

        let state = self.states.remove(&id).unwrap();

        Ok(match state {
            GasReservationState::Exists { amount, finish, .. } => {
                self.states
                    .insert(id, GasReservationState::Removed { expiration: finish });
                (amount, None)
            }
            GasReservationState::Created {
                amount, duration, ..
            } => (amount, Some(UnreservedReimbursement(duration))),
            GasReservationState::Removed { .. } => {
                let err_msg =
                    "GasReserver::unreserve: `Removed` variant is unreachable, checked above";

                log::error!("{err_msg}");
                unreachable!("{err_msg}")
            }
        })
    }

    /// Marks reservation as used.
    ///
    /// This allows to avoid double usage of the reservation
    /// for sending a new message from execution of `message_id`
    /// of current gas reserver.
    pub fn mark_used(&mut self, id: ReservationId) -> Result<(), ReservationError> {
        let used = self.check_not_used(id)?;
        *used = true;
        Ok(())
    }

    /// Check if reservation is not used.
    ///
    /// If reservation does not exist returns `InvalidReservationId` error.
    pub fn check_not_used(&mut self, id: ReservationId) -> Result<&mut bool, ReservationError> {
        if let Some(
            GasReservationState::Created { used, .. } | GasReservationState::Exists { used, .. },
        ) = self.states.get_mut(&id)
        {
            if *used {
                Err(ReservationError::InvalidReservationId)
            } else {
                Ok(used)
            }
        } else {
            Err(ReservationError::InvalidReservationId)
        }
    }

    /// Returns gas reservations current nonce.
    pub fn nonce(&self) -> ReservationNonce {
        (&self.nonce).into()
    }

    /// Gets gas reservations states.
    pub fn states(&self) -> &GasReservationStates {
        &self.states
    }

    /// Converts current gas reserver into gas reservation map.
    pub fn into_map<F>(
        self,
        current_block_height: u32,
        duration_into_expiration: F,
    ) -> GasReservationMap
    where
        F: Fn(u32) -> u32,
    {
        self.states
            .into_iter()
            .flat_map(|(id, state)| match state {
                GasReservationState::Exists {
                    amount,
                    start,
                    finish,
                    ..
                } => Some((
                    id,
                    GasReservationSlot {
                        amount,
                        start,
                        finish,
                    },
                )),
                GasReservationState::Created {
                    amount, duration, ..
                } => {
                    let expiration = duration_into_expiration(duration);
                    Some((
                        id,
                        GasReservationSlot {
                            amount,
                            start: current_block_height,
                            finish: expiration,
                        },
                    ))
                }
                GasReservationState::Removed { .. } => None,
            })
            .collect()
    }
}

/// Safety token returned when unreserved gas can be returned back to the gas counter.
///
/// Wraps duration for the newly created reservation.
#[derive(Debug, PartialEq, Eq)]
pub struct UnreservedReimbursement(u32);

impl UnreservedReimbursement {
    /// Returns duration for the newly created unreserved reservation.
    pub fn duration(&self) -> u32 {
        self.0
    }
}

/// Gas reservations states.
pub type GasReservationStates = BTreeMap<ReservationId, GasReservationState>;

/// Gas reservation state.
///
/// Used to control whether reservation was created, removed or nothing happened.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Encode, Decode)]
pub enum GasReservationState {
    /// Reservation exists.
    Exists {
        /// Amount of reserved gas.
        amount: u64,
        /// Block number when reservation is created.
        start: u32,
        /// Block number when reservation will expire.
        finish: u32,
        /// Flag signalizing whether reservation is used.
        used: bool,
    },
    /// Reservation will be created.
    Created {
        /// Amount of reserved gas.
        amount: u64,
        /// How many blocks reservation will live.
        duration: u32,
        /// Flag signalizing whether reservation is used.
        used: bool,
    },
    /// Reservation will be removed.
    Removed {
        /// Block number when reservation will expire.
        expiration: u32,
    },
}

impl From<GasReservationSlot> for GasReservationState {
    fn from(slot: GasReservationSlot) -> Self {
        Self::Exists {
            amount: slot.amount,
            start: slot.start,
            finish: slot.finish,
            used: false,
        }
    }
}

/// Gas reservations map.
///
/// Used across execution and is stored to storage.
pub type GasReservationMap = BTreeMap<ReservationId, GasReservationSlot>;

/// Gas reservation slot.
#[derive(Debug, Clone, Eq, PartialEq, Encode, Decode, TypeInfo)]
pub struct GasReservationSlot {
    /// Amount of reserved gas.
    pub amount: u64,
    /// Block number when reservation is created.
    pub start: u32,
    /// Block number when reservation will expire.
    pub finish: u32,
}

#[cfg(test)]
mod tests {
    use super::*;

    const MAX_RESERVATIONS: u64 = 256;

    fn new_reserver() -> GasReserver {
        let d = IncomingDispatch::default();
        GasReserver::new(&d, Default::default(), MAX_RESERVATIONS)
    }

    #[test]
    fn max_reservations_limit_works() {
        let mut reserver = new_reserver();
        for n in 0..(MAX_RESERVATIONS * 10) {
            let res = reserver.reserve(100, 10);
            if n > MAX_RESERVATIONS {
                assert_eq!(res, Err(ReservationError::ReservationsLimitReached));
            } else {
                assert!(res.is_ok());
            }
        }
    }

    #[test]
    fn mark_used_for_unreserved_fails() {
        let mut reserver = new_reserver();
        let id = reserver.reserve(1, 1).unwrap();
        reserver.unreserve(id).unwrap();

        assert_eq!(
            reserver.mark_used(id),
            Err(ReservationError::InvalidReservationId)
        );
    }

    #[test]
    fn mark_used_twice_fails() {
        let mut reserver = new_reserver();
        let id = reserver.reserve(1, 1).unwrap();
        reserver.mark_used(id).unwrap();
        assert_eq!(
            reserver.mark_used(id),
            Err(ReservationError::InvalidReservationId)
        );

        // not found
        assert_eq!(
            reserver.mark_used(ReservationId::default()),
            Err(ReservationError::InvalidReservationId)
        );
    }

    #[test]
    fn remove_reservation_twice_fails() {
        let mut reserver = new_reserver();
        let id = reserver.reserve(1, 1).unwrap();
        reserver.unreserve(id).unwrap();
        assert_eq!(
            reserver.unreserve(id),
            Err(ReservationError::InvalidReservationId)
        );
    }

    #[test]
    fn remove_non_existing_reservation_fails() {
        let id = ReservationId::from([0xff; 32]);

        let mut map = GasReservationMap::new();
        map.insert(
            id,
            GasReservationSlot {
                amount: 1,
                start: 1,
                finish: 100,
            },
        );

        let mut reserver = GasReserver::new(&Default::default(), map, 256);
        reserver.unreserve(id).unwrap();

        assert_eq!(
            reserver.unreserve(id),
            Err(ReservationError::InvalidReservationId)
        );
    }

    #[test]
    fn fresh_reserve_unreserve() {
        let mut reserver = new_reserver();
        let id = reserver.reserve(10_000, 5).unwrap();
        reserver.mark_used(id).unwrap();
        assert_eq!(
            reserver.unreserve(id),
            Err(ReservationError::InvalidReservationId)
        );
    }

    #[test]
    fn existing_reserve_unreserve() {
        let id = ReservationId::from([0xff; 32]);

        let mut map = GasReservationMap::new();
        map.insert(
            id,
            GasReservationSlot {
                amount: 1,
                start: 1,
                finish: 100,
            },
        );

        let mut reserver = GasReserver::new(&Default::default(), map, 256);
        reserver.mark_used(id).unwrap();
        assert_eq!(
            reserver.unreserve(id),
            Err(ReservationError::InvalidReservationId)
        );
    }

    #[test]
    fn unreserving_unreserved() {
        let id = ReservationId::from([0xff; 32]);
        let slot = GasReservationSlot {
            amount: 1,
            start: 2,
            finish: 3,
        };

        let mut map = GasReservationMap::new();
        map.insert(id, slot.clone());

        let mut reserver = GasReserver::new(&Default::default(), map, 256);

        let (amount, _) = reserver.unreserve(id).expect("Shouldn't fail");
        assert_eq!(amount, slot.amount);

        assert!(reserver.unreserve(id).is_err());
        assert_eq!(
            reserver.states().get(&id).cloned(),
            Some(GasReservationState::Removed {
                expiration: slot.finish
            })
        );
    }
}