| | 1 | | using Microsoft.Extensions.Logging; |
| | 2 | |
|
| | 3 | | namespace NLightning.Infrastructure.Node.Models; |
| | 4 | |
|
| | 5 | | using Domain.Exceptions; |
| | 6 | | using Domain.Factories; |
| | 7 | | using Domain.Node.Options; |
| | 8 | | using Domain.Protocol.Constants; |
| | 9 | | using Domain.Protocol.Messages; |
| | 10 | | using Domain.Protocol.Messages.Interfaces; |
| | 11 | | using Domain.Protocol.Services; |
| | 12 | | using Domain.Protocol.Tlv; |
| | 13 | | using Interfaces; |
| | 14 | |
|
| | 15 | | /// <summary> |
| | 16 | | /// Represents a peer in the network. |
| | 17 | | /// </summary> |
| | 18 | | /// <remarks> |
| | 19 | | /// This class is used to communicate with a peer in the network. |
| | 20 | | /// </remarks> |
| | 21 | | public sealed class Peer : IPeer |
| | 22 | | { |
| 44 | 23 | | private readonly CancellationTokenSource _cancellationTokenSource = new(); |
| | 24 | | private readonly FeatureOptions _features; |
| | 25 | | private readonly ILogger<Peer> _logger; |
| | 26 | | private readonly IMessageFactory _messageFactory; |
| | 27 | | private readonly IMessageService _messageService; |
| | 28 | | private readonly IPingPongService _pingPongService; |
| | 29 | |
|
| | 30 | | private bool _isInitialized; |
| | 31 | |
|
| | 32 | | /// <summary> |
| | 33 | | /// Event raised when the peer is disconnected. |
| | 34 | | /// </summary> |
| | 35 | | public event EventHandler? DisconnectEvent; |
| | 36 | |
|
| 140 | 37 | | public Protocol.Models.PeerAddress PeerAddress { get; } |
| | 38 | |
|
| | 39 | | /// <summary> |
| | 40 | | /// Initializes a new instance of the <see cref="Peer"/> class. |
| | 41 | | /// </summary> |
| | 42 | | /// <param name="features">The feature options</param> |
| | 43 | | /// <param name="logger">A logger</param> |
| | 44 | | /// <param name="messageFactory">The message factory</param> |
| | 45 | | /// <param name="messageService">The message service.</param> |
| | 46 | | /// <param name="networkTimeout">Network timeout</param> |
| | 47 | | /// <param name="peerAddress">Peer address</param> |
| | 48 | | /// <param name="pingPongService">The ping pong service.</param> |
| | 49 | | /// <exception cref="ConnectionException">Thrown when the connection to the peer fails.</exception> |
| 44 | 50 | | internal Peer(FeatureOptions features, ILogger<Peer> logger, IMessageFactory messageFactory, |
| 44 | 51 | | IMessageService messageService, TimeSpan networkTimeout, Protocol.Models.PeerAddress peerAddress, |
| 44 | 52 | | IPingPongService pingPongService) |
| | 53 | | { |
| 44 | 54 | | _features = features; |
| 44 | 55 | | _logger = logger; |
| 44 | 56 | | _messageFactory = messageFactory; |
| 44 | 57 | | _messageService = messageService; |
| 44 | 58 | | _pingPongService = pingPongService; |
| | 59 | |
|
| 44 | 60 | | PeerAddress = peerAddress; |
| | 61 | |
|
| 44 | 62 | | _messageService.MessageReceived += HandleMessage; |
| 44 | 63 | | _messageService.ExceptionRaised += HandleException; |
| 44 | 64 | | _pingPongService.DisconnectEvent += HandleException; |
| | 65 | |
|
| | 66 | | // Always send an init message upon connection |
| 44 | 67 | | logger.LogTrace("[Peer] Sending init message to peer {peer}", PeerAddress.PubKey); |
| 44 | 68 | | var initMessage = _messageFactory.CreateInitMessage(); |
| 44 | 69 | | _messageService.SendMessageAsync(initMessage, _cancellationTokenSource.Token).Wait(); |
| | 70 | |
|
| | 71 | | // Wait for an init message |
| 44 | 72 | | logger.LogTrace("[Peer] Waiting for init message from peer {peer}", PeerAddress.PubKey); |
| | 73 | | // Set timeout to close connection if the other peer doesn't send an init message |
| 44 | 74 | | Task.Delay(networkTimeout, _cancellationTokenSource.Token).ContinueWith(task => |
| 44 | 75 | | { |
| 16 | 76 | | if (!task.IsCanceled && !_isInitialized) |
| 44 | 77 | | { |
| 4 | 78 | | DisconnectWithException(new ConnectionException("Peer did not send init message after timeout")); |
| 44 | 79 | | } |
| 60 | 80 | | }); |
| | 81 | |
|
| 44 | 82 | | if (!_messageService.IsConnected) |
| | 83 | | { |
| 4 | 84 | | throw new ConnectionException("Failed to connect to peer"); |
| | 85 | | } |
| 40 | 86 | | } |
| | 87 | |
|
| | 88 | | private void DisconnectWithException(Exception e) |
| | 89 | | { |
| 16 | 90 | | DisconnectWithException(this, e); |
| 16 | 91 | | } |
| | 92 | | private void DisconnectWithException(object? sender, Exception? e) |
| | 93 | | { |
| 16 | 94 | | _logger.LogError(e, "Disconnecting peer {peer}", PeerAddress.PubKey); |
| 16 | 95 | | _cancellationTokenSource.Cancel(); |
| 16 | 96 | | _messageService.Dispose(); |
| | 97 | |
|
| 16 | 98 | | DisconnectEvent?.Invoke(sender, EventArgs.Empty); |
| 16 | 99 | | } |
| | 100 | |
|
| | 101 | | private void HandleMessage(object? sender, IMessage? message) |
| | 102 | | { |
| 24 | 103 | | if (message is null) |
| | 104 | | { |
| 0 | 105 | | return; |
| | 106 | | } |
| | 107 | |
|
| 24 | 108 | | if (!_isInitialized) |
| | 109 | | { |
| 16 | 110 | | _logger.LogTrace("[Peer] Received message from peer {peer} but was not initialized", PeerAddress.PubKey); |
| 16 | 111 | | HandleInitialization(message); |
| | 112 | | } |
| | 113 | | else |
| | 114 | | { |
| 8 | 115 | | switch (message.Type) |
| | 116 | | { |
| | 117 | | case MessageTypes.PING: |
| 4 | 118 | | _logger.LogTrace("[Peer] Received ping message from peer {peer}", PeerAddress.PubKey); |
| 4 | 119 | | _ = HandlePingAsync(message); |
| 4 | 120 | | break; |
| | 121 | | case MessageTypes.PONG: |
| 4 | 122 | | _logger.LogTrace("[Peer] Received pong message from peer {peer}", PeerAddress.PubKey); |
| 4 | 123 | | _pingPongService.HandlePong(message); |
| | 124 | | break; |
| | 125 | | } |
| | 126 | | } |
| 4 | 127 | | } |
| | 128 | |
|
| | 129 | | private void HandleException(object? sender, Exception e) |
| | 130 | | { |
| 0 | 131 | | DisconnectWithException(sender, e); |
| 0 | 132 | | } |
| | 133 | |
|
| | 134 | | private void HandleInitialization(IMessage message) |
| | 135 | | { |
| | 136 | | // Check if first message is an init message |
| 16 | 137 | | if (message.Type != MessageTypes.INIT || message is not InitMessage initMessage) |
| | 138 | | { |
| 4 | 139 | | DisconnectWithException(new ConnectionException("Failed to receive init message")); |
| 4 | 140 | | return; |
| | 141 | | } |
| | 142 | |
|
| | 143 | | // Check if Features are compatible |
| 12 | 144 | | if (!_features.GetNodeFeatures().IsCompatible(initMessage.Payload.FeatureSet)) |
| | 145 | | { |
| 4 | 146 | | DisconnectWithException(new ConnectionException("Peer is not compatible")); |
| 4 | 147 | | return; |
| | 148 | | } |
| | 149 | |
|
| | 150 | | // Check if Chains are compatible |
| 8 | 151 | | if (initMessage.Extension != null |
| 8 | 152 | | && initMessage.Extension.TryGetTlv(TlvConstants.NETWORKS, out var networksTlv)) |
| | 153 | | { |
| | 154 | | // Check if ChainHash contained in networksTlv.ChainHashes exists in our ChainHashes |
| 8 | 155 | | var networkChainHashes = ((NetworksTlv)networksTlv!).ChainHashes; |
| 8 | 156 | | if (networkChainHashes != null) |
| | 157 | | { |
| 16 | 158 | | if (networkChainHashes.Any(chainHash => !_features.ChainHashes.Contains(chainHash))) |
| | 159 | | { |
| 4 | 160 | | DisconnectWithException(new ConnectionException("Peer chain is not compatible")); |
| 4 | 161 | | return; |
| | 162 | | } |
| | 163 | | } |
| | 164 | | } |
| | 165 | |
|
| 4 | 166 | | FeatureOptions.GetNodeOptions(initMessage.Payload.FeatureSet, initMessage.Extension); |
| | 167 | |
|
| 4 | 168 | | _logger.LogTrace("[Peer] Message from peer {peer} is correct (init)", PeerAddress.PubKey); |
| | 169 | |
|
| 4 | 170 | | StartPingPongService(); |
| | 171 | |
|
| 4 | 172 | | _isInitialized = true; |
| 4 | 173 | | } |
| | 174 | |
|
| | 175 | | private void StartPingPongService() |
| | 176 | | { |
| 4 | 177 | | _pingPongService.PingMessageReadyEvent += (sender, pingMessage) => |
| 4 | 178 | | { |
| 4 | 179 | | // We can only send ping messages if the peer is initialized |
| 0 | 180 | | if (!_isInitialized) |
| 4 | 181 | | { |
| 0 | 182 | | return; |
| 4 | 183 | | } |
| 4 | 184 | |
|
| 0 | 185 | | _ = _messageService.SendMessageAsync(pingMessage, _cancellationTokenSource.Token).ContinueWith(task => |
| 0 | 186 | | { |
| 0 | 187 | | if (task.IsFaulted) |
| 0 | 188 | | { |
| 0 | 189 | | DisconnectWithException(new ConnectionException("Failed to send ping message", task.Exception)); |
| 0 | 190 | | } |
| 0 | 191 | | }); |
| 4 | 192 | | }; |
| | 193 | |
|
| | 194 | | // Setup Ping to keep connection alive |
| 4 | 195 | | _ = _pingPongService.StartPingAsync(_cancellationTokenSource.Token).ContinueWith(task => |
| 4 | 196 | | { |
| 4 | 197 | | if (task.IsFaulted) |
| 4 | 198 | | { |
| 0 | 199 | | DisconnectWithException(new ConnectionException("Failed to start ping service", task.Exception)); |
| 4 | 200 | | } |
| 8 | 201 | | }); |
| | 202 | |
|
| 4 | 203 | | _logger.LogInformation("[Peer] Ping service started for peer {peer}", PeerAddress.PubKey); |
| 4 | 204 | | } |
| | 205 | |
|
| | 206 | | private async Task HandlePingAsync(IMessage pingMessage) |
| | 207 | | { |
| 4 | 208 | | var pongMessage = _messageFactory.CreatePongMessage(pingMessage); |
| 4 | 209 | | await _messageService.SendMessageAsync(pongMessage); |
| 4 | 210 | | } |
| | 211 | |
|
| | 212 | | public void Disconnect() |
| | 213 | | { |
| 0 | 214 | | _logger.LogInformation("Disconnecting peer {peer}", PeerAddress.PubKey); |
| 0 | 215 | | _cancellationTokenSource.Cancel(); |
| 0 | 216 | | _messageService.Dispose(); |
| | 217 | |
|
| 0 | 218 | | DisconnectEvent?.Invoke(this, EventArgs.Empty); |
| 0 | 219 | | } |
| | 220 | | } |