-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
237 lines (199 loc) · 6.64 KB
/
Copy pathserver.js
File metadata and controls
237 lines (199 loc) · 6.64 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
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
const express = require('express')
const path = require('path');
const http = require('http');
const BurgerBlockchain = require('./burgerBlockchain')
const BurgerNode = require('./burgerNode')
const BurgerFaucet = require('./burgerFaucet');
const BurgerSync = require('./burgerSync');
var bodyParser = require('body-parser');
var cors = require('cors');
const app = express();
const server = http.createServer(app);
app.use(cors());
app.use(bodyParser.json());
const REMOTE_HOST = process.env.REMOTE_HOST;
const HOST_NAME = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 3001;
var initialPeers = process.env.PEERS ? process.env.PEERS.split(',') : [];
let burgerSync;
const config = {
host: HOST_NAME,
port: PORT,
selfUrl: REMOTE_HOST || `${HOST_NAME}:${PORT}`,
};
const burgerNode = new BurgerNode(new BurgerBlockchain(), config);
app.use('/', express.static(path.resolve('public')));
app.get('/info', (request, response) => {
response.json(burgerNode.info);
});
app.get('/blocks', (request, response) => {
response.json(burgerNode.getBlocks())
})
app.get('/blocks/:index', (request, response) => {
const index = request.params.index
if(burgerNode.chain.blocks.length > index){
const block = burgerNode.findBlockByIndex(index)
response.status(200).json(block);
}else{
response.status(404).json({
"errorMsg": "Invalid block index"
});
}
})
app.post('/mining/submit-mined-block', (request, response) => {
let minedRes = burgerNode.addMinedBlock(request.body);
const resultType = minedRes[0];
const result = minedRes[1];
const block = minedRes[2];
const minedResultType = burgerNode.chain.resultType;
switch (resultType) {
case minedResultType.VALID_BLOCK:
response.status(200).json({
"message": result
});
burgerSync.broadcastNewBlock(block);
break;
case minedResultType.INVALID_BLOCK:
response.status(404).json({
"errorMsg": result
});
break;
default:
// [Anar] not sure what a good default action would be...
// also, I was gonna have BLOCK_WAY_AHEAD here, but that
// seemed illogical at the time. Why would I submit a block
// that is way ahead of my own chain???
response.status(404).json({
"errorMsg": result
});
}
})
app.get('/mining/get-mining-job/:address', (request, response) => {
const minerAddress = request.params.address;
const information = burgerNode.chain.prepareCandidateBlock(minerAddress);
response.json(information);
})
app.get('/transactions/confirmed',(req, res) => {
const confirmedTransactions = burgerNode.pullConfirmedTransactions();
res.json(confirmedTransactions)
})
app.get('/transactions/pending',(req, res) => {
res.json(burgerNode.chain.pendingTransactions)
})
app.post('/transactions/send', (req, res) => {
const transaction = req.body;
try {
const isTransactionValid = burgerNode.addPendingTransaction(req.body);
if (isTransactionValid) {
burgerSync.broadcastNewTransaction(transaction);
res.status(200).json({
"transactionDataHash":transaction.transactionDataHash
});
} else {
res.status(400).json({
errorMsg: "Internal server error"
});
}
} catch (e) {
res.status(400).json({
errorMsg: e.message
})
}
})
app.get('/address/:address/balance', (req, res) => {
const address = req.params.address;
const safeBalance = burgerNode.getSafeBalanceOfAddress(address);
const confirmedBalance = burgerNode.getConfirmedBalanceOfAddress(address);
const pendingBalance = burgerNode.getPendingBalanceOfAddress(address);
res.status(200).json({
safeBalance,
confirmedBalance: parseFloat(confirmedBalance),
pendingBalance
});
})
app.get('/address/:address/transactions', (req, res) => {
const address = req.params.address;
if(burgerNode.getTransactionsOfAddress(address).transactions.length > 0){
res.status(200).json(burgerNode.getTransactionsOfAddress(address));
}
else{
res.status(404).json({
"errorMsg":"Invalid address"
});
}
});
app.get('/transactions/:transactionDataHash', (req, res) => {
const transactionDataHash = req.params.transactionDataHash;
const transactionData = burgerNode.getTransaction(transactionDataHash);
if (Object.keys(transactionData) <= 0) {
res.status(404).json({errorMsg: "Invalid address"});
} else {
res.status(200).json(transactionData);
}
});
app.get('/balances', (req, res) => {
const balances = {};
burgerNode.pullConfirmedTransactions().forEach((transaction) => {
if (!balances[transaction.to]) {
balances[transaction.to] = 0;
}
if (!balances[transaction.from]) {
balances[transaction.from] = 0;
}
balances[transaction.to] += transaction.value;
balances[transaction.from] -= (transaction.value + transaction.fee)
});
res.status(200).json(balances);
});
app.get('/peers', (req, res) => {
res.send(burgerNode.nodes);
})
app.post('/peers/connect', async (req, res) => {
try {
if (req.body.peer) {
await burgerSync.connect(req.body.peer, () => {
res.status(200).json({
"message": "Connected to peer: "+req.body.peer
});
});
return;
}
/**
* For debugging purposes to quickly initialize a mesh network
*/
if (req.body.peers) {
const peers = req.body.peers;
peers.forEach(async (peer) => {
await burgerSync.connect(peer);
});
res.status(200).json({
"message": "Connected to all peers!"
});
}
} catch(e) {
let status;
if (e.status) {
status = e.status;
} else {
status = 500;
}
res.status(status).send(e.message);
}
})
app.get('/debug', (req, res) => {
res.json({
"node": burgerNode,
"config": config,
});
})
app.get('/debug/reset-chain', (req, res) => {
burgerNode.resetChain();
res.json({
message: "The chain was reset to its genesis block"
});
})
const initializeServer = (customPort) => {
burgerSync = new BurgerSync(server, burgerNode);
server.listen(customPort || PORT, () => console.log('HTTP and P2P is listening on port: ' + (customPort || PORT)));
}
module.exports = {server, burgerNode, initializeServer};