fuel-vm 0.44.0

FuelVM interpreter.
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
#![cfg(feature = "std")]

use fuel_asm::PanicReason;
use test_case::test_case;

use fuel_asm::{
    op,
    RegId,
};
use fuel_tx::Receipt;
use fuel_vm::{
    consts::VM_MAX_RAM,
    interpreter::InterpreterParams,
    prelude::*,
};

use super::test_helpers::{
    assert_panics,
    run_script,
    set_full_word,
};
use fuel_tx::ConsensusParameters;

fn setup(program: Vec<Instruction>) -> Transactor<MemoryStorage, Script> {
    let storage = MemoryStorage::default();

    let gas_price = 0;
    let gas_limit = 1_000_000;
    let maturity = Default::default();
    let height = Default::default();

    let consensus_params = ConsensusParameters::standard();

    let script = program.into_iter().collect();

    let tx = TransactionBuilder::script(script, vec![])
        .gas_price(gas_price)
        .script_gas_limit(gas_limit)
        .maturity(maturity)
        .add_random_fee_input()
        .finalize()
        .into_checked(height, &consensus_params)
        .expect("failed to check tx");

    let interpreter_params = InterpreterParams::from(&consensus_params);

    let mut vm = Transactor::new(storage, interpreter_params);
    vm.transact(tx);
    vm
}

#[test]
fn test_lw() {
    let ops = vec![
        op::movi(0x10, 8),
        op::aloc(0x10),
        op::move_(0x10, RegId::HP),
        op::sw(0x10, RegId::ONE, 0),
        op::lw(0x13, 0x10, 0),
        op::ret(RegId::ONE),
    ];
    let vm = setup(ops);
    let vm: &Interpreter<MemoryStorage, Script> = vm.as_ref();
    let result = vm.registers()[0x13_usize];
    assert_eq!(1, result);
}

#[test]
fn test_lw_unaglined() {
    let ops = vec![
        op::movi(0x10, 9),
        op::aloc(0x10),
        op::move_(0x10, RegId::HP),
        op::sw(0x10, RegId::ONE, 0),
        op::lw(0x13, 0x10, 0),
        op::ret(RegId::ONE),
    ];
    let vm = setup(ops);
    let vm: &Interpreter<MemoryStorage, Script> = vm.as_ref();
    let result = vm.registers()[0x13_usize];
    assert_eq!(1, result);
}

#[test]
fn test_lb() {
    let ops = vec![
        op::movi(0x10, 8),
        op::aloc(0x10),
        op::move_(0x10, RegId::HP),
        op::sb(0x10, RegId::ONE, 0),
        op::lb(0x13, 0x10, 0),
        op::ret(RegId::ONE),
    ];
    let vm = setup(ops);
    let vm: &Interpreter<MemoryStorage, Script> = vm.as_ref();
    let result = vm.registers()[0x13_usize] as u8;
    assert_eq!(1, result);
}

#[test]
fn test_aloc_sb_lb_last_byte_of_memory() {
    let ops = vec![
        op::move_(0x20, RegId::HP),
        op::movi(0x10, 1),
        op::aloc(0x10),
        op::move_(0x21, RegId::HP),
        op::sb(RegId::HP, 0x10, 0),
        op::lb(0x13, RegId::HP, 0),
        op::ret(RegId::ONE),
    ];
    let vm = setup(ops);
    let vm: &Interpreter<MemoryStorage, Script> = vm.as_ref();
    let r1 = vm.registers()[0x20_usize];
    let r2 = vm.registers()[0x21_usize];
    assert_eq!(r1 - 1, r2);
    let result = vm.registers()[0x13_usize] as u8;
    assert_eq!(1, result);
}

#[test_case(1, false)]
#[test_case(2, false)]
#[test_case(1, true)]
#[test_case(2, true)]
fn test_stack_and_heap_cannot_overlap(offset: u64, cause_error: bool) {
    // First, allocate almost all memory to heap, and then allocate the remaining
    // memory on the stack. If cause_error is set, then attempts to allocate one
    // byte too much here, causing a memory overflow error.

    let init_bytes = 12000; // Arbitrary number of bytes larger than SSP at start
    let mut ops = set_full_word(0x10, VM_MAX_RAM - init_bytes);
    ops.extend(&[
        op::aloc(0x10),
        op::movi(0x10, (init_bytes - offset).try_into().unwrap()),
        op::sub(0x10, 0x10, RegId::SP),
        op::aloc(0x10),
        op::cfei(
            (if cause_error { offset } else { offset - 1 })
                .try_into()
                .unwrap(),
        ),
        op::ret(RegId::ONE),
    ]);

    let vm = setup(ops);

    let mut receipts = vm.receipts().unwrap().to_vec();

    if cause_error {
        let _ = receipts.pop().unwrap(); // Script result unneeded, the panic receipt below is enough
        if let Receipt::Panic { reason, .. } = receipts.pop().unwrap() {
            assert!(matches!(reason.reason(), PanicReason::MemoryOverflow));
        } else {
            panic!("Expected tx panic when cause_error is set");
        }
    } else if let Receipt::ScriptResult { result, .. } = receipts.pop().unwrap() {
        assert!(matches!(result, ScriptExecutionResult::Success));
    } else {
        panic!("Expected tx success when cause_error is not set");
    }
}

/// tests for cfe & cfs
#[test]
fn dynamic_call_frame_ops() {
    const STACK_EXTEND_AMOUNT: u32 = 100u32;
    const STACK_SHRINK_AMOUNT: u32 = 50u32;
    let ops = vec![
        // log current stack pointer
        op::log(RegId::SP, RegId::ZERO, RegId::ZERO, RegId::ZERO),
        // set stack extension amount for cfe into a register
        op::movi(0x10, STACK_EXTEND_AMOUNT),
        // extend stack dynamically
        op::cfe(0x10),
        // log the current stack pointer
        op::log(RegId::SP, RegId::ZERO, RegId::ZERO, RegId::ZERO),
        // set stack shrink amount for cfs into a register
        op::movi(0x11, STACK_SHRINK_AMOUNT),
        // shrink the stack dynamically
        op::cfs(0x11),
        // return the current stack pointer
        op::ret(RegId::SP),
    ];

    let vm = setup(ops);

    let receipts = vm.receipts().unwrap().to_vec();
    // gather values of sp from the test
    let initial_sp = if let Receipt::Log { ra, .. } = receipts[0] {
        ra
    } else {
        panic!("expected receipt to be log")
    };
    let extended_sp = if let Receipt::Log { ra, .. } = receipts[1] {
        ra
    } else {
        panic!("expected receipt to be log")
    };
    let shrunken_sp = if let Receipt::Return { val, .. } = receipts[2] {
        val
    } else {
        panic!("expected receipt to be return")
    };

    // verify sp increased by expected amount
    assert_eq!(extended_sp, initial_sp + STACK_EXTEND_AMOUNT as u64);
    // verify sp decreased by expected amount
    assert_eq!(
        shrunken_sp,
        initial_sp + STACK_EXTEND_AMOUNT as u64 - STACK_SHRINK_AMOUNT as u64
    );
}

#[test]
fn dynamic_call_frame_ops_bug_missing_ssp_check() {
    let ops = vec![
        op::cfs(RegId::SP),
        op::slli(0x10, RegId::ONE, 26),
        op::aloc(0x10),
        op::sw(RegId::ZERO, 0x10, 0),
        op::ret(RegId::ONE),
    ];
    let receipts = run_script(ops);
    assert_panics(&receipts, PanicReason::MemoryOverflow);
}

#[rstest::rstest]
fn test_mcl_and_mcli(
    #[values(0, 1, 7, 8, 9, 255, 256, 257)] count: u32,
    #[values(true, false)] half: bool, // Clear only first count/2 bytes
    #[values(true, false)] mcli: bool, // Test mcli instead of mcl
) {
    // Allocate count + 1 bytes of memory, so we can check that the last byte is not
    // cleared
    let mut ops = vec![op::movi(0x10, count + 1), op::aloc(0x10), op::movi(0x11, 1)];
    // Fill with ones
    for i in 0..(count + 1) {
        ops.push(op::sb(RegId::HP, 0x11, i as u16));
    }
    // Clear it, or only half if specified
    if mcli {
        if half {
            ops.push(op::mcli(RegId::HP, count / 2));
        } else {
            ops.push(op::mcli(RegId::HP, count));
        }
    } else {
        ops.push(op::movi(0x10, count));
        if half {
            ops.push(op::divi(0x10, 0x10, 2));
        }
        ops.push(op::mcl(RegId::HP, 0x10));
    }
    // Log the result and return
    ops.push(op::movi(0x10, count + 1));
    ops.push(op::logd(0, 0, RegId::HP, 0x10));
    ops.push(op::ret(RegId::ONE));

    let vm = setup(ops);
    let vm: &Interpreter<MemoryStorage, Script> = vm.as_ref();

    if let Some(Receipt::LogData { data, .. }) = vm.receipts().first() {
        let data = data.as_ref().unwrap();
        let c = count as usize;
        assert_eq!(data.len(), c + 1);
        if half {
            assert!(data[..c / 2] == vec![0u8; c / 2]);
            assert!(data[c / 2..] == vec![1u8; c - c / 2 + 1]);
        } else {
            assert!(data[..c] == vec![0u8; c]);
            assert!(data[c] == 1);
        }
    } else {
        panic!("Expected LogData receipt");
    }
}

#[rstest::rstest]
fn test_mcp_and_mcpi(
    #[values(0, 1, 7, 8, 9, 255, 256, 257)] count: u32,
    #[values(true, false)] mcpi: bool, // Test mcpi instead of mcp
) {
    // Allocate (count + 1) * 2 bytes of memory, so we can check that the last byte is not
    // copied
    let mut ops = vec![
        op::movi(0x10, (count + 1) * 2),
        op::aloc(0x10),
        op::movi(0x11, 1),
        op::movi(0x12, 2),
    ];
    // Fill count + 1 bytes with ones, and the next count + 1 bytes with twos
    for i in 0..(count + 1) * 2 {
        ops.push(op::sb(
            RegId::HP,
            if i < count + 1 { 0x11 } else { 0x12 },
            i as u16,
        ));
    }
    // Compute dst address
    ops.push(op::addi(0x11, RegId::HP, (count + 1) as u16));
    // Copy count bytes
    if mcpi {
        ops.push(op::mcpi(0x11, RegId::HP, count as u16));
    } else {
        ops.push(op::movi(0x10, count));
        ops.push(op::mcp(0x11, RegId::HP, 0x10));
    }
    // Log the result and return
    ops.push(op::movi(0x10, (count + 1) * 2));
    ops.push(op::logd(0, 0, RegId::HP, 0x10));
    ops.push(op::ret(RegId::ONE));

    let vm = setup(ops);
    let vm: &Interpreter<MemoryStorage, Script> = vm.as_ref();

    if let Some(Receipt::LogData { data, .. }) = vm.receipts().first() {
        let data = data.as_ref().unwrap();
        let c = count as usize;
        assert_eq!(data.len(), (c + 1) * 2);
        let mut expected = vec![1u8; c * 2 + 1];
        expected.push(2);
        assert!(data == &expected);
    } else {
        panic!("Expected LogData receipt");
    }
}

#[rstest::rstest]
fn test_meq(
    #[values(0, 1, 7, 8, 9, 255, 256, 257)] count: u32,
    #[values("equal", "last-not-equal", "first-not-equal")] pattern: &str,
) {
    // Allocate count * 2 bytes of memory
    let mut ops = vec![
        op::movi(0x10, count * 2),
        op::aloc(0x10),
        op::movi(0x11, 1),
        op::movi(0x12, 2),
    ];
    // Fill count*2 bytes with ones, and then patch with given pattern
    for i in 0..(count * 2) {
        ops.push(op::sb(RegId::HP, 0x11, i as u16));
    }
    if count != 0 {
        match pattern {
            "equal" => {
                // Do nothing
            }
            "last-not-equal" => {
                ops.push(op::sb(RegId::HP, 0x12, (count * 2 - 1) as u16));
            }
            "first-not-equal" => {
                ops.push(op::sb(RegId::HP, 0x12, 0));
            }
            _ => unreachable!(),
        }
    }

    // Compare
    ops.push(op::movi(0x10, count));
    ops.push(op::addi(0x11, RegId::HP, count as u16));
    ops.push(op::meq(0x10, RegId::HP, 0x11, 0x10));
    // Log the result and return
    ops.push(op::log(0x10, RegId::ZERO, RegId::ZERO, RegId::ZERO));
    ops.push(op::ret(RegId::ONE));

    let vm = setup(ops);
    let vm: &Interpreter<MemoryStorage, Script> = vm.as_ref();

    if let Some(Receipt::Log { ra, .. }) = vm.receipts().first() {
        if count == 0 {
            assert_eq!(*ra, 1); // Empty ranges always equal
            return
        }
        match pattern {
            "equal" => {
                assert_eq!(*ra, 1);
            }
            "last-not-equal" | "first-not-equal" => {
                assert_eq!(*ra, 0);
            }
            _ => unreachable!(),
        }
    } else {
        panic!("Expected LogData receipt");
    }
}

#[test]
fn test_heap_not_executable() {
    let receipts = run_script(vec![
        op::movi(0x10, 16),
        op::aloc(0x10),
        op::sub(0x10, RegId::HP, RegId::IS),
        op::divi(0x10, 0x10, 4),
        op::jmp(0x10),
        op::ret(RegId::ONE),
    ]);

    if let Some(Receipt::Panic { reason, .. }) = receipts.first() {
        assert!(matches!(reason.reason(), PanicReason::MemoryNotExecutable));
    } else {
        panic!("Expected panic receipt");
    }
}