/
HashDigest.cs
282 lines (257 loc) · 10.7 KB
/
HashDigest.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
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
#nullable enable
using System;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Security.Cryptography;
namespace Libplanet
{
/// <summary>
/// A value type to represent digest bytes determined by a
/// <see cref="HashAlgorithm"/>. For more type safety, it takes
/// a type parameter <typeparamref name="T"/> of
/// <see cref="HashAlgorithm"/>.
/// </summary>
/// <typeparam name="T">A <see cref="HashAlgorithm"/> which corresponds to
/// a digest. This determines <see cref="Size"/> of a digest.</typeparam>
/// <seealso cref="HashAlgorithm"/>
public readonly struct HashDigest<T> : IEquatable<HashDigest<T>>
where T : HashAlgorithm
{
/// <summary>
/// The fixed, and valid <see cref="Array.Length"/> of
/// a <see cref="byte"/> array of every digest.
/// <para>This varies depending upon what <see cref="HashAlgorithm"/> is
/// used for <typeparamref name="T"/>. For example, if <typeparamref
/// name="T"/> is <see cref="SHA1"/> <see cref="Size"/> is <c>20</c>,
/// and if <see cref="SHA256"/> it is <c>32</c>.</para>
/// </summary>
public static readonly int Size;
private static readonly byte[] _defaultByteArray;
private readonly ImmutableArray<byte> _byteArray;
static HashDigest()
{
MethodInfo? method = typeof(T).GetMethod("Create", new Type[0]);
T thunk = method?.Invoke(null, new object[0]) as T
?? throw new InvalidCastException($"Failed to instantiate {typeof(T).FullName}.");
Size = thunk.HashSize / 8;
_defaultByteArray = new byte[Size];
}
/// <summary>
/// Converts a <see cref="byte"/> array into a
/// <see cref="HashDigest{T}"/>.
/// </summary>
/// <param name="hashDigest">A <see cref="byte"/> array that encodes
/// a <see cref="HashDigest{T}"/>. It must not be <c>null</c>,
/// and its <see cref="Array.Length"/> must be the same to
/// <see cref="Size"/>.</param>
/// <exception cref="ArgumentNullException">Thrown when the given
/// <paramref name="hashDigest"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the given
/// <paramref name="hashDigest"/>'s <see cref="Array.Length"/> is not
/// the same to the <see cref="Size"/> the hash algorithm
/// (i.e., <typeparamref name="T"/> requires.</exception>
public HashDigest(byte[] hashDigest)
: this((hashDigest ?? throw new ArgumentNullException(nameof(hashDigest)))
.ToImmutableArray())
{
}
/// <summary>
/// Converts a <see cref="ImmutableArray"/> of <see cref="byte"/> array into a
/// <see cref="HashDigest{T}"/>.
/// </summary>
/// <param name="hashDigest">A <see cref="byte"/> array that encodes
/// a <see cref="HashDigest{T}"/>. It must not be <c>null</c>,
/// and its <see cref="Array.Length"/> must be the same to
/// <see cref="Size"/>.</param>
/// <exception cref="ArgumentNullException">Thrown when the given
/// <paramref name="hashDigest"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the given
/// <paramref name="hashDigest"/>'s <see cref="ImmutableArray{T}.Length"/> is not
/// the same to the <see cref="Size"/> the hash algorithm
/// (i.e., <typeparamref name="T"/> requires.</exception>
public HashDigest(ImmutableArray<byte> hashDigest)
{
if (hashDigest.Length != Size)
{
string message =
$"HashDigest<{typeof(T).Name}> must be {Size} bytes, " +
$"but {hashDigest.Length} was given";
throw new ArgumentOutOfRangeException(
nameof(hashDigest),
message
);
}
_byteArray = hashDigest;
}
/// <summary>
/// A bare immutable <see cref="byte"/> array of the digest.
/// </summary>
/// <remarks>It is immutable. For a mutable array, use
/// <see cref="ToByteArray()"/> method instead.</remarks>
/// <seealso cref="ToByteArray()"/>
public ImmutableArray<byte> ByteArray
{
get
{
if (_byteArray.IsDefault)
{
return _defaultByteArray.ToImmutableArray();
}
return _byteArray;
}
}
/// <summary>
/// Converts a given hexadecimal representation of a digest into
/// a <see cref="HashDigest{T}"/> object.
/// <para>This is an inverse function of <see cref="ToString()"/>
/// method.</para>
/// </summary>
/// <param name="hexDigest">A hexadecimal representation of
/// a <see cref="HashDigest{T}"/>.</param>
/// <returns>A corresponding <see cref="HashDigest{T}"/> value.
/// </returns>
/// <exception cref="ArgumentNullException">Thrown when the given
/// <paramref name="hexDigest"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the given
/// <paramref name="hexDigest"/>'s length is not the double of
/// the <see cref="Size"/>, the hash algorithm
/// (i.e., <typeparamref name="T"/> requires.</exception>
/// <seealso cref="ToString()"/>
/// <seealso cref="HashDigestExtensions.ToHashDigest{T}(string)"/>
[Pure]
public static HashDigest<T> FromString(string hexDigest)
{
if (hexDigest == null)
{
throw new ArgumentNullException(nameof(hexDigest));
}
if (hexDigest.Length != Size * 2)
{
string message =
$"HashDigest<{typeof(T).Name}> requires {Size * 2} " +
$"hexadecimal letters, but {hexDigest.Length} was given";
throw new ArgumentOutOfRangeException(
nameof(hexDigest),
message
);
}
return new HashDigest<T>(ByteUtil.ParseHex(hexDigest));
}
/// <summary>
/// Tests if a digest is less than the target computed for the given
/// <paramref name="difficulty"/>).
/// </summary>
/// <param name="difficulty">The difficulty to compute target number.
/// </param>
/// <returns><c>true</c> only if a digest is less than the target
/// computed for the given <paramref name="difficulty"/>).
/// If <paramref name="difficulty"/> is <c>0</c> it always returns
/// <c>true</c>.
/// </returns>
[Pure]
public bool Satisfies(long difficulty)
{
if (difficulty == 0)
{
return true;
}
double maxTarget = Math.Pow(2, 256);
var target = new BigInteger(maxTarget / difficulty);
// Add zero to convert unsigned BigInteger
var result = new BigInteger(ByteArray.Add(0).ToArray());
return result < target;
}
/// <summary>
/// Gets a bare mutable <see cref="byte"/> array of the digest.
/// </summary>
/// <returns>A new mutable <see cref="byte"/> array of the digest.
/// Since a returned array is created every time the method is called,
/// any mutations on that array does not affect to the digest object.
/// </returns>
/// <seealso cref="ByteArray"/>
[Pure]
public byte[] ToByteArray() => ByteArray.IsDefault
? _defaultByteArray
: ByteArray.ToArray();
/// <summary>
/// Gets a hexadecimal representation of a digest.
/// <para>This is an inverse function of <see cref="FromString"/>.
/// </para>
/// </summary>
/// <returns>A hexadecimal representation of a digest.</returns>
/// <seealso cref="FromString(string)"/>
[Pure]
public override string ToString()
{
return ByteUtil.Hex(ToByteArray());
}
[Pure]
public override bool Equals(object? obj)
{
return obj is IEquatable<HashDigest<T>> other
&& other.Equals(this);
}
[Pure]
public override int GetHashCode()
{
int code = 0;
unchecked
{
foreach (byte b in ByteArray)
{
code = (code * 397) ^ b.GetHashCode();
}
}
return code;
}
[Pure]
bool IEquatable<HashDigest<T>>.Equals(HashDigest<T> other)
{
for (int i = 0; i < Size; i++)
{
if (!ByteArray[i].Equals(other.ByteArray[i]))
{
return false;
}
}
return true;
}
}
/// <summary>
/// Augments types to have some shortcut methods dealing with
/// <see cref="HashDigest{T}"/> values.
/// </summary>
public static class HashDigestExtensions
{
/// <summary>
/// Converts a given hexadecimal representation of a digest into
/// a <see cref="HashDigest{T}"/> object.
/// <para>This is a shortcut of
/// <see cref="HashDigest{T}.FromString(string)"/> method.</para>
/// <para>This is an inverse function of
/// <see cref="HashDigest{T}.ToString()"/> method.</para>
/// </summary>
/// <param name="hexDigest">A hexadecimal representation of
/// a <see cref="HashDigest{T}"/>.</param>
/// <typeparam name="T">A <see cref="HashAlgorithm"/> which corresponds
/// to a digest.</typeparam>
/// <returns>A corresponding <see cref="HashDigest{T}"/> value.
/// </returns>
/// <exception cref="ArgumentNullException">Thrown when the given
/// <paramref name="hexDigest"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the given
/// <paramref name="hexDigest"/>'s length is not the double of
/// the <see cref="HashDigest{T}.Size"/>, the hash algorithm
/// (i.e., <typeparamref name="T"/> requires.</exception>
/// <seealso cref="HashDigest{T}.FromString(string)"/>
/// <seealso cref="HashDigest{T}.ToString()"/>
public static HashDigest<T> ToHashDigest<T>(this string hexDigest)
where T : HashAlgorithm
{
return HashDigest<T>.FromString(hexDigest);
}
}
}