-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.cpp
376 lines (329 loc) · 12 KB
/
server.cpp
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
#include <boost/asio.hpp>
#include <openssl/sha.h>
#include <iomanip>
#include <iostream>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
using boost::asio::ip::tcp;
// Структура транзакции
struct Transaction {
std::string senderAddress;
std::string receiverAddress;
double amount;
std::string signature;
};
// Класс для управления блокчейном
class Blockchain {
private:
struct Block {
int index;
std::vector<Transaction> transactions;
std::string previousHash;
std::string hash;
uint64_t nonce; // For mining simulation
};
std::vector<Block> chain;
std::vector<Transaction> pendingTransactions;
std::unordered_map<std::string, double> balances;
std::string calculateHash(const Block& block) {
std::string data = std::to_string(block.index)
+ block.previousHash
+ std::to_string(block.nonce);
for (const auto& tx : block.transactions) {
data += tx.senderAddress + tx.receiverAddress
+ std::to_string(tx.amount) + tx.signature;
}
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256(reinterpret_cast<const unsigned char*>(data.c_str()), data.size(), hash);
std::stringstream ss;
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(hash[i]);
}
return ss.str();
}
public:
Blockchain() {
// Create genesis block with system transaction
Block genesis;
genesis.index = 0;
genesis.previousHash = "0";
genesis.nonce = 0;
// System transaction: issue initial coins
Transaction genesisTx;
genesisTx.senderAddress = "system";
genesisTx.receiverAddress = "foundation";
genesisTx.amount = 1000000;
genesisTx.signature = "genesis_signature";
genesis.transactions.push_back(genesisTx);
genesis.hash = calculateHash(genesis);
chain.push_back(genesis);
// Update balances
balances["foundation"] = 1000000;
}
void addTransaction(const Transaction& tx) {
if (tx.senderAddress != "system" && getBalance(tx.senderAddress) < tx.amount) {
throw std::runtime_error("Insufficient balance!");
}
pendingTransactions.push_back(tx);
}
void mineBlock() {
Block newBlock;
newBlock.index = chain.size();
newBlock.previousHash = chain.back().hash;
newBlock.transactions = pendingTransactions;
newBlock.nonce = 0;
// Simple "mining" simulation (find hash starting with "00")
do {
newBlock.nonce++;
newBlock.hash = calculateHash(newBlock);
} while (newBlock.hash.substr(0, 2) != "00");
chain.push_back(newBlock);
// Update balances
for (const auto& tx : newBlock.transactions) {
if (tx.senderAddress != "system") {
balances[tx.senderAddress] -= tx.amount;
}
balances[tx.receiverAddress] += tx.amount;
}
pendingTransactions.clear();
}
void addBlock() {
// Создаем новый блок
Block newBlock = {
static_cast<int>(chain.size()),
{},
chain.back().hash,
""
};
newBlock.hash = calculateHash(newBlock);
chain.push_back(newBlock);
}
void issueCoins(const std::string& address, double amount) {
balances[address] += amount;
}
const std::vector<Block>& getChain() const {
return chain;
}
double getBalance(const std::string& address) const {
auto it = balances.find(address);
if (it != balances.end()) {
return it->second;
}
return 0.0;
}
std::unordered_map<std::string, double> getBalances() const {
return balances;
}
};
// ================== Authentication System ==================
class UserManager {
private:
struct User {
std::string password_hash;
bool is_admin;
};
std::unordered_map<std::string, User> users;
std::mutex users_mutex;
std::string hashPassword(const std::string& password) {
unsigned char digest[SHA256_DIGEST_LENGTH];
SHA256(reinterpret_cast<const unsigned char*>(password.c_str()),
password.length(), digest);
std::stringstream ss;
for(int i=0; i<SHA256_DIGEST_LENGTH; i++)
ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(digest[i]);
return ss.str();
}
public:
UserManager() {
// Add admin user (username, password, is_admin)
addUser("admin", "1234", true);
}
bool addUser(const std::string& username, const std::string& password, bool is_admin=false) {
std::lock_guard<std::mutex> lock(users_mutex);
if(users.count(username)) return false;
users[username] = {
hashPassword(password),
is_admin
};
return true;
}
std::pair<bool, bool> authenticate(const std::string& username, const std::string& password) {
std::lock_guard<std::mutex> lock(users_mutex);
auto it = users.find(username);
if(it == users.end()) return {false, false};
if(it->second.password_hash == hashPassword(password))
return {true, it->second.is_admin};
return {false, false};
}
};
// ================== Modified Session Class ==================
class Session : public std::enable_shared_from_this<Session> {
public:
Session(tcp::socket socket, Blockchain& blockchain, UserManager& auth)
: socket_(std::move(socket)),
blockchain_(blockchain),
auth_(auth),
authenticated_(false),
is_admin_(false) {}
void start() {
sendPrompt("Please login with: LOGIN <username> <password>\n");
readCommand();
}
private:
tcp::socket socket_;
Blockchain& blockchain_;
UserManager& auth_;
bool authenticated_;
bool is_admin_;
boost::asio::streambuf buffer_;
void readCommand() {
auto self(shared_from_this());
boost::asio::async_read_until(socket_, buffer_, '\n',
[this, self](boost::system::error_code ec, std::size_t length) {
if (!ec) {
std::istream is(&buffer_);
std::string command;
std::getline(is, command);
processCommand(command);
readCommand();
}
});
}
void processCommand(const std::string& command) {
std::istringstream iss(command);
std::string cmd;
iss >> cmd;
std::string response;
if (!authenticated_) {
if (cmd == "LOGIN") {
std::string username, password;
if (iss >> username >> password) {
auto [success, is_admin] = auth_.authenticate(username, password);
if(success) {
authenticated_ = true;
is_admin_ = is_admin;
response = "Authentication successful. Role: " +
std::string(is_admin ? "admin" : "user") + "\n";
} else {
response = "Invalid credentials\n";
}
} else {
response = "Usage: LOGIN <username> <password>\n";
}
} else {
response = "You must login first\n";
}
} else {
if (cmd == "ISSUE_COINS" && is_admin_) {
std::string address;
double amount;
if (!(iss >> address >> amount)) {
response = "ERROR: Invalid format. Use: ISSUE_COINS <address> <amount>\n";
}
blockchain_.issueCoins(address, amount);
response = "Coins issued successfully.\n";
}
else if (cmd == "ADD_TRANSACTION") {
Transaction tx;
if (!(iss >> tx.senderAddress >> tx.receiverAddress >> tx.amount >> tx.signature)) {
response = "ERROR: Invalid transaction format\n";
}
try {
blockchain_.addTransaction(tx);
response = "Transaction added to pending pool\n";
} catch (const std::exception& e) {
response = "Error: " + std::string(e.what()) + "\n";
}
}
else if (cmd == "MINE_BLOCK") {
blockchain_.mineBlock();
response = "Block mined with "
+ std::to_string(blockchain_.getChain().back().transactions.size())
+ " transactions\n";
}
else if (command == "GET_CHAIN") {
for (const auto& block : blockchain_.getChain()) {
response += "Block #" + std::to_string(block.index)
+ " Hash: " + block.hash + "\n";
}
}
else if (command == "GET_BALANCE") {
std::string address;
if (!(iss >> address)) {
response = "ERROR: Invalid format. Use: GET_BALANCE <address>\n";
}
double balance = blockchain_.getBalance(address);
response = "Balance: " + std::to_string(balance) + "\n";
}
else if (cmd == "ADD_USER" && is_admin_) {
std::string username, password;
if (iss >> username >> password) {
if(auth_.addUser(username, password)) {
response = "User added successfully\n";
} else {
response = "Username already exists\n";
}
}
}
else if (cmd == "VIEW_ALL_BALANCES" && is_admin_) {
response = "All balances:\n";
for (const auto& [address, balance] : blockchain_.getBalances()) {
response += address + ": " + std::to_string(balance) + "\n";
}
}
else {
response = "Unknown command\n";
}
}
sendResponse(response);
}
void sendResponse(const std::string& response) {
auto self(shared_from_this());
boost::asio::async_write(socket_, boost::asio::buffer(response + "> "),
[](boost::system::error_code, std::size_t) {});
}
void sendPrompt(const std::string& prompt) {
auto self(shared_from_this());
boost::asio::async_write(socket_, boost::asio::buffer(prompt),
[](boost::system::error_code, std::size_t) {});
}
};
// ================== Modified AdminServer ==================
class AdminServer {
private:
boost::asio::io_context& io_context_;
tcp::acceptor acceptor_;
Blockchain blockchain_;
UserManager auth_manager_;
void startAccept() {
acceptor_.async_accept(
[this](boost::system::error_code ec, tcp::socket socket) {
if (!ec) {
std::make_shared<Session>(std::move(socket),
blockchain_,
auth_manager_)->start();
}
startAccept();
});
}
public:
AdminServer(boost::asio::io_context& io_context, short port)
: io_context_(io_context),
acceptor_(io_context, tcp::endpoint(tcp::v4(), port)) {
startAccept();
}
};
int main() {
short port = 12345;
try {
boost::asio::io_context io_context;
AdminServer server(io_context, port);
std::cout << "Admin server is running on port " << port << std::endl;
io_context.run();
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}