-
Notifications
You must be signed in to change notification settings - Fork 0
/
Blockchain.java
71 lines (58 loc) · 2.68 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
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package blockchain;
import java.util.ArrayList;
import java.util.List;
public class Blockchain {
public static void main(String[] args) {
List<Block> blockChainList = new ArrayList<>();
Block genesis = new Block("BlockChain", 0);
blockChainList.add(genesis);
Block helloBlock = new Block("Hello", blockChainList.get(blockChainList.size() - 1).getHash());
blockChainList.add(helloBlock);
Block worldBlock = new Block("World", blockChainList.get(blockChainList.size() - 1).getHash());
blockChainList.add(worldBlock);
System.out.println("---------------------");
System.out.println("- BlockChain -");
System.out.println("---------------------");
System.out.println("Hash helloBlock"+ helloBlock.getHash());
System.out.println("PreviousHash WorldBlock"+ worldBlock.getPreviousHash());
System.out.println("---------------------");
System.out.println("Is valid?: " + validate(blockChainList));
System.out.println("---------------------");
// corrupt block chain by modifying one of the block
Block hiBlock = new Block("Hi", genesis.getHash());
int index = blockChainList.indexOf(helloBlock);
blockChainList.remove(index);
blockChainList.add(index, hiBlock);
System.out.println("Corrupted block chain by replacing 'Hello' block with 'Hi' Block");
System.out.println("---------------------");
System.out.println("- BlockChain -");
System.out.println("---------------------");
System.out.println("Hash hiBlock"+ hiBlock.getHash());
System.out.println("PreviousHash WorldBlock"+ worldBlock.getPreviousHash());
System.out.println("---------------------");
System.out.println("Is valid?: " + validate(blockChainList));
System.out.println("---------------------");
}
private static boolean validate(List<Block> blockChain) {
boolean result = true;
Block lastBlock = null;
for (int i = blockChain.size() - 1; i >= 0; i--) {
if (lastBlock == null) {
lastBlock = blockChain.get(i);
} else {
Block current = blockChain.get(i);
if (lastBlock.getPreviousHash() != current.getHash()) {
result = false;
break;
}
lastBlock = current;
}
}
return result;
}
}