-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlock.java
More file actions
56 lines (52 loc) · 1.56 KB
/
Block.java
File metadata and controls
56 lines (52 loc) · 1.56 KB
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
import java.util.ArrayList;
import java.util.Calendar;
public class Block implements java.io.Serializable{
private static final long serialVersionUID = 1L;
private int difficultyLevel = 22;
private ArrayList<String> transactions = new ArrayList<String>();
private long timestamp;
private String previousBlockHashID;
private int nonce = 0;
private String hashID;
public Block(String previousBlockHashID, int difficultyLevel) {
this.previousBlockHashID = previousBlockHashID;
this.timestamp = UtilityMethods.getTimeStamp();
this.difficultyLevel = difficultyLevel;
}
protected String computeHashID() {
StringBuilder sb = new StringBuilder();
sb.append(this.previousBlockHashID + Long.toHexString(this.timestamp));
for(String t : transactions) {
sb.append(t);
}
sb.append(Integer.toHexString(this.difficultyLevel) + nonce);
byte[] b = UtilityMethods.messageDigestSHA256_toBytes(sb.toString());
return UtilityMethods.toBinaryString(b);
}
public void addTransaction(String s) {
this.transactions.add(s);
}
public String getHashID() {
return this.hashID;
}
public int getNonce() {
return this.nonce;
}
public long getTimeStamp() {
return this.timestamp;
}
public String getPreviousBlockHashID() {
return this.previousBlockHashID;
}
protected boolean mineTheBlock() {
this.hashID = this.computeHashID();
while(!UtilityMethods.hashMeetsDifficultyLevel(this.hashID, this.difficultyLevel)) {
this.nonce++;
this.hashID = this.computeHashID();
}
return true;
}
public int getDifficultyLevel() {
return this.difficultyLevel;
}
}