-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBlock.java
57 lines (47 loc) · 2.02 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
import java.util.ArrayList;
import java.util.Date;
public class Block {
public String hash, previousHash, merkleRoot;
public ArrayList<Transaction> transactions = new ArrayList<Transaction>(); // our data will be a simple message
private long timeStamp; // number of milliseconds since 1/1/1970
private int nonce;
public Block(String previousHash) {
this.previousHash = previousHash;
this.timeStamp = new Date().getTime();
this.hash = calculateHash(); // **this must be done after the other values are set
}
// Calculate new hash based on blocks contents
public String calculateHash() {
String calculatedhash = StringUtil.applySha256(
previousHash +
Long.toString(timeStamp) +
Integer.toString(nonce) +
merkleRoot
);
return calculatedhash;
}
// Increases nonce value until hash target is reached.
public void mineBlock(int difficulty) {
merkleRoot = StringUtil.getMerkleRoot(transactions);
String target = StringUtil.getDifficultyString(difficulty); // Create a String with difficulty * "0"
while (!hash.substring(0, difficulty).equals(target)) {
nonce ++;
hash = calculateHash();
}
System.out.println("Block Mined!!! : " + hash);
}
// Add transactions to this block.
public boolean addTransaction(Transaction transaction) {
// process transaction and check if valid, unless block is genesis block then ignore.
if (transaction == null) return false;
if (previousHash != "0") {
if (transaction.processTransaction() != true) {
System.out.println("Transaction failed to process. Discarded.");
return false;
}
}
transactions.add(transaction);
System.out.println("Transaction successfully added to Block.");
return true;
}
}