-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBlock.java
More file actions
93 lines (74 loc) · 2.38 KB
/
Block.java
File metadata and controls
93 lines (74 loc) · 2.38 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.ByteBuffer;
/**
* A Block class that keeps track of each individual
* unit of the BlockChain.
* Has two constructors, with the first finding a nonce
* and the second requiring one to be found beforehand.
* Also includes the static hashing method.
*/
public class Block {
//fields-------------------------------------------------------------
private int num;
private int data;
private Hash prevHash;
private long nonce = -1;
private Hash hash;
//constructors-------------------------------------------------------
public Block(int num, int amount, Hash prevHash) throws NoSuchAlgorithmException {
this.num = num;
this.data = amount;
this.prevHash = prevHash;
//Generate hash
boolean nonceFound = false;
long nonce = -1;
while (this.nonce == -1) {
nonce++;
Hash hash = new Hash(Block.calculateHash(num, amount, prevHash, nonce));
if (hash.isValid()) {
this.nonce = nonce;
this.hash = hash;
}
}
}
public Block(int num, int amount, Hash prevHash, long nonce) throws NoSuchAlgorithmException {
this.num = num;
this.data = amount;
this.prevHash = prevHash;
this.nonce = nonce;
//Generate hash
this.hash = new Hash(Block.calculateHash(num, amount, prevHash, nonce));
}
//methods---------------------------------------------------------------
public int getNum() {
return this.num;
}
public int getAmount() {
return this.data;
}
public long getNonce() {
return this.nonce;
}
public Hash getPrevHash() {
return this.prevHash;
}
public Hash getHash() {
return this.hash;
}
public String toString() {
return "Block " + this.getNum() + " (Amount: " + this.getAmount()
+ ", Nonce: " + this.getNonce() + ", prevHash: " + this.getPrevHash()
+ ", hash: " + this.getHash() + ")";
}
public static byte[] calculateHash(int num, int data, Hash prevHash, long nonce) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("sha-256");
md.update(ByteBuffer.allocate(4).putInt(num).array());
md.update(ByteBuffer.allocate(4).putInt(data).array());
if (prevHash != null) {
md.update(prevHash.getData());
}
md.update(ByteBuffer.allocate(12).putLong(nonce).array());
return md.digest();
}
}