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
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
// Copyright (c) 2022 MASSA LABS <info@massa.net>

//! Implementation of the interface between massa-execution-worker and massa-sc-runtime.
//! This allows the VM runtime to access the Massa execution context,
//! for example to interact with the ledger.
//! See the definition of Interface in the massa-sc-runtime crate for functional details.

use crate::context::ExecutionContext;
use anyhow::{anyhow, bail, Result};
use massa_async_pool::{AsyncMessage, AsyncMessageTrigger};
use massa_deferred_calls::DeferredCall;
use massa_execution_exports::ExecutionConfig;
use massa_execution_exports::ExecutionStackElement;
use massa_models::bytecode::Bytecode;
use massa_models::datastore::get_prefix_bounds;
use massa_models::deferred_calls::DeferredCallId;
use massa_models::{
    address::{Address, SCAddress, UserAddress},
    amount::Amount,
    slot::Slot,
    timeslots::get_block_slot_timestamp,
};
use massa_proto_rs::massa::model::v1::{
    AddressCategory, ComparisonResult, NativeAmount, NativeTime,
};
use massa_sc_runtime::RuntimeModule;
use massa_sc_runtime::{Interface, InterfaceClone};
use massa_signature::PublicKey;
use massa_signature::Signature;
use massa_time::MassaTime;
#[cfg(any(
    feature = "gas_calibration",
    feature = "benchmarking",
    feature = "test-exports",
    test
))]
use num::rational::Ratio;
use parking_lot::Mutex;
use rand::Rng;
use rand::RngCore;
use sha2::{Digest, Sha256};
use std::collections::BTreeSet;
use std::str::FromStr;
use std::sync::Arc;
use tracing::debug;
use tracing::warn;

#[cfg(any(
    feature = "gas_calibration",
    feature = "benchmarking",
    feature = "test-exports",
    test
))]
use massa_models::datastore::Datastore;

/// helper for locking the context mutex
macro_rules! context_guard {
    ($self:ident) => {
        $self.context.lock()
    };
}

/// an implementation of the Interface trait (see massa-sc-runtime crate)
#[derive(Clone)]
pub struct InterfaceImpl {
    /// execution configuration
    config: ExecutionConfig,
    /// thread-safe shared access to the execution context (see context.rs)
    context: Arc<Mutex<ExecutionContext>>,
}

impl InterfaceImpl {
    /// creates a new `InterfaceImpl`
    ///
    /// # Arguments
    /// * `config`: execution configuration
    /// * `context`: thread-safe shared access to the current execution context (see context.rs)
    pub fn new(config: ExecutionConfig, context: Arc<Mutex<ExecutionContext>>) -> InterfaceImpl {
        InterfaceImpl { config, context }
    }

    #[cfg(any(
        feature = "gas_calibration",
        feature = "benchmarking",
        feature = "test-exports",
        test
    ))]
    /// Used to create an default interface to run SC in a test environment
    pub fn new_default(
        sender_addr: Address,
        operation_datastore: Option<Datastore>,
        config: Option<ExecutionConfig>,
    ) -> InterfaceImpl {
        use massa_db_exports::{MassaDBConfig, MassaDBController};
        use massa_db_worker::MassaDB;
        use massa_final_state::test_exports::get_sample_state;
        use massa_ledger_exports::LedgerEntry;
        use massa_models::config::{MIP_STORE_STATS_BLOCK_CONSIDERED, THREAD_COUNT};
        use massa_models::types::SetUpdateOrDelete;
        use massa_module_cache::{config::ModuleCacheConfig, controller::ModuleCache};
        use massa_pos_exports::SelectorConfig;
        use massa_pos_worker::start_selector_worker;
        use massa_versioning::{
            mips::get_mip_list,
            versioning::{MipStatsConfig, MipStore},
        };
        use parking_lot::RwLock;
        use tempfile::TempDir;

        let config = config.unwrap_or_default();
        let mip_stats_config = MipStatsConfig {
            block_count_considered: MIP_STORE_STATS_BLOCK_CONSIDERED,
            warn_announced_version_ratio: Ratio::new_raw(30, 100),
        };
        let mip_store = MipStore::try_from(([], mip_stats_config)).unwrap();
        let (_, selector_controller) = start_selector_worker(SelectorConfig::default())
            .expect("could not start selector controller");
        let disk_ledger = TempDir::new().expect("cannot create temp directory");
        let db_config = MassaDBConfig {
            path: disk_ledger.path().to_path_buf(),
            max_history_length: 10,
            max_final_state_elements_size: 100_000,
            max_versioning_elements_size: 100_000,
            thread_count: THREAD_COUNT,
            max_ledger_backups: 10,
            enable_metrics: false,
        };

        let db = Arc::new(RwLock::new(
            Box::new(MassaDB::new(db_config)) as Box<(dyn MassaDBController + 'static)>
        ));
        let (final_state, _tempfile) =
            get_sample_state(config.last_start_period, selector_controller, mip_store, db).unwrap();
        let module_cache = Arc::new(RwLock::new(ModuleCache::new(ModuleCacheConfig {
            hd_cache_path: config.hd_cache_path.clone(),
            gas_costs: config.gas_costs.clone(),
            lru_cache_size: config.lru_cache_size,
            hd_cache_size: config.hd_cache_size,
            snip_amount: config.snip_amount,
            max_module_length: config.max_bytecode_size,
            condom_limits: config.condom_limits.clone(),
        })));

        // create an empty default store
        let mip_stats_config = MipStatsConfig {
            block_count_considered: MIP_STORE_STATS_BLOCK_CONSIDERED,
            warn_announced_version_ratio: Ratio::new_raw(30, 100),
        };
        let mip_store = MipStore::try_from((get_mip_list(), mip_stats_config))
            .expect("Cannot create an empty MIP store");

        let mut execution_context = ExecutionContext::new(
            config.clone(),
            final_state,
            Default::default(),
            module_cache,
            mip_store,
            massa_hash::Hash::zero(),
        );
        execution_context.stack = vec![ExecutionStackElement {
            address: sender_addr,
            coins: Amount::zero(),
            owned_addresses: vec![sender_addr],
            operation_datastore,
        }];
        execution_context.speculative_ledger.added_changes.0.insert(
            sender_addr,
            SetUpdateOrDelete::Set(LedgerEntry {
                balance: Amount::const_init(1_000_000_000, 0),
                ..Default::default()
            }),
        );
        let context = Arc::new(Mutex::new(execution_context));
        InterfaceImpl::new(config, context)
    }

    // Allow certain addresses to bypass:
    // - the event size limit
    // - the user event count per operation / asc / deferred_call
    fn bypass_event_limitation(&self, call_stack: Vec<Address>) -> bool {
        // NOTE: the router addresses are smart contract SC_1 that will call a smart contract SC_2,
        // and SC_2 will generate the event.
        // This is why we do not check against the last address in the call stack, but the one before (call_stack.len() - 2)
        // These addresses are respectively the the Mainnet and Buildnet routers for Dusa
        let allowed_router_addresses = [
            Address::from_str("AS12UMSUxgpRBB6ArZDJ19arHoxNkkpdfofQGekAiAJqsuE6PEFJy").unwrap(),
            Address::from_str("AS1XqtvX3rz2RWbnqLfaYVKEjM3VS5pny9yKDdXcmJ5C1vrcLEFd").unwrap(),
        ];
        call_stack.len() > 1 && allowed_router_addresses.contains(&call_stack[call_stack.len() - 2])
    }
}

impl InterfaceClone for InterfaceImpl {
    /// allows cloning a boxed `InterfaceImpl`
    fn clone_box(&self) -> Box<dyn Interface> {
        Box::new(self.clone())
    }
}

/// Helper function that creates an amount from a NativeAmount
fn amount_from_native_amount(amount: &NativeAmount) -> Result<Amount> {
    let amount = Amount::from_mantissa_scale(amount.mantissa, amount.scale)
        .map_err(|err| anyhow!(format!("{}", err)))?;

    Ok(amount)
}

/// Helper function that creates a NativeAmount from the amount internal representation
fn amount_to_native_amount(amount: &Amount) -> NativeAmount {
    let (mantissa, scale) = amount.to_mantissa_scale();
    NativeAmount { mantissa, scale }
}

/// Helper function that creates an MassaTime from a NativeTime
fn massa_time_from_native_time(time: &NativeTime) -> Result<MassaTime> {
    let time = MassaTime::from_millis(time.milliseconds);
    Ok(time)
}

/// Helper function that creates a NativeTime from the MassaTime internal representation
fn massa_time_to_native_time(time: &MassaTime) -> NativeTime {
    let milliseconds = time.as_millis();
    NativeTime { milliseconds }
}

/// Helper function to get the address from the option given as argument to some ABIs
/// Fallback to the current context address if not provided.
fn get_address_from_opt_or_context(
    context: &ExecutionContext,
    option_address_string: Option<String>,
) -> Result<Address> {
    match option_address_string {
        Some(address_string) => Address::from_str(&address_string).map_err(|e| e.into()),
        None => context.get_current_address().map_err(|e| e.into()),
    }
}

/// Implementation of the Interface trait providing functions for massa-sc-runtime to call
/// in order to interact with the execution context during bytecode execution.
/// See the massa-sc-runtime crate for a functional description of the trait and its methods.
/// Note that massa-sc-runtime uses basic types (`str` for addresses, `u64` for amounts...) for genericity.
impl Interface for InterfaceImpl {
    /// prints a message in the node logs at log level 3 (debug)
    fn print(&self, message: &str) -> Result<()> {
        if cfg!(test) {
            println!("SC print: {}", message);
        } else {
            debug!("SC print: {}", message);
        }
        Ok(())
    }

    fn get_interface_version(&self) -> Result<u32> {
        let context = context_guard!(self);
        Ok(context.execution_component_version)
    }

    fn increment_recursion_counter(&self) -> Result<()> {
        let execution_component_version = self.get_interface_version()?;

        let mut context = context_guard!(self);

        context.recursion_counter += 1;

        if execution_component_version > 0
            && context.recursion_counter > self.config.max_recursive_calls_depth
        {
            bail!("recursion depth limit reached");
        }

        Ok(())
    }

    fn decrement_recursion_counter(&self) -> Result<()> {
        let mut context = context_guard!(self);

        match context.recursion_counter.checked_sub(1) {
            Some(value) => context.recursion_counter = value,
            None => bail!("recursion counter underflow"),
        }

        Ok(())
    }

    /// Initialize the call when bytecode calls a function from another bytecode
    /// This function transfers the coins passed as parameter,
    /// prepares the current execution context by pushing a new element on the top of the call stack,
    /// and returns the target bytecode from the ledger.
    ///
    /// # Arguments
    /// * `address`: string representation of the target address on which the bytecode will be called
    /// * `raw_coins`: raw representation (without decimal factor) of the amount of coins to transfer from the caller address to the target address at the beginning of the call
    ///
    /// # Returns
    /// The target bytecode or an error
    fn init_call(&self, address: &str, raw_coins: u64) -> Result<Vec<u8>> {
        // get target address
        let to_address = Address::from_str(address)?;

        // write-lock context
        let mut context = context_guard!(self);

        // check that the target address is a SC address and if it exists
        context.check_target_sc_address(to_address)?;

        // get target bytecode
        let bytecode = match context.get_bytecode(&to_address) {
            Some(bytecode) => bytecode,
            None => bail!("bytecode not found for address {}", to_address),
        };

        // get caller address
        let from_address = match context.stack.last() {
            Some(addr) => addr.address,
            _ => bail!("failed to read call stack current address"),
        };

        // transfer coins from caller to target address
        let coins = Amount::from_raw(raw_coins);
        // note: rights are not checked here we checked that to_address is an SC address above
        // and we know that the sender is at the top of the call stack
        if let Err(err) = context.transfer_coins(Some(from_address), Some(to_address), coins, false)
        {
            bail!(
                "error transferring {} coins from {} to {}: {}",
                coins,
                from_address,
                to_address,
                err
            );
        }

        // push a new call stack element on top of the current call stack
        context.stack.push(ExecutionStackElement {
            address: to_address,
            coins,
            owned_addresses: vec![to_address],
            operation_datastore: None,
        });

        // return the target bytecode
        Ok(bytecode.0)
    }

    /// Called to finish the call process after a bytecode calls a function from another one.
    /// This function just pops away the top element of the call stack.
    fn finish_call(&self) -> Result<()> {
        let mut context = context_guard!(self);

        if context.stack.pop().is_none() {
            bail!("call stack out of bounds")
        }

        Ok(())
    }

    /// Get the module from cache if possible, compile it if not
    ///
    /// # Returns
    /// A `massa-sc-runtime` CL compiled module & the remaining gas after loading the module
    fn get_module(&self, bytecode: &[u8], gas_limit: u64) -> Result<RuntimeModule> {
        let context = context_guard!(self);
        let condom_limits = context.get_condom_limits();

        let ret = context
            .module_cache
            .write()
            .load_module(bytecode, gas_limit, condom_limits)?;

        Ok(ret)
    }

    /// Compile and return a temporary module
    ///
    /// # Returns
    /// A `massa-sc-runtime` SP compiled module & the remaining gas after loading the module
    fn get_tmp_module(&self, bytecode: &[u8], gas_limit: u64) -> Result<RuntimeModule> {
        let context = context_guard!(self);
        let condom_limits = context.get_condom_limits();

        let ret =
            context
                .module_cache
                .write()
                .load_tmp_module(bytecode, gas_limit, condom_limits)?;

        Ok(ret)
    }

    /// Gets the balance of the current address address (top of the stack).
    ///
    /// # Returns
    /// The raw representation (no decimal factor) of the balance of the address,
    /// or zero if the address is not found in the ledger.
    ///
    /// [DeprecatedByNewRuntime] Replaced by `get_balance_wasmv1`
    fn get_balance(&self) -> Result<u64> {
        let context = context_guard!(self);
        let address = context.get_current_address()?;
        Ok(context.get_balance(&address).unwrap_or_default().to_raw())
    }

    /// Gets the balance of arbitrary address passed as argument.
    ///
    /// # Arguments
    /// * address: string representation of the address for which to get the balance
    ///
    /// # Returns
    /// The raw representation (no decimal factor) of the balance of the address,
    /// or zero if the address is not found in the ledger.
    ///
    /// [DeprecatedByNewRuntime] Replaced by `get_balance_wasmv1`
    fn get_balance_for(&self, address: &str) -> Result<u64> {
        let address = massa_models::address::Address::from_str(address)?;
        Ok(context_guard!(self)
            .get_balance(&address)
            .unwrap_or_default()
            .to_raw())
    }

    /// Gets the balance of arbitrary address passed as argument, or the balance of the current address if no argument is passed.
    ///
    /// # Arguments
    /// * address: string representation of the address for which to get the balance
    ///
    /// # Returns
    /// The raw representation (no decimal factor) of the balance of the address,
    /// or zero if the address is not found in the ledger.
    fn get_balance_wasmv1(&self, address: Option<String>) -> Result<NativeAmount> {
        let context = context_guard!(self);
        let address = get_address_from_opt_or_context(&context, address)?;

        let amount = context.get_balance(&address).unwrap_or_default();
        let native_amount = amount_to_native_amount(&amount);

        Ok(native_amount)
    }

    /// Creates a new ledger entry with the initial bytecode given as argument.
    /// A new unique address is generated for that entry and returned.
    ///
    /// # Arguments
    /// * bytecode: the bytecode to set for the newly created address
    ///
    /// # Returns
    /// The string representation of the newly created address
    fn create_module(&self, bytecode: &[u8]) -> Result<String> {
        match context_guard!(self).create_new_sc_address(Bytecode(bytecode.to_vec())) {
            Ok(addr) => Ok(addr.to_string()),
            Err(err) => bail!("couldn't create new SC address: {}", err),
        }
    }

    /// Get the datastore keys (aka entries) for a given address
    ///
    /// # Returns
    /// A list of keys (keys are byte arrays)
    ///
    /// [DeprecatedByNewRuntime] Replaced by `get_keys_wasmv1`
    fn get_keys(&self, prefix_opt: Option<&[u8]>) -> Result<BTreeSet<Vec<u8>>> {
        let context = context_guard!(self);
        let addr = context.get_current_address()?;
        match context.get_keys(&addr, prefix_opt.unwrap_or_default()) {
            Some(value) => Ok(value),
            _ => bail!("data entry not found"),
        }
    }

    /// Get the datastore keys (aka entries) for a given address
    ///
    /// # Returns
    /// A list of keys (keys are byte arrays)
    ///
    /// [DeprecatedByNewRuntime] Replaced by `get_keys_wasmv1`
    fn get_keys_for(&self, address: &str, prefix_opt: Option<&[u8]>) -> Result<BTreeSet<Vec<u8>>> {
        let addr = &Address::from_str(address)?;
        let context = context_guard!(self);
        match context.get_keys(addr, prefix_opt.unwrap_or_default()) {
            Some(value) => Ok(value),
            _ => bail!("data entry not found"),
        }
    }

    /// Get the datastore keys (aka entries) for a given address, or the current address if none is provided
    ///
    /// # Returns
    /// A list of keys (keys are byte arrays)
    fn get_ds_keys_wasmv1(
        &self,
        prefix: &[u8],
        address: Option<String>,
    ) -> Result<BTreeSet<Vec<u8>>> {
        let context = context_guard!(self);
        let address = get_address_from_opt_or_context(&context, address)?;

        match context.get_keys(&address, prefix) {
            Some(value) => Ok(value),
            _ => bail!("data entry not found"),
        }
    }

    /// Gets a datastore value by key for the current address (top of the call stack).
    ///
    /// # Arguments
    /// * key: string key of the datastore entry to retrieve
    ///
    /// # Returns
    /// The datastore value matching the provided key, if found, otherwise an error.
    ///
    /// [DeprecatedByNewRuntime] Replaced by `raw_get_data_wasmv1`
    fn raw_get_data(&self, key: &[u8]) -> Result<Vec<u8>> {
        let context = context_guard!(self);
        let addr = context.get_current_address()?;
        match context.get_data_entry(&addr, key) {
            Some(value) => Ok(value),
            _ => bail!("data entry not found"),
        }
    }

    /// Gets a datastore value by key for a given address.
    ///
    /// # Arguments
    /// * address: string representation of the address
    /// * key: string key of the datastore entry to retrieve
    ///
    /// # Returns
    /// The datastore value matching the provided key, if found, otherwise an error.
    ///
    /// [DeprecatedByNewRuntime] Replaced by `raw_get_data_wasmv1`
    fn raw_get_data_for(&self, address: &str, key: &[u8]) -> Result<Vec<u8>> {
        let addr = &massa_models::address::Address::from_str(address)?;
        let context = context_guard!(self);
        match context.get_data_entry(addr, key) {
            Some(value) => Ok(value),
            _ => bail!("data entry not found"),
        }
    }

    /// Gets a datastore value by key for a given address, or the current address if none is provided.
    ///
    /// # Arguments
    /// * address: string representation of the address
    /// * key: string key of the datastore entry to retrieve
    ///
    /// # Returns
    /// The datastore value matching the provided key, if found, otherwise an error.
    fn get_ds_value_wasmv1(&self, key: &[u8], address: Option<String>) -> Result<Vec<u8>> {
        let context = context_guard!(self);
        let address = get_address_from_opt_or_context(&context, address)?;

        match context.get_data_entry(&address, key) {
            Some(value) => Ok(value),
            _ => bail!("data entry not found"),
        }
    }

    /// Sets a datastore entry for the current address (top of the call stack).
    /// Fails if the address does not exist.
    /// Creates the entry if does not exist.
    ///
    /// # Arguments
    /// * address: string representation of the address
    /// * key: string key of the datastore entry to set
    /// * value: new value to set
    ///
    /// [DeprecatedByNewRuntime] Replaced by `raw_set_data_wasmv1`
    fn raw_set_data(&self, key: &[u8], value: &[u8]) -> Result<()> {
        let mut context = context_guard!(self);
        let addr = context.get_current_address()?;
        context.set_data_entry(&addr, key.to_vec(), value.to_vec())?;
        Ok(())
    }

    /// Sets a datastore entry for a given address.
    /// Fails if the address does not exist.
    /// Creates the entry if it does not exist.
    ///
    /// # Arguments
    /// * address: string representation of the address
    /// * key: string key of the datastore entry to set
    /// * value: new value to set
    ///
    /// [DeprecatedByNewRuntime] Replaced by `raw_set_data_wasmv1`
    fn raw_set_data_for(&self, address: &str, key: &[u8], value: &[u8]) -> Result<()> {
        let addr = massa_models::address::Address::from_str(address)?;
        let mut context = context_guard!(self);
        context.set_data_entry(&addr, key.to_vec(), value.to_vec())?;
        Ok(())
    }

    fn set_ds_value_wasmv1(&self, key: &[u8], value: &[u8], address: Option<String>) -> Result<()> {
        let mut context = context_guard!(self);
        let address = get_address_from_opt_or_context(&context, address)?;

        context.set_data_entry(&address, key.to_vec(), value.to_vec())?;
        Ok(())
    }

    /// Appends data to a datastore entry for the current address (top of the call stack).
    /// Fails if the address or entry does not exist.
    ///
    /// # Arguments
    /// * key: string key of the datastore entry
    /// * value: value to append
    ///
    /// [DeprecatedByNewRuntime] Replaced by `raw_append_data_wasmv1`
    fn raw_append_data(&self, key: &[u8], value: &[u8]) -> Result<()> {
        let mut context = context_guard!(self);
        let addr = context.get_current_address()?;
        context.append_data_entry(&addr, key.to_vec(), value.to_vec())?;
        Ok(())
    }

    /// Appends a value to a datastore entry for a given address.
    /// Fails if the entry or address does not exist.
    ///
    /// # Arguments
    /// * address: string representation of the address
    /// * key: string key of the datastore entry
    /// * value: value to append
    ///
    /// [DeprecatedByNewRuntime] Replaced by `raw_append_data_wasmv1`
    fn raw_append_data_for(&self, address: &str, key: &[u8], value: &[u8]) -> Result<()> {
        let addr = massa_models::address::Address::from_str(address)?;
        context_guard!(self).append_data_entry(&addr, key.to_vec(), value.to_vec())?;
        Ok(())
    }

    /// Appends a value to a datastore entry for a given address, or the current address if none is provided
    /// Fails if the entry or address does not exist.
    ///
    /// # Arguments
    /// * address: string representation of the address
    /// * key: string key of the datastore entry
    /// * value: value to append
    fn append_ds_value_wasmv1(
        &self,
        key: &[u8],
        value: &[u8],
        address: Option<String>,
    ) -> Result<()> {
        let mut context = context_guard!(self);
        let address = get_address_from_opt_or_context(&context, address)?;

        context.append_data_entry(&address, key.to_vec(), value.to_vec())?;
        Ok(())
    }

    /// Deletes a datastore entry by key for the current address (top of the call stack).
    /// Fails if the address or entry does not exist.
    ///
    /// # Arguments
    /// * key: string key of the datastore entry to delete
    ///
    /// [DeprecatedByNewRuntime] Replaced by `raw_delete_data_wasmv1`
    fn raw_delete_data(&self, key: &[u8]) -> Result<()> {
        let mut context = context_guard!(self);
        let addr = context.get_current_address()?;
        context.delete_data_entry(&addr, key)?;
        Ok(())
    }

    /// Deletes a datastore entry by key for a given address.
    /// Fails if the address or entry does not exist.
    ///
    /// # Arguments
    /// * address: string representation of the address
    /// * key: string key of the datastore entry to delete
    ///
    /// [DeprecatedByNewRuntime] Replaced by `raw_delete_data_wasmv1`
    fn raw_delete_data_for(&self, address: &str, key: &[u8]) -> Result<()> {
        let addr = &massa_models::address::Address::from_str(address)?;
        context_guard!(self).delete_data_entry(addr, key)?;
        Ok(())
    }

    /// Deletes a datastore entry by key for a given address, or the current address if none is provided.
    /// Fails if the address or entry does not exist.
    ///
    /// # Arguments
    /// * address: string representation of the address
    /// * key: string key of the datastore entry to delete
    fn delete_ds_entry_wasmv1(&self, key: &[u8], address: Option<String>) -> Result<()> {
        let mut context = context_guard!(self);
        let address = get_address_from_opt_or_context(&context, address)?;

        context.delete_data_entry(&address, key)?;
        Ok(())
    }

    /// Checks if a datastore entry exists for the current address (top of the call stack).
    ///
    /// # Arguments
    /// * key: string key of the datastore entry to retrieve
    ///
    /// # Returns
    /// true if the address exists and has the entry matching the provided key in its datastore, otherwise false
    ///
    /// [DeprecatedByNewRuntime] Replaced by `has_data_wasmv1`
    fn has_data(&self, key: &[u8]) -> Result<bool> {
        let context = context_guard!(self);
        let addr = context.get_current_address()?;
        Ok(context.has_data_entry(&addr, key))
    }

    /// Checks if a datastore entry exists for a given address.
    ///
    /// # Arguments
    /// * address: string representation of the address
    /// * key: string key of the datastore entry to retrieve
    ///
    /// # Returns
    /// true if the address exists and has the entry matching the provided key in its datastore, otherwise false
    ///
    /// [DeprecatedByNewRuntime] Replaced by `has_data_wasmv1`
    fn has_data_for(&self, address: &str, key: &[u8]) -> Result<bool> {
        let addr = massa_models::address::Address::from_str(address)?;
        let context = context_guard!(self);
        Ok(context.has_data_entry(&addr, key))
    }

    /// Checks if a datastore entry exists for a given address, or the current address if none is provided.
    ///
    /// # Arguments
    /// * address: string representation of the address
    /// * key: string key of the datastore entry to retrieve
    ///
    /// # Returns
    /// true if the address exists and has the entry matching the provided key in its datastore, otherwise false
    fn ds_entry_exists_wasmv1(&self, key: &[u8], address: Option<String>) -> Result<bool> {
        let context = context_guard!(self);
        let address = get_address_from_opt_or_context(&context, address)?;

        Ok(context.has_data_entry(&address, key))
    }

    /// Check whether or not the caller has write access in the current context
    ///
    /// # Returns
    /// true if the caller has write access
    fn caller_has_write_access(&self) -> Result<bool> {
        let context = context_guard!(self);
        let mut call_stack_iter = context.stack.iter().rev();
        let caller_owned_addresses = if let Some(last) = call_stack_iter.next() {
            if let Some(prev_to_last) = call_stack_iter.next() {
                prev_to_last.owned_addresses.clone()
            } else {
                last.owned_addresses.clone()
            }
        } else {
            return Err(anyhow!("empty stack"));
        };
        let current_address = context.get_current_address()?;
        Ok(caller_owned_addresses.contains(&current_address))
    }

    /// Returns bytecode of the current address
    ///
    /// [DeprecatedByNewRuntime] Replaced by `raw_get_bytecode_wasmv1`
    fn raw_get_bytecode(&self) -> Result<Vec<u8>> {
        let context = context_guard!(self);
        let address = context.get_current_address()?;
        match context.get_bytecode(&address) {
            Some(bytecode) => Ok(bytecode.0),
            _ => bail!("bytecode not found"),
        }
    }

    /// Returns bytecode of the target address
    ///
    /// [DeprecatedByNewRuntime] Replaced by `raw_get_bytecode_wasmv1`
    fn raw_get_bytecode_for(&self, address: &str) -> Result<Vec<u8>> {
        let context = context_guard!(self);
        let address = Address::from_str(address)?;
        match context.get_bytecode(&address) {
            Some(bytecode) => Ok(bytecode.0),
            _ => bail!("bytecode not found"),
        }
    }

    /// Returns bytecode of the target address, or the current address if not provided
    fn get_bytecode_wasmv1(&self, address: Option<String>) -> Result<Vec<u8>> {
        let context = context_guard!(self);
        let address = get_address_from_opt_or_context(&context, address)?;

        match context.get_bytecode(&address) {
            Some(bytecode) => Ok(bytecode.0),
            _ => bail!("bytecode not found"),
        }
    }

    /// Get the operation datastore keys (aka entries).
    /// Note that the datastore is only accessible to the initial caller level.
    ///
    /// # Returns
    /// A list of keys (keys are byte arrays)
    ///
    /// [DeprecatedByNewRuntime] Replaced by `get_op_keys_wasmv1`
    fn get_op_keys(&self, prefix_opt: Option<&[u8]>) -> Result<Vec<Vec<u8>>> {
        let prefix: &[u8] = prefix_opt.unwrap_or_default();

        // compute prefix range
        let prefix_range = get_prefix_bounds(prefix);
        let range_ref = (prefix_range.0.as_ref(), prefix_range.1.as_ref());

        let context = context_guard!(self);
        let stack = context.stack.last().ok_or_else(|| anyhow!("No stack"))?;
        let datastore = stack
            .operation_datastore
            .as_ref()
            .ok_or_else(|| anyhow!("No datastore in stack"))?;
        let keys = datastore
            .range::<Vec<u8>, _>(range_ref)
            .map(|(k, _v)| k.clone())
            .collect();
        Ok(keys)
    }

    /// Get the operation datastore keys (aka entries).
    /// Note that the datastore is only accessible to the initial caller level.
    ///
    /// # Returns
    /// A list of keys (keys are byte arrays) that match the given prefix
    fn get_op_keys_wasmv1(&self, prefix: &[u8]) -> Result<Vec<Vec<u8>>> {
        let prefix_range = get_prefix_bounds(prefix);
        let range_ref = (prefix_range.0.as_ref(), prefix_range.1.as_ref());

        let context = context_guard!(self);
        let stack = context.stack.last().ok_or_else(|| anyhow!("No stack"))?;
        let datastore = stack
            .operation_datastore
            .as_ref()
            .ok_or_else(|| anyhow!("No datastore in stack"))?;
        let keys = datastore
            .range::<Vec<u8>, _>(range_ref)
            .map(|(k, _v)| k.clone())
            .collect();
        Ok(keys)
    }

    /// Checks if an operation datastore entry exists in the operation datastore.
    /// Note that the datastore is only accessible to the initial caller level.
    ///
    /// # Arguments
    /// * key: byte array key of the datastore entry to retrieve
    ///
    /// # Returns
    /// true if the entry is matching the provided key in its operation datastore, otherwise false
    fn op_entry_exists(&self, key: &[u8]) -> Result<bool> {
        let context = context_guard!(self);
        let stack = context.stack.last().ok_or_else(|| anyhow!("No stack"))?;
        let datastore = stack
            .operation_datastore
            .as_ref()
            .ok_or_else(|| anyhow!("No datastore in stack"))?;
        let has_key = datastore.contains_key(key);
        Ok(has_key)
    }

    /// Gets an operation datastore value by key.
    /// Note that the datastore is only accessible to the initial caller level.
    ///
    /// # Arguments
    /// * key: byte array key of the datastore entry to retrieve
    ///
    /// # Returns
    /// The operation datastore value matching the provided key, if found, otherwise an error.
    fn get_op_data(&self, key: &[u8]) -> Result<Vec<u8>> {
        let context = context_guard!(self);
        let stack = context.stack.last().ok_or_else(|| anyhow!("No stack"))?;
        let datastore = stack
            .operation_datastore
            .as_ref()
            .ok_or_else(|| anyhow!("No datastore in stack"))?;
        let data = datastore
            .get(key)
            .cloned()
            .ok_or_else(|| anyhow!("Unknown key: {:?}", key));
        data
    }

    /// Hashes arbitrary data
    ///
    /// # Arguments
    /// * data: data bytes to hash
    ///
    /// # Returns
    /// The hash in bytes format
    fn hash(&self, data: &[u8]) -> Result<[u8; 32]> {
        Ok(massa_hash::Hash::compute_from(data).into_bytes())
    }

    /// Converts a public key to an address
    ///
    /// # Arguments
    /// * `public_key`: string representation of the public key
    ///
    /// # Returns
    /// The string representation of the resulting address
    fn address_from_public_key(&self, public_key: &str) -> Result<String> {
        let public_key = massa_signature::PublicKey::from_str(public_key)?;
        let addr = massa_models::address::Address::from_public_key(&public_key);
        Ok(addr.to_string())
    }

    fn validate_address(&self, address: &str) -> Result<bool> {
        Ok(massa_models::address::Address::from_str(address).is_ok())
    }

    /// Verifies a signature
    ///
    /// # Arguments
    /// * data: the data bytes that were signed
    /// * signature: string representation of the signature
    /// * public key: string representation of the public key to check against
    ///
    /// # Returns
    /// true if the signature verification succeeded, false otherwise
    fn signature_verify(&self, data: &[u8], signature: &str, public_key: &str) -> Result<bool> {
        let signature = match massa_signature::Signature::from_bs58_check(signature) {
            Ok(sig) => sig,
            Err(_) => return Ok(false),
        };
        let public_key = match massa_signature::PublicKey::from_str(public_key) {
            Ok(pubk) => pubk,
            Err(_) => return Ok(false),
        };
        let h = massa_hash::Hash::compute_from(data);
        Ok(public_key.verify_signature(&h, &signature).is_ok())
    }

    /// Verify an EVM signature
    ///
    /// Information:
    /// * Expects a SECP256K1 signature in full ETH format.
    ///   Format: (r, s, v) v will be ignored
    ///   Length: 65 bytes
    /// * Expects a public key in raw secp256k1 format.
    ///   Length: 64 bytes
    fn evm_signature_verify(
        &self,
        message_: &[u8],
        signature_: &[u8],
        public_key_: &[u8],
    ) -> Result<bool> {
        let execution_component_version = self.get_interface_version()?;

        // check the signature length
        if signature_.len() != 65 {
            return Err(anyhow!("invalid signature length in evm_signature_verify"));
        }

        // parse the public key
        let public_key = match execution_component_version {
            0 => libsecp256k1::PublicKey::parse_slice(
                public_key_,
                Some(libsecp256k1::PublicKeyFormat::Raw),
            )?,
            _ => libsecp256k1::PublicKey::parse_slice(public_key_, None)?,
        };

        // build the message
        let prefix = format!("\x19Ethereum Signed Message:\n{}", message_.len());
        let to_hash = [prefix.as_bytes(), message_].concat();
        let full_hash = sha3::Keccak256::digest(to_hash);
        let message = libsecp256k1::Message::parse_slice(&full_hash)
            .expect("message could not be parsed from a hash slice");

        // parse the signature as being (r, s, v)
        // r is the R.x value of the signature's R point (32 bytes)
        // s is the signature proof for R.x (32 bytes)
        // v is a recovery parameter used to ease the signature verification (1 byte)
        // see test_evm_verify for an example of its usage
        let signature = libsecp256k1::Signature::parse_standard_slice(&signature_[..64])?;

        if execution_component_version != 0 {
            let recovery_id: u8 = libsecp256k1::RecoveryId::parse_rpc(signature_[64])?.into();
            // Note: parse_rpc returns p - 27 and allow for 27, 28, 29, 30
            //       restrict to only 27 & 28 (=> 0 & 1)
            if recovery_id != 0 && recovery_id != 1 {
                // Note:
                // The v value in an EVM signature serves as a recovery ID,
                // aiding in the recovery of the public key from the signature.
                // Typically, v should be either 27 or 28
                // (or sometimes 0 or 1, depending on the implementation).
                // Ensuring that v is within the expected range is crucial
                // for correctly recovering the public key.
                // the Ethereum yellow paper specifies only 27 and 28, requiring additional checks.
                return Err(anyhow!(
                    "invalid recovery id value (v = {recovery_id}) in evm_signature_verify"
                ));
            }

            // Note:
            // The s value in an EVM signature should be in the lower half of the elliptic curve
            // in order to prevent malleability attacks.
            // If s is in the high-order range, it can be converted to its low-order equivalent,
            // which should be enforced during signature verification.
            if signature.s.is_high() {
                return Err(anyhow!(
                    "High-Order s Value are prohibited in evm_get_pubkey_from_signature"
                ));
            }
        }

        // verify the signature
        Ok(libsecp256k1::verify(&message, &signature, &public_key))
    }

    /// Keccak256 hash function
    fn hash_keccak256(&self, bytes: &[u8]) -> Result<[u8; 32]> {
        Ok(sha3::Keccak256::digest(bytes).into())
    }

    /// Get an EVM address from a raw secp256k1 public key (64 bytes).
    /// Address is the last 20 bytes of the hash of the public key.
    fn evm_get_address_from_pubkey(&self, public_key_: &[u8]) -> Result<Vec<u8>> {
        let execution_component_version = self.get_interface_version()?;

        let hash = match execution_component_version {
            0 => {
                // parse the public key
                let public_key = libsecp256k1::PublicKey::parse_slice(
                    public_key_,
                    Some(libsecp256k1::PublicKeyFormat::Raw),
                )?;
                // compute the hash of the public key
                sha3::Keccak256::digest(public_key.serialize())
            }
            _ => {
                // parse the public key
                let public_key = libsecp256k1::PublicKey::parse_slice(public_key_, None)?;
                // compute the hash of the public key
                sha3::Keccak256::digest(&public_key.serialize()[1..])
            }
        };

        // ignore the first 12 bytes of the hash
        let address = hash[12..].to_vec();

        // return the address (last 20 bytes of the hash)
        Ok(address)
    }

    /// Get a raw secp256k1 public key from an EVM signature and the signed hash.
    fn evm_get_pubkey_from_signature(&self, hash_: &[u8], signature_: &[u8]) -> Result<Vec<u8>> {
        let execution_component_version = self.get_interface_version()?;

        // check the signature length
        if signature_.len() != 65 {
            return Err(anyhow!(
                "invalid signature length in evm_get_pubkey_from_signature"
            ));
        }

        match execution_component_version {
            0 => {
                // parse the message
                let message = libsecp256k1::Message::parse_slice(hash_).unwrap();

                // parse the signature as being (r, s, v) use only r and s
                let signature =
                    libsecp256k1::Signature::parse_standard_slice(&signature_[..64]).unwrap();

                // parse v as a recovery id
                let recovery_id = libsecp256k1::RecoveryId::parse_rpc(signature_[64]).unwrap();

                // recover the public key
                let recovered = libsecp256k1::recover(&message, &signature, &recovery_id).unwrap();

                // return its serialized value
                Ok(recovered.serialize().to_vec())
            }
            _ => {
                // parse the message
                let message = libsecp256k1::Message::parse_slice(hash_)?;

                // parse the signature as being (r, s, v) use only r and s
                let signature = libsecp256k1::Signature::parse_standard_slice(&signature_[..64])?;

                // Note:
                // See evm_signature_verify explanation
                if signature.s.is_high() {
                    return Err(anyhow!(
                        "High-Order s Value are prohibited in evm_get_pubkey_from_signature"
                    ));
                }

                // parse v as a recovery id
                let recovery_id = libsecp256k1::RecoveryId::parse_rpc(signature_[64])?;

                let recovery_id_: u8 = recovery_id.into();
                if recovery_id_ != 0 && recovery_id_ != 1 {
                    // Note:
                    // See evm_signature_verify explanation
                    return Err(anyhow!(
                        "invalid recovery id value (v = {recovery_id_}) in evm_get_pubkey_from_signature"
                    ));
                }

                // recover the public key
                let recovered = libsecp256k1::recover(&message, &signature, &recovery_id)?;

                // return its serialized value
                Ok(recovered.serialize().to_vec())
            }
        }
    }

    // Return true if the address is a User address, false if it is an SC address.
    fn is_address_eoa(&self, address_: &str) -> Result<bool> {
        let address = Address::from_str(address_)?;
        Ok(matches!(address, Address::User(..)))
    }

    /// Transfer coins from the current address (top of the call stack) towards a target address.
    ///
    /// # Arguments
    /// * `to_address`: string representation of the address to which the coins are sent
    /// * `raw_amount`: raw representation (no decimal factor) of the amount of coins to transfer
    ///
    /// [DeprecatedByNewRuntime] Replaced by `transfer_coins_wasmv1`
    fn transfer_coins(&self, to_address: &str, raw_amount: u64) -> Result<()> {
        let to_address = Address::from_str(to_address)?;
        let amount = Amount::from_raw(raw_amount);
        let mut context = context_guard!(self);
        let from_address = context.get_current_address()?;
        context.transfer_coins(Some(from_address), Some(to_address), amount, true)?;
        Ok(())
    }

    /// Transfer coins from a given address towards a target address.
    ///
    /// # Arguments
    /// * `from_address`: string representation of the address that is sending the coins
    /// * `to_address`: string representation of the address to which the coins are sent
    /// * `raw_amount`: raw representation (no decimal factor) of the amount of coins to transfer
    ///
    /// [DeprecatedByNewRuntime] Replaced by `transfer_coins_wasmv1`
    fn transfer_coins_for(
        &self,
        from_address: &str,
        to_address: &str,
        raw_amount: u64,
    ) -> Result<()> {
        let from_address = Address::from_str(from_address)?;
        let to_address = Address::from_str(to_address)?;
        let amount = Amount::from_raw(raw_amount);
        let mut context = context_guard!(self);
        context.transfer_coins(Some(from_address), Some(to_address), amount, true)?;
        Ok(())
    }

    /// Transfer coins from a given address (or the current address if not specified) towards a target address.
    ///
    /// # Arguments
    /// * `to_address`: string representation of the address to which the coins are sent
    /// * `raw_amount`: raw representation (no decimal factor) of the amount of coins to transfer
    /// * `from_address`: string representation of the address that is sending the coins
    fn transfer_coins_wasmv1(
        &self,
        to_address: String,
        raw_amount: NativeAmount,
        from_address: Option<String>,
    ) -> Result<()> {
        let to_address = Address::from_str(&to_address)?;
        let amount = amount_from_native_amount(&raw_amount)?;

        let mut context = context_guard!(self);
        let from_address = match from_address {
            Some(from_address) => Address::from_str(&from_address)?,
            None => context.get_current_address()?,
        };
        context.transfer_coins(Some(from_address), Some(to_address), amount, true)?;
        Ok(())
    }

    /// Returns the list of owned addresses (top of the call stack).
    /// Those addresses are the ones the current execution context has write access to,
    /// typically it includes the current address itself,
    /// but also the ones that were created previously by the current call to allow initializing them.
    ///
    /// # Returns
    /// A vector with the string representation of each owned address.
    /// Note that the ordering of this vector is deterministic and conserved.
    fn get_owned_addresses(&self) -> Result<Vec<String>> {
        Ok(context_guard!(self)
            .get_current_owned_addresses()?
            .into_iter()
            .map(|addr| addr.to_string())
            .collect())
    }

    /// Returns the addresses in the call stack, from the bottom to the top.
    ///
    /// # Returns
    /// A vector with the string representation of each call stack address.
    fn get_call_stack(&self) -> Result<Vec<String>> {
        Ok(context_guard!(self)
            .get_call_stack()
            .into_iter()
            .map(|addr| addr.to_string())
            .collect())
    }

    /// Gets the amount of coins that have been transferred at the beginning of the call.
    /// See the `init_call` method.
    ///
    /// # Returns
    /// The raw representation (no decimal factor) of the amount of coins
    ///
    /// [DeprecatedByNewRuntime] Replaced by `get_call_coins_wasmv1`
    fn get_call_coins(&self) -> Result<u64> {
        Ok(context_guard!(self).get_current_call_coins()?.to_raw())
    }

    /// Gets the amount of coins that have been transferred at the beginning of the call.
    /// See the `init_call` method.
    ///
    /// # Returns
    /// The amount of coins
    fn get_call_coins_wasmv1(&self) -> Result<NativeAmount> {
        let amount = context_guard!(self).get_current_call_coins()?;
        Ok(amount_to_native_amount(&amount))
    }

    /// Emits an execution event to be stored.
    ///
    /// # Arguments:
    /// data: the string data that is the payload of the event
    fn generate_event(&self, data: String) -> Result<()> {
        let execution_component_version = self.get_interface_version()?;
        let mut context = context_guard!(self);

        let bypass_event_limitation = self.bypass_event_limitation(context.get_call_stack());

        // Even if we bypass the event limitation, we still limit the event size to max_event_size_v0
        let max_event_size = match (execution_component_version, bypass_event_limitation) {
            (0, _) => self.config.max_event_size_v0,
            (_, true) => self.config.max_event_size_v0,
            (_, false) => self.config.max_event_size_v1,
        };

        if data.len() > max_event_size {
            bail!("Event data size is too large");
        };

        let event = context.event_create(data, false);

        // Do not increment the event count if we bypass the event limitation
        if !bypass_event_limitation {
            context.user_event_count_in_current_exec =
                context.user_event_count_in_current_exec.saturating_add(1);
        }

        if execution_component_version > 0 {
            let event_per_op = context.user_event_count_in_current_exec as usize;

            if event_per_op > self.config.max_event_per_operation {
                bail!("Too many event for this operation");
            }
        }
        context.event_emit(event);
        Ok(())
    }

    /// Emits an execution event to be stored.
    ///
    /// # Arguments:
    /// data: the bytes_array data that is the payload of the event
    fn generate_event_wasmv1(&self, data: Vec<u8>) -> Result<()> {
        let execution_component_version = self.get_interface_version()?;
        let mut context = context_guard!(self);

        let bypass_event_limitation = self.bypass_event_limitation(context.get_call_stack());

        // Even if we bypass the event limitation, we still limit the event size to max_event_size_v0
        let max_event_size = match (execution_component_version, bypass_event_limitation) {
            (0, _) => self.config.max_event_size_v0,
            (_, true) => self.config.max_event_size_v0,
            (_, false) => self.config.max_event_size_v1,
        };

        if data.len() > max_event_size {
            bail!("Event data size is too large");
        };

        let data_str = String::from_utf8(data.clone()).unwrap_or(format!("{:?}", data));
        let event = context.event_create(data_str, false);

        // Do not increment the event count if we bypass the event limitation
        if !bypass_event_limitation {
            context.user_event_count_in_current_exec =
                context.user_event_count_in_current_exec.saturating_add(1);
        }

        if execution_component_version > 0 {
            let event_per_op = context.user_event_count_in_current_exec as usize;

            if event_per_op > self.config.max_event_per_operation {
                bail!("Too many event for this operation");
            }
        }
        context.event_emit(event);

        Ok(())
    }

    /// Returns the current time (millisecond UNIX timestamp)
    /// Note that in order to ensure determinism, this is actually the time of the context slot.
    fn get_time(&self) -> Result<u64> {
        let slot = context_guard!(self).slot;
        let ts = get_block_slot_timestamp(
            self.config.thread_count,
            self.config.t0,
            self.config.genesis_timestamp,
            slot,
        )?;
        Ok(ts.as_millis())
    }

    /// Returns a pseudo-random deterministic `i64` number
    ///
    /// # Warning
    /// This random number generator is unsafe:
    /// it can be both predicted and manipulated before the execution
    ///
    /// [DeprecatedByNewRuntime] Replaced by `unsafe_random_wasmv1`
    fn unsafe_random(&self) -> Result<i64> {
        let distr = rand::distributions::Uniform::new_inclusive(i64::MIN, i64::MAX);
        Ok(context_guard!(self).unsafe_rng.sample(distr))
    }

    /// Returns a pseudo-random deterministic `f64` number
    ///
    /// # Warning
    /// This random number generator is unsafe:
    /// it can be both predicted and manipulated before the execution
    ///
    /// [DeprecatedByNewRuntime] Replaced by `unsafe_random_wasmv1`
    fn unsafe_random_f64(&self) -> Result<f64> {
        let distr = rand::distributions::Uniform::new(0f64, 1f64);
        Ok(context_guard!(self).unsafe_rng.sample(distr))
    }

    /// Returns a pseudo-random deterministic byte array, with the given number of bytes
    ///
    /// # Warning
    /// This random number generator is unsafe:
    /// it can be both predicted and manipulated before the execution
    fn unsafe_random_wasmv1(&self, num_bytes: u64) -> Result<Vec<u8>> {
        let mut arr = vec![0u8; num_bytes as usize];
        context_guard!(self).unsafe_rng.try_fill_bytes(&mut arr)?;
        Ok(arr)
    }

    /// Adds an asynchronous message to the context speculative asynchronous pool
    ///
    /// # Arguments
    /// * `target_address`: Destination address hash in format string
    /// * `target_function`: Name of the message handling function
    /// * `validity_start`: Tuple containing the period and thread of the validity start slot
    /// * `validity_end`: Tuple containing the period and thread of the validity end slot
    /// * `max_gas`: Maximum gas for the message execution
    /// * `fee`: Fee to pay
    /// * `raw_coins`: Coins given by the sender
    /// * `data`: Message data
    fn send_message(
        &self,
        target_address: &str,
        target_function: &str,
        validity_start: (u64, u8),
        validity_end: (u64, u8),
        max_gas: u64,
        raw_fee: u64,
        raw_coins: u64,
        data: &[u8],
        filter: Option<(&str, Option<&[u8]>)>,
    ) -> Result<()> {
        if validity_start.1 >= self.config.thread_count {
            bail!("validity start thread exceeds the configuration thread count")
        }
        if validity_end.1 >= self.config.thread_count {
            bail!("validity end thread exceeds the configuration thread count")
        }

        let target_addr = Address::from_str(target_address)?;

        // check that the target address is an SC address
        if !matches!(target_addr, Address::SC(..)) {
            bail!("target address is not a smart contract address")
        }

        // Length verifications
        if target_function.len() > self.config.max_function_length as usize {
            bail!("Function name is too large");
        }
        if data.len() > self.config.max_parameter_length as usize {
            bail!("Parameter size is too large");
        }

        let mut execution_context = context_guard!(self);
        let emission_slot = execution_context.slot;

        let execution_component_version = execution_context.execution_component_version;
        if execution_component_version > 0 {
            if max_gas < self.config.gas_costs.max_instance_cost {
                bail!("max gas is lower than the minimum instance cost")
            }
            if Slot::new(validity_end.0, validity_end.1)
                < Slot::new(validity_start.0, validity_start.1)
            {
                bail!("validity end is earlier than the validity start")
            }
            if Slot::new(validity_end.0, validity_end.1) < emission_slot {
                bail!("validity end is earlier than the current slot")
            }
        }

        let emission_index = execution_context.created_message_index;
        let sender = execution_context.get_current_address()?;
        let coins = Amount::from_raw(raw_coins);
        execution_context.transfer_coins(Some(sender), None, coins, true)?;
        let fee = Amount::from_raw(raw_fee);
        execution_context.transfer_coins(Some(sender), None, fee, true)?;
        execution_context.push_new_message(AsyncMessage::new(
            emission_slot,
            emission_index,
            sender,
            target_addr,
            target_function.to_string(),
            max_gas,
            fee,
            coins,
            Slot::new(validity_start.0, validity_start.1),
            Slot::new(validity_end.0, validity_end.1),
            data.to_vec(),
            filter
                .map(|(addr, key)| {
                    let datastore_key = key.map(|k| k.to_vec());
                    if let Some(ref k) = datastore_key {
                        if k.len() > self.config.max_datastore_key_length as usize {
                            bail!("datastore key is too long")
                        }
                    }
                    Ok::<AsyncMessageTrigger, _>(AsyncMessageTrigger {
                        address: Address::from_str(addr)?,
                        datastore_key,
                    })
                })
                .transpose()?,
            None,
        ));
        execution_context.created_message_index += 1;
        Ok(())
    }

    // Returns the operation id that originated the current execution if there is one
    fn get_origin_operation_id(&self) -> Result<Option<String>> {
        let operation_id = context_guard!(self)
            .origin_operation_id
            .map(|op_id| op_id.to_string());
        Ok(operation_id)
    }

    /// Returns the period of the current execution slot
    ///
    /// [DeprecatedByNewRuntime] Replaced by `get_current_slot`
    fn get_current_period(&self) -> Result<u64> {
        let slot = context_guard!(self).slot;
        Ok(slot.period)
    }

    /// Returns the thread of the current execution slot
    ///
    /// [DeprecatedByNewRuntime] Replaced by `get_current_slot`
    fn get_current_thread(&self) -> Result<u8> {
        let slot = context_guard!(self).slot;
        Ok(slot.thread)
    }

    /// Returns the current execution slot
    fn get_current_slot(&self) -> Result<massa_proto_rs::massa::model::v1::Slot> {
        let slot_models = context_guard!(self).slot;
        Ok(slot_models.into())
    }

    /// Sets the bytecode of the current address
    ///
    /// [DeprecatedByNewRuntime] Replaced by `raw_set_bytecode_wasmv1`
    fn raw_set_bytecode(&self, bytecode: &[u8]) -> Result<()> {
        let mut execution_context = context_guard!(self);
        let address = execution_context.get_current_address()?;
        match execution_context.set_bytecode(&address, Bytecode(bytecode.to_vec())) {
            Ok(()) => Ok(()),
            Err(err) => bail!("couldn't set address {} bytecode: {}", address, err),
        }
    }

    /// Sets the bytecode of an arbitrary address.
    /// Fails if the address does not exist, is an user address, or if the context doesn't have write access rights on it.
    ///
    /// [DeprecatedByNewRuntime] Replaced by `raw_set_bytecode_wasmv1`
    fn raw_set_bytecode_for(&self, address: &str, bytecode: &[u8]) -> Result<()> {
        let address: Address = massa_models::address::Address::from_str(address)?;
        let mut execution_context = context_guard!(self);
        match execution_context.set_bytecode(&address, Bytecode(bytecode.to_vec())) {
            Ok(()) => Ok(()),
            Err(err) => bail!("couldn't set address {} bytecode: {}", address, err),
        }
    }

    /// Sets the bytecode of an arbitrary address, or the current address if not provided.
    /// Fails if the address does not exist, is an user address, or if the context doesn't have write access rights on it.
    fn set_bytecode_wasmv1(&self, bytecode: &[u8], address: Option<String>) -> Result<()> {
        let mut context = context_guard!(self);
        let address = get_address_from_opt_or_context(&context, address)?;

        match context.set_bytecode(&address, Bytecode(bytecode.to_vec())) {
            Ok(()) => Ok(()),
            Err(err) => bail!("couldn't set address {} bytecode: {}", address, err),
        }
    }

    /// Hashes givens byte array with sha256
    ///
    /// # Arguments
    /// * bytes: byte array to hash
    ///
    /// # Returns
    /// The byte array of the resulting hash
    fn hash_sha256(&self, bytes: &[u8]) -> Result<[u8; 32]> {
        let mut hasher = Sha256::new();
        hasher.update(bytes);
        let hash = hasher.finalize().into();
        Ok(hash)
    }

    /// Hashes givens byte array with blake3
    ///
    /// # Arguments
    /// * bytes: byte array to hash
    ///
    /// # Returns
    /// The byte array of the resulting hash
    fn hash_blake3(&self, bytes: &[u8]) -> Result<[u8; 32]> {
        Ok(blake3::hash(bytes).into())
    }

    /// Get the number of fees needed to reserve space in the target slot
    ///
    /// # Arguments
    /// * target_slot: tuple containing the period and thread of the target slot
    /// * gas_limit: the gas limit for the call
    ///
    /// # Returns
    /// A tuple containing a boolean indicating if the call is possible and the amount of fees needed
    fn get_deferred_call_quote(
        &self,
        target_slot: (u64, u8),
        gas_limit: u64,
        params_size: u64,
    ) -> Result<(bool, u64)> {
        // write-lock context
        let context = context_guard!(self);
        let current_slot = context.slot;

        if target_slot.1 >= self.config.thread_count {
            bail!("target slot thread exceeds the configuration thread count")
        }

        let target_slot = Slot::new(target_slot.0, target_slot.1);

        let gas_request =
            gas_limit.saturating_add(self.config.deferred_calls_config.call_cst_gas_cost);

        match context.deferred_calls_compute_call_fee(
            target_slot,
            gas_request,
            current_slot,
            params_size,
        ) {
            Ok(fee) => Ok((true, fee.to_raw())),
            Err(_) => Ok((false, 0)),
        }
    }

    /// Register deferred call
    ///
    /// # Arguments
    /// * target_addr: string representation of the target address
    /// * target_func: string representation of the target function
    /// * target_slot: tuple containing the period and thread of the target slot
    /// * max_gas: the gas limit for the call
    /// * coins: the amount of coins to send
    /// * params: byte array of the parameters
    ///
    /// # Returns
    /// The id of the call
    fn deferred_call_register(
        &self,
        target_addr: &str,
        target_func: &str,
        target_slot: (u64, u8),
        max_gas: u64,
        params: &[u8],
        coins: u64,
    ) -> Result<String> {
        // This function spends coins + deferred_call_quote(target_slot, max_gas).unwrap() from the caller, fails if the balance is insufficient or if the quote would return None.

        if target_slot.1 >= self.config.thread_count {
            bail!("target slot thread exceeds the configuration thread count")
        }

        let target_addr = Address::from_str(target_addr)?;

        // check that the target address is an SC address
        if !matches!(target_addr, Address::SC(..)) {
            bail!("target address is not a smart contract address")
        }

        // Length verifications
        if target_func.len() > self.config.max_function_length as usize {
            bail!("Function name is too large");
        }
        if params.len() > self.config.max_parameter_length as usize {
            bail!("Parameter size is too large");
        }

        // check fee, slot, gas
        let (available, fee_raw) =
            self.get_deferred_call_quote(target_slot, max_gas, params.len() as u64)?;
        if !available {
            bail!("The Deferred call cannot be registered. Ensure that the target slot is not before/at the current slot nor too far in the future, and that it has at least max_gas available gas.");
        }
        let fee = Amount::from_raw(fee_raw);
        let coins = Amount::from_raw(coins);

        // write-lock context
        let mut context = context_guard!(self);

        // get caller address
        let sender_address = context.get_current_address()?;

        // make sender pay coins + fee
        // coins + cost for booking the deferred call
        context.transfer_coins(Some(sender_address), None, coins.saturating_add(fee), true)?;

        let call = DeferredCall::new(
            sender_address,
            Slot::new(target_slot.0, target_slot.1),
            target_addr,
            target_func.to_string(),
            params.to_vec(),
            coins,
            max_gas,
            fee,
            false,
        );

        let call_id = context.deferred_call_register(call)?;
        Ok(call_id.to_string())
    }

    /// Check if an deferred call exists
    ///
    /// # Arguments
    /// * id: the id of the call
    ///
    /// # Returns
    /// true if the call exists, false otherwise
    fn deferred_call_exists(&self, id: &str) -> Result<bool> {
        // write-lock context
        let context = context_guard!(self);

        let call_id = DeferredCallId::from_str(id)?;
        Ok(context.deferred_call_exists(&call_id))
    }

    /// Cancel a deferred call
    ///
    /// # Arguments
    /// * id: the id of the call
    fn deferred_call_cancel(&self, id: &str) -> Result<()> {
        // Reimburses coins to the sender but not the deferred call fee to avoid spam. Cancelled items are not removed from storage to avoid manipulation, just ignored when it is their turn to be executed.

        let mut context = context_guard!(self);

        // Can only be called by the creator of the deferred call.
        let caller = context.get_current_address()?;

        let call_id = DeferredCallId::from_str(id)?;

        context.deferred_call_cancel(&call_id, caller)?;
        Ok(())
    }

    #[allow(unused_variables)]
    fn init_call_wasmv1(&self, address: &str, raw_coins: NativeAmount) -> Result<Vec<u8>> {
        // get target address
        let to_address = Address::from_str(address)?;

        // check that the target address is an SC address
        if !matches!(to_address, Address::SC(..)) {
            bail!("called address {} is not an SC address", to_address);
        }

        // write-lock context
        let mut context = context_guard!(self);

        // get target bytecode
        let bytecode = match context.get_bytecode(&to_address) {
            Some(bytecode) => bytecode,
            None => bail!("bytecode not found for address {}", to_address),
        };

        // get caller address
        let from_address = match context.stack.last() {
            Some(addr) => addr.address,
            _ => bail!("failed to read call stack current address"),
        };

        // transfer coins from caller to target address
        let coins = amount_from_native_amount(&raw_coins)?;
        // note: rights are not checked here we checked that to_address is an SC address above
        // and we know that the sender is at the top of the call stack
        if let Err(err) = context.transfer_coins(Some(from_address), Some(to_address), coins, false)
        {
            bail!(
                "error transferring {} coins from {} to {}: {}",
                coins,
                from_address,
                to_address,
                err
            );
        }

        // push a new call stack element on top of the current call stack
        context.stack.push(ExecutionStackElement {
            address: to_address,
            coins,
            owned_addresses: vec![to_address],
            operation_datastore: None,
        });

        // return the target bytecode
        Ok(bytecode.0)
    }

    /// Returns a NativeAmount from a string
    fn native_amount_from_str_wasmv1(&self, amount: &str) -> Result<NativeAmount> {
        let amount = Amount::from_str(amount).map_err(|err| anyhow!(format!("{}", err)))?;
        Ok(amount_to_native_amount(&amount))
    }

    /// Returns a string from a NativeAmount
    fn native_amount_to_string_wasmv1(&self, amount: &NativeAmount) -> Result<String> {
        let amount = amount_from_native_amount(amount)
            .map_err(|err| anyhow!(format!("Couldn't convert native amount to Amount: {}", err)))?;
        Ok(amount.to_string())
    }

    /// Checks if the given native amount is valid
    fn check_native_amount_wasmv1(&self, amount: &NativeAmount) -> Result<bool> {
        Ok(amount_from_native_amount(amount).is_ok())
    }

    /// Adds two native amounts, saturating at the numeric bounds instead of overflowing.
    fn add_native_amount_wasmv1(
        &self,
        amount1: &NativeAmount,
        amount2: &NativeAmount,
    ) -> Result<NativeAmount> {
        let amount1 = amount_from_native_amount(amount1)?;
        let amount2 = amount_from_native_amount(amount2)?;
        let sum = amount1.saturating_add(amount2);
        Ok(amount_to_native_amount(&sum))
    }

    /// Subtracts two native amounts, saturating at the numeric bounds instead of overflowing.
    fn sub_native_amount_wasmv1(
        &self,
        amount1: &NativeAmount,
        amount2: &NativeAmount,
    ) -> Result<NativeAmount> {
        let amount1 = amount_from_native_amount(amount1)?;
        let amount2 = amount_from_native_amount(amount2)?;
        let sub = amount1.saturating_sub(amount2);
        Ok(amount_to_native_amount(&sub))
    }

    /// Multiplies a native amount by a factor, saturating at the numeric bounds instead of overflowing.
    fn scalar_mul_native_amount_wasmv1(
        &self,
        amount: &NativeAmount,
        factor: u64,
    ) -> Result<NativeAmount> {
        let amount = amount_from_native_amount(amount)?;
        let mul = amount.saturating_mul_u64(factor);
        Ok(amount_to_native_amount(&mul))
    }

    /// Divides a native amount by a divisor, return an error if the divisor is 0.
    fn scalar_div_rem_native_amount_wasmv1(
        &self,
        dividend: &NativeAmount,
        divisor: u64,
    ) -> Result<(NativeAmount, NativeAmount)> {
        let dividend = amount_from_native_amount(dividend)?;

        let quotient = dividend
            .checked_div_u64(divisor)
            .ok_or_else(|| anyhow!(format!("Couldn't div_rem native amount")))?;
        // we can unwrap, we
        let remainder = dividend
            .checked_rem_u64(divisor)
            .ok_or_else(|| anyhow!(format!("Couldn't checked_rem_u64 native amount")))?;

        Ok((
            amount_to_native_amount(&quotient),
            amount_to_native_amount(&remainder),
        ))
    }

    /// Divides a native amount by a divisor, return an error if the divisor is 0.
    fn div_rem_native_amount_wasmv1(
        &self,
        dividend: &NativeAmount,
        divisor: &NativeAmount,
    ) -> Result<(u64, NativeAmount)> {
        let dividend = amount_from_native_amount(dividend)?;
        let divisor = amount_from_native_amount(divisor)?;

        let quotient = dividend
            .checked_div(divisor)
            .ok_or_else(|| anyhow!(format!("Couldn't div_rem native amount")))?;

        let remainder = dividend
            .checked_rem(&divisor)
            .ok_or_else(|| anyhow!(format!("Couldn't checked_rem native amount")))?;
        let remainder = amount_to_native_amount(&remainder);

        Ok((quotient, remainder))
    }

    fn base58_check_to_bytes_wasmv1(&self, s: &str) -> Result<Vec<u8>> {
        bs58::decode(s)
            .with_check(None)
            .into_vec()
            .map_err(|err| anyhow!(format!("bs58 parsing error: {}", err)))
    }

    fn bytes_to_base58_check_wasmv1(&self, data: &[u8]) -> String {
        bs58::encode(data).with_check().into_string()
    }

    fn check_address_wasmv1(&self, to_check: &str) -> Result<bool> {
        Ok(Address::from_str(to_check).is_ok())
    }

    fn check_pubkey_wasmv1(&self, to_check: &str) -> Result<bool> {
        Ok(PublicKey::from_str(to_check).is_ok())
    }

    fn check_signature_wasmv1(&self, to_check: &str) -> Result<bool> {
        Ok(Signature::from_str(to_check).is_ok())
    }

    fn get_address_category_wasmv1(&self, to_check: &str) -> Result<AddressCategory> {
        let addr = Address::from_str(to_check)?;
        let execution_component_version = context_guard!(self).execution_component_version;

        // Fixed behavior for this ABI in https://github.com/massalabs/massa/pull/4728
        // We keep the previous (bugged) code if the execution component version is 0
        // to avoid a breaking change
        match (addr, execution_component_version) {
            (Address::User(_), 0) => Ok(AddressCategory::ScAddress),
            (Address::SC(_), 0) => Ok(AddressCategory::UserAddress),
            (Address::User(_), _) => Ok(AddressCategory::UserAddress),
            (Address::SC(_), _) => Ok(AddressCategory::ScAddress),
            #[allow(unreachable_patterns)]
            (_, _) => Ok(AddressCategory::Unspecified),
        }
    }

    fn get_address_version_wasmv1(&self, address: &str) -> Result<u64> {
        let address = Address::from_str(address)?;
        match address {
            Address::User(UserAddress::UserAddressV0(_)) => Ok(0),
            // Address::User(UserAddress::UserAddressV1(_)) => Ok(1),
            Address::SC(SCAddress::SCAddressV0(_)) => Ok(0),
            // Address::SC(SCAddress::SCAddressV1(_)) => Ok(1),
            #[allow(unreachable_patterns)]
            _ => bail!("Unknown address version"),
        }
    }

    fn get_pubkey_version_wasmv1(&self, pubkey: &str) -> Result<u64> {
        let pubkey = PublicKey::from_str(pubkey)?;
        match pubkey {
            PublicKey::PublicKeyV0(_) => Ok(0),
            #[allow(unreachable_patterns)]
            _ => bail!("Unknown pubkey version"),
        }
    }

    fn get_signature_version_wasmv1(&self, signature: &str) -> Result<u64> {
        let signature = Signature::from_str(signature)?;
        match signature {
            Signature::SignatureV0(_) => Ok(0),
            #[allow(unreachable_patterns)]
            _ => bail!("Unknown signature version"),
        }
    }

    fn checked_add_native_time_wasmv1(
        &self,
        time1: &NativeTime,
        time2: &NativeTime,
    ) -> Result<NativeTime> {
        let time1 = massa_time_from_native_time(time1)?;
        let time2 = massa_time_from_native_time(time2)?;
        let sum = time1.checked_add(time2)?;
        Ok(massa_time_to_native_time(&sum))
    }

    fn checked_sub_native_time_wasmv1(
        &self,
        time1: &NativeTime,
        time2: &NativeTime,
    ) -> Result<NativeTime> {
        let time1 = massa_time_from_native_time(time1)?;
        let time2 = massa_time_from_native_time(time2)?;
        let sub = time1.checked_sub(time2)?;
        Ok(massa_time_to_native_time(&sub))
    }

    fn checked_mul_native_time_wasmv1(&self, time: &NativeTime, factor: u64) -> Result<NativeTime> {
        let time1 = massa_time_from_native_time(time)?;
        let mul = time1.checked_mul(factor)?;
        Ok(massa_time_to_native_time(&mul))
    }

    fn checked_scalar_div_native_time_wasmv1(
        &self,
        dividend: &NativeTime,
        divisor: u64,
    ) -> Result<(NativeTime, NativeTime)> {
        let dividend = massa_time_from_native_time(dividend)?;

        let quotient = dividend
            .checked_div_u64(divisor)
            .or_else(|_| bail!(format!("Couldn't div_rem native time")))?;
        let remainder = dividend
            .checked_rem_u64(divisor)
            .or_else(|_| bail!(format!("Couldn't checked_rem_u64 native time")))?;

        Ok((
            massa_time_to_native_time(&quotient),
            massa_time_to_native_time(&remainder),
        ))
    }

    fn checked_div_native_time_wasmv1(
        &self,
        dividend: &NativeTime,
        divisor: &NativeTime,
    ) -> Result<(u64, NativeTime)> {
        let dividend = massa_time_from_native_time(dividend)?;
        let divisor = massa_time_from_native_time(divisor)?;

        let quotient = dividend
            .checked_div_time(divisor)
            .or_else(|_| bail!(format!("Couldn't div_rem native time")))?;

        let remainder = dividend
            .checked_rem_time(divisor)
            .or_else(|_| bail!(format!("Couldn't checked_rem native time")))?;
        let remainder = massa_time_to_native_time(&remainder);

        Ok((quotient, remainder))
    }

    fn compare_address_wasmv1(&self, left: &str, right: &str) -> Result<ComparisonResult> {
        let left = Address::from_str(left)?;
        let right = Address::from_str(right)?;

        let res = match left.cmp(&right) {
            std::cmp::Ordering::Less => ComparisonResult::Lower,
            std::cmp::Ordering::Equal => ComparisonResult::Equal,
            std::cmp::Ordering::Greater => ComparisonResult::Greater,
        };

        Ok(res)
    }

    fn compare_native_amount_wasmv1(
        &self,
        left: &NativeAmount,
        right: &NativeAmount,
    ) -> Result<ComparisonResult> {
        let left = amount_from_native_amount(left)?;
        let right = amount_from_native_amount(right)?;

        let res = match left.cmp(&right) {
            std::cmp::Ordering::Less => ComparisonResult::Lower,
            std::cmp::Ordering::Equal => ComparisonResult::Equal,
            std::cmp::Ordering::Greater => ComparisonResult::Greater,
        };

        Ok(res)
    }

    fn compare_native_time_wasmv1(
        &self,
        left: &NativeTime,
        right: &NativeTime,
    ) -> Result<ComparisonResult> {
        let left = massa_time_from_native_time(left)?;
        let right = massa_time_from_native_time(right)?;

        let res = match left.cmp(&right) {
            std::cmp::Ordering::Less => ComparisonResult::Lower,
            std::cmp::Ordering::Equal => ComparisonResult::Equal,
            std::cmp::Ordering::Greater => ComparisonResult::Greater,
        };

        Ok(res)
    }

    fn compare_pub_key_wasmv1(&self, left: &str, right: &str) -> Result<ComparisonResult> {
        let left = PublicKey::from_str(left)?;
        let right = PublicKey::from_str(right)?;

        let res = match left.cmp(&right) {
            std::cmp::Ordering::Less => ComparisonResult::Lower,
            std::cmp::Ordering::Equal => ComparisonResult::Equal,
            std::cmp::Ordering::Greater => ComparisonResult::Greater,
        };

        Ok(res)
    }

    fn chain_id(&self) -> Result<u64> {
        Ok(self.config.chain_id)
    }

    /// Try to get a write lock on the execution context then set the
    /// gas_used_until_the_last_subexecution field to the given `gas_remaining` value.
    ///
    /// If the context is locked, this function does nothing but log a warning.
    fn save_gas_remaining_before_subexecution(&self, gas_remaining: u64) {
        match self.context.try_lock() {
            Some(mut context) => {
                context.gas_remaining_before_subexecution = Some(gas_remaining);
            }
            None => {
                warn!("Context is locked, cannot save gas remaining before subexecution");
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use massa_models::address::Address;
    use massa_signature::KeyPair;

    // Tests the get_keys_wasmv1 interface method used by the updated get_keys abi.
    #[test]
    fn test_get_keys() {
        let sender_addr = Address::from_public_key(&KeyPair::generate(0).unwrap().get_public_key());
        let interface = InterfaceImpl::new_default(sender_addr, None, None);

        interface
            .set_ds_value_wasmv1(b"k1", b"v1", Some(sender_addr.to_string()))
            .unwrap();
        interface
            .set_ds_value_wasmv1(b"k2", b"v2", Some(sender_addr.to_string()))
            .unwrap();
        interface
            .set_ds_value_wasmv1(b"l3", b"v3", Some(sender_addr.to_string()))
            .unwrap();

        let keys = interface.get_ds_keys_wasmv1(b"k", None).unwrap();

        assert_eq!(keys.len(), 2);
        assert!(keys.contains(b"k1".as_slice()));
        assert!(keys.contains(b"k2".as_slice()));
    }

    // Tests the get_op_keys_wasmv1 interface method used by the updated get_op_keys abi.
    #[test]
    fn test_get_op_keys() {
        let sender_addr = Address::from_public_key(&KeyPair::generate(0).unwrap().get_public_key());

        let mut operation_datastore = Datastore::new();
        operation_datastore.insert(b"k1".to_vec(), b"v1".to_vec());
        operation_datastore.insert(b"k2".to_vec(), b"v2".to_vec());
        operation_datastore.insert(b"l3".to_vec(), b"v3".to_vec());

        let interface = InterfaceImpl::new_default(sender_addr, Some(operation_datastore), None);

        let op_keys = interface.get_op_keys_wasmv1(b"k").unwrap();

        assert_eq!(op_keys.len(), 2);
        assert!(op_keys.contains(&b"k1".to_vec()));
        assert!(op_keys.contains(&b"k2".to_vec()));
    }

    #[test]
    fn test_native_amount() {
        let sender_addr = Address::from_public_key(&KeyPair::generate(0).unwrap().get_public_key());
        let interface = InterfaceImpl::new_default(sender_addr, None, None);

        let amount1 = interface.native_amount_from_str_wasmv1("100").unwrap();
        let amount2 = interface.native_amount_from_str_wasmv1("100").unwrap();
        let amount3 = interface.native_amount_from_str_wasmv1("200").unwrap();

        let sum = interface
            .add_native_amount_wasmv1(&amount1, &amount2)
            .unwrap();

        assert_eq!(amount3, sum);
        println!(
            "sum: {}",
            interface.native_amount_to_string_wasmv1(&sum).unwrap()
        );
        assert_eq!(
            "200",
            interface.native_amount_to_string_wasmv1(&sum).unwrap()
        );

        let diff = interface.sub_native_amount_wasmv1(&sum, &amount2).unwrap();
        assert_eq!(amount1, diff);

        let amount4 = NativeAmount {
            mantissa: 1,
            scale: 9,
        };

        let is_valid = interface.check_native_amount_wasmv1(&amount4).unwrap();
        assert!(is_valid);

        let mul = interface
            .scalar_mul_native_amount_wasmv1(&amount1, 2)
            .unwrap();
        assert_eq!(mul, amount3);

        let (quotient, remainder) = interface
            .scalar_div_rem_native_amount_wasmv1(&amount1, 2)
            .unwrap();
        let quotient_res_50 = interface.native_amount_from_str_wasmv1("50").unwrap();
        let remainder_res_0 = interface.native_amount_from_str_wasmv1("0").unwrap();
        assert_eq!(quotient, quotient_res_50);
        assert_eq!(remainder, remainder_res_0);

        let (quotient, remainder) = interface
            .scalar_div_rem_native_amount_wasmv1(&amount1, 3)
            .unwrap();
        let verif_div = interface
            .scalar_mul_native_amount_wasmv1(&quotient, 3)
            .unwrap();
        let verif_dif = interface
            .add_native_amount_wasmv1(&verif_div, &remainder)
            .unwrap();
        assert_eq!(verif_dif, amount1);

        let amount5 = interface.native_amount_from_str_wasmv1("2").unwrap();
        let (quotient, remainder) = interface
            .div_rem_native_amount_wasmv1(&amount1, &amount5)
            .unwrap();
        assert_eq!(quotient, 50);
        assert_eq!(remainder, remainder_res_0);

        let amount6 = interface.native_amount_from_str_wasmv1("3").unwrap();
        let (quotient, remainder) = interface
            .div_rem_native_amount_wasmv1(&amount1, &amount6)
            .unwrap();
        let verif_div = interface
            .scalar_mul_native_amount_wasmv1(&amount6, quotient)
            .unwrap();
        let verif_dif = interface
            .add_native_amount_wasmv1(&verif_div, &remainder)
            .unwrap();
        assert_eq!(verif_dif, amount1);
    }

    #[test]
    fn test_base58_check_to_form() {
        let sender_addr = Address::from_public_key(&KeyPair::generate(0).unwrap().get_public_key());
        let interface = InterfaceImpl::new_default(sender_addr, None, None);

        let data = "helloworld";
        let encoded = interface.bytes_to_base58_check_wasmv1(data.as_bytes());
        let decoded = interface.base58_check_to_bytes_wasmv1(&encoded).unwrap();

        assert_eq!(data.as_bytes(), decoded);
    }
    #[test]
    fn test_comparison_function() {
        let sender_addr = Address::from_public_key(&KeyPair::generate(0).unwrap().get_public_key());
        let interface = InterfaceImpl::new_default(sender_addr, None, None);

        // address
        let addr1 =
            Address::from_public_key(&KeyPair::generate(0).unwrap().get_public_key()).to_string();
        let addr2 =
            Address::from_public_key(&KeyPair::generate(0).unwrap().get_public_key()).to_string();

        let cmp_res = interface.compare_address_wasmv1(&addr1, &addr1).unwrap();
        println!("compare_address_wasmv1(: {}", cmp_res.as_str_name());
        assert_eq!(
            cmp_res,
            ComparisonResult::Equal,
            "  > Error: compare_address_wasmv1((addr1, addr1) should return EQUAL"
        );

        let cmp_res1 = interface.compare_address_wasmv1(&addr1, &addr2).unwrap();
        println!(
            "compare_address_wasmv1((addr1, addr2): {}",
            cmp_res1.as_str_name()
        );

        let cmp_res2 = interface.compare_address_wasmv1(&addr2, &addr1).unwrap();
        println!(
            "compare_address_wasmv1((addr2, addr1): {}",
            cmp_res2.as_str_name()
        );

        if cmp_res1 == ComparisonResult::Lower {
            assert_eq!(
                cmp_res2,
                ComparisonResult::Greater,
                "  > Error: compare_address_wasmv1((addr2, addr1) should return GREATER"
            );
        } else if cmp_res1 == ComparisonResult::Greater {
            assert_eq!(
                cmp_res2,
                ComparisonResult::Lower,
                "  > Error: compare_address_wasmv1((addr2, addr1) should return LOWER"
            );
        } else {
            assert_eq!(
                cmp_res1, cmp_res2,
                "  > Error: compare_address_wasmv1((addr2, addr1) should return EQUAL"
            );
        }

        //amount
        let amount1 = interface.native_amount_from_str_wasmv1("1").unwrap();
        let amount2 = interface.native_amount_from_str_wasmv1("2").unwrap();
        println!("do some compare with amount1 = 1, amount2 = 2");

        let cmp_res = interface
            .compare_native_amount_wasmv1(&amount1, &amount1)
            .unwrap();
        println!(
            "compare_native_amount_wasmv1(amount1, amount1): {}",
            cmp_res.as_str_name()
        );
        assert_eq!(
            cmp_res,
            ComparisonResult::Equal,
            "  > Error: compare_native_amount_wasmv1(amount1, amount1) should return EQUAL"
        );

        let cmp_res = interface
            .compare_native_amount_wasmv1(&amount1, &amount2)
            .unwrap();
        println!(
            "compare_native_amount_wasmv1(amount1, amount2): {}",
            cmp_res.as_str_name()
        );
        assert_eq!(
            cmp_res,
            ComparisonResult::Lower,
            "  > Error: compare_native_amount_wasmv1(amount1, amount2) should return LOWER"
        );

        let cmp_res = interface
            .compare_native_amount_wasmv1(&amount2, &amount1)
            .unwrap();
        println!(
            "compare_native_amount_wasmv1(amount2, amount1): {}",
            cmp_res.as_str_name()
        );
        assert_eq!(
            cmp_res,
            ComparisonResult::Greater,
            "  > Error: compare_native_amount_wasmv1(amount2, amount1) should return GREATER"
        );

        //time
        let time1 = massa_time_to_native_time(&MassaTime::from_millis(1));
        let time2 = massa_time_to_native_time(&MassaTime::from_millis(2));
        println!(
            "do some compare with time1 = {}, time2 = {}",
            time1.milliseconds, time2.milliseconds
        );

        let cmp_res = interface
            .compare_native_time_wasmv1(&time1, &time1)
            .unwrap();
        println!(
            "compare_native_time_wasmv1(time1, time1): {}",
            cmp_res.as_str_name()
        );
        assert_eq!(
            cmp_res,
            ComparisonResult::Equal,
            "  > Error:compare_native_time_wasmv1(time1, time1) should return EQUAL"
        );

        let cmp_res = interface
            .compare_native_time_wasmv1(&time1, &time2)
            .unwrap();
        println!(
            "compare_native_time_wasmv1(time1, time2): {}",
            cmp_res.as_str_name()
        );
        assert_eq!(
            cmp_res,
            ComparisonResult::Lower,
            "  > Error: compare_native_time_wasmv1(time1, time2) should return LOWER"
        );

        let cmp_res = interface
            .compare_native_time_wasmv1(&time2, &time1)
            .unwrap();
        println!(
            "compare_native_time_wasmv1(time2, time1): {}",
            cmp_res.as_str_name()
        );
        assert_eq!(
            cmp_res,
            ComparisonResult::Greater,
            "  > Error: compare_native_time_wasmv1(time2, time1) should return GREATER"
        );

        //pub_key
        let pub_key1 = KeyPair::generate(0).unwrap().get_public_key().to_string();
        let pub_key2 = KeyPair::generate(0).unwrap().get_public_key().to_string();

        println!(
            "do some compare with pub_key1 = {}, pub_key2 = {}",
            pub_key1, pub_key2
        );

        let cmp_res = interface
            .compare_pub_key_wasmv1(&pub_key1, &pub_key1)
            .unwrap();
        println!(
            "compare_pub_key_wasmv1(pub_key1, pub_key1): {}",
            cmp_res.as_str_name()
        );
        assert_eq!(
            cmp_res,
            ComparisonResult::Equal,
            "  > Error: compare_pub_key_wasmv1(pub_key1, pub_key1) should return EQUAL"
        );
        let cmp_res1 = interface
            .compare_pub_key_wasmv1(&pub_key1, &pub_key2)
            .unwrap();
        println!(
            "compare_pub_key_wasmv1(pub_key1, pub_key2): {}",
            cmp_res1.as_str_name()
        );
        let cmp_res2 = interface
            .compare_pub_key_wasmv1(&pub_key2, &pub_key1)
            .unwrap();
        println!(
            "compare_pub_key_wasmv1(pub_key2, pub_key1): {}",
            cmp_res2.as_str_name()
        );
        if cmp_res1 == ComparisonResult::Lower {
            assert_eq!(
                cmp_res2,
                ComparisonResult::Greater,
                "  > Error: compare_pub_key_wasmv1((pub_key2, pub_key1) should return GREATER"
            );
        } else if cmp_res1 == ComparisonResult::Greater {
            assert_eq!(
                cmp_res2,
                ComparisonResult::Lower,
                "  > Error: compare_pub_key_wasmv1((pub_key2, pub_key1) should return LOWER"
            );
        } else {
            assert_eq!(
                cmp_res1, cmp_res2,
                "  > Error: compare_pub_key_wasmv1((pub_key2, pub_key1) should return EQUAL"
            );
        }
    }
}

#[test]
fn test_evm_verify() {
    use hex_literal::hex;

    // signature info
    let address_ = hex!("807a7bb5193edf9898b9092c1597bb966fe52514");
    let message_ = b"test";
    let signature_ = hex!("d0d05c35080635b5e865006c6c4f5b5d457ec342564d8fc67ce40edc264ccdab3f2f366b5bd1e38582538fed7fa6282148e86af97970a10cb3302896f5d68ef51b");
    let private_key_ = hex!("ed6602758bdd68dc9df67a6936ed69807a74b8cc89bdc18f3939149d02db17f3");

    // build original public key
    let private_key = libsecp256k1::SecretKey::parse_slice(&private_key_).unwrap();
    let public_key = libsecp256k1::PublicKey::from_secret_key(&private_key);

    // build the message
    let prefix = format!("\x19Ethereum Signed Message:\n{}", message_.len());
    let to_hash = [prefix.as_bytes(), message_].concat();
    let full_hash = sha3::Keccak256::digest(to_hash);
    let message = libsecp256k1::Message::parse_slice(&full_hash).unwrap();

    // parse the signature as being (r, s, v)
    // r is the R.x value of the signature's R point (32 bytes)
    // s is the signature proof for R.x (32 bytes)
    // v is a recovery parameter used to ease the signature verification (1 byte)
    let signature = libsecp256k1::Signature::parse_standard_slice(&signature_[..64]).unwrap();
    let recovery_id = libsecp256k1::RecoveryId::parse_rpc(signature_[64]).unwrap();

    // check 1
    // verify the signature
    assert!(libsecp256k1::verify(&message, &signature, &public_key));

    // check 2
    // recover the public key using v and match it with the derived one
    let recovered = libsecp256k1::recover(&message, &signature, &recovery_id).unwrap();
    assert_eq!(public_key, recovered);

    // check 3
    // sign the message and match it with the original signature
    let (second_signature, _) = libsecp256k1::sign(&message, &private_key);
    assert_eq!(signature, second_signature);

    // check 4
    // generate the address from the public key and match it with the original address
    // address is the last 20 bytes of the hash of the public key in raw format (64 bytes)
    let raw_public_key = public_key.serialize();
    let hash = sha3::Keccak256::digest(&raw_public_key[1..]).to_vec();
    let generated_address = &hash[12..];
    assert_eq!(generated_address, address_);
}