fuel-core-upgradable-executor 0.43.0

Fuel Block Upgradable Executor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
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
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
#[cfg(feature = "wasm-executor")]
use crate::error::UpgradableError;
use crate::{
    config::Config,
    storage_access_recorder::StorageAccessRecorder,
};
use fuel_core_executor::{
    executor::{
        ExecutionInstance,
        ExecutionOptions,
        OnceTransactionsSource,
        TimeoutOnlyTxWaiter,
        TransparentPreconfirmationSender,
    },
    ports::{
        NewTxWaiterPort,
        PreconfirmationSenderPort,
        RelayerPort,
        TransactionsSource,
    },
};
use fuel_core_storage::{
    column::Column,
    kv_store::KeyValueInspect,
    transactional::{
        AtomicView,
        Changes,
        HistoricalView,
        Modifiable,
    },
};
use fuel_core_types::{
    blockchain::{
        block::Block,
        header::{
            StateTransitionBytecodeVersion,
            LATEST_STATE_TRANSITION_VERSION,
        },
    },
    fuel_tx::Transaction,
    fuel_types::BlockHeight,
    services::{
        block_producer::Components,
        executor::{
            DryRunResult,
            Error as ExecutorError,
            ExecutionResult,
            Result as ExecutorResult,
            StorageReadReplayEvent,
            ValidationResult,
        },
        Uncommitted,
    },
};
use futures::FutureExt;
use std::sync::Arc;

#[cfg(feature = "wasm-executor")]
use fuel_core_storage::{
    not_found,
    structured_storage::StructuredStorage,
    tables::{
        StateTransitionBytecodeVersions,
        UploadedBytecodes,
    },
    StorageAsRef,
};
#[cfg(any(test, feature = "test-helpers"))]
use fuel_core_types::blockchain::block::PartialFuelBlock;
#[cfg(any(test, feature = "test-helpers"))]
use fuel_core_types::services::executor::UncommittedResult;

#[cfg(feature = "wasm-executor")]
use fuel_core_executor::executor::convert_tx_execution_result_to_preconfirmation;
#[cfg(feature = "wasm-executor")]
use fuel_core_types::{
    fuel_types::Bytes32,
    services::preconfirmation::{
        Preconfirmation,
        PreconfirmationStatus,
    },
};
#[cfg(feature = "wasm-executor")]
use fuel_core_wasm_executor::utils::{
    convert_from_v0_execution_result,
    convert_from_v1_execution_result,
    ReturnType,
};

#[cfg(feature = "wasm-executor")]
enum ExecutionStrategy {
    /// The native executor used when the version matches.
    Native,
    /// The WASM executor used even when the version matches.
    Wasm {
        /// The compiled WASM module of the native executor bytecode.
        module: wasmtime::Module,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum BlockHeightSelection {
    Latest,
    Past { height: BlockHeight },
}

enum ProduceBlockMode {
    Produce,
    DryRun {
        height: BlockHeightSelection,
        record_storage_reads: bool,
    },
}
impl ProduceBlockMode {
    fn is_dry_run(&self) -> bool {
        matches!(self, Self::DryRun { .. })
    }

    fn record_storage_reads(&self) -> bool {
        match self {
            Self::Produce => false,
            Self::DryRun {
                record_storage_reads,
                ..
            } => *record_storage_reads,
        }
    }
}

/// Result of various `produce_*` functions
struct ProducedBlock {
    result: ExecutionResult,
    storage_reads: Vec<StorageReadReplayEvent>,
}

/// The upgradable executor supports the WASM version of the state transition function.
/// If the block has a version the same as a native executor, we will use it.
/// If not, the WASM version of the state transition function will be used
/// (if the database has a corresponding bytecode).
pub struct Executor<S, R> {
    pub storage_view_provider: S,
    pub relayer_view_provider: R,
    pub config: Arc<Config>,
    #[cfg(feature = "wasm-executor")]
    engine: wasmtime::Engine,
    #[cfg(feature = "wasm-executor")]
    execution_strategy: ExecutionStrategy,
    #[cfg(feature = "wasm-executor")]
    cached_modules: parking_lot::Mutex<
        std::collections::HashMap<StateTransitionBytecodeVersion, wasmtime::Module>,
    >,
}

#[cfg(feature = "wasm-executor")]
mod private {
    use std::sync::OnceLock;
    use wasmtime::{
        Config,
        Engine,
        Module,
    };

    /// The default engine for the WASM executor. It is used to compile the WASM bytecode.
    static DEFAULT_ENGINE: OnceLock<Engine> = OnceLock::new();

    /// The default module compiles the WASM bytecode of the native executor.
    /// It is used to create the WASM instance of the executor.
    pub(crate) static COMPILED_UNDERLYING_EXECUTOR: OnceLock<Module> = OnceLock::new();

    pub(crate) fn default_engine() -> &'static Engine {
        DEFAULT_ENGINE.get_or_init(|| {
            let mut config = Config::default();
            // Enables compilation caching.
            config
                .cache_config_load_default()
                .expect("Failed to load the default cache config");
            Engine::new(&config).expect("Failed to create the default engine")
        })
    }
}

#[cfg(feature = "wasm-executor")]
/// The environment variable that forces the executor to use the WASM
/// version of the state transition function.
pub const FUEL_ALWAYS_USE_WASM: &str = "FUEL_ALWAYS_USE_WASM";

impl<S, R> Executor<S, R> {
    /// The current version of the native executor is used to determine whether
    /// we need to use a native executor or WASM. If the version is the same as
    /// on the block, native execution is used. If the version is not the same
    /// as in the block, then the WASM executor is used.
    pub const VERSION: u32 = LATEST_STATE_TRANSITION_VERSION;

    /// This constant is used along with the `version_check` test.
    /// To avoid automatic bumping during release, the constant uses `-` instead of `.`.
    /// Each release should have its own new version of the executor.
    /// The version of the executor should grow without gaps.
    /// If publishing the release fails or the release is invalid, and
    /// we don't plan to upgrade the network to use this release,
    /// we still need to increase the version. The network can
    /// easily skip releases by upgrading to the old state transition function.
    pub const CRATE_VERSIONS: &'static [(
        &'static str,
        StateTransitionBytecodeVersion,
    )] = &[
        ("0-26-0", StateTransitionBytecodeVersion::MIN),
        ("0-27-0", 1),
        ("0-28-0", 2),
        ("0-29-0", 3),
        ("0-30-0", 4),
        ("0-31-0", 5),
        ("0-32-0", 6),
        ("0-32-1", 7),
        ("0-33-0", 8),
        ("0-34-0", 9),
        ("0-35-0", 10),
        ("0-36-0", 11),
        ("0-37-0", 12),
        ("0-37-1", 13),
        ("0-38-0", 14),
        ("0-39-0", 15),
        ("0-40-0", 16),
        ("0-40-1", 17),
        ("0-40-2", 18),
        ("0-41-4", 19),
        ("0-41-5", 20),
        ("0-41-6", 21),
        // This update has been performed on the branch release/v0.41.7 which
        // is on top of the branch release/v0.41.6 not on master.
        ("0-41-7", 22),
        // This update has been performed on the branch release/v0.41.8 which
        // is on top of the branch release/v0.41.7 not on master.
        ("0-41-8", 23),
        // This update has been performed on the branch release/v0.41.9 which
        // is on top of the branch release/v0.41.8 not on master.
        ("0-41-9", 24),
        ("0-42-0", 25),
        ("0-43-0", LATEST_STATE_TRANSITION_VERSION),
    ];

    pub fn new(
        storage_view_provider: S,
        relayer_view_provider: R,
        config: Config,
    ) -> Self {
        #[cfg(feature = "wasm-executor")]
        {
            if std::env::var_os(FUEL_ALWAYS_USE_WASM).is_some() {
                Self::wasm(storage_view_provider, relayer_view_provider, config)
            } else {
                Self::native(storage_view_provider, relayer_view_provider, config)
            }
        }
        #[cfg(not(feature = "wasm-executor"))]
        {
            Self::native(storage_view_provider, relayer_view_provider, config)
        }
    }

    pub fn native_executor_version(&self) -> StateTransitionBytecodeVersion {
        self.config.native_executor_version.unwrap_or(Self::VERSION)
    }

    pub fn native(
        storage_view_provider: S,
        relayer_view_provider: R,
        config: Config,
    ) -> Self {
        Self {
            storage_view_provider,
            relayer_view_provider,
            config: Arc::new(config),
            #[cfg(feature = "wasm-executor")]
            engine: private::default_engine().clone(),
            #[cfg(feature = "wasm-executor")]
            execution_strategy: ExecutionStrategy::Native,
            #[cfg(feature = "wasm-executor")]
            cached_modules: Default::default(),
        }
    }

    #[cfg(feature = "wasm-executor")]
    pub fn wasm(
        storage_view_provider: S,
        relayer_view_provider: R,
        config: Config,
    ) -> Self {
        let engine = private::default_engine();
        let module = private::COMPILED_UNDERLYING_EXECUTOR.get_or_init(|| {
            wasmtime::Module::new(engine, crate::WASM_BYTECODE)
                .expect("Failed to validate the WASM bytecode")
        });

        Self {
            storage_view_provider,
            relayer_view_provider,
            config: Arc::new(config),
            engine: engine.clone(),
            execution_strategy: ExecutionStrategy::Wasm {
                module: module.clone(),
            },
            cached_modules: Default::default(),
        }
    }
}

impl<S, R> Executor<S, R>
where
    S: HistoricalView<Height = BlockHeight> + Modifiable,
    S::LatestView: KeyValueInspect<Column = Column> + Send + Sync + 'static,
    S::ViewAtHeight: KeyValueInspect<Column = Column> + Send + Sync + 'static,
    R: AtomicView,
    R::LatestView: RelayerPort + Send + Sync + 'static,
{
    #[cfg(any(test, feature = "test-helpers"))]
    /// Executes the block and commits the result of the execution into the inner `Database`.
    pub fn produce_and_commit(
        &mut self,
        block: PartialFuelBlock,
    ) -> fuel_core_types::services::executor::Result<ExecutionResult> {
        let (result, changes) = self.produce_without_commit(block)?.into();

        self.storage_view_provider.commit_changes(changes)?;
        Ok(result)
    }

    #[cfg(any(test, feature = "test-helpers"))]
    /// Executes the block and commits the result of the execution into the inner `Database`.
    pub fn validate_and_commit(
        &mut self,
        block: &Block,
    ) -> fuel_core_types::services::executor::Result<ValidationResult> {
        let (result, changes) = self.validate(block)?.into();
        self.storage_view_provider.commit_changes(changes)?;
        Ok(result)
    }
}

#[cfg(any(test, feature = "test-helpers"))]
impl<S, R> Executor<S, R>
where
    S: HistoricalView<Height = BlockHeight>,
    S::LatestView: KeyValueInspect<Column = Column> + Send + Sync + 'static,
    S::ViewAtHeight: KeyValueInspect<Column = Column> + Send + Sync + 'static,
    R: AtomicView,
    R::LatestView: RelayerPort + Send + Sync + 'static,
{
    /// Executes the block and returns the result of the execution with storage changes.
    pub fn produce_without_commit(
        &self,
        block: PartialFuelBlock,
    ) -> fuel_core_types::services::executor::Result<UncommittedResult<Changes>> {
        self.produce_without_commit_with_coinbase(block, Default::default(), 0)
    }

    /// The analog of the [`Self::produce_without_commit`] method,
    /// but with the ability to specify the coinbase recipient and the gas price.
    pub fn produce_without_commit_with_coinbase(
        &self,
        block: PartialFuelBlock,
        coinbase_recipient: fuel_core_types::fuel_types::ContractId,
        gas_price: u64,
    ) -> fuel_core_types::services::executor::Result<UncommittedResult<Changes>> {
        let component = Components {
            header_to_produce: block.header,
            transactions_source: OnceTransactionsSource::new(block.transactions),
            coinbase_recipient,
            gas_price,
        };

        let options = self.config.as_ref().into();
        self.produce_inner_sync(component, options, ProduceBlockMode::Produce)
            .map(|r| r.map_result(|produced| produced.result))
    }

    /// Executes a dry-run of the block and returns the result of the execution without committing the changes.
    pub fn dry_run_without_commit_with_source<TxSource>(
        &self,
        block: Components<TxSource>,
    ) -> ExecutorResult<Uncommitted<ExecutionResult, Changes>>
    where
        TxSource: TransactionsSource + Send + Sync + 'static,
    {
        let options = self.config.as_ref().into();
        self.produce_inner_sync(
            block,
            options,
            ProduceBlockMode::DryRun {
                height: BlockHeightSelection::Latest,
                record_storage_reads: false,
            },
        )
        .map(|r| r.map_result(|produced| produced.result))
    }
}

impl<S, R> Executor<S, R>
where
    S: HistoricalView<Height = BlockHeight>,
    S::LatestView: KeyValueInspect<Column = Column> + Send + Sync + 'static,
    S::ViewAtHeight: KeyValueInspect<Column = Column> + Send + Sync + 'static,
    R: AtomicView,
    R::LatestView: RelayerPort + Send + Sync + 'static,
{
    pub fn produce_without_commit_with_source_direct_resolve<TxSource>(
        &self,
        block: Components<TxSource>,
    ) -> ExecutorResult<Uncommitted<ExecutionResult, Changes>>
    where
        TxSource: TransactionsSource + Send + Sync + 'static,
    {
        let options = self.config.as_ref().into();
        Ok(self
            .produce_inner_sync(block, options, ProduceBlockMode::Produce)?
            .map_result(|produced| produced.result))
    }

    /// Produces the block and returns the result of the execution without committing the changes.
    pub async fn produce_without_commit_with_source<TxSource>(
        &self,
        components: Components<TxSource>,
        new_tx_waiter: impl NewTxWaiterPort,
        preconfirmation_sender: impl PreconfirmationSenderPort,
    ) -> ExecutorResult<Uncommitted<ExecutionResult, Changes>>
    where
        TxSource: TransactionsSource + Send + Sync + 'static,
    {
        let options = self.config.as_ref().into();
        Ok(self
            .produce_inner(
                components,
                options,
                ProduceBlockMode::Produce,
                new_tx_waiter,
                preconfirmation_sender,
            )
            .await?
            .map_result(|produced| produced.result))
    }

    /// Executes the block and returns the result of the execution without committing
    /// the changes in the dry run mode.
    pub fn dry_run(
        &self,
        component: Components<Vec<Transaction>>,
        forbid_fake_coins: Option<bool>,
        at_height: Option<BlockHeight>,
        record_storage_reads: bool,
    ) -> ExecutorResult<DryRunResult> {
        if at_height.is_some() && !self.config.allow_historical_execution {
            return Err(ExecutorError::Other(
                "The historical execution is not allowed".to_string(),
            ));
        }

        // fallback to service config value if no utxo_validation override is provided
        let forbid_fake_coins =
            forbid_fake_coins.unwrap_or(self.config.forbid_fake_coins_default);

        let options = ExecutionOptions {
            forbid_fake_coins,
            backtrace: false,
        };

        let component = Components {
            header_to_produce: component.header_to_produce,
            transactions_source: OnceTransactionsSource::new(
                component.transactions_source,
            ),
            coinbase_recipient: Default::default(),
            gas_price: component.gas_price,
        };

        let ProducedBlock {
            result:
                ExecutionResult {
                    block,
                    skipped_transactions,
                    tx_status,
                    ..
                },
            storage_reads,
        } = self
            .produce_inner_sync(
                component,
                options,
                ProduceBlockMode::DryRun {
                    height: match at_height {
                        Some(height) => BlockHeightSelection::Past { height },
                        None => BlockHeightSelection::Latest,
                    },
                    record_storage_reads,
                },
            )?
            .into_result();

        // If any of the transactions fails, return an error.
        if let Some((_, err)) = skipped_transactions.into_iter().next() {
            return Err(err)
        }

        let (_, txs) = block.into_inner();
        let transactions = txs.into_iter().zip(tx_status).collect();

        Ok(DryRunResult {
            transactions,
            storage_reads,
        })
    }

    pub fn validate(
        &self,
        block: &Block,
    ) -> ExecutorResult<Uncommitted<ValidationResult, Changes>> {
        let options = self.config.as_ref().into();
        self.validate_inner(block, options)
    }

    #[cfg(not(feature = "wasm-executor"))]
    pub fn storage_read_replay(
        &self,
        block: &Block,
    ) -> ExecutorResult<Vec<StorageReadReplayEvent>> {
        let block_version = block.header().state_transition_bytecode_version();
        let native_executor_version = self.native_executor_version();
        if block_version == native_executor_version {
            self.native_storage_read_replay(block)
        } else {
            Err(ExecutorError::Other(format!(
                "Not supported version `{block_version}`. Expected version is `{}`",
                Self::VERSION
            )))
        }
    }

    #[cfg(feature = "wasm-executor")]
    pub fn storage_read_replay(
        &self,
        block: &Block,
    ) -> ExecutorResult<Vec<StorageReadReplayEvent>> {
        let block_version = block.header().state_transition_bytecode_version();
        let native_executor_version = self.native_executor_version();
        if block_version == native_executor_version {
            match &self.execution_strategy {
                ExecutionStrategy::Native => self.native_storage_read_replay(block),
                ExecutionStrategy::Wasm { module } => {
                    if let Ok(module) = self.get_module(block_version) {
                        self.wasm_storage_read_replay(&module, block)
                    } else {
                        self.wasm_storage_read_replay(module, block)
                    }
                }
            }
        } else {
            let module = self.get_module(block_version)?;
            self.wasm_storage_read_replay(&module, block)
        }
    }

    pub fn native_storage_read_replay(
        &self,
        block: &Block,
    ) -> ExecutorResult<Vec<StorageReadReplayEvent>> {
        let previous_block_height = block.header().height().pred();
        let relayer = self.relayer_view_provider.latest_view()?;

        let storage_rec = if let Some(previous_block_height) = previous_block_height {
            let database = self.storage_view_provider.view_at(&previous_block_height)?;
            let database = StorageAccessRecorder::new(database);
            let database_rec = database.record.clone();

            let executor =
                ExecutionInstance::new(relayer, database, self.config.as_ref().into());
            let _ = executor.validate_without_commit(block)?;
            database_rec
        } else {
            let database = self.storage_view_provider.latest_view()?;
            let database = StorageAccessRecorder::new(database);
            let database_rec = database.record.clone();
            let executor =
                ExecutionInstance::new(relayer, database, self.config.as_ref().into());
            let _ = executor.validate_without_commit(block)?;
            database_rec
        };

        let mut g = storage_rec.lock();
        Ok(core::mem::take(&mut g))
    }

    #[cfg(feature = "wasm-executor")]
    fn wasm_storage_read_replay(
        &self,
        module: &wasmtime::Module,
        block: &Block,
    ) -> ExecutorResult<Vec<StorageReadReplayEvent>> {
        let options = self.config.as_ref().into();
        let previous_block_height = block.header().height().pred();

        let instance = crate::instance::Instance::new(&self.engine).no_source()?;

        let (instance, storage_rec) = if let Some(previous_block_height) =
            previous_block_height
        {
            let storage = self.storage_view_provider.view_at(&previous_block_height)?;
            let storage = StorageAccessRecorder::new(storage);
            let storage_rec = storage.record.clone();
            (instance.add_storage(storage)?, storage_rec)
        } else {
            let storage = self.storage_view_provider.latest_view()?;
            let storage = StorageAccessRecorder::new(storage);
            let storage_rec = storage.record.clone();
            (instance.add_storage(storage)?, storage_rec)
        };

        let relayer = self.relayer_view_provider.latest_view()?;
        let instance = instance
            .add_relayer(relayer)?
            .add_validation_input_data(block, options)?;

        let output = instance.run(module)?;

        match output {
            ReturnType::ExecutionV0(result) => {
                let _ = convert_from_v0_execution_result(result)?;
            }
            ReturnType::ExecutionV1(result) => {
                let _ = convert_from_v1_execution_result(result)?;
            }
            ReturnType::Validation(result) => {
                let _ = result?;
            }
        }
        let mut g = storage_rec.lock();
        Ok(core::mem::take(&mut g))
    }

    fn produce_inner_sync<TxSource>(
        &self,
        block: Components<TxSource>,
        options: ExecutionOptions,
        mode: ProduceBlockMode,
    ) -> ExecutorResult<Uncommitted<ProducedBlock, Changes>>
    where
        TxSource: TransactionsSource + Send + Sync + 'static,
    {
        self.produce_inner(
            block,
            options,
            mode,
            TimeoutOnlyTxWaiter,
            TransparentPreconfirmationSender,
        )
        .now_or_never()
        .ok_or_else(|| {
            ExecutorError::Other(
                "Impossible to resolve the executor's future immediately".to_string(),
            )
        })?
    }

    #[cfg(feature = "wasm-executor")]
    async fn produce_inner<TxSource>(
        &self,
        block: Components<TxSource>,
        options: ExecutionOptions,
        mode: ProduceBlockMode,
        new_tx_waiter: impl NewTxWaiterPort,
        preconfirmation_sender: impl PreconfirmationSenderPort,
    ) -> ExecutorResult<Uncommitted<ProducedBlock, Changes>>
    where
        TxSource: TransactionsSource + Send + Sync + 'static,
    {
        let block_version = block.header_to_produce.state_transition_bytecode_version;
        let native_executor_version = self.native_executor_version();
        if block_version == native_executor_version {
            match &self.execution_strategy {
                ExecutionStrategy::Native => {
                    self.native_produce_inner(
                        block,
                        options,
                        mode,
                        new_tx_waiter,
                        preconfirmation_sender,
                    )
                    .await
                }
                ExecutionStrategy::Wasm { module } => {
                    let maybe_blocks_module = self.get_module(block_version).ok();
                    if let Some(blocks_module) = maybe_blocks_module {
                        self.wasm_produce_inner(
                            &blocks_module,
                            block,
                            options,
                            mode,
                            preconfirmation_sender,
                        )
                        .await
                    } else {
                        self.wasm_produce_inner(
                            module,
                            block,
                            options,
                            mode,
                            preconfirmation_sender,
                        )
                        .await
                    }
                }
            }
        } else {
            let module = self.get_module(block_version)?;
            self.wasm_produce_inner(&module, block, options, mode, preconfirmation_sender)
                .await
        }
    }

    #[cfg(not(feature = "wasm-executor"))]
    async fn produce_inner<TxSource>(
        &self,
        block: Components<TxSource>,
        options: ExecutionOptions,
        mode: ProduceBlockMode,
        new_tx_waiter: impl NewTxWaiterPort,
        preconfirmation_sender: impl PreconfirmationSenderPort,
    ) -> ExecutorResult<Uncommitted<ProducedBlock, Changes>>
    where
        TxSource: TransactionsSource + Send + Sync + 'static,
    {
        let block_version = block.header_to_produce.state_transition_bytecode_version;
        let native_executor_version = self.native_executor_version();
        if block_version == native_executor_version {
            self.native_produce_inner(
                block,
                options,
                mode,
                new_tx_waiter,
                preconfirmation_sender,
            )
            .await
        } else {
            Err(ExecutorError::Other(format!(
                "Not supported version `{block_version}`. Expected version is `{}`",
                Self::VERSION
            )))
        }
    }

    #[cfg(feature = "wasm-executor")]
    fn validate_inner(
        &self,
        block: &Block,
        options: ExecutionOptions,
    ) -> ExecutorResult<Uncommitted<ValidationResult, Changes>> {
        let block_version = block.header().state_transition_bytecode_version();
        let native_executor_version = self.native_executor_version();
        if block_version == native_executor_version {
            match &self.execution_strategy {
                ExecutionStrategy::Native => self.native_validate_inner(block, options),
                ExecutionStrategy::Wasm { module } => {
                    let maybe_blocks_module = self.get_module(block_version).ok();
                    if let Some(blocks_module) = maybe_blocks_module {
                        self.wasm_validate_inner(&blocks_module, block, options)
                    } else {
                        self.wasm_validate_inner(module, block, options)
                    }
                }
            }
        } else {
            let module = self.get_module(block_version)?;
            self.wasm_validate_inner(&module, block, self.config.as_ref().into())
        }
    }

    #[cfg(feature = "wasm-executor")]
    fn trace_block_version_warning(&self, block_version: StateTransitionBytecodeVersion) {
        tracing::warn!(
            "The block version({}) is different from the native executor version({}). \
                The WASM executor will be used.",
            block_version,
            self.native_executor_version()
        );
    }

    #[cfg(not(feature = "wasm-executor"))]
    fn validate_inner(
        &self,
        block: &Block,
        options: ExecutionOptions,
    ) -> ExecutorResult<Uncommitted<ValidationResult, Changes>> {
        let block_version = block.header().state_transition_bytecode_version();
        let native_executor_version = self.native_executor_version();
        if block_version == native_executor_version {
            self.native_validate_inner(block, options)
        } else {
            Err(ExecutorError::Other(format!(
                "Not supported version `{block_version}`. Expected version is `{}`",
                Self::VERSION
            )))
        }
    }

    #[cfg(feature = "wasm-executor")]
    async fn wasm_produce_inner<TxSource>(
        &self,
        module: &wasmtime::Module,
        component: Components<TxSource>,
        options: ExecutionOptions,
        mode: ProduceBlockMode,
        preconfirmation_sender: impl PreconfirmationSenderPort,
    ) -> ExecutorResult<Uncommitted<ProducedBlock, Changes>>
    where
        TxSource: TransactionsSource + Send + Sync + 'static,
    {
        let Components {
            header_to_produce,
            transactions_source,
            coinbase_recipient,
            gas_price,
        } = component;
        self.trace_block_version_warning(
            header_to_produce.state_transition_bytecode_version,
        );

        let source = Some(transactions_source);

        let block = Components {
            header_to_produce,
            transactions_source: (),
            coinbase_recipient,
            gas_price,
        };

        let db_height = match mode {
            ProduceBlockMode::Produce => block.header_to_produce.height().pred(),
            ProduceBlockMode::DryRun { height, .. } => match height {
                BlockHeightSelection::Latest => None,
                BlockHeightSelection::Past { height } => height.pred(),
            },
        };

        let instance_without_input =
            crate::instance::Instance::new(&self.engine).add_source(source)?;

        let mut storage_rec = Default::default();
        let instance_without_input = if let Some(previous_block_height) = db_height {
            let storage = self.storage_view_provider.view_at(&previous_block_height)?;
            if mode.record_storage_reads() {
                let storage = StorageAccessRecorder::new(storage);
                storage_rec = storage.record.clone();
                instance_without_input.add_storage(storage)?
            } else {
                instance_without_input.add_storage(storage)?
            }
        } else {
            let storage = self.storage_view_provider.latest_view()?;
            if mode.record_storage_reads() {
                let storage = StorageAccessRecorder::new(storage);
                storage_rec = storage.record.clone();
                instance_without_input.add_storage(storage)?
            } else {
                instance_without_input.add_storage(storage)?
            }
        };

        let relayer = self.relayer_view_provider.latest_view()?;
        let instance_without_input = instance_without_input.add_relayer(relayer)?;

        let instance = if mode.is_dry_run() {
            instance_without_input.add_dry_run_input_data(block, options)?
        } else {
            instance_without_input.add_production_input_data(block, options)?
        };

        let output = instance.run(module)?;

        let result = match output {
            ReturnType::ExecutionV0(result) => {
                convert_from_v0_execution_result(result)
            },
            ReturnType::ExecutionV1(result) => {
                convert_from_v1_execution_result(result)
            }
            ReturnType::Validation(_) => {
                Err(ExecutorError::Other(
                    "The WASM executor returned a validation result instead of an execution result"
                        .to_string(),
                ))
            }
        }?;

        let execution_result = result.result();
        let iter = execution_result.tx_status.iter();
        let iter = iter.zip(execution_result.block.transactions());
        let mut preconfirmations = iter
            .enumerate()
            .map(|(i, (status, tx))| {
                let tx_index = u16::try_from(i).unwrap_or(u16::MAX);
                let preconfirmation_status =
                    convert_tx_execution_result_to_preconfirmation(
                        tx,
                        status.id,
                        &status.result,
                        *execution_result.block.header().height(),
                        tx_index,
                    );
                preconfirmation_status
            })
            .collect::<Vec<_>>();

        let squeezed_out =
            execution_result
                .skipped_transactions
                .iter()
                .map(|(tx_id, error)| Preconfirmation {
                    tx_id: *tx_id,
                    status: PreconfirmationStatus::SqueezedOut {
                        reason: error.to_string(),
                    },
                });

        preconfirmations.extend(squeezed_out);

        let _ = preconfirmation_sender.send(preconfirmations).await;

        let mut g = storage_rec.lock();
        let storage_reads = core::mem::take(&mut *g);

        Ok(result.map_result(|result| ProducedBlock {
            result,
            storage_reads,
        }))
    }

    #[cfg(feature = "wasm-executor")]
    fn wasm_validate_inner(
        &self,
        module: &wasmtime::Module,
        block: &Block,
        options: ExecutionOptions,
    ) -> ExecutorResult<Uncommitted<ValidationResult, Changes>> {
        self.trace_block_version_warning(
            block.header().state_transition_bytecode_version(),
        );
        let previous_block_height = block.header().height().pred();

        let instance = crate::instance::Instance::new(&self.engine).no_source()?;

        let instance = if let Some(previous_block_height) = previous_block_height {
            let storage = self.storage_view_provider.view_at(&previous_block_height)?;
            instance.add_storage(storage)?
        } else {
            let storage = self.storage_view_provider.latest_view()?;
            instance.add_storage(storage)?
        };

        let relayer = self.relayer_view_provider.latest_view()?;
        let instance = instance
            .add_relayer(relayer)?
            .add_validation_input_data(block, options)?;

        let output = instance.run(module)?;

        match output {
            ReturnType::ExecutionV0(result) => {
                Ok(convert_from_v0_execution_result(result)?.into_validation_result())
            }
            ReturnType::ExecutionV1(result) => {
                let result = convert_from_v1_execution_result(result)?;
                Ok(result.into_validation_result())
            }
            ReturnType::Validation(result) => Ok(result?),
        }
    }

    async fn native_produce_inner<TxSource>(
        &self,
        block: Components<TxSource>,
        options: ExecutionOptions,
        mode: ProduceBlockMode,
        new_tx_waiter: impl NewTxWaiterPort,
        preconfirmation_sender: impl PreconfirmationSenderPort,
    ) -> ExecutorResult<Uncommitted<ProducedBlock, Changes>>
    where
        TxSource: TransactionsSource + Send + Sync + 'static,
    {
        let relayer = self.relayer_view_provider.latest_view()?;

        let db_height = match mode {
            ProduceBlockMode::Produce => block.header_to_produce.height().pred(),
            ProduceBlockMode::DryRun { height, .. } => match height {
                BlockHeightSelection::Latest => None,
                BlockHeightSelection::Past { height } => height.pred(),
            },
        };

        let mut storage_rec = Default::default();

        let result = if let Some(previous_block_height) = db_height {
            let database = self.storage_view_provider.view_at(&previous_block_height)?;
            if mode.record_storage_reads() {
                let database = StorageAccessRecorder::new(database);
                storage_rec = database.record.clone();
                ExecutionInstance::new(relayer, database, options)
                    .produce_without_commit(
                        block,
                        mode.is_dry_run(),
                        new_tx_waiter,
                        preconfirmation_sender,
                    )
                    .await
            } else {
                ExecutionInstance::new(relayer, database, options)
                    .produce_without_commit(
                        block,
                        mode.is_dry_run(),
                        new_tx_waiter,
                        preconfirmation_sender,
                    )
                    .await
            }
        } else {
            let database = self.storage_view_provider.latest_view()?;
            if mode.record_storage_reads() {
                let database = StorageAccessRecorder::new(database);
                storage_rec = database.record.clone();
                ExecutionInstance::new(relayer, database, options)
                    .produce_without_commit(
                        block,
                        mode.is_dry_run(),
                        new_tx_waiter,
                        preconfirmation_sender,
                    )
                    .await
            } else {
                ExecutionInstance::new(relayer, database, options)
                    .produce_without_commit(
                        block,
                        mode.is_dry_run(),
                        new_tx_waiter,
                        preconfirmation_sender,
                    )
                    .await
            }
        };

        let mut g = storage_rec.lock();
        let storage_reads = core::mem::take(&mut *g);

        Ok(result?.map_result(|result| ProducedBlock {
            result,
            storage_reads,
        }))
    }

    fn native_validate_inner(
        &self,
        block: &Block,
        options: ExecutionOptions,
    ) -> ExecutorResult<Uncommitted<ValidationResult, Changes>> {
        let previous_block_height = block.header().height().pred();
        let relayer = self.relayer_view_provider.latest_view()?;

        if let Some(previous_block_height) = previous_block_height {
            let database = self.storage_view_provider.view_at(&previous_block_height)?;
            ExecutionInstance::new(relayer, database, options)
                .validate_without_commit(block)
        } else {
            let database = self.storage_view_provider.latest_view()?;
            ExecutionInstance::new(relayer, database, options)
                .validate_without_commit(block)
        }
    }

    /// Attempt to fetch and validate an uploaded WASM module.
    #[cfg(feature = "wasm-executor")]
    pub fn validate_uploaded_wasm(
        &self,
        wasm_root: &Bytes32,
    ) -> Result<(), UpgradableError> {
        self.get_module_by_root_and_validate(*wasm_root).map(|_| ())
    }

    /// Find an uploaded WASM blob by it's hash and validate it.
    /// This is a slow operation, and the cached result should be used if possible,
    /// for instancy by calling `get_module` below.
    #[cfg(feature = "wasm-executor")]
    // TODO: This methods may compile the WASM binary inside. It can take a lot of time,
    //  blocking the runtime. Instead, we should make this function async and compile
    //  the WASM in a separate thread.
    fn get_module_by_root_and_validate(
        &self,
        bytecode_root: Bytes32,
    ) -> Result<wasmtime::Module, UpgradableError> {
        let view = StructuredStorage::new(
            self.storage_view_provider
                .latest_view()
                .map_err(ExecutorError::from)?,
        );
        let uploaded_bytecode = view
            .storage::<UploadedBytecodes>()
            .get(&bytecode_root)
            .map_err(ExecutorError::from)?
            .ok_or(not_found!(UploadedBytecodes))
            .map_err(ExecutorError::from)?;

        let fuel_core_types::fuel_vm::UploadedBytecode::Completed(bytecode) =
            uploaded_bytecode.as_ref()
        else {
            return Err(UpgradableError::IncompleteUploadedBytecode(bytecode_root))
        };

        // If the bytecode is the same as the native executor, we don't need to compile it.
        if bytecode == crate::WASM_BYTECODE {
            let engine = private::default_engine();
            let module = private::COMPILED_UNDERLYING_EXECUTOR.get_or_init(|| {
                wasmtime::Module::new(engine, crate::WASM_BYTECODE)
                    .expect("Failed to validate the WASM bytecode")
            });
            return Ok(module.clone());
        }

        wasmtime::Module::new(&self.engine, bytecode)
            .map_err(|e| UpgradableError::InvalidWasm(e.to_string()))
    }

    /// Returns the compiled WASM module of the state transition function.
    ///
    /// Note: The method compiles the WASM module if it is not cached.
    ///     It is a long process to call this method, which can block the thread.
    #[cfg(feature = "wasm-executor")]
    fn get_module(
        &self,
        version: StateTransitionBytecodeVersion,
    ) -> ExecutorResult<wasmtime::Module> {
        let mut guard = self.cached_modules.lock();
        if let Some(module) = guard.get(&version) {
            return Ok(module.clone());
        }

        let view = StructuredStorage::new(
            self.storage_view_provider
                .latest_view()
                .map_err(ExecutorError::from)?,
        );
        let bytecode_root = *view
            .storage::<StateTransitionBytecodeVersions>()
            .get(&version)
            .map_err(ExecutorError::from)?
            .ok_or(not_found!(StateTransitionBytecodeVersions))
            .map_err(ExecutorError::from)?;

        let module = self
            .get_module_by_root_and_validate(bytecode_root)
            .map_err(|err| match err {
                UpgradableError::InvalidWasm(_) => ExecutorError::Other(format!("Attempting to load invalid wasm bytecode, version={version}. Current version is `{}`", Self::VERSION)),
                UpgradableError::IncompleteUploadedBytecode(_) => ExecutorError::Other(format!("Attempting to load wasm bytecode failed since the upload is incomplete, version={version}. Current version is `{}`", Self::VERSION)),
                UpgradableError::ExecutorError(err) => err
            })?;

        guard.insert(version, module.clone());
        Ok(module)
    }
}

#[allow(clippy::cast_possible_truncation)]
#[allow(unexpected_cfgs)] // for cfg(coverage)
#[cfg(test)]
mod test {
    use super::*;
    use fuel_core_storage::{
        kv_store::Value,
        structured_storage::test::InMemoryStorage,
        tables::ConsensusParametersVersions,
        transactional::WriteTransaction,
        Result as StorageResult,
        StorageAsMut,
    };
    use fuel_core_types::{
        blockchain::{
            block::{
                Block,
                PartialFuelBlock,
            },
            header::{
                ApplicationHeader,
                ConsensusHeader,
                PartialBlockHeader,
                StateTransitionBytecodeVersion,
            },
            primitives::{
                DaBlockHeight,
                Empty,
            },
        },
        fuel_tx::{
            AssetId,
            Bytes32,
            Transaction,
        },
        services::relayer::Event,
        tai64::Tai64,
    };
    use std::collections::{
        BTreeMap,
        BTreeSet,
    };

    #[derive(Clone, Debug)]
    struct Storage(InMemoryStorage<Column>);

    impl AtomicView for Storage {
        type LatestView = InMemoryStorage<Column>;

        fn latest_view(&self) -> StorageResult<Self::LatestView> {
            Ok(self.0.clone())
        }
    }

    impl HistoricalView for Storage {
        type Height = BlockHeight;
        type ViewAtHeight = Self::LatestView;

        fn latest_height(&self) -> Option<Self::Height> {
            None
        }

        fn view_at(&self, _: &Self::Height) -> StorageResult<Self::ViewAtHeight> {
            self.latest_view()
        }
    }

    impl KeyValueInspect for Storage {
        type Column = Column;

        fn get(&self, key: &[u8], column: Self::Column) -> StorageResult<Option<Value>> {
            self.0.get(key, column)
        }
    }

    impl Modifiable for Storage {
        fn commit_changes(&mut self, changes: Changes) -> StorageResult<()> {
            self.0.commit_changes(changes)
        }
    }

    #[derive(Copy, Clone)]
    struct DisabledRelayer;

    impl RelayerPort for DisabledRelayer {
        fn enabled(&self) -> bool {
            false
        }

        fn get_events(&self, _: &DaBlockHeight) -> anyhow::Result<Vec<Event>> {
            unimplemented!()
        }
    }

    impl AtomicView for DisabledRelayer {
        type LatestView = Self;

        fn latest_view(&self) -> StorageResult<Self::LatestView> {
            Ok(*self)
        }
    }

    // When this test fails, it is a sign that we need to increase the `Executor::VERSION`.
    #[test]
    fn version_check() {
        let crate_version = env!("CARGO_PKG_VERSION");
        let dashed_crate_version = crate_version.to_string().replace('.', "-");
        let mut seen_executor_versions =
            BTreeSet::<StateTransitionBytecodeVersion>::new();
        let seen_crate_versions = Executor::<Storage, DisabledRelayer>::CRATE_VERSIONS
            .iter()
            .map(|(crate_version, version)| {
                let executor_crate_version = crate_version.to_string().replace('-', ".");
                seen_executor_versions.insert(*version);
                (executor_crate_version, *version)
            })
            .collect::<BTreeMap<_, _>>();

        if let Some(expected_version) = seen_crate_versions.get(crate_version) {
            assert_eq!(
                *expected_version,
                Executor::<Storage, DisabledRelayer>::VERSION,
                "The version of the executor should be the same as in the `CRATE_VERSIONS` constant"
            );
        } else {
            let next_version = Executor::<Storage, DisabledRelayer>::VERSION + 1;
            panic!(
                "New release {crate_version} is not mentioned in the `CRATE_VERSIONS` constant.\
                Please add the new entry `(\"{dashed_crate_version}\", {next_version})` \
                to the `CRATE_VERSIONS` constant."
            );
        }

        let last_crate_version = seen_crate_versions.last_key_value().unwrap().0.clone();
        assert_eq!(
            crate_version, last_crate_version,
            "The last version in the `CRATE_VERSIONS` constant \
                   should be the same as the current crate version."
        );

        assert_eq!(
            seen_executor_versions.len(),
            seen_crate_versions.len(),
            "Each executor version should be unique"
        );

        assert_eq!(
            seen_executor_versions.len() as u32 - 1,
            Executor::<Storage, DisabledRelayer>::VERSION,
            "The version of the executor should monotonically grow without gaps"
        );

        assert_eq!(
            seen_executor_versions.last().cloned().unwrap(),
            Executor::<Storage, DisabledRelayer>::VERSION,
            "The latest version of the executor should be the last version in the `CRATE_VERSIONS` constant"
        );
    }

    const CONSENSUS_PARAMETERS_VERSION: u32 = 0;

    fn storage() -> Storage {
        let mut storage = Storage(InMemoryStorage::default());
        let mut tx = storage.write_transaction();
        tx.storage_as_mut::<ConsensusParametersVersions>()
            .insert(&CONSENSUS_PARAMETERS_VERSION, &Default::default())
            .unwrap();
        tx.commit().unwrap();

        storage
    }

    fn valid_block(
        state_transition_bytecode_version: StateTransitionBytecodeVersion,
    ) -> Block {
        PartialFuelBlock::new(
            PartialBlockHeader {
                application: ApplicationHeader {
                    da_height: Default::default(),
                    consensus_parameters_version: CONSENSUS_PARAMETERS_VERSION,
                    state_transition_bytecode_version,
                    generated: Empty,
                },
                consensus: ConsensusHeader {
                    prev_root: Default::default(),
                    height: Default::default(),
                    time: Tai64::now(),
                    generated: Empty,
                },
            },
            vec![Transaction::mint(
                Default::default(),
                Default::default(),
                Default::default(),
                Default::default(),
                AssetId::BASE,
                Default::default(),
            )
            .into()],
        )
        .generate(
            &[],
            Bytes32::zeroed(),
            #[cfg(feature = "fault-proving")]
            &Default::default(),
        )
        .unwrap()
    }

    #[cfg(not(feature = "wasm-executor"))]
    mod native {
        use super::*;
        use crate::executor::Executor;

        #[test]
        fn can_validate_block() {
            let storage = storage();
            let executor = Executor::native(storage, DisabledRelayer, Config::default());

            // Given
            let block = valid_block(Executor::<Storage, DisabledRelayer>::VERSION);

            // When
            let result = executor.validate(&block).map(|_| ());

            // Then
            assert_eq!(Ok(()), result);
        }

        #[test]
        fn validation_fails_because_of_versions_mismatch() {
            let storage = storage();
            let executor = Executor::native(storage, DisabledRelayer, Config::default());

            // Given
            let wrong_version = Executor::<Storage, DisabledRelayer>::VERSION + 1;
            let block = valid_block(wrong_version);

            // When
            let result = executor.validate(&block).map(|_| ());

            // Then
            result.expect_err("The validation should fail because of versions mismatch");
        }
    }

    #[cfg(feature = "wasm-executor")]
    #[allow(non_snake_case)]
    mod wasm {
        use super::*;
        use crate::{
            executor::Executor,
            WASM_BYTECODE,
        };
        use fuel_core_storage::tables::UploadedBytecodes;
        use fuel_core_types::fuel_vm::UploadedBytecode;

        #[test]
        fn can_validate_block__native_strategy() {
            let storage = storage();

            // Given
            let executor = Executor::native(storage, DisabledRelayer, Config::default());
            let block = valid_block(Executor::<Storage, DisabledRelayer>::VERSION);

            // When
            let result = executor.validate(&block).map(|_| ());

            // Then
            assert_eq!(Ok(()), result);
        }

        #[test]
        fn can_validate_block__wasm_strategy() {
            let storage = storage();

            // Given
            let executor = Executor::wasm(storage, DisabledRelayer, Config::default());
            let block = valid_block(Executor::<Storage, DisabledRelayer>::VERSION);

            // When
            let result = executor.validate(&block).map(|_| ());

            // Then
            assert_eq!(Ok(()), result);
        }

        #[test]
        fn validation_fails_because_of_versions_mismatch__native_strategy() {
            let storage = storage();

            // Given
            let executor = Executor::native(storage, DisabledRelayer, Config::default());
            let wrong_version = Executor::<Storage, DisabledRelayer>::VERSION + 1;
            let block = valid_block(wrong_version);

            // When
            let result = executor.validate(&block).map(|_| ());

            // Then
            result.expect_err("The validation should fail because of versions mismatch");
        }

        #[test]
        fn validation_fails_because_of_versions_mismatch__wasm_strategy() {
            let storage = storage();

            // Given
            let executor = Executor::wasm(storage, DisabledRelayer, Config::default());
            let wrong_version = Executor::<Storage, DisabledRelayer>::VERSION + 1;
            let block = valid_block(wrong_version);

            // When
            let result = executor.validate(&block).map(|_| ());

            // Then
            result.expect_err("The validation should fail because of versions mismatch");
        }

        fn storage_with_state_transition(
            next_version: StateTransitionBytecodeVersion,
        ) -> Storage {
            // Only FuelVM requires the Merkle root to match the corresponding bytecode
            // during uploading of it. The executor itself only uses a database to get the code,
            // and how bytecode appeared there is not the executor's responsibility.
            const BYTECODE_ROOT: Bytes32 = Bytes32::zeroed();

            let mut storage = storage();
            let mut tx = storage.write_transaction();
            tx.storage_as_mut::<StateTransitionBytecodeVersions>()
                .insert(&next_version, &BYTECODE_ROOT)
                .unwrap();
            tx.storage_as_mut::<UploadedBytecodes>()
                .insert(
                    &BYTECODE_ROOT,
                    &UploadedBytecode::Completed(WASM_BYTECODE.to_vec()),
                )
                .unwrap();
            tx.commit().unwrap();

            storage
        }

        #[test]
        fn can_validate_block_with_next_version__native_strategy() {
            // Given
            let next_version = Executor::<Storage, DisabledRelayer>::VERSION + 1;
            let storage = storage_with_state_transition(next_version);
            let executor = Executor::native(storage, DisabledRelayer, Config::default());
            let block = valid_block(next_version);

            // When
            let result = executor.validate(&block).map(|_| ());

            // Then
            assert_eq!(Ok(()), result);
        }

        #[test]
        fn can_validate_block_with_next_version__wasm_strategy() {
            // Given
            let next_version = Executor::<Storage, DisabledRelayer>::VERSION + 1;
            let storage = storage_with_state_transition(next_version);
            let executor = Executor::wasm(storage, DisabledRelayer, Config::default());
            let block = valid_block(next_version);

            // When
            let result = executor.validate(&block).map(|_| ());

            // Then
            assert_eq!(Ok(()), result);
        }

        // The test verifies that `Executor::get_module` method caches the compiled WASM module.
        // If it doesn't cache the modules, the test will fail with a timeout.
        #[test]
        #[cfg(not(coverage))] // Too slow for coverage
        fn reuse_cached_compiled_module__native_strategy() {
            // Given
            let next_version = Executor::<Storage, DisabledRelayer>::VERSION + 1;
            let storage = storage_with_state_transition(next_version);
            let executor = Executor::native(storage, DisabledRelayer, Config::default());
            let block = valid_block(next_version);

            executor.validate(&block).map(|_| ()).unwrap();
            // When
            for _ in 0..1000 {
                let start = std::time::Instant::now();
                let result = executor.validate(&block).map(|_| ());

                if start.elapsed().as_secs() > 1 {
                    panic!("The test is too slow");
                }
                // Then
                assert_eq!(Ok(()), result);
            }
        }

        // The test verifies that `Executor::get_module` method caches the compiled WASM module.
        // If it doesn't cache the modules, the test will fail with a timeout.
        #[test]
        #[cfg(not(coverage))] // Too slow for coverage
        fn reuse_cached_compiled_module__wasm_strategy() {
            // Given
            let next_version = Executor::<Storage, DisabledRelayer>::VERSION + 1;
            let storage = storage_with_state_transition(next_version);
            let executor = Executor::wasm(storage, DisabledRelayer, Config::default());
            let block = valid_block(next_version);

            executor.validate(&block).map(|_| ()).unwrap();
            // When
            for _ in 0..1000 {
                let start = std::time::Instant::now();
                let result = executor.validate(&block).map(|_| ());

                if start.elapsed().as_secs() > 1 {
                    panic!("The test is too slow");
                }
                // Then
                assert_eq!(Ok(()), result);
            }
        }
    }
}