cosmwasm_vm/errors/
vm_error.rs

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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
use super::{impl_from_err, BT};
use std::fmt::{Debug, Display};
use thiserror::Error;

use cosmwasm_crypto::CryptoError;

use super::communication_error::CommunicationError;
use crate::backend::BackendError;

#[derive(Error, Debug)]
#[non_exhaustive]
pub enum VmError {
    #[error("Aborted: {}", msg)]
    Aborted { msg: String, backtrace: BT },
    #[error("Error calling into the VM's backend: {}", source)]
    BackendErr { source: BackendError, backtrace: BT },
    #[error("Cache error: {msg}")]
    CacheErr { msg: String, backtrace: BT },
    #[error("Error in guest/host communication: {source}")]
    CommunicationErr {
        source: CommunicationError,
        backtrace: BT,
    },
    #[error("Error compiling Wasm: {msg}")]
    CompileErr { msg: String, backtrace: BT },
    #[error("Couldn't convert from {} to {}. Input: {}", from_type, to_type, input)]
    ConversionErr {
        from_type: String,
        to_type: String,
        input: String,
        backtrace: BT,
    },
    #[error("Crypto error: {}", source)]
    CryptoErr { source: CryptoError, backtrace: BT },
    #[error("Ran out of gas during contract execution")]
    GasDepletion { backtrace: BT },
    /// Whenever there is no specific error type available
    #[error("Generic error: {msg}")]
    GenericErr { msg: String, backtrace: BT },
    #[error("Error instantiating a Wasm module: {msg}")]
    InstantiationErr { msg: String, backtrace: BT },
    #[error("Hash doesn't match stored data")]
    IntegrityErr { backtrace: BT },
    #[error("Error parsing into type {target_type}: {msg}")]
    ParseErr {
        /// the target type that was attempted
        target_type: String,
        msg: String,
        backtrace: BT,
    },
    #[error("Data too long for deserialization. Got: {length} bytes; limit: {max_length} bytes")]
    DeserializationLimitExceeded {
        /// the target type that was attempted
        length: usize,
        max_length: usize,
        backtrace: BT,
    },
    #[error("Error serializing type {source_type}: {msg}")]
    SerializeErr {
        /// the source type that was attempted
        source_type: String,
        msg: String,
        backtrace: BT,
    },
    #[error("Error resolving Wasm function: {}", msg)]
    ResolveErr { msg: String, backtrace: BT },
    #[error(
        "Unexpected number of result values when calling '{}'. Expected: {}, actual: {}.",
        function_name,
        expected,
        actual
    )]
    ResultMismatch {
        function_name: String,
        expected: usize,
        actual: usize,
        backtrace: BT,
    },
    #[error("Error executing Wasm: {}", msg)]
    RuntimeErr { msg: String, backtrace: BT },
    #[error("Error during static Wasm validation: {}", msg)]
    StaticValidationErr { msg: String, backtrace: BT },
    #[error("Uninitialized Context Data: {}", kind)]
    UninitializedContextData { kind: String, backtrace: BT },
    #[error("Must not call a writing storage function in this context.")]
    WriteAccessDenied { backtrace: BT },
    #[error("Maximum call depth exceeded.")]
    MaxCallDepthExceeded { backtrace: BT },
    #[error(
        "The called function args arity does not match. The contract's method arity: {}",
        contract_method_arity
    )]
    FunctionArityMismatch {
        contract_method_arity: usize,
        backtrace: BT,
    },
}

impl VmError {
    pub(crate) fn aborted(msg: impl Into<String>) -> Self {
        VmError::Aborted {
            msg: msg.into(),
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn backend_err(original: BackendError) -> Self {
        VmError::BackendErr {
            source: original,
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn cache_err(msg: impl Into<String>) -> Self {
        VmError::CacheErr {
            msg: msg.into(),
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn compile_err(msg: impl Into<String>) -> Self {
        VmError::CompileErr {
            msg: msg.into(),
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn conversion_err(
        from_type: impl Into<String>,
        to_type: impl Into<String>,
        input: impl Into<String>,
    ) -> Self {
        VmError::ConversionErr {
            from_type: from_type.into(),
            to_type: to_type.into(),
            input: input.into(),
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn crypto_err(original: CryptoError) -> Self {
        VmError::CryptoErr {
            source: original,
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn gas_depletion() -> Self {
        VmError::GasDepletion {
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn generic_err(msg: impl Into<String>) -> Self {
        VmError::GenericErr {
            msg: msg.into(),
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn instantiation_err(msg: impl Into<String>) -> Self {
        VmError::InstantiationErr {
            msg: msg.into(),
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn integrity_err() -> Self {
        VmError::IntegrityErr {
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn parse_err(target: impl Into<String>, msg: impl Display) -> Self {
        VmError::ParseErr {
            target_type: target.into(),
            msg: msg.to_string(),
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn deserialization_limit_exceeded(length: usize, max_length: usize) -> Self {
        VmError::DeserializationLimitExceeded {
            length,
            max_length,
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn serialize_err(source: impl Into<String>, msg: impl Display) -> Self {
        VmError::SerializeErr {
            source_type: source.into(),
            msg: msg.to_string(),
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn resolve_err(msg: impl Into<String>) -> Self {
        VmError::ResolveErr {
            msg: msg.into(),
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn result_mismatch(
        function_name: impl Into<String>,
        expected: usize,
        actual: usize,
    ) -> Self {
        VmError::ResultMismatch {
            function_name: function_name.into(),
            expected,
            actual,
            backtrace: BT::capture(),
        }
    }

    // Creates a runtime error with the given message.
    // This is private since it is only needed when converting wasmer::RuntimeError
    // to VmError.
    fn runtime_err(msg: impl Into<String>) -> Self {
        VmError::RuntimeErr {
            msg: msg.into(),
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn static_validation_err(msg: impl Into<String>) -> Self {
        VmError::StaticValidationErr {
            msg: msg.into(),
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn uninitialized_context_data(kind: impl Into<String>) -> Self {
        VmError::UninitializedContextData {
            kind: kind.into(),
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn write_access_denied() -> Self {
        VmError::WriteAccessDenied {
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn max_call_depth_exceeded() -> Self {
        VmError::MaxCallDepthExceeded {
            backtrace: BT::capture(),
        }
    }

    pub(crate) fn function_arity_mismatch(contract_method_arity: usize) -> Self {
        VmError::FunctionArityMismatch {
            contract_method_arity,
            backtrace: BT::capture(),
        }
    }
}

impl_from_err!(CommunicationError, VmError, VmError::CommunicationErr);

impl From<BackendError> for VmError {
    fn from(original: BackendError) -> Self {
        match original {
            BackendError::OutOfGas {} => VmError::gas_depletion(),
            _ => VmError::backend_err(original),
        }
    }
}

impl From<CryptoError> for VmError {
    fn from(original: CryptoError) -> Self {
        VmError::crypto_err(original)
    }
}

impl From<wasmer::wasmparser::BinaryReaderError> for VmError {
    fn from(original: wasmer::wasmparser::BinaryReaderError) -> Self {
        VmError::static_validation_err(format!(
            "Wasm bytecode could not be deserialized. Deserialization error: \"{original}\""
        ))
    }
}

impl From<wasmer::ExportError> for VmError {
    fn from(original: wasmer::ExportError) -> Self {
        VmError::resolve_err(format!("Could not get export: {original}"))
    }
}

impl From<wasmer::SerializeError> for VmError {
    fn from(original: wasmer::SerializeError) -> Self {
        VmError::cache_err(format!("Could not serialize module: {original}"))
    }
}

impl From<wasmer::DeserializeError> for VmError {
    fn from(original: wasmer::DeserializeError) -> Self {
        VmError::cache_err(format!("Could not deserialize module: {original}"))
    }
}

impl From<wasmer::RuntimeError> for VmError {
    fn from(original: wasmer::RuntimeError) -> Self {
        // Do not use the Display implementation or to_string() of `RuntimeError`
        // because it can contain a system specific stack trace, which can
        // lead to non-deterministic execution.
        //
        // Implementation follows https://github.com/wasmerio/wasmer/blob/2.0.0/lib/engine/src/trap/error.rs#L215
        let message = format!("RuntimeError: {}", original.message());
        debug_assert!(
            original.to_string().starts_with(&message),
            "The error message we created is not a prefix of the error message from Wasmer. Our message: '{}'. Wasmer message: '{}'",
            &message,
            original
        );
        VmError::runtime_err(format!("Wasmer runtime error: {}", &message))
    }
}

impl From<wasmer::CompileError> for VmError {
    fn from(original: wasmer::CompileError) -> Self {
        VmError::compile_err(format!("Could not compile: {original}"))
    }
}

impl From<std::convert::Infallible> for VmError {
    fn from(_original: std::convert::Infallible) -> Self {
        unreachable!();
    }
}

impl From<VmError> for wasmer::RuntimeError {
    fn from(original: VmError) -> wasmer::RuntimeError {
        let msg: String = original.to_string();
        wasmer::RuntimeError::new(msg)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // constructors

    #[test]
    fn backend_err_works() {
        let error = VmError::backend_err(BackendError::unknown("something went wrong"));
        match error {
            VmError::BackendErr {
                source: BackendError::Unknown { msg },
                ..
            } => assert_eq!(msg, "something went wrong"),
            e => panic!("Unexpected error: {e:?}"),
        }
    }

    #[test]
    fn cache_err_works() {
        let error = VmError::cache_err("something went wrong");
        match error {
            VmError::CacheErr { msg, .. } => assert_eq!(msg, "something went wrong"),
            e => panic!("Unexpected error: {e:?}"),
        }
    }

    #[test]
    fn compile_err_works() {
        let error = VmError::compile_err("something went wrong");
        match error {
            VmError::CompileErr { msg, .. } => assert_eq!(msg, "something went wrong"),
            e => panic!("Unexpected error: {e:?}"),
        }
    }

    #[test]
    fn conversion_err_works() {
        let error = VmError::conversion_err("i32", "u32", "-9");
        match error {
            VmError::ConversionErr {
                from_type,
                to_type,
                input,
                ..
            } => {
                assert_eq!(from_type, "i32");
                assert_eq!(to_type, "u32");
                assert_eq!(input, "-9");
            }
            e => panic!("Unexpected error: {e:?}"),
        }
    }

    #[test]
    fn crypto_err_works() {
        let error = VmError::crypto_err(CryptoError::generic_err("something went wrong"));
        match error {
            VmError::CryptoErr {
                source: CryptoError::GenericErr { msg, .. },
                ..
            } => assert_eq!(msg, "something went wrong"),
            e => panic!("Unexpected error: {e:?}"),
        }
    }

    #[test]
    fn gas_depletion_works() {
        let error = VmError::gas_depletion();
        match error {
            VmError::GasDepletion { .. } => {}
            e => panic!("Unexpected error: {e:?}"),
        }
    }

    #[test]
    fn generic_err_works() {
        let guess = 7;
        let error = VmError::generic_err(format!("{guess} is too low"));
        match error {
            VmError::GenericErr { msg, .. } => {
                assert_eq!(msg, String::from("7 is too low"));
            }
            e => panic!("Unexpected error: {e:?}"),
        }
    }

    #[test]
    fn instantiation_err_works() {
        let error = VmError::instantiation_err("something went wrong");
        match error {
            VmError::InstantiationErr { msg, .. } => assert_eq!(msg, "something went wrong"),
            e => panic!("Unexpected error: {e:?}"),
        }
    }

    #[test]
    fn integrity_err_works() {
        let error = VmError::integrity_err();
        match error {
            VmError::IntegrityErr { .. } => {}
            e => panic!("Unexpected error: {e:?}"),
        }
    }

    #[test]
    fn parse_err_works() {
        let error = VmError::parse_err("Book", "Missing field: title");
        match error {
            VmError::ParseErr {
                target_type, msg, ..
            } => {
                assert_eq!(target_type, "Book");
                assert_eq!(msg, "Missing field: title");
            }
            e => panic!("Unexpected error: {e:?}"),
        }
    }

    #[test]
    fn serialize_err_works() {
        let error = VmError::serialize_err("Book", "Content too long");
        match error {
            VmError::SerializeErr {
                source_type, msg, ..
            } => {
                assert_eq!(source_type, "Book");
                assert_eq!(msg, "Content too long");
            }
            e => panic!("Unexpected error: {e:?}"),
        }
    }

    #[test]
    fn resolve_err_works() {
        let error = VmError::resolve_err("function has different signature");
        match error {
            VmError::ResolveErr { msg, .. } => assert_eq!(msg, "function has different signature"),
            e => panic!("Unexpected error: {e:?}"),
        }
    }

    #[test]
    fn result_mismatch_works() {
        let error = VmError::result_mismatch("action", 0, 1);
        match error {
            VmError::ResultMismatch {
                function_name,
                expected,
                actual,
                ..
            } => {
                assert_eq!(function_name, "action");
                assert_eq!(expected, 0);
                assert_eq!(actual, 1);
            }
            e => panic!("Unexpected error: {e:?}"),
        }
    }

    #[test]
    fn runtime_err_works() {
        let error = VmError::runtime_err("something went wrong");
        match error {
            VmError::RuntimeErr { msg, .. } => assert_eq!(msg, "something went wrong"),
            e => panic!("Unexpected error: {e:?}"),
        }
    }

    #[test]
    fn static_validation_err_works() {
        let error = VmError::static_validation_err("export xy missing");
        match error {
            VmError::StaticValidationErr { msg, .. } => assert_eq!(msg, "export xy missing"),
            e => panic!("Unexpected error: {e:?}"),
        }
    }

    #[test]
    fn uninitialized_context_data_works() {
        let error = VmError::uninitialized_context_data("foo");
        match error {
            VmError::UninitializedContextData { kind, .. } => assert_eq!(kind, "foo"),
            e => panic!("Unexpected error: {e:?}"),
        }
    }

    #[test]
    fn write_access_denied() {
        let error = VmError::write_access_denied();
        match error {
            VmError::WriteAccessDenied { .. } => {}
            e => panic!("Unexpected error: {e:?}"),
        }
    }
}