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