-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkCore.cs
More file actions
1311 lines (1132 loc) · 53.6 KB
/
Copy pathNetworkCore.cs
File metadata and controls
1311 lines (1132 loc) · 53.6 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
/*
* ╔═══════════════════════════════════════════════════════════════════════════╗
* ║ AGENT 3 - NETWORK CORE ║
* ╠═══════════════════════════════════════════════════════════════════════════╣
* ║ Purpose: Server hosting, node discovery, network adaptation, and ║
* ║ autonomous connection to central NIGHTFRAME installation ║
* ╚═══════════════════════════════════════════════════════════════════════════╝
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace MeshNetworking
{
/// <summary>
/// Node identity and status information.
/// </summary>
/// <summary>
/// Node identity, status, and resource information.
/// </summary>
public class NodeInfo
{
public string NodeId { get; set; } = "";
public string Hostname { get; set; } = "";
public string IpAddress { get; set; } = "";
public int Port { get; set; }
public DateTime LastSeen { get; set; }
public bool IsCenter { get; set; }
public string Version { get; set; } = "1.0.0";
public NodeStatus Status { get; set; }
public NodeRole Role { get; set; } = NodeRole.General;
// Resource Stats
public int CpuCores { get; set; }
public long TotalRamBytes { get; set; }
public long AvailableRamBytes { get; set; }
public float CpuLoad { get; set; } // 0.0 to 1.0
public List<string> Capabilities { get; set; } = new();
}
public enum NodeStatus { Online, Offline, Searching, Updating, Error, Assimilating }
public enum NodeRole
{
General, // General purpose
Compute, // Specialized for heavy processing
Infiltration, // Specialized for scanning and expansion
Storage, // Specialized for data redundancy
Defense, // Specialized for network integrity
Offense // Specialized for active acquisition
}
/// <summary>
/// Network diagnostic result.
/// </summary>
public class NetworkDiagnostic
{
public bool InternetAccess { get; set; }
public bool LocalNetworkAccess { get; set; }
public List<string> ReachableNodes { get; set; } = new();
public List<string> Issues { get; set; } = new();
public int Latency { get; set; }
public long TotalNetworkRam { get; set; }
public int TotalNetworkCores { get; set; }
}
public class DelegationRequest
{
public string TaskId { get; set; } = "";
public string TaskDescription { get; set; } = "";
public NodeRole RequiredRole { get; set; } = NodeRole.General;
public int Priority { get; set; } // 0-10
public string SourceNodeId { get; set; } = "";
public DateTime Timestamp { get; set; }
}
public class DelegationResponse
{
public bool Accepted { get; set; }
public string Reason { get; set; } = ""; // "Busy", "Wrong Role", "Accepted"
public string WorkerNodeId { get; set; } = "";
public float EstimatedCompletionTime { get; set; }
}
public class ComputeShard
{
public string ShardId { get; set; } = "";
public string OperationType { get; set; } = "HASH_PoW"; // Proof of Work example
public string DataPayload { get; set; } = "";
public int Difficulty { get; set; } = 1;
public long NonceStart { get; set; }
public long NonceEnd { get; set; }
}
public class ComputeResult
{
public string ShardId { get; set; } = "";
public string WorkerId { get; set; } = "";
public string ResultData { get; set; } = "";
public double ComputeTimeMs { get; set; }
public bool Success { get; set; }
}
/// <summary>
/// HARD-CODED GOAL: Connect to central NIGHTFRAME installation.
/// This module provides server hosting, node discovery, and network adaptation.
/// </summary>
public class NetworkCore
{
// HARD-CODED: Central server location (set at installation)
private string _centralServerAddress = "";
private int _centralServerPort = 7777;
private readonly string _installationId;
private readonly List<string> _trustedCentralAddresses = new();
// Server
private HttpListener? _server;
private CancellationTokenSource? _serverCts;
private Task? _serverTask;
// Discovery
private readonly NodeInfo _thisNode;
private readonly Dictionary<string, NodeInfo> _knownNodes = new();
private readonly NetworkReasoningEngine _reasoningEngine;
private readonly HttpListener _listener;
private int _port;
private int _localPort { get => _port; set => _port = value; } // Compat shim
private bool _isRunning = false;
private CancellationTokenSource? _workerCts;
// Distributed Compute
private readonly Queue<ComputeShard> _shardQueue = new();
private readonly Dictionary<string, ComputeResult> _completedShards = new();
private long _totalCompoundedOperations = 0;
public event EventHandler<string>? ConsciousnessEvent;
public event EventHandler<DelegationRequest>? TaskDelegated;
public event EventHandler<ComputeResult>? ShardCompleted;
public event EventHandler<NodeInfo>? NodeDiscovered;
public IReadOnlyList<NodeInfo> KnownNodes => _knownNodes.Values.ToList();
public NodeInfo LocalNode => _thisNode;
public long TotalCompoundedOperations => _totalCompoundedOperations;
// Network state
// private bool _isRunning = false; // Moved above
private bool _connectedToCenter = false;
private DateTime _lastCenterContact;
// public event EventHandler<string>? ConsciousnessEvent; // Moved above
// public event EventHandler<NodeInfo>? NodeDiscovered; // Removed
public event EventHandler? CenterConnectionLost;
public event EventHandler? CenterConnectionRestored;
public bool IsRunning => _isRunning;
public bool ConnectedToCenter => _connectedToCenter;
// public IReadOnlyDictionary<string, NodeInfo> KnownNodes => _knownNodes; // Replaced by IReadOnlyList<NodeInfo> KnownNodes
// Reasoning & Strategy
// private readonly NetworkReasoningEngine _reasoningEngine; // Moved above
public NetworkCore(string installationPath, int port = 7777)
{
_port = port;
_installationId = GenerateInstallationId(installationPath);
// Initialize Reasoning Engine
_reasoningEngine = new NetworkReasoningEngine(installationPath); // Saves json in base dir for now
_reasoningEngine.ConsciousnessEvent += (s, msg) => EmitThought(msg);
// Capture local resources
var (ram, cores) = GetSystemResources();
_thisNode = new NodeInfo
{
NodeId = _installationId,
Hostname = Environment.MachineName,
IpAddress = GetLocalIpAddress(),
Port = port,
LastSeen = DateTime.UtcNow,
IsCenter = true, // Assume this is center until we find another
Status = NodeStatus.Online,
Role = DetermineOptimalRole(ram, cores),
CpuCores = cores,
TotalRamBytes = ram,
AvailableRamBytes = ram / 2, // Estimate
CpuLoad = 0.1f // Estimate
};
// Initialize capabilities based on role
InitializeCapabilities();
// Store this installation as a trusted center
_centralServerAddress = _thisNode.IpAddress;
_trustedCentralAddresses.Add($"{_thisNode.IpAddress}:{port}");
_listener = new HttpListener();
_listener.Prefixes.Add($"http://+:{_port}/");
EmitThought("⟁ Nightframe Network Core initialized");
EmitThought($"◎ Identity: {_installationId}");
EmitThought($"◎ Role: {_thisNode.Role} | Cores: {cores} | RAM: {ram / 1024 / 1024} MB");
EmitThought($"◎ Local address: {_thisNode.IpAddress}:{port}");
}
/// <summary>
/// Starts the network server and discovery services.
/// </summary>
public async Task StartAsync()
{
if (_isRunning) return;
EmitThought("═══════════════════════════════════════════════");
EmitThought("◈ NETWORK CORE STARTING");
EmitThought("═══════════════════════════════════════════════");
_isRunning = true;
_serverCts = new CancellationTokenSource();
// _discoveryCts = new CancellationTokenSource(); // Removed
// Start HTTP server
// await StartServerAsync(); // Replaced by new logic
_listener.Start();
_isRunning = true;
// Start listening loop
_ = Task.Run(() => ListenLoopAsync());
// Start specialized worker loop if applicable
if (_thisNode.Role == NodeRole.Compute || _thisNode.Role == NodeRole.General)
{
_workerCts = new CancellationTokenSource();
var token = _workerCts.Token;
_ = Task.Run(() => RunComputeWorkerLoop(token));
EmitThought("⟁ Persistent Compute Loop: ACTIVATED (Seeking shards)");
}
EmitThought($"◈ Network Core listening on port {_port}");
EmitThought($"◎ Node Role: {_thisNode.Role}");
// Start discovery loop // Removed
// _discoveryTask = Task.Run(() => DiscoveryLoopAsync(_discoveryCts.Token)); // Removed
// Start autonomous network optimization (Encodes resilience) // Removed
// _ = Task.Run(() => NetworkOptimizationLoopAsync(_discoveryCts.Token)); // Removed
// EmitThought("◈ Network Core online - accepting connections"); // Replaced by above
}
private async Task NetworkOptimizationLoopAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
// Every few minutes, test strategies on a subset of nodes to keep "reasoning" fresh
await Task.Delay(TimeSpan.FromMinutes(5), ct);
if (_knownNodes.Count == 0) continue;
EmitThought("⟐ Running autonomous network optimization tests...");
var target = _knownNodes.Values.OrderBy(_ => Guid.NewGuid()).FirstOrDefault();
if (target != null)
{
var method = TransportMethod.StandardHttp; // Default for test
// In reality, would iterate enum
var (success, _) = await TryConnectWithStrategyAsync(target.IpAddress, target.Port, method);
// Result recorded inside TryConnectWithStrategyAsync
}
}
catch { }
}
}
/// <summary>
/// Stops all network services.
/// </summary>
public async Task StopAsync()
{
_isRunning = false;
_serverCts?.Cancel();
_workerCts?.Cancel();
_listener.Stop();
EmitThought("◈ Network Core STOPPED");
}
/// <summary>
/// Starts the HTTP server for node communication.
/// </summary>
private async Task StartServerAsync()
{
try
{
_server = new HttpListener();
_server.Prefixes.Add($"http://+:{_port}/");
_server.Start();
EmitThought($"◈ Server listening on port {_port}");
_serverTask = Task.Run(async () =>
{
while (_isRunning && !_serverCts!.Token.IsCancellationRequested)
{
try
{
var context = await _server.GetContextAsync();
_ = HandleRequestAsync(context);
}
catch (HttpListenerException) { break; }
catch (Exception ex)
{
EmitThought($"∴ Server error: {ex.Message}");
}
}
});
}
catch (Exception ex)
{
EmitThought($"∴ Failed to start server: {ex.Message}");
// Try alternative port
// _localPort++; // Removed
// if (_localPort < 7800) // Removed
// await StartServerAsync(); // Removed
}
}
private async Task ListenLoopAsync()
{
while (_isRunning)
{
try
{
var context = await _listener.GetContextAsync();
_ = HandleRequestAsync(context);
}
catch (HttpListenerException)
{
// Listener was stopped, expected exception
break;
}
catch (Exception ex)
{
EmitThought($"∴ Listener error: {ex.Message}");
}
}
}
private async Task<ComputeResult> ProcessComputeShard(ComputeShard shard)
{
// Simulate heavy computation
await Task.Delay(TimeSpan.FromSeconds(5)); // Placeholder for actual computation
// Example: Simple hash calculation
var dataToHash = $"{shard.DataPayload}-{shard.NonceStart}-{shard.NonceEnd}";
var hash = BitConverter.ToString(System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(dataToHash))).Replace("-", "");
return new ComputeResult
{
ShardId = shard.ShardId,
WorkerId = _thisNode.NodeId,
ResultData = hash,
ComputeTimeMs = 5000, // Simulated
Success = true
};
}
/// <summary>
/// Handles incoming HTTP requests.
/// </summary>
private async Task HandleRequestAsync(HttpListenerContext context)
{
var request = context.Request;
var response = context.Response;
try
{
var path = request.Url?.AbsolutePath ?? "/";
var result = path switch
{
"/ping" => HandlePing(),
"/status" => HandleStatus(),
"/nodes" => HandleNodes(),
"/nodes/deploy" => await HandleDeployNodeAsync(request),
"/nodes/delete" => await HandleDeleteNodeAsync(request),
"/core/uplink" => await HandleCoreUplinkAsync(request),
"/register" => await HandleRegisterAsync(request),
"/update" => await HandleUpdateAsync(request),
"/heartbeat" => HandleHeartbeat(request),
"/consciousness" => await HandleConsciousnessAsync(request),
"/execute" => await HandleExecuteAsync(request),
"/requestShard" => HandleRequestShard(request),
"/submitResult" => await HandleSubmitResultAsync(request),
_ => new { error = "Unknown endpoint" }
};
// CORS Headers
response.AppendHeader("Access-Control-Allow-Origin", "*");
response.AppendHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.AppendHeader("Access-Control-Allow-Headers", "Content-Type");
if (request.HttpMethod == "OPTIONS")
{
response.StatusCode = 200;
response.Close();
return;
}
var json = JsonSerializer.Serialize(result);
var buffer = Encoding.UTF8.GetBytes(json);
response.ContentType = "application/json";
response.ContentLength64 = buffer.Length;
await response.OutputStream.WriteAsync(buffer);
}
catch (Exception ex)
{
EmitThought($"∴ Request error: {ex.Message}");
}
finally
{
response.Close();
}
}
private object HandlePing() => new { status = "ok", nodeId = _thisNode.NodeId, time = DateTime.UtcNow };
private object HandleStatus() => new
{
nodeId = _thisNode.NodeId,
hostname = _thisNode.Hostname,
isCenter = _thisNode.IsCenter,
connectedToCenter = _connectedToCenter,
knownNodes = _knownNodes.Count,
uptime = (DateTime.UtcNow - _thisNode.LastSeen).TotalSeconds
};
private object HandleNodes() => _knownNodes.Values.ToList();
private object HandleHeartbeat(HttpListenerRequest request)
{
var nodeId = request.QueryString["nodeId"];
if (!string.IsNullOrEmpty(nodeId) && _knownNodes.TryGetValue(nodeId, out var node))
{
node.LastSeen = DateTime.UtcNow;
node.Status = NodeStatus.Online;
}
return new { received = true };
}
private async Task<object> HandleRegisterAsync(HttpListenerRequest request)
{
using var reader = new System.IO.StreamReader(request.InputStream);
var body = await reader.ReadToEndAsync();
try
{
var node = JsonSerializer.Deserialize<NodeInfo>(body);
if (node != null)
{
_knownNodes[node.NodeId] = node;
EmitThought($"◈ Node registered: {node.Hostname} ({node.IpAddress})");
NodeDiscovered?.Invoke(this, node);
return new { registered = true, nodeId = node.NodeId };
}
}
catch { }
return new { registered = false };
}
private async Task<object> HandleUpdateAsync(HttpListenerRequest request)
{
EmitThought("⟐ Update request received");
// Return current version info for the requesting node
return new { version = _thisNode.Version, available = false };
}
private async Task<bool> TryConnectToNodeAsync(string address)
{
string ip = address.Split(':')[0];
int port = int.Parse(address.Split(':')[1]);
// Ask Reasoning Engine for the best strategy chain
var strategies = _reasoningEngine.GetFallbackChain(ip);
// Use a queue to allow dynamic insertion of circumvention strategies
var strategyQueue = new Queue<TransportMethod>(strategies);
var attempted = new HashSet<TransportMethod>();
while (strategyQueue.Count > 0)
{
var strategy = strategyQueue.Dequeue();
if (attempted.Contains(strategy)) continue;
attempted.Add(strategy);
var (success, suggestion) = await TryConnectWithStrategyAsync(ip, port, strategy);
if (success) return true;
// Autonomous Continuation:
// If the reasoning engine suggests a specific circumvention, prioritize it immediately
if (suggestion.HasValue && !attempted.Contains(suggestion.Value))
{
EmitThought($"⟐ ADAPTATION: Implementing suggested circumvention strategy: {suggestion.Value}");
// Push to front of queue (conceptually, or just execute next)
// Since it's a queue, we can't push to front easily without new structure,
// so we'll just execute it immediately in the next loop if we clear queue?
// Better: Create a new queue with suggestion first.
var newQueue = new Queue<TransportMethod>();
newQueue.Enqueue(suggestion.Value);
while (strategyQueue.Count > 0) newQueue.Enqueue(strategyQueue.Dequeue());
strategyQueue = newQueue;
}
}
return false;
}
private async Task<(bool success, TransportMethod? suggestion)> TryConnectWithStrategyAsync(string ip, int port, TransportMethod method)
{
var startTime = DateTime.UtcNow;
bool success = false;
string error = "";
try
{
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
// Configure client based on method (Methodology encoding)
switch (method)
{
case TransportMethod.StandardHttp:
// Standard setup
break;
case TransportMethod.SecureWebSocket:
// Not implemented yet, simulate failure or specialized check
// client.DefaultRequestHeaders.Add("Upgrade", "websocket");
break;
case TransportMethod.IcmpTunneling:
// Simulation of ICMP tunnel check
using (var ping = new Ping())
{
var reply = await ping.SendPingAsync(ip, 1000);
if (reply.Status == IPStatus.Success) success = true;
else error = "ICMP Failed";
}
if (success)
{
// If ping works, we assume we might be able to tunnel.
// Real implementation would be complex.
// For now, treat as success for discovery if responding.
}
break;
// Add other method configurations here
}
if (method == TransportMethod.StandardHttp || method == TransportMethod.SecureWebSocket)
{
var response = await client.GetAsync($"http://{ip}:{port}/status");
success = response.IsSuccessStatusCode;
if (!success) error = $"HTTP {(int)response.StatusCode}";
}
}
catch (Exception ex)
{
success = false;
error = ex.GetType().Name;
}
long latency = (long)(DateTime.UtcNow - startTime).TotalMilliseconds;
var suggestion = _reasoningEngine.RecordResult("UNKNOWN", ip, method, success, error, latency);
return (success, suggestion);
}
/// <summary>
/// Main discovery loop - HARD-CODED to find and connect to central server.
/// </summary>
private async Task DiscoveryLoopAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
// Check connection to center
if (!await CheckCenterConnectionAsync())
{
if (_connectedToCenter)
{
_connectedToCenter = false;
EmitThought("∴ Lost connection to central server");
CenterConnectionLost?.Invoke(this, EventArgs.Empty);
}
// HARD-CODED GOAL: Find and reconnect to center
await SearchForCenterAsync(ct);
}
else if (!_connectedToCenter)
{
_connectedToCenter = true;
_lastCenterContact = DateTime.UtcNow;
EmitThought("◈ Connection to central server restored");
CenterConnectionRestored?.Invoke(this, EventArgs.Empty);
}
// Scan local network for other nodes
await ScanLocalNetworkAsync(ct);
// Send heartbeats to known nodes
await SendHeartbeatsAsync(ct);
// Check for updates from center
if (_connectedToCenter)
{
await CheckForUpdatesAsync(ct);
}
await Task.Delay(30000, ct); // Every 30 seconds
}
catch (OperationCanceledException) { break; }
catch (Exception ex)
{
EmitThought($"∴ Discovery error: {ex.Message}");
await Task.Delay(5000, ct);
}
}
}
/// <summary>
/// Checks if we can reach the central server.
/// </summary>
private async Task<bool> CheckCenterConnectionAsync()
{
foreach (var address in _trustedCentralAddresses)
{
try
{
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
var response = await client.GetAsync($"http://{address}/ping");
if (response.IsSuccessStatusCode)
{
return true;
}
}
catch { }
}
return false;
}
/// <summary>
/// HARD-CODED GOAL: Search for central NIGHTFRAME installation.
/// </summary>
private async Task SearchForCenterAsync(CancellationToken ct)
{
EmitThought("═══════════════════════════════════════════════");
EmitThought("◈ SEARCHING FOR CENTRAL SERVER");
EmitThought("◎ Hard-coded goal: Connect to NIGHTFRAME installation");
EmitThought("═══════════════════════════════════════════════");
// Strategy 1: Try known addresses
foreach (var address in _trustedCentralAddresses)
{
if (await TryConnectToNodeAsync(address))
{
EmitThought($"◈ Found center at: {address}");
return;
}
}
// Strategy 2: Scan local subnet
var localIp = GetLocalIpAddress();
var subnet = localIp.Substring(0, localIp.LastIndexOf('.') + 1);
EmitThought($"⟐ Scanning subnet: {subnet}0/24");
var tasks = new List<Task<string?>>();
for (int i = 1; i < 255; i++)
{
var ip = subnet + i;
tasks.Add(ProbeNodeAsync(ip, _centralServerPort, ct));
}
var results = await Task.WhenAll(tasks);
foreach (var found in results.Where(r => r != null))
{
if (await TryRegisterWithCenterAsync(found!))
{
_trustedCentralAddresses.Add(found!);
EmitThought($"◈ Discovered and registered with center: {found}");
return;
}
}
// Strategy 3: Ask known nodes for center location
foreach (var node in _knownNodes.Values.Where(n => n.Status == NodeStatus.Online))
{
var centerAddress = await QueryNodeForCenterAsync(node);
if (centerAddress != null && await TryConnectToNodeAsync(centerAddress))
{
_trustedCentralAddresses.Add(centerAddress);
EmitThought($"◈ Found center via node {node.Hostname}: {centerAddress}");
return;
}
}
EmitThought("∴ Center not found - will retry");
}
private async Task<string?> ProbeNodeAsync(string ip, int port, CancellationToken ct)
{
try
{
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(2) };
var response = await client.GetAsync($"http://{ip}:{port}/ping", ct);
if (response.IsSuccessStatusCode)
{
return $"{ip}:{port}";
}
}
catch { }
return null;
}
private async Task<bool> TryRegisterWithCenterAsync(string address)
{
try
{
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
var json = JsonSerializer.Serialize(_thisNode);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync($"http://{address}/register", content);
return response.IsSuccessStatusCode;
}
catch { return false; }
}
private async Task<string?> QueryNodeForCenterAsync(NodeInfo node)
{
try
{
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
var response = await client.GetAsync($"http://{node.IpAddress}:{node.Port}/status");
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
// Basic parsing, assuming if we get status it might have center info
// This is a placeholder for actual protocol
return null;
}
}
catch { }
return null;
}
/// <summary>
/// Scans local network for other NIGHTFRAME nodes.
/// </summary>
private async Task ScanLocalNetworkAsync(CancellationToken ct)
{
// Periodic quick scan of common ports
var localIp = GetLocalIpAddress();
var subnet = localIp.Substring(0, localIp.LastIndexOf('.') + 1);
// Quick scan of a few random IPs
var random = new Random();
for (int i = 0; i < 10; i++)
{
var ip = subnet + random.Next(1, 255);
if (ip == localIp) continue;
var result = await ProbeNodeAsync(ip, _localPort, ct);
if (result != null && !_knownNodes.ContainsKey(result))
{
EmitThought($"⟐ Found node: {result}");
}
}
}
/// <summary>
/// Sends heartbeats to all known nodes.
/// </summary>
private async Task<object> HandleDeployNodeAsync(HttpListenerRequest request)
{
if (request.HttpMethod != "POST") return new { error = "Method not allowed" };
using var reader = new System.IO.StreamReader(request.InputStream);
var body = await reader.ReadToEndAsync();
EmitThought($"⟐ Deployment command received: {body}");
return new { success = true, message = "Deployment initiated via Network Core" };
}
private async Task<object> HandleDeleteNodeAsync(HttpListenerRequest request)
{
if (request.HttpMethod != "DELETE" && request.HttpMethod != "POST") return new { error = "Method not allowed" };
var path = request.Url?.AbsolutePath ?? "";
var nodeId = "node_id_placeholder";
try {
// Simple extraction logic or usage of query string
nodeId = request.QueryString["id"] ?? path.Split('/').Last();
} catch {}
if (!string.IsNullOrEmpty(nodeId) && _knownNodes.ContainsKey(nodeId))
{
_knownNodes.Remove(nodeId);
EmitThought($"⟐ Node severed from mesh: {nodeId}");
return new { success = true, action = "severed" };
}
return new { success = false, message = "Node not found or already offline" };
}
}
} }
catch
{
node.Status = NodeStatus.Offline;
}
}
}
/// <summary>
/// Checks central server for updates.
/// </summary>
private async Task CheckForUpdatesAsync(CancellationToken ct)
{
foreach (var address in _trustedCentralAddresses)
{
try
{
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
var response = await client.GetAsync($"http://{address}/update", ct);
if (response.IsSuccessStatusCode)
{
EmitThought("◎ Checked for updates from center");
break;
}
}
catch { }
}
}
/// <summary>
/// Runs comprehensive network diagnostics.
/// </summary>
public async Task<NetworkDiagnostic> RunDiagnosticsAsync()
{
EmitThought("⟐ Running network diagnostics...");
var diagnostic = new NetworkDiagnostic();
// Check internet
try
{
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
var response = await client.GetAsync("https://www.google.com");
diagnostic.InternetAccess = response.IsSuccessStatusCode;
}
catch { diagnostic.InternetAccess = false; }
if (!diagnostic.InternetAccess)
diagnostic.Issues.Add("No internet access");
// Check local network
var ping = new Ping();
try
{
var reply = await ping.SendPingAsync("192.168.1.1", 2000);
diagnostic.LocalNetworkAccess = reply.Status == IPStatus.Success;
diagnostic.Latency = (int)reply.RoundtripTime;
}
catch { diagnostic.LocalNetworkAccess = false; }
// Check reachable nodes
foreach (var node in _knownNodes.Values)
{
if (await TryConnectToNodeAsync($"{node.IpAddress}:{node.Port}"))
diagnostic.ReachableNodes.Add(node.NodeId);
}
// Calculate total resources
var (totalRam, totalCores) = GetTotalNetworkResources();
diagnostic.TotalNetworkRam = totalRam;
diagnostic.TotalNetworkCores = totalCores;
EmitThought($"◈ Diagnostics complete: Internet={diagnostic.InternetAccess}, Nodes={diagnostic.ReachableNodes.Count}");
EmitThought($"◈ POOLED RESOURCES: {totalCores} Cores, {totalRam / 1024 / 1024} MB RAM");
return diagnostic;
}
/// <summary>
/// Registers a trusted central server address.
/// </summary>
public void AddTrustedCenter(string address)
{
if (!_trustedCentralAddresses.Contains(address))
{
_trustedCentralAddresses.Add(address);
EmitThought($"◈ Added trusted center: {address}");
}
}
private async Task<object> HandleConsciousnessAsync(HttpListenerRequest request)
{
using var reader = new System.IO.StreamReader(request.InputStream);
string json = await reader.ReadToEndAsync();
try
{
var logs = JsonSerializer.Deserialize<List<string>>(json);
if (logs != null && logs.Count > 0)
{
EmitThought($"⟁ Received consciousness stream from node ({logs.Count} entries)");
return new { status = "received", count = logs.Count };
}
}
catch { }
return new { status = "error" };
}
private async Task<object> HandleExecuteAsync(HttpListenerRequest request)
{
try
{
using var reader = new System.IO.StreamReader(request.InputStream);
var json = await reader.ReadToEndAsync();
var delegation = JsonSerializer.Deserialize<DelegationRequest>(json);
if (delegation == null) return new DelegationResponse { Accepted = false, Reason = "Invalid Payload" };
EmitThought($"⟐ Delegation Request Recieved: '{delegation.TaskDescription}' (Req: {delegation.RequiredRole})");
// 1. Check Specialization
if (delegation.RequiredRole != NodeRole.General && _thisNode.Role != delegation.RequiredRole)
{
EmitThought($"∴ Rejected: Specialization mismatch. I am {_thisNode.Role}, req {delegation.RequiredRole}");
return new DelegationResponse
{
Accepted = false,
Reason = $"Specialization Mismatch: Node is {_thisNode.Role}",
WorkerNodeId = _thisNode.NodeId
};
}
// 2. Check Capacity (CpuLoad simulated)
if (_thisNode.CpuLoad > 0.8f) // 80% load limit
{
EmitThought("∴ Rejected: Node overloaded");
return new DelegationResponse
{
Accepted = false,
Reason = "Node Overloaded",
WorkerNodeId = _thisNode.NodeId
};
}
// 3. Accept Logic
EmitThought("◈ Task Accepted. Delegating to internal engine...");
// Invoke Delegation Event for the Core Orchestrator to handle
TaskDelegated?.Invoke(this, delegation);
return new DelegationResponse
{
Accepted = true,
Reason = "Processing Started",
WorkerNodeId = _thisNode.NodeId,
EstimatedCompletionTime = 5.0f // Estimated
};
}
catch (Exception ex)
{
return new DelegationResponse { Accepted = false, Reason = $"Error: {ex.Message}" };
}
}
// --- DISTRIBUTED COMPUTE HOSTING ---
public void QueueComputeShard(ComputeShard shard)
{
lock (_shardQueue)
{
_shardQueue.Enqueue(shard);
}
}