1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
//! Contract handler
//! The handler helps you deploy contract and test the contract you developing
use std::cell::RefCell;
use std::convert::TryInto;
use std::fs::read;
use std::sync::Arc;

use crate::errors::ContractError as Error;
use crate::runtimes::traits::{VMMessageBuilder, VMResult, RT};
use crate::types::Raw;

use anyhow::{Context, Result};
use hex::decode;
use serde_derive::{Deserialize, Serialize};

#[derive(Clone, Deserialize, Serialize, Default)]
pub struct ContractHandler {
    /// The contract data in hex literal for eWasm binary, or a file path to
    /// the .ewasm file
    pub call_data: Option<String>,
    #[serde(skip)]
    pub rt: Option<Arc<RefCell<dyn RT>>>,
}

#[cfg(any(feature = "debug", test))]
impl std::fmt::Debug for ContractHandler {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ContractHandler")
            .field("call_data", &self.call_data)
            .field("rt", &self.rt.is_some())
            .finish()
    }
}

impl ContractHandler {
    /// run the call data as function directly, this function is suppose to be used for constructor
    pub fn run_fn(
        &mut self,
        call_data: String,
        input: Option<&[u8]>,
        gas: i64,
    ) -> Result<VMResult> {
        if let Some(rt) = self.rt.take() {
            let call_data = ContractHandler::get_call_data(call_data)?;
            let mut input_data: Vec<u8> = Vec::new();
            if let Some(input) = input {
                input_data.extend_from_slice(input);
            }
            let sender = Raw::default();
            let msg = VMMessageBuilder {
                sender: Some(&sender),
                input_data: Some(&input_data),
                gas,
                code: Some(&call_data),
                ..Default::default()
            }
            .build()?;
            let result = Ok(rt.borrow_mut().execute(msg)?);
            self.rt = Some(rt);
            return result;
        }
        panic!("rt should be init when parsing the connection string")
    }

    pub fn execute(
        &mut self,
        addr: Option<&str>,
        fun_sig: [u8; 4],
        input: Option<&[u8]>,
        gas: i64,
    ) -> Result<VMResult> {
        if let Some(rt) = self.rt.take() {
            let mut result: Result<VMResult> = Err(Error::CalldataAbsent.into());
            if let Some(call_data) = self.call_data.take() {
                let call_data = ContractHandler::get_call_data(call_data)?;
                let mut input_data: Vec<u8> = fun_sig.to_vec();
                if let Some(input) = input {
                    input_data.extend_from_slice(input);
                }

                let sender = if let Some(addr) = addr {
                    let hex_str: &str = if addr.starts_with("0x") {
                        &addr[2..addr.len()]
                    } else {
                        addr
                    };
                    let byte20: [u8; 20] = decode(hex_str)
                        .expect("contract caller's address should be hex format")
                        .try_into()
                        .expect("contract caller's address should be bytes20");
                    Raw::from_raw_address(&byte20)
                } else {
                    Raw::default()
                };

                let msg = VMMessageBuilder {
                    sender: Some(&sender),
                    input_data: Some(&input_data),
                    gas,
                    code: Some(&call_data),
                    ..Default::default()
                }
                .build()?;
                result = Ok(rt.borrow_mut().execute(msg)?);
            }
            self.rt = Some(rt);
            return result;
        }
        panic!("rt should be init when parsing the connection string")
    }

    /// Return the call data binary from hex literal or from a ewasm file
    fn get_call_data(call_data_info: String) -> Result<Vec<u8>> {
        if let Some(stripped_data_info) = call_data_info.strip_prefix("0x") {
            if call_data_info.len() % 2 != 0 {
                return Err(Error::CalldataMalformat.into());
            }
            let mut format_error = false;
            let v = stripped_data_info
                .chars()
                .collect::<Vec<char>>()
                .chunks(2)
                .enumerate()
                .map(|(i, c)| {
                    u8::from_str_radix(c.iter().collect::<String>().as_str(), 16)
                        .with_context(|| {
                            format_error = true;
                            format!("Failed to parse call data at {}", i * 2 + 2)
                        })
                        .unwrap_or(0)
                })
                .collect::<Vec<u8>>();
            if format_error {
                return Err(Error::CalldataMalformat.into());
            }
            Ok(v)
        } else {
            Ok(read(call_data_info)?)
        }
    }
}