vm_runtime.rs 19 KB

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