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
//! Ceres Runtime
use crate::{storage::MemoryStorage, util, Error, Metadata, Result, Storage};
use ceres_executor::{Builder, Instance, Memory};
use ceres_sandbox::{Sandbox, Transaction};
use ceres_std::{Rc, String, ToString, Vec};
use core::cell::RefCell;
use parity_wasm::elements::Module;

/// Ceres Runtime
pub struct Runtime {
    pub sandbox: Rc<RefCell<Sandbox>>,
    instance: Instance<Sandbox>,
    pub metadata: Metadata,
    storage: Rc<RefCell<dyn Storage>>,
}

impl Runtime {
    /// Create runtime from contract
    pub fn from_contract(contract: &[u8]) -> Result<Runtime> {
        let meta = serde_json::from_str::<Metadata>(&String::from_utf8_lossy(contract))
            .map_err(|_| Error::DecodeContractFailed)?;

        Self::new(
            &hex::decode(&meta.source.wasm.as_bytes()[2..])
                .map_err(|_| Error::DecodeContractFailed)?,
            meta,
            Rc::new(RefCell::new(MemoryStorage::new())),
        )
    }

    /// Create runtime from contract
    pub fn from_contract_and_storage(
        contract: &[u8],
        storage: Rc<RefCell<impl Storage + 'static>>,
    ) -> Result<Runtime> {
        let meta = serde_json::from_str::<Metadata>(&String::from_utf8_lossy(contract))
            .map_err(|_| Error::DecodeContractFailed)?;

        Self::new(
            &hex::decode(&meta.source.wasm.as_bytes()[2..])
                .map_err(|_| Error::DecodeContractFailed)?,
            meta,
            storage,
        )
    }

    /// Create runtime from metadata and storage
    pub fn from_metadata_and_storage(
        meta: Metadata,
        storage: Rc<RefCell<impl Storage + 'static>>,
    ) -> Result<Runtime> {
        Self::new(
            &hex::decode(&meta.source.wasm.as_bytes()[2..])
                .map_err(|_| Error::DecodeContractFailed)?,
            meta,
            storage,
        )
    }

    /// New runtime
    pub fn new(
        b: &[u8],
        metadata: Metadata,
        storage: Rc<RefCell<impl Storage + 'static>>,
    ) -> Result<Runtime> {
        let mut el = Module::from_bytes(b).map_err(|_| Error::ParseWasmModuleFailed)?;
        if el.has_names_section() {
            el = match el.parse_names() {
                Ok(m) => m,
                Err((_, m)) => m,
            }
        }

        // Set memory
        let limit = util::scan_imports(&el).map_err(|_| Error::CalcuateMemoryLimitFailed)?;
        let mem = Memory::new(limit.0, limit.1).map_err(|_| Error::AllocMemoryFailed)?;

        // Get storage
        let storage_mut = storage.borrow_mut();
        let state =
            if let Some(state) = storage_mut.get(util::parse_code_hash(&metadata.source.hash)?) {
                state
            } else {
                storage_mut.new_state()
            };

        // Create Sandbox and Builder
        let sandbox = Rc::new(RefCell::new(Sandbox::new(mem, state)));

        // Construct interfaces
        cfg_if::cfg_if! {
            if #[cfg(not(feature = "std"))] {
                let mut builder = Builder::new().add_host_parcels(ceres_seal::pallet_contracts(
                    ceres_seal::NoRuntimeInterfaces,
                ));
            } else {
                let mut builder = Builder::new().add_host_parcels(ceres_seal::pallet_contracts(
                    ceres_ri::Instance
                ));
            }
        }

        // **Note**
        //
        // The memory is `cloned()`, trying using one memory.
        builder.add_memory("env", "memory", sandbox.borrow().mem());

        // Create instance
        let instance = Instance::new(
            &el.to_bytes()
                .map_err(|error| Error::SerializeFailed { error })?,
            &builder,
            &mut sandbox.borrow_mut(),
        )
        .map_err(|error| Error::InitModuleFailed { error })?;

        drop(storage_mut);
        Ok(Runtime {
            sandbox,
            instance,
            metadata,
            storage,
        })
    }

    /// Deploy contract
    pub fn deploy(&mut self, method: &str, args: &[&str], tx: Option<Transaction>) -> Result<()> {
        if let Some(tx) = tx {
            self.sandbox.borrow_mut().tx = tx;
        }

        let constructors = self.metadata.constructors();
        let (selector, tys) = constructors.get(method).ok_or(Error::GetMethodFailed {
            name: method.to_string(),
        })?;

        let mut bm = self.sandbox.borrow_mut();
        bm.input = Some(util::parse_args(
            selector,
            args,
            tys.iter().map(|ty| ty.1).collect(),
        )?);
        self.instance
            .invoke("deploy", &[], &mut bm)
            .map_err(|error| Error::DeployContractFailed { error })?;

        Ok(())
    }

    /// Call contract
    pub fn call(
        &mut self,
        method: &str,
        args: &[&str],
        tx: Option<Transaction>,
    ) -> Result<Vec<u8>> {
        if let Some(tx) = tx {
            self.sandbox.borrow_mut().tx = tx;
        }

        let messages = self.metadata.messages();
        let (selector, tys) = messages.get(method).ok_or(Error::GetMethodFailed {
            name: method.to_string(),
        })?;

        let mut bm = self.sandbox.borrow_mut();
        bm.input = Some(util::parse_args(
            selector,
            args,
            tys.iter().map(|ty| ty.1).collect(),
        )?);

        let res = self.instance.invoke("call", &[], &mut bm);
        if let Some(ret) = bm.ret.take() {
            return Ok(ret);
        } else {
            res.map_err(|error| Error::CallContractFailed { error })?;
        }

        Ok(vec![])
    }

    /// Flush storage
    pub fn flush(&mut self) -> Result<()> {
        self.storage.borrow_mut().set(
            util::parse_code_hash(&self.metadata.source.hash)?,
            self.sandbox.borrow().state.clone(),
        )?;

        Ok(())
    }
}