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