-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNode.java
312 lines (254 loc) · 8.98 KB
/
Node.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import java.sql.Timestamp;
import java.util.LinkedList;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
public class Node{
private boolean type; //type true for fast nodes and false for lazy nodes
private String uID;
private float currOwned;
private Timestamp creationTime;
//For the next set of events to executed by the node
Timestamp nextTxnTime;
Timestamp nextBlockTime;
List<Transaction> allTxns = new ArrayList<Transaction>();
// List<Transaction> testTxn = new ArrayList<Transaction>();
LinkedList<Transaction> txnIncludePending = new LinkedList<Transaction>();
int numTxnIncludePending = 0;
LinkedList<Transaction> totalTxnIncludePending = new LinkedList<Transaction>();
int numTotalTxnIncludePending = 0;
LinkedList<Block> blockIncludePending = new LinkedList<Block>();
int numBlockIncludedPending = 0;
//Varialbes to store information about longest chain received so far
Block probParentBlock;
//Transaction details
ArrayList<Transaction> receivedTxn = new ArrayList<Transaction>();
int numReceivedTxn = 0;
ArrayList<Transaction> sentTxn = new ArrayList<Transaction>();
int numSentTxn = 0;
//Connection Details
LinkedList<Node> connectedNode = new LinkedList<Node>();
int numConnection = 0;
int numCreatedBlock = 0; //Number of block generated by this node so far
//Tree to store all the blocks heard by the Node so far
HashMap<String, Block> blockChain = new HashMap<String, Block>();
//HashMap to store all the transactions forwarded by the node.
HashMap<String, Boolean> forwardedMessage = new HashMap<String, Boolean>();
public final static String GOD_ID = "god";
//Default constructor
Node(String uID, boolean type, Timestamp creationTime, Block genesisBlock){
this.uID = uID;
this.type = type;
this.creationTime = creationTime;
this.currOwned = 50;
this.probParentBlock = genesisBlock;
blockChain.put(genesisBlock.getBlockID(),genesisBlock);
}
//function to gerate block at a particular timestamp
public Block generateBlock(Block parentBlock, Timestamp creationTime, int mainDiff, int subDiff){
String uBlockID = uID + "_B_" + numCreatedBlock;
this.nextBlockTime = creationTime;
this.probParentBlock = parentBlock;
this.calculateBTC();
Block newBlock = new Block(uBlockID, creationTime, uID, parentBlock, null);
ProofWork powProof = new ProofWork();
//powProof.setMainDiff(mainDiff);
//powProof.setSubDiff(subDiff);
powProof.setMainDiff(1);
powProof.setSubDiff(0);
newBlock.setProof(powProof);
return newBlock;
}
//Code to add a block in the node's block chain
public boolean addBlock(Block newBlock){
long startMining= System.currentTimeMillis();
System.out.println("\nstart Mining at: " + startMining);
newBlock.mineBlock();
System.out.println("Mining time: " + (System.currentTimeMillis() - startMining));
//check if all txns in the block valid according to me
boolean valid = true;
ArrayList<Transaction> tmpTxns = newBlock.getTxnList();
for(int i=0;i<tmpTxns.size();i++){
Transaction tmpTxn = tmpTxns.get(i);
//check transaction validity
if(!this.checkValid(tmpTxn)){
valid = false;
break;
}
}
//end of check
String parentBlockID = newBlock.getParentBlockID();
String currentBlockID = newBlock.getBlockID();
String creatorID = newBlock.getCreatorID();
if(blockChain.containsKey(parentBlockID) && valid){
blockChain.put(currentBlockID, newBlock);
if(!blockChain.get(parentBlockID).checkChild(currentBlockID)){
blockChain.get(parentBlockID).putChild(currentBlockID);
if(this.uID.equals(creatorID)){
numCreatedBlock++;
}
return true;
}
}else{
//block can turn valid lateron
if(!this.blockIncludePending.contains(newBlock)){
this.blockIncludePending.add(newBlock);
}
}
return false;
}
//adds pending blocks to the block chain
public void addPendingBlocks(){
int num_new = 1;
while(num_new>0){
num_new = 0;
for(int i=0;i<this.blockIncludePending.size();i++) { // Note: pending list for blocks needs to be stored and loaded
if(this.addBlock(this.blockIncludePending.get(i))){ // Note: assume now, it is loaded from DB
num_new++;
}
}
}
}
// adding pending transaction to the new block
public void addPendingTx2NewBlock(Block newBlock) {
//mining fee transaction
Transaction mfee = new Transaction(getUID()+"_mining_fee", Node.GOD_ID, getUID(), 50, new Timestamp(System.currentTimeMillis()));
newBlock.addTxn(mfee); // adding mining fee at the current transaction in array list of current block
System.out.println("new block minined successfully, 50 coins rewards at time: " +System.currentTimeMillis());
//change block to include transactions
Block parent = probParentBlock;
for(int i=0;i<allTxns.size(); i++) { // verify all Txns
boolean alreadyIncluded = false;
Transaction tmpTxn = allTxns.get(i);
//check block validity
if(!checkValid(tmpTxn)){
continue; //continue if invalid. It can turn valid after some time.
}
while(parent!=null){ // controlling double spending
if(parent.txnList.contains(tmpTxn)){
alreadyIncluded = true;
break;
}
parent = parent.getParentBlock();
}
if(!alreadyIncluded) {
// long beginAdd = System.currentTimeMillis();
newBlock.addTxn(tmpTxn);
// System.out.println("add Txns time interval: " + String.valueOf(System.currentTimeMillis() - beginAdd));
}
}
}
public LinkedList<Transaction> getTxnIncludePending(){
return this.txnIncludePending;
}
//function to generate a transaction
Transaction generateTxn(String receiverID, float txnAmount, Timestamp txnTime){
String txnID = uID + "_" + numSentTxn;
Transaction newTxn = new Transaction(txnID, uID, receiverID, txnAmount, txnTime);
return newTxn;
}
//function to add a new transaction to a node
boolean addTxn(Transaction newTxn) {
if(newTxn.getSenderID().equals(this.uID)){
if(newTxn.getAmount()<=currOwned){
//Add to sentTxn ArrayList
sentTxn.add(numSentTxn, newTxn);
numSentTxn++;
this.numTotalTxnIncludePending++;
this.totalTxnIncludePending.add(newTxn);
return true;
} else {
return false;
}
} else if(newTxn.getReceiverID().equals(this.uID)){
//Add to receivedTxn ArrayList
receivedTxn.add(numReceivedTxn, newTxn);
numReceivedTxn++;
this.numTotalTxnIncludePending++;
this.totalTxnIncludePending.add(newTxn);
return true;
} else {
this.numTotalTxnIncludePending++;
this.totalTxnIncludePending.add(newTxn);
return true;
}
}
//check if txn is valid or not (Proof of work is conducted here)
public boolean checkValid(Transaction t){
String senderID = t.getSenderID();
if(senderID == GOD_ID ){
return true;
}
return (calculateBTC(senderID) >= t.getAmount());
}
//calculate number of BTC I own in the longest block chain
public double calculateBTC(){
float btc = calculateBTC(this.uID);
this.currOwned = btc;
return btc;
}
private float calculateBTC(String ownerId) {
float btc = 0;
//Note: get parent block's transaction list for a given block from DB
Block blk_iter = this.probParentBlock;
while(blk_iter!=null) {
if(blk_iter.txnList != null && blk_iter.txnList.size() > 0) {
for(Transaction tx: blk_iter.txnList) {
if(ownerId.equals(tx.getSenderID())) {
// deducting transaction amount if current node is sender
btc -= tx.getAmount();
}else if(ownerId.equals(tx.getReceiverID())){
//incrementing transaction amount if current node is receiver
btc += tx.getAmount();
}
}
}
blk_iter = blk_iter.getParentBlock();
}
return btc;
}
//Add Node to connected Nodes
void connect2Node(Node newNode){
connectedNode.add(newNode);
numConnection++;
}
//userID return
public String getUID(){
return uID;
}
//type return
public boolean getType(){
return type;
}
//creationTime return
public Timestamp getCreationTime(){
return creationTime;
}
//userID return
public float getCurrOwned(){
return currOwned;
}
//to update the currently owned value
public void updateCurrOwned(float newAmount){
this.currOwned = newAmount;
}
//overwritting toString method for Node
public String toString(){
return "ID: "+this.uID+" type: "+ (this.type?"fast":"lazy") + " Creation time: "+this.creationTime + " Balance: "+this.currOwned;
}
public Node connectedNodeAt(int index){
if(index >= numConnection){
return null;
}
else{
return connectedNode.get(index);
}
}
//Function to check given a blockID or transactionID whether that is already being forwarded or not
public boolean checkForwarded(String newID){
return (forwardedMessage.containsKey(newID));
}
public void addForwarded(String newID){
this.forwardedMessage.put(newID, true);
}
}