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
use crate::errors::{CanBeAbortion, InvokeError, RuntimeError, SelfError, VmError};
use crate::internal_prelude::*;
use crate::system::system_modules::costing::FeeReserveError;
use crate::transaction::AbortReason;

/// Represents an error when validating a WASM file.
#[derive(Debug, PartialEq, Eq, Clone, Sbor)]
pub enum PrepareError {
    /// Failed to deserialize.
    /// See <https://webassembly.github.io/spec/core/syntax/index.html>
    DeserializationError,
    /// Failed to validate
    /// See <https://webassembly.github.io/spec/core/valid/index.html>
    ValidationError(String),
    /// Failed to serialize.
    SerializationError,
    /// The wasm module contains a start function.
    StartFunctionNotAllowed,
    /// Invalid import section
    InvalidImport(InvalidImport),
    /// Invalid memory section
    InvalidMemory(InvalidMemory),
    /// Invalid table section
    InvalidTable(InvalidTable),
    /// Invalid export symbol name
    InvalidExportName(String),
    /// Too many targets in the `br_table` instruction
    TooManyTargetsInBrTable,
    /// Too many functions
    TooManyFunctions,
    /// Too many function parameters
    TooManyFunctionParams,
    /// Too many function local variables
    TooManyFunctionLocals { max: u32, actual: u32 },
    /// Too many globals
    TooManyGlobals { max: u32, current: u32 },
    /// No export section
    NoExportSection,
    /// Missing export
    MissingExport { export_name: String },
    /// The wasm module does not have the `scrypto_alloc` export.
    NoScryptoAllocExport,
    /// The wasm module does not have the `scrypto_free` export.
    NoScryptoFreeExport,
    /// Failed to inject instruction metering
    RejectedByInstructionMetering { reason: String },
    /// Failed to inject stack metering
    RejectedByStackMetering { reason: String },
    /// Not instantiatable
    NotInstantiatable { reason: String },
    /// Not compilable
    NotCompilable,
    /// Wrap errors returned by WasmInstrument::ModuleInfoError
    /// It is wrapped to String, because it's members cannot derive: Sbor, Eq and PartialEq
    ModuleInfoError(String),
    /// Wrap errors returned by wasmparser
    /// It is wrapped to String, because wasmparser error (BinaryReaderError) members cannot derive: Sbor, Eq and PartialEq
    WasmParserError(String),
    /// An overflow occurred in some of the internal math
    Overflow,
}

#[derive(Debug, PartialEq, Eq, Clone, Sbor)]
pub enum InvalidImport {
    /// The import is not allowed
    ImportNotAllowed(String),
    /// Scrypto VM version protocol mismatch
    ProtocolVersionMismatch {
        name: String,
        current_version: u64,
        expected_version: u64,
    },
    InvalidFunctionType(String),
}

#[derive(Debug, PartialEq, Eq, Clone, Sbor)]
pub enum InvalidMemory {
    /// The wasm module has no memory section.
    MissingMemorySection,
    /// The memory section is empty.
    NoMemoryDefinition,
    /// The memory section contains too many memory definitions.
    TooManyMemoryDefinition,
    /// The memory size exceeds the limit.
    MemorySizeLimitExceeded,
    /// The wasm module does not have the `memory` export.
    MemoryNotExported,
}

#[derive(Debug, PartialEq, Eq, Clone, Sbor)]
pub enum InvalidTable {
    /// More than one table defined, against WebAssembly MVP spec
    MoreThanOneTable,
    /// Initial table size too large
    InitialTableSizeLimitExceeded,
}

/// Represents an error when invoking an export of a Scrypto module.
#[derive(Debug, Clone, PartialEq, Eq, ScryptoSbor)]
pub enum WasmRuntimeError {
    /// Host attempted to call unknown WASM function, addressed by name.
    UnknownExport(String),

    /// Error when reading wasm memory.
    MemoryAccessError,

    /// WASM function return is not a `u64` fat pointer which points to a valid memory range.
    InvalidWasmPointer,

    /// WASM execution error, including trap.
    ExecutionError(String),

    /// Not implemented, no-op wasm runtime
    NotImplemented,

    /// Buffer not found
    BufferNotFound(BufferId),

    InvalidAddress(DecodeError),

    /// Invalid method ident
    InvalidString,

    /// Invalid RE node ID
    InvalidNodeId,

    InvalidGlobalAddressReservation,

    /// Invalid reference type
    InvalidReferenceType(u32),

    /// Invalid RE module ID
    InvalidAttachedModuleId(u32),

    /// Invalid initial app states
    InvalidObjectStates(DecodeError),

    /// Invalid access rules
    InvalidAccessRule(DecodeError),

    /// Invalid modules
    InvalidModules(DecodeError),

    InvalidTemplateArgs(DecodeError),

    InvalidKeyValueStoreSchema(DecodeError),

    /// Invalid component address
    InvalidLockFlags,

    /// Invalid log level
    InvalidLogLevel(DecodeError),

    /// Costing error (no-op runtime only!)
    FeeReserveError(FeeReserveError),

    InvalidEventFlags(u32),

    InvalidPackageAddress,

    TooManyBuffers,

    InvalidBlsPublicKey(DecodeError),
    InvalidBlsSignature(DecodeError),
    InvalidBlsPublicKeyOrMessage(DecodeError),
}

impl SelfError for WasmRuntimeError {
    fn into_runtime_error(self) -> RuntimeError {
        RuntimeError::VmError(VmError::Wasm(self))
    }
}

impl CanBeAbortion for WasmRuntimeError {
    fn abortion(&self) -> Option<&AbortReason> {
        match self {
            WasmRuntimeError::FeeReserveError(err) => err.abortion(),
            _ => None,
        }
    }
}

impl fmt::Display for WasmRuntimeError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

#[cfg(not(feature = "alloc"))]
impl std::error::Error for WasmRuntimeError {}

impl fmt::Display for InvokeError<WasmRuntimeError> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

#[cfg(not(feature = "alloc"))]
impl std::error::Error for InvokeError<WasmRuntimeError> {}