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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
#[cfg(test)]
mod tests;

use alloc::{
    vec,
    vec::Vec,
};

use crate::{
    checked_transaction::{
        Checked,
        IntoChecked,
        ParallelExecutor,
    },
    context::Context,
    error::{
        Bug,
        InterpreterError,
        PredicateVerificationFailed,
    },
    interpreter::{
        CheckedMetadata,
        EcalHandler,
        ExecutableTransaction,
        InitialBalances,
        Interpreter,
        Memory,
        RuntimeBalances,
    },
    pool::VmMemoryPool,
    predicate::RuntimePredicate,
    prelude::{
        BugVariant,
        RuntimeError,
    },
    state::{
        ExecuteState,
        ProgramState,
        StateTransitionRef,
    },
    storage::{
        InterpreterStorage,
        PredicateStorage,
    },
};

use crate::{
    checked_transaction::{
        CheckError,
        CheckPredicateParams,
        Ready,
    },
    interpreter::InterpreterParams,
    prelude::MemoryInstance,
    storage::{
        UploadedBytecode,
        UploadedBytecodes,
    },
};
use fuel_asm::PanicReason;
use fuel_storage::{
    StorageAsMut,
    StorageAsRef,
};
use fuel_tx::{
    field::{
        BytecodeRoot,
        BytecodeWitnessIndex,
        ReceiptsRoot,
        Salt,
        Script as ScriptField,
        ScriptGasLimit,
        StorageSlots,
        SubsectionIndex,
        SubsectionsNumber,
        UpgradePurpose as UpgradePurposeField,
        Witnesses,
    },
    input::{
        coin::CoinPredicate,
        message::{
            MessageCoinPredicate,
            MessageDataPredicate,
        },
    },
    ConsensusParameters,
    Contract,
    Create,
    FeeParameters,
    GasCosts,
    Input,
    Receipt,
    ScriptExecutionResult,
    Upgrade,
    UpgradeMetadata,
    UpgradePurpose,
    Upload,
    ValidityError,
};
use fuel_types::{
    AssetId,
    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<Tx> Interpreter<&mut MemoryInstance, PredicateStorage, Tx>
where
    Tx: ExecutableTransaction,
{
    /// 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(
        checked: &Checked<Tx>,
        params: &CheckPredicateParams,
        mut memory: impl Memory,
    ) -> Result<PredicatesChecked, PredicateVerificationFailed>
    where
        <Tx as IntoChecked>::Metadata: CheckedMetadata,
    {
        let tx = checked.transaction();
        Self::run_predicate(PredicateRunKind::Verifying(tx), params, memory.as_mut())
    }

    /// 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<E>(
        checked: &Checked<Tx>,
        params: &CheckPredicateParams,
        pool: &impl VmMemoryPool,
    ) -> Result<PredicatesChecked, PredicateVerificationFailed>
    where
        Tx: Send + 'static,
        <Tx as IntoChecked>::Metadata: CheckedMetadata,
        E: ParallelExecutor,
    {
        let tx = checked.transaction();

        let predicates_checked =
            Self::run_predicate_async::<E>(PredicateRunKind::Verifying(tx), params, pool)
                .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(
        transaction: &mut Tx,
        params: &CheckPredicateParams,
        mut memory: impl Memory,
    ) -> Result<PredicatesChecked, PredicateVerificationFailed> {
        let predicates_checked = Self::run_predicate(
            PredicateRunKind::Estimating(transaction),
            params,
            memory.as_mut(),
        )?;
        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 in parallel.
    ///
    /// The storage provider is not used since contract opcodes are not allowed for
    /// predicates.
    pub async fn estimate_predicates_async<E>(
        transaction: &mut Tx,
        params: &CheckPredicateParams,
        pool: &impl VmMemoryPool,
    ) -> Result<PredicatesChecked, PredicateVerificationFailed>
    where
        Tx: Send + 'static,
        E: ParallelExecutor,
    {
        let predicates_checked = Self::run_predicate_async::<E>(
            PredicateRunKind::Estimating(transaction),
            params,
            pool,
        )
        .await?;

        Ok(predicates_checked)
    }

    async fn run_predicate_async<E>(
        kind: PredicateRunKind<'_, Tx>,
        params: &CheckPredicateParams,
        pool: &impl VmMemoryPool,
    ) -> Result<PredicatesChecked, PredicateVerificationFailed>
    where
        Tx: Send + 'static,
        E: ParallelExecutor,
    {
        let mut checks = vec![];
        let predicate_action = PredicateAction::from(&kind);
        let tx_offset = params.tx_offset;

        for index in 0..kind.tx().inputs().len() {
            if let Some(predicate) =
                RuntimePredicate::from_tx(kind.tx(), tx_offset, index)
            {
                let tx = kind.tx().clone();
                let my_params = params.clone();
                let mut memory = pool.get_new().await;

                let verify_task = E::create_task(move || {
                    Interpreter::check_predicate(
                        tx,
                        index,
                        predicate_action,
                        predicate,
                        my_params,
                        memory.as_mut(),
                    )
                });

                checks.push(verify_task);
            }
        }

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

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

    fn run_predicate(
        kind: PredicateRunKind<'_, Tx>,
        params: &CheckPredicateParams,
        mut memory: impl Memory,
    ) -> Result<PredicatesChecked, PredicateVerificationFailed> {
        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(&tx, params.tx_offset, index)
            {
                checks.push(Interpreter::check_predicate(
                    tx,
                    index,
                    predicate_action,
                    predicate,
                    params.clone(),
                    memory.as_mut(),
                ));
            }
        }

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

    fn check_predicate(
        tx: Tx,
        index: usize,
        predicate_action: PredicateAction,
        predicate: RuntimePredicate,
        params: CheckPredicateParams,
        memory: &mut MemoryInstance,
    ) -> Result<(Word, usize), PredicateVerificationFailed> {
        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) {
                    return Err(PredicateVerificationFailed::InvalidOwner);
                }
            }
            _ => {}
        }

        let max_gas_per_tx = params.max_gas_per_tx;
        let max_gas_per_predicate = params.max_gas_per_predicate;
        let zero_gas_price = 0;
        let interpreter_params = InterpreterParams::new(zero_gas_price, params);

        let mut vm = Interpreter::<_, _, _>::with_storage(
            memory,
            PredicateStorage {},
            interpreter_params,
        );

        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, available_gas)?;
                available_gas
            }
            PredicateAction::Estimating => {
                let context = Context::PredicateEstimation { program: predicate };
                let available_gas = core::cmp::min(max_gas_per_predicate, max_gas_per_tx);

                vm.init_predicate(context, tx, 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(BugVariant::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(
        mut kind: PredicateRunKind<Tx>,
        checks: Vec<Result<(Word, usize), PredicateVerificationFailed>>,
        params: &CheckPredicateParams,
    ) -> Result<PredicatesChecked, PredicateVerificationFailed> {
        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 max_gas = kind.tx().max_gas(&params.gas_costs, &params.fee_params);
        if max_gas > params.max_gas_per_tx {
            return Err(
                PredicateVerificationFailed::TransactionExceedsTotalGasAllowance(max_gas),
            );
        }

        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)
        })?;

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

impl<M, S, Tx, Ecal> Interpreter<M, S, Tx, Ecal>
where
    S: InterpreterStorage,
{
    fn deploy_inner(
        create: &mut Create,
        storage: &mut S,
        initial_balances: InitialBalances,
        gas_costs: &GasCosts,
        fee_params: &FeeParameters,
        base_asset_id: &AssetId,
        gas_price: Word,
    ) -> Result<(), InterpreterError<S::DataError>> {
        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.body.contract_root
        } else {
            contract.root()
        };

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

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

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

        storage
            .deploy_contract_with_id(storage_slots, &contract, &id)
            .map_err(RuntimeError::Storage)?;
        Self::finalize_outputs(
            create,
            gas_costs,
            fee_params,
            base_asset_id,
            false,
            0,
            &initial_balances,
            &RuntimeBalances::try_from(initial_balances.clone())?,
            gas_price,
        )?;
        Ok(())
    }
}

impl<M, S, Tx, Ecal> Interpreter<M, S, Tx, Ecal>
where
    S: InterpreterStorage,
{
    fn upgrade_inner(
        upgrade: &mut Upgrade,
        storage: &mut S,
        initial_balances: InitialBalances,
        gas_costs: &GasCosts,
        fee_params: &FeeParameters,
        base_asset_id: &AssetId,
        gas_price: Word,
    ) -> Result<(), InterpreterError<S::DataError>> {
        let metadata = upgrade.metadata().as_ref();
        debug_assert!(
            metadata.is_some(),
            "`upgrade_inner` is called without cached metadata"
        );

        match upgrade.upgrade_purpose() {
            UpgradePurpose::ConsensusParameters { .. } => {
                let consensus_parameters = if let Some(metadata) = metadata {
                    Self::get_consensus_parameters(&metadata.body)?
                } else {
                    let metadata = UpgradeMetadata::compute(upgrade)?;
                    Self::get_consensus_parameters(&metadata)?
                };

                let current_version = storage
                    .consensus_parameters_version()
                    .map_err(RuntimeError::Storage)?;
                let next_version = current_version.saturating_add(1);

                let prev = storage
                    .set_consensus_parameters(next_version, &consensus_parameters)
                    .map_err(RuntimeError::Storage)?;

                if prev.is_some() {
                    return Err(InterpreterError::Panic(
                        PanicReason::OverridingConsensusParameters,
                    ));
                }
            }
            UpgradePurpose::StateTransition { root } => {
                let exists = storage
                    .contains_state_transition_bytecode_root(root)
                    .map_err(RuntimeError::Storage)?;

                if !exists {
                    return Err(InterpreterError::Panic(
                        PanicReason::UnknownStateTransactionBytecodeRoot,
                    ))
                }

                let current_version = storage
                    .state_transition_version()
                    .map_err(RuntimeError::Storage)?;
                let next_version = current_version.saturating_add(1);

                let prev = storage
                    .set_state_transition_bytecode(next_version, root)
                    .map_err(RuntimeError::Storage)?;

                if prev.is_some() {
                    return Err(InterpreterError::Panic(
                        PanicReason::OverridingStateTransactionBytecode,
                    ));
                }
            }
        }

        Self::finalize_outputs(
            upgrade,
            gas_costs,
            fee_params,
            base_asset_id,
            false,
            0,
            &initial_balances,
            &RuntimeBalances::try_from(initial_balances.clone())?,
            gas_price,
        )?;
        Ok(())
    }

    fn get_consensus_parameters(
        metadata: &UpgradeMetadata,
    ) -> Result<ConsensusParameters, InterpreterError<S::DataError>> {
        match &metadata {
            UpgradeMetadata::ConsensusParameters {
                consensus_parameters,
                ..
            } => Ok(consensus_parameters.as_ref().clone()),
            UpgradeMetadata::StateTransition => {
                // It shouldn't be possible since `Check<Upgrade>` guarantees that.
                Err(InterpreterError::CheckError(CheckError::Validity(
                    ValidityError::TransactionMetadataMismatch,
                )))
            }
        }
    }
}

impl<M, S, Tx, Ecal> Interpreter<M, S, Tx, Ecal>
where
    S: InterpreterStorage,
{
    fn upload_inner(
        upload: &mut Upload,
        storage: &mut S,
        initial_balances: InitialBalances,
        gas_costs: &GasCosts,
        fee_params: &FeeParameters,
        base_asset_id: &AssetId,
        gas_price: Word,
    ) -> Result<(), InterpreterError<S::DataError>> {
        let root = *upload.bytecode_root();
        let uploaded_bytecode = storage
            .storage_as_ref::<UploadedBytecodes>()
            .get(&root)
            .map_err(RuntimeError::Storage)?
            .map(|x| x.into_owned())
            .unwrap_or_else(|| UploadedBytecode::Uncompleted {
                bytecode: vec![],
                uploaded_subsections_number: 0,
            });

        let new_bytecode = match uploaded_bytecode {
            UploadedBytecode::Uncompleted {
                bytecode,
                uploaded_subsections_number,
            } => Self::upload_bytecode_subsection(
                upload,
                bytecode,
                uploaded_subsections_number,
            )?,
            UploadedBytecode::Completed(_) => {
                return Err(InterpreterError::Panic(
                    PanicReason::BytecodeAlreadyUploaded,
                ));
            }
        };

        storage
            .storage_as_mut::<UploadedBytecodes>()
            .insert(&root, &new_bytecode)
            .map_err(RuntimeError::Storage)?;

        Self::finalize_outputs(
            upload,
            gas_costs,
            fee_params,
            base_asset_id,
            false,
            0,
            &initial_balances,
            &RuntimeBalances::try_from(initial_balances.clone())?,
            gas_price,
        )?;
        Ok(())
    }

    fn upload_bytecode_subsection(
        upload: &Upload,
        mut uploaded_bytecode: Vec<u8>,
        uploaded_subsections_number: u16,
    ) -> Result<UploadedBytecode, InterpreterError<S::DataError>> {
        let index_of_next_subsection = uploaded_subsections_number;

        if *upload.subsection_index() != index_of_next_subsection {
            return Err(InterpreterError::Panic(
                PanicReason::ThePartIsNotSequentiallyConnected,
            ));
        }

        let bytecode_subsection = upload
            .witnesses()
            .get(*upload.bytecode_witness_index() as usize)
            .ok_or(InterpreterError::Bug(Bug::new(
                // It shouldn't be possible since `Checked<Upload>` guarantees
                // the existence of the witness.
                BugVariant::WitnessIndexOutOfBounds,
            )))?;

        uploaded_bytecode.extend(bytecode_subsection.as_ref());

        let new_uploaded_subsections_number = uploaded_subsections_number
            .checked_add(1)
            .ok_or(InterpreterError::Panic(PanicReason::ArithmeticOverflow))?;

        // It shouldn't be possible since `Checked<Upload>` guarantees
        // the validity of the Merkle proof.
        if new_uploaded_subsections_number > *upload.subsections_number() {
            return Err(InterpreterError::Bug(Bug::new(
                BugVariant::NextSubsectionIndexIsHigherThanTotalNumberOfParts,
            )))
        }

        let updated_uploaded_bytecode =
            if *upload.subsections_number() == new_uploaded_subsections_number {
                UploadedBytecode::Completed(uploaded_bytecode)
            } else {
                UploadedBytecode::Uncompleted {
                    bytecode: uploaded_bytecode,
                    uploaded_subsections_number: new_uploaded_subsections_number,
                }
            };

        Ok(updated_uploaded_bytecode)
    }
}

impl<M, S, Tx, Ecal> Interpreter<M, S, Tx, Ecal>
where
    M: Memory,

    S: InterpreterStorage,
    Tx: ExecutableTransaction,
    Ecal: EcalHandler,
{
    fn update_transaction_outputs(
        &mut self,
    ) -> Result<(), InterpreterError<S::DataError>> {
        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<S::DataError>> {
        // TODO: Remove `Create`, `Upgrade`, and `Upload` from here
        //  https://github.com/FuelLabs/fuel-vm/issues/251
        let gas_costs = self.gas_costs().clone();
        let fee_params = *self.fee_params();
        let base_asset_id = *self.base_asset_id();
        let gas_price = self.gas_price();
        let state = if let Some(create) = self.tx.as_create_mut() {
            Self::deploy_inner(
                create,
                &mut self.storage,
                self.initial_balances.clone(),
                &gas_costs,
                &fee_params,
                &base_asset_id,
                gas_price,
            )?;
            ProgramState::Return(1)
        } else if let Some(upgrade) = self.tx.as_upgrade_mut() {
            Self::upgrade_inner(
                upgrade,
                &mut self.storage,
                self.initial_balances.clone(),
                &gas_costs,
                &fee_params,
                &base_asset_id,
                gas_price,
            )?;
            ProgramState::Return(1)
        } else if let Some(upload) = self.tx.as_upload_mut() {
            Self::upload_inner(
                upload,
                &mut self.storage,
                self.initial_balances.clone(),
                &gas_costs,
                &fee_params,
                &base_asset_id,
                gas_price,
            )?;
            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::ContractNotInInputs));
            }

            let gas_limit;
            let is_empty_script;
            if let Some(script) = self.transaction().as_script() {
                gas_limit = *script.script_gas_limit();
                is_empty_script = script.script().is_empty();
            } else {
                unreachable!("Only `Create` and `Script` transactions can be executed inside of the VM")
            }

            // TODO set tree balance

            // `Interpreter` supports only `Create` and `Script` transactions. It is not
            // `Create` -> it is `Script`.
            let program = if !is_empty_script {
                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 = gas_limit
                .checked_sub(self.remaining_gas())
                .ok_or_else(|| Bug::new(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.receipts.push(receipt)?;

            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 gas_price = self.gas_price();
            Self::finalize_outputs(
                &mut self.tx,
                &gas_costs,
                &fee_params,
                &base_asset_id,
                revert,
                gas_used,
                &self.initial_balances,
                &self.balances,
                gas_price,
            )?;

            program
        };
        self.update_transaction_outputs()?;

        Ok(state)
    }

    pub(crate) fn run_program(
        &mut self,
    ) -> Result<ProgramState, InterpreterError<S::DataError>> {
        loop {
            // 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 => (),

                    ExecuteState::DebugEvent(d) => return Ok(ProgramState::RunProgram(d)),
                }
            }
        }
    }

    /// Update tx fields after execution
    pub(crate) fn post_execute(&mut self) {
        if let Some(script) = self.tx.as_script_mut() {
            *script.receipts_root_mut() = self.receipts.root();
        }
    }
}

impl<M, S, Tx, Ecal> Interpreter<M, S, Tx, Ecal>
where
    M: Memory,
    S: InterpreterStorage,
    Tx: ExecutableTransaction,
    <Tx as IntoChecked>::Metadata: CheckedMetadata,
    Ecal: EcalHandler,
{
    /// 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: Ready<Tx>,
    ) -> Result<StateTransitionRef<'_, Tx>, InterpreterError<S::DataError>> {
        self.verify_ready_tx(&tx)?;

        let state_result = self.init_script(tx).and_then(|_| self.run());
        self.post_execute();

        #[cfg(feature = "profile-any")]
        {
            let r = match &state_result {
                Ok(state) => Ok(state),
                Err(err) => Err(err.erase_generics()),
            };
            self.profiler.on_transaction(r);
        }

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

impl<M, S, Tx, Ecal> Interpreter<M, S, Tx, Ecal>
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: Ready<Create>,
    ) -> Result<Create, InterpreterError<S::DataError>> {
        self.verify_ready_tx(&tx)?;

        let (_, checked) = tx.decompose();
        let (mut create, metadata): (Create, <Create as IntoChecked>::Metadata) =
            checked.into();
        let base_asset_id = *self.base_asset_id();
        let gas_price = self.gas_price();
        Self::deploy_inner(
            &mut create,
            &mut self.storage,
            metadata.balances(),
            &self.interpreter_params.gas_costs,
            &self.interpreter_params.fee_params,
            &base_asset_id,
            gas_price,
        )?;
        Ok(create)
    }
}

impl<M, S, Tx, Ecal> Interpreter<M, S, Tx, Ecal>
where
    S: InterpreterStorage,
{
    /// Executes `Upgrade` transaction without initialization VM and without invalidation
    /// of the last state of execution of the `Script` transaction.
    ///
    /// Returns `Upgrade` transaction with all modifications after execution.
    pub fn upgrade(
        &mut self,
        tx: Ready<Upgrade>,
    ) -> Result<Upgrade, InterpreterError<S::DataError>> {
        self.verify_ready_tx(&tx)?;

        let (_, checked) = tx.decompose();
        let (mut upgrade, metadata): (Upgrade, <Upgrade as IntoChecked>::Metadata) =
            checked.into();
        let base_asset_id = *self.base_asset_id();
        let gas_price = self.gas_price();
        Self::upgrade_inner(
            &mut upgrade,
            &mut self.storage,
            metadata.balances(),
            &self.interpreter_params.gas_costs,
            &self.interpreter_params.fee_params,
            &base_asset_id,
            gas_price,
        )?;
        Ok(upgrade)
    }
}

impl<M, S, Tx, Ecal> Interpreter<M, S, Tx, Ecal>
where
    S: InterpreterStorage,
{
    /// Executes `Upload` transaction without initialization VM and without invalidation
    /// of the last state of execution of the `Script` transaction.
    ///
    /// Returns `Upload` transaction with all modifications after execution.
    pub fn upload(
        &mut self,
        tx: Ready<Upload>,
    ) -> Result<Upload, InterpreterError<S::DataError>> {
        self.verify_ready_tx(&tx)?;

        let (_, checked) = tx.decompose();
        let (mut upload, metadata): (Upload, <Upload as IntoChecked>::Metadata) =
            checked.into();
        let base_asset_id = *self.base_asset_id();
        let gas_price = self.gas_price();
        Self::upload_inner(
            &mut upload,
            &mut self.storage,
            metadata.balances(),
            &self.interpreter_params.gas_costs,
            &self.interpreter_params.fee_params,
            &base_asset_id,
            gas_price,
        )?;
        Ok(upload)
    }
}

impl<M, S: InterpreterStorage, Tx, Ecal> Interpreter<M, S, Tx, Ecal> {
    fn verify_ready_tx<Tx2: IntoChecked>(
        &self,
        tx: &Ready<Tx2>,
    ) -> Result<(), InterpreterError<S::DataError>> {
        self.gas_price_matches(tx)?;
        Ok(())
    }

    fn gas_price_matches<Tx2: IntoChecked>(
        &self,
        tx: &Ready<Tx2>,
    ) -> Result<(), InterpreterError<S::DataError>> {
        if tx.gas_price() != self.gas_price() {
            Err(InterpreterError::ReadyTransactionWrongGasPrice {
                expected: self.gas_price(),
                actual: tx.gas_price(),
            })
        } else {
            Ok(())
        }
    }
}