vm_runtime.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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::{
  36. blockchain::{contract_store::SMART_CONTRACT_ZKAS_DB_NAME, BlockchainOverlayPtr},
  37. util::time::TimeKeeper,
  38. Error, Result,
  39. };
  40. /// Name of the wasm linear memory in our guest module
  41. const MEMORY: &str = "memory";
  42. /// Gas limit for a single contract call (Single WASM instance)
  43. const GAS_LIMIT: u64 = 400_000_000;
  44. // ANCHOR: contract-section
  45. #[derive(Clone, Copy, PartialEq)]
  46. pub enum ContractSection {
  47. /// Setup function of a contract
  48. Deploy,
  49. /// Entrypoint function of a contract
  50. Exec,
  51. /// Apply function of a contract
  52. Update,
  53. /// Metadata
  54. Metadata,
  55. /// Placeholder state before any initialization
  56. Null,
  57. }
  58. // ANCHOR_END: contract-section
  59. impl ContractSection {
  60. pub const fn name(&self) -> &str {
  61. match self {
  62. Self::Deploy => "__initialize",
  63. Self::Exec => "__entrypoint",
  64. Self::Update => "__update",
  65. Self::Metadata => "__metadata",
  66. Self::Null => unreachable!(),
  67. }
  68. }
  69. }
  70. /// The WASM VM runtime environment instantiated for every smart contract that runs.
  71. pub struct Env {
  72. /// Blockchain overlay access
  73. pub blockchain: BlockchainOverlayPtr,
  74. /// Overlay tree handles used with `db_*`
  75. pub db_handles: RefCell<Vec<DbHandle>>,
  76. /// The contract ID being executed
  77. pub contract_id: ContractId,
  78. /// The compiled wasm bincode being executed,
  79. pub contract_bincode: Vec<u8>,
  80. /// The contract section being executed
  81. pub contract_section: ContractSection,
  82. /// State update produced by a smart contract function call
  83. pub contract_return_data: Cell<Option<Vec<u8>>>,
  84. /// Logs produced by the contract
  85. pub logs: RefCell<Vec<String>>,
  86. /// Direct memory access to the VM
  87. pub memory: Option<Memory>,
  88. /// Object store for transferring memory from the host to VM
  89. pub objects: RefCell<Vec<Vec<u8>>>,
  90. /// Helper structure to calculate time related operations
  91. pub time_keeper: TimeKeeper,
  92. }
  93. impl Env {
  94. /// Provide safe access to the memory
  95. /// (it must be initialized before it can be used)
  96. ///
  97. /// // ctx: FunctionEnvMut<Env>
  98. /// let env = ctx.data();
  99. /// let memory = env.memory_view(&ctx);
  100. ///
  101. pub fn memory_view<'a>(&'a self, store: &'a impl AsStoreRef) -> MemoryView<'a> {
  102. self.memory().view(store)
  103. }
  104. /// Get memory, that needs to have been set fist
  105. pub fn memory(&self) -> &Memory {
  106. self.memory.as_ref().unwrap()
  107. }
  108. }
  109. /// Define a wasm runtime.
  110. pub struct Runtime {
  111. /// A wasm instance
  112. pub instance: Instance,
  113. /// A wasm store (global state)
  114. pub store: Store,
  115. // Wrapper for [`Env`], defined above.
  116. pub ctx: FunctionEnv<Env>,
  117. }
  118. impl Runtime {
  119. /// Create a new wasm runtime instance that contains the given wasm module.
  120. pub fn new(
  121. wasm_bytes: &[u8],
  122. blockchain: BlockchainOverlayPtr,
  123. contract_id: ContractId,
  124. time_keeper: TimeKeeper,
  125. ) -> Result<Self> {
  126. info!(target: "runtime::vm_runtime", "[WASM] Instantiating a new runtime");
  127. // This function will be called for each `Operator` encountered during
  128. // the wasm module execution. It should return the cost of the operator
  129. // that it received as its first argument. For now, every wasm opcode
  130. // has a cost of `1`.
  131. // https://docs.rs/wasmparser/latest/wasmparser/enum.Operator.html
  132. let cost_function = |_operator: &Operator| -> u64 { 1 };
  133. // `Metering` needs to be configured with a limit and a cost function.
  134. // For each `Operator`, the metering middleware will call the cost
  135. // function and subtract the cost from the remaining points.
  136. let metering = Arc::new(Metering::new(GAS_LIMIT, cost_function));
  137. // Define the compiler and middleware, engine, and store
  138. let mut compiler_config = Singlepass::new();
  139. compiler_config.push_middleware(metering);
  140. let mut store = Store::new(compiler_config);
  141. debug!(target: "runtime::vm_runtime", "Compiling module");
  142. let module = Module::new(&store, wasm_bytes)?;
  143. // Initialize data
  144. let db_handles = RefCell::new(vec![]);
  145. let logs = RefCell::new(vec![]);
  146. debug!(target: "runtime::vm_runtime", "Importing functions");
  147. let ctx = FunctionEnv::new(
  148. &mut store,
  149. Env {
  150. blockchain,
  151. db_handles,
  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. time_keeper,
  160. },
  161. );
  162. let imports = imports! {
  163. "env" => {
  164. "drk_log_" => Function::new_typed_with_env(
  165. &mut store,
  166. &ctx,
  167. import::util::drk_log,
  168. ),
  169. "set_return_data_" => Function::new_typed_with_env(
  170. &mut store,
  171. &ctx,
  172. import::util::set_return_data,
  173. ),
  174. "db_init_" => Function::new_typed_with_env(
  175. &mut store,
  176. &ctx,
  177. import::db::db_init,
  178. ),
  179. "db_lookup_" => Function::new_typed_with_env(
  180. &mut store,
  181. &ctx,
  182. import::db::db_lookup,
  183. ),
  184. "db_get_" => Function::new_typed_with_env(
  185. &mut store,
  186. &ctx,
  187. import::db::db_get,
  188. ),
  189. "db_contains_key_" => Function::new_typed_with_env(
  190. &mut store,
  191. &ctx,
  192. import::db::db_contains_key,
  193. ),
  194. "db_set_" => Function::new_typed_with_env(
  195. &mut store,
  196. &ctx,
  197. import::db::db_set,
  198. ),
  199. "db_del_" => Function::new_typed_with_env(
  200. &mut store,
  201. &ctx,
  202. import::db::db_del,
  203. ),
  204. "zkas_db_set_" => Function::new_typed_with_env(
  205. &mut store,
  206. &ctx,
  207. import::db::zkas_db_set,
  208. ),
  209. "put_object_bytes_" => Function::new_typed_with_env(
  210. &mut store,
  211. &ctx,
  212. import::util::put_object_bytes,
  213. ),
  214. "get_object_bytes_" => Function::new_typed_with_env(
  215. &mut store,
  216. &ctx,
  217. import::util::get_object_bytes,
  218. ),
  219. "get_object_size_" => Function::new_typed_with_env(
  220. &mut store,
  221. &ctx,
  222. import::util::get_object_size,
  223. ),
  224. "merkle_add_" => Function::new_typed_with_env(
  225. &mut store,
  226. &ctx,
  227. import::merkle::merkle_add,
  228. ),
  229. "get_current_epoch_" => Function::new_typed_with_env(
  230. &mut store,
  231. &ctx,
  232. import::util::get_current_epoch,
  233. ),
  234. "get_current_slot_" => Function::new_typed_with_env(
  235. &mut store,
  236. &ctx,
  237. import::util::get_current_slot,
  238. ),
  239. "get_verifying_slot_" => Function::new_typed_with_env(
  240. &mut store,
  241. &ctx,
  242. import::util::get_verifying_slot,
  243. ),
  244. "get_verifying_slot_epoch_" => Function::new_typed_with_env(
  245. &mut store,
  246. &ctx,
  247. import::util::get_verifying_slot_epoch,
  248. ),
  249. "get_slot_" => Function::new_typed_with_env(
  250. &mut store,
  251. &ctx,
  252. import::util::get_slot,
  253. ),
  254. "get_blockchain_time_" => Function::new_typed_with_env(
  255. &mut store,
  256. &ctx,
  257. import::util::get_blockchain_time,
  258. ),
  259. }
  260. };
  261. debug!(target: "runtime::vm_runtime", "Instantiating module");
  262. let instance = Instance::new(&mut store, &module, &imports)?;
  263. let env_mut = ctx.as_mut(&mut store);
  264. env_mut.memory = Some(instance.exports.get_with_generics(MEMORY)?);
  265. Ok(Self { instance, store, ctx })
  266. }
  267. /// Call a contract method defined by a [`ContractSection`] using a supplied
  268. /// payload. Returns a `Vec<u8>` corresponding to the result data of the call.
  269. /// For calls that do not return any data, an empty `Vec<u8>` is returned.
  270. fn call(&mut self, section: ContractSection, payload: &[u8]) -> Result<Vec<u8>> {
  271. debug!(target: "runtime::vm_runtime", "Calling {} method", section.name());
  272. let env_mut = self.ctx.as_mut(&mut self.store);
  273. env_mut.contract_section = section;
  274. // Verify contract's return data is empty, or quit.
  275. assert!(env_mut.contract_return_data.take().is_none());
  276. // Clear the logs
  277. let _ = env_mut.logs.take();
  278. // Serialize the payload for the format the wasm runtime is expecting.
  279. let payload = Self::serialize_payload(&env_mut.contract_id, payload);
  280. // Allocate enough memory for the payload and copy it into the memory.
  281. let pages_required = payload.len() / WASM_PAGE_SIZE + 1;
  282. self.set_memory_page_size(pages_required as u32)?;
  283. self.copy_to_memory(&payload)?;
  284. debug!(target: "runtime::vm_runtime", "Getting {} function", section.name());
  285. let entrypoint = self.instance.exports.get_function(section.name())?;
  286. // Call the entrypoint. On success, `call` returns a WASM [`Value`]. (The
  287. // value may be empty.) This value functions similarly to a UNIX exit code.
  288. // The following section is intended to unwrap the exit code and handle fatal
  289. // errors in the Wasmer runtime. The value itself and the return data of the
  290. // contract are processed later.
  291. debug!(target: "runtime::vm_runtime", "Executing wasm");
  292. let ret = match entrypoint.call(&mut self.store, &[Value::I32(0_i32)]) {
  293. Ok(retvals) => {
  294. self.print_logs();
  295. info!(target: "runtime::vm_runtime", "[WASM] {}", self.gas_info());
  296. retvals
  297. }
  298. Err(e) => {
  299. self.print_logs();
  300. info!(target: "runtime::vm_runtime", "[WASM] {}", self.gas_info());
  301. // WasmerRuntimeError panics are handled here. Return from run() immediately.
  302. error!(target: "runtime::vm_runtime", "[WASM] Wasmer Runtime Error: {:#?}", e);
  303. return Err(e.into())
  304. }
  305. };
  306. debug!(target: "runtime::vm_runtime", "wasm executed successfully");
  307. // Move the contract's return data into `retdata`.
  308. let env_mut = self.ctx.as_mut(&mut self.store);
  309. env_mut.contract_section = ContractSection::Null;
  310. let retdata = match env_mut.contract_return_data.take() {
  311. Some(retdata) => retdata,
  312. None => Vec::new(),
  313. };
  314. // Determine the return value of the contract call. If `ret` is empty,
  315. // assumed that the contract call was successful.
  316. let retval: i64 = match ret.len() {
  317. 0 => {
  318. // Return a success value if there is no return value from
  319. // the contract.
  320. debug!(target: "runtime::vm_runtime", "Contract has no return value (expected)");
  321. entrypoint::SUCCESS
  322. }
  323. _ => {
  324. match ret[0] {
  325. Value::I64(v) => {
  326. debug!(target: "runtime::vm_runtime", "Contract returned: {:?}", ret[0]);
  327. v
  328. }
  329. // The only supported return type is i64, so panic if another
  330. // value is returned.
  331. _ => unreachable!("Got unexpected result return value: {:?}", ret),
  332. }
  333. }
  334. };
  335. // Check the integer return value of the call. A value of `entrypoint::SUCCESS` (i.e. zero)
  336. // corresponds to a successful contract call; in this case, we return the contract's
  337. // result data. Otherwise, map the integer return value to a [`ContractError`].
  338. match retval {
  339. entrypoint::SUCCESS => Ok(retdata),
  340. _ => {
  341. let err = darkfi_sdk::error::ContractError::from(retval);
  342. error!(target: "runtime::vm_runtime", "[WASM] Contract returned: {:?}", err);
  343. Err(Error::ContractError(err))
  344. }
  345. }
  346. }
  347. /// This function runs when a smart contract is initially deployed, or re-deployed.
  348. ///
  349. /// The runtime will look for an `__initialize` symbol in the wasm code, and execute
  350. /// it if found. Optionally, it is possible to pass in a payload for any kind of special
  351. /// instructions the developer wants to manage in the initialize function.
  352. ///
  353. /// This process is supposed to set up the overlay trees for storing the smart contract
  354. /// state, and it can create, delete, modify, read, and write to databases it's allowed to.
  355. /// The permissions for this are handled by the `ContractId` in the overlay db API so we
  356. /// assume that the contract is only able to do write operations on its own overlay trees.
  357. pub fn deploy(&mut self, payload: &[u8]) -> Result<()> {
  358. let cid = self.ctx.as_ref(&self.store).contract_id;
  359. info!(target: "runtime::vm_runtime", "[WASM] Running deploy() for ContractID: {}", cid);
  360. // Scoped for borrows
  361. {
  362. let env_mut = self.ctx.as_mut(&mut self.store);
  363. // We always want to have the zkas db as index 0 in db handles and batches when
  364. // deploying.
  365. let contracts = &env_mut.blockchain.lock().unwrap().contracts;
  366. // Open or create the zkas db tree for this contract
  367. let zkas_tree_handle =
  368. match contracts.lookup(&env_mut.contract_id, SMART_CONTRACT_ZKAS_DB_NAME) {
  369. Ok(v) => v,
  370. Err(_) => contracts.init(&env_mut.contract_id, SMART_CONTRACT_ZKAS_DB_NAME)?,
  371. };
  372. let mut db_handles = env_mut.db_handles.borrow_mut();
  373. db_handles.push(DbHandle::new(env_mut.contract_id, zkas_tree_handle));
  374. }
  375. //debug!(target: "runtime::vm_runtime", "[WASM] payload: {:?}", payload);
  376. let _ = self.call(ContractSection::Deploy, payload)?;
  377. // Update the wasm bincode in the WasmStore if the deploy exec passed successfully.
  378. let env_mut = self.ctx.as_mut(&mut self.store);
  379. env_mut
  380. .blockchain
  381. .lock()
  382. .unwrap()
  383. .wasm_bincode
  384. .insert(env_mut.contract_id, &env_mut.contract_bincode)?;
  385. info!(target: "runtime::vm_runtime", "[WASM] Successfully deployed ContractID: {}", cid);
  386. Ok(())
  387. }
  388. /// This function runs first in the entire scheme of executing a smart contract.
  389. ///
  390. /// The runtime will look for a `__metadata` symbol in the wasm code and execute it.
  391. /// It is supposed to correctly extract public inputs for any ZK proofs included
  392. /// in the contract calls, and also extract the public keys used to verify the
  393. /// call/transaction signatures.
  394. pub fn metadata(&mut self, payload: &[u8]) -> Result<Vec<u8>> {
  395. let cid = self.ctx.as_ref(&self.store).contract_id;
  396. info!(target: "runtime::vm_runtime", "[WASM] Running metadata() for ContractID: {}", cid);
  397. debug!(target: "runtime::vm_runtime", "metadata payload: {:?}", payload);
  398. let ret = self.call(ContractSection::Metadata, payload)?;
  399. debug!(target: "runtime::vm_runtime", "metadata returned: {:?}", ret);
  400. info!(target: "runtime::vm_runtime", "[WASM] Successfully got metadata ContractID: {}", cid);
  401. Ok(ret)
  402. }
  403. /// This function runs when someone wants to execute a smart contract.
  404. ///
  405. /// The runtime will look for an `__entrypoint` symbol in the wasm code, and
  406. /// execute it if found. A payload is also passed as an instruction that can
  407. /// be used inside the vm by the runtime.
  408. pub fn exec(&mut self, payload: &[u8]) -> Result<Vec<u8>> {
  409. let cid = self.ctx.as_ref(&self.store).contract_id;
  410. info!(target: "runtime::vm_runtime", "[WASM] Running exec() for ContractID: {}", cid);
  411. debug!(target: "runtime::vm_runtime", "exec payload: {:?}", payload);
  412. let ret = self.call(ContractSection::Exec, payload)?;
  413. debug!(target: "runtime::vm_runtime", "exec returned: {:?}", ret);
  414. info!(target: "runtime::vm_runtime", "[WASM] Successfully executed ContractID: {}", cid);
  415. Ok(ret)
  416. }
  417. /// This function runs after successful execution of `exec` and tries to
  418. /// apply the state change to the overlay databases.
  419. ///
  420. /// The runtime will lok for an `__update` symbol in the wasm code, and execute
  421. /// it if found. The function does not take an arbitrary payload, but just takes
  422. /// a state update from `env` and passes it into the wasm runtime.
  423. pub fn apply(&mut self, update: &[u8]) -> Result<()> {
  424. let cid = self.ctx.as_ref(&self.store).contract_id;
  425. info!(target: "runtime::vm_runtime", "[WASM] Running apply() for ContractID: {}", cid);
  426. debug!(target: "runtime::vm_runtime", "apply payload: {:?}", update);
  427. let ret = self.call(ContractSection::Update, update)?;
  428. debug!(target: "runtime::vm_runtime", "apply returned: {:?}", ret);
  429. info!(target: "runtime::vm_runtime", "[WASM] Successfully applied ContractID: {}", cid);
  430. Ok(())
  431. }
  432. /// Prints the wasm contract logs.
  433. fn print_logs(&self) {
  434. let logs = self.ctx.as_ref(&self.store).logs.borrow();
  435. for msg in logs.iter() {
  436. info!(target: "runtime::vm_runtime", "[WASM] Contract log: {}", msg);
  437. }
  438. }
  439. /// Calculate the remaining gas using wasm's concept
  440. /// of metering points.
  441. pub fn gas_used(&mut self) -> u64 {
  442. let remaining_points = get_remaining_points(&mut self.store, &self.instance);
  443. match remaining_points {
  444. MeteringPoints::Remaining(rem) => {
  445. if rem > GAS_LIMIT {
  446. // This should never occur, but catch it explicitly to avoid
  447. // potential underflow issues when calculating `remaining_points`.
  448. unreachable!("Remaining wasm points exceed GAS_LIMIT");
  449. }
  450. GAS_LIMIT - rem
  451. }
  452. MeteringPoints::Exhausted => GAS_LIMIT + 1,
  453. }
  454. }
  455. // Return a message informing the user whether there is any
  456. // gas remaining. Values equal to GAS_LIMIT are not considered
  457. // to be exhausted. e.g. Using 100/100 gas should not give a
  458. // 'gas exhausted' message.
  459. fn gas_info(&mut self) -> String {
  460. let gas_used = self.gas_used();
  461. if gas_used > GAS_LIMIT {
  462. format!("Gas fully exhausted: {}/{}", gas_used, GAS_LIMIT)
  463. } else {
  464. format!("Gas used: {}/{}", gas_used, GAS_LIMIT)
  465. }
  466. }
  467. /// Set the memory page size. Returns the previous memory size.
  468. fn set_memory_page_size(&mut self, pages: u32) -> Result<Pages> {
  469. // Grab memory by value
  470. let memory = self.take_memory();
  471. // Modify the memory
  472. let ret = memory.grow(&mut self.store, Pages(pages))?;
  473. // Replace the memory back again
  474. self.ctx.as_mut(&mut self.store).memory = Some(memory);
  475. Ok(ret)
  476. }
  477. /// Take Memory by value. Needed to modify the Memory object
  478. /// Will panic if memory isn't set.
  479. fn take_memory(&mut self) -> Memory {
  480. let env_memory = &mut self.ctx.as_mut(&mut self.store).memory;
  481. let memory = env_memory.take();
  482. memory.expect("memory should be set")
  483. }
  484. /// Copy payload to the start of the memory
  485. fn copy_to_memory(&self, payload: &[u8]) -> Result<()> {
  486. // Payload is copied to index 0.
  487. // Get the memory view
  488. let env = self.ctx.as_ref(&self.store);
  489. let memory_view = env.memory_view(&self.store);
  490. memory_view.write_slice(payload, 0)
  491. }
  492. /// Serialize contract payload to the format accepted by the runtime functions.
  493. /// We keep the same payload as a slice of bytes, and prepend it with a [`ContractId`],
  494. /// and then a little-endian u64 to tell the payload's length.
  495. fn serialize_payload(cid: &ContractId, payload: &[u8]) -> Vec<u8> {
  496. let ser_cid = serialize(cid);
  497. let payload_len = payload.len();
  498. let mut out = Vec::with_capacity(ser_cid.len() + 8 + payload_len);
  499. out.extend_from_slice(&ser_cid);
  500. out.extend_from_slice(&(payload_len as u64).to_le_bytes());
  501. out.extend_from_slice(payload);
  502. out
  503. }
  504. }