-
Notifications
You must be signed in to change notification settings - Fork 0
/
Blockchain.java
62 lines (53 loc) · 1.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
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Blockchain extends Thread {
List<Block> blocks;
List<Transaction> unconfirmedTransactions;
CommunicationChannel channel;
public Blockchain() {
this.blocks = new ArrayList<>();
this.blocks.add(new Block(0));
this.unconfirmedTransactions = new ArrayList<>();
this.channel = new CommunicationChannel("blockchain", this);
}
public void run() {
try {
for (int i = 0; i < 10; i++) {
synchronized (this) {
Block block = new Block(blocks.size(), Collections.emptyList(), blocks.get(blocks.size() - 1).getHash());
blocks.add(block);
}
Thread.sleep(1000);
}
System.out.println(this.toString());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public StateHolder getStateHolder() {
synchronized (this) {
return new StateHolder(blocks, unconfirmedTransactions);
}
}
public void setState(StateHolder state) {
synchronized (this) {
this.blocks.clear();
this.blocks.addAll(state.blocks);
this.unconfirmedTransactions.clear();
this.unconfirmedTransactions.addAll(state.getUnconfirmedTransactions());
}
}
@Override
public String toString() {
StringBuilder out = new StringBuilder();
for (Block block : blocks) {
out.append(block.toString())
.append("\n--------\n");
}
return out.toString();
}
public void shutdown() {
channel.disconnect();
}
}