Skip to content

Commit 029e822

Browse files
authored
Merge pull request #19 from axic/checked-u64
Add AsCheckedU64 trait to simplify gas checks
2 parents 59a071c + 9471640 commit 029e822

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

src/lib.rs

+16-5
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,19 @@ use self::vm::{
2323

2424
use ewasm_api::types::{Bytes20, Bytes32, Uint128};
2525

26+
trait AsCheckedU64 {
27+
fn as_checked_u64(&self) -> u64;
28+
}
29+
30+
impl AsCheckedU64 for U256 {
31+
fn as_checked_u64(&self) -> u64 {
32+
if self > &U256::from("ffffffffffffffff") {
33+
ewasm_api::abort();
34+
}
35+
self.as_u64()
36+
}
37+
}
38+
2639
// For some explanation see ethcore/vm/src/tests.rs::FakeExt
2740

2841
#[derive(Default)]
@@ -119,9 +132,7 @@ impl vm::Ext for EwasmExt {
119132
call_type: CallType,
120133
trap: bool,
121134
) -> ::std::result::Result<MessageCallResult, TrapKind> {
122-
// FIXME: set this properly
123-
//let gas_limit = u64::from(gas);
124-
let gas_limit = gas.as_u64();
135+
let gas_limit = gas.as_checked_u64();
125136

126137
// FIXME: might not be good enough
127138
let gas_start = ewasm_api::gas_left();
@@ -332,7 +343,7 @@ pub extern "C" fn main() {
332343
// Could run `result.finalize(ext)` here, but processing manually seemed simpler.
333344
match result {
334345
Ok(Ok(GasLeft::Known(gas_left))) => {
335-
ewasm_api::consume_gas(startgas - gas_left.as_u64());
346+
ewasm_api::consume_gas(startgas - gas_left.as_checked_u64());
336347
if ext.selfdestruct_address.is_some() {
337348
let beneficiary: [u8; 20] = ext.selfdestruct_address.unwrap().into();
338349
ewasm_api::selfdestruct(&ewasm_api::types::Bytes20 { bytes: beneficiary })
@@ -345,7 +356,7 @@ pub extern "C" fn main() {
345356
data,
346357
apply_state,
347358
})) => {
348-
ewasm_api::consume_gas(startgas - gas_left.as_u64());
359+
ewasm_api::consume_gas(startgas - gas_left.as_checked_u64());
349360
if apply_state {
350361
ewasm_api::finish_data(&data.deref())
351362
} else {

0 commit comments

Comments
 (0)