-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBlock.java
72 lines (51 loc) · 1.64 KB
/
Block.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
package sw2_a2;
import java.util.Date;
public class Block {
public String hash;//signature
public String previousHash;
private String data; //our data will be a simple message.
private long timeStamp;
private int nonce; //changed on each iteration till the leading 0 hash is found
ArrayList <Transaction> transaction = new ArrayList <>();
public Block(String previousHash ) {
this.previousHash = previousHash;
this.timeStamp = new Date().getTime();
this.hash = calculateHash();
}
public Block(String data,String previousHash ) {
this.data = data;
this.previousHash = previousHash;
this.timeStamp = new Date().getTime();
this.hash = calculateHash();
}
public String calculateHash() {
String calculatedhash = StringUtil.applySha256(
previousHash +
Long.toString(timeStamp) +
Integer.toString(nonce)+
data );
return calculatedhash;
}
public void mineBlock(int difficulty) {
String target = new String(new
char[difficulty]).replace('\0', '0');
//Create a string with difficulty * "0"
while(!hash.substring( 0, difficulty).equals(target)) {
nonce ++;
hash = calculateHash();
}
System.out.println("Block Mined : " + hash);
}
public boolean addTransaction(Transaction transaction){
if(transaction == null){return false;}
if(previousHash != "0"){
if(transaction.processTransaction() == false){
System.out.println("Transaction failled.");
return false;
}
}
transactions.add(transaction);
System.out.println("successfully,Transaction added.");
return true;
}
}