       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

    // Copyright 2015-2017 Parity Technologies (UK) Ltd.
    // This file is part of Parity.

    // Parity 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.

    // Parity 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 Parity.  If not, see <http://www.gnu.org/licenses/>.

    //! Blockchain database.

    use bloomchain as bc;
    use util::*;
    use rlp::*;
    use header::*;
    use super::extras::*;
    use transaction::*;
    use views::*;
    use log_entry::{LogEntry, LocalizedLogEntry};
    use receipt::Receipt;
    use blooms::{Bloom, BloomGroup};
    use blockchain::block_info::{BlockInfo, BlockLocation, BranchBecomingCanonChainData};
    use blockchain::best_block::{BestBlock, BestAncientBlock};
    use types::blockchain_info::BlockChainInfo;
    use types::tree_route::TreeRoute;
    use blockchain::update::ExtrasUpdate;
    use blockchain::{CacheSize, ImportRoute, Config};
    use db::{self, Writable, Readable, CacheUpdatePolicy};
    use cache_manager::CacheManager;
    use encoded;

    const LOG_BLOOMS_LEVELS: usize = 3;
    const LOG_BLOOMS_ELEMENTS_PER_INDEX: usize = 16;

    /// Interface for querying blocks by hash and by number.
    pub trait BlockProvider {
    	/// Returns true if the given block is known
    	/// (though not necessarily a part of the canon chain).
    	fn is_known(&self, hash: &H256) -> bool;

    	/// Get the first block of the best part of the chain.
    	/// Return `None` if there is no gap and the first block is the genesis.
    	/// Any queries of blocks which precede this one are not guaranteed to
    	/// succeed.
    	fn first_block(&self) -> Option<H256>;

    	/// Get the number of the first block.
    	fn first_block_number(&self) -> Option<BlockNumber> {
    		self.first_block().map(|b| self.block_number(&b).expect("First block is always set to an existing block or `None`. Existing block always has a number; qed"))
    	}

    	/// Get the best block of an first block sequence if there is a gap.
    	fn best_ancient_block(&self) -> Option<H256>;

    	/// Get the number of the first block.
    	fn best_ancient_number(&self) -> Option<BlockNumber> {
    		self.best_ancient_block().map(|h| self.block_number(&h).expect("Ancient block is always set to an existing block or `None`. Existing block always has a number; qed"))
    	}
    	/// Get raw block data
    	fn block(&self, hash: &H256) -> Option<encoded::Block>;

    	/// Get the familial details concerning a block.
    	fn block_details(&self, hash: &H256) -> Option<BlockDetails>;

    	/// Get the hash of given block's number.
    	fn block_hash(&self, index: BlockNumber) -> Option<H256>;

    	/// Get the address of transaction with given hash.
    	fn transaction_address(&self, hash: &H256) -> Option<TransactionAddress>;

    	/// Get receipts of block with given hash.
    	fn block_receipts(&self, hash: &H256) -> Option<BlockReceipts>;

    	/// Get the partial-header of a block.
    	fn block_header(&self, hash: &H256) -> Option<Header> {
    		self.block_header_data(hash).map(|header| header.decode())
    	}

    	/// Get the header RLP of a block.
    	fn block_header_data(&self, hash: &H256) -> Option<encoded::Header>;

    	/// Get the block body (uncles and transactions).
    	fn block_body(&self, hash: &H256) -> Option<encoded::Body>;

    	/// Get a list of uncles for a given block.
    	/// Returns None if block does not exist.
    	fn uncles(&self, hash: &H256) -> Option<Vec<Header>> {
    		self.block_body(hash).map(|body| body.uncles())
    	}

    	/// Get a list of uncle hashes for a given block.
    	/// Returns None if block does not exist.
    	fn uncle_hashes(&self, hash: &H256) -> Option<Vec<H256>> {
    		self.block_body(hash).map(|body| body.uncle_hashes())
    	}

    	/// Get the number of given block's hash.
    	fn block_number(&self, hash: &H256) -> Option<BlockNumber> {
    		self.block_details(hash).map(|details| details.number)
    	}

    	/// Get transaction with given transaction hash.
    	fn transaction(&self, address: &TransactionAddress) -> Option<LocalizedTransaction> {
    		self.block_body(&address.block_hash)
    			.and_then(|body| self.block_number(&address.block_hash)
    			.and_then(|n| body.view().localized_transaction_at(&address.block_hash, n, address.index)))
    	}

    	/// Get transaction receipt.
    	fn transaction_receipt(&self, address: &TransactionAddress) -> Option<Receipt> {
    		self.block_receipts(&address.block_hash).and_then(|br| br.receipts.into_iter().nth(address.index))
    	}

    	/// Get a list of transactions for a given block.
    	/// Returns None if block does not exist.
    	fn transactions(&self, hash: &H256) -> Option<Vec<LocalizedTransaction>> {
    		self.block_body(hash)
    			.and_then(|body| self.block_number(hash)
    			.map(|n| body.view().localized_transactions(hash, n)))
    	}

    	/// Returns reference to genesis hash.
    	fn genesis_hash(&self) -> H256 {
    		self.block_hash(0).expect("Genesis hash should always exist")
    	}

    	/// Returns the header of the genesis block.
    	fn genesis_header(&self) -> Header {
    		self.block_header(&self.genesis_hash())
    			.expect("Genesis header always stored; qed")
    	}

    	/// Returns numbers of blocks containing given bloom.
    	fn blocks_with_bloom(&self, bloom: &H2048, from_block: BlockNumber, to_block: BlockNumber) -> Vec<BlockNumber>;

    	/// Returns logs matching given filter.
    	fn logs<F>(&self, blocks: Vec<BlockNumber>, matches: F, limit: Option<usize>) -> Vec<LocalizedLogEntry>
    		where F: Fn(&LogEntry) -> bool, Self: Sized;
    }

    #[derive(Debug, Hash, Eq, PartialEq, Clone)]
    enum CacheId {
    	BlockHeader(H256),
    	BlockBody(H256),
    	BlockDetails(H256),
    	BlockHashes(BlockNumber),
    	TransactionAddresses(H256),
    	BlocksBlooms(LogGroupPosition),
    	BlockReceipts(H256),
    }

    impl bc::group::BloomGroupDatabase for BlockChain {
    	fn blooms_at(&self, position: &bc::group::GroupPosition) -> Option<bc::group::BloomGroup> {
    		let position = LogGroupPosition::from(position.clone());
    		let result = self.db.read_with_cache(db::COL_EXTRA, &self.blocks_blooms, &position).map(Into::into);
    		self.cache_man.lock().note_used(CacheId::BlocksBlooms(position));
    		result
    	}
    }

    /// Structure providing fast access to blockchain data.
    ///
    /// **Does not do input data verification.**
    pub struct BlockChain {
    	// All locks must be captured in the order declared here.
    	blooms_config: bc::Config,

    	best_block: RwLock<BestBlock>,
    	// Stores best block of the first uninterrupted sequence of blocks. `None` if there are no gaps.
    	// Only updated with `insert_unordered_block`.
    	best_ancient_block: RwLock<Option<BestAncientBlock>>,
    	// Stores the last block of the last sequence of blocks. `None` if there are no gaps.
    	// This is calculated on start and does not get updated.
    	first_block: Option<H256>,

    	// block cache
    	block_headers: RwLock<HashMap<H256, Bytes>>,
    	block_bodies: RwLock<HashMap<H256, Bytes>>,

    	// extra caches
    	block_details: RwLock<HashMap<H256, BlockDetails>>,
    	block_hashes: RwLock<HashMap<BlockNumber, H256>>,
    	transaction_addresses: RwLock<HashMap<H256, TransactionAddress>>,
    	blocks_blooms: RwLock<HashMap<LogGroupPosition, BloomGroup>>,
    	block_receipts: RwLock<HashMap<H256, BlockReceipts>>,

    	db: Arc<Database>,

    	cache_man: Mutex<CacheManager<CacheId>>,

    	pending_best_block: RwLock<Option<BestBlock>>,
    	pending_block_hashes: RwLock<HashMap<BlockNumber, H256>>,
    	pending_block_details: RwLock<HashMap<H256, BlockDetails>>,
    	pending_transaction_addresses: RwLock<HashMap<H256, Option<TransactionAddress>>>,
    }

    impl BlockProvider for BlockChain {
    	/// Returns true if the given block is known
    	/// (though not necessarily a part of the canon chain).
    	fn is_known(&self, hash: &H256) -> bool {
    		self.db.exists_with_cache(db::COL_EXTRA, &self.block_details, hash)
    	}

    	fn first_block(&self) -> Option<H256> {
    		self.first_block.clone()
    	}

    	fn best_ancient_block(&self) -> Option<H256> {
    		self.best_ancient_block.read().as_ref().map(|b| b.hash.clone())
    	}

    	fn best_ancient_number(&self) -> Option<BlockNumber> {
    		self.best_ancient_block.read().as_ref().map(|b| b.number)
    	}

    	/// Get raw block data
    	fn block(&self, hash: &H256) -> Option<encoded::Block> {
    		match (self.block_header_data(hash), self.block_body(hash)) {
    			(Some(header), Some(body)) => {
    				let mut block = RlpStream::new_list(3);
    				let body_rlp = body.rlp();
    				block.append_raw(header.rlp().as_raw(), 1);
    				block.append_raw(body_rlp.at(0).as_raw(), 1);
    				block.append_raw(body_rlp.at(1).as_raw(), 1);
    				Some(encoded::Block::new(block.out()))
    			},
    			_ => None,
    		}
    	}

    	/// Get block header data
    	fn block_header_data(&self, hash: &H256) -> Option<encoded::Header> {
    		// Check cache first
    		{
    			let read = self.block_headers.read();
    			if let Some(v) = read.get(hash) {
    				return Some(encoded::Header::new(v.clone()));
    			}
    		}

    		// Check if it's the best block
    		{
    			let best_block = self.best_block.read();
    			if &best_block.hash == hash {
    				return Some(encoded::Header::new(
    					Rlp::new(&best_block.block).at(0).as_raw().to_vec()
    				))
    			}
    		}

    		// Read from DB and populate cache
    		let opt = self.db.get(db::COL_HEADERS, hash)
    			.expect("Low level database error. Some issue with disk?");

    		let result = match opt {
    			Some(b) => {
    				let bytes: Bytes = UntrustedRlp::new(&b).decompress(RlpType::Blocks).to_vec();
    				let mut write = self.block_headers.write();
    				write.insert(hash.clone(), bytes.clone());
    				Some(encoded::Header::new(bytes))
    			},
    			None => None
    		};

    		self.cache_man.lock().note_used(CacheId::BlockHeader(hash.clone()));
    		result
    	}

    	/// Get block body data
    	fn block_body(&self, hash: &H256) -> Option<encoded::Body> {
    		// Check cache first
    		{
    			let read = self.block_bodies.read();
    			if let Some(v) = read.get(hash) {
    				return Some(encoded::Body::new(v.clone()));
    			}
    		}

    		// Check if it's the best block
    		{
    			let best_block = self.best_block.read();
    			if &best_block.hash == hash {
    				return Some(encoded::Body::new(Self::block_to_body(&best_block.block)));
    			}
    		}

    		// Read from DB and populate cache
    		let opt = self.db.get(db::COL_BODIES, hash)
    			.expect("Low level database error. Some issue with disk?");

    		let result = match opt {
    			Some(b) => {
    				let bytes: Bytes = UntrustedRlp::new(&b).decompress(RlpType::Blocks).to_vec();
    				let mut write = self.block_bodies.write();
    				write.insert(hash.clone(), bytes.clone());
    				Some(encoded::Body::new(bytes))
    			},
    			None => None
    		};

    		self.cache_man.lock().note_used(CacheId::BlockBody(hash.clone()));

    		result
    	}

    	/// Get the familial details concerning a block.
    	fn block_details(&self, hash: &H256) -> Option<BlockDetails> {
    		let result = self.db.read_with_cache(db::COL_EXTRA, &self.block_details, hash);
    		self.cache_man.lock().note_used(CacheId::BlockDetails(hash.clone()));
    		result
    	}

    	/// Get the hash of given block's number.
    	fn block_hash(&self, index: BlockNumber) -> Option<H256> {
    		let result = self.db.read_with_cache(db::COL_EXTRA, &self.block_hashes, &index);
    		self.cache_man.lock().note_used(CacheId::BlockHashes(index));
    		result
    	}

    	/// Get the address of transaction with given hash.
    	fn transaction_address(&self, hash: &H256) -> Option<TransactionAddress> {
    		let result = self.db.read_with_cache(db::COL_EXTRA, &self.transaction_addresses, hash);
    		self.cache_man.lock().note_used(CacheId::TransactionAddresses(hash.clone()));
    		result
    	}

    	/// Get receipts of block with given hash.
    	fn block_receipts(&self, hash: &H256) -> Option<BlockReceipts> {
    		let result = self.db.read_with_cache(db::COL_EXTRA, &self.block_receipts, hash);
    		self.cache_man.lock().note_used(CacheId::BlockReceipts(hash.clone()));
    		result
    	}

    	/// Returns numbers of blocks containing given bloom.
    	fn blocks_with_bloom(&self, bloom: &H2048, from_block: BlockNumber, to_block: BlockNumber) -> Vec<BlockNumber> {
    		let range = from_block as bc::Number..to_block as bc::Number;
    		let chain = bc::group::BloomGroupChain::new(self.blooms_config, self);
    		chain.with_bloom(&range, &Bloom::from(bloom.clone()).into())
    			.into_iter()
    			.map(|b| b as BlockNumber)
    			.collect()
    	}

    	fn logs<F>(&self, mut blocks: Vec<BlockNumber>, matches: F, limit: Option<usize>) -> Vec<LocalizedLogEntry>
    		where F: Fn(&LogEntry) -> bool, Self: Sized {
    		// sort in reverse order
    		blocks.sort_by(|a, b| b.cmp(a));

    		let mut log_index = 0;
    		let mut logs = blocks.into_iter()
    			.filter_map(|number| self.block_hash(number).map(|hash| (number, hash)))
    			.filter_map(|(number, hash)| self.block_receipts(&hash).map(|r| (number, hash, r.receipts)))
    			.filter_map(|(number, hash, receipts)| self.block_body(&hash).map(|ref b| (number, hash, receipts, b.transaction_hashes())))
    			.flat_map(|(number, hash, mut receipts, mut hashes)| {
    				if receipts.len() != hashes.len() {
    					warn!("Block {} ({}) has different number of receipts ({}) to transactions ({}). Database corrupt?", number, hash, receipts.len(), hashes.len());
    					assert!(false);
    				}
    				log_index = receipts.iter().fold(0, |sum, receipt| sum + receipt.logs.len());

    				let receipts_len = receipts.len();
    				hashes.reverse();
    				receipts.reverse();
    				receipts.into_iter()
    					.map(|receipt| receipt.logs)
    					.zip(hashes)
    					.enumerate()
    					.flat_map(move |(index, (mut logs, tx_hash))| {
    						let current_log_index = log_index;
    						let no_of_logs = logs.len();
    						log_index -= no_of_logs;

    						logs.reverse();
    						logs.into_iter()
    							.enumerate()
    							.map(move |(i, log)| LocalizedLogEntry {
    								entry: log,
    								block_hash: hash,
    								block_number: number,
    								transaction_hash: tx_hash,
    								// iterating in reverse order
    								transaction_index: receipts_len - index - 1,
    								transaction_log_index: no_of_logs - i - 1,
    								log_index: current_log_index - i - 1,
    							})
    					})
    			})
    			.filter(|log_entry| matches(&log_entry.entry))
    			.take(limit.unwrap_or(::std::usize::MAX))
    			.collect::<Vec<LocalizedLogEntry>>();
    		logs.reverse();
    		logs
    	}
    }

    /// An iterator which walks the blockchain towards the genesis.
    #[derive(Clone)]
    pub struct AncestryIter<'a> {
    	current: H256,
    	chain: &'a BlockChain,
    }

    impl<'a> Iterator for AncestryIter<'a> {
    	type Item = H256;
    	fn next(&mut self) -> Option<H256> {
    		if self.current.is_zero() {
    			None
    		} else {
    			self.chain.block_details(&self.current)
    				.map(|details| mem::replace(&mut self.current, details.parent))
    		}
    	}
    }

    impl BlockChain {
    	/// Create new instance of blockchain from given Genesis.
    	pub fn new(config: Config, genesis: &[u8], db: Arc<Database>) -> BlockChain {
    		// 400 is the avarage size of the key
    		let cache_man = CacheManager::new(config.pref_cache_size, config.max_cache_size, 400);

    		let mut bc = BlockChain {
    			blooms_config: bc::Config {
    				levels: LOG_BLOOMS_LEVELS,
    				elements_per_index: LOG_BLOOMS_ELEMENTS_PER_INDEX,
    			},
    			first_block: None,
    			best_block: RwLock::new(BestBlock::default()),
    			best_ancient_block: RwLock::new(None),
    			block_headers: RwLock::new(HashMap::new()),
    			block_bodies: RwLock::new(HashMap::new()),
    			block_details: RwLock::new(HashMap::new()),
    			block_hashes: RwLock::new(HashMap::new()),
    			transaction_addresses: RwLock::new(HashMap::new()),
    			blocks_blooms: RwLock::new(HashMap::new()),
    			block_receipts: RwLock::new(HashMap::new()),
    			db: db.clone(),
    			cache_man: Mutex::new(cache_man),
    			pending_best_block: RwLock::new(None),
    			pending_block_hashes: RwLock::new(HashMap::new()),
    			pending_block_details: RwLock::new(HashMap::new()),
    			pending_transaction_addresses: RwLock::new(HashMap::new()),
    		};

    		// load best block
    		let best_block_hash = match bc.db.get(db::COL_EXTRA, b"best").unwrap() {
    			Some(best) => {
    				H256::from_slice(&best)
    			}
    			None => {
    				// best block does not exist
    				// we need to insert genesis into the cache
    				let block = BlockView::new(genesis);
    				let header = block.header_view();
    				let hash = block.sha3();

    				let details = BlockDetails {
    					number: header.number(),
    					total_difficulty: header.difficulty(),
    					parent: header.parent_hash(),
    					children: vec![]
    				};

    				let mut batch = DBTransaction::new(&db);
    				batch.put(db::COL_HEADERS, &hash, block.header_rlp().as_raw());
    				batch.put(db::COL_BODIES, &hash, &Self::block_to_body(genesis));

    				batch.write(db::COL_EXTRA, &hash, &details);
    				batch.write(db::COL_EXTRA, &header.number(), &hash);

    				batch.put(db::COL_EXTRA, b"best", &hash);
    				bc.db.write(batch).expect("Low level database error. Some issue with disk?");
    				hash
    			}
    		};

    		{
    			// Fetch best block details
    			let best_block_number = bc.block_number(&best_block_hash).unwrap();
    			let best_block_total_difficulty = bc.block_details(&best_block_hash).unwrap().total_difficulty;
    			let best_block_rlp = bc.block(&best_block_hash).unwrap().into_inner();

    			let raw_first = bc.db.get(db::COL_EXTRA, b"first").unwrap().map(|v| v.to_vec());
    			let mut best_ancient = bc.db.get(db::COL_EXTRA, b"ancient").unwrap().map(|h| H256::from_slice(&h));
    			let best_ancient_number;
    			if best_ancient.is_none() && best_block_number > 1 && bc.block_hash(1).is_none() {
    				best_ancient = Some(bc.genesis_hash());
    				best_ancient_number = Some(0);
    			} else {
    				best_ancient_number = best_ancient.as_ref().and_then(|h| bc.block_number(h));
    			}

    			// binary search for the first block.
    			match raw_first {
    				None => {
    					let (mut f, mut hash) = (best_block_number, best_block_hash);
    					let mut l = best_ancient_number.unwrap_or(0);

    					loop {
    						if l >= f { break; }

    						let step = (f - l) >> 1;
    						let m = l + step;

    						match bc.block_hash(m) {
    							Some(h) => { f = m; hash = h },
    							None => { l = m + 1 },
    						}
    					}

    					if hash != bc.genesis_hash() {
    						trace!("First block calculated: {:?}", hash);
    						let mut batch = db.transaction();
    						batch.put(db::COL_EXTRA, b"first", &hash);
    						db.write(batch).expect("Low level database error.");
    						bc.first_block = Some(hash);
    					}
    				},
    				Some(raw_first) => {
    					bc.first_block = Some(H256::from_slice(&raw_first));
    				},
    			}

    			// and write them
    			let mut best_block = bc.best_block.write();
    			*best_block = BestBlock {
    				number: best_block_number,
    				total_difficulty: best_block_total_difficulty,
    				hash: best_block_hash,
    				block: best_block_rlp,
    			};

    			if let (Some(hash), Some(number)) = (best_ancient, best_ancient_number) {
    				let mut best_ancient_block = bc.best_ancient_block.write();
    				*best_ancient_block = Some(BestAncientBlock {
    					hash: hash,
    					number: number,
    				});
    			}
    		}

    		bc
    	}

    	/// Returns true if the given parent block has given child
    	/// (though not necessarily a part of the canon chain).
    	fn is_known_child(&self, parent: &H256, hash: &H256) -> bool {
    		self.db.read_with_cache(db::COL_EXTRA, &self.block_details, parent).map_or(false, |d| d.children.contains(hash))
    	}

    	/// Rewind to a previous block
    	#[cfg(test)]
    	fn rewind(&self) -> Option<H256> {
    		use db::Key;
    		let mut batch =self.db.transaction();
    		// track back to the best block we have in the blocks database
    		if let Some(best_block_hash) = self.db.get(db::COL_EXTRA, b"best").unwrap() {
    			let best_block_hash = H256::from_slice(&best_block_hash);
    			if best_block_hash == self.genesis_hash() {
    				return None;
    			}
    			if let Some(extras) = self.db.read(db::COL_EXTRA, &best_block_hash) as Option<BlockDetails> {
    				type DetailsKey = Key<BlockDetails, Target=H264>;
    				batch.delete(db::COL_EXTRA, &(DetailsKey::key(&best_block_hash)));
    				let hash = extras.parent;
    				let range = extras.number as bc::Number .. extras.number as bc::Number;
    				let chain = bc::group::BloomGroupChain::new(self.blooms_config, self);
    				let changes = chain.replace(&range, vec![]);
    				for (k, v) in changes {
    					batch.write(db::COL_EXTRA, &LogGroupPosition::from(k), &BloomGroup::from(v));
    				}
    				batch.put(db::COL_EXTRA, b"best", &hash);

    				let best_block_total_difficulty = self.block_details(&hash).unwrap().total_difficulty;
    				let best_block_rlp = self.block(&hash).unwrap().into_inner();

    				let mut best_block = self.best_block.write();
    				*best_block = BestBlock {
    					number: extras.number - 1,
    					total_difficulty: best_block_total_difficulty,
    					hash: hash,
    					block: best_block_rlp,
    				};
    				// update parent extras
    				if let Some(mut details) = self.db.read(db::COL_EXTRA, &hash) as Option<BlockDetails> {
    					details.children.clear();
    					batch.write(db::COL_EXTRA, &hash, &details);
    				}
    				self.db.write(batch).expect("Writing to db failed");
    				self.block_details.write().clear();
    				self.block_hashes.write().clear();
    				self.block_headers.write().clear();
    				self.block_bodies.write().clear();
    				self.block_receipts.write().clear();
    				return Some(hash);
    			}
    		}

    		None
    	}

    	/// Returns a tree route between `from` and `to`, which is a tuple of:
    	///
    	/// - a vector of hashes of all blocks, ordered from `from` to `to`.
    	///
    	/// - common ancestor of these blocks.
    	///
    	/// - an index where best common ancestor would be
    	///
    	/// 1.) from newer to older
    	///
    	/// - bc: `A1 -> A2 -> A3 -> A4 -> A5`
    	/// - from: A5, to: A4
    	/// - route:
    	///
    	///   ```json
    	///   { blocks: [A5], ancestor: A4, index: 1 }
    	///   ```
    	///
    	/// 2.) from older to newer
    	///
    	/// - bc: `A1 -> A2 -> A3 -> A4 -> A5`
    	/// - from: A3, to: A4
    	/// - route:
    	///
    	///   ```json
    	///   { blocks: [A4], ancestor: A3, index: 0 }
    	///   ```
    	///
    	/// 3.) fork:
    	///
    	/// - bc:
    	///
    	///   ```text
    	///   A1 -> A2 -> A3 -> A4
    	///              -> B3 -> B4
    	///   ```
    	/// - from: B4, to: A4
    	/// - route:
    	///
    	///   ```json
    	///   { blocks: [B4, B3, A3, A4], ancestor: A2, index: 2 }
    	///   ```
    	pub fn tree_route(&self, from: H256, to: H256) -> TreeRoute {
    		let mut from_branch = vec![];
    		let mut to_branch = vec![];

    		let mut from_details = self.block_details(&from).unwrap_or_else(|| panic!("0. Expected to find details for block {:?}", from));
    		let mut to_details = self.block_details(&to).unwrap_or_else(|| panic!("1. Expected to find details for block {:?}", to));
    		let mut current_from = from;
    		let mut current_to = to;

    		// reset from && to to the same level
    		while from_details.number > to_details.number {
    			from_branch.push(current_from);
    			current_from = from_details.parent.clone();
    			from_details = self.block_details(&from_details.parent).unwrap_or_else(|| panic!("2. Expected to find details for block {:?}", from_details.parent));
    		}

    		while to_details.number > from_details.number {
    			to_branch.push(current_to);
    			current_to = to_details.parent.clone();
    			to_details = self.block_details(&to_details.parent).unwrap_or_else(|| panic!("3. Expected to find details for block {:?}", to_details.parent));
    		}

    		assert_eq!(from_details.number, to_details.number);

    		// move to shared parent
    		while current_from != current_to {
    			from_branch.push(current_from);
    			current_from = from_details.parent.clone();
    			from_details = self.block_details(&from_details.parent).unwrap_or_else(|| panic!("4. Expected to find details for block {:?}", from_details.parent));

    			to_branch.push(current_to);
    			current_to = to_details.parent.clone();
    			to_details = self.block_details(&to_details.parent).unwrap_or_else(|| panic!("5. Expected to find details for block {:?}", from_details.parent));
    		}

    		let index = from_branch.len();

    		from_branch.extend(to_branch.into_iter().rev());

    		TreeRoute {
    			blocks: from_branch,
    			ancestor: current_from,
    			index: index
    		}
    	}

    	/// Inserts a verified, known block from the canonical chain.
    	///
    	/// Can be performed out-of-order, but care must be taken that the final chain is in a correct state.
    	/// This is used by snapshot restoration and when downloading missing blocks for the chain gap.
    	/// `is_best` forces the best block to be updated to this block.
    	/// `is_ancient` forces the best block of the first block sequence to be updated to this block.
    	/// Supply a dummy parent total difficulty when the parent block may not be in the chain.
    	/// Returns true if the block is disconnected.
    	pub fn insert_unordered_block(&self, batch: &mut DBTransaction, bytes: &[u8], receipts: Vec<Receipt>, parent_td: Option<U256>, is_best: bool, is_ancient: bool) -> bool {
    		let block = BlockView::new(bytes);
    		let header = block.header_view();
    		let hash = header.sha3();

    		if self.is_known(&hash) {
    			return false;
    		}

    		assert!(self.pending_best_block.read().is_none());

    		let block_rlp = UntrustedRlp::new(bytes);
    		let compressed_header = block_rlp.at(0).unwrap().compress(RlpType::Blocks);
    		let compressed_body = UntrustedRlp::new(&Self::block_to_body(bytes)).compress(RlpType::Blocks);

    		// store block in db
    		batch.put(db::COL_HEADERS, &hash, &compressed_header);
    		batch.put(db::COL_BODIES, &hash, &compressed_body);

    		let maybe_parent = self.block_details(&header.parent_hash());

    		if let Some(parent_details) = maybe_parent {
    			// parent known to be in chain.
    			let info = BlockInfo {
    				hash: hash.clone(),
    				number: header.number(),
    				total_difficulty: parent_details.total_difficulty + header.difficulty(),
    				location: BlockLocation::CanonChain,
    			};

    			self.prepare_update(batch, ExtrasUpdate {
    				block_hashes: self.prepare_block_hashes_update(bytes, &info),
    				block_details: self.prepare_block_details_update(bytes, &info),
    				block_receipts: self.prepare_block_receipts_update(receipts, &info),
    				blocks_blooms: self.prepare_block_blooms_update(bytes, &info),
    				transactions_addresses: self.prepare_transaction_addresses_update(bytes, &info),
    				info: info,
    				block: bytes
    			}, is_best);

    			if is_ancient {
    				let mut best_ancient_block = self.best_ancient_block.write();
    				let ancient_number = best_ancient_block.as_ref().map_or(0, |b| b.number);
    				if self.block_hash(header.number() + 1).is_some() {
    					batch.delete(db::COL_EXTRA, b"ancient");
    					*best_ancient_block = None;
    				} else if header.number() > ancient_number {
    					batch.put(db::COL_EXTRA, b"ancient", &hash);
    					*best_ancient_block = Some(BestAncientBlock {
    						hash: hash,
    						number: header.number(),
    					});
    				}
    			}

    			false
    		} else {
    			// parent not in the chain yet. we need the parent difficulty to proceed.
    			let d = parent_td
    				.expect("parent total difficulty always supplied for first block in chunk. only first block can have missing parent; qed");

    			let info = BlockInfo {
    				hash: hash,
    				number: header.number(),
    				total_difficulty: d + header.difficulty(),
    				location: BlockLocation::CanonChain,
    			};

    			let block_details = BlockDetails {
    				number: header.number(),
    				total_difficulty: info.total_difficulty,
    				parent: header.parent_hash(),
    				children: Vec::new(),
    			};

    			let mut update = HashMap::new();
    			update.insert(hash, block_details);

    			self.prepare_update(batch, ExtrasUpdate {
    				block_hashes: self.prepare_block_hashes_update(bytes, &info),
    				block_details: update,
    				block_receipts: self.prepare_block_receipts_update(receipts, &info),
    				blocks_blooms: self.prepare_block_blooms_update(bytes, &info),
    				transactions_addresses: self.prepare_transaction_addresses_update(bytes, &info),
    				info: info,
    				block: bytes,
    			}, is_best);
    			true
    		}
    	}

    	/// Add a child to a given block. Assumes that the block hash is in
    	/// the chain and the child's parent is this block.
    	///
    	/// Used in snapshots to glue the chunks together at the end.
    	pub fn add_child(&self, batch: &mut DBTransaction, block_hash: H256, child_hash: H256) {
    		let mut parent_details = self.block_details(&block_hash)
    			.unwrap_or_else(|| panic!("Invalid block hash: {:?}", block_hash));

    		parent_details.children.push(child_hash);

    		let mut update = HashMap::new();
    		update.insert(block_hash, parent_details);

    		let mut write_details = self.block_details.write();
    		batch.extend_with_cache(db::COL_EXTRA, &mut *write_details, update, CacheUpdatePolicy::Overwrite);

    		self.cache_man.lock().note_used(CacheId::BlockDetails(block_hash));
    	}

    	#[cfg_attr(feature="dev", allow(similar_names))]
    	/// Inserts the block into backing cache database.
    	/// Expects the block to be valid and already verified.
    	/// If the block is already known, does nothing.
    	pub fn insert_block(&self, batch: &mut DBTransaction, bytes: &[u8], receipts: Vec<Receipt>) -> ImportRoute {
    		// create views onto rlp
    		let block = BlockView::new(bytes);
    		let header = block.header_view();
    		let hash = header.sha3();

    		if self.is_known_child(&header.parent_hash(), &hash) {
    			return ImportRoute::none();
    		}

    		assert!(self.pending_best_block.read().is_none());

    		// store block in db
    		batch.put_compressed(db::COL_HEADERS, &hash, block.header_rlp().as_raw().to_vec());
    		batch.put_compressed(db::COL_BODIES, &hash, Self::block_to_body(bytes));

    		let info = self.block_info(&header);

    		if let BlockLocation::BranchBecomingCanonChain(ref d) = info.location {
    			info!(target: "reorg", "Reorg to {} ({} {} {})",
    				Colour::Yellow.bold().paint(format!("#{} {}", info.number, info.hash)),
    				Colour::Red.paint(d.retracted.iter().join(" ")),
    				Colour::White.paint(format!("#{} {}", self.block_details(&d.ancestor).expect("`ancestor` is in the route; qed").number, d.ancestor)),
    				Colour::Green.paint(d.enacted.iter().join(" "))
    			);
    		}

    		self.prepare_update(batch, ExtrasUpdate {
    			block_hashes: self.prepare_block_hashes_update(bytes, &info),
    			block_details: self.prepare_block_details_update(bytes, &info),
    			block_receipts: self.prepare_block_receipts_update(receipts, &info),
    			blocks_blooms: self.prepare_block_blooms_update(bytes, &info),
    			transactions_addresses: self.prepare_transaction_addresses_update(bytes, &info),
    			info: info.clone(),
    			block: bytes,
    		}, true);

    		ImportRoute::from(info)
    	}

    	/// Get inserted block info which is critical to prepare extras updates.
    	fn block_info(&self, header: &HeaderView) -> BlockInfo {
    		let hash = header.sha3();
    		let number = header.number();
    		let parent_hash = header.parent_hash();
    		let parent_details = self.block_details(&parent_hash).unwrap_or_else(|| panic!("Invalid parent hash: {:?}", parent_hash));
    		let is_new_best = parent_details.total_difficulty + header.difficulty() > self.best_block_total_difficulty();

    		BlockInfo {
    			hash: hash,
    			number: number,
    			total_difficulty: parent_details.total_difficulty + header.difficulty(),
    			location: if is_new_best {
    				// on new best block we need to make sure that all ancestors
    				// are moved to "canon chain"
    				// find the route between old best block and the new one
    				let best_hash = self.best_block_hash();
    				let route = self.tree_route(best_hash, parent_hash);

    				assert_eq!(number, parent_details.number + 1);

    				match route.blocks.len() {
    					0 => BlockLocation::CanonChain,
    					_ => {
    						let retracted = route.blocks.iter().take(route.index).cloned().collect::<Vec<_>>().into_iter().collect::<Vec<_>>();
    						let enacted = route.blocks.into_iter().skip(route.index).collect::<Vec<_>>();
    						BlockLocation::BranchBecomingCanonChain(BranchBecomingCanonChainData {
    							ancestor: route.ancestor,
    							enacted: enacted,
    							retracted: retracted,
    						})
    					}
    				}
    			} else {
    				BlockLocation::Branch
    			}
    		}
    	}

    	/// Prepares extras update.
    	fn prepare_update(&self, batch: &mut DBTransaction, update: ExtrasUpdate, is_best: bool) {

    		{
    			let mut write_receipts = self.block_receipts.write();
    			batch.extend_with_cache(db::COL_EXTRA, &mut *write_receipts, update.block_receipts, CacheUpdatePolicy::Remove);
    		}

    		{
    			let mut write_blocks_blooms = self.blocks_blooms.write();
    			batch.extend_with_cache(db::COL_EXTRA, &mut *write_blocks_blooms, update.blocks_blooms, CacheUpdatePolicy::Remove);
    		}

    		// These cached values must be updated last with all four locks taken to avoid
    		// cache decoherence
    		{
    			let mut best_block = self.pending_best_block.write();
    			// update best block
    			match update.info.location {
    				BlockLocation::Branch => (),
    				_ => if is_best {
    					batch.put(db::COL_EXTRA, b"best", &update.info.hash);
    					*best_block = Some(BestBlock {
    						hash: update.info.hash,
    						number: update.info.number,
    						total_difficulty: update.info.total_difficulty,
    						block: update.block.to_vec(),
    					});
    				},
    			}
    			let mut write_hashes = self.pending_block_hashes.write();
    			let mut write_details = self.pending_block_details.write();
    			let mut write_txs = self.pending_transaction_addresses.write();

    			batch.extend_with_cache(db::COL_EXTRA, &mut *write_details, update.block_details, CacheUpdatePolicy::Overwrite);
    			batch.extend_with_cache(db::COL_EXTRA, &mut *write_hashes, update.block_hashes, CacheUpdatePolicy::Overwrite);
    			batch.extend_with_option_cache(db::COL_EXTRA, &mut *write_txs, update.transactions_addresses, CacheUpdatePolicy::Overwrite);
    		}
    	}

    	/// Apply pending insertion updates
    	pub fn commit(&self) {
    		let mut pending_best_block = self.pending_best_block.write();
    		let mut pending_write_hashes = self.pending_block_hashes.write();
    		let mut pending_block_details = self.pending_block_details.write();
    		let mut pending_write_txs = self.pending_transaction_addresses.write();

    		let mut best_block = self.best_block.write();
    		let mut write_block_details = self.block_details.write();
    		let mut write_hashes = self.block_hashes.write();
    		let mut write_txs = self.transaction_addresses.write();
    		// update best block
    		if let Some(block) = pending_best_block.take() {
    			*best_block = block;
    		}

    		let pending_txs = mem::replace(&mut *pending_write_txs, HashMap::new());
    		let (retracted_txs, enacted_txs) = pending_txs.into_iter().partition::<HashMap<_, _>, _>(|&(_, ref value)| value.is_none());

    		let pending_hashes_keys: Vec<_> = pending_write_hashes.keys().cloned().collect();
    		let enacted_txs_keys: Vec<_> = enacted_txs.keys().cloned().collect();
    		let pending_block_hashes: Vec<_> = pending_block_details.keys().cloned().collect();

    		write_hashes.extend(mem::replace(&mut *pending_write_hashes, HashMap::new()));
    		write_txs.extend(enacted_txs.into_iter().map(|(k, v)| (k, v.expect("Transactions were partitioned; qed"))));
    		write_block_details.extend(mem::replace(&mut *pending_block_details, HashMap::new()));

    		for hash in retracted_txs.keys() {
    			write_txs.remove(hash);
    		}

    		let mut cache_man = self.cache_man.lock();
    		for n in pending_hashes_keys {
    			cache_man.note_used(CacheId::BlockHashes(n));
    		}

    		for hash in enacted_txs_keys {
    			cache_man.note_used(CacheId::TransactionAddresses(hash));
    		}

    		for hash in pending_block_hashes {
    			cache_man.note_used(CacheId::BlockDetails(hash));
    		}
    	}

    	/// Iterator that lists `first` and then all of `first`'s ancestors, by hash.
    	pub fn ancestry_iter(&self, first: H256) -> Option<AncestryIter> {
    		if self.is_known(&first) {
    			Some(AncestryIter {
    				current: first,
    				chain: self,
    			})
    		} else {
    			None
    		}
    	}

    	/// Given a block's `parent`, find every block header which represents a valid possible uncle.
    	pub fn find_uncle_headers(&self, parent: &H256, uncle_generations: usize) -> Option<Vec<Header>> {
    		self.find_uncle_hashes(parent, uncle_generations).map(|v| v.into_iter().filter_map(|h| self.block_header(&h)).collect())
    	}

    	/// Given a block's `parent`, find every block hash which represents a valid possible uncle.
    	pub fn find_uncle_hashes(&self, parent: &H256, uncle_generations: usize) -> Option<Vec<H256>> {
    		if !self.is_known(parent) { return None; }

    		let mut excluded = HashSet::new();
    		let ancestry = match self.ancestry_iter(parent.clone()) {
    			Some(iter) => iter,
    			None => return None,
    		};

    		for a in ancestry.clone().take(uncle_generations) {
    			if let Some(uncles) = self.uncle_hashes(&a) {
    				excluded.extend(uncles);
    				excluded.insert(a);
    			} else {
    				break
    			}
    		}

    		let mut ret = Vec::new();
    		for a in ancestry.skip(1).take(uncle_generations) {
    			if let Some(details) = self.block_details(&a) {
    				ret.extend(details.children.iter().filter(|h| !excluded.contains(h)))
    			} else {
    				break
    			}
    		}

    		Some(ret)
    	}

    	/// This function returns modified block hashes.
    	fn prepare_block_hashes_update(&self, block_bytes: &[u8], info: &BlockInfo) -> HashMap<BlockNumber, H256> {
    		let mut block_hashes = HashMap::new();
    		let block = BlockView::new(block_bytes);
    		let header = block.header_view();
    		let number = header.number();

    		match info.location {
    			BlockLocation::Branch => (),
    			BlockLocation::CanonChain => {
    				block_hashes.insert(number, info.hash.clone());
    			},
    			BlockLocation::BranchBecomingCanonChain(ref data) => {
    				let ancestor_number = self.block_number(&data.ancestor).expect("Block number of ancestor is always in DB");
    				let start_number = ancestor_number + 1;

    				for (index, hash) in data.enacted.iter().cloned().enumerate() {
    					block_hashes.insert(start_number + index as BlockNumber, hash);
    				}

    				block_hashes.insert(number, info.hash.clone());
    			}
    		}

    		block_hashes
    	}

    	/// This function returns modified block details.
    	/// Uses the given parent details or attempts to load them from the database.
    	fn prepare_block_details_update(&self, block_bytes: &[u8], info: &BlockInfo) -> HashMap<H256, BlockDetails> {
    		let block = BlockView::new(block_bytes);
    		let header = block.header_view();
    		let parent_hash = header.parent_hash();

    		// update parent
    		let mut parent_details = self.block_details(&parent_hash).unwrap_or_else(|| panic!("Invalid parent hash: {:?}", parent_hash));
    		parent_details.children.push(info.hash.clone());

    		// create current block details
    		let details = BlockDetails {
    			number: header.number(),
    			total_difficulty: info.total_difficulty,
    			parent: parent_hash.clone(),
    			children: vec![]
    		};

    		// write to batch
    		let mut block_details = HashMap::new();
    		block_details.insert(parent_hash, parent_details);
    		block_details.insert(info.hash.clone(), details);
    		block_details
    	}

    	/// This function returns modified block receipts.
    	fn prepare_block_receipts_update(&self, receipts: Vec<Receipt>, info: &BlockInfo) -> HashMap<H256, BlockReceipts> {
    		let mut block_receipts = HashMap::new();
    		block_receipts.insert(info.hash.clone(), BlockReceipts::new(receipts));
    		block_receipts
    	}

    	/// This function returns modified transaction addresses.
    	fn prepare_transaction_addresses_update(&self, block_bytes: &[u8], info: &BlockInfo) -> HashMap<H256, Option<TransactionAddress>> {
    		let block = BlockView::new(block_bytes);
    		let transaction_hashes = block.transaction_hashes();

    		match info.location {
    			BlockLocation::CanonChain => {
    				transaction_hashes.into_iter()
    					.enumerate()
    					.map(|(i ,tx_hash)| {
    						(tx_hash, Some(TransactionAddress {
    							block_hash: info.hash.clone(),
    							index: i
    						}))
    					})
    					.collect()
    			},
    			BlockLocation::BranchBecomingCanonChain(ref data) => {
    				let addresses = data.enacted.iter()
    					.flat_map(|hash| {
    						let body = self.block_body(hash).expect("Enacted block must be in database.");
    						let hashes = body.transaction_hashes();
    						hashes.into_iter()
    							.enumerate()
    							.map(|(i, tx_hash)| (tx_hash, Some(TransactionAddress {
    								block_hash: hash.clone(),
    								index: i,
    							})))
    							.collect::<HashMap<H256, Option<TransactionAddress>>>()
    					});

    				let current_addresses = transaction_hashes.into_iter()
    					.enumerate()
    					.map(|(i ,tx_hash)| {
    						(tx_hash, Some(TransactionAddress {
    							block_hash: info.hash.clone(),
    							index: i
    						}))
    					});

    				let retracted = data.retracted.iter().flat_map(|hash| {
    					let body = self.block_body(hash).expect("Retracted block must be in database.");
    					let hashes = body.transaction_hashes();
    					hashes.into_iter().map(|hash| (hash, None)).collect::<HashMap<H256, Option<TransactionAddress>>>()
    				});

    				// The order here is important! Don't remove transaction if it was part of enacted blocks as well.
    				retracted.chain(addresses).chain(current_addresses).collect()
    			},
    			BlockLocation::Branch => HashMap::new(),
    		}
    	}

    	/// This functions returns modified blocks blooms.
    	///
    	/// To accelerate blooms lookups, blomms are stored in multiple
    	/// layers (BLOOM_LEVELS, currently 3).
    	/// ChainFilter is responsible for building and rebuilding these layers.
    	/// It returns them in HashMap, where values are Blooms and
    	/// keys are BloomIndexes. BloomIndex represents bloom location on one
    	/// of these layers.
    	///
    	/// To reduce number of queries to databse, block blooms are stored
    	/// in BlocksBlooms structure which contains info about several
    	/// (BLOOM_INDEX_SIZE, currently 16) consecutive blocks blooms.
    	///
    	/// Later, BloomIndexer is used to map bloom location on filter layer (BloomIndex)
    	/// to bloom location in database (BlocksBloomLocation).
    	///
    	fn prepare_block_blooms_update(&self, block_bytes: &[u8], info: &BlockInfo) -> HashMap<LogGroupPosition, BloomGroup> {
    		let block = BlockView::new(block_bytes);
    		let header = block.header_view();

    		let log_blooms = match info.location {
    			BlockLocation::Branch => HashMap::new(),
    			BlockLocation::CanonChain => {
    				let log_bloom = header.log_bloom();
    				if log_bloom.is_zero() {
    					HashMap::new()
    				} else {
    					let chain = bc::group::BloomGroupChain::new(self.blooms_config, self);
    					chain.insert(info.number as bc::Number, Bloom::from(log_bloom).into())
    				}
    			},
    			BlockLocation::BranchBecomingCanonChain(ref data) => {
    				let ancestor_number = self.block_number(&data.ancestor).unwrap();
    				let start_number = ancestor_number + 1;
    				let range = start_number as bc::Number..self.best_block_number() as bc::Number;

    				let mut blooms: Vec<bc::Bloom> = data.enacted.iter()
    					.map(|hash| self.block_header_data(hash).unwrap())
    					.map(|h| h.log_bloom())
    					.map(Bloom::from)
    					.map(Into::into)
    					.collect();

    				blooms.push(Bloom::from(header.log_bloom()).into());

    				let chain = bc::group::BloomGroupChain::new(self.blooms_config, self);
    				chain.replace(&range, blooms)
    			}
    		};

    		log_blooms.into_iter()
    			.map(|p| (From::from(p.0), From::from(p.1)))
    			.collect()
    	}

    	/// Get best block hash.
    	pub fn best_block_hash(&self) -> H256 {
    		self.best_block.read().hash.clone()
    	}

    	/// Get best block number.
    	pub fn best_block_number(&self) -> BlockNumber {
    		self.best_block.read().number
    	}

    	/// Get best block total difficulty.
    	pub fn best_block_total_difficulty(&self) -> U256 {
    		self.best_block.read().total_difficulty
    	}

    	/// Get best block header
    	pub fn best_block_header(&self) -> encoded::Header {
    		let block = self.best_block.read();
    		let raw = BlockView::new(&block.block).header_view().rlp().as_raw().to_vec();
    		encoded::Header::new(raw)
    	}

    	/// Get current cache size.
    	pub fn cache_size(&self) -> CacheSize {
    		CacheSize {
    			blocks: self.block_headers.read().heap_size_of_children() + self.block_bodies.read().heap_size_of_children(),
    			block_details: self.block_details.read().heap_size_of_children(),
    			transaction_addresses: self.transaction_addresses.read().heap_size_of_children(),
    			blocks_blooms: self.blocks_blooms.read().heap_size_of_children(),
    			block_receipts: self.block_receipts.read().heap_size_of_children(),
    		}
    	}

    	/// Ticks our cache system and throws out any old data.
    	pub fn collect_garbage(&self) {
    		let current_size = self.cache_size().total();

    		let mut block_headers = self.block_headers.write();
    		let mut block_bodies = self.block_bodies.write();
    		let mut block_details = self.block_details.write();
    		let mut block_hashes = self.block_hashes.write();
    		let mut transaction_addresses = self.transaction_addresses.write();
    		let mut blocks_blooms = self.blocks_blooms.write();
    		let mut block_receipts = self.block_receipts.write();

    		let mut cache_man = self.cache_man.lock();
    		cache_man.collect_garbage(current_size, | ids | {
    			for id in &ids {
    				match *id {
    					CacheId::BlockHeader(ref h) => { block_headers.remove(h); },
    					CacheId::BlockBody(ref h) => { block_bodies.remove(h); },
    					CacheId::BlockDetails(ref h) => { block_details.remove(h); }
    					CacheId::BlockHashes(ref h) => { block_hashes.remove(h); }
    					CacheId::TransactionAddresses(ref h) => { transaction_addresses.remove(h); }
    					CacheId::BlocksBlooms(ref h) => { blocks_blooms.remove(h); }
    					CacheId::BlockReceipts(ref h) => { block_receipts.remove(h); }
    				}
    			}

    			block_headers.shrink_to_fit();
    			block_bodies.shrink_to_fit();
    			block_details.shrink_to_fit();
    			block_hashes.shrink_to_fit();
    			transaction_addresses.shrink_to_fit();
    			blocks_blooms.shrink_to_fit();
    			block_receipts.shrink_to_fit();

    			block_headers.heap_size_of_children() +
    			block_bodies.heap_size_of_children() +
    			block_details.heap_size_of_children() +
    			block_hashes.heap_size_of_children() +
    			transaction_addresses.heap_size_of_children() +
    			blocks_blooms.heap_size_of_children() +
    			block_receipts.heap_size_of_children()
    		});
    	}

    	/// Create a block body from a block.
    	pub fn block_to_body(block: &[u8]) -> Bytes {
    		let mut body = RlpStream::new_list(2);
    		let block_rlp = Rlp::new(block);
    		body.append_raw(block_rlp.at(1).as_raw(), 1);
    		body.append_raw(block_rlp.at(2).as_raw(), 1);
    		body.out()
    	}

    	/// Returns general blockchain information
    	pub fn chain_info(&self) -> BlockChainInfo {
    		// ensure data consistencly by locking everything first
    		let best_block = self.best_block.read();
    		let best_ancient_block = self.best_ancient_block.read();
    		BlockChainInfo {
    			total_difficulty: best_block.total_difficulty.clone(),
    			pending_total_difficulty: best_block.total_difficulty.clone(),
    			genesis_hash: self.genesis_hash(),
    			best_block_hash: best_block.hash.clone(),
    			best_block_number: best_block.number,
    			first_block_hash: self.first_block(),
    			first_block_number: From::from(self.first_block_number()),
    			ancient_block_hash: best_ancient_block.as_ref().map(|b| b.hash.clone()),
    			ancient_block_number: best_ancient_block.as_ref().map(|b| b.number),
    		}
    	}

    	#[cfg(test)]
    	pub fn db(&self) -> &Arc<Database> {
    		&self.db
    	}
    }

    #[cfg(test)]
    mod tests {
    	#![cfg_attr(feature="dev", allow(similar_names))]
    	use std::sync::Arc;
    	use rustc_serialize::hex::FromHex;
    	use util::{Database, DatabaseConfig};
    	use util::hash::*;
    	use util::sha3::Hashable;
    	use receipt::Receipt;
    	use blockchain::{BlockProvider, BlockChain, Config, ImportRoute};
    	use tests::helpers::*;
    	use devtools::*;
    	use blockchain::generator::{ChainGenerator, ChainIterator, BlockFinalizer};
    	use blockchain::extras::TransactionAddress;
    	use views::BlockView;
    	use transaction::{Transaction, Action};
    	use log_entry::{LogEntry, LocalizedLogEntry};
    	use ethkey::Secret;

    	fn new_db(path: &str) -> Arc<Database> {
    		Arc::new(Database::open(&DatabaseConfig::with_columns(::db::NUM_COLUMNS), path).unwrap())
    	}

    	fn new_chain(genesis: &[u8], db: Arc<Database>) -> BlockChain {
    		BlockChain::new(Config::default(), genesis, db)
    	}

    	#[test]
    	fn should_cache_best_block() {
    		// given
    		let mut canon_chain = ChainGenerator::default();
    		let mut finalizer = BlockFinalizer::default();
    		let genesis = canon_chain.generate(&mut finalizer).unwrap();
    		let first = canon_chain.generate(&mut finalizer).unwrap();

    		let temp = RandomTempPath::new();
    		let db = new_db(temp.as_str());
    		let bc = new_chain(&genesis, db.clone());
    		assert_eq!(bc.best_block_number(), 0);

    		// when
    		let mut batch =db.transaction();
    		bc.insert_block(&mut batch, &first, vec![]);
    		assert_eq!(bc.best_block_number(), 0);
    		bc.commit();
    		// NOTE no db.write here (we want to check if best block is cached)

    		// then
    		assert_eq!(bc.best_block_number(), 1);
    		assert!(bc.block(&bc.best_block_hash()).is_some(), "Best block should be queryable even without DB write.");
    	}

    	#[test]
    	fn basic_blockchain_insert() {
    		let mut canon_chain = ChainGenerator::default();
    		let mut finalizer = BlockFinalizer::default();
    		let genesis = canon_chain.generate(&mut finalizer).unwrap();
    		let first = canon_chain.generate(&mut finalizer).unwrap();
    		let genesis_hash = BlockView::new(&genesis).header_view().sha3();
    		let first_hash = BlockView::new(&first).header_view().sha3();

    		let temp = RandomTempPath::new();
    		let db = new_db(temp.as_str());
    		let bc = new_chain(&genesis, db.clone());

    		assert_eq!(bc.genesis_hash(), genesis_hash.clone());
    		assert_eq!(bc.best_block_hash(), genesis_hash.clone());
    		assert_eq!(bc.block_hash(0), Some(genesis_hash.clone()));
    		assert_eq!(bc.block_hash(1), None);
    		assert_eq!(bc.block_details(&genesis_hash).unwrap().children, vec![]);

    		let mut batch =db.transaction();
    		bc.insert_block(&mut batch, &first, vec![]);
    		db.write(batch).unwrap();
    		bc.commit();

    		assert_eq!(bc.block_hash(0), Some(genesis_hash.clone()));
    		assert_eq!(bc.best_block_number(), 1);
    		assert_eq!(bc.best_block_hash(), first_hash.clone());
    		assert_eq!(bc.block_hash(1), Some(first_hash.clone()));
    		assert_eq!(bc.block_details(&first_hash).unwrap().parent, genesis_hash.clone());
    		assert_eq!(bc.block_details(&genesis_hash).unwrap().children, vec![first_hash.clone()]);
    		assert_eq!(bc.block_hash(2), None);
    	}

    	#[test]
    	fn check_ancestry_iter() {
    		let mut canon_chain = ChainGenerator::default();
    		let mut finalizer = BlockFinalizer::default();
    		let genesis = canon_chain.generate(&mut finalizer).unwrap();
    		let genesis_hash = BlockView::new(&genesis).header_view().sha3();

    		let temp = RandomTempPath::new();
    		let db = new_db(temp.as_str());
    		let bc = new_chain(&genesis, db.clone());

    		let mut block_hashes = vec![genesis_hash.clone()];
    		let mut batch = db.transaction();
    		for _ in 0..10 {
    			let block = canon_chain.generate(&mut finalizer).unwrap();
    			block_hashes.push(BlockView::new(&block).header_view().sha3());
    			bc.insert_block(&mut batch, &block, vec![]);
    			bc.commit();
    		}
    		db.write(batch).unwrap();

    		block_hashes.reverse();

    		assert_eq!(bc.ancestry_iter(block_hashes[0].clone()).unwrap().collect::<Vec<_>>(), block_hashes)
    	}

    	#[test]
    	#[cfg_attr(feature="dev", allow(cyclomatic_complexity))]
    	fn test_find_uncles() {
    		let mut canon_chain = ChainGenerator::default();
    		let mut finalizer = BlockFinalizer::default();
    		let genesis = canon_chain.generate(&mut finalizer).unwrap();
    		let b1b = canon_chain.fork(1).generate(&mut finalizer.fork()).unwrap();
    		let b1a = canon_chain.generate(&mut finalizer).unwrap();
    		let b2b = canon_chain.fork(1).generate(&mut finalizer.fork()).unwrap();
    		let b2a = canon_chain.generate(&mut finalizer).unwrap();
    		let b3b = canon_chain.fork(1).generate(&mut finalizer.fork()).unwrap();
    		let b3a = canon_chain.generate(&mut finalizer).unwrap();
    		let b4b = canon_chain.fork(1).generate(&mut finalizer.fork()).unwrap();
    		let b4a = canon_chain.generate(&mut finalizer).unwrap();
    		let b5b = canon_chain.fork(1).generate(&mut finalizer.fork()).unwrap();
    		let b5a = canon_chain.generate(&mut finalizer).unwrap();

    		let temp = RandomTempPath::new();
    		let db = new_db(temp.as_str());
    		let bc = new_chain(&genesis, db.clone());

    		let mut batch =db.transaction();
    		for b in &[&b1a, &b1b, &b2a, &b2b, &b3a, &b3b, &b4a, &b4b, &b5a, &b5b] {
    			bc.insert_block(&mut batch, b, vec![]);
    			bc.commit();
    		}
    		bc.insert_block(&mut batch, &b1b, vec![]);
    		bc.insert_block(&mut batch, &b2a, vec![]);
    		bc.insert_block(&mut batch, &b2b, vec![]);
    		bc.insert_block(&mut batch, &b3a, vec![]);
    		bc.insert_block(&mut batch, &b3b, vec![]);
    		bc.insert_block(&mut batch, &b4a, vec![]);
    		bc.insert_block(&mut batch, &b4b, vec![]);
    		bc.insert_block(&mut batch, &b5a, vec![]);
    		bc.insert_block(&mut batch, &b5b, vec![]);
    		db.write(batch).unwrap();

    		assert_eq!(
    			[&b4b, &b3b, &b2b].iter().map(|b| BlockView::new(b).header()).collect::<Vec<_>>(),
    			bc.find_uncle_headers(&BlockView::new(&b4a).header_view().sha3(), 3).unwrap()
    		);

    		// TODO: insert block that already includes one of them as an uncle to check it's not allowed.
    	}

    	fn secret() -> Secret {
    		Secret::from_slice(&"".sha3()).unwrap()
    	}

    	#[test]
    	fn test_fork_transaction_addresses() {
    		let mut canon_chain = ChainGenerator::default();
    		let mut finalizer = BlockFinalizer::default();
    		let genesis = canon_chain.generate(&mut finalizer).unwrap();
    		let mut fork_chain = canon_chain.fork(1);
    		let mut fork_finalizer = finalizer.fork();

    		let t1 = Transaction {
    			nonce: 0.into(),
    			gas_price: 0.into(),
    			gas: 100_000.into(),
    			action: Action::Create,
    			value: 100.into(),
    			data: "601080600c6000396000f3006000355415600957005b60203560003555".from_hex().unwrap(),
    		}.sign(&secret(), None);

    		let b1a = canon_chain
    			.with_transaction(t1.clone())
    			.generate(&mut finalizer).unwrap();

    		// Empty block
    		let b1b = fork_chain
    			.generate(&mut fork_finalizer).unwrap();

    		let b2 = fork_chain
    			.generate(&mut fork_finalizer).unwrap();

    		let b1a_hash = BlockView::new(&b1a).header_view().sha3();
    		let b2_hash = BlockView::new(&b2).header_view().sha3();

    		let t1_hash = t1.hash();

    		let temp = RandomTempPath::new();
    		let db = new_db(temp.as_str());
    		let bc = new_chain(&genesis, db.clone());

    		let mut batch = db.transaction();
    		let _ = bc.insert_block(&mut batch, &b1a, vec![]);
    		bc.commit();
    		let _ = bc.insert_block(&mut batch, &b1b, vec![]);
    		bc.commit();
    		db.write(batch).unwrap();

    		assert_eq!(bc.best_block_hash(), b1a_hash);
    		assert_eq!(bc.transaction_address(&t1_hash), Some(TransactionAddress {
    			block_hash: b1a_hash.clone(),
    			index: 0,
    		}));

    		// now let's make forked chain the canon chain
    		let mut batch = db.transaction();
    		let _ = bc.insert_block(&mut batch, &b2, vec![]);
    		bc.commit();
    		db.write(batch).unwrap();

    		// Transaction should be retracted
    		assert_eq!(bc.best_block_hash(), b2_hash);
    		assert_eq!(bc.transaction_address(&t1_hash), None);
    	}

    	#[test]
    	fn test_overwriting_transaction_addresses() {
    		let mut canon_chain = ChainGenerator::default();
    		let mut finalizer = BlockFinalizer::default();
    		let genesis = canon_chain.generate(&mut finalizer).unwrap();
    		let mut fork_chain = canon_chain.fork(1);
    		let mut fork_finalizer = finalizer.fork();

    		let t1 = Transaction {
    			nonce: 0.into(),
    			gas_price: 0.into(),
    			gas: 100_000.into(),
    			action: Action::Create,
    			value: 100.into(),
    			data: "601080600c6000396000f3006000355415600957005b60203560003555".from_hex().unwrap(),
    		}.sign(&secret(), None);

    		let t2 = Transaction {
    			nonce: 1.into(),
    			gas_price: 0.into(),
    			gas: 100_000.into(),
    			action: Action::Create,
    			value: 100.into(),
    			data: "601080600c6000396000f3006000355415600957005b60203560003555".from_hex().unwrap(),
    		}.sign(&secret(), None);

    		let t3 = Transaction {
    			nonce: 2.into(),
    			gas_price: 0.into(),
    			gas: 100_000.into(),
    			action: Action::Create,
    			value: 100.into(),
    			data: "601080600c6000396000f3006000355415600957005b60203560003555".from_hex().unwrap(),
    		}.sign(&secret(), None);

    		let b1a = canon_chain
    			.with_transaction(t1.clone())
    			.with_transaction(t2.clone())
    			.generate(&mut finalizer).unwrap();

    		// insert transactions in different order
    		let b1b = fork_chain
    			.with_transaction(t2.clone())
    			.with_transaction(t1.clone())
    			.generate(&mut fork_finalizer).unwrap();

    		let b2 = fork_chain
    			.with_transaction(t3.clone())
    			.generate(&mut fork_finalizer).unwrap();

    		let b1a_hash = BlockView::new(&b1a).header_view().sha3();
    		let b1b_hash = BlockView::new(&b1b).header_view().sha3();
    		let b2_hash = BlockView::new(&b2).header_view().sha3();

    		let t1_hash = t1.hash();
    		let t2_hash = t2.hash();
    		let t3_hash = t3.hash();

    		let temp = RandomTempPath::new();
    		let db = new_db(temp.as_str());
    		let bc = new_chain(&genesis, db.clone());

    		let mut batch = db.transaction();
    		let _ = bc.insert_block(&mut batch, &b1a, vec![]);
    		bc.commit();
    		let _ = bc.insert_block(&mut batch, &b1b, vec![]);
    		bc.commit();
    		db.write(batch).unwrap();

    		assert_eq!(bc.best_block_hash(), b1a_hash);
    		assert_eq!(bc.transaction_address(&t1_hash), Some(TransactionAddress {
    			block_hash: b1a_hash.clone(),
    			index: 0,
    		}));
    		assert_eq!(bc.transaction_address(&t2_hash), Some(TransactionAddress {
    			block_hash: b1a_hash.clone(),
    			index: 1,
    		}));

    		// now let's make forked chain the canon chain
    		let mut batch = db.transaction();
    		let _ = bc.insert_block(&mut batch, &b2, vec![]);
    		bc.commit();
    		db.write(batch).unwrap();

    		assert_eq!(bc.best_block_hash(), b2_hash);
    		assert_eq!(bc.transaction_address(&t1_hash), Some(TransactionAddress {
    			block_hash: b1b_hash.clone(),
    			index: 1,
    		}));
    		assert_eq!(bc.transaction_address(&t2_hash), Some(TransactionAddress {
    			block_hash: b1b_hash.clone(),
    			index: 0,
    		}));
    		assert_eq!(bc.transaction_address(&t3_hash), Some(TransactionAddress {
    			block_hash: b2_hash.clone(),
    			index: 0,
    		}));
    	}

    	#[test]
    	#[cfg_attr(feature="dev", allow(cyclomatic_complexity))]
    	fn test_small_fork() {
    		let mut canon_chain = ChainGenerator::default();
    		let mut finalizer = BlockFinalizer::default();
    		let genesis = canon_chain.generate(&mut finalizer).unwrap();
    		let b1 = canon_chain.generate(&mut finalizer).unwrap();
    		let b2 = canon_chain.generate(&mut finalizer).unwrap();
    		let b3b = canon_chain.fork(1).generate(&mut finalizer.fork()).unwrap();
    		let b3a = canon_chain.generate(&mut finalizer).unwrap();

    		let genesis_hash = BlockView::new(&genesis).header_view().sha3();
    		let b1_hash= BlockView::new(&b1).header_view().sha3();
    		let b2_hash= BlockView::new(&b2).header_view().sha3();
    		let b3a_hash= BlockView::new(&b3a).header_view().sha3();
    		let b3b_hash= BlockView::new(&b3b).header_view().sha3();

    		// b3a is a part of canon chain, whereas b3b is part of sidechain
    		let best_block_hash = b3a_hash.clone();

    		let temp = RandomTempPath::new();
    		let db = new_db(temp.as_str());
    		let bc = new_chain(&genesis, db.clone());

    		let mut batch = db.transaction();
    		let ir1 = bc.insert_block(&mut batch, &b1, vec![]);
    		bc.commit();
    		let ir2 = bc.insert_block(&mut batch, &b2, vec![]);
    		bc.commit();
    		let ir3b = bc.insert_block(&mut batch, &b3b, vec![]);
    		bc.commit();
    		db.write(batch).unwrap();
    		assert_eq!(bc.block_hash(3).unwrap(), b3b_hash);
    		let mut batch =db.transaction();
    		let ir3a = bc.insert_block(&mut batch, &b3a, vec![]);
    		bc.commit();
    		db.write(batch).unwrap();

    		assert_eq!(ir1, ImportRoute {
    			enacted: vec![b1_hash],
    			retracted: vec![],
    			omitted: vec![],
    		});

    		assert_eq!(ir2, ImportRoute {
    			enacted: vec![b2_hash],
    			retracted: vec![],
    			omitted: vec![],
    		});

    		assert_eq!(ir3b, ImportRoute {
    			enacted: vec![b3b_hash],
    			retracted: vec![],
    			omitted: vec![],
    		});

    		assert_eq!(ir3a, ImportRoute {
    			enacted: vec![b3a_hash],
    			retracted: vec![b3b_hash],
    			omitted: vec![],
    		});

    		assert_eq!(bc.best_block_hash(), best_block_hash);
    		assert_eq!(bc.block_number(&genesis_hash).unwrap(), 0);
    		assert_eq!(bc.block_number(&b1_hash).unwrap(), 1);
    		assert_eq!(bc.block_number(&b2_hash).unwrap(), 2);
    		assert_eq!(bc.block_number(&b3a_hash).unwrap(), 3);
    		assert_eq!(bc.block_number(&b3b_hash).unwrap(), 3);

    		assert_eq!(bc.block_hash(0).unwrap(), genesis_hash);
    		assert_eq!(bc.block_hash(1).unwrap(), b1_hash);
    		assert_eq!(bc.block_hash(2).unwrap(), b2_hash);
    		assert_eq!(bc.block_hash(3).unwrap(), b3a_hash);

    		// test trie route
    		let r0_1 = bc.tree_route(genesis_hash.clone(), b1_hash.clone());
    		assert_eq!(r0_1.ancestor, genesis_hash);
    		assert_eq!(r0_1.blocks, [b1_hash.clone()]);
    		assert_eq!(r0_1.index, 0);

    		let r0_2 = bc.tree_route(genesis_hash.clone(), b2_hash.clone());
    		assert_eq!(r0_2.ancestor, genesis_hash);
    		assert_eq!(r0_2.blocks, [b1_hash.clone(), b2_hash.clone()]);
    		assert_eq!(r0_2.index, 0);

    		let r1_3a = bc.tree_route(b1_hash.clone(), b3a_hash.clone());
    		assert_eq!(r1_3a.ancestor, b1_hash);
    		assert_eq!(r1_3a.blocks, [b2_hash.clone(), b3a_hash.clone()]);
    		assert_eq!(r1_3a.index, 0);

    		let r1_3b = bc.tree_route(b1_hash.clone(), b3b_hash.clone());
    		assert_eq!(r1_3b.ancestor, b1_hash);
    		assert_eq!(r1_3b.blocks, [b2_hash.clone(), b3b_hash.clone()]);
    		assert_eq!(r1_3b.index, 0);

    		let r3a_3b = bc.tree_route(b3a_hash.clone(), b3b_hash.clone());
    		assert_eq!(r3a_3b.ancestor, b2_hash);
    		assert_eq!(r3a_3b.blocks, [b3a_hash.clone(), b3b_hash.clone()]);
    		assert_eq!(r3a_3b.index, 1);

    		let r1_0 = bc.tree_route(b1_hash.clone(), genesis_hash.clone());
    		assert_eq!(r1_0.ancestor, genesis_hash);
    		assert_eq!(r1_0.blocks, [b1_hash.clone()]);
    		assert_eq!(r1_0.index, 1);

    		let r2_0 = bc.tree_route(b2_hash.clone(), genesis_hash.clone());
    		assert_eq!(r2_0.ancestor, genesis_hash);
    		assert_eq!(r2_0.blocks, [b2_hash.clone(), b1_hash.clone()]);
    		assert_eq!(r2_0.index, 2);

    		let r3a_1 = bc.tree_route(b3a_hash.clone(), b1_hash.clone());
    		assert_eq!(r3a_1.ancestor, b1_hash);
    		assert_eq!(r3a_1.blocks, [b3a_hash.clone(), b2_hash.clone()]);
    		assert_eq!(r3a_1.index, 2);

    		let r3b_1 = bc.tree_route(b3b_hash.clone(), b1_hash.clone());
    		assert_eq!(r3b_1.ancestor, b1_hash);
    		assert_eq!(r3b_1.blocks, [b3b_hash.clone(), b2_hash.clone()]);
    		assert_eq!(r3b_1.index, 2);

    		let r3b_3a = bc.tree_route(b3b_hash.clone(), b3a_hash.clone());
    		assert_eq!(r3b_3a.ancestor, b2_hash);
    		assert_eq!(r3b_3a.blocks, [b3b_hash.clone(), b3a_hash.clone()]);
    		assert_eq!(r3b_3a.index, 1);
    	}

    	#[test]
    	fn test_reopen_blockchain_db() {
    		let mut canon_chain = ChainGenerator::default();
    		let mut finalizer = BlockFinalizer::default();
    		let genesis = canon_chain.generate(&mut finalizer).unwrap();
    		let first = canon_chain.generate(&mut finalizer).unwrap();
    		let genesis_hash = BlockView::new(&genesis).header_view().sha3();
    		let first_hash = BlockView::new(&first).header_view().sha3();

    		let temp = RandomTempPath::new();
    		{
    			let db = new_db(temp.as_str());
    			let bc = new_chain(&genesis, db.clone());
    			assert_eq!(bc.best_block_hash(), genesis_hash);
    			let mut batch =db.transaction();
    			bc.insert_block(&mut batch, &first, vec![]);
    			db.write(batch).unwrap();
    			bc.commit();
    			assert_eq!(bc.best_block_hash(), first_hash);
    		}

    		{
    			let db = new_db(temp.as_str());
    			let bc = new_chain(&genesis, db.clone());

    			assert_eq!(bc.best_block_hash(), first_hash);
    		}
    	}

    	#[test]
    	fn can_contain_arbitrary_block_sequence() {
    		let bc_result = generate_dummy_blockchain(50);
    		let bc = bc_result.reference();
    		assert_eq!(bc.best_block_number(), 49);
    	}

    	#[test]
    	fn can_collect_garbage() {
    		let bc_result = generate_dummy_blockchain(3000);
    		let bc = bc_result.reference();

    		assert_eq!(bc.best_block_number(), 2999);
    		let best_hash = bc.best_block_hash();
    		let mut block_header = bc.block_header(&best_hash);

    		while !block_header.is_none() {
    			block_header = bc.block_header(block_header.unwrap().parent_hash());
    		}
    		assert!(bc.cache_size().blocks > 1024 * 1024);

    		for _ in 0..2 {
    			bc.collect_garbage();
    		}
    		assert!(bc.cache_size().blocks < 1024 * 1024);
    	}

    	#[test]
    	fn can_contain_arbitrary_block_sequence_with_extra() {
    		let bc_result = generate_dummy_blockchain_with_extra(25);
    		let bc = bc_result.reference();
    		assert_eq!(bc.best_block_number(), 24);
    	}

    	#[test]
    	fn can_contain_only_genesis_block() {
    		let bc_result = generate_dummy_empty_blockchain();
    		let bc = bc_result.reference();
    		assert_eq!(bc.best_block_number(), 0);
    	}

    	#[test]
    	fn find_transaction_by_hash() {
    		let genesis = " ".from_hex().unwrap();
    		let b1 = " ".from_hex().unwrap();
    		let b1_hash: H256 = "f53f268d23a71e85c7d6d83a9504298712b84c1a2ba220441c86eeda0bf0b6e3".into();

    		let temp = RandomTempPath::new();
    		let db = new_db(temp.as_str());
    		let bc = new_chain(&genesis, db.clone());
    		let mut batch =db.transaction();
    		bc.insert_block(&mut batch, &b1, vec![]);
    		db.write(batch).unwrap();
    		bc.commit();

    		let transactions = bc.transactions(&b1_hash).unwrap();
    		assert_eq!(transactions.len(), 7);
    		for t in transactions {
    			assert_eq!(bc.transaction(&bc.transaction_address(&t.hash()).unwrap()).unwrap(), t);
    		}
    	}

    	fn insert_block(db: &Arc<Database>, bc: &BlockChain, bytes: &[u8], receipts: Vec<Receipt>) -> ImportRoute {
    		let mut batch = db.transaction();
    		let res = bc.insert_block(&mut batch, bytes, receipts);
    		db.write(batch).unwrap();
    		bc.commit();
    		res
    	}

    	#[test]
    	fn test_logs() {
    		// given
    		let mut canon_chain = ChainGenerator::default();
    		let mut finalizer = BlockFinalizer::default();
    		let genesis = canon_chain.generate(&mut finalizer).unwrap();
    		// just insert dummy transaction so that #transactions=#receipts
    		let t1 = Transaction {
    			nonce: 0.into(),
    			gas_price: 0.into(),
    			gas: 100_000.into(),
    			action: Action::Create,
    			value: 101.into(),
    			data: "601080600c6000396000f3006000355415600957005b60203560003555".from_hex().unwrap(),
    		}.sign(&secret(), None);
    		let t2 = Transaction {
    			nonce: 0.into(),
    			gas_price: 0.into(),
    			gas: 100_000.into(),
    			action: Action::Create,
    			value: 102.into(),
    			data: "601080600c6000396000f3006000355415600957005b60203560003555".from_hex().unwrap(),
    		}.sign(&secret(), None);
    		let t3 = Transaction {
    			nonce: 0.into(),
    			gas_price: 0.into(),
    			gas: 100_000.into(),
    			action: Action::Create,
    			value: 103.into(),
    			data: "601080600c6000396000f3006000355415600957005b60203560003555".from_hex().unwrap(),
    		}.sign(&secret(), None);
    		let tx_hash1 = t1.hash();
    		let tx_hash2 = t2.hash();
    		let tx_hash3 = t3.hash();
    		let b1 = canon_chain.with_transaction(t1).with_transaction(t2).generate(&mut finalizer).unwrap();
    		let b2 = canon_chain.with_transaction(t3).generate(&mut finalizer).unwrap();

    		let temp = RandomTempPath::new();
    		let db = new_db(temp.as_str());
    		let bc = new_chain(&genesis, db.clone());
    		insert_block(&db, &bc, &b1, vec![Receipt {
    			state_root: Some(H256::default()),
    			gas_used: 10_000.into(),
    			log_bloom: Default::default(),
    			logs: vec![
    				LogEntry { address: Default::default(), topics: vec![], data: vec![1], },
    				LogEntry { address: Default::default(), topics: vec![], data: vec![2], },
    			],
    		},
    		Receipt {
    			state_root: Some(H256::default()),
    			gas_used: 10_000.into(),
    			log_bloom: Default::default(),
    			logs: vec![
    				LogEntry { address: Default::default(), topics: vec![], data: vec![3], },
    			],
    		}]);
    		insert_block(&db, &bc, &b2, vec![
    			Receipt {
    				state_root: Some(H256::default()),
    				gas_used: 10_000.into(),
    				log_bloom: Default::default(),
    				logs: vec![
    					LogEntry { address: Default::default(), topics: vec![], data: vec![4], },
    				],
    			}
    		]);

    		// when
    		let block1 = BlockView::new(&b1);
    		let block2 = BlockView::new(&b2);
    		let logs1 = bc.logs(vec![1, 2], |_| true, None);
    		let logs2 = bc.logs(vec![1, 2], |_| true, Some(1));

    		// then
    		assert_eq!(logs1, vec![
    			LocalizedLogEntry {
    				entry: LogEntry { address: Default::default(), topics: vec![], data: vec![1] },
    				block_hash: block1.hash(),
    				block_number: block1.header().number(),
    				transaction_hash: tx_hash1.clone(),
    				transaction_index: 0,
    				transaction_log_index: 0,
    				log_index: 0,
    			},
    			LocalizedLogEntry {
    				entry: LogEntry { address: Default::default(), topics: vec![], data: vec![2] },
    				block_hash: block1.hash(),
    				block_number: block1.header().number(),
    				transaction_hash: tx_hash1.clone(),
    				transaction_index: 0,
    				transaction_log_index: 1,
    				log_index: 1,
    			},
    			LocalizedLogEntry {
    				entry: LogEntry { address: Default::default(), topics: vec![], data: vec![3] },
    				block_hash: block1.hash(),
    				block_number: block1.header().number(),
    				transaction_hash: tx_hash2.clone(),
    				transaction_index: 1,
    				transaction_log_index: 0,
    				log_index: 2,
    			},
    			LocalizedLogEntry {
    				entry: LogEntry { address: Default::default(), topics: vec![], data: vec![4] },
    				block_hash: block2.hash(),
    				block_number: block2.header().number(),
    				transaction_hash: tx_hash3.clone(),
    				transaction_index: 0,
    				transaction_log_index: 0,
    				log_index: 0,
    			}
    		]);
    		assert_eq!(logs2, vec![
    			LocalizedLogEntry {
    				entry: LogEntry { address: Default::default(), topics: vec![], data: vec![4] },
    				block_hash: block2.hash(),
    				block_number: block2.header().number(),
    				transaction_hash: tx_hash3.clone(),
    				transaction_index: 0,
    				transaction_log_index: 0,
    				log_index: 0,
    			}
    		]);
    	}

    	#[test]
    	fn test_bloom_filter_simple() {
    		// TODO: From here
    		let bloom_b1: H2048 = " ".into();

    		let bloom_b2: H2048 = " ".into();

    		let bloom_ba: H2048 = " ".into();

    		let mut canon_chain = ChainGenerator::default();
    		let mut finalizer = BlockFinalizer::default();
    		let genesis = canon_chain.generate(&mut finalizer).unwrap();
    		let mut fork = canon_chain.fork(1);
    		let mut fork_finalizer = finalizer.fork();
    		let b1 = fork.with_bloom(bloom_b1.clone()).generate(&mut fork_finalizer).unwrap();
    		let b2 = fork.with_bloom(bloom_b2.clone()).generate(&mut fork_finalizer).unwrap();
    		let b3 = fork.with_bloom(bloom_ba.clone()).generate(&mut fork_finalizer).unwrap();
    		let b1a = canon_chain.with_bloom(bloom_ba.clone()).generate(&mut finalizer).unwrap();
    		let b2a = canon_chain.with_bloom(bloom_ba.clone()).generate(&mut finalizer).unwrap();

    		let temp = RandomTempPath::new();
    		let db = new_db(temp.as_str());
    		let bc = new_chain(&genesis, db.clone());

    		let blocks_b1 = bc.blocks_with_bloom(&bloom_b1, 0, 5);
    		let blocks_b2 = bc.blocks_with_bloom(&bloom_b2, 0, 5);
    		assert_eq!(blocks_b1, vec![]);
    		assert_eq!(blocks_b2, vec![]);

    		insert_block(&db, &bc, &b1, vec![]);
    		let blocks_b1 = bc.blocks_with_bloom(&bloom_b1, 0, 5);
    		let blocks_b2 = bc.blocks_with_bloom(&bloom_b2, 0, 5);
    		assert_eq!(blocks_b1, vec![1]);
    		assert_eq!(blocks_b2, vec![]);

    		insert_block(&db, &bc, &b2, vec![]);
    		let blocks_b1 = bc.blocks_with_bloom(&bloom_b1, 0, 5);
    		let blocks_b2 = bc.blocks_with_bloom(&bloom_b2, 0, 5);
    		assert_eq!(blocks_b1, vec![1]);
    		assert_eq!(blocks_b2, vec![2]);

    		// hasn't been forked yet
    		insert_block(&db, &bc, &b1a, vec![]);
    		let blocks_b1 = bc.blocks_with_bloom(&bloom_b1, 0, 5);
    		let blocks_b2 = bc.blocks_with_bloom(&bloom_b2, 0, 5);
    		let blocks_ba = bc.blocks_with_bloom(&bloom_ba, 0, 5);
    		assert_eq!(blocks_b1, vec![1]);
    		assert_eq!(blocks_b2, vec![2]);
    		assert_eq!(blocks_ba, vec![]);

    		// fork has happend
    		insert_block(&db, &bc, &b2a, vec![]);
    		let blocks_b1 = bc.blocks_with_bloom(&bloom_b1, 0, 5);
    		let blocks_b2 = bc.blocks_with_bloom(&bloom_b2, 0, 5);
    		let blocks_ba = bc.blocks_with_bloom(&bloom_ba, 0, 5);
    		assert_eq!(blocks_b1, vec![]);
    		assert_eq!(blocks_b2, vec![]);
    		assert_eq!(blocks_ba, vec![1, 2]);

    		// fork back
    		insert_block(&db, &bc, &b3, vec![]);
    		let blocks_b1 = bc.blocks_with_bloom(&bloom_b1, 0, 5);
    		let blocks_b2 = bc.blocks_with_bloom(&bloom_b2, 0, 5);
    		let blocks_ba = bc.blocks_with_bloom(&bloom_ba, 0, 5);
    		assert_eq!(blocks_b1, vec![1]);
    		assert_eq!(blocks_b2, vec![2]);
    		assert_eq!(blocks_ba, vec![3]);
    	}

    	#[test]
    	fn test_best_block_update() {
    		let mut canon_chain = ChainGenerator::default();
    		let mut finalizer = BlockFinalizer::default();
    		let genesis = canon_chain.generate(&mut finalizer).unwrap();

    		let temp = RandomTempPath::new();

    		{
    			let db = new_db(temp.as_str());
    			let bc = new_chain(&genesis, db.clone());
    			let uncle = canon_chain.fork(1).generate(&mut finalizer.fork()).unwrap();

    			let mut batch =db.transaction();
    			// create a longer fork
    			for _ in 0..5 {
    				let canon_block = canon_chain.generate(&mut finalizer).unwrap();
    				bc.insert_block(&mut batch, &canon_block, vec![]);
    				bc.commit();
    			}

    			assert_eq!(bc.best_block_number(), 5);
    			bc.insert_block(&mut batch, &uncle, vec![]);
    			db.write(batch).unwrap();
    			bc.commit();
    		}

    		// re-loading the blockchain should load the correct best block.
    		let db = new_db(temp.as_str());
    		let bc = new_chain(&genesis, db.clone());
    		assert_eq!(bc.best_block_number(), 5);
    	}

    	#[test]
    	fn test_rewind() {
    		let mut canon_chain = ChainGenerator::default();
    		let mut finalizer = BlockFinalizer::default();
    		let genesis = canon_chain.generate(&mut finalizer).unwrap();
    		let first = canon_chain.generate(&mut finalizer).unwrap();
    		let second = canon_chain.generate(&mut finalizer).unwrap();
    		let genesis_hash = BlockView::new(&genesis).header_view().sha3();
    		let first_hash = BlockView::new(&first).header_view().sha3();
    		let second_hash = BlockView::new(&second).header_view().sha3();

    		let temp = RandomTempPath::new();
    		let db = new_db(temp.as_str());
    		let bc = new_chain(&genesis, db.clone());

    		let mut batch =db.transaction();
    		bc.insert_block(&mut batch, &first, vec![]);
    		bc.commit();
    		bc.insert_block(&mut batch, &second, vec![]);
    		bc.commit();
    		db.write(batch).unwrap();

    		assert_eq!(bc.rewind(), Some(first_hash.clone()));
    		assert!(!bc.is_known(&second_hash));
    		assert_eq!(bc.best_block_number(), 1);
    		assert_eq!(bc.best_block_hash(), first_hash.clone());

    		assert_eq!(bc.rewind(), Some(genesis_hash.clone()));
    		assert_eq!(bc.rewind(), None);
    	}
    }

# Help

## Keyboard Shortcuts

?
  Show this help dialog
S
  Focus the search field
⇤
  Move up in search results
⇥
  Move down in search results
⏎
  Go to active search result
+
  Collapse/expand all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)