-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·427 lines (346 loc) · 10.8 KB
/
index.js
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
const bodyParser = require('body-parser');
const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const PubSub = require('./app/pubsub');
const Blockchain = require('./blockchain/index');
const path = require('path');
const TransactionPool = require('./wallet/transaction-pool');
const Transaction = require('./wallet/transaction');
const Wallet = require('./wallet/index');
const TransactionMiner = require('./app/transaction-miner');
const { SENDER_INPUT } = require('./util/index');
const ip = require('ip');
const Peer = require('./app/peer');
const got = require('got');
const fs = require('fs');
// Routes
const authRoute = require('./routes/auth');
dotenv.config();
mongoose.connect(
process.env.MONGO_DB,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => console.log('Connected to DB')
);
const isDevelopment = process.env.ENV === 'development';
const REDIS_URL = isDevelopment
? 'redis://127.0.0.1:6379'
: 'redis://h:p2e12ac66333126401be49042ceb7484d6af7d3d3f946bcc1545fa177b55328f3@ec2-54-145-84-202.compute-1.amazonaws.com:26739';
const DEFAULT_PORT = 3001;
const ROOT_NODE_ADDRESS = `http://localhost:${DEFAULT_PORT}`;
const app = express();
let isLoggedIn = false;
let blockchain, transactionPool, wallet, peer, pubsub, transactionMiner;
blockchain = new Blockchain();
transactionPool = new TransactionPool();
peer = new Peer();
pubsub = new PubSub({ blockchain, transactionPool, peer, redisUrl: REDIS_URL });
//JASH CODE BELOW -
app.use(express.static(path.join(__dirname, 'client/dist')));
//JASH CODE ABOVE -
console.log('ROOT_NODE_ADDRESS - ' + ROOT_NODE_ADDRESS);
app.use(bodyParser.json());
app.use('/api/user', authRoute);
app.get('/createUser', (req, res) => {
if (isLoggedIn == false) {
if (PORT !== DEFAULT_PORT) {
syncChains();
syncTransactionPool();
syncPeerList();
}
wallet = new Wallet();
transactionMiner = new TransactionMiner({
blockchain,
transactionPool,
wallet,
pubsub,
});
console.log('Created User Successfully !');
isLoggedIn = true;
var details = JSON.stringify(wallet);
// fs.writeFileSync(path.join(__dirname, '/client/src/assets/', 'MyWallet.txt'), details);
res.send({ wallet: details });
}
});
app.get('/logout', (req, res) => {
if (isLoggedIn == true) {
isLoggedIn = false;
console.log('Logout successful !');
}
});
app.post('/login', (req, res) => {
if (isLoggedIn == true) {
res.json({
isLoggedIn: isLoggedIn,
});
} else {
const { jsonObj } = req.body;
// console.log(jsonObj.balance);
console.log(JSON.parse(jsonObj).publicKey);
// let MyWallet;
if (PORT !== DEFAULT_PORT) {
syncChains();
syncTransactionPool();
syncPeerList();
}
// MyWallet = JSON.parse(data);
// wallet = JSON.parse(JSON.stringify(jsonObj));
wallet = JSON.parse(jsonObj);
transactionMiner = new TransactionMiner({
blockchain,
transactionPool,
wallet,
pubsub,
});
wallet.balance = Wallet.calculateBalance({
chain: blockchain.chain,
address: wallet.publicKey,
});
isLoggedIn = true;
var details = JSON.stringify(wallet);
// fs.writeFileSync(path.join(__dirname, '/client/src/components/files/', 'MyWallet.txt'), details);
console.log('Login Successful !');
console.log(wallet.publicKey);
res.json({
isLoggedIn: isLoggedIn,
wallet: wallet.publicKey,
});
}
});
app.get('/api/blocks', (req, res) => {
res.json({
chain: blockchain.chain,
isLoggedIn: isLoggedIn,
});
});
app.get('/api/peer', (req, res) => {
res.json({
peer: peer.peersList,
isLoggedIn: isLoggedIn,
});
});
app.post('/api/mine', (req, res) => {
const { data } = req.body;
blockchain.addBlock({ data: data });
pubsub.broadcastChain();
res.redirect('/api/blocks');
});
app.post('/api/send', (req, res) => {
const { input } = req.body;
input.from = wallet.publicKey;
input.timestamp = Date.now();
input.address = SENDER_INPUT.sender_address;
const outputMap = { [SENDER_INPUT.receiver_address]: SENDER_INPUT.reward };
const transaction = new Transaction({ input: input, outputMap: outputMap });
pubsub.broadcastTransaction(transaction);
transactionPool.setTransaction(transaction);
res.redirect('/api/transactionPoolMap');
});
app.post('/api/receive', (req, res) => {
const { input } = req.body;
input.to = wallet.publicKey;
input.timestamp = Date.now();
input.address = SENDER_INPUT.receiver_address;
const outputMap = { [SENDER_INPUT.sender_address]: SENDER_INPUT.reward };
const transaction = new Transaction({ input: input, outputMap: outputMap });
pubsub.broadcastTransaction(transaction);
transactionPool.setTransaction(transaction);
res.redirect('/api/transactionPoolMap');
});
app.post('/api/transact', (req, res) => {
const { amount, recipient } = req.body;
let transaction = transactionPool.existingTransaction({
inputAddress: wallet.publicKey,
});
try {
if (transaction) {
transaction.update({
senderWallet: wallet,
recipient: recipient,
amount: amount,
});
} else {
transaction = wallet.createTransaction({
amount: amount,
recipient: recipient,
chain: blockchain.chain,
});
}
} catch (error) {
return res.status(400).json({ type: 'error', message: error.message });
}
pubsub.broadcastTransaction(transaction);
transactionPool.setTransaction(transaction);
res.redirect('/api/transactionPoolMap');
});
app.post('/api/trace', (req, res) => {
const { product } = req.body;
console.log('Tracing for product ' + product + ' ...');
let traceArray = [];
for (let i = 1; i < blockchain.chain.length; i++) {
const block = blockchain.chain[i];
for (let transaction of block.data) {
if (
transaction.input.address === SENDER_INPUT.sender_address ||
transaction.input.address === SENDER_INPUT.receiver_address
) {
if (transaction.input.product === product) {
let found = 0;
for (let j = 0; j < traceArray.length; j++) {
if (traceArray[j] == transaction.input.from) {
found = 1;
break;
}
}
if (found == 0) {
traceArray.push(transaction.input.from);
}
found = 0;
for (let j = 0; j < traceArray.length; j++) {
if (traceArray[j] == transaction.input.to) {
found = 1;
break;
}
}
if (found == 0) {
traceArray.push(transaction.input.to);
}
}
}
}
}
res.json({
traceArray: traceArray,
isLoggedIn: isLoggedIn,
});
});
app.get('/api/transactionPoolMap', (req, res) => {
res.json({
transactionPool: transactionPool.transactionMap,
isLoggedIn: isLoggedIn,
});
});
app.get('/api/mine-transactions', (req, res) => {
transactionMiner.mineTransactions();
// PEER ADD -
// pubsub.broadcastPeer(myIp);
// peer.addPeer(myIp);
// console.log("Ip " + myIp + " has been added to peersList.");
});
app.get('/api/wallet-info', (req, res) => {
const address = wallet.publicKey;
res.json({
address: address,
balance: Wallet.calculateBalance({
chain: blockchain.chain,
address: address,
}),
isLoggedIn: isLoggedIn,
});
});
// JASH CODE BELOW -
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client/dist/index.html'));
});
// JASH CODE ABOVE -
const syncChains = async () => {
try {
const response = await got(`${ROOT_NODE_ADDRESS}/api/blocks`);
console.log('Syncing Chain ....');
const rootchain = JSON.parse(response.body);
blockchain.replaceChain(rootchain);
console.log('Chain Synced.');
} catch (error) {
// console.log(error.response.body);
console.log("ERROR : Couldn't sync chain...");
}
};
const syncTransactionPool = async () => {
try {
const response = await got(`${ROOT_NODE_ADDRESS}/api/transactionPoolMap`);
console.log('Syncing TransactionPool ....');
const rootTransactionPool = JSON.parse(response.body);
transactionPool.setMap(rootTransactionPool);
console.log('TransactionPool Synced.');
} catch (error) {
console.log("ERROR : Couldn't sycn Transaction Pool...");
// console.log(error.response.body);
}
};
// REQUEST MODULE
// const syncPeerList = ()=>{
// request({ url : `${ROOT_NODE_ADDRESS}/api/peer`}, (error, response, body)=>{
// if(!error && response.statusCode === 200){
// const rootPeersList = JSON.parse(body);
// console.log("rootPeersList - " + rootPeersList);
// peer.setPeerList(rootPeersList);
// }
// });
// };
const syncPeerList = async () => {
try {
const response = await got(`${ROOT_NODE_ADDRESS}/api/peer`);
console.log('Syncing PeersList ....');
const rootPeersList = JSON.parse(response.body);
peer.setPeerList(rootPeersList);
console.log('PeersList Synced.');
} catch (error) {
// console.log(error.response.body);
console.log("Coudln't sync Peer List");
}
};
// JASH CODE BELOW -
// const walletFoo = new Wallet();
// const walletBar = new Wallet();
// const generateWalletTransaction = ({ wallet,recipient,amount }) => {
// const transaction = wallet.createTransaction({
// recipient,amount,chain: blockchain.chain
// });
// transactionPool.setTransaction(transaction);
// };
// const walletAction = () => generateWalletTransaction({
// wallet, recipient: walletFoo.publicKey, amount:5
// });
// const walletFooAction = () => generateWalletTransaction({
// wallet: walletFoo , recipient: walletBar.publicKey, amount:10
// });
// const walletBarAction = () => generateWalletTransaction({
// wallet: walletBar , recipient: wallet.publicKey, amount:15
// });
// for (let i=0; i<3; i++) {
// if (i%3 === 0) {
// walletAction();
// walletFooAction();
// } else if (i%3 === 1) {
// walletAction();
// walletBarAction();
// } else {
// walletFooAction();
// walletBarAction();
// }
// transactionMiner.mineTransactions();
// }
// JASH CODE ABOVE -
let PEER_PORT;
if (process.env.GENERATE_PEER_PORT === 'true') {
PEER_PORT = DEFAULT_PORT + Math.ceil(Math.random() * 1000);
}
const PORT = process.env.PORT || PEER_PORT || DEFAULT_PORT;
app.listen(`${PORT}`, () => {
console.log(`Listening at port ${PORT}`);
// if(PORT !== DEFAULT_PORT){
// syncChains();
// syncTransactionPool();
// }
// if(myIp !== `${SERVER_IP_ADDRESS}`){
// // if(PORT !== DEFAULT_PORT){
// // myIp = "123.12.12.12";
// syncChains();
// syncTransactionPool();
// syncPeerList();
// }else{
// pubsub.broadcastPeer(myIp);
// peer.addPeer(myIp);
// console.log("Ip " + myIp + " has been added to peersList.");
// }
});