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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
#[cfg(test)]
mod tests;

use crate::{
    checked_transaction::{
        Checked,
        IntoChecked,
        ParallelExecutor,
    },
    consts::*,
    context::Context,
    error::{
        Bug,
        BugId,
        BugVariant,
        InterpreterError,
        PredicateVerificationFailed,
    },
    gas::GasCosts,
    interpreter::{
        CheckedMetadata,
        ExecutableTransaction,
        InitialBalances,
        Interpreter,
        RuntimeBalances,
    },
    predicate::RuntimePredicate,
    state::{
        ExecuteState,
        ProgramState,
        StateTransition,
        StateTransitionRef,
    },
    storage::{
        InterpreterStorage,
        PredicateStorage,
    },
};

use crate::error::BugVariant::GlobalGasUnderflow;
use fuel_asm::{
    PanicReason,
    RegId,
};
use fuel_tx::{
    field::{
        ReceiptsRoot,
        Salt,
        Script as ScriptField,
        StorageSlots,
    },
    input::{
        coin::CoinPredicate,
        message::{
            MessageCoinPredicate,
            MessageDataPredicate,
        },
    },
    Chargeable,
    ConsensusParameters,
    Contract,
    Create,
    Input,
    Receipt,
    ScriptExecutionResult,
};
use fuel_types::Word;

/// Predicates were checked succesfully
#[derive(Debug, Clone, Copy)]
pub struct PredicatesChecked {
    gas_used: Word,
}
impl PredicatesChecked {
    pub fn gas_used(&self) -> Word {
        self.gas_used
    }
}

enum PredicateRunKind<'a, Tx> {
    Verifying(&'a Tx),
    Estimating(&'a mut Tx),
}

impl<'a, Tx> PredicateRunKind<'a, Tx> {
    fn tx(&self) -> &Tx {
        match self {
            PredicateRunKind::Verifying(tx) => tx,
            PredicateRunKind::Estimating(tx) => tx,
        }
    }
}

#[derive(Debug, Clone, Copy)]
enum PredicateAction {
    Verifying,
    Estimating,
}

impl<Tx> From<&PredicateRunKind<'_, Tx>> for PredicateAction {
    fn from(kind: &PredicateRunKind<'_, Tx>) -> Self {
        match kind {
            PredicateRunKind::Verifying(_) => PredicateAction::Verifying,
            PredicateRunKind::Estimating(_) => PredicateAction::Estimating,
        }
    }
}

impl<T> Interpreter<PredicateStorage, T> {
    /// Initialize the VM with the provided transaction and check all predicates defined
    /// in the inputs.
    ///
    /// The storage provider is not used since contract opcodes are not allowed for
    /// predicates.
    pub fn check_predicates<Tx>(
        checked: &Checked<Tx>,
        params: ConsensusParameters,
        gas_costs: GasCosts,
    ) -> Result<PredicatesChecked, PredicateVerificationFailed>
    where
        Tx: ExecutableTransaction,
        <Tx as IntoChecked>::Metadata: CheckedMetadata,
    {
        let tx = checked.transaction();
        let balances = checked.metadata().balances();
        Self::run_predicate(PredicateRunKind::Verifying(tx), balances, params, gas_costs)
    }

    /// Initialize the VM with the provided transaction and check all predicates defined
    /// in the inputs in parallel.
    ///
    /// The storage provider is not used since contract opcodes are not allowed for
    /// predicates.
    pub async fn check_predicates_async<Tx, E>(
        checked: &Checked<Tx>,
        params: ConsensusParameters,
        gas_costs: GasCosts,
    ) -> Result<PredicatesChecked, PredicateVerificationFailed>
    where
        Tx: ExecutableTransaction + Send + 'static,
        <Tx as IntoChecked>::Metadata: CheckedMetadata,
        E: ParallelExecutor,
    {
        let balances = checked.metadata().balances();
        let tx = checked.transaction();

        let predicates_checked = Self::run_predicate_async::<Tx, E>(
            PredicateRunKind::Verifying(tx),
            balances,
            params,
            gas_costs,
        )
        .await?;

        Ok(predicates_checked)
    }

    /// Initialize the VM with the provided transaction, check all predicates defined in
    /// the inputs and set the predicate_gas_used to be the actual gas consumed during
    /// execution for each predicate.
    ///
    /// The storage provider is not used since contract opcodes are not allowed for
    /// predicates.
    pub fn estimate_predicates<Tx>(
        transaction: &mut Tx,
        balances: InitialBalances,
        params: ConsensusParameters,
        gas_costs: GasCosts,
    ) -> Result<(), PredicateVerificationFailed>
    where
        Tx: ExecutableTransaction,
    {
        Self::run_predicate(
            PredicateRunKind::Estimating(transaction),
            balances,
            params,
            gas_costs,
        )?;
        Ok(())
    }

    /// Initialize the VM with the provided transaction, check all predicates defined in
    /// the inputs and set the predicate_gas_used to be the actual gas consumed during
    /// execution for each predicate in parallel.
    ///
    /// The storage provider is not used since contract opcodes are not allowed for
    /// predicates.
    pub async fn estimate_predicates_async<Tx, E>(
        transaction: &mut Tx,
        balances: InitialBalances,
        params: ConsensusParameters,
        gas_costs: GasCosts,
    ) -> Result<(), PredicateVerificationFailed>
    where
        Tx: ExecutableTransaction + Send + 'static,
        E: ParallelExecutor,
    {
        Self::run_predicate_async::<Tx, E>(
            PredicateRunKind::Estimating(transaction),
            balances,
            params,
            gas_costs,
        )
        .await?;

        Ok(())
    }

    async fn run_predicate_async<Tx, E>(
        kind: PredicateRunKind<'_, Tx>,
        balances: InitialBalances,
        params: ConsensusParameters,
        gas_costs: GasCosts,
    ) -> Result<PredicatesChecked, PredicateVerificationFailed>
    where
        Tx: ExecutableTransaction + Send + 'static,
        E: ParallelExecutor,
    {
        let mut checks = vec![];
        let predicate_action = PredicateAction::from(&kind);

        for index in 0..kind.tx().inputs().len() {
            if let Some(predicate) = RuntimePredicate::from_tx(&params, kind.tx(), index)
            {
                let tx = kind.tx().clone();
                let gas_costs = gas_costs.clone();
                let balances = balances.clone();

                let verify_task = E::create_task(move || {
                    Self::check_predicate(
                        tx,
                        index,
                        params,
                        gas_costs,
                        balances,
                        predicate_action,
                        predicate,
                    )
                });

                checks.push(verify_task);
            }
        }

        let checks = E::execute_tasks(checks).await;

        Self::finalize_check_predicate(kind, checks, predicate_action, params)
    }

    fn run_predicate<Tx>(
        kind: PredicateRunKind<Tx>,
        balances: InitialBalances,
        params: ConsensusParameters,
        gas_costs: GasCosts,
    ) -> Result<PredicatesChecked, PredicateVerificationFailed>
    where
        Tx: ExecutableTransaction,
    {
        let predicate_action = PredicateAction::from(&kind);
        let mut checks = vec![];

        for index in 0..kind.tx().inputs().len() {
            let tx = kind.tx().clone();

            if let Some(predicate) = RuntimePredicate::from_tx(&params, &tx, index) {
                let gas_costs = gas_costs.clone();
                let balances = balances.clone();

                checks.push(Self::check_predicate(
                    tx,
                    index,
                    params,
                    gas_costs,
                    balances,
                    predicate_action,
                    predicate,
                ));
            }
        }

        Self::finalize_check_predicate(kind, checks, predicate_action, params)
    }

    fn check_predicate<Tx>(
        tx: Tx,
        index: usize,
        params: ConsensusParameters,
        gas_costs: GasCosts,
        balances: InitialBalances,
        predicate_action: PredicateAction,
        predicate: RuntimePredicate,
    ) -> Result<(Word, usize), PredicateVerificationFailed>
    where
        Tx: ExecutableTransaction,
    {
        match &tx.inputs()[index] {
            Input::CoinPredicate(CoinPredicate {
                owner: address,
                predicate,
                ..
            })
            | Input::MessageDataPredicate(MessageDataPredicate {
                recipient: address,
                predicate,
                ..
            })
            | Input::MessageCoinPredicate(MessageCoinPredicate {
                predicate,
                recipient: address,
                ..
            }) => {
                if !Input::is_predicate_owner_valid(address, predicate, &params.chain_id)
                {
                    return Err(PredicateVerificationFailed::InvalidOwner)
                }
            }
            _ => {}
        }

        let mut vm = Interpreter::with_storage(PredicateStorage {}, params, gas_costs);

        let available_gas = match predicate_action {
            PredicateAction::Verifying => {
                let context = Context::PredicateVerification { program: predicate };
                let available_gas =
                    if let Some(x) = tx.inputs()[index].predicate_gas_used() {
                        x
                    } else {
                        return Err(PredicateVerificationFailed::GasNotSpecified)
                    };

                vm.init_predicate(context, tx, balances, available_gas)?;
                available_gas
            }
            PredicateAction::Estimating => {
                let context = Context::PredicateEstimation { program: predicate };
                let available_gas =
                    core::cmp::min(params.max_gas_per_predicate, params.max_gas_per_tx);

                vm.init_predicate(context, tx, balances, available_gas)?;
                available_gas
            }
        };

        let result = vm.verify_predicate();
        let is_successful = matches!(result, Ok(ProgramState::Return(0x01)));

        let gas_used = available_gas
            .checked_sub(vm.remaining_gas())
            .ok_or_else(|| Bug::new(BugId::ID004, GlobalGasUnderflow))?;

        if let PredicateAction::Verifying = predicate_action {
            if !is_successful {
                result?;
                return Err(PredicateVerificationFailed::False)
            }

            if vm.remaining_gas() != 0 {
                return Err(PredicateVerificationFailed::GasMismatch)
            }
        }

        Ok((gas_used, index))
    }

    fn finalize_check_predicate<Tx>(
        mut kind: PredicateRunKind<Tx>,
        checks: Vec<Result<(Word, usize), PredicateVerificationFailed>>,
        predicate_action: PredicateAction,
        params: ConsensusParameters,
    ) -> Result<PredicatesChecked, PredicateVerificationFailed>
    where
        Tx: ExecutableTransaction,
    {
        if let PredicateRunKind::Estimating(tx) = &mut kind {
            checks.iter().for_each(|result| {
                if let Ok((gas_used, index)) = result {
                    match &mut tx.inputs_mut()[*index] {
                        Input::CoinPredicate(CoinPredicate {
                            predicate_gas_used,
                            ..
                        })
                        | Input::MessageCoinPredicate(MessageCoinPredicate {
                            predicate_gas_used,
                            ..
                        })
                        | Input::MessageDataPredicate(MessageDataPredicate {
                            predicate_gas_used,
                            ..
                        }) => {
                            *predicate_gas_used = *gas_used;
                        }
                        _ => {
                            unreachable!(
                                "It was checked before during iteration over predicates"
                            )
                        }
                    }
                }
            })
        }

        let cumulative_gas_used = checks.into_iter().try_fold(0u64, |acc, result| {
            acc.checked_add(result.map(|(gas_used, _)| gas_used)?)
                .ok_or(PredicateVerificationFailed::OutOfGas)
        })?;

        match predicate_action {
            PredicateAction::Verifying => {
                if cumulative_gas_used > kind.tx().limit() {
                    return Err(PredicateVerificationFailed::CumulativePredicateGasExceededTxGasLimit);
                }
            }
            PredicateAction::Estimating => {
                if cumulative_gas_used > params.max_gas_per_tx {
                    return Err(PredicateVerificationFailed::CumulativePredicateGasExceededTxGasLimit);
                }
            }
        }

        Ok(PredicatesChecked {
            gas_used: cumulative_gas_used,
        })
    }
}

impl<S, Tx> Interpreter<S, Tx>
where
    S: InterpreterStorage,
{
    fn deploy_inner(
        create: &mut Create,
        storage: &mut S,
        initial_balances: InitialBalances,
        params: &ConsensusParameters,
    ) -> Result<(), InterpreterError> {
        let remaining_gas = create
            .limit()
            .checked_sub(create.gas_used_by_predicates())
            .ok_or_else(|| InterpreterError::Panic(PanicReason::OutOfGas))?;

        let metadata = create.metadata().as_ref();
        debug_assert!(
            metadata.is_some(),
            "`deploy_inner` is called without cached metadata"
        );
        let salt = create.salt();
        let storage_slots = create.storage_slots();
        let contract = Contract::try_from(&*create)?;
        let root = if let Some(m) = metadata {
            m.contract_root
        } else {
            contract.root()
        };

        let storage_root = if let Some(m) = metadata {
            m.state_root
        } else {
            Contract::initial_state_root(storage_slots.iter())
        };

        let id = if let Some(m) = metadata {
            m.contract_id
        } else {
            contract.id(salt, &root, &storage_root)
        };

        // Prevent redeployment of contracts
        if storage
            .storage_contract_exists(&id)
            .map_err(InterpreterError::from_io)?
        {
            return Err(InterpreterError::Panic(
                PanicReason::ContractIdAlreadyDeployed,
            ))
        }

        storage
            .deploy_contract_with_id(salt, storage_slots, &contract, &root, &id)
            .map_err(InterpreterError::from_io)?;
        Self::finalize_outputs(
            create,
            false,
            remaining_gas,
            &initial_balances,
            &RuntimeBalances::try_from(initial_balances.clone())?,
            params,
        )?;
        Ok(())
    }
}

impl<S, Tx> Interpreter<S, Tx>
where
    S: InterpreterStorage,
    Tx: ExecutableTransaction,
{
    fn update_transaction_outputs(&mut self) -> Result<(), InterpreterError> {
        let outputs = self.transaction().outputs().len();
        (0..outputs).try_for_each(|o| self.update_memory_output(o))?;
        Ok(())
    }

    pub(crate) fn run(&mut self) -> Result<ProgramState, InterpreterError> {
        // TODO: Remove `Create` from here
        let state = if let Some(create) = self.tx.as_create_mut() {
            Self::deploy_inner(
                create,
                &mut self.storage,
                self.initial_balances.clone(),
                &self.params,
            )?;
            self.update_transaction_outputs()?;
            ProgramState::Return(1)
        } else {
            if self.transaction().inputs().iter().any(|input| {
                if let Input::Contract(contract) = input {
                    !self
                        .check_contract_exists(&contract.contract_id)
                        .unwrap_or(false)
                } else {
                    false
                }
            }) {
                return Err(InterpreterError::Panic(PanicReason::ContractNotFound))
            }

            if let Some(script) = self.transaction().as_script() {
                let offset = (self.tx_offset() + script.script_offset()) as Word;

                self.registers[RegId::PC] = offset;
                self.registers[RegId::IS] = offset;
            }

            // TODO set tree balance

            // `Interpreter` supports only `Create` and `Script` transactions. It is not
            // `Create` -> it is `Script`.
            let program = if !self
                .transaction()
                .as_script()
                .expect("It should be `Script` transaction")
                .script()
                .is_empty()
            {
                self.run_program()
            } else {
                // Return `1` as successful execution.
                let return_val = 1;
                self.ret(return_val)?;
                Ok(ProgramState::Return(return_val))
            };

            let gas_used = self
                .transaction()
                .limit()
                .checked_sub(self.remaining_gas())
                .ok_or_else(|| Bug::new(BugId::ID002, BugVariant::GlobalGasUnderflow))?;

            // Catch VM panic and don't propagate, generating a receipt
            let (status, program) = match program {
                Ok(s) => {
                    // either a revert or success
                    let res = if let ProgramState::Revert(_) = &s {
                        ScriptExecutionResult::Revert
                    } else {
                        ScriptExecutionResult::Success
                    };
                    (res, s)
                }

                Err(e) => match e.instruction_result() {
                    Some(result) => {
                        self.append_panic_receipt(result);

                        (ScriptExecutionResult::Panic, ProgramState::Revert(0))
                    }

                    // This isn't a specified case of an erroneous program and should be
                    // propagated. If applicable, OS errors will fall into this category.
                    None => return Err(e),
                },
            };

            let receipt = Receipt::script_result(status, gas_used);

            self.append_receipt(receipt);

            #[cfg(feature = "debug")]
            if program.is_debug() {
                self.debugger_set_last_state(program);
            }

            if let Some(script) = self.tx.as_script_mut() {
                let receipts_root = self.receipts.root();
                *script.receipts_root_mut() = receipts_root;
            }

            let revert = matches!(program, ProgramState::Revert(_));
            let remaining_gas = self.remaining_gas();
            Self::finalize_outputs(
                &mut self.tx,
                revert,
                remaining_gas,
                &self.initial_balances,
                &self.balances,
                &self.params,
            )?;
            self.update_transaction_outputs()?;

            program
        };

        Ok(state)
    }

    pub(crate) fn run_program(&mut self) -> Result<ProgramState, InterpreterError> {
        loop {
            if self.registers[RegId::PC] >= VM_MAX_RAM {
                return Err(InterpreterError::Panic(PanicReason::MemoryOverflow))
            }

            // Check whether the instruction will be executed in a call context
            let in_call = !self.frames.is_empty();

            let state = self.execute()?;

            if in_call {
                // Only reverts should terminate execution from a call context
                if let ExecuteState::Revert(r) = state {
                    return Ok(ProgramState::Revert(r))
                }
            } else {
                match state {
                    ExecuteState::Return(r) => return Ok(ProgramState::Return(r)),

                    ExecuteState::ReturnData(d) => return Ok(ProgramState::ReturnData(d)),

                    ExecuteState::Revert(r) => return Ok(ProgramState::Revert(r)),

                    ExecuteState::Proceed => (),

                    #[cfg(feature = "debug")]
                    ExecuteState::DebugEvent(d) => return Ok(ProgramState::RunProgram(d)),
                }
            }
        }
    }
}

impl<S, Tx> Interpreter<S, Tx>
where
    S: InterpreterStorage,
    Tx: ExecutableTransaction,
    <Tx as IntoChecked>::Metadata: CheckedMetadata,
{
    /// Allocate internally a new instance of [`Interpreter`] with the provided
    /// storage, initialize it with the provided transaction and return the
    /// result of th execution in form of [`StateTransition`]
    pub fn transact_owned(
        storage: S,
        tx: Checked<Tx>,
        params: ConsensusParameters,
        gas_costs: GasCosts,
    ) -> Result<StateTransition<Tx>, InterpreterError> {
        let mut interpreter = Interpreter::with_storage(storage, params, gas_costs);
        interpreter
            .transact(tx)
            .map(ProgramState::from)
            .map(|state| {
                StateTransition::new(state, interpreter.tx, interpreter.receipts.into())
            })
    }

    /// Initialize a pre-allocated instance of [`Interpreter`] with the provided
    /// transaction and execute it. The result will be bound to the lifetime
    /// of the interpreter and will avoid unnecessary copy with the data
    /// that can be referenced from the interpreter instance itself.
    pub fn transact(
        &mut self,
        tx: Checked<Tx>,
    ) -> Result<StateTransitionRef<'_, Tx>, InterpreterError> {
        let state_result = self.init_script(tx).and_then(|_| self.run());

        #[cfg(feature = "profile-any")]
        self.profiler.on_transaction(&state_result);

        let state = state_result?;
        Ok(StateTransitionRef::new(
            state,
            self.transaction(),
            self.receipts(),
        ))
    }
}

impl<S, Tx> Interpreter<S, Tx>
where
    S: InterpreterStorage,
{
    /// Deploys `Create` transaction without initialization VM and without invalidation of
    /// the last state of execution of the `Script` transaction.
    ///
    /// Returns `Create` transaction with all modifications after execution.
    pub fn deploy(&mut self, tx: Checked<Create>) -> Result<Create, InterpreterError> {
        let (mut create, metadata) = tx.into();
        Self::deploy_inner(
            &mut create,
            &mut self.storage,
            metadata.balances(),
            &self.params,
        )?;
        Ok(create)
    }
}