util.rs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. use log::{error, warn};
  2. use super::{memory::MemoryManipulation, vm_runtime::Env};
  3. /// Serialize contract payload to format accepted by the runtime entrypoint.
  4. /// We keep the same payload as a slice of bytes, and prepend it with a
  5. /// little-endian u64 to tell the payload's length.
  6. pub fn serialize_payload(payload: &[u8]) -> Vec<u8> {
  7. let mut out = vec![];
  8. let len = payload.len() as u64;
  9. out.extend_from_slice(&len.to_le_bytes());
  10. out.extend_from_slice(payload);
  11. out
  12. }
  13. /// Host function for logging strings.
  14. /// This is injected into the runtime with wasmer's `imports!` macro.
  15. pub(crate) fn drk_log(env: &Env, ptr: u32, len: u32) {
  16. if let Some(bytes) = env.memory.get_ref().unwrap().read(ptr, len as usize) {
  17. // Piece the string together
  18. let msg = match String::from_utf8(bytes.to_vec()) {
  19. Ok(v) => v,
  20. Err(e) => {
  21. warn!(target: "wasm-runtime", "Invalid UTF-8 string: {:?}", e);
  22. return
  23. }
  24. };
  25. let mut logs = env.logs.lock().unwrap();
  26. logs.push(msg);
  27. std::mem::drop(logs);
  28. return
  29. }
  30. error!(target: "wasm-runtime", "Failed to read any bytes from VM memory");
  31. }