vm_runtime.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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, error, 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::BlockchainOverlayPtr, 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 = 200000000;
  40. /// The hardcoded db name for the zkas circuits database tree
  41. pub const SMART_CONTRACT_ZKAS_DB_NAME: &str = "_zkas";
  42. #[derive(Clone, Copy, PartialEq)]
  43. pub enum ContractSection {
  44. /// Setup function of a contract
  45. Deploy,
  46. /// Entrypoint function of a contract
  47. Exec,
  48. /// Apply function of a contract
  49. Update,
  50. /// Metadata
  51. Metadata,
  52. /// Placeholder state before any initialization
  53. Null,
  54. }
  55. impl ContractSection {
  56. pub fn name(&self) -> &str {
  57. match self {
  58. Self::Deploy => "__initialize",
  59. Self::Exec => "__entrypoint",
  60. Self::Update => "__update",
  61. Self::Metadata => "__metadata",
  62. Self::Null => unreachable!(),
  63. }
  64. }
  65. }
  66. /// The wasm vm runtime instantiated for every smart contract that runs.
  67. pub struct Env {
  68. /// Blockchain overlay access
  69. pub blockchain: BlockchainOverlayPtr,
  70. /// sled tree handles used with `db_*`
  71. pub db_handles: RefCell<Vec<DbHandle>>,
  72. /// sled tree batches, indexed the same as `db_handles`.
  73. pub db_batches: RefCell<Vec<import::util::Batch>>,
  74. /// The contract ID being executed
  75. pub contract_id: ContractId,
  76. /// The compiled wasm bincode being executed,
  77. pub contract_bincode: Vec<u8>,
  78. /// The contract section being executed
  79. pub contract_section: ContractSection,
  80. /// State update produced by a smart contract function call
  81. pub contract_return_data: Cell<Option<Vec<u8>>>,
  82. /// Logs produced by the contract
  83. pub logs: RefCell<Vec<String>>,
  84. /// Direct memory access to the VM
  85. pub memory: Option<Memory>,
  86. /// Object store for transferring memory from the host to VM
  87. pub objects: RefCell<Vec<Vec<u8>>>,
  88. }
  89. impl Env {
  90. /// Provide safe access to the memory
  91. /// (it must be initialized before it can be used)
  92. ///
  93. /// // ctx: FunctionEnvMut<Env>
  94. /// let env = ctx.data();
  95. /// let memory = env.memory_view(&ctx);
  96. ///
  97. pub fn memory_view<'a>(&'a self, store: &'a impl AsStoreRef) -> MemoryView<'a> {
  98. self.memory().view(store)
  99. }
  100. /// Get memory, that needs to have been set fist
  101. pub fn memory(&self) -> &Memory {
  102. self.memory.as_ref().unwrap()
  103. }
  104. }
  105. pub struct Runtime {
  106. pub instance: Instance,
  107. pub store: Store,
  108. pub ctx: FunctionEnv<Env>,
  109. }
  110. impl Runtime {
  111. /// Create a new wasm runtime instance that contains the given wasm module.
  112. pub fn new(
  113. wasm_bytes: &[u8],
  114. blockchain: BlockchainOverlayPtr,
  115. contract_id: ContractId,
  116. ) -> Result<Self> {
  117. info!(target: "runtime::vm_runtime", "Instantiating a new runtime");
  118. // TODO: Add necessary operators
  119. // This function will be called for each `Operator` encountered during
  120. // the wasm module execution. It should return the cost of the operator
  121. // that it received as its first argument.
  122. // https://docs.rs/wasmparser/latest/wasmparser/enum.Operator.html
  123. let cost_function = |operator: &Operator| -> u64 {
  124. match operator {
  125. Operator::LocalGet { .. } => 1,
  126. Operator::I32Const { .. } => 1,
  127. Operator::I32Add { .. } => 2,
  128. _ => 0,
  129. }
  130. };
  131. // `Metering` needs to be conigured with a limit and a cost function.
  132. // For each `Operator`, the metering middleware will call the cost
  133. // function and subtract the cost from the remaining points.
  134. let metering = Arc::new(Metering::new(GAS_LIMIT, cost_function));
  135. // Define the compiler and middleware, engine, and store
  136. let mut compiler_config = Singlepass::new();
  137. compiler_config.push_middleware(metering);
  138. let mut store = Store::new(compiler_config);
  139. debug!(target: "runtime::vm_runtime", "Compiling module");
  140. let module = Module::new(&store, wasm_bytes)?;
  141. // Initialize data
  142. let db_handles = RefCell::new(vec![]);
  143. let db_batches = RefCell::new(vec![]);
  144. let logs = RefCell::new(vec![]);
  145. debug!(target: "runtime::vm_runtime", "Importing functions");
  146. let ctx = FunctionEnv::new(
  147. &mut store,
  148. Env {
  149. blockchain,
  150. db_handles,
  151. db_batches,
  152. contract_id,
  153. contract_bincode: wasm_bytes.to_vec(),
  154. contract_section: ContractSection::Null,
  155. contract_return_data: Cell::new(None),
  156. logs,
  157. memory: None,
  158. objects: RefCell::new(vec![]),
  159. },
  160. );
  161. let imports = imports! {
  162. "env" => {
  163. "drk_log_" => Function::new_typed_with_env(
  164. &mut store,
  165. &ctx,
  166. import::util::drk_log,
  167. ),
  168. "set_return_data_" => Function::new_typed_with_env(
  169. &mut store,
  170. &ctx,
  171. import::util::set_return_data,
  172. ),
  173. "db_init_" => Function::new_typed_with_env(
  174. &mut store,
  175. &ctx,
  176. import::db::db_init,
  177. ),
  178. "db_lookup_" => Function::new_typed_with_env(
  179. &mut store,
  180. &ctx,
  181. import::db::db_lookup,
  182. ),
  183. "db_get_" => Function::new_typed_with_env(
  184. &mut store,
  185. &ctx,
  186. import::db::db_get,
  187. ),
  188. "db_contains_key_" => Function::new_typed_with_env(
  189. &mut store,
  190. &ctx,
  191. import::db::db_contains_key,
  192. ),
  193. "db_set_" => Function::new_typed_with_env(
  194. &mut store,
  195. &ctx,
  196. import::db::db_set,
  197. ),
  198. "db_del_" => Function::new_typed_with_env(
  199. &mut store,
  200. &ctx,
  201. import::db::db_del,
  202. ),
  203. "zkas_db_set_" => Function::new_typed_with_env(
  204. &mut store,
  205. &ctx,
  206. import::db::zkas_db_set,
  207. ),
  208. "put_object_bytes_" => Function::new_typed_with_env(
  209. &mut store,
  210. &ctx,
  211. import::util::put_object_bytes,
  212. ),
  213. "get_object_bytes_" => Function::new_typed_with_env(
  214. &mut store,
  215. &ctx,
  216. import::util::get_object_bytes,
  217. ),
  218. "get_object_size_" => Function::new_typed_with_env(
  219. &mut store,
  220. &ctx,
  221. import::util::get_object_size,
  222. ),
  223. "merkle_add_" => Function::new_typed_with_env(
  224. &mut store,
  225. &ctx,
  226. import::merkle::merkle_add,
  227. ),
  228. }
  229. };
  230. debug!(target: "runtime::vm_runtime", "Instantiating module");
  231. let instance = Instance::new(&mut store, &module, &imports)?;
  232. let mut env_mut = ctx.as_mut(&mut store);
  233. env_mut.memory = Some(instance.exports.get_with_generics(MEMORY)?);
  234. Ok(Self { instance, store, ctx })
  235. }
  236. fn call(&mut self, section: ContractSection, payload: &[u8]) -> Result<Vec<u8>> {
  237. debug!(target: "runtime::vm_runtime", "Calling {} method", section.name());
  238. let mut env_mut = self.ctx.as_mut(&mut self.store);
  239. env_mut.contract_section = section;
  240. assert!(env_mut.contract_return_data.take().is_none());
  241. env_mut.contract_return_data.set(None);
  242. // Clear the logs
  243. let _ = env_mut.logs.take();
  244. // Serialize the payload for the format the wasm runtime is expecting.
  245. let payload = Self::serialize_payload(&env_mut.contract_id, payload);
  246. // Allocate enough memory for the payload and copy it into the memory.
  247. let pages_required = payload.len() / WASM_PAGE_SIZE + 1;
  248. self.set_memory_page_size(pages_required as u32)?;
  249. self.copy_to_memory(&payload)?;
  250. debug!(target: "runtime::vm_runtime", "Getting {} function", section.name());
  251. let entrypoint = self.instance.exports.get_function(section.name())?;
  252. debug!(target: "runtime::vm_runtime", "Executing wasm");
  253. let ret = match entrypoint.call(&mut self.store, &[Value::I32(0_i32)]) {
  254. Ok(retvals) => {
  255. self.print_logs();
  256. debug!(target: "runtime::vm_runtime", "{}", self.gas_info());
  257. retvals
  258. }
  259. Err(e) => {
  260. self.print_logs();
  261. debug!(target: "runtime::vm_runtime", "{}", self.gas_info());
  262. // WasmerRuntimeError panics are handled here. Return from run() immediately.
  263. error!(target: "runtime::vm_runtime", "Wasmer Runtime Error: {:#?}", e);
  264. return Err(e.into())
  265. }
  266. };
  267. debug!(target: "runtime::vm_runtime", "wasm executed successfully");
  268. debug!(target: "runtime::vm_runtime", "Contract returned: {:?}", ret[0]);
  269. let mut env_mut = self.ctx.as_mut(&mut self.store);
  270. env_mut.contract_section = ContractSection::Null;
  271. let retdata = match env_mut.contract_return_data.take() {
  272. Some(retdata) => retdata,
  273. None => Vec::new(),
  274. };
  275. let retval = match ret[0] {
  276. Value::I64(v) => v,
  277. _ => unreachable!("Got unexpected result from ret: {:?}", ret),
  278. };
  279. match retval {
  280. entrypoint::SUCCESS => Ok(retdata),
  281. // FIXME: we should be able to see the error returned from the contract
  282. // We can put sdk::Error inside of this.
  283. _ => {
  284. let err = darkfi_sdk::error::ContractError::from(retval);
  285. Err(Error::ContractError(err))
  286. }
  287. }
  288. }
  289. /// This function runs when a smart contract is initially deployed, or re-deployed.
  290. /// The runtime will look for an `INITIALIZE` symbol in the wasm code, and execute
  291. /// it if found. Optionally, it is possible to pass in a payload for any kind of special
  292. /// instructions the developer wants to manage in the initialize function.
  293. /// This process is supposed to set up the sled db trees for storing the smart contract
  294. /// state, and it can create, delete, modify, read, and write to databases it's allowed to.
  295. /// The permissions for this are handled by the `ContractId` in the sled db API so we
  296. /// assume that the contract is only able to do write operations on its own sled trees.
  297. pub fn deploy(&mut self, payload: &[u8]) -> Result<()> {
  298. info!(target: "runtime::vm_runtime", "[wasm-runtime] Running deploy");
  299. // Scoped for borrows
  300. {
  301. let env_mut = self.ctx.as_mut(&mut self.store);
  302. // We always want to have the zkas db as index 0 in db handles and batches when
  303. // deploying.
  304. let contracts = &env_mut.blockchain.lock().unwrap().contracts;
  305. let zkas_tree_handle =
  306. match contracts.lookup(&env_mut.contract_id, SMART_CONTRACT_ZKAS_DB_NAME) {
  307. Ok(v) => v,
  308. Err(_) => {
  309. // FIXME: All this is deploy code is "vulnerable" and able to init a
  310. // tree regardless of execution success. We can easily delete the db
  311. // if execution fails though, and we should charge gas for db_init.
  312. // and perhaps also for the zkas database in this specific case.
  313. contracts.init(&env_mut.contract_id, SMART_CONTRACT_ZKAS_DB_NAME)?
  314. }
  315. };
  316. let mut db_handles = env_mut.db_handles.borrow_mut();
  317. let mut db_batches = env_mut.db_batches.borrow_mut();
  318. db_handles.push(DbHandle::new(env_mut.contract_id, zkas_tree_handle));
  319. db_batches.push(import::util::Batch::default());
  320. }
  321. debug!(target: "runtime::vm_runtime", "[wasm-runtime] payload: {:?}", payload);
  322. let _ = self.call(ContractSection::Deploy, payload)?;
  323. // If the above didn't fail, we write the batches.
  324. self.write_batches()?;
  325. // Update the wasm bincode in the WasmStore
  326. let env_mut = self.ctx.as_mut(&mut self.store);
  327. env_mut
  328. .blockchain
  329. .lock()
  330. .unwrap()
  331. .wasm_bincode
  332. .insert(env_mut.contract_id, &env_mut.contract_bincode)?;
  333. Ok(())
  334. }
  335. /// Apply all batches to the overlay
  336. fn write_batches(&mut self) -> Result<()> {
  337. let env_mut = self.ctx.as_mut(&mut self.store);
  338. let batches = env_mut.db_batches.borrow();
  339. let blockchain = env_mut.blockchain.lock().unwrap();
  340. let mut overlay = blockchain.overlay.lock().unwrap();
  341. for (idx, db) in env_mut.db_handles.get_mut().iter().enumerate() {
  342. let tree_handle = &db.tree;
  343. for (k, v) in &batches[idx].writes {
  344. match v {
  345. Some(u) => overlay.insert(tree_handle, &k, &u)?,
  346. None => overlay.remove(tree_handle, &k)?,
  347. };
  348. }
  349. }
  350. Ok(())
  351. }
  352. /// This funcion runs when someone wants to execute a smart contract.
  353. /// The runtime will look for an `ENTRYPOINT` symbol in the wasm code, and
  354. /// execute it if found. A payload is also passed as an instruction that can
  355. /// be used inside the vm by the runtime.
  356. pub fn exec(&mut self, payload: &[u8]) -> Result<Vec<u8>> {
  357. debug!(target: "runtime::vm_runtime", "exec: {:?}", payload);
  358. self.call(ContractSection::Exec, payload)
  359. }
  360. /// This function runs after successful execution of `exec` and tries to
  361. /// apply the state change to the sled databases.
  362. /// The runtime will lok for an `UPDATE` symbol in the wasm code, and execute
  363. /// it if found. The function does not take an arbitrary payload, but just takes
  364. /// a state update from `env` and passes it into the wasm runtime.
  365. pub fn apply(&mut self, update: &[u8]) -> Result<()> {
  366. debug!(target: "runtime::vm_runtime", "apply: {:?}", update);
  367. let _ = self.call(ContractSection::Update, update)?;
  368. // If the above didn't fail, we write the batches.
  369. self.write_batches()?;
  370. Ok(())
  371. }
  372. /// This function runs first in the entire scheme of executing a smart contract.
  373. /// It is supposed to correctly extract public inputs for any ZK proofs included
  374. /// in the contract calls, and also extract the public keys used to verify the
  375. /// call/transaction signatures.
  376. pub fn metadata(&mut self, payload: &[u8]) -> Result<Vec<u8>> {
  377. self.call(ContractSection::Metadata, payload)
  378. }
  379. fn print_logs(&self) {
  380. let logs = self.ctx.as_ref(&self.store).logs.borrow();
  381. for msg in logs.iter() {
  382. debug!(target: "runtime::vm_runtime", "Contract log: {}", msg);
  383. }
  384. }
  385. fn gas_info(&mut self) -> String {
  386. let remaining_points = get_remaining_points(&mut self.store, &self.instance);
  387. match remaining_points {
  388. MeteringPoints::Remaining(rem) => {
  389. format!("Gas used: {}/{}", GAS_LIMIT - rem, GAS_LIMIT)
  390. }
  391. MeteringPoints::Exhausted => {
  392. format!("Gas fully exhausted: {}/{}", GAS_LIMIT + 1, GAS_LIMIT)
  393. }
  394. }
  395. }
  396. /// Set the memory page size
  397. fn set_memory_page_size(&mut self, pages: u32) -> Result<Pages> {
  398. // Grab memory by value
  399. let memory = self.take_memory();
  400. // Modify the memory
  401. let ret = memory.grow(&mut self.store, Pages(pages))?;
  402. // Replace the memory back again
  403. self.ctx.as_mut(&mut self.store).memory = Some(memory);
  404. Ok(ret)
  405. }
  406. /// Take Memory by value. Needed to modify the Memory object
  407. /// Will panic if memory isn't set.
  408. fn take_memory(&mut self) -> Memory {
  409. let env_memory = &mut self.ctx.as_mut(&mut self.store).memory;
  410. let memory = env_memory.take();
  411. memory.expect("memory should be set")
  412. }
  413. /// Copy payload to the start of the memory
  414. fn copy_to_memory(&self, payload: &[u8]) -> Result<()> {
  415. // TODO: Maybe should write to first zero memory and return the pointer/offset?
  416. // Get the memory view
  417. let env = self.ctx.as_ref(&self.store);
  418. let memory_view = env.memory_view(&self.store);
  419. memory_view.write_slice(payload, 0)
  420. }
  421. /// Serialize contract payload to the format accepted by the runtime functions.
  422. /// We keep the same payload as a slice of bytes, and prepend it with a ContractId,
  423. /// and then a little-endian u64 to tell the payload's length.
  424. fn serialize_payload(cid: &ContractId, payload: &[u8]) -> Vec<u8> {
  425. let ser_cid = serialize(cid);
  426. let payload_len = payload.len();
  427. let mut out = Vec::with_capacity(ser_cid.len() + 8 + payload_len);
  428. out.extend_from_slice(&ser_cid);
  429. out.extend_from_slice(&(payload_len as u64).to_le_bytes());
  430. out.extend_from_slice(payload);
  431. out
  432. }
  433. }