-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
75 lines (63 loc) · 1.97 KB
/
server.js
File metadata and controls
75 lines (63 loc) · 1.97 KB
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
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const Blockchain = require('./DTMChain/blockchain');
const Wallet = require('./DTMChain/wallet');
const TransactionPool = require('./DTMChain/wallet/transactionPool');
const Miner = require('./DTMChain/miner');
const P2pServer = require('./DTMChain/p2pServer');
const HTTP_PORT = process.env.HTTP_PORT || 3001;
const app = express();
const blockchain = new Blockchain();
const wallet = new Wallet();
const tp = new TransactionPool();
const p2pServer = new P2pServer(blockchain, tp);
const miner = new Miner(blockchain, tp, wallet);
app.use(bodyParser.json());
app.use("/", express.static(path.join(__dirname, 'public')))
app.use(function(req, res, next) {
res.header('Content-Type', 'application/json');
next();
});
app.get('/balance', (req, res) => {
res.json({
balance: wallet.calculateBalance(blockchain),
publicKey: wallet.publicKey
});
});
app.get('/blocks', (req, res) => {
res.json(blockchain.chain);
});
app.get('/mine', (req, res) => {
const block = miner.mine();
if (!block) {
res.status(500).json({
error: "Please restart the node due to an invalid chain."
});
}
const displayMessage = `New block added: ${block.toString()}`;
p2pServer.broadcastClearTransactions();
p2pServer.syncChains(displayMessage);
p2pServer.log(displayMessage, true);
res.redirect('/blocks');
});
app.post('/transact', (req, res) => {
const {
recipient,
amount,
fee
} = req.body;
const transaction = wallet.createTransaction(recipient, amount, fee || 1, blockchain, tp);
p2pServer.broadcastTransaction(transaction, 'Transaction processed!');
res.redirect('/transactions');
});
app.get('/transactions', (req, res) => {
res.json(tp.transactions);
});
app.get('/publicKey', (req, res) => {
res.json({
publicKey: wallet.publicKey
});
});
app.listen(HTTP_PORT, () => console.log(`Listening on the port ${HTTP_PORT}`));
p2pServer.listen();