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
use super::{
    super::context::OriginInfo, executable::make_executable, run_executable,
    FrameLocal, FrameStackAction, RuntimeRes,
};
use crate::{
    machine::Machine,
    state::State,
    substate::{cleanup_mode, Substate},
};

use cfx_statedb::Result as DbResult;
use cfx_types::{Address, AddressSpaceUtil, AddressWithSpace, Space};
use cfx_vm_types::{
    ActionParams, ActionValue, CallType, CreateType, Env, Spec,
};
use primitives::{storage::STORAGE_LAYOUT_REGULAR_V0, StorageLayout};

/// A frame has not yet been executed, with all the necessary information to
/// initiate and carry out the execution of the frame.
pub struct FreshFrame<'a> {
    /// The input parameters for the frame.
    params: ActionParams,

    /// The local data associated with this frame.
    frame_local: FrameLocal<'a>,
}

impl<'a> FreshFrame<'a> {
    pub fn new(
        params: ActionParams, env: &'a Env, machine: &'a Machine,
        spec: &'a Spec, depth: usize, parent_static_flag: bool,
    ) -> Self {
        let is_create = params.create_type != CreateType::None;
        let create_address = is_create.then_some(params.code_address);
        trace!(
            "Executive::{:?}(params={:?}) self.env={:?}, parent_static={}",
            if is_create { "create" } else { "call" },
            params,
            env,
            parent_static_flag,
        );

        let static_flag =
            parent_static_flag || params.call_type == CallType::StaticCall;

        let substate = Substate::new();
        let origin = OriginInfo::from(&params);

        let frame_local = FrameLocal::new(
            params.space,
            env,
            machine,
            spec,
            depth,
            origin,
            substate,
            create_address,
            static_flag,
        );
        FreshFrame {
            frame_local,
            params,
        }
    }

    /// Initializes and executes a frame, along with runtime resources shared
    /// across all frames.
    pub(super) fn init_and_exec(
        self, resources: &mut RuntimeRes<'a>,
    ) -> DbResult<FrameStackAction<'a>> {
        let FreshFrame {
            mut frame_local,
            params,
        } = self;
        let is_create = frame_local.create_address.is_some();

        if is_create {
            debug!(
                "CallCreateExecutiveKind::ExecCreate: contract_addr = {:?}",
                params.address
            );
            resources.tracer.record_create(&params);
        } else {
            resources.tracer.record_call(&params);
        }

        // Make checkpoint for this executive, callstack is always maintained
        // with checkpoint.
        resources.state.checkpoint();

        let contract_address = frame_local.origin.recipient().clone();
        resources
            .callstack
            .push(contract_address.with_space(frame_local.space), is_create);

        // Pre execution: transfer value and init contract.
        let spec = &frame_local.spec;
        if is_create {
            transfer_exec_balance_and_init_contract(
                &params,
                spec,
                resources.state,
                // It is a bug in the Parity version.
                &mut frame_local.substate,
                Some(STORAGE_LAYOUT_REGULAR_V0),
            )?
        } else {
            transfer_balance(
                &params,
                spec,
                resources.state,
                &mut frame_local.substate,
            )?
        };

        let executable =
            make_executable(&frame_local, params, resources.tracer);
        run_executable(executable, frame_local, resources)
    }
}

fn transfer_balance(
    params: &ActionParams, spec: &Spec, state: &mut State,
    substate: &mut Substate,
) -> DbResult<()> {
    let sender = AddressWithSpace {
        address: params.sender,
        space: params.space,
    };
    let receiver = AddressWithSpace {
        address: params.address,
        space: params.space,
    };
    if let ActionValue::Transfer(val) = params.value {
        state.transfer_balance(
            &sender,
            &receiver,
            &val,
            cleanup_mode(substate, &spec),
        )?;
    }

    Ok(())
}

fn transfer_exec_balance_and_init_contract(
    params: &ActionParams, spec: &Spec, state: &mut State,
    substate: &mut Substate, storage_layout: Option<StorageLayout>,
) -> DbResult<()> {
    let sender = AddressWithSpace {
        address: params.sender,
        space: params.space,
    };
    let receiver = AddressWithSpace {
        address: params.address,
        space: params.space,
    };
    if let ActionValue::Transfer(val) = params.value {
        // It is possible to first send money to a pre-calculated
        // contract address.
        let prev_balance = state.balance(&receiver)?;
        state.sub_balance(&sender, &val, &mut cleanup_mode(substate, &spec))?;
        let admin = if params.space == Space::Native {
            params.original_sender
        } else {
            Address::zero()
        };
        state.new_contract_with_admin(
            &receiver,
            &admin,
            val.saturating_add(prev_balance),
            storage_layout,
            spec.cip107,
        )?;
    } else {
        // In contract creation, the `params.value` should never be
        // `Apparent`.
        unreachable!();
    }

    Ok(())
}