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
//! Runtime lifecycle related functionality.

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

#[cfg(not(feature = "std"))] use alloc::rc::Rc;
#[cfg(feature = "std")] use std::rc::Rc;

use bigint::{U256, M256, Gas, Address};
use errors::{RequireError, OnChainError};
use commit::AccountState;
use ::{Memory, Patch, AccountPatch};
use super::{Machine, MachineStatus, GasUsage};
use super::util::copy_into_memory_apply;
use super::cost::code_deposit_gas;

/// # Lifecycle of a Machine
///
/// When a new non-invoked transaction is created, `initialize_call`
/// or `initialize_create` should be called. After this, the machine
/// can be stepped as normal. When the machine meets a CALL/CALLCODE
/// or CREATE instruction, a sub-machine will be created. This
/// submachine should first call `invoke_call` or
/// `invoke_create`. After the submachine is finished, it should call
/// `apply_sub`. When the non-invoked transaction is finished, it
/// should first call `code_deposit` if it is a contract creation
/// transaction. After that, it should call `finalize`.

impl<M: Memory + Default, P: Patch> Machine<M, P> {
    /// Initialize a MessageCall transaction.
    ///
    /// ### Panic
    /// Requires caller of the transaction to be committed.
    pub fn initialize_call(&mut self, preclaimed_value: U256) -> Result<(), RequireError> {
        self.state.account_state.require(self.state.context.address)?;

        if !self.state.context.is_system {
            self.state.account_state.decrease_balance(self.state.context.caller, preclaimed_value);
            self.state.account_state.decrease_balance(self.state.context.caller, self.state.context.value);
        }
        self.state.account_state.increase_balance(self.state.context.address, self.state.context.value);

        Ok(())
    }

    /// Initialize the runtime as a call from a CALL or CALLCODE opcode.
    ///
    /// ### Panic
    /// Requires caller of the CALL/CALLCODE opcode to be committed.
    pub fn invoke_call(&mut self) -> Result<(), RequireError> {
        self.state.account_state.require(self.state.context.address)?;

        if !self.state.context.is_system {
            self.state.account_state.decrease_balance(self.state.context.caller, self.state.context.value);
        }
        self.state.account_state.increase_balance(self.state.context.address, self.state.context.value);

        Ok(())
    }

    /// Initialize a ContractCreation transaction.
    ///
    /// ### Panic
    /// Requires caller of the transaction to be committed.
    pub fn initialize_create(&mut self, preclaimed_value: U256) -> Result<(), RequireError> {
        self.state.account_state.require(self.state.context.address)?;

        if !self.state.context.is_system {
            self.state.account_state.decrease_balance(self.state.context.caller, preclaimed_value);
            self.state.account_state.decrease_balance(self.state.context.caller, self.state.context.value);
        }
        self.state.account_state.create(self.state.context.address, self.state.context.value).unwrap();

        Ok(())
    }

    /// Initialize the runtime as a call from a CREATE opcode.
    ///
    /// ### Panic
    /// Requires caller of the CREATE opcode to be committed.
    pub fn invoke_create(&mut self) -> Result<(), RequireError> {
        self.state.account_state.require(self.state.context.address)?;

        if !self.state.context.is_system {
            self.state.account_state.decrease_balance(self.state.context.caller, self.state.context.value);
        }
        self.state.account_state.create(self.state.context.address, self.state.context.value).unwrap();

        Ok(())
    }

    /// Deposit code for a ContractCreation transaction or a CREATE opcode.
    #[cfg_attr(feature = "cargo-clippy", allow(collapsible_if))]
    pub fn code_deposit(&mut self) {
        match self.status() {
            MachineStatus::ExitedOk | MachineStatus::ExitedErr(_) => (),
            _ => panic!(),
        }

        if P::code_deposit_limit().is_some()  {
            if self.state.out.len() > P::code_deposit_limit().unwrap() {
                reset_error_hard!(self, OnChainError::EmptyGas);
                return;
            }
        }

        let deposit_cost = code_deposit_gas(self.state.out.len());
        if deposit_cost > self.state.available_gas() {
            if !P::force_code_deposit() {
                reset_error_hard!(self, OnChainError::EmptyGas);
            } else {
                self.state.account_state.code_deposit(self.state.context.address, Rc::new(Vec::new()));
            }
        } else {
            self.state.used_gas += deposit_cost;
            self.state.account_state.code_deposit(self.state.context.address,
                                                  self.state.out.clone());
        }
    }

    /// Finalize a transaction. This should not be used when invoked
    /// by an opcode and should only be used in the top level.
    ///
    /// ### Panic
    /// Requires caller of the transaction to be committed.
    pub fn finalize_transaction(&mut self, beneficiary: Address, real_used_gas: Gas, preclaimed_value: U256, fresh_account_state: &AccountState<P::Account>) -> Result<(), RequireError> {
        self.state.account_state.require(self.state.context.address)?;
        if !P::Account::allow_partial_change() {
            self.state.account_state.require(beneficiary)?;
        }

        match self.status() {
            MachineStatus::ExitedOk => {
                // Requires removed accounts to exist.
                for address in &self.state.removed {
                    self.state.account_state.require(*address)?;
                }
            },
            MachineStatus::ExitedErr(_) => {
                // If exited with error, reset all changes.
                self.state.account_state = fresh_account_state.clone();
                self.state.removed = Vec::new();
                if !self.state.context.is_system {
                    self.state.account_state.decrease_balance(self.state.context.caller, preclaimed_value);
                }
            },
            _ => panic!(),
        }

        let gas_dec = real_used_gas * self.state.context.gas_price;
        if !self.state.context.is_system {
            self.state.account_state.increase_balance(self.state.context.caller, preclaimed_value);
            self.state.account_state.decrease_balance(self.state.context.caller, gas_dec.into());

            // Apply miner rewards
            self.state.account_state.increase_balance(beneficiary, gas_dec.into());
        }

        for address in &self.state.removed {
            self.state.account_state.remove(*address).unwrap();
        }

        match self.status() {
            MachineStatus::ExitedOk => Ok(()),
            MachineStatus::ExitedErr(_) => Ok(()),
            _ => panic!(),
        }
    }

    /// Finalize a context execution. This should not be used when
    /// invoked by an opcode and should only be used in the top level.
    ///
    /// ### Panic
    /// Requires caller of the transaction to be committed.
    pub fn finalize_context(&mut self, fresh_account_state: &AccountState<P::Account>) {
        match self.status() {
            MachineStatus::ExitedOk => (),
            MachineStatus::ExitedErr(_) => {
                self.state.account_state = fresh_account_state.clone();
                self.state.removed = Vec::new();
            },
            _ => panic!(),
        }
    }

    /// Apply a sub runtime into the current runtime. This sub runtime
    /// should have been created by the current runtime's `derive`
    /// function. Depending whether the current runtime is invoking a
    /// ContractCreation or MessageCall instruction, it will apply
    /// various states back.
    pub fn apply_sub(&mut self, sub: Machine<M, P>) {
        #[cfg(feature = "std")]
        use std::mem::swap;

        #[cfg(not(feature = "std"))]
        use core::mem::swap;

        let mut status = MachineStatus::Running;
        swap(&mut status, &mut self.status);
        match status {
            MachineStatus::InvokeCreate(_) => {
                self.apply_create(sub);
            },
            MachineStatus::InvokeCall(_, (out_start, out_len)) => {
                self.apply_call(sub, out_start, out_len);
            },
            _ => panic!(),
        }
    }

    fn apply_create(&mut self, mut sub: Machine<M, P>) {
        sub.code_deposit();

        let sub_total_used_gas = sub.state.total_used_gas();

        self.state.logs.append(&mut sub.state.logs);
        self.state.used_gas += sub_total_used_gas;
        self.state.refunded_gas = self.state.refunded_gas + sub.state.refunded_gas;
        self.state.ret = sub.state.out.clone();

        match sub.status() {
            MachineStatus::ExitedOk => {
                self.state.account_state = sub.state.account_state;
                self.state.removed = sub.state.removed;
            },
            MachineStatus::ExitedErr(_) => {
                self.state.stack.pop().unwrap();
                self.state.stack.push(M256::zero()).unwrap();
            },
            _ => panic!(),
        }
    }

    fn apply_call(&mut self, mut sub: Machine<M, P>, out_start: U256, out_len: U256) {
        let sub_total_used_gas = sub.state.total_used_gas();

        self.state.logs.append(&mut sub.state.logs);
        self.state.used_gas += sub_total_used_gas;
        self.state.refunded_gas = self.state.refunded_gas + sub.state.refunded_gas;

        copy_into_memory_apply(&mut self.state.memory, sub.state.out.as_slice(),
                               out_start, out_len);

        match sub.status() {
            MachineStatus::ExitedOk => {
                self.state.account_state = sub.state.account_state;
                self.state.removed = sub.state.removed;
                self.state.ret = Rc::new(Vec::new());
            },
            MachineStatus::ExitedErr(_) => {
                self.state.stack.pop().unwrap();
                self.state.stack.push(M256::zero()).unwrap();
                self.state.ret = sub.state.out.clone();
            },
            _ => panic!(),
        }
    }
}