rwasm 0.4.7

ZK-friendly WebAssembly runtime optimized for blockchain and zero-knowledge applications
Documentation
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
use crate::{
    types::codec::{decode_section_bytes, decode_section_vec},
    CompilationConfig, CompilationError, ConstructorParams, HintType, InstructionSet, ModuleParser,
    Opcode,
};
use alloc::{sync::Arc, vec, vec::Vec};
use bincode::{
    de::Decoder,
    enc::Encoder,
    error::{DecodeError, EncodeError},
    Decode, Encode,
};
use core::ops::Deref;

mod verification;
pub use verification::{RwasmModuleError, RwasmModuleVerificationError};

/// Represents a compiled rWasm module.
///
/// An `RwasmModule` encapsulates the executable code, static data, and element (function/table
/// reference) information needed for execution within the rWasm virtual machine.
///
/// It's compiled from Wasm
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Default, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct RwasmModule {
    inner: Arc<RwasmModuleInner>,
}

fn _check() {
    fn assert_send_sync<T>() {}
    assert_send_sync::<RwasmModule>();
}

impl RwasmModule {
    pub fn new_or_empty(sink: &[u8]) -> (Self, usize) {
        if sink.is_empty() {
            (Self::empty(), 0)
        } else {
            Self::new(sink)
        }
    }

    pub fn compile(
        config: CompilationConfig,
        wasm_binary: &[u8],
    ) -> Result<(Self, ConstructorParams), CompilationError> {
        let mut parser = ModuleParser::new(config);
        parser.parse(wasm_binary)?;
        let result = parser.finalize(wasm_binary)?;
        Ok(result)
    }

    pub fn empty() -> Self {
        RwasmModuleInner {
            code_section: InstructionSet::default(),
            data_section: vec![],
            elem_section: vec![],
            hint_section: vec![],
            source_pc: 0,
        }
        .into()
    }

    pub fn new(sink: &[u8]) -> (Self, usize) {
        Self::new_checked(sink).unwrap_or_else(|_| unreachable!("rwasm: malformed rwasm binary"))
    }

    /// Decodes one rWasm module and returns the number of bytes consumed.
    ///
    /// # Note
    ///
    /// "Checked" refers to the binary encoding only: this performs **no** structural validation of
    /// the decoded module. Branch targets, call targets, segment indices, and stack offsets are all
    /// taken at face value, so a module accepted here can still trap at any point during execution.
    /// Use [`RwasmModule::new_verified`] for bytecode that this crate did not produce itself.
    pub fn new_checked(sink: &[u8]) -> Result<(Self, usize), DecodeError> {
        let (inner, bytes_read): (RwasmModuleInner, usize) =
            bincode::decode_from_slice(sink, bincode::config::legacy())?;
        Ok((inner.into(), bytes_read))
    }

    /// Decodes exactly one rWasm module and rejects trailing bytes.
    ///
    /// # Note
    ///
    /// Just like [`RwasmModule::new_checked`], this validates the encoding but not the structure
    /// of the decoded module.
    pub fn new_checked_exact(sink: &[u8]) -> Result<Self, DecodeError> {
        let (module, bytes_read) = Self::new_checked(sink)?;
        if bytes_read != sink.len() {
            return Err(DecodeError::Other("rwasm: trailing bytes after module"));
        }
        Ok(module)
    }

    /// Decodes and explicitly verifies one rWasm module.
    pub fn new_verified(sink: &[u8]) -> Result<(Self, usize), RwasmModuleError> {
        let (module, bytes_read) = Self::new_checked(sink)?;
        module.verify()?;
        Ok((module, bytes_read))
    }

    /// Decodes and explicitly verifies exactly one rWasm module, rejecting trailing bytes.
    pub fn new_verified_exact(sink: &[u8]) -> Result<Self, RwasmModuleError> {
        let module = Self::new_checked_exact(sink)?;
        module.verify()?;
        Ok(module)
    }

    pub fn serialize(&self) -> Vec<u8> {
        bincode::encode_to_vec(&*self.inner, bincode::config::legacy())
            .unwrap_or_else(|_| unreachable!("rwasm: failed to serialize module"))
    }

    pub fn hint_type(&self) -> HintType {
        HintType::from_ref(&self.hint_section)
    }
}

impl From<RwasmModuleInner> for RwasmModule {
    fn from(value: RwasmModuleInner) -> Self {
        Self {
            inner: Arc::new(value),
        }
    }
}

impl Deref for RwasmModule {
    type Target = RwasmModuleInner;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Default, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct RwasmModuleInner {
    /// The main instruction set (bytecode) for this module that includes an entrypoint
    /// and all required functions.
    ///
    /// The source program counter-offset is always 0.
    pub code_section: InstructionSet,

    /// Linear read-only memory data initialized when the module is instantiated.
    pub data_section: Vec<u8>,

    /// Table initializers, function refs for the module's table section.
    pub elem_section: Vec<u32>,

    /// A hint section that stores original bytecode that used as a compiler input.
    /// It can be Wasm, EVM bytecode, or anything else.
    /// Use this section signature bytes to determine the type of the file,
    /// always fallback to EVM if it can't be extracted.
    pub hint_section: Vec<u8>,

    /// A program counter that points to the original bytecode offset, where the execution starts.
    /// But it ignores start and init sections.
    /// If you want to start with init (like the first function run, then use 0 offset, otherwise this PC).
    ///
    /// Note: For old binaries this is always 0.
    pub source_pc: u32,
}

/// Rwasm magic bytes 0xef52 (0x52 stands for 'R' in ASCII)
pub const RWASM_MAGIC_BYTE_0: u8 = 0xef;
pub const RWASM_MAGIC_BYTE_1: u8 = 0x52;

/// Rwasm binary version
pub const RWASM_VERSION_V1: u8 = 0x01;

impl Encode for RwasmModuleInner {
    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
        Encode::encode(&RWASM_MAGIC_BYTE_0, encoder)?;
        Encode::encode(&RWASM_MAGIC_BYTE_1, encoder)?;
        Encode::encode(&RWASM_VERSION_V1, encoder)?;
        Encode::encode(&self.code_section, encoder)?;
        Encode::encode(&self.data_section, encoder)?;
        Encode::encode(&self.elem_section, encoder)?;
        Encode::encode(&self.hint_section, encoder)?;
        Encode::encode(&self.source_pc, encoder)?;
        Ok(())
    }
}

impl<Context> Decode<Context> for RwasmModuleInner {
    fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
        let sig0: u8 = Decode::decode(decoder)?;
        let sig1: u8 = Decode::decode(decoder)?;
        if sig0 != RWASM_MAGIC_BYTE_0 || sig1 != RWASM_MAGIC_BYTE_1 {
            return Err(DecodeError::Other("rwasm: invalid magic bytes"));
        }
        let version: u8 = Decode::decode(decoder)?;
        if version != RWASM_VERSION_V1 {
            return Err(DecodeError::Other("rwasm: not supported version"));
        }
        let code_section: InstructionSet = Decode::decode(decoder)?;
        let data_section = decode_section_bytes(decoder)?;
        let elem_section: Vec<u32> = decode_section_vec(decoder)?;
        let wasm_section = decode_section_bytes(decoder)?;
        let source_pc: u32 = match Decode::decode(decoder) {
            Ok(source_pc) => source_pc,
            Err(DecodeError::UnexpectedEnd { additional }) => {
                if additional != size_of::<u32>() {
                    return Err(DecodeError::UnexpectedEnd { additional });
                }
                // This field is optional if it's not presented, then fallback to 0
                0
            }
            Err(err) => return Err(err),
        };
        Ok(Self {
            code_section,
            data_section,
            elem_section,
            hint_section: wasm_section,
            source_pc,
        })
    }
}

impl core::fmt::Display for RwasmModule {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        writeln!(f, "RwasmModule {{")?;
        let mut func_num = 0;
        writeln!(f, " .function_begin_{} (#{})", 0, func_num)?;
        for (pos, opcode) in self.code_section.iter().copied().enumerate() {
            if let Some(Opcode::SignatureCheck(_)) = self.code_section.get(pos) {
                writeln!(f, " .function_end\n")?;
                func_num += 1;
                writeln!(f, " .function_begin_{} (#{})", pos, func_num)?;
            }
            write!(f, "  {:04}: {}", pos, opcode)?;
            if pos == self.source_pc as usize {
                write!(f, "  <- SOURCE")?;
            }
            writeln!(f)?;
        }
        writeln!(f, " .function_end\n")?;
        writeln!(f, " .ro_data: {:x?},", self.data_section.as_slice())?;
        writeln!(f, " .ro_elem: {:?},", self.elem_section.as_slice())?;
        writeln!(f, " .source_pc: {:?},", self.source_pc)?;
        writeln!(f, "}}")?;
        Ok(())
    }
}

#[derive(Default)]
pub struct RwasmModuleBuilder {
    code_section: InstructionSet,
    data_section: Vec<u8>,
    elem_section: Vec<u32>,
    hint_section: Vec<u8>,
    source_pc: u32,
}

impl RwasmModuleBuilder {
    pub fn new(code_section: InstructionSet) -> Self {
        Self {
            code_section,
            ..Default::default()
        }
    }

    pub fn with_data_section(mut self, data: &[u8]) -> Self {
        self.data_section.extend_from_slice(data);
        self
    }

    pub fn with_elem_section(mut self, elem: &[u32]) -> Self {
        self.elem_section.extend_from_slice(elem);
        self
    }

    pub fn with_hint_section(mut self, hint: &[u8]) -> Self {
        self.hint_section = hint.to_vec();
        self
    }

    pub fn with_source_pc(mut self, source_pc: u32) -> Self {
        self.source_pc = source_pc;
        self
    }

    pub fn build(self) -> RwasmModule {
        RwasmModuleInner {
            code_section: self.code_section,
            data_section: self.data_section,
            elem_section: self.elem_section,
            hint_section: self.hint_section,
            source_pc: self.source_pc,
        }
        .into()
    }
}

impl From<RwasmModuleBuilder> for RwasmModule {
    fn from(val: RwasmModuleBuilder) -> Self {
        val.build()
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        instruction_set, RwasmModule, RwasmModuleInner, RWASM_MAGIC_BYTE_0, RWASM_MAGIC_BYTE_1,
        RWASM_VERSION_V1,
    };
    use bincode::error::DecodeError;
    use hex_literal::hex;

    fn test_module() -> RwasmModuleInner {
        RwasmModuleInner {
            code_section: instruction_set! {
                I32Const(100)
                I32Const(20)
                I32Add
                I32Const(3)
                I32Add
                Drop
            },
            data_section: Default::default(),
            elem_section: vec![],
            hint_section: vec![],
            source_pc: 0,
        }
    }

    #[test]
    fn test_module_encoding() {
        let module = test_module();
        let encoded_module = bincode::encode_to_vec(&module, bincode::config::legacy()).unwrap();
        println!("{}", hex::encode(&encoded_module));
        let module2: RwasmModuleInner;
        (module2, _) =
            bincode::decode_from_slice(&encoded_module, bincode::config::legacy()).unwrap();
        assert_eq!(module, module2);
        assert_eq!(encoded_module, RwasmModule::from(module2).serialize());
    }

    #[test]
    fn test_decode_module_wo_source_pc() {
        const LEGACY_MODULE: &[u8] = &hex!("ef52010600000000000000150000006400000015000000140000003e00000015000000030000003e000000160000000000000000000000050000000000000005000000060000000700000008000000090000000000000000000000");
        let module2: RwasmModuleInner;
        (module2, _) =
            bincode::decode_from_slice(LEGACY_MODULE, bincode::config::legacy()).unwrap();
        assert_eq!(module2.source_pc, 0);
    }

    #[test]
    fn test_decode_rejects_partial_source_pc() {
        let module = test_module();
        let encoded_module = bincode::encode_to_vec(&module, bincode::config::legacy()).unwrap();
        for missing in 1..size_of::<u32>() {
            let truncated_len = encoded_module.len() - missing;
            let err = bincode::decode_from_slice::<RwasmModuleInner, _>(
                &encoded_module[..truncated_len],
                bincode::config::legacy(),
            )
            .expect_err("partial source_pc must be rejected");
            assert!(
                matches!(err, DecodeError::UnexpectedEnd { .. }),
                "expected UnexpectedEnd for missing {missing} bytes, got {err:?}"
            );
        }
    }

    #[test]
    fn test_decode_exact_rejects_trailing_garbage() {
        let module = test_module();
        let mut encoded_module =
            bincode::encode_to_vec(&module, bincode::config::legacy()).unwrap();
        encoded_module.extend_from_slice(&[0xde, 0xad, 0xbe, 0xef]);

        let (_, bytes_read) = RwasmModule::new_checked(&encoded_module)
            .expect("streaming decode returns consumed length");
        assert_eq!(bytes_read, encoded_module.len() - 4);

        let err = RwasmModule::new_checked_exact(&encoded_module)
            .expect_err("exact decode must reject trailing bytes");
        assert!(matches!(err, DecodeError::Other(_)));
    }

    /// Every section length is attacker-controlled, so a truncated header must be rejected without
    /// allocating the announced capacity. Before the fix these inputs panicked with
    /// `capacity overflow`, or aborted through `handle_alloc_error` for large non-overflowing
    /// lengths.
    #[test]
    fn test_decode_rejects_oversized_section_lengths() {
        // Number of empty sections preceding the one under test, in encoding order:
        // code, data, elem, hint.
        for preceding_sections in 0..4 {
            for bogus_length in [u64::MAX, 1u64 << 40] {
                let mut sink = vec![RWASM_MAGIC_BYTE_0, RWASM_MAGIC_BYTE_1, RWASM_VERSION_V1];
                for _ in 0..preceding_sections {
                    sink.extend_from_slice(&0u64.to_le_bytes());
                }
                sink.extend_from_slice(&bogus_length.to_le_bytes());

                let err = RwasmModule::new_checked(&sink)
                    .expect_err("section length larger than the remaining input must be rejected");
                assert!(
                    matches!(
                        err,
                        DecodeError::UnexpectedEnd { .. } | DecodeError::OutsideUsizeRange(_)
                    ),
                    "unexpected error for section {preceding_sections} \
                     with length {bogus_length}: {err:?}"
                );
            }
        }
    }

    /// A section length that fits the input must still decode, so the bound above cannot be a
    /// blanket size limit.
    #[test]
    fn test_decode_accepts_large_hint_section() {
        let mut module = test_module();
        module.hint_section = vec![0xab; 512 * 1024];
        let encoded_module = bincode::encode_to_vec(&module, bincode::config::legacy()).unwrap();
        let (decoded, _): (RwasmModuleInner, usize) =
            bincode::decode_from_slice(&encoded_module, bincode::config::legacy()).unwrap();
        assert_eq!(module, decoded);
    }

    #[test]
    fn test_endianness() {
        let module = vec![1, 2, 3];
        let encoded_module = bincode::encode_to_vec(&module, bincode::config::legacy()).unwrap();
        println!("{:?}", encoded_module);
        let slc = unsafe {
            core::slice::from_raw_parts(encoded_module.as_ptr().offset(8) as *const u32, 3)
        };
        println!("{:?}", slc);
    }
}