vm_runtime.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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, entrypoint};
  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. util::time::TimeKeeper,
  38. Error, Result,
  39. };
  40. /// Name of the wasm linear memory in our guest module
  41. const MEMORY: &str = "memory";
  42. /// Gas limit for a single contract call (Single WASM instance)
  43. const GAS_LIMIT: u64 = 400_000_000;
  44. // ANCHOR: contract-section
  45. #[derive(Clone, Copy, PartialEq)]
  46. pub enum ContractSection {
  47. /// Setup function of a contract
  48. Deploy,
  49. /// Entrypoint function of a contract
  50. Exec,
  51. /// Apply function of a contract
  52. Update,
  53. /// Metadata
  54. Metadata,
  55. /// Placeholder state before any initialization
  56. Null,
  57. }
  58. // ANCHOR_END: contract-section
  59. impl ContractSection {
  60. pub const fn name(&self) -> &str {
  61. match self {
  62. Self::Deploy => "__initialize",
  63. Self::Exec => "__entrypoint",
  64. Self::Update => "__update",
  65. Self::Metadata => "__metadata",
  66. Self::Null => unreachable!(),
  67. }
  68. }
  69. }
  70. /// The WASM VM runtime environment instantiated for every smart contract that runs.
  71. pub struct Env {
  72. /// Blockchain overlay access
  73. pub blockchain: BlockchainOverlayPtr,
  74. /// Overlay tree handles used with `db_*`
  75. pub db_handles: RefCell<Vec<DbHandle>>,
  76. /// The contract ID being executed
  77. pub contract_id: ContractId,
  78. /// The compiled wasm bincode being executed,
  79. pub contract_bincode: Vec<u8>,
  80. /// The contract section being executed
  81. pub contract_section: ContractSection,
  82. /// State update produced by a smart contract function call
  83. pub contract_return_data: Cell<Option<Vec<u8>>>,
  84. /// Logs produced by the contract
  85. pub logs: RefCell<Vec<String>>,
  86. /// Direct memory access to the VM
  87. pub memory: Option<Memory>,
  88. /// Object store for transferring memory from the host to VM
  89. pub objects: RefCell<Vec<Vec<u8>>>,
  90. /// Helper structure to calculate time related operations
  91. pub time_keeper: TimeKeeper,
  92. /// Parent `Instance`
  93. pub instance: Option<Arc<Instance>>,
  94. }
  95. impl Env {
  96. /// Provide safe access to the memory
  97. /// (it must be initialized before it can be used)
  98. ///
  99. /// // ctx: FunctionEnvMut<Env>
  100. /// let env = ctx.data();
  101. /// let memory = env.memory_view(&ctx);
  102. ///
  103. pub fn memory_view<'a>(&'a self, store: &'a impl AsStoreRef) -> MemoryView<'a> {
  104. self.memory().view(store)
  105. }
  106. /// Get memory, that needs to have been set fist
  107. pub fn memory(&self) -> &Memory {
  108. self.memory.as_ref().unwrap()
  109. }
  110. /// Subtract given gas cost from remaining gas in the current runtime
  111. pub fn subtract_gas(&mut self, ctx: &mut impl AsStoreMut, gas: u64) {
  112. match get_remaining_points(ctx, self.instance.as_ref().unwrap()) {
  113. MeteringPoints::Remaining(rem) => {
  114. if gas > rem {
  115. set_remaining_points(ctx, self.instance.as_ref().unwrap(), 0);
  116. } else {
  117. set_remaining_points(ctx, self.instance.as_ref().unwrap(), rem - gas);
  118. }
  119. }
  120. MeteringPoints::Exhausted => {
  121. set_remaining_points(ctx, self.instance.as_ref().unwrap(), 0);
  122. }
  123. }
  124. }
  125. }
  126. /// Define a wasm runtime.
  127. pub struct Runtime {
  128. /// A wasm instance
  129. pub instance: Arc<Instance>,
  130. /// A wasm store (global state)
  131. pub store: Store,
  132. // Wrapper for [`Env`], defined above.
  133. pub ctx: FunctionEnv<Env>,
  134. }
  135. impl Runtime {
  136. /// Create a new wasm runtime instance that contains the given wasm module.
  137. pub fn new(
  138. wasm_bytes: &[u8],
  139. blockchain: BlockchainOverlayPtr,
  140. contract_id: ContractId,
  141. time_keeper: TimeKeeper,
  142. ) -> Result<Self> {
  143. info!(target: "runtime::vm_runtime", "[WASM] Instantiating a new runtime");
  144. // This function will be called for each `Operator` encountered during
  145. // the wasm module execution. It should return the cost of the operator
  146. // that it received as its first argument. For now, every wasm opcode
  147. // has a cost of `1`.
  148. // https://docs.rs/wasmparser/latest/wasmparser/enum.Operator.html
  149. let cost_function = |_operator: &Operator| -> u64 { 1 };
  150. // `Metering` needs to be configured with a limit and a cost function.
  151. // For each `Operator`, the metering middleware will call the cost
  152. // function and subtract the cost from the remaining points.
  153. let metering = Arc::new(Metering::new(GAS_LIMIT, cost_function));
  154. // Define the compiler and middleware, engine, and store
  155. let mut compiler_config = Singlepass::new();
  156. compiler_config.push_middleware(metering);
  157. let mut store = Store::new(compiler_config);
  158. debug!(target: "runtime::vm_runtime", "Compiling module");
  159. let module = Module::new(&store, wasm_bytes)?;
  160. // Initialize data
  161. let db_handles = RefCell::new(vec![]);
  162. let logs = RefCell::new(vec![]);
  163. debug!(target: "runtime::vm_runtime", "Importing functions");
  164. let ctx = FunctionEnv::new(
  165. &mut store,
  166. Env {
  167. blockchain,
  168. db_handles,
  169. contract_id,
  170. contract_bincode: wasm_bytes.to_vec(),
  171. contract_section: ContractSection::Null,
  172. contract_return_data: Cell::new(None),
  173. logs,
  174. memory: None,
  175. objects: RefCell::new(vec![]),
  176. time_keeper,
  177. instance: None,
  178. },
  179. );
  180. let imports = imports! {
  181. "env" => {
  182. "drk_log_" => Function::new_typed_with_env(
  183. &mut store,
  184. &ctx,
  185. import::util::drk_log,
  186. ),
  187. "set_return_data_" => Function::new_typed_with_env(
  188. &mut store,
  189. &ctx,
  190. import::util::set_return_data,
  191. ),
  192. "db_init_" => Function::new_typed_with_env(
  193. &mut store,
  194. &ctx,
  195. import::db::db_init,
  196. ),
  197. "db_lookup_" => Function::new_typed_with_env(
  198. &mut store,
  199. &ctx,
  200. import::db::db_lookup,
  201. ),
  202. "db_get_" => Function::new_typed_with_env(
  203. &mut store,
  204. &ctx,
  205. import::db::db_get,
  206. ),
  207. "db_contains_key_" => Function::new_typed_with_env(
  208. &mut store,
  209. &ctx,
  210. import::db::db_contains_key,
  211. ),
  212. "db_set_" => Function::new_typed_with_env(
  213. &mut store,
  214. &ctx,
  215. import::db::db_set,
  216. ),
  217. "db_del_" => Function::new_typed_with_env(
  218. &mut store,
  219. &ctx,
  220. import::db::db_del,
  221. ),
  222. "zkas_db_set_" => Function::new_typed_with_env(
  223. &mut store,
  224. &ctx,
  225. import::db::zkas_db_set,
  226. ),
  227. "put_object_bytes_" => Function::new_typed_with_env(
  228. &mut store,
  229. &ctx,
  230. import::util::put_object_bytes,
  231. ),
  232. "get_object_bytes_" => Function::new_typed_with_env(
  233. &mut store,
  234. &ctx,
  235. import::util::get_object_bytes,
  236. ),
  237. "get_object_size_" => Function::new_typed_with_env(
  238. &mut store,
  239. &ctx,
  240. import::util::get_object_size,
  241. ),
  242. "merkle_add_" => Function::new_typed_with_env(
  243. &mut store,
  244. &ctx,
  245. import::merkle::merkle_add,
  246. ),
  247. "get_current_epoch_" => Function::new_typed_with_env(
  248. &mut store,
  249. &ctx,
  250. import::util::get_current_epoch,
  251. ),
  252. "get_current_block_height_" => Function::new_typed_with_env(
  253. &mut store,
  254. &ctx,
  255. import::util::get_current_block_height,
  256. ),
  257. "get_current_slot_" => Function::new_typed_with_env(
  258. &mut store,
  259. &ctx,
  260. import::util::get_current_slot,
  261. ),
  262. "get_verifying_block_height_" => Function::new_typed_with_env(
  263. &mut store,
  264. &ctx,
  265. import::util::get_verifying_block_height,
  266. ),
  267. "get_verifying_block_height_epoch_" => Function::new_typed_with_env(
  268. &mut store,
  269. &ctx,
  270. import::util::get_verifying_block_height_epoch,
  271. ),
  272. "get_slot_" => Function::new_typed_with_env(
  273. &mut store,
  274. &ctx,
  275. import::util::get_slot,
  276. ),
  277. "get_blockchain_time_" => Function::new_typed_with_env(
  278. &mut store,
  279. &ctx,
  280. import::util::get_blockchain_time,
  281. ),
  282. "get_last_block_info_" => Function::new_typed_with_env(
  283. &mut store,
  284. &ctx,
  285. import::util::get_last_block_info,
  286. ),
  287. }
  288. };
  289. debug!(target: "runtime::vm_runtime", "Instantiating module");
  290. let instance = Arc::new(Instance::new(&mut store, &module, &imports)?);
  291. let env_mut = ctx.as_mut(&mut store);
  292. env_mut.memory = Some(instance.exports.get_with_generics(MEMORY)?);
  293. env_mut.instance = Some(Arc::clone(&instance));
  294. Ok(Self { instance, store, ctx })
  295. }
  296. /// Call a contract method defined by a [`ContractSection`] using a supplied
  297. /// payload. Returns a `Vec<u8>` corresponding to the result data of the call.
  298. /// For calls that do not return any data, an empty `Vec<u8>` is returned.
  299. fn call(&mut self, section: ContractSection, payload: &[u8]) -> Result<Vec<u8>> {
  300. debug!(target: "runtime::vm_runtime", "Calling {} method", section.name());
  301. let env_mut = self.ctx.as_mut(&mut self.store);
  302. env_mut.contract_section = section;
  303. // Verify contract's return data is empty, or quit.
  304. assert!(env_mut.contract_return_data.take().is_none());
  305. // Clear the logs
  306. let _ = env_mut.logs.take();
  307. // Serialize the payload for the format the wasm runtime is expecting.
  308. let payload = Self::serialize_payload(&env_mut.contract_id, payload);
  309. // Allocate enough memory for the payload and copy it into the memory.
  310. let pages_required = payload.len() / WASM_PAGE_SIZE + 1;
  311. self.set_memory_page_size(pages_required as u32)?;
  312. self.copy_to_memory(&payload)?;
  313. debug!(target: "runtime::vm_runtime", "Getting {} function", section.name());
  314. let entrypoint = self.instance.exports.get_function(section.name())?;
  315. // Call the entrypoint. On success, `call` returns a WASM [`Value`]. (The
  316. // value may be empty.) This value functions similarly to a UNIX exit code.
  317. // The following section is intended to unwrap the exit code and handle fatal
  318. // errors in the Wasmer runtime. The value itself and the return data of the
  319. // contract are processed later.
  320. debug!(target: "runtime::vm_runtime", "Executing wasm");
  321. let ret = match entrypoint.call(&mut self.store, &[Value::I32(0_i32)]) {
  322. Ok(retvals) => {
  323. self.print_logs();
  324. info!(target: "runtime::vm_runtime", "[WASM] {}", self.gas_info());
  325. retvals
  326. }
  327. Err(e) => {
  328. self.print_logs();
  329. info!(target: "runtime::vm_runtime", "[WASM] {}", self.gas_info());
  330. // WasmerRuntimeError panics are handled here. Return from run() immediately.
  331. error!(target: "runtime::vm_runtime", "[WASM] Wasmer Runtime Error: {:#?}", e);
  332. return Err(e.into())
  333. }
  334. };
  335. debug!(target: "runtime::vm_runtime", "wasm executed successfully");
  336. // Move the contract's return data into `retdata`.
  337. let env_mut = self.ctx.as_mut(&mut self.store);
  338. env_mut.contract_section = ContractSection::Null;
  339. let retdata = match env_mut.contract_return_data.take() {
  340. Some(retdata) => retdata,
  341. None => Vec::new(),
  342. };
  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. 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. 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 WasmStore 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. .wasm_bincode
  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);
  427. let ret = self.call(ContractSection::Metadata, payload)?;
  428. debug!(target: "runtime::vm_runtime", "metadata returned: {:?}", ret);
  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);
  441. let ret = self.call(ContractSection::Exec, payload)?;
  442. debug!(target: "runtime::vm_runtime", "exec returned: {:?}", ret);
  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);
  456. let ret = self.call(ContractSection::Update, update)?;
  457. debug!(target: "runtime::vm_runtime", "apply returned: {:?}", ret);
  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. }