ethereumvm 0.11.0

EthereumVM - a Portable Blockchain Virtual Machine
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
//! Cost calculation logic

use bigint::{Address, Gas, M256, U256};

#[cfg(not(feature = "std"))]
use core::cmp::max;
#[cfg(feature = "std")]
use std::cmp::max;

use super::State;
use crate::{AccountPatch, Instruction, Memory, Patch};

const G_ZERO: usize = 0;
const G_BASE: usize = 2;
const G_VERYLOW: usize = 3;
const G_LOW: usize = 5;
const G_MID: usize = 8;
const G_HIGH: usize = 10;
const G_JUMPDEST: usize = 1;
const G_SNOOP: usize = 200;
const G_SSET: usize = 20000;
const G_SRESET: usize = 5000;
const R_SRESET: isize = 15000;
const R_NETSRESETCLEAR: isize = 19800;
const R_NETSRESET: isize = 4800;
const R_NETSCLEAR: isize = 15000;
const R_SUICIDE: isize = 24000;
const G_CREATE: usize = 32000;
const G_CODEDEPOSIT: usize = 200;
const G_CALLVALUE: usize = 9000;
const G_CALLSTIPEND: usize = 2300;
const G_NEWACCOUNT: usize = 25000;
const G_EXP: usize = 10;
const G_MEMORY: usize = 3;
const G_LOG: usize = 375;
const G_LOGDATA: usize = 8;
const G_LOGTOPIC: usize = 375;
const G_SHA3: usize = 30;
const G_SHA3WORD: usize = 6;
const G_COPY: usize = 3;
const G_BLOCKHASH: usize = 20;
const G_EXTCODEHASH: usize = 400;

fn sstore_cost<M: Memory, P: Patch>(state: &State<M, P>) -> Gas {
    let index: U256 = state.stack.peek(0).unwrap().into();
    let value = state.stack.peek(1).unwrap();
    let address = state.context.address;
    let current = state.account_state.storage_read(address, index).unwrap();

    // The legacy gas metering only takes into consideration the current state
    if !state.patch.has_reduced_sstore_gas_metering() {
        if current == M256::zero() && value != M256::zero() {
            return G_SSET.into();
        } else {
            return G_SRESET.into();
        }
    }

    // Modern gas metering scheme (EIP-1283)
    trace!("using EIP1283 reduced SSTORE gas metering scheme");

    if value == current {
        return G_SNOOP.into();
    }

    // If RequireError is thrown here, that means that original storage was unset, hence defaulting to Zero.
    let original = state
        .account_state
        .storage_read_orig(address, index)
        .unwrap_or(M256::zero());

    if original == current {
        if original == M256::zero() {
            G_SSET.into()
        } else {
            G_SRESET.into()
        }
    } else {
        G_SNOOP.into()
    }
}

fn call_cost<M: Memory, P: Patch>(machine: &State<M, P>, instruction: &Instruction) -> Gas {
    let transfers_value = machine.stack.peek(2).unwrap() != M256::zero();
    machine.patch.gas_call() + xfer_cost(instruction, transfers_value) + new_cost(machine, instruction, transfers_value)
}

fn xfer_cost(instruction: &Instruction, transfers_value: bool) -> Gas {
    if (instruction == &Instruction::CALL || instruction == &Instruction::CALLCODE) && transfers_value {
        G_CALLVALUE.into()
    } else {
        Gas::zero()
    }
}

fn new_cost<M: Memory, P: Patch>(machine: &State<M, P>, instruction: &Instruction, transfers_value: bool) -> Gas {
    let address: Address = machine.stack.peek(1).unwrap().into();
    let eip161 = !machine.patch.account_patch().empty_considered_exists();
    if instruction == &Instruction::CALL || instruction == &Instruction::STATICCALL {
        if eip161 {
            if transfers_value && !machine.account_state.exists(address).unwrap() {
                Gas::from(G_NEWACCOUNT)
            } else {
                Gas::zero()
            }
        } else if !machine.account_state.exists(address).unwrap() {
            Gas::from(G_NEWACCOUNT)
        } else {
            Gas::zero()
        }
    } else {
        Gas::zero()
    }
}

fn suicide_cost<M: Memory, P: Patch>(machine: &State<M, P>) -> Gas {
    let target_address: Address = machine.stack.peek(0).unwrap().into();
    let current_balance = machine.account_state.balance(machine.context.address).unwrap();
    let is_target_existing = machine.account_state.exists(target_address).unwrap();

    // Whether the suicide gas topup should be levied:
    // if before EIP161:
    // - if target nonexistent
    // if after EIP161:
    // - if transfer balance != 0
    // - if target account is dead
    // defined by EIP161 (https://github.com/ethereum/EIPs/blob/master/EIPS/eip-161.md)
    // AccountPatch::empty_considered_exists is set to false on State-Clearing ETH fork
    let eip161 = !machine.patch.account_patch().empty_considered_exists();
    let should_charge_topup = if eip161 {
        current_balance != U256::zero() && !is_target_existing
    } else {
        !is_target_existing
    };

    debug!(
        "suicide in favor of {}, exists: {}, on_eip161: {}",
        target_address, is_target_existing, eip161
    );
    debug!("suicide transfer value: {}", current_balance);

    let suicide_gas_topup = if should_charge_topup {
        trace!("suicide with new account gas topup");
        machine.patch.gas_suicide_new_account()
    } else {
        trace!("suicide with zero gas topup");
        Gas::zero()
    };

    machine.patch.gas_suicide() + suicide_gas_topup
}

fn memory_expand(current: Gas, from: Gas, len: Gas) -> Gas {
    if len == Gas::zero() {
        return current;
    }

    let rem = (from + len) % Gas::from(32u64);
    let new = if rem == Gas::zero() {
        (from + len) / Gas::from(32u64)
    } else {
        (from + len) / Gas::from(32u64) + Gas::from(1u64)
    };
    max(current, new)
}

/// Calculate code deposit cost for a ContractCreation transaction.
pub fn code_deposit_gas(len: usize) -> Gas {
    Gas::from(G_CODEDEPOSIT) * Gas::from(len)
}

/// Calculate the memory gas from the memory cost.
pub fn memory_gas(a: Gas) -> Gas {
    Gas::from(G_MEMORY) * a + a * a / Gas::from(512u64)
}

/// Calculate the memory cost. This is the same as the active memory
/// length in the Yellow Paper.
pub fn memory_cost<M: Memory, P: Patch>(instruction: Instruction, state: &State<M, P>) -> Gas {
    let stack = &state.stack;

    let current = state.memory_cost;
    match instruction {
        Instruction::SHA3 | Instruction::RETURN | Instruction::REVERT | Instruction::LOG(_) => {
            let from: U256 = stack.peek(0).unwrap().into();
            let len: U256 = stack.peek(1).unwrap().into();
            memory_expand(current, Gas::from(from), Gas::from(len))
        }
        Instruction::CODECOPY | Instruction::CALLDATACOPY | Instruction::RETURNDATACOPY => {
            let from: U256 = stack.peek(0).unwrap().into();
            let len: U256 = stack.peek(2).unwrap().into();
            memory_expand(current, Gas::from(from), Gas::from(len))
        }
        Instruction::EXTCODECOPY => {
            let from: U256 = stack.peek(1).unwrap().into();
            let len: U256 = stack.peek(3).unwrap().into();
            memory_expand(current, Gas::from(from), Gas::from(len))
        }
        Instruction::MLOAD | Instruction::MSTORE => {
            let from: U256 = stack.peek(0).unwrap().into();
            memory_expand(current, Gas::from(from), Gas::from(32u64))
        }
        Instruction::MSTORE8 => {
            let from: U256 = stack.peek(0).unwrap().into();
            memory_expand(current, Gas::from(from), Gas::from(1u64))
        }
        Instruction::CREATE | Instruction::CREATE2 => {
            let from: U256 = stack.peek(1).unwrap().into();
            let len: U256 = stack.peek(2).unwrap().into();
            memory_expand(current, Gas::from(from), Gas::from(len))
        }
        Instruction::CALL | Instruction::CALLCODE => {
            let in_from: U256 = stack.peek(3).unwrap().into();
            let in_len: U256 = stack.peek(4).unwrap().into();
            let out_from: U256 = stack.peek(5).unwrap().into();
            let out_len: U256 = stack.peek(6).unwrap().into();
            memory_expand(
                memory_expand(current, Gas::from(in_from), Gas::from(in_len)),
                Gas::from(out_from),
                Gas::from(out_len),
            )
        }
        _ => current,
    }
}

/// Calculate the gas cost.
pub fn gas_cost<M: Memory, P: Patch>(instruction: Instruction, state: &State<M, P>) -> Gas {
    match instruction {
        Instruction::CALL => call_cost::<M, P>(state, &Instruction::CALL),
        Instruction::CALLCODE => call_cost::<M, P>(state, &Instruction::CALLCODE),
        Instruction::DELEGATECALL => call_cost::<M, P>(state, &Instruction::DELEGATECALL),
        Instruction::STATICCALL => call_cost::<M, P>(state, &Instruction::STATICCALL),
        Instruction::SUICIDE => suicide_cost::<M, P>(state),
        Instruction::SSTORE => sstore_cost(state),

        Instruction::SHA3 => {
            let len = state.stack.peek(1).unwrap();
            let wordd = Gas::from(len) / Gas::from(32u64);
            let wordr = Gas::from(len) % Gas::from(32u64);
            Gas::from(G_SHA3)
                + Gas::from(G_SHA3WORD)
                    * if wordr == Gas::zero() {
                        wordd
                    } else {
                        wordd + Gas::from(1u64)
                    }
        }

        Instruction::LOG(v) => {
            let len = state.stack.peek(1).unwrap();
            Gas::from(G_LOG) + Gas::from(G_LOGDATA) * Gas::from(len) + Gas::from(G_LOGTOPIC) * Gas::from(v)
        }

        Instruction::EXTCODECOPY => {
            let len = state.stack.peek(3).unwrap();
            let wordd = Gas::from(len) / Gas::from(32u64);
            let wordr = Gas::from(len) % Gas::from(32u64);
            state.patch.gas_extcode()
                + Gas::from(G_COPY)
                    * if wordr == Gas::zero() {
                        wordd
                    } else {
                        wordd + Gas::from(1u64)
                    }
        }

        Instruction::CALLDATACOPY | Instruction::CODECOPY | Instruction::RETURNDATACOPY => {
            let len = state.stack.peek(2).unwrap();
            let wordd = Gas::from(len) / Gas::from(32u64);
            let wordr = Gas::from(len) % Gas::from(32u64);
            Gas::from(G_VERYLOW)
                + Gas::from(G_COPY)
                    * if wordr == Gas::zero() {
                        wordd
                    } else {
                        wordd + Gas::from(1u64)
                    }
        }

        Instruction::EXP => {
            if state.stack.peek(1).unwrap() == M256::zero() {
                Gas::from(G_EXP)
            } else {
                Gas::from(G_EXP)
                    + state.patch.gas_expbyte()
                        * (Gas::from(1u64) + Gas::from(state.stack.peek(1).unwrap().log2floor()) / Gas::from(8u64))
            }
        }

        Instruction::CREATE => G_CREATE.into(),
        Instruction::CREATE2 => {
            let base = G_CREATE;
            let init_code_len = state.stack.peek(2).unwrap().as_usize();
            // ceil(init_code_len / 32.0)
            let sha_addup_base = init_code_len / 32 + if init_code_len % 32 == 0 { 0 } else { 1 };
            let sha_addup = G_SHA3WORD * sha_addup_base;
            (base + sha_addup).into()
        }
        Instruction::JUMPDEST => G_JUMPDEST.into(),
        Instruction::SLOAD => state.patch.gas_sload(),

        // W_zero
        Instruction::STOP | Instruction::RETURN | Instruction::REVERT => G_ZERO.into(),

        // W_base
        Instruction::ADDRESS
        | Instruction::ORIGIN
        | Instruction::CALLER
        | Instruction::CALLVALUE
        | Instruction::CALLDATASIZE
        | Instruction::RETURNDATASIZE
        | Instruction::CODESIZE
        | Instruction::GASPRICE
        | Instruction::COINBASE
        | Instruction::TIMESTAMP
        | Instruction::NUMBER
        | Instruction::DIFFICULTY
        | Instruction::GASLIMIT
        | Instruction::POP
        | Instruction::PC
        | Instruction::MSIZE
        | Instruction::GAS => G_BASE.into(),

        // W_verylow
        Instruction::ADD
        | Instruction::SUB
        | Instruction::NOT
        | Instruction::LT
        | Instruction::GT
        | Instruction::SLT
        | Instruction::SGT
        | Instruction::EQ
        | Instruction::ISZERO
        | Instruction::AND
        | Instruction::OR
        | Instruction::XOR
        | Instruction::BYTE
        | Instruction::CALLDATALOAD
        | Instruction::MLOAD
        | Instruction::MSTORE
        | Instruction::MSTORE8
        | Instruction::PUSH(_)
        | Instruction::DUP(_)
        | Instruction::SWAP(_)
        | Instruction::SHL
        | Instruction::SHR
        | Instruction::SAR => G_VERYLOW.into(),

        // W_low
        Instruction::MUL
        | Instruction::DIV
        | Instruction::SDIV
        | Instruction::MOD
        | Instruction::SMOD
        | Instruction::SIGNEXTEND => G_LOW.into(),

        // W_mid
        Instruction::ADDMOD | Instruction::MULMOD | Instruction::JUMP => G_MID.into(),

        // W_high
        Instruction::JUMPI => G_HIGH.into(),

        // W_extcode
        Instruction::EXTCODESIZE => state.patch.gas_extcode(),
        Instruction::BALANCE => state.patch.gas_balance(),
        Instruction::BLOCKHASH => G_BLOCKHASH.into(),
        Instruction::EXTCODEHASH => G_EXTCODEHASH.into(),
    }
}

/// Raise gas stipend for CALL and CALLCODE instruction.
pub fn gas_stipend<M: Memory, P: Patch>(instruction: Instruction, state: &State<M, P>) -> Gas {
    match instruction {
        Instruction::CALL | Instruction::CALLCODE => {
            let value = state.stack.peek(2).unwrap();

            if value != M256::zero() {
                G_CALLSTIPEND.into()
            } else {
                Gas::zero()
            }
        }
        _ => Gas::zero(),
    }
}

/// Calculate the refunded gas.
pub fn gas_refund<M: Memory, P: Patch>(instruction: Instruction, state: &State<M, P>) -> isize {
    match instruction {
        Instruction::SSTORE => {
            let index: U256 = state.stack.peek(0).unwrap().into();
            let value = state.stack.peek(1).unwrap();
            let address = state.context.address;
            let current = state.account_state.storage_read(address, index).unwrap();

            // The legacy gas metering only takes into consideration the current state
            if !state.patch.has_reduced_sstore_gas_metering() {
                if current != M256::zero() && value == M256::zero() {
                    return R_SRESET;
                } else {
                    return 0;
                }
            }

            // Modern gas metering scheme (EIP-1283)
            if current == value {
                return 0;
            }

            // If RequireError is thrown here, that means that original storage was unset, hence defaulting to Zero.
            let original = state
                .account_state
                .storage_read_orig(address, index)
                .unwrap_or(M256::zero());

            // Refund counter
            let mut refund = 0;

            if original == current && value == M256::zero() {
                return R_NETSCLEAR;
            }

            if original != M256::zero() {
                if current == M256::zero() {
                    refund -= R_NETSCLEAR;
                } else if value == M256::zero() {
                    refund += R_NETSCLEAR;
                }
            }

            if original == value {
                if original == M256::zero() {
                    refund += R_NETSRESETCLEAR
                } else {
                    refund += R_NETSRESET
                }
            }

            refund
        }
        Instruction::SUICIDE => {
            if state.removed.contains(&state.context.address) {
                0
            } else {
                R_SUICIDE
            }
        }
        _ => 0,
    }
}

pub trait AddRefund {
    fn add_refund(self, refund: isize) -> Self;
}

impl AddRefund for Gas {
    fn add_refund(self, refund: isize) -> Self {
        let (refund, sign) = if refund < 0 {
            (0 - refund, true)
        } else {
            (refund, false)
        };

        if sign {
            self - Gas::from(refund as usize)
        } else {
            self + Gas::from(refund as usize)
        }
    }
}