vm_runtime.rs 14 KB

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