| | 1 | | using System.Net; |
| | 2 | | using System.Net.Sockets; |
| | 3 | | using Microsoft.Extensions.Logging; |
| | 4 | | using Microsoft.Extensions.Options; |
| | 5 | | using NLightning.Domain.Exceptions; |
| | 6 | | using NLightning.Domain.Node.ValueObjects; |
| | 7 | | using NLightning.Infrastructure.Node.ValueObjects; |
| | 8 | | using NLightning.Infrastructure.Protocol.Models; |
| | 9 | |
|
| | 10 | | namespace NLightning.Infrastructure.Transport.Services; |
| | 11 | |
|
| | 12 | | using Domain.Node.Options; |
| | 13 | | using Events; |
| | 14 | | using Interfaces; |
| | 15 | |
|
| | 16 | | public class TcpService : ITcpService |
| | 17 | | { |
| | 18 | | private readonly ILogger<TcpService> _logger; |
| | 19 | | private readonly NodeOptions _nodeOptions; |
| 0 | 20 | | private readonly List<TcpListener> _listeners = []; |
| | 21 | |
|
| | 22 | | private CancellationTokenSource? _cts; |
| | 23 | | private Task? _listeningTask; |
| | 24 | |
|
| | 25 | | /// <inheritdoc /> |
| | 26 | | public event EventHandler<NewPeerConnectedEventArgs>? OnNewPeerConnected; |
| | 27 | |
|
| 0 | 28 | | public TcpService(ILogger<TcpService> logger, IOptions<NodeOptions> nodeOptions) |
| | 29 | | { |
| 0 | 30 | | _logger = logger; |
| 0 | 31 | | _nodeOptions = nodeOptions.Value; |
| 0 | 32 | | } |
| | 33 | |
|
| | 34 | | /// <inheritdoc /> |
| | 35 | | public Task StartListeningAsync(CancellationToken cancellationToken) |
| | 36 | | { |
| 0 | 37 | | _cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); |
| | 38 | |
|
| 0 | 39 | | foreach (var address in _nodeOptions.ListenAddresses) |
| | 40 | | { |
| 0 | 41 | | var parts = address.Split(':'); |
| 0 | 42 | | if (parts.Length != 2 || !int.TryParse(parts[1], out var port)) |
| | 43 | | { |
| 0 | 44 | | _logger.LogWarning("Invalid listen address: {Address}", address); |
| 0 | 45 | | continue; |
| | 46 | | } |
| | 47 | |
|
| 0 | 48 | | var ipAddress = IPAddress.Parse(parts[0]); |
| 0 | 49 | | var listener = new TcpListener(ipAddress, port); |
| 0 | 50 | | listener.Start(); |
| 0 | 51 | | _listeners.Add(listener); |
| | 52 | |
|
| 0 | 53 | | _logger.LogInformation("Listening for connections on {Address}:{Port}", ipAddress, port); |
| | 54 | | } |
| | 55 | |
|
| 0 | 56 | | _listeningTask = ListenForConnectionsAsync(_cts.Token); |
| | 57 | |
|
| 0 | 58 | | return Task.CompletedTask; |
| | 59 | | } |
| | 60 | |
|
| | 61 | | /// <inheritdoc /> |
| | 62 | | public async Task StopListeningAsync() |
| | 63 | | { |
| 0 | 64 | | if (_cts is null) |
| 0 | 65 | | throw new InvalidOperationException("Service is not running"); |
| | 66 | |
|
| 0 | 67 | | await _cts.CancelAsync(); |
| | 68 | |
|
| 0 | 69 | | foreach (var listener in _listeners) |
| | 70 | | { |
| | 71 | | try |
| | 72 | | { |
| 0 | 73 | | listener.Stop(); |
| 0 | 74 | | } |
| 0 | 75 | | catch (Exception ex) |
| | 76 | | { |
| 0 | 77 | | _logger.LogError(ex, "Error stopping listener"); |
| 0 | 78 | | } |
| | 79 | | } |
| | 80 | |
|
| 0 | 81 | | _listeners.Clear(); |
| | 82 | |
|
| 0 | 83 | | if (_listeningTask is not null) |
| | 84 | | { |
| | 85 | | try |
| | 86 | | { |
| 0 | 87 | | await _listeningTask; |
| 0 | 88 | | } |
| 0 | 89 | | catch (OperationCanceledException) |
| | 90 | | { |
| | 91 | | // Expected during cancellation |
| 0 | 92 | | } |
| | 93 | | } |
| 0 | 94 | | } |
| | 95 | |
|
| | 96 | | /// <inheritdoc /> |
| | 97 | | /// <exception cref="ConnectionException">Thrown when the connection to the peer fails.</exception> |
| | 98 | | public async Task<ConnectedPeer> ConnectToPeerAsync(PeerAddressInfo peerAddressInfo) |
| | 99 | | { |
| 0 | 100 | | var peerAddress = new PeerAddress(peerAddressInfo.Address); |
| | 101 | |
|
| 0 | 102 | | var tcpClient = new TcpClient(); |
| | 103 | | try |
| | 104 | | { |
| 0 | 105 | | await tcpClient.ConnectAsync(peerAddress.Host, peerAddress.Port, |
| 0 | 106 | | new CancellationTokenSource(_nodeOptions.NetworkTimeout).Token); |
| | 107 | |
|
| 0 | 108 | | return new ConnectedPeer(peerAddress.PubKey, peerAddress.Host.ToString(), (uint)peerAddress.Port, |
| 0 | 109 | | tcpClient); |
| | 110 | | } |
| 0 | 111 | | catch (OperationCanceledException) |
| | 112 | | { |
| 0 | 113 | | throw new ConnectionException($"Timeout connecting to peer {peerAddress.Host}:{peerAddress.Port}"); |
| | 114 | | } |
| 0 | 115 | | catch (Exception e) |
| | 116 | | { |
| 0 | 117 | | throw new ConnectionException($"Failed to connect to peer {peerAddress.Host}:{peerAddress.Port}", e); |
| | 118 | | } |
| 0 | 119 | | } |
| | 120 | |
|
| | 121 | | private async Task ListenForConnectionsAsync(CancellationToken cancellationToken) |
| | 122 | | { |
| | 123 | | try |
| | 124 | | { |
| 0 | 125 | | while (!cancellationToken.IsCancellationRequested) |
| | 126 | | { |
| 0 | 127 | | foreach (var listener in _listeners) |
| | 128 | | { |
| 0 | 129 | | if (!listener.Pending()) |
| | 130 | | continue; |
| | 131 | |
|
| 0 | 132 | | var tcpClient = await listener.AcceptTcpClientAsync(cancellationToken); |
| 0 | 133 | | _ = Task.Run(() => |
| 0 | 134 | | { |
| 0 | 135 | | try |
| 0 | 136 | | { |
| 0 | 137 | | _logger.LogInformation("New peer connection from {RemoteEndPoint}", |
| 0 | 138 | | tcpClient.Client.RemoteEndPoint); |
| 0 | 139 | |
|
| 0 | 140 | | if (tcpClient.Client.RemoteEndPoint is not IPEndPoint ipEndPoint) |
| 0 | 141 | | { |
| 0 | 142 | | _logger.LogError("Failed to get remote endpoint for {RemoteEndPoint}", |
| 0 | 143 | | tcpClient.Client.RemoteEndPoint); |
| 0 | 144 | | return; |
| 0 | 145 | | } |
| 0 | 146 | |
|
| 0 | 147 | | // Raise the event for a new peer connection |
| 0 | 148 | | OnNewPeerConnected?.Invoke( |
| 0 | 149 | | this, |
| 0 | 150 | | new NewPeerConnectedEventArgs(ipEndPoint.Address.ToString(), (uint)ipEndPoint.Port, |
| 0 | 151 | | tcpClient)); |
| 0 | 152 | | } |
| 0 | 153 | | catch (Exception e) |
| 0 | 154 | | { |
| 0 | 155 | | _logger.LogError(e, "Error accepting peer connection for {RemoteEndPoint}", |
| 0 | 156 | | tcpClient.Client.RemoteEndPoint); |
| 0 | 157 | | } |
| 0 | 158 | | }, cancellationToken); |
| 0 | 159 | | } |
| | 160 | |
|
| 0 | 161 | | await Task.Delay(100, cancellationToken); // Avoid busy-waiting |
| | 162 | | } |
| 0 | 163 | | } |
| 0 | 164 | | catch (OperationCanceledException) |
| | 165 | | { |
| 0 | 166 | | _logger.LogInformation("Stopping listener service"); |
| 0 | 167 | | } |
| 0 | 168 | | catch (Exception e) |
| | 169 | | { |
| 0 | 170 | | _logger.LogError(e, "Unhandled exception in listener service"); |
| 0 | 171 | | } |
| 0 | 172 | | } |
| | 173 | | } |