|
3 | 3 | import java.util.Date;
|
4 | 4 |
|
5 | 5 | public class Block {
|
6 |
| - |
7 |
| - public String hash; |
8 |
| - public String previousHash; |
9 |
| - private String data; //our data will be a simple message. |
10 |
| - private long timeStamp; //as number of milliseconds since 1/1/1970. |
11 |
| - private int nonce; |
12 |
| - |
13 |
| - //Block Constructor. |
14 |
| - public Block(String data,String previousHash ) { |
15 |
| - this.data = data; |
16 |
| - this.previousHash = previousHash; |
17 |
| - this.timeStamp = new Date().getTime(); |
18 |
| - |
19 |
| - this.hash = calculateHash(); //Making sure we do this after we set the other values. |
20 |
| - } |
21 |
| - |
22 |
| - //Calculate new hash based on blocks contents |
23 |
| - public String calculateHash() { |
24 |
| - String calculatedhash = StringUtil.applySha256( |
25 |
| - previousHash + |
26 |
| - Long.toString(timeStamp) + |
27 |
| - Integer.toString(nonce) + |
28 |
| - data |
29 |
| - ); |
30 |
| - return calculatedhash; |
31 |
| - } |
32 |
| - |
33 |
| - //Increases nonce value until hash target is reached. |
34 |
| - public void mineBlock(int difficulty) { |
35 |
| - String target = StringUtil.getDificultyString(difficulty); //Create a string with difficulty * "0" |
36 |
| - while(!hash.substring( 0, difficulty).equals(target)) { |
37 |
| - nonce ++; |
38 |
| - hash = calculateHash(); |
39 |
| - } |
40 |
| - System.out.println("Block Mined!!! : " + hash); |
41 |
| - } |
42 |
| - |
| 6 | + |
| 7 | + public String hash; |
| 8 | + public String previousHash; |
| 9 | + private final String data; //our data will be a simple message. |
| 10 | + private final long timeStamp; //as number of milliseconds since 1/1/1970. |
| 11 | + private int nonce; |
| 12 | + |
| 13 | + //Block Constructor. |
| 14 | + public Block(String data, String previousHash) { |
| 15 | + this.data = data; |
| 16 | + this.previousHash = previousHash; |
| 17 | + this.timeStamp = new Date().getTime(); |
| 18 | + |
| 19 | + this.hash = calculateHash(); //Making sure we do this after we set the other values. |
| 20 | + } |
| 21 | + |
| 22 | + //Calculate new hash based on blocks contents |
| 23 | + public String calculateHash() { |
| 24 | + return StringUtil.applySha256( |
| 25 | + previousHash + |
| 26 | + timeStamp + |
| 27 | + nonce + |
| 28 | + data |
| 29 | + ); |
| 30 | + } |
| 31 | + |
| 32 | + //Increases nonce value until hash target is reached. |
| 33 | + public void mineBlock(int difficulty) { |
| 34 | + String target = StringUtil.getDifficultyString(difficulty); //Create a string with difficulty * "0" |
| 35 | + while (!hash.substring(0, difficulty).equals(target)) { |
| 36 | + nonce++; |
| 37 | + hash = calculateHash(); |
| 38 | + } |
| 39 | + System.out.println("Block Mined!!! : " + hash); |
| 40 | + } |
| 41 | + |
43 | 42 | }
|
0 commit comments