vm_runtime.rs 23 KB

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