110
|
1 package christie.blockchain;
|
|
2
|
|
3 import org.bouncycastle.util.Arrays;
|
|
4 import org.bouncycastle.util.BigIntegers;
|
|
5
|
|
6 import java.io.ByteArrayOutputStream;
|
|
7 import java.math.BigInteger;
|
|
8 import java.nio.charset.Charset;
|
|
9
|
|
10
|
|
11 public class Miner {
|
|
12
|
|
13 HashUtil hashUtil = new HashUtil();
|
|
14
|
|
15
|
|
16 public void mineBlock(Block newBlock, int difficulty) {
|
|
17 long nonce = 0;
|
|
18
|
|
19
|
|
20 //byte[] target = new String(new char[difficulty]).replace('\0', '0').getBytes();
|
|
21 String target = new String(new char[difficulty]).replace('\0', '0');
|
|
22 byte[] hash = newBlock.getPresentHashWithoutNonce();
|
|
23
|
|
24 String hashStr = new String(hashUtil.sha256(hash), Charset.forName("utf-8"));
|
|
25
|
|
26
|
|
27 while(!hashStr.substring( 0, difficulty).equals(target)) {
|
|
28 nonce ++;
|
|
29 byte[] concat = Arrays.concatenate(hash, BigInteger.valueOf(nonce).toByteArray());
|
|
30 hashStr = new String(hashUtil.sha256(concat), Charset.forName("utf-8"));
|
|
31 }
|
|
32 newBlock.setNonce(nonce);
|
|
33 System.out.println("Block Mined!!! : " + hashStr);
|
|
34
|
|
35
|
|
36
|
|
37 }
|
|
38
|
|
39 public boolean increment(byte[] bytes) {
|
|
40 final int startIndex = 0;
|
|
41 int i;
|
|
42 for (i = bytes.length - 1; i >= startIndex; i--) {
|
|
43 bytes[i]++;
|
|
44 if (bytes[i] != 0)
|
|
45 break;
|
|
46 }
|
|
47
|
|
48 return (i >= startIndex || bytes[startIndex] != 0);
|
|
49 }
|
|
50
|
|
51 public int compareTo(byte[] buffer1, int offset1, int length1,
|
|
52 byte[] buffer2, int offset2, int length2) {
|
|
53 // Short circuit equal case
|
|
54 if (buffer1 == buffer2 &&
|
|
55 offset1 == offset2 &&
|
|
56 length1 == length2) {
|
|
57 return 0;
|
|
58 }
|
|
59 int end1 = offset1 + length1;
|
|
60 int end2 = offset2 + length2;
|
|
61 for (int i = offset1, j = offset2; i < end1 && j < end2; i++, j++) {
|
|
62 int a = (buffer1[i] & 0xff);
|
|
63 int b = (buffer2[j] & 0xff);
|
|
64 if (a != b) {
|
|
65 return a - b;
|
|
66 }
|
|
67 }
|
|
68 return length1 - length2;
|
|
69 }
|
|
70 }
|