Skip to content

Commit 081619f

Browse files
committed
Introduce recent header cache (to speed up header sync)
1 parent fae6db0 commit 081619f

1 file changed

Lines changed: 21 additions & 4 deletions

File tree

src/Blockcore/Consensus/LeveldbChainStore.cs

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,12 @@ public class LeveldbChainStore : IChainStore, IDisposable
1616
/// <summary>
1717
/// Headers that are close to the tip
1818
/// </summary>
19-
private readonly MemoryCountCache<uint256, BlockHeader> headers;
19+
private readonly MemoryCountCache<uint256, BlockHeader> nearTipHeaders;
20+
21+
/// <summary>
22+
/// Headers that are close to the tip
23+
/// </summary>
24+
private readonly MemoryCountCache<uint256, BlockHeader> recentHeaders;
2025

2126
private readonly DB leveldb;
2227

@@ -27,7 +32,8 @@ public LeveldbChainStore(Network network, DataFolder dataFolder, ChainIndexer ch
2732
this.network = network;
2833
this.ChainIndexer = chainIndexer;
2934
// this.headers = new Dictionary<uint256, BlockHeader>();
30-
this.headers = new MemoryCountCache<uint256, BlockHeader>(601);
35+
this.nearTipHeaders = new MemoryCountCache<uint256, BlockHeader>(601);
36+
this.recentHeaders = new MemoryCountCache<uint256, BlockHeader>(100);
3137
this.locker = new object();
3238

3339
// Open a connection to a new DB and create if not found
@@ -39,7 +45,12 @@ public LeveldbChainStore(Network network, DataFolder dataFolder, ChainIndexer ch
3945

4046
public BlockHeader GetHeader(ChainedHeader chainedHeader, uint256 hash)
4147
{
42-
if (this.headers.TryGetValue(hash, out BlockHeader blockHeader))
48+
if (this.nearTipHeaders.TryGetValue(hash, out BlockHeader blockHeader))
49+
{
50+
return blockHeader;
51+
}
52+
53+
if (this.recentHeaders.TryGetValue(hash, out blockHeader))
4354
{
4455
return blockHeader;
4556
}
@@ -61,7 +72,13 @@ public BlockHeader GetHeader(ChainedHeader chainedHeader, uint256 hash)
6172

6273
// If the header is 500 blocks behind tip or 100 blocks ahead cache it.
6374
if ((chainedHeader.Height > this.ChainIndexer.Height - 500) && (chainedHeader.Height <= this.ChainIndexer.Height + 100))
64-
this.headers.AddOrUpdate(hash, blockHeader);
75+
{
76+
this.nearTipHeaders.AddOrUpdate(hash, blockHeader);
77+
}
78+
else
79+
{
80+
this.recentHeaders.AddOrUpdate(hash, blockHeader);
81+
}
6582

6683
return blockHeader;
6784
}

0 commit comments

Comments
 (0)