vm_runtime.rs 25 KB

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