Browse Source

[runtime] Prevent (unlikely) underflow

This commit explicitly handles a scenario where an underflow could
occur when calculating gas. In practice, this should not occur as the
WASM points budget should be synchronized with the contract's gas usage.
For this reason, the code should panic instead of underflow if this does
somehow happen.
y 2 years ago
parent
commit
d3839ed6fc
1 changed files with 10 additions and 3 deletions
  1. 10 3
      src/runtime/vm_runtime.rs

+ 10 - 3
src/runtime/vm_runtime.rs

@@ -476,16 +476,23 @@ impl Runtime {
     /// of metering points.
     fn gas_used(&mut self) -> u64 {
         let remaining_points = get_remaining_points(&mut self.store, &self.instance);
-
+        
         match remaining_points {
-            MeteringPoints::Remaining(rem) => GAS_LIMIT - rem,
+            MeteringPoints::Remaining(rem) => {
+                if rem > GAS_LIMIT {
+                    // This should never occur, but catch it explicitly to avoid
+                    // potential underflow issues when calculating `remaining_points`.
+                    unreachable!("Remaining wasm points exceed GAS_LIMIT");
+                }
+                GAS_LIMIT - rem
+            },
             MeteringPoints::Exhausted => GAS_LIMIT + 1,
         }
     }
 
     // Return a message informing the user whether there is any
     // gas remaining. Values equal to GAS_LIMIT are not considered
-    // to be exhausted. e.g. Using 100/100 gas should not give a 
+    // to be exhausted. e.g. Using 100/100 gas should not give a
     // 'gas exhausted' message.
     fn gas_info(&mut self) -> String {
         let gas_used = self.gas_used();