| | 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 _cancellationTokenSource = 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; |
| | 27 | | private bool _isInitialized; |
| | 28 | |
|
| | 29 | | /// <inheritdoc /> |
| | 30 | | public event EventHandler<IMessage?>? MessageReceived; |
| | 31 | |
|
| | 32 | | /// <inheritdoc /> |
| | 33 | | public event EventHandler? DisconnectEvent; |
| | 34 | |
|
| | 35 | | /// <inheritdoc /> |
| | 36 | | public event EventHandler<Exception>? ExceptionRaised; |
| | 37 | |
|
| | 38 | | /// <inheritdoc /> |
| 0 | 39 | | public bool IsConnected => _messageService.IsConnected; |
| | 40 | |
|
| | 41 | | /// <inheritdoc /> |
| 0 | 42 | | public CompactPubKey PeerCompactPubKey { get; } |
| | 43 | |
|
| | 44 | | /// <summary> |
| | 45 | | /// Initializes a new instance of the <see cref="PeerCommunicationService"/> class. |
| | 46 | | /// </summary> |
| | 47 | | /// <param name="logger">The logger.</param> |
| | 48 | | /// <param name="messageService">The message service.</param> |
| | 49 | | /// <param name="messageFactory">The message factory.</param> |
| | 50 | | /// <param name="peerCompactPubKey">The peer's public key.</param> |
| | 51 | | /// <param name="pingPongService">The ping pong service.</param> |
| | 52 | | /// <param name="serviceProvider">The service provider.</param> |
| 0 | 53 | | public PeerCommunicationService(ILogger<PeerCommunicationService> logger, IMessageService messageService, |
| 0 | 54 | | IMessageFactory messageFactory, CompactPubKey peerCompactPubKey, |
| 0 | 55 | | IPingPongService pingPongService, IServiceProvider serviceProvider) |
| | 56 | | { |
| 0 | 57 | | _logger = logger; |
| 0 | 58 | | _messageService = messageService; |
| 0 | 59 | | _messageFactory = messageFactory; |
| 0 | 60 | | PeerCompactPubKey = peerCompactPubKey; |
| 0 | 61 | | _pingPongService = pingPongService; |
| 0 | 62 | | _serviceProvider = serviceProvider; |
| | 63 | |
|
| 0 | 64 | | _messageService.OnMessageReceived += HandleMessageReceived; |
| 0 | 65 | | _messageService.OnExceptionRaised += HandleExceptionRaised; |
| 0 | 66 | | _pingPongService.DisconnectEvent += HandleExceptionRaised; |
| 0 | 67 | | } |
| | 68 | |
|
| | 69 | | /// <inheritdoc /> |
| | 70 | | public async Task InitializeAsync(TimeSpan networkTimeout) |
| | 71 | | { |
| | 72 | | // Always send an init message upon connection |
| 0 | 73 | | _logger.LogTrace("Sending init message to peer {peer}", PeerCompactPubKey); |
| 0 | 74 | | var initMessage = _messageFactory.CreateInitMessage(); |
| 0 | 75 | | await _messageService.SendMessageAsync(initMessage, _cancellationTokenSource.Token); |
| | 76 | |
|
| | 77 | | // Wait for an init message |
| 0 | 78 | | _logger.LogTrace("Waiting for init message from peer {peer}", PeerCompactPubKey); |
| | 79 | |
|
| | 80 | | // Set timeout to close connection if the other peer doesn't send an init message |
| 0 | 81 | | _ = Task.Delay(networkTimeout, _cancellationTokenSource.Token).ContinueWith(task => |
| 0 | 82 | | { |
| 0 | 83 | | if (!task.IsCanceled && !_isInitialized) |
| 0 | 84 | | { |
| 0 | 85 | | RaiseException( |
| 0 | 86 | | new ConnectionException($"Peer {PeerCompactPubKey} did not send init message after timeout")); |
| 0 | 87 | | } |
| 0 | 88 | | }); |
| | 89 | |
|
| 0 | 90 | | if (!_messageService.IsConnected) |
| | 91 | | { |
| 0 | 92 | | throw new ConnectionException($"Failed to connect to peer {PeerCompactPubKey}"); |
| | 93 | | } |
| | 94 | |
|
| | 95 | | // Set up ping service to keep connection alive |
| 0 | 96 | | SetupPingPongService(); |
| 0 | 97 | | } |
| | 98 | |
|
| | 99 | | /// <inheritdoc /> |
| | 100 | | public async Task SendMessageAsync(IMessage message, CancellationToken cancellationToken = default) |
| | 101 | | { |
| | 102 | | try |
| | 103 | | { |
| 0 | 104 | | await _messageService.SendMessageAsync(message, cancellationToken); |
| 0 | 105 | | } |
| 0 | 106 | | catch (Exception ex) |
| | 107 | | { |
| 0 | 108 | | RaiseException(new ConnectionException($"Failed to send message to peer {PeerCompactPubKey}", ex)); |
| 0 | 109 | | } |
| 0 | 110 | | } |
| | 111 | |
|
| | 112 | | /// <inheritdoc /> |
| | 113 | | public void Disconnect() |
| | 114 | | { |
| 0 | 115 | | _logger.LogInformation("Disconnecting peer {peer}", PeerCompactPubKey); |
| 0 | 116 | | _cancellationTokenSource.Cancel(); |
| 0 | 117 | | _messageService.Dispose(); |
| | 118 | |
|
| 0 | 119 | | DisconnectEvent?.Invoke(this, EventArgs.Empty); |
| 0 | 120 | | } |
| | 121 | |
|
| | 122 | | private void SetupPingPongService() |
| | 123 | | { |
| 0 | 124 | | _pingPongService.OnPingMessageReady += HandlePingMessageReady; |
| 0 | 125 | | _pingPongService.OnPongReceived += HandlePongReceived; |
| | 126 | |
|
| | 127 | | // Setup Ping to keep connection alive |
| 0 | 128 | | _ = _pingPongService.StartPingAsync(_cancellationTokenSource.Token).ContinueWith(task => |
| 0 | 129 | | { |
| 0 | 130 | | if (task.IsFaulted) |
| 0 | 131 | | { |
| 0 | 132 | | RaiseException(new ConnectionException($"Failed to start ping service for peer {PeerCompactPubKey}", |
| 0 | 133 | | task.Exception)); |
| 0 | 134 | | } |
| 0 | 135 | | }); |
| | 136 | |
|
| 0 | 137 | | _logger.LogInformation("Ping service started for peer {peer}", PeerCompactPubKey); |
| 0 | 138 | | } |
| | 139 | |
|
| | 140 | | private void HandlePongReceived(object? sender, EventArgs e) |
| | 141 | | { |
| 0 | 142 | | using var scope = _serviceProvider.CreateScope(); |
| 0 | 143 | | using var uow = scope.ServiceProvider.GetRequiredService<IUnitOfWork>(); |
| | 144 | |
|
| 0 | 145 | | uow.PeerDbRepository.UpdatePeerLastSeenAsync(PeerCompactPubKey).GetAwaiter().GetResult(); |
| 0 | 146 | | uow.SaveChanges(); |
| 0 | 147 | | } |
| | 148 | |
|
| | 149 | | private void HandlePingMessageReady(object? sender, IMessage pingMessage) |
| | 150 | | { |
| | 151 | | // We can only send ping messages if the peer is initialized |
| 0 | 152 | | if (!_isInitialized) |
| 0 | 153 | | return; |
| | 154 | |
|
| | 155 | | try |
| | 156 | | { |
| 0 | 157 | | _messageService.SendMessageAsync(pingMessage, _cancellationTokenSource.Token).GetAwaiter().GetResult(); |
| 0 | 158 | | } |
| 0 | 159 | | catch (Exception ex) |
| | 160 | | { |
| 0 | 161 | | RaiseException(new ConnectionException($"Failed to send ping message to peer {PeerCompactPubKey}", ex)); |
| 0 | 162 | | } |
| 0 | 163 | | } |
| | 164 | |
|
| | 165 | | private void HandleMessageReceived(object? sender, IMessage? message) |
| | 166 | | { |
| 0 | 167 | | if (message is null) |
| | 168 | | { |
| 0 | 169 | | return; |
| | 170 | | } |
| | 171 | |
|
| 0 | 172 | | if (!_isInitialized && message.Type == MessageTypes.Init) |
| | 173 | | { |
| 0 | 174 | | _isInitialized = true; |
| | 175 | | } |
| | 176 | |
|
| | 177 | | // Forward the message to subscribers |
| 0 | 178 | | MessageReceived?.Invoke(this, message); |
| | 179 | |
|
| | 180 | | // Handle ping messages internally |
| 0 | 181 | | if (_isInitialized && message.Type == MessageTypes.Ping) |
| | 182 | | { |
| 0 | 183 | | _ = HandlePingAsync(message); |
| | 184 | | } |
| 0 | 185 | | else if (_isInitialized && message.Type == MessageTypes.Pong) |
| | 186 | | { |
| 0 | 187 | | _pingPongService.HandlePong(message); |
| | 188 | | } |
| 0 | 189 | | } |
| | 190 | |
|
| | 191 | | private async Task HandlePingAsync(IMessage pingMessage) |
| | 192 | | { |
| 0 | 193 | | var pongMessage = _messageFactory.CreatePongMessage(pingMessage); |
| 0 | 194 | | await _messageService.SendMessageAsync(pongMessage); |
| 0 | 195 | | } |
| | 196 | |
|
| | 197 | | private void HandleExceptionRaised(object? sender, Exception e) |
| | 198 | | { |
| 0 | 199 | | RaiseException(e); |
| 0 | 200 | | } |
| | 201 | |
|
| | 202 | | private void RaiseException(Exception exception) |
| | 203 | | { |
| 0 | 204 | | var mustDisconnect = false; |
| 0 | 205 | | if (exception is ErrorException errorException) |
| | 206 | | { |
| 0 | 207 | | ChannelId? channelId = null; |
| 0 | 208 | | var message = errorException.Message; |
| | 209 | |
|
| 0 | 210 | | if (errorException is ChannelErrorException channelErrorException) |
| | 211 | | { |
| 0 | 212 | | channelId = channelErrorException.ChannelId; |
| 0 | 213 | | if (!string.IsNullOrWhiteSpace(channelErrorException.PeerMessage)) |
| 0 | 214 | | message = channelErrorException.PeerMessage; |
| | 215 | | } |
| | 216 | |
|
| 0 | 217 | | _messageService.SendMessageAsync(new ErrorMessage(new ErrorPayload(channelId, message))); |
| 0 | 218 | | mustDisconnect = true; |
| | 219 | | } |
| 0 | 220 | | else if (exception is WarningException warningException) |
| | 221 | | { |
| 0 | 222 | | ChannelId? channelId = null; |
| 0 | 223 | | var message = warningException.Message; |
| | 224 | |
|
| 0 | 225 | | if (warningException is ChannelWarningException channelWarningException) |
| | 226 | | { |
| 0 | 227 | | channelId = channelWarningException.ChannelId; |
| 0 | 228 | | if (!string.IsNullOrWhiteSpace(channelWarningException.PeerMessage)) |
| 0 | 229 | | message = channelWarningException.PeerMessage; |
| | 230 | | } |
| | 231 | |
|
| 0 | 232 | | _messageService.SendMessageAsync(new WarningMessage(new ErrorPayload(channelId, message))); |
| | 233 | | } |
| | 234 | |
|
| 0 | 235 | | _logger.LogError(exception, "Exception occurred with peer {peer}. {exceptionMessage}", PeerCompactPubKey, |
| 0 | 236 | | exception.Message); |
| | 237 | |
|
| | 238 | | // Forward the exception to subscribers |
| 0 | 239 | | ExceptionRaised?.Invoke(this, exception); |
| | 240 | |
|
| | 241 | | // Disconnect if not already disconnecting |
| 0 | 242 | | if (mustDisconnect && !_cancellationTokenSource.IsCancellationRequested) |
| 0 | 243 | | Disconnect(); |
| 0 | 244 | | } |
| | 245 | | } |