vm_runtime.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. cell::{Cell, RefCell},
  20. sync::Arc,
  21. };
  22. use darkfi_sdk::{crypto::ContractId, entrypoint};
  23. use log::{debug, info};
  24. use wasmer::{
  25. imports, wasmparser::Operator, AsStoreRef, CompilerConfig, Function, FunctionEnv, Instance,
  26. Memory, MemoryView, Module, Pages, Store, Value, WASM_PAGE_SIZE,
  27. };
  28. use wasmer_compiler_singlepass::Singlepass;
  29. use wasmer_middlewares::{
  30. metering::{get_remaining_points, MeteringPoints},
  31. Metering,
  32. };
  33. use super::{import, import::db::DbHandle, memory::MemoryManipulation};
  34. use crate::{blockchain::Blockchain, Error, Result};
  35. /// Name of the wasm linear memory in our guest module
  36. const MEMORY: &str = "memory";
  37. /// Gas limit for a contract
  38. const GAS_LIMIT: u64 = 200000;
  39. #[derive(Clone, Copy)]
  40. pub enum ContractSection {
  41. /// Setup function of a contract
  42. Deploy,
  43. /// Entrypoint function of a contract
  44. Exec,
  45. /// Apply function of a contract
  46. Update,
  47. Null,
  48. }
  49. impl ContractSection {
  50. fn name(&self) -> &str {
  51. match self {
  52. Self::Deploy => "__initialize",
  53. Self::Exec => "__entrypoint",
  54. Self::Update => "__update",
  55. Self::Null => unreachable!(),
  56. }
  57. }
  58. }
  59. /// The wasm vm runtime instantiated for every smart contract that runs.
  60. pub struct Env {
  61. /// Blockchain access
  62. pub blockchain: Blockchain,
  63. /// sled tree handles used with `db_*`
  64. pub db_handles: RefCell<Vec<DbHandle>>,
  65. /// The contract ID being executed
  66. pub contract_id: ContractId,
  67. /// The contract section being executed
  68. pub contract_section: ContractSection,
  69. /// State update produced by a smart contract function call
  70. pub contract_return_data: Cell<Option<Vec<u8>>>,
  71. /// Logs produced by the contract
  72. pub logs: RefCell<Vec<String>>,
  73. /// Direct memory access to the VM
  74. pub memory: Option<Memory>,
  75. }
  76. impl Env {
  77. /// Provide safe access to the memory
  78. /// (it must be initialized before it can be used)
  79. ///
  80. /// // ctx: FunctionEnvMut<Env>
  81. /// let env = ctx.data();
  82. /// let memory = env.memory_view(&ctx);
  83. ///
  84. pub fn memory_view<'a>(&'a self, store: &'a impl AsStoreRef) -> MemoryView<'a> {
  85. self.memory().view(store)
  86. }
  87. /// Get memory, that needs to have been set fist
  88. pub fn memory(&self) -> &Memory {
  89. self.memory.as_ref().unwrap()
  90. }
  91. }
  92. pub struct Runtime {
  93. pub instance: Instance,
  94. pub store: Store,
  95. pub ctx: FunctionEnv<Env>,
  96. }
  97. impl Runtime {
  98. /// Create a new wasm runtime instance that contains the given wasm module.
  99. pub fn new(wasm_bytes: &[u8], blockchain: Blockchain, contract_id: ContractId) -> Result<Self> {
  100. info!(target: "warm_runtime::new", "Instantiating a new runtime");
  101. // This function will be called for each `Operator` encountered during
  102. // the wasm module execution. It should return the cost of the operator
  103. // that it received as its first argument.
  104. // https://docs.rs/wasmparser/latest/wasmparser/enum.Operator.html
  105. let cost_function = |operator: &Operator| -> u64 {
  106. match operator {
  107. Operator::LocalGet { .. } => 1,
  108. Operator::I32Const { .. } => 1,
  109. Operator::I32Add { .. } => 2,
  110. _ => 0,
  111. }
  112. };
  113. // `Metering` needs to be conigured with a limit and a cost function.
  114. // For each `Operator`, the metering middleware will call the cost
  115. // function and subtract the cost from the remaining points.
  116. let metering = Arc::new(Metering::new(GAS_LIMIT, cost_function));
  117. // Define the compiler and middleware, engine, and store
  118. let mut compiler_config = Singlepass::new();
  119. compiler_config.push_middleware(metering);
  120. let mut store = Store::new(compiler_config);
  121. debug!(target: "wasm_runtime::new", "Compiling module");
  122. let module = Module::new(&store, wasm_bytes)?;
  123. // Initialize data
  124. let db_handles = RefCell::new(vec![]);
  125. let logs = RefCell::new(vec![]);
  126. debug!(target: "wasm_runtime::new", "Importing functions");
  127. let ctx = FunctionEnv::new(
  128. &mut store,
  129. Env {
  130. blockchain,
  131. db_handles,
  132. contract_id,
  133. contract_section: ContractSection::Null,
  134. contract_return_data: Cell::new(None),
  135. logs,
  136. memory: None,
  137. },
  138. );
  139. let imports = imports! {
  140. "env" => {
  141. "drk_log_" => Function::new_typed_with_env(
  142. &mut store,
  143. &ctx,
  144. import::util::drk_log,
  145. ),
  146. "set_return_data_" => Function::new_typed_with_env(
  147. &mut store,
  148. &ctx,
  149. import::util::set_return_data,
  150. ),
  151. "db_init_" => Function::new_typed_with_env(
  152. &mut store,
  153. &ctx,
  154. import::db::db_init,
  155. ),
  156. "db_lookup_" => Function::new_typed_with_env(
  157. &mut store,
  158. &ctx,
  159. import::db::db_lookup,
  160. ),
  161. "db_get_" => Function::new_typed_with_env(
  162. &mut store,
  163. &ctx,
  164. import::db::db_get,
  165. ),
  166. "db_begin_tx_" => Function::new_typed_with_env(
  167. &mut store,
  168. &ctx,
  169. import::db::db_begin_tx,
  170. ),
  171. "db_set_" => Function::new_typed_with_env(
  172. &mut store,
  173. &ctx,
  174. import::db::db_set,
  175. ),
  176. "db_end_tx_" => Function::new_typed_with_env(
  177. &mut store,
  178. &ctx,
  179. import::db::db_end_tx,
  180. ),
  181. }
  182. };
  183. debug!(target: "wasm_runtime::new", "Instantiating module");
  184. let instance = Instance::new(&mut store, &module, &imports)?;
  185. let mut env_mut = ctx.as_mut(&mut store);
  186. env_mut.memory = Some(instance.exports.get_with_generics(MEMORY)?);
  187. Ok(Self { instance, store, ctx })
  188. }
  189. fn call(&mut self, section: ContractSection, payload: &[u8]) -> Result<Vec<u8>> {
  190. debug!(target: "runtime", "Calling {} method", section.name());
  191. let mut env_mut = self.ctx.as_mut(&mut self.store);
  192. env_mut.contract_section = section;
  193. assert!(env_mut.contract_return_data.take().is_none());
  194. env_mut.contract_return_data.set(None);
  195. // Serialize the payload for the format the wasm runtime is expecting.
  196. let payload = Self::serialize_payload(&env_mut.contract_id, payload);
  197. // Allocate enough memory for the payload and copy it into the memory.
  198. let pages_required = payload.len() / WASM_PAGE_SIZE + 1;
  199. self.set_memory_page_size(pages_required as u32)?;
  200. self.copy_to_memory(&payload)?;
  201. debug!(target: "runtime", "Getting initialize function");
  202. let entrypoint = self.instance.exports.get_function(section.name())?;
  203. debug!(target: "runtime", "Executing wasm");
  204. let ret = match entrypoint.call(&mut self.store, &[Value::I32(0 as i32)]) {
  205. Ok(retvals) => {
  206. self.print_logs();
  207. debug!(target: "runtime", "{}", self.gas_info());
  208. retvals
  209. }
  210. Err(e) => {
  211. self.print_logs();
  212. debug!(target: "runtime", "{}", self.gas_info());
  213. // WasmerRuntimeError panics are handled here. Return from run() immediately.
  214. return Err(e.into())
  215. }
  216. };
  217. debug!(target: "runtime", "wasm executed successfully");
  218. debug!(target: "runtime", "Contract returned: {:?}", ret[0]);
  219. let mut env_mut = self.ctx.as_mut(&mut self.store);
  220. env_mut.contract_section = ContractSection::Null;
  221. let retdata = match env_mut.contract_return_data.take() {
  222. Some(retdata) => retdata,
  223. None => Vec::new()
  224. };
  225. let retval = match ret[0] {
  226. Value::I64(v) => v as u64,
  227. _ => unreachable!(),
  228. };
  229. match retval {
  230. entrypoint::SUCCESS => Ok(retdata),
  231. // FIXME: we should be able to see the error returned from the contract
  232. // We can put sdk::Error inside of this.
  233. _ => Err(Error::ContractInitError(retval)),
  234. }
  235. }
  236. /// This function runs when a smart contract is initially deployed, or re-deployed.
  237. /// The runtime will look for an [`INITIALIZE`] symbol in the wasm code, and execute
  238. /// it if found. Optionally, it is possible to pass in a payload for any kind of special
  239. /// instructions the developer wants to manage in the initialize function.
  240. /// This process is supposed to set up the sled db trees for storing the smart contract
  241. /// state, and it can create, delete, modify, read, and write to databases it's allowed to.
  242. /// The permissions for this are handled by the `ContractId` in the sled db API so we
  243. /// assume that the contract is only able to do write operations on its own sled trees.
  244. pub fn deploy(&mut self, payload: &[u8]) -> Result<()> {
  245. let _ = self.call(ContractSection::Deploy, payload)?;
  246. Ok(())
  247. }
  248. /// This funcion runs when someone wants to execute a smart contract.
  249. /// The runtime will look for an [`ENTRYPOINT`] symbol in the wasm code, and
  250. /// execute it if found. A payload is also passed as an instruction that can
  251. /// be used inside the vm by the runtime.
  252. pub fn exec(&mut self, payload: &[u8]) -> Result<Vec<u8>> {
  253. self.call(ContractSection::Exec, payload)
  254. }
  255. /// This function runs after successful execution of [`exec`] and tries to
  256. /// apply the state change to the sled databases.
  257. /// The runtime will lok for an [`UPDATE`] symbol in the wasm code, and execute
  258. /// it if found. The function does not take an arbitrary payload, but just takes
  259. /// a state update from `env` and passes it into the wasm runtime.
  260. pub fn apply(&mut self, update: &[u8]) -> Result<()> {
  261. let _ = self.call(ContractSection::Update, update)?;
  262. Ok(())
  263. }
  264. fn print_logs(&self) {
  265. let logs = self.ctx.as_ref(&self.store).logs.borrow();
  266. for msg in logs.iter() {
  267. debug!(target: "runtime", "Contract log: {}", msg);
  268. }
  269. }
  270. fn gas_info(&mut self) -> String {
  271. let remaining_points = get_remaining_points(&mut self.store, &self.instance);
  272. match remaining_points {
  273. MeteringPoints::Remaining(rem) => {
  274. format!("Gas used: {}/{}", GAS_LIMIT - rem, GAS_LIMIT)
  275. }
  276. MeteringPoints::Exhausted => {
  277. format!("Gas fully exhausted: {}/{}", GAS_LIMIT + 1, GAS_LIMIT)
  278. }
  279. }
  280. }
  281. /// Set the memory page size
  282. fn set_memory_page_size(&mut self, pages: u32) -> Result<()> {
  283. // Grab memory by value
  284. let memory = self.take_memory();
  285. // Modify the memory
  286. memory.grow(&mut self.store, Pages(pages))?;
  287. // Replace the memory back again
  288. self.ctx.as_mut(&mut self.store).memory = Some(memory);
  289. Ok(())
  290. }
  291. /// Take Memory by value. Needed to modify the Memory object
  292. /// Will panic if memory isn't set.
  293. fn take_memory(&mut self) -> Memory {
  294. let env_memory = &mut self.ctx.as_mut(&mut self.store).memory;
  295. let memory = std::mem::replace(env_memory, None);
  296. memory.expect("memory should be set")
  297. }
  298. /// Copy payload to the start of the memory
  299. fn copy_to_memory(&self, payload: &[u8]) -> Result<()> {
  300. // TODO: Maybe should write to first zero memory and return the pointer/offset?
  301. // Get the memory view
  302. let env = self.ctx.as_ref(&self.store);
  303. let memory_view = env.memory_view(&self.store);
  304. memory_view.write_slice(payload, 0)
  305. }
  306. /// Serialize contract payload to the format accepted by the runtime functions.
  307. /// We keep the same payload as a slice of bytes, and prepend it with a
  308. /// little-endian u64 to tell the payload's length.
  309. fn serialize_payload(cid: &ContractId, payload: &[u8]) -> Vec<u8> {
  310. let ser_cid = cid.to_bytes();
  311. let payload_len = payload.len();
  312. let mut out = Vec::with_capacity(ser_cid.len() + 8 + payload_len);
  313. out.extend_from_slice(&ser_cid);
  314. out.extend_from_slice(&(payload_len as u64).to_le_bytes());
  315. out.extend_from_slice(payload);
  316. out
  317. }
  318. }