-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
316 lines (251 loc) · 9.32 KB
/
server.js
File metadata and controls
316 lines (251 loc) · 9.32 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
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
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const crypto = require('crypto');
const config = require('./config');
const { Block, Blockchain } = require('./blockchain');
const P2PNetwork = require('./p2p-network');
const { BlockchainPersistence } = require('./persistence');
const { AuthManager } = require('./auth');
const app = express();
app.use(bodyParser.json());
app.use(cors({
origin: '*',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
const blockchain = new Blockchain();
blockchain.difficulty = config.DIFFICULTY;
blockchain.miningReward = config.MINING_REWARD;
const p2pNetwork = new P2PNetwork(blockchain, config.P2P_PORT || 6001);
const p2pServer = p2pNetwork.initP2PServer();
const persistence = new BlockchainPersistence(config);
persistence.connect().then(async connected => {
if (connected) {
const savedData = await persistence.loadChain();
if (savedData && savedData.chain && savedData.chain.length > 0) {
blockchain.chain = savedData.chain;
console.log(`Blockchain loaded from database: ${blockchain.chain.length} blocks`);
}
const pendingTxs = await persistence.loadPendingTransactions();
if (pendingTxs && pendingTxs.length > 0) {
blockchain.pendingTransactions = pendingTxs;
console.log(`Loaded ${pendingTxs.length} pending transactions`);
}
}
});
setInterval(() => {
persistence.saveChain(blockchain);
persistence.savePendingTransactions(blockchain.pendingTransactions);
}, 60000);
const authManager = new AuthManager(config);
const authMiddleware = (req, res, next) => {
return authManager.authMiddleware.call(authManager, req, res, next);
};
const adminMiddleware = (req, res, next) => {
return authManager.adminMiddleware.call(authManager, req, res, next);
};
function generateWallet() {
const privateKey = crypto.randomBytes(32).toString('hex');
const address = 'wallet_' + crypto.createHash('sha256').update(privateKey).digest('hex').substring(0, 40);
return { address, privateKey };
}
app.get('/blockchain/info', (req, res) => {
res.json({
chainLength: blockchain.chain.length,
difficulty: blockchain.difficulty,
miningReward: blockchain.miningReward,
pendingTransactions: blockchain.pendingTransactions.length,
consensus: blockchain.currentConsensus,
isValid: blockchain.isChainValid().valid
});
});
app.get('/blocks', (req, res) => {
const page = parseInt(req.query.page) || 0;
const limit = parseInt(req.query.limit) || 10;
const startIndex = Math.max(0, blockchain.chain.length - 1 - (page * limit));
const endIndex = Math.max(0, startIndex - limit + 1);
const blocks = [];
for (let i = startIndex; i >= endIndex; i--) {
blocks.push(blockchain.chain[i]);
}
res.json({
blocks,
page,
limit,
total: blockchain.chain.length,
hasMore: endIndex > 0
});
});
app.get('/block/:index', (req, res) => {
const index = parseInt(req.params.index);
if (isNaN(index) || index < 0 || index >= blockchain.chain.length) {
return res.status(404).json({ error: 'Block not found' });
}
res.json(blockchain.chain[index]);
});
app.post('/auth/register', async (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ error: 'Username and password are required' });
}
const { address, privateKey } = generateWallet();
const result = await authManager.registerUser(username, password, address, privateKey);
if (!result.success) {
return res.status(400).json({ error: result.message });
}
res.status(201).json({
message: 'User registered successfully',
user: result.user,
wallet: { address }
});
});
app.post('/auth/login', async (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ error: 'Username and password are required' });
}
const result = await authManager.authenticateUser(username, password);
if (!result.success) {
return res.status(401).json({ error: result.message });
}
res.json({
message: 'Authentication successful',
token: result.token,
user: result.user
});
});
app.get('/user/profile', authMiddleware, (req, res) => {
try {
if (!req.user || !req.user.address) {
return res.status(400).json({ error: 'Invalid user data in request' });
}
const balance = blockchain.getBalanceOfAddress(req.user.address);
res.json({
username: req.user.username,
address: req.user.address,
balance,
isAdmin: req.user.isAdmin || false
});
} catch (error) {
console.error('Error fetching user profile:', error);
res.status(500).json({ error: 'Failed to retrieve user profile', details: error.message });
}
});
app.post('/transaction', authMiddleware, (req, res) => {
try {
const { to, amount } = req.body;
if (!to) {
return res.status(400).json({ error: 'Recipient address (to) is required' });
}
if (!amount) {
return res.status(400).json({ error: 'Transaction amount is required' });
}
if (isNaN(parseFloat(amount)) || parseFloat(amount) <= 0) {
return res.status(400).json({ error: 'Amount must be a positive number' });
}
const balance = blockchain.getBalanceOfAddress(req.user.address);
if (parseFloat(amount) > balance) {
return res.status(400).json({ error: 'Insufficient balance', available: balance });
}
const transaction = {
from: req.user.address,
to,
amount: parseFloat(amount),
timestamp: Date.now()
};
const result = blockchain.createTransaction(transaction);
if (!result.success) {
return res.status(400).json({ error: result.message });
}
res.json({
message: 'Transaction created successfully',
transaction
});
} catch (error) {
console.error('Error creating transaction:', error);
res.status(500).json({ error: 'Failed to create transaction', details: error.message });
}
});
app.post('/mine', authMiddleware, (req, res) => {
const result = blockchain.minePendingTransactions(req.user.address);
if (!result.success) {
return res.status(400).json({ error: result.message });
}
persistence.saveChain(blockchain);
res.json({
message: 'Block mined successfully',
block: result.block
});
});
app.get('/transactions/history', authMiddleware, (req, res) => {
const address = req.user.address;
const transactions = [];
blockchain.chain.forEach(block => {
if (Array.isArray(block.data)) {
block.data.forEach(tx => {
if (tx.from === address || tx.to === address) {
transactions.push({
...tx,
blockIndex: block.index,
blockHash: block.hash,
confirmed: true
});
}
});
}
});
blockchain.pendingTransactions.forEach(tx => {
if (tx.from === address || tx.to === address) {
transactions.push({
...tx,
confirmed: false
});
}
});
transactions.sort((a, b) => b.timestamp - a.timestamp);
res.json(transactions);
});
app.get('/network/status', authMiddleware, adminMiddleware, (req, res) => {
const stats = p2pNetwork.getNetworkStats();
res.json(stats);
});
app.post('/network/peers', authMiddleware, adminMiddleware, (req, res) => {
const { peer } = req.body;
if (!peer) {
return res.status(400).json({ error: 'Peer URL is required' });
}
p2pNetwork.connectToPeers([peer]);
res.json({ message: 'Connecting to peer', peer });
});
app.put('/admin/config', authMiddleware, adminMiddleware, (req, res) => {
const { difficulty, miningReward, consensus } = req.body;
if (difficulty !== undefined) {
blockchain.difficulty = parseInt(difficulty);
}
if (miningReward !== undefined) {
blockchain.miningReward = parseFloat(miningReward);
}
if (consensus) {
blockchain.switchConsensus(consensus);
}
res.json({
message: 'Configuration updated',
config: {
difficulty: blockchain.difficulty,
miningReward: blockchain.miningReward,
consensus: blockchain.currentConsensus
}
});
});
const PORT = config.API_PORT;
app.listen(PORT, () => {
console.log(`Blockchain API server running on port ${PORT}`);
});
process.on('SIGINT', async () => {
console.log('Shutting down...');
await persistence.saveChain(blockchain);
await persistence.savePendingTransactions(blockchain.pendingTransactions);
await persistence.close();
process.exit();
});