vm_runtime.rs 24 KB

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