vm_runtime.rs 27 KB

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