-
Notifications
You must be signed in to change notification settings - Fork 15
/
Sha256Hash.java
298 lines (262 loc) · 8.85 KB
/
Sha256Hash.java
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
package org.tron.common.utils;
/*
* Copyright 2011 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.io.ByteStreams;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import com.google.protobuf.ByteString;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
/**
* A Sha256Hash just wraps a byte[] so that equals and hashcode work correctly, allowing it to be
* used as keys in a map. It also checks that the length is correct and provides a bit more type
* safety.
*/
public class Sha256Hash implements Serializable, Comparable<Sha256Hash> {
public static final int LENGTH = 32; // bytes
public static final Sha256Hash ZERO_HASH = wrap(new byte[LENGTH]);
private final byte[] bytes;
private long blockNum;
private byte[] generateBlockId(long blockNum, Sha256Hash blockHash) {
byte[] numBytes = Longs.toByteArray(blockNum);
byte[] hash = blockHash.getBytes();
System.arraycopy(numBytes, 0, hash, 0, 8);
return hash;
}
private byte[] generateBlockId(long blockNum, byte[] blockHash) {
byte[] numBytes = Longs.toByteArray(blockNum);
byte[] hash = blockHash;
System.arraycopy(numBytes, 0, hash, 0, 8);
return hash;
}
public long getBlockNum(){
return blockNum;
}
public Sha256Hash(long num, byte[] hash) {
byte[] rawHashBytes = this.generateBlockId(num, hash);
checkArgument(rawHashBytes.length == LENGTH);
this.bytes = rawHashBytes;
this.blockNum = num;
}
public Sha256Hash(long num, Sha256Hash hash) {
byte[] rawHashBytes = this.generateBlockId(num, hash);
checkArgument(rawHashBytes.length == LENGTH);
this.bytes = rawHashBytes;
this.blockNum = num;
}
/**
* Use {@link #wrap(byte[])} instead.
*/
@Deprecated
public Sha256Hash(byte[] rawHashBytes) {
checkArgument(rawHashBytes.length == LENGTH);
this.bytes = rawHashBytes;
}
/**
* Creates a new instance that wraps the given hash value.
*
* @param rawHashBytes the raw hash bytes to wrap
* @return a new instance
* @throws IllegalArgumentException if the given array length is not exactly 32
*/
@SuppressWarnings("deprecation") // the constructor will be made private in the future
public static Sha256Hash wrap(byte[] rawHashBytes) {
return new Sha256Hash(rawHashBytes);
}
public static Sha256Hash wrap(ByteString rawHashByteString) {
return wrap(rawHashByteString.toByteArray());
}
/**
* Use {@link #of(byte[])} instead: this old name is ambiguous.
*/
@Deprecated
public static Sha256Hash create(byte[] contents) {
return of(contents);
}
/**
* Creates a new instance containing the calculated (one-time) hash of the given bytes.
*
* @param contents the bytes on which the hash value is calculated
* @return a new instance containing the calculated (one-time) hash
*/
public static Sha256Hash of(byte[] contents) {
return wrap(hash(contents));
}
/**
* Creates a new instance containing the calculated (one-time) hash of the given file's contents.
* The file contents are read fully into memory, so this method should only be used with small
* files.
*
* @param file the file on which the hash value is calculated
* @return a new instance containing the calculated (one-time) hash
* @throws IOException if an error occurs while reading the file
*/
public static Sha256Hash of(File file) throws IOException {
try (FileInputStream in = new FileInputStream(file)) {
return of(ByteStreams.toByteArray(in));
}
}
/**
* Use {@link #twiceOf(byte[])} instead: this old name is ambiguous.
*/
@Deprecated
public static Sha256Hash createDouble(byte[] contents) {
return twiceOf(contents);
}
/**
* Creates a new instance containing the hash of the calculated hash of the given bytes.
*
* @param contents the bytes on which the hash value is calculated
* @return a new instance containing the calculated (two-time) hash
*/
public static Sha256Hash twiceOf(byte[] contents) {
return wrap(hashTwice(contents));
}
/**
* Returns a new SHA-256 MessageDigest instance. This is a convenience method which wraps the
* checked exception that can never occur with a RuntimeException.
*
* @return a new SHA-256 MessageDigest instance
*/
public static MessageDigest newDigest() {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e); // Can't happen.
}
}
/**
* Calculates the SHA-256 hash of the given bytes.
*
* @param input the bytes to hash
* @return the hash (in big-endian order)
*/
public static byte[] hash(byte[] input) {
return hash(input, 0, input.length);
}
/**
* Calculates the SHA-256 hash of the given byte range.
*
* @param input the array containing the bytes to hash
* @param offset the offset within the array of the bytes to hash
* @param length the number of bytes to hash
* @return the hash (in big-endian order)
*/
public static byte[] hash(byte[] input, int offset, int length) {
MessageDigest digest = newDigest();
digest.update(input, offset, length);
return digest.digest();
}
/**
* Calculates the SHA-256 hash of the given bytes, and then hashes the resulting hash again.
*
* @param input the bytes to hash
* @return the double-hash (in big-endian order)
*/
public static byte[] hashTwice(byte[] input) {
return hashTwice(input, 0, input.length);
}
/**
* Calculates the SHA-256 hash of the given byte range, and then hashes the resulting hash again.
*
* @param input the array containing the bytes to hash
* @param offset the offset within the array of the bytes to hash
* @param length the number of bytes to hash
* @return the double-hash (in big-endian order)
*/
public static byte[] hashTwice(byte[] input, int offset, int length) {
MessageDigest digest = newDigest();
digest.update(input, offset, length);
return digest.digest(digest.digest());
}
/**
* Calculates the hash of hash on the given byte ranges. This is equivalent to concatenating the
* two ranges and then passing the result to {@link #hashTwice(byte[])}.
*/
public static byte[] hashTwice(byte[] input1, int offset1, int length1,
byte[] input2, int offset2, int length2) {
MessageDigest digest = newDigest();
digest.update(input1, offset1, length1);
digest.update(input2, offset2, length2);
return digest.digest(digest.digest());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || !(o instanceof Sha256Hash)) {
return false;
}
return Arrays.equals(bytes, ((Sha256Hash) o).bytes);
}
@Override
public String toString() {
return ByteArray.toHexString(bytes);
}
/**
* Returns the last four bytes of the wrapped hash. This should be unique enough to be a suitable
* hash code even for blocks, where the goal is to try and get the first bytes to be zeros (i.e.
* the value as a big integer lower than the target value).
*/
@Override
public int hashCode() {
// Use the last 4 bytes, not the first 4 which are often zeros in Bitcoin.
return Ints
.fromBytes(bytes[LENGTH - 4], bytes[LENGTH - 3], bytes[LENGTH - 2], bytes[LENGTH - 1]);
}
/**
* Returns the bytes interpreted as a positive integer.
*/
public BigInteger toBigInteger() {
return new BigInteger(1, bytes);
}
/**
* Returns the internal byte array, without defensively copying. Therefore do NOT modify the
* returned array.
*/
public byte[] getBytes() {
return bytes;
}
/**
* For pb return ByteString.
*/
public ByteString getByteString() {
return ByteString.copyFrom(bytes);
}
@Override
public int compareTo(final Sha256Hash other) {
for (int i = LENGTH - 1; i >= 0; i--) {
final int thisByte = this.bytes[i] & 0xff;
final int otherByte = other.bytes[i] & 0xff;
if (thisByte > otherByte) {
return 1;
}
if (thisByte < otherByte) {
return -1;
}
}
return 0;
}
}