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
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This file is part of Frontier.
//
// Copyright (c) 2020-2022 Parity Technologies (UK) Ltd.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use std::{cmp::Ordering, collections::HashSet, num::NonZeroU32, str::FromStr, sync::Arc};

use futures::TryStreamExt;
use scale_codec::{Decode, Encode};
use sqlx::{
	query::Query,
	sqlite::{
		SqliteArguments, SqliteConnectOptions, SqlitePool, SqlitePoolOptions, SqliteQueryResult,
	},
	ConnectOptions, Error, Execute, QueryBuilder, Row, Sqlite,
};
// Substrate
use sc_client_api::backend::{Backend as BackendT, StateBackend, StorageProvider};
use sp_api::{ApiExt, ProvideRuntimeApi};
use sp_blockchain::HeaderBackend;
use sp_core::{H160, H256};
use sp_runtime::{
	generic::BlockId,
	traits::{BlakeTwo256, Block as BlockT, Header as HeaderT, UniqueSaturatedInto, Zero},
};
// Frontier
use fc_api::{FilteredLog, TransactionMetadata};
use fc_storage::OverrideHandle;
use fp_consensus::{FindLogError, Hashes, Log as ConsensusLog, PostLog, PreLog};
use fp_rpc::EthereumRuntimeRPCApi;
use fp_storage::{EthereumStorageSchema, PALLET_ETHEREUM_SCHEMA};

/// Maximum number to topics allowed to be filtered upon
const MAX_TOPIC_COUNT: u16 = 4;

/// Represents a log item.
#[derive(Debug, Eq, PartialEq)]
pub struct Log {
	pub address: Vec<u8>,
	pub topic_1: Option<Vec<u8>>,
	pub topic_2: Option<Vec<u8>>,
	pub topic_3: Option<Vec<u8>>,
	pub topic_4: Option<Vec<u8>>,
	pub log_index: i32,
	pub transaction_index: i32,
	pub substrate_block_hash: Vec<u8>,
}

/// Represents the block metadata.
#[derive(Eq, PartialEq)]
struct BlockMetadata {
	pub substrate_block_hash: H256,
	pub block_number: i32,
	pub post_hashes: Hashes,
	pub schema: EthereumStorageSchema,
	pub is_canon: i32,
}

/// Represents the Sqlite connection options that are
/// used to establish a database connection.
#[derive(Debug)]
pub struct SqliteBackendConfig<'a> {
	pub path: &'a str,
	pub create_if_missing: bool,
	pub thread_count: u32,
	pub cache_size: u64,
}

/// Represents the indexed status of a block and if it's canon or not.
#[derive(Debug, Default)]
pub struct BlockIndexedStatus {
	pub indexed: bool,
	pub canon: bool,
}

/// Represents the backend configurations.
#[derive(Debug)]
pub enum BackendConfig<'a> {
	Sqlite(SqliteBackendConfig<'a>),
}

#[derive(Clone)]
pub struct Backend<Block: BlockT> {
	/// The Sqlite connection.
	pool: SqlitePool,

	/// The additional overrides for the logs handler.
	overrides: Arc<OverrideHandle<Block>>,

	/// The number of allowed operations for the Sqlite filter call.
	/// A value of `0` disables the timeout.
	num_ops_timeout: i32,
}

impl<Block: BlockT> Backend<Block>
where
	Block: BlockT<Hash = H256>,
{
	/// Creates a new instance of the SQL backend.
	pub async fn new(
		config: BackendConfig<'_>,
		pool_size: u32,
		num_ops_timeout: Option<NonZeroU32>,
		overrides: Arc<OverrideHandle<Block>>,
	) -> Result<Self, Error> {
		let any_pool = SqlitePoolOptions::new()
			.max_connections(pool_size)
			.connect_lazy_with(Self::connect_options(&config)?.disable_statement_logging());
		let _ = Self::create_database_if_not_exists(&any_pool).await?;
		let _ = Self::create_indexes_if_not_exist(&any_pool).await?;
		Ok(Self {
			pool: any_pool,
			overrides,
			num_ops_timeout: num_ops_timeout
				.map(|n| n.get())
				.unwrap_or(0)
				.try_into()
				.unwrap_or(i32::MAX),
		})
	}

	fn connect_options(config: &BackendConfig) -> Result<SqliteConnectOptions, Error> {
		match config {
			BackendConfig::Sqlite(config) => {
				log::info!(target: "frontier-sql", "📑 Connection configuration: {config:?}");
				let config = sqlx::sqlite::SqliteConnectOptions::from_str(config.path)?
					.create_if_missing(config.create_if_missing)
					// https://www.sqlite.org/pragma.html#pragma_busy_timeout
					.busy_timeout(std::time::Duration::from_secs(8))
					// 200MB, https://www.sqlite.org/pragma.html#pragma_cache_size
					.pragma("cache_size", format!("-{}", config.cache_size))
					// https://www.sqlite.org/pragma.html#pragma_analysis_limit
					.pragma("analysis_limit", "1000")
					// https://www.sqlite.org/pragma.html#pragma_threads
					.pragma("threads", config.thread_count.to_string())
					// https://www.sqlite.org/pragma.html#pragma_threads
					.pragma("temp_store", "memory")
					// https://www.sqlite.org/wal.html
					.journal_mode(sqlx::sqlite::SqliteJournalMode::Wal)
					// https://www.sqlite.org/pragma.html#pragma_synchronous
					.synchronous(sqlx::sqlite::SqliteSynchronous::Normal);
				Ok(config)
			}
		}
	}

	/// Get the underlying Sqlite pool.
	pub fn pool(&self) -> &SqlitePool {
		&self.pool
	}

	/// Canonicalize the indexed blocks, marking/demarking them as canon based on the
	/// provided `retracted` and `enacted` values.
	pub async fn canonicalize(&self, retracted: &[H256], enacted: &[H256]) -> Result<(), Error> {
		let mut tx = self.pool().begin().await?;

		// Retracted
		let mut builder: QueryBuilder<Sqlite> =
			QueryBuilder::new("UPDATE blocks SET is_canon = 0 WHERE substrate_block_hash IN (");
		let mut retracted_hashes = builder.separated(", ");
		for hash in retracted.iter() {
			let hash = hash.as_bytes();
			retracted_hashes.push_bind(hash);
		}
		retracted_hashes.push_unseparated(")");
		let query = builder.build();
		query.execute(&mut *tx).await?;

		// Enacted
		let mut builder: QueryBuilder<Sqlite> =
			QueryBuilder::new("UPDATE blocks SET is_canon = 1 WHERE substrate_block_hash IN (");
		let mut enacted_hashes = builder.separated(", ");
		for hash in enacted.iter() {
			let hash = hash.as_bytes();
			enacted_hashes.push_bind(hash);
		}
		enacted_hashes.push_unseparated(")");
		let query = builder.build();
		query.execute(&mut *tx).await?;

		tx.commit().await
	}

	/// Index the block metadata for the genesis block.
	pub async fn insert_genesis_block_metadata<Client, BE>(
		&self,
		client: Arc<Client>,
	) -> Result<Option<H256>, Error>
	where
		Client: StorageProvider<Block, BE> + HeaderBackend<Block> + 'static,
		Client: ProvideRuntimeApi<Block>,
		Client::Api: EthereumRuntimeRPCApi<Block>,
		BE: BackendT<Block> + 'static,
		BE::State: StateBackend<BlakeTwo256>,
	{
		let id = BlockId::Number(Zero::zero());
		let substrate_genesis_hash = client
			.expect_block_hash_from_id(&id)
			.map_err(|_| Error::Protocol("Cannot resolve genesis hash".to_string()))?;
		let maybe_substrate_hash: Option<H256> = if let Ok(Some(_)) =
			client.header(substrate_genesis_hash)
		{
			let has_api = client
				.runtime_api()
				.has_api_with::<dyn EthereumRuntimeRPCApi<Block>, _>(
					substrate_genesis_hash,
					|version| version >= 1,
				)
				.expect("runtime api reachable");

			log::debug!(target: "frontier-sql", "Index genesis block, has_api={has_api}, hash={substrate_genesis_hash:?}");

			if has_api {
				// The chain has frontier support from genesis.
				// Read from the runtime and store the block metadata.
				let ethereum_block = client
					.runtime_api()
					.current_block(substrate_genesis_hash)
					.expect("runtime api reachable")
					.expect("ethereum genesis block");

				let schema =
					Self::onchain_storage_schema(client.as_ref(), substrate_genesis_hash).encode();
				let ethereum_block_hash = ethereum_block.header.hash().as_bytes().to_owned();
				let substrate_block_hash = substrate_genesis_hash.as_bytes();
				let block_number = 0i32;
				let is_canon = 1i32;

				let _ = sqlx::query(
					"INSERT OR IGNORE INTO blocks(
						ethereum_block_hash,
						substrate_block_hash,
						block_number,
						ethereum_storage_schema,
						is_canon)
					VALUES (?, ?, ?, ?, ?)",
				)
				.bind(ethereum_block_hash)
				.bind(substrate_block_hash)
				.bind(block_number)
				.bind(schema)
				.bind(is_canon)
				.execute(self.pool())
				.await?;
			}
			Some(substrate_genesis_hash)
		} else {
			None
		};
		Ok(maybe_substrate_hash)
	}

	fn insert_block_metadata_inner<Client, BE>(
		client: Arc<Client>,
		hash: H256,
		overrides: Arc<OverrideHandle<Block>>,
	) -> Result<BlockMetadata, Error>
	where
		Client: StorageProvider<Block, BE> + HeaderBackend<Block> + 'static,
		BE: BackendT<Block> + 'static,
		BE::State: StateBackend<BlakeTwo256>,
	{
		log::trace!(target: "frontier-sql", "🛠️  [Metadata] Retrieving digest data for block {hash:?}");
		if let Ok(Some(header)) = client.header(hash) {
			match fp_consensus::find_log(header.digest()) {
				Ok(log) => {
					let schema = Self::onchain_storage_schema(client.as_ref(), hash);
					let log_hashes = match log {
						ConsensusLog::Post(PostLog::Hashes(post_hashes)) => post_hashes,
						ConsensusLog::Post(PostLog::Block(block)) => Hashes::from_block(block),
						ConsensusLog::Post(PostLog::BlockHash(expect_eth_block_hash)) => {
							let ethereum_block = overrides
								.schemas
								.get(&schema)
								.unwrap_or(&overrides.fallback)
								.current_block(hash);
							match ethereum_block {
								Some(block) => {
									let got_eth_block_hash = block.header.hash();
									if got_eth_block_hash != expect_eth_block_hash {
										return Err(Error::Protocol(format!(
											"Ethereum block hash mismatch: \
											frontier consensus digest ({expect_eth_block_hash:?}), \
											db state ({got_eth_block_hash:?})"
										)));
									} else {
										Hashes::from_block(block)
									}
								}
								None => {
									return Err(Error::Protocol(format!(
										"Missing ethereum block for hash mismatch {expect_eth_block_hash:?}"
									)))
								}
							}
						}
						ConsensusLog::Pre(PreLog::Block(block)) => Hashes::from_block(block),
					};

					let header_number = *header.number();
					let block_number =
						UniqueSaturatedInto::<u32>::unique_saturated_into(header_number) as i32;
					let is_canon = match client.hash(header_number) {
						Ok(Some(inner_hash)) => (inner_hash == hash) as i32,
						Ok(None) => {
							log::debug!(target: "frontier-sql", "[Metadata] Missing header for block #{block_number} ({hash:?})");
							0
						}
						Err(err) => {
							log::debug!(
								target: "frontier-sql",
								"[Metadata] Failed to retrieve header for block #{block_number} ({hash:?}): {err:?}",
							);
							0
						}
					};

					log::trace!(
						target: "frontier-sql",
						"[Metadata] Prepared block metadata for #{block_number} ({hash:?}) canon={is_canon}",
					);
					Ok(BlockMetadata {
						substrate_block_hash: hash,
						block_number,
						post_hashes: log_hashes,
						schema,
						is_canon,
					})
				}
				Err(FindLogError::NotFound) => Err(Error::Protocol(format!(
					"[Metadata] No logs found for hash {hash:?}",
				))),
				Err(FindLogError::MultipleLogs) => Err(Error::Protocol(format!(
					"[Metadata] Multiple logs found for hash {hash:?}",
				))),
			}
		} else {
			Err(Error::Protocol(format!(
				"[Metadata] Failed retrieving header for hash {hash:?}"
			)))
		}
	}

	/// Insert the block metadata for the provided block hashes.
	pub async fn insert_block_metadata<Client, BE>(
		&self,
		client: Arc<Client>,
		hash: H256,
	) -> Result<(), Error>
	where
		Client: StorageProvider<Block, BE> + HeaderBackend<Block> + 'static,
		BE: BackendT<Block> + 'static,
		BE::State: StateBackend<BlakeTwo256>,
	{
		// Spawn a blocking task to get block metadata from substrate backend.
		let overrides = self.overrides.clone();
		let metadata = tokio::task::spawn_blocking(move || {
			Self::insert_block_metadata_inner(client.clone(), hash, overrides)
		})
		.await
		.map_err(|_| Error::Protocol("tokio blocking metadata task failed".to_string()))??;

		let mut tx = self.pool().begin().await?;

		log::debug!(
			target: "frontier-sql",
			"🛠️  [Metadata] Starting execution of statements on db transaction"
		);
		let post_hashes = metadata.post_hashes;
		let ethereum_block_hash = post_hashes.block_hash.as_bytes();
		let substrate_block_hash = metadata.substrate_block_hash.as_bytes();
		let schema = metadata.schema.encode();
		let block_number = metadata.block_number;
		let is_canon = metadata.is_canon;

		let _ = sqlx::query(
			"INSERT OR IGNORE INTO blocks(
					ethereum_block_hash,
					substrate_block_hash,
					block_number,
					ethereum_storage_schema,
					is_canon)
				VALUES (?, ?, ?, ?, ?)",
		)
		.bind(ethereum_block_hash)
		.bind(substrate_block_hash)
		.bind(block_number)
		.bind(schema)
		.bind(is_canon)
		.execute(&mut *tx)
		.await?;
		for (i, &transaction_hash) in post_hashes.transaction_hashes.iter().enumerate() {
			let ethereum_transaction_hash = transaction_hash.as_bytes();
			let ethereum_transaction_index = i as i32;
			log::trace!(
				target: "frontier-sql",
				"[Metadata] Inserting TX for block #{block_number} - {transaction_hash:?} index {ethereum_transaction_index}",
			);
			let _ = sqlx::query(
				"INSERT OR IGNORE INTO transactions(
						ethereum_transaction_hash,
						substrate_block_hash,
						ethereum_block_hash,
						ethereum_transaction_index)
					VALUES (?, ?, ?, ?)",
			)
			.bind(ethereum_transaction_hash)
			.bind(substrate_block_hash)
			.bind(ethereum_block_hash)
			.bind(ethereum_transaction_index)
			.execute(&mut *tx)
			.await?;
		}

		sqlx::query("INSERT INTO sync_status(substrate_block_hash) VALUES (?)")
			.bind(hash.as_bytes())
			.execute(&mut *tx)
			.await?;

		log::debug!(target: "frontier-sql", "[Metadata] Ready to commit");
		tx.commit().await
	}

	/// Index the logs for the newly indexed blocks upto a `max_pending_blocks` value.
	pub async fn index_block_logs<Client, BE>(&self, client: Arc<Client>, block_hash: Block::Hash)
	where
		Client: StorageProvider<Block, BE> + HeaderBackend<Block> + 'static,
		BE: BackendT<Block> + 'static,
		BE::State: StateBackend<BlakeTwo256>,
	{
		let pool = self.pool().clone();
		let overrides = self.overrides.clone();
		let _ = async {
			// The overarching db transaction for the task.
			// Due to the async nature of this task, the same work is likely to happen
			// more than once. For example when a new batch is scheduled when the previous one
			// didn't finished yet and the new batch happens to select the same substrate
			// block hashes for the update.
			// That is expected, we are exchanging extra work for *acid*ity.
			// There is no case of unique constrain violation or race condition as already
			// existing entries are ignored.
			let mut tx = pool.begin().await?;
			// Update statement returning the substrate block hashes for this batch.
			match sqlx::query(
				"UPDATE sync_status
			SET status = 1
			WHERE substrate_block_hash IN
				(SELECT substrate_block_hash
				FROM sync_status
				WHERE status = 0 AND substrate_block_hash = ?) RETURNING substrate_block_hash",
			)
			.bind(block_hash.as_bytes())
			.fetch_one(&mut *tx)
			.await
			{
				Ok(_) => {
					// Spawn a blocking task to get log data from substrate backend.
					let logs = tokio::task::spawn_blocking(move || {
						Self::get_logs(client.clone(), overrides, block_hash)
					})
					.await
					.map_err(|_| Error::Protocol("tokio blocking task failed".to_string()))?;

					for log in logs {
						let _ = sqlx::query(
							"INSERT OR IGNORE INTO logs(
						address,
						topic_1,
						topic_2,
						topic_3,
						topic_4,
						log_index,
						transaction_index,
						substrate_block_hash)
					VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
						)
						.bind(log.address)
						.bind(log.topic_1)
						.bind(log.topic_2)
						.bind(log.topic_3)
						.bind(log.topic_4)
						.bind(log.log_index)
						.bind(log.transaction_index)
						.bind(log.substrate_block_hash)
						.execute(&mut *tx)
						.await?;
					}
					Ok(tx.commit().await?)
				}
				Err(e) => Err(e),
			}
		}
		.await
		.map_err(|e| {
			log::error!(target: "frontier-sql", "{e}");
		});
		// https://www.sqlite.org/pragma.html#pragma_optimize
		let _ = sqlx::query("PRAGMA optimize").execute(&pool).await;
		log::debug!(target: "frontier-sql", "Batch committed");
	}

	fn get_logs<Client, BE>(
		client: Arc<Client>,
		overrides: Arc<OverrideHandle<Block>>,
		substrate_block_hash: H256,
	) -> Vec<Log>
	where
		Client: StorageProvider<Block, BE> + HeaderBackend<Block> + 'static,
		BE: BackendT<Block> + 'static,
		BE::State: StateBackend<BlakeTwo256>,
	{
		let mut logs: Vec<Log> = vec![];
		let mut transaction_count: usize = 0;
		let mut log_count: usize = 0;
		let schema = Self::onchain_storage_schema(client.as_ref(), substrate_block_hash);
		let handler = overrides
			.schemas
			.get(&schema)
			.unwrap_or(&overrides.fallback);

		let receipts = handler
			.current_receipts(substrate_block_hash)
			.unwrap_or_default();

		transaction_count += receipts.len();
		for (transaction_index, receipt) in receipts.iter().enumerate() {
			let receipt_logs = match receipt {
				ethereum::ReceiptV3::Legacy(d)
				| ethereum::ReceiptV3::EIP2930(d)
				| ethereum::ReceiptV3::EIP1559(d) => &d.logs,
			};
			let transaction_index = transaction_index as i32;
			log_count += receipt_logs.len();
			for (log_index, log) in receipt_logs.iter().enumerate() {
				#[allow(clippy::get_first)]
				logs.push(Log {
					address: log.address.as_bytes().to_owned(),
					topic_1: log.topics.get(0).map(|l| l.as_bytes().to_owned()),
					topic_2: log.topics.get(1).map(|l| l.as_bytes().to_owned()),
					topic_3: log.topics.get(2).map(|l| l.as_bytes().to_owned()),
					topic_4: log.topics.get(3).map(|l| l.as_bytes().to_owned()),
					log_index: log_index as i32,
					transaction_index,
					substrate_block_hash: substrate_block_hash.as_bytes().to_owned(),
				});
			}
		}
		log::debug!(
			target: "frontier-sql",
			"Ready to commit {log_count} logs from {transaction_count} transactions"
		);
		logs
	}

	fn onchain_storage_schema<Client, BE>(client: &Client, at: Block::Hash) -> EthereumStorageSchema
	where
		Client: StorageProvider<Block, BE> + HeaderBackend<Block> + 'static,
		BE: BackendT<Block> + 'static,
		BE::State: StateBackend<BlakeTwo256>,
	{
		match client.storage(at, &sp_storage::StorageKey(PALLET_ETHEREUM_SCHEMA.to_vec())) {
			Ok(Some(bytes)) => Decode::decode(&mut &bytes.0[..])
				.ok()
				.unwrap_or(EthereumStorageSchema::Undefined),
			_ => EthereumStorageSchema::Undefined,
		}
	}

	/// Retrieves the status if a block has been already indexed.
	pub async fn is_block_indexed(&self, block_hash: Block::Hash) -> bool {
		sqlx::query("SELECT substrate_block_hash FROM sync_status WHERE substrate_block_hash = ?")
			.bind(block_hash.as_bytes().to_owned())
			.fetch_optional(self.pool())
			.await
			.map(|r| r.is_some())
			.unwrap_or(false)
	}

	/// Retrieves the status if a block is indexed and if also marked as canon.
	pub async fn block_indexed_and_canon_status(
		&self,
		block_hash: Block::Hash,
	) -> BlockIndexedStatus {
		sqlx::query(
			"SELECT b.is_canon FROM sync_status AS s
			INNER JOIN blocks AS b
			ON s.substrate_block_hash = b.substrate_block_hash
			WHERE s.substrate_block_hash = ?",
		)
		.bind(block_hash.as_bytes().to_owned())
		.fetch_optional(self.pool())
		.await
		.map(|result| {
			result
				.map(|row| {
					let is_canon: i32 = row.get(0);
					BlockIndexedStatus {
						indexed: true,
						canon: is_canon != 0,
					}
				})
				.unwrap_or_default()
		})
		.unwrap_or_default()
	}

	/// Sets the provided block as canon.
	pub async fn set_block_as_canon(&self, block_hash: H256) -> Result<SqliteQueryResult, Error> {
		sqlx::query("UPDATE blocks SET is_canon = 1 WHERE substrate_block_hash = ?")
			.bind(block_hash.as_bytes())
			.execute(self.pool())
			.await
	}

	/// Retrieves the first missing canonical block number in decreasing order that hasn't been indexed yet.
	/// If no unindexed block exists or the table or the rows do not exist, then the function
	/// returns `None`.
	pub async fn get_first_missing_canon_block(&self) -> Option<u32> {
		match sqlx::query(
			"SELECT b1.block_number-1
			FROM blocks as b1
			WHERE b1.block_number > 0 AND b1.is_canon=1 AND NOT EXISTS (
				SELECT 1 FROM blocks AS b2
				WHERE b2.block_number = b1.block_number-1
				AND b1.is_canon=1
				AND b2.is_canon=1
			)
			ORDER BY block_number LIMIT 1",
		)
		.fetch_optional(self.pool())
		.await
		{
			Ok(result) => {
				if let Some(row) = result {
					let block_number: u32 = row.get(0);
					return Some(block_number);
				}
			}
			Err(err) => {
				log::debug!(target: "frontier-sql", "Failed retrieving missing block {err:?}");
			}
		}

		None
	}

	/// Retrieves the first pending canonical block hash in decreasing order that hasn't had
	// its logs indexed yet. If no unindexed block exists or the table or the rows do not exist,
	/// then the function returns `None`.
	pub async fn get_first_pending_canon_block(&self) -> Option<H256> {
		match sqlx::query(
			"SELECT s.substrate_block_hash FROM sync_status AS s
			INNER JOIN blocks as b
			ON s.substrate_block_hash = b.substrate_block_hash
			WHERE b.is_canon = 1 AND s.status = 0
			ORDER BY b.block_number LIMIT 1",
		)
		.fetch_optional(self.pool())
		.await
		{
			Ok(result) => {
				if let Some(row) = result {
					let block_hash_bytes: Vec<u8> = row.get(0);
					let block_hash = H256::from_slice(&block_hash_bytes[..]);
					return Some(block_hash);
				}
			}
			Err(err) => {
				log::debug!(target: "frontier-sql", "Failed retrieving missing block {err:?}");
			}
		}

		None
	}

	/// Retrieve the block hash for the last indexed canon block.
	pub async fn get_last_indexed_canon_block(&self) -> Result<H256, Error> {
		let row = sqlx::query(
			"SELECT b.substrate_block_hash FROM blocks AS b
			INNER JOIN sync_status AS s
			ON s.substrate_block_hash = b.substrate_block_hash
			WHERE b.is_canon=1 AND s.status = 1
			ORDER BY b.id DESC LIMIT 1",
		)
		.fetch_one(self.pool())
		.await?;
		Ok(H256::from_slice(
			&row.try_get::<Vec<u8>, _>(0).unwrap_or_default()[..],
		))
	}

	/// Create the Sqlite database if it does not already exist.
	async fn create_database_if_not_exists(pool: &SqlitePool) -> Result<SqliteQueryResult, Error> {
		sqlx::query(
			"BEGIN;
			CREATE TABLE IF NOT EXISTS logs (
				id INTEGER PRIMARY KEY,
				address BLOB NOT NULL,
				topic_1 BLOB,
				topic_2 BLOB,
				topic_3 BLOB,
				topic_4 BLOB,
				log_index INTEGER NOT NULL,
				transaction_index INTEGER NOT NULL,
				substrate_block_hash BLOB NOT NULL,
				UNIQUE (
					log_index,
					transaction_index,
					substrate_block_hash
				)
			);
			CREATE TABLE IF NOT EXISTS sync_status (
				id INTEGER PRIMARY KEY,
				substrate_block_hash BLOB NOT NULL,
				status INTEGER DEFAULT 0 NOT NULL,
				UNIQUE (
					substrate_block_hash
				)
			);
			CREATE TABLE IF NOT EXISTS blocks (
				id INTEGER PRIMARY KEY,
				block_number INTEGER NOT NULL,
				ethereum_block_hash BLOB NOT NULL,
				substrate_block_hash BLOB NOT NULL,
				ethereum_storage_schema BLOB NOT NULL,
				is_canon INTEGER NOT NULL,
				UNIQUE (
					ethereum_block_hash,
					substrate_block_hash
				)
			);
			CREATE TABLE IF NOT EXISTS transactions (
				id INTEGER PRIMARY KEY,
				ethereum_transaction_hash BLOB NOT NULL,
				substrate_block_hash BLOB NOT NULL,
				ethereum_block_hash BLOB NOT NULL,
				ethereum_transaction_index INTEGER NOT NULL,
				UNIQUE (
					ethereum_transaction_hash,
					substrate_block_hash
				)
			);
			COMMIT;",
		)
		.execute(pool)
		.await
	}

	/// Create the Sqlite database indices if it does not already exist.
	async fn create_indexes_if_not_exist(pool: &SqlitePool) -> Result<SqliteQueryResult, Error> {
		sqlx::query(
			"BEGIN;
			CREATE INDEX IF NOT EXISTS logs_main_idx ON logs (
				address,
				topic_1,
				topic_2,
				topic_3,
				topic_4
			);
			CREATE INDEX IF NOT EXISTS logs_substrate_index ON logs (
				substrate_block_hash
			);
			CREATE INDEX IF NOT EXISTS blocks_number_index ON blocks (
				block_number
			);
			CREATE INDEX IF NOT EXISTS blocks_substrate_index ON blocks (
				substrate_block_hash
			);
			CREATE INDEX IF NOT EXISTS eth_block_hash_idx ON blocks (
				ethereum_block_hash
			);
			CREATE INDEX IF NOT EXISTS eth_tx_hash_idx ON transactions (
				ethereum_transaction_hash
			);
			CREATE INDEX IF NOT EXISTS eth_tx_hash_2_idx ON transactions (
				ethereum_block_hash,
				ethereum_transaction_index
			);
			COMMIT;",
		)
		.execute(pool)
		.await
	}
}

#[async_trait::async_trait]
impl<Block: BlockT<Hash = H256>> fc_api::Backend<Block> for Backend<Block> {
	async fn block_hash(
		&self,
		ethereum_block_hash: &H256,
	) -> Result<Option<Vec<Block::Hash>>, String> {
		let ethereum_block_hash = ethereum_block_hash.as_bytes();
		let res =
			sqlx::query("SELECT substrate_block_hash FROM blocks WHERE ethereum_block_hash = ?")
				.bind(ethereum_block_hash)
				.fetch_all(&self.pool)
				.await
				.ok()
				.map(|rows| {
					rows.iter()
						.map(|row| {
							H256::from_slice(&row.try_get::<Vec<u8>, _>(0).unwrap_or_default()[..])
						})
						.collect()
				});
		Ok(res)
	}

	async fn transaction_metadata(
		&self,
		ethereum_transaction_hash: &H256,
	) -> Result<Vec<TransactionMetadata<Block>>, String> {
		let ethereum_transaction_hash = ethereum_transaction_hash.as_bytes();
		let out = sqlx::query(
			"SELECT
				substrate_block_hash, ethereum_block_hash, ethereum_transaction_index
			FROM transactions WHERE ethereum_transaction_hash = ?",
		)
		.bind(ethereum_transaction_hash)
		.fetch_all(&self.pool)
		.await
		.unwrap_or_default()
		.iter()
		.map(|row| {
			let substrate_block_hash =
				H256::from_slice(&row.try_get::<Vec<u8>, _>(0).unwrap_or_default()[..]);
			let ethereum_block_hash =
				H256::from_slice(&row.try_get::<Vec<u8>, _>(1).unwrap_or_default()[..]);
			let ethereum_transaction_index = row.try_get::<i32, _>(2).unwrap_or_default() as u32;
			TransactionMetadata {
				substrate_block_hash,
				ethereum_block_hash,
				ethereum_index: ethereum_transaction_index,
			}
		})
		.collect();

		Ok(out)
	}

	fn log_indexer(&self) -> &dyn fc_api::LogIndexerBackend<Block> {
		self
	}
}

#[async_trait::async_trait]
impl<Block: BlockT<Hash = H256>> fc_api::LogIndexerBackend<Block> for Backend<Block> {
	fn is_indexed(&self) -> bool {
		true
	}

	async fn filter_logs(
		&self,
		from_block: u64,
		to_block: u64,
		addresses: Vec<H160>,
		topics: Vec<Vec<Option<H256>>>,
	) -> Result<Vec<FilteredLog<Block>>, String> {
		let mut unique_topics: [HashSet<H256>; 4] = [
			HashSet::new(),
			HashSet::new(),
			HashSet::new(),
			HashSet::new(),
		];
		for topic_combination in topics.into_iter() {
			for (topic_index, topic) in topic_combination.into_iter().enumerate() {
				if topic_index == MAX_TOPIC_COUNT as usize {
					return Err("Invalid topic input. Maximum length is 4.".to_string());
				}

				if let Some(topic) = topic {
					unique_topics[topic_index].insert(topic);
				}
			}
		}

		let log_key = format!("{from_block}-{to_block}-{addresses:?}-{unique_topics:?}");
		let mut qb = QueryBuilder::new("");
		let query = build_query(&mut qb, from_block, to_block, addresses, unique_topics);
		let sql = query.sql();

		let mut conn = self
			.pool()
			.acquire()
			.await
			.map_err(|err| format!("failed acquiring sqlite connection: {}", err))?;
		let log_key2 = log_key.clone();
		conn.lock_handle()
			.await
			.map_err(|err| format!("{:?}", err))?
			.set_progress_handler(self.num_ops_timeout, move || {
				log::debug!(target: "frontier-sql", "Sqlite progress_handler triggered for {log_key2}");
				false
			});
		log::debug!(target: "frontier-sql", "Query: {sql:?} - {log_key}");

		let mut out: Vec<FilteredLog<Block>> = vec![];
		let mut rows = query.fetch(&mut *conn);
		let maybe_err = loop {
			match rows.try_next().await {
				Ok(Some(row)) => {
					// Substrate block hash
					let substrate_block_hash =
						H256::from_slice(&row.try_get::<Vec<u8>, _>(0).unwrap_or_default()[..]);
					// Ethereum block hash
					let ethereum_block_hash =
						H256::from_slice(&row.try_get::<Vec<u8>, _>(1).unwrap_or_default()[..]);
					// Block number
					let block_number = row.try_get::<i32, _>(2).unwrap_or_default() as u32;
					// Ethereum storage schema
					let ethereum_storage_schema: EthereumStorageSchema =
						Decode::decode(&mut &row.try_get::<Vec<u8>, _>(3).unwrap_or_default()[..])
							.map_err(|_| {
								"Cannot decode EthereumStorageSchema for block".to_string()
							})?;
					// Transaction index
					let transaction_index = row.try_get::<i32, _>(4).unwrap_or_default() as u32;
					// Log index
					let log_index = row.try_get::<i32, _>(5).unwrap_or_default() as u32;
					out.push(FilteredLog {
						substrate_block_hash,
						ethereum_block_hash,
						block_number,
						ethereum_storage_schema,
						transaction_index,
						log_index,
					});
				}
				Ok(None) => break None, // no more rows
				Err(err) => break Some(err),
			};
		};
		drop(rows);
		conn.lock_handle()
			.await
			.map_err(|err| format!("{:?}", err))?
			.remove_progress_handler();

		if let Some(err) = maybe_err {
			log::error!(target: "frontier-sql", "Failed to query sql db: {err:?} - {log_key}");
			return Err("Failed to query sql db with statement".to_string());
		}

		log::info!(target: "frontier-sql", "FILTER remove handler - {log_key}");
		Ok(out)
	}
}

/// Build a SQL query to retrieve a list of logs given certain constraints.
fn build_query<'a>(
	qb: &'a mut QueryBuilder<Sqlite>,
	from_block: u64,
	to_block: u64,
	addresses: Vec<H160>,
	topics: [HashSet<H256>; 4],
) -> Query<'a, Sqlite, SqliteArguments<'a>> {
	qb.push(
		"
SELECT
	l.substrate_block_hash,
	b.ethereum_block_hash,
	b.block_number,
	b.ethereum_storage_schema,
	l.transaction_index,
	l.log_index
FROM logs AS l
INNER JOIN blocks AS b
ON (b.block_number BETWEEN ",
	);
	qb.separated(" AND ")
		.push_bind(from_block as i64)
		.push_bind(to_block as i64)
		.push_unseparated(")");
	qb.push(" AND b.substrate_block_hash = l.substrate_block_hash")
		.push(" AND b.is_canon = 1")
		.push("\nWHERE 1");

	if !addresses.is_empty() {
		qb.push(" AND l.address IN (");
		let mut qb_addr = qb.separated(", ");
		addresses.iter().for_each(|addr| {
			qb_addr.push_bind(addr.as_bytes().to_owned());
		});
		qb_addr.push_unseparated(")");
	}

	for (i, topic_options) in topics.iter().enumerate() {
		match topic_options.len().cmp(&1) {
			Ordering::Greater => {
				qb.push(format!(" AND l.topic_{} IN (", i + 1));
				let mut qb_topic = qb.separated(", ");
				topic_options.iter().for_each(|t| {
					qb_topic.push_bind(t.as_bytes().to_owned());
				});
				qb_topic.push_unseparated(")");
			}
			Ordering::Equal => {
				qb.push(format!(" AND l.topic_{} = ", i + 1)).push_bind(
					topic_options
						.iter()
						.next()
						.expect("length is 1, must exist; qed")
						.as_bytes()
						.to_owned(),
				);
			}
			Ordering::Less => {}
		}
	}

	qb.push(
		"
ORDER BY b.block_number ASC, l.transaction_index ASC, l.log_index ASC
LIMIT 10001",
	);

	qb.build()
}

#[cfg(test)]
mod test {
	use super::*;

	use std::{collections::BTreeMap, path::Path};

	use maplit::hashset;
	use scale_codec::Encode;
	use sqlx::{sqlite::SqliteRow, QueryBuilder, Row, SqlitePool};
	use tempfile::tempdir;
	// Substrate
	use sp_core::{H160, H256};
	use sp_runtime::{
		generic::{Block, Header},
		traits::BlakeTwo256,
	};
	use substrate_test_runtime_client::{
		DefaultTestClientBuilderExt, TestClientBuilder, TestClientBuilderExt,
	};
	// Frontier
	use fc_api::Backend as BackendT;
	use fc_storage::{OverrideHandle, SchemaV3Override, StorageOverride};
	use fp_storage::{EthereumStorageSchema, PALLET_ETHEREUM_SCHEMA};

	type OpaqueBlock =
		Block<Header<u64, BlakeTwo256>, substrate_test_runtime_client::runtime::Extrinsic>;

	struct TestFilter {
		pub from_block: u64,
		pub to_block: u64,
		pub addresses: Vec<H160>,
		pub topics: Vec<Vec<Option<H256>>>,
		pub expected_result: Vec<FilteredLog<OpaqueBlock>>,
	}

	#[derive(Debug, Clone)]
	struct Log {
		block_number: u32,
		address: H160,
		topics: [H256; 4],
		substrate_block_hash: H256,
		ethereum_block_hash: H256,
		transaction_index: u32,
		log_index: u32,
	}

	#[allow(unused)]
	struct TestData {
		backend: Backend<OpaqueBlock>,
		alice: H160,
		bob: H160,
		topics_a: H256,
		topics_b: H256,
		topics_c: H256,
		topics_d: H256,
		substrate_hash_1: H256,
		substrate_hash_2: H256,
		substrate_hash_3: H256,
		ethereum_hash_1: H256,
		ethereum_hash_2: H256,
		ethereum_hash_3: H256,
		log_1_abcd_0_0_alice: Log,
		log_1_dcba_1_0_alice: Log,
		log_1_badc_2_0_alice: Log,
		log_2_abcd_0_0_bob: Log,
		log_2_dcba_1_0_bob: Log,
		log_2_badc_2_0_bob: Log,
		log_3_abcd_0_0_bob: Log,
		log_3_dcba_1_0_bob: Log,
		log_3_badc_2_0_bob: Log,
	}

	impl From<Log> for FilteredLog<OpaqueBlock> {
		fn from(value: Log) -> Self {
			Self {
				substrate_block_hash: value.substrate_block_hash,
				ethereum_block_hash: value.ethereum_block_hash,
				block_number: value.block_number,
				ethereum_storage_schema: EthereumStorageSchema::V3,
				transaction_index: value.transaction_index,
				log_index: value.log_index,
			}
		}
	}

	async fn prepare() -> TestData {
		let tmp = tempdir().expect("create a temporary directory");
		// Initialize storage with schema V3
		let builder = TestClientBuilder::new().add_extra_storage(
			PALLET_ETHEREUM_SCHEMA.to_vec(),
			Encode::encode(&EthereumStorageSchema::V3),
		);
		// Client
		let (client, _) = builder
			.build_with_native_executor::<substrate_test_runtime_client::runtime::RuntimeApi, _>(
				None,
			);
		let client = Arc::new(client);
		// Overrides
		let mut overrides_map = BTreeMap::new();
		overrides_map.insert(
			EthereumStorageSchema::V3,
			Box::new(SchemaV3Override::new(client.clone())) as Box<dyn StorageOverride<_>>,
		);
		let overrides = Arc::new(OverrideHandle {
			schemas: overrides_map,
			fallback: Box::new(SchemaV3Override::new(client.clone())),
		});

		// Indexer backend
		let indexer_backend = Backend::new(
			BackendConfig::Sqlite(SqliteBackendConfig {
				path: Path::new("sqlite:///")
					.join(tmp.path())
					.join("test.db3")
					.to_str()
					.unwrap(),
				create_if_missing: true,
				cache_size: 20480,
				thread_count: 4,
			}),
			1,
			None,
			overrides.clone(),
		)
		.await
		.expect("indexer pool to be created");

		// Prepare test db data
		// Addresses
		let alice = H160::repeat_byte(0x01);
		let bob = H160::repeat_byte(0x02);
		// Topics
		let topics_a = H256::repeat_byte(0x01);
		let topics_b = H256::repeat_byte(0x02);
		let topics_c = H256::repeat_byte(0x03);
		let topics_d = H256::repeat_byte(0x04);
		// Substrate block hashes
		let substrate_hash_1 = H256::repeat_byte(0x05);
		let substrate_hash_2 = H256::repeat_byte(0x06);
		let substrate_hash_3 = H256::repeat_byte(0x07);
		// Ethereum block hashes
		let ethereum_hash_1 = H256::repeat_byte(0x08);
		let ethereum_hash_2 = H256::repeat_byte(0x09);
		let ethereum_hash_3 = H256::repeat_byte(0x0a);
		// Ethereum storage schema
		let ethereum_storage_schema = EthereumStorageSchema::V3;

		let block_entries = vec![
			// Block 1
			(
				1i32,
				ethereum_hash_1,
				substrate_hash_1,
				ethereum_storage_schema,
			),
			// Block 2
			(
				2i32,
				ethereum_hash_2,
				substrate_hash_2,
				ethereum_storage_schema,
			),
			// Block 3
			(
				3i32,
				ethereum_hash_3,
				substrate_hash_3,
				ethereum_storage_schema,
			),
		];
		let mut builder = QueryBuilder::new(
			"INSERT INTO blocks(
				block_number,
				ethereum_block_hash,
				substrate_block_hash,
				ethereum_storage_schema,
				is_canon
			)",
		);
		builder.push_values(block_entries, |mut b, entry| {
			let block_number = entry.0;
			let ethereum_block_hash = entry.1.as_bytes().to_owned();
			let substrate_block_hash = entry.2.as_bytes().to_owned();
			let ethereum_storage_schema = entry.3.encode();

			b.push_bind(block_number);
			b.push_bind(ethereum_block_hash);
			b.push_bind(substrate_block_hash);
			b.push_bind(ethereum_storage_schema);
			b.push_bind(1i32);
		});
		let query = builder.build();
		let _ = query
			.execute(indexer_backend.pool())
			.await
			.expect("insert should succeed");

		// log_{BLOCK}_{TOPICS}_{LOG_INDEX}_{TX_INDEX}
		let log_1_abcd_0_0_alice = Log {
			block_number: 1,
			address: alice,
			topics: [topics_a, topics_b, topics_c, topics_d],
			log_index: 0,
			transaction_index: 0,
			substrate_block_hash: substrate_hash_1,
			ethereum_block_hash: ethereum_hash_1,
		};
		let log_1_dcba_1_0_alice = Log {
			block_number: 1,
			address: alice,
			topics: [topics_d, topics_c, topics_b, topics_a],
			log_index: 1,
			transaction_index: 0,
			substrate_block_hash: substrate_hash_1,
			ethereum_block_hash: ethereum_hash_1,
		};
		let log_1_badc_2_0_alice = Log {
			block_number: 1,
			address: alice,
			topics: [topics_b, topics_a, topics_d, topics_c],
			log_index: 2,
			transaction_index: 0,
			substrate_block_hash: substrate_hash_1,
			ethereum_block_hash: ethereum_hash_1,
		};
		let log_2_abcd_0_0_bob = Log {
			block_number: 2,
			address: bob,
			topics: [topics_a, topics_b, topics_c, topics_d],
			log_index: 0,
			transaction_index: 0,
			substrate_block_hash: substrate_hash_2,
			ethereum_block_hash: ethereum_hash_2,
		};
		let log_2_dcba_1_0_bob = Log {
			block_number: 2,
			address: bob,
			topics: [topics_d, topics_c, topics_b, topics_a],
			log_index: 1,
			transaction_index: 0,
			substrate_block_hash: substrate_hash_2,
			ethereum_block_hash: ethereum_hash_2,
		};
		let log_2_badc_2_0_bob = Log {
			block_number: 2,
			address: bob,
			topics: [topics_b, topics_a, topics_d, topics_c],
			log_index: 2,
			transaction_index: 0,
			substrate_block_hash: substrate_hash_2,
			ethereum_block_hash: ethereum_hash_2,
		};

		let log_3_abcd_0_0_bob = Log {
			block_number: 3,
			address: bob,
			topics: [topics_a, topics_b, topics_c, topics_d],
			log_index: 0,
			transaction_index: 0,
			substrate_block_hash: substrate_hash_3,
			ethereum_block_hash: ethereum_hash_3,
		};
		let log_3_dcba_1_0_bob = Log {
			block_number: 3,
			address: bob,
			topics: [topics_d, topics_c, topics_b, topics_a],
			log_index: 1,
			transaction_index: 0,
			substrate_block_hash: substrate_hash_3,
			ethereum_block_hash: ethereum_hash_3,
		};
		let log_3_badc_2_0_bob = Log {
			block_number: 3,
			address: bob,
			topics: [topics_b, topics_a, topics_d, topics_c],
			log_index: 2,
			transaction_index: 0,
			substrate_block_hash: substrate_hash_3,
			ethereum_block_hash: ethereum_hash_3,
		};

		let log_entries = vec![
			// Block 1
			log_1_abcd_0_0_alice.clone(),
			log_1_dcba_1_0_alice.clone(),
			log_1_badc_2_0_alice.clone(),
			// Block 2
			log_2_abcd_0_0_bob.clone(),
			log_2_dcba_1_0_bob.clone(),
			log_2_badc_2_0_bob.clone(),
			// Block 3
			log_3_abcd_0_0_bob.clone(),
			log_3_dcba_1_0_bob.clone(),
			log_3_badc_2_0_bob.clone(),
		];

		let mut builder: QueryBuilder<sqlx::Sqlite> = QueryBuilder::new(
			"INSERT INTO logs(
				address,
				topic_1,
				topic_2,
				topic_3,
				topic_4,
				log_index,
				transaction_index,
				substrate_block_hash
			)",
		);
		builder.push_values(log_entries, |mut b, entry| {
			let address = entry.address.as_bytes().to_owned();
			let topic_1 = entry.topics[0].as_bytes().to_owned();
			let topic_2 = entry.topics[1].as_bytes().to_owned();
			let topic_3 = entry.topics[2].as_bytes().to_owned();
			let topic_4 = entry.topics[3].as_bytes().to_owned();
			let log_index = entry.log_index;
			let transaction_index = entry.transaction_index;
			let substrate_block_hash = entry.substrate_block_hash.as_bytes().to_owned();

			b.push_bind(address);
			b.push_bind(topic_1);
			b.push_bind(topic_2);
			b.push_bind(topic_3);
			b.push_bind(topic_4);
			b.push_bind(log_index);
			b.push_bind(transaction_index);
			b.push_bind(substrate_block_hash);
		});
		let query = builder.build();
		let _ = query.execute(indexer_backend.pool()).await;

		TestData {
			alice,
			bob,
			topics_a,
			topics_b,
			topics_c,
			topics_d,
			substrate_hash_1,
			substrate_hash_2,
			substrate_hash_3,
			ethereum_hash_1,
			ethereum_hash_2,
			ethereum_hash_3,
			backend: indexer_backend,
			log_1_abcd_0_0_alice,
			log_1_dcba_1_0_alice,
			log_1_badc_2_0_alice,
			log_2_abcd_0_0_bob,
			log_2_dcba_1_0_bob,
			log_2_badc_2_0_bob,
			log_3_abcd_0_0_bob,
			log_3_dcba_1_0_bob,
			log_3_badc_2_0_bob,
		}
	}

	async fn run_test_case(
		backend: Backend<OpaqueBlock>,
		test_case: &TestFilter,
	) -> Result<Vec<FilteredLog<OpaqueBlock>>, String> {
		backend
			.log_indexer()
			.filter_logs(
				test_case.from_block,
				test_case.to_block,
				test_case.addresses.clone(),
				test_case.topics.clone(),
			)
			.await
	}

	async fn assert_blocks_canon(pool: &SqlitePool, expected: Vec<(H256, u32)>) {
		let actual: Vec<(H256, u32)> =
			sqlx::query("SELECT substrate_block_hash, is_canon FROM blocks")
				.map(|row: SqliteRow| (H256::from_slice(&row.get::<Vec<u8>, _>(0)[..]), row.get(1)))
				.fetch_all(pool)
				.await
				.expect("sql query must succeed");
		assert_eq!(expected, actual);
	}

	#[tokio::test]
	async fn genesis_works() {
		let TestData { backend, .. } = prepare().await;
		let filter = TestFilter {
			from_block: 0,
			to_block: 0,
			addresses: vec![],
			topics: vec![],
			expected_result: vec![],
		};
		let result = run_test_case(backend, &filter).await.expect("must succeed");
		assert_eq!(result, filter.expected_result);
	}

	#[tokio::test]
	async fn unsanitized_input_works() {
		let TestData { backend, .. } = prepare().await;
		let filter = TestFilter {
			from_block: 0,
			to_block: 0,
			addresses: vec![],
			topics: vec![vec![None], vec![None, None, None]],
			expected_result: vec![],
		};
		let result = run_test_case(backend, &filter).await.expect("must succeed");
		assert_eq!(result, filter.expected_result);
	}

	#[tokio::test]
	async fn invalid_topic_input_size_fails() {
		let TestData {
			backend, topics_a, ..
		} = prepare().await;
		let filter = TestFilter {
			from_block: 0,
			to_block: 0,
			addresses: vec![],
			topics: vec![
				vec![Some(topics_a), None, None, None, None],
				vec![Some(topics_a), None, None, None],
			],
			expected_result: vec![],
		};
		run_test_case(backend, &filter)
			.await
			.expect_err("Invalid topic input. Maximum length is 4.");
	}

	#[tokio::test]
	async fn test_malformed_topic_cleans_invalid_options() {
		let TestData {
			backend,
			topics_a,
			topics_b,
			topics_d,
			log_1_badc_2_0_alice,
			..
		} = prepare().await;

		// [(a,null,b), (a, null), (d,null), null] -> [(a,b), a, d]
		let filter = TestFilter {
			from_block: 0,
			to_block: 1,
			addresses: vec![],
			topics: vec![
				vec![Some(topics_a), None, Some(topics_d)],
				vec![None], // not considered
				vec![Some(topics_b), Some(topics_a), None],
				vec![None, None, None, None], // not considered
			],
			expected_result: vec![log_1_badc_2_0_alice.into()],
		};
		let result = run_test_case(backend, &filter).await.expect("must succeed");
		assert_eq!(result, filter.expected_result);
	}

	#[tokio::test]
	async fn block_range_works() {
		let TestData {
			backend,
			log_1_abcd_0_0_alice,
			log_1_dcba_1_0_alice,
			log_1_badc_2_0_alice,
			log_2_abcd_0_0_bob,
			log_2_dcba_1_0_bob,
			log_2_badc_2_0_bob,
			..
		} = prepare().await;

		let filter = TestFilter {
			from_block: 0,
			to_block: 2,
			addresses: vec![],
			topics: vec![],
			expected_result: vec![
				log_1_abcd_0_0_alice.into(),
				log_1_dcba_1_0_alice.into(),
				log_1_badc_2_0_alice.into(),
				log_2_abcd_0_0_bob.into(),
				log_2_dcba_1_0_bob.into(),
				log_2_badc_2_0_bob.into(),
			],
		};
		let result = run_test_case(backend, &filter).await.expect("must succeed");
		assert_eq!(result, filter.expected_result);
	}

	#[tokio::test]
	async fn address_filter_works() {
		let TestData {
			backend,
			alice,
			log_1_abcd_0_0_alice,
			log_1_dcba_1_0_alice,
			log_1_badc_2_0_alice,
			..
		} = prepare().await;
		let filter = TestFilter {
			from_block: 0,
			to_block: 3,
			addresses: vec![alice],
			topics: vec![],
			expected_result: vec![
				log_1_abcd_0_0_alice.into(),
				log_1_dcba_1_0_alice.into(),
				log_1_badc_2_0_alice.into(),
			],
		};
		let result = run_test_case(backend, &filter).await.expect("must succeed");
		assert_eq!(result, filter.expected_result);
	}

	#[tokio::test]
	async fn topic_filter_works() {
		let TestData {
			backend,
			topics_d,
			log_1_dcba_1_0_alice,
			log_2_dcba_1_0_bob,
			log_3_dcba_1_0_bob,
			..
		} = prepare().await;
		let filter = TestFilter {
			from_block: 0,
			to_block: 3,
			addresses: vec![],
			topics: vec![vec![Some(topics_d)]],
			expected_result: vec![
				log_1_dcba_1_0_alice.into(),
				log_2_dcba_1_0_bob.into(),
				log_3_dcba_1_0_bob.into(),
			],
		};
		let result = run_test_case(backend, &filter).await.expect("must succeed");
		assert_eq!(result, filter.expected_result);
	}

	#[tokio::test]
	async fn test_filters_address_and_topic() {
		let TestData {
			backend,
			bob,
			topics_b,
			log_2_badc_2_0_bob,
			log_3_badc_2_0_bob,
			..
		} = prepare().await;
		let filter = TestFilter {
			from_block: 0,
			to_block: 3,
			addresses: vec![bob],
			topics: vec![vec![Some(topics_b)]],
			expected_result: vec![log_2_badc_2_0_bob.into(), log_3_badc_2_0_bob.into()],
		};
		let result = run_test_case(backend, &filter).await.expect("must succeed");
		assert_eq!(result, filter.expected_result);
	}

	#[tokio::test]
	async fn test_filters_multi_address_and_topic() {
		let TestData {
			backend,
			alice,
			bob,
			topics_b,
			log_1_badc_2_0_alice,
			log_2_badc_2_0_bob,
			log_3_badc_2_0_bob,
			..
		} = prepare().await;
		let filter = TestFilter {
			from_block: 0,
			to_block: 3,
			addresses: vec![alice, bob],
			topics: vec![vec![Some(topics_b)]],
			expected_result: vec![
				log_1_badc_2_0_alice.into(),
				log_2_badc_2_0_bob.into(),
				log_3_badc_2_0_bob.into(),
			],
		};
		let result = run_test_case(backend, &filter).await.expect("must succeed");
		assert_eq!(result, filter.expected_result);
	}

	#[tokio::test]
	async fn test_filters_multi_address_and_multi_topic() {
		let TestData {
			backend,
			alice,
			bob,
			topics_a,
			topics_b,
			log_1_abcd_0_0_alice,
			log_2_abcd_0_0_bob,
			log_3_abcd_0_0_bob,
			..
		} = prepare().await;
		let filter = TestFilter {
			from_block: 0,
			to_block: 3,
			addresses: vec![alice, bob],
			topics: vec![vec![Some(topics_a), Some(topics_b)]],
			expected_result: vec![
				log_1_abcd_0_0_alice.into(),
				log_2_abcd_0_0_bob.into(),
				log_3_abcd_0_0_bob.into(),
			],
		};
		let result = run_test_case(backend, &filter).await.expect("must succeed");
		assert_eq!(result, filter.expected_result);
	}

	#[tokio::test]
	async fn filter_with_topic_wildcards_works() {
		let TestData {
			backend,
			alice,
			bob,
			topics_d,
			topics_b,
			log_1_dcba_1_0_alice,
			log_2_dcba_1_0_bob,
			log_3_dcba_1_0_bob,
			..
		} = prepare().await;
		let filter = TestFilter {
			from_block: 0,
			to_block: 3,
			addresses: vec![alice, bob],
			topics: vec![vec![Some(topics_d), None, Some(topics_b)]],
			expected_result: vec![
				log_1_dcba_1_0_alice.into(),
				log_2_dcba_1_0_bob.into(),
				log_3_dcba_1_0_bob.into(),
			],
		};
		let result = run_test_case(backend, &filter).await.expect("must succeed");
		assert_eq!(result, filter.expected_result);
	}

	#[tokio::test]
	async fn trailing_wildcard_is_useless_but_works() {
		let TestData {
			alice,
			backend,
			topics_b,
			log_1_dcba_1_0_alice,
			..
		} = prepare().await;
		let filter = TestFilter {
			from_block: 0,
			to_block: 1,
			addresses: vec![alice],
			topics: vec![vec![None, None, Some(topics_b), None]],
			expected_result: vec![log_1_dcba_1_0_alice.into()],
		};
		let result = run_test_case(backend, &filter).await.expect("must succeed");
		assert_eq!(result, filter.expected_result);
	}

	#[tokio::test]
	async fn filter_with_multi_topic_options_works() {
		let TestData {
			backend,
			topics_a,
			topics_d,
			log_1_abcd_0_0_alice,
			log_1_dcba_1_0_alice,
			log_2_abcd_0_0_bob,
			log_2_dcba_1_0_bob,
			log_3_abcd_0_0_bob,
			log_3_dcba_1_0_bob,
			..
		} = prepare().await;
		let filter = TestFilter {
			from_block: 0,
			to_block: 3,
			addresses: vec![],
			topics: vec![
				vec![Some(topics_a)],
				vec![Some(topics_d)],
				vec![Some(topics_d)], // duplicate, ignored
			],
			expected_result: vec![
				log_1_abcd_0_0_alice.into(),
				log_1_dcba_1_0_alice.into(),
				log_2_abcd_0_0_bob.into(),
				log_2_dcba_1_0_bob.into(),
				log_3_abcd_0_0_bob.into(),
				log_3_dcba_1_0_bob.into(),
			],
		};
		let result = run_test_case(backend, &filter).await.expect("must succeed");
		assert_eq!(result, filter.expected_result);
	}

	#[tokio::test]
	async fn filter_with_multi_topic_options_and_wildcards_works() {
		let TestData {
			backend,
			bob,
			topics_a,
			topics_b,
			topics_c,
			topics_d,
			log_2_dcba_1_0_bob,
			log_2_badc_2_0_bob,
			log_3_dcba_1_0_bob,
			log_3_badc_2_0_bob,
			..
		} = prepare().await;
		let filter = TestFilter {
			from_block: 0,
			to_block: 3,
			addresses: vec![bob],
			// Product on input [null,null,(b,d),(a,c)].
			topics: vec![
				vec![None, None, Some(topics_b), Some(topics_a)],
				vec![None, None, Some(topics_b), Some(topics_c)],
				vec![None, None, Some(topics_d), Some(topics_a)],
				vec![None, None, Some(topics_d), Some(topics_c)],
			],
			expected_result: vec![
				log_2_dcba_1_0_bob.into(),
				log_2_badc_2_0_bob.into(),
				log_3_dcba_1_0_bob.into(),
				log_3_badc_2_0_bob.into(),
			],
		};
		let result = run_test_case(backend, &filter).await.expect("must succeed");
		assert_eq!(result, filter.expected_result);
	}

	#[tokio::test]
	async fn test_canonicalize_sets_canon_flag_for_redacted_and_enacted_blocks_correctly() {
		let TestData {
			backend,
			substrate_hash_1,
			substrate_hash_2,
			substrate_hash_3,
			..
		} = prepare().await;

		// set block #1 to non canon
		sqlx::query("UPDATE blocks SET is_canon = 0 WHERE substrate_block_hash = ?")
			.bind(substrate_hash_1.as_bytes())
			.execute(backend.pool())
			.await
			.expect("sql query must succeed");
		assert_blocks_canon(
			backend.pool(),
			vec![
				(substrate_hash_1, 0),
				(substrate_hash_2, 1),
				(substrate_hash_3, 1),
			],
		)
		.await;

		backend
			.canonicalize(&[substrate_hash_2], &[substrate_hash_1])
			.await
			.expect("must succeed");

		assert_blocks_canon(
			backend.pool(),
			vec![
				(substrate_hash_1, 1),
				(substrate_hash_2, 0),
				(substrate_hash_3, 1),
			],
		)
		.await;
	}

	#[test]
	fn test_query_should_be_generated_correctly() {
		use sqlx::Execute;

		let from_block: u64 = 100;
		let to_block: u64 = 500;
		let addresses: Vec<H160> = vec![
			H160::repeat_byte(0x01),
			H160::repeat_byte(0x02),
			H160::repeat_byte(0x03),
		];
		let topics = [
			hashset![
				H256::repeat_byte(0x01),
				H256::repeat_byte(0x02),
				H256::repeat_byte(0x03),
			],
			hashset![H256::repeat_byte(0x04), H256::repeat_byte(0x05),],
			hashset![],
			hashset![H256::repeat_byte(0x06)],
		];

		let expected_query_sql = "
SELECT
	l.substrate_block_hash,
	b.ethereum_block_hash,
	b.block_number,
	b.ethereum_storage_schema,
	l.transaction_index,
	l.log_index
FROM logs AS l
INNER JOIN blocks AS b
ON (b.block_number BETWEEN ? AND ?) AND b.substrate_block_hash = l.substrate_block_hash AND b.is_canon = 1
WHERE 1 AND l.address IN (?, ?, ?) AND l.topic_1 IN (?, ?, ?) AND l.topic_2 IN (?, ?) AND l.topic_4 = ?
ORDER BY b.block_number ASC, l.transaction_index ASC, l.log_index ASC
LIMIT 10001";

		let mut qb = QueryBuilder::new("");
		let actual_query_sql = build_query(&mut qb, from_block, to_block, addresses, topics).sql();
		assert_eq!(expected_query_sql, actual_query_sql);
	}
}