eosio_client_api/
wasm.rs

1use crate::errors::{ErrorKind, Result};
2use eosio_client_keys::hash::hash_sha256;
3use std::fs;
4
5const WASM_COOKIE: [u8; 8] = [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
6
7pub struct WASM {
8    pub code: Vec<u8>,
9}
10impl WASM {
11    const HEXMAP: [char; 16] = [
12        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
13    ];
14    pub fn _read_hex_string(_in_str: String) -> Result<WASM> {
15        Err("TBD".into())
16    }
17    pub fn read_file(filename: &str) -> Result<WASM> {
18        let file = fs::read(filename)?;
19        let slice = &file[0..WASM_COOKIE.len()].to_vec();
20        let matching = slice
21            .iter()
22            .zip(WASM_COOKIE.iter())
23            .filter(|&(a, b)| a == b)
24            .count();
25
26        if matching == WASM_COOKIE.len() {
27            Ok(WASM { code: file })
28        } else {
29            Err(ErrorKind::InvalidWASMFormat.into())
30        }
31    }
32    pub fn hash(&self) -> Vec<u8> {
33        hash_sha256(&self.code)
34    }
35    pub fn to_hex(&self) -> String {
36        let mut s: String = String::new();
37        for byt in &self.code {
38            s.push(WASM::HEXMAP[(byt >> 4) as usize]);
39            s.push(WASM::HEXMAP[(byt & 0xf) as usize]);
40        }
41        s
42    }
43    pub fn dummy() -> Vec<u8> {
44        //WASM_COOKIE.to_vec()
45        Vec::new()
46    }
47}
48
49#[cfg(test)]
50mod test {
51    use super::*;
52    #[test]
53    fn read_wasm() -> Result<()> {
54        WASM::read_file("test/good.wasm")?;
55        Ok(())
56    }
57}