Files
ahash
aho_corasick
ansi_term
anyhow
atty
bech32
bincode
bit_set
bit_vec
bitcoin
bitcoin_hashes
bitflags
cfg_if
clap
convert_case
core2
crunchy
cryptoxide
enum_primitive
fancy_regex
hashbrown
hex
hex_literal
itoa
libc
libloading
memchr
num
num_bigint
num_complex
num_integer
num_iter
num_rational
num_traits
ordered_float
paste
proc_macro2
proc_macro_error
proc_macro_error_attr
qimalloc
quote
regex
regex_syntax
remain
rust_ssvm
ryu
secp256k1
secp256k1_sys
serde
serde_derive
serde_json
serde_value
sewup
sewup_derive
ss_ewasm_api
ssvm_evmc_client
ssvm_evmc_sys
strsim
syn
textwrap
thiserror
thiserror_impl
tiny_keccak
toml
unicode_width
unicode_xid
vec_map
  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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
//! RT Trait
//! This trait help you abstract any VM into application runtime layer,
//! such that you can easily use your VM with SewUp libs.
//!
//! Besides, the VMErrors, VMmessage VMresult are rust style wrarp for
//! evm_error, evm_message and evm_result
use std::collections::HashMap;

use anyhow::Result;
use evmc_sys::evmc_call_kind;
use thiserror::Error;

use crate::types::Raw;

#[remain::sorted]
#[derive(Error, Debug, PartialEq)]
pub enum VmError {
    #[error("argument out of range")]
    ArgumentOutOfRange,
    #[error("bad jump destination")]
    BadJumpDestination,
    #[error("call depth exceeded")]
    CallDepthExceeded,
    #[error("contract validation failure")]
    ContractValidationFailure,
    /// If the EWASM errors are not enough for your VM,
    /// you can use this error type to help you customized you error message
    #[error("`{0}`")]
    CustomizedError(String),
    #[error("failure")]
    Failure,
    #[error("internal error")]
    InternalError,
    #[error("invalid instruction")]
    InvalidInstruction,
    #[error("invalid memory access")]
    InvalidMemoryAccess,
    #[error("out of gas")]
    OutOfGas,
    #[error("out of memory")]
    OutOfMemory,
    #[error("precompile failure")]
    PrecompileFailure,
    #[error("rejected")]
    Rejected,
    #[error("revert")]
    Revert,
    #[error("stack overflow")]
    StackOverflow,
    #[error("stack underflow")]
    StackUnderflow,
    #[error("static mode violation")]
    StaticModeViolation,
    #[error("undefined instruction")]
    UndefinedInstruction,
    #[error("there shoulbe be a caller(sender) for the message")]
    UnknownCaller,
    #[error("wasm trap")]
    WasmTrap,
    #[error("wasm unreachable instruction")]
    WasmUnreachableInstruction,
}

// TODO: abstract this, such that this can suitable for other chain than ETH
#[cfg_attr(any(feature = "debug", test), derive(Debug))]
#[derive(Default)]
pub struct VMResult {
    pub(crate) gas_left: i64,
    pub output_data: Vec<u8>,
    pub(crate) create_address: Option<Raw>,
}

#[cfg_attr(any(feature = "debug", test), derive(Debug))]
#[derive(PartialEq)]
pub enum Flags {
    Default = 0,
    Static = 1,
}

// TODO: abstract this, such that this can suitable for other chain than ETH
#[cfg_attr(any(feature = "debug", test), derive(Debug))]
pub struct VMMessage<'a> {
    pub kind: evmc_call_kind,
    pub flags: Flags,
    pub depth: i32,
    pub gas: i64,
    pub destination: Raw,
    pub sender: &'a Raw,
    pub input_data: Option<&'a Vec<u8>>,
    pub value: Raw,
    pub code: Option<&'a Vec<u8>>,
    pub create2_salt: Option<()>,
}

#[cfg_attr(any(feature = "debug", test), derive(Debug))]
pub struct VMMessageBuilder<'a> {
    pub kind: evmc_call_kind,
    pub flags: Flags,
    pub depth: i32,
    pub gas: i64,
    pub destination: Option<&'a Raw>,
    pub sender: Option<&'a Raw>,
    pub input_data: Option<&'a Vec<u8>>,
    pub value: Raw,
    pub code: Option<&'a Vec<u8>>,
    pub create2_salt: Option<()>,
}

impl<'a> VMMessageBuilder<'a> {
    /// The Message will be restricted and do not modify the storage
    #[inline]
    pub fn read_only(mut self) -> Self {
        self.flags = Flags::Static;
        self
    }

    #[inline]
    pub fn destination(mut self, addr: &'a Raw) -> Self {
        self.destination = Some(addr);
        self
    }

    #[inline]
    pub fn sender(mut self, addr: &'a Raw) -> Self {
        self.sender = Some(addr);
        self
    }

    #[inline]
    pub fn build(self) -> Result<VMMessage<'a>> {
        let VMMessageBuilder {
            kind,
            flags,
            depth,
            gas,
            destination,
            sender,
            input_data,
            value,
            code,
            create2_salt,
        } = self;

        if let Some(sender) = sender {
            let destination = if let Some(destination) = destination {
                *destination
            } else {
                Raw::from(0u32)
            };
            return Ok(VMMessage {
                kind,
                flags,
                depth,
                gas,
                destination,
                sender,
                input_data,
                value,
                code,
                create2_salt,
            });
        }
        Err(VmError::UnknownCaller.into())
    }

    /// Use Create2 EVM call with predefined salt
    /// The call help you generate the contract address.
    pub fn create2(self, _salt: ()) -> Self {
        unimplemented!()
    }
}

impl Default for VMMessageBuilder<'_> {
    fn default() -> Self {
        Self {
            kind: evmc_call_kind::EVMC_CALL,
            flags: Flags::Default,
            depth: i32::MAX,
            value: Raw::from(0u32),
            gas: 0,
            destination: None,
            sender: None,
            input_data: None,
            code: None,
            create2_salt: None,
        }
    }
}

pub trait RT {
    /// let VM execute the message
    fn execute(&mut self, msg: VMMessage) -> Result<VMResult>;

    /// Deploy contract
    fn deploy(&mut self, msg: VMMessage) -> Result<()>;

    /// Get storage
    fn get_storage(&self, account: &[u8; 20]) -> Option<&HashMap<[u8; 32], [u8; 32]>>;
}