-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDistributedServer.cs
More file actions
1740 lines (1509 loc) · 86.1 KB
/
DistributedServer.cs
File metadata and controls
1740 lines (1509 loc) · 86.1 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
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using NBitcoin; // Для работы с Bitcoin
namespace BitcoinFinder
{
public class DistributedServer
{
private readonly int port;
private readonly ConcurrentDictionary<string, AgentConnection> connectedAgents;
private readonly ConcurrentQueue<SearchBlock> pendingBlocks;
private readonly ConcurrentDictionary<int, SearchBlock> assignedBlocks;
private readonly List<string> foundResults;
private TcpListener? tcpListener;
private CancellationTokenSource? serverCts;
private bool isRunning = false;
private int currentBlockId = 1;
private readonly object lockObject = new object();
// Параметры поиска
private string targetAddress = "";
private int wordCount = 12;
private long totalCombinations = 0;
private long blockSize = 100000;
// PUBLIC: Позволяет форме сервера настроить размер блока перед запуском
public long BlockSize
{
get => blockSize;
set
{
if (value > 0)
{
blockSize = value;
}
}
}
private DateTime searchStartTime;
// Статистика
private long totalProcessed = 0;
private int completedBlocks = 0;
private readonly ConcurrentDictionary<string, AgentStats> agentStats;
// Собственный поиск сервера
private bool enableServerSearch = true;
private int serverThreads = 2; // Количество потоков для поиска на сервере
private long serverProcessedCount = 0;
private Task? serverSearchTask;
private AdvancedSeedPhraseFinder? serverFinder;
private const string AgentStateFile = "server_agents_state.json";
private Dictionary<string, AgentProgressState> agentProgressStates = new();
private class AgentProgressState
{
public string AgentId { get; set; } = "";
public string AgentName { get; set; } = "";
public int Threads { get; set; } = 1;
public int? LastBlockId { get; set; }
public long? LastIndex { get; set; }
public DateTime LastSeen { get; set; }
}
private void SaveAgentProgressStates()
{
try
{
File.WriteAllText(AgentStateFile, System.Text.Json.JsonSerializer.Serialize(agentProgressStates));
}
catch { }
}
private void LoadAgentProgressStates()
{
try
{
if (File.Exists(AgentStateFile))
{
agentProgressStates = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, AgentProgressState>>(File.ReadAllText(AgentStateFile)) ?? new();
}
}
catch { agentProgressStates = new(); }
}
public event Action<string>? OnLog;
public event Action<string>? OnFoundResult;
public event Action<ServerStats>? OnStatsUpdate;
public DistributedServer(int port = 5000)
{
this.port = port;
connectedAgents = new ConcurrentDictionary<string, AgentConnection>();
pendingBlocks = new ConcurrentQueue<SearchBlock>();
assignedBlocks = new ConcurrentDictionary<int, SearchBlock>();
foundResults = new List<string>();
agentStats = new ConcurrentDictionary<string, AgentStats>();
LoadAgentProgressStates();
// Таймер автосохранения состояния
var autosaveTimer = new System.Timers.Timer(10000); // 10 секунд
autosaveTimer.Elapsed += (s, e) => SaveAgentProgressStates();
autosaveTimer.AutoReset = true;
autosaveTimer.Start();
}
public async Task StartAsync(string targetBitcoinAddress, int wordCount, long? totalCombinations = null, bool enableServerSearch = true, int serverThreads = 2)
{
if (isRunning) return;
this.targetAddress = targetBitcoinAddress;
this.wordCount = wordCount;
this.searchStartTime = DateTime.Now;
this.enableServerSearch = enableServerSearch;
this.serverThreads = Math.Max(1, Math.Min(serverThreads, Environment.ProcessorCount));
// Инициализируем поисковый движок сервера
if (this.enableServerSearch)
{
serverFinder = new AdvancedSeedPhraseFinder();
}
// Вычисляем общее количество комбинаций если не задано
if (totalCombinations.HasValue)
{
this.totalCombinations = totalCombinations.Value;
}
else
{
var finder = new AdvancedSeedPhraseFinder();
var bip39Words = finder.GetBip39Words();
this.totalCombinations = (long)Math.Pow(bip39Words.Count, wordCount);
if (this.totalCombinations <= 0) // Overflow protection
this.totalCombinations = long.MaxValue;
}
Log($"[SERVER] Запуск сервера на порту {port}");
Log($"[SERVER] Целевой адрес: {targetAddress}");
Log($"[SERVER] Количество слов: {wordCount}");
Log($"[SERVER] Всего комбинаций: {this.totalCombinations:N0}");
Log($"[SERVER] Размер блока: {blockSize:N0}");
Log($"[SERVER] Собственный поиск сервера: {(this.enableServerSearch ? $"ВКЛ ({this.serverThreads} потоков)" : "ВЫКЛ")}");
// Генерируем блоки заданий
GenerateSearchBlocks();
serverCts = new CancellationTokenSource();
tcpListener = new TcpListener(IPAddress.Any, port);
tcpListener.Start();
isRunning = true;
Log($"[SERVER] Сервер запущен. Ожидание подключений...");
// Запускаем задачи сервера
var acceptTask = AcceptClientsAsync(serverCts.Token);
var monitorTask = MonitorAgentsAsync(serverCts.Token);
var statsTask = UpdateStatsAsync(serverCts.Token);
var allTasks = new List<Task> { acceptTask, monitorTask, statsTask };
// Запускаем собственный поиск сервера
if (this.enableServerSearch)
{
serverSearchTask = RunServerSearchAsync(serverCts.Token);
allTasks.Add(serverSearchTask);
Log($"[SERVER] Запущен собственный поиск с {this.serverThreads} потоками");
}
await Task.WhenAny(allTasks);
}
public void Stop()
{
if (!isRunning) return;
Log("[SERVER] Остановка сервера...");
isRunning = false;
// Отправляем команду SHUTDOWN всем агентам
foreach (var agent in connectedAgents.Values)
{
try
{
var shutdownMsg = JsonSerializer.Serialize(new { command = "SHUTDOWN" });
agent.Writer?.WriteLine(shutdownMsg);
}
catch { }
}
serverCts?.Cancel();
tcpListener?.Stop();
SaveAgentProgressStates(); // Финальное сохранение
Log("[SERVER] Сервер остановлен");
}
private void GenerateSearchBlocks()
{
Log("[SERVER] Генерация блоков заданий...");
long blocksGenerated = 0;
// Улучшенная адаптивная система размеров блоков
long adaptiveBlockSize = CalculateOptimalBlockSize();
Log($"[SERVER] Используется размер блока: {adaptiveBlockSize:N0}");
// Генерируем больше блоков, убираем ограничение в 10000
for (long startIndex = 0; startIndex < totalCombinations; startIndex += adaptiveBlockSize)
{
long endIndex = Math.Min(startIndex + adaptiveBlockSize - 1, totalCombinations - 1);
var block = new SearchBlock
{
BlockId = currentBlockId++,
StartIndex = startIndex,
EndIndex = endIndex,
WordCount = wordCount,
TargetAddress = targetAddress,
Status = BlockStatus.Pending,
CreatedAt = DateTime.Now,
CurrentIndex = startIndex,
Priority = CalculateBlockPriority(startIndex, endIndex)
};
pendingBlocks.Enqueue(block);
blocksGenerated++;
// Увеличиваем лимит блоков в памяти и добавляем динамическую генерацию
if (blocksGenerated >= 50000) // Увеличено с 10000
{
Log($"[SERVER] Сгенерировано {blocksGenerated:N0} блоков (предварительная партия)");
Log($"[SERVER] Покрыто {endIndex + 1:N0} из {totalCombinations:N0} комбинаций");
break;
}
}
Log($"[SERVER] Генерация завершена: {blocksGenerated:N0} блоков, размер блока: {adaptiveBlockSize:N0}");
}
private long CalculateOptimalBlockSize()
{
// Базовый размер блока
long baseBlockSize = blockSize;
// Адаптируем размер блока в зависимости от количества подключенных агентов
int connectedAgentCount = connectedAgents.Count;
if (connectedAgentCount > 0)
{
// Уменьшаем размер блока при большом количестве агентов для лучшего распределения
double agentFactor = Math.Max(0.5, 1.0 - (connectedAgentCount - 1) * 0.1);
baseBlockSize = (long)(baseBlockSize * agentFactor);
}
// Ограничиваем минимальный и максимальный размер
return Math.Max(1000, Math.Min(baseBlockSize, 1000000));
}
private long CalculateAgentMaxBlocks(AgentConnection agent)
{
// Базовое количество блоков = количество потоков агента
long baseBlocks = agent.Threads;
// Учитываем мощность обработки агента
double powerMultiplier = agent.ProcessingPower;
// Учитываем общее количество агентов (больше агентов = меньше блоков на агента)
int totalAgents = connectedAgents.Count;
double agentFactor = totalAgents > 1 ? 1.0 / Math.Sqrt(totalAgents) : 1.0;
// Рассчитываем максимальное количество блоков
long maxBlocks = (long)(baseBlocks * powerMultiplier * agentFactor);
// Ограничиваем значения
return Math.Max(1, Math.Min(maxBlocks, agent.Threads * 3)); // Максимум 3 блока на поток
}
private void UpdateAgentProcessingPower(AgentConnection agent, double currentRate)
{
// Обновляем мощность обработки на основе текущей скорости
if (currentRate > 0)
{
// Плавное обновление мощности (70% старое значение + 30% новое)
agent.ProcessingPower = agent.ProcessingPower * 0.7 + (currentRate / 1000.0) * 0.3;
// Обновляем максимальное количество блоков
agent.MaxConcurrentBlocks = CalculateAgentMaxBlocks(agent);
Log($"[SERVER] Агент {agent.AgentId}: мощность {agent.ProcessingPower:F2}, макс. блоков {agent.MaxConcurrentBlocks}");
}
}
private int CalculateBlockPriority(long startIndex, long endIndex)
{
// Приоритет на основе позиции в поиске (чем раньше, тем выше приоритет)
var progress = (double)startIndex / totalCombinations;
if (progress < 0.1) return 10; // Высокий приоритет для первых 10%
if (progress < 0.3) return 8; // Высокий для первых 30%
if (progress < 0.5) return 6; // Средний для первых 50%
if (progress < 0.8) return 4; // Низкий для 50-80%
return 2; // Очень низкий для последних 20%
}
private async Task RunServerSearchAsync(CancellationToken token)
{
Log("[SERVER] Начинаем собственный поиск сервера...");
try
{
var tasks = new List<Task>();
// Запускаем потоки поиска
for (int threadId = 0; threadId < serverThreads; threadId++)
{
int localThreadId = threadId;
var task = Task.Run(async () => await ServerSearchWorkerAsync(localThreadId, token), token);
tasks.Add(task);
}
await Task.WhenAll(tasks);
}
catch (OperationCanceledException)
{
Log("[SERVER] Поиск сервера остановлен");
}
catch (Exception ex)
{
Log($"[SERVER] Ошибка в поиске сервера: {ex.Message}");
}
}
private async Task ServerSearchWorkerAsync(int threadId, CancellationToken token)
{
Log($"[SERVER] Поток сервера {threadId} запущен");
var finder = new AdvancedSeedPhraseFinder();
var bip39Words = finder.GetBip39Words();
while (!token.IsCancellationRequested)
{
// Получаем блок для обработки
SearchBlock? block = GetNextBlockForServer();
if (block == null)
{
await Task.Delay(5000, token); // Ждем новых блоков
continue;
}
Log($"[SERVER] Поток {threadId} обрабатывает блок {block.BlockId} ({block.StartIndex}-{block.EndIndex})");
try
{
await ProcessServerBlockAsync(block, finder, bip39Words, threadId, token);
// Помечаем блок как завершенный
lock (lockObject)
{
block.Status = BlockStatus.Completed;
block.CompletedAt = DateTime.Now;
block.AssignedTo = $"SERVER_THREAD_{threadId}";
completedBlocks++;
}
Log($"[SERVER] Поток {threadId} завершил блок {block.BlockId}");
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
Log($"[SERVER] Ошибка обработки блока {block.BlockId} в потоке {threadId}: {ex.Message}");
// Возвращаем блок в очередь при ошибке
lock (lockObject)
{
block.Status = BlockStatus.Pending;
block.AssignedTo = null;
block.AssignedAt = null;
}
pendingBlocks.Enqueue(block);
}
}
}
private SearchBlock? GetNextBlockForServer()
{
lock (lockObject)
{
if (pendingBlocks.TryDequeue(out SearchBlock? block))
{
block.Status = BlockStatus.Assigned;
block.AssignedTo = "SERVER";
block.AssignedAt = DateTime.Now;
assignedBlocks.TryAdd(block.BlockId, block);
return block;
}
}
return null;
}
private async Task ProcessServerBlockAsync(SearchBlock block, AdvancedSeedPhraseFinder finder,
List<string> bip39Words, int threadId, CancellationToken token)
{
long processed = 0;
var startTime = DateTime.Now;
var lastLogTime = startTime;
// Множество для отслеживания уникальности комбинаций
var processedCombinations = new HashSet<string>();
for (long i = block.StartIndex; i <= block.EndIndex && !token.IsCancellationRequested; i++)
{
try
{
// Генерируем seed-фразу по индексу
string seedPhrase = GenerateSeedPhraseByIndex(i, bip39Words, block.WordCount);
// Проверяем уникальность комбинации
if (!processedCombinations.Add(seedPhrase))
{
Log($"[SERVER] ВНИМАНИЕ: Дублированная комбинация обнаружена в потоке {threadId}: {seedPhrase} (индекс: {i})");
}
// Логируем текущую комбинацию каждые 5000 итераций
var now = DateTime.Now;
if (processed % 5000 == 0)
{
Log($"[SERVER] Поток {threadId}: текущая комбинация: {seedPhrase} (индекс: {i:N0})");
}
// Проверяем валидность
if (!finder.IsValidSeedPhrase(seedPhrase))
continue;
// Генерируем адрес и проверяем совпадение
string generatedAddress = finder.GenerateBitcoinAddress(seedPhrase);
if (generatedAddress == block.TargetAddress)
{
// Найдено совпадение!
string? privateKey = null;
try
{
var mnemonic = new Mnemonic(seedPhrase, Wordlist.English);
var seed = mnemonic.DeriveSeed();
var masterKey = ExtKey.CreateFromSeed(seed);
var fullPath = new KeyPath("44'/0'/0'/0/0");
var key = masterKey.Derive(fullPath).PrivateKey;
privateKey = key.GetWif(Network.Main).ToString();
}
catch { }
var result = $"*** НАЙДЕНО СЕРВЕРОМ! *** Фраза: {seedPhrase}, Ключ: {privateKey}, Адрес: {generatedAddress}, Поток: {threadId}";
foundResults.Add(result);
OnFoundResult?.Invoke(result);
Log($"[SERVER] {result}");
// Сохраняем результат в файл
await SaveFoundResultAsync(seedPhrase, privateKey, generatedAddress, "SERVER", threadId);
}
processed++;
Interlocked.Increment(ref serverProcessedCount);
Interlocked.Increment(ref totalProcessed);
// Обновляем прогресс блока
block.CurrentIndex = i;
block.LastProgressAt = DateTime.Now;
if (processed % 10000 == 0)
{
var elapsed = DateTime.Now - startTime;
var rate = processed / Math.Max(elapsed.TotalSeconds, 1);
Log($"[SERVER] Поток {threadId}: обработано {processed:N0}, скорость {rate:F0}/сек, уникальных комбинаций: {processedCombinations.Count:N0}");
}
}
catch (Exception ex)
{
Log($"[SERVER] Ошибка обработки индекса {i} в потоке {threadId}: {ex.Message}");
}
}
Log($"[SERVER] Поток {threadId} завершил блок {block.BlockId}. Всего обработано: {processed:N0}, уникальных комбинаций: {processedCombinations.Count:N0}");
}
private string GenerateSeedPhraseByIndex(long index, List<string> bip39Words, int wordCount)
{
var words = new string[wordCount];
var tempIndex = index;
for (int pos = 0; pos < wordCount; pos++)
{
words[pos] = bip39Words[(int)(tempIndex % bip39Words.Count)];
tempIndex /= bip39Words.Count;
}
return string.Join(" ", words);
}
private async Task SaveFoundResultAsync(string seedPhrase, string? privateKey, string address, string foundBy, int threadId)
{
try
{
var resultData = new
{
Timestamp = DateTime.Now,
SeedPhrase = seedPhrase,
PrivateKey = privateKey,
Address = address,
FoundBy = foundBy,
ThreadId = threadId,
SearchStartTime = searchStartTime,
TotalProcessed = totalProcessed
};
var json = JsonSerializer.Serialize(resultData, new JsonSerializerOptions { WriteIndented = true });
var fileName = $"found_result_{DateTime.Now:yyyyMMdd_HHmmss}_{foundBy}_T{threadId}.json";
await File.WriteAllTextAsync(fileName, json);
Log($"[SERVER] Результат сохранен в файл: {fileName}");
}
catch (Exception ex)
{
Log($"[SERVER] Ошибка сохранения результата: {ex.Message}");
}
}
private async Task AcceptClientsAsync(CancellationToken token)
{
while (!token.IsCancellationRequested && isRunning)
{
try
{
var tcpClient = await tcpListener!.AcceptTcpClientAsync();
var clientEndpoint = tcpClient.Client.RemoteEndPoint?.ToString() ?? "unknown";
Log($"[SERVER] Новое подключение от {clientEndpoint}");
// Обрабатываем клиента в отдельной задаче
_ = Task.Run(() => HandleClientAsync(tcpClient, clientEndpoint, token));
}
catch (ObjectDisposedException)
{
break; // Сервер остановлен
}
catch (Exception ex)
{
Log($"[SERVER] Ошибка при принятии подключения: {ex.Message}");
await Task.Delay(1000, token);
}
}
}
private async Task HandleClientAsync(TcpClient client, string clientEndpoint, CancellationToken token)
{
string agentId = $"Agent_{DateTime.Now:HHmmss}_{clientEndpoint}";
AgentConnection? agentConnection = null;
try
{
using (client)
using (var stream = client.GetStream())
using (var reader = new StreamReader(stream, Encoding.UTF8))
using (var writer = new StreamWriter(stream, Encoding.UTF8) { AutoFlush = true })
{
agentConnection = new AgentConnection
{
AgentId = agentId,
Endpoint = clientEndpoint,
ConnectedAt = DateTime.Now,
LastActivity = DateTime.Now,
Writer = writer,
IsConnected = true
};
connectedAgents.TryAdd(agentId, agentConnection);
agentStats.TryAdd(agentId, new AgentStats { AgentId = agentId });
Log($"[SERVER] Создана статистика для агента {agentId}");
Log($"[SERVER] Агент {agentId} подключен");
// Logger.LogConnection($"Агент {agentId} подключен с адреса {clientEndpoint}");
// Ждем приветствие от агента (опционально - для обратной совместимости)
bool isEnhancedAgent = false;
while (!token.IsCancellationRequested && client.Connected && isRunning)
{
try
{
// Читаем сообщение от агента с таймаутом
var lineTask = reader.ReadLineAsync();
var timeoutTask = Task.Delay(120000, token); // 2 минуты таймаут
var completedTask = await Task.WhenAny(lineTask, timeoutTask);
if (completedTask == timeoutTask)
{
Log($"[SERVER] Таймаут ожидания сообщения от {agentId}");
break;
}
string? line = await lineTask;
if (line == null) break;
agentConnection.LastActivity = DateTime.Now;
Dictionary<string, object>? request = null;
try
{
request = JsonSerializer.Deserialize<Dictionary<string, object>>(line);
}
catch (JsonException ex)
{
Log($"[SERVER] Ошибка JSON от {agentId}: {ex.Message}");
await SendErrorResponse(writer, "INVALID_JSON", ex.Message);
continue;
}
if (request == null || !request.ContainsKey("command"))
{
Log($"[SERVER] Некорректное сообщение от {agentId}: нет команды");
await SendErrorResponse(writer, "MISSING_COMMAND", "Command field is required");
continue;
}
string command = request["command"].ToString()!;
// Валидируем команды
if (!IsValidCommand(command))
{
Log($"[SERVER] Неизвестная команда от {agentId}: {command}");
await SendErrorResponse(writer, "UNKNOWN_COMMAND", $"Unknown command: {command}");
continue;
}
try
{
switch (command)
{
case "AGENT_HELLO":
case "HELLO":
isEnhancedAgent = await HandleAgentHello(request, agentConnection, writer);
break;
case "AGENT_GOODBYE":
await HandleAgentGoodbye(request, agentId, writer);
Log($"[SERVER] Агент {agentId} попрощался");
return; // Выходим из цикла
case "HEARTBEAT":
await HandleHeartbeat(request, agentConnection, writer);
break;
case "GET_TASK":
await HandleGetTaskRequest(agentConnection, writer);
break;
case "TASK_ACCEPTED":
await HandleTaskAccepted(request, agentId, writer);
break;
case "TASK_COMPLETED":
await HandleTaskCompleted(request, agentId, writer);
break;
case "REPORT_PROGRESS":
await HandleProgressUpdate(request, agentId);
await writer.WriteLineAsync(JsonSerializer.Serialize(new { command = "ACK" }));
break;
case "REPORT_FOUND":
await HandleFoundReport(request, agentId);
await writer.WriteLineAsync(JsonSerializer.Serialize(new { command = "ACK" }));
break;
case "RELEASE_BLOCK":
await HandleBlockRelease(request, agentId);
await writer.WriteLineAsync(JsonSerializer.Serialize(new { command = "ACK" }));
break;
case "PING":
await writer.WriteLineAsync(JsonSerializer.Serialize(new {
command = "PONG",
timestamp = DateTime.Now,
serverTime = DateTime.Now
}));
break;
case "PONG":
// Ответ на наш PING - просто обновляем активность
Log($"[SERVER] Получен PONG от {agentId}");
break;
case "REQUEST_STATUS":
await HandleStatusRequest(agentConnection, writer);
break;
default:
Log($"[SERVER] Неподдерживаемая команда от {agentId}: {command}");
await SendErrorResponse(writer, "UNSUPPORTED_COMMAND", $"Command {command} is not supported in this version");
break;
}
}
catch (Exception ex)
{
Log($"[SERVER] Ошибка обработки команды {command} от {agentId}: {ex.Message}");
await SendErrorResponse(writer, "PROCESSING_ERROR", ex.Message);
}
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
Log($"[SERVER] Общая ошибка при обработке {agentId}: {ex.Message}");
await Task.Delay(1000, token); // Пауза перед продолжением
}
}
}
}
catch (Exception ex)
{
Log($"[SERVER] Ошибка соединения с {agentId}: {ex.Message}");
}
finally
{
// Очистка при отключении агента
if (agentConnection != null)
{
agentConnection.IsConnected = false;
agentConnection.DisconnectedAt = DateTime.Now;
// Возвращаем назначенные блоки в очередь
var blocksReturned = 0;
foreach (var kvp in assignedBlocks.ToList())
{
if (kvp.Value.AssignedTo == agentId)
{
kvp.Value.Status = BlockStatus.Pending;
kvp.Value.AssignedTo = null;
kvp.Value.AssignedAt = null;
pendingBlocks.Enqueue(kvp.Value);
assignedBlocks.TryRemove(kvp.Key, out _);
blocksReturned++;
Log($"[SERVER] Блок {kvp.Key} возвращён в очередь после отключения агента {agentId}");
}
}
if (blocksReturned > 0)
{
Log($"[SERVER] {blocksReturned} блоков возвращено в очередь после отключения {agentId}");
}
}
connectedAgents.TryRemove(agentId, out _);
agentStats.TryRemove(agentId, out _);
Log($"[SERVER] Агент {agentId} отключен");
// Logger.LogConnection($"Агент {agentId} отключен");
}
}
private bool IsValidCommand(string command)
{
var validCommands = new HashSet<string>
{
"AGENT_HELLO", "HELLO", "AGENT_GOODBYE", "HEARTBEAT", "GET_TASK",
"TASK_ACCEPTED", "TASK_COMPLETED", "REPORT_PROGRESS",
"REPORT_FOUND", "RELEASE_BLOCK", "PING", "PONG", "REQUEST_STATUS"
};
return validCommands.Contains(command);
}
private async Task SendErrorResponse(StreamWriter writer, string errorCode, string errorMessage)
{
try
{
var errorResponse = new
{
command = "ERROR",
errorCode = errorCode,
errorMessage = errorMessage,
timestamp = DateTime.Now
};
await writer.WriteLineAsync(JsonSerializer.Serialize(errorResponse));
}
catch (Exception ex)
{
Log($"[SERVER] Ошибка отправки ошибки: {ex.Message}");
}
}
private async Task<bool> HandleAgentHello(Dictionary<string, object> request, AgentConnection agent, StreamWriter writer)
{
try
{
string version = request.ContainsKey("version") ? request["version"].ToString()! : "1.0";
var capabilities = new List<string>();
if (request.ContainsKey("capabilities"))
{
var capsElement = (JsonElement)request["capabilities"];
if (capsElement.ValueKind == JsonValueKind.Array)
{
capabilities = capsElement.EnumerateArray()
.Select(e => e.GetString() ?? "")
.Where(s => !string.IsNullOrEmpty(s))
.ToList();
}
}
// Обновляем информацию об агенте
if (request.ContainsKey("agentId"))
{
string providedId = request["agentId"].ToString()!;
if (!string.IsNullOrWhiteSpace(providedId))
{
agent.AgentId = providedId;
}
}
// Сохраняем информацию об агенте
string agentName = request.ContainsKey("agentName") ? request["agentName"].ToString()! : agent.AgentId;
int threads = request.ContainsKey("threads") ? GetInt32Value(request["threads"]) : 1;
// Обновляем информацию о потоках агента
agent.Threads = threads;
agent.ProcessingPower = 1.0; // Начальная мощность
agent.MaxConcurrentBlocks = CalculateAgentMaxBlocks(agent);
if (!agentProgressStates.ContainsKey(agent.AgentId))
{
agentProgressStates[agent.AgentId] = new AgentProgressState
{
AgentId = agent.AgentId,
AgentName = agentName,
Threads = threads,
LastSeen = DateTime.Now
};
Log($"[SERVER] Создана запись прогресса для агента {agent.AgentId} ({agentName}, {threads} потоков, макс. блоков: {agent.MaxConcurrentBlocks})");
}
else
{
agentProgressStates[agent.AgentId].AgentName = agentName;
agentProgressStates[agent.AgentId].Threads = threads;
agentProgressStates[agent.AgentId].LastSeen = DateTime.Now;
Log($"[SERVER] Обновлена информация агента {agent.AgentId} ({agentName}, {threads} потоков, макс. блоков: {agent.MaxConcurrentBlocks})");
}
// Отправляем ответ
var response = new
{
command = "HELLO_ACK",
serverVersion = "2.0",
serverCapabilities = new[] { "DISTRIBUTED_SEARCH", "PROGRESS_TRACKING", "HEARTBEAT", "BLOCK_MANAGEMENT", "ADAPTIVE_LOAD_BALANCING" },
maxBlockSize = blockSize,
supportedWordCounts = new[] { 12, 15, 18, 21, 24 },
maxConcurrentBlocks = agent.MaxConcurrentBlocks,
timestamp = DateTime.Now
};
await writer.WriteLineAsync(JsonSerializer.Serialize(response));
Log($"[SERVER] Приветствие агента {agent.AgentId} (версия {version}, потоки: {threads}, возможности: {string.Join(", ", capabilities)})");
return true;
}
catch (Exception ex)
{
Log($"[SERVER] Ошибка обработки приветствия: {ex.Message}");
return false;
}
}
private async Task HandleAgentGoodbye(Dictionary<string, object> request, string agentId, StreamWriter writer)
{
try
{
// Получаем логический ID агента из сообщения, если он есть
string logicalAgentId = agentId;
if (request.ContainsKey("agentId"))
{
string providedId = request["agentId"].ToString()!;
if (!string.IsNullOrWhiteSpace(providedId))
{
logicalAgentId = providedId;
Log($"[SERVER] Используем логический ID агента из сообщения: {logicalAgentId} (вместо сетевого: {agentId})");
}
}
var response = new
{
command = "GOODBYE_ACK",
message = "Goodbye, thank you for your service",
timestamp = DateTime.Now
};
await writer.WriteLineAsync(JsonSerializer.Serialize(response));
Log($"[SERVER] Агент {logicalAgentId} попрощался");
}
catch (Exception ex)
{
Log($"[SERVER] Ошибка обработки прощания: {ex.Message}");
}
}
private async Task HandleHeartbeat(Dictionary<string, object> request, AgentConnection agent, StreamWriter writer)
{
try
{
string status = request.ContainsKey("status") ? request["status"].ToString()! : "unknown";
var response = new
{
command = "HEARTBEAT_ACK",
serverStatus = "running",
timestamp = DateTime.Now,
uptime = DateTime.Now - searchStartTime
};
await writer.WriteLineAsync(JsonSerializer.Serialize(response));
// Обновляем статистику активности
agent.LastActivity = DateTime.Now;
// Логируем heartbeat для отладки
Log($"[SERVER] Получен heartbeat от агента {agent.AgentId}, статус: {status}");
}
catch (Exception ex)
{
Log($"[SERVER] Ошибка обработки heartbeat: {ex.Message}");
await SendErrorResponse(writer, "HEARTBEAT_ERROR", ex.Message);
}
}
private async Task HandleTaskAccepted(Dictionary<string, object> request, string agentId, StreamWriter writer)
{
try
{
// Получаем логический ID агента из сообщения, если он есть
string logicalAgentId = agentId;
if (request.ContainsKey("agentId"))
{
string providedId = request["agentId"].ToString()!;
if (!string.IsNullOrWhiteSpace(providedId))
{
logicalAgentId = providedId;
Log($"[SERVER] Используем логический ID агента из сообщения: {logicalAgentId} (вместо сетевого: {agentId})");
}
}
int blockId = Convert.ToInt32(request["blockId"]);
if (assignedBlocks.TryGetValue(blockId, out var block) && block.AssignedTo == logicalAgentId)
{
block.Status = BlockStatus.Assigned; // Подтверждаем назначение
Log($"[SERVER] Агент {logicalAgentId} подтвердил принятие блока {blockId}");
await writer.WriteLineAsync(JsonSerializer.Serialize(new { command = "ACK" }));
}
else
{
Log($"[SERVER] Агент {logicalAgentId} пытается подтвердить несуществующий блок {blockId}");
await SendErrorResponse(writer, "INVALID_BLOCK", $"Block {blockId} not found or not assigned to you");
}
}
catch (Exception ex)
{
Log($"[SERVER] Ошибка подтверждения задания: {ex.Message}");
await SendErrorResponse(writer, "TASK_ACCEPTED_ERROR", ex.Message);
}
}
private async Task HandleTaskCompleted(Dictionary<string, object> request, string agentId, StreamWriter writer)
{
try
{
// Получаем логический ID агента из сообщения, если он есть
string logicalAgentId = agentId;
if (request.ContainsKey("agentId"))
{
string providedId = request["agentId"].ToString()!;
if (!string.IsNullOrWhiteSpace(providedId))
{
logicalAgentId = providedId;
Log($"[SERVER] Используем логический ID агента из сообщения: {logicalAgentId} (вместо сетевого: {agentId})");
}
}
int blockId = Convert.ToInt32(request["blockId"]);
if (assignedBlocks.TryRemove(blockId, out var block) && block.AssignedTo == logicalAgentId)
{
block.Status = BlockStatus.Completed;