vm_runtime.rs 27 KB

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