vm_runtime.rs 24 KB

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