-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblockchain-network.js
More file actions
269 lines (223 loc) · 8.13 KB
/
Copy pathblockchain-network.js
File metadata and controls
269 lines (223 loc) · 8.13 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
/**
* P2P Network Layer for Distributed Blockchain
* Uses WebSockets for peer-to-peer communication
*/
const WebSocket = require('ws');
const EventEmitter = require('events');
class BlockchainNetwork extends EventEmitter {
constructor(port, blockchain, database, nodeRole = 'HYBRID') {
super();
this.port = port;
this.blockchain = blockchain;
this.database = database;
this.nodeRole = nodeRole;
this.server = null;
this.peers = new Map();
this.isServer = false;
}
// Start as server
startServer() {
this.isServer = true;
this.server = new WebSocket.Server({ port: this.port });
this.server.on('connection', (ws, req) => {
const peerAddress = req.socket.remoteAddress;
console.log(`New peer connected: ${peerAddress}`);
this.peers.set(peerAddress, {
ws,
address: peerAddress,
lastSeen: Date.now(),
isActive: true
});
// Send current chain to new peer
this.sendChain(ws);
ws.on('message', async (message) => {
await this.handleMessage(ws, message);
});
ws.on('close', () => {
console.log(`Peer disconnected: ${peerAddress}`);
this.peers.delete(peerAddress);
});
ws.on('error', (error) => {
console.error(`Peer error: ${error.message}`);
});
});
console.log(`🌐 P2P Network Server started on port ${this.port}`);
}
// Connect to peer
connectToPeer(host, port) {
return new Promise((resolve, reject) => {
const url = `ws://${host}:${port}`;
const ws = new WebSocket(url);
ws.on('open', () => {
console.log(`Connected to peer: ${url}`);
this.peers.set(url, {
ws,
address: url,
lastSeen: Date.now(),
isActive: true
});
// Request chain from peer
this.sendMessage(ws, { type: 'REQUEST_CHAIN' });
resolve(ws);
});
ws.on('message', async (message) => {
await this.handleMessage(ws, message);
});
ws.on('error', (error) => {
console.error(`Connection error to ${url}: ${error.message}`);
reject(error);
});
ws.on('close', () => {
console.log(`Disconnected from peer: ${url}`);
this.peers.delete(url);
});
});
}
async handleMessage(ws, message) {
try {
const data = JSON.parse(message.toString());
switch (data.type) {
case 'REQUEST_CHAIN':
this.sendChain(ws);
break;
case 'CHAIN':
await this.handleReceivedChain(data.chain);
break;
case 'NEW_BLOCK':
await this.handleNewBlock(data.block);
break;
case 'NEW_TRANSACTION':
await this.handleNewTransaction(data.transaction);
break;
case 'PING':
this.sendMessage(ws, { type: 'PONG' });
break;
case 'GOVERNANCE_VOTE':
case 'SMART_CONTRACT_QUERY':
if (this.nodeRole === 'MINING') {
console.log(`🛡️ [MINING NODE] Ignored ${data.type} from ${data.senderRole || 'UNKNOWN'} to conserve resources.`);
return;
}
// Handle governance messages (placeholder for full implementation)
console.log(`[${this.nodeRole} NODE] Processing ${data.type}`);
break;
default:
console.log(`Unknown message type: ${data.type}`);
}
} catch (error) {
console.error(`Error handling message: ${error.message}`);
}
}
sendMessage(ws, message) {
if (ws.readyState === WebSocket.OPEN) {
// Attach node role to every outbound message for traffic routing
message.senderRole = this.nodeRole;
ws.send(JSON.stringify(message));
}
}
sendChain(ws) {
const chain = this.blockchain.chain;
this.sendMessage(ws, {
type: 'CHAIN',
chain: chain
});
}
async handleReceivedChain(chain) {
console.log('🛡️ SECURITY HARDENING: Automatic Chain Replacement DISABLED.');
console.log(' Received chain length:', chain.length);
console.log(' Current chain length:', this.blockchain.chain.length);
// CRITICAL SECURITY FIX:
// We are enforcing a Hard Fork (Block 58).
// We MUST NOT accept the old "longer" chain (234 blocks) that contains corrupted data.
// For now, this node is Sovereign and will not accept history rewrites.
if (chain.length > this.blockchain.chain.length) {
console.warn('⚠️ Rejected longer chain (Potential Revert Attack or Old Fragment)');
}
/*
// ORIGINAL LOGIC (VULNERABLE TO REVERT ATTACK)
if (chain.length > this.blockchain.chain.length) {
console.log('Received longer chain, replacing current chain...');
// Validate received chain
if (this.isValidChain(chain)) {
this.blockchain.chain = chain;
// Save to database
for (const block of chain) {
await this.database.saveBlock(block);
}
this.emit('chainUpdated', chain);
}
}
*/
}
async handleNewBlock(block) {
console.log('Received new block from peer');
// Validate and add block
const latestBlock = this.blockchain.getLatestBlock();
if (block.previousHash === latestBlock.hash) {
// Validate block
if (this.blockchain.isChainValid()) {
this.blockchain.chain.push(block);
await this.database.saveBlock(block);
this.emit('blockAdded', block);
}
}
}
async handleNewTransaction(transaction) {
console.log('Received new transaction from peer');
// Add to pending transactions if valid
const result = this.blockchain.createTransaction(
transaction.from,
transaction.to,
transaction.amount,
transaction.data
);
if (result.success) {
await this.database.saveTransaction(result.transaction);
this.emit('transactionAdded', result.transaction);
}
}
broadcastBlock(block) {
const message = {
type: 'NEW_BLOCK',
block: block
};
this.broadcast(message);
}
broadcastTransaction(transaction) {
const message = {
type: 'NEW_TRANSACTION',
transaction: transaction
};
this.broadcast(message);
}
broadcast(message) {
this.peers.forEach((peer) => {
if (peer.isActive && peer.ws.readyState === WebSocket.OPEN) {
this.sendMessage(peer.ws, message);
}
});
}
isValidChain(chain) {
// Basic chain validation
for (let i = 1; i < chain.length; i++) {
const currentBlock = chain[i];
const previousBlock = chain[i - 1];
if (currentBlock.previousHash !== previousBlock.hash) {
return false;
}
}
return true;
}
getPeers() {
return Array.from(this.peers.values());
}
async syncWithPeers() {
// Request chains from all peers
this.peers.forEach((peer) => {
if (peer.isActive && peer.ws.readyState === WebSocket.OPEN) {
this.sendMessage(peer.ws, { type: 'REQUEST_CHAIN' });
}
});
}
}
module.exports = BlockchainNetwork;