diff --git a/src/Neo.Core/Net/LocalNode.cs b/src/Neo.Core/Net/LocalNode.cs deleted file mode 100644 index 69d97a1..0000000 --- a/src/Neo.Core/Net/LocalNode.cs +++ /dev/null @@ -1,304 +0,0 @@ -// BSD 2-Clause License -// -// Copyright (c) 2026, Rapid Loop -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this -// list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES - -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Sockets; -using System.Threading; -using System.Threading.Tasks; - -namespace Neo.Core.Net -{ - /// - /// Manages the local P2P node, including listening for incoming connections - /// and connecting to seed nodes using TCP sockets. - /// - public sealed class LocalNode : IAsyncDisposable - { - private readonly ProtocolSettings _settings; - private readonly ILogger? _logger; - private readonly ConcurrentDictionary _peers = new(); - private TcpListener? _listener; - private CancellationTokenSource? _cts; - private bool _disposed; - - /// - /// Gets the currently connected peers. - /// - public IReadOnlyCollection ConnectedPeers => _peers.Values.ToList().AsReadOnly(); - - /// - /// Gets the number of currently connected peers. - /// - public int PeerCount => _peers.Count; - - /// - /// Occurs when a new peer connects (inbound or outbound). - /// - public event Action? PeerConnected; - - /// - /// Occurs when a peer disconnects. - /// - public event Action? PeerDisconnected; - - /// - /// Occurs when a message is received from any peer. - /// - public event Action? MessageReceived; - - /// - /// Initializes a new instance of the class. - /// - /// The protocol settings containing network magic and seed list. - /// Optional logger instance. - public LocalNode(ProtocolSettings settings, ILogger? logger = null) - { - ArgumentNullException.ThrowIfNull(settings); - _settings = settings; - _logger = logger; - } - - /// - /// Starts the local node: begins listening for inbound connections and connects to seed nodes. - /// - /// The local TCP port to listen on. Use 0 for ephemeral port. - /// Cancellation token. - public async Task StartAsync(int listenPort = 10333, CancellationToken cancellationToken = default) - { - ObjectDisposedException.ThrowIf(_disposed, this); - if (_cts is not null) - throw new InvalidOperationException("LocalNode is already started."); - - _cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - - // Start listener - _listener = new TcpListener(IPAddress.Any, listenPort); - _listener.Start(); - _logger?.LogInformation("P2P LocalNode listening on port {Port}", ((IPEndPoint)_listener.LocalEndpoint).Port); - - // Accept loop - _ = AcceptLoopAsync(_cts.Token); - - // Connect to seeds - await ConnectToSeedsAsync(_cts.Token).ConfigureAwait(false); - } - - private async Task AcceptLoopAsync(CancellationToken cancellationToken) - { - try - { - while (!cancellationToken.IsCancellationRequested && _listener is not null) - { - var socket = await _listener.AcceptSocketAsync(cancellationToken).ConfigureAwait(false); - _ = HandleInboundAsync(socket); - } - } - catch (OperationCanceledException) - { - // Expected - } - catch (Exception ex) - { - _logger?.LogError(ex, "Error in accept loop"); - } - } - - private async Task HandleInboundAsync(Socket socket) - { - try - { - var peer = new Peer(socket, _logger); - if (_peers.TryAdd(peer.RemoteEndPoint, peer)) - { - peer.MessageReceived += OnPeerMessageReceived; - peer.Disconnected += OnPeerDisconnected; - peer.Start(); - PeerConnected?.Invoke(peer); - _logger?.LogInformation("Inbound peer connected: {Remote}", peer.RemoteEndPoint); - - // Send Version handshake - await SendVersionAsync(peer).ConfigureAwait(false); - } - else - { - await peer.DisposeAsync().ConfigureAwait(false); - } - } - catch (Exception ex) - { - _logger?.LogWarning(ex, "Failed to handle inbound connection"); - try { socket.Dispose(); } catch { /* ignore */ } - } - } - - private async Task ConnectToSeedsAsync(CancellationToken cancellationToken) - { - var seeds = _settings.SeedList; - if (seeds.Length == 0) - { - _logger?.LogWarning("No seed nodes configured in ProtocolSettings."); - return; - } - - var tasks = seeds.Select(seed => ConnectToPeerAsync(seed, cancellationToken)); - await Task.WhenAll(tasks).ConfigureAwait(false); - } - - /// - /// Connects to a remote peer at the specified endpoint. - /// - /// The remote endpoint. - /// Cancellation token. - /// The connected peer, or null if connection failed. - public async Task ConnectToPeerAsync(IPEndPoint endPoint, CancellationToken cancellationToken = default) - { - ObjectDisposedException.ThrowIf(_disposed, this); - ArgumentNullException.ThrowIfNull(endPoint); - - if (_peers.ContainsKey(endPoint)) - { - _logger?.LogDebug("Already connected to {Remote}", endPoint); - return _peers[endPoint]; - } - - try - { - var socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) - { - NoDelay = true - }; - - using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - timeoutCts.CancelAfter(TimeSpan.FromSeconds(10)); - - await socket.ConnectAsync(endPoint, timeoutCts.Token).ConfigureAwait(false); - - var peer = new Peer(socket, _logger); - if (_peers.TryAdd(endPoint, peer)) - { - peer.MessageReceived += OnPeerMessageReceived; - peer.Disconnected += OnPeerDisconnected; - peer.Start(); - PeerConnected?.Invoke(peer); - _logger?.LogInformation("Outbound peer connected: {Remote}", endPoint); - - await SendVersionAsync(peer).ConfigureAwait(false); - return peer; - } - - await peer.DisposeAsync().ConfigureAwait(false); - return null; - } - catch (Exception ex) - { - _logger?.LogWarning(ex, "Failed to connect to seed {Remote}", endPoint); - return null; - } - } - - private async Task SendVersionAsync(Peer peer) - { - // Minimal Version message (payload can be extended later) - var versionPayload = new byte[0]; // Placeholder for full version payload - var message = new Message(_settings.Network, MessageCommandType.Version, versionPayload); - await peer.SendAsync(message).ConfigureAwait(false); - } - - private void OnPeerMessageReceived(Peer peer, Message message) - { - // Basic handshake handling - if (message.Command == MessageCommandType.Version) - { - // Respond with VersionAck - _ = peer.SendAsync(new Message(_settings.Network, MessageCommandType.VersionAck)); - } - else if (message.Command == MessageCommandType.Ping) - { - _ = peer.SendAsync(new Message(_settings.Network, MessageCommandType.Pong)); - } - - MessageReceived?.Invoke(peer, message); - } - - private void OnPeerDisconnected(Peer peer) - { - if (_peers.TryRemove(peer.RemoteEndPoint, out _)) - { - peer.MessageReceived -= OnPeerMessageReceived; - peer.Disconnected -= OnPeerDisconnected; - PeerDisconnected?.Invoke(peer); - } - } - - /// - /// Broadcasts a message to all currently connected peers. - /// - /// The message to broadcast. - /// Cancellation token. - public async Task BroadcastAsync(Message message, CancellationToken cancellationToken = default) - { - ObjectDisposedException.ThrowIf(_disposed, this); - ArgumentNullException.ThrowIfNull(message); - - var tasks = _peers.Values.Select(p => p.SendAsync(message, cancellationToken)); - await Task.WhenAll(tasks).ConfigureAwait(false); - } - - /// - /// Stops the local node and disconnects all peers. - /// - public async Task StopAsync() - { - if (_disposed || _cts is null) return; - - _cts.Cancel(); - - if (_listener is not null) - { - try { _listener.Stop(); } catch { /* ignore */ } - _listener = null; - } - - var disconnectTasks = _peers.Values.Select(p => p.DisconnectAsync()); - await Task.WhenAll(disconnectTasks).ConfigureAwait(false); - _peers.Clear(); - - _cts.Dispose(); - _cts = null; - - _logger?.LogInformation("LocalNode stopped."); - } - - /// - public async ValueTask DisposeAsync() - { - if (_disposed) return; - _disposed = true; - await StopAsync().ConfigureAwait(false); - } - } -} diff --git a/src/Neo.Core/Net/Message.cs b/src/Neo.Core/Net/Message.cs deleted file mode 100644 index 29fa63e..0000000 --- a/src/Neo.Core/Net/Message.cs +++ /dev/null @@ -1,122 +0,0 @@ -// BSD 2-Clause License -// -// Copyright (c) 2026, Rapid Loop -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this -// list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES - -using Neo.Core.Extensions; -using Neo.Core.Serialization; -using System; -using System.IO; -using System.Security.Cryptography; - -namespace Neo.Core.Net -{ - /// - /// Represents a P2P network message exchanged between peers. - /// - public sealed class Message : INeoSerializable - { - /// - /// The size of the message header in bytes (Magic + Command + Length + Checksum). - /// - public const int HeaderSize = 13; - - /// - /// Maximum allowed payload size to prevent resource exhaustion. - /// - public const int MaxPayloadSize = 0x02000000; // 32 MB - - /// - /// Network magic number identifying the network. - /// - public uint Magic { get; set; } - - /// - /// The command type of this message. - /// - public MessageCommandType Command { get; set; } - - /// - /// The payload data of the message. - /// - public byte[] Payload { get; set; } = []; - - /// - public int Size => HeaderSize + Payload.Length; - - /// - /// Initializes a new instance of the class. - /// - public Message() { } - - /// - /// Initializes a new instance of the class with the specified values. - /// - /// The network magic number. - /// The message command. - /// The optional payload. - public Message(uint magic, MessageCommandType command, byte[]? payload = null) - { - Magic = magic; - Command = command; - Payload = payload ?? []; - } - - /// - public void Serialize(Stream writer) - { - writer.Write(Magic); - writer.Write((byte)Command); - writer.Write((uint)Payload.Length); - writer.Write(ComputeChecksum(Payload)); - if (Payload.Length > 0) - writer.Write(Payload.AsSpan()); - } - - /// - public void Deserialize(Stream reader) - { - Magic = reader.Read(); - Command = (MessageCommandType)reader.ReadByte(); - var length = reader.Read(); - if (length > MaxPayloadSize) - throw new FormatException($"Payload length {length} exceeds maximum allowed size of {MaxPayloadSize}."); - - var checksum = reader.Read(); - Payload = length > 0 ? new byte[length] : []; - if (length > 0) - { - reader.ReadExactly(Payload); - if (ComputeChecksum(Payload) != checksum) - throw new FormatException("Message checksum mismatch."); - } - } - - /// - /// Computes a simple checksum for the payload using SHA-256 truncated to 4 bytes. - /// - public static uint ComputeChecksum(ReadOnlySpan data) - { - Span hash = stackalloc byte[32]; - SHA256.HashData(data, hash); - return BitConverter.ToUInt32(hash); - } - } -} diff --git a/src/Neo.Core/Net/Peer.cs b/src/Neo.Core/Net/Peer.cs deleted file mode 100644 index 657b8b8..0000000 --- a/src/Neo.Core/Net/Peer.cs +++ /dev/null @@ -1,233 +0,0 @@ -// BSD 2-Clause License -// -// Copyright (c) 2026, Rapid Loop -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this -// list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES - -using Microsoft.Extensions.Logging; -using Neo.Core.Extensions; -using System; -using System.IO; -using System.Net; -using System.Net.Sockets; -using System.Threading; -using System.Threading.Tasks; - -namespace Neo.Core.Net -{ - /// - /// Represents a connected remote peer in the P2P network using TCP sockets. - /// - public sealed class Peer : IAsyncDisposable - { - private readonly Socket _socket; - private readonly NetworkStream _stream; - private readonly ILogger? _logger; - private readonly CancellationTokenSource _cts = new(); - private readonly SemaphoreSlim _sendLock = new(1, 1); - private bool _disposed; - - /// - /// Gets the remote endpoint of this peer. - /// - public IPEndPoint RemoteEndPoint { get; } - - /// - /// Gets a value indicating whether the peer is currently connected. - /// - public bool IsConnected => _socket.Connected && !_disposed; - - /// - /// Occurs when a message is received from the peer. - /// - public event Action? MessageReceived; - - /// - /// Occurs when the peer is disconnected. - /// - public event Action? Disconnected; - - /// - /// Initializes a new instance of the class from an accepted socket. - /// - /// The connected socket. - /// Optional logger. - public Peer(Socket socket, ILogger? logger = null) - { - ArgumentNullException.ThrowIfNull(socket); - if (!socket.Connected) - throw new ArgumentException("Socket must be connected.", nameof(socket)); - - _socket = socket; - _socket.NoDelay = true; - _stream = new NetworkStream(socket, ownsSocket: false); - _logger = logger; - RemoteEndPoint = (IPEndPoint)_socket.RemoteEndPoint!; - } - - /// - /// Starts the receive loop for this peer. - /// - public void Start() => _ = ReceiveLoopAsync(_cts.Token); - - /// - /// Sends a message to the remote peer asynchronously. - /// - /// The message to send. - /// Cancellation token. - public async Task SendAsync(Message message, CancellationToken cancellationToken = default) - { - ObjectDisposedException.ThrowIf(_disposed, this); - ArgumentNullException.ThrowIfNull(message); - - await _sendLock.WaitAsync(cancellationToken).ConfigureAwait(false); - try - { - using var ms = new MemoryStream(); - message.Serialize(ms); - var data = ms.ToArray(); - await _stream.WriteAsync(data, cancellationToken).ConfigureAwait(false); - await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); - _logger?.LogDebug("Sent {Command} to {Remote} ({Length} bytes)", message.Command, RemoteEndPoint, data.Length); - } - finally - { - _sendLock.Release(); - } - } - - private async Task ReceiveLoopAsync(CancellationToken cancellationToken) - { - var headerBuffer = new byte[Message.HeaderSize]; - try - { - while (!cancellationToken.IsCancellationRequested && IsConnected) - { - // Read header - await ReadExactlyAsync(_stream, headerBuffer, cancellationToken).ConfigureAwait(false); - - using var headerStream = new MemoryStream(headerBuffer); - var magic = headerStream.Read(); - var command = (MessageCommandType)headerStream.ReadByte(); - var length = headerStream.Read(); - var checksum = headerStream.Read(); - - if (length > Message.MaxPayloadSize) - { - _logger?.LogWarning("Peer {Remote} sent oversized payload ({Length}). Disconnecting.", RemoteEndPoint, length); - break; - } - - byte[] payload = []; - if (length > 0) - { - payload = new byte[length]; - await ReadExactlyAsync(_stream, payload, cancellationToken).ConfigureAwait(false); - - if (Message.ComputeChecksum(payload) != checksum) - { - _logger?.LogWarning("Peer {Remote} sent message with invalid checksum. Disconnecting.", RemoteEndPoint); - break; - } - } - - var message = new Message - { - Magic = magic, - Command = command, - Payload = payload - }; - - _logger?.LogDebug("Received {Command} from {Remote} ({Length} bytes)", command, RemoteEndPoint, Message.HeaderSize + length); - MessageReceived?.Invoke(this, message); - } - } - catch (OperationCanceledException) - { - // Expected on shutdown - } - catch (IOException ex) - { - _logger?.LogInformation(ex, "IO error with peer {Remote}", RemoteEndPoint); - } - catch (Exception ex) - { - _logger?.LogError(ex, "Unexpected error receiving from peer {Remote}", RemoteEndPoint); - } - finally - { - await DisconnectAsync().ConfigureAwait(false); - } - } - - private static async Task ReadExactlyAsync(Stream stream, byte[] buffer, CancellationToken cancellationToken) - { - var offset = 0; - while (offset < buffer.Length) - { - var read = await stream.ReadAsync(buffer.AsMemory(offset), cancellationToken).ConfigureAwait(false); - if (read == 0) - throw new EndOfStreamException("Remote peer closed the connection."); - offset += read; - } - } - - /// - /// Disconnects the peer and releases resources. - /// - public async Task DisconnectAsync() - { - if (_disposed) return; - _disposed = true; - - try - { - _cts.Cancel(); - if (_socket.Connected) - { - _socket.Shutdown(SocketShutdown.Both); - } - } - catch - { - // Ignore shutdown errors - } - - try - { - _stream.Dispose(); - _socket.Dispose(); - } - catch - { - // Ignore - } - - _cts.Dispose(); - _sendLock.Dispose(); - - Disconnected?.Invoke(this); - _logger?.LogInformation("Disconnected from peer {Remote}", RemoteEndPoint); - await Task.CompletedTask.ConfigureAwait(false); - } - - /// - public async ValueTask DisposeAsync() => await DisconnectAsync().ConfigureAwait(false); - } -}