| | | 1 | | using System.Net; |
| | | 2 | | using System.Text.Unicode; |
| | | 3 | | using Microsoft.Extensions.Logging; |
| | | 4 | | |
| | | 5 | | namespace NLightning.Infrastructure.Node.Services; |
| | | 6 | | |
| | | 7 | | using Domain.Channels.ValueObjects; |
| | | 8 | | using Domain.Crypto.ValueObjects; |
| | | 9 | | using Domain.Exceptions; |
| | | 10 | | using Domain.Node.Events; |
| | | 11 | | using Domain.Node.Interfaces; |
| | | 12 | | using Domain.Node.Options; |
| | | 13 | | using Domain.Protocol.Constants; |
| | | 14 | | using Domain.Protocol.Interfaces; |
| | | 15 | | using Domain.Protocol.Messages; |
| | | 16 | | |
| | | 17 | | // TODO: Eventually move this to the Application layer |
| | | 18 | | /// <summary> |
| | | 19 | | /// Service for peer communication |
| | | 20 | | /// </summary> |
| | | 21 | | public sealed class PeerService : IPeerService |
| | | 22 | | { |
| | | 23 | | private readonly IPeerCommunicationService _peerCommunicationService; |
| | | 24 | | private readonly ILogger<PeerService> _logger; |
| | | 25 | | |
| | | 26 | | private bool _isInitialized; |
| | | 27 | | |
| | | 28 | | /// <inheritdoc/> |
| | | 29 | | public event EventHandler<PeerDisconnectedEventArgs>? OnDisconnect; |
| | | 30 | | |
| | | 31 | | /// <inheritdoc/> |
| | | 32 | | public event EventHandler<ChannelMessageEventArgs>? OnChannelMessageReceived; |
| | | 33 | | |
| | | 34 | | /// <inheritdoc/> |
| | | 35 | | public event EventHandler<AttentionMessageEventArgs>? OnAttentionMessageReceived; |
| | | 36 | | |
| | | 37 | | /// <inheritdoc/> |
| | | 38 | | public event EventHandler<Exception>? OnExceptionRaised; |
| | | 39 | | |
| | | 40 | | /// <inheritdoc/> |
| | 0 | 41 | | public CompactPubKey PeerPubKey => _peerCommunicationService.PeerCompactPubKey; |
| | | 42 | | |
| | 0 | 43 | | public string? PreferredHost { get; private set; } |
| | 0 | 44 | | public ushort? PreferredPort { get; private set; } |
| | | 45 | | |
| | 0 | 46 | | public FeatureOptions Features { get; private set; } |
| | | 47 | | |
| | | 48 | | /// <summary> |
| | | 49 | | /// Initializes a new instance of the <see cref="PeerService"/> class. |
| | | 50 | | /// </summary> |
| | | 51 | | /// <param name="peerCommunicationService">The peer communication service</param> |
| | | 52 | | /// <param name="features">The feature options</param> |
| | | 53 | | /// <param name="logger">A logger</param> |
| | | 54 | | /// <param name="networkTimeout">Network timeout</param> |
| | 0 | 55 | | public PeerService(IPeerCommunicationService peerCommunicationService, FeatureOptions features, |
| | 0 | 56 | | ILogger<PeerService> logger, TimeSpan networkTimeout) |
| | | 57 | | { |
| | 0 | 58 | | _peerCommunicationService = peerCommunicationService; |
| | 0 | 59 | | Features = features; |
| | 0 | 60 | | _logger = logger; |
| | | 61 | | |
| | | 62 | | // Set up event handlers |
| | 0 | 63 | | _peerCommunicationService.MessageReceived += HandleMessage; |
| | 0 | 64 | | _peerCommunicationService.ExceptionRaised += HandleException; |
| | 0 | 65 | | _peerCommunicationService.DisconnectEvent += HandleDisconnection; |
| | | 66 | | |
| | | 67 | | // Initialize communication |
| | | 68 | | try |
| | | 69 | | { |
| | 0 | 70 | | _peerCommunicationService.InitializeAsync(networkTimeout).GetAwaiter().GetResult(); |
| | 0 | 71 | | } |
| | 0 | 72 | | catch (Exception e) |
| | | 73 | | { |
| | 0 | 74 | | throw new ErrorException("Error initializing peer communication", e); |
| | | 75 | | } |
| | 0 | 76 | | } |
| | | 77 | | |
| | | 78 | | /// <summary> |
| | | 79 | | /// Disconnects from the peer. |
| | | 80 | | /// </summary> |
| | | 81 | | public void Disconnect(Exception? exception = null) |
| | | 82 | | { |
| | 0 | 83 | | _logger.LogInformation("Disconnecting peer {peer}", PeerPubKey); |
| | 0 | 84 | | _peerCommunicationService.Disconnect(exception); |
| | 0 | 85 | | } |
| | | 86 | | |
| | | 87 | | public Task SendMessageAsync(IChannelMessage replyMessage) |
| | | 88 | | { |
| | 0 | 89 | | return _peerCommunicationService.SendMessageAsync(replyMessage); |
| | | 90 | | } |
| | | 91 | | |
| | | 92 | | public Task SendWarningAsync(WarningException we) |
| | | 93 | | { |
| | 0 | 94 | | return _peerCommunicationService.SendWarningAsync(we); |
| | | 95 | | } |
| | | 96 | | |
| | | 97 | | /// <summary> |
| | | 98 | | /// Handles messages received from the peer. |
| | | 99 | | /// </summary> |
| | | 100 | | private void HandleMessage(object? sender, IMessage? message) |
| | | 101 | | { |
| | 0 | 102 | | if (message is null) |
| | 0 | 103 | | return; |
| | | 104 | | |
| | 0 | 105 | | if (!_isInitialized) |
| | | 106 | | { |
| | 0 | 107 | | HandleInitialization(message); |
| | | 108 | | } |
| | 0 | 109 | | else if (message is IChannelMessage channelMessage) |
| | | 110 | | { |
| | 0 | 111 | | _logger.LogTrace("Received channel message ({messageType}) from peer {peer}", |
| | 0 | 112 | | Enum.GetName(message.Type), PeerPubKey); |
| | | 113 | | |
| | 0 | 114 | | OnChannelMessageReceived?.Invoke(this, new ChannelMessageEventArgs(channelMessage, PeerPubKey)); |
| | | 115 | | } |
| | 0 | 116 | | else if (message is ErrorMessage errorMessage) |
| | | 117 | | { |
| | 0 | 118 | | var errorMessageString = string.Empty; |
| | 0 | 119 | | ChannelId? channelId = null; |
| | 0 | 120 | | if (errorMessage.Payload.ChannelId != ChannelId.Zero) |
| | 0 | 121 | | channelId = errorMessage.Payload.ChannelId; |
| | | 122 | | |
| | 0 | 123 | | if (errorMessage.Payload.Data is not null) |
| | | 124 | | { |
| | | 125 | | // Try to get utf8 string from error data |
| | 0 | 126 | | errorMessageString = Utf8.IsValid(errorMessage.Payload.Data) |
| | 0 | 127 | | ? System.Text.Encoding.UTF8.GetString(errorMessage.Payload.Data) |
| | 0 | 128 | | #if NET9_0_OR_GREATER |
| | 0 | 129 | | : Convert.ToHexStringLower(errorMessage.Payload.Data); |
| | | 130 | | #else |
| | | 131 | | : Convert.ToHexString(errorMessage.Payload.Data).ToLowerInvariant(); |
| | | 132 | | #endif |
| | | 133 | | |
| | 0 | 134 | | _logger.LogError( |
| | 0 | 135 | | "Received error message from peer {peer} for channel {channelId}: {errorMessage}", |
| | 0 | 136 | | PeerPubKey, channelId is null ? "" : channelId.ToString(), errorMessageString); |
| | | 137 | | } |
| | | 138 | | |
| | 0 | 139 | | OnAttentionMessageReceived?.Invoke( |
| | 0 | 140 | | this, new AttentionMessageEventArgs(errorMessageString, PeerPubKey, channelId)); |
| | | 141 | | } |
| | 0 | 142 | | else if (message is WarningMessage warningMessage) |
| | | 143 | | { |
| | 0 | 144 | | var warningMessageString = string.Empty; |
| | 0 | 145 | | ChannelId? channelId = null; |
| | 0 | 146 | | if (warningMessage.Payload.ChannelId != ChannelId.Zero) |
| | 0 | 147 | | channelId = warningMessage.Payload.ChannelId; |
| | | 148 | | |
| | 0 | 149 | | if (warningMessage.Payload.Data is not null) |
| | | 150 | | { |
| | | 151 | | // Try to get utf8 string from error data |
| | 0 | 152 | | warningMessageString = Utf8.IsValid(warningMessage.Payload.Data) |
| | 0 | 153 | | ? System.Text.Encoding.UTF8.GetString(warningMessage.Payload.Data) |
| | 0 | 154 | | #if NET9_0_OR_GREATER |
| | 0 | 155 | | : Convert.ToHexStringLower(warningMessage.Payload.Data); |
| | | 156 | | #else |
| | | 157 | | : Convert.ToHexString(warningMessage.Payload.Data).ToLowerInvariant(); |
| | | 158 | | #endif |
| | | 159 | | |
| | 0 | 160 | | _logger.LogError( |
| | 0 | 161 | | "Received error message from peer {peer} for channel {channelId}: {errorMessage}", |
| | 0 | 162 | | PeerPubKey, channelId is null ? "" : channelId.ToString(), warningMessageString); |
| | | 163 | | } |
| | | 164 | | |
| | 0 | 165 | | OnAttentionMessageReceived?.Invoke( |
| | 0 | 166 | | this, new AttentionMessageEventArgs(warningMessageString, PeerPubKey, channelId)); |
| | | 167 | | } |
| | 0 | 168 | | } |
| | | 169 | | |
| | | 170 | | /// <summary> |
| | | 171 | | /// Handles exceptions raised by the communication service. |
| | | 172 | | /// </summary> |
| | | 173 | | private void HandleException(object? sender, Exception e) |
| | | 174 | | { |
| | 0 | 175 | | _logger.LogError(e, "Exception occurred with peer {peer}", PeerPubKey); |
| | 0 | 176 | | OnExceptionRaised?.Invoke(this, e); |
| | 0 | 177 | | } |
| | | 178 | | |
| | | 179 | | private void HandleDisconnection(object? sender, Exception e) |
| | | 180 | | { |
| | 0 | 181 | | _logger.LogTrace(e, "Handling disconnection for peer {Peer}", PeerPubKey); |
| | 0 | 182 | | OnDisconnect?.Invoke(this, new PeerDisconnectedEventArgs(PeerPubKey, e)); |
| | 0 | 183 | | } |
| | | 184 | | |
| | | 185 | | /// <summary> |
| | | 186 | | /// Handles the initialization process when receiving the first message. |
| | | 187 | | /// </summary> |
| | | 188 | | private void HandleInitialization(IMessage message) |
| | | 189 | | { |
| | | 190 | | // Check if the first message is an init message |
| | 0 | 191 | | if (message.Type != MessageTypes.Init || message is not InitMessage initMessage) |
| | | 192 | | { |
| | 0 | 193 | | _logger.LogError("Failed to receive init message from peer {peer}", PeerPubKey); |
| | 0 | 194 | | Disconnect(); |
| | 0 | 195 | | return; |
| | | 196 | | } |
| | | 197 | | |
| | | 198 | | // Check if Features are compatible |
| | 0 | 199 | | if (!Features.GetNodeFeatures().IsCompatible(initMessage.Payload.FeatureSet, out var negotiatedFeatures) |
| | 0 | 200 | | || negotiatedFeatures is null) |
| | | 201 | | { |
| | 0 | 202 | | _logger.LogError("Peer {peer} is not compatible", PeerPubKey); |
| | 0 | 203 | | Disconnect(); |
| | 0 | 204 | | return; |
| | | 205 | | } |
| | | 206 | | |
| | | 207 | | // Check if ChainHash contained in networksTlv.ChainHashes exists in our ChainHashes |
| | 0 | 208 | | var networkChainHashes = initMessage.NetworksTlv?.ChainHashes; |
| | 0 | 209 | | if (networkChainHashes != null |
| | 0 | 210 | | && networkChainHashes.Any(chainHash => !Features.ChainHashes.Contains(chainHash))) |
| | | 211 | | { |
| | 0 | 212 | | _logger.LogError("Peer {peer} chain is not compatible", PeerPubKey); |
| | 0 | 213 | | Disconnect(); |
| | 0 | 214 | | return; |
| | | 215 | | } |
| | | 216 | | |
| | 0 | 217 | | if (initMessage.RemoteAddressTlv is not null) |
| | | 218 | | { |
| | 0 | 219 | | switch (initMessage.RemoteAddressTlv.AddressType) |
| | | 220 | | { |
| | | 221 | | case 1 or 2: |
| | | 222 | | { |
| | 0 | 223 | | if (!IPAddress.TryParse(initMessage.RemoteAddressTlv.Address, out var ipAddress)) |
| | | 224 | | { |
| | 0 | 225 | | _logger.LogWarning("Peer {peer} has an invalid remote address: {address}", |
| | 0 | 226 | | PeerPubKey, initMessage.RemoteAddressTlv.Address); |
| | | 227 | | } |
| | | 228 | | else |
| | | 229 | | { |
| | 0 | 230 | | PreferredHost = ipAddress.ToString(); |
| | 0 | 231 | | PreferredPort = initMessage.RemoteAddressTlv.Port; |
| | | 232 | | } |
| | | 233 | | |
| | 0 | 234 | | break; |
| | | 235 | | } |
| | | 236 | | case 5: |
| | 0 | 237 | | PreferredHost = initMessage.RemoteAddressTlv.Address; |
| | 0 | 238 | | PreferredPort = initMessage.RemoteAddressTlv.Port; |
| | 0 | 239 | | break; |
| | | 240 | | default: |
| | 0 | 241 | | _logger.LogWarning("Peer {peer} has an unsupported remote address type: {addressType}", |
| | 0 | 242 | | PeerPubKey, initMessage.RemoteAddressTlv.AddressType); |
| | | 243 | | break; |
| | | 244 | | } |
| | | 245 | | } |
| | | 246 | | |
| | 0 | 247 | | Features = FeatureOptions.GetNodeOptions(negotiatedFeatures, initMessage.Extension); |
| | 0 | 248 | | _logger.LogTrace("Initialization from peer {peer} completed successfully", PeerPubKey); |
| | 0 | 249 | | _isInitialized = true; |
| | 0 | 250 | | } |
| | | 251 | | |
| | | 252 | | public void Dispose() |
| | | 253 | | { |
| | 0 | 254 | | _peerCommunicationService.MessageReceived -= HandleMessage; |
| | 0 | 255 | | _peerCommunicationService.ExceptionRaised -= HandleException; |
| | 0 | 256 | | _peerCommunicationService.DisconnectEvent -= HandleDisconnection; |
| | 0 | 257 | | _peerCommunicationService.Dispose(); |
| | 0 | 258 | | } |
| | | 259 | | } |