| | | 1 | | using Microsoft.Extensions.DependencyInjection; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | |
| | | 4 | | namespace NLightning.Infrastructure.Node.Services; |
| | | 5 | | |
| | | 6 | | using Domain.Channels.ValueObjects; |
| | | 7 | | using Domain.Crypto.ValueObjects; |
| | | 8 | | using Domain.Exceptions; |
| | | 9 | | using Domain.Node.Interfaces; |
| | | 10 | | using Domain.Persistence.Interfaces; |
| | | 11 | | using Domain.Protocol.Constants; |
| | | 12 | | using Domain.Protocol.Interfaces; |
| | | 13 | | using Domain.Protocol.Messages; |
| | | 14 | | using Domain.Protocol.Payloads; |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Service for communication with a single peer. |
| | | 18 | | /// </summary> |
| | | 19 | | public class PeerCommunicationService : IPeerCommunicationService |
| | | 20 | | { |
| | 0 | 21 | | private readonly CancellationTokenSource _cts = new(); |
| | | 22 | | private readonly ILogger<PeerCommunicationService> _logger; |
| | | 23 | | private readonly IMessageService _messageService; |
| | | 24 | | private readonly IPingPongService _pingPongService; |
| | | 25 | | private readonly IServiceProvider _serviceProvider; |
| | | 26 | | private readonly IMessageFactory _messageFactory; |
| | 0 | 27 | | private readonly TaskCompletionSource<bool> _pingPongTcs = new(); |
| | | 28 | | |
| | | 29 | | private bool _isInitialized; |
| | | 30 | | private CancellationTokenSource? _initWaitCancellationTokenSource; |
| | | 31 | | |
| | | 32 | | /// <inheritdoc /> |
| | | 33 | | public event EventHandler<IMessage?>? MessageReceived; |
| | | 34 | | |
| | | 35 | | /// <inheritdoc /> |
| | | 36 | | public event EventHandler<Exception?>? DisconnectEvent; |
| | | 37 | | |
| | | 38 | | /// <inheritdoc /> |
| | | 39 | | public event EventHandler<Exception>? ExceptionRaised; |
| | | 40 | | |
| | | 41 | | /// <inheritdoc /> |
| | 0 | 42 | | public bool IsConnected => _messageService.IsConnected; |
| | | 43 | | |
| | | 44 | | /// <inheritdoc /> |
| | 0 | 45 | | public CompactPubKey PeerCompactPubKey { get; } |
| | | 46 | | |
| | | 47 | | /// <summary> |
| | | 48 | | /// Initializes a new instance of the <see cref="PeerCommunicationService"/> class. |
| | | 49 | | /// </summary> |
| | | 50 | | /// <param name="logger">The logger.</param> |
| | | 51 | | /// <param name="messageService">The message service.</param> |
| | | 52 | | /// <param name="messageFactory">The message factory.</param> |
| | | 53 | | /// <param name="peerCompactPubKey">The peer's public key.</param> |
| | | 54 | | /// <param name="pingPongService">The ping pong service.</param> |
| | | 55 | | /// <param name="serviceProvider">The service provider.</param> |
| | 0 | 56 | | public PeerCommunicationService(ILogger<PeerCommunicationService> logger, IMessageService messageService, |
| | 0 | 57 | | IMessageFactory messageFactory, CompactPubKey peerCompactPubKey, |
| | 0 | 58 | | IPingPongService pingPongService, IServiceProvider serviceProvider) |
| | | 59 | | { |
| | 0 | 60 | | _logger = logger; |
| | 0 | 61 | | _messageService = messageService; |
| | 0 | 62 | | _messageFactory = messageFactory; |
| | 0 | 63 | | PeerCompactPubKey = peerCompactPubKey; |
| | 0 | 64 | | _pingPongService = pingPongService; |
| | 0 | 65 | | _serviceProvider = serviceProvider; |
| | | 66 | | |
| | 0 | 67 | | _messageService.OnMessageReceived += HandleMessageReceived; |
| | 0 | 68 | | _messageService.OnExceptionRaised += HandleExceptionRaised; |
| | 0 | 69 | | _pingPongService.DisconnectEvent += HandleExceptionRaised; |
| | 0 | 70 | | } |
| | | 71 | | |
| | | 72 | | /// <inheritdoc /> |
| | | 73 | | public async Task InitializeAsync(TimeSpan networkTimeout) |
| | | 74 | | { |
| | 0 | 75 | | _logger.LogTrace("Waiting for init message from peer {peer}", PeerCompactPubKey); |
| | | 76 | | |
| | | 77 | | // Set timeout to close connection if the other peer doesn't send an init message |
| | 0 | 78 | | _initWaitCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token); |
| | 0 | 79 | | _ = Task.Delay(networkTimeout, _initWaitCancellationTokenSource.Token).ContinueWith(task => |
| | 0 | 80 | | { |
| | 0 | 81 | | if (!task.IsCanceled && !_isInitialized) |
| | 0 | 82 | | { |
| | 0 | 83 | | RaiseException( |
| | 0 | 84 | | new ConnectionException($"Peer {PeerCompactPubKey} did not send an init message before timeout")); |
| | 0 | 85 | | } |
| | 0 | 86 | | }); |
| | | 87 | | |
| | | 88 | | // Always send an init message upon connection |
| | 0 | 89 | | _logger.LogTrace("Sending init message to peer {peer}", PeerCompactPubKey); |
| | 0 | 90 | | var initMessage = _messageFactory.CreateInitMessage(); |
| | | 91 | | try |
| | | 92 | | { |
| | 0 | 93 | | await _messageService.SendMessageAsync(initMessage, true, _cts.Token); |
| | 0 | 94 | | } |
| | 0 | 95 | | catch (Exception e) |
| | | 96 | | { |
| | 0 | 97 | | _pingPongTcs.TrySetResult(true); |
| | 0 | 98 | | throw new ConnectionException($"Failed to send init message to peer {PeerCompactPubKey}", e); |
| | | 99 | | } |
| | | 100 | | |
| | | 101 | | // Set up ping service to keep connection alive |
| | 0 | 102 | | if (!_cts.IsCancellationRequested) |
| | | 103 | | { |
| | 0 | 104 | | if (!_messageService.IsConnected) |
| | 0 | 105 | | throw new ConnectionException($"Failed to connect to peer {PeerCompactPubKey}"); |
| | | 106 | | |
| | 0 | 107 | | SetupPingPongService(); |
| | | 108 | | } |
| | 0 | 109 | | } |
| | | 110 | | |
| | | 111 | | /// <inheritdoc /> |
| | | 112 | | public async Task SendMessageAsync(IMessage message, CancellationToken cancellationToken = default) |
| | | 113 | | { |
| | | 114 | | try |
| | | 115 | | { |
| | 0 | 116 | | await _messageService.SendMessageAsync(message, cancellationToken: cancellationToken); |
| | 0 | 117 | | } |
| | 0 | 118 | | catch (Exception ex) |
| | | 119 | | { |
| | 0 | 120 | | RaiseException(new ConnectionException($"Failed to send message to peer {PeerCompactPubKey}", ex)); |
| | 0 | 121 | | } |
| | 0 | 122 | | } |
| | | 123 | | |
| | | 124 | | /// <inheritdoc/> |
| | | 125 | | public async Task SendWarningAsync(WarningException we, CancellationToken cancellationToken = default) |
| | | 126 | | { |
| | | 127 | | try |
| | | 128 | | { |
| | 0 | 129 | | var message = we.Message; |
| | 0 | 130 | | ChannelId? channelId = null; |
| | 0 | 131 | | if (we is ChannelWarningException cwe) |
| | | 132 | | { |
| | 0 | 133 | | message = cwe.PeerMessage ?? we.Message; |
| | 0 | 134 | | channelId = cwe.ChannelId; |
| | | 135 | | } |
| | | 136 | | |
| | 0 | 137 | | var warningMessage = _messageFactory.CreateWarningMessage(message, channelId); |
| | 0 | 138 | | await _messageService.SendMessageAsync(warningMessage, cancellationToken: cancellationToken); |
| | 0 | 139 | | } |
| | 0 | 140 | | catch (Exception ex) |
| | | 141 | | { |
| | 0 | 142 | | RaiseException(new ConnectionException($"Failed to send message to peer {PeerCompactPubKey}", ex)); |
| | 0 | 143 | | } |
| | 0 | 144 | | } |
| | | 145 | | |
| | | 146 | | /// <inheritdoc /> |
| | | 147 | | public void Disconnect(Exception? exception = null) |
| | | 148 | | { |
| | | 149 | | try |
| | | 150 | | { |
| | 0 | 151 | | SendExceptionMessage(exception).GetAwaiter().GetResult(); |
| | | 152 | | |
| | 0 | 153 | | _ = _cts.CancelAsync(); |
| | 0 | 154 | | _logger.LogTrace("Waiting for ping service to stop for peer {peer}", PeerCompactPubKey); |
| | 0 | 155 | | _pingPongTcs.Task.Wait(TimeSpan.FromSeconds(5)); |
| | 0 | 156 | | _logger.LogTrace("Ping service stopped for peer {peer}", PeerCompactPubKey); |
| | 0 | 157 | | } |
| | | 158 | | finally |
| | | 159 | | { |
| | 0 | 160 | | DisconnectEvent?.Invoke(this, exception); |
| | 0 | 161 | | } |
| | 0 | 162 | | } |
| | | 163 | | |
| | | 164 | | private void SetupPingPongService() |
| | | 165 | | { |
| | 0 | 166 | | _pingPongService.OnPingMessageReady += HandlePingMessageReady; |
| | 0 | 167 | | _pingPongService.OnPongReceived += HandlePongReceived; |
| | | 168 | | |
| | | 169 | | // Setup Ping to keep connection alive |
| | 0 | 170 | | _ = _pingPongService.StartPingAsync(_cts.Token).ContinueWith(_ => |
| | 0 | 171 | | { |
| | 0 | 172 | | _logger.LogTrace("Ping service stopped for peer {peer}, setting result", PeerCompactPubKey); |
| | 0 | 173 | | _pingPongTcs.TrySetResult(true); |
| | 0 | 174 | | }); |
| | | 175 | | |
| | 0 | 176 | | _logger.LogInformation("Ping service started for peer {peer}", PeerCompactPubKey); |
| | 0 | 177 | | } |
| | | 178 | | |
| | | 179 | | private void HandlePongReceived(object? sender, EventArgs e) |
| | | 180 | | { |
| | 0 | 181 | | using var scope = _serviceProvider.CreateScope(); |
| | 0 | 182 | | using var uow = scope.ServiceProvider.GetRequiredService<IUnitOfWork>(); |
| | | 183 | | |
| | 0 | 184 | | uow.PeerDbRepository.UpdatePeerLastSeenAsync(PeerCompactPubKey).GetAwaiter().GetResult(); |
| | 0 | 185 | | uow.SaveChanges(); |
| | 0 | 186 | | } |
| | | 187 | | |
| | | 188 | | private void HandlePingMessageReady(object? sender, IMessage pingMessage) |
| | | 189 | | { |
| | | 190 | | // We can only send ping messages if the peer is initialized |
| | 0 | 191 | | if (!_isInitialized) |
| | 0 | 192 | | return; |
| | | 193 | | |
| | | 194 | | try |
| | | 195 | | { |
| | 0 | 196 | | _messageService.SendMessageAsync(pingMessage, cancellationToken: _cts.Token).GetAwaiter().GetResult(); |
| | 0 | 197 | | } |
| | 0 | 198 | | catch (Exception ex) |
| | | 199 | | { |
| | 0 | 200 | | RaiseException(new ConnectionException($"Failed to send ping message to peer {PeerCompactPubKey}", ex)); |
| | 0 | 201 | | } |
| | 0 | 202 | | } |
| | | 203 | | |
| | | 204 | | private void HandleMessageReceived(object? sender, IMessage? message) |
| | | 205 | | { |
| | 0 | 206 | | if (message is null) |
| | | 207 | | { |
| | 0 | 208 | | return; |
| | | 209 | | } |
| | | 210 | | |
| | 0 | 211 | | if (!_isInitialized && message.Type == MessageTypes.Init) |
| | | 212 | | { |
| | 0 | 213 | | _isInitialized = true; |
| | 0 | 214 | | _initWaitCancellationTokenSource?.Cancel(); |
| | | 215 | | } |
| | | 216 | | |
| | | 217 | | // Forward the message to subscribers |
| | 0 | 218 | | MessageReceived?.Invoke(this, message); |
| | | 219 | | |
| | | 220 | | // Handle ping messages internally |
| | 0 | 221 | | if (_isInitialized && message.Type == MessageTypes.Ping) |
| | | 222 | | { |
| | 0 | 223 | | _ = HandlePingAsync(message); |
| | | 224 | | } |
| | 0 | 225 | | else if (_isInitialized && message.Type == MessageTypes.Pong) |
| | | 226 | | { |
| | 0 | 227 | | _pingPongService.HandlePong(message); |
| | | 228 | | } |
| | 0 | 229 | | } |
| | | 230 | | |
| | | 231 | | private async Task HandlePingAsync(IMessage pingMessage) |
| | | 232 | | { |
| | 0 | 233 | | var pongMessage = _messageFactory.CreatePongMessage(pingMessage); |
| | 0 | 234 | | await _messageService.SendMessageAsync(pongMessage); |
| | 0 | 235 | | } |
| | | 236 | | |
| | | 237 | | private void HandleExceptionRaised(object? sender, Exception e) |
| | | 238 | | { |
| | 0 | 239 | | RaiseException(e); |
| | 0 | 240 | | } |
| | | 241 | | |
| | | 242 | | private Task SendExceptionMessage(Exception? exception) |
| | | 243 | | { |
| | | 244 | | switch (exception) |
| | | 245 | | { |
| | | 246 | | case ConnectionException: |
| | | 247 | | case null: |
| | 0 | 248 | | return Task.CompletedTask; |
| | | 249 | | case ErrorException errorException: |
| | | 250 | | { |
| | 0 | 251 | | ChannelId? channelId = null; |
| | 0 | 252 | | var message = errorException.Message; |
| | | 253 | | |
| | 0 | 254 | | if (errorException is ChannelErrorException channelErrorException) |
| | | 255 | | { |
| | 0 | 256 | | channelId = channelErrorException.ChannelId; |
| | 0 | 257 | | if (!string.IsNullOrWhiteSpace(channelErrorException.PeerMessage)) |
| | 0 | 258 | | message = channelErrorException.PeerMessage; |
| | | 259 | | } |
| | | 260 | | |
| | 0 | 261 | | _logger.LogTrace("Sending error message to peer {peer}. ChannelId: {channelId}, Message: {message}", |
| | 0 | 262 | | PeerCompactPubKey, channelId, message); |
| | | 263 | | |
| | 0 | 264 | | return _messageService.SendMessageAsync( |
| | 0 | 265 | | new ErrorMessage(new ErrorPayload(channelId, message))); |
| | | 266 | | } |
| | | 267 | | case WarningException warningException: |
| | | 268 | | { |
| | 0 | 269 | | ChannelId? channelId = null; |
| | 0 | 270 | | var message = warningException.Message; |
| | | 271 | | |
| | 0 | 272 | | if (warningException is ChannelWarningException channelWarningException) |
| | | 273 | | { |
| | 0 | 274 | | channelId = channelWarningException.ChannelId; |
| | 0 | 275 | | if (!string.IsNullOrWhiteSpace(channelWarningException.PeerMessage)) |
| | 0 | 276 | | message = channelWarningException.PeerMessage; |
| | | 277 | | } |
| | | 278 | | |
| | 0 | 279 | | _logger.LogTrace("Sending warning message to peer {peer}. ChannelId: {channelId}, Message: {message} |
| | 0 | 280 | | PeerCompactPubKey, channelId, message); |
| | | 281 | | |
| | 0 | 282 | | return _messageService.SendMessageAsync( |
| | 0 | 283 | | new WarningMessage(new ErrorPayload(channelId, message))); |
| | | 284 | | } |
| | | 285 | | default: |
| | 0 | 286 | | return Task.CompletedTask; |
| | | 287 | | } |
| | | 288 | | } |
| | | 289 | | |
| | | 290 | | private void RaiseException(Exception exception) |
| | | 291 | | { |
| | 0 | 292 | | var mustDisconnect = false; |
| | 0 | 293 | | if (exception is ErrorException) |
| | 0 | 294 | | mustDisconnect = true; |
| | | 295 | | |
| | 0 | 296 | | _ = Task.Run(() => SendExceptionMessage(exception)); |
| | | 297 | | |
| | | 298 | | // Forward the exception to subscribers |
| | 0 | 299 | | ExceptionRaised?.Invoke(this, exception); |
| | | 300 | | |
| | | 301 | | // Disconnect if not already disconnecting |
| | 0 | 302 | | if (mustDisconnect && !_cts.IsCancellationRequested) |
| | | 303 | | { |
| | 0 | 304 | | _logger.LogWarning(exception, "We're disconnecting peer {peer} because of an exception", |
| | 0 | 305 | | PeerCompactPubKey); |
| | 0 | 306 | | Disconnect(); |
| | | 307 | | } |
| | 0 | 308 | | } |
| | | 309 | | |
| | | 310 | | public void Dispose() |
| | | 311 | | { |
| | | 312 | | // Unsubscribe from events |
| | 0 | 313 | | _messageService.OnMessageReceived -= HandleMessageReceived; |
| | 0 | 314 | | _messageService.OnExceptionRaised -= HandleExceptionRaised; |
| | 0 | 315 | | _pingPongService.DisconnectEvent -= HandleExceptionRaised; |
| | | 316 | | |
| | 0 | 317 | | _cts.Dispose(); |
| | 0 | 318 | | _messageService.Dispose(); |
| | 0 | 319 | | _initWaitCancellationTokenSource?.Dispose(); |
| | 0 | 320 | | } |
| | | 321 | | } |