-
Notifications
You must be signed in to change notification settings - Fork 139
/
BlockLocator.cs
79 lines (70 loc) · 2.47 KB
/
BlockLocator.cs
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
using System;
using System.Collections;
using System.Collections.Generic;
using Libplanet.Blocks;
namespace Libplanet.Blockchain
{
/// <summary>
/// A class that contains the hashes for a series of blocks.
/// </summary>
public class BlockLocator : IEnumerable<BlockHash>
{
private readonly IEnumerable<BlockHash> _impl;
/// <summary>
/// Initializes a new instance of <see cref="BlockLocator"/> with a set of indexer
/// functions, sampling after <paramref name="sampleAfter"/> number of blocks.
/// </summary>
/// <param name="indexBlockHash">A function that converts an index to a
/// <see cref="BlockHash"/>.</param>
/// <param name="indexByBlockHash">A function that converts a <see cref="BlockHash"/> to its
/// index.</param>
/// <param name="sampleAfter">The number of consequent blocks to include before sampling.
/// </param>
public BlockLocator(
Func<long, BlockHash?> indexBlockHash,
Func<BlockHash, long> indexByBlockHash,
int sampleAfter = 10
)
{
BlockHash? current = indexBlockHash(-1);
long step = 1;
var hashes = new List<BlockHash>();
while (current is { } hash)
{
hashes.Add(hash);
long currentBlockIndex = indexByBlockHash(hash);
if (currentBlockIndex == 0)
{
break;
}
long nextIndex = Math.Max(currentBlockIndex - step, 0);
current = indexBlockHash(nextIndex);
if (hashes.Count >= sampleAfter)
{
step *= 2;
}
}
_impl = hashes;
}
/// <summary>
/// Initializes a new instance of <see cref="BlockLocator"/> from <paramref name="hashes"/>.
/// </summary>
/// <param name="hashes">Enumerable of <see cref="BlockHash"/>es to convert from.</param>
public BlockLocator(IEnumerable<BlockHash> hashes)
{
_impl = hashes;
}
/// <summary>
/// Gets the enumerator.
/// </summary>
/// <returns>The enumerator.</returns>
public IEnumerator<BlockHash> GetEnumerator()
{
return _impl.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _impl.GetEnumerator();
}
}
}