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
use super::Interpreter;
use crate::consts::*;
use crate::context::Context;
use crate::error::InterpreterError;
use crate::interpreter::RuntimeBalances;
use crate::storage::InterpreterStorage;

use fuel_tx::CheckedTransaction;
use fuel_types::bytes::SizedBytes;
use fuel_types::Word;

use std::io;

impl<S> Interpreter<S> {
    /// Initialize the VM with a given transaction
    fn _init(&mut self, tx: CheckedTransaction) -> Result<(), InterpreterError> {
        self.tx = tx;

        self.frames.clear();
        self.receipts.clear();

        // Optimized for memset
        self.registers.iter_mut().for_each(|r| *r = 0);

        self.registers[REG_ONE] = 1;
        self.registers[REG_SSP] = 0;

        // Set heap area
        self.registers[REG_HP] = VM_MAX_RAM - 1;

        self.push_stack(self.transaction().id().as_ref())
            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;

        RuntimeBalances::from(&self.tx).to_vm(self);

        let tx_size = self.transaction().serialized_size() as Word;

        self.registers[REG_GGAS] = self.transaction().gas_limit();
        self.registers[REG_CGAS] = self.transaction().gas_limit();

        self.push_stack(&tx_size.to_be_bytes())
            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;

        let tx = self.tx.tx_bytes();

        self.push_stack(tx.as_slice())
            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;

        self.registers[REG_SP] = self.registers[REG_SSP];

        Ok(())
    }

    /// Initialize the VM for a predicate context
    pub fn init_predicate(&mut self, mut tx: CheckedTransaction) -> bool {
        self.context = Context::Predicate {
            program: Default::default(),
        };

        tx.prepare_init_predicate();

        self._init(tx).is_ok()
    }
}

impl<S> Interpreter<S>
where
    S: InterpreterStorage,
{
    /// Initialize the VM with a given transaction, backed by a storage provider that allows
    /// execution of contract opcodes.
    ///
    /// For predicate verification, check [`Self::init_predicate`]
    pub fn init_script(&mut self, mut tx: CheckedTransaction) -> Result<(), InterpreterError> {
        let block_height = self.storage.block_height().map_err(InterpreterError::from_io)?;

        self.context = Context::Script { block_height };

        tx.prepare_init_script()?;

        self._init(tx)
    }
}