forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBlockchain.java
182 lines (160 loc) · 5.78 KB
/
Blockchain.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
package com.rampatra.blockchain;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
/**
* @author rampatra
* @since 2019-03-05
*/
public class Blockchain {
private List<Block> blocks;
private int difficulty;
public Blockchain(List<Block> blocks, int difficulty) {
this.blocks = blocks;
this.difficulty = difficulty;
this.blocks.add(getGenesisBlock());
}
public List<Block> getBlocks() {
return blocks;
}
public int getSize() {
return blocks.size();
}
public Block getLatestBlock() {
if (blocks.isEmpty()) return null;
return blocks.get(blocks.size() - 1);
}
public void addBlock(Block block) {
blocks.add(block);
}
/**
* Mine, create a new block with the {@code data}, and finally, add it to the blockchain.
* <p>
* Mining is nothing but the process of calculating a hash of a {@link Block} with {@code data} such
* that the hash starts with a specific number of zeros equal to the difficulty of the blockchain.
*
* @param data
* @return
*/
public Block mine(String data) {
Block previousBlock = getLatestBlock();
Block nextBlock = getNextBlock(previousBlock, data);
if (isValidNextBlock(previousBlock, nextBlock)) {
blocks.add(nextBlock);
return nextBlock;
} else {
throw new RuntimeException("Invalid block");
}
}
/**
* Executes the {@link Blockchain#isValidNextBlock(Block, Block)} on the entire blockchain.
*
* @return {@code false} if at least one block in the blockchain is invalid, {@code true} otherwise.
*/
public boolean isValidChain() {
ListIterator<Block> listIterator = blocks.listIterator();
listIterator.next();
while (listIterator.hasPrevious() && listIterator.hasNext()) {
if (!isValidNextBlock(listIterator.previous(), listIterator.next())) {
return false;
}
}
return true;
}
/**
* Creates the Genesis Block for the blockchain. The Genesis Block is the first block in the blockchain.
*
* @return the genesis block
*/
private Block getGenesisBlock() {
final long timestamp = new Date().getTime();
int nonce = 0;
String data = "Blockchain in Java";
String hash;
while (!isValidHashDifficulty(hash = calculateHashForBlock(0, "0", timestamp, data, nonce))) {
nonce++;
}
return new Block(0, "0", timestamp, data, hash, nonce);
}
private Block getNextBlock(Block previousBlock, String data) {
final int index = previousBlock.getIndex() + 1;
final long timestamp = new Date().getTime();
int nonce = 0;
String hash;
while (!isValidHashDifficulty(
hash = calculateHashForBlock(index, previousBlock.getHash(), timestamp, data, nonce))) {
nonce++;
}
return new Block(index, previousBlock.getHash(), timestamp, data, hash, nonce);
}
private boolean isValidNextBlock(Block previousBlock, Block nextBlock) {
String nextBlockHash = calculateHashForBlock(nextBlock.getIndex(), previousBlock.getHash(),
nextBlock.getTimestamp(), nextBlock.getData(), nextBlock.getNonce());
if (previousBlock.getIndex() + 1 != nextBlock.getIndex()) {
return false;
} else if (!previousBlock.getHash().equals(nextBlock.getPreviousHash())) {
return false;
} else if (!this.isValidHashDifficulty(nextBlockHash)) {
return false;
} else if (!nextBlockHash.equals(nextBlock.getHash())) {
return false;
} else {
return true;
}
}
/**
* Checks if the hash respects the difficulty of the blockchain, i.e, if the hash
* begins with a number of zeros equal to the difficulty of the blockchain.
*
* @param hash the SHA256 hash of the block.
* @return {@code true} if hash obeys difficulty, {@code false} otherwise.
*/
private boolean isValidHashDifficulty(String hash) {
for (int i = 0; i < difficulty; i++) {
if (hash.charAt(i) != '0') {
return false;
}
}
return true;
}
/**
* Calculates the SHA256 hash of the block.
*
* @param index
* @param previousHash
* @param timestamp
* @param data
* @param nonce
* @return the SHA256 hash of the block.
*/
private String calculateHashForBlock(final int index, final String previousHash, final long timestamp,
final String data, final int nonce) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] encodedhash = digest.digest(
(index + previousHash + timestamp + data + nonce).getBytes(StandardCharsets.UTF_8));
return bytesToHex(encodedhash);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Encryption Error: {}", e);
}
}
private static String bytesToHex(byte[] hash) {
StringBuilder hexString = new StringBuilder();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Blockchain{");
sb.append("blocks=").append(blocks);
sb.append('}');
return sb.toString();
}
}