-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlock.java
More file actions
68 lines (55 loc) · 2.02 KB
/
Block.java
File metadata and controls
68 lines (55 loc) · 2.02 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
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.Date;
import java.util.ArrayList;
public class Block {
public String hash;
public String previousHash;
public String merkleRoot;
public ArrayList<Transaction> transactions = new ArrayList<Transaction>();
public int difficulty;
public long timeStamp;
private int nonce;
// Block Constructor
public Block( String previoushash){
this.previousHash = previoushash;
this.timeStamp = new Date().getTime();
this.hash = calculateHash();
}
public String calculateHash() {
String calculatehash = StringUtil.applySha256(
previousHash +
Long.toString(timeStamp) +
Integer.toString(nonce) +
merkleRoot
);
return calculatehash;
}
public void mineBlock(int difficulty) {
this.difficulty = difficulty;
String target = new String(new char[difficulty]).replace('\0', '0');
while (!hash.substring(0, difficulty).equals(target)) {
nonce++;
hash = calculateHash();
}
System.out.println("Block Mined!!! : " + hash);
}
public void addCoinbase(Transaction coinbase){
transactions.add(coinbase);
merkleRoot = Transaction.getMerkleRoot(transactions);
System.out.println("Coinbase transaction added to block");
}
// 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.equals("0"))) {
if((!transaction.processTransaction())) {
System.out.println("Transaction failed to process. Discarded.");
return false;
}
}
transactions.add(transaction);
merkleRoot = Transaction.getMerkleRoot(transactions);
System.out.println("Transaction Successfully added to Block");
return true;
}
}