vm_runtime.rs 15 KB

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