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
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
//! A checked transaction is type-wrapper for transactions which have been checked.
//! It is impossible to construct a checked transaction without performing necessary
//! checks.
//!
//! This allows the VM to accept transactions with metadata that have been already
//! verified upstream.

#![allow(non_upper_case_globals)]

use fuel_tx::{
    CheckError,
    ConsensusParameters,
    Create,
    Mint,
    Script,
    Transaction,
};
use fuel_types::{
    BlockHeight,
    ChainId,
};

use core::borrow::Borrow;
use std::future::Future;

mod balances;
pub mod builder;
pub mod types;

pub use types::*;

use crate::{
    checked_transaction::balances::{
        initial_free_balances,
        AvailableBalances,
    },
    error::PredicateVerificationFailed,
    gas::GasCosts,
    interpreter::{
        CheckedMetadata as CheckedMetadataAccessTrait,
        InitialBalances,
    },
    prelude::*,
};

bitflags::bitflags! {
    /// Possible types of transaction checks.
    pub struct Checks: u32 {
        /// Basic checks defined in the specification for each transaction:
        /// https://github.com/FuelLabs/fuel-specs/blob/master/src/protocol/tx_format/transaction.md#transaction
        const Basic         = 0b00000001;
        /// Check that signature in the transactions are valid.
        const Signatures    = 0b00000010;
        /// Check that predicate in the transactions are valid.
        const Predicates    = 0b00000100;
        /// All possible checks.
        const All           = Self::Basic.bits
                            | Self::Signatures.bits
                            | Self::Predicates.bits;
    }
}

impl core::fmt::Display for Checks {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        write!(f, "{:032b}", self.bits)
    }
}

/// The type describes that the inner transaction was already checked.
///
/// All fields are private, and there is no constructor, so it is impossible to create the
/// instance of `Checked` outside the `fuel-tx` crate.
///
/// The inner data is immutable to prevent modification to invalidate the checking.
///
/// If you need to modify an inner state, you need to get inner values
/// (via the `Into<(Tx, Tx ::Metadata)>` trait), modify them and check again.
///
/// # Dev note: Avoid serde serialization of this type.
///
/// Since checked tx would need to be re-validated on deserialization anyways,
/// it's cleaner to redo the tx check.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Checked<Tx: IntoChecked> {
    transaction: Tx,
    metadata: Tx::Metadata,
    checks_bitmask: Checks,
}

impl<Tx: IntoChecked> Checked<Tx> {
    fn new(transaction: Tx, metadata: Tx::Metadata, checks_bitmask: Checks) -> Self {
        Checked {
            transaction,
            metadata,
            checks_bitmask,
        }
    }

    pub(crate) fn basic(transaction: Tx, metadata: Tx::Metadata) -> Self {
        Checked::new(transaction, metadata, Checks::Basic)
    }

    /// Returns reference on inner transaction.
    pub fn transaction(&self) -> &Tx {
        &self.transaction
    }

    /// Returns the metadata generated during the check for transaction.
    pub fn metadata(&self) -> &Tx::Metadata {
        &self.metadata
    }

    /// Returns the bitmask of all passed checks.
    pub fn checks(&self) -> &Checks {
        &self.checks_bitmask
    }

    /// Performs check of signatures, if not yet done.
    pub fn check_signatures(mut self, chain_id: &ChainId) -> Result<Self, CheckError> {
        if !self.checks_bitmask.contains(Checks::Signatures) {
            self.transaction.check_signatures(chain_id)?;
            self.checks_bitmask.insert(Checks::Signatures);
        }
        Ok(self)
    }
}

impl<Tx: IntoChecked + UniqueIdentifier> Checked<Tx> {
    /// Returns the transaction ID from the computed metadata
    pub fn id(&self) -> TxId {
        self.transaction
            .cached_id()
            .expect("Transaction metadata should be computed for checked transactions")
    }
}

#[cfg(feature = "test-helpers")]
impl<Tx: IntoChecked + Default> Default for Checked<Tx>
where
    Checked<Tx>: CheckPredicates,
{
    fn default() -> Self {
        Tx::default()
            .into_checked(Default::default(), &Default::default(), &Default::default())
            .expect("default tx should produce a valid fully checked transaction")
    }
}

impl<Tx: IntoChecked> From<Checked<Tx>> for (Tx, Tx::Metadata) {
    fn from(checked: Checked<Tx>) -> Self {
        let Checked {
            transaction,
            metadata,
            ..
        } = checked;

        (transaction, metadata)
    }
}

impl<Tx: IntoChecked> AsRef<Tx> for Checked<Tx> {
    fn as_ref(&self) -> &Tx {
        &self.transaction
    }
}

#[cfg(feature = "test-helpers")]
impl<Tx: IntoChecked> AsMut<Tx> for Checked<Tx> {
    fn as_mut(&mut self) -> &mut Tx {
        &mut self.transaction
    }
}

impl<Tx: IntoChecked> Borrow<Tx> for Checked<Tx> {
    fn borrow(&self) -> &Tx {
        self.transaction()
    }
}

/// Performs checks for a transaction
pub trait IntoChecked: FormatValidityChecks + Sized {
    /// Metadata produced during the check.
    type Metadata: Sized;

    /// Returns transaction that passed all `Checks`.
    fn into_checked(
        self,
        block_height: BlockHeight,
        params: &ConsensusParameters,
        gas_costs: &GasCosts,
    ) -> Result<Checked<Self>, CheckError>
    where
        Checked<Self>: CheckPredicates,
    {
        self.into_checked_basic(block_height, params)?
            .check_signatures(&params.chain_id)?
            .check_predicates(params, gas_costs)
    }

    /// Returns transaction that passed only `Checks::Basic`.
    fn into_checked_basic(
        self,
        block_height: BlockHeight,
        params: &ConsensusParameters,
    ) -> Result<Checked<Self>, CheckError>;
}

/// Provides predicate verification functionality for the transaction.
#[async_trait::async_trait]
pub trait CheckPredicates: Sized {
    /// Performs predicates verification of the transaction.
    fn check_predicates(
        self,
        params: &ConsensusParameters,
        gas_costs: &GasCosts,
    ) -> Result<Self, CheckError>;

    /// Performs predicates verification of the transaction in parallel.
    async fn check_predicates_async<E: ParallelExecutor>(
        self,
        params: &ConsensusParameters,
        gas_costs: &GasCosts,
    ) -> Result<Self, CheckError>;
}

/// Provides predicate estimation functionality for the transaction.
#[async_trait::async_trait]
pub trait EstimatePredicates: Sized {
    /// Estimates predicates of the transaction.
    fn estimate_predicates(
        &mut self,
        params: &ConsensusParameters,
        gas_costs: &GasCosts,
    ) -> Result<(), CheckError>;

    /// Estimates predicates of the transaction in parallel.
    async fn estimate_predicates_async<E: ParallelExecutor>(
        &mut self,
        params: &ConsensusParameters,
        gas_costs: &GasCosts,
    ) -> Result<(), CheckError>;
}

/// Executes CPU-heavy tasks in parallel.
#[async_trait::async_trait]
pub trait ParallelExecutor {
    /// Future created from a CPU-heavy task.
    type Task: Future + Send + 'static;

    /// Creates a Future from a CPU-heavy task.
    fn create_task<F>(func: F) -> Self::Task
    where
        F: FnOnce() -> Result<(Word, usize), PredicateVerificationFailed>
            + Send
            + 'static;

    /// Executes tasks created by `create_task` in parallel.
    async fn execute_tasks(
        futures: Vec<Self::Task>,
    ) -> Vec<Result<(Word, usize), PredicateVerificationFailed>>;
}

#[async_trait::async_trait]
impl<Tx> CheckPredicates for Checked<Tx>
where
    Tx: ExecutableTransaction + Send + Sync + 'static,
    <Tx as IntoChecked>::Metadata: crate::interpreter::CheckedMetadata + Send + Sync,
{
    fn check_predicates(
        mut self,
        params: &ConsensusParameters,
        gas_costs: &GasCosts,
    ) -> Result<Self, CheckError> {
        if !self.checks_bitmask.contains(Checks::Predicates) {
            let checked = Interpreter::<PredicateStorage>::check_predicates(
                &self,
                *params,
                gas_costs.clone(),
            )?;
            self.checks_bitmask.insert(Checks::Predicates);
            self.metadata.set_gas_used_by_predicates(checked.gas_used());
        }
        Ok(self)
    }

    async fn check_predicates_async<E>(
        mut self,
        params: &ConsensusParameters,
        gas_costs: &GasCosts,
    ) -> Result<Self, CheckError>
    where
        E: ParallelExecutor,
    {
        if !self.checks_bitmask.contains(Checks::Predicates) {
            let predicates_checked =
                Interpreter::<PredicateStorage>::check_predicates_async::<_, E>(
                    &self,
                    *params,
                    gas_costs.clone(),
                )
                .await?;

            self.checks_bitmask.insert(Checks::Predicates);
            self.metadata
                .set_gas_used_by_predicates(predicates_checked.gas_used());

            Ok(self)
        } else {
            Ok(self)
        }
    }
}

#[async_trait::async_trait]
impl<Tx: ExecutableTransaction + Send + Sync + 'static> EstimatePredicates for Tx {
    fn estimate_predicates(
        &mut self,
        params: &ConsensusParameters,
        gas_costs: &GasCosts,
    ) -> Result<(), CheckError> {
        // validate fees and compute free balances
        let AvailableBalances {
            non_retryable_balances,
            retryable_balance,
            ..
        } = initial_free_balances(self, params)?;

        let balances: InitialBalances = InitialBalances {
            non_retryable: NonRetryableFreeBalances(non_retryable_balances),
            retryable: Some(RetryableAmount(retryable_balance)),
        };

        Interpreter::<PredicateStorage>::estimate_predicates(
            self,
            balances,
            *params,
            gas_costs.clone(),
        )?;
        Ok(())
    }

    async fn estimate_predicates_async<E>(
        &mut self,
        params: &ConsensusParameters,
        gas_costs: &GasCosts,
    ) -> Result<(), CheckError>
    where
        E: ParallelExecutor,
    {
        // validate fees and compute free balances
        let AvailableBalances {
            non_retryable_balances,
            retryable_balance,
            ..
        } = initial_free_balances(self, params)?;

        let balances: InitialBalances = InitialBalances {
            non_retryable: NonRetryableFreeBalances(non_retryable_balances),
            retryable: Some(RetryableAmount(retryable_balance)),
        };

        Interpreter::<PredicateStorage>::estimate_predicates_async::<_, E>(
            self,
            balances,
            *params,
            gas_costs.clone(),
        )
        .await?;

        Ok(())
    }
}

#[async_trait::async_trait]
impl EstimatePredicates for Transaction {
    fn estimate_predicates(
        &mut self,
        params: &ConsensusParameters,
        gas_costs: &GasCosts,
    ) -> Result<(), CheckError> {
        match self {
            Transaction::Script(script) => script.estimate_predicates(params, gas_costs),
            Transaction::Create(create) => create.estimate_predicates(params, gas_costs),
            Transaction::Mint(_) => Ok(()),
        }
    }

    async fn estimate_predicates_async<E: ParallelExecutor>(
        &mut self,
        params: &ConsensusParameters,
        gas_costs: &GasCosts,
    ) -> Result<(), CheckError> {
        match self {
            Transaction::Script(script) => {
                script
                    .estimate_predicates_async::<E>(params, gas_costs)
                    .await
            }
            Transaction::Create(create) => {
                create
                    .estimate_predicates_async::<E>(params, gas_costs)
                    .await
            }
            Transaction::Mint(_) => Ok(()),
        }
    }
}

#[async_trait::async_trait]
impl CheckPredicates for Checked<Mint> {
    fn check_predicates(
        mut self,
        _params: &ConsensusParameters,
        _gas_costs: &GasCosts,
    ) -> Result<Self, CheckError> {
        self.checks_bitmask.insert(Checks::Predicates);
        Ok(self)
    }

    async fn check_predicates_async<E: ParallelExecutor>(
        mut self,
        _params: &ConsensusParameters,
        _gas_costs: &GasCosts,
    ) -> Result<Self, CheckError> {
        self.checks_bitmask.insert(Checks::Predicates);
        Ok(self)
    }
}

#[async_trait::async_trait]
impl CheckPredicates for Checked<Transaction> {
    fn check_predicates(
        self,
        params: &ConsensusParameters,
        gas_costs: &GasCosts,
    ) -> Result<Self, CheckError> {
        let checked_transaction: CheckedTransaction = self.into();
        let checked_transaction: CheckedTransaction = match checked_transaction {
            CheckedTransaction::Script(tx) => {
                CheckPredicates::check_predicates(tx, params, gas_costs)?.into()
            }
            CheckedTransaction::Create(tx) => {
                CheckPredicates::check_predicates(tx, params, gas_costs)?.into()
            }
            CheckedTransaction::Mint(tx) => {
                CheckPredicates::check_predicates(tx, params, gas_costs)?.into()
            }
        };
        Ok(checked_transaction.into())
    }

    async fn check_predicates_async<E>(
        self,
        params: &ConsensusParameters,
        gas_costs: &GasCosts,
    ) -> Result<Self, CheckError>
    where
        E: ParallelExecutor,
    {
        let checked_transaction: CheckedTransaction = self.into();

        let checked_transaction: CheckedTransaction = match checked_transaction {
            CheckedTransaction::Script(tx) => {
                CheckPredicates::check_predicates_async::<E>(tx, params, gas_costs)
                    .await?
                    .into()
            }
            CheckedTransaction::Create(tx) => {
                CheckPredicates::check_predicates_async::<E>(tx, params, gas_costs)
                    .await?
                    .into()
            }
            CheckedTransaction::Mint(tx) => {
                CheckPredicates::check_predicates_async::<E>(tx, params, gas_costs)
                    .await?
                    .into()
            }
        };

        Ok(checked_transaction.into())
    }
}

/// The Enum version of `Checked<Transaction>` allows getting the inner variant without
/// losing "checked" status.
///
/// It is possible to freely convert `Checked<Transaction>` into `CheckedTransaction` and
/// vice verse without the overhead.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
#[allow(missing_docs)]
pub enum CheckedTransaction {
    Script(Checked<Script>),
    Create(Checked<Create>),
    Mint(Checked<Mint>),
}

impl From<Checked<Transaction>> for CheckedTransaction {
    fn from(checked: Checked<Transaction>) -> Self {
        let Checked {
            transaction,
            metadata,
            checks_bitmask,
        } = checked;

        // # Dev note: Avoid wildcard pattern to be sure that all variants are covered.
        match (transaction, metadata) {
            (Transaction::Script(transaction), CheckedMetadata::Script(metadata)) => {
                Self::Script(Checked::new(transaction, metadata, checks_bitmask))
            }
            (Transaction::Create(transaction), CheckedMetadata::Create(metadata)) => {
                Self::Create(Checked::new(transaction, metadata, checks_bitmask))
            }
            (Transaction::Mint(transaction), CheckedMetadata::Mint(metadata)) => {
                Self::Mint(Checked::new(transaction, metadata, checks_bitmask))
            }
            // The code should produce the `CheckedMetadata` for the corresponding
            // transaction variant. It is done in the implementation of the
            // `IntoChecked` trait for `Transaction`. With the current
            // implementation, the patterns below are unreachable.
            (Transaction::Script(_), _) => unreachable!(),
            (Transaction::Create(_), _) => unreachable!(),
            (Transaction::Mint(_), _) => unreachable!(),
        }
    }
}

impl From<Checked<Script>> for CheckedTransaction {
    fn from(checked: Checked<Script>) -> Self {
        Self::Script(checked)
    }
}

impl From<Checked<Create>> for CheckedTransaction {
    fn from(checked: Checked<Create>) -> Self {
        Self::Create(checked)
    }
}

impl From<Checked<Mint>> for CheckedTransaction {
    fn from(checked: Checked<Mint>) -> Self {
        Self::Mint(checked)
    }
}

impl From<CheckedTransaction> for Checked<Transaction> {
    fn from(checked: CheckedTransaction) -> Self {
        match checked {
            CheckedTransaction::Script(Checked {
                transaction,
                metadata,
                checks_bitmask,
            }) => Checked::new(transaction.into(), metadata.into(), checks_bitmask),
            CheckedTransaction::Create(Checked {
                transaction,
                metadata,
                checks_bitmask,
            }) => Checked::new(transaction.into(), metadata.into(), checks_bitmask),
            CheckedTransaction::Mint(Checked {
                transaction,
                metadata,
                checks_bitmask,
            }) => Checked::new(transaction.into(), metadata.into(), checks_bitmask),
        }
    }
}

/// The `IntoChecked` metadata for `CheckedTransaction`.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
#[allow(missing_docs)]
pub enum CheckedMetadata {
    Script(<Script as IntoChecked>::Metadata),
    Create(<Create as IntoChecked>::Metadata),
    Mint(<Mint as IntoChecked>::Metadata),
}

impl From<<Script as IntoChecked>::Metadata> for CheckedMetadata {
    fn from(metadata: <Script as IntoChecked>::Metadata) -> Self {
        Self::Script(metadata)
    }
}

impl From<<Create as IntoChecked>::Metadata> for CheckedMetadata {
    fn from(metadata: <Create as IntoChecked>::Metadata) -> Self {
        Self::Create(metadata)
    }
}

impl From<<Mint as IntoChecked>::Metadata> for CheckedMetadata {
    fn from(metadata: <Mint as IntoChecked>::Metadata) -> Self {
        Self::Mint(metadata)
    }
}

impl IntoChecked for Transaction {
    type Metadata = CheckedMetadata;

    fn into_checked_basic(
        self,
        block_height: BlockHeight,
        params: &ConsensusParameters,
    ) -> Result<Checked<Self>, CheckError> {
        let (transaction, metadata) = match self {
            Transaction::Script(script) => {
                let (transaction, metadata) =
                    script.into_checked_basic(block_height, params)?.into();
                (transaction.into(), metadata.into())
            }
            Transaction::Create(create) => {
                let (transaction, metadata) =
                    create.into_checked_basic(block_height, params)?.into();
                (transaction.into(), metadata.into())
            }
            Transaction::Mint(mint) => {
                let (transaction, metadata) =
                    mint.into_checked_basic(block_height, params)?.into();
                (transaction.into(), metadata.into())
            }
        };

        Ok(Checked::basic(transaction, metadata))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use fuel_asm::op;
    use fuel_crypto::SecretKey;
    use fuel_tx::{
        CheckError,
        Script,
        TransactionBuilder,
    };
    use quickcheck::TestResult;
    use quickcheck_macros::quickcheck;
    use rand::{
        rngs::StdRng,
        Rng,
        SeedableRng,
    };

    #[test]
    fn checked_tx_accepts_valid_tx() {
        // simple smoke test that valid txs can be checked
        let rng = &mut StdRng::seed_from_u64(2322u64);
        let gas_price = 10;
        let gas_limit = 1000;
        let input_amount = 1000;
        let output_amount = 10;
        let tx = valid_coin_tx(rng, gas_price, gas_limit, input_amount, output_amount);

        let checked = tx
            .clone()
            .into_checked(
                Default::default(),
                &ConsensusParameters::DEFAULT,
                &Default::default(),
            )
            .expect("Expected valid transaction");

        // verify transaction getter works
        assert_eq!(checked.transaction(), &tx);
        // verify available balance was decreased by max fee
        assert_eq!(
            checked.metadata().non_retryable_balances[&AssetId::default()],
            input_amount - checked.metadata().fee.max_fee() - output_amount
        );
    }

    #[test]
    fn checked_tx_accepts_valid_signed_message_input_fees() {
        // simple test to ensure a tx that only has a message input can cover fees
        let rng = &mut StdRng::seed_from_u64(2322u64);
        let input_amount = 100;
        let gas_price = 100;
        let gas_limit = 1000;
        let tx = signed_message_coin_tx(rng, gas_price, gas_limit, input_amount);

        let checked = tx
            .into_checked(
                Default::default(),
                &ConsensusParameters::DEFAULT,
                &Default::default(),
            )
            .expect("Expected valid transaction");

        // verify available balance was decreased by max fee
        assert_eq!(
            checked.metadata().non_retryable_balances[&AssetId::default()],
            input_amount - checked.metadata().fee.max_fee()
        );
    }

    #[test]
    fn checked_tx_excludes_message_output_amount_from_fee() {
        // ensure message outputs aren't deducted from available balance
        let rng = &mut StdRng::seed_from_u64(2322u64);
        let input_amount = 100;
        let gas_price = 100;
        let gas_limit = 1000;
        let tx = signed_message_coin_tx(rng, gas_price, gas_limit, input_amount);

        let checked = tx
            .into_checked(
                Default::default(),
                &ConsensusParameters::DEFAULT,
                &Default::default(),
            )
            .expect("Expected valid transaction");

        // verify available balance was decreased by max fee
        assert_eq!(
            checked.metadata().non_retryable_balances[&AssetId::default()],
            input_amount - checked.metadata().fee.max_fee()
        );
    }

    #[test]
    fn message_data_signed_message_is_not_used_to_cover_fees() {
        // simple test to ensure a tx that only has a message input can cover fees
        let rng = &mut StdRng::seed_from_u64(2322u64);
        let input_amount = 100;
        let gas_price = 100;
        let gas_limit = 1000;
        let tx = TransactionBuilder::script(vec![], vec![])
            .gas_price(gas_price)
            .gas_limit(gas_limit)
            .add_unsigned_message_input(rng.gen(), rng.gen(), rng.gen(), input_amount, vec![0xff; 10])
            // Add empty base coin
            .add_unsigned_coin_input(rng.gen(), rng.gen(), 0, AssetId::BASE, rng.gen(), rng.gen())
            .finalize();

        let err = tx
            .into_checked(
                Default::default(),
                &ConsensusParameters::DEFAULT,
                &Default::default(),
            )
            .expect_err("Expected valid transaction");

        // verify available balance was decreased by max fee
        assert!(matches!(
            err,
            CheckError::InsufficientFeeAmount {
                expected: _,
                provided: 0
            }
        ));
    }

    #[test]
    fn message_data_predicate_message_is_not_used_to_cover_fees() {
        // simple test to ensure a tx that only has a message input can cover fees
        let rng = &mut StdRng::seed_from_u64(2322u64);
        let input_amount = 100;
        let gas_price = 100;
        let gas_limit = 1000;
        let tx = TransactionBuilder::script(vec![], vec![])
            .gas_price(gas_price)
            .gas_limit(gas_limit)
            .add_input(Input::message_data_predicate(
                rng.gen(),
                rng.gen(),
                input_amount,
                rng.gen(),
                Default::default(),
                vec![0xff; 10],
                vec![0xaa; 10],
                vec![0xbb; 10],
            ))
            // Add empty base coin
            .add_unsigned_coin_input(rng.gen(), rng.gen(), 0, AssetId::BASE, rng.gen(), rng.gen())
            .finalize();

        let err = tx
            .into_checked(
                Default::default(),
                &ConsensusParameters::DEFAULT,
                &Default::default(),
            )
            .expect_err("Expected valid transaction");

        // verify available balance was decreased by max fee
        assert!(matches!(
            err,
            CheckError::InsufficientFeeAmount {
                expected: _,
                provided: 0
            }
        ));
    }

    // use quickcheck to fuzz any rounding or precision errors in the max fee w/ coin
    // input
    #[quickcheck]
    fn max_fee_coin_input(
        gas_price: u64,
        gas_limit: u64,
        input_amount: u64,
        gas_price_factor: u64,
        seed: u64,
    ) -> TestResult {
        // verify max fee a transaction can consume based on gas limit + bytes is correct

        // dont divide by zero
        if gas_price_factor == 0 {
            return TestResult::discard()
        }

        let rng = &mut StdRng::seed_from_u64(seed);
        let params = ConsensusParameters::DEFAULT.with_gas_price_factor(gas_price_factor);
        let predicate_gas_used = rng.gen();
        let tx =
            predicate_tx(rng, gas_price, gas_limit, input_amount, predicate_gas_used);

        if let Ok(valid) = is_valid_max_fee(&tx, &params) {
            TestResult::from_bool(valid)
        } else {
            TestResult::discard()
        }
    }

    // use quickcheck to fuzz any rounding or precision errors in the min fee w/ coin
    // input
    #[quickcheck]
    fn min_fee_coin_input(
        gas_price: u64,
        gas_limit: u64,
        input_amount: u64,
        gas_price_factor: u64,
        seed: u64,
    ) -> TestResult {
        // verify min fee a transaction can consume based on bytes is correct

        // dont divide by zero
        if gas_price_factor == 0 {
            return TestResult::discard()
        }
        let rng = &mut StdRng::seed_from_u64(seed);
        let params = ConsensusParameters::DEFAULT.with_gas_price_factor(gas_price_factor);
        let predicate_gas_used = rng.gen();
        let tx =
            predicate_tx(rng, gas_price, gas_limit, input_amount, predicate_gas_used);

        if let Ok(valid) = is_valid_max_fee(&tx, &params) {
            TestResult::from_bool(valid)
        } else {
            TestResult::discard()
        }
    }

    // use quickcheck to fuzz any rounding or precision errors in the max fee w/ message
    // input
    #[quickcheck]
    fn max_fee_message_input(
        gas_price: u64,
        gas_limit: u64,
        input_amount: u64,
        gas_price_factor: u64,
        seed: u64,
    ) -> TestResult {
        // verify max fee a transaction can consume based on gas limit + bytes is correct

        // dont divide by zero
        if gas_price_factor == 0 {
            return TestResult::discard()
        }

        let rng = &mut StdRng::seed_from_u64(seed);
        let params = ConsensusParameters::DEFAULT.with_gas_price_factor(gas_price_factor);
        let tx = predicate_message_coin_tx(rng, gas_price, gas_limit, input_amount);

        if let Ok(valid) = is_valid_max_fee(&tx, &params) {
            TestResult::from_bool(valid)
        } else {
            TestResult::discard()
        }
    }

    // use quickcheck to fuzz any rounding or precision errors in the min fee w/ message
    // input
    #[quickcheck]
    fn min_fee_message_input(
        gas_price: u64,
        gas_limit: u64,
        input_amount: u64,
        gas_price_factor: u64,
        seed: u64,
    ) -> TestResult {
        // verify min fee a transaction can consume based on bytes is correct

        // dont divide by zero
        if gas_price_factor == 0 {
            return TestResult::discard()
        }
        let rng = &mut StdRng::seed_from_u64(seed);
        let params = ConsensusParameters::DEFAULT.with_gas_price_factor(gas_price_factor);
        let tx = predicate_message_coin_tx(rng, gas_price, gas_limit, input_amount);

        if let Ok(valid) = is_valid_min_fee(&tx, &params) {
            TestResult::from_bool(valid)
        } else {
            TestResult::discard()
        }
    }

    #[test]
    fn checked_tx_rejects_invalid_tx() {
        // simple smoke test that invalid txs cannot be checked
        let rng = &mut StdRng::seed_from_u64(2322u64);
        let asset = rng.gen();
        let gas_price = 1;
        let gas_limit = 100;
        let input_amount = 1_000;

        // create a tx with invalid signature
        let tx = TransactionBuilder::script(vec![], vec![])
            .gas_price(gas_price)
            .gas_limit(gas_limit)
            .add_input(Input::coin_signed(
                rng.gen(),
                rng.gen(),
                input_amount,
                asset,
                rng.gen(),
                Default::default(),
                Default::default(),
            ))
            .add_input(Input::contract(
                rng.gen(),
                rng.gen(),
                rng.gen(),
                rng.gen(),
                rng.gen(),
            ))
            .add_output(Output::contract(1, rng.gen(), rng.gen()))
            .add_output(Output::coin(rng.gen(), 10, asset))
            .add_output(Output::change(rng.gen(), 0, asset))
            .add_witness(Default::default())
            .finalize();

        let checked = tx
            .into_checked(
                Default::default(),
                &ConsensusParameters::DEFAULT,
                &Default::default(),
            )
            .expect_err("Expected invalid transaction");

        // assert that tx without base input assets fails
        assert_eq!(
            CheckError::InsufficientFeeAmount {
                expected: 1,
                provided: 0
            },
            checked
        );
    }

    #[test]
    fn checked_tx_fails_when_provided_fees_dont_cover_byte_costs() {
        let rng = &mut StdRng::seed_from_u64(2322u64);

        let input_amount = 1;
        let gas_price = 2; // price > amount
        let gas_limit = 0; // don't include any gas execution fees
        let factor = 1;
        let params = ConsensusParameters::default().with_gas_price_factor(factor);

        let transaction = base_asset_tx(rng, input_amount, gas_price, gas_limit);

        let err = transaction
            .into_checked(Default::default(), &params, &Default::default())
            .expect_err("insufficient fee amount expected");

        let provided = match err {
            CheckError::InsufficientFeeAmount { provided, .. } => provided,
            _ => panic!("expected insufficient fee amount; found {err:?}"),
        };

        assert_eq!(provided, input_amount);
    }

    #[test]
    fn checked_tx_fails_when_provided_fees_dont_cover_gas_costs() {
        let rng = &mut StdRng::seed_from_u64(2322u64);

        let input_amount = 10;
        let factor = 1;
        let params = ConsensusParameters::default().with_gas_price_factor(factor);
        // make gas price too high for the input amount
        let gas_price = 1;
        let gas_limit = input_amount + 1; // make gas cost 1 higher than input amount

        let transaction = base_asset_tx(rng, input_amount, gas_price, gas_limit);

        let err = transaction
            .into_checked(Default::default(), &params, &Default::default())
            .expect_err("insufficient fee amount expected");

        let provided = match err {
            CheckError::InsufficientFeeAmount { provided, .. } => provided,
            _ => panic!("expected insufficient fee amount; found {err:?}"),
        };

        assert_eq!(provided, input_amount);
    }

    #[test]
    fn bytes_fee_cant_overflow() {
        let rng = &mut StdRng::seed_from_u64(2322u64);

        let input_amount = 1000;
        let gas_price = Word::MAX;
        let gas_limit = 0; // ensure only bytes are included in fee
        let params = ConsensusParameters::default().with_gas_price_factor(1);
        let transaction = base_asset_tx(rng, input_amount, gas_price, gas_limit);

        let err = transaction
            .into_checked(Default::default(), &params, &Default::default())
            .expect_err("overflow expected");

        assert_eq!(err, CheckError::ArithmeticOverflow);
    }

    #[test]
    fn gas_fee_cant_overflow() {
        let rng = &mut StdRng::seed_from_u64(2322u64);
        let input_amount = 1000;
        let gas_price = Word::MAX;
        let gas_limit = 2; // 2 * max should cause gas fee overflow
        let params = ConsensusParameters::default().with_gas_price_factor(1);

        let transaction = base_asset_tx(rng, input_amount, gas_price, gas_limit);

        let err = transaction
            .into_checked(Default::default(), &params, &Default::default())
            .expect_err("overflow expected");

        assert_eq!(err, CheckError::ArithmeticOverflow);
    }

    #[test]
    fn checked_tx_fails_if_asset_is_overspent_by_coin_output() {
        let input_amount = 1_000;
        let rng = &mut StdRng::seed_from_u64(2322u64);
        let secret = SecretKey::random(rng);
        let any_asset = rng.gen();
        let tx = TransactionBuilder::script(vec![], vec![])
            .gas_price(1)
            .gas_limit(100)
            // base asset
            .add_unsigned_coin_input(
                secret,
                rng.gen(),
                input_amount,
                AssetId::default(),
                rng.gen(),
                Default::default(),
            )
            .add_output(Output::change(rng.gen(), 0, AssetId::default()))
            // arbitrary spending asset
            .add_unsigned_coin_input(
                secret,
                rng.gen(),
                input_amount,
                any_asset,
                rng.gen(),
                Default::default(),
            )
            .add_output(Output::coin(rng.gen(), input_amount + 1, any_asset))
            .add_output(Output::change(rng.gen(), 0, any_asset))
            .finalize();

        let checked = tx
            .into_checked(
                Default::default(),
                &ConsensusParameters::DEFAULT,
                &Default::default(),
            )
            .expect_err("Expected valid transaction");

        assert_eq!(
            CheckError::InsufficientInputAmount {
                asset: any_asset,
                expected: input_amount + 1,
                provided: input_amount
            },
            checked
        );
    }

    #[test]
    fn basic_check_marks_basic_flag() {
        let block_height = 1.into();
        let params = ConsensusParameters::default();

        let tx = Transaction::default_test_tx();
        // Sets Checks::Basic
        let checked = tx.into_checked_basic(block_height, &params).unwrap();
        assert!(checked.checks().contains(Checks::Basic));
    }

    #[test]
    fn signatures_check_marks_signatures_flag() {
        let mut rng = StdRng::seed_from_u64(1);
        let block_height = 1.into();
        let params = ConsensusParameters::default();

        let tx = valid_coin_tx(&mut rng, 1, 100000, 1000000, 10);
        let checked = tx
            // Sets Checks::Basic
            .into_checked_basic(block_height, &params)
            .unwrap()
            // Sets Checks::Signatures
            .check_signatures(&params.chain_id)
            .unwrap();

        assert!(checked
            .checks()
            .contains(Checks::Basic | Checks::Signatures));
    }

    #[test]
    fn predicates_check_marks_predicate_flag() {
        let mut rng = StdRng::seed_from_u64(1);
        let block_height = 1.into();
        let params = ConsensusParameters::default();
        let gas_costs = GasCosts::free();

        let tx = predicate_tx(&mut rng, 1, 1000000, 1000000, 0);

        let checked = tx
            // Sets Checks::Basic
            .into_checked_basic(block_height, &params)
            .unwrap()
            // Sets Checks::Predicates
            .check_predicates(&params, &gas_costs)
            .unwrap();
        assert!(checked
            .checks()
            .contains(Checks::Basic | Checks::Predicates));
    }

    fn is_valid_max_fee<Tx>(
        tx: &Tx,
        params: &ConsensusParameters,
    ) -> Result<bool, CheckError>
    where
        Tx: Chargeable + field::Inputs + field::Outputs,
    {
        let available_balances = balances::initial_free_balances(tx, params)?;
        // cant overflow as metered bytes * gas_per_byte < u64::MAX
        let bytes = (tx.metered_bytes_size() as u128)
            * params.gas_per_byte as u128
            * tx.price() as u128;
        let gas = tx.limit() as u128 * tx.price() as u128;
        let total = bytes + gas;
        // use different division mechanism than impl
        let fee = total / params.gas_price_factor as u128;
        let fee_remainder =
            (total.rem_euclid(params.gas_price_factor as u128) > 0) as u128;
        let rounded_fee = (fee + fee_remainder) as u64;

        Ok(rounded_fee == available_balances.fee.max_fee())
    }

    fn is_valid_min_fee<Tx>(
        tx: &Tx,
        params: &ConsensusParameters,
    ) -> Result<bool, CheckError>
    where
        Tx: Chargeable + field::Inputs + field::Outputs,
    {
        let available_balances = balances::initial_free_balances(tx, params)?;
        // cant overflow as (metered bytes + gas_used_by_predicates) * gas_per_byte <
        // u64::MAX
        let bytes = (tx.metered_bytes_size() as u128
            + tx.gas_used_by_predicates() as u128)
            * params.gas_per_byte as u128
            * tx.price() as u128;
        // use different division mechanism than impl
        let fee = bytes / params.gas_price_factor as u128;
        let fee_remainder =
            (bytes.rem_euclid(params.gas_price_factor as u128) > 0) as u128;
        let rounded_fee = (fee + fee_remainder) as u64;

        Ok(rounded_fee == available_balances.fee.min_fee())
    }

    fn valid_coin_tx(
        rng: &mut StdRng,
        gas_price: u64,
        gas_limit: u64,
        input_amount: u64,
        output_amount: u64,
    ) -> Script {
        let asset = AssetId::default();
        TransactionBuilder::script(vec![], vec![])
            .gas_price(gas_price)
            .gas_limit(gas_limit)
            .add_unsigned_coin_input(
                rng.gen(),
                rng.gen(),
                input_amount,
                asset,
                rng.gen(),
                Default::default(),
            )
            .add_input(Input::contract(
                rng.gen(),
                rng.gen(),
                rng.gen(),
                rng.gen(),
                rng.gen(),
            ))
            .add_output(Output::contract(1, rng.gen(), rng.gen()))
            .add_output(Output::coin(rng.gen(), output_amount, asset))
            .add_output(Output::change(rng.gen(), 0, asset))
            .finalize()
    }

    // used when proptesting to avoid expensive crypto signatures
    fn predicate_tx(
        rng: &mut StdRng,
        gas_price: u64,
        gas_limit: u64,
        fee_input_amount: u64,
        predicate_gas_used: u64,
    ) -> Script {
        let asset = AssetId::default();
        let predicate = vec![op::ret(1)].into_iter().collect::<Vec<u8>>();
        let owner =
            Input::predicate_owner(&predicate, &ConsensusParameters::DEFAULT.chain_id);
        TransactionBuilder::script(vec![], vec![])
            .gas_price(gas_price)
            .gas_limit(gas_limit)
            .add_input(Input::coin_predicate(
                rng.gen(),
                owner,
                fee_input_amount,
                asset,
                rng.gen(),
                Default::default(),
                predicate_gas_used,
                predicate,
                vec![],
            ))
            .add_output(Output::change(rng.gen(), 0, asset))
            .finalize()
    }

    // used to verify message inputs can cover fees
    fn signed_message_coin_tx(
        rng: &mut StdRng,
        gas_price: u64,
        gas_limit: u64,
        input_amount: u64,
    ) -> Script {
        TransactionBuilder::script(vec![], vec![])
            .gas_price(gas_price)
            .gas_limit(gas_limit)
            .add_unsigned_message_input(
                rng.gen(),
                rng.gen(),
                rng.gen(),
                input_amount,
                vec![],
            )
            .finalize()
    }

    fn predicate_message_coin_tx(
        rng: &mut StdRng,
        gas_price: u64,
        gas_limit: u64,
        input_amount: u64,
    ) -> Script {
        TransactionBuilder::script(vec![], vec![])
            .gas_price(gas_price)
            .gas_limit(gas_limit)
            .add_input(Input::message_coin_predicate(
                rng.gen(),
                rng.gen(),
                input_amount,
                rng.gen(),
                Default::default(),
                vec![],
                vec![],
            ))
            .finalize()
    }

    fn base_asset_tx(
        rng: &mut StdRng,
        input_amount: u64,
        gas_price: u64,
        gas_limit: u64,
    ) -> Script {
        TransactionBuilder::script(vec![], vec![])
            .gas_price(gas_price)
            .gas_limit(gas_limit)
            .add_unsigned_coin_input(
                rng.gen(),
                rng.gen(),
                input_amount,
                AssetId::default(),
                rng.gen(),
                Default::default(),
            )
            .add_output(Output::change(rng.gen(), 0, AssetId::default()))
            .finalize()
    }
}