| | 1 | | using System.Net.Sockets; |
| | 2 | | using Microsoft.Extensions.Logging; |
| | 3 | |
|
| | 4 | | namespace NLightning.Infrastructure.Transport.Services; |
| | 5 | |
|
| | 6 | | using Domain.Exceptions; |
| | 7 | | using Domain.Protocol.Messages.Interfaces; |
| | 8 | | using Domain.Serialization.Messages; |
| | 9 | | using Domain.Transport; |
| | 10 | | using Exceptions; |
| | 11 | | using Interfaces; |
| | 12 | | using Protocol.Constants; |
| | 13 | |
|
| | 14 | | internal sealed class TransportService : ITransportService |
| | 15 | | { |
| 12 | 16 | | private readonly CancellationTokenSource _cts = new(); |
| | 17 | | private readonly ILogger _logger; |
| | 18 | | private readonly IMessageSerializer _messageSerializer; |
| | 19 | | private readonly TimeSpan _networkTimeout; |
| 12 | 20 | | private readonly SemaphoreSlim _networkWriteSemaphore = new(1, 1); |
| | 21 | | private readonly TcpClient _tcpClient; |
| 12 | 22 | | private readonly TaskCompletionSource<bool> _tcs = new(); |
| | 23 | |
|
| | 24 | | private IHandshakeService? _handshakeService; |
| | 25 | | private ITransport? _transport; |
| | 26 | | private bool _disposed; |
| | 27 | |
|
| | 28 | | // event that will be called when a message is received |
| | 29 | | public event EventHandler<MemoryStream>? MessageReceived; |
| | 30 | | public event EventHandler<Exception>? ExceptionRaised; |
| | 31 | |
|
| 0 | 32 | | public bool IsInitiator { get; } |
| 0 | 33 | | public bool IsConnected => _tcpClient.Connected; |
| 4 | 34 | | public NBitcoin.PubKey? RemoteStaticPublicKey { get; private set; } |
| | 35 | |
|
| | 36 | | public TransportService(ILogger logger, IMessageSerializer messageSerializer, TimeSpan networkTimeout, |
| | 37 | | bool isInitiator, ReadOnlySpan<byte> s, ReadOnlySpan<byte> rs, TcpClient tcpClient) |
| 0 | 38 | | : this(logger, messageSerializer, networkTimeout, new HandshakeService(isInitiator, s, rs), tcpClient) |
| | 39 | | { |
| 0 | 40 | | _messageSerializer = messageSerializer; |
| 0 | 41 | | _networkTimeout = networkTimeout; |
| 0 | 42 | | } |
| | 43 | |
|
| 12 | 44 | | internal TransportService(ILogger logger, IMessageSerializer messageSerializer, TimeSpan networkTimeout, IHandshakeS |
| 12 | 45 | | TcpClient tcpClient) |
| | 46 | | { |
| 12 | 47 | | _handshakeService = handshakeService; |
| 12 | 48 | | _logger = logger; |
| 12 | 49 | | _messageSerializer = messageSerializer; |
| 12 | 50 | | _networkTimeout = networkTimeout; |
| 12 | 51 | | _tcpClient = tcpClient; |
| | 52 | |
|
| 12 | 53 | | IsInitiator = handshakeService.IsInitiator; |
| 12 | 54 | | } |
| | 55 | |
|
| | 56 | | public async Task InitializeAsync() |
| | 57 | | { |
| 12 | 58 | | if (_handshakeService == null) |
| | 59 | | { |
| 0 | 60 | | throw new NullReferenceException(nameof(_handshakeService)); |
| | 61 | | } |
| | 62 | |
|
| 12 | 63 | | if (!_tcpClient.Connected) |
| | 64 | | { |
| 4 | 65 | | throw new InvalidOperationException("TcpClient is not connected"); |
| | 66 | | } |
| | 67 | |
|
| 8 | 68 | | var writeBuffer = new byte[50]; |
| 8 | 69 | | var stream = _tcpClient.GetStream(); |
| | 70 | |
|
| 8 | 71 | | CancellationTokenSource networkTimeoutCancellationTokenSource = new(); |
| | 72 | |
|
| 8 | 73 | | if (_handshakeService.IsInitiator) |
| | 74 | | { |
| | 75 | | try |
| | 76 | | { |
| 8 | 77 | | _logger.LogTrace("We're initiator, writing Act One"); |
| | 78 | |
|
| | 79 | | // Write Act One |
| 8 | 80 | | var len = _handshakeService.PerformStep(ProtocolConstants.EMPTY_MESSAGE, writeBuffer, out _); |
| 8 | 81 | | await stream.WriteAsync(writeBuffer.AsMemory()[..len], networkTimeoutCancellationTokenSource.Token); |
| 8 | 82 | | await stream.FlushAsync(networkTimeoutCancellationTokenSource.Token); |
| | 83 | |
|
| | 84 | | // Read exactly 50 bytes |
| 8 | 85 | | _logger.LogTrace("Reading Act Two"); |
| 8 | 86 | | networkTimeoutCancellationTokenSource = new CancellationTokenSource(_networkTimeout); |
| 8 | 87 | | var readBuffer = new byte[50]; |
| 8 | 88 | | await stream.ReadExactlyAsync(readBuffer, networkTimeoutCancellationTokenSource.Token); |
| 4 | 89 | | networkTimeoutCancellationTokenSource.Dispose(); |
| | 90 | |
|
| | 91 | | // Read Act Two and Write Act Three |
| 4 | 92 | | _logger.LogTrace("Writing Act Three"); |
| 4 | 93 | | writeBuffer = new byte[66]; |
| 4 | 94 | | len = _handshakeService.PerformStep(readBuffer, writeBuffer, out _transport); |
| 4 | 95 | | await stream.WriteAsync(writeBuffer.AsMemory()[..len], CancellationToken.None); |
| 4 | 96 | | await stream.FlushAsync(CancellationToken.None); |
| 4 | 97 | | } |
| 4 | 98 | | catch (Exception e) |
| | 99 | | { |
| 4 | 100 | | throw new ConnectionTimeoutException("Timeout while reading Handhsake's Act 2", e); |
| | 101 | | } |
| | 102 | | } |
| | 103 | | else |
| | 104 | | { |
| 0 | 105 | | var act = 1; |
| | 106 | |
|
| | 107 | | try |
| | 108 | | { |
| 0 | 109 | | _logger.LogTrace("We're NOT initiator, reading Act One"); |
| | 110 | |
|
| | 111 | | // Read exactly 50 bytes |
| 0 | 112 | | networkTimeoutCancellationTokenSource = new CancellationTokenSource(_networkTimeout); |
| 0 | 113 | | var readBuffer = new byte[50]; |
| 0 | 114 | | await stream.ReadExactlyAsync(readBuffer, networkTimeoutCancellationTokenSource.Token); |
| | 115 | |
|
| | 116 | | // Read Act One and Write Act Two |
| 0 | 117 | | _logger.LogTrace("Writing Act Two"); |
| 0 | 118 | | var len = _handshakeService.PerformStep(readBuffer, writeBuffer, out _); |
| 0 | 119 | | await stream.WriteAsync(writeBuffer.AsMemory()[..len], CancellationToken.None); |
| 0 | 120 | | await stream.FlushAsync(CancellationToken.None); |
| | 121 | |
|
| | 122 | | // Read exactly 66 bytes |
| 0 | 123 | | _logger.LogTrace("Reading Act Three"); |
| 0 | 124 | | act = 3; |
| 0 | 125 | | networkTimeoutCancellationTokenSource = new CancellationTokenSource(_networkTimeout); |
| 0 | 126 | | readBuffer = new byte[66]; |
| 0 | 127 | | await stream.ReadExactlyAsync(readBuffer, networkTimeoutCancellationTokenSource.Token); |
| 0 | 128 | | networkTimeoutCancellationTokenSource.Dispose(); |
| | 129 | |
|
| | 130 | | // Read Act Three |
| 0 | 131 | | _ = _handshakeService.PerformStep(readBuffer, writeBuffer, out _transport); |
| 0 | 132 | | } |
| 0 | 133 | | catch (Exception e) |
| | 134 | | { |
| 0 | 135 | | throw new ConnectionTimeoutException($"Timeout while reading Handhsake's Act {act}", e); |
| | 136 | | } |
| | 137 | | } |
| | 138 | |
|
| | 139 | | // Handshake completed |
| 4 | 140 | | if (_transport is null) |
| | 141 | | { |
| 0 | 142 | | throw new InvalidOperationException("Handshake not completed"); |
| | 143 | | } |
| 4 | 144 | | RemoteStaticPublicKey = _handshakeService.RemoteStaticPublicKey |
| 4 | 145 | | ?? throw new InvalidOperationException("RemoteStaticPublicKey is null"); |
| | 146 | |
|
| | 147 | | // Listen to messages and raise event |
| 4 | 148 | | _logger.LogTrace("Handshake completed, listening to messages"); |
| 4 | 149 | | _ = Task.Run(ReadResponseAsync, CancellationToken.None).ContinueWith(task => |
| 4 | 150 | | { |
| 2 | 151 | | if (task.Exception?.InnerExceptions.Count > 0) |
| 4 | 152 | | { |
| 2 | 153 | | ExceptionRaised?.Invoke(this, task.Exception.InnerExceptions[0]); |
| 4 | 154 | | } |
| 4 | 155 | | }, TaskContinuationOptions.OnlyOnFaulted); |
| | 156 | |
|
| | 157 | | // Dispose of the handshake service |
| 4 | 158 | | _handshakeService.Dispose(); |
| 4 | 159 | | _handshakeService = null; |
| 4 | 160 | | } |
| | 161 | |
|
| | 162 | | public async Task WriteMessageAsync(IMessage message, CancellationToken cancellationToken = default) |
| | 163 | | { |
| 0 | 164 | | if (_tcpClient is null || !_tcpClient.Connected) |
| | 165 | | { |
| 0 | 166 | | throw new InvalidOperationException("TcpClient is not connected"); |
| | 167 | | } |
| | 168 | |
|
| 0 | 169 | | if (_transport is null) |
| | 170 | | { |
| 0 | 171 | | throw new InvalidOperationException("Handshake not completed"); |
| | 172 | | } |
| | 173 | |
|
| | 174 | | // Serialize message |
| 0 | 175 | | using var messageStream = new MemoryStream(); |
| 0 | 176 | | await _messageSerializer.SerializeAsync(message, messageStream); |
| | 177 | |
|
| | 178 | | // Encrypt message |
| 0 | 179 | | var buffer = new byte[ProtocolConstants.MAX_MESSAGE_LENGTH]; |
| 0 | 180 | | var size = _transport.WriteMessage(messageStream.ToArray(), buffer); |
| | 181 | |
|
| | 182 | | // Write message to stream |
| 0 | 183 | | await _networkWriteSemaphore.WaitAsync(cancellationToken); |
| | 184 | | try |
| | 185 | | { |
| 0 | 186 | | var stream = _tcpClient.GetStream(); |
| 0 | 187 | | await stream.WriteAsync(buffer.AsMemory()[..size], cancellationToken); |
| 0 | 188 | | await stream.FlushAsync(cancellationToken); |
| 0 | 189 | | } |
| | 190 | | finally |
| | 191 | | { |
| 0 | 192 | | _networkWriteSemaphore.Release(); |
| | 193 | | } |
| 0 | 194 | | } |
| | 195 | |
|
| | 196 | | private async Task ReadResponseAsync() |
| | 197 | | { |
| 4 | 198 | | while (!_cts.IsCancellationRequested) |
| | 199 | | { |
| | 200 | | try |
| | 201 | | { |
| 4 | 202 | | if (_transport == null) |
| | 203 | | { |
| 0 | 204 | | throw new InvalidOperationException("Handshake not completed"); |
| | 205 | | } |
| | 206 | |
|
| 4 | 207 | | if (_tcpClient is null || !_tcpClient.Connected) |
| | 208 | | { |
| 0 | 209 | | throw new InvalidOperationException("TcpClient is not connected"); |
| | 210 | | } |
| | 211 | |
|
| | 212 | | // Read response |
| 4 | 213 | | var stream = _tcpClient.GetStream(); |
| 4 | 214 | | var memory = new byte[ProtocolConstants.MAX_MESSAGE_LENGTH].AsMemory(); |
| 4 | 215 | | var lenRead = await stream.ReadAsync(memory[..ProtocolConstants.MESSAGE_HEADER_SIZE], _cts.Token); |
| 0 | 216 | | if (lenRead != 18) |
| | 217 | | { |
| 0 | 218 | | throw new ConnectionException("Peer sent wrong length"); |
| | 219 | | } |
| | 220 | |
|
| 0 | 221 | | var messageLen = _transport.ReadMessageLength(memory.Span[..ProtocolConstants.MESSAGE_HEADER_SIZE]); |
| 0 | 222 | | if (messageLen > ProtocolConstants.MAX_MESSAGE_LENGTH) |
| | 223 | | { |
| 0 | 224 | | throw new ConnectionException("Peer sent message too long"); |
| | 225 | | } |
| | 226 | |
|
| 0 | 227 | | lenRead = await stream.ReadAsync(memory[..messageLen], _cts.Token); |
| 0 | 228 | | if (lenRead != messageLen) |
| | 229 | | { |
| 0 | 230 | | throw new ConnectionException("Peer sent wrong body length"); |
| | 231 | | } |
| | 232 | |
|
| 0 | 233 | | messageLen = _transport.ReadMessagePayload(memory.Span[..messageLen], memory.Span); |
| | 234 | |
|
| | 235 | | // Raise event |
| 0 | 236 | | var messageStream = new MemoryStream(memory.Span[..messageLen].ToArray()); |
| 0 | 237 | | MessageReceived?.Invoke(this, messageStream); |
| 0 | 238 | | } |
| 0 | 239 | | catch (OperationCanceledException) |
| | 240 | | { |
| | 241 | | // Ignore cancellation |
| 0 | 242 | | } |
| 0 | 243 | | catch (ConnectionException) |
| | 244 | | { |
| 0 | 245 | | throw; |
| | 246 | | } |
| 2 | 247 | | catch (Exception e) |
| | 248 | | { |
| 2 | 249 | | if (!_cts.IsCancellationRequested) |
| | 250 | | { |
| 2 | 251 | | if (_tcpClient is null || !_tcpClient.Connected) |
| | 252 | | { |
| 2 | 253 | | throw new ConnectionException("Peer closed the connection"); |
| | 254 | | } |
| | 255 | |
|
| 0 | 256 | | throw new ConnectionException("Error reading response", e); |
| | 257 | | } |
| 0 | 258 | | } |
| | 259 | | } |
| | 260 | |
|
| 0 | 261 | | _tcs.TrySetResult(true); |
| 0 | 262 | | } |
| | 263 | |
|
| | 264 | | #region Dispose Pattern |
| | 265 | | public void Dispose() |
| | 266 | | { |
| 0 | 267 | | Dispose(true); |
| 0 | 268 | | GC.SuppressFinalize(this); |
| 0 | 269 | | } |
| | 270 | |
|
| | 271 | | private void Dispose(bool disposing) |
| | 272 | | { |
| 4 | 273 | | if (_disposed) |
| | 274 | | { |
| 0 | 275 | | return; |
| | 276 | | } |
| | 277 | |
|
| 4 | 278 | | if (disposing) |
| | 279 | | { |
| | 280 | | // Cancel and wait for an elegant shutdown |
| 0 | 281 | | _cts.Cancel(); |
| 0 | 282 | | _tcs.Task.Wait(TimeSpan.FromSeconds(5)); |
| | 283 | |
|
| 0 | 284 | | _handshakeService?.Dispose(); |
| 0 | 285 | | _transport?.Dispose(); |
| 0 | 286 | | _tcpClient.Dispose(); |
| | 287 | | } |
| | 288 | |
|
| 4 | 289 | | _disposed = true; |
| 4 | 290 | | } |
| | 291 | |
|
| | 292 | | ~TransportService() |
| | 293 | | { |
| 4 | 294 | | Dispose(false); |
| 8 | 295 | | } |
| | 296 | | #endregion |
| | 297 | | } |